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 {
115 name, variants := cg.Name, cg.Variants
119 for i, variant := range 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", name, variant, tag)
136 log.Tracef("loadCompactGenomes: cg %s tag %d variant %d => %d", name, tag, variant, newvariant)
137 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 v, ok := variantmap[libref]
168 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)
173 if tilelib.encoder != nil {
174 if err := tilelib.encoder.Encode(LibraryEntry{
175 CompactSequences: []CompactSequence{cseq},
182 defer tilelib.mtx.Unlock()
183 if tilelib.refseqs == nil {
184 tilelib.refseqs = map[string]map[string][]tileLibRef{}
186 for _, cseq := range cseqs {
187 tilelib.refseqs[cseq.Name] = cseq.TileSequences
192 // Load library data from rdr. Tile variants might be renumbered in
193 // the process; in that case, genomes variants will be renumbered to
196 // If onLoadGenome is non-nil, call it on each CompactGenome entry.
197 func (tilelib *tileLibrary) LoadGob(ctx context.Context, rdr io.Reader, onLoadGenome func(CompactGenome)) error {
198 cgs := []CompactGenome{}
199 cseqs := []CompactSequence{}
200 variantmap := map[tileLibRef]tileVariantID{}
201 err := DecodeLibrary(rdr, func(ent *LibraryEntry) error {
202 if ctx.Err() != nil {
205 if err := tilelib.loadTagSet(ent.TagSet); err != nil {
208 if err := tilelib.loadTileVariants(ent.TileVariants, variantmap); err != nil {
211 cgs = append(cgs, ent.CompactGenomes...)
212 cseqs = append(cseqs, ent.CompactSequences...)
218 if ctx.Err() != nil {
221 err = tilelib.loadCompactGenomes(cgs, variantmap, onLoadGenome)
225 err = tilelib.loadCompactSequences(cseqs, variantmap)
232 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader) (tileSeq, error) {
238 todo := make(chan jobT)
239 scanner := bufio.NewScanner(rdr)
245 buf := scanner.Bytes()
246 if len(buf) > 0 && buf[0] == '>' {
247 todo <- jobT{seqlabel, fasta}
248 seqlabel, fasta = string(buf[1:]), nil
249 log.Debugf("%s %s reading fasta", filelabel, seqlabel)
251 fasta = append(fasta, bytes.ToLower(buf)...)
254 todo <- jobT{seqlabel, fasta}
256 type foundtag struct {
261 found := make([]foundtag, 2000000)
262 path := make([]tileLibRef, 2000000)
265 skippedSequences := 0
266 for job := range todo {
267 if len(job.fasta) == 0 {
269 } else if strings.Contains(job.label, "_") {
273 log.Debugf("%s %s tiling", filelabel, job.label)
276 tilelib.taglib.FindAll(job.fasta, func(tagid tagID, pos, taglen int) {
277 found = append(found, foundtag{pos: pos, tagid: tagid, taglen: taglen})
279 totalFoundTags += len(found)
283 last := foundtag{tagid: -1}
285 keep := longestIncreasingSubsequence(len(found), func(i int) int { return int(found[i].tagid) })
286 for i, x := range keep {
289 skipped = len(found) - len(keep)
290 found = found[:len(keep)]
292 for i, f := range found {
293 log.Tracef("%s %s found[%d] == %#v", filelabel, job.label, i, f)
295 path = append(path, tilelib.getRef(last.tagid, job.fasta[last.pos:f.pos+f.taglen]))
302 path = append(path, tilelib.getRef(last.tagid, job.fasta[last.pos:]))
304 log.Warnf("%s %s no tags found", filelabel, job.label)
307 pathcopy := make([]tileLibRef, len(path))
309 ret[job.label] = pathcopy
310 log.Debugf("%s %s tiled with path len %d, skipped %d", filelabel, job.label, len(path), skipped)
311 totalPathLen += len(path)
313 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)
314 return ret, scanner.Err()
317 func (tilelib *tileLibrary) Len() int {
319 defer tilelib.mtx.Unlock()
320 return tilelib.variants
323 // Return a tileLibRef for a tile with the given tag and sequence,
324 // adding the sequence to the library if needed.
325 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte) tileLibRef {
326 if !tilelib.includeNoCalls {
327 for _, b := range seq {
328 if b != 'a' && b != 'c' && b != 'g' && b != 't' {
329 // return "tile not found" if seq has any
331 return tileLibRef{Tag: tag}
336 // if tilelib.seq == nil {
337 // tilelib.seq = map[[blake2b.Size]byte][]byte{}
339 if tilelib.variant == nil && tilelib.taglib != nil {
340 tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
342 if int(tag) >= len(tilelib.variant) {
343 // If we haven't seen the tag library yet (as in a
344 // merge), tilelib.taglib.Len() is zero. We can still
345 // behave correctly, we just need to expand the
346 // tilelib.variant slice as needed.
347 if int(tag) >= cap(tilelib.variant) {
348 // Allocate 2x capacity.
349 newslice := make([][][blake2b.Size256]byte, int(tag)+1, (int(tag)+1)*2)
350 copy(newslice, tilelib.variant)
351 tilelib.variant = newslice[:int(tag)+1]
353 // Use previously allocated capacity, avoiding
355 tilelib.variant = tilelib.variant[:int(tag)+1]
358 seqhash := blake2b.Sum256(seq)
359 for i, varhash := range tilelib.variant[tag] {
360 if varhash == seqhash {
362 return tileLibRef{Tag: tag, Variant: tileVariantID(i + 1)}
366 tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
367 // tilelib.seq[seqhash] = append([]byte(nil), seq...)
368 variant := tileVariantID(len(tilelib.variant[tag]))
371 if tilelib.encoder != nil {
372 tilelib.encoder.Encode(LibraryEntry{
373 TileVariants: []TileVariant{{
381 return tileLibRef{Tag: tag, Variant: variant}