Exemplo n.º 1
0
    def test_fit(self):
        args = (self.x, self.y, self.error)
        p, result = mpyfit.fit(self.func, self.p, args)

        dof = result['nfunc'] - result['nfree']
        self.assertEqual(result['status'][0], 1)
        self.assertEqual(dof, 7)
        self.assertTrue(abs(p[0] - self.pactual[0]) < result['parerrors'][0])
        self.assertFalse(abs(p[1] - self.pactual[1]) < result['parerrors'][1])
        self.assertTrue(abs(p[2] - self.pactual[2]) < result['parerrors'][2])
 def mpfitter(self):
     #m = mpfit(self.mpfit_model, self.initpar, parinfo=self.parinfo, xtol=1e-8, quiet=True)
     pfit, results = mpyfit.fit(self.mpfit_model, self.initpar, parinfo=self.parinfo, maxiter=50, xtol=1e-8, ftol=1e-8)
     model = self.model(pfit)
     self.par = pfit
     self.mod = model
     self.resid = self.obchunk - model
     dof = len(self.obchunk) - len(self.par)
     self.chi = np.sqrt(np.sum(self.resid**2/self.obchunk)/dof)
     return model, pfit
Exemplo n.º 3
0
    def test_fit(self):
        args = (self.x, self.y, self.error)
        p, result = mpyfit.fit(self.func, self.p, args)

        dof = result['nfunc'] - result['nfree']
        self.assertEqual(result['status'][0], 1)
        self.assertEqual(dof, 7)
        self.assertTrue(abs(p[0] - self.pactual[0]) < result['parerrors'][0])
        self.assertFalse(abs(p[1] - self.pactual[1]) < result['parerrors'][1])
        self.assertTrue(abs(p[2] - self.pactual[2]) < result['parerrors'][2])
    def mpfitter(self):
        #m = mpfit(self.mpfit_model, self.initpar, parinfo=self.parinfo, xtol=1e-8, quiet=True)

        pfit, results = mpyfit.fit(self.mpfit_model, self.initpar, parinfo=self.parinfo, maxiter=500, xtol=1e-9, ftol=1e-9) 
        model = self.model(pfit)
        self.par = pfit[:]
        self.mod = model[:,:]
        good = np.where(self.active)
        self.resid = self.obchunk[good,:][0] - model
        npar = len(self.par)
        dim = self.obchunk.shape
        ntel = dim[0]
        npix = dim[1]
        dof = npix - self.parspertrace # neglects any fixed parameters!
#        dofpertrace = npix - npar
#        self.chiarr = np.sqrt(np.sum((self.resid)**2/self.mod, axis=1) / dofpertrace)
#        bad = np.where(self.chiarr > 3)
        """
        if bad[0]:
            nbad = len(bad[0])
            for i in range(nbad):
                print bad[0][i], 'is bad'
        """
        sigmasq = self.obchunk[good,:][0] # sigma = sqrt(Ncts), sigma^2 = Ncts
        # ignores sky noise, read noise, flat fielding...

        # mask bad values
        bad = np.where(sigmasq == 0.0)
        sigmasq[bad] = float('inf')

        chisq = np.sum(self.resid**2/sigmasq,axis=1)

        if len(np.where(np.isnan(chisq))[0]) != 0: ipdb.set_trace()

        redchi = chisq/dof
        self.chisq = chisq[:]
        self.redchi = redchi[:]
        self.chi = np.sqrt(redchi) # sqrt(chi^2) =~ number of sigmas 

        wav = np.append(np.append(-1, self.xchunk), 1) * pfit[2] + pfit[1]
        dV = np.median(wav - np.roll(wav,-1))/wav * self.c
        if self.bstar:
            self.weight = np.zeros(self.ntel)
        else:
            self.weight = np.array([])
            tel = 0
            for i in range(ntel):
                if not self.active[i]: continue
                I = self.tempinterp[tel](wav)
                dI = I - np.roll(I, -1)
                dIdV = dI[1:len(wav)-1]/dV[1:len(wav)-1]
                sigmaV = 1.0 / np.sqrt(np.sum(dIdV**2 / I[1:len(wav)-1]))
                self.weight = np.append(self.weight, 1.0/sigmaV**2)
                tel += 1
        return model, pfit
Exemplo n.º 5
0
    def test_frozen(self):
        args = (self.x, self.y, self.error)
        # Fix the second term
        parinfo = [{}, {'fixed': True}, {}]
        self.p[1] = 0
        p, result = mpyfit.fit(self.func, self.p, args=args, parinfo=parinfo)

        dof = result['nfunc'] - result['nfree']
        self.assertEqual(result['status'][0], 1)
        self.assertEqual(dof, 8)
        self.assertTrue(abs(p[0] - self.pactual[0]) < result['parerrors'][0])
        self.assertEqual(p[1], 0.0)
        self.assertTrue(abs(p[2] - self.pactual[2]) < result['parerrors'][2])
Exemplo n.º 6
0
    def test_frozen(self):
        args = (self.x, self.y, self.error)
        # Fix the second term
        parinfo = [{}, {'fixed': True}, {}]
        self.p[1] = 0
        p, result = mpyfit.fit(self.func, self.p, args=args, parinfo=parinfo)

        dof = result['nfunc'] - result['nfree']
        self.assertEqual(result['status'][0], 1)
        self.assertEqual(dof, 8)
        self.assertTrue(abs(p[0] - self.pactual[0]) < result['parerrors'][0])
        self.assertEqual(p[1], 0.0)
        self.assertTrue(abs(p[2] - self.pactual[2]) < result['parerrors'][2])
Exemplo n.º 7
0
def fitFunction(x, components):
    # Do the fitting
    print "Fitting using mpyfit..."
    keys = sort(components.keys())
    func_list = [components[key].func for key in keys]
    p0_list = [components[key].params for key in keys]
    p0_len_list = [len(components[key].params) for key in keys]
    prior_list = [components[key].prior for key in keys]
    fixed_list = [components[key].fixed for key in keys]

    p0 = reduce(lambda x, y: x + y, p0_list)
    priors = reduce(lambda x, y: x + y, prior_list)
    fixed = reduce(lambda x, y: x + y, fixed_list)
    limited = [[True, True]] * len(p0)

    tied = [False] * len(p0)
    tied[19] = "3 * p[16]"

    parinfo = [{} for i in range(len(p0))]
    for i in range(len(p0)):
        parinfo[i]['limited'] = tuple(limited[i])
        parinfo[i]['limits'] = tuple(priors[i])
        parinfo[i]['fixed'] = fixed[i]
        parinfo[i]['tied'] = tied[i]

    p0new = []
    i_counter = 0
    for i in range(len(fixed)):
        if not fixed[i]:
            p0new.append(p0[i])
            i_counter += 1

    pfit, results = mpyfit.fit(deviates, p0new,
                               (x[:, 0], x[:, 1], buildFunction, components))

    pfit_complete = []
    i_counter = 0
    for i in range(len(fixed)):
        if fixed[i]:
            pfit_complete.append(p0[i])
        else:
            pfit_complete.append(pfit[i_counter])
            i_counter += 1
    pfit = pfit_complete

    # Put back into dictionary form
    pbest = {}
    for j in range(len(keys)):
        pbest[keys[j]] = pfit[sum(p0_len_list[k] for k in range(j)):sum(
            p0_len_list[k] for k in range(j + 1))]
    return pbest, results
    def mpfitter(self):
        # m = mpfit(self.mpfit_model, self.initpar, parinfo=self.parinfo, xtol=1e-8, quiet=True)
        pfit, results = mpyfit.fit(
            self.mpfit_model, self.initpar, parinfo=self.parinfo, maxiter=5000, xtol=1e-12, ftol=1e-12
        )
        model = self.model(pfit)
        self.par = pfit
        self.mod = model
        self.resid = self.obchunk - model
        npar = len(self.par)
        dim = self.obchunk.shape
        ntel = dim[0]
        npix = dim[1]
        dof = npix - self.parspertrace  # neglects any fixed parameters!
        #        dofpertrace = npix - npar
        #        self.chiarr = np.sqrt(np.sum((self.resid)**2/self.mod, axis=1) / dofpertrace)
        #        bad = np.where(self.chiarr > 3)
        """
        if bad[0]:
            nbad = len(bad[0])
            for i in range(nbad):
                print bad[0][i], 'is bad'
        """
        sigmasq = self.obchunk  # sigma = sqrt(Ncts), sigma^2 = Ncts

        # mask bad values
        bad = np.where(sigmasq == 0.0)
        sigmasq[bad] = float("inf")

        chisq = np.sum(self.resid ** 2 / sigmasq, axis=1)

        if len(np.where(np.isnan(chisq))[0]) != 0:
            ipdb.set_trace()

        redchi = chisq / dof
        self.chisq = chisq
        self.redchi = redchi
        self.chi = np.sqrt(redchi)  # sqrt(chi^2) =~ number of sigmas
        wav = np.append(np.append(-1, self.xchunk), 1) * pfit[2] + pfit[1]
        dV = np.median(wav - np.roll(wav, -1)) / wav * self.c
        if self.bstar:
            self.weight = np.zeros(self.ntel)
        else:
            for i in range(ntel):
                I = self.tempinterp[i](wav)
                dI = I - np.roll(I, -1)
                dIdV = dI[1 : len(wav) - 1] / dV[1 : len(wav) - 1]
                sigmaV = 1.0 / np.sqrt(np.sum(dIdV ** 2 / I[1 : len(wav) - 1]))
                self.weight[i] = 1.0 / sigmaV ** 2
        return model, pfit
Exemplo n.º 9
0
    def test_freeze(self):
        self.p[2] = 0
        self.p[3] = 0.1
        parinfo = [{'fixed': True}, {}, {'fixed': True}, {}]

        args = (self.x, self.y, self.error)
        p, result = mpyfit.fit(self.func, self.p, args, parinfo=parinfo)

        dof = result['nfunc'] - result['nfree']
        self.assertEqual(result['status'][0], 1)
        self.assertEqual(result['nfunc'] - result['nfree'], 8)
        self.assertEqual(p[0], 0.0)
        self.assertTrue(abs(p[1] - self.pactual[1]) < 1.5*result['parerrors'][1])
        self.assertEqual(p[2], 0.0)
        self.assertTrue(abs(p[3] - self.pactual[3]) < result['parerrors'][3])
Exemplo n.º 10
0
    def test_freeze(self):
        self.p[2] = 0
        self.p[3] = 0.1
        parinfo = [{'fixed': True}, {}, {'fixed': True}, {}]

        args = (self.x, self.y, self.error)
        p, result = mpyfit.fit(self.func, self.p, args, parinfo=parinfo)

        dof = result['nfunc'] - result['nfree']
        self.assertEqual(result['status'][0], 1)
        self.assertEqual(result['nfunc'] - result['nfree'], 8)
        self.assertEqual(p[0], 0.0)
        self.assertTrue(
            abs(p[1] - self.pactual[1]) < 1.5 * result['parerrors'][1])
        self.assertEqual(p[2], 0.0)
        self.assertTrue(abs(p[3] - self.pactual[3]) < result['parerrors'][3])
Exemplo n.º 11
0
def clipfitline(t, f, jumpspot, niter=5, nojump=False):
    qwe = np.where(t > -np.inf)[0]

    line = np.polyfit(t[qwe], f[qwe], 2)

    left = np.where(t < jumpspot)[0]
    right = np.where(t > jumpspot)[0]
    #pdb.set_trace()
    ssssss = np.nanmedian(f[right]) - np.nanmedian(f[left])
    pstart = np.array([line[0], line[1], line[2], 0.001, jumpspot])
    lerr = np.nanmedian(np.absolute(f[qwe] - np.polyval(line, t[qwe])))
    smod, sres = mdump_line(pstart, (t[qwe], f[qwe], f[qwe] * 0.0 + lerr),
                            model=True)

    parinfo2 = [{
        'fixed': False,
        'limits': (None, None),
        'step': 0.001
    } for dddd in range(pstart.shape[0])]
    parinfo2[4]['fixed'] = True
    if nojump == True:
        pstart[3] = 0.000
        parinfo2[3]['fixed'] = True

    for j in range(5):
        smod, sres = mdump_line(pstart, (t[qwe], f[qwe], f[qwe] * 0.0 + lerr),
                                model=True)

        llpars, llext = mpyfit.fit(mdump_mod,
                                   pstart,
                                   args=(t[qwe], f[qwe], f[qwe] * 0.0 + lerr),
                                   parinfo=parinfo2)
        lmod, lres = mdump_mod(llpars, (t[qwe], f[qwe], f[qwe] * 0.0 + lerr),
                               model=True)
        lmad = np.nanmedian(np.absolute(f[qwe] - lmod))
        keep = np.where((np.absolute(lmod - f[qwe]) / lmad < 10.0))[0]
        if j < niter - 1: qwe = qwe[keep]
        pstart = llpars
        lerr = lmad

    ##give the full model:
    ##recalculate lres
    #lmod,lres=mdump_mod(llpars,(t[qwe],f[qwe],f[qwe]*0.0+lerr),model=True)
    themodel, dummy = mdump_mod(llpars, (t, f, f * 0.0 + lerr), model=True)
    #pdb.set_trace()
    return t, themodel, lres, qwe, llpars, lerr
Exemplo n.º 12
0
    def test_limit(self):
        self.p[2] = 0
        self.p[3] = 0.1
        parinfo = [{'fixed': True}, {}, {'fixed': True},
                   {'limits': (-0.2, 0.3)}]

        args = (self.x, self.y, self.error)
        p, result = mpyfit.fit(self.func, self.p, args, parinfo=parinfo)

        dof = result['nfunc'] - result['nfree']
        self.assertEqual(result['status'][0], 1)
        self.assertEqual(result['nfunc'] - result['nfree'], 8)
        self.assertEqual(p[0], 0.0)
        self.assertEqual(result['parerrors'][0], 0)
        self.assertAlmostEqual(p[1], 5.533173)
        self.assertAlmostEqual(result['parerrors'][1], 0.3395397)
        self.assertEqual(p[2], 0.0)
        self.assertEqual(result['parerrors'][2], 0)
        self.assertTrue(p[3] >= -0.2 and p[3] <= 0.3)
Exemplo n.º 13
0
    def test_fit(self):
        x = numpy.array([-1.7237128E+00,1.8712276E+00,-9.6608055E-01,
                         -2.8394297E-01,1.3416969E+00,1.3757038E+00,
                         -1.3703436E+00,4.2581975E-02,-1.4970151E-01,
                         8.2065094E-01])
        y = numpy.array([1.9000429E-01,6.5807428E+00,1.4582725E+00,
                         2.7270851E+00,5.5969253E+00,5.6249280E+00,
                         0.787615,3.2599759E+00,2.9771762E+00,
                         4.5936475E+00])
        error = 0.07 * numpy.ones(x.shape)
        p = [1.0, 1.0]
        pactual = [3.20, 1.78]

        args = (x, y, error)
        p, result = mpyfit.fit(self.func, p, args)

        dof = result['nfunc'] - result['nfree']
        self.assertEqual(dof, 8)
        self.assertEqual(result['status'][0], 1)
        self.assertAlmostEqual(result['bestnorm'], 2.756285)
        self.assertTrue(abs(p[0] - pactual[0]) < result['parerrors'][0])
        self.assertTrue(abs(p[1] - pactual[1]) < result['parerrors'][1])
