10 "golang.org/x/crypto/blake2b"
13 type tileVariantID int32 // 1-based
15 type tileLibRef struct {
20 type tileSeq map[string][]tileLibRef
22 type tileLibrary struct {
24 variant [][][blake2b.Size]byte
26 // seq map[[blake2b.Size]byte][]byte
32 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader) (tileSeq, error) {
38 todo := make(chan jobT)
39 scanner := bufio.NewScanner(rdr)
45 buf := scanner.Bytes()
46 if len(buf) == 0 || buf[0] == '>' {
47 todo <- jobT{seqlabel, fasta}
48 seqlabel, fasta = string(buf[1:]), nil
49 log.Printf("%s %s reading fasta", filelabel, seqlabel)
51 fasta = append(fasta, bytes.ToLower(buf)...)
54 todo <- jobT{seqlabel, fasta}
56 for job := range todo {
57 if len(job.fasta) == 0 {
60 log.Printf("%s %s tiling", filelabel, job.label)
62 tilestart := -1 // position in fasta of tile that ends here
63 tiletagid := tagID(-1) // tag id starting tile that ends here
64 tilelib.taglib.FindAll(job.fasta, func(id tagID, pos int) {
66 path = append(path, tilelib.getRef(tiletagid, job.fasta[tilestart:pos]))
72 path = append(path, tilelib.getRef(tiletagid, job.fasta[tilestart:]))
75 log.Printf("%s %s tiled with path len %d", filelabel, job.label, len(path))
77 return ret, scanner.Err()
80 func (tilelib *tileLibrary) Len() int {
82 defer tilelib.mtx.Unlock()
83 return tilelib.variants
86 // Return a tileLibRef for a tile with the given tag and sequence,
87 // adding the sequence to the library if needed.
88 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte) tileLibRef {
89 for _, b := range seq {
90 if b != 'a' && b != 'c' && b != 'g' && b != 't' {
91 // return "tile not found" if seq has any
93 return tileLibRef{tag: tag}
97 defer tilelib.mtx.Unlock()
98 // if tilelib.seq == nil {
99 // tilelib.seq = map[[blake2b.Size]byte][]byte{}
101 if tilelib.variant == nil {
102 tilelib.variant = make([][][blake2b.Size]byte, tilelib.taglib.Len())
104 hash, err := blake2b.New(32, nil)
108 _, err = hash.Write(seq)
112 var seqhash [blake2b.Size]byte
113 copy(seqhash[:], hash.Sum(nil))
114 for i, varhash := range tilelib.variant[tag] {
115 if varhash == seqhash {
116 return tileLibRef{tag: tag, variant: tileVariantID(i + 1)}
120 tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
121 // tilelib.seq[seqhash] = append([]byte(nil), seq...)
122 return tileLibRef{tag: tag, variant: tileVariantID(len(tilelib.variant[tag]))}