17 log "github.com/sirupsen/logrus"
18 "golang.org/x/crypto/blake2b"
21 type tileVariantID uint16 // 1-based
23 type tileLibRef struct {
28 type tileSeq map[string][]tileLibRef
30 func (tseq tileSeq) Variants() ([]tileVariantID, int, int) {
32 for _, refs := range tseq {
33 for _, ref := range refs {
34 if maxtag < int(ref.Tag) {
39 vars := make([]tileVariantID, maxtag+1)
41 for _, refs := range tseq {
42 for _, ref := range refs {
43 if vars[int(ref.Tag)] != 0 {
48 vars[int(ref.Tag)] = ref.Variant
51 return vars, kept, dropped
54 type tileLibrary struct {
57 retainTileSequences bool
60 variant [][][blake2b.Size256]byte
61 refseqs map[string]map[string][]tileLibRef
62 compactGenomes map[string][]tileVariantID
64 seq map[[blake2b.Size256]byte][]byte
66 // if non-nil, write out any tile variants added while tiling
73 func (tilelib *tileLibrary) loadTagSet(newtagset [][]byte) error {
74 // Loading a tagset means either passing it through to the
75 // output (if it's the first one we've seen), or just ensuring
76 // it doesn't disagree with what we already have.
77 if len(newtagset) == 0 {
81 defer tilelib.mtx.Unlock()
82 if tilelib.taglib == nil || tilelib.taglib.Len() == 0 {
83 tilelib.taglib = &tagLibrary{}
84 err := tilelib.taglib.setTags(newtagset)
88 if tilelib.encoder != nil {
89 err = tilelib.encoder.Encode(LibraryEntry{
96 } else if tilelib.taglib.Len() != len(newtagset) {
97 return fmt.Errorf("cannot merge libraries with differing tagsets")
99 current := tilelib.taglib.Tags()
100 for i := range newtagset {
101 if !bytes.Equal(newtagset[i], current[i]) {
102 return fmt.Errorf("cannot merge libraries with differing tagsets")
109 func (tilelib *tileLibrary) loadTileVariants(tvs []TileVariant, variantmap map[tileLibRef]tileVariantID) error {
110 for _, tv := range tvs {
111 // Assign a new variant ID (unique across all inputs)
112 // for each input variant.
113 variantmap[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence).Variant
118 func (tilelib *tileLibrary) loadCompactGenomes(cgs []CompactGenome, variantmap map[tileLibRef]tileVariantID, onLoadGenome func(CompactGenome)) error {
119 log.Debugf("loadCompactGenomes: %d", len(cgs))
120 var wg sync.WaitGroup
121 errs := make(chan error, 1)
122 for _, cg := range cgs {
127 for i, variant := range cg.Variants {
135 newvariant, ok := variantmap[tileLibRef{Tag: tag, Variant: variant}]
137 err := fmt.Errorf("oops: genome %q has variant %d for tag %d, but that variant was not in its library", cg.Name, variant, tag)
144 log.Tracef("loadCompactGenomes: cg %s tag %d variant %d => %d", cg.Name, tag, variant, newvariant)
145 cg.Variants[i] = newvariant
147 if onLoadGenome != nil {
150 if tilelib.encoder != nil {
151 err := tilelib.encoder.Encode(LibraryEntry{
152 CompactGenomes: []CompactGenome{cg},
162 if tilelib.compactGenomes != nil {
164 defer tilelib.mtx.Unlock()
165 tilelib.compactGenomes[cg.Name] = cg.Variants
174 func (tilelib *tileLibrary) loadCompactSequences(cseqs []CompactSequence, variantmap map[tileLibRef]tileVariantID) error {
175 log.Debugf("loadCompactSequences: %d", len(cseqs))
176 for _, cseq := range cseqs {
177 for _, tseq := range cseq.TileSequences {
178 for i, libref := range tseq {
179 if libref.Variant == 0 {
180 // No variant (e.g., import
181 // dropped tiles with
182 // no-calls) = no translation.
185 v, ok := variantmap[libref]
187 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)
192 if tilelib.encoder != nil {
193 if err := tilelib.encoder.Encode(LibraryEntry{
194 CompactSequences: []CompactSequence{cseq},
201 defer tilelib.mtx.Unlock()
202 if tilelib.refseqs == nil {
203 tilelib.refseqs = map[string]map[string][]tileLibRef{}
205 for _, cseq := range cseqs {
206 tilelib.refseqs[cseq.Name] = cseq.TileSequences
211 // Load library data from rdr. Tile variants might be renumbered in
212 // the process; in that case, genomes variants will be renumbered to
215 // If onLoadGenome is non-nil, call it on each CompactGenome entry.
216 func (tilelib *tileLibrary) LoadGob(ctx context.Context, rdr io.Reader, gz bool, onLoadGenome func(CompactGenome)) error {
217 cgs := []CompactGenome{}
218 cseqs := []CompactSequence{}
219 variantmap := map[tileLibRef]tileVariantID{}
220 err := DecodeLibrary(rdr, gz, func(ent *LibraryEntry) error {
221 if ctx.Err() != nil {
224 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
227 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
230 cgs = append(cgs, ent.CompactGenomes...)
231 cseqs = append(cseqs, ent.CompactSequences...)
237 if ctx.Err() != nil {
240 err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
244 err = tilelib.loadCompactSequences(cseqs, variantmap)
251 func (tilelib *tileLibrary) dump(out io.Writer) {
252 printTV := func(tag int, variant tileVariantID) {
254 fmt.Fprintf(out, " -")
255 } else if tag >= len(tilelib.variant) {
256 fmt.Fprintf(out, " (!tag=%d)", tag)
257 } else if int(variant) > len(tilelib.variant[tag]) {
258 fmt.Fprintf(out, " (tag=%d,!variant=%d)", tag, variant)
260 fmt.Fprintf(out, " %x", tilelib.variant[tag][variant-1][:8])
263 for refname, refseqs := range tilelib.refseqs {
264 for seqname, seq := range refseqs {
265 fmt.Fprintf(out, "ref %s %s", refname, seqname)
266 for _, libref := range seq {
267 printTV(int(libref.Tag), libref.Variant)
269 fmt.Fprintf(out, "\n")
272 for name, cg := range tilelib.compactGenomes {
273 fmt.Fprintf(out, "cg %s", name)
274 for tag, variant := range cg {
275 printTV(tag/2, variant)
277 fmt.Fprintf(out, "\n")
281 type importStats struct {
287 DroppedOutOfOrderTiles int
290 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader, matchChromosome *regexp.Regexp) (tileSeq, []importStats, error) {
296 todo := make(chan jobT, 1)
297 scanner := bufio.NewScanner(rdr)
303 buf := scanner.Bytes()
304 if len(buf) > 0 && buf[0] == '>' {
305 todo <- jobT{seqlabel, append([]byte(nil), fasta...)}
306 seqlabel, fasta = strings.SplitN(string(buf[1:]), " ", 2)[0], fasta[:0]
307 log.Debugf("%s %s reading fasta", filelabel, seqlabel)
309 fasta = append(fasta, bytes.ToLower(buf)...)
312 todo <- jobT{seqlabel, fasta}
314 type foundtag struct {
318 found := make([]foundtag, 2000000)
319 path := make([]tileLibRef, 2000000)
322 skippedSequences := 0
323 taglen := tilelib.taglib.TagLen()
324 var stats []importStats
325 for job := range todo {
326 if len(job.fasta) == 0 {
328 } else if !matchChromosome.MatchString(job.label) {
332 log.Debugf("%s %s tiling", filelabel, job.label)
335 tilelib.taglib.FindAll(job.fasta, func(tagid tagID, pos, taglen int) {
336 found = append(found, foundtag{pos: pos, tagid: tagid})
338 totalFoundTags += len(found)
340 log.Warnf("%s %s no tags found", filelabel, job.label)
345 log.Infof("%s %s keeping longest increasing subsequence", filelabel, job.label)
346 keep := longestIncreasingSubsequence(len(found), func(i int) int { return int(found[i].tagid) })
347 for i, x := range keep {
350 skipped = len(found) - len(keep)
351 found = found[:len(keep)]
354 log.Infof("%s %s getting %d librefs", filelabel, job.label, len(found))
355 throttle := &throttle{Max: runtime.NumCPU()}
356 path = path[:len(found)]
358 for i, f := range found {
362 defer throttle.Release()
363 var startpos, endpos int
369 if i == len(found)-1 {
370 endpos = len(job.fasta)
372 endpos = found[i+1].pos + taglen
374 path[i] = tilelib.getRef(f.tagid, job.fasta[startpos:endpos])
375 if countBases(job.fasta[startpos:endpos]) != endpos-startpos {
376 atomic.AddInt64(&lowquality, 1)
382 log.Infof("%s %s copying path", filelabel, job.label)
384 pathcopy := make([]tileLibRef, len(path))
386 ret[job.label] = pathcopy
388 basesIn := countBases(job.fasta)
389 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)
390 stats = append(stats, importStats{
391 InputFile: filelabel,
392 InputLabel: job.label,
393 InputLength: len(job.fasta),
394 InputCoverage: basesIn,
395 PathLength: len(path),
396 DroppedOutOfOrderTiles: skipped,
399 totalPathLen += len(path)
401 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)
402 return ret, stats, scanner.Err()
405 func (tilelib *tileLibrary) Len() int64 {
406 return atomic.LoadInt64(&tilelib.variants)
409 // Return a tileLibRef for a tile with the given tag and sequence,
410 // adding the sequence to the library if needed.
411 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte) tileLibRef {
413 if !tilelib.retainNoCalls {
414 for _, b := range seq {
415 if b != 'a' && b != 'c' && b != 'g' && b != 't' {
421 seqhash := blake2b.Sum256(seq)
422 var vlock sync.Locker
425 if len(tilelib.vlock) > int(tag) {
426 vlock = tilelib.vlock[tag]
428 tilelib.mtx.RUnlock()
432 for i, varhash := range tilelib.variant[tag] {
433 if varhash == seqhash {
435 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
441 if tilelib.variant == nil && tilelib.taglib != nil {
442 tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
443 tilelib.vlock = make([]sync.Locker, tilelib.taglib.Len())
444 for i := range tilelib.vlock {
445 tilelib.vlock[i] = new(sync.Mutex)
448 if int(tag) >= len(tilelib.variant) {
449 oldlen := len(tilelib.vlock)
450 for i := 0; i < oldlen; i++ {
451 tilelib.vlock[i].Lock()
453 // If we haven't seen the tag library yet (as
454 // in a merge), tilelib.taglib.Len() is
455 // zero. We can still behave correctly, we
456 // just need to expand the tilelib.variant and
457 // tilelib.vlock slices as needed.
458 if int(tag) >= cap(tilelib.variant) {
459 // Allocate 2x capacity.
460 newslice := make([][][blake2b.Size256]byte, int(tag)+1, (int(tag)+1)*2)
461 copy(newslice, tilelib.variant)
462 tilelib.variant = newslice[:int(tag)+1]
463 newvlock := make([]sync.Locker, int(tag)+1, (int(tag)+1)*2)
464 copy(newvlock, tilelib.vlock)
465 tilelib.vlock = newvlock[:int(tag)+1]
467 // Use previously allocated capacity,
469 tilelib.variant = tilelib.variant[:int(tag)+1]
470 tilelib.vlock = tilelib.vlock[:int(tag)+1]
472 for i := oldlen; i < len(tilelib.vlock); i++ {
473 tilelib.vlock[i] = new(sync.Mutex)
475 for i := 0; i < oldlen; i++ {
476 tilelib.vlock[i].Unlock()
479 vlock = tilelib.vlock[tag]
484 for i, varhash := range tilelib.variant[tag] {
485 if varhash == seqhash {
487 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
490 atomic.AddInt64(&tilelib.variants, 1)
491 tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
492 variant := tileVariantID(len(tilelib.variant[tag]))
495 if tilelib.retainTileSequences && !dropSeq {
497 if tilelib.seq == nil {
498 tilelib.seq = map[[blake2b.Size256]byte][]byte{}
500 tilelib.seq[seqhash] = append([]byte(nil), seq...)
504 if tilelib.encoder != nil {
507 // Save the hash, but not the sequence
510 tilelib.encoder.Encode(LibraryEntry{
511 TileVariants: []TileVariant{{
519 return tileLibRef{Tag: tag, Variant: variant}
522 func (tilelib *tileLibrary) TileVariantSequence(libref tileLibRef) []byte {
523 if libref.Variant == 0 || len(tilelib.variant) <= int(libref.Tag) || len(tilelib.variant[libref.Tag]) < int(libref.Variant) {
526 return tilelib.seq[tilelib.variant[libref.Tag][libref.Variant-1]]
529 // Tidy deletes unreferenced tile variants and renumbers variants so
530 // more common variants have smaller IDs.
531 func (tilelib *tileLibrary) Tidy() {
532 log.Print("Tidy: compute inref")
533 inref := map[tileLibRef]bool{}
534 for _, refseq := range tilelib.refseqs {
535 for _, librefs := range refseq {
536 for _, libref := range librefs {
541 log.Print("Tidy: compute remap")
542 remap := make([][]tileVariantID, len(tilelib.variant))
543 throttle := throttle{Max: runtime.NumCPU() + 1}
544 for tag, oldvariants := range tilelib.variant {
545 tag, oldvariants := tagID(tag), oldvariants
546 if tag%1000000 == 0 {
547 log.Printf("Tidy: tag %d", tag)
551 defer throttle.Release()
552 uses := make([]int, len(oldvariants))
553 for _, cg := range tilelib.compactGenomes {
554 for phase := 0; phase < 2; phase++ {
555 cgi := int(tag)*2 + phase
556 if cgi < len(cg) && cg[cgi] > 0 {
562 // Compute desired order of variants:
563 // neworder[x] == index in oldvariants that
564 // should move to position x.
565 neworder := make([]int, len(oldvariants))
566 for i := range neworder {
569 sort.Slice(neworder, func(i, j int) bool {
570 if cmp := uses[neworder[i]] - uses[neworder[j]]; cmp != 0 {
573 return bytes.Compare(oldvariants[neworder[i]][:], oldvariants[neworder[j]][:]) < 0
577 // Replace tilelib.variant[tag] with a new
578 // re-ordered slice of hashes, and make a
579 // mapping from old to new variant IDs.
580 remaptag := make([]tileVariantID, len(oldvariants)+1)
581 newvariants := make([][blake2b.Size256]byte, 0, len(neworder))
582 for _, oldi := range neworder {
583 if uses[oldi] > 0 || inref[tileLibRef{Tag: tag, Variant: tileVariantID(oldi + 1)}] {
584 newvariants = append(newvariants, oldvariants[oldi])
585 remaptag[oldi+1] = tileVariantID(len(newvariants))
588 tilelib.variant[tag] = newvariants
589 remap[tag] = remaptag
594 // Apply remap to genomes and reference sequences, so they
595 // refer to the same tile variants using the changed IDs.
596 log.Print("Tidy: apply remap")
597 for _, cg := range tilelib.compactGenomes {
598 for idx, variant := range cg {
599 cg[idx] = remap[tagID(idx/2)][variant]
602 for _, refcs := range tilelib.refseqs {
603 for _, refseq := range refcs {
604 for i, tv := range refseq {
605 refseq[i].Variant = remap[tv.Tag][tv.Variant]
609 log.Print("Tidy: done")
612 func countBases(seq []byte) int {
614 for _, c := range seq {