/
pubPrepGeneDir
executable file
·1892 lines (1647 loc) · 74.7 KB
/
pubPrepGeneDir
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
# prepare the data for the mutation finder
# e.g. uniprot sequences, entrez mapping, etc
# in this file the prefix "up" always refers to "uniProt" not to the word "up" (like "down")
# load default python packages
from __future__ import print_function
import sys, logging, optparse, os, glob, shutil, gzip, collections, marshal, re, zlib, cPickle
import types, string, sqlite3
import struct, itertools, dumbdbm
import urllib, urllib2
import xml.etree.ElementTree as et
from os.path import *
from collections import defaultdict
from datetime import date
import bedLoci
import unidecode
# add <scriptDir>/lib/ to package search path
progFile = os.path.abspath(sys.argv[0])
progDir = os.path.dirname(progFile)
pubToolsLibDir = os.path.join(progDir, "lib")
sys.path.insert(0, pubToolsLibDir)
# now load our own libraries
import pubConf, pubGeneric, util, maxbio, maxCommon, pslMapBed, pubEutils, geneFinder
import pubKeyVal
from maxCommon import runCommand, makeOrCleanDir
from os.path import *
from pm_pycbio.hgdata import Psl
from Bio import SeqIO
import fastFind
# target directory for all variant information
varDataDir = pubConf.varDataDir
# files not needed by end users, only at UCSC for building
varBuildDir = pubConf.varBuildDir
DBSNPVERSION = "142"
# all possible commands for this script
allSteps = ["genePmids", "entrez", "refseq", "seqs",
"uniprot", "refseqMap", "uniprotMap", "snp",
"omim",
"geneNames", "geneDict",
"lociNames", "bandLoci",
"cells",
"accsGenbank", "accsUniprot", "accsPdb", "accsSts",
# not used anymore
"oldRefseqProtGet", "oldRefseqProtMap",
"oldRefseqGet", "oldRefseqMap",
"genbankProtGet", "genbankProtParse", "genbankProtMap",
]
genbankDir = "/hive/data/outside/genbank/data/download/genbank.208.0"
# === COMMAND LINE INTERFACE, OPTIONS AND HELP ===
parser = optparse.OptionParser("""usage: %prog [step] - reformat various gene-centric databases into tables or DBM filesfor gene/mutation finding or resolution.
Output goes to directory {}.
Possible steps are:
{}
For accession finding:
- geneNames: do the raw parsing of the entrez/hugo/uniprot databases
- lociNames: split hg19 into separate loci around exons and assign them to gene symbols
- bandLoci: get cytogenetic bands from hg19 and using lociNames, assign them to genes in them
- accsGenbank: parse genbank accession prefixes + digit lengths into text file
- accsUniprot: index uniprot accessions into sqlite db
- accsPdb: index pdb accessions into text file
For the gene dictionary:
- geneNames: do the raw parsing of the entrez/hugo/uniprot databases
- geneDict: disambiguate and filter the gene names and put into for fastFind
for the disambiguation and sequence lookup steps of the gene finder:
- genePmids: convert entrez genes pmid <-> gene table to a DBM database and marshal file
- entrez: table (entrezId, refSeqId, refSeqProtId) from entrez for human genes
- refseq: from genome browser hg19: table (protId, transId, cdsStart)
- uniprot: using uniprot, write a table that links entrezId, uniprotId and genbankIds (also marshal)
- genbankProtGet: get genbank sequences linked from human uniprot
- omim: get list of OMIM gene ids
- lociNames: split hg19 into separate loci around exons and assign them to gene symbols
- bandLoci: get cytogenetic bands from hg19 and using lociNames, assign them to genes in them
for variant finding and resolution:
- cells: get a list of cell names from cellosaurus, used as a blacklist for mutations
- snp: index dbSNP data, coord -> identifier and identifier -> coord
- refseqMap: get refSeq PSL for hg19
- seqs: load human refseq sequences into a DBM database
- entrez: table with entrezId,symbol,refseqProtIds,refseqIds,cdsStart
variant finding, but not necessary currently as they didn't improve the recall:
- uniprotMap: get uniprot -> genome PSL for hg19
- oldRefseqProtGet: map archived refseqProtIds to new Ids
- oldRefseqProtMap: get archived refseq prots -> genome PSL for hg19
- genbankProtParse: write sequences from genbankProtGet into a DBM db
- genbankProtMap: get genbank -> genome PSL for hg19
""".format(pubConf.geneDataDir, "|".join(allSteps)))
parser.add_option("-t", "--runTests", dest="test", action="store_true", help="run tests")
pubGeneric.addGeneralOptions(parser)
(options, args) = parser.parse_args()
# ==== FUNCTIONS =====
taxToDb = {9606 : "hg19"}
geneDataDir = None
# variation data base directory
varDataDir = pubConf.varDataDir
def writeGzDict(data, fname, appendFnames=None, toLower=False):
logging.info("Writing %d keys to %s" % (len(data), fname))
ofh = gzip.open(fname, "w")
for key, valList in data.iteritems():
for val in valList:
assert("|" not in val)
if toLower:
valList = [v.lower() for v in valList]
ofh.write("%s\t%s\n" % (key, "|".join(valList)))
if appendFnames:
for fn, prefix in appendFnames.iteritems():
logging.info("Appending %s to %s" % (fn, fname))
for line in open(fn):
ofh.write(prefix)
ofh.write(line)
ofh.close()
def getOmimGeneIds():
"""
return list of omim gene IDs
"""
tmpFname = join(geneDataDir, "omim.genemap2.tmp")
if not isfile(tmpFname):
#omimUrl = "ftp://grcf.jhmi.edu/OMIM/genemap2.txt"
omimUrl = pubConf.omimUrl
logging.info("Reading OMIM genemap from %s" % omimUrl)
data = urllib2.urlopen(omimUrl).read()
#data = open(omimUrl).read()
open(tmpFname, "w").write(data)
else:
data = open(tmpFname).read()
lines = data.splitlines()
geneIds = [int(l.split("|")[8]) for l in lines]
logging.info("Got %d omim gene IDs" % len(geneIds))
return geneIds
def appendToDict(data, idList, acc, stripVer=False, prefix=None):
" add an entry acc -> for all IDs in idList to data, which is a defaultdict of set"
assert(type(idList)==list)
for id in idList:
if stripVer:
id = id.split(".")[0]
if prefix:
id = prefix+id
#print id, acc
data[str(id)].add(str(acc))
def parseUniprotLinks(uniprotDir, taxId):
""" parse uniprot tab and return as dict.
keys of dict:
entrezToUp: entrezId -> upId
upToSym: upId -> symbol
upToIsos: upId -> list of sequence isoform IDs
upToGbs: upId -> list of gbank accessions
upToGbProts: upId -> list of protein gb accessions
upToRefseqProt: upId -> list of refseq protein IDs
accToUps: any accession -> list of uniprots.
versions are stripped from refseq and genbank, omim and entrez
are prefixd with "omim" and "entrez" to distinguish them
"""
tabFname = join(uniprotDir, "uniprot.tab")
logging.info("Parsing uniprot links from %s" % tabFname)
entrezToUp = {}
upToSym = {}
upToIsos = {}
upToGb = {}
upToGbProts = {}
upToRefseqProt = {}
upToRefseq = {}
accToUps = defaultdict(set)
gbToGbProt = {}
upToEntrez = {}
allOmimIds = set(getOmimGeneIds())
entrezCount = 0
duplCount = 0
u2eDuplCount =0
for row in maxCommon.iterTsvRows(tabFname, encoding=None):
acc = str(row.acc)
if int(row.taxonId)==taxId:
if row.geneName!="":
upToSym[acc] = str(row.geneName)
if row.hgncSym!="":
hugo = row.hgncSym.split(",")
appendToDict(accToUps, hugo, acc)
if row.ec!="":
ecIds = row.ec.split(",")
appendToDict(accToUps, ecIds, acc)
if row.refSeqProt!="":
refseqProtIds = row.refSeqProt.split("|")
upToRefseqProt.setdefault(row.acc, []).extend(refseqProtIds)
appendToDict(accToUps, refseqProtIds, acc, stripVer=True)
if row.refSeq!="":
refseqIds = row.refSeq.split("|")
upToRefseq.setdefault(row.acc, []).extend(refseqIds)
appendToDict(accToUps, refseqIds, acc, stripVer=True)
if row.pdb!="":
pdbIds = row.pdb.split("|")
appendToDict(accToUps, pdbIds, acc)
if row.ensemblGene!="":
ensIds = row.ensemblGene.split("|")
appendToDict(accToUps, ensIds, acc)
if row.ensemblProt!="":
ensIds = row.ensemblProt.split("|")
appendToDict(accToUps, ensIds, acc)
omimIds = None
if row.omimGene!="":
omimIds = row.omimGene.split("|")
appendToDict(accToUps, omimIds, acc, stripVer=True, prefix="omim")
if row.entrezGene!="":
ncbiGenes = row.entrezGene.split("|")
appendToDict(accToUps, ncbiGenes, acc, stripVer=True, prefix="entrez")
for ncbiGene in ncbiGenes:
ncbiGene = int(ncbiGene)
entrezCount += 1
if ncbiGene in entrezToUp:
duplCount +=1
entrezToUp.setdefault(ncbiGene, []).append(row.acc)
if row.acc in upToEntrez:
u2eDuplCount += 1
upToEntrez.setdefault(row.acc, []).append(int(ncbiGene))
if row.isoIds!="":
upToIsos.setdefault(row.acc, []).extend(row.isoIds.split("|"))
if row.emblMrna!="":
#emblIds = row.emblProt.split("|")
emblIds = row.emblMrna.split("|")
upToGb[row.acc] = emblIds
appendToDict(accToUps, emblIds, acc, stripVer=True)
if row.emblMrnaProt!="":
protIds = row.emblMrnaProt.split("|")
upToGbProts[row.acc] = protIds
#print protIds, emblIds
#print len(protIds), len(emblIds)
assert(len(protIds)==len(emblIds))
appendToDict(accToUps, protIds, acc, stripVer=True)
logging.info("%d entrez-uniprot links (cases with several uniprots for a gene rec: %d)" % \
(entrezCount, duplCount))
logging.info("%d uniprot-entrez links (cases with several genes for a up rec: %d)" % \
(len(upToEntrez), u2eDuplCount))
# convert id -> set to id->list
accToUpList = {}
for acc, upSet in accToUps.iteritems():
accToUpList[acc]=list(upSet)
data = {}
data["entrezToUp"] = entrezToUp
data["upToEntrez"] = upToEntrez
data["upToSym"] = upToSym
data["upToGbs"] = upToGb
data["upToGbProts"] = upToGbProts
data["upToIsos"] = upToIsos
data["upToRefseqProt"] = upToRefseqProt
data["upToRefseq"] = upToRefseq
data["accToUps"] = accToUpList
return data
def parseEntrezGeneRefseq(outFname):
" create a tab-sep file with human entrezGene, comma sep refseqIds, comma sep refseqProtIds"
fname = join(pubConf.ncbiGenesDir, "gene2refseq.gz")
logging.info("Parsing %s" % fname)
# parse refseq into dicts
refseqs = {}
refprots = {}
refsym = {}
for line in gzip.open(fname):
if not line.startswith("9606"):
continue
fs = line.strip("\n").split("\t")
if not fs[0]=="9606":
continue
#print fs
#if len(fs)<7:
# some genes have no refseq info
#continue
#Format: tax_id GeneID status RNA_nucleotide_accession.version RNA_nucleotide_gi protein_accession.version protein_gi genomic_nucleotide_accession.version genomic_nucleotide_gi start_position_on_the_genomic_accession end_position_on_the_genomic_accession orientation assembly mature_peptide_accession.version mature_peptide_gi Symbol (tab is used as a separator, pound sign - start of a comment)
tax, geneId, desc, refseqId, gir, refProtId, gip = fs[:7]
sym = fs[15]
if desc=="SUPPRESSED":
continue
if sym!="-":
refsym[int(geneId)] = sym
if refseqId!="-":
refseqs.setdefault(int(geneId), set()).add(refseqId)
if refProtId!="-":
refprots.setdefault(int(geneId), set()).add(refProtId)
# output dicts to tab sep file
logging.info("tab output...")
ofh = open(outFname, "w")
ofh.write("\t".join(["entrezId", "sym", "refseqIds", "refseqProtIds"]))
ofh.write("\n")
for geneId, refseqIds in refseqs.iteritems():
refseqProtIds = refprots.get(geneId, [])
sym = refsym.get(geneId, "")
row = [str(geneId), sym, ",".join(refseqIds), ",".join(refseqProtIds)]
ofh.write("\t".join(row))
ofh.write("\n")
ofh.close()
logging.info("Wrote %s" % outFname)
# write to marshal file
#outFname += ".marshal"
#data = {}
#data["entrez2refseqs"] = refseqs
#data["entrez2refprots"] = refprots
#data["entrez2sym"] = refsym
#marshal.dump(data, open(outFname, "w"))
#logging.info("Wrote %s" % outFname)
def parseEntrezGenePmids(taxIds, dbm):
" convert pmid <-> gene assignments from entrez genes to a dbm file "
pmid2geneFname = join(pubConf.ncbiGenesDir, "gene2pubmed.gz")
# at ucsc: /hive/data/outside/ncbi/genes/gene2pubmed.gz
logging.info("Parsing %s" % pmid2geneFname)
pmidToEntrez = {}
for line in gzip.open(pmid2geneFname):
if line.startswith("#"):
continue
row = line.rstrip("\n").split("\t")
rowTax, entrezId, pmid = row
if int(rowTax) in taxIds:
pmidToEntrez.setdefault(int(pmid), []).append(entrezId)
logging.info("Taxons %s: found entrez ids for %s pmids" % (taxIds, len(pmidToEntrez)))
logging.info("Writing to dbm file")
count = 0
#data = {}
for pmid, entrezList in pmidToEntrez.iteritems():
if count%10000==0:
print(count)
pmid = str(pmid)
entrezStr = ",".join(entrezList)
dbm[pmid] = entrezStr
#dbm2[pmid] = entrezStr
#data[int(pmid)] = entrezStr
count += 1
def faToDbm(faName, dbm):
logging.info("indexing %s into dbm as seqs" % faName)
faSizeOfh = open(faName+".size", "w")
logging.info("Loading %s" % faName)
for seqId, seq in maxbio.parseFasta(faName):
#dbm[seqId] = zlib.compress(seq)
dbm[seqId] = seq
#logging.info("Converted %s to dbm" % (faName))
def parseRaWriteToTab(raName, tabName):
" write refseqId.version, refProt ID and cds Start to a tabular file "
logging.info("Parsing ra")
ofh = open(tabName, "w")
ofh.write("refSeq\trefProt\tcdsStart\n")
id = None
cds = None
prt = None
data = {}
skipRec = False
skipCount = 0
accList = []
for line in open(raName):
if line.startswith("acc"):
id = line.rstrip("\n").split()[1]
continue
if line.startswith("ver"):
ver = line.rstrip("\n").split()[1]
continue
if line.startswith("prt"):
prt = line.rstrip("\n").split()[1]
continue
if line.startswith("cds"):
cds = line.rstrip("\n").split()[1].split(".")[0]
if "join" in line:
skipRec = True
continue
if line=="\n" and id!=None and cds!=None and prt!=None:
if skipRec:
skipCount += 1
else:
acc = id+"."+ver
row = [acc, prt, cds]
ofh.write("\t".join(row))
ofh.write("\n")
accList.append(acc)
id = None
cds = None
prt = None
skipRec = False
ofh.close()
logging.info("Wrote cds and pep/refseq assignment to %s" % tabName)
logging.info("Skipped %d records" % skipCount)
return accList
def makeOldToNewAccs(accs):
""" given a list of new things like NM_000325.5,
return dict with mapping old -> new, like
"NM_000325.4": "NM_000325.5", "NM_000325.3" : "NM_000325.5", etc.
"""
oldToNew = {}
for newAcc in accs:
prefix,suffix = newAcc.split(".")
version = int(suffix)-1
if version!=0:
oldVersions = range(0, version)
oldVersions = [ov+1 for ov in oldVersions]
for oldVersion in range(0, version):
oldVersion = oldVersion+1
oldAcc = prefix+"."+str(oldVersion)
oldToNew[oldAcc] = newAcc
return oldToNew
def parseRefseq(taxId, geneDataDir):
""" get prot <-> trans assignment and cdsStart for hg19 """
assert(taxId==9606)
raName = join(geneDataDir, "refseq.%s.ra" % str(taxId))
logging.info("Getting ra to %s" % raName)
cmd = "gbGetSeqs -gbRoot=/hive/data/outside/genbank RefSeq mrna %s -get=ra -db=hg19 -inclVersion -native" % raName
maxCommon.runCommand(cmd)
refseqInfoFname = join(geneDataDir, "refseqInfo.tab")
accList = parseRaWriteToTab(raName, refseqInfoFname)
os.remove(raName)
def getRefseqs(transFaName, protFaName):
" extract refseq sequences from UCSC genome browser database "
cmdTemp = "gbGetSeqs -gbRoot=/hive/data/outside/genbank RefSeq %s %s -db=hg19 -inclVersion"
for seqType, fname in [("mrna", transFaName), ("pep", protFaName)]:
logging.info("Getting data for %s" % seqType)
cmd = cmdTemp % (seqType, fname)
maxCommon.runCommand(cmd)
logging.info("Wrote fastas to %s and %s" % (transFaName, protFaName))
def loadSeqs(taxId, uniprotDir):
""" parse refseq sequences as values to sqlite file """
assert(taxId==9606)
# get old refseqs, too
#oldRefseqFname = join(geneDataDir, "oldRefseq.%s.gb")
#logging.info("Downloading old refseqs to %s" % oldRefseqFname)
#oldAccs = makeOldAccs(accList)
#outFh = open(oldRefseqFname, "w")
#chunkedDownloadFromEutils(oldAccs, outFh)
#outFh.write("\n".join(oldAccs[:1000]))
#assert(False)
# get fastas for refseq sequences
transFaName = join(varBuildDir, "refseq.%s.trans.fa" % str(taxId))
protFaName = join(varBuildDir, "refseq.%s.prot.fa" % str(taxId))
getRefseqs(transFaName, protFaName)
# index fastas
seqFname = join(pubConf.varDataDir, "seqs")
#upFaName = join(uniprotDir, "uniprot.%d.var.fa.gz" % taxId)
#gbFaName = join(varBuildDir, "genbank.%d.prot.fa" % taxId)
#oldRefseqFaName = join(varBuildDir, "oldRefseq.%d.prot.fa" % taxId)
db = pubKeyVal.SqliteKvDb(seqFname, singleProcess=True, newDb=True, \
tmpDir=pubConf.getFastTempDir(), onlyUnique=True)
#faToDbm(oldRefseqFaName, db)
#faToDbm(upFaName, db)
#faToDbm(gbFaName, db)
faToDbm(transFaName, db)
faToDbm(protFaName, db)
db.close()
#dbmFname = join(geneDataDir, "seqs.dbm")
#shutil.copy(dbmTmpFname, dbmFname)
#os.remove(dbmTmpFname)
logging.info("Finished writing all seqs to %s" % seqFname)
def writeUpRefseqPairs(taxId, uniprotDir, proteinType, pairFname):
" write a list of tuples uniprot-protein id, refseqId"
upTabFname = join(uniprotDir, "uniprot.tab")
ret = []
ofh = open(pairFname, "w")
upData = parseUniprotLinks(uniprotDir, taxId)
upToRefseq = upData["upToRefseq"]
if proteinType=="uniprot":
upToProts = upData["upToIsos"]
elif proteinType=="genbank":
upToProts = upData["upToGbProts"]
for upId, refseqIds in upToRefseq.iteritems():
for refseq in refseqIds:
for protId in upToProts.get(upId, []):
ofh.write("%s\t%s\n" % (protId, refseq))
ofh.close()
return ofh.name
def mapProtToRefseqIndex(taxId, protType, protFname, uniprotDir, stripVersion=False):
""" map from proteins given protein fa and pairs to refseq.
create psl and compressed dbm of psls
protType can be genbank or uniprot
"""
outPrefix = "%sToRefseq" % protType
tmpDir = join(pubConf.mapReduceTmpDir, "protRefseqMap-"+outPrefix)
makeOrCleanDir(tmpDir)
pairFname = join(tmpDir, "%s.%d.pairs" % (outPrefix, taxId))
writeUpRefseqPairs(taxId, uniprotDir, protType, pairFname)
dbmFname = join(varDataDir, "%s.%d" % (outPrefix, taxId))
mapFname = join(varBuildDir, "%s.%d.psl" % (outPrefix, taxId))
mapProtToRefseq(taxId, tmpDir, protFname)
filterPsls(tmpDir, pairFname, mapFname)
loadPslToDbm(mapFname, dbmFname, stripVersion=stripVersion)
def filterPsls(tmpDir, pairFname, mapFname):
""" pick the best alignment for each protein """
pslDir = join(tmpDir, "psl")
cmd = """ find %(pslDir)s -name '*.psl' | xargs cat | pslSelect -qtPairs=%(pairFname)s stdin stdout | sort -k 10,10 | pslCDnaFilter stdin -minQSize=20 -ignoreNs -globalNearBest=0 -bestOverlap -filterWeirdOverlapped stdout | sort | uniq > %(mapFname)s""" % locals()
runCommand(cmd)
logging.info("Wrote results to %s" % mapFname)
def mapDnaToRefseq(taxId, tmpDir, dnaFaName):
logging.debug("mapping %s to refseq, tmpdir %s" % (dnaFaName, tmpDir))
refseqFname = join(varBuildDir, "refseq.%s.trans.fa" % str(taxId))
targetFname = join(tmpDir, "target.fa")
logging.info("Copying %s to %s" % (refseqFname, targetFname))
shutil.copy(refseqFname, targetFname)
# split query into pieces
queryDir = join(tmpDir, "queries")
makeOrCleanDir(queryDir)
if dnaFaName.endswith(".gz"):
cmd = "gunzip %s -c | faSplit about stdin 500 %s/" % (dnaFaName, queryDir)
else:
cmd = "faSplit about %s 500 %s/" % (dnaFaName, queryDir)
maxCommon.runCommand(cmd)
pslDir = join(tmpDir, "psl")
makeOrCleanDir(pslDir)
jbl = open(join(tmpDir, "jobList"), "w")
logging.info("Created %s" % jbl.name)
faFnames = glob.glob(join(queryDir, "*.fa"))
logging.debug("Found %d query split files" % len(faFnames))
runner = pubGeneric.makeClusterRunner("pubPrepMutDir-mapDnaRefseq-%s" % basename(dnaFaName))
for fname in faFnames:
outPslName = join(pslDir, splitext(basename(fname))[0]+".psl")
cmd = "blat %(targetFname)s %(fname)s {check out exists %(outPslName)s} -noHead" % locals()
runner.submit(cmd)
runner.finish(wait=True)
def mapProtToRefseq(taxId, tmpDir, protFaName):
""" create a psl file with the best mapping protein -> refseq
input is protein fa , output goes into tmpDir/psl
"""
logging.debug("mapping %s to refseq, tmpdir %s" % (protFaName, tmpDir))
refseqFname = join(geneDataDir, "refseq.%s.prot.fa" % str(taxId))
BLASTDIR="/cluster/bin/blast/x86_64/blast-2.2.16/bin"
targetFname = join(tmpDir, "refseq.prot.fa")
logging.info("Copying %s to %s" % (refseqFname, targetFname))
shutil.copy(refseqFname, targetFname)
# split uniprot into pieces
queryDir = join(tmpDir, "queries")
makeOrCleanDir(queryDir)
if protFaName.endswith(".gz"):
cmd = "gunzip %s -c | faSplit about stdin 2500 %s/" % (protFaName, queryDir)
else:
cmd = "faSplit about %s 2500 %s/" % (protFaName, queryDir)
runCommand(cmd)
# index refseq for blast
cmd = "%s/formatdb -i %s -p T" % (BLASTDIR, targetFname)
runCommand(cmd)
# make dir for the output psl files
pslDir = join(tmpDir, "psl")
makeOrCleanDir(pslDir)
# create joblist
jbl = open(join(tmpDir, "jobList"), "w")
logging.info("Created %s" % jbl.name)
faFnames = glob.glob(join(queryDir, "*.fa"))
logging.debug("Found %d part files" % len(faFnames))
jobScriptFname = join(pubConf.ucscScriptDir, "mapUniprot_doBlast")
runner = pubGeneric.makeClusterRunner("pubPrepMutDir-mapProtRefseq-%s" % basename(protFaName))
for fname in faFnames:
outPslName = join(pslDir, splitext(basename(fname))[0]+".psl")
cmd = "%(jobScriptFname)s %(targetFname)s blastp %(fname)s {check out exists %(outPslName)s}" % locals()
runner.submit(cmd)
runner.finish(wait=True)
class FastSqlite:
" a wrapper around sqlite to load data in the fastest way possible "
def __init__(self, fname, tableCreateSql, batchSize=100000):
""" open sqlite db in the fastest mode possible, insert row in batches
The db contains only one table and it must be called "data".
"""
self.batch = []
self.batchSize = batchSize
self.tmpFname = join(pubConf.getFastTempDir(), basename(fname))
self.dbFname = fname
if isfile(self.tmpFname):
os.remove(self.tmpFname)
isolLevel = "exclusive"
self.con = sqlite3.connect(self.tmpFname, isolation_level=isolLevel)
maxCommon.delOnExit(self.tmpFname)
self.con.execute("PRAGMA synchronous=OFF") # recommended by
self.con.execute("PRAGMA count_changes=OFF") # http://blog.quibb.org/2010/08/fast-bulk-inserts-into-sqlite/
self.con.execute("PRAGMA page_size=4096") # http://stackoverflow.com/questions/788568/sqlite3-disabling-primary-key-index-while-inserting
self.con.execute("PRAGMA cache_size=1000000") # http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html NOTE: this is the number of cached pages, so 4GB!
self.con.execute("PRAGMA journal_mode=OFF") # http://www.sqlite.org/pragma.html#pragma_journal_mode
self.con.execute("PRAGMA temp_store=memory")
self.con.commit()
self.con.execute(tableCreateSql)
self.con.commit()
def _insertBatch(self):
" write the current batch to the db "
if len(self.batch)>0:
sql = "INSERT INTO data VALUES (%s)" % ",".join(["?"]*self.batchRowLen)
self.con.executemany(sql, self.batch)
self.con.commit()
self.batch = []
def insert(self, row):
" insert into table data as batches of rows "
self.batchRowLen = len(row)
self.batch.append( row )
if len(self.batch) > self.batchSize:
self._insertBatch()
def close(self):
" close db and move temp file over to final fname "
if len(self.batch)>0:
self._insertBatch()
self.con.commit()
self.con.close()
logging.info("Copying %s to %s" % (self.tmpFname, self.dbFname))
shutil.copy(self.tmpFname, self.dbFname)
os.remove(self.tmpFname)
def dbSnp(taxId, geneDataDir):
""" index dbSnp data, most of these won't be used as they're in intergenic
regions but we keep them for now
"""
assert(taxId==9606)
tmpDir = varBuildDir
snpFname = join(tmpDir, "snp%s.tab" % DBSNPVERSION)
logging.info("dumping snp table into file %s" % snpFname)
if not isfile(snpFname):
cmd = '''hgsql hg19 -NB -e 'select chrom, chromStart, chromEnd, name from snp%s' > %s''' % \
(DBSNPVERSION, snpFname)
maxCommon.runCommand(cmd)
else:
logging.info("%s already exists, delete if you want to restart" % snpFname)
sql = "CREATE TABLE data (chrom TEXT, start INT, end INT, rsId INT PRIMARY KEY)"
dbName = join(varDataDir, "dbSnp.sqlite")
db = FastSqlite(dbName, sql)
count = 1
doneRsIds = set()
for line in open(snpFname):
if count % 1000000 == 0:
print("%d" % count)
chrom, start, end, rsId = line.rstrip("\n").split("\t")
# ignore haps and _gl
if "hap" in chrom or "_gl" in chrom:
continue
intRsId = int(rsId[2:])
if intRsId in doneRsIds:
logging.warn("RsId %d already done" % intRsId)
continue
doneRsIds.add(intRsId)
row = (chrom, int(start), int(end), intRsId)
db.insert(row)
count += 1
# index by chrom pos
print("adding chrom position index")
db.con.execute("CREATE INDEX chromIdx ON data (chrom, start, end);")
db.con.commit()
db.close()
def loadPslToDbm(pslFname, dbmFname, isProt=False, stripVersion=False):
" load psl file into a sqlite file, ignore haplotypes and unplaced seqs"
qNamePsls = defaultdict(list)
count = 0
for line in open(pslFname):
line = line.rstrip("\n")
fields = line.split("\t")
qName = fields[9]
tName = fields[13]
if "hap" in tName or "_gl" in tName:
continue
count += 1
if isProt:
p = Psl(line.split("\t"))
p.protToNa()
line = str(p)
if stripVersion:
qName = qName.split(".")[0]
qNamePsls[qName].append(line)
# write to dbm as \n separated psl lines indexed by qName
#dbm = gdbm.open(dbmFname, "nf")
#dbm = pubKeyVal.SqliteKvDb(dbmFname, singleProcess=True, newDb=True, \
#tmpDir=pubConf.getFastTempDir(), compress=True)
logging.info("Writing psls to %s" % dbmFname)
dbm = pubKeyVal.SqliteKvDb(dbmFname, singleProcess=True)
for qName, pslLines in qNamePsls.iteritems():
dbm[qName]= "\n".join(pslLines)
dbm.close()
logging.info("Indexed %d psls (%d qNames) from %s to %s" % \
(count, len(qNamePsls), pslFname, dbm.dispName()))
def refseqMap(taxId, geneDataDir):
" get refseq -> genome map from browser "
db = taxToDb[taxId]
refPslFname = join(varBuildDir, "refGenePsls.%d" % taxId)
cmd = 'hgsql -NB hg19 -e "select * from refSeqAli" | grep -v hap | grep -v _gl | cut -f2- > %s' % refPslFname
runCommand(cmd)
refPslDbmFname = join(varDataDir, "refGenePsls.%s" % taxId)
loadPslToDbm(refPslFname, refPslDbmFname)
def gbToFa(inGbFname, faFname):
logging.info("Converting %s to %s" % (inGbFname, faFname))
seqs = []
outfh = open(faFname, "w")
for rec in SeqIO.parse(open(inGbFname, "rU"), "genbank") :
#seqs.append(record)
outfh.write(">%s\n%s\n" % (rec.id, rec.seq.tostring()))
#SeqIO.write(seqs, output_handle, "fasta")
outfh.close()
def mapOldRefseqToNewRefseqIndex(seqType, faFname, taxId, dbmFname):
" map old prot refseqs to new refseqs "
# convert gb to fa - this route does not work - see below
#raFname = join(geneDataDir, "oldRefseq.%d.ra" % taxId)
#taFname = join(geneDataDir, "oldRefseq.%d.ta" % taxId)
#cmd = "gbToFaRa -faInclVer /dev/null %(faFname)s %(raFname)s %(taFname)s %(oldRefseqFname)s" % locals()
# gbToFaRa doesn't work - takes only the first version
# gbtofa doesn't work - ignores peptides
# gbtocdi doesn't work
#runCommand(cmd)
# create a pair file oldAcc, newAcc
tmpDir = join(pubConf.mapReduceTmpDir, "oldRefseqMap_"+seqType)
makeOrCleanDir(tmpDir)
oldAccs = constructOldRefseqAccs(taxId, seqType)
pairFname = join(tmpDir, "oldRefseq.%s.pairs" % taxId)
pairFh = open(pairFname, "w")
for old, new in oldAccs.iteritems():
pairFh.write("%s\t%s\n" % (old, new))
pairFh.close()
logging.debug("Wrote pairs to %s" % pairFname)
# create the mapping psl file
mapFname = join(geneDataDir, "oldRefseq.%d.%s.psl" % (taxId, seqType))
if seqType=="prot":
mapProtToRefseq(taxId, tmpDir, faFname)
else:
mapDnaToRefseq(taxId, tmpDir, faFname)
filterPsls(tmpDir, pairFname, mapFname)
loadPslToDbm(mapFname, dbmFname)
def constructOldRefseqAccs(taxId, seqType):
refseqInfoFname = join(geneDataDir, "refseqInfo.tab")
logging.debug("Parsing %s" % refseqInfoFname)
accs = []
for row in maxCommon.iterTsvRows(refseqInfoFname):
if seqType=="prot":
accs.append(row.refProt)
else:
accs.append(row.refSeq)
oldAccs = makeOldToNewAccs(accs)
logging.info("Found %d old accessions" % len(oldAccs))
return oldAccs
def downloadFromGenbank(oldAccs, oldRefseqFname, oneByOne=True, db="protein"):
" download oldRefseq or genbank protein accessions "
logging.info("Writing old refseq data to %s" % oldRefseqFname)
outFh = open(oldRefseqFname, "w")
pubEutils.downloadFromEutils(db, oldAccs, outFh, retType="gb", \
retMax=1000, oneByOne=oneByOne)
return oldRefseqFname
#def downloadFromGenbankFast(accs, outFname):
#" download genbank protein accessions "
#logging.info("Writing genbank data to %s" % outFname)
#outFh = open(outFname, "w")
#pubEutils.chunkedDownloadFromEutils("protein", accs, outFh, retType="gb", chunkSize=1000)
def writeUniprotEntrezSymGbLinks(taxId, uniprotDir):
""" write a tab and .marshal file with the follwing links:
- uniprot base ID -> list of uniprot isoforms
- uniprot -> symbol
- uniprot -> list of genbank
- uniprot -> list of genbank prot
- genbank -> uniprot
- uniprot sequences
"""
global geneDataDir
assert(taxId==9606)
data = {}
data[taxId] = {}
# parse uniprot seqs (get all variants)
#faFname = join(uniprotDir, "uniprot.%s.var.fa.gz" % str(taxId))
#seqDict = maxbio.parseFastaAsDict(faFname)
#data[taxId]["upSeqs"] = seqDict
#logging.info("Found %s sequences" % len(seqDict))
# parse entrez -> uniprot id and up -> symbol and up->genbank
#entrezToUp, upToSym, upToGb, upToRefseq = parseUniprot(uniprotDir, taxId)
upData = parseUniprotLinks(uniprotDir, taxId)
entrezToUp = upData["entrezToUp"]
upToSym = upData["upToSym"]
upToGbProts = upData["upToGbProts"]
upToIsos = upData["upToIsos"]
upToGbs = upData["upToGbs"]
gbToUp = {}
for up, gbList in upToGbs.iteritems():
for gbId in gbList:
gbToUp[gbId] = up
# write to tab file
mutDataFname = join(geneDataDir, "uniprot.tab")
logging.info("Writing uniprot links to %s" % mutDataFname)
ofh = open(mutDataFname,"w")
ofh.write("geneId\tuniprotId\tuniprotIsoIds\tuniprotSym\tgbAcc\tuniprotGbProtAcc\n")
noSym = 0
for geneId, upIds in entrezToUp.iteritems():
for upId in upIds:
sym = upToSym.get(upId, None)
if sym==None:
sym=""
noSym +=1
gbAccs = ""
if upId in upToGbProts:
gbAccs = "|".join(upToGbs[upId])
gbProtAccs = ""
if upId in upToGbProts:
gbProtAccs = "|".join(upToGbProts[upId])
isoIds = upData["upToIsos"][upId]
row = [str(geneId), upId, "|".join(isoIds), sym, gbAccs, gbProtAccs]
ofh.write("\t".join(row)+"\n")
ofh.close()
logging.info("No sym: %d" % noSym)
logging.info("Wrote to %s" % mutDataFname)
# write to marshal file (faster and easier to parse)
data[taxId] = upData
data[taxId]["gbToUp"] = gbToUp
geneDataDir = join(pubConf.staticDataDir, "mutFinder")
mutDataFname = join(geneDataDir, "uniprot.tab.marshal")
del data[taxId]["upToGbs"] # don't need these
marshal.dump(data, open(mutDataFname, "w"))
logging.info("Wrote to %s" % mutDataFname)
def cleanGbAccs(gbDict):
" get only unique values from dict, flatten and clean "
gbLists = gbDict.values()
gbAccs = list(itertools.chain.from_iterable(gbLists))
gbAccs = set([str(x) for x in gbAccs])
if 'na' in gbAccs:
gbAccs.remove("na")
if '' in gbAccs:
gbAccs.remove("")
gbAccs = list(gbAccs)
return gbAccs
def getGenbankAccs(taxId, outFname):
" get all genbank accessions linked from uniprot for a given taxId, and write to file "
upLinkFname = join(geneDataDir, "uniprot.tab.marshal")
upData = marshal.load(open(upLinkFname))
upToGbs = upData[taxId]["upToGb"]
gbAccs = cleanGbAccs(upToGbs)
ofh = open(outFname, "w")
ofh.write("\n".join(gbAccs))
ofh.close()
logging.info("Wrote %d uniprot genbank DNA/RNA accs to %s" % (len(gbAccs), outFname))
#return gbAccs
def getGenbankSeqs(gbIdFname, gbOutFname):
" get genbank seqs with markd's tool "
#cmd = "gbGetSeqs -accFile=%s -allowMissing -gbRoot=/hive/data/outside/genbank genbank mrna %s -get=seq -db=hg19 -inclVersion -native" % (gbIdFname, gbFname)
gbFnames = glob.glob(join(genbankDir, "gbpri*.seq.gz"))
open(gbOutFname, "w") # truncate gbOutFname
for gbFname in gbFnames:
cmd = "gbGetEntries -accFile=%s %s -missingOk >> %s" % (gbIdFname, gbFname, gbOutFname)
runCommand(cmd)
def parseGenbankProts(gbFname, protFaFname, protIds):
" returns translations of CDS in genbank file as dict protId -> sequence "
logging.info("Parsing %s, trying to get %d prot ids" % (gbFname, len(protIds)))
record_iterator = SeqIO.parse(gbFname, "genbank")
res = {}
protIds = set(protIds)
for rec in record_iterator:
cdsFts = [f for f in rec.features if f.type=='CDS']
for cdsFt in cdsFts:
if "protein_id" in cdsFt.qualifiers and "translation" in cdsFt.qualifiers:
ftProtIds = cdsFt.qualifiers["protein_id"]
assert(len(ftProtIds)==1)
protId = ftProtIds[0]
if protId in protIds:
protSeqs = cdsFt.qualifiers["translation"]
assert(len(protSeqs)==1)
res[protId] = protSeqs[0]
else:
logging.debug("protId %s skipped, not target" % protId)
logging.info("Got %d protein sequences from genbank file" % len(res))
return res
def writeFa(data, outFname):
logging.info("Writing %s" %outFname)
ofh = open(outFname, "w")
for id, seq in data.iteritems():
ofh.write(">%s\n%s\n" % (id, seq))
ofh.close()
def loadFaSeqs(protFaFname):
" load (append) seqs in a fasta file into a dbm file as compressed sequences "
dbmFname = join(geneDataDir, "seqs")
#dbm = gdbm.open(dbmFname, "w")
#dbm = pubKeyVal.SqliteKvDb(dbmFname, singleProcess=True, compress=True)
dbm = pubKeyVal.SqliteKvDb(dbmFname, singleProcess=True)
faToDbm(protFaFname, dbm)
dbm.close()
def removeBrackets(s):
""" remove nested brackets from string s
>>> removeBrackets("hello world (no way)")
'hello world'
"""
newS = []
brackLevel = 0
for c in s:
if c=="(":
brackLevel+=1
continue
if c==")":
brackLevel-=1
continue
if brackLevel==0:
newS.append(c)
return "".join(newS).strip()
def updateDict(big, small):
" given two dicts -> list, add all entries from small to big "
for key, vals in small.iteritems():
big[key].update(vals)
return big
# set with lowercase terms that shall not be added to the dictionary
blackList = set(['dynamin', 'superoxide dismutase', 'renal cell carcinoma', 'collagenase', 'intercellular adhesion molecule', 'hormone receptor', 'serine threonine kinase', 'differentiation', 'cyclin dependent kinase', 'epidermal growth factor', 'mitogen activated protein kinase', 'aquaporin', 'calmodulin', 'toll like receptor', 'transmembrane protein', 'adenylyl cyclase', 'poly adp ribose polymerase', 'heat shock protein', 'platelet derived growth factor', 'complement component', 'angiotensin ii', 'ifn gamma', 'adenylate cyclase', 'caspase 3', 'proteoglycan', 'g protein', 'aurora', 'polypeptide', 'atp binding cassette', 'insulin like', 'argonaute', 'neuronal differentiation', 'kinesin', 'tumor necrosis factor alpha', 'nf kappab', 'chloride channel', 'transforming growth factor beta', 'tropomyosin', 'growth hormone', 'serine protease', 'transferrin', 'receptor tyrosine kinase', 'cyclooxygenase 2', 'rna binding protein', 'dna ligase', 'proline rich', 'tyrosine kinase', 'calpain', 'glycoprotein', 'nadph oxidase', 'aspartate aminotransferase', 'interferon alpha', 'amyotrophic lateral sclerosis', 'neurofilament', 'claudin', 'fibronectin', 'estrogen receptor', 'metabotropic glutamate receptor', 'cell adhesion molecule', 'adiponectin', 'prostate cancer', 'interleukin 6', 'midline', 'thrombocytopenia', 'kallikrein', 'gtp binding protein', 'vascular endothelial growth factor', 'zinc finger protein', 'interferon gamma', 'endothelin', 'p glycoprotein', 'vimentin', 'peroxiredoxin', 'epidermal growth factor receptor', 'insulin like growth factor', 'zinc finger', 'neurotrophin', 'cysteine protease', 'splicing factor', 'integral membrane protein', 'glutathione s transferase', 'nitric oxide synthase', 'keratin', 'proto oncogene', 'atp synthase', 'heavy chain', 'glutamate receptor', 'potassium channel', 'death receptor', 'ribonuclease', 'glycogen synthase', 'angiotensin converting enzyme', 'trypsin', 'protein can', 'dynactin', 'thrombospondin', 'tnf alpha', 'transferrin receptor', 'histone deacetylase', 'calcium binding protein', 'aldolase', 'glutathione peroxidase', 'hydroxysteroid dehydrogenase', 'progesterone receptor', 'myosin heavy chain', 'alzheimer disease', 'protease inhibitor', 'a protein kinase', 'alanine aminotransferase', 'transglutaminase', 'beta catenin', 'c reactive protein', 'hepatocellular carcinoma', 'cadherin', 'albumin', 'programmed cell death', 'ubiquitin like', 'fibroblast growth factor', 'a kinase', 'carbonic anhydrase', 'parathyroid hormone', 'g protein coupled receptor', 'matrix metalloproteinase', 'parkinson disease', 'tumor necrosis factor', 'muscle specific', 'exonuclease', 'pierce', 'homeobox', 'microtubule associated protein', 'salvador', 'map kinase', 'tumor suppressor', 'lysozyme', 'interferon regulatory factor', 'syntaxin', 'c jun n terminal kinase', 'tetraspanin', 'modifier', 'signal transducer and activator of transcription', 'insulin receptor substrate', 'nucleolar protein', 'catenin', 'extracellular signal regulated kinase', 'osteosarcoma', 'f box protein', 'macrophage inflammatory protein', 'bone morphogenetic protein', 'aldehyde dehydrogenase', 'interleukin 2', 'protein tyrosine kinase', 'breast cancer cell', 'proteinase', 'abc transporter', 'thioredoxin', 'membrane bound', 'acute myeloid leukemia', 'interleukin', 'retinoblastoma', 'activator', 'dna methyltransferase', 'transcription factor', 'surface antigen', 'alcohol dehydrogenase', 'catalase', 'cytochrome c', 'neuraminidase', 'importin', 'cytochrome p450', 'cyclin d1', 'e cadherin', 'cytokeratin', 'mitogen activated protein kinase kinase', 'cell cycle progression', 'nuclear protein', 'hexokinase', 'nadh dehydrogenase', 'serum albumin', 'focal adhesion kinase', 'nerve growth factor'])
def cleanupNames(descToAccs):
"""