using Plots
using LaTeXStrings
theme(:dark)
default(size = (800, 600)) # set default plot size
# Define objective functions, constraint function, and Lagrangian
# (Coefficients obtained from polynomial interpolation)
f(x) = 0.0313178884607x^4 - 0.4376575805147x^3 + 1.9507119864263x^2 - 3.3803696303696x + 6.0
g(x) = 1/2 * (x-3)^2 - 2
L(x, λ) = f(x) + λ * g(x)
x_range = 0:0.01:8
# Plot objective function f
fig = plot(x_range, f, label="f(x)", c=:red, linewidth=2)
# Vertical lines to mark the feasible region
vline!(fig, [1], linestyle=:dash, linecolor=:white, label="")
vline!(fig, [5], linestyle=:dash, linecolor=:white, label="")
# Plot the feasible region
x_feasible = x_range[1 .<= x_range .&& x_range .<= 5]
f_feasible = f.(x_feasible)
plot!(fig, x_feasible, f_feasible, label="Feasible Region",
fillrange=0, color=:blue, alpha=0.1,
yrange=(0, 10), legend=:topright)
annotate!(fig, 3.0, 1.0, "feasible region")
# Function to determine the optimal x for a given Lagrange function
x_optimal_for_lambda(λ) = x_range[argmin(L.(x_range, λ))]
# Plot the Lagrangian for different lambdas
for λ in [0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3]
plot!(fig, x_range, L.(x_range, λ), label="",
c=:lightblue, linewidth=1.5, linestyle=:dot)
end
# Get the optimal point of the Lagragian with given lambda
function dual_function_parametric(λ)
x_min = x_optimal_for_lambda(λ)
y_min = L(x_min, λ)
return x_min, y_min
end
lambda_range = 0:0.01:1.3
points_tuple_array = dual_function_parametric.(lambda_range)
# Extract x and y coordinates
x_coords = first.(points_tuple_array)
y_coords = last.(points_tuple_array)
# Plot dual function
plot!(fig, x_coords, y_coords, c="black", linewidth=5, label="dual function")
# Scatter plot for the optima of the Lagrangian
for λ in [0.1, 0.3, 0.7, 0.9, 1.1, 1.3]
x_min = x_optimal_for_lambda(λ)
y_min = L(x_min, λ)
scatter!(fig, [x_min], [y_min], label="", c=:black, markersize=4)
end
# Plot the optimal point
scatter!(fig, [5], [f(5)], markersize=6, color=:green, label="optimal point")
# Don't forget to display the plot
display(fig)