コード例 #1
0
def add_sensors():
    # Creating an instance of sensor

    my_camera = CameraStreaming(camera_no=0,
                                name="camera",
                                output_path="./output")

    # Creating an instance of device coordinator
    device_coordinator = DeviceCoordinator()

    # Adding sensor to device coordinator
    device_coordinator.add_devices([my_camera])

    experiment_id = "p01"
    stimuli_id = "S00"

    input("Press a button to start data recording")

    # Starts data recording
    device_coordinator.dispatch(start_message(experiment_id, stimuli_id))
    time.sleep(5)

    # Stops deta recording
    device_coordinator.dispatch(stop_message(experiment_id, stimuli_id))
    time.sleep(0.5)
    # Terminate, This step is necessary to close the connection with added devices
    device_coordinator.terminate()
コード例 #2
0
def test_should_auto_assign_device_id():
    test_device = Device()
    test_device._run = fake_run
    coordinator = DeviceCoordinator()
    coordinator.add_device(test_device)
    assert isinstance(test_device.name, str)
    assert len(test_device.name) > 0
コード例 #3
0
def test_preprocess_continuous_saving_mode():
    ch_names = [
        "Fp1", "Fp2", "F7", "F3", "F4", "F8", "T3", "C3", "C4", "T4", "T5",
        "P3", "P4", "T6", "O1", "O2"
    ]
    openbci16 = \
        MockedOpenBCIStreaming(name="OpenBCI_16_continuous",
                               saving_mode=SavingModeEnum.CONTINIOUS_SAVING_MODE,
                               output_path=os.path.join(
                                   RECORDED_FILES_PATH, "OpenBCI_16_continuous"),
                               channels_order=ch_names)
    ch_names = ["Fp1", "Fp2", "F7", "F3", "F4", "F8", "T3", "C3"]
    openbci8 = \
        MockedOpenBCIStreaming(name="OpenBCI_8_continuous",
                               saving_mode=SavingModeEnum.CONTINIOUS_SAVING_MODE,
                               output_path=os.path.join(
                                   RECORDED_FILES_PATH, "OpenBCI_8_continuous"),
                               channels_order=ch_names,
                               daisy=False)

    shimmer = \
        MockedShimmer3Streaming(name="Shimmer_continuous",
                                saving_mode=SavingModeEnum.CONTINIOUS_SAVING_MODE,
                                output_path=os.path.join(RECORDED_FILES_PATH, "Shimmer_continuous"))

    device_coordinator = DeviceCoordinator()
    device_coordinator.add_devices([openbci16, openbci8, shimmer])

    preprocess_file_path = "/tmp/preprocess"

    preprocess_devices(device_coordinator,
                       preprocess_file_path,
                       openbci_sampling_rate=6,
                       shimmer3_sampling_rate=6,
                       signal_preprocess=False)

    expected_openbci16_path = \
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     "data/preprocess_expected/OpenBCI_16_continuous")
    preprocess_openbci16_path = "/tmp/preprocess/OpenBCI_16_continuous"
    check_files(preprocess_openbci16_path, expected_openbci16_path)

    expected_openbci8_path = \
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     "data/preprocess_expected/OpenBCI_8_continuous")
    preprocess_openbci8_path = "/tmp/preprocess/OpenBCI_8_continuous"
    check_files(preprocess_openbci8_path, expected_openbci8_path)

    expected_shimmer_path = \
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     "data/preprocess_expected/Shimmer_continuous/gsr")
    preprocess_shimmer_path = "/tmp/preprocess/Shimmer_continuous/gsr"
    check_files(preprocess_shimmer_path, expected_shimmer_path)

    expected_shimmer_path = \
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     "data/preprocess_expected/Shimmer_continuous/ppg")
    preprocess_shimmer_path = "/tmp/preprocess/Shimmer_continuous/ppg"
    check_files(preprocess_shimmer_path, expected_shimmer_path)
コード例 #4
0
def simple_scenario(stimuli_path):
    # Reading image stimuli and assigning an ID to them based on their alphabetical order
    stimuli_list = os.listdir(stimuli_path)
    stimuli_list.sort()
    stimuli = {}
    i = 0
    for item in stimuli_list:
        stimuli[i] = item
        i += 1

    print("initializing")
    # Creating an instance of simmer3
    my_shimmer = Shimmer3Streaming(name="Shimmer3_sensor",
                                   output_path="./output")

    # Creating an instance of camera. by uncommenting this line and adding it to the dive_coordinator
    # you can record video data as well
    # my_camera = CameraStreaming(0, name="camera", output_path="./output", )

    # Creating an instance of device coordinator
    device_coordinator = DeviceCoordinator()

    # Adding sensor to device coordinator
    device_coordinator.add_devices([my_shimmer])

    experiment_id = "p01"

    # A delay to be sure initialing devices have finished
    time.sleep(3)

    input("\nPress a key to run the scenario")

    for stimuli_id, stmulus_name in stimuli.items():
        # Starts data recording by displaying the image
        device_coordinator.dispatch(start_message(experiment_id, stimuli_id))

        # Displaying image may start with some miliseconds delay after data recording
        # because of GTK initialization in show_image_standalone. If this delay is important to you,
        # use other tools for displaying image stimuli
        # Since image is displaying in another thread we have to manually create the same delay in current
        # thread to record data for 10 seconds

        timeout = 5
        stimulus = ImageStimulus(stimuli_id,
                                 os.path.join(stimuli_path, stmulus_name), 5)
        stimulus.show_standalone()
        time.sleep(timeout)

        # IF the stimuli is a video we are displaying stimuli as follows
        #stimulus = VideoStimulus(stimuli_id, os.path.join(stimuli_path, stmulus_name))
        #stimulus.show()

        # Stops data recording by closing image
        device_coordinator.dispatch(stop_message(experiment_id, stimuli_id))
        input("\nPress a key to continue")

    # Terminate, This step is necessary to close the connection with added devices
    device_coordinator.terminate()
コード例 #5
0
def preprocess_devices(device_coordinator: DeviceCoordinator,
                       output_path: str,
                       openbci_sampling_rate: int = 128,
                       shimmer3_sampling_rate: int = 128,
                       signal_preprocess: bool = True):
    '''
    Preprocees recorded files for all devices that are added to device_coordinator,
    Some devices do not have any preprocessing, so this function will ignore them

    @param DeviceCoordinator device_coordinator: an instance of DeviceCoordinator
    @param str output_path: Path for preprocessed Files
    @param int openbci_sampling_rate: New sampling rate for openbci resampling
    @param int shimmer3_sampling_rate: New sampling rate for shimmer3 resampling
    '''
    print("Start preprocessing ....")
    devices = device_coordinator.get_devices()
    for device in devices:
        if isinstance(device, OpenBCIStreaming):
            device_output_path = os.path.join(output_path, device.get_name())
            print("device_output_path", device_output_path)
            if not os.path.exists(device_output_path):
                pathlib.Path(device_output_path).mkdir(parents=True,
                                                       exist_ok=True)

            # This is the path that device saves recording data
            input_path = device.get_output_path()
            print("input_path", input_path)
            file_names = os.listdir(input_path)
            file_names.sort()
            if not os.path.exists(device_output_path):
                os.mkdir(device_output_path)
            for file_name in file_names:
                openbci_preprocess(input_path,
                                   file_name,
                                   device_output_path,
                                   device.get_channels(),
                                   saving_mode=device.get_saving_mode(),
                                   sampling_rate=openbci_sampling_rate,
                                   signal_preprocess=signal_preprocess)
        elif isinstance(device, Shimmer3Streaming):
            device_output_path = os.path.join(output_path, device.get_name())
            if not os.path.exists(device_output_path):
                pathlib.Path(device_output_path).mkdir(parents=True,
                                                       exist_ok=True)

            # This is the path that device saves recording data

            input_path = device.get_output_path()
            file_names = os.listdir(input_path)
            file_names.sort()
            print("preprocess shimmer input_path", input_path)
            print("preprocess shimmer device_output_path", device_output_path)
            for file_name in file_names:
                shimmer3_preprocess(input_path,
                                    file_name,
                                    device_output_path,
                                    saving_mode=device.get_saving_mode(),
                                    sampling_rate=shimmer3_sampling_rate,
                                    signal_preprocess=signal_preprocess)
    print("Preprocessing done")
