Exemplo n.º 1
0
        public static void Main(string[] args)
        {
            /* create the IpoptProblem */
            HS071 p = new HS071();

            /* allocate space for the initial point and set the values */
            double[] x = { 1.0, 5.0, 5.0, 1.0 };

            IpoptReturnCode status;

            using (var problem = new IpoptProblem(p._n, p._x_L, p._x_U, p._m, p._g_L, p._g_U, p._nele_jac, p._nele_hess,
                                                  p.eval_f, p.eval_g, p.eval_grad_f, p.eval_jac_g, p.eval_h))
            {
                /* Set some options.  The following ones are only examples,
                 * they might not be suitable for your problem. */
                problem.AddOption("derivative_test", "second-order");
                problem.AddOption("tol", 1e-7);
                problem.AddOption("mu_strategy", "adaptive");
                problem.AddOption("output_file", "hs071.txt");

#if INTERMEDIATE
                problem.SetIntermediateCallback(p.intermediate);
#endif
                /* solve the problem */
                double obj;
                status = problem.SolveProblem(x, out obj, null, null, null, null);
            }

            Console.WriteLine("{0}{0}Optimization return status: {1}{0}{0}", Environment.NewLine, status);

            for (int i = 0; i < 4; ++i)
            {
                Console.WriteLine("x[{0}]={1}", i, x[i]);
            }

            Console.WriteLine("{0}Press <RETURN> to exit...", Environment.NewLine);
            Console.ReadLine();
        }
Exemplo n.º 2
0
        OptimizationProblem(OptimizationSegments optimizationSegments, IEnumerable <CurveSpecification> curveSpecifications)
        {
            if (optimizationSegments == null)
            {
                throw new ArgumentNullException("segmentManager");
            }
            if (curveSpecifications == null)
            {
                throw new ArgumentNullException("curveSpecifications");
            }

            this.optimizationSegments = optimizationSegments;
            this.curveSpecifications  = curveSpecifications;

            this.curveLength = Terms.Variable("curveLength");

            this.pointSpecificationTemplates =
                (
                    from pointSpecificationIndex in Enumerable.Range(0, curveSpecifications.Count(curveSpecification => curveSpecification is PointCurveSpecification))
                    select SpecificationTemplate.CreatePointSpecificationTemplate(optimizationSegments.Segments, pointSpecificationIndex)
                )
                .ToArray();
            this.directionSpecificationTemplates =
                (
                    from directionSpecificationIndex in Enumerable.Range(0, curveSpecifications.Count(curveSpecification => curveSpecification is DirectionCurveSpecification))
                    select SpecificationTemplate.CreateDirectionSpecificationTemplate(optimizationSegments.Segments, curveLength, directionSpecificationIndex)
                )
                .ToArray();
            this.curvatureSpecificationTemplates =
                (
                    from curvatureSpecificationIndex in Enumerable.Range(0, curveSpecifications.Count(curveSpecification => curveSpecification is CurvatureCurveSpecification))
                    select SpecificationTemplate.CreateCurvatureSpecificationTemplate(optimizationSegments.Segments, curveLength, curvatureSpecificationIndex)
                )
                .ToArray();

            IEnumerable <ValueTerm> variables = optimizationSegments.Parameters;

            ValueTerm segmentLength = Terms.Quotient(curveLength, Terms.Constant(optimizationSegments.Segments.Count()));

            ValueTerm speedError = Terms.Sum
                                   (
                from segment in optimizationSegments.Segments
                let position                                                                                                             = Terms.Variable("t")
                                                                   let curve                                                             = segment.LocalCurve
                                                                                                       let speed                         = curve.Speed.Apply(position)
                                                                                                                               let error = Terms.Square(Terms.Difference(speed, segmentLength))
                                                                                                                                           select Terms.IntegrateTrapezoid(error.Abstract(position), new OrderedRange <double>(0, 1), 100)
                                   );

            ValueTerm fairnessError = Terms.Sum
                                      (
                from segment in optimizationSegments.Segments
                let position                                                          = Terms.Variable("t")
                                                      let curve                       = segment.LocalCurve
                                                                             let jerk = curve.Jerk.Apply(position)
                                                                                        let normal                         = Terms.Normal(curve.Velocity.Apply(position))
                                                                                                                 let error = Terms.Square(Terms.DotProduct(jerk, normal))
                                                                                                                             select Terms.IntegrateTrapezoid(error.Abstract(position), new OrderedRange <double>(0, 1), 100)
                                      );

//			ValueTerm pointSpecificationError = Terms.Sum
//			(
//				Enumerables.Concatenate
//				(
//					Enumerables.Create(Terms.Constant(0)),
//					from specificationTemplate in Enumerables.Concatenate(pointSpecificationTemplates)
//					select Terms.NormSquared
//					(
//						Terms.Difference
//						(
//							specificationTemplate.Constraint.Item,
//				            Terms.Vector(specificationTemplate.Constraint.Ranges.Select(range => range.Start))
//						)
//					)
//				)
//			);
//			ValueTerm directionSpecificationError = Terms.Sum
//			(
//				Enumerables.Concatenate
//				(
//					Enumerables.Create(Terms.Constant(0)),
//					from specificationTemplate in Enumerables.Concatenate(directionSpecificationTemplates)
//					select Terms.NormSquared
//					(
//						Terms.Difference
//						(
//							specificationTemplate.Constraint.Item,
//				            Terms.Vector(specificationTemplate.Constraint.Ranges.Select(range => range.Start))
//						)
//					)
//				)
//			);
//			ValueTerm curvatureSpecificationError = Terms.Sum
//			(
//				Enumerables.Concatenate
//				(
//					Enumerables.Create(Terms.Constant(0)),
//					from specificationTemplate in Enumerables.Concatenate(curvatureSpecificationTemplates)
//					select Terms.NormSquared
//					(
//						Terms.Difference
//						(
//							specificationTemplate.Constraint.Item,
//				            Terms.Vector(specificationTemplate.Constraint.Ranges.Select(range => range.Start))
//						)
//					)
//				)
//			);

            ValueTerm objectiveValue = Terms.Sum
                                       (
                Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(-2)), Terms.Constant(100000.0), speedError),
                Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(-4)), Terms.Constant(1), fairnessError)
