def test_create_workspace_instance_valid(self): storage = "strg" ws = Workspace(subscription_id=self.subscription_id, resource_group=self.resource_group, name=self.workspace_name, location=self.location) assert ws.subscription_id == self.subscription_id assert ws.resource_group == self.resource_group assert ws.name == self.workspace_name assert ws.location == self.location ws = Workspace(subscription_id=self.subscription_id, resource_group=self.resource_group, name=self.workspace_name, location=self.location, storage=storage) assert ws.storage == storage resource_id = f"/subscriptions/{self.subscription_id}/ResourceGroups/{self.resource_group}/providers/Microsoft.Quantum/Workspaces/{self.workspace_name}" ws = Workspace(resource_id=resource_id, location=self.location) assert ws.subscription_id == self.subscription_id assert ws.resource_group == self.resource_group assert ws.name == self.workspace_name ws = Workspace(resource_id=resource_id, storage=storage, location=self.location) assert ws.storage == storage
def test_create_workspace_instance_valid(self): subscription_id = "44ef49ad-64e4-44e5-a3ba-1ee87e19d3f4" resource_group = "rg" name = "n" storage = "strg" ws = Workspace(subscription_id=subscription_id, resource_group=resource_group, name=name) assert ws.subscription_id == subscription_id assert ws.resource_group == resource_group assert ws.name == name ws = Workspace(subscription_id=subscription_id, resource_group=resource_group, name=name, storage=storage) assert ws.storage == storage resource_id = f"/subscriptions/{subscription_id}/RESOurceGroups/{resource_group}/providers/Microsoft.Quantum/Workspaces/{name}" ws = Workspace(resource_id=resource_id) assert ws.subscription_id == subscription_id assert ws.resource_group == resource_group assert ws.name == name ws = Workspace(resource_id=resource_id, storage=storage) assert ws.storage == storage
def create_workspace(): workspace = Workspace(subscription_id=config._SUBSCRIPTION_ID, resource_group=config._RESOURCE_GROUP, name=config._NAME, location=config._LOCATION) workspace.login() return workspace
def _init_ws_(): return Workspace( subscription_id="subs_id", resource_group="rg", name="n", storage=None )
def create_workspace(self) -> Workspace: """Create workspace using credentials stored in config file :return: Workspace :rtype: Workspace """ workspace = Workspace( subscription_id=self.subscription_id, resource_group=self.resource_group, name=self.workspace_name, ) if self.is_live or self.in_recording: workspace.credentials = ServicePrincipalCredentials( tenant=self.tenant_id, client_id=self.client_id, secret=self.client_secret, resource="https://quantum.microsoft.com") workspace.login(False) else: workspace.credentials = BasicTokenAuthentication( token=self.dummy_auth_token) return workspace
def __init__(self, workspace=None, **kwargs): self._backends = None if workspace is None: workspace = Workspace(**kwargs) workspace.append_user_agent(QISKIT_USER_AGENT) self._workspace = workspace
def getWorkspace(self) -> Workspace: workspace = Workspace( subscription_id= self.subscription_id, resource_group= self.resource_group, name= self.name, location= self.location ) return workspace
def test_create_workspace_instance_invalid(self): storage = "invalid_storage" with pytest.raises(ValueError): Workspace() with pytest.raises(ValueError): Workspace( subscription_id=self.subscription_id, resource_group=self.resource_group, name="", ) with pytest.raises(ValueError): Workspace(resource_id="invalid/resource/id") with pytest.raises(ValueError): Workspace(storage=storage)
def test_create_workspace_locations(self): # location is mandatory with self.assertRaises(Exception) as context: Workspace( subscription_id=self.subscription_id, resource_group=self.resource_group, name=self.workspace_name, ) self.assertTrue("Azure Quantum workspace does not have an associated location." in context.exception) # User-provided location name should be normalized location = "East US" ws = Workspace( subscription_id=self.subscription_id, resource_group=self.resource_group, name=self.workspace_name, location=location, ) assert ws.location == "eastus"
def test_create_workspace_instance_invalid(self): subscription_id = "44ef49ad-64e4-44e5-a3ba-1ee87e19d3f4" resource_group = "rg" name = "n" storage = "strg" with pytest.raises(ValueError): ws = Workspace() with pytest.raises(ValueError): ws = Workspace(subscription_id=subscription_id, resource_group=resource_group, name="") with pytest.raises(ValueError): ws = Workspace(resource_id="invalid/resource/id") with pytest.raises(ValueError): ws = Workspace(storage=storage)
def test_create_workspace_locations(self): subscription_id = "44ef49ad-64e4-44e5-a3ba-1ee87e19d3f4" resource_group = "rg" name = "n" # Default should be westus ws = Workspace(subscription_id=subscription_id, resource_group=resource_group, name=name) assert ws.location == "westus" ws = Workspace(subscription_id=subscription_id, resource_group=resource_group, name=name, location=" ") assert ws.location == "westus" # User-provided location name should be normalized location = "East US" ws = Workspace(subscription_id=subscription_id, resource_group=resource_group, name=name, location=location) assert ws.location == "eastus"
def create_workspace_mock_login(**kwds) -> Workspace: """Create a mock Workspace object by patching the Azure authentication and uses a dummy authentication token.""" workspace = Workspace(**kwds) dummy_auth_token = { 'access_token': 'eyJ1eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Im5PbzNaRHJPRFhFSzFqS1doWHNsSFJfS1hFZyIsImtpZCI6Im5PbzNaRHJPRFhFSzFqS1doWHNsSFJfS1hFZyJ9.eyJidWQiOiJodHRwczovL3F1YW50dW0ubWljcm9zb2Z0LmNvbSIsImlzcyI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0LzcyZjk4OGJmLTg2ZjEtNDFhZi05MWFiLTJkN2NkMDExZGI0Ny8iLCJpYXQiOjE2MTE2ODMwNjAsIm5iZiI6MTYxMTY4MzA2MCwiZXhwIjoxNjExNjg2OTYwLCJfY2xhaW1fbmFtZXMiOnsiZ3JvdXBzIjoic3JjMSJ9LCJfY2xhaW1fc291cmNlcyI6eyJzcmMxIjp7ImVuZHBvaW50IjoiaHR0cHM6Ly9ncmFwaC53aW5kb3dzLm5ldC83MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDcvdXNlcnMvZTlhNGE5ZTEtODcxNS00Yjc1LTk2NWQtYzBkZDQxMTIzODY4L2dldE1lbWJlck9iamVjdHMifX0sImFjciI6IjEiLCJhaW8iOiJBVlFBcS84U0FBQUFXMnNsMlRORXd5eXA2OGdvejM2RnRoSXFZSlJDdmRibDF0WVJPanUrUzNCZDV5MGsyeWMyOFdKUk9IQ283a0VuNGRpaDh1dkpLQm00TFNoTHRUQ3FsMHMwNkp6N3NYclNpNTFJOEljZThZcz0iLCJhbXIiOlsid2lhIiwibWZhIl0sImFwcGlkIjoiODRiYTA5NDctNmM1My00ZGQyLTljYTktYjM2OTQ3NjE1MjFiIiwiYXBwaWRhY3IiOiIwIiwiZmFtaWx5X25hbWUiOiJCcm93biIsImdpdmVuX25hbWUiOiJUb20iLCJpbl9jb3JwIjoidHJ1ZSIsImlwYWRkciI6I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.patch.object(MsalWrapper, 'acquire_auth_token', return_value=dummy_auth_token): workspace.login(True) return workspace
def create_workspace() -> Workspace: """Create workspace using credentials stored in config file :return: Workspace :rtype: Workspace """ config = get_config() workspace = Workspace( subscription_id=config["azure.quantum"]["subscription_id"], resource_group=config["azure.quantum"]["resource_group"], name=config["azure.quantum"]["workspace_name"], storage="") # try to login - this should trigger the device flow workspace.login(False) return workspace
def __init__(self, workspace: Workspace = None, default_target: Optional[str] = None, **kwargs): """AzureQuantumService class :param workspace: Azure Quantum workspace. If missing it will create a new Workspace passing `kwargs` to the constructor. Defaults to None. :type workspace: Workspace, optional :param default_target: Default target name, defaults to None :type default_target: Optional[str], optional """ if workspace is None: workspace = Workspace(**kwargs) workspace.append_user_agent(CIRQ_USER_AGENT) self._workspace = workspace self._default_target = default_target
def create_workspace() -> Workspace: """Create workspace using credentials stored in config file :return: Workspace :rtype: Workspace """ client_id = os.environ.get("AZURE_CLIENT_ID", "") client_secret = os.environ.get("AZURE_CLIENT_SECRET", "") tenant_id = os.environ.get("AZURE_TENANT_ID", "") resource_group = os.environ.get("RESOURCE_GROUP", "") subscription_id = os.environ.get("SUBSCRIPTION_ID", "") workspace_name = os.environ.get("WORKSPACE_NAME", "") assert len( client_id) > 0, "AZURE_CLIENT_ID not found in environment variables." assert len(client_secret ) > 0, "AZURE_CLIENT_SECRET not found in environment variables." assert len( tenant_id) > 0, "AZURE_TENANT_ID not found in environment variables." assert len(resource_group ) > 0, "RESOURCE_GROUP not found in environment variables." assert len(subscription_id ) > 0, "SUBSCRIPTION_ID not found in environment variables." assert len(workspace_name ) > 0, "WORKSPACE_NAME not found in environment variables." if len(client_secret) > 0: workspace = Workspace( subscription_id=subscription_id, resource_group=resource_group, name=workspace_name, ) workspace.credentials = ServicePrincipalCredentials( tenant=tenant_id, client_id=client_id, secret=client_secret, resource="https://quantum.microsoft.com") workspace.login() return workspace
def SPLogin(): quantumWorkspace = {} try: quantumWorkspace = Workspace( subscription_id=os.environ.get( 'subscriptionId'), # Add your subscription_id resource_group=os.environ.get( 'resourceGroup'), # Add your resource_group name=os.environ.get( 'quantumWorkspaceName'), # Add your workspace name location=os.environ.get( 'quantumLocation' ) # Add the workspace location, for example, westus ) if (os.environ.get('loginMethod') == 'servicePrincipal'): quantumWorkspace.credentials = ServicePrincipalCredentials( tenant=os.environ.get( 'directoryId' ), # From service principal creation, your Directory (tenant) ID client_id=os.environ.get( 'appId' ), # From service principal creation, your Application (client) ID secret=os.environ.get( 'appsecret' ), # From service principal creation, your secret resource= "https://quantum.microsoft.com" # Do not change! This is the resource you want to authenticate against - the Azure Quantum service ) else: quantumWorkspace.login( ) #If you do not want to use service prinipal login you can use the interactive browser login except: KeyError('Failed to login with service principal') quantumWorkspace.login() return quantumWorkspace
def create_workspace(self, **kwargs) -> Workspace: """Create workspace using credentials passed via OS Environment Variables described in the README.md documentation, or when in playback mode use a placeholder credential. :return: Workspace :rtype: Workspace """ playback_credential = ClientSecretCredential(self.tenant_id, self.client_id, self.client_secret) default_credential = playback_credential if self.is_playback \ else None workspace = Workspace(credential=default_credential, subscription_id=self.subscription_id, resource_group=self.resource_group, name=self.workspace_name, location=self.location, **kwargs) workspace.append_user_agent("testapp") return workspace
def create_workspace() -> Workspace: """Create workspace using credentials stored in config file :return: Workspace :rtype: Workspace """ config = get_config() if config: workspace = Workspace( subscription_id=config["azure.quantum"]["subscription_id"], resource_group=config["azure.quantum"]["resource_group"], name=config["azure.quantum"]["workspace_name"], ) # try to login - this should trigger the device flow workspace.login(False) else: workspace = create_workspace_mock_login( subscription_id=RecordingUpdater.dummy_uid, resource_group=RecordingUpdater.dummy_rg, name=RecordingUpdater.dummy_ws, ) return workspace
def test_workspace_user_agent_appid(self): env_var_app_id = "MyEnvVarAppId" user_agent = "MyUserAgentAppId" very_long_user_agent = "MyVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongUserAgentAppId" original_env_app_id = os.environ.get(USER_AGENT_APPID_ENV_VAR_NAME, "") try: # no UserAgent parameter and no EnvVar AppId os.environ[USER_AGENT_APPID_ENV_VAR_NAME] = "" ws = Workspace( subscription_id=self.subscription_id, resource_group=self.resource_group, name=self.workspace_name, location=self.location ) assert ws.user_agent is None # no UserAgent parameter and with EnvVar AppId os.environ[USER_AGENT_APPID_ENV_VAR_NAME] = env_var_app_id ws = Workspace( subscription_id=self.subscription_id, resource_group=self.resource_group, name=self.workspace_name, location=self.location ) assert ws.user_agent == env_var_app_id # with UserAgent parameter and no EnvVar AppId os.environ[USER_AGENT_APPID_ENV_VAR_NAME] = "" ws = Workspace( subscription_id=self.subscription_id, resource_group=self.resource_group, name=self.workspace_name, location=self.location, user_agent=user_agent ) assert ws.user_agent == user_agent # with very long UserAgent parameter and no EnvVar AppId os.environ[USER_AGENT_APPID_ENV_VAR_NAME] = "" ws = Workspace( subscription_id=self.subscription_id, resource_group=self.resource_group, name=self.workspace_name, location=self.location, user_agent=very_long_user_agent ) assert ws.user_agent == very_long_user_agent # with UserAgent parameter and with EnvVar AppId os.environ[USER_AGENT_APPID_ENV_VAR_NAME] = env_var_app_id ws = Workspace( subscription_id=self.subscription_id, resource_group=self.resource_group, name=self.workspace_name, location=self.location, user_agent=user_agent ) assert ws.user_agent == f"{user_agent}-{env_var_app_id}" # Append with UserAgent parameter and with EnvVar AppId os.environ[USER_AGENT_APPID_ENV_VAR_NAME] = env_var_app_id ws = Workspace( subscription_id=self.subscription_id, resource_group=self.resource_group, name=self.workspace_name, location=self.location, user_agent=user_agent ) ws.append_user_agent("featurex") assert ws.user_agent == f"{user_agent}-featurex-{env_var_app_id}" # Append with no UserAgent parameter and no EnvVar AppId os.environ[USER_AGENT_APPID_ENV_VAR_NAME] = "" ws = Workspace( subscription_id=self.subscription_id, resource_group=self.resource_group, name=self.workspace_name, location=self.location ) ws.append_user_agent("featurex") assert ws.user_agent == "featurex" finally: if original_env_app_id: os.environ[USER_AGENT_APPID_ENV_VAR_NAME] = original_env_app_id else: os.environ.pop(USER_AGENT_APPID_ENV_VAR_NAME)
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from azure.quantum import Workspace from azure.quantum.optimization import Problem, ProblemType, Term from azure.quantum.target.oneqbit import TabuSearch, PticmSolver, PathRelinkingSolver import time # Workspace information workspace = Workspace( resource_id="", # add the Resource ID of your Azure Quantum workspace location= "" # add the location of your Azure Quantum workspace (e.g. "westus") ) # Define the problem problem = Problem(name="My First 1QBit Problem", problem_type=ProblemType.ising) problem.add_terms([ Term(w=-9, indices=[0]), Term(w=-3, indices=[1, 0]), Term(w=5, indices=[2, 0]), Term(w=9, indices=[2, 1]), Term(w=2, indices=[3, 0]), Term(w=-4, indices=[3, 1]), Term(w=4, indices=[3, 2]) ]) # Create 1QBit solvers print('instantiate solvers...')
import math import requests import json import datetime from azure.quantum import Workspace from azure.quantum.optimization import Problem, ProblemType, Term from azure.quantum.optimization import SimulatedAnnealing, HardwarePlatform from azure.quantum.optimization import ParallelTempering, HardwarePlatform from typing import List #connect to Azure Quantum workspace workspace = Workspace( subscription_id='', #your Azure subscription_id resource_group= '', #the resource group name where your quantum workspace is located name='', #the name of you Azure Quantum workspace location='' #the loocation of the workspace (example: westus) ) #open the browser and sign in with the generated code workspace.login() ### Define variables # The number of nodes NumNodes = 5 # Max cost between nodes maxCost = 10
## pip uninstall azure-quantum -y ## pip install azure-quantum # Essential imports and workspace details. # Please add your workspace details in the empty fields below. # These can be retrieved via the command line if needed. Use 'az quantum workspace show'. import time from typing import List from azure.quantum import Workspace from azure.quantum.optimization import SubstochasticMonteCarlo from azure.quantum.optimization import Problem, ProblemType, Term, SlcTerm, GroupType, RangeSchedule workspace = Workspace(subscription_id="", resource_group="", name="", location="") # Ship Loading Problem # https://docs.microsoft.com/learn/modules/solve-quantum-inspired-optimization-problems/5-apply-quantum-inspired-optimization-real-world # for details on the problem formulation - more context can also be found in the jupyter version of this sample # define weights of the containers to be loaded weights = [ 2, 5, 9, 21, 35, 5, 3,
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from azure.quantum import Workspace from azure.quantum.optimization import Problem, ProblemType, Term from azure.quantum.target.toshiba import SimulatedBifurcationMachine # Copy the settings for your workspace below workspace = Workspace( resource_id= "", # add the Resource ID of the Azure Quantum workspace you created with the Toshiba provider location="") # Define the problem problem = Problem(name="My First Toshiba SQBM+ Problem", problem_type=ProblemType.pubo) problem.add_terms([ Term(w=-9, indices=[0]), Term(w=-3, indices=[1, 0]), Term(w=5, indices=[2, 0]), Term(w=9, indices=[2, 1]), Term(w=2, indices=[3, 0]), Term(w=-4, indices=[3, 1]), Term(w=4, indices=[3, 2]) ]) # Create Toshiba SQBM+ solver with default parameters solver = SimulatedBifurcationMachine(workspace) # Submit the problem for solving with Toshiba SQBM+
#!/usr/bin/env python # coding: utf-8 # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # Instantiate Workspace object which allows you to connect to the Workspace you've previously deployed in Azure. # Be sure to fill in the settings below which can be retrieved by running 'az quantum workspace show' in the terminal. from azure.quantum import Workspace # Copy the settings for your workspace below workspace = Workspace( subscription_id="", # Add your subscription_id resource_group="", # Add your resource_group name="", # Add your workspace name location="" # Add your workspace location (for example, "westus") ) workspace.login() # Take an array of container weights and return a Problem object that represents the cost function from typing import List from azure.quantum.optimization import Problem, ProblemType, Term def create_problem_for_container_weights( container_weights: List[int]) -> Problem: terms: List[Term] = [] # Expand the squared summation for i in range(len(container_weights)): for j in range(len(container_weights)):
from azure.quantum import Workspace workspace = Workspace( resource_id = "/subscriptions/50f157c9-e6e8-4191-beb7-3de96b563d95/resourceGroups/rq-azure-quantum/providers/Microsoft.Quantum/Workspaces/aq-workspace-djohnnie" ) workspace.login() from typing import List from azure.quantum.optimization import Problem, ProblemType, Term def createProblemForContainerWeights(containerWeights: List[int]) -> List[Term]: terms: List[Term] = [] # Expand the squared summation for i in range(len(containerWeights)): for j in range(len(containerWeights)): if i == j: # Skip the terms where i == j as they can be disregarded: # w_i∗w_j∗x_i∗x_j = w_i*w_j∗(x_i)^2 = w_i∗w_j # for x_i = x_j, x_i ∈ {1, -1} continue terms.append( Term( w = containerWeights[i] * containerWeights[j], indices = [i, j] ) )