迫使求解器找到一个解

本文关键字:一个 | 更新日期: 2023-09-27 18:04:52

当不是所有的约束都像在Excel中一样满足时,我怎么能强迫MS求解器找到一个模型的解决方案?我发现了一个方法getin可行性集(显然它返回模型中不满足的约束),这是在线性报告对象,但我不能实例化这个对象,因为它需要ISolver和LinearSolutionMappings参数,我也不能实例化。

迫使求解器找到一个解

我解决了这个问题。这是我的代码。

        //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;
        }
    }
相关文章: