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

32 篇文章 0 订阅
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);
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值