Exemplo n.º 1
0
class EarthSatellitePlus(ephem.EarthSatellite):
	"""
	Sub-class of the ephem.EarthSatellite class that adds in additional
	information about the magnitude of the satellite.
	
	.. note::  The 'bearing' attribute is only computed relative to the 
	the previous call to compute().  This field is only useful during 
	tracking operations.
	"""
	
	# Rising/setting
	rising = False
	
	# Bearing information
	bearing = 0.0
	_lastRA = None
	_lastDec = None
	_lastAlt = None
	
	# Magnitude information
	stdMag = 99.0
	_sol = ephem.Sun()
	magnitude = 99.0
	
	# Signal loss information
	_nextSet = None
	los = 0.0
	
	def compute(self, observer):
		"""
		Wrapper around ephem.EarthSatellite.compute() function that 
		adds in visibility, magntiude, and satellite bearing 
		computations.
		"""
		
		## Save the 
		try:
			self._lastRA, self._lastDec, self._lastAlt = self.ra, self.dec, self.alt
		except (RuntimeError, AttributeError):
			self._lastRA, self._lastDec, self._lastAlt = None, None, None
			
		## Locate the satellite
		ephem.EarthSatellite.compute(self, observer)
		
		## Compute the location of the Sun so that we can estimate the 
		## brightness of the satellite.
		self._sol.compute(observer)
		B = math.pi - ephem.separation(self._sol, self)
		self.magnitude = self.stdMag - 15.0 + 5.0*math.log10(self.range/1e3)
		self.magnitude -= 2.5*math.log10( math.sin(B) + (math.pi-B)*math.cos(B) )
		if self.magnitude >= 15.0 or self.eclipsed:
			self.magnitude = 15.0
			
		## Calculate the bearing if this is not the first time
		## that we have tried
		try:
			self.bearing = getBearingFromPoint(self._lastRA, self._lastDec, self.ra, self.dec)[0]
			self.rising = True if self.alt > self._lastAlt else False
		except (ValueError, TypeError):
			self.bearing = 0.0
			
		## Calculate how long before we expect to lose the satellite
		if self.alt > 0:
			if self._nextSet is None:
				try:
					event = observer.next_pass(self)
					self._nextSet = event[4]
					if self._nextSet is None:
						self._nextSet = observer.date - 1.0
						
				except ValueError:
					self._nextSet = observer.date + 1.0
					
			self.los = (self._nextSet-observer.date)*86400.0
			
		else:
			self._nextSet = None
			self.los = 0.0
		
	def setStdMag(self, stdMag):
		"""
		Set the "standard magnitude" for this satellite to use for 
		brightness calculations.
		"""
		
		self.stdMag = stdMag
		
	def fillFromPyEphem(self, sat):
		"""
		Initialize this instance using an existing 
		ephem.EarthSatellite instance.
		"""
		
		for attr in ('name', 'catalog_number', '_epoch', '_n', '_orbit', '_drag', '_decay', '_e'):
			setattr(self, attr, getattr(sat, attr, None))
		for attr in ('_inc', '_raan', '_ap', '_M'):
			setattr(self, attr, getattr(sat, attr, None)*_rad2deg)
Exemplo n.º 2
0
def calcAlmucantarPrinciplePlanes(latitude,
                                  longitude,
                                  capture_time,
                                  almucantar_angles=None,
                                  principleplane_angles=None,
                                  img_resolution=301,
                                  alm_resolution=72,
                                  pp_resolution=38):
    """Calculate the Almucantar and PrinciplePlanes for a specific
    localization, datetime.

    Args:
        almucantar_angles (array like): Sampling angles (degrees) along
            Almucantar.
        principleplane_angles (array like): Sampling angles (degrees) along
            PrinciplePlane.

    Note:
         In practice the Almucantar and PrinciplePlane are measured in
         different times. So this function should be called twice for each
         with its own capture time.
    """

    #
    # Create an Sun/observer at camera position
    #
    observer = ephem.Observer()
    observer.lat, observer.long, observer.date = \
        str(latitude), str(longitude), capture_time

    sun = ephem.Sun(observer)

    #
    # Calculate Almucantar angles.
    # Almucantar samples at the altitude of the sun at differnt Azimuths.
    #
    start_az = sun.az
    if almucantar_angles is None:
        #
        # Sample uniformly along Almucantar angles.
        #
        almucantar_angles = np.linspace(0, 360, alm_resolution, endpoint=False)
        alm_az = np.linspace(start_az,
                             start_az + 2 * np.pi,
                             alm_resolution,
                             endpoint=False)
    else:
        alm_az = np.radians(almucantar_angles) + start_az
    alm_alts = sun.alt * np.ones(len(alm_az))

    #
    # Convert Almucantar angles to image coords.
    #
    alm_radius = (np.pi / 2 - alm_alts) / (np.pi / 2)
    alm_x = (alm_radius * np.sin(alm_az) + 1) * img_resolution / 2
    alm_y = (alm_radius * np.cos(alm_az) + 1) * img_resolution / 2
    Almucantar_coords = np.array((alm_x, alm_y))

    #
    # Calculate PrinciplePlane coords.
    #
    start_alt = sun.alt
    if principleplane_angles is None:
        #
        # Sample uniformly along Almucantar angles.
        #
        principleplane_angles = np.linspace(0,
                                            360,
                                            pp_resolution,
                                            endpoint=False)
        pp_alts = np.linspace(0, np.pi, pp_resolution, endpoint=False)
    else:
        pp_alts = np.radians(principleplane_angles) + start_alt
    pp_az = sun.az * np.ones(len(pp_alts))

    #
    # Convert Principal Plane angles to image coords.
    #
    pp_radius = (np.pi / 2 - pp_alts) / (np.pi / 2)
    pp_x = (pp_radius * np.sin(pp_az) + 1) * img_resolution / 2
    pp_y = (pp_radius * np.cos(pp_az) + 1) * img_resolution / 2
    PrincipalPlane_coords = np.array((pp_x, pp_y))

    return Almucantar_coords, PrincipalPlane_coords, \
           almucantar_angles, principleplane_angles
    def __init__(self):
        ChimeraObject.__init__(self)

        self._sun = ephem.Sun()
        self._moon = ephem.Moon()
Exemplo n.º 4
0
# ------------------------------------------------------------------------------------------------------------------- #
telescope = ephem.Observer()
telescope.pressure = 0
telescope.lon = OBS_LONG
telescope.lat = OBS_LAT
telescope.elevation = OBS_ALT
telescope.epoch = ephem.J2000
telescope.date = (Time(date_obs) + 1 * u.day -
                  abs(OBS_TIMEZONE) * u.hour).utc.datetime
# ------------------------------------------------------------------------------------------------------------------- #

# ------------------------------------------------------------------------------------------------------------------- #
# Calculation Of Times Of Local Sunset & Sunrise
# ------------------------------------------------------------------------------------------------------------------- #
telescope.horizon = '-0:34'
time_sunset = telescope.previous_setting(ephem.Sun(), use_center=True)
time_sunrise = telescope.next_rising(ephem.Sun(), use_center=True)

datetime_sunset = Time(
    datetime.strptime(str(time_sunset).split('.')[0], '%Y/%m/%d %H:%M:%S'))
datetime_sunrise = Time(
    datetime.strptime(str(time_sunrise).split('.')[0], '%Y/%m/%d %H:%M:%S'))
# ------------------------------------------------------------------------------------------------------------------- #

# ------------------------------------------------------------------------------------------------------------------- #
# Calculation Of Times Of Nautical Twilight [Elevation Of Sun = -12 Degrees]
# ------------------------------------------------------------------------------------------------------------------- #
telescope.horizon = '-12'
time_twildusk = telescope.previous_setting(ephem.Sun(), use_center=True)
time_twildawn = telescope.next_rising(ephem.Sun(), use_center=True)
Exemplo n.º 5
0
        # moon.phase is % of moon that is illuminated
        moon_pct = moon.moon_phase
        # calculate distance from target
        moon_sep = ephem.separation(moon, body)
        moon_sep = math.degrees(float(moon_sep))
        return (moon_alt, moon_pct, moon_sep)

    def calc_separation_alt_az(self, body):
        """Compute deltas for azimuth and altitude from another target"""
        self.body.compute(self.site)
        body.body.compute(self.site)

        delta_az = float(self.body.az) - float(target.az)
        delta_alt = float(self.body.alt) - float(target.alt)
        return (delta_alt, delta_az)


Moon = SSBody('Moon', ephem.Moon())
Sun = SSBody('Sun', ephem.Sun())
Mercury = SSBody('Mercury', ephem.Mercury())
Venus = SSBody('Venus', ephem.Venus())
Mars = SSBody('Mars', ephem.Mars())
Jupiter = SSBody('Jupiter', ephem.Jupiter())
Saturn = SSBody('Saturn', ephem.Saturn())
Uranus = SSBody('Uranus', ephem.Uranus())
Neptune = SSBody('Neptune', ephem.Neptune())
Pluto = SSBody('Pluto', ephem.Pluto())


#END
Exemplo n.º 6
0
 def previous_sunset(self, date=None):
     obs = self.copy()
     if date: obs.date = ephem.Date(date)
     obs.horizon = self.twilight
     return obs.next_setting(ephem.Sun(), use_center=True)
