forked from abostroem/science_programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcelwcs.py
executable file
·2017 lines (1651 loc) · 73.3 KB
/
celwcs.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 types
import math
import re
import copy
import numpy as N
import pyfits
__version__ = "2007 September 5"
DEGREEStoRADIANS = math.pi / 180. # convert degrees to radians
TINY = 1.e-10 # nearly zero
# WCS keywords have different names for these three different ways
# of storing image data. The name gives the term by which these
# are identified in the FITS documents.
PRIMARY_ARRAY = 1 # a primary HDU or an IMAGE HDU
BINTABLE_ARRAY = 2 # an array in one row of a column of arrays
PIXEL_LIST = 3 # a tabulated list of pixels, using two columns
# Distinguish between zenithal projections and others, because the
# default values for the longitude and latitude of the fiducial point
# are not the same.
ZENITHAL_PROJ = ["AZP", "SZP", "TAN", "STG", "SIN", "ARC", "ZPN", "ZEA", "AIR"]
CYLINDRICAL_PROJ = ["CYP", "CEA", "CAR", "MER", "SFL", "PAR", "MOL", "AIT"]
CONIC_PROJ = ["COP", "COE", "COD", "COO"]
OTHER_PROJ = ["BON", "PCO", "TSC", "CSC", "QSC", "HPX"]
SPHERICAL_MAP_PROJ = ZENITHAL_PROJ + CYLINDRICAL_PROJ + CONIC_PROJ + OTHER_PROJ
def readCoords (input, col=(0,1), extension=1):
"""Read coordinates from a FITS table.
For a table containing these three coordinate vectors:
x1 y1
x2 y2
x3 y3
the output would be:
[[x1 x2 x3]
[y1 y2 y3]]
If the table contained only the first row, the output would be:
[x1 y1]
@param input: name of a FITS file containing a bintable (or table).
@type input: string
@param col: the names or numbers (zero indexed) of columns in the table
containing the coordinates; the default is to read the first two
columns as X and Y.
@type col: tuple
@param extension: the number or EXTNAME of the extension containing
the table.
@type extension: int or string
@return: an array of coordinates read from the table, in a format suitable
for use as input to either frompixel() or topixel(); if there is only
one row in the table, the function value will be a single vector
@rtype: ndarray
"""
if type (extension) == types.IntType and extension < 1:
raise ValueError, "'extension' must be greater than zero"
fd = pyfits.open (input)
if type (extension) == types.IntType and len (fd) < extension+1:
fd.close()
raise ValueError, "extension %d does not exist in input file" % \
extension
if fd[extension].data is None or len (fd[extension].data) < 1:
fd.close()
errmess = "no data in extension " + str (extension)
raise ValueError, errmess
nrows = len (fd[extension].data)
coldata = []
for column in col:
if nrows == 1:
coldata.append (fd[extension].data.field (column)[0])
else:
coldata.append (fd[extension].data.field (column))
return N.array (coldata)
##############################################################################
class WCSbase(object):
"""Base object for WCS objects.
Contains basic functionality such as header parsing."""
def __init__ (self, hdr, alternate=None, column=None):
# this is a list of all WCS keywords in hdr
self.keywords = []
# set keyword_translate attribute
self._setKeywordDict()
# set attributes for names of spherical projection functions
# and (eventually) distortion functions
self._setFunctionAttributes()
# copy arguments to attributes, with some checking and interpretation
self._saveArguments (hdr, alternate, column)
# find the dimension of the WCS from a keyword
self._findWcsAxes (hdr)
# create attribute arrays with the right size and default values
self._initializeWcsAttributes()
# copy keyword values to attributes
self._extractWcsKeywords (hdr)
def _setKeywordDict (self):
"""Set the mapping from header keyword to attribute name."""
self.keyword_translate = {
"WCSAXES": "wcsaxes", # primary array keywords
"CTYPE": "ctype",
"CUNIT": "cunit",
"CRVAL": "crval",
"CDELT": "cdelt",
"CRPIX": "crpix",
"PC": "pc",
"CD": "cd",
"PV": "pv", # also bintable array
"PS": "ps", # also bintable array
"WCSNAME": "wcsname",
"CRDER": "crder",
"CSYER": "csyer",
"CROTA": "crota",
"LONPOLE": "lonpole",
"LATPOLE": "latpole",
"EQUINOX": "equinox",
"MJD-OBS": "mjd_obs",
"RADESYS": "radesys",
"WCAX": "wcsaxes", # bintable array
"CTYP": "ctype",
"CUNI": "cunit",
"CRVL": "crval",
"CDLT": "cdelt",
"CRPX": "crpix",
"CTY": "ctype",
"CUN": "cunit",
"CRV": "crval",
"CDE": "cdelt",
"CRP": "crpix",
"V": "pv",
"S": "ps",
"CRD": "crder",
"CSY": "csyer",
"CROT": "crota",
"WCST": "wcst",
"WCSX": "wcsx",
"LONP": "lonpole", # both bintable array and pixel list
"LATP": "latpole",
"EQUI": "equinox",
"MJDOB": "mjd_obs",
"RADE": "radesys",
"WCSN": "wcsname",
"TCTYP": "ctype", # pixel list
"TCUNI": "cunit",
"TCRVL": "crval",
"TCDLT": "cdelt",
"TCRPX": "crpix",
"TCTY": "ctype",
"TCUN": "cunit",
"TCRV": "crval",
"TCDE": "cdelt",
"TCRP": "crpix",
"TP": "pc",
"TPC": "pc",
"TC": "cd",
"TCD": "cd",
"TV": "pv",
"TPV": "pv",
"TS": "ps",
"TPS": "ps",
"TCRD": "crder",
"TCSY": "csyer",
"TCROT": "crota"}
def _setFunctionAttributes (self):
"""Assign the attributes for spherical projection functions."""
# These will be set to one pair of the functions listed below.
self._projection_fcn = None
self._inverse_fcn = None
self.TAN_projection = self._tanProj
self.TAN_inverse = self._tanInvProj
# xxx not implemented yet
self.AZP_projection = self._azpProj
self.AZP_inverse = self._azpInvProj
self.STG_projection = self._stgProj
self.STG_inverse = self._stgInvProj
self.SIN_projection = self._sinProj
self.SIN_inverse = self._sinInvProj
self.ARC_projection = self._arcProj
self.ARC_inverse = self._arcInvProj
self.SFL_projection = self._sflProj
self.SFL_inverse = self._sflInvProj
self.PAR_projection = self._parProj
self.PAR_inverse = self._parInvProj
self.MOL_projection = self._molProj
self.MOL_inverse = self._molInvProj
self.AIT_projection = self._aitProj
self.AIT_inverse = self._aitInvProj
self.MER_projection = self._merProj
self.MER_inverse = self._merInvProj
self.COP_projection = self._copProj
self.COP_inverse = self._copInvProj
self.COE_projection = self._coeProj
self.COE_inverse = self._coeInvProj
self.BON_projection = self._bonProj
self.BON_inverse = self._bonInvProj
def _tanProj (self, phi, theta):
"""gnomonic (tangent) projection"""
r = N.tan (self.lat_0 - theta)
x = r * N.sin (phi)
y = -r * N.cos (phi)
return (x, y)
def _tanInvProj (self, x, y):
"""inverse gnomonic (tangent) projection"""
r = N.sqrt (x**2 + y**2)
theta = self.lat_0 - N.arctan (r)
phi = N.arctan2 (x, -y)
return (phi, theta)
def _azpProj (self, phi, theta):
"""zenithal perspective projection"""
# xxx not implemented yet
print "\nERROR: AZP not yet implemented"
r = N.tan (self.lat_0 - theta)
x = r * N.sin (phi)
y = -r * N.cos (phi)
return (x, y)
def _azpInvProj (self, x, y):
"""inverse zenithal perspective projection"""
# xxx not implemented yet
print "\nERROR: Inverse AZP not yet implemented"
r = N.sqrt (x**2 + y**2)
theta = self.lat_0 - N.arctan (r)
phi = N.arctan2 (x, -y)
return (phi, theta)
def _stgProj (self, phi, theta):
"""stereographic projection"""
r = N.tan ((self.lat_0 - theta) / 2.)
x = r * N.sin (phi)
y = -r * N.cos (phi)
return (x, y)
def _stgInvProj (self, x, y):
"""inverse stereographic projection"""
r = N.sqrt (x**2 + y**2)
theta = self.lat_0 - 2. * N.arctan (r)
phi = N.arctan2 (x, -y)
return (phi, theta)
def _sinProj (self, phi, theta):
"""sine projection"""
r = N.cos (theta)
x = r * N.sin (phi)
y = -r * N.cos (phi)
return (x, y)
def _sinInvProj (self, x, y):
"""inverse sine projection"""
r = N.sqrt (x**2 + y**2)
theta = N.arccos (r)
phi = N.arctan2 (x, -y)
return (phi, theta)
def _arcProj (self, phi, theta):
"""zenithal equidistant projection"""
r = self.lat_0 - theta
x = r * N.sin (phi)
y = -r * N.cos (phi)
return (x, y)
def _arcInvProj (self, x, y):
"""inverse zenithal equidistant projection"""
r = N.sqrt (x**2 + y**2)
theta = self.lat_0 - r
phi = N.arctan2 (x, -y)
return (phi, theta)
def _sflProj (self, phi, theta):
"""Sanson-Flamsteed projection"""
x = phi * N.cos (theta)
y = theta
return (x, y)
def _sflInvProj (self, x, y):
"""inverse Sanson-Flamsteed projection"""
theta = y
phi = x / N.cos (y)
return (phi, theta)
def _parProj (self, phi, theta):
"""parabolic projection"""
x = phi * (2. * N.cos (2. * theta / 3.) - 1.)
y = N.pi * N.sin (theta / 3.)
return (x, y)
def _parInvProj (self, x, y):
"""inverse parabolic projection"""
theta = 3. * N.arcsin (y / N.pi)
phi = x / (1. - 4. * (y / N.pi)**2)
return (phi, theta)
def _molProj (self, phi, theta):
"""Mollweide's projection"""
gamma = self.molGamma (theta, nloops=10)
x = phi * (2. * N.sqrt (2.) / N.pi) * N.cos (gamma)
y = N.sqrt (2.) * N.sin (gamma)
return (x, y)
def _molInvProj (self, x, y):
"""inverse Mollweide's projection"""
theta = N.arcsin (2. * N.arcsin (y / N.sqrt (2.)) / N.pi + \
y * N.sqrt (2. - y**2) / N.pi)
phi = N.pi * x / (2. * N.sqrt (2. - y**2))
return (phi, theta)
def _molGamma (self, theta, nloops=10):
"""Compute gamma for Mollweide's projection
Given theta, we need to solve the following for gamma:
sin (theta) = (2*gamma + sin (2*gamma)) / pi
"""
gamma = theta * N.pi / 4. # first approximation
for i in range (nloops):
test_theta = N.arcsin ((2. * gamma + N.sin (2. * gamma)) / N.pi)
slope = (N.pi / 2.) * N.cos (test_theta) / \
(1. + N.cos (2. * gamma))
gamma += (theta - test_theta) * slope
return gamma
def _aitProj (self, phi, theta):
"""Hammer-Aitoff projection"""
gamma = N.sqrt (2. / (1. + N.cos (theta) * N.cos (phi / 2.)))
x = 2. * gamma * N.cos (theta) * N.sin (phi / 2.)
y = gamma * N.sin (theta)
return (x, y)
def _aitInvProj (self, x, y):
"""inverse Hammer-Aitoff projection"""
z = N.sqrt (1. - (x/4.)**2 - (y/2.)**2)
theta = N.arcsin (y * z)
phi = 2. * N.arctan2 (x * z/2., 2.*z**2 - 1.)
return (phi, theta)
def _merProj (self, phi, theta):
"""Mercator projection"""
x = phi
y = N.log (N.tan ((N.pi/2. + theta) / 2.))
return (x, y)
def _merInvProj (self, x, y):
"""inverse Mercator projection"""
theta = 2. * N.arctan (N.exp (y)) - N.pi / 2.
phi = x
return (phi, theta)
def _copProj (self, phi, theta):
"""conic perspective projection"""
(C, cot_theta_a, cos_eta, y0) = self.copInit()
r = cos_eta * (cot_theta_a - N.tan (theta - self.theta_a))
x = r * N.sin (C * phi)
y = -r * N.cos (C * phi) + y0
return (x, y)
def _copInvProj (self, x, y):
"""inverse conic perspective projection"""
(C, cot_theta_a, cos_eta, y0) = self.copInit()
r = N.sign (self.theta_a) * N.sqrt (x**2 + (y0 - y)**2)
theta = self.theta_a + N.arctan (cot_theta_a - r / cos_eta)
phi = N.arctan2 (x / r, (y0 - y) / r) / C
return (phi, theta)
def _copInit (self):
"""Compute some parameters for conic perspective projection"""
if self.theta_a is None:
raise RuntimeError, "theta_a is undefined " \
"(use the appropriate PV keyword)"
if self.theta_a == 0. or abs (self.theta_a) == math.pi / 2.:
raise ValueError, "theta_a = %.10g (from PV keyword) " \
"is not supported for conic projection" % self.theta_a
C = math.sin (self.theta_a)
cot_theta_a = 1. / math.tan (self.theta_a)
cos_eta = math.cos (self.eta)
y0 = cos_eta * cot_theta_a
return (C, cot_theta_a, cos_eta, y0)
def _coeProj (self, phi, theta):
"""conic equal area projection"""
(C, sin_theta1, sin_theta2, gamma, y0) = self.coeInit()
r = (2. / gamma) * N.sqrt (1. + \
sin_theta1 * sin_theta2 - gamma * N.sin (theta))
x = r * N.sin (C * phi)
y = -r * N.cos (C * phi) + y0
return (x, y)
def _coeInvProj (self, x, y):
"""inverse conic equal area projection"""
(C, sin_theta1, sin_theta2, gamma, y0) = self.coeInit()
r = N.sign (self.theta_a) * N.sqrt (x**2 + (y0 - y)**2)
theta = N.arcsin (1. / gamma + sin_theta1 * sin_theta2 / gamma - \
gamma * (r/2.)**2)
phi = N.arctan2 (x / r, (y0 - y) / r) / C
return (phi, theta)
def _coeInit (self):
"""Compute some parameters for conic equal area projection"""
if self.theta_a is None:
raise RuntimeError, "theta_a is undefined " \
"(use the appropriate PV keyword)"
theta1 = self.theta_a - self.eta
theta2 = self.theta_a + self.eta
sin_theta1 = math.sin (theta1)
sin_theta2 = math.sin (theta2)
gamma = sin_theta1 + sin_theta2
C = gamma / 2.
y0 = (2. / gamma) * math.sqrt (1. + \
sin_theta1 * sin_theta2 - gamma * math.sin (self.theta_a))
return (C, sin_theta1, sin_theta2, gamma, y0)
def _bonProj (self, phi, theta):
"""Bonne's equal area projection"""
y0 = self.theta_a + 1. / math.tan (self.theta_a)
r = y0 - theta
A = (phi / r) * N.cos (theta)
x = r * N.sin (A)
y = -r * N.cos (A) + y0
return (x, y)
def _bonInvProj (self, x, y):
"""inverse Bonne's equal area projection"""
y0 = self.theta_a + 1. / math.tan (self.theta_a)
r = N.sign (self.theta_a) * N.sqrt (x**2 + (y0 - y)**2)
A = N.arctan2 (x / r, (y0 - y) / r)
theta = y0 - r
phi = A * r / N.cos (theta)
return (phi, theta)
def _saveArguments (self, hdr, alternate, column):
"""Check arguments, and copy to attributes.
@param hdr: a set of FITS keywords and values (values are case
sensitive, but keyword names are not)
@type hdr: pyfits.Header object or dictionary
@param alternate: a single letter, specifying an alternate WCS
(default is blank, for primary WCS)
@type alternate: string (one letter) or None
@param column: for an image array, this should be None;
for an array in a table column, this should be a single column
number (zero indexed);
for a tabulated list of pixels in two columns, this should be a
list giving the column numbers for right ascension (longitude)
and declination (latitude)
@type column: None, int, or list of two ints
"""
if not isinstance (hdr, (pyfits.Header, types.DictionaryType)):
raise TypeError, \
"'hdr' must be a Header object or a dictionary of keywords and values"
self.hdr = hdr
if alternate is None or len (alternate) < 1 or alternate == " ":
self.alternate = ""
elif len (alternate) > 1:
raise ValueError, "'alternate' must be a single character or blank"
else:
self.alternate = alternate.upper()
if column is None:
self.image_rep = PRIMARY_ARRAY
self.column = None
self.tab_columns = None
else:
if isinstance (column, (types.ListType, types.TupleType)):
if len (column) < 2:
raise ValueError, \
" when 'column' is a list it must contain two or more column numbers"
elif column[0] < 0 or column[1] < 0:
raise ValueError, \
"the column numbers in 'column' must be non-negative"
self.image_rep = PIXEL_LIST
self.column = None
self.tab_columns = list (column)
else:
if column < 0:
raise ValueError, \
"column number 'column' must be non-negative"
self.image_rep = BINTABLE_ARRAY
self.column = column
self.tab_columns = None
def _findWcsAxes (self, hdr):
"""Find the dimension of the WCS system.
@param hdr: a set of FITS keywords and values (values are case
sensitive, but keyword names are not)
@type hdr: pyfits.Header object or dictionary
The dimension will be taken from keyword WCSAXES if it is present, or
NAXIS, or the dimension will be set to 2 if neither naxis nor wcsaxes
is found in hdr.
For a pixel list, the user is expected to supply a list of column
numbers, one for each axis, so the length of that list is the
dimension of the WCS.
"""
self.naxis = 2 # default
items = hdr.items()
if self.image_rep == PIXEL_LIST:
self.wcsaxes = len (self.tab_columns)
for (keyword, value) in items:
if keyword.upper() == "NAXIS":
self.naxis = value
break
if self.wcsaxes < self.naxis:
self.wcsaxes = self.naxis
return
if self.image_rep == PRIMARY_ARRAY:
r = re.compile (r"""(?x)
(?P<name>WCSAXES)
(?P<alt>[A-Z]?$)
""")
elif self.image_rep == BINTABLE_ARRAY:
r = re.compile (r"""(?x)
(?P<name>WCAX)
(?P<col>\d+)
(?P<alt>[A-Z]?$)
""")
self.wcsaxes = None
for (keyword, value) in items:
keyword = keyword.upper()
if keyword == "NAXIS":
self.naxis = value
continue
m = r.match (keyword)
if m and m.group ("alt") == self.alternate:
if self.image_rep == BINTABLE_ARRAY:
if m.group ("col") == "" or \
int (m.group ("col")) != (self.column + 1):
continue
self.wcsaxes = value
self.keywords.append (keyword)
break
if self.wcsaxes is None:
self.wcsaxes = self.naxis
if self.wcsaxes < self.naxis:
print "Warning: wcsaxes = %d is smaller than naxis = %d;" % \
(self.wcsaxes, self.naxis)
print "wcsaxes will be set to naxis."
self.wcsaxes = self.naxis
def _extractWcsKeywords (self, hdr):
"""Copy WCS keyword values to attributes.
@param hdr: a set of FITS keywords and values (values are case
sensitive, but keyword names are not)
@type hdr: pyfits.Header object or dictionary
"""
if self.image_rep == PRIMARY_ARRAY:
self._imageArrayKeywords (hdr)
elif self.image_rep == BINTABLE_ARRAY:
self._bintableArrayKeywords (hdr)
elif self.image_rep == PIXEL_LIST:
self._pixelListKeywords (hdr)
def _checkForThese (self, key, keywords):
"""Set an attribute (a flag) if key is in keywords."""
if key in keywords:
attrib = "got_" + key
self.__setattr__ (attrib, True)
def _imageArrayKeywords (self, hdr):
"""Copy WCS keyword values to attributes.
@param hdr: a set of FITS keywords and values (values are case
sensitive, but keyword names are not)
@type hdr: pyfits.Header object or dictionary
This version is for primary array keywords.
"""
r1 = re.compile (r"""(?x)
(?P<name>WCSNAME|LONPOLE|LATPOLE|EQUINOX|RADESYS)
(?P<alt>[A-Z]?$) # optional alternate WCS
""")
r2 = re.compile (r"""(?x)
(?P<name>CTYPE|CUNIT|CRVAL|CDELT|CRPIX|
CRDER|CSYER|CROTA)
(?P<index>\d+) # axis number
(?P<alt>[A-Z]?$)
""")
r3 = re.compile (r"""(?x)
(?P<name>PC|CD)
(?P<index1>\d+)_(?P<index2>\d+) # axis numbers
(?P<alt>[A-Z]?$)
""")
r4 = re.compile (r"""(?x)
(?P<name>PV|PS)
(?P<index>\d+)_(?P<par>\d+) # axis and parameter numbers
(?P<alt>[A-Z]?$)
""")
items = hdr.items()
for (keyword, value) in items:
keyword = keyword.upper()
if keyword == "HISTORY" or keyword == "COMMENT" or keyword == "":
continue
if keyword == "MJD-OBS":
self.mjd_obs = value
self.keywords.append (keyword)
continue
m = r1.match (keyword)
if m:
key = self.keyword_translate[m.group ("name")]
if m.group ("alt") == self.alternate:
self.__setattr__ (key, value)
self.keywords.append (keyword)
continue
m = r2.match (keyword)
if m and m.group ("alt") == self.alternate:
key = self.keyword_translate[m.group ("name")]
if key == "crpix":
value -= 1. # zero indexed
a = self.__getattribute__ (key)
# WTB: hack for legacy CROTA keyword w/o index
if((m.group("index")=='') and (key=="crota")):
print "Warning: keyword CROTA (with no index) was found"
a[0],a[1]=0.0,value # assign CROTA as CROTA2
self.__setattr__(key,a)
else:
i = int (m.group ("index")) - 1
a[i] = value
self.__setattr__ (key, a)
self.keywords.append (keyword)
self._checkForThese (key, ("cdelt", "crota"))
continue
m = r3.match (keyword)
if m and m.group ("alt") == self.alternate:
key = self.keyword_translate[m.group ("name")]
a = self.__getattribute__ (key)
i = int (m.group ("index1")) - 1
j = int (m.group ("index2")) - 1
a[i,j] = value
self.__setattr__ (key, a)
self.keywords.append (keyword)
self._checkForThese (key, ("cd", "pc"))
continue
m = r4.match (keyword)
if m and m.group ("alt") == self.alternate:
key = self.keyword_translate[m.group ("name")]
i = int (m.group ("index")) - 1
par = int (m.group ("par")) # already zero indexed
if key == "pv":
self.npv += 1
self.pv.append ((i, par, value))
self.keywords.append (keyword)
elif key == "ps":
self.nps += 1
self.ps.append ((i, par, value))
self.keywords.append (keyword)
continue
# Check for RADECSYS if RADESYS not found.
if self.radesys is None and hdr.has_key ("radecsys"):
self.radesys = hdr["radecsys"]
self.keywords.append (keyword)
def _bintableArrayKeywords (self, hdr):
"""Copy WCS keyword values to attributes.
@param hdr: a set of FITS keywords and values (values are case
sensitive, but keyword names are not)
@type hdr: pyfits.Header object or dictionary
This version is for bintable array keywords.
"""
r0 = re.compile (r"""(?x)
(?P<name>MJDOB)
(?P<col>\d+$) # column number
""")
r1 = re.compile (r"""(?x)
(?P<name>LONP|LATP|EQUI|RADE|WCSN)
(?P<col>\d+) # column number
(?P<alt>[A-Z]?$)
""")
r2 = re.compile (r"""(?x)
(?P<index>\d) # axis number
(?P<name>CTYP|CUNI|CRVL|CDLT|CRPX|
CTY|CUN|CRV|CDE|CRP|
CRD|CSY|WCST|WCSX|CROT)
(?P<col>\d+)
(?P<alt>[A-Z]?$)
""")
r3 = re.compile (r"""(?x)
(?P<index1>\d) # first axis number
(?P<index2>\d) # second axis number
(?P<name>PC|CD)
(?P<col>\d+)
(?P<alt>[A-Z]?$)
""")
r4 = re.compile (r"""(?x)
(?P<index>\d) # axis number
(?P<name>V|PV|S|PS)
(?P<col>\d+)_(?P<par>\d+) # column and parameter numbers
(?P<alt>[A-Z]?$)
""")
items = hdr.items()
for (keyword, value) in items:
keyword = keyword.upper()
if keyword == "HISTORY" or keyword == "COMMENT" or keyword == "":
continue
m = r0.match (keyword) # this is for MJDOBn (MJD-OBS)
if m:
if int (m.group ("col")) != (self.column + 1):
continue
self.mjd_obs = value
self.keywords.append (keyword)
continue
m = r1.match (keyword)
if m:
if int (m.group ("col")) != (self.column + 1):
continue
key = self.keyword_translate[m.group ("name")]
if m.group ("alt") == self.alternate:
self.__setattr__ (key, value)
self.keywords.append (keyword)
continue
m = r2.match (keyword)
if m:
if int (m.group ("col")) != (self.column + 1) or \
m.group ("alt") != self.alternate:
continue
key = self.keyword_translate[m.group ("name")]
if key == "crpix":
value -= 1. # zero indexed
a = self.__getattribute__ (key)
i = int (m.group ("index")) - 1
a[i] = value
self.__setattr__ (key, a)
self.keywords.append (keyword)
self._checkForThese (key, ("cdelt", "crota"))
continue
m = r3.match (keyword)
if m:
if int (m.group ("col")) != (self.column + 1) or \
m.group ("alt") != self.alternate:
continue
key = self.keyword_translate[m.group ("name")]
a = self.__getattribute__ (key)
i = int (m.group ("index1")) - 1
j = int (m.group ("index2")) - 1
a[i,j] = value
self.__setattr__ (key, a)
self.keywords.append (keyword)
self._checkForThese (key, ("cd", "pc"))
continue
m = r4.match (keyword)
if m:
if int (m.group ("col")) != (self.column + 1) or \
m.group ("alt") != self.alternate:
continue
key = self.keyword_translate[m.group ("name")]
i = int (m.group ("index")) - 1
par = int (m.group ("par")) # already zero indexed
if key == "pv":
self.npv += 1
self.pv.append ((i, par, value))
self.keywords.append (keyword)
elif key == "ps":
self.nps += 1
self.ps.append ((i, par, value))
self.keywords.append (keyword)
continue
def _pixelListKeywords (self, hdr):
"""Copy WCS keyword values to attributes.
@param hdr: a set of FITS keywords and values (values are case
sensitive, but keyword names are not)
@type hdr: pyfits.Header object or dictionary
This version is for pixel list keywords.
"""
r0 = re.compile (r"""(?x)
(?P<name>MJDOB)
(?P<col>\d+$) # column number
""")
r1 = re.compile (r"""(?x)
(?P<name>LONP|LATP|EQUI|RADE|WCSN)
(?P<col>\d+) # column number
(?P<alt>[A-Z]?$)
""")
r2 = re.compile (r"""(?x)
(?P<name>TCTYP|TCUNI|TCRVL|TCDLT|TCRPX|
TCTY|TCUN|TCRV|TCDE|TCRP|
TCRD|TCSY|TCROT)
(?P<col>\d+) # column number
(?P<alt>[A-Z]?$)
""")
r3 = re.compile (r"""(?x)
(?P<name>TP|TPC|TC|TCD)
(?P<col1>\d+)_(?P<col2>\d+) # column numbers
(?P<alt>[A-Z]?$)
""")
r4 = re.compile (r"""(?x)
(?P<name>TV|TPV|TS|TPS)
(?P<col>\d+)_(?P<par>\d+) # column and parameter numbers
(?P<alt>[A-Z]?$)
""")
items = hdr.items()
for (keyword, value) in items:
keyword = keyword.upper()
if keyword == "HISTORY" or keyword == "COMMENT" or keyword == "":
continue
m = r0.match (keyword) # this is for MJDOBn (MJD-OBS)
if m:
if (int (m.group ("col")) - 1) not in self.tab_columns:
continue
self.mjd_obs = value
self.keywords.append (keyword)
continue
m = r1.match (keyword)
if m:
if (int (m.group ("col")) - 1) not in self.tab_columns:
continue
key = self.keyword_translate[m.group ("name")]
if m.group ("alt") == self.alternate:
self.__setattr__ (key, value)
self.keywords.append (keyword)
continue
m = r2.match (keyword)
if m and m.group ("alt") == self.alternate:
col = int (m.group ("col")) - 1
if self.tab_columns.count (col) < 1:
continue
i = self.tab_columns.index (col)
key = self.keyword_translate[m.group ("name")]
if key == "crpix":
value -= 1. # zero indexed
a = self.__getattribute__ (key)
a[i] = value
self.__setattr__ (key, a)
self.keywords.append (keyword)
self._checkForThese (key, ("cdelt", "crota"))
continue
m = r3.match (keyword)
if m and m.group ("alt") == self.alternate:
col1 = int (m.group ("col1")) - 1
col2 = int (m.group ("col2")) - 1
if self.tab_columns.count (col1) < 1 or \
self.tab_columns.count (col2) < 1 :
continue
i = self.tab_columns.index (col1)
j = self.tab_columns.index (col2)
key = self.keyword_translate[m.group ("name")]
a = self.__getattribute__ (key)
a[i,j] = value
self.__setattr__ (key, a)
self.keywords.append (keyword)
self._checkForThese (key, ("cd", "pc"))
continue
m = r4.match (keyword)
if m and m.group ("alt") == self.alternate:
col = int (m.group ("col")) - 1
if self.tab_columns.count (col) < 1:
continue