18 "github.com/klauspost/pgzip"
19 log "github.com/sirupsen/logrus"
20 "golang.org/x/crypto/blake2b"
23 type tileVariantID uint16 // 1-based
25 type tileLibRef struct {
30 type tileSeq map[string][]tileLibRef
32 func (tseq tileSeq) Variants() ([]tileVariantID, int, int) {
34 for _, refs := range tseq {
35 for _, ref := range refs {
36 if maxtag < int(ref.Tag) {
41 vars := make([]tileVariantID, maxtag+1)
43 for _, refs := range tseq {
44 for _, ref := range refs {
45 if vars[int(ref.Tag)] != 0 {
50 vars[int(ref.Tag)] = ref.Variant
53 return vars, kept, dropped
56 type tileLibrary struct {
59 retainTileSequences bool
62 variant [][][blake2b.Size256]byte
63 refseqs map[string]map[string][]tileLibRef
64 compactGenomes map[string][]tileVariantID
66 seq map[[blake2b.Size256]byte][]byte
68 // if non-nil, write out any tile variants added while tiling
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 {
83 defer tilelib.mtx.Unlock()
84 if tilelib.taglib == nil || tilelib.taglib.Len() == 0 {
85 tilelib.taglib = &tagLibrary{}
86 err := tilelib.taglib.setTags(newtagset)
90 if tilelib.encoder != nil {
91 err = tilelib.encoder.Encode(LibraryEntry{
98 } else if tilelib.taglib.Len() != len(newtagset) {
99 return fmt.Errorf("cannot merge libraries with differing tagsets")
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")
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
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 {
129 for i, variant := range cg.Variants {
137 newvariant, ok := variantmap[tileLibRef{Tag: tag, Variant: variant}]
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)
146 log.Tracef("loadCompactGenomes: cg %s tag %d variant %d => %d", cg.Name, tag, variant, newvariant)
147 cg.Variants[i] = newvariant
149 if onLoadGenome != nil {
152 if tilelib.encoder != nil {
153 err := tilelib.encoder.Encode(LibraryEntry{
154 CompactGenomes: []CompactGenome{cg},
164 if tilelib.compactGenomes != nil {
166 defer tilelib.mtx.Unlock()
167 tilelib.compactGenomes[cg.Name] = cg.Variants
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.
187 v, ok := variantmap[libref]
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)
194 if tilelib.encoder != nil {
195 if err := tilelib.encoder.Encode(LibraryEntry{
196 CompactSequences: []CompactSequence{cseq},
203 defer tilelib.mtx.Unlock()
204 if tilelib.refseqs == nil {
205 tilelib.refseqs = map[string]map[string][]tileLibRef{}
207 for _, cseq := range cseqs {
208 tilelib.refseqs[cseq.Name] = cseq.TileSequences
213 func (tilelib *tileLibrary) LoadDir(ctx context.Context, path string, onLoadGenome func(CompactGenome)) error {
215 var walk func(string) error
216 walk = func(path string) error {
222 fis, err := f.Readdir(-1)
224 files = append(files, path)
227 for _, fi := range fis {
228 if fi.Name() == "." || fi.Name() == ".." {
230 } else if child := path + "/" + fi.Name(); fi.IsDir() {
235 } else if strings.HasSuffix(child, ".gob") || strings.HasSuffix(child, ".gob.gz") {
236 files = append(files, child)
241 log.Infof("LoadDir: walk dir %s", path)
246 ctx, cancel := context.WithCancel(ctx)
249 cgs := []CompactGenome{}
250 cseqs := []CompactSequence{}
251 variantmap := map[tileLibRef]tileVariantID{}
252 errs := make(chan error, len(files))
253 log.Infof("LoadDir: read %d files", len(files))
254 for _, path := range files {
263 defer log.Infof("LoadDir: finished reading %s", path)
264 errs <- DecodeLibrary(f, strings.HasSuffix(path, ".gz"), func(ent *LibraryEntry) error {
265 if ctx.Err() != nil {
268 if len(ent.TagSet) > 0 {
270 if tilelib.taglib == nil || tilelib.taglib.Len() != len(ent.TagSet) {
271 // load first set of tags, or
272 // report mismatch if 2 sets
273 // have different #tags.
274 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
281 variantmapadd := map[tileLibRef]tileVariantID{}
282 for _, tv := range ent.TileVariants {
283 variantmapadd[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence).Variant
286 cgs = append(cgs, ent.CompactGenomes...)
287 cseqs = append(cseqs, ent.CompactSequences...)
288 for k, v := range variantmapadd {
302 log.Info("LoadDir: loadCompactGenomes")
303 err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
307 log.Info("LoadDir: loadCompactSequences")
308 err = tilelib.loadCompactSequences(cseqs, variantmap)
312 log.Info("LoadDir done")
316 func (tilelib *tileLibrary) WriteDir(dir string) error {
318 files := make([]*os.File, nfiles)
319 for i := range files {
320 f, err := os.OpenFile(fmt.Sprintf("%s/library.%04d.gob.gz", dir, i), os.O_CREATE|os.O_WRONLY, 0666)
327 bufws := make([]*bufio.Writer, nfiles)
328 for i := range bufws {
329 bufws[i] = bufio.NewWriterSize(files[i], 1<<26)
331 zws := make([]*pgzip.Writer, nfiles)
333 zws[i] = pgzip.NewWriter(bufws[i])
336 encoders := make([]*gob.Encoder, nfiles)
337 for i := range encoders {
338 encoders[i] = gob.NewEncoder(zws[i])
341 log.Infof("WriteDir: writing %d files", nfiles)
342 ctx, cancel := context.WithCancel(context.Background())
344 errs := make(chan error, nfiles)
345 for start := range files {
348 err := encoders[start].Encode(LibraryEntry{TagSet: tilelib.taglib.Tags()})
354 // For now, just write all the genomes and refs
356 for name, cg := range tilelib.compactGenomes {
357 err := encoders[start].Encode(LibraryEntry{CompactGenomes: []CompactGenome{{
366 for name, tseqs := range tilelib.refseqs {
367 err := encoders[start].Encode(LibraryEntry{CompactSequences: []CompactSequence{{
369 TileSequences: tseqs,
377 tvs := []TileVariant{}
378 for tag := start; tag < len(tilelib.variant) && ctx.Err() == nil; tag += nfiles {
380 for idx, hash := range tilelib.variant[tag] {
381 tvs = append(tvs, TileVariant{
383 Variant: tileVariantID(idx + 1),
385 Sequence: tilelib.seq[hash],
388 err := encoders[start].Encode(LibraryEntry{TileVariants: tvs})
403 log.Info("WriteDir: flushing")
405 err := zws[i].Close()
409 err = bufws[i].Flush()
413 err = files[i].Close()
418 log.Info("WriteDir: done")
422 // Load library data from rdr. Tile variants might be renumbered in
423 // the process; in that case, genomes variants will be renumbered to
426 // If onLoadGenome is non-nil, call it on each CompactGenome entry.
427 func (tilelib *tileLibrary) LoadGob(ctx context.Context, rdr io.Reader, gz bool, onLoadGenome func(CompactGenome)) error {
428 cgs := []CompactGenome{}
429 cseqs := []CompactSequence{}
430 variantmap := map[tileLibRef]tileVariantID{}
431 err := DecodeLibrary(rdr, gz, func(ent *LibraryEntry) error {
432 if ctx.Err() != nil {
435 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
438 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
441 cgs = append(cgs, ent.CompactGenomes...)
442 cseqs = append(cseqs, ent.CompactSequences...)
448 if ctx.Err() != nil {
451 err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
455 err = tilelib.loadCompactSequences(cseqs, variantmap)
462 func (tilelib *tileLibrary) dump(out io.Writer) {
463 printTV := func(tag int, variant tileVariantID) {
465 fmt.Fprintf(out, " -")
466 } else if tag >= len(tilelib.variant) {
467 fmt.Fprintf(out, " (!tag=%d)", tag)
468 } else if int(variant) > len(tilelib.variant[tag]) {
469 fmt.Fprintf(out, " (tag=%d,!variant=%d)", tag, variant)
471 fmt.Fprintf(out, " %x", tilelib.variant[tag][variant-1][:8])
474 for refname, refseqs := range tilelib.refseqs {
475 for seqname, seq := range refseqs {
476 fmt.Fprintf(out, "ref %s %s", refname, seqname)
477 for _, libref := range seq {
478 printTV(int(libref.Tag), libref.Variant)
480 fmt.Fprintf(out, "\n")
483 for name, cg := range tilelib.compactGenomes {
484 fmt.Fprintf(out, "cg %s", name)
485 for tag, variant := range cg {
486 printTV(tag/2, variant)
488 fmt.Fprintf(out, "\n")
492 type importStats struct {
498 DroppedOutOfOrderTiles int
501 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader, matchChromosome *regexp.Regexp) (tileSeq, []importStats, error) {
507 todo := make(chan jobT, 1)
508 scanner := bufio.NewScanner(rdr)
514 buf := scanner.Bytes()
515 if len(buf) > 0 && buf[0] == '>' {
516 todo <- jobT{seqlabel, append([]byte(nil), fasta...)}
517 seqlabel, fasta = strings.SplitN(string(buf[1:]), " ", 2)[0], fasta[:0]
518 log.Debugf("%s %s reading fasta", filelabel, seqlabel)
520 fasta = append(fasta, bytes.ToLower(buf)...)
523 todo <- jobT{seqlabel, fasta}
525 type foundtag struct {
529 found := make([]foundtag, 2000000)
530 path := make([]tileLibRef, 2000000)
533 skippedSequences := 0
534 taglen := tilelib.taglib.TagLen()
535 var stats []importStats
536 for job := range todo {
537 if len(job.fasta) == 0 {
539 } else if !matchChromosome.MatchString(job.label) {
543 log.Debugf("%s %s tiling", filelabel, job.label)
546 tilelib.taglib.FindAll(job.fasta, func(tagid tagID, pos, taglen int) {
547 found = append(found, foundtag{pos: pos, tagid: tagid})
549 totalFoundTags += len(found)
551 log.Warnf("%s %s no tags found", filelabel, job.label)
556 log.Infof("%s %s keeping longest increasing subsequence", filelabel, job.label)
557 keep := longestIncreasingSubsequence(len(found), func(i int) int { return int(found[i].tagid) })
558 for i, x := range keep {
561 skipped = len(found) - len(keep)
562 found = found[:len(keep)]
565 log.Infof("%s %s getting %d librefs", filelabel, job.label, len(found))
566 throttle := &throttle{Max: runtime.NumCPU()}
567 path = path[:len(found)]
569 for i, f := range found {
573 defer throttle.Release()
574 var startpos, endpos int
580 if i == len(found)-1 {
581 endpos = len(job.fasta)
583 endpos = found[i+1].pos + taglen
585 path[i] = tilelib.getRef(f.tagid, job.fasta[startpos:endpos])
586 if countBases(job.fasta[startpos:endpos]) != endpos-startpos {
587 atomic.AddInt64(&lowquality, 1)
593 log.Infof("%s %s copying path", filelabel, job.label)
595 pathcopy := make([]tileLibRef, len(path))
597 ret[job.label] = pathcopy
599 basesIn := countBases(job.fasta)
600 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)
601 stats = append(stats, importStats{
602 InputFile: filelabel,
603 InputLabel: job.label,
604 InputLength: len(job.fasta),
605 InputCoverage: basesIn,
606 PathLength: len(path),
607 DroppedOutOfOrderTiles: skipped,
610 totalPathLen += len(path)
612 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)
613 return ret, stats, scanner.Err()
616 func (tilelib *tileLibrary) Len() int64 {
617 return atomic.LoadInt64(&tilelib.variants)
620 // Return a tileLibRef for a tile with the given tag and sequence,
621 // adding the sequence to the library if needed.
622 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte) tileLibRef {
624 if !tilelib.retainNoCalls {
625 for _, b := range seq {
626 if b != 'a' && b != 'c' && b != 'g' && b != 't' {
632 seqhash := blake2b.Sum256(seq)
633 var vlock sync.Locker
636 if len(tilelib.vlock) > int(tag) {
637 vlock = tilelib.vlock[tag]
639 tilelib.mtx.RUnlock()
643 for i, varhash := range tilelib.variant[tag] {
644 if varhash == seqhash {
646 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
652 if tilelib.variant == nil && tilelib.taglib != nil {
653 tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
654 tilelib.vlock = make([]sync.Locker, tilelib.taglib.Len())
655 for i := range tilelib.vlock {
656 tilelib.vlock[i] = new(sync.Mutex)
659 if int(tag) >= len(tilelib.variant) {
660 oldlen := len(tilelib.vlock)
661 for i := 0; i < oldlen; i++ {
662 tilelib.vlock[i].Lock()
664 // If we haven't seen the tag library yet (as
665 // in a merge), tilelib.taglib.Len() is
666 // zero. We can still behave correctly, we
667 // just need to expand the tilelib.variant and
668 // tilelib.vlock slices as needed.
669 if int(tag) >= cap(tilelib.variant) {
670 // Allocate 2x capacity.
671 newslice := make([][][blake2b.Size256]byte, int(tag)+1, (int(tag)+1)*2)
672 copy(newslice, tilelib.variant)
673 tilelib.variant = newslice[:int(tag)+1]
674 newvlock := make([]sync.Locker, int(tag)+1, (int(tag)+1)*2)
675 copy(newvlock, tilelib.vlock)
676 tilelib.vlock = newvlock[:int(tag)+1]
678 // Use previously allocated capacity,
680 tilelib.variant = tilelib.variant[:int(tag)+1]
681 tilelib.vlock = tilelib.vlock[:int(tag)+1]
683 for i := oldlen; i < len(tilelib.vlock); i++ {
684 tilelib.vlock[i] = new(sync.Mutex)
686 for i := 0; i < oldlen; i++ {
687 tilelib.vlock[i].Unlock()
690 vlock = tilelib.vlock[tag]
695 for i, varhash := range tilelib.variant[tag] {
696 if varhash == seqhash {
698 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
701 atomic.AddInt64(&tilelib.variants, 1)
702 tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
703 variant := tileVariantID(len(tilelib.variant[tag]))
706 if tilelib.retainTileSequences && !dropSeq {
708 if tilelib.seq == nil {
709 tilelib.seq = map[[blake2b.Size256]byte][]byte{}
711 tilelib.seq[seqhash] = append([]byte(nil), seq...)
715 if tilelib.encoder != nil {
718 // Save the hash, but not the sequence
721 tilelib.encoder.Encode(LibraryEntry{
722 TileVariants: []TileVariant{{
730 return tileLibRef{Tag: tag, Variant: variant}
733 func (tilelib *tileLibrary) TileVariantSequence(libref tileLibRef) []byte {
734 if libref.Variant == 0 || len(tilelib.variant) <= int(libref.Tag) || len(tilelib.variant[libref.Tag]) < int(libref.Variant) {
737 return tilelib.seq[tilelib.variant[libref.Tag][libref.Variant-1]]
740 // Tidy deletes unreferenced tile variants and renumbers variants so
741 // more common variants have smaller IDs.
742 func (tilelib *tileLibrary) Tidy() {
743 log.Print("Tidy: compute inref")
744 inref := map[tileLibRef]bool{}
745 for _, refseq := range tilelib.refseqs {
746 for _, librefs := range refseq {
747 for _, libref := range librefs {
752 log.Print("Tidy: compute remap")
753 remap := make([][]tileVariantID, len(tilelib.variant))
754 throttle := throttle{Max: runtime.NumCPU() + 1}
755 for tag, oldvariants := range tilelib.variant {
756 tag, oldvariants := tagID(tag), oldvariants
757 if tag%1000000 == 0 {
758 log.Printf("Tidy: tag %d", tag)
762 defer throttle.Release()
763 uses := make([]int, len(oldvariants))
764 for _, cg := range tilelib.compactGenomes {
765 for phase := 0; phase < 2; phase++ {
766 cgi := int(tag)*2 + phase
767 if cgi < len(cg) && cg[cgi] > 0 {
773 // Compute desired order of variants:
774 // neworder[x] == index in oldvariants that
775 // should move to position x.
776 neworder := make([]int, len(oldvariants))
777 for i := range neworder {
780 sort.Slice(neworder, func(i, j int) bool {
781 if cmp := uses[neworder[i]] - uses[neworder[j]]; cmp != 0 {
784 return bytes.Compare(oldvariants[neworder[i]][:], oldvariants[neworder[j]][:]) < 0
788 // Replace tilelib.variant[tag] with a new
789 // re-ordered slice of hashes, and make a
790 // mapping from old to new variant IDs.
791 remaptag := make([]tileVariantID, len(oldvariants)+1)
792 newvariants := make([][blake2b.Size256]byte, 0, len(neworder))
793 for _, oldi := range neworder {
794 if uses[oldi] > 0 || inref[tileLibRef{Tag: tag, Variant: tileVariantID(oldi + 1)}] {
795 newvariants = append(newvariants, oldvariants[oldi])
796 remaptag[oldi+1] = tileVariantID(len(newvariants))
799 tilelib.variant[tag] = newvariants
800 remap[tag] = remaptag
805 // Apply remap to genomes and reference sequences, so they
806 // refer to the same tile variants using the changed IDs.
807 log.Print("Tidy: apply remap")
808 var wg sync.WaitGroup
809 for _, cg := range tilelib.compactGenomes {
814 for idx, variant := range cg {
815 cg[idx] = remap[tagID(idx/2)][variant]
819 for _, refcs := range tilelib.refseqs {
820 for _, refseq := range refcs {
825 for i, tv := range refseq {
826 refseq[i].Variant = remap[tv.Tag][tv.Variant]
832 log.Print("Tidy: done")
835 func countBases(seq []byte) int {
837 for _, c := range seq {