qiskit-community / qiskit-aqua Goto Github PK
View Code? Open in Web Editor NEWQuantum Algorithms & Applications (**DEPRECATED** since April 2021 - see readme for more info)
Home Page: https://qiskit.org/aqua
License: Apache License 2.0
Quantum Algorithms & Applications (**DEPRECATED** since April 2021 - see readme for more info)
Home Page: https://qiskit.org/aqua
License: Apache License 2.0
program crashed
return an empty list if no symmetry is found
act as expected behavior
This is mainly a refactoring issue, where the advantage is that by making SVM Kernels as pluggable entities, researchers and developers who want to extend Aqua will have an easy interface to swap kernels in AI.
Currently, kernels are hardcoded inside the SVM Q Kernel algorithm.
Make SVM Kernels pluggable entities, such as algorithms, optimizers, variational forms, Grover oracles, IQFTs and initial states.
N/A
The goal is to continue to promote the modular and extensible nature of Qiskit Aqua.
Known breaks:
cnx.py
, something wrong with composite gatez
and x
vectors rather than v
and w
, and do not modify the vector directly. or whereever use pauli string directly, since the order of pauli string is reversed for new Terra.get_cregs()
and get_qregs()
are became properties cregs
and qregs
custom.py
CustomInitialState is not able to unroll gates to basis gatesIssues in implementation order:
1 - chop only in one representation at a time
2 - make sure summand operator is not updated in additions
3 - set to None other representations when using add or chop functions in one representation
4 - initialize diagonal representation as sparse
As suggested by Jay in last application meeting. The target unitary could be described in terms of a quantum circuit. To be used as a subroutine in the context of a more complex algorithm, we need a QPE function that takes in a set of quantum registers which are already used by said algorithm and a circuit describing the unitary, and then returns a QPE circuit defined on input registers. Said circuit can then be appended to other circuits produced by the complex super-routine.
An agnostic way to do the controlled unitary is to control every gate in the argument circuit.
A stand alone, unitary-based QPE algorithm can call this core QPE function.
I think the best option for the phase register is to be initialized outside the QPE function - even if is not used outside QPE function - , and passed in as argument. In general I think it is good practice to initialize all quantum registers at beginning of given algorithm, so the most logical use of QPE function inside a more complex algorithm is to have all registers passed in as arguments.
An alternative way of having registers as arguments is to import them from the argument circuit - this is debatable I think.
The QPE core function should initialize a new quantum circuit with the registers passed as arguments, not just append a circuit to an argument circuit passed in.
In fact the circuit appending should be done outside the core QPE function, in the super-routine. The reason for this is that in some cases in the super-routine that uses QPE we need to invert the QPE circuit, so we need to have it as a separate object, to be fed to an eventual circuit.invert() method.
Newly-added checking for max number of circuits might crash the Operator since backend
sometimes is None
.
if isinstance(input_circuit, np.ndarray):
avg = self._eval_directly(input_circuit)
std_dev = 0.0
else:
if backend.startswith('local'):
self.MAX_CIRCUITS_PER_JOB = sys.maxsize
if "statevector" in backend:
execute_config['shots'] = 1
avg = self._eval_with_statevector(operator_mode, input_circuit, backend, execute_config)
std_dev = 0.0
else:
avg, std_dev = self._eval_multiple_shots(operator_mode, input_circuit, backend, execute_config, qjob_config)
Due to the fact that users might interest the scale of the quantum circuits they are running, it will be nice to summarize the circuits.
Print out the summary of submitted circuits in the DEBUG level.
We can get width
, size
, depth
from the to-be-submitted circuit objects.
And we can try to get those stats right after we submit jobs since we wait for results, it is a good place to summarize the circuits.
Feature request.
Since current operator support single representations, use convert
method results in error, it is safer to use to_matrix()
or to_paulis()
or to_grouped_paulis()
Translators of various problems to Ising currently having duplicated code in these files. Refactoring is needed to eliminate this code and better structure the modules accordingly.
as what the title indicates.
The GUI and internal code should contain the proxies and provider name and the resulting qconfig.py should look like:
config = {
'url': 'https://q-console-api.mybluemix.net/api',
'hub': 'ibm-q-internal',
'group': 'research',
'project': 'qlib-test'
'proxies': {
''urls': {
'http': 'http://1.2.3.4:5678',
'https': 'https://1.2.3.4:5678',
}
},
'provider_name': "ibmq",
'verify': True
}
The option 'adaptive' enables the use of a Nelder Mead algorithm which enables better optimization of high-dimensional problems. See: https://docs.scipy.org/doc/scipy/reference/optimize.minimize-neldermead.html#optimize-minimize-neldermead
Traceback (most recent call last):
File "/Applications/PyCharm Edu.app/Contents/helpers/pydev/pydevd.py", line 1556, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "/Applications/PyCharm Edu.app/Contents/helpers/pydev/pydevd.py", line 940, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/Applications/PyCharm Edu.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/Users/liup/quantum/qiskit-acqua/qiskit_acqua/ising/testgraphpartition.py", line 16, in <module>
qubitOp, offset = graphpartition.get_graphpartition_qubitops(w)
File "/Users/liup/quantum/qiskit-acqua/qiskit_acqua/ising/graphpartition.py", line 113, in get_graphpartition_qubitops
return Operator(paulis=pauli_list), shift
File "/Users/liup/quantum/qiskit-acqua/qiskit_acqua/operator.py", line 65, in __init__
self._simplify_paulis()
File "/Users/liup/quantum/qiskit-acqua/qiskit_acqua/operator.py", line 217, in _simplify_paulis
paulis[idy][0] += self._paulis[idx][0]
TypeError: 'tuple' object does not support item assignment
Note: paulis[idy][0] is a tuple.
You need to trigger the _simplify_paulis() method to trigger the bug, which is not easy.
To reproduce the bug, you can replace the get_maxcut_qubitops() method in maxcut.py as the following. The replacement does not make any logical sense but will help trigger the bug.
def get_maxcut_qubitops(weight_matrix):
"""Generate Hamiltonian for the maximum stableset in a graph.
Args:
weight_matrix (numpy.ndarray) : adjacency matrix.
Returns:
operator.Operator, float: operator for the Hamiltonian and a
constant shift for the obj function.
"""
num_nodes = len(weight_matrix)
pauli_list = []
shift = 0
for i in range(num_nodes):
for j in range(i):
if (weight_matrix[i,j] != 0):
wp = np.zeros(num_nodes)
vp = np.zeros(num_nodes)
vp[i] = 1
vp[j] = 1
pauli_list.append((-0.5, Pauli(vp, wp)))
# shift += 0.5
for i in range(num_nodes):
for j in range(num_nodes):
if i != j:
wp = np.zeros(num_nodes)
vp = np.zeros(num_nodes)
vp[i] = 1
vp[j] = 1
pauli_list.append((1, Pauli(vp, wp)))
# else:
# shift += 1
return Operator(paulis=pauli_list), shift
Change the order of bitstring to q_{n-1} ... q_{0} but now we had q_{0} ... q_{n-1}. Thus, we can align the bitstring to the measured counts.
If I do "from qiskit_aqua.parser import JSONSchema" it will complain
"ImportError: cannot import name 'JSONSchema'"
Open python REPL and input "from qiskit_aqua.parser import JSONSchema", it will complain "ImportError: cannot import name 'JSONSchema'"
Silently import the package
None.
The parameters
initial_c = 0.1
target_update = 2np.pi0.1
are actually hard-coded into the SPSA optimizer. It would be better to expose them as optimizer parameters and default them with the values currently hardcoded.
https://github.com/Qiskit/qiskit-acqua/blob/master/qiskit_acqua/utils/optimizers/spsa.py
Also, what is the difference between
QuantumAlgorithm.run()
and using
run_algorithm(algo_input,params)
I personally don't think and algorithm should be able to run with a method. I think it should contain be ran by passing an algorithm and a backend to run_program (see #153).
let operator overloads -
and -=
, the current version only supports +
and +=
On the other hand, support a method to apply a constant scale on the coefficient of an Operator.
I pass the value of the default kernel that i found on the aqua files that is the QSVM_Kernel_Estimator, but when i execute the run() method, i get the following error:
TypeError Traceback (most recent call last)
in
----> 1 result = svm.run()
~/anaconda3/envs/quantum/lib/python3.6/site-packages/qiskit_aqua/algorithms/many_sample/qsvm/qsvm_kernel.py in run(self)
143
144 def run(self):
--> 145 return self.instance.run()
146
147 @Property
~/anaconda3/envs/quantum/lib/python3.6/site-packages/qiskit_aqua/algorithms/many_sample/qsvm/qsvm_kernel_multiclass.py in run(self)
53 put the train, test, predict together
54 """
---> 55 self.train(self.training_dataset[0], self.training_dataset[1])
56 if self.test_dataset is not None:
57 self.test(self.test_dataset[0], self.test_dataset[1])
~/anaconda3/envs/quantum/lib/python3.6/site-packages/qiskit_aqua/algorithms/many_sample/qsvm/qsvm_kernel_multiclass.py in train(self, data, labels)
36
37 def train(self, data, labels):
---> 38 self.multiclass_classifier.train(data, labels)
39
40 def test(self, data, labels):
~/anaconda3/envs/quantum/lib/python3.6/site-packages/qiskit_aqua/algorithms/components/multiclass_extensions/allpairs.py in train(self, x, y)
65 for j in range(i + 1, n_classes):
66 if self.params is None:
---> 67 estimator = self.estimator_cls()
68 else:
69 estimator = self.estimator_cls(*self.params)
TypeError: init() missing 2 required positional arguments: 'feature_map' and 'qalgo'
I just want to know how to call the following method... Which parameters should be passed?
svm = get_algorithm_instance("QSVM.Kernel")
svm.random_seed = 10598
svm.setup_quantum_backend(backend='ibmq_20_tokyo')
feature_map = get_feature_map_instance('SecondOrderExpansion')
feature_map.init_args(num_qubits=20, depth=2, entanglement={0: [1]})
all_pairs_extension = get_multiclass_extension_instance('AllPairs')
all_pairs_extension.init_args(estimator_cls=QSVM_Kernel_Estimator) # THE PROBLEM IS HERE. WHAT ARE THE PARAMETERS AND VALUES THAT SHOULD BE PASSED?
svm.init_args(training_input, test_input, datapoints[0], feature_map, multiclass_extension=all_pairs_extension)
load_from_file method cannot load from files created by save_to_file method, it has an issue in loading complex numbers.
Value Error raised when attempting to run the stableset optimization script using ExactEigensolver or VQE as the solver algorithm. A TypeError is raised when QAOA is used as the solver algorithm. Speifically, this used the stableset.py script to construct the operator for the Ising problem (all of this is outlined here https://github.com/Qiskit/aqua-tutorials/blob/master/optimization/stableset.ipynb).
Run the following code in Python3
from qiskit_aqua import Operator, run_algorithm, get_algorithm_instance
from qiskit_aqua.input import get_input_instance
from qiskit_aqua.algorithms.classical.cplex import stableset
import numpy as np
import networkx as nx
G = nx.gnp_random_graph(10, 0.567658261253)
w = nx.to_numpy_matrix(G)
qubitOp, offset = stableset.get_stableset_qubitops(w)
algo_input = get_input_instance('EnergyInput')
algo_input.qubit_op = qubitOp
if 1==1:
algorithm_cfg = {
'name': 'ExactEigensolver',
}
params = {
'problem': {'name': 'ising'},
'algorithm': algorithm_cfg
}
result = run_algorithm(params,algo_input)
x = stableset.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('stable set objective:', result['energy'] + offset)
print('solution:', stableset.get_graph_solution(x))
print('solution objective and feasibility:', stableset.stableset_value(x, w))
if 1==1:
algorithm_cfg = {
'name': 'VQE',
'operator_mode': 'matrix'
}
optimizer_cfg = {
'name': 'L_BFGS_B',
'maxfun': 2000
}
var_form_cfg = {
'name': 'RYRZ',
'depth': 3,
'entanglement': 'linear'
}
params = {
'problem': {'name': 'ising'},
'algorithm': algorithm_cfg,
'optimizer': optimizer_cfg,
'variational_form': var_form_cfg,
'backend': {'name': 'local_statevector_simulator'}
}
result = run_algorithm(params,algo_input)
x = stableset.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('time:', result['eval_time'])
print('stable set objective:', result['energy'] + offset)
print('solution:', stableset.get_graph_solution(x))
print('solution objective and feasibility:', stableset.stableset_value(x, w))
This Value Error (note this is error is specific to when ExactEigensolver is used, because ExactEigensolver is run first. The same error does occur if VQE is used in place of ExactEigensolver)
/root/anaconda3/lib/python3.6/site-packages/sklearn/cross_validation.py:41: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.
"This module will be removed in 0.20.", DeprecationWarning)
Traceback (most recent call last):
File "mis_test.py", line 22, in
result = run_algorithm(params,algo_input)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/algomethods.py", line 83, in run_algorithm
algorithm.init_params(algo_params, algo_input)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/exacteigensolver/exacteigensolver.py", line 73, in init_params
self.init_args(algo_input.qubit_op, k, algo_input.aux_ops)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/exacteigensolver/exacteigensolver.py", line 88, in init_args
self._operator.convert('paulis', 'matrix')
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/operator.py", line 824, in convert
self._paulis_to_matrix()
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/operator.py", line 939, in _paulis_to_matrix
self._to_dia_matrix(mode='paulis')
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/operator.py", line 310, in _to_dia_matrix
dia_matrix += coeff * pauli.to_spmatrix().diagonal()
File "/root/anaconda3/lib/python3.6/site-packages/numpy/matrixlib/defmatrix.py", line 309, in mul
return N.dot(self, asmatrix(other))
ValueError: shapes (1,10) and (1,1024) not aligned: 10 (dim 1) != 1 (dim 0)
QAOA solve: another error encountered
In place of ExactEigensolver or VQE for algorithm_cfg, if we put in QAOA instead, we get a different error than the one observed for the other two algorithms.
/root/anaconda3/lib/python3.6/site-packages/sklearn/cross_validation.py:41: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.
"This module will be removed in 0.20.", DeprecationWarning)
capi_return is NULL
Call-back cb_calcfc_in__cobyla__user__routines failed.
Traceback (most recent call last):
File "mis_test.py", line 54, in
result = run_algorithm(params,algo_input)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/algomethods.py", line 84, in run_algorithm
value = algorithm.run()
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/vqe/vqe.py", line 236, in run
self._solve()
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/vqe/vqe.py", line 188, in _solve
opt_params, opt_val = self.find_minimum_eigenvalue()
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/vqe/vqe.py", line 307, in find_minimum_eigenvalue
variable_bounds=bounds, initial_point=initial_point)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/utils/optimizers/cobyla.py", line 80, in optimize
res = minimize(objective_function, initial_point, tol=self._tol, method="COBYLA", options=self._options)
File "/root/anaconda3/lib/python3.6/site-packages/scipy/optimize/_minimize.py", line 608, in minimize
return _minimize_cobyla(fun, x0, args, constraints, **options)
File "/root/anaconda3/lib/python3.6/site-packages/scipy/optimize/cobyla.py", line 252, in _minimize_cobyla
dinfo=info)
File "/root/anaconda3/lib/python3.6/site-packages/scipy/optimize/cobyla.py", line 242, in calcfc
f = fun(x, *args)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/vqe/vqe.py", line 254, in _energy_evaluation
input_circuit = self._var_form.construct_circuit(parameters)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/qaoa/varform.py", line 60, in construct_circuit
circuit += self._cost_operator.evolve(None, gamma, 'circuit', 1, quantum_registers=q)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/operator.py", line 1369, in evolve
slice_pauli_list, evo_time, num_time_slices, quantum_registers
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/operator.py", line 1185, in construct_evolution_circuit
qc.u1(lam, state_registers[top_XYZ_pauli_indices[pauli_idx]])
File "/root/anaconda3/lib/python3.6/site-packages/qiskit/extensions/standard/u1.py", line 54, in u1
return self._attach(U1Gate(theta, q, self))
File "/root/anaconda3/lib/python3.6/site-packages/qiskit/extensions/standard/u1.py", line 26, in init
super().init("u1", [theta], [qubit], circ)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit/_gate.py", line 35, in init
super().init(name, param, args, circuit)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit/_instruction.py", line 37, in init
self.param.append(Number(single_param))
File "/root/anaconda3/lib/python3.6/site-packages/sympy/core/numbers.py", line 547, in new
raise TypeError(msg % type(obj).name)
TypeError: expected str|int|long|float|Decimal|Number object but got 'matrix'
I would suggest implementing an error handling for the ValueError here, but I am not certain of how to solve the this specific problem. For the Qaoa algorithm error, I am not certain what why it is giving a TypeError in this specific case.
When doing a variational calculation, I would expect the energy predicted by the VQE to be greater than or equal to the actual ground state energy (variational principle).
I am attempting to do a variational calculation with the VQE example code in the ACQUA tutorials using the local_qasm_simulator. I have slightly modified the file to make input easier, but none of the functionality is changed. I am using a Hamiltonian with ground state energy 0.54, but received a VQE prediction of the energy as 0.12, which is clearly less than the ground state.
It is possible that I do not completely understand how is calculated in the simulator (I am relatively new to quantum computing) and that the behavior I have seen is not unexpected, but if so then how can this be claimed to be a variational calculation? I would imagine the error (if there is one) is in the calculation of the expectation value (in that is not actually directly calculated, as this would guarantee a higher value by the variational principle), but I cannot speculate any further than that.
I have attached the file containing the Hamiltonian I used (anharmonic_osc.txt) and my code (vqe_error.txt - just change the filename to .py). Within the vqe_error.txt file, I have included my output from when I received the error. All inputs were as assigned in vqe_error.txt. Running this file should reproduce the error with some probability, but it might be best to simply work with the outputs I received after running it (outputs are included at the bottom in a comment, including the optimal parameter values returned; running the file takes ~12.4 minutes).
anharmonic_osc.txt
vqe_error.txt
I am relatively new to quantum computing, so I might be misinterpreting this and it might not be an unexpected output. However, it is troubling that a variational calculation can potentially yield an answer below the actual ground state, since that defeats the purpose of the variational calculation.
Thank you for taking the time to help.
When running the unit tests everything fails upon collection of the tests since it's trying to access qiskit
modules which do not exist.
ModuleNotFoundError: No module named 'qiskit.wrapper.credentials'
pytest .
Smooth running unit tests.
It might possible have to do with the Qiskit version (I used pip3
for installation). Unit tests need to be updated.
we need to setup travis
Integrate the qubit tapering scheme in the UCCSD variational form, similar to what is already done for the two qubit reduction
Now eval method in the operator includes multiple steps, so intermediate might be useful for the users.
E.g., users want to get the cirucits for the evaluation.
It will be better we split the steps of eval into multiple methods and then users have higher flexible to do that.
We can split it into three steps:
With this enhancement, we create the potential to bundle the circuits of different parameters in wavefunction during the VQE.
E.g., in SPSA, we need to evaluate Operate against with theta+ and theta-. if we can bundle the circuits of theta+ and theta- together, we can submit them together, rather than run them separately.
Currently Aqua uses wrapper.compile()
in Terra. This function is a bit restrictive as is, because you can only choose to skip_transpiler
or go through the default transpiler flow.
We will update this function to take a PassManager argument (Issue #1083 in Terra).
When that is done, can we also update the compile of Aqua to expose this? The skip_transpiler
will then just be identical to passing an empty pass manager: pass_manager=PassManager()
.
As title
To make implementing grover's algorithm in code faster, there should be a simpler way to generate cnf's from a unstructured array and a list of target items.
The ideal end goal is for a black box function that outputs a cnf to use with acqua's grover implementation after taking in two parameters (a list to query, a list of targets to search for).
I plan for there to be several intermediate methods before fulfilling the final goal. For example, one key intermediate function would be to generate bitstring solutions and bitstring non-solutions from a list to query and a list of targets. The value of the bitstring converted to decimal would correspond to an index of the query list.
Also, another simpler function to implement that could serve as a stepping stone to the final goal would be to make a black box that takes in N, the size of the query list/database, and a list T of the target indices that are solutions, to output a cnf for acqua's grover algorithm
Feature request.
The first link of /docs/aqua_tutorials.rst refers to a closed repository. I think it should be rewritten to indicate that there are currently two repo of tutorials, an official one and one from the community.
ModuleNotFoundError: No module named 'qiskit_aqua.ising'
run 'from qiskit_aqua.ising import maxcut, tsp'
module imported successfully
Thank you!
The random circuit generator has been floating around qiskit in the form of a script. I encountered it in the Qiskit developer challenge.
I'd suggest adding such a random circuit generator to Aqua. It can be used for testing and for benchmarking. I prefer the first variant, since the depth is somewhat guaranteed. The parameter depth
in the latter variant is somewhat of a misnomer since the output circuit does not have the given depth.
Personally, I've been using it in my mapper project (related to the Developer Challenge) to see how well the mapper performs on "Random" circuits. As it turns out, random circuits as generated by this tool are quite different from the circuits for other quantum algorithms.
flake8 testing of https://github.com/Qiskit/aqua on Python 3.7.0
$ flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics
./qiskit_aqua/ising/stableset.py:63:73: F821 undefined name 't'
outfile.write('{} {} {}\n'.format(i + 1, j + 1, t))
^
1 F821 undefined name 't'
1
https://github.com/Qiskit/aqua/blob/master/qiskit_aqua/ising/stableset.py#L63
$ flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics
No errors.
A segmentation fault occurs for a specific input.
Create the following input file of aqua chemistry:
====================================================
&name
LiH excited states molecule experiment. Var for SWAPRZ with VQKE
&end
&driver
name=PYSCF
&end
&problem
name=energy
enable_substitutions=True
random_seed=50
&end
&pyscf
atom=H 0 0 -2.5; Be 0 0 0; H 0 0 2.5
unit=Angstrom
charge=0
spin=0
basis=sto3g
&end
&operator
name=hamiltonian
transformation=particle_hole
qubit_mapping=jordan_wigner
two_qubit_reduction=False
freeze_core=True
orbital_reduction=[]
max_workers=4
&end
&algorithm
name=VQE
operator_mode=matrix
initial_point=None
&end
&optimizer
name=COBYLA
maxiter=10000
&end
&variational_form
name=SWAPRZ
depth=1000
entanglement=full
entangler_map=None
&end
&initial_state
name=HartreeFock
qubit_mapping=jordan_wigner
two_qubit_reduction=False
&end
&backend
name=local_statevector_simulator
&end
====================================================
Then run:
qiskit_aqua_chemistry_cmd <file name>
The input cam from Julia Rice, but with other values of depth and maxIter. The bug occurs for these specific depth and maxIter (depth=1000, maxIter=10000). I haven't witnessed it for other values of these parameters.
Run without segmentation fault.
For the moment I only know that it happens inside COBYLA.optimize.
As title.
After #63 is merged, more setting can set now.
Please refer to https://github.com/Qiskit/qiskit-terra/blob/master/qiskit/wrapper/_wrapper.py#L298
New backend schema is here:
https://github.com/Qiskit/aqua/blob/master/qiskit_aqua/parser/input_schema.json#L32
For the iterative algorithm, like VQE, it submits the circuits to the backend multiple times; however, sometimes the local machine might lose internet connection or other reasons, and then the program is crashed.
This leads all intermediate results gone.
One aspect to resolve this issue is having a robust querying for the result from the backend.
Another one is generating the checkpoint for the iterative algorithm, and then users can resume that later.
I would like to work on the first one.
define any pauli-type feature map, like ZZ, XY, ZXX, etc.
Remove backends from params in run_algroithm
from qiskit_aqua import run_algorithm
from qiskit import IBMQ, Aer, ThirdPartyProvider
sat_cnf = """
c Example DIMACS 3-sat
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
"""
algo_params = {
"problem": { "name": "search" },
"algorithm": { "name": "Grover" },
"oracle": { "name": "SAT", "cnf": sat_cnf },
}
IBMQ.load_accounts()
backend = IBMQ.get_backend("qasm_simulator")
result = run_algorithm(algo_params, backend=backend)
print(result["result"])
backend = Aer.get_backend("qasm_simulator")
result = run_algorithm(algo_params, backend=backend)
print(result["result"])
third_party = ThirdPartyProvider("some_login_details")
backend = third_party.get_backend("qasm_simulator")
result = run_algorithm(algo_params, backend=backend)
print(result["result"])
Installation fails because qiskit specifies numpy >= 1.13 but qiskit-acqua and qiskit-acqua-chemistry specify numpy<1.15,>=1.13. Therefore, during installation, numpy==1.15 is installed creating an incompatibility with the requirements ffrom both acqua and acqua-chemistry.
Create a virtual environment with:
virtualenv venv -p /usr/bin/python3.6
Next, activate the virtual environment using:
source venv/bin/activate
Last, begin the installation with:
pip install qiskit qiskit-acqua qiskit-acqua-chemistry --no-cache-dir
I expect the installation to finish with numpy installed without any versioning issues.
Specify numpy<1.15,>=1.13 in qiskit, exactly the same as in qiskit-acqua and qiskit-acqua-chemistry.
We are having an extensive discussion with Rudy regarding versioning issues in #235. Additional relevant details may be found there.
instead of directly sending the requests to the HPC simulator or the qiskit simulator, we send them in parallel to the proxy, which will assmebly them into one job and send it to the simulator.
This is requested by Antonio.
In p_bfgs https://github.com/Qiskit/qiskit-acqua/blob/master/qiskit_acqua/utils/optimizers/p_bfgs.py, we run multiple optimizers in parallel (embarassing parallelism).
It turns out we can parallelize the internal of the optimizer, which would lead to much better performance. At each point x, the optimizer needs to evaluate f(x') at a neighbor x' and compute the gradient (f(x')-f(x))/(x'-x). In general, the optimizer needs to evaluate 2N neighbors where N stands for the dimension. The evaluation of the 2N neighbors can be parallelized since they do not depend on each other.
In theory, this leads to 2N times speedup. In practice, this leads to C speedup, where C stands for the number of cores.
In terms of the implementation, we should choose the simplest optimizer.
And we simply follow the parallelism style in p_bfgs because it is simple and allows the parallelization of both the compiling and the execution.
If instead we follow the qiskit interface for multiple circuits, it will complicate the coding since we will have to modify the eval() function to merge multiple circuits into one job. Besides, this does not support the parallelization of compiling for now.
Add configurability of eps
parameter for scipy based optimizers that support this i.e. CG, L_BFGS_B, SLSQP and TNC
Ground state energy evaluation with VQE succeeds with statevector_simulator backend but with qasm_simulator evaluates to 0 once and then terminates.
import numpy as np
from qiskit.tools.qi.pauli import Pauli
# lib from Qiskit AQUA Chemistry
from qiskit_aqua_chemistry import FermionicOperator
from qiskit_aqua.operator import Operator
from qiskit_aqua import (get_algorithm_instance, get_optimizer_instance, get_variational_form_instance)
from qiskit_aqua.algorithms.components.initial_states.hartree_fock import HartreeFock
# lib for driver
from qiskit_aqua_chemistry.drivers import ConfigurationManager
from collections import OrderedDict
# using driver to get fermionic Hamiltonian
# PySCF example
cfg_mgr = ConfigurationManager()
pyscf_cfg = OrderedDict([('atom', 'H .0 .0 .0; H .0 .0 0.735'),
('unit', 'Angstrom'), ('charge', 0), ('spin', 0), ('basis', 'sto3g')])
section = {}
section['properties'] = pyscf_cfg
driver = cfg_mgr.get_driver_instance('PYSCF')
molecule = driver.run(section)
n_electrons = 2
# print(molecule._nuclear_repulsion_energy)
n_qubits = molecule._one_body_integrals.shape[0]
# print(molecule._one_body_integrals)
# get fermionic operator and mapping to qubit operator
ferOp = FermionicOperator(h1=molecule._one_body_integrals, h2=molecule._two_body_integrals)
qubitOp = ferOp.mapping(map_type='JORDAN_WIGNER', threshold=0.00000001)
# print(qubitOp)
qubitOp.convert('paulis','matrix')
qubitOp.chop(10**-10)
# setup VQE
# setup optimizer, use L_BFGS_B optimizer for example
lbfgs = get_optimizer_instance('L_BFGS_B')
lbfgs.set_options(maxfun=1000, factr=10, iprint=10)
# setup variation form generator (generate trial circuits for VQE)
initial_hf = HartreeFock()
initial_hf.init_args(num_qubits=n_qubits, num_orbitals=n_qubits,
qubit_mapping='jordan_wigner', two_qubit_reduction=False, num_particles= n_electrons)
var_form = get_variational_form_instance('UCCSD')
var_form.init_args(num_qubits=n_qubits, num_orbitals=n_qubits,
num_particles=n_electrons, depth=1, initial_state=initial_hf, qubit_mapping='jordan_wigner')
number_amplitudes = len(var_form._single_excitations)+ len(var_form._double_excitations)
amplitudes_0 = np.ndarray(shape=(number_amplitudes,), dtype=float, order='F')
for i in range(len(amplitudes_0)):
amplitudes_0[i] = 0.000001
# setup VQE with operator, variation form, and optimzer
vqe_algorithm = get_algorithm_instance('VQE')
backend_name = 'qasm_simulator'
vqe_algorithm.setup_quantum_backend(backend=backend_name, skip_transpiler=True)
vqe_algorithm.init_args(qubitOp, 'matrix', var_form, lbfgs, opt_init_point=amplitudes_0)
results = vqe_algorithm.run()
results['eigvals'][0] = results['eigvals'][0] + molecule._nuclear_repulsion_energy
print("Minimum value: {}".format(results['eigvals'][0].real))
print("Parameters: {}".format(results['opt_params']))
same as statevector_simulator
Since terra changes the order of Pauli, we might need to address how cplex_ising to handle the Pauli label.
I made one version that works for the newest Terra but maybe there is a better to do that.
We should take into account that one cannot stack more than a certain number of circuits on a single job under the "paulis" and "grouped_paulis" mode in the eval method for Operator class, both with finite number of shots and with the statevector simulator.
Modifying the MaxCut tutorial to have larger dimension, N=10, results in different answers for the VQE and ExactDiagonal solvers.
For
w = array([[ 0., 8., 0., 0., 9., 0., -8., 0., 0., -4.],
[ 8., 0., 0., 0., 0., 0., -5., 0., 5., 9.],
[ 0., 0., 0., -8., 0., 0., -8., 0., 0., 0.],
[ 0., 0., -8., 0., 0., 0., 0., 6., -8., 0.],
[ 9., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[-8., -5., -8., 0., 0., 0., 0., 0., 0., -3.],
[ 0., 0., 0., 6., 0., 0., 0., 0., -2., 0.],
[ 0., 5., 0., -8., 0., 0., 0., -2., 0., 0.],
[-4., 9., 0., 0., 0., 0., -3., 0., 0., 0.]])
I get ExactEigenSolver:
energy: -34.5
maxcut objective: -30.0
solution: [0. 1. 0. 0. 1. 1. 0. 1. 0. 0.]
solution objective: 30.0
where as VQE gives:
energy: -19.499999887119802
time: 638.5913169384003
maxcut objective: -14.999999887119802
solution: [1. 1. 1. 1. 0. 1. 1. 0. 1. 0.]
solution objective: 15.0
Try tutorial with above graph.
Wanted to make a slide highlighting this feature
OSX, Py36, latest Acqua
In general, I'm struggling to understand the separation of params, and algo_input
I don't like that some algorithms don't have an algo_input
. Why can't the params be part of the algorithm?
run_algorithm(params,algo_input)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.