Showing posts with label bioinformatics. Show all posts
Showing posts with label bioinformatics. Show all posts

Wednesday, June 19, 2013

Getting Started with SAMtools and Rsamtools

Have you heard of this thing called 'samtools', but not really sure what it is or how to get started?   Maybe you are a postdoc in a wet-lab that is now starting to use whole-genome and whole-exome sequencing, but there isn't an in-house bioinformatician to help sift though the computational side of the project?  If you're like me (a statistician by training and working with genomic data), learning about tools to handle next-generation sequencing data is essential.  This tutorial is meant give a little background about samtools and then provide some technical (and hopefully helpful) information on the purpose of samtools, its relation to Rsamtools and examples of how to utilize both.


Beginning with SAMtools

What does SAM mean? How is SAM different from BAM?
The Sequence Alignment/Map (SAM) format was developed to store aligned nucleotide sequence reads produced from genome aligners (e.g. BWA) in a somewhat human readable tab-deliminted text file.  Practically speaking, this format has become the standard alignment format widely used by groups such as 1000 Genomes Project.  The Binary Alignment/Map (BAM) format is a binary version of SAM  which contains the same information and simply compresses the data to save storage space (and BAM files are faster to manipulate).  In the SAM format, there is a header section (all header rows begin with '@') and an alignment section (all alignment rows contain 11 mandatory fields + optional fields).

What is SAMtools and where did SAMtools come from? 
The SAM/BAM format and SAMtools were published by Li et al. 2009. The purpose of samtools is provide a way to manipulate and interact with the aligned sequence reads in SAM/BAM format.  Samtools does not work with the entire file of aligned reads, but rather works in a stream which allows Unix commands to be used in conjunction with the SAM files.

How do you install samtools?
The easiest way to do this to check out the most recent samtools source code from the github project page.  If you're not familiar with git or github, I would suggest this wonderful tutorial by Karl Broman. The best description of github I've heard is this tutorial, Karl writes "Github is like facebook for programmers", which couldn't be more true.   So, if you've set yourself up with a github account, then simply check out the lastest samtools source code

git clone git://github.com/samtools/samtools.git
cd samtools
make
make razip

This last line is to compile razip which is a tool to compress files and still make them randomly accessible by samtools (not normally possible with gzip files).  Finally, the last step is to make samtools accessible to all the users on the machine which I extracted from this tutorial.

sudo cp ~/current/working/directory/samtools /usr/local/samtools-v0.1.19
sudo ln -s /usr/local/samtools-v0.1.19 /usr/local/samtools

The second line makes a symbolic link to the latest version directory. When a new version of samtools becomes available (e.g. samtools-v0.1.20), you can install it in the same directory and then just update the /usr/local/samtools symbolic link.  You can check to make sure samtools was installed in your $PATH with the following command:

which samtools

If nothing happens, samtools was not properly put in your $PATH.


Examples of how to use SAMtools

There are many tutorials on samtools.  The standard format of samtools requires a command and then allows for additional options.

samtools [command] <options>

If you type just 'samtools' in the terminal window,  a list of available command (and their descriptions) will be provided.  We begin by creating a folder which will contain our SAM file and reference genome in fasta format which we used to align the reads.

mkdir MyProject
cp ~/current/working/directory/test.sam MyProject
cp ~/current/working/directory/ref.fa MyProject

samtools view
To convert from SAM to BAM format (option -b) when header is available and input is SAM format (option -S)
samtools view -Sb test.sam > test.bam

To convert from SAM to BAM format when header is not available, but ref.fa was used to map the reads
samtools view -b ref.fa test.sam > test.bam

To filter out unmapped reads from BAM files (option -F)
samtools view -bF test.bam > mappedtest.bam

samtools sort
To sort BAM file by chromosomal coordinates (default) or read names (option -n) and create a test.sorted.bam file
samtools sort test.bam test.sorted

An example of using a Unix pipe to go from the SAM format to the sorted BAM format
samtools view -Sb test.sam | samtools sort test.sorted

samtools index 
To create an indexed bam file (.bai) from the test.sorted.bam file 
samtools index test.sorted.bam

samtools faidx
To create an indexed reference genome in FASTA format (creates a .fai file)
samtools faidx ref.fa 



Examples of using SAM/BAM files 

'samtools mpileup' and 'bcftools view'
To create a Binary Call Format (bcf) file (option -u) by mapping the bases using the indexed reference genome (option -f) and call genomic variants
samtools mpileup -u -f ref.fa test.sorted.bam > test.bcf

To convert the bcf file to a human readable Variant Call Format (vcf) file
bcftools view -v -g test.bcf > test.vcf

From here, you can also check out the Integrative Genomics Viewer (IGV) to visually look at the aligned reads or try importing the BAM files into tools like Rsamtools.


Examples of how to use Rsamtools

The purpose of Rsamtools is to provide an interface between R and BAM files produced by the tools samtools, bcftools, and tabix (not discussed here). To install Rsamtools in R, use

source("http://bioconductor.org/biocLite.R")
biocLite("Rsamtools")

The main purpose is to import (indexed!) BAM files into R using the scanBam() function.  The vignette for Rsamtools can be found here.  The entire BAM file should not be read into R, but rather just the portion of the genome of interest using the what and which arguments in ScanBamParam(which=which, what=what).  There are other packages which can read in BAM files include ShortRead and GenomicRanges.

To extract the header information, use scanBamHeader().  Use filterBam() to filter reads from BAM file according to the criteria defined in ScanBamParam().

Another great use of Rsamtools is to access multiple BAM files using the BamViews class in Rsamtools. This allows you to obtain metadata by 'viewing' the BAM files rather than importing each BAM individually.


Thursday, October 18, 2012

UCSC Genome Browser: A few useful tips

Most of my research revolves around analyzing next-generation sequencing data such as whole-exome sequencing data.  As a statistician, I always appreciate finding useful bioinformatic tricks/tips from various tools that make me more efficient.  Here are three examples of using the UCSC Genome Browser that I've found helpful.

Tip #1:  How do you find a list of chromosome positions given a list of dbSNP identifiers? (Taken from the Guide to the UCSC Genome Browser FAQ by Nature)
Use the 'Variation and Repeats' group in Table Browser and the SNPs track of choice.  Just specify the genome (e.g. Human) and assembly (e.g. hg19).  For 'Region', if you want the chromosomal positions for a specific regions, click position and specify the region OR click genome and upload a list of dbSNP identifiers. Finally, choose your output format (e.g. GTF, BED) and click 'get output'.

Tip #2:  How do you lift over a set of genomic coordinates from hg18 to hg19? 
Use the Batch Coordinate Conversion (liftOver) tool in Utilities. Selected Original and New assemblies. Upload the original genomic coordinates (in a BED format) and submit.  

Tip #3: How can you extract data from the UCSC browser and use it in R? 
For this, we need to install the package rtracklayer.  Here is an example on how to extract recombination rates: 

library(rtracklayer)
my.session <- browserSession()
genome(my.session) <- "hg19"
recomb.rates <- getTable(ucscTableQuery(my.session, "recombRate"))

Tuesday, October 2, 2012

Beyond the Genome 2012: Highlights and Discussion Points

This past week I attended the Beyond the Genome conference Sept 27-29 held in Boston at Harvard Medical School this year.  Genome Medicine and Genome Biology have hosted this conference for three years now and it was my first time attending.  To see more details on individual talks, check out the blogposts from Oliver Hofmann tagged with btg2012 or you can search for tweets with the hashtag #BtG2012. I want to give a few highlights from the conference, but first I'll begin with a cartoon which was a very fitting way to describe the conference!


Here are a few key discussion points I took away from the conference:
  1. Genomic or bioinformatic tools used to analyze next-generation sequencing data need to be reproducible, accessible, fast, interactive and web-based. James Taylor from Galaxy advocated for making bioinformatics more reproducible and accessible and even gave an example of in a review only 7 out of 50 papers using BWA provided all the parameters necessary to be able to reproduce their research. Gabor Marth argued bioinformatic tools shouldn't be useable by only informaticians, but also should be useable by biologists.
  2. Bioinformaticians are re-inventing the wheel. I found two recent papers giving a review of batch annotation tools for variants obtained using next-gernation sequencing (Sifrim et al. 2012; Lyon and Wang 2012) with a list of over 19 tools published just since 2010!  At the conference, several of the speakers noted in their talks, "As bioinformaticians we apparently like to keep reinventing the wheel".  I would agree with this statement.  In addition to genomic tools needing to be reproducible, accessible, fast, interactive and web-based, I would argue we need to create a standardized tool or format for annotating variants.  
  3. With mutations, context matters. Why do some of the "right mutations" not respond to treatment? Josh Stuart advocated for using pathway-based analyses to assess the impact of mutations. Should focus on recurrent, rare variants (most likely to be impactful), but also need to make sure the background mutation rate is correct and determine if mutations are in key domains such as DNA binding or conserved domains. Daniel MacArthur said we need to analyze variants in the context of tens of thousands of genomes because the human genomic landscape is dominated by ultra-rare variation and we need to require consistent variant calls across studies. He also gave a set of recommendations on establishing causality from the NHGRI (see picture below).  Lynda Chin argued even if we know the mutation changes the function of the protein, we don't necessarily know the biological consequence. Therefore she argues we need to use a model systems approach to characterize and interpret a complete catalogue of driver mutations with functional validation.  
  4. The idea of using whole exome sequencing as a diagnostic test in clinic has arrived (especially for rare genetic disorders), but we are just now starting to deal with all the challenges that come along with it.  Sharon Plon discussed her first year experience with clinical whole exome sequencing and said almost 25% of sequenced patients have "medically actionable" findings (mostly cardiac, but some cancer). Elizabeth Worthey said we need to be very careful because she explained "medically actionable" doesn't always mean "can be treated". With secondary variants and findings in clinic, Leslie Biesecker argued context matters. In his experience, the response of the patient varies depending on prior family history: with previous diagnosis - mundane response, with prior family history - mild surprise, without family history - dazed and confused.  Amy McGuire gave a beautiful talk from the legal perspective on the reasons to disclose or not disclose incidental findings and included survey results from actual GWAS researchers. In terms of drug discovery, Stuart Schreiber gave many examples of relating the genomic alterations in cancer to the small-molecule sensitivity. 

Finally, I thought the talk by Richard Gibbs deserved it's own paragraph. His talk focused on who should we be sequencing when it comes to human genetic diseases.  Though next-generation sequencing technology has come a long way, it's still not perfect.  Performing whole exome sequencing as a service can be effectively done by experts, but this is inefficient and not scalable.  Automating the process of interpretation often ends with dumb results. Sequencing healthy individuals should be a low priority especially when not tying phenotypes to the control individuals (crazy!).  Sequencing individuals with complex diseases is still tricky because of the debate regarding CDCV v. CDRV hypothesis.  He argued that if complex diseases are caused by rare variants, then we should focus within families and not broader populations.  Sequencing individuals with mendelian disease should be high on the priority list because there is a huge value in obtaining a molecular diagnosis even without a treatment.  Finally recreational sequencing is low on the priority list.  He has even coined the term 'narcciss-ome'!  Overall, he predicts sequencing will become standard of care and soon all the excitement will be passé. 

Final thoughts:  The conference was filled with fantastic talks given by world-renowned speakers.  The level of genetic complexity of diseases never ceases to amaze me, but at the same time seeing such great research being produced to answer some tough genetic questions is always exciting.  I learned a great deal and would highly recommend Beyond the Genome to future participants!  

Friday, August 31, 2012

biomaRt: Find gene name using chromosome number and position

In a previous post, I gave a few examples of using biomaRt in R.  This is a continuation giving another useful example of using biomaRt: How to obtain gene names (e.g. HGNC) or really any information in listAttributes() function using only chromosome number and chromosome position. I was interested in obtaining the gene names for a set of mutations and decided to use biomaRt.  I created a tab-delimited file called 'positions.txt' containing three columns.  The first contained the chromosome number, followed by the start and end position (in this case they were the same).  The following code identifies what gene the chromosome position is in and reports the HGNC gene symbol.

# Load the library
library(biomaRt)

# Define biomart object
mart <- useMart(biomart="ensembl", dataset="hsapiens_gene_ensembl")

# Gives a list of all possible annotations; Currently there are 1668 listed
listAttributes(mart)

# Gives a list of all filters or criteria to search by; Currently there are 333 listed
# I chose to filter by: chromosome_name, start, end
listFilters(mart)

# Read in tab-delimited file with three columns: chromosome number, start position and end position
positions <- read.table("positions.txt")

# Extract HGNC gene symbol
results <- getBM(attributes = c("hgnc_symbol", "chromosome_name", "start_position", "end_position"), filters = c("chromosome_name", "start", "end"), values = list(positions[,1], positions[,2], positions[,3]), mart = mart)

Friday, July 13, 2012

War on Cancer

As a statistician applying my research to cancer genetics it is always encouraging to see stories like this that make me feel sometimes all this work isn't for nothing.

The article published last week in the NY Times describes the story of a woman who was diagnosed with a rare form of lymphoma in which white blood cells (T cells) become cancerous and move to the skin.  Faced with a disease with no cure and no standard treatment, she was able to keep the cancer at bay using chemotherapy for five years.  At that point, her health took a turn for the worse and her son who worked at Illumina, which produces some of the latest sequencing technology, decided to quit his job and help his mom full-time by sequencing her genome.  After sequencing her normal and tumor DNA, they found 18K differences (or mutations) with no known significance for disease.  In the analysis of her DNA, the researchers found two genes fused together forcing the growth signals in cancer cells to be reversed: the signal to stop was forcing the cells to grow and the signal to grow was forcing the cells to stop growth.  The researchers decided to give her a new melanoma drug ipilimumab which forces normal T cells to grow, in hopes of stopping the growth of the tumor cells. The drug performed beautifully keeping the cancerous T cells at bay for 8 weeks before the cancer came back and ultimately she passed away a few weeks later.

41 years ago Richard Nixon signed the National Cancer Act of 1971 which started a "war on cancer". The goal was to find a "cure for cancer" by increasing the funding toward cancer research and find more effective treatments.  As defined by PubMed "cancer is the uncontrolled growth of abnormal cells in the body".  Cancer is not just one disease, in fact it is the word we have for hundreds of diseases we label as 'cancer'.  When people talk about "curing cancer", it suggests that once a treatment/cure for one type of cancer is found, it should theoretically be applied to another form of cancer.  In my experience this is definitely not the case.  Every type of cancer is unique in its etiology and treatment.  It is true that some drugs today developed for one type of cancer can be applied to another type of cancer because the target molecule may happen be the same for two different cancers, but this is a separate idea than the finding a "cure for cancer".

I work with several groups of researchers in the Texas Medical Center at University of Texas MD Anderson, Baylor College of Medicine and Texas Children's Hospital who are all trying to exactly this.  They are sequencing the genomes of individuals affected by a particular disease and trying to find the causal mutation or reason for the disease.  My small contribution comes in helping to analyze the results that come out of the sequencing.  Bioinformatics attempts to take in the large amount of sequencing data and make sense of it.  This is by no means easy and will take much longer to properly analyze the data than to just sequence it.  But, even with these small steps I look forward to more success stories like these and seeing further progress being made in the war on cancer.

Friday, June 1, 2012

Private Genetics Company Announces First Mutation Patent

Last fall when I attended the American Society of Human Genetics in Montreal, there was a buzz about the company genetics company 23andMe.  With the cost of exome sequencing falling, this company was offering the opportunity for anyone to have their exome sequenced quite inexpensively.  On Monday 23andMe announced it's first patent titled "Polymorphisms Related to Parkinson's Disease". They discovered the G2019S variant in the SGK1 gene and suggest it may be protective against the disease.  Interestingly, they say "our patent is an important step in ensuring that we've done all we can towards successful translation of this discovery" and they "want to those discoveries to move from the realm of academic publishing to the world of impacting lives by preventing, treating or curing disease".  The response from the bloggers has been quite controversial.  At ASHG the idea of patenting genes or mutations was discussed in an open forum which was equally controversial.  Nature posted a blog about it yesterday which caught my eye.

