public void DimmerVsOne_Azimuth45_EffectiveCrossExt()
        {
            // Arrange
            var radiuses = new List <double> {
                4, 10, 20, 40
            };
            var    distance     = 0;
            string dirAzimuth45 = "DimmerVsOne_Azimuth45_EffectiveCrossExt";
            string dirAzimOne   = "OneParticle_EffectiveCrossExt";

            foreach (double radius in radiuses)
            {
                var gp = new GnuPlot();
                setLineStyle(gp);
                gp.HoldOn();
                Dictionary <double, double> azim45 = SimpleFormatter.Read(
                    this.getFileFormat(dirAzimuth45, distance, radius))
                                                     .Where(x => x.Key <= 500)
                                                     .ToDictionary(x => x.Key * 1e9, x => x.Value * 2);
                gp.Plot(azim45, string.Format(@"title ""{0}""", distance));

                Dictionary <double, double> azimOne = SimpleFormatter.Read(
                    this.getFileFormatOneParticle(dirAzimOne, radius))
                                                      .Where(x => x.Key <= 500)
                                                      .ToDictionary(x => x.Key * 1e9, x => x.Value * 2);
                gp.Plot(azimOne, string.Format(@"title ""{0}""", 0));
            }
        }
Exemple #2
0
        public static void PlotData(Matrix <double> X, Vector <double> y)
        {
            List <(double x1, double x2)> pos = new List <(double x1, double x2)>();
            List <(double x1, double x2)> neg = new List <(double x1, double x2)>();

            for (int i = 0; i < y.Count; i++)
            {
                if (y[i] == 1)
                {
                    pos.Add((X[i, 0], X[i, 1]));
                }
                else
                {
                    neg.Add((X[i, 0], X[i, 1]));
                }
            }


            GnuPlot.HoldOn();
            GnuPlot.Set("title \"\"");
            GnuPlot.Set("xlabel \"Microchip test 1\"");
            GnuPlot.Set("ylabel \"Microchip test 2\"");
            GnuPlot.Plot(pos.Select(p => p.x1).ToArray(), pos.Select(p => p.x2).ToArray(), "pt 1 ps 1 lc rgb \"black\" title \"y=1\"");

            GnuPlot.Plot(neg.Select(p => p.x1).ToArray(), neg.Select(p => p.x2).ToArray(), "pt 7 ps 1 lc rgb \"yellow\" title \"y=0\"");
        }
Exemple #3
0
        public void TestMethod1()
        {
            Stopwatch watch = new Stopwatch();

            var gp = new GnuPlot();

            gp.HoldOn();
            for (int j = 0; j < 5; j++)
            {
                List <TimeSpan> list = new List <TimeSpan>();

                for (var i = 1; i <= 16; i++)
                {
                    watch.Start();
                    ParallelIterator.MaxDegreeOfParallelism = i;

                    FDTDProgram.Calculate();
                    watch.Stop();
                    list.Add(watch.Elapsed);
                    watch.Reset();
                }

                gp.Plot(list.Select(x => (double)x.Milliseconds));
            }
            gp.Wait();
        }
        public void RadiusChangeOutput_InterparticleDistance_Spectrum()
        {
            // Arrange
            GnuPlot gp       = null;
            var     radius1  = 20;
            var     radiuses = new List <double> {
                4, 10, 15, 20
            };
            double distance     = 70;
            string dirAzimuth45 = "RadiusChangeOutput_InterparticleDistance_Spectrum";

            //foreach (var radius1 in radiuses)
            //{
            gp = new GnuPlot();
            setLineStyle(gp);
            gp.HoldOn();
            setColorPalette(gp);

            gp.Set(String.Format("title \"{0}\"", radius1));

            foreach (double radius in radiuses)
            {
                Dictionary <double, double> azim45 = SimpleFormatter.Read(
                    this.getFileFormatDiffRadiuses(dirAzimuth45, distance, radius1, radius))
                                                     .ToDictionary(x => x.Key * 1e9, x => x.Value);
                gp.Plot(azim45, string.Format(@"title ""{0}""", radius));

                //gp.Clear();
            }
            //}
            gp.Wait();
        }
        public void AreClose_Azimuth45_AzimuthSum()
        {
            // Arrange
            const int    DistanceMax  = 3;
            const double DistanceStep = 0.1;
            var          radiuses     = new List <double> {
                4, 10, 20, 40, 70, 100, 200
            };
            List <double> distances     = getDistances(DistanceStep, DistanceMax);
            string        dirAzimuthSum = "RadiusDistanceOutput_AzimuthSum";
            string        dirAzimuth45  = "RadiusDistanceOutput_Azimuth45";
            var           gp            = new GnuPlot();

            setLineStyle(gp);

            foreach (double radius in radiuses)
            {
                foreach (double distance in distances)
                {
                    Dictionary <double, double> azim45 = SimpleFormatter.Read(
                        this.getFileFormat(dirAzimuth45, distance, radius));
                    Dictionary <double, double> azimSum = SimpleFormatter.Read(
                        this.getFileFormat(dirAzimuthSum, distance, radius));
                    gp.HoldOn();

                    gp.Plot(azim45);
                    gp.Plot(azimSum);
                    gp.HoldOff();
                    AssertHelper.DictionaryAreClose(azim45, azimSum, 0.5);
                }
            }
        }
        public void AreClose_Radius40_OpticalConst_DrudeLorentz()
        {
            // Arrange
            const double  DistanceMax  = 0.5;
            const double  DistanceStep = 0.1;
            List <double> distances    = getDistances(DistanceStep, DistanceMax);
            var           radius       = 40;

            string dirOpticalConst = "RadiusDistanceOutput_Azimuth45_EffectiveCrossExt";
            string dirDrudeLorentz = "RadiusDistanceDrudeLorentz_Azimuth45_EffectiveCrossExt";
            var    gp = new GnuPlot();

            setLineStyle(gp);
            gp.HoldOn();

            foreach (double distance in distances)
            {
                Dictionary <double, double> optical = SimpleFormatter.Read(
                    this.getFileFormat(dirOpticalConst, distance, radius));
                Dictionary <double, double> drudeLorentz = SimpleFormatter.Read(
                    this.getFileFormat(dirDrudeLorentz, distance, radius));

                gp.Plot(optical, @"title ""optical""");
                gp.Plot(drudeLorentz, @"title ""drude-lorentz""");

                //AssertHelper.DictionaryAreClose(optical, drudeLorentz, 0.1);
            }

            gp.Wait();
        }
        public void Peaks_Azimuth0_Azimuth90()
        {
            // Arrange
            const int    DistanceMax  = 3;
            const double DistanceStep = 0.1;
            var          radiuses     = new List <double> {
                4, 10, 20, 40
            };
            List <double> distances    = getDistances(DistanceStep, DistanceMax);
            string        dirAzimuth0  = "RadiusDistanceOutput_Azimuth0";
            string        dirAzimuth90 = "RadiusDistanceOutput_Azimuth90";
            var           gp           = new GnuPlot();

            gp.Set("style data lines");
            gp.Set("xtics 0.5");
            gp.Set("grid xtics ytics");
            gp.Set("size square");
            gp.HoldOn();
            radiuses.Reverse();
            foreach (double radius in radiuses)
            {
                Dictionary <double, double> peaks0  = this.getPeaks0(distances, radius, dirAzimuth0);
                Dictionary <double, double> peaks90 = this.getPeaks90(distances, radius, dirAzimuth90);

                //gp.HoldOn();
                // gp.Set(string.Format("terminal win {0}", radius));
                gp.Plot(peaks0);
                gp.Plot(peaks90);
                // gp.HoldOff();
            }
            gp.Wait();
        }
        public void AreCloseDistance3_OpticalConst_DrudeLorentz()
        {
            // Arrange
            var distance = 2.9;
            var radiuses = new List <double> {
                4, 10, 20, 40, 70, 100, 200
            };

            string dirOpticalConst = "RadiusDistanceOutput_Azimuth45_EffectiveCrossExt";
            string dirDrudeLorentz = "RadiusDistanceDrudeLorentz_Azimuth45_EffectiveCrossExt";
            var    gp = new GnuPlot();

            setLineStyle(gp);
            gp.HoldOn();

            foreach (double radius in radiuses)
            {
                Dictionary <double, double> optical = SimpleFormatter.Read(
                    this.getFileFormat(dirOpticalConst, distance, radius));
                Dictionary <double, double> drudeLorentz = SimpleFormatter.Read(
                    this.getFileFormat(dirDrudeLorentz, distance, radius));

                gp.Plot(optical, @"title ""optical""");
                gp.Plot(drudeLorentz, @"title ""drude-lorentz""");

                //AssertHelper.DictionaryAreClose(optical, drudeLorentz, 0.1);
            }

            gp.Wait();
        }
        public void RadiusChangeOutput_Azimuth_Spectrum()
        {
            // Arrange
            const int    DistanceMax  = 3;
            const double DistanceStep = 0.1;

            var radius1  = 4;
            var radiuses = new List <double> {
                4, 10, 20, 40, 70, 100, 200
            };
            List <double> distances    = getDistances(DistanceStep, DistanceMax);
            string        dirAzimuth45 = "RadiusChangeOutput_Azimuth45";

            var gp = new GnuPlot();

            gp.Set("style data lines");
            gp.HoldOn();
            foreach (double radius in radiuses)
            {
                Dictionary <decimal, List <double> > spectrum = this.zipToDictionaryDiffRadiuses(distances, dirAzimuth45, radius1, radius);
                string filename = Path.Combine(BasePath, this.TestContext.TestName, "Azim45.txt");
                SimpleFormatter.WriteDictionary(filename, spectrum, distances);

                foreach (double distance in distances.Take(5))
                {
                    Dictionary <double, double> azim45 = SimpleFormatter.Read(
                        this.getFileFormatDiffRadiuses(dirAzimuth45, distance, radius1, radius));
                    gp.Plot(azim45, string.Format(@"title ""{0}""", radius));
                }
                gp.Clear();
            }


            gp.Wait();
        }
        public void Calculate_PerformanceMetrics()
        {
            var           serialTicks = 192769194.79518071;
            List <double> all         = new List <double>();
            var           gp          = new GnuPlot();

            gp.Set("style data linespoints");
            gp.HoldOn();

            for (int i = 256; i <= 1024; i = i * 2)
            {
                List <long> list = new List <long>();
                for (int j = 0; j < 20; j++)
                {
                    Stopwatch watch = Stopwatch.StartNew();
                    //ArrayExtensions.MaxDegreeOfParallelism = i;

                    FDTDProgram.Calculate();
                    watch.Stop();
                    list.Add(watch.ElapsedTicks);
                }
                all.Add(list.Average());
            }

            gp.Plot(all.Select(x => serialTicks / x));

            gp.Wait();
        }
        public void CalculateOpticalConstants_DrudeLorentz_Gnuplot()
        {
            // Arrange
            var optConst     = ParameterHelper.ReadOpticalConstants("opt_const.txt");
            var drudeLorentz = new DrudeLorentz();
            var dict         = new Dictionary <double, Complex>();

            foreach (var waveLength in optConst.WaveLengthList)
            {
                var freq = new SpectrumUnit(waveLength / OpticalConstants.WaveLengthMultiplier,
                                            SpectrumUnitType.WaveLength);
                dict.Add(waveLength, drudeLorentz.GetPermittivity(freq));
            }

            ParameterHelper.WriteOpticalConstants("opt_const_drudeLorentz.txt", dict);

            using (var gp = new GnuPlot())
            {
                gp.HoldOn();
                gp.Set("style data lines");

                gp.Plot(getPermitivittyFunc(optConst));
                gp.Plot(dict);

                gp.Wait();
            }
            // Act

            // Assert
        }
Exemple #12
0
        public static void PlotData(Matrix <double> X, Vector <double> y)
        {
            List <(double x1, double x2)> pos = new List <(double x1, double x2)>();
            List <(double x1, double x2)> neg = new List <(double x1, double x2)>();

            for (int i = 0; i < y.Count; i++)
            {
                if (y[i] == 1)
                {
                    pos.Add((X[i, 0], X[i, 1]));
                }
                else
                {
                    neg.Add((X[i, 0], X[i, 1]));
                }
            }


            GnuPlot.HoldOn();
            GnuPlot.Set("title \"Data\"");
            //GnuPlot.Set("key bottom right");
            GnuPlot.Set("key outside noautotitle");
            //GnuPlot.Set("key title \"Legend\"");
            GnuPlot.Set("xlabel \"Exam 1 score\"");
            GnuPlot.Set("ylabel \"Exam 2 score\"");
            GnuPlot.Plot(pos.Select(p => p.x1).ToArray(), pos.Select(p => p.x2).ToArray(), "pt 1 ps 1 lc rgb \"black\" title \"Admitted\"");

            GnuPlot.Plot(neg.Select(p => p.x1).ToArray(), neg.Select(p => p.x2).ToArray(), "pt 7 ps 1 lc rgb \"yellow\" title \"Not admitted\"");
        }
Exemple #13
0
        private void button1_Click(object sender, EventArgs e)
        {
            GnuPlot gp = new GnuPlot();

            gp.HoldOn();
            gp.Unset("key");
            gp.Plot(NoisySine(1000, 1));
            gp.Plot(NoisySine(1000, 1.5));
            gp.Plot(NoisySine(1000, 2));
        }
Exemple #14
0
        private void button2_Click(object sender, EventArgs e)
        {
            GnuPlot gp = new GnuPlot();

            gp.HoldOn();
            gp.Set("title 'Phase-Locked Signals'");
            gp.Set("samples 2000");
            gp.Unset("key");
            gp.Plot("sin(x)");
            gp.Plot("cos(x)");
        }
        public void RadiusChangeOutputPeaks_Azimuth0_Azimuth90()
        {
            // Arrange
            const int    DistanceMax  = 3;
            const double DistanceStep = 0.1;
            var          radiuses     = new List <double> {
                4, 10, 20, 40, 70, 100, 200
            };
            var           radius1      = 4;
            List <double> distances    = getDistances(DistanceStep, DistanceMax);
            string        dirAzimuth0  = "RadiusChangeOutput_Azimuth0";
            string        dirAzimuth90 = "RadiusChangeOutput_Azimuth90";
            var           gp           = new GnuPlot();

            gp.Set("style data lines");
            gp.HoldOn();
            radiuses.Reverse();
            foreach (double radius in radiuses)
            {
                var peaks0 = new Dictionary <double, double>();

                var peaks90 = new Dictionary <double, double>();

                foreach (double distance in distances)
                {
                    Dictionary <double, double> azim0 = SimpleFormatter.Read(
                        this.getFileFormatDiffRadiuses(dirAzimuth0, distance, radius1, radius));
                    Dictionary <double, double> azim90 = SimpleFormatter.Read(
                        this.getFileFormatDiffRadiuses(dirAzimuth90, distance, radius1, radius));

                    peaks0.Add(distance, azim0.MaxPair().Key);

                    peaks90.Add(distance, azim0.MaxPair().Key);
                }
                // gp.HoldOn();
                // gp.Set(string.Format("terminal win {0}", radius));
                gp.Plot(peaks0);
                gp.Plot(peaks90);
                // gp.HoldOff();

                string basepath  = Path.Combine(BasePath, this.TestContext.TestName);
                string filename0 = Path.Combine(
                    basepath,
                    string.Format("peaks_0deg_{0}.txt", radius));
                SimpleFormatter.Write(filename0, peaks0);
                string filename90 = Path.Combine(
                    basepath,
                    string.Format("peaks_90deg_{0}.txt", radius));
                SimpleFormatter.Write(filename90, peaks90);
            }
            gp.Wait();
        }
Exemple #16
0
        // Plot J cost function
        private static void PlotJ(Matrix <double> X, Matrix <double> y, Matrix <double> theta)
        {
            // Grid over which we will calculate J
            double[] theta0_vals = MathNet.Numerics.Generate.LinearSpaced(100, -10, 10);
            double[] theta1_vals = MathNet.Numerics.Generate.LinearSpaced(100, -1, 4);

            // initialize J_vals to a matrix of 0's
            int size = theta0_vals.Length * theta1_vals.Length;

            double[] sx = new double[size];
            double[] sy = new double[size];
            double[] sz = new double[size];


            // Fill out J_vals
            int idx = 0;

            for (int i = 0; i < theta0_vals.Length; i++)
            {
                for (int k = 0; k < theta1_vals.Length; k++)
                {
                    Matrix <double> t = Matrix <double> .Build.Dense(2, 1);

                    t[0, 0] = theta0_vals[i];
                    t[1, 0] = theta1_vals[k];

                    sx[idx] = theta0_vals[i];
                    sy[idx] = theta1_vals[k];
                    sz[idx] = ComputeCost(X, y, t);
                    idx++;
                }
            }

            GnuPlot.HoldOn();
            GnuPlot.Set("terminal wxt 1");
            GnuPlot.Set("title \"Cost function J\"");
            GnuPlot.Set("key bottom right");
            GnuPlot.Set("xlabel \"{/Symbol q}_0\"");
            GnuPlot.Set("ylabel \"{/Symbol q}_1\"");

            // surface plot
            GnuPlot.SPlot(sx, sy, sz, "palette title \"J({/Symbol q}_0,{/Symbol q}_1)\"");

            // Contour plot
            GnuPlot.Set("terminal wxt 2");
            GnuPlot.Set("cntrparam levels auto 10", "logscale z", "xr[-10:10]", "yr[-1:4]");
            GnuPlot.Unset("key", "label");
            GnuPlot.Contour(sx, sy, sz);

            GnuPlot.Plot(new double[] { theta[0, 0] }, new double[] { theta[1, 0] }, "pt 2 ps 1 lc rgb \"red\"");
        }
Exemple #17
0
        private static void PlotValidationCurve(double[] x, double[] jtrain, double[] jvc)
        {
            GnuPlot.HoldOn();
            GnuPlot.Set("title \"Validation curve\"");
            GnuPlot.Set("xlabel \"Lamda\"");
            GnuPlot.Set("key top right box");
            GnuPlot.Set("ylabel \"Error\"");
            GnuPlot.Set("autoscale xy");

            GnuPlot.Plot(x, jtrain, "with lines ls 1 lw 2 lc rgb \"cyan\" title \"Train\" ");
            GnuPlot.Plot(x, jvc, "with lines ls 1 lw 2 lc rgb \"orange\" title \"Cross Validation\" ");

            GnuPlot.HoldOff();
        }
Exemple #18
0
        private static void PlotLinearLearningCurve(double[] x, double[] jtrain, double[] jvc)
        {
            GnuPlot.HoldOn();
            GnuPlot.Set("title \"Learning curve for linear regression\"");
            GnuPlot.Set("xlabel \"Number of training examples\"");
            GnuPlot.Set("key top right box");
            GnuPlot.Set("ylabel \"Error\"");
            GnuPlot.Set("xr[0:13]");
            GnuPlot.Set("yr[0:150]");

            GnuPlot.Plot(x, jtrain, "with lines ls 1 lw 2 lc rgb \"cyan\" title \"Train\" ");
            GnuPlot.Plot(x, jvc, "with lines ls 1 lw 2 lc rgb \"orange\" title \"Cross Validation\" ");

            GnuPlot.HoldOff();
        }
        [TestMethod]//todo
        public void RadiusChangeOutput_Azimuth_Spectrum()
        {
            // Arrange
            const int    DistanceMax  = 3;
            const double DistanceStep = 0.5;
            GnuPlot      gp           = null;
            var          radius1      = 4;
            var          radiuses     = new List <double> {
                4, 10, 20, 40
            };
            List <double> distances     = getDistances(DistanceStep, DistanceMax);
            string        dirAzimuth45  = "RadiusChangeOutput_Azimuth45_EffectiveExtinction";
            string        dirAzimuthOne = "OneParticle_EffectiveCrossExt";

            //foreach (var radius1 in radiuses)
            //{
            gp = new GnuPlot();
            setLineStyle(gp);

            foreach (double distance in distances)
            {
                gp.HoldOn();
                //gp.Set(String.Format("title \"{0}\"", radius1));

                foreach (double radius in radiuses)
                {
                    //Dictionary<decimal, List<double>> spectrum = this.zipToDictionaryDiffRadiuses(distances,
                    //    dirAzimuth45, radius1, radius);
                    //string filename = Path.Combine(BasePath, this.TestContext.TestName, "Azim45.txt");
                    //SimpleFormatter.WriteDictionary(filename, spectrum, distances);



                    Dictionary <double, double> azim45 = SimpleFormatter.Read(
                        this.getFileFormatDiffRadiuses(dirAzimuth45, distance, radius1, radius)).Where(x => x.Key <= 500).ToDictionary(x => x.Key * 1e9, x => x.Value);
                    gp.Plot(azim45, string.Format(@"title ""{0}""", radius));



                    gp.Clear();
                    Dictionary <double, double> azim = SimpleFormatter.Read(
                        this.getFileFormatOneParticle(dirAzimuthOne, radius)).Where(x => x.Key <= 500).ToDictionary(x => x.Key * 1e9, x => x.Value);
                    gp.Plot(azim, @"title ""single""");
                }
            }
            //}
            gp.Wait();
        }
Exemple #20
0
        private static void Main(string[] args)
        {
            string        fileTrain1     = "approximation_train_1.txt";
            string        fileTrain2     = "approximation_train_2.txt";
            string        fileTest       = "approximation_test.txt";
            string        filePathTrain1 = Path.GetFullPath(fileTrain1);
            string        filePathTrain2 = Path.GetFullPath(fileTrain2);
            string        filePathTest   = Path.GetFullPath(fileTest);
            List <double> outputValues   = new List <double>();

            DataGetter dataGetterTrain1 = new DataGetter(filePathTrain1);
            DataGetter dataGetterTrain2 = new DataGetter(filePathTrain2);
            DataGetter dataGetterTest   = new DataGetter(filePathTest);

            double learnRate             = 0.1;
            double momentum              = 0.1;
            int    numberOfRadialNeurons = 20;
            int    numberOfEpochs        = 300;

            //Console.WriteLine("SIEC NEURONOWA RBF WYKORZYSTYWANA DO APROKSYMACJI FUNKJI");
            //Console.WriteLine("Prosze wprowadzic wartosc wspolczynnika nauki:");
            //learnRate = Convert.ToDouble(Console.ReadLine(), System.Globalization.CultureInfo.InvariantCulture);
            //Console.WriteLine("Prosze wprowadzic wartosc wspolczynnika momentum:");
            //momentum = Convert.ToDouble(Console.ReadLine(), System.Globalization.CultureInfo.InvariantCulture);

            NeuralNetwork neuralNetwork = new NeuralNetwork(dataGetterTrain1.getInputData(), learnRate, momentum, numberOfRadialNeurons);

            Console.WriteLine("ZBIOR TRENINGOWY 1: ");
            neuralNetwork.Train(numberOfEpochs, dataGetterTrain2);
            Console.WriteLine("ZBIOR TRENINGOWY 2: ");
            neuralNetwork.Train(numberOfEpochs, dataGetterTrain1);
            Console.WriteLine("ZBIOR TESTOWY: ");
            outputValues = neuralNetwork.Test(dataGetterTest);

            GnuPlot.Set("term wxt 0");
            GnuPlot.HoldOn();
            GnuPlot.Set("xlabel 'X Values'");
            GnuPlot.Set("ylabel 'Y Values'");
            GnuPlot.Plot(dataGetterTest.getInputData().ToArray(), dataGetterTest.getExpectedData().ToArray(), "title 'funkcja oryginalna'");
            GnuPlot.Plot(dataGetterTest.getInputData().ToArray(), outputValues.ToArray(), "title 'funkcja po aproksymacji'");
            GnuPlot.HoldOff();
            GnuPlot.Set("term wxt 1");
            GnuPlot.Set("xlabel 'Numer epoki'");
            GnuPlot.Set("ylabel 'Wartosc bledu'");
            GnuPlot.Plot(neuralNetwork.ErrorX.ToArray(), neuralNetwork.ErrorY.ToArray(), "with lines title 'Blad aproksymacji'");
            Console.ReadKey();
        }
        [TestMethod]//todo
        public void Radius10_Azimuth_Spectrum()
        {
            // Arrange
            const int     DistanceMax  = 3;
            const double  DistanceStep = 0.5;
            int           radius       = 10;
            List <double> distances    = getDistances(DistanceStep, DistanceMax);
            string        dirAzimuth45 = "RadiusDistanceOutput_Azimuth45_EffectiveCrossExt";
            string        dirAzimuth0  = "RadiusDistanceOutput_Azimuth0_EffectiveCrossExt";
            string        dirAzimuth90 = "RadiusDistanceOutput_Azimuth90_EffectiveCrossExt";

            var gp = new GnuPlot();

            setLineStyle(gp);
            //Dictionary<decimal, List<double>> spectrum = this.zipToDictionary(distances, dirAzimuth45, radius);
            //string filename = Path.Combine(BasePath, this.TestContext.TestName, "Azim45.txt");
            //SimpleFormatter.WriteDictionary(filename, spectrum, distances);

            //spectrum = this.zipToDictionary(distances, dirAzimuth0, radius);
            //filename = Path.Combine(BasePath, this.TestContext.TestName, "Azim0.txt");
            //SimpleFormatter.WriteDictionary(filename, spectrum, distances);

            //spectrum = this.zipToDictionary(distances, dirAzimuth90, radius);
            //filename = Path.Combine(BasePath, this.TestContext.TestName, "Azim90.txt");
            //SimpleFormatter.WriteDictionary(filename, spectrum, distances);

            foreach (double distance in distances)
            {
                gp.HoldOn();
                Dictionary <double, double> azim45 = SimpleFormatter.Read(
                    this.getFileFormat(dirAzimuth45, distance, radius)).Where(x => x.Key <= 500).ToDictionary(x => x.Key * 1e9, x => x.Value * 2);
                gp.Plot(azim45, string.Format(@"title ""{0}""", distance));
                Dictionary <double, double> azim0 = SimpleFormatter.Read(
                    this.getFileFormat(dirAzimuth0, distance, radius)).Where(x => x.Key <= 500).ToDictionary(x => x.Key * 1e9, x => x.Value);
                gp.Plot(azim0, string.Format(@"title ""{0}""", distance));

                Dictionary <double, double> azim90 = SimpleFormatter.Read(
                    this.getFileFormat(dirAzimuth90, distance, radius)).Where(x => x.Key <= 500).ToDictionary(x => x.Key * 1e9, x => x.Value);
                gp.Plot(azim90, string.Format(@"title ""{0}""", distance));
            }



            //gp.Wait();
        }
Exemple #22
0
        private static (Matrix <double> centroids, Vector <double> idx) RunkMeans(Matrix <double> X, Matrix <double> initial_centroids, int max_iters, bool plot_progress)
        {
            // Plot the data if we are plotting progress
            if (plot_progress)
            {
                GnuPlot.HoldOn();
            }

            // Initialize values
            int             m                  = X.RowCount;
            int             n                  = X.ColumnCount;
            int             K                  = initial_centroids.RowCount;
            Matrix <double> centroids          = initial_centroids;
            Matrix <double> previous_centroids = centroids;
            Vector <double> idx                = Vector <double> .Build.Dense(m);

            // Run K-Means
            for (int i = 0; i < max_iters; i++)
            {
                // Output progress
                System.Console.WriteLine("K-Means iteration {0}/{1}...", i + 1, max_iters);

                // For each example in X, assign it to the closest centroid
                idx = FindClosestCentroids(X, centroids);

                // Optionally, plot progress here
                if (plot_progress)
                {
                    PlotProgresskMeans(X, centroids, previous_centroids, idx, K, i);
                    previous_centroids = centroids;
                    //Pause();
                }

                // Given the memberships, compute new centroids
                centroids = ComputeCentroids(X, idx, K);
            }

            if (plot_progress)
            {
                GnuPlot.HoldOff();
            }

            return(centroids, idx);
        }
        void PlotNutritionAndJumpmen()
        {
            GnuPlot.Set("xlabel 'Time [Seconds]'");
            GnuPlot.Set("ylabel 'Total nutrition'");
            GnuPlot.Set("y2label 'Amount of jumpmen'");
            GnuPlot.Set("ytics nomirror");
            GnuPlot.Set("y2tics");
            GnuPlot.Set("tics out");
            GnuPlot.Unset("yrange");
            GnuPlot.Unset("y2range");
            //GnuPlot.Set("autoscale y");
            //GnuPlot.Set("autoscale y2");
            GnuPlot.Set("key left top Left box 3");

            GnuPlot.HoldOn();
            GnuPlot.Plot(tracker.nutritionTmpPath, "using 1:2 title 'Nutrition' w l axes x1y1");
            GnuPlot.Plot(tracker.jumpmanCountTmpPath, "using 1:2 title 'Jumpmen' w lp axes x1y2");
            GnuPlot.HoldOff();
        }
        void PlotAverageSpeedAndSize()
        {
            GnuPlot.Set("xlabel 'Time [Seconds]'");
            GnuPlot.Set("ylabel 'Avg. speed'");
            GnuPlot.Set("y2label 'Avg. size'");
            GnuPlot.Set("ytics nomirror");
            GnuPlot.Set("y2tics");
            GnuPlot.Set("tics out");
            GnuPlot.Set(String.Format("yrange [{0}:{1}]", JumpmanAttributes.MIN_SPEED, JumpmanAttributes.MAX_SPEED));
            GnuPlot.Set(String.Format("y2range [{0}:{1}]", JumpmanAttributes.MIN_SIZE, JumpmanAttributes.MAX_SIZE));
            //GnuPlot.Set("autoscale y");
            //GnuPlot.Set("autoscale y2");
            GnuPlot.Set("key left top Left box 3");

            GnuPlot.HoldOn();
            GnuPlot.Plot(tracker.averageJumpmanAttrTmpPath, "using 1:5 title 'Speed' w lp axes x1y1");
            GnuPlot.Plot(tracker.averageJumpmanAttrTmpPath, "using 1:6 title 'Size'  w lp axes x1y2");
            GnuPlot.HoldOff();
        }
Exemple #25
0
        public void MakeContour(double[] xBound, double[] yBound)
        {
            int id = x.Count() - 1;

            double[] x1plot = new double[id + 1];
            double[] x2plot = new double[id + 1];
            for (int i = 0; i <= id; i++)
            {
                x1plot[i] = x[i][0];
                x2plot[i] = x[i][1];
            }
            string xr = "xr[" + xBound[0] + ":" + xBound[1] + "]";
            string yr = "yr[" + yBound[0] + ":" + yBound[1] + "]";

            GnuPlot.Unset("key");                                                      //hide the key or legend
            GnuPlot.HoldOn();

            GnuPlot.Set(xr, yr, "cntrparam levels 20", "isosamples 50", xr, yr, "decimalsign locale"); //notice cntrparam levels (# height levels)
            GnuPlot.Plot(x1plot, x2plot, "with linespoints linestyle 1");
            GnuPlot.Contour(filename, "lc rgb 'blue'");
        }
        public void CalculateOpticalConstants_Drude()
        {
            // Arrange
            var optConst = ParameterHelper.ReadOpticalConstants("opt_const.txt");

            var EpsInfinity = 3.9943;
            var OmegaP      = 1.369e+16;
            var DEps0       = 8.45e-1;
            var Gamma0      = 7.292e+13;

            var funcPermitivitty = new Dictionary <double, Complex>();

            foreach (var waveLength in optConst.WaveLengthList)
            {
                var omeg = SpectrumUnitConverter.Convert(waveLength / OpticalConstants.WaveLengthMultiplier,
                                                         SpectrumUnitType.WaveLength, SpectrumUnitType.CycleFrequency);
                var compl = EpsInfinity -
                            OmegaP * OmegaP /
                            (omeg * omeg -
                             Complex.ImaginaryOne * Gamma0 * omeg);
                funcPermitivitty.Add(waveLength, compl);
            }

            ParameterHelper.WriteOpticalConstants("opt_const_new.txt", funcPermitivitty);

            using (var gnuplot = new GnuPlot())
            {
                gnuplot.HoldOn();
                gnuplot.Plot(funcPermitivitty);

                var permitivittyList = getPermitivittyFunc(optConst);

                gnuplot.Plot(permitivittyList);
            }

            // Act

            // Assert
        }
        public void Radius10_Azimuth_Spectrum()
        {
            // Arrange
            const int     DistanceMax  = 3;
            const double  DistanceStep = 0.1;
            int           radius       = 10;
            List <double> distances    = getDistances(DistanceStep, DistanceMax);
            string        dirAzimuth45 = "RadiusDistanceOutput_Azimuth45_EffectiveCrossExt";
            string        dirAzimuth0  = "RadiusDistanceOutput_Azimuth0_EffectiveCrossExt";
            string        dirAzimuth90 = "RadiusDistanceOutput_Azimuth90_EffectiveCrossExt";

            var gp = new GnuPlot();

            gp.Set("style data lines");
            gp.HoldOn();

            Dictionary <decimal, List <double> > spectrum = this.zipToDictionary(distances, dirAzimuth45, radius);
            string filename = Path.Combine(BasePath, this.TestContext.TestName, "Azim45.txt");

            SimpleFormatter.WriteDictionary(filename, spectrum, distances);

            foreach (double distance in distances)
            {
                Dictionary <double, double> azim45 = SimpleFormatter.Read(
                    this.getFileFormat(dirAzimuth45, distance, radius));
                gp.Plot(azim45, string.Format(@"title ""{0}""", distance));
            }

            spectrum = this.zipToDictionary(distances, dirAzimuth0, radius);
            filename = Path.Combine(BasePath, this.TestContext.TestName, "Azim0.txt");
            SimpleFormatter.WriteDictionary(filename, spectrum, distances);

            spectrum = this.zipToDictionary(distances, dirAzimuth90, radius);
            filename = Path.Combine(BasePath, this.TestContext.TestName, "Azim90.txt");
            SimpleFormatter.WriteDictionary(filename, spectrum, distances);

            gp.Wait();
        }
        public void RadiusChangeOutput_Hybridization_Spectrum()
        {
            // Arrange
            const int    DistanceMax  = 3;
            const double DistanceStep = 0.5;
            GnuPlot      gp           = null;
            var          radius1      = 10;
            var          radiuses     = new List <double> {
                4, 10
            };
            List <double> distances    = getDistances(DistanceStep, DistanceMax);
            string        dirAzimuth90 = "RadiusChangeOutput_Azimuth90";
            string        dirAzimuth0  = "RadiusChangeOutput_Azimuth0";

            //foreach (var radius1 in radiuses)
            //{
            gp = new GnuPlot();
            setLineStyle(gp);

            //gp.Set(String.Format("title \"{0}\"", radius1));

            foreach (double radius in radiuses)
            {
                double distance = 0;
                gp.HoldOn();

                Dictionary <double, double> azim90 = SimpleFormatter.Read(
                    this.getFileFormatDiffRadiuses(dirAzimuth90, distance, radius1, radius)).Where(x => x.Key <= 500).ToDictionary(x => x.Key * 1e9, x => x.Value);
                gp.Plot(azim90, @"title ""90""");

                Dictionary <double, double> azim0 = SimpleFormatter.Read(
                    this.getFileFormatDiffRadiuses(dirAzimuth0, distance, radius1, radius)).Where(x => x.Key <= 500).ToDictionary(x => x.Key * 1e9, x => x.Value);
                gp.Plot(azim0, @"title ""0""");
            }

            //}
            gp.Wait();
        }
        public void RadiusChangeOutputPeaks_Azimuth0_Azimuth90()
        {
            // Arrange
            const int    DistanceMax  = 10;
            const double DistanceStep = 0.02;
            var          radiuses     = new List <double> {
                4, 10, 20, 40
            };
            var           radius1      = 4;
            List <double> distances    = getDistances(DistanceStep, DistanceMax);
            string        dirAzimuth0  = "RadiusChangeOutput_Azimuth0_EffectiveExtinction";
            string        dirAzimuth90 = "RadiusChangeOutput_Azimuth90_EffectiveExtinction";
            GnuPlot       gp           = null;

            gp = new GnuPlot();
            gp.HoldOn();
            radiuses.Reverse();
            //foreach (var radius1 in radiuses)
            //{
            gp.Set("style data lines");

            foreach (double radius in radiuses)
            {
                Dictionary <double, double> peaks0  = this.getPeaksDiffRad0(distances, radius1, radius, dirAzimuth0);
                Dictionary <double, double> peaks90 = this.getPeaksDiffRad90(distances, radius1, radius, dirAzimuth90);

                // gp.HoldOn();
                // gp.Set(string.Format("terminal win {0}", radius));
                gp.Plot(peaks0, string.Format(@"smooth acsplines title ""0.{0}""", radius));
                gp.Plot(peaks90, string.Format(@"smooth acsplines title ""90.{0}""", radius));
                // gp.HoldOff();
            }

            //}

            gp.Wait();
        }
Exemple #30
0
        static void Main(string[] args)
        {
            if (!System.Console.IsOutputRedirected)
            {
                System.Console.Clear();
            }

            CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");

            var M = Matrix <double> .Build;
            var V = Vector <double> .Build;


            //// =============== Part 1: Loading and Visualizing Data ================
            //  We start the exercise by first loading and visualizing the dataset.
            //  The following code will load the dataset into your environment and plot
            //  the data.
            //

            System.Console.WriteLine("Loading and Visualizing Data ...\n");

            // Load from ex6data1:
            // You will have X, y in your environment
            Dictionary <string, Matrix <double> > ms = MatlabReader.ReadAll <double>("data\\ex6data1.mat");

            Matrix <double> X = ms["X"];                 // 51 X 2
            Vector <double> y = ms["y"].Column(0);       // 51 X 1

            // Plot training data
            GnuPlot.HoldOn();
            PlotData(X, y);

            Pause();

            //// ==================== Part 2: Training Linear SVM ====================
            //  The following code will train a linear SVM on the dataset and plot the
            //  decision boundary learned.
            //

            System.Console.WriteLine("\nTraining Linear SVM ...\n");

            // You should try to change the C value below and see how the decision
            // boundary varies (e.g., try C = 1000)
            double C            = 1.0;
            var    linearKernel = KernelHelper.LinearKernel();

            List <List <double> > libSvmData = ConvertToLibSvmFormat(X, y);
            svm_problem           prob       = ProblemHelper.ReadProblem(libSvmData);
            var svc = new C_SVC(prob, linearKernel, C);

            PlotBoundary(X, svc);
            GnuPlot.HoldOff();

            System.Console.WriteLine();

            Pause();

            //// =============== Part 3: Implementing Gaussian Kernel ===============
            //  You will now implement the Gaussian kernel to use
            //  with the SVM. You should complete the code in gaussianKernel.m
            //

            System.Console.WriteLine("\nEvaluating the Gaussian Kernel ...\n");

            double sigma = 2.0;
            double sim   = GaussianKernel(
                V.DenseOfArray(new [] { 1.0, 2, 1 }),
                V.DenseOfArray(new [] { 0.0, 4, -1 }),
                sigma
                );

            System.Console.WriteLine("Gaussian Kernel between x1 = [1; 2; 1], x2 = [0; 4; -1], sigma = {0:f6} :\n\t{1:f6}\n(for sigma = 2, this value should be about 0.324652)\n", sigma, sim);

            Pause();

            //// =============== Part 4: Visualizing Dataset 2 ================
            //  The following code will load the next dataset into your environment and
            //  plot the data.
            //

            System.Console.WriteLine("Loading and Visualizing Data ...\n");

            // Load from ex6data2:
            // You will have X, y in your environment
            ms = MatlabReader.ReadAll <double>("data\\ex6data2.mat");

            X = ms["X"];                 // 863 X 2
            y = ms["y"].Column(0);       // 863 X 1

            // Plot training data
            GnuPlot.HoldOn();
            PlotData(X, y);

            Pause();

            //// ========== Part 5: Training SVM with RBF Kernel (Dataset 2) ==========
            //  After you have implemented the kernel, we can now use it to train the
            //  SVM classifier.
            //

            System.Console.WriteLine("\nTraining SVM with RBF Kernel (this may take 1 to 2 minutes) ...\n");

            // SVM Parameters
            C     = 1;
            sigma = 0.1;
            double gamma = 1 / (2 * sigma * sigma);

            var rbfKernel = KernelHelper.RadialBasisFunctionKernel(gamma);

            libSvmData = ConvertToLibSvmFormat(X, y);
            prob       = ProblemHelper.ReadProblem(libSvmData);
            svc        = new C_SVC(prob, rbfKernel, C);


            PlotBoundary(X, svc);
            GnuPlot.HoldOff();

            Pause();

            double acc = svc.GetCrossValidationAccuracy(10);

            System.Console.WriteLine("\nCross Validation Accuracy: {0:f6}\n", acc);

            Pause();

            //// =============== Part 6: Visualizing Dataset 3 ================
            //  The following code will load the next dataset into your environment and
            //  plot the data.
            //

            System.Console.WriteLine("Loading and Visualizing Data ...\n");

            // Load from ex6data2:
            // You will have X, y in your environment
            ms = MatlabReader.ReadAll <double>("data\\ex6data3.mat");

            Matrix <double> Xval;
            Vector <double> yval;

            X    = ms["X"];              // 211 X 2
            y    = ms["y"].Column(0);    // 211 X 1
            Xval = ms["Xval"];           // 200 X 2
            yval = ms["yval"].Column(0); // 200 X 1

            // Plot training data
            GnuPlot.HoldOn();
            PlotData(X, y);

            //// ========== Part 7: Training SVM with RBF Kernel (Dataset 3) ==========

            //  This is a different dataset that you can use to experiment with. Try
            //  different values of C and sigma here.
            //


            (C, sigma) = Dataset3Params(X, y, Xval, yval);

            gamma     = 1 / (2 * sigma * sigma);
            rbfKernel = KernelHelper.RadialBasisFunctionKernel(gamma);

            libSvmData = ConvertToLibSvmFormat(X, y);
            prob       = ProblemHelper.ReadProblem(libSvmData);
            svc        = new C_SVC(prob, rbfKernel, C);

            PlotBoundary(X, svc);

            GnuPlot.HoldOff();
            Pause();
        }