Configurable chromosome name pattern.
[lightning.git] / tilelib.go
1 package main
2
3 import (
4         "bufio"
5         "bytes"
6         "context"
7         "encoding/gob"
8         "fmt"
9         "io"
10         "regexp"
11         "runtime"
12         "sort"
13         "strings"
14         "sync"
15
16         log "github.com/sirupsen/logrus"
17         "golang.org/x/crypto/blake2b"
18 )
19
20 type tileVariantID uint16 // 1-based
21
22 type tileLibRef struct {
23         Tag     tagID
24         Variant tileVariantID
25 }
26
27 type tileSeq map[string][]tileLibRef
28
29 func (tseq tileSeq) Variants() ([]tileVariantID, int, int) {
30         maxtag := 0
31         for _, refs := range tseq {
32                 for _, ref := range refs {
33                         if maxtag < int(ref.Tag) {
34                                 maxtag = int(ref.Tag)
35                         }
36                 }
37         }
38         vars := make([]tileVariantID, maxtag+1)
39         var kept, dropped int
40         for _, refs := range tseq {
41                 for _, ref := range refs {
42                         if vars[int(ref.Tag)] != 0 {
43                                 dropped++
44                         } else {
45                                 kept++
46                         }
47                         vars[int(ref.Tag)] = ref.Variant
48                 }
49         }
50         return vars, kept, dropped
51 }
52
53 type tileLibrary struct {
54         retainNoCalls       bool
55         skipOOO             bool
56         retainTileSequences bool
57
58         taglib         *tagLibrary
59         variant        [][][blake2b.Size256]byte
60         refseqs        map[string]map[string][]tileLibRef
61         compactGenomes map[string][]tileVariantID
62         // count [][]int
63         seq      map[[blake2b.Size256]byte][]byte
64         variants int
65         // if non-nil, write out any tile variants added while tiling
66         encoder *gob.Encoder
67
68         mtx sync.Mutex
69 }
70
71 func (tilelib *tileLibrary) loadTagSet(newtagset [][]byte) error {
72         // Loading a tagset means either passing it through to the
73         // output (if it's the first one we've seen), or just ensuring
74         // it doesn't disagree with what we already have.
75         if len(newtagset) == 0 {
76                 return nil
77         }
78         tilelib.mtx.Lock()
79         defer tilelib.mtx.Unlock()
80         if tilelib.taglib == nil || tilelib.taglib.Len() == 0 {
81                 tilelib.taglib = &tagLibrary{}
82                 err := tilelib.taglib.setTags(newtagset)
83                 if err != nil {
84                         return err
85                 }
86                 if tilelib.encoder != nil {
87                         err = tilelib.encoder.Encode(LibraryEntry{
88                                 TagSet: newtagset,
89                         })
90                         if err != nil {
91                                 return err
92                         }
93                 }
94         } else if tilelib.taglib.Len() != len(newtagset) {
95                 return fmt.Errorf("cannot merge libraries with differing tagsets")
96         } else {
97                 current := tilelib.taglib.Tags()
98                 for i := range newtagset {
99                         if !bytes.Equal(newtagset[i], current[i]) {
100                                 return fmt.Errorf("cannot merge libraries with differing tagsets")
101                         }
102                 }
103         }
104         return nil
105 }
106
107 func (tilelib *tileLibrary) loadTileVariants(tvs []TileVariant, variantmap map[tileLibRef]tileVariantID) error {
108         for _, tv := range tvs {
109                 // Assign a new variant ID (unique across all inputs)
110                 // for each input variant.
111                 variantmap[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence).Variant
112         }
113         return nil
114 }
115
116 func (tilelib *tileLibrary) loadCompactGenomes(cgs []CompactGenome, variantmap map[tileLibRef]tileVariantID, onLoadGenome func(CompactGenome)) error {
117         log.Debugf("loadCompactGenomes: %d", len(cgs))
118         var wg sync.WaitGroup
119         errs := make(chan error, 1)
120         for _, cg := range cgs {
121                 wg.Add(1)
122                 cg := cg
123                 go func() {
124                         defer wg.Done()
125                         for i, variant := range cg.Variants {
126                                 if len(errs) > 0 {
127                                         return
128                                 }
129                                 if variant == 0 {
130                                         continue
131                                 }
132                                 tag := tagID(i / 2)
133                                 newvariant, ok := variantmap[tileLibRef{Tag: tag, Variant: variant}]
134                                 if !ok {
135                                         err := fmt.Errorf("oops: genome %q has variant %d for tag %d, but that variant was not in its library", cg.Name, variant, tag)
136                                         select {
137                                         case errs <- err:
138                                         default:
139                                         }
140                                         return
141                                 }
142                                 log.Tracef("loadCompactGenomes: cg %s tag %d variant %d => %d", cg.Name, tag, variant, newvariant)
143                                 cg.Variants[i] = newvariant
144                         }
145                         if onLoadGenome != nil {
146                                 onLoadGenome(cg)
147                         }
148                         if tilelib.encoder != nil {
149                                 err := tilelib.encoder.Encode(LibraryEntry{
150                                         CompactGenomes: []CompactGenome{cg},
151                                 })
152                                 if err != nil {
153                                         select {
154                                         case errs <- err:
155                                         default:
156                                         }
157                                         return
158                                 }
159                         }
160                         if tilelib.compactGenomes != nil {
161                                 tilelib.mtx.Lock()
162                                 defer tilelib.mtx.Unlock()
163                                 tilelib.compactGenomes[cg.Name] = cg.Variants
164                         }
165                 }()
166         }
167         wg.Wait()
168         go close(errs)
169         return <-errs
170 }
171
172 func (tilelib *tileLibrary) loadCompactSequences(cseqs []CompactSequence, variantmap map[tileLibRef]tileVariantID) error {
173         log.Debugf("loadCompactSequences: %d", len(cseqs))
174         for _, cseq := range cseqs {
175                 for _, tseq := range cseq.TileSequences {
176                         for i, libref := range tseq {
177                                 if libref.Variant == 0 {
178                                         // No variant (e.g., import
179                                         // dropped tiles with
180                                         // no-calls) = no translation.
181                                         continue
182                                 }
183                                 v, ok := variantmap[libref]
184                                 if !ok {
185                                         return fmt.Errorf("oops: CompactSequence %q has variant %d for tag %d, but that variant was not in its library", cseq.Name, libref.Variant, libref.Tag)
186                                 }
187                                 tseq[i].Variant = v
188                         }
189                 }
190                 if tilelib.encoder != nil {
191                         if err := tilelib.encoder.Encode(LibraryEntry{
192                                 CompactSequences: []CompactSequence{cseq},
193                         }); err != nil {
194                                 return err
195                         }
196                 }
197         }
198         tilelib.mtx.Lock()
199         defer tilelib.mtx.Unlock()
200         if tilelib.refseqs == nil {
201                 tilelib.refseqs = map[string]map[string][]tileLibRef{}
202         }
203         for _, cseq := range cseqs {
204                 tilelib.refseqs[cseq.Name] = cseq.TileSequences
205         }
206         return nil
207 }
208
209 // Load library data from rdr. Tile variants might be renumbered in
210 // the process; in that case, genomes variants will be renumbered to
211 // match.
212 //
213 // If onLoadGenome is non-nil, call it on each CompactGenome entry.
214 func (tilelib *tileLibrary) LoadGob(ctx context.Context, rdr io.Reader, gz bool, onLoadGenome func(CompactGenome)) error {
215         cgs := []CompactGenome{}
216         cseqs := []CompactSequence{}
217         variantmap := map[tileLibRef]tileVariantID{}
218         err := DecodeLibrary(rdr, gz, func(ent *LibraryEntry) error {
219                 if ctx.Err() != nil {
220                         return ctx.Err()
221                 }
222                 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
223                         return err
224                 }
225                 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
226                         return err
227                 }
228                 cgs = append(cgs, ent.CompactGenomes...)
229                 cseqs = append(cseqs, ent.CompactSequences...)
230                 return nil
231         })
232         if err != nil {
233                 return err
234         }
235         if ctx.Err() != nil {
236                 return ctx.Err()
237         }
238         err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
239         if err != nil {
240                 return err
241         }
242         err = tilelib.loadCompactSequences(cseqs, variantmap)
243         if err != nil {
244                 return err
245         }
246         return nil
247 }
248
249 type importStats struct {
250         InputFile              string
251         InputLabel             string
252         InputLength            int
253         InputCoverage          int
254         TileCoverage           int
255         PathLength             int
256         DroppedOutOfOrderTiles int
257 }
258
259 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader, matchChromosome *regexp.Regexp) (tileSeq, []importStats, error) {
260         ret := tileSeq{}
261         type jobT struct {
262                 label string
263                 fasta []byte
264         }
265         todo := make(chan jobT)
266         scanner := bufio.NewScanner(rdr)
267         go func() {
268                 defer close(todo)
269                 var fasta []byte
270                 var seqlabel string
271                 for scanner.Scan() {
272                         buf := scanner.Bytes()
273                         if len(buf) > 0 && buf[0] == '>' {
274                                 todo <- jobT{seqlabel, fasta}
275                                 seqlabel, fasta = strings.SplitN(string(buf[1:]), " ", 2)[0], nil
276                                 log.Debugf("%s %s reading fasta", filelabel, seqlabel)
277                         } else {
278                                 fasta = append(fasta, bytes.ToLower(buf)...)
279                         }
280                 }
281                 todo <- jobT{seqlabel, fasta}
282         }()
283         type foundtag struct {
284                 pos    int
285                 tagid  tagID
286                 taglen int
287         }
288         found := make([]foundtag, 2000000)
289         path := make([]tileLibRef, 2000000)
290         totalFoundTags := 0
291         totalPathLen := 0
292         skippedSequences := 0
293         stats := make([]importStats, 0, len(todo))
294         for job := range todo {
295                 if len(job.fasta) == 0 {
296                         continue
297                 } else if !matchChromosome.MatchString(job.label) {
298                         skippedSequences++
299                         continue
300                 }
301                 log.Debugf("%s %s tiling", filelabel, job.label)
302
303                 found = found[:0]
304                 tilelib.taglib.FindAll(job.fasta, func(tagid tagID, pos, taglen int) {
305                         found = append(found, foundtag{pos: pos, tagid: tagid, taglen: taglen})
306                 })
307                 totalFoundTags += len(found)
308
309                 basesOut := 0
310                 skipped := 0
311                 path = path[:0]
312                 last := foundtag{tagid: -1}
313                 if tilelib.skipOOO {
314                         keep := longestIncreasingSubsequence(len(found), func(i int) int { return int(found[i].tagid) })
315                         for i, x := range keep {
316                                 found[i] = found[x]
317                         }
318                         skipped = len(found) - len(keep)
319                         found = found[:len(keep)]
320                 }
321                 for i, f := range found {
322                         log.Tracef("%s %s found[%d] == %#v", filelabel, job.label, i, f)
323                         if last.tagid < 0 {
324                                 // first tag in sequence
325                                 last = foundtag{tagid: f.tagid}
326                                 continue
327                         }
328                         libref := tilelib.getRef(last.tagid, job.fasta[last.pos:f.pos+f.taglen])
329                         path = append(path, libref)
330                         if libref.Variant > 0 {
331                                 // Count output coverage from
332                                 // the end of the previous tag
333                                 // (if any) to the end of the
334                                 // current tag, IOW don't
335                                 // double-count coverage for
336                                 // the previous tag.
337                                 basesOut += countBases(job.fasta[last.pos+last.taglen : f.pos+f.taglen])
338                         } else {
339                                 // If we dropped this tile
340                                 // (because !retainNoCalls),
341                                 // set taglen=0 so the
342                                 // overlapping tag is counted
343                                 // toward coverage on the
344                                 // following tile.
345                                 f.taglen = 0
346                         }
347                         last = f
348                 }
349                 if last.tagid < 0 {
350                         log.Warnf("%s %s no tags found", filelabel, job.label)
351                 } else {
352                         libref := tilelib.getRef(last.tagid, job.fasta[last.pos:])
353                         path = append(path, libref)
354                         if libref.Variant > 0 {
355                                 basesOut += countBases(job.fasta[last.pos+last.taglen:])
356                         }
357                 }
358
359                 pathcopy := make([]tileLibRef, len(path))
360                 copy(pathcopy, path)
361                 ret[job.label] = pathcopy
362
363                 basesIn := countBases(job.fasta)
364                 log.Infof("%s %s fasta in %d coverage in %d coverage out %d path len %d skipped %d", filelabel, job.label, len(job.fasta), basesIn, basesOut, len(path), skipped)
365                 stats = append(stats, importStats{
366                         InputFile:              filelabel,
367                         InputLabel:             job.label,
368                         InputLength:            len(job.fasta),
369                         InputCoverage:          basesIn,
370                         TileCoverage:           basesOut,
371                         PathLength:             len(path),
372                         DroppedOutOfOrderTiles: skipped,
373                 })
374
375                 totalPathLen += len(path)
376         }
377         log.Printf("%s tiled with total path len %d in %d sequences (skipped %d sequences that did not match chromosome regexp, skipped %d out-of-order tags)", filelabel, totalPathLen, len(ret), skippedSequences, totalFoundTags-totalPathLen)
378         return ret, stats, scanner.Err()
379 }
380
381 func (tilelib *tileLibrary) Len() int {
382         tilelib.mtx.Lock()
383         defer tilelib.mtx.Unlock()
384         return tilelib.variants
385 }
386
387 // Return a tileLibRef for a tile with the given tag and sequence,
388 // adding the sequence to the library if needed.
389 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte) tileLibRef {
390         dropSeq := false
391         if !tilelib.retainNoCalls {
392                 for _, b := range seq {
393                         if b != 'a' && b != 'c' && b != 'g' && b != 't' {
394                                 dropSeq = true
395                                 break
396                         }
397                 }
398         }
399         tilelib.mtx.Lock()
400         if tilelib.variant == nil && tilelib.taglib != nil {
401                 tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
402         }
403         if int(tag) >= len(tilelib.variant) {
404                 // If we haven't seen the tag library yet (as in a
405                 // merge), tilelib.taglib.Len() is zero. We can still
406                 // behave correctly, we just need to expand the
407                 // tilelib.variant slice as needed.
408                 if int(tag) >= cap(tilelib.variant) {
409                         // Allocate 2x capacity.
410                         newslice := make([][][blake2b.Size256]byte, int(tag)+1, (int(tag)+1)*2)
411                         copy(newslice, tilelib.variant)
412                         tilelib.variant = newslice[:int(tag)+1]
413                 } else {
414                         // Use previously allocated capacity, avoiding
415                         // copy.
416                         tilelib.variant = tilelib.variant[:int(tag)+1]
417                 }
418         }
419         seqhash := blake2b.Sum256(seq)
420         for i, varhash := range tilelib.variant[tag] {
421                 if varhash == seqhash {
422                         tilelib.mtx.Unlock()
423                         return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
424                 }
425         }
426         tilelib.variants++
427         tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
428         if tilelib.retainTileSequences && !dropSeq {
429                 if tilelib.seq == nil {
430                         tilelib.seq = map[[blake2b.Size256]byte][]byte{}
431                 }
432                 tilelib.seq[seqhash] = append([]byte(nil), seq...)
433         }
434         variant := tileVariantID(len(tilelib.variant[tag]))
435         tilelib.mtx.Unlock()
436
437         if tilelib.encoder != nil {
438                 saveSeq := seq
439                 if dropSeq {
440                         // Save the hash, but not the sequence
441                         saveSeq = nil
442                 }
443                 tilelib.encoder.Encode(LibraryEntry{
444                         TileVariants: []TileVariant{{
445                                 Tag:      tag,
446                                 Variant:  variant,
447                                 Blake2b:  seqhash,
448                                 Sequence: saveSeq,
449                         }},
450                 })
451         }
452         return tileLibRef{Tag: tag, Variant: variant}
453 }
454
455 func (tilelib *tileLibrary) TileVariantSequence(libref tileLibRef) []byte {
456         if libref.Variant == 0 || len(tilelib.variant) <= int(libref.Tag) || len(tilelib.variant[libref.Tag]) < int(libref.Variant) {
457                 return nil
458         }
459         return tilelib.seq[tilelib.variant[libref.Tag][libref.Variant-1]]
460 }
461
462 // Tidy deletes unreferenced tile variants and renumbers variants so
463 // more common variants have smaller IDs.
464 func (tilelib *tileLibrary) Tidy() {
465         log.Print("Tidy: compute inref")
466         inref := map[tileLibRef]bool{}
467         for _, refseq := range tilelib.refseqs {
468                 for _, librefs := range refseq {
469                         for _, libref := range librefs {
470                                 inref[libref] = true
471                         }
472                 }
473         }
474         log.Print("Tidy: compute remap")
475         remap := make([][]tileVariantID, len(tilelib.variant))
476         throttle := throttle{Max: runtime.NumCPU() + 1}
477         for tag, oldvariants := range tilelib.variant {
478                 tag, oldvariants := tagID(tag), oldvariants
479                 if tag%10000 == 0 {
480                         log.Printf("Tidy: tag %d", tag)
481                 }
482                 throttle.Acquire()
483                 go func() {
484                         defer throttle.Release()
485                         uses := make([]int, len(oldvariants))
486                         for _, cg := range tilelib.compactGenomes {
487                                 for phase := 0; phase < 2; phase++ {
488                                         cgi := int(tag)*2 + phase
489                                         if cgi < len(cg) && cg[cgi] > 0 {
490                                                 uses[cg[cgi]-1]++
491                                         }
492                                 }
493                         }
494
495                         // Compute desired order of variants:
496                         // neworder[x] == index in oldvariants that
497                         // should move to position x.
498                         neworder := make([]int, len(oldvariants))
499                         for i := range neworder {
500                                 neworder[i] = i
501                         }
502                         sort.Slice(neworder, func(i, j int) bool {
503                                 if cmp := uses[neworder[i]] - uses[neworder[j]]; cmp != 0 {
504                                         return cmp > 0
505                                 } else {
506                                         return bytes.Compare(oldvariants[neworder[i]][:], oldvariants[neworder[j]][:]) < 0
507                                 }
508                         })
509
510                         // Replace tilelib.variants[tag] with a new
511                         // re-ordered slice of hashes, and make a
512                         // mapping from old to new variant IDs.
513                         remaptag := make([]tileVariantID, len(oldvariants)+1)
514                         newvariants := make([][blake2b.Size256]byte, 0, len(neworder))
515                         for _, oldi := range neworder {
516                                 if uses[oldi] > 0 || inref[tileLibRef{Tag: tag, Variant: tileVariantID(oldi + 1)}] {
517                                         newvariants = append(newvariants, oldvariants[oldi])
518                                         remaptag[oldi+1] = tileVariantID(len(newvariants))
519                                 }
520                         }
521                         tilelib.variant[tag] = newvariants
522                         remap[tag] = remaptag
523                 }()
524         }
525         throttle.Wait()
526
527         // Apply remap to genomes and reference sequences, so they
528         // refer to the same tile variants using the changed IDs.
529         log.Print("Tidy: apply remap")
530         for _, cg := range tilelib.compactGenomes {
531                 for idx, variant := range cg {
532                         cg[idx] = remap[tagID(idx/2)][variant]
533                 }
534         }
535         for _, refcs := range tilelib.refseqs {
536                 for _, refseq := range refcs {
537                         for i, tv := range refseq {
538                                 refseq[i].Variant = remap[tv.Tag][tv.Variant]
539                         }
540                 }
541         }
542         log.Print("Tidy: done")
543 }
544
545 func countBases(seq []byte) int {
546         n := 0
547         for _, c := range seq {
548                 if isbase[c] {
549                         n++
550                 }
551         }
552         return n
553 }