-
Notifications
You must be signed in to change notification settings - Fork 2
/
naive_parser.py
427 lines (349 loc) · 13.7 KB
/
naive_parser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
#!/usr/bin/python3
import sys
import os
import numpy
import re
from collections import defaultdict
import properties
import config
class Nation:
def __init__(self, tag):
self.tag = tag
self.government = ""
self.ideology = ""
self.population = 0.0
self.industry = 0.0
self.warscore = 0.0
self.points = 0.0
self.name = ""
self.capital = ""
self.climate = "pc_arid"
def longTag(self):
return self.tag + "_" + self.government
def __str__(self):
printstring = ""
printstring += self.tag + "\n"
printstring += "\t" + self.government + " " + self.ideology + "\n"
printstring += "\tPopulation: {:.3f}".format(self.population) + "\n"
printstring += "\tIndustry: {:.3f}".format(self.industry) + "\n"
printstring += "\tWarscore: {:.3f}".format(self.warscore) + "\n"
printstring += "\tOverall: {:.3f}".format(self.points) + "\n"
return printstring
def drill(blob, *args):
try:
thing = blob
for arg in args:
thing = thing[arg][0]
return thing
except BaseException:
return ""
def unquote(string):
if string == "":
return ""
string = trim(string)
if string[0] == '"':
string = string[1:]
if string[-1] == '"':
string = string[:-1]
return string
def trim(string):
if string == "":
return ""
while string[0] == ' ' or string[0] == '\t':
string = string[1:]
if string == "":
return ""
while string[-1] == ' ' or string[-1] == '\t':
string = string[:-1]
if string == "":
return ""
return string
def printstack(stack):
for blob in stack:
for line in blob:
print(line)
print("-")
print("---")
def splitstrings(string):
splits = string.split(",")
splits = [unquote(s) for s in splits]
return splits
def ParseSaveFile(path, debug=False):
try:
alllines = open(path, encoding="utf-8").read()
except UnicodeDecodeError:
import traceback
traceback.print_exc()
print("Carrying on regardless.")
alllines = open(path, encoding="utf-8", errors="ignore").read()
return ParseSaveData(alllines, debug)
def ParseSaveData(alllines, debug=False):
# Comments are troublesome
# alllines = re.sub(r"#[^\n]*?\n",r"\n",alllines)
alllines = re.sub(r"=\n\t*{", r"={", alllines)
alllines = re.sub(r"=\n *{", r"={", alllines)
lines = alllines.split("\n")
lines = [item for item in lines if len(trim(item)) > 0 and trim(item)[0] != "#"]
alllines = "\n".join(lines)
alllines = alllines.replace("}", "\n}\n").replace("{", "{\n")
lines = alllines.split("\n")
stack = [defaultdict(list)]
keystack = [""]
i = 0
fivePercentMark = len(lines) // 20
nextPercentMark = fivePercentMark
if fivePercentMark > 1000:
print("Parsing save data...")
for line in lines:
i += 1
if i > nextPercentMark and fivePercentMark > 5000:
print(str((5 * i) // fivePercentMark) + "%")
nextPercentMark += fivePercentMark
line = trim(line.replace("\n", "").replace("\t", ""))
if i == 1:
# First line weirdness
if line[:7] == "HOI4bin":
print("ERROR: The HoI4 save file is compressed, and cannot be read. Please edit 'Documents/Paradox Interactive/Hearst of Iron IV/settings.txt' with a text editor, and change 'save_as_binary=yes' to 'save_as_binary=no'. Then save your HoI4 game again.")
print("Exiting.")
sys.exit(0)
if line == "HOI4txt":
continue
if len(line) > 0:
if ord(line[0]) == 65279:
line = line[1:]
if debug:
print(line)
print(stack)
print(keystack)
print("")
input()
if line == "":
continue
end = False
if '}' in line:
line = trim(line.replace("}", ""))
end = True
if line != "":
pair = line.split('=')
key = trim(pair[0])
if len(pair) > 1:
value = trim(pair[1])
else:
key = ''
value = trim(line)
if '{' in value:
keystack.append(key)
stack.append(defaultdict(list))
else:
stack[-1][key].append(value)
if end:
stack[-2][keystack[-1]].append(stack[-1])
stack.pop()
keystack.pop()
savefile = stack[0]
return savefile
class Parser:
def __init__(self, savefile):
self.savefile = savefile
self.pops = {}
self.factories = {}
self.warscore = {}
self.stateCount = {}
self.totalStateCount = 0
states = drill(savefile, "states")
for state in states:
self.totalStateCount += 1
owner = unquote(drill(savefile, "states", state, "owner"))
manpower = drill(savefile, "states", state, "manpower_pool", "total")
if owner in self.pops:
self.pops[unquote(owner)] += int(manpower)
else:
self.pops[unquote(owner)] = int(manpower)
if owner in self.stateCount:
self.stateCount[unquote(owner)] += 1
else:
self.stateCount[unquote(owner)] = 1
buildingtypes = drill(savefile, "states", state, "buildings")
for buildingtype in buildingtypes:
rawbuildingcount = trim(
drill(
savefile,
"states",
state,
"buildings",
buildingtype,
"level",
""))
if rawbuildingcount == "":
continue
buildingcount = rawbuildingcount.split(" ")
for building in buildingcount:
if owner in self.factories:
self.factories[owner] += int(building)
else:
self.factories[owner] = int(building)
wars = savefile["previous_peace"]
for war in wars:
for winner in drill(war, "winners"):
score = int(drill(war, "winners", winner, "original_score"))
if winner in self.warscore:
self.warscore[unquote(winner)] += int(score)
else:
self.warscore[unquote(winner)] = int(score)
for war in wars:
for loser in drill(war, "losers"):
self.warscore[loser] = 0
for nation in self.pops:
if nation not in self.warscore:
self.warscore[nation] = 0
self.puppets = []
for country in drill(savefile, "countries"):
relation1 = drill(savefile, "countries", country, "diplomacy", "active_relations")
for relation in relation1:
relationdata = drill(relation1, relation)
if "puppet" in relationdata:
puppetry = drill(relationdata, "puppet")
self.puppets.append([unquote(drill(puppetry, "first")),
unquote(drill(puppetry, "second"))])
for puppetpair in self.puppets:
overlord = puppetpair[0]
vassal = puppetpair[1]
if overlord not in self.pops:
continue
if vassal not in self.pops:
continue
self.pops[overlord] += 0.25 * self.pops[vassal]
self.factories[overlord] += 0.25 * self.factories[vassal]
self.warscore[overlord] += 0.25 * self.warscore[vassal]
self.pops[vassal] = 0.1 * self.pops[vassal]
self.factories[vassal] = 0.1 * self.factories[vassal]
self.warscore[vassal] = 0.1 * self.warscore[vassal]
capitals = {}
for country in drill(savefile, "countries"):
capitalProvince = drill(savefile, "countries", country, "capital")
capitals[country] = capitalProvince
governments = {}
ideologies = {}
for country in drill(savefile, "countries"):
rulingParty = drill(savefile, "countries", country, "politics", "ruling_party")
governments[country] = rulingParty
ideology = drill(
savefile,
"countries",
country,
"politics",
"parties",
rulingParty,
"country_leader",
"ideology")
ideologies[country] = ideology
self.factions = {}
for faction in savefile["faction"]:
factionName = unquote(drill(faction, "name"))
factionMembers = drill(faction, "members", "").split(" ")
self.factions[factionName.lower()] = factionMembers
popmax = float(self.pops[max(self.pops, key=self.pops.get)])
factorymax = float(self.factories[max(self.factories, key=self.factories.get)])
scoremax = float(self.warscore[max(self.warscore, key=self.warscore.get)])
if (popmax < 1):
popmax = 1
if (factorymax < 1):
factorymax = 1
if (scoremax < 1):
scoremax = 1
self.defcon = config.Config().getDefconResults()
if self.defcon:
for dtag in self.defcon:
if not type(dtag) is str: continue
multiplier = float(drill(self.defcon, dtag, "survivors"))
multiplier /= 100.0
multiplier = 0.40 + (multiplier*0.60) # Let's not be too mean
if dtag in self.factories:
# nation tag
self.pops[dtag] *= multiplier
self.factories[dtag] *= multiplier
elif dtag.lower() in self.factions:
# faction name
factionTags = self.factions[dtag.lower()]
for factionTag in factionTags:
self.pops[factionTag] *= multiplier
self.factories[factionTag] *= multiplier
else:
print("Warning: "+dtag+" not found. Please make sure you've spelled it correctly.")
def tweakedsort(a):
popproportion = float(self.pops[a]) / popmax
factoryproportion = float(self.factories[a]) / factorymax
scoreproportion = float(self.warscore[a]) / scoremax
factor = (popproportion * factoryproportion)
factor *= 1.0 + (0.2 * scoreproportion)
return factor
self.totalScore = 0.0
for nation in self.factories:
self.totalScore += tweakedsort(nation)
climateMap = properties.getClimates()
self.topNations = []
self.smallNations = []
claimedStates = 0
for nation in sorted(self.factories, key=tweakedsort, reverse=True):
ndata = Nation(nation)
ndata.population = self.pops[nation] / popmax
ndata.industry = self.factories[nation] / factorymax
ndata.warscore = self.warscore[nation] / scoremax
ndata.points = tweakedsort(nation)
ndata.government = governments[nation]
ndata.ideology = ideologies[nation]
ndata.capital = capitals[nation]
capitalId = int(ndata.capital)
if capitalId in climateMap:
ndata.climate = climateMap[int(capitals[nation])]
else:
ndata.climate = "pc_arid"
oldtag = unquote(drill(savefile, "countries", nation, "original_tag"))
if oldtag:
ndata.tag = oldtag
claimedStates += self.stateCount[nation]
if len(self.topNations) < 6 and (tweakedsort(nation) > 0.1 or claimedStates < self.totalStateCount/10):
self.topNations.append(ndata)
else:
self.smallNations.append(ndata)
def getIndPerCapita(a):
return 1000 * (self.factories[a] / self.pops[a])
def gini_coeff(x):
# requires all values in x to be zero or positive numbers,
# otherwise results are undefined
n = len(x)
s = x.sum()
r = numpy.argsort(numpy.argsort(-x)) # calculates zero-based ranks
return 1 - (2.0 * (r * x).sum() + s) / (n * s)
villageSize = 1000
giniVillage = []
maxWealth = 0.0
for nation in sorted(self.pops):
if self.pops[nation] / popmax < 0.005:
continue
wealth = (self.factories[nation] / factorymax) / (self.pops[nation] / popmax)
if wealth > maxWealth:
maxWealth = wealth
villagerCount = int(numpy.floor(villageSize * self.pops[nation] / popmax))
for i in range(villagerCount):
giniVillage.append(wealth)
giniArray = numpy.array(giniVillage)
giniArray = giniArray / maxWealth
giniArray.sort()
self.gini = gini_coeff(giniArray)
def getTopNations(self):
return self.topNations
def getSmallNations(self):
return self.smallNations
def getTotalScore(self):
return self.totalScore
def getGiniCoeff(self):
return self.gini
if __name__ == "__main__":
savefile = ParseSaveFile("postwar_1948_06_16_01.hoi4")
parsedfile = Parser(savefile)
topNations = parsedfile.getTopNations()
gini = parsedfile.getGiniCoeff()
for topNation in topNations:
print(topNation)
print("Gini Coefficient: " + str(gini))