Пример #1
0
    def solve_qiskit_qaoa(self, p, **kwargs):
        print("USING QISKIT CODE")
        point = kwargs.get("point", None)
        tqa = kwargs.get('tqa', False)
        points = kwargs.get("points", None)
        construct_circ = kwargs.get("construct_circ", False)
        fourier_parametrise = kwargs.get("fourier_parametrise", False)

        if tqa:
            deltas = np.arange(0.25, 0.91, 0.05)
            point = np.append([(i + 1) / p for i in range(p)],
                              [1 - (i + 1) / p for i in range(p)])
            points = [delta * point for delta in deltas]
            if fourier_parametrise:
                points = [
                    convert_to_fourier_point(point, len(point))
                    for point in points
                ]
            qaoa_results, circ = QiskitQAOA(
                self.operator,
                self.quantum_instance,
                self.optimizer,
                reps=p,
                initial_state=self.initial_state,
                mixer=self.mixer,
                list_points=points,
                construct_circ=construct_circ,
                fourier_parametrise=fourier_parametrise)
        elif points is not None:
            if point is not None:
                points.append(point)
            if fourier_parametrise:
                points = [
                    convert_to_fourier_point(point, len(point))
                    for point in points
                ]
            qaoa_results, circ = QiskitQAOA(
                self.operator,
                self.quantum_instance,
                self.optimizer,
                reps=p,
                initial_state=self.initial_state,
                mixer=self.mixer,
                list_points=points,
                construct_circ=construct_circ,
                fourier_parametrise=fourier_parametrise)
        elif point is not None:
            if fourier_parametrise:
                point = convert_to_fourier_point(point, 2 * p)
            qaoa_results, circ = QiskitQAOA(
                self.operator,
                self.quantum_instance,
                self.optimizer,
                reps=p,
                initial_state=self.initial_state,
                initial_point=point,
                mixer=self.mixer,
                construct_circ=construct_circ,
                fourier_parametrise=fourier_parametrise)
        else:
            points = [[0] * (2 * p)] + [[
                1.98 * np.pi * (np.random.rand() - 0.5) for _ in range(2 * p)
            ] for _ in range(10)]
            qaoa_results, circ = QiskitQAOA(
                self.operator,
                self.quantum_instance,
                self.optimizer,
                reps=p,
                initial_state=self.initial_state,
                list_points=points,
                mixer=self.mixer,
                construct_circ=construct_circ,
                fourier_parametrise=fourier_parametrise)
        if circ:
            print(circ.draw(fold=200))
        optimal_point = qaoa_results.optimal_point
        self.optimal_point = optimal_point
        self.qaoa_result = qaoa_results

        eigenstate = qaoa_results.eigenstate
        if self.quantum_instance.is_statevector:
            from qiskit.quantum_info import Statevector
            eigenstate = Statevector(eigenstate)
            eigenstate = eigenstate.probabilities_dict()
        else:
            eigenstate = dict([(u, v**2) for u, v in eigenstate.items()
                               ])  #Change to probabilities
        num_qubits = len(list(eigenstate.items())[0][0])
        solutions = []
        eigenvalue = 0
        for bitstr, sampling_probability in eigenstate.items():
            bitstr = bitstr[::-1]
            value = self.qubo.objective.evaluate([int(bit) for bit in bitstr])
            eigenvalue += value * sampling_probability
            solutions += [(bitstr, value, sampling_probability)]
        qaoa_results.eigenstate = solutions
        qaoa_results.eigenvalue = eigenvalue
        #Sort states by decreasing probability
        sorted_eigenstate_by_prob = sorted(qaoa_results.eigenstate,
                                           key=lambda x: x[2],
                                           reverse=True)

        #print sorted state in a table
        self.print_state(sorted_eigenstate_by_prob)

        #Other print stuff
        print("Eigenvalue: {}".format(eigenvalue))
        print("Optimal point: {}".format(optimal_point))
        print("Optimizer Evals: {}".format(qaoa_results.optimizer_evals))
        scale = self.random_energy - self.opt_value

        approx_quality_2 = np.round(
            (self.random_energy - sorted_eigenstate_by_prob[0][1]) / scale, 3)
        energy_prob = {}
        for x in qaoa_results.eigenstate:
            energy_prob[np.round(
                x[1], 6)] = energy_prob.get(np.round(x[1], 6), 0) + x[2]
        prob_s = np.round(energy_prob.get(np.round(self.opt_value, 6), 0), 6)
        self.prob_s.append(prob_s)
        self.eval_s.append(eigenvalue)
        self.approx_s.append(approx_quality_2)
        print("\nQAOA most probable solution: {}".format(
            sorted_eigenstate_by_prob[0]))
        print("Approx_quality: {}".format(approx_quality_2))
