コード例 #1
0
def simulate(structure, system_size, fill, interaction_shape,
             interaction_radius, algorithm, init_temp, cool_rate,
             exact_min_energy, exact_min_gap):
    prob = maxcut.initialize_problem(structure, system_size, fill,
                                     interaction_shape, interaction_radius)
    algorithm.set_cooling_schedule(init_temp, cool_rate)
    algorithm.solve(prob)
    step = len(algorithm.get_temp_history())
    min_energy = prob.get_best_energy()
    temp_hist = algorithm.get_temp_history()
    energy_hist = prob.get_energy_history()
    partition_hist = prob.get_partition_history()
    if len(temp_hist) != len(energy_hist):
        raise RuntimeError(
            'Length of temperature and energy histories must match')
    ground_state_found = None
    if exact_min_energy:
        ground_state_found = [0 for t in range(len(energy_hist))]
        if abs(min_energy - exact_min_energy) <= exact_min_gap:
            ground_state_found = [
                float(
                    np.round(energy_hist[t], 10) == np.round(min_energy, 10))
                for t in range(len(energy_hist))
            ]
        elif min_energy - exact_min_energy < -exact_min_gap:
            print('WARNING: Cannot reach energy below ground state energy')
    return [
        step, temp_hist, energy_hist, partition_hist, ground_state_found,
        min_energy, prob
    ]
コード例 #2
0
def exact_solve(structure, system_size, fill, interaction_shape,
                interaction_radius, path):
    radius_dir_path = '{}/radius_{}'.format(path, interaction_radius)
    util.make_dir(radius_dir_path)
    start = time.time()
    prob = maxcut.initialize_problem(structure, system_size, fill,
                                     interaction_shape, interaction_radius)
    min_energy, num_ground_states, sample_ground_state, num_total_states, all_energies = classical_algorithms.BruteForce(
    ).solve(prob)
    if structure != 'free':
        with open('{}/ground_state_partitions.csv'.format(radius_dir_path),
                  'w') as output_file:
            header = sample_ground_state.keys()
            dict_writer = csv.DictWriter(output_file, header)
            dict_writer.writeheader()
            dict_writer.writerow(sample_ground_state)
    with open('{}/energies.csv'.format(radius_dir_path), 'w') as output_file:
        writer = csv.writer(output_file)
        writer.writerow(['energy'])
        min_gap = float('inf')
        prev_energy = 0.0
        for energy in sorted(all_energies):
            writer.writerow([energy])
            if energy != prev_energy:
                min_gap = min(abs(energy - prev_energy), min_gap)
                prev_energy = energy
    end = time.time()
    return {
        'radius': interaction_radius,
        'min energy': min_energy,
        '# ground states': num_ground_states,
        '# states': num_total_states,
        'min energy gap': min_gap,
        'runtime': end - start
    }
コード例 #3
0
def param_search(structure, system_size, fill, interaction_shape,
                 interaction_radius, ensemble, path, exact_min_energy,
                 exact_min_gap):
    radius_dir_path = '{}/radius_{}'.format(path, interaction_radius)
    util.make_dir(radius_dir_path)
    start = time.time()
    algorithm = classical_algorithms.SimulatedAnnealing()
    cooling_schedules = maxcut.get_cooling_schedules(
        problem=maxcut.initialize_problem(structure, system_size, fill,
                                          interaction_shape,
                                          interaction_radius))
    radius_sols = []
    sample_best_probs = {}
    for init_temp, cool_rate in cooling_schedules:
        radius_sols.append(
            run_trials(structure, system_size, fill, interaction_shape,
                       interaction_radius, algorithm, ensemble,
                       radius_dir_path, exact_min_energy, exact_min_gap,
                       init_temp, cool_rate, sample_best_probs))

    with open('{}/param_results.csv'.format(radius_dir_path),
              'w') as output_file:
        header = radius_sols[0].keys()
        dict_writer = csv.DictWriter(output_file, header)
        dict_writer.writeheader()
        dict_writer.writerows(radius_sols)

    opt_sol = min(radius_sols, key=lambda sol: sol['step_from_exact'])
    opt_init_temp = opt_sol['init_temp']
    opt_cool_rate = opt_sol['cool_rate']
    opt_step_from_exact = opt_sol['step_from_exact']
    opt_step_from_entropy = opt_sol['step_from_entropy']
    opt_prob_ground_state_per_run = opt_sol['prob_ground_state_per_run']

    if structure != 'free':
        sample_best_prob = sample_best_probs[(opt_init_temp, opt_cool_rate)]
        sample_best_partition_hist = sample_best_prob.get_partition_history()
        sample_best_energy_hist = sample_best_prob.get_energy_history()
        with open('{}/ground_state_partitions.csv'.format(radius_dir_path),
                  'w') as output_file:
            header = sample_best_partition_hist[0].keys()
            dict_writer = csv.DictWriter(output_file, header)
            dict_writer.writeheader()
            dict_writer.writerows(sample_best_partition_hist)
        with open('{}/ground_state_energies.csv'.format(radius_dir_path),
                  'w') as output_file:
            writer = csv.writer(output_file)
            writer.writerow(['energy'])
            for energy in sample_best_energy_hist:
                writer.writerow([energy])
    end = time.time()
    return dict(interaction_radius=interaction_radius,
                init_temp=opt_init_temp,
                cool_rate=opt_cool_rate,
                step_from_exact=opt_step_from_exact,
                step_from_entropy=opt_step_from_entropy,
                prob_ground_state_per_run=opt_prob_ground_state_per_run,
                search_runtime=(end - start),
                exact_min_energy=exact_min_energy)
