{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# default_exp sumstat"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "# Sumstat module\n",
    "\n",
    "> read and extract Sumstat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "#hide\n",
    "from nbdev.showdoc import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "#export\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from scipy.stats import norm\n",
    "from LDtools.utils import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "#export\n",
    "def p2z(pval,beta,twoside=True):\n",
    "    if twoside:\n",
    "        pval = pval/2\n",
    "    z=np.abs(norm.ppf(pval))\n",
    "    ind=beta<0\n",
    "    z[ind]=-z[ind]\n",
    "    return z\n",
    "    \n",
    "class Sumstat:\n",
    "    def __init__(self,sumstat_path,config_file=None):\n",
    "        self.ss = self.read_sumstat(sumstat_path,config_file)\n",
    "        \n",
    "    def __repr__(self): \n",
    "        return \"sumstat:% s\" % (self.ss)\n",
    "        \n",
    "        #functions to read sumstats\n",
    "    def read_sumstat(self,file, config_file):\n",
    "        try:\n",
    "            sumstats = pd.read_csv(file, compression='gzip', header=0, sep='\\t', quotechar='\"')\n",
    "        except:\n",
    "            sumstats = pd.read_csv(file, header=0, sep='\\t', quotechar='\"')\n",
    "        if config_file is not None:\n",
    "            import yaml\n",
    "            config = yaml.safe_load(open(config_file, 'r'))\n",
    "            try:\n",
    "                sumstats = sumstats.loc[:,list(config.values())]\n",
    "            except:\n",
    "                raise ValueError(f'According to config_file, input summary statistics should have the following columns: %s' % list(config.values()))\n",
    "            sumstats.columns = list(config.keys())\n",
    "        sumstats.SNP = 'chr'+sumstats.CHR.astype(str) + ':' + sumstats.POS.astype(str) + ':' + sumstats.REF.astype(str) + ':' + sumstats.ALT.astype(str)\n",
    "        sumstats.CHR = sumstats.CHR.astype(int)\n",
    "        sumstats.POS = sumstats.POS.astype(int)\n",
    "        return sumstats\n",
    "    \n",
    "    def extractbyregion(self,region):\n",
    "        sumstats = self.ss\n",
    "        idx = (sumstats.CHR == region[0]) & (sumstats.POS >= region[1]) & (sumstats.POS <= region[2])\n",
    "        print('this region',region,'has',sum(idx),'SNPs in Sumstat')\n",
    "        self.ss = sumstats[idx]\n",
    "        \n",
    "    def extractbyvariants(self,variants,notin=False):\n",
    "        idx = self.ss.SNP.isin(variants)\n",
    "        if notin:\n",
    "            idx = idx == False\n",
    "        #update sumstats\n",
    "        self.ss = self.ss[idx]\n",
    "        \n",
    "    def calculateZ(self):\n",
    "        self.ss['Z'] = list(p2z(self.ss.P,self.ss.BETA))\n",
    "        \n",
    "    def match_ss(self,bim):\n",
    "        self.ss = check_ss1(self.ss,bim)\n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "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.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
