2
$\begingroup$

I'm working on a portfolio optimization problem using Qiskit and I'm encountering an error when trying to solve a quadratic program using MinimumEigenOptimizer with SamplingVQE (V1 Primitives). Any insights on what might be causing this error or how to fix it would be greatly appreciated!

When I run the code below, I get the following error:

AlgorithmError: 'The number of qubits of the ansatz does not match the operator, and the ansatz does not allow setting the number of qubits using num_qubits.'

Here's the code I'm using:

from qiskit_algorithms import SamplingVQE
from qiskit_finance.applications.optimization import PortfolioOptimization
from qiskit_finance.data_providers import RandomDataProvider
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_ibm_runtime import QiskitRuntimeService, Session, SamplerV2 as Sampler
from qiskit.circuit.library import RealAmplitudes
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_algorithms.optimizers import SLSQP
import numpy as np
import datetime

num_assets = 30
seed = 123

# Generate expected return and covariance matrix from (random) time-series
stocks = [("TICKER%s" % i) for i in range(num_assets)]
data = RandomDataProvider(
    tickers=stocks,
    start=datetime.datetime(2016, 1, 1),
    end=datetime.datetime(2016, 1, 30),
    seed=seed,
)
data.run()
mu = data.get_period_return_mean_vector()
sigma = data.get_period_return_covariance_matrix()

q = 0.5  # set risk factor
budget = num_assets // 2  # set budget
penalty = num_assets  # set parameter to scale the budget penalty term

portfolio = PortfolioOptimization(
    expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget
)
qp = portfolio.to_quadratic_program()

service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.least_busy(operational=True, simulator=False)
session = Session(service=service, backend=backend)

ansatz = RealAmplitudes(qp.get_num_binary_vars(), reps=3)
pm = generate_preset_pass_manager(backend=backend, optimization_level=2)
isa_circuit = pm.run(ansatz)

vqe = SamplingVQE(sampler=Sampler(session=session), ansatz= isa_circuit, optimizer=SLSQP())  
optimizer = MinimumEigenOptimizer(vqe)
result = optimizer.solve(qp)
print(result)
$\endgroup$

0

Your Answer

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