Fix "gob: encoder: message too big"
[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 fi.IsDir() {
231                                 err = walk(path + "/" + fi.Name())
232                                 if err != nil {
233                                         return err
234                                 }
235                         } else if strings.HasSuffix(path, ".gob") || strings.HasSuffix(path, ".gob.gz") {
236                                 files = append(files, path)
237                         }
238                 }
239                 return nil
240         }
241         err := walk(path)
242         if err != nil {
243                 return err
244         }
245         ctx, cancel := context.WithCancel(ctx)
246         defer cancel()
247         var mtx sync.Mutex
248         cgs := []CompactGenome{}
249         cseqs := []CompactSequence{}
250         variantmap := map[tileLibRef]tileVariantID{}
251         errs := make(chan error, len(files))
252         for _, path := range files {
253                 path := path
254                 go func() {
255                         f, err := open(path)
256                         if err != nil {
257                                 errs <- err
258                                 return
259                         }
260                         defer f.Close()
261                         errs <- DecodeLibrary(f, strings.HasSuffix(path, ".gz"), func(ent *LibraryEntry) error {
262                                 if ctx.Err() != nil {
263                                         return ctx.Err()
264                                 }
265                                 mtx.Lock()
266                                 defer mtx.Unlock()
267                                 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
268                                         return err
269                                 }
270                                 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
271                                         return err
272                                 }
273                                 cgs = append(cgs, ent.CompactGenomes...)
274                                 cseqs = append(cseqs, ent.CompactSequences...)
275                                 return nil
276                         })
277                 }()
278         }
279         for range files {
280                 err := <-errs
281                 if err != nil {
282                         return err
283                 }
284         }
285         err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
286         if err != nil {
287                 return err
288         }
289         err = tilelib.loadCompactSequences(cseqs, variantmap)
290         if err != nil {
291                 return err
292         }
293         return nil
294 }
295
296 func (tilelib *tileLibrary) WriteDir(dir string) error {
297         nfiles := 128
298         files := make([]*os.File, nfiles)
299         for i := range files {
300                 f, err := os.OpenFile(fmt.Sprintf("%s/library.%04d.gob.gz", dir, i), os.O_CREATE|os.O_WRONLY, 0666)
301                 if err != nil {
302                         return err
303                 }
304                 defer f.Close()
305                 files[i] = f
306         }
307         bufws := make([]*bufio.Writer, nfiles)
308         for i := range bufws {
309                 bufws[i] = bufio.NewWriterSize(files[i], 1<<26)
310         }
311         zws := make([]*pgzip.Writer, nfiles)
312         for i := range zws {
313                 zws[i] = pgzip.NewWriter(bufws[i])
314                 defer zws[i].Close()
315         }
316         encoders := make([]*gob.Encoder, nfiles)
317         for i := range encoders {
318                 encoders[i] = gob.NewEncoder(zws[i])
319         }
320         ctx, cancel := context.WithCancel(context.Background())
321         defer cancel()
322         errs := make(chan error, nfiles)
323         for start := range files {
324                 start := start
325                 go func() {
326                         err := encoders[start].Encode(LibraryEntry{TagSet: tilelib.taglib.Tags()})
327                         if err != nil {
328                                 errs <- err
329                                 return
330                         }
331                         if start == 0 {
332                                 // For now, just write all the genomes and refs
333                                 // to the first file
334                                 for name, cg := range tilelib.compactGenomes {
335                                         err := encoders[start].Encode(LibraryEntry{CompactGenomes: []CompactGenome{{
336                                                 Name:     name,
337                                                 Variants: cg,
338                                         }}})
339                                         if err != nil {
340                                                 errs <- err
341                                                 return
342                                         }
343                                 }
344                                 for name, tseqs := range tilelib.refseqs {
345                                         err := encoders[start].Encode(LibraryEntry{CompactSequences: []CompactSequence{{
346                                                 Name:          name,
347                                                 TileSequences: tseqs,
348                                         }}})
349                                         if err != nil {
350                                                 errs <- err
351                                                 return
352                                         }
353                                 }
354                         }
355                         tvs := []TileVariant{}
356                         for tag := start; tag < len(tilelib.variant) && ctx.Err() == nil; tag += nfiles {
357                                 tvs = tvs[:0]
358                                 for idx, hash := range tilelib.variant[tag] {
359                                         tvs = append(tvs, TileVariant{
360                                                 Tag:      tagID(tag),
361                                                 Variant:  tileVariantID(idx + 1),
362                                                 Blake2b:  hash,
363                                                 Sequence: tilelib.seq[hash],
364                                         })
365                                 }
366                                 err := encoders[start].Encode(LibraryEntry{TileVariants: tvs})
367                                 if err != nil {
368                                         errs <- err
369                                         return
370                                 }
371                         }
372                         errs <- nil
373                 }()
374         }
375         for range files {
376                 err := <-errs
377                 if err != nil {
378                         return err
379                 }
380         }
381         for i := range zws {
382                 err := zws[i].Close()
383                 if err != nil {
384                         return err
385                 }
386                 err = bufws[i].Flush()
387                 if err != nil {
388                         return err
389                 }
390                 err = files[i].Close()
391                 if err != nil {
392                         return err
393                 }
394         }
395         return nil
396 }
397
398 // Load library data from rdr. Tile variants might be renumbered in
399 // the process; in that case, genomes variants will be renumbered to
400 // match.
401 //
402 // If onLoadGenome is non-nil, call it on each CompactGenome entry.
403 func (tilelib *tileLibrary) LoadGob(ctx context.Context, rdr io.Reader, gz bool, onLoadGenome func(CompactGenome)) error {
404         cgs := []CompactGenome{}
405         cseqs := []CompactSequence{}
406         variantmap := map[tileLibRef]tileVariantID{}
407         err := DecodeLibrary(rdr, gz, func(ent *LibraryEntry) error {
408                 if ctx.Err() != nil {
409                         return ctx.Err()
410                 }
411                 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
412                         return err
413                 }
414                 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
415                         return err
416                 }
417                 cgs = append(cgs, ent.CompactGenomes...)
418                 cseqs = append(cseqs, ent.CompactSequences...)
419                 return nil
420         })
421         if err != nil {
422                 return err
423         }
424         if ctx.Err() != nil {
425                 return ctx.Err()
426         }
427         err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
428         if err != nil {
429                 return err
430         }
431         err = tilelib.loadCompactSequences(cseqs, variantmap)
432         if err != nil {
433                 return err
434         }
435         return nil
436 }
437
438 func (tilelib *tileLibrary) dump(out io.Writer) {
439         printTV := func(tag int, variant tileVariantID) {
440                 if variant < 1 {
441                         fmt.Fprintf(out, " -")
442                 } else if tag >= len(tilelib.variant) {
443                         fmt.Fprintf(out, " (!tag=%d)", tag)
444                 } else if int(variant) > len(tilelib.variant[tag]) {
445                         fmt.Fprintf(out, " (tag=%d,!variant=%d)", tag, variant)
446                 } else {
447                         fmt.Fprintf(out, " %x", tilelib.variant[tag][variant-1][:8])
448                 }
449         }
450         for refname, refseqs := range tilelib.refseqs {
451                 for seqname, seq := range refseqs {
452                         fmt.Fprintf(out, "ref %s %s", refname, seqname)
453                         for _, libref := range seq {
454                                 printTV(int(libref.Tag), libref.Variant)
455                         }
456                         fmt.Fprintf(out, "\n")
457                 }
458         }
459         for name, cg := range tilelib.compactGenomes {
460                 fmt.Fprintf(out, "cg %s", name)
461                 for tag, variant := range cg {
462                         printTV(tag/2, variant)
463                 }
464                 fmt.Fprintf(out, "\n")
465         }
466 }
467
468 type importStats struct {
469         InputFile              string
470         InputLabel             string
471         InputLength            int
472         InputCoverage          int
473         PathLength             int
474         DroppedOutOfOrderTiles int
475 }
476
477 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader, matchChromosome *regexp.Regexp) (tileSeq, []importStats, error) {
478         ret := tileSeq{}
479         type jobT struct {
480                 label string
481                 fasta []byte
482         }
483         todo := make(chan jobT, 1)
484         scanner := bufio.NewScanner(rdr)
485         go func() {
486                 defer close(todo)
487                 var fasta []byte
488                 var seqlabel string
489                 for scanner.Scan() {
490                         buf := scanner.Bytes()
491                         if len(buf) > 0 && buf[0] == '>' {
492                                 todo <- jobT{seqlabel, append([]byte(nil), fasta...)}
493                                 seqlabel, fasta = strings.SplitN(string(buf[1:]), " ", 2)[0], fasta[:0]
494                                 log.Debugf("%s %s reading fasta", filelabel, seqlabel)
495                         } else {
496                                 fasta = append(fasta, bytes.ToLower(buf)...)
497                         }
498                 }
499                 todo <- jobT{seqlabel, fasta}
500         }()
501         type foundtag struct {
502                 pos   int
503                 tagid tagID
504         }
505         found := make([]foundtag, 2000000)
506         path := make([]tileLibRef, 2000000)
507         totalFoundTags := 0
508         totalPathLen := 0
509         skippedSequences := 0
510         taglen := tilelib.taglib.TagLen()
511         var stats []importStats
512         for job := range todo {
513                 if len(job.fasta) == 0 {
514                         continue
515                 } else if !matchChromosome.MatchString(job.label) {
516                         skippedSequences++
517                         continue
518                 }
519                 log.Debugf("%s %s tiling", filelabel, job.label)
520
521                 found = found[:0]
522                 tilelib.taglib.FindAll(job.fasta, func(tagid tagID, pos, taglen int) {
523                         found = append(found, foundtag{pos: pos, tagid: tagid})
524                 })
525                 totalFoundTags += len(found)
526                 if len(found) == 0 {
527                         log.Warnf("%s %s no tags found", filelabel, job.label)
528                 }
529
530                 skipped := 0
531                 if tilelib.skipOOO {
532                         log.Infof("%s %s keeping longest increasing subsequence", filelabel, job.label)
533                         keep := longestIncreasingSubsequence(len(found), func(i int) int { return int(found[i].tagid) })
534                         for i, x := range keep {
535                                 found[i] = found[x]
536                         }
537                         skipped = len(found) - len(keep)
538                         found = found[:len(keep)]
539                 }
540
541                 log.Infof("%s %s getting %d librefs", filelabel, job.label, len(found))
542                 throttle := &throttle{Max: runtime.NumCPU()}
543                 path = path[:len(found)]
544                 var lowquality int64
545                 for i, f := range found {
546                         i, f := i, f
547                         throttle.Acquire()
548                         go func() {
549                                 defer throttle.Release()
550                                 var startpos, endpos int
551                                 if i == 0 {
552                                         startpos = 0
553                                 } else {
554                                         startpos = f.pos
555                                 }
556                                 if i == len(found)-1 {
557                                         endpos = len(job.fasta)
558                                 } else {
559                                         endpos = found[i+1].pos + taglen
560                                 }
561                                 path[i] = tilelib.getRef(f.tagid, job.fasta[startpos:endpos])
562                                 if countBases(job.fasta[startpos:endpos]) != endpos-startpos {
563                                         atomic.AddInt64(&lowquality, 1)
564                                 }
565                         }()
566                 }
567                 throttle.Wait()
568
569                 log.Infof("%s %s copying path", filelabel, job.label)
570
571                 pathcopy := make([]tileLibRef, len(path))
572                 copy(pathcopy, path)
573                 ret[job.label] = pathcopy
574
575                 basesIn := countBases(job.fasta)
576                 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)
577                 stats = append(stats, importStats{
578                         InputFile:              filelabel,
579                         InputLabel:             job.label,
580                         InputLength:            len(job.fasta),
581                         InputCoverage:          basesIn,
582                         PathLength:             len(path),
583                         DroppedOutOfOrderTiles: skipped,
584                 })
585
586                 totalPathLen += len(path)
587         }
588         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)
589         return ret, stats, scanner.Err()
590 }
591
592 func (tilelib *tileLibrary) Len() int64 {
593         return atomic.LoadInt64(&tilelib.variants)
594 }
595
596 // Return a tileLibRef for a tile with the given tag and sequence,
597 // adding the sequence to the library if needed.
598 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte) tileLibRef {
599         dropSeq := false
600         if !tilelib.retainNoCalls {
601                 for _, b := range seq {
602                         if b != 'a' && b != 'c' && b != 'g' && b != 't' {
603                                 dropSeq = true
604                                 break
605                         }
606                 }
607         }
608         seqhash := blake2b.Sum256(seq)
609         var vlock sync.Locker
610
611         tilelib.mtx.RLock()
612         if len(tilelib.vlock) > int(tag) {
613                 vlock = tilelib.vlock[tag]
614         }
615         tilelib.mtx.RUnlock()
616
617         if vlock != nil {
618                 vlock.Lock()
619                 for i, varhash := range tilelib.variant[tag] {
620                         if varhash == seqhash {
621                                 vlock.Unlock()
622                                 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
623                         }
624                 }
625                 vlock.Unlock()
626         } else {
627                 tilelib.mtx.Lock()
628                 if tilelib.variant == nil && tilelib.taglib != nil {
629                         tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
630                         tilelib.vlock = make([]sync.Locker, tilelib.taglib.Len())
631                         for i := range tilelib.vlock {
632                                 tilelib.vlock[i] = new(sync.Mutex)
633                         }
634                 }
635                 if int(tag) >= len(tilelib.variant) {
636                         oldlen := len(tilelib.vlock)
637                         for i := 0; i < oldlen; i++ {
638                                 tilelib.vlock[i].Lock()
639                         }
640                         // If we haven't seen the tag library yet (as
641                         // in a merge), tilelib.taglib.Len() is
642                         // zero. We can still behave correctly, we
643                         // just need to expand the tilelib.variant and
644                         // tilelib.vlock slices as needed.
645                         if int(tag) >= cap(tilelib.variant) {
646                                 // Allocate 2x capacity.
647                                 newslice := make([][][blake2b.Size256]byte, int(tag)+1, (int(tag)+1)*2)
648                                 copy(newslice, tilelib.variant)
649                                 tilelib.variant = newslice[:int(tag)+1]
650                                 newvlock := make([]sync.Locker, int(tag)+1, (int(tag)+1)*2)
651                                 copy(newvlock, tilelib.vlock)
652                                 tilelib.vlock = newvlock[:int(tag)+1]
653                         } else {
654                                 // Use previously allocated capacity,
655                                 // avoiding copy.
656                                 tilelib.variant = tilelib.variant[:int(tag)+1]
657                                 tilelib.vlock = tilelib.vlock[:int(tag)+1]
658                         }
659                         for i := oldlen; i < len(tilelib.vlock); i++ {
660                                 tilelib.vlock[i] = new(sync.Mutex)
661                         }
662                         for i := 0; i < oldlen; i++ {
663                                 tilelib.vlock[i].Unlock()
664                         }
665                 }
666                 vlock = tilelib.vlock[tag]
667                 tilelib.mtx.Unlock()
668         }
669
670         vlock.Lock()
671         for i, varhash := range tilelib.variant[tag] {
672                 if varhash == seqhash {
673                         vlock.Unlock()
674                         return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
675                 }
676         }
677         atomic.AddInt64(&tilelib.variants, 1)
678         tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
679         variant := tileVariantID(len(tilelib.variant[tag]))
680         vlock.Unlock()
681
682         if tilelib.retainTileSequences && !dropSeq {
683                 tilelib.mtx.Lock()
684                 if tilelib.seq == nil {
685                         tilelib.seq = map[[blake2b.Size256]byte][]byte{}
686                 }
687                 tilelib.seq[seqhash] = append([]byte(nil), seq...)
688                 tilelib.mtx.Unlock()
689         }
690
691         if tilelib.encoder != nil {
692                 saveSeq := seq
693                 if dropSeq {
694                         // Save the hash, but not the sequence
695                         saveSeq = nil
696                 }
697                 tilelib.encoder.Encode(LibraryEntry{
698                         TileVariants: []TileVariant{{
699                                 Tag:      tag,
700                                 Variant:  variant,
701                                 Blake2b:  seqhash,
702                                 Sequence: saveSeq,
703                         }},
704                 })
705         }
706         return tileLibRef{Tag: tag, Variant: variant}
707 }
708
709 func (tilelib *tileLibrary) TileVariantSequence(libref tileLibRef) []byte {
710         if libref.Variant == 0 || len(tilelib.variant) <= int(libref.Tag) || len(tilelib.variant[libref.Tag]) < int(libref.Variant) {
711                 return nil
712         }
713         return tilelib.seq[tilelib.variant[libref.Tag][libref.Variant-1]]
714 }
715
716 // Tidy deletes unreferenced tile variants and renumbers variants so
717 // more common variants have smaller IDs.
718 func (tilelib *tileLibrary) Tidy() {
719         log.Print("Tidy: compute inref")
720         inref := map[tileLibRef]bool{}
721         for _, refseq := range tilelib.refseqs {
722                 for _, librefs := range refseq {
723                         for _, libref := range librefs {
724                                 inref[libref] = true
725                         }
726                 }
727         }
728         log.Print("Tidy: compute remap")
729         remap := make([][]tileVariantID, len(tilelib.variant))
730         throttle := throttle{Max: runtime.NumCPU() + 1}
731         for tag, oldvariants := range tilelib.variant {
732                 tag, oldvariants := tagID(tag), oldvariants
733                 if tag%1000000 == 0 {
734                         log.Printf("Tidy: tag %d", tag)
735                 }
736                 throttle.Acquire()
737                 go func() {
738                         defer throttle.Release()
739                         uses := make([]int, len(oldvariants))
740                         for _, cg := range tilelib.compactGenomes {
741                                 for phase := 0; phase < 2; phase++ {
742                                         cgi := int(tag)*2 + phase
743                                         if cgi < len(cg) && cg[cgi] > 0 {
744                                                 uses[cg[cgi]-1]++
745                                         }
746                                 }
747                         }
748
749                         // Compute desired order of variants:
750                         // neworder[x] == index in oldvariants that
751                         // should move to position x.
752                         neworder := make([]int, len(oldvariants))
753                         for i := range neworder {
754                                 neworder[i] = i
755                         }
756                         sort.Slice(neworder, func(i, j int) bool {
757                                 if cmp := uses[neworder[i]] - uses[neworder[j]]; cmp != 0 {
758                                         return cmp > 0
759                                 } else {
760                                         return bytes.Compare(oldvariants[neworder[i]][:], oldvariants[neworder[j]][:]) < 0
761                                 }
762                         })
763
764                         // Replace tilelib.variant[tag] with a new
765                         // re-ordered slice of hashes, and make a
766                         // mapping from old to new variant IDs.
767                         remaptag := make([]tileVariantID, len(oldvariants)+1)
768                         newvariants := make([][blake2b.Size256]byte, 0, len(neworder))
769                         for _, oldi := range neworder {
770                                 if uses[oldi] > 0 || inref[tileLibRef{Tag: tag, Variant: tileVariantID(oldi + 1)}] {
771                                         newvariants = append(newvariants, oldvariants[oldi])
772                                         remaptag[oldi+1] = tileVariantID(len(newvariants))
773                                 }
774                         }
775                         tilelib.variant[tag] = newvariants
776                         remap[tag] = remaptag
777                 }()
778         }
779         throttle.Wait()
780
781         // Apply remap to genomes and reference sequences, so they
782         // refer to the same tile variants using the changed IDs.
783         log.Print("Tidy: apply remap")
784         var wg sync.WaitGroup
785         for _, cg := range tilelib.compactGenomes {
786                 cg := cg
787                 wg.Add(1)
788                 go func() {
789                         defer wg.Done()
790                         for idx, variant := range cg {
791                                 cg[idx] = remap[tagID(idx/2)][variant]
792                         }
793                 }()
794         }
795         for _, refcs := range tilelib.refseqs {
796                 for _, refseq := range refcs {
797                         refseq := refseq
798                         wg.Add(1)
799                         go func() {
800                                 defer wg.Done()
801                                 for i, tv := range refseq {
802                                         refseq[i].Variant = remap[tv.Tag][tv.Variant]
803                                 }
804                         }()
805                 }
806         }
807         wg.Wait()
808         log.Print("Tidy: done")
809 }
810
811 func countBases(seq []byte) int {
812         n := 0
813         for _, c := range seq {
814                 if isbase[c] {
815                         n++
816                 }
817         }
818         return n
819 }