This file is indexed.

/usr/share/pyshared/pywcs/pywcs.py is in python-pywcs 1.10-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
# Copyright (C) 2008 Association of Universities for Research in
# Astronomy (AURA)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
#     1. Redistributions of source code must retain the above
#       copyright notice, this list of conditions and the following
#       disclaimer.
#
#     2. Redistributions in binary form must reproduce the above
#       copyright notice, this list of conditions and the following
#       disclaimer in the documentation and/or other materials
#       provided with the distribution.
#
#     3. The name of AURA and its representatives may not be used to
#       endorse or promote products derived from this software without
#       specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY AURA ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL AURA BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
# OF THE POSSIBILITY OF SUCH DAMAGE.

"""
Under the hood, there are 3 separate classes that perform different
parts of the transformation:

   - `~pywcs.Wcsprm`: Is a direct wrapper of the core WCS
     functionality in `wcslib`_.

   - `~pywcs.Sip`: Handles polynomial distortion as defined in the
     `SIP`_ convention.

   - `~pywcs.DistortionLookupTable`: Handles `Paper IV`_ distortion
     lookup tables.

Additionally, the class `WCS` aggregates all of these transformations
together in a pipeline:

   - Detector to image plane correction (by a pair of
     `~pywcs.DistortionLookupTable` objects).

   - `SIP`_ distortion correction (by an underlying `~pywcs.Sip`
     object)

   - `Paper IV`_ table-lookup distortion correction (by a pair of
     `~pywcs.DistortionLookupTable` objects).

   - `wcslib`_ WCS transformation (by a `~pywcs.Wcsprm` object)
"""

from __future__ import division # confidence high

# stdlib
import copy

# third-party
import numpy as np

# local
import _docutil as __
import _pywcs
import pyfits

assert _pywcs._sanity_check(), \
    """PyWcs did not pass its sanity check for your build on your platform.
Please send details about your build and platform to mdroe@stsci.edu"""

# This is here for the sake of epydoc
WCSBase = _pywcs._Wcs
DistortionLookupTable = _pywcs.DistortionLookupTable
Sip = _pywcs.Sip
UnitConverter = _pywcs.UnitConverter
class Wcsprm(_pywcs._Wcsprm): pass
# Copy all the constants from the C extension into this module's namespace
for key, val in _pywcs.__dict__.items():
    if (key.startswith('WCSSUB') or
        key.startswith('WCSHDR') or
        key.startswith('WCSHDO')):
        locals()[key] = val

# A wrapper around the C WCS type

def _parse_keysel(keysel):
    keysel_flags = 0
    if keysel is not None:
        for element in keysel:
            if element.lower() == 'image':
                keysel_flags |= _pywcs.WCSHDR_IMGHEAD
            elif element.lower() == 'binary':
                keysel_flags |= _pywcs.WCSHDR_BIMGARR
            elif element.lower() == 'pixel':
                keysel_flags |= _pywcs.WCSHDR_PIXLIST
            else:
                raise ValueError(
                    "keysel must be a list of 'image', 'binary' and/or 'pixel'")
    else:
        keysel_flags = -1

    return keysel_flags


class WCS(WCSBase):
    """
    WCS objects perform standard WCS transformations, and correct for
    `SIP`_ and `Paper IV`_ table-lookup distortions, based on the WCS
    keywords and supplementary data read from a FITS file.
    """

    def __init__(self, header=None, fobj=None, key=' ', minerr=0.0,
                 relax=False, naxis=None, keysel=None, colsel=None):
        """
        - *header*: A PyFITS header object.  If *header* is not
          provided or None, the object will be initialized to default
          values.

        - *fobj*: A PyFITS file (hdulist) object. It is needed when
          header keywords point to a `Paper IV`_ Lookup table
          distortion stored in a different extension.

        - *key*: A string.  The name of a particular WCS transform to
          use.  This may be either ``' '`` or ``'A'``-``'Z'`` and
          corresponds to the ``"a"`` part of the ``CTYPEia`` cards.
          *key* may only be provided if *header* is also provided.

        - *minerr*: A floating-point value.  The minimum value a
          distortion correction must have in order to be applied. If
          the value of ``CQERRja`` is smaller than *minerr*, the
          corresponding distortion is not applied.

        - *relax*: Degree of permissiveness:

            - `False`: Recognize only FITS keywords defined by the
              published WCS standard.

            - `True`: Admit all recognized informal extensions of the
              WCS standard.

            - `int`: a bit field selecting specific extensions to
              accept.  See :ref:`relaxread` for details.

        - *naxis*: int or sequence.  Extracts specific coordinate axes
          using :meth:`~pywcs.Wcsprm.sub`.  If a header is provided,
          and *naxis* is not ``None``, *naxis* will be passed to
          :meth:`~pywcs.Wcsprm.sub` in order to select specific axes
          from the header.  See :meth:`~pywcs.Wcsprm.sub` for more
          details about this parameter.

        - *keysel*: A list of flags used to select the keyword types
          considered by wcslib.  When ``None``, only the standard
          image header keywords are considered (and the underlying
          wcspih() C function is called).  To use binary table image
          array or pixel list keywords, *keysel* must be set.

          Each element in the list should be one of the following
          strings:

            - 'image': Image header keywords

            - 'binary': Binary table image array keywords

            - 'pixel': Pixel list keywords

          Keywords such as ``EQUIna`` or ``RFRQna`` that are common to
          binary table image arrays and pixel lists (including
          ``WCSNna`` and ``TWCSna``) are selected by both 'binary' and
          'pixel'.

        - *colsel*: A sequence of table column numbers used
          to restrict the WCS transformations considered to only those
          pertaining to the specified columns.  If `None`, there is no
          restriction.

        .. warning::

          pywcs supports arbitrary *n* dimensions for the core WCS
          (the transformations handled by WCSLIB).  However, the Paper
          IV lookup table and SIP distortions must be two dimensional.
          Therefore, if you try to create a WCS object where the core
          WCS has a different number of dimensions than 2 and that
          object also contains a Paper IV lookup table or SIP
          distortion, a `ValueError` exception will be raised.  To
          avoid this, consider using the *naxis* kwarg to select two
          dimensions from the core WCS.

        **Exceptions:**

        - `MemoryError`: Memory allocation failed.

        - `ValueError`: Invalid key.

        - `KeyError`: Key not found in FITS header.

        - `AssertionError`: Lookup table distortion present in the
          header but fobj not provided.
        """
        if header is None:
            if naxis is None:
                naxis = 2
            wcsprm = _pywcs._Wcsprm(header=None, key=key,
                                    relax=relax, naxis=naxis)
            self.naxis = wcsprm.naxis
            # Set some reasonable defaults.
            det2im = (None, None)
            cpdis = (None, None)
            sip = None
        else:
            keysel_flags = _parse_keysel(keysel)

            try:
                header_string = repr(header.ascard)
                wcsprm = _pywcs._Wcsprm(header=header_string, key=key,
                                        relax=relax, keysel=keysel_flags,
                                        colsel=colsel)
            except _pywcs.NoWcsKeywordsFoundError:
                # The header may have SIP or distortions, but no core
                # WCS.  That isn't an error -- we want a "default"
                # (identity) core Wcs transformation in that case.
                if colsel is None:
                    wcsprm = _pywcs._Wcsprm(header=None, key=key,
                                            relax=relax, keysel=keysel_flags,
                                            colsel=colsel)
                else:
                    raise

            if naxis is not None:
                wcsprm = wcsprm.sub(naxis)
            self.naxis = wcsprm.naxis

            det2im = self._read_det2im_kw(header, fobj)
            cpdis = self._read_distortion_kw(
                header, fobj, key=key,dist='CPDIS', err=minerr)
            sip = self._read_sip_kw(header, key=key)
            if (wcsprm.naxis != 2 and
                (det2im[0] or det2im[1] or cpdis[0] or cpdis[1] or sip)):
                raise ValueError(
                    """
Paper IV lookup tables and SIP distortions only work in 2 dimensions.
However, WCSLIB has detected %d dimensions in the core WCS keywords.
To use core WCS in conjunction with Paper IV lookup tables or SIP
distortion, you must select or reduce these to 2 dimensions using the
naxis kwarg.
""" %
                    wcsprm.naxis)
        self.get_naxis(header)
        WCSBase.__init__(self, sip, cpdis, wcsprm, det2im)

    def __copy__(self):
        new_copy = WCS()
        WCSBase.__init__(new_copy, self.sip,
                         (self.cpdis1, self.cpdis2),
                         self.wcs,
                         (self.det2im1, self.det2im2))
        new_copy.__dict__.update(self.__dict__)
        return new_copy

    def __deepcopy__(self, memo):
        new_copy = WCS()
        new_copy.naxis = copy.deepcopy(self.naxis, memo)
        WCSBase.__init__(new_copy, copy.deepcopy(self.sip, memo),
                         (copy.deepcopy(self.cpdis1, memo),
                          copy.deepcopy(self.cpdis2, memo)),
                         copy.deepcopy(self.wcs, memo),
                         (copy.deepcopy(self.det2im1, memo),
                          copy.deepcopy(self.det2im2, memo)))
        for key in self.__dict__:
            val = self.__dict__[key]
            new_copy.__dict__[key] = copy.deepcopy(val, memo)
        return new_copy

    def copy(self):
        """
        Return a shallow copy of the object.

        Convenience method so user doesn't have to import the :mod:`copy`
        stdlib module.
        """
        return copy.copy(self)

    def deepcopy(self):
        """
        Return a deep copy of the object.

        Convenience method so user doesn't have to import the :mod:`copy`
        stdlib module.
        """
        return copy.deepcopy(self)

    def sub(self, axes=None):
        copy = self.deepcopy()
        copy.wcs = self.wcs.sub(axes)
        copy.naxis = copy.wcs.naxis
        return copy
    sub.__doc__ = _pywcs._Wcsprm.sub.__doc__

    def calcFootprint(self, header=None, undistort=True):
        """
        Calculates the footprint of the image on the sky.

        A footprint is defined as the positions of the corners of the
        image on the sky after all available distortions have been
        applied.

        Returns a (4, 2) array of (*x*, *y*) coordinates.
        """
        if header is None:
            try:
                # classes that inherit from WCS and define naxis1/2
                # do not require a header parameter
                naxis1 = self.naxis1
                naxis2 = self.naxis2
            except AttributeError :
                print "Need a valid header in order to calculate footprint\n"
                return None
        else:
            naxis1 = header.get('NAXIS1', None)
            naxis2 = header.get('NAXIS2', None)

        corners = np.zeros(shape=(4,2),dtype=np.float64)
        if naxis1 is None or naxis2 is None:
            return None

        corners[0,0] = 1.
        corners[0,1] = 1.
        corners[1,0] = 1.
        corners[1,1] = naxis2
        corners[2,0] = naxis1
        corners[2,1] = naxis2
        corners[3,0] = naxis1
        corners[3,1] = 1.
        if undistort:
            return self.all_pix2sky(corners, 1)
        else:
            return self.wcs_pix2sky(corners,1)

    def _read_det2im_kw(self, header, fobj):
        """
        Create a `Paper IV`_ type lookup table for detector to image
        plane correction.
        """
        cpdis = [None, None]
        crpix = [0.,0.]
        crval = [0.,0.]
        cdelt = [1.,1.]

        if not isinstance(fobj, pyfits.HDUList):
            return (None, None)

        try:
            d2im_data = fobj[('D2IMARR', 1)].data
        except KeyError:
            return (None, None)
        except AttributeError:
            return (None, None)
        d2im_data = np.array([d2im_data])
        d2im_hdr = fobj[('D2IMARR', 1)].header
        naxis = d2im_hdr['NAXIS']

        for i in range(1,naxis+1):
            crpix[i-1] = d2im_hdr.get('CRPIX'+str(i), 0.0)
            crval[i-1] = d2im_hdr.get('CRVAL'+str(i), 0.0)
            cdelt[i-1] = d2im_hdr.get('CDELT'+str(i), 1.0)

        cpdis = DistortionLookupTable(d2im_data, crpix, crval, cdelt)

        axiscorr = header.get('AXISCORR', None)

        if axiscorr == 1:
            return (cpdis, None)
        else:
            return (None, cpdis)

    def _read_distortion_kw(self, header, fobj, key='', dist='CPDIS', err=0.0):
        """
        Reads `Paper IV`_ table-lookup distortion keywords and data,
        and returns a 2-tuple of `~pywcs.DistortionLookupTable`
        objects.

        If no `Paper IV`_ distortion keywords are found, ``(None,
        None)`` is returned.
        """
        if dist == 'CPDIS':
            d_kw = 'DP'
            err_kw = 'CPERR'
        else:
            d_kw = 'DQ'
            err_kw = 'CQERR'

        tables = {}
        for i in range(1, self.naxis+1):
            d_error = header.get(err_kw+str(i), 0.0)
            if d_error < err:
                tables[i] = None
                continue
            distortion = dist+str(i)+key
            if header.has_key(distortion):
                dis = header[distortion].lower()
                if dis == 'lookup':
                    assert isinstance(fobj, pyfits.HDUList), \
                        'A pyfits HDUList is required for Lookup table distortion.'
                    dp = (d_kw+str(i)+key).strip()
                    d_extver = header.get(dp+'.EXTVER', 1)
                    if i == header[dp+'.AXIS.%s'%i]:
                        d_data = fobj['WCSDVARR', d_extver].data
                    else: 
                        d_data = (fobj['WCSDVARR', d_extver].data).transpose()
                    d_header = fobj['WCSDVARR', d_extver].header
                    d_crpix = (d_header.get('CRPIX1', 0.0), d_header.get('CRPIX2', 0.0))
                    d_crval = (d_header.get('CRVAL1', 0.0), d_header.get('CRVAL2', 0.0))
                    d_cdelt = (d_header.get('CDELT1', 1.0), d_header.get('CDELT2', 1.0))
                    d_lookup = DistortionLookupTable(d_data, d_crpix,
                                                     d_crval, d_cdelt)
                    tables[i] = d_lookup
                else:
                    print 'Polynomial distortion is not implemented.\n'
            else:
                tables[i] = None

        if not tables:
            return (None, None)
        else:
            return (tables.get(1), tables.get(2))

    def _read_sip_kw(self, header, key=''):
        """
        Reads `SIP`_ header keywords and returns a `~pywcs.Sip`
        object.

        If no `SIP`_ header keywords are found, ``None`` is returned.
        """

        if header.has_key("A_ORDER"+key):
            if not header.has_key("B_ORDER"+key):
                raise ValueError(
                    "A_ORDER provided without corresponding B_ORDER "
                    "keyword for SIP distortion")

            m = int(header["A_ORDER"+key])
            a = np.zeros((m+1, m+1), np.double)
            for i in range(m+1):
                for j in range(m-i+1):
                    a[i, j] = header.get(("A_%d_%d" % (i, j))+key, 0.0)

            m = int(header["B_ORDER"+key])
            b = np.zeros((m+1, m+1), np.double)
            for i in range(m+1):
                for j in range(m-i+1):
                    b[i, j] = header.get(("B_%d_%d" % (i, j))+key, 0.0)
        elif header.has_key("B_ORDER"+key):
            raise ValueError(
                "B_ORDER provided without corresponding A_ORDER "
                "keyword for SIP distortion")
        else:
            a = None
            b = None

        if header.has_key("AP_ORDER"):
            if not header.has_key("BP_ORDER"):
                raise ValueError(
                    "AP_ORDER provided without corresponding BP_ORDER "
                    "keyword for SIP distortion")

            m = int(header["AP_ORDER"])
            ap = np.zeros((m+1, m+1), np.double)
            for i in range(m+1):
                for j in range(m-i+1):
                    ap[i, j] = header.get("AP_%d_%d" % (i, j), 0.0)

            m = int(header["BP_ORDER"])
            bp = np.zeros((m+1, m+1), np.double)
            for i in range(m+1):
                for j in range(m-i+1):
                    bp[i, j] = header.get("BP_%d_%d" % (i, j), 0.0)
        elif header.has_key("BP_ORDER"):
            raise ValueError(
                "BP_ORDER provided without corresponding AP_ORDER "
                "keyword for SIP distortion")
        else:
            ap = None
            bp = None

        if a is None and b is None and ap is None and bp is None:
            return None

        if not header.has_key("CRPIX1") or not header.has_key("CRPIX2"):
            raise ValueError(
                "Header has SIP keywords without CRPIX keywords")

        crpix1 = header.get("CRPIX1")
        crpix2 = header.get("CRPIX2")

        return Sip(a, b, ap, bp, (crpix1, crpix2))

    def _denormalize_sky(self, sky):
        if self.wcs.lngtyp != 'RA':
            raise ValueError(
                "WCS does not have longitude type of 'RA', therefore " +
                "(ra, dec) data can not be used as input")
        if self.wcs.lattype != 'DEC':
            raise ValueError(
                "WCS does not have longitude type of 'DEC', therefore " +
                "(ra, dec) data can not be used as input")
        if self.wcs.naxis == 2:
            if self.wcs.lng == 0 and self.wcs.lat == 1:
                return sky
            elif self.wcs.lng == 1 and self.wcs.lat == 0:
                # Reverse the order of the columns
                return sky[:,::-1]
            else:
                raise ValueError(
                    "WCS does not have longitude and latitude celestial " +
                    "axes, therefore (ra, dec) data can not be used as input")
        else:
            if self.wcs.lng < 0 or self.wcs.lat < 0:
                raise ValueError(
                    "WCS does not have both longitude and latitude celestial " +
                    "axes, therefore (ra, dec) data can not be used as input")
            out = np.zeros((sky.shape[0], self.wcs.naxis))
            out[:,self.wcs.lng] = sky[:,0]
            out[:,self.wcs.lat] = sky[:,1]
            return out

    def _normalize_sky(self, sky):
        if self.wcs.lngtyp != 'RA':
            raise ValueError(
                "WCS does not have longitude type of 'RA', therefore " +
                "(ra, dec) data can not be returned")
        if self.wcs.lattype != 'DEC':
            raise ValueError(
                "WCS does not have longitude type of 'DEC', therefore " +
                "(ra, dec) data can not be returned")
        if self.wcs.naxis == 2:
            if self.wcs.lng == 0 and self.wcs.lat == 1:
                return sky
            elif self.wcs.lng == 1 and self.wcs.lat == 0:
                # Reverse the order of the columns
                return sky[:,::-1]
            else:
                raise ValueError(
                    "WCS does not have longitude and latitude celestial "
                    "axes, therefore (ra, dec) data can not be returned")
        else:
            if self.wcs.lng < 0 or self.wcs.lat < 0:
                raise ValueError(
                    "WCS does not have both longitude and latitude celestial "
                    "axes, therefore (ra, dec) data can not be returned")
            out = np.empty((sky.shape[0], 2))
            out[:,0] = sky[:,self.wcs.lng]
            out[:,1] = sky[:,self.wcs.lat]
            return out

    def _array_converter(self, func, sky, *args, **kwargs):
        """
        A helper function to support reading either a pair of arrays
        or a single Nx2 array.
        """
        ra_dec_order = kwargs.get('ra_dec_order')
        if len(args) == 2:
            xy, origin = args
            try:
                xy = np.asarray(xy)
                origin = int(origin)
            except:
                raise TypeError(
                    "When providing two arguments, they must be (xy, origin)")
            if ra_dec_order and sky == 'input':
                xy = self._denormalize_sky(xy)
            result = func(xy, origin)
            if ra_dec_order and sky == 'output':
                result = self._normalize_sky(result)
            return result
        elif len(args) == 3:
            x, y, origin = args
            try:
                x = np.asarray(x)
                y = np.asarray(y)
                origin = int(origin)
            except:
                raise TypeError(
                    "When providing three arguments, they must be (x, y, origin)")
            if x.size != y.size:
                raise ValueError("x and y arrays are not the same size")
            length = x.size
            xy = np.hstack((x.reshape((length, 1)),
                            y.reshape((length, 1))))
            if ra_dec_order and sky == 'input':
                xy = self._denormalize_sky(xy)
            sky = func(xy, origin)
            if ra_dec_order and sky == 'output':
                sky = self._normalize_sky_output(sky)
                return sky[:, 0], sky[:, 1]
            return [sky[:, i] for i in range(sky.shape[1])]
        raise TypeError("Expected 2 or 3 arguments, %d given" % len(args))

    def all_pix2sky(self, *args, **kwargs):
        return self._array_converter(self._all_pix2sky, 'output', *args, **kwargs)
    all_pix2sky.__doc__ = """
        Transforms pixel coordinates to sky coordinates by doing all
        of the following in order:

            - Detector to image plane correction (optionally)

            - `SIP`_ distortion correction (optionally)

            - `Paper IV`_ table-lookup distortion correction (optionally)

            - `wcslib`_ WCS transformation

        %s

        %s

        For a transformation that is not two-dimensional, the
        two-argument form must be used.

        .. note::

            The order of the axes for the result is determined by the
            `CTYPEia` keywords in the FITS header, therefore it may
            not always be of the form (*ra*, *dec*).  The
            `~pywcs.Wcsprm.lat`, `~pywcs.Wcsprm.lng`,
            `~pywcs.Wcsprm.lattyp` and `~pywcs.Wcsprm.lngtyp` members
            can be used to determine the order of the axes.

        **Exceptions:**

        - `MemoryError`: Memory allocation failed.

        - `SingularMatrixError`: Linear transformation matrix is
          singular.

        - `InconsistentAxisTypesError`: Inconsistent or unrecognized
          coordinate axis types.

        - `ValueError`: Invalid parameter value.

        - `ValueError`: Invalid coordinate transformation parameters.

        - `ValueError`: x- and y-coordinate arrays are not the same
          size.

        - `InvalidTransformError`: Invalid coordinate transformation
          parameters.

        - `InvalidTransformError`: Ill-conditioned coordinate
          transformation parameters.
        """ % (__.TWO_OR_THREE_ARGS(
            'sky coordinates, in degrees', 'naxis', 8),
               __.RA_DEC_ORDER(8))

    def wcs_pix2sky(self, *args, **kwargs):
        if self.wcs is None:
            raise ValueError("No basic WCS settings were created.")
        return self._array_converter(lambda xy, o: self.wcs.p2s(xy, o)['world'],
                                     'output', *args, **kwargs)
    wcs_pix2sky.__doc__ = """
        Transforms pixel coordinates to sky coordinates by doing only
        the basic `wcslib`_ transformation.  No `SIP`_ or `Paper IV`_
        table lookup distortion correction is applied.  To perform
        distortion correction, see `~pywcs.WCS.all_pix2sky`,
        `~pywcs.WCS.sip_pix2foc`, `~pywcs.WCS.p4_pix2foc`, or
        `~pywcs.WCS.pix2foc`.

        %s

        %s

        For a transformation that is not two-dimensional, the
        two-argument form must be used.

        .. note::

            The order of the axes for the result is determined by the
            `CTYPEia` keywords in the FITS header, therefore it may
            not always be of the form (*ra*, *dec*).  The
            `~pywcs.Wcsprm.lat`, `~pywcs.Wcsprm.lng`,
            `~pywcs.Wcsprm.lattyp` and `~pywcs.Wcsprm.lngtyp` members
            can be used to determine the order of the axes.

        **Exceptions:**

        - `MemoryError`: Memory allocation failed.

        - `SingularMatrixError`: Linear transformation matrix is
          singular.

        - `InconsistentAxisTypesError`: Inconsistent or unrecognized
          coordinate axis types.

        - `ValueError`: Invalid parameter value.

        - `ValueError`: Invalid coordinate transformation parameters.

        - `ValueError`: x- and y-coordinate arrays are not the same
          size.

        - `InvalidTransformError`: Invalid coordinate transformation
          parameters.

        - `InvalidTransformError`: Ill-conditioned coordinate
          transformation parameters.
        """ % (__.TWO_OR_THREE_ARGS('sky coordinates, in degrees.', 'naxis', 8),
               __.RA_DEC_ORDER(8))

    def wcs_sky2pix(self, *args, **kwargs):
        if self.wcs is None:
            raise ValueError("No basic WCS settings were created.")
        return self._array_converter(lambda xy, o: self.wcs.s2p(xy, o)['pixcrd'],
                                     'input', *args, **kwargs)
    wcs_sky2pix.__doc__ = """
        Transforms sky coordinates to pixel coordinates, using only
        the basic `wcslib`_ WCS transformation.  No `SIP`_ or `Paper
        IV`_ table lookup distortion is applied.

        %s

        %s

        For a transformation that is not two-dimensional, the
        two-argument form must be used.

        .. note::

            The order of the axes for the input sky array is
            determined by the `CTYPEia` keywords in the FITS header,
            therefore it may not always be of the form (*ra*, *dec*).
            The `~pywcs.Wcsprm.lat`, `~pywcs.Wcsprm.lng`,
            `~pywcs.Wcsprm.lattyp` and `~pywcs.Wcsprm.lngtyp` members
            can be used to determine the order of the axes.

        **Exceptions:**

        - `MemoryError`: Memory allocation failed.

        - `SingularMatrixError`: Linear transformation matrix is
          singular.

        - `InconsistentAxisTypesError`: Inconsistent or unrecognized
          coordinate axis types.

        - `ValueError`: Invalid parameter value.

        - `InvalidTransformError`: Invalid coordinate transformation
          parameters.

        - `InvalidTransformError`: Ill-conditioned coordinate
          transformation parameters.
        """ % (__.TWO_OR_THREE_ARGS('pixel coordinates', 'naxis', 8),
               __.RA_DEC_ORDER(8))

    def pix2foc(self, *args, **kwargs):
        return self._array_converter(self._pix2foc, None, *args, **kwargs)
    pix2foc.__doc__ = """
        Convert pixel coordinates to focal plane coordinates using the
        `SIP`_ polynomial distortion convention and `Paper IV`_
        table-lookup distortion correction.

        %s

        **Exceptions:**

        - `MemoryError`: Memory allocation failed.

        - `ValueError`: Invalid coordinate transformation parameters.
        """ % (__.TWO_OR_THREE_ARGS('focal coordinates', '2', 8))

    def p4_pix2foc(self, *args, **kwargs):
        return self._array_converter(self._p4_pix2foc, None, *args, **kwargs)
    p4_pix2foc.__doc__ = """
        Convert pixel coordinates to focal plane coordinates using
        `Paper IV`_ table-lookup distortion correction.

        %s

        **Exceptions:**

        - `MemoryError`: Memory allocation failed.

        - `ValueError`: Invalid coordinate transformation parameters.
        """ % (__.TWO_OR_THREE_ARGS('focal coordinates', '2', 8))

    def det2im(self, *args, **kwargs):
        return self._array_converter(self._det2im, None, *args, **kwargs)
    det2im.__doc__ = """
        Convert detector coordinates to image plane coordinates using
        `Paper IV`_ table-lookup distortion correction.

        %s

        **Exceptions:**

        - `MemoryError`: Memory allocation failed.

        - `ValueError`: Invalid coordinate transformation parameters.
        """ % (__.TWO_OR_THREE_ARGS('pixel coordinates', '2', 8))

    def sip_pix2foc(self, *args, **kwargs):
        if self.sip is None:
            if len(args) == 2:
                return args[0]
            elif len(args) == 3:
                return args[:2]
            else:
                raise TypeError("Wrong number of arguments")
        return self._array_converter(self.sip.pix2foc, None, *args, **kwargs)
    sip_pix2foc.__doc__ = """
        Convert pixel coordinates to focal plane coordinates using the
        `SIP`_ polynomial distortion convention.

        `Paper IV`_ table lookup distortion correction is not applied,
        even if that information existed in the FITS file that
        initialized this :class:`~pywcs.WCS` object.  To correct for that,
        use `~pywcs.WCS.pix2foc` or `~pywcs.WCS.p4_pix2foc`.

        %s

        **Exceptions:**

        - `MemoryError`: Memory allocation failed.

        - `ValueError`: Invalid coordinate transformation parameters.
        """ % (__.TWO_OR_THREE_ARGS('focal coordinates', '2', 8))

    def sip_foc2pix(self, *args, **kwargs):
        if self.sip is None:
            if len(args) == 2:
                return args[0]
            elif len(args) == 3:
                return args[:2]
            else:
                raise TypeError("Wrong number of arguments")
        return self._array_converter(self.sip.foc2pix, None, *args, **kwargs)
    sip_foc2pix.__doc__ = """
        Convert focal plane coordinates to pixel coordinates using the
        `SIP`_ polynomial distortion convention.

        `Paper IV`_ table lookup distortion correction is not applied,
        even if that information existed in the FITS file that
        initialized this `~pywcs.WCS` object.

        %s

        **Exceptions:**

        - `MemoryError`: Memory allocation failed.

        - `ValueError`: Invalid coordinate transformation parameters.
        """ % (__.TWO_OR_THREE_ARGS('pixel coordinates', '2', 8))

    def to_header(self, relax=False):
        """
        Generate a `pyfits`_ header object with the WCS information
        stored in this object.

        .. warning::

          This function does not write out SIP or Paper IV distortion
          keywords, yet, only the core WCS support by `wcslib`_.

        The output header will almost certainly differ from the input in a
        number of respects:

          1. The output header only contains WCS-related keywords.  In
             particular, it does not contain syntactically-required
             keywords such as ``SIMPLE``, ``NAXIS``, ``BITPIX``, or
             ``END``.

          2. Deprecated (e.g. ``CROTAn``) or non-standard usage will
             be translated to standard (this is partially dependent on
             whether `fix` was applied).

          3. Quantities will be converted to the units used internally,
             basically SI with the addition of degrees.

          4. Floating-point quantities may be given to a different decimal
             precision.

          5. Elements of the ``PCi_j`` matrix will be written if and
             only if they differ from the unit matrix.  Thus, if the
             matrix is unity then no elements will be written.

          6. Additional keywords such as ``WCSAXES``, ``CUNITia``,
             ``LONPOLEa`` and ``LATPOLEa`` may appear.

          7. The original keycomments will be lost, although
             `to_header` tries hard to write meaningful comments.

          8. Keyword order may be changed.

        - *relax*: Degree of permissiveness:

          - `False`: Recognize only FITS keywords defined by the
            published WCS standard.

          - `True`: Admit all recognized informal extensions of the WCS
            standard.

          - `int`: a bit field selecting specific extensions to write.
            See :ref:`relaxwrite` for details.

        Returns a `pyfits`_ Header object.
        """
        header_string = self.wcs.to_header(relax)
        cards = pyfits.CardList()
        for i in range(0, len(header_string), 80):
            card_string = header_string[i:i+80]
            card = pyfits.Card()
            card.fromstring(card_string)
            cards.append(card)
        return pyfits.Header(cards)

    def to_header_string(self, relax=False):
        """
        Identical to `to_header`, but returns a string containing the
        header cards.
        """
        return self.to_header(self, relax).to_string()

    def footprint_to_file(self, filename=None, color='green', width=2):
        """
        Writes out a `ds9`_ style regions file. It can be loaded
        directly by `ds9`_.

        - *filename*: string.  Output file name - default is
          ``'footprint.reg'``

        - *color*: string.  Color to use when plotting the line.

        - *width*: int.  Width of the region line.
        """
        if not filename:
            filename = 'footprint.reg'
        comments = '# Region file format: DS9 version 4.0 \n'
        comments += '# global color=green font="helvetica 12 bold select=1 highlite=1 edit=1 move=1 delete=1 include=1 fixed=0 source\n'

        f = open(filename, 'a')
        f.write(comments)
        f.write('linear\n')
        f.write('polygon(')
        self.footprint.tofile(f, sep=',')
        f.write(') # color=%s, width=%d \n' % (color, width))
        f.close()

    def get_naxis(self, header=None):
        self.naxis1 = 0.0
        self.naxis2 = 0.0
        if header != None:
            self.naxis1 = header.get('NAXIS1', 0.0)
            self.naxis2 = header.get('NAXIS2', 0.0)

    def rotateCD(self, theta):
        _theta = DEGTORAD(theta)
        _mrot = np.zeros(shape=(2,2),dtype=np.double)
        _mrot[0] = (np.cos(_theta),np.sin(_theta))
        _mrot[1] = (-np.sin(_theta),np.cos(_theta))
        new_cd = np.dot(self.wcs.cd, _mrot)
        self.wcs.cd = new_cd

    def printwcs(self):
        """
        Temporary function for internal use.
        """
        print 'WCS Keywords\n'
        if hasattr(self.wcs, 'cd'):
            print 'CD_11  CD_12: %r %r' % (self.wcs.cd[0,0],  self.wcs.cd[0,1])
            print 'CD_21  CD_22: %r %r' % (self.wcs.cd[1,0],  self.wcs.cd[1,1])
        print 'CRVAL    : %r %r' % (self.wcs.crval[0], self.wcs.crval[1])
        print 'CRPIX    : %r %r' % (self.wcs.crpix[0], self.wcs.crpix[1])
        print 'NAXIS    : %r %r' % (self.naxis1, self.naxis2)

    def get_axis_types(self):
        """
        ``list of dicts``

        Similar to `self.wcsprm.axis_types <_pywcs._Wcsprm.axis_types>`
        but provides the information in a more Python-friendly format.

        Returns a list of dictionaries, one for each axis, each
        containing attributes about the type of that axis.

        Each dictionary has the following keys:

        - 'coordinate_type':

          - None: Non-specific coordinate type.

          - 'stokes': Stokes coordinate.

          - 'celestial': Celestial coordinate (including ``CUBEFACE``).

          - 'spectral': Spectral coordinate.

        - 'scale':

          - 'linear': Linear axis.

          - 'quantized': Quantized axis (``STOKES``, ``CUBEFACE``).

          - 'non-linear celestial': Non-linear celestial axis.

          - 'non-linear spectral': Non-linear spectral axis.

          - 'logarithmic': Logarithmic axis.

          - 'tabular': Tabular axis.

        - 'group'

          - Group number, e.g. lookup table number

        - 'number'

          - For celestial axes:

            - 0: Longitude coordinate.

            - 1: Latitude coordinate.

            - 2: ``CUBEFACE`` number.

          - For lookup tables:

            - the axis number in a multidimensional table.

        ``CTYPEia`` in ``"4-3"`` form with unrecognized algorithm code will
        generate an error.
        """
        if self.wcs is None:
            raise AttributeError(
                "This WCS object does not have a wcsprm object.")

        coordinate_type_map = {
            0: None,
            1: 'stokes',
            2: 'celestial',
            3: 'spectral'
            }

        scale_map = {
            0: 'linear',
            1: 'quantized',
            2: 'non-linear celestial',
            3: 'non-linear spectral',
            4: 'logarithmic',
            5: 'tabular'
            }

        result = []
        for axis_type in self.wcs.axis_types:
            subresult = {}

            coordinate_type = (axis_type // 1000) % 10
            subresult['coordinate_type'] = coordinate_type_map[coordinate_type]

            scale = (axis_type // 100) % 10
            subresult['scale'] = scale_map[scale]

            group = (axis_type // 10) % 10
            subresult['group'] = group

            number = axis_type % 10
            subresult['number'] = number

            result.append(subresult)

        return result


def DEGTORAD(deg):
    return (deg * np.pi / 180.)

def RADTODEG(rad):
    return (rad * 180. / np.pi)


def find_all_wcs(header, relax=False, keysel=None):
    """
    Find all the WCS transformations in the given header.

    - *header*: A PyFITS header object.

    - *relax*: Degree of permissiveness:

        - `False`: Recognize only FITS keywords defined by the
          published WCS standard.

        - `True`: Admit all recognized informal extensions of the
          WCS standard.

        - `int`: a bit field selecting specific extensions to accept.
          See :ref:`relaxread` for details.

    - *keysel*: A list of flags used to select the keyword types
      considered by wcslib.  When ``None``, only the standard image
      header keywords are considered (and the underlying wcspih() C
      function is called).  To use binary table image array or pixel
      list keywords, *keysel* must be set.

      Each element in the list should be one of the following strings:

        - 'image': Image header keywords

        - 'binary': Binary table image array keywords

        - 'pixel': Pixel list keywords

      Keywords such as ``EQUIna`` or ``RFRQna`` that are common to
      binary table image arrays and pixel lists (including ``WCSNna``
      and ``TWCSna``) are selected by both 'binary' and 'pixel'.

    Returns a list of `WCS` objects.
    """
    header_string = repr(header.ascard)

    keysel_flags = _parse_keysel(keysel)

    wcsprms = _pywcs.find_all_wcs(header_string, relax, keysel_flags)

    result = []
    for wcsprm in wcsprms:
        subresult = WCS()
        subresult.wcs = wcsprm
        result.append(subresult)

    return result