This file is indexed.

/usr/lib/python2.7/dist-packages/csb/bio/sequence/alignment.py is in python-csb 1.2.2+dfsg-2ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
"""
Collection of sequence alignment algorithms.

@note: The classes in this module have been optimized for performance.
       Think twice before switching a field to a generally nicer property
       access, because it turns out that these things often add significant
       constants to the running time of a dynamic programming algorithm.
"""

from csb.bio.sequence import AbstractSequence, SequenceAlignment, RichSequence, ResidueInfo
from abc import ABCMeta, abstractmethod


class ResidueNotFoundError(KeyError):
    pass


class AbstractScoringMatrix(object):
    """
    Defines a pairwise sequence alignment scoring function.
    """
    
    __metaclass__ = ABCMeta
    
    @abstractmethod
    def score(self, x, y):
        """
        Return the pairwise score of residues C{x} and C{y}.
        C{x} and C{y} must be comparable (e.g. implement __eq__ and __hash__).
        
        @param x: first residue
        @type x: object
        @param y: second residue
        @type y: object
        
        @rtype: float
        
        @raise ResidueNotFoundError: if C{x} or C{y} cannot be handled by this
        scoring matrix          
        """
        pass
    
class IdentityMatrix(AbstractScoringMatrix):
    """
    Simple identity-based scoring matrix.
    
    @param match: score for a match
    @type match: float
    @param mismatch: score for a mismatch
    @type mismatch: float
    """

    def __init__(self, match=1, mismatch=-1):
        
        self._match = float(match)
        self._mismatch = float(mismatch)
        
    @property
    def match(self):
        """
        Score for a match
        @rtype: float
        """
        return self._match
    
    @property
    def mismatch(self):
        """
        Score for a mismatch
        @rtype: float
        """        
        return self._mismatch
    
    def score(self, x, y):
        
        if x == y:
            return self._match
        else:
            return self._mismatch      
        
class SimilarityMatrix(AbstractScoringMatrix):
    """
    Similarity scoring matrix.
    
    @param matrix: 
    """
    
    BLOSUM62 = { 
        'A': { 'A': 4.0, 'R':-1.0, 'N':-2.0, 'D':-2.0, 'C': 0.0, 'Q':-1.0, 'E':-1.0, 'G': 0.0, 'H':-2.0, 'I':-1.0, 'L':-1.0, 'K':-1.0, 'M':-1.0, 'F':-2.0, 'P':-1.0, 'S': 1.0, 'T': 0.0, 'W':-3.0, 'Y':-2.0, 'V': 0.0, 'B':-2.0, 'Z':-1.0, 'X': 0.0, '*':-4.0 },
        'R': { 'A':-1.0, 'R': 5.0, 'N': 0.0, 'D':-2.0, 'C':-3.0, 'Q': 1.0, 'E': 0.0, 'G':-2.0, 'H': 0.0, 'I':-3.0, 'L':-2.0, 'K': 2.0, 'M':-1.0, 'F':-3.0, 'P':-2.0, 'S':-1.0, 'T':-1.0, 'W':-3.0, 'Y':-2.0, 'V':-3.0, 'B':-1.0, 'Z': 0.0, 'X':-1.0, '*':-4.0 },
        'N': { 'A':-2.0, 'R': 0.0, 'N': 6.0, 'D': 1.0, 'C':-3.0, 'Q': 0.0, 'E': 0.0, 'G': 0.0, 'H': 1.0, 'I':-3.0, 'L':-3.0, 'K': 0.0, 'M':-2.0, 'F':-3.0, 'P':-2.0, 'S': 1.0, 'T': 0.0, 'W':-4.0, 'Y':-2.0, 'V':-3.0, 'B': 3.0, 'Z': 0.0, 'X':-1.0, '*':-4.0 },
        'D': { 'A':-2.0, 'R':-2.0, 'N': 1.0, 'D': 6.0, 'C':-3.0, 'Q': 0.0, 'E': 2.0, 'G':-1.0, 'H':-1.0, 'I':-3.0, 'L':-4.0, 'K':-1.0, 'M':-3.0, 'F':-3.0, 'P':-1.0, 'S': 0.0, 'T':-1.0, 'W':-4.0, 'Y':-3.0, 'V':-3.0, 'B': 4.0, 'Z': 1.0, 'X':-1.0, '*':-4.0 },
        'C': { 'A': 0.0, 'R':-3.0, 'N':-3.0, 'D':-3.0, 'C': 9.0, 'Q':-3.0, 'E':-4.0, 'G':-3.0, 'H':-3.0, 'I':-1.0, 'L':-1.0, 'K':-3.0, 'M':-1.0, 'F':-2.0, 'P':-3.0, 'S':-1.0, 'T':-1.0, 'W':-2.0, 'Y':-2.0, 'V':-1.0, 'B':-3.0, 'Z':-3.0, 'X':-2.0, '*':-4.0 },
        'Q': { 'A':-1.0, 'R': 1.0, 'N': 0.0, 'D': 0.0, 'C':-3.0, 'Q': 5.0, 'E': 2.0, 'G':-2.0, 'H': 0.0, 'I':-3.0, 'L':-2.0, 'K': 1.0, 'M': 0.0, 'F':-3.0, 'P':-1.0, 'S': 0.0, 'T':-1.0, 'W':-2.0, 'Y':-1.0, 'V':-2.0, 'B': 0.0, 'Z': 3.0, 'X':-1.0, '*':-4.0 },
        'E': { 'A':-1.0, 'R': 0.0, 'N': 0.0, 'D': 2.0, 'C':-4.0, 'Q': 2.0, 'E': 5.0, 'G':-2.0, 'H': 0.0, 'I':-3.0, 'L':-3.0, 'K': 1.0, 'M':-2.0, 'F':-3.0, 'P':-1.0, 'S': 0.0, 'T':-1.0, 'W':-3.0, 'Y':-2.0, 'V':-2.0, 'B': 1.0, 'Z': 4.0, 'X':-1.0, '*':-4.0 },
        'G': { 'A': 0.0, 'R':-2.0, 'N': 0.0, 'D':-1.0, 'C':-3.0, 'Q':-2.0, 'E':-2.0, 'G': 6.0, 'H':-2.0, 'I':-4.0, 'L':-4.0, 'K':-2.0, 'M':-3.0, 'F':-3.0, 'P':-2.0, 'S': 0.0, 'T':-2.0, 'W':-2.0, 'Y':-3.0, 'V':-3.0, 'B':-1.0, 'Z':-2.0, 'X':-1.0, '*':-4.0 },
        'H': { 'A':-2.0, 'R': 0.0, 'N': 1.0, 'D':-1.0, 'C':-3.0, 'Q': 0.0, 'E': 0.0, 'G':-2.0, 'H': 8.0, 'I':-3.0, 'L':-3.0, 'K':-1.0, 'M':-2.0, 'F':-1.0, 'P':-2.0, 'S':-1.0, 'T':-2.0, 'W':-2.0, 'Y': 2.0, 'V':-3.0, 'B': 0.0, 'Z': 0.0, 'X':-1.0, '*':-4.0 },
        'I': { 'A':-1.0, 'R':-3.0, 'N':-3.0, 'D':-3.0, 'C':-1.0, 'Q':-3.0, 'E':-3.0, 'G':-4.0, 'H':-3.0, 'I': 4.0, 'L': 2.0, 'K':-3.0, 'M': 1.0, 'F': 0.0, 'P':-3.0, 'S':-2.0, 'T':-1.0, 'W':-3.0, 'Y':-1.0, 'V': 3.0, 'B':-3.0, 'Z':-3.0, 'X':-1.0, '*':-4.0 },
        'L': { 'A':-1.0, 'R':-2.0, 'N':-3.0, 'D':-4.0, 'C':-1.0, 'Q':-2.0, 'E':-3.0, 'G':-4.0, 'H':-3.0, 'I': 2.0, 'L': 4.0, 'K':-2.0, 'M': 2.0, 'F': 0.0, 'P':-3.0, 'S':-2.0, 'T':-1.0, 'W':-2.0, 'Y':-1.0, 'V': 1.0, 'B':-4.0, 'Z':-3.0, 'X':-1.0, '*':-4.0 },
        'K': { 'A':-1.0, 'R': 2.0, 'N': 0.0, 'D':-1.0, 'C':-3.0, 'Q': 1.0, 'E': 1.0, 'G':-2.0, 'H':-1.0, 'I':-3.0, 'L':-2.0, 'K': 5.0, 'M':-1.0, 'F':-3.0, 'P':-1.0, 'S': 0.0, 'T':-1.0, 'W':-3.0, 'Y':-2.0, 'V':-2.0, 'B': 0.0, 'Z': 1.0, 'X':-1.0, '*':-4.0 },
        'M': { 'A':-1.0, 'R':-1.0, 'N':-2.0, 'D':-3.0, 'C':-1.0, 'Q': 0.0, 'E':-2.0, 'G':-3.0, 'H':-2.0, 'I': 1.0, 'L': 2.0, 'K':-1.0, 'M': 5.0, 'F': 0.0, 'P':-2.0, 'S':-1.0, 'T':-1.0, 'W':-1.0, 'Y':-1.0, 'V': 1.0, 'B':-3.0, 'Z':-1.0, 'X':-1.0, '*':-4.0 },
        'F': { 'A':-2.0, 'R':-3.0, 'N':-3.0, 'D':-3.0, 'C':-2.0, 'Q':-3.0, 'E':-3.0, 'G':-3.0, 'H':-1.0, 'I': 0.0, 'L': 0.0, 'K':-3.0, 'M': 0.0, 'F': 6.0, 'P':-4.0, 'S':-2.0, 'T':-2.0, 'W': 1.0, 'Y': 3.0, 'V':-1.0, 'B':-3.0, 'Z':-3.0, 'X':-1.0, '*':-4.0 },
        'P': { 'A':-1.0, 'R':-2.0, 'N':-2.0, 'D':-1.0, 'C':-3.0, 'Q':-1.0, 'E':-1.0, 'G':-2.0, 'H':-2.0, 'I':-3.0, 'L':-3.0, 'K':-1.0, 'M':-2.0, 'F':-4.0, 'P': 7.0, 'S':-1.0, 'T':-1.0, 'W':-4.0, 'Y':-3.0, 'V':-2.0, 'B':-2.0, 'Z':-1.0, 'X':-2.0, '*':-4.0 },
        'S': { 'A': 1.0, 'R':-1.0, 'N': 1.0, 'D': 0.0, 'C':-1.0, 'Q': 0.0, 'E': 0.0, 'G': 0.0, 'H':-1.0, 'I':-2.0, 'L':-2.0, 'K': 0.0, 'M':-1.0, 'F':-2.0, 'P':-1.0, 'S': 4.0, 'T': 1.0, 'W':-3.0, 'Y':-2.0, 'V':-2.0, 'B': 0.0, 'Z': 0.0, 'X': 0.0, '*':-4.0 },
        'T': { 'A': 0.0, 'R':-1.0, 'N': 0.0, 'D':-1.0, 'C':-1.0, 'Q':-1.0, 'E':-1.0, 'G':-2.0, 'H':-2.0, 'I':-1.0, 'L':-1.0, 'K':-1.0, 'M':-1.0, 'F':-2.0, 'P':-1.0, 'S': 1.0, 'T': 5.0, 'W':-2.0, 'Y':-2.0, 'V': 0.0, 'B':-1.0, 'Z':-1.0, 'X': 0.0, '*':-4.0 },
        'W': { 'A':-3.0, 'R':-3.0, 'N':-4.0, 'D':-4.0, 'C':-2.0, 'Q':-2.0, 'E':-3.0, 'G':-2.0, 'H':-2.0, 'I':-3.0, 'L':-2.0, 'K':-3.0, 'M':-1.0, 'F': 1.0, 'P':-4.0, 'S':-3.0, 'T':-2.0, 'W': 11.0,'Y': 2.0, 'V':-3.0, 'B':-4.0, 'Z':-3.0, 'X':-2.0, '*':-4.0 },
        'Y': { 'A':-2.0, 'R':-2.0, 'N':-2.0, 'D':-3.0, 'C':-2.0, 'Q':-1.0, 'E':-2.0, 'G':-3.0, 'H': 2.0, 'I':-1.0, 'L':-1.0, 'K':-2.0, 'M':-1.0, 'F': 3.0, 'P':-3.0, 'S':-2.0, 'T':-2.0, 'W': 2.0, 'Y': 7.0, 'V':-1.0, 'B':-3.0, 'Z':-2.0, 'X':-1.0, '*':-4.0 },
        'V': { 'A': 0.0, 'R':-3.0, 'N':-3.0, 'D':-3.0, 'C':-1.0, 'Q':-2.0, 'E':-2.0, 'G':-3.0, 'H':-3.0, 'I': 3.0, 'L': 1.0, 'K':-2.0, 'M': 1.0, 'F':-1.0, 'P':-2.0, 'S':-2.0, 'T': 0.0, 'W':-3.0, 'Y':-1.0, 'V': 4.0, 'B':-3.0, 'Z':-2.0, 'X':-1.0, '*':-4.0 },
        'B': { 'A':-2.0, 'R':-1.0, 'N': 3.0, 'D': 4.0, 'C':-3.0, 'Q': 0.0, 'E': 1.0, 'G':-1.0, 'H': 0.0, 'I':-3.0, 'L':-4.0, 'K': 0.0, 'M':-3.0, 'F':-3.0, 'P':-2.0, 'S': 0.0, 'T':-1.0, 'W':-4.0, 'Y':-3.0, 'V':-3.0, 'B': 4.0, 'Z': 1.0, 'X':-1.0, '*':-4.0 },
        'Z': { 'A':-1.0, 'R': 0.0, 'N': 0.0, 'D': 1.0, 'C':-3.0, 'Q': 3.0, 'E': 4.0, 'G':-2.0, 'H': 0.0, 'I':-3.0, 'L':-3.0, 'K': 1.0, 'M':-1.0, 'F':-3.0, 'P':-1.0, 'S': 0.0, 'T':-1.0, 'W':-3.0, 'Y':-2.0, 'V':-2.0, 'B': 1.0, 'Z': 4.0, 'X':-1.0, '*':-4.0 },
        'X': { 'A': 0.0, 'R':-1.0, 'N':-1.0, 'D':-1.0, 'C':-2.0, 'Q':-1.0, 'E':-1.0, 'G':-1.0, 'H':-1.0, 'I':-1.0, 'L':-1.0, 'K':-1.0, 'M':-1.0, 'F':-1.0, 'P':-2.0, 'S': 0.0, 'T': 0.0, 'W':-2.0, 'Y':-1.0, 'V':-1.0, 'B':-1.0, 'Z':-1.0, 'X':-1.0, '*':-4.0 },
        '*': { 'A':-4.0, 'R':-4.0, 'N':-4.0, 'D':-4.0, 'C':-4.0, 'Q':-4.0, 'E':-4.0, 'G':-4.0, 'H':-4.0, 'I':-4.0, 'L':-4.0, 'K':-4.0, 'M':-4.0, 'F':-4.0, 'P':-4.0, 'S':-4.0, 'T':-4.0, 'W':-4.0, 'Y':-4.0, 'V':-4.0, 'B':-4.0, 'Z':-4.0, 'X':-4.0, '*': 1.0 }
    }
    
    def __init__(self, matrix=BLOSUM62):
        self._matrix = matrix        
        
    def score(self, x, y):
        try:
            return self._matrix[x][y]
        except KeyError as ke:
            raise ResidueNotFoundError(ke.message)
      
    @staticmethod
    def parse(string):
        """
        Parse a standard scoring matrix file, where the first row and
        column are residue labels.
        
        @param string: scoring matrix string
        @type string: str
        
        @rtype: L{SimilarityMatrix}
        """
        
        residues = {}
        matrix = {}
        
        for line in string.splitlines():
            if not line.strip() or line.startswith("#"):
                continue
            
            if not residues:
                residues = line.split()
                
            else:
                items = line.split()
                if len(items) != len(residues) + 1:
                    raise ValueError("{0} scoring columns expected".format(len(residues)))
                                    
                try:
                    aa, scores = items[0], map(float, items[1:])
                    matrix[aa] = dict((residues[i], s) for i, s in enumerate(scores))
                except (KeyError, ValueError):
                    raise ValueError("Corrupt scoring matrix")
        
        return SimilarityMatrix(matrix)
    
        
