Example #1
0
def get_coordsdiff(x,T1=967966720):
	from astropy.coordinates import get_sun
	import astropy.time as Time
	import numpy as np
	import lal


	T1 =  967966720
	t = Time.Time(T1,format='gps')
	t.coords = get_sun(t)
	coords = get_sun(t)
	T2 = T1 + x
	t2 = Time.Time(T2,format='gps')
	coords2 = get_sun(t2)
	dec = coords.dec.hour * np.pi/12
	ra = coords.ra.hour *np.pi/12
	ra2 = coords.ra.hour * np.pi/12
	dec2 = coords2.dec.hour * np.pi/12

	detMap = {'H1': lal.LALDetectorIndexLHODIFF, 'L1':
	lal.LALDetectorIndexLLODIFF}
	detH1 = lal.CachedDetectors[detMap['H1']]
	detL1 = lal.CachedDetectors[detMap['L1']]
	tgps = lal.LIGOTimeGPS(T1, 0)
	tgps2 = lal.LIGOTimeGPS(T2, 0)

	coords = get_sun(Time.Time(967966720.0,format='gps'))
	ra  = coords.ra.hour  * np.pi/12
	dec = coords.dec.hour * np.pi/12


	tdelay1 = lal.ArrivalTimeDiff(detH1.location, detL1.location, ra, dec, tgps)
	tdelay2 = lal.ArrivalTimeDiff(detH1.location, detL1.location, ra2, dec2, tgps2)
	diff_dec = tdelay2-tdelay1
Example #2
0
    def get(self, source_coord, frame):
        """Evaluate the constraint for given targets, a specific location and
        time.

        Parameters
        -----
        source_coord : astropy.SkyCoord
            Coordinates of the target sources.
        frame : astropy.coordinates.builtin_frames.altaz.AltAz
            A coordinate or frame in the Altitude-Azimuth system.

        Returns
        -----
        out : numpy.ndarray
            Array of boolean values. One entry for each input coordinate.
            The entry is True, if the source is observable according to the
            constraint, and False otherwise.
        """

        # if frame is the same as before re-use Moon positions:
        if self._same_frame(frame):
            sun_altaz = self.sun_altaz
        # otherwise calculate new Moon positions:
        else:
            sun_altaz = get_sun(frame.obstime).transform_to(frame)
            self.sun_altaz = sun_altaz
            self.last_frame = frame

        source_altaz = source_coord.transform_to(frame)
        sun_altaz = get_sun(frame.obstime).transform_to(frame)
        separation = source_altaz.separation(sun_altaz)
        observable = separation > self.limit
        #observable = np.array(observable, dtype=float)

        return observable
Example #3
0
    def __init__(self, telLat, telLon, telElv, time, steps, sig1=.11, m1=1.7, t1=800, xlen=500, ylen=500,
                 mag_range=(-3, 3), dec_range=(-20, 90), ra_range=(0,0), max_sun_alt = -15, timestep=.5):

        self.Bews = []
        self.Bnss = []
        self.Buds = []

        self.xlen = xlen
        self.ylen = ylen
        self.mag_range = mag_range
        self.dec_range = dec_range

        self.telLat = telLat * u.deg
        self.telLon = telLon * u.deg
        self.telElv = telElv * u.m
        self.tel_loc = EarthLocation(lat=telLat * u.deg, lon=telLon * u.deg, height=telElv * u.m)

        self.err_sig = sig1
        self.err_mag = m1
        self.err_t1 = t1

        self.time_info = None

        self.time_info = Time(time, location=self.tel_loc)
        self.delta_time = np.linspace(-12, 12, steps) * u.hour

        self.time_delt = self.delta_time[1]-self.delta_time[0]
        self.telFrame = AltAz(obstime=self.time_info + self.delta_time, location=self.tel_loc)


        #get indicies for when sky is dark
        self.sunaltazs = get_sun(self.delta_time+self.time_info).transform_to(self.telFrame)
        self.moonaltazs = get_moon(self.delta_time+self.time_info).transform_to(self.telFrame)
        dark_times = np.where((self.sunaltazs.alt < max_sun_alt * u.deg))
        self.dark_times = self.telFrame.obstime.sidereal_time('apparent')[dark_times]
        self.max_sun_alt = max_sun_alt


        self.int_delta_time = np.append(np.arange(-12,12,timestep),12)*u.hour
        self.intTelFrame = AltAz(obstime=self.time_info + self.int_delta_time, location=self.tel_loc)
        self.intsunaltazs = get_sun(self.int_delta_time+self.time_info).transform_to(self.intTelFrame)

        int_dark_times = np.where((self.intsunaltazs.alt < max_sun_alt * u.deg))
        self.int_dark_times = self.intTelFrame.obstime.sidereal_time('apparent')[int_dark_times]


        #the hour_correction is to shift the sky to include stars that have just barely risen
        hour_correction = 4 * u.hourangle
        #calculate the possible ra range of the telescope for the given night
        if ra_range:
            self.ra_range = ra_range
        else:
            self.ra_range = ((self.dark_times[0] - hour_correction).to('deg').value, (self.dark_times[-1] + hour_correction).to('deg').value)
        if self.ra_range[0] > self.ra_range[1]:
            self.ra_range = self.ra_range[::-1]

        self.catalogs = []
        self.cat_names = []

        self.star_dict = {}
def test_gcrs_diffs():
    time = Time('J2017')
    gf = GCRS(obstime=time)
    sung = get_sun(time)  # should have very little vhelio

    # qtr-year off sun location should be the direction of ~ maximal vhelio
    qtrsung = get_sun(time-.25*u.year)

    # now we use those essentially as directions where the velocities should
    # be either maximal or minimal - with or perpendiculat to Earh's orbit
    msungr = CartesianRepresentation(-sung.cartesian.xyz).represent_as(SphericalRepresentation)
    suni = ICRS(ra=msungr.lon, dec=msungr.lat, distance=100*u.au,
                pm_ra_cosdec=0*u.marcsec/u.yr, pm_dec=0*u.marcsec/u.yr,
                radial_velocity=0*u.km/u.s)
    qtrsuni = ICRS(ra=qtrsung.ra, dec=qtrsung.dec, distance=100*u.au,
                   pm_ra_cosdec=0*u.marcsec/u.yr, pm_dec=0*u.marcsec/u.yr,
                   radial_velocity=0*u.km/u.s)

    # Now we transform those parallel- and perpendicular-to Earth's orbit
    # directions to GCRS, which should shift the velocity to either include
    # the Earth's velocity vector, or not (for parallel and perpendicular,
    # respectively).
    sung = suni.transform_to(gf)
    qtrsung = qtrsuni.transform_to(gf)

    # should be high along the ecliptic-not-sun sun axis and
    # low along the sun axis
    assert np.abs(qtrsung.radial_velocity) > 30*u.km/u.s
    assert np.abs(qtrsung.radial_velocity) < 40*u.km/u.s
    assert np.abs(sung.radial_velocity) < 1*u.km/u.s

    suni2 = sung.transform_to(ICRS)
    assert np.all(np.abs(suni2.data.differentials['s'].d_xyz) < 3e-5*u.km/u.s)
    qtrisun2 = qtrsung.transform_to(ICRS)
    assert np.all(np.abs(qtrisun2.data.differentials['s'].d_xyz) < 3e-5*u.km/u.s)
Example #5
0
def sun(date):
    """ To get the Sun's geocentric coordinates"""
    to = Time([date])
    ra = np.deg2rad((get_sun(to).ra.value)[0])
    dec = np.deg2rad((get_sun(to).dec.value)[0])
    r = (get_sun(to).distance.value)[0]
    x = r*np.cos(dec)*np.cos(ra)
    y = r*np.cos(dec)*np.sin(ra)
    z = r*np.sin(dec)
    return x,y,z
Example #6
0
def sunset_time(a = -12):
    phi = 33.7485
    l = 51.4257
    now = datetime.datetime.now()
    t = Time(Time.now(), scale='utc', location = (str(l) + 'd', str(phi) + 'd'))
    ra, dec = get_sun(t).ra.deg, get_sun(t).dec.deg
    ST = t.sidereal_time('apparent').hour * 15
    H_now = ST - ra
    H_set = degrees(acos((sin(radians(a))-sin(radians(phi) * sin(radians(dec)))) / (cos(radians(phi)) * cos(radians(dec)))))
    delta = H_set - H_now
    return now.hour + now.minute / 60 + now.second / 3600 + delta / 15
