Beispiel #1
0
def deleteOldObservations(data_dir,
                          captured_dir,
                          archived_dir,
                          config,
                          duration=None):
    """ Deletes old observation directories to free up space for new ones.

    Arguments:
        data_dir: [str] Path to the RMS data directory which contains the Captured and Archived diretories
        captured_dir: [str] Captured directory name.
        archived_dir: [str] Archived directory name.
        config: [Configuration object]

    Keyword arguments:
        duration: [float] Duration of next video capturing in seconds. If None (by default), duration will
            be calculated for the next night.

    Return:
        [bool]: True if there's enough space for the next night's data, False if not.

    """

    captured_dir = os.path.join(data_dir, captured_dir)
    archived_dir = os.path.join(data_dir, archived_dir)

    ### Calculate the approximate needed disk space for the next night

    # If the duration of capture is not given
    if duration is None:

        # Time of next local noon
        #ct = datetime.datetime.utcnow()
        #noon_time = datetime.datetime(ct.year, ct.month, ct.date, 12)

        # Initialize the observer and find the time of next noon
        o = ephem.Observer()
        o.lat = config.latitude
        o.long = config.longitude
        o.elevation = config.elevation
        sun = ephem.Sun()

        sunrise = o.previous_rising(sun, start=ephem.now())
        noon_time = o.next_transit(sun, start=sunrise).datetime()

        # if ct.hour > 12:
        #     noon_time += datetime.timedelta(days=1)

        # Get the duration of the next night
        _, duration = captureDuration(config.latitude,
                                      config.longitude,
                                      config.elevation,
                                      current_time=noon_time)

    # Calculate the approx. size for the night night
    next_night_bytes = (duration *
                        config.fps) / 256 * config.width * config.height * 4

    # Always leave at least 2 GB free for archive
    next_night_bytes += config.extra_space_gb * (1024**3)

    ######

    # If there's enough free space, don't do anything
    if availableSpace(data_dir) > next_night_bytes:
        return True

    # Intermittently delete captured and archived directories until there's enough free space
    prev_available_space = availableSpace(data_dir)
    nothing_deleted_count = 0
    while True:

        # Delete one captured directory
        captured_dirs_remaining = deleteNightFolders(captured_dir, config)

        # Break the there's enough space
        if availableSpace(data_dir) > next_night_bytes:
            break

        # Delete one archived directory
        archived_dirs_remaining = deleteNightFolders(archived_dir, config)

        # Break the there's enough space
        if availableSpace(data_dir) > next_night_bytes:
            break

        # If no folders left to delete, try to delete archived files
        if (len(captured_dirs_remaining)
                == 0) and (len(archived_dirs_remaining) == 0):

            archived_files_remaining = deleteFiles(archived_dir, config)

            # If there's nothing left to delete, return False
            if len(archived_files_remaining) == 0:
                return False

        # Break the there's enough space
        if availableSpace(data_dir) > next_night_bytes:
            break

        # If nothing was deleted in this loop,
        if availableSpace(data_dir) == prev_available_space:
            nothing_deleted_count += 1

        else:
            nothing_deleted_count = 0

        # If nothing was deleted for 100 loops, indicate that no more space can be freed
        if nothing_deleted_count >= 100:
            return False

        prev_available_space = availableSpace(data_dir)

    return True
Beispiel #2
0
    o_log.insert(0, str('  ' + event + ' | ' + details))
    o_log.insert(0, now + ' - ' + action)
    with open(today + '_ObservingLog.txt', 'a') as f:
        f.write(now + ' - ' + action + ' | ' + event + ' | ' + details + '\n')
    return


# Window Options
root = tk.Tk()
root.title("RhoPi Telescope Pointing v0.0.5 (alpha)")
default_font = tkFont.nametofont("TkDefaultFont")
default_font.configure(size=11, family='system')
# print tkFont.families()

# Observer Setup
rho = ephem.Observer()
rho.lon, rho.lat = '-82.586203', '29.400249'

# --- Section Frames Column Configuration --- #
c = tk.Frame(root)  # c is for catalog section widgets
c.grid(column=0, row=0, sticky='N')
o = tk.Frame(root)  # a is for align section widgets
o.grid(column=1, row=0, sticky='N')
s = tk.Frame(root)  # s is for information section widgets
s.grid(column=2, row=0, sticky='N')

# --- All widget initializations and names --- #

# Target Section Widgets
c_fill = [
    tk.StringVar(c, '--None--'),
Beispiel #3
0
def mjd2ut(mjd):
    obs = ephem.Observer()
    doff = ephem.Date(0) - ephem.Date('1858/11/17')
    djd = mjd - doff
    obs.date = djd
    return obs.date
Beispiel #4
0
def params_struct(dateobs,
                  tobs=None,
                  filt=['r'],
                  exposuretimes=[60.0],
                  mindiff=30.0 * 60.0,
                  probability=0.9,
                  tele='ZTF',
                  airmass=2.5,
                  schedule_type='greedy',
                  doReferences=True,
                  doUsePrimary=False,
                  filterScheduleType='block',
                  schedule_strategy='tiling'):

    growthpath = os.path.dirname(growth.__file__)
    config_directory = os.path.join(growthpath, 'too', 'config')
    tiling_directory = os.path.join(growthpath, 'too', 'tiling')

    catalogpath = os.path.join('too', 'catalog')
    try:
        app.open_instance_resource('%s/CLU.hdf5' % catalogpath)
        catalog_directory = app.instance_path
    except IOError:
        catalog_directory = os.path.join(growthpath, catalogpath)

    params = {}
    params["config"] = {}
    config_files = glob.glob("%s/*.config" % config_directory)
    for config_file in config_files:
        telescope = config_file.split("/")[-1].replace(".config", "")
        params["config"][telescope] =\
            gwemopt.utils.readParamsFromFile(config_file)
        params["config"][telescope]["telescope"] = telescope
        if "tesselationFile" in params["config"][telescope]:
            params["config"][telescope]["tesselationFile"] =\
                os.path.join(config_directory,
                             params["config"][telescope]["tesselationFile"])
            tesselation_file = params["config"][telescope]["tesselationFile"]
            if not os.path.isfile(tesselation_file):
                if params["config"][telescope]["FOV_type"] == "circle":
                    gwemopt.tiles.tesselation_spiral(
                        params["config"][telescope])
                elif params["config"][telescope]["FOV_type"] == "square":
                    gwemopt.tiles.tesselation_packing(
                        params["config"][telescope])

            params["config"][telescope]["tesselation"] =\
                np.loadtxt(params["config"][telescope]["tesselationFile"],
                           usecols=(0, 1, 2), comments='%')

        if "referenceFile" in params["config"][telescope]:
            params["config"][telescope]["referenceFile"] =\
                os.path.join(config_directory,
                             params["config"][telescope]["referenceFile"])
            refs = table.unique(
                table.Table.read(params["config"][telescope]["referenceFile"],
                                 format='ascii',
                                 data_start=2,
                                 data_end=-1)['field', 'fid'])
            reference_images =\
                {group[0]['field']: group['fid'].astype(int).tolist()
                 for group in refs.group_by('field').groups}
            reference_images_map = {1: 'g', 2: 'r', 3: 'i', 4: 'z', 5: 'J'}
            for key in reference_images:
                reference_images[key] = [
                    reference_images_map.get(n, n)
                    for n in reference_images[key]
                ]
            params["config"][telescope]["reference_images"] = reference_images

        observer = ephem.Observer()
        observer.lat = str(params["config"][telescope]["latitude"])
        observer.lon = str(params["config"][telescope]["longitude"])
        observer.horizon = str(-12.0)
        observer.elevation = params["config"][telescope]["elevation"]
        params["config"][telescope]["observer"] = observer

    params["skymap"] = ""
    params["gpstime"] = -1
    params["outputDir"] = "output/%s" % dateobs.strftime("%Y%m%dT%H%M%S")
    params["tilingDir"] = tiling_directory
    params["event"] = ""
    params["telescopes"] = [tele]
    if schedule_strategy == "catalog":
        params["tilesType"] = "galaxy"
        params["catalogDir"] = catalog_directory
        params["galaxy_catalog"] = "CLU"
        params["galaxy_grade"] = "S"
        params["writeCatalog"] = False
        params["catalog_n"] = 1.0
        params["powerlaw_dist_exp"] = 1.0
        params["doChipGaps"] = False
    elif schedule_strategy == "tiling":
        params["tilesType"] = "moc"
        if tele == "ZTF":
            params["doChipGaps"] = True
        else:
            params["doChipGaps"] = False
    params["scheduleType"] = schedule_type
    params["timeallocationType"] = "powerlaw"
    params["nside"] = 512
    params["powerlaw_cl"] = probability
    params["powerlaw_n"] = 1.0
    params["powerlaw_dist_exp"] = 0.0

    params["doPlots"] = False
    params["doMovie"] = False
    params["doObservability"] = True
    params["do3D"] = False

    params["doFootprint"] = False
    params["footprint_ra"] = 30.0
    params["footprint_dec"] = 60.0
    params["footprint_radius"] = 10.0

    params["airmass"] = airmass

    params["doCommitDatabase"] = True
    params["doRequestScheduler"] = False
    params["dateobs"] = dateobs
    params["doEvent"] = False
    params["doSkymap"] = False
    params["doFootprint"] = False
    params["doDatabase"] = True
    params["doReferences"] = doReferences
    params["doUsePrimary"] = doUsePrimary
    params["doSplit"] = False
    params["doParallel"] = False
    params["doUseCatalog"] = False

    if tele in ["KPED", "GROWTH-India"]:
        params["doMinimalTiling"] = True
    else:
        params["doMinimalTiling"] = False
    params["doIterativeTiling"] = False
    params["galaxies_FoV_sep"] = 1.0

    if params["doEvent"]:
        params["skymap"], eventinfo = gwemopt.gracedb.get_event(params)
        params["gpstime"] = eventinfo["gpstime"]
        event_time = time.Time(params["gpstime"], format='gps', scale='utc')
        params["dateobs"] = event_time.iso
    elif params["doSkymap"]:
        event_time = time.Time(params["gpstime"], format='gps', scale='utc')
        params["dateobs"] = event_time.iso
    elif params["doFootprint"]:
        params["skymap"] = gwemopt.footprint.get_skymap(params)
        event_time = time.Time(params["gpstime"], format='gps', scale='utc')
        params["dateobs"] = event_time.iso
    elif params["doDatabase"]:
        event_time = time.Time(params["dateobs"],
                               format='datetime',
                               scale='utc')
        params["gpstime"] = event_time.gps
    else:
        raise ValueError('Need to enable --doEvent, --doFootprint, '
                         '--doSkymap, or --doDatabase')

    if tobs is None:
        now_time = time.Time.now()
        timediff = now_time.gps - event_time.gps
        timediff_days = timediff / 86400.0
        params["Tobs"] = np.array([timediff_days, timediff_days + 1])
    else:
        params["Tobs"] = tobs

    params["doSingleExposure"] = True
    if filterScheduleType == "block":
        params["doAlternatingFilters"] = True
    else:
        params["doAlternatingFilters"] = False
    params["filters"] = filt
    params["exposuretimes"] = exposuretimes
    params["mindiff"] = mindiff

    params = gwemopt.segments.get_telescope_segments(params)
    params = gwemopt.utils.params_checker(params)

    if params["doPlots"]:
        if not os.path.isdir(params["outputDir"]):
            os.makedirs(params["outputDir"])

    return params
Beispiel #5
0
    bodies = []
    for i in range(len(kbos)):
        kbo = eph.EllipticalBody()
        (a, e, inc, a0, a1, a2, djdM, djd, H, m) = kbos[i]
        kbo._a = a
        kbo._e = e
        kbo._inc = inc
        kbo._M = a0
        kbo._Om = a1
        kbo._om = a2
        kbo._epoch_M = djdM
        kbo._epoch = djd
        bodies.append(kbo)
        del kbo

    observer = eph.Observer()
    observer.lon = '204:31:40.1'
    observer.lat = '19:49:34.0'
    observer.elevation = 4212

    mask_files = glob.glob(masksDir + '/mask*fits')
    mask_files.sort()

    dirInd = '02530'
    if dirInd == '02531':
        dirStr = 'rocketdata/DEC2018'
    elif dirInd in ['02532', '02533', '02534']:
        dirStr = 'Hammer/DEC2018'
    else:
        dirStr = 'Thumber/DEC2018_also'
Beispiel #6
0
    if len(n) >= 1 and n[0].nodeType == n[0].TEXT_NODE:
        return n[0].data
    return None


if __name__ == '__main__':
    filename = sys.argv[1]
    waypoints = read_track_file_GPX(filename)
    if not waypoints:
        print("No waypoints in", filename)
        sys.exit(1)

    print("First waypoint:", waypoints[0])
    observerPoint = waypoints[0]

    observer = ephem.Observer()
    # Observer will take degrees as a string, but if you pass it floats
    # it expects radians, though that's undocumented.
    observer.lat = observerPoint[1] * ephem.degree
    observer.lon = observerPoint[2] * ephem.degree
    if len(observerPoint) > 3:
        observer.elevation = observerPoint[3]
    else:
        observer.elevation = 500.0  # meters
    observer.name = "%s %f, %f, %f" % (observerPoint[0], observer.lon,
                                       observer.lat, observer.elevation)
    print(observer)
    print()

    find_alignments(observer, waypoints)
Beispiel #7
0
                           passwd=DBpasswd,
                           db=DBname)
    print "MySQL Database:", DBname, " at Host:", DBhost
else:
    import sqlite3  # the SQL data base routines^M
    conn = sqlite3.connect(DBase)  # connect with the database
    print "SQLITE3 Database: ", DBase
# --------------------------------------#

curs = conn.cursor()  # set the cursor
#
#-----------------------------------------------------------------
# Initialise API for computing sunrise and sunset
#-----------------------------------------------------------------
#
location = ephem.Observer()
location.pressure = 0
location.horizon = '-0:34'  # Adjustments for angle to horizon

location.lat, location.lon = location_latitude, location_longitude
date = datetime.now()
next_sunrise = location.next_rising(ephem.Sun(), date)
next_sunset = location.next_setting(ephem.Sun(), date)
print "Sunrise today is at: ", next_sunrise, " UTC "
print "Sunset  today is at: ", next_sunset, " UTC "
print "Time now is: ", date, " Local time"

prtreq = sys.argv[1:]
if prtreq and prtreq[0] == 'prt':
    prt = True
else:
###This is a code meant to check weather and sun position to see if the dome
###should be open or not. Uses observing condition cutoffs from main minerva code

import ephem, time
from win32com.client import Dispatch 
import should_be_open

##Here, we define the location of he MINERVA telescope, used for calculating 
##locations, etc.

hopkins = ephem.Observer()
hopkins.lon='-110:52:44.6'
hopkins.lat='31:40:49.4'
hopkins.elevation= 2345.

dome=Dispatch("ascom.astrohavenpw.dome")
dome.Connected=True

i=0.

##This will run like a loop. Check a bunch of things, see if the telescope 
##should be open open or closed, take action.
while i == 0:
    hopkins.date=ephem.now()
    Sun=ephem.Sun(hopkins)
    sunalt=(float(repr(Sun.alt)))*57.3
    
#Dome shojuld be closed if Sun is more than -5, let's say. 
#This loop checks to make sure that the dome is closed, and if it isn't
#closes. Check and seems to work.  
    if  sunalt >= -5.0:
Beispiel #9
0
def calculateEphemerides(parFile):
    '''
        :INPUTS:
        parFile	 --	  path to the parameter file
        '''

    #parFile = 'umo.par'

    '''Parse the observatory .par file'''
    parFileText = open(os.path.join(os.path.dirname(oscaar.__file__),'extras','eph','observatories',parFile),'r').read().splitlines()

    def returnBool(value):
        '''Return booleans from strings'''
        if value == 'True': return True
        elif value == 'False': return False

    for line in parFileText:
        parameter = line.split(':')[0]
        if len(line.split(':')) > 1:
            value = line.split(':')[1].strip()
            if parameter == 'name': observatory_name = value
            elif parameter == 'latitude': observatory_latitude = value
            elif parameter == 'longitude': observatory_longitude = value
            elif parameter == 'elevation': observatory_elevation = float(value)
            elif parameter == 'temperature': observatory_temperature = float(value)
            elif parameter == 'min_horizon': observatory_minHorizon = value
            elif parameter == 'start_date': startSem = gd2jd(eval(value))
            elif parameter == 'end_date': endSem = gd2jd(eval(value))
            elif parameter == 'v_limit': v_limit = float(value)
            elif parameter == 'depth_limit': depth_limit = float(value)
            elif parameter == 'calc_transits': calcTransits = returnBool(value)
            elif parameter == 'calc_eclipses': calcEclipses = returnBool(value)
            elif parameter == 'html_out': htmlOut = returnBool(value)
            elif parameter == 'text_out': textOut = returnBool(value)
            elif parameter == 'twilight': twilightType = value

    from oscaar.extras.knownSystemParameters import getLatestParams
    exoplanetDB = getLatestParams.downloadAndPickle()

    ''' Set up observatory parameters '''
    observatory = ephem.Observer()
    observatory.lat =  observatory_latitude#'38:58:50.16'	## Input format-  deg:min:sec  (type=str)
    observatory.long = observatory_longitude#'-76:56:13.92' ## Input format-  deg:min:sec  (type=str)
    observatory.elevation = observatory_elevation   # m
    observatory.temp = observatory_temperature	  ## Celsius 
    observatory.horizon = observatory_minHorizon	## Input format-  deg:min:sec  (type=str)

    def trunc(f, n):
        '''Truncates a float f to n decimal places without rounding'''
        slen = len('%.*f' % (n, f))
        return str(f)[:slen]

    def RA(planet):
        '''Type: str, Units:  hours:min:sec'''
        return exoplanetDB[planet]['RA_STRING']
    def dec(planet):
        '''Type: str, Units:  deg:min:sec'''
        return exoplanetDB[planet]['DEC_STRING']
    def period(planet):
        '''Units:  days'''
        return np.float64(exoplanetDB[planet]['PER'])
    def epoch(planet):
        '''Tc at mid-transit. Units:  days'''
        if exoplanetDB[planet]['TT'] == '': return 0.0
        else: return np.float64(exoplanetDB[planet]['TT'])
    def duration(planet):
        '''Transit/eclipse duration. Units:  days'''
        if exoplanetDB[planet]['T14'] == '': return 0.0
        else: return float(exoplanetDB[planet]['T14'])
    def V(planet):
        '''V mag'''
        if exoplanetDB[planet]['V'] == '': return 0.0
        else: return float(exoplanetDB[planet]['V'])
    def KS(planet):
        '''KS mag'''
        if exoplanetDB[planet]['KS'] == '': return 0.0
        else: return float(exoplanetDB[planet]['KS'])

    def depth(planet):
        '''Transit depth'''
        if exoplanetDB[planet]['DEPTH'] == '': return 0.0
        else: return float(exoplanetDB[planet]['DEPTH'])

    def transitBool(planet):
        '''True if exoplanet is transiting, False if detected by other means'''
        if exoplanetDB[planet]['TRANSIT'] == '0': return 0
        elif exoplanetDB[planet]['TRANSIT'] == '1': return 1
    ########################################################################################
    ########################################################################################

    def datestr2list(datestr):
        ''' Take strings of the form: "2013/1/18 20:08:18" and return them as a
            tuple of the same parameters'''
        year,month,others = datestr.split('/')
        day, time = others.split(' ')
        hour,minute,sec = time.split(':')
        return (int(year),int(month),int(day),int(hour),int(minute),int(sec))

    def list2datestr(inList):
        '''Converse function to datestr2list'''
        inList = map(str,inList)
        return inList[0]+'/'+inList[1]+'/'+inList[2]+' '+inList[3].zfill(2)+':'+inList[4].zfill(2)+':'+inList[5].zfill(2)

    def list2datestrCSV(inList):
        '''Converse function to datestr2list'''
        inList = map(str,inList)
        return inList[0]+'/'+inList[1]+'/'+inList[2]+','+inList[3].zfill(2)+':'+inList[4].zfill(2)+':'+inList[5].zfill(2)


    def list2datestrHTML(inList,alt,direction):
        '''Converse function to datestr2list'''
        inList = map(str,inList)
        #return inList[1].zfill(2)+'/'+inList[2].zfill(2)+'<br />'+inList[3].zfill(2)+':'+inList[4].zfill(2)
        return inList[1].zfill(2)+'/<strong>'+inList[2].zfill(2)+'</strong>, '+inList[3].zfill(2)+':'+inList[4].split('.')[0].zfill(2)+'<br /> '+alt+'&deg; '+direction

    def simbadURL(planet):
        if exoplanetDB[planet]['SIMBADURL'] == '': return 'http://simbad.harvard.edu/simbad/'
        else: return exoplanetDB[planet]['SIMBADURL']

    def RADecHTML(planet):
        return '<a href="'+simbadURL(planet)+'">'+RA(planet).split('.')[0]+'<br />'+dec(planet).split('.')[0]+'</a>'

    def constellation(planet):
        return exoplanetDB[planet]['Constellation']

    def orbitReference(planet):
        return exoplanetDB[planet]['TRANSITURL']

    def nameWithLink(planet):
        return '<a href="'+orbitReference(planet)+'">'+planet+'</a>'

    def mass(planet):
        if exoplanetDB[planet]['MASS'] == '': return '---'
        else: return trunc(float(exoplanetDB[planet]['MASS']),2)

    def semimajorAxis(planet):
        #return trunc(0.004649*float(exoplanetDB[planet]['AR'])*float(exoplanetDB[planet]['RSTAR']),3)   ## Convert from solar radii to AU
        return trunc(float(exoplanetDB[planet]['SEP']),3)

    def radius(planet):
        return trunc(float(exoplanetDB[planet]['R']),2) ## Convert from solar radii to Jupiter radii

    def midTransit(Tc, P, start, end):
        '''Calculate mid-transits between Julian Dates start and end, using a 2500 
            orbital phase kernel since T_c (for 2 day period, 2500 phases is 14 years)
            '''
        Nepochs = np.arange(0,2500,dtype=np.float64)
        transitTimes = Tc + P*Nepochs
        transitTimesInSem = transitTimes[(transitTimes < end)*(transitTimes > start)]
        return transitTimesInSem

    def midEclipse(Tc, P, start, end):
        '''Calculate mid-eclipses between Julian Dates start and end, using a 2500 
            orbital phase kernel since T_c (for 2 day period, 2500 phases is 14 years)
            '''
        Nepochs = np.arange(0,2500,dtype=np.float64)
        transitTimes = Tc + P*(0.5 + Nepochs)
        transitTimesInSem = transitTimes[(transitTimes < end)*(transitTimes > start)]
        return transitTimesInSem

    '''Choose which planets from the database to include in the search, 
        assemble a list of them.'''
    planets = []
    for planet in exoplanetDB:
        if V(planet) != 0.0 and depth(planet) != 0.0 and float(V(planet)) <= v_limit and float(depth(planet)) >= depth_limit and transitBool(planet):
            planets.append(planet)

    if calcTransits: transits = {}
    if calcEclipses: eclipses = {}
    for day in np.arange(startSem,endSem+1):
        if calcTransits: transits[str(day)] = []
        if calcEclipses: eclipses[str(day)] = []
    planetsNeverUp = []


    def azToDirection(az):
        az = float(az)
        if (az >= 0 and az < 22.5) or (az >= 337.5 and az < 360): return 'N'
        elif az >= 22.5 and az < 67.5:  return 'NE'
        elif az >= 67.5 and az < 112.5:  return 'E'
        elif az >= 112.5 and az < 157.5:  return 'SE'
        elif az >= 157.5 and az < 202.5:  return 'S'
        elif az >= 202.5 and az < 247.5:  return 'SW'
        elif az >= 247.5 and az < 292.5:  return 'W'	
        elif az >= 292.5 and az < 337.5:  return 'NW'

    def ingressEgressAltAz(planet,observatory,ingress,egress):
        altitudes = []
        directions = []
        for time in [ingress,egress]:
            observatory.date = list2datestr(jd2gd(time))
            star = ephem.FixedBody()
            star._ra = ephem.hours(RA(planet))
            star._dec = ephem.degrees(dec(planet))
            star.compute(observatory)
            altitudes.append(str(ephem.degrees(star.alt)).split(":")[0])
            directions.append(azToDirection(str(ephem.degrees(star.az)).split(":")[0]))
        ingressAlt,egressAlt = altitudes
        ingressDir,egressDir = directions
        return ingressAlt,ingressDir,egressAlt,egressDir

    def aboveHorizonForEvent(planet,observatory,ingress,egress):
        altitudes = []
        for time in [ingress,egress]:
            observatory.date = list2datestr(jd2gd(time))
            star = ephem.FixedBody()
            star._ra = ephem.hours(RA(planet))
            star._dec = ephem.degrees(dec(planet))
            star.compute(observatory)
            #altitudes.append(str(ephem.degrees(star.alt)).split(":")[0])
            altitudes.append(float(repr(star.alt))/(2*np.pi) * 360)	## Convert altitudes to degrees
        if altitudes[0] > 0 and altitudes[1] > 0: return True
        else: return False

    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

    for planet in planets:		
        '''Compute all of the coming transits and eclipses for a long time out'''
        allTransitEpochs = midTransit(epoch(planet),period(planet),startSem,endSem)
        allEclipseEpochs = midEclipse(epoch(planet),period(planet),startSem,endSem)
        for day in np.arange(startSem,endSem+1,1.0):
            try:
                '''For each day, gather the transits and eclipses that happen'''
                transitEpochs = allTransitEpochs[(allTransitEpochs <= day+0.5)*(allTransitEpochs > day-0.5)]
                eclipseEpochs = allEclipseEpochs[(allEclipseEpochs <= day+0.5)*(allEclipseEpochs > day-0.5)]
                if calcTransits and len(transitEpochs) != 0:
                    transitEpoch = transitEpochs[0]
                    ingress = transitEpoch-duration(planet)/2
                    egress = transitEpoch+duration(planet)/2
                    
                    ''' Calculate positions of host stars'''
                    star = ephem.FixedBody()
                    star._ra = ephem.hours(RA(planet))
                    star._dec = ephem.degrees(dec(planet))
                    star.compute(observatory)
                    exoplanetDB[planet]['Constellation'] = ephem.constellation(star)[0]
                    
                    '''If star is above horizon and sun is below horizon during transit/eclipse:'''		
                    if aboveHorizonForEvent(planet,observatory,ingress,egress) and eventAfterTwilight(planet,observatory,ingress,egress,twilightType):
                        ingressAlt,ingressDir,egressAlt,egressDir = ingressEgressAltAz(planet,observatory,ingress,egress)
                        transitInfo = [planet,transitEpoch,duration(planet)/2,'transit',ingressAlt,ingressDir,egressAlt,egressDir]
                        transits[str(day)].append(transitInfo)		
                if calcEclipses and len(eclipseEpochs) != 0:
                    eclipseEpoch = eclipseEpochs[0]
                    ingress = eclipseEpoch-duration(planet)/2
                    egress = eclipseEpoch+duration(planet)/2
                    
                    ''' Calculate positions of host stars'''
                    star = ephem.FixedBody()
                    star._ra = ephem.hours(RA(planet))
                    star._dec = ephem.degrees(dec(planet))
                    star.compute(observatory)
                    exoplanetDB[planet]['Constellation'] = ephem.constellation(star)[0]
                    
                    if aboveHorizonForEvent(planet,observatory,ingress,egress) and eventAfterTwilight(planet,observatory,ingress,egress,twilightType):
                        ingressAlt,ingressDir,egressAlt,egressDir = ingressEgressAltAz(planet,observatory,ingress,egress)
                        eclipseInfo = [planet,eclipseEpoch,duration(planet)/2,'eclipse',ingressAlt,ingressDir,egressAlt,egressDir]
                        eclipses[str(day)].append(eclipseInfo)	
            
            except ephem.NeverUpError:
                if str(planet) not in planetsNeverUp:
                    print 'Note: planet %s is never above the horizon at this observing location.' % (planet)
                    planetsNeverUp.append(str(planet))

    def removeEmptySets(dictionary):
        '''Remove days where there were no transits/eclipses from the transit/eclipse list dictionary. 
            Can't iterate through the transits dictionary with a for loop because it would change length 
            as keys get deleted, so loop through with while loop until all entries are not empty sets'''
        dayCounter = startSem
        while any(dictionary[day] == [] for day in dictionary):	
            if dictionary[str(dayCounter)] == []:
                del dictionary[str(dayCounter)]
            dayCounter += 1

    if calcTransits: removeEmptySets(transits)
    if calcEclipses: removeEmptySets(eclipses)

    events = {}
    def mergeDictionaries(dict):
        for key in dict:
            if any(key == eventKey for eventKey in events) == False:	## If key does not exist in events,
                if np.shape(dict[key])[0] == 1:	## If new event is the only one on that night, add only it
                    events[key] = [dict[key][0]]
                else:			## If there were multiple events that night, add them each
                    events[key] = []
                    for event in dict[key]:
                        events[key].append(event)
            else:
                if np.shape(dict[key])[0] > 1: ## If there are multiple entries to append,
                    for event in dict[key]:
                        events[key].append(event)
                else:							## If there is only one to add,
                    events[key].append(dict[key][0])
    if calcTransits: mergeDictionaries(transits)
    if calcEclipses: mergeDictionaries(eclipses)

    if textOut: 
        allKeys = events.keys()
        allKeys = np.array(allKeys)[np.argsort(allKeys)]
        report = open(os.path.join(os.path.dirname(oscaar.__file__),'extras','eph','ephOutputs','eventReport.csv'),'w')
        firstLine = 'Planet,Event,Ingress Date, Ingress Time (UT) ,Altitude at Ingress,Azimuth at Ingress,Egress Date, Egress Time (UT) ,Altitude at Egress,Azimuth at Egress,V mag,Depth,Duration,RA,Dec,Const.,Mass,Semimajor Axis (AU),Radius (R_J)\n'
        report.write(firstLine)
        
        for key in allKeys:
            def writeCSVtransit():
                middle = ','.join([planet[0],str(planet[3]),list2datestrCSV(jd2gd(float(planet[1]-planet[2]))),planet[4],planet[5],\
                                   list2datestrCSV(jd2gd(float(planet[1]+planet[2]))),planet[6],planet[7],trunc(V(str(planet[0])),2),\
                                   trunc(depth(planet[0]),4),trunc(24.0*duration(planet[0]),2),RA(planet[0]),dec(planet[0]),constellation(planet[0]),\
                                   mass(planet[0]),semimajorAxis(planet[0]),radius(planet[0])])
                line = middle+'\n'
                report.write(line)
            
            def writeCSVeclipse():
                middle = ','.join([planet[0],str(planet[3]),list2datestrCSV(jd2gd(float(planet[1]-planet[2]))),planet[4],planet[5],\
                                   list2datestrCSV(jd2gd(float(planet[1]+planet[2]))),planet[6],planet[7],trunc(V(str(planet[0])),2),\
                                   trunc(depth(planet[0]),4),trunc(24.0*duration(planet[0]),2),RA(planet[0]),dec(planet[0]),constellation(planet[0]),\
                                   mass(planet[0]),semimajorAxis(planet[0]),radius(planet[0])])
                line = middle+'\n'
                report.write(line)
            
            if np.shape(events[key])[0] > 1:
                elapsedTime = []
                
                for i in range(1,len(events[key])):
                    nextPlanet = events[key][1]
                    planet = events[key][0]
                    double = False
                    '''If the other planet's ingress is before this one's egress, then'''
                    if ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]-nextPlanet[2])))) -\
                        ephem.Date(list2datestr(jd2gd(float(planet[1]+planet[2])))) > 0.0:
                            double = True
                            elapsedTime.append(ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]-nextPlanet[2])))) - \
                                               ephem.Date(list2datestr(jd2gd(float(planet[1]+planet[2])))))
                    
                    if ephem.Date(list2datestr(jd2gd(float(planet[1]-planet[2])))) - \
                        ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]+nextPlanet[2])))) > 0.0:
                            '''If the other planet's egress is before this one's ingress, then'''
                            double = True
                            elapsedTime.append(ephem.Date(list2datestr(jd2gd(float(planet[1]-planet[2])))) - \
                                               ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]+nextPlanet[2])))))
                
                for planet in events[key]:
                    if calcTransits and planet[3] == 'transit':
                        writeCSVtransit()
                    if calcEclipses and planet[3] == 'eclipse':
                        writeCSVeclipse()		  
            
            elif np.shape(events[key])[0] == 1:
                planet = events[key][0]
                if calcTransits and planet[3] == 'transit':
                    writeCSVtransit()
                if calcEclipses and planet[3] == 'eclipse':
                    writeCSVeclipse()
        # report.write('\n')
        
        report.close()
    #print exoplanetDB['HD 209458 b']
    print 'calculateEphemerides.py: Done'


    if htmlOut: 
        '''Write out a text report with the transits/eclipses. Write out the time of 
            ingress, egress, whether event is transit/eclipse, elapsed in time between
            ingress/egress of the temporally isolated events'''
        report = open(os.path.join(os.path.dirname(oscaar.__file__),'extras','eph','ephOutputs','eventReport.html'),'w')
        allKeys = events.keys()
        ## http://www.kryogenix.org/code/browser/sorttable/
        htmlheader = '\n'.join([
                                '<!doctype html>',\
                                '<html>',\
                                '	<head>',\
                                '		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />',\
                                '		<title>Ephemeris</title>',\
                                '		<link rel="stylesheet" href="stylesheetEphem.css" type="text/css" />',\
                                '		 <script type="text/javascript">',\
                                '		  function changeCSS(cssFile, cssLinkIndex) {',\
                                '			var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);',\
                                '			var newlink = document.createElement("link")',\
                                '			newlink.setAttribute("rel", "stylesheet");',\
                                '			newlink.setAttribute("type", "text/css");',\
                                '			newlink.setAttribute("href", cssFile);',\
                                
                                '			document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink);',\
                                '		  }',\
                                '		</script>',\
                                '	   <script src="./sorttable.js"></script>',\
                                '	</head>',\
                                '	<body>',\
                                '		<div id="textDiv">',\
                                '		<h1>Ephemerides for: '+observatory_name+'</h1>',\
                                '		<h2>Observing dates (UT): '+list2datestr(jd2gd(startSem)).split(' ')[0]+' - '+list2datestr(jd2gd(endSem)).split(' ')[0]+'</h2>'
                                '	   Click the column headers to sort. ',\
                                '		<table class="daynight" id="eph">',\
                                '		<tr><th colspan=2>Toggle Color Scheme</th></tr>',\
                                '		<tr><td><a href="#" onclick="changeCSS(\'stylesheetEphem.css\', 0);">Day</a></td><td><a href="#" onclick="changeCSS(\'stylesheetEphemDark.css\', 0);">Night</a></td></tr>',\
                                '		</table>'])
        
        tableheader = '\n'.join([
                                 '\n		<table class="sortable" id="eph">',\
                                 '		<tr> <th>Planet<br /><span class="small">[Link: Orbit ref.]</span></th>	  <th>Event</th>	<th>Ingress <br /><span class="small">(MM/DD<br />HH:MM, UT)</span></th> <th>Egress <br /><span class="small">(MM/DD<br />HH:MM, UT)</span></th>'+\
                                 '<th>V mag</th> <th>Depth<br />(mag)</th> <th>Duration<br />(hrs)</th> <th>RA/Dec<br /><span class="small">[Link: Simbad ref.]</span></th> <th>Const.</th> <th>Mass<br />(M<sub>J</sub>)</th>'+\
                                 '<th>Semimajor <br />Axis (AU)</th> <th>Radius<br />(R<sub>J</sub>)</th></tr>'])
        tablefooter = '\n'.join([
                                 '\n		</table>',\
                                 '		<br /><br />',])
        htmlfooter = '\n'.join([
                                '\n		<p class="headinfo">',\
                                '		Developed by Brett Morris with great gratitude for the help of <a href="http://rhodesmill.org/pyephem/">PyEphem</a>,<br/>',\
                                '		and for up-to-date exoplanet parameters from <a href="http://www.exoplanets.org/">exoplanets.org</a> (<a href="http://adsabs.harvard.edu/abs/2011PASP..123..412W">Wright et al. 2011</a>).<br />',\
                                '		</p>',\
                                '		</div>',\
                                '	</body>',\
                                '</html>'])
        report.write(htmlheader)
        report.write(tableheader)
        
        allKeys = np.array(allKeys)[np.argsort(allKeys)]
        for key in allKeys:
            def writeHTMLtransit():
                indentation = '		'
                middle = '</td><td>'.join([nameWithLink(planet[0]),str(planet[3]),list2datestrHTML(jd2gd(float(planet[1]-planet[2])),planet[4],planet[5]),\
                                           list2datestrHTML(jd2gd(float(planet[1]+planet[2])),planet[6],planet[7]),trunc(V(str(planet[0])),2),\
                                           trunc(depth(planet[0]),4),trunc(24.0*duration(planet[0]),2),RADecHTML(planet[0]),constellation(planet[0]),\
                                           mass(planet[0]),semimajorAxis(planet[0]),radius(planet[0])])
                line = indentation+'<tr><td>'+middle+'</td></tr>\n'
                report.write(line)
            
            def writeHTMLeclipse():
                indentation = '		'
                middle = '</td><td>'.join([nameWithLink(planet[0]),str(planet[3]),list2datestrHTML(jd2gd(float(planet[1]-planet[2])),planet[4],planet[5]),\
                                           list2datestrHTML(jd2gd(float(planet[1]+planet[2])),planet[6],planet[7]),trunc(V(str(planet[0])),2),\
                                           '---',trunc(24.0*duration(planet[0]),2),RADecHTML(planet[0]),constellation(planet[0]),\
                                           mass(planet[0]),semimajorAxis(planet[0]),radius(planet[0])])
                line = indentation+'<tr><td>'+middle+'</td></tr>\n'
                report.write(line)
            
            
            if np.shape(events[key])[0] > 1:
                elapsedTime = []
                
                for i in range(1,len(events[key])):
                    nextPlanet = events[key][1]
                    planet = events[key][0]
                    double = False
                    '''If the other planet's ingress is before this one's egress, then'''
                    if ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]-nextPlanet[2])))) -\
                        ephem.Date(list2datestr(jd2gd(float(planet[1]+planet[2])))) > 0.0:
                            double = True
                            elapsedTime.append(ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]-nextPlanet[2])))) - \
                                               ephem.Date(list2datestr(jd2gd(float(planet[1]+planet[2])))))
                    
                    if ephem.Date(list2datestr(jd2gd(float(planet[1]-planet[2])))) - \
                        ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]+nextPlanet[2])))) > 0.0:
                            '''If the other planet's egress is before this one's ingress, then'''
                            double = True
                            elapsedTime.append(ephem.Date(list2datestr(jd2gd(float(planet[1]-planet[2])))) - \
                                               ephem.Date(list2datestr(jd2gd(float(nextPlanet[1]+nextPlanet[2])))))
                
                for planet in events[key]:
                    if calcTransits and planet[3] == 'transit':
                        writeHTMLtransit()
                    if calcEclipses and planet[3] == 'eclipse':
                        writeHTMLeclipse()		  
            elif np.shape(events[key])[0] == 1:
                planet = events[key][0]
                if calcTransits and planet[3] == 'transit':
                    writeHTMLtransit()
                if calcEclipses and planet[3] == 'eclipse':
                    writeHTMLeclipse()
        report.write(tablefooter)
        report.write(htmlfooter)
        report.close()
    def setup_observatory(self):
        """Method to generate an ephem.Observer object, with hardcoded options.

        """
        #If an ephem.Observer object has been passed, use that.
        if isinstance(self.obs, ephem.Observer):
            observer = obs
        #If it is an observatory name, set up the appropriate Observer object.
        else:
            observer = ephem.Observer()
            if obs == 'keck':
                observer.long, observer.lat = '-155:28.7', '19:49.7'
                observer.elevation = 4160
            elif obs == 'lick':
                observer.long, observer.lat = '-121:38.2', '37:20.6'
                observer.elevation = 1290
            elif obs == 'palomar':
                observer.long, observer.lat = '-116:51:50', '33:21:21'
                observer.elevation = 1712
            elif obs == 'flwo':
                observer.long, observer.lat = '-110:52.7', '31:40.8'
                observer.elevation = 2606
            elif obs == 'lapalma':
                observer.long, observer.lat = '-17:53.6', '28:45.5'
                observer.elevation = 2396
            elif obs == 'ctio':
                observer.long, observer.lat = '-70:48:54', '-30:9.92'
                observer.elevation = 2215
            elif obs == 'dct' or obs == 'happyjack':
                observer.long, observer.lat = '-111:25:20', '34:44:40'
                observer.elevation = 2360
            elif obs == 'andersonmesa':
                observer.long, observer.lat = '-111:32:09', '30:05:49'
                observer.elevation = 2163
            elif obs == 'mtbigelow' or obs == 'catalina':
                observer.long, observer.lat = '-110:44:04.3', '32:24:59.3'
                observer.elevation = 2518
            elif obs == 'mtgraham':
                observer.long, observer.lat = '-109:53:23', '32:42:05'
                observer.elevation = 3221
            elif obs == 'kpno':
                observer.long, observer.lat = '-111:25:48', '31:57:30'
                observer.elevation = 2096
            elif obs == 'cerropachon':
                observer.long, observer.lat = '-70:44:11.7', '-30:14:26.6'
                observer.elevation = 2722
            elif obs == 'lasilla':
                observer.long, observer.lat = '-70:43:53', '-29:15:40'
                observer.elevation = 2400
            elif obs == 'cerroparanal':
                observer.long, observer.lat = '-70:24:15', '-24:37:38'
                observer.elevation = 2635
            elif obs == 'calaralto':
                observer.long, observer.lat = '-02:32:46', '+37:13:25'
                observer.elevation = 2168
            elif obs == 'lascampanas':
                observer.long, observer.lat = '-70:41:33', '-29:00:53'
                observer.elevation = 2380
            elif obs == 'saao':
                observer.long, observer.lat = '-32:22:42', '+20:48:38'
                observer.elevation = 1798
            elif obs == 'sidingspring':
                observer.long, observer.lat = '-31:16:24', '+149:04:16'
                observer.elevation = 1116

        #self.observer = observer
        return observer