//				Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(0)), Terms.Constant(0.1), pointSpecificationError),
//				Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(1)), Terms.Constant(10), directionSpecificationError),
//				Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(2)), Terms.Constant(100), curvatureSpecificationError)
                                       )
                                       .Simplify();

            IEnumerable <Constraint <ValueTerm> > constraintValues =
                (
                    Enumerables.Concatenate
                    (
                        from pointSpecificationTemplate in pointSpecificationTemplates
                        select pointSpecificationTemplate.Constraint,
                        from directionSpecificationTemplate in directionSpecificationTemplates
                        select directionSpecificationTemplate.Constraint,
                        from curvatureSpecificationTemplate in curvatureSpecificationTemplates
                        select curvatureSpecificationTemplate.Constraint,

                        from segmentIndex in Enumerable.Range(0, optimizationSegments.Segments.Count() - 1)
                        let segment0CurvePoint = optimizationSegments.Segments.ElementAt(segmentIndex + 0).LocalCurve.Point
                                                 let segment1CurvePoint = optimizationSegments.Segments.ElementAt(segmentIndex + 1).LocalCurve.Point
                                                                          select Constraints.CreateEquality
                                                                          (
                            segment0CurvePoint.Apply(Terms.Constant(1)),
                            segment1CurvePoint.Apply(Terms.Constant(0))
                                                                          ),

                        from segmentIndex in Enumerable.Range(0, optimizationSegments.Segments.Count() - 1)
                        let segment0CurveVelocity = optimizationSegments.Segments.ElementAt(segmentIndex + 0).LocalCurve.Velocity
                                                    let segment1CurveVelocity = optimizationSegments.Segments.ElementAt(segmentIndex + 1).LocalCurve.Velocity
                                                                                select Constraints.CreateEquality
                                                                                (
                            segment0CurveVelocity.Apply(Terms.Constant(1)),
                            segment1CurveVelocity.Apply(Terms.Constant(0))
                                                                                ),

                        from segmentIndex in Enumerable.Range(0, optimizationSegments.Segments.Count() - 1)
                        let segment0CurveAcceleration = optimizationSegments.Segments.ElementAt(segmentIndex + 0).LocalCurve.Acceleration
                                                        let segment1CurveAcceleration = optimizationSegments.Segments.ElementAt(segmentIndex + 1).LocalCurve.Acceleration
                                                                                        select Constraints.CreateEquality
                                                                                        (
                            segment0CurveAcceleration.Apply(Terms.Constant(1)),
                            segment1CurveAcceleration.Apply(Terms.Constant(0))
                                                                                        )
                    )
                )
                .ToArray();

            Constraint <ValueTerm> constraint = Constraints.Merge(constraintValues);

            FunctionTerm objectiveFunction  = objectiveValue.Abstract(variables);
            FunctionTerm constraintFunction = constraint.Item.Abstract(variables);

            this.problem = IpoptProblem.Create(objectiveFunction, constraintFunction, constraint.Ranges);
        }