Пример #2
0
    def solve_qaoa(self, p, **kwargs):
        print("USING CUSTOM CODE")
        point = kwargs.get(
            "point", None
        )  #Make sure point here is already in FOURIER space of length 2(p-1)
        fourier_parametrise = kwargs.get("fourier_parametrise", False)
        tqa = kwargs.get('tqa', False)
        points = kwargs.get("points", None)
        construct_circ = kwargs.get("construct_circ", False)

        if tqa:
            deltas = np.arange(0.25, 0.91, 0.05)
            point = np.append([(i + 1) / p for i in range(p)],
                              [1 - (i + 1) / p for i in range(p)])
            points = [delta * point for delta in deltas]
            if fourier_parametrise:
                points = [
                    convert_to_fourier_point(point, len(point))
                    for point in points
                ]
            qaoa_results, circ = CustomQAOA(
                self.operator,
                self.quantum_instance,
                self.optimizer,
                reps=p,
                initial_state=self.initial_state,
                mixer=self.mixer,
                fourier_parametrise=fourier_parametrise,
                list_points=points,
                qubo=self.qubo,
                construct_circ=construct_circ)
        elif points is not None:
            if fourier_parametrise:
                points = [
                    convert_to_fourier_point(point, len(point))
                    for point in points
                ]
                if point is not None:
                    points.append(convert_to_fourier_point(point, len(point)))
            else:
                points.append(point)

            qaoa_results, circ = CustomQAOA(
                self.operator,
                self.quantum_instance,
                self.optimizer,
                reps=p,
                initial_state=self.initial_state,
                mixer=self.mixer,
                fourier_parametrise=fourier_parametrise,
                list_points=points,
                qubo=self.qubo,
                construct_circ=construct_circ)
        elif point is not None:
            if fourier_parametrise:
                initial_point = convert_to_fourier_point(point, len(point))
            qaoa_results, circ = CustomQAOA(
                self.operator,
                self.quantum_instance,
                self.optimizer,
                reps=p,
                initial_state=self.initial_state,
                initial_point=point,
                mixer=self.mixer,
                fourier_parametrise=fourier_parametrise,
                qubo=self.qubo,
                construct_circ=construct_circ)
        else:
            points = [[0] * (2 * p)] + [[
                1.98 * np.pi * (np.random.rand() - 0.5) for _ in range(2 * p)
            ] for _ in range(10)]
            qaoa_results, circ = CustomQAOA(
                self.operator,
                self.quantum_instance,
                self.optimizer,
                reps=p,
                initial_state=self.initial_state,
                list_points=points,
                mixer=self.mixer,
                fourier_parametrise=fourier_parametrise,
                qubo=self.qubo,
                construct_circ=construct_circ)
        if circ:
            print(circ.draw(fold=200))
        optimal_point = qaoa_results.optimal_point
        eigenvalue = sum([x[1] * x[2] for x in qaoa_results.eigenstate])
        qaoa_results.eigenvalue = eigenvalue
        self.optimal_point = optimal_point

        self.qaoa_result = qaoa_results

        #Sort states by decreasing probability
        sorted_eigenstate_by_prob = sorted(qaoa_results.eigenstate,
                                           key=lambda x: x[2],
                                           reverse=True)

        #print sorted state in a table
        self.print_state(sorted_eigenstate_by_prob)

        #Other print stuff
        print("Eigenvalue: {}".format(eigenvalue))
        print("Optimal point: {}".format(optimal_point))
        print("Optimizer Evals: {}".format(qaoa_results.optimizer_evals))
        scale = self.random_energy - self.opt_value

        approx_quality_2 = np.round(
            (self.random_energy - sorted_eigenstate_by_prob[0][1]) / scale, 3)
        energy_prob = {}
        for x in qaoa_results.eigenstate:
            energy_prob[np.round(
                x[1], 6)] = energy_prob.get(np.round(x[1], 6), 0) + x[2]
        prob_s = np.round(energy_prob.get(np.round(self.opt_value, 6), 0), 6)
        self.prob_s.append(prob_s)
        self.eval_s.append(eigenvalue)
        self.approx_s.append(approx_quality_2)
        print("\nQAOA most probable solution: {}".format(
            sorted_eigenstate_by_prob[0]))
        print("Approx_quality: {}".format(approx_quality_2))
Пример #3
0
def main(args=None):
    """[summary]

    Args:
        raw_args ([type], optional): [description]. Defaults to None.
    """
    start = time()
    if args == None:
        args = parse()

    qubo_no = args["no_samples"]
    print_to_file("-" * 50)
    print_to_file("QUBO_{}".format(qubo_no))
    #Load generated qubo_no
    with open(
            'qubos_{}_car_{}_routes/qubo_{}.pkl'.format(
                args["no_cars"], args["no_routes"], qubo_no), 'rb') as f:
        qubo, max_coeff, operator, offset, routes = pkl.load(f)

    qubo = QuadraticProgram()
    qubo.from_ising(operator)

    x_s, opt_value, classical_result = find_all_ground_states(qubo)
    print_to_file(classical_result)

    #Set optimizer method
    method = args["method"]
    optimizer = NLOPT_Optimizer(method=method, result_message=False)
    # optimizer = COBYLA()
    backend = Aer.get_backend("statevector_simulator")
    quantum_instance = QuantumInstance(backend=backend)

    approx_ratios = []
    prob_s_s = []
    p_max = args["p_max"]
    no_routes, no_cars = (args["no_routes"], args["no_cars"])

    custom = True
    if custom:
        initial_state = construct_initial_state(no_routes=no_routes,
                                                no_cars=no_cars)
        mixer = n_qbit_mixer(initial_state)
    else:
        initial_state, mixer = (None, None)

    fourier_parametrise = args["fourier"]
    print_to_file("-" * 50)
    print_to_file(
        "Now solving with TQA_QAOA... Fourier Parametrisation: {}".format(
            fourier_parametrise))
    #     maxeval = 125
    for p in range(1, p_max + 1):
        construct_circ = False
        deltas = np.arange(0.45, 0.91, 0.05)
        point = np.append([(i + 1) / p for i in range(p)],
                          [1 - (i + 1) / p for i in range(p)])
        points = [delta * point for delta in deltas]
        print_to_file("-" * 50)
        print_to_file("    " + "p={}".format(p))
        if fourier_parametrise:
            points = [
                convert_to_fourier_point(point, len(point)) for point in points
            ]


