예제 #1
0
def fitModel(guess, gridParam, plot=False):
	if not guess is None:
		gridParam.modelParamA.teff = guess[0]
		gridParam.modelParamB.teff = guess[1]
		gridParam.modelParamB.fluxRatio = guess[2]
		gridParam.modelParamA.rv = guess[3]
		gridParam.modelParamB.rv = guess[4]
	
	ipf, ipg = ferre.Interpolator(lib='F'), ferre.Interpolator(lib='GK')
	componentA = bm.genComponent(gridParam.modelParamA, ipf, ipg)
	componentB = bm.genComponent(gridParam.modelParamB, ipf, ipg)
	componentBR = componentB * gridParam.modelParamB.fluxRatio
	componentAS = bm.shiftFlux(componentA, gridParam.modelParamA.rv)
	componentBS = bm.shiftFlux(componentBR, gridParam.modelParamB.rv)
	ipf.close()
	ipg.close()

	# Combine the flux as a binary
	binaryFlux = bm.combineFlux(componentAS, componentBS)

	# Make the plots
	if (plot == True):
		BinPlot.plotDeltaVCheck(gridParam, gridParam.visit, binaryFlux, 'Emcee Results', folder='emcee_deltaV')
		BinPlot.plotDeltaVCheck(gridParam, gridParam.visit, binaryFlux, 'Emcee Results', folder='emcee', range=None)

	gridParam.chi2 = calcChi2(binaryFlux, gridParam.spec, gridParam.specErr) / (len(binaryFlux) - 5.0)
	return -1.0 * gridParam.chi2
예제 #2
0
def binaryModelGen(locationID, apogeeID, params, visit, ipf=None, ipg=None, plot=True):
	'''
	Interpolates the spectra of the individual stars in the binary using some initial parameters and their velocity
	difference.

	:param locationID: The location ID of the binary.
	:param apogeeID: The apogee ID of the binary.
	:param params: The paramters to test against the observed data.
		format: [ [Teff1, ...], [logg1, ...], [metals1, ...], [am1, ...], [nm1, ...], [cm1, ...]]
	:param visit: The visit to test against.
	:param ip: The interpolator instance that keeps running ferre. Should be faster to keep using this instead. (default=None)
	:param plot: If true plots each component in the binary in 'plots/model_gen' (default=True)
	:returns: The binary model flux and the maximum value from the cross correlation function between the modeled
	totalFlux and the continuum-normalized spectrum. (totalFlux, max)
	'''
	# Generate models (flux1, flux2)
	if (np.logical_and(ipf == None, ipg == None)):
		# todo: put in condition for both gk and f libraries
		mspecs = ferre.interpolate(params[0], params[1], params[2],	params[3], params[4], params[5])
	else:
		if (params[0][0] > 6000.):
			mspec1 = ipf(params[0][0], params[1][0], params[2][0], params[3][0], params[4][0], params[5][0])
		else:
			mspec1 = ipg(params[0][0], params[1][0], params[2][0], params[3][0], params[4][0], params[5][0])
		if (params[0][1] > 6000.):
			mspec2 = ipf(params[0][1], params[1][1], params[2][1], params[3][1], params[4][1], params[5][1])
		else:
			mspec2 = ipg(params[0][1], params[1][1], params[2][1], params[3][1], params[4][1], params[5][1])
		
		mspecs = [ mspec1, mspec2 ]
	
	for mspec in mspecs:
		mspec[np.isnan(mspec)] = 0.
	
	# Calculate deltaV
	RVs = getRVs(locationID, apogeeID, visit)
	
	# Generate the wavelength grid
	restLambda = splot.apStarWavegrid()
	# Calculates wavelength grid for the second star with a doppler shift
	shiftLambda = [restLambda * (1. + rv / (const.c / 1000.)) for rv in RVs]
	
	# The fluxes of both stars
	shiftedFlux = np.array([np.interp(restLambda, shiftLambda[i], mspecs[i]) for i in range(len(shiftLambda))])

	# The combined flux of the stars in the modeled binary (params[7][1] defined as flux ratio)
	totalFlux = (shiftedFlux[0] + (shiftedFlux[1] * params[6][1])) / 2.0

	# Make the plots
	if (plot == True):
		BinPlot.plotDeltaVCheck(locationID, apogeeID, visit,
						[[ restLambda, mspecs[0], 'blue', 'rest model specA' ],
						 [ restLambda, mspecs[1], 'green', 'rest model specB' ],
						 [ restLambda, shiftedFlux[0], 'orange', 'shift model specA' ],
						 [ restLambda, shiftedFlux[1], 'purple', 'shift model specB' ]],
						[params[0][0], params[0][1]], 'Binary Model Gen - Prelim. Proc.', folder='model_gen');

	return totalFlux
