Skip to content

Commit d8b1513

Browse files
author
Sourcery AI
committed
'Refactored by Sourcery'
1 parent c5eb80e commit d8b1513

File tree

12 files changed

+229
-236
lines changed

12 files changed

+229
-236
lines changed

.ipynb_checkpoints/vse2-checkpoint.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,7 @@ def __init__(self, model, methodsAndStrats,
3434
fgs.extend([(paramStrat(m.diehardBallot, intensity=i), targetFunc) for i in m.diehardLevels]
3535
+ [(paramStrat(m.compBallot, intensity=i), targetFunc) for i in m.compLevels])
3636
fgs.append((swapPolls(m.lowInfoBallot), targetFunc))
37-
for bg in [m.honBallot, m.lowInfoBallot]:
38-
ms.append((m, bg, fgs))
37+
ms.extend((m, bg, fgs) for bg in [m.honBallot, m.lowInfoBallot])
3938
else:
4039
ms.append(m)
4140
for i in range(niter):
@@ -55,12 +54,11 @@ def saveFile(self, baseName="SimResults"):
5554
i = 1
5655
while os.path.isfile(baseName + str(i) + ".csv"):
5756
i += 1
58-
myFile = open(baseName + str(i) + ".csv", "w")
59-
dw = csv.DictWriter(myFile, self.rows[0].keys(), restval="NA")
60-
dw.writeheader()
61-
for r in self.rows:
62-
dw.writerow(r)
63-
myFile.close()
57+
with open(baseName + str(i) + ".csv", "w") as myFile:
58+
dw = csv.DictWriter(myFile, self.rows[0].keys(), restval="NA")
59+
dw.writeheader()
60+
for r in self.rows:
61+
dw.writerow(r)
6462

6563

6664
def compareStrats(method, model, backgroundStrat, nvot, ncand, niter): pass

ballotEval.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
def stratStats(model, strat, nvot, ncand, niter, stratArgs={}, numWinners=1, pollingError=0.2,
66
usePolls=True, pickiness=0.7, pollFilter=None):
77
bulletCount, totalScore = 0, 0
8-
for i in range(niter):
8+
for _ in range(niter):
99
electorate = model(nvot, ncand)
1010
if usePolls:
1111
pollBallots = [Approval.zeroInfoBallot(v, pickiness=pickiness) for v in electorate]

cid.py

Lines changed: 32 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -139,15 +139,15 @@ def influentialBlocs(voters, method, numWinners=1, utilChange=0.1, numBuckets=5,
139139
pollingMethod = method
140140
pollingStrat = method.honBallot
141141
basePollBallots = [pollingStrat(v, numWinners=numWinners, **pollingStratArgs) for v in voters]
142-
pollErrors = [random.gauss(0, pollingError/2) for i in range(numCands)]
142+
pollErrors = [random.gauss(0, pollingError/2) for _ in range(numCands)]
143143
polls = [min(1, max(0, r + e)) for r, e in zip(pollingMethod.results(basePollBallots), pollErrors)]
144144
#polls = media(pollingMethod.results(pollBallots), pollingError) #method.results can't depend on numWinners; this may need to be changed
145145
baseBallots = [strat(v, polls=polls, electabilities=polls, numWinners=numWinners, **stratArgs) for v in voters]
146146
if isinstance(sorter, type):
147147
sorter = sorter(voters)
148148
baseWinners = method.winnerSet(baseBallots, numWinners)
149149
baseResults = method.results(baseBallots)
150-
isIncentive = [[] for i in range(numCands)]
150+
isIncentive = [[] for _ in range(numCands)]
151151
#isIncentive[c][b] is 1 if candidate c is incentivized to appeal to the bth bucket of voters, 0 otherwise
152152
for cand in range(numCands):
153153
utilShifts = [0]*numCands
@@ -205,7 +205,7 @@ def __init__(self, model, methodsAndStrats, nvot, ncand, niter, nwinners=1,
205205
elif len(m) == 2:
206206
ms.append((m[0], m[1], {}))
207207
else: ms.append(m)
208-
self.mNames = [m[0].__name__ + ':' + m[1].__name__ + str(m[2]) for m in ms]
208+
self.mNames = [f'{m[0].__name__}:{m[1].__name__}{str(m[2])}' for m in ms]
209209
self.rows = []
210210
args = (model, nvot, ncand, ms, nwinners, utilChange, numBuckets, sorter, pollingMethod, pollingError, pollAfterPert)
211211
with multiprocessing.Pool(processes=7) as pool:
@@ -233,7 +233,10 @@ def chart(self, methodOnly=True):
233233
fig, ax = plt.subplots()
234234
incentFracts = self.summarize()[0]
235235
if methodOnly:
236-
incentFracts = {re.match(".*(?=:)", name).group(0): data for name, data in incentFracts.items()}
236+
incentFracts = {
237+
re.match(".*(?=:)", name)[0]: data
238+
for name, data in incentFracts.items()
239+
}
237240
for name, data in incentFracts.items():
238241
ax.plot([i/self.numBuckets for i in range(1, self.numBuckets+1)], data, label=name)
239242
#ax.set_xlim(1, self.numBuckets)
@@ -258,16 +261,17 @@ def saveFile(self, baseName="cidResults", newFile=True):
258261
fields = ['name', 'baseResult'] + list(range(self.numBuckets)) + list(universalInfo.keys())
259262
resultTypeIndices = {'all': 1, 'loss': 2, 'win': 3}
260263

261-
myFile = open(baseName + (str(i) if newFile else "") + ".csv", "w")
262-
dw = csv.DictWriter(myFile, fields, restval="data missing")
263-
dw.writeheader()
264-
for outcome, index in resultTypeIndices.items():
265-
for name, results in self.summarize()[index].items():
266-
row = {'name': name, 'baseResult': outcome}
267-
row.update({i: result for i, result in enumerate(results)})
268-
row.update(universalInfo)
269-
dw.writerow(row)
270-
myFile.close()
264+
with open(baseName + (str(i) if newFile else "") + ".csv", "w") as myFile:
265+
dw = csv.DictWriter(myFile, fields, restval="data missing")
266+
dw.writeheader()
267+
for outcome, index in resultTypeIndices.items():
268+
for name, results in self.summarize()[index].items():
269+
row = (
270+
{'name': name, 'baseResult': outcome}
271+
| enumerate(results)
272+
| universalInfo
273+
)
274+
dw.writerow(row)
271275

272276
def simOneElectorate(model, nvot, ncand, ms, nwinners, utilChange, numBuckets, sorter,
273277
pollingMethod, pollingError, pollAfterPert, baseSeed=None, i = 0):
@@ -280,9 +284,17 @@ def simOneElectorate(model, nvot, ncand, ms, nwinners, utilChange, numBuckets, s
280284
for method, strat, stratArgs in ms:
281285
allIncentives, baseWinners, baseResults = influentialBlocs(electorate, method, nwinners, utilChange, numBuckets,
282286
sorter, strat, stratArgs, pollingMethod, pollAfterPert=pollAfterPert, pollingError=pollingError)
283-
for i, candIncentives in enumerate(allIncentives):
284-
results.append(dict(incentives=candIncentives, isWinner=i in baseWinners,
285-
method=method.__name__, strat=strat.__name__, stratArgs=stratArgs, voterModel=str(model)))
287+
results.extend(
288+
dict(
289+
incentives=candIncentives,
290+
isWinner=i in baseWinners,
291+
method=method.__name__,
292+
strat=strat.__name__,
293+
stratArgs=stratArgs,
294+
voterModel=str(model),
295+
)
296+
for i, candIncentives in enumerate(allIncentives)
297+
)
286298
return results
287299

288300
def showChart(fileName, norm=1, methodOnly=True, forResult='all', percentages=True, wholeOnly=True):
@@ -298,7 +310,7 @@ def showChart(fileName, norm=1, methodOnly=True, forResult='all', percentages=Tr
298310
elif norm == 'max':
299311
normFactor = max(rawData)
300312
data = [d/normFactor for d in rawData]
301-
name = re.match(".*(?=:)", row['name']).group(0) if methodOnly else row['name']
313+
name = re.match(".*(?=:)", row['name'])[0] if methodOnly else row['name']
302314
ax.plot([(i+.5)*100/buckets for i in range(buckets)], data, label=name)
303315
ax.set_xlabel("Voter's support for candidate")
304316
ax.set_ylabel("Candidate's incentive to appeal to voter")
@@ -308,9 +320,9 @@ def yFormatFunc(value, position):
308320
if value == 1: return "Average"
309321
if value == 0: return "0"
310322
if wholeOnly:
311-
if value % 1 != 0: return ""
312-
return f'{int(value)}x Avg'
323+
return "" if value % 1 != 0 else f'{int(value)}x Avg'
313324
return f'{value:1.1f}x Avg'
325+
314326
ax.yaxis.set_major_formatter(mtick.FuncFormatter(yFormatFunc))
315327
ax.grid(True)
316328
ax.legend()

dataClasses.py

Lines changed: 30 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -100,10 +100,9 @@ def realisticBullets(cls, utils, electabilities, baseBullets=0.3, slope=0.35, ot
100100
r = random.Random(utils.id).random()
101101
if r < baseBullets + slope*margin:
102102
return cls.bulletBallot(utils)
103-
else:
104-
if otherStrat is None:
105-
otherStrat = cls.honBallot
106-
return otherStrat(utils, electabilities=electabilities)
103+
if otherStrat is None:
104+
otherStrat = cls.honBallot
105+
return otherStrat(utils, electabilities=electabilities)
107106

108107
@classmethod
109108
def diehardBallot(cls, utils, intensity, candToHelp, candToHurt, electabilities=None, polls=None):
@@ -176,7 +175,7 @@ def stratThresholdSearch(cls, targetWinner, foundAt, bgBallots, fgBallots, fgBas
176175
midpoint = int(floor((maxThreshold + minThreshold)/2))
177176
midpointBallots = bgBallots + fgBallots[:midpoint] + fgBaselineBallots[midpoint:]
178177
midpointWinner = cls.winner(cls.results(midpointBallots))
179-
if not any(midpointWinner == w for w, _ in winnersFound):
178+
if all(midpointWinner != w for w, _ in winnersFound):
180179
winnersFound.append((midpointWinner, midpoint))
181180
if midpointWinner == targetWinner:
182181
maxThreshold = midpoint
@@ -189,15 +188,15 @@ def resultsFor(cls, voters):
189188
"""Create (honest/naive) ballots and get results.
190189
Again, test on subclasses.
191190
"""
192-
return cls.results(list(cls.honBallot(v) for v in voters))
191+
return cls.results([cls.honBallot(v) for v in voters])
193192
@staticmethod
194193
def stratTarget2(places):
195-
((frontId,frontResult), (targId, targResult)) = places[0:2]
194+
((frontId,frontResult), (targId, targResult)) = places[:2]
196195
return (frontId, frontResult, targId, targResult)
197196

198197
@staticmethod
199198
def stratTarget3(places):
200-
((frontId,frontResult), (targId, targResult)) = places[0:3:2]
199+
((frontId,frontResult), (targId, targResult)) = places[:3:2]
201200

202201
return (frontId, frontResult, targId, targResult)
203202

@@ -305,9 +304,10 @@ def paramStrat(strategy, **kw):
305304
def strat(voter, polls=None, electabilities=None, candToHelp=None, candToHurt=None):
306305
return strategy(voter, polls=polls, electabilities=electabilities,
307306
candToHelp=candToHelp, candToHurt=candToHurt, **kw)
307+
308308
strat.__name__ = strategy.__name__
309309
for key, value in kw.items():
310-
strat.__name__ += "_"+str(key)[:4]+str(value)[:4]
310+
strat.__name__ += f"_{str(key)[:4]}{str(value)[:4]}"
311311
return strat
312312

313313
def wantToHelp(voter, candToHelp, candToHurt, **kw):
@@ -316,7 +316,8 @@ def wantToHelp(voter, candToHelp, candToHurt, **kw):
316316
def selectAB(candA, candB): #candA and candB are candidate IDs
317317
def fgSelect(voter, **kw):
318318
return max(voter[candA] - voter[candB], 0)
319-
fgSelect.__name__ = "select"+str(candA)+str(candB)
319+
320+
fgSelect.__name__ = f"select{str(candA)}{str(candB)}"
320321
return fgSelect
321322

322323
def selectRand(polls, **kw):
@@ -356,16 +357,25 @@ def selectV(v, **kw):
356357
"pivotalUtilDiff", "deciderUtilDiffSum", "deciderMargUtilDiffs", "numWinnersFound",
357358
"factionSize", "factionFraction"]
358359
for prefix in ["", "min", "t1", "o"]:
359-
for columnName in ["fgUtil", "fgUtilDiff", "fgSize",
360-
"fgNumHelped", "fgHelpedUtil", "fgHelpedUtilDiff",
361-
"fgNumHarmed", "fgHarmedUtil", "fgHarmedUtilDiff",
362-
"helpCandElected", "hurtCandElectedR1"]:
363-
resultColumns.append(prefix + columnName)
360+
resultColumns.extend(
361+
prefix + columnName
362+
for columnName in [
363+
"fgUtil",
364+
"fgUtilDiff",
365+
"fgSize",
366+
"fgNumHelped",
367+
"fgHelpedUtil",
368+
"fgHelpedUtilDiff",
369+
"fgNumHarmed",
370+
"fgHarmedUtil",
371+
"fgHarmedUtilDiff",
372+
"helpCandElected",
373+
"hurtCandElectedR1",
374+
]
375+
)
364376

365377
def makeResults(**kw):
366-
results = {c: kw.get(c, None) for c in resultColumns}
367-
results.update(kw)
368-
return results
378+
return {c: kw.get(c, None) for c in resultColumns} | kw
369379

370380
def makePartialResults(fgVoters, winner, r1Winner, prefix, candToHelp, candToHurt):
371381
fgHelped = []
@@ -530,10 +540,7 @@ def tieFor2Estimate(probs):
530540

531541

532542
def adaptiveTieFor2(polls, uncertainty=.15):
533-
if False and len(polls) < 6:
534-
return tieFor2Probs(polls, uncertainty)
535-
else:
536-
return tieFor2Estimate(tuple(pollsToProbs(polls, uncertainty)))
543+
return tieFor2Estimate(tuple(pollsToProbs(polls, uncertainty)))
537544

538545
def appendResults(filename, resultsList, globalComment = dict()):
539546
"""append list of results created by makeResults to a csv file.
@@ -551,17 +558,7 @@ def appendResults(filename, resultsList, globalComment = dict()):
551558

552559
with open(baseName + str(i) + ".csv", "a") as myFile:
553560
if needsHeader:
554-
print("# " + str(globalComment),
555-
#dict(
556-
#media=self.media.__name__,
557-
# version=self.repo_version,
558-
# seed=self.seed,
559-
## model=self.model,
560-
# methods=self.methods,
561-
# nvot=self.nvot,
562-
# ncand=self.ncand,
563-
# niter=self.niter)),
564-
file=myFile)
561+
print(f"# {str(globalComment)}", file=myFile)
565562
dw = csv.DictWriter(myFile, keys, restval="NA")
566563
dw.writeheader()
567564
for r in resultsList:

0 commit comments

Comments
 (0)