예제 #1
0
    def test_dimod_vs_list(self):
        G = nx.path_graph(5)

        matching = dnx.min_maximal_matching(G, ExactSolver())
        matching = dnx.algorithms.matching.maximal_matching(G, ExactSolver())
        matching = dnx.min_maximal_matching(G, SimulatedAnnealingSampler())
        matching = dnx.algorithms.matching.maximal_matching(
            G, SimulatedAnnealingSampler())
예제 #2
0
    def __init__(self,
                 objective_function=None,
                 dwave_sampler=None,
                 dwave_sampler_kwargs=None,
                 experiment_type=None,
                 population_size=1,
                 num_reads=1,
                 num_iters=None):
        super().__init__(objective_function=objective_function)

        self.n_obj = self.objective_function.n

        self.n_qubo = self.n_obj - 1
        self.dwave_solver = None
        self.sampler_kwargs = None
        self.qpu = False
        self.population_size = population_size
        self.num_reads = num_reads

        # Initialize dwave sampler:
        if dwave_sampler == 'QPU':
            self.dwave_solver = EmbeddingComposite(DWaveSampler())
            self.qpu = True
            if dwave_sampler_kwargs:
                self.sampler_kwargs = dwave_sampler_kwargs
            else:
                self.sampler_kwargs = dict()
        elif dwave_sampler == 'SA':
            self.dwave_solver = SimulatedAnnealingSampler()
            if num_reads:
                self.sampler_kwargs = {'num_reads': num_reads}
            else:
                self.sampler_kwargs = {'num_reads': 25}
        elif dwave_sampler == 'Tabu':
            self.dwave_solver = TabuSampler()
            if num_reads:
                self.sampler_kwargs = {'num_reads': num_reads}
            else:
                self.sampler_kwargs = {'num_reads': 250}

        self.stopwatch = 0

        if experiment_type == 'time_lim':
            self.n_iters = 1000
            self.time_limit = 30

        if experiment_type == 'iter_lim' and num_iters:
            self.n_iters = num_iters
            self.time_limit = False
        else:
            self.n_iters = 50
            self.time_limit = False

        self.form_qubo = NewLQUBO(objective_function=self.objective_function)

        self.solution = self.objective_function.min_v
예제 #3
0
    def test_bug1(self):
        # IN IN OUT AUX
        h = {0: -.5, 1: 0, 2: 1, 3: -.5}
        J = {(0, 2): -1, (1, 2): -1, (0, 3): .5, (1, 3): -1}

        J[(0, 4)] = -.1
        J[(4, 5)] = -.1
        J[(5, 6)] = -.1
        h[4] = 0
        h[5] = 0
        h[6] = .1

        response = SimulatedAnnealingSampler().sample_ising(h, J, num_samples=100)
예제 #4
0
    def __init__(self,
                 objective_function=None,
                 dwave_sampler=None,
                 dwave_sampler_kwargs=None):
        super().__init__(objective_function=objective_function)

        self.n = self.objective_function.n
        self.flow = self.objective_function.flow
        self.dist = self.objective_function.dist
        self.qpu = False

        # Initialize dwave sampler:
        if dwave_sampler:
            self.qpu = True
            self.dwave_solver = dwave_sampler
            if dwave_sampler_kwargs:
                self.sampler_kwargs = dwave_sampler_kwargs
            else:
                self.sampler_kwargs = dict()
        else:
            self.dwave_solver = SimulatedAnnealingSampler()
            self.sampler_kwargs = {
                'num_reads': 10
            }

        self.solution = self.objective_function.min_v

        if type(self.dwave_solver) == SimulatedAnnealingSampler:
            self.iteration_number = 10
        else:
            self.iteration_number = 1

        self.OF_tracker = np.zeros(self.iteration_number)

        self.energy = None
        self.sample = None
