// get X/Y/Z
        private double getweight(double[, ,] XYZ, int index)
        {
            if (index < 0)
            {
                index = 0;
            }
            else if (index > 2)
            {
                index = 2;
            }

            double sum  = 0;
            double mean = 0;
            float  w    = XYZ.GetLength(0);
            float  h    = XYZ.GetLength(1);

            for (int r = 0; r < w; r++)
            {
                for (int c = 0; c < h; c++)
                {
                    sum += XYZ[r, c, index];
                }
            }
            mean = sum / (w * h);
            return(mean);
        }
Exemple #2
0
        public double[, ,] RGB2XYZ(double[, ,] rgbstr)
        {
            int w = rgbstr.GetLength(0);
            int h = rgbstr.GetLength(1);

            double[, ,] xyzstr = new double[w, h, 3];
            var ccm = new[, ]
            {
                { 0.5767309, 0.2973769, 0.0270343 },
                { 0.1855540, 0.6273491, 0.0706872 },
                { 0.1881852, 0.0752741, 0.9911085 }
            };


            for (int i = 0; i < w; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    double[] rgb = new double[] { rgbstr[i, j, 0], rgbstr[i, j, 1], rgbstr[i, j, 2] };
                    double[] xyz = MultiplyVector(ccm, rgb);
                    xyzstr[i, j, 0] = xyz[0];
                    xyzstr[i, j, 1] = xyz[1];
                    xyzstr[i, j, 2] = xyz[2];
                }
            }

            return(xyzstr);
        }
 /// <summary>
 /// Returns the input vector for the sample at position (x,y)
 /// </summary>
 public IEnumerable <double> GetInputs(int x, int y)
 {
     for (int i = 0; i < samples.GetLength(0); i++)
     {
         yield return(samples[i, x, y]);
     }
 }
Exemple #4
0
        private static double[,,] processImage(double[,,] arrayImage, Action <ColorCustom> pixelAction)
        {
            double[,,] res = (double[, , ])arrayImage.Clone();

            int width  = arrayImage.GetLength(2),
                height = arrayImage.GetLength(1);

            ColorCustom c = new ColorCustom();

            for (int h = 0; h < height; h++)
            {
                for (int w = 0; w < width; w++)
                {
                    c.r = res[0, h, w];
                    c.g = res[1, h, w];
                    c.b = res[2, h, w];


                    pixelAction(c);

                    res[0, h, w] = c.r;
                    res[1, h, w] = c.g;
                    res[2, h, w] = c.b;
                }
            }

            return(res);
        }
        // get average Y from input XYZ matrix
        public double getlv(double[, ,] XYZ)
        {
            double        sum     = 0;
            double        mean    = 0;
            float         w       = XYZ.GetLength(0);
            float         h       = XYZ.GetLength(1);
            List <double> pointLv = new List <double>();
            double        value   = 0;

            for (int r = 0; r < w; r++)
            {
                for (int c = 0; c < h; c++)
                {
                    value = XYZ[r, c, 1];
                    sum  += XYZ[r, c, 1];
                    pointLv.Add(value);
                }
            }


            pointLv.Sort();
            int index = (int)(w * h * 3 / 10.0);

            pointLv.RemoveRange(0, index);
            pointLv.RemoveRange(pointLv.Count - index, index);

            double sumAverage = pointLv.Average();

            return(sumAverage);


            // mean = sum / (w * h);
            //return mean;
        }
Exemple #6
0
        public unsafe static Bitmap DoubleRgbToBitmap(double[,,] arrayImage)
        {
            int width  = arrayImage.GetLength(2),
                height = arrayImage.GetLength(1);

            Bitmap     res = new Bitmap(width, height);
            BitmapData bd  = res.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly,
                                          PixelFormat.Format24bppRgb);

            try
            {
                byte *curpos;
                fixed(double *_arrImage = arrayImage)
                {
                    double *_r = _arrImage, _g = _arrImage + width * height, _b = _arrImage + 2 * width * height;

                    for (int h = 0; h < height; h++)
                    {
                        curpos = ((byte *)bd.Scan0) + h * bd.Stride;
                        for (int w = 0; w < width; w++)
                        {
                            *(curpos++) = Limit(*_b); ++_b;
                            *(curpos++) = Limit(*_g); ++_g;
                            *(curpos++) = Limit(*_r); ++_r;
                        }
                    }
                }
            }
            finally
            {
                res.UnlockBits(bd);
            }
            return(res);
        }
 /// <summary>
 /// Act Loop on Estimated Chip Data.
 /// </summary>
 /// <param name="this"></param>
 /// <param name="boxlsit">BoxList for compare with chip Est data</param>
 /// <param name="centerPoints"></param>
 /// <param name="loopAct"></param>
 /// <returns></returns>
 public static double[,,] Act_LoopChipPos(
     this double[,,] @this,
     List <System.Drawing.Rectangle> boxlsit,
     System.Drawing.Point[] centerPoints,
     Action <int, int, double, double, List <System.Drawing.Rectangle>, System.Drawing.Point[]> loopAct)
 {
     try
     {
         for (int j = 0; j < @this.GetLength(0); j++)       // row
         {
             for (int i = 0; i < @this.GetLength(1); i++)   // col
             {
                 loopAct(
                     j, i
                     , @this[j, i, 0]
                     , @this[j, i, 1]
                     , boxlsit
                     , centerPoints);
             }
         }
         return(@this);
     }
     catch
     {
         return(@this);
     }
 }
Exemple #8
0
        public override void GetError(double[,,] error_out, double[,,] diff, double[,,] inarray, double[,,] input)
        {
            int a = 0;

            int depth1  = input_size[0];
            int height1 = input_size[1];
            int width1  = input_size[2];

            int depth2  = error_out.GetLength(0);
            int height2 = error_out.GetLength(1);
            int width2  = error_out.GetLength(2);

            for (int z1 = 0; z1 < depth1; z1++)
            {
                for (int y1 = 0; y1 < height1; y1++)
                {
                    for (int x1 = 0; x1 < width1; x1++)
                    {
                        double val = 0;
                        for (int z2 = 0; z2 < depth2; z2++)
                        {
                            for (int y2 = 0; y2 < height2; y2++)
                            {
                                for (int x2 = 0; x2 < width2; x2++)
                                {
                                    val += weights[z2, y2, x2, z1, y1, x1] * error_out[z2, y2, x2];
                                }
                            }
                        }

                        input[z1, y1, x1] = val * diff[z1, y1, x1];
                    }
                }
            }
        }
Exemple #9
0
        /*public static void SaveHDR(float[, ,] hdr, string path)
         * {
         * FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
         * BinaryWriter bw = new BinaryWriter(fs);
         *
         * int width = hdr.GetLength(0);
         * int height = hdr.GetLength(1);
         * int depth = hdr.GetLength(2);
         *
         * bw.Write(width);
         * bw.Write(height);
         * bw.Write(depth);
         *
         * for (int x = 0; x < width; x++)
         *  for (int y = 0; y < height; y++)
         *    for (int z = 0; z < depth; z++)
         *      bw.Write(hdr[x, y, z]);
         *
         * bw.Close();
         * }
         * public static float[, ,] LoadHDR(string path)
         * {
         * FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
         * BinaryReader br = new BinaryReader(fs);
         *
         * int width = br.ReadInt32();
         * int height = br.ReadInt32();
         * int depth = br.ReadInt32();
         *
         * float[, ,] hdr = new float[width, height, depth];
         *
         * for (int x = 0; x < width; x++)
         *  for (int y = 0; y < height; y++)
         *    for (int z = 0; z < depth; z++)
         *      hdr[x, y, z] = br.ReadSingle();
         *
         * br.Close();
         * }*/
        public static void ToFile(double[, ,] hdr, string path)
        {
            FileStream   fs = new FileStream(path, FileMode.Create, FileAccess.Write);
            BinaryWriter bw = new BinaryWriter(fs);

            int width  = hdr.GetLength(0);
            int height = hdr.GetLength(1);
            int depth  = hdr.GetLength(2);

            bw.Write(width);
            bw.Write(height);
            bw.Write(depth);

            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    for (int z = 0; z < depth; z++)
                    {
                        bw.Write(hdr[x, y, z]);
                    }
                }
            }

            bw.Close();
        }
        public double GetError(double[,,] input, double[,,] t)
        {
            double[,,] output = GetOutput(input);

            int depth2  = output.GetLength(0);
            int height2 = output.GetLength(1);
            int width2  = output.GetLength(2);

            double val  = 0;
            double temp = 0;

            for (int z2 = 0; z2 < depth2; z2++)
            {
                for (int y2 = 0; y2 < height2; y2++)
                {
                    for (int x2 = 0; x2 < width2; x2++)
                    {
                        temp = output[z2, y2, x2] - t[z2, y2, x2];
                        val += temp * temp;
                    }
                }
            }

            return(val);
        }
Exemple #11
0
        public double[] FlatternLayer(double[,,] input)
        {
            int rgbChannel  = input.GetLength(0);
            int rowPixel    = input.GetLength(1);
            int columnPixel = input.GetLength(2);
            int length      = rgbChannel * rowPixel * columnPixel;

            double[] output = new double[length];
            try
            {
                int count = 0;
                for (int i = 0; i < rgbChannel; i++)
                {
                    for (int j = 0; j < rowPixel; j++)
                    {
                        for (int k = 0; k < columnPixel; k++)
                        {
                            output[count] = input[i, j, k];
                            count         = count + 1;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return(output);
        }
Exemple #12
0
        // METODO per il salvataggio su csv
        public void saveData(double[,,] toSaveData, double[,,] toSaveQuaternioni, string ID)
        {
            using (sw_Save = File.AppendText(FILEPATHSAVE))
            {
                int length = (toSaveData.GetLength(1) == 500) ? toSaveData.GetLength(1) / 2 : toSaveData.GetLength(1);

                //Scorro i campionamenti e salvo su csv
                for (int k = 0; k < length; k++)
                {
                    for (int j = 0; j < numSensori; j++)
                    {
                        for (int i = 0; i < toSaveData.GetLength(0); i++)
                        {
                            sw_Save.Write(toSaveData[i, k, j] + ";");
                        }
                        for (int i = 0; i < toSaveQuaternioni.GetLength(0); i++)
                        {
                            sw_Save.Write(toSaveQuaternioni[i, k, j] + ";");
                        }
                        sw_Save.Write(";");
                    }
                    sw_Save.Write("\r");
                }
            }
            mainForm.displayText("[" + ID + "] Il file PinApp_save_xSimulator.csv è stato aggiornato.\r\r");
            Console.Beep();
        }
Exemple #13
0
        /// <summary>
        /// Производит повышение разрешения данных
        /// </summary>
        /// <param name="init">Исходные данные</param>
        /// <returns>Данные с повышенным разрешением</returns>
        public double[,,] UpSample(double[,,] init)
        {
            var res = new double[MaxPositions.GetLength(0), MaxPositions.GetLength(1), MaxPositions.GetLength(2)];

            for (int l = 0; l < init.GetLength(0); l++)
            {
                for (int i = 0; i < init.GetLength(1); i++)
                {
                    for (int j = 0; j < init.GetLength(2); j++)
                    {
                        // начинает пулинг
                        for (int poolL = 0; poolL < HowLayers; poolL++)
                        {
                            for (int poolI = 0; poolI < PoolSize; poolI++)
                            {
                                for (int poolJ = 0; poolJ < PoolSize; poolJ++)
                                {
                                    res[l * HowLayers + poolL, i *PoolSize + poolI, j *PoolSize + poolJ] =
                                        MaxPositions[l * HowLayers + poolL, i *PoolSize + poolI, j *PoolSize + poolJ] * init[l, i, j];
                                }
                            }
                        }
                    }
                }
            }

            return(res);
        }
        public static double[][,] ToArray2d(this double[,,] coordinateSets)
        {
            var length0 = coordinateSets.GetLength(0);
            var length1 = coordinateSets.GetLength(1);
            var length2 = coordinateSets.GetLength(2);

            var result = new double[length0][, ];

            for (int i = 0; i < length0; i++)
            {
                var a = new double[length1, length2];

                for (int j = 0; j < length1; j++)
                {
                    for (int k = 0; k < length2; k++)
                    {
                        a[j, k] = coordinateSets[i, j, k];
                    }
                }

                result[i] = a;
            }

            return(result);
        }
Exemple #15
0
        private void Totalpckxg(int numClusters, int fernsNumber, double[,] fernpcknumber, int[,] _r1, double[, ,] totalpck_xg, double[] mmm, out double[,] pck_xgtotal)
        {
            pck_xgtotal = new double[pck_xg.GetLength(0), pck_xg.GetLength(1)];
            double[] nu  = new double[numClusters];
            double   sum = mmm.Sum();

            for (int j = 0; j < totalpck_xg.GetLength(1); j++)
            {
                for (int k = 0; k < totalpck_xg.GetLength(2); k++)
                {
                    for (int i = 0; i < fernsNumber; i++)
                    {
                        pck_xgtotal[j, k] += (mmm[i] / sum) * totalpck_xg[i, j, _r1[i, k]];
                        nu[k]             += fernpcknumber[i, _r1[i, k]];
                    }

                    if (nu[k] == 0)
                    {
                        pck_xgtotal[j, k] = 0;
                    }
                    else
                    {
                        pck_xgtotal[j, k] = pck_xgtotal[j, k] / nu[k];
                    }
                }
            }
        }
Exemple #16
0
    public static double[,] Flatten(double[,,] input)
    {
        int inputRows    = input.GetLength(0);
        int inputColumns = input.GetLength(1);
        int inputDepth   = input.GetLength(2);

        int flattenLength = inputRows * inputColumns * inputDepth;

        double[,] result = new double[1, flattenLength];

        int resultColumn = 0;


        for (int c = 0; c < inputDepth; c++)
        {
            for (int i = 0; i < inputRows; i++)
            {
                for (int j = 0; j < inputColumns; j++)
                {
                    result[0, resultColumn] = input[i, j, c];
                    resultColumn++;
                }
            }
        }

        return(result);
    }
Exemple #17
0
    public static double[,,] PointWiseConv(double[,,] input, double[,,,] kernels)
    {
        int inputRows    = input.GetLength(0);
        int inputColumns = input.GetLength(1);
        int inputDepth   = input.GetLength(2);

        int kernelDepth = kernels.GetLength(3);


        double[,,] result = new double[inputRows, inputColumns, kernelDepth];

        for (int kernel = 0; kernel < kernelDepth; kernel++)
        {
            for (int i = 0; i < inputRows; i++)
            {
                for (int j = 0; j < inputColumns; j++)
                {
                    double convResult = 0d;

                    for (int channel = i; channel < inputDepth; channel++)
                    {
                        convResult += input[i, j, channel] * kernels[0, 0, channel, kernel];
                    }

                    result[i, j, kernel] = Mathf.Clamp((float)convResult, float.MinValue, float.MaxValue);
                }
            }
        }

        return(result);
    }
Exemple #18
0
        public static void Save(double[, ,] qTable)
        {
            // Verify the directory exists
            if (!Directory.Exists(EXPORT_DIRECTORY))
            {
                Directory.CreateDirectory(EXPORT_DIRECTORY);
            }

            // Save a CSV file for each direction
            foreach (Direction direction in Enum.GetValues(typeof(Direction)))
            {
                if (direction != Direction.NONE)
                {
                    using (StreamWriter file = new StreamWriter(EXPORT_DIRECTORY + @"\" + direction.ToString() + ".csv"))
                    {
                        for (int rowIndex = 0; rowIndex < qTable.GetLength(0); rowIndex++)
                        {
                            for (int columnIndex = 0; columnIndex < qTable.GetLength(1); columnIndex++)
                            {
                                file.Write(qTable[rowIndex, columnIndex, (int)direction]);

                                if (columnIndex == qTable.GetLength(1) - 1)
                                {
                                    file.WriteLine();
                                }
                                else
                                {
                                    file.Write(",");
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #19
0
        private static async Task UpdateH
        (
            double[,,] Hx, double[,,] Hy, double[,,] Hz,
            double[,,] Ex, double[,,] Ey, double[,,] Ez,
            double tx, double ty, double tz,
            double[,,] AH
        )
        {
            var Lx = Hx.GetLength(0);
            var Ly = Hx.GetLength(1);
            var Lz = Hx.GetLength(2);

            var tHx = Task.Factory.StartNew(() =>
            {
                for (var i = 0; i < Lx; i++)
                {
                    for (var j = 0; j < Ly - 1; j++)
                    {
                        for (var k = 0; k < Lz - 1; k++)
                        {
                            Hx[i, j, k] -= ((Ez[i, j + 1, k] - Ez[i, j, k]) / ty - (Ey[i, j, k + 1] - Ey[i, j, k]) / tz)
                                           * AH[i, j, k];
                        }
                    }
                }
            });

            var tHy = Task.Factory.StartNew(() =>
            {
                for (var i = 0; i < Lx - 1; i++)
                {
                    for (var j = 0; j < Ly; j++)
                    {
                        for (var k = 0; k < Lz - 1; k++)
                        {
                            Hy[i, j, k] -= ((Ex[i, j, k + 1] - Ex[i, j, k]) / tz - (Ez[i + 1, j, k] - Ez[i, j, k]) / tx)
                                           * AH[i, j, k];
                        }
                    }
                }
            });

            var tHz = Task.Factory.StartNew(() =>
            {
                for (var i = 0; i < Lx - 1; i++)
                {
                    for (var j = 0; j < Ly - 1; j++)
                    {
                        for (var k = 0; k < Lz; k++)
                        {
                            Hz[i, j, k] -= ((Ey[i + 1, j, k] - Ey[i, j, k]) / tx - (Ex[i, j + 1, k] - Ex[i, j, k]) / ty)
                                           * AH[i, j, k];
                        }
                    }
                }
            });

            await Task.WhenAll(tHx, tHy, tHz).ConfigureAwait(false);
        }
        double[][,,] GetBackwardErrors(double[,,] input, double[,,] t, out double err, out List <KeyValuePair <double[, , ], double[, , ]> > getOutput)
        {
            double[][,,] errors = new double[layers.Count][, , ];
            var out_pairs = GetOutAndDiff(input);

            double[,,] output = out_pairs.Last().Key;

            //Console.WriteLine("{0} {1}", (float)output[0, 0, 0], (float)output[0, 0, 1]);

            int depth2  = output.GetLength(0);
            int height2 = output.GetLength(1);
            int width2  = output.GetLength(2);

            double val  = 0;
            double temp = 0;

            double[,,] out_err = (double[, , ])t.Clone();

            double[,,] diff = out_pairs.Last().Value;

            for (int z2 = 0; z2 < depth2; z2++)
            {
                for (int y2 = 0; y2 < height2; y2++)
                {
                    for (int x2 = 0; x2 < width2; x2++)
                    {
                        temp = t[z2, y2, x2] - output[z2, y2, x2];
                        out_err[z2, y2, x2] = -temp * diff[z2, y2, x2];
                        val += temp * temp;
                    }
                }
            }

            errors[errors.Length - 1] = out_err;

            for (int i = layers.Count - 1; i >= 0; i--)
            {
                Layer prev = null;
                if (i != 0)
                {
                    prev = layers[i - 1];
                    if (prev != null)
                    {
                        errors[i - 1] = layers[i].GetError(errors[i], out_pairs[i - 1].Value, out_pairs[i - 1].Key);
                    }
                    else
                    {
                        double[,,] diff2 = (double[, , ])input.Clone();
                        diff2.ForEach(x => 1);
                        errors[i - 1] = layers[i].GetError(errors[i], diff2, input);
                    }
                }
            }

            err       = val;
            getOutput = out_pairs;

            return(errors);
        }
Exemple #21
0
        private static async Task UpdateE
        (
            double[,,] Hx, double[,,] Hy, double[,,] Hz,
            double[,,] Ex, double[,,] Ey, double[,,] Ez,
            double tx, double ty, double tz,
            double[,,] AE
        )
        {
            var Lx = Ex.GetLength(0);
            var Ly = Ex.GetLength(1);
            var Lz = Ex.GetLength(2);

            var tEx = Task.Factory.StartNew(() =>
            {
                for (var i = 0; i < Lx - 1; i++)
                {
                    for (var j = 1; j < Ly - 1; j++)
                    {
                        for (var k = 1; k < Lz - 1; k++)
                        {
                            Ex[i, j, k] = Ex[i, j, k] * AE[i, j, k]
                                          + ((Hz[i, j, k] - Hz[i, j - 1, k]) / ty - (Hy[i, j, k] - Hy[i, j, k - 1]) / tz);
                        }
                    }
                }
            });

            var tEy = Task.Factory.StartNew(() =>
            {
                for (var i = 1; i < Lx - 1; i++)
                {
                    for (var j = 0; j < Ly - 1; j++)
                    {
                        for (var k = 1; k < Lz - 1; k++)
                        {
                            Ey[i, j, k] = Ey[i, j, k] * AE[i, j, k]
                                          + ((Hx[i, j, k] - Hx[i, j, k - 1]) / tz - (Hz[i, j, k] - Hz[i - 1, j, k]) / tx);
                        }
                    }
                }
            });

            var tEz = Task.Factory.StartNew(() =>
            {
                for (var i = 1; i < Lx - 1; i++)
                {
                    for (var j = 1; j < Ly - 1; j++)
                    {
                        for (var k = 0; k < Lz - 1; k++)
                        {
                            Ez[i, j, k] = Ez[i, j, k] * AE[i, j, k]
                                          + ((Hy[i, j, k] - Hy[i - 1, j, k]) / tx - (Hx[i, j, k] - Hx[i, j - 1, k]) / ty);
                        }
                    }
                }
            });

            await Task.WhenAll(tEx, tEy, tEz).ConfigureAwait(false);
        }
Exemple #22
0
 public static System.Drawing.Point[] GetMomnetList(
     this double[,,] @this)
 {
     return(Enumerable.Range(0, @this.GetLength(0))
            .SelectMany(j => Enumerable.Range(0, @this.GetLength(1))
                        , (j, i) => new System.Drawing.Point(i, j))
            .ToArray());
 }
Exemple #23
0
 public frmPlotPSO(double[,,] PlotSwarmPsition, double[,] PlotGlobalPosition)
 {
     InitializeComponent();
     plotSwarmPositions  = (double[, , ])PlotSwarmPsition.Clone();
     plotGlobalPositions = (double[, ])PlotGlobalPosition.Clone();
     maxIter             = plotSwarmPositions.GetLength(0);
     maxSwarm            = plotSwarmPositions.GetLength(1);
 }
Exemple #24
0
    private static bool NoiseExists(Vector3 position)
    {
        bool xInBounds = position.x < noise.GetLength(0) - 1 && position.x >= 0;
        bool yInBounds = position.y < noise.GetLength(1) - 1 && position.y >= 0;
        bool zInBounds = position.z < noise.GetLength(2) - 1 && position.z >= 0;

        return(xInBounds && yInBounds && zInBounds);
    }
Exemple #25
0
        /// <summary>
        ///     Blur bitmap with the Fastest Fourier Transform
        /// </summary>
        /// <returns>Blurred bitmap</returns>
        public double[,,] Blur(double[,,] imageData)
        {
            int length = imageData.Length;
            int n0     = imageData.GetLength(0);
            int n1     = imageData.GetLength(1);
            int n2     = imageData.GetLength(2);

            var doubles = new double[length];

            Buffer.BlockCopy(imageData, 0, doubles, 0, length * sizeof(double));

            double average;
            double delta;

            AverageAndDelta(out average, out delta, doubles, _keepOption);

            Complex[] complex = doubles.Select(x => new Complex(x, 0)).ToArray();

            Fourier(n0, n1, n2, complex, FourierDirection.Forward);
            Complex level      = complex[0];
            Size    filterSize = _filterSize;

            switch (_filterMode)
            {
            case FilterMode.FilterSize:
                break;

            case FilterMode.FilterStep:
                int filterStep = _filterStep;
                filterSize = new Size(MulDiv(n1, filterStep, filterStep + 1),
                                      MulDiv(n0, filterStep, filterStep + 1));
                break;

            default:
                throw new NotImplementedException();
            }

            BlindInner(n0, n1, complex, filterSize, n2);
            complex[0] = level;
            Fourier(n0, n1, n2, complex, FourierDirection.Backward);
            doubles = complex.Select(x => x.Magnitude).ToArray();

            double average2;
            double delta2;

            AverageAndDelta(out average2, out delta2, doubles, _keepOption);

            // a*average2 + b == average
            // a*delta2 == delta
            double a = (_keepOption == KeepOption.AverageAndDelta) ? (delta / delta2) : (average / average2);
            double b = (_keepOption == KeepOption.AverageAndDelta) ? (average - a * average2) : 0;

            Debug.Assert(Math.Abs(a * average2 + b - average) < 0.1);
            doubles = doubles.Select(x => Math.Round(a * x + b)).ToArray();

            Buffer.BlockCopy(doubles, 0, imageData, 0, length * sizeof(double));
            return(imageData);
        }
Exemple #26
0
        public static double[,,] Flip(double[,,] input)
        {
            int w      = input.GetLength(1);
            int h      = input.GetLength(2);
            var output = new double[input.GetLength(0), w, h];

            input.ForEach((q, k, i, j) => output[k, w - i - 1, h - j - 1] = q);
            return(output);
        }
 public static double[] GetRank(this double[,,] D, int r1, int r2)
 {
     double[] r = new double[D.GetLength(2)];
     if (D.GetLength(0) > r1 && D.GetLength(1) > r2)
     {
         Parallel.For(0, D.GetLength(2), j => r[j] = D[r1, r2, j]);
     }
     return(r);
 }
 public static int[] get_shape(double[,,] input)
 {
     int[] res = new int[3];
     res[0] = input.GetLength(0);
     res[1] = input.GetLength(1);
     res[2] = input.GetLength(2);
     Console.WriteLine("(" + res[0] + "," + res[1] + "," + res[2] + ")");
     return(res);
 }
Exemple #29
0
        protected double[] GeneralCNN(double[,,] inputData)
        {
            int elementAmount     = inputData.GetLength(0) * inputData.GetLength(1) * inputData.GetLength(2);
            int kernelListCounter = 0;

            double[,,] current = new double[0, 0, 0];
            while (elementAmount < this.transitionElementAmount && kernelListCounter < convLayerKernels.Capacity)
            {
                //reassign elementAmount after convolution and pooling
                int kernelIndex    = 0;
                int convLayerIndex = 0;
                this.convLayerNetwork.Add(inputData);
                current = convLayerNetwork[convLayerIndex];//first time

                while ((current.GetLength(0) * current.GetLength(1) * current.GetLength(2) < this.transitionElementAmount) &&
                       kernelIndex < convLayerKernels.Capacity)
                {
                    double[,,] currentKernel = convLayerKernels[kernelIndex];
                    current = convLayerNetwork[convLayerIndex];
                    int[] currentKernelDimensions = new int[] { currentKernel.GetLength(0),
                                                                currentKernel.GetLength(1),
                                                                currentKernel.GetLength(2) };

                    this.convLayerNetwork.Add(REluOperation(MaxPoolingOperation(ConvolutionOperation(current, currentKernel),
                                                                                currentKernelDimensions)));
                }
            }
            //converting 3d tensor to 1d vector
            double[] transitionVector = new double[current.GetLength(0) * current.GetLength(1) * current.GetLength(2)];
            double[,,] transitionTensor = convLayerNetwork[convLayerNetwork.Capacity - 1];
            int transitionAccum = 0;

            for (int i = 0; i < convLayerNetwork[convLayerNetwork.Capacity - 1].GetLength(0); i++)
            {
                for (int j = 0; j < convLayerNetwork[convLayerNetwork.Capacity - 1].GetLength(1); j++)
                {
                    for (int k = 0; k < convLayerNetwork[convLayerNetwork.Capacity - 1].GetLength(2); k++)
                    {
                        transitionVector[transitionAccum] = transitionTensor[i, j, k];
                        transitionAccum++;
                    }
                }
            }
            double[] currentLayer = new double[0];
            for (int i = 0; i < this.weights.Capacity; i++)
            {
                if (i == 0)
                {
                    currentLayer = this.Add(SoftmaxOperation(MatrixVectorProduct(weights[i], transitionVector)), biases[i]);
                }
                else
                {
                    currentLayer = this.Add(SoftmaxOperation(MatrixVectorProduct(weights[i], currentLayer)), biases[i]);
                }
            }
            return(currentLayer);
        }
        public MapClusteringView(IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder,
                                 IMapClusteringDataset dataset,
                                 MapClusteringEvaluator evaluator,
                                 int nbClusters)
            : this()
        {
            this.dataset    = dataset;
            this.nbClusters = nbClusters;
            this.decoder    = genomeDecoder;
            this.evaluator  = evaluator;

            samples = dataset.GetSamplesMatrix();
            outputs = new double[nbClusters, samples.GetLength(1), samples.GetLength(2)];

            inputView.LabelName  = "Input";
            outputView.LabelName = "Output";

            inputView.SetDimensions(samples.GetLength(0), samples.GetLength(1), samples.GetLength(2));
            outputView.SetDimensions(nbClusters, samples.GetLength(1), samples.GetLength(2));

            maxValue = 0.0;
            minValue = double.PositiveInfinity;
            for (var i = 0; i < samples.GetLength(0); i++)
            {
                for (var j = 0; j < samples.GetLength(1); j++)
                {
                    for (var k = 0; k < samples.GetLength(2); k++)
                    {
                        var value = samples[i, j, k];
                        if (value > maxValue)
                        {
                            maxValue = value;
                        }
                        if (value < minValue)
                        {
                            minValue = value;
                        }
                    }
                }
            }
            // Add some margin
            maxValue *= 2;
            minValue *= 2;

            inputView.OnClusterChanged += (id) =>
            {
                currentInputIdx = id;
                RefreshInput();
            };
            outputView.OnClusterChanged += (id) =>
            {
                currentClusterIdx = id;
                RefreshOutput();
            };

            RefreshInput();
        }
        public override void Initialize(string name, XmlElement xmlConfig)
        {
            base.Initialize(name, xmlConfig);

            _dataset = CreateDataset();
            _dataset.LoadFromFile(DatasetFileName);

            samples = _dataset.GetSamplesMatrix();

            nbInputs = _dataset.InputCount;
            n = samples.GetLength(1);
            m = samples.GetLength(2);
        }
        public MapClusteringView(IGenomeDecoder<NeatGenome, IBlackBox> genomeDecoder,
                                IMapClusteringDataset dataset,
                                MapClusteringEvaluator evaluator,
                                int nbClusters)
            : this()
        {
            this.dataset = dataset;
            this.nbClusters = nbClusters;
            this.decoder = genomeDecoder;
            this.evaluator = evaluator;

            samples = dataset.GetSamplesMatrix();
            outputs = new double[nbClusters, samples.GetLength(1), samples.GetLength(2)];

            inputView.LabelName = "Input";
            outputView.LabelName = "Output";

            inputView.SetDimensions(samples.GetLength(0), samples.GetLength(1), samples.GetLength(2));
            outputView.SetDimensions(nbClusters, samples.GetLength(1), samples.GetLength(2));

            maxValue = 0.0;
            minValue = double.PositiveInfinity;
            for (var i = 0; i < samples.GetLength(0); i++)
            {
                for (var j = 0; j < samples.GetLength(1); j++)
                {
                    for (var k = 0; k < samples.GetLength(2); k++)
                    {
                        var value = samples[i, j, k];
                        if (value > maxValue) maxValue = value;
                        if (value < minValue) minValue = value;
                    }
                }
            }
            // Add some margin
            maxValue *= 2;
            minValue *= 2;

            inputView.OnClusterChanged += (id) =>
            {
                currentInputIdx = id;
                RefreshInput();
            };
            outputView.OnClusterChanged += (id) =>
            {
                currentClusterIdx = id;
                RefreshOutput();
            };

            RefreshInput();
        }
        /// <summary>
        /// Construct evaluator with the provided task arguments/variables.
        /// </summary>
        public MapClusteringEvaluator(IMapClusteringDataset dataset, int nbClusters, Phenotype phenotype)
        {
            this.nbClusters = nbClusters;
            this.phenotype = phenotype;

            // Build input layers (samples matrices)
            nbInputs = dataset.InputCount;
            samples = dataset.GetSamplesMatrix();

            // Extract useful values
            n = samples.GetLength(1); // layers width
            m = samples.GetLength(2); // layers height
            nbInputsNN = samples.Length;
            nbOutputsNN = nbClusters * n * m;
        }
        /// <summary>
        /// Construct evaluator with the provided task arguments/variables.
        /// </summary>
        public WindowMapClusteringEvaluator(IMapClusteringDataset dataset, int nbClusters, Phenotype phenotype, bool[,] filter)
        {
            this.nbClusters = nbClusters;
            this.phenotype = phenotype;
            this.filter = filter;

            Debug.Assert(filter.GetLength(0) % 2 != 0 && filter.GetLength(1) % 2 != 0);

            // Build input layers (samples matrices)
            nbInputs = dataset.InputCount;
            samples = dataset.GetSamplesMatrix();

            // Extract useful values
            f = filter.GetLength(0); // filter width
            f2 = filter.Length; // f^2
            t = (f - 1) / 2; // filter thickness
            nbInputsNN = nbInputs * f2;
            nbOutputsNN = nbClusters * f2;
            n = samples.GetLength(1); // layers width
            m = samples.GetLength(2); // layers height
        }
        public void Initialize(IGenomeDecoder<NeatGenome, IBlackBox> genomeDecoder, IMapClusteringDataset dataset, MapClusteringEvaluator evaluator, int nbClusters)
        {
            this.dataset = dataset;
            this.nbClusters = nbClusters;
            this.decoder = genomeDecoder;
            this.evaluator = evaluator;

            samples = dataset.GetSamplesMatrix();
            outputs = new double[nbClusters, samples.GetLength(1), samples.GetLength(2)];
            this.nbInputs = samples.GetLength(0);

            maxValue = 0.0;
            for (var i = 0; i < samples.GetLength(0); i++)
            {
                for (var j = 0; j < samples.GetLength(1); j++)
                {
                    for (var k = 0; k < samples.GetLength(2); k++)
                    {
                        var value = samples[i, j, k];
                        if (value > maxValue) maxValue = value;
                    }
                }
            }
            maxValue *= 2; // margin
        }