예제 #1
0
def main(fname):
    ''' '''

    # load QCA file
    cells, spacing, zones, J, feedback = parse_qca_file(fname, one_zone=True)
    J = convert_to_lim_adjacency(cells, spacing, J)

    N = len(cells)

    h = np.array([0] * N, dtype=float)
    g = np.array([0] * N, dtype=float)

    ninds = range(N)

    for i in xrange(N_TRIALS):

        # shuffle J
        np.random.shuffle(ninds)

        # generate scale
        sc = 200 * np.random.random()

        hh = sc * h[ninds]
        JJ = sc * J[ninds, :][:, ninds]
        gg = sc * g[ninds]

        val, scale, inds = hash_problem(hh, JJ, gg)

        print val, scale
예제 #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 main(fname):

    try:
        cells, spacing, J = parse_qca_file(fname)
    except:
        print('Failed to load QCA file...')
        return

    name = os.path.basename(fname).ljust(35)
    ncells, ninputs = count_cells(cells)
    print('{0}: {1} cells,\t{2} inputs'.format(name, ncells, ninputs))
예제 #4
0
def find_spectrum(fname, adj=None):
    ''' '''

    cells, spacing, zones, J, feedback = parse_qca_file(fname, one_zone=True)
    h, J = qca_to_coef(cells, spacing, J, adj=adj)
    h, J = normalized_coefs(h,J)

    # get clocking schedule
    s, eps, gamma = clock_schedule(scheme='linear')

    spectrum = Spectrum()

    spectrum.solve(h, J, eps, gamma, show=True, exact=False)
예제 #5
0
def find_spectrum(fname, adj=None):
    ''' '''

    cells, spacing, zones, J, feedback = parse_qca_file(fname, one_zone=True)
    h, J = qca_to_coef(cells, spacing, J, adj=adj)
    h, J = normalized_coefs(h, J)

    # get clocking schedule
    s, eps, gamma = clock_schedule(scheme='linear')

    spectrum = Spectrum()

    spectrum.solve(h, J, eps, gamma, show=True, exact=False)
예제 #6
0
def load_qca(fname):

    cells, spacing, zones, J, feedback = parse_qca_file(fname, one_zone=True)

    J = convert_adjacency(cells, spacing, J, adj="full")
    J = -J / np.max(np.abs(J))

    if SAVE_COEF:
        fname = os.path.splitext(os.path.basename(fname))[0]
        fname += os.path.extsep + "coef"
        to_coef(fname, J)

    return J
예제 #7
0
def load_qca(fname):

    cells, spacing, zones, J, feedback = parse_qca_file(fname, one_zone=True)

    J = convert_adjacency(cells, spacing, J, adj='full')
    J = -J / np.max(np.abs(J))

    if SAVE_COEF:
        fname = os.path.splitext(os.path.basename(fname))[0]
        fname += os.path.extsep + 'coef'
        to_coef(fname, J)

    return J
예제 #8
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]))
예제 #9
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)
예제 #10
0
def qca_sim(fn, **kwargs):
    '''Simulate all possible outcomes for each zone of a given qca circuit'''

    # parse QCADesigner file
    cells, spacing, zones, J, feedback = parse_qca_file(fn, show=False)

    # check for specification of adjacency type
    if 'adj' in kwargs:
        if kwargs['adj'].lower() == 'full':
            J = convert_to_full_adjacency(cells, spacing, J)
        elif kwargs['adj'].lower() == 'lim':
            J = convert_to_lim_adjacency(cells, spacing, J)

    # set the solver type
    if 'solver' in kwargs:
        try:
            solver = SOLVERS[kwargs['solver'].lower()]
        except:
            print('No solver specified. Using default...')
            solver = SOLVERS['default']
    else:
        solver = SOLVERS['default']

    # set up zone formulation
    Gz = construct_zone_graph(cells, zones, J, feedback, show=False)
    Zones = {key: Zone(key, Gz, J, cells, feedback) for key in Gz.nodes()}
    # solve every zone for every possible set of inputs
    solution = Solution(Gz)
    for i in xrange(len(zones)):
        for j in xrange(len(zones[i])):
            key = (i, j)
            cases, outs, z_order = Zones[key].solve_all(solver)
            solution.add_zone(Zones[key], outs, z_order)

    # write solution to file
    solution.write_to_file('./qca_sim_test')

    # run solution inputs (single sets)
    input_inds = solution.get_inputs()

    input_pols = gen_pols(len(input_inds))  # set of all possible input pols

    print 'start'
    out = {}  # dict of outputs lists for each input polarization list
    for pols in input_pols:
        input_pol = {(0, 0): [(pols, )]}
        out[pols] = solution.run_input_sequence(input_pol)

    pprint(out)
