-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathanlyzCFS_pub.py
2250 lines (1841 loc) · 60.6 KB
/
anlyzCFS_pub.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
''' anlyzCFS: analyze Calls for Service
as reported in Attachment 8 of InfoReport_OPDBudgetOperations_07.15.20
Created on Nov 1, 2020
@author: rik
'''
from collections import defaultdict
import datetime
from datetime import date
import csv
import glob
import math
import os
import re
import sys
import json
import jsonlines
import pickle
import pytz
import openpyxl
import numpy as np
# HACK: probably could suffice with using postgis SQL query
from geopy import distance
import psycopg2
import graphviz as gv
# "2018-10-20 04:40:00+00"
Postgres_DT_Format = '%Y-%m-%d %H:%M:%S%z'
PCRE = r'(?P<c1>[0-9]+)(?P<rest>.*)'
APCRE = r'A(?P<c1>[0-9]+)'
PCPat = re.compile(PCRE)
APCPat = re.compile(APCRE)
OaklandTimeZone = pytz.timezone('America/Los_Angeles')
def awareDT(dt):
'''strip away any tzinfo, assign it to OaklandTimeZone
'''
# https://dev.socrata.com/docs/datatypes/floating_timestamp.html
# you can usually assume they’re in the timezone of the publisher.
# https://docs.djangoproject.com/en/2.2/topics/i18n/timezones/#time-zones-faq
naiveDT = dt.replace(tzinfo=None)
return OaklandTimeZone.localize(naiveDT)
def dt2str(o):
if isinstance(o, datetime.datetime):
return o.__str__()
def loadCFSDetail(inf,lbl,cfsTbl):
'''load CFS from David Muhammed, 5 Nov 20
return cfsTbl: lbl_lineNo -> incidTbl
'''
# wb = openpyxl.load_workbook(xlfile)
# for sheet in wb.worksheets:
dtFormat = '%m/%d/%Y %H:%M' # 4/1/2020 0:01
reader = csv.DictReader(open(inf))
for i,entry in enumerate(reader):
# Agency,Beat,Call Source Text,Incident Type,Incident Type Description,Priority,Create Date/Time
incidTbl = {}
incidTbl['beat'] = entry['Beat']
incidTbl['source'] = entry['Call Source Text']
statute = entry['Incident Type']
incidTbl['statute'] = entry['Incident Type']
incidTbl['desc'] = entry['Incident Type Description']
incidTbl['priority'] = entry['Priority']
cdate = entry['Create Date/Time']
incidTbl['dateTime'] = datetime.datetime.strptime(cdate,dtFormat)
normStat = normPCCode(statute)
incidTbl['normStat'] = normStat
k = f'{lbl}_{i:05d}'
cfsTbl[k] = incidTbl
print('loadCFSDetail: NCFS=',len(cfsTbl))
return cfsTbl
def normPCCode(pccode):
'''return normed,segmented version of CFS type codes
'''
# NB: try basic match first, then 'A-' prefix
for ip,pat in enumerate([PCPat,APCPat]):
m = re.match(pat,pccode)
if m == None:
continue
mgdict = m.groupdict()
if ip==0:
rest = mgdict['rest']
else:
rest = 'attempted'
rest = rest.replace('.',' ')
rest = rest.replace('-',' ')
rest = rest.replace('(',' ')
rest = rest.replace(')',' ')
rest = rest.replace(' ','')
rest = rest.upper()
return( [mgdict['c1'], rest] )
# print('normPCCode: unmatched ?!', pccode)
return None
def loadCFSSummary(inf):
'''collect simple, parsed list of entries; keep line number order as key
'''
reader = csv.DictReader(open(inf))
cfsList = []
totfreq = 0
missed = {}
for i,entry in enumerate(reader):
# Type,Descriptions,Number of Incoming Calls in Past 12 Months of this Call Type,Number of Self Initiated Incidents in Past 12 Months of this Call Type,TOTAL
statuteTbl = {}
if entry['Type'] == 'Total':
continue
try:
statuteTbl['lineNo'] = i
# NB: using tweaked data
statute = entry['NormType'].strip()
statuteTbl['statute'] = statute
statuteTbl['desc'] = entry['Descriptions'].strip()
statuteTbl['nincoming'] = int(entry['Number of Incoming Calls in Past 12 Months of this Call Type'])
statuteTbl['nincSelf'] = int(entry['Number of Self Initiated Incidents in Past 12 Months of this Call Type'])
statuteTbl['tot'] = int(entry['TOTAL']) if entry['TOTAL'] != '' else 0
except Exception as e:
print('huh?',i,e)
totfreq += statuteTbl['tot']
normStat = normPCCode(statute)
statuteTbl['normStat'] = normStat
cfsList.append(statuteTbl)
print(f'loadCFS: NCFS={len(cfsList)} TotFreq={totfreq}')
# print('# Missing statutes\nStatute,Freq,Desc')
# for missStat in sorted(missed.keys(),key=lambda k:missed[k]['tot'],reverse=True):
# infoTbl = missed[missStat]
# print(f'"{missStat}",{infoTbl["tot"]},"{infoTbl["desc"]}"')
return cfsList
def bldAggregDetailList(CFSDetail):
'''collapse individual incidents into LIST of statute with counts ala summaries
return [statuteTbl]
'''
statTbl = defaultdict(list)
for k,incidTbl in CFSDetail.items():
stat = incidTbl['statute']
statTbl[stat].append(incidTbl)
statSummList = []
for stat in sorted(list(statTbl.keys())):
statuteTbl = {}
# 2do: confirm all desc,priority are the same
for k in ['statute','desc', 'normStat']:
# NB: artitrarily take from first incident
statuteTbl[k] = statTbl[stat][0][k]
statuteTbl['tot'] = len(statTbl[stat])
statuteTbl['incidList'] = statTbl[stat]
statSummList.append(statuteTbl)
return statSummList
def loadPC2CC(inf):
reader = csv.DictReader(open(inf))
pcList = []
for i,entry in enumerate(reader):
# PC0,Freq,CrimeCat
infoTbl = {}
try:
infoTbl['lineNo'] = i
statute = entry['PC0'].strip()
infoTbl['statute'] = statute
infoTbl['cc'] = entry['CrimeCat'].strip()
infoTbl['tot'] = int(entry['Freq']) if entry['Freq'] != '' else 0
except Exception as e:
print('huh?',i,e)
normStat = normPCCode(statute)
infoTbl['normStat'] = normStat
pcList.append(infoTbl)
return pcList
def getPCBits(infoTbl):
if infoTbl['normStat'] == None:
c1 = infoTbl['statute']
rest = ''
elif infoTbl['normStat'][0].isnumeric():
c1, rest = infoTbl['normStat']
else:
c1 = infoTbl['statute']
rest = ''
return c1,rest
def bldPCHier(allCFS):
'''create tree of statutes based on code/rest encoding from normPCCode()
'''
pcHier = defaultdict(lambda: defaultdict(list)) # code -> rest -> [infoTbl]
for i,infoTbl in enumerate(allCFS):
if infoTbl['normStat'] == None:
c1 = infoTbl['statute']
rest = ''
else:
c1,rest = getPCBits(infoTbl)
pcHier[c1][rest].append(infoTbl)
return pcHier
def rptPCHier(pcHier,outf):
outs = open(outf,'w')
outs.write('C1,Rest,Freq,Statute\n')
for c1key in sorted(pcHier.keys()):
for restKey in sorted(pcHier[c1key].keys()):
for infoTbl in pcHier[c1key][restKey]:
freq = infoTbl["tot"]
outs.write(f'{c1key},{restKey},{freq},"{infoTbl["statute"]}"\n')
outs.close()
CFSFields = ['Code','Description','Source','Priority','Beat','Address','Create Time','Transmit Time',\
'Dispatch Time','Arrival Time','Closed Time','Disposition1','Disposition2','Disposition3','Disposition4','Disposition5']
AttribNames = ['code', 'description', 'source', 'priority', 'beat', 'address', 'create time', 'transmit time', 'dispatch time', 'arrival time', 'closed time', 'disposition1', 'disposition2', 'disposition3', 'disposition4', 'disposition5']
def normField(fname):
norm = fname.lower()
norm = norm.replace(' ','_')
return norm
class CFS():
def __init__(self,idx):
self.idx = idx
def loadCFS2csv(inf):
'''OPD CFS data provided 201201
'''
cfsTbl = {} # line# -> CFS()
reader = csv.DictReader(open(inf))
for i,entry in enumerate(reader):
# NB: increment i for header line
idx = i+1
cfs = CFS(idx)
for f in CFSFields:
attrName = normField(f)
setattr(cfs,attrName,entry[f])
cfsTbl[idx] = cfs
return cfsTbl
CFSEventsLC = ['transmit_time','create_time','dispatch_time','arrival_time','closed_time']
CFSEvents = ['Transmit_Time','Create_Time','Dispatch_Time','Arrival_Time','Closed_Time']
def normalizeCFS(cfsTbl,conn):
'''add idx = line# + 1
convert date/time strings to datetimes
aggregate all dispositions into allDisposition
compute tot_time = Dispatch_Time - Arrival_Time
add census tract, zip, city council district, neighborhood
return cfsTbl (containing modified dicts)
'''
SRS_default = 4326
SRS_census = 4269
cfsDTFormat = '%Y-%m-%dT%H:%M:%S%z'
oneDaySec= 86400 # 60 * 60 * 24
notherDisp = 0
notherCall = 0
nbadDT = defaultdict(int) # event -> freq
nmissDT = 0
nct = 0
nzip = 0
nccd = 0
nnbrhd = 0
missCT = 0
missZip = 0
missCCD = 0
missNbrhd = 0
nLongDay = 0
totSec = 0
totChopSec = 0
if conn == None:
cur = None
else:
cur = conn.cursor()
for i,cfs in cfsTbl.items():
if i % 1e4 == 0:
print(f'normalizeCFS: {i}/{len(cfsTbl)} NMissDT={nmissDT} NLongDay={nLongDay} TotSec={totSec} TotChopTime={totChopSec} NOtherDisp={notherDisp} NOtherCFS={notherCall} NCT={nct}/{missCT} NZip={nzip}/{missZip} NCCD={nccd}/{missCCD} NNbrhd={nnbrhd}/{missNbrhd}')
idx = i+1 # to accomodate header line
cfs['idx'] = idx
badDatesP = False
## First pass: normalize all datetime
for fi,evname in enumerate(CFSEvents):
etimeStr = cfs[evname] # getattr(cfs,evname)
# 2019-01-01T00:00:12Z
try:
utcEtime = datetime.datetime.strptime(etimeStr,cfsDTFormat)
etime = utcEtime.replace(tzinfo=OaklandTimeZone)
except Exception as e:
# print(f'anlyzCFS2: bad datetime?! {i} {evname} {e}')
etime = None
nbadDT[evname] += 1
cfs[evname] = etime # setattr(cfs,evname,etime)
# 210203: definition of total time changed
if cfs['Dispatch_Time'] == None or cfs['Closed_Time'] == None:
nmissDT += 1
cfs['tot_timeSec'] = 0
cfs['chopSec'] = 0
else:
totDelta = cfs['Closed_Time'] - cfs['Dispatch_Time']
cfs['tot_timeSec'] = totDelta.days * oneDaySec + totDelta.seconds
totSec += cfs['tot_timeSec']
if cfs['tot_timeSec'] > oneDaySec:
# 210203: follow Liz's rule for long events
# "chop" time is whatever is cleaved beyond one day
nLongDay += 1
cfs['chopSec'] = cfs['tot_timeSec'] - oneDaySec
totChopSec += cfs['chopSec']
else:
cfs['chopSec'] = 0
allDisp = []
for di,k in enumerate(['Disposition1','Disposition2', 'Disposition3','Disposition4','Disposition5']):
if cfs[k] == '':
continue
disp = cfs[k]
allDisp.append(disp)
if di>0:
notherCall += 1
# 2do: delete separate attributes
# del cfs[k]
cfs['allDisposition'] = allDisp
if len(allDisp) > 1:
notherDisp += 1
if conn == None:
continue
ptStr = cfs['Geo']
pointDict = eval(ptStr)
xlng = pointDict['coordinates'][0]
ylat = pointDict['coordinates'][1]
addr = cfs['Address']
ptStrDefault = 'ST_SetSRID(ST_MakePoint(%s, %s),%d)' % (xlng,ylat,SRS_default)
ptStrCensus = 'ST_SetSRID(ST_MakePoint(%s, %s),%d)' % (xlng,ylat,SRS_census)
qry = 'SELECT geoid from "dailyIncid_censustract" where ST_Contains(geom,%s)' % (ptStrCensus)
ctGeoid = ''
try:
cur.execute(qry)
ctGeoid = cur.fetchone()[0]
# demog = ctractDemog[geoid]
nct += 1
except Exception as e:
# print(f'normalizeCFS: bad CT {addr}: {e}')
missCT += 1
cfs['ctract'] = ctGeoid
qry = 'SELECT zcta5ce10 from "dailyIncid_zip5geo" where ST_Contains(geom,%s)' % (ptStrDefault)
zip = ''
try:
cur.execute(qry)
zip = cur.fetchone()[0]
nzip += 1
except Exception as e:
# print(f'normalizeZip: bad zip {addr}: {e}')
missZip += 1
cfs['zip'] = zip
qry = 'SELECT name from "dailyIncid_citycncldistrict" where ST_Contains(geom,%s)' % (ptStrDefault)
ccd = ''
try:
cur.execute(qry)
ccd = cur.fetchone()[0]
nccd += 1
except Exception as e:
# print(f'normalizeZip: bad zip {addr}: {e}')
missCCD += 1
cfs['ccd'] = ccd
qry = 'SELECT name from oaknbrhd where ST_Contains(wkb_geometry,%s)' % (ptStrDefault)
nbrhd = ''
try:
cur.execute(qry)
nbrhd = cur.fetchone()[0]
nnbrhd += 1
except Exception as e:
# print(f'normalizeZip: bad zip {addr}: {e}')
missNbrhd += 1
cfs['nbrhd'] = nbrhd
print(f'normalizeCFS: NCFS={len(cfsTbl)} NMissDT={nmissDT} NLongDay={nLongDay} TotSec={totSec:e} TotChopSec={totChopSec:e} NOtherDisp={notherDisp} NOtherCFS={notherCall} NCT={nct}/{missCT} NZip={nzip}/{missZip} NCCD={nccd}/{missCCD} NNbrhd={nnbrhd}/{missNbrhd}')
return cfsTbl
def anlyzCFS2(cfsTbl,outdir):
'''v2: ASSUME cfsTbl has been thru normCFS()
capture timeDiff for CFS, some with BAD dispatch+arrival times
report code,beat,disposition stats
produce beat,code,disposition reports
return timeDiff
'''
timeDiff = defaultdict(lambda: defaultdict(int)) # (event1,event2) -> nminBucket -> freq
nDT = defaultdict(int) # event -> freq
nbadDT = defaultdict(int) # event -> freq
totBadDT = 0
npost = 0
codeFreq = defaultdict(lambda: defaultdict(int)) # code -> badDateP -> freq
beatFreq = defaultdict(lambda: defaultdict(int))
dispFreq = defaultdict(lambda: defaultdict(int))
maxTime = datetime.timedelta(minutes=1)
for i,cfs in cfsTbl.items():
# 201217: bad tot_time from normCFS()
totTime = cfs['Closed_Time'] - cfs['Transmit_Time']
if totTime > maxTime:
maxTime = totTime
totMin = int(totTime.seconds / 60)
timeDiff[('Transmit_Time','Closed_Time')][totMin] += 1
badDatesP = False
if cfs['Dispatch_Time'] == None or cfs['Arrival_Time'] == None:
badDatesP = True
totBadDT += 1
# elapTime = datetime.timedelta(minutes=0)
for fi,evname in enumerate(CFSEvents):
nDT[evname] += 1
etime = cfs[evname]
if etime==None:
nbadDT[evname] += 1
# NB: only collect gap times for good CFS
if fi>0 and not badDatesP:
prevName = CFSEvents[fi-1]
prevTime = cfs[prevName]
gap = etime - prevTime
# elapTime += gap
gapMinutes = int(gap.seconds / 60)
timeDiff[ (prevName,evname) ][gapMinutes] += 1
npost += 1
codeFreq[ cfs['Code'] ][int(badDatesP)] += 1
beatFreq[ cfs['Beat'] ][int(badDatesP)] += 1
for di,k in enumerate(cfs['allDisposition']):
if cfs['allDisposition'][di] == '':
continue
disp = cfs['allDisposition'][di]
dispFreq[disp][int(badDatesP)] += 1
if i % 1e5 == 0:
print(f'anlyzCFS2: i={i}' )
print(f'anlyzCFS2: NCFS={len(cfsTbl)} MaxDurationSec={maxTime.seconds} totBadDT={totBadDT} npost={npost}')
print('NDT')
for evname in CFSEvents:
print(f'\t{evname},{nDT[evname]}')
print('BadDT')
for evname in CFSEvents:
print(f'\t{evname},{nbadDT[evname]}')
print(f'anlyzCFS2: NCode={len(codeFreq)}')
outf = outdir + 'codeFreq.csv'
outs = open(outf,'w')
outs.write('Code,Full,Non\n')
for code in sorted(list(codeFreq.keys())):
outs.write(f'{code},{codeFreq[code][0]},{codeFreq[code][1]}\n')
outs.close()
print(f'anlyzCFS2: NBeat={len(beatFreq)}')
outf = outdir + 'beatFreq.csv'
outs = open(outf,'w')
outs.write('Beat,Full,Non\n')
for beat in sorted(list(beatFreq.keys())):
outs.write(f'{beat},{beatFreq[beat][0]},{beatFreq[beat][1]}\n')
outs.close()
print(f'anlyzCFS2: NDisp={len(dispFreq)}')
outf = outdir + 'dispositionFreq.csv'
outs = open(outf,'w')
outs.write('Disp,Full,Non\n')
for disp in sorted(list(dispFreq.keys())):
outs.write(f'{disp},{dispFreq[disp][0]},{dispFreq[disp][1]}\n')
outs.close()
return timeDiff
MinDay = 60 * 24
MinMon = MinDay * 30
YearMin = 525600 # 365 * 24 * 60
WeekMin = 10080 # 7 * 24 * 60
GapBins1 = np.array([1,5,10,15,30,60,120,180,240,480,MinDay,2*MinDay,7*MinDay,365*MinDay,60000])
GapBin1Lbls = ['1m','5m','10m','15m','30m','1h','2h','3h','4h','8h','1d','2d','7d','1y','More']
MaxDurationMin = 1450 # 791 # 201216
GapBinList2 = [i for i in range(MaxDurationMin)]
GapBins2 = np.array(GapBinList2)
GapBinLbls2 = [f'{i}' for i in range(MaxDurationMin)]
MinPerBin = 2
GapBinList3 = [i * MinPerBin for i in range(int(MaxDurationMin/MinPerBin))]
GapBins3 = np.array(GapBinList3)
GapBinLbls3 = [f'{i * MinPerBin}' for i in range(int(MaxDurationMin/MinPerBin))]
PairKeys = ["Transmit_Time,Create_Time",
"Create_Time,Dispatch_Time",
"Dispatch_Time,Arrival_Time",
"Arrival_Time,Closed_Time",
"Transmit_Time,Closed_Time"]
def rptBinFreq(allBinFreq,outf):
'''report CUMMULATIVE FRACTION of CFS with mins <= binMin
'''
outs = open(outf,'w')
hdr = 'Pair'
for lbl in GapBinLbls2:
hdr += f',{lbl}'
outs.write(hdr+'\n')
for pairs in PairKeys:
pk = tuple(pairs.split(','))
binFreq = allBinFreq[pk]
tot = sum(binFreq)
print(f'rptBinFreq: {pk} Tot={tot}')
line = f'"{pairs}"'
cumm = 0
# NB: Drop Zero column
for i in range(len(GapBins2)):
cumm += binFreq[i]
line += f',{float(cumm)/tot}'
outs.write(line+'\n')
outs.close()
def anlyzTimeDiff(cfsTbl,timeDiff,outf,cumm=True):
'''convert unique minute bucket keys to frequency bins
report CUMMULATIVE FRACTION of CFS with mins <= binMin
'''
outs = open(outf,'w')
hdr = 'Pair'
for lbl in GapBinLbls3:
hdr += f',{lbl}'
outs.write(hdr+'\n')
for pairs in PairKeys:
pk = tuple(pairs.split(','))
minGapDict = timeDiff[pk]
allNMin = sorted(list(minGapDict.keys()))
bidx = np.digitize(allNMin, GapBins3)
# NB: add extra bin beyond len(GapBins2)
binFreq = {bi:0 for bi in range(len(GapBins3)+1)}
nlong = 0
for ki,nmin in enumerate(allNMin):
if nmin > MaxDurationMin:
nlong += minGapDict[nmin]
continue
bi = bidx[ki]
try:
binFreq[bi] += minGapDict[nmin]
except Exception as e:
print('huh')
tot = sum(binFreq.values())
print(f'anlyzTimeDiff: {pk} maxMin = {allNMin[-1]} tot={tot} nlong={nlong}')
line = f'"{pairs}"'
cumm = 0
# NB: Drop Zero column
for i in range(len(GapBins3)):
if cumm:
cumm += binFreq[i]
val = float(cumm)/tot
else:
val = binFreq[i]
line += f',{val}'
outs.write(line+'\n')
outs.close()
def getMode(dist):
'''identify key with max value, excluding zero
'''
allKeys = sorted(list(dist.keys()))
maxVal = 0
maxK = None
for k in allKeys:
if k==0:
continue
if dist[k] > maxVal:
maxVal = dist[k]
maxK = k
return maxK,maxVal
def anlyzLocTime(cfsTbl,outdir,location='zip'):
'''capture per-location statistics for time-to-arrival
'''
arrTime = defaultdict(lambda: defaultdict(int)) # loc -> nminBucket -> freq
nbadDT = 0
nNoLoc = 0
nmissLoc = 0
for i,cfs in cfsTbl.items():
if cfs['Arrival_Time'] == None:
nbadDT += 1
continue
if location not in cfs:
nNoLoc += 1
continue
time2arr = cfs['Arrival_Time'] - cfs['Transmit_Time']
time2arrMin = int(time2arr.seconds / 60)
loc = cfs[location]
if loc=='':
nmissLoc += 1
continue
arrTime[loc][time2arrMin] += 1
print(f'anlyzLocTime: NBadDT={nbadDT} NNoLoc={nNoLoc} NMissLoc={nmissLoc}')
minFreq = 20
nloc = 0
statTbl = {}
csvf = outdir + f'locTime_{location}.csv'
csvStr = open(csvf,'w')
csvStr.write('Loc,NCFS,WAvg\n')
allLoc = sorted(list(arrTime.keys()))
for loc in allLoc:
tot = sum(arrTime[loc].values())
wavg = wgtAvg(arrTime[loc])
csvStr.write(f'{loc},{tot},{wavg}\n')
if tot > minFreq:
# NB: drop state & county digits of geoID
if location == 'ctract':
idx = loc[5:]
else:
idx = loc
statTbl[idx] = {'ncfs': tot, 'wavg': wavg}
nloc += 1
csvStr.close()
jsonf = outdir + f'locTime_{location}.json'
json.dump(statTbl,open(jsonf,'w'))
print(f'anlyzLocTime: NLoc={len(arrTime)} NBadDT={nbadDT} NNoLoc={nNoLoc} NFreqLoc={nloc}')
# 210112: Addresses > 100 mentions in CFS or Oakcrime
BogusAddr = set(['0',
'100 98TH AV',
'10700 MACARTHUR BLVD',
'2300 SAN PABLO AV',
'2300 SAN PABLO AVE',
'2600 73RD AV',
'3000 E 9TH ST',
'3200 GRAND AV',
'3200 LAKESHORE AV',
'400 7TH ST',
'400 7TH STREET',
'400 HEGENBERGER RD',
'4000 ALAMEDA AV',
'600 HEGENBERGER RD',
'6300 COLLEGE AV',
'7000 COLISEUM WY',
'7200 BANCROFT AV',
'8300 OAKPORT ST',
'8400 EDGEWATER DR'])
def comp2Incid(cfsTbl,incidConn,dispoCodes,outdir,lbl,matchRptOnly=True,pcOnly=False,uniqOnly=False):
'''attempt to join CFS with some incidents
Only attempt to match CFS with some dispo that is reported
return matches: code -> desc -> crimecat -> [opd_rd]
'''
matchFile = outdir + f'matchingCFS_{lbl}.csv'
outMatch = open(matchFile,'w')
hdr = 'CFSIdx,MatchIdx,Code,Desc,Dispo1,ArrivalDT,CFSAddr,Beat,OPD_RD,OIDx,IncidDT,IncidAddr,CrimeCat'
hdr += ',PCList,PCMatch,TimeDiff,SameAddr,DistM,Match'
outMatch.write(hdr+'\n')
missFile = outdir + f'missingReport_{lbl}.csv'
outMiss = open(missFile,'w')
hdr = 'Idx,Code,AllDispo'
outMiss.write(hdr+'\n')
maxMatch = 5
maxDistM = 200
maxSecAfter = 25 * 60 * 60 # 25h after arrival
nearbyDistM = 50.
cursor = incidConn.cursor()
matches = defaultdict(lambda: defaultdict(list)) # (code,dispo1) -> (incidType,incidDesc) -> [opd_rd]
nrpt = 0
npost = 0
nmatch = 0
nbadArrDT = 0
noMatch = 0
nmaxMatch = 0
nsameAddr = 0
nnear = 0
npcMatch = 0
ndiffBeat = 0
nbadAddr = 0
nmatchFreq = defaultdict(int)
startTime = datetime.datetime.now()
for i,cfs in cfsTbl.items():
if i % 1000 == 0:
elap = datetime.datetime.now()-startTime
print(f'comp2Incid: {i} {elap.seconds} sec NRpt={nrpt} NBadArrDT={nbadArrDT} NBadAddr={nbadAddr} NoMatch={noMatch} NPost={npost} PCMatch={npcMatch} SameAddr={nsameAddr} NNear={nnear} NMatch={nmatch}')
## Only attempt to match CFS with some dispo that is reported
allDispo = cfs['allDisposition']
rpt = False
for id,dispo in enumerate(allDispo):
if dispo not in dispoCodes:
print(f'comp2Incid: {dispo} not in table?!')
continue
if dispoCodes[dispo]['report'] or dispoCodes[dispo]['arrest']:
rpt = True
if matchRptOnly and not rpt:
continue
nrpt += 1
if 'Arrival_Time' not in cfs or cfs['Arrival_Time']==None:
nbadArrDT += 1
continue
cfsAddr = cfs['Address']
if cfsAddr in BogusAddr:
nbadAddr += 1
continue
cfsArrTime = cfs['Arrival_Time']
# minDT = (cfsArrTime - datetime.timedelta(days=1))
maxDT = (cfsArrTime + datetime.timedelta(seconds=maxSecAfter))
minDateStr = cfsArrTime.strftime(Postgres_DT_Format)
maxDateStr = maxDT.strftime(Postgres_DT_Format)
ptStr = cfs['Geo']
pointDict = eval(ptStr)
xlng = pointDict['coordinates'][0]
ylat = pointDict['coordinates'][1]
# NB: Postgis points are GEOMETRY, but ST_GeogFromText() is required?!
qryStr = '''select opd_rd,oidx,"cdateTime",addr,"crimeCat",ucr,statute,beat,geobeat,"pcList","roList",xlng,ylat from "dailyIncid_oakcrime" where
ST_Distance(ST_GeogFromText('POINT(%s %s)'), point) < %s and
"cdateTime" > %s and "cdateTime" < %s;'''
values = (xlng,ylat,maxDistM,minDateStr,maxDateStr)
cursor.execute(qryStr,values)
allResults = cursor.fetchall()
nresult = len(allResults)
idx = cfs['idx']
code = cfs['Code']
if nresult == 0:
noMatch += 1
outMiss.write(f'{idx},{code},"{allDispo}"\n')
continue
nmatchFreq[nresult] += 1
if nresult > maxMatch:
nmaxMatch += 1
# continue
cfsBeat = cfs['Beat']
normCode = normPCCode(code)
desc = cfs['Description']
dispo1 = cfs['allDisposition'][0] if len(cfs['allDisposition']) > 0 else ''
for ir,result in enumerate(allResults):
opd_rd,oidx,incidDT,incidAddr,crimeCat,ucr,statute,beatIncid,geobeatIncid,pcListStr,ucrList,incidXLng,incidYLat = result
if incidAddr in BogusAddr:
nbadAddr += 1
continue
if not(cfsBeat == beatIncid or cfsBeat == geobeatIncid):
ndiffBeat += 1
npost += 1
## Match against incident penal codes
pcMatchP = False
if pcListStr != None:
pcList = eval(pcListStr)
if normCode==None or pcList==None or pcList==[]:
pcMatchP = False
else:
probe = normCode[0]
pcMatchP = False
for pc in pcList:
if pc.find(probe) != -1:
pcMatchP = True
break
if pcMatchP:
npcMatch += 1
pcMatch = 1
else:
pcMatch = 0
pcMatchStr = '1' if pcMatchP else '0'
cfsATaware = awareDT(cfsArrTime)
gapTime = (incidDT - cfsATaware)
gapMin = gapTime.seconds / 60
# NB: EXACT string match required
sameAddr = 1 if cfsAddr==incidAddr else 0
# NB: only test distance if addresses differ
if sameAddr==1:
distM = 0.
nsameAddr += 1
else:
# NB: points whacked 90 degrees to conform to geopy?!
cfsPt = (xlng+90.,ylat)
incidPt = (incidXLng+90.,incidYLat)
distM = distance.distance(incidPt,cfsPt).meters
nearby = distM < nearbyDistM
if nearby:
nnear += 1
line = f'{idx},{ir+1},"{code}","{desc}","{dispo1}",{cfsArrTime},"{cfsAddr}",{cfsBeat},{opd_rd},{oidx},{incidDT},"{incidAddr}","{crimeCat}"'
line += f',"{pcListStr}",{pcMatchStr},{gapMin},{sameAddr},{distM}'
if uniqOnly:
nmatch += 1
line += ',1'
outMatch.write(line+'\n')
matches[ (code,dispo1) ][statute].append(opd_rd)
break
if pcOnly and pcMatchP:
nmatch += 1
line += ',1'
outMatch.write(line+'\n')
matches[ (code,dispo1) ][statute].append(opd_rd)
else:
if sameAddr==1 or pcMatchP or nearby:
nmatch += 1
line += ',1'
outMatch.write(line+'\n')
matches[ (code,dispo1) ][statute].append(opd_rd)
else:
line += ',0'
outMatch.write(line+'\n')
outMatch.close()
outMiss.close()
print(f'comp2Incid: NRpt={nrpt} NBadArrDT={nbadArrDT} NBadAddr={nbadAddr} NoMatch={noMatch} NPost={npost} PCMatch={npcMatch} SameAddr={nsameAddr} NNear={nnear} NMatch={nmatch}')
freqRpt = ';'.join(f'{k}:{nmatchFreq[k]}' for k in sorted(list(nmatchFreq.keys())))
print(f'comp2Incid: nmatch: {freqRpt}')
# matches: code -> desc -> crimecat -> [opd_rd]
matchesDict = {}
for code in matches.keys():
matchesDict[code] = {}
for desc in matches[code].keys():
matchesDict[code] = {}
for cc in matches[code].keys():
# NB: make a copy of [opd_rd] list
matchesDict[code][cc] = matches[code][cc][:]
# if dlogOnly:
# matchesDict[code][cc] = {}
# for pc in matches[code][cc].keys():
# # NB: make a copy of [opd_rd] list
# matchesDict[code][cc][pc] = matches[code][cc][pc][:]
# else:
return matchesDict
def loadIncidCodes(inf):
incidCodes = {} # incidCode -> desc
reader = csv.DictReader(open(inf))
for i,entry in enumerate(reader):
# IncidentCode,IncidentTypeDescription,Notes,IncidentType,IncidentCategory,LevelofViolence,CAPenalTitle,CAPenalTitleDesc,CAPenalChapter,CAPenalChapterDesc
try:
ucr = entry['UCRMajorCrimesReportingCategories']
if ucr == 'N/A':
ucr = None
violence = None
else:
# eg, Violent - Aggrevated Assault
if ucr.startswith('Violent'):
violence = ucr[10:]
else:
violence = None
incidCodes[entry['IncidentCode']] = {'desc': entry['IncidentTypeDescription'],
'type': entry['IncidentType'],
'category': entry['IncidentCategory'],
'violence': violence,
'ucr': ucr
}
except Exception as e:
print(f'loadIncidCodes: {i} {e}')
continue
print(f'loadIncidCodes: NIncid={len(incidCodes)}')
return incidCodes
def loadDispoCodes(inf):
dispoCodes = {} # dispoCode -> desc
reader = csv.DictReader(open(inf))
nrpt = 0
narrest=0
nalarm=0
for i,entry in enumerate(reader):
# DispositionCode,DispositionCodeDescription,DispositionCodeCategory,Report,Notes
info = {'desc': entry['DispositionCodeDescription'],
'category': entry['DispositionCodeCategory']}
rptP = True if entry['Report']=='1' else False
info['report'] = rptP
if rptP:
nrpt += 1
arrestP = True if entry['DispositionCodeCategory']=='Arrest' else False
info['arrest'] = arrestP
if arrestP:
narrest += 1
alarmP = True if entry['DispositionCodeCategory']=='Alarm' else False
info['alarm'] = alarmP
if alarmP: