Exemple #1
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
Exemple #2
0
def test_jd2gcal_fractional_day_part():
    r = jd2gcal(2400000.5, 51544.0 + 0.5)
    assert round(r[-1], 12) == 0.5

    r = jd2gcal(2400000.5, 51544.0 + 0.245)
    assert round(r[-1], 10) == round(0.245, 10)

    r = jd2gcal(2400000.5, 51544.0 + 0.75)
    assert round(r[-1], 12) == 0.75
Exemple #3
0
def test_jd2gcal_fractional_day_part():
    r = jd2gcal(2400000.5, 51544.0 + 0.5)
    assert round(r[-1], 12) == 0.5

    r = jd2gcal(2400000.5, 51544.0 + 0.245)
    assert round(r[-1], 10) == round(0.245, 10)

    r = jd2gcal(2400000.5, 51544.0 + 0.75)
    assert round(r[-1], 12) == 0.75
Exemple #4
0
def gregorian_date(julianDay, mjd=False):
    """
    For a given Julian Day convert to Gregorian date (YYYY, MM, DD, hh, mm,
    ss). Optionally convert from modified Julian Day with mjd=True).

    This function is adapted to Python from the MATLAB julian2greg.m function
    (http://www.mathworks.co.uk/matlabcentral/fileexchange/11410).

    Parameters
    ----------
    julianDay : ndarray
        Array of Julian Days
    mjd : boolean, optional
        Set to True if the input is Modified Julian Days.

    Returns
    -------
    greg : ndarray
        Array of [YYYY, MM, DD, hh, mm, ss].

    Example
    -------
    >>> greg = gregorian_date(np.array([53583.00390625, 55895.9765625]), mjd=True)
    >>> greg.astype(int)
    array([[2005,    8,    1,    0,    5,   37],
           [2011,   11,   30,   23,   26,   15])

    """

    if not mjd:
        # It's easier to use jdcal in Modified Julian Day
        julianDay -= 2400000.5

    try:
        nt = len(julianDay)
    except TypeError:
        nt = 1

    greg = np.empty((nt, 6))
    if nt == 1:
        ymdf = jdcal.jd2gcal(2400000.5, julianDay)
        fractionalday = ymdf[-1]
        hours = int(fractionalday * 24)
        minutes = int(((fractionalday * 24) - hours) * 60)
        seconds = ((((fractionalday * 24) - hours) * 60) - minutes) * 60
        greg = np.asarray((ymdf[0], ymdf[1], ymdf[2], hours, minutes, seconds))
    else:
        for ii, jj in enumerate(julianDay):
            ymdf = jdcal.jd2gcal(2400000.5, jj)
            greg[ii, :3] = ymdf[:3]
            fractionalday = ymdf[-1]
            hours = int(fractionalday * 24)
            minutes = int(((fractionalday * 24) - hours) * 60)
            seconds = ((((fractionalday * 24) - hours) * 60) - minutes) * 60
            greg[ii, 3:] = [hours, minutes, seconds]

    return greg
Exemple #5
0
def gregorian_date(julianDay, mjd=False):
    """
    For a given Julian Day convert to Gregorian date (YYYY, MM, DD, hh, mm,
    ss). Optionally convert from modified Julian Day with mjd=True).

    This function is adapted to Python from the MATLAB julian2greg.m function
    (http://www.mathworks.co.uk/matlabcentral/fileexchange/11410).

    Parameters
    ----------
    julianDay : ndarray
        Array of Julian Days
    mjd : boolean, optional
        Set to True if the input is Modified Julian Days.

    Returns
    -------
    greg : ndarray
        Array of [YYYY, MM, DD, hh, mm, ss].

    Example
    -------
    >>> greg = gregorianDate(np.array([53583.00390625, 55895.9765625]), mjd=True)
    >>> greg.astype(int)
    array([[2005,    8,    1,    0,    5,   37],
           [2011,   11,   30,   23,   26,   15])

    """

    if not mjd:
        # It's easier to use jdcal in Modified Julian Day
        julianDay = julianDay + 2400000.5

    try:
        nt = len(julianDay)
    except TypeError:
        nt = 1

    greg = np.empty((nt, 6))
    if nt == 1:
        ymdf = jdcal.jd2gcal(2400000.5, julianDay)
        fractionalday = ymdf[-1]
        hours = int(fractionalday * 24)
        minutes = int(((fractionalday * 24) - hours) * 60)
        seconds = ((((fractionalday * 24) - hours) * 60) - minutes) * 60
        greg = np.asarray((ymdf[0], ymdf[1], ymdf[2], hours, minutes, seconds))
    else:
        for ii, jj in enumerate(julianDay):
            ymdf = jdcal.jd2gcal(2400000.5, jj)
            greg[ii, :3] = ymdf[:3]
            fractionalday = ymdf[-1]
            hours = int(fractionalday * 24)
            minutes = int(((fractionalday * 24) - hours) * 60)
            seconds = ((((fractionalday * 24) - hours) * 60) - minutes) * 60
            greg[ii, 3:] = [hours, minutes, seconds]

    return greg
Exemple #6
0
def stv_downloader(request, primary_key):
    """
    Download stvs as geojson.
    """

    stv = SpacetimeVolume.objects.filter(pk=primary_key)
    if len(stv) == 0:
        return HttpResponse(status=404)

    geojson = serialize(
        "geojson",
        stv,
        geometry_field="territory",
        fields=(
            "start_date",
            "end_date",
            "entity",
            "references",
            "visual_center",
            "related_events",
        ),
    )

    geojson = json.loads(geojson)

    for features in geojson["features"]:
        features["properties"]["visual_center"] = {
            "type": "Feature",
            "properties": None,
            "geometry": json.loads(stv[0].visual_center.json),
        }
        features["properties"]["entity"] = {
            "label": stv[0].entity.label,
            "pk": stv[0].entity.pk,
        }

    start_date = jd2gcal(stv[0].start_date, 0)
    start_string = "{}-{}-{}".format(start_date[0], start_date[1],
                                     start_date[2])

    end_date = jd2gcal(stv[0].end_date, 0)
    end_string = "{}-{}-{}".format(end_date[0], end_date[1], end_date[2])
    response = JsonResponse(geojson)

    response[
        "Content-Disposition"] = "attachment;filename={}_{}_{}.json;".format(
            stv[0].entity.label, start_string, end_string)

    return response
Exemple #7
0
def get_date_time(julian_day):
    # take in floating Julian day and return a date and time as a single string
    diff = julian_day - 240000.5
    date = jdcal.jd2gcal(240000.5, diff)
    year = str(date[0])
    month = str(date[1])
    day = str(date[2])
    if len(month) == 1:
        month = '0' + month
    if len(day) == 1:
        day = '0' + day

    secs = int(round(date[3] * 86400))
    hr = secs // 3600
    minute = (secs - hr * 3600) // 60
    sec = secs - 3600 * hr - 60 * minute
    hr = str(hr)
    minute = str(minute)
    sec = str(sec)
    if len(sec) == 1:
        sec = '0' + sec
    if len(minute) == 1:
        minute = '0' + minute
    if len(hr) == 1:
        hr = '0' + hr

    fulldate = month + '/' + day + '/' + year
    time = hr + ':' + minute + ':' + sec

    return fulldate + ' ' + time
def from_excel(value, offset=CALENDAR_WINDOWS_1900):
    parts = list(jd2gcal(MJD_0, value + offset - MJD_0))
    fractions = value - int(value)
    diff = datetime.timedelta(days=fractions)
    if 1 > value > 0 or 0 > value > -1:
        return days_to_time(diff)
    return datetime.datetime(*parts[:3]) + diff
