Ejemplo n.º 1
0
    def __load_bpod_ports(self):
        # present error if no serial port is selected
        if not self._serial_port.value:
            self.warning("Please select a serial port before proceeding.",
                         "No serial port selected")
            return

        if "not connected" in self._serial_port.text:
            self.warning(
                "Please connect the device to the computer before proceeding.",
                "Device not connected")
            return

        try:
            bpod = Bpod(self._serial_port.value)
            hw = bpod.hardware
            # load the ports to the GUI ###############################
            self._active_bnc.value = [
                ('BNC{0}'.format(j + 1), True)
                for j, i in enumerate(hw.bnc_inputports_indexes)
            ]
            self._active_wired.value = [
                ('Wire{0}'.format(j + 1), True)
                for j, i in enumerate(hw.wired_inputports_indexes)
            ]
            if len(self._active_behavior.value) == 0:
                self._active_behavior.value = [
                    ('Port{0}'.format(j + 1), True)
                    for j, i in enumerate(hw.behavior_inputports_indexes)
                ]
            #############################################################
            self._events.value = [["{0} ({1})".format(
                x, i)] for i, x in enumerate(hw.channels.event_names)]
            self._inputchannels.value = [
                [x] for x in hw.channels.input_channel_names
            ]
            self._outputchannels.value = [
                [x] for x in hw.channels.output_channel_names
            ]

            bpod.close()
        except Exception as e:
            self.critical(str(e), 'Error loading ports')
