Example #1
0
def MergeSamples(hists,options,requireFullyMerged=False) :
    #
    # Yeah so this adds the samples together that you specify, in a resonable
    # order close to the one you specify in the command line "bkgs"
    # If you require that the samples are fully merged, this means that N
    # inputs is merged into one output (a check we require for data).
    #
    import math
    import ROOT
    import PyHelpers
    import re

    if not options.mergesamples :
        return hists

    hists_new = []
    keys_new = []
    hists_index = dict()
    for i in hists :
        added = False
        for j in options.mergesamples.keys() :

            # Compare to regexp
            if type(options.mergesamples[j]) == type('') :
                if not re.match(options.mergesamples[j].replace('%','.*'),i.GetTitle()) :
                    continue

            # Compare to list of samples
            if type(options.mergesamples[j]) == type([]) :
                match = False
                for mergesample in options.mergesamples[j] :
                    if re.match(mergesample.replace('%','.*'),i.GetTitle()) :
                        match = True
                if not match :
                    continue

            if j in hists_index.keys() :
                #print 'adding to existing histo'
                hists_new[hists_index[j]].Add(i)
                added = True
            else :
                #print 'starting a new histo'
                hists_index[j] = len(hists_new)
                hists_new.append(i)
                keys_new.append(j)
                hists_new[-1].SetTitle(j)
                hists_new[-1].SetName(CleanUpName(j))
                added = True
        if not added :
            hists_new.append(i)
            keys_new.append(i.GetTitle())

    for i in hists_index.keys() :
        PyHelpers.PrintNumberOfEvents(hists_new[hists_index[i]])

    if requireFullyMerged and len(hists_new) > 1 :
        print 'Error! Failed to merge histograms into one histogram! (Usually required for data.) Check your sample merging.'
        SafeExit(options.xAODInit)

    return hists_new
Example #2
0
def initCityUnit(city, sUnitClass):
    """
	都市とユニットクラス名を指定して、都市のオーナーの支配下でユニットを生成する
	都市はCyCityでもPyCityでもよい
	"""
    pyPlayer = PyHelpers.PyPlayer(city.getOwner())
    iUnit = getCivilizationUnitType(pyPlayer, sUnitClass)
    return pyPlayer.initUnit(iUnit, city.getX(), city.getY())
Example #3
0
def initCityUnitDirect(city, sUnit):
    """
	都市とユニット名を指定して、都市のオーナーの支配下でユニットを生成する
	都市はCyCityでもPyCityでもよい
	UnitClassでやるほうがいろいろと潰しがきくと思うので一応程度に
	"""
    pyPlayer = PyHelpers.PyPlayer(city.getOwner())
    iUnit = gc.getInfoTypeForString(sUnit)
    return pyPlayer.initUnit(iUnit, city.getX(), city.getY())
#

from CvPythonExtensions import *

import CvUtil
import CvEventManager
import sys
import PyHelpers
import CvConfigParser
import math
import time

gc = CyGlobalContext()

PyPlayer = PyHelpers.PyPlayer
PyGame = PyHelpers.PyGame()

localText = CyTranslator()

# Enables or disables route destruction through air bombs.
# Default value is true
g_bRouteDestructionThroughAirBombs = true

# Enables or disables experience gain from destroying improvements.
# Default value is true
g_bExperienceGainByDestroyingImprovements = true

