Exemplo n.º 1
0
    def test_serialization_init_config(self):
        count = 2
        terms = []
        for i in range(count):
            terms.append(Term(c=i, indices=[i, i + 1]))
        init_config = {"0": -1, "1": 1, "2": -1}
        problem = Problem(name="test", terms=terms, init_config=init_config)

        expected = json.dumps({
            "metadata": {
                "name": "test"
            },
            "cost_function": {
                "version": "1.1",
                "type": "ising",
                "terms": [
                    {
                        "c": 0,
                        "ids": [0, 1]
                    },
                    {
                        "c": 1,
                        "ids": [1, 2]
                    },
                ],
                "initial_configuration": {
                    "0": -1,
                    "1": 1,
                    "2": -1
                },
            }
        })
        actual = problem.serialize()
        self.assertEqual(expected, actual)
Exemplo n.º 2
0
    def test_serialization_cterms(self):
        count = 2
        terms = []
        for i in range(count):
            terms.append(Term(c=i, indices=[i, i + 1]))
        problem = Problem(name="test", terms=terms)

        expected = json.dumps({
            "metadata": {
                "name": "test"
            },
            "cost_function": {
                "version": "1.0",
                "type": "ising",
                "terms": [
                    {
                        "c": 0,
                        "ids": [0, 1]
                    },
                    {
                        "c": 1,
                        "ids": [1, 2]
                    },
                ],
            }
        })
        print(problem.serialize())
        actual = problem.serialize()
        self.assertEqual(expected, actual)
    async def __test_upload_problem(
            self,
            count: int,
            terms_thresh: int,
            size_thresh: int,
            compress: bool,
            problem_type: ProblemType = ProblemType.ising,
            initial_terms: List[Term] = [],
            **kwargs):
        if not (self.in_recording or self.is_live):
            # Temporarily disabling this test in playback mode
            # due to multiple calls to the storage API
            # that need to have a request id to distinguish
            # them while playing back
            print("Skipping this test in playback mode")
            return

        ws = self.create_async_workspace()

        sProblem = await StreamingProblem.create(ws,
                                                 name="test",
                                                 problem_type=problem_type,
                                                 terms=initial_terms)
        rProblem = Problem("test",
                           problem_type=problem_type,
                           terms=initial_terms)
        sProblem.upload_terms_threshold = terms_thresh
        sProblem.upload_size_threshold = size_thresh
        sProblem.compress = compress

        for i in range(count):
            await sProblem.add_term(c=i, indices=[i, i + 1])
            rProblem.add_term(c=i, indices=[i, i + 1])

        self.assertEqual(problem_type, sProblem.problem_type)
        self.assertEqual(problem_type.name, sProblem.stats["type"])
        self.assertEqual(count + len(initial_terms),
                         sProblem.stats["num_terms"])
        self.assertEqual(
            self.__kwarg_or_value(kwargs, "avg_coupling", 2),
            sProblem.stats["avg_coupling"],
        )
        self.assertEqual(
            self.__kwarg_or_value(kwargs, "max_coupling", 2),
            sProblem.stats["max_coupling"],
        )
        self.assertEqual(
            self.__kwarg_or_value(kwargs, "min_coupling", 2),
            sProblem.stats["min_coupling"],
        )

        uri = await sProblem.upload(ws)
        data = await sProblem.download()
        uploaded = json.loads(data.serialize())
        local = json.loads(rProblem.serialize())
        self.assertEqual(uploaded, local)
Exemplo n.º 4
0
 def test_deserialize(self):
     count = 2
     terms = []
     for i in range(count):
         terms.append(Term(c=i, indices=[i, i + 1]))
     problem = Problem(name="test", terms=terms)
     deserialized = Problem.deserialize(problem.serialize(), problem.name)
     self.assertEqual(problem.name, deserialized.name)
     self.assertEqual(problem.problem_type, deserialized.problem_type)
     self.assertEqual(count, len(deserialized.terms))
     self.assertEqual(problem.init_config, deserialized.init_config)
     self.assertEqual(Term(c=0, indices=[0, 1]), problem.terms[0])
     self.assertEqual(Term(c=1, indices=[1, 2]), problem.terms[1])
