Code Monkey home page Code Monkey logo

grove's People

Contributors

ampolloreno avatar amyfbrown avatar asiero avatar ccoffrin avatar ecpeterson avatar harleypatton avatar jansenzhao avatar joelin0 avatar jonward-rigetti avatar jotterbach avatar karalekas avatar klinvill avatar kmckiern avatar markf94 avatar mpharrigan avatar mstechly avatar ncrubin avatar ntezak avatar stevenheidel avatar tbabej avatar vontell avatar willzeng avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

grove's Issues

Increase code test coverage

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?

Removing dependency and use of parametric programs

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.

Finding the state of the system after Oracle.

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?

Testing phase estimation

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.

Fix grove docs build

The new complex dependencies (qutip+cython+cvxpy) have made the semaphore setup very complicated and broken the grove docs build.

qaoa.py instance is used incorrectly in max_cut example in pyqaoa

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]

Recursive methods should be iterative

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.

Grove tests break on Python 3.6

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

grover.py should distinguish SyncConnection from JobConnection

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)?

Remove explicit QVM targeting in QAOA module

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.

improve testing functionality

While building tests for shor.py, I realized that there are a few issues with the testing infrastructure in grove.

  1. All tests import the modules that they would like to test in the following way (example taken from 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.

  1. Originally, testing was being done by comparing the created Quil programs with the expected program. However, there are an increasing number of features in Grove that are abstracted away from the Quil code directly, and instead need to run multiple programs on Forest to get a final result (for example, the 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.

Grover search for database with decimal value and computation time

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!

Bug in qaoa.py when using QPU?

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.

Grove 2.0

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).

@mpharrigan

Not able to install quantum-grove in Windows 10

issue 1
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.
issue

grover's algorithm won't run from the CLI

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 documentation to vqe

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).

Max cut is missing ability to study under noise

Right now MaxCut is missing both:

  • the ability to pass a new connection to a possibly noisy QVM. This is addressed by the open PR #17
  • the ability to pass in a number of samples so that the expectation calculation under the noise model does happen the "fast way" but rather the more realistic noise sampled way
    @ncrubin Do you have some updated code that fixes some of the expectation sampling under finite noise issues?

Deutsch-Josza broken for two-qubit case

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

Incorrect docs for VQE example

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 compatibility issues

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'

Error in phase estimation

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

error happens when I add initial angles to the qaoa_maxcut

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

jietu20171205-225939

jietu20171205-230026

create_arbitrary_state gives different results when too many qubits are specified

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>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.