How to use the ephem.Sun function in ephem

To help you get started, we’ve selected a few ephem examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ledatelescope / bifrost / python / bifrost / addon / leda / test_model_block.py View on Github external
def setUp(self):
        """Generate simple model based on Cygnus A and the sun at 60 MHz"""
        self.blocks = []
        self.sources = {}
        self.sources['cyg'] = {
            'ra':'19:59:28.4', 'dec':'+40:44:02.1', 
            'flux': 10571.0, 'frequency': 58e6, 
            'spectral index': -0.2046}
        self.sources['sun'] = {
            'ephemeris': ephem.Sun(),
            'flux': 250.0, 'frequency':20e6,
            'spectral index':+1.9920}
        frequencies = [60e6]
        self.blocks.append((ScalarSkyModelBlock(ovro, coords, frequencies, self.sources), [], [0]))
        self.blocks.append((WriteAsciiBlock('.log.txt'), [0], []))
    def test_output_size(self):
github akkana / scripts / rise_set_az.py View on Github external
observer = None
    else:
        observer = None

    if not observer:
        observer = observer_for_city(args.observer)

    if not observer:
        print("Couldn't parse observer '%s'" % args.observer)
        parser.print_help()
        sys.exit(1)

    print("Observer:", observer)

    if args.sun:
        body = ephem.Sun()
    else:
        body = ephem.Moon()

    rise = not args.set
    if rise:
        print("Finding %srises" % body.name)
    else:
        print("Finding %ssets" % body.name)

    if not args.start:
        args.start = datetime.datetime.now()
    if not args.end:
        args.end = args.start.replace(month=12, day=31, hour=23)

    vals = find_rise_set(observer, body, rise,
                         ephem.Date(args.start), ephem.Date(args.end),
github lsst / sims_featureScheduler / python / lsst / sims / featureScheduler / observatory / speed_observatory.py View on Github external
Generate the sunrise times for LSST so we can label nights by MJD
        """

        # Set observatory horizon to zero
        self.obs.horizon = 0.

        # Swipe dates to match sims_skybrightness_pre365
        mjd_start = self.mjd
        mjd_end = np.arange(59560, 59560+365.25*nyears+day_pad+366, 366).max()
        step = 0.25
        mjds = np.arange(mjd_start, mjd_end+step, step)
        setting = mjds*0.

        # Stupid Dublin Julian Date
        djds = mjds - doff
        sun = ephem.Sun()

        for i, (mjd, djd) in enumerate(zip(mjds, djds)):
            sun.compute(djd)
            setting[i] = self.obs.previous_setting(sun, start=djd, use_center=True)
        setting = setting + doff

        # zomg, round off crazy floating point precision issues
        setting_rough = np.round(setting*100.)
        u, indx = np.unique(setting_rough, return_index=True)
        self.setting_sun_mjds = setting[indx]
        left = np.searchsorted(self.setting_sun_mjds, mjd_start)
        self.setting_sun_mjds = self.setting_sun_mjds[left:]
github OSCAAR / OSCAAR / oscaar / extras / eph / calculateEphemerides.py View on Github external
def eventAfterTwilight(planet,observatory,ingress,egress,twilightType):
        altitudes = []
        for time in [ingress,egress]:
            observatory.date = list2datestr(jd2gd(time))
            sun = ephem.Sun()
            sun.compute(observatory)
            altitudes.append(float(repr(sun.alt))/(2*np.pi) * 360)	## Convert altitudes to degrees
        if altitudes[0] < float(twilightType) and altitudes[1] < float(twilightType): return True
        else: return False
github gnuradio / gnuradio / gr-radio-astronomy / src / python / usrp_ra_receiver.py View on Github external
self.scope = ra_fftsink.ra_fft_sink_c (panel, 
			   fft_size=int(self.fft_size), sample_rate=self.fft_input_rate,
			   fft_rate=int(self.fft_rate), title="Spectral",  
			   ofunc=self.fft_outfunc, xydfunc=self.xydfunc)
		else:
			self.scope = ra_waterfallsink.waterfall_sink_c (panel,
				fft_size=int(self.fft_size), sample_rate=self.fft_input_rate,
				fft_rate=int(self.fft_rate), title="Spectral", ofunc=self.fft_outfunc, size=(1100, 600), xydfunc=self.xydfunc, ref_level=0, span=10)

		# Set up ephemeris data
		self.locality = ephem.Observer()
		self.locality.long = str(options.longitude)
		self.locality.lat = str(options.latitude)
		
		# We make notes about Sunset/Sunrise in Continuum log files
		self.sun = ephem.Sun()
		self.sunstate = "??"

		# Set up stripchart display
		tit = "Continuum"
		if (self.dual_mode != False):
			tit = "H+V Continuum"
		if (self.interferometer != False):
			tit = "East x West Correlation"
		self.stripsize = int(options.stripsize)
		if self.chartneeded == True:
			self.chart = ra_stripchartsink.stripchart_sink_f (panel,
				stripsize=self.stripsize,
				title=tit,
				xlabel="LMST Offset (Seconds)",
				scaling=1.0, ylabel=options.ylabel,
				divbase=options.divbase)
github zonyl / pytomation / reference / devices / old / location.py View on Github external
def __init__(self, latitude, longitude, tz='US/Eastern', mode=MODE.STANDARD, is_dst=True, *args, **kwargs):
        super(Location, self).__init__(*args, **kwargs)
        self.obs = ephem.Observer()
        self.obs.lat = latitude
        self.obs.long = longitude
        self.tz = pytz.timezone(tz)
        self.is_dst = is_dst

        self.sun = ephem.Sun(self.obs)
        self._horizon = mode
        
        self._sunset_timer = CronTimer()
        self._sunrise_timer = CronTimer()
        self._local_time = None
        self._recalc()
github cosmo-ethz / seek / seek / calibration / flux_calibration_transit.py View on Github external
"""
    Get the declination coordinate of a given source in degrees.

    :param source: name of source
    :param params: context parameters

    :return: declination coordinate of source in degrees
    """
    if source.target == 'Sun':
        obs = ephem.Observer()
        obs.lon = params.telescope_longitude
        obs.lat = params.telescope_latitude
        obs.elevation = params.telescope_elevation
        obs.pressure = 0
        obs.date = source.date + HOUR
        s = ephem.Sun(obs)
        source_dec = s.dec/np.pi*180.0

    else:
        time = source.date + timedelta(seconds=3600)
        ra, dec = sphere.altaz_to_ra_dec(time, source.azimut, source.elevation, params=params)
        source_dec = np.degrees(dec)
        
    return source_dec
github LASER-WOLF / OnboardComputerSystem / ocs_files / .OnboardComputerSystem / OnboardComputerSystem.py View on Github external
#Format uptime
          uptimemin, uptimesec = divmod(uptime, 60)
          uptimehour, uptimemin = divmod(uptimemin, 60)
          uptimeday, uptimehour = divmod(uptimehour, 24)
          uptimeformatfull='{0:02d}D {1:02d}H {2:02d}M'.format(uptimeday,uptimehour,uptimemin)
          
          #Calculate sunset/sunrise
          if (gpsfix==1 and astronomy_update==1):
            astronomy=ephem.Observer()
            astronomy.lat=str(gpslatdeg)
            astronomy.long=str(gpslondeg)
            astronomy.date=datetime.utcnow().strftime("%Y/%m/%d 00:00:00")
            astronomy.elev=0
            astronomy.pressure=0
            astronomy.horizon='-0:34'       
            sunrise=astronomy.next_rising(ephem.Sun())
            sunset=astronomy.next_setting(ephem.Sun())
            astronomy_update_lock.acquire()
            astronomy_update=0
            astronomy_update_lock.release()
            if astronomyfirst==1:
              astronomyfirst=0
          if astronomyfirst==0:
            sunriseformat=(sunrise.datetime()+timedelta(hours=utcoffsethours,minutes=utcoffsetminutes)).strftime('%H:%M')
            sunsetformat=(sunset.datetime()+timedelta(hours=utcoffsethours,minutes=utcoffsetminutes)).strftime('%H:%M')
          if start_update_databases==0:
            start_update_databases=1
          if start_alarm_system==0:
            start_alarm_system=1
          
        sleep(1)
github akkana / scripts / analemma.py View on Github external
'earliest sunrise': 24,
            'latest sunrise'  :  0,
            'earliest sunset' : 24,
            'latest sunset'   :  0,
            'longest day len' :  0,
            'shortest day len': 24
        }

        # Start just after midnight on New Year's Day.
        dt = self.local_to_gmt('%d/01/01 00:00:01' % (self.year))
        # Loop until it's next year:
        while (dt.tuple()[0] <= self.year):
            self.observer.date = dt
            risetime = self.observer.next_rising(ephem.Sun())
            self.observer.date = risetime
            settime = self.observer.next_setting(ephem.Sun())
            self.observer.date = settime

            # Now we're done setting observer time, so it's safe to
            # convert to localtime.
            risetime = self.local_mean_time(risetime)
            settime = self.local_mean_time(settime)
            risehours = self.ephemdate_to_hours(risetime)
            sethours = self.ephemdate_to_hours(settime)

            if risehours < self.ephemdate_to_hours(self.special_dates['earliest sunrise']):
                self.special_dates['earliest sunrise'] = risetime
            if risehours > self.ephemdate_to_hours(self.special_dates['latest sunrise']):
                self.special_dates['latest sunrise'] = risetime
            if sethours < self.ephemdate_to_hours(self.special_dates['earliest sunset']):
                self.special_dates['earliest sunset'] = settime
            if sethours > self.ephemdate_to_hours(self.special_dates['latest sunset']):
github ojhall94 / stateoftheuniverse / stateoftheuniverse / widgets / sun.py View on Github external
def get_sun_info(dt, lat, lon):
    """
    Get times of sunrise and sunset.

    If the Sun is below the horizon, the next sunrise and sunset are returned.
    If it's above the horizon - previous sunrise and next sunset.
    
    Args:
        dt (datetime.datetime): datetime in UTC
        lat (float): geographical latitude, number between -90 and 90
        lon (float): geographical longitude, number between -180 and 180
    Returns:
        A tuple of two datetime.datetime objects (sunrise, sunset) in UTC
    """
    sun = ephem.Sun()

    observer = ephem.Observer()
    observer.date = str(dt)
    # lat and lon must be converted to strings to make pyephem recognize them
    # as degrees, not radians
    observer.lat = str(lat)
    observer.lon = str(lon)

    rising = observer.next_rising(sun)
    setting = observer.next_setting(sun)
    if setting < rising:
        rising = observer.previous_rising(sun)

    return (rising.datetime(), setting.datetime())