コード例 #6
0
def fixture():
    test_device = Device()
    test_device._run = fake_run
    coordinator = DeviceCoordinator()
    coordinator.add_device(test_device)

    endpoint = DeviceMessageHTTPEndpoint(coordinator)
    endpoint.start()

    time.sleep(0.5)

    http_client = http.client.HTTPConnection("127.0.0.1:9331", timeout=2)

    yield (endpoint, coordinator, test_device, http_client)

    endpoint.stop()
コード例 #7
0
def test_http_network_device_happy_path():
    coordinator = DeviceCoordinator()
    device = HttpNetworkDevice(["http://localhost:5003/"],
                               name="test-http-network-device",
                               timeout=15)
    coordinator.add_device(device)

    server = http.server.ThreadingHTTPServer(("localhost", 5003), Handler)
    threading.Thread(target=server.serve_forever, daemon=True).start()

    # To ensure device and server are started
    time.sleep(1)

    coordinator.dispatch(start_message("exp1", "stim1"))
    coordinator.dispatch(stop_message("exp1", "stim2"))
    # Should send TERMINATE message
    coordinator.terminate()
コード例 #8
0
def test_should_not_add_duplicated_deivces():
    test_device = Device(name="device1")
    test_device._run = fake_run
    coordinator = DeviceCoordinator()
    coordinator.add_device(test_device)
    with pytest.raises(RuntimeError):
        coordinator.add_device(test_device)
コード例 #9
0
def main():
    device_coordinator = DeviceCoordinator()
    subject_id = "00"
    output_path = "output_remote/p{0}".format(subject_id)
    if not os.path.exists(output_path):
        os.makedirs(output_path, exist_ok=False)

    # Add your devices
    audio = AudioStreaming(2, name="Audio", output_path=output_path)
    camera = \
        CameraStreaming(name="webcam",
                        output_path=output_path,
                        camera_no=0,
                        image_width=640,
                        image_height=480)

    device_coordinator = DeviceCoordinator()
    device_coordinator.add_devices([audio, camera])

    # Create and start the endpoint
    message_endpoint = DeviceMessageHTTPEndpoint(device_coordinator)
    print("start listening")
    message_endpoint.start()

    while True:
        key = input("Please enter q to stop")
        if key == "q":
            break

    message_endpoint.stop()
コード例 #10
0
def main():
    subject_id, task_id = get_input_parameters()
    experiment_id = str(subject_id).zfill(2) + "-" + str(task_id).zfill(2)
    output_path = "examples/output/video/p{0}".format(subject_id)
    os.makedirs(output_path, exist_ok=False)

    ####### Create video device ###########
    #webcam_camera_path = "/dev/v4l/by-id/usb-046d_081b_97E6A7D0-video-index0"
    #main_camera = \
    #    CameraStreaming(name="camera",
    #                    output_path=output_path,
    #                   camera_path=webcam_camera_path,
    #                    image_width=640,
    #                   image_height=360)

    ####### Create OpenBCI device ###########
    #openbci = OpenBCIStreaming(name="OpenBCI_video", output_path=output_path)

    ####### Create Shimmer3 device ###########
    #shimmer = Shimmer3Streaming(name="Shimmer_video", output_path=output_path)

    ####### Create Network device ###########
    socket_device = SocketNetworkDevice("localhost", 5003)

    # Add to device coordinator for synchronous data recording
    device_coordinator = DeviceCoordinator()
    device_coordinator.add_devices([socket_device
                                    ])  #, openbci, shimmer, main_camera])

    stimuli_list = load_stimuli(stimuli_path)
    # Make delay for initializing all processes
    time.sleep(5)

    main_window = \
        MainWindow(experiment_id,
                   stimuli_list,
                   device_coordinator)
    main_window.show()
