Fixup multiple-file reading.
[lightning.git] / tilelib.go
1 package lightning
2
3 import (
4         "bufio"
5         "bytes"
6         "context"
7         "encoding/gob"
8         "fmt"
9         "io"
10         "os"
11         "regexp"
12         "runtime"
13         "sort"
14         "strings"
15         "sync"
16         "sync/atomic"
17
18         "github.com/klauspost/pgzip"
19         log "github.com/sirupsen/logrus"
20         "golang.org/x/crypto/blake2b"
21 )
22
23 type tileVariantID uint16 // 1-based
24
25 type tileLibRef struct {
26         Tag     tagID
27         Variant tileVariantID
28 }
29
30 type tileSeq map[string][]tileLibRef
31
32 func (tseq tileSeq) Variants() ([]tileVariantID, int, int) {
33         maxtag := 0
34         for _, refs := range tseq {
35                 for _, ref := range refs {
36                         if maxtag < int(ref.Tag) {
37                                 maxtag = int(ref.Tag)
38                         }
39                 }
40         }
41         vars := make([]tileVariantID, maxtag+1)
42         var kept, dropped int
43         for _, refs := range tseq {
44                 for _, ref := range refs {
45                         if vars[int(ref.Tag)] != 0 {
46                                 dropped++
47                         } else {
48                                 kept++
49                         }
50                         vars[int(ref.Tag)] = ref.Variant
51                 }
52         }
53         return vars, kept, dropped
54 }
55
56 type tileLibrary struct {
57         retainNoCalls       bool
58         skipOOO             bool
59         retainTileSequences bool
60
61         taglib         *tagLibrary
62         variant        [][][blake2b.Size256]byte
63         refseqs        map[string]map[string][]tileLibRef
64         compactGenomes map[string][]tileVariantID
65         // count [][]int
66         seq      map[[blake2b.Size256]byte][]byte
67         variants int64
68         // if non-nil, write out any tile variants added while tiling
69         encoder *gob.Encoder
70
71         mtx   sync.RWMutex
72         vlock []sync.Locker
73 }
74
75 func (tilelib *tileLibrary) loadTagSet(newtagset [][]byte) error {
76         // Loading a tagset means either passing it through to the
77         // output (if it's the first one we've seen), or just ensuring
78         // it doesn't disagree with what we already have.
79         if len(newtagset) == 0 {
80                 return nil
81         }
82         tilelib.mtx.Lock()
83         defer tilelib.mtx.Unlock()
84         if tilelib.taglib == nil || tilelib.taglib.Len() == 0 {
85                 tilelib.taglib = &tagLibrary{}
86                 err := tilelib.taglib.setTags(newtagset)
87                 if err != nil {
88                         return err
89                 }
90                 if tilelib.encoder != nil {
91                         err = tilelib.encoder.Encode(LibraryEntry{
92                                 TagSet: newtagset,
93                         })
94                         if err != nil {
95                                 return err
96                         }
97                 }
98         } else if tilelib.taglib.Len() != len(newtagset) {
99                 return fmt.Errorf("cannot merge libraries with differing tagsets")
100         } else {
101                 current := tilelib.taglib.Tags()
102                 for i := range newtagset {
103                         if !bytes.Equal(newtagset[i], current[i]) {
104                                 return fmt.Errorf("cannot merge libraries with differing tagsets")
105                         }
106                 }
107         }
108         return nil
109 }
110
111 func (tilelib *tileLibrary) loadTileVariants(tvs []TileVariant, variantmap map[tileLibRef]tileVariantID) error {
112         for _, tv := range tvs {
113                 // Assign a new variant ID (unique across all inputs)
114                 // for each input variant.
115                 variantmap[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence).Variant
116         }
117         return nil
118 }
119
120 func (tilelib *tileLibrary) loadCompactGenomes(cgs []CompactGenome, variantmap map[tileLibRef]tileVariantID, onLoadGenome func(CompactGenome)) error {
121         log.Debugf("loadCompactGenomes: %d", len(cgs))
122         var wg sync.WaitGroup
123         errs := make(chan error, 1)
124         for _, cg := range cgs {
125                 wg.Add(1)
126                 cg := cg
127                 go func() {
128                         defer wg.Done()
129                         for i, variant := range cg.Variants {
130                                 if len(errs) > 0 {
131                                         return
132                                 }
133                                 if variant == 0 {
134                                         continue
135                                 }
136                                 tag := tagID(i / 2)
137                                 newvariant, ok := variantmap[tileLibRef{Tag: tag, Variant: variant}]
138                                 if !ok {
139                                         err := fmt.Errorf("oops: genome %q has variant %d for tag %d, but that variant was not in its library", cg.Name, variant, tag)
140                                         select {
141                                         case errs <- err:
142                                         default:
143                                         }
144                                         return
145                                 }
146                                 log.Tracef("loadCompactGenomes: cg %s tag %d variant %d => %d", cg.Name, tag, variant, newvariant)
147                                 cg.Variants[i] = newvariant
148                         }
149                         if onLoadGenome != nil {
150                                 onLoadGenome(cg)
151                         }
152                         if tilelib.encoder != nil {
153                                 err := tilelib.encoder.Encode(LibraryEntry{
154                                         CompactGenomes: []CompactGenome{cg},
155                                 })
156                                 if err != nil {
157                                         select {
158                                         case errs <- err:
159                                         default:
160                                         }
161                                         return
162                                 }
163                         }
164                         if tilelib.compactGenomes != nil {
165                                 tilelib.mtx.Lock()
166                                 defer tilelib.mtx.Unlock()
167                                 tilelib.compactGenomes[cg.Name] = cg.Variants
168                         }
169                 }()
170         }
171         wg.Wait()
172         go close(errs)
173         return <-errs
174 }
175
176 func (tilelib *tileLibrary) loadCompactSequences(cseqs []CompactSequence, variantmap map[tileLibRef]tileVariantID) error {
177         log.Debugf("loadCompactSequences: %d", len(cseqs))
178         for _, cseq := range cseqs {
179                 for _, tseq := range cseq.TileSequences {
180                         for i, libref := range tseq {
181                                 if libref.Variant == 0 {
182                                         // No variant (e.g., import
183                                         // dropped tiles with
184                                         // no-calls) = no translation.
185                                         continue
186                                 }
187                                 v, ok := variantmap[libref]
188                                 if !ok {
189                                         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)
190                                 }
191                                 tseq[i].Variant = v
192                         }
193                 }
194                 if tilelib.encoder != nil {
195                         if err := tilelib.encoder.Encode(LibraryEntry{
196                                 CompactSequences: []CompactSequence{cseq},
197                         }); err != nil {
198                                 return err
199                         }
200                 }
201         }
202         tilelib.mtx.Lock()
203         defer tilelib.mtx.Unlock()
204         if tilelib.refseqs == nil {
205                 tilelib.refseqs = map[string]map[string][]tileLibRef{}
206         }
207         for _, cseq := range cseqs {
208                 tilelib.refseqs[cseq.Name] = cseq.TileSequences
209         }
210         return nil
211 }
212
213 func (tilelib *tileLibrary) LoadDir(ctx context.Context, path string, onLoadGenome func(CompactGenome)) error {
214         var files []string
215         var walk func(string) error
216         walk = func(path string) error {
217                 f, err := open(path)
218                 if err != nil {
219                         return err
220                 }
221                 defer f.Close()
222                 fis, err := f.Readdir(-1)
223                 if err != nil {
224                         files = append(files, path)
225                         return nil
226                 }
227                 for _, fi := range fis {
228                         if fi.Name() == "." || fi.Name() == ".." {
229                                 continue
230                         } else if child := path + "/" + fi.Name(); fi.IsDir() {
231                                 err = walk(child)
232                                 if err != nil {
233                                         return err
234                                 }
235                         } else if strings.HasSuffix(child, ".gob") || strings.HasSuffix(child, ".gob.gz") {
236                                 files = append(files, child)
237                         }
238                 }
239                 return nil
240         }
241         log.Infof("LoadDir: walk dir %s", path)
242         err := walk(path)
243         if err != nil {
244                 return err
245         }
246         ctx, cancel := context.WithCancel(ctx)
247         defer cancel()
248         var mtx sync.Mutex
249         cgs := []CompactGenome{}
250         cseqs := []CompactSequence{}
251         variantmap := map[tileLibRef]tileVariantID{}
252         errs := make(chan error, len(files))
253         log.Infof("LoadDir: read %d files", len(files))
254         for _, path := range files {
255                 path := path
256                 go func() {
257                         f, err := open(path)
258                         if err != nil {
259                                 errs <- err
260                                 return
261                         }
262                         defer f.Close()
263                         errs <- DecodeLibrary(f, strings.HasSuffix(path, ".gz"), func(ent *LibraryEntry) error {
264                                 if ctx.Err() != nil {
265                                         return ctx.Err()
266                                 }
267                                 mtx.Lock()
268                                 defer mtx.Unlock()
269                                 if tilelib.taglib == nil || tilelib.taglib.Len() != len(ent.TagSet) {
270                                         // load first set of tags, or
271                                         // report mismatch if 2 sets
272                                         // have different #tags.
273                                         if err := tilelib.loadTagSet(ent.TagSet); err != nil {
274                                                 return err
275                                         }
276                                 }
277                                 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
278                                         return err
279                                 }
280                                 cgs = append(cgs, ent.CompactGenomes...)
281                                 cseqs = append(cseqs, ent.CompactSequences...)
282                                 return nil
283                         })
284                 }()
285         }
286         for range files {
287                 err := <-errs
288                 if err != nil {
289                         return err
290                 }
291         }
292         log.Info("LoadDir: loadCompactGenomes")
293         err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
294         if err != nil {
295                 return err
296         }
297         log.Info("LoadDir: loadCompactSequences")
298         err = tilelib.loadCompactSequences(cseqs, variantmap)
299         if err != nil {
300                 return err
301         }
302         log.Info("LoadDir done")
303         return nil
304 }
305
306 func (tilelib *tileLibrary) WriteDir(dir string) error {
307         nfiles := 128
308         files := make([]*os.File, nfiles)
309         for i := range files {
310                 f, err := os.OpenFile(fmt.Sprintf("%s/library.%04d.gob.gz", dir, i), os.O_CREATE|os.O_WRONLY, 0666)
311                 if err != nil {
312                         return err
313                 }
314                 defer f.Close()
315                 files[i] = f
316         }
317         bufws := make([]*bufio.Writer, nfiles)
318         for i := range bufws {
319                 bufws[i] = bufio.NewWriterSize(files[i], 1<<26)
320         }
321         zws := make([]*pgzip.Writer, nfiles)
322         for i := range zws {
323                 zws[i] = pgzip.NewWriter(bufws[i])
324                 defer zws[i].Close()
325         }
326         encoders := make([]*gob.Encoder, nfiles)
327         for i := range encoders {
328                 encoders[i] = gob.NewEncoder(zws[i])
329         }
330         ctx, cancel := context.WithCancel(context.Background())
331         defer cancel()
332         errs := make(chan error, nfiles)
333         for start := range files {
334                 start := start
335                 go func() {
336                         err := encoders[start].Encode(LibraryEntry{TagSet: tilelib.taglib.Tags()})
337                         if err != nil {
338                                 errs <- err
339                                 return
340                         }
341                         if start == 0 {
342                                 // For now, just write all the genomes and refs
343                                 // to the first file
344                                 for name, cg := range tilelib.compactGenomes {
345                                         err := encoders[start].Encode(LibraryEntry{CompactGenomes: []CompactGenome{{
346                                                 Name:     name,
347                                                 Variants: cg,
348                                         }}})
349                                         if err != nil {
350                                                 errs <- err
351                                                 return
352                                         }
353                                 }
354                                 for name, tseqs := range tilelib.refseqs {
355                                         err := encoders[start].Encode(LibraryEntry{CompactSequences: []CompactSequence{{
356                                                 Name:          name,
357                                                 TileSequences: tseqs,
358                                         }}})
359                                         if err != nil {
360                                                 errs <- err
361                                                 return
362                                         }
363                                 }
364                         }
365                         tvs := []TileVariant{}
366                         for tag := start; tag < len(tilelib.variant) && ctx.Err() == nil; tag += nfiles {
367                                 tvs = tvs[:0]
368                                 for idx, hash := range tilelib.variant[tag] {
369                                         tvs = append(tvs, TileVariant{
370                                                 Tag:      tagID(tag),
371                                                 Variant:  tileVariantID(idx + 1),
372                                                 Blake2b:  hash,
373                                                 Sequence: tilelib.seq[hash],
374                                         })
375                                 }
376                                 err := encoders[start].Encode(LibraryEntry{TileVariants: tvs})
377                                 if err != nil {
378                                         errs <- err
379                                         return
380                                 }
381                         }
382                         errs <- nil
383                 }()
384         }
385         for range files {
386                 err := <-errs
387                 if err != nil {
388                         return err
389                 }
390         }
391         for i := range zws {
392                 err := zws[i].Close()
393                 if err != nil {
394                         return err
395                 }
396                 err = bufws[i].Flush()
397                 if err != nil {
398                         return err
399                 }
400                 err = files[i].Close()
401                 if err != nil {
402                         return err
403                 }
404         }
405         return nil
406 }
407
408 // Load library data from rdr. Tile variants might be renumbered in
409 // the process; in that case, genomes variants will be renumbered to
410 // match.
411 //
412 // If onLoadGenome is non-nil, call it on each CompactGenome entry.
413 func (tilelib *tileLibrary) LoadGob(ctx context.Context, rdr io.Reader, gz bool, onLoadGenome func(CompactGenome)) error {
414         cgs := []CompactGenome{}
415         cseqs := []CompactSequence{}
416         variantmap := map[tileLibRef]tileVariantID{}
417         err := DecodeLibrary(rdr, gz, func(ent *LibraryEntry) error {
418                 if ctx.Err() != nil {
419                         return ctx.Err()
420                 }
421                 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
422                         return err
423                 }
424                 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
425                         return err
426                 }
427                 cgs = append(cgs, ent.CompactGenomes...)
428                 cseqs = append(cseqs, ent.CompactSequences...)
429                 return nil
430         })
431         if err != nil {
432                 return err
433         }
434         if ctx.Err() != nil {
435                 return ctx.Err()
436         }
437         err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
438         if err != nil {
439                 return err
440         }
441         err = tilelib.loadCompactSequences(cseqs, variantmap)
442         if err != nil {
443                 return err
444         }
445         return nil
446 }
447
448 func (tilelib *tileLibrary) dump(out io.Writer) {
449         printTV := func(tag int, variant tileVariantID) {
450                 if variant < 1 {
451                         fmt.Fprintf(out, " -")
452                 } else if tag >= len(tilelib.variant) {
453                         fmt.Fprintf(out, " (!tag=%d)", tag)
454                 } else if int(variant) > len(tilelib.variant[tag]) {
455                         fmt.Fprintf(out, " (tag=%d,!variant=%d)", tag, variant)
456                 } else {
457                         fmt.Fprintf(out, " %x", tilelib.variant[tag][variant-1][:8])
458                 }
459         }
460         for refname, refseqs := range tilelib.refseqs {
461                 for seqname, seq := range refseqs {
462                         fmt.Fprintf(out, "ref %s %s", refname, seqname)
463                         for _, libref := range seq {
464                                 printTV(int(libref.Tag), libref.Variant)
465                         }
466                         fmt.Fprintf(out, "\n")
467                 }
468         }
469         for name, cg := range tilelib.compactGenomes {
470                 fmt.Fprintf(out, "cg %s", name)
471                 for tag, variant := range cg {
472                         printTV(tag/2, variant)
473                 }
474                 fmt.Fprintf(out, "\n")
475         }
476 }
477
478 type importStats struct {
479         InputFile              string
480         InputLabel             string
481         InputLength            int
482         InputCoverage          int
483         PathLength             int
484         DroppedOutOfOrderTiles int
485 }
486
487 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader, matchChromosome *regexp.Regexp) (tileSeq, []importStats, error) {
488         ret := tileSeq{}
489         type jobT struct {
490                 label string
491                 fasta []byte
492         }
493         todo := make(chan jobT, 1)
494         scanner := bufio.NewScanner(rdr)
495         go func() {
496                 defer close(todo)
497                 var fasta []byte
498                 var seqlabel string
499                 for scanner.Scan() {
500                         buf := scanner.Bytes()
501                         if len(buf) > 0 && buf[0] == '>' {
502                                 todo <- jobT{seqlabel, append([]byte(nil), fasta...)}
503                                 seqlabel, fasta = strings.SplitN(string(buf[1:]), " ", 2)[0], fasta[:0]
504                                 log.Debugf("%s %s reading fasta", filelabel, seqlabel)
505                         } else {
506                                 fasta = append(fasta, bytes.ToLower(buf)...)
507                         }
508                 }
509                 todo <- jobT{seqlabel, fasta}
510         }()
511         type foundtag struct {
512                 pos   int
513                 tagid tagID
514         }
515         found := make([]foundtag, 2000000)
516         path := make([]tileLibRef, 2000000)
517         totalFoundTags := 0
518         totalPathLen := 0
519         skippedSequences := 0
520         taglen := tilelib.taglib.TagLen()
521         var stats []importStats
522         for job := range todo {
523                 if len(job.fasta) == 0 {
524                         continue
525                 } else if !matchChromosome.MatchString(job.label) {
526                         skippedSequences++
527                         continue
528                 }
529                 log.Debugf("%s %s tiling", filelabel, job.label)
530
531                 found = found[:0]
532                 tilelib.taglib.FindAll(job.fasta, func(tagid tagID, pos, taglen int) {
533                         found = append(found, foundtag{pos: pos, tagid: tagid})
534                 })
535                 totalFoundTags += len(found)
536                 if len(found) == 0 {
537                         log.Warnf("%s %s no tags found", filelabel, job.label)
538                 }
539
540                 skipped := 0
541                 if tilelib.skipOOO {
542                         log.Infof("%s %s keeping longest increasing subsequence", filelabel, job.label)
543                         keep := longestIncreasingSubsequence(len(found), func(i int) int { return int(found[i].tagid) })
544                         for i, x := range keep {
545                                 found[i] = found[x]
546                         }
547                         skipped = len(found) - len(keep)
548                         found = found[:len(keep)]
549                 }
550
551                 log.Infof("%s %s getting %d librefs", filelabel, job.label, len(found))
552                 throttle := &throttle{Max: runtime.NumCPU()}
553                 path = path[:len(found)]
554                 var lowquality int64
555                 for i, f := range found {
556                         i, f := i, f
557                         throttle.Acquire()
558                         go func() {
559                                 defer throttle.Release()
560                                 var startpos, endpos int
561                                 if i == 0 {
562                                         startpos = 0
563                                 } else {
564                                         startpos = f.pos
565                                 }
566                                 if i == len(found)-1 {
567                                         endpos = len(job.fasta)
568                                 } else {
569                                         endpos = found[i+1].pos + taglen
570                                 }
571                                 path[i] = tilelib.getRef(f.tagid, job.fasta[startpos:endpos])
572                                 if countBases(job.fasta[startpos:endpos]) != endpos-startpos {
573                                         atomic.AddInt64(&lowquality, 1)
574                                 }
575                         }()
576                 }
577                 throttle.Wait()
578
579                 log.Infof("%s %s copying path", filelabel, job.label)
580
581                 pathcopy := make([]tileLibRef, len(path))
582                 copy(pathcopy, path)
583                 ret[job.label] = pathcopy
584
585                 basesIn := countBases(job.fasta)
586                 log.Infof("%s %s fasta in %d coverage in %d path len %d low-quality %d skipped-out-of-order %d", filelabel, job.label, len(job.fasta), basesIn, len(path), lowquality, skipped)
587                 stats = append(stats, importStats{
588                         InputFile:              filelabel,
589                         InputLabel:             job.label,
590                         InputLength:            len(job.fasta),
591                         InputCoverage:          basesIn,
592                         PathLength:             len(path),
593                         DroppedOutOfOrderTiles: skipped,
594                 })
595
596                 totalPathLen += len(path)
597         }
598         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)
599         return ret, stats, scanner.Err()
600 }
601
602 func (tilelib *tileLibrary) Len() int64 {
603         return atomic.LoadInt64(&tilelib.variants)
604 }
605
606 // Return a tileLibRef for a tile with the given tag and sequence,
607 // adding the sequence to the library if needed.
608 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte) tileLibRef {
609         dropSeq := false
610         if !tilelib.retainNoCalls {
611                 for _, b := range seq {
612                         if b != 'a' && b != 'c' && b != 'g' && b != 't' {
613                                 dropSeq = true
614                                 break
615                         }
616                 }
617         }
618         seqhash := blake2b.Sum256(seq)
619         var vlock sync.Locker
620
621         tilelib.mtx.RLock()
622         if len(tilelib.vlock) > int(tag) {
623                 vlock = tilelib.vlock[tag]
624         }
625         tilelib.mtx.RUnlock()
626
627         if vlock != nil {
628                 vlock.Lock()
629                 for i, varhash := range tilelib.variant[tag] {
630                         if varhash == seqhash {
631                                 vlock.Unlock()
632                                 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
633                         }
634                 }
635                 vlock.Unlock()
636         } else {
637                 tilelib.mtx.Lock()
638                 if tilelib.variant == nil && tilelib.taglib != nil {
639                         tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
640                         tilelib.vlock = make([]sync.Locker, tilelib.taglib.Len())
641                         for i := range tilelib.vlock {
642                                 tilelib.vlock[i] = new(sync.Mutex)
643                         }
644                 }
645                 if int(tag) >= len(tilelib.variant) {
646                         oldlen := len(tilelib.vlock)
647                         for i := 0; i < oldlen; i++ {
648                                 tilelib.vlock[i].Lock()
649                         }
650                         // If we haven't seen the tag library yet (as
651                         // in a merge), tilelib.taglib.Len() is
652                         // zero. We can still behave correctly, we
653                         // just need to expand the tilelib.variant and
654                         // tilelib.vlock slices as needed.
655                         if int(tag) >= cap(tilelib.variant) {
656                                 // Allocate 2x capacity.
657                                 newslice := make([][][blake2b.Size256]byte, int(tag)+1, (int(tag)+1)*2)
658                                 copy(newslice, tilelib.variant)
659                                 tilelib.variant = newslice[:int(tag)+1]
660                                 newvlock := make([]sync.Locker, int(tag)+1, (int(tag)+1)*2)
661                                 copy(newvlock, tilelib.vlock)
662                                 tilelib.vlock = newvlock[:int(tag)+1]
663                         } else {
664                                 // Use previously allocated capacity,
665                                 // avoiding copy.
666                                 tilelib.variant = tilelib.variant[:int(tag)+1]
667                                 tilelib.vlock = tilelib.vlock[:int(tag)+1]
668                         }
669                         for i := oldlen; i < len(tilelib.vlock); i++ {
670                                 tilelib.vlock[i] = new(sync.Mutex)
671                         }
672                         for i := 0; i < oldlen; i++ {
673                                 tilelib.vlock[i].Unlock()
674                         }
675                 }
676                 vlock = tilelib.vlock[tag]
677                 tilelib.mtx.Unlock()
678         }
679
680         vlock.Lock()
681         for i, varhash := range tilelib.variant[tag] {
682                 if varhash == seqhash {
683                         vlock.Unlock()
684                         return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
685                 }
686         }
687         atomic.AddInt64(&tilelib.variants, 1)
688         tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
689         variant := tileVariantID(len(tilelib.variant[tag]))
690         vlock.Unlock()
691
692         if tilelib.retainTileSequences && !dropSeq {
693                 tilelib.mtx.Lock()
694                 if tilelib.seq == nil {
695                         tilelib.seq = map[[blake2b.Size256]byte][]byte{}
696                 }
697                 tilelib.seq[seqhash] = append([]byte(nil), seq...)
698                 tilelib.mtx.Unlock()
699         }
700
701         if tilelib.encoder != nil {
702                 saveSeq := seq
703                 if dropSeq {
704                         // Save the hash, but not the sequence
705                         saveSeq = nil
706                 }
707                 tilelib.encoder.Encode(LibraryEntry{
708                         TileVariants: []TileVariant{{
709                                 Tag:      tag,
710                                 Variant:  variant,
711                                 Blake2b:  seqhash,
712                                 Sequence: saveSeq,
713                         }},
714                 })
715         }
716         return tileLibRef{Tag: tag, Variant: variant}
717 }
718
719 func (tilelib *tileLibrary) TileVariantSequence(libref tileLibRef) []byte {
720         if libref.Variant == 0 || len(tilelib.variant) <= int(libref.Tag) || len(tilelib.variant[libref.Tag]) < int(libref.Variant) {
721                 return nil
722         }
723         return tilelib.seq[tilelib.variant[libref.Tag][libref.Variant-1]]
724 }
725
726 // Tidy deletes unreferenced tile variants and renumbers variants so
727 // more common variants have smaller IDs.
728 func (tilelib *tileLibrary) Tidy() {
729         log.Print("Tidy: compute inref")
730         inref := map[tileLibRef]bool{}
731         for _, refseq := range tilelib.refseqs {
732                 for _, librefs := range refseq {
733                         for _, libref := range librefs {
734                                 inref[libref] = true
735                         }
736                 }
737         }
738         log.Print("Tidy: compute remap")
739         remap := make([][]tileVariantID, len(tilelib.variant))
740         throttle := throttle{Max: runtime.NumCPU() + 1}
741         for tag, oldvariants := range tilelib.variant {
742                 tag, oldvariants := tagID(tag), oldvariants
743                 if tag%1000000 == 0 {
744                         log.Printf("Tidy: tag %d", tag)
745                 }
746                 throttle.Acquire()
747                 go func() {
748                         defer throttle.Release()
749                         uses := make([]int, len(oldvariants))
750                         for _, cg := range tilelib.compactGenomes {
751                                 for phase := 0; phase < 2; phase++ {
752                                         cgi := int(tag)*2 + phase
753                                         if cgi < len(cg) && cg[cgi] > 0 {
754                                                 uses[cg[cgi]-1]++
755                                         }
756                                 }
757                         }
758
759                         // Compute desired order of variants:
760                         // neworder[x] == index in oldvariants that
761                         // should move to position x.
762                         neworder := make([]int, len(oldvariants))
763                         for i := range neworder {
764                                 neworder[i] = i
765                         }
766                         sort.Slice(neworder, func(i, j int) bool {
767                                 if cmp := uses[neworder[i]] - uses[neworder[j]]; cmp != 0 {
768                                         return cmp > 0
769                                 } else {
770                                         return bytes.Compare(oldvariants[neworder[i]][:], oldvariants[neworder[j]][:]) < 0
771                                 }
772                         })
773
774                         // Replace tilelib.variant[tag] with a new
775                         // re-ordered slice of hashes, and make a
776                         // mapping from old to new variant IDs.
777                         remaptag := make([]tileVariantID, len(oldvariants)+1)
778                         newvariants := make([][blake2b.Size256]byte, 0, len(neworder))
779                         for _, oldi := range neworder {
780                                 if uses[oldi] > 0 || inref[tileLibRef{Tag: tag, Variant: tileVariantID(oldi + 1)}] {
781                                         newvariants = append(newvariants, oldvariants[oldi])
782                                         remaptag[oldi+1] = tileVariantID(len(newvariants))
783                                 }
784                         }
785                         tilelib.variant[tag] = newvariants
786                         remap[tag] = remaptag
787                 }()
788         }
789         throttle.Wait()
790
791         // Apply remap to genomes and reference sequences, so they
792         // refer to the same tile variants using the changed IDs.
793         log.Print("Tidy: apply remap")
794         var wg sync.WaitGroup
795         for _, cg := range tilelib.compactGenomes {
796                 cg := cg
797                 wg.Add(1)
798                 go func() {
799                         defer wg.Done()
800                         for idx, variant := range cg {
801                                 cg[idx] = remap[tagID(idx/2)][variant]
802                         }
803                 }()
804         }
805         for _, refcs := range tilelib.refseqs {
806                 for _, refseq := range refcs {
807                         refseq := refseq
808                         wg.Add(1)
809                         go func() {
810                                 defer wg.Done()
811                                 for i, tv := range refseq {
812                                         refseq[i].Variant = remap[tv.Tag][tv.Variant]
813                                 }
814                         }()
815                 }
816         }
817         wg.Wait()
818         log.Print("Tidy: done")
819 }
820
821 func countBases(seq []byte) int {
822         n := 0
823         for _, c := range seq {
824                 if isbase[c] {
825                         n++
826                 }
827         }
828         return n
829 }