0
$\begingroup$

I solved "01 KnapSack problem" in Qiskit optimization module. Though the iterations doesn't gets converged but I got an answer (may be infeasible). But my question is that how to interpret the given result because my problem has 10 variable but the result it shows has only 4 variable and an improper vaule of objective function.

This is the code - https://github.com/imAshish28/Quantum_OR/blob/main/Untitled24.ipynb

filename = 'binary_knapsack_10.lp'
qp = QuadraticProgram()
qp.read_from_lp_file(filename)
print(qp.prettyprint())

''' Problem name: binary_knapsack_10

Minimize -135x_0 - 42x_1 - 677x_2 - 773x_3 - 333x_4 - 24x_5 - 819x_6 - 184x_7

  • 683x_8 - 895x_9

Subject to Linear constraints (1) 291x_0 + 80x_1 + 76x_2 + 111x_3 + 687x_4 + 87x_5 + 567x_6 + 969x_7 + 967x_8 + 392x_9 <= 2114 'capacity'

Binary variables (10) x_0 x_1 x_2 x_3 x_4 x_5 x_6 x_7 x_8 x_9 '''

from qiskit_optimization.converters import QuadraticProgramToQubo

qp2qubo = QuadraticProgramToQubo()
qubo = qp2qubo.convert(qp)
qubitOp, offset = qubo.to_ising()
print("Offset:", offset)
print("Ising Hamiltonian:")
print(str(qubitOp))

from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Options, Session

# loading the IBM Acoount with the Backend
QiskitRuntimeService.save_account(channel="ibm_quantum", token="API TOKEN",overwrite=True)
service = QiskitRuntimeService(channel='ibm_quantum')
backend = service.least_busy(operational=True, simulator=False)

from qiskit.circuit.library import QAOAAnsatz
hamiltonian = qubitOp
# QAOA ansatz circuit
ansatz = QAOAAnsatz(hamiltonian, reps=2)

from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager

target = backend.target
pm = generate_preset_pass_manager(target=target, optimization_level=3)
ansatz_isa = pm.run(ansatz)

hamiltonian_isa = hamiltonian.apply_layout(ansatz_isa.layout)
hamiltonian_isa

def cost_func(params, ansatz, hamiltonian, estimator):
    """Return estimate of energy from estimator

    Parameters:
        params (ndarray): Array of ansatz parameters
        ansatz (QuantumCircuit): Parameterized ansatz circuit
        hamiltonian (SparsePauliOp): Operator representation of Hamiltonian
        estimator (Estimator): Estimator primitive instance

    Returns:
        float: Energy estimate
    """
    energy = estimator.run(ansatz, hamiltonian, parameter_values=params).result().values[0]
    return energy

session = Session(backend=backend)

# Configure estimator
estimator = Estimator(session=session)
estimator.options.default_shots = 100


# Configure sampler
sampler = Sampler(session=session)
sampler.options.default_shots = 100


x0 = 2 * np.pi * np.random.rand(ansatz_isa.num_parameters)

from scipy.optimize import minimize
res = minimize(cost_func, x0, args=(ansatz_isa, hamiltonian_isa, estimator), method="COBYLA" , options= {'maxiter' : 5})
res

''' And this is the result which I get: message: Maximum number of function evaluations has been exceeded. success: False status: 2 fun: -464074414.1873996 x: [ 1.743e+00 3.937e+00 3.707e+00 4.516e+00] nfev: 5 maxcv: 0.0 '''

$\endgroup$
6
  • 1
    $\begingroup$ Can you post your code here directly rather than through a link? And can you also provide the results you get? $\endgroup$
    – Tristan Nemoz
    Commented May 16 at 6:30
  • $\begingroup$ Done. Have a look $\endgroup$
    – Maths_hawk
    Commented May 16 at 8:09
  • $\begingroup$ maxiter of 5 says it will do 5 function evals before stopping. Unless your x0 is very close to the solution point that seems way too small. As to how to interpret the given result, the converters not only have a convert method but also an interpret to go the other way. See this tutorial for examples qiskit-community.github.io/qiskit-optimization/tutorials/… $\endgroup$
    – Steve Wood
    Commented May 17 at 17:34
  • $\begingroup$ If I didn't pass maxiter = 5, then it gives me this error- "IBMRuntimeError: 'Failed to run program: \'400 Client Error: Bad Request for url: api.quantum.ibm.com/runtime/jobs. {"errors":[{"code":1217,"message":"Session has been closed.","solution":"Reduce time between submitting subsequent jobs in a session.","more_info":"docs.quantum-computing.ibm.com/errors"}]}\'' Any idea how can I rectify this? Because I want a better solution for this small problem instances. $\endgroup$
    – Maths_hawk
    Commented May 18 at 4:11
  • $\begingroup$ Session has two timeouts, one is an overall duration of use, the other is time between being called i.e. subsequent jobs. That would be each evaluation of your objective function. Why reducing the number of those would make a difference on the time between them - assuming that was the issue, I have no idea, unless the optimizer gets stuck after 5 or something. Maybe try local testing mode on a simulator to get things running first,see docs.quantum.ibm.com/verify/local-testing-mode before trying a real device $\endgroup$
    – Steve Wood
    Commented May 18 at 12:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.