def doFitRho(inFileName, sectors, startBin, stopBin, tBins, sectorRangeMap = {}, referenceWave = "", writeResultToFile = None, acv = None, polDeg = None):
	rhoMass  = ptc.parameter( mRho, "rhoMass" )
	rhoWidth = ptc.parameter( Grho , "rhoWidth")
	rho      = ptc.relativisticBreitWigner([rhoMass,rhoWidth], mPi, mPi, mPi, 1, 1, False)
	model    = [rho]
	if polDeg is not None:
		params = []
		sVal = 1.
		for i in range(polDeg):
			params.append(ptc.parameter( sVal, "c"+str(i+1)+"_re" ))
			sVal = 0. # Make the start value to constant 1
			params.append(ptc.parameter( 0., "c"+str(i+1)+"_im" ))
		polynome = ptc.complexPolynomial(polDeg,params)
		model.append(polynome)

	fitRho = amplitudeAnalysis(inFileName, sectors, {"1-+1+[pi,pi]1--PiP":model}, startBin, stopBin, tBins, sectorRangeMap = sectorRangeMap)
	fitRho.loadData(loadIntegrals = True, referenceWave = referenceWave)
	fitRho.finishModelSetup()
	fitRho.fitShapeParameters()
	fitRho.calculateNonShapeParameters()
	fitRho.mode = AMPL
#	fitRho.removeGlobalPhaseFromComa()
	if writeResultToFile:
		with open(writeResultToFile, 'a') as outFile:
			if len(tBins) > 1:
				raise ValueError("More than one t' bin not supported")
			resultString = str(tBins[0])+ " 666. " + str(rhoMass.value) + ' ' + str(rhoMass.error) + ' ' + str(rhoWidth.value) + ' ' + str(rhoWidth.error) + "\n"
			outFile.write(resultString)
	return fitRho
Example #2
0
def getRhoModel(inFileName,
                sector,
                startBin,
                stopBin,
                tBins,
                sectorRangeMap,
                L,
                referenceWave="",
                writeResultToFile=None,
                loadIntegrals=False):
    rhoMass = ptc.parameter(mRho - .1, "rhoMass")
    rhoWidth = ptc.parameter(Grho + .1, "rhoWidth")
    rho = ptc.relativisticBreitWigner([rhoMass, rhoWidth], mPi, mPi, mPi, 1, L,
                                      False)
    fitRho = amplitudeAnalysis(inFileName, [sector], {sector: [rho]},
                               startBin,
                               stopBin,
                               tBins,
                               sectorRangeMap=sectorRangeMap)
    fitRho.loadData(referenceWave=referenceWave, loadIntegrals=loadIntegrals)
    fitRho.finishModelSetup()
    fitRho.fitShapeParameters()
    fitRho.mode = AMPL
    if writeResultToFile:
        with open(writeResultToFile, 'a') as outFile:
            if len(tBins) > 1:
                raise ValueError("More than one t' bin not supported")
            resultString = str(tBins[0]) + " 666. " + str(
                rhoMass.value) + ' ' + str(rhoMass.error) + ' ' + str(
                    rhoWidth.value) + ' ' + str(rhoWidth.error) + "\n"
            outFile.write(resultString)
    return fitRho
Example #3
0
def getF2Model(inFileName,
               sector,
               startBin,
               stopBin,
               tBins,
               sectorRangeMap,
               L,
               referenceWave="",
               writeResultToFile=None,
               loadIntegrals=False):
    print 'sector', sector, 'has L =', L
    f2Mass = ptc.parameter(mF2, "f2Mass")
    f2Width = ptc.parameter(GF2, "f2Width")
    f2 = ptc.relativisticBreitWigner([f2Mass, f2Width], mPi, mPi, mPi, 2, L,
                                     False)
    fitF2 = amplitudeAnalysis(inFileName, [sector], {sector: [f2]},
                              startBin,
                              stopBin,
                              tBins,
                              sectorRangeMap=sectorRangeMap)
    fitF2.loadData(referenceWave=referenceWave, loadIntegrals=loadIntegrals)
    fitF2.finishModelSetup()
    fitF2.fitShapeParameters()
    fitF2.mode = AMPL
    if writeResultToFile:
        with open(writeResultToFile, 'a') as outFile:
            if len(tBins) > 1:
                raise ValueError("More than one t' bin not supported")
            resultString = str(tBins[0]) + " 666. " + str(
                f2Mass.value) + ' ' + str(f2Mass.error) + ' ' + str(
                    f2Width.value) + ' ' + str(f2Width.error) + "\n"
            outFile.write(resultString)
    return fitF2
Example #4
0
def doFitRho(inFileName,
             zeroFileName,
             sectors,
             startBin,
             stopBin,
             tBins,
             sectorRangeMap={},
             referenceWave=""):
    rhoMass = ptc.parameter(mRho, "rhoMass")
    rhoWidth = ptc.parameter(Grho, "rhoWidth")
    rho = ptc.relativisticBreitWigner([rhoMass, rhoWidth], mPi, mPi, mPi, 1, 1,
                                      False)
    fitRho = amplitudeAnalysis(inFileName,
                               sectors, {"2++1+[pi,pi]1--PiD": [rho]},
                               startBin,
                               stopBin,
                               tBins,
                               sectorRangeMap=sectorRangeMap,
                               zeroFileName=zeroFileName)
    fitRho.loadData(referenceWave=referenceWave)
    fitRho.finishModelSetup()
    fitRho.fitShapeParameters()
    fitRho.calculateNonShapeParameters()
    fitRho.mode = AMPL
    #	fitRho.removeGlobalPhaseFromComa()
    return fitRho
def doFitRho(inFileName,
             sectors,
             startBin,
             stopBin,
             tBins,
             sectorRangeMap={},
             referenceWave=""):
    rhoMass = ptc.parameter(mRho, "rhoMass")
    rhoWidth = ptc.parameter(Grho, "rhoWidth")
    binning = [
        0.278, 0.32, 0.36, 0.4, 0.44, 0.48, 0.52, 0.56, 0.6, 0.64, 0.68, 0.7,
        0.72, 0.74, 0.76, 0.78, 0.8, 0.82, 0.84, 0.86, 0.88, 0.9, 0.92, 0.96,
        1.0, 1.04, 1.08, 1.12, 1.16, 1.2, 1.24, 1.28, 1.32, 1.36, 1.4, 1.44,
        1.48, 1.52, 1.56, 1.6, 1.64, 1.68, 1.72, 1.76, 1.8, 1.84, 1.88, 1.92,
        1.96, 2.0, 2.04, 2.08, 2.12, 2.16, 2.2, 2.24, 2.28
    ]

    rho = ptc.relativisticBreitWigner([rhoMass, rhoWidth], mPi, mPi, mPi, 1, 1,
                                      False)
    #	rho = ptc.integratedRelativisticBreitWigner([rhoMass,rhoWidth], mPi, mPi, mPi, 1, 1, binning, intensWeight = False, fitPr = False, reweightInverseBW = True)
    fitRho = amplitudeAnalysis(inFileName,
                               sectors, {"0-+0+[pi,pi]1--PiP": [rho]},
                               startBin,
                               stopBin,
                               tBins,
                               sectorRangeMap=sectorRangeMap)
    fitRho.loadData(referenceWave=referenceWave)
    fitRho.finishModelSetup()
    fitRho.fitShapeParameters()
    fitRho.calculateNonShapeParameters()
    fitRho.mode = AMPL
    #	fitRho.removeGlobalPhaseFromComa()
    #	fitRho.removeZeroModeFromComa()
    return fitRho
def doF0Fit(inFileName, sectors, startBin, stopBin, tBins, sectorRangeMap = {}, referenceWave = "", deg = 0, writeResultToFile = None):
	fixedAMPD_sub = pc.fixedParameterization("/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/zeroModes/bwAmplitudes_noBF/amp_1pp0pSigmaPiP")	
	f0Mass   = ptc.parameter(mF0,"f0Mass")
	f0g1     = ptc.parameter(g1, "g1")
	f0g2     = ptc.parameter(g2, "g2")
#	f0g1.lock = True
#	f0g2.lock = True
	f0       = ptc.flatte([f0Mass, f0g1, f0g2], mPi, mPi, mPi, mK, mK, 0, 1, False)
	polyPars = []
	for i in range(deg):
		polyPars.append(ptc.parameter(0.1, "reC"+str(i+1)))
		polyPars.append(ptc.parameter(0.1, "imC"+str(i+1)))
	poly  = ptc.complexPolynomial(deg, polyPars)
	fitF0 = amplitudeAnalysis(inFileName, sectors, {"1++0+[pi,pi]0++PiP":[f0,fixedAMPD_sub]}, startBin, stopBin, tBins, sectorRangeMap = sectorRangeMap)
	fitF0.loadData(referenceWave = referenceWave)
	fitF0.finishModelSetup()
#	fitF0.unifyComa()
	fitF0.fitShapeParameters()
	fitF0.calculateNonShapeParameters()
	fitF0.mode = AMPL
	if writeResultToFile:
		with open(writeResultToFile, 'a') as outFile:
			if len(tBins) > 1:
				raise ValueError("More than one t' bin not supported")
			resultString = str(tBins[0])+ " 666. " + str(f0Mass.value) + ' ' + str(f0Mass.error) + ' ' + str(f0g1.value) + ' ' + str(f0g1.error) + ' ' + str(f0g2.value) + ' ' + str(f0g2.error) 
			for i in range(deg):
				resultString += ' ' + str(polyPars[i].value) + ' ' + str(polyPars[i].error)
			resultString +=  "\n"
			outFile.write(resultString)
	return fitF0
Example #7
0
def doFitF2(inFileName,
            zeroFileName,
            sectors,
            startBin,
            stopBin,
            tBins,
            sectorRangeMap={},
            referenceWave="",
            writeResultToFile=None):
    f2Mass = ptc.parameter(mF2, "f2Mass")
    f2Width = ptc.parameter(GF2, "f2Width")
    f2 = ptc.relativisticBreitWigner([f2Mass, f2Width], mPi, mPi, mPi, 2, 1,
                                     False)
    fitF2 = amplitudeAnalysis(inFileName,
                              sectors, {"2++1+[pi,pi]2++PiP": [f2]},
                              startBin,
                              stopBin,
                              tBins,
                              sectorRangeMap=sectorRangeMap,
                              zeroFileName=zeroFileName)
    fitF2.loadData(referenceWave=referenceWave)
    fitF2.finishModelSetup()
    fitF2.fitShapeParameters()
    fitF2.calculateNonShapeParameters()
    fitF2.mode = AMPL
    #	fitF2.removeGlobalPhaseFromComa()
    if writeResultToFile:
        with open(writeResultToFile, 'a') as outFile:
            if len(tBins) > 1:
                raise ValueError("More than one t' bin not supported")
            resultString = str(tBins[0]) + " 666. " + str(
                f2Mass.value) + ' ' + str(f2Mass.error) + ' ' + str(
                    f2Width.value) + ' ' + str(f2Width.error) + "\n"
            outFile.write(resultString)
    return fitF2
def doFitRho(inFileName,
             zeroFileName,
             sectors,
             startBin,
             stopBin,
             tBins,
             sectorRangeMap={},
             referenceWave="",
             writeResultToFile=None):
    rhoMass = ptc.parameter(mRho, "rhoMass")
    rhoWidth = ptc.parameter(Grho, "rhoWidth")
    rho = ptc.relativisticBreitWigner([rhoMass, rhoWidth], mPi, mPi, mPi, 1, 2,
                                      False)
    fitRho = amplitudeAnalysis(inFileName,
                               sectors, {"3++0+[pi,pi]1--PiD": [rho]},
                               startBin,
                               stopBin,
                               tBins,
                               sectorRangeMap=sectorRangeMap,
                               zeroFileName=zeroFileName)
    fitRho.loadData(referenceWave=referenceWave)
    fitRho.finishModelSetup()
    fitRho.fitShapeParameters()
    fitRho.calculateNonShapeParameters()
    fitRho.mode = AMPL
    #	fitRho.removeGlobalPhaseFromComa()
    if writeResultToFile:
        with open(writeResultToFile, 'a') as outFile:
            if len(tBins) > 1:
                raise ValueError("More than one t' bin not supported")
            resultString = str(tBins[0]) + " 666. " + str(
                rhoMass.value) + ' ' + str(rhoMass.error) + ' ' + str(
                    rhoWidth.value) + ' ' + str(rhoWidth.error) + "\n"
            outFile.write(resultString)
    return fitRho
Example #9
0
def doFitRho3(inFileName,
              zeroFileName,
              sectors,
              startBin,
              stopBin,
              tBins,
              sectorRangeMap={}):
    rho3Mass = ptc.parameter(mRho3, "rho3Mass")
    rho3Width = ptc.parameter(Grho3, "rho3Width")
    rho3 = ptc.relativisticBreitWigner([rho3Mass, rho3Width], mPi, mPi, mPi, 3,
                                       0, False)
    rho3BF = ptc.timesBF(rho3)
    fitRho = amplitudeAnalysis(
        inFileName,
        sectors, {"3++0+[pi,pi]3--PiS": [rho3]},
        startBin,
        stopBin,
        tBins,
        sectorRangeMap={"3++0+[pi,pi]3--PiS": (1.4, 2.0)},
        zeroFileName=zeroFileName)
    fitRho.loadData(referenceWave="4-+0+rhoPiF")
    fitRho.finishModelSetup()
    fitRho.fitShapeParameters()
    fitRho.calculateNonShapeParameters()
    fitRho.mode = AMPL
    #	fitRho.removeGlobalPhaseFromComa()
    return fitRho
def doFitBothRho(inFileName,
                 zeroFileName,
                 sectors,
                 startBin,
                 stopBin,
                 tBins,
                 sectorRangeMap={},
                 referenceWave=""):
    rhoMass = ptc.parameter(mRho, "rhoMass")
    rhoWidth = ptc.parameter(Grho, "rhoWidth")
    rhoP = ptc.relativisticBreitWigner([rhoMass, rhoWidth], mPi, mPi, mPi, 1,
                                       1, False)
    rhoF = ptc.relativisticBreitWigner([rhoMass, rhoWidth], mPi, mPi, mPi, 1,
                                       3, False)
    fitRho = amplitudeAnalysis(inFileName,
                               sectors, {
                                   "2-+0+[pi,pi]1--PiP": [rhoP],
                                   "2-+0+[pi,pi]1--PiF": [rhoF]
                               },
                               startBin,
                               stopBin,
                               tBins,
                               sectorRangeMap=sectorRangeMap,
                               zeroFileName=zeroFileName)
    fitRho.loadData(referenceWave=referenceWave)
    fitRho.finishModelSetup()
    #	for mBin in fitRho.model[0]:
    #		print ">>",mBin.nPar,"<<"
    #	raise Exception
    fitRho.fitShapeParameters()
    fitRho.calculateNonShapeParameters()
    fitRho.mode = AMPL
    #	fitRho.removeGlobalPhaseFromComa()
    return fitRho
def doFitBothF2(inFileName,
                zeroFileName,
                sectors,
                startBin,
                stopBin,
                tBins,
                sectorRangeMap={},
                referenceWave=""):
    f2Mass = ptc.parameter(mF2, "f2Mass")
    f2Width = ptc.parameter(GF2, "f2Width")
    f2S = ptc.relativisticBreitWigner([f2Mass, f2Width], mPi, mPi, mPi, 2, 0,
                                      False)
    f2D = ptc.relativisticBreitWigner([f2Mass, f2Width], mPi, mPi, mPi, 2, 2,
                                      False)
    fitF2 = amplitudeAnalysis(inFileName,
                              sectors, {
                                  "2-+0+[pi,pi]2++PiS": [f2S],
                                  "2-+0+[pi,pi]2++PiD": [f2D]
                              },
                              startBin,
                              stopBin,
                              tBins,
                              sectorRangeMap=sectorRangeMap,
                              zeroFileName=zeroFileName)
    fitF2.loadData(referenceWave=referenceWave)
    fitF2.finishModelSetup()
    fitF2.fitShapeParameters()
    fitF2.calculateNonShapeParameters()
    fitF2.mode = AMPL
    #	fitF2.removeGlobalPhaseFromComa()
    return fitF2
def doFitRhoRadius(inFileName, sectors, startBin, stopBin, tBins, sectorRangeMap = {}, referenceWave = "", writeResultToFile = None, acv = None):
	rhoMass   = ptc.parameter( mRho, "rhoMass" )
	rhoWidth  = ptc.parameter( Grho, "rhoWidth")
	rhoRadius = ptc.parameter(  Pr0, "rRho"    )
	pi1radius = ptc.parameter(  100., "rPi1"    )
	
	rhoMass.lock   = True
	rhoWidth.lock  = True
