示例#1
0
def graficar(path, kepler_id=None, Q=None):
    """
    Grafica la curva de luz de un archivo .fits
    """
    if isdir(path):
        colors = ['b+', 'g+', 'r+', 'c+', 'm+', 'y+', 'k+']
        color_index = 0
        archivos = listdir(path)
        for archivo in archivos:
            arreglo = lightcurve(join(path, archivo))
            plt.plot(arreglo[0], arreglo[3], colors[color_index % len(colors)])
            color_index += 1
    else:
        arreglo = lightcurve(path)
        plt.plot(arreglo[0], arreglo[3], 'r+')

    plt.ylabel('Flux')
    plt.xlabel('Time')
    if kepler_id and Q:
        plt.title('{0} for Q{1}'.format(kepler_id, Q))
    # plt.savefig(archivo+".png", bbox_inches="tight")

    plt.show()

    plt.gcf().clear()
示例#2
0
文件: ngc1647.py 项目: weingrill/SOCS
 def export_lightcurves(self, path=''):
     """
     make a lightcurve file from each star in the stars list
     """
     from lightcurve import lightcurve
     for star in self.stars:
         lightcurve(star, 'rp', path=self.path)
示例#3
0
def fit_tmod2(params,LDparams,time,flux,error,fixed_dict,guess_params):
    period_d, rprs, T0, Ecc, ars, inc, omega, sec, fluxoffset = params

    if fixed_dict['period'] == True:
        period_d = guess_params[0]
    if fixed_dict['rprs'] == True:
        rprs = guess_params[1]
    if fixed_dict['T0'] == True:
        T0 = guess_params[2]
    if fixed_dict['Ecc'] == True:
        Ecc = guess_params[3]
    if fixed_dict['ars'] == True:
        ars = guess_params[4]
    if fixed_dict['inc'] == True:
        inc = guess_params[5]
    if fixed_dict['omega'] == True:
        omega = guess_params[6]
    if fixed_dict['sec'] == True:
        sec = guess_params[7]
    if fixed_dict['fluxoffset'] == False:
        flux = flux + fluxoffset
    if inc > np.pi / 2.:
        return 10**(12.)
    if omega > np.pi * 2.:
        return 10**(12.)

    mod_output = tmod.lightcurve(time, period_d, rprs, T0, Ecc, ars, inc,
                                 omega, LDparams, sec)
    return np.sum(get_chi2(flux, mod_output, error))
示例#4
0
def update(i):
    filename = archivos[i].split('-')[0].replace('kplr', '')
    print "Revisando ", filename
    ax.set_title("Kepler ID: {}".format(filename))
    arreglo = lightcurve(path + "/" + archivos[i])
    ax.set_ylim(min(arreglo[3]), max(arreglo[3]))
    ax.set_xlim(min(arreglo[0]), max(arreglo[0]))
    sp.set_data(arreglo[0], arreglo[3])
    return sp, None
示例#5
0
def fit_tmod2(params,LDparams,time,flux,error,fixed_dict,guess_params):
    period_d,rprs,T0, Ecc,ars, inc, omega, sec, fluxoffset = params

    #fix things and stop params going crazy
    #here!
    if fixed_dict['period'] == True:
        period_d = guess_params[0]
    if fixed_dict['rprs'] == True:
        rprs = guess_params[1]
    if fixed_dict['T0'] == True:
        T0 = guess_params[2]
    if fixed_dict['Ecc'] == True:
        Ecc = guess_params[3]
    if fixed_dict['ars'] == True:
        ars = guess_params[4]
    if fixed_dict['inc'] == True:
        inc = guess_params[5]
    if fixed_dict['omega'] == True:
        omega = guess_params[6]
    if fixed_dict['sec'] == True:
        sec = guess_params[7]
    
    if fixed_dict['fluxoffset'] == False:
        flux = flux + fluxoffset

    if inc > np.pi / 2.:
        return 10**(12.)

    if omega > np.pi * 2.:
        return 10**(12.)

    mod_output = tmod.lightcurve(time,period_d,rprs,T0,Ecc,ars, inc, omega, LDparams, sec)
    model = mod_output

    #try ignoring unity elements in the model
    #mask = model != 1.0

    #flux2 = flux[mask]
    #model2 = model[mask]
    #error2 = error[mask]


    chi2 = get_chi2(flux,model,error)

    return np.sum(chi2)
