Ejemplo n.º 1
0
 def test_save_and_load_token_filename(self):
     filename = 'path/to/open/dummyqi.rc'
     os.makedirs = MagicMock()
     json.load = MagicMock()
     os.environ.get = MagicMock()
     os.environ.get.return_value = None
     expected_token = 'secret'
     json.load.return_value = {'token': expected_token}
     with patch("builtins.open", mock_open()) as mock_file:
         with patch('os.makedirs', os.makedirs):
             save_account(expected_token, filename)
             mock_file.assert_called_with(filename, 'w')
             handle = mock_file()
             all_calls = handle.mock_calls
             self.assertIn([
                 call.write('{'),
                 call.write('\n  '),
                 call.write('"token"'),
                 call.write(': '),
                 call.write('"' + expected_token + '"'),
                 call.write('\n'),
                 call.write('}')
             ], all_calls)
             token = load_account(filename)
             self.assertEqual(expected_token, token)
Ejemplo n.º 2
0
 def test_load_token_env(self):
     expected_token = 'secret'
     json.load = MagicMock()
     json.load.return_value = {'faulty_key': 'faulty_token'}
     with patch.dict('os.environ', values={'QI_TOKEN': expected_token}):
         with patch("builtins.open", mock_open()):
             token = load_account()
             self.assertEqual(expected_token, token)
Ejemplo n.º 3
0
 def test_load_token_env(self):
     expected_token = 'secret'
     json.load = MagicMock()
     json.load.return_value = {'faulty_key': 'faulty_token'}
     os.environ.get = MagicMock()
     os.environ.get.return_value = expected_token
     with patch("builtins.open", mock_open()):
         token = load_account()
         self.assertEqual(expected_token, token)
Ejemplo n.º 4
0
    def __init__(self, base_uri: str = QI_URL, authentication: Optional[coreapi.auth.AuthBase] = None,
                 project_name: Optional[str] = None,
                 coreapi_client_class: Type[coreapi.Client] = coreapi.Client) -> None:
        """ Python interface to the Quantum Inspire API (Application Programmer Interface).

        The Quantum Inspire API supplies an interface for executing cQASM programs and can be used to access the
        different entities in the Quantum Inspire database needed for running the programs.
        The entities for which an interface is provided are:
            Backend types: Depending on the user account more qubits can be used and simulated on faster hardware.
            Projects: Executing programs is done from a project. Projects keep track of the other entities.
            Jobs: A job contains all the information and the parameters needed for executing the program.
            Assets: A container for a cQASM program. Is part of a job.
            Results: After the job is finished, the results are gathered in the result-entity.

        QuantumInspireAPI is a convenient interface (or wrapper) to the low level API and hides details for
        requesting data (via get) and performing operations on the different entities (via actions).

        For more documentation see the knowledge base on: https://www.quantum-inspire.com/kbase/low-level-api/
        The REST API can be found on: https://api.quantum-inspire.com/
        The Core API schema is published on: https://api.quantum-inspire.com/schema/

        Args:
            base_uri: The base uri of the Quantum Inspire API-location where the schema can be found (in path
                      'schema/').
            authentication: The authentication, can be one of the following coreapi authentications:
                            BasicAuthentication(email, password), HTTP authentication with valid email/password.
                            TokenAuthentication(token, scheme="token"), token authentication with a valid API-token.
                            When authentication is None, a token is read from the default location.
            project_name: The project used for executing the jobs.
            coreapi_client_class: Coreapi client to interact with the API through a schema.
                                  Default set to coreapi.Client.

        Note: When no project name is given, a temporary project is created for the job and deleted after the job
              has finished. When a project name is given, a project is created if it does not exist, but re-used
              if a project with that name already exists. In either case, the project will not be deleted when a
              project name is supplied here.

        Raises:
            AuthenticationError: An AuthenticationError exception is raised when no authentication is given
                                 and the token could not be loaded from the default location.
            ApiError: An ApiError exception is raised when the schema could not be loaded.
        """
        if authentication is None:
            token = load_account()
            if token is not None:
                authentication = TokenAuthentication(token, scheme="token")
            else:
                raise AuthenticationError('No credentials have been provided or found on disk')
        self.__client = coreapi_client_class(auth=authentication)
        self.project_name = project_name
        self.base_uri = base_uri
        self.enable_fsp_warning = True
        try:
            self._load_schema()
        except (CoreAPIException, TypeError) as ex:
            raise ApiError(f'Could not connect to {base_uri}') from ex
Ejemplo n.º 5
0
def get_authentication_alt():
    """ Gets the authentication for connecting to the Quantum Inspire API."""
    token = load_account()
    if token is not None:
        return get_token_authentication(token)
    else:
        print('Enter email:')
        email = input()
        print('Enter password')
        password = getpass()
        return get_basic_authentication(email, password)
