"""Weighted least squares with linear constraints.

    minimize    sum w (A x - b)^2
    subject to  E x = e,  G x >= h

SciPy finds the solution; the constraints that hold with equality
there are then solved exactly as equations with NumPy (an active-set
check of the optimality conditions), so the result does not depend on
the solver's tolerance."""

import numpy as np
from scipy.optimize import minimize

TOLERANCE = 1e-7


def least_squares(A, b, w, E=None, e=None, G=None, h=None):
    A = np.asarray(A, float)
    n = A.shape[1]
    E = np.zeros((0, n)) if E is None else np.asarray(E, float)
    e = np.zeros(0) if e is None else np.asarray(e, float)
    G = np.zeros((0, n)) if G is None else np.asarray(G, float)
    h = np.zeros(0) if h is None else np.asarray(h, float)
    H = A.T @ (w[:, None] * A)
    g = -A.T @ (w * b)
    x = _scipy(H, g, E, e, G, h)
    active = [i for i in range(len(h)) if G[i] @ x - h[i] < 1e-6]
    for _ in range(10 * (len(h) + 1)):
        x, multipliers = _equality(H, g, E, e, G[active], h[active])
        slack = G @ x - h
        inactive = [i for i in range(len(h)) if i not in active]
        worst = min(inactive, key=lambda i: slack[i], default=None)
        if multipliers.size and multipliers.min() < -TOLERANCE:
            del active[int(np.argmin(multipliers))]
        elif worst is not None and slack[worst] < -TOLERANCE:
            active.append(worst)
            active.sort()
        else:
            return x
    raise ArithmeticError("the active-set check did not settle")


def _scipy(H, g, E, e, G, h):
    x0 = np.linalg.lstsq(H, -g, rcond=None)[0]
    constraints = []
    if len(e):
        constraints.append({"type": "eq", "fun": lambda x: E @ x - e,
                            "jac": lambda x: E})
    if len(h):
        constraints.append({"type": "ineq", "fun": lambda x: G @ x - h,
                            "jac": lambda x: G})
    result = minimize(
        lambda x: 0.5 * x @ H @ x + g @ x, x0, jac=lambda x: H @ x + g,
        method="SLSQP", constraints=constraints,
        options={"maxiter": 2000, "ftol": 1e-12})
    return result.x


def _equality(H, g, E, e, Ga, ha):
    """Solve with E x = e and Ga x = ha; return x and the multipliers of
    the rows of Ga (non-negative at the optimum of G x >= h)."""
    C = np.vstack([E, Ga])
    d = np.concatenate([e, ha])
    n, m = H.shape[0], C.shape[0]
    K = np.block([[H, C.T], [C, np.zeros((m, m))]])
    solution = np.linalg.lstsq(K, np.concatenate([-g, d]), rcond=None)[0]
    # K [x; mu] = [-g; d] gives H x + g = -C^T mu: the multipliers are -mu.
    return solution[:n], -solution[n + len(e):]
