コード例 #1
0
    def test_tile_around_edge_defects_pegasus(self):
        pegasus_shape = [5]

        # P5 structured sampler with one missing external edge that does not p
        # prevent tesselation of 2x2 blocks (12 tiles, equivalent to full yield)
        broken_edges_nice_coordinates = [(0, 1, 0, 0, 0), (0, 2, 0, 0, 0)]
        broken_edges = [
            tuple(
                dnx.pegasus_coordinates(pegasus_shape[0]).nice_to_linear(coord)
                for coord in broken_edges_nice_coordinates)
        ]
        mock_sampler = MockDWaveSampler(topology_type='pegasus',
                                        topology_shape=pegasus_shape,
                                        broken_edges=broken_edges)
        sampler = TilingComposite(mock_sampler, 2, 2, 4)
        self.assertTrue(len(sampler.embeddings) == 12)

        # P5 structured sampler with one missing internal edge that prevents
        # tesselation of 2x2 blocks (otherwise 12 tiles, with edge defect 11)
        broken_edge_nice_coordinates = [(0, 0, 0, 0, 0), (0, 0, 0, 1, 0)]
        broken_edges = [
            tuple(
                dnx.pegasus_coordinates(pegasus_shape[0]).nice_to_linear(coord)
                for coord in broken_edge_nice_coordinates)
        ]
        mock_sampler = MockDWaveSampler(topology_type='pegasus',
                                        topology_shape=pegasus_shape,
                                        broken_edges=broken_edges)
        sampler = TilingComposite(mock_sampler, 2, 2, 4)
        self.assertTrue(len(sampler.embeddings) == 11)
コード例 #2
0
    def test_smoke(self):
        child_sampler = MockDWaveSampler()
        sampler = VirtualGraphComposite(child_sampler, {'a': [0]},
                                        flux_bias_num_reads=1)

        # depending on how recenlty flux bias data was gathered, this may be true
        child_sampler.flux_biases_flag = False

        if sampler.flux_biases:
            sampler.sample_ising({'a': -1}, {})
            self.assertTrue(
                child_sampler.flux_biases_flag
            )  # true when some have been provided to sample_ising
