def main(): checkLaTeX() style = modernplotting.mpplot.PlotterStyle() # style.p2dColorMap = 'ocean_r' # style.p2dColorMap = 'YlOrRd' style.p2dColorMap = 'Reds' inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_3pp.root" zeroFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_3pp.root" sectors = ["3++0+[pi,pi]3--PiS"] tBin = int(sys.argv[1]) if tBin < 0 or tBin > 3: raise ValueError("Invalid t' bin: " + str(tBin)) tBins = [tBin] startBin = 32 stopBin = 50 methodBinRanges = { "fitF2": (22, 50), "fitRho3": (32, 50), "fitBothF2": (22, 50), "fitRhoF": (22, 50), "fixedShapeF2": (22, 50) } # methodBinRanges = {} # Override here print "Starting with fitting rho3" fitRho3 = doFitRho3(inFileName, zeroFileName, sectors, startBin, stopBin, tBins) print "Finished with fitting rho3" return s = 0 # only one sector?? rv = fitRho3.produceResultViewer(fitRho3.getZeroModeParametersForMode(), s, noRun=True, plotTheory=True) for b in range(startBin, stopBin): intensName = "./rho3fits/intens_" + str(b) + "_" + str(tBin) + ".pdf" argandName = "./rho3fits/argand_" + str(b) + "_" + str(tBin) + ".pdf" rv.writeBinToPdf(b, stdCmd=["", intensName, [], argandName, []]) return
def main(): checkLaTeX() inFileName = fileNameMap['std11'] mMin = None mMax = None tBins = [] for a in sys.argv: if a.startswith("mMin"): if mMin is not None: raise RuntimeError("mMin set twice") else: mMin = int(a[4:]) if a.startswith("mMax"): if mMax is not None: raise RuntimeError("mMax set twice") else: mMax = int(a[4:]) if a.startswith('t'): t = int(a[1:]) if not t in range(4): raise RuntimeError("invelide tBin: " + a) if t in tBins: raise RuntimeError("tBin speciofitd twice: " + a) tBins.append(t) if mMin is None: raise RuntimeError("mMin not set") if mMax is None: raise RuntimeError("mMax not set") if not mMin < mMax: raise RuntimeError("m borders not ordered") if len(tBins) == 0: raise RuntimeError("No t' bin set") tBins.sort() acv = None sectorRangeMap = {} lockSecondRho = True parameters = [ ptc.parameter(.36674e-01, "lambP"), ptc.parameter(.31230e-02, "lambPP"), ptc.parameter(.83386, "M"), ptc.parameter(.19771, "G"), ptc.parameter(1.4974, "MP"), ptc.parameter(.78518, "GP"), ptc.parameter(1.6855, "MPP"), ptc.parameter(.80109, "GPP") ] lock = [] if lockSecondRho: # fix m and G of the second rho, due to (1) lock.append(4) lock.append(5) fitters = [] binCount = 0 fitters = [] for t in tBins: for m in range(mMin, mMax): parameters.append( ptc.parameter(.17254, "alP_" + str(t) + "_" + str(m))) parameters.append( ptc.parameter(-.97591, "phP_" + str(t) + "_" + str(m))) parameters.append( ptc.parameter(.23374, "alPP_" + str(t) + "_" + str(m))) parameters.append( ptc.parameter(2.1982, "phPP_" + str(t) + "_" + str(m))) if lockSecondRho: # remove the second rho, since it just might modulate the intermediate region (1) lock.append(len(parameters) - 2) lock.append(len(parameters) - 3) parameters[-2].value = 0. parameters[-3].value = 0. for p in parameters: p.lock = True allowSubThr = True NDF = 0 for t in tBins: for m in range(mMin, mMax): vff = vectorFormFactor(parameters[:8] + parameters[8 + binCount * 4:8 + (binCount + 1) * 4]) vff.allowSubThr = allowSubThr fitter = opp.produceSingleMassTbinFitter( inFileName, [vff], m, t, sectorRangeMap=sectorRangeMap, referenceWave=referenceWave, acv=acv, removeZM=False) NDF += fitter.getNDFforMode() fitters.append(fitter) binCount += 1 def chi2(par): if not len(par) == len(parameters) - len(lock): raise ValueError("parameter size mismatch") count = 0 for i, p in enumerate(parameters): if not i in lock: p.value = par[count] count += 1 c2 = 0. for f in fitters: c2 += f.model[0][0].chi2() return c2 startParameters = [] for i, p in enumerate(parameters): if not i in lock: startParameters.append(p) NDF -= len(startParameters) vals = migrad(chi2, startParameters) outFileName = "./global_vff_fits_lockRhoPrime/m_" + str(mMin) + '-' + str( mMax) + "_t" for t in tBins: outFileName += str(t) outFileName += ".dat" with open(outFileName, 'w') as outFile: for i, p in enumerate(startParameters): outFile.write(p.name + ' ' + str(vals[i]) + '\n') outFile.write(str(chi2(vals)) + '/' + str(NDF)) doPlots = True if doPlots: fitterCount = 0 for t in tBins: for m in range(mMin, mMax): fitters[fitterCount].model.chi2([]) fitters[fitterCount].SET('hasFitResult') fitters[fitterCount].fitParameters = [] zeroModeParameters = fitters[ fitterCount].calculateNonShapeParameters() zeroModeParameters = fitters[ fitterCount].getZeroModeParametersForMode() RV = fitters[fitterCount].produceResultViewer( zeroModeParameters, "1++0+[pi,pi]1--PiS", noRun=True, plotTheory=True) RV.plotData = True RV.connectTheoPoints = range(100) plotNameBase = "./vectorFormFactor_lockRhoPrime_plots/1pp0p1mmPiS_<mode>_" + str( m) + "_" + str(t) + ".pdf" RV.writeBinToPdf(m, stdCmd=[ "", plotNameBase.replace("<mode>", "intens"), [], plotNameBase.replace("<mode>", "argand"), [] ]) fitterCount += 1 return
def main(): checkLaTeX() style = modernplotting.mpplot.PlotterStyle() # style.p2dColorMap = 'ocean_r' # style.p2dColorMap = 'YlOrRd' style.p2dColorMap = 'Reds' # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_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
def main(rhoFileName=""): checkLaTeX() inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_exotic.root" # # # # # Exotic (1-+) sectors = ["1-+1+[pi,pi]1--PiP"] referenceWave = "4-+0+rhoPiF" # referenceWave = "" mBin = 32 tBin = 3 startBin = mBin stopBin = mBin + 1 useBF = False merge0pp = False polyDegree = 0 polyComplex = True waveModel = {} model = [] fileNames = getFileNameForSector(sectors[0], useBF, merge0pp) for fn in fileNames: param = pc.fixedParameterization(fn, polynomialDegree=polyDegree, complexPolynomial=polyComplex) model.append(param) waveModel[sectors[0]] = model with root_open(inFileName, "READ") as inFile: histNames = GetKeyNames(inFile) histListReal = [] histListImag = [] histListNorm = [] histListIndx = [] nAmplMax = 0 for sector in sectors: realHistName = sector + "_" + str(tBin) + "_real" histReal = inFile.Get(realHistName) if not histReal: raise IOError("Could not get '" + realHistName + "' from '" + inFileName + "'") histReal.SetDirectory(0) histListReal.append(histReal) imagHistName = sector + "_" + str(tBin) + "_imag" histImag = inFile.Get(imagHistName) if not histImag: raise IOError("Could not get '" + imagHistName + "' from '" + inFileName + "'") histImag.SetDirectory(0) histListImag.append(histImag) normHistName = sector + "_" + str(tBin) + "_norm" histNorm = inFile.Get(normHistName) if not histNorm: raise IOError("Could not get '" + normHistName + "' from '" + inFileName + "'") histNorm.SetDirectory(0) histListNorm.append(histNorm) indexHistName = sector + "_" + str(tBin) + "_index" histIndx = inFile.Get(indexHistName) if not histIndx: raise IOError("Could not get '" + indexHistName + "' from '" + inFileName + "'") histIndx.SetDirectory(0) nAmplMax = max(nAmplMax, int(2 * histIndx.GetMaximum())) histListIndx.append(histIndx) histsToFill = [] comaHists = [] intHistsReal = [] intHistsImag = [] for mBin in range(startBin, stopBin): comaHistName = "COMA_" + str(tBin) + "_" + str(mBin) comaHist = inFile.Get(comaHistName) if not comaHist: print "Could not get '" + comaHistName + "' from '" + inFileName + "'", "USING IDENTITY" comaHist = pyRootPwa.ROOT.TH2D(comaHistName, comaHistName, nAmplMax, 0., 1., nAmplMax, 0., 1.) for i in range(nAmplMax): comaHist.SetBinContent(i + 1, i + 1, 1.) comaHist.SetDirectory(0) comaHists.append(comaHist) if not referenceWave == "": refHistReal = inFile.Get(referenceWave + "_" + str(tBin) + "_real") refHistReal.SetDirectory(0) if not refHistReal: raise IOError("Could not get '" + referenceWave + "_" + str(tBin) + "_real" + "' from '" + self.inFileName + "'") refHistImag = inFile.Get(referenceWave + "_" + str(tBin) + "_imag") refHistImag.SetDirectory(0) if not refHistImag: raise IOError("Could not get '" + referenceWave + "_" + str(tBin) + "_imag" + "' from '" + self.inFileName + "'") refHistIndex = inFile.Get(referenceWave + "_" + str(tBin) + "_index") refHistIndex.SetDirectory(0) if not refHistIndex: raise IOError("Could not get '" + referenceWave + "_" + str(tBin) + "_index" + "' from '" + self.inFileName + "'") changeReferenceWave(histListReal, histListImag, histListIndx, comaHists, refHistReal, refHistImag, refHistIndex, startBin, stopBin) ab = allBins(startBin, stopBin, histListReal, histListImag, histListNorm, histListIndx, comaHists, intHistsReal, intHistsImag) zeroCount = 0 zeroHistList = [] eigenHistList = [] while True: zeroName = "zero" + str(zeroCount) + "_" + str(tBin) eigenName = "eigen" + str(zeroCount) + "_" + str(tBin) zeroHist = inFile.Get(zeroName) if not zeroHist: break zeroHist.SetDirectory(0) print "Adding zero-mode" zeroCount += 1 if not zeroForSectors(sectors, zeroHist.GetTitle()): continue zeroHistList.append(zeroHist) eigenHist = inFile.Get(eigenName) eigenHist.SetDirectory(0) if eigenHist: eigenHistList.append(eigenHist) if (not len(eigenHistList) == 0) and (not len(eigenHistList) == len(zeroHistList)): raise ValueError( "Number of eigenvalue histograms does not match, but is also nonzero" ) removeCertainZeroModes(zeroHistList, eigenHistList) for zeroHist in zeroHistList: borders = getZeroHistBorders(zeroHist) ab.addZeroMode(borders, zeroHist) writeSamples = False nRand = 100 rh = histListReal[0] nPts = rh.GetNbinsY() valsC = np.zeros((2 * nPts, nRand)) valsD = np.zeros((2 * nPts, nRand)) for r in range(nRand + 1): ab.initChi2(waveModel) shapePars = [] chi2, params = ab.chi2(shapePars, returnParameters=True) errs = ab.getNonShapeUncertainties(shapePars) paramsZ = ab.linearizeZeroModeParameters(params) zeroP = [0.] * len(paramsZ) argandNameBase = "./samplingArgands/argand_<mode>_" + str( r) + ".dat" IC = rh.Clone() IC.Reset() ab.fillHistograms(paramsZ, [IC], mode=INTENS) renormToBinWidth(IC, 1.) rC = rh.Clone() rC.Reset() ab.fillHistograms(paramsZ, [rC], mode=REAL) renormToBinWidth(rC, .5) iC = rh.Clone() iC.Reset() ab.fillHistograms(paramsZ, [iC], mode=IMAG) renormToBinWidth(iC, .5) if not r == 0: # ugly, but r = 0 is unrandomized for i in range(nPts): valsC[2 * i, r - 1] = rC.GetBinContent(mBin + 1, i + 1) valsC[2 * i + 1, r - 1] = iC.GetBinContent(mBin + 1, i + 1) if writeSamples: with open(argandNameBase.replace("<mode>", "C"), 'w') as outFile: for i in range(nPts): m = rC.GetYaxis().GetBinCenter(i) outFile.write(str(m)) for h in [IC, rC, iC]: v = h.GetBinContent(mBin + 1, i + 1) e = h.GetBinError(mBin + 1, i + 1) if v == 0. and e == 0.: continue outFile.write(' ' + str(v) + ' ' + str(e)) outFile.write('\n') ID = rh.Clone() ID.Reset() ab.fillHistograms(zeroP, [ID], mode=INTENS) renormToBinWidth(ID, 1.) rD = rh.Clone() rD.Reset() ab.fillHistograms(zeroP, [rD], mode=REAL) renormToBinWidth(rD, .5) iD = rh.Clone() iD.Reset() ab.fillHistograms(zeroP, [iD], mode=IMAG) renormToBinWidth(iD, .5) if not r == 0: # ugly, but r = 0 is unrandomized for i in range(nPts): valsD[2 * i, r - 1] = rD.GetBinContent(mBin + 1, i + 1) valsD[2 * i + 1, r - 1] = iD.GetBinContent(mBin + 1, i + 1) if writeSamples: with open(argandNameBase.replace("<mode>", "D"), 'w') as outFile: for i in range(nPts): m = rD.GetYaxis().GetBinCenter(i) outFile.write(str(m)) for h in [ID, rD, iD]: v = h.GetBinContent(mBin + 1, i + 1) e = h.GetBinError(mBin + 1, i + 1) if v == 0. and e == 0.: continue outFile.write(' ' + str(v) + ' ' + str(e)) outFile.write('\n') ab.randomize( ) # Put the randomization at the end, to have the fist run with unrandomized points correl = rh.Clone() correl.Reset() ab.fillHistograms(paramsZ, [correl], mode=REIMCORRELATION) renormToBinWidth(correl, 1.) if writeSamples: with open("correlations_D.dat", 'w') as outFile: for i in range(correl.GetNbinsY()): outFile.write( str(rD.GetBinError(mBin + 1, i + 1)**2) + ' ' + str(correl.GetBinContent(mBin + 1, i + 1)) + ' ' + str(iD.GetBinError(mBin + 1, i + 1)**2) + '\n') ab.removeZeroModeFromComa() correl.Reset() ab.fillHistograms(paramsZ, [correl], mode=REIMCORRELATION) rC.Reset() iC.Reset() ab.fillHistograms(paramsZ, [rC], mode=REAL) ab.fillHistograms(paramsZ, [iC], mode=IMAG) renormToBinWidth(correl, 1.) renormToBinWidth(rC, .5) renormToBinWidth(iC, .5) with open("correlations_C.dat", 'w') as outFile: for i in range(correl.GetNbinsY()): outFile.write( str(rC.GetBinError(mBin + 1, i + 1)**2) + ' ' + str(correl.GetBinContent(mBin + 1, i + 1)) + ' ' + str(iC.GetBinError(mBin + 1, i + 1)**2) + '\n')
def main(rhoFileName=""): checkLaTeX() freeMap, freeString = parseCmdLine(sys.argv) inFileName = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/ppppppppp/DdecayResults_" + freeString + "_" + getBranchFileEnding( ) + ".root" zeroFileName = inFileName sectors = [] allSectors = [ "KpiSright", "KpiPright", "KpiDright", "KpiSwrong", "KpiPwrong", "KpiDwrong", "piPiS", "piPiP", "piPiD" ] fixMap = [False, False, False, False, False, False, False, False, False] for i in range(9): if freeString[i] == '1': if not fixMap[i]: sectors.append(allSectors[i]) # sectors = sectors[:1] sectorRangeMap = {} tBin = 0 startBin = 34 stopBin = 35 modelMode = "simpleBW_Dp" if modelMode == "simpleBW_Dp": Kmass = ptc.parameter(1.414, "KMass") Kwidth = ptc.parameter(.232, "KWidth") Kmass.lock = True Kwidth.lock = True Kstar = ptc.breitWigner([Kmass, Kwidth]) K892Mass = ptc.parameter(.89166, "K892Mass") K892Width = ptc.parameter(.0508, "K902Width") K892Mass.lock = True K892Width.lock = True K892 = ptc.breitWigner([K892Mass, K892Width]) f0Mass = ptc.parameter(.98, "f0Mass") f0Width = ptc.parameter(.1, "f0Width") f0Mass.lock = True f0Width.lock = True f0 = ptc.breitWigner([f0Mass, f0Width]) rhoMass = ptc.parameter(.77526, "rhoMass") rhoWidth = ptc.parameter(.1478, "rhoWidth") rhoMass.lock = True rhoWidth.lock = True rho = ptc.breitWigner([rhoMass, rhoWidth]) f2Mass = ptc.parameter(1.2751, "f2Mass") f2Width = ptc.parameter(.1851, "f2Width") f2Mass.lock = True f2Width.lock = True f2 = ptc.breitWigner([f2Mass, f2Width]) waveModel = { "KpiSright": [Kstar], "KpiPright": [K892], "KpiSwrong": [Kstar], "KpiPwrong": [K892], "piPiS": [f0], "piPiP": [rho], "piPiD": [f2] } uniCOMA = False with root_open(inFileName, "READ") as inFile: histNames = GetKeyNames(inFile) histListReal = [] histListImag = [] histListNorm = [] histListIndx = [] nAmplMax = 0 for sector in sectors: realHistName = sector + "_" + str(tBin) + "_real" histReal = inFile.Get(realHistName) if not histReal: raise IOError("Could not get '" + realHistName + "' from '" + inFileName + "'") histReal.SetDirectory(0) histListReal.append(histReal) imagHistName = sector + "_" + str(tBin) + "_imag" histImag = inFile.Get(imagHistName) if not histImag: raise IOError("Could not get '" + imagHistName + "' from '" + inFileName + "'") histImag.SetDirectory(0) histListImag.append(histImag) normHistName = sector + "_" + str(tBin) + "_norm" histNorm = inFile.Get(normHistName) if not histNorm: raise IOError("Could not get '" + normHistName + "' from '" + inFileName + "'") histNorm.SetDirectory(0) histListNorm.append(histNorm) indexHistName = sector + "_" + str(tBin) + "_index" histIndx = inFile.Get(indexHistName) if not histIndx: raise IOError("Could not get '" + indexHistName + "' from '" + inFileName + "'") histIndx.SetDirectory(0) nAmplMax = max(nAmplMax, int(2 * histIndx.GetMaximum())) histListIndx.append(histIndx) histsToFill = [] comaHists = [] intHistsReal = [] intHistsImag = [] for mBin in range(startBin, stopBin): comaHistName = "COMA_" + str(tBin) + "_" + str(mBin) comaHist = inFile.Get(comaHistName) if not comaHist: raise IOError("Could not load '" + comaHistName + "'") comaHist.SetDirectory(0) comaHists.append(comaHist) ab = allBins(startBin, stopBin, histListReal, histListImag, histListNorm, histListIndx, comaHists, intHistsReal, intHistsImag) with root_open(zeroFileName, "READ") as inFile: zeroCount = 0 zeroHistList = [] eigenHistList = [] while True: zeroName = "zero" + str(zeroCount) + "_" + str(tBin) eigenName = "eigen" + str(zeroCount) + "_" + str(tBin) zeroHist = inFile.Get(zeroName) if not zeroHist: break zeroHist.SetDirectory(0) print "Adding zero-mode" zeroCount += 1 if not zeroForSectors(sectors, zeroHist.GetTitle()): continue zeroHistList.append(zeroHist) eigenHist = inFile.Get(eigenName) eigenHist.SetDirectory(0) if eigenHist: eigenHistList.append(eigenHist) if (not len(eigenHistList) == 0) and (not len(eigenHistList) == len(zeroHistList)): raise ValueError( "Number of eigenvalue histograms does not match, but is also nonzero" ) removeCertainZeroModes(zeroHistList, eigenHistList) for zeroHist in zeroHistList: borders = getZeroHistBorders(zeroHist) ab.addZeroMode(borders, zeroHist) rotateToFourPPampls = False if rotateToFourPPampls: fourPPampls = loadAmplsTM(fourPPamplFileName) ab.removePhases(fourPPampls[tBin][startBin:stopBin]) # ab.rotateToPhaseOfBin(10) zeroModeComaVal = 100. #float(sys.argv[1]) # zeroModeComaVal = 100000. # zeroModeComaVal = "unchanged" # ab.removeZeroModeFromComa() # ab.addComaValueForZeroMode(zeroModeComaVal) # ab.removeGlobalPhaseFromComa() ab.unifyComa() ab.initChi2(waveModel) ab.setMassRanges(sectorRangeMap) totalPars = [] for k in waveModel: for f in waveModel[k]: totalPars += f.getParameters() shapePars = [] if not len(totalPars) == 0 and fitShape: res = scipy.optimize.minimize(ab.chi2, totalPars) hi = res.hess_inv print "m0 = ", res.x[0], "+-", (2 * hi[0, 0])**.5 print "G0 = ", res.x[1], "+-", (2 * hi[1, 1])**.5 print "Giving a Chi2 of:", res.fun shapePars = res.x chi2, params = ab.chi2(shapePars, returnParameters=True) errs = ab.getNonShapeUncertainties(shapePars) paramsZ = ab.linearizeZeroModeParameters(params) zmPar = ab.getNonShapeParameters() ab.setTheoryFromOwnFunctions(params, True) intenses = [] reals = [] imags = [] correl = [] phases = [] intensD = [] realsD = [] imagsD = [] phasesD = [] intensT = [] realsT = [] imagsT = [] phasesT = [] for rh in histListReal: Ih = rh.Clone() Ih.Reset() intenses.append(Ih) realH = rh.Clone() realH.Reset() reals.append(realH) imagH = rh.Clone() imagH.Reset() imags.append(imagH) reImCorrH = rh.Clone() reImCorrH.Reset() correl.append(reImCorrH) phaseH = rh.Clone() phaseH.Reset() phases.append(phaseH) ID = rh.Clone() ID.Reset() intensD.append(ID) rD = rh.Clone() rD.Reset() realsD.append(rD) iD = rh.Clone() iD.Reset() imagsD.append(iD) pD = rh.Clone() pD.Reset() phasesD.append(pD) IT = rh.Clone() IT.Reset() intensT.append(IT) rT = rh.Clone() rT.Reset() realsT.append(rT) iT = rh.Clone() iT.Reset() imagsT.append(iT) pT = rh.Clone() pT.Reset() phasesT.append(pT) zeroP = [0.] * len(paramsZ) # paramsZ = zeroP ab.fillHistograms(paramsZ, intenses) ab.fillHistograms(paramsZ, reals, mode=REAL) ab.fillHistograms(paramsZ, imags, mode=IMAG) ab.fillHistograms(paramsZ, phases, mode=PHASE) ab.fillHistograms(paramsZ, correl, mode=REIMCORRELATION) ab.fillHistograms(zeroP, intensD) ab.fillHistograms(zeroP, realsD, mode=REAL) ab.fillHistograms(zeroP, imagsD, mode=IMAG) ab.fillHistograms(zeroP, phasesD, mode=PHASE) ab.fillHistograms(zeroP, intensT, mode=INTENSTHEO) ab.fillHistograms(zeroP, realsT, mode=REALTHEO) ab.fillHistograms(zeroP, imagsT, mode=IMAGTHEO) ab.fillHistograms(zeroP, phasesT, mode=PHASETHEO) for i in range(len(histListReal)): renormToBinWidth(intenses[i]) renormToBinWidth(intensD[i]) renormToBinWidth(intensT[i]) renormToBinWidth(reals[i], .5) renormToBinWidth(realsD[i], .5) renormToBinWidth(realsT[i], .5) renormToBinWidth(imags[i], .5) renormToBinWidth(imagsD[i], .5) renormToBinWidth(imagsT[i], .5) renormToBinWidth(correl[i], ) allIsZero = True for binX in range(intensT[i].GetNbinsX()): for binY in range(intensT[i].GetNbinsY()): if not intensT[i].GetBinContent(binX + 1, binY + 1) == 0.: allIsZero = False break if not allIsZero: break # # # # # # # # # # # # # # # # # ric = correl[i] noRun = False if not allIsZero: rv = resultViewer([intenses[i], intensD[i], intensT[i]], [reals[i], realsD[i], realsT[i]], [imags[i], imagsD[i], imagsT[i]], [phases[i], phasesD[i], phasesT[i]], startBin=startBin, reImCorrel=ric, noRun=noRun) else: rv = resultViewer([intenses[i], intensD[i]], [reals[i], realsD[i]], [imags[i], imagsD[i]], [phases[i], phasesD[i]], startBin=startBin, reImCorrel=ric, noRun=noRun) rv.titleRight = getProperWaveName(sectors[i]) rv.tString = getProperDataSet(inFileName, tBin) rv.titleFontSize = 11 rv.overrideMassString = "" rv.printLiminary = False rv.topMarginIntens = 1.4 rv.run()
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_corrected.root" # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_std11.root" sectors = [ "2-+0+[pi,pi]0++PiD", "2-+0+[pi,pi]1--PiP", "2-+0+[pi,pi]1--PiF", "2-+0+[pi,pi]2++PiS" ] tBins = [0] startBin = 11 stopBin = 50 methodBinRanges = { "fitF2": (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}^{~}$", "fitRhoP": r"$\text{fit}_\rho^{P}$", "fitRhoF": r"$\text{fit}_\rho^{F}$", "fitBothRho": r"$\text{fit}_\rho^{2}$", "fitF2": r"$\text{fit}_{f_2}$", "smooth": r"smooth" } print "Starting with fixed 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 rhoP" # fixedShapeRhoP = doFixedShapes(inFileName, [sectors[1]], startBin, stopBin, tBins, referenceWave = referenceWave) # allMethods["fixedShapeRhoP"] = fixedShapeRhoP # print "Finished with fixed shape rhoP" # print "Starting with fixed shape rhoF" # fixedShapeRhoF = doFixedShapes(inFileName, [sectors[2]], startBin, stopBin, tBins, referenceWave = referenceWave) # allMethods["fixedShapeRhoF"] = fixedShapeRhoF # print "Finished with fixed shape rhoF" # print "Starting with fixed shape bothRho" # fixedShapeBothRho = doFixedShapes(inFileName, sectors[1:3], startBin, stopBin, tBins, referenceWave = referenceWave) # allMethods["fixedShapeBothRho"] = fixedShapeBothRho # print "Finished with fixed shape bothRho" # print "Starting with fixed shape f2" # fixedShapeF2 = doFixedShapes(inFileName, [sectors[3]], startBin, stopBin, tBins, referenceWave = referenceWave) # allMethods["fixedShapeF2"] = fixedShapeF2 # print "Finished with fixed shape f2" print "Starting with fixed shapes" fixedShapes = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave=referenceWave) allMethods["fixedShapes"] = fixedShapes print "Finished with fixed shapes" fullSig = fixedShapes.getZeroModeSignature() ## 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 rhoP" # fitRhoP = doFitRhoP(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave) # allMethods["fitRhoP"] = fitRhoP # print "Finished with fitting rhoP" # print "Starting with fitting rhoF" # fitRhoF = doFitRhoF(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave) # allMethods["fitRhoF"] = fitRhoF # print "Finished with fitting rhoF" print "Starting with fitting bothRho" fitBothRho = doFitBothRho(inFileName, sectors, startBin, stopBin, tBins, referenceWave=referenceWave) allMethods["fitBothRho"] = fitBothRho print "Finished with fitting bothRho" print "Starting with fitting f2" fitF2 = doFitF2(inFileName, sectors, startBin, stopBin, tBins, referenceWave=referenceWave) allMethods["fitF2"] = fitF2 print "Finished with fitting f2" if stopBin - startBin > 1: print "Starting with smooth" smooth = doSmooth(inFileName, sectors, startBin, stopBin, tBins, referenceWave=referenceWave) allMethods["smooth"] = smooth print "Finished with smooth" if "fixedShapeRhoF" in allMethods: allMethods["fixedShapeRhoF"].setZeroModeSignature(fullSig, 1) if "fitRhoF" in allMethods: allMethods["fitRhoF"].setZeroModeSignature(fullSig, 1) diffsFull, resolvedWA, nonResolvedWA, comps, resDiffs, nonResDiffs, resolvedDiffsFull, noCorrDiffs = cu.doAllComparisons( allMethods, startBin, methodBinRanges) # print resolvedDiffsFull from math import isnan for pair in resolvedDiffsFull: with modernplotting.toolkit.PdfWriter('./resolvedDiffPlots/2mp_' + pair[0] + "_" + pair[1] + ".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() with modernplotting.toolkit.PdfWriter( "compositions_2mp_MC.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]) style.titleRight = r"$2^{-+}0^+$" style.titleLeft = r"Monte Carlo" with modernplotting.toolkit.PdfWriter("studies_2mp.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_2mp.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') 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 + "_2mpMC_" + 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(resolvedWA, s, noRun=True, plotTheory=True) rv.writeBinToPdf(startBin, stdCmd=[ "./comparisonResultsData/" + sect + "_MC_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=[ "", "./comparisonResults/" + sect + "_MC_intens_" + str(b) + ".pdf", intensNames, "./comparisonResults/" + sect + "_MC_argand_" + str(b) + ".pdf", argandNames ]) print studyList
def main(): checkLaTeX() style = modernplotting.mpplot.PlotterStyle() # style.p2dColorMap = 'ocean_r' # style.p2dColorMap = 'YlOrRd' style.p2dColorMap = 'Reds' inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_exotic.root" sectors = ["1-+1+[pi,pi]1--PiP"] tBin = int(sys.argv[1]) if tBin < 0 or tBin > 3: raise ValueError("Invalid t' bin: " + str(tBin)) tBins = [tBin] startBin = 13 stopBin = 50 if len(sys.argv) > 3: startBin = int(sys.argv[2]) stopBin = int(sys.argv[3]) if len(sys.argv) == 4: startBin = int(sys.argv[2]) stopBin = int(sys.argv[3]) acv = 130. # artificial coma value # acv = 1.3e-5 # artificial coma value seedint = randint(0,10000) # startBin = 25 # stopBin = 30 methodBinRanges = { "fitF2" : (22, 50), "fitRhoF" : (22, 50), "fixedShapeF2" : (22, 50)} # methodBinRanges = {} # Override here rhoRange = None for a in sys.argv: if a.startswith("range"): rhoRange = float(a[5:]) sectorRangeMap = {"1++0+[pi,pi]1--PiS":(0.,rhoRange)} sectorRangeMap = {} # sectorRangeMap = {"1-+1+[pi,pi]1--PiP":(0.,1.2)} fixSectorRangeMap = {"1-+1+[pi,pi]1--PiP":(0.,1.12)} allMethods = {} methodStrings = {} shortlabels = { "fixedShapeF0" : r"$\text{fix}_{f_0}^{~}$", "fixedShapeRhoP" : r"$\text{fix}_\rho^{P}$", "fixedShapeRhoF" : r"$\text{fix}_\rho^{F}$", "fixedShapeBothRho" : r"$\text{fix}_\rho^{2}$", "fixedShapeF2" : r"$\text{fix}_{f_2}$", "fixedShapes" : r"$\text{fix}_\text{all}^{~}$", "pipiS" : r"$\phi_{[\pi\pi]_S}^{~}$", "fitRho" : r"$\text{fit}_\rho$", "fitRhoP" : r"$\text{fit}_\rho^{P}$", "fitRhoF" : r"$\text{fit}_\rho^{F}$", "fitBothRho" : r"$\text{fit}_\rho^{2}$", "fitF2" : r"$\text{fit}_{f_2}$", "smooth" : r"smooth"} # # - - - - --- Start here with the model builtind --- - - - - # # rhoRe0 = 0.579053 rhoIm0 = 0.109177 rhoMass = ptc.parameter(mRho, "rho_mass") rhoWidth = ptc.parameter(Grho, "rho_width") rho = ptc.relativisticBreitWigner([rhoMass,rhoWidth], mPi, mPi, mPi, 1, 1, False) poleReal = ptc.parameter(rhoRe0, "rhoRe") poleImag = ptc.parameter(rhoIm0, "rhoIm") nPol = 1 for a in sys.argv: if a.startswith("nPol"): nPol = int(a[4:]) polyDeg_po = 8 for a in sys.argv: if a.startswith("pdpo"): polyDeg_po = int(a[4:]) params = [poleReal,poleImag] for i in range(1, nPol): rePol = ptc.parameter(1.96, "polRe_"+str(i)) imPol = ptc.parameter(0.28, "polIm_"+str(i)) params.append(rePol) params.append(imPol) for d in range(polyDeg_po): params.append(ptc.parameter(2.*random()-1., "c_"+str(d))) Kmatrix = ptc.simpleOneChannelKmatrix(params, nPol, polyDeg_po, 4*mPi**2) useCM = False for a in sys.argv: if a == "CM": useCM = True if a == "rho": useCM = False Kmatrix.use_CM = useCM pPolyDeg3 = 7 pPolyDeg2 = 4 for a in sys.argv: if a.startswith("m3pol"): pPolyDeg3 = int(a[5:]) if a.startswith("m2pol"): pPolyDeg2 = int(a[5:]) params = [] for d in range(pPolyDeg2): for e in range(pPolyDeg3+1): params.append(ptc.parameter(2.*random()-1., "c_"+str(d+1)+"_"+str(e))) pPoly = ptc.twoDimensionalRealPolynomial(pPolyDeg2, pPolyDeg3, params, baseExponent = 2) # baseExponent = 2: polynomial in s func = ptc.multiply([Kmatrix, pPoly]) model = [func] # model = [rho] # # - - - - --- Stop the model building here --- - - - - # # zeroModeParameters = None fixZeroMode = True if fixZeroMode: fixedShapes = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, acv = acv, sectorRangeMap = fixSectorRangeMap) zeroModeParameters = fixedShapes.getZeroModeParametersForMode() # RV = fixedShapes.produceResultViewer(zeroModeParameters,"1-+1+[pi,pi]1--PiP", noRun = True, plotTheory = True) # RV.plotData = True # for b in range(startBin, stopBin): # plotNameBase = "./Kmatrix_plots/1mp1p1mmPiP_<mode>_"+str(b)+"_"+str(tBin)+".pdf" # RV.writeBinToPdf(b, stdCmd = ["", plotNameBase.replace("<mode>","intens"), [], plotNameBase.replace("<mode>","argand"), []]) # return if useCM: ps = "CM" else: ps = "rho" if rhoRange is None: rrs = "" else: rrs = "range"+str(rhoRange)+'_' if nPol == 1: nps = "" else: nps = "nPol"+str(nPol)+"_" resultFile = "./KmatrixResults/1mp_Kmatrix_"+rrs+nps+ps+"_kPol"+str(polyDeg_po-1)+"_pPol"+str(pPolyDeg3)+"-"+str(pPolyDeg2)+"_t"+str(tBin)+"_m"+str(startBin)+'-'+str(stopBin)+'_'+str(seedint)+".dat" fitter = doFunctionFit(inFileName, model, startBin, stopBin, tBins, sectorRangeMap, referenceWave = referenceWave, acv = acv, zeroModeParameters = zeroModeParameters, writeResultToFile = resultFile) rhoFitter = doFunctionFit(inFileName, [rho], startBin, stopBin, tBins, fixSectorRangeMap, referenceWave = referenceWave, acv = acv, zeroModeParameters = zeroModeParameters, writeResultToFile = None) BWfitString = "BW_fit_result: " + str(rhoMass.value) + " " +str(rhoMass.error) + " " + str(rhoWidth.value) + " " + str(rhoWidth.error) # # - - - - --- Start the evaluations here --- - - - - # # nBinsPlot = 1000 def fPlot(v): return v.imag # hist = pyRootPwa.ROOT.TH2D("hhh","hhh", nBinsPlot, -.25, 6.25,nBinsPlot, -1., 1.) # for iX in range(nBinsPlot): # x = hist.GetXaxis().GetBinCenter(iX+1) # for iY in range(nBinsPlot): # y = hist.GetYaxis().GetBinCenter(iY+1) # s = x+1.j*y # val = Kmatrix.complexCall(s) # hist.SetBinContent(iX+1, iY+1,fPlot(val)) # hist.Draw("COLZ") # raw_input("press <enter> to go to the secont sheet") Kmatrix.secondSheet = True # for iX in range(nBinsPlot): # x = hist.GetXaxis().GetBinCenter(iX+1) # for iY in range(nBinsPlot): # y = hist.GetYaxis().GetBinCenter(iY+1) # s = x+1.j*y # val = Kmatrix.complexCall(s) # hist.SetBinContent(iX+1, iY+1, fPlot(val)) # hist.Draw("COLZ") res = scipy.optimize.minimize(Kmatrix.absInverse,[rhoRe0,rhoIm0]) print res.x,"pole position" mfv = res.fun resSting = str(res.fun)+ " function value should be zero" print resSting BWstring = "BW par: "+str(abs(res.x[0])**.5)+" "+str(abs(res.x[1])/abs(res.x[0])**.5)+" (all absolute values)" print BWstring with open(resultFile,'a') as outFile: outFile.write('\n'+BWstring+" "+resSting) print "= = = = = = = = = Starting BW error ersimation = = = = = = = = = " nPoints = 1000 poleMean = res.x poleSamples = [] i = 0 failCount = 0 while i < nPoints: pts = np.random.multivariate_normal(fitter.fitParameters, fitter.MINUITcoma) fitter.MINUIT_function(pts) # Call the function once to set parameters inside # fitter.model[0].setParametersAndErrors(pts, fitter.MINUITerrs) res = scipy.optimize.minimize(Kmatrix.absInverse,poleMean) if abs(res.fun) > 100*mfv: print "No more pole found (mfv = "+str(mfv)+") : fval = "+str(res.fun) failCount += 1 if failCount > nPoints: print "Failed to find poles too often.... abort" return continue # raise ValueError("No more pole found: fval = "+str(res.fun)) poleSamples.append(res.x) i+=1 print i,"Marker to find the PRINT 57473M3N7" meanPole = [0.,0.] for p in poleSamples: meanPole[0] += p[0] meanPole[1] += p[1] meanPole[0] /= len(poleSamples) meanPole[1] /= len(poleSamples) poleComa = [[0.,0.],[0.,0.]] for p in poleSamples: poleComa[0][0] += (p[0]-meanPole[0])**2 poleComa[0][1] += (p[0]-meanPole[0])*(p[1]-meanPole[1]) poleComa[1][0] += (p[1]-meanPole[1])*(p[0]-meanPole[0]) poleComa[1][1] += (p[1]-meanPole[1])**2 poleComa[0][0] /= len(poleSamples)-1 poleComa[0][1] /= len(poleSamples)-1 poleComa[1][0] /= len(poleSamples)-1 poleComa[1][1] /= len(poleSamples)-1 comaString = str(poleComa) print " - - - - - - le compaire pramaitre - - - - - - " print meanPole, poleMean print " - - - - - - le compaire pramaitre - - - - - - " print poleComa print "= = = = = = = = = Finished BW error ersimation = = = = = = = = = " mRhoP = 1.4 GrhoP = .2 res = scipy.optimize.minimize(Kmatrix.absInverse,[mRhoP**2,mRhoP*GrhoP]) print res.x,"pole position" resSting = str(res.fun)+ " function value should be zero" print resSting BWstring = "BW' par: "+str(abs(res.x[0])**.5)+" "+str(abs(res.x[1])/abs(res.x[0])**.5)+" (all absolute values)" print BWstring with open(resultFile,'a') as outFile: outFile.write('\n'+BWstring+" "+resSting+"\ncoma "+comaString) outFile.write('\n'+BWfitString) # # - - - - --- Start the evaluations here --- - - - - # # doPlots = False if doPlots: RV = fitter.produceResultViewer(zeroModeParameters,"1-+1+[pi,pi]1--PiP", noRun = True, plotTheory = True) RV.plotData = True for b in range(startBin, stopBin): plotNameBase = "./Kmatrix_plots/1mp1p1mmPiP_<mode>_"+str(b)+"_"+str(tBin)+".pdf" RV.writeBinToPdf(b, stdCmd = ["", plotNameBase.replace("<mode>","intens"), [], plotNameBase.replace("<mode>","argand"), []]) # raw_input("press <enter> to exit") return ################################################################################# ################################################################################# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### # ################################################################################# ################################################################################# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### # ################################################################################# ################################################################################# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### # ################################################################################# ################################################################################# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### # ################################################################################# ################################################################################# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### # ################################################################################# ################################################################################# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### # ################################################################################# ################################################################################# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### # ################################################################################# ################################################################################# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### # ################################################################################# ################################################################################# # The stuff down here does not matter at the moment # polDeg = 2 outFileName = "./pietarinenFits/polyDeg"+str(polDeg)+"_t"+str(tBin)+".txt" piet = doPietarinen(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, polDeg = polDeg, polDeg3Pi = 2, writeResultToFile = outFileName, sectorRangeMap = sectorRangeMap, acv = acv, zeroModeParameters = zeroModeParameters) if not fixZeroMode: zeroModeParameters = piet.getZeroModeParametersForMode() RV = piet.produceResultViewer(zeroModeParameters,"1-+1+[pi,pi]1--PiP", noRun = True, plotTheory = True) RV.plotData = True for b in range(startBin, stopBin): plotNameBase = "./pietarinenFits/1mp1p1mmPiP_<mode>_"+str(b)+"_"+str(tBin)+".pdf" RV.writeBinToPdf(b, stdCmd = ["", plotNameBase.replace("<mode>","intens"), [], plotNameBase.replace("<mode>","argand"), []]) # doFitRho(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, writeResultToFile = "rhoMassesAndWidths_1-+1+1--_global.dat", sectorRangeMap = sectorRangeMap, acv = acv, polDeg = polDeg) return print "Starting with fixed shapes" fixedShapes = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, acv = acv, sectorRangeMap = sectorRangeMap) allMethods["fixedShapes"] = fixedShapes print "Finished with fixed shapes" # print "Starting with fitting rho" # fitRho = doFitRho(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, writeResultToFile = "rhoMassesAndWidths_1-+1+1--_global.dat", sectorRangeMap = sectorRangeMap, acv = acv) # allMethods["fitRho"] = fitRho # print "Finished with fitting rho" # if stopBin - startBin > 1: # print "Starting with smooth" # smooth = doSmooth(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave) # allMethods["smooth"] = smooth # print "Finished with smooth" if "fixedShapeRhoF" in allMethods: allMethods["fixedShapeRhoF"].setZeroModeSignature(fullSig,1) if "fitRhoF" in allMethods: allMethods["fitRhoF"].setZeroModeSignature(fullSig,1) # diffsFull, resolvedWA, nonResolvedWA, comps, resDiffs, nonResDiffs, resolvedDiffsFull,noCorrDiffs = cu.doAllComparisons(allMethods, startBin, methodBinRanges, noBelowZero = True) # print resolvedDiffsFull # from math import isnan # for pair in resolvedDiffsFull: # with modernplotting.toolkit.PdfWriter('./resolvedDiffPlots/1mp_'+pair[0]+"_"+pair[1]+"_"+str(tBin)+".pdf") as pdfOutput: # plot = style.getPlot1D() # line = [0.000000001]*len(resolvedDiffsFull[pair][0]) # line2 = [0.000000001]*len(resolvedDiffsFull[pair][0]) # one = [1.]*len(resolvedDiffsFull[pair][0]) # xAxis = [ .5 + 0.04*(startBin + i) for i in range(len(resolvedDiffsFull[pair][0]))] # for i,v in enumerate(resolvedDiffsFull[pair][0]): # if not isnan(v) and not v <= 0.: # line[i] = v # else: # line[i] = 0.000000001 # # if not pair[1] == "WAres" and not pair[1] == "WAnon": # for i,v in enumerate(resolvedDiffsFull[pair[1],pair[0]][0]): # if not isnan(v) and not v <= 0.: # line2[i] = v # else: # line2[i] = 0.000000001 # # plot.setYlog() # plot.plot(xAxis, line) # plot.plot(xAxis, one) # plot.plot(xAxis, line2) # plot.setYlim(0.00001, 10000) # plot.finishAndSaveAndClose(pdfOutput) # studyList = [] # for m in allMethods: # studyList.append(m) # studyList.sort() style.titleRight = r"$1^{-+}1^+$" style.titleLeft = LaTeX_strings.tBins[tBin] # with modernplotting.toolkit.PdfWriter("compositions_1mp_"+str(tBin)+".pdf") as pdfOutput: # plot = style.getPlot1D() # for m in studyList: # line = [0.]*len(comps[m][0]) # xAxis = [ .5 + 0.04*(startBin + i) for i in range(len(comps[m][0]))] # break # count = 0 # for m in studyList: # newLine = line[:] # for i in range(len(comps[m][0])): # newLine[i] += comps[m][0][i] # plot.axes.fill_between(xAxis, line, newLine, facecolor = modernplotting.colors.makeColorLighter(modernplotting.colors.colorScheme.blue, 0.1*count)) # count += 1 # line = newLine # plot.setYlim(0.,1.) # plot.setXlim(xAxis[0], xAxis[-1]) # plot.finishAndSaveAndClose(pdfOutput) # hist = pyRootPwa.ROOT.TH2D("hist","hist", len(studyList)+2, 0, len(studyList)+2, len(studyList), 0, len(studyList)) # # for i,m in enumerate(studyList): # for j,n in enumerate(studyList): # hist.SetBinContent(i+1, j+1, diffsFull[n,m]) # for i,m in enumerate(studyList): # hist.SetBinContent(len(studyList)+1, i+1, noCorrDiffs[m]) # hist.SetBinContent(len(studyList)+2, i+1, resDiffs[m]) # # axolotl = [] # for i,study in enumerate(studyList): # axolotl.append(shortlabels[study]) # axolotl.append(alphabet[i]) # with modernplotting.toolkit.PdfWriter("studies_1mp_"+str(tBin)+".pdf") as pdfOutput: # plot = style.getPlot2D() # plot.axes.get_xaxis().set_ticks([(i + 0.5) for i in range(len(studyList)+2)]) # plot.axes.get_yaxis().set_ticks([(i + 0.5) for i in range(len(studyList) )]) # studyPlotter.makeValuePlot(plot, hist) # # plot.axes.set_yticklabels(axolotl) # axolotl.append(unCorrected_string) # axolotl.append(weightedAVG_string) # plot.axes.set_xticklabels(axolotl, rotation = 90) # plot.setZlim((0.,1.)) # # plot.finishAndSaveAndClose(pdfOutput) # with open("studies_1mp_"+str(tBin)+".txt",'w') as out: # for axl in axolotl: # out.write(axl + ' ') # out.write("\n") # for i in range(hist.GetNbinsX()): # for j in range(hist.GetNbinsY()): # out.write(str(hist.GetBinContent(i+1, j+1)) + ' ') # out.write('\n') doRhoFits = False writeCpls = False if writeCpls: outFileCpl = open("1mp_rho_cpls_"+str(tBin)+".dat",'w') doActuallyNotFit = True if doRhoFits: with open("rhoMassesAndWidths_exotic_"+str(tBin)+".dat",'w') as out: for i in range(stopBin-startBin): binIndex = i+startBin out.write(str(binIndex)+' '+str(0.52 + 0.04*binIndex)+' ') startValueOffset = 0.00 if doActuallyNotFit: print "The fit has been turned off, due to a workaround... :(" else: exceptCount = 0 try: x,err,c2,ndf = fitRho.fitShapeParametersForBinRange([mRho+startValueOffset,Grho+startValueOffset], [0],[i], zeroModeParameters = resolvedWA) except: print "Fitter exception encountered" startValueOffset += 0.001 exceptCount += 1 if exceptCount > 3: raise Exception("Too many failed attempts: "+str(exceptCount)) out.write(str(x[0]) + ' ' + str(err[0]) + ' ' + str(x[1]) + ' ' + str(err[1])) out.write(' '+str(c2/ndf)+'\n') if writeCpls: fitRho.calculateNonShapeParametersForZeroModeParameters(resolvedWA) cpl, hess = fitRho.getCouplingParameters() hessInv = la.inv(hess[0][i]) if not len(cpl[0][1]) == 2: raise IndexError("Parameter count not 2, change implementation") integral = fitRho.model[0][i].getIntegralForFunction(0, fitRho.model[0][i].funcs[0][0]) outFileCpl.write(str(0.52 + binIndex*.04) + ' ' + str(cpl[0][i][0]**2 + cpl[0][i][0]**2) + ' ' + str(integral) + ' ') outFileCpl.write(str(cpl[0][i][0]) + ' ' + str(cpl[0][i][1]) + ' ') outFileCpl.write(str(hessInv[0][0]/2) + ' ' + str(hessInv[1][1]/2) + ' ' + str(hessInv[0][1]/2)) outFileCpl.write("\n") makeRhoFitPlots = False if makeRhoFitPlots: fitRho.calculateNonShapeParametersForZeroModeParameters(resolvedWA) rhoRV = fitRho.produceResultViewer(resolvedWA,"1-+1+[pi,pi]1--PiP", noRun = True, plotTheory = True) rhoRV.plotData = True plotNameBase = "./rhoFitPlots/1mp1p1mmPiP_<mode>_"+str(binIndex)+"_"+str(tBin)+".pdf" rhoRV.writeBinToPdf(binIndex, stdCmd = ["", plotNameBase.replace("<mode>","intens"), [], plotNameBase.replace("<mode>","argand"), []]) if writeCpls: outFileCpl.close() return ##### Writing starts here # fileNames = {} # fixedShapes.removeZeroModeFromComa() ## binRange = {"1-+1+[pi,pi]1--PiP": (10,22)} # totalHists = fixedShapes.getTotalHists(resolvedWA, binRange = binRange) # with root_open("./totals_1mp_rhoRange.root", "UPDATE") as out: # for t in totalHists: # for m in t: # m.Write() # return # for stu in allMethods: # print "Writing for '" + stu + "'" # for s, sect in enumerate(allMethods[stu].sectors): # if stu == "pipiS": # rv = allMethods[stu].produceResultViewer(allMethods[stu].getZeroModeParametersForMode(),s, plotTheory = True) # rv.run() # rv = allMethods[stu].produceResultViewer(allMethods[stu].getZeroModeParametersForMode(),s, noRun = True) # for bin in range(startBin, stopBin): # fileName = "./collectedMethods/"+stu+"_"+sect+"_1mpData_"+str(bin) # if not (sect,bin) in fileNames: # fileNames[sect,bin] = [] # fileNames[sect,bin].append(fileName) # rv.writeAmplFiles(bin, fileName = fileName) scalle = False if scalle: folder = "./comparisonResultsData_1mp_scale/" else: folder = "./comparisonResultsData_1mp/" fixedShapesFull = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, acv = acv) for s, sect in enumerate(allMethods['fixedShapes'].sectors): # allMethods['fixedShapes'].removeZeroModeFromComa() # allMethods['fixedShapes'].removeGlobalPhaseFromComa() rv = fixedShapesFull.produceResultViewer(allMethods['fixedShapes'].getZeroModeParametersForMode(),s, noRun = True, plotTheory = True) # rv.plotData = False rv.writeBinToPdf(startBin, stdCmd = [ folder + sect + "_data_2D_"+str(tBin)+".pdf", "", [], "", []]) # rv.labelPoints = [0,10,15,20] # rv.makeLegend = True if scalle: rv.scaleTo = "maxCorrData" # rv.yAxisShift = 300. # rv.tStringYpos = 0.8 # rv.topMarginIntens = 1.4 # fakkkk = 1. else: rv.plotData = False # fakkkk = .7 # rv.tStringYpos = 0.865 # rv.topMarginIntens = 1.3 # rv.yAxisShift = 100. # rv.shiftMap = {0:(fakkkk*50.,fakkkk*-280.),10:(fakkkk*-420.,fakkkk*-50.), 15:(fakkkk*-420.,fakkkk*-30.), 20:(fakkkk*-50.,fakkkk*70.)} for b in range(startBin, stopBin): # if not bin == 27: # continue # intensNames = [name+".intens" for name in fileNames[sect,b]] # argandNames = [name+".argand" for name in fileNames[sect,b]] # intensNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/evalDima/dima.intens"] # argandNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/evalDima/dima.argand"] # if not scalle: if True: intensNames = [] argandNames = [] # rv.plotData = True rv.writeBinToPdf(b, stdCmd = ["", folder + sect + "_data_intens_"+str(b)+"_"+str(tBin)+".pdf", intensNames, folder + sect + "_data_argand_"+str(b)+"_"+str(tBin)+".pdf", argandNames]) rv.wiriteReImToPdf(b, folder + sect + "_data_<ri>_"+str(b)+"_"+str(tBin)+".pdf")
def main(): checkLaTeX() style = modernplotting.mpplot.PlotterStyle() # style.p2dColorMap = 'ocean_r' # style.p2dColorMap = 'YlOrRd' style.p2dColorMap = 'Reds' inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_exotic.root" sectors = ["1-+1+[pi,pi]1--PiP"] tBin = int(sys.argv[1]) if tBin < 0 or tBin > 3: raise ValueError("Invalid t' bin: " + str(tBin)) writeCpls = False twoDmarkPlots = False scalle = False Xcheck = False globalScale = False setRanges = False writeROOT = False rangeMin = 0. rangeMax = 1.12 startBin = 11 stopBin = 50 acv = 1.3e-2 for i in range(2,len(sys.argv)): a = sys.argv[i] if a == "-scale": scalle = True elif a == "-2Dmark": twoDmarkPlots = True elif a == "-Xcheck": Xcheck = True elif a == "-cpls": writeCpls = True elif a == "-global": globalScale = True elif a.startswith("-rangeMin"): setRanges = True rangeMin = float(a[9:]) elif a.startswith("-rangeMax"): setRanges = True rangeMax = float(a[9:]) elif a.startswith("-start"): startBin = int(a[6:]) elif a.startswith("-stop"): stopBin = int(a[5:]) elif a == "-ROOT": writeROOT = True elif a.startswith("-acv"): acv = float(a[4:]) else: raise RuntimeError("Could not parse option '" + a + "'") print "-------------------------------" print "tbin",tBin print"(startBin,stopBin) (",startBin,",",stopBin,")" print "writeCpls",writeCpls print "scale", scalle print "2Dmarks",twoDmarkPlots print "Xcheck",Xcheck print "globalScale",globalScale print "fitRange ("+str(rangeMin)+","+str(rangeMax)+")" print "writeROOT",writeROOT print "acv",acv print "-------------------------------" tBins = [tBin] # acv = None # acv = 130. # artificial coma value # acv = 1.3e-3 # artificial coma value methodBinRanges = { "fitF2" : (22, 50), "fitRhoF" : (22, 50), "fixedShapeF2" : (22, 50)} # methodBinRanges = {} # Override here sectorRangeMap = {"1-+1+[pi,pi]1--PiP":(rangeMin, rangeMax)} # sectorRangeMap = {} allMethods = {} methodStrings = {} shortlabels = { "fixedShapeF0" : r"$\text{fix}_{f_0}^{~}$", "fixedShapeRhoP" : r"$\text{fix}_\rho^{P}$", "fixedShapeRhoF" : r"$\text{fix}_\rho^{F}$", "fixedShapeBothRho" : r"$\text{fix}_\rho^{2}$", "fixedShapeF2" : r"$\text{fix}_{f_2}$", "fixedShapes" : r"$\text{fix}_\text{all}^{~}$", "pipiS" : r"$\phi_{[\pi\pi]_S}^{~}$", "fitRho" : r"$\text{fit}_\rho$", "fitRhoP" : r"$\text{fit}_\rho^{P}$", "fitRhoF" : r"$\text{fit}_\rho^{F}$", "fitBothRho" : r"$\text{fit}_\rho^{2}$", "fitF2" : r"$\text{fit}_{f_2}$", "smooth" : r"smooth"} print "Starting with fixed shapes" fixedShapes = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, sectorRangeMap = sectorRangeMap, acv = acv) allMethods["fixedShapes"] = fixedShapes print "Finished with fixed shapes" fullSig = fixedShapes.getZeroModeSignature() fullRanges = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, sectorRangeMap = {}, acv = acv) zeroModeParameters = fixedShapes.getZeroModeParametersForMode() doRhoFits = False if setRanges: rangeString = "_rangeMin"+str(rangeMin)+"_rangeMax"+str(rangeMax) if writeCpls: print fixedShapes.nonShapeParameters print "Writing couplings..." fixedShapes.calculateNonShapeParametersForZeroModeParameters(zeroModeParameters) outFileCpl = open("./cplFiles/1mp_rho_cpls"+rangeString+"_"+str(tBin)+".dat",'w') cpl, hess = fixedShapes.getCouplingParameters() if not len(cpl[0][0]) == 2: raise IndexError("Parameter count not 2, change implementation") for i in range(stopBin-startBin): binIndex = i+startBin hessInv = la.inv(hess[0][i]) integral = fixedShapes.model[0][i].getIntegralForFunction(0, fixedShapes.model[0][i].funcs[0][0]) outFileCpl.write(str(0.52 + binIndex*.04) + ' ' + str(cpl[0][i][0]**2 + cpl[0][i][0]**2) + ' ' + str(integral) + ' ') outFileCpl.write(str(cpl[0][i][0]) + ' ' + str(cpl[0][i][1]) + ' ') outFileCpl.write(str(hessInv[0][0]/2) + ' ' + str(hessInv[1][1]/2) + ' ' + str(hessInv[0][1]/2)) outFileCpl.write("\n") outFileCpl.close() return doActuallyNotFit = False if doRhoFits: fitRho = doFitRho(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, writeResultToFile = "rhoMassesAndWidths_1-+1+1--_global.dat", sectorRangeMap = sectorRangeMap, acv = acv) fitRho.initMinuitFunction(fitRho.getParameters()) with open("rhoMassesAndWidths_exoticForPaper_"+str(tBin)+".dat",'w') as out: for i in range(stopBin-startBin): binIndex = i+startBin out.write(str(binIndex)+' '+str(0.52 + 0.04*binIndex)+' ') startValueOffset = 0.00 if doActuallyNotFit: print "The fit has been turned off, due to a workaround... :(" else: exceptCount = 0 # try: if True: x,err,c2,ndf = fitRho.fitShapeParametersForBinRange([mRho+startValueOffset,Grho+startValueOffset], [0],[i], zeroModeParameters = zeroModeParameters) # except: # print "Fitter exception encountered" # startValueOffset += 0.001 # exceptCount += 1 # if exceptCount > 3: # raise Exception("Too many failed attempts: "+str(exceptCount)) out.write(str(x[0]) + ' ' + str(err[0]) + ' ' + str(x[1]) + ' ' + str(err[1])) out.write(' '+str(c2/ndf)+'\n') if writeCpls: fitRho.calculateNonShapeParametersForZeroModeParameters(zeroModeParameters) cpl, hess = fitRho.getCouplingParameters() hessInv = la.inv(hess[0][i]) if not len(cpl[0][1]) == 2: raise IndexError("Parameter count not 2, change implementation") integral = fitRho.model[0][i].getIntegralForFunction(0, fitRho.model[0][i].funcs[0][0]) outFileCpl.write(str(0.52 + binIndex*.04) + ' ' + str(cpl[0][i][0]**2 + cpl[0][i][0]**2) + ' ' + str(integral) + ' ') outFileCpl.write(str(cpl[0][i][0]) + ' ' + str(cpl[0][i][1]) + ' ') outFileCpl.write(str(hessInv[0][0]/2) + ' ' + str(hessInv[1][1]/2) + ' ' + str(hessInv[0][1]/2)) outFileCpl.write("\n") makeRhoFitPlots = False if makeRhoFitPlots: fitRho.calculateNonShapeParametersForZeroModeParameters(zeroModeParameters) rhoRV = fitRho.produceResultViewer(zeroModeParameters,"1-+1+[pi,pi]1--PiP", noRun = True, plotTheory = True) rhoRV.plotData = True plotNameBase = "./rhoFitPlots/1mp1p1mmPiP_<mode>_"+str(binIndex)+"_"+str(tBin)+".pdf" rhoRV.writeBinToPdf(binIndex, stdCmd = ["", plotNameBase.replace("<mode>","intens"), [], plotNameBase.replace("<mode>","argand"), []]) if writeCpls: outFileCpl.close() return if (twoDmarkPlots and scalle) or (twoDmarkPlots and Xcheck): raise Exception("'twoDmarkPlots' only allowed without 'scalle' and 'Xcheck'") folderAddString = "" if scalle: folderAddString += "_scale" if Xcheck: folderAddString += "_Xcheck" if globalScale: folderAddString += "_global" # folder = "./ellipseComparisons/" folder = "./forPaper"+folderAddString+"/" if setRanges: folder = "./exoticFitPlots_ranges/" intensYlimFileName = "./intensYlims" arangdLimitsFileName = "./argandLims" if scalle: intensYlimFileName += "_scale" arangdLimitsFileName += "_scale" intensScales = loadLimits(intensYlimFileName, tBin) argandScales = loadLimits(arangdLimitsFileName, tBin) if globalScale: globalScales = { 0: ( [9808549.03133*.9] ,[ -1176.89018363 , 2583.08091376 , -963.530201342 , 2764.05317273 ]), 1: ( [6250000.00 ] ,[ -1000. , 2311.5523738 , -950. , 2400. ]), # 1: ( [15692071.5541] ,[ -2953.09588149 , 2311.5523738 , -1069.36767067 , 3461.97833088 ]), 2: ( [5984192.64568*13.5/15.] ,[ -1000.84212555 , 1893.32841381 , -652.0 , 2498.12259086 ]), 3: ( [3693705.14722*16.5/18.5] ,[ -1259.93088183 , 1277.85363449 , -404.005733504 , 1956.63757019 ])} for i in range(startBin, stopBin): intensScales[i] = globalScales[tBin][0] argandScales[i] = globalScales[tBin][1] fileSectorName = "1mp1p1mmP" if setRanges: fileSectorName += rangeString fullRanges.nonShapeParameters = fixedShapes.nonShapeParameters totalsAndNevents = getTotalAndNevents() for s, sect in enumerate(fullRanges.sectors): fullRanges.removeZeroModeFromComa() # rv = fullRanges.produceResultViewer(cloneZeros(zeroModeParameters),s, noRun = True, plotTheory = True) rv = fullRanges.produceResultViewer(zeroModeParameters,s, noRun = True, plotTheory = True) if writeROOT: rv.writeToRootFile(fileSectorName+".root") return # rv.writeToRootFile("exoticForRealease_"+str(tBin)+".root") rv.checkArgandRanges = False rv.intYaxisXpos = -0.15 rv.argYaxisXpos = -0.145 rv.intensLims = intensScales rv.argandLims = argandScales rv.arrowsToTheo = [14] rv.titleFontSize = 11 rv.showColorBar = True rv.XcheckArgand = Xcheck rv.writeBinToPdf(startBin, stdCmd = [ fileSectorName + "_2D_t"+str(tBin)+".pdf", "", [], "", []]) # continue if twoDmarkPlots: rv.mark2DplotColor = modernplotting.colors.colorScheme.red rv.labelPoints = [0,10,15,20] if tBin in [0,1,2] and not scalle: rv.labelPoints = [10,15,20] rv.labelPoints = [] rv.makeLegend = True if scalle: rv.scaleTo = "maxCorrData" rv.yAxisShift = 300. rv.tStringYpos = 0.8 # 0.8, if third legend item rv.topMarginIntens = 1.4 fakkkk = 1. else: rv.plotData = False fakkkk = .7 rv.tStringYpos = 0.87 # 0.8, if third legend item rv.topMarginIntens = 1.4 rv.yAxisShift = 100. # rv.scaleArgandZeroLine = 0.8 if twoDmarkPlots: rv.tStringYpos = 0.94 if Xcheck: rv.tStringYpos = 0.8 # 0.8, if third legend item rv.addiColor = modernplotting.colors.makeColorLighter(modernplotting.colors.colorScheme.blue, .5) rv.realLabel = LaTeX_strings.realReleaseNote rv.imagLabel = LaTeX_strings.imagReleaseNote rv.m2PiString = LaTeX_strings.m2PiReleaseNote rv.intensLabel = LaTeX_strings.intensReleaseNote if not Xcheck: rv.printLiminary = True else: rv.connectAddGraphs = [(0,1),(2,3)] rv.xLims = (.2,2.2) if tBin == 3: if scalle: rv.shiftMap = {0:(fakkkk*80.,fakkkk*-280.),10:(fakkkk*-360.,fakkkk*-50.), 15:(fakkkk*-390.,fakkkk*-30.), 20:(fakkkk*-500.,fakkkk*-10.)} else: rv.shiftMap = {0:(fakkkk*100.,fakkkk*-280.),10:(fakkkk*-370.,fakkkk*-50.), 15:(fakkkk*-370.,fakkkk*-30.), 20:(fakkkk*-50.,fakkkk*90.)} if tBin == 2: if scalle: rv.shiftMap = {0:(fakkkk*50.,fakkkk*-300.),10:(fakkkk*-480.,fakkkk*-50.), 15:(fakkkk*-500.,fakkkk*-30.), 20:(fakkkk*0.,fakkkk*70.)} else: rv.shiftMap = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-420.,fakkkk*-50.), 15:(fakkkk*-450.,fakkkk*-30.), 20:(fakkkk*0.,fakkkk*70.)} if tBin == 1: if scalle: rv.shiftMap = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-300.,fakkkk*-50.), 15:(fakkkk*-400.,fakkkk*-30.), 20:(fakkkk*60.,fakkkk*30.)} else: rv.shiftMap = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-350.,fakkkk*-50.), 15:(fakkkk*-400.,fakkkk*-30.), 20:(fakkkk*80.,fakkkk*30.)} if tBin == 0: if scalle: rv.shiftMap = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-450.,fakkkk*-50.), 15:(fakkkk*-450.,fakkkk*-30.), 20:(fakkkk*50.,fakkkk*30.)} else: rv.shiftMap = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-410.,fakkkk*-50.), 15:(fakkkk*-420.,fakkkk*-30.), 20:(fakkkk*70.,fakkkk*30.)} if not twoDmarkPlots: rv.scale(1000./40.) rv.writeBinToPdf(startBin, stdCmd = [folder + fileSectorName + "_2D_t"+str(tBin)+".pdf","", [], "",[]]) for b in range(startBin, stopBin): # intensNames = [name+".intens" for name in fileNames[sect,b]] # argandNames = [name+".argand" for name in fileNames[sect,b]] print "Writing bin",b rv.rightString = "{:.1f}\%".format(100*totalsAndNevents[(tBin, b)][0]/totalsAndNevents[(tBin, b)][1]) if not scalle: intensNames = [] argandNames = [] # intensNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/singlePlots/1mp1p1mm_t"+str(tBin)+".intens"] # argandNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/singlePlots/1mp1p1mm_t"+str(tBin)+".argand"] intensNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/zeroModeFitter_2D/filesForRelease/fullRangeFixing_"+str(tBin)+".intens"] argandNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/zeroModeFitter_2D/filesForRelease/fullRangeFixing_"+str(tBin)+".argand"] intensNames = [] argandNames = [] if Xcheck: intensNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/singlePlots/intensPlots/1mp1p1mm_m"+str(b)+"_t"+str(tBin)+".intens"] argandBaseName = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/singlePlots/dimasEllipses/1mp1p1mm_"+str(b)+"_"+str(tBin)+"_<ndx>.argand" argandNames = [argandBaseName.replace("<ndx>", ndx) for ndx in ['0','1','2','3','C']] # print argandNames # return for fn in intensNames: if not os.path.isfile(fn): raise IOError("'"+fn+"' does not exist") for fn in argandNames: if not os.path.isfile(fn): raise IOError("'"+fn+"' does not exist") # rv.writeAmplFiles(b, fileName = "./filesForRelease/fullRangeFixing_"+str(tBin)) rv.legendMethods = "Full range" rv.connectCorrPoints = range(70) rv.markRange = (10,15) if Xcheck: rv.addiXoffset = 0.01 rv.addiColor = modernplotting.colors.colorScheme.red rv.legendMethods = "X-check" if twoDmarkPlots: twoDplotName = folder + fileSectorName + "_2D_m"+str(b)+"_t"+str(tBin)+".pdf" intPlotName = "" argPlotName = "" else: twoDplotName = "" intPlotName = folder + fileSectorName + "_int_m"+str(b)+"_t"+str(tBin)+".pdf" argPlotName = folder+ fileSectorName + "_arg_m"+str(b)+"_t"+str(tBin)+".pdf" # rv.tString = "" # rv.scaleFakk = 1000. # rv.writeBinToPdf(b, stdCmd = ["","",[], folder+ sect + "_data_argand_"+str(b)+"_"+str(tBin)+".pdf", argandNames]) rv.writeBinToPdf(b, stdCmd = [twoDplotName, intPlotName, intensNames, argPlotName, argandNames]) # rv.wiriteReImToPdf(b, sect + "_data_<ri>_"+str(b)+"_"+str(tBin)+".pdf") print tBin,':','([',str(rv.InMax),'],[',str(rv.reMin),',',str(rv.reMax),',',str(rv.imMin),',',str(rv.imMax),'])' return with root_open("1mp1p_totals_t"+str(tBin)+".root", "RECREATE"): hists = fullRanges.makeTheoryTotals() for tb in hists: for h in tb: h.Write() totalHists = fixedShapes.getTotalHists(zeroModeParameters) for tb in totalHists: for h in tb: h.Write() return
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_rho3_2mp3pp.root" zeroFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_rho3_2mp3pp.root" sectors = [ "2-+0+[pi,pi]0++PiD", "2-+0+[pi,pi]1--PiP", "2-+0+[pi,pi]1--PiF", "2-+0+[pi,pi]2++PiS", "2-+0+[pi,pi]2++PiD", "2-+0+[pi,pi]3--PiP" ] tBin = int(sys.argv[1]) if tBin < 0 or tBin > 3: raise ValueError("Invalid t' bin: " + str(tBin)) tBins = [tBin] startBin = 36 stopBin = 50 # startBin = 20 # stopBin = 25 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}^{~}$", "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}$", "fitRho3": r"$\text{fit}_{\rho_3}$", "smooth": r"smooth" } print "Starting with fitting rho3" fitRho3 = doFitRho3( inFileName, zeroFileName, sectors, startBin, stopBin, tBins, referenceWave=referenceWave, writeResultToFile="rho3MassesAndWidths_2mp_rho3_global.dat") allMethods["fitRho3"] = fitRho3 print "Finished with fitting rho3" 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() ### print "Starting with fitting rhoP" ### fitRhoP = doFitRhoP(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave) ### allMethods["fitRhoP"] = fitRhoP ### print "Finished with fitting rhoP" ### print "Starting with fitting rhoF" ### fitRhoF = doFitRhoF(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave) ### allMethods["fitRhoF"] = fitRhoF ### print "Finished with fitting rhoF" addAll = True if addAll: print "Starting with fitting bothRho" fitBothRho = doFitBothRho(inFileName, zeroFileName, sectors, startBin, stopBin, tBins, referenceWave=referenceWave) allMethods["fitBothRho"] = fitBothRho print "Finished with fitting bothRho" print "Starting with fitting bothf2" fitBothF2 = doFitBothF2(inFileName, zeroFileName, sectors, startBin, stopBin, tBins, referenceWave=referenceWave) allMethods["fitBothF2"] = fitBothF2 print "Finished with fitting bothf2" 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" diffsFull, resolvedWA, nonResolvedWA, comps, resDiffs, nonResDiffs, resolvedDiffsFull, noCorrDiffs = cu.doAllComparisons( allMethods, startBin, methodBinRanges) makePlots = False if makePlots: plotFolder = "./comparisonResults2mp_rho3/" for s, sect in enumerate(sectors): rv = allMethods['fixedShapes'].produceResultViewer(resolvedWA, s, noRun=True, plotTheory=True, removeZM=False) rv.writeBinToPdf(startBin, stdCmd=[ plotFolder + sect + "_data_2D_" + str(tBin) + ".pdf", "", [], "", [] ]) rv.scaleTo = "maxCorrData" for b in range(startBin, stopBin): intensNames = [] argandNames = [] rv.writeBinToPdf(b, stdCmd=[ "", plotFolder + sect + "_data_intens_" + str(b) + "_" + str(tBin) + ".pdf", intensNames, plotFolder + sect + "_data_argand_" + str(b) + "_" + str(tBin) + ".pdf", argandNames ]) return doRho3Fits = True if doRho3Fits: with open("rho3massesAndWidths_2mpRho3_" + 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 = fitRho3.fitShapeParametersForBinRange( [ mRho3 + startValueOffset, Grho3 + 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')
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
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 sectors = ["4++1+[pi,pi]1--PiG", "4++1+[pi,pi]2++PiF"] inFileName = fileNameMap["4pp"] tBins = [tBin] startBin = 35 stopBin = 38 # startBin = 11 # stopBin = 50 methodBinRanges = { "fitF2": (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}^{~}$", "fitRhoP": r"$\text{fit}_\rho^{P}$", "fitRhoF": r"$\text{fit}_\rho^{F}$", "fitBothRho": r"$\text{fit}_\rho^{2}$", "fitF2": r"$\text{fit}_{f_2}$", "smooth": r"smooth" } print "Starting with fixed shapes" fixedShapes = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave=referenceWave) allMethods["fixedShapes"] = fixedShapes print "Finished with fixed shapes" fullSig = fixedShapes.getZeroModeSignature() diffsFull, resolvedWA, nonResolvedWA, comps, resDiffs, nonResDiffs, resolvedDiffsFull, noCorrDiffs = cu.doAllComparisons( allMethods, startBin, methodBinRanges) studyList = [] for m in allMethods: studyList.append(m) studyList.sort() folder = "./4ppPlots/" 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=[ folder + sect + "_data_2D_" + str(tBin) + ".pdf", "", [], "", [] ]) # continue for b in range(startBin, stopBin): intensNames = [] argandNames = [] if tBin == 3: app = True appendIndex = b - 34 if not appendIndex in range(1, 4): app = False if sect == "4++1+[pi,pi]1--PiG": waveIndexx = 12 elif sect == "4++1+[pi,pi]2++PiF": waveIndexx = 13 else: app = False if app: intensNames = [ "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/evalDima/4pp/param_" + str(waveIndexx) + "_00" + str(appendIndex) + ".intens" ] argandNames = [ "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/evalDima/4pp/param_" + str(waveIndexx) + "_00" + str(appendIndex) + ".argand" ] print intensNames print argandNames rv.writeBinToPdf(b, stdCmd=[ "", folder + sect + "_data_intens_" + str(b) + "_" + str(tBin) + ".pdf", intensNames, folder + sect + "_data_argand_" + str(b) + "_" + str(tBin) + ".pdf", argandNames ]) print studyList
def main(): checkLaTeX() style = modernplotting.mpplot.PlotterStyle() # style.p2dColorMap = 'ocean_r' # style.p2dColorMap = 'YlOrRd' style.p2dColorMap = 'Reds' inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_exotic.root" sectors = ["1-+1+[pi,pi]1--PiP"] tBin = int(sys.argv[1]) if tBin < 0 or tBin > 3: raise ValueError("Invalid t' bin: " + str(tBin)) tBins = [tBin] startBin = 13 stopBin = 50 acv = 130. # artificial coma value # acv = 1.3e-5 # artificial coma value # startBin = 26 # stopBin = 28 methodBinRanges = { "fitF2" : (22, 50), "fitRhoF" : (22, 50), "fixedShapeF2" : (22, 50)} # methodBinRanges = {} # Override here # sectorRangeMap = {"1-+1+[pi,pi]1--PiP":(0.,1.2)} sectorRangeMap = {"1-+1+[pi,pi]1--PiP":(0.,1.12)} allMethods = {} methodStrings = {} shortlabels = { "fixedShapeF0" : r"$\text{fix}_{f_0}^{~}$", "fixedShapeRhoP" : r"$\text{fix}_\rho^{P}$", "fixedShapeRhoF" : r"$\text{fix}_\rho^{F}$", "fixedShapeBothRho" : r"$\text{fix}_\rho^{2}$", "fixedShapeF2" : r"$\text{fix}_{f_2}$", "fixedShapes" : r"$\text{fix}_\text{all}^{~}$", "pipiS" : r"$\phi_{[\pi\pi]_S}^{~}$", "fitRho" : r"$\text{fit}_\rho$", "fitRhoP" : r"$\text{fit}_\rho^{P}$", "fitRhoF" : r"$\text{fit}_\rho^{F}$", "fitBothRho" : r"$\text{fit}_\rho^{2}$", "fitF2" : r"$\text{fit}_{f_2}$", "smooth" : r"smooth"} print "Starting with fixed shapes" fixedShapes = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, acv = acv, sectorRangeMap = sectorRangeMap) allMethods["fixedShapes"] = fixedShapes print "Finished with fixed shapes" fullSig = fixedShapes.getZeroModeSignature() # print "Starting with fitting rho" # fitRho = doFitRho(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, writeResultToFile = "rhoMassesAndWidths_1-+1+1--_global.dat", sectorRangeMap = sectorRangeMap, acv = acv) # allMethods["fitRho"] = fitRho # print "Finished with fitting rho" # if stopBin - startBin > 1: # print "Starting with smooth" # smooth = doSmooth(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave) # allMethods["smooth"] = smooth # print "Finished with smooth" if "fixedShapeRhoF" in allMethods: allMethods["fixedShapeRhoF"].setZeroModeSignature(fullSig,1) if "fitRhoF" in allMethods: allMethods["fitRhoF"].setZeroModeSignature(fullSig,1) # diffsFull, resolvedWA, nonResolvedWA, comps, resDiffs, nonResDiffs, resolvedDiffsFull,noCorrDiffs = cu.doAllComparisons(allMethods, startBin, methodBinRanges, noBelowZero = True) # print resolvedDiffsFull # from math import isnan # for pair in resolvedDiffsFull: # with modernplotting.toolkit.PdfWriter('./resolvedDiffPlots/1mp_'+pair[0]+"_"+pair[1]+"_"+str(tBin)+".pdf") as pdfOutput: # plot = style.getPlot1D() # line = [0.000000001]*len(resolvedDiffsFull[pair][0]) # line2 = [0.000000001]*len(resolvedDiffsFull[pair][0]) # one = [1.]*len(resolvedDiffsFull[pair][0]) # xAxis = [ .5 + 0.04*(startBin + i) for i in range(len(resolvedDiffsFull[pair][0]))] # for i,v in enumerate(resolvedDiffsFull[pair][0]): # if not isnan(v) and not v <= 0.: # line[i] = v # else: # line[i] = 0.000000001 # # if not pair[1] == "WAres" and not pair[1] == "WAnon": # for i,v in enumerate(resolvedDiffsFull[pair[1],pair[0]][0]): # if not isnan(v) and not v <= 0.: # line2[i] = v # else: # line2[i] = 0.000000001 # # plot.setYlog() # plot.plot(xAxis, line) # plot.plot(xAxis, one) # plot.plot(xAxis, line2) # plot.setYlim(0.00001, 10000) # plot.finishAndSaveAndClose(pdfOutput) # studyList = [] # for m in allMethods: # studyList.append(m) # studyList.sort() style.titleRight = r"$1^{-+}1^+$" style.titleLeft = LaTeX_strings.tBins[tBin] # with modernplotting.toolkit.PdfWriter("compositions_1mp_"+str(tBin)+".pdf") as pdfOutput: # plot = style.getPlot1D() # for m in studyList: # line = [0.]*len(comps[m][0]) # xAxis = [ .5 + 0.04*(startBin + i) for i in range(len(comps[m][0]))] # break # count = 0 # for m in studyList: # newLine = line[:] # for i in range(len(comps[m][0])): # newLine[i] += comps[m][0][i] # plot.axes.fill_between(xAxis, line, newLine, facecolor = modernplotting.colors.makeColorLighter(modernplotting.colors.colorScheme.blue, 0.1*count)) # count += 1 # line = newLine # plot.setYlim(0.,1.) # plot.setXlim(xAxis[0], xAxis[-1]) # plot.finishAndSaveAndClose(pdfOutput) # hist = pyRootPwa.ROOT.TH2D("hist","hist", len(studyList)+2, 0, len(studyList)+2, len(studyList), 0, len(studyList)) # # for i,m in enumerate(studyList): # for j,n in enumerate(studyList): # hist.SetBinContent(i+1, j+1, diffsFull[n,m]) # for i,m in enumerate(studyList): # hist.SetBinContent(len(studyList)+1, i+1, noCorrDiffs[m]) # hist.SetBinContent(len(studyList)+2, i+1, resDiffs[m]) # # axolotl = [] # for i,study in enumerate(studyList): # axolotl.append(shortlabels[study]) # axolotl.append(alphabet[i]) # with modernplotting.toolkit.PdfWriter("studies_1mp_"+str(tBin)+".pdf") as pdfOutput: # plot = style.getPlot2D() # plot.axes.get_xaxis().set_ticks([(i + 0.5) for i in range(len(studyList)+2)]) # plot.axes.get_yaxis().set_ticks([(i + 0.5) for i in range(len(studyList) )]) # studyPlotter.makeValuePlot(plot, hist) # # plot.axes.set_yticklabels(axolotl) # axolotl.append(unCorrected_string) # axolotl.append(weightedAVG_string) # plot.axes.set_xticklabels(axolotl, rotation = 90) # plot.setZlim((0.,1.)) # # plot.finishAndSaveAndClose(pdfOutput) # with open("studies_1mp_"+str(tBin)+".txt",'w') as out: # for axl in axolotl: # out.write(axl + ' ') # out.write("\n") # for i in range(hist.GetNbinsX()): # for j in range(hist.GetNbinsY()): # out.write(str(hist.GetBinContent(i+1, j+1)) + ' ') # out.write('\n') doRhoFits = True writeCpls = False if writeCpls: outFileCpl = open("1mp_rho_cpls_"+str(tBin)+".dat",'w') resolvedWA = allMethods['fixedShapes'].getZeroModeParametersForMode() doActuallyNotFit = False if doRhoFits: with open("pi1Radii_exotic_"+str(tBin)+".dat",'w') as out: rhoRadius = doFitRhoRadius(inFileName, sectors, startBin, stopBin, tBins, sectorRangeMap = {}, referenceWave = referenceWave, writeResultToFile = "rhoRadiusExotic_global.dat", acv = acv) for i in range(stopBin-startBin): binIndex = i+startBin out.write(str(binIndex)+' '+str(0.52 + 0.04*binIndex)+' ') startValueOffset = 0.00 if doActuallyNotFit: print "The fit has been turned off, due to a workaround... :(" else: exceptCount = 0 try: x,err,c2,ndf = rhoRadius.fitShapeParametersForBinRange([Pr0+ startValueOffset], [0],[i], zeroModeParameters = resolvedWA) except: print "Fitter exception encountered" startValueOffset += 0.001 exceptCount += 1 if exceptCount > 3: raise Exception("Too many failed attempts: "+str(exceptCount)) out.write(str(x[0]) + ' ' + str(err[0])) out.write(' '+str(c2/ndf)+'\n') if writeCpls: rhoRadius.calculateNonShapeParametersForZeroModeParameters(resolvedWA) cpl, hess = rhoRadius.getCouplingParameters() hessInv = la.inv(hess[0][i]) if not len(cpl[0][1]) == 2: raise IndexError("Parameter count not 2, change implementation") integral = rhoRadius.model[0][i].getIntegralForFunction(0, rhoRadius.model[0][i].funcs[0][0]) outFileCpl.write(str(0.52 + binIndex*.04) + ' ' + str(cpl[0][i][0]**2 + cpl[0][i][0]**2) + ' ' + str(integral) + ' ') outFileCpl.write(str(cpl[0][i][0]) + ' ' + str(cpl[0][i][1]) + ' ') outFileCpl.write(str(hessInv[0][0]/2) + ' ' + str(hessInv[1][1]/2) + ' ' + str(hessInv[0][1]/2)) outFileCpl.write("\n") makeRhoFitPlots = False if makeRhoFitPlots: rhoRadius.calculateNonShapeParametersForZeroModeParameters(resolvedWA) rhoRV = rhoRadius.produceResultViewer(resolvedWA,"1-+1+[pi,pi]1--PiP", noRun = True, plotTheory = True) rhoRV.plotData = True plotNameBase = "./rhoFitPlots/1mp1p1mmPiP_<mode>_"+str(binIndex)+"_"+str(tBin)+".pdf" rhoRV.writeBinToPdf(binIndex, stdCmd = ["", plotNameBase.replace("<mode>","intens"), [], plotNameBase.replace("<mode>","argand"), []]) if writeCpls: outFileCpl.close() return ##### Writing starts here # fileNames = {} # fixedShapes.removeZeroModeFromComa() ## binRange = {"1-+1+[pi,pi]1--PiP": (10,22)} # totalHists = fixedShapes.getTotalHists(resolvedWA, binRange = binRange) # with root_open("./totals_1mp_rhoRange.root", "UPDATE") as out: # for t in totalHists: # for m in t: # m.Write() # return # for stu in allMethods: # print "Writing for '" + stu + "'" # for s, sect in enumerate(allMethods[stu].sectors): # if stu == "pipiS": # rv = allMethods[stu].produceResultViewer(allMethods[stu].getZeroModeParametersForMode(),s, plotTheory = True) # rv.run() # rv = allMethods[stu].produceResultViewer(allMethods[stu].getZeroModeParametersForMode(),s, noRun = True) # for bin in range(startBin, stopBin): # fileName = "./collectedMethods/"+stu+"_"+sect+"_1mpData_"+str(bin) # if not (sect,bin) in fileNames: # fileNames[sect,bin] = [] # fileNames[sect,bin].append(fileName) # rv.writeAmplFiles(bin, fileName = fileName) scalle = False if scalle: folder = "./comparisonResultsData_1mp_scale/" else: folder = "./comparisonResultsData_1mp/" fixedShapesFull = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, acv = acv) for s, sect in enumerate(allMethods['fixedShapes'].sectors): # allMethods['fixedShapes'].removeZeroModeFromComa() # allMethods['fixedShapes'].removeGlobalPhaseFromComa() rv = fixedShapesFull.produceResultViewer(allMethods['fixedShapes'].getZeroModeParametersForMode(),s, noRun = True, plotTheory = True) # rv.plotData = False rv.writeBinToPdf(startBin, stdCmd = [ folder + sect + "_data_2D_"+str(tBin)+".pdf", "", [], "", []]) # rv.labelPoints = [0,10,15,20] # rv.makeLegend = True if scalle: rv.scaleTo = "maxCorrData" # rv.yAxisShift = 300. # rv.tStringYpos = 0.8 # rv.topMarginIntens = 1.4 # fakkkk = 1. else: rv.plotData = False # fakkkk = .7 # rv.tStringYpos = 0.865 # rv.topMarginIntens = 1.3 # rv.yAxisShift = 100. # rv.shiftMap = {0:(fakkkk*50.,fakkkk*-280.),10:(fakkkk*-420.,fakkkk*-50.), 15:(fakkkk*-420.,fakkkk*-30.), 20:(fakkkk*-50.,fakkkk*70.)} for b in range(startBin, stopBin): # if not bin == 27: # continue # intensNames = [name+".intens" for name in fileNames[sect,b]] # argandNames = [name+".argand" for name in fileNames[sect,b]] # intensNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/evalDima/dima.intens"] # argandNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/evalDima/dima.argand"] # if not scalle: if True: intensNames = [] argandNames = [] # rv.plotData = True rv.writeBinToPdf(b, stdCmd = ["", folder + sect + "_data_intens_"+str(b)+"_"+str(tBin)+".pdf", intensNames, folder + sect + "_data_argand_"+str(b)+"_"+str(tBin)+".pdf", argandNames]) rv.wiriteReImToPdf(b, folder + sect + "_data_<ri>_"+str(b)+"_"+str(tBin)+".pdf")
def main(): checkLaTeX() style = modernplotting.mpplot.PlotterStyle() # style.p2dColorMap = 'ocean_r' # style.p2dColorMap = 'YlOrRd' style.p2dColorMap = 'Reds' # referenceWave = "" inFileName = fileNameMap["std11"] for a in sys.argv: if a.startswith("mBins"): startBin = int(a.split("-")[1]) stopBin = int(a.split("-")[2]) if a.startswith("tBins"): tMin = int(a.split("-")[1]) tMax = int(a.split("-")[2]) tBins = range(tMin, tMax) nPol = 3 for a in sys.argv: if a.startswith("nPol"): nPol = int(a[4:]) f2Re0 = mF2**2 f2Im0 = mF2 * GF2 mPrime = 1.55 Gprime = .2 mPPrime = 1.91 Gpprime = .3 f2Mass = ptc.parameter(mF2, "f2_mass") f2Width = ptc.parameter(GF2, "f2_width") f2 = ptc.relativisticBreitWigner([f2Mass, f2Width], mPi, mPi, mPi, 2, 0, False) poleReal = ptc.parameter(f2Re0, "f2Re") poleImag = ptc.parameter(f2Im0, "f2Im") pPoleReal = ptc.parameter(mPrime**2, "f2pRe") pPoleImag = ptc.parameter(mPrime * Gprime, "f2pIm") ppPoleReal = ptc.parameter(mPPrime**2, "f2ppRe") ppPoleImag = ptc.parameter(mPPrime * Gpprime, "f2ppIm") # poleRealPrime = ptc.parameter(mPrime**2, "rhoRePrime") # poleImagPrime = ptc.parameter(mPrime*Gprime, "rhoImPrime") polyDeg_po = 3 for a in sys.argv: if a.startswith("pdpo"): polyDeg_po = int(a[4:]) params = [poleReal, poleImag, pPoleReal, pPoleImag, ppPoleReal, ppPoleImag] params = params[:2 * nPol] for d in range(polyDeg_po): params.append(ptc.parameter(2 * random() - 1., "c_" + str(d))) Kmatrix = ptc.simpleOneChannelKmatrix(params, nPol, polyDeg_po, 4 * mPi**2) useCM = False for a in sys.argv: if a == "CM": useCM = True if a == "rho": useCM = False if useCM: psString = "CM" else: psString = "rho" Kmatrix.use_CM = useCM for a in sys.argv: if a.startswith("polyDegP"): polyDegP = int(a[8:]) mMin = .5 + .04 * startBin mMax = .5 + .04 * stopBin smartMode = True tFuncs = [] tpPoly = [] nKpar = len(params) KparValues = [p.value for p in params] funcs = [] for d in range(polyDegP + 1): mnm = ptc.monomial(2 * d) func = ptc.multiply([Kmatrix, mnm]) funcs.append(func) phases = [] for tBin in tBins: tParams = [] for mBin in range(startBin, stopBin): phases.append( ptc.parameter(2 * pi * random(), "phi_t" + str(tBin) + "_m" + str(mBin))) for d in range(polyDegP): tParams.append( ptc.parameter( 2 * random() - 1., "c" + str(d + 1) + "_t" + str(tBin) + "_m" + str(mBin))) nPpar = len(tParams) if not smartMode: params += tParams pPoly = ptc.binnedPolynomial(tParams, mMin=mMin, mMax=mMax, nBins=stopBin - startBin, degree=polyDegP, baseExponent=2, real=True) tpPoly.append(pPoly) func = ptc.multiply([Kmatrix, pPoly]) tFuncs.append(func) bestFitVals = [ 1.591236, 0.234037, 2.419353, 0.005742, 3.702362, 0.000053, -0.189620, 0.207497, -0.058921, 0.517699, 0.166935, 0.181275, 0.959202, 1.528309, 0.501027, -1.146739, -0.535555, 0.417481, -0.419879, 1.561247, 0.120558, 1.059373, 0.393481, -0.283450, -0.182751, -0.667384, 0.619867, 0.343112, 0.069652, 0.677225, -0.116518, -0.485594, 0.693124, 0.270239, 0.139340, -2.694811, -0.062632, 1.570524, -0.493674, -2.409801, 0.394341, 0.421391, -0.524359, 0.112583, 0.285943, -0.166501, -0.408990, -0.010904, 0.088735, 0.117378, 0.166603, -0.949778, 0.500537, -1.352419, -0.639588, -2.139980, -0.146114, 1.877676, 1.025465, -0.120469, 1.197397, 0.792957, -0.507836, 0.354736, -0.571950, -0.439970, 0.635951, 1.119741, 1.078536, -1.707963, -0.894598, -0.379259, -0.256336, 1.811274, 0.460570, -2.370441, -1.519688, -2.596059, -1.472923, 0.329489, 0.963846, -0.174265, 0.497754, 0.523653, -0.082330, -2.288272, 0.238584, 2.432317, -0.219072, -1.818075, 0.101130, -1.315669, -0.095197, 0.185721, -0.468701, 1.150421, -0.706067, 1.336765, 0.114122, -2.514466, -1.292956, 0.909066, -0.136537, 1.579291, 0.917968, 0.519039, 0.560456, -3.141557, -0.919017, 1.034258, 0.651617, 0.414377, -0.954656, 0.432315, -0.250071, -0.306383, -0.916611, 0.241417, 0.196445, -0.594122, -0.610276, -2.115296, -1.232504, 0.210273, -0.539883, 1.134149, 0.582253, -1.330798, -1.189863, 2.000385, -0.286371, 0.997649, -0.268911, -0.358648, 0.209653, 0.307646, 0.294261, 2.350279, -0.342739, 1.010674, -0.547855, -1.715226, 0.599891, 0.567254, -0.731444, 2.852883, -0.398756, 2.450370, 0.296712, 0.499203, 0.284769, -7.040768, -1.148202, -0.982813, 0.349752, -6.325548, -0.494806, 0.183253, 0.745206, 2.547205, 1.571422, 0.713172, -0.253361, 0.610771, 1.308658, 1.501376, 1.023860, 2.184354, 0.927320, 0.677329, 0.589890, 0.139710, 0.550017, -0.702369, -0.847349, -0.729193, 0.541576, -0.508911, 0.495425, 1.287986, -0.364052, -1.338609, 0.281415, 0.168475, 0.184298, -0.904410, 0.193151, -0.773044, 0.324601, 4.473005, 0.046860, -0.359312, 0.368391, -1.623123, 0.531775, 0.384091, 0.988951, -0.779931, 0.030888, -0.139630, -0.264398, -9.821342, -1.601821, -7.745628, -2.010218, -3.540738, -0.067302, 0.153977, -1.635704 ] for p, par in enumerate(params): par.value = bestFitVals[p] if smartMode: params += phases sector = "2-+0+[pi,pi]2++PiS" sectors = [ "2-+0+[pi,pi]0++PiD", "2-+0+[pi,pi]1--PiP", "2-+0+[pi,pi]1--PiF", "2-+0+[pi,pi]2++PiS" ] sectorRangeMap = {} zmPars = [] fitters = [] for t, tBin in enumerate(tBins): if smartMode: ff = funcs else: ff = [tFuncs[t]] fitter = amplitudeAnalysis(inFileName, sectors, {sector: ff}, startBin, stopBin, [tBin], sectorRangeMap=sectorRangeMap) fitter.loadData(loadIntegrals=True, referenceWave=referenceWave) fitter.finishModelSetup() fitter.mode = AMPL fixSectors = [ "2-+0+[pi,pi]1--PiP", "2-+0+[pi,pi]1--PiF", "2-+0+[pi,pi]2++PiS" ] fixRangeMap = { "2-+0+[pi,pi]1--PiP": (0., 1.12), "2-+0+[pi,pi]1--PiF": (0., 1.12), "2-+0+[pi,pi]2++PiS": (0., 1.27) # Use only left side of f_2(1270) } fixedShapes = doFixedShapes(inFileName, fixSectors, startBin, stopBin, [tBin], referenceWave=referenceWave, sectorRangeMap=fixRangeMap) zmPars.append(fixedShapes.getZeroModeParametersForMode()) fitter.setZeroModeParameters(zmPars[-1]) fitter.model.setBinsToEvalueate( [0], range(stopBin - startBin) ) # [0] since it is only one tBin in this fitter (one fitter par t' bin) fitters.append(fitter) c2 = 0. for t in range(len(tBins)): ddd = fitters[t].model.fixedZMPchi2(None) print ddd, "the previous chi2 (this should not give, since it allows phase motion in the p-vector" c2 += ddd print c2 nmBins = stopBin - startBin def evalFunction(params): Kmatrix.setParameters(params[:nKpar]) chi2 = 0. for t in range(len(tBins)): if smartMode: chi2 += fitters[t].model.fixedZMPchi2_realCouplings( None, params[nKpar + t * nmBins:nKpar + (t + 1) * nmBins]) else: chi2 += fitters[t].model.fixedZMPchi2(None) return chi2 print evalFunction([p.value for p in params]), "gives it?" # return argString = ','.join([p.name + '=' + str(p.value) for p in params]) lstString = ','.join([p.name for p in params]) ndf = 0 for fitter in fitters: ndfs = fitter.model.getNDF() for t in ndfs: for m in t: ndf += m[0] - m[1] - m[2] ndf -= len(params) ndf += polyDegP * (stopBin - startBin) * ( tMax - tBin) # the couplings have just a global phase !!! # # # # # # 2mpF2_Kmatrix_nPol3_rho_kPol0_pPol0-3_t3_m49-50_5854.dat for att in range(10): # make 10 attempts at once print "Setting Start Pars for attempt", att + 1 for i in range(len(params)): if i < nKpar: params[i].value = KparValues[i] else: params[i].value = 2 * pi * random() vals = MIGRAD(argString, lstString, evalFunction) chi2 = explicit_MINUIT_function(*vals) seedint = randint(0, 10000) resultFileName = "./globalKmatrixFits/2mpF2_nPol" + str( nPol) + "_" + psString + "_kPol" + str( polyDeg_po - 1) + "_t" + str(tMin) + '-' + str(tMax) + "_m" + str( startBin) + "-" + str(stopBin) + "_polyDegP" + str( polyDegP) + "_" + str(seedint) + ".dat" with open(resultFileName, 'w') as outFile: outFile.write("- - - - parameters - - - -\n") for p in params: outFile.write(str(p) + '\n') outFile.write(" - - - - - fit - - - - -\nchi2/NDF: " + str(chi2) + "/" + str(ndf) + "=" + str(chi2 / ndf) + '\n') outFile.write("ndf corrected!!!") return parameters = [] for f in funcs: for p in f.returnParameters(): parameters.append(p) fitter.initMinuitFunction(parameters) fitter.removeZeroModeFromComa() fitter.removeGlobalPhaseFromComa() if acv is not None: print "adding ACV of", acv fitter.addComaValueForZeroMode(acv) pPoly = ptc.twoDimensionalRealPolynomial( pPolyDeg2, pPolyDeg3, params, baseExponent=2) # baseExponent = 2: polynomial in s func = ptc.multiply([Kmatrix, pPoly]) model = [func] # model = [rho] acv = None # # - - - - --- Stop the model building here --- - - - - # # zeroModeParameters = None fixZeroMode = True # print sectorRangeMap # return if fixZeroMode: fixSectors = [ "2-+0+[pi,pi]1--PiP", "2-+0+[pi,pi]1--PiF", "2-+0+[pi,pi]2++PiS" ] fixRangeMap = { "2-+0+[pi,pi]1--PiP": (0., 1.12), "2-+0+[pi,pi]1--PiF": (0., 1.12), "2-+0+[pi,pi]2++PiS": (0., 1.27) # Use only left side of f_2(1270) } fixedShapes = doFixedShapes(inFileName, fixSectors, startBin, stopBin, tBins, referenceWave=referenceWave, sectorRangeMap=fixRangeMap) zeroModeParameters = fixedShapes.getZeroModeParametersForMode() # RV = fixedShapes.produceResultViewer(zeroModeParameters,"1-+1+[pi,pi]1--PiP", noRun = True, plotTheory = True) # RV.plotData = True # for b in range(startBin, stopBin): # plotNameBase = "./Kmatrix_plots/1mp1p1mmPiP_<mode>_"+str(b)+"_"+str(tBin)+".pdf" # RV.writeBinToPdf(b, stdCmd = ["", plotNameBase.replace("<mode>","intens"), [], plotNameBase.replace("<mode>","argand"), []]) # return if useCM: ps = "CM" else: ps = "rho" if nPol == 1: nps = "" else: nps = "nPol" + str(nPol) + "_" resultFile = "./KmatrixRestrictedZMfixing_allFourSectorsActive/2mpF2_Kmatrix_" + nps + ps + "_kPol" + str( polyDeg_po - 1) + "_pPol" + str(pPolyDeg3) + "-" + str( pPolyDeg2) + "_t" + str(tBin) + "_m" + str(startBin) + '-' + str( stopBin) + '_' + str(seedint) + ".dat" fitter = doFunctionFit(inFileName, model, startBin, stopBin, tBins, sectorRangeMap, referenceWave=referenceWave, acv=acv, zeroModeParameters=zeroModeParameters, writeResultToFile=resultFile, ifn=ifn) # # - - - - --- Start the evaluations here --- - - - - # # nBinsPlot = 1000 def fPlot(v): return v.imag # hist = pyRootPwa.ROOT.TH2D("hhh","hhh", nBinsPlot, -.25, 6.25,nBinsPlot, -1., 1.) # for iX in range(nBinsPlot): # x = hist.GetXaxis().GetBinCenter(iX+1) # for iY in range(nBinsPlot): # y = hist.GetYaxis().GetBinCenter(iY+1) # s = x+1.j*y # val = Kmatrix.complexCall(s) # hist.SetBinContent(iX+1, iY+1,fPlot(val)) # hist.Draw("COLZ") # raw_input("press <enter> to go to the secont sheet") Kmatrix.secondSheet = True # for iX in range(nBinsPlot): # x = hist.GetXaxis().GetBinCenter(iX+1) # for iY in range(nBinsPlot): # y = hist.GetYaxis().GetBinCenter(iY+1) # s = x+1.j*y # val = Kmatrix.complexCall(s) # hist.SetBinContent(iX+1, iY+1, fPlot(val)) # hist.Draw("COLZ") res = scipy.optimize.minimize(Kmatrix.absInverse, [f2Re0, f2Im0]) print res.x, "pole position" mfv = res.fun resSting = str(res.fun) + " function value should be zero" print resSting BWstring = "BW par: " + str(abs(res.x[0])**.5) + " " + str( abs(res.x[1]) / abs(res.x[0])**.5) + " (all absolute values)" print BWstring if ifn is None: print "= = = = = = = = = Starting BW error ersimation = = = = = = = = = " nPoints = 1000 poleMean = res.x poleSamples = [] i = 0 failCount = 0 while i < nPoints: pts = np.random.multivariate_normal(fitter.fitParameters, fitter.MINUITcoma) fitter.MINUIT_function( pts) # Call the function once to set parameters inside # fitter.model[0].setParametersAndErrors(pts, fitter.MINUITerrs) res = scipy.optimize.minimize(Kmatrix.absInverse, poleMean) if abs(res.fun) > 100 * mfv: print "No more pole found (mfv = " + str( mfv) + ") : fval = " + str(res.fun) failCount += 1 if failCount > nPoints: print "Failed to find poles too often.... abort" return continue # raise ValueError("No more pole found: fval = "+str(res.fun)) poleSamples.append(res.x) i += 1 # print i,"Marker to find the PRINT 57473M3N7" meanPole = [0., 0.] for p in poleSamples: meanPole[0] += p[0] meanPole[1] += p[1] meanPole[0] /= len(poleSamples) meanPole[1] /= len(poleSamples) poleComa = [[0., 0.], [0., 0.]] for p in poleSamples: poleComa[0][0] += (p[0] - meanPole[0])**2 poleComa[0][1] += (p[0] - meanPole[0]) * (p[1] - meanPole[1]) poleComa[1][0] += (p[1] - meanPole[1]) * (p[0] - meanPole[0]) poleComa[1][1] += (p[1] - meanPole[1])**2 poleComa[0][0] /= len(poleSamples) - 1 poleComa[0][1] /= len(poleSamples) - 1 poleComa[1][0] /= len(poleSamples) - 1 poleComa[1][1] /= len(poleSamples) - 1 comaString = str(poleComa) print " - - - - - - le compaire pramaitre - - - - - - " print meanPole, poleMean print " - - - - - - le compaire pramaitre - - - - - - " print poleComa print "= = = = = = = = = Finished BW error ersimation = = = = = = = = = " mF2P = 1.9 GF2P = .277 res = scipy.optimize.minimize(Kmatrix.absInverse, [mF2P**2, mF2P * GF2P]) print res.x, "pole position" resSting = str(res.fun) + " function value should be zero" print resSting BWstring = "BW' par: " + str(abs(res.x[0])**.5) + " " + str( abs(res.x[1]) / abs(res.x[0])**.5) + " (all absolute values)" print BWstring with open(resultFile, 'a') as outFile: outFile.write('\n' + BWstring + " " + resSting + "\ncoma " + comaString) # outFile.write('\n'+BWfitString) # # - - - - --- Start the evaluations here --- - - - - # # doPlots = False for a in sys.argv: if a == "plot": doPlots = True if ifn is not None: doPlots = True # Set plots by default, if an inFile is given if doPlots: RV = fitter.produceResultViewer(zeroModeParameters, "2-+0+[pi,pi]2++PiS", noRun=True, plotTheory=True) RV.plotData = True for b in range(startBin, stopBin): plotNameBase = "./Kmatrix_plots/2mp0p2ppPiS_<mode>_" + str( b) + "_" + str(tBin) + "_" + str(seedint) + ".pdf" RV.writeBinToPdf(b, stdCmd=[ "", plotNameBase.replace("<mode>", "intens"), [], plotNameBase.replace("<mode>", "argand"), [] ]) # raw_input("press <enter> to exit") return
def main(): checkLaTeX() style = modernplotting.mpplot.PlotterStyle() # style.p2dColorMap = 'ocean_r' # style.p2dColorMap = 'YlOrRd' style.p2dColorMap = 'Reds' inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_exotic.root" sectors = ["1-+1+[pi,pi]1--PiP"] tBin = int(sys.argv[1]) if tBin < 0 or tBin > 3: raise ValueError("Invalid t' bin: " + str(tBin)) tBins = [tBin] startBin = 11 stopBin = 50 # startBin = 26 # stopBin = 28 acv = 130. # artificial coma value # acv = 1.3e-5 # artificial coma value methodBinRanges = { "fitF2" : (22, 50), "fitRhoF" : (22, 50), "fixedShapeF2" : (22, 50)} # methodBinRanges = {} # Override here sectorRangeMap = {"1-+1+[pi,pi]1--PiP":(0.,1.12)} # sectorRangeMap = {} allMethods = {} methodStrings = {} shortlabels = { "fixedShapeF0" : r"$\text{fix}_{f_0}^{~}$", "fixedShapeRhoP" : r"$\text{fix}_\rho^{P}$", "fixedShapeRhoF" : r"$\text{fix}_\rho^{F}$", "fixedShapeBothRho" : r"$\text{fix}_\rho^{2}$", "fixedShapeF2" : r"$\text{fix}_{f_2}$", "fixedShapes" : r"$\text{fix}_\text{all}^{~}$", "pipiS" : r"$\phi_{[\pi\pi]_S}^{~}$", "fitRho" : r"$\text{fit}_\rho$", "fitRhoP" : r"$\text{fit}_\rho^{P}$", "fitRhoF" : r"$\text{fit}_\rho^{F}$", "fitBothRho" : r"$\text{fit}_\rho^{2}$", "fitF2" : r"$\text{fit}_{f_2}$", "smooth" : r"smooth"} print "Starting with fixed shapes" fixedShapes = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, sectorRangeMap = sectorRangeMap, acv = acv) allMethods["fixedShapes"] = fixedShapes print "Finished with fixed shapes" fullSig = fixedShapes.getZeroModeSignature() fullRanges = doFixedShapes(inFileName, sectors, startBin, stopBin, tBins, referenceWave = referenceWave, sectorRangeMap = {}, acv = acv) scalle = False Xcheck = True resolvedWA = fixedShapes.getZeroModeParametersForMode() if scalle: folder = "./comparisonResultsData_1mp_scale/" else: folder = "./comparisonResultsData_1mp/" # folder = "./ellipseComparisons/" folder = "./" fileSectorName = "1mp1p1mmP" if False: # for s, sect in enumerate(fullRanges.sectors): fullRanges.removeZeroModeFromComa() # rv = fullRanges.produceResultViewer(cloneZeros(resolvedWA),s, noRun = True, plotTheory = True) rv = fullRanges.produceResultViewer(resolvedWA,s, noRun = True, plotTheory = True) # rv.writeToRootFile("exoticForRealease_"+str(tBin)+".root") rv.titleFontSize = 11 rv.showColorBar = True rv.XcheckArgand = Xcheck rv.writeBinToPdf(startBin, stdCmd = [ fileSectorName + "_2D_t"+str(tBin)+".pdf", "", [], "", []]) rv.labelPoints = [0,10,15,20] if tBin in [0,1,2] and not scalle: rv.labelPoints = [10,15,20] rv.makeLegend = True if scalle: rv.scaleTo = "maxCorrData" rv.yAxisShift = 300. rv.tStringYpos = 0.8 rv.topMarginIntens = 1.4 fakkkk = 1. else: rv.plotData = False fakkkk = .7 rv.tStringYpos = 0.8 rv.topMarginIntens = 1.4 rv.yAxisShift = 100. rv.scaleArgandZeroLine = 0.8 rv.addiColor = modernplotting.colors.makeColorLighter(modernplotting.colors.colorScheme.blue, .5) rv.realLabel = LaTeX_strings.realReleaseNote rv.imagLabel = LaTeX_strings.imagReleaseNote rv.m2PiString = LaTeX_strings.m2PiReleaseNote rv.intensLabel = LaTeX_strings.intensReleaseNote rv.printLiminary = True if tBin == 3: if scalle: rv.shiftMap = {0:(fakkkk*80.,fakkkk*-280.),10:(fakkkk*-360.,fakkkk*-50.), 15:(fakkkk*-390.,fakkkk*-30.), 20:(fakkkk*-500.,fakkkk*-10.)} else: rv.shiftMap = {0:(fakkkk*100.,fakkkk*-280.),10:(fakkkk*-370.,fakkkk*-50.), 15:(fakkkk*-370.,fakkkk*-30.), 20:(fakkkk*-50.,fakkkk*90.)} if tBin == 2: if scalle: rv.shiftMap = {0:(fakkkk*50.,fakkkk*-300.),10:(fakkkk*-480.,fakkkk*-50.), 15:(fakkkk*-500.,fakkkk*-30.), 20:(fakkkk*0.,fakkkk*70.)} else: rv.shiftMap = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-420.,fakkkk*-50.), 15:(fakkkk*-450.,fakkkk*-30.), 20:(fakkkk*0.,fakkkk*70.)} if tBin == 1: if scalle: rv.shiftMap = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-300.,fakkkk*-50.), 15:(fakkkk*-400.,fakkkk*-30.), 20:(fakkkk*60.,fakkkk*30.)} else: rv.shiftMap = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-350.,fakkkk*-50.), 15:(fakkkk*-400.,fakkkk*-30.), 20:(fakkkk*80.,fakkkk*30.)} if tBin == 0: if scalle: rv.shiftMap = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-450.,fakkkk*-50.), 15:(fakkkk*-450.,fakkkk*-30.), 20:(fakkkk*50.,fakkkk*30.)} else: rv.shiftMap = {0:(fakkkk*50.,fakkkk*-400.),10:(fakkkk*-410.,fakkkk*-50.), 15:(fakkkk*-420.,fakkkk*-30.), 20:(fakkkk*70.,fakkkk*30.)} rv.scale(1000./40.) for b in range(startBin, stopBin): if not b == 27: continue # intensNames = [name+".intens" for name in fileNames[sect,b]] # argandNames = [name+".argand" for name in fileNames[sect,b]] if not scalle: intensNames = [] argandNames = [] # intensNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/singlePlots/1mp1p1mm_t"+str(tBin)+".intens"] # argandNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/singlePlots/1mp1p1mm_t"+str(tBin)+".argand"] intensNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/zeroModeFitter_2D/filesForRelease/fullRangeFixing_"+str(tBin)+".intens"] argandNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/zeroModeFitter_2D/filesForRelease/fullRangeFixing_"+str(tBin)+".argand"] if Xcheck: intensNames = ["/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/singlePlots/1mp1p1mm_t"+str(tBin)+".intens"] argandBaseName = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/singlePlots/dimasEllipses/1mp1p1mm_"+str(b)+"_"+str(tBin)+"_<ndx>.argand" argandNames = [argandBaseName.replace("<ndx>", ndx) for ndx in ['0','1','2','3','C']] # print argandNames # return # intensNames = [] # argandNames = [] for fn in intensNames: if not os.path.isfile(fn): raise IOError for fn in argandNames: if not os.path.isfile(fn): raise IOError # rv.writeAmplFiles(b, fileName = "./filesForRelease/fullRangeFixing_"+str(tBin)) rv.legendMethods = "Full range" if Xcheck: rv.addiXoffset = 0.01 rv.addiColor = modernplotting.colors.colorScheme.red rv.legendMethods = "X-check" # rv.tString = "" # rv.scaleFakk = 1000. # rv.writeBinToPdf(b, stdCmd = ["","",[], folder+ sect + "_data_argand_"+str(b)+"_"+str(tBin)+".pdf", argandNames]) rv.writeBinToPdf(b, stdCmd = ["",folder + fileSectorName + "_int_m"+str(b)+"_t"+str(tBin)+".pdf", intensNames, folder+ fileSectorName + "_arg_m"+str(b)+"_t"+str(tBin)+".pdf", argandNames]) # rv.wiriteReImToPdf(b, sect + "_data_<ri>_"+str(b)+"_"+str(tBin)+".pdf") with root_open("1mp1p_totals_t"+str(tBin)+".root", "RECREATE"): hists = fullRanges.makeTheoryTotals() for tb in hists: for h in tb: h.Write() hists = fullRanges.makeTheoryTotals(REAL) for tb in hists: for h in tb: h.Write() hists = fullRanges.makeTheoryTotals(IMAG) for tb in hists: for h in tb: h.Write() hists = fullRanges.makeTheoryTotals(REIMCORRELATION) for tb in hists: for h in tb: h.Write() totalHists = fixedShapes.getTotalHists(resolvedWA) for tb in totalHists: for h in tb: h.Write() return
def main(): checkLaTeX() style = modernplotting.mpplot.PlotterStyle() # style.p2dColorMap = 'ocean_r' # style.p2dColorMap = 'YlOrRd' style.p2dColorMap = 'Reds' 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(rhoFileName=""): checkLaTeX() # # # # Monte-Carlo results # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_MC_corrected.root" # inFileName = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/ppppppppp/DpPiPiPi_forReleaseNote.root" # inFileName = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/ppppppppp/DpPiPiPi_normalF2.root" # inFileName = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/ppppppppp/DpPiPiPi_versionInPaper.root" # inFileName = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/ppppppppp/DpPiPiPi_forThesis.root" # inFileName = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/ppppppppp/DpPiPiPi_largeErrorStudy.root" # # # # Real-data results # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_three0pp.root" inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/std11_withIntegral.root" # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_exotic_t0.326-0.66_fixed.root" # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_exotic_t0.66-1.00_fixed.root" # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_bigger1pp.root" # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_exotic.root" # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_bigger2pp.root" # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_bigger2mp.root" # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_maximum_t0.66-1.00.root" # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_maximum.root" # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_neg_1m1m.root" # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_neg_1P0m.root" # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_3pp.root" # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_4pp.root" # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_4mp.root" # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_6mp.root" # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_exoticMC.root" # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_rho3_2mp3pp.root" fourPPamplFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/ampls_4++1+rhoPiG.dat" # inFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/results_std11.root" zeroFileName = inFileName # sectors = ["Dp[pi,pi]0++PiS","Dp[pi,pi]1--PiP"] # sectors = ["Dp[pi,pi]0++PiS"] sectors = ["Dp[pi,pi]1--PiP"] # # # # # Std11 Definitions std11_0mp0p = ["0-+0+[pi,pi]0++PiS", "0-+0+[pi,pi]1--PiP"] std11_1pp0p = ["1++0+[pi,pi]0++PiP", "1++0+[pi,pi]1--PiS"] std11_1pp1p = ["1++1+[pi,pi]1--PiS"] std11_2pp1p = ["2++1+[pi,pi]1--PiD"] std11_2mp0p = [ "2-+0+[pi,pi]0++PiD", "2-+0+[pi,pi]1--PiP", "2-+0+[pi,pi]1--PiF", "2-+0+[pi,pi]2++PiS" ] std11_2mp1p = ["2-+1+[pi,pi]1--PiP"] # # # # # Bigger 1++ definitions # sectors = std11_1pp0p + ["1++0+[pi,pi]1--PiD", "1++0+[pi,pi]2++PiP"] # # # # # Exotic (1-+) sector_exotic = ["1-+1+[pi,pi]1--PiP"] neg_1m1m = ["1-+1-[pi,pi]1--PiP"] neg_1P0m = ["1++1-[pi,pi]1--PiS"] # # # # # qBigger 2++ definitions # sectors = std11_2pp1p + ["2++1+[pi,pi]2++PiP"] # # # # # Bigger 2-+ definitions # sectors = std11_2mp0p + ["2-+0+[pi,pi]2++PiD"] # sectors = std11_2mp1p + ["2-+1+[pi,pi]2++PiS"] sectors = [ "2-+0+[pi,pi]1--PiP", "2-+0+[pi,pi]1--PiF", "2-+0+[pi,pi]2++PiS", "2-+0+[pi,pi]2++PiD", "2-+0+[pi,pi]3--PiP" ] # sectors = ["2-+0+[pi,pi]3--PiP"] # # # # # 3++ # sectors = ["3++0+[pi,pi]1--PiD", "3++0+[pi,pi]2++PiP", "3++0+[pi,pi]3--PiS"] # sectors = ["3++0+[pi,pi]2++PiP"] # # # # # 4++ # sectors = ["4++1+[pi,pi]1--PiG", "4++1+[pi,pi]2++PiF"] # sectors = ["4++1+[pi,pi]1--PiG"] # sectors = ["4++1+[pi,pi]2++PiF"] # # # # # 4-+ # sectors = ["4-+0+[pi,pi]1--PiF"] # # # # # 6-+ # sectors = ["6-+0+[pi,pi]1--PiH"] # sectors = ["2-+0+[pi,pi]2++PiD"] sectors = ["2-+0+[pi,pi]2++PiS"] sectors = std11_0mp0p # sectors = sector_exotic # sectors = std11_1pp0p # sectors = std11_1pp1p # sectors = neg_1P0m # sectors = std11_2mp0p # sectors = std11_2mp1p # + ["2-+1+[pi,pi]2++PiS"] # sectors = std11_2pp1p # sectors = ["2-+1+[pi,pi]2++PiS"] # referenceWave = "4-+0+rhoPiF" referenceWave = "" # sectors = std11_0mp0p[:1] doSpecialOneBinFit = -34 # negative values turn it off sectorUseMap = { # Defines, if for the given sector a theory curve will be used "0-+0+[pi,pi]0++PiS": True, "0-+0+[pi,pi]1--PiP": True, "1++0+[pi,pi]0++PiP": True, "1++0+[pi,pi]1--PiS": True, "2-+0+[pi,pi]0++PiD": False, "2-+0+[pi,pi]1--PiP": True, "2-+0+[pi,pi]1--PiF": True, "2-+0+[pi,pi]2++PiS": True, "2-+0+[pi,pi]3--PiP": True } sectorRangeMap = { # "2-+0+[pi,pi]1--PiP" : (0., 1.12), # "2-+0+[pi,pi]1--PiF" : (0., 1.12), # "2-+0+[pi,pi]2++PiS" : (0., 1.5 ), } for sector in sectors: if '1--' in sector: pass # sectorRangeMap[sector] = (0.55,1.00) if '0++' in sector: pass # sectorRangeMap[sector] = (0.,.94) if "extensiveFreedIsobarStudies" in inFileName: ppppppppp = False else: ppppppppp = True tBin = 0 if not ppppppppp: startBin = 25 stopBin = 50 # startBin = 27 # stopBin = startBin+1 else: startBin = 34 stopBin = 35 # startBin = 25 # stopBin = 26 polynomialDegree = 0 if not ppppppppp: modelMode = "fixedShapes" else: modelMode = "simpleBW_Dp" # modelMode = "fixedRhoExotic" # modelMode = "pipiS" # modelMode = "none" # modelMode = "simpleBW_Dp" # modelMode = "BW" # modelMode = "explicitRhoFile" useSmooth = False fitShape = True phaseFit = False produceTotals = False if modelMode == "BW" or modelMode == "2BW": # rho = pc.breitWigner() rho = pc.rpwaBreitWignerInt(0.13957018, 0.13957018, 0.13957018, 1, 0) f2 = pc.rpwaBreitWignerInt(0.13957018, 0.13957018, 0.13957018, 2, 0) rhoParameters = [.77549, .1491] f2Parameters = [1.2, 1.7] f2.setParameters(f2Parameters) # rhoParameters = [1.2, .2] rho.setParameters(rhoParameters) # rho.weightIntens = True # rhoParameters = [1.27549, .100] rhoPrime = pc.breitWigner() rhoPrimeParameters = [1.570, 0.144] rhoPrime.setParameters(rhoPrimeParameters) rhoModel = [rho] f2Model = [f2] if modelMode == "2BW": rhoModel.append(rhoPrime) waveModel = {} for sector in sectors: if '1--' in sector: waveModel[sector] = rhoModel elif "3--" in sector: waveModel[sector] = rhoModel elif "2++" in sector: waveModel[sector] = f2Model elif modelMode == "fixedRhoExotic": pdgMass = 0.7690 pdgWidth = 0.1509 massRho = ptc.parameter(pdgMass + 0.0, "rhoMass") widthRho = ptc.parameter(pdgWidth + 0.0, "rhoWidth") massRho.lock = True widthRho.lock = True rho = ptc.breitWigner([massRho, widthRho]) waveModel = {"1-+1+[pi,pi]1--PiP": [rho]} elif modelMode == "simpleBW_Dp": theWarning = """ Keep in mind the two-step procedure: - fix with the shifted - c&p the parameters - set the parameters by hand - run with the non-shifted "truth" parameters """ print theWarning f0Mass = ptc.parameter(.98, "f0Mass") f0Width = ptc.parameter(.1, "f0Width") # rhoMass = ptc.parameter(.77 + .2 + .5, "rhoMass") # rhoWidth = ptc.parameter(.16 + .1 + .1, "rhoWidth") rhoMass = ptc.parameter(.77, "rhoMass") rhoWidth = ptc.parameter(.16, "rhoWidth") # rhoMass = ptc.parameter(.77 + .2 , "rhoMass") # rhoWidth = ptc.parameter(.16 + .1 , "rhoWidth") # rhoMass = ptc.parameter(.77 + .2 + .3 , "rhoMass") # rhoWidth = ptc.parameter(.16 + .1 + .1, "rhoWidth") # rhoPMass = ptc.parameter(1.4, "rhoMass") # rhoPWidth = ptc.parameter(0.2, "rhoWidth") # f0Mass = ptc.parameter(1.4 , "f0Mass" ) # f0Width = ptc.parameter( .1 , "f0Width" ) # rhoMass = ptc.parameter( .77, "rhoMass" ) # rhoWidth = ptc.parameter( .16, "rhoWidth") # f0Mass = ptc.parameter(1., "f0Mass" ) # f0Width = ptc.parameter(.11 ,"f0Width") # rhoMass = ptc.parameter(.75, "rhoMass") # rhoWidparamsFarIntens.pdfth = ptc.parameter(.18, "rhoWidth") f0Mass.lock = True f0Width.lock = True rhoMass.lock = True rhoWidth.lock = True # rhoPMass.lock = True; rhoPWidth.lock = True f0 = ptc.breitWigner([f0Mass, f0Width]) rho = ptc.breitWigner([rhoMass, rhoWidth]) # rhoP = ptc.breitWigner([rhoPMass, rhoPWidth]) # f2 = pc.breitWigner() # f2.setParameters([1.27, .2 ]) # waveModel = {"Dp[pi,pi]0++PiS" : [f0], "Dp[pi,pi]1--PiP" : [rho], "Dp[pi,pi]2++PiD" : [f2]} waveModel = {"Dp[pi,pi]0++PiS": [f0], "Dp[pi,pi]1--PiP": [rho]} # waveModel = {"Dp[pi,pi]0++PiS" : [f0]} # waveModel = {"Dp[pi,pi]1--PiP" : [rho]} elif modelMode == "fixedShapes": useBF = False merge0pp = False polyDegree = 0 polyComplex = True waveModel = {} for sector in sectors: # if "3--" in sector: # rho = pc.rpwaBreitWignerInt(0.13957018,0.13957018,0.13957018,1,1) # rho.setParameters([1.2, .2]) # model = [rho] # waveModel[sector] = model # continue if sector in sectorUseMap: if not sectorUseMap[sector]: continue model = [] fileNames = getFileNameForSector(sector, useBF, merge0pp) # print fileNames for fn in fileNames: param = pc.fixedParameterization(fn, polynomialDegree=polyDegree, complexPolynomial=polyComplex) model.append(param) waveModel[sector] = model # for sector in sectors: # Ovveride with free rho parameterization # if '1--' in sector: # rho = pc.rpwaBreitWignerInt(0.13957018,0.13957018,0.13957018,1,0) # Override here # rho.setParameters([.77549, .1491]) # waveModel[sector] = [rho] elif modelMode == "explicitRhoFile": if not os.path.isfile(rhoFileName): raise IOError("Rho file does not exist") param = pc.fixedParameterization(rhoFileName, polynomialDegree=0, complexPolynomial=False) waveModel = {} for sector in sectors: if '1--' in sector: waveModel[sector] = [param] elif modelMode == "pipiS": pipiSfileName = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/anything/zeroModes/bwAmplitudes_noBF/amp_0mp0pSigmaPiS" pipiSw = pc.fixedParameterization(pipiSfileName, polynomialDegree=0, complexPolynomial=False) waveModel = {"0-+0+[pi,pi]0++PiS": [pipiSw]} elif modelMode == "none": waveModel = {} for sector in sectors: waveModel[sector] = [] else: raise RuntimeError("modelMode: '" + modelMode + "' is unknown") uniCOMA = False with root_open(inFileName, "READ") as inFile: histNames = GetKeyNames(inFile) histListReal = [] histListImag = [] histListNorm = [] histListIndx = [] nAmplMax = 0 for sector in sectors: realHistName = sector + "_" + str(tBin) + "_real" histReal = inFile.Get(realHistName) if not histReal: raise IOError("Could not get '" + realHistName + "' from '" + inFileName + "'") histReal.SetDirectory(0) histListReal.append(histReal) imagHistName = sector + "_" + str(tBin) + "_imag" histImag = inFile.Get(imagHistName) if not histImag: raise IOError("Could not get '" + imagHistName + "' from '" + inFileName + "'") histImag.SetDirectory(0) histListImag.append(histImag) normHistName = sector + "_" + str(tBin) + "_norm" histNorm = inFile.Get(normHistName) if not histNorm: raise IOError("Could not get '" + normHistName + "' from '" + inFileName + "'") histNorm.SetDirectory(0) histListNorm.append(histNorm) indexHistName = sector + "_" + str(tBin) + "_index" histIndx = inFile.Get(indexHistName) if not histIndx: raise IOError("Could not get '" + indexHistName + "' from '" + inFileName + "'") histIndx.SetDirectory(0) nAmplMax = max(nAmplMax, int(2 * histIndx.GetMaximum())) histListIndx.append(histIndx) histsToFill = [] comaHists = [] intHistsReal = [] intHistsImag = [] for mBin in range(startBin, stopBin): comaHistName = "COMA_" + str(tBin) + "_" + str(mBin) comaHist = inFile.Get(comaHistName) if not comaHist: uniCOMA = True print "Could not get '" + comaHistName + "' from '" + inFileName + "'", "USING IDENTITY" comaHist = pyRootPwa.ROOT.TH2D(comaHistName, comaHistName, nAmplMax, 0., 1., nAmplMax, 0., 1.) for i in range(nAmplMax): comaHist.SetBinContent(i + 1, i + 1, 1.) comaHist.SetDirectory(0) if produceTotals: realHistName = "INTEGRAL_r_" + str(tBin) + "_" + str(mBin) realHist = inFile.Get(realHistName) if not realHist: raise IOError("Could not get '" + realHistName + "' from '" + inFileName + "'") intHistsReal.append(realHist) imagHistName = "INTEGRAL_i_" + str(tBin) + "_" + str(mBin) imagHist = inFile.Get(imagHistName) imagHist.SetDirectory(0) if not imagHist: raise IOError("Could not get '" + imagHistName + "' from '" + inFileName + "'") intHistsImag.append(imagHist) comaHists.append(comaHist) if not referenceWave == "": refHistReal = inFile.Get(referenceWave + "_" + str(tBin) + "_real") refHistReal.SetDirectory(0) if not refHistReal: raise IOError("Could not get '" + referenceWave + "_" + str(tBin) + "_real" + "' from '" + self.inFileName + "'") refHistImag = inFile.Get(referenceWave + "_" + str(tBin) + "_imag") refHistImag.SetDirectory(0) if not refHistImag: raise IOError("Could not get '" + referenceWave + "_" + str(tBin) + "_imag" + "' from '" + self.inFileName + "'") refHistIndex = inFile.Get(referenceWave + "_" + str(tBin) + "_index") refHistIndex.SetDirectory(0) if not refHistIndex: raise IOError("Could not get '" + referenceWave + "_" + str(tBin) + "_index" + "' from '" + self.inFileName + "'") changeReferenceWave(histListReal, histListImag, histListIndx, comaHists, refHistReal, refHistImag, refHistIndex, startBin, stopBin) ab = allBins(startBin, stopBin, histListReal, histListImag, histListNorm, histListIndx, comaHists, intHistsReal, intHistsImag) with root_open(zeroFileName, "READ") as inFile: zeroCount = 0 zeroHistList = [] eigenHistList = [] while True: zeroName = "zero" + str(zeroCount) + "_" + str(tBin) eigenName = "eigen" + str(zeroCount) + "_" + str(tBin) zeroHist = inFile.Get(zeroName) if not zeroHist: break zeroHist.SetDirectory(0) # print "Adding zero-mode" zeroCount += 1 if not zeroForSectors(sectors, zeroHist.GetTitle()): continue zeroHistList.append(zeroHist) eigenHist = inFile.Get(eigenName) eigenHist.SetDirectory(0) if eigenHist: eigenHistList.append(eigenHist) if (not len(eigenHistList) == 0) and (not len(eigenHistList) == len(zeroHistList)): raise ValueError( "Number of eigenvalue histograms does not match, but is also nonzero" ) removeCertainZeroModes(zeroHistList, eigenHistList) for zeroHist in zeroHistList: borders = getZeroHistBorders(zeroHist) ab.addZeroMode(borders, zeroHist) rotateToFourPPampls = False if rotateToFourPPampls: fourPPampls = loadAmplsTM(fourPPamplFileName) ab.removePhases(fourPPampls[tBin][startBin:stopBin]) # ab.rotateToPhaseOfBin(10) zeroModeComaVal = 100. #float(sys.argv[1]) # zeroModeComaVal = 100000. # zeroModeComaVal = "unchanged" # ab.removeZeroModeFromComa() # ab.addComaValueForZeroMode(zeroModeComaVal) # ab.removeGlobalPhaseFromComa() if phaseFit: ab.setMassRanges(sectorRangeMap) for mb in ab.massBins: mb.setZeroTheory() from random import random ab.initChi2(waveModel) nBin = startBin leBin = ab.massBins[nBin - startBin] nTries = 10 mnn = float("inf") # for tr in range(nTries): # print "at",tr,'/',nTries # pars = [random() for _ in range(leBin.nParAll())] ## print leBin.phaseChi2(pars) # res = scipy.optimize.minimize(leBin.phaseChi2, pars) # if res.fun < mnn: # print "Improved from",mnn,"to",res.fun,"in try",tr # mnn = res.fun # bestPar = res.x[:] # print bestPar, "bestPar" paramsPhaseChi2 = [ 148.57310258, 143.66171657, 116.67030827, -6.8412118 ] paramsAmplChi2 = [ -52.51465293, -10.3576874, 6.69282325, 64.28970961 ] print "----------------====----------------------------" leBin.phaseChi2(paramsPhaseChi2) print "----------------====----------------------------" leBin.phaseChi2(paramsAmplChi2) print "----------------====----------------------------" # paramsZ = [bestPar[0], bestPar[1]] * 1 # Very, very bad hack... # paramsZ = paramsPhaseChi2[:2] ptu = paramsAmplChi2 leBin.phaseChi2(ptu) paramsZ = ptu[:2] if doSpecialOneBinFit >= 0: specialBin = ab.massBins[doSpecialOneBinFit] specialBin.initChi2(waveModel) print "Doing special fit for: ", +specialBin.bin3pi pars = [.77549, .1491] if modelMode == "explicitRhoFile": return specialBin.chi2([]) res = scipy.optimize.minimize(specialBin.chi2, pars) hi = res.hess_inv print "m0 = ", res.x[0], "+-", (2 * hi[0, 0])**.5 print "G0 = ", res.x[1], "+-", (2 * hi[1, 1])**.5 print "Giving a Chi2 of:", res.fun sys.exit(0) if not useSmooth and not phaseFit and not modelMode == "none": ab.initChi2(waveModel) ab.setMassRanges(sectorRangeMap) totalPars = [] for k in waveModel: for f in waveModel[k]: totalPars += f.getParameters() shapePars = [] if not len(totalPars) == 0 and fitShape: res = scipy.optimize.minimize(ab.chi2, totalPars) hi = res.hess_inv print "m0 = ", res.x[0], "+-", (2 * hi[0, 0])**.5 print "G0 = ", res.x[1], "+-", (2 * hi[1, 1])**.5 print "Giving a Chi2 of:", res.fun shapePars = res.x # for k in waveModel: # for f in waveModel[k]: # print "function parameters",f.getParameters() chi2, params = ab.chi2(shapePars, returnParameters=True) errs = ab.getNonShapeUncertainties(shapePars) # print "pars", len(params[0]) # print "errs",len(errs[0]) # print params,"params" # print "fitted = [", # for i in range(1, len(params[0])/2): # if not i == 1: # print ',', # print params[0][2*i], '+'+ str(params[0][2*i+1])+'j', # print ']' paramsZ = ab.linearizeZeroModeParameters(params) # print "I am here!!!,", paramsZ zmPar = ab.getNonShapeParameters() ab.setTheoryFromOwnFunctions(params, True) # print "The final chi2 =",chi2 # with open("theFinalChi2s.txt", 'a') as out: # out.write("zero-mode-coma-val "+str(zeroModeComaVal) + " finalChi2 " + str(chi2) +'\n') elif not phaseFit: A, B, C = ab.getSmoothnessABC() paramsZ = -np.dot(la.inv(A + np.transpose(A)), B) if modelMode == 'none': ab.initChi2(waveModel) params = [] for mb in ab.massBins: params.append([0.] * mb.nFunc * 2) ab.setTheoryFromOwnFunctions(params, True) # for i in range(len(paramsZ)): # paramsZ[i] = 0. # ab.writeZeroModeCoefficients(paramsZ, "zeroModeCorrections_std11", str(tBin)) # for i in range(len(zmPar)): # for j in range(len(zmPar[i])-2,len(zmPar[i])): # zmPar[i][j] = 0. # c2 = ab.getChi2forNonShapeParameters(zmPar) # c2Res = ab.eigenbasisChi2contributions(zmPar) # c2Sum = 0. # for pair in c2Res[0]: # c2Sum += pair[1]**2/pair[0] # with open("chi2Contribitions.txt", 'w') as outFile: # for i,val in enumerate(c2Res[0]): # outFile.write(str(i) + ' ' + str(val[0]) + ' ' + str(val[1]) + ' ' + str(val[1]/val[0]**.5) + '\n') # print c2, c2Sum # print sys.argv[1], sys.argv[2], "-->>|", ab.getChi2forNonShapeParameters(zmPar), # ab.removeAllCorrelations(removeReImCorrel = False) # print ab.getChi2forNonShapeParameters(zmPar), # ab.removeAllCorrelations(removeReImCorrel = True) # print ab.getChi2forNonShapeParameters(zmPar),"|<<--" # return intenses = [] reals = [] imags = [] correl = [] phases = [] intensD = [] realsD = [] imagsD = [] phasesD = [] intensT = [] realsT = [] imagsT = [] phasesT = [] for rh in histListReal: Ih = rh.Clone() Ih.Reset() intenses.append(Ih) realH = rh.Clone() realH.Reset() reals.append(realH) imagH = rh.Clone() imagH.Reset() imags.append(imagH) reImCorrH = rh.Clone() reImCorrH.Reset() correl.append(reImCorrH) phaseH = rh.Clone() phaseH.Reset() phases.append(phaseH) ID = rh.Clone() ID.Reset() intensD.append(ID) rD = rh.Clone() rD.Reset() realsD.append(rD) iD = rh.Clone() iD.Reset() imagsD.append(iD) pD = rh.Clone() pD.Reset() phasesD.append(pD) IT = rh.Clone() IT.Reset() intensT.append(IT) rT = rh.Clone() rT.Reset() realsT.append(rT) iT = rh.Clone() iT.Reset() imagsT.append(iT) pT = rh.Clone() pT.Reset() phasesT.append(pT) zeroP = [0.] * len(paramsZ) # paramsZ = zeroP # print paramsZ # paramsZ = np.asarray([ 329.73899894 , 150.29589973]) # For the wrong parameterizations in the D decay # paramsZ = np.asarray([ -49.77267381, 2.93486152]) # For the P-only for in 0-+0+ at bin 25 if not uniCOMA: ab.removeZeroModeFromComa() ab.removeGlobalPhaseFromComa() if produceTotals: hists = [] for m in range(len(sectors)): hists.append(get3PiHistogram(sectors[m] + "_t" + str(tBin))) ab.fillTotal(paramsZ, hists) with root_open("totals_noZeroModeWavesFromStd11.root", "UPDATE"): for h in hists: h.Write() return ab.fillHistograms(paramsZ, intenses) ab.fillHistograms(paramsZ, reals, mode=REAL) ab.fillHistograms(paramsZ, imags, mode=IMAG) ab.fillHistograms(paramsZ, phases, mode=PHASE) ab.fillHistograms(paramsZ, correl, mode=REIMCORRELATION) ab.fillHistograms(zeroP, intensD) ab.fillHistograms(zeroP, realsD, mode=REAL) ab.fillHistograms(zeroP, imagsD, mode=IMAG) ab.fillHistograms(zeroP, phasesD, mode=PHASE) if not useSmooth: ab.fillHistograms(zeroP, intensT, mode=INTENSTHEO) ab.fillHistograms(zeroP, realsT, mode=REALTHEO) ab.fillHistograms(zeroP, imagsT, mode=IMAGTHEO) ab.fillHistograms(zeroP, phasesT, mode=PHASETHEO) for i in range(len(histListReal)): renormToBinWidth(intenses[i]) renormToBinWidth(intensD[i]) renormToBinWidth(intensT[i]) renormToBinWidth(reals[i], .5) renormToBinWidth(realsD[i], .5) renormToBinWidth(realsT[i], .5) renormToBinWidth(imags[i], .5) renormToBinWidth(imagsD[i], .5) renormToBinWidth(imagsT[i], .5) renormToBinWidth(correl[i], ) allIsZero = True for binX in range(intensT[i].GetNbinsX()): for binY in range(intensT[i].GetNbinsY()): if not intensT[i].GetBinContent(binX + 1, binY + 1) == 0.: allIsZero = False break if not allIsZero: break # # # # # # # # # # # # # # # # # ric = correl[i] noRun = False if not allIsZero: rv = resultViewer([intenses[i], intensD[i], intensT[i]], [reals[i], realsD[i], realsT[i]], [imags[i], imagsD[i], imagsT[i]], [phases[i], phasesD[i], phasesT[i]], startBin=startBin, reImCorrel=ric, noRun=noRun) else: rv = resultViewer([intenses[i], intensD[i]], [reals[i], realsD[i]], [imags[i], imagsD[i]], [phases[i], phasesD[i]], startBin=startBin, reImCorrel=ric, noRun=noRun) rv.titleRight = getProperWaveName(sectors[i]) # rv.titleRight = r"$0^{-+}0^+[\pi\pi]_{0^{++}}\pi$S" # rv.titleRight = r"$0^{-+}0^+[\pi\pi]_{1^{--}}\pi$P" # rv.tString = "" rv.tString = getProperDataSet(inFileName, tBin) # rv.tString = "Monte Carlo" # rv.tString = "" rv.titleFontSize = 11 rv.printLiminary = False rv.topMarginIntens = 1.4 # rv.scaleTo = "corr" # rv.writeBinToPdf(startBin, stdCmd = ["rhoFixing_2D.pdf", "rhoFixing_intens.pdf", [], "rhoFixing_argand.pdf", []]) # rv.plotCorr = False # rv.plotTheo = False # rv.plotData = False rv.run()
def main(): checkLaTeX() style = modernplotting.mpplot.PlotterStyle() # style.p2dColorMap = 'ocean_r' # style.p2dColorMap = 'YlOrRd' style.p2dColorMap = 'Reds' referenceWave = globalReferenceWave tBin = int(sys.argv[1]) if tBin < 0 or tBin > 3: raise ValueError("Invalid t' bin: " + str(tBin)) sect = sys.argv[2] if not sect in [ '1++1+', '2-+1+', '2-+1+2++', '2-+1+2++', '2++1+', '2++1+2++', '4++1+1--', '4++1+2++', '3++0+', "4-+0+", "6-+0+" ]: raise RuntimeError("Invalid sector '" + sect + "'") if len(sys.argv) > 3: study = sys.argv[3] studyAdder = "_" + study else: study = "std11" studyAdder = "" print "Study: " + study # sect = '1++1+' # sect = '2-+1+' # sect = '2++1+' startBin = 11 stopBin = 50 isRho = True sectorRangeMap = {} isobName = "rho" restrictRhoRange = True rhoRange = 1.2 if sect == '1++1+': sector = "1++1+[pi,pi]1--PiS" if restrictRhoRange: sectorRangeMap = {"1++1+[pi,pi]1--PiS": (0., rhoRange)} L = 0 if sect == '2-+1+': sector = "2-+1+[pi,pi]1--PiP" L = 1 if restrictRhoRange: sectorRangeMap = {"2-+1+[pi,pi]1--PiP": (0., rhoRange)} if sect == '2-+1+2++': sector = "2-+1+[pi,pi]2++PiS" L = 0 isRho = False # startBin = 22 isobName = "f2" if sect == '2++1+': sector = "2++1+[pi,pi]1--PiD" L = 2 if restrictRhoRange: sectorRangeMap = {"2++1+[pi,pi]1--PiD": (0., rhoRange)} if sect == "2++1+2++": sector = "2++1+[pi,pi]2++PiP" L = 1 stRtBin = 22 isRho = False isobName = "f2" if sect == '4++1+1--': sector = '4++1+[pi,pi]1--PiG' L = 4 if restrictRhoRange: sectorRangeMap = {'4++1+[pi,pi]1--PiG': (0., rhoRange)} if sect == '4++1+2++': sector = '4++1+[pi,pi]2++PiF' L = 3 isRho = False # startBin = 22 isobName = "f2" if sect == "3++0+": sector = "3++0+[pi,pi]2++PiP" L = 1 isRho = False # startBin = 22 isobName = "f2" if sect == "4-+0+": sector = "4-+0+[pi,pi]1--PiF" referenceWave = "6-+0+rhoPiH" if restrictRhoRange: sectorRangeMap = {"4-+0+[pi,pi]1--PiF": (0., rhoRange)} L = 3 if sect == "6-+0+": sector = "6-+0+[pi,pi]1--PiH" L = 5 if restrictRhoRange: sectorRangeMap = {"6-+0+[pi,pi]1--PiH": (0., rhoRange)} inFileName = fileNameMap[study] # phaseFileName = "/nfs/mds/user/fkrinner/extensiveFreedIsobarStudies/ampls_4++1+rhoPiG.dat" phaseFileName = "" tBins = [tBin] allMethods = {} methodStrings = {} shortlabels = { "fixedShapeF0": r"$\text{fix}_{f_0}^{~}$", "fixedShapeRho": r"$\text{fix}_\rho^{~}$", "fixedShapeRho1G": r"$\text{fix}_\rho^{1\Gamma}$", "fixedShapeRho2G": r"$\text{fix}_\rho^{2\Gamma}$", "fixedShapes": r"$\text{fix}_\text{all}^{~}$", "pipiS": r"$\phi_{[\pi\pi]_S}^{~}$", "fitRho": r"$\text{fit}_\rho^{~}$", "fitRho1G": r"$\text{fit}_\rho^{1\Gamma}$", "fitRho2G": r"$\text{fit}_\rho^{2\Gamma}$", "smooth": r"smooth" } if isRho: print "Fit is rho" globalFileName = "rhoMassesAndWidths_" + sect if restrictRhoRange: globalFileName += "_range" + str(rhoRange) globalFileName += "_global.dat" model = getRhoModel(inFileName, sector, startBin, stopBin, tBins, sectorRangeMap, L=L, writeResultToFile=globalFileName, referenceWave=referenceWave, loadIntegrals=True) else: print "Fit is f2" model = getF2Model(inFileName, sector, startBin, stopBin, tBins, sectorRangeMap, L=L, writeResultToFile="f2MassesAndWidths_" + sect + "_global.dat", referenceWave=referenceWave, loadIntegrals=True) ##### Writing starts here print "From", startBin, 'to', stopBin parameterDummy = [[] * (stopBin - startBin)] if isRho: outFileName = "./rhoMassesAndWidths" else: outFileName = "./f2MassesAndWidths" if restrictRhoRange: outFileName += "_range" + str(rhoRange) doResonanceFits = True binWiseFit = True if doResonanceFits: with open(outFileName + '_' + sect + "_" + str(tBin) + ".dat", 'w') as outFile: if binWiseFit: bins = range(stopBin - startBin) else: bins = [1] for i in bins: binIndex = i + startBin outFile.write( str(binIndex) + ' ' + str(0.52 + 0.04 * binIndex) + ' ') startValueOffset = 0.00 exceptCount = 0 while True: try: # if True: if binWiseFit: fitRange = [i] else: fitRange = range(stopBin - startBin) if isRho: startVals = [ mRho + startValueOffset, Grho + startValueOffset ] else: startVals = [ mF2 + startValueOffset, GF2 + startValueOffset ] x, err, c2, ndf = model.fitShapeParametersForBinRange( startVals, [0], fitRange, zeroModeParameters=parameterDummy) break except: print "Fitter exception encountered" startValueOffset += 0.001 exceptCount += 1 if exceptCount > 3: raise Exception("Too many failed attempts: " + str(exceptCount)) if sect == "3++0+": with open("3pp_f2_cpls_" + str(tBin) + ".dat", 'w') as outFileCpl: model.calculateNonShapeParameters() cpl, hess = model.getCouplingParameters() outFileCpl.write(str(cpl)) outFileCpl.write("\n") outFileCpl.write(str(hess)) nBin = startBin + i if nBin in []: model.calculateNonShapeParameters() folder = "/nfs/freenas/tuph/e18/project/compass/analysis/fkrinner/fkrinner/trunk/massDependentFit/scripts/zeroModeFitter_2D/rhoShapes4pp" rv = model.produceResultViewer(parameterDummy, sector, noRun=True, plotTheory=True) rv.writeBinToPdf( nBin, stdCmd=[ "", folder + "/" + isobName + "Shape_" + sector + "_intens_" + str(nBin) + "_" + str(tBin) + ".pdf", [], folder + "/" + isobName + "Shape_" + sector + "_argand_" + str(nBin) + "_" + str(tBin) + ".pdf", [] ]) outFile.write( str(x[0]) + ' ' + str(err[0]) + ' ' + str(x[1]) + ' ' + str(err[1])) outFile.write(' ' + str(c2 / ndf) + '\n') return fileNames = {} for stu in allMethods: print "Writing for '" + stu + "'" for s, sect in enumerate(allMethods[stu].sectors): if stu == "pipiS": rv = allMethods[stu].produceResultViewer( allMethods[stu].getZeroModeParametersForMode(), s, plotTheory=True) rv.run() rv = allMethods[stu].produceResultViewer( allMethods[stu].getZeroModeParametersForMode(), s, noRun=True) for bin in range(startBin, stopBin): fileName = "./collectedMethods/" + stu + "_" + sect + "_0mpData_" + str( bin) + studyAdder if not (sect, bin) in fileNames: fileNames[sect, bin] = [] fileNames[sect, bin].append(fileName) rv.writeAmplFiles(bin, fileName=fileName) makeTotals = False if makeTotals: model.calculateNonShapeParameters() totalHists = model.getTotalHists(model.getZeroModeParametersForMode()) with root_open("./totals_2mp1p" + studyAdder + ".root", "UPDATE") as out: for t in totalHists: for m in t: m.Write() folder = "./comparisonResultsData" + studyAdder + "/" for s, sect in enumerate(model.sectors): model.removeZeroModeFromComa() model.removeGlobalPhaseFromComa() zeroParDummy = [[] * (stopBin - startBin)] model.calculateNonShapeParameters() rv = model.produceResultViewer(zeroParDummy, s, noRun=True, plotTheory=True) rv.plotData = False rv.writeBinToPdf(startBin, stdCmd=[ folder + sect + "_data_2D_" + str(tBin) + ".pdf", "", [], "", [] ]) for b in range(startBin, stopBin): # intensNames = [name+".intens" for name in fileNames[sect,b]] # argandNames = [name+".argand" for name in fileNames[sect,b]] intensNames = [] argandNames = [] rv.writeBinToPdf(b, stdCmd=[ "", folder + sect + "_data_intens_" + str(b) + "_" + str(tBin) + ".pdf", intensNames, folder + sect + "_data_argand_" + str(b) + "_" + str(tBin) + ".pdf", argandNames ])