コード例 #4
0
def maxcut_to_quantum(structure, system_size, fill, interaction_shape,
                      interaction_radius):
    prob = maxcut.initialize_problem(structure, system_size, fill,
                                     interaction_shape, interaction_radius)
    N = prob.get_num_vertices()
    basis = spin_basis_general(N)

    # Hamiltonian terms for Ising interactions and reference field
    J_zz = prob.get_edges()
    h_x = [[-1, i] for i in range(N)]

    # Hamiltonian for Ising interactions
    static = [["zz", J_zz]]
    dynamic = []
    H = hamiltonian(static, dynamic, basis=basis, dtype=np.float64)

    # reference Hamiltonian
    B = hamiltonian([["x", h_x]], [],
                    dtype=np.float64,
                    basis=basis,
                    check_herm=False,
                    check_symm=False)

    # initial state: all up in x basis (ground state of reference Hamiltonian)
    psi_0 = (1 / (2**(N / 2))) * np.ones(2**N, )  # all up in x basis

    # exact ground states
    states = util.get_states_str(system_size)
    ground_state_energy, num_ground_states, ground_states = classical_algorithms.BruteForce(
    ).solve(prob, allGroundStates=True)
    ground_states_id = []
    for ground_state in ground_states:
        ground_state_str = ''
        for v in range(N):
            ground_state_str += str(int((ground_state[v] + 1) / 2))
        ground_states_id.append(states.index(ground_state_str))

    return H, B, psi_0, ground_states_id
コード例 #5
0
                row['search_runtime'])
            if row['exact_min_energy']:
                system_sols[interaction_radius]['exact_min_energy'] = float(
                    row['exact_min_energy'])

    if structure != 'free' and interaction_shape != 'random':
        util.plot_steps_vs_radius(system_sols, system_size, interaction_shape,
                                  algo_dir_path)

    for interaction_radius, system_sol in system_sols.items():
        exact_radius_dir_path = '{}/radius_{}'.format(exact_dir_path,
                                                      interaction_radius)
        algo_radius_dir_path = '{}/radius_{}'.format(algo_dir_path,
                                                     interaction_radius)

        prob = maxcut.initialize_problem(structure, system_size, fill,
                                         interaction_shape, interaction_radius)
        if structure != 'free' and interaction_shape != 'random':
            util.plot_interaction(maxcut.get_interaction_fn(interaction_shape),
                                  interaction_radius, system_size,
                                  experiment.LATTICE_SPACING,
                                  algo_radius_dir_path)

        param_results = collections.defaultdict(dict)
        with open('{}/param_results.csv'.format(algo_radius_dir_path),
                  'r') as input_file:
            dict_reader = csv.DictReader(input_file)
            for row in dict_reader:
                init_temp = float(row['init_temp'])
                cool_rate = float(row['cool_rate'])
                # print(cool_rate)
                param_results[init_temp][cool_rate] = {}
