Apply distortion model to WCS, including modifying
        CD with linear distortion terms
551010
def apply_model(refwcs):
    
    # apply distortion model to CD matrix
    if 'ocx10' in refwcs.__dict__ and refwcs.ocx10 is not None:
        linmat = np.array([[refwcs.ocx11,refwcs.ocx10],[refwcs.ocy11,refwcs.ocy10]])/refwcs.idcscale
        refwcs.wcs.cd = np.dot(refwcs.wcs.cd,linmat)

        refwcs.wcs.set()
        refwcs.setOrient()
        refwcs.setPscale()
630389
def createWcsHDU(self):
        
        hdu = fits.ImageHDU()
        hdu.header['EXTNAME'] = 'WCS'
        hdu.header['EXTVER'] = 1
        # Now, update original image size information
        hdu.header['WCSAXES'] = (2, "number of World Coordinate System axes")
        hdu.header['NPIX1'] = (self.naxis1, "Length of array axis 1")
        hdu.header['NPIX2'] = (self.naxis2, "Length of array axis 2")
        hdu.header['PIXVALUE'] = (0.0, "values of pixels in array")

        # Write out values to header...
        excluded_keys = ['naxis1','naxis2']
        for key in self.wcskeys:
            _dkey = self.wcstrans[key]
            if _dkey not in excluded_keys:
                hdu.header[key] = self.__dict__[_dkey]


        return hdu
393832
def scale_WCS(self,pixel_scale,retain=True):
        ''' 
        '''
        _ratio = pixel_scale / self.pscale

        # Correct the size of the image and CRPIX values for scaled WCS
        self.naxis1 /= _ratio
        self.naxis2 /= _ratio
        self.crpix1 = self.naxis1/2.
        self.crpix2 = self.naxis2/2.

        if retain:
            # Correct the WCS while retaining original distortion information
            self.cd11 *= _ratio
            self.cd12 *= _ratio
            self.cd21 *= _ratio
            self.cd22 *= _ratio
        else:
            pscale = pixel_scale / 3600.
            self.cd11 = -pscale * N.cos(pa)
            self.cd12 = pscale * N.sin(pa)
            self.cd21 = self.cd12
            self.cd22 = -self.cd11

        # Now make sure that all derived values are really up-to-date based
        # on these changes
        self.update()
949102
def _cdf(self, xloc, dist, cache):
        """"""
        return evaluation.evaluate_forward(dist, numpy.e**xloc, cache=cache)
1289868
def compute_trans(expnums, ccd, version, prefix=None, default="WCS"):
    
    wcs_dict = {}
    for expnum in expnums:
        try:
            # TODO This assumes that the image is already N/E flipped.
            # If compute_trans is called after the image is retrieved from archive then we get the disk version.
            filename = storage.get_image(expnum, ccd, version, prefix=prefix)
            this_wcs = wcs.WCS(fits.open(filename)[0].header)
        except Exception as err:
            logging.warning("WCS Trans compute failed. {}".format(str(err)))
            return
        wcs_dict[expnum] = this_wcs
    x0 = wcs_dict[expnums[0]].header['NAXIS1'] / 2.0
    y0 = wcs_dict[expnums[0]].header['NAXIS2'] / 2.0
    (ra0, dec0) = wcs_dict[expnums[0]].xy2sky(x0, y0)
    result = ""
    for expnum in expnums:
        filename = storage.get_file(expnum, ccd, version, ext='.trans.jmp', prefix=prefix)
        jmp_trans = file(filename, 'r').readline().split()
        (x, y) = wcs_dict[expnum].sky2xy(ra0, dec0)
        x1 = float(jmp_trans[0]) + float(jmp_trans[1]) * x + float(jmp_trans[2]) * y
        y1 = float(jmp_trans[3]) + float(jmp_trans[4]) * x + float(jmp_trans[5]) * y
        dr = math.sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2)
        if dr > 0.5:
            result += "WARNING: WCS-JMP transforms mis-matched {} reverting to using {}.\n".format(expnum, default)
            if default == "WCS": 
               uri = storage.dbimages_uri(expnum, ccd, version, ext='.trans.jmp', prefix=prefix)
               filename = os.path.basename(uri)
               trans = file(filename, 'w')
               trans.write("{:5.2f} 1. 0. {:5.2f} 0. 1.\n".format(x0 - x, y0 - y))
               trans.close()
        else:
            result += "WCS-JMP transforms match {}\n".format(expnum)
    return result