Exemplo n.º 14
0
    def test_fit(self):
        x = numpy.array([
            -1.7237128E+00, 1.8712276E+00, -9.6608055E-01, -2.8394297E-01,
            1.3416969E+00, 1.3757038E+00, -1.3703436E+00, 4.2581975E-02,
            -1.4970151E-01, 8.2065094E-01
        ])
        y = numpy.array([
            1.9000429E-01, 6.5807428E+00, 1.4582725E+00, 2.7270851E+00,
            5.5969253E+00, 5.6249280E+00, 0.787615, 3.2599759E+00,
            2.9771762E+00, 4.5936475E+00
        ])
        error = 0.07 * numpy.ones(x.shape)
        p = [1.0, 1.0]
        pactual = [3.20, 1.78]

        args = (x, y, error)
        p, result = mpyfit.fit(self.func, p, args)

        dof = result['nfunc'] - result['nfree']
        self.assertEqual(dof, 8)
        self.assertEqual(result['status'][0], 1)
        self.assertAlmostEqual(result['bestnorm'], 2.756285)
        self.assertTrue(abs(p[0] - pactual[0]) < result['parerrors'][0])
        self.assertTrue(abs(p[1] - pactual[1]) < result['parerrors'][1])
Exemplo n.º 15
0
    def test_limit(self):
        self.p[2] = 0
        self.p[3] = 0.1
        parinfo = [{
            'fixed': True
        }, {}, {
            'fixed': True
        }, {
            'limits': (-0.2, 0.3)
        }]

        args = (self.x, self.y, self.error)
        p, result = mpyfit.fit(self.func, self.p, args, parinfo=parinfo)

        dof = result['nfunc'] - result['nfree']
        self.assertEqual(result['status'][0], 1)
        self.assertEqual(result['nfunc'] - result['nfree'], 8)
        self.assertEqual(p[0], 0.0)
        self.assertEqual(result['parerrors'][0], 0)
        self.assertAlmostEqual(p[1], 5.533173)
        self.assertAlmostEqual(result['parerrors'][1], 0.3395397)
        self.assertEqual(p[2], 0.0)
        self.assertEqual(result['parerrors'][2], 0)
        self.assertTrue(p[3] >= -0.2 and p[3] <= 0.3)
Exemplo n.º 16
0
def lightcurve_fit(_time,_flux,_eflux,_am,_RpRs,_aR,_i,_u1,_u2,_P,_e,_omega):
	'''
	'''
	########################################################################################
	########################################################################################
	#Importing data to make the model
	Rp_Rs 			= float(_RpRs)
	limbB1, limbB2 	= float(_u1),float(_u2)
	inc 			= np.radians(float(_i))
	a_Rs 			= float(_aR)
	hjd 			= _time
	rawflux 		= _flux
	eflux 			= _eflux
	am 				= _am
	period 			= float(_P)
	omega 			= float(_omega)
	e 				= float(_e)

	########################################################################################
	########################################################################################
	#Functions based on Mandel and Agol (2002)
	def simple_model(JD, startpar0, startpar1):
		phase = (JD - startpar1)/period
		distance_vector = occultation_bic.delta(phase,inc) * a_Rs
		#model = occultation_fn(distance_vector,startpar0,limbB1,limbB2,show=False)
		model = occultation_bic.occultquad(distance_vector, limbB1, limbB2, startpar0, len(hjd))
		return model
	def model_am_exp(hjd,startpar0,startpar1,startpar2,startpar3):
		model = simple_model(hjd,startpar0, startpar1)
		model_am = model * startpar2 * np.exp(-1. * startpar3 * am) #multiply light curve by factor x exponential
		return model_am
	def residuals_am_exp(params,args): #residuals function for mpfit
	    RpRs = params[0]
	    Tc = params[1]
	    mu1 = params[2]
	    mu2 = params[3]
	    hjd, data, eps_data = args
	    model = model_am_exp(hjd,RpRs,Tc,mu1,mu2)
	    return (data-model)/eps_data
	def model_am_linear(hjd,startpar0,startpar1,startpar2,startpar3):
		model = simple_model(hjd,startpar0, startpar1)
		model_am = model * (startpar2 * am + startpar3) #multiply light curve by factor x exponential
		return model_am
	def residuals_linear(params,args): #residuals function for mpfit
		RpRs = params[0]
		Tc = params[1]
		mu1 = params[2]
		mu2 = params[3]
		hjd, data, eps_data = args
		model = model_am_linear(hjd,RpRs,Tc,mu1,mu2)
		return (data-model)/eps_data
	def model_am_2deg(hjd,startpar0,startpar1,startpar2,startpar3,startpar4):
		model = simple_model(hjd,startpar0, startpar1)
		model_am = model * (startpar2 + startpar3*am + startpar4*am) #multiply light curve by factor x exponential
		return model_am
	def residuals_2deg_mpfit(params,args): #residuals function for mpfit
		RpRs = params[0]
		Tc = params[1]
		mu1 = params[2]
		mu2 = params[3]
		mu3 = params[4]
		hjd, data, eps_data = args
		model = model_am_2deg(hjd,RpRs,Tc,mu1,mu2,mu3)
		return (data-model)/eps_data
    ########################################################################################
    ########################################################################################
    #Creating dictionary with guess parameters
	startpar = [float(Rp_Rs),np.mean(hjd), 1., 0.]
	print 'Parameters for fitting a phase model = ',startpar,'\n'

	PARINFO = [{'value':Rp_Rs,'limits':(0,1.)},{'value':np.mean(hjd)},{'value':1.},{'value':0.,'fixed':True}]
	pfit1, results1 = mpyfit.fit(residuals_am_exp, startpar, args = (hjd,rawflux,eflux), parinfo=PARINFO)
	#
	# model1 = model_am_exp(hjd,pfit1[0],pfit1[1],pfit1[2],pfit1[3])
	# phase1 = (hjd - pfit1[1])/period
	# #results = [{'bestfit':pfit1},{'fit_report':results1},{'phase':phase1},{'model':model1}]
	return pfit1
Exemplo n.º 17
0
 def test_fixed(self):
     p = [10]
     parinfo = [{'fixed': True}]
     with self.assertRaisesRegex23(RuntimeError, "mpfit function error -19"):
         p, result = mpyfit.fit(self.func, p, parinfo=parinfo)
Exemplo n.º 18
0
 def test_limits(self):
     p = [10]
     parinfo = [{'limits': (10, 10)}]
     with self.assertRaisesRegex23(RuntimeError, "mpfit function error -22"):
         p, result = mpyfit.fit(self.func, p, parinfo=parinfo)
Exemplo n.º 19
0
def fit_circle(center_col, center_row, radius, data, function,
               ridge_thickness = 1):
    """Fit a circle to the input data.

    Parameters:

    * center_col : float 
        The column coordinate of the center.

    * center_row : float
        The row coordinate of the center.

    * radius : float

    * data : numpy.ndarray

    * function : object
        A reference to the function to be used for fitting.

    * ridge_thickness : float : 1
        The thickness of the ring to be fitted to the data.
    """
    log = logging.getLogger(__name__)

    parameters = (float(center_col),
                  float(center_row),
                  float(radius),
                  float(ridge_thickness))
    
    # Constraints on parameters
    parinfo = []
    parbase = {'fixed': False,
               'step': 2}
    parinfo.append(parbase)
    parbase = {'fixed': False,
               'step': 2}
    parinfo.append(parbase)
    parbase = {'fixed': False,
               'step': 2}
    parinfo.append(parbase)
    # ridge_thickness
    parbase = {'fixed': False,
               'step': 0.1}
    parinfo.append(parbase)
    
    for entry in parinfo:
        log.debug("parinfo = %s" % str(entry))
            
    try:
        log.debug("fit_circle input parameters = {}".format(parameters))
        fit_parameters, fit_result = mpyfit.fit(
            least_circle,
            parameters,
            args = (data.shape, data, function ),
            parinfo = parinfo,
            xtol = 1e-1)
    except Exception as e:
        log.error(tuna.console.output_exception(e))
        raise(e)

    log.debug("fit_circle result = {}".format(fit_result))

    return fit_parameters, function(
        (fit_parameters[0], fit_parameters[1]), fit_parameters[2],
        ridge_thickness, data.shape)