コード例 #6
0
def run_trials(structure, system_size, fill, interaction_shape,
               interaction_radius, algorithm, ensemble, path, init_temp,
               cool_rate, sample_best_probs):
    param_sols = []
    exact_min_energies = []
    exact_min_gaps = []
    prob = None
    exact_min_energy = None
    exact_min_gap = None
    for i in range(NUM_PARAM_TRIALS):
        if i % 10 == 0:
            prob = maxcut.initialize_problem(structure, system_size, fill,
                                             interaction_shape,
                                             interaction_radius)
            exact_sol = maxcut_exact.exact_solve_prob(prob)
            exact_min_energy = exact_sol['min energy']
            exact_min_gap = exact_sol['min energy gap']
            exact_min_energies.append(exact_min_energy)
            exact_min_gaps.append(exact_min_gap)
        prob.reset()
        param_sols.append(
            simulate(prob, algorithm, init_temp, cool_rate, exact_min_energy,
                     exact_min_gap))

    steps, temp_hists, energy_hists, partition_hists, ground_states_found, min_energies, probs = np.array(
        param_sols).T
    min_energy = min(min_energies)
    sample_best_probs[(init_temp, cool_rate)] = probs[np.argmin(min_energies)]

    all_temps_hist, all_energies_hist, all_partitions_hist, all_ground_states_found_hist, all_energies_vs_temp, all_partitions_vs_temp, all_ground_states_found_vs_temp = collect_param_stats(
        temp_hists, energy_hists, ground_states_found, partition_hists,
        exact_min_energies)

    stats_vs_temp = []
    for temp in all_energies_vs_temp.keys():
        stats_vs_temp.append(
            get_param_stats_per_temp(temp, all_energies_vs_temp,
                                     all_partitions_vs_temp,
                                     all_ground_states_found_vs_temp))

    stats_vs_t = []
    for t in all_energies_hist.keys():
        stats_vs_t.append(
            get_param_stats_per_t(t, all_temps_hist, all_energies_hist,
                                  all_partitions_hist,
                                  all_ground_states_found_hist))

    min_energy_from_entropy = get_total_iters(stats_vs_t, energy_hists,
                                              all_ground_states_found_hist,
                                              exact_min_energies)

    step_ave = np.mean(steps)
    step_from_exact = None
    step_from_entropy = None
    prob_ground_state_per_run = None
    t_opt_exact = None

    MT_exact = {}
    MT_from_entropy = {}
    for stat_vs_t in stats_vs_t:
        t = stat_vs_t['t']
        if t == 0: continue
        if stat_vs_t['total_iter']:
            MT_exact[t] = stat_vs_t['total_iter']
        if stat_vs_t['total_iter_from_entropy']:
            MT_from_entropy[t] = stat_vs_t['total_iter_from_entropy']
    if len(MT_exact) > 0:
        t_opt_exact = min(MT_exact, key=MT_exact.get)
        step_from_exact = MT_exact[t_opt_exact]
        stat_vs_t_opt_exact = [
            stat_vs_t for stat_vs_t in stats_vs_t
            if stat_vs_t['t'] == t_opt_exact
        ][0]
        prob_ground_state_per_run = stat_vs_t_opt_exact[
            'ave_prob_ground_state']
    if len(MT_from_entropy) > 0:
        t_opt_from_entropy = min(MT_from_entropy, key=MT_from_entropy.get)
        step_from_entropy = MT_from_entropy[t_opt_from_entropy]

    with open(
            '{}/stats_vs_temp_T_0_{}_r_{}.csv'.format(path, init_temp,
                                                      cool_rate),
            'w') as output_file:
        header = stats_vs_temp[0].keys()
        dict_writer = csv.DictWriter(output_file, header)
        dict_writer.writeheader()
        dict_writer.writerows(stats_vs_temp)

    with open(
            '{}/stats_vs_t_T_0_{}_r_{}.csv'.format(path, init_temp, cool_rate),
            'w') as output_file:
        header = stats_vs_t[0].keys()
        dict_writer = csv.DictWriter(output_file, header)
        dict_writer.writeheader()
        dict_writer.writerows(stats_vs_t)

    return dict(init_temp=init_temp,
                cool_rate=cool_rate,
                min_energy=min_energy,
                min_energy_from_entropy=min_energy_from_entropy,
                step_from_exact=step_from_exact,
                step_from_entropy=step_from_entropy,
                step_per_run=t_opt_exact,
                prob_ground_state_per_run=prob_ground_state_per_run)