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
65 seq2 map[[2]byte]map[[blake2b.Size256]byte][]byte
66 seq2lock map[[2]byte]sync.Locker
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.Infof("loadCompactSequences: %d todo", len(cseqs))
178 for _, cseq := range cseqs {
179 log.Infof("loadCompactSequences: checking %s", cseq.Name)
180 for _, tseq := range cseq.TileSequences {
181 for i, libref := range tseq {
182 if libref.Variant == 0 {
183 // No variant (e.g., import
184 // dropped tiles with
185 // no-calls) = no translation.
188 v, ok := variantmap[libref]
190 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)
195 if tilelib.encoder != nil {
196 if err := tilelib.encoder.Encode(LibraryEntry{
197 CompactSequences: []CompactSequence{cseq},
202 log.Infof("loadCompactSequences: checking %s done", cseq.Name)
205 defer tilelib.mtx.Unlock()
206 if tilelib.refseqs == nil {
207 tilelib.refseqs = map[string]map[string][]tileLibRef{}
209 for _, cseq := range cseqs {
210 tilelib.refseqs[cseq.Name] = cseq.TileSequences
212 log.Info("loadCompactSequences: done")
216 func (tilelib *tileLibrary) LoadDir(ctx context.Context, path string, onLoadGenome func(CompactGenome)) error {
218 var walk func(string) error
219 walk = func(path string) error {
225 fis, err := f.Readdir(-1)
227 files = append(files, path)
230 for _, fi := range fis {
231 if fi.Name() == "." || fi.Name() == ".." {
233 } else if child := path + "/" + fi.Name(); fi.IsDir() {
238 } else if strings.HasSuffix(child, ".gob") || strings.HasSuffix(child, ".gob.gz") {
239 files = append(files, child)
244 log.Infof("LoadDir: walk dir %s", path)
249 ctx, cancel := context.WithCancel(ctx)
252 allcgs := make([][]CompactGenome, len(files))
253 allcseqs := make([][]CompactSequence, len(files))
254 allvariantmap := map[tileLibRef]tileVariantID{}
255 errs := make(chan error, len(files))
256 log.Infof("LoadDir: read %d files", len(files))
257 for fileno, path := range files {
258 fileno, path := fileno, path
266 defer log.Infof("LoadDir: finished reading %s", path)
268 var variantmap = map[tileLibRef]tileVariantID{}
269 var cgs []CompactGenome
270 var cseqs []CompactSequence
271 err = DecodeLibrary(f, strings.HasSuffix(path, ".gz"), func(ent *LibraryEntry) error {
272 if ctx.Err() != nil {
275 if len(ent.TagSet) > 0 {
277 if tilelib.taglib == nil || tilelib.taglib.Len() != len(ent.TagSet) {
278 // load first set of tags, or
279 // report mismatch if 2 sets
280 // have different #tags.
281 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
288 for _, tv := range ent.TileVariants {
289 variantmap[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence).Variant
291 cgs = append(cgs, ent.CompactGenomes...)
292 cseqs = append(cseqs, ent.CompactSequences...)
296 allcseqs[fileno] = cseqs
299 for k, v := range variantmap {
312 log.Info("LoadDir: loadCompactGenomes")
313 var flatcgs []CompactGenome
314 for _, cgs := range allcgs {
315 flatcgs = append(flatcgs, cgs...)
317 err = tilelib.loadCompactGenomes(flatcgs, allvariantmap, onLoadGenome)
322 log.Info("LoadDir: loadCompactSequences")
323 var flatcseqs []CompactSequence
324 for _, cseqs := range allcseqs {
325 flatcseqs = append(flatcseqs, cseqs...)
327 err = tilelib.loadCompactSequences(flatcseqs, allvariantmap)
332 log.Info("LoadDir done")
336 func (tilelib *tileLibrary) WriteDir(dir string) error {
337 nfiles := 128 + len(tilelib.refseqs)
338 files := make([]*os.File, nfiles)
339 for i := range files {
340 f, err := os.OpenFile(fmt.Sprintf("%s/library.%04d.gob.gz", dir, i), os.O_CREATE|os.O_WRONLY, 0666)
347 bufws := make([]*bufio.Writer, nfiles)
348 for i := range bufws {
349 bufws[i] = bufio.NewWriterSize(files[i], 1<<26)
351 zws := make([]*pgzip.Writer, nfiles)
353 zws[i] = pgzip.NewWriter(bufws[i])
356 encoders := make([]*gob.Encoder, nfiles)
357 for i := range encoders {
358 encoders[i] = gob.NewEncoder(zws[i])
361 cgnames := make([]string, 0, len(tilelib.compactGenomes))
362 for name := range tilelib.compactGenomes {
363 cgnames = append(cgnames, name)
365 sort.Strings(cgnames)
367 refnames := make([]string, 0, len(tilelib.refseqs))
368 for name := range tilelib.refseqs {
369 refnames = append(refnames, name)
371 sort.Strings(refnames)
373 log.Infof("WriteDir: writing %d files", nfiles)
374 ctx, cancel := context.WithCancel(context.Background())
376 errs := make(chan error, nfiles)
377 for start := range files {
380 err := encoders[start].Encode(LibraryEntry{TagSet: tilelib.taglib.Tags()})
385 if refidx := start - (nfiles - len(tilelib.refseqs)); refidx >= 0 {
386 // write each ref to its own file
387 // (they seem to load very slowly)
388 name := refnames[refidx]
389 errs <- encoders[start].Encode(LibraryEntry{CompactSequences: []CompactSequence{{
391 TileSequences: tilelib.refseqs[name],
395 for i := start; i < len(cgnames); i += nfiles {
396 err := encoders[start].Encode(LibraryEntry{CompactGenomes: []CompactGenome{{
398 Variants: tilelib.compactGenomes[cgnames[i]],
405 tvs := []TileVariant{}
406 for tag := start; tag < len(tilelib.variant) && ctx.Err() == nil; tag += nfiles {
408 for idx, hash := range tilelib.variant[tag] {
409 tvs = append(tvs, TileVariant{
411 Variant: tileVariantID(idx + 1),
413 Sequence: tilelib.hashSequence(hash),
416 err := encoders[start].Encode(LibraryEntry{TileVariants: tvs})
431 log.Info("WriteDir: flushing")
433 err := zws[i].Close()
437 err = bufws[i].Flush()
441 err = files[i].Close()
446 log.Info("WriteDir: done")
450 // Load library data from rdr. Tile variants might be renumbered in
451 // the process; in that case, genomes variants will be renumbered to
454 // If onLoadGenome is non-nil, call it on each CompactGenome entry.
455 func (tilelib *tileLibrary) LoadGob(ctx context.Context, rdr io.Reader, gz bool, onLoadGenome func(CompactGenome)) error {
456 cgs := []CompactGenome{}
457 cseqs := []CompactSequence{}
458 variantmap := map[tileLibRef]tileVariantID{}
459 err := DecodeLibrary(rdr, gz, func(ent *LibraryEntry) error {
460 if ctx.Err() != nil {
463 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
466 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
469 cgs = append(cgs, ent.CompactGenomes...)
470 cseqs = append(cseqs, ent.CompactSequences...)
476 if ctx.Err() != nil {
479 err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
483 err = tilelib.loadCompactSequences(cseqs, variantmap)
490 func (tilelib *tileLibrary) dump(out io.Writer) {
491 printTV := func(tag int, variant tileVariantID) {
493 fmt.Fprintf(out, " -")
494 } else if tag >= len(tilelib.variant) {
495 fmt.Fprintf(out, " (!tag=%d)", tag)
496 } else if int(variant) > len(tilelib.variant[tag]) {
497 fmt.Fprintf(out, " (tag=%d,!variant=%d)", tag, variant)
499 fmt.Fprintf(out, " %x", tilelib.variant[tag][variant-1][:8])
502 for refname, refseqs := range tilelib.refseqs {
503 for seqname, seq := range refseqs {
504 fmt.Fprintf(out, "ref %s %s", refname, seqname)
505 for _, libref := range seq {
506 printTV(int(libref.Tag), libref.Variant)
508 fmt.Fprintf(out, "\n")
511 for name, cg := range tilelib.compactGenomes {
512 fmt.Fprintf(out, "cg %s", name)
513 for tag, variant := range cg {
514 printTV(tag/2, variant)
516 fmt.Fprintf(out, "\n")
520 type importStats struct {
526 DroppedOutOfOrderTiles int
529 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader, matchChromosome *regexp.Regexp) (tileSeq, []importStats, error) {
535 todo := make(chan jobT, 1)
536 scanner := bufio.NewScanner(rdr)
542 buf := scanner.Bytes()
543 if len(buf) > 0 && buf[0] == '>' {
544 todo <- jobT{seqlabel, append([]byte(nil), fasta...)}
545 seqlabel, fasta = strings.SplitN(string(buf[1:]), " ", 2)[0], fasta[:0]
546 log.Debugf("%s %s reading fasta", filelabel, seqlabel)
548 fasta = append(fasta, bytes.ToLower(buf)...)
551 todo <- jobT{seqlabel, fasta}
553 type foundtag struct {
557 found := make([]foundtag, 2000000)
558 path := make([]tileLibRef, 2000000)
561 skippedSequences := 0
562 taglen := tilelib.taglib.TagLen()
563 var stats []importStats
564 for job := range todo {
565 if len(job.fasta) == 0 {
567 } else if !matchChromosome.MatchString(job.label) {
571 log.Debugf("%s %s tiling", filelabel, job.label)
574 tilelib.taglib.FindAll(job.fasta, func(tagid tagID, pos, taglen int) {
575 found = append(found, foundtag{pos: pos, tagid: tagid})
577 totalFoundTags += len(found)
579 log.Warnf("%s %s no tags found", filelabel, job.label)
584 log.Infof("%s %s keeping longest increasing subsequence", filelabel, job.label)
585 keep := longestIncreasingSubsequence(len(found), func(i int) int { return int(found[i].tagid) })
586 for i, x := range keep {
589 skipped = len(found) - len(keep)
590 found = found[:len(keep)]
593 log.Infof("%s %s getting %d librefs", filelabel, job.label, len(found))
594 throttle := &throttle{Max: runtime.NumCPU()}
595 path = path[:len(found)]
597 for i, f := range found {
601 defer throttle.Release()
602 var startpos, endpos int
608 if i == len(found)-1 {
609 endpos = len(job.fasta)
611 endpos = found[i+1].pos + taglen
613 path[i] = tilelib.getRef(f.tagid, job.fasta[startpos:endpos])
614 if countBases(job.fasta[startpos:endpos]) != endpos-startpos {
615 atomic.AddInt64(&lowquality, 1)
621 log.Infof("%s %s copying path", filelabel, job.label)
623 pathcopy := make([]tileLibRef, len(path))
625 ret[job.label] = pathcopy
627 basesIn := countBases(job.fasta)
628 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)
629 stats = append(stats, importStats{
630 InputFile: filelabel,
631 InputLabel: job.label,
632 InputLength: len(job.fasta),
633 InputCoverage: basesIn,
634 PathLength: len(path),
635 DroppedOutOfOrderTiles: skipped,
638 totalPathLen += len(path)
640 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)
641 return ret, stats, scanner.Err()
644 func (tilelib *tileLibrary) Len() int64 {
645 return atomic.LoadInt64(&tilelib.variants)
648 // Return a tileLibRef for a tile with the given tag and sequence,
649 // adding the sequence to the library if needed.
650 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte) tileLibRef {
652 if !tilelib.retainNoCalls {
653 for _, b := range seq {
654 if b != 'a' && b != 'c' && b != 'g' && b != 't' {
660 seqhash := blake2b.Sum256(seq)
661 var vlock sync.Locker
664 if len(tilelib.vlock) > int(tag) {
665 vlock = tilelib.vlock[tag]
667 tilelib.mtx.RUnlock()
671 for i, varhash := range tilelib.variant[tag] {
672 if varhash == seqhash {
674 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
680 if tilelib.variant == nil && tilelib.taglib != nil {
681 tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
682 tilelib.vlock = make([]sync.Locker, tilelib.taglib.Len())
683 for i := range tilelib.vlock {
684 tilelib.vlock[i] = new(sync.Mutex)
687 if int(tag) >= len(tilelib.variant) {
688 oldlen := len(tilelib.vlock)
689 for i := 0; i < oldlen; i++ {
690 tilelib.vlock[i].Lock()
692 // If we haven't seen the tag library yet (as
693 // in a merge), tilelib.taglib.Len() is
694 // zero. We can still behave correctly, we
695 // just need to expand the tilelib.variant and
696 // tilelib.vlock slices as needed.
697 if int(tag) >= cap(tilelib.variant) {
698 // Allocate 2x capacity.
699 newslice := make([][][blake2b.Size256]byte, int(tag)+1, (int(tag)+1)*2)
700 copy(newslice, tilelib.variant)
701 tilelib.variant = newslice[:int(tag)+1]
702 newvlock := make([]sync.Locker, int(tag)+1, (int(tag)+1)*2)
703 copy(newvlock, tilelib.vlock)
704 tilelib.vlock = newvlock[:int(tag)+1]
706 // Use previously allocated capacity,
708 tilelib.variant = tilelib.variant[:int(tag)+1]
709 tilelib.vlock = tilelib.vlock[:int(tag)+1]
711 for i := oldlen; i < len(tilelib.vlock); i++ {
712 tilelib.vlock[i] = new(sync.Mutex)
714 for i := 0; i < oldlen; i++ {
715 tilelib.vlock[i].Unlock()
718 vlock = tilelib.vlock[tag]
723 for i, varhash := range tilelib.variant[tag] {
724 if varhash == seqhash {
726 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
729 atomic.AddInt64(&tilelib.variants, 1)
730 tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
731 variant := tileVariantID(len(tilelib.variant[tag]))
734 if tilelib.retainTileSequences && !dropSeq {
735 seqCopy := append([]byte(nil), seq...)
736 if tilelib.seq2 == nil {
738 if tilelib.seq2 == nil {
739 tilelib.seq2lock = map[[2]byte]sync.Locker{}
740 m := map[[2]byte]map[[blake2b.Size256]byte][]byte{}
742 for i := 0; i < 256; i++ {
744 for j := 0; j < 256; j++ {
746 m[k] = map[[blake2b.Size256]byte][]byte{}
747 tilelib.seq2lock[k] = &sync.Mutex{}
755 copy(k[:], seqhash[:])
756 locker := tilelib.seq2lock[k]
758 tilelib.seq2[k][seqhash] = seqCopy
762 if tilelib.encoder != nil {
765 // Save the hash, but not the sequence
768 tilelib.encoder.Encode(LibraryEntry{
769 TileVariants: []TileVariant{{
777 return tileLibRef{Tag: tag, Variant: variant}
780 func (tilelib *tileLibrary) hashSequence(hash [blake2b.Size256]byte) []byte {
781 var partition [2]byte
782 copy(partition[:], hash[:])
783 return tilelib.seq2[partition][hash]
786 func (tilelib *tileLibrary) TileVariantSequence(libref tileLibRef) []byte {
787 if libref.Variant == 0 || len(tilelib.variant) <= int(libref.Tag) || len(tilelib.variant[libref.Tag]) < int(libref.Variant) {
790 return tilelib.hashSequence(tilelib.variant[libref.Tag][libref.Variant-1])
793 // Tidy deletes unreferenced tile variants and renumbers variants so
794 // more common variants have smaller IDs.
795 func (tilelib *tileLibrary) Tidy() {
796 log.Print("Tidy: compute inref")
797 inref := map[tileLibRef]bool{}
798 for _, refseq := range tilelib.refseqs {
799 for _, librefs := range refseq {
800 for _, libref := range librefs {
805 log.Print("Tidy: compute remap")
806 remap := make([][]tileVariantID, len(tilelib.variant))
807 throttle := throttle{Max: runtime.NumCPU() + 1}
808 for tag, oldvariants := range tilelib.variant {
809 tag, oldvariants := tagID(tag), oldvariants
810 if tag%1000000 == 0 {
811 log.Printf("Tidy: tag %d", tag)
815 defer throttle.Release()
816 uses := make([]int, len(oldvariants))
817 for _, cg := range tilelib.compactGenomes {
818 for phase := 0; phase < 2; phase++ {
819 cgi := int(tag)*2 + phase
820 if cgi < len(cg) && cg[cgi] > 0 {
826 // Compute desired order of variants:
827 // neworder[x] == index in oldvariants that
828 // should move to position x.
829 neworder := make([]int, len(oldvariants))
830 for i := range neworder {
833 sort.Slice(neworder, func(i, j int) bool {
834 if cmp := uses[neworder[i]] - uses[neworder[j]]; cmp != 0 {
837 return bytes.Compare(oldvariants[neworder[i]][:], oldvariants[neworder[j]][:]) < 0
841 // Replace tilelib.variant[tag] with a new
842 // re-ordered slice of hashes, and make a
843 // mapping from old to new variant IDs.
844 remaptag := make([]tileVariantID, len(oldvariants)+1)
845 newvariants := make([][blake2b.Size256]byte, 0, len(neworder))
846 for _, oldi := range neworder {
847 if uses[oldi] > 0 || inref[tileLibRef{Tag: tag, Variant: tileVariantID(oldi + 1)}] {
848 newvariants = append(newvariants, oldvariants[oldi])
849 remaptag[oldi+1] = tileVariantID(len(newvariants))
852 tilelib.variant[tag] = newvariants
853 remap[tag] = remaptag
858 // Apply remap to genomes and reference sequences, so they
859 // refer to the same tile variants using the changed IDs.
860 log.Print("Tidy: apply remap")
861 var wg sync.WaitGroup
862 for _, cg := range tilelib.compactGenomes {
867 for idx, variant := range cg {
868 cg[idx] = remap[tagID(idx/2)][variant]
872 for _, refcs := range tilelib.refseqs {
873 for _, refseq := range refcs {
878 for i, tv := range refseq {
879 refseq[i].Variant = remap[tv.Tag][tv.Variant]
885 log.Print("Tidy: done")
888 func countBases(seq []byte) int {
890 for _, c := range seq {