def downsize(lon_begin, lon_end, lat_begin, lat_end, start_month, end_month,
             vnp_fname):
    # downsize the viirs_cal_bbox.log to a specific spatiotemporal range
    file_object = open("viirs_cal_bbox.log", "r")
    lines = file_object.readlines()
    file_object.close()

    y = 2014
    JD01, JD02 = gcal2jd(y, 1, 1)
    JD1, JD2 = gcal2jd(y, start_month, 1)
    julian_begin = np.int((JD2 + JD1) - (JD01 + JD02) + 1)
    JD3, JD4 = gcal2jd(y, end_month, 31)
    julian_end = np.int((JD4 + JD3) - (JD01 + JD02) + 1)

    keep_line = []
    for lineno in range(len(lines)):
        line_inter = lines[lineno].rstrip()
        line_split = line_inter.split(' ')
        min_lon = float(line_split[1])
        max_lon = float(line_split[2])
        min_lat = float(line_split[3])
        max_lat = float(line_split[4])
        line_split2 = line_split[0].split('.')
        julian_day = int(line_split2[1][7:10])

        if ((julian_day >= julian_begin) & (julian_day <= julian_end)):
            if ((min_lon >= lon_begin) & (max_lon <= lon_end)):
                if ((min_lat >= lat_begin) & (max_lat <= lat_end)):
                    keep_line.append(lines[lineno].rstrip())

    df = pd.DataFrame(keep_line)
    df.to_csv(vnp_fname, index=False, header=False)
Esempio n. 2
0
def test_gcal2jd_negative_numbers_and_zero():
    assert gcal2jd(2000, -2, -4) == gcal2jd(1999, 9, 26)
    assert gcal2jd(2000, 2, -1) == gcal2jd(2000, 1, 30)
    assert gcal2jd(2000, 3, -1) == gcal2jd(2000, 2, 28)

    assert gcal2jd(2000, 3, 0) == gcal2jd(2000, 2, 29)
    assert gcal2jd(2001, 3, 0) == gcal2jd(2001, 2, 28)
Esempio n. 3
0
    def __init__(self, site):
        """
        Set up observing site using config file
        Have it take config info since whipple is probs summit
        Also sunset and sunrise should already be loaded for the site so
        ...just pass site to init and also config
        Switch to pyephem to match minerva
        """
        # Load Data
        self.dat = cTargets.loadTargets()
        self.night = site.night

        # Split time window into 30 increments
        # convert datetime into JD to do calc, then convert back using delta added to sunset to define times back into datetimes
        DAY = datetime.timedelta(1)
        J2000_JD = datetime.timedelta(2451545)
        JULIAN_EPOCH = datetime.datetime(2000, 1, 1, 12)

        dt = site.sunset()
        self.JDsunset = sum(jdcal.gcal2jd(
            dt.year, dt.month, dt.day)) + dt.hour / 24.0 + dt.minute / (
                24. * 60) + dt.second / (24. * 3600.0)

        dt = site.sunrise()
        self.JDsunrise = sum(jdcal.gcal2jd(
            dt.year, dt.month, dt.day)) + dt.hour / 24.0 + dt.minute / (
                24. * 60) + dt.second / (24. * 3600.0)

        self.time_window = self.JDsunset + (self.JDsunrise - self.JDsunset) * \
            np.linspace(0, 1, 30)
Esempio n. 4
0
def test_gcal2jd_negative_numbers_and_zero():
    assert gcal2jd(2000, -2, -4) == gcal2jd(1999, 9, 26)
    assert gcal2jd(2000, 2, -1) == gcal2jd(2000, 1, 30)
    assert gcal2jd(2000, 3, -1) == gcal2jd(2000, 2, 28)

    assert gcal2jd(2000, 3, 0) == gcal2jd(2000, 2, 29)
    assert gcal2jd(2001, 3, 0) == gcal2jd(2001, 2, 28)
Esempio n. 5
0
def fracyear_to_date(input):
  
  try:
    # Check to see if input is array. If it is, iterate through array.
    N = len(input)
    year = np.zeros(N)
    month = np.zeros(N)
    day = np.zeros(N)
    for i in range(0,N):
      year[i] = np.floor(input[i])
  
      day1 = jdcal.gcal2jd(year[i],1,1) # Get length of year
      day2 = jdcal.gcal2jd(year[i]+1,1,1)
      dayfrac[i] = (input[i]-year[i])*float(day2[1]+day2[0]-day1[0]-day1[1])

      year[i],month[i],day[i],frac = jdcal.jd2gcal(day1[0]+day1[1],dayfrac[i])

      day[i] = day[i]+frac
  except:
    # If input has no length (i.e., it's a float), then just calculate 
    # the date for that number.
    year = np.floor(input)
    day1 = jdcal.gcal2jd(year,1,1) # Get length of year
    day2 = jdcal.gcal2jd(year+1,1,1)
  
    dayfrac = (input-year)*float(day2[1]+day2[0]-day1[0]-day1[1])

    year,month,day,frac = jdcal.jd2gcal(day1[0]+day1[1],dayfrac)

    day = day+frac

  return year,month,day
