diff --git a/pyoperant/behavior/TargObjObj.py b/pyoperant/behavior/TargObjObj.py index c2eb25e3..f67f48b0 100755 --- a/pyoperant/behavior/TargObjObj.py +++ b/pyoperant/behavior/TargObjObj.py @@ -43,8 +43,8 @@ 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): """ @@ -52,7 +52,7 @@ def get_conditions(self): """ 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] @@ -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) diff --git a/pyoperant/behavior/__init__.py b/pyoperant/behavior/__init__.py index 03ca9402..59dea136 100755 --- a/pyoperant/behavior/__init__.py +++ b/pyoperant/behavior/__init__.py @@ -1,2 +1,2 @@ -from two_alt_choice import * -from lights import * +from .two_alt_choice import * +from .lights import * diff --git a/pyoperant/behavior/text_markov.py b/pyoperant/behavior/text_markov.py index 5a15a622..0548bde8 100755 --- a/pyoperant/behavior/text_markov.py +++ b/pyoperant/behavior/text_markov.py @@ -14,7 +14,7 @@ import math import types import time -import cPickle +import pickle sys.path.append('/home/pi/') from sparray import * import sys @@ -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 @@ -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) @@ -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(): @@ -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, @@ -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) diff --git a/pyoperant/behavior/three_ac_matching.py b/pyoperant/behavior/three_ac_matching.py index 9f07fc25..c8b30cdb 100755 --- a/pyoperant/behavior/three_ac_matching.py +++ b/pyoperant/behavior/three_ac_matching.py @@ -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 @@ -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']]() diff --git a/pyoperant/interfaces/console_.py b/pyoperant/interfaces/console_.py index 8a1ff6ed..d54f7de7 100644 --- a/pyoperant/interfaces/console_.py +++ b/pyoperant/interfaces/console_.py @@ -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) diff --git a/pyoperant/interfaces/raspi_gpio_.py b/pyoperant/interfaces/raspi_gpio_.py index b368f411..73cec035 100644 --- a/pyoperant/interfaces/raspi_gpio_.py +++ b/pyoperant/interfaces/raspi_gpio_.py @@ -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() diff --git a/pyoperant/local.py b/pyoperant/local.py index 69eecaa5..dd9b5d33 100644 --- a/pyoperant/local.py +++ b/pyoperant/local.py @@ -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 * diff --git a/pyoperant/local_vogel.py b/pyoperant/local_vogel.py index 4179fafc..29794297 100644 --- a/pyoperant/local_vogel.py +++ b/pyoperant/local_vogel.py @@ -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() diff --git a/pyoperant/queues.py b/pyoperant/queues.py index 027b0c68..65eb8f4b 100644 --- a/pyoperant/queues.py +++ b/pyoperant/queues.py @@ -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): @@ -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 @@ -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 @@ -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 @@ -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 @@ -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 diff --git a/pyoperant/utils.py b/pyoperant/utils.py index bc2ceda3..afcfc265 100644 --- a/pyoperant/utils.py +++ b/pyoperant/utils.py @@ -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 @@ -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 @@ -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 @@ -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*) @@ -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 @@ -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 diff --git a/scripts/behave b/scripts/behave index a3122142..f13ba439 100755 --- a/scripts/behave +++ b/scripts/behave @@ -66,7 +66,7 @@ def list_protocols(): l = [] behav_modules = [importlib.import_module(pstr) for pstr in BEHAVIORS] for mod in behav_modules: - for name, obj in mod.__dict__.iteritems(): + for name, obj in mod.__dict__.items(): try: if issubclass(obj,BaseExp): l.append(name) @@ -112,11 +112,11 @@ def main(): print(parameters) if ('debug' in parameters) and parameters['debug']: - print parameters - print PANELS + print(parameters) + print(PANELS) for k in ['subject','panel_name','experiment_path']: - parameters.pop(k) if k in parameters.keys() else None + parameters.pop(k) if k in list(parameters.keys()) else None stimuli_path = parameters.pop('stim_path') if 'stim_path' in parameters else stimuli_path