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 errs <- DecodeLibrary(f, strings.HasSuffix(path, ".gz"), func(ent *LibraryEntry) error {
264 if ctx.Err() != nil {
269 if tilelib.taglib == nil || tilelib.taglib.Len() != len(ent.TagSet) {
270 // load first set of tags, or
271 // report mismatch if 2 sets
272 // have different #tags.
273 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
277 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
280 cgs = append(cgs, ent.CompactGenomes...)
281 cseqs = append(cseqs, ent.CompactSequences...)
292 log.Info("LoadDir: loadCompactGenomes")
293 err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
297 log.Info("LoadDir: loadCompactSequences")
298 err = tilelib.loadCompactSequences(cseqs, variantmap)
302 log.Info("LoadDir done")
306 func (tilelib *tileLibrary) WriteDir(dir string) error {
308 files := make([]*os.File, nfiles)
309 for i := range files {
310 f, err := os.OpenFile(fmt.Sprintf("%s/library.%04d.gob.gz", dir, i), os.O_CREATE|os.O_WRONLY, 0666)
317 bufws := make([]*bufio.Writer, nfiles)
318 for i := range bufws {
319 bufws[i] = bufio.NewWriterSize(files[i], 1<<26)
321 zws := make([]*pgzip.Writer, nfiles)
323 zws[i] = pgzip.NewWriter(bufws[i])
326 encoders := make([]*gob.Encoder, nfiles)
327 for i := range encoders {
328 encoders[i] = gob.NewEncoder(zws[i])
330 ctx, cancel := context.WithCancel(context.Background())
332 errs := make(chan error, nfiles)
333 for start := range files {
336 err := encoders[start].Encode(LibraryEntry{TagSet: tilelib.taglib.Tags()})
342 // For now, just write all the genomes and refs
344 for name, cg := range tilelib.compactGenomes {
345 err := encoders[start].Encode(LibraryEntry{CompactGenomes: []CompactGenome{{
354 for name, tseqs := range tilelib.refseqs {
355 err := encoders[start].Encode(LibraryEntry{CompactSequences: []CompactSequence{{
357 TileSequences: tseqs,
365 tvs := []TileVariant{}
366 for tag := start; tag < len(tilelib.variant) && ctx.Err() == nil; tag += nfiles {
368 for idx, hash := range tilelib.variant[tag] {
369 tvs = append(tvs, TileVariant{
371 Variant: tileVariantID(idx + 1),
373 Sequence: tilelib.seq[hash],
376 err := encoders[start].Encode(LibraryEntry{TileVariants: tvs})
392 err := zws[i].Close()
396 err = bufws[i].Flush()
400 err = files[i].Close()
408 // Load library data from rdr. Tile variants might be renumbered in
409 // the process; in that case, genomes variants will be renumbered to
412 // If onLoadGenome is non-nil, call it on each CompactGenome entry.
413 func (tilelib *tileLibrary) LoadGob(ctx context.Context, rdr io.Reader, gz bool, onLoadGenome func(CompactGenome)) error {
414 cgs := []CompactGenome{}
415 cseqs := []CompactSequence{}
416 variantmap := map[tileLibRef]tileVariantID{}
417 err := DecodeLibrary(rdr, gz, func(ent *LibraryEntry) error {
418 if ctx.Err() != nil {
421 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
424 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
427 cgs = append(cgs, ent.CompactGenomes...)
428 cseqs = append(cseqs, ent.CompactSequences...)
434 if ctx.Err() != nil {
437 err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
441 err = tilelib.loadCompactSequences(cseqs, variantmap)
448 func (tilelib *tileLibrary) dump(out io.Writer) {
449 printTV := func(tag int, variant tileVariantID) {
451 fmt.Fprintf(out, " -")
452 } else if tag >= len(tilelib.variant) {
453 fmt.Fprintf(out, " (!tag=%d)", tag)
454 } else if int(variant) > len(tilelib.variant[tag]) {
455 fmt.Fprintf(out, " (tag=%d,!variant=%d)", tag, variant)
457 fmt.Fprintf(out, " %x", tilelib.variant[tag][variant-1][:8])
460 for refname, refseqs := range tilelib.refseqs {
461 for seqname, seq := range refseqs {
462 fmt.Fprintf(out, "ref %s %s", refname, seqname)
463 for _, libref := range seq {
464 printTV(int(libref.Tag), libref.Variant)
466 fmt.Fprintf(out, "\n")
469 for name, cg := range tilelib.compactGenomes {
470 fmt.Fprintf(out, "cg %s", name)
471 for tag, variant := range cg {
472 printTV(tag/2, variant)
474 fmt.Fprintf(out, "\n")
478 type importStats struct {
484 DroppedOutOfOrderTiles int
487 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader, matchChromosome *regexp.Regexp) (tileSeq, []importStats, error) {
493 todo := make(chan jobT, 1)
494 scanner := bufio.NewScanner(rdr)
500 buf := scanner.Bytes()
501 if len(buf) > 0 && buf[0] == '>' {
502 todo <- jobT{seqlabel, append([]byte(nil), fasta...)}
503 seqlabel, fasta = strings.SplitN(string(buf[1:]), " ", 2)[0], fasta[:0]
504 log.Debugf("%s %s reading fasta", filelabel, seqlabel)
506 fasta = append(fasta, bytes.ToLower(buf)...)
509 todo <- jobT{seqlabel, fasta}
511 type foundtag struct {
515 found := make([]foundtag, 2000000)
516 path := make([]tileLibRef, 2000000)
519 skippedSequences := 0
520 taglen := tilelib.taglib.TagLen()
521 var stats []importStats
522 for job := range todo {
523 if len(job.fasta) == 0 {
525 } else if !matchChromosome.MatchString(job.label) {
529 log.Debugf("%s %s tiling", filelabel, job.label)
532 tilelib.taglib.FindAll(job.fasta, func(tagid tagID, pos, taglen int) {
533 found = append(found, foundtag{pos: pos, tagid: tagid})
535 totalFoundTags += len(found)
537 log.Warnf("%s %s no tags found", filelabel, job.label)
542 log.Infof("%s %s keeping longest increasing subsequence", filelabel, job.label)
543 keep := longestIncreasingSubsequence(len(found), func(i int) int { return int(found[i].tagid) })
544 for i, x := range keep {
547 skipped = len(found) - len(keep)
548 found = found[:len(keep)]
551 log.Infof("%s %s getting %d librefs", filelabel, job.label, len(found))
552 throttle := &throttle{Max: runtime.NumCPU()}
553 path = path[:len(found)]
555 for i, f := range found {
559 defer throttle.Release()
560 var startpos, endpos int
566 if i == len(found)-1 {
567 endpos = len(job.fasta)
569 endpos = found[i+1].pos + taglen
571 path[i] = tilelib.getRef(f.tagid, job.fasta[startpos:endpos])
572 if countBases(job.fasta[startpos:endpos]) != endpos-startpos {
573 atomic.AddInt64(&lowquality, 1)
579 log.Infof("%s %s copying path", filelabel, job.label)
581 pathcopy := make([]tileLibRef, len(path))
583 ret[job.label] = pathcopy
585 basesIn := countBases(job.fasta)
586 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)
587 stats = append(stats, importStats{
588 InputFile: filelabel,
589 InputLabel: job.label,
590 InputLength: len(job.fasta),
591 InputCoverage: basesIn,
592 PathLength: len(path),
593 DroppedOutOfOrderTiles: skipped,
596 totalPathLen += len(path)
598 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)
599 return ret, stats, scanner.Err()
602 func (tilelib *tileLibrary) Len() int64 {
603 return atomic.LoadInt64(&tilelib.variants)
606 // Return a tileLibRef for a tile with the given tag and sequence,
607 // adding the sequence to the library if needed.
608 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte) tileLibRef {
610 if !tilelib.retainNoCalls {
611 for _, b := range seq {
612 if b != 'a' && b != 'c' && b != 'g' && b != 't' {
618 seqhash := blake2b.Sum256(seq)
619 var vlock sync.Locker
622 if len(tilelib.vlock) > int(tag) {
623 vlock = tilelib.vlock[tag]
625 tilelib.mtx.RUnlock()
629 for i, varhash := range tilelib.variant[tag] {
630 if varhash == seqhash {
632 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
638 if tilelib.variant == nil && tilelib.taglib != nil {
639 tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
640 tilelib.vlock = make([]sync.Locker, tilelib.taglib.Len())
641 for i := range tilelib.vlock {
642 tilelib.vlock[i] = new(sync.Mutex)
645 if int(tag) >= len(tilelib.variant) {
646 oldlen := len(tilelib.vlock)
647 for i := 0; i < oldlen; i++ {
648 tilelib.vlock[i].Lock()
650 // If we haven't seen the tag library yet (as
651 // in a merge), tilelib.taglib.Len() is
652 // zero. We can still behave correctly, we
653 // just need to expand the tilelib.variant and
654 // tilelib.vlock slices as needed.
655 if int(tag) >= cap(tilelib.variant) {
656 // Allocate 2x capacity.
657 newslice := make([][][blake2b.Size256]byte, int(tag)+1, (int(tag)+1)*2)
658 copy(newslice, tilelib.variant)
659 tilelib.variant = newslice[:int(tag)+1]
660 newvlock := make([]sync.Locker, int(tag)+1, (int(tag)+1)*2)
661 copy(newvlock, tilelib.vlock)
662 tilelib.vlock = newvlock[:int(tag)+1]
664 // Use previously allocated capacity,
666 tilelib.variant = tilelib.variant[:int(tag)+1]
667 tilelib.vlock = tilelib.vlock[:int(tag)+1]
669 for i := oldlen; i < len(tilelib.vlock); i++ {
670 tilelib.vlock[i] = new(sync.Mutex)
672 for i := 0; i < oldlen; i++ {
673 tilelib.vlock[i].Unlock()
676 vlock = tilelib.vlock[tag]
681 for i, varhash := range tilelib.variant[tag] {
682 if varhash == seqhash {
684 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
687 atomic.AddInt64(&tilelib.variants, 1)
688 tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
689 variant := tileVariantID(len(tilelib.variant[tag]))
692 if tilelib.retainTileSequences && !dropSeq {
694 if tilelib.seq == nil {
695 tilelib.seq = map[[blake2b.Size256]byte][]byte{}
697 tilelib.seq[seqhash] = append([]byte(nil), seq...)
701 if tilelib.encoder != nil {
704 // Save the hash, but not the sequence
707 tilelib.encoder.Encode(LibraryEntry{
708 TileVariants: []TileVariant{{
716 return tileLibRef{Tag: tag, Variant: variant}
719 func (tilelib *tileLibrary) TileVariantSequence(libref tileLibRef) []byte {
720 if libref.Variant == 0 || len(tilelib.variant) <= int(libref.Tag) || len(tilelib.variant[libref.Tag]) < int(libref.Variant) {
723 return tilelib.seq[tilelib.variant[libref.Tag][libref.Variant-1]]
726 // Tidy deletes unreferenced tile variants and renumbers variants so
727 // more common variants have smaller IDs.
728 func (tilelib *tileLibrary) Tidy() {
729 log.Print("Tidy: compute inref")
730 inref := map[tileLibRef]bool{}
731 for _, refseq := range tilelib.refseqs {
732 for _, librefs := range refseq {
733 for _, libref := range librefs {
738 log.Print("Tidy: compute remap")
739 remap := make([][]tileVariantID, len(tilelib.variant))
740 throttle := throttle{Max: runtime.NumCPU() + 1}
741 for tag, oldvariants := range tilelib.variant {
742 tag, oldvariants := tagID(tag), oldvariants
743 if tag%1000000 == 0 {
744 log.Printf("Tidy: tag %d", tag)
748 defer throttle.Release()
749 uses := make([]int, len(oldvariants))
750 for _, cg := range tilelib.compactGenomes {
751 for phase := 0; phase < 2; phase++ {
752 cgi := int(tag)*2 + phase
753 if cgi < len(cg) && cg[cgi] > 0 {
759 // Compute desired order of variants:
760 // neworder[x] == index in oldvariants that
761 // should move to position x.
762 neworder := make([]int, len(oldvariants))
763 for i := range neworder {
766 sort.Slice(neworder, func(i, j int) bool {
767 if cmp := uses[neworder[i]] - uses[neworder[j]]; cmp != 0 {
770 return bytes.Compare(oldvariants[neworder[i]][:], oldvariants[neworder[j]][:]) < 0
774 // Replace tilelib.variant[tag] with a new
775 // re-ordered slice of hashes, and make a
776 // mapping from old to new variant IDs.
777 remaptag := make([]tileVariantID, len(oldvariants)+1)
778 newvariants := make([][blake2b.Size256]byte, 0, len(neworder))
779 for _, oldi := range neworder {
780 if uses[oldi] > 0 || inref[tileLibRef{Tag: tag, Variant: tileVariantID(oldi + 1)}] {
781 newvariants = append(newvariants, oldvariants[oldi])
782 remaptag[oldi+1] = tileVariantID(len(newvariants))
785 tilelib.variant[tag] = newvariants
786 remap[tag] = remaptag
791 // Apply remap to genomes and reference sequences, so they
792 // refer to the same tile variants using the changed IDs.
793 log.Print("Tidy: apply remap")
794 var wg sync.WaitGroup
795 for _, cg := range tilelib.compactGenomes {
800 for idx, variant := range cg {
801 cg[idx] = remap[tagID(idx/2)][variant]
805 for _, refcs := range tilelib.refseqs {
806 for _, refseq := range refcs {
811 for i, tv := range refseq {
812 refseq[i].Variant = remap[tv.Tag][tv.Variant]
818 log.Print("Tidy: done")
821 func countBases(seq []byte) int {
823 for _, c := range seq {