Exemplo n.º 1
0
def getHistograms(inFileName):
	hists = {}
	with root_open(inFileName, "READ") as inFile:
		names = GetKeyNames(inFile)
		for nn in names:
			hist = inFile.Get(nn)
			hist.SetDirectory(0)
			hists[nn] = hist
	return hists
Exemplo n.º 2
0
def main():
	inFile1 = "980.root"
	inFile2 = "1500.root"
	outFile = "f0s.root"
	hists1  = getHistograms(inFile1)
	hists2  = getHistograms(inFile2)
	for nn in hists1:
		hists1[nn].Add(hists2[nn])
	with root_open(outFile, "RECREATE"):
		for nn in hists1:
			hists1[nn].Write()
Exemplo n.º 3
0
def makeROOTfile(rootFileName, data):
    with root_open(rootFileName, "RECREATE") as outFile:
        count = 0
        for wave in waves:
            for L in spins:
                reals, imags = data[count]
                waveName = wave + L
                graph = ROOT.TGraph(len(reals), reals, imags)
                graph.SetTitle(waveName)
                graph.SetName(waveName)
                graph.Write()
                count += 1
Exemplo n.º 4
0
def main(rhoFileName=""):
    checkLaTeX()
    # # # #  Monte-Carlo results
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_MC_corrected.root"
    #	inFileName = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/ppppppppp/DpPiPiPi_forReleaseNote.root"
    #	inFileName = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/ppppppppp/DpPiPiPi_normalF2.root"
    #	inFileName = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/ppppppppp/DpPiPiPi_versionInPaper.root"
    #	inFileName = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/ppppppppp/DpPiPiPi_forThesis.root"
    #	inFileName = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/ppppppppp/DpPiPiPi_largeErrorStudy.root"
    # # # # Real-data results
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_three0pp.root"
    inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/std11_withIntegral.root"
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_exotic_t0.326-0.66_fixed.root"
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_exotic_t0.66-1.00_fixed.root"
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_bigger1pp.root"
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_exotic.root"
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_bigger2pp.root"
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_bigger2mp.root"
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_maximum_t0.66-1.00.root"
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_maximum.root"
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_neg_1m1m.root"
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_neg_1P0m.root"
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_3pp.root"
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_4pp.root"
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_4mp.root"
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_6mp.root"
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_exoticMC.root"
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_rho3_2mp3pp.root"

    fourPPamplFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/ampls_4++1+rhoPiG.dat"

    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_std11.root"

    zeroFileName = inFileName

    #	sectors = ["Dp[pi,pi]0++PiS","Dp[pi,pi]1--PiP"]
    #	sectors = ["Dp[pi,pi]0++PiS"]
    sectors = ["Dp[pi,pi]1--PiP"]
    # # # # # Std11 Definitions
    std11_0mp0p = ["0-+0+[pi,pi]0++PiS", "0-+0+[pi,pi]1--PiP"]
    std11_1pp0p = ["1++0+[pi,pi]0++PiP", "1++0+[pi,pi]1--PiS"]
    std11_1pp1p = ["1++1+[pi,pi]1--PiS"]
    std11_2pp1p = ["2++1+[pi,pi]1--PiD"]
    std11_2mp0p = [
        "2-+0+[pi,pi]0++PiD", "2-+0+[pi,pi]1--PiP", "2-+0+[pi,pi]1--PiF",
        "2-+0+[pi,pi]2++PiS"
    ]
    std11_2mp1p = ["2-+1+[pi,pi]1--PiP"]

    # # # # # Bigger 1++ definitions
    #	sectors = std11_1pp0p + ["1++0+[pi,pi]1--PiD", "1++0+[pi,pi]2++PiP"]
    # # # # # Exotic (1-+)
    sector_exotic = ["1-+1+[pi,pi]1--PiP"]

    neg_1m1m = ["1-+1-[pi,pi]1--PiP"]
    neg_1P0m = ["1++1-[pi,pi]1--PiS"]
    # # # # # qBigger 2++ definitions
    #	sectors = std11_2pp1p + ["2++1+[pi,pi]2++PiP"]
    # # # # # Bigger 2-+ definitions
    #	sectors = std11_2mp0p + ["2-+0+[pi,pi]2++PiD"]
    #	sectors = std11_2mp1p + ["2-+1+[pi,pi]2++PiS"]
    sectors = [
        "2-+0+[pi,pi]1--PiP", "2-+0+[pi,pi]1--PiF", "2-+0+[pi,pi]2++PiS",
        "2-+0+[pi,pi]2++PiD", "2-+0+[pi,pi]3--PiP"
    ]
    #	sectors = ["2-+0+[pi,pi]3--PiP"]
    # # # # # 3++
    #	sectors = ["3++0+[pi,pi]1--PiD", "3++0+[pi,pi]2++PiP", "3++0+[pi,pi]3--PiS"]
    #	sectors = ["3++0+[pi,pi]2++PiP"]
    # # # # # 4++
    #	sectors = ["4++1+[pi,pi]1--PiG", "4++1+[pi,pi]2++PiF"]
    #	sectors = ["4++1+[pi,pi]1--PiG"]
    #	sectors = ["4++1+[pi,pi]2++PiF"]
    # # # # # 4-+
    #	sectors = ["4-+0+[pi,pi]1--PiF"]
    # # # # # 6-+
    #	sectors = ["6-+0+[pi,pi]1--PiH"]

    #	sectors = ["2-+0+[pi,pi]2++PiD"]

    sectors = ["2-+0+[pi,pi]2++PiS"]

    sectors = std11_0mp0p
    #	sectors = sector_exotic
    #	sectors = std11_1pp0p
    #	sectors = std11_1pp1p
    #	sectors = neg_1P0m
    #	sectors = std11_2mp0p
    #	sectors = std11_2mp1p # + ["2-+1+[pi,pi]2++PiS"]
    #	sectors = std11_2pp1p

    #	sectors = ["2-+1+[pi,pi]2++PiS"]

    #	referenceWave = "4-+0+rhoPiF"
    referenceWave = ""

    #	sectors = std11_0mp0p[:1]

    doSpecialOneBinFit = -34  # negative values turn it off

    sectorUseMap = {  # Defines, if for the given sector a theory curve will be used
        "0-+0+[pi,pi]0++PiS": True,
        "0-+0+[pi,pi]1--PiP": True,
        "1++0+[pi,pi]0++PiP": True,
        "1++0+[pi,pi]1--PiS": True,
        "2-+0+[pi,pi]0++PiD": False,
        "2-+0+[pi,pi]1--PiP": True,
        "2-+0+[pi,pi]1--PiF": True,
        "2-+0+[pi,pi]2++PiS": True,
        "2-+0+[pi,pi]3--PiP": True
    }

    sectorRangeMap = {
        #		"2-+0+[pi,pi]1--PiP" : (0., 1.12),
        #		"2-+0+[pi,pi]1--PiF" : (0., 1.12),
        #		"2-+0+[pi,pi]2++PiS" : (0., 1.5 ),
    }
    for sector in sectors:
        if '1--' in sector:
            pass
#			sectorRangeMap[sector] = (0.55,1.00)
        if '0++' in sector:
            pass
#			sectorRangeMap[sector] = (0.,.94)

    if "extensiveFreedIsobarStudies" in inFileName:
        ppppppppp = False
    else:
        ppppppppp = True

    tBin = 0
    if not ppppppppp:
        startBin = 25
        stopBin = 50
#		startBin         = 27
#		stopBin          = startBin+1
    else:
        startBin = 34
        stopBin = 35
#	startBin         = 25
#	stopBin          = 26
    polynomialDegree = 0
    if not ppppppppp:
        modelMode = "fixedShapes"
    else:
        modelMode = "simpleBW_Dp"
#	modelMode        = "fixedRhoExotic"
#	modelMode        = "pipiS"
#	modelMode        = "none"
#	modelMode        = "simpleBW_Dp"
#	modelMode        = "BW"
#	modelMode        = "explicitRhoFile"
    useSmooth = False
    fitShape = True
    phaseFit = False
    produceTotals = False
    if modelMode == "BW" or modelMode == "2BW":
        #		rho = pc.breitWigner()
        rho = pc.rpwaBreitWignerInt(0.13957018, 0.13957018, 0.13957018, 1, 0)
        f2 = pc.rpwaBreitWignerInt(0.13957018, 0.13957018, 0.13957018, 2, 0)
        rhoParameters = [.77549, .1491]
        f2Parameters = [1.2, 1.7]
        f2.setParameters(f2Parameters)
        #		rhoParameters = [1.2, .2]
        rho.setParameters(rhoParameters)
        #		rho.weightIntens = True
        #		rhoParameters = [1.27549, .100]
        rhoPrime = pc.breitWigner()
        rhoPrimeParameters = [1.570, 0.144]
        rhoPrime.setParameters(rhoPrimeParameters)
        rhoModel = [rho]
        f2Model = [f2]
        if modelMode == "2BW":
            rhoModel.append(rhoPrime)
        waveModel = {}
        for sector in sectors:
            if '1--' in sector:
                waveModel[sector] = rhoModel
            elif "3--" in sector:
                waveModel[sector] = rhoModel
            elif "2++" in sector:
                waveModel[sector] = f2Model

    elif modelMode == "fixedRhoExotic":
        pdgMass = 0.7690
        pdgWidth = 0.1509

        massRho = ptc.parameter(pdgMass + 0.0, "rhoMass")
        widthRho = ptc.parameter(pdgWidth + 0.0, "rhoWidth")
        massRho.lock = True
        widthRho.lock = True
        rho = ptc.breitWigner([massRho, widthRho])
        waveModel = {"1-+1+[pi,pi]1--PiP": [rho]}

    elif modelMode == "simpleBW_Dp":
        theWarning = """
		Keep in mind the two-step procedure: 
		-	fix with the shifted
		-	c&p the parameters
		-	set the parameters by hand 
		-	run with the non-shifted "truth" parameters
		"""
        print theWarning

        f0Mass = ptc.parameter(.98, "f0Mass")
        f0Width = ptc.parameter(.1, "f0Width")

        #		rhoMass  = ptc.parameter(.77  + .2 + .5, "rhoMass")
        #		rhoWidth = ptc.parameter(.16  + .1 + .1, "rhoWidth")

        rhoMass = ptc.parameter(.77, "rhoMass")
        rhoWidth = ptc.parameter(.16, "rhoWidth")

        #		rhoMass  = ptc.parameter(.77 + .2  , "rhoMass")
        #		rhoWidth = ptc.parameter(.16 + .1 , "rhoWidth")

        #		rhoMass  = ptc.parameter(.77 + .2 + .3 , "rhoMass")
        #		rhoWidth = ptc.parameter(.16 + .1 + .1, "rhoWidth")

        #		rhoPMass  = ptc.parameter(1.4, "rhoMass")
        #		rhoPWidth = ptc.parameter(0.2, "rhoWidth")

        #		f0Mass   = ptc.parameter(1.4 , "f0Mass"  )
        #		f0Width  = ptc.parameter( .1 , "f0Width" )
        #		rhoMass  = ptc.parameter( .77, "rhoMass" )
        #		rhoWidth = ptc.parameter( .16, "rhoWidth")

        #		f0Mass   = ptc.parameter(1., "f0Mass" )
        #		f0Width  = ptc.parameter(.11 ,"f0Width")
        #		rhoMass  = ptc.parameter(.75, "rhoMass")
        #		rhoWidparamsFarIntens.pdfth = ptc.parameter(.18, "rhoWidth")

        f0Mass.lock = True
        f0Width.lock = True
        rhoMass.lock = True
        rhoWidth.lock = True
        #		rhoPMass.lock = True; rhoPWidth.lock = True

        f0 = ptc.breitWigner([f0Mass, f0Width])

        rho = ptc.breitWigner([rhoMass, rhoWidth])
        #		rhoP = ptc.breitWigner([rhoPMass, rhoPWidth])
        #		f2 = pc.breitWigner()
        #		f2.setParameters([1.27, .2 ])
        #		waveModel = {"Dp[pi,pi]0++PiS" : [f0], "Dp[pi,pi]1--PiP" : [rho], "Dp[pi,pi]2++PiD" : [f2]}
        waveModel = {"Dp[pi,pi]0++PiS": [f0], "Dp[pi,pi]1--PiP": [rho]}
#		waveModel = {"Dp[pi,pi]0++PiS" : [f0]}
#		waveModel = {"Dp[pi,pi]1--PiP" : [rho]}

    elif modelMode == "fixedShapes":
        useBF = False
        merge0pp = False
        polyDegree = 0
        polyComplex = True
        waveModel = {}
        for sector in sectors:
            #			if "3--" in sector:
            #				rho = pc.rpwaBreitWignerInt(0.13957018,0.13957018,0.13957018,1,1)
            #				rho.setParameters([1.2, .2])
            #				model = [rho]
            #				waveModel[sector] = model
            #				continue
            if sector in sectorUseMap:
                if not sectorUseMap[sector]:
                    continue
            model = []
            fileNames = getFileNameForSector(sector, useBF, merge0pp)
            #		print fileNames
            for fn in fileNames:
                param = pc.fixedParameterization(fn,
                                                 polynomialDegree=polyDegree,
                                                 complexPolynomial=polyComplex)
                model.append(param)
            waveModel[sector] = model
#		for sector in sectors: # Ovveride with free rho parameterization
#			if '1--' in sector:
#				rho = pc.rpwaBreitWignerInt(0.13957018,0.13957018,0.13957018,1,0) # Override here
#				rho.setParameters([.77549, .1491])
#				waveModel[sector] = [rho]

    elif modelMode == "explicitRhoFile":
        if not os.path.isfile(rhoFileName):
            raise IOError("Rho file does not exist")
        param = pc.fixedParameterization(rhoFileName,
                                         polynomialDegree=0,
                                         complexPolynomial=False)
        waveModel = {}
        for sector in sectors:
            if '1--' in sector:
                waveModel[sector] = [param]

    elif modelMode == "pipiS":
        pipiSfileName = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/zeroModes/bwAmplitudes_noBF/amp_0mp0pSigmaPiS"
        pipiSw = pc.fixedParameterization(pipiSfileName,
                                          polynomialDegree=0,
                                          complexPolynomial=False)
        waveModel = {"0-+0+[pi,pi]0++PiS": [pipiSw]}

    elif modelMode == "none":
        waveModel = {}
        for sector in sectors:
            waveModel[sector] = []

    else:
        raise RuntimeError("modelMode: '" + modelMode + "' is unknown")

    uniCOMA = False
    with root_open(inFileName, "READ") as inFile:
        histNames = GetKeyNames(inFile)
        histListReal = []
        histListImag = []
        histListNorm = []
        histListIndx = []
        nAmplMax = 0
        for sector in sectors:
            realHistName = sector + "_" + str(tBin) + "_real"
            histReal = inFile.Get(realHistName)
            if not histReal:
                raise IOError("Could not get '" + realHistName + "' from '" +
                              inFileName + "'")
            histReal.SetDirectory(0)
            histListReal.append(histReal)

            imagHistName = sector + "_" + str(tBin) + "_imag"
            histImag = inFile.Get(imagHistName)
            if not histImag:
                raise IOError("Could not get '" + imagHistName + "' from '" +
                              inFileName + "'")
            histImag.SetDirectory(0)
            histListImag.append(histImag)

            normHistName = sector + "_" + str(tBin) + "_norm"
            histNorm = inFile.Get(normHistName)
            if not histNorm:
                raise IOError("Could not get '" + normHistName + "' from '" +
                              inFileName + "'")
            histNorm.SetDirectory(0)
            histListNorm.append(histNorm)

            indexHistName = sector + "_" + str(tBin) + "_index"
            histIndx = inFile.Get(indexHistName)
            if not histIndx:
                raise IOError("Could not get '" + indexHistName + "' from '" +
                              inFileName + "'")
            histIndx.SetDirectory(0)
            nAmplMax = max(nAmplMax, int(2 * histIndx.GetMaximum()))
            histListIndx.append(histIndx)
        histsToFill = []
        comaHists = []
        intHistsReal = []
        intHistsImag = []
        for mBin in range(startBin, stopBin):
            comaHistName = "COMA_" + str(tBin) + "_" + str(mBin)
            comaHist = inFile.Get(comaHistName)
            if not comaHist:
                uniCOMA = True
                print "Could not get '" + comaHistName + "' from '" + inFileName + "'", "USING IDENTITY"
                comaHist = pyRootPwa.ROOT.TH2D(comaHistName, comaHistName,
                                               nAmplMax, 0., 1., nAmplMax, 0.,
                                               1.)
                for i in range(nAmplMax):
                    comaHist.SetBinContent(i + 1, i + 1, 1.)

            comaHist.SetDirectory(0)
            if produceTotals:
                realHistName = "INTEGRAL_r_" + str(tBin) + "_" + str(mBin)
                realHist = inFile.Get(realHistName)
                if not realHist:
                    raise IOError("Could not get '" + realHistName +
                                  "' from '" + inFileName + "'")
                intHistsReal.append(realHist)
                imagHistName = "INTEGRAL_i_" + str(tBin) + "_" + str(mBin)
                imagHist = inFile.Get(imagHistName)
                imagHist.SetDirectory(0)
                if not imagHist:
                    raise IOError("Could not get '" + imagHistName +
                                  "' from '" + inFileName + "'")
                intHistsImag.append(imagHist)
            comaHists.append(comaHist)

        if not referenceWave == "":
            refHistReal = inFile.Get(referenceWave + "_" + str(tBin) + "_real")
            refHistReal.SetDirectory(0)
            if not refHistReal:
                raise IOError("Could not get '" + referenceWave + "_" +
                              str(tBin) + "_real" + "' from '" +
                              self.inFileName + "'")
            refHistImag = inFile.Get(referenceWave + "_" + str(tBin) + "_imag")
            refHistImag.SetDirectory(0)
            if not refHistImag:
                raise IOError("Could not get '" + referenceWave + "_" +
                              str(tBin) + "_imag" + "' from '" +
                              self.inFileName + "'")
            refHistIndex = inFile.Get(referenceWave + "_" + str(tBin) +
                                      "_index")
            refHistIndex.SetDirectory(0)
            if not refHistIndex:
                raise IOError("Could not get '" + referenceWave + "_" +
                              str(tBin) + "_index" + "' from '" +
                              self.inFileName + "'")
            changeReferenceWave(histListReal, histListImag, histListIndx,
                                comaHists, refHistReal, refHistImag,
                                refHistIndex, startBin, stopBin)

        ab = allBins(startBin, stopBin, histListReal, histListImag,
                     histListNorm, histListIndx, comaHists, intHistsReal,
                     intHistsImag)
    with root_open(zeroFileName, "READ") as inFile:
        zeroCount = 0
        zeroHistList = []
        eigenHistList = []
        while True:
            zeroName = "zero" + str(zeroCount) + "_" + str(tBin)
            eigenName = "eigen" + str(zeroCount) + "_" + str(tBin)
            zeroHist = inFile.Get(zeroName)
            if not zeroHist:
                break
            zeroHist.SetDirectory(0)
            #		print "Adding zero-mode"
            zeroCount += 1
            if not zeroForSectors(sectors, zeroHist.GetTitle()):
                continue
            zeroHistList.append(zeroHist)

            eigenHist = inFile.Get(eigenName)
            eigenHist.SetDirectory(0)
            if eigenHist:
                eigenHistList.append(eigenHist)
        if (not len(eigenHistList) == 0) and (not len(eigenHistList)
                                              == len(zeroHistList)):
            raise ValueError(
                "Number of eigenvalue histograms does not match, but is also nonzero"
            )
        removeCertainZeroModes(zeroHistList, eigenHistList)
        for zeroHist in zeroHistList:
            borders = getZeroHistBorders(zeroHist)
            ab.addZeroMode(borders, zeroHist)

        rotateToFourPPampls = False
        if rotateToFourPPampls:
            fourPPampls = loadAmplsTM(fourPPamplFileName)
            ab.removePhases(fourPPampls[tBin][startBin:stopBin])

#		ab.rotateToPhaseOfBin(10)
        zeroModeComaVal = 100.  #float(sys.argv[1])
        #		zeroModeComaVal = 100000.
        #		zeroModeComaVal = "unchanged"
        #		ab.removeZeroModeFromComa()
        #		ab.addComaValueForZeroMode(zeroModeComaVal)
        #		ab.removeGlobalPhaseFromComa()

        if phaseFit:
            ab.setMassRanges(sectorRangeMap)
            for mb in ab.massBins:
                mb.setZeroTheory()
            from random import random
            ab.initChi2(waveModel)
            nBin = startBin
            leBin = ab.massBins[nBin - startBin]
            nTries = 10
            mnn = float("inf")
            #			for tr in range(nTries):
            #				print "at",tr,'/',nTries
            #				pars  = [random() for _ in range(leBin.nParAll())]
            ##				print leBin.phaseChi2(pars)
            #				res = scipy.optimize.minimize(leBin.phaseChi2, pars)
            #				if res.fun < mnn:
            #					print "Improved from",mnn,"to",res.fun,"in try",tr
            #					mnn = res.fun
            #					bestPar = res.x[:]
            #			print bestPar, "bestPar"
            paramsPhaseChi2 = [
                148.57310258, 143.66171657, 116.67030827, -6.8412118
            ]
            paramsAmplChi2 = [
                -52.51465293, -10.3576874, 6.69282325, 64.28970961
            ]
            print "----------------====----------------------------"
            leBin.phaseChi2(paramsPhaseChi2)
            print "----------------====----------------------------"
            leBin.phaseChi2(paramsAmplChi2)
            print "----------------====----------------------------"
            #			paramsZ = [bestPar[0], bestPar[1]] * 1 # Very, very bad hack...
            #			paramsZ = paramsPhaseChi2[:2]
            ptu = paramsAmplChi2
            leBin.phaseChi2(ptu)
            paramsZ = ptu[:2]

        if doSpecialOneBinFit >= 0:
            specialBin = ab.massBins[doSpecialOneBinFit]
            specialBin.initChi2(waveModel)
            print "Doing special fit for: ", +specialBin.bin3pi
            pars = [.77549, .1491]
            if modelMode == "explicitRhoFile":
                return specialBin.chi2([])
            res = scipy.optimize.minimize(specialBin.chi2, pars)
            hi = res.hess_inv
            print "m0 = ", res.x[0], "+-", (2 * hi[0, 0])**.5
            print "G0 = ", res.x[1], "+-", (2 * hi[1, 1])**.5
            print "Giving a Chi2 of:", res.fun
            sys.exit(0)

        if not useSmooth and not phaseFit and not modelMode == "none":
            ab.initChi2(waveModel)
            ab.setMassRanges(sectorRangeMap)
            totalPars = []
            for k in waveModel:
                for f in waveModel[k]:
                    totalPars += f.getParameters()
            shapePars = []
            if not len(totalPars) == 0 and fitShape:
                res = scipy.optimize.minimize(ab.chi2, totalPars)
                hi = res.hess_inv
                print "m0 = ", res.x[0], "+-", (2 * hi[0, 0])**.5
                print "G0 = ", res.x[1], "+-", (2 * hi[1, 1])**.5
                print "Giving a Chi2 of:", res.fun
                shapePars = res.x

    #		for k in waveModel:
    #			for f in waveModel[k]:
    #				print "function parameters",f.getParameters()
            chi2, params = ab.chi2(shapePars, returnParameters=True)
            errs = ab.getNonShapeUncertainties(shapePars)
            #			print "pars", len(params[0])
            #			print "errs",len(errs[0])
            #			print params,"params"
            #		print "fitted = [",
            #			for i in range(1, len(params[0])/2):
            #				if not i == 1:
            #					print ',',
            #				print params[0][2*i], '+'+ str(params[0][2*i+1])+'j',
            #			print ']'
            paramsZ = ab.linearizeZeroModeParameters(params)
            #			print "I am here!!!,", paramsZ
            zmPar = ab.getNonShapeParameters()
            ab.setTheoryFromOwnFunctions(params, True)
    #		print "The final chi2 =",chi2
    #		with open("theFinalChi2s.txt", 'a') as out:
    #			out.write("zero-mode-coma-val "+str(zeroModeComaVal) + " finalChi2 " + str(chi2) +'\n')
        elif not phaseFit:
            A, B, C = ab.getSmoothnessABC()
            paramsZ = -np.dot(la.inv(A + np.transpose(A)), B)

        if modelMode == 'none':
            ab.initChi2(waveModel)
            params = []
            for mb in ab.massBins:
                params.append([0.] * mb.nFunc * 2)

            ab.setTheoryFromOwnFunctions(params, True)

#		for i in range(len(paramsZ)):
#			paramsZ[i] = 0.

#		ab.writeZeroModeCoefficients(paramsZ, "zeroModeCorrections_std11", str(tBin))

#		for i in range(len(zmPar)):
#			for j in range(len(zmPar[i])-2,len(zmPar[i])):
#				zmPar[i][j] = 0.
#	c2 = ab.getChi2forNonShapeParameters(zmPar)
#	c2Res = ab.eigenbasisChi2contributions(zmPar)
#	c2Sum = 0.
#	for pair in c2Res[0]:
#		c2Sum += pair[1]**2/pair[0]
#	with open("chi2Contribitions.txt", 'w') as outFile:
#		for i,val in enumerate(c2Res[0]):
#			outFile.write(str(i) + ' ' + str(val[0]) + ' ' + str(val[1]) + ' ' + str(val[1]/val[0]**.5) + '\n')
#	print c2, c2Sum

#		print sys.argv[1], sys.argv[2], "-->>|", ab.getChi2forNonShapeParameters(zmPar),
#		ab.removeAllCorrelations(removeReImCorrel = False)
#		print ab.getChi2forNonShapeParameters(zmPar),
#		ab.removeAllCorrelations(removeReImCorrel = True)
#		print ab.getChi2forNonShapeParameters(zmPar),"|<<--"
#	return

        intenses = []
        reals = []
        imags = []
        correl = []
        phases = []
        intensD = []
        realsD = []
        imagsD = []
        phasesD = []
        intensT = []
        realsT = []
        imagsT = []
        phasesT = []

        for rh in histListReal:
            Ih = rh.Clone()
            Ih.Reset()
            intenses.append(Ih)

            realH = rh.Clone()
            realH.Reset()
            reals.append(realH)

            imagH = rh.Clone()
            imagH.Reset()
            imags.append(imagH)

            reImCorrH = rh.Clone()
            reImCorrH.Reset()
            correl.append(reImCorrH)

            phaseH = rh.Clone()
            phaseH.Reset()
            phases.append(phaseH)

            ID = rh.Clone()
            ID.Reset()
            intensD.append(ID)

            rD = rh.Clone()
            rD.Reset()
            realsD.append(rD)

            iD = rh.Clone()
            iD.Reset()
            imagsD.append(iD)

            pD = rh.Clone()
            pD.Reset()
            phasesD.append(pD)

            IT = rh.Clone()
            IT.Reset()
            intensT.append(IT)

            rT = rh.Clone()
            rT.Reset()
            realsT.append(rT)

            iT = rh.Clone()
            iT.Reset()
            imagsT.append(iT)

            pT = rh.Clone()
            pT.Reset()
            phasesT.append(pT)

        zeroP = [0.] * len(paramsZ)
        #		paramsZ = zeroP

        #		print paramsZ
        #		paramsZ = np.asarray([ 329.73899894 , 150.29589973]) # For the wrong parameterizations in the D decay
        #		paramsZ = np.asarray([ -49.77267381,    2.93486152]) # For the P-only for in 0-+0+ at bin 25

        if not uniCOMA:
            ab.removeZeroModeFromComa()
            ab.removeGlobalPhaseFromComa()

        if produceTotals:
            hists = []
            for m in range(len(sectors)):
                hists.append(get3PiHistogram(sectors[m] + "_t" + str(tBin)))
                ab.fillTotal(paramsZ, hists)

            with root_open("totals_noZeroModeWavesFromStd11.root", "UPDATE"):
                for h in hists:
                    h.Write()
            return

        ab.fillHistograms(paramsZ, intenses)
        ab.fillHistograms(paramsZ, reals, mode=REAL)
        ab.fillHistograms(paramsZ, imags, mode=IMAG)
        ab.fillHistograms(paramsZ, phases, mode=PHASE)
        ab.fillHistograms(paramsZ, correl, mode=REIMCORRELATION)

        ab.fillHistograms(zeroP, intensD)
        ab.fillHistograms(zeroP, realsD, mode=REAL)
        ab.fillHistograms(zeroP, imagsD, mode=IMAG)
        ab.fillHistograms(zeroP, phasesD, mode=PHASE)

        if not useSmooth:
            ab.fillHistograms(zeroP, intensT, mode=INTENSTHEO)
            ab.fillHistograms(zeroP, realsT, mode=REALTHEO)
            ab.fillHistograms(zeroP, imagsT, mode=IMAGTHEO)
            ab.fillHistograms(zeroP, phasesT, mode=PHASETHEO)

        for i in range(len(histListReal)):
            renormToBinWidth(intenses[i])
            renormToBinWidth(intensD[i])
            renormToBinWidth(intensT[i])
            renormToBinWidth(reals[i], .5)
            renormToBinWidth(realsD[i], .5)
            renormToBinWidth(realsT[i], .5)
            renormToBinWidth(imags[i], .5)
            renormToBinWidth(imagsD[i], .5)
            renormToBinWidth(imagsT[i], .5)
            renormToBinWidth(correl[i], )
            allIsZero = True
            for binX in range(intensT[i].GetNbinsX()):
                for binY in range(intensT[i].GetNbinsY()):
                    if not intensT[i].GetBinContent(binX + 1, binY + 1) == 0.:
                        allIsZero = False
                        break
                if not allIsZero:
                    break  # # # # # # # # # # # # # # # # #
            ric = correl[i]

            noRun = False
            if not allIsZero:
                rv = resultViewer([intenses[i], intensD[i], intensT[i]],
                                  [reals[i], realsD[i], realsT[i]],
                                  [imags[i], imagsD[i], imagsT[i]],
                                  [phases[i], phasesD[i], phasesT[i]],
                                  startBin=startBin,
                                  reImCorrel=ric,
                                  noRun=noRun)
            else:
                rv = resultViewer([intenses[i], intensD[i]],
                                  [reals[i], realsD[i]], [imags[i], imagsD[i]],
                                  [phases[i], phasesD[i]],
                                  startBin=startBin,
                                  reImCorrel=ric,
                                  noRun=noRun)
            rv.titleRight = getProperWaveName(sectors[i])
            #			rv.titleRight    = r"$0^{-+}0^+[\pi\pi]_{0^{++}}\pi$S"
            #			rv.titleRight    = r"$0^{-+}0^+[\pi\pi]_{1^{--}}\pi$P"
            #			rv.tString       = ""
            rv.tString = getProperDataSet(inFileName, tBin)
            #			rv.tString       = "Monte Carlo"
            #			rv.tString       = ""
            rv.titleFontSize = 11

            rv.printLiminary = False
            rv.topMarginIntens = 1.4
            #			rv.scaleTo       = "corr"
            #			rv.writeBinToPdf(startBin, stdCmd = ["rhoFixing_2D.pdf", "rhoFixing_intens.pdf", [], "rhoFixing_argand.pdf", []])
            #			rv.plotCorr      = False
            #			rv.plotTheo      = False
            #			rv.plotData      = False
            rv.run()
Exemplo n.º 5
0
def main():
	checkLaTeX()
	style = modernplotting.mpplot.PlotterStyle()
#	style.p2dColorMap = 'ocean_r'
#	style.p2dColorMap = 'YlOrRd'
	style.p2dColorMap = 'Reds'

	inFileName    = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_exotic.root"
	sectors          = ["1-+1+[pi,pi]1--PiP"]
	tBin = int(sys.argv[1])
	if tBin < 0 or tBin > 3:
		raise ValueError("Invalid t' bin: " + str(tBin))

	tBins            = [tBin]

	startBin         = 11
	stopBin          = 50

#	startBin = 26
#	stopBin  = 28

	acv = 130. # artificial coma value
#	acv = 1.3e-5 # artificial coma value

	methodBinRanges = {
	                   "fitF2"        : (22, 50),
	                   "fitRhoF"      : (22, 50),
	                   "fixedShapeF2" : (22, 50)}
#	methodBinRanges = {} # Override here 


	sectorRangeMap = {"1-+1+[pi,pi]1--PiP":(0.,1.12)}	
#	sectorRangeMap = {}


	allMethods       = {}
	methodStrings    = {}
	shortlabels      = {  "fixedShapeF0"      : r"$\text{fix}_{f_0}^{~}$",
	                      "fixedShapeRhoP"    : r"$\text{fix}_\rho^{P}$",
	                      "fixedShapeRhoF"    : r"$\text{fix}_\rho^{F}$",
	                      "fixedShapeBothRho" : r"$\text{fix}_\rho^{2}$",
	                      "fixedShapeF2"      : r"$\text{fix}_{f_2}$",
	                      "fixedShapes"       : r"$\text{fix}_\text{all}^{~}$",
	                      "pipiS"             : r"$\phi_{[\pi\pi]_S}^{~}$",
	                      "fitRho"            : r"$\text{fit}_\rho$",
	                      "fitRhoP"           : r"$\text{fit}_\rho^{P}$",
	                      "fitRhoF"           : r"$\text{fit}_\rho^{F}$",
	                      "fitBothRho"        : r"$\text{fit}_\rho^{2}$",
	                      "fitF2"             : r"$\text{fit}_{f_2}$",
	                      "smooth"            : r"smooth"}
	print "Starting with fixed shapes"
	fixedShapes = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, sectorRangeMap = sectorRangeMap, acv = acv)
	allMethods["fixedShapes"] = fixedShapes
	print "Finished with fixed shapes"
	fullSig = fixedShapes.getZeroModeSignature()

	fullRanges = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, sectorRangeMap = {}, acv = acv)


	scalle     = False
	Xcheck     = True
	resolvedWA = fixedShapes.getZeroModeParametersForMode()
	if scalle:
		folder = "./comparisonResultsData_1mp_scale/"
	else:
		folder = "./comparisonResultsData_1mp/"

#	folder = "./ellipseComparisons/"
	folder = "./"

	fileSectorName = "1mp1p1mmP"

	if False:
#	for s, sect in enumerate(fullRanges.sectors):
		fullRanges.removeZeroModeFromComa()
#		rv = fullRanges.produceResultViewer(cloneZeros(resolvedWA),s, noRun = True, plotTheory = True)
		rv = fullRanges.produceResultViewer(resolvedWA,s, noRun = True, plotTheory = True)
#		rv.writeToRootFile("exoticForRealease_"+str(tBin)+".root")

		rv.titleFontSize = 11
		rv.showColorBar  = True
		rv.XcheckArgand  = Xcheck
		rv.writeBinToPdf(startBin, stdCmd = [ fileSectorName + "_2D_t"+str(tBin)+".pdf", "", [], "", []])

		rv.labelPoints     = [0,10,15,20]
		if tBin in [0,1,2] and not scalle:
			rv.labelPoints     = [10,15,20]
		rv.makeLegend      = True
		if scalle:
			rv.scaleTo = "maxCorrData"
			rv.yAxisShift      = 300.
			rv.tStringYpos     = 0.8
			rv.topMarginIntens = 1.4
			fakkkk             = 1.
		else:
			rv.plotData        = False
			fakkkk             = .7	
			rv.tStringYpos     = 0.8
			rv.topMarginIntens = 1.4
			rv.yAxisShift      = 100.
			rv.scaleArgandZeroLine = 0.8

		rv.addiColor     = modernplotting.colors.makeColorLighter(modernplotting.colors.colorScheme.blue, .5)
		rv.realLabel     = LaTeX_strings.realReleaseNote
		rv.imagLabel     = LaTeX_strings.imagReleaseNote
		rv.m2PiString    = LaTeX_strings.m2PiReleaseNote
		rv.intensLabel   = LaTeX_strings.intensReleaseNote
		rv.printLiminary = True
		if tBin == 3:
			if scalle:
				rv.shiftMap      = {0:(fakkkk*80.,fakkkk*-280.),10:(fakkkk*-360.,fakkkk*-50.), 15:(fakkkk*-390.,fakkkk*-30.), 20:(fakkkk*-500.,fakkkk*-10.)}
			else:
				rv.shiftMap      = {0:(fakkkk*100.,fakkkk*-280.),10:(fakkkk*-370.,fakkkk*-50.), 15:(fakkkk*-370.,fakkkk*-30.), 20:(fakkkk*-50.,fakkkk*90.)}
		if tBin == 2:
			if scalle:
				rv.shiftMap      = {0:(fakkkk*50.,fakkkk*-300.),10:(fakkkk*-480.,fakkkk*-50.), 15:(fakkkk*-500.,fakkkk*-30.), 20:(fakkkk*0.,fakkkk*70.)}
			else:
				rv.shiftMap      = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-420.,fakkkk*-50.), 15:(fakkkk*-450.,fakkkk*-30.), 20:(fakkkk*0.,fakkkk*70.)}
		if tBin == 1:
			if scalle:
				rv.shiftMap      = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-300.,fakkkk*-50.), 15:(fakkkk*-400.,fakkkk*-30.), 20:(fakkkk*60.,fakkkk*30.)}
			else:
				rv.shiftMap      = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-350.,fakkkk*-50.), 15:(fakkkk*-400.,fakkkk*-30.), 20:(fakkkk*80.,fakkkk*30.)}
		if tBin == 0:
			if scalle:
				rv.shiftMap      = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-450.,fakkkk*-50.), 15:(fakkkk*-450.,fakkkk*-30.), 20:(fakkkk*50.,fakkkk*30.)}
			else:
				rv.shiftMap      = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-410.,fakkkk*-50.), 15:(fakkkk*-420.,fakkkk*-30.), 20:(fakkkk*70.,fakkkk*30.)}

		rv.scale(1000./40.)
		for b in range(startBin, stopBin):
			if not b == 27:
				continue
#			intensNames = [name+".intens" for name in fileNames[sect,b]]
#			argandNames = [name+".argand" for name in fileNames[sect,b]]
			if not scalle:
				intensNames = []
				argandNames = []
#			intensNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/singlePlots/1mp1p1mm_t"+str(tBin)+".intens"]
#			argandNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/singlePlots/1mp1p1mm_t"+str(tBin)+".argand"]

			intensNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/zeroModeFitter_2D/filesForRelease/fullRangeFixing_"+str(tBin)+".intens"]
			argandNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/zeroModeFitter_2D/filesForRelease/fullRangeFixing_"+str(tBin)+".argand"]

			if Xcheck:
				intensNames    = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/singlePlots/1mp1p1mm_t"+str(tBin)+".intens"]
				argandBaseName = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/singlePlots/dimasEllipses/1mp1p1mm_"+str(b)+"_"+str(tBin)+"_<ndx>.argand"
				argandNames    = [argandBaseName.replace("<ndx>", ndx) for ndx in ['0','1','2','3','C']]

#			print argandNames
#			return

#			intensNames = []
#			argandNames = []

			for fn in intensNames:
				if not os.path.isfile(fn):
					raise IOError
			for fn in argandNames:
				if not os.path.isfile(fn):
					raise IOError

#			rv.writeAmplFiles(b, fileName = "./filesForRelease/fullRangeFixing_"+str(tBin))

			rv.legendMethods    = "Full range"
			if Xcheck:
				rv.addiXoffset      = 0.01
				rv.addiColor        = modernplotting.colors.colorScheme.red
				rv.legendMethods    = "X-check"

#			rv.tString          = ""
#			rv.scaleFakk        = 1000.
#			rv.writeBinToPdf(b, stdCmd = ["","",[], folder+  sect + "_data_argand_"+str(b)+"_"+str(tBin)+".pdf", argandNames])
			rv.writeBinToPdf(b, stdCmd = ["",folder +  fileSectorName + "_int_m"+str(b)+"_t"+str(tBin)+".pdf", intensNames, folder+  fileSectorName + "_arg_m"+str(b)+"_t"+str(tBin)+".pdf", argandNames])
#			rv.wiriteReImToPdf(b, sect + "_data_<ri>_"+str(b)+"_"+str(tBin)+".pdf")

	with root_open("1mp1p_totals_t"+str(tBin)+".root", "RECREATE"):
		hists = fullRanges.makeTheoryTotals()
		for tb in hists:
			for h in tb:
				h.Write()
		hists = fullRanges.makeTheoryTotals(REAL)
		for tb in hists:
			for h in tb:
				h.Write()
		hists = fullRanges.makeTheoryTotals(IMAG)
		for tb in hists:
			for h in tb:
				h.Write()
		hists = fullRanges.makeTheoryTotals(REIMCORRELATION)
		for tb in hists:
			for h in tb:
				h.Write()
		totalHists = fixedShapes.getTotalHists(resolvedWA)
		for tb in totalHists:
			for h in tb:
				h.Write()
	return
def main():
	checkLaTeX()
	style = modernplotting.mpplot.PlotterStyle()
#	style.p2dColorMap = 'ocean_r'
#	style.p2dColorMap = 'YlOrRd'
	style.p2dColorMap = 'Reds'

#	referenceWave = ""

	rhoRange          = None
	for a in sys.argv:
		if a.startswith("range"):
			rhoRange = float(a[5:])

#	rhoRange = None
	if rhoRange is None:
		sectorRangeMap = {}
		rhoRangeString = ""
	else:
		sectorRangeMap = {"1++0+[pi,pi]1--PiS":(0.,rhoRange)}
		rhoRangeString = "_range"+str(rhoRange)

	tBin = int(sys.argv[1])
	if tBin < 0 or tBin > 3:
		raise ValueError("Invalid t' bin: " + str(tBin))
	if len(sys.argv) == 3:
		study = sys.argv[2]
		studyAdder = "_"+study
	else:
		study = "std11"
		studyAdder = ""
	print "Study: "+study

	inFileName       = fileNameMap[study]
	sectors          = ["1++0+[pi,pi]0++PiP", "1++0+[pi,pi]1--PiS"]
	tBins            = [tBin]

	startBin = 13
	stopBin  = 50

#	startBin = 35
#	stopBin  = 36

	if len(sys.argv) > 3:
		startBin = int(sys.argv[2])
		stopBin  = int(sys.argv[3])

	plotDataType = '.pdf'

#	startBin = 30
#	stopBin  = 34


	allMethods       = {}
	methodStrings    = {}
	shortlabels      = {  "fixedShapeF0"    : r"$\text{fix}_{f_0}^{~}$",
	                      "fixedShapeRho"   : r"$\text{fix}_\rho^{~}$",
	                      "fixedShapeRho1G" : r"$\text{fix}_\rho^{1\Gamma}$",
	                      "fixedShapeRho2G" : r"$\text{fix}_\rho^{2\Gamma}$",
	                      "fixedShapes"     : r"$\text{fix}_\text{all}^{~}$",
	                      "pipiS"           : r"$\phi_{[\pi\pi]_S}^{~}$",
	                      "fitRho"          : r"$\text{fit}_\rho^{~}$",
	                      "fitRhoPrime"     : r"$\text{fit}_{\rho^\prime}^{~}$",
	                      "fitRho1G"        : r"$\text{fit}_\rho^{1\Gamma}$",
	                      "fitRho2G"        : r"$\text{fit}_\rho^{2\Gamma}$",
	                      "smooth"          : r"smooth"}

#       # - - - - --- Start here with the model builting --- - - - - #       #


	params = [ptc.parameter( .36674e-01, "lambP" ),
		  ptc.parameter( .31230e-02, "lambPP"),
		  ptc.parameter( .83386    , "M"     ),
		  ptc.parameter( .19771    , "G"     ),
		  ptc.parameter(1.4974     , "MP"    ),
		  ptc.parameter( .78518    , "GP"    ),
		  ptc.parameter(1.6855     , "MPP"   ),
		  ptc.parameter( .80109    , "GPP"   ),
		  ptc.parameter( .17254    , "alP"   ),
		  ptc.parameter(-.97591    , "phP"   ),
		  ptc.parameter( .23374    , "alPP"  ),
		  ptc.parameter(2.1982     , "phPP"  )]

	vff = vectorFormFactor(params)
	vff.allowSubThr = True

	seedint = randint(0,10000)

	model      = [vff]
	acv = None


#	print "Start with fixed shape rho"
#	fitRho = doFitRho(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, writeResultToFile = "rhoMassesAndWidths_1++0+1--_global"+rhoRangeString+".dat", sectorRangeMap = {"1++0+[pi,pi]1--PiS":(0.,1.12)})
#	fixedShapes = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave)
#	fixedShapeRho = doFixedShapes(inFileName, sectors[1:], startBin, stopBin, tBins,referenceWave = referenceWave)
#	allMethods["fixedShapeRho"] = fixedShapeRho
#	print "Finished with fixed shape rho"
#	RV = fixedShapes.produceResultViewer(fitRho.getZeroModeParametersForMode(),"1++0+[pi,pi]1--PiS", noRun = True, plotTheory = True)
#	RV.plotData = True
#	for b in range(startBin, stopBin):
#		RV.connectTheoPoints = range(100)
#		plotNameBase = "./fit_rho_plots/1pp0p1mmPiS_<mode>_"+str(b)+"_"+str(tBin)+".pdf"
#		RV.writeBinToPdf(b, stdCmd = ["", plotNameBase.replace("<mode>","intens"), [],  plotNameBase.replace("<mode>","argand"), []])
#	RV = fixedShapes.produceResultViewer(fitRho.getZeroModeParametersForMode(),"1++0+[pi,pi]0++PiP", noRun = True, plotTheory = False)
#	RV.plotData = True
#	for b in range(startBin, stopBin):
#		RV.connectTheoPoints = range(100)
#		plotNameBase = "./fit_rho_plots/1pp0p0ppPiP_<mode>_"+str(b)+"_"+str(tBin)+".pdf"
#		RV.writeBinToPdf(b, stdCmd = ["", plotNameBase.replace("<mode>","intens"), [],  plotNameBase.replace("<mode>","argand"), []])
#	return 
#       # - - - - --- Stop the model building here --- - - - - #       #
#	zeroModeParameters = None
#	fixZeroMode        = False

#	sectorRangeMapFix = {"1++0+[pi,pi]1--PiS":(0.,1.12)}
#	if fixZeroMode:
#		fixedShapes        = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, sectorRangeMap = sectorRangeMapFix)
#		zeroModeParameters = fixedShapes.getZeroModeParametersForMode()

#		RV = fixedShapes.produceResultViewer(zeroModeParameters,"1-+1+[pi,pi]1--PiP", noRun = True, plotTheory = True)
#		RV.plotData = True
#		for b in range(startBin, stopBin):
#			plotNameBase = "./Kmatrix_plots/1mp1p1mmPiP_<mode>_"+str(b)+"_"+str(tBin)+".pdf"
#			RV.writeBinToPdf(b, stdCmd = ["", plotNameBase.replace("<mode>","intens"), [],  plotNameBase.replace("<mode>","argand"), []])
#		return

#	if rhoRange is None:
#		rrs = ""
#	else:
#		rrs = "range"+str(rhoRange)+'_'
#
#	resultFile  =  "./vectorFormFactorResults_subThresh/1pp_vff_t"+str(tBin)+"_m"+str(startBin)+'-'+str(stopBin)+'_'+str(seedint)+".dat"
#	fitter      = doFunctionFit(inFileName, model, startBin, stopBin, tBins, sectorRangeMap, referenceWave = referenceWave, acv = acv, zeroModeParameters = zeroModeParameters, writeResultToFile = resultFile)
#	print " - - - - - - tro - - - - - - "
#	print fitter.model.bestChi2UpToNow
#	print fitter.model.bestPar
#	print " - - - - - - lolo - - - - - - "
#	if not fixZeroMode:
#		fitter.calculateNonShapeParameters()
#		zeroModeParameters = fitter.getZeroModeParametersForMode()
	

#       # - - - - --- Start the evaluations here --- - - - - #       #
#	nBinsPlot = 1000
#	def fPlot(v):
#		return v.imag
#	Kmatrix.secondSheet = True
#
#	res = scipy.optimize.minimize(Kmatrix.absInverse,[rhoRe0,rhoIm0])
#	print res.x,"pole position"
#	mfv = res.fun
#	resSting = str(res.fun)+ " function value should be zero"
#	print resSting
#	BWstring = "BW par: "+str(abs(res.x[0])**.5)+" "+str(abs(res.x[1])/abs(res.x[0])**.5)+" (all absolute values)"
#	print BWstring
#	print "Starting BW error ersimation"
#	nPoints     = 1000
#	poleMean    = res.x
#	poleSamples = []
#	for i in range(nPoints):
#		pts = np.random.multivariate_normal(fitter.fitParameters, fitter.MINUITcoma)
#		fitter.MINUIT_function(pts) # Call the function once to set parameters inside
##		fitter.model[0].setParametersAndErrors(pts, fitter.MINUITerrs)
#		res = scipy.optimize.minimize(Kmatrix.absInverse,poleMean)
#		if abs(res.fun) > 100*mfv:
#			raise ValueError("No more pole found: fval = "+str(res.fun))
#		poleSamples.append(res.x)
#		print i
#	meanPole = [0.,0.]
#	for p in poleSamples:
#		meanPole[0] += p[0]
#		meanPole[1] += p[1]
#	meanPole[0] /= len(poleSamples)
#	meanPole[1] /= len(poleSamples)
#	poleComa = [[0.,0.],[0.,0.]]
#	for p in poleSamples:
#		poleComa[0][0] += (p[0]-meanPole[0])**2
#		poleComa[0][1] += (p[0]-meanPole[0])*(p[1]-meanPole[1])
#		poleComa[1][0] += (p[1]-meanPole[1])*(p[0]-meanPole[0])
#		poleComa[1][1] += (p[1]-meanPole[1])**2
#	poleComa[0][0] /= len(poleSamples)-1
#	poleComa[0][1] /= len(poleSamples)-1
#	poleComa[1][0] /= len(poleSamples)-1
#	poleComa[1][1] /= len(poleSamples)-1
#	print " - - - - - - le compaire pramaitre  - - - - - - "
#	print meanPole, poleMean
#	print " - - - - - - le compaire pramaitre  - - - - - - "
#	print poleComa
#	jac = []
#	delta = 1.e-7
#	delPars = fitter.fitParameters[:]
#	for i in range(len(delPars)):
#		delPars[i] += delta
#		fitter.MINUIT_function(delPars)
#		res = scipy.optimize.minimize(Kmatrix.absInverse,poleMean)
#		delPars[i] -= delta
#		if abs(res.fun) > 100*mfv:
#			raise ValueError("No more pole found: fval = "+str(res.fun))
#		jac.append([(res.x[0]-poleMean[0])/delta,(res.x[1]-poleMean[1])/delta])
#	poleComaJac = [[0.,0.],[0.,0.]]
#	for i in range(2):
#		for j in range(len(jac)):
#			for k in range(len(jac)):
#				for l in range(2):
#					poleComaJac[i][l] += jac[j][i]*jac[k][l]*fitter.MINUITcoma[j][k]
#	print " - - - - - - le compaire coma  - - - - - - "
#	print poleComaJac, poleComa
#	print " - - - - - - le compaire coma  - - - - - - "
#
#	with open(resultFile,'a') as outFile:
#		outFile.write('\n'+BWstring+" "+resSting)
#
#	res = scipy.optimize.minimize(Kmatrix.absInverse,[mPrime**2,mPrime*Gprime])
#	print res.x,"pole position"
#	resSting = str(res.fun)+ " function value should be zero"
#	print resSting
#	BWstring = "BW' par: "+str(abs(res.x[0])**.5)+" "+str(abs(res.x[1])/abs(res.x[0])**.5)+" (all absolute values)"
#	print BWstring
#	with open(resultFile,'a') as outFile:
#		outFile.write('\n'+BWstring+" "+resSting)
#       # - - - - --- Start the evaluations here --- - - - - #       #
#	doPlots = True
#	if doPlots:
#		RV = fitter.produceResultViewer(zeroModeParameters,"1++0+[pi,pi]1--PiS", noRun = True, plotTheory = True)
#		RV.plotData = True
#		for b in range(startBin, stopBin):
#			RV.connectTheoPoints = range(100)
#			plotNameBase = "./vectorFormFactor_plots/1pp0p1mmPiS_<mode>_"+str(b)+"_"+str(tBin)+".pdf"
#			RV.writeBinToPdf(b, stdCmd = ["", plotNameBase.replace("<mode>","intens"), [],  plotNameBase.replace("<mode>","argand"), []])
#		RV = fitter.produceResultViewer(zeroModeParameters,"1++0+[pi,pi]0++PiP", noRun = True, plotTheory = False)
#		RV.plotData = True
#		for b in range(startBin, stopBin):
#			RV.connectTheoPoints = range(100)
#			plotNameBase = "./vectorFormFactor_plots/1pp0p0ppPiP_<mode>_"+str(b)+"_"+str(tBin)+".pdf"
#			RV.writeBinToPdf(b, stdCmd = ["", plotNameBase.replace("<mode>","intens"), [],  plotNameBase.replace("<mode>","argand"), []])
#
#	raw_input("press <enter> to exit")
#	return
#################################################################################
#################################################################################
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
#################################################################################
#################################################################################
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
#################################################################################
#################################################################################
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
#################################################################################
#################################################################################
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
#################################################################################
#################################################################################
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
#################################################################################
#################################################################################
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
#################################################################################
#################################################################################
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
#################################################################################
#################################################################################
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
#################################################################################
#################################################################################


#	fit1500 = doFit1500(inFileName, sectors[:1], startBin, stopBin, tBins, referenceWave = referenceWave, writeResultToFile = "1pp_f0_1500_massesAndWidths_global.dat")

	print "Start with fixed shape f0"
	fixedShapeF0 = doFixedShapes(inFileName, sectors[:1], startBin, stopBin, tBins,referenceWave = referenceWave)
	allMethods["fixedShapeF0"] = fixedShapeF0
	print "Finished with fixed shape f0"

	print "Start with fixed shape rho"
	fixedShapes = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave)
	fixedShapeRho = doFixedShapes(inFileName, sectors[1:], startBin, stopBin, tBins,referenceWave = referenceWave)
	allMethods["fixedShapeRho"] = fixedShapeRho
	print "Finished with fixed shape rho"
	RV = fixedShapeRho.produceResultViewer(fixedShapes.getZeroModeParametersForMode(),"1++0+[pi,pi]1--PiS", noRun = True, plotTheory = True)
	RV.plotData = True
	RV.writeBinToPdf(startBin, stdCmd = ["1pp0p1mmS_2D_"+str(tBin)+".pdf","", [], "", []])
	return
	for b in range(startBin, stopBin):
		RV.connectTheoPoints = range(100)
		plotNameBase = "./fixed_rho_plots/1pp0p1mmPiS_<mode>_"+str(b)+"_"+str(tBin)+".pdf"
		RV.writeBinToPdf(b, stdCmd = ["", plotNameBase.replace("<mode>","intens"), [],  plotNameBase.replace("<mode>","argand"), []])
	RV = fitter.produceResultViewer(fixedShapes.getZeroModeParametersForMode(),"1++0+[pi,pi]0++PiP", noRun = True, plotTheory = False)
	RV.plotData = True
	for b in range(startBin, stopBin):
		RV.connectTheoPoints = range(100)
		plotNameBase = "./fixed_rho_plots/1pp0p0ppPiP_<mode>_"+str(b)+"_"+str(tBin)+".pdf"
		RV.writeBinToPdf(b, stdCmd = ["", plotNameBase.replace("<mode>","intens"), [],  plotNameBase.replace("<mode>","argand"), []])

#	print "Start with restricted rho (1 Gamma)"
#	fixedShapeRho1G = doFixedShapes(inFileName, sectors[1:], startBin, stopBin, tBins, sectorRangeMap = {"1++0+[pi,pi]1--PiS":(mRho - Grho, mRho+Grho)},referenceWave = referenceWave)
#	allMethods["fixedShapeRho1G"] = fixedShapeRho1G
#	print "Finished with restricted rho (1 Gamma)"

#	print "Start with restricted rho (2 Gammas)"
#	fixedShapeRho2G = doFixedShapes(inFileName, sectors[1:], startBin, stopBin, tBins, sectorRangeMap = {"1++0+[pi,pi]1--PiS":(mRho -2*Grho, mRho+2*Grho)},referenceWave = referenceWave)
#	allMethods["fixedShapeRho2G"] = fixedShapeRho2G
#	print "Finished with restricted rho (2 Gammas)"

	print "Start with fixed shapes"
	fixedShapes = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave)
	allMethods["fixedShapes"] = fixedShapes
	print "Finished with fixed shapes"

#	totalHists = fixedShapes.getTotalHists(fixedShapeRho.getZeroModeParametersForMode())
#	with root_open("./totals_1pp_onlyFixedRho.root", "UPDATE") as outFileRoot:
#		for t in totalHists:
#			for m in t:
#				m.Write()
#	return

#	totalHists = fixedShapes.getTotalHists(cloneZeros(fixedShapes.getZeroModeParametersForMode()))
#	with root_open("./totals_1pp_noCorr.root", "UPDATE") as outFileRoot:
#		for t in totalHists:
#			for m in t:
#				m.Write()
#	return


#	print "Start with phase"
#	fitPiPiSshape = doF0phase(inFileName, sectors[:1], startBin, stopBin, tBins,referenceWave = referenceWave)
#	allMethods["pipiS"] = fitPiPiSshape
#	print "Finished with phase"

	print "Start with fitting rho"
	fitRho = doFitRho(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, writeResultToFile = "rhoMassesAndWidths_1++0+1--_global"+rhoRangeString+".dat", sectorRangeMap = sectorRangeMap)
	allMethods["fitRho"] = fitRho
	print "Finished with fitting rho"

#	print "Start with fitting rho'"
#	fitRhoPrime = doFitRhoPrime(inFileName, sectors, startBin, stopBin, tBins,referenceWave = referenceWave)
#	allMethods["fitRhoPrime"] = fitRhoPrime
#	print "Finished with fitting rho'"

#	print "Start with fitting restricted rho (1 Gamma)"
#	fitRho1G = doFitRho(inFileName, sectors, startBin, stopBin, tBins, sectorRangeMap = {"1++0+[pi,pi]1--PiS":(mRho - Grho, mRho+Grho)},referenceWave = referenceWave)
#	allMethods["fitRho1G"] = fitRho1G
#	print "Finished with fitting restricted rho (1 Gamma)"lsd

#	print "Start with fitting restricted rho (2 Gammas)"
#	fitRho2G = doFitRho(inFileName, sectors, startBin, stopBin, tBins, sectorRangeMap = {"1++0+[pi,pi]1--PiS":(mRho -2*Grho, mRho+2*Grho)},referenceWave = referenceWave)
#	allMethods["fitRho2G"] = fitRho2G
#	print "Finished with fitting restricted rho (2 Gammas)"

	if stopBin - startBin > 1:
		print "Start with smooth"
		smooth = doSmooth(inFileName, sectors, startBin, stopBin, tBins,referenceWave = referenceWave)
		allMethods["smooth"] = smooth
		print "Finished with smooth"

	ndfs   = {}
	params = {}
	for m in allMethods:
		ndfs[m]=  allMethods[m].getNDFforMode()
		params[m] = allMethods[m].getZeroModeParametersForMode()
		print m,sumUp(allMethods[m].evaluateZeroModeParametersForMode(params[m])).real/ndfs[m]
	diffs = cu.getmBinResolvedDiffs(allMethods)
	comps = cu.getCompositions(diffs)
#	with  modernplotting.toolkit.PdfWriter("compositions_1pp_data"+str(tBin)+studyAdder+plotDataType) as pdfOutput:
#		plot = style.getPlot1D()
#		for m in comps:
#			line  = [0.]*len(comps[m][0])
#			xAxis = [ .5 + 0.04*(startBin + i) for i in range(len(comps[m][0]))]
#			break
#		count = 0
#		for m in comps:
#			print m
#
#			newLine = line[:]
#			for i in range(len(comps[m][0])):
#				newLine[i] += comps[m][0][i]
#			plot.axes.fill_between(xAxis, line, newLine, facecolor = modernplotting.colors.makeColorLighter(modernplotting.colors.colorScheme.blue, 0.1*count))
#			count += 1
#			line = newLine
#		plot.setYlim(0.,1.)
#		plot.setXlim(xAxis[0], xAxis[-1])
#		pdfOutput.savefigAndClose()
	studyList = []
	for m in allMethods:
		studyList.append(m)
	studyList.sort()

	selfEvals = {}
	for m in allMethods:
		selfEvals[m] = sumUp(allMethods[m].evaluateResolvedZeroModeParametersForMode(params[m])).real

	hist = ROOT.TH2D("hist","hist", len(params)+2, 0, len(params)+2, len(params), 0, len(params))

	cumulWeights = {}
	resolvedWeightedSum = [[]] # Assumes one t' bin
	for i in range(stopBin - startBin):
		dim = len(params[m][0][i])
		prrs = [0.] * dim
		for m in params:
			weight = comps[m][0][i]
			if not m in cumulWeights:
				cumulWeights[m] = 0.
			cumulWeights[m] += weight
			for j in range(dim):
#				print dim,i,j,params[m][0]
#				print prrs
				prrs[j] += weight * params[m][0][i][j]
		resolvedWeightedSum[0].append(prrs)

#	b    = 40
#	sect = "1++0+[pi,pi]1--PiS"
#	s    = 1
#	allMethods['fixedShapes'].removeAllCorrelations()
#	allMethods['fixedShapes'].calculateNonShapeParametersForZeroModeParameters(resolvedWeightedSum)
#	rv = allMethods['fixedShapes'].produceResultViewer(resolvedWeightedSum,s, noRun = True, plotTheory = True, removeZM = False)
#	rv.writeBinToPdf(b, stdCmd = ["", sect + "_data_intens_"+str(b)+"_"+str(tBin)+".pdf", [], sect + "_data_argand_"+str(b)+"_"+str(tBin)+".pdf", []])
#	rv.wiriteReImToPdf(b, sect + "_data_<ri>_"+str(b)+"_"+str(tBin)+".pdf" )
#	return

	evals = {}
	for i,m in enumerate(studyList):
#		print "-------------------------------"
		for j,n in enumerate(studyList):
			evl = sumUp(allMethods[n].evaluateResolvedZeroModeParametersForMode(params[m])).real
			evals[n,m] = evl
			diff = (evl-selfEvals[n])/selfEvals[n]

#			allMethods["fixedShapes"].removeZeroModeFromComa()
#			print "------------------------------------IN---------------------------------"
#			print params[m], params[n]
#			diff = sumUp(allMethods["fixedShapes"].compareTwoZeroModeCorrections(params[m], params[n]))
#			print diff
#			print "------------------------------------OUT---------------------------------"
#			print m,'in',n,":",diff
			hist.SetBinContent(i+1, j+1, diff)
#	return 
	weightedSum = weightedParametersSum(evals, selfEvals, params)
	for i,m in enumerate(studyList):
		evl = sumUp(allMethods[m].evaluateZeroModeParametersForMode(cloneZeros(weightedSum))).real
		diff = (evl - selfEvals[m])/selfEvals[m]
		evl2 = sumUp(allMethods[m].evaluateZeroModeParametersForMode(resolvedWeightedSum)).real
		diff2 = (evl2 - selfEvals[m])/selfEvals[m]

		print m,diff,";:;:;;>>>??"
		hist.SetBinContent(len(studyList)+1, i+1, diff)
		hist.SetBinContent(len(studyList)+2, i+1, diff2)



	axolotl = []
	for i,study in enumerate(studyList):
		axolotl.append(shortlabels[study])
#		axolotl.append(alphabet[i])

	style.titleRight = r"$1^{++}0^+$"
	style.titleLeft  = LaTeX_strings.tBins[tBin]


#	with modernplotting.toolkit.PdfWriter("studies_1pp_data"+str(tBin)+studyAdder+plotDataType) as pdfOutput:
#		plot = style.getPlot2D()
#		plot.axes.get_xaxis().set_ticks([(i + 0.5) for i in range(len(studyList)+2)])
#		plot.axes.get_yaxis().set_ticks([(i + 0.5) for i in range(len(studyList))])
#		studyPlotter.makeValuePlot(plot, hist)
#
#		plot.axes.set_yticklabels(axolotl)
#		axolotl.append(unCorrected_string)
#		axolotl.append(weightedAVG_string)
#		plot.axes.set_xticklabels(axolotl, rotation = 90)
#		plot.setZlim((0.,1.))
#
#		pdfOutput.savefigAndClose()

#	return

#	with open("studies_1pp_data"+str(tBin)+studyAdder+".txt",'w') as outFile:
#		for axl in axolotl:
#			outFile.write(axl + ' ')
#		outFile.write("\n")
#		for i in range(hist.GetNbinsX()):
#			for j in range(hist.GetNbinsY()):
#				outFile.write(str(hist.GetBinContent(i+1, j+1)) + ' ')
#			outFile.write('\n')

	doF0fitGlobal  = False
	doF0Fits       = False
	doFits1500     = False
	doOmnesFit     = False
	doRhoFits      = False
	doRhoPrimeFits = False

	if doF0fitGlobal:
		deg = 1
#		f0fit = doF0Fit(inFileName, sectors[:1], startBin, stopBin, tBins, sectorRangeMap = {"1++0+[pi,pi]0++PiP":(0.9,1.1)}, referenceWave = referenceWave, deg = deg)
		f0fit = doF0Fit(inFileName, sectors[:1], startBin, stopBin, tBins, referenceWave = referenceWave, deg = deg)
		startPars = [mF0,g1,g2]
		for _ in range(deg):
			startPars.append(0.)
			startPars.append(0.)
		x,err = f0fit.fitShapeParametersForBinRange(startPars,[0],range(stopBin-startBin), zeroModeParameters = resolvedWeightedSum)
#		x,err = f0fit.fitShapeParametersForBinRange([mF0],[0],range(stopBin-startBin), zeroModeParameters = resolvedWeightedSum)
		print x
		f0fit.setShapeParameters(x,err,resolvedWeightedSum)
		s = 0 # only one sector??
		rv = f0fit.produceResultViewer(resolvedWeightedSum,s, noRun = True, plotTheory = True)
		for b in range(startBin, stopBin):
			intensName = "./f0fits/1pp_intens_"+str(b)+"_"+str(tBin)+plotDataType
			argandName = "./f0fits/1pp_argand_"+str(b)+"_"+str(tBin)+plotDataType
			rv.writeBinToPdf(b, stdCmd = ["", intensName, [],  argandName, []])
		return

	if doF0Fits:
		f0fit = doF0Fit(inFileName, sectors[:1], startBin, stopBin, tBins, sectorRangeMap = {"1++0+[pi,pi]0++PiP":(0.9,1.1)}, referenceWave = referenceWave, writeResultToFile = "f0MassesAndWidths_1++0+0++_global.dat")
		with open("./f0MassesAndWidths_1pp_"+str(tBin)+".dat",'w') as outFile:
			for i in range(stopBin-startBin):
				binIndex = i+startBin
				outFile.write(str(binIndex)+' '+str(0.52 + 0.04*binIndex)+' ')
				startValueOffset = 0.00
				exceptCount      = 0
				while True:
					try:
						startPars = [mF0+startValueOffset,g1+startValueOffset,g2+startValueOffset]
#						for _ in range(deg):
#							startPars.append(startValueOffset)
#							startPars.append(startValueOffset)
						x,err,c2,ndf = f0fit.fitShapeParametersForBinRange(startPars, [0],[i], zeroModeParameters = resolvedWeightedSum)
						break
					except:
						print "Fitter exception encountered"
						startValueOffset += 0.001
						exceptCount      += 1	
						if exceptCount > 3:
							raise Exception("Too many failed attempts: "+str(exceptCount))
				outFile.write(str(x[0]) + ' ' + str(err[0]) + ' ' + str(x[1]) + ' ' + str(err[1])+ ' ' + str(x[2]) + ' ' + str(err[2]))
#				for i in range(deg):
#					outFile.write( ' ' + str(x[3+i]) + ' ' + str(err[3+i]) + ' ' + str(x[4+i]) + ' ' +str(err[4+i]))
				outFile.write(' ' +str(c2/ndf)+'\n')
		return

	if doFits1500:
		with open("./1pp_f0_1500massesAndWidths_"+str(tBin)+".dat",'w') as outFile:
			for i in range(stopBin-startBin):
				binIndex = i + startBin
				outFile.write(str(binIndex)+' '+str(0.52 + 0.04*binIndex)+' ')
				startValueOffset = 0.00
				exceptCount      = 0
				try:
#				if True:
					startPars = [m1500+startValueOffset,G1500+startValueOffset]
#					for _ in range(deg):
#						startPars.append(startValueOffset)
#						startPars.append(startValueOffset)
					x,err,c2,ndf = fit1500.fitShapeParametersForBinRange(startPars, [0],[i], zeroModeParameters = resolvedWeightedSum)
				except:
					print "Fitter exception encountered"
					startValueOffset += 0.001
					exceptCount      += 1
					if exceptCount > 3:
						raise Exception("Too many failed attempts: "+str(exceptCount))

				outFile.write(str(x[0]) + ' ' + str(err[0]) + ' ' + str(x[1]) + ' ' + str(err[1]))
#				for i in range(deg):
#					outFile.write( ' ' + str(x[3+i]) + ' ' + str(err[3+i]) + ' ' + str(x[4+i]) + ' ' +str(err[4+i]))
				outFile.write(' ' +str(c2/ndf)+'\n')
		return

	if doOmnesFit:
		deg = 1
		omnes = doOmnes(inFileName, sectors[1:], startBin, stopBin, tBins, referenceWave = referenceWave, deg = deg, sectorRangeMap = {"1++0+[pi,pi]1--PiS":(0.,1.3)})
		startPars = [0.]*deg
		if len(startPars) > 0:
			x,err = omnes.fitShapeParametersForBinRange(startPars,[0],range(stopBin-startBin), zeroModeParameters = resolvedWeightedSum)
#			x,err = f0fit.fitShapeParametersForBinRange([mF0],[0],range(stopBin-startBin), zeroModeParameters = resolvedWeightedSum)
		else:
			x,err = [],[]
		print x
		omnes.setShapeParameters(x,err,resolvedWeightedSum)
		s = 0 # only one sector??
		rv = omnes.produceResultViewer(resolvedWeightedSum,s, noRun = True, plotTheory = True)
		rv.plotData = False
		for b in range(startBin, stopBin):
			intensName = "./omnesFits/1pp_intens_"+str(b)+"_"+str(tBin)+plotDataType
			argandName = "./omnesFits/1pp_argand_"+str(b)+"_"+str(tBin)+plotDataType
			rv.writeBinToPdf(b, stdCmd = ["", intensName, [],  argandName, []])
		return

	if doRhoPrimeFits and not doRhoFits:
		raise RuntimeError("rho' fits only after rho fits possible")
	if doRhoPrimeFits:
		rhoPrimeFileName = "1pp_rhoPrimeMassesAndWidths_"+str(tBin)+".dat"
		try:
			os.remove(rhoPrimeFileName)
		except:
			pass

	if doRhoFits:
		with open("rhoMassesAndWidths_1pp_"+str(tBin)+rhoRangeString+".dat",'w') as outFile:
			for i in range(stopBin-startBin):
				binIndex = i+startBin
				outFile.write(str(binIndex)+' '+str(0.52 + 0.04*binIndex)+' ')
				startValueOffset = 0.01
				exceptCount      = 0
				while True:
#					try:
					if True:
						x,err,c2,ndf = fitRho.fitShapeParametersForBinRange([mRho+startValueOffset,Grho+startValueOffset], [0],[i], zeroModeParameters = resolvedWeightedSum)
						break
#					except:
#						print "Fitter exception encountered"
#						startValueOffset += 0.001
#						exceptCount      += 1
#						if exceptCount > 3:
#							print "Too many failed attempts in bin "+str(i)+": "+str(exceptCount)
##							raise Exception
#							x, err = [0.,0.],[0.,0.]
#							break
				outFile.write(str(x[0]) + ' ' + str(err[0]) + ' ' + str(x[1]) + ' ' + str(err[1]))
				outFile.write(' ' + str(c2/ndf) + '\n')

				fitRho.calculateNonShapeParametersForZeroModeParameters(resolvedWeightedSum)
				rhoRV = fitRho.produceResultViewer(resolvedWeightedSum,"1++0+[pi,pi]1--PiS", noRun = True, plotTheory = True)
				rhoRV.plotData = True
				plotNameBase = "./rhoFitPlots/1pp0p1mmPiS_<mode>_"+str(binIndex)+"_"+str(tBin)+".pdf"
				rhoRV.writeBinToPdf(binIndex, stdCmd = ["", plotNameBase.replace("<mode>","intens"), [],  plotNameBase.replace("<mode>","argand"), []])

				if doRhoPrimeFits:
					fitRhoPrime(i,rhoPrimeFileName, inFileName, startBin, stopBin, tBins, [x[0], x[1]], resolvedWeightedSum, referenceWave = referenceWave,
					plotNameBase = "./rhoPrimeFitPlots/"+str(binIndex)+"_"+str(tBin)+"_<mode>"+plotDataType)
#					)
		return

##### Writing starts here

	fileNames = {}

	for stu in allMethods:
		print "Writing for '" + stu + "'"
		for s, sect in enumerate(allMethods[stu].sectors):
			if stu == "pipiS":
				rv = allMethods[stu].produceResultViewer(allMethods[stu].getZeroModeParametersForMode(),s, plotTheory = True)
				rv.run()
			rv = allMethods[stu].produceResultViewer(allMethods[stu].getZeroModeParametersForMode(),s, noRun = True)
			for bin in range(startBin, stopBin):
				fileName = "./collectedMethods/"+stu+"_"+sect+"_1ppData_"+str(bin)+studyAdder
				if not (sect,bin) in fileNames:
					fileNames[sect,bin] = []
				fileNames[sect,bin].append(fileName)
				rv.writeAmplFiles(bin, fileName = fileName)

	totalHists = fixedShapes.getTotalHists(resolvedWeightedSum)
	with root_open("./totals_1pp"+studyAdder+".root", "UPDATE") as outFileRoot:
		for t in totalHists:
			for m in t:
				m.Write()
#	return

	folder = "./comparisonResultsData"+studyAdder+"/"

	for s, sect in enumerate(allMethods['fixedShapes'].sectors):
		allMethods['fixedShapes'].removeZeroModeFromComa()
		allMethods['fixedShapes'].removeGlobalPhaseFromComa()
		rv = allMethods['fixedShapes'].produceResultViewer(resolvedWeightedSum,s, noRun = True, plotTheory = True)
		rv.writeBinToPdf(startBin, stdCmd = [folder + sect + "_data_2D_"+str(tBin)+plotDataType, "", [], "", []])
		rv.plotData = True

		continue

		for b in range(startBin, stopBin):
			intensNames = [name+".intens" for name in fileNames[sect,b]]
			argandNames = [name+".argand" for name in fileNames[sect,b]]
#			intensNames = []
#			argandNames = []


			rv.writeAmplFiles(b,0,"./filesForMisha/"+sect+"_m"+str(b)+"_t"+str(tBin)+"_corrected")
			rv.writeAmplFiles(b,1,"./filesForMisha/"+sect+"_m"+str(b)+"_t"+str(tBin)+"_uncorrect")
			continue

			rv.writeBinToPdf(b, stdCmd = ["", folder + sect + "_data_intens_"+str(b)+"_"+str(tBin)+plotDataType, intensNames,  folder + sect + "_data_argand_"+str(b)+"_"+str(tBin)+plotDataType, argandNames])
	print studyList
	print cumulWeights
Exemplo n.º 7
0
def main():
    checkLaTeX()
    style = modernplotting.mpplot.PlotterStyle()
    #	style.p2dColorMap = 'ocean_r'
    #	style.p2dColorMap = 'YlOrRd'
    style.p2dColorMap = 'Reds'

    #	inFileName   = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_MC.root"
    inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_bigger2pp.root"
    zeroFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/zeroModes_bigger2pp.root"

    sectors = ["2++1+[pi,pi]1--PiD", "2++1+[pi,pi]2++PiP"]
    tBin = int(sys.argv[1])
    if tBin < 0 or tBin > 3:
        raise ValueError("Invalid t' bin: " + str(tBin))

    tBins = [tBin]

    startBin = 11
    stopBin = 50

    methodBinRanges = {
        "fitF2": (22, 50),
        "fitBothF2": (22, 50),
        "fitRhoF": (22, 50),
        "fixedShapeF2": (22, 50)
    }
    #	methodBinRanges = {} # Override here

    allMethods = {}
    methodStrings = {}
    shortlabels = {
        "fixedShapeF0": r"$\text{fix}_{f_0}^{~}$",
        "fixedShapeRhoP": r"$\text{fix}_\rho^{P}$",
        "fixedShapeRhoF": r"$\text{fix}_\rho^{F}$",
        "fixedShapeBothRho": r"$\text{fix}_\rho^{2}$",
        "fixedShapeF2": r"$\text{fix}_{f_2}$",
        "fixedShapes": r"$\text{fix}_\text{all}^{~}$",
        "pipiS": r"$\phi_{[\pi\pi]_S}^{~}$",
        "fitRho": r"$\text{fit}_\rho$",
        "fitRhoP": r"$\text{fit}_\rho^{P}$",
        "fitRhoF": r"$\text{fit}_\rho^{F}$",
        "fitBothRho": r"$\text{fit}_\rho^{2}$",
        "fitBothF2": r"$\text{fit}_{f_2}^{2}$",
        "fitF2": r"$\text{fit}_{f_2}$",
        "smooth": r"smooth"
    }

    print "Starting with fixed shapes"
    fixedShapes = doFixedShapes(inFileName,
                                zeroFileName,
                                sectors,
                                startBin,
                                stopBin,
                                tBins,
                                referenceWave=referenceWave)
    allMethods["fixedShapes"] = fixedShapes
    print "Finished with fixed shapes"
    fullSig = fixedShapes.getZeroModeSignature()

    totalHists = fixedShapes.getTotalHists(
        cloneZeros(fixedShapes.getZeroModeParametersForMode()))
    with root_open("./totals_bigger2pp_noCorr.root", "UPDATE") as outFileRoot:
        for t in totalHists:
            for m in t:
                m.Write()
    return

    print "Starting with fitting rho"
    fitRho = doFitRho(inFileName,
                      zeroFileName,
                      sectors,
                      startBin,
                      stopBin,
                      tBins,
                      referenceWave=referenceWave)
    allMethods["fitRho"] = fitRho
    print "Finished with fitting rho"

    print "Starting with fitting f2"
    fitF2 = doFitF2(
        inFileName,
        zeroFileName,
        sectors,
        startBin,
        stopBin,
        tBins,
        referenceWave=referenceWave,
        writeResultToFile="rhoMassesAndWidths_bigger2++1+1++_global.dat")
    allMethods["fitF2"] = fitF2
    print "Finished with fitting f2"

    if stopBin - startBin > 1:
        print "Starting with smooth"
        smooth = doSmooth(inFileName,
                          zeroFileName,
                          sectors,
                          startBin,
                          stopBin,
                          tBins,
                          referenceWave=referenceWave)
        allMethods["smooth"] = smooth
        print "Finished with smooth"

    if "fixedShapeF0" in allMethods:
        allMethods["fixedShapeF0"].setZeroModeSignature(fullSig, 1)

    diffsFull, resolvedWA, nonResolvedWA, comps, resDiffs, nonResDiffs, resolvedDiffsFull, noCorrDiffs = cu.doAllComparisons(
        allMethods, startBin, methodBinRanges)
    #	print resolvedDiffsFull
    from math import isnan
    for pair in resolvedDiffsFull:
        with modernplotting.toolkit.PdfWriter(
                './resolvedDiffPlots/bigger2pp_' + pair[0] + "_" + pair[1] +
                "_" + str(tBin) + ".pdf") as pdfOutput:
            plot = style.getPlot1D()
            line = [0.000000001] * len(resolvedDiffsFull[pair][0])
            line2 = [0.000000001] * len(resolvedDiffsFull[pair][0])
            one = [1.] * len(resolvedDiffsFull[pair][0])
            xAxis = [
                .5 + 0.04 * (startBin + i)
                for i in range(len(resolvedDiffsFull[pair][0]))
            ]
            for i, v in enumerate(resolvedDiffsFull[pair][0]):
                if not isnan(v) and not v <= 0.:
                    line[i] = v
                else:
                    line[i] = 0.000000001

            if not pair[1] == "WAres" and not pair[1] == "WAnon":
                for i, v in enumerate(resolvedDiffsFull[pair[1], pair[0]][0]):
                    if not isnan(v) and not v <= 0.:
                        line2[i] = v
                    else:
                        line2[i] = 0.000000001

            plot.setYlog()
            plot.plot(xAxis, line)
            plot.plot(xAxis, one)
            plot.plot(xAxis, line2)
            plot.setYlim(0.00001, 10000)
            pdfOutput.savefigAndClose()

    studyList = []
    for m in allMethods:
        studyList.append(m)
    studyList.sort()

    style.titleRight = r"$2^{++}1^+$"
    style.titleLeft = LaTeX_strings.tBins[tBin]

    with modernplotting.toolkit.PdfWriter("compositions_bigger2pp_" +
                                          str(tBin) + ".pdf") as pdfOutput:
        plot = style.getPlot1D()
        for m in studyList:
            line = [0.] * len(comps[m][0])
            xAxis = [
                .5 + 0.04 * (startBin + i) for i in range(len(comps[m][0]))
            ]
            break
        count = 0
        for m in studyList:
            newLine = line[:]
            for i in range(len(comps[m][0])):
                newLine[i] += comps[m][0][i]
            plot.axes.fill_between(
                xAxis,
                line,
                newLine,
                facecolor=modernplotting.colors.makeColorLighter(
                    modernplotting.colors.colorScheme.blue, 0.1 * count))
            count += 1
            line = newLine
        plot.setYlim(0., 1.)
        plot.setXlim(xAxis[0], xAxis[-1])
        pdfOutput.savefigAndClose()

    hist = pyRootPwa.ROOT.TH2D("hist", "hist",
                               len(studyList) + 2, 0,
                               len(studyList) + 2, len(studyList), 0,
                               len(studyList))

    for i, m in enumerate(studyList):
        for j, n in enumerate(studyList):
            hist.SetBinContent(i + 1, j + 1, diffsFull[n, m])
    for i, m in enumerate(studyList):
        hist.SetBinContent(len(studyList) + 1, i + 1, noCorrDiffs[m])
        hist.SetBinContent(len(studyList) + 2, i + 1, resDiffs[m])

    axolotl = []
    for i, study in enumerate(studyList):
        axolotl.append(shortlabels[study])
#		axolotl.append(alphabet[i])

    with modernplotting.toolkit.PdfWriter("studies_bigger2pp_" + str(tBin) +
                                          ".pdf") as pdfOutput:
        plot = style.getPlot2D()
        plot.axes.get_xaxis().set_ticks([(i + 0.5)
                                         for i in range(len(studyList) + 2)])
        plot.axes.get_yaxis().set_ticks([(i + 0.5)
                                         for i in range(len(studyList))])
        studyPlotter.makeValuePlot(plot, hist)

        plot.axes.set_yticklabels(axolotl)

        axolotl.append(unCorrected_string)
        axolotl.append(weightedAVG_string)
        plot.axes.set_xticklabels(axolotl, rotation=90)
        plot.setZlim((0., 1.))

        pdfOutput.savefigAndClose()

    with open("studies_bigger2pp_" + str(tBin) + ".txt", 'w') as out:
        for axl in axolotl:
            out.write(axl + ' ')
        out.write("\n")
        for i in range(hist.GetNbinsX()):
            for j in range(hist.GetNbinsY()):
                out.write(str(hist.GetBinContent(i + 1, j + 1)) + ' ')
            out.write('\n')
    doF2Fits = False
    if doF2Fits:
        with open("f2MassesAndWidths_bigger2pp_" + str(tBin) + ".dat",
                  'w') as outFile:
            for i in range(stopBin - startBin):
                binIndex = i + startBin
                outFile.write(
                    str(binIndex) + ' ' + str(0.52 + 0.04 * binIndex) + ' ')
                startValueOffset = 0.01
                exceptCount = 0
                while True:
                    try:
                        #					if True:
                        x, err, c2, ndf = fitF2.fitShapeParametersForBinRange(
                            [mF2 + startValueOffset, GF2 + startValueOffset],
                            [0], [i],
                            zeroModeParameters=resolvedWA)
                        break
                    except:
                        print "Fitter exception encountered"
                        startValueOffset += 0.001
                        exceptCount += 1
                        if exceptCount > 3:
                            print "Too many failed attempts in bin " + str(
                                i) + ": " + str(exceptCount)
                            #							raise Exception
                            x, err = [0., 0.], [0., 0.]
                            break

                outFile.write(
                    str(x[0]) + ' ' + str(err[0]) + ' ' + str(x[1]) + ' ' +
                    str(err[1]))
                outFile.write(' ' + str(c2 / ndf) + '\n')
        return
##### Writing starts here

    fileNames = {}

    for stu in allMethods:
        print "Writing for '" + stu + "'"
        for s, sect in enumerate(allMethods[stu].sectors):
            if stu == "pipiS":
                rv = allMethods[stu].produceResultViewer(
                    allMethods[stu].getZeroModeParametersForMode(),
                    s,
                    plotTheory=True)
                rv.run()
            rv = allMethods[stu].produceResultViewer(
                allMethods[stu].getZeroModeParametersForMode(), s, noRun=True)
            for bin in range(startBin, stopBin):
                fileName = "./collectedMethods/" + stu + "_" + sect + "_bigger2pp_" + str(
                    bin)
                if not (sect, bin) in fileNames:
                    fileNames[sect, bin] = []
                fileNames[sect, bin].append(fileName)
                rv.writeAmplFiles(bin, fileName=fileName)

    totalHists = fixedShapes.getTotalHists(resolvedWA)
    with root_open("./totals_bigger2pp.root", "UPDATE") as out:
        for t in totalHists:
            for m in t:
                m.Write()


#	return

    plotFolder = "./comparisonResultsBigger2pp/"

    for s, sect in enumerate(allMethods['fixedShapes'].sectors):
        allMethods['fixedShapes'].removeZeroModeFromComa()
        allMethods['fixedShapes'].removeGlobalPhaseFromComa()
        rv = allMethods['fixedShapes'].produceResultViewer(resolvedWA,
                                                           s,
                                                           noRun=True,
                                                           plotTheory=True)
        rv.writeBinToPdf(startBin,
                         stdCmd=[
                             plotFolder + sect + "_data_2D_" + str(tBin) +
                             ".pdf", "", [], "", []
                         ])
        for b in range(startBin, stopBin):
            intensNames = [name + ".intens" for name in fileNames[sect, b]]
            argandNames = [name + ".argand" for name in fileNames[sect, b]]
            rv.writeBinToPdf(b,
                             stdCmd=[
                                 "", plotFolder + sect + "_data_intens_" +
                                 str(b) + "_" + str(tBin) + ".pdf",
                                 intensNames,
                                 plotFolder + sect + "_data_argand_" + str(b) +
                                 "_" + str(tBin) + ".pdf", argandNames
                             ])
    print studyList
def main():
    checkLaTeX()
    style = modernplotting.mpplot.PlotterStyle()
    #	style.p2dColorMap = 'ocean_r'
    #	style.p2dColorMap = 'YlOrRd'
    style.p2dColorMap = 'Reds'

    sectors = ["0-+0+[pi,pi]0++PiS", "0-+0+[pi,pi]1--PiP"]
    #	rhoRange         = 1.2
    rhoRange = None
    if not rhoRange:
        sectorRangeMap = {}
        rhoRangeString = ""
    else:
        sectorRangeMap = {"0-+0+[pi,pi]1--PiP": (0., rhoRange)}
        rhoRangeString = "_range" + str(rhoRange)

    tBin = int(sys.argv[1])
    if tBin < 0 or tBin > 3:
        raise ValueError("Invalid t' bin: " + str(tBin))
    if len(sys.argv) > 2:
        study = sys.argv[2]
        studyAdder = "_" + study
    else:
        study = "std11"
        studyAdder = ""
    print "Study: " + study

    referenceWave = ""

    inFileName = fileNameMap[study]
    tBins = [tBin]

    startBin = 11
    stopBin = 50

    #	startBin         = 32
    #	stopBin          = 33

    allMethods = {}
    methodStrings = {}
    shortlabels = {
        "fixedShapeF0": r"$\text{fix}_{f_0}^{~}$",
        "fixedShapeRho": r"$\text{fix}_\rho^{~}$",
        "fixedShapeRho1G": r"$\text{fix}_\rho^{1\Gamma}$",
        "fixedShapeRho2G": r"$\text{fix}_\rho^{2\Gamma}$",
        "fixedShapes": r"$\text{fix}_\text{all}^{~}$",
        "pipiS": r"$\phi_{[\pi\pi]_S}^{~}$",
        "fitRho": r"$\text{fit}_\rho^{~}$",
        "fitRho1G": r"$\text{fit}_\rho^{1\Gamma}$",
        "fitRho2G": r"$\text{fit}_\rho^{2\Gamma}$",
        "smooth": r"smooth"
    }

    fit1500 = doFit1500(
        inFileName,
        sectors[:1],
        startBin,
        stopBin,
        tBins,
        referenceWave=referenceWave,
        writeResultToFile="0mp_f0_1500_massesAndWidths_global.dat")

    print "Start with fixed shape f0"
    fixedShapeF0 = doFixedShapes(inFileName,
                                 sectors[:1],
                                 startBin,
                                 stopBin,
                                 tBins,
                                 referenceWave=referenceWave)
    #	allMethods["fixedShapeF0"] = fixedShapeF0
    print "Finished with fixed shape f0"

    #	print "Start with fixed shape rho"
    #	fixedShapeRho = doFixedShapes(inFileName, sectors[1:], startBin, stopBin, tBins, referenceWave = referenceWave)
    #	allMethods["fixedShapeRho"] = fixedShapeRho
    #	print "Finished with fixed shape rho"

    #	print "Start with restricted rho (1 Gamma)"
    #	fixedShapeRho1G = doFixedShapes(inFileName, sectors[1:], startBin, stopBin, tBins, sectorRangeMap = {"0-+0+[pi,pi]1--PiP":(mRho - Grho, mRho+Grho)}, referenceWave = referenceWave)
    #	allMethods["fixedShapeRho1G"] = fixedShapeRho1G
    #	print "Finished with restricted rho (1 Gamma)"

    #	print "Start with restricted rho (2 Gammas)"
    #	fixedShapeRho2G = doFixedShapes(inFileName, sectors[1:], startBin, stopBin, tBins, sectorRangeMap = {"0-+0+[pi,pi]1--PiP":(mRho -2*Grho, mRho+2*Grho)}, referenceWave = referenceWave)
    #	allMethods["fixedShapeRho2G"] = fixedShapeRho2G
    #	print "Finished with restricted rho (2 Gammas)"

    print "Start with fixed shapes"
    fixedShapes = doFixedShapes(inFileName,
                                sectors,
                                startBin,
                                stopBin,
                                tBins,
                                referenceWave=referenceWave)
    allMethods["fixedShapes"] = fixedShapes
    print "Finished with fixed shapes"

    #	print "Start with phase"
    #	fitPiPiSshape = doF0phase(inFileName, sectors[:1], startBin, stopBin, tBins, referenceWave = referenceWave)
    #	allMethods["pipiS"] = fitPiPiSshape
    #	print "Finished with phase"

    print "Start with fitting rho"
    fitRho = doFitRho(
        inFileName,
        sectors,
        startBin,
        stopBin,
        tBins,
        sectorRangeMap=sectorRangeMap,
        referenceWave=referenceWave,
        writeResultToFile="rhoMassesAndWidths_0-+0+1--_global.dat")
    #	allMethods["fitRho"] = fitRho
    print "Finished with fitting rho"

    #	print "Start with fitting restricted rho (1 Gamma)"
    #	fitRho1G = doFitRho(inFileName, sectors, startBin, stopBin, tBins, sectorRangeMap = {"0-+0+[pi,pi]1--PiP":(mRho - Grho, mRho+Grho)}, referenceWave = referenceWave)
    #	allMethods["fitRho1G"] = fitRho1G
    #	print "Finished with fitting restricted rho (1 Gamma)"

    #	print "Start with fitting restricted rho (2 Gammas)"
    #	fitRho2G = doFitRho(inFileName, sectors, startBin, stopBin, tBins, sectorRangeMap = {"0-+0+[pi,pi]1--PiP":(mRho -2*Grho, mRho+2*Grho)}, referenceWave = referenceWave)
    #	allMethods["fitRho2G"] = fitRho2G
    #	print "Finished with fitting restricted rho (2 Gammas)"

    if stopBin - startBin > 1:
        print "Start with smooth"
        smooth = doSmooth(inFileName,
                          sectors,
                          startBin,
                          stopBin,
                          tBins,
                          referenceWave=referenceWave)
        allMethods["smooth"] = smooth
        print "Finished with smooth"

    ndfs = {}
    params = {}
    for m in allMethods:
        ndfs[m] = allMethods[m].getNDFforMode()
        params[m] = allMethods[m].getZeroModeParametersForMode()
        print m, sumUp(allMethods[m].evaluateZeroModeParametersForMode(
            params[m])).real / ndfs[m]
    diffs = cu.getmBinResolvedDiffs(allMethods)
    comps = cu.getCompositions(diffs)
    #	with  modernplotting.toolkit.PdfWriter("compositions_0mp_data"+str(tBin)+studyAdder+".pdf") as pdfOutput:
    #		plot = style.getPlot1D()
    #		for m in comps:
    #			line  = [0.]*len(comps[m][0])
    #			xAxis = [ .5 + 0.04*(startBin + i) for i in range(len(comps[m][0]))]
    #			break
    #		count = 0
    #		for m in comps:
    #			print m
    #
    #			newLine = line[:]
    #			for i in range(len(comps[m][0])):
    #				newLine[i] += comps[m][0][i]
    #			plot.axes.fill_between(xAxis, line, newLine, facecolor = modernplotting.colors.makeColorLighter(modernplotting.colors.colorScheme.blue, 0.1*count))
    #			count += 1
    #			line = newLine
    #		plot.setYlim(0.,1.)
    #		plot.setXlim(xAxis[0], xAxis[-1])
    #		pdfOutput.savefigAndClose()
    studyList = []
    for m in allMethods:
        studyList.append(m)
    studyList.sort()

    selfEvals = {}
    for m in allMethods:
        selfEvals[m] = sumUp(
            allMethods[m].evaluateResolvedZeroModeParametersForMode(
                params[m])).real

    hist = pyRootPwa.ROOT.TH2D("hist", "hist",
                               len(params) + 2, 0,
                               len(params) + 2, len(params), 0, len(params))

    cumulWeights = {}
    #	resolvedWeightedSum = [[]] # Assumes one t' bin
    #	for i in range(stopBin - startBin):
    #		dim = len(params[m][0][i])
    #		prrs = [0.] * dim
    #		for m in params:
    #			weight = comps[m][0][i]
    #			if not m in cumulWeights:
    #				cumulWeights[m] = 0.
    #			cumulWeights[m] += weight
    #			for j in range(dim):
    ##				print dim,i,j,params[m][0]
    ##				print prrs
    #				if weight < 0.:
    #					raise ValueError("Smaller than zero weight encountered...")
    #				prrs[j] += weight * params[m][0][i][j]
    #		resolvedWeightedSum[0].append(prrs)
    #
    #	evals = {}
    #	for i,m in enumerate(studyList):
    ##		print "-------------------------------"
    #		for j,n in enumerate(studyList):
    #			evl = sumUp(allMethods[n].evaluateResolvedZeroModeParametersForMode(params[m])).real
    #			evals[n,m] = evl
    #			diff = (evl-selfEvals[n])/selfEvals[n]
    #
    ##			allMethods["fixedShapes"].removeZeroModeFromComa()
    ##			print "------------------------------------IN---------------------------------"
    ##			print params[m], params[n]
    ##			diff = sumUp(allMethods["fixedShapes"].compareTwoZeroModeCorrections(params[m], params[n]))
    ##			print diff
    ##			print "------------------------------------OUT---------------------------------"
    ##			print m,'in',n,":",diff
    #			hist.SetBinContent(i+1, j+1, diff)
    ##	return
    #	weightedSum = weightedParametersSum(evals, selfEvals, params)
    #	for i,m in enumerate(studyList):
    #		evl = sumUp(allMethods[m].evaluateZeroModeParametersForMode(cloneZeros(weightedSum))).real
    #		diff = (evl - selfEvals[m])/selfEvals[m]
    #		evl2 = sumUp(allMethods[m].evaluateZeroModeParametersForMode(resolvedWeightedSum)).real
    #		diff2 = (evl2 - selfEvals[m])/selfEvals[m]
    #
    #		print m,diff,";:;:;;>>>??"
    #		hist.SetBinContent(len(studyList)+1, i+1, diff)
    #		hist.SetBinContent(len(studyList)+2, i+1, diff2)
    #
    #
    #
    #	axolotl = []
    #	for i,study in enumerate(studyList):
    #		axolotl.append(shortlabels[study])
    #		axolotl.append(alphabet[i])

    style.titleRight = r"$0^{-+}0^+$"
    style.titleLeft = LaTeX_strings.tBins[tBin]

    #	with modernplotting.toolkit.PdfWriter("studies_0mp_data"+str(tBin)+studyAdder+".pdf") as pdfOutput:
    #		plot = style.getPlot2D()
    #		plot.axes.get_xaxis().set_ticks([(i + 0.5) for i in range(len(studyList)+2)])
    #		plot.axes.get_yaxis().set_ticks([(i + 0.5) for i in range(len(studyList))])
    #		studyPlotter.makeValuePlot(plot, hist)

    #		plot.axes.set_yticklabels(axolotl)
    #		axolotl.append(unCorrected_string)
    #		axolotl.append(weightedAVG_string)
    #		plot.axes.set_xticklabels(axolotl, rotation = 90)
    #		plot.setZlim((0.,1.))

    #		pdfOutput.savefigAndClose()

    #	with open("studies_0mp_data"+str(tBin)+studyAdder+".txt",'w') as out:
    #		for axl in axolotl:
    #			out.write(axl + ' ')
    #		out.write("\n")
    #		for i in range(hist.GetNbinsX()):
    #			for j in range(hist.GetNbinsY()):
    #				out.write(str(hist.GetBinContent(i+1, j+1)) + ' ')
    #			out.write('\n')

    ##### Writing starts here
    doF0fitGlobal = False
    doF0Fits = False
    doFits1500 = False
    doRhoFits = False
    if doF0fitGlobal:
        deg = 0
        #		f0fit = doF0Fit(inFileName, sectors[:1], startBin, stopBin, tBins, sectorRangeMap = {"0-+0+[pi,pi]0++PiS":(0.9,1.1)}, referenceWave = referenceWave, deg = deg)
        f0fit = doF0Fit(inFileName,
                        sectors[:1],
                        startBin,
                        stopBin,
                        tBins,
                        referenceWave=referenceWave,
                        deg=deg)
        startPars = [mF0, g1, g2]
        for _ in range(deg):
            startPars.append(0.)
            startPars.append(0.)
        x, err = f0fit.fitShapeParametersForBinRange(
            startPars, [0],
            range(stopBin - startBin),
            zeroModeParameters=resolvedWeightedSum)
        ######	x,err = f0fit.fitShapeParametersForBinRange([mF0],[0],range(stopBin-startBin), zeroModeParameters = resolvedWeightedSum)
        print x
        f0fit.setShapeParameters(x, err, resolvedWeightedSum)
        s = 0  # only one sector??
        rv = f0fit.produceResultViewer(resolvedWeightedSum,
                                       s,
                                       noRun=True,
                                       plotTheory=True)
        for b in range(startBin, stopBin):
            intensName = "./f0fits/0mp_intens_" + str(b) + "_" + str(
                tBin) + ".pdf"
            argandName = "./f0fits/0mp_argand_" + str(b) + "_" + str(
                tBin) + ".pdf"
            rv.writeBinToPdf(b, stdCmd=["", intensName, [], argandName, []])

    if doF0Fits:
        f0fit = doF0Fit(
            inFileName,
            sectors[:1],
            startBin,
            stopBin,
            tBins,
            sectorRangeMap={"0-+0+[pi,pi]0++PiS": (0.9, 1.1)},
            referenceWave=referenceWave,
            writeResultToFile="f0MassesAndWidths_0-+0+0++_global.dat")
        with open("./f0MassesAndWidths_0mp_" + str(tBin) + ".dat",
                  'w') as outFile:
            for i in range(stopBin - startBin):
                binIndex = i + startBin
                outFile.write(
                    str(binIndex) + ' ' + str(0.52 + 0.04 * binIndex) + ' ')
                startValueOffset = 0.00
                exceptCount = 0
                #				try:
                if True:
                    startPars = [
                        mF0 + startValueOffset, g1 + startValueOffset,
                        g2 + startValueOffset
                    ]
                    #					for _ in range(deg):
                    #						startPars.append(startValueOffset)
                    #						startPars.append(startValueOffset)
                    x, err, c2, ndf = f0fit.fitShapeParametersForBinRange(
                        startPars, [0], [i],
                        zeroModeParameters=resolvedWeightedSum)
#				except:
#					print "Fitter exception encountered"
#					startValueOffset += 0.001
#					exceptCount      += 1
#					if exceptCount > 3:
#						raise Exception("Too many failed attempts: "+str(exceptCount))

                f0fit.calculateNonShapeParametersForZeroModeParameters(
                    resolvedWeightedSum)
                RV980 = f0fit.produceResultViewer(resolvedWeightedSum,
                                                  "0-+0+[pi,pi]0++PiS",
                                                  noRun=True,
                                                  plotTheory=True)
                RV980.plotData = True
                plotNameBase = "./980FitPlots/0mp0p0ppPiS_<mode>_" + str(
                    binIndex) + "_" + str(tBin) + ".pdf"
                RV980.writeBinToPdf(
                    binIndex,
                    stdCmd=[
                        "",
                        plotNameBase.replace("<mode>", "intens"), [],
                        plotNameBase.replace("<mode>", "argand"), []
                    ])
                if binIndex == 32:
                    RV980.writeToRootFile("980.root")
                outFile.write(
                    str(x[0]) + ' ' + str(err[0]) + ' ' + str(x[1]) + ' ' +
                    str(err[1]) + ' ' + str(x[2]) + ' ' + str(err[2]))
                #				for i in range(deg):
                #					outFile.write( ' ' + str(x[3+i]) + ' ' + str(err[3+i]) + ' ' + str(x[4+i]) + ' ' +str(err[4+i]))
                outFile.write(' ' + str(c2 / ndf) + '\n')

    if doFits1500:
        with open("./0mp_f0_1500massesAndWidths_" + str(tBin) + ".dat",
                  'w') as outFile:
            for i in range(stopBin - startBin):
                binIndex = i + startBin
                outFile.write(
                    str(binIndex) + ' ' + str(0.52 + 0.04 * binIndex) + ' ')
                startValueOffset = 0.00
                exceptCount = 0
                if True:
                    startPars = [
                        m1500 + startValueOffset, G1500 + startValueOffset
                    ]
                    #					for _ in range(deg):
                    #						startPars.append(startValueOffset)
                    #						startPars.append(startValueOffset)
                    x, err, c2, ndf = fit1500.fitShapeParametersForBinRange(
                        startPars, [0], [i],
                        zeroModeParameters=resolvedWeightedSum)
#				except:
#					print "Fitter exception encountered"
#					startValueOffset += 0.001
#					exceptCount      += 1
#					if exceptCount > 3:
#						raise Exception("Too many failed attempts: "+str(exceptCount))

                fit1500.calculateNonShapeParametersForZeroModeParameters(
                    resolvedWeightedSum)
                RV1500 = fit1500.produceResultViewer(resolvedWeightedSum,
                                                     "0-+0+[pi,pi]0++PiS",
                                                     noRun=True,
                                                     plotTheory=True)
                RV1500.plotData = True
                plotNameBase = "./1500FitPlots/0mp0p0ppPiS_<mode>_" + str(
                    binIndex) + "_" + str(tBin) + ".pdf"
                RV1500.writeBinToPdf(
                    binIndex,
                    stdCmd=[
                        "",
                        plotNameBase.replace("<mode>", "intens"), [],
                        plotNameBase.replace("<mode>", "argand"), []
                    ])
                if binIndex == 32:
                    RV1500.writeToRootFile("1500.root")

                outFile.write(
                    str(x[0]) + ' ' + str(err[0]) + ' ' + str(x[1]) + ' ' +
                    str(err[1]))
                #				for i in range(deg):
                #					outFile.write( ' ' + str(x[3+i]) + ' ' + str(err[3+i]) + ' ' + str(x[4+i]) + ' ' +str(err[4+i]))
                if not ndf == 0:
                    outFile.write(' ' + str(c2 / ndf) + '\n')
                else:
                    outFile.write(' noNDF \n')

    if doRhoFits:
        cplFileName = "0mp_rho_cpls_" + str(tBin) + ".dat"
        try:
            os.remove(cplFileName)
        except:
            pass
        with open(
                "./rhoMassesAndWidths_0mp_" + str(tBin) + rhoRangeString +
                ".dat", 'w') as outFile:
            for i in range(stopBin - startBin):
                binIndex = i + startBin
                outFile.write(
                    str(binIndex) + ' ' + str(0.52 + 0.04 * binIndex) + ' ')
                startValueOffset = 0.00
                exceptCount = 0
                try:
                    x, err, c2, ndf = fitRho.fitShapeParametersForBinRange(
                        [mRho + startValueOffset, Grho + startValueOffset],
                        [0], [i],
                        zeroModeParameters=resolvedWeightedSum)
                except:
                    print "Fitter exception encountered"
                    startValueOffset += 0.001
                    exceptCount += 1
                    if exceptCount > 3:
                        raise Exception("Too many failed attempts: " +
                                        str(exceptCount))

                outFile.write(
                    str(x[0]) + ' ' + str(err[0]) + ' ' + str(x[1]) + ' ' +
                    str(err[1]))
                outFile.write(' ' + str(c2 / ndf) + '\n')

                fitRho.calculateNonShapeParametersForZeroModeParameters(
                    resolvedWeightedSum)
                rhoRV = fitRho.produceResultViewer(resolvedWeightedSum,
                                                   "0-+0+[pi,pi]1--PiP",
                                                   noRun=True,
                                                   plotTheory=True)
                rhoRV.plotData = True
                plotNameBase = "./rhoFitPlots/0mp0p1mmPiP_<mode>_" + str(
                    binIndex) + "_" + str(tBin) + ".pdf"
                rhoRV.writeBinToPdf(
                    binIndex,
                    stdCmd=[
                        "",
                        plotNameBase.replace("<mode>", "intens"), [],
                        plotNameBase.replace("<mode>", "argand"), []
                    ])

#				with open(cplFileName,'a') as outFileCpl:
#					fitRho.calculateNonShapeParameters()
#					cpl, hess = fitRho.getCouplingParameters()
#					outFileCpl.write(str(cpl[0][i]))
#					outFileCpl.write(", ")
#					outFileCpl.write(str(hess[0][i]))
#					outFileCpl.write("\n")

    if doF0fitGlobal or doF0Fits or doFits1500 or doRhoFits:
        return

    fileNames = {}

    for stu in allMethods:
        print "Writing for '" + stu + "'"
        for s, sect in enumerate(allMethods[stu].sectors):
            if stu == "pipiS":
                rv = allMethods[stu].produceResultViewer(
                    allMethods[stu].getZeroModeParametersForMode(),
                    s,
                    plotTheory=True)
                rv.run()
            rv = allMethods[stu].produceResultViewer(
                allMethods[stu].getZeroModeParametersForMode(), s, noRun=True)
            for bin in range(startBin, stopBin):
                fileName = "./collectedMethods/" + stu + "_" + sect + "_0mpData_" + str(
                    bin) + studyAdder
                if not (sect, bin) in fileNames:
                    fileNames[sect, bin] = []
                fileNames[sect, bin].append(fileName)
                rv.writeAmplFiles(bin, fileName=fileName)

    resolvedWeightedSum = fixedShapes.getZeroModeParametersForMode()

    totalHists = fixedShapes.getTotalHists(resolvedWeightedSum)
    #	studyAdder = "_noCorr"

    with root_open("./totals_0mp" + studyAdder + ".root", "UPDATE") as out:
        for t in totalHists:
            for m in t:
                m.Write()


#	return
#	folder = "./comparisonResultsData"+studyAdder+"/"
    folder = "./"
    for s, sect in enumerate(allMethods['fixedShapes'].sectors):

        #		allMethods['fixedShapes'].removeZeroModeFromComa()
        #		allMethods['fixedShapes'].removeGlobalPhaseFromComa()
        rv = allMethods['fixedShapes'].produceResultViewer(resolvedWeightedSum,
                                                           s,
                                                           noRun=True,
                                                           plotTheory=True)
        #		rv.titleFontSize = 11
        rv.showColorBar = True
        rv.writeToRootFile("0mp_" + sect + ".root")

        rv.writeBinToPdf(startBin,
                         stdCmd=[
                             folder + sect + "_data_2D_" + str(tBin) + ".pdf",
                             "", [], "", []
                         ])
        rv.plotData = True
        rv.plotTheo = False

        continue
        for b in range(startBin, stopBin):
            #			if  not b == 32:
            #				continue
            rv.replaceFromRootFile("f0s.root", 2)
            intensNames = [name + ".intens" for name in fileNames[sect, b]]
            argandNames = [name + ".argand" for name in fileNames[sect, b]]
            intensNames = []
            argandNames = []

            #			rv.writeAmplFiles(b,0,"./filesForMisha/"+sect+"_m"+str(b)+"_t"+str(tBin)+"_corrected")
            #			rv.writeAmplFiles(b,1,"./filesForMisha/"+sect+"_m"+str(b)+"_t"+str(tBin)+"_uncorrect")
            #			continue

            rv.writeBinToPdf(b,
                             stdCmd=[
                                 "", folder + sect + "_data_intens_" + str(b) +
                                 "_" + str(tBin) + ".pdf", intensNames,
                                 folder + sect + "_data_argand_" + str(b) +
                                 "_" + str(tBin) + ".pdf", argandNames
                             ])
    print studyList
    print cumulWeights
Exemplo n.º 9
0
def main(rhoFileName=""):
    checkLaTeX()
    inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_exotic.root"
    # # # # # Exotic (1-+)
    sectors = ["1-+1+[pi,pi]1--PiP"]

    referenceWave = "4-+0+rhoPiF"
    #	referenceWave = ""

    mBin = 32
    tBin = 3
    startBin = mBin
    stopBin = mBin + 1

    useBF = False
    merge0pp = False
    polyDegree = 0
    polyComplex = True
    waveModel = {}

    model = []
    fileNames = getFileNameForSector(sectors[0], useBF, merge0pp)
    for fn in fileNames:
        param = pc.fixedParameterization(fn,
                                         polynomialDegree=polyDegree,
                                         complexPolynomial=polyComplex)
        model.append(param)
    waveModel[sectors[0]] = model

    with root_open(inFileName, "READ") as inFile:
        histNames = GetKeyNames(inFile)
        histListReal = []
        histListImag = []
        histListNorm = []
        histListIndx = []
        nAmplMax = 0
        for sector in sectors:
            realHistName = sector + "_" + str(tBin) + "_real"
            histReal = inFile.Get(realHistName)
            if not histReal:
                raise IOError("Could not get '" + realHistName + "' from '" +
                              inFileName + "'")
            histReal.SetDirectory(0)
            histListReal.append(histReal)

            imagHistName = sector + "_" + str(tBin) + "_imag"
            histImag = inFile.Get(imagHistName)
            if not histImag:
                raise IOError("Could not get '" + imagHistName + "' from '" +
                              inFileName + "'")
            histImag.SetDirectory(0)
            histListImag.append(histImag)

            normHistName = sector + "_" + str(tBin) + "_norm"
            histNorm = inFile.Get(normHistName)
            if not histNorm:
                raise IOError("Could not get '" + normHistName + "' from '" +
                              inFileName + "'")
            histNorm.SetDirectory(0)
            histListNorm.append(histNorm)

            indexHistName = sector + "_" + str(tBin) + "_index"
            histIndx = inFile.Get(indexHistName)
            if not histIndx:
                raise IOError("Could not get '" + indexHistName + "' from '" +
                              inFileName + "'")
            histIndx.SetDirectory(0)
            nAmplMax = max(nAmplMax, int(2 * histIndx.GetMaximum()))
            histListIndx.append(histIndx)

        histsToFill = []
        comaHists = []
        intHistsReal = []
        intHistsImag = []
        for mBin in range(startBin, stopBin):
            comaHistName = "COMA_" + str(tBin) + "_" + str(mBin)
            comaHist = inFile.Get(comaHistName)
            if not comaHist:
                print "Could not get '" + comaHistName + "' from '" + inFileName + "'", "USING IDENTITY"
                comaHist = pyRootPwa.ROOT.TH2D(comaHistName, comaHistName,
                                               nAmplMax, 0., 1., nAmplMax, 0.,
                                               1.)
                for i in range(nAmplMax):
                    comaHist.SetBinContent(i + 1, i + 1, 1.)

            comaHist.SetDirectory(0)
            comaHists.append(comaHist)

        if not referenceWave == "":
            refHistReal = inFile.Get(referenceWave + "_" + str(tBin) + "_real")
            refHistReal.SetDirectory(0)
            if not refHistReal:
                raise IOError("Could not get '" + referenceWave + "_" +
                              str(tBin) + "_real" + "' from '" +
                              self.inFileName + "'")
            refHistImag = inFile.Get(referenceWave + "_" + str(tBin) + "_imag")
            refHistImag.SetDirectory(0)
            if not refHistImag:
                raise IOError("Could not get '" + referenceWave + "_" +
                              str(tBin) + "_imag" + "' from '" +
                              self.inFileName + "'")
            refHistIndex = inFile.Get(referenceWave + "_" + str(tBin) +
                                      "_index")
            refHistIndex.SetDirectory(0)
            if not refHistIndex:
                raise IOError("Could not get '" + referenceWave + "_" +
                              str(tBin) + "_index" + "' from '" +
                              self.inFileName + "'")
            changeReferenceWave(histListReal, histListImag, histListIndx,
                                comaHists, refHistReal, refHistImag,
                                refHistIndex, startBin, stopBin)

        ab = allBins(startBin, stopBin, histListReal, histListImag,
                     histListNorm, histListIndx, comaHists, intHistsReal,
                     intHistsImag)

        zeroCount = 0
        zeroHistList = []
        eigenHistList = []
        while True:
            zeroName = "zero" + str(zeroCount) + "_" + str(tBin)
            eigenName = "eigen" + str(zeroCount) + "_" + str(tBin)
            zeroHist = inFile.Get(zeroName)
            if not zeroHist:
                break
            zeroHist.SetDirectory(0)
            print "Adding zero-mode"
            zeroCount += 1
            if not zeroForSectors(sectors, zeroHist.GetTitle()):
                continue
            zeroHistList.append(zeroHist)

            eigenHist = inFile.Get(eigenName)
            eigenHist.SetDirectory(0)
            if eigenHist:
                eigenHistList.append(eigenHist)
        if (not len(eigenHistList) == 0) and (not len(eigenHistList)
                                              == len(zeroHistList)):
            raise ValueError(
                "Number of eigenvalue histograms does not match, but is also nonzero"
            )
        removeCertainZeroModes(zeroHistList, eigenHistList)
        for zeroHist in zeroHistList:
            borders = getZeroHistBorders(zeroHist)
            ab.addZeroMode(borders, zeroHist)

        writeSamples = False
        nRand = 100

        rh = histListReal[0]
        nPts = rh.GetNbinsY()
        valsC = np.zeros((2 * nPts, nRand))
        valsD = np.zeros((2 * nPts, nRand))

        for r in range(nRand + 1):

            ab.initChi2(waveModel)

            shapePars = []
            chi2, params = ab.chi2(shapePars, returnParameters=True)
            errs = ab.getNonShapeUncertainties(shapePars)
            paramsZ = ab.linearizeZeroModeParameters(params)

            zeroP = [0.] * len(paramsZ)
            argandNameBase = "./samplingArgands/argand_<mode>_" + str(
                r) + ".dat"

            IC = rh.Clone()
            IC.Reset()
            ab.fillHistograms(paramsZ, [IC], mode=INTENS)
            renormToBinWidth(IC, 1.)

            rC = rh.Clone()
            rC.Reset()
            ab.fillHistograms(paramsZ, [rC], mode=REAL)
            renormToBinWidth(rC, .5)

            iC = rh.Clone()
            iC.Reset()
            ab.fillHistograms(paramsZ, [iC], mode=IMAG)
            renormToBinWidth(iC, .5)

            if not r == 0:  # ugly, but r = 0 is unrandomized
                for i in range(nPts):
                    valsC[2 * i, r - 1] = rC.GetBinContent(mBin + 1, i + 1)
                    valsC[2 * i + 1, r - 1] = iC.GetBinContent(mBin + 1, i + 1)

            if writeSamples:
                with open(argandNameBase.replace("<mode>", "C"),
                          'w') as outFile:
                    for i in range(nPts):
                        m = rC.GetYaxis().GetBinCenter(i)
                        outFile.write(str(m))
                        for h in [IC, rC, iC]:
                            v = h.GetBinContent(mBin + 1, i + 1)
                            e = h.GetBinError(mBin + 1, i + 1)
                            if v == 0. and e == 0.:
                                continue
                            outFile.write(' ' + str(v) + ' ' + str(e))
                        outFile.write('\n')

            ID = rh.Clone()
            ID.Reset()
            ab.fillHistograms(zeroP, [ID], mode=INTENS)
            renormToBinWidth(ID, 1.)

            rD = rh.Clone()
            rD.Reset()
            ab.fillHistograms(zeroP, [rD], mode=REAL)
            renormToBinWidth(rD, .5)

            iD = rh.Clone()
            iD.Reset()
            ab.fillHistograms(zeroP, [iD], mode=IMAG)
            renormToBinWidth(iD, .5)

            if not r == 0:  # ugly, but r = 0 is unrandomized
                for i in range(nPts):
                    valsD[2 * i, r - 1] = rD.GetBinContent(mBin + 1, i + 1)
                    valsD[2 * i + 1, r - 1] = iD.GetBinContent(mBin + 1, i + 1)

            if writeSamples:
                with open(argandNameBase.replace("<mode>", "D"),
                          'w') as outFile:
                    for i in range(nPts):
                        m = rD.GetYaxis().GetBinCenter(i)
                        outFile.write(str(m))
                        for h in [ID, rD, iD]:
                            v = h.GetBinContent(mBin + 1, i + 1)
                            e = h.GetBinError(mBin + 1, i + 1)
                            if v == 0. and e == 0.:
                                continue
                            outFile.write(' ' + str(v) + ' ' + str(e))
                        outFile.write('\n')

            ab.randomize(
            )  # Put the randomization at the end, to have the fist run with unrandomized points

        correl = rh.Clone()
        correl.Reset()
        ab.fillHistograms(paramsZ, [correl], mode=REIMCORRELATION)
        renormToBinWidth(correl, 1.)
        if writeSamples:
            with open("correlations_D.dat", 'w') as outFile:
                for i in range(correl.GetNbinsY()):
                    outFile.write(
                        str(rD.GetBinError(mBin + 1, i + 1)**2) + ' ' +
                        str(correl.GetBinContent(mBin + 1, i + 1)) + ' ' +
                        str(iD.GetBinError(mBin + 1, i + 1)**2) + '\n')
        ab.removeZeroModeFromComa()
        correl.Reset()
        ab.fillHistograms(paramsZ, [correl], mode=REIMCORRELATION)
        rC.Reset()
        iC.Reset()
        ab.fillHistograms(paramsZ, [rC], mode=REAL)
        ab.fillHistograms(paramsZ, [iC], mode=IMAG)
        renormToBinWidth(correl, 1.)
        renormToBinWidth(rC, .5)
        renormToBinWidth(iC, .5)
        with open("correlations_C.dat", 'w') as outFile:
            for i in range(correl.GetNbinsY()):
                outFile.write(
                    str(rC.GetBinError(mBin + 1, i + 1)**2) + ' ' +
                    str(correl.GetBinContent(mBin + 1, i + 1)) + ' ' +
                    str(iC.GetBinError(mBin + 1, i + 1)**2) + '\n')
Exemplo n.º 10
0
def main():
    rhoBW = BELLE_bw_amplitude(
        'pp', mD0, mKs, mPi, mPi,
        BELLE_bw(.77526, .1478, 1, mD0, mPi, mPi, mKs, 'rho'))

    K892BW_1 = BELLE_bw_amplitude(
        'Kp1', mD0, mKs, mPi, mPi,
        BELLE_bw(.89166, .0508, 1, mD0, mKs, mPi, mPi, 'K892'))
    K1430BW_1 = BELLE_bw_amplitude(
        'Kp1', mD0, mKs, mPi, mPi,
        BELLE_bw(1.420, .230, 0, mD0, mKs, mPi, mPi, 'K1430'))
    K1680BW_1 = BELLE_bw_amplitude(
        'Kp1', mD0, mKs, mPi, mPi,
        BELLE_bw(1.717, .322, 1, mD0, mKs, mPi, mPi, 'K1680'))

    K892BW_2 = BELLE_bw_amplitude(
        'Kp2', mD0, mKs, mPi, mPi,
        BELLE_bw(.89166, .0508, 1, mD0, mKs, mPi, mPi, 'K892'))
    K1430BW_2 = BELLE_bw_amplitude(
        'Kp2', mD0, mKs, mPi, mPi,
        BELLE_bw(1.420, .230, 0, mD0, mKs, mPi, mPi, 'K1430'))
    K1680BW_2 = BELLE_bw_amplitude(
        'Kp2', mD0, mKs, mPi, mPi,
        BELLE_bw(1.717, .322, 1, mD0, mKs, mPi, mPi, 'K1680'))

    inFileName = "./build/fineBinnedDalitz.root"
    histName2 = "dalitz_1.815000-1.915000"
    #	histName   = "cosTp_vs_m2pp"
    masses = []
    values = []

    resl = mD0**2 + 2 * mPi**2 + mKs**2
    #	print resl, 3.7641662108

    with root_open(inFileName, "READ") as inFile:
        dalitz = inFile.Get(histName2)

        for i in range(dalitz.GetNbinsX()):
            x = dalitz.GetXaxis().GetBinCenter(i + 1)
            for j in range(dalitz.GetNbinsY()):
                val = dalitz.GetBinContent(i + 1, j + 1)
                if val > 0.:
                    y = dalitz.GetYaxis().GetBinCenter(j + 1)
                    if x < 0. or y < 0. or resl - x - y < 0.:
                        continue
                    try:
                        c, m, j = getCosTmPP(y, x)
                    except ValueError:
                        continue
                    if abs(c) > 1.:
                        continue
                    masses.append((x, y))
                    values.append(val)

#		xMin = -1.0
#		xMax =  1.0
#		yMin =  0.26
#		yMax =  1.44913767462

        xMin = min([m[0] for m in masses])
        xMax = max([m[0] for m in masses])
        yMin = min([m[1] for m in masses])
        yMax = max([m[1] for m in masses])

        #		for m in masses:
        #			yMin = min(yMin, m[1])
        #			yMax = max(yMax, m[1])

        print xMin, "< x <", xMax
        print yMin, "< y <", yMax

        fSet = []
        fSet = [
            rhoBW, K892BW_1, K1430BW_1, K1680BW_1, K892BW_2, K1430BW_2,
            K1680BW_2
        ]
        maxDim = 7
        for i in range(maxDim):
            #			if i == 1:
            #				continue
            for j in range(maxDim - i):
                #				if j == 1:
                #					continue
                #				fSet.append(legendre_with_transformation(i,xMin,xMax,j,yMin,yMax))
                fSet.append(legendre(i, xMin, xMax, j, yMin, yMax))

        bestModel = c2ndfScan(masses, values, fSet)
        print len(bestModel)

        #		bestModel = [0, 1, 30, 2, 20, 5, 44, 23, 71, 21, 40, 3, 4, 14, 6,
        #		             24, 17, 80, 54, 9, 79, 50, 47, 29, 97, 77, 78, 90,
        #		             13, 31, 96, 98, 32, 27, 45, 62, 18, 95, 48, 26, 91,
        #		             38, 82, 41, 65, 74, 28, 58, 70, 51, 64, 16, 81, 61,
        #		             84, 8, 92, 36, 7, 25, 34, 60, 76, 66, 52, 39, 15,
        #		             75, 33, 19, 67, 83, 72, 46, 53, 99, 94, 63, 22, 73,
        #		             59, 85, 86, 37, 88, 49, 87, 68, 56, 93, 55, 43, 42] ## len([...]) = 93

        #		print len(bestModel)

        bestFset = []
        for i in bestModel:
            bestFset.append(fSet[i])

#		maxDegX = 0
#		maxDegY = 0
#		for f in bestFset:
#			maxDegX = max(maxDegX, f.degX)
#			maxDegY = max(maxDegY, f.degY)

#		overAllCoeffs = [[0.]*(maxDegY+1) for _ in range(maxDegX+1)]

        A, B, C = get_ABC(values, masses, bestFset)
        coeffs = -np.dot(la.inv(A + A.T), B)
        #		for n,f in enumerate(bestFset):
        #			legendre_coeffs = f.getCoefficients()
        #			for i in range(len(legendre_coeffs)):
        #				for j in range(len(legendre_coeffs[i])):
        #					overAllCoeffs[i][j] += coeffs[n] * legendre_coeffs[i][j]
        #		with open("./build/dalitzBackground_version2.pol", 'w') as outFile:
        #			for i in range(maxDegX+1):
        #				for j in range(maxDegY+1):
        #					coeff = overAllCoeffs[i][j]
        #					if not coeff == 0.:
        #						outFile.write(str(i) + ' ' + str(j) + ' ' + str(coeff) + '\n')

        #		chi2   = np.dot(coeffs, np.dot(A,coeffs)) + np.dot(coeffs,B) + C
        #		print "chi2/NDF =",chi2/(len(masses) - len(bestFset))
        #
        #		return

        #	histTheo = hist.Clone()
        #	histTheo.Reset()
        #	histTheo.SetTitle("Hist theo cTm")
        #	histTheo.SetName("Hist_theo_cTm")
        #
        #		for c,centers in enumerate(masses):
        #			i   = hist.GetXaxis().FindBin(centers[0])
        #			j   = hist.GetYaxis().FindBin(centers[1])
        #			dat = hist.GetBinContent(i,j)
        #			if dat == 0.:
        #				continue
        #			val = 0.
        #			for f,func in enumerate(bestFset):
        #				val += coeffs[f]*func(*centers)
        #			histTheo.SetBinContent(i,j,val)

        c2 = 0.
        ndf = 0
        jacPlot = dalitz.Clone()
        dalModel = dalitz.Clone()

        lesData = dalitz.Clone()
        lesData.Reset()
        lesData.SetName("data_replot")
        lesData.SetTitle("Data replot")

        if not len(values) == len(masses):
            raise ValueError("Da haben wir der Uebeltaeter")
        for i in range(len(values)):
            binX = lesData.GetXaxis().FindBin(masses[i][0])
            binY = lesData.GetYaxis().FindBin(masses[i][1])
            lesData.SetBinContent(binX, binY, values[i])

    #	jacPlot.Reset()
    #	jacPlot.SetTitle("Jacobian")
    #	jacPlot.SetName("Jacobian")

        dalModel.Reset()
        dalModel.SetTitle("Dalitz model")
        dalModel.SetName("Dalitz_model")

        for i in range(lesData.GetNbinsX()):
            mKp2 = lesData.GetXaxis().GetBinCenter(i + 1)
            for j in range(lesData.GetNbinsY()):
                dat = lesData.GetBinContent(i + 1, j + 1)
                if dat == 0.:
                    continue
                ndf += 1
                mpp2 = lesData.GetYaxis().GetBinCenter(j + 1)
                val = 0.
                try:
                    for f, func in enumerate(bestFset):
                        val += coeffs[f] * func(mKp2, mpp2)
                    dalModel.SetBinContent(i + 1, j + 1, val)
                except ValueError:
                    continue

        with root_open("polotossos.root", "RECREATE"):
            #			hist.Write()
            dalitz.Write()
            #			histTheo.Write()
            #			jacPlot.Write()
            dalModel.Write()
            lesData.Write()

        dalitz.Draw("colz")

        print "Im dalitz", c2 / (ndf - len(bestModel))
Exemplo n.º 11
0
def main():
	bfe = '.' + getBranchFileEnding()

	conj     = False
	if "-conj" in sys.argv:
		conj = True

	makeZM   = False
	cutFreed = True
	loadConstants()
	print mD0, mKs, mPi
	freeMap, freeString = parseCmdLine(sys.argv, additionalOptions = ["-conj"])

	zeroMap = [False, False,False, False, False, False, False, False, False]

#	bestFn  = getStartFileName(getBestFileName(freeMap))

#	firstFileWithoutPrior = "./build/BELLE_fit_results/BELLE_fit_111111111_-16956062.253189_1541618747.dat"
#	lastFileWithoutPrior  = "./build/BELLE_fit_results/BELLE_fit_111111111_-20638751.029967_1541673946.dat"

#	dataMarkerFile = "./build/BELLE_fit_results/BELLE_fit_000000000_-16927048.975653_1541596896.dat"

	bestFn, allLL = getBestFileName(freeMap, zeroMap = zeroMap)
#	bestFn, allLL = getBestFileName(freeMap, zeroMap = zeroMap, hasToBeAfterFile = dataMarkerFile)

	allLL.sort()
#	for i in xrange(10):
#		print "bestLikelihoods",allLL[i]
	print bestFn

	print "-----------------------------"
	print "best result file: '"+bestFn+"'"
	print "info file is: '"+getInfoFileName(bestFn)+"'"
	print "created:",datetime.datetime.fromtimestamp(os.path.getctime(bestFn))
	print "-----------------------------"

	ps_fileName, ac_fileName = getIntegralFileNames(bestFn)
	integral                 = integralClass(ps_fileName)
	integral.fixMap          = zeroMap

	if cutFreed:
		integral.cutFreed()
#	integral.cutFirstSector()

	prodAmps = parseResultFile(bestFn, conj = conj)
	prodAmps = cutFree(prodAmps, freeMap, fixMap = zeroMap)
	binnings = getBinnings(freeMap, fixMap = zeroMap)

	norms    = [integral.psMatrix[i,i].real for i in xrange(len(prodAmps))]

	integral.normalize()

	sectorNames = getSectorNames(freeMap, fixMap = zeroMap)
	binning     = getBinnings(freeMap, fixMap = zeroMap)

	hists = makeAllWaveHists(sectorNames, prodAmps, binnings, norms)

	integral.makeZMs(0.01)
	maxEV = np.max(integral.allEVs)

	if makeZM and cutFreed:
		for i,zeroMode in enumerate(integral.zms):
			zeroFileName = "./build/zeroModeFiles/"+freeString+"_"+str(i) + bfe
			fullZM = makeFullVector(zeroMode, freeMap, True, True)
			with open(zeroFileName, 'w') as outFile:
				for v in fullZM:
					outFile.write("("+str(v.real)+','+str(v.imag)+') ')
		return
	elif makeZM:
 # # # Use this after cutFirstSector
		print len(integral.zms),"::::::::::"
		for i,zeroMode in enumerate(integral.zms):
			zeroFileName = "./build/zeroModeFiles/"+freeString+"_"+str(i) + bfe
			with open(zeroFileName, 'w') as outFile:
				for v in zeroMode:
					outFile.write("("+str(v.real)+','+str(v.imag)+') ')
				for v in zeroMode:
					outFile.write("(0.,0.) ")
				outFile.write("(0.,0.) ")
		return

	titles = []
	for i, zeroMode in enumerate(integral.zms):
		zmh, eigh = makeZeroModeHists(sectorNames, zeroMode, integral.evs[i], binnings, i, minAmount = 0.01)
		title = zmh.GetTitle()
		while title in titles:
			title += "<|sec++>"
		titles.append(title)
		zmh.SetTitle(title)
		eigh.SetTitle(title)
		hists.append(zmh)
		hists.append(eigh)

	hists.append(getComaHist(bestFn, fixMap = zeroMap, conj = conj))

	with root_open("DdecayResults_"+freeString+"_"+getBranchFileEnding()+".root", "RECREATE"):
		for h in hists:
			h.Write()
	return

	c1 = ROOT.TCanvas()
	hist = ROOT.TH1D("h","h",len(integral.zms[0]),0.,1.)
	for i in xrange(len(integral.zms)):
		print len(integral.zms[i])
		for j in xrange(len(integral.zms[i])):
			hist.SetBinContent(j+1, integral.zms[i,j])
		hist.Draw()
		c1.Update()
		raw_input()
Exemplo n.º 12
0
def main():
    nF0, nRho, nF2 = loadN()

    bin = 34
    #				Seed    # neg log like
    #	seedAppendix   =  "_1498549364"
    #
    #	seedAppendix   =  "_1498570556" # -1.31183e+07
    #	seedAppendix   =  "_1498570525" # -1.31178e+07
    #	seedAppendix   =  "_1498570546" # -1.31174e+07
    #	seedAppendix   =  "_1498570532" # -1.31184e+07
    #	seedAppendix   =  "_1498570552" # -1.31156e+07

    #	seedAppendix   =  "_1498652006" # -1.34472e+07
    #	seedAppendix   =  "_1498652015" # -1.34515e+07
    #	seedAppendix   =  "_1498652011" # -1.34499e+07
    #	seedAppendix   =  "_1498652008" # -1.34471e+07
    #	seedAppendix   =  "_1498652038" # -1.34464e+07

    #	seedAppendix   =  "_1498815114" # -1.34505e+07
    #	seedAppendix   =  "_1498815131" # -1.34466e+07
    #	seedAppendix   =  "_1498815125" # -1.34459e+07
    #	seedAppendix   =  "_1498815128" # -1.34462e+07
    #	seedAppendix   =  "_1498815121" # -1.34475e+07

    #	seedAppendix = "_1512582427"
    seedAppendix = "_1512637090"

    amplFileName = "./build/largeErrorStudy_amplitudes" + seedAppendix + ".dat"
    hessFileName = "./build/largeErrorStudy_hessian" + seedAppendix + ".dat"
    inteFileName = "./build/largeErrorStudy_integral.dat"
    binFfileName = "./build/largeErrorStudy_binningF0.dat"
    binRfileName = "./build/largeErrorStudy_binningRho.dat"
    binF2fileName = "./build/binningF2.dat"

    conjugate = True

    binningF0 = loadBinning(binFfileName)
    binningRho = loadBinning(binRfileName)
    binningF2 = loadBinning(binF2fileName)

    nBins = 0
    eigenString = ""
    sectors = {}
    if nF2 > 1:
        dnb = len(binningF2) - 1
        sectors["Dp[pi,pi]2++PiD"] = (nBins, nBins + dnb)
        nBins += dnb
        eigenString += "Dp[pi,pi]2++PiD"
    if nF0 > 1:
        dnb = len(binningF0) - 1
        sectors["Dp[pi,pi]0++PiS"] = (nBins, nBins + dnb)
        nBins += dnb
        if len(eigenString) > 0:
            eigenString += "<|>"
        eigenString += "Dp[pi,pi]0++PiS"
    if nRho > 1:
        dnb = len(binningRho) - 1
        sectors["Dp[pi,pi]1--PiP"] = (nBins, nBins + dnb)
        nBins += dnb
        if len(eigenString) > 0:
            eigenString += "<|>"
        eigenString += "Dp[pi,pi]1--PiP"

    print nF0, nRho, nF2, nBins

    ampl = loadAmplitudeFile(amplFileName, conjugate)
    hessian = loadRealMatrixFile(hessFileName)
    inte = integral(inteFileName)

    if nRho == 1:  # Remove fixed waves from the integral matrix
        inte.removeIndices(nF0 + nF2)
        ampl, hessian = removeIndex(nF0 + nF2, ampl, hessian)
    if nF0 == 1:
        inte.removeIndices(nF2)
        ampl, hessian = removeIndex(nF2, ampl, hessian)
    if nF2 == 1:
        inte.removeIndices(0)
        ampl, hessian = removeIndex(0, ampl, hessian)

    inte.norm()
    inte.eigen()
    norm = inte.norms

    svals, sev = inte.getSmallVectors(0.001)

    hasZeroMode = False
    if len(sev) > 0:
        hasZeroMode = True
    else:
        print "No zero-mode found"

    comaName = "COMA_0_" + str(bin)
    histReName = "INTEGRAL_r_0_" + str(bin)
    histImName = "INTEGRAL_i_0_" + str(bin)
    #	COMA     = la.inv(hessian)
    COMA = utils.pinv(hessian, 1.e-4)
    if conjugate:
        for i in range(2 * nBins):
            for j in range(2 * nBins):
                iNdex = i
                jNdex = j
                sign = (-1)**(iNdex + jNdex)
                COMA[iNdex, jNdex] *= sign


#	COMA     = projectOutPhaseDirection(COMA, ampl)

    with root_open("DpPiPiPi_largeErrorStudy.root", "RECREATE") as outFile:
        COMAhist = pyRootPwa.ROOT.TH2D(comaName, comaName, 2 * nBins, 0., 1.,
                                       2 * nBins, 0., 1.)
        intReHist = pyRootPwa.ROOT.TH2D(histReName, histReName, nBins, 0., 1.,
                                        nBins, 0., 1.)
        intImHist = pyRootPwa.ROOT.TH2D(histImName, histImName, nBins, 0., 1.,
                                        nBins, 0., 1.)
        for i in range(nBins):
            for j in range(nBins):
                intReHist.SetBinContent(i + 1, j + 1, inte[i, j].real)
                intImHist.SetBinContent(i + 1, j + 1, inte[i, j].imag)
        intReHist.Write()
        intImHist.Write()

        for i in range(2 * nBins):
            #			COMAhist.SetBinContent(i+1, i+1, 1.) # first two are fixed isobar
            for j in range(2 * nBins):
                iNdex = i
                jNdex = j
                COMAhist.SetBinContent(
                    i + 1, j + 1, COMA[iNdex,
                                       jNdex])  # first two are fixed isobar
                pass
        COMAhist.Write()

        for i, zeroMode in enumerate(sev):
            eigenHist = pyRootPwa.ROOT.TH1D("eigen" + str(i) + "_0",
                                            eigenString, 50, .5, 2.5)
            eigenHist.SetBinContent(bin + 1, svals[i])
            eigenHist.Write()

            zeroHist = pyRootPwa.ROOT.TH2D("zero" + str(i) + "_0", eigenString,
                                           50, .5, 2.5, nBins, 0., 1.)
            for i in range(nBins):
                zeroHist.SetBinContent(bin + 1, i + 1, zeroMode[i].real)
            zeroHist.Write()

        for sector in sectors:
            if "1--" in sector:
                isobarBinning = binningRho
            elif "0++" in sector:
                isobarBinning = binningF0
            elif "2++" in sector:
                isobarBinning = binningF2
            else:
                "Sector not valid: '" + sector + "'"
            histIntens = pyRootPwa.ROOT.TH2D(sector + "_0_intens",
                                             sector + "_0_intens",
                                             len(binning3Pi) - 1, binning3Pi,
                                             len(isobarBinning) - 1,
                                             isobarBinning)
            histReal = pyRootPwa.ROOT.TH2D(sector + "_0_real",
                                           sector + "_0_real",
                                           len(binning3Pi) - 1, binning3Pi,
                                           len(isobarBinning) - 1,
                                           isobarBinning)
            histImag = pyRootPwa.ROOT.TH2D(sector + "_0_imag",
                                           sector + "_0_imag",
                                           len(binning3Pi) - 1, binning3Pi,
                                           len(isobarBinning) - 1,
                                           isobarBinning)
            histNorm = pyRootPwa.ROOT.TH2D(sector + "_0_norm",
                                           sector + "_0_norm",
                                           len(binning3Pi) - 1, binning3Pi,
                                           len(isobarBinning) - 1,
                                           isobarBinning)
            histIndex = pyRootPwa.ROOT.TH2D(sector + "_0_index",
                                            sector + "_0_index",
                                            len(binning3Pi) - 1, binning3Pi,
                                            len(isobarBinning) - 1,
                                            isobarBinning)
            for b, B in enumerate(range(sectors[sector][0],
                                        sectors[sector][1])):
                histIntens.SetBinContent(bin + 1, b + 1, abs(ampl[B])**2)
                histReal.SetBinContent(bin + 1, b + 1, ampl[B].real)
                histImag.SetBinContent(bin + 1, b + 1, ampl[B].imag)
                histNorm.SetBinContent(bin + 1, b + 1, norm[B])
                histIndex.SetBinContent(bin + 1, b + 1, B)
            histIntens.Write()
            histReal.Write()
            histImag.Write()
            histNorm.Write()
            histIndex.Write()
Exemplo n.º 13
0
def domtBin(tBin, mBin):
	ROOT.gStyle.SetOptStat(0)
	findBest     = True
	allFileNames = []
	if findBest:
		tString   = "_t"+str(tBin)+"_"
		bestChi2  = float('inf')
		bestFn    = None
		worstChi2 =-float('inf')
#		folder    = "./KmatrixResults/"
#		folder    = "./KmatrixRestrictedZMfixing_allFourSectorsActive/"
		folder    = "./complexF2poles/"
		m3Pi      = .5 + (mBin+.5)*.04
		for fn in os.listdir(folder):
			if not tString in fn:
				continue
			if not "_kPol0_" in fn:
				continue
			if not "m"+str(mBin)+"-"+str(mBin+1) in fn:
				continue
			if not fn.startswith("2mpF2_"):
				continue
#			if not "_nPol3_" in fn:
#				continue
#			if not "_CM_" in fn:
#				continue
			fileName     = folder + fn
			result       = KmatrixFitResult(fileName)
			try:
				result.chi2
				allFileNames.append((result.chi2, fileName,result.chi2/result.ndf))
			except AttributeError:
				print "ERROR in: ",fn
				continue
			worstChi2 = max(worstChi2, result.chi2)
			if result.chi2 < bestChi2:
				bestChi2 = result.chi2 
				bestFn   = fn
			try:
				inFileName = folder + bestFn
			except:
				print "ERROR : : : : : : "
				continue
	else:
		inFileName = "./KmatrixResults/2mpF2_Kmatrix_nPol3_rho_kPol2_pPol7-4_t0_m40-50_9696.dat"

	if len(allFileNames) == 0:
		return

	allFileNames.sort()
	allFileNames.reverse()
	allFileNames = allFileNames[~1:]



	c2h_rho = ROOT.TH1D("c2","c2",250, bestChi2, worstChi2)
	c2h_CM  = ROOT.TH1D("c2","c2",250, bestChi2, worstChi2)
	c2h_CM.SetLineColor(2)


	first = True
	hsh = []
	for f,inFileName in enumerate(allFileNames):
#		if not f == 182:
#			continue
		print f+1,'/',len(allFileNames), inFileName
		result     = KmatrixFitResult(inFileName[1])
		pyCommand = "python 2mp_data_zeroModeFixingComparison.py "+str(result.tBin)+ " ifn="+result.inFileName+ " mBins-"+str(result.mRange[0])+'-'+str(result.mRange[1])+" "+result.phaseSpace+" m3pol"+str(result.pPol[0])+" m2pol"+str(result.pPol[1])+" pdpo"+str(result.kPol+1)
		print ">>>",pyCommand,"<<<"
		Kmatrix    = result.produceFunction()
		pVector    = result.producePvector()

		intensHist = ROOT.TH1D("ntns",str(tBin)+"_"+str(mBin), nBinsPlot, 2*mPi, m3Pi - mPi)

		masses = [intensHist.GetXaxis().GetBinCenter(i+1) for i in range(nBinsPlot)]
		vK = Kmatrix(masses)
		vP = pVector(masses,[m3Pi])
		for i in range(nBinsPlot):
			intensHist.SetBinContent(i+1, abs(vK[i]*vP[i])**2)
#			intensHist.SetBinContent(i+1, vP[i])

		mMinNorm   = (2*mPi)
		mMaxNorm   = (m3Pi-mPi)
		binMinNorm = intensHist.GetXaxis().FindBin(mMinNorm)
		binMaxNorm = intensHist.GetXaxis().FindBin(mMaxNorm)
		norm       = 0.
		for i in range(binMinNorm, binMaxNorm):
			norm += intensHist.GetBinContent(i)
		intensHist.Scale(1./norm)

		hsh.append(intensHist)

		hist = ROOT.TH2D("hhh",str(tBin)+"_"+str(mBin), nBinsPlot, reMin, reMax ,nBinsPlot, imMin,imMax)

		BWtoSet = [(1.272,0.1867),(1.525, 0.075),(2.011,0.202)]

		sToSet = [BW[0]**2 for BW in BWtoSet]
		GtoSet = [BW[0]*BW[1] for BW in BWtoSet]

		bwSetLength   = 0.1
		setVal        = 10.
	
#		for iX in range(nBinsPlot):
#			x = hist.GetXaxis().GetBinCenter(iX+1)
#			for iY in range(nBinsPlot):
#				y = hist.GetYaxis().GetBinCenter(iY+1)			
#				s = x+1.j*y
#				val = Kmatrix.complexCall(s)
#				hist.SetBinContent(iX+1, iY+1,fPlot(val))
#
#		for s in sToSet:
#			iX = hist.GetXaxis().FindBin(s)
#			for iY in range(nBinsPlot):
#				hist.SetBinContent(iX, iY+1, setVal)
#	
#		hist.SetMaximum( 10.)
#		hist.SetMinimum(-10.)
#	
#		hist.Draw("COLZ")
#		raw_input("press <enter> to go to the second sheet")
		Kmatrix.secondSheet = True
		allPoles = findAllPoles(Kmatrix, [-1.,6.], [0.,2.])
		for p in allPoles:
			histAllPolePos.Fill(p[0],abs(p[1]))
			if "_CM_" in inFileName[1]:
				histAllPolePos_CM.Fill(p[0],abs(p[1]))
			else:
				histAllPolePos_rho.Fill(p[0],abs(p[1]))
		for iX in range(nBinsPlot):
			x = hist.GetXaxis().GetBinCenter(iX+1)
			for iY in range(nBinsPlot):
				y = hist.GetYaxis().GetBinCenter(iY+1)			
				s = x+1.j*y
				val = Kmatrix.complexCall(s)
				hist.SetBinContent(iX+1, iY+1, fPlot(val))
		for s in sToSet:
			iX = hist.GetXaxis().FindBin(s)
			for iY in range(nBinsPlot):
				hist.SetBinContent(iX, iY+1, -setVal)
		for g,im in enumerate(GtoSet):
			re = sToSet[g]
			binMin = hist.GetXaxis().FindBin(re-bwSetLength)
			binMax = hist.GetXaxis().FindBin(re+bwSetLength)
			binIm  = hist.GetYaxis().FindBin(im)
			binImM = hist.GetYaxis().FindBin(-im)
			for b in range(binMin, binMax):
					hist.SetBinContent(b+1, binIm, -setVal)
					hist.SetBinContent(b+1, binImM, -setVal)
		hist.SetMaximum( 10.)
		hist.SetMinimum(-10.)
		if not "_CM_" in inFileName[1]:
			c2h_rho.Fill(inFileName[0])
		else:
			c2h_CM.Fill(inFileName[0])

		c2.cd()
#		c2h_rho.Draw()
#		c2h_CM.Draw()
#		histAllPolePos.Draw("COLZ")
		if first:
			intensHist.Draw()
		else:
			intensHist.Draw("SAME")
		c2.Update()
		c1.cd()
		hist.Draw("COLZ")
		c1.Update()
#		raw_input("press <enter> to quit")
#		sleep(.3)

		first = False
	with root_open("./poleDistribution.root","RECREATE"):
		histAllPolePos.Write()
		hist.Write()
def main():
	checkLaTeX()
	style = modernplotting.mpplot.PlotterStyle()
#	style.p2dColorMap = 'ocean_r'
#	style.p2dColorMap = 'YlOrRd'
	style.p2dColorMap = 'Reds'

	inFileName    = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_exotic.root"
	sectors          = ["1-+1+[pi,pi]1--PiP"]
	tBin = int(sys.argv[1])
	if tBin < 0 or tBin > 3:
		raise ValueError("Invalid t' bin: " + str(tBin))
	writeCpls     = False
	twoDmarkPlots = False
	scalle        = False
	Xcheck        = False
	globalScale   = False
	setRanges     = False
	writeROOT     = False
	rangeMin      = 0.
	rangeMax      = 1.12
	startBin      = 11
	stopBin       = 50
	acv           = 1.3e-2
	for i in range(2,len(sys.argv)):
		a = sys.argv[i]
		if a == "-scale":
			scalle = True
		elif a == "-2Dmark":
			twoDmarkPlots = True
		elif a == "-Xcheck":
			Xcheck = True
		elif a == "-cpls":
			writeCpls = True
		elif a == "-global":
			globalScale = True
		elif a.startswith("-rangeMin"):
			setRanges = True
			rangeMin  = float(a[9:])
		elif a.startswith("-rangeMax"):
			setRanges = True
			rangeMax  = float(a[9:])
		elif a.startswith("-start"):
			startBin = int(a[6:])
		elif a.startswith("-stop"):
			stopBin = int(a[5:])
		elif a == "-ROOT":
			writeROOT = True
		elif a.startswith("-acv"):
			acv = float(a[4:])
		else:
			raise RuntimeError("Could not parse option '" + a + "'")

	print "-------------------------------"
	print "tbin",tBin
	print"(startBin,stopBin) (",startBin,",",stopBin,")"
	print "writeCpls",writeCpls
	print "scale", scalle
	print "2Dmarks",twoDmarkPlots
	print "Xcheck",Xcheck
	print "globalScale",globalScale
	print "fitRange ("+str(rangeMin)+","+str(rangeMax)+")"
	print "writeROOT",writeROOT
	print "acv",acv
	print "-------------------------------"	

	tBins            = [tBin]

#	acv = None
#	acv = 130. # artificial coma value
#	acv = 1.3e-3 # artificial coma value

	methodBinRanges = {
	                   "fitF2"        : (22, 50),
	                   "fitRhoF"      : (22, 50),
	                   "fixedShapeF2" : (22, 50)}
#	methodBinRanges = {} # Override here 


	sectorRangeMap = {"1-+1+[pi,pi]1--PiP":(rangeMin, rangeMax)}	
#	sectorRangeMap = {}


	allMethods       = {}
	methodStrings    = {}
	shortlabels      = {  "fixedShapeF0"      : r"$\text{fix}_{f_0}^{~}$",
	                      "fixedShapeRhoP"    : r"$\text{fix}_\rho^{P}$",
	                      "fixedShapeRhoF"    : r"$\text{fix}_\rho^{F}$",
	                      "fixedShapeBothRho" : r"$\text{fix}_\rho^{2}$",
	                      "fixedShapeF2"      : r"$\text{fix}_{f_2}$",
	                      "fixedShapes"       : r"$\text{fix}_\text{all}^{~}$",
	                      "pipiS"             : r"$\phi_{[\pi\pi]_S}^{~}$",
	                      "fitRho"            : r"$\text{fit}_\rho$",
	                      "fitRhoP"           : r"$\text{fit}_\rho^{P}$",
	                      "fitRhoF"           : r"$\text{fit}_\rho^{F}$",
	                      "fitBothRho"        : r"$\text{fit}_\rho^{2}$",
	                      "fitF2"             : r"$\text{fit}_{f_2}$",
	                      "smooth"            : r"smooth"}
	print "Starting with fixed shapes"
	fixedShapes = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, sectorRangeMap = sectorRangeMap, acv = acv)
	allMethods["fixedShapes"] = fixedShapes
	print "Finished with fixed shapes"
	fullSig = fixedShapes.getZeroModeSignature()

	fullRanges = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, sectorRangeMap = {}, acv = acv)
	zeroModeParameters = fixedShapes.getZeroModeParametersForMode()

	doRhoFits = False

	if setRanges:
		rangeString = "_rangeMin"+str(rangeMin)+"_rangeMax"+str(rangeMax)

	if writeCpls:
		print fixedShapes.nonShapeParameters
		print "Writing couplings..."
		fixedShapes.calculateNonShapeParametersForZeroModeParameters(zeroModeParameters)
		outFileCpl = open("./cplFiles/1mp_rho_cpls"+rangeString+"_"+str(tBin)+".dat",'w') 
		cpl, hess = fixedShapes.getCouplingParameters()
		if not len(cpl[0][0]) == 2:
			raise IndexError("Parameter count not 2, change implementation")
		for i in range(stopBin-startBin):
			binIndex = i+startBin
			hessInv = la.inv(hess[0][i])
			integral = fixedShapes.model[0][i].getIntegralForFunction(0, fixedShapes.model[0][i].funcs[0][0])
			outFileCpl.write(str(0.52 + binIndex*.04) + ' ' + str(cpl[0][i][0]**2 + cpl[0][i][0]**2) + ' ' + str(integral) + ' ')
			outFileCpl.write(str(cpl[0][i][0])     + ' ' + str(cpl[0][i][1])     + ' ')
			outFileCpl.write(str(hessInv[0][0]/2) + ' ' + str(hessInv[1][1]/2) + ' ' + str(hessInv[0][1]/2))
			outFileCpl.write("\n")
		outFileCpl.close()
		return

	doActuallyNotFit = False
	if doRhoFits:
		fitRho = doFitRho(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, writeResultToFile = "rhoMassesAndWidths_1-+1+1--_global.dat", sectorRangeMap = sectorRangeMap, acv = acv)
		fitRho.initMinuitFunction(fitRho.getParameters())
		with open("rhoMassesAndWidths_exoticForPaper_"+str(tBin)+".dat",'w') as out:
			for i in range(stopBin-startBin):
				binIndex = i+startBin
				out.write(str(binIndex)+' '+str(0.52 + 0.04*binIndex)+' ')
				startValueOffset = 0.00
				if doActuallyNotFit:
					print "The fit has been turned off, due to a workaround... :("
				else:
					exceptCount      = 0
#					try:
					if True:
						x,err,c2,ndf = fitRho.fitShapeParametersForBinRange([mRho+startValueOffset,Grho+startValueOffset], [0],[i], zeroModeParameters = zeroModeParameters)
#					except:
#						print "Fitter exception encountered"
#						startValueOffset += 0.001
#						exceptCount      += 1	
#						if exceptCount > 3:
#							raise Exception("Too many failed attempts: "+str(exceptCount))
	
					out.write(str(x[0]) + ' ' + str(err[0]) + ' ' + str(x[1]) + ' ' + str(err[1]))
					out.write(' '+str(c2/ndf)+'\n')

				if writeCpls:
					fitRho.calculateNonShapeParametersForZeroModeParameters(zeroModeParameters)
					cpl, hess = fitRho.getCouplingParameters()
					hessInv = la.inv(hess[0][i])
					if not len(cpl[0][1]) == 2:
						raise IndexError("Parameter count not 2, change implementation")
					integral = fitRho.model[0][i].getIntegralForFunction(0, fitRho.model[0][i].funcs[0][0])
					outFileCpl.write(str(0.52 + binIndex*.04) + ' ' + str(cpl[0][i][0]**2 + cpl[0][i][0]**2) + ' ' + str(integral) + ' ')
					outFileCpl.write(str(cpl[0][i][0])     + ' ' + str(cpl[0][i][1])     + ' ')
					outFileCpl.write(str(hessInv[0][0]/2) + ' ' + str(hessInv[1][1]/2) + ' ' + str(hessInv[0][1]/2))
					outFileCpl.write("\n")

				makeRhoFitPlots = False

				if makeRhoFitPlots:
					fitRho.calculateNonShapeParametersForZeroModeParameters(zeroModeParameters)
					rhoRV = fitRho.produceResultViewer(zeroModeParameters,"1-+1+[pi,pi]1--PiP", noRun = True, plotTheory = True)
					rhoRV.plotData = True
					plotNameBase = "./rhoFitPlots/1mp1p1mmPiP_<mode>_"+str(binIndex)+"_"+str(tBin)+".pdf"
					rhoRV.writeBinToPdf(binIndex, stdCmd = ["", plotNameBase.replace("<mode>","intens"), [],  plotNameBase.replace("<mode>","argand"), []])
		if writeCpls:
			outFileCpl.close()

		return

	if (twoDmarkPlots and scalle) or (twoDmarkPlots and Xcheck):
		raise Exception("'twoDmarkPlots' only allowed without 'scalle' and 'Xcheck'")

	folderAddString = ""
	if scalle:
		folderAddString += "_scale"
	if Xcheck:
		folderAddString += "_Xcheck"
	if globalScale:
		folderAddString += "_global"



#	folder = "./ellipseComparisons/"
	folder = "./forPaper"+folderAddString+"/"

	if setRanges:
		folder = "./exoticFitPlots_ranges/"


	intensYlimFileName   = "./intensYlims"
	arangdLimitsFileName = "./argandLims"
	if scalle:
		intensYlimFileName   += "_scale"
		arangdLimitsFileName += "_scale"

	intensScales = loadLimits(intensYlimFileName, tBin)
	argandScales = loadLimits(arangdLimitsFileName, tBin)

	if globalScale:
		globalScales = {
					0: ( [9808549.03133*.9] ,[ -1176.89018363 , 2583.08091376 , -963.530201342 , 2764.05317273 ]), 
					1: ( [6250000.00   ] ,[ -1000. , 2311.5523738 , -950. , 2400. ]),
#					1: ( [15692071.5541] ,[ -2953.09588149 , 2311.5523738 , -1069.36767067 , 3461.97833088 ]),
					2: ( [5984192.64568*13.5/15.] ,[ -1000.84212555 , 1893.32841381 , -652.0 , 2498.12259086 ]),
					3: ( [3693705.14722*16.5/18.5] ,[ -1259.93088183 , 1277.85363449 , -404.005733504 , 1956.63757019 ])}
		for i in range(startBin, stopBin):
			intensScales[i] = globalScales[tBin][0]
			argandScales[i] = globalScales[tBin][1]

	fileSectorName = "1mp1p1mmP"
	if setRanges:
		fileSectorName += rangeString

	fullRanges.nonShapeParameters = fixedShapes.nonShapeParameters

	totalsAndNevents = getTotalAndNevents()

	for s, sect in enumerate(fullRanges.sectors):
		fullRanges.removeZeroModeFromComa()
#		rv = fullRanges.produceResultViewer(cloneZeros(zeroModeParameters),s, noRun = True, plotTheory = True)
		rv = fullRanges.produceResultViewer(zeroModeParameters,s, noRun = True, plotTheory = True)
		if writeROOT:
			rv.writeToRootFile(fileSectorName+".root")
			return 

#		rv.writeToRootFile("exoticForRealease_"+str(tBin)+".root")

		rv.checkArgandRanges = False

		rv.intYaxisXpos = -0.15
		rv.argYaxisXpos = -0.145

		rv.intensLims = intensScales
		rv.argandLims = argandScales

		rv.arrowsToTheo = [14]

		rv.titleFontSize = 11
		rv.showColorBar  = True
		rv.XcheckArgand  = Xcheck
		rv.writeBinToPdf(startBin, stdCmd = [ fileSectorName + "_2D_t"+str(tBin)+".pdf", "", [], "", []])

#		continue

		if twoDmarkPlots:
			rv.mark2DplotColor = modernplotting.colors.colorScheme.red

		rv.labelPoints     = [0,10,15,20]
		if tBin in [0,1,2] and not scalle:
			rv.labelPoints     = [10,15,20]
		rv.labelPoints     = []
		rv.makeLegend      = True
		if scalle:
			rv.scaleTo = "maxCorrData"
			rv.yAxisShift      = 300.
			rv.tStringYpos     = 0.8 # 0.8, if third legend item 
			rv.topMarginIntens = 1.4
			fakkkk             = 1.
		else:
			rv.plotData        = False
			fakkkk             = .7	
			rv.tStringYpos     = 0.87 # 0.8, if third legend item 
			rv.topMarginIntens = 1.4
			rv.yAxisShift      = 100.
#			rv.scaleArgandZeroLine = 0.8

		if twoDmarkPlots:
			rv.tStringYpos = 0.94

		if Xcheck:
			rv.tStringYpos     = 0.8 # 0.8, if third legend item 

		rv.addiColor     = modernplotting.colors.makeColorLighter(modernplotting.colors.colorScheme.blue, .5)
		rv.realLabel     = LaTeX_strings.realReleaseNote
		rv.imagLabel     = LaTeX_strings.imagReleaseNote
		rv.m2PiString    = LaTeX_strings.m2PiReleaseNote
		rv.intensLabel   = LaTeX_strings.intensReleaseNote
		if not Xcheck:
			rv.printLiminary = True
		else:
			rv.connectAddGraphs = [(0,1),(2,3)]
		rv.xLims = (.2,2.2)
		if tBin == 3:
			if scalle:
				rv.shiftMap      = {0:(fakkkk*80.,fakkkk*-280.),10:(fakkkk*-360.,fakkkk*-50.), 15:(fakkkk*-390.,fakkkk*-30.), 20:(fakkkk*-500.,fakkkk*-10.)}
			else:
				rv.shiftMap      = {0:(fakkkk*100.,fakkkk*-280.),10:(fakkkk*-370.,fakkkk*-50.), 15:(fakkkk*-370.,fakkkk*-30.), 20:(fakkkk*-50.,fakkkk*90.)}
		if tBin == 2:
			if scalle:
				rv.shiftMap      = {0:(fakkkk*50.,fakkkk*-300.),10:(fakkkk*-480.,fakkkk*-50.), 15:(fakkkk*-500.,fakkkk*-30.), 20:(fakkkk*0.,fakkkk*70.)}
			else:
				rv.shiftMap      = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-420.,fakkkk*-50.), 15:(fakkkk*-450.,fakkkk*-30.), 20:(fakkkk*0.,fakkkk*70.)}
		if tBin == 1:
			if scalle:
				rv.shiftMap      = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-300.,fakkkk*-50.), 15:(fakkkk*-400.,fakkkk*-30.), 20:(fakkkk*60.,fakkkk*30.)}
			else:
				rv.shiftMap      = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-350.,fakkkk*-50.), 15:(fakkkk*-400.,fakkkk*-30.), 20:(fakkkk*80.,fakkkk*30.)}
		if tBin == 0:
			if scalle:
				rv.shiftMap      = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-450.,fakkkk*-50.), 15:(fakkkk*-450.,fakkkk*-30.), 20:(fakkkk*50.,fakkkk*30.)}
			else:
				rv.shiftMap      = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-410.,fakkkk*-50.), 15:(fakkkk*-420.,fakkkk*-30.), 20:(fakkkk*70.,fakkkk*30.)}

		if not twoDmarkPlots:
			rv.scale(1000./40.)

		rv.writeBinToPdf(startBin, stdCmd = [folder + fileSectorName + "_2D_t"+str(tBin)+".pdf","", [], "",[]])
		for b in range(startBin, stopBin):
#			intensNames = [name+".intens" for name in fileNames[sect,b]]
#			argandNames = [name+".argand" for name in fileNames[sect,b]]

			print "Writing bin",b

			rv.rightString  = "{:.1f}\%".format(100*totalsAndNevents[(tBin, b)][0]/totalsAndNevents[(tBin, b)][1])
			if not scalle:
				intensNames = []
				argandNames = []
#			intensNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/singlePlots/1mp1p1mm_t"+str(tBin)+".intens"]
#			argandNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/singlePlots/1mp1p1mm_t"+str(tBin)+".argand"]

			intensNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/zeroModeFitter_2D/filesForRelease/fullRangeFixing_"+str(tBin)+".intens"]
			argandNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/zeroModeFitter_2D/filesForRelease/fullRangeFixing_"+str(tBin)+".argand"]

			intensNames = []
			argandNames = []

			if Xcheck:
				intensNames    = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/singlePlots/intensPlots/1mp1p1mm_m"+str(b)+"_t"+str(tBin)+".intens"]
				argandBaseName = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/singlePlots/dimasEllipses/1mp1p1mm_"+str(b)+"_"+str(tBin)+"_<ndx>.argand"
				argandNames    = [argandBaseName.replace("<ndx>", ndx) for ndx in ['0','1','2','3','C']]

#			print argandNames
#			return

			for fn in intensNames:
				if not os.path.isfile(fn):
					raise IOError("'"+fn+"' does not exist")
			for fn in argandNames:
				if not os.path.isfile(fn):
					raise IOError("'"+fn+"' does not exist")

#			rv.writeAmplFiles(b, fileName = "./filesForRelease/fullRangeFixing_"+str(tBin))

			rv.legendMethods    = "Full range"
			rv.connectCorrPoints = range(70)
			rv.markRange = (10,15)
			if Xcheck:
				rv.addiXoffset      = 0.01
				rv.addiColor        = modernplotting.colors.colorScheme.red
				rv.legendMethods    = "X-check"

			if twoDmarkPlots:
				twoDplotName = folder +  fileSectorName + "_2D_m"+str(b)+"_t"+str(tBin)+".pdf"
				intPlotName  = ""
				argPlotName  = ""
			else:
				twoDplotName = ""
				intPlotName  = folder +  fileSectorName + "_int_m"+str(b)+"_t"+str(tBin)+".pdf"
				argPlotName  = folder+  fileSectorName + "_arg_m"+str(b)+"_t"+str(tBin)+".pdf"

				

#			rv.tString          = ""
#			rv.scaleFakk        = 1000.
#			rv.writeBinToPdf(b, stdCmd = ["","",[], folder+  sect + "_data_argand_"+str(b)+"_"+str(tBin)+".pdf", argandNames])
			rv.writeBinToPdf(b, stdCmd = [twoDplotName, intPlotName, intensNames, argPlotName, argandNames])
#			rv.wiriteReImToPdf(b, sect + "_data_<ri>_"+str(b)+"_"+str(tBin)+".pdf")
	print tBin,':','([',str(rv.InMax),'],[',str(rv.reMin),',',str(rv.reMax),',',str(rv.imMin),',',str(rv.imMax),'])'

	return

	with root_open("1mp1p_totals_t"+str(tBin)+".root", "RECREATE"):
		hists = fullRanges.makeTheoryTotals()
		for tb in hists:
			for h in tb:
				h.Write()
		totalHists = fixedShapes.getTotalHists(zeroModeParameters)
		for tb in totalHists:
			for h in tb:
				h.Write()
	return
Exemplo n.º 15
0
def main(rhoFileName=""):
    checkLaTeX()

    freeMap, freeString = parseCmdLine(sys.argv)

    inFileName = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/ppppppppp/DdecayResults_" + freeString + "_" + getBranchFileEnding(
    ) + ".root"

    zeroFileName = inFileName

    sectors = []
    allSectors = [
        "KpiSright", "KpiPright", "KpiDright", "KpiSwrong", "KpiPwrong",
        "KpiDwrong", "piPiS", "piPiP", "piPiD"
    ]

    fixMap = [False, False, False, False, False, False, False, False, False]

    for i in range(9):
        if freeString[i] == '1':
            if not fixMap[i]:
                sectors.append(allSectors[i])

#	sectors = sectors[:1]

    sectorRangeMap = {}

    tBin = 0
    startBin = 34
    stopBin = 35

    modelMode = "simpleBW_Dp"
    if modelMode == "simpleBW_Dp":

        Kmass = ptc.parameter(1.414, "KMass")
        Kwidth = ptc.parameter(.232, "KWidth")
        Kmass.lock = True
        Kwidth.lock = True
        Kstar = ptc.breitWigner([Kmass, Kwidth])

        K892Mass = ptc.parameter(.89166, "K892Mass")
        K892Width = ptc.parameter(.0508, "K902Width")
        K892Mass.lock = True
        K892Width.lock = True
        K892 = ptc.breitWigner([K892Mass, K892Width])

        f0Mass = ptc.parameter(.98, "f0Mass")
        f0Width = ptc.parameter(.1, "f0Width")
        f0Mass.lock = True
        f0Width.lock = True
        f0 = ptc.breitWigner([f0Mass, f0Width])

        rhoMass = ptc.parameter(.77526, "rhoMass")
        rhoWidth = ptc.parameter(.1478, "rhoWidth")
        rhoMass.lock = True
        rhoWidth.lock = True
        rho = ptc.breitWigner([rhoMass, rhoWidth])

        f2Mass = ptc.parameter(1.2751, "f2Mass")
        f2Width = ptc.parameter(.1851, "f2Width")
        f2Mass.lock = True
        f2Width.lock = True
        f2 = ptc.breitWigner([f2Mass, f2Width])

        waveModel = {
            "KpiSright": [Kstar],
            "KpiPright": [K892],
            "KpiSwrong": [Kstar],
            "KpiPwrong": [K892],
            "piPiS": [f0],
            "piPiP": [rho],
            "piPiD": [f2]
        }

    uniCOMA = False
    with root_open(inFileName, "READ") as inFile:
        histNames = GetKeyNames(inFile)
        histListReal = []
        histListImag = []
        histListNorm = []
        histListIndx = []
        nAmplMax = 0
        for sector in sectors:
            realHistName = sector + "_" + str(tBin) + "_real"
            histReal = inFile.Get(realHistName)
            if not histReal:
                raise IOError("Could not get '" + realHistName + "' from '" +
                              inFileName + "'")
            histReal.SetDirectory(0)
            histListReal.append(histReal)

            imagHistName = sector + "_" + str(tBin) + "_imag"
            histImag = inFile.Get(imagHistName)
            if not histImag:
                raise IOError("Could not get '" + imagHistName + "' from '" +
                              inFileName + "'")
            histImag.SetDirectory(0)
            histListImag.append(histImag)

            normHistName = sector + "_" + str(tBin) + "_norm"
            histNorm = inFile.Get(normHistName)
            if not histNorm:
                raise IOError("Could not get '" + normHistName + "' from '" +
                              inFileName + "'")
            histNorm.SetDirectory(0)
            histListNorm.append(histNorm)

            indexHistName = sector + "_" + str(tBin) + "_index"
            histIndx = inFile.Get(indexHistName)
            if not histIndx:
                raise IOError("Could not get '" + indexHistName + "' from '" +
                              inFileName + "'")
            histIndx.SetDirectory(0)
            nAmplMax = max(nAmplMax, int(2 * histIndx.GetMaximum()))
            histListIndx.append(histIndx)
        histsToFill = []
        comaHists = []
        intHistsReal = []
        intHistsImag = []
        for mBin in range(startBin, stopBin):
            comaHistName = "COMA_" + str(tBin) + "_" + str(mBin)
            comaHist = inFile.Get(comaHistName)
            if not comaHist:
                raise IOError("Could not load '" + comaHistName + "'")

            comaHist.SetDirectory(0)
            comaHists.append(comaHist)

        ab = allBins(startBin, stopBin, histListReal, histListImag,
                     histListNorm, histListIndx, comaHists, intHistsReal,
                     intHistsImag)

    with root_open(zeroFileName, "READ") as inFile:
        zeroCount = 0
        zeroHistList = []
        eigenHistList = []
        while True:
            zeroName = "zero" + str(zeroCount) + "_" + str(tBin)
            eigenName = "eigen" + str(zeroCount) + "_" + str(tBin)
            zeroHist = inFile.Get(zeroName)
            if not zeroHist:
                break
            zeroHist.SetDirectory(0)
            print "Adding zero-mode"
            zeroCount += 1
            if not zeroForSectors(sectors, zeroHist.GetTitle()):
                continue
            zeroHistList.append(zeroHist)

            eigenHist = inFile.Get(eigenName)
            eigenHist.SetDirectory(0)
            if eigenHist:
                eigenHistList.append(eigenHist)
        if (not len(eigenHistList) == 0) and (not len(eigenHistList)
                                              == len(zeroHistList)):
            raise ValueError(
                "Number of eigenvalue histograms does not match, but is also nonzero"
            )
        removeCertainZeroModes(zeroHistList, eigenHistList)
        for zeroHist in zeroHistList:
            borders = getZeroHistBorders(zeroHist)
            ab.addZeroMode(borders, zeroHist)

        rotateToFourPPampls = False
        if rotateToFourPPampls:
            fourPPampls = loadAmplsTM(fourPPamplFileName)
            ab.removePhases(fourPPampls[tBin][startBin:stopBin])

#		ab.rotateToPhaseOfBin(10)
        zeroModeComaVal = 100.  #float(sys.argv[1])
        #		zeroModeComaVal = 100000.
        #		zeroModeComaVal = "unchanged"
        #		ab.removeZeroModeFromComa()
        #		ab.addComaValueForZeroMode(zeroModeComaVal)
        #		ab.removeGlobalPhaseFromComa()
        ab.unifyComa()

        ab.initChi2(waveModel)
        ab.setMassRanges(sectorRangeMap)
        totalPars = []
        for k in waveModel:
            for f in waveModel[k]:
                totalPars += f.getParameters()
        shapePars = []
        if not len(totalPars) == 0 and fitShape:
            res = scipy.optimize.minimize(ab.chi2, totalPars)
            hi = res.hess_inv
            print "m0 = ", res.x[0], "+-", (2 * hi[0, 0])**.5
            print "G0 = ", res.x[1], "+-", (2 * hi[1, 1])**.5
            print "Giving a Chi2 of:", res.fun
            shapePars = res.x

        chi2, params = ab.chi2(shapePars, returnParameters=True)
        errs = ab.getNonShapeUncertainties(shapePars)
        paramsZ = ab.linearizeZeroModeParameters(params)
        zmPar = ab.getNonShapeParameters()
        ab.setTheoryFromOwnFunctions(params, True)

        intenses = []
        reals = []
        imags = []
        correl = []
        phases = []
        intensD = []
        realsD = []
        imagsD = []
        phasesD = []
        intensT = []
        realsT = []
        imagsT = []
        phasesT = []

        for rh in histListReal:
            Ih = rh.Clone()
            Ih.Reset()
            intenses.append(Ih)

            realH = rh.Clone()
            realH.Reset()
            reals.append(realH)

            imagH = rh.Clone()
            imagH.Reset()
            imags.append(imagH)

            reImCorrH = rh.Clone()
            reImCorrH.Reset()
            correl.append(reImCorrH)

            phaseH = rh.Clone()
            phaseH.Reset()
            phases.append(phaseH)

            ID = rh.Clone()
            ID.Reset()
            intensD.append(ID)

            rD = rh.Clone()
            rD.Reset()
            realsD.append(rD)

            iD = rh.Clone()
            iD.Reset()
            imagsD.append(iD)

            pD = rh.Clone()
            pD.Reset()
            phasesD.append(pD)

            IT = rh.Clone()
            IT.Reset()
            intensT.append(IT)

            rT = rh.Clone()
            rT.Reset()
            realsT.append(rT)

            iT = rh.Clone()
            iT.Reset()
            imagsT.append(iT)

            pT = rh.Clone()
            pT.Reset()
            phasesT.append(pT)

        zeroP = [0.] * len(paramsZ)
        #		paramsZ = zeroP

        ab.fillHistograms(paramsZ, intenses)
        ab.fillHistograms(paramsZ, reals, mode=REAL)
        ab.fillHistograms(paramsZ, imags, mode=IMAG)
        ab.fillHistograms(paramsZ, phases, mode=PHASE)
        ab.fillHistograms(paramsZ, correl, mode=REIMCORRELATION)

        ab.fillHistograms(zeroP, intensD)
        ab.fillHistograms(zeroP, realsD, mode=REAL)
        ab.fillHistograms(zeroP, imagsD, mode=IMAG)
        ab.fillHistograms(zeroP, phasesD, mode=PHASE)

        ab.fillHistograms(zeroP, intensT, mode=INTENSTHEO)
        ab.fillHistograms(zeroP, realsT, mode=REALTHEO)
        ab.fillHistograms(zeroP, imagsT, mode=IMAGTHEO)
        ab.fillHistograms(zeroP, phasesT, mode=PHASETHEO)

        for i in range(len(histListReal)):
            renormToBinWidth(intenses[i])
            renormToBinWidth(intensD[i])
            renormToBinWidth(intensT[i])
            renormToBinWidth(reals[i], .5)
            renormToBinWidth(realsD[i], .5)
            renormToBinWidth(realsT[i], .5)
            renormToBinWidth(imags[i], .5)
            renormToBinWidth(imagsD[i], .5)
            renormToBinWidth(imagsT[i], .5)
            renormToBinWidth(correl[i], )
            allIsZero = True
            for binX in range(intensT[i].GetNbinsX()):
                for binY in range(intensT[i].GetNbinsY()):
                    if not intensT[i].GetBinContent(binX + 1, binY + 1) == 0.:
                        allIsZero = False
                        break
                if not allIsZero:
                    break  # # # # # # # # # # # # # # # # #
            ric = correl[i]

            noRun = False
            if not allIsZero:
                rv = resultViewer([intenses[i], intensD[i], intensT[i]],
                                  [reals[i], realsD[i], realsT[i]],
                                  [imags[i], imagsD[i], imagsT[i]],
                                  [phases[i], phasesD[i], phasesT[i]],
                                  startBin=startBin,
                                  reImCorrel=ric,
                                  noRun=noRun)
            else:
                rv = resultViewer([intenses[i], intensD[i]],
                                  [reals[i], realsD[i]], [imags[i], imagsD[i]],
                                  [phases[i], phasesD[i]],
                                  startBin=startBin,
                                  reImCorrel=ric,
                                  noRun=noRun)
            rv.titleRight = getProperWaveName(sectors[i])
            rv.tString = getProperDataSet(inFileName, tBin)
            rv.titleFontSize = 11
            rv.overrideMassString = ""

            rv.printLiminary = False
            rv.topMarginIntens = 1.4
            rv.run()
Exemplo n.º 16
0
def main():
    checkLaTeX()
    style = modernplotting.mpplot.PlotterStyle()
    #	style.p2dColorMap = 'ocean_r'
    #	style.p2dColorMap = 'YlOrRd'
    style.p2dColorMap = 'Reds'

    referenceWave = globalReferenceWave

    tBin = int(sys.argv[1])

    if tBin < 0 or tBin > 3:
        raise ValueError("Invalid t' bin: " + str(tBin))

    sect = sys.argv[2]
    if not sect in [
            '1++1+', '2-+1+', '2-+1+2++', '2-+1+2++', '2++1+', '2++1+2++',
            '4++1+1--', '4++1+2++', '3++0+', "4-+0+", "6-+0+"
    ]:
        raise RuntimeError("Invalid sector '" + sect + "'")

    if len(sys.argv) > 3:
        study = sys.argv[3]
        studyAdder = "_" + study
    else:
        study = "std11"
        studyAdder = ""
    print "Study: " + study

    #	sect = '1++1+'
    #	sect = '2-+1+'
    #	sect = '2++1+'
    startBin = 11
    stopBin = 50
    isRho = True
    sectorRangeMap = {}
    isobName = "rho"

    restrictRhoRange = True
    rhoRange = 1.2

    if sect == '1++1+':
        sector = "1++1+[pi,pi]1--PiS"
        if restrictRhoRange:
            sectorRangeMap = {"1++1+[pi,pi]1--PiS": (0., rhoRange)}

        L = 0
    if sect == '2-+1+':
        sector = "2-+1+[pi,pi]1--PiP"
        L = 1
        if restrictRhoRange:
            sectorRangeMap = {"2-+1+[pi,pi]1--PiP": (0., rhoRange)}

    if sect == '2-+1+2++':
        sector = "2-+1+[pi,pi]2++PiS"
        L = 0
        isRho = False
        #		startBin = 22
        isobName = "f2"
    if sect == '2++1+':
        sector = "2++1+[pi,pi]1--PiD"
        L = 2
        if restrictRhoRange:
            sectorRangeMap = {"2++1+[pi,pi]1--PiD": (0., rhoRange)}

    if sect == "2++1+2++":
        sector = "2++1+[pi,pi]2++PiP"
        L = 1
        stRtBin = 22
        isRho = False
        isobName = "f2"
    if sect == '4++1+1--':
        sector = '4++1+[pi,pi]1--PiG'
        L = 4
        if restrictRhoRange:
            sectorRangeMap = {'4++1+[pi,pi]1--PiG': (0., rhoRange)}

    if sect == '4++1+2++':
        sector = '4++1+[pi,pi]2++PiF'
        L = 3
        isRho = False
        #		startBin = 22
        isobName = "f2"
    if sect == "3++0+":
        sector = "3++0+[pi,pi]2++PiP"
        L = 1
        isRho = False
        #		startBin = 22
        isobName = "f2"
    if sect == "4-+0+":
        sector = "4-+0+[pi,pi]1--PiF"
        referenceWave = "6-+0+rhoPiH"
        if restrictRhoRange:
            sectorRangeMap = {"4-+0+[pi,pi]1--PiF": (0., rhoRange)}

        L = 3
    if sect == "6-+0+":
        sector = "6-+0+[pi,pi]1--PiH"
        L = 5
        if restrictRhoRange:
            sectorRangeMap = {"6-+0+[pi,pi]1--PiH": (0., rhoRange)}

    inFileName = fileNameMap[study]
    #	phaseFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/ampls_4++1+rhoPiG.dat"
    phaseFileName = ""

    tBins = [tBin]

    allMethods = {}
    methodStrings = {}
    shortlabels = {
        "fixedShapeF0": r"$\text{fix}_{f_0}^{~}$",
        "fixedShapeRho": r"$\text{fix}_\rho^{~}$",
        "fixedShapeRho1G": r"$\text{fix}_\rho^{1\Gamma}$",
        "fixedShapeRho2G": r"$\text{fix}_\rho^{2\Gamma}$",
        "fixedShapes": r"$\text{fix}_\text{all}^{~}$",
        "pipiS": r"$\phi_{[\pi\pi]_S}^{~}$",
        "fitRho": r"$\text{fit}_\rho^{~}$",
        "fitRho1G": r"$\text{fit}_\rho^{1\Gamma}$",
        "fitRho2G": r"$\text{fit}_\rho^{2\Gamma}$",
        "smooth": r"smooth"
    }

    if isRho:
        print "Fit is rho"
        globalFileName = "rhoMassesAndWidths_" + sect
        if restrictRhoRange:
            globalFileName += "_range" + str(rhoRange)
        globalFileName += "_global.dat"

        model = getRhoModel(inFileName,
                            sector,
                            startBin,
                            stopBin,
                            tBins,
                            sectorRangeMap,
                            L=L,
                            writeResultToFile=globalFileName,
                            referenceWave=referenceWave,
                            loadIntegrals=True)
    else:
        print "Fit is f2"
        model = getF2Model(inFileName,
                           sector,
                           startBin,
                           stopBin,
                           tBins,
                           sectorRangeMap,
                           L=L,
                           writeResultToFile="f2MassesAndWidths_" + sect +
                           "_global.dat",
                           referenceWave=referenceWave,
                           loadIntegrals=True)


##### Writing starts here
    print "From", startBin, 'to', stopBin

    parameterDummy = [[] * (stopBin - startBin)]
    if isRho:
        outFileName = "./rhoMassesAndWidths"
    else:
        outFileName = "./f2MassesAndWidths"
    if restrictRhoRange:
        outFileName += "_range" + str(rhoRange)

    doResonanceFits = True
    binWiseFit = True
    if doResonanceFits:
        with open(outFileName + '_' + sect + "_" + str(tBin) + ".dat",
                  'w') as outFile:
            if binWiseFit:
                bins = range(stopBin - startBin)
            else:
                bins = [1]
            for i in bins:
                binIndex = i + startBin
                outFile.write(
                    str(binIndex) + ' ' + str(0.52 + 0.04 * binIndex) + ' ')
                startValueOffset = 0.00
                exceptCount = 0
                while True:
                    try:
                        #					if True:
                        if binWiseFit:
                            fitRange = [i]
                        else:
                            fitRange = range(stopBin - startBin)
                        if isRho:
                            startVals = [
                                mRho + startValueOffset,
                                Grho + startValueOffset
                            ]
                        else:
                            startVals = [
                                mF2 + startValueOffset, GF2 + startValueOffset
                            ]
                        x, err, c2, ndf = model.fitShapeParametersForBinRange(
                            startVals, [0],
                            fitRange,
                            zeroModeParameters=parameterDummy)
                        break
                    except:
                        print "Fitter exception encountered"
                        startValueOffset += 0.001
                        exceptCount += 1
                        if exceptCount > 3:
                            raise Exception("Too many failed attempts: " +
                                            str(exceptCount))
                if sect == "3++0+":
                    with open("3pp_f2_cpls_" + str(tBin) + ".dat",
                              'w') as outFileCpl:
                        model.calculateNonShapeParameters()
                        cpl, hess = model.getCouplingParameters()
                        outFileCpl.write(str(cpl))
                        outFileCpl.write("\n")
                        outFileCpl.write(str(hess))
                nBin = startBin + i
                if nBin in []:
                    model.calculateNonShapeParameters()
                    folder = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/zeroModeFitter_2D/rhoShapes4pp"
                    rv = model.produceResultViewer(parameterDummy,
                                                   sector,
                                                   noRun=True,
                                                   plotTheory=True)
                    rv.writeBinToPdf(
                        nBin,
                        stdCmd=[
                            "", folder + "/" + isobName + "Shape_" + sector +
                            "_intens_" + str(nBin) + "_" + str(tBin) + ".pdf",
                            [], folder + "/" + isobName + "Shape_" + sector +
                            "_argand_" + str(nBin) + "_" + str(tBin) + ".pdf",
                            []
                        ])
                outFile.write(
                    str(x[0]) + ' ' + str(err[0]) + ' ' + str(x[1]) + ' ' +
                    str(err[1]))
                outFile.write(' ' + str(c2 / ndf) + '\n')
        return

    fileNames = {}

    for stu in allMethods:
        print "Writing for '" + stu + "'"
        for s, sect in enumerate(allMethods[stu].sectors):
            if stu == "pipiS":
                rv = allMethods[stu].produceResultViewer(
                    allMethods[stu].getZeroModeParametersForMode(),
                    s,
                    plotTheory=True)
                rv.run()
            rv = allMethods[stu].produceResultViewer(
                allMethods[stu].getZeroModeParametersForMode(), s, noRun=True)
            for bin in range(startBin, stopBin):
                fileName = "./collectedMethods/" + stu + "_" + sect + "_0mpData_" + str(
                    bin) + studyAdder
                if not (sect, bin) in fileNames:
                    fileNames[sect, bin] = []
                fileNames[sect, bin].append(fileName)
                rv.writeAmplFiles(bin, fileName=fileName)

    makeTotals = False
    if makeTotals:
        model.calculateNonShapeParameters()
        totalHists = model.getTotalHists(model.getZeroModeParametersForMode())

        with root_open("./totals_2mp1p" + studyAdder + ".root",
                       "UPDATE") as out:
            for t in totalHists:
                for m in t:
                    m.Write()

    folder = "./comparisonResultsData" + studyAdder + "/"
    for s, sect in enumerate(model.sectors):
        model.removeZeroModeFromComa()
        model.removeGlobalPhaseFromComa()
        zeroParDummy = [[] * (stopBin - startBin)]
        model.calculateNonShapeParameters()
        rv = model.produceResultViewer(zeroParDummy,
                                       s,
                                       noRun=True,
                                       plotTheory=True)
        rv.plotData = False
        rv.writeBinToPdf(startBin,
                         stdCmd=[
                             folder + sect + "_data_2D_" + str(tBin) + ".pdf",
                             "", [], "", []
                         ])
        for b in range(startBin, stopBin):
            #			intensNames = [name+".intens" for name in fileNames[sect,b]]
            #			argandNames = [name+".argand" for name in fileNames[sect,b]]
            intensNames = []
            argandNames = []
            rv.writeBinToPdf(b,
                             stdCmd=[
                                 "", folder + sect + "_data_intens_" + str(b) +
                                 "_" + str(tBin) + ".pdf", intensNames,
                                 folder + sect + "_data_argand_" + str(b) +
                                 "_" + str(tBin) + ".pdf", argandNames
                             ])