Ejemplo n.º 1
0
    def fit(self,):
        """ 
	call the fitter
	
	"""
	x = self.spectrum.wavelength
	y = self.spectrum.flux
	err = self.spectrum.fluxerr
	# build initial parameter value list 
        p0 = []
	pinfo = []
        for x in self.fit_parameters:
	   par = x["parinfo"]
	   for pv in par:
               p0.append(pv['value'])
	       pinfo.append(pv)
	   
        # build argument list
        fkw={'x':x,'y':y,'err':err}
	   
	# call L-M fitter   
        Z = mpfit.mpfit(fit_function,p0,functkw=fkw,parinfo=pinfo,quiet=True)
        if (Z.status <= 0): print 'fit_spectrum.mpfit error message = ', Z.errmsg
	
	# update the fit (parinfo...?), return results
	self.result = Z  
        return Z	    
Ejemplo n.º 2
0
 def execute(self, stack_time, stack_flux, stack_er):
     p0 = [
         0.2640, 1.392, -0.1398, 2.54017, 0.001593, 0.9994, 0.000455, 3.52,
         0.13, 5.61, 0.78, 0.76, 0.001
     ]
     parinfo = self.getParamInfo()
     fa = {"x": stack_time, "y": stack_flux, "err": stack_er}
     self.m = mpfit(self.lightcurveFunc, p0, functkw=fa, parinfo=parinfo)
Ejemplo n.º 3
0
def chi2colorfit(datfile, clobber=False, Nsim=20000):
    """do chi2 fitting to a supernova light 
    curve using SNANA simulations.  Keep color
    as a free parameter"""
    sn = snana.SuperNova(SNDATA_ROOT + '/SIM/' + datfile)
    sn.getClassSim(Nsim=Nsim, clobber=clobber)

    #Type Ia chi-squared
    mIa = zeros([len(sn.ClassSim.Ia.PTROBS_MIN), len(sn.MJD)])
    for MJD, FLT, i in zip(sn.MJD, sn.FLT, range(len(sn.MJD))):
        sn.ClassSim.Ia.samplephot(MJD)
        mIa[:, i] = sn.ClassSim.Ia.__dict__['%s%i' % (FLT, int(MJD))]

    chisqIa = []
    Iaparams = []
    for i in range(len(sn.ClassSim.Ia.PTROBS_MIN)):
        if not len(where(mIa[i, :] == 99)[0]):
            fa = {
                'x': sn.MJD,
                'y': sn.FLUXCAL,
                'err': zeros(len(sn.MJD)),
                'model_mag': mIa[i, :],
                'flt': sn.FLT
            }
            mvals = mpfit.mpfit(lsfunc_color,
                                ones(len(unique(sn.FLT))),
                                functkw=fa)
            Iaparams = Iaparams + [mvals.params]

            scale = ones(len(sn.FLT))
            for f, j in zip(unique(sn.FLT), range(len(unique(sn.FLT)))):
                row = where(sn.FLT == f)[0]
                scale[row] = mvals.params[j]
            model = array(scale) * 10**(-0.4 * (mIa[i, :] - 27.5))

            chisqIa = chisqIa + [
                sum((model - sn.FLUXCAL)**2 / sn.FLUXCALERR**2)
            ]

    #Type Ib/c chi-squared
    mIbc = zeros([len(sn.ClassSim.Ibc.PTROBS_MIN), len(sn.MJD)])
    for MJD, FLT, i in zip(sn.MJD, sn.FLT, range(len(sn.MJD))):
        sn.ClassSim.Ibc.samplephot(MJD)
        mIbc[:, i] = sn.ClassSim.Ibc.__dict__['%s%i' % (FLT, int(MJD))]

    chisqIbc = []
    Ibcparams = []
    count = 0
    for i in range(len(sn.ClassSim.Ibc.PTROBS_MIN)):
        if not len(where(mIbc[i, :] == 99)[0]):
            count = count + 1
            fa = {
                'x': sn.MJD,
                'y': sn.FLUXCAL,
                'err': zeros(len(sn.MJD)),
                'model_mag': mIbc[i, :],
                'flt': sn.FLT
            }
            mvals = mpfit.mpfit(lsfunc_color,
                                ones(len(unique(sn.FLT))),
                                functkw=fa)
            Ibcparams = Ibcparams + [mvals.params]

            scale = ones(len(sn.FLT))
            for f, j in zip(unique(sn.FLT), range(len(unique(sn.FLT)))):
                row = where(sn.FLT == f)[0]
                scale[row] = mvals.params[j]
            model = array(scale) * 10**(-0.4 * (mIbc[i, :] - 27.5))

            chisqIbc = chisqIbc + [
                sum((model - sn.FLUXCAL)**2 / sn.FLUXCALERR**2)
            ]

    #Type II chi-squared
    mII = zeros([len(sn.ClassSim.II.PTROBS_MIN), len(sn.MJD)])
    for MJD, FLT, i in zip(sn.MJD, sn.FLT, range(len(sn.MJD))):
        sn.ClassSim.II.samplephot(MJD)
        mII[:, i] = sn.ClassSim.II.__dict__['%s%i' % (FLT, int(MJD))]

    chisqII = []
    IIparams = []
    for i in range(len(sn.ClassSim.II.PTROBS_MIN)):
        if not len(where(mII[i, :] == 99)[0]):
            fa = {
                'x': sn.MJD,
                'y': sn.FLUXCAL,
                'err': zeros(len(sn.MJD)),
                'model_mag': mII[i, :],
                'flt': sn.FLT
            }
            mvals = mpfit.mpfit(lsfunc_color,
                                ones(len(unique(sn.FLT))),
                                functkw=fa)
            IIparams = IIparams + [mvals.params]

            scale = ones(len(sn.FLT))
            for f, j in zip(unique(sn.FLT), range(len(unique(sn.FLT)))):
                row = where(sn.FLT == f)[0]
                scale[row] = mvals.params[j]
            model = array(scale) * 10**(-0.4 * (mII[i, :] - 27.5))

            chisqII = chisqII + [
                sum((model - sn.FLUXCAL)**2 / sn.FLUXCALERR**2)
            ]

    print """Type Ia SNe have minimum chi squared: %.2f
computed from %.f SNe""" % (min(chisqIa), len(chisqIa))
    print """Type Ibc SNe have minimum chi squared: %.2f
computed from %.f SNe""" % (min(chisqIbc), len(chisqIbc))
    print """Type II SNe have minimum chi squared: %.2f
computed from %.f SNe""" % (min(chisqII), len(chisqII))

    #now compute the likelihoods
    eIa = exp(-array(chisqIa) / 2.)
    eIbc = exp(-array(chisqIbc) / 2.)
    eII = exp(-array(chisqII) / 2.)

    chiIa = sum(exp(-array(chisqIa) / 2.))
    chiIbc = sum(exp(-array(chisqIbc) / 2.))
    chiII = sum(exp(-array(chisqII) / 2.))

    p_Ia = chiIa / (chiIa + chiIbc + chiII)
    p_Ibc = chiIbc / (chiIa + chiIbc + chiII)
    p_II = chiII / (chiIa + chiIbc + chiII)

    print """likelihoods:
Type Ia   Type Ib/c  Type II
%.4f      %.4f       %.4f""" % (p_Ia, p_Ibc, p_II)

    print """odds ratios:
Type Ia/Ib/c  Type Ia/II
%.4f      %.4f""" % (chiIa / chiIbc, chiIa / chiII)

    Iarow = where(chisqIa == min(chisqIa))[0][0]
    Ibcrow = where(chisqIbc == min(chisqIbc))[0][0]
    IIrow = where(chisqII == min(chisqII))[0][0]

    return mIa, mIbc, mII, eIa / chiIa, eIbc / chiIbc, eII / chiII, Iarow, Ibcrow, IIrow, Iaparams, Ibcparams, IIparams
