summaryrefslogtreecommitdiff
path: root/tests/src/JIT/Performance/CodeQuality/BenchmarksGame/k-nucleotide/k-nucleotide-best.cs
blob: 990417d311fb180a5960766a1151a277353f39b2 (plain)
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

// Adapted from k-nucleotide C# .NET Core #9 program
// http://benchmarksgame.alioth.debian.org/u64q/program.php?test=knucleotide&lang=csharpcore&id=9
// Best-scoring C# .NET Core version as of 2017-09-01

/* The Computer Language Benchmarks Game
   http://benchmarksgame.alioth.debian.org/
 
   submitted by Josh Goldfoot
   Modified to reduce memory and do more in parallel by Anthony Lloyd
 */

using System;
using System.IO;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;

namespace BenchmarksGame
{
    class Wrapper { public int v = 1; }
    public static class KNucleotide
    {
        const int BLOCK_SIZE = 1024 * 1024 * 8;
        static List<byte[]> threeBlocks = new List<byte[]>();
        static int threeStart, threeEnd;
        static byte[] tonum = new byte[256];
        static char[] tochar = new char[] { 'A', 'C', 'G', 'T' };

        static int read(Stream stream, byte[] buffer, int offset, int count)
        {
            var bytesRead = stream.Read(buffer, offset, count);
            return bytesRead == count ? offset + count
                 : bytesRead == 0 ? offset
                 : read(stream, buffer, offset + bytesRead, count - bytesRead);
        }

        static int find(byte[] buffer, byte[] toFind, int i, ref int matchIndex)
        {
            if (matchIndex == 0)
            {
                i = Array.IndexOf(buffer, toFind[0], i);
                if (i == -1) return -1;
                matchIndex = 1;
                return find(buffer, toFind, i + 1, ref matchIndex);
            }
            else
            {
                int bl = buffer.Length, fl = toFind.Length;
                while (i < bl && matchIndex < fl)
                {
                    if (buffer[i++] != toFind[matchIndex++])
                    {
                        matchIndex = 0;
                        return find(buffer, toFind, i, ref matchIndex);
                    }
                }
                return matchIndex == fl ? i : -1;
            }
        }

