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