Advertisement
Guest User

fdsaf

a guest
Oct 31st, 2013
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.53 KB | None | 0 0
  1. import std.array: Appender, isArray;
  2. import std.random: uniform;
  3. import std.stdio: writefln;
  4. import std.string: toLower;
  5. import std.range: ElementEncodingType;
  6.  
  7. class MarkovChain(T) if (isArray!T)
  8. {
  9.     alias E = ElementEncodingType!T; // element type
  10.     alias iT = immutable(T);
  11.     alias iE = immutable(E);
  12.  
  13.     int order;
  14.     double[iE][iT] probMap; // keys must be immutable
  15.  
  16.     this(T seqData, int order)
  17.     {
  18.         this.order = order;
  19.         probMap = createMap(seqData);
  20.     }
  21.  
  22.     // Creates a structure similar to a stochastic matrix, but uses
  23.     // associative arrays to save space.
  24.     double[iE][iT] createMap(T seqData)
  25.     {
  26.         // probMap is first used to hold the frequencies of transitions
  27.         // occurring, but later holds the probabilities of transitions
  28.         // occurring. This is done to save memory.
  29.         double[iE][iT] probMap;
  30.         int[iT] srcFreq;
  31.  
  32.         for(int i = 0; i < seqData.length-order; i++)
  33.         {
  34.             int j;
  35.            
  36.             for(j = 0; j < order; j++)
  37.         {  
  38.         alias cur = seqData[i..i+order];
  39.                 srcFreq[cur] = srcFreq.get(cur, 0) + 1;
  40.                 probMap[cur] = probMap.get(cur, null); // AAs are initially null
  41.                 probMap[cur][next] = probMap[cur].get(next, 0) + 1;
  42.         }
  43.         }
  44.  
  45.         // Turn transition frequencies into transition probabilities.
  46.         foreach(src, dstMap; probMap)
  47.             foreach(dst, ref freq; dstMap)
  48.                 freq = freq/srcFreq[src];
  49.  
  50.         return probMap;
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement