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