예제 #11
0
def exact_solve(fname, gammas=[0.], k=-1):
    '''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
    
    # isolate each type of cell
    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 label to index in list of normals
    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]
    
    h0 = np.dot(P_f, J_f).reshape([-1,])

    # for each polarization, solve for all gammas
    for pol in polarizations:
        h = h0 + np.dot(pol, J_d)
        sols = {}
        for gamma in gammas:
            pass
            
        
    
                
예제 #12
0
def from_qca_file(fname, adj=None):
    ''' '''

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

    # 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

    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 gamma=0 and extimate remaining spectrum
    for pol in gen_pols(len(drivers)):
        h = h0 + np.dot(pol, J_d)
        yield h, J_n
예제 #13
0
def exact_solve(fname, gammas=[0.], k=-1):
    '''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

    # isolate each type of cell
    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 label to index in list of normals
    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]

    h0 = np.dot(P_f, J_f).reshape([
        -1,
    ])

    # for each polarization, solve for all gammas
    for pol in polarizations:
        h = h0 + np.dot(pol, J_d)
        sols = {}
        for gamma in gammas:
            pass
예제 #14
0
def main(fname):
    
    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 = 1.*(convert_adjacency(cells, spacing, J, adj=ADJ) != 0)
    
    G = nx.Graph(J)
    for k in G:
        G.node[k]['w'] = 1./len(G[k])**2
        
    pos = graphviz_layout(G)
    nx.draw(G, pos=pos, with_labels=True)
    plt.show()
    
    chlebikova(G)
예제 #15
0
파일: test_bcp.py 프로젝트: whigg/qca-embed
def main(fname):

    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 = 1. * (convert_adjacency(cells, spacing, J, adj=ADJ) != 0)

    G = nx.Graph(J)
    for k in G:
        G.node[k]['w'] = 1. / len(G[k])**2

    pos = graphviz_layout(G)
    nx.draw(G, pos=pos, with_labels=True)
    plt.show()

    chlebikova(G)
예제 #16
0
def from_qca_file(fname, adj=None):
    ''' '''

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

    # 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

    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 gamma=0 and extimate remaining spectrum
    for pol in gen_pols(len(drivers)):
        h = h0 + np.dot(pol, J_d)
        yield h, J_n
예제 #17
0
def main(fname):
    ''' '''
    
    try:
        cells, spacing, zones, J, fb = parse_qca_file(fname, one_zone=True)
    except:
        print('Failed to load qca file')
        return
        
    h, J = qca_to_coef(cells, spacing, J, adj='full')
    
    h /= np.max(np.abs(J))
    J /= np.max(np.abs(J))
    
    for _ in range(100):
        h_, J_, K, hp, inds = mix_seriation(h, J)
        hval, K_, hp_, inds_ = hash_problem(h_, J_)
    
        if False:    
            print('K: {0:.4f}\t hp: {1}\ninds: {2}'.format(K, hp, inds))
            print('K: {0:.4f}\t hp: {1}\ninds: {2}'.format(K_, hp_, inds_))
        
        print('hash val: {0}'.format(hval))