示例#6
0
def fit_tmod(params, args):
    period_d, rprs, T0, Ecc, ars, inc, omega, sec, fluxoffset = params
    LDparams, time, flux, error, fixed_dict, guess_params = args

    #fix things and stop params going crazy
    #here!
    if fixed_dict['period'] == True:
        period_d = guess_params[0]
    if fixed_dict['rprs'] == True:
        rprs = guess_params[1]
    if fixed_dict['T0'] == True:
        T0 = guess_params[2]
    if fixed_dict['Ecc'] == True:
        Ecc = guess_params[3]
    if fixed_dict['ars'] == True:
        ars = guess_params[4]
    if fixed_dict['inc'] == True:
        inc = guess_params[5]
    if fixed_dict['omega'] == True:
        inc = guess_params[6]
    if fixed_dict['sec'] == True:
        inc = guess_params[7]

    if fixed_dict['fluxoffset'] == False:
        flux = flux + fluxoffset

    if inc > np.pi / 2.:
        return 10**(12.)

    if omega > np.pi * 2.:
        return 10**(12.)

    mod_output = tmod.lightcurve(time, period_d, rprs, T0, Ecc, ars, inc,
                                 omega, LDparams, sec)
    model = mod_output
    chi2 = get_chi2(flux, model, error)

    return chi2
示例#7
0
def fit_tmod(params,args):
    period_d,rprs,T0, Ecc,ars, inc, omega, sec, fluxoffset = params
    LDparams,time,flux,error,fixed_dict,guess_params = args

    #fix things and stop params going crazy
    #here!
    if fixed_dict['period'] == True:
        period_d = guess_params[0]
    if fixed_dict['rprs'] == True:
        rprs = guess_params[1]
    if fixed_dict['T0'] == True:
        T0 = guess_params[2]
    if fixed_dict['Ecc'] == True:
        Ecc = guess_params[3]
    if fixed_dict['ars'] == True:
        ars = guess_params[4]
    if fixed_dict['inc'] == True:
        inc = guess_params[5]
    if fixed_dict['omega'] == True:
        inc = guess_params[6]
    if fixed_dict['sec'] == True:
        inc = guess_params[7]

    if fixed_dict['fluxoffset'] == False:
        flux = flux + fluxoffset

    if inc > np.pi / 2.:
        return 10**(12.)

    if omega > np.pi * 2.:
        return 10**(12.)

    mod_output = tmod.lightcurve(time,period_d,rprs,T0,Ecc,ars, inc, omega, LDparams, sec)
    model = mod_output
    chi2 = get_chi2(flux,model,error)

    return chi2
示例#8
0
def keptransit(inputfile,outputfile,datacol,errorcol,periodini_d,rprsini,T0ini,
    Eccini,arsini,incini,omegaini,LDparams,secini,fixperiod,fixrprs,fixT0,
    fixEcc,fixars,fixinc,fixomega,fixsec,fixfluxoffset,removeflaggeddata,ftol=0.0001,fitter='nothing',norm=False,
    clobber=False, plot=True,verbose=0,logfile='logfile.dat',status=0,cmdLine=False):
    """
    tmod.lightcurve(xdata,period,rprs,T0,Ecc,ars, incl, omega, ld, sec)

    input transit parameters are
    Period in days
    T0
    rplanet / rstar
    a / rstar
    inclination

    limb darkening code number:
    0 = uniform
    1 = linear
    2 = quadratic
    3 = square root
    4 = non linear

    LDarr:
    u      -- linear limb-darkening (set NL=1)
    a, b   -- quadratic limb-darkening (set NL=2)
    c,  d  -- root-square limb-darkening (set NL= -2)
    a1, a2, a3, a4 -- nonlinear limb-darkening  (set NL=4)
    Nothing at all -- uniform limb-darkening (set NL=0)
    """

    np.seterr(all="ignore") 

    #write to a logfile
    hashline = '----------------------------------------------------------------------------'
    kepmsg.log(logfile,hashline,verbose)
    call = 'KEPTRANSIT -- '
    call += 'inputfile='+inputfile+' '
    call += 'outputfile='+outputfile+' '
    call += 'datacol='+str(datacol)+' '
    call += 'errorcol='+str(errorcol)+' '
    call += 'periodini_d='+str(periodini_d)+' '
    call += 'rprsini='+str(rprsini)+' '
    call += 'T0ini='+str(T0ini)+' '
    call += 'Eccini='+str(Eccini)+' '
    call += 'arsini='+str(arsini)+' '
    call += 'incini='+str(incini)+' '
    call += 'omegaini='+str(omegaini)+' '
    call += 'LDparams='+str(LDparams)+' '
    call += 'secini='+str(secini)+' '
    call += 'fixperiod='+str(fixperiod)+' '
    call += 'fixrprs='+str(fixrprs)+' '
    call += 'fixT0='+str(fixT0)+' '
    call += 'fixEcc='+str(fixEcc)+' '
    call += 'fixars='+str(fixars)+' '
    call += 'fixinc='+str(fixinc)+' '
    call += 'fixomega='+str(fixomega)+' '
    call += 'fixsec='+str(fixsec)+' '
    call += 'fixfluxoffset='+str(fixfluxoffset)+' '
    call += 'removeflaggeddata='+str(removeflaggeddata)+' '
    call += 'ftol='+str(ftol)+' '
    call += 'fitter='+str(fitter)+' '
    call += 'norm='+str(norm)+' '

    plotit = 'n'
    if (plot): plotit = 'y'
    call += 'plot='+plotit+ ' '
    overwrite = 'n'
    if (clobber): overwrite = 'y'
    call += 'clobber='+overwrite+ ' '
    #chatter = 'n'
    #if (verbose): chatter = 'y'
    #call += 'verbose='+chatter+' '
    call += 'logfile='+logfile
    kepmsg.log(logfile,call+'\n',verbose)


    kepmsg.clock('KEPTRANSIT started at',logfile,verbose)

    # test log file

    logfile = kepmsg.test(logfile)

