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 {
338 nfiles := ntilefiles + len(tilelib.refseqs)
339 files := make([]*os.File, nfiles)
340 for i := range files {
341 f, err := os.OpenFile(fmt.Sprintf("%s/library.%04d.gob.gz", dir, i), os.O_CREATE|os.O_WRONLY, 0666)
348 bufws := make([]*bufio.Writer, nfiles)
349 for i := range bufws {
350 bufws[i] = bufio.NewWriterSize(files[i], 1<<26)
352 zws := make([]*pgzip.Writer, nfiles)
354 zws[i] = pgzip.NewWriter(bufws[i])
357 encoders := make([]*gob.Encoder, nfiles)
358 for i := range encoders {
359 encoders[i] = gob.NewEncoder(zws[i])
362 cgnames := make([]string, 0, len(tilelib.compactGenomes))
363 for name := range tilelib.compactGenomes {
364 cgnames = append(cgnames, name)
366 sort.Strings(cgnames)
368 refnames := make([]string, 0, len(tilelib.refseqs))
369 for name := range tilelib.refseqs {
370 refnames = append(refnames, name)
372 sort.Strings(refnames)
374 log.Infof("WriteDir: writing %d files", nfiles)
375 ctx, cancel := context.WithCancel(context.Background())
377 errs := make(chan error, nfiles)
378 for start := range files {
381 err := encoders[start].Encode(LibraryEntry{TagSet: tilelib.taglib.Tags()})
386 if refidx := start - ntilefiles; refidx >= 0 {
387 // write each ref to its own file
388 // (they seem to load very slowly)
389 name := refnames[refidx]
390 errs <- encoders[start].Encode(LibraryEntry{CompactSequences: []CompactSequence{{
392 TileSequences: tilelib.refseqs[name],
396 for i := start; i < len(cgnames); i += ntilefiles {
397 err := encoders[start].Encode(LibraryEntry{CompactGenomes: []CompactGenome{{
399 Variants: tilelib.compactGenomes[cgnames[i]],
406 tvs := []TileVariant{}
407 for tag := start; tag < len(tilelib.variant) && ctx.Err() == nil; tag += ntilefiles {
409 for idx, hash := range tilelib.variant[tag] {
410 tvs = append(tvs, TileVariant{
412 Variant: tileVariantID(idx + 1),
414 Sequence: tilelib.hashSequence(hash),
417 err := encoders[start].Encode(LibraryEntry{TileVariants: tvs})
432 log.Info("WriteDir: flushing")
434 err := zws[i].Close()
438 err = bufws[i].Flush()
442 err = files[i].Close()
447 log.Info("WriteDir: done")
451 // Load library data from rdr. Tile variants might be renumbered in
452 // the process; in that case, genomes variants will be renumbered to
455 // If onLoadGenome is non-nil, call it on each CompactGenome entry.
456 func (tilelib *tileLibrary) LoadGob(ctx context.Context, rdr io.Reader, gz bool, onLoadGenome func(CompactGenome)) error {
457 cgs := []CompactGenome{}
458 cseqs := []CompactSequence{}
459 variantmap := map[tileLibRef]tileVariantID{}
460 err := DecodeLibrary(rdr, gz, func(ent *LibraryEntry) error {
461 if ctx.Err() != nil {
464 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
467 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
470 cgs = append(cgs, ent.CompactGenomes...)
471 cseqs = append(cseqs, ent.CompactSequences...)
477 if ctx.Err() != nil {
480 err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
484 err = tilelib.loadCompactSequences(cseqs, variantmap)
491 func (tilelib *tileLibrary) dump(out io.Writer) {
492 printTV := func(tag int, variant tileVariantID) {
494 fmt.Fprintf(out, " -")
495 } else if tag >= len(tilelib.variant) {
496 fmt.Fprintf(out, " (!tag=%d)", tag)
497 } else if int(variant) > len(tilelib.variant[tag]) {
498 fmt.Fprintf(out, " (tag=%d,!variant=%d)", tag, variant)
500 fmt.Fprintf(out, " %x", tilelib.variant[tag][variant-1][:8])
503 for refname, refseqs := range tilelib.refseqs {
504 for seqname, seq := range refseqs {
505 fmt.Fprintf(out, "ref %s %s", refname, seqname)
506 for _, libref := range seq {
507 printTV(int(libref.Tag), libref.Variant)
509 fmt.Fprintf(out, "\n")
512 for name, cg := range tilelib.compactGenomes {
513 fmt.Fprintf(out, "cg %s", name)
514 for tag, variant := range cg {
515 printTV(tag/2, variant)
517 fmt.Fprintf(out, "\n")
521 type importStats struct {
527 DroppedOutOfOrderTiles int
530 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader, matchChromosome *regexp.Regexp) (tileSeq, []importStats, error) {
536 todo := make(chan jobT, 1)
537 scanner := bufio.NewScanner(rdr)
543 buf := scanner.Bytes()
544 if len(buf) > 0 && buf[0] == '>' {
545 todo <- jobT{seqlabel, append([]byte(nil), fasta...)}
546 seqlabel, fasta = strings.SplitN(string(buf[1:]), " ", 2)[0], fasta[:0]
547 log.Debugf("%s %s reading fasta", filelabel, seqlabel)
549 fasta = append(fasta, bytes.ToLower(buf)...)
552 todo <- jobT{seqlabel, fasta}
554 type foundtag struct {
558 found := make([]foundtag, 2000000)
559 path := make([]tileLibRef, 2000000)
562 skippedSequences := 0
563 taglen := tilelib.taglib.TagLen()
564 var stats []importStats
565 for job := range todo {
566 if len(job.fasta) == 0 {
568 } else if !matchChromosome.MatchString(job.label) {
572 log.Debugf("%s %s tiling", filelabel, job.label)
575 tilelib.taglib.FindAll(job.fasta, func(tagid tagID, pos, taglen int) {
576 found = append(found, foundtag{pos: pos, tagid: tagid})
578 totalFoundTags += len(found)
580 log.Warnf("%s %s no tags found", filelabel, job.label)
585 log.Infof("%s %s keeping longest increasing subsequence", filelabel, job.label)
586 keep := longestIncreasingSubsequence(len(found), func(i int) int { return int(found[i].tagid) })
587 for i, x := range keep {
590 skipped = len(found) - len(keep)
591 found = found[:len(keep)]
594 log.Infof("%s %s getting %d librefs", filelabel, job.label, len(found))
595 throttle := &throttle{Max: runtime.NumCPU()}
596 path = path[:len(found)]
598 for i, f := range found {
602 defer throttle.Release()
603 var startpos, endpos int
609 if i == len(found)-1 {
610 endpos = len(job.fasta)
612 endpos = found[i+1].pos + taglen
614 path[i] = tilelib.getRef(f.tagid, job.fasta[startpos:endpos])
615 if countBases(job.fasta[startpos:endpos]) != endpos-startpos {
616 atomic.AddInt64(&lowquality, 1)
622 log.Infof("%s %s copying path", filelabel, job.label)
624 pathcopy := make([]tileLibRef, len(path))
626 ret[job.label] = pathcopy
628 basesIn := countBases(job.fasta)
629 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)
630 stats = append(stats, importStats{
631 InputFile: filelabel,
632 InputLabel: job.label,
633 InputLength: len(job.fasta),
634 InputCoverage: basesIn,
635 PathLength: len(path),
636 DroppedOutOfOrderTiles: skipped,
639 totalPathLen += len(path)
641 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)
642 return ret, stats, scanner.Err()
645 func (tilelib *tileLibrary) Len() int64 {
646 return atomic.LoadInt64(&tilelib.variants)
649 // Return a tileLibRef for a tile with the given tag and sequence,
650 // adding the sequence to the library if needed.
651 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte) tileLibRef {
653 if !tilelib.retainNoCalls {
654 for _, b := range seq {
655 if b != 'a' && b != 'c' && b != 'g' && b != 't' {
661 seqhash := blake2b.Sum256(seq)
662 var vlock sync.Locker
665 if len(tilelib.vlock) > int(tag) {
666 vlock = tilelib.vlock[tag]
668 tilelib.mtx.RUnlock()
672 for i, varhash := range tilelib.variant[tag] {
673 if varhash == seqhash {
675 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
681 if tilelib.variant == nil && tilelib.taglib != nil {
682 tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
683 tilelib.vlock = make([]sync.Locker, tilelib.taglib.Len())
684 for i := range tilelib.vlock {
685 tilelib.vlock[i] = new(sync.Mutex)
688 if int(tag) >= len(tilelib.variant) {
689 oldlen := len(tilelib.vlock)
690 for i := 0; i < oldlen; i++ {
691 tilelib.vlock[i].Lock()
693 // If we haven't seen the tag library yet (as
694 // in a merge), tilelib.taglib.Len() is
695 // zero. We can still behave correctly, we
696 // just need to expand the tilelib.variant and
697 // tilelib.vlock slices as needed.
698 if int(tag) >= cap(tilelib.variant) {
699 // Allocate 2x capacity.
700 newslice := make([][][blake2b.Size256]byte, int(tag)+1, (int(tag)+1)*2)
701 copy(newslice, tilelib.variant)
702 tilelib.variant = newslice[:int(tag)+1]
703 newvlock := make([]sync.Locker, int(tag)+1, (int(tag)+1)*2)
704 copy(newvlock, tilelib.vlock)
705 tilelib.vlock = newvlock[:int(tag)+1]
707 // Use previously allocated capacity,
709 tilelib.variant = tilelib.variant[:int(tag)+1]
710 tilelib.vlock = tilelib.vlock[:int(tag)+1]
712 for i := oldlen; i < len(tilelib.vlock); i++ {
713 tilelib.vlock[i] = new(sync.Mutex)
715 for i := 0; i < oldlen; i++ {
716 tilelib.vlock[i].Unlock()
719 vlock = tilelib.vlock[tag]
724 for i, varhash := range tilelib.variant[tag] {
725 if varhash == seqhash {
727 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
730 atomic.AddInt64(&tilelib.variants, 1)
731 tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
732 variant := tileVariantID(len(tilelib.variant[tag]))
735 if tilelib.retainTileSequences && !dropSeq {
736 seqCopy := append([]byte(nil), seq...)
737 if tilelib.seq2 == nil {
739 if tilelib.seq2 == nil {
740 tilelib.seq2lock = map[[2]byte]sync.Locker{}
741 m := map[[2]byte]map[[blake2b.Size256]byte][]byte{}
743 for i := 0; i < 256; i++ {
745 for j := 0; j < 256; j++ {
747 m[k] = map[[blake2b.Size256]byte][]byte{}
748 tilelib.seq2lock[k] = &sync.Mutex{}
756 copy(k[:], seqhash[:])
757 locker := tilelib.seq2lock[k]
759 tilelib.seq2[k][seqhash] = seqCopy
763 if tilelib.encoder != nil {
766 // Save the hash, but not the sequence
769 tilelib.encoder.Encode(LibraryEntry{
770 TileVariants: []TileVariant{{
778 return tileLibRef{Tag: tag, Variant: variant}
781 func (tilelib *tileLibrary) hashSequence(hash [blake2b.Size256]byte) []byte {
782 var partition [2]byte
783 copy(partition[:], hash[:])
784 return tilelib.seq2[partition][hash]
787 func (tilelib *tileLibrary) TileVariantSequence(libref tileLibRef) []byte {
788 if libref.Variant == 0 || len(tilelib.variant) <= int(libref.Tag) || len(tilelib.variant[libref.Tag]) < int(libref.Variant) {
791 return tilelib.hashSequence(tilelib.variant[libref.Tag][libref.Variant-1])
794 // Tidy deletes unreferenced tile variants and renumbers variants so
795 // more common variants have smaller IDs.
796 func (tilelib *tileLibrary) Tidy() {
797 log.Print("Tidy: compute inref")
798 inref := map[tileLibRef]bool{}
799 for _, refseq := range tilelib.refseqs {
800 for _, librefs := range refseq {
801 for _, libref := range librefs {
806 log.Print("Tidy: compute remap")
807 remap := make([][]tileVariantID, len(tilelib.variant))
808 throttle := throttle{Max: runtime.NumCPU() + 1}
809 for tag, oldvariants := range tilelib.variant {
810 tag, oldvariants := tagID(tag), oldvariants
811 if tag%1000000 == 0 {
812 log.Printf("Tidy: tag %d", tag)
816 defer throttle.Release()
817 uses := make([]int, len(oldvariants))
818 for _, cg := range tilelib.compactGenomes {
819 for phase := 0; phase < 2; phase++ {
820 cgi := int(tag)*2 + phase
821 if cgi < len(cg) && cg[cgi] > 0 {
827 // Compute desired order of variants:
828 // neworder[x] == index in oldvariants that
829 // should move to position x.
830 neworder := make([]int, len(oldvariants))
831 for i := range neworder {
834 sort.Slice(neworder, func(i, j int) bool {
835 if cmp := uses[neworder[i]] - uses[neworder[j]]; cmp != 0 {
838 return bytes.Compare(oldvariants[neworder[i]][:], oldvariants[neworder[j]][:]) < 0
842 // Replace tilelib.variant[tag] with a new
843 // re-ordered slice of hashes, and make a
844 // mapping from old to new variant IDs.
845 remaptag := make([]tileVariantID, len(oldvariants)+1)
846 newvariants := make([][blake2b.Size256]byte, 0, len(neworder))
847 for _, oldi := range neworder {
848 if uses[oldi] > 0 || inref[tileLibRef{Tag: tag, Variant: tileVariantID(oldi + 1)}] {
849 newvariants = append(newvariants, oldvariants[oldi])
850 remaptag[oldi+1] = tileVariantID(len(newvariants))
853 tilelib.variant[tag] = newvariants
854 remap[tag] = remaptag
859 // Apply remap to genomes and reference sequences, so they
860 // refer to the same tile variants using the changed IDs.
861 log.Print("Tidy: apply remap")
862 var wg sync.WaitGroup
863 for _, cg := range tilelib.compactGenomes {
868 for idx, variant := range cg {
869 cg[idx] = remap[tagID(idx/2)][variant]
873 for _, refcs := range tilelib.refseqs {
874 for _, refseq := range refcs {
879 for i, tv := range refseq {
880 refseq[i].Variant = remap[tv.Tag][tv.Variant]
886 log.Print("Tidy: done")
889 func countBases(seq []byte) int {
891 for _, c := range seq {