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
79 func (tilelib *tileLibrary) loadTagSet(newtagset [][]byte) error {
80 // Loading a tagset means either passing it through to the
81 // output (if it's the first one we've seen), or just ensuring
82 // it doesn't disagree with what we already have.
83 if len(newtagset) == 0 {
87 defer tilelib.mtx.Unlock()
88 if tilelib.taglib == nil || tilelib.taglib.Len() == 0 {
89 tilelib.taglib = &tagLibrary{}
90 err := tilelib.taglib.setTags(newtagset)
94 if tilelib.encoder != nil {
95 err = tilelib.encoder.Encode(LibraryEntry{
102 } else if tilelib.taglib.Len() != len(newtagset) {
103 return fmt.Errorf("cannot merge libraries with differing tagsets")
105 current := tilelib.taglib.Tags()
106 for i := range newtagset {
107 if !bytes.Equal(newtagset[i], current[i]) {
108 return fmt.Errorf("cannot merge libraries with differing tagsets")
115 func (tilelib *tileLibrary) loadTileVariants(tvs []TileVariant, variantmap map[tileLibRef]tileVariantID) error {
116 for _, tv := range tvs {
117 // Assign a new variant ID (unique across all inputs)
118 // for each input variant.
119 variantmap[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence).Variant
124 func (tilelib *tileLibrary) loadCompactGenomes(cgs []CompactGenome, variantmap map[tileLibRef]tileVariantID, onLoadGenome func(CompactGenome)) error {
125 log.Debugf("loadCompactGenomes: %d", len(cgs))
126 var wg sync.WaitGroup
127 errs := make(chan error, 1)
128 for _, cg := range cgs {
133 for i, variant := range cg.Variants {
141 newvariant, ok := variantmap[tileLibRef{Tag: tag, Variant: variant}]
143 err := fmt.Errorf("oops: genome %q has variant %d for tag %d, but that variant was not in its library", cg.Name, variant, tag)
150 // log.Tracef("loadCompactGenomes: cg %s tag %d variant %d => %d", cg.Name, tag, variant, newvariant)
151 cg.Variants[i] = newvariant
153 if onLoadGenome != nil {
156 if tilelib.encoder != nil {
157 err := tilelib.encoder.Encode(LibraryEntry{
158 CompactGenomes: []CompactGenome{cg},
168 if tilelib.compactGenomes != nil {
170 defer tilelib.mtx.Unlock()
171 tilelib.compactGenomes[cg.Name] = cg.Variants
180 func (tilelib *tileLibrary) loadCompactSequences(cseqs []CompactSequence, variantmap map[tileLibRef]tileVariantID) error {
181 log.Infof("loadCompactSequences: %d todo", len(cseqs))
182 for _, cseq := range cseqs {
183 log.Infof("loadCompactSequences: checking %s", cseq.Name)
184 for _, tseq := range cseq.TileSequences {
185 for i, libref := range tseq {
186 if libref.Variant == 0 {
187 // No variant (e.g., import
188 // dropped tiles with
189 // no-calls) = no translation.
192 v, ok := variantmap[libref]
194 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)
199 if tilelib.encoder != nil {
200 if err := tilelib.encoder.Encode(LibraryEntry{
201 CompactSequences: []CompactSequence{cseq},
206 log.Infof("loadCompactSequences: checking %s done", cseq.Name)
209 defer tilelib.mtx.Unlock()
210 if tilelib.refseqs == nil {
211 tilelib.refseqs = map[string]map[string][]tileLibRef{}
213 for _, cseq := range cseqs {
214 tilelib.refseqs[cseq.Name] = cseq.TileSequences
216 log.Info("loadCompactSequences: done")
220 func (tilelib *tileLibrary) LoadDir(ctx context.Context, path string, onLoadGenome func(CompactGenome)) error {
222 var walk func(string) error
223 walk = func(path string) error {
229 fis, err := f.Readdir(-1)
231 files = append(files, path)
234 for _, fi := range fis {
235 if fi.Name() == "." || fi.Name() == ".." {
237 } else if child := path + "/" + fi.Name(); fi.IsDir() {
242 } else if strings.HasSuffix(child, ".gob") || strings.HasSuffix(child, ".gob.gz") {
243 files = append(files, child)
248 log.Infof("LoadDir: walk dir %s", path)
253 ctx, cancel := context.WithCancel(ctx)
256 allcgs := make([][]CompactGenome, len(files))
257 allcseqs := make([][]CompactSequence, len(files))
258 allvariantmap := map[tileLibRef]tileVariantID{}
259 errs := make(chan error, len(files))
260 log.Infof("LoadDir: read %d files", len(files))
261 for fileno, path := range files {
262 fileno, path := fileno, path
270 defer log.Infof("LoadDir: finished reading %s", path)
272 var variantmap = map[tileLibRef]tileVariantID{}
273 var cgs []CompactGenome
274 var cseqs []CompactSequence
275 err = DecodeLibrary(f, strings.HasSuffix(path, ".gz"), func(ent *LibraryEntry) error {
276 if ctx.Err() != nil {
279 if len(ent.TagSet) > 0 {
281 if tilelib.taglib == nil || tilelib.taglib.Len() != len(ent.TagSet) {
282 // load first set of tags, or
283 // report mismatch if 2 sets
284 // have different #tags.
285 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
292 for _, tv := range ent.TileVariants {
293 variantmap[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence).Variant
295 cgs = append(cgs, ent.CompactGenomes...)
296 cseqs = append(cseqs, ent.CompactSequences...)
300 allcseqs[fileno] = cseqs
303 for k, v := range variantmap {
316 log.Info("LoadDir: loadCompactGenomes")
317 var flatcgs []CompactGenome
318 for _, cgs := range allcgs {
319 flatcgs = append(flatcgs, cgs...)
321 err = tilelib.loadCompactGenomes(flatcgs, allvariantmap, onLoadGenome)
326 log.Info("LoadDir: loadCompactSequences")
327 var flatcseqs []CompactSequence
328 for _, cseqs := range allcseqs {
329 flatcseqs = append(flatcseqs, cseqs...)
331 err = tilelib.loadCompactSequences(flatcseqs, allvariantmap)
336 log.Info("LoadDir done")
340 func (tilelib *tileLibrary) WriteDir(dir string) error {
342 nfiles := ntilefiles + len(tilelib.refseqs)
343 files := make([]*os.File, nfiles)
344 for i := range files {
345 f, err := os.OpenFile(fmt.Sprintf("%s/library.%04d.gob.gz", dir, i), os.O_CREATE|os.O_WRONLY, 0666)
352 bufws := make([]*bufio.Writer, nfiles)
353 for i := range bufws {
354 bufws[i] = bufio.NewWriterSize(files[i], 1<<26)
356 zws := make([]*pgzip.Writer, nfiles)
358 zws[i] = pgzip.NewWriter(bufws[i])
361 encoders := make([]*gob.Encoder, nfiles)
362 for i := range encoders {
363 encoders[i] = gob.NewEncoder(zws[i])
366 cgnames := make([]string, 0, len(tilelib.compactGenomes))
367 for name := range tilelib.compactGenomes {
368 cgnames = append(cgnames, name)
370 sort.Strings(cgnames)
372 refnames := make([]string, 0, len(tilelib.refseqs))
373 for name := range tilelib.refseqs {
374 refnames = append(refnames, name)
376 sort.Strings(refnames)
378 log.Infof("WriteDir: writing %d files", nfiles)
379 ctx, cancel := context.WithCancel(context.Background())
381 errs := make(chan error, nfiles)
382 for start := range files {
385 err := encoders[start].Encode(LibraryEntry{TagSet: tilelib.taglib.Tags()})
390 if refidx := start - ntilefiles; refidx >= 0 {
391 // write each ref to its own file
392 // (they seem to load very slowly)
393 name := refnames[refidx]
394 errs <- encoders[start].Encode(LibraryEntry{CompactSequences: []CompactSequence{{
396 TileSequences: tilelib.refseqs[name],
400 for i := start; i < len(cgnames); i += ntilefiles {
401 err := encoders[start].Encode(LibraryEntry{CompactGenomes: []CompactGenome{{
403 Variants: tilelib.compactGenomes[cgnames[i]],
410 tvs := []TileVariant{}
411 for tag := start; tag < len(tilelib.variant) && ctx.Err() == nil; tag += ntilefiles {
413 for idx, hash := range tilelib.variant[tag] {
414 tvs = append(tvs, TileVariant{
416 Variant: tileVariantID(idx + 1),
418 Sequence: tilelib.hashSequence(hash),
421 err := encoders[start].Encode(LibraryEntry{TileVariants: tvs})
436 log.Info("WriteDir: flushing")
438 err := zws[i].Close()
442 err = bufws[i].Flush()
446 err = files[i].Close()
451 log.Info("WriteDir: done")
455 // Load library data from rdr. Tile variants might be renumbered in
456 // the process; in that case, genomes variants will be renumbered to
459 // If onLoadGenome is non-nil, call it on each CompactGenome entry.
460 func (tilelib *tileLibrary) LoadGob(ctx context.Context, rdr io.Reader, gz bool, onLoadGenome func(CompactGenome)) error {
461 cgs := []CompactGenome{}
462 cseqs := []CompactSequence{}
463 variantmap := map[tileLibRef]tileVariantID{}
464 err := DecodeLibrary(rdr, gz, func(ent *LibraryEntry) error {
465 if ctx.Err() != nil {
468 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
471 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
474 cgs = append(cgs, ent.CompactGenomes...)
475 cseqs = append(cseqs, ent.CompactSequences...)
481 if ctx.Err() != nil {
484 err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
488 err = tilelib.loadCompactSequences(cseqs, variantmap)
495 func (tilelib *tileLibrary) dump(out io.Writer) {
496 printTV := func(tag int, variant tileVariantID) {
498 fmt.Fprintf(out, " -")
499 } else if tag >= len(tilelib.variant) {
500 fmt.Fprintf(out, " (!tag=%d)", tag)
501 } else if int(variant) > len(tilelib.variant[tag]) {
502 fmt.Fprintf(out, " (tag=%d,!variant=%d)", tag, variant)
504 fmt.Fprintf(out, " %x", tilelib.variant[tag][variant-1][:8])
507 for refname, refseqs := range tilelib.refseqs {
508 for seqname, seq := range refseqs {
509 fmt.Fprintf(out, "ref %s %s", refname, seqname)
510 for _, libref := range seq {
511 printTV(int(libref.Tag), libref.Variant)
513 fmt.Fprintf(out, "\n")
516 for name, cg := range tilelib.compactGenomes {
517 fmt.Fprintf(out, "cg %s", name)
518 for tag, variant := range cg {
519 printTV(tag/2, variant)
521 fmt.Fprintf(out, "\n")
525 type importStats struct {
531 DroppedOutOfOrderTiles int
534 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader, matchChromosome *regexp.Regexp) (tileSeq, []importStats, error) {
540 todo := make(chan jobT, 1)
541 scanner := bufio.NewScanner(rdr)
547 buf := scanner.Bytes()
548 if len(buf) > 0 && buf[0] == '>' {
549 todo <- jobT{seqlabel, append([]byte(nil), fasta...)}
550 seqlabel, fasta = strings.SplitN(string(buf[1:]), " ", 2)[0], fasta[:0]
551 log.Debugf("%s %s reading fasta", filelabel, seqlabel)
553 fasta = append(fasta, bytes.ToLower(buf)...)
556 todo <- jobT{seqlabel, fasta}
558 type foundtag struct {
562 found := make([]foundtag, 2000000)
563 path := make([]tileLibRef, 2000000)
566 skippedSequences := 0
567 taglen := tilelib.taglib.TagLen()
568 var stats []importStats
569 for job := range todo {
570 if len(job.fasta) == 0 {
572 } else if !matchChromosome.MatchString(job.label) {
576 log.Debugf("%s %s tiling", filelabel, job.label)
579 tilelib.taglib.FindAll(job.fasta, func(tagid tagID, pos, taglen int) {
580 found = append(found, foundtag{pos: pos, tagid: tagid})
582 totalFoundTags += len(found)
584 log.Warnf("%s %s no tags found", filelabel, job.label)
589 log.Infof("%s %s keeping longest increasing subsequence", filelabel, job.label)
590 keep := longestIncreasingSubsequence(len(found), func(i int) int { return int(found[i].tagid) })
591 for i, x := range keep {
594 skipped = len(found) - len(keep)
595 found = found[:len(keep)]
598 log.Infof("%s %s getting %d librefs", filelabel, job.label, len(found))
599 throttle := &throttle{Max: runtime.NumCPU()}
600 path = path[:len(found)]
602 for i, f := range found {
606 defer throttle.Release()
607 var startpos, endpos int
613 if i == len(found)-1 {
614 endpos = len(job.fasta)
616 endpos = found[i+1].pos + taglen
618 path[i] = tilelib.getRef(f.tagid, job.fasta[startpos:endpos])
619 if countBases(job.fasta[startpos:endpos]) != endpos-startpos {
620 atomic.AddInt64(&lowquality, 1)
626 log.Infof("%s %s copying path", filelabel, job.label)
628 pathcopy := make([]tileLibRef, len(path))
630 ret[job.label] = pathcopy
632 basesIn := countBases(job.fasta)
633 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)
634 stats = append(stats, importStats{
635 InputFile: filelabel,
636 InputLabel: job.label,
637 InputLength: len(job.fasta),
638 InputCoverage: basesIn,
639 PathLength: len(path),
640 DroppedOutOfOrderTiles: skipped,
643 totalPathLen += len(path)
645 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)
646 return ret, stats, scanner.Err()
649 func (tilelib *tileLibrary) Len() int64 {
650 return atomic.LoadInt64(&tilelib.variants)
653 // Return a tileLibRef for a tile with the given tag and sequence,
654 // adding the sequence to the library if needed.
655 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte) tileLibRef {
657 if !tilelib.retainNoCalls {
658 for _, b := range seq {
659 if b != 'a' && b != 'c' && b != 'g' && b != 't' {
665 seqhash := blake2b.Sum256(seq)
666 var vlock sync.Locker
669 if len(tilelib.vlock) > int(tag) {
670 vlock = tilelib.vlock[tag]
672 tilelib.mtx.RUnlock()
676 for i, varhash := range tilelib.variant[tag] {
677 if varhash == seqhash {
679 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
685 if tilelib.variant == nil && tilelib.taglib != nil {
686 tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
687 tilelib.vlock = make([]sync.Locker, tilelib.taglib.Len())
688 for i := range tilelib.vlock {
689 tilelib.vlock[i] = new(sync.Mutex)
692 if int(tag) >= len(tilelib.variant) {
693 oldlen := len(tilelib.vlock)
694 for i := 0; i < oldlen; i++ {
695 tilelib.vlock[i].Lock()
697 // If we haven't seen the tag library yet (as
698 // in a merge), tilelib.taglib.Len() is
699 // zero. We can still behave correctly, we
700 // just need to expand the tilelib.variant and
701 // tilelib.vlock slices as needed.
702 if int(tag) >= cap(tilelib.variant) {
703 // Allocate 2x capacity.
704 newslice := make([][][blake2b.Size256]byte, int(tag)+1, (int(tag)+1)*2)
705 copy(newslice, tilelib.variant)
706 tilelib.variant = newslice[:int(tag)+1]
707 newvlock := make([]sync.Locker, int(tag)+1, (int(tag)+1)*2)
708 copy(newvlock, tilelib.vlock)
709 tilelib.vlock = newvlock[:int(tag)+1]
711 // Use previously allocated capacity,
713 tilelib.variant = tilelib.variant[:int(tag)+1]
714 tilelib.vlock = tilelib.vlock[:int(tag)+1]
716 for i := oldlen; i < len(tilelib.vlock); i++ {
717 tilelib.vlock[i] = new(sync.Mutex)
719 for i := 0; i < oldlen; i++ {
720 tilelib.vlock[i].Unlock()
723 vlock = tilelib.vlock[tag]
728 for i, varhash := range tilelib.variant[tag] {
729 if varhash == seqhash {
731 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
734 atomic.AddInt64(&tilelib.variants, 1)
735 tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
736 variant := tileVariantID(len(tilelib.variant[tag]))
739 if tilelib.retainTileSequences && !dropSeq {
740 seqCopy := append([]byte(nil), seq...)
741 if tilelib.seq2 == nil {
743 if tilelib.seq2 == nil {
744 tilelib.seq2lock = map[[2]byte]sync.Locker{}
745 m := map[[2]byte]map[[blake2b.Size256]byte][]byte{}
747 for i := 0; i < 256; i++ {
749 for j := 0; j < 256; j++ {
751 m[k] = map[[blake2b.Size256]byte][]byte{}
752 tilelib.seq2lock[k] = &sync.Mutex{}
760 copy(k[:], seqhash[:])
761 locker := tilelib.seq2lock[k]
763 tilelib.seq2[k][seqhash] = seqCopy
767 if tilelib.encoder != nil {
770 // Save the hash, but not the sequence
773 tilelib.encoder.Encode(LibraryEntry{
774 TileVariants: []TileVariant{{
782 return tileLibRef{Tag: tag, Variant: variant}
785 func (tilelib *tileLibrary) hashSequence(hash [blake2b.Size256]byte) []byte {
786 var partition [2]byte
787 copy(partition[:], hash[:])
788 return tilelib.seq2[partition][hash]
791 func (tilelib *tileLibrary) TileVariantSequence(libref tileLibRef) []byte {
792 if libref.Variant == 0 || len(tilelib.variant) <= int(libref.Tag) || len(tilelib.variant[libref.Tag]) < int(libref.Variant) {
795 return tilelib.hashSequence(tilelib.variant[libref.Tag][libref.Variant-1])
798 // Tidy deletes unreferenced tile variants and renumbers variants so
799 // more common variants have smaller IDs.
800 func (tilelib *tileLibrary) Tidy() {
801 log.Print("Tidy: compute inref")
802 inref := map[tileLibRef]bool{}
803 for _, refseq := range tilelib.refseqs {
804 for _, librefs := range refseq {
805 for _, libref := range librefs {
810 log.Print("Tidy: compute remap")
811 remap := make([][]tileVariantID, len(tilelib.variant))
812 throttle := throttle{Max: runtime.NumCPU() + 1}
813 for tag, oldvariants := range tilelib.variant {
814 tag, oldvariants := tagID(tag), oldvariants
815 if tag%1000000 == 0 {
816 log.Printf("Tidy: tag %d", tag)
820 defer throttle.Release()
821 uses := make([]int, len(oldvariants))
822 for _, cg := range tilelib.compactGenomes {
823 for phase := 0; phase < 2; phase++ {
824 cgi := int(tag)*2 + phase
825 if cgi < len(cg) && cg[cgi] > 0 {
831 // Compute desired order of variants:
832 // neworder[x] == index in oldvariants that
833 // should move to position x.
834 neworder := make([]int, len(oldvariants))
835 for i := range neworder {
838 sort.Slice(neworder, func(i, j int) bool {
839 if cmp := uses[neworder[i]] - uses[neworder[j]]; cmp != 0 {
842 return bytes.Compare(oldvariants[neworder[i]][:], oldvariants[neworder[j]][:]) < 0
846 // Replace tilelib.variant[tag] with a new
847 // re-ordered slice of hashes, and make a
848 // mapping from old to new variant IDs.
849 remaptag := make([]tileVariantID, len(oldvariants)+1)
850 newvariants := make([][blake2b.Size256]byte, 0, len(neworder))
851 for _, oldi := range neworder {
852 if uses[oldi] > 0 || inref[tileLibRef{Tag: tag, Variant: tileVariantID(oldi + 1)}] {
853 newvariants = append(newvariants, oldvariants[oldi])
854 remaptag[oldi+1] = tileVariantID(len(newvariants))
857 tilelib.variant[tag] = newvariants
858 remap[tag] = remaptag
863 // Apply remap to genomes and reference sequences, so they
864 // refer to the same tile variants using the changed IDs.
865 log.Print("Tidy: apply remap")
866 var wg sync.WaitGroup
867 for _, cg := range tilelib.compactGenomes {
872 for idx, variant := range cg {
873 cg[idx] = remap[tagID(idx/2)][variant]
877 for _, refcs := range tilelib.refseqs {
878 for _, refseq := range refcs {
883 for i, tv := range refseq {
884 refseq[i].Variant = remap[tv.Tag][tv.Variant]
890 log.Print("Tidy: done")
893 func countBases(seq []byte) int {
895 for _, c := range seq {