-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreport_data_loader.py
776 lines (673 loc) · 32.8 KB
/
report_data_loader.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
import pandas as pd
import numpy as np
import datetime as dtime
import gc
import requests
import json
### Dictionaries and region names in different formats
regiones = ['Arica y Parinacota',
'Tarapacá',
'Antofagasta',
'Atacama',
'Coquimbo',
'Valparaíso',
'Libertador General Bernardo O\'Higgins',
'Maule',
'Ñuble',
'Biobío',
'La Araucanía',
'Los Ríos',
'Los Lagos',
'Aysén del General Carlos Ibáñez del Campo',
'Magallanes y de la Antártica Chilena',
'Metropolitana de Santiago']
region_names_dict = {
'Tarapaca':'Tarapacá',
'Valparaiso':'Valparaíso',
'Metropolitana':'Metropolitana de Santiago',
'Del Libertador General Bernardo O’Higgins':"Libertador General Bernardo O'Higgins",
'Nuble':'Ñuble',
'Biobio':'Biobío',
'La Araucania':'La Araucanía',
'Los Rios':'Los Ríos',
'Aysen':'Aysén del General Carlos Ibáñez del Campo',
'Magallanes y la Antartica':'Magallanes y de la Antártica Chilena'
}
order = [
'SS ARICA',
'SS IQUIQUE',
'SS ANTOFAGASTA',
'SS ATACAMA',
'SS COQUIMBO',
'SS ACONCAGUA',
'SS VIÑA DEL MAR QUILLOTA',
'SS VALPARAISO SAN ANTONIO',
'SS LIBERTADOR B. O\'HIGGINS',
'SS DEL MAULE',
'SS ÑUBLE',
'SS BÍO BÍO',
'SS CONCEPCIÓN',
'SS TALCAHUANO',
'SS ARAUCO',
'SS ARAUCANÍA NORTE',
'SS ARAUCANÍA SUR',
'SS VALDIVIA',
'SS OSORNO',
'SS DEL RELONCAVÍ',
'SS CHILOÉ',
'SS AISÉN',
'SS MAGALLANES',
'SS METROPOLITANO NORTE',
'SS METROPOLITANO OCCIDENTE',
'SS METROPOLITANO CENTRAL',
'SS METROPOLITANO ORIENTE',
'SS METROPOLITANO SUR',
'SS METROPOLITANO SUR ORIENTE'
]
indices_dict={'Til Til':'Tiltil',
'Ránqui':'Ránquil',
'Pitrufquén':'Pitrufquen',
'Paihuano':'Paiguano',
'Los Ángeles':'Los Angeles',
'Llay-Llay':'Llaillay',
'San Pedro de La Paz':'San Pedro de la Paz',
'La Calera': 'Calera',
'Copiapo': 'Copiapó',
'Vicuna': 'Vicuña',
'Concon': 'Concón',
'Vina del Mar':'Viña del Mar',
'Valparaiso':'Valparaíso',
'Quilpue':'Quilpué',
'Curico':'Curicó',
'Longavi':'Longaví',
'Hualpen':'Hualpén',
'Machali':'Machalí',
'Chillan':'Chillán',
'Camina':'Camiña',
'Concepcion':'Concepción',
'Requinoa':'Requínoa',
'Alhue':'Alhué',
'Maria Elena':'María Elena',
'Maria Pinto':'María Pinto',
'Donihue':'Doñihue',
'Colbun':'Colbún',
'Constitucion':'Constitución',
'Chillan Viejo':'Chillán Viejo',
'Canete':'Cañete',
'Alto Biobio':'Alto Biobío',
'Tome':'Tomé',
'Los Alamos':'Los Álamos',
'Vilcun':'Vilcún',
'Mulchen':'Mulchén',
'Santa Barbara':'Santa Bárbara',
'Conchali':'Conchalí',
'Curacavi':'Curacaví',
'Estacion Central':'Estación Central',
'Maipu':'Maipú',
'Nunoa':'Ñuñoa',
'Penaflor':'Peñaflor',
'Penalolen':'Peñalolén',
'San Joaquin':'San Joaquín',
'San Jose de Maipo':'San José de Maipo',
'San Ramon':'San Ramón',
'Olmue':'Olmué',
'Puchuncavi':'Puchuncaví',
'Coinco':'Coinco',
'Chepica':'Chépica',
'Rio Claro':'Río Claro',
'Quillon':'Quillón',
'Niquen':'Ñiquén',
'San Nicolas':'San Nicolás',
'Vilcun':'Vilcún',
'Chanaral':'Chañaral',
'Combarbala':'Combarbalá',
'Rio Hurtado': 'Río Hurtado',
'Santa Maria': 'Santa María',
'Licanten':'Licantín',
'San Fabian':'San Fabián',
'Ranquil':'Ránquil',
'Tirua':'Tirúa',
'Traiguen':'Traiguén',
'Pucon':'Pucón',
'Curacautin':'Curacautín',
'Puren':'Purén',
'Tolten':'Toltén',
'Rio Bueno':'Río Bueno',
'Mafil':'Máfil',
'La Union':'La Unión',
'Maullin':'Maullín',
'Cochamo':'Cochamó',
'Rio Negro':'Río Negro',
'Chaiten' :'Chaitén',
'Aysen':'Aysén',
'Licanten':'Licantén',
'Quellon':'Quellón',
'Hualaihue': 'Hualaihué',
'Coihaique':'Coyhaique'}
regiones_short = ['Arica y Parinacota',
'Tarapacá',
'Antofagasta',
'Atacama',
'Coquimbo',
'Valparaíso',
'O’Higgins',
'Maule',
'Ñuble',
'Biobío',
'Araucanía',
'Los Ríos',
'Los Lagos',
'Aysén',
'Magallanes',
'Metropolitana']
###
def last_data_day():
'''
It calculates the nearest past Tuesday or Saturday
output:
data_day , report_day
data_day: datetime object
report_day: "day/month" string format
'''
weekday = dtime.date.today().weekday()
if weekday>=1 and weekday<5: # nearest Tu
dif = weekday-1
else:
dif = (weekday-5)%7
data_day = dtime.date.today() - dtime.timedelta(days=dif)
report_day = data_day.strftime("%d/%m")
return data_day, report_day
def report_date():
endpoint_R = requests.get('http://192.168.2.223:5006/getNationalEffectiveReproduction' )
R = json.loads(endpoint_R.text)
year, month, day = str(R['dates'][-1].split('T')[0]).split('-')
date = dtime.datetime(int(year),int(month),int(day))
date += dtime.timedelta(days=1)
report_day = date.strftime("%d/%m")
return date.date() , report_day
def color_dim(data):#23, 41, 58
if data <= .3: color = '#00cc66'
elif data < .4: color = '#ffcc00'
else: color = '#ff0000'
return color
def color_rate_summary(data):
if data <= .25: color = '#00cc66'
elif (data < .30): color = '#FFF333'
else: color = '#DE2F2A'
return color
def color_r0_summary(data):
if data == 0.0: color = 'w'
elif data <= .8: color = '#00cc66'
elif data < 1.00: color = '#FFF333'
else: color = '#DE2F2A'
return color
def color_prvlnc_summary(data):
if data <= 4.: color = '#00cc66'
elif data < 5.: color = '#FFF333'
else: color = '#DE2F2A'
return color
def color_underreporting_summary(data):
if data =='N':
color = '#00cc66'
elif float(data) == 0:
color = '#00cc66'
elif float(data) < 10:
color = '#FFF333'
else:
color = '#DE2F2A'
return color
def color_camas(data):#23, 41, 58
if data <= .25: color = '#00cc66'
elif data < .75: color = '#FFF333'
elif data < .85: color = '#E3B500'
else: color = '#DE2F2A'
return color
def color_hos_sit(data_uti, data_uci, data_vmi):#23, 41, 58
v = len([1 for data in [data_uti, data_uci, data_vmi] if data <= .25 ])
a = len([1 for data in [data_uti, data_uci, data_vmi] if data < .75 ])
r = len([1 for data in [data_uti, data_uci, data_vmi] if data >= .75 ])
if r>=2:
color = '#DE2F2A'
elif a == 2 and r == 1:
color = '#E3B500'
elif a == 2 and v == 1:
color = '#FFF333'
elif a == 3 :
color = '#FFF333'
elif v == 2 :
color = '#27AE60'
elif v == 3:
color = '#00cc66'
return color
def color_rate(data):
if data <= .25: color = '#00cc66'
elif (data < .30): color = '#ffcc00'
else: color = '#ff0000'
return color
def color_prvlnc(data):
if data <= 4.: color = '#00cc66'
elif data < 5.: color = '#ffcc00'
else: color = 'red'
return color
def color_r0(data):
if data == 0.0: color = 'w'
elif data <= .8: color = '#00cc66'
elif data < 1.00: color = '#ffcc00'
else: color = 'red'
return color
def color_im(data):
if data <= 2.: color = '#00cc66'
elif data < 4.: color = '#ffcc00'
else: color = 'red'
return color
# para resumen de estado epidemiológico
def underreporting_by_region(slice_date = None):
endpoint = 'http://192.168.2.223:5006/getNewCasesUnderreportByState'
req_end = requests.get(endpoint)
data_ = json.loads(req_end.text)
data = data_['data']
data = pd.DataFrame(data).T
# print("underreporting_by_region slice_date", slice_date)
if slice_date is not None:
# print("underreporting_by_region slice_date", slice_date)
dates = pd.DataFrame(data.loc['10']['date']).apply(__iso_handler, axis =1)
date_index = int(np.argwhere(dates.values == slice_date))
print("date_index", date_index)
for ind in data.index:
data.loc[ind]['date'] = data.loc[ind]['date'][:date_index]
data.loc[ind]['mean'] = data.loc[ind]['mean'][:date_index]
data.loc[ind]['low'] = data.loc[ind]['low'][:date_index]
data.loc[ind]['high'] = data.loc[ind]['high'][:date_index]
return data
# para resumen de estado epidemiológico
def underreporting_national(slice_date = None):
endpoint = 'http://192.168.2.223:5006/getNationalNewCasesUnderreport'
req_end = requests.get(endpoint)
data = json.loads(req_end.text)
# print("underreporting_national slice_date", slice_date)
if slice_date is not None:
# print("underreporting_national slice_date", slice_date)
dates = pd.DataFrame(data['date']).apply(__iso_handler, axis =1)
# print("dates.values", dates.values)
date_index = int(np.argwhere(dates.values == slice_date))
# print("date_index", date_index)
data['date'] = data['date'][:date_index]
data['mean'] = data['mean'][:date_index]
data['low'] = data['low'][:date_index]
data['high'] = data['high'][:date_index]
return data
def get_total_and_active_national(slicing_date = None):
url_all_cases = 'http://192.168.2.223:5006/getTotalCasesAllComunas'
url_active_cases = 'http://192.168.2.223:5006/getActiveCasesAllComunas'
# data = pd.read_csv(url)
endpoint_all = requests.get(url_all_cases)
endpoint_active = requests.get(url_active_cases)
data_all = json.loads(endpoint_all.text)
data_active = json.loads(endpoint_active.text)
all_data = pd.DataFrame(data_all['data'])
active_data = pd.DataFrame(data_active['data'])
con_cases = pd.DataFrame(index = pd.to_datetime(data_all['dates']).strftime('%d-%m-%y'))
con_cases['total'] = all_data.sum(axis = 1).values
act_cases = pd.DataFrame(index = pd.to_datetime(data_active['dates']).strftime('%d-%m-%y'))
act_cases['total'] = active_data.sum(axis = 1).values
if slicing_date is not None:
year, month, day = slicing_date.split('-')
weekday = dtime.datetime(int(year), int(month), int(day)).weekday()
if weekday>=0 and weekday<4: # nearest Tu
dif = weekday#-1
else:
dif = weekday-4
data_day = dtime.datetime(int(year), int(month), int(day)) - dtime.timedelta(days=dif)
slice_index = np.argwhere(con_cases.index == data_day.strftime('%d-%m-%y'))[0][0]
con_cases = con_cases.iloc[:slice_index]
slice_index = np.argwhere(act_cases.index == data_day.strftime('%d-%m-%y'))[0][0]
act_cases = act_cases.iloc[:slice_index]
return con_cases, act_cases
def asp_national(national_underrep):
endpoint = 'http://192.168.2.223:5006/getActiveCasesAllComunas'
req_end = requests.get(endpoint)
data_ = json.loads(req_end.text)
#data = data_['data']
# endpoint2 = 'http://192.168.2.223:5006/getNationalNewCasesUnderreport'
# req_end2 = requests.get(endpoint2)
# data_2 = json.loads(req_end2.text)
data_2 = national_underrep
active_nat =np.sum(pd.DataFrame(data_['data']), axis = 1)
under_nat = pd.DataFrame(data_2, index = data_2['date']).drop(columns = 'date')
active_date_dt = pd.to_datetime(data_['dates'])
under_date_dt = pd.to_datetime(data_2['date'])
active_date_human = active_date_dt.strftime('%d-%m-%y')
under_date_human = under_date_dt.strftime('%d-%m-%y')
active_nat.index = active_date_human
under_nat.index = under_date_human
index = [i for i in active_date_human if i in under_date_human]
asp_data_mean = [active_nat[ind]/(1-under_nat['mean'][ind]) for ind in index]
asp_data_low = [active_nat[ind]/(1-under_nat['high'][ind]) for ind in index]
asp_data_high = [active_nat[ind]/(1-under_nat['low'][ind]) for ind in index]
return asp_data_mean, asp_data_low, asp_data_high,index
def asp_state(state, underreporting):
'''
State must be a zero padded string
'''
endpoint = 'http://192.168.2.223:5006/getActiveCasesAllComunasByState?state='+state
req_end = requests.get(endpoint)
data_ = json.loads(req_end.text)
data_2 = underreporting.loc[state].to_frame().T
active_nat =np.sum(pd.DataFrame(data_['data']), axis = 1)
under_nat = pd.DataFrame(data = {'low':data_2['low'][0], 'mean':data_2['mean'][0], 'high':data_2['high'][0]}, index = data_2['date'][0])#.drop(columns = 'date')
active_date_dt = pd.to_datetime(data_['dates'])
under_date_dt = pd.to_datetime(data_2['date'][0])
active_date_human = active_date_dt.strftime('%d/%m/%y')
under_date_human = under_date_dt.strftime('%d/%m/%y')
active_nat.index = active_date_human
under_nat.index = under_date_human
index = [i for i in active_date_human if i in under_date_human]
asp_data_mean = [active_nat[ind]/(1- under_nat['mean'][ind]) for ind in index]
asp_data_low = [active_nat[ind]/(1- under_nat['high'][ind]) for ind in index]
asp_data_high = [active_nat[ind]/(1- under_nat['low'][ind]) for ind in index]
return asp_data_mean, asp_data_low, asp_data_high, index
def __iso_handler(x): #overk
for i, item in enumerate(x.values):
s = item.split('T')
return s[0]
def color_epi(data14, data7,data1):
if data14 <= .8:
if data7 <= .8:
color = '#00cc66'
elif data7 >.8:
color = '#27AE60'
elif data14 < 1.00:
if data7 <= .8:
color = '#FFF333'
elif data7 < 1.00 and data1<1:
color = '#FFF333'
elif data7 < 1.00 and data1>=1 :
color = '#E3B500'
elif data7>=1:
color = '#E3B500'
else:
if data7 <= data14:
color = '#DE2F2A'
elif data7 > data14:
color = '#A71B08'
return color
def load_uci_data(slicing_date=None):
url = 'http://192.168.2.223:5006/getRegionalIcuBedOccupation'
endpoint = requests.get(url)
data = json.loads(endpoint.text)
regional_data = pd.DataFrame(data['data'])
regional_data_newest = pd.DataFrame(index = regional_data.index, columns = regional_data.columns)
regional_data_prev = pd.DataFrame(index = regional_data.index, columns = regional_data.columns)
indices = [-1, -8]
if slicing_date is not None:
regional_dates = data['dates']
formated = [s.split('T')[0] for s in regional_dates]
indices = [formated.index(slicing_date), formated.index(slicing_date)-7]
for i in range(1,17):
for index_name in regional_data.index:
regional_data_newest['{:02d}'.format(i)][index_name] = regional_data['{:02d}'.format(i)][index_name][indices[0]]
regional_data_prev['{:02d}'.format(i)][index_name] = regional_data['{:02d}'.format(i)][index_name][indices[0]]
order = ['15','01', '02', '03', '04', '05', '06', '07', '08', '16', '09', '14', '10', '11', '12', '13']
regional_data_prev = regional_data_prev.T
regional_data_newest = regional_data_newest.T
regional_data_prev = regional_data_prev.reindex(order)
regional_data_newest = regional_data_newest.reindex(order)
return regional_data_prev, regional_data_newest
def r_regions_db(slicing_date = None):
endpoint_R_region = requests.get('http://192.168.2.223:5006/getEffectiveReproductionAllStates' )
R_region = json.loads(endpoint_R_region.text)
R_region_data = pd.DataFrame(R_region['data']).T
dates = pd.DataFrame(R_region['dates'])
R_region_data['name']=R_region_data.index
R_region_data = R_region_data.set_index('name').apply(lambda x: x.apply(pd.Series).stack()).reset_index().drop('level_1', 1)
for i in range(4):
dates = pd.concat((dates, dates))
dates = pd.DataFrame(dates).apply(__iso_handler, axis = 1)
R_region_data['Fecha'] = dates.values
R_region_data = R_region_data.replace({'name': region_dict()})
R_region_data = R_region_data.rename(columns={'mean': 'MEAN','quantile0025': 'Low_95','quantile0975': 'High_95'})
if slicing_date is not None:
indices = []
start_slice_index = R_region_data.index[R_region_data['Fecha'] == "2020-04-07"].tolist()
end_slice_index = R_region_data.index[R_region_data['Fecha'] == slicing_date].tolist()
for i in range(len(start_slice_index)):
inter = range(start_slice_index[i], end_slice_index[i])
indices += inter
R_region_data = R_region_data.iloc[indices]
return R_region_data
def region_dict():
r_df =pd.read_json('http://192.168.2.223:5006/getStates')
r_df.index = r_df['id'].astype(str).apply(lambda x:x.zfill(2))
r_dict = r_df['name'].to_dict()
return r_dict
def r_comunas_db(slicing_date = None):
endpoint_R_comuna = requests.get('http://192.168.2.223:5006/getEffectiveReproductionAllComunas' )
R_comuna = json.loads(endpoint_R_comuna.text)
R_comuna_data = pd.DataFrame(R_comuna['data']).T
dates = pd.DataFrame(R_comuna['dates'])
R_comuna_data['comuna']=R_comuna_data.index
R_comuna_data = R_comuna_data.set_index('comuna').apply(lambda x: x.apply(pd.Series).stack()).reset_index().drop('level_1', 1)
c_df =pd.read_json('http://192.168.2.223:5006/getComunas')
c_df.index = c_df['county'].astype(str).apply(lambda x:x.zfill(5))
comunas_dict = c_df['county_name'].to_dict()
comunas_region_dict =c_df['state'].astype(str).apply(lambda x:x.zfill(2)).to_dict()
R_comuna_data['region'] = R_comuna_data['comuna']
R_comuna_data = R_comuna_data.replace({'region':comunas_region_dict})
R_comuna_data = R_comuna_data.replace({'region': region_dict(), 'comuna': comunas_dict})
n_comunas = int(R_comuna_data.shape[0]/dates.shape[0])
dates_f = dates.copy()
for n in range(n_comunas-1):
dates_f = pd.concat((dates_f, dates))
dates_f = pd.DataFrame(dates_f).apply(__iso_handler, axis = 1)
R_comuna_data['Fecha'] = dates_f.values
R_comuna_data = R_comuna_data.rename(columns={'mean': 'MEAN','quantile0025': 'Low_95','quantile0975': 'High_95'})
if slicing_date is not None:
indices = []
start_slice_index = R_comuna_data.index[R_comuna_data['Fecha'] == "2020-04-07"].tolist()
end_slice_index = R_comuna_data.index[R_comuna_data['Fecha'] == slicing_date].tolist()
for i in range(len(start_slice_index)):
inter = range(start_slice_index[i], end_slice_index[i])
indices += inter
R_comuna_data = R_comuna_data.iloc[indices]
return R_comuna_data
def r_national_db(slicing_date = None):
endpoint_R_national = requests.get('http://192.168.2.223:5006/getNationalEffectiveReproduction' )
R_national = pd.DataFrame(json.loads(endpoint_R_national.text))
R_national['Fecha'] = pd.DataFrame(R_national['dates']).apply(__iso_handler, axis = 1)
R_national = R_national.rename(columns={'mean': 'MEAN','quantile0025': 'Low_95','quantile0975': 'High_95'})
if slicing_date is not None:
slice_index = R_national.index[R_national['Fecha'] == slicing_date].tolist()[0]
R_national = R_national.iloc[:slice_index]
return R_national
def active_cases_from_db(slicing_date = None):
# not yet
endpoint = 'https://raw.githubusercontent.com/MinCiencia/Datos-COVID19/master/output/producto19/CasosActivosPorComuna_std.csv'
data_comunas = pd.read_csv(endpoint)
data_comunas = data_comunas.fillna(0)
data_comunas['Region'] = data_comunas['Region'].replace( region_names_dict)
if slicing_date is not None:
year, month, day = slicing_date.split('-')
weekday = dtime.datetime(int(year), int(month), int(day)).weekday()
if weekday>=0 and weekday<4: # nearest Tu
dif = weekday#-1
else:
dif = weekday-4
data_day = dtime.datetime(int(year), int(month), int(day)) - dtime.timedelta(days=dif)
slice_index = data_comunas.index[data_comunas['Fecha'] == data_day.strftime("%Y-%m-%d")].tolist()[0]
data_comunas = data_comunas.iloc[:slice_index]
return data_comunas
def deaths_comunas_from_db(slicing_date = None):
endpoint2 = 'https://raw.githubusercontent.com/MinCiencia/Datos-COVID19/master/output/producto38/CasosFallecidosPorComuna_std.csv'
muertos_comunas = pd.read_csv(endpoint2)
muertos_comunas = muertos_comunas.fillna(0)
muertos_comunas['Region'] = muertos_comunas['Region'].replace( region_names_dict)
if slicing_date is not None:
year, month, day = slicing_date.split('-')
weekday = dtime.datetime(int(year), int(month), int(day)).weekday()
if weekday>=0 and weekday<4: # nearest Tu
dif = weekday#-1
else:
dif = weekday-4
data_day = dtime.datetime(int(year), int(month), int(day)) - dtime.timedelta(days=dif)
slice_index = muertos_comunas.index[muertos_comunas['Fecha'] == data_day.strftime("%Y-%m-%d")].tolist()[0]
muertos_comunas = muertos_comunas.iloc[:slice_index]
muertos_comunas = muertos_comunas.drop(muertos_comunas[muertos_comunas.Comuna == 'Total'].index)
return muertos_comunas
def pcr_positivity_from_db(slicing_date = None):
endpoint2 = 'https://raw.githubusercontent.com/MinCiencia/Datos-COVID19/master/output/producto49/Positividad_Diaria_Media_T.csv'
pcr_positivity = pd.read_csv(endpoint2)
pcr_positivity = pcr_positivity.dropna(axis='index', how = 'any')
if slicing_date is not None:
year, month, day = slicing_date.split('-')
weekday = dtime.datetime(int(year), int(month), int(day)).weekday()
if weekday>=0 and weekday<4: # nearest Tu
dif = weekday#-1
else:
dif = weekday-4
data_day = dtime.datetime(int(year), int(month), int(day)) - dtime.timedelta(days=dif)
slice_index = np.where(pcr_positivity.Fecha == data_day.strftime("%Y-%m-%d"))[0][0]
pcr_positivity = pcr_positivity.iloc[:slice_index+1]
return pcr_positivity
def population_from_db():
pop =pd.read_json('http://192.168.2.223:5006/getComunas')
pop = pop[['state', 'state_name', 'county', 'county_name', 'province_name', 'male_pop', 'female_pop', 'total_pop']]
#counties_info.index = counties_info['county'].astype(str).apply(lambda x:x.zfill(5))
pop = pop.set_index('county_name')
pop_reg = pop.pivot_table(index='state_name', values=['total_pop', 'male_pop', 'female_pop'], aggfunc=sum)
return pop, pop_reg
def hospitales_reg():
#dict = {"01":"Tarapacá", "02":"Antofagasta", "03":"Atacama","04":"Coquimbo","05":"Valparaíso", "06":"O'Higgins","07":"Maule","08":"Biobío",
#"09":"La Araucanía","10":"Los Lagos","11":"Aysén", "12":"Magallanes","13","name":"Metropolitana", "14":"Los Ríos","15":"Arica","16":"Ñuble"]
#order = ['15','01', '02', '03', '04', '05', '06', '07', '08', '16', '09', '14', '10', '11', '12', '13']
dict_ss = {'Arica': 'SS ARICA',
'Tarapacá': ' SS IQUIQUE',
'Antofagasta': 'SS ANTOFAGASTA',
'Atacama': 'SS ATACAMA',
'Coquimbo': 'SS COQUIMBO',
'Valparaíso': 'SS ACONCAGUA',
'Valparaíso': 'SS VIÑA DEL MAR QUILLOTA',
'Valparaíso': 'SS VALPARAISO SAN ANTONIO',
"O'Higgins" : "SS LIBERTADOR B. O'HIGGINS ",
'Maule' : 'SS MAULE',
'Ñuble': 'SS ÑUBLE',
'Bio-Bío': 'SS BÍO BÍO',
'Bio-Bío' :'SS CONCEPCIÓN',
'Bio-Bío' :'SS TALCAHUANO',
'La Araucanía': 'SS ARAUCO',
'La Araucania' :'SS ARAUCANÍA NORTE',
'La Araucania' : 'SS ARAUCANÍA SUR',
'Los Ríos' : 'SS VALDIVIA',
'Los Lagos' :'SS OSORNO',
'Los Lagos' :'SS RELONCAVÍ',
'Los Lagos' : 'SS CHILOÉ',
'Aysén' : 'SS AYSÉN',
'Magallanes' : 'SS MAGALLANES',
'Metropolitana': 'SS METROPOLITANO NORTE',
'Metropolitana':'SS METROPOLITANO OCCIDENTE',
'Metropolitana':'SS METROPOLITANO CENTRAL',
'Metropolitana':'SS METROPOLITANO ORIENTE',
'Metropolitana':'SS METROPOLITANO SUR',
'Metropolitana':'SS METROPOLITANO SUR ORIENTE'
}
dict_ss = {'SS ARICA':'Arica',
'SS IQUIQUE':'Tarapacá',
'SS ANTOFAGASTA':'Antofagasta' ,
'SS ATACAMA' : 'Atacama',
'SS COQUIMBO': 'Coquimbo' ,
'SS ACONGAGUA': 'Valparaíso',
'SS VIÑA DEL MAR QUILLOTA': 'Valparaíso',
'SS VALPARAISO SAN ANTONIO': 'Valparaíso',
"SS LIBERTADOR B. O'HIGGINS" : "O'Higgins",
'SS DEL MAULE' : 'Maule',
'SS ÑUBLE' : 'Ñuble',
'SS BÍO BÍO' : 'Bio-Bío',
'SS CONCEPCIÓN' : 'Bio-Bío',
'SS TALCAHUANO':'Bio-Bío',
'SS ARAUCO' : 'La Araucanía',
'SS ARAUCANÍA NORTE' : 'La Araucanía',
'SS ARAUCANÍA SUR' : 'La Araucanía',
'SS VALDIVIA' : 'Los Ríos' ,
'SS OSORNO' : 'Los Lagos' ,
'SS DEL RELONCAVÍ' : 'Los Lagos',
'SS CHILOÉ' : 'Los Lagos' ,
'SS AISÉN' : 'Aysén' ,
'SS MAGALLANES' : 'Magallanes',
'SS METROPOLITANO NORTE': 'Metropolitana',
'SS METROPOLITANO OCCIDENTE' : 'Metropolitana',
'SS METROPOLITANO CENTRAL' : 'Metropolitana',
'SS METROPOLITANO ORIENTE' : 'Metropolitana',
'SS METROPOLITANO SUR' : 'Metropolitana',
'SS METROPOLITANO SUR ORIENTE' : 'Metropolitana'
}
endpoint_HEALTH_SERVICE = requests.get('http://192.168.2.223:5006/getDetailedBedsAndVentilationByHealthService' )
HEALTH_SERVICE = json.loads(endpoint_HEALTH_SERVICE.text)
HEALTH_SERVICE = pd.DataFrame(HEALTH_SERVICE['data'])
HEALTH_SERVICE.columns = HEALTH_SERVICE.loc['name']
HEALTH_SERVICE = HEALTH_SERVICE.transpose()
HEALTH_SERVICE.drop('name', axis =1, inplace = True)
HEALTH_SERVICE.drop('vmi_covid19_sospechosos', axis =1, inplace = True)
HEALTH_SERVICE.drop('vmi_covid19_confirmados', axis =1, inplace = True)
HEALTH_SERVICE_newest = pd.DataFrame(index =HEALTH_SERVICE.index , columns = HEALTH_SERVICE.columns)
HEALTH_SERVICE_prev = pd.DataFrame(index =HEALTH_SERVICE.index , columns = HEALTH_SERVICE.columns)
for i in HEALTH_SERVICE.columns:
for j in HEALTH_SERVICE.index:
HEALTH_SERVICE_newest.loc[j,i] = HEALTH_SERVICE.loc[j,i][-1]
HEALTH_SERVICE_prev.loc[j,i] = HEALTH_SERVICE.loc[j,i][-8]
HEALTH_SERVICE_newest['dates'] = pd.DataFrame(HEALTH_SERVICE_newest['dates']).apply(__iso_handler, axis=1)
HEALTH_SERVICE_prev['dates'] = pd.DataFrame(HEALTH_SERVICE_prev['dates']).apply(__iso_handler, axis=1)
columns_dict = {'camas_ocupadas_intensivo': 'Pacientes en Intensivo', 'camas_ocupadas_intermedio':'Pacientes en Intermedio',
'camas_totales_intensivo': 'Camas Intensivo', 'camas_totales_intermedio': 'Camas Intermedio',
'vmi_ocupados':'Pacientes en VMI','vmi_totales':'Número VMI'}
HEALTH_SERVICE_newest = HEALTH_SERVICE_newest.rename(columns = columns_dict)#, inplace = True)
HEALTH_SERVICE_prev = HEALTH_SERVICE_prev.rename(columns = columns_dict)#, inplace = True)
days = [HEALTH_SERVICE_prev['dates'][0], HEALTH_SERVICE_newest['dates'][0]]
HEALTH_SERVICE_prev.drop('dates', axis = 1, inplace = True)
HEALTH_SERVICE_newest.drop('dates', axis = 1, inplace = True)
HEALTH_SERVICE_prev = HEALTH_SERVICE_prev.rename(index = dict_ss)
HEALTH_SERVICE_prev = HEALTH_SERVICE_prev.groupby(HEALTH_SERVICE_prev.index).sum()
HEALTH_SERVICE_newest = HEALTH_SERVICE_newest.rename(index = dict_ss)
HEALTH_SERVICE_newest = HEALTH_SERVICE_newest.groupby(HEALTH_SERVICE_newest.index).sum()
for hs in HEALTH_SERVICE_prev.index:
if HEALTH_SERVICE_newest.loc[hs, 'Pacientes en VMI'] != 0 and HEALTH_SERVICE_newest.loc[hs,'Número VMI'] != 0:
HEALTH_SERVICE_newest.loc[hs, 'Uso VMI'] = HEALTH_SERVICE_newest.loc[hs,'Pacientes en VMI']/HEALTH_SERVICE_newest.loc[hs, 'Número VMI']
else:
HEALTH_SERVICE_newest.loc[hs, 'Uso VMI'] = 0
if HEALTH_SERVICE_newest.loc[hs, 'Camas Intermedio'] != 0 and HEALTH_SERVICE_newest.loc[hs,'Pacientes en Intermedio'] != 0:
HEALTH_SERVICE_newest.loc[hs, 'Uso Intermedias'] = HEALTH_SERVICE_newest.loc[hs,'Pacientes en Intermedio']/HEALTH_SERVICE_newest.loc[hs, 'Camas Intermedio']
else:
HEALTH_SERVICE_newest.loc[hs, 'Uso Intermedias'] = 0
if HEALTH_SERVICE_newest.loc[hs, 'Camas Intensivo'] != 0 and HEALTH_SERVICE_newest.loc[hs,'Pacientes en Intensivo'] != 0:
HEALTH_SERVICE_newest.loc[hs, 'Uso Intensivas'] = HEALTH_SERVICE_newest.loc[hs,'Pacientes en Intensivo']/HEALTH_SERVICE_newest.loc[hs, 'Camas Intensivo']
else:
HEALTH_SERVICE_newest.loc[hs, 'Uso Intensivas'] = 0
##
if HEALTH_SERVICE_prev.loc[hs, 'Pacientes en VMI'] != 0 and HEALTH_SERVICE_prev.loc[hs,'Número VMI'] != 0:
HEALTH_SERVICE_prev.loc[hs, 'Uso VMI'] = HEALTH_SERVICE_prev.loc[hs,'Pacientes en VMI']/HEALTH_SERVICE_prev.loc[hs, 'Número VMI']
else:
HEALTH_SERVICE_prev.loc[hs, 'Uso VMI'] = 0
if HEALTH_SERVICE_prev.loc[hs, 'Camas Intermedio'] != 0 and HEALTH_SERVICE_prev.loc[hs,'Pacientes en Intermedio'] != 0:
HEALTH_SERVICE_prev.loc[hs, 'Uso Intermedias'] = HEALTH_SERVICE_prev.loc[hs,'Pacientes en Intermedio']/HEALTH_SERVICE_prev.loc[hs, 'Camas Intermedio']
else:
HEALTH_SERVICE_prev.loc[hs, 'Uso Intermedias'] = 0
if HEALTH_SERVICE_prev.loc[hs, 'Camas Intensivo'] != 0 and HEALTH_SERVICE_prev.loc[hs,'Pacientes en Intensivo'] != 0:
HEALTH_SERVICE_prev.loc[hs, 'Uso Intensivas'] = HEALTH_SERVICE_prev.loc[hs,'Pacientes en Intensivo']/HEALTH_SERVICE_prev.loc[hs, 'Camas Intensivo']
else:
HEALTH_SERVICE_prev.loc[hs, 'Uso Intensivas'] = 0
summary_order = ["Arica","Tarapacá","Antofagasta","Atacama",
"Coquimbo","Valparaíso","O'Higgins","Maule",
"Ñuble","Bio-Bío","La Araucanía","Los Ríos",
"Los Lagos","Aysén","Magallanes","Metropolitana"]
HEALTH_SERVICE_prev = HEALTH_SERVICE_prev.reindex(summary_order)
HEALTH_SERVICE_newest = HEALTH_SERVICE_newest.reindex(summary_order)
global sochi_date, sochi_date2
sochi_date2, sochi_date = pd.to_datetime(days[0]).strftime("%d/%m"),pd.to_datetime(days[1]).strftime("%d/%m")
HEALTH_SERVICE_newest = HEALTH_SERVICE_newest.drop(columns = ['Pacientes en Intensivo', 'Pacientes en Intermedio', 'Camas Intensivo', 'Camas Intermedio', 'Pacientes en VMI', 'Número VMI' ])
HEALTH_SERVICE_prev = HEALTH_SERVICE_prev.drop(columns = ['Pacientes en Intensivo', 'Pacientes en Intermedio', 'Camas Intensivo', 'Camas Intermedio', 'Pacientes en VMI', 'Número VMI' ])
HEALTH_SERVICE_newest = HEALTH_SERVICE_newest[['Uso Intermedias','Uso Intensivas','Uso VMI']]
HEALTH_SERVICE_prev = HEALTH_SERVICE_prev[['Uso Intermedias','Uso Intensivas','Uso VMI']]
return days, HEALTH_SERVICE_prev, HEALTH_SERVICE_newest
def get_comunas_name():
comunas =pd.read_json('http://192.168.2.223:5006/getComunas')
comunas = comunas[['state', 'state_name', 'county', 'county_name', 'province_name', 'male_pop', 'female_pop', 'total_pop']]
comunas = comunas.set_index('county_name')
return comunas