Exemplo n.º 1
0
def greedy():
    """ Run greedy hillclimber. Enumerate neighbourhood and choose best. """
    chain = hchain.HeisenbergChain(num_qubits, v)

    steps = [-step_size, 0, step_size]

    neighbourhood_size = len(steps)**num_p_values

    suzuki = np.array(approx.suzuki(k))
    suzuki_error = approx.error(chain, approx.r_copies(suzuki, r), t)
    print('Suzuki error: {}'.format(suzuki_error))

    # Start at Suzuki
    current = suzuki
    current_error = suzuki_error

    # Start at 1/p_length
    # current = np.array([0.2] * 5)
    # current_error = approx.error(chain, approx.r_copies(current, r), t)

    # Start at suzuki permutation
    # import random
    # random.seed(1234)
    # suzuki_coeff = approx.suzuki(k)
    # random.shuffle(suzuki_coeff)
    # current = np.array(suzuki_coeff)
    # current_error = approx.error(chain, approx.r_copies(current, r), t)

    for gen in range(1, gens+1):

        current_error_percent = 100 * (current_error / suzuki_error)
        print('Gen: {} Best: {} Percent: {} '.format(gen, current_error, current_error_percent))

        all_neighbours = list(range(1, neighbourhood_size))
        random.shuffle(all_neighbours
                       )
        for neighbour_index in all_neighbours:

            move = [step_size * (coeff - 1) for coeff in ternary(neighbour_index, num_p_values)]

            neighbour = current + move

            neighbour_err = approx.error(chain, approx.r_copies(neighbour, r), t)

            neighbour_err_percent = 100 * (neighbour_err / suzuki_error)

            print('Step {} Neighbour {}/{} error: {}, error %: {}'.format(gen, neighbour_index, neighbourhood_size,
                                                                          neighbour_err, neighbour_err_percent))
            if neighbour_err < current_error:
                current = neighbour
                current_error = neighbour_err
                current_error_percent = 100 * (current_error / suzuki_error)
                print('New best: error: {} percent: {} solution: {})'.format(current_error, current_error_percent,
                                                                             current))
                break
Exemplo n.º 2
0
def compare_lambda_over_n(input_df, start_row, end_row, output_folder_path):
    df = input_df.copy()
    df.insert(1, 'optimised error', None)
    df.insert(1, 'suzuki error', None)
    df.insert(1, '%', None)
    if not os.path.isdir(output_folder_path):
        os.makedirs(output_folder_path)

    output_data_path = os.path.join(
        output_folder_path, 'output_{}_{}.csv'.format(start_row, end_row))

    for row_id in range(start_row - 1, end_row):
        row = df.loc[row_id]

        n = int(row['n'])
        v = list(map(float, list(row['v_1':'v_%d' % n])))
        k = int(row['k'])
        r = int(row['r'])

        p = list(row.loc['p_1':'p_%d' % (5**(k - 1))])
        chain = hchain.HeisenbergChain(n, v)

        suz_err = approx.error(chain, approx.suzuki_solution(k, r), t=2 * n)
        op_err = approx.error(chain, approx.r_copies(p, r), t=2 * n)

        perc = 100 * op_err / suz_err

        df.loc[row_id, 'suzuki error'] = suz_err
        df.loc[row_id, 'optimised error'] = op_err
        df.loc[row_id, '%'] = perc

    df.dropna(inplace=True)
    df.to_csv(output_data_path, index=False)
Exemplo n.º 3
0
def suzuki_sampling(input_df, start_row, end_row, output_folder_path):
    df = input_df.copy()

    NUM_SAMPLES = 100


    for row_id in range(start_row-1, end_row):
        row = df.loc[row_id]

        n = int(row['n'])
        v = row['v_1':'v_%d' % n]
        k = int(row['k'])
        r = int(row['r'])
        scale = float(row['scale'])

        cols = ['n'] + ['v_%d' % i for i in range(1, n+1)] + ['k', 'r', 'scale', 'sampled error', 'suzuki error']

        row_df = pd.DataFrame(columns=cols)

        chain = hchain.HeisenbergChain(n, v)
        sample_length = (5**(k-1))
        suzuki_vector = approx.suzuki(k)

        for _ in range(NUM_SAMPLES):
            noise = np.random.normal(loc=0, scale=scale/sample_length, size=sample_length)
            sample_vector = np.array(suzuki_vector) + noise
            sampled_err = approx.error(chain, approx.r_copies(sample_vector, r), t=2*n)
            suz_err = approx.error(chain, approx.suzuki_solution(k, r), t=2*n)

            row_df.loc[len(row_df)+1] = [n] + list(v) + [k, r, scale, sampled_err, suz_err]

        row_df.to_csv(os.path.join(output_folder_path, 'row_%d.csv'%(row_id+1)))
Exemplo n.º 4
0
    def target_error(ind):
        if NORMALISE:
            norm_ind = norm_f(ind)
        else:
            norm_ind = ind

        final_ind = approx.r_copies(approx.expand_vals(ind), r)

        return approx.error(chain, final_ind, t=2 * chain.n),
