/
multiSub
executable file
·1951 lines (1647 loc) · 71.9 KB
/
multiSub
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# tested on python2.7 and python3.6 (only 'up-gisaid' requires python3.5)
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
# Written by Maximilian Haeussler, maxh@ucsc.edu, with a lot of input from
# Kyanoush Yahosseini, RKI, for the ENA API uploader and Danny Park, Broad for the
# NCBI uploaders
import logging, sys, optparse, os, io, json, csv, zipfile, textwrap, subprocess
from collections import defaultdict, OrderedDict
from os.path import join, basename, dirname, isfile, isdir, expanduser
from datetime import datetime
from io import StringIO # python2.6 and 3
# the packages requests, urllib.requests, ftplib and xlrd are imported within the script, to
# improve startup time and also lower the dependency footprint of the basic operations
isPy2 = (sys.version_info.major == 2)
# all possible values for the --format option
allFmts = ["ncbi", "ncbi-ftp", "gisaid", "ena", "biosample"]
# when importing csv/tsv/xls files, use the following translation table to our internal annotation format
# I use NCBI's source tag definition for now for the internal storage
metaFieldMap = {
# common typos
"seqId" : "Sequence_ID",
"SequenceId" : "Sequence_ID",
"sequence_id " : "Sequence_ID",
"sequence-id " : "Sequence_ID",
"date" : "collection_date", # we have code to reformat and check this field, see checkDate()
# for GISAID import
"covv_collection_date" : "collection_date", # +special code for checking the format, see checkDate()
"covv_virus_name" : "isolate", # special code: fixupIsolate()
"covv_location" : "country", # special code -> fixupGisaidCountry()
"covv_assembly_method" : "Assembly Method",
"covv_coverage" : "Genome Coverage",
"covv_seq_technology" : "Sequencing Technology"
}
# these fields must be present after the metaFieldMap has been applied
reqFields = ["isolate", "collection_date"]
# mini config, these values are only there so the script can run without a config file
# again this is done to keep the dependencies of the basic features to a single file
config = {
# three-letter country abbreviation, for ICTV isolate names, e.g. FRA
"country" : "USA",
# full name of country/town, e.g. "France: Paris",
# see https://www.ncbi.nlm.nih.gov/genbank/collab/country/
"ncbiCountry" : "USA: Santa Cruz, CA",
# common or scientific name of host
"ncbi-host" : "human",
"ncbi-genome" : "SARS-CoV-2",
# please do not change these values here, run "multiSub init" and change the values in
# ~/.multiSub/config
# default NCBI biosamples attributes
"host" : "Homo sapiens",
"host_disease" : "COVID-19",
#"attribute_package" : "Pathogen.cl", # not optimal, as it requires lat_lon, now they have a better package
"attribute_package" : "SARS-CoV-2.cl.1.0",
"organism" : "Severe acute respiratory syndrome coronavirus 2",
# dummy values, please please run "multiSub init" and replace in ~/.multiSub/config
"collected_by" : "UCSC Molecular Diagnostics Lab",
"isolation_source" : "unknown",
# file generation does not trigger an error.
# overwritten by ~/.multiSub/config, these ENA dummy values are only there so the script can run
# without a config file
"enaCenter" : "UCSC Genomics Institute",
"enaCollector" : "UCSC Medical Diagnostics Lab",
"enaCollInst" : "",
"enaCountry" : "USA",
"enaRegion" : "CA",
"enaHost" : "human",
# bogus values:
# overwritten by ~/.multiSub/config, these bogus values are only there so the script can run
# without a config file
# for the GISAID file
"gisaidUser" : "gisaidTest",
"gisaidLocation" : "North America / USA / California / Santa Cruz",
"gisaid_host" : "Human",
"gisaid_technology" : "Illumina NextSeq 550",
"gisaid_assembly_method" : "",
"gisaid_orig_lab" : "UCSC Genomics Institute",
"gisaid_orig_lab_addr" : "1156 High Street. Santa Cruz, CA 95064",
# for the NCBI Submission XML file
"ncbiUser" : "testUser",
"contact" : ("Doe", "John", "D"),
"email" : "test@test.com",
"phone" : "",
"authors" : [
# format: (lastname, firstname, middle initial)
("Haussler","David", ""),
("Haeussler","Max", ""),
],
"affiliation" : {
"affil" : "University of California, Santa Cruz",
"div" : "Genomics Institute",
"city" : "Santa Cruz",
"sub" : "CA",
"country" : "USA",
"street" : "1156 High Street, MS Genomics Institute",
"postal-code" : "95064"
}
}
# the first line of all GISAID csv files, from the GISAID docs
GISAIDHEADERS = u"submitter,fn,covv_virus_name,covv_type,covv_passage,covv_collection_date,covv_location,covv_add_location,covv_host,covv_add_host_info,covv_gender,covv_patient_age,covv_patient_status,covv_specimen,covv_outbreak,covv_last_vaccinated,covv_treatment,covv_seq_technology,covv_assembly_method,covv_coverage,covv_orig_lab,covv_orig_lab_addr,covv_provider_sample_id,covv_subm_lab,covv_subm_lab_addr,covv_subm_sample_id,covv_authors"
# alternative format, also seen in the wild
GISAIDHEADERS2 = GISAIDHEADERS+",covv_comment,comment_type"
# all possible NCBI source tags
# see https://www.ncbi.nlm.nih.gov/WebSub/html/help/genbank-source-table.html#modifiers
allSourceTags = set("isolate,strain,specimen_voucher,bio_material,biotype,cell_line,cell_type,dev_stage,ecotype,forma,fwd_primer_name,fwd_primer_seq,lat_lon,identified_by,lab_host,note,pop_variant,serogroup,segment,serotype,sex,speximen_voucher,sub_species,subtype,substrain,tissue_type,type,variety,collection_date,country,collected_by,isolation_source,organism,host,BioProject,BioSample,db_xref,note".split(","))
# all possible NCBI structured comments tags
commentTags = set(["Assembly Name", "Assembly Method", "Genome Coverage", "Sequencing Technology"])
# required biosample fields
reqBiosFields = ["organism", "collected_by", "collection_date", "geo_loc_name", "host",
"host_disease", "isolate", "isolation_source"]
# all possible biosample fields
# copied from the template that you can download when submitting a biosample as a bulk .tsv file
# first field is always "sample_name"
allBioFields ="sample_title","bioproject_accession","organism","collected_by","collection_date","geo_loc_name","host","host_disease","isolate","isolation_source","antiviral_treatment_agent","collection_device","collection_method","date_of_prior_antiviral_treat","date_of_prior_sars_cov_2_infection","date_of_sars_cov_2_vaccination","exposure_event","geo_loc_exposure","gisaid_accession","gisaid_virus_name","host_age","host_anatomical_material","host_anatomical_part","host_body_product","host_disease_outcome","host_health_state","host_recent_travel_loc","host_recent_travel_return_date","host_sex","host_specimen_voucher","host_subject_id","lat_lon","passage_method","passage_number","prior_sars_cov_2_antiviral_treat","prior_sars_cov_2_infection","prior_sars_cov_2_vaccination","purpose_of_sampling","purpose_of_sequencing","sars_cov_2_diag_gene_name_1","sars_cov_2_diag_gene_name_2","sars_cov_2_diag_pcr_ct_value_1","sars_cov_2_diag_pcr_ct_value_2","sequenced_by","vaccine_received","virus_isolate_of_prior_infection","description"
# all required SRA fields
# from ftp://ftp-trace.ncbi.nlm.nih.gov/sra/metadata_table/SRA_metadata_acc.tsv
# and from https://www.ncbi.nlm.nih.gov/core/assets/sra/files/SRA_metadata_SP.xlsx
# also here: https://github.com/benjaminhgood/LTEE-metagenomic/blob/master/generate_sra_metadata.py
# any other fields can be added. They appear under "run" (says above .tsv)
# in addition to these, any fields filename, filename2, filename3, filename4, etc can be added
# at least 'filename' has to be defined and not empty
sraFields = ["bioproject_accession", "biosample_accession", "library_ID", "title", "library_strategy", "library_source", "library_selection", "library_layout", "platform", "instrument_model", "design_description", "filetype"]
configDone = False
# URL to download the 'init' config file
configUrl = "https://raw.githubusercontent.com/maximilianh/multiSub/main/config.sample"
def getConfigFname(fname):
" return full path to file in config dir "
homeDir = os.path.expanduser('~')
cfgDir = join(homeDir, ".multiSub")
return join(cfgDir, fname)
def getConfig():
" return config as dict "
global config
global configDone
global metaFieldMap
if not configDone:
cfgFname = getConfigFname("config")
if isfile(cfgFname):
exec(io.open(cfgFname).read(), config)
else:
logging.info("%s does not exist. Using default values. "\
"Please run 'multiSub init' and then edit the config file to your needs" % cfgFname)
configDone = True
if "metaFieldMap" in config:
metaFieldMap.update(config["metaFieldMap"])
return config
# ==== functions =====
def parseArgs():
" setup logging, parse command line arguments and options. -h shows auto-generated help page "
parser = optparse.OptionParser("""usage: %prog [options] [command] [arguments]- prepare genbank submission file
Commands:
init - write an empty config template to ~/.multiSub/config
conv faFname tsvFname outDir - converts a fasta + tsv/csv/xls to files in outDir
convDir inDir outDir - converts all fa/tsv/csv/xls files in inDir to outDir
up-biosample outDir - upload genbank.xml in outDir to NCBI Biosamples
up-genbank outDir - upload genbank.zip/genbank.xml in outDir to NCBI Genbank
down-biosample outDir - download NCBI status messages to outDir and parse accessions
down-genbank outDir - download NCBI status messages to outDir and parse accessions
up-ena outDir - upload the file ena.xml+seqs in outDir to ENA, write receipt to outDir
up-gisaid outDir - upload the files gisaid.* in outDir to GISAID
Examples:
multiSub init - create ~/multiSub/config and fill with default values
multiSub conv seqs.fa seqs.tsv mySub - convert fasta+tsv to all formats (ENA,NCBI,GISAID) in mySub/
multiSub convDir mySeqs mySub - convert all fasta/tsv/csv/xls to mySub in ENA format
multiSub up-biosample mySub - upload biosample.xml mySub to NCBI's FTP server as test submission
multiSub up-biosample mySub --prod - like above, but as a real submission
multiSub down-biosample mySub --prod - download submission results, parse accessions to biosampleAccs.tsv
multiSub convDir mySeqs mySub - convert again, now adding the biosample accessions
multiSub up-genbank mySub - upload to NCBI FTP as a Genbank test
multiSub down-genbank mySub - retrieve status reports to mySub/report.xml
multiSub up-genbank mySub --prod - upload to NCBI FTP as a real Genbank submission
multiSub down-genbank mySub --prod - download NCBI status files and create genbankAccs.tsv
multiSub convDir mySeqs mySub -f ena - convert all fasta/tsv/csv/xls to mySub in ENA format
multiSub up-ena mySub --prod - upload ENA files in mySub to ENA server as final submission
multiSub up-gisaid mySub - upload GISAID files in mySub to GISAID server as a final submission
""")
parser.add_option("-d", "--debug", dest="debug",
action="store_true", help="show debug messages")
parser.add_option("-s", "--skip", dest="skipFile",
action="store", help="file with at least one column with the sequence "
"identifier of sequences to remove. Can be the raw NCBI error report text file. These "
"sequences and their annotations will be skipped during the convert step.")
parser.add_option("-a", "--accs", dest="accFiles",
action="append", help="File with accessions. Can be in biosample tsv format. parsed fields are 'sample_name' or 'isolate' and 'accession'. Can be used multiple times (e.g. to provide one GISAID file and also the Biosamples file)")
parser.add_option("-f", "--format", dest="format", action="store",
default="all",
help="comma-separated list of output formats to generate. Can be: %s or 'all'" % ",".join(allFmts))
parser.add_option("", "--prod", dest="prod", action="store_true", help="For up-ncbi and up-ena: use the Production upload server, not Testing")
parser.add_option("", "--prefix", dest="prefix", action="store", default="",
help="For conv/confDir/up-ena: a prefix for all internal ENA IDs. If you want to force a "
"re-upload of everything, set this to a random short string, and keep it the same "
"for the 'convert' and 'up-ena' steps.")
parser.add_option("", "--test", dest="test", action="store_true", help="run tests")
(options, args) = parser.parse_args()
if options.test:
import doctest
doctest.testmod()
sys.exit(1)
if args==[]:
parser.print_help()
exit(1)
if options.debug:
logging.basicConfig(level=logging.DEBUG)
logging.getLogger().setLevel(logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
logging.getLogger().setLevel(logging.INFO)
return args, options
# ----------- main --------------
def openFile(fname, mode="rt"):
""" opens file, recognizing stdout and stdin and none"""
if hasattr(fname, "read") or hasattr(fname, "write"):
return fname
elif fname.endswith(".gz"):
fh = gzip.open(fname, mode)
elif fname=="stdout":
fh = sys.stdout
elif fname=="stdin":
fh = sys.stdin
elif fname==None or fname.lower()=="none":
fh = None
else:
fh = io.open(fname, mode)
return fh
def parseFastaId(line):
" return sequence ID given fasta seq Id line "
seqId=line.strip(">").strip()
if "|" in seqId:
seqId = seqId.split("|")[0]
return seqId
def httpDownload(url, fname):
" download file via http to fname "
logging.info("Downloading %s to %s" % (url, fname))
try:
# py3
from urllib.request import urlretrieve
except:
# py2
from urllib import urlretrieve
urlretrieve (url, fname)
def parseFasta(fname):
""" Generator: yields sequences as tuple (id, sequence) """
logging.info("Reading fasta file %s" % fname)
if hasattr(fname, 'read'):
ifh = fname
elif fname=="stdin":
ifh=sys.stdin
elif fname.endswith(".gz"):
ifh=gzip.open(fname)
else:
ifh=io.open(fname, "rt", encoding="utf8")
seqLines = []
lastId = None
doneIds = set()
for line in ifh:
line = line.rstrip("\r\n")
if line=="" or line.startswith("#"):
continue
elif not line.startswith(">"):
seqLines.append(line.replace(" ","").strip())
continue
else:
if len(seqLines)!=0: # on first >, seq is empty
faseq = (lastId, "".join(seqLines))
lastId = parseFastaId(line)
seqLines = []
yield faseq
else:
if lastId!=None:
sys.stderr.write("warning: when reading fasta file: empty "
"sequence, id: %s\n" % line)
lastId = parseFastaId(line)
seqLines=[]
# if it's the last sequence in a file, loop will end on the last line
if len(seqLines)!=0:
faseq = (lastId, "".join(seqLines))
yield faseq
else:
yield (None, None)
def fixupIsolate(metaDict):
" convert various forms of isolate names to our internal format (NBCI) "
# NCBI format is: SARS-CoV-2/human/CHN/Wuhan_X1/2019
# SPHERES format is: US/CA-CDPH-S001/2020
# see https://github.com/CDCgov/SARS-CoV-2_Sequencing#sequence-naming-conventions-for-public-repositories
# convert from GISAID to NCBI format here
if not "isolate" in metaDict:
return
isolate = metaDict["isolate"]
isoParts = isolate.split("/")
isoParts = [i.strip() for i in isoParts] # remove whitespace
if len(isoParts)==1:
# just the identifier, e.g. CA-UCSC-252
country = getConfig()["country"]
identifier = isoParts[0]
date = metaDict["collection_date"]
year = date.split("-")[0]
elif len(isoParts)==4 and isoParts[0].lower()=="hcov-19":
# GISAID format is: hCoV-19/USA/CA-UCSC-252/2021
virus, country, identifier, year = isolate.split("/")
elif len(isoParts)==5 and isoParts[0]=="SARS-CoV-2":
# NCBI format is: SARS-CoV-2/human/CHN/Wuhan_X1/2019
virus, host, country, identifier, year = isolate.split("/")
elif len(isoParts)==3 and isoParts[0]=="US":
# SPHERES format is: US/CA-CDPH-S001/2020
country, identifier, year = gisaidIsolate.split("/")
else:
errAbort("Isolate format '%s' contains slashes but is not NCBI, GISAID or SPHERES format. "
"Extend fixupIsolate() in %s" % (isolate, __file__))
virus = "SARS-CoV-2"
newIso = "/".join((virus, "human", country, identifier, year))
metaDict["isolate"] = newIso
def fixupGisaidCountry(metaDict):
" fix up the 'country' attribute "
# example input: "North America / USA / California / Santa Cruz"
# example input: "North America / USA / Wisconsin"
# has to be: USA: Santa Cruz, CA
loc = metaDict["country"]
locParts = loc.split("/")
locParts = [l.strip() for l in locParts]
if len(locParts)==4:
country = locParts[1]+": "+locParts[3]+", "+locParts[2]
elif len(locParts)==3:
country = locParts[1]+": "+locParts[2]
else:
country = locParts[1]
metaDict["country"] = country
def readMetaGisaid(fname):
""" read meta data in GISAID format and convert to our internal dictionary:
meta[isolate] -> dict with date -> date. Only imported fields are:
covv_collection_date, covv_virus_name and covv_location. They are converted to the
fields: collection_date, isolate and country. 'location' is rewritten to
comply with NCBI rules. """
if fname.lower().endswith(".xls"):
headers, rows = parseTableXls(fname)
else:
headers, rows = parseTable(fname)
meta = OrderedDict()
seqIdIdx = headers.index("covv_virus_name")
for row in rows:
assert(len(headers)==len(row))
seqId = row[seqIdIdx]
seqMeta = OrderedDict()
seqMeta["Sequence_ID"] = seqId
seqMeta["isolate"] = seqId
for field, val in zip(headers, row):
# translate the field name:
# this is very different than the default readMetaText() function,
# because for GISAID, only the explicitly named fields from metaFieldMap are imported
if field in metaFieldMap:
if field=="covv_virus_name":
continue
newName = metaFieldMap[field]
if val.strip()!="":
seqMeta[newName] = val
# and run the fixup code
fixupIsolate(seqMeta)
fixupGisaidCountry(seqMeta)
meta[seqId] = seqMeta
return meta
def errAbort(msg):
logging.error(msg)
#sys.exit(1)
raise Exception(msg)
def checkDate(dateStr):
" throw error is date is not in format 2020-03-30 "
if "-" not in dateStr:
logging.warn("Found date '%s'. This is an accepted date for GISAID, but not for all other databases. Please consider updating your input files with proper dates. For public health purposes having at least the month is crucial. This script will set the date to June 1st of the same year now, but please fix the input data rather than creating incorrect dates." % dateStr)
dateStr = dateStr+"-06-01"
year, month, day = dateStr.split("-")
year = int(year.strip())
month = int(month.strip())
day = int(day.strip())
note = " Note that input date must look like 2019-12-30"
if not year > 2019:
errAbort(("Meta data row for '%s': year must be > 2019."+note) % seqId)
if not month > 0 and not month < 13 :
errAbort(("Meta data row for '%s': month must be > 0 and < 13."+note) % seqId)
if not day > 0 and not day <= 31 :
errAbort(("Meta data row for '%s': day must be > 0 and <= 31."+note) % seqId)
def checkMeta(meta):
" throw error if something is malformed in the meta data: no isolate or date tag or wrong date "
for seqId, m in meta.items():
if not "isolate" in m.keys():
errAbort("Meta data row for '%s' does not contain an 'isolate' field" % seqId)
if not "collection_date" in m:
errAbort("Meta data row for '%s' does not contain a 'collection_date' nor a 'date' field" % seqId)
else:
checkDate(m["collection_date"])
def checkAssembler(seqId, assembler):
" more weird NCBI requirements... "
if not "v." in assembler:
errAbort("The 'Assembly' value for %s is %s (possibly specified as ncbiAssembly in the config file). "
"But NCBI requires that the string 'v.' must be between the assembler name and its version. " %
(seqId, assembler))
def readMeta(fname):
""" read meta data in format csv, tsv or xls. return as dict with 'seqId'
-> OrderedDict of 'key':'value' Standardize field names to: date and
isolate
"""
if fname.endswith(".xls"):
meta = readMetaGisaid(fname)
else:
meta = readMetaText(fname)
return meta
def readMetaText(fname):
""" read csv/tsv table with sequence meta data and return as dict with 'seqId' -> OrderedDict of 'key':'value'
"""
# GISAID files can also be in .csv format
line1 = io.open(fname).readline().strip()
if line1.startswith("submitter,fn,covv_virus_name"):
logging.info("GISAID header line detected, using GISAID parser")
return readMetaGisaid(fname)
else:
logging.debug("No GISAID header line detected, using normal meta data parser")
headers, rows = parseTable(fname)
meta = dict()
lNo = 0
for row in rows:
lNo += 1
if len(row) != len(headers):
errAbort("Line %d: number of fields is not identical to number of header fields. "
"Headers are: %s, fields are %s" % (lNo, repr(row), repr(headers)))
d = OrderedDict()
for colIdx in range(0, len(headers)):
val = row[colIdx]
key = headers[colIdx]
if val.strip()!="":
d[key] = val
seqId = row[0]
if seqId in meta:
logging.warn("sequence ID '%s' has been seen before. Only read first row." % seqId)
continue
meta[seqId] = d
return meta
def parseTableXls(fname):
" like parseTable, but for xls files "
from xlrd import open_workbook # not found? install with 'pip install xlrd --user'
logging.info("Parsing xls file '%s'" % fname)
book = open_workbook(fname,on_demand=True)
sheet = book.sheet_by_index(1)
headers = [sheet.col_values(i)[0] for i in range(sheet.ncols) if sheet.col_values(i)[0]]
rows = []
for row_idx in range(2, sheet.nrows): # Iterate through rows
row = []
for cell in sheet.row(row_idx):
row.append(cell.value)
rows.append(row)
return headers, rows
def parseTable(fname):
" read csv or tsv, return (list headers, list of row-tuples) "
line1 = openFile(fname).readline()
if "\t" in line1:
sep = "\t"
ftype = "tsv"
else:
sep = ","
ftype = "csv"
logging.info("Parsing file '%s', detected filetype %s" % (fname, ftype))
headers = None
rows = []
with openFile(fname) as ifh:
# python's sniffer was too unreliable on real files
#sample = ifh.read(80)
#deduced_dialect = csv.Sniffer().sniff(sample)
#reader = csv.reader(ifh, dialect=deduced_dialect)
reader = csv.reader(ifh, delimiter=sep, quoting=csv.QUOTE_ALL)
for row in reader:
if isPy2:
row = [x.decode("utf8") for x in row]
if len(row)==1:
errAbort("file %s looks like it should use separator %s, but not more "
"than one field found. Is this a tsv file with a csv file extension "
"or the opposite? " % (fname, repr(sep)))
if headers is None:
if row[0].startswith("#"):
row[0] = row[0].lstrip("#")
headers = row
else:
if len(row)==0 or row[0]=="":
continue
rows.append(row)
return headers, rows
def trimSeq(seqId, seq):
""" remove initial and final Ns from seq, for Genbank
# Kyanoush wrote this in the RKI importer, this would be a lot easier:
#def clean_sequence(sequence):
#sequence = sequence.replace('-', 'N')
#if sequence[0] == 'N':
# sequence = re.sub('^N*', '', sequence)
#if sequence[len(sequence) - 1] == 'N':
# sequence = re.sub('N*$', '', sequence)
#return sequence
>>> trimSeq("test", "---ACTGNNN")
(6, 'ACTG')
>>> trimSeq("test", "nnnACTGNNN")
(6, 'ACTG')
>>> trimSeq("test", "NNNACTGNNN")
(6, 'ACTG')
>>> trimSeq("test", "ACTGN")
(1, 'ACTG')
>>> trimSeq("test", "NACTG")
(1, 'ACTG')
>>> trimSeq("test", "NNN")
(3, '')
"""
logging.debug("Trimming %s" % seqId)
lowSeq = seq.lower()
lowSeq = lowSeq.replace("-", "n") # is this a good idea ? do dashes appear in the input seqs?
trimCount = 0
startPos = 0
seqLen = len(lowSeq)
while startPos < seqLen and lowSeq[startPos]=="n":
startPos+=1
trimCount += 1
endPos = len(seq)-1
# special case: sequence is all Ns - should this trigger an error?
if trimCount==endPos+1:
return trimCount, ""
while lowSeq[endPos]=="n":
endPos-=1
trimCount += 1
if trimCount != 0:
logging.debug("Trimmed %d starting and %d ending nucleotides from seq %s "
"(total: %d)" % (startPos, len(seq)-endPos-1, seqId, trimCount))
return trimCount, seq[startPos:endPos+1]
def writeFasta(seqs, ofh):
" write list of (id, seq) to ofh "
outCount = 0
for seqId, seq in seqs:
ofh.write(u">")
ofh.write(seqId)
ofh.write(u"\n")
lines = [seq[i:i + 60] for i in range(0, len(seq), 60)]
ofh.write("\n".join(lines))
ofh.write(u"\n")
outCount += 1
if "name" in dir(ofh): # ofh can be a memory-backed pseudo file, those don't have names
logging.info("Wrote %d sequences to %s" % (outCount, ofh.name))
def writeMetaTsv(meta, ofh):
" write meta information to a tsv file. Assume that all meta keys are identical. "
# get a list of all headers, in all meta dictionaries
allHeaderSet = set()
allHeaders = []
for seqId, metaDict in meta.items():
keys = metaDict.keys()
missing = set(keys) - allHeaderSet
if len(missing)!=0:
for k in keys:
if k not in allHeaders:
allHeaders.append(k)
allHeaderSet.update(missing)
ofh.write(u"\t".join(allHeaders))
ofh.write(u"\n")
for seqId, metaDict in meta.items():
#assert(headers==metaDict.keys())
vals = []
for h in allHeaders:
vals.append(metaDict.get(h, ""))
ofh.write(u"\t".join(vals))
ofh.write(u"\n")
def addAccs(seqId, seqMeta, accs):
""" accs is a dict with isolate or sequence ID -> list of accessions. Add these to seqMeta, is possible """
seqAccs = []
if seqMeta["isolate"] in accs:
seqAccs.extend(accs[seqMeta["isolate"]])
if seqId in accs:
seqAccs.extend(accs[seqId])
for acc in seqAccs:
if acc.startswith("EPI_"):
seqMeta["gisaid_accession"] = acc
elif acc.startswith("SAM"): # SAME is ENA, SAMN is NCBI
seqMeta["biosample_accession"] = acc
else:
assert(False) # accession format was not recognized
return seqMeta
def metaTransform(meta, accs):
""" convert meta data to a standard format, return as 'seqId' -> dict of 'key:'value'.
"""
# See https://submit.ncbi.nlm.nih.gov/sarscov2/genbank/
# isolation-source is not required, so we don't create it
# on country, see https://www.ncbi.nlm.nih.gov/genbank/collab/country/
# on the other fields, see https://submit.ncbi.nlm.nih.gov/biosample/template/?organism-organism_name=SARS-CoV-2&organism-taxonomy_id=&package-0=SARS-CoV-2.cl.1.0&action=definition
cf = getConfig()
newMeta = dict()
for seqId, seqMeta in meta.items():
newSeqMeta = OrderedDict()
for key, val in seqMeta.items():
if key in metaFieldMap:
key = metaFieldMap.get(key, key)
newSeqMeta[key] = val.strip()
# if there is no isolate field, use the sequence ID
if "isolate" not in newSeqMeta:
newSeqMeta["isolate"] = seqId
# check that the required fields are there - cannot be made in checkBoth(), as the fixers
# need them
for field in reqFields:
if field not in newSeqMeta or newSeqMeta[field]=="":
errAbort("meta data, row '%s': Field %s does not exist or is empty" % (seqId, field))
fixupIsolate(newSeqMeta)
addAccs(seqId, newSeqMeta, accs)
newMeta[seqId] = newSeqMeta
return newMeta
def makeGenbankTagSeqs(seqs, meta):
""" merge meta data into seq IDs as []-tags and return a list of (seqId,
seq)
"""
trimSeqCount = 0
newSeqs = []
for seqId, seq in seqs:
trimCount, seq = trimSeq(seqId, seq)
if trimCount != 0:
trimSeqCount += 1
seqMeta = meta.get(seqId)
if seqMeta is None:
logging.error("Skipping fasta sequence with ID %s - cannot find it "
"in the annotation table" % repr(seqId))
continue
isolate = seqMeta["isolate"]
title = "Severe acute respiratory syndrome coronavirus 2 " \
"isolate %s, complete genome" % isolate
tagsStrs = []
for key, val in seqMeta.items():
if key == "Sequence_ID":
continue
tagsStrs.append("["+key+"="+val+"]")
tagStr = " ".join(tagsStrs)
seqId = "%s %s %s" % (seqId, tagStr, title)
newSeqs.append( (seqId, seq) )
return newSeqs
logging.info("Trimmed starting/ending N-letters from %d sequences" % trimSeqCount)
def writeGenbankTagFa(seqs, meta, gbOutFname):
""" write sequences to genbank for interactive submission, a single fasta file
This format saves the annotations directly into the fasta file, so
you need to upload only a single file.
"""
gbSeqs = makeGenbankTagSeqs(seqs, meta)
with io.open(gbOutFname, "wt") as ofh:
writeFasta(gbSeqs, ofh)
def filterBoth(skipFile, seqs, meta):
" parse first column from skipFile and remove these seqs and their annotations "
headers, rows = parseTable(skipFile)
skipIds = set()
for row in rows:
skipIds.add( row[0] )
logging.info("Read %d sequence IDs from file %s to skip" % (len(skipIds), skipFile))
newSeqs = []
skippedSeqs = []
skipSeqCount = 0
skipAnnotCount = 0
for seqId, seq in seqs:
if seqId in skipIds:
skipSeqCount +=1
skippedSeqs.append ( (seqId, seq) )
else:
newSeqs.append ( (seqId, seq) )
newMeta = {}
skippedMeta = {}
for key, val in meta.items():
if key in skipIds:
skipAnnotCount += 1
skippedMeta[key] = val
else:
newMeta[key] = val
logging.info("Removed %d sequences and %d annotation rows" % (skipSeqCount, skipAnnotCount) )
logging.info("%d sequences and %d annotation rows remain" % (len(newSeqs), len(newMeta)) )
return newSeqs, newMeta, skippedSeqs, skippedMeta
def makeNamesAsn1(doClose):
"return ncbi templatestring for authors "
cfg = getConfig()
strs = []
for au in cfg["authors"]:
strs.append("""
{
name name {
last "%s",
first "%s",
middle "%s",
initials "",
suffix "",
title ""
}
}""" % (au[0], au[1], au[2]))
nameStr = ",\n".join(strs)
prefix = """
authors {
names std {
"""
if doClose:
suffix = """
}
},
"""
else:
suffix = """
},
"""
auStr = prefix + nameStr + suffix
return auStr
def makeTemplate():
" make genbank ASN.1 submission template and return as string "
# a much easier way to do this would be to ask the user to
# make a template with https://submit.ncbi.nlm.nih.gov/genbank/template/submission/
# and put it into ~/.multiSub/template ...
cf = getConfig()
if "ncbiTemplateFile" in cf:
return io.open(cf["ncbiTemplateFile"], "rt").read()
last = cf["contact"][0]
first = cf["contact"][1]
middle = cf["contact"][2]
email = cf["email"]
phone = cf["phone"]
altEmail = email
if "altEmail" in cf:
altEmail = cf["altEmail"]
af = cf["affiliation"]
afUni = af["affil"]
afDiv = af["div"]
afCity = af["city"]
afSub = af["sub"]
afCountry = af["country"]
afStreet = af["street"]
afPostal = af["postal-code"]
authorBlock1 = makeNamesAsn1(True)
authorBlock2 = makeNamesAsn1(False)
templ = """Submit-block ::= {
contact {
contact {
name name {
last "%(last)s",
first "%(first)s",
middle "%(middle)s",
initials "",
suffix "",
title ""
},
affil std {
affil "%(afUni)s",
div "%(afDiv)s",
city "%(afCity)s",
sub "%(afSub)s",
country "%(afCountry)s",
street "%(afStreet)s",
email "%(email)s",
phone "%(phone)s",
postal-code "%(afPostal)s"
}
}
},
cit {
%(authorBlock2)s
affil std {
affil "%(afUni)s",
div "%(afDiv)s",
city "%(afCity)s",
sub "%(afSub)s",
country "%(afCountry)s",
street "%(afStreet)s",
postal-code "%(afPostal)s"
}
}
},
subtype new
}
Seqdesc ::= pub {
pub {
gen {
cit "unpublished",
%(authorBlock1)s
title "Direct Submission"
}
}
}
Seqdesc ::= user {
type str "Submission",
data {
{
label str "AdditionalComment",
data str "ALT EMAIL:%(altEmail)s"
}
}
}
Seqdesc ::= user {
type str "Submission",
data {
{
label str "AdditionalComment",
data str "Submission Title:None"
}
}
} """ % locals()
return templ
def now():
"returns current time in isoformat, only seconds "
s = datetime.isoformat(datetime.now(), sep="_").split(".")[0].replace(":", "")
return s
def makeSubXmlDesc(ncbiUser):
" return the NCBI submission.xmls desc header "
xml = u"""<?xml version="1.0"?>
<Submission>
<Description>
<Title>multiSub automated submission</Title>
<Comment>SARS-CoV-2 test submission</Comment>
<Organization type="center" role="owner">
<Name>%(ncbiUser)s</Name>
</Organization>
</Description>
""" % locals()
return xml
def makeGenbankSubXml():
" generate a ncbi submission.xml file "
# I am not using release dates:
# <Hold release_date="2024-05-25"/>
c = getConfig()
ncbiUser = c["ncbiUser"]
uniqueId = now()
xml = makeSubXmlDesc(ncbiUser) + """
<Action>
<AddFiles target_db="GenBank">
<File file_path="genbank.zip">
<DataType>genbank-submission-package</DataType>
</File>
<Attribute name="wizard">BankIt_SARSCoV2_api</Attribute>
<Attribute name="auto_remove_failed_seqs">yes</Attribute>
<Identifier>
<SPUID spuid_namespace="ncbi-sarscov2-genbank">%(uniqueId)s</SPUID>
</Identifier>
</AddFiles>
</Action>
</Submission>
""" % locals()
return xml
def makeBiosampleSubXml(meta):
" generate a NCBI submission.xml file for biosamples "
cf = getConfig()
ncbiUser = cf["ncbiUser"]
uniqueId = now()
xmls = [makeSubXmlDesc(ncbiUser)]
for seqId, sampleMeta in meta.items():
# make sure an attribute_package is always present
if not "attribute_package" in sampleMeta:
sampleMeta["attribute_package"] = cf["attribute_package"]
if not "bioproject_accession" in sampleMeta:
sampleMeta["bioproject_accession"] = "" # this is just so we can generate the file without a config file
s = """
<Action>
<AddData target_db="BioSample">
<Data content_type="XML">
<XmlContent>
<BioSample schema_version="2.0">
<SampleId>
<SPUID spuid_namespace="ucsc-id">{isolate}</SPUID>
</SampleId>