### Install luna-quantum Source: https://docs.aqarios.com/luna-model Install the luna-quantum package using pip to access Luna Platform's optimization solvers and quantum computing resources. ```bash pip install luna-quantum ``` -------------------------------- ### Install luna-quantum Package Source: https://docs.aqarios.com/luna-model/intro Install the luna-quantum package using pip to access Luna Platform's optimization solvers and quantum computing resources. ```terminal pip install luna-quantum ``` -------------------------------- ### Install LunaModel with pip Source: https://docs.aqarios.com/luna-model/getting-started Use pip to install the luna-model package. ```bash pip install luna-model ``` -------------------------------- ### Install LunaModel with uv Source: https://docs.aqarios.com/luna-model/intro Use this command to install the luna-model package using uv. ```terminal uv add luna-model ``` -------------------------------- ### Install LunaModel with uv Source: https://docs.aqarios.com/luna-model/getting-started Use uv to add the luna-model package to your project. ```bash uv add luna-model ``` -------------------------------- ### Install LunaModel with Poetry Source: https://docs.aqarios.com/luna-model/getting-started Use Poetry to add the luna-model package to your project. ```bash poetry add luna-model ``` -------------------------------- ### Complete Integration Example Source: https://docs.aqarios.com/luna-model/translators/solution-translators Demonstrates a full workflow including model creation, solving with D-Wave, and converting solutions from D-Wave and NumPy. ```python from luna_model import Model, Vtype, Sense from luna_model.utils import quicksum from luna_model.translator import ( BqmTranslator, DwaveTranslator, NumpyTranslator ) from dimod import SimulatedAnnealingSampler import numpy as np # Create optimization model model = Model(name="Portfolio", sense=Sense.MIN) n_assets = 5 allocations = [ model.add_variable(f"a_{i}", vtype=Vtype.BINARY) for i in range(n_assets) ] # Objective: minimize risk, maximize return returns = [0.05, 0.08, 0.06, 0.07, 0.09] risk_matrix = np.random.rand(n_assets, n_assets) # Quadratic risk term risk = quicksum( risk_matrix[i, j] * allocations[i] * allocations[j] for i in range(n_assets) for j in range(n_assets) ) # Linear return term expected_return = quicksum(returns[i] * allocations[i] for i in range(n_assets)) model.objective = risk - 0.5 * expected_return # Constraint: select at least 2 assets model.constraints += quicksum(allocations) >= 2 # Method 1: Solve with D-Wave bqm_translator = BqmTranslator() bqm = bqm_translator.from_lm(model) sampler = SimulatedAnnealingSampler() sampleset = sampler.sample(bqm, num_reads=100) dwave_translator = DwaveTranslator() solution_dwave = dwave_translator.to_lm(sampleset) print("D-Wave solution:") print(f" Best: {solution_dwave.best()}") print(f" Objective: {min(solution_dwave.obj_values)}") # Method 2: Custom solver returning NumPy # Simulate custom solver result result_array = np.random.randint(0, 2, size=(10, n_assets)) obj_values = np.random.rand(10) * 10 numpy_translator = NumpyTranslator() solution_numpy = numpy_translator.to_lm( result_array, variable_names=[f"a_{i}" for i in range(n_assets)], obj_values=obj_values.tolist() ) print("\nNumPy solution:") print(f" Best: {solution_numpy.best()}") print(f" Objective: {min(solution_numpy.obj_values)}") ``` -------------------------------- ### Install dimod for BQM and CQM Translators Source: https://docs.aqarios.com/luna-model/translators/model-translators Install the luna-model package with the 'dimod' extra to enable BQM and CQM translation capabilities. ```bash pip install luna-model[dimod] ``` -------------------------------- ### Install LunaModel with poetry Source: https://docs.aqarios.com/luna-model/intro Use this command to add the luna-model package to your project using poetry. ```terminal poetry add luna-model ``` -------------------------------- ### Create a Knapsack Optimization Model Source: https://docs.aqarios.com/luna-model/intro This example demonstrates the creation of a simple Knapsack optimization model, including defining variables, setting the objective function, and adding a constraint. ```python from luna_model import Model, Sense, Vtype from luna_model.utils import quicksum # Create a model model = Model(name="Knapsack", sense=Sense.MAX) # Define problem data n_items = 5 max_weight = 25 weights = [1.5, 10.0, 5.2, 3.5, 8.32] values = [10.0, 22.0, 3.2, 1.99, 6.25] # Add binary variables (1 = take item, 0 = don't take) items = [ model.add_variable(f"item_{i}", vtype=Vtype.BINARY) for i in range(n_items) ] # Set objective: maximize total value model.objective = quicksum(values[i] * items[i] for i in range(n_items)) # Add constraint: don't exceed weight limit model.constraints += quicksum(weights[i] * items[i] for i in range(n_items)) <= max_weight print(model) ``` -------------------------------- ### Complete D-Wave Workflow with LunaModel Source: https://docs.aqarios.com/luna-model/translators/solution-translators This example demonstrates a full workflow: creating a LunaModel, converting it to a BQM, solving on a D-Wave system, and converting the results back to a LunaModel solution. ```python from luna_model import Model, Vtype from luna_model.translator import BqmTranslator, DwaveTranslator from dwave.system import DWaveSampler, EmbeddingComposite # Create model model = Model() x = model.add_variable("x", vtype=Vtype.BINARY) y = model.add_variable("y", vtype=Vtype.BINARY) model.objective = x * y - x - 2 * y # Convert to BQM bqm_translator = BqmTranslator() bqm = bqm_translator.from_lm(model) # Solve on D-Wave sampler = EmbeddingComposite(DWaveSampler()) sampleset = sampler.sample(bqm, num_reads=100) # Convert solution solution_translator = DwaveTranslator() solution = solution_translator.to_lm(sampleset) # Analyze print(f"Got {len(solution.samples)} samples") feasible_count = sum(solution.feasible) print(f"Feasible solutions: {feasible_count}") ``` -------------------------------- ### Old Custom Transformation Pass Example Source: https://docs.aqarios.com/luna-model/transformation-migration Example of a custom transformation pass using the older API, returning TransformationOutcome. ```python from luna_model.transformation import TransformationPass, TransformationOutcome class MyPass(TransformationPass): @property def name(self) -> str: return "my-pass" def run(self, model, cache): return TransformationOutcome(model, ...) def backwards(self, solution, cache): return solution ``` -------------------------------- ### Get String Representation of Solution Source: https://docs.aqarios.com/luna-model/api/solution Obtain a human-readable string representation of the Solution object, including its samples and metadata. ```python print(str(solution)) ``` -------------------------------- ### Production Planning Example Source: https://docs.aqarios.com/luna-model/user-guide/modeling-basics Solve a complete production planning problem by defining variables for production quantities, resource constraints, demand constraints, and setting a profit maximization objective. ```python from luna_model import Model, Vtype, Sense model = Model() # Products to manufacture products = ['Widget', 'Gadget', 'Doohickey'] # Production variables (units to produce) production = {} for p in products: production[p] = model.add_variable( f"produce_{p}", vtype=Vtype.INTEGER, lower=0, upper=1000 ) # Resource requirements (hours per unit) labor = {'Widget': 2, 'Gadget': 3, 'Doohickey': 1} machine = {'Widget': 1, 'Gadget': 2, 'Doohickey': 1} # Resource availability (hours) labor_available = 500 machine_available = 400 # Resource constraints model.add_constraint( sum(labor[p] * production[p] for p in products) <= labor_available ) model.add_constraint( sum(machine[p] * production[p] for p in products) <= machine_available ) # Demand constraints (minimum production) demand = {'Widget': 50, 'Gadget': 30, 'Doohickey': 40} for p in products: model.add_constraint(production[p] >= demand[p]) # Profit per unit profit = {'Widget': 12, 'Gadget': 20, 'Doohickey': 8} # Maximize profit model.set_objective( sum(profit[p] * production[p] for p in products), sense=Sense.MAX ) print(model) ``` -------------------------------- ### Complete Knapsack Problem Model Source: https://docs.aqarios.com/luna-model/user-guide/modeling-basics A complete example demonstrating the creation of a model, definition of binary variables, addition of a weight constraint, and setting a maximization objective for the knapsack problem. ```python from luna_model import Model, Vtype, Sense # Create model model = Model() # Variables item_a = model.add_variable("item_a", vtype=Vtype.BINARY) item_b = model.add_variable("item_b", vtype=Vtype.BINARY) item_c = model.add_variable("item_c", vtype=Vtype.BINARY) # Constraint model.add_constraint(2*item_a + 3*item_b + 1*item_c <= 4) # Objective model.set_objective(10*item_a + 15*item_b + 8*item_c, sense=Sense.MAX) print(model) ``` -------------------------------- ### Combine Built-in Transformation Passes Source: https://docs.aqarios.com/luna-model/transformations/builtin-passes This example demonstrates combining IntegerToBinaryPass, MaxBiasAnalysis, and EqualityConstraintsToQuadraticPenaltyPass using PassManager for a typical optimization workflow. ```python from luna_model.transformation import PassManager from luna_model.transformation.passes import ( IntegerToBinaryPass, MaxBiasAnalysis, EqualityConstraintsToQuadraticPenaltyPass, ) pm = PassManager([ IntegerToBinaryPass(), MaxBiasAnalysis(), EqualityConstraintsToQuadraticPenaltyPass(), ]) output = pm.run(model) ``` -------------------------------- ### ExprIter Usage Example Source: https://docs.aqarios.com/luna-model/api/expression Demonstrates how to use the ExprIter to loop through terms and coefficients of an expression and match them to their types. ```APIDOC ## ExprIter Iterator over terms in an expression. Iterates over all terms in an expression, yielding (term, coefficient) tuples where term is a Constant, Linear, Quadratic, or HigherOrder object. ### Example ```python >>> from luna_model import Variable, Environment >>> from luna_model import Constant, Linear, Quadratic, HigherOrder >>> with Environment(): ... x, y, z = Variable("x"), Variable("y"), Variable("z") ... expr = 3 * x + 2 * x * y + 4 * x * y * z + 5 ... for term, coeff in expr.items(): ... match term: ... case Constant(): ... print(f"constant: {coeff}") ... case Linear(var): ... print("linear:", coeff, var.name) ... case Quadratic(var_a, var_b): ... print("quadratic:", coeff, var_a.name, var_b.name) ... case HigherOrder(vars): ... print("higher-order:", coeff, *[v.name for v in vars]) ``` ### `__next__() -> tuple[Constant | Linear | Quadratic | HigherOrder, float]` Get the next term and coefficient. Returns: * `tuple[Constant or Linear or Quadratic or HigherOrder, float]` – The term and its coefficient. Raises: * `StopIteration` – When there are no more terms. ### `__iter__() -> ExprIter` Return the iterator object itself. ``` -------------------------------- ### Access First Sample in a Solution Source: https://docs.aqarios.com/luna-model/user-guide/solutions Get the variable assignments for the first sample in a `Solution`. This is useful when only the primary result is needed. ```python # Get first sample first_sample = solution.samples[0] print(first_sample) # {"x": 1, "y": 0} ``` -------------------------------- ### Example Usage of ToUnconstrainedBinaryPipeline Source: https://docs.aqarios.com/luna-model/api/transformations Demonstrates how to convert a model with binary, spin, and integer variables, including linear constraints, into an unconstrained binary model using ToUnconstrainedBinaryPipeline. Ensure all constraints are linear to avoid errors. ```python from luna_model import Model, Vtype from luna_model.transformation import PassManager, pipelines model = Model() x = model.add_variable("x", vtype=Vtype.BINARY) y = model.add_variable("y", vtype=Vtype.SPIN) z = model.add_variable("z", vtype=Vtype.INTEGER, lower=0, upper=12) model.objective = x + y + z model.constraints += x + y + z <= 3, "c0" model.constraints += x - y - z >= 0, "c1" model.constraints += x + y == 2, "c2" pm = PassManager([pipelines.ToUnconstrainedBinaryPipeline()]) ir = pm.run(model) ``` -------------------------------- ### Example Usage of ToBinaryMinimizationPipeline Source: https://docs.aqarios.com/luna-model/api/transformations Shows how to transform a model containing integer and spin variables into a binary model using ToBinaryMinimizationPipeline. This pipeline does not support real-valued variables. ```python from luna_model import Model, Vtype from luna_model.transformation import PassManager, pipelines model = Model() x = model.add_variable("x", vtype=Vtype.BINARY) y = model.add_variable("y", vtype=Vtype.SPIN) z = model.add_variable("z", vtype=Vtype.INTEGER, lower=0, upper=12) model.objective = x + y + z pm = PassManager([pipelines.ToBinaryMinimizationPipeline()]) ir = pm.run(model) ``` -------------------------------- ### Add Constraints and Set Objective Source: https://docs.aqarios.com/luna-model/user-guide/core-concepts Demonstrates how to add constraints and set the optimization objective for a Luna Model. Inspect the model's properties after setup. ```python model.add_constraint(x + y + z <= 2) model.add_constraint(x + y >= 1) # Set objective model.set_objective(3*x + 2*y + z, sense=Sense.MAX) # Inspect model print(f"Variables: {model.num_variables()}") print(f"Constraints: {model.num_constraints()}") print(f"Objective sense: {model.sense}") ``` -------------------------------- ### Initialize and Access Solution Sample Source: https://docs.aqarios.com/luna-model/api/solution Demonstrates initializing a Solution with sample data, including variable types, and accessing individual sample values by name. ```python from luna_model import Environment, Solution, Vtype solution = Solution( [{"x": 1, "y": 0, "z": 1}], counts=[1], raw_energies=[3], vtypes=[Vtype.BINARY, Vtype.BINARY, Vtype.BINARY] ) result = solution[0] sample = result.sample value = sample["x"] # Access by name print(value) ``` -------------------------------- ### Measure execution time with Timer Source: https://docs.aqarios.com/luna-model/api/utils Instantiate and use the Timer class to measure the duration of operations. Call start() to begin timing and stop() to get the results. ```python >>> from luna_model.timer import Timer >>> timer = Timer.start() >>> # ... perform operations ... >>> timing = timer.stop() >>> print(f"Elapsed: {timing.total_seconds} seconds") Elapsed: ... seconds ``` -------------------------------- ### Create and Configure a Basic Model Source: https://docs.aqarios.com/luna-model/api/model Demonstrates how to create a Model instance, add variables, set an objective function, and define constraints. This is useful for setting up a standard optimization problem. ```python >>> from luna_model import Model, Variable, Sense >>> model = Model("MyModel", sense=Sense.MAX) >>> x = model.add_variable("x") >>> y = model.add_variable("y") >>> model.objective = x * y + x >>> model.constraints += x >= 0 >>> model.constraints += y <= 5 >>> print(model) Model: MyModel Maximize x * y + x Subject To c0: x >= 0 c1: y <= 5 Binary x y ``` -------------------------------- ### Get Best Sample from Solution Source: https://docs.aqarios.com/luna-model/user-guide/solutions Identify and retrieve the sample with the best objective value (minimum for minimization, maximum for maximization) from a `Solution`. This assumes the `solution.samples` list is not empty. ```python # Get best sample (lowest objective for MIN, highest for MAX) if solution.samples: best_idx = solution.obj_values.index(min(solution.obj_values)) best_sample = solution.samples[best_idx] print(best_sample) ``` -------------------------------- ### Create Solution from Samples Source: https://docs.aqarios.com/luna-model/api/solution Demonstrates how to create a Solution object by providing samples, counts, objective values, and feasibility status. Ensure the Environment and Variables are set up prior to creating the Solution. ```python from luna_model import Solution, Environment, Variable env = Environment() x = Variable("x", env=env) y = Variable("y", env=env) samples = [{"x": 0, "y": 1}, {"x": 1, "y": 0}] solution = Solution( samples, counts=[1, 1], obj_values=[5.0, 3.0], feasible=[True, True], env=env, ) ``` -------------------------------- ### Logistics Model with BINARY and INTEGER Variables Source: https://docs.aqarios.com/luna-model/user-guide/variable-types Example of a logistics model using BINARY variables for route selection and INTEGER variables for package quantities. This demonstrates combining discrete decision types. ```python # Route selection (binary) routes = [model.add_variable(f"route_{i}", vtype=Vtype.BINARY) for i in range(10)] # Package quantities (integer) packages = model.add_variable("packages", vtype=Vtype.INTEGER, lower=0, upper=100) ``` -------------------------------- ### Solution Initialization Source: https://docs.aqarios.com/luna-model/api/solution Initializes a Solution object with samples and associated metadata. This constructor allows for detailed configuration of the solution's properties. ```APIDOC ## __init__(samples: Sequence[_Sample], counts: list[int] | None = None, raw_energies: list[float] | None = None, obj_values: list[float] | None = None, feasible: list[bool] | None = None, constraints: Sequence[dict[str, bool]] | None = None, variables_bounds: dict[str, list[bool]] | None = None, timing: Timing | None = None, sense: Sense | None = None, env: Environment | None = None, vtypes: list[Vtype] | None = None, tol: float | None = None) -> None ### Description Initialize a solution with samples and metadata. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **samples** (_Sequence[_Sample]_) – List of variable assignment dictionaries. - **counts** (_list[int]_, optional) – Number of times each sample was observed. - **raw_energies** (_list[float]_, optional) – Raw energy values from the solver. - **obj_values** (_list[float]_, optional) – Evaluated objective function values. - **feasible** (_list[bool]_, optional) – Feasibility status for each sample. - **constraints** (_Sequence[dict[str, bool]]_, optional) – Constraint satisfaction by constraint name for each sample. - **variables_bounds** (_dict[str, list[bool]]_, optional) – Variable bound satisfaction by variable name. - **timing** (_Timing_, optional) – Runtime and timing information. - **sense** (_Sense_, optional) – Optimization sense (MIN or MAX). - **env** (_Environment_, optional) – The environment for variables. - **vtypes** (_list[Vtype]_, optional) – Variable types. - **tol** (_float_, optional) – Tolerance used to treat values as near-integral when casting to binary, spin, or integer assignments. Must satisfy 0.0 <= tol < 1.0. By default a tolerance of 1e-6 is used. ``` -------------------------------- ### Get String Representation of Expression Source: https://docs.aqarios.com/luna-model/api/expression Use the `__str__` method or `print()` to get a human-readable string representation of an expression. This is helpful for debugging and understanding the expression's structure. ```python >>> from luna_model import Variable, Environment >>> with Environment(): ... x = Variable("x") ... y = Variable("y") >>> expr = 3 * x + 2 * y + 5 >>> print(expr) 3 x + 2 y + 5 ``` -------------------------------- ### Scheduling Model with BINARY and REAL Variables Source: https://docs.aqarios.com/luna-model/user-guide/variable-types Example of a scheduling model using BINARY variables for task assignment and REAL variables for task duration. This illustrates combining decision and continuous measurement types. ```python # Task assignment (binary) assigned = model.add_variable("assigned", vtype=Vtype.BINARY) # Task duration (real) duration = model.add_variable("duration", vtype=Vtype.REAL, lower=0.0, upper=8.0) ``` -------------------------------- ### New Custom Transformation Pass Example Source: https://docs.aqarios.com/luna-model/transformation-migration Example of a custom transformation pass using the new API, returning a tuple of model and artifact. It uses PassContext for analysis results. ```python from luna_model.solution.sol import Solution from luna_model.transformation import TransformationPass from luna_model.transformation.artifact import NothingArtifact from luna_model.transformation.context import PassContext class MyPass(TransformationPass[NothingArtifact]): def name(self) -> str: return "my-pass" def forward(self, model, ctx: PassContext) -> tuple: return model, NothingArtifact() @classmethod def backward(cls, artifact: NothingArtifact, solution: Solution) -> Solution: return solution ``` -------------------------------- ### __len__ Source: https://docs.aqarios.com/luna-model/api/constraint Gets the number of constraints in the collection. ```APIDOC ## __len__() -> int ### Description Get the number of constraints in the collection. ### Returns - **int** - The number of constraints. ``` -------------------------------- ### Create and Manage Environment Explicitly Source: https://docs.aqarios.com/luna-model/api/environment Shows how to create an Environment instance and manage variables explicitly. Access the number of registered variables using `num_variables`. ```python >>> env = Environment() >>> x = Variable("x", env=env) >>> print(env.num_variables) # 1 1 >>> var = env.get_variable("x") ``` -------------------------------- ### Model.variables Source: https://docs.aqarios.com/luna-model/api/model Get all variables currently defined in the model. ```APIDOC ## Model.variables ### Description Get all variables in the model. ### Method `variables() -> list[Variable]` ### Returns `list[Variable]` - A list of all variables in the model. ### Example ```python >>> model = Model() >>> x = model.add_variable("x") >>> y = model.add_variable("y") >>> model.objective += x + y >>> vars = model.variables() >>> len(vars) 2 ``` ``` -------------------------------- ### counts property Source: https://docs.aqarios.com/luna-model/api/solution Gets the observation counts for each sample. ```APIDOC ## counts: NDArray property ### Description Get counts. ### Method None ### Endpoint None ### Parameters None ### Request Example None ### Response #### Success Response (200) - **NDArray** – Observation counts for each sample. ### Response Example None ``` -------------------------------- ### Get Variable Source: https://docs.aqarios.com/luna-model/api/environment Retrieves a variable by its name from the environment. ```APIDOC ## Environment.get_variable(name: str) -> Variable ### Description Get a variable by name. ### Method get_variable ### Parameters #### Path Parameters - **name** (str) - Required - The variable name. ### Returns #### Success Response (200) - Variable: The variable with the given name. ### Raises - VariableNotExistingError: If no variable with the given name exists. ``` -------------------------------- ### Create and Manage Constraints Source: https://docs.aqarios.com/luna-model/api/constraint Demonstrates how to initialize a ConstraintCollection, add constraints with names, and access them by name or count. ```python >>> from luna_model import Variable, Environment >>> from luna_model import ConstraintCollection >>> with Environment(): ... x, y = Variable("x"), Variable("y") >>> cc = ConstraintCollection() >>> cc += x + y <= 10, "capacity" >>> cc += x >= 0, "x_lower" >>> print(len(cc)) # Number of constraints 2 >>> constraint = cc["capacity"] # Access by name ``` -------------------------------- ### Model.num_constraints Source: https://docs.aqarios.com/luna-model/api/model Get the number of constraints in the model. This is a read-only property. ```APIDOC ## Model.num_constraints ### Description Get the number of constraints in the model. ### Property `num_constraints` (int) ### Returns `int` - The total number of constraints. ### Example ```python >>> model = Model() >>> x = model.add_variable("x") >>> model.constraints += x <= 5 >>> model.num_constraints 1 ``` ``` -------------------------------- ### Model.num_variables Source: https://docs.aqarios.com/luna-model/api/model Get the number of variables in the model. This is a read-only property. ```APIDOC ## Model.num_variables ### Description Get the number of variables in the model. ### Property `num_variables` (int) ### Returns `int` - The total number of variables. ### Example ```python >>> model = Model() >>> x = model.add_variable("x") >>> y = model.add_variable("y") >>> model.objective += x + y >>> model.num_variables 2 ``` ``` -------------------------------- ### ResultView.counts Source: https://docs.aqarios.com/luna-model/api/solution Gets the number of times this specific result was observed. ```APIDOC ## ResultView.counts ### Description Get the number of times this result was observed. ### Method `counts: int` `property` ``` -------------------------------- ### Pattern 1 - Select Exactly k Items Source: https://docs.aqarios.com/luna-model/user-guide/modeling-basics Demonstrates how to model a selection problem where exactly k items must be chosen from n options using binary variables and a sum constraint. ```python # Create n binary variables n = 5 items = [model.add_variable(f"x_{i}", vtype=Vtype.BINARY) for i in range(n)] # Select exactly k items k = 3 model.add_constraint(sum(items) == k) ``` -------------------------------- ### Get All Variables Source: https://docs.aqarios.com/luna-model/api/environment Retrieves a list of all variables currently registered in the environment. ```APIDOC ## Environment.variables() -> list[Variable] ### Description Get all variables in this environment. ### Method variables ### Parameters None ### Returns - list[Variable]: List of all registered variables. ``` -------------------------------- ### Sum terms with coefficients using quicksum Source: https://docs.aqarios.com/luna-model/api/utils Demonstrates summing terms that include coefficients using the quicksum utility. ```python >>> coeffs = [1, 2, 3, 4, 5] >>> terms = [c * v for c, v in zip(coeffs, vars[:5])] >>> expr = quicksum(terms) >>> print(expr) x0 + 2 x1 + 3 x2 + 4 x3 + 5 x4 ``` -------------------------------- ### Create a LunaModel Model Instance Source: https://docs.aqarios.com/luna-model/user-guide/modeling-basics Initializes a new optimization model. This is the first step before adding variables, constraints, or objectives. ```python from luna_model import Model, Vtype, Sense model = Model() ``` -------------------------------- ### String Representation of ResultView Source: https://docs.aqarios.com/luna-model/api/solution Get a human-readable string representation of the ResultView object. ```python print(str(result_view)) ``` -------------------------------- ### from_(other: SolutionFromTypes, timing: Timing | None = None, env: Environment | None = None, **kwargs: Any) Source: https://docs.aqarios.com/luna-model/api/solution Class method to create a Solution object from various solver result formats, automatically detecting and converting the input. ```APIDOC ## from_(other: SolutionFromTypes, timing: Timing | None = None, env: Environment | None = None, **kwargs: Any) -> Solution `classmethod` ### Description Create solution from various solver result formats. Automatically detects the format and converts to a Solution object. Supports D-Wave SampleSet, Qiskit PrimitiveResult, SCIP Model, numpy arrays, dictionaries, and more. ### Parameters #### Path Parameters * **`other`** (`SolutionFromTypes`) - Required - Result object from a solver (SampleSet, PrimitiveResult, etc.) or data structure (dict, list, ndarray). * **`timing`** (`Timing`, default: `None` ) - Optional - Runtime information to attach to the solution. * **`env`** (`Environment`, default: `None` ) - Optional - Environment for variables. Required for some formats. * **`**kwargs`** (`Any`, default: `{}` ) - Optional - Additional keyword arguments specific to the source format. ### Returns * `Solution` – Converted solution object. ### Raises * `ValueError` – If the format is not recognized or supported. * `RuntimeError` – If required dependencies are not installed. ``` -------------------------------- ### Get constraint by name Source: https://docs.aqarios.com/luna-model/api/constraint Retrieves a specific constraint from the collection using its name. ```APIDOC ## get(name: str) -> Constraint ### Description Get a constraint by its name. ### Parameters #### Parameters - **`name`** (`str`) – The name of the constraint. ### Returns - `Constraint` – The constraint with the given name. ### Raises - `NoConstraintForKeyError` – If no constraint with the given name exists. ### Method get ``` -------------------------------- ### ControlFlowPass Source: https://docs.aqarios.com/luna-model/api/transformations Abstract base class for control-flow passes that guide the transformation at runtime. ```APIDOC ### ControlFlowPass #### Description Abstract base class for control-flow passes. Control-Flow passes guide the transformation at runtime. Execution of a `ControlFlowPass` return a `ControlFlowPlan` that consist of transformation and analysis (or more control-flow passes) to be executed. #### Notes This is an abstract class. Subclasses must implement the `name`, `run` methods. Additionally, the `requires` and `invalidates` and `provides` methods can be implemented. #### Methods * **`name() -> str`** `abstractmethod` * Description: Get the unique identifier for this pass. * Returns: `str` – The unique pass name. * **`run(model: Model, ctx: PassContext) -> ControlFlowPlan`** `abstractmethod` * Description: Run/Execute this transformation pass. * Parameters: * **`model`**(`Model`) – The model to transform. * **`ctx`**(`PassContext`) – Context for this pass providing read-access to the analysis cache. * Returns: `tuple[Model, Artifact]` – The transformation result containing the model and the artifact used for running the backward pass. * **`requires() -> list[str]`** * Description: List of passes that must run before the passes of this control-flow's plan. * Returns: `list[str]` – Pass names that must execute first, or empty list if no dependencies. * **`invalidates() -> list[str]`** * Description: Get a list of passes that are invalidated by this control-flow's plan. * Returns: `list of str` – Names of passes whose results become invalid after this pass runs. * **`provides() -> list[str]`** * Description: Get the identifier for the analysis cache elments this control-flow's plan generates. * Returns: `str` – The identifiers of the cache elements ``` -------------------------------- ### Create Constraints using Comparisons Source: https://docs.aqarios.com/luna-model/api/variable Demonstrates how to create Constraint objects by comparing variables using relational operators like less than or equal to. ```python >>> with Environment(): ... x = Variable("x") ... y = Variable("y") >>> constraint = x + y <= 1 # Creates a Constraint ``` -------------------------------- ### ModelSpecs String Representations Source: https://docs.aqarios.com/luna-model/api/model Get human-readable or detailed string representations of the model specifications. ```APIDOC ## __str__() -> str Return human-readable string representation. Returns: * `str` – String representation of the model specs. ## __repr__() -> str Return detailed string representation. Returns: * `str` – Detailed representation of the model specs. ``` -------------------------------- ### from_dict(data: _Sample, env: Environment | None = None, model: Model | None = None, timing: Timing | None = None, counts: int | None = None, sense: Sense | None = None, energy: float | None = None, tol: float | None = None) Source: https://docs.aqarios.com/luna-model/api/solution Class method to create a Solution object from a single sample represented as a dictionary. ```APIDOC ## from_dict(data: _Sample, env: Environment | None = None, model: Model | None = None, timing: Timing | None = None, counts: int | None = None, sense: Sense | None = None, energy: float | None = None, tol: float | None = None) -> Solution `classmethod` ### Description Create solution from a single sample dictionary. ### Parameters #### Path Parameters * **`data`** (`dict`) - Required - Single sample as a dictionary mapping variable names/objects to values. * **`env`** (`Environment`, default: `None` ) - Optional - Environment containing the variables. * **`model`** (`Model`, default: `None` ) - Optional - Model to evaluate the sample against. * **`timing`** (`Timing`, default: `None` ) - Optional - Runtime information. * **`counts`** (`int`, default: `None` ) - Optional - Number of times this sample was observed. Default is 1. * **`sense`** (`Sense`, default: `None` ) - Optional - Optimization sense. Inferred from model if provided. * **`energy`** (`float`, default: `None` ) - Optional - Raw energy value for this sample. * **`tol`** (`float`, default: `None` ) - Optional - Tolerance used to treat values as near-integral when casting to binary, spin, or integer assignments. A value `x` is accepted as integral if `abs(x - round(x)) <= tol + eps * max(abs(x), 1.0)`, where `eps` is machine epsilon for `float`. Must satisfy `0.0 <= tol < 1.0`. By default a tolerance of 1e-6 is used. ### Returns * `Solution` – Solution containing one sample. ``` -------------------------------- ### Create and Access LunaModel Solution Source: https://docs.aqarios.com/luna-model/intro Demonstrates how to create a Solution object from solver results and access its data, such as the best solution found and its objective value. Requires Environment and Variable to be imported. ```python from luna_model import Solution, Environment, Variable env = Environment() with env: _ = Variable("x") _ = Variable("y") # Create solution from solver results solution = Solution( samples=[{"x": 1, "y": 0}], obj_values=[3.0], feasible=[True], env=env, ) # Access solution data print(f"Best solution: {solution.best()}") print(f"Objective value: {solution.obj_values[0]}") ``` -------------------------------- ### Get Model Specifications Source: https://docs.aqarios.com/luna-model/api/model Retrieves the specifications of the model, including details about its structure and properties. ```python >>> model = Model() >>> specs = model.get_specs() >>> specs.max_num_variables 0 ``` -------------------------------- ### Model.name Source: https://docs.aqarios.com/luna-model/api/model Get or set the model's name. The name is used for identification and debugging. ```APIDOC ## Model.name ### Description Get or set the model's name. ### Property `name` (str, writable) ### Returns `str` - The name of the model. ### Example ```python >>> model = Model("MyModel") >>> model.name 'MyModel' >>> model.name = "UpdatedModel" >>> model.name 'UpdatedModel' ``` ``` -------------------------------- ### violated_constraints Source: https://docs.aqarios.com/luna-model/api/model Get all constraints violated by a sample. Returns a collection containing only the constraints that are violated by the sample. ```APIDOC ## violated_constraints(sample: Sample) -> ConstraintCollection ### Description Get all constraints violated by a sample. ### Parameters #### Path Parameters * **`sample`** (`Sample`) - Required - A dictionary mapping variable names to their values. ### Returns * `ConstraintCollection` - Collection containing only the constraints that are violated by the sample. ``` -------------------------------- ### Environment Initialization Source: https://docs.aqarios.com/luna-model/api/environment Initializes a new environment. Environments serve as context managers to automatically manage variable scoping. ```APIDOC ## Environment() ### Description Initialize a new environment. ### Method __init__ ### Parameters None ### Returns - None ``` -------------------------------- ### Get Variable Types Source: https://docs.aqarios.com/luna-model/api/model Retrieves a list of variable types in the model, corresponding to the order of variables. ```python >>> model = Model() >>> x = model.add_variable("x", vtype=Vtype.BINARY) >>> y = model.add_variable("y", vtype=Vtype.INTEGER) >>> model.objective += x + y >>> model.vtypes() [, ] ``` -------------------------------- ### Handle Empty Solution Sets Source: https://docs.aqarios.com/luna-model/user-guide/solutions Safely access solution data by first checking if any solutions exist. If solutions are found, retrieve and print the best one based on objective values. ```Python # Check before accessing if not solution.samples: print("No solutions found") else: # Get best solution best_idx = solution.obj_values.index(min(solution.obj_values)) best = solution.samples[best_idx] print(f"Best solution: {best}") ``` -------------------------------- ### Pattern 4 - Resource Allocation with Bounds Source: https://docs.aqarios.com/luna-model/user-guide/modeling-basics Demonstrates resource allocation with integer variables having specified lower and upper bounds. Includes constraints for total resource limits and minimum allocations. ```python # Number of resources to allocate n = 3 resources = [model.add_variable(f"resource_{i}", vtype=Vtype.INTEGER, lower=10, upper=100) for i in range(n)] # Total resource constraint model.add_constraint(sum(resources) <= 250) # Minimum allocation per resource for r in resources: model.add_constraint(r >= 10) ``` -------------------------------- ### Get Constraint by Name Source: https://docs.aqarios.com/luna-model/api/constraint Retrieves a specific constraint from the collection using its unique string name. ```python >>> cc.get("capacity") ``` -------------------------------- ### Create Binary Variables Source: https://docs.aqarios.com/luna-model/api/variable Demonstrates how to create binary variables using the Variable class. Variables are binary by default, or can be explicitly set using Vtype.BINARY. ```python >>> from luna_model import Environment, Variable, Vtype >>> with Environment(): ... x1 = Variable("x1") # Binary by default ... x2 = Variable("x2", vtype=Vtype.BINARY) ``` -------------------------------- ### Model.environment Source: https://docs.aqarios.com/luna-model/api/model Get the model's environment. The environment contains all variables and expressions used within the model. ```APIDOC ## Model.environment ### Description Get the model's environment. ### Property `environment` (Environment) ### Returns `Environment` - The environment containing all variables in this model. ``` -------------------------------- ### Create Integer Variables with Bounds Source: https://docs.aqarios.com/luna-model/api/variable Shows how to create integer variables with specified lower and upper bounds using the Bounds class. An environment must be provided or active. ```python >>> from luna_model import Variable, Vtype, Bounds >>> env = Environment() >>> y = Variable("y", vtype=Vtype.INTEGER, bounds=Bounds(0, 10), env=env) ``` -------------------------------- ### Production Planning Formulation Source: https://docs.aqarios.com/luna-model/intro Formulate a production planning problem to maximize profit subject to resource availability. Use `quicksum()` for efficient expression building. ```python # Maximize profit subject to resource constraints model.objective = quicksum(profit[p] * production[p] for p in products) model.constraints += quicksum(labor[p] * production[p] for p in products) <= labor_available ``` -------------------------------- ### Model.constraints Source: https://docs.aqarios.com/luna-model/api/model Get or set the model's constraint collection. The constraint collection holds all constraints that must be satisfied. ```APIDOC ## Model.constraints ### Description Get or set the model's constraint collection. ### Property `constraints` (ConstraintCollection, writable) ### Returns `ConstraintCollection` - The collection of constraints in the model. ### Example ```python >>> model = Model() >>> x = model.add_variable("x") >>> model.constraints += x <= 5 >>> len(model.constraints) 1 ``` ``` -------------------------------- ### Model.objective Source: https://docs.aqarios.com/luna-model/api/model Get or set the model's objective function. The objective function is the expression to be optimized (minimized or maximized). ```APIDOC ## Model.objective ### Description Get or set the model's objective function. ### Property `objective` (Expression, writable) ### Returns `Expression` - The objective function expression. ### Example ```python >>> model = Model() >>> x = model.add_variable("x") >>> y = model.add_variable("y") >>> model.objective = 2 * x + 3 * y >>> model.objective.degree() 1 ``` ``` -------------------------------- ### print Source: https://docs.aqarios.com/luna-model/api/solution Generates a formatted string representation of the solution, with options to control layout, length, and metadata display. ```APIDOC ## print(layout: Literal['row', 'column'] = 'column', max_line_len: int = 80, max_col_len: int = 5, max_lines: int = 10, max_var_name_len: int = 10, show_metadata: Literal['before', 'after', 'hide'] = 'after') -> str ### Description Get formatted string representation of the solution. ### Parameters #### Parameters - **`layout`** (`Literal['row', 'column']`, default: `"column"`) - Optional - Layout orientation for displaying samples. Default is "column". - **`max_line_len`** (`int`, default: `80`) - Optional - Maximum line length in characters. Default is 80. - **`max_col_len`** (`int`, default: `5`) - Optional - Maximum number of samples to display. Default is 5. - **`max_lines`** (`int`, default: `10`) - Optional - Maximum number of variable rows to display. Default is 10. - **`max_var_name_len`** (`int`, default: `10`) - Optional - Maximum variable name length. Default is 10. - **`show_metadata`** (`Literal['before', 'after', 'hide']`, default: `"after"`) - Optional - Where to show metadata (objective, feasibility, etc.). Default is "after". ### Returns - `str` - Formatted string representation. ``` -------------------------------- ### Manually Construct Single Solution Source: https://docs.aqarios.com/luna-model/user-guide/solutions Create a `Solution` object with a single sample for testing or analysis purposes. Ensure `samples`, `obj_values`, and `feasible` lists contain corresponding elements. ```python from luna_model import Solution # Single solution solution = Solution( samples=[{"x": 1.0, "y": 2.0}], obj_values=[5.0], feasible=[True] ) ``` -------------------------------- ### Convert MPS model to string Source: https://docs.aqarios.com/luna-model/api/translators Use MpsTranslator.from_lm without a filepath argument to get the MPS representation as a string. ```python >>> mps_string = MpsTranslator.from_lm(model) >>> print(mps_string) NAME example OBJSENSE MIN ROWS N OBJ L c0 COLUMNS x OBJ 3.0 x c0 1.0 y OBJ 2.0 y c0 1.0 RHS RHS1 c0 1.0 BOUNDS BV BND1 x BV BND1 y ENDATA ``` -------------------------------- ### Convert LP model to string Source: https://docs.aqarios.com/luna-model/api/translators Use LpTranslator.from_lm without a filepath argument to get the LP representation as a string. ```python >>> 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 ``` -------------------------------- ### Create Expressions from Variables Source: https://docs.aqarios.com/luna-model/api/expression Demonstrates creating linear expressions by combining variables and constants. Ensure an active environment context is available. ```python >>> from luna_model import Variable, Environment >>> with Environment(): ... x = Variable("x") ... y = Variable("y") >>> expr = 3 * x + 2 * y - 5 >>> print(expr) 3 x + 2 y - 5 ``` -------------------------------- ### Get Expression Degree Source: https://docs.aqarios.com/luna-model/user-guide/expressions Determine the degree of an expression using the `.degree()` method. This is useful for understanding the complexity of the expression. ```python linear = 3 * x + 2 * y print(linear.degree()) # 1 quadratic = x * y + 2 * x * x print(quadratic.degree()) # 2 higher = x * y * z print(higher.degree()) # 3 ``` -------------------------------- ### Timing Source: https://docs.aqarios.com/luna-model/api/utils Timing information for an operation. Records the start time, end time, and optional QPU time for an operation. ```APIDOC ## Timing ### Description Timing information for an operation. Records the start time, end time, and optional QPU time for an operation. ### Attributes - **`start`** (`datetime`) – When the operation started. - **`end`** (`datetime`) – When the operation ended. - **`total`** (`timedelta`) – Total elapsed time. - **`total_seconds`** (`float`) – Total elapsed time in seconds. - **`qpu`** (`float or None`) – QPU time in seconds, if applicable. ### Properties #### `start: datetime` Get the start time. #### `end: datetime` Get the end time. #### `total: timedelta` Get the total elapsed time. #### `total_seconds: float` Get the total elapsed time in seconds. #### `qpu: float | None` (writable) Get the QPU time in seconds. ### Methods #### `add_qpu(value: float) -> None` Add time to the QPU counter. #### `__str__() -> str` Return human-readable string representation. Returns: * `str` – String representation of the timing. ``` -------------------------------- ### Integrate BQM with D-Wave Sampler Source: https://docs.aqarios.com/luna-model/translators/model-translators Convert a LunaModel to a BQM, solve it using a D-Wave sampler like ExactSolver, and then convert the solution back to a LunaModel. ```python from dimod import ExactSolver from luna_model.translator import BqmTranslator, DwaveTranslator # Create and translate model model = Model() # ... define model ... # To BQM bqm = BqmTranslator.from_lm(model) # Solve with D-Wave sampler sampler = ExactSolver() sampleset = sampler.sample(bqm) # Convert solution back solution = DwaveTranslator.to_lm(sampleset) print(f"Best solution: {solution.best()}") print(f"Best energy: {min(solution.obj_values)}") ```