예제 #1
0
def changeFromSegmentsToRows(segmentCsp):
    rowCsp = CSP()
    for row in range(numberOfRows):
        variable = LineSegment(row, -1)
        rowCsp.variables.append(variable)
        rowCsp.constraints[variable] = []
    for col in range(numberOfColumns):
        variable = LineSegment(-1, col)
        rowCsp.variables.append(variable)
        rowCsp.constraints[variable] = []

    # Add rows as variables to CSP
    for row in range(numberOfRows):
        rowCsp.domains[rowCsp.variables[row]] = []

    # Add columns as variables to CSP
    for col in range(numberOfColumns):
        rowCsp.domains[rowCsp.variables[numberOfRows + col]] = []

    # Add domain to rowCsp
    addDomains(segmentCsp, rowCsp)

    # Add constraints to rowCsp
    addConstraints(rowCsp)

    return rowCsp
예제 #2
0
    def backtrackSearch(
            csp_i: CSP,
            assignment_i: Assignment = None) -> Optional[Assignment]:
        """
        Executes backtracking search for a complete assignment of a csp
        :param csp_i: csp of interest
        :param assignment_i: eventual partial assignment to respect
        :return: assignment if it exist, None otherwise
        """
        if assignment_i is None:  # if it's the init call, we run AC-3 and we initialize an assignment
            if not AC3(csp_i):
                return None
            assignment_i = Assignment()

        if len(assignment_i.getAssignment()) == csp_i.countVariables(
        ):  # if the assignment is complete, we can return it
            return assignment_i

        var = orderVariables(csp_i, assignment_i)
        values = orderDomainValues(csp_i, assignment_i, var)

        for value in values:
            localAssignment = copy(
                assignment_i
            )  # we try to assign a var in a local copy of assignment
            localAssignment.addVarAssigned(var, value)
            if MAC(
                    csp_i, localAssignment, csp_i.getNeighbour(var)
            ):  # if it's possible to complete the assignment, we iterate...
                result = backtrackSearch(csp_i, localAssignment)
                if result is not None:  # ... if it fails, we go back and propagate the None result
                    return result  # if the recursion arrive to a None, we don't want to propagate it, but we want to try next value
        return None
예제 #3
0
def batch():
  x, y = CSP.load_data()
  kv = BCI.gen_kv_idx(y, 10)
  for train_idx, test_idx in kv:
    x_train, y_train = x[train_idx], y[train_idx]
    x_test, y_test = x[test_idx], y[test_idx]

    fb_mi = fb_mibif(x_train, y_train)
    #ts_mi = ts_mibif(x_train, y_train)

    fb_idx = np.argmax(fb_mi)
    #ts_idx = np.argmax(ts_mi)

    fb_csp = CSP.filterbank_CSP(x_train)
    #ts_csp = CSP.temporal_spectral_CSP(x_train)

    fb_x = mi_selector(fb_csp, fb_idx)
    ts_x = mi_selector(ts_csp, fb_idx)
    from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
    fb_lda = LinearDiscriminantAnalysis(solver='lsqr', shrinkage='auto')
    ts_lda = LinearDiscriminantAnalysis(solver='lsqr', shrinkage='auto')

    fb_lda.fit(fb_x, y_train)
    ts_lad.fit(ts_x, y_train)
    
    fb_x_t = mi_selector(CSP.filterbank_CSP(x_test), fb_x)
    #ts_x_t = mi_selector(CSP.temporal_spectral_CSP(x_test), ts_mi)

    fb_score = fb_lda.score(fb_x_t, y_test)
    ts_score = ts_lda.score(ts_x_t, y_test)

    print(fb_score)
    print(ts_score)
예제 #4
0
def tree_csp_solver(problem, nodeList, matrix):
    Ass = []
    j = random.randrange(0, len(nodeList))
    root = nodeList[j]
    Functions.DAC(problem, nodeList, matrix)
    n = 0
    for u in nodeList:
        d = Node.Node.getDomain(u)
        if (len(d) == 0):
            return False
    mx = matrix
    ts = Functions.TopSort(mx, j)
    NL = []
    print "\n Ordine:"
    for j in ts:
        print ts[j],
    for i in ts:
        k = ts[i]
        node = nodeList[k]
        NL.append(node)
    print "\n", NL
    for u in NL:
        if (u.color == 0):
            kappa = nodeList.index(u)
            CSP.assignment(NL, matrix, u, kappa)
            ass = Node.Node.getColor(u)
            Ass.append(ass)
        else:
            Ass.append(u.color)
    print Ass
    return Ass
예제 #5
0
    def arrange(self, event):
        self.frame_body.pack_forget()
        self.frame_body = Frame(self.frame)
        self.csp = None
        self.list_of_jadwal_ruangan = []
        self.list_of_jadwal_kegiatan = []

        self.csp = CSP(self.dasbor.entry_nama_file.get())

        if self.pilihan_algoritma.get() == 0:
            schedule = Schedule()
            hill = HillClimbing()
            hill.algorithm(schedule, self.csp, int(self.dasbor.entry_iterasi_maksimal.get()))
        elif self.pilihan_algoritma.get() == 1:
            Schedule1 = Schedule()
            Schedule1.inisialisasi(self.csp)
            SimulatedAnnealing1 = SimulatedAnnealing(float(self.dasbor.entry_T.get()), float(self.dasbor.entry_Tmin.get()), float(self.dasbor.entry_alpha.get()))
            SimulatedAnnealing1.inisialisasi(Schedule1, self.csp)
        elif self.pilihan_algoritma.get() == 2:
            for i in range(int(self.dasbor.entry_iterasi_maksimal.get())):
                PopulasiGA1 = PopulasiGA()
                PopulasiGA1.isiPopulasi(self.csp.getListOfJadwal(), self.csp.getListOfRuangan())
                PopulasiGA1.selection()
                PopulasiGA1.crossOver()
                PopulasiGA1.mutasi(self.csp)
                konflikMinimal, idxMinimal = PopulasiGA1.cekKonflikPopulasi()
                self.csp.setJumlahConflict2(konflikMinimal)
                if (konflikMinimal == 0):
                    break
            PopulasiGA1.assignToCSP(PopulasiGA1.getIndividuByIndex(idxMinimal), self.csp)

        self.dasbor.label_angka_jadwal_bentrok.config(text=str(self.csp.getJumlahConflict2()))
        self.dasbor.label_angka_persentase.config(text=str(self.csp.hitungEfisiensi()*100)+'%')

        for ruangan in self.csp.getListOfRuangan():
            self.list_of_jadwal_ruangan.append(JadwalRuangan(self.frame_body, ruangan))

        for kegiatan in self.csp.getListOfJadwal():
            self.list_of_jadwal_kegiatan.append(JadwalKegiatan(self.list_of_jadwal_ruangan, kegiatan))

        #BINDING
        for jadwal_ruangan in self.list_of_jadwal_ruangan:
            for index_baris in range (2,13):
                for index_kolom in range (1,6):
                    frame_jadwal_ruangan = jadwal_ruangan.matrix_of_frame_jadwal_ruangan[index_baris][index_kolom]
                    frame_jadwal_ruangan.bind('<Button-1>', lambda event, a=jadwal_ruangan, b=index_baris, c=index_kolom: self.pindah_jadwal(a,b,c))

        for jadwal_kegiatan in self.list_of_jadwal_kegiatan:
            for button in jadwal_kegiatan.list_of_button:
                button.bind('<Button-1>', lambda event, a=button.cget('text'), b=jadwal_kegiatan: self.pilih_kegiatan(a,b))

        #SHOW
        for jadwal_ruangan in self.list_of_jadwal_ruangan:
            jadwal_ruangan.show()

        for jadwal_kegiatan in self.list_of_jadwal_kegiatan:
            jadwal_kegiatan.show()

        self.frame_body.pack(side=TOP, expand=True)
예제 #6
0
def allSolutions(
    csp: CSP,
    *,
    count: bool = False,
    assignment: Assignment = None,
    solutions: Union[List[Assignment], int] = None
) -> Union[List[Assignment], int]:
    """
    Executes a modified backtracking search for all complete assignment of a csp.
    Execution time: Theta(n^d) d=max cardinality. ONLY FOR TEST PURPOSE
    :param count: if you want only count the number of solution set it to True
    :param csp: csp of interest
    :param assignment: eventual partial assignment to respect
    :param solutions: eventual already found solutions
    :return: assignment if it exist, None otherwise
    """
    if assignment is None:  # if it's the init call, we run AC-3 and we initialize an assignment
        AC3(csp)
        assignment = Assignment()

    if solutions is None:
        if count:
            solutions = 0
        else:
            solutions = []

    unassigned = [
        var
        for var in list(csp.getVariables() - assignment.getAssignment().keys())
    ]
    var = unassigned[0]
    values = list(var.getActualDomain() - assignment.getInferencesForVar(var))
    for value in values:
        localAssignment = copy(
            assignment)  # we try to assign a var in a local copy of assignment
        localAssignment.addVarAssigned(var, value)
        if csp.assignmentConsistency(localAssignment):
            if len(localAssignment.getAssignment()) == csp.countVariables(
            ):  # if the assignment is complete and consistent, we can store it
                if count:
                    solutions += 1
                else:
                    solutions.append(localAssignment)
            else:
                if count:
                    solutions = allSolutions(csp,
                                             count=count,
                                             assignment=localAssignment,
                                             solutions=solutions)
                else:
                    allSolutions(csp,
                                 count=count,
                                 assignment=localAssignment,
                                 solutions=solutions)

    return solutions
예제 #7
0
def treeSolver(csp: CSP) -> Assignment:
    """
    Finds a possible assignment for tree-like csp
    Execution time: O(nd^2) d=max cardinality
    :param csp:  csp of interest
    :return: an assignment, eventually null if the problem is unsatisfiable
    """
    def DAC(csp_i: CSP, sequence_i: List[Variable]) -> bool:
        """
        Directional Arc Consistency. Does inference over the domain, from the leaf to the root of the graph
        Execution time: O(nd^2) d=max cardinality
        :param csp_i: csp of interest
        :param sequence_i: topological order
        :return False if the csp is unsatisfiable, True otherwise
        """
        for i in range(len(sequence_i) - 1, -1, -1):
            for j in range(i - 1, -1, -1):
                constraint = csp_i.findBinaryCostraint(sequence_i[j],
                                                       sequence_i[i])
                if constraint is not None:
                    revise(sequence_i[j], constraint, sequence_i[i])
            if sequence_i[i].getActualDomainSize() == 0:
                return False
        return True

    assignment = Assignment()
    root = csp.getVariables().pop()
    sequence = topSort(csp, root)

    if not DAC(csp, sequence):  # is unsatisfiable
        nullAssignment = Assignment()
        nullAssignment.setNull()
        return nullAssignment

    for var in sequence:  # for each var in order...
        for value in var.getActualDomain():
            assignment.addVarAssigned(
                var, value)  # ... we try to assign a variable...
            if csp.assignmentConsistencyForVar(
                    assignment,
                    var):  # ... if the partial assignment is consistent...
                break  # ... we go to the next var
            else:
                assignment.removeVarAssigned(var)
        else:  # if none of the values is consistent, the csp is unsatisfiable and we return a null assignment
            nullAssignment = Assignment()
            nullAssignment.setNull()
            return nullAssignment

    return assignment
예제 #8
0
def orderVariables(csp: CSP, assignment: Assignment) -> Variable:
    """
    Given a csp and an assignment, selects unassigned variable ordered following Minimum Remaining Values and Degree Heuristic
    :param csp: the csp
    :param assignment: partial assignment
    :return: first variable
    """
    varAssignment: Dict[Variable] = assignment.getAssignment()
    unassigned = [
        var for var in list(csp.getVariables() - varAssignment.keys())
    ]
    unassigned.sort(key=lambda var: (
        (var.getActualDomainSize() - len(assignment.getInferencesForVar(var))
         ), -len(csp.getBinaryConstraintsForVar(var))))
    return unassigned[0]
예제 #9
0
파일: RCNN_2nd.py 프로젝트: RichardLeeK/BCI
def make_data_temporal(sub):
    cnt = scipy.io.loadmat('raw_KIST/twist/raw_cnt_' + sub +
                           '.mat')['cnt'][0][0][4]
    mrk = scipy.io.loadmat('raw_KIST/twist/raw_mrk_' + sub +
                           '.mat')['mrk'][0][0][0][0]
    y = scipy.io.loadmat('raw_KIST/twist/raw_mrk_' + sub +
                         '.mat')['mrk'][0][0][3]
    epo = []
    for i in range(1, 10):
        cnt_fs = CSP.arr_bandpass_filter(cnt, i * 4, (i + 1) * 4, 1000, 4)
        epo.append(cnt_to_epo(cnt_fs, mrk))
    y_ = np.transpose(y)
    kv = BCI.gen_kv_idx(y_, 5)
    k = 1
    for train_idx, test_idx in kv:
        train_x = epo_temporal_dividing(
            np.array(epo)[:, train_idx, :, :], 0.6, 0.3)
        test_x = epo_temporal_dividing(
            np.array(epo)[:, test_idx, :, :], 0.6, 0.3)
        train_y = y[:, train_idx]
        test_y = y[:, test_idx]
        res = {
            'train_x': train_x,
            'test_x': test_x,
            'train_y': train_y,
            'test_y': test_y
        }
        scipy.io.savemat('RCNN2/twist_ori_dj/' + sub + '_' + str(k) + '.mat',
                         res)
        k += 1
예제 #10
0
def gen_tscsp(sub='1'):
    path = 'data/A0' + sub + 'T.npz'
    cnt, mrk, dur, y = Competition.load_cnt_mrk_y(path)
    epo = []
    for i in range(1, 10):  # band-pass filtering
        cnt_fs = CSP.arr_bandpass_filter(cnt, i * 4, (i + 1) * 4, 250, 4)
        cur_epo = cnt_to_epo(cnt_fs, mrk, dur)
        cur_epo, y_ = out_label_remover(cur_epo, y)
        epo.append(cur_epo)
    y = BCI.lab_inv_translator(y_, 4)
    kv = BCI.gen_kv_idx(y, 5)
    k = 1
    for train_idx, test_idx in kv:
        train_x = epo_temporal_dividing(
            np.array(epo)[:, train_idx, :, :], 4, 0.5, 250)
        test_x = epo_temporal_dividing(
            np.array(epo)[:, test_idx, :, :], 4, 0.5, 250)
        train_y = np.transpose(np.array(y)[train_idx])
        test_y = np.transpose(np.array(y)[test_idx])
        res = {
            'train_x': train_x,
            'test_x': test_x,
            'train_y': train_y,
            'test_y': test_y
        }
        scipy.io.savemat(
            'competition/ori_4_0.5/' + sub + '_' + str(k) + '.mat', res)
        k += 1
예제 #11
0
def data_load(file, filtering=True):
    path = 'E:/Richard/EEG/Competition/raw/'
    cnt, mrk, dur, y = com.load_cnt_mrk_y(path + file)
    if filtering:
        cnt = csp.arr_bandpass_filter(cnt, 8, 30, 250, 5)
    epo = com.cnt_to_epo(cnt, mrk, dur)
    epo, y = com.out_label_remover(epo, y)
    return epo, y
class NRooks:

    def __init__(self, N = 1):
        def rowConstraint(state, values, size = N):
            pairs = values.items()
            validStates = list(range(state.state//size*size, state.state//size*size+size))
            validPairs = list(filter(lambda pair: pair[1] and pair[0].state in validStates, pairs))

            statesToConsider = list(map(lambda x: x[1], validPairs))
            return sum(statesToConsider) <= 1
        def columnConstraint(state, values, size = N):
            pairs = values.items()
            validStates = list(range(state.state % size, size**2,size))
            validPairs = list(filter(lambda pair: pair[1] and pair[0].state in validStates, pairs))
            statesToConsider = map(lambda x: x[1], validPairs)
            return sum(statesToConsider) <= 1

        self._number = N
        goal = lambda values, size=N:  sum(map(lambda v: v[1], values.items())) == size
        self._CSP = CSP(goal, ChessState(0, set([True,False]),N))

        for i in range(N*N):
            self._CSP.addVariable(ChessState(i, set([True,False]),N))

        self._CSP.addConstraint(rowConstraint)
        self._CSP.addConstraint(columnConstraint)

    def solve(self):
        return self._CSP.solve()
예제 #13
0
def gen_fbcsp(path='data/A01T.npz'):
    x, y = Competition.load_one_data(path)
    for i in range(1, 10):
        print(i)
        x_ = CSP.arr_bandpass_filter(x, i * 4, (i + 1) * 4, 250)
        f = one_fbcsp(x_, y)
        scipy.io.savemat('mat/fbcsp_ori/A01T_' + str(i) + '_1.mat', f[0])
        scipy.io.savemat('mat/fbcsp_ori/A01T_' + str(i) + '_2.mat', f[1])
        scipy.io.savemat('mat/fbcsp_ori/A01T_' + str(i) + '_3.mat', f[2])
    def __init__(self, N=1):
        def leftDiagonalConstraint(state, values, size=N):
            pairs = values.items()
            validStates = list(
                range(
                    state.state -
                    min(state.state // size, state.state % size) * (size + 1),
                    size**2, size + 1))
            validPairs = list(
                filter(lambda pair: pair[1] and pair[0].state in validStates,
                       pairs))
            statesToConsider = map(lambda x: x[1], validPairs)
            return sum(statesToConsider) <= 1

        def rightDiagonalConstraint(state, values, size=N):
            pairs = values.items()
            validStates = list(
                range(
                    state.state - min(state.state // size,
                                      (N - 1) - state.state % size) *
                    (size - 1), size**2, (size - 1)))
            validPairs = list(
                filter(lambda pair: pair[1] and pair[0].state in validStates,
                       pairs))
            statesToConsider = map(lambda x: x[1], validPairs)
            return sum(statesToConsider) <= 1

        self._number = N
        goal = lambda values, size=N: sum(map(lambda v: v[1], values.items())
                                          ) == size
        self._CSP = CSP(goal, ChessState(0, set([True, False]), N))

        for i in range(N * N):
            self._CSP.addVariable(ChessState(i, set([True, False]), N))

        self._CSP.addConstraint(leftDiagonalConstraint)
        self._CSP.addConstraint(rightDiagonalConstraint)
예제 #15
0
def gen_cnt_data():
    import os
    os.chdir('E:/Richard/Competition/')
    for i in range(1, 10):
        path = 'raw/A0' + str(i) + 'T.npz'
        cnt, mrk, dur, y = Competition.load_cnt_mrk_y(path)
        f_cnt = CSP.arr_bandpass_filter(cnt, 8, 30, 250, 5)
        epo = cnt_to_epo(f_cnt, mrk, dur)
        epo, y_ = out_label_remover(epo, y)
        new_epo = []
        for v in epo:
            new_epo.append(v[750:1500, :])
        new_epo = np.array(new_epo)
        data = {'x': new_epo, 'y': y_}
        scipy.io.savemat('epo_f/A0' + str(i), data)
예제 #16
0
def load_kist_data(sub = '3'):
  import pickle
  print(sub)
  x = scipy.io.loadmat('kist_data/grasp/x_' + sub + '.mat')['x_' + sub].transpose()
  y = scipy.io.loadmat('kist_data/grasp/y_' + sub + '.mat')['y_' + sub].transpose().argmax(axis=1)

  y_ = np.array(BCI.lab_inv_translator(y))

  kv = BCI.gen_kv_idx(y_, 5)
  k = 1
  for train_idx, test_idx in kv:
    x_train, y_train = x[train_idx], y_[train_idx]
    x_test, y_test = x[test_idx], y_[test_idx]
    file = open('kist_data/grasp/np/' + sub + '_' + str(k) + '.pic', 'wb')
    pickle.dump({'x_train': x_train, 'y_train': y_train, 'x_test': x_test, 'y_test': y_test}, file)
    file.close()
    step = int(len(x[0][0]) / 5)
    for i in range(0, 5):
      cur_x_train = x_train[:, :, step * i: step * (i + 1)]
      cur_x_test = x_test[:, :, step * i: step * (i + 1)]
      for j in range(1, 10):
        cur_cur_x_train = CSP.arr_bandpass_filter(cur_x_train, j*4, (j+1)*4, 250)
        cur_cur_x_test = CSP.arr_bandpass_filter(cur_x_test, j*4, (j+1)*4, 250)

        f_train = one_fbcsp_for_kist(cur_cur_x_train, y_train.argmax(axis=1))
        f_test = one_fbcsp_for_kist(cur_cur_x_test, y_test.argmax(axis=1))

        scipy.io.savemat('mat/kist_ori/grasp/A0' + sub + 'T_' + str(i) + '_' + str(j) + '_1_' + str(k) + '_train.mat', f_train[0])
        scipy.io.savemat('mat/kist_ori/grasp/A0' + sub + 'T_' + str(i) + '_' + str(j) + '_2_' + str(k) + '_train.mat', f_train[1])
        scipy.io.savemat('mat/kist_ori/grasp/A0' + sub + 'T_' + str(i) + '_' + str(j) + '_3_' + str(k) + '_train.mat', f_train[2])

        scipy.io.savemat('mat/kist_ori/grasp/A0' + sub + 'T_' + str(i) + '_' + str(j) + '_1_' + str(k) + '_test.mat', f_test[0])
        scipy.io.savemat('mat/kist_ori/grasp/A0' + sub + 'T_' + str(i) + '_' + str(j) + '_2_' + str(k) + '_test.mat', f_test[1])
        scipy.io.savemat('mat/kist_ori/grasp/A0' + sub + 'T_' + str(i) + '_' + str(j) + '_3_' + str(k) + '_test.mat', f_test[2])

    k += 1
예제 #17
0
 def toCSP(self) -> CSP:
     """
     Transforms the map into a CSP
     :return: the CSP
     """
     csp = CSP()
     for p in self._region:
         v = Variable(
             'region ' + str('%.3f' % p.x()) + '-' + str('%.3f' % p.y()),
             self._color)
         csp.addVariable(v)
     for l in self._borders:
         csp.addBinaryConstraint(
             csp.getVariable('region ' + str('%.3f' % l[0].x()) + '-' +
                             str('%.3f' % l[0].y())), Constraint(different),
             csp.getVariable('region ' + str('%.3f' % l[1].x()) + '-' +
                             str('%.3f' % l[1].y())))
     return csp
예제 #18
0
 def DAC(csp_i: CSP, sequence_i: List[Variable]) -> bool:
     """
     Directional Arc Consistency. Does inference over the domain, from the leaf to the root of the graph
     Execution time: O(nd^2) d=max cardinality
     :param csp_i: csp of interest
     :param sequence_i: topological order
     :return False if the csp is unsatisfiable, True otherwise
     """
     for i in range(len(sequence_i) - 1, -1, -1):
         for j in range(i - 1, -1, -1):
             constraint = csp_i.findBinaryCostraint(sequence_i[j],
                                                    sequence_i[i])
             if constraint is not None:
                 revise(sequence_i[j], constraint, sequence_i[i])
         if sequence_i[i].getActualDomainSize() == 0:
             return False
     return True
예제 #19
0
def fb_mibif(x, y):
  fb_csp = CSP.filterbank_CSP(x)
  xs = [[], [], [], []]
  for i in range(len(fb_csp)):
    xs[y.argmax(axis=1)[i]].append(fb_csp[i])
  mis = np.zeros((len(xs), len(xs[0][0]), len(xs[0]) + 10))
  for i in range(len(xs)): # class number
    for j in range(len(xs[i])): # epoch count
      for k in range(len(xs[i][j])): # filter number
        one = xs[i][j][k]
        rest = []
        for l in rnage(len(xs)):
          if i == l: continue
          try: rest.extend(xs[l][j][k])
          except Exception as e: print(e)
        mis[i][j][k] = mutual_information(one, rest)
  return np.sum(np.sum(mis, axis=2), axis=0)
예제 #20
0
def playcsp(listofPos, matrix, count):
    # print count
    # do the csp first
    mine, nomine = CSP.csp(matrix)
    # print mine
    # print nomine
    # print listofPos
    # print "-----------------------"
    #judge four cases
    # case 1: no nomine and no mine, then do dfs
    if (len(nomine) == 0 and len(mine) == 0):
        return listofPos[count],listofPos,matrix

    # case 2: no nomine and have mine, then delete mine from dfs path, run dfs
    elif(len(nomine)== 0 and len(mine) != 0):
        for bomb in mine:
            if bomb in listofPos:
                listofPos.remove(bomb)
                matrix[bomb[0]][bomb[1]] = 9

        # for cell in matrix:
        #     print cell
        # print listofPos
        return listofPos[count],listofPos,matrix

    # case 3: have nomine and no mine, then click the nomine first
    elif(len(nomine) != 0 and len(mine) == 0):
        counting = count
        for safe in nomine:
            listofPos.insert(counting, safe)
            counting += 1
        return nomine[0], listofPos,matrix

    # case 4: have nomine and have mine, then click the nomine first
    else:
        for bomb in mine:
            if bomb in listofPos:
                listofPos.remove(bomb)
                matrix[bomb[0]][bomb[1]] = 9
        # print listofPos
        counting = count
        for safe in nomine:
            listofPos.insert(counting, safe)
            counting += 1
        return nomine[0], listofPos,matrix
예제 #21
0
def AC3(csp: CSP) -> bool:
    """
    Reduce CSP's variable's domain by inference, maintaining arc consistency
    Execution time: O(nd^3) d=max cardinality
    :param csp: CSP
    :return: False if the CSP is unsatisfiable
    """
    def unaryRevise(var_i: Variable, constraint_i: Constraint,
                    value_i: Any) -> None:
        """
        Check for every value of the variable if it is compatible with a unary constraint involving this variable;
        if it doesn't, the value will be hidden
        :param var_i: variable
        :param constraint_i: constraint
        :param value_i: value
        :return: None
        """
        for valueX in var_i.getActualDomain():
            if not constraint_i(valueX, value_i):
                var_i.hideValue(valueX)

    # Inference over the unary constraint
    for var in csp.getUnaryConstraints():
        for value in csp.getUnaryConstraintsForVar(var):
            unaryRevise(var, csp.findUnaryConstraint(var, value), value)

    # Inference over the binary constraints
    s = csp.getEdges()
    while len(s) is not 0:
        edge = s.pop()  # Take an edge...
        constraint = csp.findBinaryCostraint(edge[0], edge[1])
        varI = edge[0]
        varJ = edge[1]
        if revise(
                varI, constraint, varJ
        ):  # ... and analise the relative constraint. If has been made inference, we have to check something
            if varI.getActualDomainSize(
            ) == 0:  # If a domain is empty, the csp is unsatisfiable
                return False
            otherConstraints = csp.getBinaryConstraintsForVar(
                varI
            )  # get others constraints involving inferenced variable...
            otherEdges = set()
            for var in otherConstraints:
                if var != varJ:
                    otherEdges.add(
                        (var, varI))  # ... convert them to edges ...
            s = s.union(
                otherEdges)  # ... and add them to the set of edges to analise
    return True
예제 #22
0
 def performBacktrackSearch(self, rootNode, node):
     """
     This creates the search tree
     """
     
     print ("-- proc --", node.state.assignment)
     
     #check if we have reached goal state
     if node.state.checkGoalState():
         print ("reached goal state")
         return True
         
     else:
         
         #check if there is a case of early failure
         #if node.state.forwardCheck(): 
         if node.state.arcConsistency():
         
             #find an unassigned variable 
             variable = node.state.selectUnassignedVariable()
             
             #for all values in the domain
             for value in node.state.orderDomainValues():
                 
                 #check if constraints are satisfied
                 if CSP.checkConstraints(node.state.assignment,
                                         variable, value):
                 
                     #create child node
                     childNode = Node(State(node.state.assignment, 
                                            node.state.possibleValues, variable, value))
                 
                     node.addChild(childNode)
                     
                     #show the search tree explored so far
                     treeplot = TreePlot()
                     treeplot.generateDiagram(rootNode, childNode)
                     
                     result = self.performBacktrackSearch(rootNode, childNode)
                     if result == True:
                         return True
         return False        
예제 #23
0
 def _topSort(csp_i: CSP, root_i: Variable,
              previous: List[Variable]) -> List[Variable]:
     """
     Adds to the list the subroot and iterates
     :param csp_i:  csp of interest
     :param root_i: variable from which it starts
     :param previous: already elaborated nodes
     :return: updated list
     """
     children = []
     for couple in csp_i.getNeighbour(
             root_i):  # check for every edges involving root
         if couple[0] == root_i:  # discards dual edges
             if couple[
                     1] not in previous:  # if the other node is not in list, it is a child
                 children.append(couple[1])
     previous.append(root_i)  # adding the root to list...
     for var in children:
         _topSort(csp_i, var,
                  previous)  # ... before to iterate for children
     return previous
def main():
    """
    task:
        0 - N queens
        1 - Latin square
        
    size:


    algorithm:
        0 - forward checking
        1 - backtracking 
        
    """
    size = int(input("Specify the desired size of the board: "))
    csp = CSP.CSP(task=1, size=size)
    results = csp.start(algorithm=1)
    # for r in results:
    #    print(r)
    print("Solutions found: ", len(results[0]), "Number of iterations: ",
          results[1])
예제 #25
0
def new_sudoku(file=None):
	if not file:
		# Create empty sudoku with domains 1-9 for every cell
		X = [0] * DIM*DIM
		D = [ list(range(1,DIM+1)) for _ in range(len(X)) ]
	else:
		# Read a sudoku and fill in domain values
		X = read_sudoku(file)
		D = []
		for i in range(len(X)):
			if X[i] == 0:
				D.append( list(range(1,DIM+1)) )
			else:
				D.append( [ X[i] ] )
	# Only one constraint to satisfy (on a variety of arcs)
	C = [ alldiff ]
	# Seems like it could be done more correctly

	# Generate all rows, columns, and boxes
	box_size = int(sqrt(DIM))
	rows, cols, boxes = [], [], []
	for i in range(0,DIM):
		row, col, box = [], [], []
		for j in range(0,DIM):
			row.append(i + DIM*j)
			col.append(DIM*i + j)
			box.append( (j%box_size) + DIM*(j//box_size) + box_size*(i%box_size) + DIM*box_size*(i//box_size) )
		rows.append(tuple(row))
		cols.append(tuple(col))
		boxes.append(tuple(box))

	# Convert all groups into binary arcs
	groups = rows + cols + boxes
	arcs = []
	for group in groups:
		arcs += binary_arcs(group)

	# Return a CSP representation of the sudoku
	return CSP.CSP(X, D, C, arcs)
예제 #26
0
def topSort(csp: CSP, root: Variable) -> List[Variable]:
    """
    Given a csp, it searches for a "topological sort" (running a DFS). It needs a variable from which starting, because induced graph isn't a direct graph, so
    the real topological sort isn't defined
    :param csp: csp of interest
    :param root: variable from which it starts
    :return: Order list of csp's variables
    :raise Exception: if the graph induced isn't a tree (it is cyclic or not connected)
    """
    def _topSort(csp_i: CSP, root_i: Variable,
                 previous: List[Variable]) -> List[Variable]:
        """
        Adds to the list the subroot and iterates
        :param csp_i:  csp of interest
        :param root_i: variable from which it starts
        :param previous: already elaborated nodes
        :return: updated list
        """
        children = []
        for couple in csp_i.getNeighbour(
                root_i):  # check for every edges involving root
            if couple[0] == root_i:  # discards dual edges
                if couple[
                        1] not in previous:  # if the other node is not in list, it is a child
                    children.append(couple[1])
        previous.append(root_i)  # adding the root to list...
        for var in children:
            _topSort(csp_i, var,
                     previous)  # ... before to iterate for children
        return previous

    sequence = _topSort(csp, root, [])
    if len(sequence) == len(csp.getVariables()) and len(sequence) == len(
            set(sequence)):
        return sequence
    else:
        raise Exception  # It isn't a tree: EVERY var has to be ONE AND ONLY ONE time in the sequence
예제 #27
0
def gen_tscsp_trick(sub):
    path = 'data/A0' + sub + 'T.npz'
    cnt, mrk, dur, y = Competition.load_cnt_mrk_y(path)
    epo = []
    for i in range(1, 10):  # band-pass filtering
        cnt_fs = CSP.arr_bandpass_filter(cnt, i * 4, (i + 1) * 4, 250, 4)
        cur_epo = cnt_to_epo(cnt_fs, mrk, dur)
        cur_epo, y_ = out_label_remover(cur_epo, y)
        epo.append(cur_epo)
    y = BCI.lab_inv_translator(y_, 4)
    kv = BCI.gen_kv_idx(y, 5)
    k = 1
    for train_idx, test_idx in kv:
        train_x = epo_temporal_dividing(
            np.array(epo)[:, train_idx, :, :], 3.5, 0.5, 250)
        test_x = epo_temporal_dividing(
            np.array(epo)[:, test_idx, :, :], 3.5, 0.5, 250)
        cls = trick_ori(train_x, test_x,
                        np.array(y)[train_idx].argmax(axis=1),
                        np.array(y)[test_idx].argmax(axis=1))
        scipy.io.savemat(
            'competition/trick/ori_3.5_0.5/' + sub + '_' + str(k) + '.mat',
            {'cls': cls})
        k += 1
    def performBacktrackSearch(self, rootNode, node):
        """
        This creates the search tree
        """

        #print "-- proc --", node.state.assignment

        #check if we have reached our goal state
        if node.state.checkGoalState():
            print "reached goal state"
            return True
        else:
            #find an unassigned variable
            variable = node.state.selectUnassignedVariable()

            #for all values in the domain
            for value in node.state.orderDomainValues(variable):

                #check if constraints are satisfied
                if CSP.checkConstraints(node.state.assignment, variable,
                                        value):

                    #create child node
                    childNode = Node(
                        State(node.state.assignment, variable, value))
                    node.addChild(childNode)

                    #show the search tree explorer so far
                    treeplot = TreePlot()
                    treeplot.generateDiagram(rootNode, childNode)

                    result = self.performBacktrackSearch(rootNode, childNode)
                    if result == True:
                        return True

            return False
예제 #29
0
def frequentSubG(graph,graphLabel,thr,size):
    fEdges=countFrequentEdges(graph,graphLabel,thr) #take only the frequent edges from the input graph
    candidateSet=GraphPmod.subExtSimple(sorted(list(fEdges.keys()))) #generation of size 2 (size is the number of edges)
    candidateSetApp=copy.deepcopy(candidateSet)
    domains=GraphPmod.getDomains(graphLabel)
    solutionSet=[] #list used to avoid the presence of already existing assignments
    for el in candidateSetApp:
        if(CSP.isFrequent((el[0],el[1]),graph,domains,solutionSet,el[3])<thr):
            candidateSet.remove(el)
    iterations=2 #number of iterations -> at least solutions with size 2
    candidateSetPrevious=candidateSet
    while(len(candidateSet)!=0 and iterations<size):
        candidateSetPrevious=candidateSet
        candidateSetNew=GraphPmod.nuovaGenerazione(candidateSet,list(fEdges.keys())) #genration of bigger candidates -> adding all possible frequent edges
        candidateSetNewApp=copy.deepcopy(candidateSetNew)
        solutionSet=[]
        for el in candidateSetNewApp:
            r=CSP.isFrequent((el[0],el[1]),graph,domains,solutionSet,el[3])
            if(r<thr): #counting the occurrences of the candidate subgraph
                candidateSetNew.remove(el) #if the candidate does not respect the threshold is discarded
        candidateSet=candidateSetNew

        if(len(candidateSetNew)!=0):
            candidateSetPrevious=candidateSetNew
        iterations+=1
    p=0
    if(iterations==2):
        for t in candidateSetPrevious:
            GraphPmod.printResult(t[0],t[1],p)
            p+=1
        print("Number of total solutions -> ",len(candidateSetPrevious))
        print("Number of merged solutions -> ",len(candidateSetPrevious))
        print("Number of relations -> ",iterations)
    else:
        mergedResult=[]
        whoIsMerged=set()
        candidateC=copy.deepcopy(candidateSetPrevious)
        #comparing all the pairs of frequent subgraph
        candidateSetPrevious=sorted(candidateSetPrevious, key=lambda k: k[3])
        for k in range(len(candidateSetPrevious)):

            dfs1 = candidateSetPrevious[k][3]
            flagMerged=0
            if(dfs1 not in whoIsMerged):
                #whoIsMerged.add(k)
                whoIsMerged.add(dfs1)
                for i in range(k+1, len(candidateSetPrevious)):
                    dfs2 = candidateSetPrevious[i][3]
                    if (dfs2 not in whoIsMerged):
                        JarJar = DFSmod.jaroSimilarity(dfs1, dfs2)
                        if ((iterations == 3 and JarJar >= 0.9) or (iterations>3 and JarJar >= 0.8)): #if the Jaro Similarity is respected the two result are merged
                            #once one graph is merged into another it is discarded and no more considered
                            #print "MERGED ",dfs1,dfs2,JarJar
                            #print dfs1,dfs2
                            whoIsMerged.add(dfs2)
                            flagMerged=1
                            domain2=GraphPmod.getDomains(candidateSetPrevious[i][1])
                            domain1=GraphPmod.getDomains(candidateSetPrevious[k][1])
                            toAdd=[]
                            for t in candidateSetPrevious[k][1]:
                                for y in candidateSetPrevious[i][1]:
                                    if candidateSetPrevious[k][1][t] == candidateSetPrevious[i][1][y]:
                                        adjListI=candidateSetPrevious[i][0][y]
                                        for j in adjListI:
                                            labelDest=candidateSetPrevious[i][1][j[0]]
                                            newLabelDest=None
                                            if(labelDest in domain1):
                                                newLabelDest=domain1[labelDest][0]
                                            else:
                                                newLabelDest="v"+str(len(candidateSetPrevious[k][1]))
                                                toAdd.append((newLabelDest,labelDest))
                                                candidateSetPrevious[k][0][newLabelDest]=[]
                                            newEdges=(newLabelDest,j[1])
                                            if(newEdges not in candidateSetPrevious[k][0][t]):
                                                candidateSetPrevious[k][0][t].append(newEdges)
                                #break
                            for toA in toAdd:
                                candidateSetPrevious[k][1][toA[0]]=toA[1]
            #if(flagMerged==1 or (flagMerged==0 and k not in whoIsMerged)):
                #if(flagMerged==0):
                    #print "ALONE",dfs1
                mergedResult.append(copy.deepcopy(candidateSetPrevious[k]))
            #mergedResult.append(copy.deepcopy(candidateSetPrevious[k]))
            #whoIsMerged.add(k)


        p=0
        for el in mergedResult:
            GraphPmod.printResult(el[0],el[1],p)
            p+=1

        print("Number of merged solutions -> ",len(mergedResult))
        print("Number of total solutions -> ",len(candidateSetPrevious))
        print("Number of relations -> ",iterations)
예제 #30
0
board = sudokuGenerator.main()

## printing the unsolved board ##
print('Generating sudoku...')
sudokuGenerator.displayBoard(board)
print('done.')

## Converting to sudokuSolver format ##
for i in range(9):
	for j in range(9):
		if board[i][j] == 0:
			board[i][j] = None

## Making graph from list of list
print('Generating graph for sudoku board...')
G = makeSudokuGraph(board)
print('done.')

## Calling the filter function to solve board ##
import CSP
print('solving board...')
startTime = time.clock()
assgn = CSP.BacktrackSearch(G)
endTime = time.clock()
print('done.')

for i, j in assgn:
	board[i][j] = assgn[(i,j)]

sudokuGenerator.displayBoard(board)
print('Time taken to solve board:',endTime - startTime)
예제 #31
0
 def __init__(self, filename,domain):
     self.csp1 = CSP.CSP(filename, domain)
     self.csp1.parseFile()
     self.finalassignment = {}
     self.cnt = 0
예제 #32
0
def main():
    gevent.spawn(headset.setup)
    gevent.sleep(1)
    try:
        sample_counter = 0
        populate_csv_header()

        # Find mean
        #find_mean()

        # For building a finite time domain En to feed into CSP. 
        En = {
            'F3': [],
            'FC5': [],
            'AF3': [],
            'F7': [],
            'T7': [],
            'P7': [],
            'O1': [],
            'O2': [],
            'P8': [],
            'T8': [],
            'F8': [],
            'AF4': [],
            'FC6': [],
            'F4': []
        }

        print "Start!"
        
        # Run for 5 seconds
        loop_counter = 0
        while loop_counter < 20:
            # Retrieve emotiv packet
            packet = headset.dequeue()

            # Get sensor data
            F3 = packet.sensors['F3']['value']
            FC5 = packet.sensors['FC5']['value']
            AF3 = packet.sensors['AF3']['value']
            F7 = packet.sensors['F7']['value']
            T7 = packet.sensors['T7']['value']
            P7 = packet.sensors['P7']['value']
            O1 = packet.sensors['O1']['value']
            O2 = packet.sensors['O2']['value']
            P8 = packet.sensors['P8']['value']
            T8 = packet.sensors['T8']['value']
            F8 = packet.sensors['F8']['value']
            AF4 = packet.sensors['AF4']['value']
            FC6 = packet.sensors['FC6']['value']
            F4 = packet.sensors['F4']['value']

            # Build buffers for FFT
            F3Buffer.append(F3)
            FC5Buffer.append(FC5)
            AF3Buffer.append(AF3)
            F7Buffer.append(F7)
            T7Buffer.append(T7)
            P7Buffer.append(P7)
            O1Buffer.append(O1)
            O2Buffer.append(O2)
            P8Buffer.append(P8)
            T8Buffer.append(T8)
            F8Buffer.append(F8)
            AF4Buffer.append(AF4)
            FC6Buffer.append(FC6)
            F4Buffer.append(F4)

            sample_counter = sample_counter + 1

            # Do FFT for each sensor after collecting 64 samples
            if sample_counter > 32:
                # Remove high frequency noise and dc offset
                F3Buffer_clean = sp.preprocess(F3Buffer, 8885.0)
                FC5Buffer_clean = sp.preprocess(FC5Buffer, 8885.0)
                AF3Buffer_clean = sp.preprocess(AF3Buffer, 8885.0)
                F7Buffer_clean = sp.preprocess(F7Buffer, 8885.0)
                T7Buffer_clean = sp.preprocess(T7Buffer, 8885.0)
                P7Buffer_clean = sp.preprocess(P7Buffer, 8885.0)
                O1Buffer_clean = sp.preprocess(O1Buffer, 8885.0)
                O2Buffer_clean = sp.preprocess(O2Buffer, 8885.0)
                P8Buffer_clean = sp.preprocess(P8Buffer, 8885.0)
                T8Buffer_clean = sp.preprocess(T8Buffer, 8885.0)
                F8Buffer_clean = sp.preprocess(F8Buffer, 8885.0)
                AF4Buffer_clean = sp.preprocess(AF4Buffer, 8885.0)
                FC6Buffer_clean = sp.preprocess(FC6Buffer, 8885.0)
                F4Buffer_clean = sp.preprocess(F4Buffer, 8885.0)

                # Put clean data into En
                for i in range(0, len(F3Buffer_clean)):
                    En['F3'].append(F3Buffer_clean[i])
                    En['FC5'].append(FC5Buffer_clean[i])
                    En['AF3'].append(AF3Buffer_clean[i])
                    En['F7'].append(F7Buffer_clean[i])
                    En['T7'].append(T7Buffer_clean[i])
                    En['P7'].append(P7Buffer_clean[i])
                    En['O1'].append(O1Buffer_clean[i])
                    En['O2'].append(O2Buffer_clean[i])
                    En['P8'].append(P8Buffer_clean[i])
                    En['T8'].append(T8Buffer_clean[i])
                    En['F8'].append(F8Buffer_clean[i])
                    En['AF4'].append(AF4Buffer_clean[i])
                    En['FC6'].append(FC6Buffer_clean[i])
                    En['F4'].append(F4Buffer_clean[i])

                # Apply DFT to extract frequency components
                f3_fft = fft.compute_fft(F3Buffer_clean)
                fc5_fft = fft.compute_fft(FC5Buffer_clean)
                af3_fft = fft.compute_fft(AF3Buffer_clean)
                f7_fft = fft.compute_fft(F7Buffer_clean)
                t7_fft = fft.compute_fft(T7Buffer_clean)
                p7_fft = fft.compute_fft(P7Buffer_clean)
                o1_fft = fft.compute_fft(O1Buffer_clean)
                o2_fft = fft.compute_fft(O2Buffer_clean)
                p8_fft = fft.compute_fft(P8Buffer_clean)
                t8_fft = fft.compute_fft(T8Buffer_clean)
                f8_fft = fft.compute_fft(F8Buffer_clean)
                af4_fft = fft.compute_fft(AF4Buffer_clean)
                fc6_fft = fft.compute_fft(FC6Buffer_clean)
                f4_fft = fft.compute_fft(F4Buffer_clean)

                # Build dictionary
                fft_dict = {
                    'F3': f3_fft,
                    'FC5': fc5_fft,
                    'AF3': af3_fft,
                    'F7': f7_fft,
                    'T7': t7_fft,
                    'P7': p7_fft,
                    'O1': o1_fft,
                    'O2': o2_fft,
                    'P8': p8_fft,
                    'T8': t8_fft,
                    'F8': f8_fft,
                    'AF4': af4_fft,
                    'FC6': fc6_fft,
                    'F4': f4_fft
                }

                # Write data set to a csv file
                fft.write_to_file(fft_dict, start_time)

                # Clear buffers
                clear_buffers()
                sample_counter = 0
                loop_counter = loop_counter + 1
            
            gevent.sleep(0)
        
        # Feed into CSP filter.
        csp.create_e_matrix(En)
    except KeyboardInterrupt:
        headset.close()
    finally:
        headset.close()
예제 #33
0
def readCsp(textFile):
    csp = CSP()

    board = []

    file = open(textFile)

    firstLine = file.readline().split(" ")
    global numberOfRows
    numberOfRows = int(firstLine[1])
    global numberOfColumns
    numberOfColumns = int(firstLine[0])
    domainX = range(numberOfRows)
    domainY = range(numberOfColumns)

    # Creates board
    for i in range(numberOfRows):
        board.append([])
        for j in range(numberOfColumns):
            board[i].append(Node(i, j))

    # Add start position for segments in rows
    counter = 0
    for i in range(numberOfRows):
        line = file.readline().split(" ")
        for j in line:
            block = Block(counter, int(j), i, -1)
            counter += 1
            csp.variables.append(block)
            csp.constraints[block] = []
            csp.domains[block] = deepcopy(domainX)

    # Add start position for segments in columns
    for i in range(numberOfColumns):
        line = file.readline().split(" ")
        line.reverse()
        for j in line:
            block = Block(counter, int(j), -1, i)
            counter += 1
            csp.variables.append(block)
            csp.constraints[block] = []
            csp.domains[block] = deepcopy(domainY)

    # Add constraints to CSP
    for j in csp.variables:

        # Check if segment is the last
        if j.index == len(csp.variables) - 1:
            csp.constraints[j].append(Constraint([j], j.text + " + " + str(j.length) + " <= " + str(numberOfColumns)))
        # Segment is in a row
        elif j.colNumber == -1:
            if j.rowNumber == csp.variables[j.index + 1].rowNumber:

                # j.text = 'b1'
                # str(j.length) = '2'
                # csp.variables[j.index + 1].text = 'b2'
                #'b1 + 2 < b2'
                csp.constraints[j].append(
                    Constraint(
                        [j, csp.variables[j.index + 1]],
                        j.text + " + " + str(j.length) + " < " + csp.variables[j.index + 1].text,
                    )
                )
                csp.constraints[csp.variables[j.index + 1]].append(
                    Constraint(
                        [csp.variables[j.index + 1], j],
                        j.text + " + " + str(j.length) + " < " + csp.variables[j.index + 1].text,
                    )
                )
            else:
                csp.constraints[j].append(
                    Constraint([j], j.text + " + " + str(j.length) + " <= " + str(numberOfColumns))
                )
        # Segment is in a column
        else:
            if j.colNumber == csp.variables[j.index + 1].colNumber:
                csp.constraints[j].append(
                    Constraint(
                        [j, csp.variables[j.index + 1]],
                        j.text + " + " + str(j.length) + " < " + csp.variables[j.index + 1].text,
                    )
                )
                csp.constraints[csp.variables[j.index + 1]].append(
                    Constraint(
                        [csp.variables[j.index + 1], j],
                        j.text + " + " + str(j.length) + " < " + csp.variables[j.index + 1].text,
                    )
                )
            else:
                csp.constraints[j].append(Constraint([j], j.text + " + " + str(j.length) + " <= " + str(numberOfRows)))

    return csp