Beispiel #1
0
def session_plan_set_moonless_astro_twilight(session_plan_id):
    session_plan = SessionPlan.query.filter_by(id=session_plan_id).first()
    _check_session_plan(session_plan)

    t1, t2 = _get_twighligh_component(session_plan, 1)

    if t1 and t2:
        ts = load.timescale()
        _, latitude, longitude, _ = _get_location_info_from_session_plan(
            session_plan)
        observer = wgs84.latlon(latitude, longitude)
        tz_info = _get_session_plan_tzinfo(session_plan)
        ldate_start = tz_info.localize(session_plan.for_date +
                                       timedelta(hours=0))
        ldate_end = tz_info.localize(session_plan.for_date +
                                     timedelta(hours=48))
        start_t = ts.from_datetime(ldate_start)
        end_t = ts.from_datetime(ldate_end)
        eph = load('de421.bsp')
        f = almanac.risings_and_settings(eph, eph['Moon'], observer)
        t, y = almanac.find_discrete(start_t, end_t, f)

        if t1 and t2:
            rise_sets = []
            moon_rise, moon_set = None, None
            for i in range(len(y)):
                if y[i]:
                    moon_rise = t[i].astimezone(tz_info)
                else:
                    moon_set = t[i].astimezone(tz_info)
                    rise_sets.append((moon_rise, moon_set))
                    moon_rise, moon_set = None, None
            if moon_rise or moon_set:
                rise_sets.append((moon_rise, moon_set))

            for moon_rise, moon_set in rise_sets:
                if not moon_rise:
                    moon_rise = ldate_start
                if not moon_set:
                    moon_set = ldate_end
                if moon_set < t1 or moon_rise > t2:
                    continue
                if moon_rise < t1 and moon_set > t2:
                    t1, t2 = None, None
                    break
                if moon_rise > t1:
                    t2 = moon_rise
                else:
                    t1 = moon_set
            if t1 and t2 and t1 > t2:
                t1, t2 = None, None

    if t1 and t2:
        session['planner_time_from'] = t1.strftime(SCHEDULE_TIME_FORMAT)
        session['planner_time_to'] = t2.strftime(SCHEDULE_TIME_FORMAT)

    session['is_backr'] = True
    return redirect(
        url_for('main_sessionplan.session_plan_schedule',
                session_plan_id=session_plan.id))
Beispiel #2
0
def planet_timestamp(name, action, ts, planets, city, eph, names):
    print(name, action)
    logging.info('%s %s' % (name, action))
    # this function returns the next rise or set time from now
    t0 = datetime.datetime.now(timezone.utc)
    print('t0:', t0)
    logging.info('t0: %s' % t0)
    # make hours 24+1 because during spring, next sunset will be more than 24h later than current
    t1 = t0 + datetime.timedelta(hours=25)
    print('t1:', t1)
    logging.info('t1: %s' % t1)

    # t0 = t0.replace(tzinfo=utc)
    t0 = ts.utc(t0)
    # t1 = t1.replace(tzinfo=utc)
    t1 = ts.utc(t1)

    f = risings_and_settings(eph, planets[names.index(name)], city)
    #This returns a function taking a Time argument returning True if the body’s altazimuth altitude angle plus radius_degrees is greater than horizon_degrees, else False
    t, values = find_discrete(t0, t1, f)
    #Find the times at which a discrete function of time changes value. in this case, find the set (0) and rise (1) times, t.

    if action == 'rise':
        #values array is 1 for the rise. we look up the index of the rise in the time array, t, to get the time of the rise event.
        timestamp = t[numpy.where(values == 1)].utc_datetime()
        print('timestamp:', timestamp)
        logging.info('timestamp: %s' % timestamp)
    else:
        #values array is 0 for the set. we look up the index of the set in the time array, t, to get the time of the set event.
        timestamp = t[numpy.where(values == 0)].utc_datetime()
        print('timestamp:', timestamp)
        logging.info('timestamp: %s' % timestamp)

    timestamp = timestamp[0].timestamp()
    return int(timestamp)
Beispiel #3
0
def risings_and_settings(data: AstroData, body: str, t0: Time, t1: Time) -> List[RisingOrSetting]:
    f = almanac.risings_and_settings(data.ephemeris, data.get_body(body), data.babylon_topos)
    t, y = almanac.find_discrete(t0, t1, f)

    out = []
    for ti, yi in zip(t, y):
        type = RiseSetType.RISE if yi else RiseSetType.SET
        out.append(RisingOrSetting(ti, type))
    return out
 def moonSet(self, t):
     t = t.utc
     t0 = ts.utc(t[0], t[1], t[2], t[3], t[4], t[5])
     t1 = ts.utc(t[0], t[1], t[2] + 1, t[3], t[4], t[5])
     f = almanac.risings_and_settings(e, e['moon'], self.topo)
     t, y = almanac.find_discrete(t0, t1, f)
     for ti, yi in zip(t, y):
         if (yi == 0):
             return ti
         else:
             pass
Beispiel #5
0
def calc_comet(comet_df, obstime, earthcoords, numdays=0, alt_table=False):
    # Generating a position.
    cometvec = sun + mpc.comet_orbit(comet_df, ts, GM_SUN)

    cometpos = earth.at(obstime).observe(cometvec)
    ra, dec, distance = cometpos.radec()
    print("RA", ra, "   DEC", dec, "   Distance", distance)

    if earthcoords:
        if len(earthcoords) > 2:
            elev = earthcoords[2]
        else:
            elev = 0
        obstopos = Topos(latitude_degrees=earthcoords[0],
                         longitude_degrees=earthcoords[1],
                         elevation_m=elev)
        print("\nObserver at", obstopos.latitude, "N  ", obstopos.longitude,
              "E  ", "Elevation", obstopos.elevation.m, "m")
        obsvec = earth + obstopos

        alt, az, distance = \
            obsvec.at(obstime).observe(cometvec).apparent().altaz()
        print("Altitude", alt, "     Azumuth", az, distance)

        alm_twilights = almanac.dark_twilight_day(eph, obstopos)
        # dawn, dusk = find_twilights(obstime, alm_twilights)
        # print(WHICH_TWILIGHT, ": Dawn", svt2str(dawn), "Dusk", svt2str(dusk))

        if numdays:
            print("\nRises and sets over", numdays, "days:")
            datetime1 = obstime.utc_datetime() - timedelta(hours=2)
            t0 = ts.utc(datetime1)
            t1 = ts.utc(datetime1 + timedelta(days=numdays))

            alm = almanac.risings_and_settings(eph, cometvec, obstopos)
            t, y = almanac.find_discrete(t0, t1, alm)

            print_rises_sets(obsvec, cometvec, alm, t0, t1)

        if alt_table:
            print()
            oneday = timedelta(days=1)
            while True:
                print_alt_table(obstime, cometvec, obsvec, alm_twilights)
                numdays -= 1
                if numdays <= 0:
                    break
                # Add a day: there doesn't seem to be a way to do this
                # while staying within skyview's Time object.
                obstime = ts.utc(obstime.utc_datetime() + oneday)
Beispiel #6
0
def Lunar_Rise_Set(e, gs, t0=None, t1=None):
    if t0 == None:
        t0 = ts.utc(datetime.datetime.now(datetime.timezone.utc))  #Now
    if t1 == None:
        t1 = ts.utc(
            datetime.datetime.now(datetime.timezone.utc) +
            datetime.timedelta(hours=24))  #24 hours from now
    #print(t0)
    #print(t1)
    f = almanac.risings_and_settings(e, e['Moon'], gs)
    t, y = almanac.find_discrete(t0, t1, f)
    #print (t, y)
    for ti, yi in zip(t, y):
        #print (ti,yi)
        print('Lunar Rise:' if yi else ' Lunar Set:', ti.utc_datetime())
        if yi:  #Rise
            rise_time = ti.utc_datetime()
        else:
            set_time = ti.utc_datetime()

    return {'rise': rise_time, 'set': set_time, 'vis': set_time < rise_time}
data = pd.DataFrame(np.tile(latlon_base, (2 * len(jd_range), 1)),
                    columns=["LAT", "LON"])

# insert JDs and placeholders for fractions
data["JD_FLOOR"] = jd_range_repeat
data["JD_MOD"] = np.nan  # for JD modulus
data["EVENT"] = event_boolean

