{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a8460249",
   "metadata": {},
   "source": [
    "# Using `AdherR` from a `Python3` Jupyter Notebook using the custom wrapper\n",
    "\n",
    "We use here the `Python3` wrapper included with the `AdhereR` package to compute and plot CMA7 from a `Python3` `Jupyter Notebook`...\n",
    "Please make sure that you have the R AdhereR package properly installed and that Python can find the adherer module. This can be done in various ways.\n",
    "\n",
    "The wrapper is contained in single file (`adherer.py`) included with the `R` `AdhereR` package and whose location can be obtained using the function `getCallerWrapperLocation(full.path=TRUE)` from `AdhereR` (*N.B.* it is located in the directory where the `AdhereR` package is installed on the system, subdirectory `wrappers/python3/adherer.py`; for example, on the example `macos` machine this is `/Library/Frameworks/R.framework/Versions/3.4/Resources/library/AdhereR/wrappers/python3/adherer.py`).\n",
    "In the future, as more wrappers are added, the argument `callig.platform` will allow the selection of the desired wrapper (now it is implicitely set to `python3`).\n",
    "\n",
    "This file can be either:\n",
    "\n",
    "  - *copied and placed* in `Python`'s \"module search paths\" (a list of directories comprising, in order, the directory contining the input script, the environment variable `PYTHONPATH`, and a default location; see [here](https://docs.python.org/3/tutorial/modules.html#the-module-search-path) for details), in which cae it can be simply imported using the standard `Python` syntax (e.g. `import adherer` or `import adherer as ad`), or\n",
    "  - *imported from its location* by either:\n",
    "    - adding its directory to the `PYTHONPATH` environment variable [the recommended solution], or\n",
    "    - using various tricks described, for example, [here](https://stackoverflow.com/a/67692).\n",
    "\n",
    "On the example `macos` machine, this can be achieved by adding:\n",
    "``` bash\n",
    "# Add AdhereR to PYTHONPATH\n",
    "export PYTHONPATH=$PYTHONPATH:/Library/Frameworks/[...]/AdhereR/wrappers/python3\n",
    "```\n",
    "to the `.bash_profile` file in the user's home folder (if this file does not exist, then it can be created using a text editor such as `nano`; please note that the `[...]` are for shortening the path and should be replaced by the actual path given in full above).\n",
    "The process should be very similar on `Linux`, while on `MS Windows` one should use the system's \"Environment Variables\" settings (for example, see [here](https://stackoverflow.com/a/4855685) for details).\n",
    "\n",
    "Please note that `adherer` needs `pandas` and `PIL`, which can be installed, for example, using:\n",
    "``` bash\n",
    "pip3 install pandas\n",
    "pip3 install Pillow\n",
    "```\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "217c8f13",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Le chargement a nécessité le package : AdhereR\n"
     ]
    }
   ],
   "source": [
    "# import the adherer python module (see above about how to make it findable)\n",
    "import adherer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "1bfc59f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the test dataset:\n",
    "import pandas\n",
    "df = pandas.read_csv('./test-dataset.csv', sep='\\t', header=0)\n",
    "\n",
    "# Change the column names:\n",
    "df.rename(columns={'ID': 'patientID',\n",
    "                   'DATE': 'prescriptionDate',\n",
    "                   'PERDAY': 'quantityPerDay',\n",
    "                   'CLASS': 'medicationType',\n",
    "                   'DURATION': 'prescriptionDuration'},\n",
    "          inplace=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ef88b3b4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "pandas.core.frame.DataFrame"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# check the file was read correctly\n",
    "type(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "bdd02cb9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>patientID</th>\n",
       "      <th>prescriptionDate</th>\n",
       "      <th>quantityPerDay</th>\n",
       "      <th>medicationType</th>\n",
       "      <th>prescriptionDuration</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>04/26/2033</td>\n",
       "      <td>4</td>\n",
       "      <td>medA</td>\n",
       "      <td>50</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1</td>\n",
       "      <td>07/04/2033</td>\n",
       "      <td>4</td>\n",
       "      <td>medB</td>\n",
       "      <td>30</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1</td>\n",
       "      <td>08/03/2033</td>\n",
       "      <td>4</td>\n",
       "      <td>medB</td>\n",
       "      <td>30</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>1</td>\n",
       "      <td>08/17/2033</td>\n",
       "      <td>4</td>\n",
       "      <td>medB</td>\n",
       "      <td>30</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>1</td>\n",
       "      <td>10/13/2033</td>\n",
       "      <td>4</td>\n",
       "      <td>medB</td>\n",
       "      <td>30</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>1075</th>\n",
       "      <td>100</td>\n",
       "      <td>03/05/2034</td>\n",
       "      <td>6</td>\n",
       "      <td>medB</td>\n",
       "      <td>30</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1076</th>\n",
       "      <td>100</td>\n",
       "      <td>04/07/2034</td>\n",
       "      <td>6</td>\n",
       "      <td>medB</td>\n",
       "      <td>30</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1077</th>\n",
       "      <td>100</td>\n",
       "      <td>04/26/2034</td>\n",
       "      <td>6</td>\n",
       "      <td>medB</td>\n",
       "      <td>30</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1078</th>\n",
       "      <td>100</td>\n",
       "      <td>05/26/2034</td>\n",
       "      <td>6</td>\n",
       "      <td>medB</td>\n",
       "      <td>30</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1079</th>\n",
       "      <td>100</td>\n",
       "      <td>07/09/2034</td>\n",
       "      <td>4</td>\n",
       "      <td>medB</td>\n",
       "      <td>30</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>1080 rows × 5 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "      patientID prescriptionDate  quantityPerDay medicationType  \\\n",
       "0             1       04/26/2033               4           medA   \n",
       "1             1       07/04/2033               4           medB   \n",
       "2             1       08/03/2033               4           medB   \n",
       "3             1       08/17/2033               4           medB   \n",
       "4             1       10/13/2033               4           medB   \n",
       "...         ...              ...             ...            ...   \n",
       "1075        100       03/05/2034               6           medB   \n",
       "1076        100       04/07/2034               6           medB   \n",
       "1077        100       04/26/2034               6           medB   \n",
       "1078        100       05/26/2034               6           medB   \n",
       "1079        100       07/09/2034               4           medB   \n",
       "\n",
       "      prescriptionDuration  \n",
       "0                       50  \n",
       "1                       30  \n",
       "2                       30  \n",
       "3                       30  \n",
       "4                       30  \n",
       "...                    ...  \n",
       "1075                    30  \n",
       "1076                    30  \n",
       "1077                    30  \n",
       "1078                    30  \n",
       "1079                    30  \n",
       "\n",
       "[1080 rows x 5 columns]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# HTML printing of data frames\n",
    "import rpy2.ipython.html\n",
    "rpy2.ipython.html.init_printing()\n",
    "\n",
    "# print it\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "ac4a809b",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Le chargement a nécessité le package : AdhereR\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)!\n",
      "Adherer returned code 0 and said:\n",
      "AdhereR 0.7.1 on R 4.1.3 started at 2022-05-31 17:26:00:\n",
      "OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)!\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# create a CMA7 object\n",
    "cma7 = adherer.CMA7(df,\n",
    "                    id_colname='patientID',\n",
    "                    event_date_colname='prescriptionDate',\n",
    "                    event_duration_colname='prescriptionDuration',\n",
    "                    event_daily_dose_colname='quantityPerDay',\n",
    "                    medication_class_colname='medicationType',\n",
    "                    followup_window_start=230,\n",
    "                    followup_window_duration=705,\n",
    "                    observation_window_start=41,\n",
    "                    observation_window_duration=100,\n",
    "                    date_format=\"%m/%d/%Y\",\n",
    "                    suppress_warnings=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "7443b0c2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "CMA object of type CMA7 (on 1080 rows)."
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# print it for checking\n",
    "cma7"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "5d3904c6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>patientID</th>\n",
       "      <th>CMA</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>1.00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>0.35</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>0.93</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>5</td>\n",
       "      <td>0.30</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>95</th>\n",
       "      <td>96</td>\n",
       "      <td>1.00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>96</th>\n",
       "      <td>97</td>\n",
       "      <td>0.36</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>97</th>\n",
       "      <td>98</td>\n",
       "      <td>0.33</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>98</th>\n",
       "      <td>99</td>\n",
       "      <td>0.70</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>99</th>\n",
       "      <td>100</td>\n",
       "      <td>0.89</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>100 rows × 2 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "    patientID   CMA\n",
       "0           1  1.00\n",
       "1           2  0.35\n",
       "2           3  0.93\n",
       "3           4   NaN\n",
       "4           5  0.30\n",
       "..        ...   ...\n",
       "95         96  1.00\n",
       "96         97  0.36\n",
       "97         98  0.33\n",
       "98         99  0.70\n",
       "99        100  0.89\n",
       "\n",
       "[100 rows x 2 columns]"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# print the estimated CMAs\n",
    "cma7.get_cma()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "b538aaeb",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Le chargement a nécessité le package : AdhereR\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)!\n",
      "Adherer returned code 0 and said:\n",
      "AdhereR 0.7.1 on R 4.1.3 started at 2022-05-31 17:28:38:\n",
      "OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)!\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# do the plotting (and store the result for showing it later)\n",
    "x = cma7.plot(patients_to_plot=['1', '2', '3'],\n",
    "              save_as=\"jpg\",\n",
    "              width=7, height=7,\n",
    "              quality=90, dpi=92, \n",
    "              align_all_patients=True,\n",
    "              show_legend=True,\n",
    "              suppress_warnings=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "86f0818c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 326044 characters]\n",
      "text/plain": [
       "<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=644x644>"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# show the plot directly in the notebook\n",
    "x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0e027ece",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