Exemplo n.º 20
0
 def test_fit(self):
     p = [10]
     p, result = mpyfit.fit(self.func, p)
     self.assertLess(result['niter'], 10)
     self.assertEqual(result['status'][0], 4)
     self.assertAlmostEqual(p[0], 0)
Exemplo n.º 21
0
 def test_fixed(self):
     p = [10]
     parinfo = [{'fixed': True}]
     with self.assertRaisesRegex23(RuntimeError,
                                   "mpfit function error -19"):
         p, result = mpyfit.fit(self.func, p, parinfo=parinfo)
Exemplo n.º 22
0
 def test_limits(self):
     p = [10]
     parinfo = [{'limits': (10, 10)}]
     with self.assertRaisesRegex23(RuntimeError,
                                   "mpfit function error -22"):
         p, result = mpyfit.fit(self.func, p, parinfo=parinfo)
Exemplo n.º 23
0
 def test_fit(self):
     p = [0, 0]
     p, result = mpyfit.fit(self.func, p, maxiter=10000)
     self.assertEqual(result['status'][0], 2)
     self.assertAlmostEqual(p[0], 3.0, places=5)
     self.assertAlmostEqual(p[1], 0.5, places=5)
Exemplo n.º 24
0
 def test_fit(self):
     p = [10]
     p, result = mpyfit.fit(self.func, p)
     self.assertLess(result['niter'], 10)
     self.assertEqual(result['status'][0], 4)
     self.assertAlmostEqual(p[0], 0)
Exemplo n.º 25
0
def main():
    
    ##################
    # Model as input #
    ##################
    
    # Parameter initialisation for the model (obtained from the data)
    lbda = 0.6598
    pc = 791
    r1 = (347. - 142.) / 2.
    r2 = (456. - 33) / 2.
    b = np.sqrt((2 * pc - 1) / (pc **2 * (r2 ** 2 - r1 ** 2) - 2 * pc * r2 ** 2 + r2 ** 2))
    ne = lbda * pc * np.sqrt(1 + b ** 2 * r1 ** 2) / 2.
    isl_ne = ne / pc
    de = - isl_ne / 33.
    
    x, y, = 512, 512
    image = np.zeros((y, x))
    index = np.indices((y, x))
    
    I0, C, F, xc, yc = 2000., 300., 11.7, 244.1, 239.9
    
    print(I0, C, F, ne, b, xc, yc)
    
    cube = np.zeros((32, y, x))
    for z in range(32):
        data = airy2d(I0=I0, C=C, F=F, ne=ne-z*de, b=b, xc=xc, yc=yc, lbda=lbda, x=x, y=y)
        cube[z, :,:] = data.reshape((1, y, x))
    hdu = pf.PrimaryHDU(cube)
    hdulist = pf.HDUList(hdu)
    hdulist.writeto('/home/bepinat/Travail/mission_ohp_1014/test/T251/model.fits', clobber=True)
    
    
    
    data = airy2d(I0=I0, C=C, F=F, ne=ne, b=b, xc=xc, yc=yc, lbda=lbda, x=x, y=y)
    #data = airy2d0(I0=I0, C=C, F=F, ne=ne, b=b, xc=xc, yc=yc, lbda=lbda, index=index)
    
    #Initial data plot
    fig = plt.figure()
    ax1 = plt.subplot(131)
    plt.imshow(data, vmin=290, vmax=2500, cmap='spectral')
    plt.colorbar(orientation="horizontal")

    # Parameter initialisation
    f = 4.0 * F ** 2 / np.pi ** 2
    I0 = (np.percentile(data, 99) - np.percentile(data, 1)) * (1 + f) / f
    C = np.percentile(data, 99) - I0
    F = 13.
    b = 2.72e-04
    ne = ne + lbda / 16.
    xc = xc + 10.5
    yc = yc - 5.2
    flat = 1
    pi = (I0, C, F, ne, b, xc, yc)
    print(pi)
    
    # Constraints on parameters
    #parbase = {'fixed':1, 'limits':(None, None), 'step':0.1, 'relstep':0.1, 'side':0, 'deriv_reltol':1e-6, 'deriv_abstol':1e-6}
    parinfo = []
    parbase = {'fixed':False, 'limits':(I0 * 0.9, I0 * 1.1)}
    parinfo.append(parbase)
    parbase = {'fixed':False, 'limits':(C * 0.9, C * 1.1)}
    parinfo.append(parbase)
    parbase = {'fixed':False, 'limits':(F / 1.5, F * 1.5)}
    parinfo.append(parbase)
    parbase = {'fixed':False, 'limits':(ne - lbda / 4., ne + lbda / 4.)}
    parinfo.append(parbase)
    parbase = {'fixed':False, 'limits':(b * 0.96, b * 1.04)}
    parinfo.append(parbase)
    parbase = {'fixed':False, 'limits':(xc - 15, xc + 15)}
    parinfo.append(parbase)
    parbase = {'fixed':False, 'limits':(yc - 15, yc + 15)}
    parinfo.append(parbase)
    
    # Fit
    pfit, results = mpyfit.fit(least_mpyfit, pi, args=(lbda, x, y, data, flat), parinfo=parinfo, stepfactor=10)
    print(pfit, results['bestnorm'])
    
    # Model
    result = airy2d(I0=pfit[0], C=pfit[1], F=pfit[2], ne=pfit[3], b=pfit[4], xc=pfit[5], yc=pfit[6], lbda=lbda, x=x, y=y)
    
    # Residualks and plot of residuals
    residuals = data - result
    ax1 = plt.subplot(133)
    plt.imshow(residuals, vmin=-.02, vmax=.02, cmap='spectral')
    plt.colorbar(orientation="horizontal")
    plt.show()
    
    
    #################
    # Data as input #
    #################
    
    tdu = pyadhoc.readad3('/home/bepinat/Travail/mission_ohp_1014/test/T251/T251.AD3')
    index = 0
    
    # Initial data plot
    fig = plt.figure()
    ax1 = plt.subplot(141)
    plt.imshow(tdu.data[index,:,:].reshape((512,512)), vmin=290, vmax=2500, cmap='spectral')
    plt.colorbar(orientation="horizontal")

    # Construction of a flat field for calibration (relie on the hypothesis that the free spectral range is correctly sampled)
    bkg = np.percentile(tdu.data, 0.1)  # background
    flat = np.sum((tdu.data - bkg), axis=0)  # background substraction
    flat[np.where(flat <= 0)] = 1  # remove zeros
    flat /= np.percentile(flat, 99)  # normalization
    ax1 = plt.subplot(142)
    #flat = 1
    plt.imshow(flat, vmin=0, vmax=1, cmap='spectral')
    plt.colorbar(orientation="horizontal")

    data = (tdu.data[index,:,:].reshape((512,512)) - bkg) / flat + bkg  # flat field correction
    data[np.where(data < 300)] = 300
    data[np.where(data > 3000)] = 300
    
    datahdu = (tdu.data - bkg) / flat + bkg
    datahdu[np.where(datahdu < 300)] = 300
    datahdu[np.where(datahdu > 3000)] = 300
    hdu = pf.PrimaryHDU(datahdu)
    hdulist = pf.HDUList(hdu)
    hdulist.writeto('/home/bepinat/Travail/mission_ohp_1014/test/T251/T251_norm.fits', clobber=True)

    # Flat fielded data plot
    ax1 = plt.subplot(143)
    plt.imshow(data, vmin=290, vmax=2500, cmap='spectral')
    plt.colorbar(orientation="horizontal")
    plt.show()
    
    # Parameter initialisation
    lbda = 0.6598
    pc = 791
    r1 = (347. - 142.) / 2.
    r2 = (456. - 33) / 2.
    b = np.sqrt((2 * pc - 1) / (pc **2 * (r2 ** 2 - r1 ** 2) - 2 * pc * r2 ** 2 + r2 ** 2))
    ne = lbda * pc * np.sqrt(1 + b ** 2 * r1 ** 2) / 2.
    
    f = 4.0 * F ** 2 / np.pi ** 2
    I0 = (np.percentile(data, 99) - np.percentile(data, 1)) * (1 + f) / f
    C = np.percentile(data, 99) - I0
    pi = (I0, C, F, ne, b, xc, yc)
    print(pi)
    
    # Constraints on parameters
    #parbase = {'fixed':1, 'limits':(None, None), 'step':0.1, 'relstep':0.1, 'side':0, 'deriv_reltol':1e-6, 'deriv_abstol':1e-6}
    parinfo = []
    parbase = {'fixed':False, 'limits':(I0 * 0.9, I0 * 1.1)}
    parinfo.append(parbase)
    parbase = {'fixed':False, 'limits':(C * 0.9, C * 1.1)}
    parinfo.append(parbase)
    parbase = {'fixed':False, 'limits':(F / 1.5, F * 1.5)}
    parinfo.append(parbase)
    parbase = {'fixed':False, 'limits':(ne - lbda / 4., ne + lbda / 4.)}
    parinfo.append(parbase)
    parbase = {'fixed':False, 'limits':(b * 0.96, b * 1.04)}
    parinfo.append(parbase)
    parbase = {'fixed':False, 'limits':(xc - 15, xc + 15)}
    parinfo.append(parbase)
    parbase = {'fixed':False, 'limits':(yc - 15, yc + 15)}
    parinfo.append(parbase)
    
    # Fit
    pfit, results = mpyfit.fit(least_mpyfit, pi, args=(lbda, x, y, data, flat), parinfo=parinfo, stepfactor=10)
    print(pfit, results['bestnorm'])
    
    # Model
    result = airy2d(I0=pfit[0], C=pfit[1], F=pfit[2], ne=pfit[3], b=pfit[4], xc=pfit[5], yc=pfit[6], lbda=lbda, x=x, y=y)
    
    # Residuals and plot of residuals
    residuals = data - result
    ax1 = plt.subplot(144)
    plt.imshow(residuals, vmin=-250, vmax=250, cmap='spectral')
    plt.colorbar(orientation="horizontal")
    plt.show()
