forked from abostroem/science_programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwcs.py
executable file
·1632 lines (1395 loc) · 62.2 KB
/
wcs.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
#! /usr/bin/env python
import sys
import os.path
import string
import math
import copy
from time import sleep
from Tkinter import *
import tkSimpleDialog
import tkFileDialog
import tkMessageBox
import numpy as N
try:
from stsci import ndimage
except ImportError:
import ndimage
try:
from stsci.convolve import boxcar
except ImportError:
from convolve import boxcar
import pyfits
from matplotlib import pylab
from matplotlib import cm
from matplotlib import ticker
from PIL import Image as PILImage
import celwcs
__version__ = "2012 November 6"
# reference image default min and max values
vmin = None
vmax = None
#opo image default max and min
vomin = None
vomax = None
# figure numbers for reference and public release images
REF_FIGURE = 1
OPO_FIGURE = 2
# indicates where subsampling was done for block averaging
LOCN_CORNER = 1
LOCN_CENTER = 2
# bin to approximately this many pixels in each axis
BINNED_SIZE = 2048.
RADIANStoDEGREES = 180. / math.pi
class ComputeWCS (object):
def __init__ (self, root):
self.root = root
self.ref = Image (REF_FIGURE) # Image object for reference image
self.opo = Image (OPO_FIGURE) # Image object for public release image
self.angle = None # Tkinter variable
self.xdata = None # mouse cursor X coordinate
self.ydata = None # mouse cursor Y coordinate
self.total_points = 0 # total number of points marked
self.npoints = 0 # excluding deleted points
self.refXY = {} # index: x,y in reference image
self.opoXY = {} # index: x,y in public release image
self.residuals = {} # index: x,y residuals of fit in ref
# additional WCS info for the public release image
self.opo_orientation = None # degrees
self.opo_scale = None # arcseconds per pixel
# This is a measure of the skew of the public release image,
# based on ratios of the CD matrix elements.
self.opo_skew = None
# The user may specify an alternate WCS ('A', 'B', etc.).
self.altWCS_index = 0
self.altWCS = None
# If this flag is set to True, that means we need to write the
# WCS info to stdout when the user quits. It will be False if
# the plate solution has not been computed yet or if the WCS info
# has already been written to an output file.
self.print_wcs = False # initial value
# Plate solution
self.x_coeff = None
self.y_coeff = None
self.x_inverse = None
self.y_inverse = None
self.frame = Frame (root)
self.frame.grid()
# Set interactive mode on, in case the user has 'interactive : False'
# in the ~/.matplotlib/matplotlibrc file.
pylab.ion()
# Get the name of the reference image, and display it.
dummy0 = Button (self.frame, text="display reference image",
command=self.refImage)
dummy0.grid (row=0, column=0, sticky=W)
# Get the name of the public release image, and display it.
dummy0 = Button (self.frame, text="display public-release image",
command=self.opoImage)
dummy0.grid (row=1, column=0, sticky=W)
# include a dummy label to separate sections of the frame
#dummy0 = Label (self.frame, text="")
#dummy0.grid (row=2, column=0, sticky=W)
# Option to set the min and max values and redisplay reference image.
dummy0 = Button (self.frame, text="set reference image limits",
command=self.refLimits)
dummy0.grid (row=2, column=0, sticky=W)
# Option to set the min and max values and redisplay opo image.
dummy0 = Button (self.frame, text="set public-release image limits",
command=self.opoLimits)
dummy0.grid (row=3, column=0, sticky=W)
# Option to rotate the reference image in 90-degree increments.
rotframe = Frame (self.frame)
self.angle = IntVar()
self.angle.set (0)
Radiobutton (rotframe, text="original orientation",
value=0, variable=self.angle,
command=self.rotateRefImage).grid (row=0, column=0, sticky=W)
Radiobutton (rotframe, text="90 degrees",
value=90, variable=self.angle,
command=self.rotateRefImage).grid (row=1, column=0, sticky=W)
Radiobutton (rotframe, text="180 degrees",
value=180, variable=self.angle,
command=self.rotateRefImage).grid (row=2, column=0, sticky=W)
Radiobutton (rotframe, text="270 degrees",
value=270, variable=self.angle,
command=self.rotateRefImage).grid (row=3, column=0, sticky=W)
rotframe.grid (row=4, column=0)
# The QUIT button.
dummy0 = Button (self.frame, text="QUIT", command=self.exitQuit)
dummy0.grid (row=5, column=0, sticky=W)
# Status line.
self.status_label = Label (self.frame,
text="Note: display reference image", fg="red")
self.status_label.grid (row=6, column=0, columnspan=2, sticky=W)
# Add points.
dummy1 = Button (self.frame, text="add points", command=self.addPoints)
dummy1.grid (row=0, column=1, sticky=W)
dummy1 = Button (self.frame, text="stop adding points",
command=self.stopAddingPoints)
dummy1.grid (row=1, column=1, sticky=W)
# Add points using the fit.
dummy1 = Button (self.frame, text="add points using fit",
command=self.addPointsUsingFit)
dummy1.grid (row=2, column=1, sticky=W)
# Delete a point.
dummy1 = Button (self.frame, text="delete a point",
command=self.delPoint)
dummy1.grid (row=3, column=1, sticky=W)
# Public-release image may be negative.
dummy1 = Button (self.frame, text="invert public-release image",
command=self.opoInvert)
dummy1.grid (row=4, column=1, sticky=W)
# Save coordinate info.
dummy1 = Button (self.frame, text="write wcs info to file",
command=self.writeWCS)
dummy1.grid (row=5, column=1, sticky=W)
# print info about using wcs
dummy2 = Button (self.frame, text="help", command=self.helpInfo)
dummy2.grid (row=0, column=2, sticky=W)
def exitQuit (self):
if self.print_wcs:
# Coordinate information has not been saved to a file.
# Do you want to save it?
save_them = tkMessageBox.askyesno ("parameters not saved",
"Coordinate parameters have not been saved to a file.\n" \
"Do you want to save them?", default="yes")
if save_them:
self.writeWCS()
self.print_wcs = False
if self.print_wcs:
self.writeInfo (sys.stdout)
self.frame.quit()
def helpInfo (self):
"""Print info about using wcs.py."""
print (
"""button "display reference image":
The reference image and public-release image must be specified before other
operations can be done.
Use this button to specify the name of the FITS-format reference image.
""")
print (
"""button "display public-release image":
Use this button to specify the name of the public-release image (the one
for which coordinate information is to be computed). The file format may be
FITS, TIFF, or JPG.
""")
print (
"""button "set reference image limits":
By default the image display includes the full range of data values in the
input. "set reference image limits" can be used to set the minimum and
maximum values for the reference image display.
""")
print (
"""buttons "original orientation", "90 degrees", "180 degrees", "270 degrees":
If the reference image and public-release image are rotated significantly
with respect to each other, it can be difficult to match stars in the two
images. This set of "radio" buttons lets you rotate the reference image by
a multiple of 90 degrees in order to approximately match the orientations
of the two images.
""")
print (
"""button "QUIT":
Exit the application, closing all windows.
If the coordinate information has not been written to a file (see "write wcs
info to file") and you choose not to do so at this time, the info will be
written to the standard output.
""")
print (
"""button "add points":
Click on this button to enter the mode for marking matching stars in the
two images.
Find a star (or other sharp feature) that is visible in both images.
Click on the star in the reference image, and then click on the star in
the public-release image. Repeat. In each image, the brightest pixel
near the cursor (with quadratic weighting centered on the cursor position)
will be taken as the location of the star. Exit this mode with "stop adding
points" or by right-clicking in the reference image.
After four or more pairs of matching stars have been marked, a fit will
be computed, and the residuals of the fit will be printed to the standard
output. Large "skew factors" or large residuals imply that one or more
points are mismatched (see "delete a point").
""")
print (
"""button "stop adding points":
Click on this button to exit the "add points" mode. However, due to a
bug in the code, you must also click once more in the reference image
before the program will actually leave the "add points" mode.
An alternative to using this button is to click in the reference image
with the right mouse button, which will exit the "add points" mode
immediately.
""")
print (
"""button "add points using fit":
After marking at least three pairs of matching stars, you can use this
button to enter an "add points" mode in which you only mark stars in the
reference image. The current fit between the two images will then be
used to compute the expected position of the matching star in the
public-release image, and the brightest pixel near that location (with
quadratic weighting, as usual) will be taken as the location of the
matching star in the public-release image.
You can exit this mode by using "stop adding points" or by right-clicking
with the mouse in the reference image.
""")
print (
"""button "delete a point":
If it looks as if a pair of stars has been marked incorrectly (i.e. the
points in the two images aren't really the same star), as implied by the
residuals of the fit, that point can be deleted. First exit "add points"
mode, then click "delete a point", then click on the point in the reference
image. The images will be redisplayed. Note that the numbers attached to
the other points will remain unchanged.
""")
print (
"""button "invert public-release image":
Sometimes a public-release image may be a negative image (though it may be
displayed as a positive image due to the look-up table). In that case when
you try to mark points ("add points") in that image, the plus sign showing
the location will not be centered on the star; this is because the program
looks for the brightest pixel, but the location would be a minimum in a
negative image. Click on this button to invert the image in memory.
""")
print (
"""button "write wcs info to file":
Click on this button to specify the name of a (new) text file to which the
WCS information will be written. If this is not done, you will also have
the opportunity to specify a file name after clicking on "QUIT" (and if you
still do not specify a file, the information will be written to the screen).
""")
if self.ref.data is None:
self.showStatus ("Note: display reference image")
elif self.opo.data is None:
self.showStatus ("Note: display public-release image")
else:
self.showStatus ("")
def showStatus (self, message):
"""Display message on the status line."""
self.status_label.config (text=message)
self.status_label.update_idletasks()
def refImage (self):
"""Get the name of the reference file, and display the image."""
self.ref.name = tkFileDialog.askopenfilename (
title="reference image", parent=self.frame)
if not self.ref.name:
return
self.showStatus ("reading reference image ...")
# Reset these, in case another image was loaded earlier.
self.total_points = 0
self.npoints = 0
self.refXY = {}
self.opoXY = {}
self.residuals = {}
self.angle.set (0)
(tempdata, self.ref.header) = pyfits.getdata (self.ref.name,
header=True)
shape = tempdata.shape
n = math.sqrt (shape[0] * shape[1])
block_size = int (round (float (n) / BINNED_SIZE))
block_size = max (1, block_size)
if block_size > 1:
self.ref.bin_locn = LOCN_CORNER
boxcar (tempdata, (block_size,block_size), output=tempdata)
self.ref.data = tempdata[0:-1:block_size,0:-1:block_size]
del tempdata
print "info: binning for reference image is", block_size
else:
self.ref.data = tempdata
self.ref.current_data = self.ref.data
# Set binning factor, compute mapping to binned pixels.
self.ref.setBinning (block_size)
if self.ref.Vmin is None:
self.ref.Vmin = N.minimum.reduce (self.ref.data.flat)
if self.ref.Vmax is None:
self.ref.Vmax = N.maximum.reduce (self.ref.data.flat)
self.displayRefImage()
(self.ref.xlow, self.ref.xhigh) = pylab.xlim()
(self.ref.ylow, self.ref.yhigh) = pylab.ylim()
shape = self.ref.data.shape
self.ref.marklen = self.ref.length_fraction * max (shape[0], shape[1])
self.ref.setSearchParameters()
if self.opo.data is None:
self.showStatus ("Note: display public-release image")
else:
self.showStatus ("")
# Read the WCS info from the reference image header.
self.getRefWCS()
def getRefWCS (self):
"""Get the WCS info for the reference image."""
hdr = self.ref.header
shape = self.ref.data.shape
# shape of the binned data
self.ref.bnaxis[0] = shape[1] # note: swapping axis numbers
self.ref.bnaxis[1] = shape[0]
# shape of the original data
self.ref.naxis[0] = hdr["naxis1"]
self.ref.naxis[1] = hdr["naxis2"]
no_wcs = False # initial value
alt = [""]
if hdr.has_key ("CRPIX1"): # likely to be present
if hdr.has_key ("WCSNAME"):
wcsname = [hdr["WCSNAME"]]
else:
wcsname = ["primary WCS"]
for a in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']:
if hdr.has_key ("CRPIX1" + a):
alt.append (a)
key = "WCSNAME" + a
if hdr.has_key (key):
wcsname.append (hdr[key])
else:
wcsname.append ("")
if len (alt) > 1:
# ask which WCS to use
self.inputAlt (alt, wcsname)
try:
# read WCS info from header
self.altWCS = alt[self.altWCS_index]
self.ref.wcs = celwcs.celwcs (hdr, alternate=self.altWCS)
(self.ref.crval, self.ref.crpix, self.ref.cd) = \
self.ref.wcs.getRADec_WCS()
self.ref.current_crpix = self.ref.crpix.copy()
self.ref.current_cd = self.ref.cd.copy()
except ValueError:
no_wcs = True
if no_wcs:
if self.altWCS:
tkMessageBox.showerror ("no WCS info",
"Alternate WCS '%s' not found in reference image %s" % \
(self.altWCS, self.ref.name))
else:
tkMessageBox.showerror ("no WCS info",
"WCS info not found in reference image %s" % self.ref.name)
pylab.close (REF_FIGURE)
self.ref.data = None
self.showStatus ("Note: redisplay reference image")
elif len (alt) > 1:
if self.altWCS:
print "info: using alternate WCS '%s'" % self.altWCS
else:
print "info: using primary WCS"
def inputAlt (self, alt, wcsname):
"""Let the user specify which WCS to read.
@param alt: list of WCS identifiers, "" for the primary or a single
letter for an alternate WCS
@type alt: list
@param wcsname: list of the name (or a null string) for each WCS
@type wcsname: list of strings
"""
self.alt_top = Toplevel (self.frame)
altframe = Frame (self.alt_top)
altframe.grid()
txt = Label (altframe, text="specify which WCS to use")
txt.grid (row=0, column=0, sticky=W)
scrollbar = Scrollbar (altframe, orient=VERTICAL)
scrollbar.grid (row=1, column=1, sticky=NS)
self.listbox = Listbox (altframe, height=15,
selectmode=SINGLE,
yscrollcommand=scrollbar.set)
self.listbox.grid (row=1, column=0, sticky=W)
scrollbar.config (command=self.listbox.yview)
for i in range (len (alt)):
self.listbox.insert (END, "%1s %s" % (alt[i], wcsname[i]))
self.listbox.bind ("<Button1-ButtonRelease>", self.setAlt)
self.root.wait_window (self.alt_top)
self.showStatus ("")
def setAlt (self, event):
value = self.listbox.curselection()
if len (value) < 1:
self.altWCS_index = ""
self.altWCS_index = int (value[0])
self.alt_top.destroy()
def opoImage (self):
"""Get the name of the public release file, and display the image."""
self.opo.name = tkFileDialog.askopenfilename (
title="public-release image", parent=self.frame)
if not self.opo.name:
return
self.showStatus ("reading public-release image ...")
# Reset these, in case another image was loaded earlier.
self.total_points = 0
self.npoints = 0
self.refXY = {}
self.opoXY = {}
self.residuals = {}
if self.opo.name.endswith (".fits") or \
self.opo.name.endswith (".fit"):
tempdata = pyfits.getdata (self.opo.name)
shape = tempdata.shape
self.opo.crpix[0] = shape[1] / 2.
self.opo.crpix[1] = shape[0] / 2.
n = math.sqrt (shape[0] * shape[1])
block_size = int (round (float (n) / BINNED_SIZE))
block_size = max (1, block_size)
if block_size > 1:
self.opo.bin_locn = LOCN_CORNER
boxcar (tempdata, (block_size,block_size), output=tempdata)
self.opo.data = tempdata[0:-1:block_size,0:-1:block_size]
del tempdata
print "info: binning for public-release image is", block_size
else:
self.opo.data = tempdata
else:
im = PILImage.open (self.opo.name)
size = im.size
self.opo.crpix[0] = size[0] / 2.
self.opo.crpix[1] = size[1] / 2.
if len (size) != 2:
raise RuntimeError, "The shape of %s is peculiar" % \
self.opo.name
if im.mode != "RGB":
tkMessageBox.showwarning ("unknown mode",
"the mode %s of %s might be a problem" % \
(im.mode, self.opo.name))
n = math.sqrt (size[0] * size[1])
block_size = int (round (float (n) / BINNED_SIZE))
block_size = max (1, block_size)
if block_size > 1:
self.opo.bin_locn = LOCN_CENTER
# make the block size an odd number
if (block_size // 2 * 2) == block_size:
block_size += 1
print "info: size of public-release image is", size
print "info: binning for public-release image is", block_size
oposize = [size[0] // block_size, size[1] // block_size]
# round up the X axis length (but not the Y axis)
if oposize[0] * block_size < size[0]:
oposize[0] += 1
if oposize[0] < 1 or oposize[1] < 1:
tkMessageBox.showwarning ("too small",
"can't handle public-release image %s" % self.opo.name)
print "ERROR: original size is", size
print "ERROR: binned size is", oposize
if oposize[0] < 1:
oposize[0] = 1
if oposize[1] < 1:
oposize[1] = 1
self.opo.data = N.zeros ((oposize[1], oposize[0], 3),
dtype=N.float32)
ylow = 0
yhigh = block_size
half_block = block_size // 2
for n in range (oposize[1]):
y = oposize[1] - 1 - n
if yhigh > size[1]:
yhigh = size[1]
if yhigh - ylow < block_size:
break
box = (0, ylow, size[0], yhigh)
region = im.crop (box)
regionstr = region.tostring()
tempdata = N.fromstring (regionstr, dtype=N.uint8)
tempdata = N.reshape (tempdata,
newshape=(yhigh-ylow, size[0], 3))
nregion = tempdata.astype (N.float32) / 255.
# block average each color separately;
temp0 = boxcar (nregion[:,:,0], (block_size,block_size))
temp1 = boxcar (nregion[:,:,1], (block_size,block_size))
temp2 = boxcar (nregion[:,:,2], (block_size,block_size))
# fill opo.data from the top down
if n == 0:
# this is a 1-D subarray
nelem = temp0[0,half_block:-1:block_size].shape[0]
# sample at the center of each block
self.opo.data[y,0:nelem,0] = \
temp0[half_block,half_block:-1:block_size]
self.opo.data[y,0:nelem,1] = \
temp1[half_block,half_block:-1:block_size]
self.opo.data[y,0:nelem,2] = \
temp2[half_block,half_block:-1:block_size]
ylow += block_size
yhigh += block_size
del tempdata
else:
print "info: size of public-release image is", size
imstr = im.tostring()
del im
nim = N.fromstring (imstr, dtype=N.uint8)
nim = N.reshape (nim, newshape=(size[1], size[0], 3))
del imstr
self.opo.data = nim[::-1,:,:].astype (N.float32) / 255.
del nim
# set binning factor, compute mapping to binned pixels.
self.opo.setBinning (block_size)
if self.opo.Vmin is None:
self.opo.Vmin = N.minimum.reduce (self.opo.data.flat)
if self.opo.Vmax is None:
self.opo.Vmax = N.maximum.reduce (self.opo.data.flat)
self.displayOPOImage()
(self.opo.xlow, self.opo.xhigh) = pylab.xlim()
(self.opo.ylow, self.opo.yhigh) = pylab.ylim()
shape = self.opo.data.shape
self.opo.marklen = self.opo.length_fraction * max (shape[0], shape[1])
self.opo.setSearchParameters()
# Mark the center of the image.
self.opo.drawPlus (x0=self.opo.crpix[0], y0=self.opo.crpix[1],
lenfactor=2, color="r", rescale=True)
if self.ref.data is None:
self.showStatus ("Note: display reference image")
else:
self.showStatus ("")
def refLimits (self):
global vmin, vmax
vmin = self.ref.Vmin
vmax = self.ref.Vmax
x = GetRefMinMax (self.frame, title="give min and max")
if x.vmin is None or x.vmax is None:
return
self.ref.Vmin = x.vmin
self.ref.Vmax = x.vmax
if self.ref.data is None:
self.refImage()
else:
self.displayRefImage()
if self.npoints > 0:
for i in range (1, self.total_points + 1):
if self.refXY.has_key (i):
(xr, yr) = self.refXY[i]
self.ref.drawPlus (xr, yr, index=i, color="c",
draw_it=False)
pylab.draw()
#pylab.xlim (self.ref.xlow, self.ref.xhigh)
#pylab.ylim (self.ref.ylow, self.ref.yhigh)
def opoLimits (self):
global vomin, vomax
vomin = self.opo.Vmin
vomax = self.opo.Vmax
x = GetOpoMinMax (self.frame, title="give min and max")
#x.vomin = 0
#x.vomax = 10
if x.vomin is None or x.vomax is None:
return
self.opo.Vmin = x.vomin
self.opo.Vmax = x.vomax
if self.opo.data is None:
self.opoImage()
else:
self.displayOPOImage()
if self.npoints > 0:
for i in range (1, self.total_points + 1):
if self.opoXY.has_key (i):
(xr, yr) = self.opoXY[i]
self.opo.drawPlus (xr, yr, index=i, color="c",
draw_it=False)
pylab.draw()
#pylab.xlim (self.opo.xlow, self.opo.xhigh)
#pylab.ylim (self.opo.ylow, self.opo.yhigh)
def rotateRefImage (self):
if self.ref.data is None:
self.refImage()
if self.ref.data is None:
tkMessageBox.showerror ("no reference image",
"you must specify a reference image before you can rotate it")
return
self.ref.rotangle = int (self.angle.get())
angle = float (self.ref.rotangle)
self.showStatus ("rotating reference image ...")
if self.ref.rotangle == 0:
self.ref.current_data = self.ref.data
self.ref.current_crpix = self.ref.crpix.copy()
self.ref.current_cd = self.ref.cd.copy()
else:
self.ref.current_data = ndimage.rotate (self.ref.data, angle)
if self.ref.rotangle == 90:
self.ref.current_crpix[0] = self.ref.crpix[1]
self.ref.current_crpix[1] = \
self.ref.bnaxis[0] * self.ref.block_size - \
self.ref.crpix[0] - 1.
cosa = 0.
sina = 1.
elif self.ref.rotangle == 180:
self.ref.current_crpix[0] = \
self.ref.bnaxis[0] * self.ref.block_size - \
self.ref.crpix[0] - 1.
self.ref.current_crpix[1] = \
self.ref.bnaxis[1] * self.ref.block_size - \
self.ref.crpix[1] - 1.
cosa = -1.
sina = 0.
elif self.ref.rotangle == 270:
self.ref.current_crpix[0] = \
self.ref.bnaxis[1] * self.ref.block_size - \
self.ref.crpix[1] - 1.
self.ref.current_crpix[1] = self.ref.crpix[0]
cosa = 0.
sina = -1.
else:
print "internal error, angle %d not supported" % \
self.ref.rotangle
m_rot = N.matrix (((cosa, -sina), (sina, cosa)), dtype=N.float64)
self.ref.current_cd = (N.matrix (self.ref.cd) * m_rot).A
# Update the celwcs object with the current crpix and CD matrix.
self.ref.wcs.setRADec_WCS (crpix=self.ref.current_crpix,
cd=self.ref.current_cd)
self.displayRefImage()
if self.opo.data is None:
self.showStatus ("Note: display public-release image")
else:
self.showStatus ("")
# xxx It would be better to modify these rather than clobbering them.
if self.total_points > 0:
self.total_points = 0
self.npoints = 0
self.refXY = {}
self.opoXY = {}
if self.opo.data is not None:
self.displayOPOImage()
self.opo.drawPlus (x0=self.opo.crpix[0], y0=self.opo.crpix[1],
lenfactor=2, color="r", draw_it=False)
pylab.xlim (self.opo.xlow, self.opo.xhigh)
pylab.ylim (self.opo.ylow, self.opo.yhigh)
def opoInvert (self):
"""Invert the public release image."""
if self.opo.data is not None:
self.opo.data = 1. - self.opo.data
self.refreshImageDisplays()
def addPoints (self):
self.addPointsDone = False
self.showStatus ("Mark points, reference first")
pylab.figure (REF_FIGURE)
(self.ref.xlow, self.ref.xhigh) = pylab.xlim()
(self.ref.ylow, self.ref.yhigh) = pylab.ylim()
pylab.figure (OPO_FIGURE)
(self.opo.xlow, self.opo.xhigh) = pylab.xlim()
(self.opo.ylow, self.opo.yhigh) = pylab.ylim()
while not self.addPointsDone:
self.read_mouse_xy (REF_FIGURE)
if self.addPointsDone:
break
(x0_b, y0_b) = self.locatePoint (self.ref.current_data,
self.xdata, self.ydata,
search=self.ref.search, weight=self.ref.weight)
if x0_b is None:
tkMessageBox.showinfo ("try again",
"the cursor was outside the image\ntry again")
self.showStatus ("add points: mark in reference image")
continue
else:
(x0, y0) = self.ref.fromBinned ((x0_b, y0_b))
self.refXY[self.total_points+1] = (x0, y0)
self.ref.drawPlus (x0, y0, index=self.total_points+1,
color="c")
self.showStatus ("add points: mark in public-release image")
pylab.xlim (self.ref.xlow, self.ref.xhigh)
pylab.ylim (self.ref.ylow, self.ref.yhigh)
self.read_mouse_xy (OPO_FIGURE)
(x0_b, y0_b) = self.locatePoint (self.opo.data,
self.xdata, self.ydata,
search=self.opo.search, weight=self.opo.weight)
while x0_b is None:
tkMessageBox.showinfo ("try again",
"the cursor was outside the image\ntry again")
self.showStatus ("add points: mark in public-release image")
self.read_mouse_xy (OPO_FIGURE)
(x0_b, y0_b) = self.locatePoint (self.opo.data,
self.xdata, self.ydata,
search=self.opo.search, weight=self.opo.weight)
(x0, y0) = self.opo.fromBinned ((x0_b, y0_b))
self.opoXY[self.total_points+1] = (x0, y0)
self.opo.drawPlus (x0, y0, index=self.total_points+1, color="c")
self.showStatus ("add points: mark in reference image")
pylab.xlim (self.opo.xlow, self.opo.xhigh)
pylab.ylim (self.opo.ylow, self.opo.yhigh)
self.total_points += 1
self.npoints += 1
if self.npoints >= 3:
# Do a plate solution, compute residuals, compute WCS.
self.computeOpoWCS()
self.showResiduals()
self.showStatus ("")
def stopAddingPoints (self):
# xxx This isn't sufficient; I have to click one additional time in
# the reference image window. How can this be fixed?
self.addPointsDone = True
self.showStatus ("click once more in reference image (anywhere)")
def addPointsUsingFit (self):
if self.npoints < 3:
tkMessageBox.showwarning ("not enough points",
"you must mark at least three points before using this option")
self.showStatus ("")
return
self.addPointsDone = False
self.showStatus ("Mark points in reference image")
pylab.figure (REF_FIGURE)
(self.ref.xlow, self.ref.xhigh) = pylab.xlim()
(self.ref.ylow, self.ref.yhigh) = pylab.ylim()
pylab.figure (OPO_FIGURE)
(self.opo.xlow, self.opo.xhigh) = pylab.xlim()
(self.opo.ylow, self.opo.yhigh) = pylab.ylim()
while not self.addPointsDone:
self.read_mouse_xy (REF_FIGURE)
if self.addPointsDone:
break
# _b in a variable name for a coordinate means that the
# coordinate is in binned pixels
(x0_b_ref, y0_b_ref) = self.locatePoint (self.ref.current_data,
self.xdata, self.ydata,
search=self.ref.search, weight=self.ref.weight)
if x0_b_ref is None:
tkMessageBox.showinfo ("outside image",
"the cursor was outside the image\ntry again")
continue
(x0_ref, y0_ref) = self.ref.fromBinned ((x0_b_ref, y0_b_ref))
# this is the predicted position in the public-release image
(x_fit, y_fit) = self.refToOpo (x0_ref, y0_ref)
if x_fit is None:
self.showStatus ("")
return
# predicted position in public-release image, but in binned pixels
(x_b_fit, y_b_fit) = self.opo.toBinned ((x_fit, y_fit))
(x0_b_opo, y0_b_opo) = self.locatePoint (self.opo.data,
x_b_fit, y_b_fit,
search=self.opo.search, weight=self.opo.weight)
if x0_b_opo is None:
tkMessageBox.showinfo ("outside image",
"the corresponding point is outside " \
"the public-release image\ntry again")
continue
(x0_opo, y0_opo) = self.opo.fromBinned ((x0_b_opo, y0_b_opo))
self.refXY[self.total_points+1] = (x0_ref, y0_ref)
self.opoXY[self.total_points+1] = (x0_opo, y0_opo)
self.ref.drawPlus (x0_ref, y0_ref,
index=self.total_points+1, color="c")
pylab.xlim (self.ref.xlow, self.ref.xhigh)
pylab.ylim (self.ref.ylow, self.ref.yhigh)
self.opo.drawPlus (x0_opo, y0_opo,
index=self.total_points+1, color="c")
pylab.xlim (self.opo.xlow, self.opo.xhigh)
pylab.ylim (self.opo.ylow, self.opo.yhigh)
self.total_points += 1
self.npoints += 1
if self.npoints >= 3:
# Do a plate solution, compute residuals, compute WCS.
self.computeOpoWCS()
self.showResiduals()
self.showStatus ("")
def delPoint (self):
if self.npoints < 1:
tkMessageBox.showinfo ("no points",
"There are no marked points to delete.")
return
pylab.figure (REF_FIGURE)
(self.ref.xlow, self.ref.xhigh) = pylab.xlim()
(self.ref.ylow, self.ref.yhigh) = pylab.ylim()
pylab.figure (OPO_FIGURE)
(self.opo.xlow, self.opo.xhigh) = pylab.xlim()
(self.opo.ylow, self.opo.yhigh) = pylab.ylim()
self.showStatus ("Mark point in reference image")
# Note that we work with binned pixel coordinates here.
self.read_mouse_xy (REF_FIGURE)
nfound = 0
mindist = None
index = -1
for i in range (1, self.total_points + 1):
if self.refXY.has_key (i):
(xr, yr) = self.ref.toBinned (self.refXY[i])
distance = math.sqrt ((xr - self.xdata)**2 +
(yr - self.ydata)**2)
if distance <= self.ref.search:
nfound += 1
if mindist is None or distance < mindist:
mindist = distance
index = i
if nfound > 0:
if nfound > 1:
tkMessageBox.showwarning ("ambiguous",
"deleting one of %d nearby points" % nfound)
self.delThisIndex (index)
else:
tkMessageBox.showinfo ("not found",
"No nearby marked point found in reference image.")
self.showStatus ("")
def delThisIndex (self, index):
"""Delete the point with the specified index."""
del (self.refXY[index])
del (self.opoXY[index])
if self.residuals.has_key (index):
del (self.residuals[index])
self.npoints -= 1
self.showStatus ("point deleted (refreshing displays) ...")
self.refreshImageDisplays()
self.computeOpoWCS() # recompute with fewer points
self.showResiduals()
self.showStatus ("")
def refreshImageDisplays (self):
self.displayRefImage()
self.displayOPOImage()
self.opo.drawPlus (x0=self.opo.crpix[0], y0=self.opo.crpix[1],
lenfactor=2, color="r", draw_it=False)
for i in range (1, self.total_points + 1):
if self.refXY.has_key (i):
(xr, yr) = self.refXY[i]
self.ref.drawPlus (xr, yr, index=i, color="c", draw_it=False)
pylab.draw()
pylab.xlim (self.ref.xlow, self.ref.xhigh)
pylab.ylim (self.ref.ylow, self.ref.yhigh)
for i in range (1, self.total_points + 1):
if self.opoXY.has_key (i):
(xo, yo) = self.opoXY[i]
self.opo.drawPlus (xo, yo, index=i, color="c", draw_it=False)
pylab.draw()
pylab.xlim (self.opo.xlow, self.opo.xhigh)
pylab.ylim (self.opo.ylow, self.opo.yhigh)
def showResiduals (self):
if self.npoints < 3:
return
if self.residuals.has_key ("rms_x"):
if self.npoints > 3:
rms = math.sqrt (self.residuals["rms_x"]**2 +
self.residuals["rms_y"]**2)
print "RMS = %.3g; skew factor = %.3f" % (rms, self.opo_skew)
else:
print "skew factor = %.3f" % self.opo_skew
if self.npoints > 3:
print "residuals of fit:"
for i in range (1, self.total_points + 1):
if self.residuals.has_key (i):
(x_resid, y_resid) = self.residuals[i]
print "%d: %5.2f" % \
(i, math.sqrt (x_resid**2 + y_resid**2))
def locatePoint (self, image, x0, y0, search=10, weight=None):
"""Find the brightest point near x0, y0."""
# Note that these are binned pixel coordinates.
shape = image.shape
nx = shape[1]
ny = shape[0]
x0 = int (round (x0))
y0 = int (round (y0))
x1 = x0 - search
y1 = y0 - search
x2 = x1 + 2*search+1
y2 = y1 + 2*search+1
if x1 < 0 or y1 < 0 or x2 >= nx or y2 >= ny:
return (None, None)
region = image[y1:y2,x1:x2].copy().astype (N.float32)
# Use quadratic weighting centered on the user-specified
# location to reduce the chance of finding a bright point
# that is close to but offset from the intended target.
region *= weight
position = ndimage.maximum_position (region)
x = position[1] + x1
y = position[0] + y1
return (x, y)
def computeOpoWCS (self):
if self.opo.wcs is None:
# Assign initial values.