Metadata-Version: 2.4
Name: fourcolors
Version: 1.0.0
Summary: The Python client for the 4colors API: 4colors Quantum Compiler and 4colors Optimizer for QUBO.
Author: 4colors
License-Expression: LicenseRef-Proprietary
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.10
Provides-Extra: ocean
Requires-Dist: blake3>=0.4; extra == 'ocean'
Requires-Dist: dimod>=0.12; extra == 'ocean'
Requires-Dist: numpy>=1.22; extra == 'ocean'
Requires-Dist: zstandard>=0.22; extra == 'ocean'
Provides-Extra: optimizer
Requires-Dist: blake3>=0.4; extra == 'optimizer'
Requires-Dist: numpy>=1.22; extra == 'optimizer'
Requires-Dist: zstandard>=0.22; extra == 'optimizer'
Provides-Extra: qiskit
Requires-Dist: qiskit-qasm3-import>=0.5; extra == 'qiskit'
Requires-Dist: qiskit>=2.2; extra == 'qiskit'
Description-Content-Type: text/markdown

# fourcolors

The Python client for the 4colors API: the 4colors Optimizer for QUBO and the 4colors Quantum
Compiler.

```python
import fourcolors

client = fourcolors.Client()          # the key from FOURCOLORS_API_KEY
job = client.solve("optimizer.qubo", input={...}, options={"time_limit_s": 60})
print(job.status, job.result)
```

The key comes from `FOURCOLORS_API_KEY` (or `api_key=`). The API is
`https://api.4colors-research.com/v1` unless `FOURCOLORS_BASE_URL` (or `base_url=`) says otherwise.

`submit` queues a job and returns at once; `wait` polls it until it ends (`done` or `failed`);
`solve` does both; `stop` asks a running job to stop and keep its answer so far.
Each returns a `fourcolors.JobInfo`, the job as the API last showed it. Its attributes are the job
record's, named as in the HTTP guide: `id`, `status`, `stopped`, `solver`, `result`, `error`,
`submitted_at`, `started_at`, `finished_at`, `revision`, `queue_position`, `estimated_start_at`,
`ends_by`, `time_limit_s`, `wait_s`, `run_s`, `billed_s` and `incumbent`. A failed job's `error` reads
as its message and carries its code, `info.error.code`. A `JobInfo` also reads as the job's JSON
(`info["queue_position"]`, `info.get("billed_s")`, `"result" in info`). The running job that
`fourcolors.qubo.submit` and `fourcolors.quantum.compiler.submit` return is a `fourcolors.Job`, with the
same attributes (read from the API as the job runs) and its methods.
Errors are typed (`fourcolors.errors`), each with the API's `code`; `Unavailable` (HTTP 503) and
`RateLimited` (429) carry `retry_after` in seconds when the API gives one.
Once a job has ended, `job.billed_s` and `res.billed_s` on its result are the seconds it is billed
for, as the platform metered it: execution time only, never queueing or the check. The API sends
the final value from the first read that shows the job ended. None while the job waits or runs.

## QUBO and Ising models

```python
import fourcolors

result = fourcolors.solve(Q, time_limit_s=10)   # the same as fourcolors.qubo.solve
print(result.objective, result.solution)         # the best found objective, and the values
```

`Q` is a square numpy array or scipy.sparse matrix (E = offset + x^T Q x), a dict `{(i, j): v}`
(with `linear=`), a dimod BQM, a model read from a 4CQB file with `fourcolors.read_file(path)`,
or the path of a 4CQB file. `sense="max"` maximises;
`vartype="SPIN"` reads a matrix or dict as an Ising model. The model goes to `POST /v1/jobs` as
solver `optimizer.qubo`; the answer is the best solution found within `time_limit_s` seconds, and
`result.objective` is its objective, offset included. `result.trajectory` lists each
improvement the search made (`seq`, `t_search_s`, `objective`, `objective_exact`).

Reading a model from a file: `read_file` reads a 4CQB file (raw, zstd or gzip, recognised by its
bytes). Text model formats are not supported in fourcolors 1.0.0: convert the file to 4CQB.

```python
m = fourcolors.read_file("model.4cqb")
result = fourcolors.solve(m, time_limit_s=10)
```

A file that cannot be read raises `fourcolors.errors.FormatError`, a `FourColorsError` like every
other error of this package.

### Watching a long solve

```python
job = fourcolors.qubo.submit(Q, time_limit_s=600)  # a fourcolors.Job, returned at once
job.status, job.estimated_start_at, job.ends_by  # queued / running; epoch seconds
job.best()                                       # the best so far, or None
for best in job.incumbents():                    # each new best as it is found
    print(best.objective)
result = job.result()                            # wait for the end
result = job.stop()                              # or stop now and keep the best so far

fourcolors.qubo.solve(Q, time_limit_s=600, on_incumbent=lambda r: print(r.objective))
```

Ctrl-C while `solve`, `job.result()` or a `for best in job.incumbents()` loop waits stops the job
on the server and returns the best found so far (`result.status == "stopped"`; the loop yields it
last and ends, also when its solution is the one yielded just before, and also after `job.stop()`
or a stop from elsewhere). A job stopped before it found any solution returns a stopped result with
no solution. The client waits up to 30 seconds for the stop to take; if the job is still stopping
then, it says so, names the job and returns the best so far (the job finishes stopping on the
server). A second Ctrl-C leaves at once.

A job's status is the HTTP API's: `queued`, `running`, `done` or `failed`; "stopped" is never a job
status. A stopped job is done; its result's status is stopped and it holds the best answer found so
far. Ask the result (`result.stopped`, True exactly when `result.status == "stopped"`, and
`result.reason`, kept as the solver reports it) or the job (`job.stopped`, a convenience that is
True exactly when its result is stopped). The result's status and reason are per solver:

| Case | Job status | `quantum.compiler` | `optimizer.qubo` |
|---|---|---|---|
| Stopped while running (`stop()`, Ctrl-C) | `done` | `stopped`; the best circuit so far | `stopped`; the best solution so far (None before the first) |
| Used its whole time | `done` | `stopped`, `reason.code` `time_limit`; the best circuit | `finished`, `reason` None; the best solution (not stopped) |
| Stopped while queued | `done` | `stopped`, `reason.code` `stopped_before_start`; no circuit, nothing billed | `stopped`, `reason.code` `stopped_before_start`; no solution, nothing billed |

A job stopped while waiting to resume has `reason.code` `stopped_while_waiting`: the time it ran
before is billed, nothing after. A QUBO run may also end `finished` with `reason.code`
`no_feasible_found` or `deadline_overrun` (an answer kept past its deadline): not a stop, so
`result.stopped` is False; read `result.reason`. `job.result()`, `job.wait()` and `job.stop()`
return the result in every case above (a QUBO job stopped before its first answer gives a result
whose `objective` and `solution` are None; it does not raise). A request refused at submit raises
`InvalidRequest` with its code; a job that fails at run time (a refusal included) has job status
`failed` and raises `JobFailed` with its `code`, as the HTTP failed job says it.

While waiting, the client retries an API that cannot be reached, is busy (429) or is briefly down
(503), honouring its Retry-After, for up to five minutes; an error raised from a wait names the
job, which may still be running. Every submit carries a fresh `Idempotency-Key`, and a retry sends
the same key, so the API answers the job it already made rather than making a second one. A submit
is retried, after the API's Retry-After, for up to five minutes, where the API says it did not
accept it: your team's request rate (429 `rate_limited`), the API's own "not starting jobs just now"
(503 `unavailable`), and a first request with the same key still being admitted (409
`idempotency_key_in_progress`). Another 5xx, a timeout or a broken connection, where the job may
have been queued, is retried only when the API honours the key. By default the client asks the API
once, before its first submit (`GET /v1/version` lists `idempotency_key` in its `features` with the
current API), and raises at once when it cannot tell. `Client(idempotent_retries=True | False)`
decides it instead; pass True only for a server that honours the key.
`client.features()` lists what the API supports. When all of your plan's job slots are busy, `RateLimited` (code `quota_exceeded`) is raised
at once: wait for a running job (`job.wait()`), or submit again later. The client never follows a redirect, so your API key is only ever
sent to the address you gave.

### Large models

Build a large model as a `scipy.sparse` matrix or numpy arrays: that is the fastest way in. A dict of
`{(i, j): value}` works too. A plain one (non-negative integer keys; values all integers or all floats) is read in
bulk; any other dict is read one term at a time, which takes much longer at hundreds of thousands of terms or more.
To solve one model several times, upload it once and pass its id, so it is encoded and sent once:

```python
model_id = fourcolors.qubo.upload(Q)          # Q: a scipy.sparse matrix
for seed in (0, 1, 2):
    print(fourcolors.qubo.solve(input_id=model_id, time_limit_s=30, seed=seed).objective)
```

There is no fixed size limit to meet (`model_limits` in the `optimizer.qubo` entry of `client.license()["solvers"]`: a null
size limit means none, and the memory check decides when the job starts, billed nothing if it refuses): models over 8 MiB (as 4CQB) are uploaded once (`PUT /v1/inputs`,
streamed) and the job names them by id; a file path (raw 4CQB, zstd or gzip) is streamed from
disk, not read into memory. `fourcolors.qubo.upload(model_or_path)` uploads a model and returns its
id; `input_id=` (or `model_id=`, the same) submits a model uploaded before.
`pip install "fourcolors[optimizer]"` (or `[ocean]`) installs zstandard and blake3, which make jobs faster to send: a model is
compressed with zstd (inline too), and an upload's id is computed here so a model the API already
holds is not sent again. Without them an upload, and a model inline, goes uncompressed. A zstd or
gzip file of your own is sent as it is: a zstd file must be one zstd frame (as `zstd` writes it),
and a gzip file one gzip stream; a zstd file of several frames is refused before it is sent. A
gzip (`.gz`) file needs an API that takes gzip uploads (the current API does); an older
one refuses it as `input_unreadable` (decompress it, or compress it with zstd, for those). An upload waits up to ten minutes for the API's
answer (`Client(upload_timeout=...)`), as the API checks the whole model first; one the service has
no disk space for just now is refused as `storage_full`.

### Constraints

Linear rows on 0/1 variables, each with a lower bound, an upper bound or both, are added to the model and travel in
it (a 4CQB version 2 file):

```python
m = fourcolors.qubo.to_model(Q)                      # or read_file(...), or a dimod BQM
m.add_constraint({0: 1, 1: 1, 2: 1}, lo=1, hi=1)     # x0 + x1 + x2 = 1
m.add_constraint({0: "2.5", 3: -1}, hi="0.75")       # 2.5 x0 - x3 <= 0.75
result = fourcolors.qubo.solve(m, time_limit_s=10)
result.constraints      # the service's check: {"m": 2, "feasible": True, "rows_checked": 2, "rows_violated": 0}
m.feasible(result.solution)                          # the same check, exactly, here
```

- Keys are variable indices, or the BQM's labels. Coefficients and bounds are exact decimals: an int, a
  `decimal.Decimal`, a str, or a float that is a whole number (`0.1` as a float is refused: write `"0.1"`).
  Feasibility is decided exactly, with no rounding.
- A row the solver cannot hold exactly is refused when it is added (`FormatError`), never rounded: `code`
  `constraint_out_of_range` for a row whose values spread too far for exact arithmetic (contract: per row, scaled to
  its finest exponent, sum |coefficient| + the larger |bound| at most 2^125), as the API would refuse it; `code`
  `format_error` for a value the file cannot hold (an exponent beyond ±400, a mantissa beyond int64).
- `result.constraints` is set on the final result and None on a running job's best so far (the service checks only
  the answer it returns); `model.feasible(solution)` checks any assignment here.
- When no answer meeting every row is found in time, the job still finishes: `result.status` is `finished`,
  `result.reason["code"]` is `no_feasible_found`, and `solution` and `objective` are None.
- `result.objective` is E(solution), the objective alone, whether or not the solution meets the rows.

**Spin (−1/+1) models with rows.** The service takes rows on 0/1 variables only, so the client sends a SPIN model
with rows as its exact 0/1 equivalent: s = 2x − 1, and each row lo ≤ Σ aᵢsᵢ ≤ hi becomes
(lo + A)/2 ≤ Σ aᵢxᵢ ≤ (hi + A)/2 with A = Σ aᵢ, in exact decimals (a one-sided row stays one-sided). The answer,
its energy and every incumbent come back in the spin variables, each checked here against the 0/1 model the service
solved, and `result.converted_from` is `"spin"`. A warm start is given in ±1. When the 0/1 model cannot hold a value
exactly, the client refuses it (`FormatError`) rather than rounding. `fourcolors.qubo.to_binary(m)` is that 0/1
model. `upload(m)` uploads the 0/1 model, so a job by its `input_id` answers in 0/1 values: solve the model itself
to have the answer in spin variables. A spin 4CQB file with rows is refused (`constraints_spin_unsupported`).

### dimod

A dimod sampler: `fourcolors.FourColorsSampler().sample(bqm, time_limit_s=10)`.
`pip install "fourcolors[optimizer]"` for numpy and the upload libraries, `"fourcolors[ocean]"` for dimod too.

`FourColorsSampler().sample(cqm, time_limit_s=10)` takes a dimod `ConstrainedQuadraticModel` whose variables are all
BINARY and whose constraints are all linear and hard; anything else (SPIN, INTEGER or REAL variables, a quadratic or
a soft constraint) is refused with `FormatError` (code `cqm_unsupported`) naming the variable or the constraint.

- CQM constraint coefficients and right-hand sides are read as the shortest decimal that round-trips the float64
  (0.1 is 0.1); the constraint check is exact on those decimals.
- The SampleSet holds the single best sample found. `num_reads` above 1 is refused: the service returns one best
  answer, never several samples.
- The SampleSet's `is_satisfied` and `is_feasible` are dimod's own float checks with a tolerance, which can differ
  from the exact check for a row at its bound (both ways). `sampleset.info["constraints"]` is the service's exact
  check of the answer and is the authoritative verdict.
- A job that finds no answer meeting every row raises `RuntimeError`, its message naming `no_feasible_found`.
- A row that cannot be written exactly is refused naming the constraint (`FormatError`): `constraint_out_of_range`
  past the exact range, `format_error` for a bound needing more than an int64 mantissa (a large left-hand constant
  moved to the right, for example).

## Quantum circuits

The compiler is `fourcolors.quantum.compiler`; `fourcolors.compiler` is the same module, kept as an
alias.

```python
import fourcolors

res = fourcolors.quantum.compiler.compile(qasm, target="heavy_hex_156_cz", time_budget_s=30)
print(res.metrics["two_qubit_gates"], res.mapping["initial_layout"])
print(res.circuit)                 # OpenQASM 3 text
print(res.verification.label)      # pending, verified, approximate, unverified or skipped
res.wait_verification(timeout=120) # pending: wait for the check (or res.refresh() to read once)
qc = res.to_qiskit()               # needs "fourcolors[qiskit]"
```

`qasm` is OpenQASM 2 or 3 text (`str` or UTF-8 `bytes`), or a Qiskit `QuantumCircuit`. `target` is a named target, a
custom target (`{"format_version": 1, "n_qubits", "two_qubit_gate", "couplers"}`), or a Qiskit
`BackendV2` or `Target`. `time_budget_s` (the third argument, 1 to 600) is the seconds to spend
optimising; the answer is the best found in that time. Without `time_limit_s=` the job's time limit
follows from `time_budget_s` (1.1 x it + 15 s), else your plan's default time per job if it sets one,
else the service's default; your plan's time per job caps it. `objective="depth"` minimises depth
first instead of two-qubit gates (`"two_qubit"`, the default). The result's attributes are `status`,
`circuit`, `format`, `metrics`, `mapping`, `verification`, `target` (the target compiled for, its
qubit count `n_qubits`), `seed`, `engine` (`version`), `timings`, `reason`, `stopped`, `billed_s` and
`job`. A compile that found no circuit in its time ends with `reason.code` `no_solution`. The verification label
says what has been checked: `pending` means the check has not finished yet. With the default
`verify="background"` the job ends with its circuit `pending` while the equivalence check runs
after it; the job's record then changes to `verified` (or `unverified` if the check could not
finish), so fetch the job again (`GET /v1/jobs/{id}`, a higher `revision`) or keep its event
stream open for one more `verification` event. From a result, `res.refresh()` reads the job again
and updates `res`, and `res.wait_verification(timeout=...)` waits until the label is decided
(raising `WaitTimeout` if it is still pending then; the check goes on, so you can wait again
later). `verify="wait"` returns only once checked;
`verify="skip"` checks nothing (`skipped`). The check is never charged.
A circuit or target the compiler refuses (too large for the target, more qubits than the device)
raises `fourcolors.errors.JobFailed`: `err.code` is the refusal's code (`input_too_large`,
`does_not_fit_target`, `invalid_input` for the circuit, ...), `err.message` its sentence, `err.field` and
`err.reason` say what was at fault, and `err.job.result` keeps the refused result with its `limit`. A
refusal is never charged. One the service can tell at submit (an unknown target, a bad option) raises
`InvalidRequest` with the same codes; a refused option's code is `invalid_option`, with its `field`.
`fourcolors.quantum.compiler.submit(...)` returns the running job, with the same `result()`, `stop()` and
status fields as above. While it runs, `job.best()` is the best circuit so far and
`for res in job.incumbents():` gets each better one as it is found (status `running`, verification
`pending`), then the final result. The compiler needs no extra; `"fourcolors[qiskit]"` adds Qiskit.