#	pi1radius.lock = True
	rhoRadius.lock = True

	rho = ptc.relativisticBreitWigner([rhoMass, rhoWidth, pi1radius, rhoRadius], mPi, mPi, mPi, 1, 1, fitPr = True)
	fitRho = amplitudeAnalysis(inFileName, sectors, {"1-+1+[pi,pi]1--PiP":[rho]}, startBin, stopBin, tBins, sectorRangeMap = sectorRangeMap)
	fitRho.loadData( loadIntegrals = True, referenceWave = referenceWave)
	fitRho.finishModelSetup()
	fitRho.fitShapeParameters()
	fitRho.calculateNonShapeParameters()
	fitRho.mode = AMPL
#	fitRho.removeGlobalPhaseFromComa()
	if writeResultToFile is not None:
		with open(writeResultToFile, 'a') as outFile:
			if len(tBins) > 1:
				raise ValueError("More than one t' bin not supported")
			resultString = str(tBins[0]) + " 666. " + str(rhoRadius.value) + "\n"
#	#	#	resultString = str(tBins[0])+ " 666. "  + str(rhoMass.value) + ' ' + str(rhoMass.error) + ' ' + str(rhoWidth.value) + ' ' + str(rhoWidth.error) + "\n"
			outFile.write(resultString)
	return fitRho
def doFitRhoPR(inFileName, sectors, startBin, stopBin, tBins, sectorRangeMap = {}, referenceWave = ""):
	rhoMass  = ptc.parameter( mRho, "rhoMass"  )
	rhoWidth = ptc.parameter( Grho , "rhoWidth")
	PrA1  = ptc.PRparameter( Pr0, "PrA1" )
	PrRho = ptc.PRparameter( Pr0, "PrRho")
	rho = ptc.relativisticBreitWigner([rhoMass,rhoWidth,PrA1,PrRho], mPi, mPi, mPi, 1, 0, True)
	fitRho = amplitudeAnalysis(inFileName, sectors, {"1++0+[pi,pi]1--PiS":[rho]}, startBin, stopBin, tBins, sectorRangeMap = sectorRangeMap)
	fitRho.loadData(referenceWave = referenceWave)
	fitRho.finishModelSetup()
	fitRho.fitShapeParameters()
	fitRho.calculateNonShapeParameters()
	fitRho.mode = AMPL
#	fitRho.removeGlobalPhaseFromComa()
	return fitRho
def doFitRhoPrime(inFileName, sectors, startBin, stopBin, tBins, sectorRangeMap = {},referenceWave = ""):
	rhoMass  = ptc.parameter( mRho, "rhoMass" )
	rhoWidth = ptc.parameter( Grho , "rhoWidth")
	rhoPrimeMass  = ptc.parameter( mRhoPrime, "rhoPrimeMass" )
	rhoPrimeWidth = ptc.parameter( GrhoPrime, "rhoPrimeWidth")
	ratio         = ptc.parameter( .9       , "reImRatio"    )
	rho      = ptc.relativisticBreitWigner([rhoMass,rhoWidth], mPi, mPi, mPi, 1, 0, False)
	rhoPrime = ptc.relativisticBreitWignerRatio([rhoPrimeMass,rhoPrimeWidth,ratio], mPi, mPi, mPi, 1, 0, False)
	fitRho = amplitudeAnalysis(inFileName, sectors, {"1++0+[pi,pi]1--PiS":[rho, rhoPrime]}, startBin, stopBin, tBins, sectorRangeMap = sectorRangeMap)
	fitRho.loadData(referenceWave = referenceWave)
	fitRho.finishModelSetup()
	fitRho.fitShapeParameters()
	fitRho.calculateNonShapeParameters()
	fitRho.mode = AMPL
#	fitRho.removeGlobalPhaseFromComa()
	return fitRho
def doOmnes(inFileName, sectors, startBin, stopBin, tBins, sectorRangeMap = {}, referenceWave = "", deg = 0, compl = False):
	parameters = []
	for i in range(deg):
		if compl:
			parameters.append(ptc.parameter(0., "re"+str(i)))
			parameters.append(ptc.parameter(0., "im"+str(i)))
		else:
			parameters.append(ptc.parameter(0., "c"+str(i)))
	omnes  = ptc.omnesFunctionPolynomial(parameters, nDimPol = deg, shift = False, stretch = False, complexPolynomial = compl)
	fitRho = amplitudeAnalysis(inFileName, sectors, {"1++0+[pi,pi]1--PiS":[omnes]}, startBin, stopBin, tBins, sectorRangeMap = sectorRangeMap)
	fitRho.loadData(referenceWave = referenceWave)
	fitRho.finishModelSetup()
	fitRho.fitShapeParameters()
	fitRho.calculateNonShapeParameters()
	fitRho.mode = AMPL
#	fitRho.removeGlobalPhaseFromComa()
	return fitRho
def fitRhoPrime(fitBin, outFileName, inFileName, startBin, stopBin, tBins, pars, zeroModeParameters, plotNameBase = "",referenceWave = ""):
	global rhoPrimeFit
	if not rhoPrimeFit:
		rhoMass  = ptc.parameter( pars[0],  "rhoMass")
		rhoWidth = ptc.parameter( pars[1], "rhoWidth")
		rhoMass.lock  = True
		rhoWidth.lock = True
		rho = ptc.relativisticBreitWigner([rhoMass,rhoWidth], mPi, mPi, mPi, 1, 0, False)
		primeMass   = ptc.parameter( mRhoPrime, "primeMass" )
		primeWidth  = ptc.parameter( GrhoPrime, "primeWidth")
		prime       = ptc.relativisticBreitWigner([primeMass,primeWidth], mPi, mPi, mPi, 1, 0, False)
		rhoPrimeFit = amplitudeAnalysis(inFileName, ["1++0+[pi,pi]1--PiS"], {"1++0+[pi,pi]1--PiS":[rho,prime]}, startBin, stopBin, tBins)
		rhoPrimeFit.loadData(referenceWave = referenceWave)
		rhoPrimeFit.finishModelSetup()
		rhoPrimeFit.fitShapeParameters()
		rhoPrimeFit.calculateNonShapeParameters()
		rhoPrimeFit.mode = AMPL
	binIndex = fitBin+startBin
	with open(outFileName, 'a') as outFile:
		outFile.write(str(binIndex)+' '+str(0.52 + 0.04*binIndex)+' ')
		startValueOffset = 0.01
		exceptCount      = 0
		while True:
#			try:
			if True:
				x,err,c2,ndf = rhoPrimeFit.fitShapeParametersForBinRange([mRhoPrime+startValueOffset,GrhoPrime+startValueOffset], [0],[fitBin], zeroModeParameters = zeroModeParameters)
				break
#			except:
#				print "Fitter exception encountered"
#				startValueOffset += 0.001
#				exceptCount      += 1
#				if exceptCount > 3:
#					print "Too many failed attempts in bin "+str(fitBin)+": "+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')
		if not plotNameBase == "":
			rhoPrimeFit.calculateNonShapeParametersForZeroModeParameters(zeroModeParameters)
			rhoPrimeRV = rhoPrimeFit.produceResultViewer(zeroModeParameters,"1++0+[pi,pi]1--PiS", noRun = True, plotTheory = True)
			rhoPrimeRV.plotData = True
			rhoPrimeRV.writeBinToPdf(binIndex, stdCmd = ["", plotNameBase.replace("<mode>","intens"), [],  plotNameBase.replace("<mode>","argand"), []])
Example #17
0
	def loadFile(self):
		parameters = []
		with open(self.inFileName) as inFile:
			inPars = False
			for line in inFile.readlines():
				if "parameters" in line:
					inPars = True
					continue
				if "fit" in line and not "_fit_" in line:
					inPars = False
					continue
				if inPars:
					chunks    = line.split()
					par       = parameter(float(chunks[2]),chunks[0], float(chunks[4]))
					parameters.append(par)
				if "chi2/NDF" in line:
					self.chi2 = complex(line.split()[1].split('/')[0]).real
					self.ndf  = int(line.split('/')[2].split('=')[0])
				if "BW par" in line:
					chunks = line.split()
					self.mRho = float(chunks[2])
					self.Grho = float(chunks[3])
					if len(chunks) > 7:
						fVal      = float(chunks[7])
						if abs(fVal) > self.numLim:
							raise ValueError("Rho pole finding did not converge!!! Function value: "+str(fVal))
						self.fVal = fVal
				if "coma" in line:
					if self.coma is None:
						exec line.replace("coma","self.coma = ")	

					else:
						raise ValueError("COMA set twoce")

				if "BW' par" in line:
					chunks         = line.split()
					self.mRhoPrime = float(chunks[2])
					self.GrhoPrime = float(chunks[3])
					if len(chunks) > 7:
						self.fValPrime = float(chunks[7])
				if "BW_fit_result" in line:
					if self.BWresult is None:
						chunks = line.split()
						vals = [float(chunks[i]) for i in range(1, 5)]
						self.BWresult = ((vals[0],vals[1]),(vals[2],vals[3]))
					else:
						raise ValueError("BWpar set twice")
		self.parameters = parameters
		self.nPar       = len(parameters)
		if self.nPol is None:
			self.nPol       = (self.nPar - (self.kPol+1) - (self.pPol[0]+1) *self.pPol[1])/2	
			if not self.nPol == 1:
				print self.inFileName
				raise NotImplementedError("Number of poles not implemented yet")
def doFitF2(inFileName,
            sectors,
            startBin,
            stopBin,
            tBins,
            sectorRangeMap={},
            referenceWave=""):
    f2Mass = ptc.parameter(mF2, "f2Mass")
    f2Width = ptc.parameter(GF2, "f2Width")
    binning = [
        0.278, 0.32, 0.36, 0.4, 0.44, 0.48, 0.52, 0.56, 0.6, 0.64, 0.68, 0.72,
        0.76, 0.8, 0.84, 0.88, 0.92, 0.96, 1.0, 1.04, 1.08, 1.12, 1.16, 1.18,
        1.2, 1.22, 1.24, 1.26, 1.28, 1.30, 1.32, 1.34, 1.36, 1.38, 1.4, 1.44,
        1.48, 1.52, 1.56, 1.6, 1.64, 1.68, 1.72, 1.76, 1.8, 1.84, 1.88, 1.92,
        1.96, 2.0, 2.04, 2.08, 2.12, 2.16, 2.2, 2.24, 2.28
    ]
    #	f2 = ptc.relativisticBreitWigner([f2Mass,f2Width], mPi, mPi, mPi, 2, 0, False)
    f2 = ptc.integratedRelativisticBreitWigner(
        [f2Mass, f2Width],
        mPi,
        mPi,
        mPi,
        2,
        0,
        binning,
        intensWeight=intensWeight,
        fitPr=False,
        reweightInverseBW=reweightInverseBW)
    fitF2 = amplitudeAnalysis(inFileName,
                              sectors, {"2-+0+[pi,pi]2++PiS": [f2]},
                              startBin,
                              stopBin,
                              tBins,
                              sectorRangeMap=sectorRangeMap)
    fitF2.loadData(referenceWave=referenceWave)
    fitF2.finishModelSetup()
    fitF2.fitShapeParameters()
    fitF2.calculateNonShapeParameters()
    fitF2.mode = AMPL
    #	fitF2.removeGlobalPhaseFromComa()
    return fitF2
def doFit1500(inFileName,
              sectors,
              startBin,
              stopBin,
              tBins,
              sectorRangeMap={"0-+0+[pi,pi]0++PiS": (1.15, 1.75)},
              referenceWave="",
              writeResultToFile=None):
    fixedAMPD_sub = pc.fixedParameterization(
        "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/zeroModes/bwAmplitudes_noBF/amp_0mp0pSigmaPiS"
    )
    const = pc.constant()
    linea = pc.linear()
    f0mass = ptc.parameter(m1500, "1500mass")
    f0width = ptc.parameter(G1500, "1500width")
    f0_1500 = ptc.relativisticBreitWigner([f0mass, f0width], mPi, mPi, mPi, 0,
                                          0, False)
    fit1500 = amplitudeAnalysis(
        inFileName,
        sectors, {"0-+0+[pi,pi]0++PiS": [f0_1500, fixedAMPD_sub]},
        startBin,
        stopBin,
        tBins,
        sectorRangeMap=sectorRangeMap)
    #	fit1500 = amplitudeAnalysis(inFileName, sectors, {"0-+0+[pi,pi]0++PiS":[f0_1500, const, linea]}, startBin, stopBin, tBins, sectorRangeMap = sectorRangeMap)
    fit1500.loadData(referenceWave=referenceWave)
    fit1500.finishModelSetup()
    fit1500.fitShapeParameters()
    fit1500.calculateNonShapeParameters()
    fit1500.mode = AMPL
    #	fit1500.removeGlobalPhaseFromComa()
    if writeResultToFile:
        with open(writeResultToFile, 'a') as outFile:
            if len(tBins) > 1:
                raise ValueError("More than one t' bin not supported")
            resultString = str(tBins[0]) + " 666. " + str(
                f0mass.value) + ' ' + str(f0mass.error) + ' ' + str(
                    f0width.value) + ' ' + str(f0width.error) + "\n"
            outFile.write(resultString)
    return fit1500
def doPietarinen(inFileName, sectors, startBin, stopBin, tBins, sectorRangeMap = {}, referenceWave = "", polDeg = 1, polDeg3Pi = 0, writeResultToFile = None, acv = None, zeroModeParameters = None):
	rhoResRe  = ptc.parameter( 1.       ,  "rhoResRe"  )
	rhoResIm  = ptc.parameter( 0.       ,  "rhoResIm"  )
	rhoPoleRe = ptc.parameter( mRho**2  ,  "rhoPoleRe" )
	rhoPoleIm = ptc.parameter(-mRho*Grho,  "rhoPoleIm" )

	thresholds = [(4*mPi**2,polDeg)]
	alphaPiPi  = ptc.parameter( 0.      ,  "alphaPiPi" )
	polyCoeffs = [alphaPiPi]
	for i in range(polDeg):
		for j in range(polDeg3Pi+1):
			c = ptc.parameter( 0.,    "C"+str(i+1)+"_"+str(j)+"_PiPi" )
			polyCoeffs.append(c)
	parameters  = [rhoResRe,rhoResIm,rhoPoleRe,rhoPoleIm]
	if polDeg == 0:
		thresholds = []
	else:
		parameters += polyCoeffs

	pietarinen    = ptc.pietarinenExpansion(parameters, 1, threshsolds = thresholds, polDeg3Pi = polDeg3Pi)
	fitPietarinen = amplitudeAnalysis(inFileName, sectors, {"1-+1+[pi,pi]1--PiP":[pietarinen]}, startBin, stopBin, tBins, sectorRangeMap = sectorRangeMap)
	fitPietarinen.loadData(loadIntegrals = True, referenceWave = referenceWave)
	fitPietarinen.finishModelSetup()
	fitPietarinen.mode = AMPL

	fitPietarinen.removeZeroModeFromComa()
	if acv is not None:
		fitPietarinen.addComaValueForZeroMode(acv)

	if zeroModeParameters is None:
		fitPietarinen.fitShapeParameters()
		fitPietarinen.calculateNonShapeParameters()
		chi2 = fitPietarinen.chi2
		ndf  = fitPietarinen.getNDFforMode()
	else:
		x,err,chi2,ndf = fitPietarinen.fitShapeParametersForBinRange([p.value for p in parameters], [0],range(stopBin-startBin), zeroModeParameters = zeroModeParameters)
		fitPietarinen.calculateNonShapeParametersForZeroModeParameters(zeroModeParameters)

	print "mRho:", rhoPoleRe.value**.5
	print "Grho:",-rhoPoleIm.value/rhoPoleRe.value**.5
	print "chi2/NDF",chi2/ndf

	if writeResultToFile is not None:
		with open(writeResultToFile, 'w') as outFile:
			outFile.write("mRho: "+str(rhoPoleRe.value**.5)+'\n')
			outFile.write("Grho: "+str(-rhoPoleIm.value/rhoPoleRe.value**.5)+'\n')
			outFile.write("- - - - parameters - - - -\n")
			for p in parameters:
				outFile.write(str(p)+'\n')
			outFile.write(" - - - - - fit - - - - -\nchi2/NDF: "+str(chi2)+"/"+str(ndf)+"="+str(chi2/ndf))
	pietarinen.writeToFile("./pietarinenFits/pietarinenAmplitude_1.5_"+str(tBins[0])+".dat", [0.139*2 + 0.001*i for i in range(2000)], [1.5])
	return fitPietarinen
Example #21
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()
Example #22
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()
Example #23
0
def main():
	default_params =[parameter( .36674e-01, "lambP" ),
	                 parameter( .31230e-02, "lambPP"),
	                 parameter( .83386    , "M"     ),
	                 parameter( .19771    , "G"     ),
	                 parameter(1.4974     , "MP"    ),
	                 parameter( .78518    , "GP"    ),
	                 parameter(1.6855     , "MPP"   ),
	                 parameter( .80109    , "GPP"   ),
	                 parameter( .17254    , "alP"   ),
	                 parameter(-.97591    , "phP"   ),
	                 parameter( .23374    , "alPP"  ),
	                 parameter(2.1982     , "phPP"  )]

#	inFolder = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/zeroModeFitter_2D/global_vff_fits_subThresh/"
	inFolder = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/zeroModeFitter_2D/global_vff_fits/"
	names = [p.name for p in default_params]
	import ROOT
	hist = ROOT.TH2D("poles","poles", 100, 0.6, 1.6 ,100, 0., 1.)
	for fn in os.listdir(inFolder):
		if not '0123' in fn:
			continue
		if names is None:
			names = getNames(inFolder + fn)
		params = parseFile(inFolder + fn)
		pars = [parameter(params[i], names[i]) for i in range(12)]
		pars = default_params
		vff1 = vectorFormFactor(pars, sCut = 4)
		vff1.piSheet = 2
		vff1.Ksheet  = 1
		poles = findPoles(vff1.tildeCall, -.5, 2.5, -2., 2.)

		print pars[2].value**2,',',pars[2].value*pars[3].value
		print pars[4].value**2,',',pars[4].value*pars[5].value
		print pars[6].value**2,',',pars[6].value*pars[7].value

		for p in poles:
			print p.real**.5, p.imag/p.real**.5,p
			hist.Fill(p.real**.5, p.imag/p.real**.5)
		break
	hist.Draw("COLZ")
	raw_input()
Example #24
0
def main():
    checkLaTeX()
    inFileName = fileNameMap['std11']

    mMin = None
    mMax = None
    tBins = []
    for a in sys.argv:
        if a.startswith("mMin"):
            if mMin is not None:
                raise RuntimeError("mMin set twice")
            else:
                mMin = int(a[4:])

        if a.startswith("mMax"):
            if mMax is not None:
                raise RuntimeError("mMax set twice")
            else:
                mMax = int(a[4:])

        if a.startswith('t'):
            t = int(a[1:])
            if not t in range(4):
                raise RuntimeError("invelide tBin: " + a)
            if t in tBins:
                raise RuntimeError("tBin speciofitd twice: " + a)
            tBins.append(t)
    if mMin is None:
        raise RuntimeError("mMin not set")
    if mMax is None:
        raise RuntimeError("mMax not set")
    if not mMin < mMax:
        raise RuntimeError("m borders not ordered")
    if len(tBins) == 0:
        raise RuntimeError("No t' bin set")

    tBins.sort()
    acv = None
    sectorRangeMap = {}
    lockSecondRho = True

    parameters = [
        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")
    ]

    lock = []
    if lockSecondRho:
        # fix m and G of the second rho, due to (1)
        lock.append(4)
        lock.append(5)

    fitters = []
    binCount = 0
    fitters = []
    for t in tBins:
        for m in range(mMin, mMax):
            parameters.append(
                ptc.parameter(.17254, "alP_" + str(t) + "_" + str(m)))
            parameters.append(
                ptc.parameter(-.97591, "phP_" + str(t) + "_" + str(m)))
            parameters.append(
                ptc.parameter(.23374, "alPP_" + str(t) + "_" + str(m)))
            parameters.append(
                ptc.parameter(2.1982, "phPP_" + str(t) + "_" + str(m)))

            if lockSecondRho:
                # remove the second rho, since it just might modulate the intermediate region (1)
                lock.append(len(parameters) - 2)
                lock.append(len(parameters) - 3)

                parameters[-2].value = 0.
                parameters[-3].value = 0.

    for p in parameters:
        p.lock = True

    allowSubThr = True
    NDF = 0
    for t in tBins:
        for m in range(mMin, mMax):
            vff = vectorFormFactor(parameters[:8] +
                                   parameters[8 + binCount * 4:8 +
                                              (binCount + 1) * 4])
            vff.allowSubThr = allowSubThr
            fitter = opp.produceSingleMassTbinFitter(
                inFileName, [vff],
                m,
                t,
                sectorRangeMap=sectorRangeMap,
                referenceWave=referenceWave,
                acv=acv,
                removeZM=False)
            NDF += fitter.getNDFforMode()
            fitters.append(fitter)
            binCount += 1

    def chi2(par):
        if not len(par) == len(parameters) - len(lock):
            raise ValueError("parameter size mismatch")
        count = 0
        for i, p in enumerate(parameters):
            if not i in lock:
                p.value = par[count]
                count += 1
        c2 = 0.
        for f in fitters:
            c2 += f.model[0][0].chi2()
        return c2

    startParameters = []
    for i, p in enumerate(parameters):
        if not i in lock:
            startParameters.append(p)
    NDF -= len(startParameters)
    vals = migrad(chi2, startParameters)

    outFileName = "./global_vff_fits_lockRhoPrime/m_" + str(mMin) + '-' + str(
        mMax) + "_t"
    for t in tBins:
        outFileName += str(t)
    outFileName += ".dat"

    with open(outFileName, 'w') as outFile:
        for i, p in enumerate(startParameters):
            outFile.write(p.name + ' ' + str(vals[i]) + '\n')
        outFile.write(str(chi2(vals)) + '/' + str(NDF))

    doPlots = True
    if doPlots:
        fitterCount = 0
        for t in tBins:
            for m in range(mMin, mMax):
                fitters[fitterCount].model.chi2([])
                fitters[fitterCount].SET('hasFitResult')
                fitters[fitterCount].fitParameters = []

                zeroModeParameters = fitters[
                    fitterCount].calculateNonShapeParameters()
                zeroModeParameters = fitters[
                    fitterCount].getZeroModeParametersForMode()
                RV = fitters[fitterCount].produceResultViewer(
                    zeroModeParameters,
                    "1++0+[pi,pi]1--PiS",
                    noRun=True,
                    plotTheory=True)
                RV.plotData = True
                RV.connectTheoPoints = range(100)
                plotNameBase = "./vectorFormFactor_lockRhoPrime_plots/1pp0p1mmPiS_<mode>_" + str(
                    m) + "_" + str(t) + ".pdf"
                RV.writeBinToPdf(m,
                                 stdCmd=[
                                     "",
                                     plotNameBase.replace("<mode>", "intens"),
                                     [],
                                     plotNameBase.replace("<mode>", "argand"),
                                     []
                                 ])
                fitterCount += 1
    return
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          = 13
	stopBin           = 50
	if len(sys.argv) > 3:
		startBin = int(sys.argv[2])
		stopBin  = int(sys.argv[3])

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

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

	seedint = randint(0,10000)

#	startBin          = 25
#	stopBin           = 30

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

	rhoRange = None
	for a in sys.argv:
		if a.startswith("range"):
			rhoRange = float(a[5:])
			sectorRangeMap = {"1++0+[pi,pi]1--PiS":(0.,rhoRange)}

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

	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"}

#       # - - - - --- Start here with the model builtind --- - - - - #       #
	rhoRe0     =  0.579053
	rhoIm0     =  0.109177

	rhoMass    = ptc.parameter(mRho, "rho_mass")
	rhoWidth   = ptc.parameter(Grho, "rho_width")
	rho        = ptc.relativisticBreitWigner([rhoMass,rhoWidth], mPi, mPi, mPi, 1, 1, False)

	poleReal   = ptc.parameter(rhoRe0, "rhoRe")
	poleImag   = ptc.parameter(rhoIm0, "rhoIm")

	nPol = 1
	for a in sys.argv:
		if a.startswith("nPol"):
			nPol = int(a[4:])
	polyDeg_po = 8
	for a in sys.argv:
		if a.startswith("pdpo"):
			polyDeg_po = int(a[4:])


	params     = [poleReal,poleImag]
	for i in range(1, nPol):
		rePol = ptc.parameter(1.96, "polRe_"+str(i))
		imPol = ptc.parameter(0.28, "polIm_"+str(i))
		params.append(rePol)
		params.append(imPol)

	for d in range(polyDeg_po):
		params.append(ptc.parameter(2.*random()-1., "c_"+str(d)))
	Kmatrix    = ptc.simpleOneChannelKmatrix(params, nPol, polyDeg_po, 4*mPi**2)
	useCM      = False
	for a in sys.argv:
		if a == "CM":
			useCM = True
		if a == "rho":
			useCM = False

	Kmatrix.use_CM = useCM

	pPolyDeg3  = 7
	pPolyDeg2  = 4
	for a in sys.argv:
		if a.startswith("m3pol"):
			pPolyDeg3 = int(a[5:])
		if a.startswith("m2pol"):
			pPolyDeg2 = int(a[5:])


	params     = []
	for d in range(pPolyDeg2):
		for e in range(pPolyDeg3+1):
			params.append(ptc.parameter(2.*random()-1., "c_"+str(d+1)+"_"+str(e)))
	pPoly      = ptc.twoDimensionalRealPolynomial(pPolyDeg2, pPolyDeg3, params, baseExponent = 2) # baseExponent = 2: polynomial in s
	func       = ptc.multiply([Kmatrix, pPoly])	

	model      = [func]
