Example #1
0
def f(t, n, k):
    t = t * pi
    state = prep(n, k)
    #state = dicke(n, k)
    state = common.mixer(state, common.create_ring_M(n), t)
    state = [np.real(np.conj(s) * s) for s in state]
    probs = []
    for i in range(0, 2**n):
        if common.num_ones(i) == k:
            probs.append(state[i])
    return probs
Example #2
0
def test():
    n = 4
    eps = 1e-15
    M = common.create_ring_M(n)
    beta = 17.5 * pi
    ring = expm(np.complex(0, -1) * beta * M) - np.eye(2**n)
    total = 0
    for i in range(2**n):
        for j in range(2**n):
            ring[i, j] = np.real(ring[i, j] * np.conj(ring[i, j]))
            if ring[i, j] < eps: ring[i, j] = 0
            total += ring[i, j]
    print(np.real(total))
def dicke_ps_ring(G, k, p, num_steps):
    C = common.create_C(G)
    M = common.create_ring_M(len(G.nodes))
    kwargs = {
        'method': 'L-BFGS-B',
        'args': (G, C, M, k, p),
        'bounds': [[0, pi / 2], [0, pi]]
    }
    optimal = basinhopping(opt,
                           np.array([pi / 4, pi / 2]),
                           minimizer_kwargs=kwargs,
                           niter=num_steps)
    return -optimal.fun, optimal.x
Example #4
0
def main():
    n = 2
    k = 1
    eps = 0.001
    start = 0
    end = 10
    M = common.create_ring_M(n)
    period = []
    step = 0.01
    beta = start
    while beta < end:
        ring = expm(np.complex(0, -1) * beta * pi * M)
        total = 0
        # check if all off diagonal elements are 0
        for i in range(2**n):
            for j in range(2**n):
                #if common.num_ones(j) == k:
                if i != j:
                    total += np.real(ring[i, j] * np.conj(ring[i, j]))
        if total < eps:
            # Now check phases are equal
            noteq = False
            for i in range(1, 2**n):
                if (np.real(ring[0, 0]) - np.real(ring[i, i])) > eps or (
                        np.imag(ring[0, 0]) - np.imag(ring[i, i])) > eps:
                    noteq = True
                    break
            if noteq:
                beta += step
                continue
            if total < 1e-12: print('******************************')
            print('b: ' + str(beta) + '\t t: ' + str(total) + '\t t*pi: ' +
                  str(beta * pi))
            period.append(beta)
        beta += step

    print(period)
    dist = []
    for i in range(len(period) - 1):
        dist.append(period[i + 1] - period[i])
    print(dist)
Example #5
0
def ring_ps_ring(G, k, p, num_steps):
    C = common.create_C(G)
    M = common.create_ring_M(len(G.nodes))
    exp_arr = []
    angle_arr = []

    num_init = int(comb(len(G.nodes), k))
    for m in range(0, num_init):
        kwargs = {
            'method': 'L-BFGS-B',
            'args': (G, C, M, k, p, m),
            'bounds': [[0, pi / 2], [0, pi], [0, pi]]
        }
        optimal = basinhopping(opt,
                               np.array([pi / 4, pi / 2, pi / 2]),
                               minimizer_kwargs=kwargs,
                               niter=num_steps)
        angle_arr.append(optimal.x)
        exp_arr.append(-optimal.fun)

    avg = 0
    for entry in exp_arr:
        avg += entry * (1 / num_init)
    return avg, angle_arr
    plt.title('<C> histogram for p = ' + str(p) + ', gi=502, samples=' +
              str(num_samples))
    plt.xlabel('Value of measured solution')
    plt.ylabel('Probability of measuring')
    axes = plt.gca()
    axes.set_ylim([0, 0.5])
    if not os.path.exists('hist/fig/'): os.mkdir('hist/fig/')
    plt.savefig('hist/fig/p' + str(p) + '.png')
    #plt.show()
    plt.cla()


if __name__ == '__main__':
    G = nx.read_gpickle('atlas/502.gpickle')
    C = common.create_C(G)
    M = common.create_ring_M(len(G.nodes))
    k = int(len(G.nodes) / 2)

    num_samples = 1000

    max_p = 10
    best_g, best_b = [], []
    for p in range(1, max_p + 1):
        found = False
        data = [0] * 6
        print('--------- p = ' + str(p) + '----------')
        path = 'hist/' + str(p) + '.hist'
        if os.path.exists(path):
            with open(path, 'rb') as f:
                try:
                    data = pickle.load(f)
Example #7
0
def temp_map():
    global G
    random.seed(4)
    num_nodes = 10
    G = nx.fast_gnp_random_graph(num_nodes, 0.5)
    while not nx.is_connected(G):
        G = nx.fast_gnp_random_graph(num_nodes, 0.5)
    k = int(len(G.nodes) / 2)
    C = common.create_C(G, k)
    #M = common.create_complete_M(len(G.nodes), k)
    M = common.create_ring_M(len(G.nodes), k)

    p = Process(target=draw)
    p.start()

    num_steps = 50
    gamma, beta = 0, 0
    g_list, grid = [], []
    grid_min = -1
    grid_max = 0
    fig, ax = plt.subplots()

    print('0/' + str(num_steps) + '\t' + str(datetime.datetime.now().time()))
    for i in range(0, num_steps):
        for j in range(0, num_steps):
            val = qaoa(gamma, beta, G, C, M, k)
            g_list.append(val)
            if grid_max < val: grid_max = val
            if grid_min == -1: grid_min = val
            if grid_min > val: grid_min = val
            gamma += 2 * pi / (num_steps - 1)
        beta += pi / (2 * (num_steps - 1))
        gamma = 0
        grid.append(g_list)
        g_list = []
        print(
            str(i + 1) + '/' + str(num_steps) + '\t' +
            str(datetime.datetime.now().time()))

    grid = list(reversed(grid))

    size = 15
    axis_size = 17
    im = ax.imshow(grid,
                   aspect='auto',
                   extent=(0, 2, 0, 0.5),
                   interpolation='gaussian',
                   cmap=cm.inferno_r)
    cbar = ax.figure.colorbar(im, ax=ax)
    #cbar = ax.figure.colorbar(im, ax=ax, ticks=[])
    #cbar.ax.tick_params(labelsize=size)
    #cbar.ax.set_ylabel('$\\langle H_P \\rangle$', rotation=0, va="bottom")
    #cbar.ax.get_yaxis().labelpad = 28
    #cbar.ax.set_ylabel('$\\langle H_P \\rangle$', rotation=0, fontsize=axis_size)

    plt.gca().set_xlabel('$\\gamma\,/\,\pi$', fontsize=axis_size)
    plt.gca().set_ylabel('$\\beta\,/\,\pi$', fontsize=axis_size)

    plt.xticks([0, 0.5, 1, 1.5, 2], size=size)
    plt.yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5], size=size)

    #plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
    #plt.gca().set_xlim([0.8,6.2])
    #plt.gca().set_ylim([1, 1.10])

    extent = im.get_extent()
    ax.set_aspect(abs((extent[1] - extent[0]) / (extent[3] - extent[2])) / 1)
    #plt.title('$\\beta \\ vs \\ \\gamma$\nn=' + str(len(G.nodes)) + ', k=' + str(k) + \
    #', p=' + str(1) + ', grid_size=' + str(num_steps) + 'x' + str(num_steps) + ', gi=' + str(gi))
    plt.tight_layout()
    plt.show()
Example #8
0
def temp_map():
    total = []
    for ii in range(1, 100):
        #gi = random.randint(143, 955)
        #print('gi = ' + str(gi))
        #G, C, M, k = common.get_stuff(gi)
        G = nx.gnp_random_graph(7, random.uniform(0, 1))
        while not nx.is_connected(G):
            G = nx.gnp_random_graph(7, random.uniform(0, 1))
        k = int(len(G.nodes) / 2)
        C = common.create_C(G)
        M = common.create_ring_M(len(G.nodes))

        num_steps = 50
        gamma, beta = 0, 0
        g_list, grid = [], []
        grid_min = -1
        grid_max = 0
        fig, ax = plt.subplots()

        print('0/' + str(num_steps) + '\t' +
              str(datetime.datetime.now().time()))
        for i in range(0, num_steps):
            for j in range(0, num_steps):
                val = qaoa(gamma, beta, G, C, M, k, 1, 1)
                g_list.append(val)
                if grid_max < val: grid_max = val
                if grid_min == -1: grid_min = val
                if grid_min > val: grid_min = val
                gamma += pi / (2 * (num_steps - 1))
            beta += pi / (2 * (num_steps - 1))
            gamma = 0
            grid.append(g_list)
            g_list = []
            print(
                str(i + 1) + '/' + str(num_steps) + '\t' +
                str(datetime.datetime.now().time()))

        grid = list(reversed(grid))
        print('-------------- max grid <C>: ' + str(grid_max))
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                grid[i][j] = (1 /
                              (grid_max - grid_min)) * (grid[i][j] - grid_min)

        if not total:
            total = grid
        else:
            for i in range(len(total)):
                for j in range(len(total[0])):
                    total[i][j] += grid[i][j]

        temp = total
        '''
        temp_max = -1
        temp_min = -1
        for i in range(len(total)):
            for j in range(len(total[0])):
                if temp_max == -1: temp_max = temp[i][j]
                if temp[i][j] > temp_max: temp_max = temp[i][j]
                if temp_min == -1: temp_min = temp[i][j]
                if temp[i][j] < temp_min: temp_min = temp[i][j]
                #temp[i][j] = (1/ii)*temp[i][j]
        for i in range(len(total)):
            for j in range(len(total[0])):
                temp[i][j] = (1/(temp_max-temp_min))*(temp[i][j] - temp_min)
        '''

        SIZE = 11
        plt.rc('font', size=SIZE)  # controls default text sizes
        plt.rc('axes', titlesize=SIZE)  # fontsize of the axes title
        plt.rc('axes', labelsize=SIZE)  # fontsize of the x and y labels
        plt.rc('xtick', labelsize=SIZE)  # fontsize of the tick labels
        plt.rc('ytick', labelsize=SIZE)  # fontsize of the tick labels
        plt.rc('legend', fontsize=SIZE)  # legend fontsize
        plt.rc('figure', titlesize=SIZE)  # fontsize of the figure title

        im = ax.imshow(temp,
                       aspect='auto',
                       extent=(0, 0.5, 0, 0.5),
                       interpolation='gaussian',
                       cmap=cm.inferno_r)
        cbar = ax.figure.colorbar(im, ax=ax, ticks=[])
        #cbar.ax.set_ylabel('$\\langle H_P \\rangle$', rotation=0, va="bottom")
        cbar.ax.get_yaxis().labelpad = 25
        cbar.ax.set_ylabel('average\n$\\langle H_P \\rangle$', rotation=0)

        plt.xlabel('$\\gamma\,/\,\pi$')
        plt.ylabel('$\\beta\,/\,\pi$')
        #plt.title('$\\beta \\ vs \\ \\gamma$\nn=' + str(len(G.nodes)) + ', k=' + str(k) + \
        #', p=' + str(1) + ', grid_size=' + str(num_steps) + 'x' + str(num_steps) + ', gi=' + str(gi))
        #plt.show()
        plt.savefig('overlay-ring-random/' + str(ii) + '.svg')