# clobber output file

    if clobber: 
        status = kepio.clobber(outputfile,logfile,verbose)
    if kepio.fileexists(outputfile): 
        message = 'ERROR -- KEPTRANSIT: ' + outputfile + ' exists. Use clobber=yes'
        status = kepmsg.err(logfile,message,verbose)

# open input file

    if status == 0:
        instr, status = kepio.openfits(inputfile,'readonly',logfile,verbose)
    if status == 0:
        tstart, tstop, bjdref, cadence, status = kepio.timekeys(instr,
            inputfile,logfile,verbose,status)
    if status == 0:
        try:
            work = instr[0].header['FILEVER']
            cadenom = 1.0
        except:
            cadenom = cadence

# fudge non-compliant FITS keywords with no values

    if status == 0:
        instr = kepkey.emptykeys(instr,file,logfile,verbose)

# read table structure

    if status == 0:
        table, status = kepio.readfitstab(inputfile,instr[1],logfile,verbose)

    if status == 0:
        intime_o = table.field('time')
        influx_o = table.field(datacol)
        inerr_o = table.field(errorcol)
        try:
            qualflag = table.field('SAP_QUALITY')
        except:
            qualflag = np.zeros(len(intime_o))

    if status == 0:
        intime, indata, inerr, baddata = cutBadData(intime_o, influx_o, inerr_o,removeflaggeddata,qualflag)

    if status == 0 and norm:
        #first remove outliers before normalizing
        threesig = 3.* np.std(indata)
        mask = np.logical_and(indata< indata + threesig,indata > indata - threesig)
        #now normalize
        indata = indata / np.median(indata[mask])

    if status == 0:
        #need to check if LD params are sensible and in right format
        LDparams = [float(i) for i in LDparams.split()]

        incini = incini * np.pi / 180.

        omegaini = omegaini * np.pi / 180.

    if arsini*np.cos(incini) > 1.0 + rprsini:
        message = 'The guess inclination and a/r* values result in a non-transing planet'
        status = kepmsg.err(logfile,message,verbose)

    if status == 0:
        fixed_dict = fix_params(fixperiod,fixrprs,fixT0,
            fixEcc,fixars,fixinc,fixomega,fixsec,fixfluxoffset)

    #force flux offset to be guessed at zero
    fluxoffsetini = 0.0

    if status == 0:
        guess_params = [periodini_d,rprsini,T0ini,Eccini,arsini, incini, omegaini, 
        secini,fluxoffsetini]

        print('cleaning done: about to fit transit')

        if fitter == 'leastsq':
            fit_output = leastsq(fit_tmod,guess_params,
                args=[LDparams,intime,indata,inerr,fixed_dict,guess_params],
                full_output=True,ftol=ftol)
        elif fitter == 'fmin':

            fit_output = fmin(fit_tmod2,guess_params,
                args=[LDparams,intime,indata,inerr,fixed_dict,guess_params],
                full_output=True,ftol=ftol,xtol=ftol)

        elif fitter == 'anneal':
            fit_output = anneal(fit_tmod2,guess_params,
                args=[LDparams,intime,indata,inerr,fixed_dict,guess_params],
                full_output=True)

    if status == 0:
        if fixed_dict['period'] == True:
            newperiod = guess_params[0]
            print('Fixed period (days) = ' + str(newperiod))
        else:
            newperiod = fit_output[0][0]
            print('Fit period (days) = ' + str(newperiod))
        if fixed_dict['rprs'] == True:
            newrprs = guess_params[1]
            print('Fixed R_planet / R_star = ' + str(newrprs))
        else:
            newrprs = fit_output[0][1]
            print('Fit R_planet / R_star = ' + str(newrprs))
        if fixed_dict['T0'] == True:
            newT0 = guess_params[2]
            print('Fixed T0 (BJD) = ' + str(newT0))
        else:
            newT0 = fit_output[0][2]
            print('Fit T0 (BJD) = ' + str(newT0))
        if fixed_dict['Ecc'] == True:
            newEcc = guess_params[3]
            print('Fixed eccentricity = ' + str(newEcc))
        else:
            newEcc = fit_output[0][3]
            print('Fit eccentricity = ' + str(newEcc))
        if fixed_dict['ars'] == True:
            newars = guess_params[4]
            print('Fixed a / R_star = ' + str(newars))
        else:
            newars = fit_output[0][4]
            print('Fit a / R_star = ' + str(newars))
        if fixed_dict['inc'] == True:
            newinc = guess_params[5]
            print('Fixed inclination (deg) = ' + str(newinc* 180. / np.pi))
        else:
            newinc = fit_output[0][5]
            print('Fit inclination (deg) = ' + str(newinc* 180. / np.pi))
        if fixed_dict['omega'] == True:
            newomega = guess_params[6]
            print('Fixed omega = ' + str(newomega))
        else:
            newomega = fit_output[0][6]
            print('Fit omega = ' + str(newomega))
        if fixed_dict['sec'] == True:
            newsec = guess_params[7]
            print('Fixed seconary eclipse depth = ' + str(newsec))
        else:
            newsec = fit_output[0][7]
            print('Fit seconary eclipse depth = ' + str(newsec))
        if fixfluxoffset == False:
            newfluxoffset = fit_output[0][8]
            print('Fit flux offset = ' + str(newfluxoffset))

    

        modelfit = tmod.lightcurve(intime,newperiod,newrprs,newT0,newEcc,
            newars,newinc,newomega,LDparams,newsec)

        if fixfluxoffset == False:
            modelfit += newfluxoffset


        #output to a file
        phi, fluxfold, modelfold, errorfold, phiNotFold = fold_data(intime, 
            modelfit,indata,inerr,newperiod,newT0)


        make_outfile(instr,outputfile,phiNotFold,modelfit, baddata)


    # end time

    if (status == 0):
        message = 'KEPTRANSIT completed at'
    else:
        message = '\nKEPTRANSIT aborted at'
    kepmsg.clock(message,logfile,verbose)

    if plot and status == 0:
        do_plot(intime,modelfit,indata,inerr,newperiod,newT0,cmdLine)
