Solver and cancellation#

class pybsp_rust.Solver[source]#

Independent mutable BSP state with inspectable message passing.

Parameters:
  • formula (Formula) – Immutable normalized formula. Compatible objects exposing clauses and n are copied into a native Formula on construction.

  • options (Options or None, default None) – Optional compatibility configuration. Prefer the named algorithm keywords. Combining this object with any algorithm keyword raises TypeError.

  • execution (ExecutionOptions or None, default None) – Optional compatibility configuration. Prefer backend, threads, and profile. Combining this object with any hardware keyword raises TypeError.

  • seed (int, default 1) – Unsigned 64-bit solver RNG seed. Controls initial messages and local search. It does not change a formula already generated with another seed.

  • backtrack_ratio (float, default 0.9) – Target ratio of backtracking actions to decimation actions, in [0,1). This is a deterministic scheduling ratio, not a per-step probability. Zero disables scheduled backtracking. Large values increase revisiting.

  • batch_fraction (float, default 0.00125) – Fraction in (0,1] of currently free variables selected per decimation. The batch is max(1, floor(batch_fraction * free_variables)), capped by the number free. Smaller batches require more SP fixed points.

  • epsilon (float, default 0.01) – Absolute tolerance in (0,1) on the largest undamped message update. Convergence does not establish the accuracy of the survey approximation.

  • damping (float, default 0.0) – Old-message weight in [0,1): new = raw + damping * (old - raw). Zero is undamped. Increasing it can stabilize oscillations but slows relaxation. The convergence test still compares raw against old.

  • max_sweeps (int, default 1024) – Positive sweep limit for each SP fixed-point attempt.

  • max_steps (int, default 100000) – Positive limit on recorded BSP actions. A step can contain many sweeps.

  • max_flips (int, default 0) – Nonnegative unsigned 64-bit WalkSAT flip budget across all restarts. Zero selects walksat_restarts * max(10000, 100 * residual_variables), counting free variables in active clauses at WalkSAT entry. Positive values override the automatic budget.

  • walksat_restarts (int, default 4) – Positive maximum number of randomized completions. Each restart has a quota of ceil(resolved_budget / walksat_restarts); the total cap still holds.

  • walksat_noise (float, default 0.5) – Probability in [0,1] of a uniformly random free variable in a sampled unsatisfied clause when every candidate has positive break count. Otherwise choose among minimum-break candidates, breaking ties randomly.

  • timeout_seconds (float or None, default None) – Positive finite cooperative wall-time limit since solver construction, including backend setup and time between calls. None disables it.

  • backend ({'cpu', 'cpu-parallel', 'metal', 'cuda', 'cuda-f32'}, default 'cpu') – Scalar CPU double precision, multicore CPU double precision, Apple GPU single precision, NVIDIA GPU double precision, or NVIDIA GPU single precision. Metal requires a macOS metal build; CUDA requires a Linux cuda build and a supported device. Availability is checked when a solver is constructed. Single precision may change the search path.

  • threads (int, default 0) – Worker limit in 0..1024. Zero selects available logical CPUs. A single scalar CPU or GPU solver uses one host execution thread; solve_many uses this budget for independent jobs. The parallel CPU backend also uses it for sweeps within a job when appropriate.

  • profile (str or pathlib.Path or None, default None) – JSON profile destination written by Solver.solve(). Enables phase timers and GPU timestamps; GPU instrumentation changes submission costs. Batch solving rejects profiling: profile individual solvers instead.

formula#

Normalized input with shared immutable native topology.

Type:

Formula

cancellation_token#

Thread-safe one-way handle for cooperative interruption.

Type:

CancellationToken

Raises:
  • ValueError – If a setting, formula, or backend is invalid or unavailable.

  • TypeError – If a keyword is unknown or configuration sources conflict.

Notes

The DEFAULT marker in the signature means omitted; effective defaults are listed for each parameter above. Direct calls send dictionaries to Rust without constructing configuration dataclasses. Existing Options calls remain supported. Each solver owns its RNG, assignments, messages, counters, and cancellation state. Native calls release the GIL; do not mutate a solver concurrently. Reassigning a Python configuration attribute does not reconfigure native state.