Example #7
0
def is_observable(pdat):
    """are objects observable between SUNSET and SUNRISE at PALOMAR on XXX to YYY?
    where "observable" means ZZZ
    follows http://www.astropy.org/astropy-tutorials/Coordinates.html
    returns minimum airmass
    """

    # create Coordinate object for catalog
    names = pdat['Name']
    ra, dec = [], []
    for i in range(len(names)):
        ra += [str(pdat['RAh'][i])+'h '+str(pdat['RAm'][i])+'m '+str(pdat['RAs'][i])+'s']
        dec += [str(pdat['DE-'][i])+str(pdat['DEd'][i])+'d '+str(pdat['DEm'][i])+'m '+str(pdat['DEs'][i])+'s']
    galcoords = coord.SkyCoord(ra, dec, frame='fk5')

    # location of observatory
    observing_location = coord.EarthLocation(lat='33.3563d', lon='-116.8648d', height=1712*u.m)

    # what times are 18-degree twilight?
    # create array of sun altitude starting @ at 6pm on Friday March 30
    observing_time = Time('2018-3-30 1:00')

    # find start time
    full_night_times = observing_time + np.linspace(0, 6, 100)*u.hour
    full_night_aa_frames = coord.AltAz(location=observing_location, obstime=full_night_times)
    full_night_sun_coos = coord.get_sun(full_night_times).transform_to(full_night_aa_frames)
    starttime = full_night_times[np.abs(full_night_sun_coos.alt.deg+18).argmin()]

    # find end time
    full_night_times = observing_time + np.linspace(6, 14, 100)*u.hour
    full_night_aa_frames = coord.AltAz(location=observing_location, obstime=full_night_times)
    full_night_sun_coos = coord.get_sun(full_night_times).transform_to(full_night_aa_frames)
    endtime = full_night_times[np.abs(full_night_sun_coos.alt.deg+18).argmin()]

    # now calculate MINIMUM AIR MASS between those times
    # first generate time array
    full_night_times = observing_time + np.linspace(0, 14, 250)*u.hour
    idx = (full_night_times > starttime) & (full_night_times < endtime)
    full_night_times = np.array(full_night_times)[idx].tolist()

    # now calculate airmass for all objects
    full_night_aa_frames = coord.AltAz(location=observing_location, obstime=full_night_times)
    min_airmass = []
    for co in galcoords:

        # require that they be above the horizon
        x = co.transform_to(full_night_aa_frames)
        idx = x.alt > 0
        if idx.sum() > 0:
            min_airmass += [np.min(x[idx].secz).value]
        else:
            min_airmass += [np.nan]

    return np.array(min_airmass)
Example #8
0
 def calculateSunPosition(self, ntimes):
     azi_ang = np.zeros((ntimes))
     elv_ang = np.zeros((ntimes))
     for tt, time in enumerate(self.times):
         sun_time = Time(time)  #UTC time
         sunpos = coord.AltAz(obstime=sun_time, location=self.location)
         alt = coord.get_sun(sun_time).transform_to(sunpos).alt
         azi = coord.get_sun(sun_time).transform_to(sunpos).az
         elv_ang[tt] = alt.degree
         azi_ang[tt] = azi.degree
     self.elevation_angle = elv_ang
     self.azimuth_angle = azi_ang
Example #9
0
def test_regression_4996():
    # this part is the actual regression test
    deltat = np.linspace(-12, 12, 1000)*u.hour
    times = Time('2012-7-13 00:00:00') + deltat
    suncoo = get_sun(times)
    assert suncoo.shape == (len(times),)

    # and this is an additional test to make sure more complex arrays work
    times2 = Time('2012-7-13 00:00:00') + deltat.reshape(10, 20, 5)
    suncoo2 = get_sun(times2)
    assert suncoo2.shape == times2.shape

    # this is intentionally not allclose - they should be *exactly* the same
    assert np.all(suncoo.ra.ravel() == suncoo2.ra.ravel())
Example #10
0
def test_regression_4996():
    # this part is the actual regression test
    deltat = np.linspace(-12, 12, 1000)*u.hour
    times = Time('2012-7-13 00:00:00') + deltat
    suncoo = get_sun(times)
    assert suncoo.shape == (len(times),)

    # and this is an additional test to make sure more complex arrays work
    times2 = Time('2012-7-13 00:00:00') + deltat.reshape(10, 20, 5)
    suncoo2 = get_sun(times2)
    assert suncoo2.shape == times2.shape

    # this is intentionally not allclose - they should be *exactly* the same
    assert np.all(suncoo.ra.ravel() == suncoo2.ra.ravel())
Example #11
0
    def _get_solar_altitudes(self, times, observer, targets):
        if not hasattr(observer, '_altaz_cache'):
            observer._altaz_cache = {}

        aakey = _make_cache_key(times, 'sun')

        if aakey not in observer._altaz_cache:
            try:
                if self.force_pressure_zero:
                    observer_old_pressure = observer.pressure
                    observer.pressure = 0

                # find solar altitude at these times
                altaz = observer.altaz(times, get_sun(times))
                altitude = altaz.alt
                # cache the altitude
                observer._altaz_cache[aakey] = dict(times=times,
                                                    altitude=altitude)
            finally:
                if self.force_pressure_zero:
                    observer.pressure = observer_old_pressure
        else:
            altitude = observer._altaz_cache[aakey]['altitude']

        return altitude
Example #12
0
 def drop_nml_due_to_suns_position(self):
   now=Time(datetime.utcnow(), scale='utc',location=self.obs,out_subfmt='date_hms')
   sun_aa= get_sun(now).transform_to(AltAz(obstime=now,location=self.obs))
   #
   sun_max_alt=-2.
   if sun_aa.alt.degree < sun_max_alt: # ToDo
     #self.lg.debug('drop_nml_due_to_suns_position: sun altitude: {} deg, below max: {} deg'.format(sun_aa.alt.degree,sun_max_alt))
     return
   
   #nml_aa_max_alt=max([x.nml_aa.alt.radian for x in self.nml if x.nml_aa is not None])
   for nml in self.nml:
     if nml.nml_aa is None:
       #self.lg.debug('drop_nml_due_to_suns_position: sun altitude: {} deg, below max: {} deg'.format(sun_aa.alt.degree,sun_max_alt))
       continue
             
     nml_aa=SkyCoord(az=nml.nml_aa.az.radian,alt=nml.nml_aa.alt.radian,unit=(u.radian,u.radian),frame='altaz',location=self.obs,obstime=now)
     sep= sun_aa.separation(nml_aa)
     # drop all within
     if sep.radian < self.sun_separation.radian:
       nml.nml_aa=None
       #self.lg.dbug('set None: {}, {}'.format(nml.nml_id,sep.degree))
       continue
     
     # drop all below sun
     if sun_aa.az.radian - self.sun_separation.radian < nml_aa.az.radian  < sun_aa.az.radian + self.sun_separation.radian:
       if nml_aa.alt.radian <  sun_aa.alt.radian:
         #self.lg.debug('set None below sun altitude: {}, {}'.format(nml.nml_id,nml_aa.alt.degree))
         nml.nml_aa=None
