Пример #1
0
def solve_coef_file(fname):
    '''solve a coef file using the rp_solver'''
    
    h, J = load_coef_file(fname)

    e_vecs, e_vals, modes = rp_solve(h, J, gam=0.01, cache_dir=None, verbose=True)
    
    print(e_vecs)
Пример #2
0
def approx_solve(fname, gammas=[0.], k=-1, adj=None):
    ''' '''
    # process the QCADesigner file
    try:
        cells, spacing, zones, J, _ = parse_qca_file(fname, one_zone=True)
    except:
        print('Failed to process QCA file: {0}'.format(fname))
        return None

    # convert J to specified adjacency
    J = convert_adjacency(cells, spacing, J, adj=adj)

    # normalize J
    J /= np.max(np.abs(J))

    # group each type of cell: normal = NORMAL or OUTPUT
    drivers, fixeds, normals, outputs = [], [], [], []
    for i, c in enumerate(cells):
        if c['cf'] == CELL_FUNCTIONS['QCAD_CELL_INPUT']:
            drivers.append(i)
        elif c['cf'] == CELL_FUNCTIONS['QCAD_CELL_FIXED']:
            fixeds.append(i)
        else:
            if c['cf'] == CELL_FUNCTIONS['QCAD_CELL_OUTPUT']:
                outputs.append(i)
            normals.append(i)

    print(fixeds)
    # map from output cell labels to indices in normals list
    output_map = {i: n for n, i in enumerate(normals) if i in outputs}

    J_d = J[drivers, :][:, normals]  # matrix for mapping drivers to h
    J_f = J[fixeds, :][:, normals]  # matrix for mapping fixed cells to h
    J_n = J[normals, :][:, normals]  # J internal to set of normal cells

    P_f = [(cells[i]['pol'] if 'pol' in cells[i] else 0.)
           for i in fixeds]  # polarization of fixed cells

    h0 = np.dot(P_f, J_f).reshape([
        -1,
    ])  # h contribution from fixed cells

    # for each polarization, solve for all gammas
    for pol in gen_pols(len(drivers)):
        h = h0 + np.dot(pol, J_d)
        for gamma in gammas:
            t = time()
            e_vals, e_vecs, modes = rp_solve(h, J_n, gam=gamma, verbose=True)
            print('\n')
            print(e_vals[0:2], time() - t)
            if False:
                t = time()
                e_vals, e_vecs = solve(h,
                                       J_n,
                                       gamma=gamma,
                                       minimal=False,
                                       exact=False)
                print(e_vals[0:2], time() - t)
Пример #3
0
def solve_coef_file(fname):
    '''solve a coef file using the rp_solver'''

    h, J = load_coef_file(fname)

    e_vecs, e_vals, modes = rp_solve(h,
                                     J,
                                     gam=0.01,
                                     cache_dir=None,
                                     verbose=True)

    print(e_vecs)
Пример #4
0
def approx_solve(fname, gammas=[0.0], k=-1, adj=None):
    """ """
    # process the QCADesigner file
    try:
        cells, spacing, zones, J, _ = parse_qca_file(fname, one_zone=True)
    except:
        print("Failed to process QCA file: {0}".format(fname))
        return None

    # convert J to specified adjacency
    J = convert_adjacency(cells, spacing, J, adj=adj)

    # normalize J
    J /= np.max(np.abs(J))

    # group each type of cell: normal = NORMAL or OUTPUT
    drivers, fixeds, normals, outputs = [], [], [], []
    for i, c in enumerate(cells):
        if c["cf"] == CELL_FUNCTIONS["QCAD_CELL_INPUT"]:
            drivers.append(i)
        elif c["cf"] == CELL_FUNCTIONS["QCAD_CELL_FIXED"]:
            fixeds.append(i)
        else:
            if c["cf"] == CELL_FUNCTIONS["QCAD_CELL_OUTPUT"]:
                outputs.append(i)
            normals.append(i)

    print(fixeds)
    # map from output cell labels to indices in normals list
    output_map = {i: n for n, i in enumerate(normals) if i in outputs}

    J_d = J[drivers, :][:, normals]  # matrix for mapping drivers to h
    J_f = J[fixeds, :][:, normals]  # matrix for mapping fixed cells to h
    J_n = J[normals, :][:, normals]  # J internal to set of normal cells

    P_f = [(cells[i]["pol"] if "pol" in cells[i] else 0.0) for i in fixeds]  # polarization of fixed cells

    h0 = np.dot(P_f, J_f).reshape([-1])  # h contribution from fixed cells

    # for each polarization, solve for all gammas
    for pol in gen_pols(len(drivers)):
        h = h0 + np.dot(pol, J_d)
        for gamma in gammas:
            t = time()
            e_vals, e_vecs, modes = rp_solve(h, J_n, gam=gamma, verbose=True)
            print("\n")
            print(e_vals[0:2], time() - t)
            if False:
                t = time()
                e_vals, e_vecs = solve(h, J_n, gamma=gamma, minimal=False, exact=False)
                print(e_vals[0:2], time() - t)
Пример #5
0
def wire_size_sweep(N_max):
    '''compute ground and first excited band for up to N_max length
    wires'''

    rp_times = {'naive': [], 'local': [], 'global': []}
    sp_times = []
    Ns = np.arange(2, N_max + 1, int(np.ceil((N_max - 1) * 1. / 40)))
    for N in Ns:
        sys.stdout.write('\r{0:.1f}%: {1}'.format((N - 1) * 100 / (N_max - 1),
                                                  N))
        sys.stdout.flush()
        h, J = gen_wire_coefs(N)
        for k in rp_times:
            if k == 'naive':
                chdir = None
            elif k == 'global':
                chdir = CACHE
            elif k == 'local':
                chdir = os.path.join(CACHE, str(N))
            t = time()
            if False:
                e_vals, e_vecs, modes = rp_solve(h,
                                                 J,
                                                 gam=0.01,
                                                 cache_dir=chdir)
            else:
                solver = RP_Solver(h, J, gam=0, cache_dir=chdir)
                solver.solve()
            rp_times[k].append(time() - t)
        if N <= 0:
            t = time()
            e_vals, e_vecs = solve(h, J, gamma=0.1)
            sp_times.append(time() - t)

    plt.figure('Run-times')
    plt.plot(Ns, rp_times['naive'], 'b', linewidth=2)
    plt.plot(Ns, rp_times['local'], 'g', linewidth=2)
    plt.plot(Ns, rp_times['global'], 'r', linewidth=2)
    if sp_times:
        plt.plot(Ns[:len(sp_times)], sp_times, 'g', linewidth=2)
    plt.xlabel('Wire length')
    plt.ylabel('Run-time (s)')
    plt.legend(['Naive', 'Local', 'Global'], fontsize=FS)
    plt.show()

    if SAVE:
        plt.savefig(os.path.join(IMG_DIR, 'rp_wire_{0}.eps'.format(N_max)),
                    bbox_inches='tight')
Пример #6
0
    def run_rp(self, gset, caching, cache_dir):
        '''Compute the spectrum using the old RP-Solver'''

        print('\nRunning Old RP-Solver method...')
        t = time()

        if caching:
            cache_dir = CACHE if cache_dir is None else cache_dir
        else:
            cache_dir = None

        # find initial modes
        print('Finding initial modes...'),
        e_vals, e_vac, modes = rp_solve(self.h,
                                        self.J,
                                        gam=gset,
                                        verbose=False,
                                        cache_dir=cache_dir)

        print('{0:.2f} sec'.format(time() - t))

        print('Number of included modes: {0}'.format(len(modes)))

        # pre-compute sparse Hamiltonian components
        print('Pre-computing sparse Hamiltonian components...'),
        t = time()
        Hx = build_comp_H([self.h], [self.J], [], 1., [modes])
        diag = Hx.diagonal()
        Hx.setdiag([0] * diag.size)
        print('{0:.2f} sec'.format(time() - t))

        spectrum = []

        print('number of modes: {0}'.format(len(modes)))
        print('Estimating spectrum sweep...')

        for i, (gamma, ep) in enumerate(zip(self.gammas, self.eps)):
            sys.stdout.write('\r{0:.2f}%'.format(i * 100. / self.nsteps))
            sys.stdout.flush()
            Hs = Hx * gamma
            Hs.setdiag(ep * diag)
            e_vals, e_vecs = solve_sparse(Hs, more=True)
            spectrum.append(e_vals)
        print('...done')

        return spectrum
