Exemple #1
0
    def finish(self, cfg):
        f_name = self.config.get_param("csp_file_name")
        f_dir = self.config.get_param("csp_file_path")

        if self.mode == 'offline':
            ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
        elif self.mode == 'always_pass':
            self._determine_means(cfg)  #for debug only
            self._show_configs(cfg,
                               suffix=self.config.get_param('bci_start_text'))
            time.sleep(5)
            self._shuffle_freqs(cfg)
            self._send_csp_info(cfg)
            ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
            self._run_next_scenario()
        elif self.mode == 'manual':
            self._show_configs(
                cfg, suffix=self.config.get_param('propose_freqs_text'))
            self._edit_configs(cfg)
            self._send_csp_info(cfg)
            ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
            self._run_next_scenario()
        elif self.mode == 'retry_on_failure':
            if self._determine_means(cfg):
                self._show_configs(
                    cfg, suffix=self.config.get_param('bci_start_text'))
                time.sleep(5)
                self._shuffle_freqs(cfg)
                self._send_csp_info(cfg)
                ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
                self._run_next_scenario()
            else:
                self._show_configs(cfg,
                                   suffix=self.config.get_param(
                                       'first_faild_calibration_text'))
                time.sleep(5)
                self._send_csp_info(cfg)
                self._run_prev_scenario()
        elif self.mode == 'abort_on_failure':
            if self._determine_means(cfg):
                self._show_configs(
                    cfg, suffix=self.config.get_param('bci_start_text'))
                time.sleep(5)
                self._shuffle_freqs(cfg)
                self._send_csp_info(cfg)
                ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
                self._run_next_scenario()
            else:
                self._show_configs(cfg,
                                   suffix=self.config.get_param(
                                       'second_faild_calibration_text'))
                time.sleep(5)
                self._send_csp_info(cfg)
                #sys.exit(1)
        else:
            self.logger.warning("Unrecognised mode: " + self.mode)
    def finish(self, cfg):
        f_name = self.config.get_param("csp_file_name")
        f_dir = self.config.get_param("csp_file_path")

        if self.mode == 'offline':
            self._determine_means(cfg)#just for debug
            ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
            self.logger.info("Calibration saved!!!")
        elif self.mode == 'manual':
            self._show_configs(cfg, suffix=u'Suggested frequencies:')
            self._edit_configs(cfg)
            ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
            self._run_next_scenario()
        elif self.mode == 'retry_on_failure':
            if self._determine_means(cfg):
                self._show_configs(cfg, suffix=u'Calibration passed, wait to start BCI app...')
                time.sleep(5)
                ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
                self._run_next_scenario()
            else:
                self._show_configs(cfg, suffix=u'Calibration FAILED, Try again with another freqs...')
                time.sleep(5)
                self._run_prev_scenario()
        elif self.mode == 'abort_on_failure':
            if self._determine_means(cfg):            
                self._show_configs(cfg, suffix=u'Calibration passed, wait to start BCI app...')
                time.sleep(5)
                ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
                self._run_next_scenario()
            else:
                self._show_configs(cfg, suffix=u'Calibration FAILED, You are not working, Bye...')
                time.sleep(15)
                sys.exit(1)
        else:
            self.logger.warning("Unrecognised mode: "+self.mode)
    def finish(self, cfg):
        f_name = self.config.get_param("csp_file_name")
        f_dir = self.config.get_param("csp_file_path")

        if self.mode == 'offline':
            ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
        elif self.mode == 'always_pass':
            self._determine_means(cfg)#for debug only
            self._show_configs(cfg, suffix=self.config.get_param('bci_start_text'))
            time.sleep(5)
            self._shuffle_freqs(cfg)
            self._send_csp_info(cfg)
            ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
            self._run_next_scenario()
        elif self.mode == 'manual':
            self._show_configs(cfg, suffix=self.config.get_param('propose_freqs_text'))
            self._edit_configs(cfg)
            self._send_csp_info(cfg)
            ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
            self._run_next_scenario()
        elif self.mode == 'retry_on_failure':
            if self._determine_means(cfg):
                self._show_configs(cfg, suffix=self.config.get_param('bci_start_text'))
                time.sleep(5)
                self._shuffle_freqs(cfg)
                self._send_csp_info(cfg)
                ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
                self._run_next_scenario()
            else:
                self._show_configs(cfg, suffix=self.config.get_param('first_faild_calibration_text'))
                time.sleep(5)
                self._send_csp_info(cfg)
                self._run_prev_scenario()
        elif self.mode == 'abort_on_failure':
            if self._determine_means(cfg):            
                self._show_configs(cfg, suffix=self.config.get_param('bci_start_text'))
                time.sleep(5)
                self._shuffle_freqs(cfg)
                self._send_csp_info(cfg)
                ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
                self._run_next_scenario()
            else:
                self._show_configs(cfg, suffix=self.config.get_param('second_faild_calibration_text'))
                time.sleep(5)
                self._send_csp_info(cfg)
                #sys.exit(1)
        else:
            self.logger.warning("Unrecognised mode: "+self.mode)
    def finish(self, cfg):
        f_name = self.config.get_param("csp_file_name")
        f_dir = self.config.get_param("csp_file_path")

        if self.mode == 'offline':
            self._determine_means(cfg)  #just for debug
            ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
            self.logger.info("Calibration saved!!!")
        elif self.mode == 'manual':
            self._show_configs(cfg, suffix=u'Suggested frequencies:')
            self._edit_configs(cfg)
            ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
            self._run_next_scenario()
        elif self.mode == 'retry_on_failure':
            if self._determine_means(cfg):
                self._show_configs(
                    cfg,
                    suffix=u'Calibration passed, wait to start BCI app...')
                time.sleep(5)
                ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
                self._run_next_scenario()
            else:
                self._show_configs(
                    cfg,
                    suffix=
                    u'Calibration FAILED, Try again with another freqs...')
                time.sleep(5)
                self._run_prev_scenario()
        elif self.mode == 'abort_on_failure':
            if self._determine_means(cfg):
                self._show_configs(
                    cfg,
                    suffix=u'Calibration passed, wait to start BCI app...')
                time.sleep(5)
                ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
                self._run_next_scenario()
            else:
                self._show_configs(
                    cfg,
                    suffix=u'Calibration FAILED, You are not working, Bye...')
                time.sleep(15)
                sys.exit(1)
        else:
            self.logger.warning("Unrecognised mode: " + self.mode)
    def run(self):
        LOGGER.info("START FDA...")

        f_name = self.config.get_param("data_file_name")
        f_dir = self.config.get_param("data_file_path")
        in_file = acquisition_helper.get_file_path(f_dir, f_name)

        filename = os.path.join(f_dir, f_name + ".obci")
        data = sp.signalParser(filename)
            
        fs = int(float(data.getSamplingFrequency()))

        mgr = read_manager.ReadManager(
            in_file+'.obci.xml',
            in_file+'.obci.raw',
            in_file+'.obci.tag')
        
        if self.use_channels is None:
            self.use_channels = data.getChannelList()
        if self.ignore_channels is not None:
            for i in self.ignore_channels:
                try:
                    self.use_channels.remove(i)
                except:
                    pass

        self.montage = self.config.get_param("montage")
        tmp = self.config.get_param("montage_channels")
        if len(tmp) > 0:
            self.montage_channels = tmp.split(';')
        else:
            self.montage_channels = []


        LOGGER.info("USE CHANNELS: "+str(self.use_channels))
        LOGGER.info("CHANNELS NAMES: "+str(mgr.get_param('channels_names')))
        
        ## Get data and tags
        data.setMontage(self.montage_channels)
        Signal = data.getData(self.use_channels)
        trgTags = data.get_p300_tags()
        ntrgTags = data.get_not_p300_tags()

        target, nontarget = data.getTargetNontarget(Signal, trgTags, ntrgTags)

        ## Get params from file
        pVal = float(self.config.get_param("p_val"))
        nRepeat = int(self.config.get_param("n_repeat"))
        nMin = int(self.config.get_param("n_min"))
        nMax = int(self.config.get_param("n_max"))
        
        avrM_l = map(lambda x: int(x), self.config.get_param("avr_m").split(';'))
        conN_l = map(lambda x: int(x), self.config.get_param("con_n").split(';'))
        csp_dt_l = map(lambda x: float(x), self.config.get_param("csp_dt").split(';'))
        csp_time_l = map(lambda x: float(x), self.config.get_param("csp_time").split(';'))

        ## Define buffer
        buffer = 1.1*fs
        LOGGER.info("Computer buffer len: "+str(buffer))

        
        ## Make montage matrix
        conf = self.use_channels, self.montage, self.montage_channels
        self.montage_matrix = self._get_montage_matrix(conf[0], conf[1], conf[2], mgr.get_param('channels_names'))
        print "self.montage_matrix: ", self.montage_matrix


        channels = ";".join(self.use_channels)
        
        # make sure that:
        # channels -- is in format like "P07;O1;Oz;O2"
        # fs -- is a number
        # avrM -- are int
        # conN -- are int
        # csp_time -- is a list of two float 0 < x < 1
        N = 0
        d, P_dict = {}, {}
        for avrM in avrM_l:
            for conN in conN_l:
                for csp_time in csp_time_l:
                    for dt in csp_dt_l:
                        d[N] = {"avrM":avrM, "conN":conN, "csp_time":[csp_time, csp_time+dt]}
                        print "d[%i] = " %N, d[N]
                        N += 1
        
        #################################
        ## CROSS CHECKING
        l = np.zeros(N)
        for idxN in range(N):
            KEY = d[idxN].keys()
            for k in KEY:
                #~ c = "{0} = {1}".format(k, d[idxN][k])
                #~ print c
                #~ exec(c)
                exec "{0}_tmp = {1}".format(k, d[idxN][k]) in globals(), locals()
                
            p300 = P300_train(channels, fs, avrM_tmp, conN_tmp, csp_time_tmp)
            l[idxN] = p300.valid_kGroups(Signal, target, nontarget, 2)
            P_dict[idxN] = p300.getPWC()


        #################################
        # Finding best    

        print "\n"*5
        print "L: ", l
        P, conN, avrM, csp_time = None, None, None, None
        BEST = -1
        arr = np.arange(len(l))
        for i in range(5):
            bestN = int(arr[l==l.max()])
            
            print "best_{0}: {1}".format(i, bestN)
            print "d[bestN]: ", d[bestN]
            print "l[bestN]: ", l.max()
            if (l.max() < 1000) and (BEST == -1): BEST = bestN
            l[bestN] = l.min()-1

        print "best: ", BEST

        P, w, c = P_dict[BEST]
        avrM = d[BEST]["avrM"]
        conN = d[BEST]["conN"]
        csp_time = d[BEST]["csp_time"]
        cfg = {"csp_time":csp_time,
                "use_channels": ';'.join(self.use_channels),
                'pVal':pVal,
                'avrM':avrM,
                'conN':conN,
                "nRepeat":nRepeat,
                "P":P,
                "w":w,
                "c":c,
                "montage":self.montage,
                "montage_channels":';'.join(self.montage_channels),
                "buffer":buffer
                }
        
        f_name = self.config.get_param("csp_file_name")
        f_dir = self.config.get_param("csp_file_path")
        ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)

        ## Plotting best
        p300_draw = P300_draw()
        p300_draw.setCalibration(target, nontarget, trgTags, ntrgTags)
        p300_draw.setCSP(P)
        p300_draw.setTimeLine(conN, avrM, csp_time)
        p300_draw.plotSignal()
        p300_draw.plotSignal_ds()
        
        LOGGER.info("FDA Calibration complete")
        if not self.run_offline:
            self._run_next_scenario()
    def run(self):
        LOGGER.info("START FDA...")

        f_name = self.config.get_param("data_file_name")
        f_dir = self.config.get_param("data_file_path")
        in_file = acquisition_helper.get_file_path(f_dir, f_name)

        filename = os.path.join(f_dir, f_name + ".obci")
        data = sp.signalParser(filename)

        fs = int(float(data.getSamplingFrequency()))

        mgr = read_manager.ReadManager(in_file + '.obci.xml',
                                       in_file + '.obci.raw',
                                       in_file + '.obci.tag')

        if self.use_channels is None:
            self.use_channels = data.getChannelList()
        if self.ignore_channels is not None:
            for i in self.ignore_channels:
                try:
                    self.use_channels.remove(i)
                except:
                    pass

        self.montage = self.config.get_param("montage")
        tmp = self.config.get_param("montage_channels")
        if len(tmp) > 0:
            self.montage_channels = tmp.split(';')
        else:
            self.montage_channels = []

        LOGGER.info("USE CHANNELS: " + str(self.use_channels))
        LOGGER.info("CHANNELS NAMES: " + str(mgr.get_param('channels_names')))

        ## Get data and tags
        data.setMontage(self.montage_channels)
        Signal = data.getData(self.use_channels)
        trgTags = data.get_p300_tags()
        ntrgTags = data.get_not_p300_tags()

        target, nontarget = data.getTargetNontarget(Signal, trgTags, ntrgTags)

        ## Get params from file
        pVal = float(self.config.get_param("p_val"))
        nRepeat = int(self.config.get_param("n_repeat"))
        nMin = int(self.config.get_param("n_min"))
        nMax = int(self.config.get_param("n_max"))

        avrM_l = map(lambda x: int(x),
                     self.config.get_param("avr_m").split(';'))
        conN_l = map(lambda x: int(x),
                     self.config.get_param("con_n").split(';'))
        csp_dt_l = map(lambda x: float(x),
                       self.config.get_param("csp_dt").split(';'))
        csp_time_l = map(lambda x: float(x),
                         self.config.get_param("csp_time").split(';'))

        ## Define buffer
        buffer = 1.1 * fs
        LOGGER.info("Computer buffer len: " + str(buffer))

        ## Make montage matrix
        conf = self.use_channels, self.montage, self.montage_channels
        self.montage_matrix = self._get_montage_matrix(
            conf[0], conf[1], conf[2], mgr.get_param('channels_names'))
        print "self.montage_matrix: ", self.montage_matrix

        channels = ";".join(self.use_channels)

        # make sure that:
        # channels -- is in format like "P07;O1;Oz;O2"
        # fs -- is a number
        # avrM -- are int
        # conN -- are int
        # csp_time -- is a list of two float 0 < x < 1
        N = 0
        d, P_dict = {}, {}
        for avrM in avrM_l:
            for conN in conN_l:
                for csp_time in csp_time_l:
                    for dt in csp_dt_l:
                        d[N] = {
                            "avrM": avrM,
                            "conN": conN,
                            "csp_time": [csp_time, csp_time + dt]
                        }
                        print "d[%i] = " % N, d[N]
                        N += 1

        #################################
        ## CROSS CHECKING
        l = np.zeros(N)
        for idxN in range(N):
            KEY = d[idxN].keys()
            for k in KEY:
                #~ c = "{0} = {1}".format(k, d[idxN][k])
                #~ print c
                #~ exec(c)
                exec "{0}_tmp = {1}".format(k,
                                            d[idxN][k]) in globals(), locals()

            p300 = P300_train(channels, fs, avrM_tmp, conN_tmp, csp_time_tmp)
            l[idxN] = p300.valid_kGroups(Signal, target, nontarget, 2)
            P_dict[idxN] = p300.getPWC()

        #################################
        # Finding best

        print "\n" * 5
        print "L: ", l
        P, conN, avrM, csp_time = None, None, None, None
        BEST = -1
        arr = np.arange(len(l))
        for i in range(5):
            bestN = int(arr[l == l.max()])

            print "best_{0}: {1}".format(i, bestN)
            print "d[bestN]: ", d[bestN]
            print "l[bestN]: ", l.max()
            if (l.max() < 1000) and (BEST == -1): BEST = bestN
            l[bestN] = l.min() - 1

        print "best: ", BEST

        P, w, c = P_dict[BEST]
        avrM = d[BEST]["avrM"]
        conN = d[BEST]["conN"]
        csp_time = d[BEST]["csp_time"]
        cfg = {
            "csp_time": csp_time,
            "use_channels": ';'.join(self.use_channels),
            'pVal': pVal,
            'avrM': avrM,
            'conN': conN,
            "nRepeat": nRepeat,
            "P": P,
            "w": w,
            "c": c,
            "montage": self.montage,
            "montage_channels": ';'.join(self.montage_channels),
            "buffer": buffer
        }

        f_name = self.config.get_param("csp_file_name")
        f_dir = self.config.get_param("csp_file_path")
        ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)

        ## Plotting best
        p300_draw = P300_draw()
        p300_draw.setCalibration(target, nontarget, trgTags, ntrgTags)
        p300_draw.setCSP(P)
        p300_draw.setTimeLine(conN, avrM, csp_time)
        p300_draw.plotSignal()
        p300_draw.plotSignal_ds()

        LOGGER.info("FDA Calibration complete")
        if not self.run_offline:
            self._run_next_scenario()
    def run(self):
        self.logger.info("START CSP...")
        f_name = self.config.get_param("data_file_name")
        f_dir = self.config.get_param("data_file_path")
        in_file = acquisition_helper.get_file_path(f_dir, f_name)
        mgr = read_manager.ReadManager(in_file + ".obci.xml", in_file + ".obci.raw", in_file + ".obci.tag")
        fs = int(float(mgr.get_param("sampling_frequency")))
        if self.use_channels is None:
            self.use_channels = mgr.get_param("channels_names")
        if self.ignore_channels is not None:
            for i in self.ignore_channels:
                try:
                    self.use_channels.remove(i)
                except:
                    pass

        self.logger.info("USE CHANNELS: " + str(self.use_channels))
        csp_time = [0.0, 0.7]
        data = p300.p300_train(
            in_file + ".obci", self.use_channels, fs, self.montage_channels, self.montage, idx=1, csp_time=csp_time
        )  # idx oznacza indeks na który
        new_tags = data.wyr()
        not_idx_tags = data.data.get_p300_tags(idx=1, rest=True, samples=False)  # Tutaj idx musi być -idx z linijki 11
        # Tagi pozostałych przypadków
        mean, left, right = data.get_mean(new_tags, m_time=csp_time, plot_mean=True)
        buffer_start = int(-csp_time[0] * fs)
        buffer_len = len(mean)
        self.logger.info("Computer buffer start / len: " + str(buffer_start) + " / " + str(buffer_len))
        mean[:left] = 0
        mean[right:] = 0
        t_vec = data.show_mean_CSP(csp_time, new_tags)
        plt.plot(t_vec, mean, "r-")
        plt.show()
        sr = 12  # Maksymalna liczba odcinków do uśrednienia; gdzieś do parametryzacji
        # targets = np.zeros([sr, len(new_tags)])
        # non_targets = np.zeros([sr, len(not_idx_tags)])
        # mu = np.zeros(sr)
        # sigma = np.zeros(sr)
        # for i in xrange(1, sr + 1):
        # x = data.get_n_mean(i, new_tags, csp_time, 0.05)
        # targets[i - 1, :], non_targets[i - 1, :], mu[i - 1], sigma[i - 1] = x
        cl, mu, sigma, mean, left, right = data.prep_classifier(sr, P_vectors=2, reg=1, mean_time=csp_time)
        q = data
        cfg = {
            "mu": mu,
            "sigma": sigma,
            "mean": mean,
            #'targets':targets,
            #'non_targets':non_targets,
            "q": q,
            "buffer_len": buffer_len,
            "buffer_start": buffer_start,
            "use_channels": ";".join(self.use_channels),
            "montage": self.montage,
            "montage_channels": ";".join(self.montage_channels),
            "left": left,
            "right": right,
            "cl": cl,
            "a_features": data.a_features,
            "bands": data.bands,
        }

        f_name = self.config.get_param("csp_file_name")
        f_dir = self.config.get_param("csp_file_path")
        ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
        self.logger.info("CSP DONE")
        if not self.run_offline:
            self._run_next_scenario()
    def run(self):
        self.logger.info("START CSP...")
        f_name = self.config.get_param("data_file_name")
        f_dir = self.config.get_param("data_file_path")
        in_file = acquisition_helper.get_file_path(f_dir, f_name)
        mgr = read_manager.ReadManager(in_file + '.obci.xml',
                                       in_file + '.obci.raw',
                                       in_file + '.obci.tag')
        fs = int(float(mgr.get_param("sampling_frequency")))
        if self.use_channels is None:
            self.use_channels = mgr.get_param('channels_names')
        if self.ignore_channels is not None:
            for i in self.ignore_channels:
                try:
                    self.use_channels.remove(i)
                except:
                    pass

        self.logger.info("USE CHANNELS: " + str(self.use_channels))
        csp_time = [0.0, 0.7]
        data = p300.p300_train(in_file + '.obci',
                               self.use_channels,
                               fs,
                               self.montage_channels,
                               self.montage,
                               idx=1,
                               csp_time=csp_time)  #idx oznacza indeks na który
        new_tags = data.wyr()
        not_idx_tags = data.data.get_p300_tags(
            idx=1, rest=True,
            samples=False)  #Tutaj idx musi być -idx z linijki 11
        #Tagi pozostałych przypadków
        mean, left, right = data.get_mean(new_tags,
                                          m_time=csp_time,
                                          plot_mean=True)
        buffer_start = int(-csp_time[0] * fs)
        buffer_len = len(mean)
        self.logger.info("Computer buffer start / len: " + str(buffer_start) +
                         " / " + str(buffer_len))
        mean[:left] = 0
        mean[right:] = 0
        t_vec = data.show_mean_CSP(csp_time, new_tags)
        plt.plot(t_vec, mean, 'r-')
        plt.show()
        sr = 12  #Maksymalna liczba odcinków do uśrednienia; gdzieś do parametryzacji
        #targets = np.zeros([sr, len(new_tags)])
        #non_targets = np.zeros([sr, len(not_idx_tags)])
        #mu = np.zeros(sr)
        #sigma = np.zeros(sr)
        #for i in xrange(1, sr + 1):
        #x = data.get_n_mean(i, new_tags, csp_time, 0.05)
        #targets[i - 1, :], non_targets[i - 1, :], mu[i - 1], sigma[i - 1] = x
        cl, mu, sigma, mean, left, right = data.prep_classifier(
            sr, P_vectors=2, reg=1, mean_time=csp_time)
        q = data
        cfg = {
            'mu': mu,
            'sigma': sigma,
            'mean': mean,
            #'targets':targets,
            #'non_targets':non_targets,
            'q': q,
            'buffer_len': buffer_len,
            'buffer_start': buffer_start,
            'use_channels': ';'.join(self.use_channels),
            'montage': self.montage,
            'montage_channels': ';'.join(self.montage_channels),
            'left': left,
            'right': right,
            'cl': cl,
            'a_features': data.a_features,
            'bands': data.bands
        }

        f_name = self.config.get_param("csp_file_name")
        f_dir = self.config.get_param("csp_file_path")
        ssvep_csp_helper.set_csp_config(f_dir, f_name, cfg)
        self.logger.info("CSP DONE")
        if not self.run_offline:
            self._run_next_scenario()