#	model      = [rho]

#       # - - - - --- Stop the model building here --- - - - - #       #
	zeroModeParameters = None
	fixZeroMode        = True
	if fixZeroMode:
		fixedShapes        = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, acv = acv, sectorRangeMap = fixSectorRangeMap)
		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 useCM:
		ps = "CM"
	else:
		ps = "rho"
	if rhoRange is None:
		rrs = ""
	else:
		rrs = "range"+str(rhoRange)+'_'
	if nPol == 1:
		nps = ""
	else:
		nps = "nPol"+str(nPol)+"_"
	resultFile  =  "./KmatrixResults/1mp_Kmatrix_"+rrs+nps+ps+"_kPol"+str(polyDeg_po-1)+"_pPol"+str(pPolyDeg3)+"-"+str(pPolyDeg2)+"_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)
	rhoFitter   = doFunctionFit(inFileName, [rho], startBin, stopBin, tBins, fixSectorRangeMap, referenceWave = referenceWave, acv = acv, zeroModeParameters = zeroModeParameters, writeResultToFile = None)
	BWfitString = "BW_fit_result: " + str(rhoMass.value) + " " +str(rhoMass.error) + " " + str(rhoWidth.value) + " " + str(rhoWidth.error)

#       # - - - - --- Start the evaluations here --- - - - - #       #
	nBinsPlot = 1000
	def fPlot(v):
		return v.imag
#	hist = pyRootPwa.ROOT.TH2D("hhh","hhh", nBinsPlot, -.25, 6.25,nBinsPlot, -1., 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))
#	hist.Draw("COLZ")
#	raw_input("press <enter> to go to the secont sheet")
	Kmatrix.secondSheet = True
#	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))
#	hist.Draw("COLZ")
	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


	with open(resultFile,'a') as outFile:
		outFile.write('\n'+BWstring+" "+resSting)

	print "= = = = = = = = = Starting BW error ersimation = = = = = = = = = "
	nPoints     = 1000
	poleMean    = res.x
	poleSamples = []
	i           = 0
	failCount   = 0
	while i < 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:
			print "No more pole found (mfv = "+str(mfv)+") : fval = "+str(res.fun)
			failCount += 1
			if failCount > nPoints:
				print "Failed to find poles too often.... abort"
				return
			continue
#			raise ValueError("No more pole found: fval = "+str(res.fun))

		poleSamples.append(res.x)
		i+=1
		print i,"Marker to find the PRINT 57473M3N7"
	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
	comaString      = str(poleComa)
	print " - - - - - - le compaire pramaitre  - - - - - - "
	print meanPole, poleMean
	print " - - - - - - le compaire pramaitre  - - - - - - "
	print poleComa
	print "= = = = = = = = = Finished BW error ersimation = = = = = = = = = "
	mRhoP = 1.4
	GrhoP = .2
	res = scipy.optimize.minimize(Kmatrix.absInverse,[mRhoP**2,mRhoP*GrhoP])
	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+"\ncoma "+comaString)
		outFile.write('\n'+BWfitString)
#       # - - - - --- Start the evaluations here --- - - - - #       #
	doPlots = False
	if doPlots:
		RV = fitter.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"), []])
#	raw_input("press <enter> to exit")
	return
#################################################################################
#################################################################################
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
#################################################################################
#################################################################################
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
#################################################################################
#################################################################################
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
#################################################################################
#################################################################################
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
#################################################################################
#################################################################################
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
#################################################################################
#################################################################################
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
#################################################################################
#################################################################################
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
#################################################################################
#################################################################################
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
#################################################################################
#################################################################################
# The stuff down here does not matter at the moment #
	
	polDeg      = 2
	outFileName = "./pietarinenFits/polyDeg"+str(polDeg)+"_t"+str(tBin)+".txt"

	piet = doPietarinen(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, polDeg = polDeg, polDeg3Pi = 2, writeResultToFile = outFileName, sectorRangeMap = sectorRangeMap, acv = acv, zeroModeParameters = zeroModeParameters)
	if not fixZeroMode:
		zeroModeParameters = piet.getZeroModeParametersForMode()
	RV = piet.produceResultViewer(zeroModeParameters,"1-+1+[pi,pi]1--PiP", noRun = True, plotTheory = True)
	RV.plotData = True
	for b in range(startBin, stopBin):
		plotNameBase = "./pietarinenFits/1mp1p1mmPiP_<mode>_"+str(b)+"_"+str(tBin)+".pdf"
		RV.writeBinToPdf(b, stdCmd = ["", plotNameBase.replace("<mode>","intens"), [],  plotNameBase.replace("<mode>","argand"), []])
#	doFitRho(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, writeResultToFile = "rhoMassesAndWidths_1-+1+1--_global.dat", sectorRangeMap = sectorRangeMap, acv = acv, polDeg = polDeg)
	return

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

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

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

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

#	diffsFull, resolvedWA, nonResolvedWA, comps, resDiffs, nonResDiffs, resolvedDiffsFull,noCorrDiffs = cu.doAllComparisons(allMethods, startBin, methodBinRanges, noBelowZero = True)

#	print resolvedDiffsFull
#	from math import isnan
#	for pair in resolvedDiffsFull:
#		with  modernplotting.toolkit.PdfWriter('./resolvedDiffPlots/1mp_'+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)
#			plot.finishAndSaveAndClose(pdfOutput)

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

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

#	with  modernplotting.toolkit.PdfWriter("compositions_1mp_"+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])
#		plot.finishAndSaveAndClose(pdfOutput)

#	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_1mp_"+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.))
#
#		plot.finishAndSaveAndClose(pdfOutput)

#	with open("studies_1mp_"+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')

	doRhoFits = False
	writeCpls = False
	if writeCpls:
		outFileCpl = open("1mp_rho_cpls_"+str(tBin)+".dat",'w') 

	doActuallyNotFit = True
	if doRhoFits:
		with open("rhoMassesAndWidths_exotic_"+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:
						x,err,c2,ndf = fitRho.fitShapeParametersForBinRange([mRho+startValueOffset,Grho+startValueOffset], [0],[i], zeroModeParameters = resolvedWA)
					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(resolvedWA)
					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(resolvedWA)
					rhoRV = fitRho.produceResultViewer(resolvedWA,"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
##### Writing starts here

#	fileNames = {}

#	fixedShapes.removeZeroModeFromComa()
##	binRange = {"1-+1+[pi,pi]1--PiP": (10,22)}
#	totalHists = fixedShapes.getTotalHists(resolvedWA, binRange = binRange)
#	with root_open("./totals_1mp_rhoRange.root", "UPDATE") as out:
#		for t in totalHists:
#			for m in t:
#				m.Write()
#	return

#	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+"_1mpData_"+str(bin)
#				if not (sect,bin) in fileNames:
#					fileNames[sect,bin] = []
#				fileNames[sect,bin].append(fileName)
#				rv.writeAmplFiles(bin, fileName = fileName)
	scalle = False
	if scalle:
		folder = "./comparisonResultsData_1mp_scale/"
	else:
		folder = "./comparisonResultsData_1mp/"

	fixedShapesFull = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, acv = acv)

	for s, sect in enumerate(allMethods['fixedShapes'].sectors):
#		allMethods['fixedShapes'].removeZeroModeFromComa()
#		allMethods['fixedShapes'].removeGlobalPhaseFromComa()
		rv = fixedShapesFull.produceResultViewer(allMethods['fixedShapes'].getZeroModeParametersForMode(),s, noRun = True, plotTheory = True)
#		rv.plotData = False
		rv.writeBinToPdf(startBin, stdCmd = [ folder + sect + "_data_2D_"+str(tBin)+".pdf", "", [], "", []])
#		rv.labelPoints     = [0,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.865
#			rv.topMarginIntens = 1.3
#			rv.yAxisShift      = 100.
#		rv.shiftMap        = {0:(fakkkk*50.,fakkkk*-280.),10:(fakkkk*-420.,fakkkk*-50.), 15:(fakkkk*-420.,fakkkk*-30.), 20:(fakkkk*-50.,fakkkk*70.)}
		for b in range(startBin, stopBin):
#			if not bin == 27:
#				continue
#			intensNames = [name+".intens" for name in fileNames[sect,b]]
#			argandNames = [name+".argand" for name in fileNames[sect,b]]
#			intensNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/evalDima/dima.intens"]
#			argandNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/evalDima/dima.argand"]
#			if not scalle:
			if True:
				intensNames = []
				argandNames = []
#			rv.plotData = True
			rv.writeBinToPdf(b, stdCmd = ["", folder + sect + "_data_intens_"+str(b)+"_"+str(tBin)+".pdf", intensNames,  folder + sect + "_data_argand_"+str(b)+"_"+str(tBin)+".pdf", argandNames])
			rv.wiriteReImToPdf(b, folder +  sect + "_data_<ri>_"+str(b)+"_"+str(tBin)+".pdf")
def main():
    checkLaTeX()
    style = modernplotting.mpplot.PlotterStyle()
    #	style.p2dColorMap = 'ocean_r'
    #	style.p2dColorMap = 'YlOrRd'
    style.p2dColorMap = 'Reds'
    #	referenceWave     = ""

    inFileName = fileNameMap["std11"]

    for a in sys.argv:
        if a.startswith("mBins"):
            startBin = int(a.split("-")[1])
            stopBin = int(a.split("-")[2])
        if a.startswith("tBins"):
            tMin = int(a.split("-")[1])
            tMax = int(a.split("-")[2])
            tBins = range(tMin, tMax)

    nPol = 3
    for a in sys.argv:
        if a.startswith("nPol"):
            nPol = int(a[4:])

    f2Re0 = mF2**2
    f2Im0 = mF2 * GF2

    mPrime = 1.55
    Gprime = .2

    mPPrime = 1.91
    Gpprime = .3

    f2Mass = ptc.parameter(mF2, "f2_mass")
    f2Width = ptc.parameter(GF2, "f2_width")
    f2 = ptc.relativisticBreitWigner([f2Mass, f2Width], mPi, mPi, mPi, 2, 0,
                                     False)

    poleReal = ptc.parameter(f2Re0, "f2Re")
    poleImag = ptc.parameter(f2Im0, "f2Im")

    pPoleReal = ptc.parameter(mPrime**2, "f2pRe")
    pPoleImag = ptc.parameter(mPrime * Gprime, "f2pIm")

    ppPoleReal = ptc.parameter(mPPrime**2, "f2ppRe")
    ppPoleImag = ptc.parameter(mPPrime * Gpprime, "f2ppIm")

    #	poleRealPrime = ptc.parameter(mPrime**2, "rhoRePrime")
    #	poleImagPrime = ptc.parameter(mPrime*Gprime, "rhoImPrime")

    polyDeg_po = 3
    for a in sys.argv:
        if a.startswith("pdpo"):
            polyDeg_po = int(a[4:])

    params = [poleReal, poleImag, pPoleReal, pPoleImag, ppPoleReal, ppPoleImag]
    params = params[:2 * nPol]

    for d in range(polyDeg_po):
        params.append(ptc.parameter(2 * random() - 1., "c_" + str(d)))

    Kmatrix = ptc.simpleOneChannelKmatrix(params, nPol, polyDeg_po, 4 * mPi**2)
    useCM = False
    for a in sys.argv:
        if a == "CM":
            useCM = True
        if a == "rho":
            useCM = False
    if useCM:
        psString = "CM"
    else:
        psString = "rho"

    Kmatrix.use_CM = useCM

    for a in sys.argv:
        if a.startswith("polyDegP"):
            polyDegP = int(a[8:])

    mMin = .5 + .04 * startBin
    mMax = .5 + .04 * stopBin

    smartMode = True

    tFuncs = []
    tpPoly = []
    nKpar = len(params)
    KparValues = [p.value for p in params]

    funcs = []
    for d in range(polyDegP + 1):
        mnm = ptc.monomial(2 * d)
        func = ptc.multiply([Kmatrix, mnm])
        funcs.append(func)

    phases = []
    for tBin in tBins:
        tParams = []
        for mBin in range(startBin, stopBin):
            phases.append(
                ptc.parameter(2 * pi * random(),
                              "phi_t" + str(tBin) + "_m" + str(mBin)))
            for d in range(polyDegP):
                tParams.append(
                    ptc.parameter(
                        2 * random() - 1., "c" + str(d + 1) + "_t" +
                        str(tBin) + "_m" + str(mBin)))
        nPpar = len(tParams)
        if not smartMode:
            params += tParams
        pPoly = ptc.binnedPolynomial(tParams,
                                     mMin=mMin,
                                     mMax=mMax,
                                     nBins=stopBin - startBin,
                                     degree=polyDegP,
                                     baseExponent=2,
                                     real=True)
        tpPoly.append(pPoly)
        func = ptc.multiply([Kmatrix, pPoly])
        tFuncs.append(func)

    bestFitVals = [
        1.591236, 0.234037, 2.419353, 0.005742, 3.702362, 0.000053, -0.189620,
        0.207497, -0.058921, 0.517699, 0.166935, 0.181275, 0.959202, 1.528309,
        0.501027, -1.146739, -0.535555, 0.417481, -0.419879, 1.561247,
        0.120558, 1.059373, 0.393481, -0.283450, -0.182751, -0.667384,
        0.619867, 0.343112, 0.069652, 0.677225, -0.116518, -0.485594, 0.693124,
        0.270239, 0.139340, -2.694811, -0.062632, 1.570524, -0.493674,
        -2.409801, 0.394341, 0.421391, -0.524359, 0.112583, 0.285943,
        -0.166501, -0.408990, -0.010904, 0.088735, 0.117378, 0.166603,
        -0.949778, 0.500537, -1.352419, -0.639588, -2.139980, -0.146114,
        1.877676, 1.025465, -0.120469, 1.197397, 0.792957, -0.507836, 0.354736,
        -0.571950, -0.439970, 0.635951, 1.119741, 1.078536, -1.707963,
        -0.894598, -0.379259, -0.256336, 1.811274, 0.460570, -2.370441,
        -1.519688, -2.596059, -1.472923, 0.329489, 0.963846, -0.174265,
        0.497754, 0.523653, -0.082330, -2.288272, 0.238584, 2.432317,
        -0.219072, -1.818075, 0.101130, -1.315669, -0.095197, 0.185721,
        -0.468701, 1.150421, -0.706067, 1.336765, 0.114122, -2.514466,
        -1.292956, 0.909066, -0.136537, 1.579291, 0.917968, 0.519039, 0.560456,
        -3.141557, -0.919017, 1.034258, 0.651617, 0.414377, -0.954656,
        0.432315, -0.250071, -0.306383, -0.916611, 0.241417, 0.196445,
        -0.594122, -0.610276, -2.115296, -1.232504, 0.210273, -0.539883,
        1.134149, 0.582253, -1.330798, -1.189863, 2.000385, -0.286371,
        0.997649, -0.268911, -0.358648, 0.209653, 0.307646, 0.294261, 2.350279,
        -0.342739, 1.010674, -0.547855, -1.715226, 0.599891, 0.567254,
        -0.731444, 2.852883, -0.398756, 2.450370, 0.296712, 0.499203, 0.284769,
        -7.040768, -1.148202, -0.982813, 0.349752, -6.325548, -0.494806,
        0.183253, 0.745206, 2.547205, 1.571422, 0.713172, -0.253361, 0.610771,
        1.308658, 1.501376, 1.023860, 2.184354, 0.927320, 0.677329, 0.589890,
        0.139710, 0.550017, -0.702369, -0.847349, -0.729193, 0.541576,
        -0.508911, 0.495425, 1.287986, -0.364052, -1.338609, 0.281415,
        0.168475, 0.184298, -0.904410, 0.193151, -0.773044, 0.324601, 4.473005,
        0.046860, -0.359312, 0.368391, -1.623123, 0.531775, 0.384091, 0.988951,
        -0.779931, 0.030888, -0.139630, -0.264398, -9.821342, -1.601821,
        -7.745628, -2.010218, -3.540738, -0.067302, 0.153977, -1.635704
    ]

    for p, par in enumerate(params):
        par.value = bestFitVals[p]

    if smartMode:
        params += phases

    sector = "2-+0+[pi,pi]2++PiS"
    sectors = [
        "2-+0+[pi,pi]0++PiD", "2-+0+[pi,pi]1--PiP", "2-+0+[pi,pi]1--PiF",
        "2-+0+[pi,pi]2++PiS"
    ]

    sectorRangeMap = {}
    zmPars = []
    fitters = []
    for t, tBin in enumerate(tBins):
        if smartMode:
            ff = funcs
        else:
            ff = [tFuncs[t]]
        fitter = amplitudeAnalysis(inFileName,
                                   sectors, {sector: ff},
                                   startBin,
                                   stopBin, [tBin],
                                   sectorRangeMap=sectorRangeMap)
        fitter.loadData(loadIntegrals=True, referenceWave=referenceWave)
        fitter.finishModelSetup()
        fitter.mode = AMPL

        fixSectors = [
            "2-+0+[pi,pi]1--PiP", "2-+0+[pi,pi]1--PiF", "2-+0+[pi,pi]2++PiS"
        ]
        fixRangeMap = {
            "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.27)  # Use only left side of f_2(1270)
        }

        fixedShapes = doFixedShapes(inFileName,
                                    fixSectors,
                                    startBin,
                                    stopBin, [tBin],
                                    referenceWave=referenceWave,
                                    sectorRangeMap=fixRangeMap)
        zmPars.append(fixedShapes.getZeroModeParametersForMode())
        fitter.setZeroModeParameters(zmPars[-1])
        fitter.model.setBinsToEvalueate(
            [0], range(stopBin - startBin)
        )  # [0] since it is only one tBin in this fitter (one fitter par t' bin)
        fitters.append(fitter)

    c2 = 0.
    for t in range(len(tBins)):
        ddd = fitters[t].model.fixedZMPchi2(None)
        print ddd, "the previous chi2 (this should not give, since it allows phase motion in the p-vector"
        c2 += ddd
    print c2

    nmBins = stopBin - startBin

    def evalFunction(params):
        Kmatrix.setParameters(params[:nKpar])
        chi2 = 0.
        for t in range(len(tBins)):
            if smartMode:
                chi2 += fitters[t].model.fixedZMPchi2_realCouplings(
                    None, params[nKpar + t * nmBins:nKpar + (t + 1) * nmBins])
            else:
                chi2 += fitters[t].model.fixedZMPchi2(None)
        return chi2

    print evalFunction([p.value for p in params]), "gives it?"
    #	return

    argString = ','.join([p.name + '=' + str(p.value) for p in params])
    lstString = ','.join([p.name for p in params])

    ndf = 0
    for fitter in fitters:
        ndfs = fitter.model.getNDF()
        for t in ndfs:
            for m in t:
                ndf += m[0] - m[1] - m[2]
    ndf -= len(params)
    ndf += polyDegP * (stopBin - startBin) * (
        tMax - tBin)  # the couplings have just a global phase !!!
    # # # # # # 2mpF2_Kmatrix_nPol3_rho_kPol0_pPol0-3_t3_m49-50_5854.dat

    for att in range(10):  # make 10 attempts at once
        print "Setting Start Pars for attempt", att + 1
        for i in range(len(params)):
            if i < nKpar:
                params[i].value = KparValues[i]
            else:
                params[i].value = 2 * pi * random()
        vals = MIGRAD(argString, lstString, evalFunction)

        chi2 = explicit_MINUIT_function(*vals)

        seedint = randint(0, 10000)
        resultFileName = "./globalKmatrixFits/2mpF2_nPol" + str(
            nPol) + "_" + psString + "_kPol" + str(
                polyDeg_po -
                1) + "_t" + str(tMin) + '-' + str(tMax) + "_m" + str(
                    startBin) + "-" + str(stopBin) + "_polyDegP" + str(
                        polyDegP) + "_" + str(seedint) + ".dat"

        with open(resultFileName, 'w') as outFile:
            outFile.write("- - - - parameters - - - -\n")
            for p in params:
                outFile.write(str(p) + '\n')
            outFile.write(" - - - - - fit - - - - -\nchi2/NDF: " + str(chi2) +
                          "/" + str(ndf) + "=" + str(chi2 / ndf) + '\n')
            outFile.write("ndf corrected!!!")
    return

    parameters = []
    for f in funcs:
        for p in f.returnParameters():
            parameters.append(p)

    fitter.initMinuitFunction(parameters)
    fitter.removeZeroModeFromComa()
    fitter.removeGlobalPhaseFromComa()

    if acv is not None:
        print "adding ACV of", acv
        fitter.addComaValueForZeroMode(acv)
    pPoly = ptc.twoDimensionalRealPolynomial(
        pPolyDeg2, pPolyDeg3, params,
        baseExponent=2)  # baseExponent = 2: polynomial in s
    func = ptc.multiply([Kmatrix, pPoly])

    model = [func]
    #	model      = [rho]

    acv = None

    #       # - - - - --- Stop the model building here --- - - - - #       #
    zeroModeParameters = None
    fixZeroMode = True
    #	print sectorRangeMap
    #	return
    if fixZeroMode:
        fixSectors = [
            "2-+0+[pi,pi]1--PiP", "2-+0+[pi,pi]1--PiF", "2-+0+[pi,pi]2++PiS"
        ]
        fixRangeMap = {
            "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.27)  # Use only left side of f_2(1270)
        }

        fixedShapes = doFixedShapes(inFileName,
                                    fixSectors,
                                    startBin,
                                    stopBin,
                                    tBins,
                                    referenceWave=referenceWave,
                                    sectorRangeMap=fixRangeMap)
        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 useCM:
        ps = "CM"
    else:
        ps = "rho"
    if nPol == 1:
        nps = ""
    else:
        nps = "nPol" + str(nPol) + "_"

    resultFile = "./KmatrixRestrictedZMfixing_allFourSectorsActive/2mpF2_Kmatrix_" + nps + ps + "_kPol" + str(
        polyDeg_po - 1) + "_pPol" + str(pPolyDeg3) + "-" + str(
            pPolyDeg2) + "_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,
                           ifn=ifn)

    #       # - - - - --- Start the evaluations here --- - - - - #       #
    nBinsPlot = 1000

    def fPlot(v):
        return v.imag
#	hist = pyRootPwa.ROOT.TH2D("hhh","hhh", nBinsPlot, -.25, 6.25,nBinsPlot, -1., 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))
#	hist.Draw("COLZ")
#	raw_input("press <enter> to go to the secont sheet")

    Kmatrix.secondSheet = True
    #	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))
    #	hist.Draw("COLZ")
    res = scipy.optimize.minimize(Kmatrix.absInverse, [f2Re0, f2Im0])
    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

    if ifn is None:
        print "= = = = = = = = = Starting BW error ersimation = = = = = = = = = "
        nPoints = 1000
        poleMean = res.x
        poleSamples = []
        i = 0
        failCount = 0
        while i < 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:
                print "No more pole found (mfv = " + str(
                    mfv) + ") : fval = " + str(res.fun)
                failCount += 1
                if failCount > nPoints:
                    print "Failed to find poles too often.... abort"
                    return
                continue
    #			raise ValueError("No more pole found: fval = "+str(res.fun))

            poleSamples.append(res.x)
            i += 1
    #		print i,"Marker to find the PRINT 57473M3N7"
        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
        comaString = str(poleComa)
        print " - - - - - - le compaire pramaitre  - - - - - - "
        print meanPole, poleMean
        print " - - - - - - le compaire pramaitre  - - - - - - "
        print poleComa
        print "= = = = = = = = = Finished BW error ersimation = = = = = = = = = "
        mF2P = 1.9
        GF2P = .277
        res = scipy.optimize.minimize(Kmatrix.absInverse,
                                      [mF2P**2, mF2P * GF2P])
        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 + "\ncoma " +
                          comaString)
    #		outFile.write('\n'+BWfitString)
    #       # - - - - --- Start the evaluations here --- - - - - #       #
        doPlots = False
        for a in sys.argv:
            if a == "plot":
                doPlots = True
    if ifn is not None:
        doPlots = True  # Set plots by default, if an inFile is given

    if doPlots:
        RV = fitter.produceResultViewer(zeroModeParameters,
                                        "2-+0+[pi,pi]2++PiS",
                                        noRun=True,
                                        plotTheory=True)
        RV.plotData = True
        for b in range(startBin, stopBin):
            plotNameBase = "./Kmatrix_plots/2mp0p2ppPiS_<mode>_" + str(
                b) + "_" + str(tBin) + "_" + str(seedint) + ".pdf"
            RV.writeBinToPdf(b,
                             stdCmd=[
                                 "",
                                 plotNameBase.replace("<mode>", "intens"), [],
                                 plotNameBase.replace("<mode>", "argand"), []
                             ])


#	raw_input("press <enter> to exit")
    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