16 log "github.com/sirupsen/logrus"
17 "golang.org/x/crypto/blake2b"
20 type tileVariantID uint16 // 1-based
22 type tileLibRef struct {
27 type tileSeq map[string][]tileLibRef
29 func (tseq tileSeq) Variants() ([]tileVariantID, int, int) {
31 for _, refs := range tseq {
32 for _, ref := range refs {
33 if maxtag < int(ref.Tag) {
38 vars := make([]tileVariantID, maxtag+1)
40 for _, refs := range tseq {
41 for _, ref := range refs {
42 if vars[int(ref.Tag)] != 0 {
47 vars[int(ref.Tag)] = ref.Variant
50 return vars, kept, dropped
53 type tileLibrary struct {
56 retainTileSequences bool
59 variant [][][blake2b.Size256]byte
60 refseqs map[string]map[string][]tileLibRef
61 compactGenomes map[string][]tileVariantID
63 seq map[[blake2b.Size256]byte][]byte
65 // if non-nil, write out any tile variants added while tiling
71 func (tilelib *tileLibrary) loadTagSet(newtagset [][]byte) error {
72 // Loading a tagset means either passing it through to the
73 // output (if it's the first one we've seen), or just ensuring
74 // it doesn't disagree with what we already have.
75 if len(newtagset) == 0 {
79 defer tilelib.mtx.Unlock()
80 if tilelib.taglib == nil || tilelib.taglib.Len() == 0 {
81 tilelib.taglib = &tagLibrary{}
82 err := tilelib.taglib.setTags(newtagset)
86 if tilelib.encoder != nil {
87 err = tilelib.encoder.Encode(LibraryEntry{
94 } else if tilelib.taglib.Len() != len(newtagset) {
95 return fmt.Errorf("cannot merge libraries with differing tagsets")
97 current := tilelib.taglib.Tags()
98 for i := range newtagset {
99 if !bytes.Equal(newtagset[i], current[i]) {
100 return fmt.Errorf("cannot merge libraries with differing tagsets")
107 func (tilelib *tileLibrary) loadTileVariants(tvs []TileVariant, variantmap map[tileLibRef]tileVariantID) error {
108 for _, tv := range tvs {
109 // Assign a new variant ID (unique across all inputs)
110 // for each input variant.
111 variantmap[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence).Variant
116 func (tilelib *tileLibrary) loadCompactGenomes(cgs []CompactGenome, variantmap map[tileLibRef]tileVariantID, onLoadGenome func(CompactGenome)) error {
117 log.Debugf("loadCompactGenomes: %d", len(cgs))
118 var wg sync.WaitGroup
119 errs := make(chan error, 1)
120 for _, cg := range cgs {
125 for i, variant := range cg.Variants {
133 newvariant, ok := variantmap[tileLibRef{Tag: tag, Variant: variant}]
135 err := fmt.Errorf("oops: genome %q has variant %d for tag %d, but that variant was not in its library", cg.Name, variant, tag)
142 log.Tracef("loadCompactGenomes: cg %s tag %d variant %d => %d", cg.Name, tag, variant, newvariant)
143 cg.Variants[i] = newvariant
145 if onLoadGenome != nil {
148 if tilelib.encoder != nil {
149 err := tilelib.encoder.Encode(LibraryEntry{
150 CompactGenomes: []CompactGenome{cg},
160 if tilelib.compactGenomes != nil {
162 defer tilelib.mtx.Unlock()
163 tilelib.compactGenomes[cg.Name] = cg.Variants
172 func (tilelib *tileLibrary) loadCompactSequences(cseqs []CompactSequence, variantmap map[tileLibRef]tileVariantID) error {
173 log.Debugf("loadCompactSequences: %d", len(cseqs))
174 for _, cseq := range cseqs {
175 for _, tseq := range cseq.TileSequences {
176 for i, libref := range tseq {
177 if libref.Variant == 0 {
178 // No variant (e.g., import
179 // dropped tiles with
180 // no-calls) = no translation.
183 v, ok := variantmap[libref]
185 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)
190 if tilelib.encoder != nil {
191 if err := tilelib.encoder.Encode(LibraryEntry{
192 CompactSequences: []CompactSequence{cseq},
199 defer tilelib.mtx.Unlock()
200 if tilelib.refseqs == nil {
201 tilelib.refseqs = map[string]map[string][]tileLibRef{}
203 for _, cseq := range cseqs {
204 tilelib.refseqs[cseq.Name] = cseq.TileSequences
209 // Load library data from rdr. Tile variants might be renumbered in
210 // the process; in that case, genomes variants will be renumbered to
213 // If onLoadGenome is non-nil, call it on each CompactGenome entry.
214 func (tilelib *tileLibrary) LoadGob(ctx context.Context, rdr io.Reader, gz bool, onLoadGenome func(CompactGenome)) error {
215 cgs := []CompactGenome{}
216 cseqs := []CompactSequence{}
217 variantmap := map[tileLibRef]tileVariantID{}
218 err := DecodeLibrary(rdr, gz, func(ent *LibraryEntry) error {
219 if ctx.Err() != nil {
222 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
225 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
228 cgs = append(cgs, ent.CompactGenomes...)
229 cseqs = append(cseqs, ent.CompactSequences...)
235 if ctx.Err() != nil {
238 err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
242 err = tilelib.loadCompactSequences(cseqs, variantmap)
249 type importStats struct {
256 DroppedOutOfOrderTiles int
259 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader, matchChromosome *regexp.Regexp) (tileSeq, []importStats, error) {
265 todo := make(chan jobT)
266 scanner := bufio.NewScanner(rdr)
272 buf := scanner.Bytes()
273 if len(buf) > 0 && buf[0] == '>' {
274 todo <- jobT{seqlabel, fasta}
275 seqlabel, fasta = strings.SplitN(string(buf[1:]), " ", 2)[0], nil
276 log.Debugf("%s %s reading fasta", filelabel, seqlabel)
278 fasta = append(fasta, bytes.ToLower(buf)...)
281 todo <- jobT{seqlabel, fasta}
283 type foundtag struct {
288 found := make([]foundtag, 2000000)
289 path := make([]tileLibRef, 2000000)
292 skippedSequences := 0
293 stats := make([]importStats, 0, len(todo))
294 for job := range todo {
295 if len(job.fasta) == 0 {
297 } else if !matchChromosome.MatchString(job.label) {
301 log.Debugf("%s %s tiling", filelabel, job.label)
304 tilelib.taglib.FindAll(job.fasta, func(tagid tagID, pos, taglen int) {
305 found = append(found, foundtag{pos: pos, tagid: tagid, taglen: taglen})
307 totalFoundTags += len(found)
312 last := foundtag{tagid: -1}
314 keep := longestIncreasingSubsequence(len(found), func(i int) int { return int(found[i].tagid) })
315 for i, x := range keep {
318 skipped = len(found) - len(keep)
319 found = found[:len(keep)]
321 for i, f := range found {
322 log.Tracef("%s %s found[%d] == %#v", filelabel, job.label, i, f)
324 // first tag in sequence
325 last = foundtag{tagid: f.tagid}
328 libref := tilelib.getRef(last.tagid, job.fasta[last.pos:f.pos+f.taglen])
329 path = append(path, libref)
330 if libref.Variant > 0 {
331 // Count output coverage from
332 // the end of the previous tag
333 // (if any) to the end of the
334 // current tag, IOW don't
335 // double-count coverage for
337 basesOut += countBases(job.fasta[last.pos+last.taglen : f.pos+f.taglen])
339 // If we dropped this tile
340 // (because !retainNoCalls),
341 // set taglen=0 so the
342 // overlapping tag is counted
343 // toward coverage on the
350 log.Warnf("%s %s no tags found", filelabel, job.label)
352 libref := tilelib.getRef(last.tagid, job.fasta[last.pos:])
353 path = append(path, libref)
354 if libref.Variant > 0 {
355 basesOut += countBases(job.fasta[last.pos+last.taglen:])
359 pathcopy := make([]tileLibRef, len(path))
361 ret[job.label] = pathcopy
363 basesIn := countBases(job.fasta)
364 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)
365 stats = append(stats, importStats{
366 InputFile: filelabel,
367 InputLabel: job.label,
368 InputLength: len(job.fasta),
369 InputCoverage: basesIn,
370 TileCoverage: basesOut,
371 PathLength: len(path),
372 DroppedOutOfOrderTiles: skipped,
375 totalPathLen += len(path)
377 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)
378 return ret, stats, scanner.Err()
381 func (tilelib *tileLibrary) Len() int {
383 defer tilelib.mtx.Unlock()
384 return tilelib.variants
387 // Return a tileLibRef for a tile with the given tag and sequence,
388 // adding the sequence to the library if needed.
389 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte) tileLibRef {
391 if !tilelib.retainNoCalls {
392 for _, b := range seq {
393 if b != 'a' && b != 'c' && b != 'g' && b != 't' {
400 if tilelib.variant == nil && tilelib.taglib != nil {
401 tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
403 if int(tag) >= len(tilelib.variant) {
404 // If we haven't seen the tag library yet (as in a
405 // merge), tilelib.taglib.Len() is zero. We can still
406 // behave correctly, we just need to expand the
407 // tilelib.variant slice as needed.
408 if int(tag) >= cap(tilelib.variant) {
409 // Allocate 2x capacity.
410 newslice := make([][][blake2b.Size256]byte, int(tag)+1, (int(tag)+1)*2)
411 copy(newslice, tilelib.variant)
412 tilelib.variant = newslice[:int(tag)+1]
414 // Use previously allocated capacity, avoiding
416 tilelib.variant = tilelib.variant[:int(tag)+1]
419 seqhash := blake2b.Sum256(seq)
420 for i, varhash := range tilelib.variant[tag] {
421 if varhash == seqhash {
423 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
427 tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
428 if tilelib.retainTileSequences && !dropSeq {
429 if tilelib.seq == nil {
430 tilelib.seq = map[[blake2b.Size256]byte][]byte{}
432 tilelib.seq[seqhash] = append([]byte(nil), seq...)
434 variant := tileVariantID(len(tilelib.variant[tag]))
437 if tilelib.encoder != nil {
440 // Save the hash, but not the sequence
443 tilelib.encoder.Encode(LibraryEntry{
444 TileVariants: []TileVariant{{
452 return tileLibRef{Tag: tag, Variant: variant}
455 func (tilelib *tileLibrary) TileVariantSequence(libref tileLibRef) []byte {
456 if libref.Variant == 0 || len(tilelib.variant) <= int(libref.Tag) || len(tilelib.variant[libref.Tag]) < int(libref.Variant) {
459 return tilelib.seq[tilelib.variant[libref.Tag][libref.Variant-1]]
462 // Tidy deletes unreferenced tile variants and renumbers variants so
463 // more common variants have smaller IDs.
464 func (tilelib *tileLibrary) Tidy() {
465 log.Print("Tidy: compute inref")
466 inref := map[tileLibRef]bool{}
467 for _, refseq := range tilelib.refseqs {
468 for _, librefs := range refseq {
469 for _, libref := range librefs {
474 log.Print("Tidy: compute remap")
475 remap := make([][]tileVariantID, len(tilelib.variant))
476 throttle := throttle{Max: runtime.NumCPU() + 1}
477 for tag, oldvariants := range tilelib.variant {
478 tag, oldvariants := tagID(tag), oldvariants
479 if tag%1000000 == 0 {
480 log.Printf("Tidy: tag %d", tag)
484 defer throttle.Release()
485 uses := make([]int, len(oldvariants))
486 for _, cg := range tilelib.compactGenomes {
487 for phase := 0; phase < 2; phase++ {
488 cgi := int(tag)*2 + phase
489 if cgi < len(cg) && cg[cgi] > 0 {
495 // Compute desired order of variants:
496 // neworder[x] == index in oldvariants that
497 // should move to position x.
498 neworder := make([]int, len(oldvariants))
499 for i := range neworder {
502 sort.Slice(neworder, func(i, j int) bool {
503 if cmp := uses[neworder[i]] - uses[neworder[j]]; cmp != 0 {
506 return bytes.Compare(oldvariants[neworder[i]][:], oldvariants[neworder[j]][:]) < 0
510 // Replace tilelib.variants[tag] with a new
511 // re-ordered slice of hashes, and make a
512 // mapping from old to new variant IDs.
513 remaptag := make([]tileVariantID, len(oldvariants)+1)
514 newvariants := make([][blake2b.Size256]byte, 0, len(neworder))
515 for _, oldi := range neworder {
516 if uses[oldi] > 0 || inref[tileLibRef{Tag: tag, Variant: tileVariantID(oldi + 1)}] {
517 newvariants = append(newvariants, oldvariants[oldi])
518 remaptag[oldi+1] = tileVariantID(len(newvariants))
521 tilelib.variant[tag] = newvariants
522 remap[tag] = remaptag
527 // Apply remap to genomes and reference sequences, so they
528 // refer to the same tile variants using the changed IDs.
529 log.Print("Tidy: apply remap")
530 for _, cg := range tilelib.compactGenomes {
531 for idx, variant := range cg {
532 cg[idx] = remap[tagID(idx/2)][variant]
535 for _, refcs := range tilelib.refseqs {
536 for _, refseq := range refcs {
537 for i, tv := range refseq {
538 refseq[i].Variant = remap[tv.Tag][tv.Variant]
542 log.Print("Tidy: done")
545 func countBases(seq []byte) int {
547 for _, c := range seq {