Beispiel #11
0
        # pyephem needs yyyy/mm/dd format
        # correct time format is e.g. starttime = '2015/10/15 04:00:00'
        starttime = line.split("=")[-1].replace('-', '/')
    if line.find("Observation.Beam[%s].subbandList" % (sap)) >= 0:
        subbandlist = line.split("=")[-1]
file.close()

# convert to HHMMSS
src = ephem.FixedBody()
src._ra = float(rarad)
src._dec = float(decrad)

# Estimate the beam shape, only for HBA data
# set up the observatory
src._epoch = ephem.J2000
telescope = ephem.Observer()
telescope.lat = ephem.degrees('52.91511')
telescope.long = ephem.degrees('6.869883')
telescope.elevation = 0
telescope.date = ephem.Date(starttime)
src.compute(telescope)

# calculate the approximate beam size
LOW_FREQ = ????? 		# SET YOUR BOTTOM OBS FREQUENCY HERE!
BW = ????? 			# SET YOUR BANDWIDTH HERE!

# CHAN_BW = ?????		# SET YOUR CHANNEL BANDWIDTH HERE!
#BOTTOMSUBBAND = float(re.findall(r"\d+", subbandlist)[0])
#l = 300.0 / (LOW_FREQ + chan_bw * BOTTOMSUBBAND) # bottom wavelength in m

l = 300.0 / (LOW_FREQ + BW / 2) # high wavelength in m 
Beispiel #12
0
#!/usr/bin/env python

import os
import sys
import ephem
import numpy as np
import tables as tb
from leda_cal.leda_cal import *
from leda_cal.params import params

ovro_location = ('37.2397808', '-118.2816819', 1183.4839)
ovro = ephem.Observer(); (ovro.lat, ovro.lon, ovro.elev) = ovro_location
sun = ephem.Sun()

gal_center = ephem.FixedBody()  
gal_center._ra  =  '17 45 40.04'
gal_center._dec = '-29 00 28.1'
gal_center.name = "Galactic Center"

def main(args, all_lsts):
    filenames = args
    results = {}
    for filename in filenames:
        print "Working on '%s'" % os.path.basename(filename)
        h5 = tb.open_file(filename)

        T_ant = apply_calibration(h5)
        lst_stamps = T_ant['lst']
        if len(lst_stamps) == 0:
            print "No LSTS in file"
            continue
import math
import ephem
import datetime

#Penentuan Lintasan Arah Kiblat Harian
latitudkaabah = 21+25/60+21/3600
longitudkaabah = 39+49/60+34.32/3600

print("Masukkan Nama Tempat")
namatempat = str(input())
print("Masukkan Koordinate Tempat yang ingin Dikira Kiblatnya")

lokasi = ephem.Observer()
print("Masukkan Latitud (Utara = Positif, Selatan=Negatif)")
lokasi.lat = input()

print("Masukkan Longitud(Timur = Positif, Barat=Negatif)")
lokasi.long = input()

print("Masukkan Hari")
day = int(input())

print("Masukkan Bulan")
month = int(input())

print("Masukkan Tahun")
year = int(input ())
time = 0
print("Masukkan Time Zone")
tz = int(input())
tz1 = time - tz
Beispiel #14
0
def scheduler_map(request, size=600):
    targets = SchedulerTargets.objects.order_by('-time_created').exclude(
        ra__isnull=True)

    # SAO location
    obs = ephem.Observer()
    obs.lat = deg2rad(settings.LATITUDE)
    obs.lon = deg2rad(settings.LONGITUDE)
    obs.elevation = settings.ELEVATION
    obs.pressure = 0.0

    # Current zenith position
    z = obs.radec_of(0, 90)
    st = rad2deg(z[0])  # stellar time in degrees

    fig = Figure(facecolor='white',
                 dpi=72,
                 figsize=(size / 72, size / 72),
                 tight_layout=True)
    ax = fig.add_subplot(111)

    # set up orthographic map projection
    map = Basemap(projection='ortho',
                  lat_0=rad2deg(obs.lat),
                  lon_0=-st,
                  resolution=None,
                  celestial=True,
                  ax=ax)
    # draw the edge of the map projection region (the projection limb)
    map.drawmapboundary()

    # draw and label ra/dec grid lines every 30 degrees.
    degtoralabel = lambda deg: "$%d^h$" % int(deg / 15)
    degtodeclabel = lambda deg: "%+d$^\circ$" % deg
    map.drawparallels(np.arange(-90, 90, 30),
                      color='lightgray')  #, fmt=degtodeclabel)
    map.drawmeridians(np.arange(0, 360, 45), color='lightgray')

    for h in [0, 3, 6, 9, 12, 15, 18, 21]:
        try:
            x, y = map(h * 15, 0)
            if abs(x) < 1e10 and abs(y) < 1e10:
                ax.text(x, y, degtoralabel(h * 15), color='black')
        except:
            pass

    # Place stars
    star_size = [10 * (10**(-0.4 * v)) for v in tycho2['v']]
    px, py = map(tycho2['ra'], tycho2['dec'])
    map.scatter(px, py, s=star_size, c='gray')

    # Sun
    s = ephem.Sun()
    s.compute(obs)
    px, py = map(rad2deg(s.ra), rad2deg(s.dec))
    if abs(px) < 1e10 and abs(py) < 1e10:
        map.scatter(px, py, s=2000, c='lightgray', marker='o')
        ax.text(px, py, "Sun", color='black', va='center', ha='center')

    # Moon
    m = ephem.Moon()
    m.compute(obs)
    px, py = map(rad2deg(m.ra), rad2deg(m.dec))
    if abs(px) < 1e10 and abs(py) < 1e10:
        map.scatter(px, py, s=1200, c='lightgray', marker='o')
        ax.text(px, py, "Moon", color='black', va='center', ha='center')

    mp, ip, cp = None, None, None
    for target in targets:
        if target.status.name == 'completed' or target.status.name == 'archived' or target.status.name == 'inactive' or target.status.name == 'failed':
            continue

        px, py = map(target.ra, target.dec)
        if abs(px) < 1e10 and abs(py) < 1e10:
            if target.type == 'monitoring':
                mp = map.scatter(px,
                                 py,
                                 marker='o',
                                 s=300,
                                 alpha=0.3,
                                 color='blue')
            elif target.type == 'imaging':
                ip = map.scatter(px,
                                 py,
                                 marker='o',
                                 s=300,
                                 alpha=0.3,
                                 color='green')
            else:
                cp = map.scatter(px,
                                 py,
                                 marker='o',
                                 s=300,
                                 alpha=0.3,
                                 color='yellow')

            ax.text(px, py, target.name, color='black', va='bottom', ha='left')

    # Title etc
    ax.set_title("%s UT, Sidereal %s" % (obs.date, (ephem.hours(deg2rad(st)))))

    if cp or mp or ip:
        fig.legend([mp, ip, cp], ["Monitoring", "Imaging", "Custom"],
                   loc=4).draw_frame(False)

    # Return the image
    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response, bbox_inches='tight')

    return response
    print('Pan axis (x-axis) PID gains kpx=', params.kpx, 'kix=', params.kix,
          'kdx=', params.kdx)
    print('Tilt axis (t-axis) PID gains kpy=', params.kpy, 'kiy=', params.kiy,
          'kdy=', params.kdy)

    #Define tracking/data collection parameters
    track_time = params.track_time  #20  #number of seconds to capture data/track
    hz = params.hz  #15      #data sample rate
    cnt = 0
    delay = 1.0 / hz

    #Define directory to save data in
    save_dir = params.save_dir  #'C:/git_repos/GLO/Tutorials/tracking/'

    #Obtain ephemeris data
    ep = ephem.Observer()

    #Establish communication with sun sensor/s - store in a list
    ss = [
        SS(inst_id=params.ss1_inst_id,
           com_port=params.ss1_com_port,
           baudrate=params.ss1_baud_rate),
        SS(inst_id=params.ss2_inst_id,
           com_port=params.ss2_com_port,
           baudrate=params.ss2_baud_rate),
        SS(inst_id=params.ss3_inst_id,
           com_port=params.ss3_com_port,
           baudrate=params.ss3_baud_rate)
    ]

    #List of sun sensors to read data from (reduce number of sensors to increase sampling rate)
