Skip to content

Commit

Permalink
Merge pull request #126 from Qiskit/master
Browse files Browse the repository at this point in the history
fetch from origin
  • Loading branch information
stefan-woerner authored Aug 3, 2020
2 parents 081acf5 + 9999b6e commit 3b7f27a
Show file tree
Hide file tree
Showing 67 changed files with 1,615 additions and 1,079 deletions.
3 changes: 3 additions & 0 deletions .pylintdict
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ composable
conda
conf
config
contravariance
conv
coord
coords
Expand Down Expand Up @@ -384,6 +385,7 @@ msq
multiclass
multinomial
multiprocess
mypy
nakanishi
namelist
nan
Expand Down Expand Up @@ -689,6 +691,7 @@ wavefunctions
weightedpaulioperator
wf
whitespace
whitespaces
wigner
wikipedia
workq
Expand Down
32 changes: 24 additions & 8 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ notifications:
email:
if: fork = false AND type = cron
recipients:
- manoel@us.ibm.com
- manoel.marques@ibm.com
on_success: never
on_failure: always

Expand Down Expand Up @@ -122,24 +122,39 @@ jobs:
include:
- stage: Checks and Tests
<<: *stage_dependencies
name: "Pip, spell, style, lint, copyright and docs checks"
name: "Pip, spell, style, lint, copyright and docs checks Python 3.7"
if: tag IS blank
install:
# install spell check libraries
- sudo apt-get -y install python3-enchant
- sudo apt-get -y install hunspell-en-us
- pip install pyenchant
- pip install cplex
- pip install "cvxpy>1.0.0,<1.1.0"
- pip install "cvxpy>1.0.0"
- pip install https://github.com/rpmuller/pyquante2/archive/master.zip --progress-bar off
script:
- pip check
- make spell
- make style
- make lint
# Lint with latest pylint also
- pip install -U pylint
- make lint
- make copyright
- make html SPHINXOPTS=-W
- make doctest
- name: "Lint check Python 3.8"
<<: *stage_dependencies
if: tag IS blank
python: 3.8
install:
- pip install "cvxpy>1.0.0"
- pip install https://github.com/rpmuller/pyquante2/archive/master.zip --progress-bar off
script:
- make lint
# Lint with latest pylint also
- pip install -U pylint
- make lint
- name: "Mypy check"
<<: *stage_dependencies
if: tag IS blank
Expand All @@ -159,7 +174,7 @@ jobs:
- aqua137.dep
before_script:
- pip install cplex
- pip install "cvxpy>1.0.0,<1.1.0"
- pip install "cvxpy>1.0.0"
- export PYTHON="coverage3 run --source qiskit/aqua,qiskit/chemistry,qiskit/finance,qiskit/ml,qiskit/optimization --omit */gauopen/* --parallel-mode"
script:
- stestr --test-path test/aqua run --blacklist-file selection.txt 2> >(tee /dev/stderr out.txt > /dev/null)
Expand All @@ -175,7 +190,7 @@ jobs:
paths: aqua138.dep
python: 3.8
before_script:
- pip install "cvxpy>1.0.0,<1.1.0"
- pip install "cvxpy>1.0.0"
script:
- stestr --test-path test/aqua run --blacklist-file selection.txt 2> >(tee /dev/stderr out.txt > /dev/null)
- python tools/extract_deprecation.py -file out.txt -output aqua138.dep
Expand All @@ -190,7 +205,7 @@ jobs:
- aqua237.dep
before_script:
- pip install cplex
- pip install "cvxpy>1.0.0,<1.1.0"
- pip install "cvxpy>1.0.0"
- export PYTHON="coverage3 run --source qiskit/aqua,qiskit/chemistry,qiskit/finance,qiskit/ml,qiskit/optimization --omit */gauopen/* --parallel-mode"
script:
- stestr --test-path test/aqua run --whitelist-file selection.txt 2> >(tee /dev/stderr out.txt > /dev/null)
Expand All @@ -206,7 +221,7 @@ jobs:
paths: aqua238.dep
python: 3.8
before_script:
- pip install "cvxpy>1.0.0,<1.1.0"
- pip install "cvxpy>1.0.0"
script:
- stestr --test-path test/aqua run --whitelist-file selection.txt 2> >(tee /dev/stderr out.txt > /dev/null)
- python tools/extract_deprecation.py -file out.txt -output aqua238.dep
Expand All @@ -228,7 +243,7 @@ jobs:
- sudo apt-get -y install libgfortran5
# Installing pyquante2 master branch...
- pip install https://github.com/rpmuller/pyquante2/archive/master.zip --progress-bar off
- pip install cplex
- pip install cplex pyscf
before_script:
- export PYTHON="coverage3 run --source qiskit/aqua,qiskit/chemistry,qiskit/finance,qiskit/ml,qiskit/optimization --omit */gauopen/* --parallel-mode"
script:
Expand All @@ -251,6 +266,7 @@ jobs:
- sudo apt-get -y install libgfortran5
# Installing pyquante2 master branch...
- pip install https://github.com/rpmuller/pyquante2/archive/master.zip --progress-bar off
- pip install pyscf
script:
- stestr --test-path test/chemistry run 2> >(tee /dev/stderr out.txt > /dev/null)
- python tools/extract_deprecation.py -file out.txt -output chemistry38.dep
Expand Down
6 changes: 1 addition & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ these on a quantum backend, whether a real device or simulator.
* **IBM CPLEX** may be [installed](https://qiskit.org/documentation/apidoc/qiskit.aqua.algorithms.minimum_eigen_solvers.cplex.html)
to allow use of the `ClassicalCPLEX` classical solver algorithm. `pip install cplex` may be used
as an alternative.
* **PyTorch**, may be installed either using command `pip install qiskit-aqua[torch]` to install the
* **PyTorch**, may be installed either using command `pip install torch` to install the
package or refer to PyTorch [getting started](https://pytorch.org/get-started/locally/). PyTorch
being installed will enable the neural networks `PyTorchDiscriminator` component to be used with
the QGAN algorithm.
Expand Down Expand Up @@ -161,10 +161,6 @@ Several, as listed below, are supported, and while logic to interface these prog
the chemistry module via the above pip installation, the dependent programs/libraries themselves need
to be installed separately.

Note: As `PySCF` can be installed via pip the installation of Qiskit (Aqua) will install PySCF
where it's supported (MacOS and Linux x86). For other platforms see the PySCF information as to
whether this might be possible manually.

1. [Gaussian 16&trade;](https://qiskit.org/documentation/apidoc/qiskit.chemistry.drivers.gaussiand.html), a commercial chemistry program
2. [PSI4](https://qiskit.org/documentation/apidoc/qiskit.chemistry.drivers.psi4d.html), a chemistry program that exposes a Python interface allowing for accessing internal objects
3. [PySCF](https://qiskit.org/documentation/apidoc/qiskit.chemistry.drivers.pyscfd.html), an open-source Python chemistry program
Expand Down
2 changes: 1 addition & 1 deletion qiskit/aqua/algorithms/algorithm_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def pop(self, key: object, default: Optional[object] = None) -> object:
def popitem(self) -> Tuple[object, object]:
raise TypeError("'popitem' invalid for this object.")

def update(self, *args, **kwargs) -> None:
def update(self, *args, **kwargs) -> None: # pylint: disable=arguments-differ,signature-differs
raise TypeError("'update' invalid for this object.")

def combine(self, result: 'AlgorithmResult') -> None:
Expand Down
14 changes: 9 additions & 5 deletions qiskit/aqua/algorithms/amplitude_amplifiers/grover.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,9 +246,15 @@ def construct_circuit(self, measurement=False):
Returns:
QuantumCircuit: the QuantumCircuit object for the constructed circuit
"""
if self._qc_amplitude_amplification is None:
self._qc_amplitude_amplification = \
QuantumCircuit() + self.qc_amplitude_amplification_iteration
if self._incremental:
if self._qc_amplitude_amplification is None:
self._qc_amplitude_amplification = \
QuantumCircuit() + self.qc_amplitude_amplification_iteration
else:
self._qc_amplitude_amplification = QuantumCircuit()
for _ in range(self._num_iterations):
self._qc_amplitude_amplification += self.qc_amplitude_amplification_iteration

qc = QuantumCircuit(self._oracle.variable_register, self._oracle.output_register)
qc.u3(pi, 0, pi, self._oracle.output_register) # x
qc.u2(0, pi, self._oracle.output_register) # h
Expand Down Expand Up @@ -291,8 +297,6 @@ def _try_target_num_iterations():

else:
self._qc_amplitude_amplification = QuantumCircuit()
for _ in range(self._num_iterations):
self._qc_amplitude_amplification += self.qc_amplitude_amplification_iteration
assignment, oracle_evaluation = self._run_with_existing_iterations()

self._ret['result'] = assignment
Expand Down
2 changes: 1 addition & 1 deletion qiskit/aqua/algorithms/classifiers/qsvm/_qsvm_binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ def run(self):

def load_model(self, file_path):
""" load model """
model_npz = np.load(file_path, allow_pickle=True)
model_npz = np.load(file_path, allow_pickle=True) # pylint: disable=unexpected-keyword-arg
model = {'alphas': model_npz['alphas'],
'bias': model_npz['bias'],
'support_vectors': model_npz['support_vectors'],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def run(self):

def load_model(self, file_path):
""" load model """
model_npz = np.load(file_path, allow_pickle=True)
model_npz = np.load(file_path, allow_pickle=True) # pylint: disable=unexpected-keyword-arg
for i in range(len(self.multiclass_classifier.estimators)):
self.multiclass_classifier.estimators.ret['svm']['alphas'] = \
model_npz['alphas_{}'.format(i)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def run(self):

def load_model(self, file_path):
""" load model """
model_npz = np.load(file_path, allow_pickle=True)
model_npz = np.load(file_path, allow_pickle=True) # pylint: disable=unexpected-keyword-arg
model = {'alphas': model_npz['alphas'],
'bias': model_npz['bias'],
'support_vectors': model_npz['support_vectors'],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def run(self):

def load_model(self, file_path):
""" load model """
model_npz = np.load(file_path, allow_pickle=True)
model_npz = np.load(file_path, allow_pickle=True) # pylint: disable=unexpected-keyword-arg
for i in range(len(self.multiclass_classifier.estimators)):
self.multiclass_classifier.estimators.ret['svm']['alphas'] = \
model_npz['alphas_{}'.format(i)]
Expand Down
2 changes: 1 addition & 1 deletion qiskit/aqua/algorithms/classifiers/vqc.py
Original file line number Diff line number Diff line change
Expand Up @@ -589,7 +589,7 @@ def class_to_label(self):

def load_model(self, file_path):
""" load model """
model_npz = np.load(file_path, allow_pickle=True)
model_npz = np.load(file_path, allow_pickle=True) # pylint: disable=unexpected-keyword-arg
self._ret['opt_params'] = model_npz['opt_params']

def save_model(self, file_path):
Expand Down
8 changes: 8 additions & 0 deletions qiskit/aqua/algorithms/distribution_learners/qgan.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,9 @@ def _store_params(self, e, d_loss, g_loss, rel_entr):
def train(self):
"""
Train the qGAN
Raises:
AquaError: Batch size bigger than the number of items in the truncated data set
"""
if self._snapshot_dir is not None:
with open(os.path.join(self._snapshot_dir, 'output.csv'), mode='w') as csv_file:
Expand All @@ -278,6 +281,11 @@ def train(self):
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()

if len(self._data) < self._batch_size:
raise AquaError(
'The batch size needs to be less than the '
'truncated data size of {}'.format(len(self._data)))

for e in range(self._num_epochs):
aqua_globals.random.shuffle(self._data)
index = 0
Expand Down
2 changes: 1 addition & 1 deletion qiskit/aqua/algorithms/factorizers/shor.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def __init__(self,
"""
Args:
N: The integer to be factored, has a min. value of 3.
a: A random integer that satisfies a < N and gcd(a, N) = 1, has a min. value of 2.
a: Any integer that satisfies 1 < a < N and gcd(a, N) = 1.
quantum_instance: Quantum Instance or Backend
Raises:
Expand Down
77 changes: 57 additions & 20 deletions qiskit/aqua/algorithms/minimum_eigen_solvers/vqe.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ def __init__(self,
self._max_evals_grouped = max_evals_grouped
self._circuit_sampler = None # type: Optional[CircuitSampler]
self._expectation = expectation
self._user_valid_expectation = self._expectation is not None
self._include_custom = include_custom
self._expect_op = None
self._operator = None
Expand Down Expand Up @@ -184,26 +185,29 @@ def operator(self, operator: Union[OperatorBase, LegacyBaseOperator]) -> None:
self._operator = operator
self._expect_op = None
self._check_operator_varform()
if self._expectation is None:
# Expectation was not passed by user, try to create one
if not self._user_valid_expectation:
self._try_set_expectation_value_from_factory()

def _try_set_expectation_value_from_factory(self):
if self.operator and self.quantum_instance:
self.expectation = ExpectationFactory.build(operator=self.operator,
backend=self.quantum_instance,
include_custom=self._include_custom)
def _try_set_expectation_value_from_factory(self) -> None:
if self.operator is not None and self.quantum_instance is not None:
self._set_expectation(ExpectationFactory.build(operator=self.operator,
backend=self.quantum_instance,
include_custom=self._include_custom))

def _set_expectation(self, exp: ExpectationBase) -> None:
self._expectation = exp
self._user_valid_expectation = False
self._expect_op = None

@QuantumAlgorithm.quantum_instance.setter
def quantum_instance(self, quantum_instance: Union[QuantumInstance, BaseBackend]) -> None:
""" set quantum_instance """
super(VQE, self.__class__).quantum_instance.__set__(self, quantum_instance)

if self._circuit_sampler is None:
self._circuit_sampler = CircuitSampler(self._quantum_instance)
else:
self._circuit_sampler.quantum_instance = self._quantum_instance

if self._expectation is None:
self._circuit_sampler = CircuitSampler(self._quantum_instance)
# Expectation was not passed by user, try to create one
if not self._user_valid_expectation:
self._try_set_expectation_value_from_factory()

@property
Expand All @@ -214,8 +218,8 @@ def expectation(self) -> ExpectationBase:

@expectation.setter
def expectation(self, exp: ExpectationBase) -> None:
self._expectation = exp
self._expect_op = None
self._set_expectation(exp)
self._user_valid_expectation = self._expectation is not None

@property
def aux_operators(self) -> Optional[List[Optional[OperatorBase]]]:
Expand Down Expand Up @@ -299,9 +303,9 @@ def print_settings(self):
ret += "===============================================================\n"
return ret

def construct_circuit(self,
parameter: Union[List[float], List[Parameter], np.ndarray]
) -> OperatorBase:
def construct_expectation(self,
parameter: Union[List[float], List[Parameter], np.ndarray]
) -> OperatorBase:
r"""
Generate the ansatz circuit and expectation value measurement, and return their
runnable composition.
Expand All @@ -328,14 +332,47 @@ def construct_circuit(self,
else:
wave_function = self.var_form.construct_circuit(parameter)

# If ExpectationValue was never created, create one now.
if not self.expectation:
# Expectation was never created, try to create one
if self._expectation is None:
self._try_set_expectation_value_from_factory()

# If setting the expectation failed, raise an Error:
if self._expectation is None:
raise AquaError('No expectation set and could not automatically set one, please '
'try explicitly setting an expectation or specify a backend so it '
'can be chosen automatically.')

observable_meas = self.expectation.convert(StateFn(self.operator, is_measurement=True))
ansatz_circuit_op = CircuitStateFn(wave_function)
return observable_meas.compose(ansatz_circuit_op).reduce()

def construct_circuit(self,
parameter: Union[List[float], List[Parameter], np.ndarray]
) -> List[QuantumCircuit]:
"""Return the circuits used to compute the expectation value.
Args:
parameter: Parameters for the ansatz circuit.
Returns:
A list of the circuits used to compute the expectation value.
"""
expect_op = self.construct_expectation(parameter).to_circuit_op()

circuits = []

# recursively extract circuits
def extract_circuits(op):
if isinstance(op, CircuitStateFn):
circuits.append(op.primitive)
elif isinstance(op, ListOp):
for op_i in op.oplist:
extract_circuits(op_i)

extract_circuits(expect_op)

return circuits

def supports_aux_operators(self) -> bool:
return True

Expand Down Expand Up @@ -436,7 +473,7 @@ def _energy_evaluation(self, parameters: Union[List[float], np.ndarray]
RuntimeError: If the variational form has no parameters.
"""
if not self._expect_op:
self._expect_op = self.construct_circuit(self._var_form_params)
self._expect_op = self.construct_expectation(self._var_form_params)

num_parameters = self.var_form.num_parameters
if self._var_form.num_parameters == 0:
Expand Down
Loading

0 comments on commit 3b7f27a

Please sign in to comment.