File: bigpsl.py

package info (click to toggle)
python-biopython 1.85%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 126,372 kB
  • sloc: xml: 1,047,995; python: 332,722; ansic: 16,944; sql: 1,208; makefile: 140; sh: 81
file content (613 lines) | stat: -rw-r--r-- 23,407 bytes parent folder | download
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
# Copyright 2022 by Michiel de Hoon.  All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Bio.Align support for alignment files in the bigPsl format.

A bigPsl file is a bigBed file with a BED12+13 format consisting of the 12
predefined BED fields and 13 custom fields defined in the autoSql file
bigPsl.as. This module uses the Bio.Align.bigbed module to parse the file,
but stores the data in a PSL-consistent manner as defined in bigPsl.as. As the
bigPsl format is a special case of the bigBed format, bigPsl files are binary
and are indexed as bigBed files.

See http://genome.ucsc.edu/goldenPath/help/bigPsl.html for more information.

You are expected to use this module via the Bio.Align functions.
"""

import numpy as np

from Bio.Align import Alignment
from Bio.Align import Alignments
from Bio.Align import bigbed
from Bio.Align.bigbed import AutoSQLTable
from Bio.Align.bigbed import Field
from Bio.Seq import reverse_complement
from Bio.Seq import Seq
from Bio.Seq import UndefinedSequenceError
from Bio.SeqFeature import Location
from Bio.SeqFeature import SeqFeature
from Bio.SeqIO.InsdcIO import _insdc_location_string
from Bio.SeqRecord import SeqRecord

declaration = AutoSQLTable(
    "bigPsl",
    "bigPsl pairwise alignment",
    [
        Field(
            as_type="string",
            name="chrom",
            comment="Reference sequence chromosome or scaffold",
        ),
        Field(
            as_type="uint",
            name="chromStart",
            comment="Start position in chromosome",
        ),
        Field(
            as_type="uint",
            name="chromEnd",
            comment="End position in chromosome",
        ),
        Field(
            as_type="string",
            name="name",
            comment="Name or ID of item, ideally both human readable and unique",
        ),
        Field(
            as_type="uint",
            name="score",
            comment="Score (0-1000)",
        ),
        Field(
            as_type="char[1]",
            name="strand",
            comment="+ or - indicates whether the query aligns to the + or - strand on the reference",
        ),
        Field(
            as_type="uint",
            name="thickStart",
            comment="Start of where display should be thick (start codon)",
        ),
        Field(
            as_type="uint",
            name="thickEnd",
            comment="End of where display should be thick (stop codon)",
        ),
        Field(
            as_type="uint",
            name="reserved",
            comment="RGB value (use R,G,B string in input file)",
        ),
        Field(
            as_type="int",
            name="blockCount",
            comment="Number of blocks",
        ),
        Field(
            as_type="int[blockCount]",
            name="blockSizes",
            comment="Comma separated list of block sizes",
        ),
        Field(
            as_type="int[blockCount]",
            name="chromStarts",
            comment="Start positions relative to chromStart",
        ),
        Field(
            as_type="uint",
            name="oChromStart",
            comment="Start position in other chromosome",
        ),
        Field(
            as_type="uint",
            name="oChromEnd",
            comment="End position in other chromosome",
        ),
        Field(
            as_type="char[1]",
            name="oStrand",
            comment="+ or -, - means that psl was reversed into BED-compatible coordinates",
        ),
        Field(
            as_type="uint",
            name="oChromSize",
            comment="Size of other chromosome.",
        ),
        Field(
            as_type="int[blockCount]",
            name="oChromStarts",
            comment="Start positions relative to oChromStart or from oChromStart+oChromSize depending on strand",
        ),
        Field(
            as_type="lstring",
            name="oSequence",
            comment="Sequence on other chrom (or edit list, or empty)",
        ),
        Field(
            as_type="string",
            name="oCDS",
            comment="CDS in NCBI format",
        ),
        Field(
            as_type="uint",
            name="chromSize",
            comment="Size of target chromosome",
        ),
        Field(
            as_type="uint",
            name="match",
            comment="Number of bases matched.",
        ),
        Field(
            as_type="uint",
            name="misMatch",
            comment="Number of bases that don't match",
        ),
        Field(
            as_type="uint",
            name="repMatch",
            comment="Number of bases that match but are part of repeats",
        ),
        Field(
            as_type="uint",
            name="nCount",
            comment="Number of 'N' bases",
        ),
        Field(
            as_type="uint",
            name="seqType",
            comment="0=empty, 1=nucleotide, 2=amino_acid",
        ),
    ],
)


class AlignmentWriter(bigbed.AlignmentWriter):
    """Alignment file writer for the bigPsl file format."""

    fmt = "bigPsl"

    def __init__(
        self,
        target,
        targets=None,
        compress=True,
        extraIndex=(),
        cds=False,
        fa=False,
        mask=None,
        wildcard="N",
    ):
        """Create an AlignmentWriter object.

        Arguments:
         - target      - output stream or file name.
         - targets     - A list of SeqRecord objects with the chromosomes in the
                         order as they appear in the alignments. The sequence
                         contents in each SeqRecord may be undefined, but the
                         sequence length must be defined, as in this example:

                         SeqRecord(Seq(None, length=248956422), id="chr1")

                         If targets is None (the default value), the alignments
                         must have an attribute .targets providing the list of
                         SeqRecord objects.
         - compress    - If True (default), compress data using zlib.
                         If False, do not compress data.
         - extraIndex  - List of strings with the names of extra columns to be
                         indexed.
                         Default value is an empty list.
         - cds         - If True, look for a query feature of type CDS and write
                         it in NCBI style in the PSL file (default: False).
         - fa          - If True, include the query sequence in the PSL file
                         (default: False).
         - mask        - Specify if repeat regions in the target sequence are
                         masked and should be reported in the `repMatches` field
                         instead of in the `matches` field.
                         Acceptable values are
                         None   : no masking (default);
                         "lower": masking by lower-case characters;
                         "upper": masking by upper-case characters.
         - wildcard    - Report alignments to the wildcard character in the
                         target or query sequence in the `nCount` field instead
                         of in the `matches`, `misMatches`, or `repMatches`
                         fields.
                         Default value is 'N'.
        """
        super().__init__(
            target,
            bedN=12,
            declaration=declaration,
            targets=targets,
            compress=compress,
            extraIndex=extraIndex,
        )
        self.cds = cds
        self.fa = fa
        self.mask = mask
        self.wildcard = wildcard

    def write_file(self, stream, alignments):
        """Write the file."""
        fixed_alignments = Alignments()
        cds = self.cds
        fa = self.fa
        for alignment in alignments:
            if not isinstance(alignment, Alignment):
                raise TypeError("Expected an Alignment object")
            coordinates = alignment.coordinates
            if not coordinates.size:  # alignment consists of gaps only
                continue
            target, query = alignment.sequences
            try:
                query = query.seq
            except AttributeError:
                pass
            try:
                target = target.seq
            except AttributeError:
                pass
            tSize = len(target)
            qSize = len(query)
            # fmt: off
            dnax = None  # set to True for translated DNA aligned to protein,
            # and to False for DNA/RNA aligned to DNA/RNA  # noqa: E114, E116
            # fmt: on
            if coordinates[1, 0] > coordinates[1, -1]:
                # DNA/RNA mapped to reverse strand of DNA/RNA
                strand = "-"
                query = reverse_complement(query)
                coordinates = coordinates.copy()
                coordinates[1, :] = qSize - coordinates[1, :]
            elif coordinates[0, 0] > coordinates[0, -1]:
                # protein mapped to reverse strand of DNA
                strand = "-"
                target = reverse_complement(target)
                coordinates = coordinates.copy()
                coordinates[0, :] = tSize - coordinates[0, :]
                dnax = True
            else:
                # mapped to forward strand
                strand = "+"
            wildcard = self.wildcard
            mask = self.mask
            # variable names follow those in the PSL file format specification
            matches = 0
            misMatches = 0
            repMatches = 0
            nCount = 0
            blockSizes = []
            qStarts = []
            tStarts = []
            tStart, qStart = coordinates[:, 0]
            for tEnd, qEnd in coordinates[:, 1:].transpose():
                if tStart == tEnd:
                    qStart = qEnd
                elif qStart == qEnd:
                    tStart = tEnd
                else:
                    tCount = tEnd - tStart
                    qCount = qEnd - qStart
                    tStarts.append(tStart)
                    qStarts.append(qStart)
                    blockSizes.append(qCount)
                    if tCount == qCount:
                        assert dnax is not True
                        dnax = False
                    else:
                        # translated DNA aligned to protein, typically generated by
                        # blat -t=dnax -q=prot
                        assert tCount == 3 * qCount
                        assert dnax is not False
                        dnax = True
                    tSeq = target[tStart:tEnd]
                    qSeq = query[qStart:qEnd]
                    try:
                        tSeq = bytes(tSeq)
                    except TypeError:  # string
                        tSeq = bytes(tSeq, "ASCII")
                    except UndefinedSequenceError:  # sequence contents is unknown
                        tSeq = None
                    try:
                        qSeq = bytes(qSeq)
                    except TypeError:  # string
                        qSeq = bytes(qSeq, "ASCII")
                    except UndefinedSequenceError:  # sequence contents is unknown
                        qSeq = None
                    if tSeq is None or qSeq is None:
                        # contents of at least one sequence is unknown;
                        # count all aligned letters as matches:
                        matches += qCount
                    else:
                        if mask == "lower":
                            for u1, u2, c1 in zip(tSeq.upper(), qSeq.upper(), tSeq):
                                if u1 == wildcard or u2 == wildcard:
                                    nCount += 1
                                elif u1 == u2:
                                    if u1 == c1:
                                        matches += 1
                                    else:
                                        repMatches += 1
                                else:
                                    misMatches += 1
                        elif mask == "upper":
                            for u1, u2, c1 in zip(tSeq.lower(), qSeq.lower(), tSeq):
                                if u1 == wildcard or u2 == wildcard:
                                    nCount += 1
                                elif u1 == u2:
                                    if u1 == c1:
                                        matches += 1
                                    else:
                                        repMatches += 1
                                else:
                                    misMatches += 1
                        else:
                            for u1, u2 in zip(tSeq.upper(), qSeq.upper()):
                                if u1 == wildcard or u2 == wildcard:
                                    nCount += 1
                                elif u1 == u2:
                                    matches += 1
                                else:
                                    misMatches += 1
                    tStart = tEnd
                    qStart = qEnd
            tStarts = np.array(tStarts)
            qStarts = np.array(qStarts)
            blockSizes = np.array(blockSizes)
            try:
                matches = alignment.matches
            except AttributeError:
                pass
            try:
                misMatches = alignment.misMatches
            except AttributeError:
                pass
            try:
                repMatches = alignment.repMatches
            except AttributeError:
                pass
            try:
                nCount = alignment.nCount
            except AttributeError:
                pass
            qStart = qStarts[0]  # start of alignment in query
            qEnd = qStarts[-1] + qCount  # end of alignment in query
            oStrand = "+"
            if strand == "-":
                if dnax is True:
                    oStrand = "-"
                    qStarts = qSize - (qStarts + blockSizes)
                    qStarts = qStarts[::-1]
                    alignment.coordinates = alignment.coordinates[:, ::-1]
                else:
                    qStart, qEnd = qSize - qEnd, qSize - qStart
            if fa is True:
                oSequence = str(alignment.query.seq)
            else:
                oSequence = ""
            if cds is True:
                for feature in alignment.query.features:
                    if feature.type == "CDS":
                        oCDS = _insdc_location_string(
                            feature.location, len(alignment.query)
                        )
                        break
                else:
                    oCDS = "n/a"
            else:
                oCDS = ""
            seqType = 0
            molecule_type = alignment.query.annotations.get("molecule_type")
            if molecule_type == "DNA":
                seqType = "1"
            elif molecule_type == "protein":
                seqType = "2"
            else:
                seqType = "0"
            alignment.annotations["oChromStart"] = str(qStart)
            alignment.annotations["oChromEnd"] = str(qEnd)
            alignment.annotations["oStrand"] = oStrand
            alignment.annotations["oChromSize"] = str(qSize)
            alignment.annotations["oChromStarts"] = ",".join(map(str, qStarts))
            alignment.annotations["oSequence"] = oSequence
            alignment.annotations["oCDS"] = oCDS
            alignment.annotations["chromSize"] = str(tSize)
            alignment.annotations["match"] = str(matches)
            alignment.annotations["misMatch"] = str(misMatches)
            alignment.annotations["repMatch"] = str(repMatches)
            alignment.annotations["nCount"] = str(nCount)
            alignment.annotations["seqType"] = seqType
            fixed_alignments.append(alignment)
        fixed_alignments.sort(
            key=lambda alignment: (alignment.target.id, alignment.coordinates[0, 0])
        )
        fixed_alignments.targets = alignments.targets
        bigbed.AlignmentWriter(
            stream, bedN=12, declaration=declaration, compress=self.compress
        ).write(fixed_alignments)


class AlignmentIterator(bigbed.AlignmentIterator):
    """Alignment iterator for bigPsl files.

    The pairwise alignments stored in the bigPsl file are loaded and returned
    incrementally.  Additional alignment information is stored as attributes
    of each alignment.
    """

    fmt = "bigPsl"

    def _analyze_fields(self, fields, fieldCount, definedFieldCount):
        names = (
            "chrom",
            "chromStart",
            "chromEnd",
            "name",  # 0
            "score",  # 1
            "strand",  # 2
            "thickStart",  # 3
            "thickEnd",  # 4
            "reserved",  # 5
            "blockCount",  # 6
            "blockSizes",  # 7
            "chromStarts",  # 8
            "oChromStart",  # 9
            "oChromEnd",  # 10
            "oStrand",  # 11
            "oChromSize",  # 12
            "oChromStarts",  # 13
            "oSequence",  # 14
            "oCDS",  # 15
            "chromSize",  # 16
            "match",  # 17
            "misMatch",  # 18
            "repMatch",  # 19
            "nCount",  # 20
            "seqType",  # 21
        )
        for i, name in enumerate(names):
            if name != fields[i].name:
                raise ValueError(
                    "Expected field name '%s'; found '%s'" % (name, fields[i].name)
                )

    def _create_alignment(self, chromId, tStart, tEnd, rest, dataStart, dataEnd):
        assert rest[dataEnd - 1] == 0
        words = rest[dataStart : dataEnd - 1].decode().split("\t")
        if len(words) != 22:
            raise ValueError(
                "Unexpected number of fields (%d, expected 22)" % len(words)
            )
        target_record = self.targets[chromId]
        tSize = int(words[16])
        if len(target_record) != tSize:
            raise ValueError(
                "Unexpected chromosome size %d (expected %d)"
                % (tSize, len(target_record))
            )
        strand = words[2]
        qName = words[0]
        qSize = int(words[12])
        blockCount = int(words[6])
        blockSizes = [int(blockSize) for blockSize in words[7].rstrip(",").split(",")]
        tStarts = [int(start) for start in words[8].rstrip(",").split(",")]
        qStarts = [int(start) for start in words[13].rstrip(",").split(",")]
        if len(blockSizes) != blockCount:
            raise ValueError(
                "Inconsistent number of blocks (%d found, expected %d)"
                % (len(blockSizes), blockCount)
            )
        if len(qStarts) != blockCount:
            raise ValueError(
                "Inconsistent number of query start positions (%d found, expected %d)"
                % (len(qStarts), blockCount)
            )
        if len(tStarts) != blockCount:
            raise ValueError(
                "Inconsistent number of target start positions (%d found, expected %d)"
                % (len(qStarts), blockCount)
            )
        qStarts = np.array(qStarts)
        tStarts = np.array(tStarts)
        tBlockSizes = np.array(blockSizes)
        query_sequence = words[14]
        if query_sequence == "":
            query_sequence = Seq(None, length=qSize)
        else:
            query_sequence = Seq(query_sequence)
            if len(query_sequence) != qSize:
                raise ValueError(
                    "Inconsistent query sequence length (%d, expected %d)"
                    % (len(query_sequence), qSize)
                )
        query_record = SeqRecord(query_sequence, id=qName)
        cds = words[15]
        if cds and cds != "n/a":
            location = Location.fromstring(cds)
            feature = SeqFeature(location, type="CDS")
            query_record.features.append(feature)
        seqType = words[21]
        if seqType == "0":
            qBlockSizes = tBlockSizes
        elif seqType == "1":
            query_record.annotations["molecule_type"] = "DNA"
            qBlockSizes = tBlockSizes
        elif seqType == "2":
            query_record.annotations["molecule_type"] = "protein"
            qBlockSizes = tBlockSizes // 3
        else:
            raise ValueError("Unexpected sequence type '%s'" % seqType)
        tStarts += tStart
        qStrand = words[11]
        if qStrand == "-" and strand == "-":
            tStart, tEnd = tEnd, tStart
            qStarts = qSize - qStarts - qBlockSizes
            tStarts = tSize - tStarts - tBlockSizes
            qStarts = qStarts[::-1]
            tStarts = tStarts[::-1]
            qBlockSizes = qBlockSizes[::-1]
            tBlockSizes = tBlockSizes[::-1]
        qPosition = qStarts[0]
        tPosition = tStarts[0]
        coordinates = [[tPosition, qPosition]]
        for tB, qB, tS, qS in zip(tBlockSizes, qBlockSizes, tStarts, qStarts):
            if tS != tPosition:
                coordinates.append([tS, qPosition])
                tPosition = tS
            if qS != qPosition:
                coordinates.append([tPosition, qS])
                qPosition = qS
            tPosition += tB
            qPosition += qB
            coordinates.append([tPosition, qPosition])
        coordinates = np.array(coordinates).transpose()
        qStart = int(words[9])
        qEnd = int(words[10])
        if strand == "-":
            if qStrand == "-":
                coordinates[0, :] = tSize - coordinates[0, :]
            else:
                qStart, qEnd = qEnd, qStart
                coordinates[1, :] = qSize - coordinates[1, :]
        if tStart != coordinates[0, 0]:
            raise ValueError(
                "Inconsistent tStart found (%d, expected %d)"
                % (tStart, coordinates[0, 0])
            )
        if tEnd != coordinates[0, -1]:
            raise ValueError(
                "Inconsistent tEnd found (%d, expected %d)" % (tEnd, coordinates[0, -1])
            )
        if qStart != coordinates[1, 0]:
            raise ValueError(
                "Inconsistent qStart found (%d, expected %d)"
                % (qStart, coordinates[1, 0])
            )
        if qEnd != coordinates[1, -1]:
            raise ValueError(
                "Inconsistent qEnd found (%d, expected %d)" % (qEnd, coordinates[1, -1])
            )
        records = [target_record, query_record]
        alignment = Alignment(records, coordinates)
        alignment.annotations = {}
        score = words[1]
        try:
            score = float(score)
        except ValueError:
            pass
        else:
            if score.is_integer():
                score = int(score)
        alignment.score = score
        alignment.thickStart = int(words[3])
        alignment.thickEnd = int(words[4])
        alignment.itemRgb = words[5]
        alignment.matches = int(words[17])
        alignment.misMatches = int(words[18])
        alignment.repMatches = int(words[19])
        alignment.nCount = int(words[20])
        return alignment