Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sanjgupt/onlineproblem #55

Merged
merged 25 commits into from
May 10, 2021
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
9a63c66
add online problem plus testing for it. Download method in problme
sanjgupt May 3, 2021
d83a6d5
nit
sanjgupt May 3, 2021
35620ab
add another assertion for online problems
sanjgupt May 3, 2021
926ad2a
update solver to handle online problmes
sanjgupt May 3, 2021
f473660
Raise error for setting fixed variables for online problem and test
sanjgupt May 3, 2021
b7a6b28
merge from upstream main
sanjgupt May 4, 2021
a15062f
codestyle errors
sanjgupt May 4, 2021
95d808d
nit
sanjgupt May 4, 2021
6ba91ab
Make online problem wrapper for name and url
sanjgupt May 4, 2021
40c1f0b
codestyle errors
sanjgupt May 4, 2021
cabf16e
add a small function to enable getting terms from index
sanjgupt May 4, 2021
89226d9
remove evalutate and fixed variables from online problem
sanjgupt May 5, 2021
cd4272f
update the download function to correctly authenticate the storage ac…
sanjgupt May 5, 2021
197754d
styling errors
sanjgupt May 5, 2021
ace7965
styling errors
sanjgupt May 5, 2021
1e108b6
Merge branch 'main' into sanjgupt/onlineproblem
sanjgupt May 6, 2021
0d3b9b2
nit
sanjgupt May 6, 2021
6d63cec
Merge branch 'main' of https://github.com/microsoft/qdk-python into s…
sanjgupt May 6, 2021
417939e
Merge branch 'sanjgupt/onlineproblem' of https://github.com/sanjgupt/…
sanjgupt May 6, 2021
9986d47
disablinb test for Online Problem for now till it becomes available i…
sanjgupt May 7, 2021
ee2a67c
Update azure-quantum/tests/unit/test_online_problem.py
sanjgupt May 10, 2021
e05559b
revert styles changes to _client. This folder should not be changed b…
sanjgupt May 10, 2021
e68e221
nit
sanjgupt May 10, 2021
342f430
commneting out onliune problem code till OnlineProblem can be made av…
sanjgupt May 10, 2021
bad7699
nit
sanjgupt May 10, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion azure-quantum/azure/quantum/optimization/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
from .problem import *
from .solvers import *
from .streaming_problem import *

from .online_problem import *
33 changes: 33 additions & 0 deletions azure-quantum/azure/quantum/optimization/online_problem.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import logging
from typing import TYPE_CHECKING, Union, Dict
from azure.quantum.optimization import Problem

logger = logging.getLogger(__name__)

__all__ = ['OnlineProblem']

if TYPE_CHECKING:
from azure.quantum.workspace import Workspace

class OnlineProblem(Problem):
sanjgupt marked this conversation as resolved.
Show resolved Hide resolved
def __init__(self, name:str, blob_uri:str):
super().__init__(self)
self.name = name
self.uploaded_blob_uri = blob_uri

def evaluate(self, configuration: Union[Dict[int, int], Dict[str, int]]) -> float:
sanjgupt marked this conversation as resolved.
Show resolved Hide resolved
"""
An OnlineProblem cannot be evaluated on client side. Calling this function will raise a user exception
"""
raise Exception('An Online Problem cannot be evaluated. Please download the problem to do this operation')

def set_fixed_variables(self, fixed_variables: Union[Dict[int, int], Dict[str, int]]) -> Problem:
"""
An OnlineProblem cannot be evaluated on client side. Calling this function will raise a user exception
"""
raise Exception('An Online Problem cannot set fixed terms. Please download the problem to do this operation')

def download(self)-> Problem:
logger.warning('The problem will be downloaded to the client')
return super().download()

13 changes: 11 additions & 2 deletions azure-quantum/azure/quantum/optimization/problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
from typing import List, Union, Dict, Optional, TYPE_CHECKING
from enum import Enum
from azure.quantum.optimization import Term
from azure.quantum.storage import upload_blob, ContainerClient

from azure.quantum.storage import upload_blob, ContainerClient, BlobClient, download_blob
#import azure.quantum.storage
sanjgupt marked this conversation as resolved.
Show resolved Hide resolved

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -230,3 +230,12 @@ def is_large(self) -> bool:
set_vars.update(term.ids)

return (len(set_vars) >= Problem.NUM_VARIABLES_LARGE and len(self.terms) >= Problem.NUM_TERMS_LARGE)

def download(self):
"""Dowloads an uploaded problem as an instance of 'Problem'
"""
if not self.uploaded_blob_uri:
raise Exception("Problem must be uploaded before it can be downloaded")
contents = download_blob(self.uploaded_blob_uri)
return Problem.deserialize(contents, self.name)

5 changes: 4 additions & 1 deletion azure-quantum/azure/quantum/optimization/solvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,10 @@ def submit(self, problem: Union[str, Problem], compress: bool = True) -> Job:

