-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGuestTreeGen.py
274 lines (225 loc) · 9.45 KB
/
GuestTreeGen.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
from ete3 import Tree
import numpy as np
from scipy.stats import expon
from math import exp
from stats import gaussNoise
from random import randint
LOSS_CODE = -1
#DUPLICATION_FACTOR = 3 breaks tandem duplication detection, do this later instead
dupevents = 0
dupnodes = 0
lossnodes = 0
#####################################
# #
# Helper Functions #
# #
#####################################
def createNode():
"""Creates a domain node with required fields precreated"""
node = Tree()
node.name = 'placeholder'
node.add_feature('pos', 0)
node.add_feature('event', 'SPECIATION')
node.dist = 0
return node
def createTree(n):
tree = Tree()
tree.dist = 0
for i in range(n):
node = createNode()
node.add_feature('position', i)
node.pos = i
node.name = "g0_" + str(i)
tree.children.append(node)
node.up = tree
return tree
def addcherry(node, hostName = '', domCounter = 0):
"""Takes a node with no children and adds two children"""
left = createNode()
right = createNode()
if hostName != '':
left.name = "g" + hostName[1:] + "_" + str(domCounter)
right.name = "g" + hostName[1:] + "_" + str(domCounter + 1)
domCounter += 2
left.add_feature('pos', 0)
right.add_feature('pos', 1)
node.add_child(left)
node.add_child(right)
return domCounter
def clean(host, guest):
"""
Takes in host and guest trees and removes all attributes other than name, dist, and event
"""
allowedFeatures = ['support','dist','name','event']
for node in host:
features = node.features.copy()
for feature in features:
if feature not in allowedFeatures:
node.del_feature(feature)
for node in guest:
features = node.features.copy()
for feature in features:
if feature not in allowedFeatures:
node.del_feature(feature)
#####################################
# #
# Guest Tree Generation #
# #
#####################################
def buildGuestNode(startingTree, dupRateFunc, dupfunc, hostName = '',
branchLength = 1, branchFunc = gaussNoise, eventDist = .05):
"""
Creates topology of guest tree within a single node of the host tree.
Starting tree nodes must have a pos feature (position of domain in sequence).
Number of events at this node is determined by branchLength and eventDistribution
Args:
startingTree (Tree): The symbolic tree to evolve. For example, a tree with
three leaves will be treated as a sequence with three
domains
dupRateFunc (func): function with # domains as input and a duplication rate output
dupfunc (func): A function which returns the size of a tandem duplication.
Must be of the form dupfunc(x,y), where x and y are the
min and max duplication sizes respectively
hostName (str ): If given, hostName (of the form H<HOST_ID>) will be used to label
guest nodes in the form G<HOST_ID>_<GENE_ID>
branchLength (float): used to determine the number of events that occur here
eventDist (float): Average distance between events
branchFunc (func): takes eventDist as input, returns actual distance between two events
Returns:
branchLength (float):
"""
global dupnodes
global dupevents
global lossnodes
domCounter = 0 #if hostName is given, names of dom nodes will be 'hostName_domCounter'
leaves = [leaf for leaf in startingTree]
for leaf in leaves:
leaf.add_feature('bl', branchLength)
if hostName != '':
for leaf in leaves:
leaf.name = 'g' + hostName[1:] + "_" + str(domCounter)
domCounter += 1
leaves.sort(key=lambda x: x.pos)
dist = branchFunc(eventDist)
while(branchLength > dist and len(leaves) > 0):
event = np.random.random()
branchLength -= dist
#Duplication
if event < dupRateFunc(len(leaves)):
numDomains = len(leaves)
size = dupfunc(1, len(leaves))
start = np.random.randint(numDomains - size + 1)
dupNumber = randint(1,99999)
dupevents += 1
dupnodes += size
for i in range(start, start+size):
node = leaves[i]
node.event = "DUPLICATION"
node.add_feature('dupNumber', dupNumber)
domCounter = addcherry(node, hostName, domCounter)
node.dist = node.bl - branchLength
node.children[0].dist = 0
node.children[1].dist = 0
node.children[0].add_feature('bl', branchLength)
node.children[1].add_feature('bl', branchLength)
leaves[i] = node.children[0]
node.children[0].pos = node.pos
node.children[1].pos = node.pos + size
leaves.insert(i + size, node.children[1])
for i in range(start + 2*size, len(leaves)):
leaves[i].pos += size
#Loss
else:
lossnodes += 1
position = np.random.randint(len(leaves))
leaves[position].pos = LOSS_CODE
leaves[position].event = 'LOSS'
leaves.pop(position)
for i in range(position, len(leaves)):
leaves[i].pos -= 1
dist = branchFunc(eventDist)
for node in leaves:
if 'bl' in node.features:
node.dist += node.bl
return branchLength
def buildGuestTree(host, dupRateFunc, dupfunc, eventDist, branchFunc, startSize):
"""
Creates a guest tree topology inside of the host tree given parameters
Args:
host (Tree): The host tree (ete3 format) to evolve inside
dupRateFunc (func): A function that takes the current number of domains as input
and returns the rate at which duplications occur
dupfunc (func): A function which returns the size of a tandem duplication.
Must be of the form dupfunc(x,y), where x and y are the
min and max duplication sizes respectively
eventDist (float): function that takes no arguments and returns the distance to
the next evolutionary event
branchFunc (func): takes eventDist as input, returns actual distance between two events
startSize (int ): The number of leaves in the initial guest, prior to any
evolutionary event.
Returns:
guest (Tree): The complete guest tree topology
nodemap (dict): host -> guest mapping of nodes
"""
global dupnodes
global dupevents
global lossnodes
dupnodes = 0
dupevents = 0
lossnodes = 0
guest = createTree(startSize)
guest.name = "g" + host.name[1:] + "_0"
guest.add_feature('pos', 0)
nodemap = {}
branchLength = 0
for node in host:
node.add_feature('bl', node.dist)
nodemap[node] = []
for hostNode in host.traverse():
if hostNode == host: #Root node
branchLength = buildGuestNode(guest, dupRateFunc, dupfunc, hostNode.name, hostNode.dist, branchFunc, eventDist)
hostNode.bl = branchLength
nodemap[hostNode] = [node for node in guest.traverse()]
hostNode.add_feature('leaves', [leaf for leaf in guest if leaf.pos != LOSS_CODE])
else:
#Find last occurrence of domain nodes above me
gleaves = hostNode.up.leaves
hostNode.add_feature('leaves', [])
if gleaves == []:
continue
newTrees = []
treepositions = []
#create a subtree for each gleaf
for i in range(len(gleaves)):
if gleaves[i].pos != LOSS_CODE:
t = createNode()
t.pos = gleaves[i].pos
newTrees.append(t)
treepositions.append(i)
if len(treepositions) == 0:
continue
supernode = Tree()
supernode.children = newTrees
branchLength = buildGuestNode(supernode, dupRateFunc, dupfunc,
hostNode.name, hostNode.dist, branchFunc, eventDist)
hostNode.bl = branchLength
hostNode.leaves += [leaf for leaf in supernode if leaf != LOSS_CODE]
nodemap[hostNode] = [n for n in supernode.traverse()]
nodemap[hostNode].pop(0)
for i in range(len(treepositions)):
gleaves[treepositions[i]].add_child(newTrees[i])
#clean(host, guest) #Only add this back in when clean problems are solved
#print "GuestTreeGen: The cost is " + str(cost())
return guest, nodemap
def cost():
return 2 * dupevents + .5 * (dupnodes - dupevents) + lossnodes
if __name__ == '__main__':
def s2(x):
denom = 1 + exp(7-x)
return 1 - .6 / denom
def expfunc(minimum=1, maximum=3):
"""Exponential distribution with lambda=0.75 and min/max parameters"""
return min(maximum, max(minimum, int(expon(0.75).rvs())))
g = buildGuestTree(Tree(), s2, expfunc, .2 ,gaussNoise, 1)[0]
print dupevents, dupnodes, lossnodes
print g.get_ascii(attributes=['event'])