def main(filename):
	records=[]
	i=0
	with open(filename, 'rb') as f:
		reader = csv.reader(f)
		for row in reader:
			RA = row[5]
			DEC = row[6]
			l,b = coords.eq2gal(RA,DEC, b1950=False, dtype='f8')
			#print row[0],row[1],row[2],row[3],row[4],row[5],row[6],l,b,row[11],row[12],row[14],row[15],row[16]
			RAflip = float(RA)*-1
			lflip = float(l)*-1
			#construct output record
			#record = '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",%f,%f,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"' % (row[0],row[1],row[2],row[3],row[4],row[5],row[6],l,b,row[11],row[12],row[14],row[15],row[16]) 
			record = '\"%s\",\"%s\",\"%s\",%f,%s,%f,%f,\"%s\",\"%s\",%s,\"%s\",\"%s\",\"%s\"' % (row[0],row[1],row[2],RAflip,DEC,lflip,b,row[11],row[12],row[13],row[14],row[15],row[16])
			records.append(record)

   	#print out results
   	#fl = codecs.open('cxc_sources_fix.csv', 'w', 'utf8')
	fl = open('cxc_sources_fix.csv', 'a')
   	line = '\n'.join(records)
   	#fl.write(line + u'\r\n')
   	fl.write(line)
   	fl.close()
Beispiel #2
0
def main(image):

    #initialize variables
    BASE_RESOURCE_URL = 'http://chandra.harvard.edu/photo/'
    web_img = os.path.basename(image)
    filename, fileext = os.path.splitext(image)
    jpg = basename(filename)+".jpg"
    records=[]
    Type = ""
    Dist = ""
    SubType = "None";

    #jpegs seem to work more consistently with pyavm - use the main jpg image for AVM
    try:
        print "Reading AVM from: "+filename+".jpg"
        avm = AVM(filename+'.jpg')
        ThmbLink = BASE_RESOURCE_URL+filename+'_250.jpg'
        ThmbLink2 = BASE_RESOURCE_URL+filename+'_map.jpg'
    except:
        print 'Trouble reading AVM: '+filename+".jpg"
        return 1

    URL = (avm.ReferenceURL).strip('\n')
    Date = avm.Date
    try:
        Name = avm.Subject.Name[0]
    except:
        print "Missing Name:" +filename+".jpg"
    
    try:
        f = urllib2.urlopen(urllib2.Request(ThmbLink2))
        Img = ThmbLink
    except:
        Img = avm.ResourceURL
    if Img == avm.ResourceURL:
        try:
            f = urllib2.urlopen(urllib2.Request(ThmbLink))
            Img = ThmbLink
        except:
            Img = avm.ResourceURL
            print "Missing thumbnail! (" + ThmbLink + "): " + filename+".jpg"
        
    Cat = re.split("\.",avm.Subject.Category[0])
    Title = avm.Title[0].replace('\"','\'')
                    
    try:
        Headline = avm.Headline.replace('\"','\'')
    except:
        print 'Missing Headline:' +filename+".jpg"

                        
    #coordinate conversions
    try:
        Xeq = avm.Spatial.ReferenceValue[0]
        Yeq = avm.Spatial.ReferenceValue[1]
        Xgal,Ygal = coords.eq2gal(Xeq,Yeq, b1950=False, dtype='f8')
        #Xgal,Ygal = coords.radec2aitoff(l,b)
        #Xeq, Yeq = coords.radec2aitoff(RA, DEC)
    except:
        print 'Missing spatial info:' +filename+".jpg"

    #category parser
    if Cat[0] == "A":
        Dist = "SS"
    if Cat[0] == "B":
        Dist = "MW"
    if Cat[0] == "C":
        Dist = "LU"
    if Cat[0] == "D":
        Dist = "EU"
    if Cat[1] == "1":
        Type = "Planet"
    if Cat[1] == "2":
        Type = "IP"
    if Cat[1] == "3":
        Type = "Star"
        try:
            if Cat[2] == "1":
                if Cat[3] == "7":
                    SubType = "WD"
                if Cat[3] == "8":
                    SubType = "SN"
                if Cat[3] == "9":
                    SubType = "NS"
                if Cat[3] == "10":
                    SubType = "BH"
        except:
            return 1
    if Cat[1] == "4":
        Type = "Nebula"
        try:
            if Cat[2] == "1":
                if Cat[3] == "1":
                    SubType = "ISM"
                if Cat[3] == "2":
                    SubType = "SF"
                if Cat[3] == "3":
                    SubType = "PN"
                if Cat[3] == "4":
                    SubType = "SNR"
                if Cat[3] == "5":
                    SubType = "Jet"
        except:
            return 1
    if Cat[1] == "5":
        Type = "Galaxy"
        try:
            if Cat[2] == "1":
                if Cat[3] == "1":
                    SubType = "Spiral"
                if Cat[3] == "2":
                    SubType = "Barred"
                if Cat[3] == "3":
                    SubType = "Lenticular"
                if Cat[3] == "4":
                    SubType = "Elliptical"
                if Cat[3] == "5":
                    SubType = "Ring"
                if Cat[3] == "6":
                    SubType = "Irregular"
                if Cat[3] == "7":
                    SubType = "Interacting"
                if Cat[3] == "8":
                    SubType = "GravLens"
            if Cat[2] == "2":
                if Cat[3] == "1":
                    SubType = "Giant"
                if Cat[3] == "2":
                    SubType = "Dwarf"
            if Cat[2] == "3":
                if Cat[3] == "1":
                    SubType = "Normal"
                if Cat[3] == "2":
                    SubType = "AGN"
                if Cat[3] == "3":
                    SubType = "Starburst"
                if Cat[3] == "4":
                    SubType = "UL"
        except:
            return 1
    if Cat[1] == "6":
        Type = "Cosmology"            
    
    #Coordinate conversions
    #l,b = coords.eq2gal(RA,DEC, b1950=False, dtype='f8')
    #Xgal,Ygal = coords.radec2aitoff(l,b)
    #Xeq, Yeq = coords.radec2aitoff(RA, DEC)
    
    #construct output record
    record = '\"%s\",\"%s\",\"%s\",%f,%f,%f,%f,\"%s\",\"%s\",%s,\"%s\",\"%s\",\"%s\"' % (Dist,Type,SubType,Xeq*-1,Yeq,Xgal[0]*-1,Ygal[0],Title,Name,Date,URL,Headline,Img) 
    records.append(record)
  
    #print out results
    fl = codecs.open('cxc_sources.csv', 'a', 'utf8')
    line = '\n'.join(records)
    fl.write(line + u'\r\n')
    fl.close()