Ejemplo n.º 4
0
def annealFit(session, spinwave_domain, spinwave_range, spinwave_range_Err, size=3, k = 100, tMin = .001, tMax = 15, tFactor = .95, MCeveryTime = True, recordKeeperCallback = None):
    # Create fitter
    fitter = PM.Fitter(session, spinwave_domain, size, k, tMin, tMax, tFactor, MCeveryTime)
    #testFile = open("/home/tom/Desktop/annealOutput1.txt", 'w')
    #testFile = open("C:\\annealOutput1.txt", 'w')
    
    # Helper function for GetResult
    def myfunc(p, y=None, err=None, callback = None):
        """returns Chi Squared to be minimized."""
        if callback:
            callback(p)
            
        #testFile.write('\np: ' + str(p))
        #testFile.flush()
        fitter.fit_list = p
        model = fitter.GetResult()
        #print 'y:\n', y, '\n\nmodel:\n', model
        #for i in range(len(y)):
        #    testFile.write("  p: p %3.5f y %3.5f model %3.5f err %3.5f"%(p,y[i],model[i],err[i]) )
        result = (y-model)/err
        chi_sq = 0
        for entry in result:
            #print "entry: ", entry
            chi_sq += math.pow(entry, 2)
        #print '\n\nresult:\n', result
        #print "\nchi_sq: " + str(chi_sq)
        #testFile.write("\nchi_sq: " + str(chi_sq))
        #testFile.flush()
        return chi_sq

    # Function Keywords
    y = spinwave_range
    err = spinwave_range_Err
    p0 = fitter.fit_list
    #testFile.write("initial p: " + str(p0))
    
    #_______________________ Testing _____________________________
    #START = -10
    #STOP = 10
    #step = .01
    
    #FILE = "C:\\CHISQ_points3.txt"
    
    ##plot
    
    #handle = open(FILE, 'w')
    ##handle.write("data: "+ str(y))
    ##handle.flush()
    #for i in range((STOP-START)/step):
	#x = START + i*step
	#val = myfunc([x], y, err)
	#if i != 0:
	    #handle.write("\n")
	#handle.write(str(x) + " " + str(val))
    #handle.close()
    #sys.exit()
	
	
    #_____________________________________________________________________


    result=anneal(myfunc,p0,args=(y,err, recordKeeperCallback), schedule='simple',lower=fitter.min_range_list,upper=fitter.max_range_list,
                  maxeval=None, maxaccept=None,dwell=50, maxiter=2000, full_output=1)
    
    print "annealing result: ", result
    p = result[0]
    myfunc(p, y, err)#To propogate final value

    
    #----Now Localy optimize with mpfit to fine tune the answer -----------
    def mpfitfunc(p, fjac=None, y=None, err=None, callback = None):
        if callback:
            callback(p)
	#testFile.write("mpfit: " + str(p))
        fitter.fit_list = p
        model = fitter.GetResult()
        status = 0
        print 'y:\n', y, '\n\nmodel:\n', model
        #print '\n\ny-model:\n', (y-model)
        #print '\n\nerr:\n', err
        result = (y-model)/err
        print '\n\nresult:\n', result
        return [status, result]
    
    fa = {'y':y, 'err':err, 'callback':recordKeeperCallback}
    
    # Set parinfo with the limits and such. Probably don't need
    parbase={'value':0., 'limited':[0,0], 'limits':[0.,0.]}
    parinfo=[]
    p0 = fitter.fit_list
    for i in range(len(p0)):
        parinfo.append(copy.deepcopy(parbase))
    for i in range(len(p0)):
        parinfo[i]['value']=p0[i]
        if(fitter.min_range_list[i] != np.NINF):
            parinfo[i]['limits'][0]=fitter.min_range_list[i]
            parinfo[i]['limited'][0] = 1
        else:
            parinfo[i]['limited'][0] = 0
        if fitter.max_range_list[i] != np.PINF:
            parinfo[i]['limits'][1] = fitter.max_range_list[i]
            parinfo[i]['limited'][1] = 1
        else:
            parinfo[i]['limited'][1] = 0

    # Run mpfit on fitlist with all the jazz.
    print "params: ", p0
    print "parinfo: ", parinfo
    m = mpfit(mpfitfunc, p0, parinfo=parinfo, functkw = fa)
    #testFile.write("\nresult: " + str(result))
    #testFile.write("\nm: " + str(m))
    #testFile.close()
    return (m.status, m.params, m.perror)
