Пример #1
0
    def __init__(self,
                 coordinates,
                 observatory='Mt Graham',
                 night=None,
                 timezone='UTC',
                 ax=None,
                 timedelta=None):
        if not isinstance(coordinates, SkyCoord):
            self.coord = SkyCoord(coordinates, unit=(u.hourangle, u.deg))
        else:
            self.coord = coordinates

        try:
            self.observer = Observer.at_site(observatory, timezone=timezone)
        except USE:
            print EarthLocation.get_site_names()
            raise

        if not night:
            self.time = Time.now()
        else:
            self.time = Time(night)

        if timedelta:
            self.time = timedelta

        self.ax = ax

        self._make_figure()
Пример #2
0
 def init_units(self, num_units):
     """Initialize a network of new units and their cameras, assigning unique IDs."""
     units = []
     for i in range(num_units):
         unit = "PAN{:03d}".format(i)
         site = random.choice(EarthLocation.get_site_names())
         self.unit_dict[unit] = site
         self.init_cameras(unit)
         units.append(unit)
     return units
Пример #3
0
 def init_units(self, num_units):
     """Initialize a network of new units and their cameras, assigning unique IDs."""
     units = []
     for i in range(num_units):
         unit = "PAN{:03d}".format(i)
         site = random.choice(EarthLocation.get_site_names())
         self.unit_dict[unit] = site
         self.init_cameras(unit)
         units.append(unit)
     return units
Пример #4
0
 def __init__(self, filename, location):
     self.hdu_list = fits.open(filename)
     self.hdr = self.hdu_list[0].header
     self.ra = self.hdr['RA']
     self.dec = self.hdr['DEC']
     try:
         self.location = EarthLocation.of_site(location)
     except errors.UnknownSiteException:
         print('Unknown site, use one of these sites:')
         print(EarthLocation.get_site_names())
         sys.exit(1)
Пример #5
0
def parser():
    from astropy.coordinates import EarthLocation
    parser = ArgumentParser(parents=[figure_parser])
    parser.add_argument('-v',
                        '--verbose',
                        action='store_true',
                        help='Print airmass table to stdout')
    parser.add_argument('input',
                        metavar='INPUT.fits[.gz]',
                        type=FileType('rb'),
                        default='-',
                        nargs='?',
                        help='Input FITS file')
    parser.add_argument('--time', help='UTC time')
    parser.add_argument('--max-airmass',
                        default=2.5,
                        type=float,
                        help='Maximum airmass')
    parser.add_argument(
        '--twilight',
        default='astronomical',
        choices=('astronomical', 'nautical', 'civil'),
        help='Twilight definition: astronomical (-18 degrees), '
        'nautical (-12 degrees), or civil (-6 degrees)')
    parser.add_argument('--site',
                        nargs='*',
                        default=[],
                        choices=EarthLocation.get_site_names(),
                        help='Observatory site')
    parser.add_argument('--site-name',
                        nargs='*',
                        default=[],
                        help='Observatory name.')
    parser.add_argument('--site-longitude',
                        nargs='*',
                        default=[],
                        metavar='DEG',
                        type=float,
                        help='Observatory longitude on the WGS84 ellipsoid.')
    parser.add_argument('--site-latitude',
                        nargs='*',
                        default=[],
                        metavar='DEG',
                        type=float,
                        help='Observatory latitude on the WGS84 ellipsoid.')
    parser.add_argument('--site-height',
                        nargs='*',
                        default=[],
                        metavar='METERS',
                        type=float,
                        help='Observatory height from the WGS84 ellipsoid.')
    return parser
Пример #6
0
def test_EarthLocation_basic():
    greenwichel = EarthLocation.of_site('greenwich')
    lon, lat, el = greenwichel.to_geodetic()
    assert_quantity_allclose(lon, Longitude('0:0:0', unit=u.deg),
                             atol=10*u.arcsec)
    assert_quantity_allclose(lat, Latitude('51:28:40', unit=u.deg),
                             atol=1*u.arcsec)
    assert_quantity_allclose(el, 46*u.m, atol=1*u.m)

    names = EarthLocation.get_site_names()
    assert 'greenwich' in names
    assert 'example_site' in names

    with pytest.raises(KeyError) as exc:
        EarthLocation.of_site('nonexistent site')
    assert exc.value.args[0] == "Site 'nonexistent site' not in database. Use EarthLocation.get_site_names to see available sites."
Пример #7
0
    def show_sites(self):
        """
        Displays the different sites on earth which are available
        """
        locations = EarthLocation.get_site_names()

        locations = [location for location in locations if location != '']

        cutoff_index = locations.index("Whipple Observatory")
        new_locations = locations[:cutoff_index + 1]

        location_string = ', '.join(new_locations)

        self.display_info(
            "List of astronomical sites:\n{}".format(location_string),
            "List of sites")
Пример #8
0
 def get_current_network(self):
     """Get the units and their cameras that currently have simulated data on the cloud."""
     units = []
     files = self.storage.list_remote(prefix='LC')
     for fl in files:
         dirs = fl.split('/')
         for i in range(len(dirs)):
             dir = dirs[i]
             if dir.startswith('PAN'):
                 unit = dir
                 if unit not in units:
                     units.append(unit)
                     site = random.choice(EarthLocation.get_site_names())
                     self.unit_dict[unit] = site
                 cam = dirs[i + 1]
                 if cam not in self.cameras[unit]:
                     self.cameras[unit].append(cam)
                 break
     return units
Пример #9
0
 def get_current_network(self):
     """Get the units and their cameras that currently have simulated data on the cloud."""
     units = []
     files = self.storage.list_remote(prefix='LC')
     for fl in files:
         dirs = fl.split('/')
         for i in range(len(dirs)):
             dir = dirs[i]
             if dir.startswith('PAN'):
                 unit = dir
                 if unit not in units:
                     units.append(unit)
                     site = random.choice(EarthLocation.get_site_names())
                     self.unit_dict[unit] = site
                 cam = dirs[i + 1]
                 if cam not in self.cameras[unit]:
                     self.cameras[unit].append(cam)
                 break
     return units
Пример #10
0
def test_EarthLocation_basic():
    greenwichel = EarthLocation.of_site('greenwich')
    lon, lat, el = greenwichel.to_geodetic()
    assert_quantity_allclose(lon,
                             Longitude('0:0:0', unit=u.deg),
                             atol=10 * u.arcsec)
    assert_quantity_allclose(lat,
                             Latitude('51:28:40', unit=u.deg),
                             atol=1 * u.arcsec)
    assert_quantity_allclose(el, 46 * u.m, atol=1 * u.m)

    names = EarthLocation.get_site_names()
    assert 'greenwich' in names
    assert 'example_site' in names

    with pytest.raises(KeyError) as exc:
        EarthLocation.of_site('nonexistent site')
    assert exc.value.args[
        0] == "Site 'nonexistent site' not in database. Use EarthLocation.get_site_names to see available sites."
def parser():
    from astropy.coordinates import EarthLocation
    site_names = EarthLocation.get_site_names()
    parser = ArgumentParser(parents=[figure_parser])
    parser.add_argument('-v',
                        '--verbose',
                        action='store_true',
                        help='Print airmass table to stdout')
    parser.add_argument('input',
                        metavar='INPUT.fits[.gz]',
                        type=FileType('rb'),
                        default='-',
                        nargs='?',
                        help='Input FITS file')
    parser.add_argument('--time', help='UTC time')
    parser.add_argument('--site',
                        metavar='SITE',
                        choices=site_names,
                        help='Observatory site')
    parser.add_argument('--help-site',
                        action=HelpChoicesAction,
                        choices=site_names)
    parser.add_argument('--site-longitude',
                        metavar='DEG',
                        type=float,
                        help='Observatory longitude on the WGS84 ellipsoid. '
                        'Mutually exclusive with --site.')
    parser.add_argument('--site-latitude',
                        metavar='DEG',
                        type=float,
                        help='Observatory latitude on the WGS84 ellipsoid. '
                        'Mutually exclusive with --site.')
    parser.add_argument('--site-height',
                        metavar='METERS',
                        type=float,
                        help='Observatory height from the WGS84 ellipsoid. '
                        'Mutually exclusive with --site.')
    parser.add_argument('--site-timezone',
                        help='Observatory time zone, e.g. "US/Pacific". '
                        'Mutually exclusive with --site.')
    return parser
