Metadata-Version: 2.4
Name: horatio-solver
Version: 0.6.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Rust
Classifier: Topic :: Scientific/Engineering :: Mathematics
Requires-Dist: numpy
Requires-Dist: scipy
Requires-Dist: cvxpy>=1.4 ; extra == 'cvxpy'
Provides-Extra: cvxpy
License-File: LICENSE
License-File: NOTICE
License-File: THIRD_PARTY_NOTICES.md
License-File: LICENSES/Apache-2.0.txt
License-File: LICENSES/BSD-3-Clause.txt
License-File: LICENSES/MIT.txt
Summary: Horatio: a convex, linear and mixed-integer conic optimization solver, with a cvxpy interface
Keywords: optimization,solver,conic,mixed-integer,convex,nonlinear,cvxpy,linear-programming,semidefinite
Author: Ian Davis
License-Expression: (PolyForm-Noncommercial-1.0.0 OR LicenseRef-PolyForm-Free-Trial-1.0.0) AND Apache-2.0 AND BSD-3-Clause AND MIT
Requires-Python: >=3.9
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM

# Horatio

Horatio is an optimization solver for **linear, convex conic, mixed-integer and DNLP** problems, inspired by the
requirements of Portfolio Optimization, written in Rust. Its Python package has a [cvxpy](https://www.cvxpy.org)
interface, SciPy-style `linprog` and `milp`, and `horatio.read` for MPS, CPLEX LP and CBF files (with `horatio.write`
for MPS and CBF).

It solves

```
minimize    ½ xᵀPx + qᵀx
subject to  Ax + s = b,  s ∈ K
            l ≤ x ≤ u,   x_j integer for j ∈ I
```

where K is a product of zero, nonnegative, second-order, exponential, power and positive semidefinite cones. That
covers LPs, QPs, SOCPs, exponential- and power-cone programs and SDPs, each with or without integer variables.
Through cvxpy's disciplined nonlinear programming (DNLP, cvxpy 1.9), Horatio also solves smooth nonlinear problems, convex
or not, to a local optimum.

| Problem | Method |
|---|---|
| LP | Bounded dual simplex: sparse LU with updates, dual steepest edge, bound flipping, warm starts. An interior point for LPs with many free columns in long equality rows. |
| QP, SOCP, exponential, power and PSD cones | Primal-dual interior point on the homogeneous embedding, with its own sparse LDLᵀ and minimum-degree ordering, and faer's supernodal LDLᵀ for the heaviest factorisations. Sparse LMIs use chordal decomposition. N-dimensional power cones are taken whole. |
| Mixed-integer (MILP, MIQP, MISOCP, mixed-integer exponential, power and PSD cones) | LP-based branch-and-cut with outer approximation: presolve (large models lose the columns their bounds pin or dominance fixes), probing, perspective strengthening, Gomory and c-MIR cuts, heuristics, repeatable parallel tree search. Each node can also be solved exactly by the interior point. |
| Smooth nonlinear (cvxpy's `nlp=True`) | Primal-dual interior point with a filter line search and a feasibility restoration phase, after Wächter and Biegler, on exact Hessians. A nonconvex problem gets a local optimum. |

## Built for portfolio optimisation

Horatio is tuned for the problems that portfolio construction and rebalancing produce, and its defaults are chosen
on them. A rebalance is rarely a single solve. It mixes continuous convex solves (mean-variance and tracking-error QPs
and SOCPs over a factor or full covariance model, CVaR LPs over scenarios) with mixed-integer ones (a limit on the
number of holdings, minimum position sizes, round lots), and it is repeated across many accounts. Horatio is built
for that mix:

- **Factor-model risk.** The dense rows of a factor model (the exposures and the budget row) are ordered last and
  factored as one dense block, so a QP or SOCP over thousands of assets and a few dozen factors stays cheap to factor.
- **Holdings limits and minimum positions.** A variance over positions tied to binaries (w ≤ u·z) is strengthened
  into perspective form, which Horatio finds by itself. Rank heuristics find a first answer where a holdings limit
  spreads the relaxation thinly over many assets.
- **Large universes.** Where bounds and constraints rule most of a large universe out of the answer, presolve takes
  those columns out before branch-and-bound.
- **Round lots.** Convex costs on whole-lot positions get secant cuts between neighbouring lots.
- **Trades.** A trade variable d = w − w₀ that is used nowhere else is taken out of the interior point's system and
  put back afterwards.
- **Many similar solves.** A parametrized cvxpy problem reuses the solver built for its first solve, and
  `horatio.Solver` re-solves new data from its last basis or factorisation.

On other problem classes Horatio is a general solver, measured on public benchmarks, but its defaults are not tuned
for them.

## Installing

You need Python 3.9 or later, and cvxpy 1.4 or later to use Horatio from cvxpy (1.9 or later for nonlinear
problems; 1.9.4 or later recommended for large ones, as earlier 1.9 releases evaluate some Hessians far more slowly).
In a virtual environment:

```bash
python -m venv .venv
source .venv/bin/activate                # on Windows: .venv\Scripts\activate
pip install "horatio-solver[cvxpy]"      # Horatio with cvxpy; numpy and scipy come with it
python -c "import horatio, cvxpy; print(horatio.__version__, cvxpy.__version__)"
```

`pip install horatio-solver` installs Horatio alone, for an environment that already has cvxpy or for use without it.
With uv, use `uv add "horatio-solver[cvxpy]"`. Horatio is not on conda-forge: inside a conda environment, install it
with pip.

There are abi3 wheels, for every Python from 3.9, for Linux x86-64 and ARM (glibc, and musl for Alpine-based systems),
macOS Apple Silicon and Intel, and Windows x86-64. The extension needs no external solver library and no licence key.
Horatio is published as these wheels only: on any other platform, or a Python older than 3.9, pip finds nothing to
install.

Three names are involved: `horatio-solver` is what you install, `horatio` is what you import, and `"HORATIO"` is the
solver's name in cvxpy.

## Getting started with cvxpy

**A first solve.** Pass a Horatio instance as the solver:

```python
import cvxpy as cp
from horatio import Horatio

x = cp.Variable(2)
prob = cp.Problem(cp.Maximize(x[0] + 2 * x[1]),
                  [x >= 0, x[0] + x[1] <= 4, x[0] + 3 * x[1] <= 6])
prob.solve(solver=Horatio())
print(prob.status, prob.value, x.value)      # optimal 5.0 [3. 1.]
```

cvxpy hands Horatio its conic form directly, including native variable bounds, integer indices and duals. Horatio
takes every cone cvxpy can send to a solver, and the shapes cvxpy rewrites into them, with or without integers.

**By name.** Tools that take solver names as strings need Horatio registered, once per Python process:

```python
import horatio
horatio.register()
print("HORATIO" in cp.installed_solvers())   # True
prob.solve(solver="HORATIO")
```

Always say which solver you want. Without `solver=`, cvxpy uses its own default solvers. It falls back to a
registered Horatio only for problems none of those can take, such as a mixed-integer QP or SOCP, and then warns that
it did.

**Mixed-integer problems.** Declare integer or boolean variables as usual:

```python
import numpy as np

y = cp.Variable(5, integer=True)
target = np.array([0.4, 1.6, 2.5, -0.7, 3.2])
prob = cp.Problem(cp.Minimize(cp.sum_squares(y - target)), [cp.sum(y) <= 5, y >= -1])
prob.solve(solver=Horatio(), time_limit=10)
print(prob.status, round(prob.value, 6), y.value.round().astype(int))   # optimal 0.9 [ 0  1  2 -1  3]
stats = prob.solver_stats.extra_stats                                    # nodes, bound, gap, cut counts, …
```

- **The gap.** A mixed-integer solve stops when its answer is proved within a relative gap of 1e-4 of the best
  possible. Set `rel_gap` smaller to prove more.
- **Limits.** With `time_limit` or `node_limit` reached, the status is `user_limit` and the variables hold the best
  answer found, not a proven optimum.
- **Duals.** Mixed-integer problems return no duals; continuous ones return them as cvxpy expects.

**Settings** go to `prob.solve` as keyword arguments, such as `time_limit=30, rel_gap=1e-5, verbose=True`. *Main
settings* below lists them.

**Re-solving.**
- **Parameters.** A problem written with `cp.Parameter`s under cvxpy's DPP rules is compiled once. Each re-solve with
  new parameter values reuses the solver Horatio built for the first solve.
- **Warm starts.** `prob.solve(solver=Horatio(), warm_start=True)` seeds a mixed-integer search with the variables'
  current values.

**Nonlinear problems (cvxpy 1.9 or later).** cvxpy's disciplined nonlinear programming (DNLP) solves smooth problems,
convex or not. After `horatio.register()`, Horatio is one of its solvers:

```python
import numpy as np
import cvxpy as cp
import horatio

horatio.register()
y = cp.Variable(2, value=np.array([-1.2, 1.0]))      # the start
prob = cp.Problem(cp.Minimize((1 - y[0]) ** 2 + 100 * (y[1] - y[0] ** 2) ** 2))
prob.solve(nlp=True, solver="HORATIO")
print(prob.status, y.value)                          # optimal [1. 1.]
```

The answer is a local optimum, and another start can find another. Nonlinear solves have their own settings: `tol`,
`max_iter`, `time_limit`, `acceptable_tol`, `mu_init` and `verbose`.

**Many solves in parallel.**
- **Threads.** Keep `threads=1` and set `HORATIO_NUM_THREADS=1`, or the cores divided by the workers, so workers do
  not compete for cores.
- **Registration in each worker.** `horatio.register()` affects only the process that calls it. Workers started with
  `spawn`, the default on macOS and Windows, must register for themselves:

```python
import multiprocessing as mp

with mp.get_context("spawn").Pool(4, initializer=horatio.register) as pool:
    results = pool.map(solve_one, cases)
```

Passing `solver=Horatio()` instead of the name needs no registration.

**Statuses.**

| Horatio's result | cvxpy status |
|---|---|
| optimal | `OPTIMAL` |
| infeasible | `INFEASIBLE` |
| unbounded | `UNBOUNDED` |
| time, node or iteration limit, with an answer | `USER_LIMIT` (the best answer found, not proven optimal) |
| time, node or iteration limit, no answer found | `INFEASIBLE_INACCURATE` |
| interior point stopped short of its tolerances, answer meets the reduced ones | `OPTIMAL_INACCURATE`, `INFEASIBLE_INACCURATE` or `UNBOUNDED_INACCURATE` |
| numerical failure, with an answer in hand | `OPTIMAL_INACCURATE` |
| numerical failure, no answer | `SOLVER_ERROR` |

**Troubleshooting.**

| What you see | What to do |
|---|---|
| `The solver HORATIO is not installed.` | Call `horatio.register()` in this process, or pass `solver=Horatio()`. In worker processes, register in each worker. |
| `Solver HORATIO is not supported for NLP problems.` | Call `horatio.register()` in this process first. Nonlinear problems also need cvxpy 1.9 or later. |
| `ModuleNotFoundError: No module named 'cvxpy'` | Install the extra: `pip install "horatio-solver[cvxpy]"`. |
| `No matching distribution found for horatio-solver` | No wheel matches your platform or Python: Horatio is published as wheels only, for the platforms listed above. To ask for another platform, write to i.e.davis@outlook.com. |
| `horatio.UnknownSettingError` | A setting's name is misspelt or not Horatio's; the message names it. |
| Status `user_limit` | A time or node limit was reached: the answer is the best found, not proven optimal. Raise `time_limit`. |

## Directly from Python

```python
import horatio

r = horatio.solve_conic(P, q, A, b, cones=[("z", 1), ("l", 20), ("q", 5)], integers=[3, 4])
r["status"], r["objective"], r["x"]

s = horatio.Solver(P, q, A, b, cones)      # persistent: re-solve with new numbers
r = s.solve()
s.update(q=q_new)                          # warm start from the last basis or factorization
r = s.solve()
```

The cone list gives each cone's type and size, in row order: `("z", d)` zero, `("l", d)` nonnegative, `("q", d)`
second-order, `("ep", 1)` exponential, `("p", α)` power, `("pnd", (α_1, …, α_d))` n-dimensional power (d + 1 rows,
Σ α_i = 1) and `("s", n)` positive semidefinite (the upper triangle, column by column, √2 off the diagonal). This is
the conic form cvxpy uses; only the upper triangle of P is read.

SciPy users can call `horatio.linprog` and `horatio.milp` in place of `scipy.optimize.linprog` and
`scipy.optimize.milp`: the same arguments, checks and results.

## Reading problem files (`horatio.read`)

Horatio reads the formats most solvers exchange and the standard test sets are published in: MPS (with or without a
quadratic objective), CPLEX LP and CBF (the Conic Benchmark Format). No other solver or modelling package is needed.

```python
import horatio

prob = horatio.read("model.mps.gz")        # .mps or .qps, .lp, .cbf, each optionally .gz
print(prob)                                # FileProblem('model', mps, minimize, 120 variables (40 integer), ...)
res = prob.solve(time_limit=60, rel_gap=1e-4)
print(res["status"], res["objective"], res["bound"])
values = {name: float(v) for name, v in zip(prob.var_names, res["x"])}
```

The format comes from the extension; `format="mps"`, `"lp"` or `"cbf"` names it where the extension doesn't. `solve`
takes any of Horatio's settings and reports `objective` and `bound` in the file's own sense, so a file that maximises
gets its maximum back. `x` has one value per variable, in the order of `prob.var_names`. The problem's data (`P`,
`q`, `A`, `b`, `cones`, bounds, integer variables) is on the object, in `solve_conic`'s form, to inspect or change
before solving.

| format | read | refused |
|---|---|---|
| MPS (free or fixed) | rows, columns, integer markers, RHS, ranges, every bound type including semi-continuous (SC, SI), OBJSENSE; a quadratic objective in QUADOBJ, QSECTION or QMATRIX; SOS sets; convex quadratic constraints (QCMATRIX) | non-convex quadratic constraints, indicators |
| CPLEX LP | objective (with a constant and `[ … ] / 2` quadratic terms), constraints and ranges, bounds, General, Binary, Semi-continuous, SOS, convex quadratic constraints | non-convex quadratic constraints, indicators |
| CBF | free, linear, second-order, rotated second-order and exponential cones and their duals, the 3-dimensional power cone and its dual, integer variables | semidefinite parts |

A refused feature raises `ValueError`, naming the line and the feature; nothing is approximated. A semi-continuous
variable (x = 0 or l ≤ x ≤ u) is read exactly, as a binary z with l·z ≤ x ≤ u·z added after the file's variables, and
so are SOS1 and SOS2 sets, as binaries limiting which members can be nonzero; `solve` still returns `x` over the
file's own variables. An integer column in
an MPS file's markers with no bounds is binary, as CPLEX documents it. The standard sets read as they are published:
netlib and MIPLIB (`.mps`), the Maros–Mészáros convex QPs (`.qps`), QPLIB (`.lp`, `.mps`) and CBLIB (`.cbf.gz`). The
same readers are in the Rust crate as `horatio_solver::read_file` and `read_problem`.


`horatio.write("model.cbf", P, q, A, b, cones, ...)` saves a problem in `solve_conic`'s form as an MPS or CBF file
(optionally `.gz`), `prob.write(path)` saves a `FileProblem`, and through cvxpy `prob.solve(solver=Horatio(),
save_file="model.cbf")` writes the problem Horatio receives before solving it. MPS holds linear constraints with a
quadratic objective; CBF holds the cones as well.
## Main settings

The same names work as keyword arguments to `prob.solve(solver=Horatio(), ...)`, to `horatio.solve_conic` and to
`horatio.Solver`. An unknown name raises `horatio.UnknownSettingError`, which is both a `KeyError` and a `ValueError`.

| name | default | effect |
|---|---|---|
| `time_limit` | ∞ | seconds |
| `node_limit` | ∞ | branch-and-bound nodes |
| `work_limit` | ∞ | counted work: about a second each on a recent desktop core, and the same count on every run, so a search it stops ends at the same point every time (status `WorkLimit`) |
| `solution_limit` | ∞ | stop once the search has found this many answers (1: the first feasible one) |
| `objective_target` | −∞ | stop once an answer's objective is at most this (in the minimisation form: for a cvxpy `Maximize`, minus the value wanted) |
| `rel_gap`, `abs_gap` | 1e-4, 1e-9 | stop when the incumbent is this close to the bound |
| `threads` | 1 | threads for the mixed-integer search; what runs on them is `deterministic`'s choice |
| `deterministic` | True | with `threads` above 1, parallel work that gives the same answer on every run: the tree shared out between the threads in rounds of counted work, merged in a fixed order; False: the workers share one search tree freely, and the answer can differ from run to run |
| `node_relax` | `"auto"` | `"lp"`: outer approximation with the dual simplex; `"nlp"`: the interior point at every node; `"auto"` picks by structure |
| `verbose` | False | progress log on stderr |
| `ipm_threads` | 0 | threads for a large continuous problem (from about a million rows); 0: the environment variable `HORATIO_NUM_THREADS` where it is set, else one per core. The answer is the same on any number of threads |

**Repeatable answers.** With `deterministic=True`, the default, on one thread or several, a solve gives the same
answer every time it is run on the same kind of processor, however fast or busy the machine is, unless its time limit
stops it: the search's own budgets are counted work, not seconds, and threads exchange what they found only at fixed
points. Different numbers of threads can give different answers from each other (each searches its own part of the
tree), but each repeats. A time limit stops the search wherever it has got to, which depends on the
machine and its load; `work_limit` stops it at the same point every time. A solve's work is in its statistics
(`work`). A warm start, or a `horatio.Solver` that starts from its last answer, is part of what the answer depends on.

## Feedback

Questions, bug reports and suggestions are welcome at i.e.davis@outlook.com. For a wrong answer or a slow solve,
please include the versions (`horatio.__version__`, and cvxpy's if you use it), your platform, and the problem, or a
script that builds it.

## Licence

Horatio is offered under two licences, and you may use it under either of them (`LICENSE`, in every wheel):

- the **PolyForm Noncommercial License 1.0.0**, for any noncommercial purpose: personal study, research, experiment and
  hobby use with no anticipated commercial application, and use by charities, educational institutions, public
  research organisations, public safety or health organisations, environmental protection organisations and
  government bodies. Under it you may also copy, modify and redistribute Horatio, passing its terms on.
- the **PolyForm Free Trial License 1.0.0**, under which anyone, a business included, may evaluate whether Horatio
  suits a particular application for less than 32 consecutive calendar days. It does not allow redistribution.

Any other use, including production use by or for a business, needs a commercial licence from the author:
i.e.davis@outlook.com.

Parts of Horatio are derived from open-source projects (Clarabel.rs, QDLDL, SuiteSparse AMD and HiGHS),
and those parts keep their own licences and notices. The licence texts and notices (`LICENSE`, `NOTICE`,
`THIRD_PARTY_NOTICES.md`, `LICENSES/`) come with every wheel.

Copyright (c) 2026 Ian Davis.

