-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyfec.py
1306 lines (1064 loc) · 33.4 KB
/
pyfec.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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## pyfec.py
## Python analysis of FEC data as provided by CIR via Kaggle
## October, 2012
##
## v. 0.1
## Rik Belew ([email protected])
## 27 Oct 12
import _mysql
import csv
import cPickle as pickle
import re
import random
import math
DataDir = '/Data/corpora/kaggle_CIR/'
## Database variables & routines
SchemaTableNames = [] # list of table names
SchemaColumns = {} # tblName -> [columnNameList]
TableLoadOrder = ('fec_itemized_cand_2012',
'fec_itemized_comm_2012',
'fec_itemized_ccl_2012',
'fec_itemized_indiv_2012',
'fec_itemized_pas_2012',
'fec_itemized_oth_2012'
)
DBSpecTbl = { \
# rootName -> (idAttr, [ (fkeyAttr,fObj,foAttr,add?) ], [keepAttr] )
"cand": ('candidate_id',[],["candidate_name", "party", "candidate_state", "candidate_office", \
"current_district", "incum_challenger_openseat", "candidate_status", \
"principle_campaign_committee_id", "city", "state", "zip", "fec_election_year"]),
"comm": ('committee_id',[],["committee_name", "treasurers_name", "city", "state", "zip", "nicar_election_year"]),
"ccl": ("linkage_id",[("candidate_id","cand","candidate_id",False), ("committee_id","comm","committee_id",False)], \
["fec_election_year"]),
"indiv": ("transaction_id", [("filer_id","comm","committee_id",False),("contributor_name","contrib","name",True)], \
["transaction_type", "nicar_date","amount","other_id", "nicar_election_year"]),
"oth": ("transaction_id", [("filer_id","comm","committee_id",False),("contributor_name","contrib","name",True)], \
["transaction_type", "nicar_date","amount","other_id", "nicar_election_year"]),
"pas": ("transaction_id", [("filer_id","comm","committee_id",False),("candidate_id","cand","candidate_id",False)],
["transaction_type", "nicar_date","amount","other_id", "nicar_election_year"])
}
class Cand():
pass
class Ccl():
pass
class Comm():
pass
class Indiv():
pass
class Oth():
pass
class Pas():
pass
class Contrib():
pass
CandTbl = {}
CclTbl = {}
CommTbl = {}
IndivTbl = {}
OthTbl = {}
PasTbl = {}
ContribTbl = {}
AllTbls = {}
AllTblNames = ['cand', 'comm', 'contrib', 'ccl', 'indiv', 'pas', 'oth']
class DBConn():
def __init__(self,dbName=''):
self.currDB = _mysql.connect(host="localhost",user="root", passwd="PWHERE", db=dbName)
def get_tableNames(self):
self.currDB.query('show tables;')
r=self.currDB.store_result()
tblNames = []
for ri in range(r.num_rows()):
f = r.fetch_row()
# (('fec_itemized_cand_2012',),)
tname = f[0][0]
tblNames.append(tname)
return tblNames
def get_colNames(self,tblName):
self.currDB.query("select column_name from information_schema.columns where table_name = '%s';" % tblName)
r=self.currDB.store_result()
colNames = []
for ri in range(r.num_rows()):
f = r.fetch_row()
# (('fec_itemized_cand_2012',),)
cname = f[0][0]
colNames.append(cname)
return colNames
def reconn(dbName):
db = DBConn(dbName)
tblNames = db.get_tableNames()
for tname in tblNames:
print '*',tname
for cname in db.get_colNames(tname):
print cname
def getRootName(tname):
# 'fec_itemized_cand_2012' -> 'cand'
return tname[13:-5]
def testCandID(rid,row,colNames):
idoff = rid[0]
idstate = rid[2:4]
iddist = rid[4:6]
off = row[colNames.index("candidate_office")]
state = row[colNames.index("state")]
dist = row[colNames.index("current_district")]
rv = idoff==off and idstate==state and iddist==dist
# if not rv:
# print 'odd CandID?!',rid,off,state,dist
return rv
def bldPyDict(db,tname,trn):
'return dictionary of _id -> tname objects'
db.currDB.query("select * from %s;" % tname)
r=db.currDB.store_result()
nrows = r.num_rows()
print 'bldPyDict: Table %s has %d rows' % (trn,nrows)
colNames = SchemaColumns[trn]
# ASSUME first attribute is UID
assert colNames[0].endswith('_id'), 'ASSUME first attribute is UID?!'
logicSpec = DBSpecTbl[trn]
# (idAttr, [ (fkeyAttr,fObj,foAttr,add?) ], [keepAttr] )
idAttr, fkeyList, keepList = logicSpec
newTbl = {}
allForeignRefTbl = {}
nRptErr = 5
nmiss=0
nadd=0
ndup=0
nnull=0
nnullfkey=0
ncull=0
ncomm=0
ncand=0
noddCand=0
# NB: silently ignore non-2012 entries
if trn=='comm' or trn=='indiv' or trn=='oth' or trn=='pas':
yrAttrib = "nicar_election_year"
else:
yrAttrib = "fec_election_year"
for ri in range(nrows):
row = r.fetch_row()[0] # ?? why first element of row?
assert len(row)==len(colNames), '#attribues != #values?!'
# NB: silently ignore non-2012 entries
idx = colNames.index(yrAttrib)
eyear = row[ idx ]
if eyear != '2012':
continue
idx = colNames.index(idAttr)
rid = row[ idx ]
rid = rid.strip()
if rid=='':
if nnull < nRptErr:
print 'bldPyDict: null id?! %s: currRow=%d' % (trn,ri)
nnull += 1
continue
if rid in newTbl:
if ndup < nRptErr:
print 'bldPyDict: dup id?! %s:%s currRow=%d prevRow=%d' % (trn,rid,ri,newTbl[rid].rowNum)
ndup += 1
continue
if trn=='cand':
match = testCandID(rid,row,colNames)
if not match:
noddCand += 1
# NB: avoid double counting PAS contributions included in other
# ASSUME pas loaded before oth
if (trn=='oth' and rid in AllTbls['pas']):
if ndup < nRptErr:
print 'bldPyDict: oth dup with pas id?! %s:%s currRow=%d' % (trn,rid,ri)
ndup += 1
continue
newObj = None # to kill pydev syntax errors
currfo0 = None
currfo1 = None
currfobj1 = None # actual object retrieved
# ASSUME 2 foreign keys ==> RELATION between foreign objects
# create newObj of type trn with id and any additional attributes
# add its ID to lists in both foreign objects
if len(fkeyList)==2:
fkTbl = {}
fka0,fo0,foa0,addP0 = fkeyList[0]
fka1,fo1,foa1,addP1 = fkeyList[1]
currForeignTbl0 = AllTbls[fo0]
currForeignTbl1 = AllTbls[fo1]
idx = colNames.index(fka0)
fkey0 = row[ idx ]
fkey0 = fkey0.strip()
if fkey0=='':
if nnullfkey < nRptErr:
print 'bldPyDict: null fkey0?! %s:%s currRow=%d' % (trn,rid,ri)
nnullfkey += 1
continue
if fkey0 in currForeignTbl0:
# cull dormant committees!
if fo0=='comm' and fkey0 in Comm2CullTbl:
ncull += 1
continue
currfo0 = fkey0
elif addP0:
if nadd < nRptErr:
print 'bldPyDict: adding new %s:%s from %s:%s' % (fo0,fkey0,trn,rid)
nadd += 1
newFObj = eval('%s()' % (fo0.capitalize()))
setattr(newFObj,"id",fkey0)
currForeignTbl0[fkey0] = newFObj
currfo0 = fkey0
else:
if nadd < nRptErr:
print 'bldPyDict: missing fkey0 %s:%s from %s:%s' % (fo0,fkey0,trn,rid)
fobj0 = None
nmiss += 1
# NB: for indiv and other, prefer other_id if it exists over free-text contrib name
# 2do: what about pas with other_id?!
if trn=='indiv' or trn=='oth':
idx = colNames.index('other_id')
fkey1 = row[ idx ]
fkey1 = fkey1.strip()
if fkey1!='':
if fkey1.startswith('C'):
if fkey1 in AllTbls['comm']:
currfo1 = fkey1
currfobj1 = AllTbls['comm'][currfo1]
ncomm += 1
elif fkey1.startswith('P') or fkey1.startswith('S') or fkey1.startswith('H'):
if fkey1 in AllTbls['cand']:
currfo1 = fkey1
currfobj1 = AllTbls['cand'][currfo1]
ncand += 1
else:
print 'bldPyDict: odd other_id?! %s in %s:%s' % (fkey1,trn,rid)
# if trn=='indiv' or trn=='oth' and haven't found valid other_id, proceed normally
if not currfo1:
idx = colNames.index(fka1)
fkey1 = row[ idx ]
fkey1 = fkey1.strip()
if fkey1=='':
if nnullfkey < nRptErr:
print 'bldPyDict: null fkey1?! %s:%s currRow=%d' % (trn,rid,ri)
nnullfkey += 1
continue
if fkey1 in currForeignTbl1:
# cull dormant committees!
if fo1=='comm' and fkey1 in Comm2CullTbl:
ncull += 1
continue
currfo1 = fkey1
currfobj1 = currForeignTbl1[currfo1]
elif addP1:
if nadd < nRptErr:
print 'bldPyDict: adding new %s:%s from %s:%s' % (fo1,fkey1,trn,rid)
nadd += 1
newFObj = eval('%s()' % (fo1.capitalize()))
setattr(newFObj,"id",fkey1)
currForeignTbl1[fkey1] = newFObj
currfo1 = fkey1
currfobj1 = currForeignTbl1[currfo1]
else:
if nmiss < nRptErr:
print 'bldPyDict: mising fkey %s:%s from %s:%s' % (fo1,fkey1,trn,rid)
nmiss += 1
## error checking will have caused some to 'continue' before this
## those with foreign keys have additional criteria
if len(fkeyList)==2 and not(currfo0 and currfo1):
continue
exec('newObj = %s()' % (trn.capitalize()))
setattr(newObj,"id",rid)
setattr(newObj,'rowNum',ri)
if len(keepList)>0:
for ka in keepList:
idx = colNames.index(ka)
val = row[ idx ]
setattr(newObj,ka,val)
if currfo0 and currfo1:
setattr(newObj,fo0,currfo0)
setattr(newObj,fo1,currfo1)
fobj0 = currForeignTbl0[currfo0]
currList = getattr(fobj0,trn,[])
currList.append(rid)
setattr(fobj0,trn,currList)
# NB, currfobj1 bound above, as might be of different types
currList = getattr(currfobj1,trn,[])
currList.append(rid)
setattr(currfobj1,trn,currList)
newTbl[rid] = newObj
print 'bldPyDict: done. N_%s=%d NDup=%d NMiss=%d NAdd=%d NCull=%d NNull=%d NNullFK=%d NCand' % (trn,len(newTbl),ndup,nmiss,nadd,ncull,nnull,nnullfkey)
if trn=='cand':
print '\tNoddCand=%d' % (noddCand)
return newTbl
Comm2CullTbl = {}
def parseAll(dbName,commCullFile=None):
db = DBConn(dbName)
global SchemaTableNames
SchemaTableNames = db.get_tableNames()
global SchemaColumns
for tname in SchemaTableNames:
rootName = getRootName(tname)
# NB rootNames are keys, tname needed by db
SchemaColumns[rootName] = db.get_colNames(tname)
global AllTbls
AllTbls['contrib'] = ContribTbl
if commCullFile:
dormantFile = DataDir+commCullFile
print ('parseAll: loading dormant committees from %s...' % dormantFile),
global Comm2CullTbl
Comm2CullTbl = {}
csvDictReader = csv.DictReader(open(dormantFile,"r"),delimiter="\t")
for i,entry in enumerate(csvDictReader):
cid = entry['CommID']
cname = entry['Comm.Name']
Comm2CullTbl[cid] = cname
Comm2CullTbl[cid]
print 'done. NDormant=%d' % (len(Comm2CullTbl))
for tname in TableLoadOrder:
rootName = getRootName(tname)
currTbl = bldPyDict(db,tname,rootName)
AllTbls[rootName] = currTbl
print 'done.'
for tblName in AllTbls.keys():
tbl = AllTbls[tblName]
pklFile = DataDir+'%sTbl.pkl' % tblName
print 'Pickling %d to %s...' % (len(tbl),pklFile)
# can't use cPickle, cuz of my special class objects (:
pstr = open(pklFile, 'w')
pickle.Pickler(pstr).dump(tbl)
pstr.close()
tbl = {}
del AllTbls[tblName]
def loadAllTbls():
global AllTbls
AllTbls = {}
for tblName in AllTblNames:
pklFile = DataDir+'%sTbl.pkl' % tblName
print ('Loading from %s...' % pklFile),
pstr = open(pklFile)
tbl = pickle.Unpickler(pstr).load()
AllTbls[tblName] = tbl
pstr.close()
print ' done. N=%d' % len(tbl)
print 'loadAllTbls: done.'
def loadOneTbl(tname):
pklFile = DataDir+'%sTbl.pkl' % tname
print ('Loading from %s...' % pklFile),
pstr = open(pklFile)
tbl = pickle.Unpickler(pstr).load()
pstr.close()
print ' done. N=%d' % len(tbl)
return tbl
## Analysis routines
def analCand():
'''handle against Type24 payments with commid_
drop NTopComm threshold
maintain committee cumms'''
global AllTbls
# 2do: collapse all these loadOneTbl() paras to function, but with global consequence!?
if 'cand' in AllTbls:
candTbl = AllTbls['cand']
else:
candTbl = loadOneTbl('cand')
AllTbls['cand'] = candTbl
if 'pas' in AllTbls:
pasTbl = AllTbls['pas']
else:
pasTbl = loadOneTbl('pas')
AllTbls['pas'] = pasTbl
outs = open(DataDir+'candSumm.csv','w')
outs.write('CandID,Name,Party,State,Office,District,Comm1,NComm,Tot,NContrib,NegTot,NNeg\n')
outs2 = open(DataDir+'cand2comm.csv','w')
outs2.write('CandID,CommID,Amt\n')
nzero = 0
ncand = 0
nedge=0
cummCommTbl = {}
# negAmtTbl = {} # typeCode -> Total
for cid,cand in candTbl.items():
tot = 0
antitot = 0
commTbl = {}
ncontrib = 0
nanti=0
comm1 = cand.principle_campaign_committee_id
if not ('pas' in dir(cand) and len(cand.pas)>0):
nzero += 1
continue
ncand += 1
ncontrib = len(cand.pas)
for contrib in cand.pas:
# ASSUME it's there
pas = pasTbl[contrib]
ptype = pas.transaction_type
amt = int(round(float(pas.amount)))
commID = pas.comm
negAmtFnd=False
# http://influenceexplorer.com/about/methodology/campaign_finance
# discovered 24 Oct 12 !
#
# In deciding what contributions to include, we attempt to follow the methodology of CRP and NIMSP:
#
# For federal contributions from individuals, we only count contributions with an FEC transaction type of 10, 11, 15, 15e, 15j or 22y.
# For federal contributions from organizations, we only count contributions with an FEC transaction type of 24k, 24r or 24z.
# We ignore all contributions with a category code of starting with 'Z', except for codes beginning with 'Z90' (candidate self-contributions), which are included.
# treat neg amounts as anti
if amt < 0:
amt = - amt
negAmtFnd=True
# NB: "against" transaction types
if negAmtFnd or ptype == '24A' or ptype == '24N':
commID += '_'
antitot += amt
nanti += 1
else:
tot += amt
if commID in commTbl:
commTbl[commID] += amt
else:
commTbl[commID] = amt
commKeys = commTbl.keys()
cname = cand.candidate_name
cname = cname.replace('"',"''")
outs.write('%s,"%s",%s,%s,%s,%s,%s,%d,%d,%d,%d,%d\n' % \
(cid,cname, cand.party, cand.candidate_state, \
cand.candidate_office, cand.current_district, comm1, \
len(commTbl),tot,ncontrib, antitot,nanti))
for ck in commKeys:
nedge+=1
outs2.write('%s,%s,%d\n' % (cid,ck,commTbl[ck]))
if ck in cummCommTbl:
cummCommTbl[ck] += commTbl[ck]
else:
cummCommTbl[ck] = commTbl[ck]
outs.close()
outs2.close()
print 'analCand: NCand=%d Nzero=%d NEdge=%d' % (ncand,nzero,nedge)
# see /Data/corpora/kaggle_CIR/logs/analCand2_121024.log
# print '# PType Amt'
# for ptype,amt in negAmtTbl.items():
# print ptype,amt
# Create committee summary, combining pos and anti contrib
combineCommTbl = {}
for k,v in cummCommTbl.items():
if k.endswith('_'):
basek = k[:-1]
anti = 1
else:
basek = k
anti = 0
currSumms = combineCommTbl.get(basek, [0,0] )
currSumms[anti] = cummCommTbl[k]
combineCommTbl[basek] = currSumms
outs3 = open(DataDir+'commCandTot.csv','w')
outs3.write('CommID,Pos,Neg,Tot\n')
commKeys = combineCommTbl.keys()
commKeys.sort()
for commID in commKeys:
pos = combineCommTbl[commID][0]
neg = combineCommTbl[commID][1]
outs3.write('%s,%d,%d,%d\n' % (commID,pos,neg,pos+neg) )
outs3.close()
SmallGivePrefix = 'otherStrata'
def analTopContrib(ntop=300):
global AllTbls
if 'contrib' in AllTbls:
contribTbl = AllTbls['contrib']
else:
contribTbl = loadOneTbl('contrib')
AllTbls['contrib'] = contribTbl
if 'indiv' in AllTbls:
indivTbl = AllTbls['indiv']
else:
indivTbl = loadOneTbl('indiv')
AllTbls['indiv'] = indivTbl
if 'oth' in AllTbls:
othTbl = AllTbls['oth']
else:
othTbl = loadOneTbl('oth')
AllTbls['oth'] = othTbl
contribList = []
allContrib = 0
for cid,contrib in contribTbl.items():
itot = 0
nindiv=0
otot = 0
nother=0
if 'indiv' in dir(contrib):
nindiv = len(contrib.indiv)
for contrib2 in contrib.indiv:
indiv = indivTbl[contrib2]
amt = int(round(float(indiv.amount)))
if amt<0:
amt = -amt
itot += amt
if 'oth' in dir(contrib):
nother= len(contrib.oth)
for contrib2 in contrib.oth:
oth = othTbl[contrib2]
amt = int(round(float(oth.amount)))
if amt<0:
amt = -amt
otot += amt
bothTot = itot+otot
allContrib += (itot+otot)
contribList.append( (cid,bothTot,nindiv,itot,nother,otot) )
ncontrib = len(contribTbl)
assert ncontrib == len(contribList), 'analTopContrib: dropped contrib?!'
print 'analTopContrib: allContrib = %e NContrib=%d ' % (allContrib,len(contribList))
print 'analTopContrib: sorting contribList...'
contribList.sort(key=(lambda x: x[1]),reverse=True)
contribRpt = DataDir+'topContrib.csv'
print 'writing to ',contribRpt
outs = open(contribRpt,'w')
outs.write('# Contrib,NIndiv,ITot,NOther,OTot,BothTot\n')
for ci, cinfo in enumerate(contribList[:ntop]):
cid,bothtot,nindiv,itot,nother,otot = cinfo
outs.write('"%s",%d,%d,%d,%d,%d\n' % (cid,nindiv,itot,nother,otot,bothtot))
outs.close()
def analContrib(computeStrata=False,outOtherComm=False,filterContrib=False):
'''v2: ASSUME contrib4comm_top and cand2comm lists already build
form cohorts of BigSpenders and then strata of others into
FracPercent bands
create pseudo contribNames for all but biggest spenders
and produce contrib,committee,amt records for graph
'''
c4cTbl = {}
c2cTbl = {}
if filterContrib:
contrib4commf = '/Data/corpora/kaggle_CIR/analData/contrib4comm_top.csv'
csvDictReader = csv.DictReader(open(contrib4commf,"r"))
for i,entry in enumerate(csvDictReader):
# CommID,CommName,Tot
cid = entry['CommID']
c4cTbl[cid] = int(entry['Tot'])
cand2commf = '/Data/corpora/kaggle_CIR/analData/cand2comm.csv'
csvDictReader = csv.DictReader(open(cand2commf,"r"))
for i,entry in enumerate(csvDictReader):
# CandID,CommID,Amt
# Source,Target,Weight
cid = entry['Target']
c2cTbl[cid] = (cid,entry['Amt'])
global AllTbls
if 'contrib' in AllTbls:
contribTbl = AllTbls['contrib']
else:
contribTbl = loadOneTbl('contrib')
AllTbls['contrib'] = contribTbl
if 'indiv' in AllTbls:
indivTbl = AllTbls['indiv']
else:
indivTbl = loadOneTbl('indiv')
AllTbls['indiv'] = indivTbl
if 'oth' in AllTbls:
othTbl = AllTbls['oth']
else:
othTbl = loadOneTbl('oth')
AllTbls['oth'] = othTbl
if 'comm' in AllTbls:
commTbl = AllTbls['comm']
else:
commTbl = loadOneTbl('comm')
AllTbls['comm'] = commTbl
NStrata = 10
# 23 Oct 12
StrataThreshVec = [1000, 2185, 3500, 6000, 10900, 25000, 48700, 80100, 144700]
# V3: provide for pre-computed StrataThreshVec
if computeStrata:
contribList = []
allContrib = 0
for cid,contrib in contribTbl.items():
bothTot = 0
if 'indiv' in dir(contrib):
for contrib2 in contrib.indiv:
# ASSUME it's there
indiv = indivTbl[contrib2]
amt = int(round(float(indiv.amount)))
# NB: what are negative numbers about?!
# but they only total $1.5e6; ignore
if amt<0:
amt = -amt
bothTot += amt
if 'oth' in dir(contrib):
for contrib2 in contrib.oth:
# ASSUME it's there
oth = othTbl[contrib2]
amt = int(round(float(oth.amount)))
# NB: what are negative numbers about?!
# but they only total $1.5e6; ignore
if amt<0:
amt = -amt
bothTot += amt
allContrib += bothTot
contribList.append( (cid,bothTot) )
ncontrib = len(contribTbl)
assert ncontrib == len(contribList), 'analContrib2: dropped contrib?!'
print 'analContrib2: allContrib = %e NContrib=%d ' % (allContrib,len(contribList))
print 'analContrib2: sorting contribList...'
contribList.sort(key=(lambda x: x[1]))
runSum = 0
stratSum = 0
si = 0
stratThreshFrac = allContrib / float(NStrata)
strataVec = [0 for i in range(NStrata)]
# computed 18 Oct 12
zeroVal = True
print '# ci,amt,stratSum,runSum'
for ci, cinfo in enumerate(contribList):
cid,amt = cinfo
if zeroVal and amt < 1:
continue
elif zeroVal:
print 'first %d zero!' % ci
zeroVal = False
stratSum += amt
runSum += amt
if stratSum >= stratThreshFrac:
strataVec[si] = amt
print '%d,%d,%d,%d' % (ci,amt,stratSum,runSum)
stratSum = 0
si += 1
if strataVec != StrataThreshVec:
print 'analContrib2: new strataVec != StrataThreshVec?!\n\tnew=%s\n\tcached=%s' % (strataVec,StrataThreshVec)
def getStrataIdx(samt,svec=StrataThreshVec):
'''return first i s.t. svec[i] > amt
last category of BigSpenders > svec[-1] return -1
'''
for i,amt in enumerate(svec):
if samt < amt:
return i
return -1
TestVec = [10,1500,2500,5001,7500,10000,20000,40000,100000,1e6]
# 23 Oct 12
TestStrataVec = [0, 1, 2, 3, 4, 4, 5, 6, 8, -1]
assert TestStrataVec == [getStrataIdx(amt) for amt in TestVec]
## End of strata code
contribRpt = DataDir+'contribSumm.csv'
print 'writing to ',contribRpt
outs = open(contribRpt,'w')
outs.write('# Contrib,NIndiv,ITot,NOther,OTot\n')
print 'analContrib2: Aggregating across contributions'
outStrataTbl = {}
# Accumulate across committees
for cid,contrib in contribTbl.items():
nicontrib = 0
itot=0
nocontrib = 0
otot=0
con4comTbl = {}
if 'indiv' in dir(contrib):
nicontrib = len(contrib.indiv)
for contrib in contrib.indiv:
indiv = indivTbl[contrib]
amt = int(round(float(indiv.amount)))
commID = indiv.comm
# NB: only output records to 'domoinant' committees wrt/ contrib4comm or comm2cand
if filterContrib and not(commID in c4cTbl or commID in c2cTbl):
if outOtherComm:
commID = 'OtherComm'
else:
continue
# NB: "against" transaction types
if indiv.transaction_type == '24A' or indiv.transaction_type == '24N':
commID = commID+'_'
if amt<0:
amt = -amt
itot += amt
if commID in con4comTbl:
con4comTbl[commID] += amt
else:
con4comTbl[commID] = amt
if 'oth' in dir(contrib):
nocontrib = len(contrib.oth)
for contrib in contrib.oth:
oth = othTbl[contrib]
amt = int(round(float(oth.amount)))
commID = oth.comm
# NB: only output records to 'domoinant' committees wrt/ contrib4comm or comm2cand
if filterContrib and not(commID in c4cTbl or commID in c2cTbl):
if outOtherComm:
commID = 'OtherComm'
else:
continue
# NB: "against" transaction types
if oth.transaction_type == '24A' or oth.transaction_type == '24N':
commID = commID+'_'
if amt<0:
amt = -amt
otot += amt
if commID in con4comTbl:
con4comTbl[commID] += amt
else:
con4comTbl[commID] = amt
outs.write('"%s",%d,%d,%d,%d\n' % (cid,nicontrib,itot,nocontrib,otot))
totContrib = itot + otot
strataIdx = getStrataIdx(totContrib)
outContrib = None
if strataIdx == -1:
outContrib = cid
# print outContrib,totContrib,len(con4comTbl)
else:
outContrib = '%s_%s' % (SmallGivePrefix,strataIdx)
if outContrib not in outStrataTbl:
outStrataTbl[outContrib] = {}
for commID in con4comTbl.keys():
amt = con4comTbl[commID]
if commID in outStrataTbl[outContrib]:
outStrataTbl[outContrib][commID] += amt
else:
outStrataTbl[outContrib][commID] = amt
outs.close()
contrib2commf = DataDir+'contrib2comm.csv'
print 'analContrib2: outputing %d contributors to %s' %(len(outStrataTbl),contrib2commf)
nedge=0
outs = open(contrib2commf,'w')
outs.write('ContribID,CommID,Amt\n')
for contrib,commTbl in outStrataTbl.items():
for commID in commTbl.keys():
amt = outStrataTbl[contrib][commID]
outs.write('"%s",%s,%d\n' % (contrib,commID,amt))
nedge += 1
outs.close()
print 'analContrib2 done. NEdge=%d' % (nedge)
def analComm():
global AllTbls
if 'comm' in AllTbls:
commTbl = AllTbls['comm']
else:
commTbl = loadOneTbl('comm')
AllTbls['comm'] = commTbl
if 'indiv' in AllTbls:
indivTbl = AllTbls['indiv']
else:
indivTbl = loadOneTbl('indiv')
AllTbls['indiv'] = indivTbl
if 'oth' in AllTbls:
othTbl = AllTbls['oth']
else:
othTbl = loadOneTbl('oth')
AllTbls['oth'] = othTbl
if 'pas' in AllTbls:
pasTbl = AllTbls['pas']
else:
pasTbl = loadOneTbl('pas')
AllTbls['pas'] = pasTbl
nindiv = 0
noth = 0
npas = 0
nzero=0
ncomm=0
nc2cedge=0
outs = open(DataDir+'commSumm.csv','w')
# HACK: bars used because commas in committee names(:
outs.write('CID,Name,NIndiv,ISum,NOther,OSum,NPas,PSum\n')
for cid,comm in commTbl.items():
indivLen=0
othLen=0
pasLen=0
isum = 0
osum = 0
psum = 0
try:
if 'indiv' in dir(comm):
indivLen=len(comm.indiv)
nindiv += 1
for indivID in comm.indiv:
indiv = indivTbl[indivID]
isum += float(indiv.amount)
if 'oth' in dir(comm):
othLen=len(comm.oth)
noth += 1
for othID in comm.oth:
oth = othTbl[othID]
osum += float(oth.amount)
nc2cedge += othLen
if 'pas' in dir(comm):
pasLen=len(comm.pas)
npas += 1
for pasID in comm.pas:
pas = pasTbl[pasID]
psum += float(pas.amount)
# HACK: bars used because commans in committee names(:
if indivLen+othLen+pasLen==0:
nzero += 1
else:
ncomm += 1
outs.write('%s,"%s",%d,%d,%d,%d,%d,%d\n' % \
(cid,comm.committee_name,indivLen,int(round(isum)),othLen,int(round(osum)),pasLen,int(round(psum))))
except Exception,e:
print 'Err? cid=%s name=%s e=%s' % (cid,comm.committee_name,e)
outs.close()
print 'analComm: NComm=%d nzero=%d NC2CEdge=%d' % (ncomm,nzero,nc2cedge)
def bldRaceTbl():
'raceID -> [(candID,state,party,ico)]'
candTbl = loadOneTbl('cand')
raceTbl = {}
for cid,cand in candTbl.items():
party = cand.party.strip()
state = cand.candidate_state.strip()
office = cand.candidate_office.strip()
district = cand.current_district.strip()
# raceID = '_'.join([state,office,district])
raceID = '%s_%s%s' % (office,state,district)
ico = cand.incum_challenger_openseat
if raceID in raceTbl:
raceTbl[raceID].append( (cid,state,party,ico) )
else:
raceTbl[raceID] = [ (cid,state,party,ico) ]
print '# RaceTbl\nRaceID,NCand'
for raceID in raceTbl.keys():
# if len(raceTbl[raceID]) != 2:
# print 'odd race ~2?!',raceID,raceTbl[raceID]
# else:
# parties = [cinfo[1] for cinfo in raceTbl[raceID] ]
# parties = parties.sort()
# if parties != ['DEM','REP']:
# print 'odd race D/R?!',raceID,raceTbl[raceID]
# else:
# nnorm += 1
print '%s,%d' % (raceID,len(raceTbl[raceID]))
# print 'bldRaceTbl: NRace=%d NNorm=%d' % (len(raceTbl),nnorm)
print 'bldRaceTbl: NRace=%d' % (len(raceTbl))
return raceTbl