<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/bioinformatics-series-mitochondrial-control-region-ae-part-i-ae-using-gnu-bash-r-to-handle-large-genbank-files-in-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://monkeysworking.wordpress.com/2018/08/28/handle-large-genbank-files-in-r/"> R â€“ Monkeys Working</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><span>Hi everyone! In this series we are going to work with a gene called the Mitochondrial Control Region. This series will be about getting some insights into it from sequence analysis. We are going through the entire process, from getting data to reach some conclusions and more importantly raise some questions.</span></p>
<figure data-shortcode="caption" class="wp-caption"><img data-orig-file="https://monkeysworking.files.wordpress.com/2018/08/featured_hugo.jpeg?w=723" data-orig-size="394,387" data-medium-file="https://monkeysworking.files.wordpress.com/2018/08/featured_hugo.jpeg?w=723?w=300" data-attachment-id="151" data-image-meta="{" data-image-description="&lt;p&gt;Hugo Bendahan’s Carpincho grazing mitochondrions.&lt;/p&gt;
" src="https://monkeysworking.files.wordpress.com/2018/08/featured_hugo.jpeg?w=723" data-permalink="https://monkeysworking.wordpress.com/2018/08/28/handle-large-genbank-files-in-r/featured_hugo/" data-large-file="https://monkeysworking.files.wordpress.com/2018/08/featured_hugo.jpeg?w=723?w=394" alt="Hugo Bendahan's Carpincho grazing mitochondrions" data-image-title="Hugo Bendahan’s Carpincho grazing mitochondrions" sizes="(max-width: 394px) 100vw, 394px" data-comments-opened="1" class="wp-image-151"><figcaption class="wp-caption-text">Hugo Bendahan’s Carpincho grazing mitochondrions. Kindly contributed from <a rel="nofollow" href="https://gioiaseyes.wordpress.com/" target="_blank">https://gioiaseyes.wordpress.com/</a></figcaption></figure>
<p><span>All of the bash scripts and R functions used in this post are available in <a rel="nofollow" href="https://github.com/federiva/Monkeys-Working" target="_blank">our Github</a>, each function is properly linked out to it and we have not uploaded the raw data used in this post for memory reasons and also because this kind of data is ever evolving, nevertheless all the data which is not in our Github is linked out to the respective NCBI server and available for anyone.</span></p>
<p><span>Specifically, in this post we are going to do one of the most simple and sometimes most laborious thing to do, getting the data out from the chaotic and well ordered universe of sequences, annotations and variegated ids of databases.</span></p>
<p>To do this we are going to:</p>
<ul>
<li>Download nucleotide sequences (using a web-server)</li>
<li>Parse large genbank files (.gbff) in R, but using bash scripts.</li>
</ul>
<p>Since we are going to work with mitochondrial sequences we want to download full mitochondrial genomes (in .gbff format) from the NCBI’s RefSeqÂ <a rel="nofollow" target="_blank">ftp server</a><span>. The reason for using this specific database is that the RefSeq database has two important properties that we are interested in: First, the database is non-redundant and second, it is well annotated.Â For more of the Refseq's collection features check their <a rel="nofollow" href="https://www.ncbi.nlm.nih.gov/refseq/about/" target="_blank">website</a>.</span></p>
<p><span>As we know R has some memory issues when dealing with large files, so loading ~600 MB or more as an object in R for further processing is a bit complicated and perhaps it is not the better approach. Because of that we are going to write some Bash scripts to process the data with R but externally to it (using bash and other GNU tools).</span></p>
<p><span>The mitochondrial gene that we are interested in is called the â€˜Control region', but for now we are not going to talk about it because the first thing that we need to do is to get the data.</span></p>
<p>Once we've downloaded the data into our local drive we need to parse it. We chose the <a rel="nofollow" href="https://www.ncbi.nlm.nih.gov/Sitemap/samplerecord.html" target="_blank">.gbff file format</a> <span>because it has some other information that we may be interested in. Here arises the first problem when we try to load this large file in R (~614 MB with more than 10 million lines): My computer together with R almost explodes. Wellâ€¦ no, but seriously it gets stuck and runs slow, really slow, so it is really impractical.</span></p>
<p><span>So as we can't just load the data into R to parse it, Â we need to devise some kind of plan to work with it. For now, we may ask ourselves the following questions:</span></p>
<ol>
<li>Of all of the mitochondrial sequences that we have (8866 genomes), in which of them are we really interested in?</li>
<li>Are we interested in complete mitochondrial genomes?</li>
</ol>
<p>In the case of the first question, we are going to define a taxonomic criterion to subset our dataset. <span>We could choose any of the available taxa, but we are going Â to restrict our search into one specific suborder of Rodentia:</span> theÂ <a rel="nofollow" href="https://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Info&id=33550&lvl=3&lin=f&keep=1&srchmode=1&unlock" target="_blank">Hystricomorpha</a>. And the second answer is: Yes we are going to keep the full genomes because we are interested in what happens with other genes of the same macromolecule (mtDNA) and to make comparisons between them and our region of interest.</p>
<p>ThereforeÂ  we need to restrict our dataset into every genome that is part of the Hystricomorpha suborder of rodents.</p>
<p>Consequently, what we need then is to progressively subset our dataset into a manageable dataset for R. So, this means that we need to subset the ~600 MB file into a more &quot;discreet oneâ€� but sufficiently informative so we can still have the information that we need.</p>
<p>Roughly, the idea is represented in the following figure:</p>
<p><img data-orig-file="https://monkeysworking.files.wordpress.com/2018/08/figure_11.png?w=456" data-orig-size="1968,543" data-medium-file="https://monkeysworking.files.wordpress.com/2018/08/figure_11.png?w=456?w=300" data-attachment-id="149" data-image-meta="{" data-image-description="" src="https://monkeysworking.files.wordpress.com/2018/08/figure_11.png?w=456" data-permalink="https://monkeysworking.wordpress.com/2018/08/28/handle-large-genbank-files-in-r/figure_1-2/" data-large-file="https://monkeysworking.files.wordpress.com/2018/08/figure_11.png?w=456?w=723" alt="figure_1" data-image-title="figure_1" sizes="(max-width: 723px) 100vw, 723px" data-comments-opened="1" class="wp-image-149" data-recalc-dims="1"></p>
<p>If we check again the structure of a <a rel="nofollow" href="https://www.ncbi.nlm.nih.gov/Sitemap/samplerecord.html" target="_blank">gb/gbf/gbff file</a> then we can see that it has some taxonomic information which is stored in each entry in the following field:</p>
<p>FEATURES â†' SOURCE â†' /db_xref=”taxon:</p>
<p>In this field we have a number that it is related to the NCBI taxonomy database (see the disclaimer in the NCBI website if you are a taxonomist!), and with this number, we can know if a particular entry is an hystricomorph or not using another file named nodes.dmp from the taxdmp file locatedÂ <a rel="nofollow" target="_blank">here.</a></p>
<p><span>Then, in order to parse this large .gbff file using R we wrote some functions in Bash using the following GNU programs:</span></p>
<ul>
<li>GNU Awk 4.0.1</li>
<li>GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)</li>
<li>cmp (GNU diffutils) 3.3</li>
<li>grep (GNU grep) 2.16</li>
<li>sed (GNU sed) 4.2.2</li>
</ul>
<p>The figure below shows an algorithm which give us an idea in how to do this task.</p>
<p><img data-orig-file="https://monkeysworking.files.wordpress.com/2018/08/figure_21.png?w=456" data-orig-size="2460,1426" data-medium-file="https://monkeysworking.files.wordpress.com/2018/08/figure_21.png?w=456?w=300" data-attachment-id="147" data-image-meta="{" data-image-description="" src="https://monkeysworking.files.wordpress.com/2018/08/figure_21.png?w=456" data-permalink="https://monkeysworking.wordpress.com/2018/08/28/handle-large-genbank-files-in-r/figure_2/" data-large-file="https://monkeysworking.files.wordpress.com/2018/08/figure_21.png?w=456?w=723" alt="figure_2" data-image-title="figure_2" sizes="(max-width: 723px) 100vw, 723px" data-comments-opened="1" class="wp-image-147" data-recalc-dims="1"></p>
<p><span>For each one of these processes (A, B, C and D) we are going to write different bash scripts and R functions. The idea is that every one of these scripts and functions would give us some output files to work in R. Each one of the R functions have some Bash script associated with. Ok, let start.</span></p>
<h2>A – Generating an index of each one of the entries in the .gbff file</h2>
<p><span>In this section we use an R function called</span>Â <a rel="nofollow" href="https://github.com/federiva/Monkeys-Working/blob/master/mitochondrial_DNA/r_project_mitochondrial_DNA/R/function_create_a_csv_file_from_a_gbff_file.R" target="_blank">CreateCSVFromGBFF()</a>Â <span>that uses a bash script named</span> <a rel="nofollow" href="https://github.com/federiva/Monkeys-Working/blob/master/mitochondrial_DNA/r_project_mitochondrial_DNA/bash_scripts/CreateCSVFromGBFF.sh" target="_blank">CreateCSVFromGBFF.sh</a>. This function takes as input a .gbff file and gives us an output file saved in the working directory as <code>./csv_files/indexes_summary.csv</code>. For example:</p>
<pre>
#Run the function to generate a .csv index of the .gbff file
CreateCSVFromGBFF(&quot;../raw_data/mitochondrion.1.2.genomic.gbff&quot;)
index_mitochondrion &lt;- read.csv(&quot;.csv_files/indexes_summary.csv&quot;)
str(index_mitochondrion)