示例#9
0
"""
Crea un FITS basado en los datos de una carpeta con FITS
"""

dire = sys.argv[1]

archivos = listdir(dire)
archivos.sort()

datos = []
for i in range(20): #20 es la cantidad de caracteristicas que tienen las curvas de luz
    datos.append([])

for archivo in archivos:
    datos_ar = lightcurve.lightcurve(join(dire, archivo))
    for i in range(len(datos)):
        datos[i].extend(datos_ar[i])

table_hdu = fits.open(join(dire,archivos[0]))[1]

columnas_lista = [str(i).split(';') for i in table_hdu.columns]
columnas_lista = [[k.split('=')[1].strip()[1:-1] for k in i] for i in columnas_lista]

columnas_astropy = []

for i in range(len(columnas_lista)):
    if len(columnas_lista[i]) == 3: #Sucede que esta caracteristica no tiene datos de unidades
        columnas_astropy.append(fits.Column(name=columnas_lista[i][0], format=columnas_lista[i][1], disp=columnas_lista[i][2], array=datos[i]))
    else:
        columnas_astropy.append(fits.Column(name=columnas_lista[i][0], format=columnas_lista[i][1], unit=columnas_lista[i][2], disp=columnas_lista[i][3], array=datos[i]))
示例#10
0
def keptransitmodel(inputfile,
                    datacol,
                    errorcol,
                    period_d,
                    rprs,
                    T0,
                    Ecc,
                    ars,
                    inc,
                    omega,
                    LDparams,
                    sec,
                    norm=False,
                    verbose=0,
                    logfile='logfile.dat',
                    status=0,
                    cmdLine=False):

    #write to a logfile
    hashline = '----------------------------------------------------------------------------'
    kepmsg.log(logfile, hashline, verbose)
    call = 'KEPTRANSIT -- '
    call += 'inputfile=' + inputfile + ' '
    call += 'datacol=' + str(datacol) + ' '
    call += 'errorcol=' + str(errorcol) + ' '
    call += 'period_d=' + str(period_d) + ' '
    call += 'rprs=' + str(rprs) + ' '
    call += 'T0=' + str(T0) + ' '
    call += 'Ecc=' + str(Ecc) + ' '
    call += 'ars=' + str(ars) + ' '
    call += 'inc=' + str(inc) + ' '
    call += 'omega=' + str(omega) + ' '
    call += 'LDparams=' + str(LDparams) + ' '
    call += 'sec=' + str(sec) + ' '
    #to finish

    # open input file

    if status == 0:
        instr, status = kepio.openfits(inputfile, 'readonly', logfile, verbose)
    if status == 0:
        tstart, tstop, bjdref, cadence, status = kepio.timekeys(
            instr, inputfile, logfile, verbose, status)
    if status == 0:
        try:
            work = instr[0].header['FILEVER']
            cadenom = 1.0
        except:
            cadenom = cadence

    # fudge non-compliant FITS keywords with no values

    if status == 0:
        instr = kepkey.emptykeys(instr, file, logfile, verbose)

