Advertisement
Guest User

Moving average

a guest
Oct 16th, 2013
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 2.22 KB | None | 0 0
  1. module main;
  2.  
  3. import std.stdio;
  4. import std.conv;
  5. import std.string;
  6. import std.array;
  7. import std.math;
  8. import std.range;
  9. import std.format;
  10.  
  11. import canvas;
  12. import dlib.image.color;
  13. import dlib.image.io.png;
  14.  
  15. void main()
  16. {
  17.     // Чтение массива данных (y) из файла
  18.     auto a = appender!(double[]);
  19.     foreach(line; File("test.txt").byLine)
  20.         a.put(line.strip.to!double);
  21.     double[] y = a.data;
  22.  
  23.     // Второй массив для хранения логарифмов,
  24.     // чтобы не "портить" первый нулями
  25.     double[] y2 = new double[y.length];
  26.     y2[] = 0;
  27.  
  28.     uint period = 11;
  29.     uint k = (period - 1) / 2;
  30.  
  31.     auto sk = new double[y.length - k];
  32.     sk[] = 0;
  33.  
  34.     for (uint i = k + 1; i < y.length - k; i++)
  35.     {
  36.         sk[i] = 0;
  37.  
  38.         for (uint j = i - k; j < i + k + 1; j++)
  39.         {
  40.             y2[j] = log(y[j]);
  41.  
  42.             // Проверка на NaN (NaN'ов теперь быть не должно)
  43.             assert( !isNaN(y2[j]), format("y2[%s] = %s", j, y2[j]) );
  44.  
  45.             sk[i] += y2[j];
  46.         }
  47.  
  48.         sk[i] = exp(sk[i] / period);
  49.  
  50.         // Проверка на бесконечность (не должно быть)
  51.         assert( sk[i] != double.infinity, format("sk[%s] = %s", i, sk[i]) );
  52.  
  53.         // Для C#:
  54.         // ppl.Add(new PointPair(i, sk[i]));
  55.     }
  56.  
  57.     // Рисуем график
  58.     {
  59.         Canvas c = new Canvas(512, 256, White);
  60.  
  61.         plotData(c, y, Blue);
  62.         plotData(c, sk, Red);
  63.  
  64.         c.image.savePNG("output.png");
  65.     }
  66. }
  67.  
  68. /*
  69.  * Всякие ненужные Наташе функции...
  70.  */
  71. string format(T...)(string f, T t)
  72. {
  73.     auto writer = appender!string;
  74.     formattedWrite(writer, f, t);
  75.     return writer.data;
  76. }
  77.  
  78. void plotData(Canvas c, double[] y, Color4 col)
  79. {
  80.     double px = 0, py = c.image.width / 2;
  81.     foreach(i; 0..y.length)
  82.     {
  83.         auto x = i * 10;
  84.  
  85.         double Y = y[i];
  86.         auto ny = Y * 20;
  87.         if (x > 0 && Y > 0 && py > 0)
  88.         {
  89.             if (py < c.image.height)
  90.                 c.drawLineAA(px, py, x, ny, col);
  91.         }
  92.         px = x;
  93.         py = ny;
  94.     }
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement