コード例 #1
0
ファイル: main_window.py プロジェクト: retallickj/qca-embed
    def save_coef_file(self, hq, Jq, fname):
        ''' '''
        
        try:
            fp = open(fname, 'w')
        except:
            print('Failed to open file: {0}'.format(fname))
            raise IOError
        
        # chimera size
        M, N, L = self.chimera_widget.M, self.chimera_widget.N, 4
        Nqbits = 2*M*N*L
        
        fp.write('{0}\n'.format(Nqbits))
        
        # h parameters
        for qb in sorted(hq):
            qbl = tuple_to_linear(qb, M, N, L=L, index0=False)
            if hq[qb] != 0:
                fp.write('{0} {1} {2}\n'.format(qbl, qbl, round(hq[qb],3)))
        
        # J parameters
        for qb1, qb2 in sorted(Jq):
            qbl1 = tuple_to_linear(qb1, M, N, L=L, index0=False)
            qbl2 = tuple_to_linear(qb2, M, N, L=L, index0=False)
            if Jq[(qb1, qb2)] != 0:
                fp.write('{0} {1} {2}\n'.format(qbl1, qbl2,
                         round(Jq[(qb1, qb2)], 3)))

        fp.close()
コード例 #2
0
ファイル: main_window.py プロジェクト: whigg/qca-embed
    def save_coef_file(self, hq, Jq, fname):
        ''' '''

        try:
            fp = open(fname, 'w')
        except:
            print('Failed to open file: {0}'.format(fname))
            raise IOError

        # chimera size
        M, N, L = self.chimera_widget.M, self.chimera_widget.N, 4
        Nqbits = 2 * M * N * L

        fp.write('{0}\n'.format(Nqbits))

        # h parameters
        for qb in sorted(hq):
            qbl = tuple_to_linear(qb, M, N, L=L, index0=False)
            if hq[qb] != 0:
                fp.write('{0} {1} {2}\n'.format(qbl, qbl, round(hq[qb], 3)))

        # J parameters
        for qb1, qb2 in sorted(Jq):
            qbl1 = tuple_to_linear(qb1, M, N, L=L, index0=False)
            qbl2 = tuple_to_linear(qb2, M, N, L=L, index0=False)
            if Jq[(qb1, qb2)] != 0:
                fp.write('{0} {1} {2}\n'.format(qbl1, qbl2,
                                                round(Jq[(qb1, qb2)], 3)))

        fp.close()
コード例 #3
0
ファイル: classes.py プロジェクト: whigg/qca-embed
    def run_heur_embedding(self, full_adj=True):
        '''Setup and run the Heuristic algorithm'''

        # update embedding type in case direct call
        self.use_dense = False

        active_cells, qca_adj = self.get_reduced_qca_adj()
        S_size = len(qca_adj)
        A_size = len(self.chimera_adj)

        # construct S
        S = {}
        for i in range(S_size):
            c1 = active_cells[i]
            for j in range(S_size):
                c2 = active_cells[j]
                v = 1 if c2 in qca_adj[c1] else 0
                S[(i, j)] = v
                S[(j, i)] = v

        # construct A
        A = set()
        for qb1 in self.chimera_adj:
            for qb2 in self.chimera_adj[qb1]:
                l1 = tuple_to_linear(qb1,
                                     self.M,
                                     self.N,
                                     L=self.L,
                                     index0=True)
                l2 = tuple_to_linear(qb2,
                                     self.M,
                                     self.N,
                                     L=self.L,
                                     index0=True)
                A.add((l1, l2))

        try:
            print 'Running heuristic embedding'
            models = find_embedding(S, S_size, A, A_size)
        except Exception as e:
            print(e.message())

        print 'Embedding finished'
        self.good = len(models) == S_size

        # map models to standard format
        mapper = lambda ind: linear_to_tuple(
            ind, self.M, self.N, L=self.L, index0=True)
        self.models = {
            active_cells[i]: [mapper(c) for c in models[i]]
            for i in xrange(S_size)
        }
