强制MS Solver找到解决方案

时间:2016-08-31 14:51:07

标签: c# winforms ms-solver-foundation

如果不像Excel中那样满足所有约束条件,我如何强制MS求解器找到模型的解决方案? 我找到了一个方法GetInfeasibilitySet(显然它返回了模型中不满足的约束),这个方法在LinearReport对象中,但我无法实例化这个对象,因为它需要我无法实例化的ISolver和LinearSolutionMappings参数同样。

1 个答案:

答案 0 :(得分:0)

I solved the problem. Here's my code.

        //constraints avoiding the optimal solution 
        List<int> Restricoes = new List<int>();

        bool solucaoOtima = false;

        //index = 1, because the first constraint is always in the model
        int index = 1;

        while (solucaoOtima == false)
        {
            var restricao = auxModel.Constraints.ToList()[index];

            restricao.Enabled = false;

            auxSolution = auxContext.Solve();

            //that's the trick part, I assumed that if I find the optimal
            //solution by removing the current index, then I assumed
            //the problem was this index
            if (auxSolution.Quality.ToString().Equals("Optimal"))
            {
                Restricoes.Add(index); 
                VoltarRestricoes(auxModel, Restricoes);

                auxSolution = auxContext.Solve();

                solucaoOtima =   auxSolution.Quality.ToString().Equals("Optimal") ? true : false;
            }

            index = index == limiteIteracao ? 1 : index + 1;
        }

    /// <summary>
    /// Reset all the constraints of the model, except those indexes that are in Restricoes list.
    /// </summary>
    /// <param name="auxModel"></param>
    /// <param name="Restricoes"></param>
    private void VoltarRestricoes(Model auxModel, List<int> Restricoes)
    {
        for (int i = 0; i < auxModel.Constraints.ToList().Count; i++)
        {
            var restricao = auxModel.Constraints.ToList()[i];
            restricao.Enabled = Restricoes.Contains(i) ? false : true;
        }
    }