'data.frame':	8868 obs. of  8 variables:
 $ fromLine         : Factor w/ 8868 levels &quot;1&quot;,&quot;10000512&quot;,..: 1 416 1437 2347 3196 4184 4998 7369 8236 408 ...
 $ toLine           : int  1043 2091 3140 4077 5133 6090 8454 9378 10392 11405 ...
 $ taxonId          : int  123685 291360 104659 648471 123683 182643 536035 83285 244518 8150 ...
 $ organism         : Factor w/ 8803 levels &quot;&quot;,&quot;Abacion magnum&quot;,..: 5700 5695 5698 358 5696 2067 1359 3939 6142 8460 ...
 $ definition       : Factor w/ 8856 levels &quot;&quot;,&quot; 1986&quot;,&quot; 1989)&quot;,..: 5768 5763 5766 358 5764 2108 1380 3994 6202 8524 ...
 $ locus            : Factor w/ 8867 levels &quot;&quot;,&quot;AC_000022 16300 bp DNA circular ROD 28-AUG-2012&quot;,..: 1855 1856 1858 2267 1860 2305 3872 2888 3078 3079 ...
 $ accession        : Factor w/ 8867 levels &quot;&quot;,&quot;AC_000022&quot;,..: 1853 1854 1856 2266 1858 2304 3872 2888 3078 3079 ...
 $ accession_version: Factor w/ 8867 levels &quot;&quot;,&quot;AC_000022.2&quot;,..: 1853 1854 1856 2266 1858 2304 3872 2888 3078 3079 ...