def ephem_doponly(maindir, tleoff=10.0):
    """
    This function will output a dictionary that can be used to remove the
    frequency offset.

    Args:
        maindir (:obj:'str'): Directory that holds the digital rf and metadata.
        tleoff (:obj:'float'): Offset of the tle from the actual data.

    Returns:
        outdict (dict[str, obj]): Output data dictionary::

            {
                    't': Time in posix,
                    'dop1': Doppler frequency of 150 MHz channel from TLE ,
                    'dop2': Doppler frequency of 400 MHz channel from TLE ,
            }
    """

    #%% Get Ephem info
    # Assuming this will stay the same
    ut0 = 25567.5
    e2p = 3600.0 * 24  # ephem day to utc seconds

    sitepath = os.path.expanduser(os.path.join(maindir,
                                               "metadata/config/site"))
    sitemeta = drf.DigitalMetadataReader(sitepath)
    sdict = sitemeta.read_latest()
    sdict1 = list(sdict.values())[0]

    infopath = os.path.expanduser(os.path.join(maindir, "metadata/info"))
    infometa = drf.DigitalMetadataReader(infopath)
    idict = infometa.read_latest()
    idict1 = list(idict.values())[0]

    passpath = os.path.expanduser(os.path.join(maindir, "metadata/pass/"))
    passmeta = drf.DigitalMetadataReader(passpath)
    pdict = passmeta.read_latest()
    pdict1 = list(pdict.values())[0]
    rtime = (pdict1["rise_time"] - ut0) * e2p
    tsave = list(pdict.keys())[0]

    Dop_bw = pdict1["doppler_bandwidth"]
    t = sp.arange(0, (Dop_bw.shape[0] + 1) * 10, 10.0) + rtime
    t = t.astype(float)

    obsLoc = ephem.Observer()
    obsLoc.lat = sdict1["latitude"]
    obsLoc.long = sdict1["longitude"]

    satObj = ephem.readtle(idict1["name"], idict1["tle1"][1:-1],
                           idict1["tle2"][1:-1])
    tephem = (t - rtime) * ephem.second + pdict1["rise_time"]

    sublat = sp.zeros_like(tephem)
    sublon = sp.zeros_like(tephem)
    for i, itime in enumerate(tephem):
        obsLoc.date = itime
        satObj.compute(obsLoc)
        sublat[i] = sp.rad2deg(satObj.sublat)
        sublon[i] = sp.rad2deg(satObj.sublong)

    # XXX Extend t vector because for the most part the velocities at the edge
    # are not changing much so to avoid having the interpolation extrapolate.
    # If extrapolation used then error messages that the time was off
    t[-1] = t[-1] + 600
    t[-2] = t[-2] + 500
    t[0] = t[0] - 240

    tdop = (t[0:(len(t) - 1)] + t[1:len(t)]) / 2.0
    tdop[0] = tdop[0] - 35.0
    # XXX Used this to line up inital TLE times
    tdop = tdop - tleoff

    tephem = (tdop - rtime) * ephem.second + pdict1["rise_time"]

    sublat = sp.zeros_like(tephem)
    sublon = sp.zeros_like(tephem)
    for i, itime in enumerate(tephem):
        obsLoc.date = itime
        satObj.compute(obsLoc)
        sublat[i] = sp.rad2deg(satObj.sublat)
        sublon[i] = sp.rad2deg(satObj.sublong)
    return {
        "t": t,
        "tsave": tsave,
        "dop1": sp.interpolate.interp1d(tdop, Dop_bw[:, 0], kind="cubic"),
        "dop2": sp.interpolate.interp1d(tdop, Dop_bw[:, 1], kind="cubic"),
        "sublat": sp.interpolate.interp1d(tdop, sublat, kind="cubic"),
        "sublon": sp.interpolate.interp1d(tdop, sublon, kind="cubic"),
        "site_latitude": float(sdict1["latitude"]),
        "site_longitude": float(sdict1["longitude"]),
    }
Beispiel #17
0
def alerts_map(request, night='', state='all', size=800):
    alerts = Alerts.objects.order_by('time')
    time = None

    if night and night != 'all':
        alerts = alerts.filter(night=night)
        time = get_time_from_night(night)

    ra, dec = [], []
    N = 0
    N0 = 0
    Nf = 0

    for alert in alerts:
        ra.append(alert.ra)
        dec.append(alert.dec)

        N0 += 1
        if RealtimeObjects.objects.filter(channel_id=alert.channel_id).filter(
                time_start=alert.time).exists():
            N += 1

        if Images.objects.filter(type='alert').extra(
                where=["keywords->'TARGET'='alert_%s'" % alert.id]).exists():
            Nf += 1

    # Map
    fig = Figure(facecolor='white',
                 dpi=72,
                 figsize=(size / 72, 0.6 * size / 72),
                 tight_layout=True)
    ax = fig.add_subplot(111)

    # set up gnomonic map projection
    map = Basemap(projection='hammer',
                  lat_0=0,
                  lon_0=0,
                  resolution=None,
                  celestial=True,
                  ax=ax)
    # draw the edge of the map projection region (the projection limb)
    map.drawmapboundary()

    # draw and label ra/dec grid lines every 30 degrees.
    degtoralabel = lambda deg: "$%d^h$" % int(deg / 15)
    degtodeclabel = lambda deg: "%+d$^\circ$" % deg
    map.drawparallels(np.arange(-90, 90, 30),
                      color='lightgray')  #, fmt=degtodeclabel)
    map.drawmeridians(np.arange(0, 360, 45), color='lightgray')

    for h in [0, 3, 6, 9, 12, 15, 18, 21]:
        try:
            x, y = map(h * 15, 0)
            if abs(x) < 1e10 and abs(y) < 1e10:
                ax.text(x, y, degtoralabel(h * 15), color='black')
        except:
            pass

    # Place stars
    star_size = [10 * (10**(-0.4 * v)) for v in tycho2['v']]
    px, py = map(tycho2['ra'], tycho2['dec'])
    map.scatter(px, py, s=star_size, c='gray', edgecolors='None')

    # Sun and Moon
    if time is not None:
        # SAO location
        obs = ephem.Observer()
        obs.lat = np.deg2rad(settings.LATITUDE)
        obs.lon = np.deg2rad(settings.LONGITUDE)
        obs.elevation = settings.ELEVATION
        obs.pressure = 0.0
        obs.date = time

        s = ephem.Sun()
        s.compute(obs)
        px, py = map(np.rad2deg(s.ra), np.rad2deg(s.dec))
        if abs(px) < 1e10 and abs(py) < 1e10:
            map.scatter(px, py, s=2000, c='lightgray', marker='o')
            ax.text(px, py, "Sun", color='black', va='center', ha='center')

        # anti-Sun
        as_ra = (np.rad2deg(s.ra) + 180) % 360
        as_dec = -np.rad2deg(s.dec)
        px, py = map(as_ra, as_dec)
        if abs(px) < 1e10 and abs(py) < 1e10:
            map.scatter(px,
                        py,
                        s=2000,
                        c='lightgray',
                        marker='o',
                        linestyle='--',
                        alpha=0.5)
            ax.text(px,
                    py,
                    "Anti\nSun",
                    color='black',
                    va='center',
                    ha='center',
                    alpha=0.5)

        m = ephem.Moon()
        m.compute(obs)
        px, py = map(np.rad2deg(m.ra), np.rad2deg(m.dec))
        if abs(px) < 1e10 and abs(py) < 1e10:
            map.scatter(px, py, s=1200, c='lightgray', marker='o')
            ax.text(px, py, "Moon", color='black', va='center', ha='center')

    # Alerts
    if alerts:
        px, py = map(ra, dec)
        map.scatter(px,
                    py,
                    s=100,
                    c='red',
                    marker='*',
                    edgecolors='blue',
                    linewidths=0.3)

    # Title
    if night and night != 'all':
        fig.suptitle("Realtime Alerts for night %s" % night)
    else:
        fig.suptitle("Realtime Alerts")

    ax.set_title("%d alerts, %d with objects, %d followed up" % (N0, N, Nf))

    # Return the image
    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response, bbox_inches='tight')

    return response
