예제 #1
0
def run_experiment():

    eeg = EEG(board_id=2, ip_port=6677, serial_port="COM4")

    exp = OnlineExperiment(eeg=eeg, model=None, num_trials=3, buffer_time=3, threshold=3)

    exp.run(use_eeg=False)
예제 #2
0
    def _csp_lda(self, eeg: EEG):

        print('Training CSP & LDA model')

        # convert data to mne.Epochs
        ch_names = eeg.get_board_names()
        ch_types = ['eeg'] * len(ch_names)
        sfreq: int = eeg.sfreq
        n_samples: int = min([t.shape[1] for t in self.trials])
        epochs_array: np.ndarray = np.stack(
            [t[:, :n_samples] for t in self.trials])

        info = mne.create_info(ch_names, sfreq, ch_types)
        epochs = mne.EpochsArray(epochs_array, info)

        # set montage
        montage = make_standard_montage('standard_1020')
        epochs.set_montage(montage)

        # Apply band-pass filter
        epochs.filter(7.,
                      30.,
                      fir_design='firwin',
                      skip_by_annotation='edge',
                      verbose=False)

        # Assemble a classifier
        lda = LinearDiscriminantAnalysis()
        csp = CSP(n_components=6, reg=None, log=True, norm_trace=False)

        # Use scikit-learn Pipeline
        self.clf = Pipeline([('CSP', csp), ('LDA', lda)])

        # fit transformer and classifier to data
        self.clf.fit(epochs.get_data(), self.labels)
예제 #3
0
    def _wait_between_trials(feedback: Feedback, eeg: EEG, use_eeg: bool):
        """
        Method for waiting between trials.

        1. Show and empty feedback while waiting.
        2. wait for user's key-press
        3. Empty the EEG board
        """

        # Show empty feedback
        feedback.display(0)

        # Wait for key-press
        event.waitKeys()

        # Empty the board
        if use_eeg:
            eeg.clear_board()
예제 #4
0
def control_mouse(config: MouseConfig, model_path: str):

    # Init variables
    model = MLModel(model_path=model_path)
    eeg = EEG(board_id=-1)
    vm = VirtualMouse(eeg=eeg, model=model, mouse_actions=config.mouse_actions)

    # Turn EEG on
    eeg.on()

    # Start controlling the virtual mouse
    while True:

        # Monitor the movement to indicate standstill
        vm.monitor(r=25, counter_limit=5, interval=0.4)

        # Predict the label imagined by the user
        label = vm.predict(buffer_time=4)

        # Convert the label to action according to current config
        action = config.get_action(label=label)

        # Execute the action
        vm.execute(action=action)
예제 #5
0
def main():

    eeg = EEG(board_id=2, ip_port=6677, serial_port="COM6")

    exp = OfflineExperiment(eeg=eeg, num_trials=4, trial_length=2)

    trials, labels = exp.run()

    trials = preprocess(eeg, trials, ch_names=['C3', 'C4'])

    features = extract_features(eeg,
                                trials,
                                features=['ptp_amp', 'mean', 'skewness'])
    # features, labels = load_featuresNlabels_fromPKL()
    model, mean_acc = train_model(features, labels)
    print(mean_acc)
예제 #6
0
def run_experiment(model_path: str):

    model = pickle.load(open(model_path, 'rb'))

    SYNTHETIC_BOARD = -1
    CYTON_DAISY = 2
    eeg = EEG(board_id=SYNTHETIC_BOARD)

    exp = OnlineExperiment(eeg=eeg,
                           model=model,
                           num_trials=10,
                           buffer_time=4,
                           threshold=3,
                           skip_after=8,
                           co_learning=True,
                           debug=False)

    exp.run(use_eeg=True, full_screen=True)
예제 #7
0
def offline_experiment():

    SYNTHETIC_BOARD = -1
    CYTON_DAISY = 2
    eeg = EEG(board_id=CYTON_DAISY)

    exp = OfflineExperiment(eeg=eeg,
                            num_trials=20,
                            trial_length=5,
                            full_screen=True,
                            audio=False)

    trials, labels = exp.run()

    # Classification
    model = MLModel(trials=trials, labels=labels)
    session_directory = exp.session_directory
    model.offline_training(eeg=eeg, model_type='csp_lda')

    # Dump the MLModel
    pickle.dump(model,
                open(os.path.join(session_directory, 'model.pickle'), 'wb'))
예제 #8
0
def preprocess(eeg: EEG, trials: List[pd.DataFrame],
               ch_names: List[str]) -> List[RawArray]:
    filtered_trials = []

    for trial in trials:
        # Create MNE RawArray object
        eeg_data = trial.to_numpy(
        ) / 1000000  # BrainFlow returns uV, convert to V for MNE
        eeg_data = eeg_data.T  # Transpose for MNE
        ch_types = ['eeg'] * len(eeg_data)
        info = mne.create_info(ch_names=eeg.eeg_names,
                               sfreq=eeg.sfreq,
                               ch_types=ch_types)
        raw = RawArray(eeg_data, info).pick_channels(ch_names)

        # Filter the data
        raw = EEG.filter_data(raw, notch=50, low_pass=4, high_pass=48)

        # Append to the filtered list
        filtered_trials.append(raw)

    return filtered_trials