#         maxeval *= 2 #Double max_allowed evals for optimizer
#         optimizer.set_options(maxeval = maxeval)
        optimizer.set_options(maxeval=1000 * p)
        qaoa_results, optimal_circ = CustomQAOA(
            operator,
            quantum_instance,
            optimizer,
            reps=p,
            initial_state=initial_state,
            mixer=mixer,
            construct_circ=construct_circ,
            fourier_parametrise=fourier_parametrise,
            list_points=points,
            qubo=qubo)
        exp_val = qaoa_results.eigenvalue * max_coeff
        state_solutions = {
            item[0][::-1]: item[1:]
            for item in qaoa_results.eigenstate
        }
        for item in sorted(state_solutions.items(),
                           key=lambda x: x[1][1],
                           reverse=True)[0:5]:
            print_to_file(item)
        prob_s = 0
        for string in x_s:
            prob_s += state_solutions[string][
                1] if string in state_solutions else 0
        prob_s /= len(x_s)  #normalise
        optimal_point = qaoa_results.optimal_point
        if fourier_parametrise:
            optimal_point = convert_from_fourier_point(optimal_point,
                                                       len(optimal_point))
        approx_ratio = 1 - np.abs((opt_value - exp_val) / opt_value)
        nfev = qaoa_results.cost_function_evals
        print_to_file(
            "    " + "Optimal_point: {}, Nfev: {}".format(optimal_point, nfev))
        print_to_file("    " +
                      "Exp_val: {}, Prob_s: {}, approx_ratio: {}".format(
                          exp_val, prob_s, approx_ratio))
        approx_ratios.append(approx_ratio)
        prob_s_s.append(prob_s)
    print_to_file("-" * 50)
    print_to_file("QAOA terminated")
    print_to_file("-" * 50)
    print_to_file("Approximation ratios per layer: {}".format(approx_ratios))
    print_to_file("Prob_success per layer: {}".format(prob_s_s))
    save_results = np.append(approx_ratios, prob_s_s)
    if fourier_parametrise:
        with open(
                'results_{}cars{}routes/TQA_F_{}.csv'.format(
                    args["no_cars"], args["no_routes"], args["no_samples"]),
                'w') as f:
            np.savetxt(f, save_results, delimiter=',')
        print_to_file(
            "Results saved in results_{}cars{}routes/TQA_F_{}.csv".format(
                args["no_cars"], args["no_routes"], args["no_samples"]))
    else:
        with open(
                'results_{}cars{}routes/TQA_NF_{}.csv'.format(
                    args["no_cars"], args["no_routes"], args["no_samples"]),
                'w') as f:
            np.savetxt(f, save_results, delimiter=',')
        print_to_file(
            "Results saved in results_{}cars{}routes/TQA_NF_{}.csv".format(
                args["no_cars"], args["no_routes"], args["no_samples"]))
    finish = time()
    print_to_file("Time Taken: {}".format(finish - start))
Пример #4
0
def main(args=None):
    start = time()
    if args == None:
        args = parse()

    #Load QUBO and reduce, then check existing classical solution
    with open(
            'qubos_{}_car_{}_routes/qubo_{}.pkl'.format(
                args["no_cars"], args["no_routes"], args["no_samples"]),
            'rb') as f:
        load_data = pkl.load(f)
        if len(load_data) == 5:
            qubo, max_coeff, operator, offset, routes = load_data
            classical_result = None
        else:
            qubo, max_coeff, operator, offset, routes, classical_result = load_data
    qubo, normalize_factor = reduce_qubo(qubo)
    if classical_result:
        classical_result._fval /= normalize_factor  #Also normalize classical result
    print("NO CARS: {}, NO ROUTES: {}, SAMPLE: {}\n".format(
        args["no_cars"], args["no_routes"], args["no_samples"]))
    #Noise
    if args["noisy"]:
        multiplier = args["multiplier"]
        print(
            "Simulating with noise...Error mulitplier: {}".format(multiplier))
        with open('average_gate_errors.json', 'r') as f:
            noise_rates = json.load(f)
        noise_model = build_noise_model(noise_rates, multiplier)
    else:
        print("Simulating without noise...")
        noise_model = None

    #Initialize QAOA object
    qaoa = QAOA_Base(qubo=qubo,
                     no_cars=args["no_cars"],
                     no_routes=args["no_routes"],
                     symmetrise=args["symmetrise"],
                     customise=args["customise"],
                     classical_result=classical_result,
                     simulator=args["simulator"],
                     noise_model=noise_model,
                     opt_str=args["optimizer"])
    p_max = args["p_max"]
    fourier_parametrise = args["fourier"]
    print("QAOA METHODS")
    print("FOURIER: {}\nINTERP: {}".format(args["fourier"], args["interp"]))
    print("CUSTOM: {}\nSYMMETR: {}".format(args["customise"],
                                           args["symmetrise"]))

    for p in range(1, p_max + 1):
        p_start = time()
        print("\nQAOA p={}. Results below:".format(p))
        qaoa.optimizer.set_options(maxeval=100 * (2**p))
        if p == 1:
            qaoa.solve_qiskit_qaoa(p, fourier_parametrise=fourier_parametrise)
        else:
            if args["interp"]:
                next_point = interp_point(qaoa.optimal_point)
            else:
                point = qaoa.optimal_point if not args[
                    "fourier"] else convert_to_fourier_point(
                        qaoa.optimal_point, len(qaoa.optimal_point))
                next_point = np.zeros(2 * p)
                next_point[0:p - 1] = point[0:p - 1]
                next_point[p:2 * p - 1] = point[p - 1:2 * p - 2]
                if args["fourier"]:
                    next_point = convert_from_fourier_point(next_point, 2 * p)
            qaoa.solve_qiskit_qaoa(p,
                                   point=next_point,
                                   fourier_parametrise=fourier_parametrise)
        p_end = time()
        print("Time taken (for this iteration): {}s".format(p_end - p_start))

    prob_s = [np.round(prob, 3) for prob in qaoa.prob_s]
    eval_s = [np.round(e_val, 3) for e_val in qaoa.eval_s]
    approx_s = [np.round(approx, 3) for approx in qaoa.approx_s]
    print("\nProbabilities: {}".format(prob_s))
    print("Eigenvalue at each p: {}".format(eval_s))
    print("Approx Qualities of most_probable_state: {}\n".format(approx_s))
    filedir = 'results_{}cars{}routes/'.format(args["no_cars"],
                                               args["no_routes"])
    p_max = str(args["p_max"]).zfill(2)
    err_multipler = '{:.2f}'.format(
        args["multiplier"]) if args["noisy"] else '{:.2f}'.format(0.0)
    sample = str(args["no_samples"]).zfill(3)
    if args["noisy"]:
        filedir += "Noisy_QAOA_p={}_s={}_err={}".format(
            p_max, sample, err_multipler)
    else:
        filedir += "Ideal_QAOA_p={}_s={}_err={}".format(
            p_max, sample, err_multipler)
    if args["symmetrise"]:
        filedir += "_Symm"
    else:
        filedir += "_Base"
    if args["customise"]:
        filedir += "_Cust"
    else:
        filedir += "_Base"
    if args["fourier"]:
        filedir += "_FOUR"
    else:
        filedir += "_NONE"
    if args["interp"]:
        filedir += "_INTP"
    else:
        filedir += "_NONE"
    filedir += "_{}".format(str(args["optimizer"]))
    print(filedir)
    #Save results to file
    save_results = np.append(qaoa.prob_s, qaoa.eval_s)
    save_results = np.append(save_results, qaoa.approx_s)
    with open(filedir, 'w') as f:
        np.savetxt(f, save_results, delimiter=',')

    result_saved_string = "Results saved in {}".format(filedir)
    print(result_saved_string)
    finish = time()
    print("\nTime taken: {} s".format(finish - start))
    print("_" * len(result_saved_string))
