【C#】 24. HybridLocalSearchSolver + 自定义函数调用 + AddConstraint (constraint===1)

来源:互联网 发布:java代码漏洞扫描工具 编辑:程序博客网 时间:2024/05/20 19:31
using System;using System.Collections.Generic;using System.Linq;using System.Text;using Microsoft.SolverFoundation.Services;using Microsoft.SolverFoundation.Solvers;namespace ConsoleApplication1{    public static class SF    {        public static void Main()        {            IndividualSolvers();            //TheAbstractWay();            Console.ReadLine();        }        private static double MinimizeThat(double[] args)        {                   return Math.Cos(args[0]) + args[1] * args[1];        }        private static double  Cons(double[] args)        {            return(Math.Abs (args[0] + args[1]));        }        private static void IndividualSolvers()        {            var hls = new HybridLocalSearchSolver();            int x, y,z;                        hls.AddVariable(out x, 0, 5, false);            hls.AddVariable(out y,-1, 1,true);            z = hls.CreateNaryFunction(Cons, new[] { x, y });            hls.AddConstraint(z); //constraint z =1             hls.AddGoal(hls.CreateNaryFunction(MinimizeThat,  new[] { x, y }));                       var hlsr = hls.Solve(new HybridLocalSearchParameters());            Console.WriteLine("HLS: f({0}, {1}) = {2}", hlsr.GetValue(x),hlsr.GetValue(y), hlsr.GetSolutionValue(0));            Console.WriteLine("Constraint x+y = {0}",hlsr.GetValue(z));            //var nms = NelderMeadSolver.Solve(MinimizeThat, new[] { 0.0, 0.0 }, new[] { 0.0, -1.0 }, new[] { 5.0, 1.0 });            //Console.WriteLine("NMS: f({0}, {1}) = {2}", nms.GetValue(1), nms.GetValue(2), nms.GetSolutionValue(0));        }        private static void TheAbstractWay()        {            var ctx = new SolverContext();            var m = ctx.CreateModel();            var x = new Decision(Domain.Real, "x");            var y = new Decision(Domain.Real, "y");            m.AddDecisions(x, y);            m.AddConstraints("Bounds", 0 <= x, x <= 5, -1 <= y, y <= 1);            m.AddGoal("Minimize", GoalKind.Minimize, "Cos[x]+y^2");            //m.AddGoal("Minimize", GoalKind.Minimize, Model.Cos(x) + y * y);            var r = ctx.Solve();            ctx.PropagateDecisions();            Console.WriteLine("{3}: f({0}, {1}) = {2}", x.GetDouble(), y.GetDouble(), r.Goals.Single().ToDouble(), r.GetReport().SolverType.Name);        }    }}

0 0