コード例 #1
0
class wcs2refracted_azel(object):

    latitude = 35.940874
    longitude = 138.472153
    height = 1386
    wcs_frame = 'fk5'
    nobeyama = EarthLocation(lat=latitude * u.deg,
                             lon=longitude * u.deg,
                             height=height * u.m)
    wcs = ''
    wcs_li = []

    press = 1000
    temp = 0
    humid = 0.5
    obswl = 230  #GHz

    #obswl = 600000 #GHz

    def __init__(self):
        rospy.Subscriber('/necst/telescope/coordinate/wcs_azel_cmd',
                         Float64MultiArray, self.recieve_wcs)
        rospy.Subscriber('/necst/telescope/coordinate/wcs_frame_cmd', String,
                         self.recieve_wcs_frame)
        rospy.Subscriber('/necst/telescope/coordinate/stop_cmd', Bool,
                         self.recieve_stop_cmd)

        rospy.Subscriber('/necst/telescope/weather/pressure', Float64,
                         self.recieve_pressure)
        rospy.Subscriber('/necst/telescope/weather/temperature', Float64,
                         self.recieve_temprature)
        rospy.Subscriber('/necst/telescope/weather/humidity', Float64,
                         self.recieve_humidity)
        rospy.Subscriber('/necst/telescope/obswl', Float64, self.recieve_obswl)

        self.pub_real_azel = rospy.Publisher(
            '/necst/telescope/coordinate/refracted_azel_cmd',
            Float64MultiArray,
            queue_size=1)
        self.pub_wcs = rospy.Publisher('/necst/telescope/coordinate/wcs',
                                       Float64MultiArray,
                                       queue_size=1)
        self.init_flag = True

    def recieve_wcs(self, q):
        self.wcs = q.data

    def recieve_wcs_frame(self, q):
        self.wcs_frame = q.data

    def recieve_pressure(self, q):
        self.press = q.data

    def recieve_temprature(self, q):
        self.temp = q.data

    def recieve_humidity(self, q):
        self.humid = q.data

    def recieve_obswl(self, q):
        self.obswl = q.data

    def recieve_stop_cmd(self, q):
        if q.data == True:
            self.wcs = ''
            self.init_flag = True
        else:
            pass

    def convert_azel(self, dt):
        on_coord = SkyCoord(self.wcs[0],
                            self.wcs[1],
                            frame=self.wcs_frame,
                            unit=(u.deg, u.deg))
        on_coord.location = self.nobeyama
        on_coord.pressure = self.press * u.hPa
        on_coord.temperature = self.temp * u.deg_C
        on_coord.relative_humidity = self.humid
        on_coord.obswl = (astropy.constants.c /
                          (self.obswl * u.GHz)).to('micron')
        altaz_list = on_coord.transform_to(
            AltAz(obstime=Time.now() + TimeDelta(dt, format='sec')))
        return altaz_list

    def publish_azel(self):
        while not rospy.is_shutdown():
            if self.wcs != '':
                x = self.wcs[0]
                y = self.wcs[1]
                if self.init_flag == True:
                    for i in range(10):
                        altaz = self.convert_azel(dt=0.1 * i)
                        obstime = altaz.obstime.to_value("unix")
                        alt = altaz.alt.deg + self.wcs[2]
                        az = altaz.az.deg + self.wcs[3]
                        array = Float64MultiArray()
                        array.data = [obstime, az, alt]
                        self.pub_real_azel.publish(array)

                        data = [obstime, x, y]
                        self.wcs_li.append(data)

                    self.init_flag = False

                else:
                    altaz = self.convert_azel(dt=1)
                    obstime = altaz.obstime.to_value("unix")
                    alt = altaz.alt.deg
                    az = altaz.az.deg
                    array = Float64MultiArray()
                    array.data = [obstime, az, alt]
                    self.pub_real_azel.publish(array)

                    data = [obstime, x, y]
                    self.wcs_li.append(data)
                    time.sleep(0.1)

            else:
                time.sleep(0.0001)
            continue

    def wcs_pub(self):
        while not rospy.is_shutdown():
            #print(len(self.offset_li))
            try:
                wcs = self.wcs_li.pop(0)
            except:
                time.sleep(0.00001)
                continue

            while True:
                if wcs[0] < time.time():
                    q = Float64MultiArray()
                    q.data = [wcs[0], wcs[1], wcs[2]]  #[time,x,y]
                    self.pub_wcs.publish(q)
                    break
                else:
                    time.sleep(0.0001)
                    continue

            continue

    def start_thread(self):
        th = threading.Thread(target=self.publish_azel)
        th.setDaemon(True)
        th.start()

        th2 = threading.Thread(target=self.wcs_pub)
        th2.setDaemon(True)
        th2.start()
コード例 #2
0
ファイル: plot_tel_airmass.py プロジェクト: pndaly/SASSy
def plot_tel_airmass(_log=None,
                     _ra=math.nan,
                     _dec=math.nan,
                     _oid='',
                     _tel='mmt',
                     _img=''):

    # define observer, observatory, time, frame, sun and moon
    if _tel.lower().strip() == 'bok':
        _observatory = EarthLocation(lat=BOK_LATITUDE * u.deg,
                                     lon=BOK_LONGITUDE * u.deg,
                                     height=BOK_ELEVATION * u.m)
        _observer = Observer(location=_observatory,
                             name='BOK',
                             timezone='US/Arizona')
    elif _tel.lower().strip() == 'greenwich':
        _observatory = EarthLocation(lat=GREENWICH_LATITUDE * u.deg,
                                     lon=GREENWICH_LONGITUDE * u.deg,
                                     height=GREENWICH_ELEVATION * u.m)
        _observer = Observer(location=_observatory,
                             name='GREENWICH',
                             timezone='Greenwich')
    elif _tel.lower().strip() == 'kuiper':
        _observatory = EarthLocation(lat=KUIPER_LATITUDE * u.deg,
                                     lon=KUIPER_LONGITUDE * u.deg,
                                     height=KUIPER_ELEVATION * u.m)
        _observer = Observer(location=_observatory,
                             name='KUIPER',
                             timezone='US/Arizona')
    elif _tel.lower().strip() == 'mmt':
        _observatory = EarthLocation(lat=MMT_LATITUDE * u.deg,
                                     lon=MMT_LONGITUDE * u.deg,
                                     height=MMT_ELEVATION * u.m)
        _observer = Observer(location=_observatory,
                             name='MMT',
                             timezone='US/Arizona')
    elif _tel.lower().strip() == 'steward':
        _observatory = EarthLocation(lat=STEWARD_LATITUDE * u.deg,
                                     lon=STEWARD_LONGITUDE * u.deg,
                                     height=STEWARD_ELEVATION * u.m)
        _observer = Observer(location=_observatory,
                             name='STEWARD',
                             timezone='US/Arizona')
    elif _tel.lower().strip() == 'vatt':
        _observatory = EarthLocation(lat=VATT_LATITUDE * u.deg,
                                     lon=VATT_LONGITUDE * u.deg,
                                     height=VATT_ELEVATION * u.m)
        _observer = Observer(location=_observatory,
                             name='VATT',
                             timezone='US/Arizona')
    else:
        return

    if _log:
        _log.info(
            f"plot_tel_airmass(_ra={_ra:.3f}, _dec={_dec:.3f}, _oid={_oid}, _tel={_tel}, _img={_img}"
        )

    # get sun, moon etc
    _now_isot = get_isot(0)
    _now = Time(_now_isot)
    _start_time = Time(_now_isot.replace(
        'T',
        ' ')) + 1.0 * u.day * np.linspace(0.0, 1.0, int(24.0 * 60.0 / 5.0))

    _frame = AltAz(obstime=_start_time, location=_observatory)

    _moon = _observer.moon_altaz(_start_time)
    _moon_time = _moon.obstime
    _moon_alt = _moon.alt
    _moon_az = _moon.az

    _sun = _observer.sun_altaz(_start_time)
    _sun_time = _sun.obstime
    _sun_alt = _sun.alt
    _sun_az = _sun.az

    # convert
    _oid_s = str(_oid).replace("'", "")
    _ra_hms = ra_to_hms(_ra)
    _dec_dms = dec_to_dms(_dec)
    _dec_dms = f"{_dec_dms}".replace("+", "")
    _sup_title = f"{_oid} Airmass @ {_tel.upper()}"
    _sub_title = f"RA={_ra_hms} ({_ra:.3f}), Dec={_dec_dms} ({_dec:.3f})"

    # get target
    _coords = SkyCoord(ra=_ra * u.deg, dec=_dec * u.deg)
    _target = _coords.transform_to(_frame)
    _target_time = _target.obstime
    _target_alt = _target.alt
    _target_az = _target.az

    # plot data
    _time = str(_target_time[0]).split()[0]
    fig, ax = plt.subplots()
    fig.suptitle(_sup_title.replace("'", "").replace("{", "").replace("}", ""))
    _ax_scatter = ax.plot(_moon_time.datetime,
                          _moon_alt.degree,
                          'g--',
                          label='Moon')
    _ax_scatter = ax.plot(_sun_time.datetime,
                          _sun_alt.degree,
                          'r--',
                          label='Sun')
    _ax_scatter = ax.scatter(_target_time.datetime,
                             _target_alt.degree,
                             c=np.array(_target_az.degree),
                             lw=0,
                             s=8,
                             cmap='viridis')
    ax.plot([_now.datetime, _now.datetime], [ASTRONOMICAL_DAWN, 90.0],
            'orange')
    ax.plot([_target_time.datetime[0], _target_time.datetime[-1]], [0.0, 0.0],
            'black')
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
    plt.gcf().autofmt_xdate()
    plt.colorbar(_ax_scatter, ax=ax).set_label(f'Azimuth ({OBS_DEGREE})')
    ax.set_ylim([ASTRONOMICAL_DAWN, 90.0])
    ax.set_xlim([_target_time.datetime[0], _target_time.datetime[-1]])
    ax.set_title(_sub_title)
    ax.set_ylabel(f'Altitude ({OBS_DEGREE})')
    ax.set_xlabel(f'{_time} (UTC)')
    plt.legend(loc='upper left')
    plt.fill_between(_target_time.datetime,
                     ASTRONOMICAL_DAWN * u.deg,
                     90.0 * u.deg,
                     _sun_alt < 0.0 * u.deg,
                     color='0.80',
                     zorder=0)
    plt.fill_between(_target_time.datetime,
                     ASTRONOMICAL_DAWN * u.deg,
                     90.0 * u.deg,
                     _sun_alt < CIVIL_DAWN * u.deg,
                     color='0.60',
                     zorder=0)
    plt.fill_between(_target_time.datetime,
                     ASTRONOMICAL_DAWN * u.deg,
                     90.0 * u.deg,
                     _sun_alt < NAUTICAL_DAWN * u.deg,
                     color='0.40',
                     zorder=0)
    plt.fill_between(_target_time.datetime,
                     ASTRONOMICAL_DAWN * u.deg,
                     90.0 * u.deg,
                     _sun_alt < ASTRONOMICAL_DAWN * u.deg,
                     color='0.20',
                     zorder=0)

    # save plot
    _buf = io.BytesIO()
    plt.savefig(_img)
    plt.savefig(_buf, format='png', dpi=100, bbox_inches='tight')
    plt.close()

    # return
    _img = os.path.abspath(os.path.expanduser(_img))
    if os.path.exists(_img):
        if _log:
            _log.debug(f"created {_img}")
        return _img
    else:
        if _log:
            _log.debug(f"created None")
        return
コード例 #3
0
import astropy
from astropy.coordinates import AltAz
from astropy.coordinates import get_sun
from astropy.time import Time
from astropy.coordinates import EarthLocation
from astropy import units as u
from astropy.coordinates import SkyCoord
import numpy as np

observing_time = Time('2017-09-27T18:45:00', format='isot',
                      scale='utc')  #use UTC time
observing_location = EarthLocation(lat='37d55.1m',
                                   lon='-122d9.4m',
                                   height=304 * u.m)  #leuschner location#
AA = AltAz(location=observing_location, obstime=observing_time)
sun = SkyCoord(get_sun(observing_time))
#Change to local Az and Alt#
LA_sun_at_obs = sun.transform_to(AA)
print LA_sun_at_obs
print '#######Postion for source in Observatory########'
print 'Azimuth:', LA_sun_at_obs.az, 'Altitude:', LA_sun_at_obs.alt
コード例 #4
0
ファイル: mars_from_ztf_pt2.py プロジェクト: ninoc/ZTF
from astropy.time import Time
from astropy import units as u
from astropy.coordinates import AltAz
import matplotlib.pyplot as plt

#Today at 7 pm (ast) = 11pm UTC
#Current strategy at Etelman is to observe from ~7-11 pm
now = Time.now()
print now
now_str = str(now)
today = now_str.split(' ')[0]
today_7 = today + ' 23:00:00'
observing_time = Time(today_7)

observing_location = EarthLocation(lat='18.3381',
                                   lon='-64.8941',
                                   height=500 * u.m)


def az_alt(time, ra, dec):
    observing_time = Time(time)
    aa = AltAz(location=observing_location, obstime=observing_time)
    coord = SkyCoord(ra * u.deg, dec * u.deg)
    aa = coord.transform_to(aa)
    az = "{0.az}".format(aa)
    az_deg = az.split(' ')[0]
    alt = "{0.alt}".format(aa)
    alt_deg = alt.split(' ')[0]
    return az_deg, alt_deg

コード例 #5
0
fitsin = easygui.fileopenbox(default=os.path.join(timedir, '*'))
if fitsin == '.': sys.exit("No file selected")
fitsinfile = os.path.basename(fitsin)
filebase = fitsinfile[:fitsinfile.find('.')]

#ensures image inputted correctly depending on size of data cube
[colr, colg, colb, fitscoords] = correct_for_imagetype(timedir, fitsin,
                                                       fitsinfile)

#%%**********************
#INTERMISSION
#************************

azibits = np.empty((comappobs.shape[0], 6), dtype=float)
paranal = EarthLocation(lat=-24.627493 * u.deg,
                        lon=-70.404384 * u.deg,
                        height=0 * u.m)
radecpos = SkyCoord(Longitude(comappobs[:, 5] * u.degree, unit=u.deg),
                    comappobs[:, 6] * u.degree)

firsttime = Time(
    datetime.datetime(int(comappobs[0, 0]), int(comappobs[0, 1]),
                      int(comappobs[0, 2]), int(comappobs[0, 3]),
                      int(comappobs[0, 4]), 0))
endtime = Time(
    datetime.datetime(int(comappobs[-1, 0]), int(comappobs[-1, 1]),
                      int(comappobs[-1, 2]), int(comappobs[-1, 3]),
                      int(comappobs[-1, 4]), 0))
dt = TimeDelta(60, format='sec')
times = Time(np.arange(firsttime.jd, (endtime.jd + dt.jd), dt.jd), format='jd')
コード例 #6
0
def keo_sp_calibration(fit_path,masterdark_fname,solve_pars_fname,save_fname=None,area_rad=3, med_size=15,lat_deg=55.9305361,lon_deg=48.7444861,hei_m=91.):
    if save_fname==None:
        save_fname=solve_pars_fname.split('/')[-1][0:-11]+'.spcal'

    hdulist = fits.open(masterdark_fname,ignore_missing_end=True)
    masterdark=hdulist[0].data
    hdulist.close()

    err, az0,alt0,a,b,c,d=get_solve_pars(solve_pars_fname)
    M_s1c = get_scale_and_orientation_info(c,d)

    spath="./.temp/"
    if not os.path.exists(spath):
        os.makedirs(spath)
    fit_filenames=[fit_path+'/'+fn for fn in next(os.walk(fit_path))[2]]

    R_median=np.zeros(len(fit_filenames))
    R_std=np.zeros(len(fit_filenames))
    
    fig=plt.figure(figsize=(12.8,7.2))
    fig.set_size_inches(12.8, 7.2)

#     ax=plt.axes(position=[0.035000000000000003+dx/2, 0.061764705882352888, 0.50624999999999998, 0.89999999999999991])
    ax=plt.axes(position=[0.035000000000000003+dx/2, 0.26, 0.50624999999999998, 0.7])
    plt.axis('off')
    ax1=plt.axes(position=[0.58205882352941185+dx, 0.71052941176470596-0.15, 0.35,0.4])
    plt.grid()
    ax2=plt.axes(position=[0.58205882352941185+dx, 0.061764705882352888, 0.35, 0.4])
    plt.grid()

    ax3=plt.axes(position=[0.035000000000000003+dx/2,0.04, 0.5/4, 0.7/4])
    plt.grid(b=True)
    ax4=plt.axes(position=[0.035000000000000003+dx/2+0.19,0.04, 0.5/4, 0.7/4])
    plt.grid(b=True)
    ax5=plt.axes(position=[0.035000000000000003+dx/2+0.38,0.04, 0.5/4, 0.7/4])
    plt.grid(b=True)

    R_day=0

#     vrange=1000
#     vshift=2000

    alt_min=44*np.pi/180
    alt_max=62*np.pi/180

#     area_rad=3
#     med_size=31

    XX,YY=np.meshgrid(range(2*area_rad+1),range(2*area_rad+1))

    fid=open(save_fname,'w')
    fid.write("# Camera calibration coefficients [Rayleighs per ADC unit] for each fit file:\n")

    for i in range(len(fit_filenames)):
#     for i in range(5):
#     for i in range(109,120):
        sys.stdout.write('\r')
        sys.stdout.write("Processing frame "+str(i+1)+"/"+str(len(fit_filenames)))
        sys.stdout.flush()
        fit_fname=fit_filenames[i]
        hdulist = fits.open(fit_fname,ignore_missing_end=True)
        img=hdulist[0].data.astype('float')
        img0=np.copy(img)
        img=img-masterdark.astype('float')
        img_medfilt=img - ss.medfilt(img,kernel_size=med_size)
#         np.save('img.npy',img)
        hdulist.close()

        med_img=np.median(img)
        max_img0=np.max(img0)
#         print(max_img0)

        keo_site=EarthLocation(lat=lat_deg*u.deg, lon=lon_deg*u.deg, height=hei_m*u.m)
        date_obs=keo_get_date_obs(fit_fname)

        png_prefix=spath+"frame_keo_"+str(date_obs.year)[2::]+"{0:0>2}".format(date_obs.month)+"{0:0>2}".format(date_obs.day)+"_"

        BS_coord=SkyCoord(RA, DEC, frame='icrs', unit='rad');
        altaz=BS_coord.transform_to(AltAz(obstime=date_obs, location=keo_site,temperature=20*u.deg_C,pressure=1013*u.hPa,
                                               relative_humidity=0.5,obswl=630.0*u.nm))
        AZ=altaz.az.rad
        ALT=altaz.alt.rad

        X,Y = arc_hor2pix(AZ,ALT,az0,alt0,c,d)

        # Catalog filtration
        filt_mask=np.zeros(len(NUM),dtype=bool)
        for j in range(len(NUM)):
            if ALT[j]>=alt_min and ALT[j]<=alt_max and X[j]>=10 and Y[j]>=10 and X[j]<=img.shape[1]-10 and Y[j]<=img.shape[0]-10:
                filt_mask[j]=True
        NUM_filt=NUM[filt_mask]
        BS_ID_filt=BS_ID[filt_mask]
        RA_filt=RA[filt_mask]
        DEC_filt=DEC[filt_mask]
        MAG_filt=MAG[filt_mask]
        FLUX_filt=FLUX[filt_mask]
        SP_type_filt=[SP_type[j] for j in range(len(SP_type)) if filt_mask[j]==True]
        ALT_filt=ALT[filt_mask]
        AZ_filt=AZ[filt_mask]
        X_filt=X[filt_mask]
        Y_filt=Y[filt_mask]

        star_pixels=np.zeros(len(NUM_filt),dtype=int)
        star_adc=np.zeros(len(NUM_filt))

        AREA=np.zeros((2*area_rad+1,2*area_rad+1,len(NUM_filt)))
        AREA0=np.zeros((2*area_rad+1,2*area_rad+1,len(NUM_filt)))

        for j in range(len(NUM_filt)):
            sum_temp=0
            num=0
            AREA[:,:,j]=np.copy(img_medfilt[int(Y_filt[j])-area_rad:int(Y_filt[j])+area_rad+1, int(X_filt[j])-area_rad:int(X_filt[j])+area_rad+1])
            AREA0[:,:,j]=np.copy(img0[int(Y_filt[j])-area_rad:int(Y_filt[j])+area_rad+1, int(X_filt[j])-area_rad:int(X_filt[j])+area_rad+1])

            arg_max=np.argmax(AREA[:,:,j])
#             print("max=", np.max(AREA[:,:,j]))
            x0=XX.flat[arg_max]
            y0=YY.flat[arg_max]

            AREA[:,:,j]=np.copy(img_medfilt[int(Y_filt[j])-area_rad+y0-area_rad:int(Y_filt[j])+y0+1, int(X_filt[j])-area_rad+x0-area_rad:int(X_filt[j])+x0+1])
            AREA0[:,:,j]=np.copy(img0[int(Y_filt[j])-area_rad+y0-area_rad:int(Y_filt[j])+y0+1, int(X_filt[j])-area_rad+x0-area_rad:int(X_filt[j])+x0+1])

            Rast=np.sqrt((XX-area_rad)**2+(YY-area_rad)**2)

#             print(Rast)

            area=np.copy(AREA[:,:,j])

            for k in range((2*area_rad+1)**2):
                if Rast.flat[k]<=area_rad:
                    num+=1
                    sum_temp+=AREA[:,:,j].flat[k]
            star_pixels[j]=num
            star_adc[j]=sum_temp