Ejemplo n.º 5
0
def fitting(session, spinwave_domain, spinwave_range, spinwave_range_Err, size=3, k = 100, tMin = .001, tMax = 15, tFactor = .95, MCeveryTime = True, recordKeeperCallback = None):

    # Create fitter
    fitter = PM.Fitter(session, spinwave_domain, size, k, tMin, tMax, tFactor, MCeveryTime)
    
    # Helper function for GetResult
    def myfunc(p, fjac=None, y=None, err=None, callback = None):
        if callback:
            callback(p)
        fitter.fit_list = p
        model = fitter.GetResult()
        status = 0
        print 'y:\n', y, '\n\nmodel:\n', model
        #print '\n\ny-model:\n', (y-model)
        #print '\n\nerr:\n', err
        result = (y-model)/err
        print '\n\nresult:\n', result
        return [status, result]

    # Function Keywords
    
    #spinwave_domain is a list of 3D lists:
    #-[(x1,y1,z1),(x2,y2,z2),...]
    #x must be a 1D numpy array:
    #[x1,y1,z1,x2,t2,z2,...]
    #xList = []
    #for point in fit.spinwave_domain:
    #    xList.append(point[0])
    #    yList.append(point[1])
    #    zList.append(point[2])
    #x = np.array(xList)
    #y = myfunc(fit)
    y = spinwave_range
    #errVal = .001
    #err = [errVal]*len(y)
    err = spinwave_range_Err
    #fa = {'x':x, 'y':y, 'err':err}
    fa = {'y':y, 'err':err, 'callback':recordKeeperCallback}
    
    # Set parinfo with the limits and such. Probably don't need
    parbase={'value':0., 'limited':[0,0], 'limits':[0.,0.]}
    parinfo=[]
    p0 = fitter.fit_list
    for i in range(len(p0)):
        parinfo.append(copy.deepcopy(parbase))
    for i in range(len(p0)):
        parinfo[i]['value']=p0[i]
        if(fitter.min_range_list[i] != np.NINF):
            parinfo[i]['limits'][0]=fitter.min_range_list[i]
            parinfo[i]['limited'][0] = 1
        else:
            parinfo[i]['limited'][0] = 0
        if fitter.max_range_list[i] != np.PINF:
            parinfo[i]['limits'][1] = fitter.max_range_list[i]
            parinfo[i]['limited'][1] = 1
        else:
            parinfo[i]['limited'][1] = 0

    # Run mpfit on fitlist with all the jazz.
    print "params: ", p0
    print "parinfo: ", parinfo
    m = mpfit(myfunc, p0, parinfo=parinfo, functkw = fa)
    # Bare Bones Run for when the above (especially keywords x) breaks instantly
    #m = mpfit(myfunc, fit.fitlist)
    
    #Return the parameters
    return (m.status, m.params, m.perror)