# read table structure

    if status == 0:
        table, status = kepio.readfitstab(inputfile, instr[1], logfile,
                                          verbose)

# filter input data table

    if status == 0:
        try:
            nanclean = instr[1].header['NANCLEAN']
        except:
            naxis2 = 0
            try:
                for i in range(len(table.field(0))):
                    if np.isfinite(table.field('barytime')[i]) and \
                            np.isfinite(table.field(datacol)[i]):
                        table[naxis2] = table[i]
                        naxis2 += 1
                        instr[1].data = table[:naxis2]
            except:
                for i in range(len(table.field(0))):
                    if np.isfinite(table.field('time')[i]) and \
                            np.isfinite(table.field(datacol)[i]):
                        table[naxis2] = table[i]
                        naxis2 += 1
                        instr[1].data = table[:naxis2]


#            comment = 'NaN cadences removed from data'
#            status = kepkey.new('NANCLEAN',True,comment,instr[1],outfile,logfile,verbose)

# read table columns

    if status == 0:
        try:
            intime = instr[1].data.field('barytime') + 2.4e6
        except:
            intime, status = kepio.readfitscol(inputfile, instr[1].data,
                                               'time', logfile, verbose)

        indata, status = kepio.readfitscol(inputfile, instr[1].data, datacol,
                                           logfile, verbose)
        inerr, status = kepio.readfitscol(inputfile, instr[1].data, errorcol,
                                          logfile, verbose)
    if status == 0:
        intime = intime + bjdref
        indata = indata / cadenom
        inerr = inerr / cadenom

    if status == 0 and norm:
        #first remove outliers before normalizing
        threesig = 3. * np.std(indata)
        mask = np.logical_and(indata < indata + threesig,
                              indata > indata - threesig)
        #now normalize
        indata = indata / np.median(indata[mask])

    if status == 0:
        #need to check if LD params are sensible and in right format
        LDparams = [float(i) for i in LDparams.split()]

        inc = inc * np.pi / 180.

    if status == 0:
        modelfit = tmod.lightcurve(intime, period_d, rprs, T0, Ecc, ars, inc,
                                   omega, LDparams, sec)

    if status == 0:
        phi, fluxfold, modelfold, errorfold, phiNotFold = fold_data(
            intime, modelfit, indata, inerr, period_d, T0)

    if status == 0:
        do_plot(intime, modelfit, indata, inerr, period_d, T0, cmdLine)