コード例 #11
0
def main():
    '''
    Scenario starts by 
    1- Initialization and displaying a gray screen (Put the cursor on each monitor that 
       you want to the scenario is being displayed)
    2- Displaying a fixation cross for 3 seconds
    3- Displaying a video stimulus and start to record data
    4- Displaying a questionnaire
    5- By answering the questionnaire and closing it, the same process repeat from the step 2.
       It will be repeated for the number of video stimulus in the stimuli directory
    
    Run the code like `pipenv run python watching_video_scenario.py -s 1`
    By running this command it will consider `1` as the subject number and will record data in `p01` directory
    '''

    subject_id = get_input_parameters()
    experiment_id = str(subject_id).zfill(2)
    output_path = "output/p{0}".format(experiment_id)
    os.makedirs(output_path, exist_ok=True)

    # Create and instance of video device
    camera = \
        CameraStreaming(name="webcam",
                        output_path=output_path,
                        camera_no=0,
                        image_width=640,
                        image_height=360)

    # Create an instance of OpenBCI device
    openbci = BrainFlowOpenBCIStreaming(name="eeg",
                                        output_path=output_path,
                                        serial_port="/dev/ttyUSB2",
                                        channels_order=[
                                            "Fp1", "Fp2", "F7", "F3", "F4",
                                            "F8", "T3", "C3", "C4", "T4", "T5",
                                            "P3", "P4", "T6", "O1", "O2"
                                        ])

    # Create Network device if you want to send triggers to other software and add it to device_coordinator
    #socket_device = SocketNetworkDevice("localhost", 5006)

    # Add to device coordinator for synchronous data recording
    device_coordinator = DeviceCoordinator()
    device_coordinator.add_devices([openbci, camera])

    stimuli_list = load_stimuli(stimuli_path)
    # Make delay for initializing all processes
    print("Initializing")
    time.sleep(5)

    # Creating the main Gtk window
    main_window = \
        MainWindow(experiment_id,
                   stimuli_list,
                   device_coordinator,
                   output_path=output_path)

    # After running this code, Run `pipenv run octopus-sensing-monitoring` in another terminal
    # and then monitor data on browser.
    # (Make sure to install octopus-sensing-monitoring if you want to monitor data in real time)
    monitoring_endpoint = MonitoringEndpoint(device_coordinator)
    monitoring_endpoint.start()

    try:
        # Start the scenario
        main_window.show()
        monitoring_endpoint.stop()

        # After running this code, data will be prepared in preprocessed_output path
        # By configging octopus_sensing_visualizer_config.conf in your project derectory and
        # running `pipenv run octopus-sensing-visualizer` you can visualize data on browser after finishing
        # the data collection (Make sure to install octopus-sensing-visualizer if you want to visualize data)
        preprocess_devices(device_coordinator,
                           "preprocessed_output",
                           openbci_sampling_rate=125,
                           signal_preprocess=True)
    finally:
        device_coordinator.terminate()
コード例 #12
0
def __server():
    '''
    Starts a server and send several messages and terminates
    '''
    device_coordinator = DeviceCoordinator()
    socket_device = SocketNetworkDevice("localhost", 5002)
    device_coordinator.add_devices([socket_device])

    time.sleep(5)
    message = start_message("test", "00")
    device_coordinator.dispatch(message)

    time.sleep(2)
    message = stop_message("test", "00")
    device_coordinator.dispatch(message)
    time.sleep(2)
    message = start_message("test", "01")
    device_coordinator.dispatch(message)
    time.sleep(2)
    message = stop_message("test", "01")
    device_coordinator.dispatch(message)
    time.sleep(3)

    device_coordinator.terminate()