コード例 #4
0
ファイル: classes.py プロジェクト: retallickj/qca-embedding
    def run_heur_embedding(self, full_adj=True):
        '''Setup and run the Heuristic algorithm'''

        # update embedding type in case direct call
        self.embed_method = 'heur'

        active_cells, qca_adj = self.get_reduced_qca_adj()
        S_size = len(qca_adj)
        A_size = len(self.chimera_adj)

        # construct S, the problem adjacency edge list
        S = set()
        smap = {c: i for i, c in enumerate(active_cells)}
        for c1, adj in qca_adj.items():
            for c2 in adj:
                if c1 < c2:
                    S.add((smap[c1], smap[c2]))

        # construct A, the chimera adjacency edge list
        A = set()
        for qb1 in self.chimera_adj:
            for qb2 in self.chimera_adj[qb1]:
                l1 = tuple_to_linear(qb1,
                                     self.M,
                                     self.N,
                                     L=self.L,
                                     index0=True)
                l2 = tuple_to_linear(qb2,
                                     self.M,
                                     self.N,
                                     L=self.L,
                                     index0=True)
                A.add((l1, l2))

        try:
            print 'Running heuristic embedding'
            #models = find_embedding(S, S_size, A, A_size)
            models = find_embedding(S, A)
        except Exception as e:
            print(e.message())

        print 'Embedding finished'
        self.good = len(models) == S_size

        # map models to standard format
        mapper = lambda ind: linear_to_tuple(
            ind, self.M, self.N, L=self.L, index0=True)
        self.models = {
            active_cells[i]: [mapper(c) for c in model]
            for i, model in enumerate(models)
        }
コード例 #5
0
ファイル: proc_sol.py プロジェクト: whigg/qca-embed
    def process_solution(self, fname, coef_data, pol_data, embeddings):
        '''Process a single solution file. It is assumed that the solution
        corresponds to the configurations set by the pol_data and embeddings.
        The filename should be of format [name][pind]_[rt]us.json, where pind
        and rt are integers. If there is only one element of pol_data there is
        no pind.'''

        fprint(os.path.basename(fname))

        NP = len(pol_data)  # number of possible polarization comfigurations
        print(NP)
        pind = None
        if NP == 1:
            fn_regex = re.compile('.*[a-zA-Z_]+_[0-9]+us\.json')
            val_regex = re.compile('_[0-9]+us')
        else:
            fn_regex = re.compile('.*[0-{0}]+_[0-9]+us\.json'.format(NP))
            val_regex = re.compile('[0-{0}]+_[0-9]+us'.format(NP))
        if not fn_regex.match(fname):
            try:
                fn_regex = re.compile('.*_[0-9]+us\.json')
                assert fn_regex.match(fname)
                val_regex = re.compile('_[0-9]+us')
                pind = 0
            except:
                print('Given filename does not match the required pattern: {0}...'.format(fname))
                return

        # extract pind and rt
        val_str = val_regex.findall(fname)[-1]  # will work if this far
        vals = [int(x) for x in re.findall('[0-9]+', val_str)]

        if pind is None:
            pind = 0 if NP==1 else vals[0]
        rt = vals[-1]

#        print('{0}: pind={1}, rt={2}'.format(fname, pind, rt))

        # get solution object
        try:
            solution = DWAVE_Sol(fname)
            sol_name = os.path.basename(fname)
        except IOError:
            return

        h = coef_data[pind]['h']
        J = coef_data[pind]['J']

        efunc = lambda s: compute_E(h, J, s)

        for key in embeddings:
            embed = embeddings[key]
            pols = pol_data[pind][key]
            qbits = list(reduce(lambda x,y:x+y, embed['models'].values()))
            qbits = [tuple_to_linear(qb, M=12, N=12, L=4, index0=False) for qb in qbits]
            sol = solution.get_reduced_solution(qbits, efunc)
            self.save_subsol(embed, pols, sol, h, J, rt, pind, sol_name)
コード例 #6
0
ファイル: classes.py プロジェクト: retallickj/qca-embed
    def run_heur_embedding(self, full_adj=True):
        '''Setup and run the Heuristic algorithm'''

        # update embedding type in case direct call
        self.use_dense = False

        active_cells, qca_adj = self.get_reduced_qca_adj()
        S_size = len(qca_adj)
        A_size = len(self.chimera_adj)

        # construct S
        S = {}
        for i in range(S_size):
            c1 = active_cells[i]
            for j in range(S_size):
                c2 = active_cells[j]
                v = 1 if c2 in qca_adj[c1] else 0
                S[(i, j)] = v
                S[(j, i)] = v

        # construct A
        A = set()
        for qb1 in self.chimera_adj:
            for qb2 in self.chimera_adj[qb1]:
                l1 = tuple_to_linear(qb1, self.M, self.N, L=self.L, index0=True)
                l2 = tuple_to_linear(qb2, self.M, self.N, L=self.L, index0=True)
                A.add((l1, l2))

        try:
            print 'Running heuristic embedding'
            models = find_embedding(S, S_size, A, A_size)
        except Exception as e:
            print(e.message())

        print 'Embedding finished'
        self.good = len(models) == S_size

        # map models to standard format
        mapper = lambda ind: linear_to_tuple(ind, self.M, self.N,
                                             L=self.L, index0=True)
        self.models = {active_cells[i]: [mapper(c) for c in models[i]]
            for i in xrange(S_size)}
