-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfam_to_graph.py
2616 lines (2367 loc) · 137 KB
/
fam_to_graph.py
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
# -*- coding: utf-8 -*-
import os, sys
import itertools
import json
import re
import copy
import argparse
import networkx as nx
import fileinput
from operator import methodcaller
from operator import itemgetter
#from networkx import Graph
#from networkx import readwrite
#from Bio import bgzf
import json
from collections import deque
from collections import OrderedDict
from cStringIO import StringIO
from subprocess import Popen, PIPE, STDOUT
import time
import requests
import logging
def pretty_print_POST(req):
"""
printed and may differ from the actual request.
"""
print('{}\n{}\n{}\n\n{}'.format(
'-----------START-----------',
req.method + ' ' + req.url,
'\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),
req.body,
))
# heap analysis from guppy import hpy
#requires 2.7 or greater
if sys.version_info < (2, 7):
raise Exception("must use python 2.7 or greater")
#from lxml.etree import Element, ElementTree, tostring, fromstring, register_namespace, CDATA
#try:
# from xml.etree.cElementTree import Element, ElementTree, tostring, fromstring, register_namespace, SubElement
#except ImportError:
# try:
# from xml.etree.ElementTree import Element, ElementTree, tostring, fromstring, register_namespace, SubElement
# except ImportError:
# pass
##This script expects files which contain a list of consecutive protein family ID's for the replicons in an organism
## and some kind of summary information about where the kmers come from
##NCBI_TAX_ID RANK TAX_PATH
##590 genus 220341,90370,59201,28901,590
#genome_name genome_info_id ncbi_tax_id taxon_lineage_ids
##NAME NCBI_TAX_ID ACCESSION START_MIN
##FIG01045527 946034 AERV01000001 507
#fam_id gid ncbi_tax_id sequence_info_id start_max figfam_product
ip={'org_id':0,'contig_id':1,'locus_id':2,'start':3, 'end':4, 'fam_id':5}
fi={'fam_id':0,'fam_description':1}
#Edge Classes by reverse status. Here indexed to zero. Class 1: Forward, Forward; Class2: Forward, Reverse; Class3:Reverse, Forward; Class4:Reverse, Reverse
edgeClass={(False,False):1,(False,True):2,(True,False):4,(True,True):8}
edgePossible=set([1,2,4,8])
def warning(*objs):
for o in objs:
print >> sys.stderr, o
##Class for storing information about the origin of a Kmer
class featureInfo():
#expand to parse out this information from different sources
def __init__(self, line=None):
self.md5=None
self.contig_id=None
self.genome_id=None
self.feature_id=None
self.feature_ref=None
self.group_id=None
self.group_num=None
self.start=None
self.end=None
self.function=""
self.rf_forward=None # when this feature leaves out of its kmer window (left side) its in transition to this rf-node
self.rf_reverse=None # when this feature leaves out of the kmer window (right side) its in transition to this rf-node
self.pg_assignment=None
self.repeat_num=1 #the local repeat number for this 'character'
self.instance_key=None
self.rf_ends=[]#Stores orieintation information as which rf-nodes this feature enters/exits
def addRFPointer(self, direction, pointer):
if direction=="increase":
self.rf_forward=pointer
else:
self.rf_reverse=pointer
def addEndInfo(self, rf_id, rhs, direction):
self.rf_ends.append((rf_id, rhs, direction)) # storing the id of the feature on the rhs for convenience. effectively tells you what side *this* feature is on
def compareInstance(self, other_feature):
count1=self.instance_key.count(".")
count2=other_feature.instance_key.count(".")
short_str = long_str = None
if count1 == count2 == self.ksize:
return self.instance_key == other_feature.instance_key
elif count1 >= count2:
short_str = other_feature.instance_key
long_str = self.instance_key
else:
short_str = self.instance_key
long_str = other_feature.instance_key
short_option2= ".".join(short_str.split(".")[::-1]) # reverse
return long_str.startswith(short_str) or long_str.startswith(short_option2) or long_str.endswith(short_str) or long_str.endswith(short_option2)
def getContextValue(self, context):
if context=="genome":
return self.genome_id
elif context=="contig":
return self.contig_id
else:
return None
def getString(self):
#result="|".join([self.contig_id,self.org_id,str(self.start),str(self.end),self.function,self.fam_id])
#return result
return line
def getParts(self):
return line.split("\t")
def dict_to_line(self, target):
line_list=[None for i in range(len(ip))]
for k in ip:
line_list[ip[k]]=str(target[k])
return "\t".join(line_list)
#calculate region between genes
def getInterFeature(self,nxt_feature):
#print "from "+self.fam_id+" to "+nxt_feature.fam_id
cur_info=self.parse_line(self.line)
nxt_info=self.parse_line(nxt_feature.line)
edge_info={}
edge_info['contig_id']=cur_info['contig_id']
edge_info['org_id']=cur_info['org_id']
edge_info['start']=int(cur_info['end'])+1
edge_info['end']=int(nxt_info['start'])-1
edge_info['fam_id']="EDGE"
edge_info['locus_id']="None"
result=geneInfo(self.dict_to_line(edge_info))
return result
def parse_line(self, line=None):
result={}
if line == None:
line =self.line
try:
parts=line.strip().split("\t")
result['fam_id']=parts[ip['fam_id']]
result['contig_id']=parts[ip['contig_id']]
result['org_id']=parts[ip['org_id']]
result['start']=parts[ip['start']]
result['end']=parts[ip['end']]
except:
logging.debug("parsing problem. couldn't parse line: "+line)
return result
def getLocation(self):
result=self.parse_line(self.line)
return [result['contig_id'],result['start'],result['end']]
#return [self.contig_id, self.start, self.end]
def getLocationString(self):
result=self.parse_line(self.line)
return ":".join([result['contig_id'],str(result['start']),str(result['end'])])
#return ":".join([self.contig_id, str(self.start), str(self.end)])
def getFeatureString(self, delim=":"):
result=self.parse_line(self.line)
return delim.join([result['contig_id'],str(result['start']),str(result['end']), str(result['fam_id']), result['org_id']])
#return delim.join([self.contig_id, str(self.start), str(self.end), str(fam_id), str(org_id)])
def getReplicon(self):
result=self.parse_line(self.line)
return result['contig_id']
def getOrganism(self):
result=self.parse_line(self.line)
return result['org_id']
def getFam(self):
result=self.parse_line(self.line)
return result['fam_id']
#return self.org_id
##Class for storing all the geneInfo in a particular node
##along with the kmer information. does not store information in direction
##specific way.
class rfNode():
def __init__(self, nodeID, feature_list, ksize, reverse, palindrome):
self.features=[set([]),set([])]# first position represents a k-lengthed series of features in the positive direction; the second, in reverse
self.positive_features=[0]
self.negative_features=[1]
self.assigned_features=[set([]),set([])]# first position represents a k-lengthed series of features in the positive direction; the second, in reverse
self.addFeatures(reverse, feature_list)
self.duplicate=False #whether this node is duplicated in any context bin
self.nodeID=nodeID
self.palindrome=palindrome
self.split=False
self.has_forward=False
self.has_reverse=False
#dfs non-recursive variables
#self.done=False
#self.visited=False
#self.descending=True
#old variables
self.weightLabel=None
self.weight=None
self.linkOut={}#four classes of edges
self.visited=False
self.queued=False
self.self_edge=False
self.numBins =0
#self.curRevStatus=rev_status
def bidirectional(self):
return (len(self.features[0]) > 0 or len(self.assigned_features[0]) > 0) and (len(self.features[1]) > 0 or len(self.assigned_features[1]) > 0)
def anchorNode(self):
return (not self.duplicate) and (not self.palindrome)
def numFeatures(self):
return len(self.features[0])+len(self.features[1])
def addFeatures(self, reverse, feature_list):
if(reverse):
self.features[-1].add(feature_list[-1])#for space efficency only store right most feature in kmer
self.has_reverse=True
else:
self.features[0].add(feature_list[-1])#for space efficency only store right most feature in kmer
self.has_forward=True
#each cell in list stores info[LetterOfKmer]=geneInfo()
def addInfo(self, position, cur_fam, info):
if self.infoList[position] != None:
if self.infoList[position][0]!=cur_fam:
logging.warning("logical error: trying to insert information about wrong family\n")
sys.exit()
self.infoList[position][-1].append(info)
else:
self.infoList[position]=(cur_fam,[info])
#add intergenic information to what will eventually become pan-genome edges
def addPGEInfo(self, inter_info, position):
if position > len(self.peInfo)-1:
print "out of bounds "+str(position)+" for "+" ".join(self.peInfo)
else:
self.peInfo[position].add(inter_info)
def addEdges(self,node_id,nxt_rev_status):
#get class of edge type
#if self.nodeID ==1 and node_id ==0:
# print "Debug: makes no sense for this to link backwards"
edgeStatus=edgeClass[(self.curRevStatus,nxt_rev_status)]
if node_id in self.linkOut:
self.linkOut[node_id]=self.linkOut[node_id]|edgeStatus #bitwise OR to represent both multi status
else:
self.linkOut[node_id]=edgeStatus
#if the node has been visited before update its references
def updateNode(self, prev_node, in_edge_status, storage):
update_pos=[] #ordered pg-node references to project onto current node
if (not in_edge_status in edgePossible):
logging.warning("unforseen case: transitioning from "+"|".join(prev_node.infoList.keys())+" to "+"|".join(self.infoList.keys()))
#update references to pg-nodes from overlapping portion of previous k-mer
if in_edge_status & 1:
update_pos = range(1,len(prev_node.pgRefs),1)+[None]
elif in_edge_status & 2:
update_pos = [None]+range(len(prev_node.pgRefs)-1,0,-1)
elif in_edge_status & 4:
update_pos = range(len(prev_node.pgRefs)-2,-1,-1)+[None]
elif in_edge_status & 8:
update_pos = [None]+range(0,len(prev_node.pgRefs)-1,1)
for cur_pos, prev_pos in enumerate(update_pos):
if prev_pos != None:
if self.pgRefs[cur_pos] == None: #happens if already queued. transfer the reference
self.pgRefs[cur_pos]=prev_node.pgRefs[prev_pos]
elif prev_node.pgRefs[prev_pos] != self.pgRefs[cur_pos]:
storage.updatePGNode(prev_node.pgRefs[prev_pos], self.pgRefs[cur_pos])
#if the node has not been visited before transfer previous references
def transferRefs(self, prev_node, in_edge_status, storage):
#add references to pg-nodes from overlapping portion of previous k-mer
#if in_edge_status & 1:
# for n in prev_node.pgRefs[1:]:self.pgRefs.append(n)
#elif in_edge_status & 2:
# for n in reversed(prev_node.pgRefs[1:]):self.pgRefs.append(n)
#elif in_edge_status & 4:
# for n in reversed(prev_node.pgRefs[0:-1]):self.pgRefs.append(n)
#elif in_edge_status & 8:
# for n in prev_node.pgRefs[0:-1]):self.pgRefs.append(n)
#if self.nodeID == 1 or self.nodeID ==2 or (prev_node != None and (prev_node.nodeID ==1 or prev_node.nodeID ==2)):
# print "Debug: pgRefs and in_edge_status screwed up"
update_pos=[] #ordered pg-node references to project onto current node
#update references to pg-nodes from overlapping portion of previous k-mer
if in_edge_status & 1:
update_pos = range(1,len(prev_node.pgRefs),1)+[None]
elif in_edge_status & 2:
update_pos = [None]+range(len(prev_node.pgRefs)-1,0,-1)
elif in_edge_status & 4:
update_pos = range(len(prev_node.pgRefs)-2,-1,-1)+[None]
elif in_edge_status & 8:
update_pos = [None]+range(0,len(prev_node.pgRefs)-1,1)
for cur_pos, prev_pos in enumerate(update_pos):
if prev_pos != None:
if self.pgRefs[cur_pos] == None: #happens if already queued. transfer the reference
self.pgRefs[cur_pos]=prev_node.pgRefs[prev_pos]
elif prev_node.pgRefs[prev_pos] != self.pgRefs[cur_pos]:
storage.updatePGNode(prev_node.pgRefs[prev_pos], self.pgRefs[cur_pos])
#apply this kmers location info to current pg-node references
def applyInfo(self,storage):
#infoList is an OrderedDict
#if self.nodeID == 1 or self.nodeID ==2:
# print "Debug: pgRefs and in_edge_status screwed up"
for count,info in enumerate(self.infoList):
nid=self.pgRefs[count]
storage.addInfoPGNode(nid,info[-1])#adds the node. edges are implied within every k-mer
def addPGEdges(self,storage):
#if self.nodeID == 1 or self.nodeID ==2 :
# print "Debug: pgRefs and in_edge_status screwed up"
for i in range(0,len(self.pgRefs)-1,1):
if self.pgRefs[i] == None or self.pgRefs[i+1] == None:
print "missing pg-nodes in "+str(self.nodeID)
sys.exit()
if len(self.peInfo[i]):
storage.getPGNode(self.pgRefs[i]).addEdge(self.pgRefs[i+1],self.peInfo[i])
#1st process previous knode using incoming direction edge to put ref in this kmer. And add this kmers labels to previous references.
#2nd Add edges to new family added in this kmer FOR ALL INCOMING EDGE TYPES
#if there is no previous node just straight expand it
#3rd Check outbound k nodes to see if identity process necessary (in BFS)
#4th when checking outbound k nodes see if prev_node == next_node OR cur_node == next_node
#NOTES direction does not matter at the pg-edge/node level
#model letters in k-mer more explicitly than stupid | separated
def visitNode(self, prev_node, in_edge_status, storage):
#if self.nodeID == 1 or self.nodeID ==2 or (prev_node != None and (prev_node.nodeID ==1 or prev_node.nodeID ==2)):
# print "Debug: pgRefs and in_edge_status screwed up"
#if self.nodeID ==3261:
# print "Debug: investigate here"
if prev_node == None:
for count,info in enumerate(self.infoList):
g_id=storage.addPGNode(info[0],info[-1])#adds the node. edges are implied within every k-mer
self.pgRefs[count]=g_id
else:
if (not in_edge_status in edgePossible):
logging.warning("unforseen case: transitioning from "+"|".join([x[0] for x in prev_node.infoList])+" to "+"|".join([x[0] for x in self.infoList]))
#if the beginnning of this kmer is new create a pg-node for it and a reference to it in this kmer
#handle new portion exposed in this kmer
#case 2|8 =10
if (in_edge_status & 10):
g_id=storage.addPGNode(self.infoList[0][0],self.infoList[0][-1])
self.pgRefs[0]=g_id
#transfer references from previous k-mer
#if self.nodeID==3261:
# print "Debug: look at transfer of references to this node"
self.transferRefs(prev_node, in_edge_status, storage)
#if the end of *this* kmer is new create a PG-node for it and add the reference to this kmer
#handle new portion exposed in this kmer
#case 1|4 =5
if (in_edge_status & 5):
g_id=storage.addPGNode(self.infoList[-1][0],self.infoList[-1][-1])
self.pgRefs[-1]=g_id
#some information may be unique to this kmer. apply it to the pg-nodes
self.applyInfo(storage)
self.visited=True
def getReplicons(self):
result=set([])
#all the replicons should be the same for each fam in this kmer
for fam in self.infoList:
for info in fam[-1]:
result.add(info.getReplicon())
return result
def testNode(self):
#make sure that all the families in the kmer come from same replicons
ref_set=set([info.getReplicon() for info in self.infoList[0][-1]])
for tup in self.infoList:
test_set=set([])
for info in tup[-1]:
test_set.add(info.getReplicon())
if test_set != ref_set:
warning("kmer "+self.nodeID+" has inconsistent replicons")
#pg-node "incubator" class
class pgShell():
def __init__(self, nid,fid,gene_list):
self.node_id=nid
self.subsumed=False
self.consumed_list=[]#ids of the things its consumed
self.famSubset=famVersion(nid, fid,gene_list)
self.edges={}#key is nodeRef, value is set of geneInfo intergenic
def addEdge(self, nodeRef, e_info):
if not nodeRef in self.edges:
self.edges[nodeRef]=e_info.copy()
else: self.edges[nodeRef].update(e_info)
def addInfo(self, info_list):
for i in info_list:
self.famSubset.instances.add(i)
def subsumeNode(self, target):
for nid in target.edges:
if nid in self.edges:
self.edges[nid].update(target.edges[nid])
else:
self.edges[nid]=target.edges[nid] #Does this need to be copied?? It is a reference to a set after all...
self.famSubset.instances.update(target.famSubset.instances)
target.famSubset.subsumed=True
self.consumed_list.append(target.node_id)
self.consumed_list.extend(target.consumed_list)
#provides a summary of where this family occurs
#a family may be differentiated into multiple version depending on its ocurrence in kmers
class famVersion():
def __init__(self, id, famID, id_list):
self.summary_status=False
self.id=id
self.famID=famID
self.instances=set(id_list) #set of locations that identify this version of family
self.organisms=set()
self.tax_summary=set()
self.replicons=set()
self.locations=set()
self.functions=set()
#returns of summary items
def get_summary(self):
if not self.summary_status:
for i in self.instances:
self.replicons.add(i.getReplicon())
self.organisms.add(i.getOrganism())
self.locations.add(i.getLocationString())
self.summary_status=True
result={"replicons":self.replicons, "organisms":self.organisms, "locations":self.locations, "functions":self.functions}
return result
#storing information about each protein family
#function, name, locations
#organizes occurences into versions depending on kmer
class famInfo():
def __init__(self, fID):
self.fID=fID
self.versions=[]#stores famSummary objects which detail locations
self.label=""
self.description=""
#checks to see if the ID set that has changed now overlaps with any of the other sets
#function returns the number to adjust original idx by to account for emptied sets
def checkChainReaction(self, idx, fID, threshold, start=-1):
debug=False
num_adjust=0
adjustment=True
sets_merged=False #inefficient. should figure out which sets are merged and only updated those
while adjustment:
found=False
for idx2, v in enumerate(self.versions):
if idx2 != idx and idx2 > start: #id_set_list[0:idx]+id_set_list[idx+1:]:
intersect=self.versions[idx].instances.intersection(v.instances)
score=len(intersect)
if(score>=threshold):
if debug and fID == "FIG00638284":
warning("Merging groups for "+fID)
warning("Intersection", [':'.join(x.getLocation()) for x in intersect])
warning("Group1", [':'.join(x.getLocation()) for x in self.versions[idx].instances])
warning("Group2",[':'.join(x.getLocation()) for x in v.instances])
self.versions[idx].instances |= v.instances
v.instances=set([])
found=True
sets_merged=True
if idx2 < idx:
num_adjust=num_adjust+1
start=idx2
adjustment= found
#remove empty sets
self.versions= [y for y in self.versions if len(y.instances)]
return (idx-num_adjust, sets_merged)
#add id_set for an occurrence of the figfam in a kmer
def add_instance(self, id_set, threshold, locationHash):
matching_group=-1
change_groups=False#keeps track of which groups need to be updated
for idx, v in enumerate(self.versions):
#bigset= id_set if len(id_set) > len(uid_set) else uid_set
score=len(id_set.intersection(v.instances))
if(score>=threshold):
matching_group=idx
#store the bigest id_set as the identifying one for this figfam
v.instances |= id_set
break
if matching_group == -1:
self.versions.append(famVersion(id_set))
matching_group = len(self.versions)-1
else:
matching_group, change_groups=self.checkChainReaction(matching_group, self.fID, threshold)
if not change_groups:
for loc in self.versions[matching_group].instances:
locationHash[loc]=(str(self.fID),str(matching_group))
else:
for idx_grp, v in enumerate(self.versions):
for loc in v.instances:
locationHash[loc]=(str(self.fID),str(idx_grp))
class featureParser():
def __init__(self, **kwargs):
self.feature_files=kwargs['feature_files']
self.feature_selector=kwargs['feature_selector']
self.file_type=kwargs['file_type']
self.parse_function=kwargs['parse_function']
self.alpha=kwargs["alpha"]
self.parse=None
self.ip = None
self.plaintab={'genome':0,'contig':1,'feature':2,'start':3, 'end':4, 'group':5}
#self.ip={'taxid':2, 'genome':1, 'contig':3,'feature':2,'start':4, 'end':5, 'group':0}
self.pc_figfam={'genome':0,'contig':2,'feature':5,'start':9, 'end':10, 'group':15, 'function':14, 'organism':1}
self.pc_plfam={'genome':0,'contig':2,'feature':5,'start':9, 'end':10, 'group':16, 'function':14, 'organism':1}
self.pc_pgfam={'genome':0,'contig':2,'feature':5,'start':9, 'end':10, 'group':17, 'function':14, 'organism':1}
if self.file_type=="patric_tab" or self.file_type=="patric_genomes":
self.parse=self.parseFeatureTab
self.ip = self.plaintab
if self.alpha=="figfam_id":
self.ip = self.pc_figfam
if self.alpha=="plfam_id":
self.ip = self.pc_plfam
if self.alpha=="pgfam_id":
self.ip = self.pc_pgfam
def parseFeatureTab(self):
#if parsing the feature_files to download patric genome ids, need to use the generator defined by genome_id_feature_gen
if self.file_type=="patric_genomes":
generator = self.genome_id_feature_gen()
else:
generator = fileinput.input(files=self.feature_files)
#if files is empty it should read from stdin
# for line in fileinput.input(files=self.feature_files):
for line in generator:
result=featureInfo()
header=False
try:
header = line.startswith('#')
if header:
#define column position based on header
parts=line.strip().replace("#","").split("\t")
x=0
while x < len(parts):
cur_part=parts[x].lower()
if cur_part in self.ip:
self.ip[cur_part]=x
x+=1
continue
else:
parts=line.strip().split("\t")
result.group_id=parts[self.ip['group']]
result.contig_id=parts[self.ip['contig']]
result.genome_id=parts[self.ip['genome']]
result.start=int(parts[self.ip['start']])
result.end=int(parts[self.ip['end']])
result.feature_ref = parts[self.ip['feature']]
result.organism = parts[self.ip['organism']]
if self.file_type=="patric_genomes" or self.alpha=="pgfam_id":
result.md5 = parts[-1]
if self.parse_function:
result.function = parts[self.ip['function']]
#result.end=parts[ip['end']]
except:
logging.debug("warning: couldn't parse line: "+line)
continue
yield result
def chunker(self, seq, size):
return (seq[pos:pos + size] for pos in xrange(0, len(seq), size))
def genome_id_feature_gen(self, limit=2500000):
genome_id_files=self.feature_files
genome_ids = []
#Will open all files, or stdin if no arguments passed (or if "-" is passed as an argument)
for line in fileinput.input(files=self.feature_files):
#Parses all files for the genome_ids, and will split on commas, or tabs (as well as newlines implcitly by the iterator above)
delim ='; |, |,|;| |\t'
line = re.split(delim,line.strip())
for l in line:
genome_ids.append(l)
logging.info("genome_ids:"+",".join(genome_ids))
for gids in self.chunker(genome_ids, 10):
selectors = ["ne(feature_type,source)","eq(annotation,PATRIC)","in({},({}))".format(self.feature_selector, ','.join(gids))]
genomes = "and({})".format(','.join(selectors))
limit = "limit({})".format(limit)
select = "select(genome_id,genome_name,accession,annotation,feature_type,patric_id,refseq_locus_tag,alt_locus_tag,uniprotkb_accession,start,end,strand,na_length,gene,product,figfam_id,plfam_id,pgfam_id,go,ec,pathway,aa_sequence_md5)&sort(+genome_id,+accession,+start)"
base = "https://www.patricbrc.org/api/genome_feature/"
query = "&".join([genomes, limit, select])
headers = {"accept":"text/tsv", "content-type": "application/rqlquery+x-www-form-urlencoded"}
#Stream the request so that we don't have to load it all into memory
r = requests.post(url=base, data=query, headers=headers, stream=True)
#r = requests.Request('POST', url=base, headers=headers, data=query)
#prepared = r.prepare()
#pretty_print_POST(prepared)
if r.encoding is None:
r.encoding = "utf-8"
if not r.ok:
logging.warning("Error in API request \n")
for line in r.iter_lines(decode_unicode=True):
yield line
##CALCULATE DIVERSITY QUOTIENT!!! GENUS/TOTAL GENOMES
##CALCULATE NORMALIZED NUMBER WEIGHT of NUMBER OF genomes in edge/ total number of genomes
##This class is for storing dictionary structures that facilitate different pan-genome graph calculations
##Parameters are filepaths and the size of kmer to use
#GraphMaker(feature_tab=some_file, context="genome")
class GraphMaker():
def __init__(self, **kwargs):#feature_file, family_file, summary_file, ksize, ignore_fams=set([])):
#print feature_file
#print summary_file
#print str(ksize)
self.feature_parser=None
#convert option passed to file_type
self.feature_parser=featureParser(feature_files=kwargs["feature_files"], feature_selector=kwargs["feature_selector"], file_type=kwargs["file_type"], parse_function=kwargs["label_function"], alpha=kwargs["alpha"])
self.context=kwargs["context"] #should be ["genome", "contig", "feature"]
self.context_levels={"genome":0,"contig":1,"feature":2}
self.ksize=kwargs["ksize"]
self.break_conflict=kwargs["break_conflict"]
self.label_function=kwargs["label_function"]
self.diversity=kwargs["diversity"]
self.all_diversity={}#for tracking total taxa numbers in the graph
self.num_pg_nodes=0
self.rf_graph=nx.DiGraph()# the rf-graph (close to de bruijn) created from series of features with group designations
self.pg_graph=pFamGraph()# pg-graph is an undirected grpah
self.rf_node_index=[]
self.replicon_map=OrderedDict()#stores {genome_id:OrderedDict(contig_id)}
self.minSeq = kwargs["minSeq"]
self.no_edge=set([])
self.conflicts={}
self.contig_order={}#stores {genome_id:OrderedDict{contig_id:[feature_number]}}
self.contig_unorder={}#stores {genome_id:OrderedDict{contig_id:[feature_number]}}
self.order_contigs=False
self.contig_to_rf ={}# track which contigs have which rf-nodes
self.contig_weight={} # for calculating which contigs should be prioritized in traversal to use in layout algorithm
self.traverse_priority = None
self.groups_seen={}
self.group_index=[]
self.context_bin=set([])
self.feature_index=[]
self.debug = False
self.prebundle = False
self.eat_repeats =False
self.anchor_instance_keys={} #structured as {instance_key: [pg_assignment, [features with this instance key]]}
self.non_anchor_guides={} # this is a lookup with the following structure [pg_id][rf_id]=feature_id. Allows looking of a guide_feature based on the pan-genome/transition to a particular rf_id. Should get limited use.
#self.ignore_fams=ignore_fams
self.kmerLevel=0 #the level of a kmer increases if it occurs in repeated series with itself
self.kmerLookup={}#stores array for contig info and set for pointing to the next kmer
self.cur_rf_node=None
self.prev_node=None
self.pg_node_alt={}#for a given visit to an rf-node, for a given kmer position if there are multiple pg-nodes x=set([p1, p2, p3]) store it as pg_node_alt[pg1]=x, pg_node_alt[pg2]=x, etc.
self.prev_indices=[]
self.rf_starting_list=[]
self.visit_number=0
self.alt_counter =0
#based on the feature that is leaving the kmer: flip 0/1, orientation forward/reverse 0/1, leaving_position left/right 0/f1
#gives position of the newest feature in the next kmer, the adjustment to the leaving feature to get the rhs of next kmer
self.projection_table=[[[
{"nxt_position":1,"rhs_adj":self.ksize,"feature_adj":self.ksize},# ++ lp=0
{"nxt_position":0,"rhs_adj":-1,"feature_adj":-self.ksize} # ++ lp=k-1
],[
{"nxt_position":1,"rhs_adj":-self.ksize,"feature_adj":-self.ksize},#projection_table[0][0][0] -- lp=0
{"nxt_position":0,"rhs_adj":1,"feature_adj":self.ksize} #projection_table[0][0][1] -- lp=k-1
]],[[
{"nxt_position":0,"rhs_adj":1,"feature_adj":self.ksize},# +- lp=0
{"nxt_position":1,"rhs_adj":-self.ksize,"feature_adj":-self.ksize} # +- lp=k-1
],[
{"nxt_position":0,"rhs_adj":-1,"feature_adj":-self.ksize},# -+ lp=0
{"nxt_position":1,"rhs_adj":self.ksize,"feature_adj":self.ksize} # -+ lp=k-1
]]]
#based on target info: orientation 0/1 forward/reverse, kmer_side 0/1 left/right
self.rhs_adj_table=[[
{"new_feature_adj":-(self.ksize-1),"prev_feature_adj":-(self.ksize-2),"leaving_feature_adj":0},# increasing left side
{"new_feature_adj":0,"prev_feature_adj":-1,"leaving_feature_adj":-(self.ksize-1)} # increasing right side
],[
{"new_feature_adj":(self.ksize-1),"prev_feature_adj":(self.ksize-2),"leaving_feature_adj":0},#decreasing left side
{"new_feature_adj":0,"prev_feature_adj":1,"leaving_feature_adj":self.ksize-1}#decreasing right side
]]
#self.pg_initial=[] #initial node storage
#self.pg_ptrs=[] #idx of nodes. for merging identity
#self.figfamHash={}#stores sets of coordinates for each figfam used to distinguish between paralogs/orthologs/distant orthologs
#self.summaryLookup={}
#self.familyInfo={}
#self.locationHash={}#stores the disambiguated 'version' of the protein family. hashed by (seq. accession, location)
#self.geneHash={} #storing information about the individual genes
#self.replicon_edges_dict={}#stores which replicons have which edges
#self.summary_level=None#taxon level at which to summarize
#self.ksize=ksize #size of the kmer to store
#self.recentK=deque(maxlen=ksize-1)#used for elevating k-mers to the next level
#self.replicon_map={}#stores relationships between org_ids and contig_ids (contig_ids)
#self.parseFeatures(feature_file)
#h=hpy()
#print h.heap()
#self.parseSummary(summary_file)
#self.parseFamilyInfo(family_file)
def checkRFGraph(self):
ambig=0
for r in self.rf_node_index:
if r.numFeatures() >0:
ambig+=1
logging.info("rf-graph: "+str(ambig)+" nodes unexapanded")
#assert LogicError("RFNode unexpanded")
def checkPGGraph(self):
for cnode in self.pg_graph.nodes_iter(data=True):
if len(cnode[1]["features"]) == 0 :
logging.warning("pg-graph node "+str(cnode[0])+"has no features")
group_id=None
for g in cnode[1]["features"]:
if g in ["md5", "start", "end", "info"]:
continue
for contig in cnode[1]["features"][g]:
for f in cnode[1]["features"][g][contig]:
if group_id == None:
group_id = self.feature_index[int(f)].group_id
elif group_id != self.feature_index[int(f)].group_id:
raise Exception("LogicError")
def calcStatistics(self):
stats=[]
stats.append("rf-graph:")
stats.append("nodes "+str(self.rf_graph.number_of_nodes()))
stats.append("edges "+str(self.rf_graph.number_of_edges()))
stats.append("ps-graph:")
stats.append("nodes "+str(self.pg_graph.number_of_nodes()))
stats.append("edges "+str(self.pg_graph.number_of_edges()))
stats.append("alt-nodes "+str(self.alt_counter))
logging.warning("\n"+"\n".join(stats))
def write_contigs(self, contig_file, unsorted_file=None):
#first assure that all contigs are represented
missing_contigs=0
missing_genomes=0
for k,v in self.replicon_map.iteritems():
if k not in self.contig_order:
missing_genomes+=1
logging.warning("WARNING: missing genome in contig order "+k+"\n")
self.contig_order.setdefault(k, OrderedDict())
for contig_id in v.keys():
if contig_id not in self.contig_order[k]:
missing_contigs+=1
logging.warning("WARNING: missing contig in contig order "+" ".join([k,contig_id])+"\n")
if unsorted_file != None:
self.contig_unorder.setdefault(k,{}).setdefault(contig_id,[])
else:
self.contig_order[k].setdefault(contig_id,[])
if missing_contigs or missing_genomes:
logging.warning("WARNING: missing genomes count "+str(missing_genomes)+" missing contigs count "+str(missing_contigs)+"\n")
with open(contig_file, 'w') as ch:
for g in self.replicon_map.keys():
ch.write("\t".join([g]+self.contig_order[g].keys())+"\n")
if unsorted_file != None:
with open(unsorted_file, 'w') as ch:
for g in self.contig_unorder.keys():
ch.write("\t".join([g]+self.contig_unorder[g].keys())+"\n")
def getTaxaIndicator(self, feature_id, mode="name"):
if mode=="name":
string_part = 0
if self.diversity == "genus":
string_part =0
elif self.diversity == "species":
string_part = 1
cur_taxa =self.feature_index[feature_id].organism.split()[string_part]
return cur_taxa
def trackDiversity(self, feature_id, tracking_dict):
taxa = self.getTaxaIndicator(feature_id)
tracking_dict.setdefault(taxa, 0)
tracking_dict[taxa]+=1
def calcDiversity(self, cur_profile):
#taxa=self.getTaxaIndicator(feature_id)
diversity = float(len(cur_profile.keys()))/float(len(self.all_diversity.keys()))
return diversity
def finalizeGraphAttr(self, replaceIDs=False):
num_genomes=float(len(self.replicon_map.keys()))
alt_group = {}
processed_n =set([])
grp_id =0
for n, alts in self.pg_node_alt.iteritems():
if n in processed_n:
continue
else:
processed_n.update(alts)
for n in alts:
alt_group[n]=grp_id
grp_id+=1
for e in self.pg_graph.edges_iter():
attr=self.pg_graph.get_edge_data(*e)
if "genomes" in attr:
attr["weight"]=len(attr["genomes"])/num_genomes
for a in attr:
if type(attr[a])==set:
attr[a] = ','.join(attr[a])
for n,d in self.pg_graph.nodes_iter(data=True):
label_set =set([])
cur_diversity = {}
f_id=[i for key, i in d["features"].items() if type(i) == dict and key != "info"][0].values()[0][0]
d["label"]=self.feature_index[f_id].group_id
import pdb;
for g in d["features"]:
if g in ["md5", "start", "end", "info"]:
continue
f_id=d["features"][g].values()[0][0]
self.trackDiversity(f_id, cur_diversity)
for s in d["features"][g]:
feature_refs=[]
for f in d["features"][g][s]:
feature_refs.append(self.feature_index[f].feature_ref)
if self.label_function:
label_set.add(self.feature_index[f].function)
d["features"][g][s] = feature_refs
diversity=self.calcDiversity(cur_diversity)
d["diversity"]=diversity
if self.label_function:
d["family"]=d["label"]
d["label"]=list(label_set)[0]
d["features"]=json.dumps(d["features"])
#make conflict attribute always present
if not "conflict" in d:
d["conflict"]= 0
grp_id = alt_group.get(n, 0)
d["alternate"]= grp_id
#sys.stderr.write("real alt number: "+str(len(processed_n))+"\n")
class taxInfo():
def __init__(self, genome_name, summary_id):
self.genome_name=genome_name
self.summary_id=summary_id
def get_summary_id(self):
return self.summary_id
##adds a PGShell to pg_initial and a pointer in pg_ptrs
def addPGNode(self,fid,gene_list):
nid=len(self.pg_initial)
self.pg_initial.append(pgShell(nid,fid,set(gene_list)))
self.pg_ptrs.append(nid)
return len(self.pg_ptrs)-1
def getPGNode(self, node_idx):
cur_ref=self.pg_ptrs[node_idx]
result=self.pg_initial[cur_ref]
#if result == None:
# print "Debug: None type"
return result
def addInfoPGNode(self, nid, gene_list):
#if nid == None:
# print "Debug: whats going on?"
cur_node=self.getPGNode(nid)
cur_node.addInfo(gene_list)
#using the idx provided make the main node subsume the target node
#don't have to destroy target...
def updatePGNode(self, main_idx, target_idx):
main_idx2=self.pg_ptrs[main_idx]
main_node = self.pg_initial[main_idx2]
target_idx2 = self.pg_ptrs[target_idx]
target_node = self.pg_initial[target_idx2]
#if main_node == None or target_node == None or target_idx==18:
# print "Debug: None type here"
if main_node.node_id != target_node.node_id:
main_node.subsumeNode(target_node)
#now point all future references to target_node at main_node
for c in main_node.consumed_list:
self.pg_ptrs[c]=main_idx2
self.pg_initial[target_node.node_id]=None #destroy target
#called after all features have been processed so that can flip them
#and so that those that contain an anchor node can be added the anchor_instance_keys lookup
def finalizeInstanceKeys(self):
f=0
while f < len(self.feature_index):
if self.feature_index[f].instance_key !=None: #if its None then the contig wasn't big enough to create a node
lv = [int(i) for i in self.feature_index[f].instance_key.split(".")]
instance_reverse, instance_palindrome = self.flipKmer(lv)
#the function actually flips the kmer
#if instance_reverse:
# lv.reverse()
instance_key_orig = ".".join(str(i) for i in lv)
self.feature_index[f].instance_key = instance_key_orig+"."+str(self.feature_index[f].repeat_num)+"r"
# if the instance key has a single anchor node in it then it is an anchor instance key
if instance_key_orig in self.anchor_instance_keys:
self.anchor_instance_keys[instance_key_orig][1].append(f)
else:
#check to see if any of the instances are anchor nodes
for rf in lv:
if self.rf_node_index[rf].anchorNode():
self.anchor_instance_keys[instance_key_orig]=[None,[f]]
break
f+=1
##This function checks whether the kmer is in the graph
#and links kmer graph data structure appropriately
#store kmers according to the combined protein family ids, and a set of IDs for which kmer comes next
#id of prev kmer, id of this kmer, information about this kmer, whether this kmer has been reversed
def addRFNode(self, feature_list):
reverse,palindrome,feature_indices,kmer_key=self.hashKmer(feature_list)#put IDs together to make kmer
nodeID=None
duplicate=False
dup_number=0
if not kmer_key in self.kmerLookup:
nodeID = len(self.rf_node_index)
self.rf_node_index.append(rfNode(nodeID, feature_indices, self.ksize, reverse, palindrome))
self.cur_rf_node=self.rf_node_index[-1]
self.kmerLookup[kmer_key]=self.rf_node_index[-1]
else:
duplicate=kmer_key in self.context_bin
self.cur_rf_node=self.kmerLookup[kmer_key]
self.cur_rf_node.addFeatures(reverse, feature_indices)
if duplicate:
self.cur_rf_node.duplicate=True
dup_number=1
if self.context != "feature":
self.context_bin.add(kmer_key)
self.rf_graph.add_node(self.cur_rf_node.nodeID, label=kmer_key, duplicate=dup_number)
if not duplicate:
self.cur_rf_node.numBins+=1
if self.traverse_priority == "area":
self.contig_to_rf.setdefault(feature_list[0].contig_id,[]).append(self.cur_rf_node.nodeID)
#here we add a key that marks which kmers the feature occurs in for later disambiguation
for f in feature_indices:
if self.feature_index[f].instance_key == None:
self.feature_index[f].instance_key= str(self.cur_rf_node.nodeID)
else:
self.feature_index[f].instance_key += "."+str(self.cur_rf_node.nodeID)
#add information regarding which end of this rf-node the features are on
self.feature_index[feature_indices[0]].addEndInfo(self.cur_rf_node.nodeID, feature_indices[self.ksize-1], reverse)
self.feature_index[feature_indices[self.ksize-1]].addEndInfo(self.cur_rf_node.nodeID, feature_indices[self.ksize-1], reverse)
#rf-edges. properties dictated by the relationship of the kmers (flipped or not)
if self.prev_node!=None:
if self.prev_reverse:
if reverse: # -1 -1
leaving_position=self.ksize-1
reverse_lp=0
else: # -1 +1
leaving_position=self.ksize-1
reverse_lp=self.ksize-1
else:
if reverse:# +1 -1
leaving_position=0
reverse_lp=0
else:# +1 +1
leaving_position=0
reverse_lp=self.ksize-1
self.feature_index[self.prev_indices[leaving_position]].addRFPointer(direction="increase", pointer=self.cur_rf_node.nodeID) #record which direction a feature is leaving the k-window and what rf-node it is traversing to
self.feature_index[feature_indices[reverse_lp]].addRFPointer(direction="decrease", pointer=self.prev_node.nodeID) # to enable thread based navigation.
if not self.rf_graph.has_edge(self.prev_node.nodeID, self.cur_rf_node.nodeID):
rflip = fflip = self.prev_reverse ^ reverse #xor. if kmers are flipped relative to each other
if palindrome:
fflip = "no"
if self.prev_node.palindrome:
rflip= "no"
self.rf_graph.add_edge(self.prev_node.nodeID, self.cur_rf_node.nodeID, **{"flip":fflip,"leaving_position":leaving_position})
self.rf_graph.add_edge(self.cur_rf_node.nodeID, self.prev_node.nodeID, **{"flip":rflip,"leaving_position":reverse_lp})
self.prev_indices=feature_indices
self.prev_node=self.cur_rf_node