**Approximation.** `compile()` is exact by default: nothing is approximated.
`approximation_mode="per_block"` lets each two-qubit block of the compiled circuit differ from its
input by a small per-block budget, which often saves gates.
`max_approximation_error=<x>` sets one bound for the whole circuit instead. The verification label
says what was checked: `verified`, `approximate` with the measured distance, or `unverified` with
a reason (for example when the circuit is larger than the exact check covers). On the circuit
`to_qiskit()` returns, `metadata["fourcolors"]` has the check's `verification` label and measured
`distance`, and the compile's own `approximation_spent`.
For a Qiskit circuit, `to_qiskit()` also keeps its classical registers (names, sizes and order),
so measurement counts have the same keys as for the circuit you sent. A circuit sent as OpenQASM
text comes back with one classical bit per measured bit (`_bit0`, `_bit1`, ...), in its bit order.

### In Qiskit

With `"fourcolors[qiskit]"`, the compiler is also Qiskit's five compile stages, all named
`fourcolors`. The supported way: give all five of `init_method`, `layout_method`,
`routing_method`, `translation_method` and `optimization_method` the value `"fourcolors"` in
Qiskit's own compile call, with your backend, or use `generate_pass_manager` (below). Without
`init_method="fourcolors"`, Qiskit's own init stage may rewrite your circuit before the compile
sees it, so the answer can differ from compiling the circuit
as you wrote it. At optimization levels 2 and 3 it can take swaps out; `circuit.layout` and the
classical bits still read as your circuit, while `pm.property_set["fourcolors_result"]` describes
the circuit the compile received, without those swaps.
With all five stages, the layout stage compiles on the service and the other stages pass its
answer through unchanged, so the circuit you get is the one the service returned. With only
`layout_method` and `routing_method` set to `"fourcolors"`, Qiskit's own translation and
optimization stages run on the answer afterward and may change its gates and depth, depth for the
worse too. Those stages are Qiskit's own, so the verification label and metrics in the record
describe the service's answer, not the circuit they return. For the service's answer as it is, use
all five stages. Either way the circuit carries its layout (`circuit.layout`), as any circuit Qiskit compiles does. Or build the same stages as a pass manager, with Qiskit's
scheduling stage after them:

```python
pm = fourcolors.quantum.compiler.generate_pass_manager(backend, time_budget_s=30)
qc_out = pm.run(qc)
record = pm.property_set["fourcolors_result"]      # metrics, verification label, job
```