Exemplo n.º 7
0
    def time(self, cluster, date=None, verbose=False):

        izana = ephem.Observer()
        if date is None:
            date = ephem.Date('2015/8/2 00:00:00')
        izana.date = date  # '2015/03/19 00:00:00'
        izana.lat = '28.301195'
        izana.lon = '-16.509209'
        izana.horizon = '-0:34'
        # izana.elevation = 2096
        sun = ephem.Sun(izana)  # @UndefinedVariable
        c = SkyCoord(cluster['ra'], cluster['dec'], frame='icrs', unit=(u.deg, u.deg))  # @UndefinedVariable
        rastr = c.ra.to_string(unit=u.hour, sep='::')  # @UndefinedVariable
        decstr = c.dec.to_string(unit=u.deg, sep='::')  # @UndefinedVariable
        ephemstr = '%s,f|O,%s,%s, 5.,2000' % (cluster['name'], rastr, decstr)
        clusterephem = ephem.readdb(ephemstr)
        eventlist = []
        # set airmass 2.0 
        izana.horizon = '30:00'
        clusterephem.compute(izana)
        cnrise = izana.next_rising(clusterephem)
        cnset = izana.next_setting(clusterephem)
        cprise = izana.previous_rising(clusterephem)
        cpset = izana.previous_setting(clusterephem)
        eventlist.append([self._eph2dt(cnrise), 'cluster rise (next)'])
        eventlist.append([self._eph2dt(cnset), 'cluster set (next)'])
        eventlist.append([self._eph2dt(cprise), 'cluster rise (prev)'])
        eventlist.append([self._eph2dt(cpset), 'cluster set (prev)'])

        # set astronomical dawn
        izana.horizon = '-19:00'
        spset = izana.previous_setting(sun)
        snrise = izana.next_rising(sun)
        eventlist.append([self._eph2dt(snrise), 'sunrise'])
        eventlist.append([self._eph2dt(spset), 'sunset'])

        eventlist.sort()
        sundown = False
        clusterup = False
        t0, t1 = None, None

        for t, e in eventlist:
            if verbose: print(t, e)
            if e == 'sunset':
                sundown = True
                if clusterup:
                    t0 = t

            if e == 'sunrise':
                sundown = False
                if clusterup:
                    t1 = t

            if e == 'cluster rise (next)' or \
                    e == 'cluster rise (prev)':
                clusterup = True
                if sundown: t0 = t
            if e == 'cluster set (next)' or \
                    e == 'cluster set (prev)':
                clusterup = False
                if sundown: t1 = t

        if verbose: print(t0, t1)
        if t0 is None and t1 is None:
            return 0.0
        return (ephem.Date(t1) - ephem.Date(t0)) * 24.0
Exemplo n.º 8
0
def dusk_dawn_utc(datetime_utc,
                  latitude_column=None,
                  longitude_column=None,
                  temperature_column=None,
                  elevation_column=None,
                  air_pressure_column=None,
                  latitude_const='49.088964',
                  longitude_const='20.070236',
                  temperature_const=0,
                  elevation_const=952,
                  air_pressure_const=1010,
                  twilight_const='-6',
                  horizon_const='-0:34',
                  duration=False):
    '''
    dusk_dawn_utc will give you the categories (strings) "night", "dusk", "day", "dawn" based on the variables
    and optionally with the duration is a second variable.  
    The input time must be in UTC 

    Args:
        datetime_utc,          the column name containing the UTC time of the observation

        If the *_column variables are not provided than it is assumed that these values are provides as constant 
        for all observations 
        latitude_column:       the column name containing the latitude of the observation  
        longitude_column:      the column name containing the longitude of the observation
        temperature_column:    the temperature in degrees celcius at the moment of the observation at the 
                               location of the observation
        elevation_column:      the column name containing the number of meters above sealevel of the location of 
                               the observation 
        air_pressure_column:   the column name containing the air preassure at the moment of the observation on the 
                               location


        In case the variables are not present at the observation these values are provides as constant for 
        all observations
        latitude_cons          the latitude of the observation  
        longitude_const        the longitude of the observation
        temperature_const:     the temperature in degrees celcius at the moment of the observation
        elevation_const        the number of meters above sealevel of the observation
        air_pressure_const:    the air preassure at the moment of the observation


        constants for observation and twilight calculation
        twilight_const='-6':   the twilight start -6 is civil, -12 is nautic and -18 is astronomical 
                               the value should be entered as a string ('-6', '-12'' '-18')
        horizon_const='-0:34') the horizon attribute defines your horizon, the altitude of the upper limb of a body 
                               at the moment you consider it to be rising and setting. The United States Naval Observatory, 
                               rather than computing refraction dynamically, uses a constant estimate of 34’ of refraction 
                               at the horizon.

        duration:              gives the timedelta between the events and gives how long the night, dusk, day and 
                               dawn took. If "True" the function returns a second variable with the duration of the 
                               observed dusk, day, dawn, night.

    Returns:
        a string with one of the labels "night", "dusk", "day", "dawn"
        or when duration=True 
        returns a the label mentioned above and the duration

    Raises:
        KeyError: Raises an exception.
               
    See https://rhodesmill.org/pyephem/quick.html'''

    my_observer = ephem.Observer()
    my_observer.date = datetime_utc
    if latitude_column == None:
        my_observer.lat = str(latitude_const)
    else:
        my_observer.lat = str(latitude_column)

    if longitude_column == None:
        my_observer.lon = str(longitude_const)
    else:
        my_observer.lon = str(longitude_column)

    # %% these parameters are for super-precise estimates, not necessary.
    if elevation_column == None:
        my_observer.elevation = elevation_const
    else:
        my_observer.elevation = elevation_column

    if air_pressure_column == None:
        my_observer.pressure = air_pressure_const  # millibar. The difference between the lowest ever observed (923.6) and the highest ever observed (1072) in Europe is 36 seconds later
    else:
        my_observer.pressure = air_pressure_column

    if temperature_column == None:
        my_observer.temp = temperature_const  # deg. Celcius. The difference between 0 deg. Celcius and 50 deg. Celcius = 37 seconds later
    else:
        my_observer.temp = temperature_column

    my_observer.horizon = str(horizon_const)

    sun = ephem.Sun()

    next_sunrise_utc = my_observer.next_rising(sun)
    next_sunset_utc = my_observer.next_setting(sun)

    if duration:
        previous_sunrise_utc = my_observer.previous_rising(sun)
        previous_sunset_utc = my_observer.previous_setting(sun)
    else:
        pass

    #Relocate the horizon to get twilight times
    #-6=civil twilight, -12=nautical, -18=astronomical
    my_observer.horizon = str(twilight_const)
    next_twilight_rise_utc = my_observer.next_rising(
        ephem.Sun(), use_center=True)  #Begin dusk
    next_twilight_set_utc = my_observer.next_setting(
        ephem.Sun(), use_center=True)  #Begin dawn

    if duration:
        previous_twilight_rise_utc = my_observer.previous_rising(sun)
        previous_twilight_set_utc = my_observer.previous_setting(sun)
    else:
        pass

    result_dict = {
        "next_twilight_rise_utc": next_twilight_rise_utc,
        "next_sunrise_utc": next_sunrise_utc,
        "next_sunset_utc": next_sunset_utc,
        "next_twilight_set_utc": next_twilight_set_utc
    }

    result_lowest = min(result_dict, key=result_dict.get)

    if result_lowest == "next_twilight_rise_utc":
        result = "night"
    elif result_lowest == "next_sunrise_utc":
        result = "dawn"
    elif result_lowest == "next_sunset_utc":
        result = "day"
    elif result_lowest == "next_twilight_set_utc":
        result = "dusk"

    if duration:
        if result == "night":
            duration = str(
                timedelta(next_twilight_rise_utc - previous_twilight_set_utc))
        elif result == "dusk":
            duration = str(
                timedelta(next_sunrise_utc - previous_twilight_rise_utc))
        elif result == "day":
            duration = str(timedelta(next_sunset_utc - previous_sunrise_utc))
        elif result == "dawn":
            duration = str(
                timedelta(next_twilight_set_utc - previous_sunset_utc))
        else:
            result = 'Error defining the string dusk, day, dawn, night'
    else:
        pass

    if duration:
        return (result, duration)
    else:
        return (result)
Exemplo n.º 9
0
def StarObsPlot(year=None,
                targets=None,
                observatory=None,
                period=None,
                hover=False,
                sunless_hours=None,
                remove_watermark=False):
    """
    Plot the visibility of target.

    Parameters
    ----------
    year: int
        The year for which to calculate the visibility.
    targets: list
        List of targets.
        Each target should be a dictionary with keys 'name' and 'coord'.
        The key 'name' is a string, 'coord' is a SkyCoord object.
    observatory: string
        Name of the observatory that pyasl.observatory can resolve.
        Basically, any of pyasl.listObservatories().keys()
    period: string, optional
        ESO period for which to calculate the visibility. Overrides `year`.
    hover: boolean, optional
        If True, color visibility lines when mouse over.
    sunless_hours: float, optional
        If not None, plot sunless hours above this airmass
  """

    from mpl_toolkits.axes_grid1 import host_subplot
    from matplotlib.ticker import MultipleLocator
    from matplotlib.font_manager import FontProperties
    from matplotlib import rcParams
    rcParams['xtick.major.pad'] = 12
    font0 = FontProperties()
    font1 = font0.copy()
    font0.set_family('sans-serif')
    font0.set_weight('light')
    font1.set_family('sans-serif')
    font1.set_weight('medium')

    # set the observatory
    if isinstance(observatory, dict):
        obs = observatory
    else:
        obs = pyasl.observatory(observatory)

    fig = plt.figure(figsize=(15, 10))
    fig.subplots_adjust(left=0.07, right=0.8, bottom=0.15, top=0.88)

    # watermak
    if not remove_watermark:
        fig.text(0.99,
                 0.99,
                 'Created with\ngithub.com/iastro-pt/ObservationTools',
                 fontsize=10,
                 color='gray',
                 ha='right',
                 va='top',
                 alpha=0.5)

    # plotting sunless hours?
    shmode = False
    if sunless_hours is not None:
        shmode = True
        # limit in airmass (assumed plane-parallel atm)
        shairmass = sunless_hours
        # correspoing limit in altitude
        from scipy.optimize import bisect
        shalt = 90 - bisect(lambda alt: pyasl.airmassPP(alt) - shairmass, 0,
                            89)

    if shmode:
        fig.subplots_adjust(hspace=0.35)
        ax = host_subplot(211)
        axsh = host_subplot(212)
        plt.text(0.5,
                 0.47,
                 "- sunless hours above airmass {:.1f} - \n".format(shairmass),
                 transform=fig.transFigure,
                 ha='center',
                 va='bottom',
                 fontsize=12)
        plt.text(0.5, 0.465,
              "the thick line above the curves represents the total sunless hours "\
              "for each day of the year",
              transform=fig.transFigure, ha='center', va='bottom', fontsize=10)

    else:
        ax = host_subplot(111)

    for n, target in enumerate(targets):

        target_coord = target['coord']
        target_ra = target_coord.ra.deg
        target_dec = target_coord.dec.deg

        if period is not None:
            jd_start, jd_end = get_ESO_period(period)
        else:
            jd_start = pyasl.jdcnv(dt.datetime(year, 1, 1))
            jd_end = pyasl.jdcnv(dt.datetime(year, 12, 31))

        jdbinsize = 1  # every day
        each_day = np.arange(jd_start, jd_end, jdbinsize)
        jds = []

        ## calculate the mid-dark times
        sun = ephem.Sun()
        for day in each_day:
            date_formatted = '/'.join([str(i) for i in pyasl.daycnv(day)[:-1]])
            s = ephem.Observer()
            s.date = date_formatted
            s.lat = ':'.join([str(i) for i in decdeg2dms(obs['latitude'])])
            s.lon = ':'.join([str(i) for i in decdeg2dms(obs['longitude'])])
            jds.append(ephem.julian_date(s.next_antitransit(sun)))

        jds = np.array(jds)

        # Get JD floating point
        jdsub = jds - np.floor(jds[0])

        # Get alt/az of object
        altaz = pyasl.eq2hor(jds, np.ones_like(jds)*target_ra, np.ones_like(jds)*target_dec, \
                            lon=obs['longitude'], lat=obs['latitude'], alt=obs['altitude'])
        ax.plot(jdsub, altaz[0], '-', color='k')

        # label for each target
        plabel = "[{0:2d}]  {1!s}".format(n + 1, target['name'])

        # number of target at the top of the curve
        ind_label = np.argmax(altaz[0])
        # or at the bottom if the top is too close to the corners
        # if jdsub[ind_label] < 5 or jdsub[ind_label] > jdsub.max()-5:
        #   ind_label = np.argmin(altaz[0])
        ax.text( jdsub[ind_label], altaz[0][ind_label], str(n+1), color="b", fontsize=14, \
                 fontproperties=font1, va="bottom", ha="center")

        if n + 1 == 29:
            # too many?
            ax.text(1.1, 1.0-float(n+1)*0.04, "too many targets", ha="left", va="top", transform=ax.transAxes, \
                    fontsize=10, fontproperties=font0, color="r")
        else:
            ax.text(1.1, 1.0-float(n+1)*0.04, plabel, ha="left", va="top", transform=ax.transAxes, \
                    fontsize=12, fontproperties=font0, color="b")

    if shmode:
        sunless_hours = []
        for day in each_day:
            date_formatted = '/'.join([str(i) for i in pyasl.daycnv(day)[:-1]])
            s = ephem.Observer()
            s.date = date_formatted
            s.lat = ':'.join([str(i) for i in decdeg2dms(obs['latitude'])])
            s.lon = ':'.join([str(i) for i in decdeg2dms(obs['longitude'])])
            # hours from sunrise to sunset
            td = pyasl.daycnv(ephem.julian_date(s.next_setting(sun)), mode='dt') \
                  - pyasl.daycnv(ephem.julian_date(s.next_rising(sun)), mode='dt')
            sunless_hours.append(24 - td.total_seconds() / 3600)

        days = each_day - np.floor(each_day[0])
        axsh.plot(days, sunless_hours, '-', color='k', lw=2)
        axsh.set(
            ylim=(0, 15),
            yticks=range(1, 15),
            ylabel='Useful hours',
            yticklabels=[r'${}^{{\rm h}}$'.format(n) for n in range(1, 15)])


    ax.text(1.1, 1.03, "List of targets", ha="left", va="top", transform=ax.transAxes, \
            fontsize=12, fontproperties=font0, color="b")

    axrange = ax.get_xlim()

    if period is None:
        months = range(1, 13)
        ndays = [0] + [calendar.monthrange(date, m)[1] for m in months]
        ax.set_xlim([0, 366])
        ax.set_xticks(np.cumsum(ndays)[:-1] + (np.array(ndays) / 2.)[1:])
        ax.set_xticklabels(map(calendar.month_abbr.__getitem__, months),
                           fontsize=10)
        if shmode:
            axsh.set_xlim([0, 366])
            axsh.set_xticks(np.cumsum(ndays)[:-1] + (np.array(ndays) / 2.)[1:])
            axsh.set_xticklabels(map(calendar.month_abbr.__getitem__, months),
                                 fontsize=10)
    else:
        if int(period) % 2 == 0:
            # even ESO period, Oct -> Mar
            months = [10, 11, 12, 1, 2, 3]
            ndays = [0] + [calendar.monthrange(date, m)[1] for m in months]
            ax.set_xlim([0, 181])
            ax.set_xticks(np.cumsum(ndays)[:-1] + (np.array(ndays) / 2.)[1:])
            ax.set_xticklabels(map(calendar.month_abbr.__getitem__, months),
                               fontsize=10)
            if shmode:
                axsh.set_xlim([0, 181])
                axsh.set_xticks(
                    np.cumsum(ndays)[:-1] + (np.array(ndays) / 2.)[1:])
                axsh.set_xticklabels(map(calendar.month_abbr.__getitem__,
                                         months),
                                     fontsize=10)
        else:
            # odd ESO period, Apr -> Sep
            months = range(4, 10)
            ndays = [0] + [calendar.monthrange(date, m)[1] for m in months]
            ax.set_xlim([0, 182])
            ax.set_xticks(np.cumsum(ndays)[:-1] + (np.array(ndays) / 2.)[1:])
            ax.set_xticklabels(map(calendar.month_abbr.__getitem__, months),
                               fontsize=10)
            if shmode:
                axsh.set_xlim([0, 182])
                axsh.set_xticks(
                    np.cumsum(ndays)[:-1] + (np.array(ndays) / 2.)[1:])
                axsh.set_xticklabels(map(calendar.month_abbr.__getitem__,
                                         months),
                                     fontsize=10)

    if axrange[1] - axrange[0] <= 1.0:
        jdhours = np.arange(0, 3, 1.0 / 24.)
        utchours = (np.arange(0, 72, dtype=int) + 12) % 24
    else:
        jdhours = np.arange(0, 3, 1.0 / 12.)
        utchours = (np.arange(0, 72, 2, dtype=int) + 12) % 24

    # Make ax2 responsible for "top" axis and "right" axis
    ax2 = ax.twin()
    # Set upper x ticks
    ax2.set_xticks(np.cumsum(ndays))
    ax2.set_xlabel("Day")

    # plane-parallel airmass
    airmass_ang = np.arange(10, 81, 5)
    geo_airmass = pyasl.airmass.airmassPP(airmass_ang)[::-1]
    ax2.set_yticks(airmass_ang)
    airmassformat = []
    for t in range(geo_airmass.size):
        airmassformat.append("{0:2.2f}".format(geo_airmass[t]))
    ax2.set_yticklabels(airmassformat)  #, rotation=90)
    ax2.set_ylabel("Relative airmass", labelpad=32)
    ax2.tick_params(axis="y", pad=6, labelsize=8)
    plt.text(1.02,-0.04, "Plane-parallel", transform=ax.transAxes, ha='left', \
             va='top', fontsize=10, rotation=90)

    ax22 = ax.twin()
    ax22.set_xticklabels([])
    ax22.set_frame_on(True)
    ax22.patch.set_visible(False)
    ax22.yaxis.set_ticks_position('right')
    ax22.yaxis.set_label_position('right')
    ax22.spines['right'].set_position(('outward', 30))
    ax22.spines['right'].set_color('k')
    ax22.spines['right'].set_visible(True)
    airmass2 = list(
        map(
            lambda ang: pyasl.airmass.airmassSpherical(90. - ang, obs[
                'altitude']), airmass_ang))
    ax22.set_yticks(airmass_ang)
    airmassformat = []
    for t in range(len(airmass2)):
        airmassformat.append(" {0:2.2f}".format(airmass2[t]))
    ax22.set_yticklabels(airmassformat, rotation=90)
    ax22.tick_params(axis="y", pad=8, labelsize=8)
    plt.text(1.05,-0.04, "Spherical+Alt", transform=ax.transAxes, ha='left', va='top', \
             fontsize=10, rotation=90)

    ax.set_ylim([0, 91])
    ax.yaxis.set_major_locator(MultipleLocator(15))
    ax.yaxis.set_minor_locator(MultipleLocator(5))
    yticks = ax.get_yticks()
    ytickformat = []
    for t in range(yticks.size):
        ytickformat.append(str(int(yticks[t])) + r"$^\circ$")
    ax.set_yticklabels(ytickformat, fontsize=16)
    ax.set_ylabel("Altitude", fontsize=18)
    yticksminor = ax.get_yticks(minor=True)
    ymind = np.where(yticksminor % 15. != 0.)[0]
    yticksminor = yticksminor[ymind]
    ax.set_yticks(yticksminor, minor=True)
    m_ytickformat = []
    for t in range(yticksminor.size):
        m_ytickformat.append(str(int(yticksminor[t])) + r"$^\circ$")
    ax.set_yticklabels(m_ytickformat, minor=True)
    ax.set_ylim([0, 91])

    ax.yaxis.grid(color='gray', linestyle='dashed')
    ax.yaxis.grid(color='gray', which="minor", linestyle='dotted')
    ax2.xaxis.grid(color='gray', linestyle='dotted')

    if period is not None:
        plt.text(
            0.5,
            0.95,
            "Visibility over P{0!s}\n - altitudes at mid-dark time -".format(
                period),
            transform=fig.transFigure,
            ha='center',
            va='bottom',
            fontsize=12)
    else:
        plt.text(
            0.5,
            0.95,
            "Visibility over {0!s}\n - altitudes at mid-dark time -".format(
                date),
            transform=fig.transFigure,
            ha='center',
            va='bottom',
            fontsize=12)

    obsco = "Obs coord.: {0:8.4f}$^\circ$, {1:8.4f}$^\circ$, {2:4f} m".format(
        obs['longitude'], obs['latitude'], obs['altitude'])

    plt.text(0.01,
             0.97,
             obsco,
             transform=fig.transFigure,
             ha='left',
             va='center',
             fontsize=10)
    plt.text(0.01,
             0.95,
             obs['name'],
             transform=fig.transFigure,
             ha='left',
             va='center',
             fontsize=10)

    # interactive!
    if hover:
        main_axis = fig.axes[0]
        all_lines = set(main_axis.get_lines())

        def on_plot_hover(event):
            for line in main_axis.get_lines():
                if line.contains(event)[0]:
                    line.set_color('red')  # make this line red
                    # and all others black
                    all_other_lines = all_lines - set([line])
                    for other_line in all_other_lines:
                        other_line.set_color('black')
                    fig.canvas.draw_idle()

        fig.canvas.mpl_connect('motion_notify_event', on_plot_hover)

    return fig
Exemplo n.º 10
0
OBSERVER_END_DT = OBSERVER_TIMEZONE.localize(datetime.datetime.strptime(END_DATE, "%Y-%m-%d"))

# Setup observer
OBS = ephem.Observer()
OBS.lat = str(OBSERVER_LATITUDE)
OBS.lon = str(OBSERVER_LONGITUDE)
OBS.elev = OBSERVER_ELEVATION

