-
Notifications
You must be signed in to change notification settings - Fork 3
/
astrom_intra.py
1725 lines (1449 loc) · 58.7 KB
/
astrom_intra.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
if __name__ == '__main__':
import matplotlib
matplotlib.use('Agg')
from optparse import OptionParser
from glob import glob
import os
import time
from astrometry.util.fits import *
from astrometry.util.file import *
from astrometry.util.plotutils import antigray
from astrometry.util.ttime import *
from math import cos, pi, floor, ceil, log10, sqrt
import matplotlib
import numpy as np
import pylab as plt
import scipy.sparse
import scipy.sparse.linalg
from astrom_common import *
def totalstars(TT):
return sum([len(T) for T in TT])
class Intra(object):
# self.edges:
# 0-5: i, j, matched RAs, matched Decs, matched dRAs, matched dDecs
# 6-8: aligned dRADec (mu in deg), mean RA, mean Dec,
# 9: muarcsec
# 10-11: matched dRAs (arcsec), matched dDecs (arcsec)
# 12: A.subset
# 13-14: M.I, M.J
# 15: A.fore
# 16,17,18,19: good-RAs, good-Decs, good-dRAs, good-dDecs
# 20,21,22,23: bad-""
# 24,25: good, bad
# mu in deg
def __init__(self, N):
self.edges = []
self.alignments = []
self.affines = [ Affine() for i in range(N) ]
def __str__(self):
return 'Intra: affines [\n ' + ',\n '.join(str(a) for a in self.affines) + ' ]'
def __repr__(self):
return str(self)
def update_all_dradecs(self, CC):
for i,Ci in enumerate(CC):
for j,Cj in enumerate(CC):
if j <= i:
continue
A = self.AA[i].get(j, None)
if A is None:
continue
A.match.recompute_dradec(Ci, Cj)
# shared SIP terms
def set_joint_sip_terms(self, sip):
self.joint_sip = sip
# per-field SIP terms
def set_sip_terms(self, sip):
self.sip = sip
def get_sip_terms(self, i):
if hasattr(self, 'joint_sip'):
return self.joint_sip
if hasattr(self, 'sip'):
return self.sip[i]
return None
def set_shifts(self, dra, ddec):
for a,dr,dd in zip(self.affines, dra, ddec):
a.setShift(dr, dd)
def get_affine(self, i):
return self.affines[i]
def get_affines(self):
return self.affines
def add_to_affines(self, affs):
assert(len(self.affines) == len(affs))
for a,ame in zip(affs, self.affines):
a.add(ame)
def set_affine(self, T1, T2, T3, T4):
for a,t1,t2,t3,t4 in zip(self.affines, T1,T2,T3,T4):
a.setAffine(t1,t2,t3,t4)
def get_rascale(self, fieldi):
return self.affines[fieldi].getRascale()
def get_rascales(self):
return [a.getRascale() for a in self.affines]
def set_rascales(self, rascale):
for a in self.affines:
a.setRascale(rascale)
def set_rotation(self, R):
for a,r in zip(self.affines, R):
a.setRotation(r)
def set_reference_radec(self, fieldi, r, d):
return self.affines[fieldi].setReferenceRadec(r, d)
def get_reference_radecs(self):
return [self.affines[fieldi].getReferenceRadec()
for fieldi in range(len(self.affines))]
def get_reference_radec(self, fieldi):
return self.affines[fieldi].getReferenceRadec()
def get_ra_shift_deg(self, fieldi):
ra,dec = self.affines[fieldi].getShiftDeg()
return ra
def get_dec_shift_deg(self, fieldi):
ra,dec = self.affines[fieldi].getShiftDeg()
return dec
def get_radec_shift_arcsec(self, fieldi):
return self.affines[fieldi].getShiftArcsec()
def offset(self, fieldi, ra, dec, ignoreSip=True):
return self.affines[fieldi].offset(ra,dec, ignoreSip=ignoreSip)
def apply(self, fieldi, ra, dec):
return self.affines[fieldi].apply(ra,dec)
def applyTo(self, TT):
assert(len(self.affines) == len(TT))
for i,Ti in enumerate(TT):
(cr,cd) = self.offset(i, Ti.ra, Ti.dec)
Ti.ra += cr
Ti.dec += cd
def applyToWcsObjects(self, WCS):
for i,wcs in enumerate(WCS):
self.affines[i].applyToWcsObject(wcs)
def add(self, other):
for a, o in zip(self.affines, other.affines):
a.add(o)
def toTable(self):
return Affine.toTable(self.affines)
def get_all_dradec(self, apply=False):
alldra = []
allddec = []
for ei in range(len(self.edges)):
(ra,dec,dra,ddec) = self.get_edge_dradec_arcsec(ei, corrected=apply)
alldra.append(dra)
allddec.append(ddec)
return np.hstack(alldra), np.hstack(allddec)
def trimBeforeSaving(self):
# Dump all but the results ( enough to support offset() )
self.edges = []
def nedges(self):
return len(self.edges)
def add_alignment(self, a):
self.alignments.append(a)
def add_edge(self, *args):
S = args[12]
good = np.zeros_like(S)
fore = args[15]
good[S] = (fore > 0.5)
G = [args[i][good] for i in range(2,6)]
bad = np.logical_not(good)
B = [args[i][bad] for i in range(2,6)]
self.edges.append(args + tuple(G) + tuple(B) + (good, bad))
def radec_axes(self, TT, fieldi):
T = TT[fieldi]
rl,rh = T.ra.min(), T.ra.max()
dl,dh = T.dec.min(), T.dec.max()
setRadecAxes(rl,rh, dl,dh)
def edge_ij(self, edgei):
return (self.edges[edgei])[0:2]
def edge_IJ(self, edgei):
return (self.edges[edgei])[13:15]
def edge_good(self, edgei):
return self.edges[edgei][24]
# (RAs, Decs, dRAs, dDecs), all in deg.
def edge_matches(self, edgei, goodonly=False, badonly=False):
if goodonly:
return self.edges[edgei][16:20]
elif badonly:
return self.edges[edgei][20:24]
else:
return self.edges[edgei][2:6]
def get_edge_dradec_deg(self, edgei, corrected=False, goodonly=False, badonly=False):
i,j = self.edge_ij(edgei)
(matchRA, matchDec, matchdRA, matchdDec) = self.edge_matches(edgei, goodonly, badonly)
dr = matchdRA.copy()
dd = matchdDec.copy()
if corrected:
(cri,cdi) = self.offset(i, matchRA, matchDec)
(crj,cdj) = self.offset(j, matchRA, matchDec)
dr += cri - crj
dd += cdi - cdj
return (matchRA, matchDec, dr, dd)
def get_edge_dradec_arcsec(self, edgei, corrected=False, goodonly=False,
badonly=False):
(ra, dec, dra, ddec) = (
self.get_edge_dradec_deg(edgei, corrected=corrected,
goodonly=goodonly, badonly=badonly))
return (ra, dec, dra * rascale * 3600., ddec * 3600.)
def get_total_matches(self):
return sum([len(e[2]) for e in self.edges])
# float array, foreground weights for matches in the 'subset'
def get_edge_fg(self, edgei):
return self.edges[edgei][15]
# foreground weights for all matches (not just the 'subset')
def get_edge_all_weights(self, ei):
S = self.get_edge_subset(ei)
w = np.zeros(len(S))
w[S] = self.get_edge_fg(ei)
return w
# boolean array, len(matches for edge ei)
def get_edge_subset(self, edgei):
return self.edges[edgei][12]
def plotallstars(self, TT):
if totalstars(TT) > 10000:
plothist(np.hstack([T.ra for T in TT]), np.hstack([T.dec for T in TT]),
101, imshowargs=dict(cmap=antigray), dohot=False)
else:
for T in TT:
plt.plot(T.ra, T.dec, '.', alpha=0.1, color='0.5')
def plotmatchedstars(self, edgei):
X = self.edges[edgei]
#(i, j, matchRA, matchDec, matchdRA, matchdDec, mu) = X[:7]
(matchRA, matchDec, dr,dd) = self.edge_matches(edgei, badonly=True)
plt.plot(matchRA, matchDec, 'k.', alpha=0.5)
(matchRA, matchDec, dr,dd) = self.edge_matches(edgei, goodonly=True)
plt.plot(matchRA, matchDec, '.', color=(0.5,0,0), alpha=0.5)
def plotallmatches(self):
for ei in range(len(self.edges)):
self.plotmatchedstars(ei)
# one plot per edge
def edgeplot(self, TT, ps):
for ei,X in enumerate(self.edges):
(i, j) = X[:2]
Ta = TT[i]
Tb = TT[j]
plt.clf()
if len(Ta) > 1000:
nbins = 101
ra = np.hstack((Ta.ra, Tb.ra))
dec = np.hstack((Ta.dec, Tb.dec))
H,xe,ye = np.histogram2d(ra, dec, bins=nbins)
(matchRA, matchDec, dr,dd) = self.edge_matches(ei, goodonly=True)
G,xe,ye = np.histogram2d(matchRA, matchDec, bins=(xe,ye))
assert(G.shape == H.shape)
img = antigray(H / H.max())
img[G>0,:] = matplotlib.cm.hot(G[G>0] / H[G>0])
ax = setRadecAxes(xe[0], xe[-1], ye[0], ye[-1])
plt.imshow(img, extent=(min(xe), max(xe), min(ye), max(ye)),
aspect='auto', origin='lower', interpolation='nearest')
plt.axis(ax)
else:
self.plotallstars([Ta,Tb])
self.plotmatchedstars(ei)
plt.xlabel('RA (deg)')
plt.ylabel('Dec (deg)')
ps.savefig()
# one plot per edge
def edgescatter(self, ps):
for ei,X in enumerate(self.edges):
i,j = X[:2]
matchdRA, matchdDec = X[10:12]
mu = X[9]
A = self.alignments[ei]
plt.clf()
if len(matchdRA) > 1000:
plothist(matchdRA, matchdDec, 101)
else:
plt.plot(matchdRA, matchdDec, 'k.', alpha=0.5)
plt.axvline(0, color='0.5')
plt.axhline(0, color='0.5')
plt.axvline(mu[0], color='b')
plt.axhline(mu[1], color='b')
for nsig in [1,2]:
X,Y = A.getContours(nsigma=nsig)
plt.plot(X, Y, 'b-')
plt.xlabel('delta-RA (arcsec)')
plt.ylabel('delta-Dec (arcsec)')
plt.axis('scaled')
ps.savefig()
def vecplot(self, TT, apply=False, scale=100, outlines=None,
arrowminmatches=100):
# find RA,Dec range of stars
ral,rah = 1000,-1000
decl,dech = 1000,-1000
for i in range(len(TT)):
print('File', i, 'RA', TT[i].ra.min(), TT[i].ra.max(), 'DEC', TT[i].dec.min(), TT[i].dec.max())
ral = min(ral, TT[i].ra.min())
rah = max(rah, TT[i].ra.max())
decl = min(decl, TT[i].dec.min())
dech = max(dech, TT[i].dec.max())
print('ra,dec range', ral,rah,decl,dech)
#ps3 = PlotSequence('tst-', format='%02i')
plt.clf()
self.plotallstars(TT)
###
# ps3.savefig()
ax = plt.axis()
if outlines is not None:
for rr,dd in outlines:
plt.plot(rr, dd, 'k-', alpha=0.4)
###
# ps3.savefig()
for ei in range(len(self.edges)):
self.plotmatchedstars(ei)
###
# ps3.savefig()
for ei,X in enumerate(self.edges):
(i, j) = self.edge_ij(ei)
(matchRA, matchDec, dr,dd) = self.edge_matches(ei, goodonly=True)
Nmatches = len(matchRA)
if Nmatches == 0:
continue
assert(all(np.isfinite(matchRA)))
assert(all(np.isfinite(matchDec)))
#print 'edge from', i, 'to', j, 'has', len(matchRA), 'matches'
mu = X[6].copy()
Ta = TT[i]
Tb = TT[j]
era,edec = np.mean(matchRA), np.mean(matchDec)
ara,adec = np.mean(Ta.ra), np.mean(Ta.dec)
bra,bdec = np.mean(Tb.ra), np.mean(Tb.dec)
plt.text(era, edec, '%i' % Nmatches, color='g', zorder=11)
plt.text(ara, adec, '%i' % i, color='k', zorder=11)
plt.text(bra, bdec, '%i' % j, color='k', zorder=11)
if Nmatches < arrowminmatches:
continue
if apply:
# ignoreSIP = True
(ri,di) = self.offset(i, era, edec)
(rj,dj) = self.offset(j, era, edec)
mu[0] += ri - rj
mu[1] += di - dj
mu *= scale
lw = max(1, log10(Nmatches))
W = ax[1]-ax[0]
aargs = dict(width=W * 2e-3, head_width=W * 4e-3, lw=lw, zorder=10)
#aargs = dict(width=0.005, head_width=0.04, lw=lw, zorder=10)
plt.arrow(era, edec, mu[0], mu[1], color='r', **aargs)
plt.arrow(ara, adec, mu[0], mu[1], color='b', alpha=0.7, **aargs)
plt.arrow(bra, bdec, -mu[0], -mu[1], color='b', alpha=0.7, **aargs)
plt.plot([ara,bra,era], [adec,bdec,edec], 'k.', zorder=11)
###
# ps3.savefig()
setRadecAxes(ral, rah, decl, dech)
###
# ps3.savefig()
def scatterplot(self, TT, apply=False, markshifts=True, mas=False,
force_hist=False, range=None):
if len(self.edges) == 0:
print('Cannot create scatterplot() without edge data')
return False
rng = range
import __builtin__
range = __builtin__.range
plt.clf()
H = None
dohist = force_hist or (self.get_total_matches() > 10000)
if mas:
S = 1000.
else:
S = 1.
if dohist:
if rng is not None:
mn,mx = rng
else:
mn = -self.matchrad_arcsec * S
mx = self.matchrad_arcsec * S
bins = np.linspace(mn, mx, 201)
sr,sd = [],[]
for ei in range(len(self.edges)):
(ra,dec,bdRA,bdDec) = self.get_edge_dradec_arcsec(ei, corrected=apply, badonly=True)
(ra,dec,gdRA,gdDec) = self.get_edge_dradec_arcsec(ei, corrected=apply, goodonly=True)
if len(gdRA) == 0:
continue
if not apply and markshifts:
i,j = self.edge_ij(ei)
drai,ddeci = self.get_radec_shift_arcsec(i)
draj,ddecj = self.get_radec_shift_arcsec(j)
dra = draj - drai
ddec = ddecj - ddeci
sr.append(dra * S)
sd.append(ddec* S)
if dohist:
Hi,xe,ye = np.histogram2d(gdRA *S, gdDec *S, bins=bins)
if H is None:
H = Hi
else:
H += Hi
else:
plt.plot(bdRA *S, bdDec *S, 'k.', alpha=0.1)
plt.plot(gdRA *S, gdDec *S, 'r.', alpha=0.1)
if dohist:
plt.imshow(H.T, extent=(min(xe), max(xe), min(ye), max(ye)),
aspect='auto', origin='lower', interpolation='nearest')
plt.hot()
plt.colorbar()
# compute ||dra,ddec||^2 weighted by p(fg) -- estimated size of residuals
sumd2 = 0
sumfg = 0
sumra = 0
sumdec = 0
for ei in range(len(self.edges)):
(ra,dec,dra,ddec) = self.get_edge_dradec_arcsec(ei, corrected=apply)
sub = self.get_edge_subset(ei)
dra,ddec = dra[sub],ddec[sub]
fg = self.get_edge_fg(ei)
sumd2 += np.sum(fg * (dra**2 + ddec**2))
sumfg += np.sum(fg)
sumra += np.sum(fg * dra)
sumdec += np.sum(fg * ddec)
mra,mdec = sumra/sumfg * S, sumdec/sumfg * S
# 2: per-coordinate
md = sqrt(sumd2/(sumfg*2.)) * S
ax = plt.axis()
if len(sr):
plt.plot(sr, sd, 'g+', mew=2, zorder=10)
plt.plot([mra],[mdec], 'b+')
angles = np.linspace(0, 2.*pi, 100)
plt.plot(mra + md * np.cos(angles), mdec + md * np.sin(angles), 'b-')
plt.plot(mra + 2. * md * np.cos(angles),
mdec + 2. * md * np.sin(angles), 'b-')
plt.title('%i matches, mean (%.1g, %.1g) mas, std %.1f mas' %
(int(round(sumfg)), 1000.*mra/S, 1000.*mdec/S, 1000.*md/S))
plt.axvline(0, color='0.5')
plt.axhline(0, color='0.5')
if mas:
plt.xlabel('delta RA (mas)')
plt.ylabel('delta Dec (mas)')
else:
plt.xlabel('delta RA (arcsec)')
plt.ylabel('delta Dec (arcsec)')
if not dohist and rng is not None:
plt.axis([rng[0], rng[1], rng[0], rng[1]])
else:
plt.axis(ax)
plt.axis('scaled')
def xyoffsets(self, TT, apply=False, scale=100., binsize=None, wcs=None, subplotsize=None, ps=None):
plt.clf()
if subplotsize is None:
subplotsize = (3,3)
(subw,subh) = subplotsize
print('x,y size', (TT[0].x.max() - TT[0].x.min()), (TT[0].y.max() - TT[0].y.min()))
if binsize is None:
binsize = 200
for i,T in enumerate(TT):
print('xyoffsets: field', i)
if ps is None:
plt.subplot(subw,subh, i+1)
else:
plt.clf()
if wcs is not None:
thiswcs = wcs[i]
else:
thiswcs = None
for ei in range(len(self.edges)):
ii,jj = self.edge_ij(ei)
I,J = self.edge_IJ(ei)
if i == ii:
K = I
s = 1.
elif i == jj:
K = J
s = -1.
else:
continue
x,y = T.x[K], T.y[K]
(r,d, dr,dd) = self.get_edge_dradec_deg(ei, corrected=apply, goodonly=True)
good = self.edge_good(ei)
x,y = x[good],y[good]
#print len(x), len(r), len(dr)
assert(len(x) == len(r))
assert(len(r) == len(dr))
dr *= s
dd *= s
x0 = min(x)
y0 = min(y)
NX = 1 + int(floor((max(x) - x0) / binsize))
NY = 1 + int(floor((max(y) - y0) / binsize))
NB = NX * NY
bi = (
(np.floor(x - x0) / binsize).astype(int) +
(np.floor(y - y0) / binsize).astype(int)*NX )
if thiswcs:
RR,DD = [],[]
w,h = thiswcs.get_width(), thiswcs.get_height()
for x,y in [ (0,0), (w,0), (w,h), (0,h), (0,0) ]:
ri,di = thiswcs.pixelxy2radec(x,y)
RR.append(ri)
DD.append(di)
plt.plot(RR, DD, '-', color='0.5')
px = []
py = []
dx = []
dy = []
for b in np.unique(bi): #range(NB):
#ix = b % NX
#iy = b / NX
#cx = x0 + (ix + 0.5) * binsize
#cy = y0 + (iy + 0.5) * binsize
I = (bi == b)
if sum(I) == 0:
continue
mra,mdec = np.mean(r[I]), np.mean(d[I])
mdra,mddec = np.mean(dr[I]), np.mean(dd[I])
#plt.plot([mra], [mdec], 'k.', zorder=10, ms=2)
#plt.plot([mra, mra + mdra*scale], [mdec, mdec + mddec*scale],
#'r-', zorder=11)
px.append(mra)
py.append(mdec)
dx.append((mra, mra + mdra * scale))
dy.append((mdec, mdec + mddec * scale))
plt.plot(px, py, 'k.', zorder=10, ms=2)
plt.plot(np.array(dx).T, np.array(dy).T,
'r-', zorder=11)
self.radec_axes(TT, i)
if ps is not None:
ps.savefig()
else:
plt.xticks([],[])
plt.yticks([],[])
def quiveroffsets(self, TT, apply=False):
plt.clf()
self.plotallstars(TT)
self.plotallmatches()
for ei in range(len(self.edges)):
(matchRA, matchDec, dr, dd) = self.get_edge_dradec_deg(ei, corrected=apply, goodonly=True)
scale = 100.
plt.plot(np.vstack((matchRA, matchRA + dr*scale)),
np.vstack((matchDec, matchDec + dd*scale)),
'r-', alpha=0.5)
plt.xlabel('RA (deg)')
plt.ylabel('Dec (deg)')
# rad in arcsec
def hsvoffsets(self, TT, rad, apply=False):
print('hsv offsets plot')
plt.clf()
for ix,X in enumerate(self.edges):
X = self.get_edge_dradec_arcsec(ix, corrected=apply, goodonly=True)
(matchRA, matchDec, dra, ddec) = X
print('matchRA,Dec:', len(matchRA), len(matchDec))
print('dra,dec:', len(dra), len(ddec))
for ra,dec,dr,dd in zip(matchRA, matchDec, dra, ddec):
angle = arctan2(dd, dr) / (2.*pi)
angle = fmod(angle + 1, 1.)
mag = hypot(dd, dr)
mag = min(1, mag/(0.5*rad))
rgb = colorsys.hsv_to_rgb(angle, mag, 0.5)
plt.plot([ra], [dec], '.', color=rgb, alpha=0.5)
# legend in top-right corner.
ax=plt.axis()
xlo,xhi = plt.gca().get_xlim()
ylo,yhi = plt.gca().get_ylim()
# fraction
keycx = xlo + 0.90 * (xhi-xlo)
keycy = ylo + 0.90 * (yhi-ylo)
keyrx = 0.1 * (xhi-xlo) / 1.4 # HACK
keyry = 0.1 * (yhi-ylo)
nrings = 5
for i,(rx,ry) in enumerate(zip(np.linspace(0, keyrx, nrings), np.linspace(0, keyry, nrings))):
nspokes = ceil(i / float(nrings-1) * 30)
angles = np.linspace(0, 2.*pi, nspokes, endpoint=False)
for a in angles:
rgb = colorsys.hsv_to_rgb(a/(2.*pi), float(i)/(nrings-1), 0.5)
plt.plot([keycx + rx*sin(a)], [keycy + ry*cos(a)], '.', color=rgb, alpha=1.)
plt.axis(ax)
plt.xlabel('RA (deg)')
plt.ylabel('Dec (deg)')
def get_mags(self, TT, apply, magcol='mag1', magerrcol='mag1_err'):
alldd = []
allmagI = []
allmagJ = []
allmagerrI = []
allmagerrJ = []
for ei in range(len(self.edges)):
good = self.edge_good(ei)
ii,jj = self.edge_ij(ei)
I,J = self.edge_IJ(ei)
(r,d, dra,ddec) = self.get_edge_dradec_arcsec(ei, corrected=apply,
goodonly=True)
dd = np.sqrt(dra**2 + ddec**2)
alldd.append(dd)
# 'I' is an int array
# 'good' is a bool array of size == size(I)
# number of True elements in 'good' == len(dra)
magI = TT[ii][I][good].get(magcol)
magJ = TT[jj][J][good].get(magcol)
allmagI.append(magI)
allmagJ.append(magJ)
if magerrcol in TT[ii].columns():
allmagerrI.append(TT[ii].get(magerrcol)[I][good])
allmagerrJ.append(TT[jj].get(magerrcol)[J][good])
alldd = np.hstack(alldd)
allmagI = np.hstack(allmagI)
allmagJ = np.hstack(allmagJ)
allmagerrI = np.hstack(allmagerrI)
allmagerrJ = np.hstack(allmagerrJ)
return (allmagI, allmagJ, alldd, magcol, allmagerrI, allmagerrJ)
def magmagplot(self, TT, magcol, filtname, weighted=True):
plt.clf()
m1 = []
m2 = []
ww = []
for ei in range(self.nedges()):
i,j = self.edge_ij(ei)
I,J = self.edge_IJ(ei)
Ti = TT[i][I]
Tj = TT[j][J]
mag1 = Ti.get(magcol)
mag2 = Tj.get(magcol)
weights = self.get_edge_all_weights(ei)
K = (mag1 < 50) * (mag2 < 50)
m1.append(mag1[K])
m2.append(mag2[K])
ww.append(weights[K])
m1 = np.hstack(m1)
m2 = np.hstack(m2)
ww = np.hstack(ww)
if weighted:
loghist(m1, m2, weights=ww)
else:
loghist(m1, m2)
plt.xlabel('%s (mag)' % filtname)
plt.ylabel('%s (mag)' % filtname)
return ww
def magplot(self, TT, apply=False, hist=False, errbars=False,
step=0.5, maxerr=None, magcol='mag1', magerrcol='mag1_err'):
''' maxerr: cut any errors larger than this, in arcsec. '''
allmagI,allmagJ,alldd,magcol, allmagerrI,allmagerrJ = self.get_mags(TT, apply, magcol=magcol, magerrcol=magerrcol)
allmag = (allmagI+allmagJ) / 2.
allmagerr = (allmagerrI+allmagerrJ) / 2.
if maxerr is not None:
I = (alldd <= maxerr)
allmag = allmag[I]
allmagerr = allmagerr[I]
alldd = alldd[I]
I = (allmag < 50.)
allmag = allmag[I]
allmagerr = allmagerr[I]
alldd = alldd[I]
# work in milli-arcsec.
alldd *= 1000.
plt.clf()
#plt.plot(allmag1, alldd, 'm.', zorder=9, alpha=0.5)
#plt.plot(allmag2, alldd, 'm.', zorder=9, alpha=0.5)
#plt.plot(allmag, alldd, 'r.', zorder=10, alpha=0.5)
loghist(allmag, alldd, 100, imshowargs=dict(cmap=antigray), hot=False)
plt.xlabel('Mag ' + magcol)
plt.ylabel('Match distance (milli-arcsec)')
ax = plt.axis()
bind = []
binerr = []
if hist or errbars:
mn = int(floor(allmag.min()))
mx = int(ceil(allmag.max()))
binx = []
biny = []
binyerr = []
# "step" is mag bin size
for m in np.arange(mn,mx, step):
I = ((allmag > m) * (allmag < (m+step)))
d = alldd[I]
bind.append(d)
binerr.append(np.median(allmagerr[I]))
binx.append(m+step/2.)
if len(d) == 0:
biny.append(0)
binyerr.append(0)
else:
biny.append(np.mean(d))
binyerr.append(np.std(d))
if hist:
# histogram per 1-mag big
bins = np.linspace(0, ax[3], 20)
for d,m in zip(bind,binx):
if len(d) == 0:
continue
H,e = np.histogram(d, bins=bins)
pk = H.max()
n,b,p = plt.hist(d, bins=bins,
weights=np.ones_like(d) * 0.5/pk,
orientation='horizontal', bottom=m, zorder=15,
ec='b', fc='none')
if errbars:
I = np.array([(len(d) >= 4) for d in bind])
binx = np.array(binx)
biny = np.array(biny)
binyerr = np.array(binyerr)
binerr = np.array(binerr)
p1,p2,p3 = plt.errorbar(binx[I], biny[I], binyerr[I], fmt='o',
barsabove=True, zorder=15)
for p in p2 + p3:
p.set_zorder(15)
if False:
ax1 = plt.gca()
plt.twinx()
plt.plot(binx[I], binerr[I], 'ro', zorder=16)
plt.sca(ax1)
if False:
# contours
B = 50
H,xe,ye = np.histogram2d(allmag, alldd,
bins=(np.linspace(ax[0],ax[1],B),
np.linspace(ax[2],ax[3],B)))
#plt.imshow(H.T, extent=ax, #(min(xe), max(xe), min(ye), max(ye)),
# aspect='auto', origin='lower', interpolation='nearest')
#plt.colorbar()
mx = H.max()
print('max histogram:', mx)
step = max(mx / 5, 10)
plt.contour(H.T, extent=ax, colors='k', zorder=15,
levels=np.arange(step, mx, step))
plt.axis(ax)
return biny,binerr
def n_sip_terms(sip_order):
assert(sip_order >= 2)
n = 0
for order in range(2, sip_order+1):
n += 2 * (order + 1)
return n
# for parallelization of matching in 'intrabrickshift'...
def alignfunc(args):
try:
return _real_alignfunc(args)
except:
import traceback
print('Exception in alignfunc:')
traceback.print_exc()
raise
def _real_alignfunc(args):
(Ti, Tj, matchradius, align_kwargs, mag1diff, mag2diff, i, j,
mdhrad, alignplotargs, silent) = args
weightrange = align_kwargs.pop('weightrange', None)
if i == j:
jname = 'ref'
else:
jname = j
if not silent:
print('Matching', i, 'to', jname, 'with radius', matchradius, 'arcsec...')
A = Alignment(Ti, Tj, searchradius = matchradius,
**align_kwargs)
# apply maximum magnitude difference cuts
if mag1diff is not None or mag2diff is not None:
M = Match(Ti, Tj, matchradius)
if mag1diff is not None:
magdiff = np.abs(Ti.mag1[M.I] - Tj.mag1[M.J])
K = np.flatnonzero(magdiff <= mag1diff)
M.cut(K)
if mag2diff is not None:
magdiff = np.abs(Ti.mag2[M.I] - Tj.mag2[M.J])
K = np.flatnonzero(magdiff <= mag2diff)
M.cut(K)
A.match = M
if A.shift() is None:
if not silent:
print('Failed to find a shift between files', i, 'and', j)
return i,j,None
if not silent:
print('Matching', i, 'to', jname, ': got', len(A.match.I))
# use EM results to weight the matches
# A.match (a Match object) are the matches
# A.subset (a slice) are the matches used in EM peak-fitting
# A.fore are the foreground probabilities for the matches.
M = A.match
# Save histogram of matches (before the cut)
hist2dargs = alignplotargs
if not 'range' in hist2dargs:
RR = matchradius * 1000.
hist2dargs.update(range=((-RR,RR),(-RR,RR)))
(H,xe,ye) = np.histogram2d(M.dra_arcsec * 1000., M.ddec_arcsec*1000., **hist2dargs)
alplot = dict(H=H.T, extent=(min(xe), max(xe), min(ye), max(ye)),
aspect='auto', interpolation='nearest', origin='lower',
esize=A.getEllipseSize(),
estring=A.getEllipseString(),
econ1=A.getContours(1),
econ2=A.getContours(2),
ecen=A.arcsecshift(),
foresum = np.sum(A.fore),
)
matchra, matchdec = Ti.ra[M.I], Ti.dec[M.I]
# Cut to the objects used in the EM fit
S = A.subset
# possibly cut on A.fore
w = np.sqrt(A.fore)
if weightrange is not None:
maxw = np.max(w)
K = np.flatnonzero(w >= (maxw * weightrange))
if not silent:
print('Cut to', len(K), 'of', len(w), 'matches with weights greater than fraction', weightrange, 'of max')
# A.subset is a bool array
assert(S.dtype == bool)
S = np.flatnonzero(S)[K]
w = w[K]
matchra,matchdec = matchra[S], matchdec[S]
alplot.update(MIall=M.I, MJall=M.J)
M.cut(S)
# dra,ddec are in degrees.
dra,ddec = M.dra,M.ddec
# make the errors isotropic
dra *= A.rascale
mdh = np.histogram(M.getdist_mas(), bins=100, range=(0, mdhrad*1000.))
alplot.update(MI=M.I, MJ=M.J)
return i,j, (dra,ddec,matchra,matchdec,w, M.I, M.J, mdh, alplot)
def intrabrickshift(TT, matchradius = 1.,
do_rotation=False, do_affine=False,
refradecs = None,
mag1diff = None, mag2diff = None,
sip_order = None,
sip_groups = None,
refxys = None,
cdmatrices = None,
align_kwargs = {},
lsqr_kwargs = {},
ref=None, refrad=0.,
# Cuts to apply to the catalogs before matching to ref.
refmag1cut=None, refmag2cut=None,
mp=None,
cam='(cam)', refcam='(refcam)',
mdhrad=None,
alignplotargs={},
# If non-None: a 2-d numpy array of booleans, indicating whether
# fields i,j overlap.
overlaps=None,
# Save alignment results?
save_aligngrid = False,
):
'''
match radius is in arcsec
refxys: list, one element per field, of (crpix0, crpix1)
cdmatrices: list, one per field, of (cd11, cd12, cd21, cd22)
= [ d(isotropic RA)/dx, d(iRA)/dy, dDec/dx, dDec/dy ]
sip_groups: list of integers, same length as TT and starting at
zero; fields with the same sipgroup will share SIP polynomial
coefficients.
AA: [ [Alignment],] objects; AA[i][j] is Alignment between fields
i and j, or None for no matches.
'''
do_sip = False
t0 = Time()
if sip_order is not None:
do_sip = True
do_affine = True
assert(refxys is not None)
assert(cdmatrices is not None)
assert(sip_groups is not None)
assert(len(sip_groups) == len(TT))
assert(len(refxys) == len(TT))
assert(len(cdmatrices) == len(TT))
Nsip = n_sip_terms(sip_order)
Nsipgroups = len(np.unique([sg for sg in sip_groups if sg != -1]))
print('sip groups:', np.unique([sg for sg in sip_groups if sg != -1]))
print('Solving for', Nsip, 'SIP terms for each of', Nsipgroups, 'groups')
if do_rotation and do_affine:
print('Both do_rotation and do_affine are set -- doing affine.')
do_affine = True
do_rotation = False
intra = Intra(len(TT))
intra.matchrad_arcsec = matchradius
#intra.AA = {}
ramin,ramax = [],[]
decmin,decmax = [],[]
for i,Ti in enumerate(TT):
ramin.append(Ti.ra.min())
ramax.append(Ti.ra.max())
decmin.append(Ti.dec.min())
decmax.append(Ti.dec.max())
if refradecs is None:
intra.set_reference_radec(i, (ramin[i]+ramax[i])/2., (decmin[i]+decmax[i])/2.)
else: