-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
168 lines (129 loc) · 4.2 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""
Utilities.
"""
from math import sqrt
from distarray.externals.six import next
def multi_for(iterables):
if not iterables:
yield ()
else:
for item in iterables[0]:
for rest_tuple in multi_for(iterables[1:]):
yield (item,) + rest_tuple
def divisors_minmax(n, dmin, dmax):
"""Find the divisors of n in the interval (dmin,dmax]."""
i = dmin+1
while i<=dmax:
if n % i == 0:
yield i
i += 1
def list_or_tuple(seq):
return isinstance(seq, (list, tuple))
def flatten(seq, to_expand=list_or_tuple):
"""Flatten a nested sequence."""
for item in seq:
if to_expand(item):
for subitem in flatten(item, to_expand):
yield subitem
else:
yield item
def mult_partitions(n, s):
"""Compute the multiplicative partitions of n of size s
>>> mult_partitions(52,3)
[(2, 2, 13)]
>>> mult_partitions(52,2)
[(2, 26), (4, 13)]
"""
return [tuple(flatten(p)) for p in mult_partitions_recurs(n, s)]
def mult_partitions_recurs(n, s, pd=0):
if s == 1:
return [n]
divs = divisors_minmax(n, pd, int(sqrt(n)))
fs = []
for d in divs:
fs.extend([(d,f) for f in mult_partitions_recurs(n/d, s-1, pd)])
pd = d
return fs
def mirror_sort(seq, ref_seq):
"""Sort `seq` into the order that `ref_seq` is in.
>>> mirror_sort(range(5),[1,5,2,4,3])
[0, 4, 1, 3, 2]
"""
if not len(seq) == len(ref_seq):
raise ValueError("Sequences must have the same length")
shift = list(zip(range(len(ref_seq)), ref_seq))
shift.sort(key=lambda x: x[1])
shift = [s[0] for s in shift]
newseq = len(ref_seq)*[0]
for s_index in range(len(shift)):
newseq[shift[s_index]] = seq[s_index]
return newseq
def _raise_nie():
msg = "This has not yet been implemented for distributed arrays"
raise NotImplementedError(msg)
def sanitize_indices(indices):
"""Check and possibly sanitize indices.
Parameters
----------
indices : int, slice, or sequence of ints and slices
If an int or slice is passed in, it is converted to a
1-tuple.
Returns
-------
2-tuple
('point', indices) if all `indices` are ints, or
('view', indices) if some `indices` are slices.
Raises
------
TypeError
If `indices` is not all ints or slices.
"""
if isinstance(indices, int) or isinstance(indices, slice):
return sanitize_indices((indices,))
elif all(isinstance(i, int) for i in indices):
return 'point', indices
elif all(isinstance(i, int) or isinstance(i, slice) for i in indices):
return 'view', indices
else:
raise TypeError("Index must be a sequence of ints and slices")
def slice_intersection(s1, s2):
"""Compute a slice that represents the intersection of two slices.
Currently only implemented for steps of size 1.
Parameters
----------
s1, s2 : slice objects
Returns
-------
slice object
"""
valid_steps = {None, 1}
if (s1.step in valid_steps) and (s2.step in valid_steps):
step = 1
stop = min(s1.stop, s2.stop)
start = max(s1.start, s2.start)
return slice(start, stop, step)
else:
msg = "Slice intersection only implemented for step=1."
raise NotImplementedError(msg)
def has_exactly_one(iterable):
"""Does `iterable` have exactly one non-None element?"""
test = (x is not None for x in iterable)
if sum(test) == 1:
return True
else:
return False
def all_equal(iterable):
"""Return True if all elements in `iterable` are equal.
Also returns True if iterable is empty.
"""
iterator = iter(iterable)
try:
first = next(iterator)
except StopIteration:
return True # vacuously True
return all(element == first for element in iterator)