Exemplo n.º 5
0
def greedy():
    """ Run greedy hillclimber. Enumerate neighbourhood and choose best. """

    random.seed(1234)

    chain = hchain.HeisenbergChain(num_qubits, v)

    suzuki = np.array(approx.suzuki(k))
    suzuki_error = approx.error(chain, approx.r_copies(suzuki, r), t)
    print('Suzuki error: {}'.format(suzuki_error))

    # Start at Suzuki
    current = suzuki
    current_error = suzuki_error

    for gen in range(1, gens + 1):

        current_error_percent = 100 * (current_error / suzuki_error)
        print('Gen: {} Best: {} Percent: {} '.format(gen, current_error,
                                                     current_error_percent))

        first = random.randint(1, num_p_values)
        second = random.randint(1, num_p_values)

        neighbour = current.copy()
        neighbour[first - 1] = neighbour[first - 1] + step_size
        neighbour[second - 1] = neighbour[second - 1] - step_size

        neighbour_err = approx.error(chain, approx.r_copies(neighbour, r), t)

        neighbour_err_percent = 100 * (neighbour_err / suzuki_error)

        print('Step {}  error: {}, error %: {}'.format(gen, neighbour_err,
                                                       neighbour_err_percent))

        if neighbour_err < current_error:
            current = neighbour
            current_error = neighbour_err
            current_error_percent = 100 * (current_error / suzuki_error)
            print('New best: error: {} percent: {} solution: {})'.format(
                current_error, current_error_percent, current))
Exemplo n.º 6
0
def run(input_file, start, end):

    if not os.path.isdir(OUTPUT_DIR):
        os.makedirs(OUTPUT_DIR)

    input_file_prefix = os.path.splitext(os.path.basename(input_file))[0]

    output_file = os.path.join(
        OUTPUT_DIR, input_file_prefix + '_output_{}_{}.csv'.format(start, end))

    header, all_rows = read_all(input_file)

    with open(output_file, 'w') as outcsv:

        output_header = header + ['suzuki error', 'optimised error', '%']

        writer = csv.DictWriter(outcsv, output_header)
        writer.writeheader()

        for row in all_rows[start - 1:end]:

            n = int(row['n'])
            k = int(row['k'])
            r = int(row['r'])
            t = int(row['t'])

            p_vect = {k: v for k, v in row.items() if k.startswith('p_')}
            v_vect = {
                k: v
                for k, v in row.items() if k.startswith('v_') and v != ''
            }

            v_values = [float(v) for v in v_vect.values()]
            p_values = [float(p) for p in p_vect.values()]

            chain = hchain.HeisenbergChain(n, v_values)

            suz_err = approx.error(chain, approx.suzuki_solution(k, r), t)
            op_err = approx.error(chain, approx.r_copies(p_values, r), t)

            percentage = 100 * op_err / suz_err

            row['suzuki error'] = suz_err
            row['optimised error'] = op_err
            row['%'] = percentage

            writer.writerow(row)
Exemplo n.º 7
0
def evaluate_rows(input_df, start_row, end_row, output_folder_path):
    df = input_df.copy()
    if not os.path.isdir(output_folder_path):
        os.makedirs(output_folder_path)

    logs_path = os.path.join(output_folder_path, 'logs')
    if not os.path.isdir(logs_path):
        os.makedirs(logs_path)

    output_data_path = os.path.join(output_folder_path, 'output_{}_{}.csv'.format(start_row, end_row))

    for row_id in range(start_row-1, end_row):
        row = df.loc[row_id]

        n = int(row['n'])
        v = row['v_1':'v_%d' % n]
        k = int(row['k'])
        r = int(row['r'])
        seed = int(row['seed'])
        gens = int(row['gens'])

        chain = hchain.HeisenbergChain(n, v)

        t = time.time()
        pop, log, hof = run_cmaes_p(v=v, k=k, r=r, seed=seed, generations=gens)
        t = time.time() - t

        best = hof[0]

        suz_err = approx.error(chain,approx.suzuki_solution(k, r),t=2*n)
        op_err = approx.error(chain,approx.r_copies(best, r),t=2*n)
        perc = 100*op_err/suz_err

        for j in range(1,5**(k-1)+1):
            df.loc[row_id,'p_%d'%j] = best[j-1]
        df.loc[row_id,'optimised error'] = op_err
        df.loc[row_id, 'suzuki error'] = suz_err
        df.loc[row_id, '% error'] = perc
        df.loc[row_id, 'time'] = t

        pd.DataFrame(log).to_csv(os.path.join(logs_path, 'row_{}.csv'.format(row_id + 1)), index=False)

    df.dropna(inplace=True)
    df.to_csv(output_data_path, index=False)
Exemplo n.º 8
0
    def testRcopies(self):

        x = [1] * 10
        r = 30
        expected = [1 / 30] * 300
        self.assertTrue(np.allclose(expected, approx.r_copies(x, r)))
Exemplo n.º 9
0
    def target_error(ind):
        final_ind = approx.r_copies(ind, int((r * 5**(k - 1)) / len(ind)))

        return approx.error(chain, final_ind, t=2 * chain.n),