Beispiel #18
0
    def __init__(self):
        """Create the TCC Frame"""
        wx.Frame.__init__(self, None, -1, self.title,
                          size=(900, 675))  #Wxpython frame object

        #############################################################

        #Dictionaries of relevant telescope information

        #Most of Bifrost's functions rely on and alter the contents of these dictionaries.
        #Bifrost has been designed such that these dictionaries provide a quick summary of the overall observing
        #session.

        #Telescope Status: Contains information on dynamic processes in GUI operation
        self.telescope_status = {
            'connectState': False,
            'RA': 'Unknown',
            'Dec': 'Unknown',
            'slewing': False,
            'tracking': False,
            'guiding': False,
            'pointState': False,
            'precession': True,
            'initState': False,
            'guider_rot': False
        }

        #Initilization Status: Contains information on (typically) static processes in GUI operation or information
        #from past observing sessions.
        self.dict = {
            'lat': None,
            'lon': None,
            'elevation': None,
            'lastRA': None,
            'lastDEC': None,
            'lastGuiderRot': None,
            'lastFocusPos': None,
            'maxdRA': None,
            'maxdDEC': None,
            'RAtrackingRate': None
        }

        #Target Coordinates: For pointing, align telescope coordinates with these values once pointing is carried out.
        self.target_coords = {"Name": None, "RA": None, "Dec": None}

        #############################################################

        #Additional variables

        self.protocol = None  # twisted python connection protocol to server, overwrite during connection
        self.server = DataForwardingProtocol(
        )  # Twisted Python server identification
        self.calculate = True  # Flag for dynamic airmass calculation
        self.night = True  # Send GUI to night mode
        self.export_active = False  # Track the status of the export target list window
        self.d_color = wx.SystemSettings.GetColour(
            wx.SYS_COLOUR_BACKGROUND)  #Default background color for OS
        self.list_count = 0  #Tracks the number of targets currently in the targetlist.
        self.active_threads = {}  #Keep track of threads open in GUI
        self.thread_to_close = -1
        self.current_timezone = "PST"  #Current timezone is Pacific Standard Time at MRO
        self.mro = ephem.Observer(
        )  #Ephem object for mro location (To do: Roll this into Astroplan's Observer object)
        self.mrolat = 46.9528 * u.deg  #Latitude of Manastash Ridge Observatory
        self.MRO = Observer(
            longitude=-120.7278 * u.deg,  #Astroplan Observer Object for MRO
            latitude=46.9528 * u.deg,
            elevation=1198 * u.m,
            name="Manastash Ridge Observatory")
        #self.at_MRO = True #Dev variable for ease of development offsite
        self.process_list = []
        debug = True  #Debug mode, currently no functionality
        ico = wx.Icon("bifrost_small.ico", wx.BITMAP_TYPE_ICO)  #GUI Icon
        self.SetIcon(ico)
        self.dir = os.getcwd()  #Current path for file IO
        #if self.at_MRO == True:
        self.stordir = "/home/mro/storage/tcc_data"
        #else:
        #self.stordir = self.dir
        self.plot_open = False

        self.code_timer_W = wx.Timer(self)
        self.code_timer_E = wx.Timer(self)
        self.code_timer_N = wx.Timer(self)
        self.code_timer_S = wx.Timer(self)
        self.code_timer_Slew = wx.Timer(self)

        self.stop_time = 250  #Waiting time for tracking to finish 500 works

        #self.targetlists=glob.glob('/home/mro/Desktop/targetlists/*')
        #self.targetlists=glob.glob('/home/doug/TCC/targetlists/*')

        #############################################################

        #Setup Notebook

        p = wx.Panel(self)
        nb = wx.Notebook(p)
        controlPage = Control(nb, debug, self.night)  #Telescope Control Tab
        targetPage = Target(nb, debug, self.night)  #Target List Tab
        guiderControlPage = GuiderControl(nb, debug,
                                          self.night)  #Guider Control Tab
        initPage = Initialization(nb, debug, self.night)  #Initialization Tab
        logPage = NightLog(nb, debug, self.night)  #Night Log Tab

        nb.AddPage(controlPage, "Telescope Control")
        self.control = nb.GetPage(0)

        nb.AddPage(targetPage, "Target List")
        self.target = nb.GetPage(1)

        nb.AddPage(guiderControlPage, "Guider Control")
        self.guiderControl = nb.GetPage(2)

        nb.AddPage(initPage, "Initialization")
        self.init = nb.GetPage(3)

        #nb.AddPage(logPage,"Night Log")
        #self.nl=nb.GetPage(3)

        #Control Tab Bindings
        self.Bind(wx.EVT_BUTTON, self.startSlew, self.control.slewButton)
        self.Bind(wx.EVT_BUTTON, self.toggletracksend,
                  self.control.trackButton)
        self.Bind(wx.EVT_BUTTON, self.pointing, self.control.pointButton)
        self.Bind(wx.EVT_BUTTON, self.haltmotion, self.control.stopButton)
        self.Bind(wx.EVT_BUTTON, self.Noffset, self.control.jogNButton)
        self.Bind(wx.EVT_BUTTON, self.Soffset, self.control.jogSButton)
        self.Bind(wx.EVT_BUTTON, self.Eoffset, self.control.jogEButton)
        self.Bind(wx.EVT_BUTTON, self.Woffset, self.control.jogWButton)
        self.Bind(wx.EVT_BUTTON, self.focusIncPlus,
                  self.control.focusIncPlusButton)
        self.Bind(wx.EVT_BUTTON, self.focusIncNeg,
                  self.control.focusIncNegButton)
        self.Bind(wx.EVT_BUTTON, self.setfocus, self.control.focusAbsMove)

        #Target Tab Bindings
        self.Bind(wx.EVT_BUTTON, self.set_target, self.target.selectButton)
        self.Bind(wx.EVT_BUTTON, self.addToList, self.target.enterButton)
        self.Bind(wx.EVT_BUTTON, self.populateCurrPos, self.target.popButton)
        self.Bind(wx.EVT_BUTTON, self.readToList, self.target.listButton)
        self.Bind(wx.EVT_BUTTON, self.removeFromList, self.target.removeButton)
        self.Bind(wx.EVT_BUTTON, self.ExportOpen, self.target.exportButton)
        self.Bind(wx.EVT_BUTTON, self.target_plot, self.target.plot_button)
        self.Bind(wx.EVT_BUTTON, self.airmass_plot, self.target.airmass_button)
        self.Bind(wx.EVT_BUTTON, self.FinderOpen, self.target.finder_button)
        #self.Bind(wx.EVT_BUTTON,self.refreshList,self.target.refresh_button)

        #Guider Control Tab Bindings
        #self.Bind(wx.EVT_BUTTON,self.on_Rot,self.guiderControl.guiderRotButton)

        # Init Tab Bindings
        self.Bind(wx.EVT_BUTTON, self.setTelescopeZenith,
                  self.init.atZenithButton)
        self.Bind(wx.EVT_BUTTON, self.setTelescopePosition,
                  self.init.syncButton)
        self.Bind(wx.EVT_BUTTON, self.onInit, self.init.initButton)
        self.Bind(wx.EVT_BUTTON, self.setRATrackingRate,
                  self.init.rateRAButton)
        self.Bind(wx.EVT_BUTTON, self.resetRATrackingRate,
                  self.init.resetTRButton)
        self.Bind(wx.EVT_BUTTON, self.setmaxdRA, self.init.dRAButton)
        self.Bind(wx.EVT_BUTTON, self.setmaxdDEC, self.init.dDECButton)
        self.Bind(wx.EVT_BUTTON, self.coverpos, self.init.coverposButton)
        self.Bind(wx.EVT_BUTTON, self.parkscope, self.init.parkButton)
        #self.Bind(wx.EVT_BUTTON, self.pointing, self.init.onTargetButton)

        self.Bind(wx.EVT_TIMER, self.timeW, self.code_timer_W)
        self.Bind(wx.EVT_TIMER, self.timeE, self.code_timer_E)
        self.Bind(wx.EVT_TIMER, self.timeN, self.code_timer_N)
        self.Bind(wx.EVT_TIMER, self.timeS, self.code_timer_S)

        self.Bind(wx.EVT_TIMER, self.timeSlew, self.code_timer_Slew)

        self.createMenu()

        self.sb = self.CreateStatusBar(5)
        self.sb.SetStatusWidths([150, 150, 150, -2, -1])

        sizer = wx.BoxSizer()
        sizer.Add(nb, 1, wx.EXPAND | wx.ALL)
        p.SetSizer(sizer)
        p.Layout()

        #############################################################

        self.readConfig()
        """Target testing parameters """
        #self.target.nameText.SetValue('M31')
        #self.target.raText.SetValue('00h42m44.330s')
        #self.target.decText.SetValue('+41d16m07.50s')
        #self.target.epochText.SetValue('J2000')
        #self.target.magText.SetValue('3.43')

        img_default = os.path.join(self.dir, 'gimg', 'gcam_56901_859.jpg')
        img = mpimg.imread(img_default)
Beispiel #19
0
def astro_parameter_calculate(utc_datetime):

    homedir = os.getcwd()
    conf_obs_parameters_sys = './conf_obs_parameters_sys.dat'
    conf_obs_parameters_sys_dev = open(conf_obs_parameters_sys, 'rU')

    lines2 = conf_obs_parameters_sys_dev.read().splitlines()
    conf_obs_parameters_sys_dev.close()

    for line2 in lines2:
        word = line2.split()
        if word[0] == 'observatory_lat':
            observatory_lat = word[2]
        elif word[0] == 'observatory_lon':
            observatory_lon = word[2]
        elif word[0] == 'observatory_elevation':
            observatory_elevation = float(word[2])
        elif word[0] == 'zenith_sun_min':
            zenith_sun_min = float(word[2])
        elif word[0] == 'zenith_min':
            zenith_min = float(word[2])
        elif word[0] == 'gal_min':
            gal_min = float(word[2])
        elif word[0] == 'moon_dis_min_para':
            moon_dis_min_str = word[2]
            moon_dis_para_str = moon_dis_min_str.split('|')
            moon_dis_phase_data = [[]]
            for moon_dis_para in moon_dis_para_str:
                moon_dis_para_phase_min = float(
                    moon_dis_para.split(':')[0].split('-')[0])
                moon_dis_para_phase_max = float(
                    moon_dis_para.split(':')[0].split('-')[1])
                moon_dis_para_dis = float(moon_dis_para.split(':')[1])
                moon_dis_phase_data.append([
                    moon_dis_para_phase_min, moon_dis_para_phase_max,
                    moon_dis_para_dis
                ])
            moon_dis_phase_data = filter(None, moon_dis_phase_data)

    # set observatory parameters ----------------------------------------
    observatory = ephem.Observer()
    observatory.lat = observatory_lat
    observatory.lon = observatory_lon
    observatory.elevation = observatory_elevation
    lat_dd = float(str(observatory.lat).split(":")[0])+\
    float(str(observatory.lat).split(":")[1])/60.0+\
    float(str(observatory.lat).split(":")[2])/3600.0

    # print "utc_datetime", utc_datetime
    utc_datetime_str = time.strftime('%Y/%m/%d %H:%M:%S', utc_datetime)
    # print "utc_datetime_str",utc_datetime_str
    observatory.date = utc_datetime_str

    # calculate local time  ----------------------------------------
    local_time = ephem.localtime(observatory.date)
    local_time_str = str(local_time).replace(' ', 'T')

    # calculate local sidereal time  ----------------------------------------
    lst_dd = float(str(observatory.sidereal_time()).split(":")[0])* 15.0+\
    float(str(observatory.sidereal_time()).split(":")[1])/60.0* 15.0+\
    float(str(observatory.sidereal_time()).split(":")[2])/3600.0* 15.0

    # calculate time difference between ut and lst ----------------------------------
    ut_time_dd = float(str(observatory.date).split(" ")[1].split(":")[0])* 15.0+\
    float(str(observatory.date).split(" ")[1].split(":")[1])/60.0* 15.0+\
    float(str(observatory.date).split(" ")[1].split(":")[2])/3600.0* 15.0
    lst_ut_dd = lst_dd - ut_time_dd
    # print 'lst_ut', observatory.date, local_time,observatory.sidereal_time(), lst_dd,ut_time_dd,lst_ut_dd

    # calculate altitude angle or zenith angular distance of the sun   ---------------------------------
    solar = ephem.Sun(observatory)
    solar_alt_dd = 90 - float(str(solar.alt).split(":")[0]) + float(
        str(solar.alt).split(":")[1]) / 60.0 + float(
            str(solar.alt).split(":")[2]) / 3600.0
    #print('solar  %s' % (solar_alt_dd))

    lunar = ephem.Moon(observatory)
    lunar_ra_dd = float(str(lunar.ra).split(":")[0]) * 15.0 + float(
        str(lunar.ra).split(":")[1]) / 60.0 * 15.0 + float(
            str(lunar.ra).split(":")[2]) / 3600.0 * 15.0
    lunar_dec_dd = float(str(lunar.dec).split(":")[0]) + float(
        str(lunar.dec).split(":")[1]) / 60.0 + float(
            str(lunar.dec).split(":")[2]) / 3600.0
    moon_phase = float(lunar.moon_phase)
    #print('lunar %s %s %s' % (lunar_ra_dd, lunar_dec_dd, lunar.moon_phase))

    return [
        lat_dd, local_time_str, lst_dd, solar_alt_dd, lunar_ra_dd,
        lunar_dec_dd, lst_ut_dd, moon_dis_phase_data, moon_phase,
        zenith_sun_min, zenith_min, gal_min
    ]
