def greg_to_mjd(greg): """ Convert gregorian date into MJD. Parameters ---------- greg : string Gregorian date (format: YYYYMMDD_HHMMSS) Returns ---------- mjd : float Date in the format MJD. Examples ---------- >>> greg = '19881103_000000' >>> mjd = greg_to_mjd(greg) >>> print('GREG={} ->'.format(greg), 'MJD={}'.format(round(mjd, 2))) GREG=19881103_000000 -> MJD=47468.0 """ year = int(greg[:4]) month = int(greg[4:6]) day = int(greg[6:8]) hour = int(greg[9:11]) minute = int(greg[11:13]) second = int(greg[13:15]) fracday, status = slalib.sla_dtf2d(hour, minute, second) mjd, status = slalib.sla_cldj(year, month, day) mjd += fracday return mjd
def _test_gcal2jd_with_sla_cldj(): """Compare gcal2jd with slalib.sla_cldj.""" import random try: from pyslalib import slalib except ImportError: print("SLALIB (PySLALIB not available).") return 1 n = 1000 mday = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # sla_cldj needs year > -4699 i.e., 4700 BC. year = [random.randint(-4699, 2200) for i in range(n)] month = [random.randint(1, 12) for i in range(n)] day = [random.randint(1, 31) for i in range(n)] for i in range(n): x = 0 if is_leap(year[i]) and month[i] == 2: x = 1 if day[i] > mday[month[i]] + x: day[i] = mday[month[i]] jd_jdc = [gcal2jd(y, m, d)[1] for y, m, d in zip(year, month, day)] jd_sla = [slalib.sla_cldj(y, m, d)[0] for y, m, d in zip(year, month, day)] diff = [abs(i - j) for i, j in zip(jd_sla, jd_jdc)] assert max(diff) <= 1e-8 assert min(diff) <= 1e-8
def radvel(self, sdate, time, radeg, decdeg): # decode the date, convert to MJD ss = sdate.split('-') year = int(ss[0]) mont = int(ss[1]) day = int(ss[2]) mjdv = s.sla_cldj(year, mont, day) mjd0 = mjdv[0] rstat = mjdv[1] uttime, tf1 = self.sex2deg(time) # time in hours #radeg,tf1 = sex2deg(rastring) #if tf1 == 0 : radeg = radeg*15.0 #decdeg,tf1 = sex2deg(decstring) # print '<br>RA=%8.4f deg, DEC=%8.4f deg' % (radeg,decdeg) mjdt = mjd0 + uttime / 24.0 # print 'Using ', sdate, mjdt, uttime, radeg,decdeg rr = self.rvel(mjdt, radeg, decdeg) # ((mjdd, last*12.0/math.pi, Rgeo, totalhelio,totalbary, totallsrk,totalgal)) return rr
def current_MJD(): """ current_MJD(): Return the current MJD accurate to ~1 sec. """ YY, MM, DD, hh, mm, ss, wday, yday, isdst = time.gmtime() mjd_f, J = s.sla_dtf2d(hh, mm, ss) mjd_i, J = s.sla_cldj(YY, MM, DD) return mjd_i + mjd_f
def DATEOBS_to_MJD(dateobs): """Convert DATE-OBS string from PSRFITS primary HDU to a MJD. Returns a 2-tuple: (integer part of MJD, fractional part of MJD) """ # Parse string using regular expression defined at top of file m = date_obs_re.match(dateobs) mjd_fracday = (float(m.group("hour")) + (float(m.group("min")) + \ (float(m.group("sec")) / 60.0)) / 60.0) / 24.0 mjd_day, err = slalib.sla_cldj(float(m.group("year")), \ float(m.group("month")), float(m.group("day"))) return mjd_day, mjd_fracday
def datetime_to_mjd_utc(d): """Function to calculate MJD for a given UTC""" (mjd, status) = slalib.sla_cldj(d.year, d.month, d.day) if status != 0: return None (fday, status ) = slalib.sla_dtf2d(d.hour, d.minute, d.second+(d.microsecond/1e6)) if status != 0: return None mjd_utc = mjd + fday return mjd_utc
def datetime2mjd_utc(d): # Compute MJD for UTC (mjd, status) = S.sla_cldj(d.year, d.month, d.day) if status != 0: return None (fday, status ) = S.sla_dtf2d(d.hour, d.minute, d.second+(d.microsecond/1e6)) if status != 0: return None mjd_utc = mjd + fday return mjd_utc
def datetime2mjd_utc(d): """Converts a passed datetime object in UTC to the equivalent Modified Julian Date (MJD), which is returned""" # Compute MJD for UTC (mjd, status) = S.sla_cldj(d.year, d.month, d.day) if status != 0: return None (fday, status) = S.sla_dtf2d(d.hour, d.minute, d.second + (d.microsecond / 1e6)) if status != 0: return None mjd_utc = mjd + fday return mjd_utc
def epochToMJD(t=None): """ Return the current MJD accurate to ~1 sec if no argument otherwise convert argument from unix epoch to MJD """ from pyslalib import slalib as s if t is None: YY, MM, DD, hh, mm, ss, wday, yday, isdst = time.gmtime() else: YY, MM, DD, hh, mm, ss, wday, yday, isdst = time.gmtime(t) mjd_f, J = s.sla_dtf2d(hh, mm, ss) mjd_i, J = s.sla_cldj(YY, MM, DD) return mjd_i + mjd_f
def calc_hjd(date_obs,ra,dec,debug=False): """Function to convert a timestamp in %Y-%m-%dT%H:%M:%S UTC format to Heliocentric Julian Date for a given RA, Dec of target""" # Convert RA, Dec to radians: c = SkyCoord(ra,dec,unit=(u.hourangle,u.deg)) if debug==True: print 'RA '+ra+' -> decimal radians '+str(c.ra.radian) if debug==True: print 'Dec '+dec+' -> decimal radians '+str(c.dec.radian) # Convert the timestamp into a DateTime object: if 'T' in date_obs: try: dt = datetime.strptime(date_obs,"%Y-%m-%dT%H:%M:%S") except ValueError: dt = datetime.strptime(date_obs,"%Y-%m-%dT%H:%M:%S.%f") else: try: dt = datetime.strptime(date_obs,"%Y-%m-%d %H:%M:%S") except ValueError: dt = datetime.strptime(date_obs,"%Y-%m-%d %H:%M:%S.%f") # Calculate the MJD (UTC) timestamp: mjd_utc = datetime_to_mjd_utc(dt) if debug==True: print 'MJD_UTC = '+str(mjd_utc) # Correct the MJD to TT: mjd_tt = mjd_utc_to_mjd_tt(mjd_utc) if debug==True: print 'MJD_TT = '+str(mjd_tt) # Calculating MJD of 1st January that year: (mjd_jan1,iexec) = slalib.sla_cldj(dt.year,1,1) if debug==True: print 'MJD of Jan 1, '+str(dt.year)+' = '+str(mjd_jan1) # Calculating the MJD difference between the DateObs and Jan 1 of the same year: tdiff = mjd_tt - mjd_jan1 if debug==True: print 'Time difference from Jan 1 - dateobs, '+str(dt.year)+' = '+str(tdiff) # Calculating the RV and time corrections to the Sun: (rv,tcorr) = slalib.sla_ecor(c.ra.radian,c.dec.radian,\ dt.year,int(tdiff),(tdiff-int(tdiff))) if debug==True: print 'Time correction to the Sun = '+str(tcorr) # Calculating the HJD: hjd = mjd_tt + tcorr/86400.0 + 2400000.5 if debug==True: print 'HJD = '+str(hjd) return hjd
def radvellist(self, sdate, rastring, decstring): # decode the date, convert to MJD ss = sdate.split('-') year = int(ss[0]) mont = int(ss[1]) day = int(ss[2]) mjdv = s.sla_cldj(year, mont, day) mjd0 = mjdv[0] rstat = mjdv[1] raval = s.sla_dafin(rastring, 1) # convert to radians dcval = s.sla_dafin(decstring, 1) rarad = raval[1] * 15. dcrad = dcval[1] # degrees radeg = rarad * 180.0 / math.pi decdeg = dcrad * 180.0 / math.pi # print "" # print ' %3s %7s %7s %7s %13s %13s %13s' % \ # ('UTHr', 'LST', 'Geo', 'Helio', 'Barycentric', 'LSRK', 'Galacto') # loop through 25 hours for i in range(0, 25): hour = i dfrac = hour / 24.0 mjd1 = mjd0 + dfrac rr = self.rvel(mjd1, radeg, decdeg) # ((mjdd, last*12.0/math.pi, Rgeo, totalhelio,totalbary, totallsrk,totalgal)) print(' %3d %7.3f %7.3f %7.3f %13.3f %13.3f %13.3f' % \ (hour,rr[1],rr[2],rr[3],rr[4],rr[5],rr[6]))
def all_sky_shot(self, number, magnitude, az_star, el_star, data_name, status): thr = 80 #threshold of brightness if os.path.exists("/home/amigos/NECST/soft/data/"+str(data_name)): pass else: os.mkdir("/home/amigos/NECST/soft/data/"+str(data_name)) #status = {"Command_Az":0,"Command_El":0,"Current_Az":0,"Current_El":0,"OutTemp":0,"Press":0,"OutHumi":0} date = datetime.datetime.today() month = str("{0:02d}".format(date.month)) day = str("{0:02d}".format(date.day)) hour = str("{0:02d}".format(date.hour)) minute = str("{0:02d}".format(date.minute)) second = str("{0:02d}".format(date.second)) name = str(date.year)+month+day+hour+minute+second #oneshot self.oneshot(name) ret = slalib.sla_cldj(date.year, date.month, date.day) mjd = ret[0] secofday = date.hour*60*60 + date.minute*60 + date.second + date.microsecond*0.000001 #load array path = os.getcwd() com = "mv "+str(path)+"/"+str(name)+".png /home/amigos/NECST/soft/data/"+str(data_name)+"/"+str(name)+".png" ret = commands.getoutput(com) print(ret) in_image = Image.open("/home/amigos/NECST/soft/data/"+str(data_name)+"/"+name+".png") image = np.array(ImageOps.grayscale(in_image)) ori_image = np.array(image) #threshold width = len(image[0]) height = len(image) for i in range(height): for j in range(width): if image[i][j] < thr: image[i][j] = 0 #calc dimention p_array = np.zeros(256) for i in range(height): for j in range(width): p_array[image[i][j]] += 1 #find color num = 1 nmax = 1 for i in range(255): if nmax < p_array[i+1]: nmax = p_array[i+1] num = i+1 #find star x = 0 y = 0 n = 0 for i in range(height): for j in range(width): if image[i][j] == num: x += j y += i n += 1 if n == 0: print("CAN'T FIND STAR") #black photograph return x = x/n y = y/n #find center xx = 0. yy = 0. f = 0. for i in range(21): for j in range(21): xx += (x+j-10.)*image[y+i-10.][x+j-10.] yy += (y+i-10.)*image[y+i-10.][x+j-10.] f += image[y+i-10.][x+j-10.] if f == 0.: #two or more stars print("MANY STARS ARE PHOTOGRAPHED") return xx = xx/f yy = yy/f print(xx) print(yy) self.save_status(xx, yy, number, magnitude, az_star, el_star, mjd, data_name, secofday, status) return
def onepoint_shot(self, ra, dec, az_star, el_star, data_name, status): thr = 80 #threshold of brightness <=? if os.path.exists("/home/amigos/NECST/soft/data/"+str(data_name)): pass else: os.mkdir("/home/amigos/NECST/soft/data/"+str(data_name)) name = time.strftime('%Y%m%d_%H%M%S') #oneshot self.oneshot(name) ret = slalib.sla_cldj(date.year, date.month, date.day) mjd = ret[0] secofday = date.hour*60*60 + date.minute*60 + date.second + date.microsecond*0.000001 #load array path = os.getcwd() com = "mv "+str(path)+"/"+str(name)+".png /home/amigos/NECST/soft/data/"+str(data_name)+"/"+str(name)+".png" ret = commands.getoutput(com) print(ret) in_image = Image.open("/home/amigos/NECST/soft/data/"+str(data_name)+"/"+name+".png") image = np.array(ImageOps.grayscale(in_image)) ori_image = np.array(image) #threshold width = len(image[0]) height = len(image) for i in range(height): for j in range(width): if image[i][j] < thr: image[i][j] = 0 #calc dimention p_array = np.zeros(256) for i in range(height): for j in range(width): p_array[image[i][j]] += 1 #find color num = 1 nmax = 1 for i in range(255): if nmax < p_array[i+1]: nmax = p_array[i+1] num = i+1 #find star x = 0 y = 0 n = 0 for i in range(height): for j in range(width): if image[i][j] == num: x += j y += i n += 1 if n == 0: print("CAN'T FIND STAR") #black photograph return 1 x = x/n y = y/n #find center xx = 0. yy = 0. f = 0. for i in range(21): for j in range(21): xx += (x+j-10.)*image[y+i-10.][x+j-10.] yy += (y+i-10.)*image[y+i-10.][x+j-10.] f += image[y+i-10.][x+j-10.] if f == 0.: #two or more stars print("MANY STARS ARE PHOTOGRAPHED") return 1 xx = xx/f yy = yy/f print(xx) print(yy) self.save_track_status(xx, yy, ra, az_star, el_star, mjd, data_name, secofday, status) return
def create_table(self): #create target_list f = open(self.pointing_list) line = f.readline() target_list = [] tv = time.time() mjd2 = tv / 24. / 3600. + 40587.0 # 40587.0 = MJD0 #calculate mjd(now) and mjd(2000) date = datetime.datetime.today() ret = slalib.sla_cldj(date.year, date.month, date.day) mjd = ret[0] ret = slalib.sla_cldj(2000, 1, 1) mjd2000 = ret[0] while line: list = [] line = line.replace(";", " ") line = line.split() #number(FK6) list.append(line[0]) #ra,dec(degree) ra = float(line[1]) * (360. / 24.) + float( line[2]) * (360. / 24.) / 60. + float( line[3]) * (360. / 24.) / 3600. + float(line[4]) * ( 360. / 24.) / 3600. * (mjd - mjd2000) / 36525. if line[5] == "+": dec = float(line[6]) + float(line[7]) / 60. + float( line[8]) / 3600. + float( line[9]) / 3600. * (mjd - mjd2000) / 36525. else: dec = -(float(line[6]) + float(line[7]) / 60. + float(line[8]) / 3600.) + float( line[9]) / 3600. * (mjd - mjd2000) / 36525. list.append(ra) list.append(dec) list.append(line[21]) #magnitude ret = self.calc_star_azel(ra, dec, mjd2) list.append(ret[0]) #az #list = [number, ra, dec, magnitude, az] #print(ret[1]) print(str(ra) + " " + str(dec)) if ret[1] >= 30 and ret[1] <= 80: print("============") num = len(target_list) if num == 0: target_list.append(list) elif num == 1: if target_list[0][4] < list[4]: target_list.append(list) else: target_list.insert(0, list) else: for i in range(num): if target_list[i][4] > list[4]: target_list.insert(i, list) break if i == num - 1: target_list.insert(num, list) #print(target_list) line = f.readline() f.close() return target_list
def create_table(self): #create target_list f = open(self.pointing_list) line = f.readline() target_list = [] tv = time.time() mjd2 = tv/24./3600. + 40587.0 # 40587.0 = MJD0 #calculate mjd(now) and mjd(2000) date = datetime.datetime.today() ret = slalib.sla_cldj(date.year, date.month, date.day) mjd = ret[0] ret = slalib.sla_cldj(2000, 1, 1) mjd2000 = ret[0] while line: list = [] line = line.replace(";", " ") line = line.split() #number(FK6) list.append(line[0]) #ra,dec(degree) ra = float(line[1])*(360./24.)+float(line[2])*(360./24.)/60.+float(line[3])*(360./24.)/3600.+float(line[4])*(360./24.)/3600.*(mjd - mjd2000)/36525. if line[5] == "+": dec = float(line[6])+float(line[7])/60.+float(line[8])/3600.+float(line[9])/3600.*(mjd - mjd2000)/36525. else: dec = -(float(line[6])+float(line[7])/60.+float(line[8])/3600.)+float(line[9])/3600.*(mjd - mjd2000)/36525. list.append(ra) list.append(dec) list.append(line[21]) #magnitude ret = self.calc_star_azel(ra, dec, mjd2) list.append(ret[0]) #az #list = [number, ra, dec, magnitude, az] #print(ret[1]) print(str(ra)+" "+str(dec)) if ret[1] >= 30 and ret[1] <= 80: print("============") num = len(target_list) if num == 0: target_list.append(list) elif num == 1: if target_list[0][4] < list[4]: target_list.append(list) else: target_list.insert(0, list) else: for i in range(num): if target_list[i][4] > list[4]: target_list.insert(i, list) break if i == num-1: target_list.insert(num, list) #print(target_list) line = f.readline() f.close() return target_list
def _convert_coordinates(self, lat, long, ra_ref, dec_ref, date, time): """ Accurate conversion from equatorial coordiantes (RA, DEC) to Spherical (TH,PH) coordinates. The code uses the pyslalib library for a number of functions from the SLALIB Fortran library converted to Python. :param lat: latitude (decimal degrees) :param long: longitude (decimal degrees) :param ra_ref: RA(J2000) (decimal hours) :param dec_ref: Dec(J2000) (decimal degrees) :param date: vector date [iyear, imonth, iday] :param time: vector time [ihour imin isec] :return: [theta, pi]: Theta and Phi angles (degrees) """ const_2pi = 2.0 * math.pi d2r = math.pi / 180 r2d = 180 / math.pi # Conversion factor seconds of time to days const_st2day = 1.0/(24 * 3600) # Specify latitude and longitude (radians) lat *= d2r long *= d2r # Specify catalogued position (J2000 coordinates, radians) ra_ref = ra_ref * 15 * d2r dec_ref *= d2r # Specify current time and date % isec = time[2] imin = time[1] ihour = time[0] iday = date[2] imonth = date[1] iyear = date[0] # Convert current UTC to Modified Julian date djm, j1 = slalib.sla_cldj(iyear, imonth, iday) fdutc, j2 = slalib.sla_dtf2d(ihour, imin, isec) djutc = djm + fdutc # Calculate Greenwich Mean Sidereal Time from MJD gmst1 = slalib.sla_gmst(djutc) # Add longitude and Equation of Equinoxes for Local Apparent ST djtt = djutc + slalib.sla_dtt(djutc)*const_st2day last = gmst1 + long + slalib.sla_eqeqx(djtt) if last < 0.0: last += const_2pi # Convert catalogued position to apparent RA, Dec at current date pr = 0.e0 pd = 0.e0 px = 0.e0 rv = 0.e0 eq = 2000.0e0 [raobs, decobs] = slalib.sla_map(ra_ref, dec_ref, pr, pd, px, rv, eq, djutc) # Get Hour Angle and Declination ha = last - raobs if ha < -math.pi: ha += const_2pi if ha > math.pi: ha -= const_2pi dec = decobs # Convert to Azimuth and Elevation azim, elev = slalib.sla_de2h(ha, dec, lat) theta = (90 - elev * r2d).real phi = (azim * r2d).real return [theta, phi]