Note
Go to the end to download the full example code.
Example of using the QUBO solver on a pool of small random instances.
# pylint: disable=invalid-name
import numpy as np
from qtealeaves.optimization import QUBOConvergenceParameters, QUBOSolver
def main(qubo_size: int | None = 8, n_instances: int | None = 10) -> None:
"""Example of a QUBO solver routine on random instances."""
# Create a small pool of small random (integer) QUBO problems
np.random.seed(11)
qubo_problems = [
np.random.randint(-50, 50, (qubo_size, qubo_size)) for _ in range(n_instances)
]
qubo_problems = [qubo + qubo.T for qubo in qubo_problems]
# Solve the QUBOs and benchmarking with brute-force
print("\n\n")
separator = "-" * 60
for jj, qprob in enumerate(qubo_problems):
my_solver = QUBOSolver(qprob)
print(separator)
print(f"Solving QUBO problem instance n° {jj + 1}......")
## Brute-force for benchmarking
my_solver.solve("brute-force")
bf_config = my_solver.best_config
bf_cost = my_solver.best_cost
print(
f" Brute-force solution in {my_solver.runtimes['time-to-solution']:.2f} s"
)
print(f"\t Cost --> {bf_cost}")
print(f"\t Solution --> {bf_config}")
## Tensor-network based solver:
## define user's parameters for solving the QUBO
my_conv_params = QUBOConvergenceParameters(
max_bond_dimension=8,
tn_ansatz="MPS", # can be 'TTN'
data_type="D",
max_iter=10,
transverse_field_ratio=1e9,
tn_io_tag=f"{jj + 1}",
# the two following parameters automatically define
# the tensor backend from qtaleaves and / or redtea
linalg_backend_library="numpy", # Can be 'torch'
device="cpu", # can be 'gpu'
)
## Tensor-network based solver:
## call the TN-based solver
my_solver.solve(tn_conv_params=my_conv_params)
## Tensor-network based solver:
## process results
print(
f" Tensor-network solution in {my_solver.runtimes['time-to-solution']:.2f} s"
)
print(f"\t Cost --> {my_solver.best_cost}")
print(f"\t Solution --> {my_solver.best_config}")
print(f"Solving QUBO problem instance n° {jj + 1}......done")
print(separator, "\n\n")
# Output
print(f"\nExample `{__file__}` ran successfully; no asserts implemented.")
if __name__ == "__main__":
main()