The stages Qiskit builds by name take their options from
`fourcolors.quantum.compiler.set_qiskit_options(time_budget_s=..., client=..., target=...)`.
`set_qiskit_options`, `qiskit_options` and `generate_pass_manager` take exactly `compile()`'s option
keywords (`target`, `time_budget_s`, `objective`, `seed`, `repeatable`, `verify`, `output_format`,
`calibration`, `approximation_mode`, `max_approximation_error`, `time_limit_s`) and `client`, all by
name; any other keyword raises `TypeError`. `generate_pass_manager(backend, *, time_budget_s=None,
**options)` also takes Qiskit's `scheduling_method` and `approximation_degree`.
The job's target is `target=` when given; otherwise the service's named target when your backend
is that device (same qubits, gates and couplers; the backend may list couplers the target does not
use); otherwise a custom target made from your backend. A backend is matched to these
five named targets only: `heavy_hex_156_cz`, `square_120_cz`, `square_108_cz` (one-qubit gates
`rx` and `rz`), `square_20_prx` and `square_54_prx` (two-qubit gate `cz`, one-qubit gate prx,
which Qiskit names `r`).
`pm.property_set["fourcolors_target"]` says which, and why a named target did not match.

A backend without a coupling map makes Qiskit skip the layout stage, so the compile cannot run
there: the later `fourcolors` stages then raise an error rather than return the circuit
uncompiled. Use `fourcolors.quantum.compiler.compile(qc, target=...)` or
`fourcolors.quantum.compiler.generate_pass_manager(backend, target=...)` instead.

Each compiled circuit carries its record in `circuit.metadata["fourcolors"]` (verification label,
job, target), also when Qiskit compiles several circuits at once in worker processes;
`pm.property_set["fourcolors_result"]` holds only the last compile's full result. The label in the
metadata is the one at return, usually `pending`: pass `verify="wait"` to return only once checked.
`set_qiskit_options` applies to the current thread (or async task) until changed; for one block
only, use `with fourcolors.quantum.compiler.qiskit_options(...)`. `generate_pass_manager` takes its own
arguments and ignores both. A user `initial_layout` is not supported yet (the compile chooses the
layout); asking for one raises an error. Needs qiskit 2.2 or later.

**Qiskit's other settings.** `seed_transpiler` is the compile's `seed`, unless you set `seed` in
`set_qiskit_options`. `optimization_level` does not change the compile: the hosted compile does not
have levels, and what buys a better circuit is `time_budget_s`. A list of circuits
runs one compile per process: when they outnumber your plan's job slots, the stages wait for a slot
(up to 15 minutes), and `num_processes=1` compiles them one after another.
**Parameters in Qiskit.** A parametric circuit comes back from the stages and from `to_qiskit()` with your own
`Parameter` objects, so bind it as you bind the input: by position, or by the objects. `res.parameters` lists the names
to bind. For a circuit given as OpenQASM text, `to_qiskit()` makes new parameters and Qiskit sorts them by name
(`p0, p1, p10, ...`), so bind those by name. The circuit text of a parametric Qiskit input (`res.circuit`, and a job read
back by id) has generated names, `fc_p0`, `fc_p1`, ..., numbered in the input's parameter order and sorting in that order:
the map to your names is the input circuit, which the service does not keep. So hold on to the result of `compile()`, or
compile again. From the text alone you can bind by position, with two limits: an expression that is not a real linear
sum (`a**2`) is one more generated name there, so the count differs from your parameters and a positional bind raises
a length error; and the text has no parametric global phase, which matters only if the circuit is later controlled.

**Approximation in Qiskit.** The stages follow Qiskit's own `approximation_degree`, which Qiskit
documents as "1.0 means no approximation (up to numerical tolerance)". At that value, Qiskit's
default, the stages compile exactly: nothing is approximated. For a per-block approximation (each
two-qubit block may differ from its input by a small budget), give `approximation_mode="per_block"`;
`metadata["fourcolors"]` on each output circuit then says what the compile approximated
(`approximation_spent`) and what the check measured (`verification`, `distance`).

| Your Qiskit setting | What the `fourcolors` stages compile |
|---|---|
| `approximation_degree` left at 1.0 (Qiskit's default) | exact |
| any other `approximation_degree`, `None` included | refused, with an error saying what to use |
| `approximation_mode="exact"` in `set_qiskit_options` or `generate_pass_manager` | exact |
| `approximation_mode="per_block"` there | per-block |
| `max_approximation_error=<x>` there | one bound for the whole circuit |

## License

Use of this package with the 4colors service is governed by the 4colors Terms of Service, https://4colors-research.com/terms.
