Esempio n. 1
0
    def getDate(self, line, columns):
        if columns['sep'] == ',':
            fields = line.split(columns['sep'])
            dateStr = fields[columns['Date']['num']].strip()
        else:
            dateStr = line[columns['Date']['start']:columns['Date']['end']]
        if columns['Date']['type'] == 'CAL':
            dateFmt = columns['Date']['format']
            if '.' in dateStr:
                dateTimeStr, msecStr = dateStr.split('.')
                msec = int(msecStr)
            else:
                dateTimeStr = dateStr
                msec = 0
        elif columns['Date']['type'] == 'JD':
            # The subtraction is because sla_djcl wants an MJD
            jd = float(dateStr)
            yy, mm, dd, fracDay, j = slalib.sla_djcl(jd - 2400000.5)
            sign, hmsf = slalib.sla_dd2tf(3, fracDay)
            dateStr = '-'.join([str(yy), '%02d' % mm, '%02d' % dd])
            timeStr = ':'.join(
                ['%02d' % hmsf[0],
                 '%02d' % hmsf[1],
                 '%02d' % hmsf[2]])
            dateTimeStr = ' '.join([dateStr, timeStr])
            dateFmt = '%Y-%m-%d %H:%M:%S'
            msec = int(hmsf[3])

        date = datetime.datetime.strptime(
            dateTimeStr, dateFmt) + datetime.timedelta(milliseconds=msec)
        return date
Esempio n. 2
0
def mjd_to_greg(mjd):
    """
    Convert MJD into gregorian date.

    Parameters
    ----------
    mjd : float
        Date in the format MJD.

    Returns
    ----------
    greg : string
        Gregorian date (format: YYYYMMDD_HHMMSS)

    Examples
    ----------
    >>> mjd = greg_to_mjd('19881103_000000')
    >>> greg = mjd_to_greg(mjd)
    >>> print('MJD={} ->'.format(round(mjd, 2)), 'GREG={}'.format(greg))
    MJD=47468.0 -> GREG=19881103_000000
    """
    year, month, day, fracday, baddate = slalib.sla_djcl(mjd)

    if baddate:
        raise ValueError(BadMJD)

    sign, (hour, minute, second, frac) = slalib.sla_dd2tf(2, fracday)

    s = '{:4d}{:2d}{:2d}_{:2d}{:2d}{:2d}'.format(year, month, day, hour,
                                                 minute, second)
    s = s.replace(' ', '0')

    return s
Esempio n. 3
0
def mjd_utc2datetime(mjd):
    """Converts a passed Modified Julian date to a Python datetime object. 'None' is
    returned if the conversion was not possible."""

    year, month, day, frac, status = S.sla_djcl(mjd)
    if status != 0:
        return None
    sign, hms = S.sla_dd2tf(0, frac)
    dt = datetime(year, month, day, hms[0], hms[1], hms[2])
    return dt
Esempio n. 4
0
def utcFromMjd (mjd) :
    from pyslalib import slalib
    date = slalib.sla_djcl(mjd)
    year = np.int(date[0])
    month= np.int(date[1])
    day = np.int(date[2])
    hour = np.int(date[3]*24.)
    minute = np.int( (date[3]*24.-hour)*60.  )
    #time = "UTC-{}-{}-{}-{:02d}:{:02d}:00"..format(year,month,day,hour,minute)  old way
    time = "UTC-{}-{:02d}-{:02d}-{:02d}:{:02d}:00".format(year,month,day,hour,minute)
    return time
Esempio n. 5
0
def jd_utc2datetime(jd):
    """Converts a passed Julian date to a Python datetime object. 'None' is
    returned if the conversion was not possible."""

    try:
        mjd_utc = jd - 2400000.5
    except TypeError:
        try:
            mjd_utc = float(jd) - 2400000.5
        except:
            return None
    year, month, day, frac, status = S.sla_djcl(mjd_utc)
    if status != 0:
        return None
    sign, hms = S.sla_dd2tf(0, frac)
    dt = datetime(year, month, day, hms[0], hms[1], hms[2])
    return dt
