def test_seds(err=0.1, Av0=1., Z0=0.02):
	import grid
	#filters  = 'hst_wfc3_f225w hst_wfc3_f336w hst_acs_hrc_f475w hst_acs_hrc_f814w hst_wfc3_f110w hst_wfc3_f160w'.upper().split()


	#osl = stellib.BaSeL()
	oAv = extinction.Cardelli()
	g = grid.FileSpectralGrid('libs/SEDs_basel_padovaiso.fits')
	lamb = g.lamb#*1e6


	#fake DATA
	fakein, l, fakesed, fakeerr = getFake(g, Av0, 3.1, err=err)

	mask = numpy.zeros(fakesed.shape, dtype=bool)
	mask[3] = True
	mask[2] = True

	Av = numpy.arange(0.,3., 0.1)	
	r = numpy.empty( (g.seds.shape[0], len(Av)), dtype=float )
	with timeit('Likelihood'):
		for k in range(len(Av)):
			r[:, k] = job(lamb[:], numpy.copy(fakesed), numpy.copy(fakeerr), mask, numpy.copy(g.seds), oAv, Av=Av[k], Rv=3.1) 

	return g,r, Av, fakein, lamb, fakesed, fakeerr, Av0, Z0
def generate_spectral_grid_from_isochrones(outfile, osl, oiso, Z=0.02):
	""" Reinterpolate a given stellar spectral library on to an Isochrone grid
	INPUTS:
		outfile		str		   	fits file to export to
		osl		stellib.stellib		a stellar library
		oiso		isochrone.Isochrone	an isochrone library
		Z		float			metallicity to use
	
	OUTPUTS:
		None

		only write into outfile
	"""
	
	assert(isNestedInstance(osl, stellib.Stellib) )
	assert(isNestedInstance(oiso, isochrone.Isochrone) )
	specs = numpy.empty( (oiso.data.nrows+1, len(osl.wavelength)), dtype=float )
	specs[-1] = osl.wavelength[:]

	progress = 0
	with timeit('interpolation'):
		for k in range(oiso.data.nrows):
			if progress < int(100*(k+1)/oiso.data.nrows):
				progress = int(100*(k+1)/oiso.data.nrows)
				print "progress... %d / 100" % progress
			r = numpy.array( osl.interp(oiso.data['logT'][k], oiso.data['logg'][k], Z, oiso.data['logL'][k]) ).T
			specs[k,:] = osl.genSpectrum(r)
	pyfits.writeto(outfile, specs)

	#copy pars
	data = {}
	for k in oiso.data.keys():
		data[k] = oiso.data[k]
	pars  = mytables.Table(data, name='Reinterpolated stellib grid')
	pars.header['stellib'] = osl.source
	pars.header['isoch'] = oiso.source

	pars.write(outfile, append=True)
def test_specs():
	osl = stellib.BaSeL()
	oAv = extinction.Cardelli()
	#fake DATA
	#fakein  = 2000 # random between 0 & 4523, no idea what this is :p
	idx      = osl.grid.where('(Teff >= 3.6) & (Teff <= 3.8) & (logG >= 4.5) & (logG <= 4.7) & (Z == 0.02)')
	fakein   = idx[0][0]
	fakesed  = numpy.copy(osl.spectra[fakein,:])
	Av0      = 0.1
	lamb     = osl.wavelength
	tau      = getFluxAttenuation(oAv, lamb, Av = Av0, Rv = 3.1)
	fakesed *= exp(-tau)
	#magerr  = 0.05
	#fakeerr = fakesed * (1. - 10**(-0.4*magerr) ) 
	fakeerr = 0.5 * fakesed

	#get Models
	# will be replaced by broad-band SEDs but structure will be identical
	seds = numpy.copy(osl.spectra)
	#idx = osl.grid.where('(Z == 0.02)')
	#seds = osl.spectra[idx]
	lamb = osl.wavelength

	Av = numpy.arange(0,1,0.1)	
	r = numpy.empty( (seds.shape[0], len(Av)), dtype=float )
	with timeit('Likelihood'):
		for k in range(len(Av)):
			r[:, k] = job(lamb, fakesed, fakeerr, seds, oAv, Av=Av[k], Rv=3.1) 
	

	def plot(_r, idx=None):
		import pylab as plt
		if _r.ndim == 2:
			r = _r.sum(1)
		else:
			r = _r
		if idx == None:
			idx = numpy.arange(len(r))
		n0, bT, bg = numpy.histogram2d(osl.Teff[idx], osl.logg[idx], bins=[25,11])
		n , bT, bg = numpy.histogram2d(osl.Teff[idx], osl.logg[idx], bins=[bT,bg], weights=exp(r) )

		n0 = n0.astype(float)/n0.sum()
		n  = n.astype(float)/n.sum()
		n1 = numpy.copy(n[:])

		ind =  n0 > 0. 
		n[ind] /= n0[ind]

		n /= n.sum()

		n1 = numpy.ma.masked_where( n0 == 0, n1 )
		n  = numpy.ma.masked_where( n0 == 0, n  )

		plt.figure(1, figsize=(10,10))
		plt.clf()
		
		ax0 = plt.subplot(221)
		ax0.imshow(n1.T, extent=[min(bT), max(bT), min(bg), max(bg)], 
				vmin=0., vmax=numpy.max([n1.max(),n.max()]), 
				origin='lower', aspect='auto')
		ax0.plot([osl.Teff[fakein]], [osl.logg[fakein]], 'o', mec='#ff0000', mfc='None', mew=2., ms=10.)
		ax0.set_xlabel('logT')
		ax0.set_ylabel('logg')
		ax0.set_xlim(ax0.get_xlim()[::-1])
		ax0.set_ylim(ax0.get_ylim()[::-1])
		ax0.set_title('Raw: P0(logT,logg) = K')

		ax1 =plt.subplot(222, sharex=ax0, sharey=ax0)
		ax1.imshow(n.T, extent=[min(bT), max(bT), min(bg), max(bg)], 
				vmin=0., vmax=numpy.max([n1.max(),n.max()]), 
				origin='lower', aspect='auto')
		ax1.plot([osl.Teff[fakein]], [osl.logg[fakein]], 'o', mec='#ff0000', mfc='None', mew=2., ms=10.)
		ax1.set_xlabel('logT')
		ax1.set_ylabel('logg')
		ax1.set_xlim(ax1.get_xlim()[::-1])
		ax1.set_ylim(ax1.get_ylim()[::-1])
		ax1.set_title('Corrected: P/P0(logT,logg) = K')
		
		ax2 =plt.subplot(223)
		x = 0.5*(bT[1:]+bT[:-1])
		#ax2.step( bT[:-1], n1.sum(1), where='pre', lw=2.)
		#ax2.step( bT[:-1], n.sum(1),  where='pre', lw=2.)
		ax2.plot( x, n1.sum(1), lw=2., label='raw')
		ax2.plot( x, n.sum(1),  lw=2., label='cor')
		ylim = ax2.get_ylim()
		ax2.vlines([osl.Teff[fakein]], ylim[0],ylim[1])
		ax2.set_ylim(ylim)
		ax2.set_xlabel('log(Teff)')
		ax2.set_ylabel(r'P( data $\mid$ log(Teff) ) P(Teff) / P0(log(Teff))')
		ax2.legend(loc=0, frameon=False, borderaxespad=2., prop={'size':14})


		ax3 = plt.subplot(224)
		x = 0.5*(bg[1:]+bg[:-1])
		#ax3.step( bg[:-1], n1.sum(0), where='pre', lw=2.)
		#ax3.step( bg[:-1], n.sum(0),  where='pre', lw=2.)
		ax3.plot( x, n1.sum(0), lw=2.)
		ax3.plot( x, n.sum(0),  lw=2.)
		ylim = ax3.get_ylim()
		ax3.vlines([osl.logg[fakein]], ylim[0],ylim[1])
		ax3.set_ylim(ylim)
		ax3.set_xlabel('log(g)')
		ax3.set_ylabel(r'P( data $\mid$ log(g) ) P(log(g)) / P0(log(g))')

		figure.theme(ax=ax0)
		figure.theme(ax=ax1)
		figure.theme(ax=ax2)
		figure.theme(ax=ax3)

	plot(r)
	return r