# Date range helper
def closed_dates_interval(start_date, end_date):
    for n in range(int ((end_date - start_date).days + 1)):
        yield start_date + datetime.timedelta(days=n)

import math

SUN = ephem.Sun()

OBSERVATION_HOUR = 12

ALTS = []
AZIS = []

for day in closed_dates_interval(OBSERVER_BEG_DT, OBSERVER_END_DT):

    # Analemma computation
    physical_timezone_delta = datetime.timedelta(hours=(float(OBS.lon) * 12 / math.pi))
    hour_o_clock = day.replace(tzinfo=None) \
                    + datetime.timedelta(hours=OBSERVATION_HOUR) \
                    - physical_timezone_delta
    OBS.date = hour_o_clock.strftime("%Y-%m-%d %H:%M:%S")
    SUN.compute(OBS)
Exemplo n.º 11
0
    def sunaz(self):

        self.obs.date = datetime.datetime.utcnow()
        sun = ephem.Sun()
        sun.compute(self.obs)
        return float(sun.az) * 180.0 / math.pi
Exemplo n.º 12
0
def planet_rise():
    sitka = ephem.Observer()
    # sitka.date = '2015/6/18'
    sitka.lat = '22.5'
    sitka.long = '77.5'
    m = ephem.Sun()
    sitka.pressure = 0
    sitka.horizon = '-18'
    time_zone = 5.5
    planet = {}
    print 'Rise/ hign noon/set times for:', sitka.lat, sitka.long
    print 'Rise -Twilight ', ephem.date(
        sitka.next_rising(m) + time_zone * ephem.hour)
    sitka.horizon = '-12'
    print 'Rise - Nautical', ephem.date(
        sitka.next_rising(m) + time_zone * ephem.hour)
    sitka.horizon = '-6'
    print 'Rise - Civil   ', ephem.date(
        sitka.next_rising(m) + time_zone * ephem.hour)
    sitka.horizon = '-0:50'
    sun_rise = ephem.date(sitka.next_rising(m) + time_zone * ephem.hour)
    print 'Rise Regular   ', sun_rise
    sitka.date = ephem.date(sitka.next_rising(m))
    m = ephem.Sun(sitka)
    print 'azimuth        ', m.az
    noon = ephem.date(sitka.next_transit(m) + time_zone * ephem.hour)
    print 'Noon           ', noon
    sitka.date = ephem.date(sitka.next_transit(m))
    m = ephem.Sun(sitka)
    print 'azimuth        ', m.alt
    sun_set = ephem.date(sitka.next_setting(m) + time_zone * ephem.hour)
    print 'Set            ', sun_set
    sitka.date = ephem.date(sitka.next_setting(m))
    m = ephem.Sun(sitka)
    print 'azimuth        ', m.az
    print 'Day Length     ', (sun_set - sun_rise) * 24
    sitka.horizon = '-6'
    sun_set = ephem.date(sitka.next_setting(m) + time_zone * ephem.hour)
    print 'Sunset - Civil ', sun_set
    sitka.horizon = '-12'
    sun_set = ephem.date(sitka.next_setting(m) + time_zone * ephem.hour)
    print 'Sunset - Naut  ', sun_set
    sitka.horizon = '-18'
    sun_set = ephem.date(sitka.next_setting(m) + time_zone * ephem.hour)
    print 'Sunset - Astro ', sun_set
    print '--------------------------------'

    print 'Moon'
    print '--------------------------------'
    sitka = ephem.Observer()
    # sitka.date = '2015/6/22'
    sitka.lat = '34:1'
    sitka.long = '-118:15'
    m = ephem.Moon()
    print 'Rise/ hign noon/set times for:', sitka.lat, sitka.long
    print 'Rise   ', ephem.date(sitka.next_rising(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_rising(m))
    m = ephem.Moon(sitka)
    print 'azimuth', m.az

    print 'Noon   ', ephem.date(sitka.next_transit(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_transit(m))
    m = ephem.Moon(sitka)
    print 'azimuth', m.alt, m.phase, '% phase', m.earth_distance * ephem.meters_per_au / 1600

    print 'Set    ', ephem.date(sitka.next_setting(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_setting(m))
    m = ephem.Moon(sitka)
    print 'azimuth', m.az
    print '--------------------------------'
    print 'Moon - Now'
    sitka = ephem.Observer()
    # sitka.date = '2015/10/19 4:21:54'
    sitka.lat = '34:03'
    sitka.long = '-118:15'
    v = ephem.Moon(sitka)
    Altitude = v.alt
    Direction = v.az
    m = ephem.Moon()
    m.compute()
    Phase = m.phase
    Distance = (m.earth_distance * ephem.meters_per_au / 1600)
    planet['Moon'] = {
        'Phase': Phase,
        'Distance': Distance,
        'Altitude': Altitude,
        'Direction': Direction
    }
    print '--------------------------------'
    print 'Mercury'
    print '--------------------------------'
    sitka = ephem.Observer()
    #sitka.date = '2015/10/12'
    sitka.lat = '34:03'
    sitka.long = '-118:15'
    m = ephem.Mercury()
    print 'Rise/ hign noon/set times for:', sitka.lat, sitka.long
    print 'Rise   ', ephem.date(sitka.next_rising(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_rising(m))
    m = ephem.Mercury(sitka)
    print 'azimuth', m.az

    print 'Noon   ', ephem.date(sitka.next_transit(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_transit(m))
    m = ephem.Mercury(sitka)
    print 'azimuth', m.alt, m.phase, '% phase'

    print 'Set    ', ephem.date(sitka.next_setting(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_setting(m))
    m = ephem.Mercury(sitka)
    print 'azimuth', m.az
    print '--------------------------------'
    print 'Mercury - Now'
    sitka = ephem.Observer()
    #sitka.date = '2015/10/19 4:21:54'
    sitka.lat = '34:03'
    sitka.long = '-118:15'
    v = ephem.Mercury(sitka)
    Altitude = v.alt
    Direction = v.az
    m = ephem.Mercury()
    m.compute()
    Phase = m.phase
    Distance = (m.earth_distance * ephem.meters_per_au / 1600)
    planet['Mercury'] = {
        'Phase': Phase,
        'Distance': Distance,
        'Altitude': Altitude,
        'Direction': Direction
    }
    print '--------------------------------'
    print 'Venus'
    print '--------------------------------'
    sitka = ephem.Observer()
    # sitka.date = '2015/10/12'
    sitka.lat = '34:03'
    sitka.long = '-118:15'
    m = ephem.Venus()
    print 'Rise/ hign noon/set times for:', sitka.lat, sitka.long
    print 'Rise   ', ephem.date(sitka.next_rising(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_rising(m))
    m = ephem.Venus(sitka)
    print 'azimuth', m.az

    print 'Noon   ', ephem.date(sitka.next_transit(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_transit(m))
    m = ephem.Venus(sitka)
    print 'azimuth', m.alt, m.phase, '% phase'

    print 'Set    ', ephem.date(sitka.next_setting(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_setting(m))
    m = ephem.Venus(sitka)
    print 'azimuth', m.az
    print '--------------------------------'
    print 'Venus - Now'
    sitka = ephem.Observer()
    #sitka.date = '2015/10/19 4:21:54'
    sitka.lat = '34:03'
    sitka.long = '-118:15'
    v = ephem.Venus(sitka)
    Altitude = v.alt
    Direction = v.az
    m = ephem.Venus()
    m.compute()
    Phase = m.phase
    Distance = (m.earth_distance * ephem.meters_per_au / 1600)
    planet['Venus'] = {
        'Phase': Phase,
        'Distance': Distance,
        'Altitude': Altitude,
        'Direction': Direction
    }
    print '--------------------------------'
    print 'Mars'
    print '--------------------------------'
    sitka = ephem.Observer()
    #sitka.date = '2015/10/12'
    sitka.lat = '34:03'
    sitka.long = '-118:15'
    m = ephem.Mars()
    print 'Rise/ hign noon/set times for:', sitka.lat, sitka.long
    print 'Rise   ', ephem.date(sitka.next_rising(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_rising(m))
    m = ephem.Mars(sitka)
    print 'azimuth', m.az

    print 'Noon   ', ephem.date(sitka.next_transit(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_transit(m))
    m = ephem.Mars(sitka)
    print 'azimuth', m.alt, m.phase, '% phase'

    print 'Set    ', ephem.date(sitka.next_setting(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_setting(m))
    m = ephem.Mars(sitka)
    print 'azimuth', m.az
    print '--------------------------------'
    print 'Mars - Now'
    sitka = ephem.Observer()
    #sitka.date = '2015/10/19 4:21:54'
    sitka.lat = '34:03'
    sitka.long = '-118:15'
    v = ephem.Mars(sitka)
    Altitude = v.alt
    Direction = v.az
    m = ephem.Mars()
    m.compute()
    Phase = m.phase
    Distance = (m.earth_distance * ephem.meters_per_au / 1600)
    planet['Mars'] = {
        'Phase': Phase,
        'Distance': Distance,
        'Altitude': Altitude,
        'Direction': Direction
    }
    print '--------------------------------'
    print 'Jupiter'
    print '--------------------------------'
    sitka = ephem.Observer()
    #sitka.date = '2015/10/12'
    sitka.lat = '34:03'
    sitka.long = '-118:15'
    m = ephem.Jupiter()
    print 'Rise/ hign noon/set times for:', sitka.lat, sitka.long
    Rise = str(ephem.date(sitka.next_rising(m) + time_zone * ephem.hour))
    sitka.date = ephem.date(sitka.next_rising(m))
    m = ephem.Jupiter(sitka)
    print 'azimuth', m.az

    print 'Noon   ', ephem.date(sitka.next_transit(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_transit(m))
    m = ephem.Jupiter(sitka)
    print 'azimuth', m.alt, m.phase, '% phase'

    Set = str(ephem.date(sitka.next_setting(m) + time_zone * ephem.hour))
    sitka.date = ephem.date(sitka.next_setting(m))
    m = ephem.Jupiter(sitka)
    azimuth = m.az
    #print '--------------------------------'
    #print 'Jupiter - Now'
    sitka = ephem.Observer()
    #sitka.date = '2015/10/19 4:21:54'
    sitka.lat = '34:03'
    sitka.long = '-118:15'
    v = ephem.Jupiter(sitka)
    Altitude = str(v.alt)
    Direction = str(v.az)
    m = ephem.Jupiter()
    m.compute()
    Phase = str(m.phase)
    Distance = str(m.earth_distance * ephem.meters_per_au / 1600)
    planet['Jupiter'] = {
        'Azimuth': azimuth,
        'Rise': Rise,
        'Set': Set,
        'Phase': Phase,
        'Distance': Distance,
        'Altitude': Altitude,
        'Direction': Direction
    }
    print '--------------------------------'
    print 'Saturn'
    print '--------------------------------'
    sitka = ephem.Observer()
    #sitka.date = '2015/10/12'
    sitka.lat = '34:03'
    sitka.long = '-118:15'
    m = ephem.Saturn()
    print 'Rise/ hign noon/set times for:', sitka.lat, sitka.long
    print 'Rise   ', ephem.date(sitka.next_rising(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_rising(m))
    m = ephem.Saturn(sitka)
    print 'azimuth', m.az

    print 'Noon   ', ephem.date(sitka.next_transit(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_transit(m))
    m = ephem.Saturn(sitka)
    print 'azimuth', m.alt, m.phase, '% phase'

    print 'Set    ', ephem.date(sitka.next_setting(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_setting(m))
    m = ephem.Saturn(sitka)
    print 'azimuth', m.az
    print '--------------------------------'
    print 'Saturn - Now'
    sitka = ephem.Observer()
    #sitka.date = '2015/10/19 4:21:54'
    sitka.lat = '34:03'
    sitka.long = '-118:15'
    v = ephem.Saturn(sitka)
    Altitude = v.alt
    Direction = v.az
    m = ephem.Saturn()
    m.compute()
    Phase = m.phase
    Distance = (m.earth_distance * ephem.meters_per_au / 1600)
    planet['Saturn'] = {
        'Phase': Phase,
        'Distance': Distance,
        'Altitude': Altitude,
        'Direction': Direction
    }
    print '--------------------------------'
    print 'Uranus'
    print '--------------------------------'
    sitka = ephem.Observer()
    #sitka.date = '2015/10/12'
    sitka.lat = '34:03'
    sitka.long = '-118:15'
    m = ephem.Uranus()
    print 'Rise/ hign noon/set times for:', sitka.lat, sitka.long
    print 'Rise   ', ephem.date(sitka.next_rising(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_rising(m))
    m = ephem.Uranus(sitka)
    print 'azimuth', m.az

    print 'Noon   ', ephem.date(sitka.next_transit(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_transit(m))
    m = ephem.Uranus(sitka)
    print 'azimuth', m.alt, m.phase, '% phase'

    print 'Set    ', ephem.date(sitka.next_setting(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_setting(m))
    m = ephem.Uranus(sitka)
    print 'azimuth', m.az
    print '--------------------------------'
    print 'Uranus - Now'
    sitka = ephem.Observer()
    #sitka.date = '2015/10/19 4:21:54'
    sitka.lat = '34:03'
    sitka.long = '-118:15'
    v = ephem.Uranus(sitka)
    Altitude = v.alt
    Direction = v.az
    m = ephem.Uranus()
    m.compute()
    Phase = m.phase
    Distance = (m.earth_distance * ephem.meters_per_au / 1600)
    planet['Uranus'] = {
        'Phase': Phase,
        'Distance': Distance,
        'Altitude': Altitude,
        'Direction': Direction
    }
    print '--------------------------------'
    print 'Neptune'
    print '--------------------------------'
    sitka = ephem.Observer()
    #sitka.date = '2015/10/12'
    sitka.lat = '34:03'
    sitka.long = '-118:15'
    m = ephem.Neptune()
    print 'Rise/ hign noon/set times for:', sitka.lat, sitka.long
    print 'Rise   ', ephem.date(sitka.next_rising(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_rising(m))
    m = ephem.Neptune(sitka)
    print 'azimuth', m.az

    print 'Noon   ', ephem.date(sitka.next_transit(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_transit(m))
    m = ephem.Neptune(sitka)
    print 'azimuth', m.alt, m.phase, '% phase'

    print 'Set    ', ephem.date(sitka.next_setting(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_setting(m))
    m = ephem.Neptune(sitka)
    print 'azimuth', m.az
    print '--------------------------------'
    print 'Neptune - Now'
    sitka = ephem.Observer()
    #sitka.date = '2015/10/19 4:21:54'
    sitka.lat = '34:03'
    sitka.long = '-118:15'
    v = ephem.Neptune(sitka)
    Altitude = v.alt
    Direction = v.az
    m = ephem.Neptune()
    m.compute()
    Phase = m.phase
    Distance = (m.earth_distance * ephem.meters_per_au / 1600)
    planet['Neptune'] = {
        'Phase': Phase,
        'Distance': Distance,
        'Altitude': Altitude,
        'Direction': Direction
    }
    print '--------------------------------'
    print 'Pluto'
    print '--------------------------------'
    sitka = ephem.Observer()
    #sitka.date = '2015/10/12'
    sitka.lat = '34:03'
    sitka.long = '-118:15'
    m = ephem.Pluto()
    print 'Rise/ hign noon/set times for:', sitka.lat, sitka.long
    print 'Rise   ', ephem.date(sitka.next_rising(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_rising(m))
    m = ephem.Pluto(sitka)
    print 'azimuth', m.az

    print 'Noon   ', ephem.date(sitka.next_transit(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_transit(m))
    m = ephem.Pluto(sitka)
    print 'azimuth', m.alt, m.phase, '% phase'

    print 'Set    ', ephem.date(sitka.next_setting(m) + time_zone * ephem.hour)
    sitka.date = ephem.date(sitka.next_setting(m))
    m = ephem.Pluto(sitka)
    print 'azimuth', m.az
    print '--------------------------------'
    print 'Pluto - Now'
    sitka = ephem.Observer()
    #sitka.date = '2015/10/19 4:21:54'
    sitka.lat = '34:03'
    sitka.long = '-118:15'
    v = ephem.Pluto(sitka)
    Altitude = v.alt
    Direction = v.az
    m = ephem.Pluto()
    m.compute()
    Phase = m.phase
    Distance = (m.earth_distance * ephem.meters_per_au / 1600)
    planet['Pluto'] = {
        'Phase': Phase,
        'Distance': Distance,
        'Altitude': Altitude,
        'Direction': Direction
    }
    return (planet)
Exemplo n.º 13
0
import numpy
from datetime import datetime
import math
import sidereal
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
import ephem

date = '2014-05-01 00:00:00'  #UTC
figname = '05.eps'

skinakas = ephem.Observer()
skinakas.lat, skinakas.lon = '24.89', '35.23'
skinakas.date = date
skinakas.horizon = '-12'
end = skinakas.previous_rising(ephem.Sun(), use_center=True).tuple()
start = skinakas.next_setting(ephem.Sun(), use_center=True).tuple()
night_end = end[3] + end[3] / 60. + end[3] / 3600.
night_start = start[3] + start[3] / 60. + start[3] / 3600.


class Config():
    def __init__(self):
        config = ConfigParser.RawConfigParser()
        config.read('config.cfg')
        self.longitude = config.getfloat('location', 'longitude')
        self.latitude = config.getfloat('location', 'latitude')
        self.altitude = config.getfloat('location', 'altitude')
        self.tabobdec = config.getboolean('location', 'tabobdec')
        self.tabobpath = config.get('location', 'tabobpath')
        self.timebins = config.getfloat('misc', 'timebins')
Exemplo n.º 14
0
import ephem
import pytz
import timezonefinder

from stateoftheuniverse.widgets.prototypes import WidgetPrototype
from stateoftheuniverse.widgets.utils import stringdecorator

# TIMEZONE = pytz.timezone('Europe/London')

EPHEM_BODIES = [
    ephem.Sun(),
    ephem.Moon(),
    ephem.Mercury(),
    ephem.Venus(),
    ephem.Mars(),
    ephem.Jupiter(),
    ephem.Saturn(),
    # ephem.Uranus(),
    # ephem.Neptune(),
]


class EphemBodies(WidgetPrototype):
    def __init__(
        self,
        longitude: float,
        latitude: float,
        datetime,
    ):
        super().__init__(longitude, latitude, datetime)
Exemplo n.º 15
0
def dashboard(request):
    reading = dict()
    reading['indoor'] = get_current_reading()

    date_from = datetime.utcnow() - timedelta(hours=24)

    records = Record.objects.filter(
        date__gte=date_from).order_by('date').values()
    records_list = []

    for record in list(records):
        records_list.append({k: v for k, v in record.items() if v is not None})
    reading['chart_data'] = json.dumps(records_list, cls=DjangoJSONEncoder)

    if records:
        reading['outdoor'] = {}
        if records.exclude(outdoor_temperature=None).last():
            reading['outdoor']['temperature'] = records.exclude(
                outdoor_temperature=None).last()['outdoor_temperature']
        else:
            reading['outdoor']['temperature'] = None
        if records.exclude(outdoor_humidity=None).last():
            reading['outdoor']['humidity'] = records.exclude(
                outdoor_humidity=None).last()['outdoor_humidity']
        else:
            reading['outdoor']['humidity'] = None

        reading['aqi'] = {}
        reading['aqi']['index'] = {}
        reading['aqi']['index']['value'] = None
        reading['aqi']['index']['description'] = None

        if records.exclude(pm25=None).last():
            reading['aqi']['PM25'] = records.exclude(pm25=None).last()['pm25']
        else:
            reading['aqi']['PM25'] = None

        if records.exclude(pm10=None).last():
            reading['aqi']['PM10'] = records.exclude(pm10=None).last()['pm10']
        else:
            reading['aqi']['PM10'] = None

        if records.exclude(no2=None).last():
            reading['aqi']['NO2'] = records.exclude(no2=None).last()['no2']
        else:
            reading['aqi']['NO2'] = None

        if records.exclude(o3=None).last():
            reading['aqi']['O3'] = records.exclude(o3=None).last()['o3']
        else:
            reading['aqi']['O3'] = None
    else:
        reading['outdoor'] = {}
        reading['outdoor']['temperature'] = None
        reading['outdoor']['humidity'] = None

        reading['aqi'] = {}
        reading['aqi']['index'] = {}
        reading['aqi']['index']['value'] = None
        reading['aqi']['index']['description'] = None

        reading['aqi']['PM25'] = None
        reading['aqi']['PM10'] = None
        reading['aqi']['NO2'] = None
        reading['aqi']['O3'] = None

    city = ephem.Observer()
    city.lat = '51.110'
    city.lon = '17.032'
    city.elev = 110
    city.date = datetime.utcnow()

    tz = pytz.timezone('Europe/Warsaw')
    sunrise = city.previous_rising(ephem.Sun()).datetime().astimezone(tz)
    sunset = city.next_setting(ephem.Sun()).datetime().astimezone(tz)

    reading['sunrise'] = sunrise.strftime('%H:%M')
    reading['sunset'] = sunset.strftime('%H:%M')

    return render(request, 'thermo/dashboard.html', reading)
Exemplo n.º 16
0
#!/usr/bin/env python3
import ephem
import time
import sys

date = time.strftime('%Y-%m-%d %H:%M:%S',
                     time.localtime(int(sys.argv[1]) + 3 * 60 * 60))

obs = ephem.Observer()
obs.lat = ''
obs.long = ''
obs.date = date

sun = ephem.Sun(obs)
sun.compute(obs)
sun_angle = float(sun.alt) * 57.2957795  # Rad to deg
print(int(sun_angle))
Exemplo n.º 17
0
 def next_sunrise(self, date=None):
     obs = self.copy()
     if date: obs.date = ephem.Date(date)
     obs.horizon = self.twilight
     return obs.next_rising(ephem.Sun(), use_center=True)
Exemplo n.º 18
0
                        help='degress above or below horizon of Sun, with sign',
                        default=0.0)
    args = parser.parse_args()

    horizon = args.horizon
    lat = args.latitude
    long = args.longitude
    elev = args.elevation

    o = ephem.Observer()
    o.lat = str(lat)
    o.long = str(long)
    o.elevation = elev
    o.horizon = str(horizon)

    s = ephem.Sun()
    s.compute()

    next_rise = o.next_rising(s).datetime()
    next_set = o.next_setting(s).datetime()
    prev_rise = o.previous_rising(s).datetime()
    prev_set = o.previous_setting(s).datetime()

    now = datetime.datetime.utcnow()

    print('As of {},'.format(str(now)))
    print('    latitude  =  {},'.format(lat))
    print('    longitude =  {},'.format(long))
    print('    elevation =  {},'.format(elev))
    print('    horizon   =  {}'.format(horizon))
Exemplo n.º 19
0
Arquivo: trigon.py Projeto: fedtf/gsee
def sun_angles(datetime_index, coords, rise_set_times=None):
    """Calculate sun angles. Returns a dataframe containing `sun_alt`,
    `sun_zenith`, `sun_azimuth` and `duration` over the passed datetime index.

    Parameters
    ----------
    datetime_index : pandas datetime index
        Handled as if they were UTC not matter what timezone info
        they may supply.
    coords : (float, float) or (int, int) tuple
        Latitude and longitude.
    rise_set_times : list, default None
        List of (sunrise, sunset) time tuples, if not passed, is computed
        here.

    """
    def _sun_alt_azim(sun, obs):
        sun.compute(obs)
        return sun.alt, sun.az

    # Initialize ephem objects
    obs = ephem.Observer()
    obs.lat = str(coords[0])
    obs.lon = str(coords[1])
    sun = ephem.Sun()

    # Calculate daily sunrise/sunset times
    if not rise_set_times:
        rise_set_times = _sun_rise_set(datetime_index, obs)

    # Calculate hourly altitute, azimuth, and sunshine
    alts = []
    azims = []
    durations = []

    for index, item in enumerate(datetime_index):
        obs.date = item
        # rise/set times are indexed by day, so need to scale the index
        rise_time, set_time = rise_set_times[int(index / 24)]

        # Set angles, sun altitude and duration based on hour of day:
        if rise_time is not None and item.hour == rise_time.hour:
            # Special case for sunrise hour
            duration = 60 - rise_time.minute - (rise_time.second / 60.0)
            obs.date = rise_time + datetime.timedelta(minutes=duration / 2)
            sun_alt, sun_azimuth = _sun_alt_azim(sun, obs)
        elif set_time is not None and item.hour == set_time.hour:
            # Special case for sunset hour
            duration = set_time.minute + set_time.second / 60.0
            obs.date = item + datetime.timedelta(minutes=duration / 2)
            sun_alt, sun_azimuth = _sun_alt_azim(sun, obs)
        else:
            # All other hours
            duration = 60
            obs.date = item + datetime.timedelta(minutes=30)
            sun_alt, sun_azimuth = _sun_alt_azim(sun, obs)
            if sun_alt < 0:  # If sun is below horizon
                sun_alt, sun_azimuth, duration = 0, 0, 0

        alts.append(sun_alt)
        azims.append(sun_azimuth)
        durations.append(duration)
    df = pd.DataFrame(
        {
            'sun_alt': alts,
            'sun_azimuth': azims,
            'duration': durations
        },
        index=datetime_index)
    df['sun_zenith'] = (np.pi / 2) - df.sun_alt
    return df
Exemplo n.º 20
0
    args = parser.parse_args()

    debug = False
    cadence = args.cadence
    uploadCadence = args.upload
    lastUpload = datetime.datetime.now()
    destinationPath = "/home/pi/share/camera"

    if args.service:
        log = logging.getLogger('skycam.service')
        log.addHandler(journal.JournaldLogHandler())
        log.setLevel(logging.INFO)
        logLine = "Starting the skycam with a cadence of %d seconds" % cadence
        log.info(logLine)

    sun = ephem.Sun()
    meteoLocation = ephem.Observer()
    #meteoLocation.lon = '-3.5262707'
    #meteoLocation.lat = '40.3719808'
    #meteoLocation.elevation = 900
    #meteoLocation.lon = '342.12'
    # meteoLocation.lat = '28.76'
    meteoLocation.elevation = 2326
    meteoLocation.lon = '-17.7742491'
    meteoLocation.lat = '28.6468866'
    #meteoLocation.elevation = 281
    d = datetime.datetime.utcnow()
    localTime = ephem.localtime(ephem.Date(d))
    print(localTime)
    meteoLocation.date = ephem.Date(d)
    sun = ephem.Sun(meteoLocation)
Exemplo n.º 21
0
def main(args):
    # The task at hand
    filename = args.filename

    # The station
    if args.metadata is not None:
        site = parse_ssmif(args.metadata)
        ssmifContents = open(args.metadata).readlines()
    else:
        site = lwa1
        ssmifContents = open(os.path.join(dataPath,
                                          'lwa1-ssmif.txt')).readlines()
    observer = site.get_observer()
    antennas = site.antennas

    # The file's parameters
    fh = open(filename, 'rb')

    nFramesFile = os.path.getsize(filename) // tbn.FRAME_SIZE
    srate = tbn.get_sample_rate(fh)
    antpols = len(antennas)
    fh.seek(0)
    if srate < 1000:
        fh.seek(len(antennas) * 4 * tbn.FRAME_SIZE)
        srate = tbn.get_sample_rate(fh)
        antpols = len(antennas)
        fh.seek(len(antennas) * 4 * tbn.FRAME_SIZE)

    # Reference antenna
    ref = args.reference
    foundRef = False
    for i, a in enumerate(antennas):
        if a.stand.id == ref and a.pol == 0:
            refX = i
            foundRef = True
        elif a.stand.id == ref and a.pol == 1:
            refY = i
        else:
            pass
    if not foundRef:
        raise RuntimeError("Cannot file Stand #%i" % ref)

    # Integration time (seconds and frames)
    tInt = args.average
    nFrames = int(round(tInt * srate / 512 * antpols))
    tInt = nFrames / antpols * 512 / srate

    # Total run length
    nChunks = int(1.0 * nFramesFile / antpols * 512 / srate / tInt)

    # Read in the first frame and get the date/time of the first sample
    # of the frame.  This is needed to get the list of stands.
    junkFrame = tbn.read_frame(fh)
    fh.seek(-tbn.FRAME_SIZE, 1)
    startFC = junkFrame.header.frame_count
    try:
        central_freq = junkFrame.central_freq
    except AttributeError:
        from lsl.common.dp import fS
        central_freq = fS * junkFrame.header.second_count / 2**32
    beginDate = junkFrame.time.datetime

    observer.date = beginDate
    srcs = [
        ephem.Sun(),
    ]
    for line in _srcs:
        srcs.append(ephem.readdb(line))

    for i in xrange(len(srcs)):
        srcs[i].compute(observer)

        if srcs[i].alt > 0:
            print("source %s: alt %.1f degrees, az %.1f degrees" %
                  (srcs[i].name, srcs[i].alt * 180 / numpy.pi,
                   srcs[i].az * 180 / numpy.pi))

    # File summary
    print("Filename: %s" % filename)
    print("Date of First Frame: %s" % str(beginDate))
    print("Ant/Pols: %i" % antpols)
    print("Sample Rate: %i Hz" % srate)
    print("Tuning Frequency: %.3f Hz" % central_freq)
    print("Frames: %i (%.3f s)" %
          (nFramesFile, 1.0 * nFramesFile / antpols * 512 / srate))
    print("---")
    print("Integration: %.3f s (%i frames; %i frames per stand/pol)" %
          (tInt, nFrames, nFrames // antpols))
    print("Chunks: %i" % nChunks)

    # Create the FrameBuffer instance
    buffer = TBNFrameBuffer(stands=range(1, antpols // 2 + 1), pols=[0, 1])

    # Create the phase average and times
    LFFT = 512
    times = numpy.zeros(nChunks, dtype=numpy.float64)
    simpleVis = numpy.zeros((nChunks, antpols), dtype=numpy.complex64)
    central_freqs = numpy.zeros(nChunks, dtype=numpy.float64)

    # Go!
    k = 0
    for i in xrange(nChunks):
        # Find out how many frames remain in the file.  If this number is larger
        # than the maximum of frames we can work with at a time (maxFrames),
        # only deal with that chunk
        framesRemaining = nFramesFile - k
        if framesRemaining > nFrames:
            framesWork = nFrames
            data = numpy.zeros((antpols, framesWork // antpols * 512),
                               dtype=numpy.complex64)
        else:
            framesWork = framesRemaining + antpols * buffer.nsegments
            data = numpy.zeros((antpols, framesWork // antpols * 512),
                               dtype=numpy.complex64)
        print("Working on chunk %i, %i frames remaining" %
              (i + 1, framesRemaining))

        count = [0 for a in xrange(len(antennas))]

        j = 0
        fillsWork = framesWork // antpols
        # Inner loop that actually reads the frames into the data array
        done = False
        while j < fillsWork:
            cFrames = deque()
            for l in xrange(len(antennas)):
                try:
                    cFrames.append(tbn.read_frame(fh))
                    k = k + 1
                except errors.EOFError:
                    ## Exit at the EOF
                    done = True
                    break
                except errors.SyncError:
                    #print("WARNING: Mark 5C sync error on frame #%i" % (int(fh.tell())/tbn.FRAME_SIZE-1))
                    ## Exit at the first sync error
                    done = True
                    break

            buffer.append(cFrames)
            cFrames = buffer.get()

            if cFrames is None:
                continue

            for cFrame in cFrames:
                stand, pol = cFrame.header.id

                # In the current configuration, stands start at 1 and go up to 260.  So, we
                # can use this little trick to populate the data array
                aStand = 2 * (stand - 1) + pol

                # Save the time
                if j == 0 and aStand == 0:
                    times[i] = cFrame.time
                    try:
                        central_freqs[i] = cFrame.central_freq
                    except AttributeError:
                        central_freqs[
                            i] = fS * cFrame.header.second_count / 2**32
                    if i > 0:
                        if central_freqs[i] != central_freqs[i - 1]:
                            print(
                                "Frequency change from %.3f to %.3f MHz at chunk %i"
                                % (central_freqs[i - 1] / 1e6,
                                   central_freqs[i] / 1e6, i + 1))

                data[aStand, count[aStand] * 512:(count[aStand] + 1) *
                     512] = cFrame.payload.data

                # Update the counters so that we can average properly later on
                count[aStand] = count[aStand] + 1

            j += 1

            if done:
                break

        if done:
            break

        # Time-domain blanking and cross-correlation with the outlier
        simpleVis[i, :] = fringe.Simple(data, refX, refY, args.clip)

    fh.close()

    # Save the data
    outname = os.path.split(filename)[1]
    outname = os.path.splitext(outname)[0]
    outname = "%s-ref%03i-multi-vis.npz" % (outname, args.reference)
    numpy.savez(outname,
                ref=ref,
                refX=refX,
                refY=refY,
                tInt=tInt,
                central_freqs=central_freqs,
                times=times,
                simpleVis=simpleVis,
                ssmifContents=ssmifContents)
Exemplo n.º 22
0
def logfftdata(flist, plist, longit, decln, rate, srate, pfx, combine):
    global lastfftlogged
    global doephem
    global darkslides
    global darkcounts
    global dsinit

    #
    # Initialize darkslides to length of plist entries
    #
    if (darkslides == None):
        darkslides = [[-200.0] * len(plist[0])] * COVERAGE

    decisid = None
    t = time.gmtime()
    if (doephem):
        sid = cur_sidereal(longit, 0)[0]
        sids = sid.split(",")
        decisid = float(
            sids[0]) + float(sids[1]) / 60.0 + float(sids[2]) / 3600.0
    else:
        sid = "??,??,??"

    if os.path.exists(pfx + "-current_decln.txt"):
        f = open(pfx + "-current_decln.txt", "r")
        v = f.readline()
        v = v.strip("\n")
        v = float(v)
        f.close()
        for i in range(len(decln)):
            decln[i] = v

    #
    # Not time for it yet, buddy
    #
    t2 = time.time()
    if ((t2 - lastfftlogged) < rate):
        return

    lastfftlogged = t2
    di = 0
    #
    # MUST be 1:1 correspondence between flist and plist
    #
    if combine == True and len(plist) == 2:
        lp1 = linearize(plist[0])
        lp2 = linearize(plist[1])
        ratio = numpy.sum(lp1) / numpy.sum(lp2)

        #
        # If one side is significantly stronger than another, there's a problem
        #  So, we append a message to an "ALERT" file
        #
        if (ratio > 2.50 or ratio < (1.0 / 2.5)):
            f = open(pfx + "-ALERT.txt", "a")
            f.write("%02d:%02d:%02d: ratio %f\n" %
                    (t.tm_hour, t.tm_min, t.tm_sec, ratio))
            f.close()

        #
        # We adjust the two sides to be roughly-equal in magnitude
        #
        if (ratio < 1.0):
            lp1 = numpy.multiply(lp1, 1.0 / ratio)
        else:
            lp2 = numpy.multiply(lp2, ratio)

        #
        # Then compute the linearized average
        #
        avg = numpy.add(lp1, lp2)
        avg = numpy.divide(avg, 2.0)

        #
        # Then back into log10 form
        #
        newplist = numpy.log10(avg)
        newplist = numpy.multiply(newplist, 10.0)

        flist = [flist[0]]
        plist = [newplist]

    for x in range(0, len(flist)):

        #
        # Construct filename
        #
        fn = "%s-%04d%02d%02d-fft-%d.csv" % (pfx, t.tm_year, t.tm_mon,
                                             t.tm_mday, x)
        f = open(fn, "a")

        #
        # Determine GMT (UTC) time
        #
        gt = "%02d,%02d,%02d" % (t.tm_hour, t.tm_min, t.tm_sec)

        #
        # Scale frequency into MHz
        #
        fweq = "%g" % (flist[x] / 1.0e6)

        #
        # Write header stuff
        #
        f.write(gt + "," + sid + "," + fweq + ",")
        f.write(str(int(srate)) + ",")
        f.write(str(decln[di]) + ",")

        if (decisid != None):
            #
            # Compute where the Sun currently is
            #
            sun = ephem.Sun()
            sun.compute()

            #
            # Figure out our beam pointing--for a transit instrument, it's just
            #  LMST,DEC
            #
            beam = ephem.Equatorial(str(decisid), str(decln[di]))

            #
            # Suppress dark-slide writing if Sun is too close to our beam
            #
            sunbeam = False
            if (math.degrees(
                    ephem.separation((beam.ra, beam.dec),
                                     (sun.ra, sun.dec))) <= 10.0):
                sunbeam = True

            #
            # Compute galactic coordinates of our beam
            #
            gp = ephem.Galactic(beam)
            glat = math.degrees(gp.lat)

            #
            # If the galactic latitude of the current observation is outside of
            #   the main galactic plane, we use it as a "cold sky" calibrator
            #   and "dark slide" to remove instrument artifacts.
            #
            # We also avoid writing dark-slide data when the Sun is in the beam
            #
            #
            if (sunbeam == False
                    and (glat < -OUTSIDE_GP or glat > OUTSIDE_GP)):

                #
                # Form an index into the darkslides array of lists
                #
                ndx = int(decln[di])
                ndx += int(COVERAGE / 2)

                #
                # Pick up the values
                #
                vs = darkslides[ndx]

                #
                # Initialize
                #
                if (dsinit[ndx] == False):
                    dsinit[ndx] = True
                    darkslides[ndx] = copy.deepcopy(plist[x])

                #
                # Add current values in
                #
                darkslides[ndx] = numpy.add(darkslides[ndx], plist[x])
                darkcounts[ndx] += 1

                vs = darkslides[ndx]

                #
                # Write out the darkslide file
                #
                df = open(pfx + "-darkslide-%02d.csv" % (int(decln[di])), "w")
                half = len(vs) / 2
                half = int(half)
                full = len(vs)
                for dx in range(half, full):
                    val = vs[dx] / float(darkcounts[ndx])
                    df.write("%-6.2f," % val)
                for dx in range(0, half):
                    val = vs[dx] / float(darkcounts[ndx])
                    df.write("%-6.2f" % val)
                    if (dx < half - 1):
                        df.write(",")

                df.write("\n")
                df.close()

                #
                # Reduce occasionally to prevent overflow
                #
                if (darkcounts[ndx] >= 20):
                    darkslides[ndx] = numpy.divide(darkslides[ndx],
                                                   float(darkcounts[ndx]))
                    darkcounts[ndx] = 1
        #
        # Bumpeth the declination index
        #
        di += 1

        #
        # Write out the FFT data
        #
        half = len(plist[x]) / 2
        half = int(half)
        full = len(plist[x])
        y = plist[x]
        for i in range(half, full):
            f.write("%-6.2f," % y[i])
        for i in range(0, half):
            f.write("%-6.2f" % y[i])
            if (i < half - 1):
                f.write(",")
        f.write("\n")
        f.close()
Exemplo n.º 23
0
    def __init__(self, name, lon, lat, elevation, horizon, telescopes,
                 obs_date_str, utc_offset, utc_offset_name, startNow, start,
                 end):

        self.name = name
        self.ephemeris = ephem.Observer()
        self.ephemeris.lon = lon
        self.ephemeris.lat = lat
        self.ephemeris.elevation = elevation
        self.ephemeris.horizon = horizon
        self.telescopes = telescopes

        self.obs_date_string = obs_date_str
        obs_date = parse("%s 12:00" % obs_date_str)  # UTC Noon
        self.obs_date = obs_date
        self.ephemeris.date = (self.obs_date - timedelta(hours=utc_offset)
                               )  # Local Noon n UTC

        self.utc_begin_night = self.ephemeris.next_setting(
            ephem.Sun(), use_center=True).datetime()
        self.utc_end_night = self.ephemeris.next_rising(
            ephem.Sun(), use_center=True).datetime()

        if startNow:
            self.utc_begin_night = datetime.now()
        elif start is not None:
            self.utc_begin_night = self.utc_begin_night.replace(
                hour=int(start[:2]))
            self.utc_begin_night = self.utc_begin_night.replace(
                minute=int(start[2:]))
            self.utc_end_night = self.ephemeris.next_rising(
                ephem.Sun(), use_center=True).datetime() + timedelta(-1)
        if end is not None:
            self.utc_end_night = self.utc_end_night.replace(hour=int(end[:2]))
            self.utc_end_night = self.utc_end_night.replace(
                minute=int(end[2:]))

        self.local_begin_night = pytz.utc.localize(self.utc_begin_night) \
                                 .astimezone(UTC_Offset(utc_offset,utc_offset_name))
        self.local_end_night = pytz.utc.localize(self.utc_end_night) \
                                   .astimezone(UTC_Offset(utc_offset,utc_offset_name))

        timeDiff = self.local_end_night - self.local_begin_night
        self.length_of_night = int(round(timeDiff.total_seconds() / 60))

        self.utc_time_array = np.asarray([self.utc_begin_night + timedelta(minutes=minute) \
                                          for minute in range(self.length_of_night)])

        self.local_time_array = np.asarray([self.local_begin_night + timedelta(minutes=minute) \
                                      for minute in range(self.length_of_night)])

        self.sidereal_string_array = []
        self.sidereal_radian_array = []

        for utc_time in self.utc_time_array:
            self.ephemeris.date = utc_time
            st = self.ephemeris.sidereal_time()

            tokens = str(st).split(":")
            float_tokens = [float(t) for t in tokens]
            st_string = "%02d:%02d:%02d" % (float_tokens[0], float_tokens[1],
                                            float_tokens[2])

            self.sidereal_string_array.append(st_string)
            self.sidereal_radian_array.append(st)

        print("%s - %s deg Twilight Ends: %s" %
              (self.name, np.abs(
                  self.ephemeris.horizon), self.local_begin_night))
        print(
            "%s - %s deg Dawn Begins: %s" %
            (self.name, np.abs(self.ephemeris.horizon), self.local_end_night))
Exemplo n.º 24
0
boia      = ephem.Observer()
#Localização do observador
boia.lon  = str(-48.42101867)      #Note that lon should be in string format
boia.lat  = str(-27.27445333)      #Note that lat should be in string format
#Elevação do observador em metros
boia.elev = 0
# criando listas vazias para os vetores tempo e fchl para o período noturno
dn_dt = []
dn_flu = []
nh = []
# laço para cada passo de tempo da série temporal
bar = progressbar.ProgressBar(max_value=progressbar.UnknownLength)
for h in range(len(df_sc.index)):
    bar.update(h) # barra de progresso
    boia.date = df_sc.index[h].strftime("%Y-%m-%d") # dia da medição
    sunrise = boia.next_rising(ephem.Sun()) # horário do nascer do sol no dia
    sunset  = boia.next_setting(ephem.Sun()) #horário por do sol no dia
    
    if sunset.datetime()-dt.timedelta(hours=1)<=df_sc.index[h].to_pydatetime(): # seleção para os dados amostrados após o pôr do sol
        dn_dt.append(df_sc.index[h]) # adicionando os horários à lista tempo
        dn_flu.append(df_sc['flu'][h]) # adicionando os dados à lista de Fchl
        nh.append(h)
    if sunrise.datetime()+dt.timedelta(hours=1)>=df_sc.index[h].to_pydatetime(): # seleção para os dados amostrados antes do nascer do sol
        dn_dt.append(df_sc.index[h]) # adicionando os horários à lista tempo
        dn_flu.append(df_sc['flu'][h]) # adicionando os dados à lista de Fchl 
        nh.append(h)

os.system('cls') # limpando o display de resultados 
dn = pd.DataFrame({'dt':dn_dt,'flu':dn_flu}) # criando pandas  dataframe com os dados noturnos
max_night = dn.groupby(pd.Grouper(key='dt', freq='1D')).agg({'flu':[np.max]}) # agrupando os maiores valores por dia
Exemplo n.º 25
0
def getlocation(LOCATION, CBODY):

    #observation locations
    locations = dict(
        Barcroft=EarthLocation(lat=Angle(37.5838176, 'deg'),
                               lon=Angle(-118.2373297, 'deg'),
                               height=3800 * u.m),
        Greenland=EarthLocation(lat=Angle(72.5796, 'deg'),
                                lon=Angle(-38.4592, 'deg'),
                                height=3200 * u.m),
        UCSB=EarthLocation(lat=Angle(34.414, 'deg'),
                           lon=Angle(-119.843, 'deg'),
                           height=14 * u.m),
    )

    #celestial bodies
    cbodies = dict(Sun=ephem.Sun(),
                   Moon=ephem.Moon(),
                   Mercury=ephem.Mercury(),
                   Venus=ephem.Venus(),
                   Mars=ephem.Mars(),
                   Jupiter=ephem.Jupiter(),
                   Saturn=ephem.Saturn(),
                   Uranus=ephem.Uranus(),
                   Neptune=ephem.Neptune())

    #observer location
    location = locations[LOCATION]

    #current utc time
    time = str(datetime.utcnow())

    #celestial body of interest
    if type(CBODY) == list:
        az = CBODY[1]
        alt = CBODY[2]
        return az, alt
    if type(CBODY) == str:
        cbody = cbodies[CBODY]
        #this method take 2x as long and produces a slightly different azel, I am not sure which is more accurate
        '''##########################
        #compute radec of body at current time
        cbody.compute(time)

        #create icrs object to convert to az el
        icrs = ICRS(ra = Angle(str(cbody.ra) + 'hours'), dec = Angle(str(cbody.dec) + 'degrees'))
        #print icrs.ra.deg, icrs.dec.deg
        #convert to altaz coordinates
        altaz = icrs.transform_to(AltAz(obstime=t, location=location))
        print altaz.az.deg, altaz.alt.deg
        #############################
      '''
        #set observer location and epoch
        obs = ephem.Observer()
        obs.lon, obs.lat = str(location.longitude.deg), str(
            location.latitude.deg)
        obs.elevation = float(str(location.height).split()[0])
        obs.date = time
        #compute celestial body az/el coordinates given observer spacetime coordiantes
        cbody.compute(obs)
        print cbody.az
        #convert azimuth to degrees
        az = str(cbody.az).split(':')
        az = [float(i) for i in az]
        az = (az[0] + az[1] / 60. + az[2] / 60. / 60.)
        #convert altitude to degrees
        alt = str(cbody.alt).split(':')
        alt = [float(i) for i in alt]
        alt = (alt[0] + alt[1] / 60. + alt[2] / 60. / 60.)
        #return azimuth and altitude of celestial body
        return az, alt
Exemplo n.º 26
0
# Jimmy ephemeris calculations -
# angle between Polaris and the Sun
import datetime
import ephem  # PyEphem - calculate ephemerides
import ephem.stars  # star catalog
from math import degrees

TIME_FORMAT = "%Y-%m-%d %H:%M:%S"

#
# Set up bodies for observation
#

# major body
SUN = ephem.Sun()

# from star catalog
POL = ephem.stars.stars["Polaris"]

# location on Earth
JIMMY = ephem.Observer()
JIMMY.lat = "33.885829"  # as string (degrees North latitude)
JIMMY.lon = "-117.818459"  # as string (degrees East longitude)
JIMMY.elevation = 111.3 + 1.5  # as float  (meters ASL)
JIMMY_TZ = datetime.timedelta(hours=-8)  # timezone offset (PST)


def update(utc_date_time):
    """
    Compute locations at given date and time
    """
Exemplo n.º 27
0
    def _setupPointGrid(self):
        """
        Setup the points for the interpolation functions.
        """
        # Switch to Dublin Julian Date for pyephem
        self.Observatory.date = mjd2djd(self.mjd)

        sun = ephem.Sun()
        sun.compute(self.Observatory)
        self.sunAlt = sun.alt
        self.sunAz = sun.az
        self.sunRA = sun.ra
        self.sunDec = sun.dec

        # Compute airmass the same way as ESO model
        self.airmass = 1. / np.cos(np.pi / 2. - self.alts)

        self.points['airmass'] = self.airmass
        self.points['nightTimes'] = 2
        self.points['alt'] = self.alts
        self.points['az'] = self.azs

        if self.twilight:
            self.points['sunAlt'] = self.sunAlt
            self.azRelSun = wrapRA(self.azs - self.sunAz)
            self.points['azRelSun'] = self.azRelSun

        if self.moon:
            moon = ephem.Moon()
            moon.compute(self.Observatory)
            self.moonPhase = moon.phase
            self.moonAlt = moon.alt
            self.moonAz = moon.az
            self.moonRA = moon.ra
            self.moonDec = moon.dec
            # Calc azimuth relative to moon
            self.azRelMoon = calcAzRelMoon(self.azs, self.moonAz)
            self.moonTargSep = haversine(self.azs, self.alts, self.moonAz,
                                         self.moonAlt)
            self.points['moonAltitude'] += np.degrees(self.moonAlt)
            self.points['azRelMoon'] += self.azRelMoon
            self.moonSunSep = self.moonPhase / 100. * 180.
            self.points['moonSunSep'] += self.moonSunSep

        if self.zodiacal:
            self.eclipLon = np.zeros(self.npts)
            self.eclipLat = np.zeros(self.npts)

            for i, temp in enumerate(self.ra):
                eclip = ephem.Ecliptic(
                    ephem.Equatorial(self.ra[i], self.dec[i], epoch='2000'))
                self.eclipLon[i] += eclip.lon
                self.eclipLat[i] += eclip.lat
            # Subtract off the sun ecliptic longitude
            sunEclip = ephem.Ecliptic(sun)
            self.sunEclipLon = sunEclip.lon
            self.points['altEclip'] += self.eclipLat
            self.points['azEclipRelSun'] += wrapRA(self.eclipLon -
                                                   self.sunEclipLon)

        self.mask = np.where((self.airmass > self.airmassLimit)
                             | (self.airmass < 1.))[0]
        self.goodPix = np.where((self.airmass <= self.airmassLimit)
                                & (self.airmass >= 1.))[0]
Exemplo n.º 28
0
 def get_next_sunset(self, timezone, location):
     tz = pytz.timezone(timezone)
     obs = self.create_observer(location)
     sunset = obs.next_setting(ephem.Sun()).datetime()
     return pytz.utc.localize(sunset).astimezone(tz)
Exemplo n.º 29
0
from    get_sky                  import  get_sky
from    pkg_resources            import  resource_filename
from    desiutil.iers            import  freeze_iers


freeze_iers()

mayall            = get_location()

emayall           = ephem.Observer()
emayall.lon       = ephem.degrees(mayall.lon.value * np.pi / 180.)
emayall.lat       = ephem.degrees(mayall.lat.value * np.pi / 180.)
emayall.elevation = mayall.height.value

moon              = ephem.Moon()
sun               = ephem.Sun()

def airmass(zd):
    # Airmass at given zenith distance.                                                                                                                                                                                                 
    return  (1. - 0.96 * np.sin(zd * np.pi / 180.)**2.)**-0.5

def get_solar(mjd, ras, decs):
    t                 = Time(mjd, format='mjd', scale='utc')
    emayall.date      = t.iso

    ras               = np.atleast_1d(ras)
    decs              = np.atleast_1d(decs)
    
    pos               = SkyCoord(ra = ras * u.degree, dec = decs * u.degree, frame='icrs').transform_to(AltAz(obstime=t, location=mayall))
    alt               = pos.alt.degree
    az                = pos.az.degree
Exemplo n.º 30
0
 def calculate_sun(self, obs):
     aux = obs
     aux.compute_pressure()
     aux.horizon = '-12'
     sun = ephem.Sun(aux)
     return aux.previous_setting(sun), aux.next_rising(sun)