Пример #12
0
 def __init__(self, instrument='ultracam', tel_location=None):
     root = Tk()
     root.withdraw()
     self.instrument = instrument
     format_dict = {'Name': 'string',
                    'RA_hms': 'string',
                    'DEC_dms': 'string',
                    'Type': 'string',
                    'SpType': 'string',
                    'fname': 'string',
                    'Variability': 'string'}
     # set instrument specific variables
     if self.instrument=='ultracam':
         self.tel_location = EarthLocation.of_site('La Silla Observatory')
         self.filt2ccd = {'u':'3', 'us':'3', 'g':'2', 'gs':'2', 'r':'1',
                          'rs':'1', 'i':'1', 'is':'1', 'z':'1', 'zs':'1'}
         self.rootDataDir = '/local/alex/backed_up_on_astro3/Data/photometry/ultracam'
         self.stds = pd.read_csv('cam_standards/ucam_flux_stds.csv', dtype=format_dict)
     elif self.instrument=='hipercam':
         self.tel_location = EarthLocation.of_site('Roque de los Muchachos')
         self.filt2ccd = {'us':'1', 'gs':'2', 'rs':'3', 'is':'4', 'zs':'5'}
         self.rootDataDir = '/local/alex/backed_up_on_astro3/Data/photometry/hipercam'
         self.stds = pd.read_csv('cam_standards/hcam_flux_stds.csv', dtype=format_dict)
     else: raise ValueError(f"{self.instrument} is not a valid instrument")
     if tel_location:
         if tel_location in EarthLocation.get_site_names():
             self.tel_location = EarthLocation.of_site(tel_location)
         elif isinstance(tel_location, EarthLocation):
             self.tel_location = tel_location
         else:
             raise ValueError(f'"{tel_location}" not a valid EarthLocation site name or '
                              'an EarthLocation object')
     # set extinction coeffs and instrumental zeropoints
     self.set_default()
     #initialise observation dict
     self.observations = dict.fromkeys(['science', 'std', 'atm'])
Пример #13
0
    test_value = 0
    for hval in inithour.split(':'):
        test_value += np.int(hval)
    if test_value == 0:
        inithour = '00:00:00.1'

    return inithour, night_starts

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

if len(sys.argv) < 2:
    print_help()
elif ('--help' in sys.argv) | ('-h' in sys.argv):
    print_help()
elif (len(sys.argv) == 2) & ('--observatory' in sys.argv):
    for site in EarthLocation.get_site_names(): print(site)
    sys.exit(0)

# define the starting night
if ('--nightstarts' in sys.argv) | ('-ns' in sys.argv):
    if ('--nightstarts' in sys.argv):
        index = np.arange(len(sys.argv))[np.array(sys.argv) == '--nightstarts']
    else:
        index = np.arange(len(sys.argv))[np.array(sys.argv) == '-ns']
    night_starts = np.array(sys.argv)[index + 1].item()
    night_beg = night_starts
    if len(night_starts.split('-')) < 3:
        raise IOError('wrong format for date')
    else:
        startsin = Time('%sT23:59:59' % night_starts)
        ns = startsin.datetime
Пример #14
0
def demo_site_chooser():
    EarthLocation.get_site_names(
    )  # Print names of all sites astropy knows about. May need internet connection
    keck = EarthLocation.of_site('keck')
    lco = EarthLocation.of_site('Las Campanas Observatory')
    return (0)
