Esempio n. 1
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)
Esempio n. 2
0
def main(N, cache_dir=None):
    '''Generate and test a problem with N spins'''

    if WIRE:
        h, J, gam = generate_wire(N)
    else:
        h, J, gam = generate_prob(N)

    t = time()
    if N < 18:
        print('Exact solution...')
        e_vals, e_vecs = solve(h, J, gamma=gam)
        print(e_vals[:2])
    print('Runtime: {0:.3f} (s)'.format(time()-t))

    t = time()
    solver = RP_Solver(h, J, gam, verbose=False, cache_dir=cache_dir)
    solver.solve()

    print('\n'*3)
    print('New RP solution:')
    print(solver.node.Es[:2])
    print('Runtime: {0:.3f} (s)'.format(time()-t))

    msolver = RP_Solver(h, J, gam)
    t = time()
    modes = solver.node.modes
    msolver.mode_solve(modes)

    print('\n'*3)
    print('Mode solved:')
    print(msolver.node.Es[:2])
    print('Runtime: {0:.3f} (s)'.format(time()-t))

    f = lambda x: np.round(x,2)

    print(solver.node.Hx.shape)
    print(msolver.node.Hx.shape)

    Dx = solver.node.Hx - msolver.node.Hx

    print('Dx diffs...')
    for i,j in np.transpose(np.nonzero(Dx)):
        print('\t{0}:{1} :: {2:.3f}'.format(i,j,Dx[i,j]))


    # resolve
    for _ in range(TRIALS):
        t = time()
        nx, nz = solver.ground_fields()

        solver = RP_Solver(h, J, gam, nx=nx, nz=nz, verbose=False, cache_dir=cache_dir)
        solver.solve()

        print('\n'*3)
        print('New RP solution:')
        print(solver.node.Es[:2])
        print('Runtime: {0:.3f} (s)'.format(time()-t))
Esempio n. 3
0
    def run_exact(self):
        '''Compute the spectrum using an exact solver'''

        print('\nRunning Exact Solver method...')
        t = time()
        spectrum = []
        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()
            e_vals, e_vecs = solve(ep*self.h, ep*self.J, gamma=gamma,
                                    more=False)
            spectrum.append(e_vals)
        return spectrum
Esempio n. 4
0
def exact_solve(fname, gammas = [0.], k=-1, adj=None):
    '''Exactly solve the first k eigenstates for a QCA circuit for all possible
    input configurations and all specified transverse fields. Assumes all cells
    have the same transverse field.'''
    
    # 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)
    
    # 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:
            e_vals, e_vecs = solve(h, J_n, gamma=gamma, minimal=True, exact=False)
            # e_vecs[:,i] is the i^th eigenstate
            pols = state_to_pol(e_vecs)
            # pols[:,i] gives the polarizations of all cells for the i^th e-vec
            print('GS: {0:.4f}'.format(e_vals[0]))
            print('pols: {0}'.format(pols[:,0]))
Esempio n. 5
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)
Esempio n. 6
0
def new_gamma_sweep(N, gmax=10.):
    ''' '''

    rp_times = []
    sp_times = []

    N_steps = 50
    gammas = np.linspace(1e-5,1, N_steps)
    eps = np.linspace(1,1e-5, N_steps)

    h, J = gen_wire_coefs(N)
    for i, (gam,ep) in enumerate(zip(gammas,eps)):

        sys.stdout.write('\r{0:.1f}%: {1}'.format(i*100/N_steps, i))
        sys.stdout.flush()

        t = time()
        for _ in range(TRIALS):
            sys.stdout.write('.')
            sys.stdout.flush()
            solver = RP_Solver(ep*h, ep*J, gam)
            solver.solve()
        rp_times.append((time()-t)/TRIALS)
        print(rp_times[-1])

        if N <= SP_MAX:
            t = time()
            for _ in range(TRIALS):
                sys.stdout.write(',')
                sys.stdout.flush()
                e_vals, e_vecs = solve(ep*h, ep*J, gamma=gam)
            sp_times.append((time()-t)/TRIALS)

    plt.figure('Gamma-Sweep')
    plt.plot(gammas, rp_times, 'g', linewidth=LW)

    if sp_times:
        plt.plot(gammas, sp_times, 'b', linewidth=LW)

    plt.xlabel('s', fontsize=GS)
    plt.ylabel('Run-time (s)', fontsize=FS)


    plt.text(0.28, .6, 'H = s$H_T$ + (1-s) $H_P$', fontsize=20)

    if SAVE:
        plt.savefig(os.path.join(IMG_DIR, 'rp_wire_gamma_{0}.eps'.format(N)),
                    bbox_inches='tight')
    plt.show()
Esempio n. 7
0
    def run_exact(self):
        '''Compute the spectrum using an exact solver'''

        print('\nRunning Exact Solver method...')
        t = time()
        spectrum = []
        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()
            e_vals, e_vecs = solve(ep * self.h,
                                   ep * self.J,
                                   gamma=gamma,
                                   more=False)
            spectrum.append(e_vals)
        return spectrum
Esempio n. 8
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')
Esempio n. 9
0
def new_gamma_sweep(N, gmax=10.):
    ''' '''

    rp_times = []
    sp_times = []

    N_steps = 50
    gammas = np.linspace(1e-5, 1, N_steps)
    eps = np.linspace(1, 1e-5, N_steps)

    h, J = gen_wire_coefs(N)
    for i, (gam, ep) in enumerate(zip(gammas, eps)):

        sys.stdout.write('\r{0:.1f}%: {1}'.format(i * 100 / N_steps, i))
        sys.stdout.flush()

        t = time()
        for _ in range(TRIALS):
            sys.stdout.write('.')
            sys.stdout.flush()
            solver = RP_Solver(ep * h, ep * J, gam)
            solver.solve()
        rp_times.append((time() - t) / TRIALS)
        print(rp_times[-1])

        if N <= SP_MAX:
            t = time()
            for _ in range(TRIALS):
                sys.stdout.write(',')
                sys.stdout.flush()
                e_vals, e_vecs = solve(ep * h, ep * J, gamma=gam)
            sp_times.append((time() - t) / TRIALS)

    plt.figure('Gamma-Sweep')
    plt.plot(gammas, rp_times, 'g', linewidth=LW)

    if sp_times:
        plt.plot(gammas, sp_times, 'b', linewidth=LW)

    plt.xlabel('s', fontsize=GS)
    plt.ylabel('Run-time (s)', fontsize=FS)

    plt.text(0.28, .6, 'H = s$H_T$ + (1-s) $H_P$', fontsize=20)

    if SAVE:
        plt.savefig(os.path.join(IMG_DIR, 'rp_wire_gamma_{0}.eps'.format(N)),
                    bbox_inches='tight')
    plt.show()
Esempio n. 10
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')
Esempio n. 11
0
def new_wire_size_sweep(N_max):
    ''' '''

    rp_times = []
    rp_times2 = []
    sp_times = []
    sp_times2 = []

    Ns = np.arange(2, N_max+1)

    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)
        # rp solver
        t = time()
        for _ in range(TRIALS):
            sys.stdout.write(',')
            sys.stdout.flush()
            solver = RP_Solver(h, J, 0)
            solver.solve()
        rp_times.append((time()-t)/TRIALS)

        # rp solver with gamma=eps
        t = time()
        for _ in range(TRIALS):
            sys.stdout.write('.')
            sys.stdout.flush()
            solver = RP_Solver(h, J, 1)
            solver.solve()
        rp_times2.append((time()-t)/TRIALS)

        # exact solver
        if N <= SP_MAX:
            t = time()
            for _ in range(TRIALS):
                sys.stdout.write(',')
                sys.stdout.flush()
                e_vals, e_vecs = solve(h, J, gamma=0)
            sp_times.append((time()-t)/TRIALS)

            t = time()
            for _ in range(TRIALS):
                sys.stdout.write('.')
                sys.stdout.flush()
                e_vals, e_vecs = solve(h, J, gamma=1)
            sp_times2.append((time()-t)/TRIALS)

    # plotting
    plt.figure('Run-times')

    plt.plot(Ns, rp_times, 'g', linewidth=LW)
    plt.plot(Ns[:len(sp_times)], sp_times, 'b', linewidth=LW)

    plt.plot(Ns, rp_times2, 'g--', linewidth=LW)
    plt.plot(Ns[:len(sp_times2)], sp_times2, 'b--', linewidth=LW)

    plt.xlabel('Wire length', fontsize=FS)
    plt.ylabel('Run-time (s)', fontsize=FS)
    plt.legend(['RP-Solver', 'Exact: ARPACK'], fontsize=FS)

    if SAVE:
        plt.savefig(os.path.join(IMG_DIR, 'rp_wire_{0}.eps'.format(N_max)),
                    bbox_inches='tight')
    plt.show()
