Ejemplo n.º 1
0
        private void startBatchRunButton_Click(object sender, EventArgs e)
        {
            startBatchRunButton.Enabled     = false;
            batchRunProgressListBox.Enabled = false;

            batchRunInfo += "%% Optimization method: " + Enum.Parse(typeof(OptimizationMethod), OptimizationMethod.GA.ToString()) + "\r\n";
            batchRunInfo += "%% Number of generations: " + optimizationSettings.NumberOfGenerations.ToString("0") + "\r\n";
            batchRunInfo += "%% Population size: " + optimizationSettings.PopulationSize.ToString("0") + "\r\n";
            batchRunInfo += "%% Tournament selection rate: " + optimizationSettings.TournamentSelectionParameter.ToString("0.00") + "\r\n";
            batchRunInfo += "%% Tournament size: " + optimizationSettings.TournamentSize.ToString("0") + "\r\n";
            batchRunInfo += "%% Crossover probability: " + optimizationSettings.CrossoverProbability.ToString("0.00") + "\r\n";
            batchRunInfo += "%% Relative mutation rate: " + optimizationSettings.RelativeMutationProbability.ToString("0.00") + "\r\n";
            batchRunInfo += "%% Creep mutation rate: " + optimizationSettings.CreepMutationRate.ToString("0.00") + "\r\n";
            batchRunInfo += "%% Road file name " + roadFileName + "\r\n";
            batchRunInfo += "%% RunID, BestFitness(=1/fc), AverageFitness, [variables], IndexOfTheVariableVector, NumberOfEvaluatedIndividuals \r\n";

            PlotRoadProfile(roadPlot2DPanel);
            batchRunProgressListBox.Items.Clear();
            bestIndividualsList = new List <OptimizableStructure>();

            OptimizationMethod optimizationMethod = OptimizationMethod.GA;

            int numberOfBatchRuns = int.Parse(numberOfBatchRunsTextBox.Text);

            batchRunThread = new Thread(new ThreadStart(() => BatchRunLoop(numberOfBatchRuns, optimizationSettings, optimizationMethod)));
            batchRunThread.Start();
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Generates the R script which performs the optimization.
        /// </summary>
        /// <param name="fileName">File path to which the R code will be saved.</param>
        /// <param name="outputPath">Directory/path to which output results will be saved. This is passed as a parameter to croptimizR.</param>
        /// <param name="apsimxFileName">Name of the .apsimx file to be run by the optimisation.</param>
        private void GenerateRScript(string fileName, string outputPath, string apsimxFileName)
        {
            // tbi: package installation. Need to test on a clean VM.
            StringBuilder contents = new StringBuilder();

            contents.AppendLine($"variable_names <- c({string.Join(", ", VariableNames.Select(x => $"'{x.Trim()}'").ToArray())})");

            // If we're reading from the PredictedObserved table, need to fix
            // Predicted./Observed. suffix for the observed variables.
            string[] sanitisedObservedVariables = GetObservedVariableName().Select(x => $"'{x.Trim()}'").ToArray();
            string   dateVariable = VariableNames.Any(v => v.StartsWith("Predicted.")) ? "Predicted.Clock.Today" : "Clock.Today";

            contents.AppendLine($"observed_variable_names <- c({string.Join(", ", sanitisedObservedVariables)}, '{dateVariable}')");
            contents.AppendLine($"apsimx_path <- '{typeof(IModel).Assembly.Location.Replace(@"\", @"\\")}'");
            contents.AppendLine($"apsimx_file <- '{apsimxFileName.Replace(@"\", @"\\")}'");
            contents.AppendLine($"simulation_names <- {GetSimulationNames()}");
            contents.AppendLine($"predicted_table_name <- '{PredictedTableName}'");
            contents.AppendLine($"observed_table_name <- '{ObservedTableName}'");
            contents.AppendLine($"param_info <- {GetParamInfo()}");
            contents.AppendLine();
            contents.AppendLine(OptimizationMethod.GenerateOptimizationOptions("optim_options"));
            contents.AppendLine($"optim_options$path_results <- '{outputPath.Replace(@"\", @"\\")}'");
            if (RandomSeed != null)
            {
                contents.AppendLine($"optim_options$ranseed <- {RandomSeed}");
            }
            contents.AppendLine();
            contents.AppendLine($"crit_function <- {OptimizationMethod.CritFunction}");
            contents.AppendLine($"optim_method <- '{OptimizationMethod.ROptimizerName}'");
            contents.AppendLine();
            contents.Append(ReflectionUtilities.GetResourceAsString("Models.Resources.RScripts.OptimizR.r"));

            File.WriteAllText(fileName, contents.ToString());
        }
Ejemplo n.º 3
0
 public void calibrateVolatilitiesIterative(CalibrationHelperVector helpers, OptimizationMethod method, EndCriteria endCriteria, Constraint constraint, DoubleVector weights)
 {
     NQuantLibcPINVOKE.Gsr_calibrateVolatilitiesIterative__SWIG_0(swigCPtr, CalibrationHelperVector.getCPtr(helpers), OptimizationMethod.getCPtr(method), EndCriteria.getCPtr(endCriteria), Constraint.getCPtr(constraint), DoubleVector.getCPtr(weights));
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Ejemplo n.º 4
0
 public void calibrateVolatilitiesIterative(CalibrationHelperVector helpers, OptimizationMethod method, EndCriteria endCriteria)
 {
     NQuantLibcPINVOKE.Gsr_calibrateVolatilitiesIterative__SWIG_2(swigCPtr, CalibrationHelperVector.getCPtr(helpers), OptimizationMethod.getCPtr(method), EndCriteria.getCPtr(endCriteria));
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
 public void calibrate(CalibrationHelperVector instruments, OptimizationMethod method, EndCriteria endCriteria, Constraint constraint, DoubleVector weights, BoolVector fixParameters)
 {
     NQuantLibcPINVOKE.Gsr_calibrate__SWIG_0(swigCPtr, CalibrationHelperVector.getCPtr(instruments), OptimizationMethod.getCPtr(method), EndCriteria.getCPtr(endCriteria), Constraint.getCPtr(constraint), DoubleVector.getCPtr(weights), BoolVector.getCPtr(fixParameters));
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Ejemplo n.º 6
0
 public virtual void calibrate(CalibrationHelperVector arg0, OptimizationMethod arg1, EndCriteria arg2, Constraint constraint, DoubleVector weights, BoolVector fixParameters)
 {
     NQuantLibcPINVOKE.CalibratedModel_calibrate__SWIG_0(swigCPtr, CalibrationHelperVector.getCPtr(arg0), OptimizationMethod.getCPtr(arg1), EndCriteria.getCPtr(arg2), Constraint.getCPtr(constraint), DoubleVector.getCPtr(weights), BoolVector.getCPtr(fixParameters));
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
 public void calibrate(BlackCalibrationHelperVector helper, OptimizationMethod method, EndCriteria endCriteria, Constraint constraint, DoubleVector weights)
 {
     NQuantLibcPINVOKE.MarkovFunctional_calibrate__SWIG_1(swigCPtr, BlackCalibrationHelperVector.getCPtr(helper), OptimizationMethod.getCPtr(method), EndCriteria.getCPtr(endCriteria), Constraint.getCPtr(constraint), DoubleVector.getCPtr(weights));
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
 public void calibrate(BlackCalibrationHelperVector helper, OptimizationMethod method, EndCriteria endCriteria)
 {
     NQuantLibcPINVOKE.MarkovFunctional_calibrate__SWIG_3(swigCPtr, BlackCalibrationHelperVector.getCPtr(helper), OptimizationMethod.getCPtr(method), EndCriteria.getCPtr(endCriteria));
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
 public void calibrate(CalibrationHelperVector arg0, OptimizationMethod arg1, EndCriteria arg2, Constraint constraint, DoubleVector weights)
 {
     NQuantLibcPINVOKE.ShortRateModelHandle_calibrate__SWIG_1(swigCPtr, CalibrationHelperVector.getCPtr(arg0), OptimizationMethod.getCPtr(arg1), EndCriteria.getCPtr(arg2), Constraint.getCPtr(constraint), DoubleVector.getCPtr(weights));
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
 public void calibrate(CalibrationHelperVector arg0, OptimizationMethod arg1, EndCriteria arg2)
 {
     NQuantLibcPINVOKE.ShortRateModelHandle_calibrate__SWIG_3(swigCPtr, CalibrationHelperVector.getCPtr(arg0), OptimizationMethod.getCPtr(arg1), EndCriteria.getCPtr(arg2));
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Ejemplo n.º 11
0
 public virtual void calibrate(CalibrationHelperVector arg0, OptimizationMethod arg1, EndCriteria arg2, Constraint constraint)
 {
     NQuantLibcPINVOKE.CalibratedModel_calibrate__SWIG_2(swigCPtr, CalibrationHelperVector.getCPtr(arg0), OptimizationMethod.getCPtr(arg1), EndCriteria.getCPtr(arg2), Constraint.getCPtr(constraint));
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
 public void calibrate(CalibrationHelperVector instruments, OptimizationMethod method, EndCriteria endCriteria)
 {
     NQuantLibcPINVOKE.Gsr_calibrate__SWIG_3(swigCPtr, CalibrationHelperVector.getCPtr(instruments), OptimizationMethod.getCPtr(method), EndCriteria.getCPtr(endCriteria));
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Ejemplo n.º 13
0
        public QlArray solve(CostFunctionDelegate function, Constraint c, OptimizationMethod m, EndCriteria e, QlArray iv)
        {
            QlArray ret = new QlArray(NQuantLibcPINVOKE.Optimizer_solve(swigCPtr, CostFunctionDelegate.getCPtr(function), Constraint.getCPtr(c), OptimizationMethod.getCPtr(m), EndCriteria.getCPtr(e), QlArray.getCPtr(iv)), true);

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Generates the R script which performs the optimization.
        /// </summary>
        /// <param name="fileName">File path to which the R code will be saved.</param>
        /// <param name="outputPath">Directory/path to which output results will be saved. This is passed as a parameter to croptimizR.</param>
        /// <param name="apsimxFileName">Name of the .apsimx file to be run by the optimisation.</param>
        private void GenerateRScript(string fileName, string outputPath, string apsimxFileName)
        {
            // tbi: package installation. Need to test on a clean VM.
            StringBuilder contents = new StringBuilder();

            contents.AppendLine($"variable_names <- c({string.Join(", ", VariableNames.Select(x => $"'{x.Trim()}'").ToArray())})");

            // In theory, it would be better to always use relative path to
            // the input file, by setting the working directory of the R
            // process appropriately. Unfortunately, this will require some
            // refactoring of the R wrapper which I don't really want to do
            // right now. So for now I'm going to just use relative path if
            // using docker.
            if (RDocker.UseDocker())
            {
                apsimxFileName = Path.GetFileName(apsimxFileName);
            }

            // If we're reading from the PredictedObserved table, need to fix
            // Predicted./Observed. suffix for the observed variables.
            string escapedOutputPath = outputPath.Replace(@"\", "/");

            string[] sanitisedObservedVariables = GetObservedVariableName().Select(x => $"'{x.Trim()}'").ToArray();
            string   dateVariable = VariableNames.Any(v => v.StartsWith("Predicted.")) ? "Predicted.Clock.Today" : "Clock.Today";

            contents.AppendLine($"observed_variable_names <- c({string.Join(", ", sanitisedObservedVariables)}, '{dateVariable}')");
            contents.AppendLine($"apsimx_path <- '{PathToModels().Replace(@"\", "/")}'");
            contents.AppendLine($"apsimx_file <- '{apsimxFileName.Replace(@"\", "/")}'");
            contents.AppendLine($"simulation_names <- {GetSimulationNames()}");
            contents.AppendLine($"predicted_table_name <- '{PredictedTableName}'");
            contents.AppendLine($"observed_table_name <- '{ObservedTableName}'");
            contents.AppendLine($"param_info <- {GetParamInfo()}");
            contents.AppendLine();
            contents.AppendLine(OptimizationMethod.GenerateOptimizationOptions("optim_options"));
            contents.AppendLine($"optim_options$path_results <- '{escapedOutputPath}'");
            if (RandomSeed != null)
            {
                contents.AppendLine($"optim_options$ranseed <- {RandomSeed}");
            }
            contents.AppendLine();
            contents.AppendLine($"crit_function <- {OptimizationMethod.CritFunction}");
            contents.AppendLine($"optim_method <- '{OptimizationMethod.ROptimizerName}'");
            contents.AppendLine();
            contents.AppendLine(ReflectionUtilities.GetResourceAsString("Models.Resources.RScripts.OptimizR.r"));

            // Don't use Path.Combine() - as this may be running in a (linux) docker container.
            // R will work with forward slashes for path separators on win and linux,
            // but backslashes will not work on linux.
            string rDataExpectedPath = $"{escapedOutputPath}/optim_results.Rdata";

            contents.AppendLine(CreateReadRDataScript(rDataExpectedPath));

            File.WriteAllText(fileName, contents.ToString());
        }
Ejemplo n.º 15
0
        static bool OptimizeSolution(OptimizationMethod optimizationMethod, Solution solution, int maxDeliveries)
        {
            bool optimized = false;

            while (optimizationMethod(solution, maxDeliveries))
            {
                Console.WriteLine("Optimizing score: {0}", ScoreSolution(solution.Deliveries));
                optimized = true;
            }

            return(optimized);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// <para>Unscented transform parameters optimization procedure.</para>
        /// <para>The OptimizationMethod param determines the optimization method:</para>
        /// <para>- OptimizationMethod.RandomShoot - parameters are randomly sampled and the best sample is chosen as optimal;
        /// <para>- OptimizationMethod.NelderMeed - parameters are optimized with non-gradient Nelder-Meed method.</para>
        /// <para>The UTOptimizationType type param determines the relation between the optimized variable and the unscented tranform params (see UTParams and its constructors for details). </para>
        /// <para>- If type is UTOptimizationType.ImplicitAlpha, then the optimized variable is saclar [alpha0];</para>
        /// <para>- If type is UTOptimizationType.ImplicitAlphaBetaKappa, then optimized variable is a vector [alpha, beta, kappa];</para>
        /// <para>- If type is UTOptimizationType.Explicit, then then optimized variable is a vector [lambda, wm0, wc0, wi]. ///TODO it is not correct to define the parameters of the unsctnted transform arbitraty, they have to be interdependent, so that the mean and cov would be transformed correctly.</para>
        /// </summary>
        /// <param name="method">Unscented transform parameters optimization method</param>
        /// <param name="type">Unscented transform parameters definition type</param>
        /// <param name="Phi1">State transformation: a nonlinear function which determines the dynamics: x_{t+1} = Phi_1(x_t) + Phi_2(x_t) W_t</param>
        /// <param name="Phi2">Noise multiplicator in the dynamics equation: x_{t+1} = Phi(x_t) + W_t</param>
        /// <param name="Psi1">Observations transformation: a nonlinear function which determines the relation between the state and the observations: y_t = Psi_1(x_t) + Psi_2(x_t) Nu_t</param>
        /// <param name="Psi2">Noise multiplicator in the observations equation: y_t = Psi_1(x_t) + Psi_2(x_t) Nu_t</param>
        /// <param name="Mw">Mean of the noise in the dynamics equation </param>
        /// <param name="Rw">Covariance matrix of the state disturbances</param>
        /// <param name="Mnu">Mean of the noise in the obseration equation </param>
        /// <param name="Rnu">Convariance matrix of the observation noise</param>
        /// <param name="Crit">Criterion: a function which determines the quality of the unscented Kalman filter. Depends on the sample covariance of the estimation error on the last step: val = Crit(Cov(X_T-Xhat_T,X_T-Xhat_T))  </param>
        /// <param name="T">The upper bound of the observation interval</param>
        /// <param name="models">Discrete vector model samples</param>
        /// <param name="xhat0">Initial condition</param>
        /// <param name="DX0Hat">Initial condition covariance</param>
        /// <param name="outputFolder">The results are saved to this folder in file "UT_optimization_{type}.txt"</param>
        static (double, UTParams, UTParams) UTParmsOptimize(OptimizationMethod method, UTDefinitionType type,
                                                            Func <int, Vector <double>, Vector <double> > Phi1,
                                                            Func <int, Vector <double>, Matrix <double> > Phi2,
                                                            Func <int, Vector <double>, Vector <double> > Psi1,
                                                            Func <int, Vector <double>, Matrix <double> > Psi2,
                                                            Vector <double> Mw,
                                                            Matrix <double> Rw,
                                                            Vector <double> Mnu,
                                                            Matrix <double> Rnu,
                                                            Func <Matrix <double>, double> Crit,
                                                            int T,
                                                            DiscreteVectorModel[] models,
                                                            Vector <double> xhat0,
                                                            Matrix <double> DX0Hat,
                                                            string outputFolder)
        {
            (int n, Vector <double> lowerBound, Vector <double> upperBound, Vector <double> initialGuess, string filename) = DefineOptimizationParameters(type, xhat0, string.IsNullOrWhiteSpace(outputFolder) ? null : Path.Combine(outputFolder, "UT_optimization_{type}.txt"));
            double          min    = double.MaxValue;
            Vector <double> argmin = Exts.Stack(initialGuess, initialGuess);

            switch (method)
            {
            case OptimizationMethod.RandomShoot:
                var OptimumRandom = RandomOptimizer.Minimize((x) => CalculateSampleCriterion(Phi1, Phi2, Psi1, Psi2, Mw, Rw, Mnu, Rnu, Crit, x, T, models, xhat0, DX0Hat), Exts.Stack(lowerBound, lowerBound), Exts.Stack(upperBound, upperBound), 100, 100, filename);
                min    = OptimumRandom.min;
                argmin = OptimumRandom.argmin;
                break;

            case OptimizationMethod.NelderMeed:
                NelderMeadSimplex optimizer = new NelderMeadSimplex(1e-3, 100);
                var objective = ObjectiveFunction.Value((x) => CalculateSampleCriterion(Phi1, Phi2, Psi1, Psi2, Mw, Rw, Mnu, Rnu, Crit, x, T, models, xhat0, DX0Hat));
                try
                {
                    var optimumNM = optimizer.FindMinimum(objective, Exts.Stack(initialGuess, initialGuess));
                    min    = optimumNM.FunctionInfoAtMinimum.Value;
                    argmin = optimumNM.MinimizingPoint;
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Optimizer faild, using the initail guess ({e.Message})");
                    argmin = Exts.Stack(initialGuess, initialGuess);
                }
                break;

            default:     // no optimization by default
                break;
            }
            return(min, new UTParams(xhat0.Count, argmin.Take(n).ToArray()), new UTParams(xhat0.Count, argmin.Skip(n).Take(n).ToArray()));
        }
Ejemplo n.º 17
0
        /// <summary>
        ///   Initializes a new Optimizer using the default values.
        ///   <param name="theta">Theta to optimize.</param>
        ///   <param name="maxIterations">Maximum number of iterations.</param>
        ///   <param name="learningRate">Learning Rate (alpha) (Optional).</param>
        ///   <param name="momentum">Momentum parameter for use in accelerated methods (Optional).</param>
        ///   <param name="optimizationMethod">Type of optimization method to use (Optional).</param>
        ///   <param name="optimizer">An external typed optimization method to use (Optional).</param>
        /// </summary>
        public Optimizer(
            Vector theta,
            int maxIterations,
            double learningRate = 1.0,
            double momentum     = 0.9,
            OptimizationMethods optimizationMethod = OptimizationMethods.StochasticGradientDescent,
            OptimizationMethod optimizer           = null)
        {
            Completed = false;
            if (optimizationMethod != OptimizationMethods.External)
            {
                switch (optimizationMethod)
                {
                case OptimizationMethods.FastGradientDescent:
                    optimizer = new FastGradientDescent {
                        Momentum = momentum
                    };
                    break;

                case OptimizationMethods.StochasticGradientDescent:
                    optimizer = new StochasticGradientDescent();
                    break;

                case OptimizationMethods.NAGDescent:
                    optimizer = new NAGDescent {
                        Momentum = momentum
                    };
                    break;
                }
            }

            OpimizationMethod = optimizer;

            Properties = new OptimizerProperties
            {
                Iteration     = 0,
                MaxIterations = maxIterations,
                Cost          = double.MaxValue,
                Gradient      = Vector.Zeros(theta.Length),
                Theta         = theta,
                LearningRate  = learningRate,
                Momentum      = momentum
            };
        }
Ejemplo n.º 18
0
 public MethodResult Execute(FunctionDelegate F, GradientDelegate Gradient, OptimizationMethod OptimizationMethod, Vector StartVector, int MaxIterations)
 {
     stopwatch.Start();
     currentVector = StartVector;
     for (int i = 0; i < MaxIterations; i++)
     {
         oldVector = currentVector;
         deltaGradient = Gradient(currentVector);
         var lambda = OptimizationMethod((x) => { return F(currentVector - x * deltaGradient); }, -10, 10, 1E-9, MaxIterations);
         currentVector = currentVector - lambda * deltaGradient;
         if (deltaGradient.LengthSquared < epsilon)
         {
             stopwatch.Stop();
             return new MethodResult() { Result = new Vector[] { currentVector }, IterationEnd = false, Iterations = i, MethodName = "Метод градиентного спуска", stopwatch = stopwatch, StartPoint = new Vector[] { StartVector }, FunctionValue = F(currentVector) };
         }
     }
     stopwatch.Stop();
     return new MethodResult() { Result = new Vector[] { currentVector }, IterationEnd = true, MethodName = "Метод градиентного спуска", Iterations = MaxIterations, stopwatch = stopwatch, StartPoint = new Vector[] { StartVector }, FunctionValue = F(currentVector) };
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Generates the R script which performs the optimization.
        /// </summary>
        /// <param name="fileName">File path to which the R code will be saved.</param>
        private void GenerateRScript(string fileName)
        {
            // tbi: package installation. Need to test on a clean VM.
            StringBuilder contents       = new StringBuilder();
            string        apsimxFileName = GenerateApsimXFile();

            contents.AppendLine($"variable_names <- c('{VariableName}')");
            contents.AppendLine($"apsimx_path <- '{typeof(IModel).Assembly.Location.Replace(@"\", @"\\")}'");
            contents.AppendLine($"apsimx_file <- '{apsimxFileName.Replace(@"\", @"\\")}'");
            contents.AppendLine($"simulation_names <- {GetSimulationNames()}");
            contents.AppendLine($"predicted_table_name <- '{PredictedTableName}'");
            contents.AppendLine($"observed_table_name <- '{ObservedTableName}'");
            contents.AppendLine($"param_info <- {GetParamInfo()}");
            contents.AppendLine();
            contents.AppendLine(OptimizationMethod.GenerateOptimizationOptions("optim_options"));
            contents.AppendLine();
            contents.AppendLine($"crit_function <- {OptimizationMethod.CritFunction}");
            contents.AppendLine($"optim_method <- '{OptimizationMethod.ROptimizerName}'");
            contents.AppendLine();
            contents.Append(ReflectionUtilities.GetResourceAsString("Models.Resources.RScripts.OptimizR.r"));

            File.WriteAllText(fileName, contents.ToString());
        }
Ejemplo n.º 20
0
 public MethodResult Execute(FunctionDelegate F, GradientDelegate Gradient, OptimizationMethod OptimizationMethod, int MaxIterations)
 {
     stopwatch.Start();
     for (int i = 0; i < MaxIterations; i++)
     {
         var oldGradientValue = Gradient(currentValue);
         Vector newDirection = -(hessianMatrix * oldGradientValue);
         var lambda = OptimizationMethod((alpha) => { return F(currentValue + alpha * newDirection); }, -10, 10, 1E-9, MaxIterations);
         var vector = lambda * newDirection;
         currentValue = vector + currentValue;
         //var functionValue = F(currentValue);
         var gradientValue = Gradient(currentValue);
         if (gradientValue.LengthSquared < epsilon || vector.LengthSquared < epsilon)
         {
             stopwatch.Stop();
             return new MethodResult() { Result = new Vector[] { currentValue }, IterationEnd = false, MethodName = "Квазиньютоновский метод", Iterations = i, stopwatch = stopwatch, StartPoint = new Vector[] { StartVector }, FunctionValue = F(currentValue) };
         }
         var matrixU = gradientValue - oldGradientValue;
         var matrixA = (vector * vector.GetTranspose()) / (vector.ToMatrix().GetTranspose() * matrixU)[0, 0];
         var matrixB = -(hessianMatrix * matrixU * matrixU.GetTranspose() * hessianMatrix) / (matrixU.GetTranspose() * hessianMatrix * matrixU)[0, 0];
         hessianMatrix = hessianMatrix + matrixA + matrixB;
     }
     return new MethodResult() { Result = new Vector[] { currentValue }, IterationEnd = true, MethodName = "Квазиньютоновский метод", Iterations = MaxIterations, stopwatch = stopwatch, StartPoint = new Vector[] { StartVector }, FunctionValue = F(currentValue) };
 }
Ejemplo n.º 21
0
 public MethodResult Execute(FunctionDelegate F, GradientDelegate Gradient, OptimizationMethod OptimizationMethod, int MaxIterations)
 {
     stopwatch.Start();
     var antiGradient = -Gradient(x);
     var gradientSquare = antiGradient.LengthSquared;
     for (int i = 0; i < MaxIterations; i++)
     {
         var lambda = OptimizationMethod((alpha) => { return F(x + alpha * antiGradient); }, -10, 10, 1E-9, MaxIterations);
         x = x + lambda * antiGradient;
         var newAntiGradient = -Gradient(x);
         var newGradientSquare = newAntiGradient.LengthSquared;
         var beta = newGradientSquare / gradientSquare;
         if (i % (500) == 0 && i != 0) beta = 0;
         antiGradient = newAntiGradient + beta * antiGradient;
         gradientSquare = newGradientSquare;
         if (gradientSquare < epsilon)
         {
             stopwatch.Stop();
             return new MethodResult() { Result = new Vector[] { x }, IterationEnd = false, Iterations = i, MethodName = "Метод сопряженных градиентов", stopwatch = stopwatch , StartPoint = new Vector[] { StartVector}, FunctionValue = F(x)};
         }
     }
     stopwatch.Stop();
     return new MethodResult() { Result = new Vector[] { x }, IterationEnd = true, MethodName = "Метод сопряженных градиентов", Iterations = MaxIterations, stopwatch = stopwatch, StartPoint = new Vector[] { StartVector }, FunctionValue = F(x) };
 }
Ejemplo n.º 22
0
        /// <summary>
        /// <para>Unscented transform parameters stepwize optimization procedure.</para>
        /// <para>The OptimizationMethod param determines the optimization method:</para>
        /// <para>- OptimizationMethod.RandomShoot - parameters are randomly sampled and the best sample is chosen as optimal;
        /// <para>- OptimizationMethod.NelderMeed - parameters are optimized with non-gradient Nelder-Meed method.</para>
        /// <para>The UTOptimizationType type param determines the relation between the optimized variable and the unscented tranform params (see UTParams and its constructors for details). </para>
        /// <para>- If type is UTOptimizationType.ImplicitAlpha, then the optimized variable is saclar [alpha0];</para>
        /// <para>- If type is UTOptimizationType.ImplicitAlphaBetaKappa, then optimized variable is a vector [alpha, beta, kappa];</para>
        /// <para>- If type is UTOptimizationType.Explicit, then then optimized variable is a vector [lambda, wm0, wc0, wi]. ///TODO it is not correct to define the parameters of the unsctnted transform arbitraty, they have to be interdependent, so that the mean and cov would be transformed correctly.</para>
        /// </summary>
        /// <param name="method">Unscented transform parameters optimization method</param>
        /// <param name="type">Unscented transform parameters definition type</param>
        /// <param name="Phi1">State transformation: a nonlinear function which determines the dynamics: x_{t+1} = Phi_1(x_t) + Phi_2(x_t) W_t</param>
        /// <param name="Phi2">Noise multiplicator in the dynamics equation: x_{t+1} = Phi(x_t) + W_t</param>
        /// <param name="Psi1">Observations transformation: a nonlinear function which determines the relation between the state and the observations: y_t = Psi_1(x_t) + Psi_2(x_t) Nu_t</param>
        /// <param name="Psi2">Noise multiplicator in the observations equation: y_t = Psi_1(x_t) + Psi_2(x_t) Nu_t</param>
        /// <param name="Mw">Mean of the noise in the dynamics equation </param>
        /// <param name="Rw">Covariance matrix of the state disturbances</param>
        /// <param name="Mnu">Mean of the noise in the obseration equation </param>
        /// <param name="Rnu">Convariance matrix of the observation noise</param>
        /// <param name="Crit">Criterion: a function which determines the quality of the unscented Kalman filter. Depends on the sample covariance of the estimation error on the last step: val = Crit(Cov(X_T-Xhat_T,X_T-Xhat_T))  </param>
        /// <param name="T">The upper bound of the observation interval</param>
        /// <param name="models">Discrete vector model samples</param>
        /// <param name="xhat0">Initial condition</param>
        /// <param name="DX0Hat">Initial condition covariance</param>
        /// <param name="outputFolder">The results are saved to this folder in file "UT_optimization_{type}.txt"</param>
        static (double, UTParams[], UTParams[]) UTParmsOptimizeStepwise(OptimizationMethod method, UTDefinitionType type,
                                                                        Func <int, Vector <double>, Vector <double> > Phi1,
                                                                        Func <int, Vector <double>, Matrix <double> > Phi2,
                                                                        Func <int, Vector <double>, Vector <double> > Psi1,
                                                                        Func <int, Vector <double>, Matrix <double> > Psi2,
                                                                        Vector <double> Mw,
                                                                        Matrix <double> Rw,
                                                                        Vector <double> Mnu,
                                                                        Matrix <double> Rnu,
                                                                        Func <Matrix <double>, double> Crit,
                                                                        int T,
                                                                        DiscreteVectorModel[] models,
                                                                        Vector <double> xhat0,
                                                                        Matrix <double> DX0Hat,
                                                                        string outputFolder)
        {
            UTParams[] pForecast = new UTParams[T];
            UTParams[] pCorrect  = new UTParams[T];

            (int n, Vector <double> lowerBound, Vector <double> upperBound, Vector <double> initialGuess, string filename) = DefineOptimizationParameters(type, xhat0, string.IsNullOrWhiteSpace(outputFolder) ? null : Path.Combine(outputFolder, "UT_stepwise_ptimization_{type}.txt"));

            Vector <double>[] xHatU = models.Select(x => xhat0).ToArray();
            Matrix <double>[] PHatU = models.Select(x => DX0Hat).ToArray();

            double min = double.MaxValue;

            Console.WriteLine($"UKF estimate parameters start");
            DateTime start = DateTime.Now;

            for (int t = 1; t < T; t++)
            //Parallel.For(0, T, new ParallelOptions() { MaxDegreeOfParallelism = System.Environment.ProcessorCount }, t =>
            {
                DateTime startiteration = DateTime.Now;
                min = double.MaxValue;
                Vector <double> argmin = initialGuess;

                switch (method)
                {
                case OptimizationMethod.RandomShoot:
                    var OptimumRandom = RandomOptimizer.Minimize((x) => CalculateSampleStepwiseCriterion(Phi1, Phi2, Psi1, Psi2, Mw, Rw, Mnu, Rnu, Crit, x, t, models, xHatU, PHatU), Exts.Stack(lowerBound, lowerBound), Exts.Stack(upperBound, upperBound), 100, 100, filename);
                    min    = OptimumRandom.min;
                    argmin = OptimumRandom.argmin;
                    break;

                case OptimizationMethod.NelderMeed:
                    NelderMeadSimplex optimizer = new NelderMeadSimplex(1e-3, 100);
                    var objective = ObjectiveFunction.Value((x) => CalculateSampleStepwiseCriterion(Phi1, Phi2, Psi1, Psi2, Mw, Rw, Mnu, Rnu, Crit, x, t, models, xHatU, PHatU));
                    try
                    {
                        var optimumNM = optimizer.FindMinimum(objective, Exts.Stack(initialGuess, initialGuess));
                        min    = optimumNM.FunctionInfoAtMinimum.Value;
                        argmin = optimumNM.MinimizingPoint;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Optimizer faild, using the initail guess ({e.Message})");
                        argmin = Exts.Stack(initialGuess, initialGuess);
                    }
                    break;
                }
                pForecast[t] = new UTParams(xhat0.Count, argmin.Take(n).ToArray());
                pCorrect[t]  = new UTParams(xhat0.Count, argmin.Skip(n).Take(n).ToArray());
                for (int i = 0; i < models.Count(); i++)
                {
                    (xHatU[i], PHatU[i]) = Step(Phi1, Phi2, Psi1, Psi2, Mw, Rw, Mnu, Rnu, pForecast[t], pCorrect[t], t, models[i].Trajectory[t][1], xHatU[i], PHatU[i]);
                }
                Console.WriteLine($"UKF estimate parameters for t={t}, done in {(DateTime.Now - startiteration).ToString(@"hh\:mm\:ss\.fff")}");
            }
            //    });
            DateTime finish = DateTime.Now;

            Console.WriteLine($"UKF estimate parameters finished in {(finish - start).ToString(@"hh\:mm\:ss\.fff")}");
            return(min, pForecast, pCorrect);
        }
 public NoArbSabrInterpolatedSmileSection(Date optionDate, QuoteHandle forward, DoubleVector strikes, bool hasFloatingStrikes, QuoteHandle atmVolatility, QuoteHandleVector volHandles, double alpha, double beta, double nu, double rho, bool isAlphaFixed, bool isBetaFixed, bool isNuFixed, bool isRhoFixed, bool vegaWeighted, SWIGTYPE_p_boost__shared_ptrT_EndCriteria_t endCriteria, OptimizationMethod method) : this(NQuantLibcPINVOKE.new_NoArbSabrInterpolatedSmileSection__SWIG_1(Date.getCPtr(optionDate), QuoteHandle.getCPtr(forward), DoubleVector.getCPtr(strikes), hasFloatingStrikes, QuoteHandle.getCPtr(atmVolatility), QuoteHandleVector.getCPtr(volHandles), alpha, beta, nu, rho, isAlphaFixed, isBetaFixed, isNuFixed, isRhoFixed, vegaWeighted, SWIGTYPE_p_boost__shared_ptrT_EndCriteria_t.getCPtr(endCriteria), OptimizationMethod.getCPtr(method)), true)
 {
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Ejemplo n.º 24
0
 public SABRInterpolation(QlArray x, QlArray y, double expiry, double forward, double alpha, double beta, double volvol, double rho, EndCriteria endCriteria, OptimizationMethod optimizationMethod) : this(NQuantLibcPINVOKE.new_SABRInterpolation__SWIG_5(QlArray.getCPtr(x), QlArray.getCPtr(y), expiry, forward, alpha, beta, volvol, rho, EndCriteria.getCPtr(endCriteria), OptimizationMethod.getCPtr(optimizationMethod)), true)
 {
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="type">Unscented transform parameters definition type</param>
 /// <param name="method">Unscented transform parameters optimization method</param>
 public UTStaticEstimate(UTDefinitionType type = UTDefinitionType.ImplicitAlpha, OptimizationMethod method = OptimizationMethod.NelderMeed)
 {
     utDefinitionType   = type;
     optimizationMethod = method;
 }
Ejemplo n.º 26
0
        /// <summary>
        /// <para>Unscented transform parameters optimization procedure.</para>
        /// <para>The OptimizationMethod param determines the optimization method:</para>
        /// <para>- OptimizationMethod.RandomShoot - parameters are randomly sampled and the best sample is chosen as optimal;
        /// <para>- OptimizationMethod.NelderMeed - parameters are optimized with non-gradient Nelder-Meed method.</para>
        /// <para>The UTOptimizationType type param determines the relation between the optimized variable and the unscented tranform params (see UTParams and its constructors for details). </para>
        /// <para>- If type is UTOptimizationType.ImplicitAlpha, then the optimized variable is saclar [alpha0];</para>
        /// <para>- If type is UTOptimizationType.ImplicitAlphaBetaKappa, then optimized variable is a vector [alpha, beta, kappa];</para>
        /// <para>- If type is UTOptimizationType.Explicit, then then optimized variable is a vector [lambda, wm0, wc0, wi]. ///TODO it is not correct to define the parameters of the unsctnted transform arbitraty, they have to be interdependent, so that the mean and cov would be transformed correctly.</para>
        /// </summary>
        /// <param name="method">Unscented transform parameters optimization method</param>
        /// <param name="type">Unscented transform parameters definition type</param>
        /// <param name="Phi">Transformation: a nonlinear function which determines the transformation of the random vector variable: y = Phi(x) + nu</param>
        /// <param name="Crit">Criterion: a function which determines the quality of the unscented transform estimate. Depends on the sample covariance of the estimation error: val = Crit(Cov(X-Xhat,X-Xhat))  </param>
        /// <param name="X">Array of initial variable x samples</param>
        /// <param name="Y">Array of transformed variable y = Phi(x) + nu samples</param>
        /// <param name="mX">Mean of x</param>
        /// <param name="KX">Cov of x</param>
        /// <param name="KNu">Cov of the noize nu</param>
        /// <param name="outputFolder">If needed, the results or the random sampling (OptimizationMethod.RandomShoot) are saved to this folder in file "UT_optimization_{type}.txt"</param>
        /// <returns>Returns touple (the best criteron value, the parameters of the unscented transform with best estimation quality)</returns>
        static (double, UTParams) UTParmsOptimize(OptimizationMethod method, UTDefinitionType type,
                                                  Func <Vector <double>, Vector <double> > Phi,
                                                  Func <Matrix <double>, double> Crit,
                                                  Vector <double>[] X,
                                                  Vector <double>[] Y,
                                                  Vector <double> mX,
                                                  Matrix <double> KX,
                                                  Matrix <double> KNu,
                                                  string outputFolder = null
                                                  )
        {
            int             n;
            string          filename = string.IsNullOrWhiteSpace(outputFolder) ? null : Path.Combine(outputFolder, "UT_optimization_{type}.txt");
            Vector <double> lowerBound;
            Vector <double> upperBound;
            Vector <double> initialGuess;

            switch (type)
            {
            case UTDefinitionType.ImplicitAlpha:
                n            = 1;
                lowerBound   = Exts.Vector(1 - 2 / mX.Count);
                upperBound   = Exts.Vector(1);
                initialGuess = Exts.Vector(0.5);
                filename     = filename.Replace("{type}", "ImplicitAlpha");
                break;

            case UTDefinitionType.ImplicitAlphaBetaKappa:
                n            = 3;
                lowerBound   = Exts.Vector(0, 0, 3.0 - mX.Count - 2.0);
                upperBound   = Exts.Vector(5, 5, 3.0 - mX.Count + 2.0);
                initialGuess = Exts.Vector(0.5, 2.0, 3.0 - mX.Count);
                filename     = filename.Replace("{type}", "ImplicitABK"); break;

            case UTDefinitionType.Explicit:
                n            = 4;
                lowerBound   = Exts.Vector(-10, -10, -10, -10);
                upperBound   = Exts.Vector(10, 10, 10, 10);
                initialGuess = Exts.Vector((new UTParams(mX.Count, 0.5, 2.0, 3.0 - mX.Count)).Params);
                filename     = filename.Replace("{type}", "Explicit"); break;

            default:
                n            = 0;
                lowerBound   = null;
                upperBound   = null;
                initialGuess = null;
                break;
            }

            double          min    = double.MaxValue;
            Vector <double> argmin = initialGuess;

            switch (method)
            {
            case OptimizationMethod.RandomShoot:
                var OptimumRandom = RandomOptimizer.Minimize((p) => CalculateSampleCriterion(Phi, Crit, p, X, Y, mX, KX, KNu), lowerBound, upperBound, 1000, 1000, filename);
                min    = OptimumRandom.min;
                argmin = OptimumRandom.argmin;
                break;

            case OptimizationMethod.NelderMeed:
                NelderMeadSimplex optimizer = new NelderMeadSimplex(1e-3, 100);
                var objective = ObjectiveFunction.Value((p) => CalculateSampleCriterion(Phi, Crit, p, X, Y, mX, KX, KNu));
                var optimumNM = optimizer.FindMinimum(objective, initialGuess);
                min    = optimumNM.FunctionInfoAtMinimum.Value;
                argmin = optimumNM.MinimizingPoint;
                break;
            }
            return(min, new UTParams(mX.Count, argmin.AsArray()));
        }
Ejemplo n.º 27
0
 public SwaptionVolCube1(SwaptionVolatilityStructureHandle atmVolStructure, PeriodVector optionTenors, PeriodVector swapTenors, DoubleVector strikeSpreads, QuoteHandleVectorVector volSpreads, SwapIndex swapIndex, SwapIndex shortSwapIndex, bool vegaWeightedSmileFit, QuoteHandleVectorVector parametersGuess, BoolVector isParameterFixed, bool isAtmCalibrated, SWIGTYPE_p_boost__shared_ptrT_EndCriteria_t endCriteria, double maxErrorTolerance, OptimizationMethod optMethod) : this(NQuantLibcPINVOKE.new_SwaptionVolCube1__SWIG_0(SwaptionVolatilityStructureHandle.getCPtr(atmVolStructure), PeriodVector.getCPtr(optionTenors), PeriodVector.getCPtr(swapTenors), DoubleVector.getCPtr(strikeSpreads), QuoteHandleVectorVector.getCPtr(volSpreads), SwapIndex.getCPtr(swapIndex), SwapIndex.getCPtr(shortSwapIndex), vegaWeightedSmileFit, QuoteHandleVectorVector.getCPtr(parametersGuess), BoolVector.getCPtr(isParameterFixed), isAtmCalibrated, SWIGTYPE_p_boost__shared_ptrT_EndCriteria_t.getCPtr(endCriteria), maxErrorTolerance, OptimizationMethod.getCPtr(optMethod)), true)
 {
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Ejemplo n.º 28
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(OptimizationMethod obj) {
   return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
 }
 public AndreasenHugeVolatilityInterpl(CalibrationSet calibrationSet, QuoteHandle spot, YieldTermStructureHandle rTS, YieldTermStructureHandle qTS, AndreasenHugeVolatilityInterpl.InterpolationType interpolationType, AndreasenHugeVolatilityInterpl.CalibrationType calibrationType, uint nGridPoints, double minStrike, double maxStrike, OptimizationMethod optimizationMethod) : this(NQuantLibcPINVOKE.new_AndreasenHugeVolatilityInterpl__SWIG_1(CalibrationSet.getCPtr(calibrationSet), QuoteHandle.getCPtr(spot), YieldTermStructureHandle.getCPtr(rTS), YieldTermStructureHandle.getCPtr(qTS), (int)interpolationType, (int)calibrationType, nGridPoints, minStrike, maxStrike, OptimizationMethod.getCPtr(optimizationMethod)), true)
 {
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
 public ZabrShortMaturityNormalInterpolatedSmileSection(Date optionDate, double forward, DoubleVector strikes, bool hasFloatingStrikes, double atmVolatility, DoubleVector vols, double alpha, double beta, double nu, double rho, double gamma, bool isAlphaFixed, bool isBetaFixed, bool isNuFixed, bool isRhoFixed, bool isGammaFixed, bool vegaWeighted, SWIGTYPE_p_boost__shared_ptrT_EndCriteria_t endCriteria, OptimizationMethod method) : this(NQuantLibcPINVOKE.new_ZabrShortMaturityNormalInterpolatedSmileSection__SWIG_11(Date.getCPtr(optionDate), forward, DoubleVector.getCPtr(strikes), hasFloatingStrikes, atmVolatility, DoubleVector.getCPtr(vols), alpha, beta, nu, rho, gamma, isAlphaFixed, isBetaFixed, isNuFixed, isRhoFixed, isGammaFixed, vegaWeighted, SWIGTYPE_p_boost__shared_ptrT_EndCriteria_t.getCPtr(endCriteria), OptimizationMethod.getCPtr(method)), true)
 {
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Ejemplo n.º 31
0
 public void calibrate(CalibrationHelperVector arg0, OptimizationMethod arg1, EndCriteria arg2, Constraint constraint) {
   NQuantLibcPINVOKE.CalibratedModel_calibrate__SWIG_1(swigCPtr, CalibrationHelperVector.getCPtr(arg0), OptimizationMethod.getCPtr(arg1), EndCriteria.getCPtr(arg2), Constraint.getCPtr(constraint));
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
 }
Ejemplo n.º 32
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="type">Unscented transform parameters definition type</param>
 /// <param name="method">Unscented transform parameters optimization method</param>
 public UKFilter(UTDefinitionType type = UTDefinitionType.ImplicitAlpha, OptimizationMethod method = OptimizationMethod.NelderMeed)
 {
     utDefinitionType   = type;
     optimizationMethod = method;
 }
Ejemplo n.º 33
0
 public void calibrate(CalibrationHelperVector arg0, OptimizationMethod arg1, EndCriteria arg2) {
   NQuantLibcPINVOKE.ShortRateModelHandle_calibrate__SWIG_2(swigCPtr, CalibrationHelperVector.getCPtr(arg0), OptimizationMethod.getCPtr(arg1), EndCriteria.getCPtr(arg2));
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
 }
Ejemplo n.º 34
0
 public SVIInterpolation(QlArray x, QlArray y, double expiry, double forward, double a, double b, double rho, double m, double sigma, EndCriteria endCriteria, OptimizationMethod optimizationMethod) : this(NQuantLibcPINVOKE.new_SVIInterpolation__SWIG_1(QlArray.getCPtr(x), QlArray.getCPtr(y), expiry, forward, a, b, rho, m, sigma, EndCriteria.getCPtr(endCriteria), OptimizationMethod.getCPtr(optimizationMethod)), true)
 {
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Ejemplo n.º 35
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(OptimizationMethod obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
Ejemplo n.º 36
0
 public void calibrate(CalibrationHelperVector arg0, OptimizationMethod arg1, EndCriteria arg2, Constraint constraint, DoubleVector weights) {
   NQuantLibcPINVOKE.ShortRateModelHandle_calibrate__SWIG_0(swigCPtr, CalibrationHelperVector.getCPtr(arg0), OptimizationMethod.getCPtr(arg1), EndCriteria.getCPtr(arg2), Constraint.getCPtr(constraint), DoubleVector.getCPtr(weights));
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
 }
Ejemplo n.º 37
0
        private void BatchRunLoop(int numberOfBatchRuns, PiecewiseLinearSpeedProfileOptimizationSettings optimizationSettings, OptimizationMethod optimizationMethod)
        {
            for (int iRun = 0; iRun < numberOfBatchRuns; iRun++)
            {
                speedProfileOptimizer = new PiecewiseLinearSpeedProfileOptimization();
                speedProfileOptimizer.OptimizationMethod   = optimizationMethod;
                speedProfileOptimizer.IndividualEvaluated += new EventHandler <EvaluatedIndividualEventArgs>(ThreadSafeHandleBatchRunIndividualEvaluated);

                speedProfileOptimizer.RunSynchronous(optimizationSettings, new Random(), optimizationSettings.OptimizationTime, metricMap, metricPath);

                double bestScore = speedProfileOptimizer.BestScore;
                int    numberOfEvaluatedIndividuals   = speedProfileOptimizer.NumberOfEvaluatedIndividuals;
                OptimizableStructure optimizedProfile = speedProfileOptimizer.OptimizedSpeedProfile.Copy();
                bestIndividualsList.Add(optimizedProfile);
                double averageScore = speedProfileOptimizer.AverageFitness;

                List <double> speedSequence          = new List <double>();
                List <int>    speedSequenceIndexList = new List <int>();

                for (int i = 0; i < optimizationSettings.NumberOfSpeedPoints + 1; i++)
                {
                    int speedIndex = ((IntParameter)optimizedProfile.ParameterList[i]).ParameterValue;
                    speedSequenceIndexList.Add(speedIndex);
                    speedSequence.Add(speedProfileOptimizer.PossibleSpeedList[speedIndex]);
                }
                long speedProfileIndex = GetIndexFromValues(speedSequenceIndexList, speedProfileOptimizer.PossibleSpeedList.Count);

                batchRunInfo += iRun.ToString("0").PadLeft(3) + " " +
                                bestScore.ToString("0.000000").PadLeft(11) + " " +
                                averageScore.ToString("0.000000").PadLeft(11) + " [";
                for (int ii = 0; ii < speedSequenceIndexList.Count - 1; ii++)
                {
                    batchRunInfo += speedSequenceIndexList[ii].ToString("0") + " ";
                }
                batchRunInfo += speedSequenceIndexList[speedSequenceIndexList.Count - 1].ToString("0") + "] " +
                                speedProfileIndex.ToString("0").PadLeft(13) + " " +
                                numberOfEvaluatedIndividuals.ToString("0").PadLeft(6) + "\r\n";

                ThreadSafeShowResult(numberOfEvaluatedIndividuals, bestScore, averageScore, iRun, optimizedProfile);
            }

            if (InvokeRequired)
            {
                this.BeginInvoke(new MethodInvoker(() => startBatchRunButton.Enabled = true));
            }
            else
            {
                startBatchRunButton.Enabled = true;
            }
            if (InvokeRequired)
            {
                this.BeginInvoke(new MethodInvoker(() => batchRunProgressListBox.Enabled = true));
            }
            else
            {
                batchRunProgressListBox.Enabled = true;
            }
            string path = batchPath + "\\BatchRunResult" + "_" + roadFileName + ".txt";

            System.IO.File.WriteAllText(path, batchRunInfo);
        }