-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
254 lines (193 loc) · 6.11 KB
/
Copy pathutils.py
File metadata and controls
254 lines (193 loc) · 6.11 KB
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
from functools import wraps
from itertools import islice, chain, zip_longest, tee
from collections import deque
import re
import numpy as np
from math import log10, floor
from random import random
def head(it, n):
yield from islice(it, n)
def tail(it, n):
yield from deque(it, maxlen=n)
def cache(args_dict, max_size=128):
'''
Decorator to make a function cache its return values for later calls
'''
def decorator(fun):
@wraps(fun)
def cached_func(*args, **kwargs):
argument_tuple = (tuple(args), tuple(sorted(kwargs.items())))
if argument_tuple in args_dict:
return args_dict[argument_tuple]
else:
return_value = fun(*args, **kwargs)
if max_size >= len(args_dict):
args_dict[argument_tuple] = return_value
return return_value
return cached_func
return decorator
def flatten(iterable):
'''
Takes a iterable of nested iterables and yields each 'atom' in
the nested structure. An atom is a non-iterable or a string.
'''
if not hasattr(iterable, '__iter__') or type(iterable) == str:
yield iterable
return
iterable = iter(iterable)
while 1:
try:
item = next(iterable)
except StopIteration:
break
try:
if type(item) == str:
yield item
else:
data = iter(item)
iterable = chain(data, iterable)
except TypeError:
yield item
def split(delimiter, string):
'''Splits the string on the delimiters.
Like the built-in *split* method, but with extra power.
Args:
delimiter : Regex of characters to split around.
string : The string to split
Returns:
iterable of the pieces
'''
regex = r'[^{}]+'.format(delimiter)
yield from (m.group(0) for m in re.finditer(regex, string))
def split_rows(rows):
'''First splits the string on rows,
then the rows on whitespace.'''
rows = rows.split('\n')
return [[*split(r'\s', row)]
for row in rows]
def chunks(iterable, n, fillvalue=None):
'''Take the items from the iterable in chunks of n.
If the values run out 'fillvalue' will be used instead.'''
it = iter(iterable)
if fillvalue is None:
return zip_longest(*(it for i in range(n)))
return zip_longest(*(it for i in range(n)), fillvalue=fillvalue)
def neighbors(iterable, n):
deq = deque([], maxlen=n)
for item in iterable:
deq.append(item)
if len(deq) < n:
continue
yield tuple(deq)
def unzip(mapping):
return zip(*mapping)
def GroupDict(mapping):
'''Takes a mapping, ((key, value), (key, value) ... )
and returns a dict with the values grouped by key.
Returns:
dict( key : set(value1, value2 ... ) )
'''
dictionary = dict()
for k, v in mapping:
if k in dictionary:
dictionary[k].add(v)
continue
dictionary[k] = {v}
return dictionary
def teemap(key, iterable):
it, itp = tee(iterable)
return map(key, it), itp
def group(iterable, key):
return GroupDict(zip(*teemap(key, iterable)))
def linear_interp(time, values, errors, n=100):
'''Interpolates values between given datapoints'''
if not n:
n = int(time[-1] - time[0])
new_time = np.linspace(time[0], time[-1], n)
new_vals = np.interp(new_time, time, values)
new_errs = np.interp(new_time, time, errors)
return new_time, new_vals, new_errs
def moving_average(a, n=3):
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
def laplacian2d(Z, dx):
'''
Argument should be a 2d numpy array,
returned array has dimensions (n-1)x(k-1)
'''
Ztop = Z[0:-2, 1:-1]
Zleft = Z[1:-1, 0:-2]
Zbottom = Z[2:, 1:-1]
Zright = Z[1:-1, 2:]
Zcenter = Z[1:-1, 1:-1]
return (Ztop + Zleft + Zbottom + Zright - 4 * Zcenter) / dx**2
def sign(a):
if a == 0:
return 1
return a/abs(a)
def itersolve(func, expected, start=0,
step=1, tolerance=0.1, max_iterations=100):
cnt = 1
oldx = start
x = start
olddiff = expected-func(x)
oldsgn = sign(olddiff)
x += step
diff = expected-func(x)
sgn = sign(diff)
while abs(diff) > tolerance:
if abs(diff) > abs(olddiff):
if sgn == oldsgn:
step = -step
else:
step = step/2
x = oldx
else:
if sgn == oldsgn:
pass
else:
step = -step/2
oldx = x
olddiff = diff
oldsgn = sgn
x += step
diff = expected - func(x)
sgn = sign(diff)
cnt += 1
if cnt >= max_iterations:
break
return x, func(x), cnt
def solve(func, expected, interval=(-10, 10), n=100,
tolerance=0.1, give_all=False):
''' Tries itersolve for the expected value on n different places along
the given interval.
Returns:
The successful return values, x and y sorted from best to worst.
Example:
f = lambda x: x**2 + 1
solve(f, 3, tolerance=0.01, interval=(-10, 10))'''
start, stop = interval
step = abs(stop-start)/n
results = []
for k in range(n):
x, y, c = itersolve(
func,
expected,
start=start+step*k,
step=step*random()+step/2,
tolerance=tolerance)
if abs(expected-y) < tolerance:
results.append((x, y))
if give_all:
return sorted(results, key=lambda v: abs(expected-v[1]))
exponent = -log10(tolerance)
if not exponent == floor(exponent):
exponent = floor(exponent+1)
print(int(exponent))
result = GroupDict(map(lambda v: (round(v[0], int(exponent)), v), results))
def aggregate(res):
return sorted(res, key=lambda x: abs(expected-x[1]))[0]
for res in result:
result[res] = aggregate(result[res])
return result.values()