Exemplo n.º 26
0
 def test_fit(self):
     p = [0, 0]
     p, result = mpyfit.fit(self.func, p, maxiter=10000)
     self.assertEqual(result['status'][0], 2)
     self.assertAlmostEqual(p[0], 3.0, places=5)
     self.assertAlmostEqual(p[1], 0.5, places=5)
Exemplo n.º 27
0
 def test_fit(self):
     p = [0, 0]
     p, result = mpyfit.fit(self.func, p)
     # Does not even come close
     self.assertNotAlmostEqual(round(p[0], 1), 1.0)
     self.assertNotAlmostEqual(round(p[1], 1), 1.0)
Exemplo n.º 28
0
 def test_fit(self):
     p = [1, 1]
     p, result = mpyfit.fit(self.func, p)
     self.assertEqual(result['status'][0], 5)
     self.assertAlmostEqual(p[0], 0)
     self.assertAlmostEqual(p[1], 0)
Exemplo n.º 29
0
 def test_fit10000iterations(self):
     p = [1, 1]
     p, result = mpyfit.fit(self.func, p, maxiter=50000)
     self.assertEqual(result['status'][0], 4)
     self.assertAlmostEqual(p[0], 0)
     self.assertAlmostEqual(p[1], 0)
Exemplo n.º 30
0
 def test_fit(self):
     p = [1, 1]
     p, result = mpyfit.fit(self.func, p)
     self.assertEqual(result['status'][0], 5)
     self.assertAlmostEqual(p[0], 0)
     self.assertAlmostEqual(p[1], 0)
Exemplo n.º 31
0
 def test_fit50000iterations(self):
     p = [0, 0]
     p, result = mpyfit.fit(self.func, p, maxiter=50000)
     self.assertAlmostEqual(p[0], 1., places=4)
     self.assertAlmostEqual(p[1], 1., places=4)
Exemplo n.º 32
0
 def test_fit10000iterations(self):
     p = [1, 1]
     p, result = mpyfit.fit(self.func, p, maxiter=50000)
     self.assertEqual(result['status'][0], 4)
     self.assertAlmostEqual(p[0], 0)
     self.assertAlmostEqual(p[1], 0)