#             print(star_pixels[j],star_adc[j])
#             print(AREA[:,:,j])
#             print(" ")


        # Catalog filtration 2
        filt_mask=np.zeros(len(NUM_filt),dtype=bool)
        for j in range(len(NUM_filt)):
            if np.max(AREA0[:,:,j])<0.9*max_img0:
                if np.max(AREA[:,:,j])>1000:
                    filt_mask[j]=True

        AREA_filt2=np.copy(AREA[:,:,filt_mask])
        AREA0_filt2=np.copy(AREA0[:,:,filt_mask])

        NUM_filt2=NUM_filt[filt_mask]
        BS_ID_filt2=BS_ID_filt[filt_mask]
        RA_filt2=RA_filt[filt_mask]
        DEC_filt2=DEC_filt[filt_mask]
        MAG_filt2=MAG_filt[filt_mask]
        FLUX_filt2=FLUX_filt[filt_mask]
        SP_type_filt2=[SP_type_filt[j] for j in range(len(SP_type_filt)) if filt_mask[j]==True]
        X_filt2=X_filt[filt_mask]
        Y_filt2=Y_filt[filt_mask]
        ALT_filt2=ALT_filt[filt_mask]
        AZ_filt2=AZ_filt[filt_mask]
        star_pixels_filt2=star_pixels[filt_mask]
        star_adc_filt2=star_adc[filt_mask]

        R=np.zeros(len(NUM_filt2))
        for j in range(len(NUM_filt2)):
            sol_angle=tan_get_pixel_solid_angle(M_s1c,np.pi/2-ALT_filt2[j])
            br=get_brightness_in_Rayleighs(20,sol_angle,1,FLUX_filt2[j])
            sa=star_adc_filt2[j]
            R[j]=br/sa
#             print('br[R]=', br, "; sa[ADC.u]=",sa,"; R=",R[j])

        x_bord=np.arange(2*area_rad+1,dtype=float)
        y1_bord=np.sqrt(area_rad**2-(x_bord-area_rad)**2)+area_rad+0.5
        y2_bord=-np.sqrt(area_rad**2-(x_bord-area_rad)**2)+area_rad+0.5

        if len(NUM_filt2)>0:

            sort_ord=np.argsort(star_pixels_filt2)

            plt.sca(ax3)
            idd=0
            area1=AREA_filt2[:,:,sort_ord[idd]]
            area1_max=np.max(AREA0_filt2[:,:,sort_ord[idd]])
            area1_id=BS_ID_filt2[sort_ord[idd]]
            plt.pcolormesh(area1, cmap="seismic",vmin=-1000, vmax=1000)

            plt.plot(x_bord+0.5,y1_bord,'k-',lw=2)
            plt.plot(x_bord+0.5,y2_bord,'k-',lw=2)

            plt.ylim(area_rad*2+1,0)
            plt.xlim(0,area_rad*2+1)
            plt.title(str(area1_id),loc='left',fontsize='smaller')
            plt.title(str(int(star_adc_filt2[sort_ord[idd]])),loc='right',fontsize='smaller')
            plt.title(str(int(R[sort_ord[idd]]*1000)/1000),fontsize='smaller')
            plt.ylabel(str(int(R[sort_ord[idd]]*star_adc_filt2[sort_ord[idd]])))

            if len(NUM_filt2)>1:
                plt.sca(ax4)
                idd=1
                area2=AREA_filt2[:,:,sort_ord[idd]]
                area2_max=np.max(AREA0_filt2[:,:,sort_ord[idd]])
                area2_id=BS_ID_filt2[sort_ord[idd]]
                plt.pcolormesh(area2, cmap="seismic",vmin=-1000, vmax=1000)

                plt.plot(x_bord+0.5,y1_bord,'k-',lw=2)
                plt.plot(x_bord+0.5,y2_bord,'k-',lw=2)

                plt.ylim(area_rad*2+1,0)
                plt.xlim(0,area_rad*2+1)
                plt.title(str(area2_id),loc='left',fontsize='smaller')
                plt.title(str(int(star_adc_filt2[sort_ord[idd]])),loc='right',fontsize='smaller')
                plt.title(str(int(R[sort_ord[idd]]*1000)/1000),fontsize='smaller')
                plt.ylabel(str(int(R[sort_ord[idd]]*star_adc_filt2[sort_ord[idd]])))
            if len(NUM_filt2)>2:
                plt.sca(ax5)
                idd=2
                area3=AREA_filt2[:,:,sort_ord[idd]]
                area3_max=np.max(AREA0_filt2[:,:,sort_ord[idd]])
                area3_id=BS_ID_filt2[sort_ord[idd]]
                plt.pcolormesh(area3, cmap="seismic",vmin=-1000, vmax=1000)

                plt.plot(x_bord+0.5,y1_bord,'k-',lw=2)
                plt.plot(x_bord+0.5,y2_bord,'k-',lw=2)

                plt.ylim(area_rad*2+1,0)
                plt.xlim(0,area_rad*2+1)
                plt.title(str(area3_id),loc='left',fontsize='smaller')
                plt.title(str(int(star_adc_filt2[sort_ord[idd]])),loc='right',fontsize='smaller')
                plt.title(str(int(R[sort_ord[idd]]*1000)/1000),fontsize='smaller')
                plt.ylabel(str(int(R[sort_ord[idd]]*star_adc_filt2[sort_ord[idd]])))



        # print(len(R),R)
        if len(R)>0:
            R_median[i]=np.median(R)
            temp=(R-R_median[i])**2
            R_std[i]=np.sqrt(np.median(temp))
        #     print(R_median[i])

        plt.sca(ax1)
        plt.plot([0, 50000], [R_median[i], R_median[i]], c='r', lw=2)
        plt.scatter(R*star_adc_filt2,R,s=np.pi*(star_adc_filt2/12000*7)**2)
#         print(R[0]*star_adc_filt2[0])
#         print(R[0]*star_adc_filt2[0]*star_pixels_filt2[0])

        for j in range(len(X_filt2)):
            plt.text(R[j]*star_adc_filt2[j],R[j],str(BS_ID_filt2[j])+"_"+str(star_pixels_filt2[j]))
        plt.ylabel('Calibration coef. [R/ADCu]')
        plt.xlabel('Star summ brightness [R]')
        plt.title(date_obs, loc='left')
        plt.title(R_median[i], loc='right')
        ax1.set_xlim((0, 30000))
        ax1.set_ylim((0, 1))
        plt.grid(b=True)

        plt.sca(ax2)
        plt.xlim([0,len(fit_filenames)-1])
        plt.ylim([0,1])
        plt.plot(i,R_median[i],"r.")
        plt.grid(b=True)
        plt.ylabel('Calibration coef. [R/ADCu]')
        plt.xlabel('frame number')
        if i==len(fit_filenames)-1:
            R_day=np.median(R_median[np.where(R_median>0)])
            plt.plot([0, 5000], [R_day, R_day], c='b', lw=2)
            plt.title(R_day, loc='right')

        plt.sca(ax)
        plt.pcolormesh(img, cmap="gray", vmin=np.median(img)-300, vmax=np.median(img)+300)
        plt.axis('equal')
        plt.plot(X,Y,marker="o", lw=0.,mew=mew,mec="b", mfc='none',ms=ms)
        plt.plot(X_filt,Y_filt,marker="o", lw=0.,mew=mew,mec="g", mfc='none',ms=ms)
        plt.plot(X_filt2,Y_filt2,marker="o", lw=0.,mew=mew,mec="r", mfc='none',ms=ms)
        for j in range(len(X_filt2)):
            plt.text(X_filt2[j],Y_filt2[j],str(BS_ID_filt2[j])+"_" + "{0:4.2f}".format(R[j]), color='w')
        ax.set_xlim((0,img.shape[1]))
        ax.set_ylim((img.shape[0],0))
        plt.title(fit_fname.split('/')[-1] + " " + "{0:0>2}".format(date_obs.hour) + ":" + "{0:0>2}".format(date_obs.minute) + ":" + "{0:0>2}".format(date_obs.second))
    #     plt.show()
        plt.axis('off')
        png_fname=png_prefix+"{0:0>4}".format(i+1)+".png"
    #   print(png_fname)
        plt.savefig(png_fname)
        ax.clear()
        ax1.clear()
        ax3.clear()
        ax4.clear()
        ax5.clear()

        fid.write(fit_fname.split('/')[-1] + " " + str(R_median[i])+ " " + str(R_std[i]) + "\n")

    plt.close()
    sys.stdout.write('\n')
    sys.stdout.flush()
    fid.close()

    return png_prefix, len(fit_filenames), R_median
コード例 #7
0
    assert_allclose(gcrs_coo.distance, gcrs_roundtrip.distance)

    pgeo_coo2 = gcrs_coo.transform_to(PrecessedGeocentric(equinox='B1850'))
    assert np.abs(gcrs_coo.ra - pgeo_coo2.ra) > 1.5 * u.deg
    assert np.abs(gcrs_coo.dec - pgeo_coo2.dec) > 0.5 * u.deg
    assert_allclose(gcrs_coo.distance, pgeo_coo2.distance)

    gcrs2_roundtrip = pgeo_coo2.transform_to(GCRS)
    assert_allclose(gcrs_coo.ra, gcrs2_roundtrip.ra)
    assert_allclose(gcrs_coo.dec, gcrs2_roundtrip.dec)
    assert_allclose(gcrs_coo.distance, gcrs2_roundtrip.distance)


# shared by parametrized tests below.  Some use the whole AltAz, others use just obstime
totest_frames = [
    AltAz(location=EarthLocation(-90 * u.deg, 65 * u.deg),
          obstime=Time('J2000')
          ),  # J2000 is often a default so this might work when others don't
    AltAz(location=EarthLocation(120 * u.deg, -35 * u.deg),
          obstime=Time('J2000')),
    AltAz(location=EarthLocation(-90 * u.deg, 65 * u.deg),
          obstime=Time('2014-01-01 00:00:00')),
    AltAz(location=EarthLocation(-90 * u.deg, 65 * u.deg),
          obstime=Time('2014-08-01 08:00:00')),
    AltAz(location=EarthLocation(120 * u.deg, -35 * u.deg),
          obstime=Time('2014-01-01 00:00:00'))
]
MOONDIST = 385000 * u.km  # approximate moon semi-major orbit axis of moon
MOONDIST_CART = CartesianRepresentation(3**-0.5 * MOONDIST, 3**-0.5 * MOONDIST,
                                        3**-0.5 * MOONDIST)
EARTHECC = 0.017 + 0.005  # roughly earth orbital eccentricity, but with an added tolerance
コード例 #8
0
ファイル: samedec.py プロジェクト: luciencd/starhopper
##python practice file
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from astropy.visualization import astropy_mpl_style
plt.style.use(astropy_mpl_style)
import astropy.units as u
from astropy.time import Time
from astropy.coordinates import SkyCoord, EarthLocation, AltAz
import math

field_of_view = 6  #degrees

bear_mountain = EarthLocation(lat=42.6 * u.deg,
                              lon=-83.14 * u.deg,
                              height=0.0 * u.m)
utcoffset = -4 * u.hour  # Eastern Daylight Time
time = Time('2017-2-1 23:00:00') - utcoffset

midnight = Time('2017-2-2 00:00:00') - utcoffset
delta_midnight = np.linspace(-6, 10, 100) * u.hour
'''

plt.plot(delta_midnight, m33airmasss_July13night)
plt.xlim(-2, 10)
plt.ylim(1, 4)
plt.xlabel('Hours from EDT Midnight')
plt.ylabel('Airmass [Sec(z)]')
plt.show()
'''
コード例 #9
0
VU = np.zeros(shape=grid.data[2].shape, dtype='f4')

minlat = 9999
minlon = 9999
maxlat = -9999
maxlon = -9999

# realign model
#for i, lat in enumerate(np.arange(grid.latmin, grid.latmax+grid.dlat, grid.dlat)):
for i, lat in enumerate(
        np.arange(grid.latmax + grid.dlat, grid.latmin, -grid.dlat)):
    for j, lon in enumerate(
            np.arange(grid.lonmin, grid.lonmax + grid.dlat, grid.dlon)):

        # geodetic -> cartesian conversion
        P = EarthLocation(lat=lat, lon=lon, height=0, ellipsoid='GRS80')
        C = (P.x.value, P.y.value, P.z.value)

        # Data is aligned as North, East, Up
        (dN, dE, dU) = (grid.data[0][i, j], grid.data[1][i,
                                                         j], grid.data[2][i,
                                                                          j])

        # dNEU -> dXYZ conversion
        lat_rad = lat * math.pi / 180
        lon_rad = lon * math.pi / 180

        # convert from NEU-space to XYZ-space
        (dX, dY, dZ) = neu2xyz(dN, dE, dU, lat_rad, lon_rad)

        # re-align velocities in 2003 model
def calculate_lsst_field_visibility(fieldRA,
                                    fieldDec,
                                    start_date,
                                    end_date,
                                    min_alt=30.0,
                                    dt_days=1.0,
                                    diagnostics=False,
                                    verbose=False):
    """Method to calculate the visibility of a given RA and Dec from LSST 
        over the course of a year
        
        Adapted from an example in the Astropy docs.
        
        Inputs:
            :param float fieldRA: Field RA in decimal degrees
            :param float fieldDec: Field Dec in decimal degrees
        """

    field = SkyCoord(fieldRA, fieldDec, unit=(u.hourangle, u.deg))

    lsst = EarthLocation(lat=-30.239933333333333 * u.deg,
                         lon=-70.7429638888889 * u.deg,
                         height=2663.0 * u.m)

    total_time_visible = 0.0
    t_start = Time(start_date + ' 00:00:00')
    t_end = Time(end_date + ' 00:00:00')
    cadence = 0.0007  # In days

    n_days = int((t_end - t_start).value)

    dates = np.array([t_start + \
            TimeDelta(i,format='jd',scale=None) for i in range(0,n_days,1)])

    target_alts = []
    hrs_visible_per_night = []
    hrs_per_night = []
    jds = []
    n_nights_low_vis = 0
    n_nights_hi_vis = 0

    f = open('target_visibility_windows.txt', 'w')

    for d in dates:

        jds.append(d.jd)

        t = copy.copy(d)
        t.out_subfmt = 'date'
        tstr = t.value

        intervals = np.arange(0.0, 1.0, cadence)

        dt = TimeDelta(intervals, format='jd', scale=None)

        ts = d + dt

        frame = AltAz(obstime=ts, location=lsst)

        altaz = field.transform_to(frame)

        alts = np.array((altaz.alt * u.deg).value)

        idx = np.where(alts > min_alt)[0]

        sun_altaz = get_sun(ts).transform_to(frame)

        sun_alts = np.array((sun_altaz.alt * u.deg).value)

        jdx = np.where(sun_alts < 12.0)[0]

        hrs_per_night.append(cadence * len(sun_alts[jdx]) * 24.0)

        idx = list(set(idx).intersection(set(jdx)))

        target_alts.append(alts[jdx].max())

        if len(idx) > 0:

            ts_vis = ts[idx]

            midyear = Time(str(int(d.decimalyear)) + '-07-15T00:00:00.0',
                           format='isot',
                           scale='utc')
            lateyear = Time(str(int(d.decimalyear)) + '-11-10T00:00:00.0',
                            format='isot',
                            scale='utc')

            tvis = cadence * len(ts_vis)

            total_time_visible += tvis

            hrs_visible_tonight = tvis * 24.0

            if hrs_visible_tonight >= 0.5 and hrs_visible_tonight < 4.0:
                n_nights_low_vis += 1

            elif hrs_visible_tonight >= 4.0:
                n_nights_hi_vis += 1

            if d < midyear or d > lateyear:
                f.write(ts_vis.min().value + ' ' + ts_vis.max().value + ' ' +
                        str(hrs_visible_tonight) + '\n')
            else:
                midday = Time(d.datetime.date().strftime("%Y-%m-%d") +
                              'T12:00:00.0',
                              format='isot',
                              scale='utc')

                k = np.where(ts_vis < midday)
                print(k)
                if len(k) > 0:
                    tmax = ts_vis[k].max()

                    k = np.where(ts_vis > midday)
                    tmin = ts_vis[k].min()

                    f.write(tmin.value + ' ' + tmax.value + ' ' +
                            str(hrs_visible_tonight) + '\n')

            #target_alts.append(alts[idx].max())

            if verbose:
                print('Target visible from LSST for '+str(round(tvis*24.0,2))+\
                    'hrs on '+tstr)

            hrs_visible_per_night.append((tvis * 24.0))

        else:

            #target_alts.append(-1e5)

            hrs_visible_per_night.append(0.0)

            if verbose:
                print('Target not visible from LSST on ' + tstr)

    f.close()

    if diagnostics and len(dates) > 0:

        plot_visibility(jds, target_alts, sun_alts, hrs_visible_per_night,
                        min_alt)

    elif diagnostics and len(dates) == 0:

        raise IOError('WARNING: invalid date range input')

    print('N nights at low visibility = ' + str(n_nights_low_vis))
    print('N nights at hi visibility = ' + str(n_nights_hi_vis))

    return total_time_visible, hrs_visible_per_night
コード例 #11
0
from math import pi
from astropy import units as u
from astropy.time import Time
#import astropy.coordinates as coord
from astropy.coordinates import SkyCoord, EarthLocation, AltAz, Angle
#from astropy.utils import iers
#2016iers.IERS.iers_table = iers.IERS_A.open(iers.IERS_A_URL)
encoding = "utf-8"

GBT_ALT_SLEW = 17.6 * (u.deg / u.min)
GBT_AZ_SLEW = 35.2 * (u.deg / u.min)

#warnings.filterwarnings("ignore")

green_bank = EarthLocation(lat=38.433129 * u.deg,
                           lon=-79.83983858 * u.deg,
                           height=20 * u.m)

#raw_input -> Python 2.x
#starting_time = raw_input("Enter start time for observation (YYYY-M-DD HH:MM:SS) UTC: ")
starting_time = input(
    "Enter start time for observation (YYYY-M-DD HH:MM:SS) UTC: ")

time_start = Time(starting_time, location=green_bank)
print(time_start.sidereal_time('mean'))

#raw_input -> Python 2.x
#ending_time = raw_input("Enter end time for observation (YYYY-M-DD HH:MM:SS) UTC: ")
ending_time = input(
    "Enter end time for observation (YYYY-M-DD HH:MM:SS) UTC: ")
コード例 #12
0
ファイル: chart.py プロジェクト: astrolpy/astrolpy
    plt.text(60, -70, asp_txt, zorder=999, fontname='DejaVu Sans Mono')

    plt.tight_layout()
    plt.show()


if __name__ == '__main__':

    loc_name = None
    while loc_name is None:
        in_name = 'Manchester'  #input('Enter name of city on Earth: ').capitalize()
        try:
            raise Exception
            loc_coord = EarthLocation.of_address(in_name)
            loc_name = in_name
        except:
            print('Can not find location: "{}"'.format(in_name))
            print('Defaulting to Manchester...')
            loc_name = 'Manchester'
            loc_coord = EarthLocation(lat=53.4807593 * u.deg,
                                      lon=-2.2426305 * u.deg,
                                      height=0)

    print(loc_coord.lat, loc_coord.lon)
    obs = Observer(location=loc_coord)

    tt = Time('2018-04-28 04:00:00')
    print(tt)

    plot_horoscope(tt, loc_coord)
コード例 #13
0
def main(args=None):
    p = parser()
    opts = p.parse_args(args)

    # Late imports
    import operator
    import sys

    from astroplan import Observer
    from astroplan.plots import plot_airmass
    from astropy.coordinates import EarthLocation, SkyCoord
    from astropy.table import Table
    from astropy.time import Time
    from astropy import units as u
    from matplotlib import dates
    from matplotlib.cm import ScalarMappable
    from matplotlib.colors import Normalize
    from matplotlib.patches import Patch
    from matplotlib import pyplot as plt
    from tqdm import tqdm
    import pytz

    from ..io import fits
    from .. import moc
    from .. import plot  # noqa
    from ..extern.numpy.quantile import percentile

    if opts.site is None:
        if opts.site_longitude is None or opts.site_latitude is None:
            p.error('must specify either --site or both '
                    '--site-longitude and --site-latitude')
        location = EarthLocation(lon=opts.site_longitude * u.deg,
                                 lat=opts.site_latitude * u.deg,
                                 height=(opts.site_height or 0) * u.m)
        if opts.site_timezone is not None:
            location.info.meta = {'timezone': opts.site_timezone}
        observer = Observer(location)
    else:
        if not ((opts.site_longitude is None) and
                (opts.site_latitude is None) and (opts.site_height is None) and
                (opts.site_timezone is None)):
            p.error('argument --site not allowed with arguments '
                    '--site-longitude, --site-latitude, '
                    '--site-height, or --site-timezone')
        observer = Observer.at_site(opts.site)

    m = fits.read_sky_map(opts.input.name, moc=True)

    # Make an empty airmass chart.
    t0 = Time(opts.time) if opts.time is not None else Time.now()
    t0 = observer.midnight(t0)
    ax = plot_airmass([], observer, t0, altitude_yaxis=True)

    # Remove the fake source and determine times that were used for the plot.
    del ax.lines[:]
    times = Time(np.linspace(*ax.get_xlim()), format='plot_date')

    theta, phi = moc.uniq2ang(m['UNIQ'])
    coords = SkyCoord(phi, 0.5 * np.pi - theta, unit='rad')
    prob = moc.uniq2pixarea(m['UNIQ']) * m['PROBDENSITY']

    levels = np.arange(90, 0, -10)
    nlevels = len(levels)
    percentiles = np.concatenate((50 - 0.5 * levels, 50 + 0.5 * levels))

    airmass = np.column_stack([
        percentile(condition_secz(coords.transform_to(observer.altaz(t)).secz),
                   percentiles,
                   weights=prob) for t in tqdm(times)
    ])

    cmap = ScalarMappable(Normalize(0, 100), plt.get_cmap())
    for level, lo, hi in zip(levels, airmass[:nlevels], airmass[nlevels:]):
        ax.fill_between(
            times.plot_date,
            clip_verylarge(lo),  # Clip infinities to large but finite values
            clip_verylarge(hi),  # because fill_between cannot handle inf
            color=cmap.to_rgba(level),
            zorder=2)

    ax.legend([Patch(facecolor=cmap.to_rgba(level)) for level in levels],
              ['{}%'.format(level) for level in levels])
    # ax.set_title('{} from {}'.format(m.meta['objid'], observer.name))

    # Adapted from astroplan
    start = times[0]
    twilights = [
        (times[0].datetime, 0.0),
        (observer.sun_set_time(Time(start), which='next').datetime, 0.0),
        (observer.twilight_evening_civil(Time(start),
                                         which='next').datetime, 0.1),
        (observer.twilight_evening_nautical(Time(start),
                                            which='next').datetime, 0.2),
        (observer.twilight_evening_astronomical(Time(start),
                                                which='next').datetime, 0.3),
        (observer.twilight_morning_astronomical(Time(start),
                                                which='next').datetime, 0.4),
        (observer.twilight_morning_nautical(Time(start),
                                            which='next').datetime, 0.3),
        (observer.twilight_morning_civil(Time(start),
                                         which='next').datetime, 0.2),
        (observer.sun_rise_time(Time(start), which='next').datetime, 0.1),
        (times[-1].datetime, 0.0),
    ]

    twilights.sort(key=operator.itemgetter(0))
    for i, twi in enumerate(twilights[1:], 1):
        if twi[1] != 0:
            ax.axvspan(twilights[i - 1][0],
                       twilights[i][0],
                       ymin=0,
                       ymax=1,
                       color='grey',
                       alpha=twi[1],
                       linewidth=0)
        if twi[1] != 0.4:
            ax.axvspan(twilights[i - 1][0],
                       twilights[i][0],
                       ymin=0,
                       ymax=1,
                       color='white',
                       alpha=0.8 - 2 * twi[1],
                       zorder=3,
                       linewidth=0)

    # Add local time axis
    timezone = (observer.location.info.meta or {}).get('timezone')
    if timezone:
        tzinfo = pytz.timezone(timezone)
        ax2 = ax.twiny()
        ax2.set_xlim(ax.get_xlim())
        ax2.set_xticks(ax.get_xticks())
        ax2.xaxis.set_major_formatter(dates.DateFormatter('%H:%M', tz=tzinfo))
        plt.setp(ax2.get_xticklabels(), rotation=-30, ha='right')
        ax2.set_xlabel("Time from {} [{}]".format(
            min(times).to_datetime(tzinfo).date(), timezone))

    if opts.verbose:
        # Write airmass table to stdout.
        times.format = 'isot'
        table = Table(masked=True)
        table['time'] = times
        table['sun_alt'] = np.ma.masked_greater_equal(
            observer.sun_altaz(times).alt, 0)
        table['sun_alt'].format = lambda x: '{}'.format(int(np.round(x)))
        for p, data in sorted(zip(percentiles, airmass)):
            table[str(p)] = np.ma.masked_invalid(data)
            table[str(p)].format = lambda x: '{:.01f}'.format(np.around(x, 1))
        table.write(sys.stdout, format='ascii.fixed_width')

    # Show or save output.
    opts.output()
