{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "91667632",
   "metadata": {},
   "source": [
    "# Using `AdherR` through `rpy2` from a `Python3` Jupyter Notebook\n",
    "\n",
    "We use here `rpy2` to compute and plot CMA7 from a `Python3` `Jupyter Notebook`..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "72457996",
   "metadata": {},
   "outputs": [],
   "source": [
    "# import ryp2 (please note that you might need to install it as per https://rpy2.github.io/doc.html)\n",
    "import rpy2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "9cd68c44",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['/Users/ddediu/Library/Python/3.10/lib/python/site-packages/rpy2']"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# check that all is ok\n",
    "rpy2.__path__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "cc2971d2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# import R's \"AdhereR\" package\n",
    "from rpy2.robjects.packages import importr\n",
    "adherer = importr('AdhereR')\n",
    "\n",
    "# access the internal R session\n",
    "import rpy2.robjects as robjects"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "af747077",
   "metadata": {},
   "outputs": [],
   "source": [
    "# access the med.events dataset\n",
    "med_events = robjects.r['med.events']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "fe2226d1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "rpy2.robjects.vectors.DataFrame"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# check its type\n",
    "type(med_events)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "e9ddbc24",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<emph>DataFrame</emph> with 1080 rows and\n",
       "  5 columns:\n",
       "<table class=\"rpy2_table\">\n",
       "  <thead>\n",
       "    <tr class=\"rpy2_names\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>PATIENT_ID</th>\n",
       "      <th>DATE</th>\n",
       "      <th>PERDAY</th>\n",
       "      <th>CATEGORY</th>\n",
       "      <th>DURATION</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td class=\"rpy2_rowname\">0</td>\n",
       "        <td class=\"rpy2_names\">286</td>\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",
       "      <td class=\"rpy2_rowname\">1</td>\n",
       "        <td class=\"rpy2_names\">287</td>\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",
       "      <td class=\"rpy2_rowname\">2</td>\n",
       "        <td class=\"rpy2_names\">288</td>\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",
       "      <td class=\"rpy2_rowname\">3</td>\n",
       "        <td class=\"rpy2_names\">289</td>\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",
       "      <td class=\"rpy2_rowname\">4</td>\n",
       "        <td class=\"rpy2_names\">291</td>\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",
       "      <td class=\"rpy2_rowname\">5</td>\n",
       "        <td class=\"rpy2_names\">290</td>\n",
       "      <td>1</td>\n",
       "      <td>10/16/2033</td>\n",
       "      <td>4</td>\n",
       "      <td>medB</td>\n",
       "      <td>30</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td class=\"rpy2_rowname\">6</td>\n",
       "        <td class=\"rpy2_names\">292</td>\n",
       "      <td>1</td>\n",
       "      <td>11/23/2033</td>\n",
       "      <td>4</td>\n",
       "      <td>medB</td>\n",
       "      <td>30</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td class=\"rpy2_rowname\">7</td>\n",
       "        <td class=\"rpy2_names\">293</td>\n",
       "      <td>1</td>\n",
       "      <td>01/19/2034</td>\n",
       "      <td>4</td>\n",
       "      <td>medB</td>\n",
       "      <td>30</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td class=\"rpy2_rowname\">...</td>\n",
       "        <td class=\"rpy2_names\">...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td class=\"rpy2_rowname\">1078</td>\n",
       "        <td class=\"rpy2_names\">949</td>\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",
       "      <td class=\"rpy2_rowname\">1079</td>\n",
       "        <td class=\"rpy2_names\">950</td>\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>"
      ],
      "text/plain": [
       "<rpy2.robjects.vectors.DataFrame object at 0x106317600> [RTYPES.VECSXP]\n",
       "R classes: ('data.frame',)\n",
       "[IntSexp..., StrSexp..., IntSexp..., StrSexp..., IntSexp...]\n",
       "  PATIENT_ID: <class 'rpy2.rinterface.IntSexpVector'>\n",
       "  <rpy2.rinterface.IntSexpVector object at 0x1474bb300> [RTYPES.INTSXP]\n",
       "  DATE: <class 'rpy2.rinterface_lib.sexp.StrSexpVector'>\n",
       "  <rpy2.rinterface_lib.sexp.StrSexpVector object at 0x122e11600> [RTYPES.STRSXP]\n",
       "  PERDAY: <class 'rpy2.rinterface.IntSexpVector'>\n",
       "  <rpy2.rinterface.IntSexpVector object at 0x1251817c0> [RTYPES.INTSXP]\n",
       "  CATEGORY: <class 'rpy2.rinterface_lib.sexp.StrSexpVector'>\n",
       "  <rpy2.rinterface_lib.sexp.StrSexpVector object at 0x1474d1040> [RTYPES.STRSXP]\n",
       "  DURATION: <class 'rpy2.rinterface.IntSexpVector'>\n",
       "  <rpy2.rinterface.IntSexpVector object at 0x1474d14c0> [RTYPES.INTSXP]"
      ]
     },
     "execution_count": 6,
     "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",
    "med_events"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f4e3b4c2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# make some AdhereR functions available to Python\n",
    "CMA7 = robjects.r['CMA7']\n",
    "getCMA = robjects.r['getCMA']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "635b8f44",
   "metadata": {},
   "outputs": [],
   "source": [
    "# create a CMA7 object\n",
    "cma7 = CMA7(med_events,\n",
    "            ID_colname=\"PATIENT_ID\",\n",
    "            event_date_colname=\"DATE\",\n",
    "            event_duration_colname=\"DURATION\",\n",
    "            event_daily_dose_colname=\"PERDAY\",\n",
    "            medication_class_colname=\"CATEGORY\",\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\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "f518c839",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<emph>ListVector</emph> with 26 elements:\n",
       "<table class=\"rpy2_table\">\n",
       "<thead>\n",
       "</thead>\n",
       "<tbody>\n",
       "  <tr>\n",
       "    <td class=\"rpy2_rowname\">0</td>\n",
       "    <td class=\"rpy2_names\">data</td>\n",
       "    <td>    ...</td>\n",
       "  </tr>\n",
       "  <tr>\n",
       "    <td class=\"rpy2_rowname\">1</td>\n",
       "    <td class=\"rpy2_names\">ID.colname</td>\n",
       "    <td>[1] \"PATIENT_ID\"\n",
       "</td>\n",
       "  </tr>\n",
       "  <tr>\n",
       "    <td class=\"rpy2_rowname\">2</td>\n",
       "    <td class=\"rpy2_names\">event.date.colname</td>\n",
       "    <td>[1] \"DATE\"\n",
       "</td>\n",
       "  </tr>\n",
       "  <tr>\n",
       "    <td class=\"rpy2_rowname\">3</td>\n",
       "    <td class=\"rpy2_names\">event.duration.colname</td>\n",
       "    <td>[1] \"DURATION\"\n",
       "</td>\n",
       "  </tr>\n",
       "  <tr>\n",
       "    <td class=\"rpy2_rowname\">4</td>\n",
       "    <td class=\"rpy2_names\">event.daily.dose.colname</td>\n",
       "    <td>[1] \"PERDAY\"\n",
       "</td>\n",
       "  </tr>\n",
       "  <tr>\n",
       "    <td class=\"rpy2_rowname\">5</td>\n",
       "    <td class=\"rpy2_names\">medication.class.colname</td>\n",
       "    <td>[1] \"CATEGORY\"\n",
       "</td>\n",
       "  </tr>\n",
       "  <tr>\n",
       "    <td class=\"rpy2_rowname\">6</td>\n",
       "    <td class=\"rpy2_names\">medication.groups</td>\n",
       "    <td><rpy2.rin...</td>\n",
       "  </tr>\n",
       "  <tr>\n",
       "    <td class=\"rpy2_rowname\">7</td>\n",
       "    <td class=\"rpy2_names\">flatten.medication.groups</td>\n",
       "    <td>[1] FALSE\n",
       "</td>\n",
       "  </tr>\n",
       "  <tr>\n",
       "    <td class=\"rpy2_rowname\">...</td>\n",
       "    <td class=\"rpy2_names\">...</td>\n",
       "    <td>...</td>\n",
       "  </tr>\n",
       "  <tr>\n",
       "    <td class=\"rpy2_rowname\">24</td>\n",
       "    <td class=\"rpy2_names\">CMA</td>\n",
       "    <td>   ...</td>\n",
       "  </tr>\n",
       "  <tr>\n",
       "    <td class=\"rpy2_rowname\">25</td>\n",
       "    <td class=\"rpy2_names\">event.info</td>\n",
       "    <td>   ...</td>\n",
       "  </tr>\n",
       "</tr>\n",
       "</tbody>\n",
       "</table>"
      ],
      "text/plain": [
       "<rpy2.robjects.vectors.ListVector object at 0x1470f4d80> [RTYPES.VECSXP]\n",
       "R classes: ('CMA7', 'CMA1', 'CMA0')\n",
       "[ListSexpV..., StrSexpVe..., StrSexpVe..., StrSexpVe..., ..., StrSexpVe..., StrSexpVe..., ListSexpV..., ListSexpV...]\n",
       "<rpy2.robjects.vectors.ListVector object at 0x1470f4d80> [RTYPES.VECSXP]\n",
       "R classes: ('CMA7', 'CMA1', 'CMA0')\n",
       "[ListSexpV..., StrSexpVe..., StrSexpVe..., StrSexpVe..., ..., StrSexpVe..., StrSexpVe..., ListSexpV..., ListSexpV...]\n",
       "  ID.colname: <class 'rpy2.robjects.vectors.StrVector'>\n",
       "  <rpy2.robjects.vectors.StrVector object at 0x1068b9d00> [RTYPES.STRSXP]\n",
       "R classes: ('character',)\n",
       "['PATIENT_ID']\n",
       "  event.date.colname: <class 'rpy2.robjects.vectors.StrVector'>\n",
       "  <rpy2.robjects.vectors.StrVector object at 0x1077bb7c0> [RTYPES.STRSXP]\n",
       "R classes: ('character',)\n",
       "['DATE']\n",
       "  event.duration.colname: <class 'rpy2.robjects.vectors.StrVector'>\n",
       "  <rpy2.robjects.vectors.StrVector object at 0x1474b8380> [RTYPES.STRSXP]\n",
       "R classes: ('character',)\n",
       "['DURATION']\n",
       "...\n",
       "  medication.class.colname: <class 'rpy2.robjects.vectors.StrVector'>\n",
       "  <rpy2.robjects.vectors.StrVector object at 0x1077ced80> [RTYPES.STRSXP]\n",
       "R classes: ('character',)\n",
       "['%m/%d/%Y']\n",
       "  medication.groups: <class 'rpy2.robjects.vectors.StrVector'>\n",
       "  <rpy2.robjects.vectors.StrVector object at 0x1474d4800> [RTYPES.STRSXP]\n",
       "R classes: ('character',)\n",
       "['The ratio of days with medication available in t...]\n",
       "<rpy2.robjects.vectors.ListVector object at 0x1470f4d80> [RTYPES.VECSXP]\n",
       "R classes: ('CMA7', 'CMA1', 'CMA0')\n",
       "[ListSexpV..., StrSexpVe..., StrSexpVe..., StrSexpVe..., ..., StrSexpVe..., StrSexpVe..., ListSexpV..., ListSexpV...]\n",
       "<rpy2.robjects.vectors.ListVector object at 0x1470f4d80> [RTYPES.VECSXP]\n",
       "R classes: ('CMA7', 'CMA1', 'CMA0')\n",
       "[ListSexpV..., StrSexpVe..., StrSexpVe..., StrSexpVe..., ..., StrSexpVe..., StrSexpVe..., ListSexpV..., ListSexpV...]"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# print it for checking\n",
    "cma7"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "1e9e623b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<emph>DataFrame</emph> with 100 rows and\n",
       "  2 columns:\n",
       "<table class=\"rpy2_table\">\n",
       "  <thead>\n",
       "    <tr class=\"rpy2_names\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>PATIENT_ID</th>\n",
       "      <th>CMA</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td class=\"rpy2_rowname\">0</td>\n",
       "        <td class=\"rpy2_names\">1</td>\n",
       "      <td>1</td>\n",
       "      <td>1.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td class=\"rpy2_rowname\">1</td>\n",
       "        <td class=\"rpy2_names\">2</td>\n",
       "      <td>2</td>\n",
       "      <td>0.35</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td class=\"rpy2_rowname\">2</td>\n",
       "        <td class=\"rpy2_names\">3</td>\n",
       "      <td>3</td>\n",
       "      <td>0.9299999999999999</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td class=\"rpy2_rowname\">3</td>\n",
       "        <td class=\"rpy2_names\">4</td>\n",
       "      <td>4</td>\n",
       "      <td>nan</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td class=\"rpy2_rowname\">4</td>\n",
       "        <td class=\"rpy2_names\">5</td>\n",
       "      <td>5</td>\n",
       "      <td>0.30000000000000004</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td class=\"rpy2_rowname\">5</td>\n",
       "        <td class=\"rpy2_names\">6</td>\n",
       "      <td>6</td>\n",
       "      <td>0.06000000000000005</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td class=\"rpy2_rowname\">6</td>\n",
       "        <td class=\"rpy2_names\">7</td>\n",
       "      <td>7</td>\n",
       "      <td>0.24</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td class=\"rpy2_rowname\">7</td>\n",
       "        <td class=\"rpy2_names\">8</td>\n",
       "      <td>8</td>\n",
       "      <td>0.39</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td class=\"rpy2_rowname\">...</td>\n",
       "        <td class=\"rpy2_names\">...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td class=\"rpy2_rowname\">98</td>\n",
       "        <td class=\"rpy2_names\">99</td>\n",
       "      <td>99</td>\n",
       "      <td>0.7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td class=\"rpy2_rowname\">99</td>\n",
       "        <td class=\"rpy2_names\">100</td>\n",
       "      <td>100</td>\n",
       "      <td>0.89</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>"
      ],
      "text/plain": [
       "<rpy2.robjects.vectors.DataFrame object at 0x10678dc80> [RTYPES.VECSXP]\n",
       "R classes: ('data.frame',)\n",
       "[IntSexpVector, FloatSexpVector]\n",
       "  PATIENT_ID: <class 'rpy2.rinterface.IntSexpVector'>\n",
       "  <rpy2.rinterface.IntSexpVector object at 0x1474e2c00> [RTYPES.INTSXP]\n",
       "  CMA: <class 'rpy2.rinterface.FloatSexpVector'>\n",
       "  <rpy2.rinterface.FloatSexpVector object at 0x1474e15c0> [RTYPES.REALSXP]"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# print the estimated CMAs\n",
    "getCMA(cma7)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "0c9802d8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<emph>IntVector</emph> with 1 elements:\n",
       "<table class=\"rpy2_table\">\n",
       "<thead>\n",
       "</thead>\n",
       "<tbody>\n",
       "<tr>\n",
       "      <td>1</td>\n",
       "</tr>\n",
       "</tbody>\n",
       "</table>"
      ],
      "text/plain": [
       "<rpy2.robjects.vectors.IntVector object at 0x168f47680> [RTYPES.INTSXP]\n",
       "R classes: ('integer',)\n",
       "[1]"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# plot it\n",
    "# this is some clunky code involving do.call and named lists because\n",
    "# plot has lots of arguments with . that cannot be autmatically handeled by rpy2\n",
    "# the idea is to use a TaggedList that associated values and argument names\n",
    "\n",
    "import rpy2.rlike.container as rlc # for TaggedList\n",
    "rcall = robjects.r['do.call'] # do.call()\n",
    "grdevices = importr('grDevices') # R graphics device\n",
    "\n",
    "# the actual plotting\n",
    "grdevices.jpeg(file=\"./cma7plot.jpg\", width=512, height=512)\n",
    "rcall(\"plot\",\n",
    "      rlc.TaggedList([cma7,\n",
    "                      robjects.IntVector([1,2,3]), \n",
    "                      False,\n",
    "                      True], \n",
    "                     tags=('cma', \n",
    "                           'patients.to.plot', \n",
    "                           'show.legend',\n",
    "                           'align.all.patients')))\n",
    "grdevices.dev_off()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c5853cff",
   "metadata": {},
   "source": [
    "Include the CMA7 plot using the Markdown syntax (there are several alternatives: https://stackoverflow.com/questions/32370281/how-to-embed-image-or-picture-in-jupyter-notebook-either-from-a-local-machine-o): \n",
    "\n",
    "![The plot](./cma7plot.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d480258",
   "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
}
