15 log "github.com/sirupsen/logrus"
16 "golang.org/x/crypto/blake2b"
19 type tileVariantID uint16 // 1-based
21 type tileLibRef struct {
26 type tileSeq map[string][]tileLibRef
28 func (tseq tileSeq) Variants() ([]tileVariantID, int, int) {
30 for _, refs := range tseq {
31 for _, ref := range refs {
32 if maxtag < int(ref.Tag) {
37 vars := make([]tileVariantID, maxtag+1)
39 for _, refs := range tseq {
40 for _, ref := range refs {
41 if vars[int(ref.Tag)] != 0 {
46 vars[int(ref.Tag)] = ref.Variant
49 return vars, kept, dropped
52 type tileLibrary struct {
55 retainTileSequences bool
58 variant [][][blake2b.Size256]byte
59 refseqs map[string]map[string][]tileLibRef
60 compactGenomes map[string][]tileVariantID
62 seq map[[blake2b.Size256]byte][]byte
64 // if non-nil, write out any tile variants added while tiling
70 func (tilelib *tileLibrary) loadTagSet(newtagset [][]byte) error {
71 // Loading a tagset means either passing it through to the
72 // output (if it's the first one we've seen), or just ensuring
73 // it doesn't disagree with what we already have.
74 if len(newtagset) == 0 {
78 defer tilelib.mtx.Unlock()
79 if tilelib.taglib == nil || tilelib.taglib.Len() == 0 {
80 tilelib.taglib = &tagLibrary{}
81 err := tilelib.taglib.setTags(newtagset)
85 if tilelib.encoder != nil {
86 err = tilelib.encoder.Encode(LibraryEntry{
93 } else if tilelib.taglib.Len() != len(newtagset) {
94 return fmt.Errorf("cannot merge libraries with differing tagsets")
96 current := tilelib.taglib.Tags()
97 for i := range newtagset {
98 if !bytes.Equal(newtagset[i], current[i]) {
99 return fmt.Errorf("cannot merge libraries with differing tagsets")
106 func (tilelib *tileLibrary) loadTileVariants(tvs []TileVariant, variantmap map[tileLibRef]tileVariantID) error {
107 for _, tv := range tvs {
108 // Assign a new variant ID (unique across all inputs)
109 // for each input variant.
110 variantmap[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence).Variant
115 func (tilelib *tileLibrary) loadCompactGenomes(cgs []CompactGenome, variantmap map[tileLibRef]tileVariantID, onLoadGenome func(CompactGenome)) error {
116 log.Debugf("loadCompactGenomes: %d", len(cgs))
117 var wg sync.WaitGroup
118 errs := make(chan error, 1)
119 for _, cg := range cgs {
124 for i, variant := range cg.Variants {
132 newvariant, ok := variantmap[tileLibRef{Tag: tag, Variant: variant}]
134 err := fmt.Errorf("oops: genome %q has variant %d for tag %d, but that variant was not in its library", cg.Name, variant, tag)
141 log.Tracef("loadCompactGenomes: cg %s tag %d variant %d => %d", cg.Name, tag, variant, newvariant)
142 cg.Variants[i] = newvariant
144 if onLoadGenome != nil {
147 if tilelib.encoder != nil {
148 err := tilelib.encoder.Encode(LibraryEntry{
149 CompactGenomes: []CompactGenome{cg},
159 if tilelib.compactGenomes != nil {
161 defer tilelib.mtx.Unlock()
162 tilelib.compactGenomes[cg.Name] = cg.Variants
171 func (tilelib *tileLibrary) loadCompactSequences(cseqs []CompactSequence, variantmap map[tileLibRef]tileVariantID) error {
172 log.Debugf("loadCompactSequences: %d", len(cseqs))
173 for _, cseq := range cseqs {
174 for _, tseq := range cseq.TileSequences {
175 for i, libref := range tseq {
176 if libref.Variant == 0 {
177 // No variant (e.g., import
178 // dropped tiles with
179 // no-calls) = no translation.
182 v, ok := variantmap[libref]
184 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)
189 if tilelib.encoder != nil {
190 if err := tilelib.encoder.Encode(LibraryEntry{
191 CompactSequences: []CompactSequence{cseq},
198 defer tilelib.mtx.Unlock()
199 if tilelib.refseqs == nil {
200 tilelib.refseqs = map[string]map[string][]tileLibRef{}
202 for _, cseq := range cseqs {
203 tilelib.refseqs[cseq.Name] = cseq.TileSequences
208 // Load library data from rdr. Tile variants might be renumbered in
209 // the process; in that case, genomes variants will be renumbered to
212 // If onLoadGenome is non-nil, call it on each CompactGenome entry.
213 func (tilelib *tileLibrary) LoadGob(ctx context.Context, rdr io.Reader, gz bool, onLoadGenome func(CompactGenome)) error {
214 cgs := []CompactGenome{}
215 cseqs := []CompactSequence{}
216 variantmap := map[tileLibRef]tileVariantID{}
217 err := DecodeLibrary(rdr, gz, func(ent *LibraryEntry) error {
218 if ctx.Err() != nil {
221 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
224 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
227 cgs = append(cgs, ent.CompactGenomes...)
228 cseqs = append(cseqs, ent.CompactSequences...)
234 if ctx.Err() != nil {
237 err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
241 err = tilelib.loadCompactSequences(cseqs, variantmap)
248 type importStats struct {
255 DroppedOutOfOrderTiles int
258 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader) (tileSeq, []importStats, error) {
264 todo := make(chan jobT)
265 scanner := bufio.NewScanner(rdr)
271 buf := scanner.Bytes()
272 if len(buf) > 0 && buf[0] == '>' {
273 todo <- jobT{seqlabel, fasta}
274 seqlabel, fasta = strings.SplitN(string(buf[1:]), " ", 2)[0], nil
275 log.Debugf("%s %s reading fasta", filelabel, seqlabel)
277 fasta = append(fasta, bytes.ToLower(buf)...)
280 todo <- jobT{seqlabel, fasta}
282 type foundtag struct {
287 found := make([]foundtag, 2000000)
288 path := make([]tileLibRef, 2000000)
291 skippedSequences := 0
292 stats := make([]importStats, 0, len(todo))
293 for job := range todo {
294 if len(job.fasta) == 0 {
296 } else if strings.Contains(job.label, "_") {
300 log.Debugf("%s %s tiling", filelabel, job.label)
303 tilelib.taglib.FindAll(job.fasta, func(tagid tagID, pos, taglen int) {
304 found = append(found, foundtag{pos: pos, tagid: tagid, taglen: taglen})
306 totalFoundTags += len(found)
311 last := foundtag{tagid: -1}
313 keep := longestIncreasingSubsequence(len(found), func(i int) int { return int(found[i].tagid) })
314 for i, x := range keep {
317 skipped = len(found) - len(keep)
318 found = found[:len(keep)]
320 for i, f := range found {
321 log.Tracef("%s %s found[%d] == %#v", filelabel, job.label, i, f)
323 // first tag in sequence
324 last = foundtag{tagid: f.tagid}
327 libref := tilelib.getRef(last.tagid, job.fasta[last.pos:f.pos+f.taglen])
328 path = append(path, libref)
329 if libref.Variant > 0 {
330 // Count output coverage from
331 // the end of the previous tag
332 // (if any) to the end of the
333 // current tag, IOW don't
334 // double-count coverage for
336 basesOut += countBases(job.fasta[last.pos+last.taglen : f.pos+f.taglen])
338 // If we dropped this tile
339 // (because !retainNoCalls),
340 // set taglen=0 so the
341 // overlapping tag is counted
342 // toward coverage on the
349 log.Warnf("%s %s no tags found", filelabel, job.label)
351 libref := tilelib.getRef(last.tagid, job.fasta[last.pos:])
352 path = append(path, libref)
353 if libref.Variant > 0 {
354 basesOut += countBases(job.fasta[last.pos+last.taglen:])
358 pathcopy := make([]tileLibRef, len(path))
360 ret[job.label] = pathcopy
362 basesIn := countBases(job.fasta)
363 log.Infof("%s %s fasta in %d coverage in %d coverage out %d path len %d skipped %d", filelabel, job.label, len(job.fasta), basesIn, basesOut, len(path), skipped)
364 stats = append(stats, importStats{
365 InputFile: filelabel,
366 InputLabel: job.label,
367 InputLength: len(job.fasta),
368 InputCoverage: basesIn,
369 TileCoverage: basesOut,
370 PathLength: len(path),
371 DroppedOutOfOrderTiles: skipped,
374 totalPathLen += len(path)
376 log.Printf("%s tiled with total path len %d in %d sequences (skipped %d sequences with '_' in name, skipped %d out-of-order tags)", filelabel, totalPathLen, len(ret), skippedSequences, totalFoundTags-totalPathLen)
377 return ret, stats, scanner.Err()
380 func (tilelib *tileLibrary) Len() int {
382 defer tilelib.mtx.Unlock()
383 return tilelib.variants
386 // Return a tileLibRef for a tile with the given tag and sequence,
387 // adding the sequence to the library if needed.
388 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte) tileLibRef {
390 if !tilelib.retainNoCalls {
391 for _, b := range seq {
392 if b != 'a' && b != 'c' && b != 'g' && b != 't' {
399 if tilelib.variant == nil && tilelib.taglib != nil {
400 tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
402 if int(tag) >= len(tilelib.variant) {
403 // If we haven't seen the tag library yet (as in a
404 // merge), tilelib.taglib.Len() is zero. We can still
405 // behave correctly, we just need to expand the
406 // tilelib.variant slice as needed.
407 if int(tag) >= cap(tilelib.variant) {
408 // Allocate 2x capacity.
409 newslice := make([][][blake2b.Size256]byte, int(tag)+1, (int(tag)+1)*2)
410 copy(newslice, tilelib.variant)
411 tilelib.variant = newslice[:int(tag)+1]
413 // Use previously allocated capacity, avoiding
415 tilelib.variant = tilelib.variant[:int(tag)+1]
418 seqhash := blake2b.Sum256(seq)
419 for i, varhash := range tilelib.variant[tag] {
420 if varhash == seqhash {
422 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
426 tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
427 if tilelib.retainTileSequences && !dropSeq {
428 if tilelib.seq == nil {
429 tilelib.seq = map[[blake2b.Size256]byte][]byte{}
431 tilelib.seq[seqhash] = append([]byte(nil), seq...)
433 variant := tileVariantID(len(tilelib.variant[tag]))
436 if tilelib.encoder != nil {
439 // Save the hash, but not the sequence
442 tilelib.encoder.Encode(LibraryEntry{
443 TileVariants: []TileVariant{{
451 return tileLibRef{Tag: tag, Variant: variant}
454 func (tilelib *tileLibrary) TileVariantSequence(libref tileLibRef) []byte {
455 if libref.Variant == 0 || len(tilelib.variant) <= int(libref.Tag) || len(tilelib.variant[libref.Tag]) < int(libref.Variant) {
458 return tilelib.seq[tilelib.variant[libref.Tag][libref.Variant-1]]
461 // Tidy deletes unreferenced tile variants and renumbers variants so
462 // more common variants have smaller IDs.
463 func (tilelib *tileLibrary) Tidy() {
464 log.Print("Tidy: compute inref")
465 inref := map[tileLibRef]bool{}
466 for _, refseq := range tilelib.refseqs {
467 for _, librefs := range refseq {
468 for _, libref := range librefs {
473 log.Print("Tidy: compute remap")
474 remap := make([][]tileVariantID, len(tilelib.variant))
475 throttle := throttle{Max: runtime.NumCPU() + 1}
476 for tag, oldvariants := range tilelib.variant {
477 tag, oldvariants := tagID(tag), oldvariants
479 log.Printf("Tidy: tag %d", tag)
483 defer throttle.Release()
484 uses := make([]int, len(oldvariants))
485 for _, cg := range tilelib.compactGenomes {
486 for phase := 0; phase < 2; phase++ {
487 cgi := int(tag)*2 + phase
488 if cgi < len(cg) && cg[cgi] > 0 {
494 // Compute desired order of variants:
495 // neworder[x] == index in oldvariants that
496 // should move to position x.
497 neworder := make([]int, len(oldvariants))
498 for i := range neworder {
501 sort.Slice(neworder, func(i, j int) bool {
502 if cmp := uses[neworder[i]] - uses[neworder[j]]; cmp != 0 {
505 return bytes.Compare(oldvariants[neworder[i]][:], oldvariants[neworder[j]][:]) < 0
509 // Replace tilelib.variants[tag] with a new
510 // re-ordered slice of hashes, and make a
511 // mapping from old to new variant IDs.
512 remaptag := make([]tileVariantID, len(oldvariants)+1)
513 newvariants := make([][blake2b.Size256]byte, 0, len(neworder))
514 for _, oldi := range neworder {
515 if uses[oldi] > 0 || inref[tileLibRef{Tag: tag, Variant: tileVariantID(oldi + 1)}] {
516 newvariants = append(newvariants, oldvariants[oldi])
517 remaptag[oldi+1] = tileVariantID(len(newvariants))
520 tilelib.variant[tag] = newvariants
521 remap[tag] = remaptag
526 // Apply remap to genomes and reference sequences, so they
527 // refer to the same tile variants using the changed IDs.
528 log.Print("Tidy: apply remap")
529 for _, cg := range tilelib.compactGenomes {
530 for idx, variant := range cg {
531 cg[idx] = remap[tagID(idx/2)][variant]
534 for _, refcs := range tilelib.refseqs {
535 for _, refseq := range refcs {
536 for i, tv := range refseq {
537 refseq[i].Variant = remap[tv.Tag][tv.Variant]
541 log.Print("Tidy: done")
544 func countBases(seq []byte) int {
546 for _, c := range seq {