Пример #1
0
    def test_qaoa_random_initial_point(self):
        """ QAOA random initial point """
        w = nx.adjacency_matrix(
            nx.fast_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed)).toarray()
        qubit_op, _ = self._get_operator(w)
        qaoa = QAOA(optimizer=NELDER_MEAD(disp=True), reps=1, quantum_instance=self.qasm_simulator)
        _ = qaoa.compute_minimum_eigenvalue(operator=qubit_op)

        np.testing.assert_almost_equal([-0.879, 0.395], qaoa.optimal_params, decimal=3)
Пример #2
0
    def test_qaoa_random_initial_point(self):
        """QAOA random initial point"""
        w = rx.adjacency_matrix(
            rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed)
        )
        qubit_op, _ = self._get_operator(w)
        qaoa = QAOA(optimizer=NELDER_MEAD(disp=True), reps=1, quantum_instance=self.qasm_simulator)
        result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)

        self.assertLess(result.eigenvalue, -0.97)
    def test_qaoa_random_initial_point(self):
        """ QAOA random initial point """
        aqua_globals.random_seed = 10598
        w = nx.adjacency_matrix(
            nx.fast_gnp_random_graph(5, 0.5,
                                     seed=aqua_globals.random_seed)).toarray()
        qubit_op, _ = max_cut.get_operator(w)
        q_i = QuantumInstance(BasicAer.get_backend('qasm_simulator'),
                              seed_simulator=aqua_globals.random_seed,
                              seed_transpiler=aqua_globals.random_seed,
                              shots=4096)
        qaoa = QAOA(optimizer=NELDER_MEAD(disp=True),
                    p=1,
                    quantum_instance=q_i)
        _ = qaoa.compute_minimum_eigenvalue(operator=qubit_op)

        np.testing.assert_almost_equal([-0.8792, 0.3948],
                                       qaoa.optimal_params,
                                       decimal=4)
 def test_nelder_mead(self):
     """ nelder mead test """
     optimizer = NELDER_MEAD(maxfev=10000, tol=1e-06)
     res = self._optimize(optimizer)
     self.assertLessEqual(res[2], 10000)
Пример #5
0
 def test_nelder_mead(self):
     """nelder mead test"""
     optimizer = NELDER_MEAD(maxfev=10000, tol=1e-06)
     self.run_optimizer(optimizer, max_nfev=10000)
Пример #6
0
def main():
    #Must load after importing/defining Ox_Route and QAOA_Traffic classes
    with open("traffic.pkl", 'rb') as f:
        traffic = pkl.load(f)

    routing_dict = {
        var: traffic.routing_dict()[var].routing()
        for var in traffic.routing_dict()
    }
    edges_dict = get_edges_dict(routing_dict)
    new_dict = deepcopy(edges_dict)
    #Remove edges with <50m overlaps.
    for edge, value in edges_dict.items():
        weight = 0
        edge_data = traffic.obtain_map().get_edge_data(*edge,
                                                       default=[None])[0]
        if edge_data:
            weight += edge_data["length"]
        if weight < 50:
            # print(edge, value, weight)
            new_dict.pop(edge, None)
    variable_renaming = {
        "Car_{}_Route_{}".format(str(i).zfill(2), j):
        "X_{}_{}".format(str(i).zfill(2), j)
        for i, j in product(range(21), range(3))
    }
    new_edges_dict = {}
    for edge, variables in new_dict.items():
        new_edges_dict[edge] = [variable_renaming[var] for var in variables]
    del edges_dict
    del new_dict
    global qubo
    unconstrained_qubo, linear, quadratic = build_qubo_unconstrained_from_edges_dict(
        traffic.obtain_map(),
        new_edges_dict,
        variables=variable_renaming.values())
    qubo = add_qubo_constraints(unconstrained_qubo, no_cars=21, no_routes=3)
    qubo, max_coeff = convert_qubo(qubo,
                                   linear,
                                   quadratic,
                                   penalty_multiplier=1.5)
    min_results = {}
    min_total_obj = 0
    max_results = {}
    max_total_obj = 0
    for car in range(21):
        zeros = [0] * 3
        assignments = [[0] * i + [1] + [0] * (2 - i) for i in range(3)]
        assignments_obj = {}
        for assignment in assignments:
            x = zeros * (car) + assignment + zeros * (20 - car)
            var_dict = {
                "X_{}_{}".format(str(int((k - k % 3) / 3)).zfill(2), k % 3):
                x[k]
                for k in range(len(x))
            }
            obj = unconstrained_qubo.objective.evaluate(var_dict)
            assignments_obj[tuple(assignment)] = obj
        min_assignment = min(assignments_obj.items(), key=lambda x: x[1])
        max_assignment = max(assignments_obj.items(), key=lambda x: x[1])
        min_total_obj += min_assignment[1]
        max_total_obj += max_assignment[1]
        min_car_dict_assignment = {
            "X_{}_{}".format(str(car).zfill(2), k): min_assignment[0][k]
            for k in range(3)
        }
        max_car_dict_assignment = {
            "X_{}_{}".format(str(car).zfill(2), k): max_assignment[0][k]
            for k in range(3)
        }
        for var, value in min_car_dict_assignment.items():
            min_results[var] = value
        for var, value in max_car_dict_assignment.items():
            max_results[var] = value
    greedy = qubo.objective.evaluate(min_results)
    max_greedy = qubo.objective.evaluate(max_results)
    print("Zeros:", qubo.objective.evaluate([0 for _ in range(63)]))
    print("MIN GREEDY:", greedy)
    print("Total distance traversed(min):", min_total_obj)
    print(min_results)
    print("MAX GREEDY:", max_greedy)
    print("Total distance traversed(max):", max_total_obj)
    print(max_results)
    optimizer = NELDER_MEAD()
    optimizer.set_options(maxiter=1)
    backend = Aer.get_backend("aer_simulator_matrix_product_state")
    quantum_instance = QuantumInstance(backend, shots=1)
    op, offset = qubo.to_ising()
    op *= 1 / max_coeff
    print(op)
    #     initial_state = construct_initial_state(no_routes = 3, no_cars = 21)
    #     mixer = n_qbit_mixer(initial_state)

    #p=1
    start = time()
    result, qc = QiskitQAOA(operator=op,
                            quantum_instance=quantum_instance,
                            optimizer=optimizer,
                            reps=1,
                            construct_circ=True,
                            initial_state=None,
                            mixer=None,
                            initial_point=[0, 0])
    print(qc.draw())
    print(qc.depth())
    end = time()
    print(result.eigenstate)
    print(max_coeff * (result.eigenvalue) + offset)
    print("p=1, Time taken: {}s".format(end - start))
    print(result.cost_function_evals)