Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
774 changes: 609 additions & 165 deletions simple_plots.py

Large diffs are not rendered by default.

14 changes: 9 additions & 5 deletions stand_alone/gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,20 @@
from user_settings import get_user_info
import os

info_dict = get_user_info(box=os.uname()[1])
info_dict = get_user_info()

# scp -r C:\Users\Elissa\GoogleDrive\Code\Python\behavior_code\stand_alone pi@elissapi0:\home\pi
# scp C:\Users\Elissa\GoogleDrive\Code\Python\behavior_code\stand_alone\scp_rescue.py pi@elissapi1:\home\pi\behavior

# scp -r "C:\Users\Shichen\OneDrive - Johns Hopkins\ShulerLab\behavior_code\stand_alone" pi@elissapi1:\home\pi\behavior1
pastel_colors = ['#ffffcc', '#99ccff', '#cc99ff', '#ff99cc', '#ffcc99', '#ffffcc', '#99ffcc', '#ccffff', '#ccccff',
'#ffccff', '#ffcccc', '#D3D3D3']
'#ffccff', '#ffcccc', '#D3D3D3', '#f0a207']


class Gui:
def __init__(self):
self.root = tk.Tk()
self.root.geometry('2000x700')
self.root.geometry('960x360')
self.root.title('BehaviorGui')

with open('durations.pkl', 'rb') as f:
Expand All @@ -37,9 +37,11 @@ def __init__(self):
myFont = font.Font(size=30)
mouse_rows = len(info_dict['mouse_buttons'])
self.mouse_assignments = info_dict['mouse_assignments']
self.port_swap_assignments = info_dict['port_swap_assignments']
self.block_swap_assignments = info_dict['block_swap_assignments']
tasks = {
'single_reward': single_reward,
'cued_forgo': cued_forgo
'multi_reward': multi_reward
}
for key in self.mouse_assignments.keys():
self.mouse_assignments[key] = tasks[self.mouse_assignments[key]]
Expand Down Expand Up @@ -105,8 +107,10 @@ def __init__(self):

def run_behavior(self, mouse):
task = self.mouse_assignments[mouse]
swap_port = self.port_swap_assignments[mouse]
swap_block = self.block_swap_assignments[mouse]
print(f"running {task} for {mouse}")
main(mouse, task, forgo=False, forced_trials=True)
main(mouse, task, swap_port=swap_port, swap_block=swap_block)

def calibrate(self, port):
print(f'calibrating port {port}')
Expand Down
80 changes: 45 additions & 35 deletions stand_alone/main.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from support_classes import *
from tasks import *
# from tasks import *
from tasks_RK import multireward_task
from timescapes import *
import random

Expand Down Expand Up @@ -36,68 +37,76 @@
# session.start([task1])


def cued_forgo(session, reward_level, starting_prob, session_length, forgo=False, forced_trials=True):
def multi_reward(session, reward_level, starting_prob, session_length, swap_port=False, swap_block = False):
print(reward_level)
print(starting_prob)
print(session_length)
task_structure = cued_forgo_task

if forgo:
task_name = 'cued_forgo'
print('cued forgo')
task_structure = multireward_task

# rates = [.4, .8, .4, .8, .4, .8]
# if np.random.random() > .5:
# rates.reverse()

# rates = [.4, .8] #swap_block random is session by session change, swap block trial is trial by trial change
if swap_block == "random":
rates = [random.choice([0.4, 0.8])]
print (rates)
elif swap_block == "trial":
rates = [.4, .8, .4, .8, .4, .8]
if np.random.random() > .5:
rates.reverse()
else:
task_name = 'cued_no_forgo'
print('cued bg without forgo option')

if forced_trials:
task_name = task_name + '_forced'
print('forced trials included')
rates = [0.4] if not swap_block else [0.8] #0.4 if swap_block is false, 0.8 if true
# rates.reverse()

rates = [.4, .8, .4, .8, .4, .8]
if np.random.random() > .5:
rates.reverse()
exp_port = 1 if not swap_port else 2
bg_port = 2 if not swap_port else 1
print(f'exp_port = {exp_port}')
print(f'bg_port = {bg_port}')
background_dist = {'distribution': 'background',
'rates': rates,
'duration': 5,
'port_num': 2}
'port_num': bg_port}
print(background_dist['rates'])
exp_dist = {'distribution': exp_decreasing,
'cumulative': reward_level,
'starting_probability': starting_prob,
'port_num': 1}
'port_num': exp_port}
ports = {'exp': Port(exp_dist['port_num'], dist_info=exp_dist),
'background': Port(background_dist['port_num'], dist_info=background_dist)}
task1 = Task(session, name=task_name, structure=task_structure, ports=ports,
maximum=session_length, limit='time', forgo=forgo, forced_trials=forced_trials)
task1 = Task(session, name='multi_reward', structure=task_structure, ports=ports,
maximum=session_length, limit='time')
session.start([task1])


def single_reward(session, reward_level, starting_prob, session_length, forgo=False, forced_trials=True):
def single_reward(session, reward_level, starting_prob, session_length, swap_port=False, swap_block= False):
reward_level = 0.5994974874371859 # cumulative for an 8 reward version
starting_prob = 0.1301005025125628
print(reward_level)
print(starting_prob)
print(session_length)
task_structure = single_reward_task

task_name = 'single_reward'

rates = [.4, .8, .4, .8, .4, .8]
if np.random.random() > .5:
rates.reverse()
exp_port = 1 if not swap_port else 2
bg_port = 2 if not swap_port else 1
background_dist = {'distribution': 'background',
'rates': rates,
'duration': 5,
'port_num': 2}
'rates': rates,
'duration': 5,
'port_num': bg_port}
print(background_dist['rates'])
exp_dist = {'distribution': exp_decreasing,
'cumulative': reward_level,
'starting_probability': starting_prob,
'port_num': 1}
'cumulative': reward_level,
'starting_probability': starting_prob,
'port_num': exp_port}
ports = {'exp': Port(exp_dist['port_num'], dist_info=exp_dist),
'background': Port(background_dist['port_num'], dist_info=background_dist)}
'background': Port(background_dist['port_num'], dist_info=background_dist)}
task1 = Task(session, name=task_name, structure=task_structure, ports=ports,
maximum=session_length, limit='time')
maximum=session_length, limit='time')
session.start([task1])

# def give_up_blocked(session, reward_level, starting_prob, session_length, forgo=True, forced_trials=False):
Expand All @@ -122,7 +131,8 @@ def single_reward(session, reward_level, starting_prob, session_length, forgo=Fa
# session.start([task1])


def main(mouse, to_run, forgo=False, forced_trials=False):
# def main(mouse, to_run, forgo=False, forced_trials=False, swap_port=False):
def main(mouse, to_run, swap_port=False, swap_block = False): #swap port swaps BG/EXP, swap_block is the stage
cumulative = 8
start_prob = 1
session_time = 18
Expand All @@ -135,9 +145,9 @@ def main(mouse, to_run, forgo=False, forced_trials=False):

try:
if mouse not in mouse_settings.keys():
to_run(session, *mouse_settings['default'], forgo=forgo, forced_trials=forced_trials) # Run the task
to_run(session, *mouse_settings['default'], swap_port=swap_port, swap_block=swap_block) # Run the task
else:
to_run(session, *mouse_settings[mouse], forgo=forgo, forced_trials=forced_trials) # Run the task
to_run(session, *mouse_settings[mouse], swap_port=swap_port, swap_block=swap_block) # Run the task
session.smooth_finish = True
print('smooth finish')
except KeyboardInterrupt: # Catch if the task is stopped via ctrl-C or the stop button
Expand All @@ -149,6 +159,6 @@ def main(mouse, to_run, forgo=False, forced_trials=False):
if __name__ == "__main__":
# main('testmouse', cued_forgo, forgo=False, forced_trials=True)
# main('ES024', cued_forgo, forgo=False, forced_trials=True)
main('ES030', cued_forgo, forgo=False, forced_trials=True)
main('ES030', multi_reward)
# main('testmouse', give_up_blocked)

111 changes: 90 additions & 21 deletions stand_alone/support_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,72 @@ def test(i):
print('test ' + str(i))


def ssh(host, cmd, user, password, timeout=30, bg_run=False):
# def ssh(host, cmd, user, password, timeout=30, bg_run=False):
# """SSH'es to a host using the supplied credentials and executes a command.
# Throws an exception if the command doesn't return 0.
# bgrun: run command in the background"""
#
# options = '-q -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oPubkeyAuthentication=no'
# if bg_run:
# options += ' -f'
#
# ssh_cmd = 'ssh %s@%s %s \'%s\'' % (user, host, options, cmd)
# print(ssh_cmd)
# child = pexpect.spawnu(ssh_cmd, timeout=timeout)
# child.expect([r'(?i).*password.*:'])
# child.sendline(password)
# child.expect(pexpect.EOF)
# child.close()


# def scp(host, filename, destination, user, password, timeout=30, bg_run=False, recursive=False, cmd=False):
# """Scp's to a host using the supplied credentials and executes a command.
# Throws an exception if the command doesn't return 0.
# bgrun: run command in the background"""
#
# options = '-q -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oPubkeyAuthentication=no'
# if recursive:
# options += ' -r'
# if bg_run:
# options += ' -f'
# scp_cmd = 'scp %s %s %s@%s:\'"%s"\'' % (options, filename, user, host, os.path.join(destination, filename))
# password_prompt = rf"{user}@{host}'s password: "
# print(password_prompt)
# child = None
# status = 1
# print(scp_cmd)
# try:
# if cmd:
# return scp_cmd
# child = pexpect.spawnu(scp_cmd, timeout=timeout) # spawnu for Python 3
# child.expect(password_prompt)
# child.sendline(password)
# child.expect(pexpect.EOF)
# child.close()
# status = child.exitstatus
# except Exception as e:
# print('scp didn\'t work the first time so we are trying again with different password')
# try:
# # scp_cmd2 = 'scp %s %s %s@%s:"%s"' % (options, filename, user, host, os.path.join(destination, filename))
# # print(scp_cmd2)
# # if cmd:
# # return scp_cmd2
# child = pexpect.spawnu(scp_cmd, timeout=timeout) # spawnu for Python 3
# child.expect([r"(?i).*password.*:?(\s*)"])
# child.sendline(password)
# child.expect(pexpect.EOF)
# child.close()
# status = child.exitstatus
# except Exception as e_2:
# print(f"still didnt work: {e_2}")
# status = 1
# if status == 0:
# print("file transfer completed!")
# else:
# print("transfer failed.")
# return status

def ssh(host, cmd, user, password, timeout=60, bg_run=False):
"""SSH'es to a host using the supplied credentials and executes a command.
Throws an exception if the command doesn't return 0.
bgrun: run command in the background"""
Expand All @@ -54,12 +119,10 @@ def ssh(host, cmd, user, password, timeout=30, bg_run=False):
ssh_cmd = 'ssh %s@%s %s \'%s\'' % (user, host, options, cmd)
print(ssh_cmd)
child = pexpect.spawnu(ssh_cmd, timeout=timeout)
child.expect(['[Pp]assword: '])
child.expect([r"(?i).*password.*:?(\s*)"])
child.sendline(password)
child.expect(pexpect.EOF)
child.close()


def scp(host, filename, destination, user, password, timeout=30, bg_run=False, recursive=False, cmd=False):
"""Scp's to a host using the supplied credentials and executes a command.
Throws an exception if the command doesn't return 0.
Expand Down Expand Up @@ -96,7 +159,6 @@ def scp(host, filename, destination, user, password, timeout=30, bg_run=False, r
print('worked!')
return child.exitstatus


def sync_stream(self):
pin_map = {'session': 25,
'trial': 8,
Expand Down Expand Up @@ -142,7 +204,7 @@ def __init__(self, mouse):
self.data_write_path = "/data/" + self.mouse
self.datetime = time.strftime("%Y-%m-%d_%H-%M-%S")
self.filename = "data_" + self.datetime + ".txt"

self.isstarted = False
self.halted = False
self.smooth_finish = False
GPIO.setmode(GPIO.BCM)
Expand All @@ -167,6 +229,7 @@ def __init__(self, mouse):
GPIO.output(self.camera_pin, GPIO.LOW)

def start(self, task_list):
self.isstarted = True
for val in self.sync_pins.values():
GPIO.setup(val, GPIO.OUT)
GPIO.output(val, GPIO.LOW)
Expand All @@ -190,27 +253,33 @@ def start(self, task_list):
perform(task)

def log(self, string): # Adds session time stamp to beginning of string and logs it
session_time = time.time() - self.start_time
new_line = str(session_time) + ',' + string + '\n'
# print(new_line)
self.f.write(new_line)
if self.isstarted:
session_time = time.time() - self.start_time
new_line = str(session_time) + ',' + string + '\n'
# print(new_line)
self.f.write(new_line)

def end(self):
self.log('nan,nan,nan,nan,setup,nan,0,session')
self.f.close()
os.system('sudo chmod o-w ' + self.filename)
mkdir_command = 'if not exist "%s" mkdir "%s"' % (
self.ssh_path.replace('/', '\\'), self.ssh_path.replace('/', '\\'))
ssh(self.ip, mkdir_command, self.user, self.password)
res = scp(self.ip, self.filename, self.data_send_path, self.user, self.password)
if not res:
print('\nSuccessful file transfer to "%s"\nDeleting local file from pi.' % self.data_send_path)
os.remove(self.filename)
else:
print('connection back to desktop timed out')
GPIO.cleanup()
os.chdir(os.path.join(os.getcwd(), '..', '..'))
print('\nFile closed and clean up complete')
try:
ssh(self.ip, mkdir_command, self.user, self.password)
res = scp(self.ip, self.filename, self.data_send_path, self.user, self.password)
if res == 0:
print('\nSuccessful file transfer to "%s"\nDeleting local file from pi.' % self.data_send_path)
os.remove(self.filename)
except Exception as e:
res = 1
print('scp failed with the following error')
print(e)
finally:
os.chdir(os.path.join(os.getcwd(), '..', '..'))
print('file location is back to the project root')
GPIO.cleanup()
print('\nFile closed and clean up complete')
if self.halted:
print('Session stopped early')
elif self.smooth_finish:
Expand Down Expand Up @@ -323,7 +392,7 @@ def lick_status_change(self):

class Task:
def __init__(self, session, name='blank', structure=None, ports=None, limit='trials',
maximum=None, forgo=True, forced_trials=False):
maximum=None, forgo=False, forced_trials=True):
print('Starting task: %s' % name)
self.structure = structure
self.port_dict = ports
Expand Down
Loading