def check_map_params(image1, image2, ifhdu):
    """v1 < v2"""

    header1 = take_header(image1, ifhdu)
    header2 = take_header(image2, ifhdu)

    cell1 = header1[0]
    cell2 = header2[0]

    if cell1 == cell2:
        cells = header1[0]
        print 'Same cellsize'
    else:
        print 'The images do not have the same cellsize'
        print 'Convolve them using the same cell'
        raise Exception('Stopping!')

    map_data1 = read_map(image1, ifhdu)
    realDAT = map_data1[0]
    map_data2 = read_map(image2, ifhdu)
    realDAT2 = map_data2[0]

    if realDAT.shape == realDAT2.shape:
        print 'Same mapsize'
    else:
        print 'The images do not have the same mapsize'
        print 'Convolve them using the same mapsize'
        raise Exception('Stopping!')

    beam1 = header1[7]
    beam2 = header2[7]

    if beam1 == beam2:
        beam = header1[7]
        print 'Same beam'
    else:
        print 'The images do not have the same beam'
        print 'Convolve them using the same beam'
        raise Exception('Stopping!')

    #obtaining frequencies
    freq1 = header1[5]
    freq2 = header2[5]

    #obtaining map centers in pixels
    cent_mapx = map_data1[5]
    cent_mapy = map_data1[6]

    #obtaining the four corners of the maps in mas
    x1 = map_data1[1]
    x2 = map_data1[2]
    y1 = map_data1[3]
    y2 = map_data1[4]

    print 'Proceeding with the next step'

    return realDAT, realDAT2, freq1, freq2, cells, beam, cent_mapx, cent_mapy, x1, x2, y1, y2
    def Bfieldcalculation(self):

	self.viewingangle = float(self.viewing.text())
	self.viewingangle = np.deg2rad(self.viewingangle)
	self.openingangle = np.deg2rad(self.openingangle)
	self.openingangle = float(self.opening.text())
	self.gammavalue = float(self.gamma.text())

	self.beta = np.sqrt(1. - 1./self.gammavalue**2)
	self.deltavalue = 1./(self.gammavalue*(1-self.beta*np.cos(self.viewingangle)))

	for i in xrange(len(self.checks)):
		if self.checks[i].isChecked():
			#if a == 0:
			self.fits1 = needed_param.fits[i]
			self.models1 = needed_param.modelfit[i]
			self.models1errors = needed_param.modelfiterror[i]
			tempi = i


	header1 = take_header(self.fits1,self.ifhdu)
	self.freq1 = header1[5]

	self.Btb[tempi] = Bfield_Tb(self.Tbcore[tempi]/10**(12),self.zvalue,self.gammavalue,self.deltavalue,self.freq1)

	print self.Btb
class needed_param():

	path = os.getcwd()



	#store the uvf, mod and fits files of the maps in a list
	files = []
	for filename in sorted(glob.glob(path+'/UVF/*.uvf*')):   
		files.append(filename)     #for the moment as well, you can also read the file with header = pf.getheader(uvffile) and then freq = header['CRVAL4'], all that would be easier in general as i dont need to depend of having a similar modification date in all of them ----> leads to changing the function order_by_nu
			
	models = []
	for filename in sorted(glob.glob(path+'/MODELS/*.mod*')):   
		models.append(filename)  #for the moment, in the modelfit file it is posible to read the frequency, which will simplify how to get it in general
		
	fits = []
	for filename in sorted(glob.glob(path+'/FITS/*.fits*')):   
		fits.append(filename)  

	modelfit = []
	for filename in sorted(glob.glob(path+'/modelfit/*.mod*')):   
		modelfit.append(filename)  #for the moment, in the modelfit file it is posible to read the frequency, which will simplify how to get it in general

	modelfit.sort(key=natural_keys)

	modelfiterror = []
	for filename in sorted(glob.glob(path+'/modelfit/*.dat*')):   
		modelfiterror.append(filename)  #for the moment, in the modelfit file it is posible to read the frequency, which will simplify how to get it in general

	modelfiterror.sort(key=natural_keys)

	coreshiftfile = []
	for filename in sorted(glob.glob(path+'/coreshiftmeas/*.meas*')):   
		coreshiftfile.append(filename)   #for the moment, in the modelfit file it is posible to read the frequency, which will simplify how to get it in general

					
	#initialize arrays
	cell = np.array([0.]*len(fits))
	bmaj = np.array([0.]*len(fits))
	bmin = np.array([0.]*len(fits))
	bpa = np.array([0.]*len(fits))
	freq = np.array([0.]*len(fits))
	beam = np.array([0.]*len(fits))
	size_map = np.array([0.]*len(fits))
	size_map_y =np.array([0.]*len(fits))

	#order the the list by frequency and 
	#getting the corresponding values of the previous initialized arrays ordered by frequency 
	#(lower to higher)
	ordered_params = order_by_nu(files,models,fits,False)
	
	freq = ordered_params[0]
	files = ordered_params[8]
	models = ordered_params[9]
	fits = ordered_params[10]
	
	#source name
	header = take_header(fits[0],False)
	source_name = header[8]
def order_by_nu(files, models, fits, ifhdu):

    #initialize arrays
    cell = np.array([0.] * len(fits))
    bmaj = np.array([0.] * len(fits))
    bmin = np.array([0.] * len(fits))
    bpa = np.array([0.] * len(fits))
    freq = np.array([0.] * len(fits))
    beam = np.array([0.] * len(fits))
    size_map = np.array([0.] * len(fits))
    size_map_y = np.array([0.] * len(fits))

    #read some parameters of the map
    for i in xrange(0, len(fits)):
        header = take_header(fits[i], ifhdu)
        cell[i] = header[0]
        bmaj[i] = header[1]
        bmin[i] = header[2]
        bpa[i] = header[3]
        freq[i] = header[5]
        beam[i] = header[7]
        map_details = read_map(fits[i], ifhdu)
        if map_details[7] == map_details[8]:
            size_map[i] = map_details[7]
        else:
            size_map[i] = map_details[7]
            size_map_y[i] = map_details[8]

    #store them in ascendent order related with the frequency
    n = 0
    for z in freq:
        n += 1
    for i in range(n):
        for j in range(1, n - i):
            if freq[j - 1] > freq[j]:
                (freq[j - 1], freq[j]) = (freq[j], freq[j - 1])
                (cell[j - 1], cell[j]) = (cell[j], cell[j - 1])
                (bmaj[j - 1], bmaj[j]) = (bmaj[j], bmaj[j - 1])
                (bmin[j - 1], bmin[j]) = (bmin[j], bmin[j - 1])
                (bpa[j - 1], bpa[j]) = (bpa[j], bpa[j - 1])
                (beam[j - 1], beam[j]) = (beam[j], beam[j - 1])
                (size_map[j - 1], size_map[j]) = (size_map[j], size_map[j - 1])
                (size_map_y[j - 1], size_map_y[j]) = (size_map_y[j],
                                                      size_map_y[j - 1])
                (files[j - 1], files[j]) = (files[j], files[j - 1])
                (models[j - 1], models[j]) = (models[j], models[j - 1])
                (fits[j - 1], fits[j]) = (fits[j], fits[j - 1])

    return freq, cell, bmaj, bmin, bpa, beam, size_map, size_map_y, files, models, fits
Esempio n. 5
0
class needed_param():

	path = os.getcwd()

	if not os.path.exists('Plot_fitted_synchrotron'):
		os.makedirs('Plot_fitted_synchrotron')
	if not os.path.exists('Plot_fitted_PL'):
		os.makedirs('Plot_fitted_PL')
	if not os.path.exists('Plot_fitted_synchrotronExtrapolated'):
		os.makedirs('Plot_fitted_synchrotronExtrapolated')


	#store the uvf, mod and fits files of the maps in a list
	files = []
	for filename in sorted(glob.glob(path+'/UVF/*.uvf*')):   
		files.append(filename)   
			
	models = []
	for filename in sorted(glob.glob(path+'/MODELS/*.mod*')):   
		models.append(filename)  
		
	fits = []
	for filename in sorted(glob.glob(path+'/FITS/*.fits*')):   
		fits.append(filename)  
					
	#initialize arrays
	cell = np.array([0.]*len(fits))
	bmaj = np.array([0.]*len(fits))
	bmin = np.array([0.]*len(fits))
	bpa = np.array([0.]*len(fits))
	freq = np.array([0.]*len(fits))
	beam = np.array([0.]*len(fits))
	size_map = np.array([0.]*len(fits))
	size_map_y =np.array([0.]*len(fits))

	#order the the list by frequency and 
	#getting the corresponding values of the previous initialized arrays ordered by frequency 
	#(lower to higher)
	ordered_params = order_by_nu(files,models,fits,False)
	
	freq = ordered_params[0]
	files = ordered_params[8]
	models = ordered_params[9]
	fits = ordered_params[10]
	
	#source name
	header = take_header(fits[0],False)
	source_name = header[8]
Esempio n. 6
0
    def Bfieldcalculation(self):

	self.DLvalue = float(self.DL.text())
	self.zvalue = float(self.z.text())
	self.scalevalue = float(self.scale.text())
	self.gammavalue = float(self.gamma.text())
	self.deltavalue = float(self.delta.text())

	filefreq = 'bo/shifted15.fits'
	header = take_header(filefreq,False)
	self.cellsize = header[0]
	mapdata = read_map(filefreq,False)
	realDAT = mapdata[0]
	self.ext = [mapdata[1],mapdata[2],mapdata[3],mapdata[4]]

	res = open('turnoverdata.p','rb')
	pick = pickle.load(res)
	res.close()
	self.vmall = pick[0]
	self.small = pick[1]#*1.4213481404770085
	self.alpha0all = pick[2]
	self.alphathickall = pick[3]
	shapee = np.shape(self.alpha0all)
	self.Ball = np.zeros(shapee)
	self.Kall = np.zeros(shapee)


	self.Ball[:] = np.nan
	self.Kall[:] = np.nan


	#cellsize *2 for getting the diameter
	for i in xrange (0,shapee[0]):
	    for j in xrange(0,shapee[1]):
		if np.isnan(self.small[i][j]) == False:
		    tempBK = B_field(self.alpha0all[i][j],self.alphathickall[i][j],self.DLvalue,self.zvalue,self.scalevalue,self.cellsize*2*self.gammavalue,self.deltavalue,self.vmall[i][j],self.small[i][j])
		    self.Ball[i][j] = tempBK[0]
		    self.Kall[i][j] = tempBK[1]

	plt.figure(1)
	cset = plt.contour(realDAT,0.008*np.array([2.,4.,16.,64.,256.,1020.,2050.]),inline=1,colors=['grey'],aspect=1.0,extent=self.ext)
	plt.imshow(self.Ball,origin='bottom',extent=self.ext,vmin=0,vmax=0.1)
	plt.colorbar()
	plt.show()
    def SigmaNcalculation(self):

	self.gammamaxvalue = float(self.gammamax.text())
	self.gammaminvalue = float(self.gammamin.text())
	self.alpha0value = float(self.alpha0.text())

	for i in xrange(len(self.checks)):
		if self.checks[i].isChecked():
			#if a == 0:
			self.fits1 = needed_param.fits[i]
			self.models1 = needed_param.modelfit[i]
			self.models1errors = needed_param.modelfiterror[i]
			tempi = i

	header1 = take_header(self.fits1,self.ifhdu)
	self.freq1 = header1[5]

	#kr=1
	#coreshiftmeas=48

	self.Sigma[tempi], self.nrad[tempi] = Magnetization(self.alpha0value,self.gammaminvalue,self.gammamaxvalue,self.Btb[tempi],self.scalevalue,self.viewingangle,self.openingangle,self.zvalue,self.gammavalue,self.deltavalue,1.,self.freq1,self.Tbcore[tempi]/10**(12),48.)

	print self.Sigma
	print self.nrad
Esempio n. 8
0
def check_map_params(image1, image2, ifhdu):
    """v1 < v2"""

    header1 = take_header(image1, ifhdu)
    header2 = take_header(image2, ifhdu)

    cell1 = header1[0]
    cell2 = header2[0]

    if cell1 == cell2:
        cells = header1[0]
        OK = True
        print('Same cellsize')
    else:
        cells = 0.
        print('The images do not have the same cellsize')
        print('Convolve them using the same cell')
        OK = False

    map_data1 = read_map(image1, ifhdu)
    realDAT = map_data1[0]
    map_data2 = read_map(image2, ifhdu)
    realDAT2 = map_data2[0]

    if realDAT.shape == realDAT2.shape:
        if OK == False:
            OK = False
        else:
            OK = True
        print('Same mapsize')
    else:
        print('The images do not have the same mapsize')
        print('Convolve them using the same mapsize')
        OK = False

    beam1 = header1[7]
    beam2 = header2[7]

    if beam1 == beam2:
        beam = header1[7]
        if OK == False:
            OK = False
        else:
            OK = True
        print('Same beam')
    else:
        beam = 0.
        print('The images do not have the same beam')
        print('Convolve them using the same beam')
        OK = False
        #raise IOError('Stopping!') compatible with python 3, same that raise Exception

    #obtaining frequencies
    freq1 = header1[5]
    freq2 = header2[5]

    #obtaining map centers in pixels
    cent_mapx = map_data1[5]
    cent_mapy = map_data1[6]

    #obtaining the four corners of the maps in mas
    x1 = map_data1[1]
    x2 = map_data1[2]
    y1 = map_data1[3]
    y2 = map_data1[4]

    print('Proceeding with the next step')

    return OK, realDAT, realDAT2, freq1, freq2, cells, beam, cent_mapx, cent_mapy, x1, x2, y1, y2
    def Tbcalculation(self):

	self.DLvalue = float(self.DL.text())
	self.zvalue = float(self.z.text())
	self.scalevalue = float(self.scale.text())

	a = 0
	for i in xrange(len(self.checks)):
		if self.checks[i].isChecked():
			#if a == 0:
			self.fits1 = needed_param.fits[i]
			self.models1 = needed_param.modelfit[i]
			self.models1errors = needed_param.modelfiterror[i]
			tempi = i
			#	a = 1
			#if a == 1:
			#	self.fits2 = needed_param.fits[i]

	#self.reading_rms_param()
	header1 = take_header(self.fits1,self.ifhdu)
	#header2 = take_header(self.fits2,self.ifhdu)
	map_data1 = read_map(self.fits1,self.ifhdu)		
	self.image1 = map_data1[0]
	#map_data2 = read_map(self.fits2,self.ifhdu)		
	#self.image2 = map_data2[0]

	#obtaining the beam and cell
	self.bmaj_files = header1[1]
	self.bmin_files = header1[2]
	self.bpa_files = header1[3]
	self.beam_files = header1[7]
	self.cells_files = header1[0]
	self.freq1 = header1[5]

	#obtaining map centers in pixels
	self.cent_mapx = map_data1[5]
	self.cent_mapy = map_data1[6]
	self.mapsize_files = 2*map_data1[7]

	#obtaining the four corners of the maps in mas
	x1 = map_data1[1]
	x2 = map_data1[2]
	y1 = map_data1[3]
	y2 = map_data1[4]

	self.extmas=[x1,x2,y1,y2] 
	
		
	self.sigma_cut = float(self.SigmaCut.text())

	if self.freq1 < 0.5:
		self.freq1name = str('%1.0f' %(self.freq1*1000))
		self.freq1unit = 'MHz'
	else:
		self.freq1name = str('%1.2f' %(self.freq1))
		self.freq1unit = 'GHz'

	res=open(needed_param.path+'/rms'+self.freq1name+'.p','rb')
	pick = pickle.load(res)
	res.close() 

	self.rms1 = pick	

	modelfitparameters = read_modfile([self.models1],self.beam_files,self.zvalue,self.freq1,True,self.models1errors)

	#r_arr,errr_arr,
	#2psi_arr,errpsi_arr,
	#4size_arr,errsize_arr,
	#6flux_arr,errflux_arr,
	#8tb1_arr,errtb1_arr,
	#dlim1_arr,
	#11tb2_arr,errtb2_arr,
	#dlim2_arr

	x_and_y = x_y(modelfitparameters[0],modelfitparameters[1],modelfitparameters[2],modelfitparameters[3],True)
	x, errx = np.asarray(x_and_y[0]), np.asarray(x_and_y[1])
	y, erry = np.asarray(x_and_y[2]), np.asarray(x_and_y[3])

	#for plotting the components in the map
	pts_arr=[]
	pt_arr=[]
	x_el_arr=[]
	x_elH_arr=[]
	y_el_arr=[]
	y_elH_arr=[]

	#r_arr 0,errr_arr 1 ,psi_arr 2,errpsi_arr 3,size_arr 4,errsize_arr 5,tb_arr 6,errtb_arr 7,flux_arr 8,errflux_arr 9,tbNew 10

	r = modelfitparameters[0]
	errr = modelfitparameters[1]
	psi = modelfitparameters[2]
	size = modelfitparameters[4]
	errsize = modelfitparameters[5]
	Tb = modelfitparameters[8][0]
	errTb = modelfitparameters[9][0]
	self.Tbcore[tempi] = Tb[0]
	self.sizecore[tempi] = modelfitparameters[4][0]
	self.fluxcore[tempi] = modelfitparameters[6][0]
	print 'Tb', self.Tbcore
	print 'size', self.sizecore
	print 'flux', self.fluxcore

	ellipse_plot = ellipse_axis_lines(x,y,modelfitparameters[4])
	pts_arr,pt_arr = ellipse_plot[0], ellipse_plot[1]
	x_el_arr,y_el_arr = ellipse_plot[2], ellipse_plot[3]
	x_elH_arr,y_elH_arr = ellipse_plot[4], ellipse_plot[5]  

	plt.figure(1)
	plot_components(pts_arr,x_el_arr,x_elH_arr,y_elH_arr,y_el_arr)
	plot_maps(self.image1,self.extmas,self.rms1*self.sigma_cut)
	plt.xlim(x1,x2)
	#plt.ylim(-1.5,1.5)
	#plt.savefig('1642CBAND.png', bbox_inches='tight')

	plt.show()

	"""limits = Annotate()
	plt.show()
		
	ext_new = []
	[self.limplot_x1,self.limplot_x2,self.limplot_y1,self.limplot_y2] = limits()

	self.extmasnew = [self.limplot_x1,self.limplot_x2,self.limplot_y2,self.limplot_y1]

	plt.figure(1)
	plot_components(pts_arr,x_el_arr,x_elH_arr,y_elH_arr,y_el_arr)
	plot_maps(self.image1,self.extmas,self.rms1*self.sigma_cut)
	plt.xlim(self.limplot_x1,self.limplot_x2)
	plt.ylim(self.limplot_y2,self.limplot_y1)
	plt.savefig('modelfit'+str('%1.1f' % (self.freq1))+'.png', bbox_inches='tight')

	plt.show()"""



	plt.close('all')

	plt.figure(2)
	plt.plot(needed_param.freq,self.Tbcore,'r.',markersize=12)
	plt.xscale('log')
	plt.yscale('log')
	plt.ylabel(r'$T_b$ [K]')
	plt.xlabel(r'$\nu$ [GHz]')
	plt.savefig('logTb_ground.png')

	plt.figure(3)
	plt.plot(needed_param.freq,self.sizecore,'r.',markersize=12)
	plt.xscale('log')
	plt.yscale('log')
	plt.ylabel(r'$\theta$ [mas]')
	plt.xlabel(r'$\nu$ [GHz]')
	plt.savefig('logTheta_ground.png')

	plt.figure(4)
	plt.plot(needed_param.freq,self.fluxcore,'r.',markersize=12)
	plt.xscale('log')
	plt.yscale('log')
	plt.ylabel(r'$S_y$ [Jy]')
	plt.xlabel(r'$\nu$ [GHz]')
	plt.savefig('logS_ground.png')
	#plt.xlim(x1,x2)
	#plt.ylim(-1.5,1.5)
	#plt.savefig('1642CBAND.png', bbox_inches='tight')

	plt.close('all')

	plt.figure(2)
	plt.xscale('log')
	plt.yscale('log')
	plt.errorbar(r,Tb,yerr=0.434*errTb,fmt='ro',ecolor='r', capthick=2)
	plt.ylabel(r'$T_b$ [K]')
	plt.xlabel('r [mas]')
	plt.savefig('Tbfreq'+str('%1.1f' % (self.freq1))+'.png')

	plt.close('all')


	res=open(needed_param.path+'/pickle'+str('%1.1f' % (self.freq1))+'.p','wb')
	pickle.dump([r,Tb,0.434*errTb,psi,x,y,size,errsize],res)
	res.close()     
Esempio n. 10
0
class needed_param():

    path = os.getcwd()

    #store the uvf, mod and fits files of the maps in a list
    files = []
    for filename in sorted(glob.glob(path + '/UVF/*.uvf*')):
        files.append(filename)

    models = []
    for filename in sorted(glob.glob(path + '/MODELS/*.mod*')):
        models.append(filename)

    fits = []
    for filename in sorted(glob.glob(path + '/FITS/*.fits*')):
        fits.append(filename)

    modelfit = []
    for filename in sorted(glob.glob(path + '/modelfit/*.mod*')):
        modelfit.append(filename)

    modelfit.sort(key=natural_keys)

    #initialize arrays
    cell = np.array([0.] * len(fits))
    bmaj = np.array([0.] * len(fits))
    bmin = np.array([0.] * len(fits))
    bpa = np.array([0.] * len(fits))
    freq = np.array([0.] * len(fits))
    beam = np.array([0.] * len(fits))
    size_map = np.array([0.] * len(fits))
    size_map_y = np.array([0.] * len(fits))

    #order the the list by frequency and
    #getting the corresponding values of the previous initialized arrays ordered by frequency
    #(lower to higher)
    ordered_params = order_by_nu(files, models, fits, False)

    freqOrig = ordered_params[0]
    beam = ordered_params[5]
    files = ordered_params[8]
    models = ordered_params[9]
    fits = ordered_params[10]

    freq = freqOrig.copy()
    units = []

    for i in xrange(0, len(freq)):
        if freq[i] < 0.5:
            freq[i] = freq[i] * 1000
            units.append('MHz')
        else:
            units.append('GHz')

    units = np.asarray(units)

    #source name
    header = take_header(fits[0], False)
    source_name = header[8]

    #reads the modelfit files and obtains the modelfit values and errors

    if len(modelfit) > 0:
        if os.path.isfile('pos_errors.dat'):
            errors = True
        else:
            errors = None

        mod_parameters = read_modfile(modelfit, beam, errors)
        """
		r, errr = radial distance and error of the component
		psi, errpsi = position angle and error of the component
		size, errsize =  size and error of the component
		"""
        r, errr = mod_parameters[0], mod_parameters[1]
        psi, errpsi = mod_parameters[2], mod_parameters[3]
        size, errsize = mod_parameters[4], mod_parameters[5]
        flux, errflux = mod_parameters[7], mod_parameters[8]

        #with the radial distance and position angle, the central positions of the components in RA and DEC are calculated
        """
		x, errx = position in RA and error of the component
		y, erry = position in DEC and error of the component
		"""
        x_and_y = x_y(r, errr, psi, errpsi, errors)
        x, errx = np.asarray(x_and_y[0]), np.asarray(x_and_y[1])
        y, erry = np.asarray(x_and_y[2]), np.asarray(x_and_y[3])

        #for plotting the components in the map
        """
		pts_arr = points for drawing the external countour of the ellipse, i.e., the ellipse itself

		x_el_arr = points for the x axis in the x direction of the ellipse. They are between (x_cent_component - size component) and (x_cent_component + size component).They are a total of 50
		y_elH_arr = points for the y axis in the x direction of the ellipse. It is a constant, so it is the same value 50 times, for using it with x_el_arr 

		y_el_arr = points for the y axis in the y direction of the ellipse. They are between (y_cent_component - size component) and (y_cent_component + size component). They are a total of 50
		x_elH_arr = points for the x axis in the y direction of the ellipse. It is a constant, so it is the same value 50 times, for using it with y_el_arr 

		"""
        pts_arr = []
        pt_arr = []
        x_el_arr = []
        x_elH_arr = []
        y_el_arr = []
        y_elH_arr = []

        ellipse_plot = ellipse_axis_lines(x, y, size)
        pts_arr, pt_arr = ellipse_plot[0], ellipse_plot[1]
        x_el_arr, y_el_arr = ellipse_plot[2], ellipse_plot[3]
        x_elH_arr, y_elH_arr = ellipse_plot[4], ellipse_plot[5]
