"""区分的線形近似の 5 つの定式化の比較（8 章）.

凹関数 f(x) = -x^2 + 10x を [0,10] で 10 等分して近似し、x >= 3 のもとで最小化する。
真の答えは x=10, f=0。凸結合定式化だけが誤った解（x=3 で f=0）を返す。
"""
from amplpy import AMPL

K = 10
a = {k: k for k in range(K+1)}
b = {k: -(k**2) + 10*k for k in range(K+1)}

MODELS = ["convex_comb.mod", "convex_comb_sos.mod",
          "convex_comb_dis.mod", "convex_comb_dis_log.mod",
          "mult_selection.mod"]

for mod in MODELS:
    ampl = AMPL()
    ampl.read(mod)
    ampl.read("pw_objective.mod")      # 試験用の目的関数を重ねて読み込む
    ampl.param["K"] = K
    ampl.param["a"] = a
    ampl.param["b"] = b
    ampl.param["xlb"] = 3
    ampl.option["solver"] = "highs"
    try:
        ampl.solve(verbose=False)
        if ampl.solve_result == "solved":
            print("%-24s obj=%-8.3f x=%.3f" % (
                mod, ampl.get_objective("Obj").value(),
                ampl.get_variable("x").value()))
        elif mod == "convex_comb_sos.mod":
            print("%-24s SOS2 非対応のソルバー（Gurobi 等が必要）" % mod)
        else:
            print("%-24s %s" % (mod, ampl.solve_result))
    except Exception as exc:
        # convex_comb_sos.mod は SOS2 対応ソルバーが必要（HiGHS では解けない）
        print("%-24s ソルバー非対応: %s" % (mod, str(exc).split("\n")[0]))