Exemplo n.º 33
0
def model_airmassfit(hjd, am, rawflux, limbB1, limB2, inc, period, a_Rs, Rp_Rs, show=False):
    """
    Return the bestfit model for the lightcurve using 4 models of airmass correction:
    1. model with no airmass correction
    2. model with exponential airmass correction
    3. model with linear airmass correction
    4, model with 2deg polynomial airmass correction
    ___
    INPUT:

    hjd:
    am:
    rawflux:
    limbB1:
    limbB2:
    inc:
    period:
    a_Rs:
    startpar:

    OUTPUT:
    result: dataframe structure with besfit values for each model, the errors and BIC values.
    phase: from the bestfit model
    lc: lightcurve from the bestfit model
    """
    # Model 1: no airmass correction
    startpar = [Rp_Rs, np.mean(hjd), 1., 0.]
    PARINFO = [{'value':Rp_Rs,'limits':(0,1.)}, {'value':np.mean(hjd)}, {'value':1.}, {'value':0.,'fixed':True}]
    pfit1, results1 = mpyfit.fit(residuals_am_exp, startpar, args = (hjd,rawflux,eflux), parinfo=PARINFO)
    model1 = model_am_exp(hjd,pfit1[0],pfit1[1],pfit1[2],pfit1[3])
    phase1 = (hjd - pfit1[1])/period
    if show == True:
        print '...'
        print 'Model 1: no airmass correction'
        print 'bestfit values = ',pfit1
        print 'error = ', results1['parerrors']
        print 'bestnorm1 = ', results1['bestnorm']
        print 'chi-square, scipy routine = ',chisquare(rawflux, model1)
    #Model 2: exponential airmass correction
    PARINFO = [{'value':Rp_Rs,'limits':(0,1.)}, {'value':np.mean(hjd)}, {'value':1.}, {'value':0.,'fixed':False}]
    pfit2, results2 = mpyfit.fit(residuals_am_exp, startpar, args = (hjd,rawflux,eflux), parinfo=PARINFO)
    model2 = model_am_exp(hjd,pfit2[0],pfit2[1],pfit2[2],pfit2[3])
    phase2 = (hjd - pfit2[1])/period
    if show == True:
        print '...'
        print 'Model 2: exponential airmass correction'
        print 'bestfit values = ',pfit2
        print 'error = ', results2['parerrors']
        print 'bestnorm1 = ', results2['bestnorm']
        print 'chi-square, scipy routine = ',chisquare(rawflux, model2)
    #Model 3: linear airmass correction
    PARINFO = [{'value':Rp_Rs,'limits':(0,1.)},{'value':np.mean(hjd)},{'value':1.}, {'value':0.,'fixed':False}]
    pfit3, results3 = mpyfit.fit(residuals_linear, startpar, args = (hjd,rawflux,eflux), parinfo=PARINFO)
    model3 = model_am_linear(hjd,pfit3[0],pfit3[1],pfit3[2],pfit3[3])
    phase3 = (hjd - pfit3[1])/period
    if show == True:
        print '...'
        print 'Model 3: linear airmass correction'
        print 'bestfit values = ',pfit3
        print 'error = ', results3['parerrors']
        print 'bestnorm1 = ', results3['bestnorm']
        print 'chi-square, scipy routine = ',chisquare(rawflux, model3)
    #Model 4: 2deg polynomial airmss correction
    PARINFO = [{'value':Rp_Rs,'limits':(0,1.)},{'value':np.mean(hjd)},{'value':1.},{'value':0.},{'value':0.}]
    pstart = [Rp_Rs,np.mean(hjd),1.,0.,0.]
    pfit4, results4 = mpyfit.fit(residuals_2deg_mpfit, pstart, args = (hjd,rawflux,eflux), parinfo=PARINFO)
    model4 = model_am_2deg(hjd,pfit4[0],pfit4[1],pfit4[2],pfit4[3],pfit4[4])
    phase4 = (hjd - pfit4[1])/period
    if show == True:
        print '...'
        print 'Model 4: 2deg poly airmass correction'
        print 'bestfit values = ',pfit4
        print 'error = ', results4['parerrors']
        print 'bestnorm1 = ', results4['bestnorm']
        print 'chi-square, scipy routine = ',chisquare(rawflux, model4)
    #Obtain BIC values:
    #Let's create our fit file and our best BIC
    BICarray = ['none', 'exponential', 'linear','2nd_deg_poly']
    nfree = [3,4,4,5]
    bestnorm = [results1['bestnorm'],results2['bestnorm'],results3['bestnorm'],results4['bestnorm']]
    bic = BIC(nfree,bestnorm,len(rawflux))
    RpRs = [pfit1[0], pfit2[0], pfit3[0], pfit4[0]]
    Tc   = [pfit1[1], pfit2[1], pfit3[1], pfit4[1]]
    a    = [pfit1[2], pfit2[2], pfit3[2], pfit4[2]]
    b    = [pfit1[3], pfit2[3], pfit3[3], pfit4[3]]
    c    = ['Nan','Nan','Nan',pfit4[4]]
    error1 = [results1['parerrors'][0], results2['parerrors'][0], results3['parerrors'][0], results4['parerrors'][0]]
    error2 = [results1['parerrors'][1], results2['parerrors'][1], results3['parerrors'][1], results4['parerrors'][1]]
    error3 = [results1['parerrors'][2], results2['parerrors'][2], results3['parerrors'][2], results4['parerrors'][2]]
    error4 = [results1['parerrors'][3], results2['parerrors'][3], results3['parerrors'][3], results4['parerrors'][3]]
    error5 = ['Nan','Nan','Nan', results4['parerrors'][0]]
    result = DataFrame([BICarray,list(bic),RpRs,error1,Tc,error2,a,error3,b,error4,c,error5]).T
    result.columns=['Model','BIC','RpRs','eRpRs','Tc','eTc','a','ea','b','eb','c','ec']
    if show == True:
        print '... Results:'
        print result
        print 'The best model is: ',result.Model[result.BIC == result.BIC.min()]
        print 'with the BIC = ',result.BIC.min()
    #Saving the bestfit transit image:
    bestfit = np.where(result.BIC == result.BIC.min())
    indx = bestfit[0][0]
    if indx == 0:
        lc = model1
        phase = phase1
    if indx == 1:
        lc = model2
        phase = phase2
    if indx == 2:
        lc = model3
        phase = phase3
    if indx == 3:
        lc = model4
        phase = phase4
    return result, phase, lc
Exemplo n.º 34
0
 def test_fit(self):
     p = [0, 0]
     p, result = mpyfit.fit(self.func, p)
     # Does not even come close
     self.assertNotAlmostEqual(round(p[0], 1), 1.0)
     self.assertNotAlmostEqual(round(p[1], 1), 1.0)
Exemplo n.º 35
0
def tess_gauss_fit(im,
                   sig_im,
                   centroidmode='fixed',
                   xsigcmode=0.5,
                   stopper=False):

    ##make a cutout
    ##evertythin more than 5 pixels away should be ignored in fit

    ##first make the x/y grids
    xvect = np.arange(im.shape[0])
    yvect = np.arange(im.shape[1])

    imx, imy = np.meshgrid(yvect, xvect)
    #pdb.set_trace()
    if len(xvect) % 2 != 0:
        xstart = (len(xvect) + 1) / 2
    else:
        xstart = len(xvect) / 2
    xstart = int(xstart)

    #
    ##adjust the starting position to the brightest pixel in a small distance from the initial guess
    shiny = np.unravel_index(
        np.argmax(im[xstart - 2:xstart + 2, xstart - 2:xstart + 2]),
        im[xstart - 2:xstart + 2, xstart - 2:xstart + 2].shape)
    starterx, startery = xstart - 2 + shiny[0], xstart - 2 + shiny[1]
    #pdb.set_trace()
    #if centroidmode=='free':
    #    xxx =np.where(im == np.max(im))
    #    ystart = xxx[0][0]
    #    xstart = xxx[1][0]

    ##pdb.set_trace()
    qwe = np.where((imx - starterx)**2 + (imy - startery)**2 > 4**2)
    qwe2 = np.where((imx - starterx)**2 + (imy - startery)**2 <= 2**2)
    sig_im[qwe[0], qwe[1]] = im[qwe[0], qwe[1]] * 10.0
    pstart = np.array([
        imx[starterx, startery] * 1.0, imy[starterx, startery] * 1.0, 0.5, 0.5,
        np.nanmax(im[qwe2[0], qwe2[1]]),
        np.max([np.nanmin(im[qwe2[0], qwe2[1]]), 0.1]), 0.01
    ])

    qwe = np.where(np.isnan(im))
    im[qwe[0], qwe[1]] = 0.0
    sig_im[qwe[0], qwe[1]] = np.nanmax(im) * 100

    ##limit certain parameters
    parinfo2 = [{
        'fixed': False,
        'limits': (None, None)
    } for dddd in range(pstart.shape[0])]
    parinfo2[4]['limits'] = (0.01, None)
    parinfo2[5]['limits'] = (0.01, None)
    parinfo2[6]['limits'] = (0.0001, 0.99)
    parinfo2[0]['limits'] = (pstart[0] - .2, pstart[0] + .2)
    parinfo2[1]['limits'] = (pstart[1] - .2, pstart[1] + .2)
    parinfo2[2]['limits'] = (0.1, 1.0)
    parinfo2[3]['limits'] = (0.1, 1.0)
    if centroidmode == 'free':  ##let the centroid move alot more, mostly for custom stuff

        parinfo2[0]['limits'] = (pstart[0] - 1.0, pstart[0] + 1.0)
        parinfo2[1]['limits'] = (pstart[1] - 1.0, pstart[1] + 1.0)
        parinfo2[2]['fixed'] = True
        parinfo2[3]['fixed'] = True
        # parinfo2[5]['fixed'] = True
        ##parinfo[6]['fixed'] = True
        pstart[2] = xsigcmode
        pstart[3] = xsigcmode
        pstart[5] = 10.0
        #pstart[0] = starterx
        #pstart[1] = startery

    #pdb.set_trace()
    ##parinfo2[6]['fixed'] = True

    if stopper == True: pdb.set_trace()
    try:
        fitpars, extrares = mpyfit.fit(gaussmodel,
                                       pstart,
                                       args=(imx, imy, im, sig_im),
                                       maxiter=200,
                                       parinfo=parinfo2)
        bestmod, bestresid = gaussmodel(fitpars, (imx, imy, im, sig_im),
                                        model=True)
    except:
        print('the image fit failed!')
        pdb.set_trace()
    return fitpars[0], fitpars[1], fitpars[5], fitpars[2], fitpars[3]
Exemplo n.º 36
0
 def test_fit50000iterations(self):
     p = [0, 0]
     p, result = mpyfit.fit(self.func, p, maxiter=50000)
     self.assertAlmostEqual(p[0], 1., places=4)
     self.assertAlmostEqual(p[1], 1., places=4)