        static void loadThreeData()
        {
            var stream = Console.OpenStandardInput();

            // find three sequence
            int matchIndex = 0;
            var toFind = new[] { (byte)'>', (byte)'T', (byte)'H', (byte)'R', (byte)'E', (byte)'E' };
            var buffer = new byte[BLOCK_SIZE];
            do
            {
                threeEnd = read(stream, buffer, 0, BLOCK_SIZE);
                threeStart = find(buffer, toFind, 0, ref matchIndex);
            } while (threeStart == -1);

            // Skip to end of line
            matchIndex = 0;
            toFind = new[] { (byte)'\n' };
            threeStart = find(buffer, toFind, threeStart, ref matchIndex);
            while (threeStart == -1)
            {
                threeEnd = read(stream, buffer, 0, BLOCK_SIZE);
                threeStart = find(buffer, toFind, 0, ref matchIndex);
            }
            threeBlocks.Add(buffer);

            if (threeEnd != BLOCK_SIZE) // Needs to be at least 2 blocks
            {
                var bytes = threeBlocks[0];
                for (int i = threeEnd; i < bytes.Length; i++)
                    bytes[i] = 255;
                threeEnd = 0;
                threeBlocks.Add(Array.Empty<byte>());
                return;
            }

            // find next seq or end of input
            matchIndex = 0;
            toFind = new[] { (byte)'>' };
            threeEnd = find(buffer, toFind, threeStart, ref matchIndex);
            while (threeEnd == -1)
            {
                buffer = new byte[BLOCK_SIZE];
                var bytesRead = read(stream, buffer, 0, BLOCK_SIZE);
                threeEnd = bytesRead == BLOCK_SIZE ? find(buffer, toFind, 0, ref matchIndex)
                            : bytesRead;
                threeBlocks.Add(buffer);
            }

            if (threeStart + 18 > BLOCK_SIZE) // Key needs to be in the first block
            {
                byte[] block0 = threeBlocks[0], block1 = threeBlocks[1];
                Buffer.BlockCopy(block0, threeStart, block0, threeStart - 18, BLOCK_SIZE - threeStart);
                Buffer.BlockCopy(block1, 0, block0, BLOCK_SIZE - 18, 18);
                for (int i = 0; i < 18; i++) block1[i] = 255;
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static void check(Dictionary<long, Wrapper> dict, ref long rollingKey, byte nb, long mask)
        {
            if (nb == 255) return;
            rollingKey = ((rollingKey & mask) << 2) | nb;
            Wrapper w;
            if (dict.TryGetValue(rollingKey, out w))
                w.v++;
            else
                dict[rollingKey] = new Wrapper();
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static void checkEnding(Dictionary<long, Wrapper> dict, ref long rollingKey, byte b, byte nb, long mask)
        {
            if (nb == b)
            {
                Wrapper w;
                if (dict.TryGetValue(rollingKey, out w))
                    w.v++;
                else
                    dict[rollingKey] = new Wrapper();
                rollingKey = ((rollingKey << 2) | nb) & mask;
            }
            else if (nb != 255)
            {
                rollingKey = ((rollingKey << 2) | nb) & mask;
            }
        }

        static Task<string> count(int l, long mask, Func<Dictionary<long, Wrapper>, string> summary)
        {
            return Task.Run(() =>
            {
                long rollingKey = 0;
                var firstBlock = threeBlocks[0];
                var start = threeStart;
                while (--l > 0) rollingKey = (rollingKey << 2) | firstBlock[start++];
                var dict = new Dictionary<long, Wrapper>();
                for (int i = start; i < firstBlock.Length; i++)
                    check(dict, ref rollingKey, firstBlock[i], mask);

                int lastBlockId = threeBlocks.Count - 1;
                for (int bl = 1; bl < lastBlockId; bl++)
                {
                    var bytes = threeBlocks[bl];
                    for (int i = 0; i < bytes.Length; i++)
                        check(dict, ref rollingKey, bytes[i], mask);
                }

                var lastBlock = threeBlocks[lastBlockId];
                for (int i = 0; i < threeEnd; i++)
                    check(dict, ref rollingKey, lastBlock[i], mask);
                return summary(dict);
            });
        }

        static Dictionary<long, Wrapper> countEnding(int l, long mask, byte b)
        {
            long rollingKey = 0;
            var firstBlock = threeBlocks[0];
            var start = threeStart;
            while (--l > 0) rollingKey = (rollingKey << 2) | firstBlock[start++];
            var dict = new Dictionary<long, Wrapper>();
            for (int i = start; i < firstBlock.Length; i++)
                checkEnding(dict, ref rollingKey, b, firstBlock[i], mask);

            int lastBlockId = threeBlocks.Count - 1;
            for (int bl = 1; bl < lastBlockId; bl++)
            {
                var bytes = threeBlocks[bl];
                for (int i = 0; i < bytes.Length; i++)
                    checkEnding(dict, ref rollingKey, b, bytes[i], mask);
            }

            var lastBlock = threeBlocks[lastBlockId];
            for (int i = 0; i < threeEnd; i++)
                checkEnding(dict, ref rollingKey, b, lastBlock[i], mask);
            return dict;
        }

        static Task<string> count4(int l, long mask, Func<Dictionary<long, Wrapper>, string> summary)
        {
            return Task.Factory.ContinueWhenAll(
                new[] {
                Task.Run(() => countEnding(l, mask, 0)),
                Task.Run(() => countEnding(l, mask, 1)),
                Task.Run(() => countEnding(l, mask, 2)),
                Task.Run(() => countEnding(l, mask, 3))
                }
                , dicts =>
                {
                    var d = new Dictionary<long, Wrapper>(dicts.Sum(i => i.Result.Count));
                    for (int i = 0; i < dicts.Length; i++)
                        foreach (var kv in dicts[i].Result)
                            d[(kv.Key << 2) | (long)i] = kv.Value;
                    return summary(d);
                });
        }

        static string writeFrequencies(Dictionary<long, Wrapper> freq, int fragmentLength)
        {
            var sb = new StringBuilder();
            double percent = 100.0 / freq.Values.Sum(i => i.v);
            foreach (var kv in freq.OrderByDescending(i => i.Value.v))
            {
                var keyChars = new char[fragmentLength];
                var key = kv.Key;
                for (int i = keyChars.Length - 1; i >= 0; --i)
                {
                    keyChars[i] = tochar[key & 0x3];
                    key >>= 2;
                }
                sb.Append(keyChars);
                sb.Append(" ");
                sb.AppendLine((kv.Value.v * percent).ToString("F3"));
            }
            return sb.ToString();
        }

        static string writeCount(Dictionary<long, Wrapper> dictionary, string fragment)
        {
            long key = 0;
            for (int i = 0; i < fragment.Length; ++i)
                key = (key << 2) | tonum[fragment[i]];
            Wrapper w;
            var n = dictionary.TryGetValue(key, out w) ? w.v : 0;
            return string.Concat(n.ToString(), "\t", fragment);
        }

        public static void Main(string[] args)
        {
            tonum['c'] = 1; tonum['C'] = 1;
            tonum['g'] = 2; tonum['G'] = 2;
            tonum['t'] = 3; tonum['T'] = 3;
            tonum['\n'] = 255; tonum['>'] = 255; tonum[255] = 255;

            loadThreeData();

            Parallel.ForEach(threeBlocks, bytes =>
            {
                for (int i = 0; i < bytes.Length; i++)
                    bytes[i] = tonum[bytes[i]];
            });

            var task18 = count4(18, 34359738367, d => writeCount(d, "GGTATTTTAATTTATAGT"));
            var task12 = count4(12, 8388607, d => writeCount(d, "GGTATTTTAATT"));
            var task6 = count(6, 0b1111111111, d => writeCount(d, "GGTATT"));
            var task4 = count(4, 0b111111, d => writeCount(d, "GGTA"));
            var task3 = count(3, 0b1111, d => writeCount(d, "GGT"));
            var task2 = count(2, 0b11, d => writeFrequencies(d, 2));
            var task1 = count(1, 0, d => writeFrequencies(d, 1));

            Console.Out.WriteLineAsync(task1.Result);
            Console.Out.WriteLineAsync(task2.Result);
            Console.Out.WriteLineAsync(task3.Result);
            Console.Out.WriteLineAsync(task4.Result);
            Console.Out.WriteLineAsync(task6.Result);
            Console.Out.WriteLineAsync(task12.Result);
            Console.Out.WriteLineAsync(task18.Result);
        }
    }
}