rigetti / grove Goto Github PK
View Code? Open in Web Editor NEWQuantum algorithms built using pyQuil.
Home Page: http://rigetti.com/forest
License: Apache License 2.0
Quantum algorithms built using pyQuil.
Home Page: http://rigetti.com/forest
License: Apache License 2.0
Current test coverage is fairly low
----------- coverage: platform linux, python 3.6.1-final-0 -----------
Name Stmts Miss Cover
--------------------------------------------------------------------
grove/__init__.py 1 0 100%
grove/amplification/__init__.py 0 0 100%
grove/amplification/amplification.py 70 3 96%
grove/amplification/grover.py 41 41 0%
grove/arbitrary_state/__init__.py 0 0 100%
grove/arbitrary_state/arbitrary_state.py 95 45 53%
grove/arbitrary_state/unitary_operator.py 42 17 60%
grove/bernstein_vazirani/__init__.py 0 0 100%
grove/bernstein_vazirani/bernstein_vazirani.py 57 49 14%
grove/deutsch_jozsa/__init__.py 0 0 100%
grove/deutsch_jozsa/deutsch_jozsa.py 72 62 14%
grove/fermion_transforms/__init__.py 0 0 100%
grove/fermion_transforms/bktransform.py 38 6 84%
grove/fermion_transforms/fenwick_tree.py 52 0 100%
grove/fermion_transforms/jwtransform.py 24 0 100%
grove/phaseestimation/__init__.py 0 0 100%
grove/phaseestimation/phase_estimation.py 45 45 0%
grove/pyqaoa/__init__.py 1 0 100%
grove/pyqaoa/maxcut_qaoa.py 39 9 77%
grove/pyqaoa/numpartition_qaoa.py 30 30 0%
grove/pyqaoa/qaoa.py 113 17 85%
grove/pyqaoa/utils.py 16 0 100%
grove/pyvqe/__init__.py 0 0 100%
grove/pyvqe/vqe.py 128 30 77%
grove/qft/__init__.py 0 0 100%
grove/qft/fourier.py 34 3 91%
grove/simon/__init__.py 0 0 100%
grove/simon/simon.py 158 102 35%
grove/teleport/__init__.py 0 0 100%
grove/teleport/teleportation.py 27 27 0%
--------------------------------------------------------------------
TOTAL 1083 486 55%
@ncrubin @willzeng what are the low hanging fruits and dangerzones. I.e. what should be addressed first?
Right now both VQE and QAOA return and use parametric program objects from pyquil. These objects are used as they are intended to be efficient templates for variational quantum programs.
That said, the parametric.py library is still very experimental. This means that it can be pretty unintuitive to use and still has several bugs and strange edge cases.
Due to this, we should remove the dependency of pyqve and pyqaoa on these objects until they are more stable. In the meantime they can be replaced with basic python functions that return pyQuil programs.
@jotterbach Is going to start taking a look at this.
Working on Deutsch-Jozsa. I want to find the wavefunction of our system after undergoing the oracle.
def dj(oracle, qubits, ancilla):
p = pq.Program()
p.inst(X(ancilla), H(ancilla))
p.inst([H(qubit) for qubit in qubits])
p += oracle
print qvm.wavefunction(p)[0] #Displaying the wavefunction.
p.inst([H(qubit) for qubit in qubits])
return p
deutsch_program = pq.Program()
qubits = [deutsch_program.alloc() for _ in range(n)]
ancilla = deutsch_program.alloc()
unitary_funct = unitary_function(mappings) #Mappings list is initialised before.
oracle = oracle_function(unitary_funct, qubits, ancilla)
deutsch_program += dj(oracle, qubits, ancilla) #Changed function to dj()
deutsch_program.out()
This is producing RuntimeError: Can't get the index of an unassigned qubit.
How can I get the wavefunction after the oracle?
We are doing some sanity checks to see how phase estimation works and we cannot reconcile it
with our expectations: the value of the estimation just does not match the correct value. Here's a minimal working example.
Furthermore, if you change the phase to pi/8
, the phase estimation fails all together, dropping ValueError: The wavefunction is not normalized
.
The new complex dependencies (qutip+cython+cvxpy) have made the semaphore setup very complicated and broken the grove docs build.
right now it requires any version of pyquil. As pyquil is evolving quickly, the setup.py
for grove should have an explicit dependency on a version of pyquil.
The example max cut optimization problem given at https://github.com/rigetticomputing/grove/tree/master/grove/pyqaoa gives this error when I run it:
Traceback (most recent call last):
File "pyquil_optimization_test.py", line 24, in
for state_index in range(2**inst.n_qubits):
AttributeError: 'QAOA' object has no attribute 'n_qubits'
This makes sense because the instance used in qaoa.py is actually qubits, not n_qubits.
Then I would get this error after that correction:
Traceback (most recent call last):
File "pyquil_optimization_test.py", line 24, in
for state_index in range(2**inst.qubits):
TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'list'
If I am not mistaken, the example under the directory pyqaoa should have this modification:
for state_index in range(2**len(inst.qubits)):
print inst.states[state_index], np.conj(wf[state_index])*wf[state_index]
While running some analytics on the Shor's algorithm implementation, I discovered that the QFT implementation crashes when working with large qubit ranges due to recursion depth limits. This may mean that we should go through our algorithms and look where recursion can be replaced by iterative processes, in order to avoid these kinds of bugs as we scale in the future.
@ampolloreno and @vtomole
Please fix the failing build. Looks like it was induced by your PR
running tox on python 3.6 leads to errors due to missing hasability of pyQuil programs in the latest version of pyQuil:
x_oracle = (<pyquil.quil.Program object at 0x10a839a90>, <Qubit 10A839BE0>)
def test_x_oracle_one_grover(x_oracle):
"""Testing that Grover's algorithm with an oracle that applies an X gate to the query bit works,
with one iteration."""
x_oracle_grover = Program()
qubit0 = x_oracle_grover.alloc()
qubits = [qubit0]
oracle, query_qubit = x_oracle
with patch("pyquil.quilbase.InstructionGroup.alloc") as mock_alloc:
mock_alloc.return_value = qubit0
generated_x_oracle_grover = Grover().oracle_grover(oracle, qubits, 1)
# First we put the input into uniform superposition.
x_oracle_grover.inst(H(qubit0))
# Now an oracle is applied.
x_oracle_grover.inst(X(query_qubit))
# We now apply the diffusion operator.
x_oracle_grover.inst(H(qubit0))
x_oracle_grover.inst(Z(qubit0))
x_oracle_grover.inst(H(qubit0))
> synthesize_programs(generated_x_oracle_grover, x_oracle_grover)
grove/tests/amplification/test_grover.py:60:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
progs = (<pyquil.quil.Program object at 0x10a85ebe0>, <pyquil.quil.Program object at 0x10a8306a0>), get_allocated_qubits = <function synthesize_programs.<locals>.get_allocated_qubits at 0x10a83a378>
qubits_to_progs = {<Qubit 10A839BE0>: [<pyquil.quil.Program object at 0x10a85ebe0>, <pyquil.quil.Program object at 0x10a85ebe0>, <pyquil...object at 0x10a85ebe0>, <pyquil.quil.Program object at 0x10a85ebe0>, <pyquil.quil.Program object at 0x10a8306a0>, ...]}
prog = <pyquil.quil.Program object at 0x10a8306a0>
def synthesize_programs(*progs):
"""Synthesizes programs together, paying attention to shared qubits. This breaks if synthesize
is called after, very fragile.
:param progs: List of Programs.
:return: None
:rtype: NoneType"""
def get_allocated_qubits(*progs):
qubits_to_progs = {}
for prog in progs:
for inst in prog:
if inst[0] == ACTION_INSTANTIATE_QUBIT:
qubits_to_progs[inst[1]] = [prog]
return qubits_to_progs
qubits_to_progs = get_allocated_qubits(*progs)
for prog in progs:
for inst in prog:
if isinstance(inst[1], Gate):
for arg in inst[1].arguments:
if isinstance(arg, Qubit):
qubits_to_progs[arg].append(prog)
equiv_classes = list(qubits_to_progs.values())
repeat = True
while repeat:
repeat = False
for i, equiv_class in enumerate(equiv_classes):
for j, other_equiv_class in enumerate(equiv_classes):
if j <= i:
continue
> if set(equiv_class).intersection(set(other_equiv_class)):
E TypeError: unhashable type: 'Program'
grove/tests/utils/utils_for_testing.py:78: TypeError
____________________________________________________________________________________________________ test_x_oracle_two_grover _____________________________________________________________________________________________________
x_oracle = (<pyquil.quil.Program object at 0x108637d30>, <Qubit 108637BE0>)
def test_x_oracle_two_grover(x_oracle):
"""Testing that Grover's algorithm with an oracle that applies an X gate to the query bit works,
with two iterations."""
x_oracle_grover = Program()
qubit0 = x_oracle_grover.alloc()
qubits = [qubit0]
oracle, query_qubit = x_oracle
with patch("pyquil.quilbase.InstructionGroup.alloc") as mock_alloc:
mock_alloc.return_value = qubit0
generated_x_oracle_grover = Grover().oracle_grover(oracle, qubits, 2)
# First we put the input into uniform superposition.
x_oracle_grover.inst(H(qubit0))
# Two iterations.
for _ in range(2):
# Now an oracle is applied.
x_oracle_grover.inst(X(query_qubit))
# We apply the diffusion operator.
x_oracle_grover.inst(H(qubit0))
x_oracle_grover.inst(Z(qubit0))
x_oracle_grover.inst(H(qubit0))
> synthesize_programs(generated_x_oracle_grover, x_oracle_grover)
grove/tests/amplification/test_grover.py:84:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
progs = (<pyquil.quil.Program object at 0x10a89ff60>, <pyquil.quil.Program object at 0x10a818b70>), get_allocated_qubits = <function synthesize_programs.<locals>.get_allocated_qubits at 0x10a87cb70>
qubits_to_progs = {<Qubit 108637BE0>: [<pyquil.quil.Program object at 0x10a89ff60>, <pyquil.quil.Program object at 0x10a89ff60>, <pyquil...object at 0x10a89ff60>, <pyquil.quil.Program object at 0x10a89ff60>, <pyquil.quil.Program object at 0x10a89ff60>, ...]}
prog = <pyquil.quil.Program object at 0x10a818b70>
def synthesize_programs(*progs):
"""Synthesizes programs together, paying attention to shared qubits. This breaks if synthesize
is called after, very fragile.
:param progs: List of Programs.
:return: None
:rtype: NoneType"""
def get_allocated_qubits(*progs):
qubits_to_progs = {}
for prog in progs:
for inst in prog:
if inst[0] == ACTION_INSTANTIATE_QUBIT:
qubits_to_progs[inst[1]] = [prog]
return qubits_to_progs
qubits_to_progs = get_allocated_qubits(*progs)
for prog in progs:
for inst in prog:
if isinstance(inst[1], Gate):
for arg in inst[1].arguments:
if isinstance(arg, Qubit):
qubits_to_progs[arg].append(prog)
equiv_classes = list(qubits_to_progs.values())
repeat = True
while repeat:
repeat = False
for i, equiv_class in enumerate(equiv_classes):
for j, other_equiv_class in enumerate(equiv_classes):
if j <= i:
continue
> if set(equiv_class).intersection(set(other_equiv_class)):
E TypeError: unhashable type: 'Program'
grove/tests/utils/utils_for_testing.py:78: TypeError
_______________________________________________________________________________________________________ test_optimal_grover _______________________________________________________________________________________________________
x_oracle = (<pyquil.quil.Program object at 0x10a8b1208>, <Qubit 10A8B1278>)
def test_optimal_grover(x_oracle):
"""Testing that Grover's algorithm with an oracle that applies an X gate to the query bit works,
and defaults to the optimal number of iterations."""
grover_precircuit = Program()
qubit0 = grover_precircuit.alloc()
qubits = [qubit0]
oracle, query_qubit = x_oracle
with patch("pyquil.quilbase.InstructionGroup.alloc") as mock_alloc:
mock_alloc.return_value = qubit0
generated_one_iter_grover = Grover().oracle_grover(oracle, qubits)
# First we put the input into uniform superposition.
grover_precircuit.inst(H(qubit0))
# We only do one iteration, which is the result of rounding pi * sqrt(N)/4
iter = Program()
# An oracle is applied.
iter.inst(X(query_qubit))
# We now apply the diffusion operator.
iter.inst(H(qubit0))
iter.inst(Z(qubit0))
iter.inst(H(qubit0))
one_iter_grover = grover_precircuit + iter
> synthesize_programs(generated_one_iter_grover, one_iter_grover)
grove/tests/amplification/test_grover.py:110:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
progs = (<pyquil.quil.Program object at 0x10a89a780>, <pyquil.quil.Program object at 0x10a89a208>), get_allocated_qubits = <function synthesize_programs.<locals>.get_allocated_qubits at 0x10a87ca60>
qubits_to_progs = {<Qubit 10A8B1278>: [<pyquil.quil.Program object at 0x10a89a780>, <pyquil.quil.Program object at 0x10a89a780>, <pyquil...object at 0x10a89a780>, <pyquil.quil.Program object at 0x10a89a780>, <pyquil.quil.Program object at 0x10a89a208>, ...]}
prog = <pyquil.quil.Program object at 0x10a89a208>
def synthesize_programs(*progs):
"""Synthesizes programs together, paying attention to shared qubits. This breaks if synthesize
is called after, very fragile.
:param progs: List of Programs.
:return: None
:rtype: NoneType"""
def get_allocated_qubits(*progs):
qubits_to_progs = {}
for prog in progs:
for inst in prog:
if inst[0] == ACTION_INSTANTIATE_QUBIT:
qubits_to_progs[inst[1]] = [prog]
return qubits_to_progs
qubits_to_progs = get_allocated_qubits(*progs)
for prog in progs:
for inst in prog:
if isinstance(inst[1], Gate):
for arg in inst[1].arguments:
if isinstance(arg, Qubit):
qubits_to_progs[arg].append(prog)
equiv_classes = list(qubits_to_progs.values())
repeat = True
while repeat:
repeat = False
for i, equiv_class in enumerate(equiv_classes):
for j, other_equiv_class in enumerate(equiv_classes):
if j <= i:
continue
> if set(equiv_class).intersection(set(other_equiv_class)):
E TypeError: unhashable type: 'Program'
grove/tests/utils/utils_for_testing.py:78: TypeError
========================================================================================= 3 failed, 82 passed, 10 skipped in 4.29 seconds =========================================================================================
ERROR: InvocationError: '/Users/johannes/code/grove/.tox/py36/bin/py.test --cov=grove'
_____________________________________________________________________________________________________________ summary _____________________________________________________________________________________________________________
ERROR: py36: commands failed
The util
folder is empty- I think we should just delete it.
So that pip install -e .
will fully install grove and all of its dependencies
The inverse QFT is used in the phase estimation algorithm to encode the kicked phase into the bitstring. What phase convention did we choose so the QFT is correct?
https://readthedocs.org/projects/grove-docs/builds/6091190/
Someone may have already addressed this but copying here in case it got missed.
In grover.py, the line
sampled_bitstring = cxn.run_and_measure(self.grover_circuit, self.qubits)[0]
works ok when cxn is a SyncConnection, but when cxn in a JobConnection I get
TypeError: 'JobResult' object does not support indexing
It worked when I replaced it with this code
import pyquil.api as api # added for type check
if type(cxn) is api.SyncConnection:
sampled_bitstring = cxn.run_and_measure(self.grover_circuit, self.qubits)[0]
elif type(cxn) is api.JobConnection:
res=cxn.run_and_measure(self.grover_circuit, self.qubits)
import time
while not res.is_done():
time.sleep(1)
sampled_bitstring=res.decode()[0]
else:
assert False, "connection object of unidentified type"
Either that, or perhaps the SyncConnection and JobConnection objects should be redesigned to have the same structure to avoid having to check the type of connection (a requirement that likely will not scale well)
-As an aside, both Sync and Job Connections can at most execute Grover's algorithm for a 7 bit number. When I try 8 bit string e.g. '10001000', I get a
HTTPError: 413 Client Error: Request Entity Too Large for url: https://job.rigetti.com/beta/job
Why doesn't the Job connection (with 25 qubits) have a higher capacity than the sync (with 16)?
When I try to run
from grove.amplification.oracles import basis_selector_oracle
it returns the error:
from grove.utils.utility_programs import ControlledProgramBuilder
ImportError: No module named utils.utility_programs
After downloading the file from https://pypi.python.org/pypi/quantum-grove/1.2.0 , i find that there is no utils folders inside the grove folder.
In each page of documentation for the modules, at the bottom of the page (here, for example: http://grove-docs.readthedocs.io/en/latest/qaoa.html#source-code-docs), only the headings for the Source Code Docs show up, but no code/documentation.
The recent changes (I) made to pyquil change the way we handle coefficients- namely everything is a complex
now. This broke the tests that check for string
equality.
In both requirements.txt and setup.py a more specific version of PyQuil should be used other than >=1.0.0
Grove QAOA should work on both the QVM and the QPU. This appears to largely be the case, but the code was written with the QVM in mind: function arguments/docstrings state qvm
, and the probabilities
method calls qvm.wavefunction
.
While building tests for shor.py, I realized that there are a few issues with the testing infrastructure in grove.
test_maxcut.py
:from grove.pyqaoa.maxcut_qaoa import maxcut_qaoa
from grove.pyqaoa.qaoa import QAOA
from grove.pyqaoa.utils import compare_progs
...
However, these imports are grabbing the module from the pip installed grove dependency, rather than the actual current pyqaoa
file one directory above. This means that in order to accurately test the newly updated pyqaoa
module, one needs to install their grove directory with pip install -e .
, which may have broken changes due to updates you have made.
Additionally, that means if you try to create a new module with tests, those tests won't work until you actually update grove with the new module, which doesn't make too much sense from a test-first perspective. I think that these grove imports should instead use relative imports, which will allow tests to use the currently-defined grove files on your local machine without having to install the entire library using pip.
factor()
function in shor.py
simply returns a final answer after multiple calls to Forest). Pytest provides some tools to ignore certain tests. I think it would be useful if we had tests that were run conditional on whether or not the testing machine could make a valid connection to the Forest service.Hello, I saw the example of the binary search using Grover, however, I am interested in search decimal values from a database. Let's say. I want to search for '20' feet from a database which has data from 0-100 feet values. Could you please enlighten me about how to do that? Could you please let me know if converting the decimal to binary would be appropriate?
Another question is the time of Grover search computation, could you let me know how can I find the time for the search?
Thanks in advance and have a great day!
In QAOA, by default the driver is an X acting on all qubits; Of course it is supposed to be on the specified qubits. But instead, in the source code grove/pyqaoa/qaoa.py, line 88 and 89:
for i in range(self.n_qubits):
ref_prog.inst(H(i))
So it is applying X to the range of (0,n_qubits), instead of the qubits desired.
Similar to this ticket: rigetti/pyquil#227 we'd like to drop Python 2 support and remove any deprecated code in the upcoming major release of Grove (which is yet to be scheduled).
It would be nice to match the API of Grover's to that of Simon's and Bernstein-Vazirani.
The description of the oracle U_w
is wrong.
def amplify(A, A_inv, U_w, qubits, num_iter, init=True):
"""
[...]
:param U_w: an oracle maps any basis vector to either |0> or |1>
[...]
"""
There are also a few typos.
To do once #104 is merged.
The description of the oracle U_w
is wrong.
def amplify(A, A_inv, U_w, qubits, num_iter, init=True):
"""
[...]
:param U_w: an oracle maps any basis vector to either |0> or |1>
[...]
"""
There are also a few typos.
I am trying to install quantum-grove through Anaconda and also using "pip install -e " after downloading the grove-master zip file. But there is error every time. I have attached the screenshot what it is saying every time. I have already installed pyquil-master using "pip install -e", no issue occurred at that time.
Simon's has a nice .ipynb example and non-empty documentation on the readthedocs, Grover's should as well.
I think it was broken during the refactor into the amplification module, but here is a traceback trying to run it from the command line:
python grover.py 1
Traceback (most recent call last):
File "grover.py", line 90, in <module>
oracle = basis_selector_oracle(target, qubits)
File "grover.py", line 72, in basis_selector_oracle
np.array([[1, 0], [0, -1]]), 'Z')
File "/home/ampolloreno/repos/grove/grove/amplification/amplification.py", line 93, in n_qubit_control
assert len(controls) > 0, "The control qubits list must not be empty"
AssertionError: The control qubits list must not be empty
Improve the documentation of optional arguments and required arguments with examples. Also correct the disp_fun doc string (currently it says the variable should be a boolean when it should be a function).
Right now MaxCut is missing both:
The following example breaks Deutsch-Josza for two-qubit case with error:
Traceback (most recent call last):
File "./deutsch-josza.py", line 15, in <module>
is_constant = dj.is_constant(qvm,qubit_bitmap)
File "/Users/ruslan/anaconda3/envs/pyquil/lib/python3.6/site-packages/grove/deutsch_jozsa/deutsch_jozsa.py", line 59, in is_constant
constant = all([bit == 0 for bit in bitstring])
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Code producing the error:
import numpy as np
import pyquil.api as api
import pyquil.quil as pq
from pyquil.gates import X, H, CNOT
from grove.deutsch_jozsa.deutsch_jozsa import DeutschJosza, ORACLE_GATE_NAME
qvm = api.QVMConnection()
qubit_bitmap = {"00": "1", "01" : "1", "10" : "1", "11": "1"}
dj = DeutschJosza()
is_constant = dj.is_constant(qvm,qubit_bitmap)
print(is_constant)
Is fixable by changing the offending line to:
constant = all([bit == 0 for bit in bitstring][0])
but I'm not sure if that's the most elegant solution.
You might also want to consider adding it to tests (they lack working 2-qubit mapping examples, only the ones that are invalid).
See also PR #146
http://grove-docs.readthedocs.io/en/latest/vqe.html reads:
from grove import VQE
from scipy.optimize import minimize
import numpy as np
vqe_inst = vqe(minimizer=minimize,
minimizer_kwargs={'method': 'nelder-mead'})
It should read:
from grove import VQE
from scipy.optimize import minimize
import numpy as np
vqe_inst = vqe(minimizer=minimize,
minimizer_kwargs={'method': 'nelder-mead'})
python3's syntax changes create a couple of problems with grove. Here it's just parenthesis in the print
function
python qaoa_rkdemo.py Traceback (most recent call last): File "qaoa_rkdemo.py", line 2, in <module> from grove.pyqaoa.maxcut_qaoa import maxcut_qaoa File "/Users/Ryan/anaconda3/lib/python3.6/site-packages/grove/__init__.py", line 18, in <module> from grove.pyvqe.vqe import VQE File "/Users/Ryan/anaconda3/lib/python3.6/site-packages/grove/pyvqe/vqe.py", line 126 models will be ineffective""" ^ SyntaxError: Missing parentheses in call to 'print'
I ran the following script:
import pyquil.api as api
qvm = api.QVMConnection()
import numpy as np
from grove.alpha.phaseestimation.phase_estimation import phase_estimation
precision = 18
for p in range(10):
phase = 1/(2**p)
phase_factor = np.exp(1.0j * 2 * np.pi * phase)
U = np.array([[phase_factor, 0],
[0, -1*phase_factor]])
p = phase_estimation(U, precision)
output = qvm.run(p, range(precision))
wavefunction = qvm.wavefunction(p)
print("~~~~~~~~~~~~~~~~~~~")
print(phase)
print(output)
print(wavefunction)
print("~~~~~~~~~~~~~~~~~~~")
For phase = 0.25, it outputs all zeros. After 0.125, it throws an error. Here is the output:
``~~~~~~~~~~~~~~~~~~~
1.0
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
(1+0j)|0000000000000000000>
0.5
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]]
(1+0j)|0100000000000000000>
0.25
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
(1+0j)|0110000000000000000>
0.125
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]]
(1+0j)|0111000000000000000>
Traceback (most recent call last):
File "C:\Users\Josh\Desktop\phaseTest.py", line 21, in <module>
wavefunction = qvm.wavefunction(p)
File "C:\Users\Josh\AppData\Local\Programs\Python\Python36\lib\site-packages\pyquil\api\qvm.py", line 270, in wavefunction
return Wavefunction.from_bit_packed_string(response.content, classical_addresses)
File "C:\Users\Josh\AppData\Local\Programs\Python\Python36\lib\site-packages\pyquil\wavefunction.py", line 93, in from_bit_packed_string
return Wavefunction(wf, mem)
File "C:\Users\Josh\AppData\Local\Programs\Python\Python36\lib\site-packages\pyquil\wavefunction.py", line 41, in __init__
"The probabilities sum to {} instead of 1".format(sumprob))
ValueError: The wavefunction is not normalized. The probabilities sum to 2.759271215133724e-32 instead of 1
estimate routines rotate program the user passes with the post rotations dictated by the Pauli operators being measured. This should not happen.
The solution to the maxcut problem of ring is not unique,so I want to add an initial_beta and initial_gamma which I guess will give me the optimal angles near the given initial angles. Thus, I add initial angles to the qaoa_maxcut
inst = maxcut_qaoa(graph=square_ring, steps=steps, initial_beta=1.2, initial_gamma=1.2 )
Then error happens as below
When using the function grove.alpha.arbitrary_state.arbitrary_state(vector, qubits)
, inserting qubits that will not be used in the qubits
option modifies the output program and the results. Only when len(qubits) =ceil(log2(len(vector)))
(i.e., only when the number of qubits specified equals the minimum number of qubits for encoding the state) the result is correct. Here is a MWE:
import pyquil.api as api
import pyquil.quil as pq
from pyquil.gates import I
from grove.alpha.arbitrary_state.arbitrary_state import create_arbitrary_state
good = pq.Program()
bad = pq.Program()
qvm = api.QVMConnection()
# To show that the problem is independent of the position of the qubits
for i in range(6):
good.inst(I(i))
bad.inst(I(i))
good.inst(create_arbitrary_state([0,0,0,0,1], [2,3,4]))
print('Good: ', qvm.wavefunction(good))
bad.inst(create_arbitrary_state([0,0,0,0,1], [2,3,4,5]))
print('Bad: ', qvm.wavefunction(bad))
The result being
Good: (1+0j)|010000>
Bad: (0.7071067812+0j)|010000> + (0.3535533906+0j)|100000> + (0.3535533906+0j)|100100> + (0.3535533906+0j)|101000> + (0.3535533906+0j)|101100>
Deutsch-Jozsa need to be cleaned up and moved out of alpha.
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.