コード例 #7
0
ファイル: gt_asis.py プロジェクト: whigg/qca-embed
    def run_processing(self):
        ''' '''

        sol_fname = os.path.normpath(str(self.i1.text()))
        coef_fname = os.path.normpath(str(self.i2.text()))
        summ_fname = os.path.normpath(str(self.i3.text()))

        # confirm fname  format
        if not re.match('.+[.]json', sol_fname):
            print('Invalid filename format...')
            return

        if not coef_fname:
            print('Missing coef file')
            return

        try:
            sol = DWAVE_Sol(sol_fname)
        except IOError:
            print('Failed to read solution file')
            return

        try:
            # load coef file
            h, J = self.load_coef_file(coef_fname)
            efunc = lambda s: compute_E(h, J, s)
        except:
            print('Invalid coef file given...')
            return

        try:
            # load summary file
            embeds = self.process_summ_file(summ_fname)
            subsols = {}
            params = {}
            for k, embed in embeds.items():
                qca_file = os.path.basename(embed['qca_file'])
                if not qca_file == EMBED_FILTER:
                    continue
                qbits = list(
                    reduce(lambda x, y: x + y, embed['models'].values()))
                qbits = [
                    tuple_to_linear(qb, M=12, N=12, L=4, index0=False)
                    for qb in qbits
                ]
                subsols[k] = sol.get_reduced_solution(qbits, efunc)
                h_, J_ = reduce_coefs(h, J, qbits)
                params[k] = {'h': h_, 'J': J_, 'qca_file': qca_file}
        except:
            print('Failed to read embed summary...')
            return

        for k, subsol in subsols.items():
            self.export_subsol(subsol, params[k])

        return
        for k, subsol in subsols.items():
            print(k)
            keys, spins, cell_occ, occ = subsol.model_reduction(embeds[k]['models'], \
                ind_map=lambda qb: tuple_to_linear(qb, 12, 12, index0=False))

            # outcome statistics
            #        cell_occ = sol.cell_occ
            #            cell_occ = subsols[k].cell_occ
            M = max(cell_occ)  # number fo gauge transformation
            N = max(max(x) for k, x in cell_occ.items())  # number of states
            D = np.zeros([M, N], dtype=int)

            for g, co in cell_occ.items():
                for s, o in co.items():
                    D[g - 1, s - 1] = o

            # reject rare outcomes
            if False:
                inds = np.nonzero(np.max(D, axis=0) > 2)[0]
                D = D[:, inds]

            if False:
                if True:
                    stack_plot = stackPlot(label='GT')
                    stack_plot.set_data(D)
                    stack_plot.plot(block=True)
                else:
                    plt.figure('GT')
                    plt.clf()
                    plt.plot(D.transpose(), 'x')
                    plt.show(block=True)

            # statistical distance
            SD = np.zeros([M, M], dtype=float)

            print('Computing statistical distances...')
            k = 0
            for i in range(M - 1):
                for j in range(i + 1, M):
                    k += 1
                    sys.stdout.write('\r{0}%'.format(k * 100. / (.5 * M *
                                                                 (M - 1))))
                    sys.stdout.flush()
                    SD[i, j] = SD[j, i] = stat_dist(D[i, :], D[j, :])
            print('\n')

            # seriate SD matrix if at least one pair of GTs have SD overlap
            if True:
                mask = np.ones(SD.shape, dtype=bool)
                np.fill_diagonal(mask, 0)
                if np.min(SD[mask]) > 0:
                    print('seriating SD matrix...')
                    try:
                        print('\tattempting {0}'.format(self.i4.text()))
                        new_inds = seriate(SD, method=str(self.i4.text()))
                    except:
                        print('\tfailed, using default method')
                        new_inds = seriate(SD, method='MDS')
                    print(new_inds)

                    SD = SD[new_inds, :][:, new_inds]
                else:
                    print(
                        'No overlap between GT distributions. Seriation not possible.'
                    )

            plt.imshow(SD, aspect='auto', interpolation='none')
            plt.colorbar()
            plt.show(block=True)

            if False:
                avg_pdf = np.sum(D, axis=0) * 1. / np.sum(D)

                # look at number of random GT needed to estimate avg_pdf
                sd_est = {k: match_dist(D, avg_pdf, k) for k in range(1, M)}

                pprint(sd_est)

                K = sorted(sd_est.keys())

                plt.figure('SD v K')
                plt.plot(K, [sd_est[x][0] for x in K], 'x')
                plt.xlabel('Number of samples', fontsize=FS)
                plt.ylabel('Statistical Distance', fontsize=FS)
                plt.show(block=False)

                plt.figure('stdev(SD) v K')
                plt.plot(K, [sd_est[x][1] for x in K])
                plt.xlabel('Number of samples', fontsize=FS)
                plt.ylabel('$\sigma_{SD}$', fontsize=FS)
                plt.show(block=True)
