Skip to content

Commit

Permalink
Merge 05b1b23 into 0079197
Browse files Browse the repository at this point in the history
  • Loading branch information
carlosp420 committed May 19, 2018
2 parents 0079197 + 05b1b23 commit 3bdec8e
Show file tree
Hide file tree
Showing 27 changed files with 2,109 additions and 338 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ dist
*csv
.idea
*.py[cod]
.mypy_cache
_trial_temp*
tests_eero
benchmarks.R
Expand Down
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
language: python
sudo: false
python:
- "2.7"
- "3.6"

# command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors
install: pip install -r requirements-test.txt

# command to run tests, e.g. python setup.py test
script: coverage run --source=bold_retriever `which trial` tests/
script: coverage run setup.py test

after_success: coveralls
13 changes: 5 additions & 8 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
Copyright (c) 2014, Carlos Pena
All rights reserved.
MIT License

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Copyright (c) 2018, Carlos Pena

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

* Neither the name of Bold Retriever nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ test-all:
tox

coverage: clean-test
coverage run --source=bold_retriever `which trial` tests/
coverage run setup.py test
coverage report
coverage html

Expand Down
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# bold retriever

bold_retriever is a Python application to identify specimens from COI sequences and BOLD SYSTEMS

## Basic setup

Install the requirements:
```
$ pip install -r requirements.txt
```

Run the application:
```
$ python -m bold_retriever --help
```

To run the tests:
```
$ pytest
```
2 changes: 1 addition & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ For example::

* output::

seq_id bold_id similarity division class order family species collection_country
OtuID bold_id similarity division class order family species collection_country
OTU_99 FBNE064-11 1 animal Insecta Neuroptera Hemerobiidae Hemerobius pini Germany
OTU_99 NEUFI079-11 1 animal Insecta Neuroptera Hemerobiidae Hemerobius pini Finland
OTU_99 FBNE172-13 0.9937 animal Insecta Neuroptera Hemerobiidae Hemerobius atrifrons Germany
Expand Down
24 changes: 0 additions & 24 deletions benchmarks.R

This file was deleted.

Binary file removed benchmarks.png
Binary file not shown.
Binary file added bold.sqlite
Binary file not shown.
136 changes: 136 additions & 0 deletions bold_retriever.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
from datetime import datetime, timedelta
from typing import Dict, Optional
from urllib.parse import urlencode

from Bio import SeqIO
import click
import dataset
import requests

from engine import generate_output_content, parse_id_engine_xml


DATABASE_URL = "sqlite:///bold.sqlite"
DB = dataset.connect(DATABASE_URL)


@click.command()
@click.option('-f', '--filename', type=str, help='Fasta filename', required=True)
@click.option('-db',
'--database',
type=click.Choice([
'COX1_SPECIES', 'COX1', 'COX1_SPECIES_PUBLIC', 'COX1_L640bp',
]),
help='Choose a BOLD database. Enter one option.',
required=True,
)
def bold(filename, database):
"Send seqs to BOLD Systems API and retrieve results"
click.echo(filename + " " + database)
output_filename = create_output_file(filename)
generate_jobs(output_filename, filename, database)


def create_output_file(input_filename: str) -> str:
"""Containing only column headers of the CSV file."""
output = "id,bold_id,sequencedescription,database,citation,taxonomicidentification,similarity,url,country,lat,lon,class,order,family,species,"
output += "collection_country\n"

output_filename = input_filename.strip() + "_output.csv"
print(f"Creating output file {output_filename}")
with open(output_filename, "w") as handle:
handle.write(output)
return output_filename


def generate_jobs(output_filename: str, fasta_file: str, db: str):
print(f"Reading sequences from {fasta_file}")

for seq_record in SeqIO.parse(fasta_file, "fasta"):
print(f"* Reading seq {seq_record.name}")
response = id_engine(seq_record, db, output_filename)
seq_record_identifications = parse_id_engine_xml(response.text)

# add our seq id to the list of identifications
for seq_record_identification in seq_record_identifications:
seq_record_identification["OtuID"] = seq_record.id
taxonomy = get_taxonomy(seq_record_identification)
seq_record_identification.update(taxonomy)
generate_output_content(seq_record_identifications, output_filename, seq_record)


def id_engine(seq_record, db, output_filename):
"""Send a COI sequence to BOLD and retrieve its identification"""
print(f"* Processing sequence for {seq_record.id}")

domain = "http://boldsystems.org/index.php/Ids_xml"
payload = {'db': db, 'sequence': str(seq_record.seq)}
url = domain + '?' + urlencode(payload)

res = requests.get(url, headers={'User-Agent': 'bold_retriever'})
return res


def get_taxonomy(seq_record: Dict[str, str]) -> Optional[Dict[str, str]]:
tax_id = get_tax_id(seq_record)
if tax_id:
taxonomy = get_higher_level_taxonomy(tax_id)
return taxonomy


def get_tax_id(seq_record: Dict[str, str]):
tax_id = get_tax_id_from_db(seq_record)
if tax_id:
return tax_id

domain = "http://boldsystems.org/index.php/API_Tax/TaxonSearch?taxName="
url = domain + seq_record["taxonomicidentification"]
res = requests.get(url, headers={'User-Agent': 'bold_retriever'})
response_json = res.json()
try:
tax_id = response_json["top_matched_names"][0]["taxid"]
except (KeyError, IndexError):
tax_id = None

if tax_id:
table = DB["tax_ids"]
data = {
"taxon": seq_record["taxonomicidentification"],
"tax_id": tax_id,
}
table.insert(data)
return tax_id


def get_tax_id_from_db(seq_record: Dict[str, str]) -> Optional[str]:
table = DB["tax_ids"]
element = table.find_one(taxon=seq_record["taxonomicidentification"])
if element:
return element["tax_id"]


def get_higher_level_taxonomy(tax_id):
table = DB["taxonomy"]
element = table.find_one(tax_id=tax_id)
if element:
del element["id"]
return element

url = f"http://boldsystems.org/index.php/API_Tax/TaxonData?taxId={tax_id}&dataTypes=basic&includeTree=true"
res = requests.get(url, headers={'User-Agent': 'bold_retriever'})
response_json = res.json()
taxonomy = dict()

for id in response_json.keys():
category = response_json[id]
value = category["taxon"]
key = category["tax_rank"]
taxonomy[key] = value

taxonomy["tax_id"] = tax_id
table.insert(taxonomy)
return taxonomy


if __name__ == '__main__':
bold()
5 changes: 0 additions & 5 deletions bold_retriever/__init__.py

This file was deleted.

126 changes: 0 additions & 126 deletions bold_retriever/bold_retriever.py

This file was deleted.

2 changes: 1 addition & 1 deletion docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ For example::

The output should look like this::

seq_id bold_id similarity division class order family species collection_country
OtuID bold_id similarity division class order family species collection_country
TE-14-27_FHYP_av FIDIP558-11 0.9884 animal Insecta Diptera None Diptera Finland
TE-14-27_FHYP_av GBDP6413-09 0.9242 animal Insecta Diptera Hippoboscidae Ornithomya anchineura None
TE-14-27_FHYP_av GBDP2916-07 0.922 animal Insecta Diptera Hippoboscidae Stenepteryx hirundinis None
Expand Down

0 comments on commit 3bdec8e

Please sign in to comment.