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 {
54 variant [][][blake2b.Size256]byte
55 refseqs map[string]map[string][]tileLibRef
57 // seq map[[blake2b.Size]byte][]byte
59 // if non-nil, write out any tile variants added while tiling
65 func (tilelib *tileLibrary) loadTagSet(newtagset [][]byte) error {
66 // Loading a tagset means either passing it through to the
67 // output (if it's the first one we've seen), or just ensuring
68 // it doesn't disagree with what we already have.
69 if len(newtagset) == 0 {
73 defer tilelib.mtx.Unlock()
74 if tilelib.taglib == nil || tilelib.taglib.Len() == 0 {
75 tilelib.taglib = &tagLibrary{}
76 err := tilelib.taglib.setTags(newtagset)
80 if tilelib.encoder != nil {
81 err = tilelib.encoder.Encode(LibraryEntry{
88 } else if tilelib.taglib.Len() != len(newtagset) {
89 return fmt.Errorf("cannot merge libraries with differing tagsets")
91 current := tilelib.taglib.Tags()
92 for i := range newtagset {
93 if !bytes.Equal(newtagset[i], current[i]) {
94 return fmt.Errorf("cannot merge libraries with differing tagsets")
101 func (tilelib *tileLibrary) loadTileVariants(tvs []TileVariant, variantmap map[tileLibRef]tileVariantID) error {
102 for _, tv := range tvs {
103 // Assign a new variant ID (unique across all inputs)
104 // for each input variant.
105 variantmap[tileLibRef{Tag: tv.Tag, Variant: tv.Variant}] = tilelib.getRef(tv.Tag, tv.Sequence).Variant
110 func (tilelib *tileLibrary) loadCompactGenomes(cgs []CompactGenome, variantmap map[tileLibRef]tileVariantID, onLoadGenome func(CompactGenome)) error {
111 log.Debugf("loadCompactGenomes: %d", len(cgs))
112 var wg sync.WaitGroup
113 errs := make(chan error, 1)
114 for _, cg := range cgs {
119 for i, variant := range cg.Variants {
127 newvariant, ok := variantmap[tileLibRef{Tag: tag, Variant: variant}]
129 err := fmt.Errorf("oops: genome %q has variant %d for tag %d, but that variant was not in its library", cg.Name, variant, tag)
136 log.Tracef("loadCompactGenomes: cg %s tag %d variant %d => %d", cg.Name, tag, variant, newvariant)
137 cg.Variants[i] = newvariant
139 if onLoadGenome != nil {
142 if tilelib.encoder != nil {
143 err := tilelib.encoder.Encode(LibraryEntry{
144 CompactGenomes: []CompactGenome{cg},
161 func (tilelib *tileLibrary) loadCompactSequences(cseqs []CompactSequence, variantmap map[tileLibRef]tileVariantID) error {
162 log.Debugf("loadCompactSequences: %d", len(cseqs))
163 for _, cseq := range cseqs {
164 for _, tseq := range cseq.TileSequences {
165 for i, libref := range tseq {
166 if libref.Variant == 0 {
167 // No variant (e.g., import
168 // dropped tiles with
169 // no-calls) = no translation.
172 v, ok := variantmap[libref]
174 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)
179 if tilelib.encoder != nil {
180 if err := tilelib.encoder.Encode(LibraryEntry{
181 CompactSequences: []CompactSequence{cseq},
188 defer tilelib.mtx.Unlock()
189 if tilelib.refseqs == nil {
190 tilelib.refseqs = map[string]map[string][]tileLibRef{}
192 for _, cseq := range cseqs {
193 tilelib.refseqs[cseq.Name] = cseq.TileSequences
198 // Load library data from rdr. Tile variants might be renumbered in
199 // the process; in that case, genomes variants will be renumbered to
202 // If onLoadGenome is non-nil, call it on each CompactGenome entry.
203 func (tilelib *tileLibrary) LoadGob(ctx context.Context, rdr io.Reader, onLoadGenome func(CompactGenome)) error {
204 cgs := []CompactGenome{}
205 cseqs := []CompactSequence{}
206 variantmap := map[tileLibRef]tileVariantID{}
207 err := DecodeLibrary(rdr, func(ent *LibraryEntry) error {
208 if ctx.Err() != nil {
211 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
214 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
217 cgs = append(cgs, ent.CompactGenomes...)
218 cseqs = append(cseqs, ent.CompactSequences...)
224 if ctx.Err() != nil {
227 err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
231 err = tilelib.loadCompactSequences(cseqs, variantmap)
238 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader) (tileSeq, error) {
244 todo := make(chan jobT)
245 scanner := bufio.NewScanner(rdr)
251 buf := scanner.Bytes()
252 if len(buf) > 0 && buf[0] == '>' {
253 todo <- jobT{seqlabel, fasta}
254 seqlabel, fasta = strings.SplitN(string(buf[1:]), " ", 2)[0], nil
255 log.Debugf("%s %s reading fasta", filelabel, seqlabel)
257 fasta = append(fasta, bytes.ToLower(buf)...)
260 todo <- jobT{seqlabel, fasta}
262 type foundtag struct {
267 found := make([]foundtag, 2000000)
268 path := make([]tileLibRef, 2000000)
271 skippedSequences := 0
272 for job := range todo {
273 if len(job.fasta) == 0 {
275 } else if strings.Contains(job.label, "_") {
279 log.Debugf("%s %s tiling", filelabel, job.label)
282 tilelib.taglib.FindAll(job.fasta, func(tagid tagID, pos, taglen int) {
283 found = append(found, foundtag{pos: pos, tagid: tagid, taglen: taglen})
285 totalFoundTags += len(found)
290 last := foundtag{tagid: -1}
292 keep := longestIncreasingSubsequence(len(found), func(i int) int { return int(found[i].tagid) })
293 for i, x := range keep {
296 skipped = len(found) - len(keep)
297 found = found[:len(keep)]
299 for i, f := range found {
300 log.Tracef("%s %s found[%d] == %#v", filelabel, job.label, i, f)
302 // first tag in sequence
303 last = foundtag{tagid: f.tagid}
306 libref := tilelib.getRef(last.tagid, job.fasta[last.pos:f.pos+f.taglen])
307 path = append(path, libref)
308 if libref.Variant > 0 {
309 // Count output coverage from
310 // the end of the previous tag
311 // (if any) to the end of the
312 // current tag, IOW don't
313 // double-count coverage for
315 basesOut += countBases(job.fasta[last.pos+last.taglen : f.pos+f.taglen])
317 // If we dropped this tile
318 // (because !includeNoCalls),
319 // set taglen=0 so the
320 // overlapping tag is counted
321 // toward coverage on the
328 log.Warnf("%s %s no tags found", filelabel, job.label)
330 libref := tilelib.getRef(last.tagid, job.fasta[last.pos:])
331 path = append(path, libref)
332 if libref.Variant > 0 {
333 basesOut += countBases(job.fasta[last.pos+last.taglen:])
337 pathcopy := make([]tileLibRef, len(path))
339 ret[job.label] = pathcopy
340 log.Debugf("%s %s tiled with path len %d, skipped %d", filelabel, job.label, len(path), skipped)
342 log.Infof("%s %s fasta in %d coverage in %d coverage out %d", filelabel, job.label, len(job.fasta), countBases(job.fasta), basesOut)
343 totalPathLen += len(path)
345 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)
346 return ret, scanner.Err()
349 func (tilelib *tileLibrary) Len() int {
351 defer tilelib.mtx.Unlock()
352 return tilelib.variants
355 // Return a tileLibRef for a tile with the given tag and sequence,
356 // adding the sequence to the library if needed.
357 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte) tileLibRef {
358 if !tilelib.includeNoCalls {
359 for _, b := range seq {
360 if b != 'a' && b != 'c' && b != 'g' && b != 't' {
361 // return "tile not found" if seq has any
363 return tileLibRef{Tag: tag}
368 // if tilelib.seq == nil {
369 // tilelib.seq = map[[blake2b.Size]byte][]byte{}
371 if tilelib.variant == nil && tilelib.taglib != nil {
372 tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
374 if int(tag) >= len(tilelib.variant) {
375 // If we haven't seen the tag library yet (as in a
376 // merge), tilelib.taglib.Len() is zero. We can still
377 // behave correctly, we just need to expand the
378 // tilelib.variant slice as needed.
379 if int(tag) >= cap(tilelib.variant) {
380 // Allocate 2x capacity.
381 newslice := make([][][blake2b.Size256]byte, int(tag)+1, (int(tag)+1)*2)
382 copy(newslice, tilelib.variant)
383 tilelib.variant = newslice[:int(tag)+1]
385 // Use previously allocated capacity, avoiding
387 tilelib.variant = tilelib.variant[:int(tag)+1]
390 seqhash := blake2b.Sum256(seq)
391 for i, varhash := range tilelib.variant[tag] {
392 if varhash == seqhash {
394 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
398 tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
399 // tilelib.seq[seqhash] = append([]byte(nil), seq...)
400 variant := tileVariantID(len(tilelib.variant[tag]))
403 if tilelib.encoder != nil {
404 tilelib.encoder.Encode(LibraryEntry{
405 TileVariants: []TileVariant{{
413 return tileLibRef{Tag: tag, Variant: variant}
416 func countBases(seq []byte) int {
418 for _, c := range seq {