예제 #5
0
def doMaxCut(G,
             numMaxCutUBNodes=1,
             numLBs=2,
             numMinCutUBNodes=1,
             maxLmtNodes=1024,
             numIterMaxCut=1,
             numIterMinCut=1,
             mode=SA):
    '''
        Do max cut.
        @param G: Graph model instance of networkx.
        @param numMaxCutUBNodes: Number of a max cut upper bound' nodes.
        @param numLBs: Number of low bounds set.
        @param numMinCutUBNodes: Number of a min cut upper bound' nodes.
        @param maxLmtNodes: Maximum number of nodes of a low bound.
        @param numIterMaxCut: Number of iteration for max cut.
        @param numIterMinCut: Number of iteration for min cut.
        @param mode: SA or QA.
    '''

    biVarVals = np.zeros((G.number_of_nodes()),
                         dtype=np.int64)  # Zero index based.

    # Make a node index map.
    i2n = list(G.nodes)  # Key order of dictionary. Nodes not sorted.
    n2i = dict()

    for i, n in enumerate(i2n):
        n2i[n] = i

    # Get low bounds via minimum cut.
    LBs, UBNodes = getLowBoundsViaSAQABasedMinCut(
        G,
        numMaxCutUBNodes=numMaxCutUBNodes,
        numLBs=numLBs,
        numMinCutUBNodes=numMinCutUBNodes,
        maxLmtNodes=maxLmtNodes,
        numIter=numIterMinCut,
        mode=mode)

    # Get indexes of the upper bound's values for each graph.
    ubIdxes = [[] for _ in range(len(LBs))]

    for ub in UBNodes:
        for i, g in enumerate(LBs):
            ubIdxes[i].append((np.asarray(list(
                g.nodes)) == ub).nonzero()[0][0])  # Nodes not sorted.

    biVarVals[[n2i[n] for n in UBNodes]] = 1

    # Conduct max cut.
    for i in range(numIterMaxCut):
        if mode == SA:
            for k, tG in enumerate(LBs):

                # Make a node index map.
                pi2n = list(
                    tG.nodes)  # Key order of dictionary. Nodes not sorted.
                pn2i = dict()

                for i, n in enumerate(pi2n):
                    pn2i[n] = i

                # Calculate Q for a vertex set.
                vSet = set(list(tG.nodes))
                Q = QUBO(len(vSet))

                # Apply objective and constraint conditions.
                # Objective
                vEdgeSet = set(list(G.getEdgesForNodes(list(vSet))))

                for i in range(len(vSet)):
                    for j in range(i + 1, len(vSet)):
                        q_ij = 1 if vEdgeSet.issuperset(set(
                            [(i, j)])) else 0  # i, j order?

                        # q_ij(x_i + x_j - 2x_ix_j).
                        Q.addCoeff(i, i, -1 * q_ij)
                        Q.addCoeff(j, j, -1 * q_ij)
                        Q.addCoeff(i, j, 2 * q_ij)

                # Constraint.
                if k > 0:
                    fixedVarsBeingOne \
                        = searchForFixedVarsAsOne(biVarVals, n2i, tG, LBs[k-1], G, ubIdxes[k])

                    for n in fixedVarsBeingOne:
                        Q.addCoeff(pn2i[n], pn2i[n], -1)
                        Q.addConstant(1)

                for ub in ubIdxes[k]:
                    Q.addCoeff(ub, ub, -1)
                    Q.addConstant(1)

                bqm = BinaryQuadraticModel.from_qubo(Q.getQDict(),
                                                     offset=Q.getOffset())

                print('Sample solutions via SA...')
                res = SimulatedAnnealingSampler().sample(bqm)
                res = res.record
                res = res.sample[res.energy == res.energy.min()]

                freq = {}
                for v in res:
                    freq[tuple(v)] = freq.get(tuple(v), 0) + 1

                maxFreqSol = list(freq)[np.argmax(
                    np.asarray(list(freq.values())))]

                # Update binary variable values.
                biVarVals[[
                    n2i[pi2n[idx - 1]] for idx, v in enumerate(maxFreqSol)
                    if v == 1
                ]] = 1  #?
        else:
            # Make a node index map.
            pi2n = list(tG.nodes)  # Key order of dictionary. Nodes not sorted.
            pn2i = dict()

            for i, n in enumerate(pi2n):
                pn2i[n] = i

            # Calculate Q for a vertex set.
            vSet = set(list(tG.nodes))
            Q = QUBO(len(vSet))

            # Apply objective and constraint conditions.
            # Objective
            vEdgeSet = set(list(G.getEdgesForNodes(list(vSet))))

            for i in range(len(vSet)):
                for j in range(i + 1, len(vSet)):
                    q_ij = 1 if vEdgeSet.issuperset(set(
                        [(i, j)])) else 0  # i, j order?

                    # q_ij(x_i + x_j - 2x_ix_j).
                    Q.addCoeff(i, i, -1 * q_ij)
                    Q.addCoeff(j, j, -1 * q_ij)
                    Q.addCoeff(i, j, 2 * q_ij)

            # Constraint.
            if k > 0:
                fixedVarsBeingOne \
                    = searchForFixedVarsAsOne(biVarVals, n2i, tG, LBs[k-1], G, ubIdxes[k])

                for n in fixedVarsBeingOne:
                    Q.addCoeff(pn2i[n], pn2i[n], -1)
                    Q.addConstant(1)

            for ub in ubIdxes[k]:
                Q.addCoeff(ub, ub, -1)
                Q.addConstant(1)

            bqm = BinaryQuadraticModel.from_qubo(Q.getQDict(),
                                                 offset=Q.getOffset())

            print('Sample solutions via QA...')
            sampler = EmbeddingComposite(
                DWaveSampler(endpoint='https://cloud.dwavesys.com/sapi',
                             token='xxx',
                             solver='DW_2000Q_2_1'))
            res = sampler.sample(bqm, num_reads=10)
            res = res.record
            res = res.sample[res.energy == res.energy.min()]

            freq = {}
            for v in res:
                freq[tuple(v)] = freq.get(tuple(v), 0) + 1

            maxFreqSol = list(freq)[np.argmax(np.asarray(list(freq.values())))]

            # Update binary variable values.
            biVarVals[[
                n2i[pi2n[idx - 1]] for idx, v in enumerate(maxFreqSol)
                if v == 1
            ]] = 1  #?

        #print(range(len(biVarVals)))
        #print(biVarVals)

        # Rotate LBs and ubIdxes right.
        LBs = [LBs[-1]] + LBs[:-1]
        ubIdxes = [ubIdxes[-1]] + ubIdxes[:-1]

    # Get group1, group2.
    group_1 = []
    group_2 = []

    for i, bit in enumerate(biVarVals):
        if bit == 0:
            group_1.append(i + 1)
        else:
            group_2.append(i + 1)

    # Calculate a max cut value.
    GG1 = G.copy()
    GG2 = G.copy()
    GG1.remove_nodes_from(np.asarray(group_2) - 1)
    GG2.remove_nodes_from(np.asarray(group_1) - 1)

    maxCutVal = calMaxCutVal([GG1, GG2], G)
    #print('Max cut value: ', maxCutVal)

    return group_1, group_2, maxCutVal