Пример #7
0
def wire_size_sweep(N_max):
    '''compute ground and first excited band for up to N_max length
    wires'''

    rp_times = {'naive': [], 'local': [], 'global': []}
    sp_times = []
    Ns = np.arange(2, N_max+1, int(np.ceil((N_max-1)*1./40)))
    for N in Ns:
        sys.stdout.write('\r{0:.1f}%: {1}'.format((N-1)*100/(N_max-1), N))
        sys.stdout.flush()
        h, J = gen_wire_coefs(N)
        for k in rp_times:
            if k=='naive':
                chdir = None
            elif k == 'global':
                chdir = CACHE
            elif k == 'local':
                chdir = os.path.join(CACHE, str(N))
            t = time()
            if False:
                e_vals, e_vecs, modes = rp_solve(h, J, gam=0.01, cache_dir=chdir)
            else:
                solver = RP_Solver(h, J, gam=0, cache_dir=chdir)
                solver.solve()
            rp_times[k].append(time()-t)
        if N <= 0:
            t = time()
            e_vals, e_vecs = solve(h, J, gamma=0.1)
            sp_times.append(time()-t)


    plt.figure('Run-times')
    plt.plot(Ns, rp_times['naive'], 'b', linewidth=2)
    plt.plot(Ns, rp_times['local'], 'g', linewidth=2)
    plt.plot(Ns, rp_times['global'], 'r', linewidth=2)
    if sp_times:
        plt.plot(Ns[:len(sp_times)], sp_times, 'g', linewidth=2)
    plt.xlabel('Wire length')
    plt.ylabel('Run-time (s)')
    plt.legend(['Naive', 'Local', 'Global'], fontsize=FS)
    plt.show()

    if SAVE:
        plt.savefig(os.path.join(IMG_DIR, 'rp_wire_{0}.eps'.format(N_max)),
                    bbox_inches='tight')
Пример #8
0
    def run_rp(self, gset, caching, cache_dir):
        '''Compute the spectrum using the old RP-Solver'''

        print('\nRunning Old RP-Solver method...')
        t = time()

        if caching:
            cache_dir = CACHE if cache_dir is None else cache_dir
        else:
            cache_dir = None

        # find initial modes
        print('Finding initial modes...'),
        e_vals, e_vac, modes = rp_solve(self.h, self.J, gam=gset,
                                        verbose=False, cache_dir=cache_dir)

        print('{0:.2f} sec'.format(time()-t))

        print('Number of included modes: {0}'.format(len(modes)))

        # pre-compute sparse Hamiltonian components
        print('Pre-computing sparse Hamiltonian components...'),
        t = time()
        Hx = build_comp_H([self.h], [self.J], [], 1., [modes])
        diag = Hx.diagonal()
        Hx.setdiag([0]*diag.size)
        print('{0:.2f} sec'.format(time()-t))

        spectrum = []

        print('number of modes: {0}'.format(len(modes)))
        print('Estimating spectrum sweep...')

        for i, (gamma, ep) in enumerate(zip(self.gammas, self.eps)):
            sys.stdout.write('\r{0:.2f}%'.format(i*100./self.nsteps))
            sys.stdout.flush()
            Hs = Hx*gamma
            Hs.setdiag(ep*diag)
            e_vals, e_vecs = solve_sparse(Hs, more=True)
            spectrum.append(e_vals)
        print('...done')

        return spectrum