</pre>
<p>We can see here that the .csv file has some basic information given in the gbff file and furthermore we add two more columns named <code>fromLine</code> and <code>toLine</code> which have the line number corresponding to the each entry in the .gbff input file. These line numbers along with the <code>taxonId</code> column are the information that we are going to use to further processing the dataset.<br>
Essentially we’ve condensed the information present in the .gbff file into a .csv that can be read as a data.frame in R. We went from a ~600 MB file to a ~1.5 MB file which is a lot better (actually ~400x less memory) to work with.</p>
<p>Now if we go again to the <a rel="nofollow" href="https://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Info&id=33550&lvl=3&lin=f&keep=1&srchmode=1&unlock" target="_blank">NCBI’s taxonomy browser</a> and look into the Hystricomorpha’s entry we can see that it has a field called “Taxonomy id” (taxid) that is a number, in this case, <strong>33550</strong>. This Id is unique to the Hystricomorpha entry and each entry (either a genus, species, subspecies, order, etc.) has a unique one. So now, we need to know which taxids belongs to the Hystricomorpha suborder. And this is part of the following section.</p>
<h2>B – Generating a list of child taxids</h2>
<p>This part answers to the following question. Given an arbitrary NCBI taxonomic id (parent id): Which are all of the taxids that are below the parent id?. In other words: Which are the child taxids to a given parent taxid?<br>
<span>In order to answer this question more data is required, we need to know the complete list of records of the NCBI's taxonomy. We have this data at hand (thanks to NCBI) in the taxdmp.zip, more specifically we'll work with the nodes.dmp file which has the information that we want.</span></p>
<p>In this particular case we are going to use the bash script: <a rel="nofollow" href="https://github.com/federiva/Monkeys-Working/blob/master/mitochondrial_DNA/r_project_mitochondrial_DNA/bash_scripts/GetNCBITaxonomyChildNodes.sh" target="_blank">GetNCBITaxonomyChildNodes.sh</a> into the R function called <a rel="nofollow" href="https://github.com/federiva/Monkeys-Working/blob/master/mitochondrial_DNA/r_project_mitochondrial_DNA/R/function_get_all_ncbi_taxonomy_child_nodes_from_a_given_taxid.R" target="_blank">GetNCBITaxonomyChildNodes()</a>. This R function writes a .csv file called <code>./csv_files/child_nodes.csv</code> that later can be read as a data.frame in R, for example:</p>
<pre>
# Run the function
GetNCBITaxonomyChildNodes(nodes.dmp.path = &quot;../raw_data/taxdmp/nodes.dmp&quot;, target.taxid = &quot;33550&quot;)
# Read the .csv output file
child.taxids.df &lt;- read.csv(&quot;csv_files/child_nodes.csv&quot;, sep=&quot;|&quot;, header = T)
</pre>
<p>Afterwards we can make an exploratory plot of the distribution of ranks which are Hystricomorpha’s child nodes.<br>
<img data-orig-file="https://monkeysworking.files.wordpress.com/2018/08/plot_1_ranks_distribution.png?w=456" data-orig-size="2125,1771" data-medium-file="https://monkeysworking.files.wordpress.com/2018/08/plot_1_ranks_distribution.png?w=456?w=300" data-attachment-id="148" data-image-meta="{" data-image-description="" src="https://monkeysworking.files.wordpress.com/2018/08/plot_1_ranks_distribution.png?w=456" data-permalink="https://monkeysworking.wordpress.com/2018/08/28/handle-large-genbank-files-in-r/plot_1_ranks_distribution/" data-large-file="https://monkeysworking.files.wordpress.com/2018/08/plot_1_ranks_distribution.png?w=456?w=723" alt="plot_1_ranks_distribution" data-image-title="plot_1_ranks_distribution" sizes="(max-width: 723px) 100vw, 723px" data-comments-opened="1" class="wp-image-148" data-recalc-dims="1"><br>
Here we can see that we have 340 taxids in the lower nodes (species + subspecies) and an odd one that has no rank. A search in the taxonomy browser for this taxid returns that is an unclassified <em>Ctenomys</em>, and given that <em>Ctenomys</em> is an hystricomorph then it’s ok.<br>
The next thing that we need to do is to filter our first dataset (output file of the CreateCSVFromGBFF() function of section A) with another function we wrote called <a rel="nofollow" href="https://github.com/federiva/Monkeys-Working/blob/master/mitochondrial_DNA/r_project_mitochondrial_DNA/R/function_subset_a_csv_filtered_gbff_with_a_csv_of_taxids.R" target="_blank">FilterParsedGBFF()</a> running the following code:</p>
<pre>
filtered.gbff.index &lt;- FilterParsedGBFF(path.to.parsed.gbff.csv = &quot;csv_files/indexes_summary.csv&quot;, path.to.child.taxids.csv = &quot;csv_files/child_nodes.csv&quot;)
</pre>
<p>Which give us 23 results, this means that we only have 23 complete mitochondrial genomes out of approximately 340 (species+subspecies). This is less than 7% of all hystricomorphs mitochondrial genomes are actually sequenced.</p>
<p><span>In conclusion:</span></p>
<ol>
<li><span>We have got all the child taxids of a given parent taxid in the NCBI’s taxonomy database.</span></li>
<li><span>We have subsetted a larger database by using the taxonomic units of interest (from 8866 entries to 23).</span></li>
</ol>
<h2>C and D – Extracting individual .gbff and .fasta sequence files</h2>
<p><span>Now with the last filtered database we can finally extract from the large ~600 MB file the individual .gbff and .fasta entries.</span></p>
<pre>
ExtractFilteredGBFFFromCSV(path.to.filtered.CSV = &quot;csv_files/filtered.csv&quot;,path.to.gbff.sourcefile = &quot;../raw_data/mitochondrion.1.2.genomic.gbff&quot;)
ExtractFastaSeqsFromGBFF(path.to.folder.with.gbff.files = &quot;gbff_filtered_files/&quot;)
</pre>
<p>The <a rel="nofollow" href="https://github.com/federiva/Monkeys-Working/blob/master/mitochondrial_DNA/r_project_mitochondrial_DNA/R/function_extract_individual_gbff_files_from_a_csv_of_filtered_entries.R" target="_blank">ExtractFilteredGBFFFromCSV()</a> uses the filtered.csv file which have the line number of each entry within the source .gbff file, and it returns individual .gbff files (23 in this case) in the directory <code>./gbff_filtered_files/</code> <span>named according to the following format:Â </span>Organism Name + Accession number like for example: <code>Ctenomys_sociabilis_NC_020658.gbff</code><br>
After extracting each entry to separate .gbff files we use <a rel="nofollow" href="https://github.com/federiva/Monkeys-Working/blob/master/mitochondrial_DNA/r_project_mitochondrial_DNA/R/function_extract_fasta_sequences_from_a_gbff_file.R" target="_blank">ExtractFastaSeqsFromGBFF()</a> in the following way:</p>
<pre>
# Run the function
ExtractFastaSeqsFromGBFF(path.to.folder.with.gbff.files = &quot;gbff_filtered_files/&quot;)
</pre>
<p>And finally all the .fasta files will be saved into the folder <code>./gbff_filtered_files/fasta_seqs/</code>.</p>
<p>The last two R functions also use the corresponding bash scripts:</p>
<ul>
<li><a rel="nofollow" href="https://github.com/federiva/Monkeys-Working/blob/master/mitochondrial_DNA/r_project_mitochondrial_DNA/bash_scripts/ExtractFilteredGBFFFromCSV.sh" target="_blank">ExtractFilteredGBFFFromCSV.sh</a></li>
<li><a rel="nofollow" href="https://github.com/federiva/Monkeys-Working/blob/master/mitochondrial_DNA/r_project_mitochondrial_DNA/bash_scripts/ExtractFastaSeqsFromGBFF.sh" target="_blank">ExtractFastaSeqsFromGBFF.sh</a></li>
</ul>
<h2>Conclusion, limitations and final remarks</h2>
<ul>
<li>We have successfully filtered a large .gbff file using R + Bash overcoming the memory limitations when loading large datasets in R. Bypassing this with Bash creating local files instead of loading every middle step of the workflow into the memory in R</li>
<li>There could be some compatibility issues when trying to use the bash scripts in other operating systems rather than Linux. If it’s necessary this could be worked out.</li>
</ul>
<p><span>The figure below gives us a final understanding of this post's workflow, the different scripts+functions used, and also the files and temporary folders created.</span></p>
<p><img data-orig-file="https://monkeysworking.files.wordpress.com/2018/08/figure_3.png?w=456" data-orig-size="1772,2658" data-medium-file="https://monkeysworking.files.wordpress.com/2018/08/figure_3.png?w=456?w=200" data-attachment-id="150" data-image-meta="{" data-image-description="" src="https://monkeysworking.files.wordpress.com/2018/08/figure_3.png?w=456" data-permalink="https://monkeysworking.wordpress.com/2018/08/28/handle-large-genbank-files-in-r/figure_3/" data-large-file="https://monkeysworking.files.wordpress.com/2018/08/figure_3.png?w=456?w=683" alt="figure_3" data-image-title="figure_3" sizes="(max-width: 723px) 100vw, 723px" data-comments-opened="1" class="wp-image-150" data-recalc-dims="1"></p>
<p> </p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://monkeysworking.wordpress.com/2018/08/28/handle-large-genbank-files-in-r/"> R â€“ Monkeys Working</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/9EQh_GujwWQ" height="1"></a></div>