class AbstractAlignmentAlgorithm(object):
    """
    Base class for all sequence alignment algorithms.
    
    This class was designed with simple sequence alignment algorithms in mind.
    Implementors have full control over the behavior of the scoring function and
    the dynamic programming matrix, but implementing things that require
    additional matrices (such as affine gap penalties) might be trickier.
    
    @param scoring: scoring matrix 
    @type scoring: L{AbstractScoringMatrix}
    @param gap: simple gap penalty
    @type gap: float
    """
    
    __metaclass__ = ABCMeta
    
    def __init__(self, scoring=IdentityMatrix(), gap=0):
        
        if not isinstance(scoring, AbstractScoringMatrix):
            raise TypeError(scoring)
        
        self._gap = float(gap)
        self._scoring = scoring
        
    @property
    def gap(self):
        """
        Simple gap penalty
        @rtype: float 
        """
        return self._gap

    @property
    def scoring_matrix(self):
        """
        Scoring matrix 
        @rtype: L{AbstractScoringMatrix} 
        """        
        return self._scoring

    def align(self, query, subject):
        """
        Align two sequences and return the optimal alignment.
        
        @param query: first sequence
        @type query: L{AbstractSequence}
        @param subject: second sequence
        @type subject: L{AbstractSequence}
        
        @rtype: L{AlignmentResult}     
        """
        if query.length == 0 or subject.length == 0:
            raise ValueError("Can't align zero length sequence")        
        
        # working with string sequences results in a massive speed-up
        qseq = ["*"] + self._sequence(query)
        sseq = ["*"] + self._sequence(subject)
        
        # 1. create a dynamic programming matrix
        matrix = []        
        rows, cols = len(query), len(subject)
        
        for i in range(rows + 1):
            matrix.append([])
            for j in range(cols + 1):
                matrix[i].append(None)                    

        # 2. initialize the first row and column  
        self._initialize(matrix)
            
        # fill
        for i in range(1, rows + 1):
            for j in range(1, cols + 1):
                score = self._score(qseq[i], sseq[j])
                self._fill(matrix, i, j, score)
        
        # 3. compute alignment          
        return self._traceback(matrix, query, subject)    
    
    def _sequence(self, s):
        """
        Extract and return the string sequence of {s}.
        
        @param s: sequence object
        @type s: L{AbstractSequence}
        
        @rtype: list of str
        """
        return list(s.sequence)
    
    @abstractmethod
    def _initialize(self, matrix):
        """
        Initialize (typically the first row and column) of the dynamic
        programming matrix.
        
        @param matrix: list (2D)
        @type matrix: list
        """
        pass        
                                    
    def _score(self, residue1, residue2):
        """
        Retrieve the pairwise score of two residues using the current
        scoring matrix.
        
        @rtype: float
        """      
        return self._scoring.score(residue1, residue2)
    
    def _fill(self, matrix, i, j, score):
        """
        Compute and set the best score that leads to cell i,j in the dynamic
        programming matrix: right, down or diagonal.
        
        See also L{AbstractAlignmentAlgorithm._max}.
        
        @param score: pairwise score at matrix[i][j]
        @type score: float
        @return: the best score
        @rtype: float
        """
        
        match = matrix[i-1][j-1] + score
        insertion = matrix[i][j-1] + self._gap                
        deletion = matrix[i-1][j] + self._gap
        
        best = self._max(match, insertion, deletion)
        matrix[i][j] = best
        
        return best

    @abstractmethod    
    def _max(self, match, insertion, deletion):
        """
        Choose the best score among all given possibilities:
        scores for match, insertion and deletion. This will determine
        the direction taken at each step while building the dynamic programming
        matrix (diagonal, down or right). 

        This is an expected notable point of divergence for most sequence
        alignment algorithms.
        """
        pass

    def _traceback(self, m, seq1, seq2):
        """
        Trace back and return the optimal alignment.
        """

        query = []
        subject = []        

        # working with string sequences results in a massive speed-up
        qseq = ["*"] + self._sequence(seq1)
        sseq = ["*"] + self._sequence(seq2)

        i, j = self._terminus(m)
        qstart, start = i, j
        qend, end = i, j
        score = m[i][j]        
        
        while self._expandable(m, i, j):

            if i > 0 and j > 0 and m[i][j] == (m[i-1][j-1] + self._score(qseq[i], sseq[j])):
                query.append(seq1.residues[i])
                subject.append(seq2.residues[j])
                qstart, start = i, j
                i, j = i - 1, j - 1 
                
            elif i > 0 and  m[i][j] == (m[i-1][j] + self._gap):
                query.append(seq1.residues[i])
                subject.append(ResidueInfo(-1, seq2.alphabet.GAP))
                qstart = i
                i = i - 1
                
            elif j > 0 and  m[i][j] == (m[i][j-1] + self._gap):
                query.append(ResidueInfo(-1, seq1.alphabet.GAP))
                subject.append(seq2.residues[j])
                start = j
                j = j - 1
                
            else:
                assert False
                
        query.reverse()
        subject.reverse()
    
        aligned_query = RichSequence(seq1.id, seq1.header, query, seq1.type)
        aligned_subject = RichSequence(seq2.id, seq2.header, subject, seq2.type)
          
        return AlignmentResult(score, aligned_query, aligned_subject, qstart, qend, start, end)     

    @abstractmethod      
    def _terminus(self, matrix):
        """
        Find the coordinates of the optimal alignment's right endpoint in the
        dynamic programming matrix. This is the starting point of a traceback.
        
        @param matrix: the complete dynamic programming matrix
        @type matrix: 2D list
        
        @rtype: 2-tuple (i, j)
        """
        pass
    
    @abstractmethod
    def _expandable(self, i, j):
        """
        Return True if the traceback procedure must not terminate at
        position C{i,j} in the dynamic programming matrix.
        
        @rtype: bool
        """
        pass
    

