Exemplo n.º 1
0
    def solve_all(self, solver=None, **kwargs):
        '''Solve all possible input configurations for the zone using the
        specified solver

        inputs: solver  : A solver function which takes h and J values and
                         returns some form of an output to be used externally
                kwargs  : arguments to pass to solver

        outputs: cases  : A list of all considered configurations of driver and
                         zone input polarizations
                 outs   : A dict of the corresponding output dicts from solver
                 z-order: order of zones as they appear in outs keys
        '''

        # relative indices in each input-zone of cells which couple in.
        c_inds = {}
        for z in self.C_ins:
            z_inds = list(set(np.nonzero(self.C_ins[z])[0].tolist()))
            c_inds[z] = z_inds

        # input zone order
        z_order = sorted(c_inds)

        # set of all driver inputs
        driver_inds = gen_pols(len(self.drivers))
        if len(driver_inds) == 0:
            driver_inds = [()]

        # set of all inputs for each input-zone
        inzone_inds = [gen_pols(len(c_inds[z])) for z in c_inds]

        # combine into list product for easy looping
        cases = list(itertools.product(driver_inds, *inzone_inds))

        # run each configuration, solve
        outs = {}

        for case in cases:
            # compute driver contribution to h
            self.h_driver = .5 * np.matrix(case[0]) * self.C_driver
            # for each input zone, map pol key to state and get h contr.
            self.h = self.h_fixed + self.h_driver
            for i in xrange(1, len(case)):
                key = z_order[i - 1]
                pol = np.zeros([1, len(self.C_ins[key])], dtype=float)
                pol[0, c_inds[key]] = case[i]
                self.h += .5 * np.asmatrix(pol) * self.C_ins[key]

            outs[case] = solver(self.h, -.5 * self.J, **kwargs)
Exemplo n.º 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)
Exemplo n.º 3
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]))
Exemplo n.º 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)
Exemplo n.º 5
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)
Exemplo n.º 6
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
Exemplo n.º 7
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
Exemplo n.º 8
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()
Exemplo n.º 9
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()