Esempio n. 12
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()
Esempio n. 13
0
def new_wire_size_sweep(N_max):
    ''' '''

    rp_times = []
    rp_times2 = []
    sp_times = []
    sp_times2 = []

    Ns = np.arange(2, N_max + 1)

    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)
        # rp solver
        t = time()
        for _ in range(TRIALS):
            sys.stdout.write(',')
            sys.stdout.flush()
            solver = RP_Solver(h, J, 0)
            solver.solve()
        rp_times.append((time() - t) / TRIALS)

        # rp solver with gamma=eps
        t = time()
        for _ in range(TRIALS):
            sys.stdout.write('.')
            sys.stdout.flush()
            solver = RP_Solver(h, J, 1)
            solver.solve()
        rp_times2.append((time() - t) / TRIALS)

        # exact solver
        if N <= SP_MAX:
            t = time()
            for _ in range(TRIALS):
                sys.stdout.write(',')
                sys.stdout.flush()
                e_vals, e_vecs = solve(h, J, gamma=0)
            sp_times.append((time() - t) / TRIALS)

            t = time()
            for _ in range(TRIALS):
                sys.stdout.write('.')
                sys.stdout.flush()
                e_vals, e_vecs = solve(h, J, gamma=1)
            sp_times2.append((time() - t) / TRIALS)

    # plotting
    plt.figure('Run-times')

    plt.plot(Ns, rp_times, 'g', linewidth=LW)
    plt.plot(Ns[:len(sp_times)], sp_times, 'b', linewidth=LW)

    plt.plot(Ns, rp_times2, 'g--', linewidth=LW)
    plt.plot(Ns[:len(sp_times2)], sp_times2, 'b--', linewidth=LW)

    plt.xlabel('Wire length', fontsize=FS)
    plt.ylabel('Run-time (s)', fontsize=FS)
    plt.legend(['RP-Solver', 'Exact: ARPACK'], fontsize=FS)

    if SAVE:
        plt.savefig(os.path.join(IMG_DIR, 'rp_wire_{0}.eps'.format(N_max)),
                    bbox_inches='tight')
    plt.show()
Esempio n. 14
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()
Esempio n. 15
0
def main(N, cache_dir=None):
    '''Generate and test a problem with N spins'''

    if WIRE:
        h, J, gam = generate_wire(N)
    else:
        h, J, gam = generate_prob(N)

    t = time()
    if N < 18:
        print('Exact solution...')
        e_vals, e_vecs = solve(h, J, gamma=gam)
        print(e_vals[:2])
    print('Runtime: {0:.3f} (s)'.format(time() - t))

    t = time()
    solver = RP_Solver(h, J, gam, verbose=False, cache_dir=cache_dir)
    solver.solve()

    print('\n' * 3)
    print('New RP solution:')
    print(solver.node.Es[:2])
    print('Runtime: {0:.3f} (s)'.format(time() - t))

    msolver = RP_Solver(h, J, gam)
    t = time()
    modes = solver.node.modes
    msolver.mode_solve(modes)

    print('\n' * 3)
    print('Mode solved:')
    print(msolver.node.Es[:2])
    print('Runtime: {0:.3f} (s)'.format(time() - t))

    f = lambda x: np.round(x, 2)

    print(solver.node.Hx.shape)
    print(msolver.node.Hx.shape)

    Dx = solver.node.Hx - msolver.node.Hx

    print('Dx diffs...')
    for i, j in np.transpose(np.nonzero(Dx)):
        print('\t{0}:{1} :: {2:.3f}'.format(i, j, Dx[i, j]))

    # resolve
    for _ in range(TRIALS):
        t = time()
        nx, nz = solver.ground_fields()

        solver = RP_Solver(h,
                           J,
                           gam,
                           nx=nx,
                           nz=nz,
                           verbose=False,
                           cache_dir=cache_dir)
        solver.solve()

        print('\n' * 3)
        print('New RP solution:')
        print(solver.node.Es[:2])
        print('Runtime: {0:.3f} (s)'.format(time() - t))