Esempio n. 1
0
def CompareSum( fname1, fname2, referenceSum_fname, minValue=0.0 ):
	"""Sum the first two images and compare the result with the third; if the maximum
	relative deviation is >= 1e-6, return False, else return True.
	"""
	# kludge to avoid division by zero or very small numbers problem when one or
	# more input image has values equal to or very close to zero: add 1 to each
	# input image (and 2 to the reference image)
	imdata1 = fits_open(fname1)[0].data + 1.0
	imdata2 = fits_open(fname2)[0].data + 1.0
	imSum = imdata1 + imdata2
	refSum_imdata = fits_open(referenceSum_fname)[0].data + 2.0
	devianceImdata = np.abs((imSum / refSum_imdata) - 1.0)
		
	if np.max(devianceImdata) >= TOLERANCE:
# 		i,j = np.unravel_index(devianceImdata.argmax(), devianceImdata.shape)
# 		print()
# 		print(np.max(devianceImdata))
# 		print(imSum[i,j], refSum_imdata[i,j], devianceImdata[i,j])
# 		print()
		return False
	else:
		return True
Esempio n. 2
0
def open_kepler(filename):
    """ Opens a Kepler filename and retrieves corrected flux """
    if os.path.exists(filename)==False:
        print "{} not found".format(filename)
        return [-1],[-1],[-1]

    hdu = fits_open(filename)
    #print hdu[1].data.dtype.names
    time = hdu[1].data.field("TIME")

    ## Use the corrected flux, not raw
    flux = hdu[1].data.field("PDCSAP_FLUX")
    flux_err = hdu[1].data.field("PDCSAP_FLUX_ERR")
    hdu.close()
    return time,flux,flux_err
Esempio n. 3
0
def paths_to_fits(paths):
    """
    paths (tuple): list of paths to a astronomical image which can be opened with
                  casacore
                  
    returns:
        tuple: of HDUlist objects
    """
    for path in paths:
        try:
            i = casacore_image(path)
        except RuntimeError:
            logging.error("can't open image {}".format(path))
            yield
        else:
            with NamedTemporaryFile() as temp_file:
                i.tofits(temp_file.name)
                fits = fits_open(temp_file.name)
                yield cPickle.dumps(fits[0].data), str(fits[0].header)
Esempio n. 4
0
    def get_stamps(self, oid, candid=None):
        """Download Stamps for an specific alert.

        Parameters
        ----------
        oid : :py:class:`str`
            object ID in ALeRCE DBs.
        candid : :py:class:`int`
            Candid of the stamp to be displayed.

        Returns
        -------
        :class:`astropy.io.fits.HDUList`
            Science, Template and Difference stamps for an specific alert.
        """
        if candid is None:
            candid = self._get_first_detection(oid)
        try:
            hdulist = HDUList()
            for stamp_type in ["science", "template", "difference"]:
                tmp_hdulist = fits_open(
                    "%s?oid=%s&candid=%s&type=%s&format=fits"
                    % (
                        self.config["AVRO_URL"]
                        + self.config["AVRO_ROUTES"]["get_stamp"],
                        oid,
                        candid,
                        stamp_type,
                    )
                )
                hdu = tmp_hdulist[0]
                hdu.header["STAMP_TYPE"] = stamp_type
                hdulist.append(hdu)
            return hdulist
        except HTTPError:
            warnings.warn("AVRO File not found.", RuntimeWarning)
            return None
Esempio n. 5
0
    def get_stamp(self, oid='', candid=0, stamp='science', output='png'):
        """
            :param oid: str, case-sensitive, ZTF identifier
            :param candid: int, candidate identifier (0 for earliest)
            :param stamp: str, stamp from ['science', 'difference', 'template']
            :param output: str, output format from ['fits', 'jpg', 'png']
            :return: thumbnail in given format or None
        """

        # check input(s)
        if not isinstance(oid, str) or oid.strip() == '':
            return
        if not isinstance(candid, int) or candid < 0:
            return
        if not isinstance(stamp, str) or stamp.strip().lower() not in self.__alerce_stamps:
            return
        if not isinstance(output, str) or output.strip().lower() not in self.__alerce_outputs:
            return
        if self.__log:
            self.__log.debug(f"get_stamp(oid='{oid}', candid={candid}, stamp='{stamp}', output='{output}')")

        # execute
        self.__reinit__()
        self.__oid = oid
        self.__stamp = stamp.strip().lower()
        self.__output = output.strip().lower()

        if candid > 0:
            self.__candid = candid
        else:
            self.__url = 'https://ztf.alerce.online/get_detections'
            self.__json = {'oid': f'{self.__oid}'}
            self.__detections = self.__http_post__()
            if self.__detections is None:
                return
            _tmp = {_i['mjd']: _i['candid'] for _i in self.__detections['result']['detections']}
            _min = min(_tmp.keys())
            self.__candid = _tmp[_min]
        self.__url = f'https://avro.alerce.online/get_stamp?' \
                     f'oid={self.__oid}&candid={self.__candid}&type={self.__stamp}&format=fits'

        # get data
        try:
            self.__image = fits_open(self.__url)[0]
            self.__image.header['STAMP'] = self.__stamp
        except Exception as _e:
            if self.__log:
                self.__log.error(f"failed to get_stamp(oid='{oid}', candid={candid}, stamp='{stamp}'), error={_e}")
            return

        # create output file
        self.__output = os.path.join(os.getcwd(), f'{self.__oid}_{self.__candid}_{self.__stamp}.{self.__output}')
        try:
            if 'fits' in self.__output:
                self.__image.writeto(self.__output)
            else:
                self.__image = Image.fromarray(self.__image.data)
                self.__image.convert('RGB').save(self.__output)
        except:
            pass
        return self.__output
Esempio n. 6
0
def CompareImagesEqual( fname1, fname2, minValue=0.0 ):
	imdata1 = fits_open(fname1)[0].data
	imdata2 = fits_open(fname2)[0].data
	validPix = imdata2 > minValue
	return np.array_equal(imdata1[validPix], imdata2[validPix])
Esempio n. 7
0
def CompareImagesNew( fname1, fname2, tol=TOERLANCE_ALLCLOSE ):
	imdata1 = fits_open(fname1)[0].data
	imdata2 = fits_open(fname2)[0].data
	return np.allclose(imdata1, imdata2, rtol=0, atol=tol)