예제 #3
0
            # Heliocentric velocity (km/s) of visit 1
            helioV = header["VHELIO" + str(visit)]
            alpha = header["CDELT1"]

            velocityShift = 10.0 ** (alpha * pixelShift) - 1.0  # + helioV
            # Calculates wavelength grid for the second star with a doppler shift
        shiftLambda = restLambda * (1.0 + velocityShift / (const.c / 1000.0))

        # The flux of the model
        shiftedFlux = np.interp(restLambda, shiftLambda, mspecs[0])

        BinPlot.plotCOMPCCF(
            locationID,
            apogeeID,
            visit,
            velocityShift,
            [[ccfs[0], "green", "approx Teff"], [ccfs[1], "blue", "Hot Teff"], [ccfs[2], "orange", "Cool Teff"]],
            params,
            "",
            folder="comparison_CCF",
        )
        BinPlot.plotCOMPCCF(
            locationID,
            apogeeID,
            visit,
            header["VRAD" + str(visit)],
            [[ccf, "blue", "Off. CCF"]],
            params,
            "",
            folder="comparison_CCF_OFF",
        )
예제 #4
0
def targetGrid(gridParam, minimizedVisitParams, plot=True):
	'''
	The grid tests against ranging effective temperatures for both stars and the flux ratio of the
	secondary component. This is done by target.

	:param gridParam: [in/out] The GridParam of the target
	:param gridRes: [out] The visits that have the same paramters as the minimized chi2 visit
	:param plot: [in] If true makes plots to see intermediate steps (default=True)
	'''
	locationID = gridParam.locationID
	apogeeID = gridParam.apogeeID

	badheader, header = apread.apStar(locationID, apogeeID, ext=0, header=True)
	specs = apread.apStar(locationID, apogeeID, ext=1, header=False)
	specerrs = apread.apStar(locationID, apogeeID, ext=2, header=False)
	nvisits = header['NVISITS']
	
	# chi2 = np.full((nvisits, nrangeTeffA, nrangeTeffB, nrangeFluxRatio), -1.)
	#chi2 = np.full((nvisits, nrangeTeffA, nrangeTeffB, nrangeFluxRatio, nrangeRVA, nrangeRVB), -1.)
	ipg = ferre.Interpolator(lib='GK')
	ipf = ferre.Interpolator(lib='F')

	# Create file to store all the chi2 values
	path = 'lists/all_chi2/' + str(locationID) + '/'
	if not os.path.exists(path):
		os.makedirs(path)
	fn = open(path + apogeeID + '.lis', 'w')
	fn.write(gridParam.toStringHeader())
	timer = Timer()
	timeSum = 0.0
	allChi2 = []
	visitGridParamsBuffer = []
	for visit in range(1, nvisits + 1):
		timer.start()
		if (nvisits != 1):
			spec = specs[1+visit]
			specerr = specerrs[1+visit]
		else:
			spec = specs
			specerr = specerrs
		
		if (len(minimizedVisitParams) == 0):
			gridParam = GridParam(locationID, apogeeID)
			gridParam.constructParams()
			gridParam.getRVs(visit)
		else:
			gridParam = minimizedVisitParams[visit - 1]
		visitGridParamsBuffer.append(gridParam)
		
		# Prepare grid ranges
		rangeTeffA = np.arange(gridParam.minTeffA, gridParam.maxTeffA, gridParam.teffStepA)
		rangeTeffB = np.arange(gridParam.minTeffB, gridParam.maxTeffB, gridParam.teffStepB)
		rangeFluxRatio = np.arange(gridParam.minFluxRatio, gridParam.maxFluxRatio, gridParam.fluxStep)
		rangeRVA = np.arange(gridParam.minRVA, gridParam.maxRVA, gridParam.rvAStep)
		rangeRVB = np.arange(gridParam.minRVB, gridParam.maxRVB, gridParam.rvBStep)
		nrangeTeffA = len(rangeTeffA)
		nrangeTeffB = len(rangeTeffB)
		nrangeFluxRatio = len(rangeFluxRatio)
		nrangeRVA =len(rangeRVA)
		nrangeRVB =len(rangeRVB)

		chi2 = np.full((nrangeTeffA, nrangeTeffB, nrangeFluxRatio, nrangeRVA, nrangeRVB), -1.)
		print('Visit: ' + str(visit) ,'Grid dimensions: ' + str(chi2.shape))
		# Prep Spectra
		aspec= np.reshape(spec,(1, len(spec)))
		aspecerr= np.reshape(specerr,(1, len(specerr)))
		cont= spec / continuum.fit(aspec, aspecerr, type='aspcap')[0]
		conterr = specerr / continuum.fit(aspec, aspecerr, type='aspcap')[0]
		shiftedSpec = bm.shiftFlux(cont, header['VHELIO' + str(visit)])

		# Run grid
		for i in range(nrangeTeffA):
			gridParam.modelParamA.teff = rangeTeffA[i]
			componentA = bm.genComponent(gridParam.modelParamA, ipf, ipg)
			for j in range(nrangeTeffB):
				gridParam.modelParamB.teff = rangeTeffB[j]
				componentB = bm.genComponent(gridParam.modelParamB, ipf, ipg)
				for k in range(nrangeFluxRatio):
					gridParam.modelParamB.fluxRatio = rangeFluxRatio[k]
					componentBR = componentB * rangeFluxRatio[k]
					for l in range(nrangeRVA):
						gridParam.modelParamA.rv = rangeRVA[l]
						componentAS = bm.shiftFlux(componentA, rangeRVA[l])
						for m in range(nrangeRVB):
							gridParam.modelParamB.rv = rangeRVB[m]
							componentBS = bm.shiftFlux(componentBR, rangeRVB[m])
							binaryFlux = bm.combineFlux(componentAS, componentBS)
							chi2[i][j][k][l][m] = calcChi2(binaryFlux, shiftedSpec, conterr) / (len(binaryFlux) - 5.0)
							gridParam.chi2 = chi2[i][j][k][l][m]
							fn.write(gridParam.toString())
							if (plot is True):
								restLambda = splot.apStarWavegrid()
								BinPlot.plotDeltaVCheck(locationID, apogeeID, visit,
													[	[ restLambda, binaryFlux, 'blue', 'model' ],
														[ restLambda, cont, 'orange', 'unshifted' ],
														[ restLambda, shiftedSpec, 'green', 'shifted' ]],
														[gridParam.modelParamA.teff,gridParam.modelParamB.teff, gridParam.modelParamB.fluxRatio],
														'Delta V Shift', folder='grid_deltaVCheck')

		timeSum+=timer.end()
		allChi2.append(chi2)
	fn.close()

	print('Average visit time: ' + str(round(timeSum/nvisits, 2)) + str('s'))

	# Get minized values for each visit
	indices = None
	for i in range(nvisits):
		inds = getMinIndicies(allChi2[i])
		rangeTeffA = np.arange(visitGridParamsBuffer[i].minTeffA, visitGridParamsBuffer[i].maxTeffA, visitGridParamsBuffer[i].teffStepA)
		rangeTeffB = np.arange(visitGridParamsBuffer[i].minTeffB, visitGridParamsBuffer[i].maxTeffB, visitGridParamsBuffer[i].teffStepB)
		rangeFluxRatio = np.arange(visitGridParamsBuffer[i].minFluxRatio, visitGridParamsBuffer[i].maxFluxRatio, visitGridParamsBuffer[i].fluxStep)
		rangeRVA = np.arange(visitGridParamsBuffer[i].minRVA, visitGridParamsBuffer[i].maxRVA, visitGridParamsBuffer[i].rvAStep)
		rangeRVB = np.arange(visitGridParamsBuffer[i].minRVB, visitGridParamsBuffer[i].maxRVB, visitGridParamsBuffer[i].rvBStep)
		nrangeTeffA = len(rangeTeffA)
		nrangeTeffB = len(rangeTeffB)
		nrangeFluxRatio = len(rangeFluxRatio)
		nrangeRVA =len(rangeRVA)
		nrangeRVB =len(rangeRVB)
		visitGridParamsBuffer[i].setParams(i + 1, rangeTeffA[inds[0]], rangeTeffB[inds[1]], rangeFluxRatio[inds[2]],
					rangeRVA[inds[3]], rangeRVB[inds[4]], allChi2[i][inds[0]][inds[1]][inds[2]][inds[3]][inds[4]])

		if (indices is None):
			indices = [i + 1, inds, allChi2[i][inds[0]][inds[1]][inds[2]][inds[3]][inds[4]]]
		if (allChi2[i][inds[0]][inds[1]][inds[2]][inds[3]][inds[4]] < indices[2]):
			indices = [i + 1, inds, allChi2[i][inds[0]][inds[1]][inds[2]][inds[3]][inds[4]]]
	
	inds = getMinIndicies(allChi2)
	gridParam = visitGridParamsBuffer[inds[0]]
	return gridParam, visitGridParamsBuffer
예제 #5
0
spec = apread.apStar(locationID, apogeeID, ext=1, header=False)[1 + visit]
specerr = apread.apStar(locationID, apogeeID, ext=2, header=False)[1 + visit]
# plt.plot(restLambda, spec)

aspec = np.reshape(spec, (1, len(spec)))
aspecerr = np.reshape(specerr, (1, len(specerr)))
cont = spec / continuum.fit(aspec, aspecerr, type="aspcap")[0]
conterr = specerr / continuum.fit(aspec, aspecerr, type="aspcap")[0]
shiftedSpec = bm.shiftFlux(cont, header["VHELIO" + str(visit)])
conterr = bm.shiftFlux(cont, header["VHELIO" + str(visit)])
BinPlot.plotDeltaVCheck(
    locationID,
    apogeeID,
    visit,
    [[restLambda, cont, "blue", "Data"]],
    [gridParam.modelParamA.teff, gridParam.modelParamB.teff],
    "",
    folder="model_gen",
)
# plt.plot(restLambda, cont)
# plt.show()
ipg = ferre.Interpolator(lib="GK")
ipf = ferre.Interpolator(lib="F")

componentA = bm.genComponent(gridParam.modelParamA, ipf, ipg)
componentB = bm.genComponent(gridParam.modelParamB, ipf, ipg)
"""BinPlot.plotDeltaVCheck(locationID, apogeeID, visit,
						[[restLambda, componentA, 'blue'],
						 [restLambda, componentB, 'orange']],
						[gridParam.modelParamA.teff, gridParam.modelParamB.teff], '', folder='model_gen')"""