Skip to content

Commit 75c5133

Browse files
committed
Python 3 Compatibility
1 parent 0e7eac5 commit 75c5133

File tree

6 files changed

+31
-31
lines changed

6 files changed

+31
-31
lines changed

cili/cleanup.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from models import *
1+
from .models import *
22
import pandas as pd
33

44
#-------------------------------------------------------------
@@ -189,8 +189,8 @@ def ev_row_idxs(samples, events):
189189
"""
190190
import numpy as np
191191
idxs = []
192-
for idx, dur in events.duration.iteritems():
193-
idxs.extend(range(idx, int(idx+dur)))
192+
for idx, dur in events.duration.items():
193+
idxs.extend(list(range(idx, int(idx+dur))))
194194
idxs = np.unique(idxs)
195195
idxs = np.intersect1d(idxs, samples.index.tolist())
196196
return idxs
@@ -221,7 +221,7 @@ def adjust_eyelink_recov_idxs(samples, events, z_thresh=.1, window=1000, kernel_
221221
threshold.
222222
"""
223223
import numpy as np
224-
from util import PUP_FIELDS
224+
from .util import PUP_FIELDS
225225
# find a pupil size field to use
226226
p_fields = [f for f in samples.columns if f in PUP_FIELDS]
227227
if len(p_fields) == 0:
@@ -236,11 +236,11 @@ def adjust_eyelink_recov_idxs(samples, events, z_thresh=.1, window=1000, kernel_
236236
samp_count = len(samples)
237237
# search for drop beneath z_thresh after end index
238238
new_durs = []
239-
for idx, dur in events.duration.iteritems():
239+
for idx, dur in events.duration.items():
240240
try:
241241
s_pos = samples.index.get_loc(idx + dur) - 1
242242
e_pos = samples.index[min(s_pos+window, samp_count-1)]
243-
except Exception, e:
243+
except Exception as e:
244244
# can't do much about that
245245
s_pos = e_pos = 0
246246
if s_pos == e_pos:

cili/extract.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from models import *
1+
from .models import *
22
import pandas as pd
33
import numpy as np
44
from copy import deepcopy
@@ -64,7 +64,7 @@ def extract_event_ranges(samples, events_dataframe, start_offset=0,
6464
r_len = len(np.where(ev_idxs)[0]) + 1
6565
# we're going to make a df with a hierarchical index.
6666
samples['orig_idx'] = samples.index
67-
midx = pd.MultiIndex.from_product([range(len(e_starts)), range(r_len)],
67+
midx = pd.MultiIndex.from_product([list(range(len(e_starts))), list(range(r_len))],
6868
names=['event', 'onset'])
6969
# get all of the samples!
7070
# idxs = []
@@ -159,7 +159,7 @@ def extract_events(samples, events, offset=0, duration=0,
159159

160160
# make a hierarchical index
161161
samples['orig_idx'] = samples.index
162-
midx = pd.MultiIndex.from_product([range(len(e_starts)), range(r_dur)],
162+
midx = pd.MultiIndex.from_product([list(range(len(e_starts))), list(range(r_dur))],
163163
names=['event', 'onset'])
164164
# get the samples
165165
df = pd.DataFrame()

cili/models.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,15 +54,15 @@ def __init__(self, *args, **kwargs):
5454

5555
def save(self, save_path):
5656
s = pt.HDFStore(save_path)
57-
for k in self.dframes.keys():
57+
for k in list(self.dframes.keys()):
5858
s[k] = self.dframes[k]
5959
s.close()
6060

6161
@classmethod
6262
def load_saved(cls, save_path):
6363
obj = cls()
6464
s = pt.HDFStore(save_path)
65-
obj.dframes = dict([(k[1:],s[k]) for k in s.keys()])
65+
obj.dframes = dict([(k[1:],s[k]) for k in list(s.keys())])
6666
s.close()
6767
return obj
6868

@@ -93,7 +93,7 @@ def from_list_of_dicts(cls, events_list):
9393
corresponding DataFrame.
9494
"""
9595
import os
96-
from cPickle import load as pload
96+
from pickle import load as pload
9797
if isinstance(events_list, str):
9898
if not os.path.isfile(events_list):
9999
raise ValueError("Could not find file %s" % events_list)
@@ -108,13 +108,13 @@ def from_list_of_dicts(cls, events_list):
108108
evd[ev["name"]] = [ev]
109109
else:
110110
evd[ev["name"]].append(ev)
111-
for k in evd.keys():
111+
for k in list(evd.keys()):
112112
evd[k] = pd.DataFrame(evd[k])
113113
return cls.from_dict(evd)
114114

115115
def _local_dir(self):
116116
""" add the string-like attributes from the info_axis """
117-
return [c for c in self.dframes.keys()
117+
return [c for c in list(self.dframes.keys())
118118
if isinstance(c, string_types) and isidentifier(c)]
119119

120120
def __dir__(self):

cili/util.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from time import sleep
77
import numpy as np
88

9-
from models import *
9+
from .models import *
1010

1111
ASC_SFIELDS_EYE = {
1212
'l':[('onset', np.int64),
@@ -174,10 +174,10 @@ def pandas_df_from_txt(file_path):
174174
# accordingly. It would be nice if the dtypes would work in read_csv, but
175175
# so far no luck...
176176
df = pd.read_csv(file_path, sep="\t", index_col="TIMESTAMP", low_memory=False, na_values=["."],)
177-
fields = [str(x) for x in df.dtypes.keys()]
178-
dtypes = dict([(d, object) for d in fields if not d in TXT_FIELDS.keys()])
179-
dtypes.update(dict([(k, v) for k, v in TXT_FIELDS.iteritems() if k in fields]))
180-
nums = [k for k, v in dtypes.iteritems() if v not in [object]]
177+
fields = [str(x) for x in list(df.dtypes.keys())]
178+
dtypes = dict([(d, object) for d in fields if not d in list(TXT_FIELDS.keys())])
179+
dtypes.update(dict([(k, v) for k, v in TXT_FIELDS.items() if k in fields]))
180+
nums = [k for k, v in dtypes.items() if v not in [object]]
181181
ints = [k for k in nums if dtypes[k] in TXT_INT_TYPES]
182182
df[nums] = df[nums].convert_objects(convert_numeric=True)
183183
df[ints] = df[ints].astype(np.int64)
@@ -233,9 +233,9 @@ def pandas_dfs_from_asc(file_path):
233233

234234
def pandas_df_from_lines(csv_lines, dtypes, ignore):
235235
import pandas as pd
236-
import cStringIO
237-
c = cStringIO.StringIO("".join(csv_lines))
238-
fields, dts = zip(*dtypes)
236+
import io
237+
c = io.StringIO("".join(csv_lines))
238+
fields, dts = list(zip(*dtypes))
239239
# use_names = [n for n in fields if not n in ignore]
240240
df = pd.read_csv(c,
241241
delim_whitespace=True,
@@ -404,14 +404,14 @@ def list_run_corruption(asc_dir):
404404
vals = {}
405405
for i, fn in enumerate(files):
406406
vals[os.path.basename(fn)] = file_checks[i]
407-
print "\nDropout by File:"
407+
print("\nDropout by File:")
408408
pprint(vals)
409409

410410
def constrain_events(samples, events):
411411
""" adjusts start times of any events that overflow sample bounds"""
412412
lowtime = samples.index[0]
413413
hightime = samples.index[-1]
414-
enames = events.dframes.keys()
414+
enames = list(events.dframes.keys())
415415
for en in enames:
416416
df = events.dframes[en]
417417
idxs = np.where(df.index < lowtime)[0]
@@ -435,7 +435,7 @@ def main(argv=None):
435435
try:
436436
try:
437437
opts, args = getopt.getopt(argv[1:], "d:", ["dir", "dropout"])
438-
except getopt.error, msg:
438+
except getopt.error as msg:
439439
raise Usage(msg="\n"+str(msg))
440440
# option processing
441441
drop_check = False
@@ -452,12 +452,12 @@ def main(argv=None):
452452
if drop_check and asc_dir:
453453
list_run_corruption(asc_dir)
454454
return
455-
except Usage, err:
455+
except Usage as err:
456456
f_str = sys.argv[0].split("/")[-1] + ":"
457457
lfs = len(f_str)
458458
f_str = "%s\n%s\n%s\n" % ("-"*lfs, f_str, "-"*lfs)
459-
print >> sys.stderr, f_str + str(err.msg)
460-
print >> sys.stderr, "-------------------\nfor help use --help\n-------------------"
459+
print(f_str + str(err.msg), file=sys.stderr)
460+
print("-------------------\nfor help use --help\n-------------------", file=sys.stderr)
461461
return 2
462462

463463
if __name__ == '__main__':

tests/test_extract.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from nose.tools import assert_equal, assert_true, assert_raises, raises
55
from numpy.testing import assert_array_equal
66

7-
from config import *
7+
from .config import *
88
from cili.extract import *
99
from cili.util import load_eyelink_dataset, pandas_dfs_from_asc
1010

tests/test_util.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from pandas.util.testing import assert_frame_equal
66
from nose.tools import assert_equal, assert_true, assert_raises, raises
77

8-
from config import *
8+
from .config import *
99
from cili.util import load_eyelink_dataset, pandas_dfs_from_asc
1010

1111
# Unit tests for the util module. Paths to data files assume tests
@@ -154,7 +154,7 @@ def test_event_types():
154154
# make sure the full list of events is there
155155
ds, es = pandas_dfs_from_asc(paths['binoRemote500'])
156156
test_evs = ['END', 'EFIX', 'EBLINK', 'START', 'ESACC', 'MSG']
157-
assert_array_equal(es.dframes.keys(), test_evs)
157+
assert_array_equal(list(es.dframes.keys()), test_evs)
158158

159159
def test_end_fields():
160160
ds, es = pandas_dfs_from_asc(paths['binoRemote500'])

0 commit comments

Comments
 (0)