forked from ACTCollaboration/enlib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
1536 lines (1402 loc) · 52.8 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
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np, scipy.ndimage, os, errno, scipy.optimize, time, datetime, warnings, re
degree = np.pi/180
arcmin = degree/60
arcsec = arcmin/60
fwhm = 1.0/(8*np.log(2))**0.5
T_cmb = 2.73
c = 299792458.0
h = 6.62606957e-34
k = 1.3806488e-23
def lines(file_or_fname):
"""Iterates over lines in a file, which can be specified
either as a filename or as a file object."""
if isinstance(file_or_fname, basestring):
with open(file_or_fname,"r") as file:
for line in file: yield line
else:
for line in file: yield line
def listsplit(seq, elem):
"""Analogue of str.split for lists.
listsplit([1,2,3,4,5,6,7],4) -> [[1,2],[3,4,5,6]]."""
# Sadly, numpy arrays misbehave, and must be treated specially
def iseq(e1, e2): return np.all(e1==e2)
inds = [i for i,v in enumerate(seq) if iseq(v,elem)]
ranges = zip([0]+[i+1 for i in inds],inds+[len(seq)])
return [seq[a:b] for a,b in ranges]
def find(array, vals):
"""Return the indices of each value of vals in the given array."""
order = np.argsort(array)
return order[np.searchsorted(array, vals, sorter=order)]
def contains(array, vals):
"""Given an array[n], returns a boolean res[n], which is True
for any element in array that is also in vals, and False otherwise."""
array = np.asarray(array)
vals = np.sort(vals)
inds = np.searchsorted(vals, array)
# If a value would be inserted after the end, it wasn't
# present in the original array.
inds[inds>=len(vals)] = 0
return vals[inds] == array
def common_vals(arrs):
"""Given a list of arrays, returns their intersection.
For example
common_vals([[1,2,3,4,5],[2,4,6,8]]) -> [2,4]"""
res = arrs[0]
for arr in arrs[1:]:
res = np.intersect1d(res,arr)
return res
def common_inds(arrs):
"""Given a list of arrays, returns the indices into each of them of
their common elements. For example
common_inds([[1,2,3,4,5],[2,4,6,8]]) -> [[1,3],[0,1]]"""
vals = common_vals(arrs)
return [find(arr, vals) for arr in arrs]
def union(arrs):
"""Given a list of arrays, returns their union."""
res = arrs[0]
for arr in arrs[1:]:
res = np.union1d(res,arr)
return res
def dict_apply_listfun(dict, function):
"""Applies a function that transforms one list to another
with the same number of elements to the values in a dictionary,
returning a new dictionary with the same keys as the input
dictionary, but the values given by the results of the function
acting on the input dictionary's values. I.e.
if f(x) = x[::-1], then dict_apply_listfun({"a":1,"b":2},f) = {"a":2,"b":1}."""
keys = dict.keys()
vals = [dict[key] for key in keys]
res = function(vals)
return {key: res[i] for i, key in enumerate(keys)}
def unwind(a, period=2*np.pi, axes=[-1], ref=0):
"""Given a list of angles or other cyclic coordinates
where a and a+period have the same physical meaning,
make a continuous by removing any sudden jumps due to
period-wrapping. I.e. [0.07,0.02,6.25,6.20] would
become [0.07,0.02,-0.03,-0.08] with the default period
of 2*pi."""
res = rewind(a, period=period, ref=ref)
for axis in axes:
with flatview(res, axes=[axis]) as flat:
# Avoid trying to sum nans
mask = ~np.isfinite(flat)
bad = flat[mask]
flat[mask] = 0
flat[:,1:]-= np.cumsum(np.round((flat[:,1:]-flat[:,:-1])/period),-1)*period
# Restore any nans
flat[mask] = bad
return res
def rewind(a, ref=0, period=2*np.pi):
"""Given a list of angles or other cyclic corodinates,
add or subtract multiples of the period in order to ensure
that they all lie within the same period. The ref argument
specifies the angle furthest away from the cut, i.e. the
period cut will be at ref+period/2."""
a = np.asanyarray(a)
if ref is "auto": ref = np.sort(a.reshape(-1))[a.size/2]
return ref + (a-ref+period/2.)%period - period/2.
def cumsplit(sizes, capacities):
"""Given a set of sizes (of files for example) and a set of capacities
(of disks for example), returns the index of the sizes for which
each new capacity becomes necessary, assuming sizes can be split
across boundaries.
For example cumsplit([1,1,2,0,1,3,1],[3,2,5]) -> [2,5]"""
return np.searchsorted(np.cumsum(sizes),np.cumsum(capacities),side="right")
def mask2range(mask):
"""Convert a binary mask [True,True,False,True,...] into
a set of ranges [:,{start,stop}]."""
# We consider the outside of the array to be False
mask = np.concatenate([[False],mask,[False]]).astype(np.int8)
# Find where we enter and exit ranges with true mask
dmask = mask[1:]-mask[:-1]
start = np.where(dmask>0)[0]
stop = np.where(dmask<0)[0]
return np.array([start,stop]).T
def repeat_filler(d, n):
"""Form an array n elements long by repeatedly concatenating
d and d[::-1]."""
d = np.concatenate([d,d[::-1]])
nmul = (n+d.size-1)/d.size
dtot = np.concatenate([d]*nmul)
return dtot[:n]
def deslope(d, w=1, inplace=False, axis=-1):
"""Remove a slope and mean from d, matching up the beginning
and end of d. The w parameter controls the number of samples
from each end of d that is used to determine the value to
match up."""
if not inplace: d = np.array(d)
with flatview(d, axes=[axis]) as dflat:
for di in dflat:
di -= np.arange(di.size)*(np.mean(di[-w:])-np.mean(di[:w]))/(di.size-1)+np.mean(di[:w])
return d
def ctime2mjd(ctime):
"""Converts from unix time to modified julian date."""
return np.asarray(ctime)/86400. + 40587.0
def mjd2ctime(mjd):
"""Converts from modified julian date to unix time."""
return (np.asarray(mjd)-40587.0)*86400
day2sec = 86400.
def mjd2ctime(mjd):
"""Converts from modified julian date to unix time"""
return (np.asarray(mjd)-40587.0)*86400
def medmean(x, frac=0.5):
x = np.sort(x)
i = int(x.size*frac)/2
return np.mean(x[i:-i])
def moveaxis(a, o, n):
if o < 0: o = o+a.ndim
if n < 0: n = n+a.ndim
if n <= o: return np.rollaxis(a, o, n)
else: return np.rollaxis(a, o, n+1)
def moveaxes(a, old, new):
"""Move the axes listed in old to the positions given
by new. This is like repeated calls to numpy rollaxis
while taking into account the effect of previous rolls.
This version is slow but simple and safe. It moves
all axes to be moved to the end, and then moves them
one by one to the target location."""
# The final moves will happen in left-to-right order.
# Hence, the first moves must be in the reverse of
# this order.
n = len(old)
old = np.asarray(old)
order = np.argsort(new)
rold = old[order[::-1]]
for i in range(n):
a = moveaxis(a, rold[i], -1)
# This may have moved some of the olds we're going to
# move next, so update these
for j in range(i+1,n):
if rold[j] > rold[i]: rold[j] -= 1
# Then do the final moves
for i in range(n):
a = moveaxis(a, -1, new[order[i]])
return a
def partial_flatten(a, axes=[-1], pos=0):
"""Flatten all dimensions of a except those mentioned
in axes, and put the flattened one at the given position.
Example: if a.shape is [1,2,3,4],
then partial_flatten(a,[-1],0).shape is [6,4]."""
# Move the selected axes first
a = moveaxes(a, axes, range(len(axes)))
# Flatten all the other axes
a = a.reshape(a.shape[:len(axes)]+(-1,))
# Move flattened axis to the target position
return moveaxis(a, -1, pos)
def partial_expand(a, shape, axes=[-1], pos=0):
"""Undo a partial flatten. Shape is the shape of the
original array before flattening, and axes and pos should be
the same as those passed to the flatten operation."""
a = moveaxis(a, pos, -1)
axes = np.array(axes)%len(shape)
rest = list(np.delete(shape, axes))
a = np.reshape(a, list(a.shape[:len(axes)])+rest)
return moveaxes(a, range(len(axes)), axes)
def addaxes(a, axes):
axes = np.array(axes)
axes[axes<0] += a.ndim
axes = np.sort(axes)[::-1]
inds = [slice(None) for i in a.shape]
for ax in axes: inds.insert(ax, None)
return a[inds]
def delaxes(a, axes):
axes = np.array(axes)
axes[axes<0] += a.ndim
axes = np.sort(axes)[::-1]
inds = [slice(None) for i in a.shape]
for ax in axes: inds[ax] = 0
return a[inds]
class flatview:
"""Produce a read/writable flattened view of the given array,
via with flatview(arr) as farr:
do stuff with farr
Changes to farr are propagated into the original array.
Flattens all dimensions of a except those mentioned
in axes, and put the flattened one at the given position."""
def __init__(self, array, axes=[], mode="rwc", pos=0):
self.array = array
self.axes = axes
self.flat = None
self.mode = mode
self.pos = pos
def __enter__(self):
self.flat = partial_flatten(self.array, self.axes, pos=self.pos)
if "c" in self.mode:
self.flat = np.ascontiguousarray(self.flat)
return self.flat
def __exit__(self, type, value, traceback):
# Copy back out from flat into the original array, if necessary
if "w" not in self.mode: return
if np.may_share_memory(self.array, self.flat): return
# We need to copy back out
self.array[:] = partial_expand(self.flat, self.array.shape, self.axes, pos=self.pos)
class nowarn:
"""Use in with block to suppress warnings inside that block."""
def __enter__(self):
self.filters = list(warnings.filters)
warnings.filterwarnings("ignore")
return self
def __exit__(self, type, value, traceback):
warnings.filters = self.filters
def dedup(a):
"""Removes consecutive equal values from a 1d array, returning the result.
The original is not modified."""
return a[np.concatenate([[True],a[1:]!=a[:-1]])]
def interpol(a, inds, order=3, mode="nearest", mask_nan=True, cval=0.0, prefilter=True):
"""Given an array a[{x},{y}] and a list of float indices into a,
inds[len(y),{z}], returns interpolated values at these positions as [{x},{z}]."""
a = np.asanyarray(a)
inds = np.asanyarray(inds)
inds_orig_nd = inds.ndim
if inds.ndim == 1: inds = inds[:,None]
npre = a.ndim - inds.shape[0]
res = np.empty(a.shape[:npre]+inds.shape[1:],dtype=a.dtype)
fa, fr = partial_flatten(a, range(npre,a.ndim)), partial_flatten(res, range(npre, res.ndim))
if mask_nan:
mask = ~np.isfinite(fa)
fa[mask] = 0
for i in range(fa.shape[0]):
fr[i].real = scipy.ndimage.map_coordinates(fa[i].real, inds, order=order, mode=mode, cval=cval, prefilter=prefilter)
if np.iscomplexobj(fa[i]):
fr[i].imag = scipy.ndimage.map_coordinates(fa[i].imag, inds, order=order, mode=mode, cval=cval, prefilter=prefilter)
if mask_nan and np.sum(mask) > 0:
fmask = np.empty(fr.shape,dtype=bool)
for i in range(mask.shape[0]):
fmask[i] = scipy.ndimage.map_coordinates(mask[i], inds, order=0, mode=mode, cval=cval, prefilter=prefilter)
fr[fmask] = np.nan
if inds_orig_nd == 1: res = res[...,0]
return res
def interpol_prefilter(a, npre=None, order=3, inplace=False):
a = np.asanyarray(a)
if not inplace: a = a.copy()
if npre is None: npre = a.ndim - 2
with flatview(a, range(npre, a.ndim), "rw") as aflat:
for i in range(len(aflat)):
aflat[i] = scipy.ndimage.spline_filter(aflat[i], order=order)
return a
def bin_multi(pix, shape, weights=None):
"""Simple multidimensional binning. Not very fast.
Given pix[{coords},:] where coords are indices into an array
with shape shape, count the number of hits in each pixel,
returning map[shape]."""
pix = np.maximum(np.minimum(pix, (np.array(shape)-1)[:,None]),0)
inds = np.ravel_multi_index(tuple(pix), tuple(shape))
size = np.product(shape)
if weights is not None: weights = inds*0+weights
return np.bincount(inds, weights=weights, minlength=size).reshape(shape)
def grid(box, shape, endpoint=True, axis=0, flat=False):
"""Given a bounding box[{from,to},ndim] and shape[ndim] in each
direction, returns an array [ndim,shape[0],shape[1],...] array
of evenly spaced numbers. If endpoint is True (default), then
the end point is included. Otherwise, the last sample is one
step away from the end of the box. For one dimension, this is
similar to linspace:
linspace(0,1,4) => [0.0000, 0.3333, 0.6667, 1.0000]
grid([[0],[1]],[4]) => [[0,0000, 0.3333, 0.6667, 1.0000]]
"""
n = np.asarray(shape)
box = np.asfarray(box)
off = -1 if endpoint else 0
inds = np.rollaxis(np.indices(n),0,len(n)+1) # (d1,d2,d3,...,indim)
res = inds * (box[1]-box[0])/(n+off) + box[0]
if flat: res = res.reshape(-1, res.shape[-1])
return np.rollaxis(res, -1, axis)
def cumsum(a, endpoint=False):
"""As numpy.cumsum for a 1d array a, but starts from 0. If endpoint is True, the result
will have one more element than the input, and the last element will be the sum of the
array. Otherwise (the default), it will have the same length as the array, and the last
element will be the sum of the first n-1 elements."""
res = np.concatenate([[0],np.cumsum(a)])
return res if endpoint else res[:-1]
def nearest_product(n, factors, direction="below"):
"""Compute the highest product of positive integer powers of the specified
factors that is lower than or equal to n. This is done using a simple,
O(n) brute-force algorithm."""
if 1 in factors: return n
below = direction=="below"
nmax = n+1 if below else n*min(factors)+1
a = np.zeros(nmax+1,dtype=bool)
a[1] = True
best = 1
for i in xrange(n+1):
if not a[i]: continue
for f in factors:
m = i*f
if below:
if m > n: continue
else:
if m >= n: return m
a[m] = True
best = m
return best
def mkdir(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
def decomp_basis(basis, vec):
return np.linalg.solve(basis.dot(basis.T),basis.dot(vec.T)).T
def find_period(d, axis=-1):
dwork = partial_flatten(d, [axis])
guess = find_period_fourier(dwork)
res = np.empty([3,len(dwork)])
for i, (d1, g1) in enumerate(zip(dwork, guess)):
res[:,i] = find_period_exact(d1, g1)
periods = res[0].reshape(d.shape[:axis]+d.shape[axis:][1:])
phases = res[1].reshape(d.shape[:axis]+d.shape[axis:][1:])
chisqs = res[2].reshape(d.shape[:axis]+d.shape[axis:][1:])
return periods, phases, chisqs
def find_period_fourier(d, axis=-1):
"""This is a simple second-order estimate of the period of the
assumed-periodic signal d. It finds the frequency with the highest
power using an fft, and partially compensates for nonperiodicity
by taking a weighted mean of the position of the top."""
d2 = partial_flatten(d, [axis])
fd = np.fft.rfft(d2)
ps = np.abs(fd)**2
ps[:,0] = 0
periods = []
for p in ps:
n = np.argmax(p)
r = [int(n*0.5),int(n*1.5)+1]
denom = np.sum(p[r[0]:r[1]])
if denom <= 0: denom = 1
n2 = np.sum(np.arange(r[0],r[1])*p[r[0]:r[1]])/denom
periods.append(float(d.shape[axis])/n2)
return np.array(periods).reshape(d.shape[:axis]+d.shape[axis:][1:])
def find_period_exact(d, guess):
n = d.size
# Restrict to at most 10 fiducial periods
n = int(min(10,n/float(guess))*guess)
off = (d.size-n)/2
d = d[off:off+n]
def chisq(x):
w,phase = x
model = interpol(d, np.arange(n)[None]%w+phase, order=1)
return np.var(d-model)
period,phase = scipy.optimize.fmin_powell(chisq, [guess,guess], xtol=1, disp=False)
return period, phase+off, chisq([period,phase])/np.var(d**2)
def equal_split(weights, nbin):
"""Split weights into nbin bins such that the total
weight in each bin is as close to equal as possible.
Returns a list of indices for each bin."""
inds = np.argsort(weights)[::-1]
bins = [[] for b in xrange(nbin)]
bw = np.zeros([nbin])
for i in inds:
j = np.argmin(bw)
bins[j].append(i)
bw[j] += weights[i]
return bins
def range_sub(a,b, mapping=False):
"""Given a set of ranges a[:,{from,to}] and b[:,{from,to}],
return a new set of ranges c[:,{from,to}] which corresponds to
the ranges in a with those in b removed. This might split individual
ranges into multiple ones. If mapping=True, two extra objects are
returned. The first is a mapping from each output range to the
position in a it comes from. The second is a corresponding mapping
from the set of cut a and b range to indices into a and b, with
b indices being encoded as -i-1. a and b are assumed
to be internally non-overlapping.
Example: utils.range_sub([[0,100],[200,1000]], [[1,2],[3,4],[8,999]], mapping=True)
(array([[ 0, 1],
[ 2, 3],
[ 4, 8],
[ 999, 1000]]),
array([0, 0, 0, 1]),
array([ 0, -1, 1, -2, 2, -3, 3]))
The last array can be interpreted as: Moving along the number line,
we first encounter [0,1], which is a part of range 0 in c. We then
encounter range 0 in b ([1,2]), before we hit [2,3] which is
part of range 1 in c. Then comes range 1 in b ([3,4]) followed by
[4,8] which is part of range 2 in c, followed by range 2 in b
([8,999]) and finally [999,1000] which is part of range 3 in c.
The same call without mapping: utils.range_sub([[0,100],[200,1000]], [[1,2],[3,4],[8,999]])
array([[ 0, 1],
[ 2, 3],
[ 4, 8],
[ 999, 1000]])
"""
def fixshape(a):
a = np.asarray(a)
if a.size == 0: a = np.zeros([0,2],dtype=int)
return a
a = fixshape(a)
b = fixshape(b)
ainds = np.argsort(a[:,0])
binds = np.argsort(b[:,0])
rainds= np.arange(len(a))[ainds]
rbinds= np.arange(len(b))[binds]
a = a[ainds]
b = b[binds]
ai,bi = 0,0
c = []
abmap = []
rmap = []
while ai < len(a):
# Iterate b until it ends past the start of a
while bi < len(b) and b[bi,1] <= a[ai,0]:
abmap.append(-rbinds[bi]-1)
bi += 1
# Now handle each b until the start of b is past the end of a
pstart = a[ai,0]
while bi < len(b) and b[bi,0] <= a[ai,1]:
r=(pstart,min(a[ai,1],b[bi,0]))
if r[1]-r[0] > 0:
abmap.append(len(c))
rmap.append(rainds[ai])
c.append(r)
abmap.append(-rbinds[bi]-1)
pstart = b[bi,1]
bi += 1
# Then append what remains
r=(pstart,a[ai,1])
if r[1]>r[0]:
abmap.append(len(c))
rmap.append(rainds[ai])
c.append(r)
else:
# If b extended beyond the end of a, then
# we need to consider it again for the next a,
# so undo the previous increment. This may lead to
# the same b being added twice. We will handle that
# by removing duplicates at the end.
bi -= 1
# And advance to the next range in a
ai += 1
c = np.array(c)
# Remove duplicates if necessary
abmap=dedup(np.array(abmap))
rmap = np.array(rmap)
return (c, rmap, abmap) if mapping else c
def range_union(a, mapping=False):
"""Given a set of ranges a[:,{from,to}], return a new set where all
overlapping ranges have been merged, where to >= from. If mapping=True,
then the mapping from old to new ranges is also returned."""
# We will make a single pass through a in sorted order
a = np.asarray(a)
n = len(a)
inds = np.argsort(a[:,0])
rmap = np.zeros(n,dtype=int)-1
b = []
# i will point at the first unprocessed range
for i in xrange(n):
if rmap[inds[i]] >= 0: continue
rmap[inds[i]] = len(b)
start, end = a[inds[i]]
# loop through every unprocessed range in range
for j in xrange(i+1,n):
if rmap[inds[j]] >= 0: continue
if a[inds[j],0] > end: break
# This range overlaps, so register it and merge
rmap[inds[j]] = len(b)
end = max(end, a[inds[j],1])
b.append([start,end])
b = np.array(b)
if b.size == 0: b = b.reshape(0,2)
return (b,rmap) if mapping else b
def range_normalize(a):
"""Given a set of ranges a[:,{from,to}], normalize the ranges
such that no ranges are empty, and all ranges go in increasing
order. Decreasing ranges are interpreted the same way as in a slice,
e.g. empty."""
a = np.asarray(a)
n1 = len(a)
a = a[a[:,1]!=a[:,0]]
reverse = a[:,1]<a[:,0]
a = a[~reverse]
n2 = len(a)
return a
def range_cut(a, c):
"""Cut range list a at positions given by c. For example
range_cut([[0,10],[20,100]],[0,2,7,30,200]) -> [[0,2],[2,7],[7,10],[20,30],[30,100]]."""
return range_sub(a,np.dstack([c,c])[0])
def compress_beam(sigma, phi):
sigma = np.asarray(sigma,dtype=float)
c,s=np.cos(phi),np.sin(phi)
R = np.array([[c,-s],[s,c]])
C = np.diag(sigma**-2)
C = R.dot(C).dot(R.T)
return np.array([C[0,0],C[1,1],C[0,1]])
def expand_beam(irads, return_V=False):
C = np.array([[irads[0],irads[2]],[irads[2],irads[1]]])
E, V = np.linalg.eigh(C)
phi = np.arctan2(V[1,0],V[0,0])
sigma = E**-0.5
if sigma[1] > sigma[0]:
sigma = sigma[::-1]
phi += np.pi/2
phi %= np.pi
if return_V: return sigma, phi, V
else: return sigma, phi
def combine_beams(irads_array):
Cs = np.array([[[ir[0],ir[2]],[ir[2],ir[1]]] for ir in irads_array])
Ctot = np.eye(2)
for C in Cs:
E, V = np.linalg.eigh(C)
B = (V*E[None]**0.5).dot(V.T)
Ctot = B.dot(Ctot).dot(B.T)
return np.array([Ctot[0,0],Ctot[1,1],Ctot[0,1]])
def read_lines(fname, col=0):
"""Read lines from file fname, returning them as a list of strings.
If fname ends with :slice, then the specified slice will be applied
to the list before returning."""
toks = fname.split(":")
fname, fslice = toks[0], ":".join(toks[1:])
lines = [line.split()[col] for line in open(fname,"r") if line[0] != "#"]
n = len(lines)
return eval("lines"+fslice)
def loadtxt(fname):
"""As numpy.loadtxt, but allows slice syntax."""
toks = fname.split(":")
fname, fslice = toks[0], ":".join(toks[1:])
a = np.loadtxt(fname)
return eval("a"+fslice)
def atleast_3d(a):
a = np.asanyarray(a)
if a.ndim == 0: return a.reshape(1,1,1)
elif a.ndim == 1: return a.reshape(1,1,-1)
elif a.ndim == 2: return a.reshape((1,)+a.shape)
else: return a
def to_Nd(a, n, return_inverse=False):
a = np.asanyarray(a)
if n >= a.ndim:
res = a.reshape((1,)*(n-a.ndim)+a.shape)
else:
res = a.reshape((-1,)+a.shape[1:])
return (res, a.shape) if return_inverse else res
def between_angles(a, range, period=2*np.pi):
a = rewind(a, np.mean(range), period=period)
return (a>=range[0])&(a<range[1])
def greedy_split(data, n=2, costfun=max, workfun=lambda w,x: x if w is None else x+w):
"""Given a list of elements data, return indices that would
split them it into n subsets such that cost is approximately
minimized. costfun specifies which cost to minimize, with
the default being the value of the data themselves. workfun
specifies how to combine multiple values. workfun(datum,workval)
=> workval. scorefun then operates on a list of the total workval
for each group score = scorefun([workval,workval,....]).
Example: greedy_split(range(10)) => [[9,6,5,2,1,0],[8,7,4,3]]
greedy_split([1,10,100]) => [[2],[1,0]]
greedy_split("012345",costfun=lambda x:sum([xi**2 for xi in x]),
workfun=lambda w,x:0 if x is None else int(x)+w)
=> [[5,2,1,0],[4,3]]
"""
# Sort data based on standalone costs
costs = []
nowork = workfun(None,None)
work = [nowork for i in xrange(n)]
for d in data:
work[0] = workfun(nowork,d)
costs.append(costfun(work))
order = np.argsort(costs)[::-1]
# Build groups using greedy algorithm
groups = [[] for i in xrange(n)]
work = [nowork for i in xrange(n)]
cost = costfun(work)
for di in order:
d = data[di]
# Try adding to each group
for i in xrange(n):
iwork = workfun(work[i],d)
icost = costfun(work[:i]+[iwork]+work[i+1:])
if i == 0 or icost < best[2]: best = (i,iwork,icost)
# Add it to the best group
i, iwork, icost = best
groups[i].append(di)
work[i] = iwork
cost = icost
return groups, cost, work
def cov2corr(C):
"""Scale rows and columns of C such that its diagonal becomes one.
This produces a correlation matrix from a covariance matrix. Returns
the scaled matrix and the square root of the original diagonal."""
std = np.diag(C)**0.5
istd = 1/std
return np.einsum("ij,i,j->ij",C,istd,istd), std
def corr2cov(corr,std):
"""Given a matrix "corr" and an array "std", return a version
of corr with each row and column scaled by the corresponding entry
in std. This is the reverse of cov2corr."""
return np.einsum("ij,i,j->ij",corr,std,std)
def eigsort(A, nmax=None, merged=False):
"""Return the eigenvalue decomposition of the real, symmetric matrix A.
The eigenvalues will be sorted from largest to smallest. If nmax is
specified, only the nmax largest eigenvalues (and corresponding vectors)
will be returned. If merged is specified, E and V will not be returned
separately. Instead, Q=VE**0.5 will be returned, such that QQ' = VEV'."""
E,V = np.linalg.eigh(A)
inds = np.argsort(E)[::-1][:nmax]
if merged: return V[:,inds]*E[inds][None]**0.5
else: return E[inds],V[:,inds]
def nodiag(A):
"""Returns matrix A with its diagonal set to zero."""
A = np.array(A)
np.fill_diagonal(A,0)
return A
def date2ctime(dstr):
import dateutil.parser
d = dateutil.parser.parse(dstr, ignoretz=True, tzinfos=0)
return time.mktime(d.timetuple())
def bounding_box(boxes):
"""Compute bounding box for a set of boxes [:,2,:], or a
set of points [:,2]"""
boxes = np.asarray(boxes)
if boxes.ndim == 2:
return np.array([np.min(boxes,0),np.max(boxes,0)])
else:
return np.array([np.min(boxes[:,0,:],0),np.max(boxes[:,1,:],0)])
def unpackbits(a): return np.unpackbits(np.atleast_1d(a).view(np.uint8)[::-1])[::-1]
def box2corners(box):
"""Given a [{from,to},:] bounding box, returns [ncorner,:] coordinates
of of all its corners."""
box = np.asarray(box)
ndim= box.shape[1]
return np.array([[box[b,bi] for bi,b in enumerate(unpackbits(i)[:ndim])] for i in range(2**ndim)])
def box2contour(box, nperedge=5):
"""Given a [{from,to},:] bounding box, returns [npoint,:] coordinates
definiting its edges. Nperedge is the number of samples per edge of
the box to use. For nperedge=2 this is equal to box2corners. Nperegege
can be a list, in which case the number indicates the number to use in
each dimension."""
box = np.asarray(box)
ndim = box.shape[1]
nperedge = np.zeros(ndim,int)+nperedge
# Generate the range of each coordinate
points = []
for i in range(ndim):
x = np.linspace(box[0,i],box[1,i],nperedge[i])
for j in range(2**ndim):
bits = unpackbits(j)[:ndim]
if bits[i]: continue
y = np.zeros((len(x),ndim))
y[:] = box[bits,np.arange(ndim)]; y[:,i] = x
points.append(y)
return np.concatenate(points,0)
def box_slice(a, b):
"""Given two boxes/boxarrays of shape [{from,to},dims] or [:,{from,to},dims],
compute the bounds of the part of each b that overlaps with each a, relative
to the corner of a. For example box_slice([[2,5],[10,10]],[[0,0],[5,7]]) ->
[[0,0],[3,2]]."""
a = np.asarray(a)
b = np.asarray(b)
fa = a.reshape(-1,2,a.shape[-1])
fb = b.reshape(-1,2,b.shape[-1])
s = np.minimum(np.maximum(0,fb[None,:]-fa[:,None,0,None]),fa[:,None,1,None]-fa[:,None,0,None])
return s.reshape(a.shape[:-2]+b.shape[:-2]+(2,2))
def box_area(a):
"""Compute the area of a [{from,to},ndim] box, or an array of such boxes."""
return np.abs(np.product(a[...,1,:]-a[...,0,:],-1))
def box_overlap(a, b):
"""Given two boxes/boxarrays, compute the overlap of each box with each other
box, returning the area of the overlaps. If a is [2,ndim] and b is [2,ndim], the
result will be a single number. if a is [n,2,ndim] and b is [2,ndim], the result
will be a shape [n] array. If a is [n,2,ndim] and b is [m,2,ndim], the result will'
be [n,m] areas."""
return box_area(box_slice(a,b))
def widen_box(box, margin=1e-3, relative=True):
box = np.asarray(box)
margin = np.zeros(box.shape[1:])+margin
if relative: margin = (box[1]-box[0])*margin
margin = np.asarray(margin) # Support 1d case
margin[box[0]>box[1]] *= -1
return np.array([box[0]-margin/2, box[1]+margin/2])
def unwrap_range(range, nwrap=2*np.pi):
"""Given a logically ordered range[{from,to},...] that
may have been exposed to wrapping with period nwrap,
undo the wrapping so that range[1] > range[0]
but range[1]-range[0] is as small as possible.
Also makes the range straddle 0 if possible.
Unlike unwind and rewind, this function will not
turn a very wide range into a small one because it
doesn't assume that ranges are shorter than half the
sky. But it still shortens ranges that are longer than
a whole wrapping period."""
range = np.asanyarray(range)
range[1] -= np.floor((range[1]-range[0])/nwrap)*nwrap
range -= np.floor(range[1,None]/nwrap)*nwrap
return range
def sum_by_id(a, ids, axis=0):
ra = moveaxis(a, axis, 0)
fa = ra.reshape(ra.shape[0],-1)
fb = np.zeros((np.max(ids)+1,fa.shape[1]),fa.dtype)
for i,id in enumerate(ids):
fb[id] += fa[i]
rb = fb.reshape((fb.shape[0],)+ra.shape[1:])
return moveaxis(rb, 0, axis)
def pole_wrap(pos):
"""Given pos[{lat,lon},...], normalize coordinates so that
lat is always between -pi/2 and pi/2. Coordinates outside this
range are mirrored around the poles, and for each mirroring a phase
of pi is added to lon."""
pos = pos.copy()
lat, lon = pos # references to columns of pos
halforbit = np.floor((lat+np.pi/2)/np.pi).astype(int)
front = halforbit % 2 == 0
back = ~front
# Get rid of most of the looping
lat -= np.pi*halforbit
# Then handle the "backside" of the sky, where lat is between pi/2 and 3pi/2
lat[back] = -lat[back]
lon[back]+= np.pi
return pos
def allreduce(a, comm, op=None):
"""Convenience wrapper for Allreduce that returns the result
rather than needing an output argument."""
res = a.copy()
if op is None: comm.Allreduce(a, res)
else: comm.Allreduce(a, res, op)
return res
def allgather(a, comm):
"""Convenience wrapper for Allgather that returns the result
rather than needing an output argument."""
a = np.asarray(a)
res = np.zeros((comm.size,)+a.shape,dtype=a.dtype)
if np.issubdtype(a.dtype, str):
comm.Allgather(a.view(dtype=np.uint8), res.view(dtype=np.uint8))
else:
comm.Allgather(a, res)
return res
def allgatherv(a, comm, axis=0):
"""Perform an mpi allgatherv along the specified axis of the array
a, returning an array with the individual process arrays concatenated
along that dimension. For example gatherv([[1,2]],comm) on one task
and gatherv([[3,4],[5,6]],comm) on another task results in
[[1,2],[3,4],[5,6]] for both tasks."""
a = np.asarray(a)
fa = moveaxis(a, axis, 0)
# mpi4py doesn't handle all types. But why not just do this
# for everything?
must_fix = np.issubdtype(a.dtype, str) or a.dtype == bool
if must_fix:
fa = fa.view(dtype=np.uint8)
ra = fa.reshape(fa.shape[0],-1) if fa.size > 0 else fa.reshape(0,np.product(fa.shape[1:],dtype=int))
N = ra.shape[1]
n = allgather([len(ra)],comm)
o = cumsum(n)
rb = np.zeros((np.sum(n),N),dtype=ra.dtype)
comm.Allgatherv(ra, (rb, (n*N,o*N)))
fb = rb.reshape((rb.shape[0],)+fa.shape[1:])
# Restore original data type
if must_fix:
fb = fb.view(dtype=a.dtype)
return moveaxis(fb, 0, axis)
def send(a, comm, dest=0, tag=0):
"""Faster version of comm.send for numpy arrays.
Avoids slow pickling. Used with recv below."""
a = np.asanyarray(a)
comm.send((a.shape,a.dtype), dest=dest, tag=tag)
comm.Send(a, dest=dest, tag=tag)
def recv(comm, source=0, tag=0):
"""Faster version of comm.recv for numpy arrays.
Avoids slow pickling. Used with send above."""
shape, dtype = comm.recv(source=source, tag=tag)
res = np.empty(shape, dtype)
comm.Recv(res, source=source, tag=tag)
return res
def tuplify(a):
try: return tuple(a)
except TypeError: return (a,)
def resize_array(arr, size, axis=None, val=0):
"""Return a new array equal to arr but with the given
axis reshaped to the given sizes. Inserted elements will
be set to val."""
arr = np.asarray(arr)
size = tuplify(size)
axis = range(len(size)) if axis is None else tuplify(axis)
axis = [a%arr.ndim for a in axis]
oshape = np.array(arr.shape)
oshape[np.array(axis)] = size
res = np.full(oshape, val, arr.dtype)
slices = tuple([slice(0,min(s1,s2)) for s1,s2 in zip(arr.shape,res.shape)])
res[slices] = arr[slices]
return res
def redistribute(iarrs, iboxes, oboxes, comm, wrap=0):
"""Given the array iarrs[[{pre},{dims}]] which represents slices
garr[...,narr,ibox[0,0]:ibox[0,1]:ibox[0,2],ibox[1,0]:ibox[1,1]:ibox[1,2],etc]
of some larger, distributed array garr, returns a different
slice of the global array given by obox."""
iarrs = [np.asanyarray(iarr) for iarr in iarrs]
iboxes = sbox_fix(iboxes)
oboxes = sbox_fix(oboxes)
ndim = iboxes[0].shape[-2]
dtype = iarrs[0].dtype
preshape = iarrs[0].shape[:-2]
oshapes= [tuple(sbox_size(b)) for b in oboxes]
oarrs = [np.zeros(preshape+oshape,dtype) for oshape in oshapes]
presize= np.product(preshape,dtype=int)
# Find out what we must send to and receive from each other task.
# rboxes will contain slices into oarr and sboxes into iarr.
# Due to wrapping, a single pair of boxes can have multiple intersections,
# so we may need to send multiple arrays to each other task.
# We handle this by flattening and concatenating into a single buffer.
# sbox_intersect must return a list of lists of boxes
niarrs = allgather(len(iboxes), comm)
nimap = [i for i,a in enumerate(niarrs) for j in range(a)]
noarrs = allgather(len(oboxes), comm)
nomap = [i for i,a in enumerate(noarrs) for j in range(a)]
def safe_div(a,b,wrap=0):
return sbox_div(a,b,wrap=wrap) if len(a) > 0 else [np.array([[0,0,1]]*ndim)]
# Set up receive buffer
nrecv = np.zeros(len(niarrs), int)
all_iboxes = allgatherv(iboxes, comm)
rboxes = sbox_intersect(all_iboxes, oboxes, wrap=wrap)
for i1 in range(rboxes.shape[0]):
count = 0
for i2 in range(rboxes.shape[1]):
rboxes[i1,i2] = safe_div(rboxes[i1,i2], oboxes[i2])
for box in rboxes[i1,i2]:
count += np.product(sbox_size(box))
nrecv[nimap[i1]] += count*presize
recvbuf = np.empty(np.sum(nrecv), dtype)
# Set up send buffer
nsend = np.zeros(len(noarrs), int)
sendbuf = []
all_oboxes = allgatherv(oboxes, comm)
sboxes = sbox_intersect(all_oboxes, iboxes, wrap=wrap)
for i1 in range(sboxes.shape[0]):
count = 0
for i2 in range(sboxes.shape[1]):
sboxes[i1,i2] = safe_div(sboxes[i1,i2], iboxes[i2])
for box in sboxes[i1,i2]:
count += np.product(sbox_size(box))
sendbuf.append(iarrs[i2][sbox2slice(box)].reshape(-1))
nsend[nomap[i1]] += count*presize
sendbuf = np.concatenate(sendbuf)
# Perform the actual all-to-all send
sbufinfo = (nsend,cumsum(nsend))
rbufinfo = (nrecv,cumsum(nrecv))
comm.Alltoallv((sendbuf, sbufinfo), (recvbuf,rbufinfo))
# Copy out the result
off = 0
for i1 in range(rboxes.shape[0]):
for i2 in range(rboxes.shape[1]):
for rbox in rboxes[i1,i2]:
rshape = tuple(sbox_size(rbox))
data = recvbuf[off:off+np.product(rshape)*presize]
oarrs[i2][sbox2slice(rbox)] = data.reshape(preshape + rshape)
off += data.size
return oarrs
def sbox_intersect(a,b,wrap=0):
"""Given two Nd sboxes a,b [...,ndim,{start,end,step}] into the
same array, compute an sbox representing
their intersection. The resulting sbox will have poxitive step size.
The result is a possibly empty list of sboxes - it is empty if there is
no overlap. If wrap is specified, then it should be a list of length ndim
of pixel wraps, each of which can be zero to disable wrapping in
that direction."""
# First get intersection along each axis
a = sbox_fix(a)
b = sbox_fix(b)
fa = a.reshape((-1,)+a.shape[-2:])
fb = b.reshape((-1,)+b.shape[-2:])
ndim = a.shape[-2]
wrap = np.zeros(ndim,int)+wrap
# Loop over all combinations
res = np.empty((fa.shape[0],fb.shape[0]),dtype=np.object)
for ai, a1 in enumerate(fa):
for bi, b1 in enumerate(fb):
peraxis = [sbox_intersect_1d(a1[d],b1[d],wrap=wrap[d]) for d in range(ndim)]
# Get the outer product of these
nper = tuple([len(p) for p in peraxis])
iflat = np.arange(np.product(nper))
ifull = np.array(np.unravel_index(iflat, nper)).T
subres = [[p[i] for i,p in zip(inds,peraxis)] for inds in ifull]
res[ai,bi] = subres
res = res.reshape(a.shape[:-2]+b.shape[:-2])
if res.ndim == 0:
res = res.reshape(-1)[0]
return res