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