summaryrefslogtreecommitdiff
path: root/src/Election.hs
blob: 6d946cda3aa9bf086c58c6917ce09b8af451a6a1 (plain)
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
module Election(
    Election,

    createElection,
    doCount
    ) where




import qualified System.IO as IO
import qualified System.Exit as Ex
import qualified Control.Monad as Con
import qualified Control.Monad.Trans.Either as ET
import qualified Control.Monad.IO.Class as MIO
import Data.List ( (\\) )
import qualified Data.List as List
import qualified Data.Maybe as Maybe
import qualified Data.Either.Unwrap as Either
import Data.Ratio ( (%) )
import qualified Counter as Sen
import qualified Candidate as Typ
import qualified CSV as CSV
import qualified Miscellaneous as Misc




data Election = Election
    { getEntries       :: [Entry]
    , getCounter       :: Sen.SenateCounter
    , getLogDir        :: FilePath
    , getTotalPapers   :: Int
    , getQuota         :: Int
    , getMainLog       :: String
    , getNextLogNum    :: Int
    , getSeats         :: Int
    , getVacancies     :: Int
    , getTransferQueue :: [Transfer]
    , getNextToElect   :: Int
    , isDone           :: Bool
    , isVerbose        :: Bool }

data Entry = Entry
    { getID           :: Typ.CandidateID
    , getVoteChange   :: Int
    , getTotalVotes   :: Int
    , getCritTrace    :: [Trace]
    , getStatus       :: Status
    , getChanged      :: Bool
    , getOrderElected :: Maybe Int }
    deriving (Eq)

data Trace = Trace
    { getCriteria    :: Sen.Criteria
    , getTransferVal :: Rational }
    deriving (Eq)

data Status = Running | Elected | Eliminated
    deriving (Show, Eq)

data Transfer = Transfer
    { getWhoFrom    :: Typ.CandidateID
    , getVoteAmount :: Int
    , getNewValue   :: Rational
    , getWhatToDist :: [Trace] }
    deriving (Eq)




createElection :: FilePath -> Sen.SenateCounter -> Int -> Bool -> IO Election
createElection outDir counter numToElect verbosity = do
    entries <- mapM (candToEntry counter) (Sen.getBallot counter)
    return (Election
        { getEntries       = entries
        , getCounter       = counter
        , getLogDir        = outDir
        , getTotalPapers   = Sen.getTotal counter
        , getQuota         = droopQuota (Sen.getTotal counter) numToElect
        , getMainLog       = outDir ++ "/" ++ "log.txt"
        , getNextLogNum    = 1
        , getSeats         = numToElect
        , getVacancies     = numToElect
        , getTransferQueue = []
        , getNextToElect   = 1
        , isDone           = False
        , isVerbose        = verbosity })




droopQuota :: Int -> Int -> Int
droopQuota votes seats =
    1 + floor ((fromIntegral votes) / (fromIntegral (seats + 1)))




compareVotes :: Entry -> Entry -> Ordering
compareVotes x y = compare (getTotalVotes x) (getTotalVotes y)




candToEntry :: Sen.SenateCounter -> Typ.CandidateID -> IO Entry
candToEntry counter candidate = do
    let criteria = [Sen.matchID candidate]
        trace = Trace criteria 1
    firstPrefs <- Sen.doCount counter criteria
    return (Entry
        { getID           = candidate
        , getVoteChange   = firstPrefs
        , getTotalVotes   = firstPrefs
        , getCritTrace    = [trace]
        , getStatus       = Running
        , getChanged      = False
        , getOrderElected = Nothing })




doCount :: Election -> IO ()
doCount e =
    Con.when (not (isDone e)) $ do
        writeLog e
        let e1 = e { getNextLogNum = 1 + getNextLogNum e }
        let e2 = e1 { getEntries = map clearChange (getEntries e1) }

        --  these following calculations probably aren't the
        --  intended use of Either monads, but the pattern fits
        --  and it's certainly a lot better than a bunch of
        --  if-then-else constructs in haskell
        r <- ET.eitherT return return $
            electCandidates e2 >>=
            checkIfDone >>=
            transferVotes >>=
            checkNoQuota >>=
            excludeCandidates

        --  this should never happen unless there's a bug somewhere
        Con.when (getEntries e2 == getEntries r && getTransferQueue e2 == getTransferQueue r && not (isDone r)) $
            Ex.die "Infinite loop detected in election counting"

        doCount r