예제 #6
0
def getLowBoundsViaSAQABasedMinCut(G,
                                   numMaxCutUBNodes=1,
                                   numLBs=2,
                                   numMinCutUBNodes=1,
                                   maxLmtNodes=1024,
                                   numIter=1,
                                   mode=SA):
    '''
        Get low bounds via SA or QA based minimum cut.
        @param G: Graph model instance of networkx.
        @param numMaxCutUBNodes: Number of a max cut upper bound' nodes.
        @param numLBs: Number of low bounds set.
        @param numMinCutUBNodes: Number of a min cut upper bound' nodes.
        @param maxLmtNodes: Maximum number of nodes of a low bound.
        @param numIter: Number of iteration.
        @param mode: SA or QA.
    '''

    # Get an upper bound. Exception?
    maxCutUBNodes = []
    degrees = np.asarray(list(G.degree.values()))
    numNodes = len(degrees)

    for i in range(numMaxCutUBNodes):
        ubNode = degrees[np.argmax(degrees[:, 1]), 0]
        maxCutUBNodes.append(ubNode)
        degrees = degrees[degrees[:, 0] != ubNode]

    # Check exception. Exception?
    if numLBs == 1:
        maxCutLBs = [G]
        return maxCutLBs, maxCutUBNodes

    if (numNodes // numLBs + numNodes % numLBs \
        + numMaxCutUBNodes * numLBs) > maxLmtNodes:
        raise ValueError(
            'numNodes // numLBs + numNodes % numLBs + numMaxCutUBNodes * numLBs <= maxLmtNodes'
        )

    tG = G.copy()  # Graph without an upper bound's nodes.
    tG.remove_nodes_from(maxCutUBNodes)

    # Separate a graph into low bound graphs via digital annealing based minimum cut.
    # Get low bound graphs for minimum cut.
    minCutLBs = []
    numAssignedNodes = numNodes // numLBs - numMaxCutUBNodes  #?

    # Separate a graph randomly.
    for i in range(numLBs - 1):
        ttG = tG.copy()
        nodes1 = np.random.choice(np.asarray(list(tG.nodes)),
                                  numAssignedNodes,
                                  replace=False)
        tG.remove_nodes_from(nodes1)
        nodes2 = list(tG.nodes)
        ttG.remove_nodes_from(nodes2)
        minCutLBs.append(ttG)

    minCutLBs.append(tG)

    # Separate a graph according to the number of iteration
    # And get graphs having a minimum cut value.
    optMinCutLBs = []
    minCutValR = 1.0

    for i in range(numIter):
        for k in range(len(minCutLBs) - 1):

            # Get a pair of graphs.
            partMinCutLBs = [minCutLBs[k], minCutLBs[k + 1]]
            uG = Graph.union(partMinCutLBs[0], partMinCutLBs[1])

            # Get an upper bound. Exception?
            minCutUBNodes = []
            degrees = np.asarray(list(uG.degree.values()))
            numNodes = len(degrees)

            for _ in range(numMinCutUBNodes):
                ubNode = degrees[np.argmax(degrees[:, 1]), 0]
                minCutUBNodes.append(ubNode)
                degrees = degrees[degrees[:, 0] != ubNode]

            # Create a new pair of graphs.
            uuG = uG.copy()
            uuG.remove_nodes_from(minCutUBNodes)
            nodes1 = np.random.choice(np.asarray(list(uuG.nodes)),
                                      len(uuG.nodes) // 2,
                                      replace=False)
            uuG.remove_nodes_from(nodes1)
            nodes2 = np.asarray(list(uuG.nodes))

            partMinCutLBs[0] = uG.copy()
            partMinCutLBs[0].remove_nodes_from(nodes2)
            partMinCutLBs[1] = uG.copy()
            partMinCutLBs[1].remove_nodes_from(nodes1)

            # Conduct min cut.
            biVarVals = np.zeros((uG.number_of_nodes()),
                                 dtype=np.int64)  # Zero index based.

            # Make a node index map.
            i2n = list(uG.nodes)  # Key order of dictionary. Nodes not sorted.
            n2i = dict()

            for idx, n in enumerate(i2n):
                n2i[n] = idx

            # Get indexes of the upper bound's values for each graph.
            ubIdxes = [[], []]

            for ub in minCutUBNodes:
                ubIdxes[0].append((np.asarray(list(
                    partMinCutLBs[0].nodes)) == ub).nonzero()[0][0])
                ubIdxes[1].append((np.asarray(list(
                    partMinCutLBs[1].nodes)) == ub).nonzero()[0][0])

            biVarVals[[n2i[n] for n in minCutUBNodes]] = 1

            if mode == SA:
                for l, pG in enumerate(partMinCutLBs):

                    # Make a node index map.
                    pi2n = list(
                        pG.nodes)  # Key order of dictionary. Nodes not sorted.

                    vSet = set(list(pG.nodes))

                    # Calculate Q.
                    Q = QUBO(pG.number_of_nodes())

                    # Apply objective and constraint conditions.
                    # Objective
                    vEdgeSet = set(list(G.getEdgesForNodes(list(vSet))))

                    for i in range(len(vSet)):
                        for j in range(i + 1, len(vSet)):
                            q_ij = 1 if vEdgeSet.issuperset(set(
                                [(i, j)])) else 0  # i, j order?

                            # q_ij(x_i + x_j - 2x_ix_j).
                            Q.addCoeff(i, i, 1 * q_ij)
                            Q.addCoeff(j, j, 1 * q_ij)
                            Q.addCoeff(i, j, -2 * q_ij)

                    # Constraint.
                    '''
                    v1Vals = biVarVals[np.asarray(v1Set)] #?
                    v1ValsNZIdxs = (v1Vals == 1).nonzero()[0]
                    
                    for i in v1ValsNZIdxs:
                        Q1.addCoeff(i, i, 1)
                    '''
                    for i in range(len(vSet)):
                        Q.addCoeff(i, i, -1 * (2 * int(len(vSet) / 2) - 1))

                    for i in range(len(vSet)):
                        for j in range(i + 1, len(vSet)):
                            Q.addCoeff(i, j, 2)

                    Q.addConstant(int(np.power(len(vSet) / 2, 2)))

                    for ub in ubIdxes[l]:
                        Q.addCoeff(ub, ub, -1)
                        Q.addConstant(1)

                    bqm = BinaryQuadraticModel.from_qubo(Q.getQDict(),
                                                         offset=Q.getOffset())

                    print('Sample solutions via SA...')
                    res = SimulatedAnnealingSampler().sample(bqm)
                    res = res.record
                    res = res.sample[res.energy == res.energy.min()]

                    freq = {}
                    for v in res:
                        freq[tuple(v)] = freq.get(tuple(v), 0) + 1

                    maxFreqSol = list(freq)[np.argmax(
                        np.asarray(list(freq.values())))]

                    # Update binary variable values.
                    biVarVals[[
                        n2i[pi2n[idx]] for idx, v in enumerate(maxFreqSol)
                        if v == 1
                    ]] = 1  #?
            else:
                for l, pG in enumerate(partMinCutLBs):

                    # Make a node index map.
                    pi2n = list(
                        pG.nodes)  # Key order of dictionary. Nodes not sorted.

                    vSet = set(list(pG.nodes))

                    # Calculate Q.
                    Q = QUBO(pG.number_of_nodes())

                    # Apply objective and constraint conditions.
                    # Objective
                    vEdgeSet = set(list(G.getEdgesForNodes(list(vSet))))

                    for i in range(len(vSet)):
                        for j in range(i + 1, len(vSet)):
                            q_ij = 1 if vEdgeSet.issuperset(set(
                                [(i, j)])) else 0  # i, j order?

                            # q_ij(x_i + x_j - 2x_ix_j).
                            Q.addCoeff(i, i, 1 * q_ij)
                            Q.addCoeff(j, j, 1 * q_ij)
                            Q.addCoeff(i, j, -2 * q_ij)

                    # Constraint.
                    '''
                    v1Vals = biVarVals[np.asarray(v1Set)] #?
                    v1ValsNZIdxs = (v1Vals == 1).nonzero()[0]
                    
                    for i in v1ValsNZIdxs:
                        Q1.addCoeff(i, i, 1)
                    '''
                    for i in range(len(vSet)):
                        Q.addCoeff(i, i, -1 * (2 * int(len(vSet) / 2) - 1))

                    for i in range(len(vSet)):
                        for j in range(i + 1, len(vSet)):
                            Q.addCoeff(i, j, 2)

                    Q.addConstant(int(np.power(len(vSet) / 2, 2)))

                    for ub in ubIdxes[l]:
                        Q.addCoeff(ub, ub, -1)
                        Q.addConstant(1)

                    bqm = BinaryQuadraticModel.from_qubo(Q.getQDict(),
                                                         offset=Q.getOffset())

                    print('Sample solutions via QA...')
                    sampler = EmbeddingComposite(
                        DWaveSampler(
                            endpoint='https://cloud.dwavesys.com/sapi',
                            token='xxx',
                            solver='DW_2000Q_2_1'))
                    res = sampler.sample(bqm, num_reads=10)
                    res = res.record
                    res = res.sample[res.energy == res.energy.min()]

                    freq = {}
                    for v in res:
                        freq[tuple(v)] = freq.get(tuple(v), 0) + 1

                    maxFreqSol = list(freq)[np.argmax(
                        np.asarray(list(freq.values())))]

                    # Update binary variable values.
                    biVarVals[[
                        n2i[pi2n[idx]] for idx, v in enumerate(maxFreqSol)
                        if v == 1
                    ]] = 1  #?

            #print(range(len(biVarVals)))
            #print(biVarVals)

            # Get group1, group2.
            group_1 = []
            group_2 = []

            for idx, bit in enumerate(biVarVals):
                if bit == 0:
                    group_1.append(i2n[idx])
                else:
                    group_2.append(i2n[idx])

            minCutLBs[k] = uG.copy()
            minCutLBs[k].remove_nodes_from(group_2)
            minCutLBs[k + 1] = uG.copy()
            minCutLBs[k + 1].remove_nodes_from(group_1)

        # Calculate a min cut value.
        tG = G.copy()  # Graph without an upper bound's nodes.
        tG.remove_nodes_from(maxCutUBNodes)

        minCutVal = calMinCutVal(minCutLBs, tG)
        #print(minCutVal)

        # Select LBs with a less minimum cut value.
        if minCutVal[1] < minCutValR:
            optMinCutLBs = minCutLBs
            minCutValR = minCutVal[1]

        # Rotate minCutLBs right.
        minCutLBs = [minCutLBs[-1]] + minCutLBs[:-1]

    minCutLBs = optMinCutLBs

    # Adjust the number of a low bound's nodes into <= maxLmtNodes - numMaxCutUBNodes.
    for k, g in enumerate(minCutLBs):

        # Check the number of a low bound's nodes.
        if len(list(g.nodes)) + numMaxCutUBNodes > maxLmtNodes:
            numRemoveNodes = maxLmtNodes - (len(list(g.nodes)) +
                                            numMaxCutUBNodes)
        else:
            continue

        # Remove nodes randomly.
        rNodes = np.random.choice(np.asarray(list(g.nodes)),
                                  numRemoveNodes,
                                  replace=False)
        g.remove_nodes_from(rNodes)

    # Add maxCutUBNodes to each minCutLB.
    LBs = []
    for g in minCutLBs:
        tG = G.copy()
        tG.remove_nodes_from(list(g.nodes) + maxCutUBNodes)
        ttG = G.copy()
        ttG.remove_nodes_from(list(tG.nodes))
        LBs.append(ttG)  # Exception?

    for k, g in enumerate(LBs):
        print(k, len(g.nodes))  #?

    return LBs, maxCutUBNodes
