{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# differential gene expression in Rstudio on data we will use for Chipseq."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# a different dataset was used for Chipseq because sra files weren't avaiable for the data we initially intened to use for micro-array analysis!\n",
    "# source of the data: http://bioconductor.org/packages/release/data/experiment/html/airway.html\n",
    "# GEO entry GSE52778, PubMed entry 24926665\n",
    "# workdirectory: /home/luna.kuleuven.be/r0378624/data/work"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# we have 8 samples (4 treated with Dexamethasone (Dex) and 4 untreated), the article discusses 16 samples but only included half of them in the datapackage. \n",
    "# we want to see which genes are differentially expressed and between which samples are the biggest variations \n",
    "# we will take a treated and untreated sample with high variability between groups and low variability within groups to do our Chipseq analysis. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# We use less than 12 biological replicates which is why we opt to use EdgeR instead of DESeq. This according to the article:\n",
    "# How many biological replicates are needed in an RNA-seq experiment and which differential expression tool should you use? By NICHOLAS J. SCHURCH et al. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "#install packages (airway data and EdgeR diff gene expression package)\r",
      "\r\n",
      "source(\"https://bioconductor.org/biocLite.R\")\r",
      "\r\n",
      "biocLite(\"airway\")\r",
      "\r\n",
      "\r",
      "\r\n",
      "source(\"https://bioconductor.org/biocLite.R\")\r",
      "\r\n",
      "biocLite(\"edgeR\")\r",
      "\r\n",
      "\r",
      "\r\n",
      "#download these packages into Rstudio\r",
      "\r\n",
      "library(airway)\r",
      "\r\n",
      "library(edgeR)\r",
      "\r\n",
      "\r",
      "\r\n",
      "#to learn how to use this datapackage:\r",
      "\r\n",
      "?airway\r",
      "\r\n",
      "\r",
      "\r\n",
      "#it tells us to use data(\"airway\") to get the values of the datapackage in R\r",
      "\r\n",
      "data (\"airway\")\r",
      "\r\n",
      "\r",
      "\r\n",
      "#to get the data as a data frame into R we make a name for our dataframe\r",
      "\r\n",
      "sampleData = as.data.frame(colData(airway))\r",
      "\r\n",
      "\r",
      "\r\n",
      "#we can visualize this dataframe simply by typing sampledata\r",
      "\r\n",
      "#this will give us information on the samples, treatments and so on. \r",
      "\r\n",
      "sampleData\r",
      "\r\n",
      "\r",
      "\r\n",
      "#the airway package contains a command called assay to put the data of the reads in a matrix\r",
      "\r\n",
      "#with genes in every row for a sample in every collumn\r",
      "\r\n",
      "assay <- assay(airway)\r",
      "\r\n",
      "head (assay)\r",
      "\r\n",
      "\r",
      "\r\n",
      "#we are now assigning our matrix assay(airway) to a simpler letter x\r",
      "\r\n",
      "x <- assay(airway)\r",
      "\r\n",
      "\r",
      "\r\n",
      "# and we add a grouping factor for our simple list based data object which we will make in the next step.\r",
      "\r\n",
      "#for our group we select the treatment column of our sampleData (= dex, see sampledata)\r",
      "\r\n",
      "#this group will have 2 levels: treated vs untreated.\r",
      "\r\n",
      "group = as.factor(sampleData$dex)\r",
      "\r\n",
      "#now we have x (our matrix) and our grouping factor which will be combined and stored in the DGEList which is a data object\r",
      "\r\n",
      "y <- DGEList(counts=x,group=group)\r",
      "\r\n",
      "\r",
      "\r\n",
      "#we now have to normalize the gene counts because we want to know relative- instead of absolute differences\r",
      "\r\n",
      "#we normalize based on RNA composition to obtain the effective library size (norm factors will now differ from 1)\r",
      "\r\n",
      "y <- calcNormFactors(y)\r",
      "\r\n",
      "y\r",
      "\r\n",
      "#factors > 1 scales up the library size analogues to downscaling the gene counts.\r",
      "\r\n",
      "#the library size will be adjusted in our downstream analysis.\r",
      "\r\n",
      "\r",
      "\r\n",
      "#we can visualize the librarysize per sample in a barplot\r",
      "\r\n",
      "barplot(y$samples$lib.size*1e-6, xlab=\"samples\", names = (1:8), ylab = \"library size in millions\")\r",
      "\r\n",
      "\r",
      "\r\n",
      "#we first have to look at dispersion before we can look at differential gene axpression\r",
      "\r\n",
      "#we want to estimate dispersion of the groups of our matrix so we first provide the group design \r",
      "\r\n",
      "design <- model.matrix(~0+group, data=y$samples)\r",
      "\r\n",
      "design\r",
      "\r\n",
      "y <- estimateDisp(y, design)\r",
      "\r\n",
      "\r",
      "\r\n",
      "#estimate the dispersion in a plot\r",
      "\r\n",
      "plotBCV (y)\r",
      "\r\n",
      "\r",
      "\r\n",
      "#we can now look for differentially expressed genes between our two groups (treated vs untreated)\r",
      "\r\n",
      "et <- exactTest(y, pair=c(\"untrt\",\"trt\"))\r",
      "\r\n",
      "topTags(et)\r",
      "\r\n",
      "#we see that the 10 most significant changes are upregulations of expression in treated compared to untreated (exept for 1 gene)\r",
      "\r\n",
      "\r",
      "\r\n",
      "#multidimensional scaling plots of log2 fold changes in distances between samples and groups.\r",
      "\r\n",
      "Samples <- as.factor(sampleData$Sample)\r",
      "\r\n",
      "plotMDS(y, labels = Samples)\r",
      "\r\n",
      "\r",
      "\r\n",
      "plotMDS(y, labels = group)\r",
      "\r\n",
      "\r",
      "\r\n"
     ]
    }
   ],
   "source": [
    "# Rscript used to do differential gene expression and MDS plotting on the airway datapackage\n",
    "cat /home/luna.kuleuven.be/r0372261/data/work/Rscript.R"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#image of the sampledata\n",
    "<img src=\"/user/r0372261/files/Sampledata.jpg\">"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#toptag of differential gene expression between groups\n",
    "<img src=\"/user/r0372261/files/DE%20expression.jpg\">"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#images of the MDS plots with sample labels and group labels\n",
    "<img src=\"/user/r0372261/files/PlotMDS%20samples.jpg\">\n",
    "<img src=\"/user/r0372261/files/PlotMDS%20groups.jpg\">"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Chipseq and visualization in IGV"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mkdir: cannot create directory ‘/home/luna.kuleuven.be/r0372261/data/ncbi’: File exists\r\n"
     ]
    }
   ],
   "source": [
    "mkdir ~/data/ncbi\n",
    "vdb-config -s /repository/user/main/public/root=~/data/ncbi"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mkdir: cannot create directory ‘/home/luna.kuleuven.be/r0372261/data/work’: File exists\r\n"
     ]
    }
   ],
   "source": [
    "mkdir ~/data/work\n",
    "cd ~/data/work "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Read 43356464 spots for SRR1039513\r\n",
      "Written 43356464 spots for SRR1039513\r\n",
      "Read 28136282 spots for SRR1039512\r\n",
      "Written 28136282 spots for SRR1039512\r\n"
     ]
    }
   ],
   "source": [
    "# de sra files omzetten in fastq (we kozen een Dex treated sample vs een untreated sample, beide met lage variabiliteit binnen de groep)\n",
    "fastq-dump SRR1039513\n",
    "fastq-dump SRR1039512"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "#naam van de fastq files aanpassen (optioneel)\n",
    "mv SRR1039513.fastq treated_sammple.fastq\n",
    "mv SRR1039512.fastq untreated_sammple.fastq"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "43356464 reads; of these:\r\n",
      "  43356464 (100.00%) were unpaired; of these:\r\n",
      "    19953227 (46.02%) aligned 0 times\r\n",
      "    17694247 (40.81%) aligned exactly 1 time\r\n",
      "    5708990 (13.17%) aligned >1 times\r\n",
      "53.98% overall alignment rate\r\n",
      "28136282 reads; of these:\r\n",
      "  28136282 (100.00%) were unpaired; of these:\r\n",
      "    28127740 (99.97%) aligned 0 times\r\n",
      "    7533 (0.03%) aligned exactly 1 time\r\n",
      "    1009 (0.00%) aligned >1 times\r\n",
      "0.03% overall alignment rate\r\n"
     ]
    }
   ],
   "source": [
    "# de fastq files alignen met ons referentiegenoom h19\n",
    "bowtie2-align -x /mnt/nfs/data/resources/bowtie2/hg19 treated_sammple.fastq -S treated_sample_aligned.sam\n",
    "bowtie2-align -x /mnt/nfs/data/resources/bowtie2/hg19 untreated_sammple.fastq -S untreated_sample_aligned.sam"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "#.sam files omzetten in .bam files\n",
    "samtools view -S -b treated_sample_aligned.sam > treated_sample_aligned.bam\n",
    "samtools view -S -b untreated_sample_aligned.sam > untreated_sample_aligned.bam"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[bam_sort_core] merging from 18 files...\r\n",
      "[bam_sort_core] merging from 12 files...\r\n"
     ]
    }
   ],
   "source": [
    "# sort and index the bam file\n",
    "samtools sort -O bam -o treated_sample_aligned_sorted.bam treated_sample_aligned.bam \n",
    "samtools index treated_sample_aligned_sorted.bam \n",
    "\n",
    "samtools sort -O bam -o untreated_sample_aligned_sorted.bam untreated_sample_aligned.bam \n",
    "samtools index untreated_sample_aligned_sorted.bam "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "#rename the files\n",
    "mv treated_sample_aligned_sorted.bam treatedS1.bam\n",
    "mv untreated_sample_aligned_sorted.bam untreatedS2.bam"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mkdir: cannot create directory ‘/home/luna.kuleuven.be/r0372261/data/macs2_peakcalling’: File exists\r\n",
      "INFO  @ Sun, 29 Jan 2017 11:30:51: \r\n",
      "# Command line: callpeak -t treatedS1.bam --outdir macs2_peakcalling -n SRR1039513 -g 59128983 -q 0.005\r\n",
      "# ARGUMENTS LIST:\r\n",
      "# name = SRR1039513\r\n",
      "# format = AUTO\r\n",
      "# ChIP-seq file = ['treatedS1.bam']\r\n",
      "# control file = None\r\n",
      "# effective genome size = 5.91e+07\r\n",
      "# band width = 300\r\n",
      "# model fold = [5, 50]\r\n",
      "# qvalue cutoff = 5.00e-03\r\n",
      "# Larger dataset will be scaled towards smaller dataset.\r\n",
      "# Range for calculating regional lambda is: 10000 bps\r\n",
      "# Broad region calling is off\r\n",
      " \r\n",
      "INFO  @ Sun, 29 Jan 2017 11:30:51: #1 read tag files... \r\n",
      "INFO  @ Sun, 29 Jan 2017 11:30:51: #1 read treatment tags... \r\n",
      "Traceback (most recent call last):\r\n",
      "  File \"/usr/local/bin/macs2\", line 614, in <module>\r\n",
      "    main()\r\n",
      "  File \"/usr/local/bin/macs2\", line 56, in main\r\n",
      "    run( args )\r\n",
      "  File \"/usr/local/lib/python2.7/dist-packages/MACS2/callpeak_cmd.py\", line 70, in run\r\n",
      "    else:       (treat, control) = load_tag_files_options  (options)\r\n",
      "  File \"/usr/local/lib/python2.7/dist-packages/MACS2/callpeak_cmd.py\", line 392, in load_tag_files_options\r\n",
      "    tp = options.parser(options.tfile[0], buffer_size=options.buffer_size)\r\n",
      "  File \"MACS2/IO/Parser.pyx\", line 68, in MACS2.IO.Parser.guess_parser (MACS2/IO/Parser.c:2754)\r\n",
      "  File \"MACS2/IO/Parser.pyx\", line 90, in MACS2.IO.Parser.guess_parser (MACS2/IO/Parser.c:2410)\r\n",
      "  File \"MACS2/IO/Parser.pyx\", line 670, in MACS2.IO.Parser.BAMParser.__init__ (MACS2/IO/Parser.c:8989)\r\n",
      "  File \"/usr/lib/python2.7/gzip.py\", line 34, in open\r\n",
      "    return GzipFile(filename, mode, compresslevel)\r\n",
      "  File \"/usr/lib/python2.7/gzip.py\", line 94, in __init__\r\n",
      "    fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb')\r\n",
      "IOError: [Errno 2] No such file or directory: 'treatedS1.bam'\r\n",
      "INFO  @ Sun, 29 Jan 2017 11:30:52: \r\n",
      "# Command line: callpeak -t untreatedS2.bam --outdir macs2_peakcalling -n SRR1039512 -g 59128983 -q 0.005\r\n",
      "# ARGUMENTS LIST:\r\n",
      "# name = SRR1039512\r\n",
      "# format = AUTO\r\n",
      "# ChIP-seq file = ['untreatedS2.bam']\r\n",
      "# control file = None\r\n",
      "# effective genome size = 5.91e+07\r\n",
      "# band width = 300\r\n",
      "# model fold = [5, 50]\r\n",
      "# qvalue cutoff = 5.00e-03\r\n",
      "# Larger dataset will be scaled towards smaller dataset.\r\n",
      "# Range for calculating regional lambda is: 10000 bps\r\n",
      "# Broad region calling is off\r\n",
      " \r\n",
      "INFO  @ Sun, 29 Jan 2017 11:30:52: #1 read tag files... \r\n",
      "INFO  @ Sun, 29 Jan 2017 11:30:52: #1 read treatment tags... \r\n",
      "Traceback (most recent call last):\r\n",
      "  File \"/usr/local/bin/macs2\", line 614, in <module>\r\n",
      "    main()\r\n",
      "  File \"/usr/local/bin/macs2\", line 56, in main\r\n",
      "    run( args )\r\n",
      "  File \"/usr/local/lib/python2.7/dist-packages/MACS2/callpeak_cmd.py\", line 70, in run\r\n",
      "    else:       (treat, control) = load_tag_files_options  (options)\r\n",
      "  File \"/usr/local/lib/python2.7/dist-packages/MACS2/callpeak_cmd.py\", line 392, in load_tag_files_options\r\n",
      "    tp = options.parser(options.tfile[0], buffer_size=options.buffer_size)\r\n",
      "  File \"MACS2/IO/Parser.pyx\", line 68, in MACS2.IO.Parser.guess_parser (MACS2/IO/Parser.c:2754)\r\n",
      "  File \"MACS2/IO/Parser.pyx\", line 90, in MACS2.IO.Parser.guess_parser (MACS2/IO/Parser.c:2410)\r\n",
      "  File \"MACS2/IO/Parser.pyx\", line 670, in MACS2.IO.Parser.BAMParser.__init__ (MACS2/IO/Parser.c:8989)\r\n",
      "  File \"/usr/lib/python2.7/gzip.py\", line 34, in open\r\n",
      "    return GzipFile(filename, mode, compresslevel)\r\n",
      "  File \"/usr/lib/python2.7/gzip.py\", line 94, in __init__\r\n",
      "    fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb')\r\n",
      "IOError: [Errno 2] No such file or directory: 'untreatedS2.bam'\r\n"
     ]
    }
   ],
   "source": [
    "#peakcalling on the aligned, sorted and indexed file\n",
    "mkdir ~/data/macs2_peakcalling\n",
    "macs2 callpeak -t  treatedS1.bam --outdir macs2_peakcalling -n SRR1039513 -g 59128983 -q 0.005\n",
    "\n",
    "macs2 callpeak -t  untreatedS2.bam --outdir macs2_peakcalling -n SRR1039512 -g 59128983 -q 0.005"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "macs2_peakcalling\t     SRR1039513_model.r\r\n",
      "SRR1039512_model.r\t     SRR1039513_peaks.narrowPeak\r\n",
      "SRR1039512_peaks.narrowPeak  SRR1039513_peaks.xls\r\n",
      "SRR1039512_peaks.xls\t     SRR1039513_summits.bed\r\n",
      "SRR1039512_summits.bed\r\n"
     ]
    }
   ],
   "source": [
    "#see which files are in your directory now\n",
    "ls"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "chr10\t17271402\t17271623\tSRR1039512_peak_1\t172\t.\t13.19261\t24.34644\t17.27386\t59\r\n",
      "chr12\t91539495\t91539964\tSRR1039512_peak_2\t100\t.\t9.77756\t16.72079\t10.09417\t341\r\n",
      "chr12\t91552105\t91552298\tSRR1039512_peak_3\t165\t.\t13.05862\t23.55883\t16.51532\t55\r\n",
      "chr17\t38600142\t38600314\tSRR1039512_peak_4\t95\t.\t9.67118\t16.19693\t9.59222\t51\r\n",
      "chr19\t49469877\t49470095\tSRR1039512_peak_5\t221\t.\t14.81043\t29.53810\t22.19667\t81\r\n",
      "chr2\t216236825\t216236997\tSRR1039512_peak_6\t75\t.\t8.62610\t13.87448\t7.52775\t63\r\n",
      "chr3\t13612480\t13612656\tSRR1039512_peak_7\t125\t.\t11.12878\t19.28225\t12.51070\t115\r\n",
      "chr3\t112357675\t112357898\tSRR1039512_peak_8\t125\t.\t10.60741\t19.34377\t12.56887\t111\r\n",
      "chr6\t27620392\t27620584\tSRR1039512_peak_9\t227\t.\t16.68601\t32.27706\t22.78951\t89\r\n",
      "chr9\t135895081\t135895253\tSRR1039512_peak_10\t35\t.\t6.44995\t9.36982\t3.59710\t16\r\n",
      " 10 774 SRR1039512_peaks.narrowPeak\r\n"
     ]
    }
   ],
   "source": [
    "#look at the files with the narrow peaks and count them = how many TF binding sites (look at ls results for name of the files!)\n",
    "head SRR1039512_peaks.narrowPeak\n",
    "wc -lc SRR1039512_peaks.narrowPeak"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 SRR1039513_peaks.narrowPeak\r\n"
     ]
    }
   ],
   "source": [
    "#do the same for the untreated sample to see the differences.\n",
    "head SRR1039513_peaks.narrowPeak\n",
    "wc -l SRR1039513_peaks.narrowPeak"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "#IGV visualization of the peaks\n",
    "<img src=\"/user/r0372261/files/All%20peaks.jpg\">"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "there are 10 peaks (on chromosomes 2, 2x3, 6, 9, 10, 2x12, 17 and 19)\n",
    "\n",
    "these possibly new TF binding sites are located in the following genes and are involved in the following biological process (GO) VIM (chr10) = vimentin = protein/glycogen binding DCN (ch12) = decorin = protein binding and placenta/kidney development IGFBP4 (chr17) = insulin like growth factor binding protein 4 = proliferation, cellular growth and inflammation FTL (chr19) = ferritin light chain = iron ion binding FN1 (chr2) = fibronectin = integrin binding and angiogenesis FBLN2 (chr3) = fubulin 2 = extracellular matrix constituent CCDC80 (chr3) = membrane/matrix organisation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "visualization of peak 7 located in chromosome 3\n",
    "<img src=\"/user/r0372261/files/Peak%207.jpg\">"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "We first did differential gene expression analysis with EdgeR in Rstudio to look at the differences in gene expression between treated and untreated samples. The variability within groups is very small whereas the variability between in groups is high suggesting a differences in gene expression after treatment. We have chosen a sample from the treated group and a sample from the untreated group of the same celline to ChipSeq analysis. The untreated sample had 10 peaks suggesting 10 TF binding sites which aren't present in the treated sample (downregulation in treated sample). Most of these peaks are located in genes which are involved in protein binding and matrix constitution (according to gene ontology)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Bash",
   "language": "bash",
   "name": "bash"
  },
  "language_info": {
   "codemirror_mode": "shell",
   "file_extension": ".sh",
   "mimetype": "text/x-sh",
   "name": "bash"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