writeLog :: Election -> IO ()
writeLog e = do
    let logName = (getLogDir e) ++ "/" ++ (show (getNextLogNum e)) ++ ".csv"

        header =
            [ "Seats"
            , "Vacancies"
            , "Total Papers"
            , "Quota"
            , "Candidate"
            , "Votes"
            , "Transfer"
            , "Status"
            , "Changed"
            , "Order Elected" ]
        static =
            [ show (getSeats e)
            , show (getVacancies e)
            , show (getTotalPapers e)
            , show (getQuota e)]
        dynFunc c =
            [ getID c
            , show (getTotalVotes c)
            , show (getVoteChange c)
            , show (getStatus c)
            , if (getChanged c) then show (getChanged c) else ""
            , if (Maybe.isJust (getOrderElected c)) then show (Maybe.fromJust (getOrderElected c)) else "" ]

        records = map (\x -> static ++ dynFunc x) (getEntries e)
        headerLine = CSV.unParseRecord CSV.defaultSettings header
        recordLines = map (CSV.unParseRecord CSV.defaultSettings) records
        output = unlines (headerLine:recordLines)
    IO.writeFile logName output




clearChange :: Entry -> Entry
clearChange entry = entry
    { getChanged = False
    , getVoteChange = 0 }




electCandidates :: Election -> ET.EitherT Election IO Election
electCandidates e = do
    let oldToElectNum = getNextToElect e
        electLoop x = ET.eitherT return electLoop $ doElectCandidate x
    r <- MIO.liftIO $ electLoop e
    if (getNextToElect r > oldToElectNum)
        then ET.left r
        else ET.right r




--  needs to be modified to take into account ties
--  may be prudent to put this just in the IO monad instead of EitherT
doElectCandidate :: Election -> ET.EitherT Election IO Election
doElectCandidate e = do
    let (running, notRunning) = List.partition ((== Running) . getStatus) (getEntries e)
        electedEntry = List.maximumBy compareVotes running
        (beforeEntries, afterEntries) = Misc.partBeforeAfter electedEntry (getEntries e)

        newTransfer = Transfer
            { getWhoFrom = getID electedEntry
            , getVoteAmount = getTotalVotes electedEntry - getQuota e
            , getNewValue = (fromIntegral (getTotalVotes electedEntry - getQuota e)) %
                                (fromIntegral (getTotalVotes electedEntry))
            , getWhatToDist = getCritTrace electedEntry }

        revisedElectedEntry = electedEntry
            { getStatus = Elected
            , getChanged = True
            , getOrderElected = Just (getNextToElect e) }
        allRevised = beforeEntries ++ [revisedElectedEntry] ++ afterEntries

    if (getTotalVotes electedEntry >= getQuota e)
        then do
            let logmsg = show (getID electedEntry) ++ " elected at logfile #" ++ show (getNextLogNum e)
            MIO.liftIO $ IO.appendFile (getMainLog e) (logmsg ++ "\n")
            MIO.liftIO $ Con.when (isVerbose e) (IO.hPutStrLn IO.stderr logmsg)
            ET.right (e
                { getEntries = allRevised
                , getTransferQueue = (getTransferQueue e) ++ [newTransfer]
                , getNextToElect = getNextToElect e + 1
                , getVacancies = getVacancies e - 1 })
        else ET.left e




checkIfDone :: Election -> ET.EitherT Election IO Election
checkIfDone e =
    let stillRunning = filter ((== Running) . getStatus) (getEntries e)
    in if (getVacancies e == 0 || length stillRunning == 0)
        then ET.left (e { isDone = True })
        else ET.right e




--  redistributing votes in STV is annoying as hell
transferVotes :: Election -> ET.EitherT Election IO Election
transferVotes e =
    if (length (getTransferQueue e) > 0)
        then doVoteTransfer e
        else ET.right e




