Up load throttle to gomaxprocs.
[lightning.git] / tilelib.go
1 package lightning
2
3 import (
4         "bufio"
5         "bytes"
6         "context"
7         "encoding/gob"
8         "fmt"
9         "io"
10         "os"
11         "regexp"
12         "runtime"
13         "sort"
14         "strings"
15         "sync"
16         "sync/atomic"
17
18         "github.com/klauspost/pgzip"
19         log "github.com/sirupsen/logrus"
20         "golang.org/x/crypto/blake2b"
21 )
22
23 type tileVariantID uint16 // 1-based
24
25 type tileLibRef struct {
26         Tag     tagID
27         Variant tileVariantID
28 }
29
30 type tileSeq map[string][]tileLibRef
31
32 func (tseq tileSeq) Variants() ([]tileVariantID, int, int) {
33         maxtag := 0
34         for _, refs := range tseq {
35                 for _, ref := range refs {
36                         if maxtag < int(ref.Tag) {
37                                 maxtag = int(ref.Tag)
38                         }
39                 }
40         }
41         vars := make([]tileVariantID, maxtag+1)
42         var kept, dropped int
43         for _, refs := range tseq {
44                 for _, ref := range refs {
45                         if vars[int(ref.Tag)] != 0 {
46                                 dropped++
47                         } else {
48                                 kept++
49                         }
50                         vars[int(ref.Tag)] = ref.Variant
51                 }
52         }
53         return vars, kept, dropped
54 }
55
56 type tileLibrary struct {
57         retainNoCalls       bool
58         skipOOO             bool
59         retainTileSequences bool
60
61         taglib         *tagLibrary
62         variant        [][][blake2b.Size256]byte
63         refseqs        map[string]map[string][]tileLibRef
64         compactGenomes map[string][]tileVariantID
65         // count [][]int
66         seq      map[[blake2b.Size256]byte][]byte
67         variants int64
68         // if non-nil, write out any tile variants added while tiling
69         encoder *gob.Encoder
70
71         mtx   sync.RWMutex
72         vlock []sync.Locker
73 }
74
75 func (tilelib *tileLibrary) loadTagSet(newtagset [][]byte) error {
76         // Loading a tagset means either passing it through to the
77         // output (if it's the first one we've seen), or just ensuring
78         // it doesn't disagree with what we already have.
79         if len(newtagset) == 0 {
80                 return nil
81         }
82         tilelib.mtx.Lock()
83         defer tilelib.mtx.Unlock()
84         if tilelib.taglib == nil || tilelib.taglib.Len() == 0 {
85                 tilelib.taglib = &tagLibrary{}
86                 err := tilelib.taglib.setTags(newtagset)
87                 if err != nil {
88                         return err
89                 }
90                 if tilelib.encoder != nil {
91                         err = tilelib.encoder.Encode(LibraryEntry{
92                                 TagSet: newtagset,
93                         })
94                         if err != nil {
95                                 return err
96                         }
97                 }
98         } else if tilelib.taglib.Len() != len(newtagset) {
99                 return fmt.Errorf("cannot merge libraries with differing tagsets")
100         } else {
101                 current := tilelib.taglib.Tags()
102                 for i := range newtagset {
103                         if !bytes.Equal(newtagset[i], current[i]) {
104                                 return fmt.Errorf("cannot merge libraries with differing tagsets")
105                         }
106                 }
107         }
108         return nil
109 }
110
111 func (tilelib *tileLibrary) loadTileVariants(tvs []TileVariant, variantmap map[tileLibRef]tileVariantID) error {
112         for _, tv := range tvs {
113                 // Assign a new variant ID (unique across all inputs)
114                 // for each input variant.
115                 variantmap[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence).Variant
116         }
117         return nil
118 }
119
120 func (tilelib *tileLibrary) loadCompactGenomes(cgs []CompactGenome, variantmap map[tileLibRef]tileVariantID, onLoadGenome func(CompactGenome)) error {
121         log.Debugf("loadCompactGenomes: %d", len(cgs))
122         var wg sync.WaitGroup
123         errs := make(chan error, 1)
124         for _, cg := range cgs {
125                 wg.Add(1)
126                 cg := cg
127                 go func() {
128                         defer wg.Done()
129                         for i, variant := range cg.Variants {
130                                 if len(errs) > 0 {
131                                         return
132                                 }
133                                 if variant == 0 {
134                                         continue
135                                 }
136                                 tag := tagID(i / 2)
137                                 newvariant, ok := variantmap[tileLibRef{Tag: tag, Variant: variant}]
138                                 if !ok {
139                                         err := fmt.Errorf("oops: genome %q has variant %d for tag %d, but that variant was not in its library", cg.Name, variant, tag)
140                                         select {
141                                         case errs <- err:
142                                         default:
143                                         }
144                                         return
145                                 }
146                                 log.Tracef("loadCompactGenomes: cg %s tag %d variant %d => %d", cg.Name, tag, variant, newvariant)
147                                 cg.Variants[i] = newvariant
148                         }
149                         if onLoadGenome != nil {
150                                 onLoadGenome(cg)
151                         }
152                         if tilelib.encoder != nil {
153                                 err := tilelib.encoder.Encode(LibraryEntry{
154                                         CompactGenomes: []CompactGenome{cg},
155                                 })
156                                 if err != nil {
157                                         select {
158                                         case errs <- err:
159                                         default:
160                                         }
161                                         return
162                                 }
163                         }
164                         if tilelib.compactGenomes != nil {
165                                 tilelib.mtx.Lock()
166                                 defer tilelib.mtx.Unlock()
167                                 tilelib.compactGenomes[cg.Name] = cg.Variants
168                         }
169                 }()
170         }
171         wg.Wait()
172         go close(errs)
173         return <-errs
174 }
175
176 func (tilelib *tileLibrary) loadCompactSequences(cseqs []CompactSequence, variantmap map[tileLibRef]tileVariantID) error {
177         log.Debugf("loadCompactSequences: %d", len(cseqs))
178         for _, cseq := range cseqs {
179                 for _, tseq := range cseq.TileSequences {
180                         for i, libref := range tseq {
181                                 if libref.Variant == 0 {
182                                         // No variant (e.g., import
183                                         // dropped tiles with
184                                         // no-calls) = no translation.
185                                         continue
186                                 }
187                                 v, ok := variantmap[libref]
188                                 if !ok {
189                                         return fmt.Errorf("oops: CompactSequence %q has variant %d for tag %d, but that variant was not in its library", cseq.Name, libref.Variant, libref.Tag)
190                                 }
191                                 tseq[i].Variant = v
192                         }
193                 }
194                 if tilelib.encoder != nil {
195                         if err := tilelib.encoder.Encode(LibraryEntry{
196                                 CompactSequences: []CompactSequence{cseq},
197                         }); err != nil {
198                                 return err
199                         }
200                 }
201         }
202         tilelib.mtx.Lock()
203         defer tilelib.mtx.Unlock()
204         if tilelib.refseqs == nil {
205                 tilelib.refseqs = map[string]map[string][]tileLibRef{}
206         }
207         for _, cseq := range cseqs {
208                 tilelib.refseqs[cseq.Name] = cseq.TileSequences
209         }
210         return nil
211 }
212
213 func (tilelib *tileLibrary) LoadDir(ctx context.Context, path string, onLoadGenome func(CompactGenome)) error {
214         var files []string
215         var walk func(string) error
216         walk = func(path string) error {
217                 f, err := open(path)
218                 if err != nil {
219                         return err
220                 }
221                 defer f.Close()
222                 fis, err := f.Readdir(-1)
223                 if err != nil {
224                         files = append(files, path)
225                         return nil
226                 }
227                 for _, fi := range fis {
228                         if fi.Name() == "." || fi.Name() == ".." {
229                                 continue
230                         } else if 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         cgs := []CompactGenome{}
250         cseqs := []CompactSequence{}
251         variantmap := map[tileLibRef]tileVariantID{}
252         errs := make(chan error, len(files))
253         log.Infof("LoadDir: read %d files", len(files))
254         throttle := throttle{Max: runtime.GOMAXPROCS(0)}
255         for _, path := range files {
256                 path := path
257                 go func() {
258                         throttle.Acquire()
259                         defer throttle.Release()
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                         errs <- DecodeLibrary(f, strings.HasSuffix(path, ".gz"), func(ent *LibraryEntry) error {
268                                 if ctx.Err() != nil {
269                                         return ctx.Err()
270                                 }
271                                 if len(ent.TagSet) > 0 {
272                                         mtx.Lock()
273                                         if tilelib.taglib == nil || tilelib.taglib.Len() != len(ent.TagSet) {
274                                                 // load first set of tags, or
275                                                 // report mismatch if 2 sets
276                                                 // have different #tags.
277                                                 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
278                                                         mtx.Unlock()
279                                                         return err
280                                                 }
281                                         }
282                                         mtx.Unlock()
283                                 }
284                                 variantmapadd := map[tileLibRef]tileVariantID{}
285                                 for _, tv := range ent.TileVariants {
286                                         variantmapadd[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence).Variant
287                                 }
288                                 mtx.Lock()
289                                 cgs = append(cgs, ent.CompactGenomes...)
290                                 cseqs = append(cseqs, ent.CompactSequences...)
291                                 for k, v := range variantmapadd {
292                                         variantmap[k] = v
293                                 }
294                                 mtx.Unlock()
295                                 return nil
296                         })
297                 }()
298         }
299         for range files {
300                 err := <-errs
301                 if err != nil {
302                         return err
303                 }
304         }
305         log.Info("LoadDir: loadCompactGenomes")
306         err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
307         if err != nil {
308                 return err
309         }
310         log.Info("LoadDir: loadCompactSequences")
311         err = tilelib.loadCompactSequences(cseqs, variantmap)
312         if err != nil {
313                 return err
314         }
315         log.Info("LoadDir done")
316         return nil
317 }
318
319 func (tilelib *tileLibrary) WriteDir(dir string) error {
320         nfiles := 128
321         files := make([]*os.File, nfiles)
322         for i := range files {
323                 f, err := os.OpenFile(fmt.Sprintf("%s/library.%04d.gob.gz", dir, i), os.O_CREATE|os.O_WRONLY, 0666)
324                 if err != nil {
325                         return err
326                 }
327                 defer f.Close()
328                 files[i] = f
329         }
330         bufws := make([]*bufio.Writer, nfiles)
331         for i := range bufws {
332                 bufws[i] = bufio.NewWriterSize(files[i], 1<<26)
333         }
334         zws := make([]*pgzip.Writer, nfiles)
335         for i := range zws {
336                 zws[i] = pgzip.NewWriter(bufws[i])
337                 defer zws[i].Close()
338         }
339         encoders := make([]*gob.Encoder, nfiles)
340         for i := range encoders {
341                 encoders[i] = gob.NewEncoder(zws[i])
342         }
343
344         cgnames := make([]string, 0, len(tilelib.compactGenomes))
345         for name := range tilelib.compactGenomes {
346                 cgnames = append(cgnames, name)
347         }
348         sort.Strings(cgnames)
349
350         log.Infof("WriteDir: writing %d files", nfiles)
351         ctx, cancel := context.WithCancel(context.Background())
352         defer cancel()
353         errs := make(chan error, nfiles)
354         for start := range files {
355                 start := start
356                 go func() {
357                         err := encoders[start].Encode(LibraryEntry{TagSet: tilelib.taglib.Tags()})
358                         if err != nil {
359                                 errs <- err
360                                 return
361                         }
362                         if start == 0 {
363                                 // For now, just write all the refs to
364                                 // the first file
365                                 for name, tseqs := range tilelib.refseqs {
366                                         err := encoders[start].Encode(LibraryEntry{CompactSequences: []CompactSequence{{
367                                                 Name:          name,
368                                                 TileSequences: tseqs,
369                                         }}})
370                                         if err != nil {
371                                                 errs <- err
372                                                 return
373                                         }
374                                 }
375                         }
376                         for i := start; i < len(cgnames); i += nfiles {
377                                 err := encoders[start].Encode(LibraryEntry{CompactGenomes: []CompactGenome{{
378                                         Name:     cgnames[i],
379                                         Variants: tilelib.compactGenomes[cgnames[i]],
380                                 }}})
381                                 if err != nil {
382                                         errs <- err
383                                         return
384                                 }
385                         }
386                         tvs := []TileVariant{}
387                         for tag := start; tag < len(tilelib.variant) && ctx.Err() == nil; tag += nfiles {
388                                 tvs = tvs[:0]
389                                 for idx, hash := range tilelib.variant[tag] {
390                                         tvs = append(tvs, TileVariant{
391                                                 Tag:      tagID(tag),
392                                                 Variant:  tileVariantID(idx + 1),
393                                                 Blake2b:  hash,
394                                                 Sequence: tilelib.seq[hash],
395                                         })
396                                 }
397                                 err := encoders[start].Encode(LibraryEntry{TileVariants: tvs})
398                                 if err != nil {
399                                         errs <- err
400                                         return
401                                 }
402                         }
403                         errs <- nil
404                 }()
405         }
406         for range files {
407                 err := <-errs
408                 if err != nil {
409                         return err
410                 }
411         }
412         log.Info("WriteDir: flushing")
413         for i := range zws {
414                 err := zws[i].Close()
415                 if err != nil {
416                         return err
417                 }
418                 err = bufws[i].Flush()
419                 if err != nil {
420                         return err
421                 }
422                 err = files[i].Close()
423                 if err != nil {
424                         return err
425                 }
426         }
427         log.Info("WriteDir: done")
428         return nil
429 }
430
431 // Load library data from rdr. Tile variants might be renumbered in
432 // the process; in that case, genomes variants will be renumbered to
433 // match.
434 //
435 // If onLoadGenome is non-nil, call it on each CompactGenome entry.
436 func (tilelib *tileLibrary) LoadGob(ctx context.Context, rdr io.Reader, gz bool, onLoadGenome func(CompactGenome)) error {
437         cgs := []CompactGenome{}
438         cseqs := []CompactSequence{}
439         variantmap := map[tileLibRef]tileVariantID{}
440         err := DecodeLibrary(rdr, gz, func(ent *LibraryEntry) error {
441                 if ctx.Err() != nil {
442                         return ctx.Err()
443                 }
444                 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
445                         return err
446                 }
447                 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
448                         return err
449                 }
450                 cgs = append(cgs, ent.CompactGenomes...)
451                 cseqs = append(cseqs, ent.CompactSequences...)
452                 return nil
453         })
454         if err != nil {
455                 return err
456         }
457         if ctx.Err() != nil {
458                 return ctx.Err()
459         }
460         err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
461         if err != nil {
462                 return err
463         }
464         err = tilelib.loadCompactSequences(cseqs, variantmap)
465         if err != nil {
466                 return err
467         }
468         return nil
469 }
470
471 func (tilelib *tileLibrary) dump(out io.Writer) {
472         printTV := func(tag int, variant tileVariantID) {
473                 if variant < 1 {
474                         fmt.Fprintf(out, " -")
475                 } else if tag >= len(tilelib.variant) {
476                         fmt.Fprintf(out, " (!tag=%d)", tag)
477                 } else if int(variant) > len(tilelib.variant[tag]) {
478                         fmt.Fprintf(out, " (tag=%d,!variant=%d)", tag, variant)
479                 } else {
480                         fmt.Fprintf(out, " %x", tilelib.variant[tag][variant-1][:8])
481                 }
482         }
483         for refname, refseqs := range tilelib.refseqs {
484                 for seqname, seq := range refseqs {
485                         fmt.Fprintf(out, "ref %s %s", refname, seqname)
486                         for _, libref := range seq {
487                                 printTV(int(libref.Tag), libref.Variant)
488                         }
489                         fmt.Fprintf(out, "\n")
490                 }
491         }
492         for name, cg := range tilelib.compactGenomes {
493                 fmt.Fprintf(out, "cg %s", name)
494                 for tag, variant := range cg {
495                         printTV(tag/2, variant)
496                 }
497                 fmt.Fprintf(out, "\n")
498         }
499 }
500
501 type importStats struct {
502         InputFile              string
503         InputLabel             string
504         InputLength            int
505         InputCoverage          int
506         PathLength             int
507         DroppedOutOfOrderTiles int
508 }
509
510 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader, matchChromosome *regexp.Regexp) (tileSeq, []importStats, error) {
511         ret := tileSeq{}
512         type jobT struct {
513                 label string
514                 fasta []byte
515         }
516         todo := make(chan jobT, 1)
517         scanner := bufio.NewScanner(rdr)
518         go func() {
519                 defer close(todo)
520                 var fasta []byte
521                 var seqlabel string
522                 for scanner.Scan() {
523                         buf := scanner.Bytes()
524                         if len(buf) > 0 && buf[0] == '>' {
525                                 todo <- jobT{seqlabel, append([]byte(nil), fasta...)}
526                                 seqlabel, fasta = strings.SplitN(string(buf[1:]), " ", 2)[0], fasta[:0]
527                                 log.Debugf("%s %s reading fasta", filelabel, seqlabel)
528                         } else {
529                                 fasta = append(fasta, bytes.ToLower(buf)...)
530                         }
531                 }
532                 todo <- jobT{seqlabel, fasta}
533         }()
534         type foundtag struct {
535                 pos   int
536                 tagid tagID
537         }
538         found := make([]foundtag, 2000000)
539         path := make([]tileLibRef, 2000000)
540         totalFoundTags := 0
541         totalPathLen := 0
542         skippedSequences := 0
543         taglen := tilelib.taglib.TagLen()
544         var stats []importStats
545         for job := range todo {
546                 if len(job.fasta) == 0 {
547                         continue
548                 } else if !matchChromosome.MatchString(job.label) {
549                         skippedSequences++
550                         continue
551                 }
552                 log.Debugf("%s %s tiling", filelabel, job.label)
553
554                 found = found[:0]
555                 tilelib.taglib.FindAll(job.fasta, func(tagid tagID, pos, taglen int) {
556                         found = append(found, foundtag{pos: pos, tagid: tagid})
557                 })
558                 totalFoundTags += len(found)
559                 if len(found) == 0 {
560                         log.Warnf("%s %s no tags found", filelabel, job.label)
561                 }
562
563                 skipped := 0
564                 if tilelib.skipOOO {
565                         log.Infof("%s %s keeping longest increasing subsequence", filelabel, job.label)
566                         keep := longestIncreasingSubsequence(len(found), func(i int) int { return int(found[i].tagid) })
567                         for i, x := range keep {
568                                 found[i] = found[x]
569                         }
570                         skipped = len(found) - len(keep)
571                         found = found[:len(keep)]
572                 }
573
574                 log.Infof("%s %s getting %d librefs", filelabel, job.label, len(found))
575                 throttle := &throttle{Max: runtime.NumCPU()}
576                 path = path[:len(found)]
577                 var lowquality int64
578                 for i, f := range found {
579                         i, f := i, f
580                         throttle.Acquire()
581                         go func() {
582                                 defer throttle.Release()
583                                 var startpos, endpos int
584                                 if i == 0 {
585                                         startpos = 0
586                                 } else {
587                                         startpos = f.pos
588                                 }
589                                 if i == len(found)-1 {
590                                         endpos = len(job.fasta)
591                                 } else {
592                                         endpos = found[i+1].pos + taglen
593                                 }
594                                 path[i] = tilelib.getRef(f.tagid, job.fasta[startpos:endpos])
595                                 if countBases(job.fasta[startpos:endpos]) != endpos-startpos {
596                                         atomic.AddInt64(&lowquality, 1)
597                                 }
598                         }()
599                 }
600                 throttle.Wait()
601
602                 log.Infof("%s %s copying path", filelabel, job.label)
603
604                 pathcopy := make([]tileLibRef, len(path))
605                 copy(pathcopy, path)
606                 ret[job.label] = pathcopy
607
608                 basesIn := countBases(job.fasta)
609                 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)
610                 stats = append(stats, importStats{
611                         InputFile:              filelabel,
612                         InputLabel:             job.label,
613                         InputLength:            len(job.fasta),
614                         InputCoverage:          basesIn,
615                         PathLength:             len(path),
616                         DroppedOutOfOrderTiles: skipped,
617                 })
618
619                 totalPathLen += len(path)
620         }
621         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)
622         return ret, stats, scanner.Err()
623 }
624
625 func (tilelib *tileLibrary) Len() int64 {
626         return atomic.LoadInt64(&tilelib.variants)
627 }
628
629 // Return a tileLibRef for a tile with the given tag and sequence,
630 // adding the sequence to the library if needed.
631 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte) tileLibRef {
632         dropSeq := false
633         if !tilelib.retainNoCalls {
634                 for _, b := range seq {
635                         if b != 'a' && b != 'c' && b != 'g' && b != 't' {
636                                 dropSeq = true
637                                 break
638                         }
639                 }
640         }
641         seqhash := blake2b.Sum256(seq)
642         var vlock sync.Locker
643
644         tilelib.mtx.RLock()
645         if len(tilelib.vlock) > int(tag) {
646                 vlock = tilelib.vlock[tag]
647         }
648         tilelib.mtx.RUnlock()
649
650         if vlock != nil {
651                 vlock.Lock()
652                 for i, varhash := range tilelib.variant[tag] {
653                         if varhash == seqhash {
654                                 vlock.Unlock()
655                                 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
656                         }
657                 }
658                 vlock.Unlock()
659         } else {
660                 tilelib.mtx.Lock()
661                 if tilelib.variant == nil && tilelib.taglib != nil {
662                         tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
663                         tilelib.vlock = make([]sync.Locker, tilelib.taglib.Len())
664                         for i := range tilelib.vlock {
665                                 tilelib.vlock[i] = new(sync.Mutex)
666                         }
667                 }
668                 if int(tag) >= len(tilelib.variant) {
669                         oldlen := len(tilelib.vlock)
670                         for i := 0; i < oldlen; i++ {
671                                 tilelib.vlock[i].Lock()
672                         }
673                         // If we haven't seen the tag library yet (as
674                         // in a merge), tilelib.taglib.Len() is
675                         // zero. We can still behave correctly, we
676                         // just need to expand the tilelib.variant and
677                         // tilelib.vlock slices as needed.
678                         if int(tag) >= cap(tilelib.variant) {
679                                 // Allocate 2x capacity.
680                                 newslice := make([][][blake2b.Size256]byte, int(tag)+1, (int(tag)+1)*2)
681                                 copy(newslice, tilelib.variant)
682                                 tilelib.variant = newslice[:int(tag)+1]
683                                 newvlock := make([]sync.Locker, int(tag)+1, (int(tag)+1)*2)
684                                 copy(newvlock, tilelib.vlock)
685                                 tilelib.vlock = newvlock[:int(tag)+1]
686                         } else {
687                                 // Use previously allocated capacity,
688                                 // avoiding copy.
689                                 tilelib.variant = tilelib.variant[:int(tag)+1]
690                                 tilelib.vlock = tilelib.vlock[:int(tag)+1]
691                         }
692                         for i := oldlen; i < len(tilelib.vlock); i++ {
693                                 tilelib.vlock[i] = new(sync.Mutex)
694                         }
695                         for i := 0; i < oldlen; i++ {
696                                 tilelib.vlock[i].Unlock()
697                         }
698                 }
699                 vlock = tilelib.vlock[tag]
700                 tilelib.mtx.Unlock()
701         }
702
703         vlock.Lock()
704         for i, varhash := range tilelib.variant[tag] {
705                 if varhash == seqhash {
706                         vlock.Unlock()
707                         return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
708                 }
709         }
710         atomic.AddInt64(&tilelib.variants, 1)
711         tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
712         variant := tileVariantID(len(tilelib.variant[tag]))
713         vlock.Unlock()
714
715         if tilelib.retainTileSequences && !dropSeq {
716                 seqCopy := append([]byte(nil), seq...)
717                 tilelib.mtx.Lock()
718                 if tilelib.seq == nil {
719                         tilelib.seq = map[[blake2b.Size256]byte][]byte{}
720                 }
721                 tilelib.seq[seqhash] = seqCopy
722                 tilelib.mtx.Unlock()
723         }
724
725         if tilelib.encoder != nil {
726                 saveSeq := seq
727                 if dropSeq {
728                         // Save the hash, but not the sequence
729                         saveSeq = nil
730                 }
731                 tilelib.encoder.Encode(LibraryEntry{
732                         TileVariants: []TileVariant{{
733                                 Tag:      tag,
734                                 Variant:  variant,
735                                 Blake2b:  seqhash,
736                                 Sequence: saveSeq,
737                         }},
738                 })
739         }
740         return tileLibRef{Tag: tag, Variant: variant}
741 }
742
743 func (tilelib *tileLibrary) TileVariantSequence(libref tileLibRef) []byte {
744         if libref.Variant == 0 || len(tilelib.variant) <= int(libref.Tag) || len(tilelib.variant[libref.Tag]) < int(libref.Variant) {
745                 return nil
746         }
747         return tilelib.seq[tilelib.variant[libref.Tag][libref.Variant-1]]
748 }
749
750 // Tidy deletes unreferenced tile variants and renumbers variants so
751 // more common variants have smaller IDs.
752 func (tilelib *tileLibrary) Tidy() {
753         log.Print("Tidy: compute inref")
754         inref := map[tileLibRef]bool{}
755         for _, refseq := range tilelib.refseqs {
756                 for _, librefs := range refseq {
757                         for _, libref := range librefs {
758                                 inref[libref] = true
759                         }
760                 }
761         }
762         log.Print("Tidy: compute remap")
763         remap := make([][]tileVariantID, len(tilelib.variant))
764         throttle := throttle{Max: runtime.NumCPU() + 1}
765         for tag, oldvariants := range tilelib.variant {
766                 tag, oldvariants := tagID(tag), oldvariants
767                 if tag%1000000 == 0 {
768                         log.Printf("Tidy: tag %d", tag)
769                 }
770                 throttle.Acquire()
771                 go func() {
772                         defer throttle.Release()
773                         uses := make([]int, len(oldvariants))
774                         for _, cg := range tilelib.compactGenomes {
775                                 for phase := 0; phase < 2; phase++ {
776                                         cgi := int(tag)*2 + phase
777                                         if cgi < len(cg) && cg[cgi] > 0 {
778                                                 uses[cg[cgi]-1]++
779                                         }
780                                 }
781                         }
782
783                         // Compute desired order of variants:
784                         // neworder[x] == index in oldvariants that
785                         // should move to position x.
786                         neworder := make([]int, len(oldvariants))
787                         for i := range neworder {
788                                 neworder[i] = i
789                         }
790                         sort.Slice(neworder, func(i, j int) bool {
791                                 if cmp := uses[neworder[i]] - uses[neworder[j]]; cmp != 0 {
792                                         return cmp > 0
793                                 } else {
794                                         return bytes.Compare(oldvariants[neworder[i]][:], oldvariants[neworder[j]][:]) < 0
795                                 }
796                         })
797
798                         // Replace tilelib.variant[tag] with a new
799                         // re-ordered slice of hashes, and make a
800                         // mapping from old to new variant IDs.
801                         remaptag := make([]tileVariantID, len(oldvariants)+1)
802                         newvariants := make([][blake2b.Size256]byte, 0, len(neworder))
803                         for _, oldi := range neworder {
804                                 if uses[oldi] > 0 || inref[tileLibRef{Tag: tag, Variant: tileVariantID(oldi + 1)}] {
805                                         newvariants = append(newvariants, oldvariants[oldi])
806                                         remaptag[oldi+1] = tileVariantID(len(newvariants))
807                                 }
808                         }
809                         tilelib.variant[tag] = newvariants
810                         remap[tag] = remaptag
811                 }()
812         }
813         throttle.Wait()
814
815         // Apply remap to genomes and reference sequences, so they
816         // refer to the same tile variants using the changed IDs.
817         log.Print("Tidy: apply remap")
818         var wg sync.WaitGroup
819         for _, cg := range tilelib.compactGenomes {
820                 cg := cg
821                 wg.Add(1)
822                 go func() {
823                         defer wg.Done()
824                         for idx, variant := range cg {
825                                 cg[idx] = remap[tagID(idx/2)][variant]
826                         }
827                 }()
828         }
829         for _, refcs := range tilelib.refseqs {
830                 for _, refseq := range refcs {
831                         refseq := refseq
832                         wg.Add(1)
833                         go func() {
834                                 defer wg.Done()
835                                 for i, tv := range refseq {
836                                         refseq[i].Variant = remap[tv.Tag][tv.Variant]
837                                 }
838                         }()
839                 }
840         }
841         wg.Wait()
842         log.Print("Tidy: done")
843 }
844
845 func countBases(seq []byte) int {
846         n := 0
847         for _, c := range seq {
848                 if isbase[c] {
849                         n++
850                 }
851         }
852         return n
853 }