private INonlinearSolution _perform_itr(Rational var1_initial, Rational var2_initial, out int vidRow, out int vidVariable1, out int vidVariable2, out int vidVariable3, out int vidVariable4)
        {
            var solver = new NelderMeadSolver();

            // By CQN solver convention, the vid for a row will always be 0
            solver.AddRow(null, out vidRow);
            solver.AddGoal(vidRow, 0, true);
            // By CQN solver convention, first (and in this case only) variable always has the vid of 1
            solver.AddVariable(null, out vidVariable1);
            solver.AddVariable(null, out vidVariable2);
            solver.AddVariable(null, out vidVariable3);
            solver.AddVariable(null, out vidVariable4);
            //solver.AddVariable(null, out vidVariable4);

            Rational rVariable1 = var1_initial; solver.SetValue(vidVariable1, rVariable1);
            Rational rVariable2 = var2_initial; solver.SetValue(vidVariable2, rVariable2);
            //Rational rVariable2 = 0.0001; solver.SetValue(vidVariable2, rVariable2);
            Rational rVariable3 = -0.2; solver.SetValue(vidVariable3, rVariable3);
            Rational rVariable4 = 0.0; solver.SetValue(vidVariable4, rVariable4);

            //Setting the evaluators
            //solver.FunctionEvaluator = ((m,r,v,n) => { return Math.Pow(v[1] + _decay[1], 2); });
            solver.FunctionEvaluator = this.SinxValue;
            //solver.GradientEvaluator = SinxGradient;

            var param = new NelderMeadSolverParams();

            //param.MaximumSearchPoints = 10;

            return(solver.Solve(param));
        }
Exemplo n.º 2
0
        public void Config(NelderMeadSolver solver)
        {
            Configuration = new NelderMeadSolverParams();

            Vector3D pos = FEstimatedPosition[0];
            Vector3D min = pos - 0.5 * FTolerancePosition[0];
            Vector3D max = pos + 0.5 * FTolerancePosition[0];

            solver.SetBounds(1, min.x, max.x);             // translation
            solver.SetBounds(2, min.y, max.y);
            solver.SetBounds(3, min.z, max.z);

            for (int b = 4; b <= 6; b++)
            {
                solver.SetBounds(b, -0.5, 0.5);     // rotation
            }
            solver.SetBounds(7, 0.05, 0.49);        // fov
            solver.SetBounds(8, -1, 1);             // shift x
            solver.SetBounds(9, -1, 1);             // shift y


            solver.SetValue(1, pos.x);
            solver.SetValue(2, pos.y);
            solver.SetValue(3, pos.z);

            solver.SetValue(4, VMath.Map(VMath.Random.Next(100), 0, 100, -0.05, 0.05, TMapMode.Float));
            solver.SetValue(5, VMath.Map(VMath.Random.Next(100), 0, 100, -0.05, 0.05, TMapMode.Float));
            solver.SetValue(6, VMath.Map(VMath.Random.Next(100), 0, 100, -0.05, 0.05, TMapMode.Float));

            solver.SetValue(7, 0.01);
            solver.SetValue(8, 0.01);
            solver.SetValue(9, 0.20);
        }
Exemplo n.º 3
0
        public Doll EstimateSingleFrame(float w, float h, List <Keypoint> keypoints)
        {
            // Setup unknown variables' information
            var estimationDoll = new Doll();

            double[] unknowns;
            double[] lowerLimits;
            double[] upperLimits;
            InitializeInputArrays(estimationDoll, out unknowns, out lowerLimits, out upperLimits);
            double[] unknowns2 = new double[unknowns.Length];

            // Call Nelder-mead solver in Microsoft.Solver.Foundation librabry
            var solution = NelderMeadSolver.Solve(
                (input) =>
            {
                ReflectDecisionsToDoll(input, estimationDoll);
                estimationDoll.RenewAllPositions();
                return(estimationDoll.CalculateResidualSum(w, h, (float)input[0], keypoints));
            },
                unknowns, lowerLimits, upperLimits);

            Debug.WriteLine($"{solution.Result}");
            Debug.WriteLine($"Solution = {solution.GetSolutionValue(0)}");

            // Output
            return(estimationDoll);
        }
        static void Main(string[] args)
        {
            double[] xInitial = new double[17] {
                1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
            };
            double[] xLower = new double[17];
            xLower.Populate(-5);
            double[] xUpper = new double[17];
            xUpper.Populate(5);

            Matrix <Double> featureValues = DenseMatrix.OfArray(readFileIntoArray("testData"));

            Vector <Double> trueValues = DenseVector.OfArray(readResultFileIntoArray("saveResult"));

            var solution = NelderMeadSolver.Solve(x => MyCostFunctionMethod(x, featureValues, trueValues), xInitial, xLower, xUpper);

            Console.WriteLine(solution.Result);
            Console.WriteLine("solution = {0}", solution.GetSolutionValue(0));
            for (int i = 0; i < 17; i++)
            {
                Console.WriteLine("x = {0}", solution.GetValue(i + 1));
            }

            Console.ReadKey();
        }
