Пример #1
0
def fitHistGaussian(x, bins=50):
    h = np.histogram(x, bins=bins)
    xh = 0.5*(h[1][:-1]+h[1][1:])
    best, uncer, chi2, model = \
          dpfit.leastsqFit(gaussian, xh,
                               {'a':0.1, 'x0':0.0, 'w':10.}, h[0])
    return (best, uncer, xh, model)
Пример #2
0
 def __fitContinuum__(self):
     """
     fit polynomial continuum and adjust the model (adds parameters)
     """
     fitOnly = filter(lambda k: k[:5]=='polyN', self.model.keys())
     #print self.model, fitOnly
     best, uncer, reducedChi2, model = dpfit.leastsqFit(
         dpfit.meta, self.wlTable[self.whereCont],
         self.model, self.spectrum[self.whereCont], err=self.noise,
         fitOnly=fitOnly, verbose=False)
     #print 'Continuum:  CHI2=', reducedChi2
     while reducedChi2>self.chi2threshold:
         N = len(fitOnly)
         best['polyN:A'+str(N)] = 0.0
         fitOnly = filter(lambda k: k[:5]=='polyN', best.keys())
         best, uncer, reducedChi2, model = dpfit.leastsqFit(
             dpfit.meta, self.wlTable[self.whereCont],
             best, self.spectrum[self.whereCont], err=self.noise,
             fitOnly=fitOnly, verbose=False)
         #print '  continuum -> adding order', N, 'CHI2=', reducedChi2
     self.model = best
     return
Пример #3
0
def test1(N=10):
    diamMin = 1; diamMax = 2; P=1000
    bMin = 50; bMax = 150 
    err = 0.01 # fractional error
    
    # actual diameters
    diam = diamMin + np.random.rand()*(diamMax-diamMin)

    # observations:
    B = bMin + np.random.rand(N)*(bMax-bMin)
    obs = v2(B*diam/2.2)

    # error bars
    obs += np.random.randn(N)*err

    
    # prior:
    diams = np.linspace(diamMin, diamMax, P)
    prior = np.ones(P)/float(P)

    # inference
    for i,o in enumerate(obs):
        newPrior = []
        probs = np.array([normDistr(o, v2(B[i]*d/2.2), err*o)
                          for d in diams])
        norma = (prior*probs).sum()
        for k,p in enumerate(prior):
            newPrior.append(probs[k]*prior[k]/norma)
        # update
        prior = np.array(newPrior)

    # plot
    pyplot.clf()
    pyplot.vlines(diam, 0, 1.1*prior.max(), color='k',
                  linewidth=3, alpha=0.2, label='real value')
    pyplot.plot(diams, prior, label='Bayesian')
    
    print 'Least Square:'
    guess = {'diam':0.5*diamMin+0.5*diamMax}
    pfix, uncer, reducedChi2, model = \
          dpfit.leastsqFit(dpV2, B/2.2, guess, obs,
                           err=err*obs)
    print 'CHI2 reduced=', reducedChi2
    pyplot.vlines(pfix['diam'],0,prior.max(), 'r')
    pyplot.hlines(prior.max()/2,
                  pfix['diam']-uncer['diam'],
                  pfix['diam']+uncer['diam'], color='r',
                  label='least square')
    pyplot.legend()
    return
Пример #4
0
    def __fitAll__(self, noCont=True, restrict=True):
        if noCont:
            doNotFit=filter(lambda k: 'polyN' in k, self.model.keys())
        else:
            doNotFit=[]
    
        if restrict:
            w = np.zeros(len(self.spectrum))
            for k in self.model.keys():
                if 'SIGMA' in k or 'GAMMA' in k:
                    w += (np.abs(self.wlTable-self.model[k.split(':')[0]+':MU'])<=
                          np.abs(self.model[k]))
            w = np.where(w)
        else:
            w = np.where(np.isfinite(self.spectrum))
        
        best, uncer, reducedChi2, model = dpfit.leastsqFit(
            dpfit.meta, self.wlTable[w], self.model, self.spectrum[w],
            err=self.noise, verbose=False, doNotFit=doNotFit)
        self.model = best

        return
Пример #5
0
    for o in res:    
        DL2_DL1.extend(o['DL2-DL1'])
        DDL.extend(o['DDL'])
        ERR.extend(o['ERR'])
        OPD.extend(o['computed opd'])
    DL2_DL1 = np.array(DL2_DL1)
    DDL = np.array(DDL)
    ERR = np.array(ERR)
    OPD = np.array(OPD)
    guess = {'X':res[0]['XYZA'][0],
             'Y':res[0]['XYZA'][1],
             'Z':res[0]['XYZA'][2],
             'A':res[0]['XYZA'][3],
             'LAT':-24.62743941}
    best, uncer, chi2, model =\
          dpfit.leastsqFit(opdFunc, res, guess, DL2_DL1, err=ERR,
                               doNotFit=['Z', 'LAT'])
    print 'CHI2:', chi2
    print 'RESIDUAL:', (DL2_DL1-model).std(), 'm'
    ke = best.keys(); ke.sort()
    for k in ke:
        if uncer[k]>0:
            print '| %3s | %10.6f | %10.6f +- %8.6f |' %\
                  (k,guess[k], best[k], uncer[k] )
        else:
            print '| %3s | %10.6f | %10.6f             |' %\
                  (k,guess[k], best[k] )

    pyplot.figure(0)
    pyplot.clf()

    ax = pyplot.subplot(221)
Пример #6
0
def fitAllHD10360():
    global pup
    HD10360corr = []
    HD10360 = []
    for k, f in enumerate(files_hd10360):
        print k+1, '/', len(files_hd10360)
        fg = {'SEP':8., 'PA':135, 'M0':0.0}
        for k in ATsPUP.keys():
            fg[k] = ATsPUP[k]
        HD10360corr.append(astromNew.fitListOfFiles(f, directory=data_directory,
                                                  firstGuess=fg,
                                                  doNotFit=['AT3','AT4','PUP'],
                                                  plot=False, verbose=False))
        print HD10360corr[-1]['MJD_MIN'], '-', HD10360corr[-1]['MJD_MAX']

        HD10360.append(astromNew.fitListOfFiles(f, directory=data_directory,
                                     firstGuess={'SEP':8., 'PA':135, 'M0':-0.0},
                                     plot=False, verbose=False))


    pyplot.figure(10)
    pyplot.clf()
    pyplot.axes().set_aspect('equal', 'datalim')
    th = np.linspace(0, 2*np.pi, 100)
    colors=['r', 'g', 'b', 'y', 'm', 'c']

    ### data reduced without correction: ####################
    XYT = []
    for k,d in enumerate(HD10360):
        ### observation:
        X = d['BEST']['SEP']*np.sin(d['BEST']['PA']*np.pi/180)
        Y = d['BEST']['SEP']*np.cos(d['BEST']['PA']*np.pi/180)
        XYT.append((X,Y, d['MJD_MEAN']))
        pyplot.plot(X, Y, 's'+colors[k], markersize=10, alpha=0.5,
                    label = 'no correction' if k==0 else None)
    # linear fit
    Xb, Xe, chi2, Xm =\
        dpfit.leastsqFit(dpfit.polyN, [x[2]-55885 for x in XYT],
                         {'A0':0, 'A1':1},
                         [x[0] for x in XYT])
    Yb, Ye, chi2, Ym =\
       dpfit.leastsqFit(dpfit.polyN, [x[2]-55885 for x in XYT],
                        {'A0':0, 'A1':1},
                        [x[1] for x in XYT])
    # display linear fit
    MJD = np.linspace(55885, 55890, 100)
    pyplot.plot(dpfit.polyN(MJD-55885, Xb), dpfit.polyN(MJD-55885, Yb),
                'k-', linewidth=3, alpha=0.3)
    # distance to fit
    for k,d in enumerate(HD10360):
        X = d['BEST']['SEP']*np.sin(d['BEST']['PA']*np.pi/180)
        Y = d['BEST']['SEP']*np.cos(d['BEST']['PA']*np.pi/180)
        pyplot.plot(Xm[k], Ym[k], 'x'+colors[k], markersize=6)
        pyplot.plot([X, Xm[k]], [Y, Ym[k]], '-'+colors[k],
                    linewidth=2, alpha=0.5)

    ### data reduced with correction ############################
    XYT=[]
    for k,d in enumerate(HD10360corr):
        ### observation:
        X = d['BEST']['SEP']*np.sin(d['BEST']['PA']*np.pi/180)
        Y = d['BEST']['SEP']*np.cos(d['BEST']['PA']*np.pi/180)
        XYT.append((X,Y, d['MJD_MEAN']))
        pyplot.plot(X, Y, 'o'+colors[k], markersize=10,
                    label = 'scaled correction' if k==0 else None)
    # linear fit
    Xb, Xe, chi2, Xm =\
        dpfit.leastsqFit(dpfit.polyN, [x[2]-55885 for x in XYT],
                         {'A0':0, 'A1':1},
                         [x[0] for x in XYT])
    Yb, Ye, chi2, Ym =\
       dpfit.leastsqFit(dpfit.polyN, [x[2]-55885 for x in XYT],
                        {'A0':0, 'A1':1},
                        [x[1] for x in XYT])
    print 'linrate:', np.sqrt(Xb['A1']**1+Yb['A1']**2)*1e6, 'uas/day'
    # display linear fit
    MJD = np.linspace(55885, 55892, 10)
    pyplot.plot(dpfit.polyN(MJD-55885, Xb), dpfit.polyN(MJD-55885, Yb),
                'k-', linewidth=3, alpha=0.3)

    # distance to fit
    for k,d in enumerate(HD10360corr):
        X = d['BEST']['SEP']*np.sin(d['BEST']['PA']*np.pi/180)
        Y = d['BEST']['SEP']*np.cos(d['BEST']['PA']*np.pi/180)
        pyplot.plot(Xm[k], Ym[k], 'x'+colors[k], markersize=6)
        pyplot.plot([X, Xm[k]], [Y, Ym[k]], '-'+colors[k],
                    linewidth=2, alpha=0.5)

    pyplot.legend(loc='upper left')
    pyplot.xlabel('$\delta$ E (\")')
    pyplot.ylabel('$\delta$ N (\")')
    return
Пример #7
0
def fitListOfFiles(
    files=[],
    directory="",
    fitOnlyFiles=None,
    firstGuess={"M0": 0.0, "SEP": 10.0, "PA": 90.0},
    fitOnly=None,
    doNotFit=None,
    maxResiduals=None,
    verbose=1,
    reduceData=False,
    pssRecDir=None,
    max_err_um=1.0,
    max_GD_um=2.5,
    sigma_clipping=3.5,
    plot=True,
    randomize=False,
    exportFits=None,
    exportAscii=None,
    rectified=True,
    allX=False,
):

    """ files, list of files

    directory='', where the data are

    fitOnlyFiles=None, list of index of files to fit

    firstGuess={'M0':0.0, 'SEP':10.0, 'PA':90.0}, see dOPDfunc



    fitOnly=None, doNotFit=None, list of names of variable to fit or not fit

    verbose=1, 2 for max verbosity (list of files)

    reduceData=False, : to forece reducing the data: relevant parameters:
       pssRecDir=None,
       max_err_um=2.0,
       max_GD_um=4.0,
       sigma_clipping=5.0,

    exportFits=None, exportAscii=None : give a filename to activate
 
    plot=True,
       rectified=True, plot 'rectified' residuals,
       maxResiduals=None, for the plot, for the MAX/min to this value (in um)
       
    randomize=False : to be used for bootstrapping
    """
    global dOPDfuncNiter, obs, obsFit

    if len(files) == 0:  # no files given means all of them!
        files = os.listdir(directory)
        files = filter(lambda x: ".fits" in x and not "RED" in x, files)

    if reduceData:
        for f in files:
            print "#" * 3, "reducing:", f, "#" * 5
            a = prima.drs(directory + f, pssRec=pssRecDir)
            if "OBJ_ASTRO" in f:  # reduce dual fringe tracking data
                a.astrometryFtk(
                    max_err_um=max_err_um,
                    max_GD_um=max_GD_um,
                    sigma_clipping=sigma_clipping,
                    max_length_s=1.0,
                    writeOut=True,
                    overwrite=True,
                )
            else:  # reduce scanning data:
                a.astrometryScan(
                    max_err_um=max_err_um,
                    max_GD_um=max_GD_um,
                    sigma_clipping=sigma_clipping,
                    writeOut=True,
                    overwrite=True,
                )
            a = []
    red = []  # tables of atom
    # load all reduced files
    if fitOnlyFiles is None:
        fitOnlyFiles = range(len(files))

    for k, f in enumerate(files):
        # reduced file:
        rf = f.split(".")[0] + "_RED.fits"
        #  load reduced file
        a = atom(os.path.join(directory, rf))
        # print the table of loaded files:
        if not fitOnlyFiles == None:
            if k in fitOnlyFiles:
                fit = "X"
            else:
                fit = "_"
        else:
            fit = "X"
        if verbose > 1:  # pretty printing of files, in a table:
            if k == 0:
                N = len(rf)
                print "|idx |fit|INS.MODE | TARGET     | file" + " " * 20 + "| UT " + " " * 16 + " | MJD-OBS"
            print "| %2d | %1s | %7s | %10s | %s | %s | %10.6f" % (
                k,
                fit,
                a.insmode,
                a.PS_ID[:10],
                rf.split("OBJ_")[1],
                a.date_obs[:19],
                a.mjd_obs,
            )

        red.append(a)  # list of reduced files
    if verbose:
        print ""

    # prepare observation vector for the FIT
    obs = []
    for k in range(len(red)):
        for i in range(len(red[k].d_al)):
            obs.append(
                {
                    "TARGET": red[k].data[0].header["ESO OCS PS ID"],
                    "FILENAME": red[k].filename.split("/")[-1],
                    "DOPD": red[k].d_al[i],
                    "eDOPD": red[k].d_al_err[i],
                    "LST": red[k].lst[i],
                    "MJD": red[k].mjd[i].min(),
                    "RA": red[k].radec[0],
                    "DEC": red[k].radec[1],
                    "SWAPPED": int(red[k].swapped[i]),
                    "FIT": k in fitOnlyFiles and red[k].d_al_err[i] > 0,
                    "B_XYZA": [
                        red[k].data[0].header["ESO ISS CONF T1X"] - red[k].data[0].header["ESO ISS CONF T2X"],
                        red[k].data[0].header["ESO ISS CONF T1Y"] - red[k].data[0].header["ESO ISS CONF T2Y"],
                        red[k].data[0].header["ESO ISS CONF T1Z"] - red[k].data[0].header["ESO ISS CONF T2Z"],
                        red[k].data[0].header["ESO ISS CONF A1L"] - red[k].data[0].header["ESO ISS CONF A2L"],
                    ],
                    "ROT3": red[k].rot3[i],
                    "ROT4": red[k].rot4[i],
                    "AZ3": red[k].az3[i],
                    "AZ4": red[k].az4[i],
                    "ALT3": red[k].alt3[i],
                    "ALT4": red[k].alt4[i],
                }
            )
    obsFit = filter(lambda x: x["FIT"], obs)
    obsNoFit = filter(lambda x: not x["FIT"], obs)
    t0 = time.time()

    if not doNotFit is None:
        # fitOnly = filter(lambda k: not k in doNotFit, firstGuess.keys())
        fitOnly = filter(lambda k: not any([x in k for x in doNotFit]), firstGuess.keys())
    dOPDfuncNiter = 0

    if randomize > 0:  # to be used by bootstrapping
        if randomize != True:
            np.random.seed(randomize)
        w = np.random.randint(len(obsFit), size=len(obsFit))
        tmp = []
        for k in w:
            tmp.append(obsFit[k])
        obsFit = tmp

    if "T:" in [x[:2] for x in firstGuess.keys()]:
        ### multiple targets case:
        fit = dpfit.leastsqFit(
            dOPDfuncMultiTargets,
            obsFit,
            firstGuess,
            [o["DOPD"] for o in obsFit],
            err=[o["eDOPD"] for o in obsFit],
            fitOnly=fitOnly,
            verbose=0,
            epsfcn=1e-5,
        )
        best = fit["best"]
        uncer = fit["uncer"]
        chi2 = fit["chi2"]
        model = fit["model"]

        obs = dOPDfuncMultiTargets(obs, best, addIntermediate=True)
        obsFit = dOPDfuncMultiTargets(obsFit, best, addIntermediate=True)
        obsNoFit = dOPDfuncMultiTargets(obsNoFit, best, addIntermediate=True)
        ### compute a chi2 for each targets:
        targets = list(set([x["TARGET"] for x in obsFit]))
        chi2T = {}
        rmsT = {}
        for t in targets:
            obsT = filter(lambda x: x["TARGET"] == t, obsFit)
            tmp = dOPDfuncMultiTargets(obsT, best) - np.array([x["DOPD"] for x in obsT])
            rmsT[t] = round(tmp.std() * 1e6, 2)
            chi2T[t] = round((tmp ** 2 / np.array([x["eDOPD"] for x in obsT]) ** 2).mean(), 2)
        if plot:
            print "RMS (um):", rmsT
            print "CHI2    :", chi2T
    else:
        fit = dpfit.leastsqFit(
            dOPDfunc,
            obsFit,
            firstGuess,
            [o["DOPD"] for o in obsFit],
            err=[o["eDOPD"] for o in obsFit],
            fitOnly=fitOnly,
            verbose=0,
            epsfcn=1e-5,
        )
        best = fit["best"]
        uncer = fit["uncer"]
        chi2 = fit["chi2"]
        model = fit["model"]

        obs = dOPDfunc(obs, best, addIntermediate=True)
        obsFit = dOPDfunc(obsFit, best, addIntermediate=True)
        obsNoFit = dOPDfunc(obsNoFit, best, addIntermediate=True)

    RMSum = (np.array([o["DOPD"] for o in obsFit]) - model).std() * 1e6
    if plot:
        print "residuals= %4.2f (um)" % (RMSum)
        print "CHI2= %4.2f" % (chi2)

    # print result
    tmp = best.keys()
    tmp.sort()
    if best.has_key("AT scale") and best["AT scale"] == 0:
        tmp = filter(lambda x: not "AT4" in x and "AT3" not in x, tmp)
    units = {
        "M0": "mm",
        "SEP": "arcsec",
        "PA": "deg",
        "AT3 phi": "deg",
        "AT4 phi": "deg",
        "LINRATE": "uas/day",
        "LINDIR": "deg",
    }
    if plot:
        for k in tmp:
            if uncer[k] > 0:
                nd = int(-np.log10(uncer[k]) + 2)
                form = "%" + str(max(nd, 0) + 2) + "." + str(max(nd, 0)) + "f"
                form = k + " = " + form + " +/- " + form
                print form % (round(best[k], nd), round(uncer[k], nd)),
            else:
                print k + " = " + " %f" % (best[k]),
            u = ""
            for z in units.keys():
                if z in k:
                    u = "(" + units[z] + ")"
            print u

    # export to Ascii:
    if not exportAscii is None:
        f = open(exportAscii, "w")
        tmp = best.keys()
        tmp.sort()
        for k in tmp:
            f.write("# " + k + " =" + str(best[k]) + "\n")
            if uncer[k] != 0:
                f.write("# ERR " + k + " =" + str(uncer[k]) + "\n")
        tmp = obs[0].keys()
        tmp.sort()
        f.write("# " + "; ".join([t.replace(" ", "_") for t in tmp]) + "\n")
        for o in obs:
            f.write("" + "; ".join([str(o[k]) for k in tmp]) + "\n")
        f.close()
    # export to FITS:
    if not exportFits is None:
        # create fits object
        hdu0 = pyfits.PrimaryHDU(None)
        tmp = best.keys()
        tmp.sort()
        for k in tmp:
            hdu0.header.update("HIERARCH " + k, best[k])
            if uncer[k] != 0:
                hdu0.header.update("HIERARCH ERR " + k, uncer[k])
        tmp = obs[0].keys()
        tmp.sort()
        cols = []
        for k in tmp:
            if k == "MJD":
                form = "F12.5"
            elif (
                type(obs[0][k]) == float
                or type(obs[0][k]) == np.float
                or type(obs[0][k]) == np.float32
                or type(obs[0][k]) == np.float64
            ):
                form = "F12.9"
            elif type(obs[0][k]) == str:
                form = "A" + str(max([len(o[k]) for o in obs]))
            elif (
                type(obs[0][k]) == bool
                or type(obs[0][k]) == np.bool
                or type(obs[0][k]) == np.bool_
                or type(obs[0][k]) == int
            ):
                form = "I"
            else:
                print "DEBUG:", k, obs[0][k], type(obs[0][k])
                form = ""

            if k != "B_XYZA":
                cols.append(pyfits.Column(name=k.replace(" ", "_"), format=form, array=[o[k] for o in obs]))
            else:
                cols.append(pyfits.Column(name="B_X", format="F12.8", array=[o[k][0] for o in obs]))
                cols.append(pyfits.Column(name="B_Y", format="F12.8", array=[o[k][1] for o in obs]))
                cols.append(pyfits.Column(name="B_Z", format="F12.8", array=[o[k][2] for o in obs]))
                cols.append(pyfits.Column(name="B_A", format="F12.8", array=[o[k][3] for o in obs]))

        hducols = pyfits.ColDefs(cols)
        hdub = pyfits.new_table(hducols)
        hdub.header.update("EXTNAME", "ASTROMETRY REDUCED", "")
        thdulist = pyfits.HDUList([hdu0, hdub])
        outfile = exportFits
        if os.path.exists(outfile):
            os.remove(outfile)
        print "writting ->", outfile
        thdulist.writeto(outfile)
        return

    # return fitting result
    res = {
        "BEST": best,
        "UNCER": uncer,
        "CHI2": chi2,
        "RMS": RMSum,
        "MJD_MIN": min([o["MJD"] for o in obsFit]),
        "MJD_MAX": max([o["MJD"] for o in obsFit]),
        "MJD_MEAN": np.array([o["MJD"] for o in obsFit]).mean(),
    }
    res["RA"] = {}
    res["DEC"] = {}
    for o in obs:
        if not res["RA"].has_key(o["TARGET"]):
            res["RA"][o["TARGET"]] = o["RA"]
            res["DEC"][o["TARGET"]] = o["DEC"]

    if not plot:
        return res

    # =============== PLOT =============================
    if "T:" in [x[:2] for x in best.keys()]:
        modelNoFit = dOPDfuncMultiTargets(obsNoFit, best)
    else:
        modelNoFit = dOPDfunc(obsNoFit, best)

    pyplot.figure(0, figsize=(18, 6))
    pyplot.clf()
    pyplot.subplots_adjust(left=0.05, bottom=0.07, right=0.99, top=0.95, wspace=0.01)

    if allX:
        # display all sorts of X axis
        Xs = [
            lambda o: (o["LST"] - o["RA"] + 12) % 24 - 12,
            lambda o: o["ROT4"],
            lambda o: (o["AZ4"] - o["ALT4"] - 2 * o["ROT4"]) % 360,
            lambda o: o["AZ4"],
            lambda o: o["MJD"],
        ]

        Xlabels = ["hour angle (h)", "ROT4 (degrees)", "AZ4 - ALT4 - 2*ROT4 (degrees)", "AZ4 (degrees)", "MJD"]
    else:
        # display only Hour Angle
        Xs = [lambda o: (o["LST"] - o["RA"] + 12) % 24 - 12]
        Xlabels = ["hour angle (h)"]

    for i in range(len(Xs)):
        X = Xs[i]
        Xlabel = Xlabels[i]
        if i == 0:
            ax0 = pyplot.subplot(1, len(Xs), i + 1)
        else:
            pyplot.subplot(1, len(Xs), i + 1, sharey=ax0)

        if not rectified:
            ### plot data used for the fit
            pyplot.plot(
                [X(o) if not o["SWAPPED"] else None for o in obsFit],
                [(obsFit[k]["DOPD"] - model[k]) * 1e6 for k in range(len(obsFit))],
                "ob",
                alpha=0.3,
                label="NORMAL",
            )
            pyplot.plot(
                [X(o) if o["SWAPPED"] else None for o in obsFit],
                [(obsFit[k]["DOPD"] - model[k]) * 1e6 for k in range(len(obsFit))],
                "or",
                alpha=0.3,
                label="SWAPPED",
            )
            if len(obsNoFit) > 1:
                ### plot data NOT used for the fit
                pyplot.plot(
                    [X(o) if not o["SWAPPED"] else None for o in obsNoFit],
                    [(obsNoFit[k]["DOPD"] - modelNoFit[k]) * 1e6 for k in range(len(obsNoFit))],
                    "+c",
                    alpha=0.2,
                    label="NORMAL, not fitted",
                )
                pyplot.plot(
                    [X(o) if o["SWAPPED"] else None for o in obsNoFit],
                    [(obsNoFit[k]["DOPD"] - modelNoFit[k]) * 1e6 for k in range(len(obsNoFit))],
                    "+y",
                    alpha=0.2,
                    label="SWAPPED, not fitted",
                )
            pyplot.ylabel("$O-C$ ($\mu$m)")
        else:
            ### plot data used for the fit
            pyplot.plot(
                [X(o) if not o["SWAPPED"] else None for o in obsFit],
                [(-1) ** obsFit[k]["SWAPPED"] * (obsFit[k]["DOPD"] - model[k]) * 1e6 for k in range(len(obsFit))],
                "ob",
                alpha=0.3,
                label="NORMAL",
            )
            pyplot.plot(
                [X(o) if o["SWAPPED"] else None for o in obsFit],
                [(-1) ** obsFit[k]["SWAPPED"] * (obsFit[k]["DOPD"] - model[k]) * 1e6 for k in range(len(obsFit))],
                "or",
                alpha=0.3,
                label="SWAPPED",
            )
            if len(obsNoFit) > 1:
                ### plot data NOT used for the fit
                pyplot.plot(
                    [X(o) if not o["SWAPPED"] else None for o in obsNoFit],
                    [
                        (-1) ** obsNoFit[k]["SWAPPED"] * (obsNoFit[k]["DOPD"] - modelNoFit[k]) * 1e6
                        for k in range(len(obsNoFit))
                    ],
                    "+c",
                    alpha=0.2,
                    label="NORMAL, not fitted",
                )
                pyplot.plot(
                    [X(o) if o["SWAPPED"] else None for o in obsNoFit],
                    [
                        (-1) ** obsNoFit[k]["SWAPPED"] * (obsNoFit[k]["DOPD"] - modelNoFit[k]) * 1e6
                        for k in range(len(obsNoFit))
                    ],
                    "+y",
                    alpha=0.2,
                    label="SWAPPED, not fitted",
                )

            # -- plot pupil bias correction
            # pyplot.plot([X(o) for o in obs],
            #            [(-1)**o['SWAPPED']*o['fit PUPbias']*1e6 for o in obs],
            #            '.k', label='pup runout correction')

        if i == 0:
            pyplot.ylabel("$(-1)^\mathrm{swapped}(O-C)$ ($\mu$m)")
            pyplot.text(
                min([X(o) for o in obs]),
                0,
                "RMS=" + str(round(RMSum, 2)) + "$\mu$m",
                va="center",
                ha="left",
                bbox=dict(boxstyle="round", ec=(0.4, 0.2, 0.0), fc=(1.0, 0.8, 0.0), alpha=0.2),
            )
            pyplot.legend(ncol=4, loc="upper left")
        pyplot.xlabel(Xlabel)
        if not maxResiduals is None:
            pyplot.ylim(-maxResiduals, maxResiduals)

    return res
Пример #8
0
    def _fitPhases(self, scan=1, FSU='FSUA'):
        self._fittedScan=scan
        self._fittedFSU=FSU
        
        i0 = self.labScans[scan][FSU]['GDSNR'].argmax()
        
        self._fitiMin = i0-100
        self._fitiMax = i0+100
        
        channels = [1,2,3,4,5]
        params={}
        Y, doNotFit, fitOnly =[], [], []
        for c in channels:
            tmp={#'0OPD'+str(c):self.labScans[scan][FSU]['DELTAL'][self._fitiMin],
                 'WL'+str(c):self.effWl[FSU]['A'][c]*1e-6,
                #'phiB'+str(c):self.phases[FSU]['PHIB'][c],
                #'phiC'+str(c):self.phases[FSU]['PHIC'][c],
                #'phiD'+str(c):self.phases[FSU]['PHID'][c]
                 }   
            for k in tmp.keys():
                params[k]=tmp[k]
            Y.append(self.labScans[scan][FSU]['DELTAL'][self._fitiMin:self._fitiMax])

        params['phiB_2.2']=0.0
        params['phiC_2.2']=0.0
        params['phiD_2.2']=0.0
        params['0OPD_2.2']=0.0
        params['0OPD_c']=0.0
        Y = np.array(Y)
        for k in params.keys():
            if '0OPD' in k or 'WL' in k:
                fitOnly.append(k)
                
        fit0 = dpfit.leastsqFit(self.__fitPhasesFunc, channels,
                               params,Y, doNotFit=doNotFit,
                               fitOnly=fitOnly)
        model0 = fit0['model']
        doNotFit, fitOnly = [], None
        fit = dpfit.leastsqFit(self.__fitPhasesFunc, channels,
                               fit0['best'],Y, doNotFit=doNotFit,
                               fitOnly=fitOnly, verbose=1)
        model = fit['model']
        
        plt.figure(10)
        plt.clf()
        ax1=plt.subplot(211)
        for k in range(len(Y)):
            plt.plot(Y[k]*1e6, Y[k]*1e6-model[k]*1e6, 'r', alpha=0.5)
            plt.plot(Y[k]*1e6, Y[k]*1e6-model0[k]*1e6, 'k', alpha=0.5)           

        plt.subplot(313, sharex=ax1)
        plt.plot(Y[0]*1e6,
                 self.labScans[scan][FSU]['A'][self._fitiMin:self._fitiMax,0]-
                self.labScans[scan][FSU]['C'][self._fitiMin:self._fitiMax,0])
        plt.plot(Y[0]*1e6,
                 self.labScans[scan][FSU]['B'][self._fitiMin:self._fitiMax,0]-
                self.labScans[scan][FSU]['D'][self._fitiMin:self._fitiMax,0])
        for k in fit['best'].keys():
            if 'phi' in k:
                fit['best'][k] = (fit['best'][k]+np.pi)%(2*np.pi)-np.pi
        
        #plt.figure(11)
        #plt.clf()
        #for c in channels:
        #    plt.plot(fit['best']['WL'+str(c)]*1e6, fit['best']['phiB'+str(c)], 'or')
        #    plt.plot(fit['best']['WL'+str(c)]*1e6, fit['best']['phiC'+str(c)], 'og')
        #    plt.plot(fit['best']['WL'+str(c)]*1e6, fit['best']['phiD'+str(c)], 'oy')
        return