Пример #5
0
def main(args = None):
    """[summary]

    Args:
        raw_args ([type], optional): [description]. Defaults to None.
    """
    start = time()
    if args == None:
        args = parse()

    qubo_no = args["no_samples"]
    print_to_file("-"*50)
    print_to_file("QUBO_{}".format(qubo_no))
    #Load generated qubo_no
    with open('qubos_{}_car_{}_routes/qubo_{}.pkl'.format(args["no_cars"], args["no_routes"], qubo_no), 'rb') as f:
        qubo, max_coeff, operator, offset, routes = pkl.load(f)
    qubo = QuadraticProgram()
    qubo.from_ising(operator)
    
    x_s, opt_value, classical_result = find_all_ground_states(qubo)
    print_to_file(classical_result)
    
    #Set optimizer method
    method = args["method"]
    optimizer = NLOPT_Optimizer(method = method, result_message=False)
    backend = Aer.get_backend("statevector_simulator")
    quantum_instance = QuantumInstance(backend = backend)

    approx_ratios = []
    prob_s_s = []
    p_max = args["p_max"]
    no_routes, no_cars = (args["no_routes"], args["no_cars"])

    custom = True
    if custom:
        initial_state = construct_initial_state(no_routes = no_routes, no_cars = no_cars)
        mixer = n_qbit_mixer(initial_state)
    else:
        initial_state, mixer = (None, None)

    fourier_parametrise = args["fourier"]
    print_to_file("-"*50)
    print_to_file("Now solving with QAOA... Fourier Parametrisation: {}".format(fourier_parametrise))
    for p in range(1, p_max+1):
        if p == 1:
            points = [[0,0]] + [ np.random.uniform(low = -np.pi/2+0.01, high = np.pi/2-0.01, size = 2*p) for _ in range(2**p)]
            next_point = []
        else:
            penalty = 0.6
            points = [next_point_l] + generate_points(next_point, no_perturb=min(2**p-1,10), penalty=penalty)
        construct_circ = False
        #empty lists to save following results to choose best result
        results = []
        exp_vals = []
        print_to_file("-"*50)
        print_to_file("    "+"p={}".format(p))
        optimizer.set_options(maxeval = 1000*p)
        for r, point in enumerate(points):
            qaoa_results, optimal_circ = CustomQAOA(operator,
                                                        quantum_instance,
                                                        optimizer,
                                                        reps = p,
                                                        initial_fourier_point= point,
                                                        initial_state = initial_state,
                                                        mixer = mixer,
                                                        construct_circ= construct_circ,
                                                        fourier_parametrise = fourier_parametrise,
                                                        qubo = qubo
                                                        )
            if r == 0:
                if fourier_parametrise:
                    next_point_l = np.zeros(shape = 2*p + 2)
                    next_point_l[0:p] = qaoa_results.optimal_point[0:p]
                    next_point_l[p+1:2*p+1] = qaoa_results.optimal_point[p:2*p]
                else:
                    next_point_l = interp_point(qaoa_results.optimal_point)
            exp_val = qaoa_results.eigenvalue * max_coeff
            exp_vals.append(exp_val)
            
            state_solutions = { item[0][::-1]: item[1:] for item in qaoa_results.eigenstate }
            
            for item in sorted(state_solutions.items(), key = lambda x: x[1][1], reverse = True)[0:5]:
                print_to_file( item )
                
            prob_s = 0
            for string in x_s:
                prob_s += state_solutions[string][1] if string in state_solutions else 0
            prob_s /= len(x_s) #normalise
            results.append((qaoa_results, optimal_circ, prob_s))
            print_to_file("    "+"Point_{}, Exp_val: {}, Prob_s: {}".format(r, exp_val, prob_s))
        minim_index = np.argmin(exp_vals)
        optimal_qaoa_result, optimal_circ, optimal_prob_s = results[minim_index]
        if fourier_parametrise:
            next_point = convert_from_fourier_point( optimal_qaoa_result.optimal_point, 2*p )
            next_point = convert_to_fourier_point( interp_point(next_point), 2*p + 2 )
#             next_point = np.zeros(shape = 2*p + 2)
#             next_point[0:p] = optimal_qaoa_result.optimal_point[0:p]
#             next_point[p+1:2*p+1] = optimal_qaoa_result.optimal_point[p:2*p]
        else:
            next_point = interp_point(optimal_qaoa_result.optimal_point)
        if construct_circ:
            print_to_file(optimal_circ.draw(fold=150))
        minim_exp_val = exp_vals[minim_index]
        approx_ratio = 1.0 - np.abs( (opt_value - minim_exp_val ) / opt_value )
        print_to_file("    "+"Minimum: {}, prob_s: {}, approx_ratio {}".format(minim_exp_val, optimal_prob_s, approx_ratio))
        approx_ratios.append(approx_ratio)
        prob_s_s.append(optimal_prob_s)
    print_to_file("-"*50)
    print_to_file("QAOA terminated")
    print_to_file("-"*50)
    print_to_file("Approximation ratios per layer: {}".format(approx_ratios))
    print_to_file("Prob_success per layer: {}".format(prob_s_s))
    save_results = np.append(approx_ratios, prob_s_s)
    if fourier_parametrise:
        with open('results_{}cars{}routes/RI_F_{}.csv'.format(args["no_cars"], args["no_routes"], args["no_samples"]), 'w') as f:
            np.savetxt(f, save_results, delimiter=',')
        print_to_file("Results saved in results_{}cars{}routes/RI_F_{}.csv".format(args["no_cars"], args["no_routes"], args["no_samples"]))
    else:
        with open('results_{}cars{}routes/RI_NF_{}.csv'.format(args["no_cars"], args["no_routes"], args["no_samples"]), 'w') as f:
            np.savetxt(f, save_results, delimiter=',')
        print_to_file("Results saved in results_{}cars{}routes/RI_NF_{}.csv".format(args["no_cars"], args["no_routes"], args["no_samples"]))
    finish = time()
    print_to_file("Time Taken: {}".format(finish - start))