Exemplo n.º 5
0
    def create_problem(
        self,
        name: str,
        init: bool = False,
        problem_type: ProblemType = ProblemType.pubo,
    ) -> Problem:
        """Create optimization problem with some default terms

        :param init: Set initial configuration
        :type init: bool
        :return: Optimization problem
        :rtype: Problem
        """
        terms = [
            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]),
        ]

        initial_config = {"1": 0, "0": 1, "2": 0, "3": 1} if init \
                         else None

        return Problem(
            name=name,
            terms=terms,
            init_config=initial_config,
            problem_type=problem_type,
        )
Exemplo n.º 6
0
    async def download(self):
        """Downloads the uploaded problem as an instance of `Problem`"""
        if not self.uploaded_uri:
            raise Exception(
                "StreamingProblem may not be downloaded before it is uploaded")

        coords = await self._get_upload_coords()
        blob = coords["container_client"].get_blob_client(coords["blob_name"])
        contents = await download_blob(blob.url)
        return Problem.deserialize(contents, self.name)
Exemplo n.º 7
0
    def test_provide_cterms(self):
        count = 4
        terms = []
        for i in range(count):
            terms.append(Term(c=i, indices=[i, i + 1]))
        problem = Problem(name="test",
                          terms=terms,
                          problem_type=ProblemType.pubo)

        self.assertEqual(ProblemType.pubo, problem.problem_type)
        self.assertEqual(count, len(problem.terms))
        self.assertEqual(Term(c=1, indices=[1, 2]), problem.terms[1])
Exemplo n.º 8
0
def problem():
    ## QUBO problem
    problem = Problem(name="test")
    problem.terms = [
        Term(c=3, indices=[1, 0]),
        Term(c=5, indices=[2, 0]),
    ]
    problem.uploaded_blob_uri = "mock_blob_uri"

    # Create equivalent NPZ file for translation
    problem.row = numpy.array([1, 2])
    problem.col = numpy.array([0, 0])
    problem.data = numpy.array([3, 5])
    return problem
Exemplo n.º 9
0
def pubo_problem():
    ## PUBO problem
    pubo_problem = Problem(name="test")
    pubo_problem.terms = [
        Term(c=3, indices=[1, 0, 1]),
        Term(c=5, indices=[2, 0, 0]),
        Term(c=-1, indices=[1, 0, 0]),
        Term(c=4, indices=[0, 2, 1])
    ]

    # Create equivalent NPZ file for translation
    pubo_problem.i = numpy.array([1, 2, 1, 0])
    pubo_problem.j = numpy.array([0, 0, 0, 2])
    pubo_problem.k = numpy.array([1, 0, 0, 1])
    pubo_problem.c = numpy.array([3, 5, -1, 4])
    return pubo_problem
Exemplo n.º 10
0
    def test_add_terms_cterms(self):
        problem = Problem(name="test")
        count = 4

        for i in range(count):
            problem.add_term(c=i, indices=[i, i + 1])
        self.assertEqual(ProblemType.ising, problem.problem_type)
        self.assertEqual(count, len(problem.terms))
        self.assertEqual(Term(c=1, indices=[1, 2]), problem.terms[1])

        more = []
        for i in range(count + 1):
            more.append(Term(c=i, indices=[i, i - 1]))
        problem.add_terms(more)
        self.assertEqual((count * 2) + 1, len(problem.terms))
        self.assertEqual(Term(c=count, indices=[count, count - 1]),
                         problem.terms[count * 2])
Exemplo n.º 11
0
def test_get_term_raise_exception():
    test_prob = Problem(name="random")
    with pytest.raises(Exception):
        test_prob.get_terms(id=0)
Exemplo n.º 12
0
    def test_problem_large(self):
        problem = Problem(name="test", terms=[], problem_type=ProblemType.pubo)
        self.assertTrue(not problem.is_large())

        problem.add_term(5.0, [])
        self.assertTrue(not problem.is_large())

        problem.add_term(6.0, list(range(3000)))
        self.assertTrue(not problem.is_large())

        problem.add_terms([Term(indices=[9999], c=1.0)] *
                          int(1e6))  # create 1mil dummy terms
        self.assertTrue(problem.is_large())
Exemplo n.º 13
0
    def test_problem_fixed_variables(self):
        terms = []
        problem = Problem(name="test",
                          terms=terms,
                          problem_type=ProblemType.pubo)
        problem_new = problem.set_fixed_variables({"0": 1})
        self.assertEqual([], problem_new.terms)

        # test small cases
        terms = [Term(c=10, indices=[0, 1, 2]), Term(c=-5, indices=[1, 2])]
        problem = Problem(name="test",
                          terms=terms,
                          problem_type=ProblemType.pubo)
        self.assertEqual([], problem.set_fixed_variables({"1": 0}).terms)
        self.assertEqual(
            [Term(c=10, indices=[0]),
             Term(c=-5, indices=[])],
            problem.set_fixed_variables({
                "1": 1,
                "2": 1
            }).terms,
        )

        # test all const terms get merged
        self.assertEqual(
            [Term(c=5, indices=[])],
            problem.set_fixed_variables({
                "0": 1,
                "1": 1,
                "2": 1
            }).terms,
        )

        # test init_config gets transferred
        problem = Problem("My Problem",
                          terms=terms,
                          init_config={
                              "0": 1,
                              "1": 1,
                              "2": 1
                          })
        problem2 = problem.set_fixed_variables({"0": 0})
        self.assertEqual({"1": 1, "2": 1}, problem2.init_config)
Exemplo n.º 14
0
    def test_problem_evaluate(self):
        terms = []
        problem = Problem(name="test",
                          terms=terms,
                          problem_type=ProblemType.pubo)
        self.assertEqual(0, problem.evaluate({}))
        self.assertEqual(0, problem.evaluate({"0": 1}))

        terms = [Term(c=10, indices=[0, 1, 2])]
        problem = Problem(name="test",
                          terms=terms,
                          problem_type=ProblemType.pubo)
        self.assertEqual(0, problem.evaluate({"0": 0, "1": 1, "2": 1}))
        self.assertEqual(10, problem.evaluate({"0": 1, "1": 1, "2": 1}))

        problem = Problem(name="test",
                          terms=terms,
                          problem_type=ProblemType.ising)
        self.assertEqual(-10, problem.evaluate({"0": -1, "1": 1, "2": 1}))
        self.assertEqual(10, problem.evaluate({"0": -1, "1": -1, "2": 1}))

        terms = [Term(c=10, indices=[0, 1, 2]), Term(c=-5, indices=[1, 2])]
        problem = Problem(name="test",
                          terms=terms,
                          problem_type=ProblemType.pubo)
        self.assertEqual(-5, problem.evaluate({"0": 0, "1": 1, "2": 1}))
        self.assertEqual(5, problem.evaluate({"0": 1, "1": 1, "2": 1}))

        terms = [Term(c=10, indices=[])]  # constant term
        problem = Problem(name="test",
                          terms=terms,
                          problem_type=ProblemType.pubo)
        self.assertEqual(10, problem.evaluate({}))
Exemplo n.º 15
0
async def test_submit_problem(testsolver):
    problem = Problem(name="test", terms=[])
    with patch("azure.quantum.aio.job.base_job.upload_blob") as mock_upload:
        job = await testsolver.submit(problem)
    mock_upload.assert_called_once()
    testsolver.workspace.submit_job.assert_called_once()