コード例 #3
0
    def test_pegasus_multi_cell(self):
        #Test case of 2x3 cell embedding over defect free
        mock_sampler = MockDWaveSampler(
            topology_type='pegasus',
            topology_shape=[8])  # P8 structured sampler
        self.assertTrue('topology' in mock_sampler.properties
                        and 'type' in mock_sampler.properties['topology'])
        self.assertTrue(
            mock_sampler.properties['topology']['type'] == 'pegasus'
            and 'shape' in mock_sampler.properties['topology'])
        sampler = TilingComposite(mock_sampler, 1, 1)
        h = {
            node: random.uniform(-1, 1)
            for node in sampler.structure.nodelist
        }
        J = {(u, v): random.uniform(-1, 1)
             for u, v in sampler.structure.edgelist}

        m_sub = 2
        n_sub = 3
        sampler = TilingComposite(mock_sampler, m_sub, n_sub)
        h = {
            node: random.uniform(-1, 1)
            for node in sampler.structure.nodelist
        }
        J = {(u, v): random.uniform(-1, 1)
             for u, v in sampler.structure.edgelist}

        m = n = mock_sampler.properties['topology']['shape'][0] - 1
        expected_number_of_cells = (m // m_sub) * (n // 3) * 3
        num_reads = 1
        response = sampler.sample_ising(h, J, num_reads=num_reads)
        self.assertTrue(
            sum(response.record.num_occurrences) == expected_number_of_cells *
            num_reads)
コード例 #4
0
    def test_tile_around_hole(self):

        # Create a chimera graph with the following structure:
        # OOOX
        # OOOO
        # OOOO
        # OOOO
        # where O: complete cell, X: incomplete cell
        mock_sampler = MockDWaveSampler(broken_nodes=[8 * 3])  # C4 structured sampler with a node missing
        hardware_graph = dnx.chimera_graph(4)  # C4

        sampler = TilingComposite(mock_sampler, 2, 2, 4)
        # Given the above chimera graph, check that the embeddings are as follows:
        # 00XX
        # 0011
        # 2211
        # 22XX
        # where 0,1,2: belongs to correspoding embedding, X: not used in any embedding
        self.assertSetEqual({v for s in sampler.embeddings[0].values() for v in s},
                            {linear_index for linear_index, (i, j, u, k)
                             in hardware_graph.nodes(data='chimera_index')
                             if i in (0, 1) and j in (0, 1)})
        self.assertSetEqual({v for s in sampler.embeddings[1].values() for v in s},
                            {linear_index for linear_index, (i, j, u, k)
                             in hardware_graph.nodes(data='chimera_index')
                             if i in (1, 2) and j in (2, 3)})
        self.assertSetEqual({v for s in sampler.embeddings[2].values() for v in s},
                            {linear_index for linear_index, (i, j, u, k)
                             in hardware_graph.nodes(data='chimera_index')
                             if i in (2, 3) and j in (0, 1)})
コード例 #5
0
    def test_max_cut(self):
        sampler = EmbeddingComposite(MockDWaveSampler())

        m = 2
        n = 2
        t = 2

        hoff = 2 * t
        voff = n * hoff
        mi = m * voff
        ni = n * hoff

        edges = []

        # tile edges
        edges.extend((k0, k1) for i in range(0, ni, hoff)
                     for j in range(i, mi, voff) for k0 in range(j, j + t)
                     for k1 in range(j + t, j + 2 * t))
        # horizontal edges
        edges.extend((k, k + hoff) for i in range(t, 2 * t)
                     for j in range(i, ni - hoff, hoff)
                     for k in range(j, mi, voff))
        # vertical edges
        edges.extend((k, k + voff) for i in range(t)
                     for j in range(i, ni, hoff)
                     for k in range(j, mi - voff, voff))

        J = {edge: 1 for edge in edges}
        h = {v: 0 for v in set().union(*J)}

        response = sampler.sample_ising(h, J)
コード例 #6
0
    def test_sample_instantiation(self):
        # Check that graph related values have not been instantiated
        sampler = LazyFixedEmbeddingComposite(MockDWaveSampler())
        self.assertIsNone(sampler.embedding)
        self.assertIsNone(sampler.nodelist)
        self.assertIsNone(sampler.edgelist)
        self.assertIsNone(sampler.adjacency)

        # Set up an and_gate BQM and sample
        Q = {
            ('a', 'a'): 0.0,
            ('c', 'c'): 6.0,
            ('b', 'b'): 0.0,
            ('b', 'a'): 2.0,
            ('c', 'a'): -4.0,
            ('c', 'b'): -4.0
        }
        sampler.sample_qubo(Q)

        # Check that values have been populated
        self.assertIsNotNone(sampler.embedding)
        self.assertEqual(sampler.nodelist, ['a', 'b', 'c'])
        self.assertEqual(sampler.edgelist, [('a', 'b'), ('a', 'c'),
                                            ('b', 'c')])
        self.assertEqual(sampler.adjacency, {
            'a': {'b', 'c'},
            'b': {'a', 'c'},
            'c': {'a', 'b'}
        })
コード例 #7
0
    def test_tile_around_node_defects_pegasus(self):
        pegasus_shape = [5]
        # Create a pegasus P5 structured solver subject to node defects with the
        # following (nice-coordinate) 3x4x4 cell-level structure:
        # OOOX OOOO OOOO
        # OOOO OOOO OOOO
        # OOOO OOOO OOOO
        # OOOO OOOO OOOX
        # where O: complete cell, X: incomplete cell
        broken_node_nice_coordinates = [(0, 0, 3, 0, 1), (2, 3, 3, 1, 3)]
        broken_node_linear_coordinates = [
            dnx.pegasus_coordinates(pegasus_shape[0]).nice_to_linear(coord)
            for coord in broken_node_nice_coordinates
        ]
        mock_sampler = MockDWaveSampler(
            topology_type='pegasus',
            topology_shape=pegasus_shape,
            broken_nodes=broken_node_linear_coordinates)
        # Tile with 2x2 cells:
        sampler = TilingComposite(mock_sampler, 2, 2, 4)

        # Given the above pegasus graph, check that the embeddings are as
        # follows:
        # 00XX  3344 7788
        # 0011  3344 7788
        # 2211  5566 99XX
        # 22XX  5566 99XX

        # Check correct number of embeddings and size of each is sufficient,
        # given chimera test checks detailed position:
        self.assertTrue(len(sampler.embeddings) == 10)
        self.assertFalse(any([len(emb) != 32 for emb in sampler.embeddings]))
コード例 #8
0
 def test_pegasus_topology(self):
     grid_parameter = 4
     sampler = MockDWaveSampler(topology_type='pegasus',
                                topology_shape=[grid_parameter])
     # P4 fabric only has 264 nodes
     self.assertTrue(len(sampler.nodelist) == 264)
     dit.assert_sampler_api(sampler)
     dit.assert_structured_api(sampler)
コード例 #9
0
    def test_ising_sample(self):
        h = {'a': 1, 'b': -2}
        J = {('a', 'b'): -3}
        sampler = LazyFixedEmbeddingComposite(MockDWaveSampler())
        response = sampler.sample_ising(h, J)

        # Check that at least one response was found
        self.assertGreaterEqual(len(response), 1)
コード例 #10
0
    def test_instantiation_triangle(self):
        embedding = {'a': [0, 4], 'b': [1, 5], 'c': [2, 6]}
        sampler = FixedEmbeddingComposite(MockDWaveSampler(), embedding)
        self.assertEqual(embedding, sampler.embedding)

        dtest.assert_sampler_api(sampler)  # checks adj consistent with nodelist/edgelist

        self.assertEqual(sampler.nodelist, ['a', 'b', 'c'])
        self.assertEqual(sampler.edgelist, [('a', 'b'), ('a', 'c'), ('b', 'c')])
コード例 #11
0
    def test_instantiation_empty_adjacency(self):
        sampler = FixedEmbeddingComposite(MockDWaveSampler(), source_adjacency={})

        dtest.assert_sampler_api(sampler)  # checks for attributes needed in a sampler

        self.assertEqual(sampler.edgelist, [])

        self.assertTrue(hasattr(sampler, 'embedding'))
        self.assertIn('embedding', sampler.properties)
コード例 #12
0
    def test_instantiation_empty_embedding(self):
        sampler = FixedEmbeddingComposite(MockDWaveSampler(), {})

        dtest.assert_sampler_api(sampler)  # checks adj consistent with nodelist/edgelist

        self.assertEqual(sampler.edgelist, [])

        self.assertTrue(hasattr(sampler, 'embedding'))
        self.assertIn('embedding', sampler.properties)
コード例 #13
0
    def test_sample_ising(self):
        mock_sampler = MockDWaveSampler()  # C4 structured sampler

        sampler = TilingComposite(mock_sampler, 2, 2)

        h = {node: random.uniform(-1, 1) for node in sampler.structure.nodelist}
        J = {(u, v): random.uniform(-1, 1) for u, v in sampler.structure.edgelist}

        response = sampler.sample_ising(h, J)
コード例 #14
0
 def test_basic_operation(self):
     bqm = dimod.BinaryQuadraticModel({}, {
         'ab': 1,
         'bc': 1,
         'ca': 1
     }, 0, dimod.SPIN)
     sampleset = KerberosSampler().sample(bqm,
                                          qpu_sampler=MockDWaveSampler(),
                                          max_subproblem_size=1)
コード例 #15
0
    def test_singleton_variables(self):
        sampler = EmbeddingComposite(MockDWaveSampler())

        h = {0: -1., 4: 2}
        J = {}

        response = sampler.sample_ising(h, J)

        # nothing failed and we got at least one response back
        self.assertGreaterEqual(len(response), 1)
コード例 #16
0
    def test_sample_bqm_triangle(self):
        sampler = FixedEmbeddingComposite(MockDWaveSampler(), {
            'a': [0, 4],
            'b': [1, 5],
            'c': [2, 6]
        })

        resp = sampler.sample_ising({'a': 1, 'b': 1, 'c': 0}, {})

        self.assertEqual(set(resp.variables), {'a', 'b', 'c'})
コード例 #17
0
    def test_adjacency(self):
        square_adj = {1: [2, 3], 2: [1, 4], 3: [1, 4], 4: [2, 3]}
        sampler = FixedEmbeddingComposite(MockDWaveSampler(), source_adjacency=square_adj)

        self.assertTrue(hasattr(sampler, 'adjacency'))
        self.assertTrue(hasattr(sampler, 'embedding'))
        self.assertIn('embedding', sampler.properties)

        self.assertEqual(sampler.nodelist, [1, 2, 3, 4])
        self.assertEqual(sampler.edgelist, [(1, 2), (1, 3), (2, 4), (3, 4)])
コード例 #18
0
    def test_deprecation_raise(self):
        # Temporarily mutate warnings filter
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")  # Cause all warnings to always be triggered.
            LazyEmbeddingComposite(MockDWaveSampler())  # Trigger warning

            # Verify deprecation warning
            assert len(w) == 1
            assert issubclass(w[-1].category, DeprecationWarning)
            assert "renamed" in str(w[-1].message)
コード例 #19
0
    def test_structured_child_sampler(self):
        q = QPUSubproblemAutoEmbeddingSampler(qpu_sampler=MockDWaveSampler())

        # test sampler is converted to unstructured
        self.assertFalse(isinstance(q.sampler, dimod.Structured))

        # test sampling works
        bqm = dimod.BinaryQuadraticModel({'a': 1}, {}, 0, 'SPIN')
        init = State.from_subsample({'a': 1}, bqm)
        res = q.run(init).result()
        self.assertEqual(res.subsamples.first.energy, -1)
コード例 #20
0
 def test_with_embedding_and_adjacency(self):
     self.assertRaises(
         TypeError, lambda: FixedEmbeddingComposite(MockDWaveSampler(), {
             'a': [0, 4],
             'b': [1],
             'c': [5]
         }, {
             'a': ['b', 'c'],
             'b': ['a', 'c'],
             'c': ['a', 'b']
         }))
コード例 #21
0
 def test_chimera_topology(self):
     grid_parameter = 5
     tile_parameter = 2
     sampler = MockDWaveSampler(
         topology_type='chimera',
         topology_shape=[grid_parameter, grid_parameter, tile_parameter])
     # C5 (shore 2) fabric only has 200 nodes
     self.assertTrue(
         len(sampler.nodelist) == grid_parameter * grid_parameter *
         tile_parameter * 2)
     dit.assert_sampler_api(sampler)
     dit.assert_structured_api(sampler)
コード例 #22
0
    def test_problem_labelling(self):
        sampler = self.embedding_composite_class(MockDWaveSampler())

        self.assertIn('label', sampler.parameters)

        ss = sampler.sample_ising({}, {(0, 1): -1})
        self.assertNotIn('problem_label', ss.info)

        label = 'problem label'
        ss = sampler.sample_ising({}, {(0, 1): -1}, label=label)
        self.assertIn('problem_label', ss.info)
        self.assertEqual(ss.info['problem_label'], label)
コード例 #23
0
 def test_zephyr_topology(self):
     grid_parameter = 3
     tile_parameter = 4
     sampler = MockDWaveSampler(
         topology_type='zephyr',
         topology_shape=[grid_parameter, tile_parameter])
     # P4 fabric only has 264 nodes
     self.assertTrue(
         len(sampler.nodelist) == tile_parameter * grid_parameter *
         (8 * grid_parameter + 4))
     dit.assert_sampler_api(sampler)
     dit.assert_structured_api(sampler)
コード例 #24
0
 def test_concrete_runnables(self):
     # composers
     self.assertEqual(self.children(IdentityComposer()), [])
     self.assertEqual(self.children(SplatComposer()), [])
     # sample of samplers
     self.assertEqual(self.children(QPUSubproblemAutoEmbeddingSampler(qpu_sampler=MockDWaveSampler())), [])
     self.assertEqual(self.children(SimulatedAnnealingSubproblemSampler()), [])
     self.assertEqual(self.children(TabuProblemSampler()), [])
     # sample of decomposers
     self.assertEqual(self.children(IdentityDecomposer()), [])
     self.assertEqual(self.children(EnergyImpactDecomposer(size=1)), [])
     self.assertEqual(self.children(RandomSubproblemDecomposer(size=1)), [])
コード例 #25
0
    def test_chain_break_method_customization(self):
        sampler = LazyFixedEmbeddingComposite(MockDWaveSampler())

        with mock.patch('dwave.system.composites.embedding.unembed_sampleset'
                        ) as mock_unembed:
            sampler.sample_ising({'a': 1}, {},
                                 chain_break_method=chain_breaks.discard)

            # assert chain_break_method propagated to unembed_sampleset
            __, kwargs = mock_unembed.call_args
            self.assertEqual(kwargs['chain_break_method'],
                             chain_breaks.discard)
コード例 #26
0
    def test_sparse_qubo(self):
        # There is no relationship between nodes 2 and 3
        Q = {(1, 1): 1, (2, 2): 2, (3, 3): 3, (1, 2): 4, (1, 3): 6}
        sampler = LazyFixedEmbeddingComposite(MockDWaveSampler())
        response = sampler.sample_qubo(Q)

        # Check embedding
        self.assertIsNotNone(sampler.embedding)
        self.assertEqual(sampler.nodelist, [1, 2, 3])
        self.assertEqual(sampler.edgelist, [(1, 2), (1, 3)])

        # Check that at least one response was found
        self.assertGreaterEqual(len(response), 1)
コード例 #27
0
    def test_qubo(self):
        Q = {(1, 1): 1, (2, 2): 2, (3, 3): 3, (1, 2): 4, (2, 3): 5, (1, 3): 6}
        sampler = LazyFixedEmbeddingComposite(MockDWaveSampler())
        response = sampler.sample_qubo(Q)

        # Check embedding
        self.assertIsNotNone(sampler.embedding)
        self.assertEqual(sampler.nodelist, [1, 2, 3])
        self.assertEqual(sampler.edgelist, [(1, 2), (1, 3), (2, 3)])
        self.assertEqual(sampler.adjacency, {1: {2, 3}, 2: {1, 3}, 3: {1, 2}})

        # Check that at least one response was found
        self.assertGreaterEqual(len(response), 1)
コード例 #28
0
    def test_too_many_nodes(self):
        mock_sampler = MockDWaveSampler()  # C4 structured sampler

        sampler = TilingComposite(mock_sampler, 2, 2)

        h = {0: -1, 1: 1}
        J = {}

        response = sampler.sample_ising(h, J)

        __, num_columns = response.record.sample.shape

        self.assertEqual(num_columns, 2)
コード例 #29
0
    def test_ising(self):
        h = {0: 11, 5: 2}
        J = {(0, 5): -8}
        sampler = LazyFixedEmbeddingComposite(MockDWaveSampler())
        response = sampler.sample_ising(h, J)

        # Check embedding
        self.assertIsNotNone(sampler.embedding)
        self.assertEqual(sampler.nodelist, [0, 5])
        self.assertEqual(sampler.edgelist, [(0, 5)])
        self.assertEqual(sampler.adjacency, {0: {5}, 5: {0}})

        # Check that at least one response was found
        self.assertGreaterEqual(len(response), 1)
コード例 #30
0
    def test_chain_break_method_customization(self):
        sampler = LazyFixedEmbeddingComposite(MockDWaveSampler())

        def mock_unembed(*args, **kwargs):
            self.assertIn('chain_break_method', kwargs)
            self.assertEqual(kwargs['chain_break_method'], chain_breaks.discard)
            mock_unembed.call_count += 1
            return dwave.embedding.unembed_sampleset(*args, **kwargs)

        mock_unembed.call_count = 0

        with mock.patch('dwave.system.composites.embedding.unembed_sampleset', mock_unembed):
            sampler.sample_ising({'a': 1}, {}, chain_break_method=chain_breaks.discard).resolve()

        self.assertEqual(mock_unembed.call_count, 1)