Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deprecate bind_parameters in favor of assign_parameters #10792

Merged
merged 12 commits into from
Sep 12, 2023
14 changes: 9 additions & 5 deletions qiskit/algorithms/eigen_solvers/vqd.py
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,9 @@ def _eval_aux_ops(
list_op = ListOp(aux_operators)

aux_op_meas = expectation.convert(StateFn(list_op, is_measurement=True))
aux_op_expect = aux_op_meas.compose(CircuitStateFn(self.ansatz.bind_parameters(parameters)))
aux_op_expect = aux_op_meas.compose(
CircuitStateFn(self.ansatz.assign_parameters(parameters))
)
aux_op_expect_sampled = sampler.convert(aux_op_expect)

# compute means
Expand Down Expand Up @@ -611,7 +613,9 @@ def compute_eigenvalues(

eigenvalue = (
StateFn(operator, is_measurement=True)
.compose(CircuitStateFn(self.ansatz.bind_parameters(result.optimal_parameters[-1])))
.compose(
CircuitStateFn(self.ansatz.assign_parameters(result.optimal_parameters[-1]))
)
.reduce()
.eval()
)
Expand All @@ -620,7 +624,7 @@ def compute_eigenvalues(
result.eigenstates.append(self._get_eigenstate(result.optimal_parameters[-1]))

if aux_operators is not None:
bound_ansatz = self.ansatz.bind_parameters(result.optimal_point[-1])
bound_ansatz = self.ansatz.assign_parameters(result.optimal_point[-1])
aux_value = eval_observables(
self.quantum_instance, bound_ansatz, aux_operators, expectation=expectation
)
Expand Down Expand Up @@ -715,7 +719,7 @@ def get_energy_evaluation(

for state in range(step - 1):

prev_circ = self.ansatz.bind_parameters(prev_states[state])
prev_circ = self.ansatz.assign_parameters(prev_states[state])
overlap_op.append(~CircuitStateFn(prev_circ) @ CircuitStateFn(self.ansatz))

def energy_evaluation(parameters):
Expand Down Expand Up @@ -751,7 +755,7 @@ def energy_evaluation(parameters):

def _get_eigenstate(self, optimal_parameters) -> list[float] | dict[str, int]:
"""Get the simulation outcome of the ansatz, provided with parameters."""
optimal_circuit = self.ansatz.bind_parameters(optimal_parameters)
optimal_circuit = self.ansatz.assign_parameters(optimal_parameters)
state_fn = self._circuit_sampler.convert(StateFn(optimal_circuit)).eval()
if self.quantum_instance.is_statevector:
state = state_fn.primitive.data # VectorStateFn -> Statevector -> np.array
Expand Down
2 changes: 1 addition & 1 deletion qiskit/algorithms/eigensolvers/vqd.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ def compute_eigenvalues(
initial_point = validate_initial_point(initial_points[step - 1], self.ansatz)

if step > 1:
prev_states.append(self.ansatz.bind_parameters(result.optimal_points[-1]))
prev_states.append(self.ansatz.assign_parameters(result.optimal_points[-1]))

self._eval_count = 0
energy_evaluation = self._get_evaluate_energy(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult:
f"PauliSumOp | SummedOp, {type(hamiltonian)} provided."
)
if isinstance(hamiltonian, OperatorBase):
hamiltonian = hamiltonian.bind_parameters(evolution_problem.param_value_dict)
hamiltonian = hamiltonian.assign_parameters(evolution_problem.param_value_dict)
if isinstance(hamiltonian, SummedOp):
hamiltonian = self._summed_op_to_pauli_sum_op(hamiltonian)
# the evolution gate
Expand Down
2 changes: 1 addition & 1 deletion qiskit/algorithms/gradients/reverse/bind.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def bind(
"""Bind parameters in a circuit (or list of circuits).

This method also allows passing parameter binds to parameters that are not in the circuit,
and thereby differs to :meth:`.QuantumCircuit.bind_parameters`.
and thereby differs to :meth:`.QuantumCircuit.assign_parameters`.

Args:
circuits: Input circuit(s).
Expand Down
4 changes: 2 additions & 2 deletions qiskit/algorithms/minimum_eigen_solvers/vqe.py
Original file line number Diff line number Diff line change
Expand Up @@ -569,7 +569,7 @@ def compute_minimum_eigenvalue(
self._ret = result

if aux_operators is not None:
bound_ansatz = self.ansatz.bind_parameters(result.optimal_point)
bound_ansatz = self.ansatz.assign_parameters(result.optimal_point)

aux_values = eval_observables(
self.quantum_instance, bound_ansatz, aux_operators, expectation=expectation
Expand Down Expand Up @@ -648,7 +648,7 @@ def energy_evaluation(parameters):

def _get_eigenstate(self, optimal_parameters) -> list[float] | dict[str, int]:
"""Get the simulation outcome of the ansatz, provided with parameters."""
optimal_circuit = self.ansatz.bind_parameters(optimal_parameters)
optimal_circuit = self.ansatz.assign_parameters(optimal_parameters)
state_fn = self._circuit_sampler.convert(StateFn(optimal_circuit)).eval()
if self.quantum_instance.is_statevector:
state = state_fn.primitive.data # VectorStateFn -> Statevector -> np.array
Expand Down
4 changes: 2 additions & 2 deletions qiskit/algorithms/optimizers/qnspsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def loss(x):
initial_point = np.random.random(ansatz.num_parameters)

def loss(x):
bound = ansatz.bind_parameters(x)
bound = ansatz.assign_parameters(x)
return np.real((StateFn(observable, is_measurement=True) @ StateFn(bound)).eval())

fidelity = QNSPSA.get_fidelity(ansatz)
Expand Down Expand Up @@ -387,7 +387,7 @@ def fidelity(values_x, values_y):
value_dict = dict(
zip(params_x[:] + params_y[:], values_x.tolist() + values_y.tolist())
)
return np.abs(expression.bind_parameters(value_dict).eval()) ** 2
return np.abs(expression.assign_parameters(value_dict).eval()) ** 2

else:
sampler = CircuitSampler(backend)
Expand Down
2 changes: 1 addition & 1 deletion qiskit/algorithms/optimizers/spsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ class SPSA(Optimizer):
initial_point = np.random.random(ansatz.num_parameters)

def loss(x):
bound = ansatz.bind_parameters(x)
bound = ansatz.assign_parameters(x)
return np.real((StateFn(observable, is_measurement=True) @ StateFn(bound)).eval())

spsa = SPSA(maxiter=300)
Expand Down
4 changes: 2 additions & 2 deletions qiskit/algorithms/time_evolvers/pvqd/pvqd.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ def get_loss(
self._validate_setup(skip={"optimizer"})

# use Trotterization to evolve the current state
trotterized = ansatz.bind_parameters(current_parameters)
trotterized = ansatz.assign_parameters(current_parameters)

evolution_gate = PauliEvolutionGate(hamiltonian, time=dt, synthesis=self.evolution)

Expand Down Expand Up @@ -388,7 +388,7 @@ def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult
if observables is not None:
observable_values.append(evaluate_observables(next_parameters))

evolved_state = self.ansatz.bind_parameters(parameters[-1])
evolved_state = self.ansatz.assign_parameters(parameters[-1])

result = PVQDResult(
evolved_state=evolved_state,
Expand Down
2 changes: 1 addition & 1 deletion qiskit/circuit/parameter.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class Parameter(ParameterExpression):
qc.draw('mpl')

# bind the parameters after circuit to create a bound circuit
bc = qc.bind_parameters({phi: 3.14})
bc = qc.assign_parameters({phi: 3.14})
bc.measure_all()
bc.draw('mpl')
"""
Expand Down
4 changes: 4 additions & 0 deletions qiskit/circuit/quantumcircuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -2780,6 +2780,10 @@ def _unroll_param_dict(
out[parameter] = value
return out

@deprecate_func(
additional_msg=("Use assign_parameters() instead"),
since="0.45.0",
)
def bind_parameters(
self, values: Union[Mapping[Parameter, float], Sequence[float]]
) -> "QuantumCircuit":
Expand Down
2 changes: 1 addition & 1 deletion qiskit/compiler/assembler.py
Original file line number Diff line number Diff line change
Expand Up @@ -587,7 +587,7 @@ def _expand_parameters(circuits, run_config):
)

circuits = [
circuit.bind_parameters(binds) for circuit in circuits for binds in parameter_binds
circuit.assign_parameters(binds) for circuit in circuits for binds in parameter_binds
]

# All parameters have been expanded and bound, so remove from run_config
Expand Down
2 changes: 1 addition & 1 deletion qiskit/primitives/backend_estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ def _call(
bound_circuits = [
transpiled_circuits[circuit_index]
if len(p) == 0
else transpiled_circuits[circuit_index].bind_parameters(p)
else transpiled_circuits[circuit_index].assign_parameters(p)
for i, (p, n) in enumerate(zip(parameter_dicts, num_observables))
for circuit_index in range(accum[i], accum[i] + n)
]
Expand Down
2 changes: 1 addition & 1 deletion qiskit/primitives/backend_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def _call(
bound_circuits = [
transpiled_circuits[i]
if len(value) == 0
else transpiled_circuits[i].bind_parameters((dict(zip(self._parameters[i], value))))
else transpiled_circuits[i].assign_parameters((dict(zip(self._parameters[i], value))))
for i, value in zip(circuits, parameter_values)
]
bound_circuits = self._bound_pass_manager_run(bound_circuits)
Expand Down
2 changes: 1 addition & 1 deletion qiskit/primitives/estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def _call(
bound_circuits.append(
self._circuits[i]
if len(value) == 0
else self._circuits[i].bind_parameters(dict(zip(self._parameters[i], value)))
else self._circuits[i].assign_parameters(dict(zip(self._parameters[i], value)))
)
sorted_observables = [self._observables[i] for i in observables]
expectation_values = []
Expand Down
2 changes: 1 addition & 1 deletion qiskit/primitives/sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def _call(
bound_circuits.append(
self._circuits[i]
if len(value) == 0
else self._circuits[i].bind_parameters(dict(zip(self._parameters[i], value)))
else self._circuits[i].assign_parameters(dict(zip(self._parameters[i], value)))
)
qargs_list.append(self._qargs_list[i])
probabilities = [
Expand Down
2 changes: 1 addition & 1 deletion qiskit/transpiler/passes/synthesis/unitary_synthesis.py
Original file line number Diff line number Diff line change
Expand Up @@ -784,7 +784,7 @@ def is_controlled(gate):
# rewrite XX of the same strength in terms of it
embodiment = XXEmbodiments[type(v)]
if len(embodiment.parameters) == 1:
embodiments[strength] = embodiment.bind_parameters([strength])
embodiments[strength] = embodiment.assign_parameters([strength])
else:
embodiments[strength] = embodiment
# basis equivalent to CX are well optimized so use for the pi/2 angle if available
Expand Down
4 changes: 3 additions & 1 deletion qiskit/transpiler/passes/utils/unroll_forloops.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ def run(self, dag):

unrolled_dag = circuit_to_dag(body).copy_empty_like()
for index_value in indexset:
bound_body = body.bind_parameters({loop_param: index_value}) if loop_param else body
bound_body = (
body.assign_parameters({loop_param: index_value}) if loop_param else body
)
unrolled_dag.compose(circuit_to_dag(bound_body), inplace=True)
dag.substitute_node_with_dag(forloop_op, unrolled_dag)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
deprecations:
- |
The method :meth:`~qiskit.QuantumCircuit.bind_parameters` is now deprecated. Its functionality
ElePT marked this conversation as resolved.
Show resolved Hide resolved
overlapped highly with :meth:`~qiskit.QuantumCircuit.assign_parameters`, and can be totally
replaced by it. Please use :meth:`~qiskit.QuantumCircuit.assign_parameters` instead.
2 changes: 1 addition & 1 deletion test/benchmarks/circuit_construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,4 +93,4 @@ def setup(self, width, gates, params):
self.circuit, self.params = build_parameterized_circuit(width, gates, params)

def time_bind_params(self, _, __, ___):
self.circuit.bind_parameters({x: 3.14 for x in self.params})
self.circuit.assign_parameters({x: 3.14 for x in self.params})
jakelishman marked this conversation as resolved.
Show resolved Hide resolved
2 changes: 1 addition & 1 deletion test/python/algorithms/test_aux_ops_evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def test_eval_observables(self, observables: ListOrDict[OperatorBase]):
dtype=float,
)

bound_ansatz = ansatz.bind_parameters(parameters)
bound_ansatz = ansatz.assign_parameters(parameters)
expected_result = self.get_exact_expectation(bound_ansatz, observables)

for backend_name in self.backend_names:
Expand Down
6 changes: 3 additions & 3 deletions test/python/algorithms/test_observables_evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def test_estimate_observables(self, observables: ListOrDict[BaseOperator | Pauli
dtype=float,
)

bound_ansatz = ansatz.bind_parameters(parameters)
bound_ansatz = ansatz.assign_parameters(parameters)
states = bound_ansatz
expected_result = self.get_exact_expectation(bound_ansatz, observables)
estimator = Estimator()
Expand All @@ -140,7 +140,7 @@ def test_estimate_observables_zero_op(self):
dtype=float,
)

bound_ansatz = ansatz.bind_parameters(parameters)
bound_ansatz = ansatz.assign_parameters(parameters)
state = bound_ansatz
estimator = Estimator()
observables = [SparsePauliOp(["XX", "YY"]), 0]
Expand All @@ -162,7 +162,7 @@ def test_estimate_observables_shots(self):
dtype=float,
)

bound_ansatz = ansatz.bind_parameters(parameters)
bound_ansatz = ansatz.assign_parameters(parameters)
state = bound_ansatz
estimator = Estimator(options={"shots": 2048})
with self.assertWarns(DeprecationWarning):
Expand Down
2 changes: 1 addition & 1 deletion test/python/algorithms/test_vqe.py
Original file line number Diff line number Diff line change
Expand Up @@ -844,7 +844,7 @@ def test_construct_eigenstate_from_optpoint(self):
vqe = VQE(optimizer=optimizer, quantum_instance=quantum_instance)
result = vqe.compute_minimum_eigenvalue(hamiltonian)

optimal_circuit = vqe.ansatz.bind_parameters(result.optimal_point)
optimal_circuit = vqe.ansatz.assign_parameters(result.optimal_point)
self.assertTrue(Statevector(result.eigenstate).equiv(optimal_circuit))


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def expected_state(time):
result = varqrte.evolve(evolution_problem)

final_parameters = result.parameter_values[-1]
final_state = Statevector(circuit.bind_parameters(final_parameters)).to_dict()
final_state = Statevector(circuit.assign_parameters(final_parameters)).to_dict()
final_expected_state = expected_state(final_time)

for key, expected_value in final_state.items():
Expand Down
4 changes: 3 additions & 1 deletion test/python/circuit/test_circuit_load_from_qpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,9 @@ def test_parameter(self):
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.bind_parameters({theta: 3.14}), new_circ.bind_parameters({theta: 3.14}))
self.assertEqual(
qc.assign_parameters({theta: 3.14}), new_circ.assign_parameters({theta: 3.14})
)
self.assertDeprecatedBitProperties(qc, new_circ)

def test_bound_parameter(self):
Expand Down
4 changes: 2 additions & 2 deletions test/python/circuit/test_circuit_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -760,7 +760,7 @@ def test_bind_global_phase(self):
circuit = QuantumCircuit(1, global_phase=x)
self.assertEqual(circuit.parameters, {x})

bound = circuit.bind_parameters({x: 2})
bound = circuit.assign_parameters({x: 2})
self.assertEqual(bound.global_phase, 2)
self.assertEqual(bound.parameters, set())

Expand All @@ -774,7 +774,7 @@ def test_bind_parameter_in_phase_and_gate(self):
ref = QuantumCircuit(1, global_phase=2)
ref.rx(2, 0)

bound = circuit.bind_parameters({x: 2})
bound = circuit.assign_parameters({x: 2})
self.assertEqual(bound, ref)
self.assertEqual(bound.parameters, set())

Expand Down
10 changes: 5 additions & 5 deletions test/python/circuit/test_hamiltonian_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def test_1q_hamiltonian(self):
qc.x(qr[0])
theta = Parameter("theta")
qc.append(HamiltonianGate(matrix, theta), [qr[0]])
qc = qc.bind_parameters({theta: 1})
qc = qc.assign_parameters({theta: 1})

# test of text drawer
self.log.info(qc)
Expand Down Expand Up @@ -107,7 +107,7 @@ def test_2q_hamiltonian(self):
theta = Parameter("theta")
uni2q = HamiltonianGate(matrix, theta)
qc.append(uni2q, [qr[0], qr[1]])
qc2 = qc.bind_parameters({theta: -np.pi / 2})
qc2 = qc.assign_parameters({theta: -np.pi / 2})
dag = circuit_to_dag(qc2)
nodes = dag.two_qubit_ops()
self.assertEqual(len(nodes), 1)
Expand All @@ -131,7 +131,7 @@ def test_3q_hamiltonian(self):
qc.cx(qr[3], qr[2])
# test of text drawer
self.log.info(qc)
qc = qc.bind_parameters({theta: -np.pi / 2})
qc = qc.assign_parameters({theta: -np.pi / 2})
dag = circuit_to_dag(qc)
nodes = dag.multi_qubit_ops()
self.assertEqual(len(nodes), 1)
Expand All @@ -150,7 +150,7 @@ def test_qobj_with_hamiltonian(self):
uni = HamiltonianGate(matrix, theta, label="XIZ")
qc.append(uni, [qr[0], qr[1], qr[3]])
qc.cx(qr[3], qr[2])
qc = qc.bind_parameters({theta: np.pi / 2})
qc = qc.assign_parameters({theta: np.pi / 2})
qobj = qiskit.compiler.assemble(qc)
instr = qobj.experiments[0].instructions[1]
self.assertEqual(instr.name, "hamiltonian")
Expand All @@ -167,6 +167,6 @@ def test_decomposes_into_correct_unitary(self):
theta = Parameter("theta")
uni2q = HamiltonianGate(matrix, theta)
qc.append(uni2q, [0, 1])
qc = qc.bind_parameters({theta: -np.pi / 2}).decompose()
qc = qc.assign_parameters({theta: -np.pi / 2}).decompose()
decomposed_ham = qc.data[0].operation
self.assertEqual(decomposed_ham, UnitaryGate(Operator.from_label("XY")))
Loading