Esempio n. 6
0
def parse_archive(filenm):
    """
    Parse an input fits file header and create a remote path.

    Parameters
    ----------
    filenm : str
        The name of the input archive.

    Returns
    -------
    cornell_path : str
        The path to send to the Cornell FTP server.
    ubc_path : str
        The path to send to the UBC data archive.
    """

    # Open the file using pyfits and get the header
    hdulist = PF.open(filenm)
    hdr     = hdulist[0].header
    hdulist.close()
    source  = hdr["SRC_NAME"].strip("B").strip("J")
    backend = hdr["BACKEND"]

    if backend == "GUPPI2":
        # This is for uniformity between incoherent/coherent GUPPI modes
        backend = "GUPPI" 
        year = hdr["DATE-OBS"].split("-")[0]

    elif backend == "PUPPI":
        year = hdr["DATE-OBS"].split("-")[0]
    
    elif backend == "xASP":
        backend = "ASP"
        MJD     = hdr["STT_IMJD"] + hdr["STT_SMJD"]/SECPERDAY
        year    = str(sla_djcl(MJD)[0]) # Convert MJD to calendar date

    else:
        backend = None
        year    = None

    return source,backend,year
Esempio n. 7
0
def processDatetime(dateTime):
    """
    Returns a Python datetime object.

    Given a date/time, supplied as any any of the following:
    
      - Python datetime object
      - Julian date (JD)
      - Modified Julian date (MJD)
      - YYYYMMDD.DDDD
      - YYYYMMDD HH:MM:SS (You can leave off the HH:MM:SS or some subset of that)
      - YYYY-MM-DD HH:MM:SS (You can leave off the HH:MM:SS or some subset of that)
      - YYYY/MM/DD HH:MM:SS (You can leave off the HH:MM:SS or some subset of that)
      - YYYY-MMM-DD HH:MM

    returns the equivalent date/time, expressed as a Python datetime
    object.

    Args:
        jd: The date/time

    Returns:
        The date/time, expressed as a datetime object
    """
    dateTimeFormats = ('%Y%m%d', '%Y-%m-%d', '%Y/%m/%d', '%Y%m%d %H',
                       '%Y%m%d %H%M', '%Y%m%d %H%M%S', '%Y%m%d %H',
                       '%Y%m%d %H:%M', '%Y%m%d %H:%M:%S', '%Y%m%d-%H',
                       '%Y%m%d-%H:%M', '%Y%m%d-%H:%M:%S', '%Y-%m-%dT%H',
                       '%Y-%m-%dT%H:%M', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H',
                       '%Y-%m-%d %H:%M', '%Y-%m-%d %H:%M:%S', '%Y/%m/%d %H',
                       '%Y/%m/%d %H:%M', '%Y/%m/%d %H:%M:%S', '%Y-%b-%d %H:%M')

    # if the input value is already a datetime object, just return it.
    if isinstance(dateTime, datetime.datetime):
        return dateTime
    else:
        # The input value might be a JD, MJD, or a YYYYMMDD.DDDD. If
        # it is any of those, we can convert it to a float. If we
        # can't convert it to a float, it must be one of the string
        # representations, e.g., YYYYMMDD HH:MM:SS.
        try:
            dateTime = float(dateTime)
        except ValueError:
            pass

        if isinstance(dateTime, float):
            # The input is a float. Now we have to determine if it is
            # YYYYMMDD.DDDD or JD/MJD.  If the string represention of
            # the date portion of the input is the same length as
            # 'YYYYMMDD', it must be a YYYYMMDD.DDDD. JD and MJD dates
            # are typically either 7 or 5 characters long,
            # respectively, not 8 characters, at least for the range
            # of dates that we usually care about.
            (fracDay, date) = math.modf(dateTime)
            if len(str(int(date))) == len('YYYYMMDD'):
                # Convert input YYYYMMDD.DDDD into datetime object
                return datetime.datetime.strptime(str(
                    int(date)), '%Y%m%d') + datetime.timedelta(days=fracDay)
            else:
                # Input is either JD or MJD. Raise an exception if we
                # slalib isn't available.
                if not jdOk:
                    raise NoSlalibError(
                        'Julian dates require slalib, but slalib is not available'
                    )
                # For the dates that we care about, if the value is
                # greater than 2400000, we assume that it is a JD, so
                # convert it to an MJD.
                if dateTime > 2400000:
                    dateTime -= 2400000.5
                yy, mm, dd, fracDay, j = slalib.sla_djcl(dateTime - 2400000.5)
                sign, hmsf = slalib.sla_dd2tf(3, fracDay)
                dateStr = '-'.join([str(yy), '%02d' % mm, '%02d' % dd])
                timeStr = ':'.join(
                    ['%02d' % hmsf[0],
                     '%02d' % hmsf[1],
                     '%02d' % hmsf[2]])
                dateTimeStr = ' '.join([dateStr, timeStr])
                dateFmt = '%Y-%m-%d %H:%M:%S'
                msec = int(hmsf[3])
                return datetime.datetime.strptime(
                    dateTimeStr,
                    dateFmt) + datetime.timedelta(milliseconds=msec)

        elif isinstance(dateTime, str):
            # The input date is a string. Using one of the acceptable
            # formats, parse it and create a datetime object.
            dateTimeObj = None
            for format in dateTimeFormats:
                try:
                    dateTimeObj = datetime.datetime.strptime(dateTime, format)
                    break
                except ValueError:
                    pass

            # If we were able to parse the input string, return the
            # datetime object. Otherwise, raise an exception.
            if dateTimeObj:
                return dateTimeObj
            else:
                raise DateTimeFormatError('Unexpected date/time format: %s' %
                                          dateTime)
        else:
            raise DateTimeFormatError('Unexpected date/time format: %s' %
                                      dateTime)