Ejemplo n.º 6
0
def plot_planet(obj=None,caltype=None,nobs=None):

    sectdatapath='../data/FTS/sect_planets/'
    ftsdatapath='../data/FTS/'
    modelfile=None
    mc=False

    if obj == 'saturn':
        datapath=sectdatapath
        nobs=nobs
        d_plt_ini=16.
        obsid=['1342198279','1342224754','1342247750']
        dobs=[17.7,16.7,17.4]
        suffix=''
        modelfile='spire_JanskyGHz.dat'
        ftspsfile='./v11/Saturn/'+obsid[nobs]+ \
            '_spectrum_point_HR_unapod_18Apr2013' \
            +suffix+'.fits'
        dtrue=dobs[nobs]
        scale=(dtrue/dobs[0])**2.
        nskip=3
        munit=1.
        uplot=1e-3
        unit='kJy'
        yrange=[3.,40.]
        sim_func=sim_planet
        psuf='_v11_'+str(nobs)

    if obj == 'mars':
        datapath=sectdatapath
        d_plt_ini=6.
        nobs=nobs
        modelfile='MarsModel_OD176.txt'
        obsid=['1342193675', '1342197462', '1342198930', \
                   '1342231056', '1342231059', '1342231062', \
                   '1342231064', '1342231070', '1342231076', \
                   '1342231079', '1342231085', '1342245848', \
                   '1342247563', '1342247571']
        dobs=[8.8,6.0,5.4,5.5,5.5,5.5, \
                  5.5,5.5,5.5,5.5,5.5,8.8,6.6,6.6]
        ftspsfile='./v11/Mars/'+obsid[nobs]+'_spectrum_' \
            'point_HR_unapod_18Apr2013.fits'
        dtrue=dobs[nobs]
        scale=(dtrue/5.5)**2.
        nskip=2
        munit=1e3
        uplot=1e-3
        unit='kJy'
        yrange=[0.5,20.]
        sim_func=sim_planet
        psuf='_v11_'+str(nobs)

    if obj == 'neptune':
        datapath=sectdatapath
        d_plt_ini=2.
        dtrue=2.28
        modelfile='0x5000AD87_model_HR.fits'
        obsid='1342221703'
        ftspsfile='./v10/'+obsid+'_spectrum_' \
            'point_HR_unapod_v10.fits'
        scale=1.
        uplot=1.
        unit='Jy'
        yrange=[20.,300.]
        sim_func=sim_planet
        psuf=''

    if obj == 'uranus':
        datapath=sectdatapath
        d_plt_ini=3.
        dtrue=3.55
        modelfile='5001389B_model_HR.fits'
        obsid='1342257307'
        ftspsfile='./v10/'+obsid+'_spectrum_' \
            'point_HR_unapod_v10.fits'
        scale=1.
        uplot=1.
        unit='Jy'
        yrange=[90.,600.]
        sim_func=sim_planet
        psuf=''

    if obj == 'm83' or obj == 'M83':
        datapath=ftsdatapath
        modelfile=''
        d_plt_ini=18.
        ftspsfile='M83/HIPE.9.0.2742/unapodize/' \
            '1342212345_avgspectrum_HR_unapod_0_6.fits'
        ftsexfile='M83/HIPE.9.0.2742/unapodize/' \
            '1342212345_avgspectrum_HR_unapod_0_6.fits'
        yrange=[0.1,300.]
        uplot=1.
        unit='Jy'
        sim_func=sim_gauss
        psuf=''

    if obj == 'm82' or obj == 'M82':
        datapath=ftsdatapath
        modelfile=''
        d_plt_ini=22.
        ftspsfile='M82/HIPE.8.0.3384/unapodize/' \
            '1342208388_avgspectrum_HR_unapod_0_6.fits'
        ftsexfile='M82/HIPE.8.0.3384/unapodize/' \
            '1342208388_avgspectrum_HR_unapod_0_6.fits'
        yrange=[1.,2000.]
        uplot=1.
        unit='Jy'
        sim_func=sim_gauss
        psuf=''

    if obj == 'ngc4214' or obj == 'NGC4214':
        datapath=ftsdatapath
        modelfile=''
        d_plt_ini=18.
        ftspsfile=obj.upper()+'/HIPE.11.0.2785/unapodize/' \
            '1342256082_spectrum_point_HR_unapod.fits'
        ftsexfile='M83/HIPE.11.0.2785/unapodize/' \
            '1342256082_spectrum_extended_HR_unapod.fits'
        yrange=[0.01,20.]
        uplot=1.
        unit='Jy'
        sim_func=sim_gauss
        psuf=''

    if caltype == 'point':
        ftsfile=pyfits.open(datapath+ftspsfile)
    if caltype == 'extended':
        ftsfile=pyfits.open(datapath+ftsexfile)

    ftsfile.verify('silentfix')
    ctrxy=array([128,128])

    # ======= Read model spectrum of the planet =========

    if bool(modelfile):

        if modelfile[-4:] != 'fits':

            spec_mod=open('../data/FTS/sect_planets/'+modelfile)
            modline=spec_mod.readlines()
            smfreq=[]
            smkjy=[]

            for i in range(len(modline)/10-nskip):
                ii=i*10+nskip
                temp=None
                temp=modline[ii].split()
                smfreq.append(double(temp[0]))
                smkjy.append(double(temp[len(temp)-1]))
                mfreq=array(smfreq)
                mkjy=array(smkjy).copy()/munit

            if obj == 'mars':
                    
                mfreq=3e5/array(smfreq)
                scalem=0.
                
                for np in range(len(modelwn)):
                    
                    anp=abs(mfreq-modelwn[np]*30.)
                    idxnp=where(anp == min(anp))
                    scalem=scalem+(1e-3*(fluxLellouch[np]+fluxRudy[np])/2.)/ \
                        mkjy[idxnp[0][0]]
                    
                scalem=scalem/float(len(modelwn))
                
                mkjy=scalem*mkjy.copy()

        else:

            model=pyfits.open('../data/FTS/sect_planets/'+modelfile)
            model.verify('silentfix')
            nover=len((where(model['SSWD4'].data['wave'] <= \
                            model['SLWC3'].data['wave'].max()))[0])
            mslw=model['SLWC3'].data
            mssw=model['SSWD4'].data
            nmod=len(mslw['flux'])+len(mssw['flux'])-nover

            mfreq=zeros(nmod)
            mkjy=zeros(nmod)

            mfreq[0:len(mslw['flux'])]= \
                mslw['wave'][0:len(mslw['flux'])]
            mfreq[len(mslw['flux']):]=mssw['wave'][nover:]

            mkjy[0:(len(mslw['flux'])-nover)]= \
                mslw['flux'][0:(len(mslw['flux'])-nover)]
            mkjy[(len(mslw['flux'])-nover):len(mslw['flux'])]= \
                0.5*(mslw['flux'][(len(mslw['flux'])-nover):]+ \
                         mssw['flux'][0:nover])
            mkjy[len(mslw['flux']):]=mssw['flux'][nover:]
            

    # ======== Construct planet light distribution image =========

    [chiparam,chierr,dplt]=find_best_d(ftsfile,d_plt_ini, \
                                    caltype=caltype,obj=obj)
    prob=exp(-(chiparam-chiparam.min())/chiparam.min())
    mindx=where(chiparam == chiparam.min())
    mindx=mindx[0][0]
    proberr=zeros(len(prob))+1.
