Ejemplo n.º 1
0
def test_2(subject_list=[]):
    #---DATA DIR
    datadir = my.get_test_folder(foldername="e2_data")  #
    outdir = my.get_test_folder(foldername='e2_data_bva')

    fileid_seq = ["alpha_eo_3.meta"]
    #                ["rest_ec_1.meta","rest_eo_2.meta","alpha_eo_3.meta", #b1
    #                "rest_ec_4.meta", "rest_eo_4.meta","breathingv6_ec_4.meta", "breathingv6_eo_4.meta","imageryv6_ec_4.meta", "imageryv6_eo_4.meta","alpha_ec_5.meta","alpha_eo_5.meta",#b2
    #                "rest_ec_6.meta", "rest_eo_6.meta","breathingv6_ec_6.meta", "breathingv6_eo_6.meta","imageryv6_ec_6.meta", "imageryv6_eo_6.meta","alpha_ec_7.meta","alpha_eo_7.meta",#b3
    #                "rest_ec_8.meta", "rest_eo_8.meta","breathingv6_ec_8.meta", "breathingv6_eo_8.meta","imageryv6_ec_8.meta", "imageryv6_eo_8.meta","alpha_ec_9.meta","alpha_eo_9.meta",#b4
    #                "rest_ec_10.meta", "rest_eo_10.meta","breathingv6_ec_10.meta", "breathingv6_eo_10.meta","imageryv6_ec_10.meta", "imageryv6_eo_10.meta","alpha_ec_11.meta","alpha_eo_11.meta",#b5
    #                "rest_ec_12.meta","rest_eo_13.meta","alpha_eo_14.meta"#b6
    #                ]

    #Factorial design folder analysis
    groupdir = datadir
    group_l = os.listdir(groupdir)
    for g in group_l:
        subjectdir = os.path.join(datadir, g)
        if not os.path.isdir(subjectdir): continue  #test if is a folder
        subject_l = os.listdir(subjectdir)
        for s in subject_l:
            taskdir = os.path.join(subjectdir, s)
            if not os.path.isdir(taskdir): continue  #test if is a folder
            if subject_list and s not in subject_list: continue
            task_l = os.listdir(taskdir)
            for t in task_l:
                filedir = os.path.join(taskdir, t)
                if not os.path.isdir(filedir): continue  #test if is a folder
                file_l = [
                    name for name in os.listdir(filedir)
                    if os.path.isfile(os.path.join(filedir, name))
                ]  #get only files
                #PROCESSING
                fnseq = get_filenamesequence(file_l,
                                             fileid_seq)  #dict as no sequence
                true_fileid_seq = []
                for dn in fileid_seq:
                    if dn in fnseq:
                        true_fileid_seq.append(dn.split(".")[0])
                for k in fnseq:
                    f = fnseq[k]  #f.meta
                    if f:  #if file exists
                        filepath = os.path.join(filedir, f)
                        mushu2bva(filepath, outdir, manual_amp_ref=['Cz'])
Ejemplo n.º 2
0
    def __init__(self,
                 simulate=False,
                 replayamp=False,
                 filetoreplay=None,
                 realtimereplay=True,
                 inlet_sleep_time=float(0.0005),
                 max_inlet_samples=1024,
                 inlet_block_time=None,
                 filelogger=False,
                 logfolder='logfolder'):
        #Class logger
        loggername = self.__class__.__name__
        self.logger = logging.getLogger(loggername)
        self.logger.setLevel(logging_level)
        ##file_logger
        if filelogger:
            logpath = my.get_test_folder(foldername=logfolder)
            my.sethandlerfile(modulename=loggername,
                              setlevel=logging.INFO,
                              filepath=logpath)
        #my.all_logs_enabler(disable=True) #disable all other logs

        #INLET defs
        self.max_inlet_samples = max_inlet_samples  ##MAX INLET SAMPLES THAT WILL BE PULLED #1024 is pylsl pull_chunk standard of max samples pulled
        self.inlet_block_time = inlet_block_time  #s - directly implement block buffer in the amp.get_data() function of mushu
        self.inlet_sleep_time = inlet_sleep_time  #s - sleep time between pull chunks

        #Replay data
        self.replayamp = replayamp
        self.filetoreplay = filetoreplay
        self.realtimereplay = realtimereplay
        self.replaytime = None

        #SIMULATE AMPLIFIER in other process
        self.simulate = simulate
        if self.simulate:
            import platform
            if platform.system() == 'Windows':
                self.logger.debug("#BUG windows multiprocessing error")
                self.logger.debug(
                    "#BUG #TODO : Windows multiprocessing has some problems -  use simulate=False,  go to functions -> simulateActichamp and run the scripts for simulation"
                )
                raise RuntimeError("Windows Not Working the simulate")
            self.p_data = multiprocessing.Process(
                target=self.init_actichamp_data_simulation
            )  # can also pass parameters
            self.p_marker = multiprocessing.Process(
                target=self.init_actichamp_marker_simulation)
            self.p_data.start()  # start process
            self.p_marker.start()  # start process

        #INIT VARS
        self.init()
Ejemplo n.º 3
0
    def init(self):
        """
        Global Constants
        """
        #1.INIT Parent Class
        initbciclass.init(self)
        #2.Alter or add other functions

        #INIT SAVING
        self.TASK = 'NFT'  # NFT
        self.subtask = ""  #ALL TASKs in same FILE

        #INIT PRESENTATION VARS
        #Presentation PROTOCOL VARS- TODO: randomize protocol_feature
        self.PROTOCOL_TYPE = ""  #NFT or REST the functions will change it accordingly
        self.PROTOCOL_DESIGN = "normal"  #ABA or Normal -
        #presentation init screen
        self.INIT_TEXT = ""

        self.STIM_TIME = 30  #s

        ##EXPERIMENT VARS
        self.datatdir = my.get_test_folder(foldername="e2_data")
        self.subjectdir = "EG/S001"  #
        self.fileid = "online_result"  #id that identifies the file

        #protocol features of NFT
        self.PROTOCOL_FEATURES_L = ["SMR", "upper_alpha"]  #List
        self.PROTOCOL_FEATURE = "SMR"  #SMR or upper_alpha
        self.random_seed = None  #None or no argument seeds from current time or from an operating system specific randomness source if available

        #OFFLINE PROCESSING -
        #reward and inhibit bands - dict objects to buffer band features
        self.initial_reward_bands, self.initial_inhibit_bands = {}, {
        }  #initial bands
        self.reward_bands, self.inhibit_bands = {}, {
        }  #state bands - updated during online neurofeedback