Ejemplo n.º 6
0
 def test_enable_token_env(self):
     expected_token = 'secret'
     json.load = MagicMock()
     json.load.return_value = {'faulty_key': 'faulty_token'}
     environment = MagicMock()
     environment.get.return_value = expected_token
     with patch('os.environ', environment):
         enable_account(expected_token)
         all_calls = environment.mock_calls
         self.assertIn([call.__setitem__('QI_TOKEN', expected_token)],
                       all_calls)
         token = load_account()
         all_calls = environment.mock_calls
         self.assertIn([call.get('QI_TOKEN', None)], all_calls)
         self.assertEqual(expected_token, token)
Ejemplo n.º 7
0
def get_authentication(B):
    if B == 'QI':
        """ Gets the authentication for connecting to the Quantum Inspire API."""
        token = load_account()
        if token is not None:
            return get_token_authentication(token)
        else:
            if QI_EMAIL is None or QI_PASSWORD is None:
                print('Enter email:')
                email = input()
                print('Enter password')
                password = getpass()
            else:
                email, password = QI_EMAIL, QI_PASSWORD
            return get_basic_authentication(email, password)
    elif B == 'IBMQ':
        print('Enter IBMQ token:')
        ibmq_token = input()
        return IBMQ.enable_account(ibmq_token)
Ejemplo n.º 8
0
 def test_save_and_load_token_default_rc(self):
     os.makedirs = MagicMock()
     json.load = MagicMock()
     with patch.dict('os.environ', values={'QI_TOKEN': ''}):
         expected_token = 'secret'
         json.load.return_value = {'token': expected_token}
         with patch("builtins.open", mock_open()) as mock_file:
             with patch('os.makedirs', os.makedirs):
                 save_account(expected_token)
                 mock_file.assert_called_with(DEFAULT_QIRC_FILE, 'w')
                 handle = mock_file()
                 all_calls = handle.mock_calls
                 self.assertIn([
                     call.write('{'),
                     call.write('\n  '),
                     call.write('"token"'),
                     call.write(': '),
                     call.write('"' + expected_token + '"'),
                     call.write('\n'),
                     call.write('}')
                 ], all_calls)
                 token = load_account()
                 self.assertEqual(expected_token, token)
Ejemplo n.º 9
0
from src.qasm_optimizer.optimizer import optimize
from src.qasm_error_introducer.error_introducer import introduce_error
from src.qasm_topology_mapper.mapping import map_to_topology
from src.quantum_phase_estimation.processing.classical_postprocessing import print_result, remove_degeneracy
from src.quantum_phase_estimation.plot_results import plot_results

import numpy as np

if __name__ == "__main__":
    QI_EMAIL = os.getenv('QI_EMAIL')
    QI_PASSWORD = os.getenv('QI_PASSWORD')
    QI_URL = os.getenv('API_URL', 'https://api.quantum-inspire.com/')

    authentication = get_authentication(qi_email=QI_EMAIL,
                                        qi_password=QI_PASSWORD,
                                        token=load_account())
    qi = QuantumInspireAPI(QI_URL, authentication, 'matrix')

    # variables
    phase = 0.08
    print(phase)
    unitary_qasm = f"QASM\nRz q[0], {-phase*2*np.pi}"
    unitary_matrix = np.array([[np.exp(phase * 1j * np.pi), 0],
                               [0, np.exp(-phase * 1j * np.pi)]])
    unitary = unitary_matrix
    custom_prepare = "prep_z q[0]\n X q[0]"
    desired_bit_accuracy = 5
    minimum_chance_of_success = 0.5
    mu = 0.5
    sigma = 0.5
    error_toggle = 0
Ejemplo n.º 10
0
from src.connecting.quantum_inspire import get_authentication
from quantuminspire.api import QuantumInspireAPI

from examples.utils.mapping import generate_data
from src.quantum_phase_estimation.util_functions import error_estimate
from src.quantum_phase_estimation.util_functions import decimal_to_binary_fracion, find_max_value_keys, to_array
from src.quantum_phase_estimation.processing.plotting import heatmap, graph
from quantuminspire.credentials import load_account

if __name__ == "__main__":
    QI_EMAIL = os.getenv('QI_EMAIL')
    QI_PASSWORD = os.getenv('QI_PASSWORD')
    QI_URL = os.getenv('API_URL', 'https://api.quantum-inspire.com/')

    tokens = [load_account()]
    qis = list(
        map(
            lambda x: QuantumInspireAPI(
                QI_URL,
                get_authentication(
                    qi_email=QI_EMAIL, qi_password=QI_PASSWORD, token=x),
                'Quantum Phase Estimation matrix'), tokens))

    # variables
    desired_bit_accuracy = 6
    minimum_chance_of_success = 0.5
    mu = 0
    sigma = 0.05
    use_error_model = False
    use_multiple = True