Esempio n. 6
0
def date_to_doy(year,month,day):

  day0 = jdcal.gcal2jd(year,month,day)
  day2 = jdcal.gcal2jd(year+1,1,1)
  day1 = jdcal.gcal2jd(year,1,1)
  doy = day0[1]+day0[0]-day1[1]-day1[0]+1
  
  return year,doy
Esempio n. 7
0
def doy_to_fracyear(year,doy):

  day1 = jdcal.gcal2jd(year,1,1) # Get length of year
  day2 = jdcal.gcal2jd(year+1,1,1)

  fracyear = year + (doy-1)/(day2[1]+day2[0]-day1[0]-day1[1])

  return fracyear
def day_of_year(yr, mn, dy):
    '''
    yr,mn,dy (int)
    '''
    JD01, JD02 = gcal2jd(yr, 1, 1)
    JD1, JD2 = gcal2jd(yr, mn, dy)
    JD = np.int((JD2 + JD1) - (JD01 + JD02) + 1)
    return JD
Esempio n. 9
0
def fracyear_to_doy(input):

  year = np.floor(input)
  
  day1 = jdcal.gcal2jd(year,1,1) # Get length of year
  day2 = jdcal.gcal2jd(year+1,1,1)
  
  doy = (input-year)*float(day2[1]+day2[0]-day1[0]-day1[1])+1

  return year,doy
Esempio n. 10
0
def get_news(actor, start_date, end_date):
    service = build("customsearch", "v1",
                    developerKey="AIzaSyBdV1Emfi7Zd-T8_PQ1tr_Av7G4WuGpHOo")
    start_date_j = int(sum(gcal2jd(start_date.year, start_date.month, start_date.day)))
    end_date_j = int(sum(gcal2jd(end_date.year, end_date.month, end_date.day)))
    res = service.cse().list(
        q='{0} daterange:{1}-{2}'.format(actor, start_date_j, end_date_j),
        cx='012147580588716782987:kvx5v_ad2jk'
    ).execute()
    return res
Esempio n. 11
0
def get_news(actor, start_date, end_date):
    service = build("customsearch",
                    "v1",
                    developerKey="AIzaSyBdV1Emfi7Zd-T8_PQ1tr_Av7G4WuGpHOo")
    start_date_j = int(
        sum(gcal2jd(start_date.year, start_date.month, start_date.day)))
    end_date_j = int(sum(gcal2jd(end_date.year, end_date.month, end_date.day)))
    res = service.cse().list(q='{0} daterange:{1}-{2}'.format(
        actor, start_date_j, end_date_j),
                             cx='012147580588716782987:kvx5v_ad2jk').execute()
    return res
Esempio n. 12
0
def yearlength(year):
  '''
  Return number of days for year (depending on whether or not it is a leap year)
  '''
  
  day1 = jdcal.gcal2jd(year,1,1) # Get length of year
  day2 = jdcal.gcal2jd(year+1,1,1)
  
  days = day2[1]-day1[1]
  
  return days
Esempio n. 13
0
    def _year(self):
        """Return the year for all the TOAs of this pulsar
        """
        #day, jyear = self.dayandyear_old()
        gyear, gmonth, gday, gfd = mjd2gcal(self.stoas())

        # MJD of start of the year (31st Dec)
        mjdy = np.array([jdcal.gcal2jd(gyear[ii], 1, 0)[1] for ii in range(len(gfd))])
        # MJD of end of the year
        mjdy1 = np.array([jdcal.gcal2jd(gyear[ii]+1, 1, 0)[1] for ii in range(len(gfd))])

        # Day of the year
        doy = self.stoas() - mjdy
        
        return gyear + (self.stoas() - mjdy) / (mjdy1 - mjdy)
 def geostrophic_current(self, where, when, step = _numdifflength):
     LAT = where[1]
     LON = where[0]
     f   = 2*omega*sin(LAT*deg2rad) # Coriolis frequency at this latitude
     ttup       = when.timetuple()[:3]
     jday       = jdcal.gcal2jd(*ttup)[1]
     hfrac      = (when.hour + (when.minute + (when.second + when.microsecond*1e-6)/60.0)/60.0)/24.0
     lookuptime = jday+hfrac
     dlon   = 0.5*step/EarthMeanRadius/cos(LAT*deg2rad) # assume spherical earth
     dlat   = 0.5*step/EarthMeanRadius                  # assume spherical earth
     TIDE0  = array(1.0, float)
     TIDE1  = array(1.0, float)
     ISDATA = array(False, bool)
     #
     dummy = dtu10API.perth3( LAT, LON+dlon, lookuptime, TIDE1, ISDATA )
     if not bool(ISDATA):
         raise GridRangeViolation # perth3 does not resolve further
     dummy = dtu10API.perth3( LAT, LON-dlon, lookuptime, TIDE0, ISDATA )
     if not bool(ISDATA):
         raise GridRangeViolation # perth3 does not resolve further
     dtide_dx = float((TIDE1-TIDE0)/step) # centered difference
     #
     dummy = dtu10API.perth3( LAT+dlat, LON, lookuptime, TIDE1, ISDATA )
     if not bool(ISDATA):
         raise GridRangeViolation # perth3 does not resolve further
     dummy = dtu10API.perth3( LAT-dlat, LON, lookuptime, TIDE0, ISDATA )
     if not bool(ISDATA):
         raise GridRangeViolation # perth3 does not resolve further
     dtide_dy = float((TIDE1-TIDE0)/step) # centered difference
     #
     return g*array([-dtide_dy, dtide_dx], float)/f
Esempio n. 15
0
def JD(x):
    ''' Converts UTC time into Julian date
    http://129.79.46.40/~foxd/cdrom/musings/formulas/formulas.htm
    
    The above website contains all kinds of useful formulae for
    this type of stuff :)'''
    return sum(jdcal.gcal2jd(x.year, x.month, x.day))
Esempio n. 16
0
def parse_julian_date(dateString):
    from jdcal import gcal2jd
    flex_date = parse_flex_date(dateString)
    julian = gcal2jd(int(flex_date.year),
                     int(flex_date.month if flex_date.month != '' else '1'),
                     int(flex_date.day if flex_date.day != '' else '1'))
    return julian[0] + julian[1]
Esempio n. 17
0
def to_json(line, idx):
    values = line.split(',')
    # Designation
    name = values[2]
    color = [0.4, 1.0, 0.4, 0.5]
    # Epoch in yyyymmdd, convert
    ymd = values[8]
    dt = datetime.datetime.strptime(ymd, FMT)
    epoch = sum(jdcal.gcal2jd(dt.year, dt.month, dt.day))
    # Mean anomaly [deg]
    meananomaly = float(values[9])
    # Semimajor axis [Km]
    a_au = float(values[14])
    semimajoraxis = a_au * AU_TO_KM
    # Eccentricity
    eccentricity = float(values[13])
    # Argument of pericenter [deg]
    argofpericenter = float(values[10])
    # Ascending node [deg]
    ascendingnode = float(values[11])
    # Period in days
    period = pow(a_au, 1.5) * Y_TO_D
    # Inclination [deg]
    inclination = float(values[12])
    
    bean = SSO(name, color, epoch, meananomaly, semimajoraxis, eccentricity, argofpericenter, ascendingnode, period, inclination)
    
    jsonstr = json.dumps(bean.__dict__)
    
    return jsonstr
Esempio n. 18
0
 def get_julian_day(dt: datetime):
     day = sum(jdcal.gcal2jd(dt.year, dt.month, dt.day))
     day += dt.hour / 24
     day += dt.minute / 24 / 60
     day += dt.second / 24 / 60 / 60
     day += dt.microsecond / 24 / 60 / 60 / 1000000
     return day
Esempio n. 19
0
def test_gcal2jd_with_sla_cldj():
    """Compare gcal2jd with slalib.sla_cldj."""
    import random
    try:
        from pyslalib import slalib
    except ImportError:
        print("SLALIB (PySLALIB not available).")
        return 1
    n = 1000
    mday = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

    # sla_cldj needs year > -4699 i.e., 4700 BC.
    year = [random.randint(-4699, 2200) for i in range(n)]
    month = [random.randint(1, 12) for i in range(n)]
    day = [random.randint(1, 31) for i in range(n)]
    for i in range(n):
        x = 0
        if is_leap(year[i]) and month[i] == 2:
            x = 1
        if day[i] > mday[month[i]] + x:
            day[i] = mday[month[i]]

    jd_jdc = [gcal2jd(y, m, d)[1]
              for y, m, d in zip(year, month, day)]
    jd_sla = [slalib.sla_cldj(y, m, d)[0]
              for y, m, d in zip(year, month, day)]
    diff = [abs(i - j) for i, j in zip(jd_sla, jd_jdc)]
    assert max(diff) <= 1e-8
    assert min(diff) <= 1e-8
Esempio n. 20
0
File: ocal.py Progetto: mlv/ocal
    def __init__(self, **kw):
        """Initialize.

        Ideally called with constructor methods. Optional parameters include:
        * year, month, day: year, month, day according to the calendar system.
        * date: modified julian date
        * gregorian: if true (the default), use the Gregorian calendar to
        * convert year,month,day to a julian date.julian: if true, use the
        * Julian calendar to convert year,month,day to a julian date.
        """
        if 'calendar' in kw:
            cal = kw['calendar']
        else:
            # default calendar: Gregorian
            cal = GREGORIAN
        if 'date' in kw:
            self.date = kw['date']
        else:
            y = kw['year']
            m = kw['month']
            d = kw['day']
            if cal == GREGORIAN:
                self.date = int(jdcal.gcal2jd(y, m, d)[1])
            elif cal == JULIAN:
                self.date = int(jdcal.jcal2jd(y, m, d)[1])
            else:
                raise ValueError("Unknown calendar:{}".format(cal))
        self.calendar = cal
        self.sync_ymd()
Esempio n. 21
0
def to_excel(dt, offset=CALENDAR_WINDOWS_1900):
    jul = sum(gcal2jd(dt.year, dt.month, dt.day)) - offset
    if jul <= 60 and offset == CALENDAR_WINDOWS_1900:
        jul -= 1
    if hasattr(dt, 'time'):
        jul += time_to_days(dt)
    return jul
def getJulianDayNew(
    yr, mo, dy, hr, mn, sc
):  # items are year, anything, month, day, hour, minute, second  with offset=1 for boat file
    jd = gcal2jd(
        asInt(yr), asInt(mo),
        asInt(dy))[1] + (asInt(hr) + asInt(mn) / 60 + asInt(sc) / 3600) / 24.0
    return jd
Esempio n. 23
0
def conv2jd(datestr):
    from datetime import datetime
    from jdcal import gcal2jd
    (struse, fmt) = format_datestr(datestr)
    dt = datetime.strptime(struse, fmt).timetuple()
    jd = sum(gcal2jd(dt[0], dt[1], dt[2]))
    return jd
Esempio n. 24
0
    def test_julian_day(self):
        """
        Test Julian Day -> Datetime conversion
        """
        tuples = [gcal2jd(2000, x, 1) for x in range(1, 13)]

        ds = xr.Dataset({
            'first': (['lat', 'lon', 'time'], np.zeros([45, 90, 12])),
            'second': (['lat', 'lon', 'time'], np.zeros([45, 90, 12])),
            'lat':
            np.linspace(-88, 88, 45),
            'lon':
            np.linspace(-178, 178, 90),
            'time': [x[0] + x[1] for x in tuples]
        })
        ds.time.attrs['long_name'] = 'time in julian days'

        expected = xr.Dataset({
            'first': (['lat', 'lon', 'time'], np.zeros([45, 90, 12])),
            'second': (['lat', 'lon', 'time'], np.zeros([45, 90, 12])),
            'lat':
            np.linspace(-88, 88, 45),
            'lon':
            np.linspace(-178, 178, 90),
            'time': [datetime(2000, x, 1) for x in range(1, 13)]
        })
        expected.time.attrs['long_name'] = 'time'

        actual = harmonize(ds)

        assertDatasetEqual(actual, expected)
def planet_elements_and_sv(planet_id, year, month, day, hour, minute, second):
    global mu
    mu = 1.327124e11

    #calculating julian time
    j0 = sum(jdcal.gcal2jd(year, month, day))
    ut = (hour+minute/60+second/3600)/24
    jd = j0+ut

    #determining state vectors
    eph = Ephemeris(de421)
    planet = month_planet_names.planet_name(planet_id)
    if planet=="earth":
        barycenter = eph.position_and_velocity('earthmoon', jd)
        moonvector = eph.position_and_velocity('moon', jd)
        r = barycenter[0] - eph.earth_share*moonvector[0]
        v = barycenter[1] - eph.earth_share*moonvector[1]

    elif planet=="moon":
        barycenter = eph.position_and_velocity('earthmoon', jd)
        moonvector = eph.position_and_velocity('moon', jd)
        r = barycenter[0] - eph.moon_share*moonvector[0]
        v = barycenter[1] - eph.moon_share*moonvector[1]
        mu = 3.986e14

    else:
        r, v = eph.position_and_velocity(planet, jd)

    r = r.flatten()
    v = v.flatten()/(24*3600)

    coe = coe_from_sv.coe_from_sv(r, v, mu)

    return [coe, r, v, jd]
Esempio n. 26
0
def vexdate_to_MJD_hr(vexdate):
    time = re.findall("[-+]?\d+[\.]?\d*", vexdate)
    year = int(time[0])
    date = int(time[1])
    mjd = jdcal.gcal2jd(year, 1, 1)[1] + date - 1
    hour = int(time[2]) + float(time[3]) / 60. + float(time[4]) / 60. / 60.
    return mjd, hour
def ngdc_viirs_date_text_convert(date_text):
    yyyy = date_text[1:5]
    mm = date_text[5:7]
    dd = date_text[7:9]
    date_jul = np.sum(jdcal.gcal2jd(yyyy, mm, dd)) - 0.5

    return date_jul
