-
Notifications
You must be signed in to change notification settings - Fork 143
/
Copy path7.go
331 lines (276 loc) · 6.99 KB
/
7.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/* The Computer Language Benchmarks Game
* https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
*
* contributed by Mark van Weert
* based on Go#6 C++#2
*/
package main
import (
"bufio"
"fmt"
"math"
"os"
"runtime"
"sort"
"strings"
"sync"
)
var toNum = strings.NewReplacer("A", string(0), "C", string(1), "T", string(2), "G", string(3))
var toChar = []byte{'A', 'C', 'T', 'G'}
func main() {
dna := input()
out := bufio.NewWriter(os.Stdout)
defer out.Flush()
fmt.Fprintln(out, WriteFrequencies(dna, 1))
fmt.Fprintln(out, WriteFrequencies(dna, 2))
fmt.Fprintln(out, WriteCount(dna, "GGT"))
fmt.Fprintln(out, WriteCount(dna, "GGTA"))
fmt.Fprintln(out, WriteCount(dna, "GGTATT"))
fmt.Fprintln(out, WriteCount(dna, "GGTATTTTAATT"))
fmt.Fprintln(out, WriteCount(dna, "GGTATTTTAATTTATAGT"))
}
// input returns the transformed data
func input() []byte {
fileName := "25000_in"
if len(os.Args) > 1 {
fileName = os.Args[1]
}
if f, err := os.Open(fileName); err == nil {
defer f.Close()
scanner := bufio.NewScanner(f)
data := readStdin(scanner)
// A = 0, C = 1, T = 2, G = 3
for idx := range data {
data[idx] = data[idx] >> 1 & 3
}
return data
} else {
panic(err)
}
}
// readStdin returns the data marked with >THREE from stdin
func readStdin(scanner *bufio.Scanner) []byte {
var lineCount int
for scanner.Scan() {
// Keep reading until we encounter the start marker >THREE
line := scanner.Text()
if len(line) == 0 {
continue
}
lineCount++
if line[0] == '>' && strings.HasPrefix(string(line), ">THREE") {
data := make([]byte, 0, lineCount*61)
for scanner.Scan() {
line := scanner.Text()
if len(line) > 0 {
data = append(data, line...)
}
}
return data
}
}
return []byte{}
}
// WriteFrequencies returns the frequencies of the nucleotides with the given length
func WriteFrequencies(data []byte, size int) string {
// Get counts
counts := startCount32(data, size)
// Store the map keys and values in a struct to sort them
type kv struct {
Key uint32
Value int
}
var sortedCounts []kv
for k, v := range counts {
sortedCounts = append(sortedCounts, kv{k, *v})
}
sort.Slice(sortedCounts, func(i, j int) bool {
return sortedCounts[i].Value > sortedCounts[j].Value
})
sum := float32(len(data) - size + 1)
var result string
for _, count := range sortedCounts {
result += fmt.Sprintf("%v %.3f\n", decompress32(count.Key, size), 100.0*float32(count.Value)/sum)
}
return result
}
// WriteCount returns the number of given nucleotides in the data
func WriteCount(data []byte, nucleotide string) string {
size := len(nucleotide)
if len(nucleotide) <= 16 {
// Get counts nucleotide key can fit in an uint32
counts := startCount32(data, size)
key := compress32([]byte(toNum.Replace(nucleotide)))
count := counts[key]
if count == nil {
count = new(int)
}
return fmt.Sprintf("%v\t%v", *count, nucleotide)
} else {
// Get counts for longer nucleotides
counts := startCount64(data, size)
key := compress64([]byte(toNum.Replace(nucleotide)))
count := counts[key]
if count == nil {
count = new(int)
}
return fmt.Sprintf("%v\t%v", *count, nucleotide)
}
}
func startCount32(data []byte, size int) map[uint32]*int {
maps := make([]map[uint32]*int, runtime.NumCPU())
wg := sync.WaitGroup{}
// Create a map for each goroutine we will spawn
for i := 0; i < len(maps); i++ {
maps[i] = make(map[uint32]*int)
wg.Add(1)
go calc32(data, maps[i], i, size, &wg)
}
wg.Wait()
// Add counts from all goroutines to the first map
m0 := maps[0]
for i := 1; i < len(maps); i++ {
for i2, val := range maps[i] {
if val == nil {
continue
}
if m0[i2] == nil {
m0[i2] = new(int)
}
*m0[i2] += *val
}
}
return m0
}
func startCount64(data []byte, size int) map[uint64]*int {
maps := make([]map[uint64]*int, runtime.NumCPU())
wg := sync.WaitGroup{}
// Create a map for each goroutine we will spawn
for i := 0; i < len(maps); i++ {
maps[i] = make(map[uint64]*int)
wg.Add(1)
go calc64(data, maps[i], i, size, &wg)
}
wg.Wait()
// Add counts from all goroutines to the first map
m0 := maps[0]
for i := 1; i < len(maps); i++ {
for i2, val := range maps[i] {
if val == nil {
continue
}
if m0[i2] == nil {
m0[i2] = new(int)
}
*m0[i2] += *val
}
}
return m0
}
func calc32(data []byte, result map[uint32]*int, begin int, size int, wg *sync.WaitGroup) {
var key uint32
goroutineCount := uint(runtime.NumCPU())
// Init key
for i := 0; i < size; i++ {
key <<= 2
key |= uint32(data[i+begin])
}
// Create a map to do the counts in.
// We don't use the map we are passed but instead return a copy of this
p := new(int)
*p++
result[key] = p
nsize := uint(size)
if goroutineCount < nsize {
nsize = goroutineCount
}
mask := ^uint32(math.MaxUint32 << uint(2*size))
start := uint(begin) + goroutineCount
end := uint(len(data) + 1 - size)
for idx := start; idx < end; idx += goroutineCount {
// Update the key with 1 byte at a time
for i := uint(0); i < nsize; i++ {
key <<= 2
key |= uint32(data[idx+i])
}
// Mask out excess information
key &= mask
// Get pointer to the count for this key from the map
// For a low number of different keys using a map with
// pointers is faster than just using a value map and do: m[key]++
p, ok := result[key]
if !ok {
p = new(int)
result[key] = p
}
*p++
}
// Signal done
wg.Done()
}
func calc64(data []byte, result map[uint64]*int, begin int, size int, wg *sync.WaitGroup) {
var key uint64
goroutineCount := uint(runtime.NumCPU())
// Init key
for i := 0; i < size; i++ {
key <<= 2
key |= uint64(data[i+begin])
}
// Create a map to do the counts in. We don't use the map
// we are passed but instead return a copy of this
p := new(int)
*p++
result[key] = p
nsize := uint(size)
if goroutineCount < nsize {
nsize = goroutineCount
}
mask := ^uint64(math.MaxUint64 << uint(2*size))
start := uint(begin) + goroutineCount
end := uint(len(data) + 1 - size)
for idx := start; idx < end; idx += goroutineCount {
// Update the key with 1 byte at a time
if uint(len(data)) < idx+nsize {
continue
}
for i := uint(0); i < nsize; i++ {
key <<= 2
key |= uint64(data[idx+i])
}
// Mask out excess information
key &= mask
// Get pointer to the count for this key from the map
// For a low number of different keys using a map with
// pointers is faster than just using a value map and do: m[key]++
p, ok := result[key]
if !ok {
p = new(int)
result[key] = p
}
*p++
}
// Signal done
wg.Done()
}
func compress64(sequence []byte) uint64 {
var num uint64
for _, char := range sequence {
num = num<<2 | uint64(char)
}
return num
}
func compress32(sequence []byte) uint32 {
var num uint32
for _, char := range sequence {
num = num<<2 | uint32(char)
}
return num
}
func decompress32(num uint32, length int) string {
var sequence = make([]byte, length)
for i := 0; i < length; i++ {
sequence[length-i-1] = toChar[byte(num&3)]
num = num >> 2
}
return string(sequence)
}