Exemplo n.º 37
0
def master_shifting_planet(
    bjd,
    ccfBary,
    rvh,
    ref_frame_shift,  # "off" or a specific value in km/s
    removed_planet_rvs,  # array of rv values for planet signal in km/s OR "NULL"
    injected_planet_params,  # array of amplitude (km/s), 2pi/period, phase
    zero_or_median):  # "zero" or "median"
    number_of_ccfs = len(ccfBary)

    # HARPS direct data lists
    BJD_list = []
    og_ccf_list = []
    rv_from_HARPS_list = []
    v_rad_raw_list = []

    # injected planet list
    planet_signal_list = []

    # mpyfit lists
    mu_og_list = []
    mu_jup_list = []
    mu_planet_list = []
    mu_zero_list = []
    CCF_normalized_list = []

    # CCF lists
    compiled_ccf_list = []
    jup_shifted_CCF_data_list = []
    planet_shifted_CCF_data_list = []
    shifted_CCF_list = []
    final_ccf_list = []

    def planet_signal(x):
        return injected_planet_params[0] * np.sin(
            injected_planet_params[1] * x + injected_planet_params[2])

    spline_method = 'quadratic'
    for i in range(0, number_of_ccfs):
        day_of_observation = bjd[i]
        BJD_list.append(day_of_observation)

        # extracts the CCF data and rv from fits
        CCF_data = ccfBary[i]
        og_ccf_list.append(CCF_data)
        rv_from_HARPS = rvh[i]  # - bsrv[i]
        rv_from_HARPS_list.append(rv_from_HARPS)

        # Finds the local minima using a Gaussian fit
        # Define the actual function where     A = p[0], mu = p[1], sigma = p[2], c = p[3]
        def gauss(x, p):
            return -p[0] * np.exp(-(x - p[1])**2 / (2. * p[2]**2)) + p[3]

        # A simple minimization function:
        def least(p, args):
            x, y = args
            return gauss(x, p) - y

        parinfo = [{
            'fixed': False,
            'step': 1e-6
        }, {
            'fixed': False,
            'step': 1e-4
        }, {
            'fixed': False,
            'step': 1e-14
        }, {
            'fixed': False,
            'step': 1e-9
        }]

        # no_shift fit
        rv_data = np.linspace(-20, 20, 161)
        p_no_shifted = [1., 0.1, 1., 0.5]
        pfit_no_shift, results_no_shift = mpyfit.fit(least, p_no_shifted,
                                                     (rv_data, CCF_data),
                                                     parinfo)
        mu_og = pfit_no_shift[1]
        mu_og_list.append(mu_og)
        compiled_ccf_list.append(CCF_data)

        # Add in reference frame shift

        if removed_planet_rvs[0] != "NULL":
            jupiter_shift = removed_planet_rvs[i]
            v_rad_raw = rvh[i] + removed_planet_rvs[i]
            v_rad_raw_list.append(v_rad_raw)

            # planet removal shift
            rv_data_jupiter_shift = rv_data + jupiter_shift  # minus sign
            f_jup = interp1d(rv_data_jupiter_shift,
                             CCF_data,
                             kind=spline_method,
                             fill_value='extrapolate')
            jupiter_shifted_CCF_data = f_jup(rv_data)
            jup_shifted_CCF_data_list.append(jupiter_shifted_CCF_data)
            compiled_ccf_list.append(jupiter_shifted_CCF_data)

            # fits the shifted by jupiter data
            p_shifted_jup = [1., 0.1 + jupiter_shift, 1., 0.5]
            pfit_jup, results_jup = mpyfit.fit(
                least, p_shifted_jup, (rv_data, jupiter_shifted_CCF_data),
                parinfo)
            m = pfit_jup[1]
            mu_jup_list.append(m)

        if injected_planet_params[0] != "NULL":
            # inject a planet (k=0.3 m/s, p = 365.24d)
            ccf_to_use = compiled_ccf_list[len(compiled_ccf_list) - 1]

            bjd_array = np.asarray(day_of_observation)
            inj_planet_shift = planet_signal(bjd_array)  # km/s
            planet_signal_list.append(inj_planet_shift)
            rv_data_planet_shift = rv_data + inj_planet_shift
            f_planet = interp1d(rv_data_planet_shift,
                                ccf_to_use,
                                kind='cubic',
                                fill_value='extrapolate')
            planet_shifted_CCF_data = f_planet(rv_data)
            planet_shifted_CCF_data_list.append(planet_shifted_CCF_data)
            compiled_ccf_list.append(planet_shifted_CCF_data)

            # fits the shifted by planet data
            p_shifted_planet = [1., 0.1 + inj_planet_shift, 1., 0.5]
            pfit_planet, results_planet = mpyfit.fit(
                least, p_shifted_planet, (rv_data, planet_shifted_CCF_data),
                parinfo)

            m = pfit_planet[1]
            mu_planet_list.append(m)

            if zero_or_median == "zero":
                # Shift to zero, after planet shift
                ccf_to_use = compiled_ccf_list[len(compiled_ccf_list) - 1]

                shift_to_zero = -(rv_from_HARPS + inj_planet_shift)
                rv_data_shifted = rv_data + shift_to_zero

                f = interp1d(rv_data_shifted,
                             ccf_to_use,
                             kind='cubic',
                             fill_value='extrapolate')
                shifted_CCF_data = f(rv_data)
                shifted_CCF_list.append(shifted_CCF_data)
                compiled_ccf_list.append(shifted_CCF_data)

                # fits the shifted data
                p_shifted = [1., 0.1 - shift_to_zero, 1., 0.5]
                pfit, results = mpyfit.fit(least, p_shifted,
                                           (rv_data, shifted_CCF_data),
                                           parinfo)
                m_zero = pfit[1]
                mu_zero_list.append(m_zero)  # -0.1)
            else:
                # Shift to median, after planet shift
                ccf_to_use = compiled_ccf_list[len(compiled_ccf_list) - 1]

                shift_to_zero = ((np.mean(rvh) - rv_from_HARPS) -
                                 inj_planet_shift)
                rv_data_shifted = rv_data + shift_to_zero

                f = interp1d(rv_data_shifted,
                             ccf_to_use,
                             kind='cubic',
                             fill_value='extrapolate')
                shifted_CCF_data = f(rv_data)
                shifted_CCF_list.append(shifted_CCF_data)
                compiled_ccf_list.append(shifted_CCF_data)

                # fits the shifted data
                p_shifted = [1., 0.1 - shift_to_zero, 1., 0.5]
                pfit, results = mpyfit.fit(least, p_shifted,
                                           (rv_data, shifted_CCF_data),
                                           parinfo)
                m_zero = pfit[1]
                mu_zero_list.append(m_zero)  # -0.1)
        else:
            if zero_or_median == "zero":
                # Shift to zero
                ccf_to_use = compiled_ccf_list[len(compiled_ccf_list) - 1]

                shift_to_zero = -(rv_from_HARPS)
                rv_data_shifted = rv_data + shift_to_zero

                f = interp1d(rv_data_shifted,
                             ccf_to_use,
                             kind='cubic',
                             fill_value='extrapolate')
                shifted_CCF_data = f(rv_data)
                shifted_CCF_list.append(shifted_CCF_data)
                compiled_ccf_list.append(shifted_CCF_data)

                # fits the shifted data
                p_shifted = [1., 0.1 - shift_to_zero, 1., 0.5]
                pfit, results = mpyfit.fit(least, p_shifted,
                                           (rv_data, shifted_CCF_data),
                                           parinfo)
                m_zero = pfit[1]
                mu_zero_list.append(m_zero)  # -0.1)
            else:  # shifted to median instead
                ccf_to_use = compiled_ccf_list[len(compiled_ccf_list) - 1]
                shift_to_median = (np.mean(rvh) - rv_from_HARPS)
                rv_data_shifted = rv_data + shift_to_median

                f = interp1d(rv_data_shifted,
                             ccf_to_use,
                             kind='cubic',
                             fill_value='extrapolate')
                shifted_CCF_data = f(rv_data)
                shifted_CCF_list.append(shifted_CCF_data)
                compiled_ccf_list.append(shifted_CCF_data)

                # fits the shifted data
                p_shifted = [1., 0.1 - shift_to_median, 1., 0.5]
                pfit, results = mpyfit.fit(least, p_shifted,
                                           (rv_data, shifted_CCF_data),
                                           parinfo)
                m_zero = pfit[1]
                mu_zero_list.append(m_zero)  # -0.1)
        ccf_to_use = compiled_ccf_list[len(compiled_ccf_list) - 1]
        final_ccf_list.append(ccf_to_use)

        # normalize the CCFs
        x_left = ccf_to_use[0:40]
        x_right = ccf_to_use[121:161]
        x_norm_range = list(x_left) + list(x_right)
        CCF_normalized = ccf_to_use * (1 / np.mean(x_norm_range))
        CCF_normalized_list.append(CCF_normalized)

    # Create a dataframe
    d = {
        'BJD': BJD_list,
        'vrad_star': rvh,
        'vrad_plan_star': rvh + planet_signal_list,
        'og_ccf_list': og_ccf_list,
        'jup_shifted_CCF_data_list': jup_shifted_CCF_data_list,
        'planet_shifted_CCF_data_list': planet_shifted_CCF_data_list,
        'zero_shifted_CCF_list': shifted_CCF_list,
        'CCF_normalized_list': CCF_normalized_list,
        'mu_og_list': mu_og_list,
        'mu_jup_list': mu_jup_list,
        'mu_planet_list': mu_planet_list,
        'mu_zero_list': mu_zero_list
    }
    df = pd.DataFrame(data=d)

    return df
