Skip to content

Commit 64caf42

Browse files
dongreenbergmanoelmarqueswoodsp-ibm
authored
* Add abelian property to opvecs and AbelianGrouper to operator init. * Break up PauliCoB big clifford synthesis function into smaller ones. * Add AbelianGrouper test. * Add better input checking in primitives and remove unnecessary print. * Fix coeffs bugs in pauli_cob.py. * Reorganize pauli_cob. All tests pass, with grouping on and off. * Change expectation_value backends to work through setters. * Reorganize local_simulator_sampler.py a bit to use it in a test. * Grouping Paulis works!! All tests pass. * Add "compute TPB pauli" function to pauli_cob. * Add WIP attempt at evolution over Abelian paulis. * Fix trotter bug. * Fix some other Trotter bugs. * Add parameters to OpPaulis and test. Parameterized evolution passes!!! * Add parameter binding for Op coefficients. * Add parameter binding, and binding tests. Tests pass. * Add division to Operators to make normalization convenient. * Finish merging MinEigenSolver PR. All tests pass. * Update QAOA, all tests pass!! * Update some QAOA imports and typehints. * Add QDrift trotterization method. All tests pass. * Start migrating QPE, tests fail. * fix spell * fix almost all style errors * fix copyright * fix import cycles, changed to relative imports when possible * relative imports * Add bind_params to state_fn_circuit.py and op_circuit.py, and tests. Add list unrolling for param binding, and tests. Tests pass. * Add param list handling for all Op types. * Make OpVec printing nicer. * Add op_converter to imports for better backwards compatibility. * Add AerPauliExpectation tests. Tests pass. Issue with Aer though. * Fix a few AerPauliExpectation bugs * Start building toward parameterized Qobj. * fix some lint errors * fix some lint errors * fix style * fix copyright * set style to defaults, fix aqua unit test loading * change loading tests qpe/iqpe * Fix OpPrimitive lint errors. * Fix operator_base.py lint errors. * Fix state_fn.py lint errors. * Fix OpVec lint errors. * Fix state_fn_circuit.py lint errors. * Fix state_fn_dict.py lint errors. * Fix state_fn_operator.py lint errors. * Fix state_fn_vector.py lint errors. Tests pass. * Fix QDrift test to deal with first Op in trotterization list being OpCircuit. * Fix op_circuit.py lint errors. * Fix op_pauli.py lint errors. * Fix op_composition.py lint errors. * Fix op_kron.py lint errors. * Fix abelian_grouper.py lint errors. Tests pass. * Fix pauli_cob.py lint errors. Tests pass. * Fix Expectation lint errors. Tests pass. * Fix circuit sampler lint errors. Tests pass. * Fix other expectation lint errors. Tests pass. * Fix trotterization lint errors. Tests pass. * Add MatrixEvolution shell, fix evolution lint errors. * Fix bug in evolution tests after fixing lint errors. * Fix cyclic import for lint. * fix pylint cyclic import error * Make tests pass. Add aux_ops back to VQE, and make VQE and QAOA take old or new ops. * fix spell and lint * Fix swapping issue in evolution. * Fix composition in OpEvolution. * Fix add OpSum and kron OpKron in OpEvolution. * Add to_opflow to legacy base_operator * Clean OpCircuit and StateFnCircuit __str__ * Fix qaoa mixer. * fix spell,style * Ok now really all tests pass. * add to_matrix_op() methods to ops. * Start migrating NumpyEigensolver for Opflow * Start removing back from op_primitive eval functions. All tests pass. * Update eval logic (to be able to remove back) for operator_combos. * Add to_matrix_op for OpMatrix and StateFnVector, and change some `if back`s to `if back is not None` * Finish decoupling back args from evals. All tests pass. * Remove back from eval logic. * Remove back from eval. All tests pass. * Change matrix_expectation.py to rely on to_matrix_op. * Migrate numpy_eigen_solver.py and numpy_minimum_eigen_solver. * Remove ToMatrixOp converter. * set VQE _auto_conversion to False for now * Add sampling and tests. Fix a rounding error in a test. Fix a not none error in numpy_eigen_solver.py. * Add array methods to OpVec. Fix typo in OpPauli. Allow reverse_endianness in to_opflow for WeightedPauli. * Make NumpyEigensolver return a StateFn in result.eigenstate. * Fix flaky optimization tests. Fix OpVec so iterator interface works. * Fix StateFnVector sampling. Fix sparse NumpyEigensolution. Fix some aux_op stuff. Fix some other things here and there. Please no more breakage. * Change some sparsity stuff. * fix spelling * Typehints. * More typehints * fix copyright * fix spelling * More typehints, make globals immutable. * fix style * Rearrange tests, Add CZ to globals. * Refactor some names. * Rename OpEvolution to EvolutionOp. Tests pass. * Rename primitive ops. All tests pass. * Finish renamings. * Test IBMQ Pauli expectation. All tests pass. * Update spelling. * Update Pauli to num_qubits. * Updating some naming. * Add diag support to fix knapsack issue. * fix unit test * fix unit test * fix travis * Turn half of Steve's comments. * Fix some exponentiation things. * Fix some exponentiation things. * Add trotterization_factory. All tests pass. * Add evolution_factory. All tests pass. * Add circuit_sampler_factory. All tests pass. * Rename get_primitives to primitive_strings. Turn some of Julien's changes. * Only allow sample_circuits to accept circuit_ops. Tests pass. * Turn more review changes * fix spell, style * Add matrix_op exp_i() into HamiltonianGate. Tests fail due to CircuitOp decompose() during composition. If commented out (line 158) tests pass. * Change CircuitOp and StateFnCircuit to rely on QuantumCircuit instead of Instruction. All tests pass. Add to_circuit_op to relevant ops. Solves all the decompose issues. * Add matrix_evolution and update QAOA to test matrix_op for cost operator. Add logic to update UCCSD to operator flow. Tests pass. * Delete PauliToInstruction, as it's obsolete. * Add to_pauli_op and tests. Tests pass. * Fix composed_op.py eval bug * Add sig digit rounding. VQE tests fail. * better precision for sig digit rounding. Tests pass. * Fix pep8, add comment * Add to_circuit_op to statefns, making DictToCircuit mostly obsolete. Tests pass. * fix cyclic imports * fix numpy boolean to string coercion * Update repr and a docstring. * Make ExpectationValues into converters. Test pass. * Fix bug from merge. * Fix bugs, make Minus just a CircuitStateFn and not a ComposedOp. * Uncomment HamiltonianGate * Update lots of docstrings part I. Tests pass. * fix docstring * More docstrings. Change class.rst so docs are generated for some python operator overloads. * Add navigation structure for docs to init files * More docs. * fix doctrings * 1) Change local_simulator_sampler.py to circuit_sampler.py 2) Set up circuit_samplers directory to be removed. 3) Add IBMQ VQE test. 4) Change AerPauliExpectation and CircuitSampler to handle expval_measurement/snapshots correctly. Tests pass. * 1) Delete circuit_samplers. 2) Allow CircuitSampler to attach_results. * Update Operator init * Change Operator directory names. Tests pass. * fix spell, docs * Turn Expectations purely into converters. Tests pass. * fix docs * skip IBMQ test * Add Converters docs. Tests pass. * fix spell * Add Evolutions docs. Tests pass. * Add Expectation docs. Tests pass. * fix spell * Add StateFn docs. Tests pass. * Fix typo. * Add ListOp init docs. * Fix some ordering * Little docs edits. * fix spell * Little docs edits. * 1) Add to_legacy_op to OperatorBase to allow non-migrated algos to accept new Operators. 2) Allow QPE and iQPE to accept new Operators, migrate tests. Tests pass. * Fix typehints for minimum_eigen_solvers * Make sure expectations can handle mixed observables. * fix spell * Turn some more of Steve's comments. Tests pass. * Turn some more of Steve's comments. Fix a buncha parameter stuff, and make sure mixed Pauli evolution works. * Turn some more of Steve's comments. Tests pass. * Turn some comments, fix a QAOA bug. * Try collapsing ListOp to_matrix a bit. * Turn more comments, fix some bugs. * Turn more comments, fix some bugs. * Update ListOp docs. * Update ListOp docs. * Update ListOp docs. * fix docstring * Update minimum_eigen_solvers setter typehints. * Add Changelog and tests for DictToCircuitSum. * Update VQE's construct_circuit and some changelog elements. * fix spell * Allow MinEigenOptimizer to accept StateFn result in result.eigenstate. * fix style * Update changelog with more detail. Update VQE to call super. * Typo Co-authored-by: Manoel Marques <manoel@us.ibm.com> Co-authored-by: woodsp <woodsp@us.ibm.com>
1 parent 4278d25 commit 64caf42