class GlobalAlignmentAlgorithm(AbstractAlignmentAlgorithm):
    """
    Needleman-Wunsch global sequence alignment.
    """

    def __init__(self, scoring=IdentityMatrix(), gap=0):
        super(GlobalAlignmentAlgorithm, self).__init__(scoring, gap)
            
    def _initialize(self, matrix):
        
        for i in range(len(matrix)):
            matrix[i][0] = self._gap * i
        for j in range(len(matrix[0])):            
            matrix[0][j] = self._gap * j       

    def _max(self, match, insertion, deletion):
        return max(match, insertion, deletion)    
    
    def _terminus(self, matrix):
        
        i = len(matrix) - 1
        j = len(matrix[0]) - 1
        
        return (i, j)        

    def _expandable(self, matrix, i, j):
        return i > 0 or j > 0        
    
class LocalAlignmentAlgorithm(AbstractAlignmentAlgorithm):
    """
    Smith-Waterman local sequence alignment.
    """
        
    START = 0
    """
    Score for initiation of a new local alignment
    """

    def __init__(self, scoring=IdentityMatrix(), gap=-1):
        super(LocalAlignmentAlgorithm, self).__init__(scoring, gap)
            
    def _initialize(self, matrix):
        
        for i in range(len(matrix)):
            matrix[i][0] = LocalAlignmentAlgorithm.START
        for j in range(len(matrix[0])):            
            matrix[0][j] = LocalAlignmentAlgorithm.START      

    def _max(self, match, insertion, deletion):
        return max(match, insertion, deletion, LocalAlignmentAlgorithm.START)        

    def _terminus(self, matrix):
        
        maxi, maxj = 0, 0
        
        for i in range(len(matrix)):
            for j in range(len(matrix[i])):
                if matrix[i][j] > matrix[maxi][maxj]:
                    maxi, maxj = i, j
        
        return (maxi, maxj)
    
    def _expandable(self, matrix, i, j):
        return matrix[i][j] != LocalAlignmentAlgorithm.START  
    