Example #13
0
def pickObsTime(coord,loc,t,t_res,objAltThres,sunAltThres=-18.):
    #coord is SkyCoord object; loc is EarthLocation object; t0 is Time object
    #t_res is time resolution in minutes. Suggest 5 or 10 minutes
    
    delta_t = np.linspace(0,24,24*60./t_res)*u.hour #divides a day into 5-minute chunks
    timeRange = t+delta_t
        
    altazframe = AltAz(obstime=timeRange, location=loc)
    sunaltazs = get_sun(timeRange).transform_to(altazframe)
    objaltazs = coord.transform_to(altazframe)
    
    sunDownTimes = delta_t[np.where(sunaltazs.alt < sunAltThres*u.deg)]
    objUpTimes = delta_t[np.where(objaltazs.alt > objAltThres*u.deg)]

    sunBools = sunaltazs.alt < sunAltThres*u.deg #True/False arrays
    objBools = objaltazs.alt > objAltThres*u.deg
    
    goodoffsets = delta_t[sunBools*objBools]
    size = np.size(goodoffsets)
    
    if size == 0:
        return pickObsTime(coord,loc,findNextOpportunity(t,coord,loc,t_res,objAltThres),
                           t_res,objAltThres)
    else:
        goodtimes = t+goodoffsets #picks out the times that satisfy both conditions
        return goodtimes[np.random.randint(0,size)]
    def can_observe(self):
        """Check for night and weather"""
        self.logger.info(self.current_time.iso)

        # start by checking for 12 degree twilight
        if coord.get_sun(self.current_time).transform_to(
                coord.AltAz(obstime=self.current_time,
                            location=P48_loc)).alt.is_within_bounds(
                upper=-12. * u.deg):
            if self.historical_observability_year is None:
                # don't use weather, just use 12 degree twilight
                return True
            else:
                is_observable = self.observability.check_historical_observability(
                    self.current_time, year=self.historical_observability_year)
                if not is_observable:
                    # optimization: fast-forward to start of next block
                    block_now = block_index(self.current_time)
                    block_end_time = block_index_to_time(block_now,
                        self.current_time, where='end')[0]
                    self.logger.info('Weathered out.  Fast forwarding to end of this block: {}'.format(
                        block_end_time.iso))
                    self.current_time = block_end_time

                return is_observable
        else:
            # daytime
            # optimization: fast-forward to sunset
            next_twilight = next_12deg_evening_twilight(self.current_time)
            self.logger.info('Fast forwarding to 12 deg twilight: {}'.format(
                next_twilight.iso))
            self.current_time = next_twilight
            return False
Example #15
0
    def _get_solar_altitudes(self, times, observer, targets):
        if not hasattr(observer, '_altaz_cache'):
            observer._altaz_cache = {}

        aakey = (tuple(times.jd), 'sun')

        if aakey not in observer._altaz_cache:
            try:
                if self.force_pressure_zero:
                    observer_old_pressure = observer.pressure
                    observer.pressure = 0

                # Broadcast the solar altitudes for the number of targets:
                altaz = observer.altaz(times, get_sun(times))
                altitude = altaz.alt
                altitude.resize(1, len(altitude))
                altitude = altitude + np.zeros((len(targets), 1))

                observer._altaz_cache[aakey] = dict(times=times,
                                                    altitude=altitude)
            finally:
                if self.force_pressure_zero:
                    observer.pressure = observer_old_pressure

        return observer._altaz_cache[aakey]
Example #16
0
def moon_phase_angle(time, location):
    """
    Calculate lunar orbital phase [radians].

    Parameters
    ----------
    time : `~astropy.time.Time`
        Time of observation

    location : `~astropy.coordinates.EarthLocation`
        Location of observer

    Returns
    -------
    i : float
        Phase angle of the moon [radians]
    """
    # TODO: cache these sun/moon SkyCoord objects
    sun = get_sun(time).transform_to(AltAz(location=location, obstime=time))
    moon = get_moon(time, location)
    # The line below should have worked, but needs a workaround.
    # TODO: once bug has been fixed, replace workaround with simpler version.
    # elongation = sun.separation(moon)
    elongation = Angle(angular_separation(moon.spherical.lon,
                                   moon.spherical.lat,
                                   sun.spherical.lon,
                                   sun.spherical.lat), u.deg)
    return np.arctan2(sun.distance*np.sin(elongation),
                      moon.distance - sun.distance*np.cos(elongation))
Example #17
0
    def drawSun(self,qp):
        x,y,w,h = self.sceneSize
        d = 6
        blackSunPen = QtGui.QPen(QtCore.Qt.black,5,QtCore.Qt.SolidLine)
        yellowSunPen = QtGui.QPen(QtCore.Qt.yellow,5,QtCore.Qt.SolidLine)
        qp.setPen(blackSunPen)
        qp.setFont(QtGui.QFont('Decorative', 6))

        # temp astropy for testing

        acre_road = EarthLocation(lat=55.9*u.deg,lon=-4.3*u.deg,height=45*u.m)
        now = Time(time.time(),format='unix')
        altazframe = AltAz(obstime=now, location=acre_road)
        sunaltaz = get_sun(now).transform_to(altazframe)
        alt = float(sunaltaz.alt.degree)
        az = float(sunaltaz.az.degree)

        #obs = ephem.Observer()
        #obs.lon, obs.lat = '-4.3', '55.9'   #glasgow                           
        #obs.date = ephem.now()
        #sun = ephem.Sun()
        #sun.compute(obs)
        #x = float(repr(sun.az))*(180/math.pi)
        #y = float(repr(sun.alt))*(180/math.pi)
        
        qp.drawText(self.degreeToPixelX(az+10),self.degreeToPixelY(alt),"Sun")
        qp.drawEllipse(self.degreeToPixelX(az),self.degreeToPixelY(alt),d,d)
        
        qp.setPen(yellowSunPen)
        qp.drawEllipse(self.degreeToPixelX(az),self.degreeToPixelY(alt),d-2,d-2)
Example #18
0
    def compute_sun_moon(self, trange, which='sun', dt_min=5):
        """
		compute the position of the sun/moon from the location of the observatory
		between the specified time interval.
			
		:param iterable trange: list of 2 elements specifying the time range (UTC). 
		Each of them can be either a `str` or `astropy.time.Time`.
		:param str which: celestial body to 'move'. Either 'sun' or 'moon'
		:param float dt_min: time resolution in minues.
		:returns: position of the sun/moon as observed from this location at the given time.
		:rtype astropy.coordinates.SkyCoord:
		"""
        start = time.time()

        # create the time object
        times = get_times(trange, dt_min)

        # define the observatory reference frame and move the sun
        obs_altaz = self.get_alt_az()
        if which.lower() == 'sun':
            skypos = get_sun(times).transform_to(obs_altaz)
        elif which.lower() == 'moon':
            skypos = get_moon(times).transform_to(obs_altaz)
        else:
            raise ValueError(
                "compute_sun_moon accepts either 'sun' or 'moon'. Got %s" %
                (which))
        end = time.time()
        self.logger.debug(
            "Computing %s motion from %s to %s (res: %.2f min, %d steps). Took %.2f sec"
            % (which, times.min().iso, times.max().iso, dt_min, len(times),
               (end - start)))
        return skypos
Example #19
0
def compute_sun_time_offset(LONG, LAT):
    EL = el.from_geodetic(LONG, LAT)
    sidingSpringEL = el.from_geodetic(149.071111, -31.273333)

    ### calculate time offset:
    time_offsets = np.linspace(0, 24, num=24 * 6)
    full_night_times = time.Time.now() + time_offsets * u.hour
    full_night_aa_frames = AltAz(location=EL, obstime=full_night_times)

    sun = ((coor.get_sun(full_night_times).transform_to(full_night_aa_frames)
            ).alt.deg)

    s = 0
    if sun[0] < -18:
        start = 0
    else:
        while sun[s] > -18:
            s = s + 1
        start = time_offsets[s]

    e = s + 1
    while sun[e] < -18:
        e = e + 1
    end = time_offsets[e]
    mid = time_offsets[s + (e - s) // 2]

    return [start, mid, end]
def compute_sun_time_offset(LONG,LAT):
    EL = el.from_geodetic( LONG , LAT )
    sidingSpringEL = el.from_geodetic(149.071111, -31.273333)

    ### calculate time offset:
    time_offsets = np.linspace(0, 24, num=24 * 6)
    full_night_times = time.Time.now() + time_offsets * u.hour
    full_night_aa_frames = AltAz(location=EL, obstime=full_night_times)

    sun = ((coor.get_sun(full_night_times).transform_to(full_night_aa_frames)).alt.deg)

    s = 0
    if sun[0] < -18:
        start = 0
    else:
        while sun[s] > -18:
            s = s + 1
        start = time_offsets[s]

    e = s + 1
    while sun[e] < -18:
        e = e + 1
    end = time_offsets[e]
    mid = time_offsets[s + (e - s) // 2]


    return [start, mid, end]
Example #21
0
File: v.py Project: willcode/gr-ata
def vlsr_correction(obs_timestamp, ra, dec):
    # hcro
    loc = EarthLocation.from_geodetic(lat=40.8172439*u.deg, \
                                      lon=-121.4698327*u.deg, \
                                      height=986.0*u.m)

    # Correction for the Sun's motion in our own Galaxy
    sun = get_sun(Time(obs_timestamp)).icrs
    psun = SkyCoord(ra="18:03:50.29", \
                    dec="+30:00:16.8", \
                    frame="icrs", unit=(u.hourangle, u.deg))
    vsun = -20.0 * u.km / u.s

    #Calculate the correction:
    T = Time('2010-03-26T15:16:33')

    # Source (Antenna) Direction. Make sure to transform to icrs
    SD = SkyCoord(ra=ra*u.hourangle, dec=dec*u.deg, frame='icrs', \
                  location = loc, obstime = T)

    # Calculate radial velocity and correct for Solar motion
    v = SD.cartesian.dot(
        psun.cartesian) * vsun - SD.radial_velocity_correction()

    return v.value
Example #22
0
    def can_observe(self):
        """Check for night and weather"""
        self.logger.info(self.current_time.iso)

        # start by checking for 12 degree twilight
        if coord.get_sun(self.current_time).transform_to(
                coord.AltAz(obstime=self.current_time,
                            location=P48_loc)).alt.is_within_bounds(
                                upper=-12. * u.deg):
            if self.historical_observability_year is None:
                # don't use weather, just use 12 degree twilight
                return True
            else:
                return self.observability.check_historical_observability(
                    self.current_time, year=self.historical_observability_year)
        else:
            # daytime
            # optimization: fast-forward to sunset
            next_twilight = next_12deg_evening_twilight(self.current_time)
            self.logger.info(
                'Fast forwarding to 12 deg twilight: {}'.format(next_twilight))
            # TODO: check if this works--may not be possible to change state
            # here
            self.current_time = next_twilight
            return False
Example #23
0
    def __init__(self, centers, time, indices=None):
        self.centers = centers
        self.time = time
        self.indices = indices

        # figure out where the sun is
        self.solar_coord = ac.get_sun(time)

        # subset by the provided indices, if specified
        if indices is None:
            lats = centers.lat
            lons = centers.lon
        else:
            lats = centers.lat[indices]
            lons = centers.lon[indices]

        # calculate the solar zenith angle at each pixel center.
        # neglect refraction and height above geoid.
        pixels = ac.EarthLocation(lons, lats, ellipsoid='GRS80')
        solar_vecs = self.solar_coord.transform_to(
            ac.AltAz(obstime=time, location=pixels))

        # mask out the non earth pixels, unless the user specified which pixels to calculate
        if indices is None:
            mask = ma.getmask(centers.lon)
        else:
            mask = None

        self.solar_zenith = ma.array(solar_vecs.zen.to_value(u.deg), mask=mask)
        self.solar_az = ma.array(solar_vecs.az.to_value(u.deg), mask=mask)
Example #24
0
    def can_observe(self):
        """Check for night and weather"""
        self.logger.info(self.current_time.iso)

        # start by checking for 12 degree twilight
        if coord.get_sun(self.current_time).transform_to(
                coord.AltAz(obstime=self.current_time,
                            location=P48_loc)).alt.is_within_bounds(
                upper=-12. * u.deg):
            if self.historical_observability_year is None:
                # don't use weather, just use 12 degree twilight
                return True
            else:
                return self.observability.check_historical_observability(
                    self.current_time, year=self.historical_observability_year)
        else:
            # daytime
            # optimization: fast-forward to sunset
            next_twilight = next_12deg_evening_twilight(self.current_time)
            self.logger.info('Fast forwarding to 12 deg twilight: {}'.format(
                next_twilight))
            # TODO: check if this works--may not be possible to change state
            # here
            self.current_time = next_twilight
            return False
Example #25
0
def separateap():
    for ctime in times:
        t = start + ctime
        frame = AltAz(obstime=t, location=berlin)
        sunaltaz = get_sun(t).transform_to(frame)
        if sunaltaz.alt < astronight:
            #sunaltazs.append(sunaltaz.alt)
            #print(sunaltaz)
            #print(sunaltaz.alt)
            #print('Moon phase angle:', moon_phase_angle(t, berlin))
            lum = moon_illumination(t, berlin)
            #print('Moon illumination:', moon_illumination(t, berlin))

            if lum < maxillum:
                delta.append(ctime)
                illum.append(lum)
                moon = get_moon(t, berlin)
                moonaltaz = moon.transform_to(frame)
                #print("Moon's Altitude = {0.alt:.2}".format(moonaltaz))
                moonaltazs.append(moonaltaz.alt)
                # print(moonaltaz.alt)
                if mod == 'graph':
                    pass
                elif mod == 'text' or mod == 'both':
                    if moonaltaz.alt > Latitude(minalt * u.deg):

                        dtxt.write('Date and time: ' + str(t) + '\n' +
                                   'Altitude: ' + str(moonaltaz.alt) + '\n' +
                                   'Illumination: ' + str(lum) + '\n \n')

    if mod == 'text':
        pass
    elif mod == 'graph' or mod == 'both':
        chobj(delta, illum, moonaltazs)
Example #26
0
    def _get_solar_altitudes(self, times, observer, targets):
        if not hasattr(observer, '_altaz_cache'):
            observer._altaz_cache = {}

        aakey = _make_cache_key(times, 'sun')

        if aakey not in observer._altaz_cache:
            try:
                if self.force_pressure_zero:
                    observer_old_pressure = observer.pressure
                    observer.pressure = 0

                # find solar altitude at these times
                altaz = observer.altaz(times, get_sun(times))
                altitude = altaz.alt
                # cache the altitude
                observer._altaz_cache[aakey] = dict(times=times,
                                                    altitude=altitude)
            finally:
                if self.force_pressure_zero:
                    observer.pressure = observer_old_pressure
        else:
            altitude = observer._altaz_cache[aakey]['altitude']

        return altitude
Example #27
0
def _get_sun_pos(met):
    """
    Convenience wrapper module for getting the solar position
    and north pole angle at a given time.

    Synax:
    ----------
    sun_pos, sun_np = _get_sun_pos(met)

    Parameters
    ----------
    met: Time for the observation, given in MJD.

    Returns
    -------

    sun_pos:
        Index of evtdata that passes the filtering.
    """
    # Deprecated from sunpy v1 onwards
    #     from sunpy.coordinates import get_sun_P
    #  Use new version instead
    from sunpy.coordinates import sun

    sun_time = astropy.time.Time(met, format='mjd')
    astro_sun_pos = get_sun(sun_time)

    # Get the center of the Sun, and assign it degrees.
    sun_pos = np.array([astro_sun_pos.ra.deg, astro_sun_pos.dec.deg]) * u.deg

    # Solar NP roll angle:
    #     sun_np = get_sun_P(last_met)
    sun_np = sun.P(met)

    return sun_pos, sun_np
Example #28
0
    def _get_solar_altitudes(self, times, observer, targets):
        if not hasattr(observer, '_altaz_cache'):
            observer._altaz_cache = {}

        aakey = (tuple(times.jd), 'sun')

        if aakey not in observer._altaz_cache:
            try:
                if self.force_pressure_zero:
                    observer_old_pressure = observer.pressure
                    observer.pressure = 0

                # find solar altitude at these times
                altaz = observer.altaz(times, get_sun(times))
                altitude = altaz.alt
                # cache the altitude
                observer._altaz_cache[aakey] = dict(times=times,
                                                    altitude=altitude)
            finally:
                if self.force_pressure_zero:
                    observer.pressure = observer_old_pressure
        else:
            altitude = observer._altaz_cache[aakey]['altitude']

        # Broadcast the solar altitudes for the number of targets.
        # Needs to be done after storing/fetching cache so we get the
        # correct shape if targets changes, but times does not.
        altitude = np.atleast_2d(altitude)
        altitude = altitude + np.zeros((len(targets), 1))
        return altitude
Example #29
0
    def calculate_az_el(self, name, time, alt_az_frame):
        """Calculates Azimuth and Elevation of the Specified Object at the Specified Time

        Parameters
        ----------
        name : str
            Name of the Object being Tracked
        time : Time
            Current Time (only necessary for Sun/Moon Ephemeris)
        alt_az_frame : AltAz
            AltAz Frame Object

        Returns
        -------
        (float, float)
            (az, el) Tuple
        """
        if name == "Sun":
            alt_az = get_sun(time).transform_to(alt_az_frame)
        elif name == "Moon":
            alt_az = get_moon(time, self.location).transform_to(alt_az_frame)
        else:
            alt_az = self.sky_coords[self.sky_coord_names[name]].transform_to(
                alt_az_frame)
        return alt_az.az.degree, alt_az.alt.degree
Example #30
0
def solarzenithangle(t, glat, glon, alt_m):
    """

    Parameters
    ----------

    t : datetime
      time of observation
    glat : float
      latitude
    glon : float
      longitude
    alt_m : float
      observer altitude [meters]

    Returns
    -------
    sza : float
      solar zenith angle [degrees]
    """

    obs = ac.EarthLocation(lat=glat * u.deg, lon=glon * u.deg, height=alt_m * u.m)
    times = astropy.time.Time(t, scale="ut1")
    sun = ac.get_sun(times)
    sunobs = sun.transform_to(ac.AltAz(obstime=times, location=obs))

    return 90.0 - sunobs.alt.degree
Example #31
0
def plot_sun(ax, obs_time):

    sun = get_sun(obs_time)
    sun = SkyCoord(sun.ra, sun.dec, frame='gcrs').transform_to('icrs')
    theta = sun.ra.radian - ax_rotation_angle - np.pi / 2
    r = 45 - sun.dec.value

    # body
    ax.scatter(theta, r, color='white', s=40, zorder=7)
    # halo
    ax.scatter(theta, r, color='white', s=40 * 25, zorder=7, alpha=0.03)
    ax.scatter(theta, r, color='white', s=40 * 20, zorder=7, alpha=0.05)
    ax.scatter(theta, r, color='white', s=40 * 9, zorder=7, alpha=0.05)
    # text
    curve_txt(theta + np.pi / 180 * 2,
              r + 10,
              'Sun',
              ax,
              weight='semibold',
              fontsize=6,
              color=colors['solar_name'],
              zorder=7,
              alpha=alphas['solar'])

    print('sun is plotted.')
Example #32
0
def moon_phase_angle(time, ephemeris=None):
    """
    Calculate lunar orbital phase in radians.

    Parameters
    ----------
    time : `~astropy.time.Time`
        Time of observation

    ephemeris : str, optional
        Ephemeris to use.  If not given, use the one set with
        `~astropy.coordinates.solar_system_ephemeris` (which is
        set to 'builtin' by default).

    Returns
    -------
    i : float
        Phase angle of the moon [radians]
    """
    # TODO: cache these sun/moon SkyCoord objects

    sun = get_sun(time)
    moon = get_moon(time, ephemeris=ephemeris)
    elongation = sun.separation(moon)
    return np.arctan2(sun.distance*np.sin(elongation),
                      moon.distance - sun.distance*np.cos(elongation))
Example #33
0
def _get_obs_param(ra, dec, mjd):
    ''' get observing condition given tileid and time of observation 
    '''
    from astropy.time import Time
    from astropy.coordinates import EarthLocation, SkyCoord, AltAz, get_sun, get_moon
    kpno = EarthLocation.of_site('kitt peak')

    # get observing conditions
    coord = SkyCoord(ra=ra * u.deg, dec=dec * u.deg)
    utc_time = Time(mjd, format='mjd')  # observed time (UTC)

    kpno_altaz = AltAz(obstime=utc_time, location=kpno)
    coord_altaz = coord.transform_to(kpno_altaz)

    airmass = coord_altaz.secz

    # sun
    sun = get_sun(utc_time)
    sun_altaz = sun.transform_to(kpno_altaz)
    sun_alt = sun_altaz.alt.deg
    sun_sep = sun.separation(coord).deg  # sun separation
    # moon
    moon = get_moon(utc_time)
    moon_altaz = moon.transform_to(kpno_altaz)
    moon_alt = moon_altaz.alt.deg
    moon_sep = moon.separation(coord).deg  #coord.separation(self.moon).deg

    elongation = sun.separation(moon)
    phase = np.arctan2(sun.distance * np.sin(elongation),
                       moon.distance - sun.distance * np.cos(elongation))
    moon_phase = phase.value
    moon_ill = (1. + np.cos(phase)) / 2.
    return airmass, moon_ill.value, moon_alt, moon_sep, sun_alt, sun_sep
Example #34
0
    def is_dark(self,
                horizon='observe',
                default_dark=-18 * u.degree,
                at_time=None):
        """If sun is below horizon.

        Args:
            horizon (str, optional): Which horizon to use, 'flat', 'focus', or
                'observe' (default).
            default_dark (`astropy.unit.Quantity`, optional): The default horizon
                for when it is considered "dark". Default is astronomical twilight,
                -18 degrees.
            at_time (None or `astropy.time.Time`, optional): Time at which to
                check if dark, defaults to now.

        Returns:
            bool: If it is dark or not.
        """
        if at_time is None:
            at_time = current_time()

        horizon_deg = self.get_config(f'location.{horizon}_horizon',
                                      default=default_dark)
        is_dark = self.observer.is_night(at_time, horizon=horizon_deg)

        self._local_sun_pos = self.observer.altaz(at_time,
                                                  target=get_sun(at_time)).alt
        self.logger.debug(
            f"Sun {self._local_sun_pos:.02f} > {horizon_deg} [{horizon}]")

        return is_dark
Example #35
0
def getSunPos(latitude, longitude, t):
    loc = coord.EarthLocation(lon=longitude * u.deg, lat=latitude * u.deg)
    now = Time(t)
    altaz = coord.AltAz(location=loc, obstime=now)
    sun = coord.get_sun(now)
    result = sun.transform_to(altaz)
    return result
Example #36
0
    def tileVisibility(self, t, gps=False):
        '''
		METHOD	:: This method takes as input the time (gps or mjd) of observation
				   and the observatory site name, and returns the alt and az of the 
				   ranked tiles. It also returns the alt and az of the sun.
		t	    :: The time at which observation is made. Default is mjd. If time is 
				   given in gps then set gps to True.

		'''
        if gps:
            time = Time(t, format='gps')  ### If time is given in GPS format
        else:
            time = Time(t,
                        format='mjd')  ### else time is assumed in mjd format
        altAz_tile = self.tiles.transform_to(
            AltAz(obstime=time, location=self.Observatory))
        altAz_sun = get_sun(time).transform_to(
            AltAz(obstime=time, location=self.Observatory))

        isSunDown = altAz_sun.alt.value < -18.0  ### Checks if it is past twilight.
        whichTilesUp = altAz_tile.alt.value > 20.0  ### Checks which tiles are up

        # 		return [altAz_tile, self.tileProbs, altAz_sun]
        return [
            self.tileIndices[whichTilesUp], self.tileProbs[whichTilesUp],
            altAz_sun
        ]
Example #37
0
def moon_phase_angle(time, location):
    """
    Calculate lunar orbital phase [radians].

    Parameters
    ----------
    time : `~astropy.time.Time`
        Time of observation

    location : `~astropy.coordinates.EarthLocation`
        Location of observer

    Returns
    -------
    i : float
        Phase angle of the moon [radians]
    """
    # TODO: cache these sun/moon SkyCoord objects
    sun = get_sun(time).transform_to(AltAz(location=location, obstime=time))
    moon = get_moon(time, location)
    # The line below should have worked, but needs a workaround.
    # TODO: once bug has been fixed, replace workaround with simpler version.
    # elongation = sun.separation(moon)
    elongation = Angle(
        angular_separation(moon.spherical.lon, moon.spherical.lat,
                           sun.spherical.lon, sun.spherical.lat), u.deg)
    return np.arctan2(sun.distance * np.sin(elongation),
                      moon.distance - sun.distance * np.cos(elongation))
def apparent_to_absolute(magapp, jd, ra, dec):
    """ Compute absolute magnitude from apparent magnitude
    
    Parameters
    ----------
    magapp: array
        Apparent magnitudes of alerts
    jd: array
        Times (JD) of alerts
    ra: array
        RA of alerts (deg)
    dec: array
        Dec of alerts (deg)
        
    Returns
    ----------
    magabs: array
        Absolute magnitude of alerts
    """
    sun_pos = get_sun(Time(jd, format='jd'))
    sun_dists = sun_pos.separation(SkyCoord(ra, dec, unit='deg')).rad
    
    denominator = np.sin(sun_dists) + (np.pi - sun_dists) * np.cos(sun_dists)
    magabs = magapp - 5. / 2. * np.log10(np.pi / denominator)
    return magabs, sun_dists
Example #39
0
 def get_sun_for_whole_day(self):
     tnow = datetime.now().date()
     today = datetime(tnow.year,
                      tnow.month,
                      tnow.day,
                      0,
                      0,
                      0,
                      tzinfo=self.tz)
     tomorrow = datetime(today.year,
                         today.month,
                         today.day,
                         23,
                         59,
                         59,
                         tzinfo=self.tz)
     time_arr = pd.date_range(start=today, end=tomorrow, freq='1min')
     frame = AltAz(obstime=time_arr, location=self.site)
     sun = get_sun(Time(time_arr))
     self.sunpos = pd.DataFrame()
     self.sunpos['ISO_AZ'] = time_arr.strftime("%Y-%m-%dT%H:%M:%S")
     self.sunpos['ISO_UTC'] = [x.isot[0:19] for x in Time(time_arr)]
     self.sunpos['MJD'] = [x.mjd for x in Time(time_arr)]
     self.sunpos['RA'] = sun.ra.value
     self.sunpos['RA_STR'] = sun.ra.to_string(u.hour,
                                              sep=':',
                                              precision=0,
                                              pad=True)
     self.sunpos['DEC_STR'] = sun.dec.to_string(u.deg,
                                                sep=':',
                                                precision=2,
                                                pad=True)
     self.sunpos['Az'] = sun.transform_to(frame).az.value
     self.sunpos['Alt'] = sun.transform_to(frame).alt.value
 def eff_night(cls,day_ini,earth_loc):
     """This method calculates the time range between the Sun being
     at -14deg below the horizon (begin and end of night), for a single
     night of observation
     Inputs
     - day_ini: noon of the initial day of observation, the date at which
     the night starts
     - earth_loc: location of the observing site, EarthLocation object
     Returns
     - array of astropy.time.core.Time elements, containing begin,
     middle, and end of the night
     """
     #sample the day by minute
     aux = day_ini + np.linspace(0,24,1440) * apy_u.hour
     #Sun position is in GCRS
     sun1 = apy_coord.get_sun(aux)
     altaz_frame = apy_coord.AltAz(obstime=aux,location=earth_loc)
     sun1_altaz = sun1.transform_to(altaz_frame)
     #transform AltAz to degrees
     vs,v1,v2,v3 = apy_coord.Angle(sun1_altaz.alt).signed_dms
     todeg = lambda w,x,y,z: w*(x + y/np.float(60) + z/np.float(60**2))
     vect = np.vectorize(todeg,otypes=["f4"])
     sun1_deg = vect(vs,v1,v2,v3)
     #Sun position closest to -14deg, use local minima
     idx_minim = signal.argrelextrema(np.abs(sun1_deg + 14),np.less)
     if idx_minim[0].shape[0] != 2:
         logger.error("Error setting Sun at -14deg")
         exit(1)
     #save time for begin, middle, and end of the night
     ntime = aux[idx_minim]
     midnight = apy_time.Time(apy_time.Time(np.mean(ntime.jd),format="jd"),
                             scale="utc",format="iso")
     ntime = np.insert(ntime,1,midnight)
     return ntime
Example #41
0
    def run(self):
        astroTime = Time.now()
        altazframe = AltAz(obstime=astroTime, location = EarthLocation(lat=49*u.deg, lon=15*u.deg, height=300*u.m))
        self.sunLoc = get_sun(astroTime).transform_to(altazframe).altaz

        print ""
        print "#############################"
        groups = rospy.get_param('/blind/')
        self.groups = groups
        self.group  = groups
        self.inTemp = float(self._sql('SELECT value FROM weather WHERE sensors_id = 6 order by id desc LIMIT 1;')[0][0])
        self.outLum = float(self._sql('SELECT AVG(value) FROM weather WHERE sensors_id = 4 and date > %i;' %(int(time.time() - int(rospy.get_param('/blind/global/min_light_delay', 30)*60))) )[0][0])
        
        for i, group_id in enumerate(sorted(groups)):
            print "=====", i, "====", group_id, "===="
            if 'group' in group_id:
                group = groups[group_id]
                if group['rw'] == 'd':
                    break

                rospy.loginfo(">> %s" % repr(group_id))
                if not self.isWindOk():
                    self.openBlind(group_id)
                    rospy.logerr("blind '%s' is in wind alarm" %group_id)
                    print "chyba vetru"

                else:
                    if self.isModeAuto(group_id):
                        print "vitr OK - automaticky mod - ",
                        rospy.loginfo("blind '%s' is in auto" %group_id)
                        if self.isMorgen(group_id):
                            print "je dopoledne - ",
                            self.areMorgenCondOk(group_id)
                        else:
                            print "je odpoledne - ",
                            self.areAfternoonCondOk(group_id)
                            #self.closeBlind(group_id)

                    elif self.isModeManual(group_id):
                        print "vitr OK - manualni mod - "
                        '''
                        print "pohyb", group['status'] != group['status_driver'], group['status'], group['status_driver']
                        #if group['status'] == 'open':
                        #    print "STATUS **********************",
                        #else:
                        #    print "STATUS ######################",
                        #if group['status_driver'] == 'open':
                        #    print "  DRIVER  **********************"
                        #else:
                        #    print " DRIVER ######################"
                        #if group['status'] != group['status_driver']:
                        #    self.moveBlind(group_id, group['status'])
                        '''


                    else:
                        print "vitr OK - chyba modu - ",
                        rospy.loginfo("blind '%s' is in dimised/manual" %group_id)
                        pass
                        print ""
Example #42
0
def calculate_elevation(tt, loc=_loc_blindern):
    sun_time = Time(tt)
    if ( (tt.hour == 0) and (tt.minute == 0) ):
        print(f'Calculate solar elevation angle for: {sun_time}')
    zen_ang = coord.get_sun(sun_time).transform_to(
        coord.AltAz(obstime=sun_time, location=loc)).alt.degree
    return zen_ang
Example #43
0
def moon_phase_angle(time, ephemeris=None):
    """
    Calculate lunar orbital phase in radians.

    Parameters
    ----------
    time : `~astropy.time.Time`
        Time of observation

    location : `~astropy.coordinates.EarthLocation`
        Location of observer

    ephemeris : str, optional
        Ephemeris to use.  If not given, use the one set with
        `~astropy.coordinates.solar_system_ephemeris` (which is
        set to 'builtin' by default).

    Returns
    -------
    i : float
        Phase angle of the moon [radians]
    """
    # TODO: cache these sun/moon SkyCoord objects

    sun = get_sun(time)
    moon = get_moon(time, ephemeris=ephemeris)
    elongation = sun.separation(moon)
    return np.arctan2(sun.distance * np.sin(elongation),
                      moon.distance - sun.distance * np.cos(elongation))
Example #44
0
    def geocentric(self, time):
        """ Calculates the position of the star, propagating the position using parallax and proper motion

        Parameters:
            time (float, Time): reference time to apply proper motion and calculate paralax.
        """
        try:
            time = Time(time)
        except:
            time = Time(time, format='jd', scale='utc')
        n_coord = self.barycentric(time)
        if self.coord.distance.unit.is_unity() or np.isnan(
                self.coord.distance):
            g_coord = n_coord
        else:
            sun = get_sun(time)
            g_coord = SkyCoord(*(n_coord.cartesian.xyz + sun.cartesian.xyz),
                               representation_type='cartesian')
            g_coord = g_coord.represent_as(SphericalRepresentation)
            g_coord = SkyCoord(g_coord.lon, g_coord.lat, g_coord.distance)

        if hasattr(self, 'offset'):
            star_frame = SkyOffsetFrame(origin=g_coord)
            new_pos = SkyCoord(lon=self.offset.d_lon_coslat,
                               lat=self.offset.d_lat,
                               frame=star_frame)
            return new_pos.transform_to(ICRS)

        return g_coord
Example #45
0
def get_sunriseset(t, lat, lon, height, refalt):
    loc = EarthLocation(lat=lat * u.deg, lon=lon * u.deg, height=height * u.m)
    t0 = Time(t, format='unix')
    print(t0.isot)
    # Compute solar position every 10 minutes
    t = Time(t0.mjd + np.arange(160) / 160.0, format='mjd', scale='utc')
    psun = get_sun(t)
    hor = psun.transform_to(AltAz(obstime=t, location=loc))

    # Interpolating function
    alt_diff = hor.alt.deg - refalt
    f = interpolate.interp1d(t.mjd, alt_diff)

    # Find sunrise/sunset
    sign = alt_diff[1:] * alt_diff[:-1]
    idx = np.where(sign < 0.0)[0]
    print(idx)
    for i in idx:
        # Set
        if alt_diff[i] > alt_diff[i + 1]:
            tset = Time(optimize.bisect(f, t[i].mjd, t[i + 1].mjd),
                        format='mjd',
                        scale='utc')
            # Rise
        else:
            trise = Time(optimize.bisect(f, t[i].mjd, t[i + 1].mjd),
                         format='mjd',
                         scale='utc')

    return trise.unix, tset.unix
Example #46
0
def get_sunriseset(t,lat,lon,height,refalt):
    loc=EarthLocation(lat=lat*u.deg,lon=lon*u.deg,height=height*u.m)
    t0=Time(t,format='unix')
    print(t0.isot)
    # Compute solar position every 10 minutes
    t=Time(t0.mjd+np.arange(160)/160.0,format='mjd',scale='utc')
    psun=get_sun(t)
    hor=psun.transform_to(AltAz(obstime=t,location=loc))
    
    # Interpolating function
    alt_diff=hor.alt.deg-refalt
    f=interpolate.interp1d(t.mjd,alt_diff)
    
    # Find sunrise/sunset
    sign=alt_diff[1:]*alt_diff[:-1]
    idx=np.where(sign<0.0)[0]
    print(idx)
    for i in idx:
        # Set
        if alt_diff[i]>alt_diff[i+1]:
            tset=Time(optimize.bisect(f,t[i].mjd,t[i+1].mjd),format='mjd',scale='utc')
            # Rise
        else:
            trise=Time(optimize.bisect(f,t[i].mjd,t[i+1].mjd),format='mjd',scale='utc')

    return trise.unix,tset.unix
Example #47
0
def observe():
    """Dummy function to check if tests / docs work.
    """
    time = Time.now()
    pos = get_sun(time)
    print('Current time: {}'.format(time))
    print('Sun location: {}'.format(pos))
    return time, pos
Example #48
0
    def run(self):
        astroTime = Time.now()
        altazframe = AltAz(obstime=astroTime, location = EarthLocation(lat=49*u.deg, lon=15*u.deg, height=300*u.m))
        self.sunLoc = get_sun(astroTime).transform_to(altazframe).altaz

        print ""
        print "#############################"
        groups = rospy.get_param('/blind/')
        self.groups = groups
        self.group  = groups
        self.inTemp = float(self._sql('SELECT value FROM weather WHERE sensors_id = 5 order by id desc LIMIT 1;')[0][0])
        self.outLum = float(self._sql('SELECT AVG(value) FROM weather WHERE sensors_id = 3 and date > %i;' %(int(time.time()) - int(rospy.get_param('/blind/global/min_light_delay', '30'))*60))[0][0])
        #int(time.time() -  (int(rospy.get_param('/blind/global/min_light_delay'))*60)) 
        #print self.outLum, 'SELECT AVG(value) FROM weather WHERE sensors_id = 3 and date > %i;' %
        #(int(time.time() - int(rospy.get_param('/blind/global/min_light_delay', 30)*60))) 
        for i, group_id in enumerate(sorted(groups)):
            print "=====", i, "====", group_id, "===="
            if 'group' in group_id:
                group = groups[group_id]
                if group['rw'] == 'd':
                    break

                if datetime.datetime.now().hour == 0:
                	if self.isTempMode(group_id):
                		rospy.set_param('/blind/'+group_id+"/modeTemp", False)
                		rospy.set_param('/blind/'+group_id+"/status", 'open')

                rospy.loginfo(">> %s" % repr(group_id))
                if not self.isWindOk():
                    self.openBlind(group_id)
                    rospy.logerr("blind '%s' is in wind alarm" %group_id)
                    print "chyba vetru"

                else:
                    if self.isModeAuto(group_id) and not self.isTempMode(group_id):
                        print "vitr OK - automaticky mod - ",
                        rospy.loginfo("blind '%s' is in auto" %group_id)
                        if self.isMorgen(group_id):
                            print "je dopoledne - ",
                            self.areMorgenCondOk(group_id)
                        else:
                            print "je odpoledne - ",
                            self.areAfternoonCondOk(group_id)
                            #self.closeBlind(group_id)
                    elif self.isTempMode(group_id):
                        print "vitr OK - automaticky mod v manual TEM rezimu "

                    elif self.isModeManual(group_id):
                        print "vitr OK - manualni mod - "
                        '''
                        '''


                    else:
                        print "vitr OK - chyba modu - ",
                        rospy.loginfo("blind '%s' is in dimised/manual" %group_id)
                        pass
                        print ""
Example #49
0
def solarPosition( gps, coord="C" ):
    '''
    '''
    timeObj = astropyTime( tconvert(int(gps), form="%Y-%m-%dT%H:%M:%S")+("%.3f"%(gps%1))[1:], format='isot', scale='utc')
    sun = astropyCoordinates.get_sun(timeObj)
    if coord=="C":
        return float(sun.dec.radian), float(sun.ra.radian)
    else:
        return float(sun.dec.radian), rotateRAC2E( float(sun.ra.radian), gps )
Example #50
0
def test_regression_3998():
    """
    Issue: https://github.com/astropy/astropy/issues/3998
    """
    time = Time('2012-01-01 00:00:00')
    assert time.isscalar

    sun = get_sun(time)
    assert sun.isscalar
    # in 3998, the above yields False - `sun` is a length-1 vector

    assert sun.obstime is time
Example #51
0
File: alcor.py Project: NGTS/Alcor
def dayOrNight():
	tnow=Time(dt.utcnow(),scale='utc')
	altazframe = AltAz(obstime=tnow, location=obsloc)
	sunaltaz = get_sun(tnow).transform_to(altazframe)
	sunalt=sunaltaz.alt.deg
	if sunalt <= sun_alt_limit:
		result='night'
	else:
		result='day'
	if args.v:
		print "%s - Sun altitude: %.2f - %s" % (dt.utcnow(),sunalt,result)
	return result
Example #52
0
    def is_dark(self):
        horizon = self.location.get('twilight_horizon', -18 * u.degree)

        time = current_time()
        is_dark = self.scheduler.is_night(time, horizon=horizon)

        self.logger.debug("Is dark (☉ < {}): {}".format(horizon, is_dark))
        if not is_dark:
            sun_pos = self.scheduler.altaz(time, target=get_sun(time)).alt
            self.logger.debug("Sun position: {:.02f}".format(sun_pos))

        return is_dark
Example #53
0
    def __init__(self, date=None, site='sutherland', targets=None, tz=2*u.h, **options): #res
        
        self.sitename = site.title()
        self.siteloc = EarthLocation.of_site(self.sitename)
        #TODO from time import timezone
        self.tz = tz                         #can you get this from the site location??
        #obs = Observer(self.siteloc)
        self.targets = {}
        self.trajectories = {}
        self.plots = OrderedDict()
        
        if not date:
            now = datetime.now()        #current local time
            #default behaviour of this function changes depending on the time of day.
            #if calling during early morning hours (at telescope) - let midnight refer to previous midnight
            #if calling during afternoon hours - let midnight refer to coming midnight
            d = now.day# + (now.hour > 7)    #FIXME =32??
            date = datetime(now.year, now.month, d, 0, 0, 0)
        else:
            raise NotImplementedError
        self.date = date
        
        self.midnight = midnight = Time(date) - tz    #midnight UTC in local time
        #TODO: efficiency here.  Dont need to plot everything over 
        self.hours = h = np.linspace(-12, 12, 250) * u.h      #variable time 
        self.t = t = midnight + h
        self.tp = t.plot_date
        self.frames = AltAz(obstime=t, location=self.siteloc)
        #self.tmoon
        
        #collect name, coordinates in dict

        if not targets is None:
            self.add_coordinates(targets)
        
        #Get sun, moon coordinates
        sun = get_sun(t)
        self.sun = sun.transform_to(self.frames)    #WARNING: slow!!!!
        #TODO: other bright stars / planets
        
        #get dawn / dusk times
        self.dusk, self.dawn = self.get_daylight()
        self.sunset, self.sunrise = self.dusk['sunset'], self.dawn['sunrise']
        
        #get moon rise/set times, phase, illumination etc...
        self.moon = get_moon(t).transform_to(self.frames)
        self.mooning = self.get_moonlight()
        self.moon_phase, self.moon_ill  = self.get_moon_phase()
        
        self.setup_figure()
        #HACK
        self.cid = self.figure.canvas.mpl_connect('draw_event', self._on_first_draw)
def test_gcrs_altaz_sunish(testframe):
    """
    Sanity-check that the sun is at a reasonable distance from any altaz
    """
    sun = get_sun(testframe.obstime)

    assert sun.frame.name == 'gcrs'

    # the .to(u.au) is not necessary, it just makes the asserts on failure more readable
    assert (EARTHECC - 1)*u.au < sun.distance.to(u.au) < (EARTHECC + 1)*u.au

    sunaa = sun.transform_to(testframe)
    assert (EARTHECC - 1)*u.au < sunaa.distance.to(u.au) < (EARTHECC + 1)*u.au
Example #55
0
def dark_window(tmrw=0,WHEN=''):
    # comments:
    # 
    #-------------------------------------------------
    if WHEN == '':
	t = datetime.utcnow()
    else:
	t = datetime.strptime(WHEN, "%Y-%m-%d %H:%M:%S")	
    time = Time(datetime(t.year, t.month, t.day+tmrw, 0, 0, 0)) #, scale='utc')

    delta_midnight = linspace(-400, 800, 121)*u.min
    time = time + delta_midnight
    
    # Geodetic coordinates of observatory (SPM)
    observatory = EarthLocation(
            lat=31.0453*u.deg, lon=-115.4667*u.deg, height=2790*u.m)
    
    # Alt/az reference frame at observatory
    frame = AltAz(obstime=time, location=observatory)
    
    # Where is the sun?
    sun_altaz = get_sun(time).transform_to(frame)
    
    wh = where((sun_altaz.alt <= -18*u.deg))[0]
    wh_sz = size(where(wh))
 
    night_strt = time[wh[0]]
    night_stop = time[wh[-1]]
    diff_1m = 0.0006944	
    tm_available = floor((night_stop.jd - night_strt.jd)*1./diff_1m) # in minutes	
    #print night_strt
    #print night_stop
    #
    if Time(t) > night_strt:
	#print "we've passed the night_start!"
	discard = timedelta(minutes=t.minute % 10,
                                 seconds=t.second,
                                 microseconds=t.microsecond)
    	t -= discard
    	if discard >= timedelta(minutes=5):
		t += timedelta(minutes=10)
       
    	t = Time(t)
	diff_10m = (t.jd - night_strt.jd)/0.007
	diff_10m = int(ceil(diff_10m)) 
	wh_sz = wh_sz - diff_10m
	night_strt = t
	if Time(t) < night_stop:
		tm_available = floor((night_stop.jd - t.jd)*1./diff_1m) # in minutes 

    return night_strt, wh_sz, tm_available    	
Example #56
0
def solarzenithangle(time: datetime, glat: float, glon: float, alt_m: float) -> tuple:
    """
    Input:

    t: scalar or array of datetime
    """
    time = totime(time)

    obs = EarthLocation(lat=glat*u.deg, lon=glon*u.deg, height=alt_m*u.m)
    times = Time(time, scale='ut1')
    sun = get_sun(times)
    sunobs = sun.transform_to(AltAz(obstime=times, location=obs))

    return 90 - sunobs.alt.degree, sun, sunobs
def test_gcrs_altaz_bothroutes(testframe):
    """
    Repeat of both the moonish and sunish tests above to make sure the two
    routes through the coordinate graph are consistent with each other
    """
    sun = get_sun(testframe.obstime)
    sunaa_viaicrs = sun.transform_to(ICRS).transform_to(testframe)
    sunaa_viaitrs = sun.transform_to(ITRS(obstime=testframe.obstime)).transform_to(testframe)

    moon = GCRS(MOONDIST_CART, obstime=testframe.obstime)
    moonaa_viaicrs = moon.transform_to(ICRS).transform_to(testframe)
    moonaa_viaitrs = moon.transform_to(ITRS(obstime=testframe.obstime)).transform_to(testframe)

    assert_allclose(sunaa_viaicrs.cartesian.xyz, sunaa_viaitrs.cartesian.xyz)
    assert_allclose(moonaa_viaicrs.cartesian.xyz, moonaa_viaitrs.cartesian.xyz)
Example #58
0
def isSolarOccluded( dec, ra, gps, dead_zone ):
    if isinstance( gps, (np.ndarray, list, tuple) ):
        theta_sun = np.empty_like( gps )
        phi_sun = np.empty_like( gps )
        for i, t in enumerate(gps):
            timeObj = astropyTime( tconvert(int(t), form="%Y-%m-%dT%H:%M:%S")+("%.3f"%(t%1))[1:], format='isot', scale='utc')

            ### get solar position in spherical coordinate
            sun = astropyCoordinates.get_sun(timeObj)
            theta_sun[i] = pi2 - sun.dec.radian
            phi_sun[i] = sun.ra.radian
    else:
        timeObj = astropyTime( tconvert(int(gps), form="%Y-%m-%dT%H:%M:%S")+("%.3f"%(gps%1))[1:], format='isot', scale='utc')

        ### get solar position in spherical coordinate
        sun = astropyCoordinates.get_sun(timeObj)
        theta_sun = pi2 - sun.dec.radian
        phi_sun = sun.ra.radian

    theta = pi2 - dec
    ### compute cos(theta) between all pixels and the sun in spherical coordinates
    cosdtheta = np.cos(theta_sun)*np.cos(theta) + np.sin(theta_sun)*np.sin(theta)*np.cos(phi_sun-ra)

    return cosdtheta > np.cos(dead_zone)
Example #59
0
 def compute_constraint(self, times, observer, targets):
     sun = get_sun(times)
     targets = [target.coord if hasattr(target, 'coord') else target
                for target in targets]
     solar_separation = Angle([sun.separation(target) for target in targets])
     if self.min is None and self.max is not None:
         mask = self.max > solar_separation
     elif self.max is None and self.min is not None:
         mask = self.min < solar_separation
     elif self.min is not None and self.max is not None:
         mask = ((self.min < solar_separation) &
                 (solar_separation < self.max))
     else:
         raise ValueError("No max and/or min specified in "
                          "SunSeparationConstraint.")
     return mask
Example #60
0
 def compute_constraint(self, times, observer, targets):
     sunaltaz = observer.altaz(times, get_sun(times))
     target_coos = [target.coord if hasattr(target, 'coord') else target
                for target in targets]
     target_altazs = [observer.altaz(times, coo) for coo in target_coos]
     solar_separation = Angle([sunaltaz.separation(taa) for taa in target_altazs])
     if self.min is None and self.max is not None:
         mask = self.max >= solar_separation
     elif self.max is None and self.min is not None:
         mask = self.min <= solar_separation
     elif self.min is not None and self.max is not None:
         mask = ((self.min <= solar_separation) &
                 (solar_separation <= self.max))
     else:
         raise ValueError("No max and/or min specified in "
                          "SunSeparationConstraint.")
     return mask