File tree

8 files changed

+125
-118
lines changed

8 files changed

+125
-118
lines changed

qiskit/aqua/algorithms/classifiers/vqc.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -368,8 +368,8 @@ def _cost_function_wrapper(self, theta):
368368
if self._callback is not None:
369369
self._callback(
370370
self._eval_count,
371-
theta[i * self._var_form.num_parameters:(i + 1) *
372-
self._var_form.num_parameters],
371+
theta[i * self._var_form.num_parameters:(i + 1)
372+
* self._var_form.num_parameters],
373373
curr_cost,
374374
self._batch_index
375375
)
@@ -671,8 +671,8 @@ def cost_estimate(probs, gt_labels, shots=None): # pylint: disable=unused-argum
671671
def cross_entropy(predictions, targets, epsilon=1e-12):
672672
predictions = np.clip(predictions, epsilon, 1. - epsilon)
673673
N = predictions.shape[0]
674-
tmp = np.sum(targets*np.log(predictions), axis=1)
675-
ce = -np.sum(tmp)/N
674+
tmp = np.sum(targets * np.log(predictions), axis=1)
675+
ce = -np.sum(tmp) / N
676676
return ce
677677

678678
x = cross_entropy(probs, mylabels)

qiskit/aqua/algorithms/distribution_learners/qgan.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ def __init__(self, data: np.ndarray, bounds: Optional[np.ndarray] = None,
116116
# pylint: disable=unsubscriptable-object
117117
if np.ndim(data) > 1:
118118
if self._num_qubits is None:
119-
self._num_qubits = np.ones[len(data[0])]*3
119+
self._num_qubits = np.ones[len(data[0])] * 3
120120
else:
121121
if self._num_qubits is None:
122122
self._num_qubits = np.array([3])
@@ -274,15 +274,15 @@ def train(self):
274274
for e in range(self._num_epochs):
275275
aqua_globals.random.shuffle(self._data)
276276
index = 0
277-
while (index+self._batch_size) <= len(self._data):
278-
real_batch = self._data[index: index+self._batch_size]
277+
while (index + self._batch_size) <= len(self._data):
278+
real_batch = self._data[index: index + self._batch_size]
279279
index += self._batch_size
280280
generated_batch, generated_prob = self._generator.get_output(self._quantum_instance,
281281
shots=self._batch_size)
282282

283283
# 1. Train Discriminator
284284
ret_d = self._discriminator.train([real_batch, generated_batch],
285-
[np.ones(len(real_batch))/len(real_batch),
285+
[np.ones(len(real_batch)) / len(real_batch),
286286
generated_prob])
287287
d_loss_min = ret_d['loss']
288288

qiskit/aqua/components/neural_networks/numpy_discriminator.py

+18-14
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727

2828
logger = logging.getLogger(__name__)
2929

30+
3031
# pylint: disable=invalid-name
3132

3233

@@ -167,12 +168,13 @@ def single_layer_backward_propagation(da_curr,
167168
m = y.shape[1]
168169
y = y.reshape(np.shape(x))
169170
if weights is not None:
170-
da_prev = - np.multiply(weights,
171-
np.divide(y, np.maximum(np.ones(np.shape(x))*1e-4, x)) -
172-
np.divide(1 - y, np.maximum(np.ones(np.shape(x))*1e-4, 1 - x)))
171+
da_prev = - np.multiply(
172+
weights,
173+
np.divide(y, np.maximum(np.ones(np.shape(x)) * 1e-4, x))
174+
- np.divide(1 - y, np.maximum(np.ones(np.shape(x)) * 1e-4, 1 - x)))
173175
else:
174-
da_prev = - (np.divide(y, np.maximum(np.ones(np.shape(x))*1e-4, x)) -
175-
np.divide(1 - y, np.maximum(np.ones(np.shape(x))*1e-4, 1 - x))) / m
176+
da_prev = - (np.divide(y, np.maximum(np.ones(np.shape(x)) * 1e-4, x))
177+
- np.divide(1 - y, np.maximum(np.ones(np.shape(x)) * 1e-4, 1 - x))) / m
176178

177179
pointer = 0
178180

@@ -306,17 +308,18 @@ def loss(self, x, y, weights=None):
306308
if weights is not None:
307309
# Use weights as scaling factors for the samples and compute the sum
308310
return (-1) * np.dot(np.multiply(y,
309-
np.log(np.maximum(np.ones(np.shape(x)) * 1e-4, x))) +
310-
np.multiply(np.ones(np.shape(y))-y,
311-
np.log(np.maximum(np.ones(np.shape(x))*1e-4,
312-
np.ones(np.shape(x))-x))), weights)
311+
np.log(np.maximum(np.ones(np.shape(x)) * 1e-4, x)))
312+
+ np.multiply(np.ones(np.shape(y)) - y,
313+
np.log(np.maximum(np.ones(np.shape(x)) * 1e-4,
314+
np.ones(np.shape(x)) - x))),
315+
weights)
313316
else:
314317
# Compute the mean
315318
return (-1) * np.mean(np.multiply(y,
316-
np.log(np.maximum(np.ones(np.shape(x)) * 1e-4, x))) +
317-
np.multiply(np.ones(np.shape(y))-y,
318-
np.log(np.maximum(np.ones(np.shape(x))*1e-4,
319-
np.ones(np.shape(x))-x))))
319+
np.log(np.maximum(np.ones(np.shape(x)) * 1e-4, x)))
320+
+ np.multiply(np.ones(np.shape(y)) - y,
321+
np.log(np.maximum(np.ones(np.shape(x)) * 1e-4,
322+
np.ones(np.shape(x)) - x))))
320323