示例#11
0
def keptransit(inputfile, outputfile, datacol, errorcol, periodini_d,
               rprsini, T0ini, Eccini, arsini, incini, omegaini,
               LDparams, secini,fixperiod, fixrprs, fixT0, fixEcc, fixars,
               fixinc, fixomega, fixsec, fixfluxoffset, removeflaggeddata,
               ftol=0.0001, fitter='nothing', norm=False, clobber=False,
               plot=True, verbose=False, logfile='keptransit.log'):
    """
    tmod.lightcurve(xdata,period,rprs,T0,Ecc,ars, incl, omega, ld, sec)

    input transit parameters are
    Period in days
    T0
    rplanet / rstar
    a / rstar
    inclination

    limb darkening code number:
    0 = uniform
    1 = linear
    2 = quadratic
    3 = square root
    4 = non linear

    LDarr:
    u      -- linear limb-darkening (set NL=1)
    a, b   -- quadratic limb-darkening (set NL=2)
    c,  d  -- root-square limb-darkening (set NL= -2)
    a1, a2, a3, a4 -- nonlinear limb-darkening  (set NL=4)
    Nothing at all -- uniform limb-darkening (set NL=0)

    Written by: Tom Barclay

    This code is intended to fit a transit model to a Kepler light curve.
    We assume that the data has been cleaned in some way to remove instrumental
    signals and stellar variability.

    Reference:
    The transit model a Mandel and Agol model
    <http://adsabs.harvard.edu/abs/2002ApJ...580L.171M>.

    This code calls a module called lightcurve
    This code was created by Ian Crossfield <http://www.astro.ucla.edu/~ianc/>
    and Susanne Aigraine.

    The lighcurve module has been modified by TSB in order to sample the model
    on a finer grid than the original data.

    """
    #write to a logfile
    hashline = '--------------------------------------------------------------'
    kepmsg.log(logfile, hashline, verbose)
    call = ('KEPTRANSIT -- '
            + ' inputfile={}'.format(inputfile)
            + ' outputfile={}'.format(outputfile)
            + ' datacol={}'.format(datacol)
            + ' errorcol={}'.format(errorcol)
            + ' periodini_d={}'.format(periodini_d)
            + ' rprsini={}'.format(rprsini)
            + ' T0ini={}'.format(T0ini)
            + ' Eccini={}'.format(Eccini)
            + ' arsini={}'.format(arsini)
            + ' incini={}'.format(incini)
            + ' omegaini={}'.format(omegaini)
            + ' LDparams={}'.format(LDparams)
            + ' secini={}'.format(secini)
            + ' fixperiod={}'.format(fixperiod)
            + ' fixrprs={}'.format(fixrprs)
            + ' fixT0={}'.format(fixT0)
            + ' fixEcc={}'.format(fixEcc)
            + ' fixars={}'.format(fixars)
            + ' fixinc={}'.format(fixinc)
            + ' fixomega={}'.format(fixomega)
            + ' fixsec={}'.format(fixsec)
            + ' fixfluxoffset={}'.format(fixfluxoffset)
            + ' removeflaggeddata={}'.format(removeflaggeddata)
            + ' ftol={}'.format(ftol)
            + ' fitter={}'.format(fitter)
            + ' norm={}'.format(norm)
            + ' plot={}'.format(plot)
            + ' clobber={}'.format(clobber)
            + ' verbose={}'.format(verbose)
            + ' logfile={}'.format(logfile))

    kepmsg.log(logfile, call+'\n', verbose)
    kepmsg.clock('KEPTRANSIT started at', logfile, verbose)

    # clobber output file
    if clobber:
        kepio.clobber(outputfile, logfile, verbose)
    if kepio.fileexists(outputfile):
        errmsg = 'ERROR -- KEPTRANSIT: {} exists. Use clobber=yes'.format(outputfile)
        kepmsg.err(logfile, errmsg, verbose)

    # open input file
    instr = pyfits.open(inputfile, 'readonly')
    tstart, tstop, bjdref, cadence = kepio.timekeys(instr, inputfile, logfile,
                                                    verbose)
    try:
        work = instr[0].header['FILEVER']
        cadenom = 1.0
    except:
        cadenom = cadence

    # fudge non-compliant FITS keywords with no values
    instr = kepkey.emptykeys(instr, inputfile, logfile, verbose)

    # read table structure
    table = kepio.readfitstab(inputfile, instr[1], logfile, verbose)

    intime_o = table.field('time')
    influx_o = table.field(datacol)
    inerr_o = table.field(errorcol)
    try:
        qualflag = table.field('SAP_QUALITY')
    except:
        qualflag = np.zeros(len(intime_o))

    intime, indata, inerr, baddata = cutBadData(intime_o, influx_o, inerr_o,
                                                removeflaggeddata, qualflag)

    if norm:
        #first remove outliers before normalizing
        threesig = 3.* np.std(indata)
        mask = np.logical_and(indata < indata + threesig, indata > indata - threesig)
        #now normalize
        indata = indata / np.median(indata[mask])

    #need to check if LD params are sensible and in right format
    LDparams = [float(i) for i in LDparams.split()]
    incini = incini * np.pi / 180.
    omegaini = omegaini * np.pi / 180.

    if arsini * np.cos(incini) > 1.0 + rprsini:
        errmsg = ("The guess inclination and a/r* values result in a"
                  " non-transing planet")
        kepmsg.err(logfile, errmsg, verbose)

    fixed_dict = fix_params(fixperiod, fixrprs, fixT0, fixEcc, fixars, fixinc,
                            fixomega, fixsec, fixfluxoffset)

    #force flux offset to be guessed at zero
    fluxoffsetini = 0.0

    guess_params = [periodini_d, rprsini, T0ini, Eccini, arsini, incini,
                    omegaini, secini, fluxoffsetini]

    print('cleaning done: about to fit transit')

    if fitter == 'leastsq':
        fit_output = leastsq(fit_tmod, guess_params,
                             args=(LDparams, intime, indata, inerr,
                                   fixed_dict, guess_params),
                             full_output=True, ftol=ftol)
    elif fitter == 'fmin':
        fit_output = fmin(fit_tmod2,guess_params,
                          args=(LDparams, intime, indata, inerr, fixed_dict,
                                guess_params),
                          full_output=True, ftol=ftol, xtol=ftol)
    elif fitter == 'basinhopping':
        fit_output = basinhopping(git_tmod2, guess_params,
                                  args=(LDparams, intime, indata, inerr,
                                        fixed_dict, guess_params),
                                  full_output=True, ftol=ftol, xtol=ftol)

    if fixed_dict['period']:
        newperiod = guess_params[0]
        print('Fixed period (days) = {}'.format(newperiod))
    else:
        newperiod = fit_output[0][0]
        print('Fit period (days) = {}'.format(newperiod))
    if fixed_dict['rprs']:
        newrprs = guess_params[1]
        print('Fixed R_planet / R_star = {}'.format(newrprs))
    else:
        newrprs = fit_output[0][1]
        print('Fit R_planet / R_star = {}'.format(newrprs))
    if fixed_dict['T0']:
        newT0 = guess_params[2]
        print('Fixed T0 (BJD) = {}'.format(newT0))
    else:
        newT0 = fit_output[0][2]
        print('Fit T0 (BJD) = {}'.format(newT0))
    if fixed_dict['Ecc']:
        newEcc = guess_params[3]
        print('Fixed eccentricity = {}'.format(newEcc))
    else:
        newEcc = fit_output[0][3]
        print('Fit eccentricity = {}'.format(newEcc))
    if fixed_dict['ars']:
        newars = guess_params[4]
        print('Fixed a / R_star = {}'.format(newars))
    else:
        newars = fit_output[0][4]
        print 'Fit a / R_star = {}'.format(newars)
    if fixed_dict['inc']:
        newinc = guess_params[5]
        print 'Fixed inclination (deg) = {}'.format(newinc* 180. / np.pi)
    else:
        newinc = fit_output[0][5]
        print 'Fit inclination (deg) = {}'.format(newinc* 180. / np.pi)
    if fixed_dict['omega']:
        newomega = guess_params[6]
        print 'Fixed omega = {}'.format(newomega)
    else:
        newomega = fit_output[0][6]
        print 'Fit omega = {}'.format(newomega)
    if fixed_dict['sec']:
        newsec = guess_params[7]
        print 'Fixed seconary eclipse depth = {}'.format(newsec)
    else:
        newsec = fit_output[0][7]
        print 'Fit seconary eclipse depth = {}'.format(newsec)
    if not fixfluxoffset:
        newfluxoffset = fit_output[0][8]
        print('Fit flux offset = {}'.format(newfluxoffset))

    modelfit = tmod.lightcurve(intime, newperiod, newrprs, newT0, newEcc,
                               newars, newinc, newomega, LDparams, newsec)

    if not fixfluxoffset:
        modelfit += newfluxoffset

    #output to a file
    phi, fluxfold, modelfold, errorfold, phiNotFold = fold_data(intime,
        modelfit, indata, inerr, newperiod, newT0)

    make_outfile(instr, outputfile, phiNotFold, modelfit, baddata)

    # end time
    kepmsg.clock('KEPTRANSIT completed at', logfile, verbose)

    if plot:
        do_plot(intime, modelfit, indata, inerr, newperiod, newT0)