def automate():  #main function for automation
    #initialize ephemeris
    #pos = ephem.city("Toronto")#need to enter exact coordinates
    pos = ephem.Observer()
    pos.lon, pos.lat = '-79.39', '43.66'
    sun = ephem.Sun()

    try:
        #dome initialization
        sun.compute(pos)  #get data on sun
        if dome.shutter == 'Unknown':  #send dome to starting position if shutter is unknown
            dome.write_command('GHOM')
            sleep(30)
            dome.write_command('GCLS')
            sleep(30)
        if goodWeather(
        ) == True and dome.shutter == 'Closed' and sun.alt > 0.15:  #send Dome to sun position if weather permits and daytime
            dome.write_command('GHOM')
            print '\n Sun is out! Going to home position ....\n'
            sleep(30)
            dome.write_command("GOPN")
            print '\n Openning the dome shutter ....\n'
            sleep(30)
            print '\n Moving the dome to the right position ....\n'
            move(57.2958 * float(sun.az) + 10)
            sleep(30)

        while True:  #looping program
            pos.date = ephem.now()

            sun.compute(pos)
            dome.write_command('GINF')
            result, message = dome.readfrom()
            if result == 1:  #check dome info
                parseinfo(message)
            else:
                print '\t Contact Failed.  Dome status unknown.'
            if dome.shutter == 'Opened':
                if sun.alt < 0.15:  #closing for night time
                    dome.write_command('GHOM')
                    sleep(30)
                    dome.write_command('GCLS')
                    for i in range(60):
                        sleep(1)
                    print "\nNight time -- Dome closed"
                elif goodWeather() == False:  #closing for bad weather
                    dome.write_command('GHOM')
                    sleep(30)
                    dome.write_command('GCLS')
                    sleep(60)
                    print "\nPoor weather conditions detected -- Dome closed"
                elif positionAccurate(
                        sun.az) == False and goodWeather() == True:
                    print "\n Sun position and dome position don't match. Checking... \n"
                    checkMovement(float(sun.az))  #move to track sun
                for i in range(10):  #wait 10 seconds
                    sleep(
                        1
                    )  #enables keyboardinterrupt to be processed right away

            else:
                if goodWeather(
                ) == True and sun.alt > 0.15:  #opens dome again if conditions allow it
                    dome.write_command('GHOM')
                    sleep(30)
                    dome.write_command("GOPN")
                    for i in range(30):
                        sleep(1)
                    move(57.2958 * float(sun.az) + 10)
                    sleep(30)
                else:  #waiting in bad conditions
                    for i in range(60):
                        sleep(1)

    except KeyboardInterrupt:  #allows user to exit infinite loop by pressing ctrl-c
        print "\nKeyboardInterrupt -- exiting automation"
        return
Beispiel #21
0
    obpos                   = GLOBALutils.obspos( longitude, obsradius, R0 )

    jplephem.set_ephemeris_dir( baryc_dir , ephemeris )
    jplephem.set_observer_coordinates( obpos[0], obpos[1], obpos[2] )

    res = jplephem.doppler_fraction(ra/15.0, dec, int(mjd), mjd%1, 1, 0.0)
    lbary_ltopo = 1.0 + res['frac'][0]
    bcvel_baryc = ( lbary_ltopo - 1.0 ) * 2.99792458E5

    print("\t\tBarycentric velocity:", bcvel_baryc)

    res = jplephem.pulse_delay(ra/15.0, dec, int(mjd), mjd%1, 1, 0.0)
    mbjd = mjd + res['delay'][0] / (3600.0 * 24.0)

    # Moon Phase Calculations
    gobs = ephem.Observer()
    gobs.name='Clay_Mag_2'
    gobs.lat=rad(latitude)  # lat/long in decimal degrees
    gobs.long=rad(longitude)
    DDATE = h[0].header['UT-DATE']
    HHOUR = h[0].header['UT-TIME']
    Mho = HHOUR[:2]
    Mmi = HHOUR[3:5]
    Mse = HHOUR[6:]
    gobs.date = str(DDATE[:4]) + '-' +  str(DDATE[5:6]) + '-' + str(DDATE[7:]) + ' ' +  Mho + ':' + Mmi +':' +Mse
    mephem = ephem.Moon()
    mephem.compute(gobs)
    Mcoo = jplephem.object_track("Moon", int(mjd), float(mjd%1), 1, 0.0)
    Mp = jplephem.barycentric_object_track("Moon", int(mjd), float(mjd%1), 1, 0.0)
    Sp = jplephem.barycentric_object_track("Sun", int(mjd), float(mjd%1), 1, 0.0)
    res = jplephem.object_doppler("Moon", int(mjd), mjd%1, 1, 0.0)
    def only_daytime_overpasses(self, sun):
        """
        Return only those which are visible -- this will take awhile i imagine
        """
        observer_on_the_ground = ephem.Observer()
        observer_on_the_ground.lat = np.radians(self.lat)
        observer_on_the_ground.long = np.radians(self.long)
        observer_on_the_ground.date = self.datetime

        """
        Improvment from
        http://stackoverflow.com/questions/15044521/
                javascript-or-python-how-do-i-figure-out-if-its-night-or-day

        think should work without timezones
        -- essentially next sunset should be before the next sunset

        For it to be the day time the sunset must be nearer than
        the next sunrise


        NOTE: towards the poles the sun never rises or sets
              depending on time of year. When this happens
              pyephem raises an error...
              These are some annoying edge cases to deal
              with

        """

        #import pdb; pdb.set_trace()
        try:
            next_sunrise= observer_on_the_ground.next_rising(sun).datetime()
            next_sunset = observer_on_the_ground.next_setting(sun).datetime()
        except (ephem.AlwaysUpError):
            # polar summer and sun never sets
            # so it must be daytime...
            self.daytime = True
            sun.compute(observer_on_the_ground)
            # can check with solarzenith angle
            solZenith = np.degrees(sun.alt)
            return None
        except (ephem.NeverUpError):
            # polar winter and sun never sets
            # so it must be nighttime
            self.daytime = False
            sun.compute(observer_on_the_ground)
            # can check with solarzenith angle
            solZenith = np.degrees(sun.alt)
            return None
        # if no exceptions it's not polar and sun does rise and set...
        if next_sunset < next_sunrise:
            self.daytime = True
        elif next_sunset > next_sunrise:
            self.daytime = False
        else:
            import pdb; pdb.set_trace() # something wrong
            self.daytime = -1 #error
        sun.compute(observer_on_the_ground)
        # can check with solarzenith angle
        solZenith = np.degrees(sun.alt)
        self.solarZenith = solZenith
        return None
Beispiel #23
0
converge_percent = 0.0001
max_iter = 50
step_size = .3

######################################################################
######################################################################
######################################################################

########Massage user parameters###################################
oppath += '/'

####get some info from the first uvfile   ################
print "Getting some basic info from %s" % uvfiles[0],
sys.stdout.flush()

sa = ephem.Observer()
sa.pressure = 0

if input_type == 'odf':
    with open(uvfiles[0] + '/header.txt') as f:
        for l in f.readlines():
            if l.split()[0] == 'nChannels':
                nfreq = int(l.split()[1])
            elif l.split()[0] == 'nAntennas':
                nant = int(l.split()[1])
            elif l.split(
            )[0] == 'longitude':  #odf header has bug that switched lat and lon
                sa.lat = float(l.split()[1]) * PI / 180.
            elif l.split()[0] == 'latitude':
                sa.lon = float(l.split()[1]) * PI / 180.
            elif l.split()[0] == 'startFreq':
Beispiel #24
0
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Jan  4 13:55:58 2017

