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