示例#12
0
def keptransitmodel(inputfile,datacol,errorcol,period_d,rprs,T0,
    Ecc,ars,inc,omega,LDparams,sec,norm=False,
    verbose=0,logfile='logfile.dat',status=0,cmdLine=False):
    

    #write to a logfile
    hashline = '----------------------------------------------------------------------------'
    kepmsg.log(logfile,hashline,verbose)
    call = 'KEPTRANSIT -- '
    call += 'inputfile='+inputfile+' '
    call += 'datacol='+str(datacol)+' '
    call += 'errorcol='+str(errorcol)+' '
    call += 'period_d='+str(period_d)+' '
    call += 'rprs='+str(rprs)+' '
    call += 'T0='+str(T0)+' '
    call += 'Ecc='+str(Ecc)+' '
    call += 'ars='+str(ars)+' '
    call += 'inc='+str(inc)+' '
    call += 'omega='+str(omega)+' '
    call += 'LDparams='+str(LDparams)+' '
    call += 'sec='+str(sec)+' '
    #to finish


    # open input file

    if status == 0:
        instr, status = kepio.openfits(inputfile,'readonly',logfile,verbose)
    if status == 0:
        tstart, tstop, bjdref, cadence, status = kepio.timekeys(instr,
            inputfile,logfile,verbose,status)
    if status == 0:
        try:
            work = instr[0].header['FILEVER']
            cadenom = 1.0
        except:
            cadenom = cadence


    # fudge non-compliant FITS keywords with no values

    if status == 0:
        instr = kepkey.emptykeys(instr,file,logfile,verbose)

