<commit_before><commit_msg>propensity score matching by Hien<commit_after>{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Test of propensity score matching"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "### Code to perform Optimal full matching by Mahalanobis\n",
    "### distance on numerical variables and propensity score\n",
    "### clamping on numeric and categorical variables.\n",
    "\n",
    "### REQUIREMENTS:\n",
    "# R installation\n",
    "# optmatch package in R\n",
    "# ** install in R using install.packages('optmatch')\n",
    "# rpy2\n",
    "# ** installation instructions from https://pypi.python.org/pypi/rpy2\n",
    "\n",
    "### Load python libraries\n",
    "import rpy2.robjects as robjects"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "### Variables to be parsed to R\n",
    "# Working directory\n",
    "work_dir = \"/data1/subtypes/test/\"\n",
    "# CSV file name\n",
    "CSV_file =  \"schizo_matching_60vols_20151111.csv\"\n",
    "# Declare a list of variables that need to be categorical (using the names from CSV; assuming NOSPACE)\n",
    "categories = robjects.StrVector(['study', 'sex','sz'])\n",
    "# Declare Formula for Mahalanobis distance matching (using the names from CSV)\n",
    "## Format: Disease variable ~  What to Match by 1 + What to Match by 2 + ...\n",
    "## All variables matched by must be NUMERIC\n",
    "Mah_formula = 'sz ~ age + FD' \n",
    "# Declare Caliper Width (as a fraction of the SD of the Propensity Scores)\n",
    "cal_width = 0.5\n",
    "# Declare Formula for PSM distance matching (using the names from CSV)\n",
    "## Format: Disease variable ~  What to Match by 1 + What to Match by 2 + ...\n",
    "PSM_formula = 'sz ~ age + FD + study + sex'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "### Parsing Stuff\n",
    "robjects.globalenv[\"work_dir\"] = work_dir\n",
    "robjects.globalenv[\"CSV_file\"] = CSV_file\n",
    "robjects.globalenv[\"categories\"] = categories\n",
    "robjects.globalenv[\"Mah_formula\"] = Mah_formula\n",
    "robjects.globalenv[\"cal_width\"] = cal_width\n",
    "robjects.globalenv[\"PSM_formula\"] = PSM_formula"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/surchs/Venv/serv2/lib/python2.7/site-packages/rpy2/robjects/functions.py:106: UserWarning: Loading required package: survival\n",
      "\n",
      "  res = super(Function, self).__call__(*new_args, **new_kwargs)\n",
      "/home/surchs/Venv/serv2/lib/python2.7/site-packages/rpy2/robjects/functions.py:106: UserWarning: The optmatch package has an academic license. Enter relaxinfo() for more information.\n",
      "\n",
      "  res = super(Function, self).__call__(*new_args, **new_kwargs)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "rpy2.rinterface.NULL"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Run R script\n",
    "## R scripts write a CSV file of the form\n",
    "## matching_*CSV_file*\n",
    "## containing two extra columns;\n",
    "## keep column is 1 to keep and 0 to leave out.\n",
    "robjects.r('''\n",
    "  # Load R Librarires\n",
    "  library(optmatch)\n",
    "  \n",
    "  # Set Working directory\n",
    "  setwd(work_dir)\n",
    "  \n",
    "  # Read CSV\n",
    "  data <- read.csv(CSV_file)\n",
    "  \n",
    "  # Make all categories factors\n",
    "  for (ff in 1:length(categories)) {\n",
    "    data[[categories[ff]]] <- as.factor(data[[categories[ff]]])\n",
    "  }\n",
    "  \n",
    "  # Performs Matching\n",
    "  Matching <- fullmatch(\n",
    "  match_on( as.formula(Mah_formula),\n",
    "           data = data ) + \n",
    "    caliper( match_on( as.formula(PSM_formula), \n",
    "                     data = data ),\n",
    "            width = cal_width ),\n",
    "  data = data )\n",
    "  \n",
    "  # Make a data frame with a column with 1 to keep an observation and 0 to leave out\n",
    "  save_data <- cbind(data,match=Matching)\n",
    "  save_data$keep <- as.numeric(!is.na(save_data$match))\n",
    "  write.csv(save_data,file=paste('matched_',CSV_file,sep=''))\n",
    "''')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.11+"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
{'fraction_non_alphanumeric': 0.18968481375358165, 'fraction_numerical': 0.010506208213944603, 'mean_word_length': 2.6411682892906816, 'pattern_counts': {'":': 59, '<': 8, '<?xml version=': 0, '>': 3, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4430743', 'n_tokens_mistral': 1986, 'n_tokens_neox': 1903, 'n_words': 416}