Skip to content

Commit 4cbc8c3

Browse files
committed
Merge branch 'py3'
2 parents bb185d7 + 73ce7d1 commit 4cbc8c3

17 files changed

Lines changed: 352 additions & 275 deletions

gat/Engine.pyx

Lines changed: 114 additions & 97 deletions
Large diffs are not rendered by default.

gat/Experiment.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ def getParams(options=None):
117117
result.append("# %-40s: %s" % (k, str(v).encode("string_escape")))
118118
else:
119119
vars = inspect.currentframe().f_back.f_locals
120-
for var in filter(lambda x: re.match("param_", x), vars.keys()):
120+
for var in [x for x in list(vars.keys()) if re.match("param_", x)]:
121121
result.append("# %-40s: %s" %
122122
(var, str(vars[var]).encode("string_escape")))
123123

@@ -133,7 +133,7 @@ def getFooter():
133133
return "# job finished in %i seconds at %s -- %s -- %s" %\
134134
(time.time() - global_starting_time,
135135
time.asctime(time.localtime(time.time())),
136-
" ".join(map(lambda x: "%5.2f" % x, os.times()[:4])),
136+
" ".join(["%5.2f" % x for x in os.times()[:4]]),
137137
global_id)
138138

139139

@@ -417,7 +417,7 @@ def Stop():
417417
global_options.stdlog.write(
418418
"######### Time spent in benchmarked functions ###################\n")
419419
global_options.stdlog.write("# function\tseconds\tpercent\n")
420-
for key, value in global_benchmark.items():
420+
for key, value in list(global_benchmark.items()):
421421
global_options.stdlog.write(
422422
"# %s\t%6i\t%5.2f%%\n" % (key, value, (100.0 * float(value) / t)))
423423
global_options.stdlog.write(
@@ -452,8 +452,8 @@ def Stop():
452452
"host", "system", "release", "machine",
453453
"start", "end", "path", "cmd")) + "\n")
454454

455-
csystem, host, release, version, machine = map(str, os.uname())
456-
uusr, usys, c_usr, c_sys = map(lambda x: "%5.2f" % x, os.times()[:4])
455+
csystem, host, release, version, machine = list(map(str, os.uname()))
456+
uusr, usys, c_usr, c_sys = ["%5.2f" % x for x in os.times()[:4]]
457457
t_end = time.time()
458458
c_wall = "%5.2f" % (t_end - global_starting_time)
459459

@@ -483,7 +483,7 @@ def wrapper(*arg):
483483
t1 = time.time()
484484
res = func(*arg)
485485
t2 = time.time()
486-
key = "%s:%i" % (func.func_name, func.func_code.co_firstlineno)
486+
key = "%s:%i" % (func.__name__, func.__code__.co_firstlineno)
487487
global_benchmark[key] += t2 - t1
488488
global_options.stdlog.write(
489489
'## benchmark: %s completed in %6.4f s\n' % (key, (t2 - t1)))
@@ -620,18 +620,18 @@ def __setattr__(self, name, value):
620620
self._counts[name] = value
621621

622622
def __str__(self):
623-
return ", ".join("%s=%i" % x for x in self._counts.iteritems())
623+
return ", ".join("%s=%i" % x for x in self._counts.items())
624624

625625
def __iadd__(self, other):
626626
try:
627-
for key, val in other.iteritems():
627+
for key, val in other.items():
628628
self._counts[key] += val
629629
except:
630630
raise TypeError("unknown type")
631631
return self
632632

633633
def iteritems(self):
634-
return self._counts.iteritems()
634+
return iter(self._counts.items())
635635

636636

637637
def run(cmd):

gat/IO.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,7 @@ def outputMetrics(outfile, segments, workspace, track, section):
431431
.'''
432432

433433
stats_per_isochore = []
434-
for isochore, ss in segments.iteritems():
434+
for isochore, ss in segments.items():
435435
stats = SegmentsSummary()
436436
stats.update(ss, workspace[isochore])
437437
stats_per_isochore.append(stats)

gat/IOTools.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ def readMultiMap(infile,
200200
try:
201201
key = map_functions[0](d[columns[0]])
202202
val = map_functions[1](d[columns[1]])
203-
except (ValueError, IndexError), msg:
203+
except (ValueError, IndexError) as msg:
204204
raise ValueError("parsing error in line %s: %s" % (l[:-1], msg))
205205

206206
if key not in m:
@@ -235,20 +235,20 @@ def readTable(file,
235235
236236
"""
237237

238-
lines = filter(lambda x: x[0] != "#", file.readlines())
238+
lines = [x for x in file.readlines() if x[0] != "#"]
239239

240240
if len(lines) == 0:
241241
return None, []
242242

243243
if take == "all":
244244
num_cols = len(string.split(lines[0][:-1], "\t"))
245-
take = range(0, num_cols)
245+
take = list(range(0, num_cols))
246246
else:
247247
num_cols = len(take)
248248

249249
if headers:
250250
headers = lines[0][:-1].split("\t")
251-
headers = map(lambda x: headers[x], take)
251+
headers = [headers[x] for x in take]
252252
del lines[0]
253253

254254
num_rows = len(lines)
@@ -263,7 +263,7 @@ def readTable(file,
263263
max_data = None
264264
for l in lines:
265265
data = l[:-1].split("\t")
266-
data = map(lambda x: data[x], take)
266+
data = [data[x] for x in take]
267267

268268
# try conversion. Unparseable fields set to missing_value
269269
for x in range(len(data)):
@@ -328,10 +328,10 @@ def getInvertedDictionary(dict, make_unique=False):
328328
"""
329329
inv = {}
330330
if make_unique:
331-
for k, v in dict.iteritems():
331+
for k, v in dict.items():
332332
inv[v] = k
333333
else:
334-
for k, v in dict.iteritems():
334+
for k, v in dict.items():
335335
inv.setdefault(v, []).append(k)
336336
return inv
337337

@@ -440,28 +440,28 @@ def __init__(self,
440440

441441
def __del__(self):
442442
"""close all open files."""
443-
for file in self.mFiles.values():
443+
for file in list(self.mFiles.values()):
444444
file.close()
445445

446446
def __len__(self):
447447
return len(self.mCounts)
448448

449449
def close(self):
450450
"""close all open files."""
451-
for file in self.mFiles.values():
451+
for file in list(self.mFiles.values()):
452452
file.close()
453453

454454
def values(self):
455-
return self.mCounts.values()
455+
return list(self.mCounts.values())
456456

457457
def keys(self):
458-
return self.mCounts.keys()
458+
return list(self.mCounts.keys())
459459

460460
def iteritems(self):
461-
return self.mCounts.iteritems()
461+
return iter(self.mCounts.items())
462462

463463
def items(self):
464-
return self.mCounts.items()
464+
return list(self.mCounts.items())
465465

466466
def __iter__(self):
467467
return self.mCounts.__iter__()
@@ -499,7 +499,7 @@ def write(self, identifier, line):
499499
if filename not in self.mFiles:
500500

501501
if self.maxopen and len(self.mFiles) > self.maxopen:
502-
for f in self.mFiles.values():
502+
for f in list(self.mFiles.values()):
503503
f.close()
504504
self.mFiles = {}
505505

@@ -509,7 +509,7 @@ def write(self, identifier, line):
509509

510510
try:
511511
self.mFiles[filename].write(line)
512-
except ValueError, msg:
512+
except ValueError as msg:
513513
raise ValueError(
514514
"error while writing to %s: msg=%s" % (filename, msg))
515515
self.mCounts[filename] += 1
@@ -518,7 +518,7 @@ def deleteFiles(self, min_size=0):
518518
"""delete all files below a minimum size."""
519519

520520
ndeleted = 0
521-
for filename, counts in self.mCounts.items():
521+
for filename, counts in list(self.mCounts.items()):
522522
if counts < min_size:
523523
os.remove(filename)
524524
ndeleted += 1
@@ -554,7 +554,7 @@ def close(self):
554554
if self.isClosed:
555555
raise IOError("write on closed FilePool in close()")
556556

557-
for filename, data in self.data.iteritems():
557+
for filename, data in self.data.items():
558558
f = self.openFile(filename, "a")
559559
if self.mHeader:
560560
f.write(self.mHeader)
@@ -613,7 +613,7 @@ def iterflattened(self):
613613
iterate through values with nested keys flattened into a tuple
614614
"""
615615

616-
for key, value in self.iteritems():
616+
for key, value in self.items():
617617
if isinstance(value, nested_dict):
618618
for keykey, value in value.iterflattened():
619619
yield (key,) + keykey, value

gat/PositionList.pyx

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33

44
cimport cython
55

6-
from cpython cimport PyString_AsString, PyString_FromStringAndSize
6+
from cpython.bytes cimport PyBytes_AsString, PyBytes_FromStringAndSize
7+
from cpython cimport PyBytes_Check, PyUnicode_Check
78
from libc.stdlib cimport qsort, calloc, malloc, realloc, free
89
from libc.string cimport memcpy
910
from libc.errno cimport errno
@@ -15,6 +16,20 @@ from posix.fcntl cimport O_CREAT, O_RDWR, O_RDONLY
1516

1617
from SegmentList cimport Position, Segment, SegmentList
1718

19+
cdef bytes force_bytes(object s, encoding="ascii"):
20+
"""convert string or unicode object to bytes, assuming
21+
ascii encoding.
22+
"""
23+
if s is None:
24+
return None
25+
elif PyBytes_Check(s):
26+
return s
27+
elif PyUnicode_Check(s):
28+
return s.encode(encoding)
29+
else:
30+
raise TypeError("Argument must be string, bytes or unicode.")
31+
32+
1833
# trick to permit const void * in function definitions
1934
cdef extern from *:
2035
ctypedef void * const_void_ptr "const void*"
@@ -142,7 +157,7 @@ cdef class PositionList:
142157
self.is_shared = True
143158
self.is_slave = True
144159
else:
145-
p = PyString_AsString(unreduce[6])
160+
p = PyBytes_AsString(unreduce[6])
146161
self.positions = <Position*>malloc(self.npositions * sizeof(Position))
147162
memcpy(self.positions, p, cython.sizeof(Position) * self.npositions)
148163

@@ -182,7 +197,7 @@ cdef class PositionList:
182197
def __reduce__(self):
183198
'''pickling function - returns class contents as a tuple.'''
184199

185-
cdef str data
200+
cdef bytes data
186201

187202
if self.shared_fd >= 0:
188203
return (buildPositionList, (self.npositions,
@@ -194,7 +209,7 @@ cdef class PositionList:
194209
self.shared_fd))
195210

196211
else:
197-
data = PyString_FromStringAndSize(
212+
data = PyBytes_FromStringAndSize(
198213
<char*>self.positions, \
199214
self.npositions * cython.sizeof(Position) * 2)
200215

gat/SegmentList.pxd

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ cdef extern from "gat_utils.h":
2020
int toCompressedFile(unsigned char *, size_t, FILE *)
2121
int fromCompressedFile(unsigned char *, size_t, FILE *)
2222

23+
cdef bytes force_bytes(object s, encoding=*)
24+
cdef force_str(object s, encoding=*)
25+
2326
#####################################################
2427
#####################################################
2528
## type definitions

gat/SegmentList.pyx

Lines changed: 51 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ import random
66

77
cimport cython
88

9-
from cpython cimport PyString_AsString, PyString_FromStringAndSize
9+
from cpython.version cimport PY_MAJOR_VERSION, PY_MINOR_VERSION
10+
from cpython.bytes cimport PyBytes_AsString, PyBytes_FromStringAndSize
11+
from cpython cimport PyBytes_Check, PyUnicode_Check
1012
from libc.stdlib cimport qsort, realloc, malloc, calloc, free
1113
from libc.stdint cimport UINT32_MAX
1214
from libc.string cimport memcpy, memmove
@@ -19,6 +21,33 @@ from posix.stat cimport S_IRUSR, S_IWUSR
1921
from posix.fcntl cimport O_CREAT, O_RDWR, O_RDONLY
2022
from posix.unistd cimport ftruncate
2123

24+
25+
cdef bytes force_bytes(object s, encoding="ascii"):
26+
"""convert string or unicode object to bytes, assuming
27+
ascii encoding.
28+
"""
29+
if s is None:
30+
return None
31+
elif PyBytes_Check(s):
32+
return s
33+
elif PyUnicode_Check(s):
34+
return s.encode(encoding)
35+
else:
36+
raise TypeError("Argument must be string, bytes or unicode.")
37+
38+
cdef force_str(object s, encoding="ascii"):
39+
"""Return s converted to str type of current Python
40+
(bytes in Py2, unicode in Py3)"""
41+
if s is None:
42+
return None
43+
if PY_MAJOR_VERSION < 3:
44+
return s
45+
elif PyBytes_Check(s):
46+
return s.decode(encoding)
47+
else:
48+
# assume unicode
49+
return s
50+
2251
#####################################################
2352
## numpy import
2453
## both import and cimport are necessary
@@ -249,7 +278,7 @@ cdef class SegmentList:
249278
self.is_shared = True
250279
self.is_slave = True
251280
else:
252-
p = PyString_AsString(unreduce[5])
281+
p = PyBytes_AsString(unreduce[5])
253282
self.segments = <Segment*>malloc(self.nsegments * sizeof(Segment))
254283
memcpy(self.segments, p, cython.sizeof(Position) * 2 * self.nsegments)
255284

@@ -285,7 +314,7 @@ cdef class SegmentList:
285314
def __reduce__(self):
286315
'''pickling function - returns class contents as a tuple.'''
287316

288-
cdef str data
317+
cdef bytes data
289318

290319
if self.shared_fd >= 0:
291320
return (buildSegmentList, (self.nsegments,
@@ -296,7 +325,7 @@ cdef class SegmentList:
296325
self.shared_fd))
297326

298327
else:
299-
data = PyString_FromStringAndSize(
328+
data = PyBytes_FromStringAndSize(
300329
<char*>self.segments, \
301330
self.nsegments * cython.sizeof(Position) * 2)
302331

@@ -324,7 +353,8 @@ cdef class SegmentList:
324353
return
325354

326355
cdef int fd
327-
fd = shm_open( key, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR)
356+
key = force_bytes(key)
357+
fd = shm_open(key, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR)
328358
if fd == -1:
329359
error = errno
330360
raise OSError( "could not create shared memory at %s; ERRNO=%i" % (key, error ))
@@ -1684,18 +1714,29 @@ cdef class SegmentList:
16841714
if key >= self.nsegments:
16851715
raise IndexError("index out of range")
16861716
return self.segments[key].start, self.segments[key].end
1687-
1688-
def __cmp__(self, SegmentList other):
1717+
1718+
def compare(self, SegmentList other):
16891719
cdef int idx
1690-
x = self.__len__().__cmp__(len(other))
1691-
if x != 0:
1692-
return x
1720+
cdef int l1 = self.__len__()
1721+
if other is None:
1722+
return -1
1723+
cdef int l2 = len(other)
1724+
if l2 - l1 != 0:
1725+
return l2 - l1
16931726
for idx from 0 <= idx < self.nsegments:
16941727
x = cmpSegmentsStartAndEnd(&self.segments[idx], &other.segments[idx])
16951728
if x != 0:
16961729
return x
16971730
return 0
16981731

1732+
def __richcmp__(self, SegmentList other, int op):
1733+
if op == 2: # == operator
1734+
return self.compare(other) == 0
1735+
elif op == 3: # != operator
1736+
return self.compare(other) != 0
1737+
else:
1738+
return NotImplemented
1739+
16991740

17001741
def buildSegmentList(*args):
17011742
'''pickling helper function.

0 commit comments

Comments
 (0)