Пример #9
0
def compare(fname):
    '''Compare stored solution from D-Wave annealer to computed solutions'''
    
    try:
        fp = open(fname, 'r')
    except:
        print('Failed to open file: {0}'.format(fname))
        return
        
    data = json.load(fp)
    
    qbits = data['qbits']
    qbit_map = {str(qb): n for n, qb in enumerate(qbits)}
    
    N = len(qbits)  # number of qubits
    h = np.zeros([N,], dtype=float)
    J = np.zeros([N,N], dtype=float)
    
    for qb, val in data['h'].iteritems():
        h[qbit_map[qb]] = val

    for qb1 in data['J']:
        for qb2, val in data['J'][qb1].iteritems():
            J[qbit_map[qb1], qbit_map[qb2]] = val
            J[qbit_map[qb2], qbit_map[qb1]] = val
    
    tree = compute_rp_tree(J)
    show_tree(J, tree)    

    G = nx.Graph(J)
    pos = graphviz_layout(G)
    nx.draw(G, pos=pos, with_labels=True)
    plt.show()
    
    e_vals, e_vecs, modes = rp_solve(h, J, gam=0.01)
    
    print(e_vals)
    print(data['energies'])
Пример #10
0
def compare_spectrum(fname, gmin=0.01, gmax=.5, adj='lim'):
    ''' '''
    
    try:
        cells, spacing, zones, J, _ = parse_qca_file(fname, one_zone=True)
    except:
        print('Failed ot process QCA file: {0}'.format(fname))
        return None
        
    # convert J to specified adjacency
    J = convert_adjacency(cells, spacing, J, adj=adj)
    
    # normalize J
    J /= np.max(np.abs(J))
        
    # group each type of cell: normal = NORMAL or OUTPUT
    drivers, fixeds, normals, outputs = [], [], [], []
    for i,c in enumerate(cells):
        if c['cf'] == CELL_FUNCTIONS['QCAD_CELL_INPUT']:
            drivers.append(i)
        elif c['cf'] == CELL_FUNCTIONS['QCAD_CELL_FIXED']:
            fixeds.append(i)
        else:
            if c['cf'] == CELL_FUNCTIONS['QCAD_CELL_OUTPUT']:
                outputs.append(i)
            normals.append(i)
    
    # map from output cell labels to indices in normals list
    output_map = {i: n for n, i in enumerate(normals) if i in outputs}
    
    J_d = J[drivers, :][:, normals]     # matrix for mapping drivers to h
    J_f = J[fixeds, :][:, normals]      # matrix for mapping fixed cells to h
    J_n = J[normals, :][:, normals]     # J internal to set of normal cells
    
    P_f = [(cells[i]['pol'] if 'pol' in cells[i] else 0.) for i in fixeds]  # polarization of fixed cells
    
    h0 = np.dot(P_f, J_f).reshape([-1,])    # h contribution from fixed cells
    
    gammas = np.linspace(gmin, gmax, STEPS)
    
    for pol in gen_pols(len(drivers)):
        h = h0 + np.dot(pol, J_d)
        SP_E, RP_E = [], []
        times = []
        for gamma in gammas:
            print(gamma)
            t = time()
            rp_vals, rp_vecs, modes = rp_solve(h, J_n, gam=gamma, 
                                               cache_dir=CACHE)
            times.append(time()-t)
            sp_vals, sp_vecs = solve(h, J_n, gamma=gamma)
            SP_E.append(sp_vals)
            RP_E.append(rp_vals)
        LSP = min(len(x) for x in SP_E)
        L = min(LSP, min(len(x) for x in RP_E))
        SP_E = np.array([x[:L] for x in SP_E])
        RP_E = np.array([x[:L] for x in RP_E])
        
        plt.figure('spectrum')
        plt.plot(gammas, SP_E, linewidth=2)
        plt.plot(gammas, RP_E, 'x', markersize=8, markeredgewidth=2)
        plt.xlabel('Gamma', fontsize=FS)
        plt.ylabel('Energy', fontsize=FS)
        plt.title('Circuit Spectrum', fontsize=FS)
        plt.show(block=False)
        
        plt.figure('runtimes')
        plt.plot(gammas, times, 'b', linewidth=2)
        plt.xlabel('Gammas', fontsize=FS)
        plt.ylabel('Runtime (s)', fontsize=FS)
        plt.title('RP-Solver runtime', fontsize=FS)
        plt.show()
