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