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