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