Пример #15
0
def createTargetLists():
    allSiteNames = EarthLocation.get_site_names()
    observatoryName = "Roque de los Muchachos"

    gtcObs = Observer.at_site(
        observatoryName)  #, timezone='Eastern Standard Time')
    print('dir(gtcObs) = ', dir(gtcObs))
    print('gtcObs.location = ', gtcObs.location)
    #    gtc = EarthLocation(lat=dmsToDeg()*u.deg, lon=149.0685*u.deg, height=1165*u.m)
    gtc_utcoffset = 1 * u.hour  # Australian Eastern Standard Time

    minimumAltitude = 30.

    midnight = midnightTime - gtc_utcoffset

    #print('astronomical twilight as Observatory: %s - %s' % (obs.twilight_evening_astronomical(midnight), obs.twilight_morning_astronomical(midnight)))
    observationStartTime = gtcObs.twilight_evening_astronomical(
        midnight)  #Time('2019-9-5 19:10:00') - utcoffset
    observationEndTime = gtcObs.twilight_morning_astronomical(
        midnight)  #Time('2019-9-6 4:55:00') - utcoffset
    observationStartTime.format = 'iso'
    observationEndTime.format = 'iso'

    catLines = readCSV(allPossibleTargets)
    targetsWithCS = findCSPNe(catLines)

    time = observationStartTime
    times = [time]
    fullHours = []
    while time < observationEndTime:
        time += 1 * u.minute
        #                    print('time = ',time)
        times.append(time)
        #                    print('time = ',time)
        #                    print('type(time) = ',type(time))
        #                    print('dir(time) = ',dir(time))
        #                    print('type(time.to_datetime()) = ',type(time.to_datetime()))
        #                    print('dir(time.to_datetime()) = ',dir(time.to_datetime()))
        if time.to_datetime().strftime("%M") == '00':
            #                        print('full hour found at ',time)
            fullHours.append(time)

    goodTargets = findGoodTargets(targetsWithCS,
                                  gtcObs.location,
                                  raString='CS_DRAJ2000',
                                  decString='CS_DDECJ2000')
    writeCSV(goodTargets, targetListOut, 'DRAJ2000')

    allGoodTargets = []
    allGoodTargetIDs = []
    for time in fullHours:
        visibleAt = findTargetsVisibleAt(goodTargets, time, gtcObs.location,
                                         gtc_utcoffset, minimumAltitude)
        localTime = time + gtc_utcoffset
        writeCSV(
            visibleAt, targetListOut[:-4] + '_visible_at_' + date + '_' +
            localTime.strftime("%H-%M") + '.csv', 'DRAJ2000')

        #        print('visibleAt[0] = ',visibleAt[0])
        ra = float(visibleAt[0]['CS_DRAJ2000'])
        dec = float(visibleAt[0]['CS_DDECJ2000'])
        targetCoord = SkyCoord(ra=ra * u.deg, dec=dec * u.deg, frame='icrs')
        #        print('ra, dec = ',ra,dec)
        #        plot_target(targetCoord, gtcObs.location, observatoryName, gtc_utcoffset, date, False)
        print('ra, dec = ', ra, dec)

        for line in visibleAt:
            if line['idPNMain'] not in allGoodTargetIDs:
                allGoodTargetIDs.append(line['idPNMain'])
                allGoodTargets.append(line)
    writeCSV(allGoodTargets,
             targetListOut[:-4] + '_visible_at_' + date + '.csv')
Пример #16
0
def demo_site_chooser() :
    EarthLocation.get_site_names()  # Print names of all sites astropy knows about. May need internet connection
    keck = EarthLocation.of_site('keck')  
    lco  = EarthLocation.of_site('Las Campanas Observatory') 
    return(0)
Пример #17
0
#refProfApDef = os.path.join(refPath,'database/aprefProfApDef_spupnic_gr7_15_85')#16_3')
#refProfApDef = os.path.join(refPath,'database/aprefProfApDef_spupnic_gr7_%d_%d')
#refProfApDef = os.path.join(refPath,'database/aprefProfApDef_spupnic_gr7_%d_%d_aug2013')
refProfApDef = os.path.join(refPath, 'database/aprefProfApDef_spupnic_May2007')
#lineList = os.path.join(refPath,'saao_refspec_gr7_angle16_3_lines_identified_good.dat')
#lineList = os.path.join(refPath,'saao_refspec_gr7_angle16_3_may2020_lines_identified_good.dat')
#lineList = os.path.join(refPath,'saao_refspec_gr7_angle15_85_lines_identified_good.dat')
#lineList = os.path.join(refPath,'saao_refspec_gr7_angle%d_%d_lines_identified_good_aug2018.dat')
#lineList = os.path.join(refPath,'saao_refspec_gr7_angle%d_%d_lines_identified_good_mar2014.dat')
#lineList = os.path.join(refPath,'saao_refspec_gr7_angle%d_%d_lines_identified_good_aug2013.dat')
lineList = os.path.join(refPath, 'saao_refspec_may2007.new')
#referenceSpectrum = '/Users/azuri/stella/referenceFiles/spupnic/refArc_spupnic_gr7_15_70_otzxfifEc_aug2018.fits'
#referenceSpectrum = '/Users/azuri/stella/referenceFiles/spupnic/refArc_spupnic_otzxfifEc_mar2014.fits'
referenceSpectrum = '/Users/azuri/stella/referenceFiles/spupnic/refArc_spupnic_may2007.fits'

print('EarthLocation.get_site_names() = ', EarthLocation.get_site_names())
observatoryLocation = EarthLocation.of_site('SAAO')
print('SAAO.lon = ', observatoryLocation.lon)
print('SAAO.lat = ', observatoryLocation.lat)

fluxStandardNames, fluxStandardDirs, fluxStandardFileNames = readFluxStandardsList(
)

if not os.path.exists(os.path.join(workPath, 'database')):
    os.makedirs(os.path.join(workPath, 'database'))


def fixHeaders():
    with open(os.path.join(workPath, 'allFits.list'), 'r') as f:
        lines = f.readlines()
    for line in lines: