这是我第一次使用 Solver Foundation,我不明白如何指定目标函数。我试图使用 Solver 解决的问题是根据目标函数在 2D 表面上找到最佳点。作为输入数据,我在这个表面上有 3 个点,声波需要从源(最佳点)到达这三个点的时间差。这个时间差导致距离差。
这是我的代码:
var solver = SolverContext.GetContext();
var model = solver.CreateModel();
decisionX = new Decision( Domain.Real, "X" );
decisionY = new Decision( Domain.Real, "Y" );
model.AddDecision( decisionX );
model.AddDecision( decisionY );
model.AddGoal( "Goal", GoalKind.Minimize, GoalFunction() );
var solution = solver.Solve();
Console.WriteLine("X " + decisionX.GetDouble());
Console.WriteLine("Y " + decisionY.GetDouble());
GoalFunction() 定义如下:
double GoalFunction() {
Location X = new Location( decisionX.ToDouble(), decisionY.ToDouble() );
var rA = A.Location.Distance( X );
var rB = B.Location.Distance( X );
var rC = C.Location.Distance( X );
rA = (Distance)( rA - dsA );
rB = (Distance)( rB - dsA );
rC = (Distance)( rC - dsA );
return ( rA * rA + rB * rB + rC * rC ) / 3;
}
上面的代码抛出异常 ( decisionX.ToDouble()
),因为此时尚未初始化决策。
有人可以帮我重写吗?
我已将我的 GoalFunction 重写为 all-Model.methods-calls。
var solver = SolverContext.GetContext();
var model = solver.CreateModel();
decisionX = new Decision( Domain.Real, "X" );
decisionY = new Decision( Domain.Real, "Y" );
model.AddDecision( decisionX );
model.AddDecision( decisionY );
var rA = Model.Difference(
Model.Sqrt(
Model.Sum(
Model.Power( Model.Difference( decisionX, A.Location.X ), 2 ),
Model.Power( Model.Difference( decisionY, A.Location.Y ), 2 )
)
),
dsA.Value
);
var rB = Model.Difference(
Model.Sqrt(
Model.Sum(
Model.Power( Model.Difference( decisionX, B.Location.X ), 2 ),
Model.Power( Model.Difference( decisionY, B.Location.Y ), 2 )
)
),
dsB.Value
);
var rC = Model.Difference(
Model.Sqrt(
Model.Sum(
Model.Power( Model.Difference( decisionX, C.Location.X ), 2 ),
Model.Power( Model.Difference( decisionY, C.Location.Y ), 2 )
)
),
dsC.Value
);
var miner = Model.Min( rA, rB, rC );
rA = Model.Difference( rA, miner );
rB = Model.Difference( rB, miner );
rC = Model.Difference( rC, miner );
var goal = Model.Sum(
Model.Power( rA, 2 ),
Model.Power( rB, 2 ),
Model.Power( rC, 2 )
);
model.AddGoal( "Goal", GoalKind.Minimize, goal );
var solution = solver.Solve();
var q = solution.Quality;
double x = decisionX.GetDouble();
double y = decisionY.GetDouble();
solution.GetNext();
x = decisionX.GetDouble();
y = decisionY.GetDouble();
此代码有效,但返回 {0.0} 作为 LocalOptimal 解决方案,而最优是 {2,2}(我检查过,GoalFunction 为 {2,2} 返回 0,而为 {0,0} 返回更高的值。可能是 {0,当决策是 Domain.Real 时,0} 是起点。
Solution.GetNext() 没有任何改变。
decisionX = new Decision( Domain.RealRange( -10, 10 ), "X" );
decisionY = new Decision( Domain.RealRange( -10, 10 ), "Y" );
如果我限制域,返回的解决方案是 {1.9999999984154413,1.99999999990963979} 所以它是正确的。
但为什么解算器不启动完整的真实域?还是不知道
也许有一天有人会回答......我希望,但我将下面的答案标记为正确。