forked from nanoporetech/spliced_bam2gff
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bam2gff.go
470 lines (401 loc) · 12.9 KB
/
bam2gff.go
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
package main
import (
"bufio"
"fmt"
"io"
"os"
"path"
"github.com/biogo/biogo/feat"
"github.com/biogo/biogo/feat/gene"
"github.com/biogo/biogo/feat/genome"
"github.com/biogo/biogo/io/featio/gff"
"github.com/biogo/biogo/seq"
"github.com/biogo/hts/sam"
)
type Locus struct {
Chrom string
Start int
End int
Feats []gff.Feature
Order int
Size int
}
// NewLocus return a pointer to a new Locus structure.
func NewLocus(chrom string, start, end, order int) *Locus {
return &Locus{chrom, start, end, []gff.Feature{}, order, 0}
}
// String representation of a locus object.
func (l *Locus) String() string {
return fmt.Sprintf("%09d_%s:%d:%d", l.Order, l.Chrom, l.Start, l.End)
}
// SplicedBam2PartGFF converts spliced BAM alignments to locus-partitioned GFF files.
func SplicedBam2PartGFF(inBam string, outDir string, minBundle int, nrProcBam int, minimapInput bool, strandBehaviour int, maxDel int, keepS bool) {
err := os.MkdirAll(outDir, 0750)
if err != nil {
L.Fatalf("Could not create GFF output directory: %s", err)
}
var locus *Locus
locusCache := make([]*Locus, 0, 1000)
var count, bundleCount, bc int
locusChan := SplicedBam2Loci(inBam, nrProcBam, minimapInput, strandBehaviour, maxDel, keepS)
for locus = range locusChan {
count += locus.Size
bc += locus.Size
if locus.Size > minBundle {
locusCache = append(locusCache, locus)
}
if (bc > minBundle) || (locus.Size > minBundle) {
bundleName := fmt.Sprintf("%09d_%s:%d:%d_bundle.gff", bundleCount, locus.Chrom, locusCache[0].Start, locus.End)
outName := path.Join(outDir, bundleName)
outFh, err := os.Create(outName)
if err != nil {
L.Fatalf("Could not create GFF output file: %s", err)
}
outBuff := bufio.NewWriter(outFh)
gffWriter := gff.NewWriter(outBuff, 1000, true)
for _, l := range locusCache {
WriteFeatures(l.Feats, gffWriter)
}
outBuff.Flush()
outFh.Close()
locusCache = locusCache[:0]
bc = 0
bundleCount++
} else {
locusCache = append(locusCache, locus)
}
}
if len(locusCache) > 0 {
bundleName := fmt.Sprintf("%09d_%s:%d:%d_bundle.gff", bundleCount, locus.Chrom, locusCache[0].Start, locus.End)
outName := path.Join(outDir, bundleName)
outFh, err := os.Create(outName)
if err != nil {
L.Fatalf("Could not create GFF output file: %s", err)
}
outBuff := bufio.NewWriter(outFh)
gffWriter := gff.NewWriter(outBuff, 1000, true)
for _, l := range locusCache {
WriteFeatures(l.Feats, gffWriter)
}
outBuff.Flush()
outFh.Close()
L.Println(len(locusCache))
locusCache = locusCache[:0]
bc = 0
bundleCount++
}
L.Printf("Written %d transcripts to %d loci and %d bundles.", count, locus.Order+1, bundleCount)
}
// SplicedBam2PartGFF converts spliced BAM alignments to GFF features grouped by loci.
func SplicedBam2Loci(inBam string, nrProcBam int, minimapInput bool, strandBehaviour int, maxDel int, keepS bool) chan *Locus {
bamReader := NewBamReader(inBam, nrProcBam)
outChan := make(chan *Locus, 100)
var cache []*sam.Record
var loc *Locus
var chrom string
locCount := 0
go func() {
// Ierate over BAM records:
for {
record, err := bamReader.Read()
if err == io.EOF {
break
}
// Turn mapped SAM records into GFF:
if record.Flags&sam.Unmapped == 0 {
if !keepS {
if (record.Flags&sam.Secondary != 0) || (record.Flags&sam.Supplementary != 0) || hasSupp(record) {
continue
}
}
if cache == nil {
cache = make([]*sam.Record, 0, 5000)
loc = NewLocus(record.Ref.Name(), record.Start(), record.End(), locCount)
cache = append(cache, record)
loc.Size++
locCount++
} else if (record.Start() > loc.End) || (record.Ref.Name() != loc.Chrom) {
for _, r := range cache {
loc.Feats = append(loc.Feats, SplicedSAM2GFF(r, minimapInput, strandBehaviour, maxDel)...)
}
outChan <- loc
loc = NewLocus(record.Ref.Name(), record.Start(), record.End(), locCount)
if loc.Chrom != chrom {
chrom = loc.Chrom
L.Printf("Processing chromosome: %s\n", chrom)
}
cache = cache[:0]
cache = append(cache, record)
loc.Size++
locCount++
} else {
if record.Start() < cache[len(cache)-1].Start() {
L.Fatalf("BAM file is not sorted! Offending records: %s %s\n", cache[len(cache)-1].Ref.Name(), record.Ref.Name())
}
if record.End() > loc.End {
loc.End = record.End()
}
cache = append(cache, record)
loc.Size++
}
}
}
for _, r := range cache {
loc.Feats = append(loc.Feats, SplicedSAM2GFF(r, minimapInput, strandBehaviour, maxDel)...)
}
outChan <- loc
close(outChan)
}()
return outChan
}
// Turn a BAM file containing sliced alignments into GFF2 format annotation.
func SplicedBam2GFF(inBam string, out io.Writer, nrProcBam int, minimapInput bool, strandBehaviour int, maxDel int, keepS bool) {
bamReader := NewBamReader(inBam, nrProcBam)
gffWriter := gff.NewWriter(out, 1000, true)
count := 0
// Ierate over BAM records:
for {
record, err := bamReader.Read()
if err == io.EOF {
break
}
// Turn mapped SAM records into GFF:
if record.Flags&sam.Unmapped == 0 {
if !keepS {
if (record.Flags&sam.Secondary != 0) || (record.Flags&sam.Supplementary != 0) || hasSupp(record) {
continue
}
}
SplicedSAM2GFFWrite(record, gffWriter, minimapInput, strandBehaviour, maxDel)
count++
}
}
L.Printf("Written %d transcripts.", count)
}
// Create a new gene.CodingTranscript object from SAM reference, position and orientation.
func NewCodingTranscript(chrom *sam.Reference, id string, pos int, strand feat.Orientation) *gene.CodingTranscript {
// This will allocate a new chromosome for each transcript
// but withing this application that should be OK:
ch := &genome.Chromosome{
Chr: chrom.Name(),
Desc: chrom.Name(),
Length: chrom.Len(),
Features: nil,
}
tr := &gene.CodingTranscript{
ID: id,
Loc: ch,
Offset: pos,
Orient: strand,
Desc: id,
CDSstart: 0,
CDSend: 0,
}
return tr
}
func hasSupp(rec *sam.Record) bool {
_, ok := rec.Tag([]byte("SA"))
if ok {
return true
}
return false
}
// Get orientation from transcript strand tag (either XS, or ts for minimap2).
func getTrStrand(rec *sam.Record, minimapInput bool) feat.Orientation {
var aux sam.Aux
if minimapInput {
aux, _ = rec.Tag([]byte("ts"))
} else {
aux, _ = rec.Tag([]byte("XS"))
}
// We got the tag value:
if aux != nil {
// Convert tag value to string:
strand := string(aux.Value().(uint8))
// Decide orientation:
switch strand {
case "+":
return feat.Forward
case "-":
return feat.Reverse
case "?":
return feat.NotOriented
default:
L.Fatalf("Unknown orientation string: %s\n", strand)
}
} else {
//L.Printf("Missing strand tag in record: %s\n", rec.Name)
}
// Missing tag, feature not oriented:
return feat.NotOriented
}
// Flip orientation:
func flipOrientation(orient feat.Orientation) feat.Orientation {
switch orient {
case feat.Forward:
return feat.Reverse
case feat.Reverse:
return feat.Forward
case feat.NotOriented:
return feat.NotOriented
default:
L.Fatalf("Unknown orientation: %s", orient)
}
return feat.NotOriented
}
// Decide on the feature strand depending on the transcript strand tag and read orientation:
func figureStrand(readStrand, trStrand feat.Orientation, minimapInput bool, strandBehaviour int) feat.Orientation {
// Use read orientation as feature strand:
if strandBehaviour == StrandRead {
return readStrand
}
var strand feat.Orientation
// Strand tag is missing:
if trStrand == feat.NotOriented {
switch strandBehaviour {
case StrandTag:
strand = feat.NotOriented // Strand tag takes precedence, feature is not oriented.
case StrandTagRead:
strand = readStrand // Fallback to read orientation.
}
return strand
}
// Transript strand tag is present:
switch minimapInput {
case true:
if trStrand == feat.Reverse {
strand = flipOrientation(readStrand) // Flip orientaton.
} else {
strand = readStrand // Use read strand.
}
case false:
// Input is not minimap2, use transcript strand tag as feature orientation.
strand = trStrand
}
return strand
}
// Convert SAM record into GFF2 records. Each read will be represented as a distinct transcript.
func SplicedSAM2GFFWrite(record *sam.Record, gffWriter *gff.Writer, minimapInput bool, strandBehaviour int, maxDel int) {
WriteFeatures(SplicedSAM2GFF(record, minimapInput, strandBehaviour, maxDel), gffWriter)
}
// Convert SAM record into GFF2 records. Each read will be represented as a distinct transcript.
func SplicedSAM2GFF(record *sam.Record, minimapInput bool, strandBehaviour int, maxDel int) []gff.Feature {
//Get read strand:
var readStrand feat.Orientation = feat.Forward
if record.Flags&sam.Reverse != 0 {
readStrand = feat.Reverse
}
// Get transcript strand:
trStrand := getTrStrand(record, minimapInput)
// Decide feature strand:
strand := figureStrand(readStrand, trStrand, minimapInput, strandBehaviour)
transcript := NewCodingTranscript(record.Ref, record.Name, record.Pos, strand)
exons := make(gene.Exons, 0) // To accumulate exons.
// First exon starts at record position:
var currBlockStart int = record.Pos
var currBlockLen int = 0
var exonNr int = 0
CIGAR_LOOP: // Iterate over CIGAR:
for _, cigar := range record.Cigar {
op := cigar.Type()
length := cigar.Len()
switch op {
// Soft clip, hard clip, or insertion - do not consume reference:
case sam.CigarSoftClipped, sam.CigarHardClipped, sam.CigarInsertion:
continue CIGAR_LOOP
// Match, mismatch or deletion - add to current exon length:
case sam.CigarDeletion:
if length < maxDel {
currBlockLen += length
} else {
exonStart := currBlockStart // Previous exon starting here.
exonEnd := currBlockStart + currBlockLen // Previous exon ends here.
// Create exon object:
exonId := fmt.Sprintf("exon_%d", exonNr)
exon := gene.Exon{transcript, exonStart - record.Pos, exonEnd - exonStart, exonId}
// Discard zero length exons - FIXME: maybe this should not happen.
if exon.Len() > 0 {
exons = append(exons, exon) // Register exon.
}
currBlockLen = 0 // Reset exon length counter.
currBlockStart = exonEnd + length // Next exon starts after the N operation.
exonNr++
}
case sam.CigarMatch, sam.CigarEqual, sam.CigarMismatch:
currBlockLen += length
// N operation:
case sam.CigarSkipped:
exonStart := currBlockStart // Previous exon starting here.
exonEnd := currBlockStart + currBlockLen // Previous exon ends here.
// Create exon object:
exonId := fmt.Sprintf("exon_%d", exonNr)
exon := gene.Exon{transcript, exonStart - record.Pos, exonEnd - exonStart, exonId}
// Discard zero length exons - FIXME: maybe this should not happen.
if exon.Len() > 0 {
exons = append(exons, exon) // Register exon.
}
currBlockLen = 0 // Reset exon length counter.
currBlockStart = exonEnd + length // Next exon starts after the N operation.
exonNr++
default:
L.Fatalf("Unsupported CIGAR operation %s\n in record %s\n", op, record.Name) // FIXME
}
}
// Deal with the last exon:
exonStart := currBlockStart
exonEnd := currBlockStart + currBlockLen
exonId := fmt.Sprintf("exon_%d", exonNr)
exon := gene.Exon{transcript, exonStart - record.Pos, exonEnd - exonStart, exonId}
if exon.Len() > 0 {
exons = append(exons, exon)
}
// Add exons to the transcript:
err := transcript.SetExons(exons...)
if err != nil {
L.Fatalf("Could not set exons for %s: %s\n", transcript.ID, err)
}
// Convert transcript into GFF2 features:
trFeatures := Transcript2GFF(transcript)
return trFeatures
}
// Write a slice of GFF fetures to file.
func WriteFeatures(features []gff.Feature, writer *gff.Writer) {
// Write GFF features:
for _, feat := range features {
_, err := writer.Write(&feat)
if err != nil {
L.Fatalf("Failed to write feature %s: %s", feat, err)
}
}
}
// Convert a gene.CodingTranscript object into a slice of GFF features.
func Transcript2GFF(tr *gene.CodingTranscript) []gff.Feature {
res := make([]gff.Feature, 0, len(tr.Exons())+1)
trFeat := gff.Feature{
SeqName: tr.Location().Name(),
Source: "pinfish",
Feature: "mRNA",
FeatStart: tr.Start(),
FeatEnd: tr.End(),
FeatScore: nil,
FeatStrand: seq.Strand(tr.Orient),
FeatFrame: gff.NoFrame,
FeatAttributes: gff.Attributes{gff.Attribute{Tag: "gene_id", Value: "\"" + tr.ID + "\""}, gff.Attribute{Tag: "transcript_id", Value: "\"" + tr.ID + "\";"}},
}
res = append(res, trFeat)
for _, exon := range tr.Exons() {
exFeat := gff.Feature{
SeqName: tr.Location().Name(),
Source: "pinfish",
Feature: "exon",
FeatStart: tr.Offset + exon.Start(),
FeatEnd: tr.Offset + exon.End(),
FeatScore: nil,
FeatStrand: seq.Strand(tr.Orient),
FeatFrame: gff.NoFrame,
FeatAttributes: gff.Attributes{gff.Attribute{Tag: "transcript_id", Value: "\"" + tr.ID + "\";"}},
}
res = append(res, exFeat)
}
return res
}