summaryrefslogtreecommitdiff
path: root/tests/src/JIT/Performance/CodeQuality/BenchmarksGame/k-nucleotide/k-nucleotide-1.cs
blob: 449baa2da287354d041161f61c9e485367451331 (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
// 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 program
// http://benchmarksgame.alioth.debian.org/u64q/program.php?test=knucleotide&lang=csharpcore&id=1
// aka (as of 2017-09-01) rev 1.2 of https://alioth.debian.org/scm/viewvc.php/benchmarksgame/bench/knucleotide/knucleotide.csharp?root=benchmarksgame&view=log
// Best-scoring single-threaded C# .NET Core version as of 2017-09-01

/* The Computer Language Benchmarks Game
   http://benchmarksgame.alioth.debian.org/
 *
 * byte processing version using C# *3.0 idioms by Robert F. Tobler
 */

using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xunit.Performance;
using Xunit;

[assembly: OptimizeForBenchmarks]
[assembly: MeasureGCCounts]

namespace BenchmarksGame
{

    public struct ByteString : IEquatable<ByteString>
    {
        public byte[] Array;
        public int Start;
        public int Length;

        public ByteString(byte[] array, int start, int length)
        {
            Array = array; Start = start; Length = length;
        }

        public ByteString(string text)
        {
            Start = 0; Length = text.Length;
            Array = Encoding.ASCII.GetBytes(text);
        }

        public override int GetHashCode()
        {
            if (Length < 1) return 0;
            int hc = Length ^ (Array[Start] << 24); if (Length < 2) return hc;
            hc ^= Array[Start + Length - 1] << 20; if (Length < 3) return hc;
            for (int c = Length - 2; c > 0; c--)
                hc ^= Array[Start + c] << (c & 0xf);
            return hc;
        }

        public bool Equals(ByteString other)
        {
            if (Length != other.Length) return false;
            for (int i = 0; i < Length; i++)
                if (Array[Start + i] != other.Array[other.Start + i]) return false;
            return true;
        }

        public override string ToString()
        {
            return Encoding.ASCII.GetString(Array, Start, Length);
        }
    }

    public static class Extensions
    {
        public static byte[] GetBytes(this List<string> input)
        {
            int count = 0;
            for (int i = 0; i < input.Count; i++) count += input[i].Length;
            var byteArray = new byte[count];
            count = 0;
            for (int i = 0; i < input.Count; i++)
            {
                string line = input[i];
                Encoding.ASCII.GetBytes(line, 0, line.Length, byteArray, count);
                count += line.Length;
            }
            return byteArray;
        }
    }

    public class KNucleotide_1
    {

        public static int Main(string[] args)
        {
            var helpers = new TestHarnessHelpers(bigInput: false);

            using (var inputStream = helpers.GetInputStream())
            {
                if (!Bench(inputStream, helpers, true))
                {
                    return -1;
                }
            }

            return 100;
        }

        [Benchmark(InnerIterationCount = 3)]
        public static void RunBench()
        {
            var helpers = new TestHarnessHelpers(bigInput: true);
            bool ok = true;

            Benchmark.Iterate(() =>
            {
                using (var inputStream = helpers.GetInputStream())
                {
                    ok &= Bench(inputStream, helpers, false);
                }
            });
            Assert.True(ok);
        }

        static bool Bench(Stream inputStream, TestHarnessHelpers helpers, bool verbose)
        {
            string line;
            StreamReader source = new StreamReader(inputStream);
            var input = new List<string>();

            while ((line = source.ReadLine()) != null)
                if (line[0] == '>' && line.Substring(1, 5) == "THREE")
                    break;

            while ((line = source.ReadLine()) != null)
            {
                char c = line[0];
                if (c == '>') break;
                if (c != ';') input.Add(line.ToUpper());
            }

            KNucleotide kn = new KNucleotide(input.GetBytes());
            input = null;
            bool ok = true;
            for (int f = 1; f < 3; f++)
                ok &= kn.WriteFrequencies(f, helpers.expectedFrequencies[f - 1], verbose);
            int i = 0;
            foreach (var seq in
                     new[] { "GGT", "GGTA", "GGTATT", "GGTATTTTAATT",
                         "GGTATTTTAATTTATAGT"})
                ok &= kn.WriteCount(seq, helpers.expectedCountFragments[i++], verbose);

            return ok;
        }
    }

    public class KNucleotide
    {

        private class Count
        {
            public int V;
            public Count(int v) { V = v; }
        }

        private Dictionary<ByteString, Count> frequencies
            = new Dictionary<ByteString, Count>();
        private byte[] sequence;

        public KNucleotide(byte[] s) { sequence = s; }

        public bool WriteFrequencies(int length, int[] expectedCounts, bool verbose)
        {
            GenerateFrequencies(length);
            var items = new List<KeyValuePair<ByteString, Count>>(frequencies);
            items.Sort(SortByFrequencyAndCode);
            double percent = 100.0 / (sequence.Length - length + 1);
            bool ok = true;
            int i = 0;
            foreach (var item in items)
            {
                ok &= (item.Value.V == expectedCounts[i++]);
                if (verbose)
                {
                    Console.WriteLine("{0} {1:f3}",
                                item.Key.ToString(), item.Value.V * percent);
                }
            }
            if (verbose) Console.WriteLine();
            return ok;
        }

        public bool WriteCount(string fragment, int expectedCount, bool verbose)
        {
            GenerateFrequencies(fragment.Length);
            Count count;
            if (!frequencies.TryGetValue(new ByteString(fragment), out count))
                count = new Count(0);
            if (verbose) Console.WriteLine("{0}\t{1}", count.V, fragment);
            return (count.V == expectedCount);
        }

        private void GenerateFrequencies(int length)
        {
            frequencies.Clear();
            for (int frame = 0; frame < length; frame++)
                KFrequency(frame, length);
        }

        private void KFrequency(int frame, int k)
        {
            int n = sequence.Length - k + 1;
            for (int i = frame; i < n; i += k)
            {
                var key = new ByteString(sequence, i, k);
                Count count;
                if (frequencies.TryGetValue(key, out count))
                    count.V++;
                else
                    frequencies[key] = new Count(1);
            }
        }

        int SortByFrequencyAndCode(
                KeyValuePair<ByteString, Count> i0,
                KeyValuePair<ByteString, Count> i1)
        {
            int order = i1.Value.V.CompareTo(i0.Value.V);
            if (order != 0) return order;
            return i0.Key.ToString().CompareTo(i1.Key.ToString());
        }
    }
}