aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPjotr Prins2021-01-01 12:09:10 +0000
committerPjotr Prins2021-01-01 12:09:10 +0000
commitdd9c8df418040093f2116de6592fc6add0c6a2ce (patch)
tree723c6976953159b0a17ea2c2c3b78480832b64be
parentacdd66f36e1596f8337195f22fdd7dd8a85c2b70 (diff)
downloadbh20-seq-resource-dd9c8df418040093f2116de6592fc6add0c6a2ce.tar.gz
bh20-seq-resource-dd9c8df418040093f2116de6592fc6add0c6a2ce.tar.lz
bh20-seq-resource-dd9c8df418040093f2116de6592fc6add0c6a2ce.zip
genbank: cleaning up
-rw-r--r--workflows/pull-data/genbank/README.md9
-rwxr-xr-xworkflows/pull-data/genbank/update-from-genbank.py206
2 files changed, 80 insertions, 135 deletions
diff --git a/workflows/pull-data/genbank/README.md b/workflows/pull-data/genbank/README.md
index 22dd920..c235be7 100644
--- a/workflows/pull-data/genbank/README.md
+++ b/workflows/pull-data/genbank/README.md
@@ -4,12 +4,9 @@
# --- get list of IDs already in PubSeq
sparql-fetch-ids > pubseq_ids.txt
# --- fetch XML
-update-from-genbank --skip pubseq_ids.txt --max 100 --outdir ~/tmp/genbank
-# --- get new IDs
-genbank-fetch-ids > genbank_ids.txt
-# --- loop through IDs (pseudo code)
-for id in genbank_ids.txt:
- transform-genbank-xml2yamlfa --dir ~/tmp/genbank id --outdir ~/tmp/pubseq
+update-from-genbank.py --skip pubseq_ids.txt --outdir ~/tmp/genbank
+# --- Transform to YAML and FASTA
+transform-genbank-xml2yamlfa --dir ~/tmp/genbank id --outdir ~/tmp/pubseq
```
# TODO
diff --git a/workflows/pull-data/genbank/update-from-genbank.py b/workflows/pull-data/genbank/update-from-genbank.py
index 132f553..e62a611 100755
--- a/workflows/pull-data/genbank/update-from-genbank.py
+++ b/workflows/pull-data/genbank/update-from-genbank.py
@@ -3,20 +3,21 @@
# - bulk download genbank data and matadata, preparing the FASTA and
# the YAML files
#
-# See .guix-run
+# update-from-genbank.py --max 10 --skip ids.txt --outdir ~/tmp/genbank
+#
+# See directory .guix-run and README.md
+
+BATCH_SIZE=5000
import argparse
parser = argparse.ArgumentParser()
-parser.add_argument('--ids-to-ignore', type=str, help='file with ids to ignore in all steps, 1 id per line', required=False)
-parser.add_argument('--ids-to-consider', type=str, help='file with ids to consider in all steps, 1 id per line', required=False)
-parser.add_argument('--skip-request', action='store_true', help='skip metadata and sequence request', required=False)
-parser.add_argument('--only-missing-ids', action='store_true', help='download only missing ids not already downloaded', required=False)
-parser.add_argument('--dict-ontology', type=str, help='where is the ontology',
- default='../dict_ontology_standardization/', required=False)
+parser.add_argument('--max', type=int, help='Max queries', required=False)
+parser.add_argument('--skip', type=str, help='File with ids to skip, 1 id per line', required=False)
+parser.add_argument('--outdir', type=str, help='Output directory', required=True)
args = parser.parse_args()
from Bio import Entrez
-Entrez.email = 'another_email@gmail.com'
+Entrez.email = 'another_email@gmail.com' # FIXME
import xml.etree.ElementTree as ET
import json
@@ -27,140 +28,87 @@ from datetime import date, datetime
from dateutil.parser import parse
import sys
-sys.path.append('../')
+# sys.path.append('../')
from utils import is_integer, chunks, check_and_get_ontology_dictionaries
-
-num_ids_for_request = 100
+num_ids_for_request = 100 # batch calls
min_acceptable_collection_date = datetime(2019, 12, 1)
-dir_metadata = 'metadata_from_nuccore'
-dir_fasta_and_yaml = 'fasta_and_yaml'
-dir_dict_ontology_standardization = args.dict_ontology
+outdir = args.outdir
today_date = date.today().strftime("%Y.%m.%d")
path_ncbi_virus_accession = 'sequences.{}.acc'.format(today_date)
+if not os.path.exists(outdir):
+ raise Exception(f"Output directory {outdir} does not exist!")
-field_to_term_to_uri_dict = check_and_get_ontology_dictionaries(dir_dict_ontology_standardization)
-
-
-if os.path.exists(dir_metadata):
- print("The directory '{}' already exists.".format(dir_metadata))
-
- if not args.skip_request:
- print("\tTo start the request, delete the directory '{}' or specify --skip-request.".format(dir_metadata))
- sys.exit(-1)
-
-
-accession_to_ignore_set = set()
-
-if args.ids_to_ignore:
- if not os.path.exists(args.ids_to_ignore):
- print("\tThe '{}' file doesn't exist.".format(args.ids_to_ignore))
- sys.exit(-1)
-
- with open(args.ids_to_ignore) as f:
- accession_to_ignore_set.update(set([x.split('.')[0] for x in f.read().strip('\n').split('\n')]))
-
- print('There are {} accessions to ignore.'.format(len(accession_to_ignore_set)))
+skip = set()
+if args.skip:
+ with open(args.skip) as f:
+ content = f.readlines()
+ for line in content:
+ skip.add(line.strip())
-
-# ----------------------------------------------------------------------
-"""
-With --only-missing-ids only download accessions that we do not yet have!
-"""
-accession_already_downloaded_set = set()
-
-if os.path.exists(dir_fasta_and_yaml):
- """
- If the fasta_and_yaml directory exists and --only-missing-ids was set
- we make a list of all downloaded accessions:
- """
- print("The directory '{}' already exists.".format(dir_fasta_and_yaml))
- if not args.only_missing_ids:
- print("To start the download, delete the directory '{}' or specify --only-missing-ids.".format(dir_fasta_and_yaml))
- sys.exit(-1)
-
- """
- Fetch all YAML filenames and load `accession_already_downloaded_set`
- """
- accession_already_downloaded_set = set([x.split('.yaml')[0].split('.')[0] for x in os.listdir(dir_fasta_and_yaml) if x.endswith('.yaml')])
- print('There are {} accessions already downloaded.'.format(len(accession_already_downloaded_set)))
-
-accession_to_ignore_set.update(accession_already_downloaded_set)
-
-# ----------------------------------------------------------------------
-"""
-Check for --ids-to-consider
-"""
-accession_to_consider_set = set()
-
-if args.ids_to_consider:
- if not os.path.exists(args.ids_to_consider):
- print("\tThe '{}' file doesn't exist.".format(args.ids_to_consider))
- sys.exit(-1)
-
- with open(args.ids_to_consider) as f:
- accession_to_consider_set.update(set([x.split('.')[0] for x in f.read().strip('\n').split('\n')]))
-
- if len(accession_to_consider_set) > 0:
- print('There are {} accessions to consider.'.format(len(accession_to_consider_set)))
+print(f"Skip size is {len(skip)}",file=sys.stderr)
# ----------------------------------------------------------------------
"""
Download section for genbank XML
"""
-if not os.path.exists(dir_metadata):
- # Take all the ids
- id_set = set()
-
- # Try to search several strings
- term_list = ['SARS-CoV-2', 'SARS-CoV2', 'SARS CoV2', 'SARSCoV2', 'txid2697049[Organism]']
- for term in term_list:
- tmp_list = Entrez.read(
- Entrez.esearch(db='nuccore', term=term, idtype='acc', retmax='10000')
- )['IdList']
-
- # Remove mRNAs, ncRNAs, Proteins, and predicted models (more information here: https://en.wikipedia.org/wiki/RefSeq)
- # Remove the version in the id
- new_ids_set = set([x.split('.')[0] for x in tmp_list if x[:2] not in ['NM', 'NR', 'NP', 'XM', 'XR', 'XP', 'WP']])
-
- if len(accession_to_consider_set) > 0:
- new_ids_set = new_ids_set.intersection(accession_to_consider_set)
-
- new_ids = len(new_ids_set.difference(id_set))
- id_set.update(new_ids_set)
-
- print('Term:', term, '-->', new_ids, 'new IDs from', len(tmp_list), '---> Total unique IDs:', len(id_set))
-
- if not os.path.exists(path_ncbi_virus_accession):
- r = requests.get('https://www.ncbi.nlm.nih.gov/genomes/VirusVariation/vvsearch2/?q=*:*&fq=%7B!tag=SeqType_s%7DSeqType_s:(%22Nucleotide%22)&fq=VirusLineageId_ss:(2697049)&cmd=download&sort=SourceDB_s%20desc,CreateDate_dt%20desc,id%20asc&dlfmt=acc&fl=id')
- with open(path_ncbi_virus_accession, 'w') as fw:
- fw.write(r.text)
-
- with open(path_ncbi_virus_accession) as f:
- tmp_list = [line.strip('\n') for line in f]
-
- new_ids_set = set(tmp_list)
- if len(accession_to_consider_set) > 0:
- new_ids_set = new_ids_set.intersection(accession_to_consider_set)
-
- new_ids = len(new_ids_set.difference(id_set))
- id_set.update(new_ids_set)
-
- print('DB: NCBI Virus', today_date, '-->', new_ids, 'new IDs from', len(tmp_list), '---> Total unique IDs:', len(id_set))
-
- id_set = id_set.difference(accession_to_ignore_set)
- print('There are {} missing IDs to download.'.format(len(id_set)))
-
- os.makedirs(dir_metadata)
- for i, id_x_list in enumerate(chunks(list(id_set), num_ids_for_request)):
- path_metadata_xxx_xml = os.path.join(dir_metadata, 'metadata_{}.xml'.format(i))
- print('Requesting {} ids --> {}'.format(len(id_x_list), path_metadata_xxx_xml))
-
- with open(path_metadata_xxx_xml, 'w') as fw:
- fw.write(
- Entrez.efetch(db='nuccore', id=id_x_list, retmode='xml').read()
- )
+# Try to search several strings
+TERMS = ['SARS-CoV-2', 'SARS-CoV2', 'SARS CoV2', 'SARSCoV2', 'txid2697049[Organism]']
+# Remove mRNAs, ncRNAs, Proteins, and predicted models (more information here: https://en.wikipedia.org/wiki/RefSeq) starting with
+PREFIX = ['NM', 'NR', 'NP', 'XM', 'XR', 'XP', 'WP']
+
+ids = set()
+for term in TERMS:
+ num_read = BATCH_SIZE
+ retstart = 0
+ while num_read == BATCH_SIZE:
+ record = Entrez.read(
+ Entrez.esearch(db='nuccore', term=term, idtype='acc',
+ retstart=retstart, retmax=BATCH_SIZE)
+ )
+ idlist = record['IdList']
+ new_ids = set(idlist)
+ num_read = len(new_ids)
+ print(num_read,":",idlist[0],file=sys.stderr)
+ retstart += num_read
+ new_ids.difference_update(skip) # remove skip ids
+ new_ids = set([id for id in new_ids if id[:2] not in PREFIX])
+ ids.update(new_ids) # add to total set
+ print(f"Term: {term} --> #{len(new_ids)} new IDs ---> Total unique IDs #{len(ids)})",file=sys.stderr)
+ if args.max and len(ids) > args.max:
+ print(f"Stopping past #{args.max} items",file=sys.stderr)
+ break
+
+for id in ids:
+ print(id)
+
+sys.exit(2)
+
+with open(path_ncbi_virus_accession) as f:
+ tmp_list = [line.strip('\n') for line in f]
+
+new_ids_set = set(tmp_list)
+if len(accession_to_consider_set) > 0:
+ new_ids_set = new_ids_set.intersection(accession_to_consider_set)
+
+new_ids = len(new_ids_set.difference(id_set))
+id_set.update(new_ids_set)
+
+print('DB: NCBI Virus', today_date, '-->', new_ids, 'new IDs from', len(tmp_list), '---> Total unique IDs:', len(id_set))
+
+id_set = id_set.difference(accession_to_ignore_set)
+print('There are {} missing IDs to download.'.format(len(id_set)))
+
+os.makedirs(outdir)
+for i, id_x_list in enumerate(chunks(list(id_set), num_ids_for_request)):
+ path_metadata_xxx_xml = os.path.join(outdir, 'metadata_{}.xml'.format(i))
+ print('Requesting {} ids --> {}'.format(len(id_x_list), path_metadata_xxx_xml))
+
+ with open(path_metadata_xxx_xml, 'w') as fw:
+ fw.write(
+ Entrez.efetch(db='nuccore', id=id_x_list, retmode='xml').read()
+ )