-
Notifications
You must be signed in to change notification settings - Fork 3
/
astrom_common.py
1761 lines (1543 loc) · 56.3 KB
/
astrom_common.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
from __future__ import print_function
import sys
import os
from glob import glob
from math import sqrt, ceil, pi, cos
import re
import numpy as np
from astrometry.util.fits import fits_table
from astrometry.util.util import Tan
from astrometry.libkd import spherematch
from astrometry.util.starutil_numpy import arcsec2dist, arcsec2deg
import astrometry
def memusage():
import resource
import gc
gc.collect()
if len(gc.garbage):
print('Garbage list:')
for obj in gc.garbage:
print(obj)
# print heapy.heap()
#ru = resource.getrusage(resource.RUSAGE_BOTH)
ru = resource.getrusage(resource.RUSAGE_SELF)
pgsize = resource.getpagesize()
print('Memory usage:')
print('page size', pgsize)
mb = int(np.ceil(ru.ru_maxrss * pgsize / 1e6))
unit = 'MB'
f = 1.
if mb > 1024:
f = 1024.
unit = 'GB'
print('max rss: %.1f %s' % (mb/f, unit))
#print 'shared memory size:', (ru.ru_ixrss / 1e6), 'MB'
#print 'unshared memory size:', (ru.ru_idrss / 1e6), 'MB'
#print 'unshared stack size:', (ru.ru_isrss / 1e6), 'MB'
#print 'shared memory size:', ru.ru_ixrss
#print 'unshared memory size:', ru.ru_idrss
#print 'unshared stack size:', ru.ru_isrss
procfn = '/proc/%d/status' % os.getpid()
try:
t = open(procfn).readlines()
#print 'proc file:', t
d = dict([(line.split()[0][:-1], line.split()[1:]) for line in t])
#print 'dict:', d
for key in ['VmPeak', 'VmSize', 'VmRSS', 'VmData', 'VmStk' ]: # VmLck, VmHWM, VmExe, VmLib, VmPTE
#print key, ' '.join(d.get(key, []))
#print 'd:', d
va = d.get(key,[])
if len(va) < 2:
continue
v = float(va[-2])
unit = va[-1]
if unit == 'kB' and v > 1024:
unit = 'MB'
v /= 1024.
if unit == 'MB' and v > 1024:
unit = 'GB'
v /= 1024.
print(key, '%.1f %s' % (v, unit))
except:
pass
def cosd(d):
return np.cos(np.deg2rad(d))
class Field(object):
def __init__(self, **kwargs):
for k,v in kwargs.items():
setattr(self, k, v)
def copy(self):
print('Field copy(): dir', dir(self))
d = {}
for k,v in self.__dict__.items():
if k.startswith('__'):
continue
if hasattr(v, 'copy'):
d[k] = v.copy()
else:
d[k] = v
return Field(**d)
def match_many(TT, rad, midra,middec, kdfns=None):
# Project around central RA,Dec
fakewcs = Tan(midra, middec, 0, 0, 0, 0, 0, 0, 0, 0)
kds = []
# Ugly hackery due to poor spherematch.py API: open/create vs close/free
closekds = []
freekds = []
# HACK -- can we use threads here? (Can't use multiprocessing
# since kd-trees refer to local memory).
print('Building kd-trees...')
for i,T in enumerate(TT):
if kdfns is not None and os.path.exists(kdfns[i]):
kd = spherematch.tree_open(kdfns[i])
print('Loaded kd-tree from', kdfns[i])
closekds.append(kd)
else:
ok,ix,iy = fakewcs.radec2iwc(T.ra, T.dec)
X = np.vstack((ix, iy)).T
kd = spherematch.tree_build(X)
freekds.append(kd)
if kdfns is not None and kdfns[i] is not None:
spherematch.tree_save(kd, kdfns[i])
print('Saved kd-tree to', kdfns[i])
kds.append(kd)
print('Matching trees...')
kdrad = arcsec2deg(rad)
matches = []
for i,kdi in enumerate(kds):
for j in range(i+1, len(kds)):
kdj = kds[j]
I,J,d = spherematch.trees_match(kdi, kdj, kdrad)
print('Match', i, 'to', j, '-->', len(I))
if len(I) == 0:
continue
m = Match(TT[i], TT[j], rad, I=I, J=J, dists=d)
matches.append((i, j, m))
print('Freeing trees...')
for kd in closekds:
spherematch.tree_close(kd)
for kd in freekds:
spherematch.tree_free(kd)
print('Done')
return matches
def _makematch(args):
(i,j,Ti,Tj,rad) = args
print('Matching', i, 'to', j, '...')
M = Match(Ti,Tj,rad)
print('Matching', i, 'to', j, '...',)
print('Got', len(M.I), 'matches')
return i,j,M
def findprimaries(TT, rad, mp):
# start by initializing all to have primary = True
print('Initializing primary arrays...')
for i,Ti in enumerate(TT):
Ti.primary = np.ones(len(Ti), bool)
print('Setting up matching arguments...')
# look at pairs of fields... (in parallel)
ranges = []
for Ti in TT:
ranges.append((Ti.ra.min(), Ti.ra.max(), Ti.dec.min(), Ti.dec.max()))
margs = []
for i,Ti in enumerate(TT):
irlo,irhi,idlo,idhi = ranges[i]
for j in range(i+1, len(TT)):
jrlo,jrhi,jdlo,jdhi = ranges[j]
if (jrlo > irhi) or (jdlo > idhi) or (jrhi < irlo) or (jdhi < idlo):
#print 'No overlap between', i, 'and', j, ':', ranges[i], ranges[j]
continue
Tj = TT[j]
margs.append((i, j, Ti, Tj, rad))
print('Set up matching arguments...', len(margs))
print('Matching...')
matches = mp.map(_makematch, margs)
print('Matching done')
for i,j,M in matches:
if len(M.I) == 0:
continue
Tj = TT[j]
# arbitrarily declare the lower-index field to be 'primary'
# Does this simple approach work?
# if A->B->C, A is primary, B gets set un-primary, C gets set un-primary,
# and if later A->C, C gets un-primary again, but that's fine.
Tj.primary[M.J] = False
return matches
def read_header_as_dict(filename, hdu):
try:
import pyfits
return pyfits.open(filename)[hdu].header
except:
import fitsio
hdr = fitsio.read_header(filename, ext=hdu)
d = dict()
for k in hdr.keys():
d[k] = hdr[k]
return d
def write_update_script(wcsfn, outfn, scriptfn, f=sys.stderr, inext=0, outext=0,
verbose=True):
hdr0 = read_header_as_dict(wcsfn, inext)
hdr1 = read_header_as_dict(outfn, outext)
if verbose:
print("\n# Old file: %s\n# New file: %s" % (wcsfn, outfn), file=sys.stderr)
for k,v in hdr1.items():
s = None
v0 = hdr0.get(k, None)
if k in ['SIMPLE', 'BITPIX', 'NAXIS', 'EXTEND']:
s = '# Key "%s" ignored' % k
elif v == v0:
# skip
s = '# Key "%s" unchanged: "%s"' % (k, str(v))
else:
if verbose:
print('key', k, 'val', v, 'type', type(v))
if type(v) is float:
sv = '%.10G' % v
else:
sv = str(v)
s = 'hedit %s %s %s ver- add+' % (scriptfn, k, sv)
f.write(s + '\n')
f.flush()
def magcuts(T, mag1cut=None, mag2cut=None, copy=True):
if mag1cut is not None and mag2cut is not None:
T = T[(T.mag1 < mag1cut) * (T.mag2 < mag2cut)]
elif mag1cut is not None:
T = T[T.mag1 < mag1cut]
elif mag2cut is not None:
T = T[T.mag2 < mag2cut]
elif copy:
T = T.copy()
return T
def getwcsoutline(wcs, w=None, h=None):
if w is None:
# Tan
if hasattr(wcs, 'imagew'):
w = wcs.imagew
# Sip
if hasattr(wcs, 'wcstan') and hasattr(wcs.wcstan, 'imagew'):
w = wcs.wcstan.imagew
if h is None:
if hasattr(wcs, 'imageh'):
h = wcs.imageh
# Sip
if hasattr(wcs, 'wcstan') and hasattr(wcs.wcstan, 'imageh'):
h = wcs.wcstan.imageh
rd = np.array([wcs.pixelxy2radec(x,y) for x,y in
[(1,1), (w,1), (w,h), (1,h), (1,1)]])
return (rd[:,0], rd[:,1])
def set_fp_err():
#np.seterr(all='raise')
np.seterr(all='warn')
def plotmatchdisthist(M, mas=True, nbins=100, doclf=True, color='b', **kwa):
import pylab as plt
if doclf:
plt.clf()
R = np.sqrt(M.dra_arcsec**2 + M.ddec_arcsec**2)
if mas:
R *= 1000.
rng = [0, M.rad*1000.]
else:
rng = [0, M.rad]
print('Match distances: median', np.median(R), 'arcsec')
n,b,p = plt.hist(R, nbins, range=rng, histtype='step', color=color, **kwa)
if mas:
plt.xlabel('Match distance (mas)')
else:
plt.xlabel('Match distance (arcsec)')
plt.xlim(*rng)
return n,b,p
def findFile(fn, path=''):
if path == '':
g = fn
else:
g = os.path.join(path, fn)
G = glob(g)
if len(G) == 0:
print('Could not find file "%s" in path "%s"' % (fn,path))
return None
if len(G) > 1:
print('Warning: found', len(G), 'matches to filename pattern', g)
print('Keeping', G[0])
return G[0]
def get_bboxes(wcs):
bboxes = []
for wcsi in wcs:
r,d = [],[]
W,H = wcsi.imagew, wcsi.imageh
for x,y in [ (0,0), (W,0), (W,H), (0,H), (0,0) ]:
rr,dd = wcsi.pixelxy2radec(x,y)
r.append(rr)
d.append(dd)
bboxes.append((r,d))
return bboxes
def resetplot():
import matplotlib
import pylab as plt
kw = {}
for p in ['bottom', 'top', 'left', 'right', 'hspace', 'wspace']:
kw[p] = matplotlib.rcParams['figure.subplot.' + p]
plt.subplots_adjust(**kw)
def plotaffinegrid(affines, exag=1e3, affineOnly=True, R=0.025, tpre='', bboxes=None):
import pylab as plt
NR = 3
NC = int(ceil(len(affines)/3.))
#R = 0.025 # 1.5 arcmin
#for (exag,affonly) in [(1e2, False), (1e3, True), (1e4, True)]:
plt.clf()
for i,aff in enumerate(affines):
plt.subplot(NR, NC, i+1)
dl = aff.refdec - R
dh = aff.refdec + R
rl = aff.refra - R / aff.rascale
rh = aff.refra + R / aff.rascale
RR,DD = np.meshgrid(np.linspace(rl, rh, 11),
np.linspace(dl, dh, 11))
plotaffine(aff, RR.ravel(), DD.ravel(), exag=exag, affineOnly=affineOnly,
doclf=False,
units='dots', width=2, headwidth=2.5, headlength=3, headaxislength=3)
if bboxes is not None:
for bb in bboxes:
plt.plot(*bb, linestyle='-', color='0.5')
plt.plot(*bboxes[i], linestyle='-', color='k')
setRadecAxes(rl,rh,dl,dh)
plt.xlabel('')
plt.ylabel('')
plt.xticks([])
plt.yticks([])
plt.title('field %i' % (i+1))
plt.subplots_adjust(left=0.05, right=0.95, wspace=0.1)
if affineOnly:
tt = tpre + 'Affine part of transformations'
else:
tt = tpre + 'Transformations'
plt.suptitle(tt + ' (x %g)' % exag)
def plotaffine(aff, RR, DD, exag=1000, affineOnly=False, doclf=True, **kwargs):
import pylab as plt
if doclf:
plt.clf()
if affineOnly:
dr,dd = aff.getAffineOffset(RR, DD)
else:
rr,dd = aff.apply(RR, DD)
dr = rr - RR
dd = dd - DD
#plt.plot(RR, DD, 'r.')
#plt.plot(RR + dr*exag, DD + dd*exag, 'bx')
plt.quiver(RR, DD, exag*dr, exag*dd,
angles='xy', scale_units='xy', scale=1,
pivot='middle', color='b', **kwargs)
#pivot='tail'
ax = plt.axis()
plt.plot([aff.getReferenceRa()], [aff.getReferenceDec()], 'r+', mew=2, ms=5)
plt.axis(ax)
esuf = ''
if exag != 1.:
esuf = ' (x %g)' % exag
plt.title('Affine transformation found' + esuf)
def mahalanobis_distsq(X, mu, C):
#print 'X', X.shape
#print 'mu', mu.shape
#print 'C', C.shape
assert(C.shape == (2,2))
det = C[0,0]*C[1,1] - C[0,1]*C[1,0]
Cinv = np.array([[ C[1,1]/det, -C[0,1]/det],
[-C[1,0]/det, C[0,0]/det]])
#print 'Cinv', Cinv.shape
#print 'Cinv * C:', np.dot(Cinv, C)
#print 'C * Cinv:', np.dot(C, Cinv)
d = X - mu
#print 'd', d.shape
Cinvd = np.dot(Cinv, d.T)
#print 'Cinvd', Cinvd.shape
M = np.sum(d * Cinvd.T, axis=1)
#print 'M', M.shape
return M
def gauss2d_from_M2(M2, C):
M = -0.5 * M2
rtn = np.zeros_like(M)
I = (M > -700) # -> ~ 1e-304
det = C[0,0]*C[1,1] - C[0,1]*C[1,0]
#print 'det', det
rtn[I] = 1./(2.*pi*sqrt(abs(det))) * np.exp(M[I])
return rtn
def gauss2d_cov(X, mu, C):
M2 = mahalanobis_distsq(X, mu, C)
return gauss2d_from_M2(M2, C)
def em_cov_step(X, mu, C, background, B, Creg=1e-6):
#print ' em_cov_step: mu', mu, 'cov', C.ravel(), 'background fraction', B
# E:
# fg = p( Y, Z=f | theta ) = p( Y | Z=f, theta ) p( Z=f | theta )
fg = gauss2d_cov(X, mu, C) * (1. - B)
# bg = p( Y, Z=b | theta ) = p( Y | Z=b, theta ) p( Z=b | theta )
bg = background * B
assert(all(np.isfinite(fg)))
assert(all(np.isfinite(np.atleast_1d(bg))))
assert(all(fg >= 0))
assert(bg >= 0)
# normalize:
# fore = p( Z=f | Y, theta )
fore = fg / (fg + bg)
# back = p( Z=b | Y, theta )
back = bg / (fg + bg)
assert(all(np.isfinite(fore)))
assert(all(np.isfinite(back)))
assert(all(fore >= 0))
assert(all(fore <= 1))
assert(all(back >= 0))
assert(all(back <= 1))
# M:
# maximize mu, C:
if np.sum(fore) == 0:
print('em_cov_step: no foreground weight')
return None
mu = np.sum(fore[:,np.newaxis] * X, axis=0) / np.sum(fore)
#print 'X', X.shape
#print 'mu', mu.shape
dx = (X - mu)[:,0]
dy = (X - mu)[:,1]
#print 'dx', dx.shape
#print 'dy', dy.shape
C = np.zeros((2,2))
#print 'C', C.shape
# this produced underflow in the numerator multiply once...
np.seterr(all='warn')
#try:
C[0,0] = np.sum(fore * (dx**2)) / np.sum(fore)
#except:
#print 'fore:', fore
# print 'dx:', dx
# print 'sum fore:', np.sum(fore)
# print 'numerator:', np.sum(fore * (dx**2))
C[1,0] = C[0,1] = np.sum(fore * (dx*dy)) / np.sum(fore)
C[1,1] = np.sum(fore * (dy**2)) / np.sum(fore)
# regularize... we are working in arcsec here; we add in a small
# regularizer to the covariance.
C += np.eye(2) * Creg**2
if np.linalg.det(C) < 1e-30:
print(' -> det(C) =', np.linalg.det(C), ', bailing out.')
return None
#print 'mu', mu
#print 'C', C.ravel()
# maximize B.
# B = p( Z=b | theta )
B = np.mean(back)
# avoid multiplying 0 * -inf = NaN
I = (fg > 0)
lfg = np.zeros_like(fg)
lfg[I] = np.log(fg[I])
lbg = np.log(bg * np.ones_like(fg))
lbg[np.flatnonzero(np.isfinite(lbg) == False)] = 0.
# Total expected log-likelihood
Q = np.sum(fore*lfg + back*lbg)
return (mu, C, B, Q, fore)
def gauss2d(X, mu, sigma):
# single-component:
#
# # prevent underflow in exp
# e = -np.sum((X - mu)**2, axis=1) / (2.*sigma**2)
# rtn = np.zeros_like(e)
# I = (e > -700) # -> ~ 1e-304
# rtn[I] = 1./(2.*pi*sigma**2) * np.exp(e[I])
# return rtn
N,two = X.shape
assert(two == 2)
C,two = mu.shape
assert(two == 2)
rtn = np.zeros((N,C))
for c in range(C):
e = -np.sum((X - mu[c,:])**2, axis=1) / (2.*sigma[c]**2)
I = (e > -700) # -> ~ 1e-304
rtn[I,c] = 1./(2.*pi*sigma[c]**2) * np.exp(e[I])
return rtn
def em_step(X, weights, mu, sigma, background, B):
'''
mu: shape (C,2) or (2,)
sigma: shape (C,) or scalar
weights: shape (C,) or 1.
C: number of Gaussian components
X: (N,2)
'''
mu_orig = mu
mu = np.atleast_2d(mu)
sigma = np.atleast_1d(sigma)
weights = np.atleast_1d(weights)
weights /= np.sum(weights)
#print 'em_step: X', X.shape, 'mu', mu.shape, 'sigma', sigma.shape, 'background', background, 'B', B
print(' em_step: weights', weights, 'mu', mu, 'sigma', sigma, 'background fraction', B)
# E:
# fg = p( Y, Z=f | theta ) = p( Y | Z=f, theta ) p( Z=f | theta )
fg = gauss2d(X, mu, sigma) * (1. - B) * weights
# fg shape is (N,C)
# bg = p( Y, Z=b | theta ) = p( Y | Z=b, theta ) p( Z=b | theta )
bg = background * B
assert(all(np.isfinite(fg.ravel())))
assert(all(np.isfinite(np.atleast_1d(bg))))
# normalize:
sfg = np.sum(fg, axis=1)
# fore = p( Z=f | Y, theta )
fore = fg / (sfg + bg)[:,np.newaxis]
# back = p( Z=b | Y, theta )
back = bg / (sfg + bg)
assert(all(np.isfinite(fore.ravel())))
assert(all(np.isfinite(back.ravel())))
# M:
# maximize mu, sigma:
#mu = np.sum(fore[:,np.newaxis] * X, axis=0) / np.sum(fore)
mu = np.dot(fore.T, X) / np.sum(fore)
# 2.*sum(fore) because X,mu are 2-dimensional.
#sigma = np.sqrt(np.sum(fore[:,np.newaxis] * (X - mu)**2) / (2.*np.sum(fore)))
C = len(sigma)
for c in range(C):
sigma[c] = np.sqrt(np.sum(fore[:,c][:,np.newaxis] * (X - mu[c,:])**2) / (2. * np.sum(fore[:,c])))
#print 'mu', mu, 'sigma', sigma
if np.min(sigma) == 0:
return (mu, sigma, B, -1e6, np.zeros(len(X)))
assert(np.all(sigma > 0))
# maximize weights:
weights = np.mean(fore, axis=0)
weights /= np.sum(weights)
# maximize B.
# B = p( Z=b | theta )
B = np.mean(back)
# avoid multiplying 0 * -inf = NaN
I = (fg > 0)
lfg = np.zeros_like(fg)
lfg[I] = np.log(fg[I])
lbg = np.log(bg * np.ones_like(fg))
lbg[np.flatnonzero(np.isfinite(lbg) == False)] = 0.
# Total expected log-likelihood
Q = np.sum(fore*lfg + back[:,np.newaxis]*lbg)
if len(mu_orig.shape) == 1:
return (1., mu[0,:], sigma[0], B, Q, fore[0,:])
return (weights, mu, sigma, B, Q, fore)
class Alignment(object):
'''
A class to represent the alignment between two catalogs.
'''
def __init__(self, tableA, tableB, searchradius=1.,
histbins=21, cov=True, cutrange=None, match=None,
maxB=None, minEMsteps=5,
initsigma=None, rascale=None,
ngaussians=1):
'''
self.match.I: matched pairs
self.subset : region around the peak in dRA,Ddec
- bool, len(subset) == len(match.I)
- sum(subset) == len(fore)
self.fore: float, foreground probabilities, for the "subset" objects
'''
self.TA = tableA
self.TB = tableB
if rascale is None:
d = np.mean(tableA.dec)
#print 'Alignment: using mean Dec', d
self.rascale = cosd(d)
#print '-> rascale', self.rascale
self.searchradius = searchradius
self.histbins = histbins
self.cov = cov
self.ngauss = ngaussians
self.cutrange = cutrange
self.match = match
self.maxB = maxB
self.minsteps = minEMsteps
self.initsigma = initsigma
def getEllipseString(self, fmt='%.1f', mas=True):
sigs = self.getEllipseSize()
if mas:
sigs[0] *= 1000.
sigs[1] *= 1000.
s = ((fmt + ' x ' + fmt) % (sigs[0], sigs[1]))
if mas:
s += ' mas'
else:
s += ' arcsec'
return s
# In arcsec
def getEllipseSize(self):
if self.cov:
U,S,V = np.linalg.svd(self.C)
eigs = np.sqrt(S)
return eigs
else:
if self.ngauss == 1:
return [self.sigma, self.sigma]
else:
return [self.sigma[0], self.sigma[0]]
def getContours(self, nsigma=1, steps=100, c=0):
if self.cov:
if not hasattr(self, 'C'):
return None
C = self.C
U,S,V = np.linalg.svd(C)
angles = np.linspace(0, 2.*pi, steps)
xy = np.vstack((np.cos(angles), np.sin(angles)))
sxy = np.sqrt(S[:,np.newaxis]) * xy * nsigma
usxy = np.dot(U, sxy)
return (self.mu[0] + usxy[0,:], self.mu[1] + usxy[1,:])
else:
angles = np.linspace(0, 2.*pi, steps)
std = self.sigma
if self.ngauss == 1:
return (self.mu[0] + self.sigma * nsigma * np.cos(angles),
self.mu[1] + self.sigma * nsigma * np.sin(angles))
else:
return (self.mu[c,0] + self.sigma[c] * nsigma * np.cos(angles),
self.mu[c,1] + self.sigma[c] * nsigma * np.sin(angles))
def getMatchWeights(self):
W = np.zeros_like(self.match.dra_arcsec)
W[self.subset] = self.fore
return W
def getNfore(self):
return sum(self.fore)
def arcsecshift(self):
return self.mu.copy()
def getshift(self):
# from arcsec back to deg.
return np.array([self.mu[0]/self.rascale, self.mu[1]])/3600.
def findMatches(self, **kwargs):
# For brick 21, fields 3-4, the shift is about 1"
rad = self.searchradius
#print 'Matching with radius', rad, 'arcsec...'
M = Match(self.TA, self.TB, rad, **kwargs)
#print 'Found %i matches' % (len(M.I))
self.match = M
def shift(self):
rad = self.searchradius
if not hasattr(self, 'match') or self.match is None:
self.findMatches(rascale=self.rascale)
M = self.match
if len(M.I) == 0:
return None
# Assume a Gaussian peak plus flat background.
# Estimate peak location with EM.
dra,ddec = M.dra_arcsec, M.ddec_arcsec
# histogram to get a first estimate of the peak.
bb = np.linspace(-rad, rad, self.histbins+1)
H,xe,ye = np.histogram2d(dra, ddec, bins=(bb,bb))
# peak
mx = np.argmax(H)
xmax = xe[int(mx / (len(ye)-1))] + 0.5*(xe[1]-xe[0])
ymax = ye[int(mx % (len(ye)-1))] + 0.5*(ye[1]-ye[0])
mu = np.array([xmax,ymax])
if self.initsigma is not None:
sigma = self.initsigma
else:
sigma = (xe[1]-xe[0])/2.
# Background fraction
B = 0.5
lastQ = None
# Cut to matches within a small distance of the peak.
if self.cutrange is None:
# default: two bins (ie, keep radius of (2/histbins ~ 10% of search radius))
#(xe[2]-xe[0])
# NO, make it bigger!
cutrange = self.cutrange = rad/2.
else:
cutrange = self.cutrange
assert(cutrange <= self.searchradius)
self.cutcenter = mu.copy()
# Re-center if the cut circle goes outside the search circle.
# (otherwise the EM is biased because not enough background matches are observed)
if sqrt(sum(self.cutcenter**2)) + cutrange > self.searchradius:
ccr = sqrt(sum(self.cutcenter**2))
newccr = self.searchradius - cutrange
self.cutcenter *= (newccr / ccr)
X = np.vstack((dra,ddec)).T
I = (np.sum((X - self.cutcenter)**2, axis=1) < cutrange**2)
X = X[I,:]
background = 1/(pi*cutrange**2)
self.subset = I
W = 1.
if self.cov:
C = np.array([[sigma**2, 0],[0, sigma**2]])
for i in range(101):
if self.maxB is not None:
B = min(self.maxB, B)
EM = em_cov_step(X, mu, C, background, B)
if EM is None:
return None
(mu, C, B, Q, fore) = EM
#print 'Q', Q
if lastQ is not None and Q - lastQ < 1 and i >= (self.minsteps-1):
#print 'Q did not improve enough, bailing'
break
lastQ = Q
nil = em_cov_step(X, mu, C, background, B)
if self.maxB is not None:
B = min(self.maxB, B)
fore = nil[-1]
self.C = C
else:
if self.ngauss > 1:
mu = mu[np.newaxis,:].repeat(self.ngauss, axis=0)
sigma = sigma * 1.5 ** np.arange(self.ngauss)
W = np.ones(self.ngauss) / float(self.ngauss)
for i in range(101):
if self.maxB is not None:
B = min(self.maxB, B)
(W, mu, sigma, B, Q, fore) = em_step(X, W, mu, sigma, background, B)
#print ' Q', Q
if lastQ is not None and Q - lastQ < 1:
break
lastQ = Q
if np.min(sigma) == 0:
break
# assert(sigma < 0.1)
# print 'Found match sigma:', sigma
if np.min(sigma) == 0:
print('EM failed')
return None
# em_step returns the foreground/background assignments of the *previous*
# settings... here we grab the assignments for the final step.
if self.maxB is not None:
B = min(self.maxB, B)
nil = em_step(X, W, mu, sigma, background, B)
fore = nil[-1]
# this is used for getMatchWeights(), so sum the foreground components.
fore = np.sum(fore, axis=1)
self.sigma = sigma
self.H = H
self.xe, self.ye = xe, ye
# the EM data
self.X = X
self.fore = fore
self.mu = mu
self.weights = W
if self.maxB is not None:
B = min(self.maxB, B)
self.bg = background * B
self.B = B
return True
def getModel(self, X, Y):
mod = np.zeros_like(X)
mod += self.bg
XY = np.vstack((X,Y)).T
if self.cov:
mod += (1. - self.B) * gauss2d_cov(XY, self.mu, self.C)
else:
mod += (1. - self.B) * gauss2d(XY, self.mu, self.sigma)
return mod
def plotresids3(Tme, Tother, M, **kwargs):
ra = (Tme.ra [M.I] + Tother.ra[M.J] )/2.
dec = (Tme.dec[M.I] + Tother.dec[M.J])/2.
dra = M.dra_arcsec
ddec = M.ddec_arcsec
plotresids2(ra, dec, dra, ddec, **kwargs)
def plotresids(Tme, M, **kwargs):
ra = Tme.ra[M.I]
dec = Tme.dec[M.I]
dra = M.dra_arcsec
ddec = M.ddec_arcsec
plotresids2(ra, dec, dra, ddec, **kwargs)
def plotresids2(ra, dec, dra, ddec, title=None, mas=True, bins=200,
dralabel=None, ddeclabel=None, ralabel=None, declabel=None,
dlim=None, doclf=True, **kwargs):
import pylab as plt
from astrometry.util.plotutils import plothist
scale = 1.
if mas:
scale = 1000.
dralab = 'dRA (mas)'
ddeclab = 'dDec (mas)'
else:
dralab = 'dRA (arcsec)'
ddeclab = 'dDec (arcsec)'
ra_kwargs = kwargs.copy()
dec_kwargs = kwargs.copy()
if dlim is not None and not 'range' in kwargs:
rarange = (ra.min(), ra.max())
decrange = (dec.min(), dec.max())
drange = (-dlim, dlim)
ra_kwargs['range'] = (rarange, drange)
dec_kwargs['range'] = (decrange, drange)
plt.clf()
plt.subplot(2,2,1)
plothist(ra, dra * scale, bins, doclf=False, docolorbar=False, **ra_kwargs)
if dlim is not None:
plt.ylim(-dlim, dlim)
#plt.xlabel('RA (deg)')
if dralabel is not None:
plt.ylabel(dralabel)
else:
plt.ylabel(dralab)
# flip RA
ax = plt.axis()
raticks,ratlabs = plt.xticks()
if len(raticks) > 3:
# FIXME -- might want to choose between the options....
raticks = raticks[::2]
plt.xticks(raticks)
plt.axis([ax[1],ax[0],ax[2],ax[3]])
plt.subplot(2,2,2)
plothist(dec, dra * scale, bins, doclf=False, docolorbar=False, **dec_kwargs)
if dlim is not None:
plt.ylim(-dlim, dlim)
#plt.xlabel('Dec (deg)')
#plt.ylabel(dralab)
ax = plt.axis()
decticks,dectlabs = plt.xticks()
if len(decticks) > 3:
decticks = decticks[::2]
plt.xticks(decticks)
plt.axis(ax)
plt.subplot(2,2,3)
plothist(ra, ddec * scale, bins, doclf=False, docolorbar=False, **ra_kwargs)
if dlim is not None:
plt.ylim(-dlim, dlim)
if ralabel is not None:
plt.xlabel(ralabel)
else:
plt.xlabel('RA (deg)')
if ddeclabel is not None:
plt.ylabel(ddeclabel)
else:
plt.ylabel(ddeclab)
# flip RA
ax = plt.axis()
plt.xticks(raticks)
plt.axis([ax[1],ax[0],ax[2],ax[3]])
plt.subplot(2,2,4)
plothist(dec, ddec * scale, bins, doclf=False, docolorbar=False, **dec_kwargs)
if dlim is not None:
plt.ylim(-dlim, dlim)
if declabel is not None:
plt.xlabel(declabel)
else:
plt.xlabel('Dec (deg)')
#plt.ylabel(ddeclab)
ax = plt.axis()
plt.xticks(decticks)
plt.axis(ax)
if title is not None:
plt.suptitle(title)
class Affine(object):
@staticmethod
def fromTable(tab):
'''
Returns: a list of Affine objects
Given: a FITS table.
'''
### FIXME -- polynomial!
affines = [ Affine(tab.dra[i], tab.ddec[i],
[ tab.tra_dra[i], tab.tra_ddec[i],
tab.tdec_dra[i], tab.tdec_ddec[i] ],
tab.refra[i], tab.refdec[i])
for i in range(len(tab)) ]
return affines
@staticmethod
def toTable(affines, T=None):
### FIXME -- polynomial!
if T is None:
from astrometry.util.fits import tabledata
T = tabledata()
N = len(affines)
T.dra = [ a.getShiftDeg()[0] for a in affines ]
T.ddec = [ a.getShiftDeg()[1] for a in affines ]
T.tra_dra = [ a.getAffine(0) for a in affines ]
T.tra_ddec = [ a.getAffine(1) for a in affines ]
T.tdec_dra = [ a.getAffine(2) for a in affines ]
T.tdec_ddec = [ a.getAffine(3) for a in affines ]
T.refra = [ a.getReferenceRadec()[0] for a in affines ]
T.refdec = [ a.getReferenceRadec()[1] for a in affines ]
a0 = affines[0]
if ((a0.refxy is not None) and
(a0.cdmatrix is not None) and
(a0.sipterms is not None)):
T.sip_refxy = np.array([ a.refxy for a in affines ])
T.sip_cd = np.array([ a.cdmatrix for a in affines ])
T.sip_terms = np.array([ a.sipterms for a in affines ])
return T
'''
dra, ddec: in degrees; not isotropic
[ r* ] = r + sra + [1/rascale] * [ Tra_ra Tra_dec ] * [ (r - r_ref) * rascale ]
[ d* ] = d + sdec + [1 ] [ Tdec_ra Tdec_dec ] [ (d - d_ref) ]
T is [ Tra_ra, Tra_dec, Tdec_ra, Tdec_dec ]; isotropic
'''
def __init__(self, dra=0., ddec=0.,
T=[0,0,0,0],
refra=0, refdec=0,
# This was an earlier attempt to do polynomial distortion corrections
# in RA,Dec space rather than in pixel space as in SIP.
rapoly=None, decpoly=None,
# These are the SIP values
refxy=None, cdmatrix=None, sipterms=None
):
self.dra = dra
self.ddec = ddec
self.T = T
if refra is not None and refdec is not None:
self.setReferenceRadec(refra, refdec)
self.rapoly = rapoly
self.decpoly = decpoly
self.refxy = refxy
self.cdmatrix = cdmatrix
self.sipterms = sipterms
def copy(self):
return Affine(self.dra, self.ddec, [self.T[i] for i in range(4)],
self.refra, self.refdec, self.rapoly, self.decpoly,
self.refxy, self.cdmatrix, self.sipterms)
def averageWith(self, other):
'''
Returns a *NEW* affine that is the average of this with *other*.
'''
assert(other.refra == self.refra)
assert(other.refdec == self.refdec)
assert(other.refxy == self.refxy)
assert(other.cdmatrix == self.cdmatrix)