def getCompositions(diffs):
    lst = []
    for pair in diffs:
        if not pair[0] in lst:
            lst.append(pair[0])
    diffSums = {}
    totals = None
    for m in lst:
        diffSum = cloneZeros(diffs[m, m])
        if not totals:
            totals = cloneZeros(diffs[m, m])
        for n in lst:
            addBtoA(diffSum, diffs[n, m], noBelowZero=True)
        diffSums[m] = diffSum
    for m in lst:
        invertAllEntries(diffSums[m], nanToZero=True)

    for m in lst:
        addBtoA(totals, diffSums[m])
    for m in lst:
        divideAbyB(diffSums[m], totals, ignoreZero=True)
    return diffSums
def getmBinResolvedDiffs(methodMap):
    params = {}
    selfEvals = {}
    for m in methodMap:
        params[m] = methodMap[m].getZeroModeParametersForMode()
        selfEvals[m] = methodMap[m].evaluateResolvedZeroModeParametersForMode(
            params[m])
    diff = {}
    #	for m in params:
    #		print m, params[m]
    #	raise Exception
    for m in methodMap:
        for n in methodMap:
            evals = methodMap[m].evaluateResolvedZeroModeParametersForMode(
                params[n])
            diff[m, n] = cloneZeros(evals)
            makeStructureDiff(evals, selfEvals[m], diff[m, n])
    return diff
def doAllComparisons(methodMap,
                     startBin,
                     methodBinRanges={},
                     noBelowZero=False):
    """
	Does everything theo toher methods do, bit with the possibility of restricted ranged for several methods
	Start bin has to be given to match the bin ranges, parameters are just counted in the methods
	"""
    params = {}
    evals = {}
    for m in methodMap:
        params[m] = methodMap[m].getZeroModeParametersForMode()

        #		for mb in params[m][0]:
        #			print len(mb),
        #		print "<-----",m

        for n in methodMap:
            evals[n,
                  m] = methodMap[n].evaluateResolvedZeroModeParametersForMode(
                      params[m])
    diffs = {}
    resolvedDiffs = {}
    for m in methodMap:
        for n in methodMap:
            sumM = 0.
            sumN = 0.
            resolvedDiffs[m, n] = []
            for tBin in range(len(evals[m, n])):
                resolvedDiffs[m, n].append([])
                for mBin in range(len(evals[m, n][tBin])):
                    nBin = mBin + startBin
                    if m in methodBinRanges:
                        if nBin < methodBinRanges[m][
                                0] or nBin >= methodBinRanges[m][1]:
                            resolvedDiffs[m, n][tBin].append(float('nan'))
                            continue
                    if n in methodBinRanges:
                        if nBin < methodBinRanges[n][
                                0] or nBin >= methodBinRanges[n][1]:
                            resolvedDiffs[m, n][tBin].append(float('nan'))
                            continue
                    resolvedDiffs[m, n][tBin].append(
                        (evals[m, n][tBin][mBin] - evals[m, m][tBin][mBin]) /
                        evals[m, m][tBin][mBin])
                    sumM += evals[m, m][tBin][mBin]
                    sumN += evals[m, n][tBin][mBin]
            diffs[m, n] = (sumN - sumM) / sumM
    for m in methodMap:
        resolvedWA = cloneZeros(params[m])
        nonResolvedWA = cloneZeros(params[m])
        break
    compositions = {}
    for m in methodMap:
        compositions[m] = [[0.] * len(resolvedWA[i])
                           for i in range(len(resolvedWA))]
    for tBin in range(len(resolvedWA)):
        for mBin in range(len(resolvedWA[tBin])):
            totalWeight = 0.
            totalWeightNon = 0.
            for m in methodMap:
                nBin = mBin + startBin
                if m in methodBinRanges:
                    if nBin < methodBinRanges[m][0] or nBin >= methodBinRanges[
                            m][1]:
                        continue
                totalDiff = 0.
                totalDiffNon = 0.
                for n in methodMap:
                    if n in methodBinRanges:
                        if nBin < methodBinRanges[n][
                                0] or nBin >= methodBinRanges[n][1]:
                            continue
                    toadd = (evals[n, m][tBin][mBin] -
                             evals[n, n][tBin][mBin]) / evals[n, n][tBin][mBin]
                    if not toadd < 0. or not noBelowZero:
                        totalDiff += toadd
                    totalDiffNon += diffs[n, m]
                for i in range(len(resolvedWA[tBin][mBin])):

                    resolvedWA[tBin][mBin][
                        i] += params[m][tBin][mBin][i] / totalDiff
                    nonResolvedWA[tBin][mBin][
                        i] += params[m][tBin][mBin][i] / totalDiffNon
                totalWeight += 1. / totalDiff
                totalWeightNon += 1. / totalDiffNon
                compositions[m][tBin][mBin] = 1. / totalDiff
            for i in range(len(resolvedWA[tBin][mBin])):
                resolvedWA[tBin][mBin][i] /= totalWeight
                nonResolvedWA[tBin][mBin][i] /= totalWeightNon
            for m in methodMap:
                compositions[m][tBin][mBin] /= totalWeight

    resolvedWAdiffs = {}
    nonResovledWAdiffs = {}
    noCorrDiffs = {}
    for m in methodMap:
        resEvals = methodMap[m].evaluateResolvedZeroModeParametersForMode(
            resolvedWA)
        nonEvals = methodMap[m].evaluateResolvedZeroModeParametersForMode(
            nonResolvedWA)
        zerEvals = methodMap[m].evaluateResolvedZeroModeParametersForMode(
            cloneZeros(nonResolvedWA))
        aSumRes = 0.
        aSumNon = 0.
        aSumZer = 0.
        oSum = 0.
        resolvedDiffs[m, "WAres"] = []
        resolvedDiffs[m, "WAnon"] = []
        for tBin in range(len(resolvedWA)):
            resolvedDiffs[m, "WAres"].append([])
            resolvedDiffs[m, "WAnon"].append([])
            for mBin in range(len(resolvedWA[tBin])):
                nBin = mBin + startBin
                if m in methodBinRanges:
                    if nBin < methodBinRanges[m][0] or nBin >= methodBinRanges[
                            m][1]:
                        resolvedDiffs[m, "WAres"][tBin].append(float('nan'))
                        resolvedDiffs[m, "WAnon"][tBin].append(float('nan'))
                        continue
                resolvedDiffs[m, "WAres"][tBin].append(
                    (resEvals[tBin][mBin] - evals[m, m][tBin][mBin]) /
                    evals[m, m][tBin][mBin])
                resolvedDiffs[m, "WAnon"][tBin].append(
                    (nonEvals[tBin][mBin] - evals[m, m][tBin][mBin]) /
                    evals[m, m][tBin][mBin])
                aSumRes += resEvals[tBin][mBin]
                aSumNon += nonEvals[tBin][mBin]
                aSumZer += zerEvals[tBin][mBin]
                oSum += evals[m, m][tBin][mBin]
        resolvedWAdiffs[m] = (aSumRes - oSum) / oSum
        nonResovledWAdiffs[m] = (aSumNon - oSum) / oSum
        noCorrDiffs[m] = (aSumZer - oSum) / oSum
    return diffs, resolvedWA, nonResolvedWA, compositions, resolvedWAdiffs, nonResovledWAdiffs, resolvedDiffs, noCorrDiffs
Beispiel #4
0
def main():
    checkLaTeX()
    style = modernplotting.mpplot.PlotterStyle()
    #	style.p2dColorMap = 'ocean_r'
    #	style.p2dColorMap = 'YlOrRd'
    style.p2dColorMap = 'Reds'

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

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

    tBins = [tBin]

    startBin = 11
    stopBin = 50

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        plot.axes.set_yticklabels(axolotl)

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

        pdfOutput.savefigAndClose()

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

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

    fileNames = {}

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

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


#	return

    plotFolder = "./comparisonResultsBigger2pp/"

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

    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'

#	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