if isinstance(problem, str):
name = "Optimization problem"
problem_uri = problem
problem_uri = problem
elif not problem.terms:
name = problem.name
problem_uri = problem.uploaded_blob_uri
else:
name = problem.name
problem_uri = problem.upload(self.workspace, compress=compress, container_name=container_name, blob_name="inputData")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from azure_devtools.scenario_tests.base import ReplayableTest
from azure_devtools.scenario_tests.recording_processors import RecordingProcessor, is_text_payload, AccessTokenReplacer
from azure_devtools.scenario_tests.utilities import _get_content_type

import json
class QuantumTestBase(ReplayableTest):
"""QuantumTestBase

Expand Down Expand Up @@ -196,3 +196,16 @@ def process_response(self, response):

return response

#helper functions

# helpers
def expected_terms():
expected = json.dumps({
"cost_function": {
"version": "1.1",
"type": "ising",
"terms": [ { 'c':3, 'ids':[1,0] }, {'c':5, 'ids':[2,0]} ],
"initial_configuration": {"0":-1 , "1": 1, "2": -1},
}
})
return expected
2 changes: 1 addition & 1 deletion azure-quantum/tests/unit/test_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from azure.quantum.optimization import Problem
from azure.quantum.optimization.solvers import SimulatedAnnealing
from azure.quantum import Job
from quantum_test_base import QuantumTestBase
from common import QuantumTestBase


class TestJob(QuantumTestBase):
Expand Down
39 changes: 39 additions & 0 deletions azure-quantum/tests/unit/test_online_problem.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import unittest
from unittest.mock import Mock
from azure.quantum.optimization import Problem, Term, OnlineProblem
import azure.quantum.optimization.problem
from common import expected_terms
import json


class TestOnlineProblemClass(unittest.TestCase):

def setUp(self):
self.o_problem = OnlineProblem(name = "test", blob_uri = "mock_blob_uri")


def test_download(self):
azure.quantum.optimization.problem.download_blob = Mock(return_value = expected_terms())
acutal_result = self.o_problem.download()
#to-do add test that user warning was registered in log
assert acutal_result.name == 'test'
azure.quantum.optimization.problem.download_blob.assert_called_once()
assert isinstance(acutal_result, Problem)

def test_evaluate(self):
config_dict = {
1:1,
0:1
}
with self.assertRaises(Exception):
self.o_problem.evaluate(config_dict)

def test_set_fixed_variables(self):
config_dict = {
1:1,
0:1
}
with self.assertRaises(Exception):
self.o_problem.set_fixed_variables(config_dict)


4 changes: 2 additions & 2 deletions azure-quantum/tests/unit/test_optimization.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@
## IMPORTS ##

import json

import unittest
from azure.quantum import Workspace
from azure.quantum.optimization import Problem, ProblemType, Term
from azure.quantum.optimization.solvers import ParallelTempering, PopulationAnnealing, RangeSchedule, SimulatedAnnealing, HardwarePlatform, QuantumMonteCarlo, SubstochasticMonteCarlo
from quantum_test_base import QuantumTestBase
from common import QuantumTestBase

class TestProblem(QuantumTestBase):
def test_add_terms(self):
Expand Down
26 changes: 26 additions & 0 deletions azure-quantum/tests/unit/test_problem.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import unittest
from unittest.mock import Mock
from azure.quantum.optimization import Problem, Term
import azure.quantum.optimization.problem
from common import expected_terms
import json


class TestProblemClass(unittest.TestCase):

def setUp(self):
self.problem = Problem(name = "test")
self.problem.terms = [
Term(c = 3, indices=[1,0]),
Term(c = 5, indices=[2,0])
]
self.problem.uploaded_blob_uri = "mock_blob_uri"

def test_download(self):
azure.quantum.optimization.problem.download_blob = Mock(return_value = expected_terms())
acutal_result = self.problem.download()
assert acutal_result.name == 'test'
azure.quantum.optimization.problem.download_blob.assert_called_once()



21 changes: 21 additions & 0 deletions azure-quantum/tests/unit/test_solvers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import unittest
from unittest.mock import Mock, patch
from azure.quantum import Workspace, storage
from azure.quantum.optimization import Solver, OnlineProblem
import azure.quantum.storage

class TestSolvers(unittest.TestCase):
def setUp(self):
self.mock_ws = Mock(spec = Workspace)
self.mock_ws.storage = "mock_storage"
#self.mock_ws.submit_job = Mock(return_value = )
self.testsolver = Solver(self.mock_ws, 'Microsoft', 'SimulatedAnnealing', 'json', 'json')

def test_submit_online_problem(self):
#Arrange
o_problem = OnlineProblem(name = "test", blob_uri = "mock_blob_uri")
#Act
azure.quantum.storage.get_container_uri = Mock(return_value = "mock_container_uri")
_ = self.testsolver.submit(o_problem)
#Assert
self.testsolver.workspace.submit_job.assert_called_once()
2 changes: 1 addition & 1 deletion azure-quantum/tests/unit/test_workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import pytest

from azure.quantum import Workspace
from quantum_test_base import QuantumTestBase
from common import QuantumTestBase

class TestWorkspace(QuantumTestBase):
def test_workspace_login(self):
Expand Down