예제 #18
0
def main(fname):
    ''' '''

    try:
        cells, spacing, zones, J, fb = parse_qca_file(fname, one_zone=True)
    except:
        print('Failed to load qca file')
        return

    h, J = qca_to_coef(cells, spacing, J, adj='full')

    h /= np.max(np.abs(J))
    J /= np.max(np.abs(J))

    for _ in range(100):
        h_, J_, K, hp, inds = mix_seriation(h, J)
        hval, K_, hp_, inds_ = hash_problem(h_, J_)

        if False:
            print('K: {0:.4f}\t hp: {1}\ninds: {2}'.format(K, hp, inds))
            print('K: {0:.4f}\t hp: {1}\ninds: {2}'.format(K_, hp_, inds_))

        print('hash val: {0}'.format(hval))
예제 #19
0
#!/usr/bin/python

from gui.qca_widget import test_app
from parse_qca import parse_qca_file
from numpy.random import random

import sys

if __name__ == '__main__':
    try:
        fn = sys.argv[1]
    except:
        print('no file entered...')
        sys.exit()

    cells, spacing, zones, J = parse_qca_file(fn)
    N = len(cells)
    pols = [2 * random() - 1 for _ in xrange(N)]
    parts = [int(random() * 6) - 1 for _ in xrange(N)]
    test_app(cells, spacing, pols, parts, style='pols')
예제 #20
0
#!/usr/bin/python

from gui.qca_widget import test_app
from parse_qca import parse_qca_file
from numpy.random import random

import sys

if __name__ == '__main__':
    try:
        fn = sys.argv[1]
    except:
        print('no file entered...')
        sys.exit()

    cells, spacing, zones, J = parse_qca_file(fn)
    N = len(cells)
    pols = [2*random()-1 for _ in xrange(N)]
    parts = [int(random()*6)-1 for _ in xrange(N)]
    test_app(cells, spacing, pols, parts, style='pols')
예제 #21
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()
예제 #22
0
def main(fname):
    ''' '''
    
    plt.close('all')

    # parse QCA file
    cells, spacing, zones, J, feedback = parse_qca_file(fname, one_zone=False)
    J /= -np.max(np.abs(J))

    Nz = len(zones)     # number of zones

    # get isolated coefficients
    hs, Js, Jxs = construct_coefs(cells, zones, J)
    Mz = [len(h) for h in hs]    

    # construct static Hamiltonians
    H0, Gammas = construct_hams(hs, Js, Jxs)
    
    # loop through gamma configurations
    schedule = gamma_schedule(GMIN, GMAX, Nz, NSTEPS)
    G = []
    C = []
    SC = [[] for _ in xrange(Nz)]
    E = []
    while True:
        try:
            gammas = next(schedule)
        except:
            break
        sys.stdout.write('\r{0:.1f}%'.format((len(G)+1)*100./NSTEPS))
        sys.stdout.flush()
        G.append(gammas)

        # construct new Hamiltonian
        H = H0.copy()
        for n in xrange(Nz):
            H = H + gammas[n]*Gammas[n]
        
        # analyse spectrum
        if H.shape[0]>5:
            evals, evecs = eigsh(H, which='SA', k=2*int(np.log2(H.shape[0])))
        else:
            evals, evecs = eigh(H.todense())
        
#        to_state(evecs)
        
        # decompose and store
        comp, scomps = decompose(evecs, evals, Mz)
        
        C.append(comp)
        for i in xrange(Nz):
            SC[i].append(scomps[i])
        E.append(evals)
    
    # standardize formatting
    G = np.array(G)
    E = np.array(E)
    C = np.array(C).transpose()
    SC = [np.array(SC[i]).transpose() for i in xrange(Nz)]

    # find state reordering, sorted by max contribution summed over full clock
    C = C[np.argsort(-np.sum(C, axis=1)),:]
    SC = [sc[np.argsort(-np.sum(sc, axis=1)), :] for sc in SC]    
    
    C = C[0:int(np.sqrt(C.shape[0])), :]
#    SC = [sc[0:int(np.sqrt(sc.shape[0])), :] for sc in SC]

    X = np.linspace(0, 1, NSTEPS)
    
    plt.figure('Spectrum')
    plt.plot(X, E)
    plt.xlabel('Time', fontsize=FS)
    plt.ylabel('Energy (eV)', fontsize=FS)
    plt.show(block=False)
    
    plt.figure('Gamma Schedule')
    plt.plot(X, G)
    plt.xlabel('Time', fontsize=FS)
    plt.ylabel('Gamma', fontsize=FS)
    plt.show(block=False)
    
    plt.figure('Decomposition')
    plt.imshow(C, interpolation='none', aspect='auto', origin='lower')
    plt.xlabel('Time', fontsize=FS)
    plt.ylabel('State index', fontsize=FS)
    plt.colorbar()
    plt.show(block=False)
    
    for i in xrange(Nz):
        plt.figure('Zone: {0}'.format(i))
        plt.imshow(SC[i], interpolation='none', aspect='auto', origin='lower')
        plt.xlabel('Time', fontsize=FS)
        plt.ylabel('State index', fontsize=FS)
        plt.colorbar()
        plt.show(block=False)
    
    plt.show(block=True)
    print('\n')
예제 #23
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()
예제 #24
0
def main(fname):
    ''' '''

    plt.close('all')

    # parse QCA file
    cells, spacing, zones, J, feedback = parse_qca_file(fname, one_zone=False)
    J /= -np.max(np.abs(J))

    Nz = len(zones)  # number of zones

    # get isolated coefficients
    hs, Js, Jxs = construct_coefs(cells, zones, J)
    Mz = [len(h) for h in hs]

    # construct static Hamiltonians
    H0, Gammas = construct_hams(hs, Js, Jxs)

    # loop through gamma configurations
    schedule = gamma_schedule(GMIN, GMAX, Nz, NSTEPS)
    G = []
    C = []
    SC = [[] for _ in xrange(Nz)]
    E = []
    while True:
        try:
            gammas = next(schedule)
        except:
            break
        sys.stdout.write('\r{0:.1f}%'.format((len(G) + 1) * 100. / NSTEPS))
        sys.stdout.flush()
        G.append(gammas)

        # construct new Hamiltonian
        H = H0.copy()
        for n in xrange(Nz):
            H = H + gammas[n] * Gammas[n]

        # analyse spectrum
        if H.shape[0] > 5:
            evals, evecs = eigsh(H, which='SA', k=2 * int(np.log2(H.shape[0])))
        else:
            evals, evecs = eigh(H.todense())


#        to_state(evecs)

# decompose and store
        comp, scomps = decompose(evecs, evals, Mz)

        C.append(comp)
        for i in xrange(Nz):
            SC[i].append(scomps[i])
        E.append(evals)

    # standardize formatting
    G = np.array(G)
    E = np.array(E)
    C = np.array(C).transpose()
    SC = [np.array(SC[i]).transpose() for i in xrange(Nz)]

    # find state reordering, sorted by max contribution summed over full clock
    C = C[np.argsort(-np.sum(C, axis=1)), :]
    SC = [sc[np.argsort(-np.sum(sc, axis=1)), :] for sc in SC]

    C = C[0:int(np.sqrt(C.shape[0])), :]
    #    SC = [sc[0:int(np.sqrt(sc.shape[0])), :] for sc in SC]

    X = np.linspace(0, 1, NSTEPS)

    plt.figure('Spectrum')
    plt.plot(X, E)
    plt.xlabel('Time', fontsize=FS)
    plt.ylabel('Energy (eV)', fontsize=FS)
    plt.show(block=False)

    plt.figure('Gamma Schedule')
    plt.plot(X, G)
    plt.xlabel('Time', fontsize=FS)
    plt.ylabel('Gamma', fontsize=FS)
    plt.show(block=False)

    plt.figure('Decomposition')
    plt.imshow(C, interpolation='none', aspect='auto', origin='lower')
    plt.xlabel('Time', fontsize=FS)
    plt.ylabel('State index', fontsize=FS)
    plt.colorbar()
    plt.show(block=False)

    for i in xrange(Nz):
        plt.figure('Zone: {0}'.format(i))
        plt.imshow(SC[i], interpolation='none', aspect='auto', origin='lower')
        plt.xlabel('Time', fontsize=FS)
        plt.ylabel('State index', fontsize=FS)
        plt.colorbar()
        plt.show(block=False)

    plt.show(block=True)
    print('\n')