Exemplo n.º 3
0
        bool Solve()
        {
            IpoptReturnCode status;

            cLB = new double[this.ProblemData.Equations.Count + this.ProblemData.Constraints.Count];
            cUB = new double[this.ProblemData.Equations.Count + this.ProblemData.Constraints.Count];
            x0  = ProblemData.Variables.Select(v => v.ValueInSI).ToArray();
            xLB = new double[ProblemData.Variables.Count];
            xUB = new double[ProblemData.Variables.Count];
            r   = new double[ProblemData.Equations.Count + ProblemData.Constraints.Count];

            for (int i = 0; i < ProblemData.Variables.Count; i++)
            {
                xLB[i] = ProblemData.Variables[i].LowerBound;
                xUB[i] = ProblemData.Variables[i].UpperBound;
            }

            for (int i = 0; i < ProblemData.Equations.Count; i++)
            {
                cLB[i] = 0.0;
                cUB[i] = 0.0;
            }
            for (int i = 0; i < ProblemData.Constraints.Count; i++)
            {
                cLB[i + ProblemData.Equations.Count] = ProblemData.Constraints[i].LowerBound;
                cUB[i + ProblemData.Equations.Count] = ProblemData.Constraints[i].UpperBound;
            }
            ProblemData.CreateIndex();
            ProblemData.GenerateJacobian();
            var m = ProblemData.Equations.Count + ProblemData.Constraints.Count;

            using (var problem = new IpoptProblem(ProblemData.NumberOfVariables,
                                                  xLB,
                                                  xUB,
                                                  m,
                                                  cLB,
                                                  cUB,
                                                  ProblemData.Jacobian.Count,
                                                  ProblemData.HessianStructure.Count,
                                                  eval_f, eval_g, eval_grad_f, eval_jac_g, eval_h))
            {
                evaluator = new Evaluator();
                if (problemData.UseHessian)
                {
                    problem.AddOption("hessian_approximation", "exact");
                }
                else
                {
                    problem.AddOption("hessian_approximation", "limited-memory");
                }
                // problem.AddOption("tol", 1e-8);
                problem.AddOption("max_iter", 150);
                problem.AddOption("max_cpu_time", 30);
                // problem.AddOption("mu_strategy", "adaptive");
                //  problem.AddOption("derivative_test", "first-order");
                //    problem.AddOption("derivative_test", "second-order");
                problem.AddOption("output_file", "ipopt.out");
                problem.AddOption("linear_solver", "ma27");
                problem.AddOption("print_user_options", "yes");
                //problem.AddOption("bound_relax_factor", 1e-8);
                //problem.AddOption("bound_frac", 1e-8);
                //problem.AddOption("bound_push", 1e-8);
                problem.AddOption("constr_viol_tol", 1e-5);
                // problem.AddOption("nlp_scaling_method", "gradient-based");
                // problem.AddOption("nlp_scaling_method", "equilibration-based");



                problem.SetIntermediateCallback(intermediate);
                double obj;
                Log(String.Format("{0} {4,15} {1,15} {3,15} {2}", "ITER", "D_NORM", "ALG", "INF_PR", "OBJ"));
                status = problem.SolveProblem(x0, out obj, r);
                //ProblemData.Update(ProblemData.VariableValues);
                Log(String.Format("{0:0000} {4,15} {1,15} {3,15} {2}", iterations, "", status, "", obj.ToString("G4", CultureInfo.InvariantCulture)));
            }

            // var status == IpoptReturnCode.Solve_Succeeded;
            bool result = false;

            switch (status)
            {
            case IpoptReturnCode.Solve_Succeeded:
            case IpoptReturnCode.Solved_To_Acceptable_Level:
                result = true;
                break;

            case IpoptReturnCode.Maximum_CpuTime_Exceeded:
                result = false;
                break;

            case IpoptReturnCode.Maximum_Iterations_Exceeded:
                result = false;
                break;

            case IpoptReturnCode.Infeasible_Problem_Detected:
            case IpoptReturnCode.Restoration_Failed:
                result = false;
                break;
            }
            return(result);
        }