Skip to content

Commit e31a444

Browse files
etalMarkusPiotrowski
authored andcommitted
TreeConstruction: Add 'skip_letters' parameter to DistanceCalculator (biopython#491)
When scoring with a distance matrix other than 'identity', the gap and stop characters '-' and '*' are skipped & not counted toward the total score. With the 'identity' model, the default for DistanceCalculator, these characters are retained and compared. That's potentially surprising, so this patch exposes the 'skip_letters' keyword argument in the constructor so that the scoring/skipping behavior can be changed for any model. In a future release, it would be better to set the default value of skip_letters=('-', '*') and have 'identity' use this default value like the other models do. For now, we'll leave a shim for backward compatibility.
1 parent 3b930da commit e31a444

1 file changed

Lines changed: 14 additions & 9 deletions

File tree

‎Bio/Phylo/TreeConstruction.py‎

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -401,8 +401,16 @@ class DistanceCalculator(object):
401401

402402
models = ['identity'] + dna_models + protein_models
403403

404-
def __init__(self, model='identity'):
404+
def __init__(self, model='identity', skip_letters=None):
405405
"""Initialize with a distance model."""
406+
# Shim for backward compatibility (#491)
407+
if skip_letters:
408+
self.skip_letters = skip_letters
409+
elif model == 'identity':
410+
self.skip_letters = ()
411+
else:
412+
self.skip_letters = ('-', '*')
413+
406414
if model == 'identity':
407415
self.scoring_matrix = None
408416
elif model in self.dna_models:
@@ -426,11 +434,10 @@ def _pairwise(self, seq1, seq2):
426434
if self.scoring_matrix:
427435
max_score1 = 0
428436
max_score2 = 0
429-
skip_letters = ['-', '*']
430437
for i in range(0, len(seq1)):
431438
l1 = seq1[i]
432439
l2 = seq2[i]
433-
if l1 in skip_letters or l2 in skip_letters:
440+
if l1 in self.skip_letters or l2 in self.skip_letters:
434441
continue
435442
if l1 not in self.scoring_matrix.names:
436443
raise ValueError("Bad alphabet '%s' in sequence '%s' at position '%s'"
@@ -445,13 +452,11 @@ def _pairwise(self, seq1, seq2):
445452
max_score = max(max_score1, max_score2)
446453
else:
447454
# Score by character identity, not skipping any special letters
448-
for i in range(0, len(seq1)):
449-
l1 = seq1[i]
450-
l2 = seq2[i]
451-
if l1 == l2:
452-
score += 1
455+
score = sum(l1 == l2
456+
for l1, l2 in zip(seq1, seq2)
457+
if l1 not in self.skip_letters
458+
and l2 not in self.skip_letters)
453459
max_score = len(seq1)
454-
455460
if max_score == 0:
456461
return 1 # max possible scaled distance
457462
return 1 - (score * 1.0 / max_score)

0 commit comments

Comments
 (0)