1 // Copyright (C) The Lightning Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
23 "github.com/klauspost/pgzip"
24 log "github.com/sirupsen/logrus"
25 "golang.org/x/crypto/blake2b"
28 type tileVariantID uint16 // 1-based
30 type tileLibRef struct {
35 type tileSeq map[string][]tileLibRef
37 func (tseq tileSeq) Variants() ([]tileVariantID, int, int) {
39 for _, refs := range tseq {
40 for _, ref := range refs {
41 if maxtag < int(ref.Tag) {
46 vars := make([]tileVariantID, maxtag+1)
48 for _, refs := range tseq {
49 for _, ref := range refs {
50 if vars[int(ref.Tag)] != 0 {
55 vars[int(ref.Tag)] = ref.Variant
58 return vars, kept, dropped
61 type tileLibrary struct {
64 retainTileSequences bool
68 variant [][][blake2b.Size256]byte
69 refseqs map[string]map[string][]tileLibRef
70 compactGenomes map[string][]tileVariantID
71 seq2 map[[2]byte]map[[blake2b.Size256]byte][]byte
72 seq2lock map[[2]byte]sync.Locker
74 // if non-nil, write out any tile variants added while tiling
76 // set Ref flag when writing new variants to encoder
79 onAddTileVariant func(libref tileLibRef, hash [blake2b.Size256]byte, seq []byte) error
80 onAddGenome func(CompactGenome) error
81 onAddRefseq func(CompactSequence) error
87 func (tilelib *tileLibrary) loadTagSet(newtagset [][]byte) error {
88 // Loading a tagset means either passing it through to the
89 // output (if it's the first one we've seen), or just ensuring
90 // it doesn't disagree with what we already have.
91 if len(newtagset) == 0 {
95 defer tilelib.mtx.Unlock()
96 if tilelib.taglib == nil || tilelib.taglib.Len() == 0 {
97 tilelib.taglib = &tagLibrary{}
98 err := tilelib.taglib.setTags(newtagset)
102 if tilelib.encoder != nil {
103 err = tilelib.encoder.Encode(LibraryEntry{
110 } else if tilelib.taglib.Len() != len(newtagset) {
111 return fmt.Errorf("cannot merge libraries with differing tagsets")
113 current := tilelib.taglib.Tags()
114 for i := range newtagset {
115 if !bytes.Equal(newtagset[i], current[i]) {
116 return fmt.Errorf("cannot merge libraries with differing tagsets")
123 func (tilelib *tileLibrary) loadTileVariants(tvs []TileVariant, variantmap map[tileLibRef]tileVariantID) error {
124 for _, tv := range tvs {
125 // Assign a new variant ID (unique across all inputs)
126 // for each input variant.
127 variantmap[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence, tv.Ref).Variant
132 func (tilelib *tileLibrary) loadCompactGenomes(cgs []CompactGenome, variantmap map[tileLibRef]tileVariantID) error {
133 log.Debugf("loadCompactGenomes: %d", len(cgs))
134 var wg sync.WaitGroup
135 errs := make(chan error, 1)
136 for _, cg := range cgs {
141 for i, variant := range cg.Variants {
149 newvariant, ok := variantmap[tileLibRef{Tag: tag, Variant: variant}]
151 err := fmt.Errorf("oops: genome %q has variant %d for tag %d, but that variant was not in its library", cg.Name, variant, tag)
158 // log.Tracef("loadCompactGenomes: cg %s tag %d variant %d => %d", cg.Name, tag, variant, newvariant)
159 cg.Variants[i] = newvariant
161 if tilelib.onAddGenome != nil {
162 err := tilelib.onAddGenome(cg)
171 if tilelib.encoder != nil {
172 err := tilelib.encoder.Encode(LibraryEntry{
173 CompactGenomes: []CompactGenome{cg},
183 if tilelib.compactGenomes != nil {
185 defer tilelib.mtx.Unlock()
186 tilelib.compactGenomes[cg.Name] = cg.Variants
195 func (tilelib *tileLibrary) loadCompactSequences(cseqs []CompactSequence, variantmap map[tileLibRef]tileVariantID) error {
196 log.Infof("loadCompactSequences: %d todo", len(cseqs))
197 for _, cseq := range cseqs {
198 log.Infof("loadCompactSequences: checking %s", cseq.Name)
199 for _, tseq := range cseq.TileSequences {
200 for i, libref := range tseq {
201 if libref.Variant == 0 {
202 // No variant (e.g., import
203 // dropped tiles with
204 // no-calls) = no translation.
207 v, ok := variantmap[libref]
209 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)
214 if tilelib.encoder != nil {
215 if err := tilelib.encoder.Encode(LibraryEntry{
216 CompactSequences: []CompactSequence{cseq},
221 if tilelib.onAddRefseq != nil {
222 err := tilelib.onAddRefseq(cseq)
227 log.Infof("loadCompactSequences: checking %s done", cseq.Name)
230 defer tilelib.mtx.Unlock()
231 if tilelib.refseqs == nil {
232 tilelib.refseqs = map[string]map[string][]tileLibRef{}
234 for _, cseq := range cseqs {
235 tilelib.refseqs[cseq.Name] = cseq.TileSequences
237 log.Info("loadCompactSequences: done")
241 func allFiles(path string, re *regexp.Regexp) ([]string, error) {
248 fis, err := f.Readdir(-1)
250 return []string{path}, nil
252 for _, fi := range fis {
253 if fi.Name() == "." || fi.Name() == ".." {
255 } else if child := path + "/" + fi.Name(); fi.IsDir() {
256 add, err := allFiles(child, re)
260 files = append(files, add...)
261 } else if re == nil || re.MatchString(child) {
262 files = append(files, child)
269 var matchGobFile = regexp.MustCompile(`\.gob(\.gz)?$`)
271 func (tilelib *tileLibrary) LoadDir(ctx context.Context, path string) error {
272 log.Infof("LoadDir: walk dir %s", path)
273 files, err := allFiles(path, matchGobFile)
277 ctx, cancel := context.WithCancel(ctx)
280 allcgs := make([][]CompactGenome, len(files))
281 allcseqs := make([][]CompactSequence, len(files))
282 allvariantmap := map[tileLibRef]tileVariantID{}
283 errs := make(chan error, len(files))
284 log.Infof("LoadDir: read %d files", len(files))
285 for fileno, path := range files {
286 fileno, path := fileno, path
294 defer log.Infof("LoadDir: finished reading %s", path)
296 var variantmap = map[tileLibRef]tileVariantID{}
297 var cgs []CompactGenome
298 var cseqs []CompactSequence
299 err = DecodeLibrary(f, strings.HasSuffix(path, ".gz"), func(ent *LibraryEntry) error {
300 if ctx.Err() != nil {
303 if len(ent.TagSet) > 0 {
305 if tilelib.taglib == nil || tilelib.taglib.Len() != len(ent.TagSet) {
306 // load first set of tags, or
307 // report mismatch if 2 sets
308 // have different #tags.
309 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
316 for _, tv := range ent.TileVariants {
317 variantmap[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence, tv.Ref).Variant
319 cgs = append(cgs, ent.CompactGenomes...)
320 cseqs = append(cseqs, ent.CompactSequences...)
324 allcseqs[fileno] = cseqs
327 for k, v := range variantmap {
340 log.Info("LoadDir: loadCompactGenomes")
341 var flatcgs []CompactGenome
342 for _, cgs := range allcgs {
343 flatcgs = append(flatcgs, cgs...)
345 err = tilelib.loadCompactGenomes(flatcgs, allvariantmap)
350 log.Info("LoadDir: loadCompactSequences")
351 var flatcseqs []CompactSequence
352 for _, cseqs := range allcseqs {
353 flatcseqs = append(flatcseqs, cseqs...)
355 err = tilelib.loadCompactSequences(flatcseqs, allvariantmap)
360 log.Info("LoadDir done")
364 func (tilelib *tileLibrary) WriteDir(dir string) error {
366 nfiles := ntilefiles + len(tilelib.refseqs)
367 files := make([]*os.File, nfiles)
368 for i := range files {
369 f, err := os.OpenFile(fmt.Sprintf("%s/library.%04d.gob.gz", dir, i), os.O_CREATE|os.O_WRONLY, 0666)
376 bufws := make([]*bufio.Writer, nfiles)
377 for i := range bufws {
378 bufws[i] = bufio.NewWriterSize(files[i], 1<<26)
380 zws := make([]*pgzip.Writer, nfiles)
382 zws[i] = pgzip.NewWriter(bufws[i])
385 encoders := make([]*gob.Encoder, nfiles)
386 for i := range encoders {
387 encoders[i] = gob.NewEncoder(zws[i])
390 cgnames := make([]string, 0, len(tilelib.compactGenomes))
391 for name := range tilelib.compactGenomes {
392 cgnames = append(cgnames, name)
394 sort.Strings(cgnames)
396 refnames := make([]string, 0, len(tilelib.refseqs))
397 for name := range tilelib.refseqs {
398 refnames = append(refnames, name)
400 sort.Strings(refnames)
402 log.Infof("WriteDir: writing %d files", nfiles)
403 ctx, cancel := context.WithCancel(context.Background())
405 errs := make(chan error, nfiles)
406 for start := range files {
409 err := encoders[start].Encode(LibraryEntry{TagSet: tilelib.taglib.Tags()})
414 if refidx := start - ntilefiles; refidx >= 0 {
415 // write each ref to its own file
416 // (they seem to load very slowly)
417 name := refnames[refidx]
418 errs <- encoders[start].Encode(LibraryEntry{CompactSequences: []CompactSequence{{
420 TileSequences: tilelib.refseqs[name],
424 for i := start; i < len(cgnames); i += ntilefiles {
425 err := encoders[start].Encode(LibraryEntry{CompactGenomes: []CompactGenome{{
427 Variants: tilelib.compactGenomes[cgnames[i]],
434 tvs := []TileVariant{}
435 for tag := start; tag < len(tilelib.variant) && ctx.Err() == nil; tag += ntilefiles {
437 for idx, hash := range tilelib.variant[tag] {
438 tvs = append(tvs, TileVariant{
440 Variant: tileVariantID(idx + 1),
442 Sequence: tilelib.hashSequence(hash),
445 err := encoders[start].Encode(LibraryEntry{TileVariants: tvs})
460 log.Info("WriteDir: flushing")
462 err := zws[i].Close()
466 err = bufws[i].Flush()
470 err = files[i].Close()
475 log.Info("WriteDir: done")
479 // Load library data from rdr. Tile variants might be renumbered in
480 // the process; in that case, genomes variants will be renumbered to
482 func (tilelib *tileLibrary) LoadGob(ctx context.Context, rdr io.Reader, gz bool) error {
483 cgs := []CompactGenome{}
484 cseqs := []CompactSequence{}
485 variantmap := map[tileLibRef]tileVariantID{}
486 err := DecodeLibrary(rdr, gz, func(ent *LibraryEntry) error {
487 if ctx.Err() != nil {
490 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
493 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
496 cgs = append(cgs, ent.CompactGenomes...)
497 cseqs = append(cseqs, ent.CompactSequences...)
503 if ctx.Err() != nil {
506 err = tilelib.loadCompactGenomes(cgs, variantmap)
510 err = tilelib.loadCompactSequences(cseqs, variantmap)
517 func (tilelib *tileLibrary) dump(out io.Writer) {
518 printTV := func(tag int, variant tileVariantID) {
520 fmt.Fprintf(out, " -")
521 } else if tag >= len(tilelib.variant) {
522 fmt.Fprintf(out, " (!tag=%d)", tag)
523 } else if int(variant) > len(tilelib.variant[tag]) {
524 fmt.Fprintf(out, " (tag=%d,!variant=%d)", tag, variant)
526 fmt.Fprintf(out, " %x", tilelib.variant[tag][variant-1][:8])
529 for refname, refseqs := range tilelib.refseqs {
530 for seqname, seq := range refseqs {
531 fmt.Fprintf(out, "ref %s %s", refname, seqname)
532 for _, libref := range seq {
533 printTV(int(libref.Tag), libref.Variant)
535 fmt.Fprintf(out, "\n")
538 for name, cg := range tilelib.compactGenomes {
539 fmt.Fprintf(out, "cg %s", name)
540 for tag, variant := range cg {
541 printTV(tag/2, variant)
543 fmt.Fprintf(out, "\n")
547 type importStats struct {
553 DroppedRepeatedTags int
554 DroppedOutOfOrderTags int
557 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader, matchChromosome *regexp.Regexp, isRef bool) (tileSeq, []importStats, error) {
559 type foundtag struct {
563 found := make([]foundtag, 2000000)
564 path := make([]tileLibRef, 2000000)
567 skippedSequences := 0
568 taglen := tilelib.taglib.TagLen()
569 var stats []importStats
571 in := bufio.NewReader(rdr)
575 // Advance to next '>', then
576 // read seqlabel up to \r?\n
578 for seqlabelStarted := false; ; {
579 rune, _, err := in.ReadRune()
582 } else if err != nil {
587 case seqlabelStarted && rune == '\n':
589 case seqlabelStarted:
590 seqlabel += string(rune)
592 seqlabelStarted = true
596 log.Debugf("%s %s reading fasta", filelabel, seqlabel)
597 if !matchChromosome.MatchString(seqlabel) {
601 log.Debugf("%s %s tiling", filelabel, seqlabel)
603 fasta := bytes.NewBuffer(nil)
605 err := tilelib.taglib.FindAll(in, fasta, func(tagid tagID, pos, taglen int) {
606 found = append(found, foundtag{pos: pos, tagid: tagid})
611 totalFoundTags += len(found)
613 log.Warnf("%s %s no tags found", filelabel, seqlabel)
617 if !tilelib.useDups {
618 // Remove any tags that appeared more than once
619 dup := map[tagID]bool{}
620 for _, ft := range found {
621 _, dup[ft.tagid] = dup[ft.tagid]
624 for _, ft := range found {
630 droppedDup = len(found) - dst
631 log.Infof("%s %s dropping %d non-unique tags", filelabel, seqlabel, droppedDup)
637 keep := longestIncreasingSubsequence(len(found), func(i int) int { return int(found[i].tagid) })
638 for i, x := range keep {
641 droppedOOO = len(found) - len(keep)
642 log.Infof("%s %s dropping %d out-of-order tags", filelabel, seqlabel, droppedOOO)
643 found = found[:len(keep)]
646 log.Infof("%s %s getting %d librefs", filelabel, seqlabel, len(found))
647 path = path[:len(found)]
649 // Visit each element of found, but start at a random
650 // index, to reduce the likelihood of lock contention
651 // when importing many samples concurrently.
652 startpoint := rand.Int() % len(found)
653 for offset := range found {
654 i := startpoint + offset
659 var startpos, endpos int
665 if i == len(found)-1 {
668 endpos = found[i+1].pos + taglen
670 path[i] = tilelib.getRef(f.tagid, fasta.Bytes()[startpos:endpos], isRef)
671 if countBases(fasta.Bytes()[startpos:endpos]) != endpos-startpos {
676 log.Infof("%s %s copying path", filelabel, seqlabel)
678 pathcopy := make([]tileLibRef, len(path))
680 ret[seqlabel] = pathcopy
682 basesIn := countBases(fasta.Bytes())
683 log.Infof("%s %s fasta in %d coverage in %d path len %d low-quality %d", filelabel, seqlabel, fasta.Len(), basesIn, len(path), lowquality)
684 stats = append(stats, importStats{
685 InputFile: filelabel,
686 InputLabel: seqlabel,
687 InputLength: fasta.Len(),
688 InputCoverage: basesIn,
689 PathLength: len(path),
690 DroppedOutOfOrderTags: droppedOOO,
691 DroppedRepeatedTags: droppedDup,
694 totalPathLen += len(path)
696 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)
697 return ret, stats, nil
700 func (tilelib *tileLibrary) Len() int64 {
701 return atomic.LoadInt64(&tilelib.variants)
704 // Return a tileLibRef for a tile with the given tag and sequence,
705 // adding the sequence to the library if needed.
706 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte, usedByRef bool) tileLibRef {
708 if !tilelib.retainNoCalls {
709 for _, b := range seq {
710 if b != 'a' && b != 'c' && b != 'g' && b != 't' {
716 seqhash := blake2b.Sum256(seq)
717 var vlock sync.Locker
720 if len(tilelib.vlock) > int(tag) {
721 vlock = tilelib.vlock[tag]
723 tilelib.mtx.RUnlock()
727 for i, varhash := range tilelib.variant[tag] {
728 if varhash == seqhash {
730 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
736 if tilelib.variant == nil && tilelib.taglib != nil {
737 tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
738 tilelib.vlock = make([]sync.Locker, tilelib.taglib.Len())
739 for i := range tilelib.vlock {
740 tilelib.vlock[i] = new(sync.Mutex)
743 if int(tag) >= len(tilelib.variant) {
744 oldlen := len(tilelib.vlock)
745 for i := 0; i < oldlen; i++ {
746 tilelib.vlock[i].Lock()
748 // If we haven't seen the tag library yet (as
749 // in a merge), tilelib.taglib.Len() is
750 // zero. We can still behave correctly, we
751 // just need to expand the tilelib.variant and
752 // tilelib.vlock slices as needed.
753 if int(tag) >= cap(tilelib.variant) {
754 // Allocate 2x capacity.
755 newslice := make([][][blake2b.Size256]byte, int(tag)+1, (int(tag)+1)*2)
756 copy(newslice, tilelib.variant)
757 tilelib.variant = newslice[:int(tag)+1]
758 newvlock := make([]sync.Locker, int(tag)+1, (int(tag)+1)*2)
759 copy(newvlock, tilelib.vlock)
760 tilelib.vlock = newvlock[:int(tag)+1]
762 // Use previously allocated capacity,
764 tilelib.variant = tilelib.variant[:int(tag)+1]
765 tilelib.vlock = tilelib.vlock[:int(tag)+1]
767 for i := oldlen; i < len(tilelib.vlock); i++ {
768 tilelib.vlock[i] = new(sync.Mutex)
770 for i := 0; i < oldlen; i++ {
771 tilelib.vlock[i].Unlock()
774 vlock = tilelib.vlock[tag]
779 for i, varhash := range tilelib.variant[tag] {
780 if varhash == seqhash {
782 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
785 atomic.AddInt64(&tilelib.variants, 1)
786 tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
787 variant := tileVariantID(len(tilelib.variant[tag]))
790 if tilelib.retainTileSequences && !dropSeq {
791 seqCopy := append([]byte(nil), seq...)
792 if tilelib.seq2 == nil {
794 if tilelib.seq2 == nil {
795 tilelib.seq2lock = map[[2]byte]sync.Locker{}
796 m := map[[2]byte]map[[blake2b.Size256]byte][]byte{}
798 for i := 0; i < 256; i++ {
800 for j := 0; j < 256; j++ {
802 m[k] = map[[blake2b.Size256]byte][]byte{}
803 tilelib.seq2lock[k] = &sync.Mutex{}
811 copy(k[:], seqhash[:])
812 locker := tilelib.seq2lock[k]
814 tilelib.seq2[k][seqhash] = seqCopy
820 // Save the hash, but not the sequence
823 if tilelib.encoder != nil {
824 tilelib.encoder.Encode(LibraryEntry{
825 TileVariants: []TileVariant{{
834 if tilelib.onAddTileVariant != nil {
835 tilelib.onAddTileVariant(tileLibRef{tag, variant}, seqhash, saveSeq)
837 return tileLibRef{Tag: tag, Variant: variant}
840 func (tilelib *tileLibrary) hashSequence(hash [blake2b.Size256]byte) []byte {
841 var partition [2]byte
842 copy(partition[:], hash[:])
843 return tilelib.seq2[partition][hash]
846 func (tilelib *tileLibrary) TileVariantSequence(libref tileLibRef) []byte {
847 if libref.Variant == 0 || len(tilelib.variant) <= int(libref.Tag) || len(tilelib.variant[libref.Tag]) < int(libref.Variant) {
850 return tilelib.hashSequence(tilelib.variant[libref.Tag][libref.Variant-1])
853 // Tidy deletes unreferenced tile variants and renumbers variants so
854 // more common variants have smaller IDs.
855 func (tilelib *tileLibrary) Tidy() {
856 log.Print("Tidy: compute inref")
857 inref := map[tileLibRef]bool{}
858 for _, refseq := range tilelib.refseqs {
859 for _, librefs := range refseq {
860 for _, libref := range librefs {
865 log.Print("Tidy: compute remap")
866 remap := make([][]tileVariantID, len(tilelib.variant))
867 throttle := throttle{Max: runtime.NumCPU() + 1}
868 for tag, oldvariants := range tilelib.variant {
869 tag, oldvariants := tagID(tag), oldvariants
870 if tag%1000000 == 0 {
871 log.Printf("Tidy: tag %d", tag)
875 defer throttle.Release()
876 uses := make([]int, len(oldvariants))
877 for _, cg := range tilelib.compactGenomes {
878 for phase := 0; phase < 2; phase++ {
879 cgi := int(tag)*2 + phase
880 if cgi < len(cg) && cg[cgi] > 0 {
886 // Compute desired order of variants:
887 // neworder[x] == index in oldvariants that
888 // should move to position x.
889 neworder := make([]int, len(oldvariants))
890 for i := range neworder {
893 sort.Slice(neworder, func(i, j int) bool {
894 if cmp := uses[neworder[i]] - uses[neworder[j]]; cmp != 0 {
897 return bytes.Compare(oldvariants[neworder[i]][:], oldvariants[neworder[j]][:]) < 0
901 // Replace tilelib.variant[tag] with a new
902 // re-ordered slice of hashes, and make a
903 // mapping from old to new variant IDs.
904 remaptag := make([]tileVariantID, len(oldvariants)+1)
905 newvariants := make([][blake2b.Size256]byte, 0, len(neworder))
906 for _, oldi := range neworder {
907 if uses[oldi] > 0 || inref[tileLibRef{Tag: tag, Variant: tileVariantID(oldi + 1)}] {
908 newvariants = append(newvariants, oldvariants[oldi])
909 remaptag[oldi+1] = tileVariantID(len(newvariants))
912 tilelib.variant[tag] = newvariants
913 remap[tag] = remaptag
918 // Apply remap to genomes and reference sequences, so they
919 // refer to the same tile variants using the changed IDs.
920 log.Print("Tidy: apply remap")
921 var wg sync.WaitGroup
922 for _, cg := range tilelib.compactGenomes {
927 for idx, variant := range cg {
928 cg[idx] = remap[tagID(idx/2)][variant]
932 for _, refcs := range tilelib.refseqs {
933 for _, refseq := range refcs {
938 for i, tv := range refseq {
939 refseq[i].Variant = remap[tv.Tag][tv.Variant]
945 log.Print("Tidy: done")
948 func countBases(seq []byte) int {
950 for _, c := range seq {