class AlignmentResult(object):
    """
    Represents a pairwise sequence alignment result.
    
    @param score: raw alignment score
    @type score: float
    @param query: aligned query sequence (with gaps)
    @type query: L{AbstractSequence}
    @param subject: aligned subject sequence (with gaps)
    @type subject: L{AbstractSequence}     
    @param qstart: query start position
    @type qstart: int
    @param qend: query end position
    @type qend: int
    @param start: subject start position
    @type start: int
    @param end: subject end position
    @type end: int  
    """
    
    def __init__(self, score, query, subject, qstart, qend, start, end):
        
        if not isinstance(query, AbstractSequence):
            raise TypeError(query)
        if not isinstance(subject, AbstractSequence):
            raise TypeError(query)
        
        if not (len(query) == len(subject)):
            raise ValueError("Corrupt alignment")
                        
        self._score = float(score)
        self._query = query
        self._subject = subject
        self._qstart = int(qstart)
        self._qend = int(qend)
        self._start = int(start)
        self._end = int(end)
        self._identicals = 0
        self._gaps = 0        
        self._length = 0
        
        if query.length > 0 and subject.length > 0:

            if not 1 <= qstart <= qend:
                raise ValueError("Invalid query start/end positions")
            if not 1 <= start <= end:
                raise ValueError("Invalid subject start/end positions")
                        
            qgap = query.alphabet.GAP
            sgap = subject.alphabet.GAP
            
            for q, s in zip(query, subject):
                if q.type == qgap or s.type == sgap:
                    self._gaps += 1
                elif q.type == s.type:
                    self._identicals += 1
                    
            self._length = (self._gaps + (qend - qstart + 1) + (end - start + 1)) / 2
            
        else:
            if (score + qstart + qend + start + end) != 0:
                raise ValueError("Corrupt alignment")
            self._length = 0
                 
        
    def __str__(self):
        string = "{0.qstart:5} {0.query.sequence:} {0.qend:<5}\n"
        string += "{0.start:5} {0.subject.sequence:} {0.end:<5}"
        return string.format(self)        
    
    @property
    def is_empty(self):
        """
        Return True if this is an empty alignment (i.e. no matches)
        @rtype: bool
        """
        return self.length == 0 or self.gaps == self.length   
        
    @property
    def score(self):
        """
        Raw alignment score
        @rtype: float
        """
        return self._score
    
    @property
    def query(self):
        """
        Aligned query sequence (with gaps)
        @rtype: L{AbstractSequence}
        """
        return self._query
    
    @property
    def subject(self):
        """
        Aligned subject sequence (with gaps)
        @rtype: L{AbstractSequence}        
        """        
        return self._subject
    
    @property
    def qstart(self):
        """
        Query start position
        @rtype: int
        """        
        return self._qstart
    
    @property
    def qend(self):
        """
        Query end position
        @rtype: int
        """        
        return self._qend
    
    @property
    def start(self):
        """
        Subject start position
        @rtype: int
        """                
        return self._start
    
    @property
    def end(self):
        """
        Subject end position        
        @rtype: int
        """                
        return self._end
    
    @property
    def identicals(self):
        """
        Number of identical residues
        @rtype: int
        """                
        return self._identicals
    
    @property
    def identity(self):
        """
        Percentage of identical residues
        @rtype: int
        """                
        return float(self._identicals) / self._length
    
    @property
    def gaps(self):
        """
        Total number of gaps (query + subject)
        @rtype: int
        """               
        return self._gaps
    
    @property
    def length(self):
        """
        Alignment length (query + subject + gaps / 2)
        @rtype: int
        """               
        return self._length
    
    def alignment(self):
        """
        @return: as a sequence alignment object
        @rtype: L{SequenceAlignment}
        """
        return SequenceAlignment([self.query, self.subject])