@author: ahmed
"""

# IMPORTATION
from pylab import *
import ephem as ep
# OBSERVATEUR
obs = ep.Observer()
obs.lon, obs.lat, obs.elev = '10.08', '36.4', 100.0
obs.name = "SAT-TUNIS"
# OBJETS
soleil = ep.Sun()
lune = ep.Moon()
# pas de temps - heure
dt = ep.hour
# temps initial
#ts = ep.now()
ts = ep.Date("2019-01-01 00:00:00")
# heure actuelle
tm = ts

for i in range(365 * 24 * 10):
    # nous fixons l'heure actuelle
    obs.date = tm
    # nous calculons les coordonnées
    soleil.compute(obs)
Beispiel #25
0
    print(
        "This program returns the rise and set LSTs for the provided RA and DEC at the requested site"
    )
    print("e.g. riseset mk 12:34:56 -43:21:00")
    print("Site = MeerKAT")
    print("Long,Lat = 21:24:40.0 -30:43:16.0")
    print("Target Coordinates = 12:34:56.00 -43:21:00.0")
    print("Rise Time (LST) = 6:01:30.97")
    print("Set Time (LST)  = 19:10:28.11")
    sys.exit(0)

place = sys.argv[1]
ra = sys.argv[2]
dec = sys.argv[3]

site = ephem.Observer()

# NB. I got all coordinates from wikipedia. Sorry if they are incorrect!
if (place == "jbo" or place == "jodrell"):
    site.long = '-2.30715'
    site.lat = '53.23700'
    site.elevation = 0
    place = "Jodrell Bank"
elif (place == "birr" or place == "Birr" or place == "I-LOFAR"
      or place == "ilofar"):
    site.long = '-7.9133'
    site.lat = '53.0914'
    site.elevation = 0
    place = "Birr"
elif (place == "eff" or place == "effelsberg"):
    site.long = '6:52:58'
Beispiel #26
0
import ephem
from datetime import *
from time import strftime

#Make an observer
fred = ephem.Observer()

#PyEphem takes and returns only UTC times. 15:00 is noon in Fredericton
fred.date = datetime.today()

#Location of Fredericton, Canada
#fred.lon  = str(-66.666667) #Note that lon should be in string format
#fred.lat  = str(45.95)      #Note that lat should be in string format#

#Elevation of Fredericton, Canada, in metres
#fred.elev = 20

#To get U.S. Naval Astronomical Almanac values, use these settings
#fred.pressure= 0
#fred.horizon = '-0:34'

#Location of New York, NY
fred.lon = str(-73.9400)
fred.lat = str(40.6700)

#Elevation of New York, NY in meters
fred.elev = 56.6928
fred.pressure = 0
fred.horizon = '-0:34'

sunrise = fred.previous_rising(ephem.Sun())  #Sunrise
Beispiel #27
0
def ut2Mjd(dateString):
    obs = ephem.Observer()
    obs.date = dateString
    doff = ephem.Date(0) - ephem.Date('1858/11/17')
    mjd = obs.date + doff
    return mjd
Beispiel #28
0
def main():
    """ Main entry point """
    os.system('reset')
    startup_ts = dt.datetime.utcnow().strftime("%Y%m%d_%H%M%S")
    cwd = os.getcwd()
    #--------START Command Line argument parser------------------------------------------------------
    parser = argparse.ArgumentParser(
        description="Generates Doppler Curves from TLE list, \
                                        uses measurement metadata to derive required parameters",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    tle = parser.add_argument_group('TLE related configurations')
    tle_fp_default = '/'.join([cwd, 'tle'])
    tle.add_argument('--tle_file',
                     dest='tle_file',
                     type=str,
                     default='pslv40_st.tle',
                     help="TLE File of candidate satellites",
                     action="store")
    tle.add_argument('--tle_folder',
                     dest='tle_folder',
                     type=str,
                     default=tle_fp_default,
                     help="Folder containing TLE file",
                     action="store")

    meas = parser.add_argument_group('Measurement Related Configurations')
    meas_fp_default = '/'.join([cwd, 'measurements'])
    meas.add_argument(
        '--meas_json',
        dest='meas_json',
        type=str,
        default='DOPPLER_FOX-1D_20180113_161201.862011_UTC_10sps.json',
        help="Converted Doppler offset measurement file, JSON format",
        action="store")
    meas.add_argument(
        '--meas_csv',
        dest='meas_csv',
        type=str,
        default='DOPPLER_FOX-1D_20180113_161201.862011_UTC_10sps.csv',
        help="Converted Doppler offset measurement file, CSV format",
        action="store")
    meas.add_argument(
        '--meas_md',
        dest='meas_md',
        type=str,
        default='DOPPLER_FOX-1D_20180113_161201.862011_UTC_10sps.md',
        help="Measurement metadata file, JSON format",
        action="store")
    meas.add_argument(
        '--meas_folder',
        dest='meas_folder',
        type=str,
        default=meas_fp_default,
        help="Converted Doppler offset measurement file location",
        action="store")

    gen = parser.add_argument_group('Generated Doppler Related Configurations')
    gen_fp_default = '/'.join([cwd, 'generated'])
    gen.add_argument('--gen_folder',
                     dest='gen_folder',
                     type=str,
                     default=gen_fp_default,
                     help="Generated Doppler measurement file location",
                     action="store")
    gen.add_argument(
        '--gen_json',
        dest='gen_json',
        type=str,
        default=None,
        help="Generated Doppler offset measurement file, JSON format",
        action="store")
    gen.add_argument(
        '--gen_csv',
        dest='gen_csv',
        type=str,
        default=None,
        help="Generated Doppler offset measurement file, CSV format",
        action="store")

    plot = parser.add_argument_group('Plotting Related Configurations')
    fig_fp_default = '/'.join([cwd, 'figures'])
    plot.add_argument('--fig_path',
                      dest='fig_path',
                      type=str,
                      default=fig_fp_default,
                      help="Folder location for saved figures",
                      action="store")
    plot.add_argument('--fig_save',
                      dest='fig_save',
                      type=int,
                      default=0,
                      help="Save Figure Flag, 0=N, 1=Y",
                      action="store")

    args = parser.parse_args()
    #--------END Command Line argument parser------------------------------------------------------
    import warnings
    warnings.filterwarnings('ignore')

    #--Read in Measurement metadata
    fp_md = '/'.join([args.meas_folder, args.meas_md])
    if not os.path.isfile(fp_md) == True:
        print 'ERROR: invalid Measurement Metadata file: {:s}'.format(fp_md)
        sys.exit()

    print 'Importing measurement metadata from: {:s}'.format(fp_md)
    with open(fp_md, 'r') as f:
        md = json.load(f)

    for k in md.keys():
        print k, md[k]
    #with open

    #--Read in TLE Files--
    tle = utilities.pyephem.tle_file_input(args.tle_folder, args.tle_file)
    #print tle

    #--create list of satellite objects with pyephem--
    sats = []  #list of satellite objects
    for sat in tle.keys():
        ephem_sat = ephem.readtle(sat, tle[sat]['line1'], tle[sat]['line2'])
        norad_id = tle[sat]['line1'][2:7]
        sats.append(utilities.satellite.satellite(ephem_sat, sat, norad_id))

    #--create ground station object with pyephem--
    gs = ephem.Observer()
    gs.lat, gs.lon, gs.elevation =  md['gs_lat']*deg2rad, \
                                    md['gs_lon']*deg2rad, \
                                    md['gs_alt']

    #Read in Doppler Measurement File
    #This data is needed to get the relevant time stamps
    fp_meas = '/'.join([args.meas_folder, args.meas_json])
    print 'Importing measurement metadata from: {:s}'.format(fp_meas)
    df = pd.read_json(fp_meas, orient='records')
    df.name = md['sat_name']

    dopplers = []  #list containing doppler data, might not be needed
    for sat in sats:
        print "Generating Doppler data for {:s}_{:s}".format(
            sat.sat_name, sat.norad_id)
        print "Downlink Center Freq [MHz]: {:3.6f}".format(
            md['rx_center_freq'] / 1e6)
        dop_df = sat.gen_doppler(   gs, \
                                    df['timestamp'].values.tolist(), \
                                    md['rx_center_freq'])

        dopplers.append(dop_df)

    for dop in dopplers:
        ts = dop['timestamp'][0].strftime("%Y%m%d_%H%M%S.%f_UTC")
        fn = '_'.join(['DOPPLER', dop.name, ts, md['samp_rate_str']])
        fp_json = '/'.join([args.gen_folder, fn]) + '.json'
        fp_csv = '/'.join([args.gen_folder, fn]) + '.csv'

        #--Export JSON Doppler File
        print "Exporting JSON Doppler Measurement File: {:s}".format(fp_json)
        dop.to_json(fp_json, \
                    orient='records', \
                    date_format='iso', \
                    date_unit = 'us')

        #--Export CSV Doppler File
        print " Exporting CSV Doppler Measurement File: {:s}".format(fp_csv)
        dop.to_csv( fp_csv, \
                    index_label ="index", \
                    float_format="%.10f", \
                    date_format='%Y-%m-%dT%H:%M:%S.%fZ')
Beispiel #29
0
def load(fnames,
         tag=None,
         sat_id=None,
         obs_long=0.,
         obs_lat=0.,
         obs_alt=0.,
         TLE1=None,
         TLE2=None):
    """
    Returns data and metadata in the format required by pysat. Finds position
    of satellite in both ECI and ECEF co-ordinates.

    Routine is directly called by pysat and not the user.

    Parameters
    ----------
    fnames : list-like collection
        File name that contains date in its name.
    tag : string
        Identifies a particular subset of satellite data
    sat_id : string
        Satellite ID
    obs_long: float
        Longitude of the observer on the Earth's surface
    obs_lat: float
        Latitude of the observer on the Earth's surface
    obs_alt: float
        Altitude of the observer on the Earth's surface
    TLE1 : string
        First string for Two Line Element. Must be in TLE format
    TLE2 : string
        Second string for Two Line Element. Must be in TLE format

    Example
    -------
      inst = pysat.Instrument('pysat', 'sgp4',
              TLE1='1 25544U 98067A   18135.61844383  .00002728  00000-0  48567-4 0  9998',
              TLE2='2 25544  51.6402 181.0633 0004018  88.8954  22.2246 15.54059185113452')
      inst.load(2018, 1)

    """

    # wgs72 is the most commonly used gravity model in satellite tracking
    # community
    from sgp4.earth_gravity import wgs72
    from sgp4.io import twoline2rv
    import ephem
    import pysatMagVect

    # TLEs (Two Line Elements for ISS)
    # format of TLEs is fixed and available from wikipedia...
    # lines encode list of orbital elements of an Earth-orbiting object
    # for a given point in time
    line1 = (
        '1 25544U 98067A   18135.61844383  .00002728  00000-0  48567-4 0  9998'
    )
    line2 = (
        '2 25544  51.6402 181.0633 0004018  88.8954  22.2246 15.54059185113452'
    )
    # use ISS defaults if not provided by user
    if TLE1 is not None:
        line1 = TLE1
    if TLE2 is not None:
        line2 = TLE2

    # create satellite from TLEs and assuming a gravity model
    # according to module webpage, wgs72 is common
    satellite = twoline2rv(line1, line2, wgs72)

    # grab date from filename
    parts = os.path.split(fnames[0])[-1].split('-')
    yr = int(parts[0])
    month = int(parts[1])
    day = int(parts[2][0:2])
    date = pysat.datetime(yr, month, day)

    # create timing at 1 Hz (for 1 day)
    times = pds.date_range(start=date,
                           end=date + pds.DateOffset(seconds=86399),
                           freq='1S')
    # reduce requirements if on testing server
    # TODO Remove this when testing resources are higher
    on_travis = os.environ.get('ONTRAVIS') == 'True'
    if on_travis:
        times = times[0:100]

    # create list to hold satellite position, velocity
    position = []
    velocity = []
    for time in times:
        # orbit propagator - computes x,y,z position and velocity
        pos, vel = satellite.propagate(time.year, time.month, time.day,
                                       time.hour, time.minute, time.second)
        position.extend(pos)
        velocity.extend(vel)

    # put data into DataFrame
    data = pysat.DataFrame(
        {
            'position_eci_x': position[::3],
            'position_eci_y': position[1::3],
            'position_eci_z': position[2::3],
            'velocity_eci_x': velocity[::3],
            'velocity_eci_y': velocity[1::3],
            'velocity_eci_z': velocity[2::3]
        },
        index=times)
    data.index.name = 'Epoch'

    # add position and velocity in ECEF
    # add call for GEI/ECEF translation here
    # instead, since available, I'll use an orbit predictor from another
    # package that outputs in ECEF
    # it also supports ground station calculations

    # the observer's (ground station) position on the Earth surface
    site = ephem.Observer()
    site.lon = str(obs_long)
    site.lat = str(obs_lat)
    site.elevation = obs_alt

    # The first parameter in readtle() is the satellite name
    sat = ephem.readtle('pysat', line1, line2)
    output_params = []
    for time in times:
        lp = {}
        site.date = time
        sat.compute(site)
        # parameters relative to the ground station
        lp['obs_sat_az_angle'] = ephem.degrees(sat.az)
        lp['obs_sat_el_angle'] = ephem.degrees(sat.alt)
        # total distance away
        lp['obs_sat_slant_range'] = sat.range
        # satellite location
        # sub latitude point
        lp['glat'] = np.degrees(sat.sublat)
        # sublongitude point
        lp['glong'] = np.degrees(sat.sublong)
        # elevation of sat in m, stored as km
        lp['alt'] = sat.elevation / 1000.
        # get ECEF position of satellite
        lp['x'], lp['y'], lp['z'] = pysatMagVect.geodetic_to_ecef(
            lp['glat'], lp['glong'], lp['alt'])
        output_params.append(lp)
    output = pds.DataFrame(output_params, index=times)
    # modify input object to include calculated parameters
    data[['glong', 'glat', 'alt']] = output[['glong', 'glat', 'alt']]
    data[['position_ecef_x', 'position_ecef_y', 'position_ecef_z']] = \
        output[['x', 'y', 'z']]
    data['obs_sat_az_angle'] = output['obs_sat_az_angle']
    data['obs_sat_el_angle'] = output['obs_sat_el_angle']
    data['obs_sat_slant_range'] = output['obs_sat_slant_range']
    return data, meta.copy()
    def find_parallax(self, date):
        '''Find the maximum parallax of self.planet on the given date
           from self.observer's location -- in other words, the difference
           in Mars' position between the observer's position and an
           observer at the same latitude but opposite longitude:
           this tells you you how much difference you would see from
           your position if Mars didn't move between your sunrise and sunset.
        '''
        save_date = self.observer.date

        # https://www.quora.com/Is-it-possible-to-measure-the-distance-to-Mars-using-a-telescope-and-the-parallax-method
        # says it should vary between 361.9 arc sec > a > 51.6 arc sec,
        # but I think he's smoking something.
        # So let's calculate it.
        observer = ephem.Observer()
        observer.name = "Observer"
        # To calculate from a point on the equator, set observer.lat to 0.
        observer.lat = self.observer.lat
        observer.lon = self.observer.lon
        observer.elevation = 0

        antipode = ephem.Observer()
        antipode.name = "Anti-point"
        antipode.lat = observer.lat
        antipode.lon = 360 - self.observer.lon
        antipode.elevation = 0

        observer.date = observer.next_rising(self.planet, start=date)
        self.planet.compute(observer)
        our_ra = self.planet.ra
        our_dec = self.planet.dec
        antipode.date = observer.date
        self.planet.compute(antipode)
        antipode_ra = self.planet.ra
        antipode_dec = self.planet.dec

        # Calculate it the straightforward way using trig:
        print()
        mars_dist_miles = self.planet.earth_distance * 9.2956e7
        print("Miles to Mars:", mars_dist_miles)
        earth_mean_radius = 3958.8  # in miles
        half_dist = earth_mean_radius * math.cos(observer.lat)
        print("Distance between observers:", 2. * half_dist)
        par = 2. * math.atan(
            half_dist / mars_dist_miles) * 180 / math.pi * 3600
        print("Calculated parallax (arcsec):", par)

        # See what pyephem calculates as the difference between observations:
        print()
        print("     Us:", our_ra, our_dec)
        print("Anti-pt:", antipode_ra, antipode_dec)
        print("parallax on %s: RA %f, dec %f" %
              (antipode.date, our_ra - antipode_ra, our_dec - antipode_dec))
        total_par = (math.sqrt((our_ra - antipode_ra)**2 +
                               (our_dec - antipode_dec)**2) * 180. / math.pi *
                     3600.)
        print("Total parallax (sum of squares): %f arcseconds" % total_par)
        print()

        # Set planet back to its previous position,
        # since we're in the middle of ongoing computations:
        self.planet.compute(self.observer.date)