Esempio n. 28
0
def to_json(line, idx):
    values = line.split(',')
    # Designation
    name = values[2]
    color = [0.4, 1.0, 0.4, 0.5]
    # Epoch in yyyymmdd, convert
    ymd = values[8]
    dt = datetime.datetime.strptime(ymd, FMT)
    epoch = sum(jdcal.gcal2jd(dt.year, dt.month, dt.day))
    # Mean anomaly [deg]
    meananomaly = float(values[9])
    # Semimajor axis [Km]
    a_au = float(values[14])
    semimajoraxis = a_au * AU_TO_KM
    # Eccentricity
    eccentricity = float(values[13])
    # Argument of pericenter [deg]
    argofpericenter = float(values[10])
    # Ascending node [deg]
    ascendingnode = float(values[11])
    # Period in days
    period = pow(a_au, 1.5) * Y_TO_D
    # Inclination [deg]
    inclination = float(values[12])

    bean = SSO(name, color, epoch, meananomaly, semimajoraxis, eccentricity,
               argofpericenter, ascendingnode, period, inclination)

    jsonstr = json.dumps(bean.__dict__)

    return jsonstr
def datecalc():
    dtime = [int(x) for x in time.strftime('%Y %m %d').split()]
    jd = int(gcal2jd(dtime[0], dtime[1], dtime[2])[1])
    std = 57503
    if (std >= jd) or jd > (std + 7):
        episode = "01"
    elif (std + 7 >= jd) or jd > std + 14:
        episode = "02"
    elif (std + 14 >= jd) or jd > std + 21:
        episode = "03"
    elif (std + 21 >= jd) or jd > std + 28:
        episode = "04"
    elif (std + 28 >= jd) or jd > std + 35:
        episode = "05"
    elif (std + 35 >= jd) or jd > std + 42:
        episode = "06"
    elif (std + 42 >= jd) or jd > std + 49:
        episode = "07"
    elif (std + 49 >= jd) or jd > std + 56:
        episode = "08"
    elif (std + 56 >= jd) or jd > std + 63:
        episode = "09"
    elif (std + 63 >= jd) or jd > std + 100:
        episode = "10"
    else:
        episode = "00"

    return episode
Esempio n. 30
0
def gyear2jd(year):
    y = ipart(year)
    d = fpart(year) * days_in_year(y)
    day = ipart(d)
    jd1, jd2 = gcal2jd(y, 1, day)
    jd2 += fpart(d)
    return jd1, jd2
Esempio n. 31
0
def date_2_jd(date):
    """ Compute the Julian day from the date.

  INPUT
  -----

  date: datetime
    The date.

  RETURN
  ------

  jd: float
    The Julian day

  """

    yy = int(date.strftime('%Y'))
    mm = int(date.strftime('%m'))
    dd = int(date.strftime('%d'))
    hh = int(date.strftime('%H'))
    mi = int(date.strftime('%M'))
    ss = float(date.strftime('%S.%f'))

    sec = hh * 3600. + mi * 60. + ss
    day_dec = sec / 86400.

    jd = np.sum(gcal2jd(yy, mm, dd)) + day_dec

    return jd
Esempio n. 32
0
def test_gcal2jd_with_astropy_erfa_cal2jd():
    """Compare gcal2jd with astropy._erfa.cal2jd."""
    import random
    import numpy as np
    from astropy import _erfa

    n = 1000
    mday = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

    # sla_cldj needs year > -4699 i.e., 4700 BC.
    year = [random.randint(-4699, 2200) for i in range(n)]
    month = [random.randint(1, 12) for i in range(n)]
    day = [random.randint(1, 31) for i in range(n)]
    for i in range(n):
        x = 0
        if is_leap(year[i]) and month[i] == 2:
            x = 1
        if day[i] > mday[month[i]] + x:
            day[i] = mday[month[i]]

    jd_jdcal = np.array(
        [gcal2jd(y, m, d) for y, m, d in zip(year, month, day)])
    jd_erfa = np.array(_erfa.cal2jd(year, month, day)).T

    assert np.allclose(jd_jdcal, jd_erfa)
Esempio n. 33
0
    def test_normalize_julian_day(self):
        """
        Test Julian Day -> Datetime conversion
        """
        tuples = [gcal2jd(2000, x, 1) for x in range(1, 13)]

        ds = xr.Dataset({
            'first': (['lat', 'lon', 'time'], np.zeros([45, 90, 12])),
            'second': (['lat', 'lon', 'time'], np.zeros([45, 90, 12])),
            'lat': np.linspace(-88, 88, 45),
            'lon': np.linspace(-178, 178, 90),
            'time': [x[0] + x[1] for x in tuples]})
        ds.time.attrs['long_name'] = 'time in julian days'

        expected = xr.Dataset({
            'first': (['time', 'lat', 'lon'], np.zeros([12, 45, 90])),
            'second': (['time', 'lat', 'lon'], np.zeros([12, 45, 90])),
            'lat': np.linspace(-88, 88, 45),
            'lon': np.linspace(-178, 178, 90),
            'time': [datetime(2000, x, 1) for x in range(1, 13)]})
        expected.time.attrs['long_name'] = 'time'

        actual = normalize(ds)

        assertDatasetEqual(actual, expected)
def getJulianDay(
    offset, items
):  # items are year, anything, month, day, hour, minute, second  with offset=1 for boat file
    jd = gcal2jd(asInt(items[offset + 0]), asInt(items[offset + 2]),
                 asInt(items[offset + 3]))[1] + (
                     asInt(items[offset + 4]) + asInt(items[offset + 5]) / 60 +
                     asInt(items[offset + 6]) / 3600) / 24.0
    return jd
Esempio n. 35
0
def now_in_jd():
    now_utc = datetime.datetime.utcnow()
    now_jd = jdcal.gcal2jd(now_utc.year, now_utc.month, now_utc.day) #TODO
    now_jd = now_jd[0] + now_jd[1]
    now_jd = now_jd + now_utc.hour/24 + now_utc.minute/24/60 + now_utc.second/24/60/60

    now_jd -= t_offset
    return(now_jd)
def lst(yr, mn, day, ut, lon):
    jd1 = sum(jdcal.gcal2jd(yr, mn, day))
    d_2000 = jd1 + ut/24. - 2451545.0
    LST = 100.46 + 0.985647*d_2000 + lon + 15.0*ut
    if LST < 0:
        LST = LST + 360.
    resd, LST = divmod(LST, 360.)
    return LST/15.
Esempio n. 37
0
def parseDate(dateString):
    from datautil.date import DateutilDateParser
    from jdcal import gcal2jd
    parser = DateutilDateParser()
    flexdate = parser.parse(dateString)
    julian = gcal2jd(int(flexdate.year), int(flexdate.month if flexdate.month is not '' else '1'), \
        int(flexdate.day if flexdate.day is not '' else '1'))
    return julian[0] + julian[1]
Esempio n. 38
0
def parseDate(dateString):
    from datautil.date import DateutilDateParser
    from jdcal import gcal2jd
    parser = DateutilDateParser()
    flexdate = parser.parse(dateString)
    julian = gcal2jd(int(flexdate.year), int(flexdate.month if flexdate.month is not '' else '1'), \
        int(flexdate.day if flexdate.day is not '' else '1'))
    return julian[0] + julian[1]
Esempio n. 39
0
def MJD(x):
    s=x.split('T')
    o=s[0].split('-')
    e=s[1].split(':')

    year=jdcal.gcal2jd(int(float(o[0])),int(float(o[1])),int(float(o[2])))[1]
    year+=float(e[0])/24.+float(e[1])/24./60.+float(e[2])/24./3600.

    return year
Esempio n. 40
0
    def dayofyear(self):
        """
        Return the day of the year for all the TOAs of this pulsar
        """
        gyear, gmonth, gday, gfd = mjd2gcal(self.stoas)

        mjdy = np.array([jdcal.gcal2jd(gyear[ii], 1, 0)[1] for ii in range(len(gyear))])

        return self.stoas - mjdy
Esempio n. 41
0
def get_mjd_from_timestamp(timestamp):
    
    year, month, day = int(timestamp[0:4]), int(timestamp[4:6]), int(timestamp[6:8])
    hour, minute, second = int(timestamp[9:11]), int(timestamp[11:13]), int(timestamp[13:15])

    off, mjd1 = jdcal.gcal2jd(year, month, day)
    mjd2 = hour/24. + minute/1440. + second/86400.

    return mjd1 + mjd2
Esempio n. 42
0
def getjuliandate(inputdate):
	"""Converting a date object to the julian date format
	Args: 
		inputdate (datetime) - The date to covert

	Returns:
		(int) - The formattet julian date
	"""
	jdate = jdcal.gcal2jd(inputdate.year, inputdate.day, inputdate.month)
	return int(jdate[0] + jdate[1])
def calculate_julian_date(year, julian_doy):
    """"""

    first_of_the_year = int(sum(gcal2jd(year, 1, 1)))
    # print "first day jd", first_of_the_year

    julian_date = first_of_the_year + int(julian_doy)
    # print "full julian date", julian_date

    return julian_date
Esempio n. 44
0
def fecha2jd_all(fecha_sismo):
    Ano=fecha_sismo[0]
    Mes=fecha_sismo[1]
    Dia=fecha_sismo[2]
    Hora=fecha_sismo[3]
    Minuto=fecha_sismo[4]
    Segundo=fecha_sismo[5]
    siglo,desfase=jdcal.gcal2jd(int(Ano),int(Mes),int(Dia))
    jd=siglo+desfase+(int(Hora)+int(Minuto)/60.+int(Segundo)/3600.)/24
    return jd
	def _toJulianDateDatetime(self, dateTime, printing=False):		## takes as input a datetime.datetime object  or datetime.date object
		if self.canPerformDateTimeConversionToJulian():
			from jdcal import gcal2jd
			jd_tuple = gcal2jd(dateTime.year, dateTime.month, dateTime.day)
			julian_day = jd_tuple[0] + jd_tuple[1] + 0.5
			return int(julian_day)
		else:
			if printing:
				print("\n\tERROR in GoogleSearchQuery._toJulianDateDatetime(): the julian conversion library jdcal has not been installed.")
			return -1
Esempio n. 46
0
    def time(self, jd=False, net=False):
        # returns current in-game time representation as a string
        delim = " "
        if net is True:
            delim = '-'

        if jd is True:
            return sum(gcal2jd(self.date.year, self.date.month, self.date.day))

        return self.date.strftime('%d')+delim+self.date.strftime('%b')+delim+self.date.strftime('%Y')
Esempio n. 47
0
def process_events(event_block, sat_num):
    # takes in list of raw data as strings, processes them, and returns a list of strings to be printed in the output file
    event = Event(event_block)
    print_out = []
    
    # get the julian day
    day = int(event.utc_day[0:2])
    month = int(event.utc_day[2:4])
    year = int('20' + event.utc_day[4:])
    julian_start = str(sum(gcal2jd(year, month, day)) + event.t_abs/86400)
    [jul_day, jul_frac] = julian_start.split('.')    
    
    jul_frac = '.' + jul_frac
    edge_counts = [['re1_count', '1'], 'fe1_count', ['re2_count', '2'], 'fe2_count', ['re3_count', '3'], 'fe3_count', ['re4_count', '4'], 'fe4_count']
    # somewhat cluttered construction, but I have it here to make sure the printed
    # channel number is correctly matched
    
    switch = jul_day # added to stop the start day from changing
    
    # generate text for all happenings in the event
    for i in range(0, 8, 2):
        out_line = ''
        jul_day = int(switch)
        for j in range(len(getattr(event, edge_counts[i][0]))):
            out_line = sat_num + '.{}  '.format(edge_counts[i][1])
            
            t_rise_list = getattr(event, edge_counts[i][0])
            t_rise = t_rise_list[j]/1e9
            t_fall_list = getattr(event, edge_counts[i+1])
            t_fall = t_fall_list[j]/1e9
            
            t_over_thresh = (t_fall - t_rise)*1e9  # Time over threshold
            
            t_rise = t_rise/86400 + float(jul_frac)  
            t_fall = t_fall/86400 + float(jul_frac)
       # Due to a bug in newer versions of the DAQ software, times are off
       # by exactly one second. I will likely implement this whenever
       # I add in the wire delays.
       #   t_rise -= 1/86400
       #   t_fall -= 1/86400
            
            # If the fractional day exceeds 1, we need to adjust accordingly
            if t_rise > 1 or t_fall > 1 or (t_rise and t_fall) > 1:
                jul_day += 1
            if t_rise > 1:
                t_rise -= 1
            if t_fall > 1:
                t_fall -= 1

            out_line += str(jul_day) + '  '
            out_line += '{0:.16f}  '.format(t_rise)
            out_line += '{0:.16f} '.format(t_fall)
            out_line += ' {0:.2f}\n'.format(t_over_thresh)
        print_out.append(out_line)
    return print_out
Esempio n. 48
0
    def get_start_time(self):
        self.start_time = self.hdu[5].data.TIME[0]
        self.start_date = self.hdu[5].data.DATE[0]
        self.obs_date_str = self.hdu[5].header['DATE-OBS']
        self.obs_RA = self.hdu[5].header['CRVAL5']
        self.obs_DEC = self.hdu[5].header['CRVAL6']

        yr,mn,dy = self.obs_date_str.split('-')
        self.obs_JD = sum(jdcal.gcal2jd(yr,mn,dy))

        self.source = self.hdu[2].data.SOURCE[0].strip()
def tojulian(date_string,format):

	'''
	converts a string into a julian date number 
	
	'''

	if format == "AAAA*MM*DD":
		year = date_string[0:4]
		month = date_string[5:7]
		day = date_string[8:10]
		juliandate = jd.gcal2jd(year,month,day)[1]
	
	elif format == "DD*MM*AAAA":
		year = date_string[6:10]
		month = date_string[3:5]
		day = date_string[0:2]
		juliandate = jd.gcal2jd(year,month,day)[1]

	return juliandate
Esempio n. 50
0
def to_excel(dt, offset=CALENDAR_WINDOWS_1900):
    if isinstance(dt, datetime.time):
        return time_to_days(dt)
    if isinstance(dt, datetime.timedelta):
        return timedelta_to_days(dt)
    if isnan(dt.year): # Pandas supports Not a Date
        return
    jul = sum(gcal2jd(dt.year, dt.month, dt.day)) - offset
    if jul <= 60 and offset == CALENDAR_WINDOWS_1900:
        jul -= 1
    if hasattr(dt, 'time'):
        jul += time_to_days(dt)
    return jul
 def _interpolate_single(self, where, when):
     TIDE       = array(1.0, float)
     ISDATA     = array(False, bool)
     ttup       = when.timetuple()[:3]
     jday       = jdcal.gcal2jd(*ttup)[1]
     hfrac      = (when.hour + (when.minute + (when.second + when.microsecond*1e-6)/60.0)/60.0)/24.0
     lookuptime = jday+hfrac
     dummy = dtu10API.perth3( where[1], where[0], lookuptime, TIDE, ISDATA )
     print 
     if bool(ISDATA):
         return float(TIDE)/100.0 # convert to meters
     else:
         raise GridRangeViolation # perth3 does not resolve further
Esempio n. 52
0
    def ParseJulian(self,dates):

        jd = np.zeros(len(dates))
        for i,dt in enumerate(dates):
            yr,mn,other= dt.split('-')
            if float(yr) < 2000:
                yr = str(int(yr) + 2000)

            dy, other = other.split('T')
            hr,mt,sec = other.split(':')
            sec = sec[0:2]
            jd[i] = sum(jdcal.gcal2jd(yr,mn,dy)) + (float(hr)+float(mt)/60. + float(sec)/3600.)/24. 

        return jd
Esempio n. 53
0
def JD_from_dt_object(datetime_object):
    # returns total julian day given a datetime object
    # compute main part
    year = datetime_object.year
    month = datetime_object.month
    day = datetime_object.day
    jul_day = dec.Decimal(sum(jdcal.gcal2jd(year, month, day)))

    # get partial day
    partial = dec.Decimal(3600*datetime_object.hour + 60*datetime_object.minute + datetime_object.second)
    partial += dec.Decimal(datetime_object.microsecond/1000000)
    partial /= dec.Decimal(86400)

    return float(jul_day + partial)
Esempio n. 54
0
def get_julian_day(date,time):
    # takes date and time and returns fractional julian day
    # date should be written as 'MM/DD/YYYY' or 'MM/DD/YY' and time as 'HH:MM:SS'
    # can also accept seconds with trailing decimals
    month = int(date[0:2])
    day = int(date[3:5])
    year = int(date[6:])
    if len(date[6:]) == 2:
        year += 2000
    jul_day = sum(jdcal.gcal2jd(year,month,day))

    # use 86400 sec/day to calculate partial day
    seconds = float(time[0:2])*3600 + float(time[3:5])*60 + float(time[6:])
    partial = seconds/86400.0

    return jul_day + partial
def format_date(date, year):
    """"""

    year_jd = int(sum(gcal2jd(year, 1, 1)))
    # print "year 2000", year_2000

    date = date - year_jd
    d = jd2gcal(year_jd, date)
    print "datedate", d

    # test
    for i in (1, 10, 100):
        print "{num:02d}".format(num=i)

    date_string = "{}_{a:02d}_{b:02d}".format(d[0], a=d[1], b=d[2])

    return date_string
Esempio n. 56
0
def convert_to_JulianDate(row):
    
    """Creates Julian Dates
    
    Takes each row of the Trapping_Table dataframe and applies the 
    Julian Date Converter to the Gregorian Date
    
    Args:
        row: a row from a pandas dataframe containing a separate columns for
            year, month, day
    
    Returns:
        a single numeric value representing the Julian Date of the year, month,
        day given to the function
        """
    
    return sum(jdcal.gcal2jd(int(row['yr']), int(row['mo']), 
                             int(row['dy']))) 
Esempio n. 57
0
def process_events(event_block, sat_num):
    # takes in list of raw data string, processes them, and returns a list of strings to be printed in the output file
    event = Event(event_block)
    print_out = []
    day = int(event.utc_day[0:2])
    month = int(event.utc_day[2:4])
    year = int('20' + event.utc_day[4:])
    julian_start = str(sum(gcal2jd(year, month, day)) + event.t_abs/86400)
    [jul_day, jul_frac] = julian_start.split('.')
    jul_frac = '.' + jul_frac
    edge_counts = [['re1_count', '1'], 'fe1_count', ['re2_count', '2'], 'fe2_count', ['re3_count', '3'], 'fe3_count', ['re4_count', '4'], 'fe4_count']
    const = jul_day
    # generate text for each part of the event
    for i in range(0, 8, 2):
        out_line = ''
        jul_day = int(const)
        for j in range(len(getattr(event, edge_counts[i][0]))):
            out_line = sat_num + '.{}  '.format(edge_counts[i][1])
            t_rise = getattr(event, edge_counts[i][0])
            t_rise = t_rise[j]/1e9
            t_fall = getattr(event, edge_counts[i+1])
            t_fall = t_fall[j]/1e9
            t_over_thresh = (t_fall - t_rise)*1e9
            t_rise = t_rise/86400 + float(jul_frac)  # - 1/86400
            t_fall = t_fall/86400 + float(jul_frac)  # - 1/86400
            if t_rise > 1 or t_fall > 1 or (t_rise and t_fall) > 1:
                jul_day += 1
            if t_rise > 1:
                t_rise -= 1
            if t_fall > 1:
                t_fall -= 1

            out_line += str(jul_day) + '  '
            out_line += '{0:.16f}  '.format(t_rise)
            out_line += '{0:.16f} '.format(t_fall)
            out_line += ' {0:.2f}\n'.format(t_over_thresh)
        print_out.append(out_line)
    return print_out