Skip to content

Commit 9816da0

Browse files
committed
Avoid a ZeroDivisionError in TreeConstruction.DistanceCalculator (#491)
Also add some comments and a line to the docstring to explain what's happening. In an alignment where a pair of sequences have no overlapping non-gap characters, there are no aligned characters to score. Instead, return the maximum possible distance (i.e. 1, since distances are scaled to [0,1]).
1 parent 35183e1 commit 9816da0

1 file changed

Lines changed: 10 additions & 3 deletions

File tree

‎Bio/Phylo/TreeConstruction.py‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -415,7 +415,11 @@ def __init__(self, model='identity'):
415415
+ ", ".join(self.models))
416416

417417
def _pairwise(self, seq1, seq2):
418-
"""Calculate pairwise distance from two sequences"""
418+
"""Calculate pairwise distance from two sequences.
419+
420+
Returns a value between 0 (identical sequences) and 1 (completely
421+
different, or seq1 is an empty string.)
422+
"""
419423
score = 0
420424
max_score = 0
421425
if self.scoring_matrix:
@@ -436,16 +440,19 @@ def _pairwise(self, seq1, seq2):
436440
max_score1 += self.scoring_matrix[l1, l1]
437441
max_score2 += self.scoring_matrix[l2, l2]
438442
score += self.scoring_matrix[l1, l2]
439-
440-
max_score = max_score1 > max_score2 and max_score1 or max_score2
443+
# Take the higher score if the matrix is asymmetrical
444+
max_score = max(max_score1, max_score2)
441445
else:
446+
# Score by character identity, not skipping any special letters
442447
for i in range(0, len(seq1)):
443448
l1 = seq1[i]
444449
l2 = seq2[i]
445450
if l1 == l2:
446451
score += 1
447452
max_score = len(seq1)
448453

454+
if max_score == 0:
455+
return 1 # max possible scaled distance
449456
return 1 - (score * 1.0 / max_score)
450457

451458
def get_distance(self, msa):

0 commit comments

Comments
 (0)