Beispiel #3
0
def main(filename):
    j = 0;
    outCONST = ["Andromeda","Antlia","Apus","Aquarius","Aquila","Ara ","Aries","Auriga","Bootes","Caelum","Camelopardalis","Cancer ","Canes Venatici","Canis Major ","Canis Minor ","Capricornus ","Carina ","Cassiopeia","Centaurus","Cepheus","Cetus ","Chamaeleon","Circinus","Columba","Coma Berenices","Corona Australis","Corona Borealis","Corvus","Crater","Crux","Cygnus ","Delphinus","Dorado","Draco","Equuleus","Eridanus","Fornax","Gemini","Grus","Hercules","Horologium","Hydra","Hydrus","Indus","Lacerta","Leo ","Leo Minor","Lepus","Libra","Lupus","Lynx","Lyra","Mensa","Microscopium","Monoceros","Musca","Norma","Octans","Ophiuchus","Orion","Pavo","Pegasus","Perseus","Phoenix","Pictor","Pisces","Piscis Austrinus","Puppis","Pyxis","Reticulum","Sagitta ","Sagittarius","Scorpius","Sculptor","Scutum","Serpens","Sextans","Taurus","Telescopium","Triangulum ","Triangulum Australe","Tucana","Ursa Major ","Ursa Minor ","Vela","Virgo","Volans","Vulpecula"];
    
    #print out results
    fl = codecs.open('GalBound.json', 'w', 'utf8')
    fl2 = codecs.open('EqBound.json', 'w', 'utf8')
    fl3 = codecs.open('RADecBound.json', 'w', 'utf8')
    fl4 = codecs.open('TestBound.json', 'w', 'utf8')
    fl.write("{\n\t\"boundaries\": [\n")
    fl2.write("{\n\t\"boundaries\": [\n")
    fl3.write("{\n\t\"boundaries\": [\n")
    fl4.write("{\n\t\"boundaries\":\n[\n")

    json_data=open(filename)
    data = json.load(json_data)

    while (j < 88):
        i = 1;
        records=[]
        records2=[]
        records3=[]
        records4=[]
        while (i < len(data["boundaries"][j])-2):

            RA = data["boundaries"][j][i]
            DEC = data["boundaries"][j][i+1]         

            l,b = coords.eq2gal(RA,DEC, b1950=False, dtype='f8')
            Xgal,Ygal = coords.radec2aitoff(l,b)
            Xeq,Yeq = coords.radec2aitoff(RA,DEC)

            #construct output record
            record = '%s,%s' % (Xgal[0]*-1,Ygal[0]) 
            records.append(record)
            record2 = '%s,%s' % (Xeq[0]*-1,Yeq[0]) 
            records2.append(record2)
            record3 = '%s,%s' % (RA,DEC) 
            records3.append(record3)
            record4 = '{"x":'+str(Xgal[0]*-1)+',"y":'+str(Ygal[0])+'}'
            records4.append(record4)
            i = i+2

        line = ','.join(records)
        fl.write('[\"' + outCONST[j] + '\",')
        line2 = ','.join(records2)
        fl2.write('[\"' + outCONST[j] + '\",')
        line3 = ','.join(records3)
        fl3.write('[\"' + outCONST[j] + '\",')
        line4 = ','.join(records4)
        fl4.write('{"name":\"' + outCONST[j] + '\","box":[')
        if (j < 87):
            fl.write(line + '],\n')
            fl2.write(line2 + '],\n')
            fl3.write(line3 + '],\n')
            fl4.write(line4 + ']},\n')
        if (j == 87):
            fl.write(line + ']\n')
            fl2.write(line2 + ']\n')
            fl3.write(line3 + ']\n')
            fl4.write(line4 + ']}\n')
        j = j+1

    fl.write("\n\t]\n}")
    fl2.write("\n\t]\n}")
    fl3.write("\n\t]\n}")
    fl4.write("]\n}")
    fl.close()
    fl2.close()
    fl3.close()
    fl4.close()
def func_coor_obs_timewindow_calculate(obj_id,group_id,unit_id,racen,deccen,priority,MJD_time_current,tele_pointing_constrain_dframe_all,conf_obs_parameters,observatory):
	MJD_current = float(int(MJD_time_current))
	# print(MJD_current,MJD_time_current)

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

	path = './'

	# start calculate observation sequence
	time_interval = 20.0 # 20 munitues
	night_number = 72 # every 20 munitues, 72 in total.

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

	# set mjd time ----------------------------------------
	nighttime_current = jd2gcal(2400000.5, MJD_time_current)
	hh = int(nighttime_current[3] * 24.0 )
	mm = int((nighttime_current[3] * 24.0 - hh)*60.0)
	ss = (((nighttime_current[3] * 24.0 - hh)*60.0) - mm)*60.0
	hms = "%02d:%02d:%0.1f" % (hh,mm,ss)
	nighttime_current_cal = ('%s/%s/%s %s' % (nighttime_current[0],nighttime_current[1],nighttime_current[2],hms))
	nighttime_current_str = ('%s/%s/%sT%s' % (nighttime_current[0],nighttime_current[1],nighttime_current[2],hms))
	observatory.date = nighttime_current_cal
	

	# calculate local sidereal time  ----------------------------------------
	current_lst_dd = float(str(observatory.sidereal_time()).split(":")[0])* 15.0+\
	float(str(observatory.sidereal_time()).split(":")[1])/60.0* 15.0+\
	float(str(observatory.sidereal_time()).split(":")[2])/3600.0* 15.0
	# print(observatory.date,'current lst 1',(current_lst_dd/15.0))

	# calculate galactic coordinate of field center and all vertexes
	g_cen_lon_dd,g_cen_lat_dd = eq2gal(racen,deccen)

	galactic_lat_min = abs(g_cen_lat_dd)

	data = Table(names=('obj_id', 'tw_begin', 'tw_end', 'obs_stag'),dtype=('a19','a19','a19','a19'))

	for i in range(len(racen)):

		# print(i,float(racen[i]),float(deccen[i]))

		if group_id[i] == "XL001":
			tele_pointing_constrain_dframe_1 =  tele_pointing_constrain_dframe_all[(tele_pointing_constrain_dframe_all["Group_ID"] == "XL001")].copy().reset_index(drop=True)
			tele_pointing_constrain_dframe =  tele_pointing_constrain_dframe_1[(tele_pointing_constrain_dframe_1["Unit_ID"] == 1)].copy().reset_index(drop=True)
			# print(tele_pointing_constrain_dframe)
		else:
			tele_pointing_constrain_dframe_1 =  tele_pointing_constrain_dframe_all[(tele_pointing_constrain_dframe_all["Group_ID"] == "XL002")].copy().reset_index(drop=True)
			tele_pointing_constrain_dframe =  tele_pointing_constrain_dframe_1[(tele_pointing_constrain_dframe_1["Unit_ID"] == 1)].copy().reset_index(drop=True)
		# print(group_id[i],'\n',tele_pointing_constrain_dframe)

		
		for m in range(len(tele_pointing_constrain_dframe)):
			if deccen[i] >= tele_pointing_constrain_dframe['dec_deg'][m] and deccen[i] < (tele_pointing_constrain_dframe['dec_deg'][m] + 10 ) :
				hourangle_east = (tele_pointing_constrain_dframe['hourangle_east'][m])
				hourangle_west = (tele_pointing_constrain_dframe['hourangle_west'][m])

		mjd = []
		ut_time = []
		lst = []
		zenith = []
		hour_angle = []
		for n in range(night_number):	
			# set mjd time ----------------------------------------
			MJD_time = MJD_current + (n*time_interval/60.0/24.0)
			nighttime_current = jd2gcal(2400000.5, MJD_time)
			hh = int(nighttime_current[3] * 24.0 )
			mm = int((nighttime_current[3] * 24.0 - hh)*60.0)
			ss = (((nighttime_current[3] * 24.0 - hh)*60.0) - mm)*60.0
			hms = "%02d:%02d:%0.1f" % (hh,mm,ss)
			nighttime_current_cal = ('%s/%s/%s %s' % (nighttime_current[0],nighttime_current[1],nighttime_current[2],hms))
			nighttime_current_str = ('%s/%s/%sT%s' % (nighttime_current[0],nighttime_current[1],nighttime_current[2],hms))
			observatory.date = nighttime_current_cal
			# print(observatory.date)

			# # set local time ----------------------------------------
			local_nighttime_current = ephem.localtime(observatory.date)
			str(local_nighttime_current).replace(' ','T')

			# set UT time ----------------------------------------
			UT_nighttime_current = ephem.Date(observatory.date)
			UT_nighttime_current_str_T = UT_nighttime_current.datetime().strftime("%Y/%m/%d %H:%M:%S")

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


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

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

			# calculate zenith angular distance of field center and all vertexes
			zenith_ang_dis_cen_dd = (angular_distance(racen[i], deccen[i],lst_dd,lat_dd))

			# calculate angular distance between field center and all vertexes and moon
			moon_ang_dis_min = (angular_distance(racen[i], deccen[i],lunar_ra_dd,lunar_dec_dd))

			# set mini distance from the moon
			for mm in range(len(moon_dis_phase_data)):
				if (lunar.moon_phase >= moon_dis_phase_data[mm][0] and lunar.moon_phase < moon_dis_phase_data[mm][1]):
					moon_dis_min = moon_dis_phase_data[mm][2]
					break

			# calculate hour angle
			hour_angle_n = ((lst_dd - racen[i]) / 15.0)
			# print(lst_dd,hour_angle_n)
			if hour_angle_n >= 12.0 and hour_angle_n <= 24.0:
				hour_angle_n = hour_angle_n - 24.0
			if hour_angle_n <= -12.0 and hour_angle_n >= -24.0:
				hour_angle_n = hour_angle_n + 24.0

			if ( solar_alt_dd > zenith_sun_min ) and ( zenith_ang_dis_cen_dd < zenith_min ) and (moon_ang_dis_min > moon_dis_min ) and (hour_angle_n >= hourangle_east) and (hour_angle_n <= hourangle_west): # and (galactic_lat_min[0] > gal_min) and (moon_ang_dis_min > moon_dis_min ):		
				mjd.append(MJD_time)
				ut_time.append(UT_nighttime_current_str_T)
				lst.append(lst_dd)
				zenith.append(zenith_ang_dis_cen_dd)
				hour_angle.append(hour_angle_n)


		obs_cons = 0
		mjd_begin = 0.0
		mjd_end = 0.0
		obs_phase = ''
		if (len(mjd) > 0 ):
			obs_mjd_begin_index = 0
			obs_mjd_end_index = 0
			if obs_mjd_begin_index == 0:
				obs_mjd_begin_index = mjd.index(min(mjd))
				obs_mjd_end_index = mjd.index(max(mjd))
				mjd_begin = mjd[obs_mjd_begin_index]
				mjd_end = mjd[obs_mjd_end_index]
				lst_begin = lst[obs_mjd_begin_index]
				lst_end = lst[obs_mjd_end_index]
				zenith_begin = zenith[obs_mjd_begin_index]
				zenith_end = zenith[obs_mjd_end_index]
				date_begin = jd2gcal(2400000.5, mjd_begin) #`` float
				date_end = jd2gcal(2400000.5, mjd_end) #`` flaot
				begin_hh = int(date_begin[3] * 24.0 ) #``
				begin_mm = int((date_begin[3] * 24.0 - begin_hh)*60.0) #``                          The last element of the tuple is the same as
				begin_ss = (((date_begin[3] * 24.0 - begin_hh)*60.0) - begin_mm)*60.0 #``              (hh + mm / 60.0 + ss / 3600.0) / 24.0  
				end_hh = int(date_end[3] * 24.0 ) #``                                               where hh, mm, and ss are the hour, minute and second of the day.
				end_mm = int((date_end[3] * 24.0 - end_hh)*60.0) #``
				end_ss = (((date_end[3] * 24.0 - end_hh)*60.0) - end_mm)*60.0 #``
				calendar_date_begin = "%d/%02d/%02d %02d:%02d:%02d" % (date_begin[0],date_begin[1],date_begin[2],begin_hh,begin_mm,begin_ss) #``
				calendar_date_end = "%d/%02d/%02d %02d:%02d:%02d" % (date_end[0],date_end[1],date_end[2],end_hh,end_mm,end_ss) #``
				obs_stag = 'observable'
				# obs_phase = "continous_slot"
	
		if mjd_begin >= mjd_end:
			mjd_begin = 0.0
			mjd_end = 0.0
			calendar_date_begin = "0000/00/00 00:00:00"
			calendar_date_end = "0000/00/00 00:00:00"
			obs_stag = 'unobservable'

		if priority[i] >= 90 and priority[i] <=99:
			obs_stag = 'observable'
			
		data.add_row([obj_id[i],calendar_date_begin,calendar_date_end,obs_stag])

	return data
Beispiel #5
0
def func_coor_obs_timewindow_calculate(Obj_ID, racen, deccen,
                                       MJD_time_current):

    MJD_current = float(int(MJD_time_current))
    # print(MJD_current,MJD_time_current)

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

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

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

    path = './'
    # # set observation day ------------------------------------------------
    # # current_utc_datetime = datetime.datetime.utcnow()
    # Op_time = current_utc_datetime.strftime( '%Y-%m-%d' )
    # Op_time = time.strptime( Op_time, "%Y-%m-%d")
    # gcal_y = Op_time.tm_year
    # gcal_m = Op_time.tm_mon
    # gcal_d = Op_time.tm_mday
    # MJD_current = gcal2jd(gcal_y,gcal_m,gcal_d)[1]
    # MJD_current = MJD_newyear
    # date_current = jd2gcal(2400000.5, MJD_current)
    # calendar_d_lable = "%d_%d_%d" % (date_current[0],date_current[1],date_current[2])
    # calendar_d = "%d-%d-%d" % (date_current[0],date_current[1],date_current[2])

    # print calendar_d

    # start calculate observation sequence
    time_interval = 20.0  # 20 munitues
    night_number = 72  # every 20 munitues, 72 in total.

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

    # set mjd time ----------------------------------------
    nighttime_current = jd2gcal(2400000.5, MJD_time_current)
    hh = int(nighttime_current[3] * 24.0)
    mm = int((nighttime_current[3] * 24.0 - hh) * 60.0)
    ss = (((nighttime_current[3] * 24.0 - hh) * 60.0) - mm) * 60.0
    hms = "%02d:%02d:%0.1f" % (hh, mm, ss)
    nighttime_current_cal = ('%s/%s/%s %s' %
                             (nighttime_current[0], nighttime_current[1],
                              nighttime_current[2], hms))
    nighttime_current_str = ('%s/%s/%sT%s' %
                             (nighttime_current[0], nighttime_current[1],
                              nighttime_current[2], hms))
    observatory.date = nighttime_current_cal

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

    # calculate galactic coordinate of field center and all vertexes
    g_cen_lon_dd, g_cen_lat_dd = eq2gal(racen, deccen)

    galactic_lat_min = abs(g_cen_lat_dd)

    # obs_id_1 = []
    # racen_1 = []
    # deccen_1 = []
    # priority_1 = []
    # ut_time_begin = []
    # ut_time_end = []
    # mjd_begin = []
    # mjd_end = []

    mjd = []
    ut_time = []
    lst = []
    zenith = []
    for n in range(night_number):
        # set mjd time ----------------------------------------
        MJD_time = MJD_current + (n * time_interval / 60.0 / 24.0)
        nighttime_current = jd2gcal(2400000.5, MJD_time)
        hh = int(nighttime_current[3] * 24.0)
        mm = int((nighttime_current[3] * 24.0 - hh) * 60.0)
        ss = (((nighttime_current[3] * 24.0 - hh) * 60.0) - mm) * 60.0
        hms = "%02d:%02d:%0.1f" % (hh, mm, ss)
        nighttime_current_cal = ('%s/%s/%s %s' %
                                 (nighttime_current[0], nighttime_current[1],
                                  nighttime_current[2], hms))
        nighttime_current_str = ('%s/%s/%sT%s' %
                                 (nighttime_current[0], nighttime_current[1],
                                  nighttime_current[2], hms))
        observatory.date = nighttime_current_cal
        # print(observatory.date)

        # # set local time ----------------------------------------
        local_nighttime_current = ephem.localtime(observatory.date)
        str(local_nighttime_current).replace(' ', 'T')

        # set UT time ----------------------------------------
        UT_nighttime_current = ephem.Date(observatory.date)
        UT_nighttime_current_str_T = UT_nighttime_current.datetime().strftime(
            "%Y/%m/%d %H:%M:%S")

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

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

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

        # calculate zenith angular distance of field center and all vertexes
        zenith_ang_dis_cen_dd = (angular_distance(racen, deccen, lst_dd,
                                                  lat_dd))

        # calculate angular distance between field center and all vertexes and moon
        moon_ang_dis_min = (angular_distance(racen, deccen, lunar_ra_dd,
                                             lunar_dec_dd))

        # set mini distance from the moon
        for mm in range(len(moon_dis_phase_data)):
            if (lunar.moon_phase >= moon_dis_phase_data[mm][0]
                    and lunar.moon_phase < moon_dis_phase_data[mm][1]):
                moon_dis_min = moon_dis_phase_data[mm][2]
                break
        # if ( solar_alt_dd > zenith_sun_min ) and ( zenith_ang_dis_cen_dd < zenith_min ):
        # 	print(local_nighttime_current,zenith_ang_dis_cen_dd,zenith_min,MJD_time)
        if (solar_alt_dd > zenith_sun_min) and (
                zenith_ang_dis_cen_dd < zenith_min
        ) and (
                moon_ang_dis_min > moon_dis_min
        ):  # and (galactic_lat_min[0] > gal_min) and (moon_ang_dis_min > moon_dis_min ):
            mjd.append(MJD_time)
            ut_time.append(UT_nighttime_current_str_T)
            lst.append(lst_dd)
            zenith.append(zenith_ang_dis_cen_dd)

    obs_cons = 0
    if (len(mjd) > 0):
        obs_mjd_begin_index = 0
        obs_mjd_end_index = 0
        for mmm in range(len(mjd) - 1):
            m_gap = mjd[mmm + 1] - mjd[mmm]
            m_int = (2.0 / 24.0)
            if m_gap > m_int:
                obs_mjd_begin_index = mjd.index(mjd[mmm + 1])
        if obs_mjd_begin_index == 0:
            obs_mjd_begin_index = mjd.index(min(mjd))
            obs_mjd_end_index = mjd.index(max(mjd))
            mjd_begin = mjd[obs_mjd_begin_index]
            mjd_end = mjd[obs_mjd_end_index]
            lst_begin = lst[obs_mjd_begin_index]
            lst_end = lst[obs_mjd_end_index]
            zenith_begin = zenith[obs_mjd_begin_index]
            zenith_end = zenith[obs_mjd_end_index]
        obs_cons = 1
        print(Obj_ID, mjd_begin, mjd_end)

        # 	hour_ang_current = (current_lst_dd - racen) / 15.0
        # 	if hour_ang_current > 12:
        # 		hour_ang_current = hour_ang_current - 24
        # 	elif hour_ang_current < (-12):
        # 		hour_ang_current = 24 + hour_ang_current

        # 	hour_ang_west = ( current_lst_dd - lst_begin) / 15.0

        # 	if hour_ang_west > 12:
        # 		hour_ang_west = hour_ang_west - 24
        # 	elif hour_ang_west < (-12):
        # 		hour_ang_west = 24 + hour_ang_west

        # 	hour_ang_east = ( current_lst_dd - lst_end ) / 15.0
        # 	if hour_ang_east > 12:
        # 		hour_ang_east = hour_ang_east - 24
        # 	elif hour_ang_east < (-12):
        # 		hour_ang_east = 24 + hour_ang_east

        # 	hourangle_east = -5
        # 	hourangle_west = 5
        # 	if hour_ang_east < hourangle_east:
        # 		hour_ang_east_shift = hour_ang_east - hourangle_east
        # 	else:
        # 		hour_ang_east_shift = 0
        # 	if hour_ang_west > hourangle_west:
        # 		hour_ang_west_shift = hour_ang_west - hourangle_west
        # 	else:
        # 		hour_ang_west_shift = 0

        # 	mjd_begin = mjd_begin + (hour_ang_east_shift / 24.0 / 15.0)
        # 	mjd_end = mjd_end + (hour_ang_west_shift / 24.0 / 15.0 )
        # 	# print(mjd_begin,mjd_end,MJD_time_current,hour_ang_east,hour_ang_west,hourangle_east,hourangle_west)
        # 	if MJD_time_current > mjd_begin and MJD_time_current < mjd_end:
        # 		obs_cons = 1
        # 		# mjd_begin = MJD_time_current + (hour_ang_east / 24.0 / 15.0)
        # 		# mjd_end = MJD_time_current + (hour_ang_west / 24.0 / 15.0 )
        # 	else:
        # 		obs_cons = 0

    if obs_cons == 0:
        mjd_begin = 0.0
        mjd_end = 0.0

    # print(obs_cons,racen, deccen,mjd_begin,mjd_end)
    return obs_cons
def main(filename):
    records=[]

    with open(filename, 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            RA = coords.ra_parse(row[0])
            DEC = float(row[1])
            if row[2] == "AND":
                outCONST = "Andromeda"
            elif row[2] == "ANT":
                outCONST = "Antlia"
            elif row[2] == "APS":
                outCONST = "Apus"
            elif row[2] == "AQR":
                outCONST = "Aquarius"
            elif row[2] == "AQL":
                outCONST = "Aquila"
            elif row[2] == "ARA":
                outCONST = "Ara"
            elif row[2] == "ARI":
                outCONST = "Aries"
            elif row[2] == "AUR":
                outCONST = "Auriga"
            elif row[2] == "BOO":
                outCONST = "Bootes"
            elif row[2] == "CAE":
                outCONST = "Caelum"
            elif row[2] == "CAM":
                outCONST = "Camelopardalis"
            elif row[2] == "CNC":
                outCONST = "Cancer"
            elif row[2] == "CVN":
                outCONST = "Canes Venatici"
            elif row[2] == "CMA":
                outCONST = "Canis Major"
            elif row[2] == "CMI":
                outCONST = "Canis Minor"
            elif row[2] == "CAP":
                outCONST = "Capricornus"
            elif row[2] == "CAR":
                outCONST = "Carina"
            elif row[2] == "CAS":
                outCONST = "Cassiopeia"
            elif row[2] == "CEN":
                outCONST = "Centaurus"
            elif row[2] == "CEP":
                outCONST = "Cepheus"
            elif row[2] == "CET":
                outCONST = "Cetus"
            elif row[2] == "CHA":
                outCONST = "Chamaeleon"
            elif row[2] == "CIR":
                outCONST = "Circinus"
            elif row[2] == "COL":
                outCONST = "Columba"
            elif row[2] == "COM":
                outCONST = "Coma Berenices"
            elif row[2] == "CRA":
                outCONST = "Corona Austrina"
            elif row[2] == "CRB":
                outCONST = "Corona Borealis"
            elif row[2] == "CRV":
                outCONST = "Corvus"
            elif row[2] == "CRT":
                outCONST = "Crater"
            elif row[2] == "CRU":
                outCONST = "Crux"
            elif row[2] == "CYG":
                outCONST = "Cygnus"
            elif row[2] == "DEL":
                outCONST = "Delphinus"
            elif row[2] == "DOR":
                outCONST = "Dorado"
            elif row[2] == "DRA":
                outCONST = "Draco"
            elif row[2] == "EQE":
                outCONST = "Equules"
            elif row[2] == "ERI":
                outCONST = "Eridanus"
            elif row[2] == "FOR":
                outCONST = "Fornax"
            elif row[2] == "GEM":
                outCONST = "Gemini"
            elif row[2] == "GRU":
                outCONST = "Grus"
            elif row[2] == "HER":
                outCONST = "Hercules"
            elif row[2] == "HOR":
                outCONST = "Horologium"
            elif row[2] == "HYA":
                outCONST = "Hydra"
            elif row[2] == "HYI":
                outCONST = "Hydrus"
            elif row[2] == "IND":
                outCONST = "Indus"
            elif row[2] == "LAC":
                outCONST = "Lacerta"
            elif row[2] == "LEO":
                outCONST = "Leo"
            elif row[2] == "LMI":
                outCONST = "Leo Minor"
            elif row[2] == "LEP":
                outCONST = "Lepus"
            elif row[2] == "LIB":
                outCONST = "Libra"
            elif row[2] == "LUP":
                outCONST = "Lepus"
            elif row[2] == "LYN":
                outCONST = "Lynx"
            elif row[2] == "LYR":
                outCONST = "Lyra"
            elif row[2] == "MEN":
                outCONST = "Mensa"
            elif row[2] == "MIC":
                outCONST = "Microscopium"
            elif row[2] == "MON":
                outCONST = "Monoceros"
            elif row[2] == "MUS":
                outCONST = "Musca"
            elif row[2] == "NOR":
                outCONST = "Norma"
            elif row[2] == "OCT":
                outCONST = "Octans"
            elif row[2] == "OPH":
                outCONST = "Ophiuchus"
            elif row[2] == "ORI":
                outCONST = "Orion"
            elif row[2] == "PAV":
                outCONST = "Pavo"
            elif row[2] == "PEG":
                outCONST = "Pegasus"
            elif row[2] == "PER":
                outCONST = "Perseus"
            elif row[2] == "PHE":
                outCONST = "Phoenix"
            elif row[2] == "PIC":
                outCONST = "Pictor"
            elif row[2] == "PSC":
                outCONST = "Pisces"
            elif row[2] == "PSA":
                outCONST = "Piscis Austrinus"
            elif row[2] == "PUP":
                outCONST = "Puppis"
            elif row[2] == "PYX":
                outCONST = "Pyxis"
            elif row[2] == "RET":
                outCONST = "Reticulum"
            elif row[2] == "SGE":
                outCONST = "Sagitta"
            elif row[2] == "SGR":
                outCONST = "Sagittarius"
            elif row[2] == "SCO":
                outCONST = "Scorpius"
            elif row[2] == "SCL":
                outCONST = "Sculptor"
            elif row[2] == "SCT":
                outCONST = "Scutum"
            elif row[2] == "SER":
                outCONST = "Serpens"
            elif row[2] == "SEX":
                outCONST = "Sextans"
            elif row[2] == "TAU":
                outCONST = "Taurus"
            elif row[2] == "TEL":
                outCONST = "Telescopium"
            elif row[2] == "TRI":
                outCONST = "Triangulum"
            elif row[2] == "TRA":
                outCONST = "Triangulum Austrinus"
            elif row[2] == "TUC":
                outCONST = "Tucana"
            elif row[2] == "UMA":
                outCONST = "Ursa Major"
            elif row[2] == "UMI":
                outCONST = "Ursa Minor"
            elif row[2] == "VEL":
                outCONST = "Vela"
            elif row[2] == "VIR":
                outCONST = "Virgo"
            elif row[2] == "VOL":
                outCONST = "Volanus"
            elif row[2] == "VUL":
                outCONST = "Vulpecula"                
                
            l,b = coords.eq2gal(RA,DEC, b1950=False, dtype='f8')
            Xgal,Ygal = coords.radec2aitoff(l,b)
            Xeq,Yeq = coords.radec2aitoff(RA,DEC)

            #construct output record
            record = '%s,%s,%s,%s,%s,%s,\"%s\",\"%s\"' % (RA,DEC,Xgal[0]*-1,Ygal[0],Xeq[0]*-1,Yeq[0],row[2],outCONST) 
            records.append(record)
            
    #print out results
    fl = codecs.open('constellationboundaries_formatted.csv', 'a', 'utf8')
    line = '\n'.join(records)
    fl.write(line + u'\r\n')
    fl.close()
def calc_likeli_uniformXYZ(group_name,
                           X,
                           Y,
                           Z,
                           dX,
                           dY,
                           dZ,
                           a1,
                           a2,
                           a3,
                           U,
                           V,
                           W,
                           dU,
                           dV,
                           dW,
                           b1,
                           b2,
                           b3,
                           ra,
                           de,
                           pra,
                           epra,
                           pde,
                           epde,
                           v=False,
                           ev=False,
                           d=False,
                           ed=False,
                           lencon=1.0,
                           sharpsmooth='-'):

    const = -1.0
    a1 = a1 * const
    a2 = a2 * const
    a3 = a3 * const
    b1 = b1 * const
    b2 = b2 * const
    b3 = b3 * const

    import coords
    import numpy as np

    if np.isnan(v): v = False
    if np.isnan(ev): ev = False
    if np.isnan(d): d = False
    if np.isnan(ed): ed = False

    gl_obs, gb_obs = coords.eq2gal(ra, de, b1950=False)

    # zyx rotation
    R1_S = np.array([[np.cos(a1), -np.sin(a1), 0.],
                     [np.sin(a1), np.cos(a1), 0.], [0., 0., 1.]])
    R2_S = np.array([[np.cos(a2), 0., np.sin(a2)], [0., 1., 0.],
                     [-np.sin(a2), 0., np.cos(a2)]])
    R3_S = np.array([[1., 0., 0.], [0., np.cos(a3), -np.sin(a3)],
                     [0., np.sin(a3), np.cos(a3)]])

    Rot_S1 = np.dot(R2_S, R3_S)
    #    Rot_SFin = np.dot(R1_S,Rot_S1)
    Rot_SFin = np.dot(R3_S, np.dot(R2_S, R1_S))
    # zyx
    R1_D = np.array([[np.cos(b1), -np.sin(b1), 0], [np.sin(b1),
                                                    np.cos(b1), 0],
                     [0., 0., 1.]])
    R2_D = np.array([[np.cos(b2), 0, np.sin(b2)], [0., 1., 0.],
                     [-np.sin(b2), 0, np.cos(b2)]])
    R3_D = np.array([[1., 0., 0.], [0, np.cos(b3), -np.sin(b3)],
                     [0, np.sin(b3), np.cos(b3)]])

    Rot_D1 = np.dot(R2_D, R3_D)
    #    Rot_DFin = np.dot(R1_D,Rot_D1)
    Rot_DFin = np.dot(R3_D, np.dot(R2_D, R1_D))

    pdir = './'

    infile = pdir + 'PriorPDF_rv_dist_b_pm_%s_%.1f_uniformXYZ.txt' % (
        group_name, 10000000.0)
    rv, rvpdf, dist, distpdf, gb, gbpdf, pm, pmpdf = np.loadtxt(infile,
                                                                delimiter=',',
                                                                unpack=True)
    didx = min(range(len(dist)), key=lambda ii: abs(dist[ii] - 100))
    ridx, = np.where(rvpdf > 0.)
    distrange = range(0, didx, 5)
    rvrange = range(ridx[0], ridx[-1], len(ridx) / 20)

    dist_err = np.zeros(len(dist))
    ddist = abs(dist[distrange[1]] - dist[distrange[0]])
    rv_err = np.zeros(len(rv))
    drv = abs(rv[rvrange[1]] - rv[rvrange[0]])

    # calculate (actual) likellihood

    if d:
        dist = [d]
        dist_err = [ed]
        ddist = 1.0
        distpdf = [1.]
        distrange = [0]
    if v:
        rv = [v]
        rv_err = [ev]
        drv = 1.0
        rvpdf = [1.]
        rvrange = [0]

    like = 0.

    xx = np.cos(gb_obs * np.pi / 180.) * np.cos(gl_obs * np.pi / 180.)
    yy = np.cos(gb_obs * np.pi / 180.) * np.sin(gl_obs * np.pi / 180.)
    zz = np.sin(gb_obs * np.pi / 180.)

    TA = calc_TA(ra, de)
    #    K = 4.74057
    K = 4.743717361  # Gagne IDL procedure

    resultarr = np.zeros([len(distrange) + 1, len(rvrange) + 1])

    for iid, ii in enumerate(distrange):  # 50 iteration #(len(dist)):
        resultarr[iid + 1, 0] = dist[ii]

        x = xx * dist[ii]
        y = yy * dist[ii]
        z = zz * dist[ii]
        dx = xx * dist_err[ii]
        dy = yy * dist_err[ii]
        dz = zz * dist_err[ii]

        xp = Rot_SFin[0][0] * (x - X) + Rot_SFin[0][1] * (
            y - Y) + Rot_SFin[0][2] * (z - Z) + X
        yp = Rot_SFin[1][0] * (x - X) + Rot_SFin[1][1] * (
            y - Y) + Rot_SFin[1][2] * (z - Z) + Y
        zp = Rot_SFin[2][0] * (x - X) + Rot_SFin[2][1] * (
            y - Y) + Rot_SFin[2][2] * (z - Z) + Z

        dxp = np.sqrt((Rot_SFin[0][0] * dx)**2 + (Rot_SFin[0][1] * dy)**2 +
                      (Rot_SFin[0][2] * dz)**2)
        dyp = np.sqrt((Rot_SFin[1][0] * dx)**2 + (Rot_SFin[1][1] * dy)**2 +
                      (Rot_SFin[1][2] * dz)**2)
        dzp = np.sqrt((Rot_SFin[2][0] * dx)**2 + (Rot_SFin[2][1] * dy)**2 +
                      (Rot_SFin[2][2] * dz)**2)

        Xerr = np.sqrt(dX**2 + dxp**2)
        Yerr = np.sqrt(dY**2 + dyp**2)
        Zerr = np.sqrt(dZ**2 + dzp**2)

        #dX = Xerr ; dY = Yerr ; dZ = Zerr
        dXX = dX * lencon
        dYY = dY * lencon
        dZZ = dZ * lencon
        volume = 4 * np.pi / 3. * dXX * dYY * dZZ

        if sharpsmooth == 'sh':
            p = 1. / volume
            ellip = (xp - X)**2 / dXX**2 + (yp - Y)**2 / dYY**2 + (
                zp - Z)**2 / dZZ**2
            if ellip < 1.:
                likeX = p**(1 / 3.)
                likeY = likeX
                likeZ = likeX
            else:
                likeX = 0
                likeY = 0
                likeZ = 0.
        elif sharpsmooth == 'sm':
            B = 0.2
            pin = 0.9 / volume
            pout = pin * np.exp(0.5 / B**2 - 0.5 *
                                ((xp - X) / dX / B)**2 - 0.5 *
                                ((yp - Y) / dY / B)**2 - 0.5 *
                                ((zp - Z) / dZ / B)**2)
            ellip = (xp - X)**2 / dXX**2 + (yp - Y)**2 / dYY**2 + (
                zp - Z)**2 / dZZ**2
            if ellip < 1.:
                likeX = pin**(1 / 3.)
                likeY = likeX
                likeZ = likeX
            else:
                likeX = pout**(1. / 3.)
                likeY = likeX
                likeZ = likeX

        for jjr, jj in enumerate(rvrange):  # range(len(rv)):
            #print "DIST and RV= ",dist[ii],dist_err[ii],rv[jj],ev
            resultarr[0, jjr + 1] = rv[jj]

            arr = np.array([rv[jj], K * pra * dist[ii], K * pde * dist[ii]])
            u, v, w = np.dot(TA, arr)

            du = np.sqrt((TA[0][0] * ev)**2. + (TA[0][1] * K)**2 *
                         ((epra * dist[ii])**2 + (pra * dist_err[ii])**2 +
                          (epra * dist_err[ii])**2) + (TA[0][2] * K)**2 *
                         ((epde * dist[ii])**2 + (pde * dist_err[ii])**2 +
                          (epde * dist_err[ii])**2))
            dv = np.sqrt((TA[1][0] * ev)**2. + (TA[1][1] * K)**2 *
                         ((epra * dist[ii])**2 + (pra * dist_err[ii])**2 +
                          (epra * dist_err[ii])**2) + (TA[1][2] * K)**2 *
                         ((epde * dist[ii])**2 + (pde * dist_err[ii])**2 +
                          (epde * dist_err[ii])**2))
            dw = np.sqrt((TA[2][0] * ev)**2. + (TA[2][1] * K)**2 *
                         ((epra * dist[ii])**2 + (pra * dist_err[ii])**2 +
                          (epra * dist_err[ii])**2) + (TA[2][2] * K)**2 *
                         ((epde * dist[ii])**2 + (pde * dist_err[ii])**2 +
                          (epde * dist_err[ii])**2))

            up = Rot_DFin[0][0] * (u - U) + Rot_DFin[0][1] * (
                v - V) + Rot_DFin[0][2] * (w - W) + U
            vp = Rot_DFin[1][0] * (u - U) + Rot_DFin[1][1] * (
                v - V) + Rot_DFin[1][2] * (w - W) + V
            wp = Rot_DFin[2][0] * (u - U) + Rot_DFin[2][1] * (
                v - V) + Rot_DFin[2][2] * (w - W) + W

            dup = np.sqrt((Rot_DFin[0][0] * du)**2 + (Rot_DFin[0][1] * dv)**2 +
                          (Rot_DFin[0][2] * dw)**2)
            dvp = np.sqrt((Rot_DFin[1][0] * du)**2 + (Rot_DFin[1][1] * dv)**2 +
                          (Rot_DFin[1][2] * dw)**2)
            dwp = np.sqrt((Rot_DFin[2][0] * du)**2 + (Rot_DFin[2][1] * dv)**2 +
                          (Rot_DFin[2][2] * dw)**2)

            Uerr = np.sqrt(dup**2. + dU**2.)
            Verr = np.sqrt(dvp**2. + dV**2.)
            Werr = np.sqrt(dwp**2. + dW**2.)

            likeU = np.exp(-0.5 * (up - U)**2. / Uerr**2.) / Uerr / np.sqrt(
                2. * np.pi)
            likeV = np.exp(-0.5 * (vp - V)**2. / Verr**2.) / Verr / np.sqrt(
                2. * np.pi)
            likeW = np.exp(-0.5 * (wp - W)**2. / Werr**2.) / Werr / np.sqrt(
                2. * np.pi)

            like = rvpdf[jj] * distpdf[
                ii] * likeX * likeY * likeZ * likeU * likeV * likeW * drv * ddist

            resultarr[iid + 1, jjr + 1] = like
    likearr = np.array(resultarr[1:, 1:])

    idx = np.where(likearr == np.max(likearr))
    statdist = resultarr[idx[0] + 1, 0]
    statrv = resultarr[0, idx[1] + 1]

    result = [likearr.sum(), statdist, statrv]

    #    return result

    return result[0], result[1], result[
        2], likeX, likeY, likeZ, likeU, likeV, likeW  #,x,y,z,u,v,w,rv,dist,pmra_obs,pmde_obs
Beispiel #8
0
def calc_prior(gname,
               Nk,
               ra,
               de,
               pmra_obs=False,
               epmra_obs=False,
               pmde_obs=False,
               epmde_obs=False,
               rv_obs=False,
               erv_obs=False,
               dist_obs=False,
               edist_obs=False,
               goru=False):

    import coords
    import numpy as np

    pdir = './'

    if np.isnan(rv_obs): rv_obs = False
    if np.isnan(erv_obs): erv_obs = False
    if np.isnan(dist_obs): dist_obs = False
    if np.isnan(edist_obs): edist_obs = False

    gl_obs, gb_obs = coords.eq2gal(ra, de, b1950=False)

    pm_obs = np.sqrt(pmra_obs**2. + pmde_obs**2.)
    epm_obs = np.sqrt((pmra_obs / pm_obs * epmra_obs)**2. +
                      (pmde_obs / pm_obs * epmde_obs)**2.)

    if goru == 'u':
        PDFfile = pdir + 'PriorPDF_rv_dist_b_pm_%s_%.1f_uniformXYZ.txt' % (
            gname, 10000000.0)
    elif goru == 'g':
        PDFfile = pdir + 'PriorPDF_rv_dist_b_pm_%s_%.1f.txt' % (gname,
                                                                10000000.0)

    rv, rvpdf, dist, distpdf, gb, gbpdf, pm, pmpdf = np.loadtxt(PDFfile,
                                                                delimiter=',',
                                                                unpack=True)

    drv = np.abs(rv[1] - rv[0])
    ddist = np.abs(dist[1] - dist[0])
    dgb = np.abs(gb[1] - gb[0])
    dpm = np.abs(pm[1] - pm[0])

    prior_pm = 0.
    prior_gb = 0.
    prior_rv = 0.
    prior_dist = 0.
    for j in range(len(rv)):
        prior_pm = prior_pm + np.exp(
            -0.5 * (pm[j] - pm_obs)**2. / epm_obs**2.) * pmpdf[j] * dpm

    idx, num = min(enumerate(gb), key=lambda x: abs(x[1] - gb_obs))
    prior_gb = gbpdf[idx] * dgb
    if rv_obs:
        for j in range(len(rv)):
            prior_rv = prior_rv + np.exp(
                -0.5 * (rv[j] - rv_obs)**2. / erv_obs**2.) * rvpdf[j] * drv
    else:
        prior_rv = 1.
        erv_obs = 1.0

    if dist_obs:
        for j in range(len(rv)):
            prior_dist = prior_dist + np.exp(
                -0.5 *
                (dist[j] - dist_obs)**2. / edist_obs**2.) * distpdf[j] * ddist
    else:
        prior_dist = 1.
        edist_obs = 1.0

    prior_pm = prior_pm / epm_obs
    prior_gb = prior_gb
    prior_rv = prior_rv / erv_obs
    prior_dist = prior_dist / edist_obs

    fin_prior = Nk * prior_pm * prior_gb * prior_rv * prior_dist

    #   print fin_prior
    return fin_prior, prior_pm, prior_gb, prior_rv, prior_dist, pm_obs, gb_obs, rv_obs, dist_obs