13 log "github.com/sirupsen/logrus"
14 "golang.org/x/crypto/blake2b"
17 type tileVariantID uint16 // 1-based
19 type tileLibRef struct {
24 type tileSeq map[string][]tileLibRef
26 func (tseq tileSeq) Variants() ([]tileVariantID, int, int) {
28 for _, refs := range tseq {
29 for _, ref := range refs {
30 if maxtag < int(ref.Tag) {
35 vars := make([]tileVariantID, maxtag+1)
37 for _, refs := range tseq {
38 for _, ref := range refs {
39 if vars[int(ref.Tag)] != 0 {
44 vars[int(ref.Tag)] = ref.Variant
47 return vars, kept, dropped
50 type tileLibrary struct {
53 retainTileSequences bool
56 variant [][][blake2b.Size256]byte
57 refseqs map[string]map[string][]tileLibRef
58 compactGenomes map[string][]tileVariantID
60 seq map[[blake2b.Size256]byte][]byte
62 // if non-nil, write out any tile variants added while tiling
68 func (tilelib *tileLibrary) loadTagSet(newtagset [][]byte) error {
69 // Loading a tagset means either passing it through to the
70 // output (if it's the first one we've seen), or just ensuring
71 // it doesn't disagree with what we already have.
72 if len(newtagset) == 0 {
76 defer tilelib.mtx.Unlock()
77 if tilelib.taglib == nil || tilelib.taglib.Len() == 0 {
78 tilelib.taglib = &tagLibrary{}
79 err := tilelib.taglib.setTags(newtagset)
83 if tilelib.encoder != nil {
84 err = tilelib.encoder.Encode(LibraryEntry{
91 } else if tilelib.taglib.Len() != len(newtagset) {
92 return fmt.Errorf("cannot merge libraries with differing tagsets")
94 current := tilelib.taglib.Tags()
95 for i := range newtagset {
96 if !bytes.Equal(newtagset[i], current[i]) {
97 return fmt.Errorf("cannot merge libraries with differing tagsets")
104 func (tilelib *tileLibrary) loadTileVariants(tvs []TileVariant, variantmap map[tileLibRef]tileVariantID) error {
105 for _, tv := range tvs {
106 // Assign a new variant ID (unique across all inputs)
107 // for each input variant.
108 variantmap[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence).Variant
113 func (tilelib *tileLibrary) loadCompactGenomes(cgs []CompactGenome, variantmap map[tileLibRef]tileVariantID, onLoadGenome func(CompactGenome)) error {
114 log.Debugf("loadCompactGenomes: %d", len(cgs))
115 var wg sync.WaitGroup
116 errs := make(chan error, 1)
117 for _, cg := range cgs {
122 for i, variant := range cg.Variants {
130 newvariant, ok := variantmap[tileLibRef{Tag: tag, Variant: variant}]
132 err := fmt.Errorf("oops: genome %q has variant %d for tag %d, but that variant was not in its library", cg.Name, variant, tag)
139 log.Tracef("loadCompactGenomes: cg %s tag %d variant %d => %d", cg.Name, tag, variant, newvariant)
140 cg.Variants[i] = newvariant
142 if onLoadGenome != nil {
145 if tilelib.encoder != nil {
146 err := tilelib.encoder.Encode(LibraryEntry{
147 CompactGenomes: []CompactGenome{cg},
157 if tilelib.compactGenomes != nil {
159 defer tilelib.mtx.Unlock()
160 tilelib.compactGenomes[cg.Name] = cg.Variants
169 func (tilelib *tileLibrary) loadCompactSequences(cseqs []CompactSequence, variantmap map[tileLibRef]tileVariantID) error {
170 log.Debugf("loadCompactSequences: %d", len(cseqs))
171 for _, cseq := range cseqs {
172 for _, tseq := range cseq.TileSequences {
173 for i, libref := range tseq {
174 if libref.Variant == 0 {
175 // No variant (e.g., import
176 // dropped tiles with
177 // no-calls) = no translation.
180 v, ok := variantmap[libref]
182 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)
187 if tilelib.encoder != nil {
188 if err := tilelib.encoder.Encode(LibraryEntry{
189 CompactSequences: []CompactSequence{cseq},
196 defer tilelib.mtx.Unlock()
197 if tilelib.refseqs == nil {
198 tilelib.refseqs = map[string]map[string][]tileLibRef{}
200 for _, cseq := range cseqs {
201 tilelib.refseqs[cseq.Name] = cseq.TileSequences
206 // Load library data from rdr. Tile variants might be renumbered in
207 // the process; in that case, genomes variants will be renumbered to
210 // If onLoadGenome is non-nil, call it on each CompactGenome entry.
211 func (tilelib *tileLibrary) LoadGob(ctx context.Context, rdr io.Reader, onLoadGenome func(CompactGenome)) error {
212 cgs := []CompactGenome{}
213 cseqs := []CompactSequence{}
214 variantmap := map[tileLibRef]tileVariantID{}
215 err := DecodeLibrary(rdr, func(ent *LibraryEntry) error {
216 if ctx.Err() != nil {
219 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
222 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
225 cgs = append(cgs, ent.CompactGenomes...)
226 cseqs = append(cseqs, ent.CompactSequences...)
232 if ctx.Err() != nil {
235 err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
239 err = tilelib.loadCompactSequences(cseqs, variantmap)
246 type importStats struct {
253 DroppedOutOfOrderTiles int
256 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader) (tileSeq, []importStats, error) {
262 todo := make(chan jobT)
263 scanner := bufio.NewScanner(rdr)
269 buf := scanner.Bytes()
270 if len(buf) > 0 && buf[0] == '>' {
271 todo <- jobT{seqlabel, fasta}
272 seqlabel, fasta = strings.SplitN(string(buf[1:]), " ", 2)[0], nil
273 log.Debugf("%s %s reading fasta", filelabel, seqlabel)
275 fasta = append(fasta, bytes.ToLower(buf)...)
278 todo <- jobT{seqlabel, fasta}
280 type foundtag struct {
285 found := make([]foundtag, 2000000)
286 path := make([]tileLibRef, 2000000)
289 skippedSequences := 0
290 stats := make([]importStats, 0, len(todo))
291 for job := range todo {
292 if len(job.fasta) == 0 {
294 } else if strings.Contains(job.label, "_") {
298 log.Debugf("%s %s tiling", filelabel, job.label)
301 tilelib.taglib.FindAll(job.fasta, func(tagid tagID, pos, taglen int) {
302 found = append(found, foundtag{pos: pos, tagid: tagid, taglen: taglen})
304 totalFoundTags += len(found)
309 last := foundtag{tagid: -1}
311 keep := longestIncreasingSubsequence(len(found), func(i int) int { return int(found[i].tagid) })
312 for i, x := range keep {
315 skipped = len(found) - len(keep)
316 found = found[:len(keep)]
318 for i, f := range found {
319 log.Tracef("%s %s found[%d] == %#v", filelabel, job.label, i, f)
321 // first tag in sequence
322 last = foundtag{tagid: f.tagid}
325 libref := tilelib.getRef(last.tagid, job.fasta[last.pos:f.pos+f.taglen])
326 path = append(path, libref)
327 if libref.Variant > 0 {
328 // Count output coverage from
329 // the end of the previous tag
330 // (if any) to the end of the
331 // current tag, IOW don't
332 // double-count coverage for
334 basesOut += countBases(job.fasta[last.pos+last.taglen : f.pos+f.taglen])
336 // If we dropped this tile
337 // (because !includeNoCalls),
338 // set taglen=0 so the
339 // overlapping tag is counted
340 // toward coverage on the
347 log.Warnf("%s %s no tags found", filelabel, job.label)
349 libref := tilelib.getRef(last.tagid, job.fasta[last.pos:])
350 path = append(path, libref)
351 if libref.Variant > 0 {
352 basesOut += countBases(job.fasta[last.pos+last.taglen:])
356 pathcopy := make([]tileLibRef, len(path))
358 ret[job.label] = pathcopy
360 basesIn := countBases(job.fasta)
361 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)
362 stats = append(stats, importStats{
363 InputFile: filelabel,
364 InputLabel: job.label,
365 InputLength: len(job.fasta),
366 InputCoverage: basesIn,
367 TileCoverage: basesOut,
368 PathLength: len(path),
369 DroppedOutOfOrderTiles: skipped,
372 totalPathLen += len(path)
374 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)
375 return ret, stats, scanner.Err()
378 func (tilelib *tileLibrary) Len() int {
380 defer tilelib.mtx.Unlock()
381 return tilelib.variants
384 // Return a tileLibRef for a tile with the given tag and sequence,
385 // adding the sequence to the library if needed.
386 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte) tileLibRef {
387 if !tilelib.includeNoCalls {
388 for _, b := range seq {
389 if b != 'a' && b != 'c' && b != 'g' && b != 't' {
390 // return "tile not found" if seq has any
392 return tileLibRef{Tag: tag}
397 if tilelib.variant == nil && tilelib.taglib != nil {
398 tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
400 if int(tag) >= len(tilelib.variant) {
401 // If we haven't seen the tag library yet (as in a
402 // merge), tilelib.taglib.Len() is zero. We can still
403 // behave correctly, we just need to expand the
404 // tilelib.variant slice as needed.
405 if int(tag) >= cap(tilelib.variant) {
406 // Allocate 2x capacity.
407 newslice := make([][][blake2b.Size256]byte, int(tag)+1, (int(tag)+1)*2)
408 copy(newslice, tilelib.variant)
409 tilelib.variant = newslice[:int(tag)+1]
411 // Use previously allocated capacity, avoiding
413 tilelib.variant = tilelib.variant[:int(tag)+1]
416 seqhash := blake2b.Sum256(seq)
417 for i, varhash := range tilelib.variant[tag] {
418 if varhash == seqhash {
420 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
424 tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
425 if tilelib.retainTileSequences {
426 if tilelib.seq == nil {
427 tilelib.seq = map[[blake2b.Size256]byte][]byte{}
429 tilelib.seq[seqhash] = append([]byte(nil), seq...)
431 variant := tileVariantID(len(tilelib.variant[tag]))
434 if tilelib.encoder != nil {
435 tilelib.encoder.Encode(LibraryEntry{
436 TileVariants: []TileVariant{{
444 return tileLibRef{Tag: tag, Variant: variant}
447 func (tilelib *tileLibrary) TileVariantSequence(libref tileLibRef) []byte {
448 if libref.Variant == 0 || len(tilelib.variant) <= int(libref.Tag) || len(tilelib.variant[libref.Tag]) < int(libref.Variant) {
451 return tilelib.seq[tilelib.variant[libref.Tag][libref.Variant-1]]
454 func countBases(seq []byte) int {
456 for _, c := range seq {