# read table structure

    if status == 0:
        table, status = kepio.readfitstab(inputfile,instr[1],logfile,verbose)

# filter input data table

    if status == 0:
        try:
            nanclean = instr[1].header['NANCLEAN']
        except:
            naxis2 = 0
            try:
                for i in range(len(table.field(0))):
                    if np.isfinite(table.field('barytime')[i]) and \
                            np.isfinite(table.field(datacol)[i]):
                        table[naxis2] = table[i]
                        naxis2 += 1
                        instr[1].data = table[:naxis2]
            except:
                for i in range(len(table.field(0))):
                    if np.isfinite(table.field('time')[i]) and \
                            np.isfinite(table.field(datacol)[i]):
                        table[naxis2] = table[i]
                        naxis2 += 1
                        instr[1].data = table[:naxis2]
#            comment = 'NaN cadences removed from data'
#            status = kepkey.new('NANCLEAN',True,comment,instr[1],outfile,logfile,verbose)
 
# read table columns

    if status == 0:
        try:
            intime = instr[1].data.field('barytime') + 2.4e6
        except:
            intime, status = kepio.readfitscol(inputfile,instr[1].data,'time',logfile,verbose)
        
        indata, status = kepio.readfitscol(inputfile,instr[1].data,datacol,logfile,verbose)
        inerr, status = kepio.readfitscol(inputfile,instr[1].data,errorcol,logfile,verbose)
    if status == 0:
        intime = intime + bjdref
        indata = indata / cadenom
        inerr = inerr / cadenom

    if status == 0 and norm:
        #first remove outliers before normalizing
        threesig = 3.* np.std(indata)
        mask = np.logical_and(indata< indata + threesig,indata > indata - threesig)
        #now normalize
        indata = indata / np.median(indata[mask])

    if status == 0:
        #need to check if LD params are sensible and in right format
        LDparams = [float(i) for i in LDparams.split()]

        inc = inc * np.pi / 180.


    if status == 0:
        modelfit = tmod.lightcurve(intime,period_d,rprs,T0,Ecc,
            ars,inc,omega,LDparams,sec)

    if status == 0:
        phi, fluxfold, modelfold, errorfold, phiNotFold = fold_data(intime, 
            modelfit,indata,inerr,period_d,T0)

    if status == 0:
        do_plot(intime,modelfit,indata,inerr,period_d,T0,cmdLine)