# for each coordinate, calculate sunrise and sunset times for the relevant range of dates
for ind_num in range(0, len(data)):

    print(ind_num)

    bluffton = api.wgs84.latlon(data["LAT"][ind_num], data["LON"][ind_num])

    f = almanac.risings_and_settings(eph, eph['Sun'], bluffton)
    epochs_full, riseorset = almanac.find_discrete(t0, t1, f)

    # loop over each event and populate the JD_MOD column with the decimal
    # part of the JD
    for t in range(0, len(epochs_full)):

        #print(riseorset[t])
        #import ipdb; ipdb.set_trace()

        #epoch_this = epochs_full[t]
        #riseorset_this = riseorset[t]

        data.loc[(
            (data["JD_FLOOR"] == np.floor(epochs_full.tdb[t].astype(float))) &
            (data["LAT"] == data["LAT"][ind_num]) &
Beispiel #8
0
    print(err)

add_rise_set = ("""
INSERT INTO rise_set
VALUES (%s, %s, %s, %s)
""")

eph = load('de421.bsp')
p_names = ['Mercury', 'Venus', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
p_codes = [1, 2, 4, 5, 6, 7, 8]
ts = api.load.timescale()
t0 = ts.now()
t1 = ts.utc(t0.utc_datetime() + timedelta(days=1))
location = api.wgs84.latlon(39.700096, -75.111423) # Glassboro, NJ

for code, planet in zip(p_codes, p_names):
    f = almanac.risings_and_settings(eph, eph[code], location)
    t, y = almanac.find_discrete(t0, t1, f)
    
    for ti, yi in zip(t, y):
        if yi:
            rise_t = ti.utc_iso()
        else:
            set_t = ti.utc_iso()
    insert = (code, planet, rise_t, set_t)
    cursor.execute(add_rise_set, insert)
db.commit()
print("Successfully inserted rise and set times of the planets")
cursor.close()
db.close()
Beispiel #9
0
from skyfield import api, almanac
from datetime import datetime, timedelta

ts = api.load.timescale()

ephemeris = api.load('de421.bsp')

my_position = api.Topos('34.606 S', '58.419 W')

# Only naked-eye visible planets:
planets = 'Mercury Venus Mars Jupiter Saturn'.split()

# Collect all boolean functions in one list:
ras = [
    almanac.risings_and_settings(ephemeris, ephemeris[p + '_barycenter'],
                                 my_position) for p in planets
]

# Append one for checking that the Sun is down:
is_sun_down = lambda t: not almanac.sunrise_sunset(ephemeris, my_position)(t)
ras.append(is_sun_down)

delta = timedelta(hours=1)  # days=0.5)
t = datetime.now(api.utc)

while not all(f(ts.utc(t)) for f in ras):
    t += delta
print(t)

# TODO: allow a minimum elevation
# TODO: take into account Mercury distance from the Sun, to avoid being dazzled by it.
Beispiel #10
0
goal_az = 99.7                # degrees ; for azimuth search
max_err_days = 0.0000001      # = 0.0086 sec ; max search error
search_range_days = 0.1       # = 2.4 hours ; search at either side of the approx sunrise


goal_alt_approx = alt_of_first_light - Bennett_refraction(alt_of_first_light) - approx_sun_radius
print ('Approx goal altitude =', goal_alt_approx, '\n') # The astronomical altitude of the center of the Sun's disk, without atmospheric refraction

ts = api.load.timescale()
ts.julian_calendar_cutoff = 2299161          # Converts to Julian date when earlier than 2299161 = 15 October 1582 ; start of the Gregorian calendar
t_start = ts.ut1(-514, 3, 12)  # scan dates: proleptic Gregorian dates (e.g. -959 = BC 960)
t_finsh = ts.ut1(-514, 3, 14)  # not including this date


almanac_func = almanac.risings_and_settings(ephem, sun_abs, site_local, horizon_degrees = goal_alt_approx)
t, y = almanac.find_discrete(t_start, t_finsh, almanac_func)

print ("For each day in range, we check:")
print (' Approximate local sunrise, with fixed Sun radius')
print (' More accurate local sunrise, with variable Sun radius')
print (' When the Sun is near an azimuth of', goal_az)
print ()

print ('   Julian Day           Julian Date (UT1 +2)           Altitude   Azimuth')
print ('  -------------    ---------------------------------    -------   --------')
for ti, yi in zip(t,y):
    if yi == True:     # sunrise
        position = site_abs.at(ti).observe(sun_abs).apparent()
        alt, az, distance = position.altaz()
        print('  %.5f' % ti.ut1, '  ', string_date_timezone(ts, ti, 2), '   %.5f' % alt.degrees, '  %.5f' % az.degrees)
Beispiel #11
0
next_new_moon_selected = False
for phase_time, phase_identifier in next_phases:
    if next_new_moon_selected:
        break
    if phase_identifier == NEW_MOON_IDENTIFIER:
        next_new_moon_selected = True
    moon_phases.append({
        "name": almanac.MOON_PHASES[phase_identifier],
        "datetime": phase_time.utc_datetime()
    })

# Rising and setting

next_day = observation_datetime + timedelta(days=1)
next_day_time = timescale.utc(next_day)
rs_almanac = almanac.risings_and_settings(eph, moon, observer_topos)
rs_times, rs_moments = almanac.find_discrete(observation_time, next_day_time,
                                             rs_almanac)

# Constellation

constellation_at = load_constellation_map()
moon_position = position_from_radec(ra.hours, dec.degrees)
current_constellation = constellation_at(moon_position)

# JSON build

data = detailled_coordinates(ra, dec, alt, az, dist)

for rs_time, rs_moment in zip(rs_times, rs_moments):
    rs_apparent = observer_location.at(rs_time).observe(moon).apparent()
def get_sun_moon_rise_set_for_latlon(
    latitude: float,
    longitude: float,
    requested_date: datetime.datetime,
    elevation: float = 0.0,
):
    """
    Determine sunrise/sunset and moonrise/moonset for a given set of coordinates
    for a certain date

    Parameters
    ==========
    latitude : 'float'
        Latitude value
    longitude : 'float'
        Longitude value
    requested_date: class 'datetime'
        Datestamp for the given calculation
    elevation : 'float'
        Elevation in meters above sea levels
        Default is 0 (sea level)

    Returns
    =======
    sunrise: 'datetime'
        Datetime object of the next sunrise
        for the given coordinates and date
        Timezone = UTC
    sunset: 'datetime'
        Datetime object of the next sunset
        for the given coordinates and date
        Timezone = UTC
    moonrise: 'datetime'
        Datetime object of the next moonrise
        for the given coordinates and date
        Timezone = UTC
    moonset: 'datetime'
        Datetime object of the next moonset
        for the given coordinates and date
        Timezone = UTC
    """

    ts = api.load.timescale()
    eph = api.load("de421.bsp")

    sunrise = sunset = moonrise = moonset = None

    today = requested_date
    tomorrow = requested_date + datetime.timedelta(days=1)

    pos = api.Topos(latitude_degrees=latitude,
                    longitude_degrees=longitude,
                    elevation_m=elevation)

    t0 = ts.utc(today.year, today.month, today.day)
    t1 = ts.utc(tomorrow.year, tomorrow.month, tomorrow.day)
    t, y = almanac.find_discrete(t0, t1, almanac.sunrise_sunset(eph, pos))

    for ti, yi in zip(t, y):
        if yi:
            sunrise = ti.utc_datetime()
        else:
            sunset = ti.utc_datetime()

    f = almanac.risings_and_settings(eph, eph["Moon"], pos)
    t, y = almanac.find_discrete(t0, t1, f)

    for ti, yi in zip(t, y):
        if yi:
            moonrise = ti.utc_datetime()
        else:
            moonset = ti.utc_datetime()
    return sunrise, sunset, moonrise, moonset
Beispiel #13
0
    # astrometric = earth.at(t0).observe(ephem[planets[p]])
    astrometric = amstercentric.at(t0).observe(ephem[planets[p]])
    ra, dec, distance = astrometric.radec()
    alt, az, distance = astrometric.apparent().altaz()

    print("  Declinatie: %6.2f Rechte klimming: %6.2f " %
          (dec.to(units.deg).value, ra.to(units.deg).value))
    if alt.to(units.deg) > 0.0:
        print("  Hoogte: %6.2f, Azimuth: %6.2f" %
              (alt.to(units.deg).value, az.to(units.deg).value))
        ix = epd.height * az.to(units.deg).value / 360.0
        iy = epd.width * (maxalt - alt.to(units.deg).value) / maxalt
        drawblack.text((ix, iy - 5), symbols[p], font=cmastro14, fill=0)
    else:
        f = almanac.risings_and_settings(ephem, ephem[planets[p]], amsterdam)
        t, y = almanac.find_discrete(t0, t1, f)
        for ti, yi in zip(t, y):
            trise = ti.utc_datetime().astimezone(cet).time()
            if yi:
                opkomst = trise.strftime('%H:%M')
                print('  Opkomst om ' + opkomst)
                drawred.text((2, irise * 14),
                             symbols[p],
                             font=cmastro12,
                             fill=0)
                drawred.text((16, irise * 14), opkomst, font=font12, fill=0)
                irise = irise + 1

maanverlicht = int(100 *
                   (almanac.fraction_illuminated(ephem, 'Moon', t0) + 0.05))