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
66 variant [][][blake2b.Size256]byte
67 refseqs map[string]map[string][]tileLibRef
68 compactGenomes map[string][]tileVariantID
69 seq2 map[[2]byte]map[[blake2b.Size256]byte][]byte
70 seq2lock map[[2]byte]sync.Locker
72 // if non-nil, write out any tile variants added while tiling
74 // set Ref flag when writing new variants to encoder
77 onAddTileVariant func(libref tileLibRef, hash [blake2b.Size256]byte, seq []byte) error
78 onAddGenome func(CompactGenome) error
79 onAddRefseq func(CompactSequence) error
85 func (tilelib *tileLibrary) loadTagSet(newtagset [][]byte) error {
86 // Loading a tagset means either passing it through to the
87 // output (if it's the first one we've seen), or just ensuring
88 // it doesn't disagree with what we already have.
89 if len(newtagset) == 0 {
93 defer tilelib.mtx.Unlock()
94 if tilelib.taglib == nil || tilelib.taglib.Len() == 0 {
95 tilelib.taglib = &tagLibrary{}
96 err := tilelib.taglib.setTags(newtagset)
100 if tilelib.encoder != nil {
101 err = tilelib.encoder.Encode(LibraryEntry{
108 } else if tilelib.taglib.Len() != len(newtagset) {
109 return fmt.Errorf("cannot merge libraries with differing tagsets")
111 current := tilelib.taglib.Tags()
112 for i := range newtagset {
113 if !bytes.Equal(newtagset[i], current[i]) {
114 return fmt.Errorf("cannot merge libraries with differing tagsets")
121 func (tilelib *tileLibrary) loadTileVariants(tvs []TileVariant, variantmap map[tileLibRef]tileVariantID) error {
122 for _, tv := range tvs {
123 // Assign a new variant ID (unique across all inputs)
124 // for each input variant.
125 variantmap[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence, tv.Ref).Variant
130 func (tilelib *tileLibrary) loadCompactGenomes(cgs []CompactGenome, variantmap map[tileLibRef]tileVariantID) error {
131 log.Debugf("loadCompactGenomes: %d", len(cgs))
132 var wg sync.WaitGroup
133 errs := make(chan error, 1)
134 for _, cg := range cgs {
139 for i, variant := range cg.Variants {
147 newvariant, ok := variantmap[tileLibRef{Tag: tag, Variant: variant}]
149 err := fmt.Errorf("oops: genome %q has variant %d for tag %d, but that variant was not in its library", cg.Name, variant, tag)
156 // log.Tracef("loadCompactGenomes: cg %s tag %d variant %d => %d", cg.Name, tag, variant, newvariant)
157 cg.Variants[i] = newvariant
159 if tilelib.onAddGenome != nil {
160 err := tilelib.onAddGenome(cg)
169 if tilelib.encoder != nil {
170 err := tilelib.encoder.Encode(LibraryEntry{
171 CompactGenomes: []CompactGenome{cg},
181 if tilelib.compactGenomes != nil {
183 defer tilelib.mtx.Unlock()
184 tilelib.compactGenomes[cg.Name] = cg.Variants
193 func (tilelib *tileLibrary) loadCompactSequences(cseqs []CompactSequence, variantmap map[tileLibRef]tileVariantID) error {
194 log.Infof("loadCompactSequences: %d todo", len(cseqs))
195 for _, cseq := range cseqs {
196 log.Infof("loadCompactSequences: checking %s", cseq.Name)
197 for _, tseq := range cseq.TileSequences {
198 for i, libref := range tseq {
199 if libref.Variant == 0 {
200 // No variant (e.g., import
201 // dropped tiles with
202 // no-calls) = no translation.
205 v, ok := variantmap[libref]
207 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)
212 if tilelib.encoder != nil {
213 if err := tilelib.encoder.Encode(LibraryEntry{
214 CompactSequences: []CompactSequence{cseq},
219 if tilelib.onAddRefseq != nil {
220 err := tilelib.onAddRefseq(cseq)
225 log.Infof("loadCompactSequences: checking %s done", cseq.Name)
228 defer tilelib.mtx.Unlock()
229 if tilelib.refseqs == nil {
230 tilelib.refseqs = map[string]map[string][]tileLibRef{}
232 for _, cseq := range cseqs {
233 tilelib.refseqs[cseq.Name] = cseq.TileSequences
235 log.Info("loadCompactSequences: done")
239 func allGobFiles(path string) ([]string, error) {
246 fis, err := f.Readdir(-1)
248 return []string{path}, nil
250 for _, fi := range fis {
251 if fi.Name() == "." || fi.Name() == ".." {
253 } else if child := path + "/" + fi.Name(); fi.IsDir() {
254 add, err := allGobFiles(child)
258 files = append(files, add...)
259 } else if strings.HasSuffix(child, ".gob") || strings.HasSuffix(child, ".gob.gz") {
260 files = append(files, child)
266 func (tilelib *tileLibrary) LoadDir(ctx context.Context, path string) error {
267 log.Infof("LoadDir: walk dir %s", path)
268 files, err := allGobFiles(path)
272 ctx, cancel := context.WithCancel(ctx)
275 allcgs := make([][]CompactGenome, len(files))
276 allcseqs := make([][]CompactSequence, len(files))
277 allvariantmap := map[tileLibRef]tileVariantID{}
278 errs := make(chan error, len(files))
279 log.Infof("LoadDir: read %d files", len(files))
280 for fileno, path := range files {
281 fileno, path := fileno, path
289 defer log.Infof("LoadDir: finished reading %s", path)
291 var variantmap = map[tileLibRef]tileVariantID{}
292 var cgs []CompactGenome
293 var cseqs []CompactSequence
294 err = DecodeLibrary(f, strings.HasSuffix(path, ".gz"), func(ent *LibraryEntry) error {
295 if ctx.Err() != nil {
298 if len(ent.TagSet) > 0 {
300 if tilelib.taglib == nil || tilelib.taglib.Len() != len(ent.TagSet) {
301 // load first set of tags, or
302 // report mismatch if 2 sets
303 // have different #tags.
304 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
311 for _, tv := range ent.TileVariants {
312 variantmap[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence, tv.Ref).Variant
314 cgs = append(cgs, ent.CompactGenomes...)
315 cseqs = append(cseqs, ent.CompactSequences...)
319 allcseqs[fileno] = cseqs
322 for k, v := range variantmap {
335 log.Info("LoadDir: loadCompactGenomes")
336 var flatcgs []CompactGenome
337 for _, cgs := range allcgs {
338 flatcgs = append(flatcgs, cgs...)
340 err = tilelib.loadCompactGenomes(flatcgs, allvariantmap)
345 log.Info("LoadDir: loadCompactSequences")
346 var flatcseqs []CompactSequence
347 for _, cseqs := range allcseqs {
348 flatcseqs = append(flatcseqs, cseqs...)
350 err = tilelib.loadCompactSequences(flatcseqs, allvariantmap)
355 log.Info("LoadDir done")
359 func (tilelib *tileLibrary) WriteDir(dir string) error {
361 nfiles := ntilefiles + len(tilelib.refseqs)
362 files := make([]*os.File, nfiles)
363 for i := range files {
364 f, err := os.OpenFile(fmt.Sprintf("%s/library.%04d.gob.gz", dir, i), os.O_CREATE|os.O_WRONLY, 0666)
371 bufws := make([]*bufio.Writer, nfiles)
372 for i := range bufws {
373 bufws[i] = bufio.NewWriterSize(files[i], 1<<26)
375 zws := make([]*pgzip.Writer, nfiles)
377 zws[i] = pgzip.NewWriter(bufws[i])
380 encoders := make([]*gob.Encoder, nfiles)
381 for i := range encoders {
382 encoders[i] = gob.NewEncoder(zws[i])
385 cgnames := make([]string, 0, len(tilelib.compactGenomes))
386 for name := range tilelib.compactGenomes {
387 cgnames = append(cgnames, name)
389 sort.Strings(cgnames)
391 refnames := make([]string, 0, len(tilelib.refseqs))
392 for name := range tilelib.refseqs {
393 refnames = append(refnames, name)
395 sort.Strings(refnames)
397 log.Infof("WriteDir: writing %d files", nfiles)
398 ctx, cancel := context.WithCancel(context.Background())
400 errs := make(chan error, nfiles)
401 for start := range files {
404 err := encoders[start].Encode(LibraryEntry{TagSet: tilelib.taglib.Tags()})
409 if refidx := start - ntilefiles; refidx >= 0 {
410 // write each ref to its own file
411 // (they seem to load very slowly)
412 name := refnames[refidx]
413 errs <- encoders[start].Encode(LibraryEntry{CompactSequences: []CompactSequence{{
415 TileSequences: tilelib.refseqs[name],
419 for i := start; i < len(cgnames); i += ntilefiles {
420 err := encoders[start].Encode(LibraryEntry{CompactGenomes: []CompactGenome{{
422 Variants: tilelib.compactGenomes[cgnames[i]],
429 tvs := []TileVariant{}
430 for tag := start; tag < len(tilelib.variant) && ctx.Err() == nil; tag += ntilefiles {
432 for idx, hash := range tilelib.variant[tag] {
433 tvs = append(tvs, TileVariant{
435 Variant: tileVariantID(idx + 1),
437 Sequence: tilelib.hashSequence(hash),
440 err := encoders[start].Encode(LibraryEntry{TileVariants: tvs})
455 log.Info("WriteDir: flushing")
457 err := zws[i].Close()
461 err = bufws[i].Flush()
465 err = files[i].Close()
470 log.Info("WriteDir: done")
474 // Load library data from rdr. Tile variants might be renumbered in
475 // the process; in that case, genomes variants will be renumbered to
477 func (tilelib *tileLibrary) LoadGob(ctx context.Context, rdr io.Reader, gz bool) error {
478 cgs := []CompactGenome{}
479 cseqs := []CompactSequence{}
480 variantmap := map[tileLibRef]tileVariantID{}
481 err := DecodeLibrary(rdr, gz, func(ent *LibraryEntry) error {
482 if ctx.Err() != nil {
485 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
488 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
491 cgs = append(cgs, ent.CompactGenomes...)
492 cseqs = append(cseqs, ent.CompactSequences...)
498 if ctx.Err() != nil {
501 err = tilelib.loadCompactGenomes(cgs, variantmap)
505 err = tilelib.loadCompactSequences(cseqs, variantmap)
512 func (tilelib *tileLibrary) dump(out io.Writer) {
513 printTV := func(tag int, variant tileVariantID) {
515 fmt.Fprintf(out, " -")
516 } else if tag >= len(tilelib.variant) {
517 fmt.Fprintf(out, " (!tag=%d)", tag)
518 } else if int(variant) > len(tilelib.variant[tag]) {
519 fmt.Fprintf(out, " (tag=%d,!variant=%d)", tag, variant)
521 fmt.Fprintf(out, " %x", tilelib.variant[tag][variant-1][:8])
524 for refname, refseqs := range tilelib.refseqs {
525 for seqname, seq := range refseqs {
526 fmt.Fprintf(out, "ref %s %s", refname, seqname)
527 for _, libref := range seq {
528 printTV(int(libref.Tag), libref.Variant)
530 fmt.Fprintf(out, "\n")
533 for name, cg := range tilelib.compactGenomes {
534 fmt.Fprintf(out, "cg %s", name)
535 for tag, variant := range cg {
536 printTV(tag/2, variant)
538 fmt.Fprintf(out, "\n")
542 type importStats struct {
548 DroppedOutOfOrderTiles int
551 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader, matchChromosome *regexp.Regexp, isRef bool) (tileSeq, []importStats, error) {
557 todo := make(chan jobT, 1)
558 scanner := bufio.NewScanner(rdr)
564 buf := scanner.Bytes()
565 if len(buf) > 0 && buf[0] == '>' {
566 todo <- jobT{seqlabel, append([]byte(nil), fasta...)}
567 seqlabel, fasta = strings.SplitN(string(buf[1:]), " ", 2)[0], fasta[:0]
568 log.Debugf("%s %s reading fasta", filelabel, seqlabel)
570 fasta = append(fasta, bytes.ToLower(buf)...)
573 todo <- jobT{seqlabel, fasta}
575 type foundtag struct {
579 found := make([]foundtag, 2000000)
580 path := make([]tileLibRef, 2000000)
583 skippedSequences := 0
584 taglen := tilelib.taglib.TagLen()
585 var stats []importStats
586 for job := range todo {
587 if len(job.fasta) == 0 {
589 } else if !matchChromosome.MatchString(job.label) {
593 log.Debugf("%s %s tiling", filelabel, job.label)
596 tilelib.taglib.FindAll(job.fasta, func(tagid tagID, pos, taglen int) {
597 found = append(found, foundtag{pos: pos, tagid: tagid})
599 totalFoundTags += len(found)
601 log.Warnf("%s %s no tags found", filelabel, job.label)
606 log.Infof("%s %s keeping longest increasing subsequence", filelabel, job.label)
607 keep := longestIncreasingSubsequence(len(found), func(i int) int { return int(found[i].tagid) })
608 for i, x := range keep {
611 skipped = len(found) - len(keep)
612 found = found[:len(keep)]
615 log.Infof("%s %s getting %d librefs", filelabel, job.label, len(found))
616 throttle := &throttle{Max: runtime.NumCPU()}
617 path = path[:len(found)]
619 for i, f := range found {
623 defer throttle.Release()
624 var startpos, endpos int
630 if i == len(found)-1 {
631 endpos = len(job.fasta)
633 endpos = found[i+1].pos + taglen
635 path[i] = tilelib.getRef(f.tagid, job.fasta[startpos:endpos], isRef)
636 if countBases(job.fasta[startpos:endpos]) != endpos-startpos {
637 atomic.AddInt64(&lowquality, 1)
643 log.Infof("%s %s copying path", filelabel, job.label)
645 pathcopy := make([]tileLibRef, len(path))
647 ret[job.label] = pathcopy
649 basesIn := countBases(job.fasta)
650 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)
651 stats = append(stats, importStats{
652 InputFile: filelabel,
653 InputLabel: job.label,
654 InputLength: len(job.fasta),
655 InputCoverage: basesIn,
656 PathLength: len(path),
657 DroppedOutOfOrderTiles: skipped,
660 totalPathLen += len(path)
662 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)
663 return ret, stats, scanner.Err()
666 func (tilelib *tileLibrary) Len() int64 {
667 return atomic.LoadInt64(&tilelib.variants)
670 // Return a tileLibRef for a tile with the given tag and sequence,
671 // adding the sequence to the library if needed.
672 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte, usedByRef bool) tileLibRef {
674 if !tilelib.retainNoCalls {
675 for _, b := range seq {
676 if b != 'a' && b != 'c' && b != 'g' && b != 't' {
682 seqhash := blake2b.Sum256(seq)
683 var vlock sync.Locker
686 if len(tilelib.vlock) > int(tag) {
687 vlock = tilelib.vlock[tag]
689 tilelib.mtx.RUnlock()
693 for i, varhash := range tilelib.variant[tag] {
694 if varhash == seqhash {
696 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
702 if tilelib.variant == nil && tilelib.taglib != nil {
703 tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
704 tilelib.vlock = make([]sync.Locker, tilelib.taglib.Len())
705 for i := range tilelib.vlock {
706 tilelib.vlock[i] = new(sync.Mutex)
709 if int(tag) >= len(tilelib.variant) {
710 oldlen := len(tilelib.vlock)
711 for i := 0; i < oldlen; i++ {
712 tilelib.vlock[i].Lock()
714 // If we haven't seen the tag library yet (as
715 // in a merge), tilelib.taglib.Len() is
716 // zero. We can still behave correctly, we
717 // just need to expand the tilelib.variant and
718 // tilelib.vlock slices as needed.
719 if int(tag) >= cap(tilelib.variant) {
720 // Allocate 2x capacity.
721 newslice := make([][][blake2b.Size256]byte, int(tag)+1, (int(tag)+1)*2)
722 copy(newslice, tilelib.variant)
723 tilelib.variant = newslice[:int(tag)+1]
724 newvlock := make([]sync.Locker, int(tag)+1, (int(tag)+1)*2)
725 copy(newvlock, tilelib.vlock)
726 tilelib.vlock = newvlock[:int(tag)+1]
728 // Use previously allocated capacity,
730 tilelib.variant = tilelib.variant[:int(tag)+1]
731 tilelib.vlock = tilelib.vlock[:int(tag)+1]
733 for i := oldlen; i < len(tilelib.vlock); i++ {
734 tilelib.vlock[i] = new(sync.Mutex)
736 for i := 0; i < oldlen; i++ {
737 tilelib.vlock[i].Unlock()
740 vlock = tilelib.vlock[tag]
745 for i, varhash := range tilelib.variant[tag] {
746 if varhash == seqhash {
748 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
751 atomic.AddInt64(&tilelib.variants, 1)
752 tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
753 variant := tileVariantID(len(tilelib.variant[tag]))
756 if tilelib.retainTileSequences && !dropSeq {
757 seqCopy := append([]byte(nil), seq...)
758 if tilelib.seq2 == nil {
760 if tilelib.seq2 == nil {
761 tilelib.seq2lock = map[[2]byte]sync.Locker{}
762 m := map[[2]byte]map[[blake2b.Size256]byte][]byte{}
764 for i := 0; i < 256; i++ {
766 for j := 0; j < 256; j++ {
768 m[k] = map[[blake2b.Size256]byte][]byte{}
769 tilelib.seq2lock[k] = &sync.Mutex{}
777 copy(k[:], seqhash[:])
778 locker := tilelib.seq2lock[k]
780 tilelib.seq2[k][seqhash] = seqCopy
786 // Save the hash, but not the sequence
789 if tilelib.encoder != nil {
790 tilelib.encoder.Encode(LibraryEntry{
791 TileVariants: []TileVariant{{
800 if tilelib.onAddTileVariant != nil {
801 tilelib.onAddTileVariant(tileLibRef{tag, variant}, seqhash, saveSeq)
803 return tileLibRef{Tag: tag, Variant: variant}
806 func (tilelib *tileLibrary) hashSequence(hash [blake2b.Size256]byte) []byte {
807 var partition [2]byte
808 copy(partition[:], hash[:])
809 return tilelib.seq2[partition][hash]
812 func (tilelib *tileLibrary) TileVariantSequence(libref tileLibRef) []byte {
813 if libref.Variant == 0 || len(tilelib.variant) <= int(libref.Tag) || len(tilelib.variant[libref.Tag]) < int(libref.Variant) {
816 return tilelib.hashSequence(tilelib.variant[libref.Tag][libref.Variant-1])
819 // Tidy deletes unreferenced tile variants and renumbers variants so
820 // more common variants have smaller IDs.
821 func (tilelib *tileLibrary) Tidy() {
822 log.Print("Tidy: compute inref")
823 inref := map[tileLibRef]bool{}
824 for _, refseq := range tilelib.refseqs {
825 for _, librefs := range refseq {
826 for _, libref := range librefs {
831 log.Print("Tidy: compute remap")
832 remap := make([][]tileVariantID, len(tilelib.variant))
833 throttle := throttle{Max: runtime.NumCPU() + 1}
834 for tag, oldvariants := range tilelib.variant {
835 tag, oldvariants := tagID(tag), oldvariants
836 if tag%1000000 == 0 {
837 log.Printf("Tidy: tag %d", tag)
841 defer throttle.Release()
842 uses := make([]int, len(oldvariants))
843 for _, cg := range tilelib.compactGenomes {
844 for phase := 0; phase < 2; phase++ {
845 cgi := int(tag)*2 + phase
846 if cgi < len(cg) && cg[cgi] > 0 {
852 // Compute desired order of variants:
853 // neworder[x] == index in oldvariants that
854 // should move to position x.
855 neworder := make([]int, len(oldvariants))
856 for i := range neworder {
859 sort.Slice(neworder, func(i, j int) bool {
860 if cmp := uses[neworder[i]] - uses[neworder[j]]; cmp != 0 {
863 return bytes.Compare(oldvariants[neworder[i]][:], oldvariants[neworder[j]][:]) < 0
867 // Replace tilelib.variant[tag] with a new
868 // re-ordered slice of hashes, and make a
869 // mapping from old to new variant IDs.
870 remaptag := make([]tileVariantID, len(oldvariants)+1)
871 newvariants := make([][blake2b.Size256]byte, 0, len(neworder))
872 for _, oldi := range neworder {
873 if uses[oldi] > 0 || inref[tileLibRef{Tag: tag, Variant: tileVariantID(oldi + 1)}] {
874 newvariants = append(newvariants, oldvariants[oldi])
875 remaptag[oldi+1] = tileVariantID(len(newvariants))
878 tilelib.variant[tag] = newvariants
879 remap[tag] = remaptag
884 // Apply remap to genomes and reference sequences, so they
885 // refer to the same tile variants using the changed IDs.
886 log.Print("Tidy: apply remap")
887 var wg sync.WaitGroup
888 for _, cg := range tilelib.compactGenomes {
893 for idx, variant := range cg {
894 cg[idx] = remap[tagID(idx/2)][variant]
898 for _, refcs := range tilelib.refseqs {
899 for _, refseq := range refcs {
904 for i, tv := range refseq {
905 refseq[i].Variant = remap[tv.Tag][tv.Variant]
911 log.Print("Tidy: done")
914 func countBases(seq []byte) int {
916 for _, c := range seq {