Exemple #9
0
def jd_2_date(julian_day):
    """ Compute the date from the Julian day.

    INPUT
    -----

    julian_day: float
      The date in Julian day.

    RETURN
    ------

    t: datetime
      The date.

    """

    date = jd2gcal(2400000.5, julian_day - 2400000.5)
    sec_day = date[3] * 24 * 3600
    year = date[0]
    month = date[1]
    day = date[2]
    hour = int(divmod(sec_day, 3600)[0])
    minu = int(divmod(sec_day - hour * 3600, 60)[0])
    seco = int(divmod(sec_day - hour * 3600, 60)[1])
    frac = int((divmod(sec_day - hour * 3600, 60)[1] - seco) * 1E6)
    t = datetime(year, month, day, hour, minu, seco, frac)

    return t
Exemple #10
0
def readtime(filename):
    metafile = open(filename + ".meta", "r")
    lines = metafile.readlines()

    try:
        if lines[0][0] == 'N':  # Using nominal date
            time = float(lines[0][15:21])
            interval = 'NaN'
        else:  # Using Central Julian date
            jdate = float(lines[0][36:47])

            # Get date
            year, month, day, fracday = jdcal.jd2gcal(jdate, 0)

            time = datelib.date_to_fracyear(year, month, day + fracday)

            # Get time interval for velocity (time of second image - time of first image)
            month1 = datelib.month(lines[1][32:35])
            day1 = float(lines[1][36:38])
            year1 = float(lines[1][39:43])

            month2 = datelib.month(lines[2][33:36])
            day2 = float(lines[2][37:39])
            year2 = float(lines[2][40:44])

            interval = datelib.date_to_fracyear(
                year2, month2, day2) - datelib.date_to_fracyear(
                    year1, month1, day1)
    except:
        time = float('nan')
        interval = float('nan')

    return time, interval
Exemple #11
0
def from_excel(value, offset=CALENDAR_WINDOWS_1900):
    parts = list(jd2gcal(MJD_0, value + offset - MJD_0))
    fractions = value - int(value)
    diff = datetime.timedelta(days=fractions)
    if 1 > value > 0 or 0 > value > -1:
        return days_to_time(diff)
    return datetime.datetime(*parts[:3]) + diff
Exemple #12
0
def get_date_time(julian_day):
    # take in floating Julian day and return a date and time as a single string
    diff = julian_day - 240000.5
    date = jdcal.jd2gcal(240000.5, diff)
    year = str(date[0])
    month = str(date[1])
    day = str(date[2])
    if len(month) == 1:
        month = '0' + month
    if len(day) == 1:
        day = '0' + day

    secs = int(round(date[3]*86400))
    hr = secs//3600
    minute = (secs - hr * 3600) // 60
    sec = secs - 3600*hr - 60*minute
    hr = str(hr)
    minute = str(minute)
    sec = str(sec)
    if len(sec) == 1:
        sec = '0' + sec
    if len(minute) == 1:
        minute = '0' + minute
    if len(hr) == 1:
        hr = '0' + hr

    fulldate = month + '/' + day + '/' + year
    time = hr + ':' + minute + ':' + sec

    return fulldate + ' ' + time
Exemple #13
0
def republican_to_gregorian(y, m, d):
    """
    Take a year (y>=1), a month (1<=m<=13), and a day (1<=d<=30) that represent
    a day from the French Republican calendar and return a (year, month, day)
    tuple that represent the same date in the Gregorian calendar.
    """
    y, m, d, _ = jdcal.jd2gcal(0, _republican_ymd_to_julian_day(y, m, d))
    return (y, m, d)
def getDateFromJulian(jDay):
    dt = jd2gcal(2400000.5, jDay)
    dayDec = dt[3] - int(dt[3])
    hr = int(dayDec * 24)
    minDec = dayDec - hr / 24
    minute = int(minDec * 60 * 24)
    sec = int((dayDec * 24 - hr - minute / 60) * 3600)
    return (dt[0], dt[1], dt[2], hr, minute, sec)
def from_excel(value, offset=CALENDAR_WINDOWS_1900):
    if value is None:
        return
    parts = list(jd2gcal(MJD_0, value + offset - MJD_0))
    _, fraction = divmod(value, 1)
    diff = datetime.timedelta(days=fraction)
    if 0 < abs(value) < 1:
        return days_to_time(diff)
    return datetime.datetime(*parts[:3]) + diff
Exemple #16
0
 def get_end_year(self, obj):  # pylint: disable=R0201
     """
     Retrieves year of last narration in set
     """
     if obj.narration_set.last() is not None:
         return jd2gcal(
             obj.narration_set.order_by("map_datetime").last().map_datetime,
             0)[0]
     return None
def jul_greg(jd):
    d = jdcal.jd2gcal(0, jd)
    g = datetime.timedelta(days=d[3])
    hrs = g.seconds / 3600
    min = (g.seconds % 3600) / 60
    sec = g.seconds % 60
    decsec = 0 # uncomment if need greater precision: g.microseconds/1E6
    
    date = str(d[0]).zfill(4) + str(d[1]).zfill(2) + str(d[2]).zfill(2) + str(hrs).zfill(2) + str(min).zfill(2) + str(sec + decsec)
    return date
Exemple #18
0
def jd_to_cald(julian_day):
    """
    Converts julian day into calendar day in string format.
    Args:
        julian_day  : Julian day value to be converted to calendar day
    Returns:
        cal_date    : Calendar date corresponding to input julian day
    """
    time_tuple = jd2gcal(epoch, julian_day - epoch)
    cal_date = date(*time_tuple[0:3]).strftime("%Y-%m-%d")

    return cal_date
def mjd_to_time(mjd):

    year, month, day, time = jdcal.jd2gcal(2400000.5, mjd)

    hour = int(math.floor(time * 24.))
    x = time * 24 - hour

    minute = int(math.floor(x * 60))
    x = x * 60 - minute

    second = x * 60

    return year, month, day, hour, minute, second
Exemple #20
0
def mjd2000_to_date(mjd):
    """
    Convert a MJD2000 date to a datetime object
    
    :param mjd float: the MJD2000 date to convert
    :return: a datetime object
    :rtype: datetime.datetime
    """
    dat = jdcal.jd2gcal(jdcal.MJD_0 + jdcal.MJD_JD2000, mjd)
    tm = __mjd2000_fraction_to_timedelta(dat[3])
        
    return datetime.datetime(dat[0], dat[1], dat[2],
                             *__split_timedelta(tm))
def mjd_to_time(mjd):

    year, month, day, time = jdcal.jd2gcal(2400000.5, mjd)

    hour = int(math.floor(time * 24.))
    x = time*24 - hour

    minute = int(math.floor(x * 60))
    x = x * 60 - minute

    second = x * 60

    return year, month, day, hour, minute, second
def dday2timestr(yr, dday):
    ''' 
    Convert dday to str of timestamp
    yr     data.yearbase
    dday   one or more items in a list from data.dday
    '''
    yr1day = jdcal.gcal2jd(yr, 1, 1)  # get numbers for start of the year
    gcal = [jdcal.jd2gcal(yr1day[0], yr1day[1] + x) for x in np.nditer(dday)]
    td = [
        datetime.datetime(year=xx[0], month=xx[1], day=xx[2]) +
        datetime.timedelta(days=xx[-1]) for xx in gcal
    ]
    return [x.strftime('%H:%M:%S') for x in td]
def getDate(jDay):
    jd = (
        2400000.5, jDay
    )  #  Note:  This is a tuple, not a list (i.e. ordered and unchangeable)
    dt = jd2gcal(*jd)
    yr = dt[0]
    mo = dt[1]
    day = int(dt[2])
    dayFrac = dt[3]
    hr = int(dayFrac * 24)
    mins = int((dayFrac * 24 - hr) * 60)
    sec = int((dayFrac * 24 - hr - mins / 60) * 3600)
    return (yr, mo, day, hr, mins, sec)
Exemple #24
0
def read_ncjuld(d):
    """Convert the netcdf Julian date into a proper format"""
    t_ref = parser.parse(np.unique(d['JULD_REFERENCE'])[0])
    t = jdcal.jd2gcal(sum(jdcal.gcal2jd(t_ref.year, t_ref.month, t_ref.day)),np.unique(d['JULD']))
    return t

# def open_erddap(dsub, i_obs):
#     # WMO of the platform:
#     wmo = np.asmatrix(dsub['STATION_IDENTIFIER'].isel(N_OBS=i_obs).values)[0, 0].strip()
#     # Datetime of the measurement:
#     jd = np.asmatrix(dsub['JULD'].isel(N_OBS=i_obs).values)[0, 0]
#     ts = pd.Timestamp('1950-01-01') + pd.Timedelta(days=jd)
#     # ts.to_datetime().strftime("%Y%m%d%H%M%S")
#     # http://www.ifremer.fr/erddap/tabledap/ArgoFloats.htmlTable?temp%2Cpres%2Cpsal%2Ctime&platform_number=%226901047%22&time=2014-06-07T05%3A53%3A50Z
Exemple #25
0
def convert_mjd_to_greg(toas):
    """
    Converts MJD array to year array

    :param toas: Array of TOAs in days

    :return: Array of TOAs in years
    """

    dates = np.zeros(len(toas))
    for ct, toa in enumerate(toas):
        x = jdcal.jd2gcal(2400000.5, toa)
        dates[ct] = x[0] + x[1] / 12 + x[2] / 365.25 + x[3] / 365.25

    return dates
Exemple #26
0
def convert_mjd_to_greg(toas):
    """
    Converts MJD array to year array

    :param toas: Array of TOAs in days

    :return: Array of TOAs in years
    """

    dates = np.zeros(len(toas))
    for ct, toa in enumerate(toas):
        x = jdcal.jd2gcal(2400000.5, toa)
        dates[ct] = x[0] + x[1] / 12 + x[2] / 365.25 + x[3] / 365.25

    return dates
Exemple #27
0
def from_excel(value, offset=CALENDAR_WINDOWS_1900):
    if value is None:
        return
    if 1 < value < 60 and offset == CALENDAR_WINDOWS_1900:
        value += 1
    parts = list(jd2gcal(MJD_0, value + offset - MJD_0))
    _, fraction = divmod(value, 1)
    jumped = (parts[-1] == 0 and fraction > 0)
    diff = datetime.timedelta(days=fraction)

    if 0 < abs(value) < 1:
        return days_to_time(diff)
    if not jumped:
        return datetime.datetime(*parts[:3]) + diff
    else:
        return datetime.datetime(*parts[:3] + [0])
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
Exemple #29
0
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
Exemple #30
0
def _normalize_jd2datetime(ds: xr.Dataset) -> xr.Dataset:
    """
    Convert the time dimension of the given dataset from Julian date to
    datetime.

    :param ds: Dataset on which to run conversion
    """
    ds = ds.copy()
    # Decode JD time
    tuples = [jd2gcal(x, 0) for x in ds.time.values]
    # Replace JD time with datetime
    ds.time.values = [datetime(x[0], x[1], x[2]) for x in tuples]
    # Adjust attributes
    ds.time.attrs['long_name'] = 'time'
    ds.time.attrs['calendar'] = 'standard'

    return ds
Exemple #31
0
def _normalize_jd2datetime(ds: xr.Dataset) -> xr.Dataset:
    """
    Convert the time dimension of the given dataset from Julian date to
    datetime.

    :param ds: Dataset on which to run conversion
    """

    try:
        time = ds.time
    except AttributeError:
        return ds

    try:
        units = time.units
    except AttributeError:
        units = None

    try:
        long_name = time.long_name
    except AttributeError:
        long_name = None

    if units:
        units = units.lower().strip()

    if long_name:
        units = long_name.lower().strip()

    units = units or long_name

    if not units or units != 'time in julian days':
        return ds

    ds = ds.copy()
    # Decode JD time
    # noinspection PyTypeChecker
    tuples = [jd2gcal(x, 0) for x in ds.time.values]
    # Replace JD time with datetime
    ds.time.values = [datetime(x[0], x[1], x[2]) for x in tuples]
    # Adjust attributes
    ds.time.attrs['long_name'] = 'time'
    ds.time.attrs['calendar'] = 'standard'

    return ds
Exemple #32
0
def _normalize_jd2datetime(ds: xr.Dataset) -> xr.Dataset:
    """
    Convert the time dimension of the given dataset from Julian date to
    datetime.

    :param ds: Dataset on which to run conversion
    """

    try:
        time = ds.time
    except AttributeError:
        return ds

    try:
        units = time.units
    except AttributeError:
        units = None

    try:
        long_name = time.long_name
    except AttributeError:
        long_name = None

    if units:
        units = units.lower().strip()

    if long_name:
        units = long_name.lower().strip()

    units = units or long_name

    if not units or units != 'time in julian days':
        return ds

    ds = ds.copy()
    # Decode JD time
    # noinspection PyTypeChecker
    tuples = [jd2gcal(x, 0) for x in ds.time.values]
    # Replace JD time with datetime
    ds.time.values = [datetime(x[0], x[1], x[2]) for x in tuples]
    # Adjust attributes
    ds.time.attrs['long_name'] = 'time'
    ds.time.attrs['calendar'] = 'standard'

    return ds
Exemple #33
0
def mjd2gcal(mjds):
    """
    Calculate the Gregorian dates from a numpy-array of MJDs

    @param mjds:    Numpy array of MJDs
    """
    nmjds = len(mjds)
    gyear = np.zeros(nmjds)
    gmonth = np.zeros(nmjds)
    gday = np.zeros(nmjds)
    gfd = np.zeros(nmjds)

    # TODO: get rid of ugly for loop. Use some zip or whatever
    for ii in range(nmjds):
        gyear[ii], gmonth[ii], gday[ii], gfd[ii] = \
                jdcal.jd2gcal(jdcal.MJD_0, mjds[ii])
    
    return gyear, gmonth, gday, gfd
Exemple #34
0
def mjd2gcal(mjds):
    """
    Calculate the Gregorian dates from a numpy-array of MJDs

    @param mjds:    Numpy array of MJDs
    """
    nmjds = len(mjds)
    gyear = np.zeros(nmjds)
    gmonth = np.zeros(nmjds)
    gday = np.zeros(nmjds)
    gfd = np.zeros(nmjds)

    # TODO: get rid of ugly for loop. Use some zip or whatever
    for ii in range(nmjds):
        gyear[ii], gmonth[ii], gday[ii], gfd[ii] = \
                jdcal.jd2gcal(jdcal.MJD_0, mjds[ii])

    return gyear, gmonth, gday, gfd
def mjd2datetime(mjd):
    '''  convert modified Julian date to Python daytime
    
    Uses jdcal package for dealing with modified julian dates 
        See https://oneau.wordpress.com/2011/08/30/jdcal/
        jdcal.jd2gcal(jdcal.MJD_0,57827.5774306)
        (have to pass both base date of MJD and the MJD to this function)

    :param mjd: time as modified julian date
    :return: equivalent datetime object
    '''

    jdcal_time = jdcal.jd2gcal(jdcal.MJD_0, mjd)
    jdcal_time_hours = math.floor(jdcal_time[3] * 24)
    jdcal_time_minutes = math.floor((jdcal_time[3] * 24 - jdcal_time_hours) * 60)
    jdcal_time_seconds = math.floor(((jdcal_time[3] * 24 - jdcal_time_hours) * 60 - jdcal_time_minutes) * 60)
    datetime_time = datetime(jdcal_time[0], jdcal_time[1], jdcal_time[2], int(jdcal_time_hours),
                                            int(jdcal_time_minutes), int(jdcal_time_seconds))
    return datetime_time
def nc_time_slice(width, height, timeindex, t, base_jd, output_directory,
                  input_filename, input_file, input_variable):
    date_georg = jdcal.jd2gcal(2400000.5, t + base_jd)
    year = int(date_georg[0])
    month = int(date_georg[1])
    day = int(date_georg[2])
    date = datetime(year, month, day)
    str_date = date.strftime('%Y-%m-%d')

    output_file = path.join(
        output_directory,
        path.splitext(input_filename)[0] + '_' + str_date + '.nc')

    dataset, lon_variable, lat_variable, time_variable, depth_variable = \
        create_netcdf_dataset_dimensions(width, height, output_file, add_depth=True)

    # input_variables = ['CHL_mean']
    # output_variables = ['CHL']
    # output_variables_units = ['mg/m^3']
    # output_variables_long_name = ['Chlorophyll a concentration']
    # output_variables_standard_name = ['CHL']
    input_variables = ['chl']
    output_variables = ['chl']
    output_variables_units = ['mg/m^3']
    output_variables_long_name = ['Chlorophyll a concentration']
    output_variables_standard_name = ['chl']
    create_nc_vars(dataset, input_variables, output_variables,
                   output_variables_units, output_variables_long_name,
                   output_variables_standard_name)

    time_variable[0] = t
    lon_variable[:] = input_file.variables['longitude'][:]
    lat_variable[:] = input_file.variables['latitude'][:]

    depth_variable[0] = 0.0
    target_chl_variable = dataset.variables[output_variables[0]]
    input_data = input_variable[timeindex:timeindex + 1, :, :]
    data = input_data.reshape((1, 1, height, width))
    target_chl_variable[:, :, :, :] = data

    dataset.close()
Exemple #37
0
def getCalDay(JD):
    year, month, day, hour = jdcal.jd2gcal(JD, 0.0)
    hour = hour * 24
    minutes = modf(hour)[0] * 60.0
    seconds = modf(minutes)[0] * 60.0
    hh = int(modf(hour)[1])
    mm = int(modf(minutes)[1])
    ss = seconds
    if (hh < 10):
        hh = '0' + str(hh)
    else:
        hh = str(hh)
    if (mm < 10):
        mm = '0' + str(mm)
    else:
        mm = str(mm)
    if (ss < 10):
        ss = '0' + str(np.round(ss, 1))
    else:
        ss = str(np.round(ss, 1))
    return year, month, day, hh, mm, ss
Exemple #38
0
def gps2utc(timeOfWeek, week, cycle=0):
    """Convert GPS time to UTC, taking into account leap seconds"""
    week += cycle * GPS_CYCLE_WEEKS

    jd = gps2julian(timeOfWeek, week)

    leap_seconds_since_gps_epoch = get_gps_utc_offset(jd)
    offset = -1. * leap_seconds_since_gps_epoch / DAY_S

    year, month, day, daytime = jd2gcal(jd + offset, 0)

    day_seconds = daytime * DAY_S
    hours = int(day_seconds // 3600)
    minutes = int((day_seconds % 3600) // 60)
    frac_seconds = day_seconds % 60
    seconds = int(floor(frac_seconds))
    microseconds = int(floor(frac_seconds % 1 * 1000000))

    dt = datetime(year, month, day, hours, minutes, seconds, microseconds, pytz.utc)

    return dt
Exemple #39
0
def getCalDay(JD):
	year, month, day, hour= jdcal.jd2gcal(JD,0.0)
	hour = hour*24
	minutes = modf(hour)[0]*60.0
	seconds = modf(minutes)[0]*60.0
	hh = int(modf(hour)[1])
	mm = int(modf(minutes)[1])
	ss = seconds
	if(hh<10):
	   hh = '0'+str(hh)
	else:
	   hh = str(hh)
	if(mm<10):
	   mm = '0'+str(mm)
	else:
	   mm = str(mm)
	if(ss<10):
	   ss = '0'+str(np.round(ss,1))
	else:
	   ss = str(np.round(ss,1))
        return year,month,day,hh,mm,ss
Exemple #40
0
    def parseImageObservationTimeHeader(self, printInfo=False):
        """
        Parses HRIT Image Observation Time header (type 131)
        :param printInfo: Print info after parsing.
        """

        if self.readbytes(0) == b'\x83':
            self.imageObservationTimeHeader['valid'] = True
            self.imageObservationTimeHeader['header_type'] = 131
            self.imageObservationTimeHeader['header_len'] = int.from_bytes(
                self.readbytes(1, 2), byteorder='big')
            self.imageObservationTimeHeader['header_offset'] = self.byteOffset
            self.imageObservationTimeHeader['mjd'] = self.readbytes(
                3, self.imageObservationTimeHeader['header_len'] - 3).decode()
            self.imageObservationTimeHeader['date'] = jd2gcal(
                2400000.5, float(self.imageObservationTimeHeader['mjd']))

            self.byteOffset += self.imageObservationTimeHeader['header_len']
            if printInfo:
                self.printImageObservationTimeHeader()
        else:
            self.imageObservationTimeHeader['valid'] = False
def parse_file(input_filepath):
    output = []
    with open(input_filepath) as ifile:
        buf = []
        d = {}
        
        state = None
        for line in [ln.strip() for ln in ifile.readlines()]:
            if   line.startswith('STARTMETADATA'):
                state = 'METADATA'
                continue
            elif line.startswith('ENDMETADATA'):
                state = 'DATA'
                continue
            elif line.startswith('ENDDATA'):
                state = None
                d['data'] = buf
                output.append(d)
                d = {}
                buf = []
                continue
            
            if   state == 'METADATA':
                key, val = line.split('=', 1)
                d[key] = val
            elif state == 'DATA':
                julian_date, magnitude, error_margin, airmass = line.split('=')[1].split('|')
                jyear = int(julian_date[:2])*10e4
                jday = float(julian_date[2:])
                year, month, day, secfrac = jdcal.jd2gcal(jyear, jday)
                date = datetime.datetime(year, month, day) + datetime.timedelta(0, secfrac*86400)
                buf.append([str(date), float(magnitude),
                            str_to_float_or_None(error_margin),
                            str_to_float_or_None(airmass),
                            ])
            else:
                raise Exception('unknown state %s! typo?' % (state))
    return output
Exemple #42
0
#Le format est 
#Time Tau Delta_Tau 
#avec Time from 31/12/1991 at 0 hs
#Ils m’ont aussi donné une valeur pour la conversion : PWV = 14.425 * Tau
#mais apparemment c’est fait avec un modèle d’atmosphère pas très sur…

import numpy as np
data = np.loadtxt('chorrillo_2009.dat')
tau = data[:,1]
dtau = data[:,2]

import jdcal as jdcal
init=np.sum(jdcal.gcal2jd(1991,12,31))
jd = init+data[:,0]
jdcal.jd2gcal(0,jd[0])


jdstart = np.sum(jdcal.gcal2jd(2009,1,1))
datestart = jdcal.jd2gcal(0,jdstart)
day = jd - jdstart

clf()
plot(day/365*12,tau)
xlim(0,12)

pwv = 14.425 * tau
clf()
plot(day/365*12,pwv)
xlim(0,12)
def func_night_time_calculator(current_date_str):

	# set observation day ------------------------------------------------
	# current_utc_datetime = time.gmtime()
	# Op_time = current_utc_datetime.strftime( '%Y-%m-%d %H:%M:%S' ) 
	# current_utc_datetime = "2017-05-23 21:29:38"
	Op_time = time.strptime(current_date_str, "%Y-%m-%d") 
	gcal_y = Op_time.tm_year
	gcal_m = Op_time.tm_mon
	gcal_d = Op_time.tm_mday 
	gcal_h = Op_time.tm_hour
	gcal_min = Op_time.tm_min
	gcal_sec = Op_time.tm_sec
	MJD_newyear = gcal2jd(gcal_y,gcal_m,gcal_d)[1] 
	MJD_current = MJD_newyear
	print(MJD_current)

	# start calculate observation sequence
	time_interval = 5.0 # 2 munitues
	night_number = 288 # every 2 munitues, 720 in total.

	mjd = []
	ut_time = []
	local_time = []
	solar_alt = []
	for n in range(night_number):	
		# set mjd time ----------------------------------------
		MJD_time = MJD_current + (n*time_interval/60.0/24.0)
		nighttime_current = jd2gcal(2400000.5, MJD_time)
		# print('night time', nighttime_current)
		hh = int(nighttime_current[3] * 24.0 )
		mm = int((nighttime_current[3] * 24.0 - hh)*60.0)
		ss = (((nighttime_current[3] * 24.0 - hh)*60.0) - mm)*60.0
		hms = "%02d:%02d:%02d" % (hh,mm,ss)
		nighttime_current_cal = ('%s/%s/%s %s' % (nighttime_current[0],nighttime_current[1],nighttime_current[2],hms))
		nighttime_current_str = ('%s/%02d/%02dT%s' % (nighttime_current[0],nighttime_current[1],nighttime_current[2],hms))

		nighttime_current_cal_datetime = time.strptime(nighttime_current_cal, '%Y/%m/%d %H:%M:%S')
		astro_parameter_night = astro_parameter_calculate(nighttime_current_cal_datetime)

		local_time_str = astro_parameter_night[1]
		solar_alt_dd = astro_parameter_night[3]
		zenith_sun_min =  astro_parameter_night[9]

		if ( solar_alt_dd > zenith_sun_min ):
			mjd.append(MJD_time)
			local_time.append(local_time_str)
			solar_alt.append(solar_alt_dd)

	if (len(mjd) > 0 ):
		obs_mjd_begin_index = 0
		for mmm in range(len(mjd)-1):
			m_gap = mjd[mmm+1] - mjd[mmm] 
			m_int = (2.0/24.0)
			if m_gap > m_int:
				obs_mjd_begin_index = mjd.index(mjd[mmm+1])
		if obs_mjd_begin_index == 0:
			obs_mjd_begin_index = mjd.index(min(mjd))
		obs_mjd_end_index = mjd.index(max(mjd))

	mjd_begin = mjd[obs_mjd_begin_index]
	mjd_end = mjd[obs_mjd_end_index]
	local_time_begin = local_time[obs_mjd_begin_index]
	local_time_end = local_time[obs_mjd_end_index]
	solar_alt_begin = solar_alt[obs_mjd_begin_index]
	solar_alt_end = solar_alt[obs_mjd_end_index]

	return [str(local_time_begin),str(local_time_end),\
	str(solar_alt_begin),str(solar_alt_end)]
def convert_ansi_date(date, offset=0.5):
    logging.info('function `convert_ansi_date` complete')
    return jdcal.jd2gcal(2305812.5, date + offset) # 0.5 offset is to adjust from night to noon
Exemple #45
0
def main():
    """ main method """
    usage = "Example: python grid_obs_calculate.py -g G0008 "
    parser = OptionParser(usage, version=__version__)  #"test")# __version__ )
    parser.add_option( "-g", "--gridid", dest = "gridid" , type = "string", \
                      help = "Grid ID,  default=G0001",default="G0001")
    opts, args = parser.parse_args()

    if len(sys.argv) == 1:
        print "please use -h to see help"
        print usage
        sys.exit()

    GridID = opts.gridid

    homedir = os.getcwd()
    configuration_file = './configuration.dat'
    configuration_file_dev = open(configuration_file, 'rU')

    lines1 = configuration_file_dev.read().splitlines()
    configuration_file_dev.close()

    for line1 in lines1:
        word = line1.split()
        if word[0] == 'griduser':
            griduser = word[2]
        elif word[0] == 'gridip':
            gridip = word[2]
        elif word[0] == 'gridmypassword':
            gridmypassword = word[2]
        elif word[0] == 'gridmydb':
            gridmydb = word[2]

    conf_obs_parameters_sys = './conf_obs_parameters_sys.dat'
    conf_obs_parameters_sys_dev = open(conf_obs_parameters_sys, 'rU')

    lines2 = conf_obs_parameters_sys_dev.read().splitlines()
    conf_obs_parameters_sys_dev.close()

    for line2 in lines2:
        word = line2.split()
        if word[0] == 'observatory_lat':
            observatory_lat = word[2]
        elif word[0] == 'observatory_lon':
            observatory_lon = word[2]
        elif word[0] == 'observatory_elevation':
            observatory_elevation = float(word[2])
        elif word[0] == 'zenith_sun_min':
            zenith_sun_min = float(word[2])
        elif word[0] == 'zenith_min':
            zenith_min = float(word[2])
        elif word[0] == 'gal_min':
            gal_min = float(word[2])
        elif word[0] == 'moon_dis_min_para':
            moon_dis_min_str = word[2]
            moon_dis_para_str = moon_dis_min_str.split('|')
            moon_dis_phase_data = [[]]
            for moon_dis_para in moon_dis_para_str:
                moon_dis_para_phase_min = float(
                    moon_dis_para.split(':')[0].split('-')[0])
                moon_dis_para_phase_max = float(
                    moon_dis_para.split(':')[0].split('-')[1])
                moon_dis_para_dis = float(moon_dis_para.split(':')[1])
                moon_dis_phase_data.append([
                    moon_dis_para_phase_min, moon_dis_para_phase_max,
                    moon_dis_para_dis
                ])
            moon_dis_phase_data = filter(None, moon_dis_phase_data)

    conn_gwacoc_grid = MySQLdb.connect(host=gridip,
                                       user=griduser,
                                       passwd=gridmypassword,
                                       db=gridmydb)
    cursor_gwacoc_grid = conn_gwacoc_grid.cursor()

    grid_cmd = "select * from Grid_table where GridID = '" + GridID + "'"
    #print grid_cmd
    cursor_gwacoc_grid.execute(grid_cmd)
    extract_grid_result = cursor_gwacoc_grid.fetchall()
    print extract_grid_result
    cursor_gwacoc_grid.close()

    # define grid date frame ----------------------------------------
    gridframe = pd.DataFrame()
    if len(extract_grid_result) > 0:
        gridframe['obs_date'] = 0
        gridframe['Grid_ID'] = zip(*extract_grid_result)[1]
        gridframe['field_ID'] = zip(*extract_grid_result)[2]
        gridframe['ra_center'] = zip(*extract_grid_result)[3]
        gridframe['dec_center'] = zip(*extract_grid_result)[4]
        gridframe['radeg_h1'] = zip(*extract_grid_result)[5]
        gridframe['decdeg_h1'] = zip(*extract_grid_result)[6]
        gridframe['radeg_h2'] = zip(*extract_grid_result)[7]
        gridframe['decdeg_h2'] = zip(*extract_grid_result)[8]
        gridframe['radeg_l1'] = zip(*extract_grid_result)[9]
        gridframe['decdeg_l1'] = zip(*extract_grid_result)[10]
        gridframe['radeg_l2'] = zip(*extract_grid_result)[11]
        gridframe['decdeg_l2'] = zip(*extract_grid_result)[12]
        gridframe['mjd_begin'] = 0
        gridframe['mjd_end'] = 0
        gridframe['local_time_begin'] = 0
        gridframe['local_time_end'] = 0
        gridframe['lst_begin'] = 0
        gridframe['lst_end'] = 0
        gridframe['solar_alt_begin'] = 0
        gridframe['solar_alt_end'] = 0
        gridframe['lunar_ra_begin'] = 0
        gridframe['lunar_dec_begin'] = 0
        gridframe['lunar_phase_begin'] = 0
        gridframe['lunar_ra_end'] = 0
        gridframe['lunar_dec_end'] = 0
        gridframe['lunar_phase_end'] = 0

    #path = '/Users/han/tmp_pool/gwac_dispatch/obs_skymap/'

    # set observation day ------------------------------------------------
    current_utc_datetime = datetime.datetime.utcnow()
    Op_time = current_utc_datetime.strftime('%Y-%m-%d')
    Op_time = time.strptime(Op_time, "%Y-%m-%d")
    gcal_y = Op_time.tm_year
    gcal_m = Op_time.tm_mon
    gcal_d = Op_time.tm_mday
    MJD_newyear = gcal2jd(gcal_y, gcal_m, gcal_d)[1]
    MJD_current = MJD_newyear
    date_current = jd2gcal(2400000.5, MJD_current)
    calendar_d_lable = "%d_%d_%d" % (date_current[0], date_current[1],
                                     date_current[2])
    calendar_d = "%d-%d-%d" % (date_current[0], date_current[1],
                               date_current[2])

    # start calculate observation sequence
    # time_interval = 40.0 # 2 munitues
    # night_number = 36 # every 2 munitues, 720 in total.
    time_interval = 5.0  # 2 munitues
    night_number = 288  # every 2 munitues, 720 in total.

    # set observatory parameters ----------------------------------------
    observatory = ephem.Observer()
    observatory.lat = observatory_lat
    observatory.lon = observatory_lon
    observatory.elevation = observatory_elevation
    lat_dd = float(str(observatory.lat).split(":")[0])+\
    float(str(observatory.lat).split(":")[1])/60.0+\
    float(str(observatory.lat).split(":")[2])/3600.0

    # define obs date frame ----------------------------------------
    obsframe = pd.DataFrame()

    for k in range(len(gridframe['Grid_ID'])):
        #print 'field coor: ',gridframe['ra_center'][k],gridframe['dec_center'][k]
        mjd = []
        local_time = []
        lst = []
        solar_alt = []
        lunar_ra = []
        lunar_dec = []
        lunar_phase = []
        gridframe.loc[k, 'obs_date'] = calendar_d
        # calculate galactic coordinate of field center and all vertexes
        coor_equ_cen = ephem.Equatorial(gridframe['ra_center'][k],
                                        gridframe['dec_center'][k],
                                        epoch='2000')
        g_cen = ephem.Galactic(coor_equ_cen)
        g_cen_lat_dd = float(str(g_cen.lat).split(":")[0])+\
         float(str(g_cen.lat).split(":")[1])/60.0+\
         float(str(g_cen.lat).split(":")[2])/3600.0
        coor_equ_h1 = ephem.Equatorial(gridframe['radeg_h1'][k],
                                       gridframe['decdeg_h1'][k],
                                       epoch='2000')
        g_h1 = ephem.Galactic(coor_equ_h1)
        g_h1_lat_dd = float(str(g_h1.lat).split(":")[0])+\
         float(str(g_h1.lat).split(":")[1])/60.0+\
         float(str(g_h1.lat).split(":")[2])/3600.0
        coor_equ_h2 = ephem.Equatorial(gridframe['radeg_h2'][k],
                                       gridframe['decdeg_h2'][k],
                                       epoch='2000')
        g_h2 = ephem.Galactic(coor_equ_h2)
        g_h2_lat_dd = float(str(g_h2.lat).split(":")[0])+\
         float(str(g_h2.lat).split(":")[1])/60.0+\
         float(str(g_h2.lat).split(":")[2])/3600.0
        coor_equ_l1 = ephem.Equatorial(gridframe['radeg_l1'][k],
                                       gridframe['decdeg_l1'][k],
                                       epoch='2000')
        g_l1 = ephem.Galactic(coor_equ_l1)
        g_l1_lat_dd = float(str(g_l1.lat).split(":")[0])+\
         float(str(g_l1.lat).split(":")[1])/60.0+\
         float(str(g_l1.lat).split(":")[2])/3600.0
        coor_equ_l2 = ephem.Equatorial(gridframe['radeg_l2'][k],
                                       gridframe['decdeg_l2'][k],
                                       epoch='2000')
        g_l2 = ephem.Galactic(coor_equ_l2)
        g_l2_lat_dd = float(str(g_l2.lat).split(":")[0])+\
         float(str(g_l2.lat).split(":")[1])/60.0+\
         float(str(g_l2.lat).split(":")[2])/3600.0

        galactic_lat_min = min([
            abs(g_cen_lat_dd),
            abs(g_h1_lat_dd),
            abs(g_h2_lat_dd),
            abs(g_l1_lat_dd),
            abs(g_l2_lat_dd)
        ])

        for n in range(night_number):
            # set mjd time ----------------------------------------
            MJD_time = MJD_current + (n * time_interval / 60.0 / 24.0)
            nighttime_current = jd2gcal(2400000.5, MJD_time)
            hh = int(nighttime_current[3] * 24.0)
            mm = int((nighttime_current[3] * 24.0 - hh) * 60.0)
            ss = (((nighttime_current[3] * 24.0 - hh) * 60.0) - mm) * 60.0
            hms = "%02d:%02d:%02d" % (hh, mm, ss)
            nighttime_current_cal = (
                '%s/%s/%s %s' % (nighttime_current[0], nighttime_current[1],
                                 nighttime_current[2], hms))
            nighttime_current_str = (
                '%s/%s/%sT%s' % (nighttime_current[0], nighttime_current[1],
                                 nighttime_current[2], hms))
            observatory.date = nighttime_current_cal

            # set local time ----------------------------------------
            local_nighttime_current = ephem.localtime(observatory.date)
            local_nighttime_current_str = str(local_nighttime_current).replace(
                ' ', 'T')[0:22]

            # calculate local sidereal time  ----------------------------------------
            lst_dd = float(str(observatory.sidereal_time()).split(":")[0])* 15.0+\
            float(str(observatory.sidereal_time()).split(":")[1])/60.0* 15.0+\
            float(str(observatory.sidereal_time()).split(":")[2])/3600.0* 15.0

            # calculate altitude angle or zenith angular distance of the sun   ---------------------------------
            solar = ephem.Sun(observatory)
            solar_alt_dd = 90 - float(str(solar.alt).split(":")[0]) + float(
                str(solar.alt).split(":")[1]) / 60.0 + float(
                    str(solar.alt).split(":")[2]) / 3600.0
            #print('solar  %s' % (solar_alt_dd))

            lunar = ephem.Moon(observatory)
            lunar_ra_dd = float(str(lunar.ra).split(":")[0]) * 15.0 + float(
                str(lunar.ra).split(":")[1]) / 60.0 * 15.0 + float(
                    str(lunar.ra).split(":")[2]) / 3600.0 * 15.0
            lunar_dec_dd = float(str(lunar.dec).split(":")[0]) + float(
                str(lunar.dec).split(":")[1]) / 60.0 + float(
                    str(lunar.dec).split(":")[2]) / 3600.0
            #print('lunar %s %s %s' % (lunar_ra_dd, lunar_dec_dd, lunar.moon_phase))

            # calculate zenith angular distance of field center and all vertexes
            zenith_ang_dis_cen_dd = angular_distance(
                gridframe['ra_center'][k], gridframe['dec_center'][k], lst_dd,
                lat_dd)

            # calculate angular distance between field center and all vertexes and moon
            moon_ang_dis_cen_dd = angular_distance(gridframe['ra_center'][k],
                                                   gridframe['dec_center'][k],
                                                   lunar_ra_dd, lunar_dec_dd)
            moon_ang_dis_h1_dd = angular_distance(gridframe['radeg_h1'][k],
                                                  gridframe['decdeg_h1'][k],
                                                  lunar_ra_dd, lunar_dec_dd)
            moon_ang_dis_h2_dd = angular_distance(gridframe['radeg_h2'][k],
                                                  gridframe['decdeg_h2'][k],
                                                  lunar_ra_dd, lunar_dec_dd)
            moon_ang_dis_l1_dd = angular_distance(gridframe['radeg_l1'][k],
                                                  gridframe['decdeg_l1'][k],
                                                  lunar_ra_dd, lunar_dec_dd)
            moon_ang_dis_l2_dd = angular_distance(gridframe['radeg_l2'][k],
                                                  gridframe['decdeg_l2'][k],
                                                  lunar_ra_dd, lunar_dec_dd)
            moon_ang_dis_min = min([
                moon_ang_dis_cen_dd, moon_ang_dis_h1_dd, moon_ang_dis_h2_dd,
                moon_ang_dis_l1_dd, moon_ang_dis_l2_dd
            ])

            # set mini distance from the moon
            for mm in range(len(moon_dis_phase_data)):
                if (lunar.moon_phase >= moon_dis_phase_data[mm][0]
                        and lunar.moon_phase < moon_dis_phase_data[mm][1]):
                    moon_dis_min = moon_dis_phase_data[mm][2]
                    break
            #print lunar.moon_phase,moon_dis_min

            #print k,gridframe.loc[k,'field_ID'],zenith_ang_dis_cen_dd , zenith_min , galactic_lat_min , gal_min , moon_ang_dis_min , moon_dis_min
            if (solar_alt_dd > zenith_sun_min) and (
                    zenith_ang_dis_cen_dd < zenith_min
            ):  # and galactic_lat_min > gal_min and moon_ang_dis_min > moon_dis_min ):
                # print 'mjd: ',MJD_current,MJD_time,nighttime_current
                # print 'zenith: ',gridframe['ra_center'][k], gridframe['dec_center'][k],lst_dd,lat_dd,solar_alt_dd,zenith_ang_dis_cen_dd,zenith_min
                mjd.append(MJD_time)
                local_time.append(local_nighttime_current_str)
                lst.append(lst_dd)
                solar_alt.append(solar_alt_dd)
                lunar_ra.append(lunar_ra_dd)
                lunar_dec.append(lunar_dec_dd)
                lunar_phase.append(lunar.moon_phase)
                #print gridframe['field_ID'],MJD_time
        # del mjd[0]
        # del local_time[0]
        # del lst[0]
        # del solar_alt[0]
        # del lunar_ra[0]
        # del lunar_dec[0]
        # del lunar_phase[0]

        # mjd = filter(None,mjd)
        # local_time = filter(None,local_time)
        # lst = filter(None,lst)
        # solar_alt = filter(None,solar_alt)
        # lunar_ra = filter(None,lunar_ra)
        # lunar_dec = filter(None,lunar_dec)
        # lunar_phase = filter(None,lunar_phase)

        if (len(mjd) > 0):
            obs_mjd_begin_index = 0
            for mmm in range(len(mjd) - 1):
                m_gap = mjd[mmm + 1] - mjd[mmm]
                m_int = (2.0 / 24.0)
                if m_gap > m_int:
                    obs_mjd_begin_index = mjd.index(mjd[mmm + 1])
            if obs_mjd_begin_index == 0:
                obs_mjd_begin_index = mjd.index(min(mjd))
            obs_mjd_end_index = mjd.index(max(mjd))

            gridframe.loc[k, 'mjd_begin'] = mjd[obs_mjd_begin_index]
            gridframe.loc[k, 'mjd_end'] = mjd[obs_mjd_end_index]
            gridframe.loc[k,
                          'local_time_begin'] = local_time[obs_mjd_begin_index]
            gridframe.loc[k, 'local_time_end'] = local_time[obs_mjd_end_index]
            gridframe.loc[k, 'lst_begin'] = lst[obs_mjd_begin_index]
            gridframe.loc[k, 'lst_end'] = lst[obs_mjd_end_index]
            gridframe.loc[k,
                          'solar_alt_begin'] = solar_alt[obs_mjd_begin_index]
            gridframe.loc[k, 'solar_alt_end'] = solar_alt[obs_mjd_end_index]
            gridframe.loc[k, 'lunar_ra_begin'] = lunar_ra[obs_mjd_begin_index]
            gridframe.loc[k, 'lunar_dec_begin'] = lunar_dec[obs_mjd_end_index]
            gridframe.loc[
                k, 'lunar_phase_begin'] = lunar_phase[obs_mjd_begin_index]
            gridframe.loc[k, 'lunar_ra_end'] = lunar_ra[obs_mjd_end_index]
            gridframe.loc[k, 'lunar_dec_end'] = lunar_dec[obs_mjd_begin_index]
            gridframe.loc[k,
                          'lunar_phase_end'] = lunar_phase[obs_mjd_end_index]

    for k in range(len(gridframe['obs_date'])):
        CurrentTable = "grid_observable_timetable"
        if gridframe.loc[k, 'mjd_begin'] > 0:
            insert_cmd = "insert into " + CurrentTable + " values ( DEFAULT , " + \
            "'" + gridframe.loc[k,'obs_date']  + "' , " + \
            "'" + gridframe.loc[k,'Grid_ID'] + "' , " + \
            "'" + gridframe.loc[k,'field_ID'] + "' , " + \
            " " + str(gridframe.loc[k,'ra_center']) + " , " + \
            " " + str(gridframe.loc[k,'dec_center']) + " , " + \
            " " + str(gridframe.loc[k,'radeg_h1']) + " , " + \
            " " + str(gridframe.loc[k,'decdeg_h1']) + " , " + \
            " " + str(gridframe.loc[k,'radeg_h2']) + " , " + \
            " " + str(gridframe.loc[k,'decdeg_h2']) + " , " + \
            " " + str(gridframe.loc[k,'radeg_l1']) + " , " + \
            " " + str(gridframe.loc[k,'decdeg_l1']) + " , " + \
            " " + str(gridframe.loc[k,'radeg_l2']) + " , " + \
            " " + str(gridframe.loc[k,'decdeg_l2']) + " , " + \
            " " + str(gridframe.loc[k,'mjd_begin']) + " , " + \
            " " + str(gridframe.loc[k,'mjd_end']) + " , " + \
            "'" + str(gridframe.loc[k,'local_time_begin']) + "' , " + \
            "'" + str(gridframe.loc[k,'local_time_end']) + "' , " + \
            " " + str(gridframe.loc[k,'lst_begin']) + " , " + \
            " " + str(gridframe.loc[k,'lst_end']) + " , " + \
            " " + str(gridframe.loc[k,'solar_alt_begin']) + " , " + \
            " " + str(gridframe.loc[k,'solar_alt_end']) + " , " + \
            " " + str(gridframe.loc[k,'lunar_ra_begin']) + " , " + \
            " " + str(gridframe.loc[k,'lunar_dec_begin']) + " , " + \
            " " + str(gridframe.loc[k,'lunar_phase_begin']) + " , " + \
            " " + str(gridframe.loc[k,'lunar_ra_end']) + " , " + \
            " " + str(gridframe.loc[k,'lunar_dec_end']) + " , " + \
            " " + str(gridframe.loc[k,'lunar_phase_end']) + " " + \
            " " + ")"
            print insert_cmd
            cursor = conn_gwacoc_grid.cursor()
            cursor.execute(insert_cmd)
            conn_gwacoc_grid.commit()
            cursor.close()

    conn_gwacoc_grid.close()
import jdcal

assert jdcal.gcal2jd(2000,1, 1) == (2400000.5, 51544.0)
assert jdcal.gcal2jd(2001,2,30) == (2400000.5, 51970.0)
assert jdcal.jd2gcal(2400000.5, 51544.75) == (2000, 1, 1, 0.75)
assert jdcal.__version__ == '1.3'
Exemple #47
0
Fichier : ocal.py Projet : mlv/ocal
 def get_ymd_g(self):
     """return the year, month, and day of the instance, according to the
     Gregorian calendar"""
     return jdcal.jd2gcal(jdcal.MJD_0, self.date)[:3]
Exemple #48
0
    vals = []
    for perc in percentiles:
        vals.append(sd[perc*len(sd)])
        truc = truc + '{0:.1f} ({1:.0f}%) - '.format(sd[perc*len(sd)], perc*100)
    return truc[0:-3], vals




### Wind data
dir = '/Users/hamilton/Qubic/Sites/FromMarcelo/data_h/'
ts0, rec0, WS_ms_Avg, WS_ms_Std, WS_ms_Max, WS_ms_S_WVT, WindDir_D1_WVT, WindDir_SD1_WVT = np.loadtxt(dir+'chorrillo-t1m_cal.csv', usecols = [2,3,4,5,6,7,8,9]).T
import jdcal as jdcal
init = np.sum(jdcal.gcal2jd(1970,1,1))
jd0 = ts0/3600/24
jdcal.jd2gcal(init, jd0[0])
jdcal.jd2gcal(init, jd0[-1])
jdstartyear = np.sum(jdcal.gcal2jd(2011,1,1))
jdsince0 = init + ts0/3600/24 - jdstartyear


clf()
plot(jdsince0, WS_ms_Max, 'r,')
plot(jdsince0, WS_ms_Avg)
plot(jdsince0, WS_ms_Std)
xlabel('JD since 2011')
ylabel('Wind Speed $[m/s]$')

#### comparer avec https://science.nrao.edu/facilities/alma/aboutALMA/Technology/ALMA_Memo_Series/alma497/memo497.pdf
#### Figure 3.1
bla=hist(WS_ms_Avg, range=[0,30], bins=300, cumulative=True,normed=1, alpha=0.1)
Exemple #49
0
def main(argv):
	if len(argv) < 4:
		print "Error: not enough arguments"
		print
		display_usage(argv[0])
		return 1

	from_date = datetime.strptime(argv[1], u"%Y-%m-%d")
	to_date = datetime.strptime(argv[2], u"%Y-%m-%d")
	site_abbr = argv[3]
	cmd = 'wget -nv'
	if len(argv) >= 5:
		cmd = ' '.join(argv[4:])
		#print "# Command = <%s>" % (cmd, )

	list_only = None
	if cmd != '-':
		list_only = False
		cmd = cmd + ' '
	else:
		list_only = True
		cmd = ''
	# if-else

	# Convert to Julian Day numbers
	from_mjday = date2mjday(from_date)
	to_mjday = date2mjday(to_date)

	# Compute the GPS zero day
	gps_zeroday = date2mjday(datetime(1980, 1, 6))

	if list_only == False:
		print "#!/bin/bash"
		print
		print "# Automatically generated script for downloading "\
		    "RINEX NAV files."
		print "# From date:   %s" % (from_date.strftime("%Y-%m-%d"), )
		print "# To date:     %s (excluded)" % (to_date.strftime("%Y-%m-%d"), )
		print "# Span:        %d days" % (to_mjday - from_mjday, )
		print
	# if: not list_only

	# Loop from the first day until the last day (exclusive)
	for mjday in range(from_mjday, to_mjday):
		gpsday = mjday - gps_zeroday
		gdate = datetime(*jdcal.jd2gcal(jdcal.MJD_0, mjday)[:3])
		year = gdate.year

		# Compute the mjd for the first day of the year
		yday_zero = date2mjday(datetime(year, 1, 1))
		yday = mjday - yday_zero + 1

		# Get the GPS week number
		gpscycle = int(gpsday / (1024*7))
		gpsweek = int(gpsday / 7) % 1024
		gpsdow = gpsday % 7

		# Compute day of the year

		"""
		print "# %s is gpsday %s (cycle %d week %d dow %d; yday %d)" % (
		    gdate.strftime("%Y-%m-%d"), 
		    gpsday,
		    gpscycle,
		    gpsweek,
		    gpsdow,
		    yday,
		)
		"""

		# Select correct base url.
		urls = build_urls_for(year, yday)

		print "%s%s" % (cmd, urls[site_abbr],)	
Exemple #50
0
def test_jd2gcal():
    assert jd2gcal(*gcal2jd(2000, 1, 1)) == (2000, 1, 1, 0.0)
    assert jd2gcal(*gcal2jd(1950, 1, 1)) == (1950, 1, 1, 0.0)
    assert jd2gcal(*gcal2jd(1999, 10, 12)) == (1999, 10, 12, 0.0)
    assert jd2gcal(*gcal2jd(2000, 2, 30)) == (2000, 3, 1, 0.0)
    assert jd2gcal(*gcal2jd(2000, -2, -4)) == (1999, 9, 26, 0.0)
#
# I hope this information be useful for you.
#
#  Please do not hesitate to let me know if you need anything else.
#
# Regards
#
# Emiliano
#

####### Macon tipper data
ts,tau, tau_s = np.genfromtxt('/Users/hamilton/CMB/Interfero/Sites/FromEmiliano/tipper_macon.dat',skiprows=1,invalid_raise=False).T

import jdcal as jdcal
init = np.sum(jdcal.gcal2jd(1992,1,1))
newts = init+ts

yy=[]
mm=[]
dd=[]
ut=[]
for thets in ts:
    theyy, themm, thedd, theut = jdcal.jd2gcal(init,thets)
    yy.append(theyy)
    mm.append(themm)
    dd.append(thedd)
    ut.append(theut)


clf()
plot(time,tau,',')