#    proberr=sqrt((chierr**2.+chiparam[mindx]**2.)) #\
#                     +(chiparam*chierr[mindx]/chiparam[mindx]**2.)**2.)

    figure(10)
    plot(dplt,prob,marker='*')
    fa={'x':dplt,'y':prob,'err':proberr}
    p_info=[{'value':d_plt_ini,'fixed':0, \
                 'limited':[1,1],'limits':[0.,100.]}, \
                {'value':2.,'fixed':0, \
                     'limited':[1,1],'limits':[0.,100.]}]
    params=mpfit.mpfit(fit_likelihood,functkw=fa,maxiter=1000,parinfo=p_info)
    dplt_g=dplt[0]+arange(101)*(dplt[-1]-dplt[0])/100.
    yy=fit_gaussian(dplt_g,params.params[0],params.params[1])
    plot(dplt_g,yy)
    xlim([dplt[0],dplt[-1]])
    ylim([0.,1.2])
    xlabel('Diameter (arcsec)')
    ylabel('exp(chi-param)')
    annotate('$\mu$ = {:.2f} (arcsec)'.format(params.params[0]), \
                 [dplt_g[0],1.1])
    annotate('$\sigma$ = {:.2f} (arcsec)'.format(params.params[1]), \
                 [dplt_g[0],1.0])
    savefig(plotdir+obj+'_d_fit'+psuf+'.png',format='PNG')
    close(10)

#    dplanet=params.params[0]
    dplanet=params.params[0]
    planet_mod=sim_func(dplanet,ctrxy)
    planet_area=sum(planet_mod)
    if obj == 'saturn':
        mod1=sim_gauss(12.,ctrxy)
        mod1_area=sum(mod1)
        mod2=sim_exp(4.,ctrxy)
        mod2_area=sum(mod2)

    # ======== Correcting the FTS Spectra ==========

    figure(0,figsize=[8.,8.])
    subplot(111)
    title('Correction on the '+obj.capitalize()+' FTS Spectrum',fontsize='large')
#    suptitle('$\\theta_{D}=$'+'{:.2f}'.format(params.params[0]) \
#                 +'   $\\theta_{obs}=$'+'{:.2f}'.format(dtrue))

    out=pyfits.HDUList()
    for i in range(2):
        if i == 0:
            wn=wn_ssw
            beam=beam_ssw
            fwhm=fwhm_ssw
            rtel=telrsrf[1]
            iro='blue'
            ni='SSW'
            deti='SSWD4'
        if i == 1:
            wn=wn_slw
            beam=beam_slw
            fwhm=fwhm_slw
            rtel=telrsrf[2]
            iro='red'
            ni='SLW'
            deti='SLWC3'

        fts=ftsfile[deti]

        if (obj == 'm83' or obj == 'M83') or \
                (obj == 'm82' or obj == 'M82'):
            fts.data['flux'][:]= \
                fts.data['flux'].copy()*cps[deti].data['pointConv']

        beam_area=[]
        beam_planet=[]
        if obj == 'saturn':
            beam_mod1=[]
            beam_mod2=[]
        for j in range(len(wn[0].data)):

            beam_area.append(sum(beam[0].data[j,:,:]))
            beam_planet.append(sum(beam[0].data[j,:,:]*planet_mod))
            if obj == 'saturn':
                beam_mod1.append(sum(beam[0].data[j,:,:]*mod1))
                beam_mod2.append(sum(beam[0].data[j,:,:]*mod2))

        a_beam=None
        ps_coup=None
        eta_mb=None
        a_beam=array(beam_area)

        if i == 0:
            assw=a_beam.copy()
        if i == 1:
            aslw=a_beam.copy()

        ps_coup=array(beam_planet)

        if obj == 'saturn':
            pmod1_coup=array(beam_mod1)
            pmod2_coup=array(beam_mod2)

        x=wn[0].data*30.   # change the wave number to GHz
        fab=interpolate.interp1d(x,a_beam, \
                                     bounds_error=False,fill_value=a_beam[0])
        fps=interpolate.interp1d(x,ps_coup, \
                                     bounds_error=False,fill_value=ps_coup[0])
        if obj == 'saturn':
            fmod1=interpolate.interp1d(x,pmod1_coup, \
                                         bounds_error=False,fill_value=pmod1_coup[0])
            fmod2=interpolate.interp1d(x,pmod2_coup, \
                                         bounds_error=False,fill_value=pmod2_coup[0])
            
        xp=ftsfile[deti].data['wave']
        ypa=ftsfile[deti].data['flux']*uplot
        rs=rtel.data['rsrf']/cps[deti].data['pointConv']* \
            fps(xp)/planet_area

        if caltype == 'point':
            correction=rtel.data['rsrf']/(rs*cps[deti].data['pointConv'])

        if caltype == 'extended':
            correction=rtel.data['rsrf']/rs

        ypb=ypa.copy()*correction
        if obj == 'saturn':
            ypb1=ypb/(planet_area/fps(xp)*fmod1(xp)/mod1_area)
            ypb2=ypb/(planet_area/fps(xp)*fmod2(xp)/mod2_area)
            fill_between(xp,ypb1,ypb2,color='gray',alpha=0.5)
            exec('foo'+str(i)+'=ypb1')
            exec('bar'+str(i)+'=ypb2')
        
        plot(xp,ypa,'--',color=iro,label=ni+' '+caltype,linewidth=1.)
        plot(xp,ypb,'-',color=iro,linewidth=1.,label=ni+' corrected')
        fts.data['flux'][:]=ypb[:]
        fts.data['error'][:]=fts.data['error']*correction
        out.append(fts)

        tempfts=fts.copy()

        if bool(modelfile):
            if modelfile[-4:] != 'fits':
                idx=(mfreq >=xp[0]-5.) & (mfreq <= xp[-1]+5.)
                fmod=interpolate.interp1d(mfreq[idx],mkjy[idx], \
                                              bounds_error=False, \
                                              fill_value=mkjy[-1])
                tempfts.data['flux'][:]=fmod(xp)*scale/ypb
            else:
                idx=(mfreq >= xp[0]) & (mfreq <= xp[-1])
                tempfts.data['flux'][:]=scale*mkjy[idx]/ypb

            tempfts.data['error'][:]=0.
            tempfts.data['mask'][:]=0.
            tempfts.name='GAMMA'+deti

            out.append(tempfts)


    if bool(modelfile):
        plot(mfreq,scale*mkjy,color='black',label='Model')
    if obj == 'mars':
        plot(modelwn*30.,scale*fluxLellouch*1e-3,linewidth=0.,marker='+', \
                 markersize=10.,color='black',markeredgewidth=2., \
                 label='Lellouch')
        plot(modelwn*30.,scale*fluxRudy*1e-3,linewidth=0.,marker='+', \
                 markersize=10.,color='red',markeredgewidth=2., \
                 label='Rudy')
    
    xlabel('Frequency (GHz)',fontsize='x-large')
    ylabel('Flux Density('+unit+')',fontsize='x-large')
    xlim([400.,1600.])
    ylim(yrange)
#    annotate('{:.2f}'.format(params.params[0]),[450.,0.95*yrange[0]])
    axvline(linewidth=3.,color='black')
    axhline(linewidth=3.,color='black')
    yscale('log')
    legend(loc=2)
    savefig(filename=plotdir+obj+psuf+'.png',format='PNG')
    close(0)    

    os.system('open %s%s%s.png &'%(plotdir,obj,psuf))
    out.writeto(plotdir+obj+'_correct'+psuf+'.fits',clobber=True, \
                    output_verify='ignore')

    return
Ejemplo n.º 7
0
def annealFit(session, spinwave_domain, spinwave_range, spinwave_range_Err, size=3, k = 100, tMin = .001, tMax = 15, tFactor = .95, MCeveryTime = True, recordKeeperCallback = None):
    # Create fitter
    fitter = PM.Fitter(session, spinwave_domain, size, k, tMin, tMax, tFactor, MCeveryTime)
    #testFile = open("/home/tom/Desktop/annealOutput1.txt", 'w')
    #testFile = open("C:\\annealOutput1.txt", 'w')
    
    # Helper function for GetResult
    def myfunc(p, y=None, err=None, callback = None):
        """returns Chi Squared to be minimized."""
        if callback:
            callback(p)
            
        #testFile.write('\np: ' + str(p))
        #testFile.flush()
        fitter.fit_list = p
        model = fitter.GetResult()
        #print 'y:\n', y, '\n\nmodel:\n', model
        #for i in range(len(y)):
        #    testFile.write("  p: p %3.5f y %3.5f model %3.5f err %3.5f"%(p,y[i],model[i],err[i]) )
        result = (y-model)/err
        chi_sq = 0
        for entry in result:
            #print "entry: ", entry
            chi_sq += math.pow(entry, 2)
        #print '\n\nresult:\n', result
        #print "\nchi_sq: " + str(chi_sq)
        #testFile.write("\nchi_sq: " + str(chi_sq))
        #testFile.flush()
        return chi_sq

    # Function Keywords
    y = spinwave_range
    err = spinwave_range_Err
    p0 = fitter.fit_list
    #testFile.write("initial p: " + str(p0))
    
    #_______________________ Testing _____________________________
    #START = -10
    #STOP = 10
    #step = .01
    
    #FILE = "C:\\CHISQ_points3.txt"
    
    ##plot
    
    #handle = open(FILE, 'w')
    ##handle.write("data: "+ str(y))
    ##handle.flush()
    #for i in range((STOP-START)/step):
	#x = START + i*step
	#val = myfunc([x], y, err)
	#if i != 0:
	    #handle.write("\n")
	#handle.write(str(x) + " " + str(val))
    #handle.close()
    #sys.exit()
	
	
    #_____________________________________________________________________


    result=anneal(myfunc,p0,args=(y,err, recordKeeperCallback), schedule='simple',lower=fitter.min_range_list,upper=fitter.max_range_list,
                  maxeval=None, maxaccept=None,dwell=50, maxiter=2000, full_output=1)
    
    print "annealing result: ", result
    p = result[0]
    myfunc(p, y, err)#To propogate final value

    
    #----Now Localy optimize with mpfit to fine tune the answer -----------
    def mpfitfunc(p, fjac=None, y=None, err=None, callback = None):
        if callback:
            callback(p)
	#testFile.write("mpfit: " + str(p))
        fitter.fit_list = p
        model = fitter.GetResult()
        status = 0
        print 'y:\n', y, '\n\nmodel:\n', model
        #print '\n\ny-model:\n', (y-model)
        #print '\n\nerr:\n', err
        result = (y-model)/err
        print '\n\nresult:\n', result
        return [status, result]
    
    fa = {'y':y, 'err':err, 'callback':recordKeeperCallback}
    
    # Set parinfo with the limits and such. Probably don't need
    parbase={'value':0., 'limited':[0,0], 'limits':[0.,0.]}
    parinfo=[]
    p0 = fitter.fit_list
    for i in range(len(p0)):
        parinfo.append(copy.deepcopy(parbase))
    for i in range(len(p0)):
        parinfo[i]['value']=p0[i]
        if(fitter.min_range_list[i] != np.NINF):
            parinfo[i]['limits'][0]=fitter.min_range_list[i]
            parinfo[i]['limited'][0] = 1
        else:
            parinfo[i]['limited'][0] = 0
        if fitter.max_range_list[i] != np.PINF:
            parinfo[i]['limits'][1] = fitter.max_range_list[i]
            parinfo[i]['limited'][1] = 1
        else:
            parinfo[i]['limited'][1] = 0

    # Run mpfit on fitlist with all the jazz.
    print "params: ", p0
    print "parinfo: ", parinfo
    m = mpfit(mpfitfunc, p0, parinfo=parinfo, functkw = fa)
    #testFile.write("\nresult: " + str(result))
    #testFile.write("\nm: " + str(m))
    #testFile.close()
    return (m.status, m.params, m.perror)
Ejemplo n.º 8
0
def fitting(session, spinwave_domain, spinwave_range, spinwave_range_Err, size=3, k = 100, tMin = .001, tMax = 15, tFactor = .95, MCeveryTime = True, recordKeeperCallback = None):

    # Create fitter
    fitter = PM.Fitter(session, spinwave_domain, size, k, tMin, tMax, tFactor, MCeveryTime)
    
    # Helper function for GetResult
    def myfunc(p, fjac=None, y=None, err=None, callback = None):
        if callback:
            callback(p)
        fitter.fit_list = p
        model = fitter.GetResult()
        status = 0
        print 'y:\n', y, '\n\nmodel:\n', model
        #print '\n\ny-model:\n', (y-model)
        #print '\n\nerr:\n', err
        result = (y-model)/err
        print '\n\nresult:\n', result
        return [status, result]

    # Function Keywords
    
    #spinwave_domain is a list of 3D lists:
    #-[(x1,y1,z1),(x2,y2,z2),...]
    #x must be a 1D numpy array:
    #[x1,y1,z1,x2,t2,z2,...]
    #xList = []
    #for point in fit.spinwave_domain:
    #    xList.append(point[0])
    #    yList.append(point[1])
    #    zList.append(point[2])
    #x = np.array(xList)
    #y = myfunc(fit)
    y = spinwave_range
    #errVal = .001
    #err = [errVal]*len(y)
    err = spinwave_range_Err
    #fa = {'x':x, 'y':y, 'err':err}
    fa = {'y':y, 'err':err, 'callback':recordKeeperCallback}
    
    # Set parinfo with the limits and such. Probably don't need
    parbase={'value':0., 'limited':[0,0], 'limits':[0.,0.]}
    parinfo=[]
    p0 = fitter.fit_list
    for i in range(len(p0)):
        parinfo.append(copy.deepcopy(parbase))
    for i in range(len(p0)):
        parinfo[i]['value']=p0[i]
        if(fitter.min_range_list[i] != np.NINF):
            parinfo[i]['limits'][0]=fitter.min_range_list[i]
            parinfo[i]['limited'][0] = 1
        else:
            parinfo[i]['limited'][0] = 0
        if fitter.max_range_list[i] != np.PINF:
            parinfo[i]['limits'][1] = fitter.max_range_list[i]
            parinfo[i]['limited'][1] = 1
        else:
            parinfo[i]['limited'][1] = 0

    # Run mpfit on fitlist with all the jazz.
    print "params: ", p0
    print "parinfo: ", parinfo
    m = mpfit(myfunc, p0, parinfo=parinfo, functkw = fa)
    # Bare Bones Run for when the above (especially keywords x) breaks instantly
    #m = mpfit(myfunc, fit.fitlist)
    
    #Return the parameters
    return (m.status, m.params, m.perror)