Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Algorithms Homework 5

Course policies and AI category

Read the Artificial Intelligence Policy and Collaboration Policy and Honor Code before starting. Assignment-specific directions control. The categories are No AI, AI permitted after independent work, and AI required.

Unless a problem says otherwise, its category is AI permitted after independent work. Spend about 30 minutes on each top-level problem without AI, solution pages, or another person’s help, stopping early if complete. You may consult lecture notes, textbooks, and nonsolution pages of the course website; bias toward those course sources. Afterward, AI and genuine collaboration, including coding together, are permitted. Everyone must contribute intellectually, understand the work, and verify it.

At the end of each top-level problem, add a concise AI disclosure: approximately how long the independent attempt took, how far you got, where you became stuck, any AI or collaborative help used afterward, and how you verified it. If you used no AI, say so. Do not submit prompts or transcripts. Time estimates help the instructor improve the assignment and are not a speed test.

Overview

This assignment practices Lecture 24 (Barrier and Interior Point Methods) and pulls together several earlier lectures:

  • Lecture 19 (KKT Conditions, Multipliers, and Sensitivity): KKT conditions, multipliers, and strongly or weakly active bounds (Problem 1).

  • Lecture 21 (Second Order Conditions and Equality Constrained NLPs): the Newton step for the KKT system and inertia correction (Problems 2 and 3).

  • Lecture 22 (Globalization for Constrained Optimization): the merit function and the filter (Problems 3 and 4). This is a recorded lecture this semester; Lecture 24 restates what you need.

  • Lecture 24 (Barrier and Interior Point Methods): the barrier subproblem, central path, primal-dual step, and fraction-to-the-boundary rule (all problems).

The problems are ordered so that you can start before Lecture 24:

  • Problems 1 and 2 need only this notebook’s background section (and Lectures 19 and 21). Start them before Lecture 24.

  • Problem 3 runs a supplied interior point solver that calls your Problem 2 code. Do it after Lecture 24.

  • Problem 4 is optional.

Expect about three hours. Derivations may be done on paper; upload a photo or scan of that work.

Background: the primal-dual interior point step

We solve

min⁡xf(x)s.t.h(x)=0,xi≥0    (i∈I),\min_{\mathbf{x}} f(\mathbf{x}) \quad \mathrm{s.t.} \quad \mathbf{h}(\mathbf{x}) = \mathbf{0}, \quad x_i \ge 0 \;\; (i \in \mathcal{I}),

where I\mathcal{I} lists the rr coordinates with a lower bound of zero (bounds in the code) and J\mathbf{J} is the m×nm \times n row Jacobian of h\mathbf{h}. Following Lecture 24, the Lagrangian is L=f+vTh−∑i∈IuixiL = f + \mathbf{v}^T \mathbf{h} - \sum_{i \in \mathcal{I}} u_i x_i with bound multipliers u≥0\mathbf{u} \ge \mathbf{0}.

Barrier subproblem. For μ>0\mu > 0, replace the bounds by a logarithmic barrier:

min⁡x  φμ(x)=f(x)−μ∑i∈Ilog⁡xis.t.h(x)=0.\min_{\mathbf{x}} \; \varphi_\mu(\mathbf{x}) = f(\mathbf{x}) - \mu \sum_{i \in \mathcal{I}} \log x_i \quad \mathrm{s.t.} \quad \mathbf{h}(\mathbf{x}) = \mathbf{0}.

Its solutions x(μ)\mathbf{x}(\mu) trace the central path. Writing ui=μ/xiu_i = \mu / x_i turns its optimality conditions into the primal-dual equations, which are the KKT conditions with complementarity perturbed from xiui=0x_i u_i = 0 to xiui=μx_i u_i = \mu:

rd=∇f+JTv−Gu=0,rh=h=0,rc=X^u−μe=0,\mathbf{r}_d = \nabla f + \mathbf{J}^T \mathbf{v} - \mathbf{G}\mathbf{u} = \mathbf{0}, \qquad \mathbf{r}_h = \mathbf{h} = \mathbf{0}, \qquad \mathbf{r}_c = \hat{\mathbf{X}} \mathbf{u} - \mu \mathbf{e} = \mathbf{0},

with X^=diag(xi:i∈I)\hat{\mathbf{X}} = \mathrm{diag}(x_i : i \in \mathcal{I}), e\mathbf{e} a vector of ones and G\mathbf{G} the n×rn \times r matrix that places bound multipliers in their coordinates.

Newton step. Linearizing gives the full (unsymmetric) system from Lecture 24, with U=diag(u)\mathbf{U} = \mathrm{diag}(\mathbf{u}) and W=∇xx2(f+vTh)\mathbf{W} = \nabla^2_{\mathbf{xx}}(f + \mathbf{v}^T\mathbf{h}), which contains no barrier term:

[WJT−GJ00UGT0X^][dxdvdu]=−[rdrhrc].\begin{bmatrix} \mathbf{W} & \mathbf{J}^T & -\mathbf{G} \\ \mathbf{J} & \mathbf{0} & \mathbf{0} \\ \mathbf{U}\mathbf{G}^T & \mathbf{0} & \hat{\mathbf{X}} \end{bmatrix} \begin{bmatrix} \mathbf{d}_x \\ \mathbf{d}_v \\ \mathbf{d}_u \end{bmatrix} = - \begin{bmatrix} \mathbf{r}_d \\ \mathbf{r}_h \\ \mathbf{r}_c \end{bmatrix}.

Eliminating du\mathbf{d}_u with the last block row gives the smaller, symmetric system that the solver uses,

[W+Σ+δWIJTJ−δAI][dxdv]=−[∇φμ+JTvh],Σ=GX^−1UGT,\begin{bmatrix} \mathbf{W} + \boldsymbol{\Sigma} + \delta_W \mathbf{I} & \mathbf{J}^T \\ \mathbf{J} & -\delta_A \mathbf{I} \end{bmatrix} \begin{bmatrix} \mathbf{d}_x \\ \mathbf{d}_v \end{bmatrix} = - \begin{bmatrix} \nabla \varphi_\mu + \mathbf{J}^T \mathbf{v} \\ \mathbf{h} \end{bmatrix}, \qquad \boldsymbol{\Sigma} = \mathbf{G} \hat{\mathbf{X}}^{-1} \mathbf{U} \mathbf{G}^T,

where ∇φμ=∇f−μGX^−1e\nabla \varphi_\mu = \nabla f - \mu \mathbf{G} \hat{\mathbf{X}}^{-1} \mathbf{e}, followed by

du=μX^−1e−u−X^−1UGTdx.\mathbf{d}_u = \mu \hat{\mathbf{X}}^{-1} \mathbf{e} - \mathbf{u} - \hat{\mathbf{X}}^{-1} \mathbf{U} \mathbf{G}^T \mathbf{d}_x .

Σ\boldsymbol{\Sigma} is diagonal, with ui/xiu_i / x_i in bounded coordinates and zero elsewhere. The shifts δW,δA≥0\delta_W, \delta_A \ge 0 are inertia corrections (Lecture 21); the solver chooses them, and with both zero the system is exactly the elimination above (Eqs. 6.56--6.58 in Biegler, 2010).

Staying interior. The iterates must keep xi>0x_i > 0 and ui>0u_i > 0. The fraction-to-the-boundary rule caps the step: for a positive vector z\mathbf{z} with step d\mathbf{d} and 0<τ<10 < \tau < 1,

αmax⁡=min⁡{1,  min⁡i: di<0−τzidi},soz+αd≥(1−τ)z>0    for 0≤α≤αmax⁡.\alpha_{\max} = \min\left\{1, \; \min_{i:\, d_i < 0} \frac{-\tau z_i}{d_i}\right\}, \qquad \text{so} \qquad \mathbf{z} + \alpha \mathbf{d} \ge (1 - \tau)\mathbf{z} > \mathbf{0} \;\; \text{for } 0 \le \alpha \le \alpha_{\max}.

It is applied separately to x\mathbf{x} (bounded coordinates) and to u\mathbf{u} (Eqs. 6.61--6.62 in Biegler, 2010).

Outer loop. Solve the barrier subproblem approximately, until Eμ=max⁡{∥rd∥∞,∥rh∥∞,∥rc∥∞}≤10μE_\mu = \max\{\|\mathbf{r}_d\|_\infty, \|\mathbf{r}_h\|_\infty, \|\mathbf{r}_c\|_\infty\} \le 10\mu, then decrease μ\mu by μl+1=max⁡{ϵtol/10,min⁡(0.2 μl,μl1.5)}\mu_{l+1} = \max\{\epsilon_{\rm tol}/10, \min(0.2\,\mu_l, \mu_l^{1.5})\}, as in Lecture 24.

### Load Python libraries and finite-difference helpers (provided)

import sys

if "google.colab" in sys.modules:
    !wget "https://raw.githubusercontent.com/ndcbe/optimization/main/notebooks/helper.py"
    import helper

    helper.easy_install()
    helper.install_idaes()
    helper.install_ipopt()
else:
    sys.path.insert(0, "../")
    import helper
helper.set_plotting_style()

import contextlib
import io
import warnings

import numpy as np
from scipy import linalg
import pyomo.environ as pyo


def my_grad_approx(x, f, eps1=1e-6):
    """Gradient of the scalar function f at x by central differences."""
    n = len(x)
    grad = np.zeros(n)
    for i in range(n):
        e = np.zeros(n)
        e[i] = eps1
        grad[i] = (f(x + e) - f(x - e)) / (2 * eps1)
    return grad


def my_jac_approx(x, h, eps1=1e-6):
    """Row Jacobian J (m x n) of the vector function h at x by central differences."""
    n = len(x)
    m = len(h(x))
    J = np.zeros((m, n))
    for i in range(n):
        e = np.zeros(n)
        e[i] = eps1
        J[:, i] = (h(x + e) - h(x - e)) / (2 * eps1)
    return J


def my_hes_approx(x, grad, eps2=1e-6):
    """Hessian from a gradient function by central differences."""
    n = len(x)
    H = np.zeros((n, n))
    for i in range(n):
        e = np.zeros(n)
        e[i] = eps2
        H[:, i] = (grad(x + e) - grad(x - e)) / (2 * eps2)
    return 0.5 * (H + H.T)

Problem 1: The central path by hand

Consider

min⁡x  x12+3x2s.t.x1+x2=1,x2≥0.\min_{\mathbf{x}} \; x_1^2 + 3 x_2 \quad \mathrm{s.t.} \quad x_1 + x_2 = 1, \quad x_2 \ge 0 .

Only x2x_2 is bounded, so I={2}\mathcal{I} = \{2\} and there is one bound multiplier uu and one equality multiplier vv.

1a. The KKT point

Write the KKT conditions with the Lecture 24 Lagrangian L=f+v h−u x2L = f + v\,h - u\,x_2. Find x∗\mathbf{x}^*, v∗v^* and u∗u^*. Is the bound strongly or weakly active (Lecture 19)?

Answer:

x∗\mathbf{x}^*v∗v^*u∗u^*Strongly or weakly active?

1b. The barrier subproblem and its solution

Write the barrier subproblem for this problem. Eliminate x1x_1 with the equality constraint and solve for x2(μ)x_2(\mu) in closed form. Then give x1(μ)x_1(\mu), v(μ)v(\mu) and u(μ)=μ/x2(μ)u(\mu) = \mu / x_2(\mu). Show that x(μ)→x∗\mathbf{x}(\mu) \to \mathbf{x}^* and u(μ)→u∗u(\mu) \to u^* as μ→0\mu \to 0. Hint: you should obtain a quadratic in x2x_2; keep the positive root.

# Add your solution here

Answer:

1c. Tabulate the central path

Complete central_path(mu) (return x(μ)\mathbf{x}(\mu), v(μ)v(\mu) and u(μ)u(\mu)) if you have not already, and tabulate x2(μ)x_2(\mu), u(μ)u(\mu), x2ux_2 u and ∥x(μ)−x∗∥∞\|\mathbf{x}(\mu) - \mathbf{x}^*\|_\infty for μ=1,0.1,0.01,0.001\mu = 1, 0.1, 0.01, 0.001. How does the distance to x∗\mathbf{x}^* scale with μ\mu? Which KKT condition does every point on the central path violate, and by how much?

# Add your solution here

Answer:

μ\mux2(μ)x_2(\mu)u(μ)u(\mu)x2ux_2 u∥x(μ)−x∗∥∞\lVert\mathbf{x}(\mu) - \mathbf{x}^*\rVert_\infty
1
0.1
0.01
0.001

AI disclosure

Approximately how long was your independent attempt?

How far did you get? where did you get stuck?

What AI or collaborative help did you use afterward, and how did you verify it?

If you used no AI, answer “not applicable”.

Problem 2: Implement the primal-dual step

Complete the three functions below using the background section:

  1. fraction_to_boundary(z, dz, tau): the step cap αmax⁡\alpha_{\max}.

  2. barrier_kkt_system(...): the condensed matrix and right-hand side, including δW\delta_W and δA\delta_A.

  3. recover_du(...): the bound-multiplier step.

Loops are fine; the problems are tiny. Then run the provided tests. The second test solves your condensed system and checks that the step satisfies the full unsymmetric system, so it catches sign errors in the elimination.

def fraction_to_boundary(z, dz, tau):
    """Fraction-to-the-boundary rule (Lecture 24).

    Largest alpha in (0, 1] with z + alpha*dz >= (1 - tau)*z, elementwise.

    Inputs:
        z   - strictly positive vector (bounded components of x, or u)
        dz  - Newton step for z
        tau - fraction-to-boundary parameter, 0 < tau < 1

    Outputs:
        alpha_max - scalar in (0, 1]
    """
    # Add your solution here
    return alpha_max


def barrier_kkt_system(W, J, grad_f, h, x, u, v, mu, bounds, delta_W=0.0, delta_A=0.0):
    """Condensed primal-dual Newton system for one barrier subproblem.

    Inputs:
        W       - Hessian of the Lagrangian (n x n), WITHOUT any barrier term
        J       - row Jacobian of h (m x n)
        grad_f  - objective gradient (n)
        h       - equality constraint values (m)
        x       - current primal point (n); x[bounds] > 0
        u       - bound multipliers (r = len(bounds)); u > 0
        v       - equality multipliers (m)
        mu      - barrier parameter
        bounds  - list of the r indices with a lower bound of zero
        delta_W - inertia-correction shift on the (1,1) block
        delta_A - regularization on the (2,2) block

    Outputs:
        K   - (n + m) x (n + m) matrix
        rhs - right-hand side (n + m); the step solves K [dx; dv] = rhs
    """
    # Add your solution here
    return K, rhs


def recover_du(dx, x, u, mu, bounds):
    """Bound-multiplier step from the eliminated product row (Lecture 24).

    Outputs:
        du - step for u (length r = len(bounds))
    """
    # Add your solution here
    return du
### Tests (provided). Run after completing the three functions above.

# 1. Fraction to the boundary: the activity from Lecture 24.
alpha = fraction_to_boundary(np.array([2.0, 1.2]), np.array([-3.0, -0.5]), 0.75)
print("alpha_max for the Lecture 24 activity:", alpha)
assert abs(alpha - 0.5) < 1e-12
assert fraction_to_boundary(np.array([1.0, 2.0]), np.array([0.5, 0.0]), 0.99) == 1.0


# 2. The condensed step must satisfy the FULL primal-dual system from Lecture 24:
#      W dx + J^T dv - G du = -r_d,   J dx = -r_h,   U G^T dx + X du = -r_c
def check_full_system(W, J, grad_f, h, x, u, v, mu, bounds):
    n, m, r = len(x), len(h), len(bounds)
    K, rhs = barrier_kkt_system(W, J, grad_f, h, x, u, v, mu, bounds)
    z = linalg.solve(K, rhs)
    dx, dv = z[:n], z[n:]
    du = recover_du(dx, x, u, mu, bounds)
    G = np.zeros((n, r))
    for k, i in enumerate(bounds):
        G[i, k] = 1.0
    r_d = grad_f + J.T @ v - G @ u
    r_h = h
    r_c = x[bounds] * u - mu
    res = np.concatenate(
        (
            W @ dx + J.T @ dv - G @ du + r_d,
            J @ dx + r_h,
            u * dx[bounds] + x[bounds] * du + r_c,
        )
    )
    return dx, dv, du, linalg.norm(res, np.inf)


# Problem 1 at x = (0.5, 0.2), v = 0, u = 1, mu = 0.1. Exact derivatives.
x_t = np.array([0.5, 0.2])
dx, dv, du, res = check_full_system(
    W=np.array([[2.0, 0.0], [0.0, 0.0]]),
    J=np.array([[1.0, 1.0]]),
    grad_f=np.array([2 * x_t[0], 3.0]),
    h=np.array([x_t[0] + x_t[1] - 1]),
    x=x_t,
    u=np.array([1.0]),
    v=np.array([0.0]),
    mu=0.1,
    bounds=[1],
)
print("dx =", dx, " dv =", dv, " du =", du)
print("residual of the full primal-dual system:", res)
assert res < 1e-10, "The condensed step does not solve the full system. Check the signs."
print("All tests passed.")

2b. Interpret the condensed system

  1. Why is the condensed matrix symmetric when the full matrix is not?

  2. At the test point, x2=0.2x_2 = 0.2 and u=1u = 1, so Σ22=u/x2=5\Sigma_{22} = u/x_2 = 5. Lecture 24 contrasts Σ\boldsymbol{\Sigma} with the Hessian of the barrier term, whose entry is μ/x22\mu / x_2^2. Compute that entry for μ=0.1\mu = 0.1. When are the two equal, and why does the primal-dual method use Σ\boldsymbol{\Sigma}?

Answer:

Value at the test point
Σ22=u/x2\Sigma_{22} = u / x_2
barrier Hessian entry μ/x22\mu / x_2^2

AI disclosure

Approximately how long was your independent attempt?

How far did you get? where did you get stuck?

What AI or collaborative help did you use afterward, and how did you verify it?

If you used no AI, answer “not applicable”.

Problem 3: Run an interior point method

The solver below is provided. It evaluates derivatives by finite differences, applies inertia correction (Algorithm 5.2 in Biegler, 2010), calls your three functions for the step, and offers four step-length strategies:

  • "none": always take the full step.

  • "boundary": apply the fraction-to-the-boundary rule and nothing else.

  • "merit": fraction to the boundary, then backtrack on the ℓ1\ell_1 merit function φμ+ρ ∥h∥1\varphi_\mu + \rho\,\|\mathbf{h}\|_1 (Lecture 22).

  • "filter": fraction to the boundary, then a backtracking filter line search on (∥h∥1,φμ)(\|\mathbf{h}\|_1, \varphi_\mu) (Lecture 22).

You do not need to modify it. Read barrier_subproblem and find where your functions are called.

### Interior point solver (provided). It calls YOUR three functions.

def barrier_objective(x, calc_f, bounds, mu):
    """phi_mu(x) = f(x) - mu * sum(log x_i); +inf outside the domain of the log."""
    xb = x[bounds]
    if np.any(xb <= 0):
        return np.inf
    return calc_f(x) - mu * np.sum(np.log(xb))


def constraint_violation(x, calc_h):
    """theta(x) = ||h(x)||_1"""
    return linalg.norm(calc_h(x), 1)


def filter_dominated(theta, phi, filter_set):
    """True if some filter entry is no worse in both theta and phi."""
    return any(theta >= t and phi >= p for t, p in filter_set)


def count_inertia(K, zero_tol=1e-12):
    """(positive, negative, zero) eigenvalue counts of K."""
    l = np.real(linalg.eigvals(K))
    return sum(l >= zero_tol), sum(l <= -zero_tol), sum(np.abs(l) < zero_tol)


def barrier_subproblem(x0, v0, u0, calc_f, calc_h, bounds, mu, eps,
                       max_iter=100, globalization="boundary", info=None, verbose=False):
    """Newton's method on the primal-dual equations for one barrier parameter mu.

    globalization:
        "none"     - full step, alpha = 1, no safeguard
        "boundary" - fraction-to-the-boundary rule only, no acceptance test
        "merit"    - fraction to the boundary, then Armijo backtracking on the l1 merit function
        "filter"   - fraction to the boundary, then a backtracking filter line search
    """
    if globalization not in ("none", "boundary", "merit", "filter"):
        raise ValueError("Unknown globalization strategy: " + str(globalization))

    # Inertia correction (Algorithm 5.2 in Biegler, 2010)
    dW_min, dW_0, dW_max, dA_bar, kappa_u, kappa_l = 1e-20, 1e-4, 1e40, 1e-8, 8, 1 / 3
    # Line search (Section 5.6 in Biegler, 2010)
    tau = max(0.99, 1.0 - mu)
    eta, xi, alpha_min, rho_margin = 1e-4, 0.5, 1e-10, 1.0
    gamma_theta, gamma_phi, delta_switch, s_phi, s_theta = 1e-5, 1e-5, 1.0, 2.3, 1.1

    x, v, u = np.array(x0, dtype=float), np.array(v0, dtype=float), np.array(u0, dtype=float)
    n, m = len(x), len(calc_h(x))
    dW_last, rho, filter_set, log = 0.0, 0.0, [], []
    status, E, k = "converged", np.inf, 0

    while k < max_iter:
        if (not np.all(np.isfinite(x))) or np.any(x[bounds] <= 0):
            status, E = "left the interior", np.inf
            break

        f_k, h_k = calc_f(x), calc_h(x)
        grad_f = my_grad_approx(x, calc_f)
        J = my_jac_approx(x, calc_h)
        L_grad = lambda z, v=v: my_grad_approx(z, lambda y: calc_f(y) + calc_h(y) @ v)
        W = my_hes_approx(x, L_grad)

        # Convergence check on the barrier residual E_mu (Lecture 24)
        G_u = np.zeros(n)
        G_u[bounds] = u
        E = max(
            linalg.norm(grad_f + J.T @ v - G_u, np.inf),
            linalg.norm(h_k, np.inf),
            linalg.norm(x[bounds] * u - mu, np.inf),
        )
        if E <= eps:
            break

        # Step 1: assemble and correct the inertia to (n, m, 0)
        dW, dA = 0.0, 0.0
        K, rhs = barrier_kkt_system(W, J, grad_f, h_k, x, u, v, mu, bounds, dW, dA)
        pos, neg, zero = count_inertia(K)
        if not (pos == n and neg == m):
            if zero:
                dA = dA_bar
            dW = dW_0 if dW_last == 0 else max(dW_min, kappa_l * dW_last)
            while True:
                K, rhs = barrier_kkt_system(W, J, grad_f, h_k, x, u, v, mu, bounds, dW, dA)
                pos, neg, zero = count_inertia(K)
                if pos == n and neg == m:
                    break
                dW = kappa_u * dW
                if dW > dW_max:
                    status = "ill-conditioned KKT matrix"
                    break
            if status != "converged":
                break
        dW_last = dW

        # Step 2: solve, then recover du
        z = linalg.solve(K, rhs)
        dx, dv = z[:n], z[n:]
        du = recover_du(dx, x, u, mu, bounds)

        # Step 3: step lengths
        phi_k = barrier_objective(x, calc_f, bounds, mu)
        theta_k = constraint_violation(x, calc_h)
        grad_phi = grad_f.copy()
        grad_phi[bounds] -= mu / x[bounds]
        rejected = []

        if globalization == "none":
            alpha, alpha_u = 1.0, 1.0
        else:
            alpha = fraction_to_boundary(x[bounds], dx[bounds], tau)
            alpha_u = fraction_to_boundary(u, du, tau)

        if globalization == "merit":
            rho = max(rho, linalg.norm(v + dv, np.inf) + rho_margin)
            merit_k = phi_k + rho * theta_k
            D_merit = grad_phi @ dx - rho * theta_k
            while True:
                xt = x + alpha * dx
                phi_t = barrier_objective(xt, calc_f, bounds, mu)
                theta_t = constraint_violation(xt, calc_h)
                if np.isfinite(phi_t) and phi_t + rho * theta_t <= merit_k + eta * alpha * D_merit:
                    break
                rejected.append((theta_t, phi_t))
                alpha *= xi
                if alpha < alpha_min:
                    status = "line search failed"
                    break

        elif globalization == "filter":
            while True:
                xt = x + alpha * dx
                phi_t = barrier_objective(xt, calc_f, bounds, mu)
                theta_t = constraint_violation(xt, calc_h)
                accept = augment = False
                if np.isfinite(phi_t) and not filter_dominated(theta_t, phi_t, filter_set):
                    m_k = alpha * grad_phi @ dx
                    switch = m_k < 0 and (-m_k) ** s_phi * alpha ** (1 - s_phi) > delta_switch * theta_k**s_theta
                    if switch:
                        accept = phi_t <= phi_k + eta * m_k
                    else:
                        accept = theta_t <= (1 - gamma_theta) * theta_k or phi_t <= phi_k - gamma_phi * theta_k
                        augment = accept
                if accept:
                    if augment:
                        filter_set.append((theta_k, phi_k))
                    break
                rejected.append((theta_t, phi_t))
                alpha *= xi
                if alpha < alpha_min:
                    # A complete method would enter feasibility restoration here.
                    status = "restoration required"
                    break

        if status != "converged":
            break

        log.append({"mu": mu, "k": k, "alpha": alpha, "alpha_u": alpha_u, "theta": theta_k,
                    "phi": phi_k, "rho": rho, "E": E, "rejected": rejected,
                    "trials": len(rejected) + 1})
        if verbose:
            print(f"  k={k:3d}  f={f_k: .6e}  ||h||={linalg.norm(h_k):.2e}  E={E:.2e}  "
                  f"alpha={alpha:.3e}  alpha_u={alpha_u:.3e}")
        x, v, u = x + alpha * dx, v + alpha * dv, u + alpha_u * du
        k += 1
    else:
        status = "max iterations"

    if info is not None:
        info.update(status=status, iterations=log, filter=filter_set, rho=rho)
    return x, v, u, E


def interior_point(x0, calc_f, calc_h, bounds, max_iter=20, globalization="boundary",
                   info=None, verbose=False):
    """A sequence of barrier subproblems with the monotone mu update from Lecture 24.

    Outputs: lists x, v, u (x[0] is the start; x[l+1] is the result for mu[l]), mu, E
    """
    eps_tol, mu0, kappa_eps, kappa_mu, theta_mu = 1e-8, 10.0, 10.0, 0.2, 1.5
    m, r = len(calc_h(np.asarray(x0, dtype=float))), len(bounds)
    x, v, u, mu, E = [np.asarray(x0, dtype=float)], [np.ones(m)], [np.ones(r)], [mu0], []
    all_its, rho, status, l = [], 0.0, "converged", 0
    while True:
        if verbose:
            print(f"Barrier subproblem {l}: mu = {mu[l]:.3e}")
        sub = {}
        x_, v_, u_, E_ = barrier_subproblem(x[l], v[l], u[l], calc_f, calc_h, bounds, mu[l],
                                            kappa_eps * mu[l], globalization=globalization,
                                            info=sub, verbose=verbose)
        status = sub["status"]
        all_its += sub["iterations"]
        rho = max(rho, sub["rho"])
        x.append(x_)
        v.append(v_)
        u.append(u_)
        E.append(E_)
        l += 1
        if status != "converged" or l >= max_iter:
            break
        # Original-problem stopping test: barrier residual with mu = 0
        if mu[-1] <= eps_tol / 10 + 1e-16 and E_ <= eps_tol:
            break
        mu.append(max(eps_tol / 10, min(kappa_mu * mu[l - 1], mu[l - 1] ** theta_mu)))
    if status == "converged" and l >= max_iter:
        status = "max iterations"
    if info is not None:
        info.update(status=status, iterations=all_its, rho=rho,
                    newton_iterations=len(all_its),
                    trial_points=sum(e["trials"] for e in all_its), barrier_subproblems=l)
    return x, v, u, mu, E


def compare_globalization(x0, calc_f, calc_h, bounds, strategies=("none", "boundary", "merit", "filter"),
                          max_iter=20, reference=None):
    """Solve one problem with each globalization strategy and tabulate the outcome."""
    results = {}
    print(f"{'strategy':10s} {'status':22s} {'Newton':>6s} {'trials':>6s} {'f(x)':>13s} {'||h||_1':>10s} {'||x-x*||':>10s}")
    print("-" * 84)
    for g in strategies:
        info = {}
        with contextlib.redirect_stdout(io.StringIO()), warnings.catch_warnings():
            warnings.simplefilter("ignore")
            out = interior_point(np.array(x0, dtype=float), calc_f, calc_h, bounds,
                                 max_iter=max_iter, globalization=g, info=info)
        results[g] = out + (info,)
        xf = np.asarray(out[0][-1], dtype=float)
        if np.all(np.isfinite(xf)):
            fs = f"{calc_f(xf): .6e}"
            cs = f"{constraint_violation(xf, calc_h):.2e}"
            ds = f"{linalg.norm(xf - reference, np.inf):.2e}" if reference is not None else "---"
        else:
            fs = cs = ds = "---"
        print(f"{g:10s} {info['status']:22s} {info['newton_iterations']:6d} {info['trial_points']:6d} {fs:>13s} {cs:>10s} {ds:>10s}")
    return results
### Problem 1 functions (provided)

f1 = lambda x: x[0] ** 2 + 3 * x[1]
h1 = lambda x: np.array([x[0] + x[1] - 1])
bounds1 = [1]  # only x2 has a lower bound of zero

3a. Does the method follow the central path?

Solve Problem 1 from x0=(0.5,0.5)\mathbf{x}^0 = (0.5, 0.5) with globalization="boundary". For each barrier subproblem, compare the returned x2x_2 and uu with your analytic x2(μ)x_2(\mu) and u(μ)u(\mu) from Problem 1.

  1. Does the method follow the central path? Why are the iterates not exactly on it?

  2. How many barrier subproblems and Newton iterations were needed, and what are the final x\mathbf{x}, vv and uu?

info1 = {}
x, v, u, mu, E = interior_point(np.array([0.5, 0.5]), f1, h1, bounds1, globalization="boundary", info=info1)
print("status:", info1["status"], " barrier subproblems:", info1["barrier_subproblems"],
      " Newton iterations:", info1["newton_iterations"])
print("final x =", x[-1], " v =", v[-1], " u =", u[-1])
# Add your solution here

Answer:

Barrier subproblemsNewton iterationsFinal x\mathbf{x}Final vvFinal uu

3b. When the full Newton step fails

Consider

min⁡x  1+x12+12x1+x2s.t.x2−x3−1=0,x2≥0,  x3≥0,\min_{\mathbf{x}} \; \sqrt{1 + x_1^2} + \tfrac{1}{2} x_1 + x_2 \quad \mathrm{s.t.} \quad x_2 - x_3 - 1 = 0, \quad x_2 \ge 0, \; x_3 \ge 0,

from x0=(2,2,1)\mathbf{x}^0 = (2, 2, 1). With x2=x3+1x_2 = x_3 + 1 the objective is minimized at x3=0x_3 = 0, and stationarity in x1x_1 gives x1/1+x12=−12x_1 / \sqrt{1 + x_1^2} = -\tfrac{1}{2}, so

x∗=(−13,  1,  0),f(x∗)=32+1≈1.8660.\mathbf{x}^* = \left(-\tfrac{1}{\sqrt{3}}, \; 1, \; 0\right), \qquad f(\mathbf{x}^*) = \tfrac{\sqrt{3}}{2} + 1 \approx 1.8660 .

In x1x_1 this is the classic Newton counterexample: for g(t)=1+t2g(t) = \sqrt{1 + t^2} the Newton step −g′/g′′=−t(1+t2)-g'/g'' = -t(1 + t^2) overshoots whenever ∣t∣>1|t| > 1.

Run the comparison, then answer:

  1. Which strategies fail and which converge? Explain each failure using the structure of the problem. In particular, why can the fraction-to-the-boundary rule not prevent the failure?

  2. What does this tell you about the division of labor between the fraction-to-the-boundary rule and a merit function or filter?

  3. Compare the Newton iterations and trial points used by the merit function and the filter.

f4 = lambda x: np.sqrt(1 + x[0] ** 2) + 0.5 * x[0] + x[1]
h4 = lambda x: np.array([x[1] - x[2] - 1])
bounds4 = [1, 2]
x0_4 = np.array([2.0, 2.0, 1.0])
x_star_4 = np.array([-1 / np.sqrt(3), 1.0, 0.0])

results4 = compare_globalization(x0_4, f4, h4, bounds4, reference=x_star_4)

Answer:

StrategyStatusNewton iterationsTrial pointsWhy it fails or converges
none
boundary
merit
filter

3c. Cross-check with Ipopt

Ipopt is a production interior point method with a filter line search (Lecture 24). The cell below solves Problems 1 and 3b with it. Compare its solutions and multipliers with yours, remembering Pyomo’s sign convention from Algorithms 4.

def build_p1():
    m = pyo.ConcreteModel()
    m.x1 = pyo.Var(initialize=0.5)
    m.x2 = pyo.Var(initialize=0.5, bounds=(0, None))
    m.obj = pyo.Objective(expr=m.x1**2 + 3 * m.x2)
    m.h = pyo.Constraint(expr=m.x1 + m.x2 - 1 == 0)
    return m


def build_p4():
    m = pyo.ConcreteModel()
    m.x1 = pyo.Var(initialize=2.0)
    m.x2 = pyo.Var(initialize=2.0, bounds=(0, None))
    m.x3 = pyo.Var(initialize=1.0, bounds=(0, None))
    m.obj = pyo.Objective(expr=pyo.sqrt(1 + m.x1**2) + 0.5 * m.x1 + m.x2)
    m.h = pyo.Constraint(expr=m.x2 - m.x3 - 1 == 0)
    return m


for name, build in [("Problem 1", build_p1), ("Problem 3b", build_p4)]:
    m = build()
    m.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
    m.ipopt_zL_out = pyo.Suffix(direction=pyo.Suffix.IMPORT)
    res = pyo.SolverFactory("ipopt").solve(m)
    xs = [round(pyo.value(var), 7) for var in m.component_data_objects(pyo.Var)]
    print(f"{name}: {res.solver.termination_condition},  x = {xs},  f = {pyo.value(m.obj):.7f}")
    print(f"   Pyomo dual on h: {m.dual[m.h]:.7f}")
    print("   bound multipliers (zL):", {v.name: round(m.ipopt_zL_out.get(v, 0.0), 7)
                                         for v in m.component_data_objects(pyo.Var) if v.lb is not None})

Answer:

x\mathbf{x}vv (Lecture 24 convention)Bound multipliers u\mathbf{u}
Problem 1
Problem 3b

AI disclosure

Approximately how long was your independent attempt?

How far did you get? where did you get stuck?

What AI or collaborative help did you use afterward, and how did you verify it?

If you used no AI, answer “not applicable”.

Problem 4 (optional): Merit function versus filter, and a limit of globalization

This problem explores globalization in more depth, for students who are interested in it.

4a. Where the merit function and the filter disagree

min⁡x  2x1+x2s.t.x12+x22−1=0,x2≥0,\min_{\mathbf{x}} \; 2x_1 + x_2 \quad \mathrm{s.t.} \quad x_1^2 + x_2^2 - 1 = 0, \quad x_2 \ge 0,

from the infeasible start x0=(0.9,0.9)\mathbf{x}^0 = (0.9, 0.9). The solution is x∗=(−1,0)\mathbf{x}^* = (-1, 0) with f∗=−2f^* = -2. Run the comparison and print the step lengths. Find the iteration where the two strategies accept different step lengths, and explain how each one judges the trade between the infeasibility ∥h∥1\|\mathbf{h}\|_1 and the barrier objective φμ\varphi_\mu there. Which acceptance region is larger, and is larger always better?

f5 = lambda x: 2 * x[0] + x[1]
h5 = lambda x: np.array([x[0] ** 2 + x[1] ** 2 - 1])
results5 = compare_globalization(np.array([0.9, 0.9]), f5, h5, [1],
                                 strategies=("none", "merit", "filter"), reference=np.array([-1.0, 0.0]))
print()
for g in ("none", "merit", "filter"):
    print(f"{g:7s} alphas:", [round(float(e["alpha"]), 4) for e in results5[g][-1]["iterations"]])

Answer:

Step length accepted at the iteration where they differReason
merit function
filter

4b. Where every strategy fails

The Wächter--Biegler example (Example 6.8, Eq. 6.63, pp. 155--156 in Biegler, 2010):

min⁡x  x1s.t.x12−x2−1=0,x1−x3−12=0,x2,x3≥0,\min_{\mathbf{x}} \; x_1 \quad \mathrm{s.t.} \quad x_1^2 - x_2 - 1 = 0, \quad x_1 - x_3 - \tfrac{1}{2} = 0, \quad x_2, x_3 \ge 0,

from x0=(−2,3,1)\mathbf{x}^0 = (-2, 3, 1), with solution x∗=(1,0,12)\mathbf{x}^* = (1, 0, \tfrac{1}{2}). Feasibility needs x1≥1x_1 \ge 1, but from x1<0x_1 < 0 an interior line search method cannot cross x1=0x_1 = 0 without making x2x_2 or x3x_3 negative. Run the comparison. Describe each failure mode, then explain what a feasibility restoration phase (not implemented here) is for.

f6 = lambda x: x[0]
h6 = lambda x: np.array([x[0] ** 2 - x[1] - 1, x[0] - x[2] - 0.5])
results6 = compare_globalization(np.array([-2.0, 3.0, 1.0]), f6, h6, [1, 2],
                                 strategies=("none", "merit", "filter"), reference=np.array([1.0, 0.0, 0.5]))

Answer:

StrategyStatusFinal x\mathbf{x}∥h∥1\lVert\mathbf{h}\rVert_1
none
merit
filter