The main problem with this announcement is the company is advertising the idea of patenting a gene or mutation as being beneficial because it will give individuals access to their genomes.  In reality, these are two separate issues.  The idea of patenting a gene or mutation is beneficial for the company to make money.  Giving people access to their genome is a nice thought, but as a researcher who works in the field of interpreting the variants discovered in exomes or genomes, there is not a sufficient amount of information available yet to properly interpret the variants.  We are just now discovering ways to efficiently sequence genomes and only at the very beginning of interpreting them. There is this idea of a $1,000 genome, but $1 million interpretation.  I'm curious to see how researchers in both academia and industry respond to this new world of patenting genes and mutations.

Monday, April 30, 2012

Freely Available Machine Learning Data sets

I cam across a great resource for anyone in statistics / machine learning! It's called the UCI Machine Learning Repository.  The website contains over 200 downloadable data sets and it is even classified by the task (classification, regression, clustering, etc), data type (multivariate, time-series, ... ), area (biological, business, ... ), and number of covariates.   Very valuable resource.



Tuesday, April 17, 2012

Gaddy Getz - April 18th 4pm

Gaddy Getz is giving a talk at 4pm in the medical center tomorrow!  It should be a great talk for everyone interested cancer genomics.

Wednesday, April 11, 2012

Using BioMart and biomaRt

I've been wanting to explore the tools BioMart and the corresponding R package biomaRt which is a part of the bioconductor suite.  I recently came across this blogpost explaining a bit more about the strength of the package.

biomaRt is a package which interfaces with a large number of databases implemented by the BioMart suite.  You don't need to know SQL, just R.  Examples of BioMart database include Ensembl and HapMap.  As the blogpost above says, "The concept is simple. You have a set of identifiers that describe a biological object, such as a gene. These are called filters. They have values – for example, HGNC symbols. You want to retrieve other identifiers – attributes – for your objects."  

First, we must install the R library biomaRt. 
source("http://bioconductor.org/biocLite.R")
biocLite("biomaRt")


We use the useMart() function to interface with a particular database.  To see the available marts, use listMarts(). Within the database, we need to pick a particular dataset.  You can see what datasets are available using the function listDatasets().  If we want to extract particular attributes from the database, we need to know what attributes are available.  This can be found using the listAttributes() function.  Finally, we use the getBM() function to actually extract the information.

Next, I will consider two examples. 

Example 1: Randomly sample n = 500 HGNC gene IDs from the human genome

# Load library
library(biomaRt)

# Define biomart object
mart <- useMart(biomart = "ensembl", dataset = "hsapiens_gene_ensembl")
# listDatasets(mart)
# listAttributes(mart)

# Extract information from biomart
results <- getBM(attributes = c("hgnc_symbol"), mart = mart)

# Randomly sample the gene name list
N <- 500
sample.hgnc <- sample(results$hgnc_symbol,N)

Sample results
> head(sample.hgnc)
[1] "LINC00293" "C6orf223"  "PRMT5-AS1" "SYT11"     "FLNB"      "SNORA49"  


Example 2: Given a list of REFSEQ IDs, convert gene IDs to HGNC IDs or Uniprot Swissprot IDs
library(biomaRt)

# Define biomart object
mart <- useMart(biomart = "ensembl", dataset = "hsapiens_gene_ensembl")

# Read in file with gene names
genes <- read.csv("refseq.csv")

# Extract information from biomart
results <- getBM(attributes = c("refseq_mrna", "hgnc_symbol"), filters = "refseq_mrna", values = genes[,1], mart = mart)

results <- getBM(attributes = c("refseq_mrna", "uniprot_swissprot"), filters = "refseq_mrna", values = genes[,1], mart = mart)
# see uniqueRows = TRUE/FALSE to return unique list of IDs or not

# Match the RefSeq names with the Uniprot names
matched <- match(genes[,1], results[,2])
cbind(genes,results[matched,2])

Sample results
     refseq Uniprot
1 NM_023018  O95544
2 NM_178545  Q8NDY8
3 NM_033467  Q495T6
4 NM_004402  O76075
5 NM_018198  Q9NVH1
6 NM_018198  Q9NVH1

After working through all this, I've quickly learned this is a very powerful tool in bioinformatics.