Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert to python3 #124

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
16 changes: 8 additions & 8 deletions pyoperant/behavior/TargObjObj.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,16 @@ def clear_song_folder(self):
if os.path.isfile(file_path):
os.unlink(file_path)
#elif os.path.isdir(file_path): shutil.rmtree(file_path)
except Exception, e:
print e
except Exception as e:
print(e)

def get_conditions(self):
"""
generates a random 100 trial block (ABA, AAB, BAB, etc)
"""
self.trial_types = np.matrix('0; 1'); #
self.trials=[]
for i in xrange(100):
for i in range(100):
self.trials.append(random.randrange(0,2,1))
self.trial_output = [self.parameters["category_conditions"][i]["class"] for i in self.trials]

Expand All @@ -79,16 +79,16 @@ def get_motifs(self):
# if self.parameters["curblock"] == "pos2":
# thisstim.append((self.parameters["hightones"][int(np.random.uniform(0,12))], 0))

[thisstim.append((stims[str(first_motif)], 0)) for thing in xrange(repeats)]
[thisstim.append((stims[str(first_motif)], 0)) for thing in range(repeats)]

if (i == 1 and self.parameters["curblock"] == "pos1") or (i == 0 and self.parameters["curblock"] == "pos2"):
#if match and pos1 is target or nonmatch and pos2 is target
[thisstim.append((stims[str(first_motif)], 0)) for thing in xrange(repeats)]
[thisstim.append((stims[str(second_motif)], 0)) for thing in xrange(repeats)]
[thisstim.append((stims[str(first_motif)], 0)) for thing in range(repeats)]
[thisstim.append((stims[str(second_motif)], 0)) for thing in range(repeats)]
elif (i == 1 and self.parameters["curblock"] == "pos2") or (i == 0 and self.parameters["curblock"] == "pos1"):
#if match and pos2 is target or nonmatch and pos1 is target
[thisstim.append((stims[str(second_motif)], 0)) for thing in xrange(repeats)]
[thisstim.append((stims[str(first_motif)], 0)) for thing in xrange(repeats)]
[thisstim.append((stims[str(second_motif)], 0)) for thing in range(repeats)]
[thisstim.append((stims[str(first_motif)], 0)) for thing in range(repeats)]

self.song_motifs.append(thisstim)

Expand Down
4 changes: 2 additions & 2 deletions pyoperant/behavior/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
from two_alt_choice import *
from lights import *
from .two_alt_choice import *
from .lights import *
28 changes: 14 additions & 14 deletions pyoperant/behavior/text_markov.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import math
import types
import time
import cPickle
import pickle
sys.path.append('/home/pi/')
from sparray import *
import sys
Expand Down Expand Up @@ -100,28 +100,28 @@ def generate_sequences(self):
if np.random.binomial(1, self.parameters['prob_fixed_example']): # at some probability, make the model use a fixed example
# Choose which fixed example
if order == -1: # if this is a true sentence
stim_dict[unicode("class", "utf-8")] = self.parameters['reinforce_real_side']
stim_dict[str("class", "utf-8")] = self.parameters['reinforce_real_side']
seq = self.parameters['real_exemplars'][np.random.choice(self.parameters['n_exemplars'])] # chose a pregenerated real sequence
else:
stim_dict[unicode("class", "utf-8")] = self.parameters['reinforce_markov_side']
stim_dict[str("class", "utf-8")] = self.parameters['reinforce_markov_side']
seq = self.parameters['generated_exemplars'][np.random.choice(self.parameters['n_exemplars'])] # choose a pregenerated fake sequence
else:
if order == -1: # if this is a true sentence
stim_dict[unicode("class", "utf-8")] = self.parameters['reinforce_real_side'] # either L or R, this represents the reinforcement
stim_dict[str("class", "utf-8")] = self.parameters['reinforce_real_side'] # either L or R, this represents the reinforcement
seq = sentences[np.random.choice(len(sentences))]
else: # if this is a Markov generated sentence
stim_dict[unicode("class", "utf-8")] = self.parameters['reinforce_markov_side']
stim_dict[str("class", "utf-8")] = self.parameters['reinforce_markov_side']
sequence_length = sentence_lens[np.random.choice(len(sentence_lens))] # length of the sentence to be generated
seq = generate_MM_seq(sequence_length, MMs[:order+1], self.parameters['n_symbols'], use_tqdm=False)
seq_str = '-'.join([str(i) for i in seq]) # create a string representing the sequence
stim_dict[unicode("stim_name", "utf-8")] = seq_str
stim_dict[unicode("seq", "utf-8")] = list(seq)
stim_dict[unicode("order", "utf-8")] = str(order)
stim_dict[str("stim_name", "utf-8")] = seq_str
stim_dict[str("seq", "utf-8")] = list(seq)
stim_dict[str("order", "utf-8")] = str(order)
#self.sequences.append(seq)
self.parameters["stims"][seq_str] = self.parameters["stim_path"] + str(trial_num) + '.wav'
# generate the wav