Ejemplo n.º 2
0
# !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Example adapted from Josh Sanders' original version on Sanworks Bpod repository
"""
from pybpodapi.bpod import Bpod
"""
Run this protocol now
"""
bpod = Bpod()

for m in bpod.modules:
    print(m)

bpod.close()
Ejemplo n.º 3
0
from pybpodapi.bpod import Bpod
from pybpodapi.state_machine import StateMachine

bpod = Bpod()

trials = 10
iti = 2

for trial in range(trials):

    # send ttl to bnc1
    sma = StateMachine(bpod)

    # initial state
    sma.add_state(
        state_name="start",
        state_timer=5,
        state_change_conditions={"Tup": "reward"},
        output_actions=[("BNC1", 1)],
    )

    # open valve1 for 20 seconds
    sma.add_state(
        state_name="reward",
        # output action will be performed for whole time state is active
        state_timer=20,
        state_change_conditions={"Tup": "exit"},
        # output action for valve open = 255
        # notation for valve alsways Valve + numer of port connected to
        output_actions=[("Valve1", 255)],
    )
Ejemplo n.º 4
0
from pybpodapi.bpod import Bpod
from pybpodapi.state_machine import StateMachine
from pybpodapi.bpod.hardware.events import EventName
from pybpodapi.bpod.hardware.output_channels import OutputChannel
import timeit

valvetimes = [.04, .06, .08, .1, .12]
Dropnum = 5
ValveOpenTime_L = 0.1  #ds
ValveOpenTime_R = 0.1  #nds
ValveOpenTime_M = 0.1  #nds
waittime = 2
ValveCloseTime = 3

my_bpod = Bpod()

# ----> Start the task
for valvetime in valvetimes:

    ValveOpenTime_L = valvetime

    ValveOpenTime_R = valvetime
    ValveOpenTime_M = valvetime

    print(ValveOpenTime_R)
    for i in range(Dropnum):  # Main loop
        print('Trial: ', i + 1)

        sma = StateMachine(my_bpod)
        sma.add_state(state_name='Wait',
Ejemplo n.º 5
0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: Niccolò Bonacchi
# @Date: Friday, January 4th 2019, 11:52:41 am
from pybpodapi.bpod import Bpod
from pybpodapi.state_machine import StateMachine

ntrials = 1
valve_on_time = 3600
iti = 0.9

# =============================================================================
# CONNECT TO BPOD
# =============================================================================
bpod = Bpod()

# =============================================================================
# TRIAL PARAMETERS AND STATE MACHINE
# =============================================================================

for i in range(ntrials):
    print('Starting trial: ', i + 1)
    # =============================================================================
    #     Start state machine definition
    # =============================================================================
    sma = StateMachine(bpod)
    sma.add_state(state_name='init',
                  state_timer=0,
                  state_change_conditions={'Tup': 'reward'},
                  output_actions=[])
Ejemplo n.º 6
0
from parameter_handler import TrialParameterHandler
from userinput import UserInput
from helperfunctions import *

# import usersettings
import usersettings

# create settings object
session_folder = os.getcwd()
settings_folder = currentdir  #os.path.join(currentdir.split('experiments')[0],"tasks","confidentiality_task_training_simple")
global settings_obj
settings_obj = TrialParameterHandler(usersettings, settings_folder,
                                     session_folder)

# create bpod object 'COM6' '/dev/cu.usbmodem62917601'
bpod = Bpod()
#bpod= Bpod('/dev/cu.usbmodem62917601') #TODO:
#create tkinter userinput dialoge window
window = UserInput(settings_obj)
window.draw_window_bevore_conf(stage="habituation_complex")
window.show_window()

# create multiprocessing variabls
# flags
display_stim_event = threading.Event()
still_show_event = threading.Event()
display_stim_event.clear()
still_show_event.clear()

#settings_obj.run_session = True #TODO:
Ejemplo n.º 7
0
                    setspeed_cmd = zaber_serial.BinaryCommand(1, 42, 1000000)
                    ser.write(setspeed_cmd)
                    setacc_cmd = zaber_serial.BinaryCommand(1, 43, 1000)
                    ser.write(setacc_cmd)
                    break
            except zaber_serial.binaryserial.serial.SerialException:
                print('can' 't access Zaber ' + str(zabertry_i))
                time.sleep(.01)


# ======================================================================================
# Main function starts here
# ======================================================================================

# ========= Setting up environment (path, metadata, etc.) ==========
my_bpod = Bpod()
history = my_bpod.session.history
experiment_name = 'not defined'
setup_name = 'not defined'
subject_name = 'not defined'
experimenter_name = 'not defined'
for histnow in history:
    if hasattr(histnow, 'infoname'):
        if histnow.infoname == 'SUBJECT-NAME':
            subject_name = histnow.infovalue
            subject_name = subject_name[2:subject_name[2:].find("'") + 2]
        elif histnow.infoname == 'CREATOR-NAME':
            experimenter_name = histnow.infovalue
            experimenter_name = experimenter_name[2:experimenter_name[2:].
                                                  find('"') + 2]
        elif histnow.infoname == 'SETUP-NAME':
Ejemplo n.º 8
0
from pybpodapi.bpod import Bpod
from pybpodapi.state_machine import StateMachine
import numpy as np
from pybpod_rotaryencoder_module.module_api import RotaryEncoderModule
from pybpodapi.com.arcom import ArCOM, ArduinoTypes
import time
import threading

bpod = Bpod()

trials = 10

#==============================================================================
# rotary encoder config
#==============================================================================
rotary_encoder = [x for x in bpod.modules if x.name == "RotaryEncoder1"][0]

reset_re = 1

bpod.load_serial_message(rotary_encoder, 1, [ord('Z'), ord('E')])
bpod.load_serial_message(rotary_encoder, 2, [ord("#"), 2])

#====================================
# onfigure encoder
#====================================
rotary_encoder = RotaryEncoderModule('COM6')

ALL_THRESHOLDS = [-10, 10]
ENABLE_THRESHOLDS = [True, True, False, False, False, False, False, False]

rotary_encoder.set_zero_position()  # Not necessarily needed
Ejemplo n.º 9
0
sampleRate = 1000  # of samples per second 1kHz
wave = np.ones(100000) * 5

waveplayer.set_sampling_period(sampleRate)
waveplayer.set_output_range(0)
waveplayer.set_loop_mode(
    [False, False, False, False, False, False, False, False])
#waveplayer.set_loop_mode([False, False, False, False])
waveplayer.debug()

print(waveplayer.load_waveform(1, wave))

waveplayer.disconnect()

# create bpod object all necessary settings are imported from GUI
bpod = Bpod('COM5')
bpod.modules[0].name
bpod.modules[1].name

wave_player = [x for x in bpod.modules if x.name == "WavePlayer1"][0]
bpod.load_serial_message(wave_player, 1, [ord('P'), 3, 0])  #15=1111
#wave_player.load_message([ord('P'), 15, 1],1)
"""
for _ in range(10):
    print(f"loop:{_}")
    waveplayer.play(1,1)
    waveplayer.play(2,1)
    waveplayer.play(3,1)
    waveplayer.play(4,1)

    time.sleep(5)
Ejemplo n.º 10
0
    def __init__(self, parent_win=None):
        self.setup = parent_win
        self.started_correctly = False

        title = 'Emulator for setup: ' + self.setup.name

        BaseWidget.__init__(self, title, parent_win=parent_win)

        self.CHECKED_ICON = conf.EMULATOR_CHECKED_ICON
        self.UNCHECKED_ICON = conf.EMULATOR_UNCHECKED_ICON

        self._currentSetup = ControlLabel(self.setup.name)
        self._selectedBoard = ControlLabel(self.setup.board.name)
        self._selectedProtocol = ControlLabel(self.setup.task.name)

        self._run_task_btn = ControlButton('Run protocol',
                                           default=self.__run_protocol_btn_evt,
                                           checkable=True,
                                           helptext="When a task is running, you can skip all remaining trials by pressing this button. <br/> <b>NOTE:</b> This means that you will need to break the cycle in your task code when the run_state_machine method returns False.")
        self._kill_task_btn = ControlButton('Kill',
                                            default=self.__kill_btn_evt,
                                            style="background-color:rgb(255,0,0);font-weight:bold;",
                                            helptext="<b>NOTE:</b>This will exit the task process abruptly. The code you might have after the trial loop won't execute.")

        self._kill_task_btn.enabled = False

        self._stop_trial_btn = ControlButton('Skip trial',
                                             default=self.__stop_trial_btn_evt,
                                             enabled=False)
        self._pause_btn = ControlButton('Pause',
                                        default=self.__pause_btn_evt,
                                        checkable=True,
                                        enabled=False)

        try:
            bpod = Bpod(self.setup.board.serial_port)
        except SerialException:
            self.critical('No Bpod device connected, cannot continue until one is connected.', 'Bpod not connected')
            return
        except Exception:
            # NOTE: try again in case of the first connection attempt where we always get the utf-8 exception
            bpod = Bpod(self.setup.board.serial_port)

        number_ports = bpod.hardware.inputs.count('P')
        number_bnc = bpod.hardware.outputs.count('B')
        number_wire_in = bpod.hardware.inputs.count('W')
        number_wire_out = bpod.hardware.outputs.count('W')

        self._valve_buttons = []
        self._valve_label = ControlLabel("Valve")
        self._led_buttons = []
        self._led_label = ControlLabel("LED")
        self._poke_buttons = []
        self._poke_label = ControlLabel("Poke")
        
        self._time_control = ControlText()   # HH

        for n in range(1, number_ports + 1):
            btn_valve = ControlButton(str(n), icon=self.UNCHECKED_ICON, checkable=True)
            btn_led = ControlButton(str(n), icon=self.UNCHECKED_ICON, checkable=True)
            btn_poke = ControlButton(str(n), icon=self.UNCHECKED_ICON, checkable=True)

            btn_valve.value = make_lambda_func(self.__button_on_click_evt, btn=btn_valve)
            btn_led.value = make_lambda_func(self.__button_on_click_evt, btn=btn_led)
            btn_poke.value = make_lambda_func(self.__button_on_click_evt, btn=btn_poke)

            setattr(self, f'_btn_Valve{n}', btn_valve)
            setattr(self, f'_btn_PWM{n}', btn_led)
            setattr(self, f'_btn_Port{n}', btn_poke)
            self._valve_buttons.append(btn_valve)
            self._led_buttons.append(btn_led)
            self._poke_buttons.append(btn_poke)

        self._bnc_in_buttons = []
        self._bnc_in_label = ControlLabel("BNC In")
        self._bnc_out_buttons = []
        self._bnc_out_label = ControlLabel("BNC Out")

        for n in range(1, number_bnc + 1):
            btn_bnc_in = ControlButton(str(n), icon=self.UNCHECKED_ICON, checkable=True)
            btn_bnc_out = ControlButton(str(n), icon=self.UNCHECKED_ICON, checkable=True)

            btn_bnc_in.value = make_lambda_func(self.__button_on_click_evt, btn=btn_bnc_in)
            btn_bnc_out.value = make_lambda_func(self.__button_on_click_evt, btn=btn_bnc_out)

            setattr(self, f'_btn_BNC_in{n}', btn_bnc_in)
            setattr(self, f'_btn_BNC_out{n}', btn_bnc_out)
            self._bnc_in_buttons.append(btn_bnc_in)
            self._bnc_out_buttons.append(btn_bnc_out)

        self._wire_in_buttons = []
        self._wire_in_label = ControlLabel("Wire In")
        self._wire_out_buttons = []
        self._wire_out_label = ControlLabel("Wire Out")

        for n in range(1, number_wire_in + 1):
            btn_wire_in = ControlButton(str(n), icon=self.UNCHECKED_ICON, checkable=True)
            btn_wire_in.value = make_lambda_func(self.__button_on_click_evt, btn=btn_wire_in)

            setattr(self, f'_btn_Wire_in{n}', btn_wire_in)
            self._wire_in_buttons.append(btn_wire_in)

        for n in range(1, number_wire_out + 1):
            btn_wire_out = ControlButton(str(n), icon=self.UNCHECKED_ICON, checkable=True)
            btn_wire_out.value = make_lambda_func(self.__button_on_click_evt, btn=btn_wire_out)

            setattr(self, f'_btn_Wire_out{n}', btn_wire_out)
            self._wire_out_buttons.append(btn_wire_out)

        self._modules_indexes_loaded = []

        for idx, mod in enumerate(bpod.modules):
            n = mod.serial_port
            self._modules_indexes_loaded.append(n)
            module_label = ControlLabel(f'{mod.name}')
            control_text_bytes_msg = ControlText()

            btn_send_msg_module = ControlButton(f'Send bytes')
            btn_send_msg_module.value = make_lambda_func(self.__send_msg_btn_evt,
                                                         btn=btn_send_msg_module,
                                                         control_text=control_text_bytes_msg)

            setattr(self, f'_module_label{n}', module_label)
            setattr(self, f'_control_text_bytes_msg{n}', control_text_bytes_msg)
            setattr(self, f'_btn_send_msg_module{n}', btn_send_msg_module)

        if bpod:
            bpod.close()

        self.formset = [
            ([('Current setup:', '_currentSetup'),
              ('Selected board:', '_selectedBoard'),
              ('Selected protocol:', '_selectedProtocol')],
             '',
             ['_run_task_btn', '_kill_task_btn', '_stop_trial_btn', '_pause_btn']),
            '',
            'Behaviour Ports',
            ('_valve_label', tuple([f'_btn_Valve{n.label}' for n in self._valve_buttons])),
            ('_led_label', tuple([f'_btn_PWM{n.label}' for n in self._led_buttons])),
            ('_poke_label', tuple([f'_btn_Port{n.label}' for n in self._poke_buttons])),
            '',
            ('Time Control (sec)', '_time_control'),
            '',
            'BNC',
            ('_bnc_in_label',
             tuple([f'_btn_BNC_in{n.label}' for n in self._bnc_in_buttons]),
             '_bnc_out_label',
             tuple([f'_btn_BNC_out{n.label}' for n in self._bnc_out_buttons])
             ),
            'Wire' if number_wire_in != 0 else '',
            ('_wire_in_label' if number_wire_in != 0 else '',
             tuple([f'_btn_Wire_in{n.label}' for n in self._wire_in_buttons]),
             '_wire_out_label' if number_wire_out != 0 else '',
             tuple([f'_btn_Wire_out{n.label}' for n in self._wire_out_buttons])
             ),
            '',
            'Send bytes to modules' if self._modules_indexes_loaded else '',
            [(f'_module_label{n}', f'_control_text_bytes_msg{n}', f'_btn_send_msg_module{n}') for n in self._modules_indexes_loaded]
        ]

        self.set_margin(10)
        self.started_correctly = True