11 "golang.org/x/crypto/blake2b"
14 type tileVariantID uint16 // 1-based
16 type tileLibRef struct {
21 type tileSeq map[string][]tileLibRef
23 func (tseq tileSeq) Variants() []tileVariantID {
25 for _, refs := range tseq {
26 for _, ref := range refs {
27 if maxtag < int(ref.tag) {
32 vars := make([]tileVariantID, maxtag+1)
33 for _, refs := range tseq {
34 for _, ref := range refs {
35 vars[int(ref.tag)] = ref.variant
41 type tileLibrary struct {
43 variant [][][blake2b.Size256]byte
45 // seq map[[blake2b.Size]byte][]byte
51 func (tilelib *tileLibrary) TileFasta(filelabel string, rdr io.Reader) (tileSeq, error) {
57 todo := make(chan jobT)
58 scanner := bufio.NewScanner(rdr)
64 buf := scanner.Bytes()
65 if len(buf) == 0 || buf[0] == '>' {
66 todo <- jobT{seqlabel, fasta}
67 seqlabel, fasta = string(buf[1:]), nil
68 log.Printf("%s %s reading fasta", filelabel, seqlabel)
70 fasta = append(fasta, bytes.ToLower(buf)...)
73 todo <- jobT{seqlabel, fasta}
75 path := make([]tileLibRef, 2000000)
76 for job := range todo {
77 if len(job.fasta) == 0 || strings.Contains(job.label, "_") {
80 log.Printf("%s %s tiling", filelabel, job.label)
82 tilestart := -1 // position in fasta of tile that ends here
83 tiletagid := tagID(-1) // tag id starting tile that ends here
84 tilelib.taglib.FindAll(job.fasta, func(id tagID, pos, taglen int) {
86 path = append(path, tilelib.getRef(tiletagid, job.fasta[tilestart:pos+taglen]))
92 path = append(path, tilelib.getRef(tiletagid, job.fasta[tilestart:]))
94 pathcopy := make([]tileLibRef, len(path))
96 ret[job.label] = pathcopy
97 log.Printf("%s %s tiled with path len %d", filelabel, job.label, len(path))
99 return ret, scanner.Err()
102 func (tilelib *tileLibrary) Len() int {
104 defer tilelib.mtx.Unlock()
105 return tilelib.variants
108 // Return a tileLibRef for a tile with the given tag and sequence,
109 // adding the sequence to the library if needed.
110 func (tilelib *tileLibrary) getRef(tag tagID, seq []byte) tileLibRef {
111 for _, b := range seq {
112 if b != 'a' && b != 'c' && b != 'g' && b != 't' {
113 // return "tile not found" if seq has any
115 return tileLibRef{tag: tag}
119 defer tilelib.mtx.Unlock()
120 // if tilelib.seq == nil {
121 // tilelib.seq = map[[blake2b.Size]byte][]byte{}
123 if tilelib.variant == nil {
124 tilelib.variant = make([][][blake2b.Size256]byte, tilelib.taglib.Len())
126 seqhash := blake2b.Sum256(seq)
127 for i, varhash := range tilelib.variant[tag] {
128 if varhash == seqhash {
129 return tileLibRef{tag: tag, variant: tileVariantID(i + 1)}
133 tilelib.variant[tag] = append(tilelib.variant[tag], seqhash)
134 // tilelib.seq[seqhash] = append([]byte(nil), seq...)
135 return tileLibRef{tag: tag, variant: tileVariantID(len(tilelib.variant[tag]))}