This repository has been archived by the owner on Mar 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
optimize_guides.go
249 lines (184 loc) · 7.63 KB
/
optimize_guides.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package main
import (
"bufio"
"io"
"os"
"fmt"
"strings"
"strconv"
"math/rand"
"sort"
"github.com/shenwei356/bio/seqio/fastx"
"regexp"
)
func checkError(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
// updateCounts updates how many reads each guide is currently
// hitting. Reads that have been covered by other guides are not
// counted.
func updateCounts(guidesToReads [][]int, coverage []int, counts []int, coverageNum int) {
for guideIdx, guide := range guidesToReads {
c := 0
if counts[guideIdx] < 0 {
// This guide has been used already, so don't update its count
continue
}
for _, read := range guide {
if coverage[read] < coverageNum {
c++
}
}
counts[guideIdx] = c
}
}
func coverReadsGreedy(guidesToReads [][]int, coverage []int, counts []int, maxGuides int, coverageNum int) ([]int, []int) {
guides := make([]int, maxGuides)
// How many new counts each chosen guide covers that weren't
// covered by a previous guide
countsChosen := make([]int, maxGuides)
for i := 0; i < maxGuides; i++ {
// Greedy: Find guide with largest count
maxCount := -1
maxCountIdx := -1
for guideIdx, guideCount := range counts {
if guideCount > maxCount {
maxCount = guideCount
maxCountIdx = guideIdx
}
}
// for calculating statistics about how many reads our guide
// set is covering, we only want to count reads for this guide
// that haven't already been counted for another guide
numUncoveredReads := 0
// take this guide!
guides[i] = maxCountIdx
for _, read := range guidesToReads[maxCountIdx] {
if coverage[read] == 0 {
numUncoveredReads += 1
}
coverage[read] += 1
}
countsChosen[i] = numUncoveredReads
// don't reuse the guide we just used
counts[maxCountIdx] = -1
updateCounts(guidesToReads, coverage, counts, coverageNum)
if i % 20 == 0 {
fmt.Fprintf(os.Stderr, "Found %d guides...\n", i + 1)
}
}
fmt.Fprintf(os.Stderr, "Found %d guides...\n", len(guides))
return guides, countsChosen
}
func printUsage() {
os.Stderr.WriteString("go run optimize_guides.go [input sites -> reads map] [number of crispr sites to return] [number of times to cover each read] [optional: reads file to output representative reads along with guides]\n")
}
func main() {
if len(os.Args) < 4 {
os.Stderr.WriteString("Error: Not enough input arguments\n")
printUsage()
os.Exit(-1);
}
inputFilename := os.Args[1]
numSites, _ := strconv.Atoi(os.Args[2])
coverageNum, _ := strconv.Atoi(os.Args[3])
// optionally specify reads file
var readsFile string = ""
if len(os.Args) == 5 {
readsFile = os.Args[4]
}
fmt.Fprintf(os.Stderr, "Choosing the %d sites from %s that will cover the most reads...\n", numSites, inputFilename)
if file, err := os.Open(inputFilename); err == nil {
defer file.Close()
reader := bufio.NewReader(file)
var guidesToReads [][]int
var sites []string
maxNumReads := 0
line, err := reader.ReadString('\n')
var totalNumReadsRegExp = regexp.MustCompile(`Total.*?(\d+)`)
if len(totalNumReadsRegExp.FindStringSubmatch(line)) == 0 {
fmt.Fprintf(os.Stderr, "Error: Input file %s doesn't list total number of reads on the first line. Re-create this file with crispr_sites -r\n", inputFilename)
os.Exit(-1)
}
var totalNumReads, _ = strconv.Atoi(totalNumReadsRegExp.FindStringSubmatch(line)[1])
fmt.Fprintf(os.Stderr, "Total number of reads: %d\n", totalNumReads)
line, err = reader.ReadString('\n')
for err == nil {
readsStr := strings.Fields(line)
sites = append(sites, readsStr[0])
readsStr = readsStr[1:]
reads := make([]int, 0)
for _, rStr := range readsStr {
r, _ := strconv.Atoi(rStr)
reads = append(reads, r)
}
if len(reads) > maxNumReads {
maxNumReads = len(reads)
}
guidesToReads = append(guidesToReads, reads)
line, err = reader.ReadString('\n')
}
fmt.Fprintf(os.Stderr, "Largest # of reads hit by a single guide is %d\n", maxNumReads)
coverage := make([]int, totalNumReads + 1)
counts := make([]int, len(guidesToReads))
updateCounts(guidesToReads, coverage, counts, coverageNum)
guides, countsChosen := coverReadsGreedy(guidesToReads, coverage, counts, numSites, coverageNum)
readIdxToSeq := make(map[int] string)
guideIdxToReadIdx := make([]int, numSites)
fmt.Printf("Total number of reads: %d\n", totalNumReads)
if len(readsFile) > 0 {
// collect a random read for each guide we've designed
for i, g := range guides {
guideIdxToReadIdx[i] = guidesToReads[g][rand.Intn(len(guidesToReads[g]))]
}
// Now we'll find the reads we chose in the specified
// input FASTA file. Since this can be a big file, we'll
// sort the read indices we need to lookup and find them
// sequentially
sortedReads := make([]int, len(guideIdxToReadIdx))
copy(sortedReads, guideIdxToReadIdx)
sort.Ints(sortedReads)
nextReadIdx := 0
reader, err := fastx.NewDefaultReader(readsFile)
checkError(err)
// Reads in normally formatted fasta files (that begin
// with a >chromosome comment) are 1-indexed
i := 1
for {
record, err := reader.Read()
if err != nil {
if err == io.EOF {
break
}
checkError(err)
break
}
if i == sortedReads[nextReadIdx] {
nextReadIdx += 1
readIdxToSeq[i] = fmt.Sprintf("%s", record.Seq.Seq)
if nextReadIdx >= numSites {
break
}
}
i += 1
}
fmt.Printf("Guide,Site,Number of reads covered by site,cumulative number of reads covered,cumulative percent of reads covered,random read hit by this guide\n");
} else {
fmt.Printf("Guide,Site,Number of reads covered by site,cumulative number of reads covered,cumulative percent of reads covered\n");
}
cumulativeReadsCovered := 0
for i, g := range guides {
cumulativeReadsCovered += countsChosen[i]
if len(readsFile) > 0 {
fmt.Printf("%d,%s,%d,%d,%.2f,%s\n", i + 1, sites[g], countsChosen[i], cumulativeReadsCovered, float64(cumulativeReadsCovered)/float64(totalNumReads) * 100, readIdxToSeq[guideIdxToReadIdx[i]]);
} else {
fmt.Printf("%d,%s,%d,%d,%.2f\n", i + 1, sites[g], countsChosen[i], cumulativeReadsCovered, float64(cumulativeReadsCovered)/float64(totalNumReads) * 100);
}
}
fmt.Fprintf(os.Stderr, "%d sites covered %d reads, # reads: %d\n", numSites, cumulativeReadsCovered, totalNumReads)
}
os.Stderr.Sync()
}