예제 #7
0
    def test_dimod_vs_list(self):
        G = nx.path_graph(5)

        cover = dnx.min_vertex_cover(G, ExactSolver())
        cover = dnx.min_vertex_cover(G, SimulatedAnnealingSampler())
예제 #8
0
 def test_dimod_response_vs_list(self):
     # should be able to handle either a dimod response or a list of dicts
     G = dnx.chimera_graph(1, 1, 3)
     coloring = dnx.min_vertex_coloring(G, ExactSolver())
     coloring = dnx.min_vertex_coloring(G, SimulatedAnnealingSampler())
예제 #9
0
    def __init__(self,
                 objective_function=None,
                 dwave_sampler=None,
                 dwave_sampler_kwargs=None,
                 num_activation_vectors=None,
                 activation_vec_hamming_dist=1,
                 max_hd=None,
                 parse_samples=True,
                 experiment_type=None,
                 num_reads=None,
                 num_iters=None,
                 network_type='minimum'):
        super().__init__(objective_function=objective_function)

        # Initialize switch network:
        # The default behavior here is to choose the smaller of either permutation or
        # sorting networks for the given input size.
        self.n_obj = self.objective_function.n
        if network_type == 'sorting':
            self.network = SortingNetwork(self.n_obj)
        elif network_type == 'permutation':
            self.network = PermutationNetwork(self.n_obj)
        elif network_type == 'minimum':
            s = SortingNetwork(self.n_obj)
            p = PermutationNetwork(self.n_obj)
            if s.depth <= p.depth:
                self.network = s
            else:
                self.network = p
        else:
            raise TypeError('Network type {} not recognized'.format(str(network_type)))
        self.n_qubo = self.network.depth
        self.dwave_solver = None
        self.sampler_kwargs = None
        self.qpu = False

        # Initialize dwave sampler:
        if dwave_sampler == 'QPU':
            self.dwave_solver = EmbeddingComposite(DWaveSampler())
            self.qpu = True
            if dwave_sampler_kwargs:
                self.sampler_kwargs = dwave_sampler_kwargs
            else:
                self.sampler_kwargs = dict()
        elif dwave_sampler == 'SA':
            self.dwave_solver = SimulatedAnnealingSampler()
            if num_reads:
                self.sampler_kwargs = {
                    'num_reads': num_reads
                }
            else:
                self.sampler_kwargs = {
                    'num_reads': 25
                }
        elif dwave_sampler == 'Tabu':
            self.dwave_solver = TabuSampler()
            if num_reads:
                self.sampler_kwargs = {
                    'num_reads': num_reads
                }
            else:
                self.sampler_kwargs = {
                    'num_reads': 250
                }

        self.stopwatch = 0

        # Initialize type of experiment
        # When running a timed experiment there is a high number of iterations and a 30 sec wall clock
        # When running a iteration experiment there is a iteration limit of 30 and no wall clock
        if experiment_type == 'time_lim':
            self.n_iters = 1000
            self.time_limit = 30

        if experiment_type == 'iter_lim' and num_iters:
            self.n_iters = num_iters
            self.time_limit = False
        else:
            self.n_iters = 50
            self.time_limit = False

        if max_hd:
            self.max_hd = max_hd
        else:
            self.max_hd = 0

        if num_activation_vectors:
            self.num_activation_vec = num_activation_vectors
        else:
            self.num_activation_vec = self.n_qubo

        self.form_qubo = LQUBO(objective_function=self.objective_function,
                               switch_network=self.network,
                               max_hamming_dist=self.max_hd,
                               num_activation_vectors=self.num_activation_vec,
                               activation_vec_hamming_dist=activation_vec_hamming_dist)

        self.solution = self.objective_function.min_v

        if parse_samples:
            self.selection = CheckAndSelect
        else:
            self.selection = Select
예제 #10
0
class NaturalEncodingSolver(Solver):
    """
    This Natural Encoding solver is how QAP is normally formulated as a QUBO.  This requires a binary variable for every
    entry of the permutation matrix.  As it is set up, you can solve this formulation by using the D-Wave
    QPU or D-Wave Simulated Annealing.
    """

    def __init__(self,
                 objective_function=None,
                 dwave_sampler=None,
                 dwave_sampler_kwargs=None):
        super().__init__(objective_function=objective_function)

        self.n = self.objective_function.n
        self.flow = self.objective_function.flow
        self.dist = self.objective_function.dist
        self.qpu = False

        # Initialize dwave sampler:
        if dwave_sampler:
            self.qpu = True
            self.dwave_solver = dwave_sampler
            if dwave_sampler_kwargs:
                self.sampler_kwargs = dwave_sampler_kwargs
            else:
                self.sampler_kwargs = dict()
        else:
            self.dwave_solver = SimulatedAnnealingSampler()
            self.sampler_kwargs = {
                'num_reads': 10
            }

        self.solution = self.objective_function.min_v

        if type(self.dwave_solver) == SimulatedAnnealingSampler:
            self.iteration_number = 10
        else:
            self.iteration_number = 1

        self.OF_tracker = np.zeros(self.iteration_number)

        self.energy = None
        self.sample = None

    def minimize_objective(self):

        identity = np.identity(self.n)
        a = np.ones((self.n, self.n))
        np.fill_diagonal(a, 0)
        qap = np.kron(self.flow, self.dist)
        p = 1.5*np.amax(np.amax(qap))
        quadratic_penalty = p*np.kron(a, identity) + p*np.kron(identity, a) - 2*p*np.kron(identity, identity)
        natural_qubo = qap + quadratic_penalty
        additive_const = 2*self.n*p

        for i in range(self.n ** 2):  # makes the QUBO Upper triangular
            for j in range(self.n ** 2):
                if j > i:
                    natural_qubo[i][j] = 2 * natural_qubo[i][j]
                elif i > j:
                    natural_qubo[i][j] = 0
        b = {}  # QUBO in dictionary form
        for i in range(self.n ** 2):
            for j in range(self.n ** 2):
                if i <= j:
                    b[(i, j)] = natural_qubo[i][j]

        if self.qpu:
            self.sampler_kwargs.update({
                'chain_strength': 1.5 * abs(max(b.values(), key=abs)),
                'num_reads': 1000
            })

        qubo_dictionary = dict(b)

        response = self.dwave_solver.sample_qubo(qubo_dictionary, **self.sampler_kwargs)

        if type(self.dwave_solver) == SimulatedAnnealingSampler:
            for i in range(self.iteration_number):
                self.OF_tracker[i] = response.record[i][1] + additive_const
            self.energy = min(self.OF_tracker)
            self.sample = response.record[np.where(self.OF_tracker == self.energy)][0][0]
        else:
            self.sample = response.record[0][0]
            self.energy = response.record[0][1] + additive_const
            self.OF_tracker[0] = self.energy

        return self.sample, self.energy
    def test_dimod_vs_list(self):
        G = nx.path_graph(5)

        indep_set = dnx.maximum_independent_set(G, ExactSolver())
        indep_set = dnx.maximum_independent_set(G, SimulatedAnnealingSampler())
예제 #12
0
 def setUp(self):
     self.sampler = SimulatedAnnealingSampler()