Array properties are owned snapshots in normalized clause incidence order. Only read free-variable surveys after successful converge() and before another update or graph mutation. These are cluster-forcing surveys, not ordinary SAT marginals. The solver is a heuristic and cannot prove UNSAT.

Examples

>>> formula = Formula([[1], [-2]], n=2)
>>> Solver(formula=formula, seed=3).solve().status
'sat'
__init__(formula, options=None, *, execution=None, seed=DEFAULT, backtrack_ratio=DEFAULT, batch_fraction=DEFAULT, epsilon=DEFAULT, damping=DEFAULT, max_sweeps=DEFAULT, max_steps=DEFAULT, max_flips=DEFAULT, walksat_restarts=DEFAULT, walksat_noise=DEFAULT, timeout_seconds=DEFAULT, backend=DEFAULT, threads=DEFAULT, profile=DEFAULT)[source]#

Initialize native solver state using the class parameter contract.

property options#

Return a lazily materialized algorithm compatibility snapshot.

Returns:

Options – Immutable settings snapshot; reading it does not reconfigure Rust.

property execution#

Return a lazily materialized hardware compatibility snapshot.

Returns:

ExecutionOptions – Requested hardware settings. Inspect execution_report for actual use.

property assignment#

Return an owned snapshot of the current partial assignment.

Returns:

numpy.ndarray – Shape (n,), dtype int8, with -1 for free, 0 for false, and 1 for true. Mutating this snapshot does not change native state.

property execution_report#

Return current backend, resource, fallback, and profiling metadata.

Returns:

dict – Fresh report with requested/actual backend, precision, device, memory, counters, fallbacks, errors, and enabled phase timings.

property messages#

Return an owned snapshot of clause-to-variable warnings.

Returns:

numpy.ndarray – Shape (formula.edges,), dtype float64, probabilities in [0, 1], in normalized clause incidence order. Fixed/inactive incidences are zero.

Notes

GPU f32 values are widened on export; float64 snapshots do not imply f64 internal arithmetic. Pass edited values to set_messages() to update state.

property surveys#

Return an owned snapshot of variable cluster-forcing surveys.

Returns:

numpy.ndarray – Shape (n, 3), dtype float64, columns true, false, and unfrozen. Fixed rows are one-hot true/false. Free rows are meaningful only after converge().

Notes

These are not ordinary marginals of a uniform satisfying-assignment measure. Sweeps and graph mutations can leave free-variable surveys stale.

property free_variables#

Return the number of currently unfixed variables.

Returns:

int – Count of free variables in the BSP partial assignment.

property active_clauses#

Return the number of clauses not yet satisfied by fixed variables.

Returns:

int – Count of active clauses in the residual graph.

set_messages(values)[source]#

Replace live and frozen messages in normalized incidence order.

Parameters:

values (numpy.ndarray) – Flat array of length formula.edges with finite probabilities in [0, 1]. Inactive/fixed values are saved for restoration; live incidences stay zero.

Returns:

None – Native state is updated in place.

Raises:

ValueError – If the array is not flat, has the wrong length, or contains invalid values.

Notes

This invalidates surveys and clears terminal state. Counters, elapsed time, and cancellation persist. Unsafe GPU f32 conversion records a CPU fallback.

fix(variable, value)[source]#

Fix one variable and simplify its incidences.

Parameters:
  • variable (int) – Zero-based index of a currently free variable in [0, formula.n).

  • value (bool) – True fixes the variable true; False fixes it false.

Returns:

None – Graph state is updated in place.

Raises:

ValueError – If the variable is out of range or already fixed.

Notes

Unit propagation is deferred until propagate(), converge(), or advance(). Free surveys become stale. This explicit decision can later be released.

release(variable)[source]#

Unfix an explicit decision and restore its frozen messages.

Parameters:

variable (int) – Zero-based index of a fixed decision variable in [0, formula.n).

Returns:

None – Graph state is updated in place and terminal state is cleared.

Raises:

ValueError – If the index is invalid, the variable is free, or it was unit-forced.

Notes

Free surveys become stale. Unit implications are not rolled back; construct a fresh solver to explore an independent branch with fresh implications.

propagate()[source]#

Apply queued unit implications.

Returns:

int – Number of newly forced variables in this call.

Raises:

RuntimeError – On a contradictory residual, cancellation, timeout, or numerical/device failure. A contradiction under heuristic decisions is not an UNSAT proof.

sweep()[source]#

Run one synchronous cavity/clause update.

Returns:

float – Maximum absolute undamped message update in the sweep.

Raises:

RuntimeError – On numerical failure, contradiction, cancellation, or timeout.

Notes

Units are not propagated and surveys are not refreshed. Use converge() for a fixed-point attempt. The returned array snapshots are synchronized.

sweep_many(count)[source]#

Run raw synchronous sweeps, synchronizing snapshots once.

Parameters:

count (int) – Nonnegative number of sweeps. Zero returns 0.0 without updating messages.

Returns:

float – Final undamped residual, or 0.0 for zero sweeps.

Raises:
  • OverflowError – If count is negative or outside the native index range.

  • RuntimeError – On numerical/device failure, contradiction, cancellation, or timeout.

Notes

Units and surveys are not refreshed. GPU readback is amortized across sweeps; numerical recovery and cooperative interruption remain enabled.

converge()[source]#

Propagate units, attempt an SP fixed point, then refresh surveys.

Returns:

dict – sweeps for this attempt, last undamped residual, total complexity estimate, and paramagnetic diagnostic. The latter is not a SAT verdict.

Raises:

RuntimeError – On nonconvergence, contradiction, numerical/device failure, cancellation, or timeout.

Notes

At most max_sweeps are attempted per precision attempt. GPU numerical recovery can retry on CPU f64. Convergence alone does not certify survey accuracy.

advance()[source]#

Converge and perform one scheduled BSP action.

Returns:

dict – Step record with action (decimate/backtrack/walksat), index, pre-action free/active counts, cumulative sweeps, residual, complexity, and change count.

Raises:

RuntimeError – On a terminal condition, including calls after termination.

Notes

WalkSAT may finish the search. Use solve() to retrieve a terminal result record.

decimate()[source]#

Fix the highest-certainty free-variable batch using cached surveys.

Returns:

int – Number of variables changed by this decision batch.

Raises:

RuntimeError – If interruption or a native operational failure prevents the action.

Notes

Call converge() first. This method does not compute a fixed point or propagate units. Equal certainty uses ascending variable index; equal true/false forcing selects false.

backtrack()[source]#

Release eligible decisions with the lowest frozen certainty.

Returns:

int – Number of decisions released by this action.

Raises:

RuntimeError – If interruption or a native operational failure prevents the action.

Notes

The budget uses the preceding decimation batch plus pending unit implications, capped by eligible decisions. Unit-forced variables cannot be released. This does not recompute surveys or propagate units.

residual_formula()[source]#

Return active clauses with fixed literals removed.

Returns:

Formula – Normalized residual with the original declared variable count and labels.

Notes

Variable IDs are not compacted. Retain the partial assignment separately when reconstructing a completion of the original input.

solve()[source]#

Continue the current search until a terminal condition.

Returns:

SolveResult – Owned result with a CPU-verified assignment only for status ‘sat’. Other statuses report heuristic failures or limits and do not prove UNSAT.

Notes

Existing work, decisions, counters, cancellation, and elapsed time are retained. Operational failures are represented in status, rather than raised as RuntimeError. A profile-write error is recorded in execution metadata without replacing an otherwise valid result.

class pybsp_rust.CancellationToken#

Thread-safe, one-way cancellation handle obtained from a Solver.

Call cancel() from another thread during a long native computation. The solver checks cooperatively at sweep/submission and local-search checkpoints. There is no reset method; create another solver for a fresh token.

classmethod __new__(*args, **kwargs)#
cancel()#

Request cancellation. Repeated calls are harmless; the flag stays set.

Returns:

None – Cancellation stays permanently requested for the associated solver.

is_cancelled#

Whether cancellation has been requested, even if computation has not stopped.

Returns:

bool – Whether interruption has been requested; native work may still be stopping.

The cancellation handle is obtained through solver.cancellation_token; it has no public constructor or reset operation. See Inspecting and controlling a search for state transitions, snapshot freshness, and concurrent cancellation examples.