Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import std.array: Appender, isArray;
- import std.random: uniform;
- import std.stdio: writefln;
- import std.string: toLower;
- import std.range: ElementEncodingType;
- class MarkovChain(T) if (isArray!T)
- {
- alias E = ElementEncodingType!T; // element type
- alias iT = immutable(T);
- alias iE = immutable(E);
- int order;
- double[iE][iT] probMap; // keys must be immutable
- this(T seqData, int order)
- {
- this.order = order;
- probMap = createMap(seqData);
- }
- // Creates a structure similar to a stochastic matrix, but uses
- // associative arrays to save space.
- double[iE][iT] createMap(T seqData)
- {
- // probMap is first used to hold the frequencies of transitions
- // occurring, but later holds the probabilities of transitions
- // occurring. This is done to save memory.
- double[iE][iT] probMap;
- int[iT] srcFreq;
- for(int i = 0; i < seqData.length-order; i++)
- {
- int j;
- for(j = 0; j < order; j++)
- {
- alias cur = seqData[i..i+order];
- srcFreq[cur] = srcFreq.get(cur, 0) + 1;
- probMap[cur] = probMap.get(cur, null); // AAs are initially null
- probMap[cur][next] = probMap[cur].get(next, 0) + 1;
- }
- }
- // Turn transition frequencies into transition probabilities.
- foreach(src, dstMap; probMap)
- foreach(dst, ref freq; dstMap)
- freq = freq/srcFreq[src];
- return probMap;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement