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