コード例 #13
0
def test_system_health(mocked):
    '''Runs the whole system to roughly check everything is working together.'''
    # To ensure mocks are applied, we import these modules here.
    import octopus_sensing.devices.openbci_streaming as openbci_streaming
    import octopus_sensing.devices.shimmer3_streaming as shimmer3_streaming
    from octopus_sensing.device_coordinator import DeviceCoordinator
    from octopus_sensing.common.message_creators import start_message, stop_message, terminate_message
    from octopus_sensing.monitoring_endpoint import MonitoringEndpoint

    output_dir = tempfile.mkdtemp(prefix="octopus-sensing-test")

    coordinator = DeviceCoordinator()

    openbci = openbci_streaming.OpenBCIStreaming(name="eeg",
                                                 output_path=output_dir)
    coordinator.add_device(openbci)

    shimmer = shimmer3_streaming.Shimmer3Streaming(name="shimmer",
                                                   output_path=output_dir)
    coordinator.add_device(shimmer)

    monitoring_endpoint = MonitoringEndpoint(coordinator)
    monitoring_endpoint.start()

    try:
        coordinator.dispatch(start_message("int_test", "stimulus_1"))
        # Allowing data collection for five seconds
        time.sleep(5)
        coordinator.dispatch(stop_message("int_test", "stimulus_1"))

        http_client = http.client.HTTPConnection("127.0.0.1:9330")
        http_client.request("GET", "/")
        response = http_client.getresponse()
        assert response.status == 200
        monitoring_data = pickle.loads(response.read())
        assert isinstance(monitoring_data, dict)

        assert isinstance(monitoring_data["eeg"], list)
        # three seconds * data rate
        assert len(monitoring_data["eeg"]) == 3 * 128
        assert len(monitoring_data["eeg"][0]) in (34, 35)
        assert len(monitoring_data["eeg"][-1]) in (34, 35)

        assert isinstance(monitoring_data["shimmer"], list)
        assert len(monitoring_data["shimmer"]) == 3 * 128
        assert len(monitoring_data["shimmer"][0]) in (8, 9)
        assert len(monitoring_data["shimmer"][-1]) in (8, 9)

    finally:
        coordinator.dispatch(terminate_message())
        monitoring_endpoint.stop()

    # To ensure termination is happened.
    time.sleep(0.5)

    eeg_output = os.path.join(output_dir, "eeg")
    assert os.path.exists(eeg_output)
    assert len(os.listdir(eeg_output)) == 1
    assert os.listdir(eeg_output)[0] == "eeg-int_test.csv"

    shimmer_output = os.path.join(output_dir, "shimmer")
    assert os.path.exists(shimmer_output)
    assert len(os.listdir(shimmer_output)) == 1
    assert os.listdir(shimmer_output)[0] == "shimmer-int_test.csv"
コード例 #14
0
def server():
    '''
    Starts a server and sends several messages and terminates
    '''
    device_coordinator = DeviceCoordinator()
    socket_device = SocketNetworkDevice("0.0.0.0", 5002)
    device_coordinator.add_devices([socket_device])

    time.sleep(2)
    input("Press enter to start sending marker")
    message = start_message("test", "00")
    device_coordinator.dispatch(message)

    time.sleep(2)
    message = stop_message("test", "00")
    device_coordinator.dispatch(message)
    time.sleep(2)
    message = start_message("test", "01")
    device_coordinator.dispatch(message)
    time.sleep(2)
    message = stop_message("test", "01")
    device_coordinator.dispatch(message)
    time.sleep(3)

    device_coordinator.terminate()