Example #1
0
def main(argv):
    datetime = ''
    coords = ''
    try:
        opts, args = getopt.getopt(argv, "hd:c", ["datetime=", "coords="])
    except getopt.GetoptError:
        print('moon.py -d <datetime at 2018/07/05t23:59:59>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('moon.py  -d <datetime at 2018/07/05t23:59:59>')
            sys.exit()
        elif opt in ("-d", "--datetime"):
            datetime = arg
        elif opt in ("-c", "--coords"):
            datetime = arg

    # print(datetime)
    year = int(datetime[:-15])
    month = int(datetime[5:-12])
    day = int(datetime[8:-9])
    hh = int(datetime[11:-6])
    mm = int(datetime[14:-3])
    ss = int(datetime[17:])

    # print(datetime[:-15] +" "+ datetime[5:-12] + " " + datetime[8:-9])

    mi = pylunar.MoonInfo((33, 00, 00), (-70, 33, 26))
    mi.update((year, month, day, hh, mm, ss))
    phase_name = mi.phase_name()
    percent = mi.fractional_phase()
    age = mi.age()

    print("Phase Name: " + str(phase_name) + " Percent:" + str(percent) +
          " Age:" + str(age))
    def lunar(self):
        """Calculate age of moon as integer."""

        m = pylunar.MoonInfo((31, 46, 19), (35, 13, 1))  # lat/long Jerusalem
        m.update((self.date.year, self.date.month, self.date.day, 0, 0, 0))
        age = round(m.age())
        return age
Example #3
0
def set_up_forecast(city, state, centering, new_loc=False):
    """
    Sets up the forecast table
    Returns the context for the html
    :return:
    """
    global current_hour, master_forecast
    global formatted_current

    # Determine if city/state or lat/lng, return loc data and location
    if request.form:
        geocoder_data, loc = get_user_locational_data(city, state)
    else:
        loc = default_loc
        geocoder_data = geocoder.geocode(default_loc)

    lat = geocoder_data[0]['geometry']['lat']
    lng = geocoder_data[0]['geometry']['lng']

    # Localize the time to where the data is being requested
    tz_obj = TimezoneFinder()
    my_date = dt.now(pytz.timezone(tz_obj.timezone_at(lng=lng, lat=lat)))
    localized_hour = my_date.hour

    if new_loc:
        master_forecast = request_data(lat, lng)

    hourly_forcast = parse_weather_data(centering)

    # Get a list of wind directions and ids
    wind_direction_ids = []
    wind_directions = []
    for key in hourly_forcast:
        wind_directions.append(
            u.wind_direction(hourly_forcast[key]['wind_deg']))
        wind_direction_ids.append("direction" + str(key))

    # Get moon rise / set times
    lat_dms = u.decdeg2dms(geocoder_data[0]['geometry']['lat'])
    lng_dms = u.decdeg2dms(geocoder_data[0]['geometry']['lng'])
    moon_obj = pylunar.MoonInfo(lat_dms, lng_dms)
    lunar_set_rise = pylunar.MoonInfo.rise_set_times(moon_obj, "UTC-07:00")

    # Return the context for flask html variables as a dictionary
    return {
        'geocode': geocoder_data,
        'darksky': hourly_forcast,
        'wind_directions': wind_directions,
        'wind_direction_ids': wind_direction_ids,
        'date': u.get_current_date(),
        'location': loc,
        'phase': moon_obj.phase_name().replace("_", " "),
        'lunar_times': lunar_set_rise,
        'current_hour': localized_hour
    }
Example #4
0
    def lunar(self, date: datetime):
        """

        Parameters
        ----------
        date: datetime :


        Returns
        -------

        """
        m = pylunar.MoonInfo((31, 46, 19), (35, 13, 1))  # lat/long Jerusalem
        m.update((date.year, date.month, date.day, 0, 0, 0))
        age = round(m.age())
        return age
Example #5
0
def main():
    url = "https://opendata.aemet.es/opendata/api/prediccion/especifica/municipio/diaria/17105"
    querystring = {"api_key":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJlcG9uc2NAZ21haWwuY29tIiwianRpIjoiZjJmYzNhYTEtYmM4OC00ZTkyLTgyMTctOTI0MzdiZTI5NTkxIiwiaXNzIjoiQUVNRVQiLCJpYXQiOjE1NjkyNjEyNTAsInVzZXJJZCI6ImYyZmMzYWExLWJjODgtNGU5Mi04MjE3LTkyNDM3YmUyOTU5MSIsInJvbGUiOiIifQ.pD9llUZtFQqJCwpDjj8BG_deFOm7R5tSoJNxkBFWOfU"}
    headers = {
        'cache-control': "no-cache"
    }
    response = requests.get(url, headers=headers, params=querystring)
    url_municipi = response.json()["datos"]
    response = requests.get(url_municipi, headers=headers, params=querystring)
    prediction = response.json()[0]["prediccion"]["dia"]
    
    daily_sky_status = []
    for day in prediction:
        daily_sky_status.append(day["estadoCielo"][-1]["descripcion"])
    
    one_day = datetime.timedelta(days=1)
    today = datetime.date.today()
    days = []
    for x in range(7):
        days.append(today + one_day * x)

    mi = pylunar.MoonInfo((42, 7, 30), (2, 38, 19))

    daily_moon_phase = []
    days_string = []

    for x in days:
        mi.update((x.year, x.month, x.day, 22, 0, 0))
        daily_moon_phase.append(mi.fractional_phase())
        days_string.append(x.strftime("%d/%m/%Y"))

    preresult = list(zip(daily_sky_status, daily_moon_phase))

    result = []
    for sky_status, moon_phase in preresult:
        if moon_phase < 0.5 and sky_status in ["Despejado", "Despejado noche", "Poco nuboso", "Poco nuboso noche"]:
            result.append("Very Good Night for stargazing")
        elif moon_phase < 0.5 and sky_status in ["Intervalos nubosos", "Intervalos nubosos noche"]:
            result.append("Good Night for stargazing")
        elif moon_phase < 0.2 and sky_status in ["Despejado", "Despejado noche", "Poco nuboso", "Poco nuboso noche"]:
            result.append("Perfect Night for stargazing")
        else:
            result.append("Another Night would be better")
    final_result = list(zip(days_string, result))
    pprint(final_result)
Example #6
0
def lua(greet_bot, last_chat_id):
    # Brasilia
    mi = pylunar.MoonInfo((-15, 47, 38), (-47, 52, 58))
    mi.update(datetime.datetime.utcnow())
    percentual = mi.fractional_phase()
    idade = mi.age()
    x = mi.rise_set_times('America/Sao_Paulo')
    nascimento = datetime.datetime(*x[0][1])
    topo = datetime.datetime(*x[1][1])
    por = datetime.datetime(*x[2][1])
    # New Moon.
    # Waxing Crescent.
    # First Quarter.
    # Waxing Gibbous.
    # Full Moon.
    # Waning Gibbous.
    # Last Quarter.
    # Waning Crescent.
    #

    lua = {
        "NEW_MOON": "Lua nova",
        "WAXING_CRESCENT": "Lua nova crescente ",
        "FIRST_QUARTER": "Lua cresente",
        "WAXING_GIBBOUS": "Lua cresente quase cheia",
        "FULL_MOON": "Lua cheia",
        "WANING_GIBBOUS": "Lua cheia minguando",
        "LAST_QUARTER": "Lua minguante",
        "WANING_CRESCENT": "Lua minguante quase nova"
    }
    print(mi.phase_name())
    print(mi.magnitude())
    greet_bot.send_message(
        last_chat_id, "Lua %s.  %.2f percentual de cheia\nIdade %.2f\n"
        "Nascimento %s \nÁplice %s\nPor %s\n" %
        (lua[mi.phase_name()], percentual * 100, idade,
         nascimento.strftime("%d/%m/%Y %H:%M:%S"),
         topo.strftime("%d/%m/%Y %H:%M:%S"),
         por.strftime("%d/%m/%Y %H:%M:%S")))
Example #7
0
def bokehTile(tileFile,
              jsonFile,
              TT=[0, 0, 0],
              DD=[2019, 10, 1],
              dynamic=False,
              plotTitle=''):
    citls, h = fitsio.read(tileFile, header=True)
    w = (np.where(citls['IN_DESI'] == 1)[0])
    inci = citls[w]

    if jsonFile is not None:
        with open(jsonFile, "r") as read_file:
            data = json.load(read_file)

    ## Coloring scheme
    palette = ['green', 'red', 'white']
    dye = []

    for tile in citls['TILEID']:

        rang = 2  # 'orange'

        if jsonFile is not None:
            if str(tile) in data:
                rang = 0  # 'green' #green default
                if len(data[str(tile)]
                       ['unassigned']) > 0:  # not assigned (red)
                    rang = 1  # 'red' #'red'
                if (0 in data[str(tile)]['gfa_stars_percam']):
                    print(data[str(tile)]['gfa_stars_percam'])
                    rang = 1  # 'cyan'
        else:
            rang = 0  # green if qa.json is not provided

        dye.append(rang)

    dye = np.asarray(dye)
    w = (np.where(dye < 2)[0])
    citls = citls[w]
    dye = dye[w]
    mapper = linear_cmap(field_name='DYE', palette=palette, low=0, high=2)

    #########################################################
    TOOLS = [
        'pan', 'tap', 'wheel_zoom', 'box_zoom', 'reset', 'save', 'box_select'
    ]

    obsTime = dt(DD[0], DD[1], DD[2], TT[0], TT[1], TT[2])
    # print(get_kp_twilights(TT,DD))

    if plotTitle == '' or plotTitle is None:
        PTITLE = ''
    else:
        PTITLE = 'Program: ' + plotTitle

    p = figure(tools=TOOLS,
               toolbar_location="right",
               plot_width=800,
               plot_height=450,
               title=PTITLE,
               active_drag='box_select')  # str(DD[1])+" - 2019")
    p.title.text_font_size = '16pt'
    p.title.text_color = 'black'
    p.grid.grid_line_color = "gainsboro"

    ###############################  adding ecliptic plane+ hour grid ####################3
    add_plane(p, color='red', plane='ecliptic', projection='equatorial')

    tiledata = dict(
        RA=citls['RA'],
        DEC=citls['DEC'],
        TILEID=citls['TILEID'],
        BRIGHTRA=citls['BRIGHTRA'][:, 0],
        BRIGHTDEC=citls['BRIGHTDEC'][:, 0],
        BRIGHTVTMAG=citls['BRIGHTVTMAG'][:, 0],
        EBV_MED=np.round(citls['EBV_MED'], 3),
        STAR_DENSITY=citls['STAR_DENSITY'],
        DYE=dye,
        program=citls['PROGRAM'],
        selected=np.ones(len(citls), dtype=bool),
    )

    for colname in ['STAR_DENSITY', 'EBV_MED']:
        if colname in citls.dtype.names:
            tiledata[colname] = citls[colname]

    tiles = ColumnDataSource(data=tiledata)

    colformat = bktables.NumberFormatter(format='0,0.00')
    columns = [
        bktables.TableColumn(field='TILEID', title='TILEID', width=80),
        bktables.TableColumn(field='RA', title='RA', formatter=colformat),
        bktables.TableColumn(field='DEC', title='DEC', formatter=colformat),
    ]

    for colname in ['STAR_DENSITY', 'EBV_MED']:
        if colname in tiledata:
            columns.append(
                bktables.TableColumn(field=colname,
                                     title=colname,
                                     formatter=colformat))

    columns.append(bktables.TableColumn(field='selected', title='Selected'))

    tiletable = bktables.DataTable(columns=columns, source=tiles, width=800)

    tiles.selected.js_on_change(
        'indices',
        CustomJS(args=dict(s1=tiles),
                 code="""
        var inds = cb_obj.indices;
        var d1 = s1.data;
        for (var i=0; i<d1['selected'].length; i++) {
            d1['selected'][i] = false;
        }
        for (var i = 0; i < inds.length; i++) {
            d1['selected'][inds[i]] = true;
        }
        s1.change.emit();
    """))

    render = p.circle(
        'RA',
        'DEC',
        source=tiles,
        size=9,
        line_color='chocolate',
        color=mapper,
        alpha=0.4,
        hover_color='orange',
        hover_alpha=1,
        hover_line_color='red',

        # set visual properties for selected glyphs
        selection_fill_color='orange',
        selection_line_color='white',
        # set visual properties for non-selected glyphs
        nonselection_fill_alpha=0.4,
        nonselection_fill_color=mapper)

    p.xaxis.axis_label = 'RA [deg]'
    p.yaxis.axis_label = 'Dec. [deg]'
    p.xaxis.axis_label_text_font_size = "14pt"
    p.yaxis.axis_label_text_font_size = "14pt"
    p.grid.grid_line_color = "gainsboro"
    p.yaxis.major_label_text_font_size = "12pt"
    p.xaxis.major_label_text_font_size = "12pt"

    p.x_range = Range1d(360, 0)
    p.y_range = Range1d(-40, 95)
    p.toolbar.logo = None
    p.toolbar_location = None

    # mytext = Label(x=180, y=-35, text="S", text_color='gray', text_font_size='12pt') ; p.add_layout(mytext)
    # mytext = Label(x=180, y=88, text="N", text_color='gray', text_font_size='12pt') ; p.add_layout(mytext)
    # mytext = Label(x=350, y=45, text="E", text_color='gray', text_font_size='12pt', angle=np.pi/2) ; p.add_layout(mytext)
    # mytext = Label(x=4, y=45, text="W", text_color='gray', text_font_size='12pt', angle=np.pi/2) ; p.add_layout(mytext)

    ## Javascript code to open up custom html pages, once user click on a tile
    code = """
        var index_selected = source.selected['1d']['indices'][0];
        var tileID = source.data['TILEID'][index_selected];
        if (tileID!==undefined) {
        var win = window.open("http://www.astro.utah.edu/~u6022465/cmx/ALL_SKY/dr8/allSKY_ci_tiles/sub_pages/tile-"+tileID+".html", " ");
        try {win.focus();} catch (e){} }
    """

    taptool = p.select(type=TapTool)
    taptool.callback = CustomJS(args=dict(source=tiles), code=code)

    ## The html code for the hover window that contain tile infrormation
    ttp = """
        <div>
            <div>
                <span style="font-size: 14px; color: blue;">Tile ID:</span>
                <span style="font-size: 14px; font-weight: bold;">@TILEID{int}</span>
            </div>
            <div>
                <span style="font-size: 14px; color: blue;">RA:</span>
                <span style="font-size: 14px; font-weight: bold;">@RA</span>
            </div>  
            <div>
                <span style="font-size: 14px; color: blue;">Dec:</span>
                <span style="font-size: 14px; font-weight: bold;">@DEC</span>
            </div>     
            <div>
                <span style="font-size: 14px; color: blue;">EBV_MED:</span>
                <span style="font-size: 14px; font-weight: bold;">@EBV_MED{0.000}</span>
            </div> 
            <div>
                <span style="font-size: 14px; color: blue;">STAR_DENSITY:</span>
                <span style="font-size: 14px; font-weight: bold;">@STAR_DENSITY{0}</span>
            </div> 
            <div>
                <span style="font-size: 14px; color: blue;">BRIGHTEST_STAR_VTMAG:</span>
                <span style="font-size: 14px; font-weight: bold;">@BRIGHTVTMAG</span>
            </div> 
            <div>
                <span style="font-size: 14px; color: blue;">BRIGHTEST_STAR_LOC:</span>
                <span style="font-size: 14px; font-weight: bold;">(@BRIGHTRA, @BRIGHTDEC)</span>
            </div> 
        </div>
    """

    hover = HoverTool(tooltips=ttp, renderers=[render])

    hover.point_policy = 'snap_to_data'
    hover.line_policy = 'nearest'
    # hover.mode='vline'
    p.add_tools(hover)

    cross = CrosshairTool()
    # cross.dimensions='height'
    cross.line_alpha = 0.3
    cross.line_color = 'gray'
    p.add_tools(cross)

    # Setting the second y axis range name and range
    p.extra_y_ranges = {"foo": p.y_range}
    p.extra_x_ranges = {"joo": p.x_range}

    # Adding the second axis to the plot.
    p.add_layout(LinearAxis(y_range_name="foo"), 'right')
    p.add_layout(LinearAxis(x_range_name="joo"), 'above')

    p.xaxis.major_label_text_font_size = "12pt"
    p.yaxis.major_label_text_font_size = "12pt"

    if dynamic:

        # twilight_source = get_kp_twilights(TT,DD)   # evening and morning twilights at every TT and DD
        circleSource_1 = skyCircle(TT, DD, 1.5)
        p.circle('RA', 'DEC', source=circleSource_1, size=1.5, color='black')
        circleSource_2 = skyCircle(TT, DD, 2.0)
        p.circle('RA', 'DEC', source=circleSource_2, size=0.5, color='gray')

    else:
        circleSource = skyCircle(TT, DD, 1.5)
        p.circle('RA', 'DEC', source=circleSource, size=1.5, color=None)

    ### Dealing with the Moon and Jupiter
    inFile = 'moonLoc_jupLoc_fracPhase.csv'  # 'moon_loc_jup_loc_fracPhase_namePhase.csv'
    tbl_moon_jup = np.genfromtxt(inFile,
                                 delimiter=',',
                                 filling_values=-1,
                                 names=True,
                                 dtype=None)  # , dtype=np.float)

    loc = EarthLocation.of_site('Kitt Peak')
    kp_lat = 31, 57, 48
    kp_lon = -111, 36, 00
    mooninfo_obj = pylunar.MoonInfo((kp_lat), (kp_lon))

    m_ra, m_dec, frac_phase, name_phase = moonLoc(TT, DD, loc, mooninfo_obj)
    j_ra, j_dec = jupLoc(TT, DD, loc)

    #moonSource = ColumnDataSource({"moon_RAS": tbl_moon_jup['moon_ra'], "moon_DECS": tbl_moon_jup['moon_dec'],
    #                               "Phase_frac": tbl_moon_jup['moon_phase_frac']})

    moonSource = ColumnDataSource({
        "moon_RAS":
        tbl_moon_jup['moon_ra'],
        "moon_DECS":
        tbl_moon_jup['moon_dec'],
        "Phase_frac":
        np.round(100 * tbl_moon_jup['moon_phase_frac'])
    })

    ####moon_RADEC = ColumnDataSource({"moon_ra": [m_ra.deg], "moon_dec": [m_dec.deg], "phase_frac": [frac_phase]})
    moon_RADEC_ = ColumnDataSource({
        "moon_ra": [m_ra.deg - 360],
        "moon_dec": [m_dec.deg],
        "phase_frac": [frac_phase]
    })
    moon_RADEC = ColumnDataSource({
        "moon_ra": [m_ra.deg],
        "moon_dec": [m_dec.deg],
        "phase_frac": [frac_phase]
    })

    render_moon = p.circle('moon_ra',
                           'moon_dec',
                           source=moon_RADEC,
                           size=170,
                           color='cyan',
                           alpha=0.2)
    render_moon = p.circle('moon_ra',
                           'moon_dec',
                           source=moon_RADEC,
                           size=4,
                           color='blue')

    render_moon = p.circle('moon_ra',
                           'moon_dec',
                           source=moon_RADEC_,
                           size=170,
                           color='cyan',
                           alpha=0.2)
    render_moon = p.circle('moon_ra',
                           'moon_dec',
                           source=moon_RADEC_,
                           size=4,
                           color='blue')

    jupSource = ColumnDataSource({
        "jup_RAS": tbl_moon_jup['jup_ra'],
        "jup_DECS": tbl_moon_jup['jup_dec']
    })
    jup_RADEC = ColumnDataSource({
        "jup_ra": [j_ra.deg],
        "jup_dec": [j_dec.deg]
    })

    twilight = get_kp_twilights(
        TT, DD)  # evening and morning twilights at every TT and DD
    twilight_source = ColumnDataSource({
        "eve_twilight": [twilight[0]],
        "mor_twilight": [twilight[1]]
    })

    render_jup = p.circle('jup_ra',
                          'jup_dec',
                          source=jup_RADEC,
                          size=5,
                          color='blue')
    render_jup = p.circle('jup_ra',
                          'jup_dec',
                          source=jup_RADEC,
                          size=4,
                          color='gold')

    from bokeh.models.glyphs import Text
    TXTsrc = ColumnDataSource(
        dict(x=[350],
             y=[85],
             text=['Moon Phase: ' + "%.0f" % (frac_phase * 100) + "%"]))
    glyph = Text(x="x", y="y", text="text", angle=0, text_color="black")
    p.add_glyph(TXTsrc, glyph)

    TXTsrc_moon = ColumnDataSource(
        dict(x=[m_ra.deg + 10], y=[m_dec.deg - 10], text=['Moon']))
    glyph = Text(x="x",
                 y="y",
                 text="text",
                 angle=0,
                 text_color="blue",
                 text_alpha=0.3,
                 text_font_size='10pt')
    p.add_glyph(TXTsrc_moon, glyph)

    TXTsrc_jup = ColumnDataSource(
        dict(x=[j_ra.deg + 5], y=[j_dec.deg - 8], text=['Jup.']))
    glyph = Text(x="x",
                 y="y",
                 text="text",
                 angle=0,
                 text_color="black",
                 text_alpha=0.3,
                 text_font_size='10pt')
    p.add_glyph(TXTsrc_jup, glyph)

    callback = CustomJS(args=dict(source_sky1=circleSource_1,
                                  source_sky2=circleSource_2,
                                  source_moon=moonSource,
                                  source_moon_RADEC=moon_RADEC,
                                  source_moon_RADEC_=moon_RADEC_,
                                  source_jup=jupSource,
                                  source_jup_RADEC=jup_RADEC,
                                  sourceTXT=TXTsrc,
                                  sourceTXTmoon=TXTsrc_moon,
                                  sourceTXTjup=TXTsrc_jup),
                        code="""
                // First set times as if they were UTC
                var t = new Date(time_slider.value);
                var d = new Date(date_slider.value);
                var data1 = source_sky1.data;
                var ra_1 = data1['RA'];
                var ra0_1 = data1['RA0'];
                
                var data2 = source_sky2.data;
                var ra_2 = data2['RA'];
                var ra0_2 = data2['RA0'];
                
                var data_moon = source_moon.data;
                var ras_moon = data_moon['moon_RAS'];
                var decs_moon = data_moon['moon_DECS'];
                var phase_frac = data_moon['Phase_frac'];
                
                var moonRADEC = source_moon_RADEC.data;
                var moon_ra = moonRADEC['moon_ra'];
                var moon_dec = moonRADEC['moon_dec'];
     
                var moonRADEC_ = source_moon_RADEC_.data;
                var moon_ra_ = moonRADEC_['moon_ra'];
                var moon_dec_ = moonRADEC_['moon_dec'];
                
                var data_jup = source_jup.data;
                var ras_jup = data_jup['jup_RAS'];
                var decs_jup = data_jup['jup_DECS'];
                
                var jupRADEC = source_jup_RADEC.data;
                var jup_ra = jupRADEC['jup_ra'];
                var jup_dec = jupRADEC['jup_dec'];


                var Hour  = t.getUTCHours();
                var Day   = d.getDate();
                var Month = d.getMonth();
                
                var Year = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
                var all_FULdays = 0;
                for (var i = 0; i < Month; i++)
                    all_FULdays=all_FULdays+Year[i];
                all_FULdays = all_FULdays + (Day-1);
                
                if (Hour<12) all_FULdays=all_FULdays+1;
                
                var all_minutes = all_FULdays*24+Hour;
                
                if (all_minutes<8800) {
                    moon_ra[0] = ras_moon[all_minutes];
                    moon_dec[0] = decs_moon[all_minutes];   
                    moon_ra_[0] = ras_moon[all_minutes]-360.;
                    moon_dec_[0] = decs_moon[all_minutes];   
                                        
                }


                var jupTXTdata = sourceTXTjup.data;
                var x_jup = jupTXTdata['x'];
                var y_jup = jupTXTdata['y'];
                var text_jup = jupTXTdata['text'];  
                
                
                if (all_minutes<8800) {
                    jup_ra[0] = ras_jup[all_minutes];
                    jup_dec[0] = decs_jup[all_minutes];   
                    x_jup[0] = jup_ra[0]+5;
                    y_jup[0] = jup_dec[0]-8;                     
                }
                 
                                
                if (t.getUTCHours() < 12) {
                    d.setTime(date_slider.value + 24*3600*1000);
                } else {
                    d.setTime(date_slider.value);
                }
                d.setUTCHours(t.getUTCHours());
                d.setUTCMinutes(t.getUTCMinutes());
                d.setUTCSeconds(0);        
                
                // Correct to KPNO local time
                // d object still thinks in UTC, which is 7 hours ahead of KPNO
                d.setTime(d.getTime() + 7*3600*1000);
                // noon UT on 2000-01-01
                var reftime = new Date();
                reftime.setUTCFullYear(2000);
                reftime.setUTCMonth(0);   // Months are 0-11 (!)
                reftime.setUTCDate(1);    // Days are 1-31 (!)
                reftime.setUTCHours(12);
                reftime.setUTCMinutes(0);
                reftime.setUTCSeconds(0);
                
                // time difference in days (starting from milliseconds)
                var dt = (d.getTime() - reftime.getTime()) / (24*3600*1000);

                // Convert to LST
                var mayall_longitude_degrees = -(111 + 35/60. + 59.6/3600);
                var LST_hours = ((18.697374558 + 24.06570982441908 * dt) + mayall_longitude_degrees/15) % 24;
                var LST_degrees = LST_hours * 15;
                
                

                for (var i = 0; i < ra_1.length; i++) {
                    ra_1[i] = (ra0_1[i] + LST_degrees) % 360;
                }
                
                for (var i = 0; i < ra_2.length; i++) {
                    ra_2[i] = (ra0_2[i] + LST_degrees) % 360;
                }                

                //// Here we gtake care of the moon phasde text
                var TXTdata = sourceTXT.data;
                var x = TXTdata['x'];
                var y = TXTdata['y'];
                var text = TXTdata['text'];
                
                var moonTXTdata = sourceTXTmoon.data;
                var x_moon = moonTXTdata['x'];
                var y_moon = moonTXTdata['y'];
                var text_moon = moonTXTdata['text'];   

                // x[0] = 1;
                // y[0] = 40;
                if (all_minutes<8800) {
                    text[0] = 'Moon Phase: ' + phase_frac[all_minutes]+'%';
                    x_moon[0] = moon_ra[0]+10;
                    y_moon[0] = moon_dec[0]-10;
                }

                sourceTXT.change.emit();
                /////////////////////////////// Moon phase code ends.

                source_sky1.change.emit();
                source_sky2.change.emit();
                //source_moon_RADEC.change.emit();
                //source_moon_RADEC_.change.emit();
                //source_jup_RADEC.change.emit();
                sourceTXTmoon.change.emit();
                sourceTXTjup.change.emit();

                //alert(d);
    """)

    if dynamic:
        ### TIME
        Timeslider = DateSlider(start=dt(2019, 9, 1, 16, 0, 0),
                                end=dt(2019, 9, 2, 8, 0, 0),
                                value=dt(2019, 9, 1, 16, 0, 0),
                                step=1,
                                title="KPNO local time(hh:mm)",
                                format="%H:%M",
                                width=800)

        ## DATE
        Dateslider = DateSlider(start=dt(2019, 9, 1, 16, 0, 0),
                                end=dt(2020, 8, 31, 8, 0, 0),
                                value=dt(2019, 10, 1, 16, 0, 0),
                                step=1,
                                title="Date of sunset(4pm-8am)",
                                format="%B:%d",
                                width=800)

        callback.args['time_slider'] = Timeslider
        callback.args['date_slider'] = Dateslider

        Dateslider.js_on_change('value', callback)
        Timeslider.js_on_change('value', callback)

        layout = column(p, Dateslider, Timeslider, tiletable)
        # show(p)
        return layout

    return p
Example #8
0
#! /usr/bin/python3

import datetime
import pylunar

#import pytz
location = {'lat': (17, 30, 5), 'lon': (-88, 12, 12)}
location_name = 'Belize City'

# pylunar takes UTC time as a tuple
UTC_now = datetime.datetime.utcnow()

observation_time = (UTC_now.year, UTC_now.month, UTC_now.day, UTC_now.hour,
                    UTC_now.minute, UTC_now.second)

mi = pylunar.MoonInfo(location['lat'], location['lon'])

mi.update(observation_time)

now = datetime.datetime.now()

print(f'Observation time: {now:%Y-%m-%d %H:%M}')

print(f'Moon age: {mi.age():0.2f} days')

print(f'Moon phase: {(mi.fractional_phase())*100.0:0.2f} %')

print(f'Moon phase name: {mi.phase_name()}')

print(f'Azimuth: {mi.azimuth():0.2f}')
Example #9
0
import pylunar, datetime

# City lati/long in DMS format
TEHRAN_LAT = (35, 41, 21.308)
TEHRAN_LONG = (51, 23, 22.561)


def get_shape_moon(phase):
    """
    get shape of moon by passing phase

    :phase: current moon phase
    :return: string contain shape of moon
    """
    with open('moon.txt', 'r') as file:
        lines = file.readlines()
        index = [lines.index(line) for line in lines if phase in line][0]
        return ''.join(lines[index - 2:index + 4])


moon = pylunar.MoonInfo(TEHRAN_LAT, TEHRAN_LONG)
today = datetime.datetime.now()

moon.update((today.year, today.month, today.day, today.hour, today.minute, 0))

# normalize the phase name by removing '_'
phase = moon.phase_name().replace('_', ' ')

print(get_shape_moon(phase))
Example #10
0
start_day = str(start_day).split(" ")[0].replace("-", "")
end_day = str(end_day).split(" ")[0].replace("-", "")

# Get the tidal data.
url = f"https://opendap.co-ops.nos.noaa.gov/axis/webservices/predictions/response.jsp?stationId={args.s}&" \
    f"beginDate={start_day}&endDate={end_day}&datum=MLLW&unit=0&timeZone=0&dataInterval=60&format=text&Submit=Submit"
resp = get(url).content.decode("utf-8")

print(f"Got tidal data for station {args.s}")
# Get the longitude and latitude.
latitude = re.search(r"\s+Latitude\s+:\s+(.*)", resp).group(1)
latitude = (int(latitude.split(".")[0]), int(latitude[-4:]), int(latitude[-2:]))
longitude = re.search(r"\s+Longitude\s+:\s+(.*)", resp).group(1)
longitude = (int(longitude.split(".")[0]), int(longitude[-4:]), int(longitude[-2:]))
# Load the lunar data.
mi = pylunar.MoonInfo(latitude, longitude)
mi_start = (int(start_day[:4]), int(start_day[4:6]), int(start_day[6:8]), 0, 0, 0)
mi.update(mi_start)
print("Got the lunar data.")

tidal_data = resp.split("<pre>")[-1].replace("</pre>", "")

# The months of the Aquatic Jewish calendar.
MONTHS = ["Tishrei", "Kheshvan", "Kislev", "Tevet", "Shvat", "Adar", "Nisan", "Iyar", "Sivan", "Tammuz", "Av", "Elul"]
# The days of the Aquatic Jewish week.
DAYS_OF_WEEK = ["Dag", "Gal", "Khof", "Zerem", "Ruakh", "Melakh", "Shabbat"]
# LaTeX symbols for printing the moon phase. If the phase isn't one of the quarters, then no symbol is printed.
MOON_PHASES = [r"\CIRCLE", r"\LEFTcircle", r"\Circle", r"\RIGHTcircle", r""]
# Index of the current month.
current_month_index = -1
# The current day of the month.
Example #11
0
def update():
    # current time
    cur_datetime = datetime.datetime.now()
    cur_utc_tm_info = time.gmtime()
    print("update at %s" % datetime.datetime.now())

    # loop over all channels
    for c, channel in enumerate(settings['channels']):

        print("   channel %d, %s" % (c, channel["name"]))

        # no update of the percentage in manual mode
        if channel['manual']:
            print("    manual mode, no update")
            pwm = channel["pwm"]

        # normal channel (new percentage calculated via interpolation of the data_points)
        if not channel['manual'] and not channel['moonlight']:

            # normal channel
            # new percentage updated via linear interpolation of the data_points
            print("    regular channel")

            # first load percentage and time values into the lists datetime_list and percentage_list
            datetime_list, pwm_list = [], []
            for i in channel["data_points"]:
                # list of datetime.datetime values
                datetime_list.append(
                    datetime.datetime.combine(
                        cur_datetime.date(),
                        datetime.time(*map(int, i[0].split(':')))))
                # list of % values
                pwm_list.append(float(i[1]))

            # periodic boundary conditions, so one interpolate between the last time of the day and the first time of the next day
            datetime_list.append(datetime_list[0] + datetime.timedelta(days=1))
            pwm_list.append(pwm_list[0])
            datetime_list.insert(
                0, datetime_list[-2] - datetime.timedelta(days=1))
            pwm_list.insert(0, pwm_list[-2])

            # searches the two times the current time is inbetween and interpolates linear the pwm value
            for i in range(len(datetime_list) - 1):
                if datetime_list[i] < cur_datetime < datetime_list[i + 1]:
                    pwm = pwm_list[i]
                    pwm += (pwm_list[i + 1] - pwm_list[i]) * (
                        (cur_datetime - datetime_list[i]) /
                        (datetime_list[i + 1] - datetime_list[i]))

        # moonlight channel
        # calc current brightness of the moon
        # percentage is max_moonlight_percentage times moonlight_brightness in percent
        if not channel['manual'] and channel['moonlight']:
            print("    moonlight channel")
            # create moonlight object using the location
            moon = pylunar.MoonInfo(latitude=tuple(settings['latitude']),
                                    longitude=tuple(settings['longitude']))
            # feed time (utc time required)
            moon.update((cur_utc_tm_info.tm_year, cur_utc_tm_info.tm_mon,
                         cur_utc_tm_info.tm_mday, cur_utc_tm_info.tm_hour,
                         cur_utc_tm_info.tm_min, cur_utc_tm_info.tm_sec))
            # ratio of the illuminated part of the moon
            fractional_phase = moon.fractional_phase()
            print("    fractional phase: %.3f" % (fractional_phase))
            # hight of the moon at your location
            altitude = moon.altitude()
            print("    altitude: %.3f°" % (altitude))

            pwm = float(channel["max_moonlight_pwm"]
                        ) * fractional_phase * math.sin(altitude)
            # if moon is not visible -> percentage = 0
            if pwm < 0:
                pwm = 0

        # update percentage in the settings
        settings['channels'][c]['pwm'] = pwm
        print("    pwm: %.3f" % pwm)

    # calculate current power
    settings['power'] = 0
    for channel in settings['channels']:
        settings['power'] += channel['max_power'] * channel['pwm']
    print('  power [watt]: %.2f' % settings['power'])
    print()
Example #12
0
def main(year, month, day, body='moon'):

    #find alt-az between observer and waterfall
    lib = Geodesic.WGS84.Inverse(observer[0], observer[1], target[0],
                                 target[1])
    az_obs_targ = np.radians(
        lib['azi1'])  #azimuth in radians. Geodesic returns degrees
    if az_obs_targ < 0: az_obs_targ += 2 * np.pi  #no negative azimuths
    d = lib['s12']  #distance
    alt_obs_targ = np.arctan2(
        target[2] - observer[2],
        d)  #altitude of target as viewed by observer, radians

    print("The distance, elevation, az, alt from observer to the waterfall is: " + \
        str(int(round(d))) + ' m, ' + str(int(round(target[2]-observer[2]))) + ' m, ', \
        str(round(np.degrees(az_obs_targ), 1)) + '°, ' + str(round(np.degrees(alt_obs_targ), 1)) + '°.')
    print()

    #initialize dates and ephemeris parameters
    date_pst = ephem.Date(
        str(year) + '/' + str(month) + '/' + str(day) +
        ' 0:00')  #midnight local time on date
    date_utc = ephem.date(
        date_pst - timezone_offset * ephem.hour)  #UTC of midnight local time

    me = ephem.Observer()
    me.lon = str(observer[1])
    me.lat = str(observer[0])
    me.elevation = observer[2]
    me.temp = 5  #deg C
    me.pressure = 12.2 / 14.7 * 1000  #mbar
    me.date = ephem.date(date_utc)

    #get sunrise/sunset/moonrise/moonset times
    sun = ephem.Sun()
    sunrise = me.next_rising(sun)
    sunset = me.next_setting(sun)
    moon = ephem.Moon()
    moonrise = me.next_rising(moon)
    moonset = me.next_setting(moon)

    print("On " + str(datetime.strftime(date_pst.datetime(), '%a %b %d %Y')) + \
        ", sunrise occurs at " + str(datetime.strftime(ephem.date(sunrise+timezone_offset* ephem.hour).datetime(), '%X')) + \
        " and sunset occurs at " + str(datetime.strftime(ephem.date(sunset+timezone_offset* ephem.hour).datetime(), '%X'))+' local time.')
    print("Moonrise occurs at " + str(datetime.strftime(ephem.date(moonrise+timezone_offset* ephem.hour).datetime(), '%X')) + \
        " and moonset occurs at " + str(datetime.strftime(ephem.date(moonset+timezone_offset* ephem.hour).datetime(), '%X'))+' local time.')
    print()

    #initialize moon object to get the phase later
    mi = pylunar.MoonInfo([round(observer[0]), round((observer[0] - np.floor(observer[0]))*60.), 0], \
                          [round(observer[1]), round((observer[1] - np.floor(observer[1]))*60.), 0] )

    #initize booleans to guide later code flow
    moonbow_occurring = False
    moonbow_occurred = False

    #Now do a for loop over each minute in the 24 hours of the date given to see if/when moonbows occur
    for time_offset in np.arange(0, 24 * 60, 1):
        me.date = ephem.date(date_utc + time_offset * ephem.minute)

        if (body.lower() == 'moon'):  #Are we interested in moonbows?
            if (me.date > sunrise) & (
                    me.date <
                    sunset):  #if daytime, skip to next loop iteration
                continue
            v = ephem.Moon(me)
            bowtype = 'moon'
            body = 'moon'
        elif (body.lower() == 'sun'):  #Are we interested in rainbows?
            if (me.date < sunrise) | (
                    me.date >
                    sunset):  #if nighttime, skip to next loop iteration
                continue
            v = ephem.Sun(me)
            bowtype = 'rain'
            body = 'sun'
        else:  #The user was ham-fisted and mis-typed something
            print("Set body='moon' or body='sun'. Cannot continue.")
            return

        m_alt = v.alt  #radians
        m_az = v.az  #radians

        if m_alt < 0:  #if the moon is below the horizon, you're not getting a moonbow.
            continue  #skip to next minute

        #The relevant vector for calculating moonbows is directly opposite the vector from the observer to the moon.
        m_alt_opp = -1. * m_alt  #moonbow is opposite the moon
        m_az_opp = m_az + np.pi

        #calculate angle between (observer to waterfall vector) and (observer to opposite moon ray vectors)
        angle = ephem.separation(
            (az_obs_targ, alt_obs_targ),
            (m_az_opp,
             m_alt_opp))  #saves me from doing a cross product and dot product

        #print(ephem.date(date_pst + time_offset * ephem.minute), np.degrees([angle, m_alt_opp, m_az_opp])
        if np.abs(
                41.5 - np.degrees(angle)
        ) < mist_radius:  #Is a moonbow occuring now? Moon/rainbows form ~41.5* circles
            if not moonbow_occurring:  #is this the first minute of the moonbow?
                moonbow_occurred = True
                moonbow_occurring = True
                print('A ' + bowtype + 'bow begins at ' + str(
                    datetime.strftime(
                        ephem.date(date_pst + time_offset *
                                   ephem.minute).datetime(), '%X')) + '.')
                mi.update(
                    ephem.date(date_utc +
                               time_offset * ephem.minute).datetime())
                print('The ' + body + ' is at az, alt: ' +
                      str(round(np.degrees(m_az), 1)) + ', ' +
                      str(round(np.degrees(m_alt), 1)) + '.')
                print("The moon has a phase of " +
                      str(int(round(mi.fractional_phase() * 100.))) + '%.')

        else:  #moonbow is not occurring at this minute
            if moonbow_occurring:  #but moonbow occurred the previous minute
                print('The ' + bowtype + 'bow ends at ' + str(
                    datetime.strftime(
                        ephem.date(date_pst + time_offset *
                                   ephem.minute).datetime(), '%X')) + '.')
                print('The ' + body + ' is at az, alt: ' +
                      str(round(np.degrees(m_az), 1)) + ', ' +
                      str(round(np.degrees(m_alt), 1)) + '.')
                print()
                moonbow_occurring = False

    if not moonbow_occurred:  #if nothing happened on this date
        print("No " + bowtype + "bow occurred on this day.")
        print()
                          (25 / 100)):
        return 'New Moon'
    elif (fractional_phase >= length_of_lunar_cycle *
          (25 / 100)) and (fractional_phase < length_of_lunar_cycle *
                           (50 / 100)):
        return 'First Quarter'
    elif (fractional_phase >= length_of_lunar_cycle *
          (50 / 100)) and (fractional_phase < length_of_lunar_cycle *
                           (75 / 100)):
        return 'Full Moon'
    elif (fractional_phase >= length_of_lunar_cycle * (75 / 100)):
        return 'Last Quarter'


# Detroit
mi = pylunar.MoonInfo((42, 19, 53), (-83, 2, 45))

moon_phase = []
moon_fraction = []

for index, row in df.iterrows():

    date_year = row['Order Date'].year
    date_month = row['Order Date'].month
    date_day = row['Order Date'].day
    mi.update((date_year, date_month, date_day, 12, 0, 0))
    fractional_phase = mi.age()
    moon_phase.append(translate_moon_phase(fractional_phase=fractional_phase))
    moon_fraction.append(fractional_phase)

df['Moon Phase'] = moon_phase
Example #14
0
def get_moon_info(x):
    if isinstance(x, datetime) == True:
        # convert datetime to string
        x_str = x.strftime("%Y-%m-%d %H:%M:%S")

        # slice string to use in pylunar function
        year = int(x_str[0:4])
        mes = int(x_str[5:7])
        day = int(x_str[8:10])
        hr = int(x_str[11:13])
        min = int(x_str[14:16])
        sec = int(x_str[17:19])

        # call pylunar MoonInfo function with correct coordinates
        moon = pylunar.MoonInfo((37, 32, 10.82), (-77, 27, 24.85))
        # use the current date in UTC format
        moon.update((year, mes, day, hr, min, sec))

        # moon phase:
        print(moon.phase_name())
        fp_now = moon.fractional_phase()
        print('{:.1%}'.format(fp_now) + ' full')

        # age since last new moon
        age = moon.age()
        print('{:.2}'.format(age) + ' days since last New Moon')

        # get the local rising and setting times
        rise_set = moon.rise_set_times('US/Eastern')  # list

        # have to slice through list
        for i in range(3):
            if 'rise' in rise_set[i]:
                rise = rise_set[i]
                rise_time = rise[1]  #0th in list is the label

                # create datetime, will be naive
                rise_dt = datetime(rise_time[0], rise_time[1], rise_time[2],
                                   rise_time[3], rise_time[4], rise_time[5])

                # make datetime aware of local time zone
                rise_dt = eastern.localize(rise_dt)
                rise_dt_str = rise_dt.strftime("%Y-%m-%d %H:%M:%S")

                # compare rising time to current time
                if rise_dt > now:
                    print('The Moon will rise today at: ' + rise_dt_str)
                elif rise_dt < now:
                    print('The Moon rose today at: ' + rise_dt_str)
                else:
                    print('It seems that the Moon is rising right now!')

            elif 'set' in rise_set[i]:
                set = rise_set[i]
                set_time = set[1]  #0th in list is the label

                # create datetime, will be naive
                set_dt = datetime(set_time[0], set_time[1], set_time[2],
                                  set_time[3], set_time[4], set_time[5])

                # make datetime aware of local time zone
                set_dt = eastern.localize(set_dt)
                set_dt_str = set_dt.strftime("%Y-%m-%d %H:%M:%S")

                # compare setting time to current time
                if set_dt > now:
                    print('The Moon will set today at: ' + set_dt_str)
                elif set_dt < now:
                    print('The Moon set today at: ' + set_dt_str)
                else:
                    print('It seems that the Moon is setting right now!')

            # we don't care about the transit times
            elif 'transit' in rise_set[i]:
                pass

    else:
        print('Something has gone wrong with the datetime verification!')