Skip to content

Commit 2246b07

Browse files
author
Sourcery AI
committed
'Refactored by Sourcery'
1 parent aa581d2 commit 2246b07

File tree

13 files changed

+266
-279
lines changed

13 files changed

+266
-279
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
@@ -8,7 +8,7 @@ def stratStats(model, strat, nvot, ncand, niter, stratArgs={}, numWinners=1, pol
88
usePolls=True, pickiness=0.7, pollFilter=None):
99
bulletCount, totalScore = 0, 0
1010
scoreCounts = collections.Counter()
11-
for i in range(niter):
11+
for _ in range(niter):
1212
electorate = model(nvot, ncand)
1313
if usePolls:
1414
pollBallots = [Approval.zeroInfoBallot(v, pickiness=pickiness) for v in electorate]

cid.py

Lines changed: 34 additions & 22 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()
@@ -325,11 +337,11 @@ def showDFUandCS(fileName, positions=(0.25,0.5), methodOnly=True, forResult='all
325337
buckets = int(row['numBuckets'])
326338
rawData = [float(row[str(i)]) for i in range(buckets)]
327339
total = sum(rawData)
328-
name = re.match(".*(?=:)", row['name']).group(0) if methodOnly else row['name']
340+
name = re.match(".*(?=:)", row['name'])[0] if methodOnly else row['name']
329341
DFU = sum(entry/total - 1/buckets for entry in rawData if entry/total > 1/buckets)
330342
CSs = [sum(entry/total for i, entry in enumerate(rawData) if i < buckets*pos) for pos in positions]
331343
csString = "\t".join(f"{cs:1.2f}" for cs in CSs)
332-
print(f"{name}: {DFU:1.2f}\t"+csString)
344+
print(f"{name}: {DFU:1.2f}\t{csString}")
333345

334346
if __name__ == "__main__":
335347
import doctest

dataClasses.py

Lines changed: 36 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def winnerSet(cls, ballots, numWinners=1):
5656
def honBallot(cls, utils, **kw):
5757
"""Takes utilities and returns an honest ballot
5858
"""
59-
raise NotImplementedError("{} needs honBallot".format(cls))
59+
raise NotImplementedError(f"{cls} needs honBallot")
6060

6161
@classmethod
6262
def vaBallot(cls, utils, electabilities, **kw):
@@ -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):
@@ -152,7 +151,7 @@ def winner(results):
152151
>>> 2 < Method().winner([1,2,1,3,3,3,2,1,2]) < 6
153152
True
154153
"""
155-
winScore = max([result for result in results if isnum(result)])
154+
winScore = max(result for result in results if isnum(result))
156155
winners = [cand for (cand, score) in enumerate(results) if score==winScore]
157156
#return random.choice(winners)
158157
return winners[0] #made it deterministic to prevent nondeterministic behaviors in useful functions
@@ -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
return (frontId, frontResult, targId, targResult)
202201

203202
stratTargetFor = stratTarget2
@@ -247,8 +246,9 @@ def rememberBallot(fun):
247246
"""
248247
def getAndRemember(cls, voter, tally=None):
249248
ballot = fun(cls, voter)
250-
setattr(voter, cls.__name__ + "_" + fun.__name__[:-6], ballot) #leave off the "...Ballot"
249+
setattr(voter, f"{cls.__name__}_{fun.__name__[:-6]}", ballot)
251250
return ballot
251+
252252
getAndRemember.__name__ = fun.__name__
253253
getAndRemember.allTallyKeys = lambda:[]
254254
return getAndRemember
@@ -263,9 +263,10 @@ def getAndRemember(cls, voter, tally=None):
263263
ballots = fun(cls, voter)
264264
for bType, ballot in ballots.items():
265265

266-
setattr(voter, cls.__name__ + "_" + bType, ballot)
266+
setattr(voter, f"{cls.__name__}_{bType}", ballot)
267267

268268
return ballots[fun.__name__[:-6]] #leave off the "...Ballot"
269+
269270
getAndRemember.__name__ = fun.__name__
270271
getAndRemember.allTallyKeys = lambda:[]
271272
return getAndRemember
@@ -302,9 +303,10 @@ def paramStrat(strategy, **kw):
302303
def strat(voter, polls=None, electabilities=None, candToHelp=None, candToHurt=None):
303304
return strategy(voter, polls=polls, electabilities=electabilities,
304305
candToHelp=candToHelp, candToHurt=candToHurt, **kw)
306+
305307
strat.__name__ = strategy.__name__
306308
for key, value in kw.items():
307-
strat.__name__ += "_"+str(key)[:4]+str(value)[:4]
309+
strat.__name__ += f"_{str(key)[:4]}{str(value)[:4]}"
308310
return strat
309311

310312
def wantToHelp(voter, candToHelp, candToHurt, **kw):
@@ -313,7 +315,8 @@ def wantToHelp(voter, candToHelp, candToHurt, **kw):
313315
def selectAB(candA, candB): #candA and candB are candidate IDs
314316
def fgSelect(voter, **kw):
315317
return max(voter[candA] - voter[candB], 0)
316-
fgSelect.__name__ = "select"+str(candA)+str(candB)
318+
319+
fgSelect.__name__ = f"select{str(candA)}{str(candB)}"
317320
return fgSelect
318321

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

362376
def makeResults(**kw):
363-
results = {c: kw.get(c, None) for c in resultColumns}
364-
results.update(kw)
365-
return results
377+
return {c: kw.get(c, None) for c in resultColumns} | kw
366378

367379
def makePartialResults(fgVoters, winner, r1Winner, prefix, candToHelp, candToHurt):
368380
fgHelped = []
@@ -527,10 +539,7 @@ def tieFor2Estimate(probs):
527539

528540

529541
def adaptiveTieFor2(polls, uncertainty=.15):
530-
if False and len(polls) < 6:
531-
return tieFor2Probs(polls, uncertainty)
532-
else:
533-
return tieFor2Estimate(tuple(pollsToProbs(polls, uncertainty)))
542+
return tieFor2Estimate(tuple(pollsToProbs(polls, uncertainty)))
534543

535544
def appendResults(filename, resultsList, globalComment = dict()):
536545
"""append list of results created by makeResults to a csv file.
@@ -548,17 +557,7 @@ def appendResults(filename, resultsList, globalComment = dict()):
548557

549558
with open(baseName + str(i) + ".csv", "a") as myFile:
550559
if needsHeader:
551-
print("# " + str(globalComment),
552-
#dict(
553-
#media=self.media.__name__,
554-
# version=self.repo_version,
555-
# seed=self.seed,
556-
## model=self.model,
557-
# methods=self.methods,
558-
# nvot=self.nvot,
559-
# ncand=self.ncand,
560-
# niter=self.niter)),
561-
file=myFile)
560+
print(f"# {str(globalComment)}", file=myFile)
562561
dw = csv.DictWriter(myFile, keys, restval="NA")
563562
dw.writeheader()
564563
for r in resultsList:

0 commit comments

Comments
 (0)