Translators API Reference
Model Translators
LpTranslator
Translator for LP file format.
LpTranslator provides static methods to convert between LunaModel's internal Model representation and the LP file format. The LP format is a widely-used text-based format for representing linear and quadratic optimization problems.
The LP format supports: - Linear and quadratic objective functions - Linear and quadratic constraints - Integer, binary, and continuous variables - Variable bounds
Examples:
Read a model from an LP file:
Write a model to an LP file:
>>> from luna_model import Model, Variable, Vtype
>>> from luna_model.translator import LpTranslator
>>> model = Model(name="example")
>>> x = model.add_variable("x", vtype=Vtype.BINARY)
>>> y = model.add_variable("y", vtype=Vtype.BINARY)
>>> model.objective = 3 * x + 2 * y
>>> model.constraints += x + y <= 1
>>> LpTranslator.from_lm(model, "problem.lp")
Convert to LP string without writing to file:
>>> lp_string = LpTranslator.from_lm(model)
>>> print(lp_string)
\ Model example
\ Problem name: example
Minimize
3 x + 2 y
Subject To
c0: 1 x + 1 y <= 1
Bounds
Binaries
x y
End
to_lm(file: str | Path) -> Model
staticmethod
Convert LP file or string to LunaModel.
Reads an optimization model from an LP file or parses an LP-formatted string and converts it to a LunaModel Model object.
Parameters:
-
file(str or Path) –Either a path to an LP file or an LP-formatted string. If the string contains newlines or looks like LP content, it will be parsed as a string. Otherwise, it will be treated as a file path.
Returns:
-
Model–The parsed model in LunaModel format.
Raises:
-
TranslationError–If the LP file is malformed or contains unsupported constructs.
-
FileNotFoundError–If the specified file path does not exist.
Examples:
From a file:
From a string:
from_lm(model: Model, filepath: Path | None = None) -> str | None
staticmethod
Convert LunaModel to LP file or string.
Converts a LunaModel Model to LP format, either writing to a file or returning the LP-formatted string.
Parameters:
-
model(Model) –The LunaModel to convert.
-
filepath(Path, default:None) –If provided, writes the LP representation to this file path. If
None, returns the LP string without writing to a file.
Returns:
-
str or None–If
filepathisNone, returns the LP-formatted string. Iffilepathis provided, writes to file and returnsNone.
Raises:
-
TranslationError–If the model contains constructs that cannot be represented in LP format (e.g., higher-order terms).
Examples:
Write to file:
>>> from luna_model import Model
>>> model = Model(name="example")
>>> # ... build model ...
>>> LpTranslator.from_lm(model, "output.lp")
Get LP string:
QuboTranslator
Translator for QUBO format.
QuboTranslator provides static methods to convert between LunaModel's internal Model representation and the QUBO (Quadratic Unconstrained Binary Optimization) format. QUBO is a matrix-based representation widely used in quantum computing and combinatorial optimization.
QUBO format requires: - All variables must be binary (or spin) - No constraints (unconstrained) - At most quadratic degree (no cubic or higher terms)
If the model doesn't meet these requirements, use transformations first.
Examples:
Convert matrix to LunaModel:
>>> import numpy as np
>>> from luna_model.translator import QuboTranslator
>>> # Define QUBO matrix (upper-triangular)
>>> Q = np.array([[-1, 2], [0, -1]])
>>> model = QuboTranslator.to_lm(Q, variable_names=["x", "y"])
Convert model to QUBO:
>>> from luna_model import Model
>>> model = Model()
>>> x = model.add_variable("x")
>>> y = model.add_variable("y")
>>> model.objective = x * y - 2 * x + y
>>> qubo = QuboTranslator.from_lm(model)
to_lm(qubo: NDArray, *, offset: float | None = None, variable_names: list[str] | None = None, name: str | None = None, vtype: Vtype | None = None) -> Model
staticmethod
Convert QUBO matrix to LunaModel.
Creates a LunaModel Model from a QUBO matrix representation.
Parameters:
-
qubo(NDArray) –QUBO matrix where Q[i,j] represents the coefficient for x[i]*x[j]. Diagonal elements Q[i,i] are linear coefficients. If the matrix is not symmetric, it will be made symmetric by summing Q[i,j] and Q[j,i].
-
offset(float, default:None) –Constant offset term to add to objective. Default is 0.
-
variable_names(list[str], default:None) –Names for variables. If None, generates names like "x0", "x1", etc.
-
name(str, default:None) –Name for the model.
-
vtype(Vtype, default:None) –Variable type (BINARY or SPIN). Default is BINARY.
Returns:
-
Model–LunaModel with objective function representing the QUBO.
Examples:
Basic usage:
With custom names and offset:
Notes
Non-symmetric matrices are automatically symmetrized: the coefficient for x[i]*x[j] becomes Q[i,j] + Q[j,i].
from_lm(model: Model) -> Qubo
staticmethod
Convert LunaModel to QUBO format.
Converts a LunaModel Model to QUBO representation.
Parameters:
-
model(Model) –The model to convert. Must be: - Unconstrained (no constraints) - Binary or spin variables only - At most quadratic (degree ≤ 2)
Returns:
-
Qubo–QUBO representation with matrix, offset, and metadata.
Raises:
-
TranslationError–If the model has constraints, non-binary variables, or higher-order terms.
Examples:
>>> from luna_model import Model
>>> model = Model()
>>> x = model.add_variable("x")
>>> y = model.add_variable("y")
>>> model.objective = x * y - 2 * x + y
>>> qubo = QuboTranslator.from_lm(model)
>>> print(qubo.matrix)
[[-2. 0.5]
[ 0.5 1. ]]
Notes
If your model doesn't meet the QUBO requirements, use transformations to convert it:
BqmTranslator
Translator for Binary Quadratic Model format.
Converts between LunaModel and BinaryQuadraticModel (BQM) format.
Requires the dimod extra.
Examples:
>>> from dimod import BinaryQuadraticModel
>>> from luna_model.translator import BqmTranslator
>>> bqm = BinaryQuadraticModel({"x": -1, "y": -1}, {("x", "y"): 2}, 0.0, "BINARY")
>>> model = BqmTranslator.to_lm(bqm, name="my_model")
>>> from luna_model import Model
>>> model = Model()
>>> x = model.add_variable("x")
>>> y = model.add_variable("y")
>>> model.objective = -x - y + 2 * x * y
>>> bqm = BqmTranslator.from_lm(model)
Notes
The model must be unconstrained with at most quadratic terms.
to_lm(bqm: BinaryQuadraticModel, *, name: str | None = None) -> Model
staticmethod
Convert D-Wave BQM to LunaModel.
Converts a D-Wave Ocean SDK BinaryQuadraticModel to a LunaModel Model.
Parameters:
-
bqm(BinaryQuadraticModel) –D-Wave BQM to convert. All variable names must be strings.
-
name(str, default:None) –Name for the resulting model. If None, uses default name.
Returns:
-
Model–LunaModel representation with objective function matching the BQM.
Raises:
-
RuntimeError–If
dimodpackage is not installed. -
TypeError–If
bqmis not a BinaryQuadraticModel or if variable names are not strings.
Examples:
>>> from dimod import BinaryQuadraticModel
>>> from luna_model.translator import BqmTranslator
>>> bqm = BinaryQuadraticModel({"x": -1, "y": 2}, {("x", "y"): 1}, 0.5, "BINARY")
>>> model = BqmTranslator.to_lm(bqm, name="example")
>>> print(model.objective)
x y - x + 2 y + 0.5
Notes
The translator preserves variable types (BINARY or SPIN) and the constant offset term from the BQM.
from_lm(model: Model) -> BinaryQuadraticModel
staticmethod
Convert LunaModel to D-Wave BQM.
Converts a LunaModel Model to a D-Wave BinaryQuadraticModel.
Parameters:
-
model(Model) –The model to convert. Must be: - Unconstrained (no constraints) - Binary or spin variables only - At most quadratic (degree ≤ 2)
Returns:
-
BinaryQuadraticModel–D-Wave BQM ready for use with D-Wave solvers.
Raises:
-
RuntimeError–If
dimodpackage is not installed. -
TranslationError–If the model has constraints, non-binary/spin variables, or higher-order terms.
Examples:
CqmTranslator
Translator for Constrained Quadratic Model format.
Converts between LunaModel and ConstrainedQuadraticModel (CQM) format.
Requires the dimod extra.
Examples:
>>> from dimod import ConstrainedQuadraticModel, Binary
>>> from luna_model.translator import CqmTranslator
>>> cqm = ConstrainedQuadraticModel()
>>> x = Binary("x")
>>> y = Binary("y")
>>> cqm.set_objective(-x - y + 2 * x * y)
>>> _ = cqm.add_constraint(x + y <= 1, label="c1")
>>> model = CqmTranslator.to_lm(cqm, name="my_model")
>>> print(model)
Model: my_model
Minimize
2 * x * y - x - y
Subject To
c1: x + y <= 1
Binary
x y
>>> from luna_model import Model, Vtype
>>> from luna_model.translator import CqmTranslator
>>> model = Model()
>>> x = model.add_variable("x", vtype=Vtype.BINARY)
>>> y = model.add_variable("y", vtype=Vtype.BINARY)
>>> model.objective = x * y - 2 * x + y
>>> model.constraints += x + y <= 1
>>> cqm = CqmTranslator.from_lm(model)
>>> print(cqm)
Constrained quadratic model: 2 variables, 1 constraints, 5 biases
Objective
-2*Binary('x') + Binary('y') + Binary('x')*Binary('y')
Constraints
c0: Binary('x') + Binary('y') <= 1.0
Bounds
to_lm(cqm: ConstrainedQuadraticModel, *, name: str | None = None) -> Model
staticmethod
Convert D-Wave CQM to LunaModel.
Converts a D-Wave ConstrainedQuadraticModel to a LunaModel Model.
Parameters:
-
cqm(ConstrainedQuadraticModel) –D-Wave CQM to convert.
-
name(str, default:None) –Name for the resulting model. If None, uses the CQM's name or a default name.
Returns:
-
Model–LunaModel representation with objective and constraints matching the CQM.
Raises:
-
RuntimeError–If
dimodpackage is not installed. -
TypeError–If
cqmis not a ConstrainedQuadraticModel.
Examples:
>>> from dimod import ConstrainedQuadraticModel, Binary, Integer
>>> from luna_model.translator import CqmTranslator
>>> cqm = ConstrainedQuadraticModel()
>>> x = Binary("x")
>>> y = Integer("y", lower_bound=0, upper_bound=10)
>>> cqm.set_objective(x + 2 * y)
>>> _ = cqm.add_constraint(x + y >= 3, label="min_sum")
>>> model = CqmTranslator.to_lm(cqm, name="example")
>>> print(model.objective)
x + 2 y
>>> print(len(model.constraints))
1
Notes
The conversion preserves all variable types, bounds, constraints, and the objective function from the CQM.
from_lm(model: Model) -> ConstrainedQuadraticModel
staticmethod
Convert LunaModel to D-Wave CQM.
Converts a LunaModel Model to a D-Wave ConstrainedQuadraticModel.
Parameters:
-
model(Model) –The model to convert. Should have: - At most quadratic objective and constraints
Returns:
-
ConstrainedQuadraticModel–D-Wave CQM ready for use with D-Wave hybrid solvers.
Raises:
-
RuntimeError–If
dimodpackage is not installed. -
TranslationError–If the model contains constructs not supported by CQM format.
Examples:
>>> from luna_model import Model, Variable, Vtype
>>> from luna_model.translator import CqmTranslator
>>> model = Model(name="knapsack")
>>> x = [model.add_variable(f"x{i}", vtype=Vtype.BINARY) for i in range(5)]
>>> values = [10, 15, 20, 25, 30]
>>> weights = [2, 3, 4, 5, 6]
>>> # Maximize value
>>> model.objective = sum(v * x[i] for i, v in enumerate(values))
>>> # Weight constraint
>>> model.constraints += sum(w * x[i] for i, w in enumerate(weights)) <= 10
>>> cqm = CqmTranslator.from_lm(model)
Solution Translators
NumpyTranslator
Translator for NumPy array solutions.
Converts solution data in NumPy array format to LunaModel Solutions.
Examples:
>>> import numpy as np
>>> from luna_model import Environment, Variable
>>> from luna_model.translator import NumpyTranslator
>>> samples = np.array([[0, 1], [1, 0], [1, 1]])
>>> energies = np.array([-2.5, -1.0, 0.5])
>>> env = Environment()
>>> with env:
... _ = Variable("x")
... _ = Variable("y")
>>> solution = NumpyTranslator.to_lm(samples, energies, env=env)
>>> print(solution)
x y │ feas raw obj count
0 1 │ ? -2.5 ? 1
1 0 │ ? -1.0 ? 1
1 1 │ ? 0.5 ? 1
Total samples: 3
Total variables: 2
to_lm(result: NDArray, energies: NDArray, timing: Timing | None = None, *, env: Environment | None = None) -> Solution
staticmethod
Convert NumPy arrays to LunaModel solution.
Parameters:
-
result(NDArray) –2D array of solution samples, shape (n_samples, n_variables).
-
energies(NDArray) –1D array of energy/objective values, shape (n_samples,).
-
timing(Timing, default:None) –Timing information for the solution process.
-
env(Environment, default:None) –Environment for mapping array indices to variable names. Required either as parameter or active context.
Returns:
-
Solution–LunaModel Solution with samples and energies.
DwaveTranslator
Translator for D-Wave solution format.
Converts D-Wave SampleSet objects to LunaModel Solutions. Automatically aggregates duplicate solutions.
Requires the dimod extra.
to_lm(sample_set: SampleSet, timing: Timing | None = None, *, env: Environment | None = None) -> Solution
staticmethod
Convert D-Wave SampleSet to LunaModel solution.
Parameters:
-
sample_set(SampleSet) –D-Wave SampleSet returned by a sampler.
-
timing(Timing, default:None) –Timing information for the solution process.
-
env(Environment, default:None) –Environment for variable mapping. Required either as parameter or active context.
Returns:
-
Solution–LunaModel Solution with aggregated samples.
Raises:
-
RuntimeError–If
dimodpackage is not installed.
IbmTranslator
Translator for IBM Qiskit solution format.
Converts IBM Qiskit PrimitiveResult objects to LunaModel Solutions.
Requires the qiskit extra.
to_lm(result: PrimitiveResult[PubResult], quadratic_program: QuadraticProgram, timing: Timing | None = None, *, env: Environment | None = None) -> Solution
staticmethod
Convert IBM Qiskit result to LunaModel solution.
Parameters:
-
result(PrimitiveResult[PubResult]) –Qiskit primitive result containing measurement outcomes.
-
quadratic_program(QuadraticProgram) –Original QuadraticProgram used to evaluate objective values.
-
timing(Timing, default:None) –Timing information for the solution process.
-
env(Environment, default:None) –Environment for variable mapping. Required either as parameter or active context.
Returns:
-
Solution–LunaModel Solution with bitstring counts and energies.
Raises:
-
RuntimeError–If
qiskitorqiskit-optimizationpackages are not installed.
AwsTranslator
Translator for Amazon Braket solution format.
Converts Amazon Braket result dictionaries to LunaModel Solutions.
to_lm(aws_result: dict[str, Any], timing: Timing | None = None, *, env: Environment | None = None) -> Solution
staticmethod
Convert Amazon Braket result to LunaModel solution.
Parameters:
-
aws_result(dict[str, Any]) –Amazon Braket result dictionary containing 'samples' and 'energies', default None.
-
timing(Timing, default:None) –Timing information for the solution process.
-
env(Environment, default:None) –Environment for variable mapping. Required either as parameter or active context.
Returns:
-
Solution–LunaModel Solution with samples and energies.
QctrlTranslator
Translator for Q-Ctrl solution format.
Converts Q-Ctrl result dictionaries to LunaModel Solutions. Handles variable-to-bitstring mapping and reordering.
to_lm(result: dict[str, Any], timing: Timing | None = None, *, env: Environment | None = None) -> Solution
staticmethod
Convert Q-Ctrl result to LunaModel solution.
Parameters:
-
result(dict[str, Any]) –Q-Ctrl result dictionary containing 'final_bitstring_distribution' and 'variables_to_bitstring_index_map'.
-
timing(Timing, default:None) –Timing information for the solution process.
-
env(Environment, default:None) –Environment for variable mapping. Required either as parameter or active context.
Returns:
-
Solution–LunaModel Solution with bitstring counts.
Notes
Extracts indices from bracket notation (e.g., 'var[0]') and reorders bitstrings accordingly.
ZibTranslator
Translator for SCIP/ZIB solution format.
Converts SCIP Model objects to LunaModel Solutions.
Requires the scip extra.
to_lm(model: ScipModel, timing: Timing | None = None, *, env: Environment | None = None) -> Solution
staticmethod
Convert SCIP solution to LunaModel solution.
Parameters:
-
model(Model) –A solved SCIP model (from pyscipopt).
-
timing(Timing, default:None) –Timing information for the solution process.
-
env(Environment, default:None) –Environment for variable filtering. Required either as parameter or active context. Only variables in the environment are included in the solution.
Returns:
-
Solution–LunaModel Solution with variable values from SCIP.
Raises:
-
RuntimeError–If
pyscipoptpackage is not installed.