コード例 #8
0
ファイル: gt_asis.py プロジェクト: retallickj/qca-embed
    def run_processing(self):
        ''' '''

        sol_fname = os.path.normpath(str(self.i1.text()))
        coef_fname = os.path.normpath(str(self.i2.text()))
        summ_fname = os.path.normpath(str(self.i3.text()))

         # confirm fname  format
        if not re.match('.+[.]json', sol_fname):
            print('Invalid filename format...')
            return

        if not coef_fname:
            print('Missing coef file')
            return

        try:
            sol = DWAVE_Sol(sol_fname)
        except IOError:
            print('Failed to read solution file')
            return

        try:
            # load coef file
            h, J = self.load_coef_file(coef_fname)
            efunc = lambda s: compute_E(h, J, s)
        except:
            print('Invalid coef file given...')
            return

        try:
            # load summary file
            embeds = self.process_summ_file(summ_fname)
            subsols = {}
            params = {}
            for k, embed in embeds.items():
                qca_file = os.path.basename(embed['qca_file'])
                if not qca_file == EMBED_FILTER:
                    continue
                qbits = list(reduce(lambda x,y:x+y, embed['models'].values()))
                qbits = [tuple_to_linear(qb, M=12, N=12, L=4, index0=False) for qb in qbits]
                subsols[k] = sol.get_reduced_solution(qbits, efunc)
                h_, J_ = reduce_coefs(h, J, qbits)
                params[k] = {'h': h_, 'J': J_, 'qca_file': qca_file}
        except:
            print('Failed to read embed summary...')
            return

        for k, subsol in subsols.items():
            self.export_subsol(subsol, params[k])

        return
        for k, subsol in subsols.items():
            print(k)
            keys, spins, cell_occ, occ = subsol.model_reduction(embeds[k]['models'], \
                ind_map=lambda qb: tuple_to_linear(qb, 12, 12, index0=False))

        # outcome statistics
#        cell_occ = sol.cell_occ
#            cell_occ = subsols[k].cell_occ
            M = max(cell_occ)   # number fo gauge transformation
            N = max(max(x) for k, x in cell_occ.items())    # number of states
            D = np.zeros([M, N], dtype=int)

            for g, co in cell_occ.items():
                for s, o in co.items():
                    D[g-1,s-1] = o

            # reject rare outcomes
            if False:
                inds = np.nonzero(np.max(D, axis=0) > 2)[0]
                D = D[:, inds]

            if False:
                if True:
                    stack_plot = stackPlot(label='GT')
                    stack_plot.set_data(D)
                    stack_plot.plot(block=True)
                else:
                    plt.figure('GT')
                    plt.clf()
                    plt.plot(D.transpose(), 'x')
                    plt.show(block=True)

            # statistical distance
            SD = np.zeros([M, M], dtype=float)

            print('Computing statistical distances...')
            k = 0
            for i in range(M-1):
                for j in range(i+1, M):
                    k += 1
                    sys.stdout.write('\r{0}%'.format(k*100./(.5*M*(M-1))))
                    sys.stdout.flush()
                    SD[i,j] = SD[j,i] = stat_dist(D[i,:], D[j,:])
            print('\n')

            # seriate SD matrix if at least one pair of GTs have SD overlap
            if True:
                mask = np.ones(SD.shape, dtype=bool)
                np.fill_diagonal(mask, 0)
                if np.min(SD[mask])>0:
                    print('seriating SD matrix...')
                    try:
                        print('\tattempting {0}'.format(self.i4.text()))
                        new_inds = seriate(SD, method=str(self.i4.text()))
                    except:
                        print('\tfailed, using default method')
                        new_inds = seriate(SD, method='MDS')
                    print(new_inds)

                    SD = SD[new_inds, :][:, new_inds]
                else:
                    print('No overlap between GT distributions. Seriation not possible.')

            plt.imshow(SD, aspect='auto', interpolation='none')
            plt.colorbar()
            plt.show(block=True)

            if False:
                avg_pdf = np.sum(D,axis=0)*1./np.sum(D)

                # look at number of random GT needed to estimate avg_pdf
                sd_est = {k: match_dist(D, avg_pdf, k) for k in range(1, M)}

                pprint(sd_est)

                K = sorted(sd_est.keys())

                plt.figure('SD v K')
                plt.plot(K, [sd_est[x][0] for x in K], 'x')
                plt.xlabel('Number of samples', fontsize=FS)
                plt.ylabel('Statistical Distance', fontsize=FS)
                plt.show(block=False)

                plt.figure('stdev(SD) v K')
                plt.plot(K, [sd_est[x][1] for x in K])
                plt.xlabel('Number of samples', fontsize=FS)
                plt.ylabel('$\sigma_{SD}$', fontsize=FS)
                plt.show(block=True)