Commit adbe9b56 authored by HankG's avatar HankG

Merge branch '6-straight-port-knucleotide' into 'develop'

Added knucleotide straight port

Closes #6

See merge request !4
parents 63cb838c 74407473
/* The Computer Language Benchmarks Game
http://benchmarksgame.alioth.debian.org/
Based on Java version #6 by James McIlree
Contributed by Hank Grabowski
*/
import java.util.*
import java.io.*
import java.util.concurrent.*
object knucleotide {
internal fun createFragmentTasks(sequence: ByteArray, fragmentLengths: IntArray): ArrayList<Callable<MutableMap<ByteString, ByteString>>> {
val tasks = ArrayList<Callable<MutableMap<ByteString, ByteString>>>()
for (fragmentLength in fragmentLengths) {
for (index in 0..fragmentLength - 1) {
tasks.add(Callable { createFragmentMap(sequence, index, fragmentLength) })
}
}
return tasks
}
internal fun createFragmentMap(sequence: ByteArray, offset: Int, fragmentLength: Int): MutableMap<ByteString, ByteString> {
val map = HashMap<ByteString, ByteString>()
val lastIndex = sequence.size - fragmentLength + 1
var key = ByteString(fragmentLength)
var index = offset
while (index < lastIndex) {
key.calculateHash(sequence, index)
val fragment = map[key]
if (fragment != null) {
fragment.count++
} else {
map.put(key, key)
key = ByteString(fragmentLength)
}
index += fragmentLength
}
return map
}
// Destructive!
internal fun sumTwoMaps(map1: MutableMap<ByteString, ByteString>, map2: Map<ByteString, ByteString>): Map<ByteString, ByteString> {
for ((key, value) in map2) {
val sum = map1[key]
if (sum != null)
sum.count += value.count
else
map1.put(key, value)
}
return map1
}
internal fun writeFrequencies(totalCount: Float, frequencies: Map<ByteString, ByteString>): String {
val list = TreeSet(frequencies.values)
val sb = StringBuilder()
for (k in list)
sb.append(String.format("%s %.3f\n", k.toString().toUpperCase(), k.count.toFloat() * 100.0f / totalCount))
return sb.append('\n').toString()
}
@Throws(Exception::class)
internal fun writeCount(futures: MutableList<Future<MutableMap<ByteString, ByteString>>>, nucleotideFragment: String): String {
val key = ByteString(nucleotideFragment.length)
key.calculateHash(nucleotideFragment.toByteArray(), 0)
var count = 0
for (future in futures) {
val temp = future.get()[key]
if (temp != null) count += temp.count
}
return count.toString() + "\t" + nucleotideFragment.toUpperCase() + '\n'
}
@Throws(Exception::class)
@JvmStatic
fun main(args: Array<String>) {
var line: String = ""
val `in` = BufferedReader(InputStreamReader(System.`in`))
while ({line = `in`.readLine(); line}() != null) {
if (line.startsWith(">THREE")) break
}
val baos = ByteArrayOutputStream()
var bytes = ByteArray(100)
while ({line = `in`.readLine()}() != null) {
if (line.length > bytes.size)
bytes = ByteArray(line.length)
var i: Int
i = 0
while (i < line.length) {
bytes[i] = line[i].toByte()
i++
}
baos.write(bytes, 0, i)
}
val sequence = baos.toByteArray()
val pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())
val fragmentLengths = intArrayOf(1, 2, 3, 4, 6, 12, 18)
val futures = pool.invokeAll(createFragmentTasks(sequence, fragmentLengths))
pool.shutdown()
val sb = StringBuilder()
sb.append(writeFrequencies(sequence.size.toFloat(), futures[0].get()))
sb.append(writeFrequencies((sequence.size - 1).toFloat(), sumTwoMaps(futures[1].get(), futures[2].get())))
val nucleotideFragments = arrayOf("ggt", "ggta", "ggtatt", "ggtattttaatt", "ggtattttaatttatagt")
for (nucleotideFragment in nucleotideFragments) {
sb.append(writeCount(futures, nucleotideFragment))
}
print(sb.toString())
}
internal class ByteString(size: Int) : Comparable<ByteString> {
var hash: Int = 0
var count = 1
val bytes: ByteArray
init {
bytes = ByteArray(size)
}
fun calculateHash(k: ByteArray, offset: Int) {
var temp = 0
for (i in bytes.indices) {
val b = k[offset + i]
bytes[i] = b
temp = temp * 31 + b
}
hash = temp
}
override fun hashCode(): Int {
return hash
}
override fun equals(obj: Any?): Boolean {
return Arrays.equals(bytes, (obj as ByteString).bytes)
}
override fun compareTo(other: ByteString): Int {
return other.count - count
}
override fun toString(): String {
return String(bytes)
}
}
}
......@@ -70,6 +70,7 @@ onlydirs =
binarytrees
chameneosredux
fannkuchredux
knucleotide
......
/* The Computer Language Benchmarks Game
http://benchmarksgame.alioth.debian.org/
contributed by James McIlree
ByteString code thanks to Matthieu Bentot and The Anh Tran
*/
import java.util.*;
import java.io.*;
import java.util.concurrent.*;
public class knucleotide {
static ArrayList<Callable< Map<ByteString, ByteString> > > createFragmentTasks(final byte[] sequence, int[] fragmentLengths) {
ArrayList<Callable<Map<ByteString, ByteString>>> tasks = new ArrayList<Callable<Map<ByteString, ByteString>>>();
for (int fragmentLength : fragmentLengths) {
for (int index=0; index<fragmentLength; index++) {
final int offset = index;
final int finalFragmentLength = fragmentLength;
tasks.add(new Callable<Map<ByteString, ByteString>>() {
public Map<ByteString, ByteString> call() {
return createFragmentMap(sequence, offset, finalFragmentLength);
}
});
}
}
return tasks;
}
static Map<ByteString, ByteString> createFragmentMap(byte[] sequence, int offset, int fragmentLength) {
HashMap<ByteString, ByteString> map = new HashMap<ByteString, ByteString>();
int lastIndex = sequence.length - fragmentLength + 1;
ByteString key = new ByteString(fragmentLength);
for (int index=offset; index<lastIndex; index+=fragmentLength) {
key.calculateHash(sequence, index);
ByteString fragment = map.get(key);
if (fragment != null) {
fragment.count++;
} else {
map.put(key, key);
key = new ByteString(fragmentLength);
}
}
return map;
}
// Destructive!
static Map<ByteString, ByteString> sumTwoMaps(Map<ByteString, ByteString> map1, Map<ByteString, ByteString> map2) {
for (Map.Entry<ByteString, ByteString> entry : map2.entrySet()) {
ByteString sum = map1.get(entry.getKey());
if (sum != null)
sum.count += entry.getValue().count;
else
map1.put(entry.getKey(), entry.getValue());
}
return map1;
}
static String writeFrequencies(float totalCount, Map<ByteString, ByteString> frequencies) {
SortedSet<ByteString> list = new TreeSet<ByteString>(frequencies.values());
StringBuilder sb = new StringBuilder();
for (ByteString k : list)
sb.append(String.format("%s %.3f\n", k.toString().toUpperCase(), (float)(k.count) * 100.0f / totalCount));
return sb.append('\n').toString();
}
static String writeCount(List<Future<Map<ByteString, ByteString>>> futures, String nucleotideFragment) throws Exception {
ByteString key = new ByteString(nucleotideFragment.length());
key.calculateHash(nucleotideFragment.getBytes(), 0);
int count = 0;
for (Future<Map<ByteString, ByteString>> future : futures) {
ByteString temp = future.get().get(key);
if (temp != null) count += temp.count;
}
return count + "\t" + nucleotideFragment.toUpperCase() + '\n';
}
public static void main (String[] args) throws Exception {
String line;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while ((line = in.readLine()) != null) {
if (line.startsWith(">THREE")) break;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte bytes[] = new byte[100];
while((line = in.readLine()) != null) {
if (line.length() > bytes.length)
bytes = new byte[line.length()];
int i;
for(i=0; i<line.length(); i++)
bytes[i] = (byte)line.charAt(i);
baos.write(bytes, 0, i);
}
byte[] sequence = baos.toByteArray();
ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
int[] fragmentLengths = { 1, 2, 3, 4, 6, 12, 18 };
List<Future<Map<ByteString, ByteString>>> futures = pool.invokeAll(createFragmentTasks(sequence, fragmentLengths));
pool.shutdown();
StringBuilder sb = new StringBuilder();
sb.append(writeFrequencies(sequence.length, futures.get(0).get()));
sb.append(writeFrequencies(sequence.length - 1, sumTwoMaps(futures.get(1).get(), futures.get(2).get())));
String[] nucleotideFragments = { "ggt", "ggta", "ggtatt", "ggtattttaatt", "ggtattttaatttatagt" };
for (String nucleotideFragment : nucleotideFragments) {
sb.append(writeCount(futures, nucleotideFragment));
}
System.out.print(sb.toString());
}
static final class ByteString implements Comparable<ByteString> {
public int hash, count=1;
public final byte bytes[];
public ByteString(int size) {
bytes = new byte[size];
}
public void calculateHash(byte k[], int offset) {
int temp = 0;
for (int i=0; i<bytes.length; i++) {
byte b = k[offset+i];
bytes[i] = b;
temp = temp * 31 + b;
}
hash = temp;
}
public int hashCode() {
return hash;
}
public boolean equals(Object obj) {
return Arrays.equals(bytes, ((ByteString)obj).bytes);
}
public int compareTo(ByteString other) {
return other.count - count;
}
public String toString() {
return new String(bytes);
}
}
}
/* The Computer Language Benchmarks Game
http://benchmarksgame.alioth.debian.org/
Based on Java version #6 by James McIlree
Contributed by Hank Grabowski
*/
import java.util.*
import java.io.*
import java.util.concurrent.*
object knucleotide {
internal fun createFragmentTasks(sequence: ByteArray, fragmentLengths: IntArray): ArrayList<Callable<MutableMap<ByteString, ByteString>>> {
val tasks = ArrayList<Callable<MutableMap<ByteString, ByteString>>>()
for (fragmentLength in fragmentLengths) {
for (index in 0..fragmentLength - 1) {
tasks.add(Callable { createFragmentMap(sequence, index, fragmentLength) })
}
}
return tasks
}
internal fun createFragmentMap(sequence: ByteArray, offset: Int, fragmentLength: Int): MutableMap<ByteString, ByteString> {
val map = HashMap<ByteString, ByteString>()
val lastIndex = sequence.size - fragmentLength + 1
var key = ByteString(fragmentLength)
var index = offset
while (index < lastIndex) {
key.calculateHash(sequence, index)
val fragment = map[key]
if (fragment != null) {
fragment.count++
} else {
map.put(key, key)
key = ByteString(fragmentLength)
}
index += fragmentLength
}
return map
}
// Destructive!
internal fun sumTwoMaps(map1: MutableMap<ByteString, ByteString>, map2: Map<ByteString, ByteString>): Map<ByteString, ByteString> {
for ((key, value) in map2) {
val sum = map1[key]
if (sum != null)
sum.count += value.count
else
map1.put(key, value)
}
return map1
}
internal fun writeFrequencies(totalCount: Float, frequencies: Map<ByteString, ByteString>): String {
val list = TreeSet(frequencies.values)
val sb = StringBuilder()
for (k in list)
sb.append(String.format("%s %.3f\n", k.toString().toUpperCase(), k.count.toFloat() * 100.0f / totalCount))
return sb.append('\n').toString()
}
@Throws(Exception::class)
internal fun writeCount(futures: MutableList<Future<MutableMap<ByteString, ByteString>>>, nucleotideFragment: String): String {
val key = ByteString(nucleotideFragment.length)
key.calculateHash(nucleotideFragment.toByteArray(), 0)
var count = 0
for (future in futures) {
val temp = future.get()[key]
if (temp != null) count += temp.count
}
return count.toString() + "\t" + nucleotideFragment.toUpperCase() + '\n'
}
@Throws(Exception::class)
@JvmStatic
fun main(args: Array<String>) {
var line: String = ""
val `in` = BufferedReader(InputStreamReader(System.`in`))
while ({line = `in`.readLine(); line}() != null) {
if (line.startsWith(">THREE")) break
}
val baos = ByteArrayOutputStream()
var bytes = ByteArray(100)
while ({line = `in`.readLine()}() != null) {
if (line.length > bytes.size)
bytes = ByteArray(line.length)
var i: Int
i = 0
while (i < line.length) {
bytes[i] = line[i].toByte()
i++
}
baos.write(bytes, 0, i)
}
val sequence = baos.toByteArray()
val pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())
val fragmentLengths = intArrayOf(1, 2, 3, 4, 6, 12, 18)
val futures = pool.invokeAll(createFragmentTasks(sequence, fragmentLengths))
pool.shutdown()
val sb = StringBuilder()
sb.append(writeFrequencies(sequence.size.toFloat(), futures[0].get()))
sb.append(writeFrequencies((sequence.size - 1).toFloat(), sumTwoMaps(futures[1].get(), futures[2].get())))
val nucleotideFragments = arrayOf("ggt", "ggta", "ggtatt", "ggtattttaatt", "ggtattttaatttatagt")
for (nucleotideFragment in nucleotideFragments) {
sb.append(writeCount(futures, nucleotideFragment))
}
print(sb.toString())
}
internal class ByteString(size: Int) : Comparable<ByteString> {
var hash: Int = 0
var count = 1
val bytes: ByteArray
init {
bytes = ByteArray(size)
}
fun calculateHash(k: ByteArray, offset: Int) {
var temp = 0
for (i in bytes.indices) {
val b = k[offset + i]
bytes[i] = b
temp = temp * 31 + b
}
hash = temp
}
override fun hashCode(): Int {
return hash
}
override fun equals(obj: Any?): Boolean {
return Arrays.equals(bytes, (obj as ByteString).bytes)
}
override fun compareTo(other: ByteString): Int {
return other.count - count
}
override fun toString(): String {
return String(bytes)
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment