1 // Copyright (C) The Lightning Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
22 "github.com/klauspost/pgzip"
23 log "github.com/sirupsen/logrus"
24 "golang.org/x/crypto/blake2b"
27 type tileVariantID uint16 // 1-based
29 type tileLibRef struct {
34 type tileSeq map[string][]tileLibRef
36 func (tseq tileSeq) Variants() ([]tileVariantID, int, int) {
38 for _, refs := range tseq {
39 for _, ref := range refs {
40 if maxtag < int(ref.Tag) {
45 vars := make([]tileVariantID, maxtag+1)
47 for _, refs := range tseq {
48 for _, ref := range refs {
49 if vars[int(ref.Tag)] != 0 {
54 vars[int(ref.Tag)] = ref.Variant
57 return vars, kept, dropped
60 type tileLibrary struct {
63 retainTileSequences bool
67 variant [][][blake2b.Size256]byte
68 refseqs map[string]map[string][]tileLibRef
69 compactGenomes map[string][]tileVariantID
70 seq2 map[[2]byte]map[[blake2b.Size256]byte][]byte
71 seq2lock map[[2]byte]sync.Locker
73 // if non-nil, write out any tile variants added while tiling
75 // set Ref flag when writing new variants to encoder
78 onAddTileVariant func(libref tileLibRef, hash [blake2b.Size256]byte, seq []byte) error
79 onAddGenome func(CompactGenome) error
80 onAddRefseq func(CompactSequence) error
86 func (tilelib *tileLibrary) loadTagSet(newtagset [][]byte) error {
87 // Loading a tagset means either passing it through to the
88 // output (if it's the first one we've seen), or just ensuring
89 // it doesn't disagree with what we already have.
90 if len(newtagset) == 0 {
94 defer tilelib.mtx.Unlock()
95 if tilelib.taglib == nil || tilelib.taglib.Len() == 0 {
96 tilelib.taglib = &tagLibrary{}
97 err := tilelib.taglib.setTags(newtagset)
101 if tilelib.encoder != nil {
102 err = tilelib.encoder.Encode(LibraryEntry{
109 } else if tilelib.taglib.Len() != len(newtagset) {
110 return fmt.Errorf("cannot merge libraries with differing tagsets")
112 current := tilelib.taglib.Tags()
113 for i := range newtagset {
114 if !bytes.Equal(newtagset[i], current[i]) {
115 return fmt.Errorf("cannot merge libraries with differing tagsets")
122 func (tilelib *tileLibrary) loadTileVariants(tvs []TileVariant, variantmap map[tileLibRef]tileVariantID) error {
123 for _, tv := range tvs {
124 // Assign a new variant ID (unique across all inputs)
125 // for each input variant.
126 variantmap[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence, tv.Ref).Variant
131 func (tilelib *tileLibrary) loadCompactGenomes(cgs []CompactGenome, variantmap map[tileLibRef]tileVariantID) error {
132 log.Debugf("loadCompactGenomes: %d", len(cgs))
133 var wg sync.WaitGroup
134 errs := make(chan error, 1)
135 for _, cg := range cgs {
140 for i, variant := range cg.Variants {
148 newvariant, ok := variantmap[tileLibRef{Tag: tag, Variant: variant}]
150 err := fmt.Errorf("oops: genome %q has variant %d for tag %d, but that variant was not in its library", cg.Name, variant, tag)
157 // log.Tracef("loadCompactGenomes: cg %s tag %d variant %d => %d", cg.Name, tag, variant, newvariant)
158 cg.Variants[i] = newvariant
160 if tilelib.onAddGenome != nil {
161 err := tilelib.onAddGenome(cg)
170 if tilelib.encoder != nil {
171 err := tilelib.encoder.Encode(LibraryEntry{
172 CompactGenomes: []CompactGenome{cg},
182 if tilelib.compactGenomes != nil {
184 defer tilelib.mtx.Unlock()
185 tilelib.compactGenomes[cg.Name] = cg.Variants
194 func (tilelib *tileLibrary) loadCompactSequences(cseqs []CompactSequence, variantmap map[tileLibRef]tileVariantID) error {
195 log.Infof("loadCompactSequences: %d todo", len(cseqs))
196 for _, cseq := range cseqs {
197 log.Infof("loadCompactSequences: checking %s", cseq.Name)
198 for _, tseq := range cseq.TileSequences {
199 for i, libref := range tseq {
200 if libref.Variant == 0 {
201 // No variant (e.g., import
202 // dropped tiles with
203 // no-calls) = no translation.
206 v, ok := variantmap[libref]
208 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)
213 if tilelib.encoder != nil {
214 if err := tilelib.encoder.Encode(LibraryEntry{
215 CompactSequences: []CompactSequence{cseq},
220 if tilelib.onAddRefseq != nil {
221 err := tilelib.onAddRefseq(cseq)
226 log.Infof("loadCompactSequences: checking %s done", cseq.Name)
229 defer tilelib.mtx.Unlock()
230 if tilelib.refseqs == nil {
231 tilelib.refseqs = map[string]map[string][]tileLibRef{}
233 for _, cseq := range cseqs {
234 tilelib.refseqs[cseq.Name] = cseq.TileSequences
236 log.Info("loadCompactSequences: done")
240 func allFiles(path string, re *regexp.Regexp) ([]string, error) {
247 fis, err := f.Readdir(-1)
249 return []string{path}, nil
251 for _, fi := range fis {
252 if fi.Name() == "." || fi.Name() == ".." {
254 } else if child := path + "/" + fi.Name(); fi.IsDir() {
255 add, err := allFiles(child, re)
259 files = append(files, add...)
260 } else if re == nil || re.MatchString(child) {
261 files = append(files, child)
268 var matchGobFile = regexp.MustCompile(`\.gob(\.gz)?$`)
270 func (tilelib *tileLibrary) LoadDir(ctx context.Context, path string) error {
271 log.Infof("LoadDir: walk dir %s", path)
272 files, err := allFiles(path, matchGobFile)
276 ctx, cancel := context.WithCancel(ctx)
279 allcgs := make([][]CompactGenome, len(files))
280 allcseqs := make([][]CompactSequence, len(files))
281 allvariantmap := map[tileLibRef]tileVariantID{}
282 errs := make(chan error, len(files))
283 log.Infof("LoadDir: read %d files", len(files))
284 for fileno, path := range files {
285 fileno, path := fileno, path
293 defer log.Infof("LoadDir: finished reading %s", path)
295 var variantmap = map[tileLibRef]tileVariantID{}
296 var cgs []CompactGenome
297 var cseqs []CompactSequence
298 err = DecodeLibrary(f, strings.HasSuffix(path, ".gz"), func(ent *LibraryEntry) error {
299 if ctx.Err() != nil {
302 if len(ent.TagSet) > 0 {
304 if tilelib.taglib == nil || tilelib.taglib.Len() != len(ent.TagSet) {
305 // load first set of tags, or
306 // report mismatch if 2 sets
307 // have different #tags.
308 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
315 for _, tv := range ent.TileVariants {
316 variantmap[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence, tv.Ref).Variant
318 cgs = append(cgs, ent.CompactGenomes...)
319 cseqs = append(cseqs, ent.CompactSequences...)
323 allcseqs[fileno] = cseqs
326 for k, v := range variantmap {
339 log.Info("LoadDir: loadCompactGenomes")
340 var flatcgs []CompactGenome
341 for _, cgs := range allcgs {
342 flatcgs = append(flatcgs, cgs...)
344 err = tilelib.loadCompactGenomes(flatcgs, allvariantmap)
349 log.Info("LoadDir: loadCompactSequences")
350 var flatcseqs []CompactSequence
351 for _, cseqs := range allcseqs {
352 flatcseqs = append(flatcseqs, cseqs...)
354 err = tilelib.loadCompactSequences(flatcseqs, allvariantmap)
359 log.Info("LoadDir done")
363 func (tilelib *tileLibrary) WriteDir(dir string) error {
365 nfiles := ntilefiles + len(tilelib.refseqs)
366 files := make([]*os.File, nfiles)
367 for i := range files {
368 f, err := os.OpenFile(fmt.Sprintf("%s/library.%04d.gob.gz", dir, i), os.O_CREATE|os.O_WRONLY, 0666)
375 bufws := make([]*bufio.Writer, nfiles)
376 for i := range bufws {
377 bufws[i] = bufio.NewWriterSize(files[i], 1<<26)
379 zws := make([]*pgzip.Writer, nfiles)
381 zws[i] = pgzip.NewWriter(bufws[i])
384 encoders := make([]*gob.Encoder, nfiles)
385 for i := range encoders {
386 encoders[i] = gob.NewEncoder(zws[i])
389 cgnames := make([]string, 0, len(tilelib.compactGenomes))
390 for name := range tilelib.compactGenomes {
391 cgnames = append(cgnames, name)
393 sort.Strings(cgnames)
395 refnames := make([]string, 0, len(tilelib.refseqs))
396 for name := range tilelib.refseqs {
397 refnames = append(refnames, name)
399 sort.Strings(refnames)
401 log.Infof("WriteDir: writing %d files", nfiles)
402 ctx, cancel := context.WithCancel(context.Background())
404 errs := make(chan error, nfiles)
405 for start := range files {
408 err := encoders[start].Encode(LibraryEntry{TagSet: tilelib.taglib.Tags()})
413 if refidx := start - ntilefiles; refidx >= 0 {
414 // write each ref to its own file
415 // (they seem to load very slowly)
416 name := refnames[refidx]
417 errs <- encoders[start].Encode(LibraryEntry{CompactSequences: []CompactSequence{{
419 TileSequences: tilelib.refseqs[name],
423 for i := start; i < len(cgnames); i += ntilefiles {
424 err := encoders[start].Encode(LibraryEntry{CompactGenomes: []CompactGenome{{
426 Variants: tilelib.compactGenomes[cgnames[i]],
433 tvs := []TileVariant{}
434 for tag := start; tag < len(tilelib.variant) && ctx.Err() == nil; tag += ntilefiles {
436 for idx, hash := range tilelib.variant[tag] {
437 tvs = append(tvs, TileVariant{
439 Variant: tileVariantID(idx + 1),
441 Sequence: tilelib.hashSequence(hash),
444 err := encoders[start].Encode(LibraryEntry{TileVariants: tvs})
459 log.Info("WriteDir: flushing")
461 err := zws[i].Close()
465 err = bufws[i].Flush()
469 err = files[i].Close()
474 log.Info("WriteDir: done")
478 // Load library data from rdr. Tile variants might be renumbered in
479 // the process; in that case, genomes variants will be renumbered to
481 func (tilelib *tileLibrary) LoadGob(ctx context.Context, rdr io.Reader, gz bool) error {
482 cgs := []CompactGenome{}
483 cseqs := []CompactSequence{}
484 variantmap := map[tileLibRef]tileVariantID{}
485 err := DecodeLibrary(rdr, gz, func(ent *LibraryEntry) error {
486 if ctx.Err() != nil {
489 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
492 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
495 cgs = append(cgs, ent.CompactGenomes...)
496 cseqs = append(cseqs, ent.CompactSequences...)
502 if ctx.Err() != nil {
505 err = tilelib.loadCompactGenomes(cgs, variantmap)
509 err = tilelib.loadCompactSequences(cseqs, variantmap)
516 func (tilelib *tileLibrary) dump(out io.Writer) {
517 printTV := func(tag int, variant tileVariantID) {
519 fmt.Fprintf(out, " -")
520 } else if tag >= len(tilelib.variant) {
521 fmt.Fprintf(out, " (!tag=%d)", tag)
522 } else if int(variant) > len(tilelib.variant[tag]) {
523 fmt.Fprintf(out, " (tag=%d,!variant=%d)", tag, variant)
525 fmt.Fprintf(out, " %x", tilelib.variant[tag][variant-1][:8])
528 for refname, refseqs := range tilelib.refseqs {
529 for seqname, seq := range refseqs {
530 fmt.Fprintf(out, "ref %s %s", refname, seqname)
531 for _, libref := range seq {
532 printTV(int(libref.Tag), libref.Variant)
534 fmt.Fprintf(out, "\n")
537 for name, cg := range tilelib.compactGenomes {
538 fmt.Fprintf(out, "cg %s", name)
539 for tag, variant := range cg {
540 printTV(tag/2, variant)
542 fmt.Fprintf(out, "\n")
546 type importStats struct {
552 DroppedOutOfOrderTiles int
555 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader, matchChromosome *regexp.Regexp, isRef bool) (tileSeq, []importStats, error) {
561 todo := make(chan jobT, 1)
562 scanner := bufio.NewScanner(rdr)
563 scanner.Buffer(make([]byte, 256), 1<<29) // 512 MiB, in case fasta does not have line breaks
569 buf := scanner.Bytes()
570 if len(buf) > 0 && buf[0] == '>' {
571 todo <- jobT{seqlabel, append([]byte(nil), fasta...)}
572 seqlabel, fasta = strings.SplitN(string(buf[1:]), " ", 2)[0], fasta[:0]
573 log.Debugf("%s %s reading fasta", filelabel, seqlabel)
575 fasta = append(fasta, bytes.ToLower(buf)...)
578 todo <- jobT{seqlabel, fasta}
580 type foundtag struct {
584 found := make([]foundtag, 2000000)
585 path := make([]tileLibRef, 2000000)
588 skippedSequences := 0
589 taglen := tilelib.taglib.TagLen()
590 var stats []importStats
591 for job := range todo {
592 if len(job.fasta) == 0 {
594 } else if !matchChromosome.MatchString(job.label) {
598 log.Debugf("%s %s tiling", filelabel, job.label)
601 tilelib.taglib.FindAll(job.fasta, func(tagid tagID, pos, taglen int) {
602 found = append(found, foundtag{pos: pos, tagid: tagid})
604 totalFoundTags += len(found)
606 log.Warnf("%s %s no tags found", filelabel, job.label)
611 if !tilelib.useDups {
612 // Remove any tags that appeared more than once
613 dup := map[tagID]bool{}
614 for _, ft := range found {
615 _, dup[ft.tagid] = dup[ft.tagid]
618 for _, ft := range found {
624 skipped += len(found) - dst
629 log.Infof("%s %s keeping longest increasing subsequence", filelabel, job.label)
630 keep := longestIncreasingSubsequence(len(found), func(i int) int { return int(found[i].tagid) })
631 for i, x := range keep {
634 skipped += len(found) - len(keep)
635 found = found[:len(keep)]
638 log.Infof("%s %s getting %d librefs", filelabel, job.label, len(found))
639 throttle := &throttle{Max: runtime.NumCPU()}
640 path = path[:len(found)]
642 for i, f := range found {
646 defer throttle.Release()
647 var startpos, endpos int
653 if i == len(found)-1 {
654 endpos = len(job.fasta)
656 endpos = found[i+1].pos + taglen
658 path[i] = tilelib.getRef(f.tagid, job.fasta[startpos:endpos], isRef)
659 if countBases(job.fasta[startpos:endpos]) != endpos-startpos {
660 atomic.AddInt64(&lowquality, 1)
666 log.Infof("%s %s copying path", filelabel, job.label)
668 pathcopy := make([]tileLibRef, len(path))
670 ret[job.label] = pathcopy
672 basesIn := countBases(job.fasta)
673 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)
674 stats = append(stats, importStats{
675 InputFile: filelabel,
676 InputLabel: job.label,
677 InputLength: len(job.fasta),
678 InputCoverage: basesIn,
679 PathLength: len(path),
680 DroppedOutOfOrderTiles: skipped,
683 totalPathLen += len(path)
685 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)
686 return ret, stats, scanner.Err()
689 func (tilelib *tileLibrary) Len() int64 {
690 return atomic.LoadInt64(&tilelib.variants)
693 // Return a tileLibRef for a tile with the given tag and sequence,
694 // adding the sequence to the library if needed.
695 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte, usedByRef bool) tileLibRef {
697 if !tilelib.retainNoCalls {
698 for _, b := range seq {
699 if b != 'a' && b != 'c' && b != 'g' && b != 't' {
705 seqhash := blake2b.Sum256(seq)
706 var vlock sync.Locker
709 if len(tilelib.vlock) > int(tag) {
710 vlock = tilelib.vlock[tag]
712 tilelib.mtx.RUnlock()
716 for i, varhash := range tilelib.variant[tag] {
717 if varhash == seqhash {
719 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
725 if tilelib.variant == nil && tilelib.taglib != nil {
726 tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
727 tilelib.vlock = make([]sync.Locker, tilelib.taglib.Len())
728 for i := range tilelib.vlock {
729 tilelib.vlock[i] = new(sync.Mutex)
732 if int(tag) >= len(tilelib.variant) {
733 oldlen := len(tilelib.vlock)
734 for i := 0; i < oldlen; i++ {
735 tilelib.vlock[i].Lock()
737 // If we haven't seen the tag library yet (as
738 // in a merge), tilelib.taglib.Len() is
739 // zero. We can still behave correctly, we
740 // just need to expand the tilelib.variant and
741 // tilelib.vlock slices as needed.
742 if int(tag) >= cap(tilelib.variant) {
743 // Allocate 2x capacity.
744 newslice := make([][][blake2b.Size256]byte, int(tag)+1, (int(tag)+1)*2)
745 copy(newslice, tilelib.variant)
746 tilelib.variant = newslice[:int(tag)+1]
747 newvlock := make([]sync.Locker, int(tag)+1, (int(tag)+1)*2)
748 copy(newvlock, tilelib.vlock)
749 tilelib.vlock = newvlock[:int(tag)+1]
751 // Use previously allocated capacity,
753 tilelib.variant = tilelib.variant[:int(tag)+1]
754 tilelib.vlock = tilelib.vlock[:int(tag)+1]
756 for i := oldlen; i < len(tilelib.vlock); i++ {
757 tilelib.vlock[i] = new(sync.Mutex)
759 for i := 0; i < oldlen; i++ {
760 tilelib.vlock[i].Unlock()
763 vlock = tilelib.vlock[tag]
768 for i, varhash := range tilelib.variant[tag] {
769 if varhash == seqhash {
771 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
774 atomic.AddInt64(&tilelib.variants, 1)
775 tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
776 variant := tileVariantID(len(tilelib.variant[tag]))
779 if tilelib.retainTileSequences && !dropSeq {
780 seqCopy := append([]byte(nil), seq...)
781 if tilelib.seq2 == nil {
783 if tilelib.seq2 == nil {
784 tilelib.seq2lock = map[[2]byte]sync.Locker{}
785 m := map[[2]byte]map[[blake2b.Size256]byte][]byte{}
787 for i := 0; i < 256; i++ {
789 for j := 0; j < 256; j++ {
791 m[k] = map[[blake2b.Size256]byte][]byte{}
792 tilelib.seq2lock[k] = &sync.Mutex{}
800 copy(k[:], seqhash[:])
801 locker := tilelib.seq2lock[k]
803 tilelib.seq2[k][seqhash] = seqCopy
809 // Save the hash, but not the sequence
812 if tilelib.encoder != nil {
813 tilelib.encoder.Encode(LibraryEntry{
814 TileVariants: []TileVariant{{
823 if tilelib.onAddTileVariant != nil {
824 tilelib.onAddTileVariant(tileLibRef{tag, variant}, seqhash, saveSeq)
826 return tileLibRef{Tag: tag, Variant: variant}
829 func (tilelib *tileLibrary) hashSequence(hash [blake2b.Size256]byte) []byte {
830 var partition [2]byte
831 copy(partition[:], hash[:])
832 return tilelib.seq2[partition][hash]
835 func (tilelib *tileLibrary) TileVariantSequence(libref tileLibRef) []byte {
836 if libref.Variant == 0 || len(tilelib.variant) <= int(libref.Tag) || len(tilelib.variant[libref.Tag]) < int(libref.Variant) {
839 return tilelib.hashSequence(tilelib.variant[libref.Tag][libref.Variant-1])
842 // Tidy deletes unreferenced tile variants and renumbers variants so
843 // more common variants have smaller IDs.
844 func (tilelib *tileLibrary) Tidy() {
845 log.Print("Tidy: compute inref")
846 inref := map[tileLibRef]bool{}
847 for _, refseq := range tilelib.refseqs {
848 for _, librefs := range refseq {
849 for _, libref := range librefs {
854 log.Print("Tidy: compute remap")
855 remap := make([][]tileVariantID, len(tilelib.variant))
856 throttle := throttle{Max: runtime.NumCPU() + 1}
857 for tag, oldvariants := range tilelib.variant {
858 tag, oldvariants := tagID(tag), oldvariants
859 if tag%1000000 == 0 {
860 log.Printf("Tidy: tag %d", tag)
864 defer throttle.Release()
865 uses := make([]int, len(oldvariants))
866 for _, cg := range tilelib.compactGenomes {
867 for phase := 0; phase < 2; phase++ {
868 cgi := int(tag)*2 + phase
869 if cgi < len(cg) && cg[cgi] > 0 {
875 // Compute desired order of variants:
876 // neworder[x] == index in oldvariants that
877 // should move to position x.
878 neworder := make([]int, len(oldvariants))
879 for i := range neworder {
882 sort.Slice(neworder, func(i, j int) bool {
883 if cmp := uses[neworder[i]] - uses[neworder[j]]; cmp != 0 {
886 return bytes.Compare(oldvariants[neworder[i]][:], oldvariants[neworder[j]][:]) < 0
890 // Replace tilelib.variant[tag] with a new
891 // re-ordered slice of hashes, and make a
892 // mapping from old to new variant IDs.
893 remaptag := make([]tileVariantID, len(oldvariants)+1)
894 newvariants := make([][blake2b.Size256]byte, 0, len(neworder))
895 for _, oldi := range neworder {
896 if uses[oldi] > 0 || inref[tileLibRef{Tag: tag, Variant: tileVariantID(oldi + 1)}] {
897 newvariants = append(newvariants, oldvariants[oldi])
898 remaptag[oldi+1] = tileVariantID(len(newvariants))
901 tilelib.variant[tag] = newvariants
902 remap[tag] = remaptag
907 // Apply remap to genomes and reference sequences, so they
908 // refer to the same tile variants using the changed IDs.
909 log.Print("Tidy: apply remap")
910 var wg sync.WaitGroup
911 for _, cg := range tilelib.compactGenomes {
916 for idx, variant := range cg {
917 cg[idx] = remap[tagID(idx/2)][variant]
921 for _, refcs := range tilelib.refseqs {
922 for _, refseq := range refcs {
927 for i, tv := range refseq {
928 refseq[i].Variant = remap[tv.Tag][tv.Variant]
934 log.Print("Tidy: done")
937 func countBases(seq []byte) int {
939 for _, c := range seq {