Ejemplo n.º 4
0
        ###OFFLINE PIPELINE
        self.off_rest_bci(markernumerate=markernumerate)

        ###LOG TIME
        self.end_time = time.time()
        self.elapsed_time = self.end_time - self.start_time
        self.logger.info("!!ON_PLAY ELAPSED TIME!! : {}".format(
            self.elapsed_time))


if __name__ == "__main__":
    #1.Start Class
    rest = restclass(inlet_block_time=None)
    #save folder dir
    test_folder_path = os.path.join(my.get_test_folder(),
                                    'restclass')  #folderpath

    try:
        #2.RE-INIT Vars
        #SAVING - Reinitialize parameters
        rest.SAVE = True
        #Start dialogue
        info = {
            'SAVE': ['no', 'yes'],
            'savefolder': test_folder_path,
            'subject': 999,
            'session': 999,
            'exp_version': 2,
            'group': ['EG', 'CG', 'PILOT'],
            "technician": "Nuno Costa"
Ejemplo n.º 5
0
                  stream_server='lsl',
                  lsl_amp_name='HRV',
                  lsl_marker_name="PyffMarkerStream")
    amp = hrv
    while True:
        if run.value:
            amp.start()
            amp = loop_get_data(amp)  #update amp
            #stop() amp to close files
            amp.stop()
            run.value = not run.value


if __name__ == "__main__":
    #TEST FOLDER for files
    test_folder_path = my.get_test_folder(foldername='temp_test')

    #TEST save in multiprocessing (Something wrong in saving )
    TEST_0 = True
    if TEST_0:
        data = {'signals': 'lool'}
        #file
        timestamp = time.strftime('%d%m%Y_%Hh%Mm', time.localtime())
        datadir = test_folder_path
        method = "pcl"
        filepath = os.path.join(
            datadir,
            'e2_test_save_in_subprocess' + '_' + timestamp + '.' + method)
        subsave = my.save_in_subprocess(data, filepath, method=method)
        subsave.save()
Ejemplo n.º 6
0
        self.end_time = time.time()
        self.elapsed_time = self.end_time - self.start_time
        self.logger.info("!!ON_PLAY ELAPSED TIME!! : {}".format(
            self.elapsed_time))


if __name__ == "__main__":
    #WARNING TO SIMULATE:  USE Generated data or Replay data ( - Generated(outlet_actichamp.py,sine waves), Replay(PREFERABLY file_stream_player.py or class replayamp - does not simulate all)
    replayamp = False

    #replay sample data
    filetoreplay = my.get_filetoreplay()  #filepath

    #save folder dir
    test_folder_path = my.get_test_folder()  #folderpath

    #1.Start Class
    prime = primeclass(replayamp=replayamp, filetoreplay=filetoreplay)
    try:
        #2.RE-INIT Vars
        #SAVING - Reinitialize parameters
        #Start dialogue
        info = {
            'SAVE': ['no', 'yes'],
            'savefolder': test_folder_path,
            'subject': 1,
            'session': 1,
            'exp_version': 2,
            'group': ['EG', 'CG', 'PILOT'],
            "technician": "Nuno Costa"
Ejemplo n.º 7
0
def test_1():
    """BUG: Report class is breaking  next task
    SOLVED:
    """
    bci = initbciclass()
    prime = primeclass()
    report = reportclass()

    #save folder dir
    test_folder_path = os.path.join(my.get_test_folder(),
                                    'test_class_problems')  #folderpath

    #1.Start Class
    report = reportclass()
    prime = primeclass()
    try:
        #2.RE-INIT Vars
        #SAVING - Reinitialize parameters
        bci.SAVE = prime.SAVE = False
        report.SAVE = False  #Nao grave
        bci.SAVE_TASK = prime.SAVE_TASK = report.SAVE_TASK = True  #report.SAVE_TASK

        #Start dialogue
        info = {
            'savefolder': test_folder_path,
            'subject': 1,
            'session': 1,
            'exp_version': 2,
            'group': ['EG', 'CG', 'PILOT'],
            "technician": "Nuno Costa"
        }
        title = 'test experiment'
        fixed = ['exp_version']
        newinfo = my.gui_dialogue(info=info, title=title, fixed=fixed)

        #Save vars
        bci.FOLDER_DATA = prime.FOLDER_DATA = newinfo['savefolder']
        bci.GROUP = bci.FOLDER_DATA = prime.GROUP = newinfo['group']  #EG or CG
        bci.SUBJECT_NR = prime.SUBJECT_NR = newinfo['subject']
        bci.SESSION_NR = prime.SESSION_NR = newinfo['session']

        #INIT Methods - Saving, Acquisition and Presentation
        bci.on_init()
        #1.PRESENTATION PATCHING
        prime.pyff = bci.pyff
        report.pyff = bci.pyff
        #2.ACQUISITON PATCHING
        prime.amp = bci.amp
        report.amp = bci.amp

        #Experiment Vars
        prime.audiostimulus_l = ["imagery_v6.ogg"]
        #random.shuffle(prime.audiostimulus_l)

        #Task 1 report
        report.START_WAIT_FOR_KEY = True
        report.on_play_check()

        #Task 2 stim
        prime.STIM_TIME = 30  #s
        prime.protocol_eyes = "eyes_open"
        prime.START_WAIT_FOR_KEY = True

        #PLAY
        for i, stim in enumerate(prime.audiostimulus_l):
            print("RUN STIMULUS:", stim)
            prime.BLOCK_NR = i + 1  #BLOCK
            prime.on_play(audiostimulus=stim,
                          videostimulus=None,
                          imagestimulus=None,
                          textstimulus=None,
                          markernumerate=prime.BLOCK_NR)

        bci.on_quit()
    except:
        bci.on_quit()
Ejemplo n.º 8
0
@author: nm.costa
"""
from __future__ import (
    absolute_import, division, print_function
)  #unicode_literals - more info needed to addapt; absolute_import does not let you to import from current folder, need to specify from the main package phdproject...
from builtins import *  #all the standard builtins python 3 style

import os
import scipy
import neuroprime.src.utils.myfunctions as my

dir_dataroot = 'C:/Users/admin.DDIAS4/Desktop/e2_data/EG/S001/REST'
filename = 'EG_S001_REST_ss01_b01_16102019_11h15m_rest_ec_1'
filepath = os.path.join(dir_dataroot, filename + '.meta')

#------
filedir, filenametype = os.path.split(filepath)
filename, filetype = os.path.splitext(filenametype)
#load mushu data to mne
raw, event_id = my.mushu_to_mne(filepath, ch_names=None, montage=None)
#TODO:add manually the ref
#Save in mne fif format
nfiledir = my.get_test_folder(foldername='e2_data_fif')
nfilename = filename + ".fif"
out_filepath = os.path.join(nfiledir, nfilename)
print('saving eeg fif', nfilename)
raw.save(out_filepath)
#save in mat event_id
event_id_filepath = os.path.join(nfiledir, filename + "_event_id.mat")
print('saving event_id', event_id_filepath)
scipy.io.savemat(event_id_filepath, event_id, oned_as='row')
Ejemplo n.º 9
0
def bci():
    st = time.time()
    bci = initbciclass(filelogger=FILELOGGER, logfolder='e2_data/')
    rest = restclass(filelogger=FILELOGGER, logfolder='e2_data/')
    nft = nftclass(filelogger=FILELOGGER, logfolder='e2_data/')
    prime = primeclass(filelogger=FILELOGGER, logfolder='e2_data/')
    report = reportclass()
    et = time.time() - st
    logger.info("!!ELAPSED TIME INIT CLASS BCICLASS!! : {}".format(et))

    #RANDOM VARS
    random.seed(
    )  #None or no argument seeds from current time or from an operating system specific randomness source if available

    try:  #catch errors and close

        #2RE-INIT Vars
        #Manual REF
        bci.amp_ref_channels = rest.amp_ref_channels = nft.amp_ref_channels = prime.amp_ref_channels = AMP_MANUAL_REF

        #SAVE BY TASK
        bci.SAVE_TASK = rest.SAVE_TASK = nft.SAVE_TASK = prime.SAVE_TASK = report.SAVE_TASK = SAVE_BY_TASK  #True, save file by task or False, by session (WARNING: ALL TASKS SHOULD RESPECK THE SAME METHOD)
        folder_path = my.get_test_folder(foldername=SAVE_FOLDER)  #folderpath
        #Start dialogue (alphabetic order)
        info = {
            'EXP_VERSION': 'e2_bci',
            'SAVE_FOLDER': folder_path,
            'SAVE': ['yes', 'no'],
            'NFT_PROCESS_CHS': str(NFT_PROCESS_CHS),
            'subject': 1,
            'session': 1,
            'pg': ['EG', 'CG'],  #['EG', 'CG', 'random'],
            'feat': ['a', 's', 'd', 't', 'b', 'g'],
            'eyes': ['ec', 'eo'],
            'prime': ['BM', 'IM', 'WHM'],
            "technician": "Nuno Costa"
        }
        title = 'experiment 2'
        fixed = ['EXP_VERSION']
        newinfo = my.gui_dialogue(info=info, title=title, fixed=fixed)
        #random group choice - randomize EG and CG-not good because never know how it can end - using pseudo randomization in excel
        #        if newinfo['pg'] =="random":
        #           newinfo['pg'] = random.choice(['EG','CG'])
        #SAVE VARS
        bci.FOLDER_DATA = rest.FOLDER_DATA = nft.FOLDER_DATA = prime.FOLDER_DATA = newinfo[
            'SAVE_FOLDER']
        bci.GROUP = rest.GROUP = nft.GROUP = prime.GROUP = newinfo[
            'pg']  #EG or CG
        bci.SUBJECT_NR = rest.SUBJECT_NR = nft.SUBJECT_NR = prime.SUBJECT_NR = newinfo[
            'subject']
        bci.SESSION_NR = rest.SESSION_NR = nft.SESSION_NR = prime.SESSION_NR = newinfo[
            'session']
        bci.NFT_PROCESS_CHS = ast.literal_eval(newinfo['NFT_PROCESS_CHS'])

        if newinfo['SAVE'] == 'yes':
            bci.SAVE = rest.SAVE = nft.SAVE = prime.SAVE = True
        if newinfo['SAVE'] == 'no':
            bci.SAVE = rest.SAVE = nft.SAVE = prime.SAVE = False
        report.SAVE = False  #Nao grave

        #TOTAL BLOCK NUMBER
        bci.TOTAL_BLOCK_NR = rest.TOTAL_BLOCK_NR = nft.TOTAL_BLOCK_NR = prime.TOTAL_BLOCK_NR = TOTAL_BLOCK_NR

        ###INIT BCI
        st = time.time()

        #INIT SAVING
        rest.init_io()
        prime.init_io()
        nft.init_io()
        report.init_io()

        #INIT PRESENTATION AND ACQUISITION, PATCH NFT AND prime CLASS WITH only one AMP and PYFF object
        bci.on_init()

        #add subprocess amps - limitation - using only the first filname - #TODO: add updates
        if ADD_AMPS_ON:
            #clean up any old process
            import multiprocessing
            for p in multiprocessing.active_children():
                print("TERMINATING PROCESS: ", p.name, p.pid)
                p.terminate()  #force termination
                p.join()  #wait to terminate
            if bci.SAVE:  #add james folder to path
                bci.TASK = "JAMES"
                bci.update_file_path()
            gsr = get_amp_subprocess(filepath=bci.FILENAME_EEG_PATH,
                                     save_task=ADD_AMPS_SAVE_BY_TASK,
                                     process_name='GSR')
            gsr.configure(stream_type='GSR',
                          stream_server='lsl',
                          lsl_amp_name='GSR',
                          lsl_marker_name="PyffMarkerStream")
            hr = get_amp_subprocess(filepath=bci.FILENAME_EEG_PATH,
                                    save_task=ADD_AMPS_SAVE_BY_TASK,
                                    process_name='HR')
            hr.configure(stream_type='HR',
                         stream_server='lsl',
                         lsl_amp_name='HR',
                         lsl_marker_name="PyffMarkerStream")
            time.sleep(10)
            if bci.SAVE:  #go to james folder to path
                bci.TASK = ""
                bci.update_file_path()

        #1.PRESENTATION PATCHING
        rest.pyff = bci.pyff
        prime.pyff = bci.pyff
        nft.pyff = bci.pyff
        report.pyff = bci.pyff
        #2.ACQUISITON PATCHING
        rest.amp = bci.amp
        prime.amp = bci.amp
        nft.amp = bci.amp
        report.amp = bci.amp

        ##DEFINE VARS
        #bci vars
        bci.thresholdbuffer_eo = []
        bci.thresholdbuffer_ec = []
        #TASK protocol eyes
        if newinfo['eyes'] == "eo":
            bci.protocol_eyes_l = [
                "eyes_closed_v2", "eyes_open_v2", "eyes_open", "eyes_open",
                "eyes_open", "eyes_closed", "eyes_closed", "eyes_closed",
                "eyes_closed", "eyes_open", "eyes_open", "eyes_closed_v2",
                "eyes_open_v2", "eyes_open"
            ]
        if newinfo['eyes'] == "ec":
            bci.protocol_eyes_l = [
                "eyes_closed_v2", "eyes_open_v2", "eyes_open", "eyes_closed",
                "eyes_closed", "eyes_open", "eyes_open", "eyes_open",
                "eyes_open", "eyes_closed", "eyes_closed", "eyes_closed_v2",
                "eyes_open_v2", "eyes_open"
            ]

        #rest vars
        rest.PROTOCOL_TYPE = "REST"  #
        rest.PROTOCOL_DESIGN = "normal"

        #prime VARS
        if newinfo['prime'] == "BM":
            prime.audiostimulus_l = [
                "breathingv6.ogg", "imageryv6.ogg", "breathingv6.ogg",
                "imageryv6.ogg"
            ]
        if newinfo['prime'] == "IM":
            prime.audiostimulus_l = [
                "imageryv6.ogg", "breathingv6.ogg", "imageryv6.ogg",
                "breathingv6.ogg"
            ]
        if newinfo['prime'] == "WHM":
            prime.audiostimulus_l = [
                "imageryv6.ogg", "whmv1.ogg", "whmv1.ogg", "whmv1.ogg"
            ]
        prime.PROTOCOL_TYPE = "PRIME"  #
        prime.PROTOCOL_DESIGN = "normal"  #normal, test

        #REPORT VARS
        #None

        #NFT VARS
        if newinfo['feat'] == "a": nft.PROTOCOL_FEATURE = "alpha"
        if newinfo['feat'] == "s": nft.PROTOCOL_FEATURE = "SMR"
        nft.PROTOCOL_TYPE = "NFT"  #
        nft.PROTOCOL_DESIGN = "normal"  # Normal
        #online vars (advanced: change in nftclass)
        nft.adaptative_threshold_aftertask = MASTER_UPDATE_THRESHOLD_AFTERTASK
        nft.select_chs = bci.NFT_PROCESS_CHS  #chs used throught the processing #NOTE: Include Fp1 and Fp2 for rejection of blinks and saccades
        nft.ref_channels = RE_REFERENCE
        nft.threshold_reward_level = THRESHOLD_REWARD_LEVEL
        #INIT NFT ALGORITHM
        nft.init_processing_algorithm(feature=nft.PROTOCOL_FEATURE)

        et = time.time() - st
        logger.info("!!ELAPSED TIME INIT METHODS BCICLASS!! : {}".format(et))

        ###EXPERIMENT SESSION
        bci.start_time = time.time()

        #class initial stae
        nft.serialize(objectname="nftclass_init_state"
                      )  #BUG: #Solved puttingin init state
        prime.serialize(objectname="primeclass_init_state")
        rest.serialize(objectname="restclass_init_state")
        bci.serialize(objectname="bci_init_state")

        #master stim time for tasks
        master_stim_1 = MASTER_STIMULUS_TIME  #s #rest eo & ec
        master_stim_2 = 2 * master_stim_1  #s #rest, prime and nft full task

        #raise RuntimeError("END EXPERIMENT")

        #1. BLOCK IN
        bci.BLOCK_NR = 1
        rest.BLOCK_NR = prime.BLOCK_NR = nft.BLOCK_NR = bci.BLOCK_NR

        #task 1: rest olhos fechados
        bci.TASK_NR = 1
        rest.TASK_NR = prime.TASK_NR = nft.TASK_NR = bci.TASK_NR
        rest.STIM_TIME = master_stim_1  #s
        rest.protocol_eyes = bci.protocol_eyes_l[bci.TASK_NR - 1]
        rest.START_WAIT_FOR_KEY = True
        if ADD_AMPS_ON:
            gsr.start()
            hr.start()
        rest.on_play_check(
            markernumerate=bci.TASK_NR
        )  #rest.on_play(markernumerate=bci.TASK_NR) #or nft.off_rest_bci
        if ADD_AMPS_ON:
            gsr.stop()
            hr.stop()
        baseline_data = np.array(
            rest.amp.amp.samples_buffer
        )  #mushu format: numpy array samples X channels
        baseline_markers = rest.amp.amp.markers_buffer_mushu  #mushu format: list #timecorrected
        #initial bands thresholds eyes closed(ec)
        initial_reward_bands_ec, initial_inhibit_bands_ec = nft.baseline_thresholds(
            data=baseline_data,
            markers=baseline_markers,
            markernumerate=bci.TASK_NR)
        update_reward_bands_ec, update_inhibit_bands_ec = initial_reward_bands_ec, initial_inhibit_bands_ec
        bci.thresholdbuffer_ec.append(
            update_reward_bands_ec[nft.PROTOCOL_FEATURE]['threshold'])

        #task 2: rest olhos abertos
        bci.TASK_NR = 2
        rest.TASK_NR = prime.TASK_NR = nft.TASK_NR = bci.TASK_NR
        rest.STIM_TIME = master_stim_1  #s
        rest.protocol_eyes = bci.protocol_eyes_l[bci.TASK_NR - 1]
        rest.START_WAIT_FOR_KEY = True
        if ADD_AMPS_ON:
            gsr.start()
            hr.start()
        rest.on_play_check(
            markernumerate=bci.TASK_NR
        )  #rest.on_play(markernumerate=bci.TASK_NR) #or nft.off_rest_bci
        if ADD_AMPS_ON:
            gsr.stop()
            hr.stop()
        baseline_data = np.array(
            rest.amp.amp.samples_buffer
        )  #mushu format: numpy array samples X channels
        baseline_markers = rest.amp.amp.markers_buffer_mushu  #mushu format: list #timecorrected
        #initial bands thresholds eyes open(eo)
        initial_reward_bands_eo, initial_inhibit_bands_eo = nft.baseline_thresholds(
            data=baseline_data,
            markers=baseline_markers,
            markernumerate=bci.TASK_NR)
        update_reward_bands_eo, update_inhibit_bands_eo = initial_reward_bands_eo, initial_inhibit_bands_eo
        bci.thresholdbuffer_eo.append(
            update_reward_bands_eo[nft.PROTOCOL_FEATURE]['threshold'])

        #task 3: nft eyes open
        bci.TASK_NR = 3
        rest.TASK_NR = prime.TASK_NR = nft.TASK_NR = bci.TASK_NR
        nft.STIM_TIME = master_stim_2  #s
        nft.protocol_eyes = bci.protocol_eyes_l[bci.TASK_NR - 1]
        nft.START_WAIT_FOR_KEY = False
        nft.initial_reward_bands, nft.initial_inhibit_bands = update_reward_bands_eo, update_inhibit_bands_eo
        if ADD_AMPS_ON:
            gsr.start()
            hr.start()
        nft.on_play_check(markernumerate=bci.TASK_NR
                          )  #nft.on_play(markernumerate=bci.TASK_NR)
        if ADD_AMPS_ON:
            gsr.stop()
            hr.stop()
        #update thresholds
        if MASTER_UPDATE_THRESHOLD_AFTERTASK:
            update_reward_bands_eo[
                nft.PROTOCOL_FEATURE]['threshold'] = nft.new_threshold
        bci.thresholdbuffer_eo.append(
            update_reward_bands_eo[nft.PROTOCOL_FEATURE]['threshold'])

        #task report:  (dont update task_nr because files not saved)
        report.START_WAIT_FOR_KEY = True
        report.on_play_check()
        #raise RuntimeError("Terminate Experiment") #for tests

        #2.Block of stimulus ( FACTORIAL DESIGN)
        for i, audio in enumerate(prime.audiostimulus_l):
            #UPATE BLOCK
            bci.BLOCK_NR += 1
            rest.BLOCK_NR = prime.BLOCK_NR = nft.BLOCK_NR = bci.BLOCK_NR
            #eyes protocol copy of previous update
            irb_eo, iib_eo = copy.copy(update_reward_bands_eo), copy.copy(
                update_inhibit_bands_eo)
            irb_ec, iib_ec = copy.copy(update_reward_bands_ec), copy.copy(
                update_inhibit_bands_ec)

            #PLAY NEW BLOCK
            if bci.GROUP == "EG":
                #task 1:prime
                bci.TASK_NR += 1
                rest.TASK_NR = prime.TASK_NR = nft.TASK_NR = bci.TASK_NR
                prime.STIM_TIME = master_stim_2  #s
                prime.protocol_eyes = bci.protocol_eyes_l[bci.TASK_NR - 1]
                prime.START_WAIT_FOR_KEY = True
                if ADD_AMPS_ON:
                    gsr.start()
                    hr.start()
                prime.on_play_check(audiostimulus=audio,
                                    markernumerate=bci.TASK_NR)
                if ADD_AMPS_ON:
                    gsr.stop()
                    hr.stop()
                #task 2: NFT
                bci.TASK_NR += 1
                rest.TASK_NR = prime.TASK_NR = nft.TASK_NR = bci.TASK_NR
                nft.STIM_TIME = master_stim_2  #s
                nft.protocol_eyes = bci.protocol_eyes_l[bci.TASK_NR - 1]
                nft.START_WAIT_FOR_KEY = False
                nft.initial_reward_bands, nft.initial_inhibit_bands = irb_eo, iib_eo
                if nft.protocol_eyes == "eyes_closed":
                    nft.initial_reward_bands, nft.initial_inhibit_bands = irb_ec, iib_ec
                if ADD_AMPS_ON:
                    gsr.start()
                    hr.start()
                nft.on_play_check(markernumerate=bci.TASK_NR
                                  )  #nft.on_play(markernumerate=bci.TASK_NR)
                if ADD_AMPS_ON:
                    gsr.stop()
                    hr.stop()
                #update nft thresholds
                if nft.protocol_eyes == "eyes_open":
                    if MASTER_UPDATE_THRESHOLD_AFTERTASK:
                        update_reward_bands_eo[nft.PROTOCOL_FEATURE][
                            'threshold'] = nft.new_threshold
                    bci.thresholdbuffer_eo.append(update_reward_bands_eo[
                        nft.PROTOCOL_FEATURE]['threshold'])
                if nft.protocol_eyes == "eyes_closed":
                    if MASTER_UPDATE_THRESHOLD_AFTERTASK:
                        update_reward_bands_ec[nft.PROTOCOL_FEATURE][
                            'threshold'] = nft.new_threshold
                    bci.thresholdbuffer_ec.append(update_reward_bands_ec[
                        nft.PROTOCOL_FEATURE]['threshold'])

            elif bci.GROUP == "CG":
                #task 1: rest
                bci.TASK_NR += 1
                rest.TASK_NR = prime.TASK_NR = nft.TASK_NR = bci.TASK_NR
                rest.STIM_TIME = master_stim_1  #s
                rest.protocol_eyes = bci.protocol_eyes_l[bci.TASK_NR - 1]
                rest.START_WAIT_FOR_KEY = True
                if ADD_AMPS_ON:
                    gsr.start()
                    hr.start()
                rest.on_play_check(markernumerate=bci.TASK_NR)
                if ADD_AMPS_ON:
                    gsr.stop()
                    hr.stop()
                #task 2: nft
                bci.TASK_NR += 1
                rest.TASK_NR = prime.TASK_NR = nft.TASK_NR = bci.TASK_NR
                nft.STIM_TIME = master_stim_2  #s
                nft.protocol_eyes = bci.protocol_eyes_l[bci.TASK_NR - 1]
                nft.START_WAIT_FOR_KEY = False
                nft.initial_reward_bands, nft.initial_inhibit_bands = irb_eo, iib_eo
                if nft.protocol_eyes == "eyes_closed":
                    nft.initial_reward_bands, nft.initial_inhibit_bands = irb_ec, iib_ec
                if ADD_AMPS_ON:
                    gsr.start()
                    hr.start()
                nft.on_play_check(markernumerate=bci.TASK_NR
                                  )  #nft.on_play(markernumerate=bci.TASK_NR)
                if ADD_AMPS_ON:
                    gsr.stop()
                    hr.stop()
                #update nft thresholds
                if nft.protocol_eyes == "eyes_open":
                    if MASTER_UPDATE_THRESHOLD_AFTERTASK:
                        update_reward_bands_eo[nft.PROTOCOL_FEATURE][
                            'threshold'] = nft.new_threshold
                    bci.thresholdbuffer_eo.append(update_reward_bands_eo[
                        nft.PROTOCOL_FEATURE]['threshold'])
                if nft.protocol_eyes == "eyes_closed":
                    if MASTER_UPDATE_THRESHOLD_AFTERTASK:
                        update_reward_bands_ec[nft.PROTOCOL_FEATURE][
                            'threshold'] = nft.new_threshold
                    bci.thresholdbuffer_ec.append(update_reward_bands_ec[
                        nft.PROTOCOL_FEATURE]['threshold'])

        #3. BLOCK OUT
        bci.BLOCK_NR += 1
        rest.BLOCK_NR = prime.BLOCK_NR = nft.BLOCK_NR = bci.BLOCK_NR

        #task 1: rest olhos fechados
        bci.TASK_NR += 1
        rest.TASK_NR = prime.TASK_NR = nft.TASK_NR = bci.TASK_NR
        rest.STIM_TIME = master_stim_1  #s
        rest.protocol_eyes = bci.protocol_eyes_l[bci.TASK_NR - 1]
        rest.START_WAIT_FOR_KEY = True
        if ADD_AMPS_ON:
            gsr.start()
            hr.start()
        rest.on_play_check(markernumerate=bci.TASK_NR)
        if ADD_AMPS_ON:
            gsr.stop()
            hr.stop()

        #task 2: rest olhos abertos
        bci.TASK_NR += 1
        rest.TASK_NR = prime.TASK_NR = nft.TASK_NR = bci.TASK_NR
        rest.STIM_TIME = master_stim_1  #s
        rest.protocol_eyes = bci.protocol_eyes_l[bci.TASK_NR - 1]
        rest.START_WAIT_FOR_KEY = True
        if ADD_AMPS_ON:
            gsr.start()
            hr.start()
        rest.on_play_check(markernumerate=bci.TASK_NR)
        if ADD_AMPS_ON:
            gsr.stop()
            hr.stop()

        #task 3: nft
        bci.TASK_NR += 1
        rest.TASK_NR = prime.TASK_NR = nft.TASK_NR = bci.TASK_NR
        nft.STIM_TIME = master_stim_2  #s
        nft.protocol_eyes = bci.protocol_eyes_l[bci.TASK_NR - 1]
        nft.START_WAIT_FOR_KEY = False
        nft.initial_reward_bands, nft.initial_inhibit_bands = update_reward_bands_eo, update_inhibit_bands_eo  #or self.reward_bands, self.inhibit_bands - last calculated reward and inhibit bands
        if ADD_AMPS_ON:
            gsr.start()
            hr.start()
        nft.on_play_check(markernumerate=bci.TASK_NR
                          )  #nft.on_play(markernumerate=bci.TASK_NR)
        if ADD_AMPS_ON:
            gsr.stop()
            hr.stop()

        #task report
        report.START_WAIT_FOR_KEY = True
        report.on_play_check()

        bci.elapsed_time = time.time() - bci.start_time
        logger.info("!!ELAPSED TIME INIT METHODS BCICLASS!! : {}".format(
            bci.elapsed_time))

        bci.on_quit()
        if ADD_AMPS_ON:
            gsr.on_quit()
            hr.on_quit()

    except Exception as e:
        logger.error("!!!!SOMETHING WENT WRONG DURING BCI : {}".format(e))
        bci.on_quit()
        if ADD_AMPS_ON:
            gsr.on_quit()
            hr.on_quit()
Ejemplo n.º 10
0
def test_1():
    dir_dataroot = 'C:/Users/admin.DDIAS4/Desktop/e2_data/EG/S001/REST'
    filename = 'EG_S001_REST_ss01_b01_16102019_11h15m_rest_ec_1'
    filepath = os.path.join(dir_dataroot, filename + '.meta')
    outdir = my.get_test_folder(foldername='e2_data_bva')
    mushu2bva(filepath, outdir)
Ejemplo n.º 11
0
def bci():
    st = time.time()
    bci = initbciclass()
    rest = restclass()
    nft = nftclass()
    prime = primeclass()
    report = reportclass()

    et = time.time() - st

    logger.info("!!ELAPSED TIME INIT CLASS BCICLASS!! : {}".format(et))

    #RANDOM VARS
    random.seed(
    )  #None or no argument seeds from current time or from an operating system specific randomness source if available

    try:  #catch and close

        #2RE-INIT Vars

        #SAVE
        bci.SAVE = rest.SAVE = nft.SAVE = prime.SAVE = False
        bci.SAVE_TASK = rest.SAVE_TASK = nft.SAVE_TASK = prime.SAVE_TASK = False  #True, save file by task or False, by session
        folder_path = my.get_test_folder(foldername='e2_bci_v1')  #folderpath
        #Start dialogue
        info = {
            'savefolder': folder_path,
            'subject': 1,
            'session': 1,
            'exp_version': 'e2_v1',
            'pg': ['EG', 'CG', 'random'],
            'prime': ['BM', 'IM'],
            'feat': ['a', 's', 'd', 't', 'b', 'g'],
            "technician": "Nuno Costa"
        }  #'pg': ['EG', 'CG', 'PILOT', 'TEST','random']
        title = 'experiment 2'
        fixed = ['exp_version']
        newinfo = my.gui_dialogue(info=info, title=title, fixed=fixed)
        #random group choice - randomize EG and CG-not good because never know how it can end - using pseudo randomization in excel
        if newinfo['pg'] == "random":
            newinfo['pg'] = random.choice(['EG', 'CG'])
        #SAVE VARS
        bci.FOLDER_DATA = rest.FOLDER_DATA = nft.FOLDER_DATA = prime.FOLDER_DATA = newinfo[
            'savefolder']
        bci.GROUP = rest.GROUP = nft.GROUP = prime.GROUP = newinfo[
            'pg']  #EG or CG
        bci.SUBJECT_NR = rest.SUBJECT_NR = nft.SUBJECT_NR = prime.SUBJECT_NR = newinfo[
            'subject']
        bci.SESSION_NR = rest.SESSION_NR = nft.SESSION_NR = prime.SESSION_NR = newinfo[
            'session']

        ###INIT BCI
        st = time.time()

        #INIT SAVING
        rest.init_io()
        prime.init_io()
        nft.init_io()
        report.init_io()

        #INIT PRESENTATION AND ACQUISITION, PATCH NFT AND prime CLASS WITH only one AMP and PYFF object
        bci.on_init()

        #1.PRESENTATION PATCHING
        rest.pyff = bci.pyff
        prime.pyff = bci.pyff
        nft.pyff = bci.pyff
        report.pyff = bci.pyff
        #2.ACQUISITON PATCHING
        rest.amp = bci.amp
        prime.amp = bci.amp
        nft.amp = bci.amp
        report.amp = bci.amp

        ##DEFINE VARS
        #bci vars
        bci.thresholdbuffer_eo = []
        bci.thresholdbuffer_ec = []

        #rest vars
        nft.PROTOCOL_TYPE = "REST"  #
        rest.PROTOCOL_DESIGN = "normal"

        #prime VARS
        if newinfo['prime'] == "BM":
            prime.audiostimulus_l = ["breathingv6.ogg", "imageryv6.ogg"]
        if newinfo['prime'] == "IM":
            prime.audiostimulus_l = ["imageryv6.ogg", "breathingv6.ogg"]
        prime.PROTOCOL_TYPE = "PRIME"  #
        prime.PROTOCOL_DESIGN = "normal"  #normal, test

        #NFT VARS
        if newinfo['feat'] == "a": nft.PROTOCOL_FEATURE = "alpha"
        if newinfo['feat'] == "s": nft.PROTOCOL_FEATURE = "SMR"
        nft.PROTOCOL_TYPE = "NFT"  #
        nft.PROTOCOL_DESIGN = "normal"  # Normal
        #online vars (change in nftclass)
        #INIT NFT ALGORITHM
        nft.init_processing_algorithm(feature=nft.PROTOCOL_FEATURE)

        et = time.time() - st
        logger.info("!!ELAPSED TIME INIT METHODS BCICLASS!! : {}".format(et))

        ###EXPERIMENT SESSION
        bci.start_time = time.time()

        #master stim time for tasks
        master_stim_1 = 10  #s #rest eo & ec
        master_stim_2 = 2 * master_stim_1  #s #rest, prime and nft full task

        #1. BLOCK IN
        bci.BLOCK_NR = 1
        prime.BLOCK_NR = nft.BLOCK_NR = bci.BLOCK_NR

        #task 1: rest olhos fechados
        bci.TASK_NR = 1
        rest.TASK_NR = prime.TASK_NR = nft.TASK_NR = bci.TASK_NR
        rest.STIM_TIME = master_stim_1  #s
        rest.protocol_eyes = "eyes_closed_v2"
        rest.START_WAIT_FOR_KEY = True
        rest.on_play_check(
            markernumerate=bci.TASK_NR
        )  #rest.on_play(markernumerate=bci.TASK_NR) #or nft.off_rest_bci
        baseline_data = np.array(
            rest.amp.amp.samples_buffer
        )  #mushu format: numpy array samples X channels
        baseline_markers = rest.amp.amp.markers_buffer_mushu  #mushu format: list #timecorrected
        #initial bands thresholds eyes closed(ec)
        initial_reward_bands_ec, initial_inhibit_bands_ec = nft.baseline_thresholds(
            data=baseline_data,
            markers=baseline_markers,
            markernumerate=bci.TASK_NR)
        update_reward_bands_ec, update_inhibit_bands_ec = initial_reward_bands_ec, initial_inhibit_bands_ec
        bci.thresholdbuffer_ec.append(
            update_reward_bands_ec[nft.PROTOCOL_FEATURE]['threshold'])

        #task 2: rest olhos abertos
        bci.TASK_NR = 2
        rest.TASK_NR = prime.TASK_NR = nft.TASK_NR = bci.TASK_NR
        rest.STIM_TIME = master_stim_1  #s
        rest.protocol_eyes = "eyes_open_v2"
        rest.START_WAIT_FOR_KEY = True
        rest.on_play_check(
            markernumerate=bci.TASK_NR
        )  #rest.on_play(markernumerate=bci.TASK_NR) #or nft.off_rest_bci
        baseline_data = np.array(
            rest.amp.amp.samples_buffer
        )  #mushu format: numpy array samples X channels
        baseline_markers = rest.amp.amp.markers_buffer_mushu  #mushu format: list #timecorrected
        #initial bands thresholds eyes open(eo)
        initial_reward_bands_eo, initial_inhibit_bands_eo = nft.baseline_thresholds(
            data=baseline_data,
            markers=baseline_markers,
            markernumerate=bci.TASK_NR)
        update_reward_bands_eo, update_inhibit_bands_eo = initial_reward_bands_eo, initial_inhibit_bands_eo
        bci.thresholdbuffer_eo.append(
            update_reward_bands_eo[nft.PROTOCOL_FEATURE]['threshold'])

        #task 3: nft eyes open
        bci.TASK_NR = 3
        rest.TASK_NR = prime.TASK_NR = nft.TASK_NR = bci.TASK_NR
        nft.STIM_TIME = master_stim_2  #s
        nft.protocol_eyes = "eyes_open"
        nft.START_WAIT_FOR_KEY = False
        nft.initial_reward_bands, nft.initial_inhibit_bands = update_reward_bands_eo, update_inhibit_bands_eo
        nft.on_play_check(markernumerate=bci.TASK_NR
                          )  #nft.on_play(markernumerate=bci.TASK_NR)
        #update thresholds
        update_reward_bands_eo[
            nft.PROTOCOL_FEATURE]['threshold'] = nft.new_threshold
        bci.thresholdbuffer_eo.append(
            update_reward_bands_eo[nft.PROTOCOL_FEATURE]['threshold'])

        #task report:  (dont update task_nr because files not saved)
        report.START_WAIT_FOR_KEY = True
        report.on_play_check()

        #raise RuntimeError("Terminate Experiment")

        #2.Block of stimulus ( FACTORIAL DESIGN)
        for i, audio in enumerate(prime.audiostimulus_l):
            #UPATE BLOCK
            bci.BLOCK_NR += 1
            prime.BLOCK_NR = nft.BLOCK_NR = bci.BLOCK_NR
            #eyes protocol
            protocol_eyes = "eyes_open"
            irb, iib = update_reward_bands_eo, update_inhibit_bands_eo
            if bci.BLOCK_NR == 2 or bci.BLOCK_NR == 4:
                protocol_eyes = "eyes_closed"
                irb, iib = update_reward_bands_ec, update_inhibit_bands_ec

            #PLAY NEW BLOCK
            if bci.GROUP == "EG":
                #task 1:prime
                bci.TASK_NR += 1
                rest.TASK_NR = prime.TASK_NR = nft.TASK_NR = bci.TASK_NR
                prime.STIM_TIME = master_stim_2  #s
                prime.protocol_eyes = protocol_eyes
                prime.START_WAIT_FOR_KEY = True
                prime.on_play_check(
                    audiostimulus=audio, markernumerate=bci.TASK_NR
                )  #prime.on_play(audiostimulus=audio, markernumerate=bci.TASK_NR)

                #task 2: NFT
                bci.TASK_NR += 1
                rest.TASK_NR = prime.TASK_NR = nft.TASK_NR = bci.TASK_NR
                nft.STIM_TIME = master_stim_2  #s
                nft.protocol_eyes = protocol_eyes
                nft.START_WAIT_FOR_KEY = False
                nft.initial_reward_bands, nft.initial_inhibit_bands = irb, iib  #or self.reward_bands, self.inhibit_bands - last calculated reward and inhibit bands
                nft.on_play_check(markernumerate=bci.TASK_NR
                                  )  #nft.on_play(markernumerate=bci.TASK_NR)

            elif bci.GROUP == "CG":
                #task 1: rest
                bci.TASK_NR += 1
                rest.TASK_NR = prime.TASK_NR = nft.TASK_NR = bci.TASK_NR
                rest.STIM_TIME = master_stim_1  #s
                rest.protocol_eyes = protocol_eyes
                rest.START_WAIT_FOR_KEY = True
                rest.on_play_check(markernumerate=bci.TASK_NR)
                #task 2: nft
                bci.TASK_NR += 1
                rest.TASK_NR = prime.TASK_NR = nft.TASK_NR = bci.TASK_NR
                nft.STIM_TIME = master_stim_2  #s
                nft.protocol_eyes = protocol_eyes
                nft.START_WAIT_FOR_KEY = False
                nft.initial_reward_bands, nft.initial_inhibit_bands = irb, iib  #or self.reward_bands, self.inhibit_bands - last calculated reward and inhibit bands
                nft.on_play_check(markernumerate=bci.TASK_NR
                                  )  #nft.on_play(markernumerate=bci.TASK_NR)

            #update nft thresholds
            if protocol_eyes == "eyes_open":
                update_reward_bands_eo[
                    nft.PROTOCOL_FEATURE]['threshold'] = nft.new_threshold
                bci.thresholdbuffer_eo.append(
                    update_reward_bands_eo[nft.PROTOCOL_FEATURE]['threshold'])
            if protocol_eyes == "eyes_closed":
                update_reward_bands_ec[
                    nft.PROTOCOL_FEATURE]['threshold'] = nft.new_threshold
                bci.thresholdbuffer_ec.append(
                    update_reward_bands_ec[nft.PROTOCOL_FEATURE]['threshold'])
        """
        #3. BLOCK OUT
        bci.BLOCK_NR+1
        prime.BLOCK_NR=nft.BLOCK_NR=bci.BLOCK_NR

        #task 1: rest olhos fechados
        bci.TASK_NR +=1
        rest.TASK_NR=prime.TASK_NR=nft.TASK_NR=bci.TASK_NR
        rest.STIM_TIME= master_stim_1 #s
        rest.protocol_eyes="eyes_closed_v2"
        rest.START_WAIT_FOR_KEY=True
        rest.on_play_check(markernumerate=bci.TASK_NR)

        #task 2: rest olhos abertos
        bci.TASK_NR +=1
        rest.TASK_NR=prime.TASK_NR=nft.TASK_NR=bci.TASK_NR
        rest.STIM_TIME= master_stim_1 #s
        rest.protocol_eyes="eyes_open_v2"
        rest.START_WAIT_FOR_KEY=True
        rest.on_play_check(markernumerate=bci.TASK_NR)

        #task 3: nft
        bci.TASK_NR+=1
        rest.TASK_NR=prime.TASK_NR=nft.TASK_NR=bci.TASK_NR
        nft.STIM_TIME= master_stim_2 #s
        nft.protocol_eyes="eyes_open"
        nft.START_WAIT_FOR_KEY=False
        nft.initial_reward_bands, nft.initial_inhibit_bands = update_reward_bands_eo, update_inhibit_bands_eo #or self.reward_bands, self.inhibit_bands - last calculated reward and inhibit bands
        nft.on_play_check( markernumerate=bci.TASK_NR)#nft.on_play(markernumerate=bci.TASK_NR)

        #task report
        report.START_WAIT_FOR_KEY=True
        report.on_play_check()
        """

        bci.elapsed_time = time.time() - bci.start_time
        logger.info("!!ELAPSED TIME INIT METHODS BCICLASS!! : {}".format(
            bci.elapsed_time))

        nft.serialize(objectname="nftclass_finalstate")
        prime.serialize(objectname="primeclass_finalstate")
        bci.serialize(objectname="bci_finalstate")

        bci.on_quit()

    except Exception as e:
        logger.error("!!!!SOMETHING WENT WRONG DURING BCI : {}".format(e))
        bci.on_quit()