321324
def _get_objective_function(self, data, weights):
322325
"""
@@ -342,7 +345,7 @@ def objective_function(params):
342345
prediction_fake = self.get_label(generated_batch)
343346
loss_fake = self.loss(prediction_fake,
344347
np.zeros(np.shape(prediction_fake)), generated_prob)
345-
return 0.5*(loss_real[0]+loss_fake[0])
348+
return 0.5 * (loss_real[0] + loss_fake[0])
346349

347350
return objective_function
348351

@@ -371,6 +374,7 @@ def gradient_function(params):
371374
grad_generated = self._discriminator.backward(prediction_generated, np.zeros(
372375
np.shape(prediction_generated)), generated_prob)
373376
return np.add(grad_real, grad_generated)
377+
374378
return gradient_function
375379

376380
def train(self, data, weights, penalty=False, quantum_instance=None, shots=None):

qiskit/aqua/components/neural_networks/pytorch_discriminator.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ def gradient_penalty(self, x, lambda_=5., k=0.01, c=1.):
170170
x = Variable(x)
171171
# pylint: disable=no-member
172172
delta_ = torch.rand(x.size()) * c
173-
z = Variable(x+delta_, requires_grad=True)
173+
z = Variable(x + delta_, requires_grad=True)
174174
o_l = self.get_label(z)
175175
# pylint: disable=no-member
176176
d_g = torch.autograd.grad(o_l, z, grad_outputs=torch.ones(o_l.size()),

qiskit/aqua/components/neural_networks/quantum_generator.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -301,9 +301,9 @@ def loss(self, x, weights): # pylint: disable=arguments-differ
301301
"""
302302
try:
303303
# pylint: disable=no-member
304-
loss = (-1)*np.dot(np.log(x).transpose(), weights)
304+
loss = (-1) * np.dot(np.log(x).transpose(), weights)
305305
except Exception: # pylint: disable=broad-except
306-
loss = (-1)*np.dot(np.log(x), weights)
306+
loss = (-1) * np.dot(np.log(x), weights)
307307
return loss.flatten()
308308

309309
def _get_objective_function(self, quantum_instance, discriminator):

qiskit/aqua/utils/dataset_helper.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
# This code is part of Qiskit.
44
#
5-
# (C) Copyright IBM 2018, 2019.
5+
# (C) Copyright IBM 2018, 2020.
66
#
77
# This code is licensed under the Apache License, Version 2.0. You may
88
# obtain a copy of this license in the LICENSE.txt file in the root directory
@@ -193,8 +193,9 @@ def discretize_and_truncate(data, bounds, num_qubits, return_data_grid_elements=
193193
# prepare element grid for dim j
194194
elements_current_dim = np.linspace(bounds[j, 0], bounds[j, 1], (2 ** prec))
195195
# find index for data sample in grid
196-
index_grid = np.searchsorted(elements_current_dim,
197-
data_row-(elements_current_dim[1]-elements_current_dim[0])*0.5)
196+
index_grid = np.searchsorted(
197+
elements_current_dim,
198+
data_row - (elements_current_dim[1] - elements_current_dim[0]) * 0.5)
198199
for k, index in enumerate(index_grid):
199200
data[k, j] = elements_current_dim[index]
200201
if j == 0:

0 commit comments

Comments
 (0)