stim_dict[unicode("syll_time_lens", "utf-8")] = self.build_wav(seq, self.parameters["stim_path"] + str(trial_num) + '.wav')
stim_dict[str("syll_time_lens", "utf-8")] = self.build_wav(seq, self.parameters["stim_path"] + str(trial_num) + '.wav')


self.parameters["block_design"]["blocks"]["default"]["conditions"].append(stim_dict) # add to the list of stims
Expand Down Expand Up @@ -259,7 +259,7 @@ def stimulus_main(self):
#sys.stdout.write(self.parameters["num_to_char"][str(self.this_trial.sequence[cur_sym])])
#sys.stdout.flush()
cur_sym +=1"""
for class_, port in self.class_assoc.items():
for class_, port in list(self.class_assoc.items()):
port.on() # turns on lights
break
time.sleep(.1)
Expand Down Expand Up @@ -293,7 +293,7 @@ def stimulus_main(self):
def callback(self):
# callback exists in self.panel.speaker.interface

for class_, port in self.class_assoc.items():
for class_, port in list(self.class_assoc.items()):

if port.status():

Expand Down Expand Up @@ -377,7 +377,7 @@ def generate_MM_seq(sequence_length, MMs, n_elements, use_tqdm=True):
#print('prepping seq list')
sequence = np.zeros(sequence_length)
#print('prepping iter')
seqlist = tqdm(range(sequence_length), leave=False) if use_tqdm else range(sequence_length)
seqlist = tqdm(list(range(sequence_length)), leave=False) if use_tqdm else list(range(sequence_length))
for i in seqlist:
prediction = MM_make_prediction(prev_seq = np.array(sequence)[:i],
MMs = MMs,
Expand Down Expand Up @@ -424,9 +424,9 @@ def clear_song_folder(folder= 'Generated_Songs/'):

def load_MMs(loc):
with open(loc, 'rb') as f:
return cPickle.load(f)
return pickle.load(f)


def save_MMs(MMs, loc):
with open(loc, "wb") as f:
cPickle.dump(MMs, f)
pickle.dump(MMs, f)
16 changes: 8 additions & 8 deletions pyoperant/behavior/three_ac_matching.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,33 +16,33 @@ def __init__(self, *args, **kwargs):
self.log.debug('Using reduced stimuli set only')

self.shaper = shape.Shaper3ACMatching(self.panel, self.log, self.parameters, self.get_stimuli, self.log_error_callback)
self.num_stims = len(self.parameters['stims'].items())
self.num_stims = len(list(self.parameters['stims'].items()))

def get_stimuli(self, trial_class):
""" take trial class and return a tuple containing the stimulus event to play and a list of additional events

"""
if not self.parameters['reduced_stims']:
mids = random.sample(xrange(self.num_stims), 3)
mids = random.sample(range(self.num_stims), 3)
else:
mids = random.sample(xrange(2), 2) + random.sample(xrange(3), 1)
mids = random.sample(range(2), 2) + random.sample(range(3), 1)

if trial_class == "L":
mids[2] = mids[0]
elif trial_class == "R":
mids[2] = mids[1]

motif_names, motif_files = zip(*[self.parameters['stims'].items()[mid] for mid in mids])
motif_names, motif_files = list(zip(*[list(self.parameters['stims'].items())[mid] for mid in mids]))

motif_isi = [max(random.gauss(self.parameters['isi_mean'], self.parameters['isi_stdev']), 0.0) for mot in motif_names]
motif_isi[-1] = 0.0

input_files = zip(motif_files, motif_isi)
input_files = list(zip(motif_files, motif_isi))
filename = os.path.join(self.parameters['stim_path'], ''.join(motif_names) + '.wav')
stim, epochs = utils.concat_wav(input_files, filename)

for ep in epochs:
for stim_name, f_name in self.parameters['stims'].items():
for stim_name, f_name in list(self.parameters['stims'].items()):
if ep.name in f_name:
ep.name = stim_name

Expand Down Expand Up @@ -125,8 +125,8 @@ def _run_correction_reward(self):


if parameters['debug']:
print parameters
print PANELS
print(parameters)
print(PANELS)

panel = PANELS[parameters['panel_name']]()

Expand Down
4 changes: 2 additions & 2 deletions pyoperant/interfaces/console_.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ def __init__(self,*args,**kwargs):
def _read(self,prompt=''):
""" read from keyboard input
"""
return raw_input(prompt)
return input(prompt)

def _write(self,value):
"""Write to console
"""
print value
print(value)
2 changes: 1 addition & 1 deletion pyoperant/interfaces/raspi_gpio_.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ def _poll2(self, channel, timeout=None, suppress_longpress=True, **kwargs):
print('Starting poll')
while True:
if cb1.tally() > 0:
print(cb1.tally())
print((cb1.tally()))
cb1.reset_tally()
cb1.cancel()
return datetime.datetime.now()
Expand Down
6 changes: 3 additions & 3 deletions pyoperant/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
hostname = socket.gethostname()

if 'vogel' in hostname:
from local_vogel import *
from .local_vogel import *
elif 'zog' in hostname:
from local_zog import *
from .local_zog import *
elif 'pi' in hostname:
from local_pi import *
from .local_pi import *
4 changes: 2 additions & 2 deletions pyoperant/local_vogel.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,10 @@ def test(self):
self.reset()
dur = 2.0
for output in self.outputs:
print ('output %s on' % output)
print(('output %s on' % output))
output.write(True)
utils.wait(dur)
print ('output %s off' % output)
print(('output %s off' % output))
output.write(False)
print ('reset')
self.reset()
Expand Down
26 changes: 13 additions & 13 deletions pyoperant/queues.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import random
from pyoperant.utils import rand_from_log_shape_dist
import cPickle as pickle
import pickle as pickle
import numpy as np

def random_queue(conditions,tr_max=100,weights=None):
Expand Down Expand Up @@ -72,7 +72,7 @@ def update(self, correct, no_resp):
if no_resp:
self.no_response()

def next(self):
def __next__(self):
if not self.updated: #hasn't been updated since last trial
raise Exception(self.update_error_msg()) #TODO: find what causes bug
self.updated = False
Expand Down Expand Up @@ -177,8 +177,8 @@ def update(self, correct, no_resp):
elif (self.min_val!=None) and (self.val < self.min_val):
self.val = self.min_val

def next(self):
super(KaernbachStaircase, self).next()
def __next__(self):
next(super(KaernbachStaircase, self))
if self.counter > self.crit:
raise StopIteration
self.counter += 1 if self.crit_method=='trials' else 0
Expand Down Expand Up @@ -216,8 +216,8 @@ def update(self, correct, no_resp):
self.high_idx = self.trial['value']
self.trial = {}

def next(self):
super(DoubleStaircase, self).next()
def __next__(self):
next(super(DoubleStaircase, self))
if self.high_idx - self.low_idx <= 1:
raise StopIteration

Expand Down Expand Up @@ -266,19 +266,19 @@ def update(self, correct, no_resp):
self.dblstaircase.update(correct, no_resp)
super(DoubleStaircaseReinforced, self).update(correct, no_resp)

def next(self):
super(DoubleStaircaseReinforced, self).next()
def __next__(self):
next(super(DoubleStaircaseReinforced, self))

if random.random() < self.probe_rate:
try:
ret = self.dblstaircase.next()
ret = next(self.dblstaircase)
self.last_probe = True
return ret
except StopIteration:
self.probe_rate = 0
self.last_probe = False
self.updated = True
return self.next()
return next(self)
else:
self.last_probe = False
if random.random() < .5: # probe left
Expand Down Expand Up @@ -335,12 +335,12 @@ def update(self, correct, no_resp):
self.sub_queues[self.sub_queue_idx].update(correct, no_resp)
self.save()

def next(self):
super(MixedAdaptiveQueue, self).next()
def __next__(self):
next(super(MixedAdaptiveQueue, self))
if self.probabilities is None:
try:
self.sub_queue_idx = random.randrange(len(self.sub_queues))
return self.sub_queues[self.sub_queue_idx].next()
return next(self.sub_queues[self.sub_queue_idx])
except StopIteration:
#TODO: deal with subqueue finished, and possibility of all subqueues finishing
raise NotImplementedError
Expand Down
19 changes: 9 additions & 10 deletions pyoperant/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,16 +92,16 @@ def run_state_machine(start_in='pre', error_state=None, error_callback=None, **s
None
"""
# make sure the start state has a function to run
assert (start_in in state_functions.keys())
assert (start_in in list(state_functions.keys()))
# make sure all of the arguments passed in are callable
for func in state_functions.values():
for func in list(state_functions.values()):
assert hasattr(func, '__call__')

state = start_in
while state is not None:
try:
state = state_functions[state]()
except Exception, e:
except Exception as e:
if error_callback:
error_callback(e)
raise
Expand Down Expand Up @@ -149,7 +149,7 @@ class Command(object):
output, error = '', ''

def __init__(self, command):
if isinstance(command, basestring):
if isinstance(command, str):
command = shlex.split(command)
self.command = command

Expand Down Expand Up @@ -200,10 +200,10 @@ def check_cmdline_params(parameters, cmd_line):
allchars=string.maketrans('','')
nodigs=allchars.translate(allchars, string.digits)
if not ('box' not in cmd_line or cmd_line['box'] == int(parameters['panel_name'].encode('ascii','ignore').translate(allchars, nodigs))):
print "box number doesn't match config and command line"
print("box number doesn't match config and command line")
return False
if not ('subj' not in cmd_line or int(cmd_line['subj'].encode('ascii','ignore').translate(allchars, nodigs)) == int(parameters['subject'].encode('ascii','ignore').translate(allchars, nodigs))):
print "subject number doesn't match config and command line"
print("subject number doesn't match config and command line")
return False
return True

Expand All @@ -216,7 +216,7 @@ def time_in_range(start, end, x):
else:
return start <= x or x <= end

def is_day((latitude, longitude) = ('32.82', '-117.14')):
def is_day(xxx_todo_changeme = ('32.82', '-117.14')):
"""Is it daytime?

(lat,long) -- latitude and longitude of location to check (default is San Diego*)
Expand All @@ -225,6 +225,7 @@ def is_day((latitude, longitude) = ('32.82', '-117.14')):
* Discovered by the Germans in 1904, they named it San Diego,
which of course in German means a whale's vagina. (Burgundy, 2004)
"""
(latitude, longitude) = xxx_todo_changeme
import ephem
obs = ephem.Observer()
obs.lat = latitude # San Diego, CA
Expand Down Expand Up @@ -392,9 +393,7 @@ def get_num_open_fds():
[ "lsof", '-w', '-Ff', "-p", str( pid ) ] )

nprocs = len(
filter(
lambda s: s and s[ 0 ] == 'f' and s[1: ].isdigit(),
procs.split( '\n' ) )
[s for s in procs.split( '\n' ) if s and s[ 0 ] == 'f' and s[1: ].isdigit()]
)
return nprocs

Expand Down
Loading