Exemplo n.º 38
0
Arquivo: airy.py Projeto: rcbrgs/tuna
    def run(self):
        """Fit an Airy model to a given input.
        """
        start = time.time()

        lower_percentile = tuna.tools.find_lowest_nonnull_percentile (
            self.data)
        upper_percentile = 99          
        self.log.debug("%d-percentile = %f, %d-percentile = %f."
                       % (lower_percentile,
                          numpy.percentile(self.data, lower_percentile),
                          upper_percentile,
                          numpy.percentile(self.data, upper_percentile)))
        
        intensity = numpy.percentile(
            self.data, upper_percentile) - numpy.percentile(
                self.data, lower_percentile)
        self.log.debug("percentile difference = %f" % intensity)
        finesse_factor = 4.0 * self.finesse**2 / numpy.pi**2
        finesse_intensity_factor = (1 + finesse_factor) / finesse_factor
        self.log.debug("finesse_intensity_factor = ( 1 + F ) / F = %f"
                       % finesse_intensity_factor )
        intensity *= finesse_intensity_factor
        self.log.debug("intensity = %f" % intensity)

        continuum = abs(
            numpy.percentile(self.data, upper_percentile) - intensity)

        self.log.debug("guesses:\n"
                       "\tb_ratio     = {:e},\n"
                       "\tcenter      = ( {}, {} )\n"
                       "\tcontinuum   = {:e}\n"
                       "\tfinesse     = {:e}\n"
                       "\tinitial gap = {:e}\n"
                       "\tintensity   = {:e}".format(
                           self.b_ratio, self.center_col,
                           self.center_row, continuum, self.finesse,
                           self.gap, intensity))
              
        parameters = (self.b_ratio,
                      self.center_col,
                      self.center_row,
                      continuum,
                      self.finesse,
                      self.gap,
                      intensity)
        
        # Constraints on parameters
        if self.mpyfit_parinfo == []:
            parinfo = []
            parbase = {'fixed': False,
                       'limits': (self.b_ratio * 0.9, self.b_ratio * 1.1)}
            parinfo.append(parbase)
            parbase = {'fixed': False,
                       'limits': (self.center_col - 5, self.center_col + 5)}
            parinfo.append(parbase)
            parbase = {'fixed': False,
                       'limits': (self.center_row - 5, self.center_row + 5)}
            parinfo.append(parbase)
            parbase = {'fixed': False,
                       'limits': (continuum * 0.9, continuum * 1.1)}
            parinfo.append (parbase)
            parbase = {'fixed': False,
                       'limits': (self.finesse * 0.95, self.finesse * 1.05)}
            parinfo.append(parbase)
            parbase = {'fixed': False,
                       'limits': (self.gap - self.wavelength / 4.,
                                  self.gap + self.wavelength / 4.)}
            parinfo.append(parbase)
            parbase = { 'fixed': False,
                        'limits': (intensity * 0.9, intensity * 1.1)}
            parinfo.append(parbase)
        else:
            parinfo = []
            parbase = self.mpyfit_parinfo[0]
            parinfo.append(parbase)
            parbase = self.mpyfit_parinfo[1]
            parinfo.append(parbase)
            parbase = self.mpyfit_parinfo[2]
            parinfo.append(parbase)
            parbase = {'fixed': self.mpyfit_parinfo[3]['fixed'],
                       'limits': (continuum * 0.9, continuum * 1.1)}
            parinfo.append(parbase)
            parbase = self.mpyfit_parinfo[4]
            parinfo.append(parbase)
            parbase = self.mpyfit_parinfo[5]
            parinfo.append(parbase)
            parbase = {'fixed': self.mpyfit_parinfo[6]['fixed'],
                       'limits': (intensity * 0.9, intensity * 1.1)}
            parinfo.append(parbase)

        for entry in parinfo:
            self.log.debug("parinfo = %s" % str(entry))
            
        flat = 1

        self.log.debug("run()")

        try:
            self.log.debug("parameters = %s" % str(parameters)) 
            fit_parameters, fit_result = mpyfit.fit(least_mpyfit,
                                                    parameters,
                                                    args = (self.shape_cols,
                                                            self.shape_rows,
                                                            self.wavelength,
                                                            self.data,
                                                            flat),
                                                    parinfo = parinfo,
                                                    xtol = 1e-7)
                                                    #stepfactor = 10 )
        except Exception as e:
            self.log.error(tuna.console.output_exception(e))
            self.log.error("Error was using parameters = {}".format(
                parameters))
            raise(e)
        
        self.log.debug("fit_result['bestnorm'] = %s" % str(
            fit_result['bestnorm']))
        non_spammy_results = copy.copy(fit_result)
        del(non_spammy_results['covariances'])
        for key in non_spammy_results.keys():
            self.log.debug("fit_result[{}] = {}".format (
                key, non_spammy_results[key]))

        self.log.debug("results:\n"
                       "\tb_ratio     = {:e},\n"
                       "\tcenter      = ( {}, {} )\n"
                       "\tcontinuum   = {:e}\n"
                       "\tfinesse     = {:e}\n"
                       "\tinitial gap = {:e}\n"
                       "\tintensity   = {:e}".format(fit_parameters[0],
                                                     fit_parameters[1], 
                                                     fit_parameters[2], 
                                                     fit_parameters[3],
                                                     fit_parameters[4], 
                                                     fit_parameters[5],
                                                     fit_parameters[6]))

        self.log.debug("Airy fit took %ds." % (time.time() - start))
        self.fit = tuna.io.Can(airy_plane(fit_parameters[0],
                                          fit_parameters[1],
                                          fit_parameters[2],
                                          fit_parameters[3],
                                          fit_parameters[4],
                                          fit_parameters[5],
                                          fit_parameters[6],
                                          self.shape_cols,
                                          self.shape_rows,
                                          self.wavelength))
        self.parameters = fit_parameters