Esempio n. 11
0
    def selectComp(self, fits1, fits2):

        self.rms = []

        header1 = take_header(fits1, False)
        header2 = take_header(fits2, False)
        #self.rms.append(header1[9])
        #self.rms.append(header2[9])
        map_data1 = read_map(fits1, False)
        realDAT = map_data1[0]
        map_data2 = read_map(fits2, False)
        realDAT2 = map_data2[0]

        #picks the value of the first contour for plotting the maps
        ShiftComponentsWindow.realDATA = [realDAT, realDAT2]

        ShiftComponentsWindow.numComp = int(self.numComp.text())

        #obtaining the beam and cell
        self.bmaj_files = header1[1]
        self.bmin_files = header1[2]
        self.bpa_files = header1[3]
        self.beam_files = header1[7]
        self.cells_files = header1[0]

        #obtaining frequencies
        self.freq1 = header1[5]
        self.freq2 = header2[5]

        if self.freq1 < 0.5:
            self.freq1name = str('%1.0f' % (self.freq1 * 1000))
            self.freq1unit = 'MHz'
        else:
            self.freq1name = str('%1.2f' % (self.freq1))
            self.freq1unit = 'GHz'

        if self.freq2 < 0.5:
            self.freq2name = str('%1.0f' % (self.freq2 * 1000))
            self.freq2unit = 'MHz'
        else:
            self.freq2name = str('%1.2f' % (self.freq2))
            self.freq2unit = 'GHz'

        res = open(needed_param.path + '/rms' + self.freq1name + '.p', 'rb')
        pick = pickle.load(res)
        res.close()

        self.rms.append(pick)

        res = open(needed_param.path + '/rms' + self.freq2name + '.p', 'rb')
        pick = pickle.load(res)
        res.close()

        self.rms.append(pick)

        ShiftComponentsWindow.freq1 = self.freq1
        ShiftComponentsWindow.freq2 = self.freq2

        self.first_contour = []
        sigma_cut = float(self.SigmaCut.text())
        for i in xrange(0, len(self.rms)):
            self.first_contour.append(sigma_cut * self.rms[i])

        ShiftComponentsWindow.firstCont = self.first_contour

        #obtaining map centers in pixels
        cent_mapx = map_data1[5]
        cent_mapy = map_data1[6]
        self.mapsize_files = 2 * map_data1[7]

        #obtaining the four corners of the maps in mas
        x1 = map_data1[1]
        x2 = map_data1[2]
        y1 = map_data1[3]
        y2 = map_data1[4]

        ShiftComponentsWindow.ext = [x1, x2, y1, y2]

        #for plotting the components
        ShiftComponentsWindow.pts_arr,ShiftComponentsWindow.x_el_arr,ShiftComponentsWindow.x_elH_arr = [],[],[]
        ShiftComponentsWindow.y_elH_arr,ShiftComponentsWindow.y_el_arr = [],[]
        ShiftComponentsWindow.xSelected,ShiftComponentsWindow.ySelected = [],[]
        ShiftComponentsWindow.errxSelected,ShiftComponentsWindow.errySelected = [],[]
        for i in xrange(0, len(self.checks)):
            if self.checks[i].isChecked():
                ShiftComponentsWindow.pts_arr.append(needed_param.pts_arr[i])
                ShiftComponentsWindow.x_el_arr.append(needed_param.x_el_arr[i])
                ShiftComponentsWindow.x_elH_arr.append(
                    needed_param.x_elH_arr[i])
                ShiftComponentsWindow.y_elH_arr.append(
                    needed_param.y_elH_arr[i])
                ShiftComponentsWindow.y_el_arr.append(needed_param.y_el_arr[i])
                ShiftComponentsWindow.xSelected.append(needed_param.x[i])
                ShiftComponentsWindow.ySelected.append(needed_param.y[i])
                ShiftComponentsWindow.errxSelected.append(needed_param.errx[i])
                ShiftComponentsWindow.errySelected.append(needed_param.erry[i])

        indexComp = selectComponent(
            realDAT, realDAT2, self.first_contour,
            ShiftComponentsWindow.pts_arr, ShiftComponentsWindow.x_el_arr,
            ShiftComponentsWindow.x_elH_arr, ShiftComponentsWindow.y_elH_arr,
            ShiftComponentsWindow.y_el_arr, ShiftComponentsWindow.ext,
            self.freq1, self.freq2, ShiftComponentsWindow.xSelected,
            ShiftComponentsWindow.ySelected, ShiftComponentsWindow.numComp,
            self.orientation)

        ShiftComponentsWindow.indexes = [indexComp[0], indexComp[1]]

        plt.close('all')

        self.wi = popupAutomaticSelection()
        self.wi.show()
        self.wi.YesButton.clicked.connect(lambda: self.GoodCompSelection())
        self.wi.NoButton.clicked.connect(lambda: self.BadCompSelection())
import iminuit, probfit
from scipy.optimize import curve_fit
from functions_conv import order_by_nu, read_conv_params
from functions_align import find_same_beam, beam_array, check_map_params, cuttingMAP, cross_correlation_shifts_FITS, checking_shift
from functions_turnover import cuttingTURN, synchrotron, synchrotron_v1, guesses_turnover, guesses_turnoverPoint, guesses_PL, powerLaw, powerLawPlot
from functions2 import take_header, read_map, saver
from functions2 import convolve_difmap, get_ellipse_coords, Annotate
from functions_Bfield import searchNEDnoGUI, B_field, N_UeUb_sigma
import os, glob
import subprocess as sub
from astropy.nddata import Cutout2D
from correlate2d import *
#from fast_ftts import *

filefreq = 'bo/shifted15.fits'
header = take_header(filefreq, False)
cellsize = header[0]
mapdata = read_map(filefreq, False)
realDAT = mapdata[0]
ext = [mapdata[1], mapdata[2], mapdata[3], mapdata[4]]

res = open('turnoverdata.p', 'rb')
pick = pickle.load(res)
res.close()
nu = pick[0]
s = pick[1]  #*1.4213481404770085
alpha0 = pick[2]
alphathick = pick[3]

plt.figure(1)
ax = plt.gca()
    def shifting(self,checkBOXes,fits1,fits2,files,models):

	self.get_thread = updateGUIshiftText()
	self.get_thread.start()	

	header1 = take_header(fits1)
	header2 = take_header(fits2)
	map_data1 = read_map(fits1)		
	realDAT = map_data1[0]
	map_data2 = read_map(fits2)		
	realDAT2 = map_data2[0]

	#obtaining the beam and cell
	self.bmaj_files = header1[1]
	self.bmin_files = header1[2]
	self.bpa_files = header1[3]
	self.beam_files = header1[7]
	self.cells_files = header1[0]

	#obtaining frequencies
	self.freq1 = header1[5]
	self.freq2 = header2[5]

	#obtaining map centers in pixels
	cent_mapx = map_data1[5]
	cent_mapy = map_data1[6]
	self.mapsize_files = 2*map_data1[7]

	#obtaining the four corners of the maps in mas
	x1 = map_data1[1]
	x2 = map_data1[2]
	y1 = map_data1[3]
	y2 = map_data1[4]

	ShiftWindow.ext=[x1,x2,y1,y2] 

	#cut maps v1 < v2, map region to study
	cut = cuttingMAP(realDAT,realDAT2,cent_mapx,cent_mapy,self.cells_files,self.freq1,self.freq2,iteration=0)

	cutout_v1 = cut[0]
	cutout_v2 = cut[1]
	    
	self.position = cut[2]
	self.size = cut[3]
	ShiftWindow.ext = cut[4]


	#cut maps v1 < v2, feature
	cut = cuttingMAP(cutout_v1.data,cutout_v2.data,cent_mapx,cent_mapy,self.cells_files,self.freq1,self.freq2,iteration=1)

	cutout_v1feature = cut[0]
	cutout_v2feature = cut[1]
    
	self.position_feature = cut[2]
	self.size_feature = cut[3]

	plt.figure(1)
	plt.subplot(121)
	plt.imshow(cutout_v2feature.data, origin='bottom')
	#plt.axis('scaled')
	plt.xlabel('Right Ascension [pixels]')
	plt.ylabel('Relative Declination [pixels]')
	plt.title(str('%1.3f' %(self.freq2))+' GHz')

	plt.subplot(122)
	plt.imshow(cutout_v1feature.data, origin='bottom')
	#plt.axis('scaled')
	plt.xlabel('Right Ascension [pixels]')
	#plt.ylabel('Relative Declination [pixels]')
	plt.title(str('%1.3f' %(self.freq1))+' GHz')

	plt.show()

	#2d cross-correlation

	image1 = cutout_v1feature.data
	image2 = cutout_v2feature.data

	ShiftWindow.offset = cross_correlation_shifts_FITS(image1, image2, sigma_cut=0.004)

	ShiftWindow.xshift=-ShiftWindow.offset[0]*self.cells_files #mas
	ShiftWindow.yshift=ShiftWindow.offset[1]*self.cells_files #mas

	self.shifted_files=[]
	self.shifted_files.append(needed_param.path+'/SHIFT/'+needed_param.source_name+'-'+str(round(self.freq1))+'convolved_with_beam'+str('%1.2f' % (self.beam_files))+'shifted.fits')
	self.shifted_files.append(needed_param.path+'/SHIFT/'+needed_param.source_name+'-'+str(round(self.freq2))+'convolved_with_beam'+str('%1.2f' % (self.beam_files))+'shifted.fits')
	

	self.models_chosen = []
	self.files_chosen = []
	for i in xrange(len(checkBOXes)):
		if checkBOXes[i].isChecked():
			self.models_chosen.append(models[i])
			self.files_chosen.append(files[i])


	self.freqsSHIFTING.setText(("Image2 ( %s GHz)  - image1 ( %s GHz)" % ('%1.2f' % (self.freq2), '%1.2f' % (self.freq1))))
	self.freqsSHIFTING.setStyleSheet('QLabel {color: blue } QLabel {font: Bold }')
	self.labelSHIFTraMAS.setText(("%s mas" % ('%1.4f' % (ShiftWindow.xshift))))
	self.labelSHIFTraMAS.setStyleSheet('QLabel {color: blue } QLabel {font: Bold }')
	self.labelSHIFTraPIXEL.setText(("%s pix" % ('%1.2f' % (ShiftWindow.offset[0]))))
	self.labelSHIFTraPIXEL.setStyleSheet('QLabel {color: blue } QLabel {font: Bold }')
	self.labelSHIFTdecMAS.setText(("%s mas" % ('%1.4f' % (ShiftWindow.yshift))))
	self.labelSHIFTdecMAS.setStyleSheet('QLabel {color: blue } QLabel {font: Bold }')
	self.labelSHIFTdecPIXEL.setText(("%s pix" % ('%1.2f' % (ShiftWindow.offset[1]))))
	self.labelSHIFTdecPIXEL.setStyleSheet('QLabel {color: blue } QLabel {font: Bold }')


	#print 'Image2 (', freq2, ') - image1 (' , freq1, ')' 
	#print 'Shift RA: ', offset[0], 'pixels'
	#print 'Shift DEC: ', offset[1], 'pixels'

	#print 'Shift RA: ', xshift, 'mas'
	#print 'Shift DEC: ', yshift, 'mas'


	os.system('rm difmap.log*\n')

	convolve_difmap([self.files_chosen[0]],[self.models_chosen[0]],self.bmaj_files,self.bmin_files,self.bpa_files,ShiftWindow.xshift,ShiftWindow.yshift,self.mapsize_files,self.cells_files,2,-1,[self.shifted_files[0]])

	#rms1 (lower freq)
	self.rms1 = search_rms()[0]
	os.system('rm difmap.log*\n')

	convolve_difmap([self.files_chosen[1]],[self.models_chosen[1]],self.bmaj_files,self.bmin_files,self.bpa_files,0,0,self.mapsize_files,self.cells_files,2,-1,[self.shifted_files[1]])

	self.rms2 = search_rms()[0]
	os.system('rm difmap.log*\n')


	#check if the shift was done properly
	self.checkingShift()
class needed_files():

	path = os.getcwd()
	sourcepath = os.getcwd()

	if not os.path.exists('UVF'):
		os.makedirs('UVF')
	if not os.path.exists('MODELS'):
		os.makedirs('MODELS')
	if not os.path.exists('FITS'):
		os.makedirs('FITS')
	if not os.path.exists('CONV'):
		os.makedirs('CONV')
	if not os.path.exists('CONV_ALL'):
		os.makedirs('CONV_ALL')
	if not os.path.exists('SHIFT'):
		os.makedirs('SHIFT')
	if not os.path.exists('Shift_parameters'):
		os.makedirs('Shift_parameters')
	if not os.path.exists('SHIFT_ALL'):
		os.makedirs('SHIFT_ALL')
	if not os.path.exists('Plot_fitted'):
		os.makedirs('Plot_fitted')
	if not os.path.exists('SPIX_MAPS'):
		os.makedirs('SPIX_MAPS')
	if not os.path.exists('coreshiftmeas'):
		os.makedirs('coreshiftmeas')

	source = os.listdir(sourcepath)
	destinationpath_uvf = path+'/UVF/'
	destinationpath_models = path+'/MODELS/'
	destinationpath_fits = path+'/FITS/'

	for files in source:
		if files.endswith('.uvf'):
       			 shutil.move(os.path.join(sourcepath,files), os.path.join(destinationpath_uvf,files))
		if files.endswith('.mod'):
       			 shutil.move(os.path.join(sourcepath,files), os.path.join(destinationpath_models,files))
		if files.endswith('.fits'):
       			 shutil.move(os.path.join(sourcepath,files), os.path.join(destinationpath_fits,files))

	#store the uvf, mod and fits files of the maps in a list
	files = []
	for filename in sorted(glob.glob(path+'/UVF/*.uvf*')):   
		files.append(filename)   
			
	models = []
	for filename in sorted(glob.glob(path+'/MODELS/*.mod*')):   
		models.append(filename)  
		
	fits = []
	for filename in sorted(glob.glob(path+'/FITS/*.fits*')):   
		fits.append(filename)  
					
	#initialize arrays
	cell = np.array([0.]*len(fits))
	bmaj = np.array([0.]*len(fits))
	bmin = np.array([0.]*len(fits))
	bpa = np.array([0.]*len(fits))
	freq = np.array([0.]*len(fits))
	beam = np.array([0.]*len(fits))
	size_map = np.array([0.]*len(fits))
	size_map_y =np.array([0.]*len(fits))

	#order the the list by frequency and 
	#getting the corresponding values of the previous initialized arrays ordered by frequency 
	#(lower to higher)
	ordered_params = order_by_nu(files,models,fits,False)
	
	freqOrig = ordered_params[0]
	cell = ordered_params[1]
	bmaj = ordered_params[2]
	bmin = ordered_params[3]
	bpa = ordered_params[4]
	beam = ordered_params[5]
	size_map = ordered_params[6]
	size_map_y = ordered_params[7]
	files = ordered_params[8]
	models = ordered_params[9]
	fits = ordered_params[10]

	freq = freqOrig.copy()

	units = []

	for i in xrange(0,len(freq)):
		if freq[i] < 0.5:
			freq[i] = freq[i]*1000
			units.append('MHz')
		else:
			units.append('GHz')
	
	units = np.asarray(units)

	#source name
	header = take_header(fits[0],False)
	source_name = header[8]
	
	xshift = 0
	yshift = 0
Esempio n. 15
0
def conv_params(freq, cell, bmaj, bmin, bpa, beam, size_map, size_map_y, files,
                models, fits):

    #choose the number of frequencies for which the convolution is needed
    number = len(freq) + 1

    while number > len(freq):
        prompt = 'How many frequencies do you want to convolve with the same beam? \n'
        number = int(raw_input(prompt))

    #choose for which frequencies the convolucion will be done, and create the new list of files and models
    #initializing arrays
    files2conv = []
    models2conv = []
    files_out = []
    cell2conv = np.array([0.] * len(fits))
    bmajnew = np.array([0.] * len(fits))
    bminnew = np.array([0.] * len(fits))
    bpanew = np.array([0.] * len(fits))
    freq2conv = np.array([0.] * len(fits))
    beamnew = np.array([0.] * len(fits))
    size_map2conv = np.array([0.] * len(fits))
    size_map_y2conv = np.array([0.] * len(fits))

    #if a correct number of frequencies is given, select the ones to convolve by the position in the printed array
    #if they are less than the original array
    if number < len(freq):
        print 'The number of freq selected is smaller than the total'
        print 'Which frequencies?'
        print 'Please, select the position in the array. The first one is considered as zero'
        prompt = raw_input('Enter them separated by commas : \n')
        positions_list = prompt.split(',')
        positions = [int(x.strip()) for x in positions_list]

        print 'The frequencies to convolve are:\n'
        #add the values of the files,models,fits,cell, freq and size to the new arrays
        for i in xrange(0, len(positions)):
            index = positions[i]
            print 'Freq', i, ' ', freq[index]
            files2conv.append(files[index])
            models2conv.append(models[index])
            cell2conv[i] = cell[index]
            #bmajnew[i] = bmaj[index]
            #bminnew[i] = bmin[index]
            #bpanew[i] = bpa[index]
            freq2conv[i] = freq[index]
            #beamnew[i] = beam[index]
            size_map2conv[i] = size_map[index]
            size_map_y2conv[i] = size_map_y[index]

    #if the ones to convolve are all the ones in the original array
    else:
        files2conv = files
        models2conv = models
        cell2conv = cell
        #bmajnew = bmaj
        #bminnew = bmin
        #bpanew = bpa
        freq2conv = freq
        #beamnew = beam
        size_map2conv = size_map
        size_map_y2conv = size_map_y
        positions = freq  #just for checks later

    #choose the restoring beam
    track = False
    circ = False
    while track == False:
        prompt = raw_input(
            'Do you want to restore them with the beam of one of them?\n')
        var = str(prompt)
        if var == 'y':
            track = True
            print 'Select the frequency with the restoring beam you want to use'
            print 'Please, select the position in the first array.'
            prompt = raw_input('The first one is considered as zero \n')
            index = int(prompt)
            while circ == False:
                prompt = raw_input(
                    'Do you want to use the equivalent circular beam? (y/n)\n')
                circ_beam = str(prompt)
                if circ_beam == 'y':
                    circ = True
                    bmaj2conv = beam[index]
                    bmin2conv = beam[index]
                    bpa2conv = 0.
                elif circ_beam == 'n':
                    circ = True
                    bmaj2conv = bmaj[index]
                    bmin2conv = bmin[index]
                    bpa2conv = bpa[index]

        elif var == 'n':
            track = True
            print 'Select the restoring beam'
            prompt = raw_input('bmaj,bmin,bpa (do not forget the commas) \n')
            positions_list = prompt.split(',')
            beam_par = [float(x.strip()) for x in positions_list]
            bmaj2conv = beam_par[0]
            bmin2conv = beam_par[1]
            bpa2conv = beam_par[2]

    beam = np.sqrt(bmaj2conv * bmin2conv)

    header = take_header(fits[0])
    source_name = header[8]

    print 'bmaj = ', bmaj2conv, 'bmin = ', bmin2conv, 'bpa = ', bpa2conv

    #select the mapsize (mapsize of the low frequency image) and cellsize (half of the cellsize of the high frequency image)
    mapsize = 4 * size_map2conv[0]
    tracker = False
    for i in xrange(0, len(cell2conv)):
        if cell2conv[i] == 0. and tracker == False:
            index = i - 1
            tracker = True

    if tracker == False:
        index = len(cell2conv) - 1

    pixelsize = cell2conv[index]

    tofile = index

    print 'Mapsize = ', mapsize, 'cell = ', pixelsize

    change_map_track = False
    while change_map_track == False:
        prompt = raw_input('Do you wish to increase the mapsize? \n')
        change_map = str(prompt)
        if 'Y' in change_map or 'y' in change_map or 'n' in change_map:
            change_map_track = True
    if change_map == 'Y' or change_map == 'y':
        prompt = raw_input('Which mapsize? \n')
        mapsize = float(prompt)

    change_map_track = False
    while change_map_track == False:
        prompt = raw_input('Do you wish to increase the cellsize? \n')
        change_map = str(prompt)
        if 'Y' in change_map or 'y' in change_map or 'n' in change_map:
            change_map_track = True
    if change_map == 'Y' or change_map == 'y':
        prompt = raw_input('Which cellsize? \n')
        pixelsize = float(prompt)

    if len(positions) == len(freq):
        for i in xrange(0, len(positions)):
            files_out.append('CONV_ALL/' + source_name + '_' +
                             str(int(round(freq2conv[i]))) +
                             'convolved_with_beam' + str('%1.2f' % (beam)) +
                             'and_cell' + str('%1.3f' % (pixelsize)) + '.fits')
    else:
        for i in xrange(0, len(positions)):
            index = positions[i]
            files_out.append('CONV/' + source_name + '_' +
                             str(int(round(freq2conv[i]))) +
                             'convolved_with_beam' + str('%1.2f' % (beam)) +
                             'and_cell' + str('%1.3f' % (pixelsize)) + '.fits')

    #save convolution parameters to a pickle file
    final = [
        freq2conv, cell2conv, bmaj2conv, bmin2conv, bpa2conv, size_map2conv,
        size_map_y2conv, files2conv, models2conv, files_out, mapsize, pixelsize
    ]

    if tofile > 1:
        res = open(
            'convolve_param' + str(int(round(freq2conv[0]))) + 'to' +
            str(int(round(freq2conv[tofile]))) + '.p', 'wb')
        pickle.dump(final, res)
        res.close()
    else:
        res = open(
            'convolve_param' + str(int(round(freq2conv[0]))) + 'and' +
            str(int(round(freq2conv[tofile]))) + '.p', 'wb')
        pickle.dump(final, res)
        res.close()

    return freq2conv, cell2conv, bmaj2conv, bmin2conv, bpa2conv, size_map2conv, size_map_y2conv, files2conv, models2conv, files_out, mapsize, pixelsize