コード例 #14
0
"""
Created on Tue May 26 22:01:05 2020

['altaz', 'barycentrictrueecliptic', 'cirs', 'fk4', 
'fk4noeterms', 'fk5', 'galactic', 'galacticlsr', 
'galactocentric', 'gcrs', 'geocentrictrueecliptic', 
'hcrs', 'heliocentrictrueecliptic', 'icrs', 'itrs', 
'lsr', 'precessedgeocentric', 'supergalactic']

@author: PC
"""

from astropy import units as u
from astropy.coordinates import SkyCoord, EarthLocation, AltAz
from astropy.time import Time

# 天体座標値取得(ICRS座標系)
c = SkyCoord('22h50m0.19315s', '+24d36m05.6984s', frame='icrs')
loc = EarthLocation(lat=31.7581 * u.deg,
                    lon=-95.6386 * u.deg,
                    height=147 * u.m)

# 時刻設定
time = Time('1991-06-06 12:00:00')

# ICRS(赤道座標とほぼ同じ)->AltAz(地平座標)座標変換
cAltAz = c.transform_to(AltAz(obstime=time, location=loc))
print(cAltAz)
print("az : ", cAltAz.az)
print("alt : ", cAltAz.alt)
コード例 #15
0
def test_io_time_write_fits_local(tmpdir, table_types):
    """
    Test that table with a Time mixin with scale local can also be written
    by io.fits. Like ``test_io_time_write_fits_standard`` above, but avoiding
    ``cxcsec`` format, which requires an epoch and thus cannot be used for a
    local time scale.
    """
    t = table_types([[1, 2], ['string', 'column']])
    t['a_local'] = time.Time([[50001, 50002], [50003, 50004]],
                             format='mjd',
                             scale='local',
                             location=EarthLocation(-2446354,
                                                    4237210,
                                                    4077985,
                                                    unit='m'))
    t['b_local'] = time.Time(
        ['1999-01-01T00:00:00.123456789', '2010-01-01T00:00:00'],
        scale='local')
    t['c'] = [3., 4.]

    filename = str(tmpdir.join('table-tmp'))

    # Show that FITS format succeeds

    with pytest.warns(AstropyUserWarning,
                      match='Time Column "b_local" has no specified location'):
        t.write(filename, format='fits', overwrite=True)

    with pytest.warns(
            AstropyUserWarning,
            match='Time column reference position "TRPOSn" is not specified.'):
        tm = table_types.read(filename, format='fits', astropy_native=True)

    for ab in ('a', 'b'):
        name = ab + '_local'

        # Assert that the time columns are read as Time
        assert isinstance(tm[name], time.Time)

        # Assert that the scales round-trip
        assert tm[name].scale == t[name].scale

        # Assert that the format is jd
        assert tm[name].format == 'jd'

        # Assert that the location round-trips
        assert tm[name].location == t[name].location

        # Finally assert that the column data round-trips
        assert (tm[name] == t[name]).all()

    for name in ('col0', 'col1', 'c'):
        # Assert that the non-time columns are read as Column
        assert isinstance(tm[name], Column)

        # Assert that the non-time columns' data round-trips
        assert (tm[name] == t[name]).all()

    # Test for conversion of time data to its value, as defined by its format.
    for ab in ('a', 'b'):
        name = ab + '_local'
        t[name].info.serialize_method['fits'] = 'formatted_value'

    t.write(filename, format='fits', overwrite=True)
    tm = table_types.read(filename, format='fits')

    for ab in ('a', 'b'):
        name = ab + '_local'

        assert not isinstance(tm[name], time.Time)
        assert (tm[name] == t[name].value).all()
コード例 #16
0
ファイル: wcs_full_night.py プロジェクト: jmilou/all_sky_phot
from astropy.time import Time
from astropy.table import Table, vstack

import matplotlib.pylab as plt

# restore list of photometry tables, one per image
temp = np.load('full_night.npz')
phot_tables = temp['phot_tables'][()]
temp.close()

hdulist = fits.open('initial_wcs.fits')
w = wcs.WCS(hdulist[0].header)
hdulist.close()

lsst_location = EarthLocation(lat=-30.2444 * u.degree,
                              lon=-70.7494 * u.degree,
                              height=2650.0 * u.meter)


def coord_trans(ptable, w):
    """
    Take a photometry table and add ra and dec cols
    """
    time = Time(ptable['mjd'].max(), format='mjd')
    az, alt = w.all_pix2world(ptable['xcenter'], ptable['ycenter'], 0)
    coords = AltAz(az=az * u.degree,
                   alt=alt * u.degree,
                   location=lsst_location,
                   obstime=time)
    sky_coords = coords.transform_to(ICRS)
    ptable['alt_rough'] = coords.alt
コード例 #17
0
        (date, err) = date.communicate()
        date_text = date.decode("utf-8").rstrip()
        return date_text
    else:
        date = subprocess.Popen(["date"], stdout=subprocess.PIPE)
        (date, err) = date.communicate()
        date_text = date.decode("utf-8").rstrip()
        return date_text

        
   
# main program implemented as boiler plate logic
if __name__ == "__main__":

   # nch location
   nch = EarthLocation(lat="37.8732", lon="-122.2573", height=123.1*u.m)
   
   # argparse stuff
   parser = argparse.ArgumentParser(description='''Program used to capture data via digital sampling''')
   parser.add_argument('-vr', "--volts", action="store_true", help="shows volt range options")
   parser.add_argument('-vrs', "--vrangeset", type=int, help="[int] pick voltage range from options (run -vr to see options)")
   parser.add_argument('-loc', "--location", type=str, help="[string] enter location instead of lat, lon. Format: 'address, city, state', e.g., 'University Dr., Berkeley, CA'")
   parser.add_argument('-lt', "--lat", type=float, help="[float] takes in latitude")
   parser.add_argument('-lg', "--lon", type=float, help="[float] takes in longitude")
   parser.add_argument('-az', "--azimuth", type=float, help="[float] take in azimuth")
   parser.add_argument('-alt', "--altitude", type=float, help="[float] take in altitude")
   parser.add_argument('-c', "--capture", action="store_true", help="captures data")
   parser.add_argument('-dm', "--dualmode", action="store_true", help="toggles dual mode")
   parser.add_argument('-d', "--directory", type=str, help="[string] write data to new directory")
   parser.add_argument('-ns', "--numsamples", type=int, help="[int] sets the number of samples to take")
   parser.add_argument('-nb', "--numblocks", type=int, help="[int] sets the number of blocks to take")
コード例 #18
0
ファイル: psfpreparation.py プロジェクト: dlbrittain/PynPoint
    def run(self):
        """
        Run method of the module. Calculates the parallactic angles from the position of the object
        on the sky and the telescope location on earth. The start of the observation is used to
        extrapolate for the observation time of each individual image of a data cube. The values
        are written as PARANG attributes to *data_tag*.

        Returns
        -------
        NoneType
            None
        """

        # Load cube sizes
        steps = self.m_data_in_port.get_attribute('NFRAMES')
        ndit = self.m_data_in_port.get_attribute('NDIT')

        self._attribute_check(ndit, steps)

        # Load exposure time [hours]
        exptime = self.m_data_in_port.get_attribute('DIT')/3600.

        # Load telescope location
        tel_lat = self.m_data_in_port.get_attribute('LATITUDE')
        tel_lon = self.m_data_in_port.get_attribute('LONGITUDE')

        # Load temporary target position
        tmp_ra = self.m_data_in_port.get_attribute('RA')
        tmp_dec = self.m_data_in_port.get_attribute('DEC')

        # Parse to degree depending on instrument
        if 'SPHERE' in self.m_instrument:

            # get sign of declination
            tmp_dec_sign = np.sign(tmp_dec)
            tmp_dec = np.abs(tmp_dec)

            # parse RA
            tmp_ra_s = tmp_ra % 100
            tmp_ra_m = ((tmp_ra - tmp_ra_s) / 1e2) % 100
            tmp_ra_h = ((tmp_ra - tmp_ra_s - tmp_ra_m * 1e2) / 1e4)

            # parse DEC
            tmp_dec_s = tmp_dec % 100
            tmp_dec_m = ((tmp_dec - tmp_dec_s) / 1e2) % 100
            tmp_dec_d = ((tmp_dec - tmp_dec_s - tmp_dec_m * 1e2) / 1e4)

            # get RA and DEC in degree
            ra = (tmp_ra_h + tmp_ra_m / 60. + tmp_ra_s / 3600.) * 15.
            dec = tmp_dec_sign * (tmp_dec_d + tmp_dec_m / 60. + tmp_dec_s / 3600.)

        else:
            ra = tmp_ra
            dec = tmp_dec

        # Load start times of exposures
        obs_dates = self.m_data_in_port.get_attribute('DATE')

        # Load pupil positions during observations
        if self.m_instrument == 'NACO':
            pupil_pos = self.m_data_in_port.get_attribute('PUPIL')

        elif self.m_instrument == 'SPHERE/IRDIS':
            pupil_pos = np.zeros(steps.shape)

        elif self.m_instrument == 'SPHERE/IFS':
            pupil_pos = np.zeros(steps.shape)

        new_angles = np.array([])
        pupil_pos_arr = np.array([])

        # Calculate parallactic angles for each cube
        for i, tmp_steps in enumerate(steps):
            t = Time(obs_dates[i].decode('utf-8'),
                     location=EarthLocation(lat=tel_lat, lon=tel_lon))

            sid_time = t.sidereal_time('apparent').value

            # Extrapolate sideral times from start time of the cube for each frame of it
            sid_time_arr = np.linspace(sid_time+self.m_O_START,
                                       (sid_time+self.m_O_START) + (exptime+self.m_DIT_DELAY+ \
                                                 self.m_ROT)*(tmp_steps-1),
                                       tmp_steps)

            # Convert to degrees
            sid_time_arr_deg = sid_time_arr * 15.

            # Calculate hour angle in degrees
            hour_angle = sid_time_arr_deg - ra[i]

            # Conversion to radians:
            hour_angle_rad = np.deg2rad(hour_angle)
            dec_rad = np.deg2rad(dec[i])
            lat_rad = np.deg2rad(tel_lat)

            p_angle = np.arctan2(np.sin(hour_angle_rad),
                                 (np.cos(dec_rad)*np.tan(lat_rad) - \
                                  np.sin(dec_rad)*np.cos(hour_angle_rad)))

            new_angles = np.append(new_angles, np.rad2deg(p_angle))
            pupil_pos_arr = np.append(pupil_pos_arr, np.ones(tmp_steps)*pupil_pos[i])

        # Correct for rotator (SPHERE) or pupil offset (NACO)
        if self.m_instrument == 'NACO':
            # See NACO manual page 65 (v102)
            new_angles_corr = new_angles - (90. + (self.m_rot_offset-pupil_pos_arr))

        elif self.m_instrument == 'SPHERE/IRDIS':
            # See SPHERE manual page 64 (v102)
            new_angles_corr = new_angles - self.m_pupil_offset

        elif self.m_instrument == 'SPHERE/IFS':
            # See SPHERE manual page 64 (v102)
            new_angles_corr = new_angles - self.m_pupil_offset

        indices = np.where(new_angles_corr < -180.)[0]
        if indices.size > 0:
            new_angles_corr[indices] += 360.

        indices = np.where(new_angles_corr > 180.)[0]
        if indices.size > 0:
            new_angles_corr[indices] -= 360.

        self.m_data_out_port.add_attribute('PARANG', new_angles_corr, static=False)

        sys.stdout.write('Running AngleCalculationModule... [DONE]\n')
        sys.stdout.flush()
コード例 #19
0
def create_standard_mid_simulation_rsexecute_workflow(band, rmax, phasecentre,
                                                      time_range, time_chunk,
                                                      integration_time,
                                                      shared_directory):
    """ Create the standard MID simulation
    
    :param band:
    :param rmax:
    :param ra:
    :param declination:
    :param time_range:
    :param time_chunk:
    :param integration_time:
    :param shared_directory:
    :return:
    """

    # Set up details of simulated observation
    if band == 'B1':
        frequency = [0.765e9]
    elif band == 'B2':
        frequency = [1.36e9]
    elif band == 'Ku':
        frequency = [12.179e9]
    else:
        raise ValueError("Unknown band %s" % band)

    channel_bandwidth = [1e7]
    mid_location = EarthLocation(lon="21.443803", lat="-30.712925", height=0.0)

    # Do each time_chunk in parallel
    start_times = numpy.arange(time_range[0] * 3600, time_range[1] * 3600,
                               time_chunk)
    end_times = start_times + time_chunk

    start_times = find_times_above_elevation_limit(start_times,
                                                   end_times,
                                                   location=mid_location,
                                                   phasecentre=phasecentre,
                                                   elevation_limit=15.0)
    times = [
        numpy.arange(start_times[itime], end_times[itime], integration_time)
        for itime in range(len(start_times))
    ]

    s2r = numpy.pi / (12.0 * 3600)
    rtimes = s2r * numpy.array(times)
    ntimes = len(rtimes.flat)
    nchunks = len(start_times)

    assert ntimes > 0, "No data above elevation limit"

    #print('%d integrations of duration %.1f s processed in %d chunks' % (ntimes, integration_time, nchunks))

    mid = create_configuration_from_MIDfile('%s/ska1mid_local.cfg' %
                                            shared_directory,
                                            rmax=rmax,
                                            location=mid_location)

    bvis_graph = [
        rsexecute.execute(create_blockvisibility)(
            mid,
            rtimes[itime],
            frequency=frequency,
            channel_bandwidth=channel_bandwidth,
            weight=1.0,
            phasecentre=phasecentre,
            polarisation_frame=PolarisationFrame("stokesI"),
            zerow=True) for itime in range(nchunks)
    ]

    return bvis_graph
コード例 #20
0
            data.antenna_positions = info['antenna_positions']
            data.antenna_numbers = np.array(
                info['antenna_numbers']).astype(int)
            data.antenna_names = np.asarray(
                [str(a) for a in info['antenna_names']])
            data.Nants_telescope = len(data.antenna_numbers)
            data.Nants_data = 3

            # Write times
            jds = Time(times, format='unix')
            data.time_array = jds.jd
            data.set_lsts_from_time_array()

            # Set ra,dec of zenith during observation
            observatory = EarthLocation(lat=info['cofa_lat'] * u.degree,
                                        lon=info['cofa_lon'] * u.degree,
                                        height=info['cofa_alt'] * u.m)
            data.zenith_ra = np.zeros_like(data.time_array)
            data.zenith_dec = np.zeros_like(data.time_array)

            for tnum, t in enumerate(data.time_array):
                observation_time = Time(t, format='jd')
                zenith_altaz = SkyCoord(location=observatory,
                                        obstime=observation_time,
                                        alt=90. * u.degree,
                                        az=0. * u.degree,
                                        frame='altaz').icrs
                data.zenith_ra[tnum] = zenith_altaz.ra.degree
                data.zenith_dec[tnum] = zenith_altaz.dec.degree

            # Other header
コード例 #21
0
def polarCalc(mylat, mylong, myelev, observing_time, p1, p2, p3):
    #iers.conf.auto_download = False
    #iers.conf.auto_max_age = None

    #Create time object based on given time
    observing_time = Time(observing_time)

    #Create location object based on lat/long/elev
    observing_location = EarthLocation(lat=mylat * u.deg,
                                       lon=mylong * u.deg,
                                       height=myelev * u.m)

    #Create coordinate objects for each point
    #p1 = SkyCoord(p1RA, p1DEC, unit='deg')
    #p2 = SkyCoord(p2RA, p2DEC, unit='deg')
    #p3 = SkyCoord(p3RA, p3DEC, unit='deg')
    p1X = (90 - p1.dec.degree) * math.cos(p1.ra.radian)
    p1Y = (90 - p1.dec.degree) * math.sin(p1.ra.radian)
    p2X = (90 - p2.dec.degree) * math.cos(p2.ra.radian)
    p2Y = (90 - p2.dec.degree) * math.sin(p2.ra.radian)
    p3X = (90 - p3.dec.degree) * math.cos(p3.ra.radian)
    p3Y = (90 - p3.dec.degree) * math.sin(p3.ra.radian)

    #Calculate center of circle using three points in the complex plane. RA/DEC are treated as unitless for the purposes of the calculation.
    x, y, z = complex(p1X, p1Y), complex(p2X, p2Y), complex(p3X, p3Y)
    w = z - x
    w /= y - x
    c = (x - y) * (w - abs(w)**2) / 2j / w.imag - x
    resultX = -c.real
    resultY = -c.imag

    #Convert X/Y values of circle into RA/DEC
    resultDEC = (90 - math.sqrt(resultX**2 + resultY**2))
    resultRA = math.atan2(resultY, resultX) * 360 / (2 * math.pi)
    if resultRA < 0:
        resultRA = (180 - abs(resultRA)) + 180

    print(
        f"Current alignment in RA/DEC: {Angle(resultRA*u.deg).to_string(u.hour, precision=2)}/{Angle(resultDEC*u.deg).to_string(u.degree, precision=2)}."
    )

    #Create alt/az coordinate object for pole
    poleAzAlt = RADECtoAltAz(observing_location, observing_time, 0, 90)
    print(
        f"True polar alignment in Az./Alt.: 00h00m00s/{poleAzAlt.alt.to_string(u.degree, precision=2)}."
    )

    #Create alt/az coordinate object for current alignment
    offsetAzAlt = RADECtoAltAz(observing_location, observing_time, resultRA,
                               resultDEC)
    print(
        f"Current alignment in Az./Alt.: {offsetAzAlt.az.to_string(u.hour, precision=2)}/{offsetAzAlt.alt.to_string(u.degree, precision=2)}."
    )

    #Calculate offset deltas from pole
    #Normalize the azimuth values to between -180 and 180 degrees prior to determining offset.
    errorAz = (((poleAzAlt.az.deg + 180) % 360 - 180) -
               ((offsetAzAlt.az.deg + 180) % 360 - 180)) * 60
    errorAlt = (poleAzAlt.alt.deg - offsetAzAlt.alt.deg) * 60

    return errorAz, errorAlt
コード例 #22
0
        # Mixin info.meta can None instead of empty OrderedDict(), #6720 would
        # fix this.
        if attr == 'info.meta':
            if a1 is None:
                a1 = {}
            if a2 is None:
                a2 = {}

        assert np.all(a1 == a2)


# Testing HDF5 table read/write with mixins.  This is mostly
# copied from FITS mixin testing.

el = EarthLocation(x=1 * u.km, y=3 * u.km, z=5 * u.km)
el2 = EarthLocation(x=[1, 2] * u.km, y=[3, 4] * u.km, z=[5, 6] * u.km)
sc = SkyCoord([1, 2], [3, 4], unit='deg,deg', frame='fk4', obstime='J1990.5')
scc = sc.copy()
scc.representation_type = 'cartesian'
tm = Time([2450814.5, 2450815.5], format='jd', scale='tai', location=el)

