Skip to content

Exploring the Solution Object

After running the optimization of a Model, using an algorithm, a Solution object is returned. The Solution stores all the relevant information about the outcome of the optimization, including the obtained samples, their objective values, solver energies, occurrence counts, and metadata such as the runtime.

In this section, we demonstrate how to work with a Solution object and explain the purpose of each of its properties.

Inspecting Samples and Occurrence Counts

The Solution.samples property provides an iterator over the candidate solutions obtained, where each sample represents an assignment of values to the model's variables. To get a list of all samples, you should explicitly convert the iterator using .tolist():

samples = solution.samples.tolist()
print(samples)

If you're interested in how often each sample was found during the solution process, you can use the Solution.counts property:

counts = solution.counts
print(counts)

This gives you a list of the number of times each sample appears, in the same order as in samples.

Objective Values and Solver Energies

The Solution.obj_values method returns the evaluated objective values, as an np.array, corresponding to each sample. If the sample has not been evaluated yet, its objective value will be None. In addition to the objective values, solvers may also return native energy scores of their computations. These can be accessed through the Solution.raw_energies method.

Evaluate the solution with:

solution = model.evaluate(solution)

Then, retrieve the objective values and raw energies:

print(solution.raw_energies)
print(solution.obj_values)

Runtime Information

To get the total runtime (in seconds) it took the algorithm to compute the solution, for benchmarking and comparing solver performance for example, the Solution.runtime method can be called.

print(solution.runtime)

Accessing the Best Solution

In the case you are primarily interested in the best-performing candidate without manually comparing all samples, you can retrieve the solution with the best objective value using solution.best().

best_solution = solution.best()
best_value = best_solution.obj_value

print(f"Best solution: {best_solution}")
print(f"Objective value of best solution: {best_value}")

Iterating Over Results

Finally, the solution.results iterates over the detailed results for each sample. These include all previously discussed information attached to each sample.

for result in solution.results:
    print(result)