Esempio n. 8
0
    def __init__(self,
                 ra,
                 dec,
                 values,
                 mjd,
                 alpha=0.,
                 degradeRes=True,
                 verbose=True):
        self.verbose = verbose
        data_dir = os.environ["DESGW_DATA_DIR"]
        ctio_lat = -30.16527778
        ctio_lon = -70.8125
        ctio_height = 2215.

        self.date = slalib.sla_djcl(mjd)

        self.degToRad = 0.0174532925199
        self.lat = ctio_lat * self.degToRad
        self.lon = ctio_lon * self.degToRad
        self.height = ctio_height

        self.mjd = mjd
        self.ra = ra * self.degToRad
        self.dec = dec * self.degToRad
        self.map = values
        self.nside = hp.npix2nside(values.size)

        # observational astronomy
        self.lst = self.mjdToLST(self.mjd, self.lon)
        self.ha, self.zd = self.equatorialToObservational(
            self.ra, self.dec, self.lst, self.lat)
        self.airmass = self.airmassModel(self.zd)
        self.sunData = self.getSolarPosition(self.mjd, self.lon, self.lat,
                                             self.lst)
        self.sunZD = self.sunData[2]
        self.moonData = self.getLunarPosition(self.mjd, self.lon, self.lat,
                                              self.lst)
        self.moonZD = self.moonData[2]
        self.moonSep = self.getLunarSeparation(self.ra, self.dec,
                                               self.moonData)
        self.moonPhase = self.getLunarPhase()

        # telescope limits
        self.limits = 0.0

        # galactic dust
        dust_dir = data_dir
        dust_file = "plank-ebv-HFI_CompMap_ThermaDustModel.fits"
        ra, dec, ebv = dustModel.loadDust(dust_dir, dust_file)
        if degradeRes:
            ra, dec, ebv = hp2np.map2np(ebv,
                                        resolution=self.nside,
                                        fluxConservation=False)
        self.dust_ra = ra
        self.dust_dec = dec
        self.ebv = ebv

        # stellar density in the form of a probability of recognizing object map
        print "\t loading inverse stellar density = probability of recognition map"
        ra, dec, precog = hp2np.hp2np(data_dir + "precognize.fits")
        if degradeRes:
            ra, dec, precog = hp2np.map2np(precog,
                                           resolution=self.nside,
                                           fluxConservation=False)
        self.pra = ra
        self.pdec = dec
        self.precog = precog

        # limiting mag
        self.maglim = ""
        self.maglimall = ""

        # where to put the central meridan in the  mcbryde-thomas projection
        # - the ra which one wants on the meridian
        self.mcbryde_alpha = alpha