Пример #11
0
def compare_spectrum(fname, gmin=0.01, gmax=0.5, adj="lim"):
    """ """

    try:
        cells, spacing, zones, J, _ = parse_qca_file(fname, one_zone=True)
    except:
        print("Failed ot process QCA file: {0}".format(fname))
        return None

    # convert J to specified adjacency
    J = convert_adjacency(cells, spacing, J, adj=adj)

    # normalize J
    J /= np.max(np.abs(J))

    # group each type of cell: normal = NORMAL or OUTPUT
    drivers, fixeds, normals, outputs = [], [], [], []
    for i, c in enumerate(cells):
        if c["cf"] == CELL_FUNCTIONS["QCAD_CELL_INPUT"]:
            drivers.append(i)
        elif c["cf"] == CELL_FUNCTIONS["QCAD_CELL_FIXED"]:
            fixeds.append(i)
        else:
            if c["cf"] == CELL_FUNCTIONS["QCAD_CELL_OUTPUT"]:
                outputs.append(i)
            normals.append(i)

    # map from output cell labels to indices in normals list
    output_map = {i: n for n, i in enumerate(normals) if i in outputs}

    J_d = J[drivers, :][:, normals]  # matrix for mapping drivers to h
    J_f = J[fixeds, :][:, normals]  # matrix for mapping fixed cells to h
    J_n = J[normals, :][:, normals]  # J internal to set of normal cells

    P_f = [(cells[i]["pol"] if "pol" in cells[i] else 0.0) for i in fixeds]  # polarization of fixed cells

    h0 = np.dot(P_f, J_f).reshape([-1])  # h contribution from fixed cells

    gammas = np.linspace(gmin, gmax, STEPS)

    for pol in gen_pols(len(drivers)):
        h = h0 + np.dot(pol, J_d)
        SP_E, RP_E = [], []
        times = []
        for gamma in gammas:
            print(gamma)
            t = time()
            rp_vals, rp_vecs, modes = rp_solve(h, J_n, gam=gamma, cache_dir=CACHE)
            times.append(time() - t)
            sp_vals, sp_vecs = solve(h, J_n, gamma=gamma)
            SP_E.append(sp_vals)
            RP_E.append(rp_vals)
        LSP = min(len(x) for x in SP_E)
        L = min(LSP, min(len(x) for x in RP_E))
        SP_E = np.array([x[:L] for x in SP_E])
        RP_E = np.array([x[:L] for x in RP_E])

        plt.figure("spectrum")
        plt.plot(gammas, SP_E, linewidth=2)
        plt.plot(gammas, RP_E, "x", markersize=8, markeredgewidth=2)
        plt.xlabel("Gamma", fontsize=FS)
        plt.ylabel("Energy", fontsize=FS)
        plt.title("Circuit Spectrum", fontsize=FS)
        plt.show(block=False)

        plt.figure("runtimes")
        plt.plot(gammas, times, "b", linewidth=2)
        plt.xlabel("Gammas", fontsize=FS)
        plt.ylabel("Runtime (s)", fontsize=FS)
        plt.title("RP-Solver runtime", fontsize=FS)
        plt.show()