# 出典: mo-notebooks/06/building-insulation.ipynb

# %%
# install dependencies and select solver

SOLVER_CONIC = "mosek"  # ipopt, mosek, gurobi, knitro

from amplpy import AMPL, ampl_notebook

ampl = ampl_notebook(
    modules=["coin", "mosek"],  # modules to install
    license_uuid="default",  # license to use
)  # instantiate AMPL object and register notebook magics

# %%
# application parameters
alpha = 30  # $ K / W annualized cost per sq meter per W/sq m/K
beta = 0.05  # equivalent annual cost factor
R0 = 2.0  # Watts/K/m**2
T = 0.30  # maximum insulation thickness

# material properties
k = 0.030  # thermal conductivity as installed
a = 5.0  # installation cost per square meter
b = 150.0  # installed material cost per cubic meter

# %%
import matplotlib.pyplot as plt
import numpy as np

f = lambda x: alpha / (R0 + x / k)
g = lambda x: beta * (a + b * x)

# solution
xopt = -k * R0 + np.sqrt(alpha * k / beta / b)

print(f"The optimal cost is equal to {f(xopt) + g(xopt):0.5f} per sq. meter")
print(f"The optimal thickness is {xopt:0.5f} meters\n")

# plotting
x = np.linspace(0, 1, 201)

fig, ax = plt.subplots(1, 1, figsize=(6.5, 4))

ax.plot(x, f(x), label="energy")
ax.plot(x, g(x), label="insulation")
ax.plot(x, f(x) + g(x), label="total", lw=3)
ax.plot(xopt, f(xopt) + g(xopt), ".", ms=10, label="minimum")
ax.legend()

ax.plot([0, xopt], [f(xopt) + g(xopt)] * 2, "r--")
ax.plot([xopt] * 2, [0, f(xopt) + g(xopt)], "r--")
ax.text(0, f(xopt) + g(xopt) + 0.3, f"{f(xopt) + g(xopt):0.3f}")
ax.text(xopt, 0.3, f"{xopt:0.3f}")

ax.set_xlabel("Insulation thickness [m]")
ax.set_ylabel("Cost ")
ax.set_title("Annualized costs of insulation and energy per sq. meter")

ax.grid(True)

# %%
ampl = AMPL()

ampl.eval(
    r"""
    # application parameters
    param alpha;      # $ K / W annualized cost per sq meter per W/sq m/K
    param beta;       # equivalent annual cost factor
    param R0;         # Watts/K/m**2
    param T;          # maximum insulation thickness

    # material properties
    param k;          # thermal conductivity as installed
    param a;          # installation cost per square meter
    param b;          # installed material cost per cubic meter

    # decision variables
    var R >= 0;
    var U >= 0;
    var x >= 0 <= T;

    # objective
    minimize cost: alpha*U + beta*(a + b*x);

    # insulation model
    s.t. r: R == R0 + x/k;

    # conic constraint
    s.t. q: R*U >= 1;
"""
)

ampl.param["alpha"] = alpha
ampl.param["beta"] = beta
ampl.param["R0"] = R0
ampl.param["T"] = T

ampl.param["k"] = k
ampl.param["a"] = a
ampl.param["b"] = b

ampl.solve(solver=SOLVER_CONIC)
assert ampl.solve_result == "solved", ampl.solve_result

print(
    f"The optimal cost is equal to {ampl.get_objective('cost').value():0.5f} per sq. meter"
)
print(f"The optimal thickness is xopt = {ampl.get_value('x'):0.5f} meters")

# %%
def insulate(df, alpha, beta, R0, T):
    ampl = AMPL()

    ampl.eval(
        r"""
        # application parameters
        param alpha;      # $ K / W annualized cost per sq meter per W/sq m/K
        param beta;       # equivalent annual cost factor
        param R0;         # Watts/K/m**2
        param T;          # maximum insulation thickness

        # material properties
        set MAT;
        param k{MAT};     # thermal conductivity as installed
        param a{MAT};     # installation cost per square meter
        param b{MAT};     # installed material cost per cubic meter

        # decision variables
        var R >= 0;
        var U >= 0;
        var x{MAT} >= 0;
        var y{MAT} binary;

        # objective
        minimize cost:
            alpha*U + beta * sum {i in MAT} (a[i] + b[i]*x[i]);

        # insulation model
        s.t. insulation: R == R0 + sum {i in MAT} x[i]/k[i];

        # total thickness limit
        s.t. thickness: sum {i in MAT} x[i] <= T;

        # layer model   
        s.t. layers {i in MAT}:
            x[i] <= T * y[i];

        # conic constraint
        s.t. q: R*U >= 1;
    """
    )

    ampl.param["alpha"] = alpha
    ampl.param["beta"] = beta
    ampl.param["R0"] = R0
    ampl.param["T"] = T

    ampl.set["MAT"] = list(df.index)
    ampl.set_data(df, "MAT")

    ampl.solve(solver=SOLVER_CONIC)
    assert ampl.solve_result == "solved", ampl.solve_result

    df["x_opt"] = ampl.get_variable("x").to_pandas()

    print(
        f"\nThe optimal cost is equal to"
        f" {ampl.get_objective('cost').value():0.5f} per sq. meter"
    )
    display(df.round(5))

    return ampl

# %%
import pandas as pd

# application parameters
alpha = 30  # $ K / W annualized cost per sq meter per W/sq m/K
beta = 0.05  # equivalent annual cost factor
R0 = 2.0  # Watts/K/m**2
T = 0.30  # maximum insulation thickness

df = pd.DataFrame(
    {
        "Mineral Wool": {"k": 0.030, "a": 5.0, "b": 150.0},
        "Rigid Foam (high R)": {"k": 0.015, "a": 8.0, "b": 180.0},
        "Rigid Foam (low R)": {"k": 0.3, "a": 8.0, "b": 120.0},
    }
).T

m = insulate(df, alpha, beta, R0, T)

# %%
# application parameters
alpha = 30  # $ K / W annualized cost per sq meter per W/sq m/K
beta = 0.05  # equivalent annual cost factor
R0 = 2.0  # Watts/K/m**2
T = 0.15  # maximum insulation thickness

df = pd.DataFrame(
    {
        "Foam": {"k": 0.015, "a": 0.0, "b": 110.0},
        "Wool": {"k": 0.010, "a": 0.0, "b": 200.0},
    }
).T

m = insulate(df, alpha, beta, R0, T)

# %%
import numpy as np
import matplotlib.pyplot as plt

k = list(df["k"])
a = list(df["a"])
b = list(df["b"])

f = lambda x0, x1: alpha / (R0 + x0 / k[0] + x1 / k[1]) + beta * (
    a[0] + b[0] * x0 + a[1] + b[1] * x1
)

x0 = np.linspace(0, 1.1 * T, 201)
x1 = np.linspace(0, 1.1 * T, 201)

X0, X1 = np.meshgrid(x0, x1)

fig, ax = plt.subplots(1, 1)
ax.contour(x0, x1, f(X0, X1), 50)
ax.set_xlim(min(x0), max(x0))
ax.set_ylim(min(x1), max(x1))
ax.plot([0, T], [T, 0], "g", lw=2.5)

ax.set_aspect(1)

x = df["x_opt"].to_list()

ax.plot(x[0], x[1], "r.", ms=20)
ax.text(x[0], x[1], f"    ({x[0]:0.4f}, {x[1]:0.4f})")

ax.set_xlabel(r"$x_0$")
ax.set_ylabel(r"$x_1$")
ax.set_title("Contours of Constant Cost")
plt.show()