1334783
def _process_input_wcs_single(fname, wcskey, updatewcs):
    
    if wcskey in ['', ' ', 'INDEF', None]:
        if updatewcs:
            uw.updatewcs(fname, checkfiles=False)
    else:
        numext = fileutil.countExtn(fname)
        extlist = []
        for extn in range(1, numext + 1):
            extlist.append(('SCI', extn))
        if wcskey in string.ascii_uppercase:
            wkey = wcskey
            wname = ' '
        else:
            wname = wcskey
            wkey = ' '
        altwcs.restoreWCS(fname, extlist, wcskey=wkey, wcsname=wname)
    # make an asn table at the end
    # Make sure there is a WCSCORR table for each input image
    if wcskey not in ['', ' ', 'INDEF', None] or updatewcs:
        wcscorr.init_wcscorr(fname)
217894
def _hgvs_coord_to_ci(s, e):
    """"""

    def _hgvs_to_ci(c):
        assert c != 0, "received CDS coordinate 0; expected ..,-2,-1,1,1,..."
        return c - 1 if c > 0 else c

    return (None if s is None else _hgvs_to_ci(s), None if e is None else _hgvs_to_ci(e) + 1)
717701
def _cdf(self, xloc, dist, base, cache):
        """"""
        return evaluation.evaluate_forward(dist, base**xloc, cache=cache)
938959
function boxBlur(scl, tcl, w, h, r) {
    for (var i = 0, l = scl.length; i < l; i++) { tcl[i] = scl[i]; }
    boxBlurH(tcl, scl, w, h, r);
    boxBlurV(scl, tcl, w, h, r);
}
1083376
def wcs_to_coords(w, shape):
    """"""
    if w.naxis == 2:
        y, x = wcs_to_axes(w, shape)
    elif w.naxis == 3:
        z, y, x = wcs_to_axes(w, shape)
    else:
        raise Exception("Wrong number of WCS axes %i" % w.naxis)

    x = 0.5 * (x[1:] + x[:-1])
    y = 0.5 * (y[1:] + y[:-1])

    if w.naxis == 2:
        x = np.ravel(np.ones(shape) * x[:, np.newaxis])
        y = np.ravel(np.ones(shape) * y[np.newaxis, :])
        return np.vstack((x, y))

    z = 0.5 * (z[1:] + z[:-1])
    x = np.ravel(np.ones(shape) * x[:, np.newaxis, np.newaxis])
    y = np.ravel(np.ones(shape) * y[np.newaxis, :, np.newaxis])
    z = np.ravel(np.ones(shape) * z[np.newaxis, np.newaxis, :])

    return np.vstack((x, y, z))
68198
def build_reference_wcs(inputs, sciname='sci'):
    """"""
    # start by creating a composite field-of-view for all inputs
    wcslist = []
    for img in inputs:
        nsci = countExtn(img)
        for num in range(nsci):
            extname = (sciname, num + 1)
            if sciname == 'sci':
                extwcs = wcsutil.HSTWCS(img, ext=extname)
            else:
                # Working with HDRLET as input and do the best we can...
                extwcs = read_hlet_wcs(img, ext=extname)

            wcslist.append(extwcs)

    # This default output WCS will have the same plate-scale and orientation
    # as the first chip in the list, which for WFPC2 data means the PC.
    # Fortunately, for alignment, this doesn't matter since no resampling of
    # data will be performed
    outwcs = utils.output_wcs(wcslist)

    return outwcs
1160267
def build_hstwcs(crval1, crval2, crpix1, crpix2, naxis1, naxis2, pscale, orientat):
    
    wcsout = wcsutil.HSTWCS()
    wcsout.wcs.crval = np.array([crval1, crval2])
    wcsout.wcs.crpix = np.array([crpix1, crpix2])
    wcsout.naxis1 = naxis1
    wcsout.naxis2 = naxis2
    wcsout.wcs.cd = buildRotMatrix(orientat) * [-1, 1] * pscale / 3600.0
    # Synchronize updates with astropy.wcs objects
    wcsout.wcs.set()
    wcsout.setPscale()
    wcsout.setOrient()
    wcsout.wcs.ctype = ['RA---TAN', 'DEC--TAN']

    return wcsout
360917
def compamp_to_ac(compamp, window=np.hanning):  # convert single or multi-subband compamps into autocorrelation waterfall

  '''
  
  
  '''
  header = compamp.header()
 
  cdata = compamp.complex_data()

  #Apply Windowing and Padding
  cdata = np.multiply(cdata, window(cdata.shape[2]))  # window for smoothing sharp time series start/end in freq. dom.
  cdata_normal = cdata - cdata.mean(axis=2)[:, :, np.newaxis]  # zero mean, does influence a minority of lines in some plots

  cdata = np.zeros((cdata.shape[0], cdata.shape[1], 2 * cdata.shape[2]), complex)
  cdata[:, :, cdata.shape[2]/2:cdata.shape[2] + cdata.shape[2]/2] = cdata_normal  # zero-pad to 2N

  #Perform Autocorrelation
  cdata = np.fft.fftshift(np.fft.fft(cdata), 2)  # FFT all blocks separately and arrange correctly
  cdata = cdata.real**2 + cdata.imag**2  # FFT(AC(x)) = FFT(x)FFT*(x) = abs(x)^2
  cdata = np.fft.ifftshift(np.fft.ifft(cdata), 2)  # AC(x) = iFFT(abs(x)^2) and arrange correctly
  cdata = np.abs(cdata)  # magnitude of AC

  # normalize each row to sqrt of AC triangle
  cdata = np.divide(cdata, np.sqrt(np.sum(cdata, axis=2))[:, :, np.newaxis])  

  return cdata
225948
def verifyUpdatewcs(fname):
    
    updated = True
    numsci,extname = count_sci_extensions(fname)
    for n in range(1,numsci+1):
        hdr = fits.getheader(fname, extname=extname, extver=n, memmap=False)
        if 'wcsname' not in hdr:
            updated = False
            break
    return updated
1151412
def blur(dset,fwhm,prefix=None):
    ''''''
    if prefix==None:
        prefix = nl.suffix(dset,'_blur%.1fmm'%fwhm)
    return available_method('blur')(dset,fwhm,prefix)
645697
def updateWCS(self, pixel_scale=None, orient=None,refpos=None,refval=None,size=None):
        
        # Set up parameters necessary for updating WCS
        # Check to see if new value is provided,
        # If not, fall back on old value as the default

        _updateCD = no
        if orient is not None and orient != self.orient:
            pa = DEGTORAD(orient)
            self.orient = orient
            self._orient_lin = orient
            _updateCD = yes
        else:
            # In case only pixel_scale was specified
            pa = DEGTORAD(self.orient)

        if pixel_scale is not None and pixel_scale != self.pscale:
            _ratio = pixel_scale / self.pscale
            self.pscale = pixel_scale
            _updateCD = yes
        else:
            # In case, only orient was specified
            pixel_scale = self.pscale
            _ratio = None

        # If a new plate scale was given,
        # the default size should be revised accordingly
        # along with the default reference pixel position.
        # Added 31 Mar 03, WJH.
        if _ratio is not None:
            self.naxis1 /= _ratio
            self.naxis2 /= _ratio
            self.crpix1 = self.naxis1/2.
            self.crpix2 = self.naxis2/2.

        # However, if the user provides a given size,
        # set it to use that no matter what.
        if size is not None:
            self.naxis1 = size[0]
            self.naxis2 = size[1]

        # Insure that naxis1,2 always return as integer values.
        self.naxis1 = int(self.naxis1)
        self.naxis2 = int(self.naxis2)

        if refpos is not None:
            self.crpix1 = refpos[0]
            self.crpix2 = refpos[1]
        if self.crpix1 is None:
            self.crpix1 = self.naxis1/2.
            self.crpix2 = self.naxis2/2.

        if refval is not None:
            self.crval1 = refval[0]
            self.crval2 = refval[1]

        # Reset WCS info now...
        if _updateCD:
            # Only update this should the pscale or orientation change...
            pscale = pixel_scale / 3600.

            self.cd11 = -pscale * N.cos(pa)
            self.cd12 = pscale * N.sin(pa)
            self.cd21 = self.cd12
            self.cd22 = -self.cd11

        # Now make sure that all derived values are really up-to-date based
        # on these changes
        self.update()
1087359
def convertWCS(inwcs,drizwcs):
    
    drizwcs[0] = inwcs.crpix[0]
    drizwcs[1] = inwcs.crval[0]
    drizwcs[2] = inwcs.crpix[1]
    drizwcs[3] = inwcs.crval[1]
    drizwcs[4] = inwcs.cd[0][0]
    drizwcs[5] = inwcs.cd[1][0]
    drizwcs[6] = inwcs.cd[0][1]
    drizwcs[7] = inwcs.cd[1][1]

    return drizwcs