-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdev_ccmatch.py
More file actions
executable file
·2842 lines (2165 loc) · 103 KB
/
dev_ccmatch.py
File metadata and controls
executable file
·2842 lines (2165 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
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
#!/usr/bin/env python3
"""
This module contains all functionality to perform the astrometric correction of
a frame by matching the source catalog to a catalog of reference stars.
"""
import sys
import numpy
import os
import astropy.io.fits as pyfits
import datetime
import scipy
import scipy.stats
import math
import scipy.spatial
import itertools
from podi_definitions import *
from podi_commandline import *
import podi_search_ipprefcat
from podi_wcs import *
import podi_search_ipprefcat
import podi_sitesetup as sitesetup
from podi_photcalib import estimate_zeropoint, estimate_mean_star_color
import queue
import multiprocessing
max_pointing_error = 8.
import podi_logging
import logging
create_debug_files = False
create_debug_files2 = False
def select_brightest(radec, mags, n):
"""
Create a new catalog containing only the n brightest members of the input
catalog.
"""
# print mags
si = numpy.argsort(mags[:,0])
# print si
output_radec = numpy.zeros(shape=(n, radec.shape[1]))
output_mags = numpy.zeros(shape=(n, mags.shape[1]))
for i in range(n):
# print si[i], mags[si[i],0]
output_radec[i,:] = radec[si[i],:]
output_mags[i,:] = mags[si[i],:]
return output_radec, output_mags
def count_matches(src_cat, ref_cat,
pointing_error=(max_pointing_error/60.),
matching_radius=(4./3600.), debugangle=None):
"""
This is the main routine in ccmatch. First, find for each source in catalog
1 all nearby sources in catalog 2. In a second step, determine the
approximate relative position that occurs the most frequently.
"""
logger = logging.getLogger("CountMatches")
#
# Now loop over all stars in the source catalog and find nearby stars in the reference catalog
# Use a rather large matching radius for this step
#
# matching_radius = 1./60. # 1 arcmin
# Fix the cos(declination) problem
max_declination = numpy.max(numpy.fabs(src_cat[:,1]))
if (max_declination > 85): max_declination = 85
cos_dec = math.cos(math.radians(max_declination))
ref_cat = ref_cat.copy()
ref_cat[:,0] *= cos_dec
src_cat = src_cat.copy()
src_cat[:,0] *= cos_dec
logger.debug("Creating ref KDtree")
ref_tree = scipy.spatial.cKDTree(ref_cat)
# print "\n\n\nIn count_matches:"
# print "src-cat:",src_cat.shape
# print "ref-cat:",ref_cat.shape
#
# Allocate some memory to hold a 2-d binned count array
# bin-size is 1 arcsec^2, with side-length +/- pointing_errors [in degrees]
#
grid_size = int(pointing_error * 3600 * 2 + 1)
count_grid_2d = numpy.zeros((grid_size, grid_size))#, dtype=int)
idx_x, idx_y = numpy.indices(count_grid_2d.shape)
idx_x -= (grid_size-1)//2
idx_y -= (grid_size-1)//2
valid_pixelpos = numpy.hypot(idx_x, idx_y) < (pointing_error * 3600)
#
# Split catalog into chunks to limit momory usage
# and hopefully speed things up
#
chunksize = 50
n_chunks = int(math.ceil(float(src_cat.shape[0]) / float(chunksize)))
logger.debug("splitting reference catalog into %d chunks" % (n_chunks))
peak_position = []
all_significance = []
all_max_mean_std = []
no_gain_chunks = 0
previous_max = -1
previous_peak_std = numpy.array([1e9, 1e9])
for chunk in range(n_chunks):
# Get this chunk of the catalog
src_chunk = src_cat[chunk*chunksize:(chunk+1)*chunksize, :]
# logger.info("Creating src KDtree")
src_tree = scipy.spatial.cKDTree(src_chunk)
#
# First create a catalog of nearby reference stars for each source star
#
# find all matches
# logger.info("Running ball_tree query")
matches = src_tree.query_ball_tree(ref_tree, pointing_error, p=2)
# also count how many matches in total we have found
# logger.info("counting all neighbors")
n_matches = src_tree.count_neighbors(ref_tree, pointing_error, p=2)
# Allocate memory to hold all offsets between src and reference catalog
all_offsets = numpy.zeros(shape=(n_matches,2))
cur_pair = 0
# dummy = open("ccmatch.offsets.%d" % int(round((debugangle*60),0)), "w")
# logger.info("assembling entire catalog (%d)" % (len(matches)))
for cur_src in range(len(matches)):
if (len(matches[cur_src]) <= 0):
continue
#if (verbose): print "\n",cur_src
# print matches[cur_src]
#
# matches[cur_src] contains the indices of matching stars from
# the reference catalog.
# So extract the actual coordinates of all nearby reference stars
#
cur_matches = numpy.array(ref_cat[matches[cur_src]])
#if (verbose): print cur_matches
# print cur_matches.shape
#
# Subtract the source position to get relative offsets
#
cur_matches -= src_chunk[cur_src]
#if (verbose): print cur_matches
#numpy.savetxt(dummy, cur_matches)
#print >>dummy, "\n\n\n\n\n"
#
# And add all offsets into the global offset registry
#
# for cur_refstar in range(len(matches[cur_src])):
# all_offsets[cur_pair,:] = cur_matches[cur_refstar]
# cur_pair += 1
all_offsets[cur_pair:cur_pair+cur_matches.shape[0], :] = cur_matches[:,:]
cur_pair += cur_matches.shape[0]
# #
# # Add the new found src-ref pairs to count grid
# #
# this_2d, xedges, yedges = numpy.histogram2d(cur_matches[:,0]*3600, cur_matches[:,1]*3600,
# bins=grid_size,
# range=[[-pointing_error*3600, pointing_error*3600],
# [-pointing_error*3600, pointing_error*3600]],
# density=False,
# weights=None)
# count_grid_2d += this_2d
# all_offsets[cur_pair:cur_pair+len(matches[cur_src]), :] = cur_matches[matches[cur_src]]
# cur_pair += len(matches[cur_src])
#print "#matches for source",cur_src, "-->", len(matches[cur_src]), src_cat.shape[0], ref_cat.shape[0], this_2d.shape, numpy.sum(this_2d)
# sys.stdout.write(".")
# sys.stdout.flush()
this_2d, xedges, yedges = numpy.histogram2d(all_offsets[:,0]*3600, all_offsets[:,1]*3600,
bins=grid_size,
range=[[-pointing_error*3600, pointing_error*3600],
[-pointing_error*3600, pointing_error*3600]],
density=False,
weights=None)
count_grid_2d += this_2d.astype(numpy.float32)
if (create_debug_files2): numpy.savetxt("cc_countgrid_%+0.3f_chunk%03d" % (debugangle, chunk), count_grid_2d)
# print "all-offsets:", all_offsets.shape, count_grid_2d.shape
# Now smooth the count_grid with a small kernel to avoid spurious
# single-pixel peaks and combine more extended peaks
# smoothed = scipy.ndimage.filters.gaussian_filter(
# input=count_grid_2d, sigma=3, order=0,
# output=None, mode='constant', cval=0.0)
smoothed = count_grid_2d
# peak_index = numpy.array(numpy.unravel_index(count_grid_2d.argmax(), count_grid_2d.shape))
peak_index = numpy.array(numpy.unravel_index(smoothed.argmax(), count_grid_2d.shape))
peak_pos = peak_index - (grid_size-1)/2
# _max = numpy.max(count_grid_2d[valid_pixelpos])
# _std = numpy.std(count_grid_2d[valid_pixelpos])
# _mean = numpy.mean(count_grid_2d[valid_pixelpos])
# _median = numpy.median(count_grid_2d[valid_pixelpos])
_max = numpy.max(smoothed[valid_pixelpos])
_std = numpy.std(smoothed[valid_pixelpos])
_mean = numpy.mean(smoothed[valid_pixelpos])
_median = numpy.median(smoothed[valid_pixelpos])
if (create_debug_files2):
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(15, 15))
ax = fig.add_subplot(111)
# sys.stdout.write("\r%d / %d" % (cur_src, len(matches)))
# sys.stdout.flush()
# ax.imshow(count_grid_2d, interpolation='nearest', origin='low',
# extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
ax.imshow(smoothed, interpolation='nearest', origin='low',
extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
#plt.show()
figname = "progress_chunk_%03d.png" % (chunk) if debugangle==None \
else "progress_%.2fdeg_chunk%03d.png" % (debugangle, chunk)
fig.savefig(figname)
plt.close(fig)
plt.close()
print("\npeak at:", peak_pos, "max=%f std=%f mean=%f median=%f" % (
numpy.max(count_grid_2d), numpy.std(count_grid_2d), numpy.mean(count_grid_2d), numpy.median(count_grid_2d))
)
print("valid_only: std=%f, mean=%f, median=%f" % (
numpy.std(count_grid_2d[valid_pixelpos]),
numpy.mean(count_grid_2d[valid_pixelpos]),
numpy.median(count_grid_2d[valid_pixelpos])
))
# Compute the number of input sources we compared to the reference catalog
n_searched = numpy.min([(chunk+1) * chunksize, src_cat.shape[0]])
significance = _max / _std
all_significance.append(significance)
all_max_mean_std.append([_max, _mean, _std, n_searched])
peak_position.append(peak_pos)
peak_position_np = numpy.array(peak_position)
# Keep track if we keep finding new matches
if (_max <= previous_max):
# print "This was a NO-GAIN chunk!"
no_gain_chunks += 1
previous_max = _max
# numpy.savetxt("peakpos_%s" % (str(debugangle)), peak_position_np)
# numpy.savetxt("mms_%s" % (str(debugangle)), numpy.array(all_max_mean_std))
# now determine the scatter in peak position across the last three chunks
peak_std = numpy.std(peak_position_np[-3:, :], axis=0)
if (create_debug_files2):
print("scatter in peak position:", peak_std, (peak_std<2).all())
print("significance:", significance)
#
# Check if the uncertainty in the peak position was reduced or not
# In good cases, the uncertainty only goes down, never up
#
if (chunk > 4):
if ((peak_std > previous_peak_std).any()):
if (create_debug_files2): print("Uncertainty in position is increasing, this is not good")
# Mark this run as invalid
significance = -1.
break
previous_peak_std = peak_std
if (n_chunks > 3 and chunk < 3):
# Try at least 3 chunks
if (create_debug_files2): print("--> need more chunks")
continue
elif (n_chunks <= 3 and chunk < n_chunks-1):
# If less than 3 chunks, only finish after the last chunk to
# include all/sufficient sources
if (create_debug_files2): print("--> waiting for last chunk")
continue
if ((peak_std < 2).all()): # scatter less than 2 arcsec in all directions
if (create_debug_files2): print("We found a solution!")
break
if (no_gain_chunks >= 2):
if (create_debug_files2): print("This seems to go no-where, aborting")
significance = -2.
break
# Average the peak position for which we find a small scatter
mean_peak_pos = numpy.mean(peak_position_np[-3:, :], axis=0)
# convert peak position back to degrees, and
# un-do the cos(dec) correction we applied in the beginning
offset = (mean_peak_pos / 3600.) / numpy.array([cos_dec, 1.])
final_significance = significance
# Compute the number of input sources we compared to the reference catalog
n_searched = numpy.min([(chunk+1) * chunksize, src_cat.shape[0]])
# Now that we have a solution, match the shifted source catalog
# and count the number of matches
n_matches = -1
if (final_significance >= -3): #0):
src_corrected = src_cat[:, 0:2] + (mean_peak_pos / 3600.) #(offset) * numpy.array([cos_dec, 1.])
corr_tree = scipy.spatial.cKDTree(src_corrected)
n_matches = corr_tree.count_neighbors(ref_tree, 2./3600., p=2) # match stars within 2 arcsec
logger.debug("done with entire cat (% 7s): max=%8.4f mean=%8.4f std=%8.4f --> sigma=%8.4f #matches=% 6d #searched=% 6d" % (
str(debugangle), _max, _mean, _std, final_significance, n_matches, n_searched))
return offset, n_matches, n_searched, _max, _mean, _std
def rotate_shift_catalog(src_cat, center, angle, shift=None, verbose = False):
"""
Apply a rotation and shift to a catalog.
"""
if (verbose):
print("\n\n\nIn rotate_shift_catalog")
print("angle =", angle)
print("shift =", shift)
print("center =", center)
print("src-cat=\n", src_cat[:3])
center_ra, center_dec = center
# print center_ra, center_dec
src_rotated = numpy.zeros(shape=(src_cat.shape[0],2))
src_rel_to_center = src_cat[:,0:2] - [center_ra, center_dec]
# print "\n\n\nDuring rotation"
# print "src-cat=\n",src_cat[:5,:]
# print "src-cat rel to center=\n",src_rel_to_center[:5,:]
# print "rotation end...\n\n"
# angles are given in arcmin
angle_rad = math.radians(angle)
if (verbose): print("angle radians =",angle_rad)
# print "in rot_shift: angle-rad=",angle_rad
# Account for cos(declination)
src_rel_to_center[:,0] *= math.cos(math.radians(center_dec))
if (verbose and shift is not None):
print("@@@@ shift rotation")
print("shift=", shift)
print("angle=", angle*60, "arcmin")
print("X=",math.cos(angle_rad) * shift[0] - math.sin(angle_rad) * shift[1])
print("y=",math.sin(angle_rad) * shift[0] + math.cos(angle_rad) * shift[1])
# Apply rotation
src_rotated[:,0] \
= math.cos(angle_rad) * src_rel_to_center[:,0] \
- math.sin(angle_rad) * src_rel_to_center[:,1]
src_rotated[:,1] \
= math.sin(angle_rad) * src_rel_to_center[:,0] \
+ math.cos(angle_rad) * src_rel_to_center[:,1] \
# Fix cos(declination)
src_rotated[:,0] /= math.cos(math.radians(center_dec))
# Add center position
src_rotated += [center_ra, center_dec]
# if requested, add shift
if (not type(shift) == type(None)):
src_rotated += shift
if (verbose):
print("src_rotated=\n", src_rotated[:3,0:2])
print("src-final=\n", src_rotated[:3],"\n\n\n")
src_output = src_cat.copy()
src_output[:,0:2] = src_rotated[:,0:2]
return src_output
def kd_match_catalogs(src_cat, ref_cat, matching_radius, max_count=1):
"""
Match two catalogs using kD-trees.
Parameters:
src_cat : ndarray
input catalog 1. first two columns have to be Ra/Dec
ref_cat : ndarray
input catalog 2. again, columns 1 &2 have to be Ra/Dec.
matching_radius : float
matching radius in arcsec. If two sources are closer than this, they are
considered a match.
max_count : int
Exclude all sources that have more than (max_count) matches.
Returns
-------
The matched catalog. The columns of this output catalog first contain
all columns from the input catalog 1, followed by all columns of the
matched sources in catalog 2. If no counterpart is found in catalog 2,
this source is omitted from the output catalog.
Currently only the first match is returned for each input source.
"""
src_cat = src_cat.copy()
ref_cat = ref_cat.copy()
max_declination = numpy.max(numpy.fabs(ref_cat[:,1]))
if (max_declination > 85): max_declination = 85
cos_dec = math.cos(math.radians(max_declination))
src_cat[:,0] *= cos_dec
ref_cat[:,0] *= cos_dec
src_tree = scipy.spatial.cKDTree(src_cat[:,0:2])
ref_tree = scipy.spatial.cKDTree(ref_cat[:,0:2])
# print src_cat[0:5]
# print ref_cat[0:5]
# Create an array to hold the matched catalog
output_cat = numpy.empty(shape=(src_cat.shape[0], src_cat.shape[1]+ref_cat.shape[1]))
# and insert the source catalog
n_src_columns = src_cat.shape[1]
output_cat[:,0:n_src_columns] = src_cat
# print output_cat[0:5]
# also create an array holding for which sources we found a match
match_found = numpy.zeros(shape=(src_cat.shape[0]))
# match the catalogs using a kD-tree
match_indices = src_tree.query_ball_tree(ref_tree, matching_radius, p=2)
# print(match_indices)
# print src_tree.count_neighbors(ref_tree, matching_radius, p=2)
# Now loop over all matches and merge the found matches
for cur_src in range(src_cat.shape[0]):
# Determine how many reference stars are close to this source
# Do not keep match if none or too many reference stars are nearby
n_matches = len(match_indices[cur_src])
if (n_matches <= 0 or n_matches > max_count):
continue
output_cat[cur_src, n_src_columns:] = ref_cat[match_indices[cur_src][0]]
match_found[cur_src] = 1
# Now eliminate all sources without matches
final_cat = output_cat[match_found == 1]
# Reverse the cos_declination fix from above
final_cat[:,0] /= cos_dec
final_cat[:,n_src_columns] /= cos_dec
return final_cat
def count_matches_parallelwrapper(work_queue, return_queue,
src_cat, ref_cat,
center_ra, center_dec,
pointing_error=(max_pointing_error/60.),
matching_radius=(4./3600.),
debugangle=None
):
"""
Just a small wrapper to enable parallel execution of `count_matches`.
"""
logger = logging.getLogger("ParCountMatch")
while (True):
task = work_queue.get()
if (task is None):
break
angle_id, angle = task
logger.debug("Starting work on angle %f deg / %f arcmin" % (angle,angle*60))
# print "Starting work on angle",angle,angle*60,"(deg/arcmin)"
src_rotated = rotate_shift_catalog(src_cat, (center_ra, center_dec), angle, None)
# print "Angle:",angle*60.," --> ",
#logger.debug("angle=%s src=%d ref=%d" % (angle, src_rotated.shape[0], ref_cat.shape[0]))
cm_data = count_matches(src_rotated, ref_cat,
pointing_error=pointing_error,
matching_radius=matching_radius,
debugangle=angle)
if (create_debug_files):
offset, final_significance, n_searched, _max, _mean, _std = cm_data
numpy.savetxt("ccmatch.cat%f" % (angle*60), src_rotated)
# print angle*60,offset
matched_cat = kd_match_catalogs(src_rotated[:,0:2]+offset, ref_cat[:,0:2], matching_radius, max_count=1)
numpy.savetxt("ccmatch.matched_%f" % (angle*60), matched_cat)
return_queue.put((angle_id, cm_data))
work_queue.task_done()
return
def find_best_guess(src_cat, ref_cat,
center_ra, center_dec,
pointing_error=(max_pointing_error/60.),
angle_max=5., #degrees
d_angle=3, # arcmin
matching_radius=5./3600.,
allow_parallel=True,
):
"""Find the best-guess astrometric correction by finding the shift and rotation
angle that yields the most matching stars by iterating over a number of
possible rotator angles.
Parameters
----------
src_cat : ndarray
Catalog of sources in ODI image
ref_cat : ndarray
Reference catalog of stars from, e.g., 2MASS
center_ra : double
center of rotation in RA - this has to be CRVAL1 to make the solution
compatible with the FITS WCS convention
center_dec : double
center of rotation in Dec - has to be CRVAL2
pointing_error : double
Maximum positional uncertainty, in degrees. Larger is safer, but takes
more time to compute and doesn't help if pointing errors are small.
angle_max : double or double[2]
Maximum uncertainty in the rotator angle position, in degrees. Can
either be a single angle or a float[2], e.g. [-1,2].
matching_radius : double
radius to use when computing the density of overlapping points. Smaller
numbers give slightly more accurate results, but larger values are
more reliable when frames show some distortion.
allow_parallel : Bool
Run the catalog matching in parallel (faster, recommended) or as a
single process (slower, needs fewer resources)
Returns
-------
The best_guess shift and rotation angle
"""
#
# Now loop over all stars in the source catalog and find nearby stars in the reference catalog
# Use a rather large matching radius for this step
#
#matching_radius = 1./60. # 1 arcmin
ref_tree = scipy.spatial.cKDTree(ref_cat)
#angle_max = 2.
#d_angle = 5.
logger = logging.getLogger('findbestguess')
if (angle_max is None):
# This means there's no rotation at all
n_angles = 1
all_results = numpy.zeros(shape=(1, 4))
all_results[0,0] = 0.
elif (type(angle_max) == int or type(angle_max) == float):
# Just a number given, assume the range is from -x to +x
n_angles = int(math.ceil((2 * angle_max) / (d_angle / 60.))) + 1
all_results = numpy.zeros(shape=(n_angles, 4))
all_results[:,0] = numpy.linspace(-angle_max, angle_max, n_angles)
elif (len(angle_max) == 2):
# Two angles given, interpret them as min and max
n_angles = int(math.ceil((angle_max[1] - angle_max[0]) / (d_angle / 60.))) + 1
all_results = numpy.zeros(shape=(n_angles, 4))
all_results[:,0] = numpy.linspace(angle_max[0], angle_max[1], n_angles)
else:
print("We don't know how to handle this case")
print("in find_best_guess, angle_max =",angle_max)
sys.exit(0)
if (allow_parallel):
processes = []
queue = multiprocessing.JoinableQueue()
queue._start_thread()
queue._thread.name = "QueueFeederThread_FindBestGuess_Jobs"
return_queue = multiprocessing.Queue()
return_queue._start_thread()
return_queue._thread.name = "QueueFeederThread_FindBestGuess_Results"
# Feed all angles to check into the queue
for cur_angle in range(n_angles):
angle = all_results[cur_angle,0]
queue.put((cur_angle, angle))
# worker_args = (queue, return_queue,
# src_cat, ref_cat, center_ra, center_dec,
# matching_radius,
# fine_radius,
# angle)
worker_args = {
"work_queue": queue,
"return_queue": return_queue,
"src_cat": src_cat,
"ref_cat": ref_cat,
"center_ra": center_ra,
"center_dec": center_dec,
"pointing_error": pointing_error,
"matching_radius": matching_radius,
"debugangle": None,
}
number_cpus = sitesetup.number_cpus
logger.debug("Running ccmatch on %d CPUs, hold on ..." % (number_cpus))
for i in range(number_cpus):
p = multiprocessing.Process(target=count_matches_parallelwrapper, kwargs=worker_args)
p.start()
processes.append(p)
# Also send a quit signal to each process
queue.put(None)
# And finally, collect all results
for i in range(n_angles):
returned = return_queue.get()
# cur_angle, n_matches, offset = returned
cur_angle, cm_data = returned
offset, n_matched, n_searched, _max, _mean, _std = cm_data
# Compute number of real matches as the fraction of stars
#n_matched = (_max - _mean) / n_searched
#if (final_significance < 0): n_matched = 0
all_results[cur_angle,1:3] = offset
all_results[cur_angle,3] = n_matched
# Join all processes to make sure they terminate alright
# without leaving zombie processes behind.
for p in processes:
p.join()
#
#
#
queue.close()
queue.join_thread()
return_queue.close()
return_queue.join_thread()
else:
for cur_angle in range(n_angles):
angle = all_results[cur_angle,0]
logger.debug("Starting work on angle %f deg / %f arcmin" % (angle,angle*60))
# print "Starting work on angle",angle,angle*60,"(deg/arcmin)"
src_rotated = rotate_shift_catalog(src_cat, (center_ra, center_dec), angle, None)
logger.debug("Angle: %f -->" % (angle*60.))
n_matches, offset = count_matches(src_rotated, ref_cat,
pointing_error=pointing_error,
matching_radius=matching_radius,
debugangle=angle)
if (create_debug_files):
numpy.savetxt("ccmatch.cat%f" % (angle*60), src_rotated)
print(angle*60,offset)
matched_cat = kd_match_catalogs(src_rotated[:,0:2]+offset, ref_cat[:,0:2], matching_radius, max_count=1)
numpy.savetxt("ccmatch.matched_%f" % (angle*60), matched_cat)
all_results[cur_angle,1:3] = offset
all_results[cur_angle,3] = n_matches
if (create_debug_files): numpy.savetxt("ccmatch.allresults.%d" % (pointing_error), all_results)
def format_results_histogram(all_results):
nmax = numpy.max(all_results[:,3])
if (nmax < 10): nmax=10
rel = all_results[:,3]/nmax
rel[rel<0]=0
all = [
"% 49d % 100d" % (0, nmax),
" angle dRA [deg] dDec [deg] matches |"+"-"*100+"|",
]
for i in range(all_results.shape[0]):
a = "%10.3f %12.6f %12.6f % 8d |%-100s|" % (
all_results[i,0],
all_results[i,1],
all_results[i,2],
all_results[i,3], "*"*int(rel[i]*100))
all.append(a)
all.append(" "*48+"|"+"-"*100+"|")
return "\n".join(all)
logger.debug("Combined Results from ccmatch:\n\n%s\n" % (format_results_histogram(all_results)))
#
# Now find the best solution (the one with the highest matched star density)
#
idx_best_angle = numpy.argmax(all_results[:,3])
best_guess = all_results[idx_best_angle]
logger.debug("Best guess: angle=%f arcmin" % (best_guess[0]*60.))
logger.debug(best_guess)
# print best_guess, "angle=",best_guess[0]*60.,"arcmin"
#
# Also determine a contrast as quality estimator
#
best_angle = best_guess[0]
# select all results with rotator angles differing by >20 arcmin
wrong_angles = numpy.fabs(all_results[:,0]-best_angle) > 40./60.
# random_matches = wrong_angles & (all_results[:,3] > 0)
# random_results = numpy.median(all_results[random_matches:, 3])
# contrast = (best_guess[3]-random_results) / random_results
# print "\n"*10,"Determining contrast:",random_matches,best_guess,"\n"*5
# number random matches:
n_random_matches = 1
if (numpy.sum(wrong_angles) > 0):
randoms = all_results[:,3][wrong_angles]
valid_count = randoms >= 0
if (numpy.sum(valid_count) > 0):
n_random_matches = numpy.median(randoms[valid_count]) #all_results[:,3][wrong_angles])
contrast = best_guess[3] / n_random_matches
#n_src = src_cat.shape[0]
if (n_random_matches >= 1):
contrast = (best_guess[3]-n_random_matches) / math.sqrt(n_random_matches) #* math.sqrt(n_src*best_guess[3])
else:
contrast = best_guess[3]
return best_guess, n_random_matches, contrast, all_results
def fit_best_rotation_shift(src_cat, ref_cat,
best_guess,
center_ra, center_dec,
matching_radius=(6./3600.)
):
"""
optimize the astroemtric solution by minimizing the difference betweeen
source and reference positions in a matched catalog.
"""
logger = logging.getLogger("OptimizeShiftRotation")
# print "initial best guess before optimizing", best_guess
src_rotated = rotate_shift_catalog(src_cat,
(center_ra, center_dec),
angle=best_guess[0],
shift=best_guess[1:3])
if (create_debug_files): numpy.savetxt("ccmatch.roughalign", src_rotated)
if (create_debug_files):
numpy.savetxt("ccm.src", src_cat)
numpy.savetxt("ccm.ref", ref_cat)
print("src-cat:", src_cat[:5])
print("ref-cat:", ref_cat[:5])
#
# Fix the cos(declination) problem
# Important when using these fixed coordinates: Undo this correction
# at the end to returning offsets in true RA and DEC !!!!!
#
max_declination = numpy.max(numpy.fabs(src_cat[:,1]))
if (max_declination > 85): max_declination = 85
cos_dec = math.cos(math.radians(max_declination))
ref_cat_cosdec = ref_cat.copy()
ref_cat_cosdec[:,0] *= cos_dec
src_rotated[:,0] *= cos_dec
if (create_debug_files):
numpy.savetxt("ref", ref_cat_cosdec)
numpy.savetxt("src", src_rotated)
#
# Match up stars from the source and reference catalog. Once we have a
# matched catalog we can optimize the WCS to minimize the errors between
# stars in each of the catalogs.
#
logger.debug("Matching catalogs")
ref_tree = scipy.spatial.cKDTree(ref_cat_cosdec)
src_tree = scipy.spatial.cKDTree(src_rotated)
matched_src_ref_idx = src_tree.query_ball_tree(ref_tree, matching_radius, p=2)
src_ref_pairs = numpy.ones(shape=(src_rotated.shape[0],4))
src_ref_pairs[:,0:2] = src_rotated[:,0:2]
src_ref_pairs[:,2:4] = numpy.nan
#
# Merge the two catalogs to make fitting easier
# Ignore all points with no or more than 1 closest match
#
# Important: While we match catalogs based on cos(dec)-fixed coordinates,
# the matched catalog contains the uncorrected coordinates. This is
# important to get real Ra/Dec offsets!
#
logger.debug("Merging catalogs for easier fitting")
for i in range(len(matched_src_ref_idx)):
n_close_stars = len(matched_src_ref_idx[i])
if (not n_close_stars == 1):
continue
src_ref_pairs[i, 2:4] = ref_cat[matched_src_ref_idx[i][0]]
if (create_debug_files): numpy.savetxt("ccmatch.srcrefmatched", src_ref_pairs)
#
# Further optimize the rotation angle by introducing the
# shift and rotation as free parameters and fitting to minimize
# the deviations
#
p_init = [best_guess[0], best_guess[1], best_guess[2]]
logger.debug("Minimizing offsets between source- and reference catalog")
logger.debug("Initial guess (angle, dx, dy): %s" % (str(p_init)))
# This is the function that computes the errors
# This is operating on real Ra/Dec data, so correct for cos(declination)
def difference_source_reference_cat(p, src_cat, ref_cat, center, for_fitting=False):
src_rotated = rotate_shift_catalog(src_cat, center,
angle=p[0],
shift=p[1:3])
diff = src_rotated - ref_cat
diff[:,0] *= numpy.cos(numpy.radians(ref_cat[:,1]))
if (for_fitting):
return diff.ravel()
return diff
#
# Eliminate all source stars without nearby/unique
# match in the reference catalog
#
valid_matches = numpy.isfinite(src_ref_pairs[:,2])
# numpy.savetxt("XXXX_src_ref_pairs.txt", src_ref_pairs)
n_valid_matches = numpy.sum(valid_matches)
center_radec = (center_ra, center_dec)
if (n_valid_matches <= 10):
logger.warning("Unable to optimize WCS, only found %d star-pairs (raw: %d)" % (
n_valid_matches, src_ref_pairs.shape[0]
))
best_fit = best_guess
matched_src = src_cat
matched_ref = src_ref_pairs[:,2:4]
else:
matched_src = src_cat[valid_matches]
matched_ref = src_ref_pairs[:,2:4][valid_matches]
args = (matched_src, matched_ref, center_radec, True)
if (create_debug_files):
numpy.savetxt("ccm.matched_src", matched_src)
numpy.savetxt("ccm.matched_ref", matched_ref)
logger.debug("Starting guess: %s (%s / %s)" % (
str(p_init), str(matched_src.shape), str(matched_ref.shape)))
fit = scipy.optimize.leastsq(difference_source_reference_cat,
p_init,
args=args,
full_output=1)
best_fit = fit[0]
logger.debug("optimized parameters: " + str(best_fit))
# print "\n\nbefore/after fit"
# print p_init
# print fit[0]
# # Compute uncertainty on the shift and rotation
# uncert = numpy.sqrt(numpy.diag(fit[1]))
# print uncert
# best_shift_rotation_solution = fit[0]
diff_afterfit = difference_source_reference_cat(best_fit,
matched_src,
matched_ref,
center_radec,
for_fitting=False)
if (create_debug_files): numpy.savetxt("ccmatch.diff_afterfit", diff_afterfit)
return_value = [best_fit[0],
best_fit[1], best_fit[2],
numpy.sum(valid_matches)
]
return return_value
def optimize_shift_rotation(p, guessed_match, hdulist, fitting=True):
"""
outdated, don't use.
"""
diff = numpy.zeros(shape=(guessed_match.shape[0],2))
n_start = 0
for ext in range(3): #len(hdulist)):
if (not is_image_extension(hdulist[ext])):
continue
ota_extension = hdulist[ext]
ota = int(ota_extension.header['FPPOS'][2:4])
# sources from this OTA
in_this_ota = (guessed_match[:,8] == ota)
number_src_in_this_ota = numpy.sum(in_this_ota)
# print number_src_in_this_ota
if (number_src_in_this_ota <= 0):
continue
ota_cat = guessed_match[in_this_ota]
# Read the WCS imformation from the fits file
wcs_poly = header_to_polynomial(ota_extension.header)
# And apply the current shift and rotation values