pyham 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyham/mapper.py ADDED
@@ -0,0 +1,414 @@
1
+ from .genome import Genome
2
+ import logging
3
+ import abc
4
+ logger = logging.getLogger(__name__)
5
+
6
+
7
+ class HOGsMap(object):
8
+ """
9
+ Class to compare HOG evolutionary relations (duplication, loss, gain and retained) between an ancestor genome and
10
+ its descendant genome.
11
+
12
+ Let's consider Go the oldest genome and Gy the youngest genome with their respected HOGs Ho and Hy.
13
+
14
+ Those relations are classified into the following categories:
15
+ - RETAINED: if Ho will correspond to a single Hy.
16
+ - DUPLICATE: If a duplication occurred in Ho in between Go ang Gy.
17
+ - LOSS: If Ho have no representative Hy in Gy.
18
+ - GAIN: if Hy have no ancestor Ho in Go.
19
+
20
+ First, a "UpMap" is build to find for each Hy its potential ancestor Ho. If during the traversal from Hy to Ho a
21
+ duplication occurred, a flag "paralog" is added in the UpMap[Hy]. Hy with no corresponding Ho are considered as
22
+ gained meanwhile Ho without corresponding Hy are considered as lost. Ho with only one corresponding Hy (and no
23
+ duplication tag) are clustered as retained otherwhise as duplicated.
24
+
25
+
26
+ Attributes:
27
+ | Ham (:obj:`pyham.pyham.Ham`): Ham object.
28
+ | ancestor (:obj:`pyham.genome.Genome`): :obj:`pyham.genome.Genome` of Go.
29
+ | descendant (:obj:`pyham.genome.Genome`): :obj:`pyham.genome.Genome` of Gy.
30
+ | upMap (:obj:`dict`): a dictionary that map each Ho with its related Hy (or None if no HOG founded) associated a boolean if a duplication occurs or not in between them.
31
+ | RETAINED (:obj:`dict`): Dictionary that map a Ho with its descendant Hy.
32
+ | DUPLICATE (:obj:`dict`): Dictionary that map a Ho with its list of descendants Hy.
33
+ | LOSS (:obj:`list`): a list of Ho with no matching in Gy.
34
+ | GAIN: (:obj:`list`): a list of Hy with no ancestor in Go.
35
+ | number_duplication: (:obj:`int`): number of duplication events that explain the DUPLICATE genes.
36
+
37
+
38
+ """
39
+
40
+ def __init__(self, ham_object, genome1, genome2):
41
+ """
42
+ Args:
43
+ | genome1 (:obj:`pyham.genome.Genome`): First :obj:`pyham.genome.Genome` to compare.
44
+ | genome2 (:obj:`pyham.genome.Genome`): Second :obj:`pyham.genome.Genome` to compare.
45
+
46
+ """
47
+
48
+ if not isinstance(genome1, Genome):
49
+ raise TypeError("expect subclass obj of '{}', got {}"
50
+ .format(Genome.__name__,
51
+ type(genome1).__name__))
52
+
53
+ if not isinstance(genome2, Genome):
54
+ raise TypeError("expect subclass obj of '{}', got {}"
55
+ .format(Genome.__name__,
56
+ type(genome2).__name__))
57
+
58
+ self.HAM = ham_object
59
+ self.ancestor, self.descendant = self.HAM._get_oldest_from_genome_pair(genome1, genome2)
60
+ self.upMap = self._build_UpMap()
61
+ self.LOSS, self.GAIN, self.RETAINED, self.DUPLICATE = self._build_event_clusters()
62
+ self.number_duplication = self._count_duplications()
63
+ self.consistent = self._check_consistency_numbers() # for unittest purposes
64
+
65
+ def _check_consistency_numbers(self):
66
+ """
67
+ This function check that the numbers in different event cluster add ups and print warning if not !
68
+
69
+ """
70
+
71
+ consistent = True
72
+
73
+ # First check for numbers additivity in descendant genome
74
+ duplicated_gene_descendant = 0
75
+ for dg in self.DUPLICATE.values():
76
+ duplicated_gene_descendant += len(dg)
77
+ sum_descendant = len(self.GAIN) + len(self.RETAINED.values()) + duplicated_gene_descendant
78
+ number_descendant = len(self.descendant.genes)
79
+
80
+ if sum_descendant != number_descendant:
81
+ consistent = False
82
+ if len(logger.handlers) > 0:
83
+ logger.critical(
84
+ 'Inconsistency founded when comparing {} with its descendant genome {}. There is {} genes in the descendant genome but {} are founded in the sum of genes resulting of duplication, retained and gain'.format(
85
+ self.ancestor.name, self.descendant.name, number_descendant, sum_descendant))
86
+
87
+ # Then check for numbers additivity of ancestor genomes
88
+ sum_ancestor = len(self.RETAINED.keys()) + len(self.LOSS) + len(self.DUPLICATE.keys())
89
+ number_ancestor = len(self.ancestor.genes)
90
+
91
+ if sum_ancestor != number_ancestor:
92
+ consistent = False
93
+ if len(logger.handlers) > 0:
94
+ logger.critical(
95
+ 'Inconsistency founded when comparing {} with its descendant genome {}. There is {} genes in the ancestor genome but {} are founded in the sum of genes in retained, loss and duplicated categories'.format(
96
+ self.ancestor.name, self.descendant.name, number_ancestor, sum_ancestor))
97
+
98
+ return consistent
99
+
100
+ def _count_duplications(self):
101
+
102
+ dup = 0
103
+
104
+ for Ho, Hys in self.DUPLICATE.items():
105
+
106
+ dup += len(Hys) - 1
107
+
108
+ return dup
109
+
110
+ def _build_event_clusters(self):
111
+ """
112
+ This method builds all the event clusters based on the UpMap.
113
+
114
+ Returns:
115
+ list of loss, list of gain, dict of retained and dict of duplicated.
116
+
117
+ """
118
+ GAIN = [] # [Hy]
119
+ RETAINED = {} # {Ho -> Hy}
120
+ DUPLICATE = {} # {Ho -> [Hy]}
121
+ ancestral_hogs_computed = set()
122
+
123
+ for Hy, Ho in self.upMap.items():
124
+ if Ho[0] is None: # GAIN
125
+ GAIN.append(Hy)
126
+ else:
127
+ if Ho[1]: # DUPLICATE
128
+ DUPLICATE.setdefault(Ho[0], []).append(Hy)
129
+ else: # SINGLE
130
+ RETAINED[Ho[0]] = Hy
131
+ ancestral_hogs_computed.add(Ho[0])
132
+
133
+ # LOSS
134
+ LOSS = set(self.ancestor.genes) - ancestral_hogs_computed
135
+
136
+ return LOSS, GAIN, RETAINED, DUPLICATE
137
+
138
+ def _build_UpMap(self):
139
+ """
140
+ This method construct the UpMap between Ho and Hy.
141
+
142
+ Returns:
143
+ A dictionary that map each Ho with its related Hy (or None if no HOG founded) associated a boolean if a
144
+ duplication occurs or not in between them.
145
+ """
146
+
147
+ upMap = {} # {Hy -> [Ho|None, True|False]}
148
+
149
+ for Hy in self.descendant.genes:
150
+ Ho, paralog = Hy.search_ancestor_hog_in_ancestral_genome(self.ancestor)
151
+ upMap[Hy] = [Ho, paralog]
152
+
153
+ return upMap
154
+
155
+ class MapResults(metaclass=abc.ABCMeta):
156
+ """
157
+ Abstract class to map HOGs across multiple genomes through their most recent common ancestral genome. The HOGs are all
158
+ clustered based on their relation with the mrca genome HOGs (duplicated, lost, gained and retained).
159
+
160
+ Let's consider Go the mrca genome and Gn the youngest genomes with their respected HOGs Ho and Hn.
161
+
162
+ The HOG relations between Ho and Hn are classified into the following categories:
163
+ - RETAINED: if Ho will correspond to a single Hn in Gn.
164
+ - DUPLICATE: If a duplication occurred in Ho in between Go ang Gn.
165
+ - LOSS: If Ho have no representative Hn in Gn.
166
+ - GAIN: if Hn have no ancestor Ho in Go.
167
+
168
+ There is two type of possible mapping:
169
+ - vertical: compare a genome with its ancestor (that act as "mrca").
170
+ - lateral: compare genomes with their mrca.
171
+
172
+ The MapResults provides methods to compare HOGs across genomes:
173
+ - get_loss()
174
+ - get_gain()
175
+ - get_duplicate()
176
+ - get_retained()
177
+
178
+ Attributes:
179
+ | Ham (:obj:`pyham.pyham.Ham`): Ham object.
180
+ | ancestor (:obj:`pyham.genome.Genome`): :obj:`pyham.genome.Genome` of Go.
181
+ """
182
+
183
+ def __init__(self, HAM):
184
+ self.HAM = HAM
185
+ self.ancestor = None
186
+
187
+ @abc.abstractmethod
188
+ def add_map(self, map):
189
+ """Add a map to the MapResults object"""
190
+ pass
191
+
192
+ @abc.abstractmethod
193
+ def get_lost(self):
194
+ """Return the lost genes"""
195
+ pass
196
+
197
+ @abc.abstractmethod
198
+ def get_gained(self):
199
+ """Return the gained genes"""
200
+ pass
201
+
202
+ @abc.abstractmethod
203
+ def get_retained(self):
204
+ """Return genes that stay single copy"""
205
+ pass
206
+
207
+ @abc.abstractmethod
208
+ def get_duplicated(self):
209
+ """Return genes that duplicate"""
210
+ pass
211
+
212
+
213
+ class MapVertical(MapResults):
214
+ """
215
+ Class to map HOGs between a genome and its ancestor.
216
+
217
+ Let's consider Go the oldest genome and Gn the youngest genome with their respected HOGs Ho and Hn.
218
+
219
+ Attributes:
220
+ | descendant (:obj:`pyham.genome.Genome`): :obj:`pyham.genome.Genome` of Gn.
221
+ | map (:obj:`pyham.mapper.HOGsMap`): :obj:`pyham.genome.Genome` of Go.
222
+ """
223
+
224
+ def __init__(self, ham):
225
+ super(MapVertical, self).__init__(ham)
226
+ self.descendant = None
227
+ self.map = None
228
+
229
+ def add_map(self, HogMap):
230
+ """
231
+ Method to set the HOGsMap.
232
+
233
+ Args:
234
+ HogMap (:obj:`pyham.mapper.HOGsMap`): HOGsMap to add.
235
+
236
+ Raises:
237
+ TypeError: if HogMap is not :obj:`pyham.mapper.HOGsMap` or if a :obj:`pyham.mapper.HOGsMap` is already set.
238
+
239
+ """
240
+ if not isinstance(HogMap, HOGsMap):
241
+ raise TypeError("expect subclass obj of '{}', got {}"
242
+ .format(HOGsMap.__name__,
243
+ type(HogMap).__name__))
244
+ if self.map is not None:
245
+ raise TypeError("MapVertical can only contains one HOGMap object.")
246
+ self.ancestor = HogMap.ancestor
247
+ self.descendant = HogMap.descendant
248
+ self.map = HogMap
249
+
250
+ def get_lost(self):
251
+ """
252
+ Getter for lost genes.
253
+
254
+ Returns:
255
+ List of Ho.
256
+ """
257
+
258
+ return self.map.LOSS
259
+
260
+ def get_gained(self):
261
+ """
262
+ Getter for gained genes.
263
+
264
+ Returns:
265
+ List of Hn.
266
+
267
+ """
268
+ return self.map.GAIN
269
+
270
+ def get_retained(self):
271
+ """
272
+ Getter for retained genes.
273
+
274
+ Returns:
275
+ Dictionary of Ho mapped to their descendant Hy.
276
+ """
277
+
278
+ return self.map.RETAINED
279
+
280
+ def get_duplicated(self):
281
+ """
282
+ Getter for duplicated genes.
283
+
284
+ Returns:
285
+ Dictionary of Ho mapped to their list of descendants Hy.
286
+ """
287
+
288
+ return self.map.DUPLICATE
289
+
290
+ def get_number_duplications(self):
291
+ """
292
+ Getter of number of duplication events.
293
+
294
+ Returns:
295
+ int for number of duplications.
296
+ """
297
+
298
+ return self.map.number_duplication()
299
+
300
+
301
+ class MapLateral(MapResults):
302
+ """
303
+
304
+ Class to map HOGs between genomes through their ancestor.
305
+
306
+ Let's consider Go the oldest genome and Gn the youngest genomes with their respected HOGs Ho and Hn.
307
+
308
+ Attributes:
309
+ | descendant (:obj:`list`): list of Gn.
310
+ | map (:obj:`dict`): dictionary of Gn mapped to a HOGMap(Go,Gn).
311
+ | LOSS (:obj:`dict`): dictionary of Ho mapped to the list of Gn where this HOG is lost.
312
+ | GAIN (:obj:`dict`): dictionary of Gn mapped to their list of gained Hn.
313
+ | RETAINED (:obj:`dict`): dictionary of Ho mapped to a dict of Gn mapped to a Hn.
314
+ | DUPLICATE (:obj:`dict`): dictionary of Ho mapped to a dict of Gn mapped to a list of Hn.
315
+
316
+ """
317
+
318
+ def __init__(self, HAM):
319
+ super(MapLateral, self).__init__(HAM)
320
+ self.descendants = []
321
+ self.maps = {}
322
+ self.LOSS = None
323
+ self.GAIN = None
324
+ self.RETAINED = None
325
+ self.DUPLICATE = None
326
+
327
+ def add_map(self, HogMap):
328
+ """
329
+ Method to add the HOGsMap.
330
+
331
+ Args:
332
+ HogMap (:obj:`pyham.mapper.HOGsMap`): HOGsMap to add.
333
+
334
+ Raises:
335
+ TypeError: if HogMap is not :obj:`pyham.mapper.HOGsMap` or if HOGMap ancestor doesn't match the MapLateral one.
336
+ """
337
+
338
+ if not isinstance(HogMap, HOGsMap):
339
+ raise TypeError("expect subclass obj of '{}', got {}"
340
+ .format(HOGsMap.__name__,
341
+ type(HogMap).__name__))
342
+ if self.maps == {}:
343
+ self.ancestor = HogMap.ancestor
344
+ else:
345
+ if self.ancestor != HogMap.ancestor:
346
+ raise TypeError(
347
+ "You can only add map to MapLateral object that have the same ancestor. The current ancestor is {} and the map ancestor you try to add is {}.".format(
348
+ self.ancestor, HogMap.ancestor))
349
+ self.maps[HogMap.descendant] = HogMap
350
+ self.descendants.append(HogMap.descendant)
351
+
352
+ def get_lost(self):
353
+ """
354
+ Lazy getter for lost genes.
355
+
356
+ Returns:
357
+ dictionary of Ho -> [Gn].
358
+ """
359
+
360
+ if self.LOSS is None:
361
+ loss = {}
362
+ for genome, hmap in self.maps.items():
363
+ for lost_gene in hmap.LOSS:
364
+ loss.setdefault(lost_gene, []).append(genome)
365
+ self.LOSS = loss
366
+
367
+ return self.LOSS
368
+
369
+ def get_gained(self):
370
+ """
371
+ Lazy getter for gained genes.
372
+
373
+ Returns:
374
+ dictionary of Gn -> [Hn].
375
+ """
376
+ if self.GAIN is None:
377
+ gain = {}
378
+ for genome, hmap in self.maps.items():
379
+ gain[genome] = hmap.GAIN
380
+ self.GAIN = gain
381
+ return self.GAIN
382
+
383
+ def get_retained(self):
384
+ """
385
+ Lazy getter for retained genes.
386
+
387
+ Returns:
388
+ dictionary of Hi -> dict of Gn -> Hn.
389
+ """
390
+
391
+ if self.RETAINED is None:
392
+ single = {}
393
+ for genome, hmap in self.maps.items():
394
+ for hi, hj in hmap.RETAINED.items():
395
+ single.setdefault(hi, {})[genome] = hj
396
+ self.RETAINED = single
397
+
398
+ return self.RETAINED
399
+
400
+ def get_duplicated(self):
401
+ """
402
+ Lazy getter for duplicated genes.
403
+
404
+ Returns:
405
+ dictionary of Hi -> dict of Gn -> list of Hn.
406
+ """
407
+ if self.DUPLICATE is None:
408
+ duplicate = {}
409
+ for genome, hmap in self.maps.items():
410
+ for hi, list_hj in hmap.DUPLICATE.items():
411
+ duplicate.setdefault(hi, {})[genome] = list_hj
412
+ self.DUPLICATE = duplicate
413
+
414
+ return self.DUPLICATE