Exemplo n.º 5
0
        static public void CalibrateToSwaptionValues(double[] inputVs
                                                     , SimpleBermudanSwaption[] europeanSwaptions
                                                     , double a, double init_sigma, out double sigma)
        {
            double[] xInitial = new double[] { init_sigma };
            double[] xLower   = new double[] { 1e-4 };
            double[] xUpper   = new double[] { 10 };
            var      solution = NelderMeadSolver.Solve(x =>
            {
                double J, J1 = 0D, J2 = 0D;
                ComputeSwaptionCalibrationObjectives(false, inputVs, europeanSwaptions, a, x[0], out J, ref J1, ref J2);
                Console.WriteLine("J={0},sigma={1}", J, x[0]);
                return(J);
            }, xInitial, xLower, xUpper);

            sigma = solution.GetValue(1);
            Console.WriteLine(solution.ToString());
        }
Exemplo n.º 6
0
        public NelderMeadSolver Init()
        {
            var solver = new NelderMeadSolver();

            int vidRow;

            solver.AddRow(null, out vidRow);
            solver.AddGoal(vidRow, 0, true);

            int[] vidVariables = new int[dimensions];
            for (int i = 0; i < dimensions; i++)
            {
                solver.AddVariable(null, out vidVariables[i]);
            }

            solver.FunctionEvaluator = DiffMapping;

            Solvers.Clear();
            Solvers.Add(solver);

            return(solver);
        }
        /// <summary>
        /// Execute optimisation of theta values based on training data.
        /// </summary>
        /// <param name="theta">Current values of theta.</param>
        /// <param name="featureData">values of features.</param>
        /// <param name="result">List of results based on feature values.</param>
        /// <returns>Optimised values of theta</returns>
        public static double[] Learn(double[] theta, double[,] featureData, double[] results)
        {
            double[] xInitial = theta;
            double[] xLower   = new double[theta.Length];
            xLower.Populate(-5);
            double[] xUpper = new double[theta.Length];
            xUpper.Populate(5);

            Matrix <Double> featureValues = DenseMatrix.OfArray(featureData);

            Vector <Double> trueValues = DenseVector.OfArray(results);

            var solution = NelderMeadSolver.Solve(x => CostFunction(x, featureValues, trueValues), xInitial, xLower, xUpper);

            double[] optimisedTheta = new double[theta.Length];
            //Console.WriteLine(solution.Result);

            for (int i = 0; i < theta.Length; i++)
            {
                optimisedTheta[i] = solution.GetValue(i + 1);
            }

            return(optimisedTheta);
        }
Exemplo n.º 8
0
        public double computeFWHM()
        {
            // these all need to be arrays, because that's the way the NelderMeadSolver works
            double[] coeffs = new double[]
            { initialParams.intensity,
              initialParams.wavelength,
              initialParams.width,
              initialParams.baseline };

            ////////////////////////////////////////////////////////////////////
            // Bound the search
            ////////////////////////////////////////////////////////////////////

            // TODO: add a method to override these from the caller
            // TODO: find a way to "optimize" these based on initial conditions
            //       (an optimizer on the optimizer...yes I see the irony)
            //
            // (note we call the x-axis "wavelength," but sometimes it may be wavenumber or just pixel)
            //                              int     wl width    base
            double[] min = new double[] { 0, -1000, 0.1, 0 };
            double[] max = new double[] { 65535, 3500, 50, 65535 };

            // consider bounding things a bit closer than that, based on initial conditions:

            // min[0] = coeffs[0] * 0.5;   // intensity should be +/- 50% initial guess
            // max[0] = coeffs[0] * 1.5;

            // min[1] = coeffs[1] - 5 ;    // wavelength shouldn't vary by more than 20,
            // max[1] = coeffs[1] + 5 ;    // whether wavelength, wavenumber or pixel

            // max[3] = coeffs[0];         // baseline certainly shouldn't exceed peak height

            ////////////////////////////////////////////////////////////////////
            // run solver
            ////////////////////////////////////////////////////////////////////

            var solution = NelderMeadSolver.Solve(x => computeGaussianFitQuality(x[0], x[1], x[2], x[3]), coeffs, min, max);

            ////////////////////////////////////////////////////////////////////
            // post-process results
            ////////////////////////////////////////////////////////////////////

            optimalParams            = new Params(initialParams);
            optimalParams.intensity  = solution.GetValue(1); // 1-indexed
            optimalParams.wavelength = solution.GetValue(2);
            optimalParams.width      = solution.GetValue(3);
            optimalParams.baseline   = solution.GetValue(4);
            optimalParams.computeGaussian();

            // assuming width has been properly optimized now
            double fwhm = 2.0 * Math.Sqrt((2 * Math.Log(2))) * optimalParams.width;

            // generate report
            logger.log("");
            logger.log("NelderMeadSolver:");
            logger.log("  Initial: intensity {0:f2}, wavelength {1:f2}, width {2:f2}, baseline {3:f2}", initialParams.intensity, initialParams.wavelength, initialParams.width, initialParams.baseline);
            logger.log("  Optimal: intensity {0:f2}, wavelength {1:f2}, width {2:f2}, baseline {3:f2}", optimalParams.intensity, optimalParams.wavelength, optimalParams.width, optimalParams.baseline);
            for (int i = 0; i < initialParams.xvalues.Count; i++)
            {
                logger.log("  {0}, {1:f2}, {2:f2}, {3:f2}{4}",
                           i,
                           initialParams.xvalues[i],
                           initialParams.yvalues[i],
                           optimalParams.yvalues[i],
                           i == ((initialParams.xvalues.Count - 1) / 2) ? ", peak" : "");
            }

            return(fwhm);
        }