--  may be prudent to put this just in the IO monad instead of EitherT
doVoteTransfer :: Election -> ET.EitherT Election IO Election
doVoteTransfer e = do
    let (currentTransfer:remainingTransfers) = getTransferQueue e
        fromEntry = Maybe.fromJust (List.find ((== getWhoFrom currentTransfer) . getID) (getEntries e))
        (beforeEntries, afterEntries) = Misc.partBeforeAfter fromEntry (getEntries e)
        notRunningIDs = map getID (filter ((/= Running) . getStatus) (getEntries e))

        reviseTrace candID trace = trace
            { getCriteria = getCriteria trace ++ [Sen.matchList notRunningIDs, Sen.matchID candID]
            , getTransferVal = getTransferVal trace * getNewValue currentTransfer }

        reviseFunc entry = do
            let newTraces = map (reviseTrace (getID entry)) (getWhatToDist currentTransfer)
            rawVoteChanges <- mapM (Sen.doCount (getCounter e)) (map getCriteria newTraces)
            let tracesAndChanges = zip (map fromIntegral rawVoteChanges) newTraces
                adjustedChanges = map (\(r,t) -> (floor (r * getTransferVal t), t)) tracesAndChanges
                filteredChanges = filter ((/= 0) . fst) adjustedChanges
                totalVoteChange = sum (map fst filteredChanges)
                addedTraces = map snd filteredChanges
            return (entry
                { getVoteChange = totalVoteChange
                , getTotalVotes = getTotalVotes entry + totalVoteChange
                , getCritTrace = getCritTrace entry ++ addedTraces })

        revisedFromEntry = fromEntry
            { getVoteChange = -(getVoteAmount currentTransfer)
            , getTotalVotes = getTotalVotes fromEntry - (getVoteAmount currentTransfer)
            , getCritTrace = (getCritTrace fromEntry) \\ (getWhatToDist currentTransfer) }
    revisedBeforeEntries <- MIO.liftIO $ mapM reviseFunc beforeEntries
    revisedAfterEntries <- MIO.liftIO $ mapM reviseFunc afterEntries
    let allRevised = revisedBeforeEntries ++ [revisedFromEntry] ++ revisedAfterEntries

    ET.left (e
        { getEntries = allRevised
        , getTransferQueue = remainingTransfers })




--  needs to be modified to take into account ties
checkNoQuota :: Election -> ET.EitherT Election IO Election
checkNoQuota e = do
    let (running, notRunning) = List.partition ((== Running) . getStatus) (getEntries e)
        minimumEntry = List.minimumBy compareVotes running
        (beforeEntries, afterEntries) = Misc.partBeforeAfter minimumEntry (getEntries e)

        makeElect entry = do
            let logmsg = show (getID entry) ++ " elected at logfile #" ++ show (getNextLogNum e)
            MIO.liftIO $ IO.appendFile (getMainLog e) (logmsg ++ "\n")
            MIO.liftIO $ Con.when (isVerbose e) (IO.hPutStrLn IO.stderr logmsg)
            return (entry
                { getStatus = Elected
                , getChanged = True })
        reviseFunc entry =
            if ((getStatus entry == Running) && (entry /= minimumEntry))
                then makeElect entry
                else return entry

    revisedMinEntry <-
        if (length running <= getVacancies e)
            then makeElect minimumEntry
            else return minimumEntry
    revisedBeforeEntries <- mapM reviseFunc beforeEntries
    revisedAfterEntries <- mapM reviseFunc afterEntries
    let allRevised = revisedBeforeEntries ++ [revisedMinEntry] ++ revisedAfterEntries

    if (length running <= getVacancies e + 1)
        then ET.left (e
            { getEntries = allRevised
            , getVacancies = 0 })
        else ET.right e




excludeCandidates :: Election -> ET.EitherT Election IO Election
excludeCandidates e = do
    let running = filter ((== Running) . getStatus) (getEntries e)
        sorted = reverse (List.sortBy compareVotes running)
        appliedBreakpoint = getQuota e - getTotalVotes (head sorted)

        excludeLoop n v e = do
            (i,r) <- MIO.liftIO $ excludeSomeone e
            let v1 = v + i
                n1 = n + 1
            if (v1 > appliedBreakpoint)
                then if (n > 0)
                        then ET.left e
                        else ET.left r
                else excludeLoop n1 v1 r

    if (length running > 0 && all (< getQuota e) (map getTotalVotes running))
        then excludeLoop 0 0 e
        else ET.right e




--  needs to be modified to take into account ties
--  this function is still in the IO monad in case I want to log something in verbose mode later
excludeSomeone :: Election -> IO (Int, Election)
excludeSomeone e = do
    let running = filter ((== Running) . getStatus) (getEntries e)
        excludedEntry = List.minimumBy compareVotes running
        (beforeEntries, afterEntries) = Misc.partBeforeAfter excludedEntry (getEntries e)

        newTransfer = Transfer
            { getWhoFrom = getID excludedEntry
            , getVoteAmount = getTotalVotes excludedEntry
            , getNewValue = 1
            , getWhatToDist = getCritTrace excludedEntry }

        revisedExcludedEntry = excludedEntry
            { getStatus = Eliminated
            , getChanged = True }
        allRevised = beforeEntries ++ [revisedExcludedEntry] ++ afterEntries

    return (getTotalVotes excludedEntry, e
        { getEntries = allRevised
        , getTransferQueue = (getTransferQueue e) ++ [newTransfer] })