mixin_cols = {
    'tm':
    tm,
    'dt':
    TimeDelta([1, 2] * u.day),
    'sc':
    sc,
    'scc':
    scc,
コード例 #23
0
def generate_ddf(ddf_name, nyears=10):
    previous_ddf = generate_dd_surveys()
    survey_names = np.array([survey.survey_name for survey in previous_ddf])
    survey_indx = np.where(survey_names == ddf_name)[0].max()
    ddf_ra = previous_ddf[survey_indx].ra * u.rad
    ddf_dec = previous_ddf[survey_indx].dec * u.rad

    site = Site('LSST')
    location = EarthLocation(lat=site.latitude,
                             lon=site.longitude,
                             height=site.height)

    mjd = np.arange(59853.5, 59853.5 + 365.25 * nyears, 20. / 60 / 24.)
    times = Time(mjd, format='mjd', location=location)

    airmass_limit = 2.5  # demand airmass lower than this
    twilight_limit = -18.  # Sun below this altitude in degrees
    dist_to_moon_limit = 30.  # minimum distance to keep from moon degrees
    zenith_limit = 10.  # Need to be this far away from zenith to start (20 min = 5 deg)
    g_m5_limit = 23.5  # mags

    season_gap = 20.  # days. Count any gap longer than this as it's own season
    season_length_limit = 80  # Days. Demand at least this many days in a season

    # How long to keep attempting a DDF
    expire_dict = {1: 36. / 24., 2: 0.5}

    sun_coords = get_sun(times)
    moon_coords = get_moon(times)

    sched_downtime_data = ScheduledDowntimeData(Time(mjd[0], format='mjd'))
    observatory_up = np.ones(mjd.size, dtype=bool)
    for dt in sched_downtime_data():
        indx = np.where((mjd >= dt['start'].mjd) & (mjd <= dt['end'].mjd))[0]
        observatory_up[indx] = False

    lst = times.sidereal_time('mean')

    sun_altaz = sun_coords.transform_to(AltAz(location=location))

    # generate a night label for each timestep
    sun_rise = np.where((sun_altaz.alt[0:-1] < 0) & (sun_altaz.alt[1:] > 0))[0]
    night = np.zeros(mjd.size, dtype=int)
    night[sun_rise] = 1
    night = np.cumsum(night) + 1  # 1-index for night

    sun_down = np.where(sun_altaz.alt < twilight_limit * u.deg)[0]

    ddf_coord = SkyCoord(ra=ddf_ra, dec=ddf_dec)
    ddf_altaz = ddf_coord.transform_to(AltAz(location=location, obstime=times))
    ddf_airmass = 1. / np.cos(np.radians(90. - ddf_altaz.az.deg))
    zenith = AltAz(alt=90. * u.deg, az=0. * u.deg)
    ddf_zenth_dist = zenith.separation(ddf_altaz)

    nside = 32
    ddf_indx = raDec2Hpid(nside, ddf_coord.ra.deg, ddf_coord.dec.deg)
    sm = SkyModelPre()

    g_sb = mjd * 0 + np.nan

    indices = np.where((sun_altaz.alt < twilight_limit * u.deg)
                       & (ddf_airmass > airmass_limit))[0]
    # In theory, one could reach into the sky brightness model and do a much faster interpolation
    # There might be an airmass limit on the sky brightness.
    for indx in sun_down:
        g_sb[indx] = sm.returnMags(mjd[indx],
                                   indx=[ddf_indx],
                                   filters='g',
                                   badval=np.nan)['g']

    dist_to_moon = ddf_coord.separation(moon_coords)
    seeing_model = SeeingModel()
    ddf_approx_fwhmEff = seeing_model(0.7, ddf_airmass)
    # I think this should pluck out the g-filter. Really should be labled
    ddf_approx_fwhmEff = ddf_approx_fwhmEff['fwhmEff'][1].ravel()

    ddf_m5 = m5_flat_sed('g',
                         g_sb,
                         ddf_approx_fwhmEff,
                         30.,
                         ddf_airmass,
                         nexp=1.)

    # demand sun down past twilight, ddf is up, and observatory is open, and not too close to the moon
    good = np.where((ddf_airmass < airmass_limit)
                    & (sun_altaz.alt < twilight_limit * u.deg)
                    & (ddf_airmass > 0) & (observatory_up == True)
                    & (dist_to_moon > dist_to_moon_limit * u.deg)
                    & (ddf_zenth_dist > zenith_limit * u.deg)
                    & (ddf_m5 > g_m5_limit))

    potential_nights = np.unique(night[good])
    night_gap = potential_nights[1:] - potential_nights[0:-1]
    big_gap = np.where(night_gap > season_gap)[0] + 1
    season = potential_nights * 0
    season[big_gap] = 1
    season = np.cumsum(season)

    u_seasons = np.unique(season)
    season_lengths = []
    for se in u_seasons:
        in_se = np.where(season == se)
        season_lengths.append(
            np.max(potential_nights[in_se]) - np.min(potential_nights[in_se]))
    season_lengths = np.array(season_lengths)

    good_seasons = u_seasons[np.where(season_lengths > season_length_limit)[0]]
    gn = np.isin(season, good_seasons)
    potential_nights = potential_nights[gn]
    season = season[gn]

    obs_attempts = []
    for sea in np.unique(season):
        night_indx = np.where(season == sea)
        obs_attempts.append(place_obs(potential_nights[night_indx]))
    obs_attempts = np.concatenate(obs_attempts)

    mjd_observe = []
    m5_approx = []
    for indx in np.where(obs_attempts > 0)[0]:
        in_night_indx = np.where(night == potential_nights[indx])[0]
        best_depth_indx = np.min(
            np.where(
                ddf_m5[in_night_indx] == np.nanmax(ddf_m5[in_night_indx]))[0])
        mjd_start = mjd[in_night_indx[best_depth_indx]]
        m5_approx.append(ddf_m5[in_night_indx[best_depth_indx]])
        mjd_end = mjd_start + expire_dict[obs_attempts[indx]]
        mjd_observe.append((mjd_start, mjd_end))

    return mjd_observe, ddf_ra, ddf_dec, previous_ddf[
        survey_indx].observations, m5_approx
コード例 #24
0
        plt.tight_layout()
        plt.savefig("%s.azel.png" % (prefix))
        plt.clf()
        plt.close()


#        plt.show()

    return (out_fname)

if __name__ == "__main__":
    # SD video
    fname = img_mean(fname="tests/2022_01_10_00_04_00_000_011331.mp4",
                     t0=Time("2022-01-10T00:04:00", format="isot"),
                     obs=EarthLocation(lon=19.22454409315662,
                                       height=77.3,
                                       lat=69.5861167101982),
                     plot=True)

    fname = img_mean(fname="tests/2022_01_09_22_08_02_000_011331.mp4",
                     t0=Time("2022-01-09T22:08:02", format="isot"),
                     obs=EarthLocation(lon=19.22454409315662,
                                       height=77.3,
                                       lat=69.5861167101982),
                     plot=True)

#    img_mean(fname="tests/2022_01_10_02_15_00_000_011335.mp4")
#   img_mean(fname="tests/2022_01_10_02_34_00_000_011331.mp4")
#    img_mean(fname="tests/2022_01_10_01_08_00_000_011332.mp4")
#   img_mean(fname="tests/2022_01_10_01_08_00_000_011333.mp4")
#  img_mean(fname="tests/2022_01_10_15_00_01_000_011334.mp4")
コード例 #25
0
# ## Time
#
# Is the Crab visible now?

# In[ ]:

now = Time.now()
print(now)
print(now.mjd)

# In[ ]:

# define the location for the AltAz system
from astropy.coordinates import EarthLocation, AltAz

paris = EarthLocation(lat=48.8567 * u.deg, lon=2.3508 * u.deg)

# calculate the horizontal coordinates
crab_altaz = c2.transform_to(AltAz(obstime=now, location=paris))

print(crab_altaz)

# ## Table: Manipulating the 3FGL catalog
#
# Here we are going to do some selections with the 3FGL catalog. To do so we use the Table class from astropy.
#
# ### Accessing the table
# First, we need to open the catalog in a Table.

# In[ ]:
コード例 #26
0
def img_mean(fname="full_59.mp4",
             t0=Time(0, format="unix"),
             obs=EarthLocation(lon=19.22454409315662,
                               height=77.3,
                               lat=69.5861167101982),
             scale=1.0,
             solve=False,
             n_blocks_x=3,
             n_blocks_y=3,
             clip_x=10,
             clip_y=100,
             refit=True,
             blur_width=5,
             plot=False):

    prefix = re.search("(.*).(...)", fname).group(1)
    if os.path.exists("%s.azel.h5" % (prefix)) and not refit:
        print("already fitted")
        return

    cap = cv2.VideoCapture(fname)
    ret, frame0 = cap.read()
    avg = n.array(cv2.cvtColor(frame0, cv2.COLOR_BGR2GRAY), dtype=n.float32)
    h = avg.shape[0]
    w = avg.shape[1]

    need_to_resize = False
    new_dim = (1920, 1080)
    if w != 1920:
        print("resizing SD to HD size")
        need_to_resize = True

        avg = cv2.resize(avg, new_dim)
        h = 1080
        w = 1920

    n_avg = 1.0
    idx = 0
    while (1):
        ret, frame0 = cap.read()
        if not ret:
            break

        frame = n.array(cv2.cvtColor(frame0, cv2.COLOR_BGR2GRAY),
                        dtype=n.float32)
        frame = cv2.resize(frame, new_dim)
        #        frame = cv2.blur(frame,(blur_width,blur_width))
        #        print(n_avg)
        #        avg=n.maximum(frame,avg)
        avg += frame
        n_avg += 1.0
    cap.release()
    avg = avg / n_avg
    avg = avg - n.min(avg)
    avg = 255.0 * avg / n.max(avg)

    avg[avg > 255.0] = 255.0
    avg[avg < 0] = 0

    #   apply pre-distortion to make it easier to find stars
    #   avg=lm.img_spherical_to_gnomic(n.array(avg,dtype=n.uint8), out_fname="%s.orig.png"%(fname),f_g=1.1, f_s=1.6,plot=False)

    imageio.imwrite("%s.orig.png" % (fname), n.array(avg, dtype=n.uint8))

    dx = int(n.floor((avg.shape[0] - 2 * clip_x) / n_blocks_x))
    xstep = int(dx / 2)
    dy = int(n.floor((avg.shape[1] - 2 * clip_y) / n_blocks_y))
    ystep = int(dy / 2)

    all_xs = n.array([])
    all_ys = n.array([])
    all_azs = n.array([])
    all_els = n.array([])
    all_wgts = n.array([])
    all_flxs = n.array([])

    for i in range(2 * n_blocks_x):
        for j in range(2 * n_blocks_y):
            fromx = (i * xstep) + clip_x
            fromy = (j * ystep) + clip_y
            print(fromx)
            print(fromy)
            tox = n.min([avg.shape[0], fromx + dx])
            toy = n.min([avg.shape[1], fromy + dy])
            print("from x", fromx, " fromy ", fromy, " tox ", tox, " toy ",
                  toy)
            BI = n.copy(avg[fromx:tox, fromy:toy])

            BI = BI - n.min(BI)
            BI = 255.0 * BI / n.max(BI)
            BI[BI > 255.0] = 255.0
            BI[BI < 0] = 0

            block_fname = "%s.%d.%d.png" % (fname, i, j)
            print(block_fname)
            imageio.imwrite(block_fname, n.array(BI, dtype=n.uint8))
            det_file = ah.solve_field(block_fname)

            if det_file != None:
                xs, ys, azs, els, wgts, flxs = ah.detection_azel(block_fname,
                                                                 det_file,
                                                                 t0,
                                                                 obs,
                                                                 plot=False)
                # x,y were flipped!
                all_xs = n.concatenate((all_xs, xs + fromy))
                all_ys = n.concatenate((all_ys, ys + fromx))
                all_azs = n.concatenate((all_azs, azs))
                all_els = n.concatenate((all_els, els))
                all_wgts = n.concatenate((all_wgts, wgts))
                all_flxs = n.concatenate((all_flxs, flxs))

    out_fname = "%s.azel.h5" % (prefix)
    ho = h5py.File("%s.azel.h5" % (prefix), "w")
    ho["weigth"] = all_wgts
    ho["width_pix"] = w
    ho["height_pix"] = h
    ho["flux"] = all_flxs
    ho["x_pix"] = all_xs
    ho["y_pix"] = all_ys
    ho["az_deg"] = all_azs
    ho["el_deg"] = all_els
    ho["t0_unix"] = t0.unix
    ho["lat_deg"] = float(obs.lat / u.deg)
    ho["lon_deg"] = float(obs.lon / u.deg)
    ho["height_m"] = float(obs.height / u.m)
    ho.close()
    if plot:
        plt.scatter(all_xs,
                    all_ys,
                    s=100,
                    facecolors='none',
                    edgecolors='white')
        plt.title(fname)
        plt.imshow(avg, vmax=64)
        plt.tight_layout()
        plt.savefig("%s.solved.png" % (prefix))
        plt.clf()
        plt.close()
        #
        #       plt.show()

        plt.subplot(121)
        plt.scatter(all_xs, all_ys, c=all_els, s=20, vmin=0, vmax=90)
        plt.xlim([0, 1920])
        plt.ylim([0, 1080])
        plt.colorbar()
        plt.subplot(122)
        plt.scatter(all_xs, all_ys, c=all_azs, s=20, vmin=0, vmax=360)
        plt.xlim([0, 1920])
        plt.ylim([0, 1080])
        plt.colorbar()
        plt.tight_layout()
        plt.savefig("%s.azel.png" % (prefix))
        plt.clf()
        plt.close()


#        plt.show()

    return (out_fname)
コード例 #27
0
##
###


import numpy as np
import bmxdata
from .datamanager import datamanager
import os
import pickle as cP
import astropy.units as u
from astropy.coordinates import EarthLocation, AltAz, SkyCoord
from astropy.time import Time
from copy import deepcopy as dc
import time

telescope_loc = EarthLocation(
    lat=40.87792*u.deg, lon=-72.85852*u.deg, height=0*u.m)

# Initialize empty data manager so we can use its functions
dm = datamanager()


class reduce(object):

    def __init__(self, tag):
        """ Init with a tag string E.g.
        r = reduce('170928_1000')
        """

        # Store tag string and get filename
        self.tag = tag
        self.rawfname = dm.getrawfname(tag)
コード例 #28
0
def test_io_time_write_fits_standard(tmpdir, table_types):
    """
    Test that table with Time mixin columns can be written by io.fits.
    Validation of the output is done. Test that io.fits writes a table
    containing Time mixin columns that can be partially round-tripped
    (metadata scale, location).

    Note that we postpone checking the "local" scale, since that cannot
    be done with format 'cxcsec', as it requires an epoch.
    """
    t = table_types([[1, 2], ['string', 'column']])
    for scale in time.STANDARD_TIME_SCALES:
        t['a' + scale] = time.Time([[1, 2], [3, 4]],
                                   format='cxcsec',
                                   scale=scale,
                                   location=EarthLocation(-2446354,
                                                          4237210,
                                                          4077985,
                                                          unit='m'))
        t['b' + scale] = time.Time(
            ['1999-01-01T00:00:00.123456789', '2010-01-01T00:00:00'],
            scale=scale)
    t['c'] = [3., 4.]

    filename = str(tmpdir.join('table-tmp'))

    # Show that FITS format succeeds
    with pytest.warns(AstropyUserWarning,
                      match='Time Column "btai" has no specified location, '
                      'but global Time Position is present'):
        t.write(filename, format='fits', overwrite=True)
    with pytest.warns(
            AstropyUserWarning,
            match='Time column reference position "TRPOSn" is not specified'):
        tm = table_types.read(filename, format='fits', astropy_native=True)

    for scale in time.STANDARD_TIME_SCALES:
        for ab in ('a', 'b'):
            name = ab + scale

            # Assert that the time columns are read as Time
            assert isinstance(tm[name], time.Time)

            # Assert that the scales round-trip
            assert tm[name].scale == t[name].scale

            # Assert that the format is jd
            assert tm[name].format == 'jd'

            # Assert that the location round-trips
            assert tm[name].location == t[name].location

            # Finally assert that the column data round-trips
            assert (tm[name] == t[name]).all()

    for name in ('col0', 'col1', 'c'):
        # Assert that the non-time columns are read as Column
        assert isinstance(tm[name], Column)

        # Assert that the non-time columns' data round-trips
        assert (tm[name] == t[name]).all()

    # Test for conversion of time data to its value, as defined by its format
    for scale in time.STANDARD_TIME_SCALES:
        for ab in ('a', 'b'):
            name = ab + scale
            t[name].info.serialize_method['fits'] = 'formatted_value'

    t.write(filename, format='fits', overwrite=True)
    tm = table_types.read(filename, format='fits')

    for scale in time.STANDARD_TIME_SCALES:
        for ab in ('a', 'b'):
            name = ab + scale

            assert not isinstance(tm[name], time.Time)
            assert (tm[name] == t[name].value).all()
コード例 #29
0
ファイル: Crabobserving.py プロジェクト: cczhu/scint_analysis
frb = SkyCoord('05h31m58s +33d08m04s', FK5)
magnetar = SkyCoord('17h45m40.1662s -29d00m29.8958s', FK5)
J1723 = SkyCoord('17h23m23.1856s -28d37m57.17s', FK5)

J0518 = SkyCoord('05h18m05.1424740s +33d06m13.365060s', FK5)
J0530 = SkyCoord('05h30m12.5492240s +37d23m32.619700s', FK5)
""" Nearby Calibration Sources """
J0539p3308 = SkyCoord('05h39m09.6718850s +33d08m15.490870s', FK5)
J0533p3451 = SkyCoord('05h33m12.7651060s +34d51m30.336990s', FK5)
""" Nearby Fringe Finders """
J0555p3948 = SkyCoord('05h55m30.8056160s +39d48m49.164930s',
                      FK5)  # Probably use this one
J0530p1331 = SkyCoord('05h30m56.4167490s +13d31m55.149440s', FK5)

#Observatories
ARO = EarthLocation(lat=45.6 * u.deg, lon=-78.04 * u.deg, height=390 * u.m)
DRAO = EarthLocation(lat=49.19 * u.deg, lon=-119.37 * u.deg, height=545 * u.m)
Ef = EarthLocation(lat=50.5247 * u.deg, lon=6.8828 * u.deg, height=319 * u.m)
JB = EarthLocation(lat=53.23 * u.deg, lon=-02.3 * u.deg, height=86 * u.m)
VLA = EarthLocation(lat=34.1 * u.deg, lon=-107.6 * u.deg,
                    height=100 * u.m)  # Height = guess?

#BR_VLBA = EarthLocation(-2112065.0155, -3705356.5107, 4726813.7669)
#FD_VLBA = EarthLocation(-1324009.1622 ,-5332181.9600, 3231962.4508)
#HN_VLBA = EarthLocation( 1446375.0685, -4447939.6572, 4322306.1267)
#KP_VLBA = EarthLocation(-1995678.6640, -5037317.7064, 3357328.1027)
#LA_VLBA = EarthLocation(-1449752.3988, -4975298.5819, 3709123.9044)
#MK_VLBA = EarthLocation(-5464075.0019, -2495248.9291, 2148296.9417)
#NL_VLBA = EarthLocation(-130872.2990, -4762317.1109, 4226851.0268)
#OV_VLBA = EarthLocation(-2409150.1629, -4478573.2045, 3838617.3797)
#PT_VLBA = EarthLocation(-1640953.7116, -5014816.0236, 3575411.8801)
コード例 #30
0
class constant_speed_azel_test(object):

    latitude = 35.940874
    longitude = 138.472153
    height = 1386
    frame = 'fk5'
    nobeyama = EarthLocation(lat=latitude * u.deg,
                             lon=longitude * u.deg,
                             height=height * u.m)
    el_cmd = ''
    az_cmd = ''

    press = 1000
    temp = -2
    humid = 0.8
    #obswl = 230 #GHz
    obswl = 600000  #GHz

    def __init__(self):
        self.start_az = float(input("Start az = "))
        self.end_az = float(input("End az = "))
        self.start_el = float(input("Start el = "))
        self.end_el = float(input("End el = "))
        self.logger = core_controller.logger()
        self.pub_real_azel = rospy.Publisher(
            '/necst/telescope/coordinate/azel_cmd',
            Float64MultiArray,
            queue_size=1)

    def convert_refracted_azel(self):
        altaz = AltAz(location=self.nobeyama,
                      pressure=self.press * u.hPa,
                      temperature=self.temp * u.deg_C,
                      relative_humidity=self.humid,
                      obswl=(astropy.constants.c /
                             (self.obswl * u.GHz)).to('micron'))
        on_coord = SkyCoord(self.az_cmd,
                            self.el_cmd,
                            frame=altaz,
                            unit=(u.deg, u.deg))
        altaz = on_coord.altaz
        return altaz

    def create_az(self):
        start_az = self.start_az
        end_az = self.end_az
        self.az_cmd = start_az
        speed_az = 360 / (24 * 3600)  #deg/s
        dt = 0.01
        while not rospy.is_shutdown():
            if self.az_cmd >= end_az:
                break
            else:
                self.az_cmd += speed_az * dt
                time.sleep(dt)
            continue
        print("Finish to send AZ")

    def create_el(self):
        start_el = self.start_el
        end_el = self.end_el
        self.el_cmd = start_el
        speed_el = 360 / (24 * 3600)  #deg/s
        dt = 0.01
        while not rospy.is_shutdown():
            if self.el_cmd >= end_el:
                break
            else:
                self.el_cmd += speed_el * dt
                time.sleep(dt)
            continue
        print("Finish to send EL")

    def publish_azel(self):
        while not rospy.is_shutdown():
            if self.el_cmd != '':
                altaz = self.convert_refracted_azel()
                #obstime = altaz.obstime
                alt = altaz.alt.deg
                az = altaz.az.deg
                array = Float64MultiArray()
                #array.data = [obstime, az, alt]
                array.data = [az, alt]
                self.pub_real_azel.publish(array)
                time.sleep(0.2)
            else:
                time.sleep(1)
            continue

    def measurement(self):
        date = datetime.datetime.today().strftime('%Y%m%d_%H%M%S')
        file_name = name + '/' + date + '.necstdb'
        print(file_name)
        logger = core_controller.logger()
        self.start_thread_az()
        self.start_thread_el()
        input("Enter to star measurement !!!")
        logger.start(file_name)
        time.sleep(60)
        logger.stop()

    def start_thread(self):
        th = threading.Thread(target=self.publish_azel)
        th.setDaemon(True)
        th.start()

    def start_thread_el(self):
        th = threading.Thread(target=self.create_el)
        th.setDaemon(True)
        th.start()

    def start_thread_az(self):
        th = threading.Thread(target=self.create_az)
        th.setDaemon(True)
        th.start()