def main():
    checkLaTeX()
    style = modernplotting.mpplot.PlotterStyle()
    #	style.p2dColorMap = 'ocean_r'
    #	style.p2dColorMap = 'YlOrRd'
    style.p2dColorMap = 'Reds'

    style.titleRight = r"$0^{-+}0^+$"
    style.titleLeft = r"Monte-Carlo"

    inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_MC_corrected.root"
    #	inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_std11.root"
    sectors = ["0-+0+[pi,pi]0++PiS", "0-+0+[pi,pi]1--PiP"]
    tBins = [0]
    startBin = 12
    stopBin = 50

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

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

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

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

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

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

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

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

    #	fitRho.setZeroModeParameters(fixedShapes.getZeroModeParametersForMode())
    #	for i in range(10):
    #		x,err  = fitRho.fitShapeParametersForBinRange([mRho,Grho], [0], [i,i+1])
    #		print x,err
    #	print "Finished with fitting rho"
    #	return

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

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

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

    ndfs = {}
    params = {}
    for m in allMethods:
        ndfs[m] = allMethods[m].getNDFforMode()
        params[m] = allMethods[m].getZeroModeParametersForMode()
        print m, sumUp(allMethods[m].evaluateZeroModeParametersForMode(
            params[m])).real / ndfs[m]
    diffs = cu.getmBinResolvedDiffs(allMethods)
    comps = cu.getCompositions(diffs)
    with modernplotting.toolkit.PdfWriter("compositions_0mp.pdf") as pdfOutput:
        plot = style.getPlot1D()
        for m in comps:
            line = [0.] * len(comps[m][0])
            xAxis = [
                .5 + 0.04 * (startBin + i) for i in range(len(comps[m][0]))
            ]
            break
        count = 0
        for m in comps:
            print m

            newLine = line[:]
            for i in range(len(comps[m][0])):
                newLine[i] += comps[m][0][i]
            plot.axes.fill_between(
                xAxis,
                line,
                newLine,
                facecolor=modernplotting.colors.makeColorLighter(
                    modernplotting.colors.colorScheme.blue, 0.1 * count))
            count += 1
            line = newLine
        plot.setYlim(0., 1.)
        plot.setXlim(xAxis[0], xAxis[-1])
        pdfOutput.savefigAndClose()
    studyList = []
    for m in allMethods:
        studyList.append(m)
    studyList.sort()

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

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

    cumulWeights = {}
    resovedWeightedSum = [[]]  # 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]
        resovedWeightedSum[0].append(prrs)

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

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

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

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

    style.titleRight = r"$0^{-+}0^+$"
    style.titleLeft = r"Monte Carlo"

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

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

        pdfOutput.savefigAndClose()

    return

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


##### Writing starts here

    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 + "_0mpMC_" + str(
                    bin)
                if not (sect, bin) in fileNames:
                    fileNames[sect, bin] = []
                fileNames[sect, bin].append(fileName)
                rv.writeAmplFiles(bin, fileName=fileName)

    for s, sect in enumerate(allMethods['fixedShapes'].sectors):
        allMethods['fixedShapes'].removeZeroModeFromComa()
        allMethods['fixedShapes'].removeGlobalPhaseFromComa()
        rv = allMethods['fixedShapes'].produceResultViewer(resovedWeightedSum,
                                                           s,
                                                           noRun=True,
                                                           plotTheory=True)
        rv.writeBinToPdf(startBin,
                         stdCmd=[
                             "./comparisonResults/" + sect + "_MC_2D.pdf", "",
                             [], "", []
                         ])
        for b in range(startBin, stopBin):
            if not b == 32:
                continue
            intensNames = [name + ".intens" for name in fileNames[sect, b]]
            argandNames = [name + ".argand" for name in fileNames[sect, b]]
            rv.writeBinToPdf(b,
                             stdCmd=[
                                 "", "./comparisonResults/" + sect +
                                 "_MC_intens_" + str(b) + ".pdf", intensNames,
                                 "./comparisonResults/" + sect +
                                 "_MC_argand_" + str(b) + ".pdf", argandNames
                             ])
    print studyList
    print cumulWeights
def main():
    checkLaTeX()
    style = modernplotting.mpplot.PlotterStyle()
    #	style.p2dColorMap = 'ocean_r'
    #	style.p2dColorMap = 'YlOrRd'
    style.p2dColorMap = 'Reds'

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

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

    referenceWave = ""

    inFileName = fileNameMap[study]
    tBins = [tBin]

    startBin = 11
    stopBin = 50

    #	startBin         = 32
    #	stopBin          = 33

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    #		pdfOutput.savefigAndClose()

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

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

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

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

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

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

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

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

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

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

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

    if doF0fitGlobal or doF0Fits or doFits1500 or doRhoFits:
        return

    fileNames = {}

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

    resolvedWeightedSum = fixedShapes.getZeroModeParametersForMode()

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

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


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

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

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

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

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

            rv.writeBinToPdf(b,
                             stdCmd=[
                                 "", folder + sect + "_data_intens_" + str(b) +
                                 "_" + str(tBin) + ".pdf", intensNames,
                                 folder + sect + "_data_argand_" + str(b) +
                                 "_" + str(tBin) + ".pdf", argandNames
                             ])
    print studyList
    print cumulWeights
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
def main():
	checkLaTeX()
	style = modernplotting.mpplot.PlotterStyle()
#	style.p2dColorMap = 'ocean_r'
#	style.p2dColorMap = 'YlOrRd'
	style.p2dColorMap = 'Reds'

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

	inFileName = fileNameMap[study]
	sectors    = ["1++0+[pi,pi]0++PiP", "1++0+[pi,pi]1--PiS"]
	tBins      = [tBin]
	startBin   = 30
	stopBin    = 50
#	startBin   = 25
#	stopBin    = 28


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

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

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

	print "Starting with fitting rho"
	fitRho = opp.doFitRho(inFileName, sectors, startBin, stopBin, tBins,sectorRangeMap = {"1++0+[pi,pi]0++PiP" : (0., 1.1)}, referenceWave = referenceWave)
	allMethods["fitRho"] = fitRho
	print "Finished with fitting rho"

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

	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)
	studyList = []
	for m in allMethods:
		studyList.append(m)
	studyList.sort()

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

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

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

	fitRhoPrime = doFitRhoPrime(inFileName, sectors[1:], startBin, stopBin, tBins, referenceWave = referenceWave)
	startPars   = [mRho,Grho,mRhoPrime,GrhoPrime,1.]
	x,err       = fitRhoPrime.fitShapeParametersForBinRange(startPars,[0],range(stopBin-startBin), zeroModeParameters = resolvedWeightedSum)
	print x
	fitRhoPrime.setShapeParameters(x,err,resolvedWeightedSum)
	s = 0 # only one sector??
	rv = fitRhoPrime.produceResultViewer(resolvedWeightedSum,s, noRun = True, plotTheory = True)
	for b in range(startBin, stopBin):
		intensName = "./rhoPrimeFits/intens_"+str(b)+"_"+str(tBin)+".pdf"
		argandName = "./rhoPrimeFits/argand_"+str(b)+"_"+str(tBin)+".pdf"
		rv.writeBinToPdf(b, stdCmd = ["", intensName, [],  argandName, []])
	return