# Enables or disables experience gain from destroying Routes.
# Default value is true
g_bExperienceGainByDestroyingRoutes = true
Example #5
0
def main(options, args):

    plotfunc.SetupStyle()

    files_b, trees_b, keys_b = anaplot.GetTreesFromFiles(
        options.bkgs, treename=options.treename)
    files_s, trees_s, keys_s = anaplot.GetTreesFromFiles(
        options.signal, treename=options.treename)
    file_d, tree_d, key_d = anaplot.GetChainFromFiles(
        options.data, treename=options.treename)

    scales_b = anaplot.GetScales(files_b, trees_b, keys_b, options)
    scales_s = anaplot.GetScales(files_s, trees_s, keys_s, options)

    dweight = ''  # weight value (and cuts) applied to data
    weight = options.weight
    if ''.join(options.cuts):
        weight = (weight + '*(%s)' %
                  (' && '.join(options.cuts + options.truthcuts))).lstrip('*')
        dweight = '(' + ' && '.join(options.cuts + options.blindcut) + ')'

    cans = []

    v1 = 'HGamEventInfoAuxDyn.m_yy/1000'
    v2 = 'HGamEventInfoAuxDyn.catCoup_Moriond2017BDT'

    bkg_hists = []
    sig_hists = []
    data_hist = None

    if options.data:
        data_hist = anaplot.Get2dVariableHistsFromTrees(
            tree_d, key_d, v1, v2, dweight, options)[0]
        data_hist.SetLineWidth(2)
        data_hist.SetLineColor(1)
        data_hist.SetMarkerColor(1)
    if options.bkgs:
        bkg_hists = anaplot.Get2dVariableHistsFromTrees(trees_b,
                                                        keys_b,
                                                        v1,
                                                        v2,
                                                        weight,
                                                        options,
                                                        scales=scales_b)
        bkg_hists, keys_b = anaplot.MergeSamples(bkg_hists, options)
        anaplot.PrepareBkgHistosForStack(bkg_hists, options)
    if options.signal:
        sig_hists = anaplot.Get2dVariableHistsFromTrees(trees_s,
                                                        keys_s,
                                                        v1,
                                                        v2,
                                                        weight,
                                                        options,
                                                        scales=scales_s)
        sig_hists, keys_s = anaplot.MergeSamples(sig_hists, options)
        sig_hists[-1].SetLineColor(2)
        sig_hists[-1].SetMarkerColor(2)

    # get the histograms from the files
    for c in range(len(CouplingsHelpers.categories)):
        #if not categories[c] : continue

        lo_bin = c + 1
        hi_bin = c + 1
        if c == 0:  # inclusive case.
            lo_bin = 0
            hi_bin = 10000  # just to be safe, 10k categories

        # MERGE VH DILEP CATEGORIES (23 and 24 --> 23):
        if CouplingsHelpers.categories[c] == 'M17_VHdilep_LOW':
            hi_bin = hi_bin + 1
        # MERGE VH MET HIGH and BSM CATEGORIES (19 and 20 --> 19):
        if CouplingsHelpers.categories[c] == 'M17_VHMET_HIGH':
            hi_bin = hi_bin + 1

        name = 'c%d_%s' % (c, CouplingsHelpers.categories[c])

        bkg_projs = []
        sig_projs = []
        data_proj = None

        if options.data:
            data_proj = data_hist.ProjectionX('%s_data' % (name), lo_bin,
                                              hi_bin)
            PyHelpers.PrintNumberOfEvents(data_proj)
        if options.bkgs:
            for i, b in enumerate(bkg_hists):
                bkg_projs.append(
                    b.ProjectionX('%s_%s' % (name, keys_b[i]), lo_bin, hi_bin))
                PyHelpers.PrintNumberOfEvents(bkg_projs[-1])
        if options.signal:
            for i, s in enumerate(sig_hists):
                sig_projs.append(
                    s.ProjectionX('%s_%s' % (name, keys_s[i]), lo_bin, hi_bin))
                PyHelpers.PrintNumberOfEvents(sig_projs[-1])

        cans.append(
            anaplot.DrawHistos(v1,
                               options,
                               bkg_projs,
                               sig_projs,
                               data_proj,
                               name=name))
        cans[-1].SetName(anaplot.CleanUpName(name))

    anaplot.UpdateCanvases(options, cans)

    if not options.batch:
        raw_input('Press enter to exit')

    anaplot.doSaving(options, cans)

    # Do this afterwards, to make sure the outdir exists.
    f = ROOT.TFile('%s/couplings.root' % (options.outdir), 'RECREATE')
    for can in cans:
        for i in can.GetListOfPrimitives():
            if i.GetName()[-6:] == '_error':
                continue
            if 'stack' in i.GetName():
                if not issubclass(type(i), ROOT.THStack):
                    continue
                for j in range(i.GetNhists()):
                    print 'writing from stack:', i.GetHists()[j].GetName()
                    i.GetHists()[j].Write()
            if issubclass(type(i), ROOT.TH1):
                print 'writing:', i.GetName()
                i.Write()

    f.Close()

    print 'done.'
    return
Example #6
0
	def showVictoryConditionScreen(self):
					
		activePlayer = PyHelpers.PyPlayer(self.iActivePlayer)
		iActiveTeam = gc.getPlayer(self.iActivePlayer).getTeam()
		
		# Conquest
		nRivals = -1 
		for i in range(gc.getMAX_CIV_TEAMS()):
			if (gc.getTeam(i).isAlive() and not gc.getTeam(i).isMinorCiv() and not gc.getTeam(i).isBarbarian()):
				nRivals += 1

		# Population
		totalPop = gc.getGame().getTotalPopulation()
		ourPop = activePlayer.getTeam().getTotalPopulation()
		if (totalPop > 0):
			popPercent = (ourPop * 100.0) / totalPop
		else:
			popPercent = 0.0

		iBestPopTeam = -1
		bestPop = 0
		for iLoopTeam in range(gc.getMAX_CIV_TEAMS()):
			if (gc.getTeam(iLoopTeam).isAlive() and not gc.getTeam(iLoopTeam).isMinorCiv() and not gc.getTeam(iLoopTeam).isBarbarian()):
				if (iLoopTeam != iActiveTeam and (activePlayer.getTeam().isHasMet(iLoopTeam) or gc.getGame().isDebugMode())):
					teamPop = gc.getTeam(iLoopTeam).getTotalPopulation()
					if (teamPop > bestPop):
						bestPop = teamPop
						iBestPopTeam = iLoopTeam

		# Score
		ourScore = gc.getGame().getTeamScore(iActiveTeam)
			
		iBestScoreTeam = -1
		bestScore = 0
		for iLoopTeam in range(gc.getMAX_CIV_TEAMS()):
			if (gc.getTeam(iLoopTeam).isAlive() and not gc.getTeam(iLoopTeam).isMinorCiv() and not gc.getTeam(iLoopTeam).isBarbarian()):
				if (iLoopTeam != iActiveTeam and (activePlayer.getTeam().isHasMet(iLoopTeam) or gc.getGame().isDebugMode())):
					teamScore = gc.getGame().getTeamScore(iLoopTeam)
					if (teamScore > bestScore):
						bestScore = teamScore
						iBestScoreTeam = iLoopTeam

		# Land Area
		totalLand = gc.getMap().getLandPlots()
		ourLand = activePlayer.getTeam().getTotalLand()
		if (totalLand > 0):
			landPercent = (ourLand * 100.0) / totalLand
		else:
			landPercent = 0.0
			
		iBestLandTeam = -1
		bestLand = 0
		for iLoopTeam in range(gc.getMAX_CIV_TEAMS()):
			if (gc.getTeam(iLoopTeam).isAlive() and not gc.getTeam(iLoopTeam).isMinorCiv() and not gc.getTeam(iLoopTeam).isBarbarian()):
				if (iLoopTeam != iActiveTeam and (activePlayer.getTeam().isHasMet(iLoopTeam) or gc.getGame().isDebugMode())):
					teamLand = gc.getTeam(iLoopTeam).getTotalLand()
					if (teamLand > bestLand):
						bestLand = teamLand
						iBestLandTeam = iLoopTeam

		# Religion
		iOurReligion = -1
		ourReligionPercent = 0
		for iLoopReligion in range(gc.getNumReligionInfos()):
			if (activePlayer.getTeam().hasHolyCity(iLoopReligion)):
				religionPercent = gc.getGame().calculateReligionPercent(iLoopReligion)
				if (religionPercent > ourReligionPercent):
					ourReligionPercent = religionPercent
					iOurReligion = iLoopReligion

		iBestReligion = -1
		bestReligionPercent = 0
		for iLoopReligion in range(gc.getNumReligionInfos()):
			if (iLoopReligion != iOurReligion):
				religionPercent = gc.getGame().calculateReligionPercent(iLoopReligion)
				if (religionPercent > bestReligionPercent):
					bestReligionPercent = religionPercent
					iBestReligion = iLoopReligion

		# Total Culture
		ourCulture = activePlayer.getTeam().countTotalCulture()

		iBestCultureTeam = -1
		bestCulture = 0
		for iLoopTeam in range(gc.getMAX_CIV_TEAMS()):
			if (gc.getTeam(iLoopTeam).isAlive() and not gc.getTeam(iLoopTeam).isMinorCiv() and not gc.getTeam(iLoopTeam).isBarbarian()):
				if (iLoopTeam != iActiveTeam and (activePlayer.getTeam().isHasMet(iLoopTeam) or gc.getGame().isDebugMode())):
					teamCulture = gc.getTeam(iLoopTeam).countTotalCulture()
					if (teamCulture > bestCulture):
						bestCulture = teamCulture
						iBestCultureTeam = iLoopTeam

		# Vote
		aiVoteBuildingClass = []
		for i in range(gc.getNumBuildingInfos()):
			for j in range(gc.getNumVoteSourceInfos()):
				if (gc.getBuildingInfo(i).getVoteSourceType() == j):
					iUNTeam = -1
					bUnknown = true 
					for iLoopTeam in range(gc.getMAX_CIV_TEAMS()):
						if (gc.getTeam(iLoopTeam).isAlive() and not gc.getTeam(iLoopTeam).isMinorCiv() and not gc.getTeam(iLoopTeam).isBarbarian()):
							if (gc.getTeam(iLoopTeam).getBuildingClassCount(gc.getBuildingInfo(i).getBuildingClassType()) > 0):
								iUNTeam = iLoopTeam
								if (iLoopTeam == iActiveTeam or gc.getGame().isDebugMode() or activePlayer.getTeam().isHasMet(iLoopTeam)):
									bUnknown = false		
								break

					aiVoteBuildingClass.append((gc.getBuildingInfo(i).getBuildingClassType(), iUNTeam, bUnknown))

		self.bVoteTab = (len(aiVoteBuildingClass) > 0)
		
		self.deleteAllWidgets()	
		screen = self.getScreen()
														
		# Start filling in the table below
		screen.addPanel(self.getNextWidgetName(), "", "", False, False, self.X_AREA-10, self.Y_AREA-15, self.W_AREA+20, self.H_AREA+30, PanelStyles.PANEL_STYLE_BLUE50)
		szTable = self.getNextWidgetName()
		screen.addTableControlGFC(szTable, 6, self.X_AREA, self.Y_AREA, self.W_AREA, self.H_AREA, False, False, 32,32, TableStyles.TABLE_STYLE_STANDARD)
		screen.setTableColumnHeader(szTable, 0, "", self.TABLE_WIDTH_0)
		screen.setTableColumnHeader(szTable, 1, "", self.TABLE_WIDTH_1)
		screen.setTableColumnHeader(szTable, 2, "", self.TABLE_WIDTH_2)
		screen.setTableColumnHeader(szTable, 3, "", self.TABLE_WIDTH_3)
		screen.setTableColumnHeader(szTable, 4, "", self.TABLE_WIDTH_4)
		screen.setTableColumnHeader(szTable, 5, "", self.TABLE_WIDTH_5)
		screen.appendTableRow(szTable)
		
		for iLoopVC in range(gc.getNumVictoryInfos()):
			victory = gc.getVictoryInfo(iLoopVC)
			if gc.getGame().isVictoryValid(iLoopVC):
				
				iNumRows = screen.getTableNumRows(szTable)
				szVictoryType = u"<font=4b>" + victory.getDescription().upper() + u"</font>"
				if (victory.isEndScore() and (gc.getGame().getMaxTurns() > gc.getGame().getElapsedGameTurns())):
					szVictoryType += "    (" + localText.getText("TXT_KEY_MISC_TURNS_LEFT", (gc.getGame().getMaxTurns() - gc.getGame().getElapsedGameTurns(), )) + ")"

				iVictoryTitleRow = iNumRows - 1
				screen.setTableText(szTable, 0, iVictoryTitleRow, szVictoryType, "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
				bSpaceshipFound = False
					
				bEntriesFound = False
				
				if (victory.isTargetScore() and gc.getGame().getTargetScore() != 0):
										
					iRow = screen.appendTableRow(szTable)
					screen.setTableText(szTable, 0, iRow, localText.getText("TXT_KEY_VICTORY_SCREEN_TARGET_SCORE", (gc.getGame().getTargetScore(), )), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					screen.setTableText(szTable, 2, iRow, activePlayer.getTeam().getName() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					screen.setTableText(szTable, 3, iRow, (u"%d" % ourScore), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					
					if (iBestScoreTeam != -1):
						screen.setTableText(szTable, 4, iRow, gc.getTeam(iBestScoreTeam).getName() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						screen.setTableText(szTable, 5, iRow, (u"%d" % bestScore), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						
					bEntriesFound = True
				
				if (victory.isEndScore()):

					szText1 = localText.getText("TXT_KEY_VICTORY_SCREEN_HIGHEST_SCORE", (CyGameTextMgr().getTimeStr(gc.getGame().getStartTurn() + gc.getGame().getMaxTurns(), false), ))

					iRow = screen.appendTableRow(szTable)
					screen.setTableText(szTable, 0, iRow, szText1, "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					screen.setTableText(szTable, 2, iRow, activePlayer.getTeam().getName() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					screen.setTableText(szTable, 3, iRow, (u"%d" % ourScore), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					
					if (iBestScoreTeam != -1):
						screen.setTableText(szTable, 4, iRow, gc.getTeam(iBestScoreTeam).getName() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						screen.setTableText(szTable, 5, iRow, (u"%d" % bestScore), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						
					bEntriesFound = True
					
				if (victory.isConquest()):
					iRow = screen.appendTableRow(szTable)
					screen.setTableText(szTable, 0, iRow, localText.getText("TXT_KEY_VICTORY_SCREEN_ELIMINATE_ALL", ()), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					screen.setTableText(szTable, 2, iRow, localText.getText("TXT_KEY_VICTORY_SCREEN_RIVALS_LEFT", ()), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					screen.setTableText(szTable, 3, iRow, unicode(nRivals), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					bEntriesFound = True
					
				
				if (gc.getGame().getAdjustedPopulationPercent(iLoopVC) > 0):			
					iRow = screen.appendTableRow(szTable)
					screen.setTableText(szTable, 0, iRow, localText.getText("TXT_KEY_VICTORY_SCREEN_PERCENT_POP", (gc.getGame().getAdjustedPopulationPercent(iLoopVC), )), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					screen.setTableText(szTable, 2, iRow, activePlayer.getTeam().getName() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					screen.setTableText(szTable, 3, iRow, (u"%.2f%%" % popPercent), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					if (iBestPopTeam != -1):
						screen.setTableText(szTable, 4, iRow, gc.getTeam(iBestPopTeam).getName() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						screen.setTableText(szTable, 5, iRow, (u"%.2f%%" % (bestPop * 100 / totalPop)), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					bEntriesFound = True


				if (gc.getGame().getAdjustedLandPercent(iLoopVC) > 0):
					iRow = screen.appendTableRow(szTable)
					screen.setTableText(szTable, 0, iRow, localText.getText("TXT_KEY_VICTORY_SCREEN_PERCENT_LAND", (gc.getGame().getAdjustedLandPercent(iLoopVC), )), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					screen.setTableText(szTable, 2, iRow, activePlayer.getTeam().getName() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					screen.setTableText(szTable, 3, iRow, (u"%.2f%%" % landPercent), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					if (iBestLandTeam != -1):
						screen.setTableText(szTable, 4, iRow, gc.getTeam(iBestLandTeam).getName() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						screen.setTableText(szTable, 5, iRow, (u"%.2f%%" % (bestLand * 100 / totalLand)), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					bEntriesFound = True

				if (victory.getReligionPercent() > 0):			
					iRow = screen.appendTableRow(szTable)
					screen.setTableText(szTable, 0, iRow, localText.getText("TXT_KEY_VICTORY_SCREEN_PERCENT_RELIGION", (victory.getReligionPercent(), )), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					if (iOurReligion != -1):
						screen.setTableText(szTable, 2, iRow, gc.getReligionInfo(iOurReligion).getDescription() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						screen.setTableText(szTable, 3, iRow, (u"%d%%" % ourReligionPercent), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					else:
						screen.setTableText(szTable, 2, iRow, activePlayer.getTeam().getName() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						screen.setTableText(szTable, 3, iRow, u"No Holy City", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					if (iBestReligion != -1):
						screen.setTableText(szTable, 4, iRow, gc.getReligionInfo(iBestReligion).getDescription() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						screen.setTableText(szTable, 5, iRow, (u"%d%%" % religionPercent), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					bEntriesFound = True
				
				if (victory.getTotalCultureRatio() > 0):			
					iRow = screen.appendTableRow(szTable)
					screen.setTableText(szTable, 0, iRow, localText.getText("TXT_KEY_VICTORY_SCREEN_PERCENT_CULTURE", (int((100.0 * bestCulture) / victory.getTotalCultureRatio()), )), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					screen.setTableText(szTable, 2, iRow, activePlayer.getTeam().getName() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					screen.setTableText(szTable, 3, iRow, unicode(ourCulture), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					if (iBestLandTeam != -1):
						screen.setTableText(szTable, 4, iRow, gc.getTeam(iBestCultureTeam).getName() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						screen.setTableText(szTable, 5, iRow, unicode(bestCulture), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
					bEntriesFound = True

				iBestBuildingTeam = -1
				bestBuilding = 0
				for iLoopTeam in range(gc.getMAX_CIV_TEAMS()):
					if (gc.getTeam(iLoopTeam).isAlive() and not gc.getTeam(iLoopTeam).isMinorCiv() and not gc.getTeam(iLoopTeam).isBarbarian()):
						if (iLoopTeam != iActiveTeam and (activePlayer.getTeam().isHasMet(iLoopTeam) or gc.getGame().isDebugMode())):
							teamBuilding = 0
							for i in range(gc.getNumBuildingClassInfos()):
								if (gc.getBuildingClassInfo(i).getVictoryThreshold(iLoopVC) > 0):					
									teamBuilding += gc.getTeam(iLoopTeam).getBuildingClassCount(i)
							if (teamBuilding > bestBuilding):
								bestBuilding = teamBuilding
								iBestBuildingTeam = iLoopTeam	
											
				for i in range(gc.getNumBuildingClassInfos()):
					if (gc.getBuildingClassInfo(i).getVictoryThreshold(iLoopVC) > 0):
						iRow = screen.appendTableRow(szTable)
						szNumber = unicode(gc.getBuildingClassInfo(i).getVictoryThreshold(iLoopVC))
						screen.setTableText(szTable, 0, iRow, localText.getText("TXT_KEY_VICTORY_SCREEN_BUILDING", (szNumber, gc.getBuildingClassInfo(i).getTextKey())), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						screen.setTableText(szTable, 2, iRow, activePlayer.getTeam().getName() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
#						screen.setTableText(szTable, 3, iRow, activePlayer.getTeam().getBuildingClassCount(i), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						screen.setTableText(szTable, 3, iRow, str(activePlayer.getTeam().getBuildingClassCount(i)), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						if (iBestBuildingTeam != -1):
							screen.setTableText(szTable, 4, iRow, gc.getTeam(iBestBuildingTeam).getName() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
#							screen.setTableText(szTable, 5, iRow, gc.getTeam(iBestBuildingTeam).getBuildingClassCount(i), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
							screen.setTableText(szTable, 5, iRow, str(gc.getTeam(iBestBuildingTeam).getBuildingClassCount(i)), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						bEntriesFound = True
						
				iBestProjectTeam = -1
				bestProject = 0
				for iLoopTeam in range(gc.getMAX_CIV_TEAMS()):
					if (gc.getTeam(iLoopTeam).isAlive() and not gc.getTeam(iLoopTeam).isMinorCiv() and not gc.getTeam(iLoopTeam).isBarbarian()):
						if (iLoopTeam != iActiveTeam and (activePlayer.getTeam().isHasMet(iLoopTeam) or gc.getGame().isDebugMode())):
							teamProject = 0
							for i in range(gc.getNumProjectInfos()):
								if (gc.getProjectInfo(i).getVictoryThreshold(iLoopVC) > 0):					
									teamProject += gc.getTeam(iLoopTeam).getProjectCount(i)
							if (teamProject > bestProject):
								bestProject = teamProject
								iBestProjectTeam = iLoopTeam					
					
				for i in range(gc.getNumProjectInfos()):
					if (gc.getProjectInfo(i).getVictoryThreshold(iLoopVC) > 0):
						iRow = screen.appendTableRow(szTable)
						if (gc.getProjectInfo(i).getVictoryMinThreshold(iLoopVC) == gc.getProjectInfo(i).getVictoryThreshold(iLoopVC)):
							szNumber = unicode(gc.getProjectInfo(i).getVictoryThreshold(iLoopVC))
						else:
							szNumber = unicode(gc.getProjectInfo(i).getVictoryMinThreshold(iLoopVC)) + u"-" + unicode(gc.getProjectInfo(i).getVictoryThreshold(iLoopVC))
						screen.setTableText(szTable, 0, iRow, localText.getText("TXT_KEY_VICTORY_SCREEN_BUILDING", (szNumber, gc.getProjectInfo(i).getTextKey())), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						screen.setTableText(szTable, 2, iRow, activePlayer.getTeam().getName() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						screen.setTableText(szTable, 3, iRow, str(activePlayer.getTeam().getProjectCount(i)), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						
						#check if spaceship
						#if (gc.getProjectInfo(i).isSpaceship() and (activePlayer.getTeam().getProjectCount(i) > 0)):
						if (gc.getProjectInfo(i).isSpaceship()):
							bSpaceshipFound = True
						
						if (iBestProjectTeam != -1):
							screen.setTableText(szTable, 4, iRow, gc.getTeam(iBestProjectTeam).getName() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
							screen.setTableText(szTable, 5, iRow, unicode(gc.getTeam(iBestProjectTeam).getProjectCount(i)), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						bEntriesFound = True
						
				#add spaceship button
				if (bSpaceshipFound):
					screen.setButtonGFC("SpaceShipButton" + str(iLoopVC), localText.getText("TXT_KEY_GLOBELAYER_STRATEGY_VIEW", ()), "", 0, 0, 15, 10, WidgetTypes.WIDGET_GENERAL, self.SPACESHIP_SCREEN_BUTTON, -1, ButtonStyles.BUTTON_STYLE_STANDARD )
					screen.attachControlToTableCell("SpaceShipButton" + str(iLoopVC), szTable, iVictoryTitleRow, 1)
					
					victoryDelay = gc.getTeam(iActiveTeam).getVictoryCountdown(iLoopVC)
					if((victoryDelay > 0) and (gc.getGame().getGameState() != GameStateTypes.GAMESTATE_EXTENDED)):
						victoryDate = CyGameTextMgr().getTimeStr(gc.getGame().getGameTurn() + victoryDelay, false)
						screen.setTableText(szTable, 2, iVictoryTitleRow, localText.getText("TXT_KEY_SPACE_SHIP_SCREEN_ARRIVAL", ()) + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						screen.setTableText(szTable, 3, iVictoryTitleRow, victoryDate, "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						screen.setTableText(szTable, 4, iVictoryTitleRow, localText.getText("TXT_KEY_REPLAY_SCREEN_TURNS", ()) + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						screen.setTableText(szTable, 5, iVictoryTitleRow, str(victoryDelay), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						
				if (victory.isDiploVote()):
					for (iVoteBuildingClass, iUNTeam, bUnknown) in aiVoteBuildingClass:
						iRow = screen.appendTableRow(szTable)
						screen.setTableText(szTable, 0, iRow, localText.getText("TXT_KEY_VICTORY_SCREEN_ELECTION", (gc.getBuildingClassInfo(iVoteBuildingClass).getTextKey(), )), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						if (iUNTeam != -1):
							if bUnknown:
								szName = localText.getText("TXT_KEY_TOPCIVS_UNKNOWN", ())
							else:
								szName = gc.getTeam(iUNTeam).getName()
							screen.setTableText(szTable, 2, iRow, localText.getText("TXT_KEY_VICTORY_SCREEN_BUILT", (szName, )), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						else:
							screen.setTableText(szTable, 2, iRow, localText.getText("TXT_KEY_VICTORY_SCREEN_NOT_BUILT", ()), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						bEntriesFound = True
					
				if (victory.getCityCulture() != CultureLevelTypes.NO_CULTURELEVEL and victory.getNumCultureCities() > 0):
					ourBestCities = self.getListCultureCities(self.iActivePlayer)[0:victory.getNumCultureCities()]
					
					iBestCulturePlayer = -1
					bestCityCulture = 0
					maxCityCulture = gc.getCultureLevelInfo(victory.getCityCulture()).getSpeedThreshold(gc.getGame().getGameSpeedType())
					for iLoopPlayer in range(gc.getMAX_PLAYERS()):
						if (gc.getPlayer(iLoopPlayer).isAlive() and not gc.getPlayer(iLoopPlayer).isMinorCiv() and not gc.getPlayer(iLoopPlayer).isBarbarian()):
							if (iLoopPlayer != self.iActivePlayer and (activePlayer.getTeam().isHasMet(gc.getPlayer(iLoopPlayer).getTeam()) or gc.getGame().isDebugMode())):
								theirBestCities = self.getListCultureCities(iLoopPlayer)[0:victory.getNumCultureCities()]
								
								iTotalCulture = 0
								for loopCity in theirBestCities:
									if loopCity[0] >= maxCityCulture:
										iTotalCulture += maxCityCulture
									else:
										iTotalCulture += loopCity[0]
								
								if (iTotalCulture >= bestCityCulture):
									bestCityCulture = iTotalCulture
									iBestCulturePlayer = iLoopPlayer

					if (iBestCulturePlayer != -1):
						theirBestCities = self.getListCultureCities(iBestCulturePlayer)[0:(victory.getNumCultureCities())]
					else:
						theirBestCities = []
						
					iRow = screen.appendTableRow(szTable)
					screen.setTableText(szTable, 0, iRow, localText.getText("TXT_KEY_VICTORY_SCREEN_CITY_CULTURE", (victory.getNumCultureCities(), gc.getCultureLevelInfo(victory.getCityCulture()).getTextKey())), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)

					for i in range(victory.getNumCultureCities()):
						if (len(ourBestCities) > i):
							screen.setTableText(szTable, 2, iRow, ourBestCities[i][1].getName() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
							screen.setTableText(szTable, 3, iRow, str(ourBestCities[i][0]), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						if (len(theirBestCities) > i):
							screen.setTableText(szTable, 4, iRow, theirBestCities[i][1].getName() + ":", "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
							screen.setTableText(szTable, 5, iRow, unicode(theirBestCities[i][0]), "", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)
						if (i < victory.getNumCultureCities()-1):
							iRow = screen.appendTableRow(szTable)
					bEntriesFound = True
					
				if (bEntriesFound):
					screen.appendTableRow(szTable)
					screen.appendTableRow(szTable)

		# civ picker dropdown
		if (CyGame().isDebugMode()):
			self.szDropdownName = self.DEBUG_DROPDOWN_ID
			screen.addDropDownBoxGFC(self.szDropdownName, 22, 12, 300, WidgetTypes.WIDGET_GENERAL, -1, -1, FontTypes.GAME_FONT)
			for j in range(gc.getMAX_PLAYERS()):
				if (gc.getPlayer(j).isAlive()):
					screen.addPullDownString(self.szDropdownName, gc.getPlayer(j).getName(), j, j, False )
		
		self.drawTabs()
Example #7
0
def Get2dVariableHistsFromTrees(trees,keys,variable1,variable2,weight,options,scales=0,inputname='',files=None) :
    import ROOT
    from array import array
    import PlotFunctions as plotfunc
    import math
    import PyHelpers

    if not options.macro :
        if not options.limits.get(variable1,None) or not options.limits.get(variable2,None) :
            print 'Error - you need to specify limits for both %s and %s.'%(variable1,variable2)
            print '(Note you probably have to add these variables to the list of variables as well.)'
            SafeExit(options.xAODInit)

    n1,low1,high1 = options.limits.get(variable1)
    n2,low2,high2 = options.limits.get(variable2)

    if not inputname :
        inputname = '%s_%s'%(variable1,variable2)
        
    hists = []
    for k in keys :
        k_clean = CleanUpName(k,originalIsDirectoryName=True)
        name = CleanUpName('%s_%s'%(inputname,k_clean))

        if issubclass(type(ROOT.gDirectory.Get(name)),ROOT.TH1) :
            print 'Using existing histogram, %s'%(name)
            # will load the histogram later...

        elif options.macro :

            RunMacro(options.macro,files[k],CleanUpName(k))

            # if Draw did not work, then exit.
            if not issubclass(type(ROOT.gDirectory.Get(name)),ROOT.TH1) :
                print 'ERROR Macro failed trying to create %s Exiting.'%(name)
                SafeExit(options.xAODInit)

        else :

            arg1 = '%s:%s>>%s(%s,%s,%s,%s,%s,%s)'%(variable2,variable1,name,
                                                   n1,low1,high1,n2,low2,high2)
            arg2 = weight
            arg3 = 'egoff'
            print 'tree.Draw(\'%s\',\'%s\',\'%s\')'%(arg1,arg2,arg3)
            tmp = ROOT.gErrorIgnoreLevel
            ROOT.gErrorIgnoreLevel = ROOT.kFatal
            trees[k].Draw(arg1,arg2,arg3)
            ROOT.gErrorIgnoreLevel = tmp

            # if Draw did not work, then exit.
            if not issubclass(type(ROOT.gDirectory.Get(name)),ROOT.TH1) :
                print 'ERROR TTree::Draw failed trying to draw %s Exiting.'%(name)
                SafeExit(options.xAODInit)

        hists.append(ROOT.gDirectory.Get(name))
        hists[-1].SetDirectory(0)

        hists[-1].SetTitle(k)
        if scales and (scales[k] != 1) :
            hists[-1].Scale(scales[k])

        # print the yield and error after cuts (includes overflow)
        PyHelpers.PrintNumberOfEvents(hists[-1])

        if options.normalize :
            try :
                hists[-1].Scale(1/float(hists[-1].Integral()))
            except ZeroDivisionError :
                pass

    return hists
Example #8
0
def GetVariableHistsFromTrees(trees,keys,variable,weight,options=None,scales=0,inputname='',files=None) :
    import ROOT
    from array import array
    import PlotFunctions as plotfunc
    import TAxisFunctions as taxisfunc
    import math
    import PyHelpers

    # Parse options
    n,low,high = -1,-1,-1
    if hasattr(options,'limits') :
        n,low,high = options.limits.get(variable,[-1,-1,-1])
    rebin = options.rebin.get(variable,[]) if hasattr(options,'rebin') else []
    showflows = hasattr(options,'showflows') and options.showflows

    if not inputname :
        inputname = variable

    hists = []
    for k in keys :
        k_clean = CleanUpName(k,originalIsDirectoryName=True)
        name = CleanUpName('%s_%s'%(inputname,k_clean))

        if issubclass(type(ROOT.gDirectory.Get(name)),ROOT.TH1) :
            print 'Using existing histogram, %s'%(name)
            # will load the histogram later...

        elif options.macro :

            RunMacro(options.macro,files[k],CleanUpName(k))

            # if Draw did not work, then exit.
            if not issubclass(type(ROOT.gDirectory.Get(name)),ROOT.TH1) :
                print 'ERROR Macro failed trying to create %s Exiting.'%(name)
                SafeExit(options.xAODInit)

        else :

            if rebin and type(rebin) == type([]) :
                name = name+'_unrebinned'

            bins = '(%s,%s,%s)'%(n,low,high)
            if (n <= 0) :
                bins = ''
            arg1,arg2,arg3 = '%s>>%s%s'%(variable,name,bins),weight,'egoff'

            # Reset the default binning to 100, if "n" is not specified.
            ROOT.gEnv.SetValue('Hist.Binning.1D.x','100')

            print 'tree.Draw(\'%s\',\'%s\',\'%s\')'%(arg1,arg2,arg3)
            tmp = ROOT.gErrorIgnoreLevel
            ROOT.gErrorIgnoreLevel = ROOT.kFatal
            trees[k].Draw(arg1,arg2,arg3)
            ROOT.gErrorIgnoreLevel = tmp

            # if Draw did not work, then exit.
            if not issubclass(type(ROOT.gDirectory.Get(name)),ROOT.TH1) :
                print 'ERROR TTree::Draw failed trying to draw %s Exiting.'%(name)
                SafeExit(options.xAODInit)

            if rebin and type(rebin) == type([]) :
                tmp = ROOT.gDirectory.Get(name)
                name = name.replace('_unrebinned','')
                tmp.Rebin(len(rebin)-1,name,array('d',rebin))

        hists.append(ROOT.gDirectory.Get(name))
        hists[-1].SetDirectory(0)

        if rebin and type(rebin) == type(1) :
            hists[-1].Rebin(rebin)

        if (n <= 0) :
            print 'Changing limits to match those from the first plot.'
            n    = hists[-1].GetNbinsX()
            low  = hists[-1].GetBinLowEdge(1)
            high = hists[-1].GetBinLowEdge(n+1)
            if hasattr(options,'limits') :
                options.limits[variable] = [n,low,high]

        if showflows :
            taxisfunc.PutOverflowIntoLastBin(hists[-1])
            taxisfunc.PutUnderflowIntoFirstBin(hists[-1])

        #RebinSmoothlyFallingFunction(hists[-1])

        hists[-1].SetTitle(k)
        if scales and (scales[k] != 1) :
            hists[-1].Scale(scales[k])

        # print the yield and error after cuts (includes overflow)
        PyHelpers.PrintNumberOfEvents(hists[-1])

    return hists