-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodular_report.py
1582 lines (1374 loc) · 92.6 KB
/
modular_report.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
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import seaborn as sns
import numpy as np
import datetime as dt
import locale
from math import ceil
import gc
import os
from zipfile import ZipFile
#from report_utils import *
from report_data_loader import *
from matplotlib.backends.backend_pdf import PdfPages
# this_year = dt.date.today().year
# print(this_year)
class report(object):
"""docstring"""
def __init__(self, date):
super(report, self).__init__()
self.pages = []
self.predefined_types = ['national', 'state', 'summary', 'cover']
self.slicing_date = None
self.simulate_report = False
self.date = date
self.pdf = PdfPages('reporte_' + date + '.pdf')#formatear
self.logos = mpimg.imread('logos/uss_cinv_udd.png')
self.logo_sochimi = mpimg.imread('logos/logo_sochimi.png')
self.logo_fcv = mpimg.imread('logos/logos.png')
self.logofcv = mpimg.imread('logos/logo_fcv.png')
self.logofinis = mpimg.imread('logos/logo_finis.png')
def current_r_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)
r_day = date.strftime("%d/%m")
return date.date() , r_day
def current_report_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 = sdif)
report_day = data_day.strftime("%d/%m")
report_completeDate = data_day.strftime("%d/%m/%Y")
return data_day, report_day, report_completeDate
## PAGES
# PAGE 01
def add_cover(self, report_day, delta):
sns.set_context("paper", font_scale = 1)
figcover = plt.figure(edgecolor = 'k', figsize = (11, 8.5))
axlogos = figcover.add_axes([0.05, .77, .3*0.5, .3*0.5]) # [0.05,.7,.3,.3]
axsochi = figcover.add_axes([0.30, .8, .2*1.2, .085*1.2])
axfcv = figcover.add_axes([.8, .75, .15, .2])
axmain = figcover.add_axes([.0, .0, 1, .9])
axlogos.imshow(self.logos)
axsochi.imshow(self.logo_sochimi)
axfcv.imshow(self.logo_fcv[:, :1000])
axmain.axis('off')
axlogos.axis('off')
axsochi.axis('off')
axfcv.axis('off')
authors = r'César Ravello $^{1,2}$, Felipe Castillo $^{1,2}$, Samuel Ropert $^{1,2}$, Nicole Krumm $^{1}$, María José Pozo $^{1}$, Alejandro Bernardin $^{1}$, Tomás Pérez-Acle $^{1,2}$'
affiliations = '¹Computational Biology Lab, Centro BASAL Ciencia & Vida, Fundación Ciencia & Vida, Universidad San Sebastián\n²Facultad de Ingeniería y Tecnología, Universidad San Sebastián, Chile\n\nAgradecimientos: Proyecto CV19GM AFOSR grant number FA9550-20-1-0196'
axmain.text(.5,.7, 'Impacto de la pandemia Covid19 en Chile', ha = 'center', fontsize = 'xx-large')
axmain.text(.5,.6, 'Reporte al ' + report_day + '\nSemana epidemiológica {}'.format(ceil(delta.days/7)), ha = 'center', fontsize = 'xx-large')
axmain.text(.5,.25, authors, ha = 'center')
axmain.text(.5,.15, affiliations, ha = 'center', fontsize = 'small')
figcover.savefig(self.pdf, format = 'pdf', dpi = 600)
plt.savefig('cover.png', format = 'png', dpi = 600)
pass
# PAGE 21
def add_otras_provincias_page(self, report_day, pop, display, display_values, reg_display, reg_display_values, data, subrep, region_avg_rate,prevalencia_region, comun_per_region, muni_raw1, muni_raw2, weekly_prev1, weekly_prev2, R_arrow_past, R_arrow_last, death_rate1, death_rate2):
sns.set_context("paper", font_scale = .6)
every_nth = 21
fig = plt.figure(figsize = (11, 8.5))
fig.text(0.95,0.06, '©2020, Laboratorio de Biología Computacional, Fundación Ciencia & Vida', ha = 'right', fontsize = 'large')
ax_logo = fig.add_axes([.85, .875, .1, .1])
ax_logo.imshow(self.logofcv)
ax_logo.axis('off')
ax_cinv = fig.add_axes([-.03, .875, .25, .08])
ax_sochi = fig.add_axes([.775, .885, .07, .07])
ax_cinv.imshow(self.logos)
ax_sochi.imshow(self.logo_sochimi)
ax_cinv.axis('off')
ax_sochi.axis('off')
dates = pd.to_datetime(subrep['date']['Metropolitana de Santiago']).strftime('%d-%m-%y')
## Encabezado
region = 'Metropolitana de Santiago'
r = 15
mean = (1 - subrep['mean'][region][-1]) # reporte
if mean > 1: mean = 1
high = (1 - subrep['low'][region][-1])
low = (1 - subrep['high'][region][-1])
if low < 0: low = 0
high = (1 - subrep['low'][region][-1])
if high > 1 : high = 1
fig.text(.5, .935, 'Región Metropolitana: otras provincias', horizontalalignment = 'center', verticalalignment = 'center',\
weight = 'bold', fontsize = 'xx-large')
fig.text(.5, .9, 'Datos últimos 14 días\nPrevalencia región: {} / Tasa región: {}%\nEstimación de infectados sintomáticos detectados: {:.0f}% ({:.0f}% - {:.0f}%)'.format('{:.2f}'.format(prevalencia_region.loc[3, 'Metropolitana de Santiago']).replace('.',','), '{:.2f}'.format(region_avg_rate.loc[3,'Metropolitana de Santiago']*100).replace('.',','), mean*100, low*100, high*100),
horizontalalignment = 'center', verticalalignment = 'center', weight = 'bold', fontsize = 'x-large')
## Leyendas def regional_legend
fig.text(.187, .825, '1', fontsize = 'small')
fig.text(.2335, .825, '2', fontsize = 'small')
fig.text(.2775, .825, '3', fontsize = 'small')
fig.text(.3405, .825, '4', fontsize = 'small')
fig.text(.4225, .825, '5', fontsize = 'small')
fig.text(.4825, .825, '6', fontsize = 'small')
#fig.text(.5275, .825, '7', fontsize='small')
#fig.text(.5875, .825, '7', fontsize='small')
fig.text(.605, .27, 'Prevalencia \u2264 4', color = '#00cc66', horizontalalignment = 'left', verticalalignment = 'center', weight = 'bold')
fig.text(.605, .26, '4 < Prevalencia < 5', color = '#ffcc00', horizontalalignment = 'left', verticalalignment = 'center', weight = 'bold')
fig.text(.605, .25, 'Prevalencia \u2265 5', color = '#ff0000', horizontalalignment = 'left', verticalalignment = 'center', weight = 'bold')
fig.text(.705, .27, 'Tasa \u2264 25%', color = '#00cc66', horizontalalignment = 'left', verticalalignment = 'center', weight = 'bold')
fig.text(.705, .26, '25% < Tasa < 30%', color = '#ffcc00', horizontalalignment = 'left', verticalalignment = 'center', weight = 'bold')
fig.text(.705, .25, 'Tasa \u2265 30%', color = '#ff0000', horizontalalignment = 'left', verticalalignment = 'center', weight = 'bold')
fig.text(.805, .27, 'R_e \u2264 0,8', color = '#00cc66', horizontalalignment = 'left', verticalalignment = 'center', weight = 'bold')
fig.text(.805, .26, '0,8 < R_e < 1,0', color = '#ffcc00', horizontalalignment = 'left', verticalalignment = 'center', weight = 'bold')
fig.text(.805, .25, 'R_e \u2265 1,0', color = '#ff0000', horizontalalignment = 'left', verticalalignment = 'center', weight = 'bold')
fig.text(0.605,0.06,
'1 Infectados activos / 10.000 habitantes.\n'+
'2 Tasa diaria de nuevos infectados (promedio acumulado).\n'+
'3 R_e últimos 14 días según Cori et al. (2019)\n'
'4 Datos epidemiológicos\nhttps://github.com/MinCiencia/Datos-COVID19\n'+
'5 De acuerdo a subreporte según\nhttps://cmmid.github.io/topics/covid19/global_cfr_estimates.html\n'+
'6 Fallecimientos acumulados COVID19 / 100.000 habitantes\n'+
#'7 Datos movilidad '+im_dates+' vs. 09/03-15/03.\n'+
# 'https://github.com/MinCiencia/Datos-COVID19, producto 33.\n'+
'7 Datos regionales incluyen casos de comuna desconocida\n'+'\n'+
'- ND no hay suficientes datos para calcular R_e.\n'+
#'- Uso de camas por Servicio de Salud al ' + sochi_date + ' según SOCHIMI.\n'+
'- Flechas R_e: cambio mayor/menor a 5% vs ultimos 7 días.\n'+
'- Otras flechas: cambio mayor/menor a 5% vs semana anterior.\n'
, ha = 'left', fontsize = 'large')
ax = fig.add_axes([.125, .01, .475, .84])
selection = pop[(pop['state_name'] == 'Metropolitana de Santiago') & (pop['province_name']!='Santiago')].index.values
#make_table(display.loc[selection], display_values.loc[selection], ax, True)
self._make_table(display.loc[selection], display_values.loc[selection],
reg_display[reg_display.index == region].rename(index = {region: 'VALOR REGIONAL ⁷'}), reg_display_values[reg_display.index == region], ax, True)
self._add_arrows(display_values.loc[selection], muni_raw1, muni_raw2, weekly_prev1, weekly_prev2, R_arrow_past, R_arrow_last, death_rate1,death_rate2, ax, 0.49, .935, .18, .06, .29, .68, .905, .0315, .0205)
#fig.text(.12, .85, 'Región de ' + regiones[r], horizontalalignment='left', verticalalignment='center', weight = 'bold')
ax2 = fig.add_axes([.645, .625, .3, .22])#.645, .595, .3, .22])
comuna = regiones_short[r]
comuna = region
ax2.plot(data[data.name==comuna]['MEAN'][1:])
ax2.fill_between(data[data.name==comuna].index[1:],
data[data.name==comuna]['Low_95'][1:], data[data.name==comuna]['High_95'][1:], alpha=.4)
ax2.hlines(data[data.name==comuna]['MEAN'][-14:].mean(), data[data.name==comuna].iloc[-14].name,data[data.name==comuna].iloc[-1].name, color='C4')
ax2.hlines(data[data.name==comuna]['MEAN'][-7:].mean(), data[data.name==comuna].iloc[-7].name,data[data.name==comuna].iloc[-1].name, color='C2')
ax2.hlines(1, data[data.name==comuna].iloc[1].name,data[data.name==comuna].iloc[-1].name, ls='--',color='k')
ax2.annotate('R_e 14d = {:.2f}'.format(data[data.name==comuna]['MEAN'][-14:].mean()), (.75,.7), color='C4',xycoords='axes fraction')
ax2.annotate('R_e 7d = {:.2f}'.format(data[data.name==comuna]['MEAN'][-7:].mean()), (.75,.65), color='C2',xycoords='axes fraction')
ax2.annotate('R_e inst. = {:.2f}'.format(data[data.name==comuna]['MEAN'][-1]), (.75,.60), color='k',xycoords='axes fraction')
matplotlib.pyplot.sca(ax2)
r_dates = pd.to_datetime(data.index[1:])
ticks_labels = [r_dates[i].strftime("%d-%m-%y") for i in range(len(r_dates))]
ax2.tick_params(axis='x',rotation=45, bottom=False, left=True, labelleft=True, labelbottom=True)
ax2.set_xticklabels(ticks_labels)#, fontdict = {'fontsize' : '8'})
#plt.xticks(rotation=45)
#ax2.tick_params(bottom=False, left=True, labelleft=True, labelbottom=True)
for n, label in enumerate(ax2.xaxis.get_ticklabels()):
if n % every_nth != 0:
label.set_visible(False)
ax2.set_ylabel('R efectivo')
ax2.set_ylim([0,3])
ax3 = fig.add_axes([.645, .335, .3, .22])
ax3.plot(dates, np.asarray(subrep['mean'][region])*100)
ax3.fill_between(dates, np.asarray(subrep['low'][region])*100, np.asarray(subrep['high'][region])*100, alpha=0.4)
ax3.set_ylim([0,100])
ax3.set_ylabel('% Subreporte')
ax3.tick_params(axis = 'x', rotation=45)
ax3.tick_params(bottom=False, left=True, labelleft=True, labelbottom=True)
color = 'purple'
m, l, h, i = asp_state(region, subrep)
pos = []
for j, ind in enumerate(i):
pos +=[dates.get_loc(ind)]
ax2 = ax3.twinx()
ax2.set_ylabel('Infectados sintomáticos activos probables', color='black', fontsize = 7)
p2, = ax2.plot(pos,m,color=color)
ax2.tick_params(axis='y', labelcolor='black')
ax2.set_ylim(bottom =0)
for n, label in enumerate(ax3.xaxis.get_ticklabels()):
if n % every_nth != 0:
label.set_visible(False)
fig.savefig(self.pdf, format='pdf', dpi=1200)
plt.savefig('otras_provincias.png', format = 'png', dpi = 600)
pass
# FOR TABLES
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 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
def color_dim(data):#23, 41, 58
if data <= .3: color = '#00cc66'
elif data < .4: color = '#ffcc00'
else: color = '#ff0000'
return color
# PAGE ???
def add_regiones_page(self, report_day, pop, display, display_values, reg_display, reg_display_values, data, subrep, region_avg_rate,prevalencia_region, comun_per_region, muni_raw1, muni_raw2 ,weekly_prev1, weekly_prev2, R_arrow_past,R_arrow_last,death_rate1,death_rate2):
sns.set_context("paper", font_scale=.6)
every_nth = 21
filenames = []
######## Arica # Tarapa Antofag Atacama Coquimb Valpo # Liberta Maule # Ñuble # Biobio Arauca Ríos ## Lagos # Aisen # Maga
heights=[.1, .35, .45, .45, .50, .84, .84, .84, .84, .84, .84, .30, .84, .30, .30, .8]
pos_x = [.175, .175, .175, .58, .58, .175, .58, .175, .58, .175, .58, .175, .58, .175, .175, .40]
pos_y = [.73, .55, .55, .39, .10, .01, .01, .01, .01, .01, .01, .5375, .01, .25, .01, .01]
y_text = [.85, .705, .505, .85, .60, .85, .85, .85, .85, .85, .85, .85, .85, .56, .315, .85]
labels = [True, True, True, True, True, True, True, True, True, True, True, True, True, True]
########### Valores para dibujar flechas
########### l_lim, h_lim, x_t, x_p, x_m, dx, dy lower limit, high limit pos x tasa, pos x prevalencia,
arrow_props = [
[0.865, .935, .18, .06, .29,.68,.905,.0325, .0215], #Arica
[0.795, .935, .18, .06, .29,.68,.905,.0325, .0215], #Tarapacá
[0.7475, .935, .18, .06, .29,.68,.905,.0325, .0215], #Antofagasta
[0.7475, .935, .18, .06, .29,.68,.905,.0325, .0215], #Atacama
[0.6075, .935, .18, .06, .29,.68,.905,.0325, .0215], #Coquimbo
[0.0715, .935, .18, .06, .29,.68,.905,.0325, .0215], #Valparaíso
[0.1875, .935, .18, .06, .29,.68,.905,.0325, .0215], #Libertador
[0.2575, .935, .18, .06, .29,.68,.905,.0325, .0215], #Maule
[0.4675, .935, .18, .06, .29,.68,.905,.0325, .0215], #Ñuble
[0.1875, .935, .18, .06, .29,.68,.905,.0325, .0215], #Biobio
[0.2100, .935, .18, .06, .29,.68,.905,.0325, .0215], #Araucanía
[0.6775, .935, .18, .06, .29,.68,.905,.0325, .0215], #Los Ríos
[0.2575, .935, .18, .06, .29,.68,.905,.0325, .0215], #Los Lagos
[0.7270, .935, .18, .06, .29,.68,.905,.0325, .0215], #Aisén
[0.6985, .935, .18, .06, .29,.68,.905,.0325, .0215], #Magallanes
[0.050, .9, .235, .055, .29,.68 ,.015, .0215], #Metropolitana
]
## Encabezados, pies de página y leyendas
underreporting = underreporting_by_region()
dict = {"01":"Tarapacá", "02":"Antofagasta",
"03":"Atacama", "04":"Coquimbo",
"05":"Valparaíso", "06":"Libertador General Bernardo O\'Higgins",
"07":"Maule", "08":"Biobío",
"09":"La Araucanía","10":"Los Lagos",
"11":"Aysén del General Carlos Ibáñez del Campo",
"12":"Magallanes y de la Antártica Chilena",
"13":"Metropolitana", "14":"Los Ríos",
"15":"Arica y Parinacota","16":"Ñuble"}
inv_map = {v: k for k, v in dict.items()}
for r, region in enumerate(regiones[:-1]):
fig = plt.figure(figsize=(11, 8.5))
## Logos
fig.text(0.95,0.06, '©2020, Laboratorio de Biología Computacional, Fundación Ciencia & Vida', ha='right', fontsize='large')
ax_logo = fig.add_axes([.85,.875,.1,.1])
ax_logo.imshow(self.logofcv)
ax_logo.axis('off')
ax_cinv = fig.add_axes([-.03,.875,.25,.08])
ax_sochi = fig.add_axes([.775,.885,.07,.07])
ax_cinv.imshow(self.logos)
ax_sochi.imshow(self.logo_sochimi)
ax_cinv.axis('off')
ax_sochi.axis('off')
## Encabezado
fig.text(.5, .935, 'Región de ' + regiones[r], horizontalalignment='center', verticalalignment='center', weight = 'bold', fontsize='xx-large')
if region in subrep.index and region != "Aysén del General Carlos Ibáñez del Campo":
reg_num = inv_map[region]
dates = pd.to_datetime(underreporting.loc[reg_num]['date']).strftime('%d-%m-%y')
mean = (1-underreporting.loc[reg_num]['mean'][-1]) #reporte
if mean>1: mean = 1
low = (1-underreporting.loc[reg_num]['high'][-1]) #estan al revés
if low <0: low = 0
high = (1-underreporting.loc[reg_num]['low'][-1])
if high > 1: high = 1
fig.text(.5, .9, 'Datos últimos 14 días\nPrevalencia región: {} / Tasa región: {}%\nEstimación de infectados sintomáticos detectados: {:.0f}% ({:.0f}% - {:.0f}%)'.format('{:.2f}'.format(prevalencia_region.loc[3,region]).replace('.',','), '{:.2f}'.format(region_avg_rate.loc[3,region]*100).replace('.',','), mean*100, low*100, high*100),
horizontalalignment='center', verticalalignment='center', weight = 'bold', fontsize='x-large')
else:
fig.text(.5, .9, 'Datos últimos 14 días\nPrevalencia región: {} / Tasa región: {}%\nEstimación de infectados sintomáticos detectados: ND'.format('{:.2f}'.format(prevalencia_region.loc[3,region]).replace('.',','), '{:.2f}'.format(region_avg_rate.loc[3,region]*100).replace('.',',')),
horizontalalignment='center', verticalalignment='center', weight = 'bold', fontsize='x-large')
## Leyendas
fig.text(.187, .825, '1', fontsize='small')
fig.text(.2335, .825, '2', fontsize='small')
fig.text(.2775, .825, '3', fontsize='small')
fig.text(.3405, .825, '4', fontsize='small')
fig.text(.4225, .825, '5', fontsize='small')
fig.text(.4825, .825, '6', fontsize='small')
#fig.text(.5275, .825, '7', fontsize='small')
#fig.text(.5875, .825, '7', fontsize='small') 605, 52 51 50 - - 47...
fig.text(.605, .27, 'Prevalencia \u2264 4', color='#00cc66', horizontalalignment='left', verticalalignment='center', weight = 'bold')
fig.text(.605, .26, '4 < Prevalencia < 5', color='#ffcc00', horizontalalignment='left', verticalalignment='center', weight = 'bold')
fig.text(.605, .25, 'Prevalencia \u2265 5', color='#ff0000', horizontalalignment='left', verticalalignment='center', weight = 'bold')
fig.text(.705, .27, 'Tasa \u2264 25%', color='#00cc66', horizontalalignment='left', verticalalignment='center', weight = 'bold')
fig.text(.705, .26, '25% < Tasa < 30%', color='#ffcc00', horizontalalignment='left', verticalalignment='center', weight = 'bold')
fig.text(.705, .25, 'Tasa \u2265 30%', color='#ff0000', horizontalalignment='left', verticalalignment='center', weight = 'bold')
fig.text(.805, .27, 'R_e \u2264 0,8', color='#00cc66', horizontalalignment='left', verticalalignment='center', weight = 'bold')
fig.text(.805, .26, '0,8 < R_e < 1,0', color='#ffcc00', horizontalalignment='left', verticalalignment='center', weight = 'bold')
fig.text(.805, .25, 'R_e \u2265 1,0', color='#ff0000', horizontalalignment='left', verticalalignment='center', weight = 'bold')
#fig.text(.705, .23, 'Movilidad remanente \u2264 30%', color='#00cc66', horizontalalignment='left', verticalalignment='center', weight = 'bold')
#fig.text(.705, .22, '30% < Movilidad remanente < 40%', color='#ffcc00', horizontalalignment='left', verticalalignment='center', weight = 'bold')
#fig.text(.705, .21, 'Movilidad remanente \u2265 40%', color='#ff0000', horizontalalignment='left', verticalalignment='center', weight = 'bold')
fig.text(0.605,0.06,
'1 Infectados activos / 10.000 habitantes.\n'+
'2 Tasa diaria de nuevos infectados (promedio acumulado).\n'+
'3 R_e últimos 14 días según Cori et al. (2019)\n'
'4 Datos epidemiológicos\nhttps://github.com/MinCiencia/Datos-COVID19\n'+
'5 De acuerdo a subreporte según\nhttps://cmmid.github.io/topics/covid19/global_cfr_estimates.html\n'+
'6 Fallecimientos acumulados COVID19 / 100.000 habitantes\n'+
#'7 Datos movilidad '+im_dates+' vs. 09/03-15/03.\n'+
# 'https://github.com/MinCiencia/Datos-COVID19, producto 33.\n'
'7 Datos regionales incluyen casos de comuna desconocida\n'+'\n'+
'- ND no hay suficientes datos para calcular R_e.\n'+
#'- Uso de camas por Servicio de Salud al ' + sochi_date + ' según SOCHIMI.\n'+
'- Flechas R_e: cambio mayor/menor a 5% vs ultimos 7 días.\n'+
'- Otras flechas: cambio mayor/menor a 5% vs semana anterior.\n'
, ha='left',fontsize='large')#'x-large')
ax = fig.add_axes([.125, .01, .475, .84])
selection = comun_per_region[comun_per_region == region].index
self._make_table(display.loc[selection], display_values.loc[selection],
reg_display[reg_display.index==region].rename(index={region:'VALOR REGIONAL ⁷'}), reg_display_values[reg_display.index==region], ax, True)
self._add_arrows(display_values.loc[selection], muni_raw1, muni_raw2 ,weekly_prev1, weekly_prev2, R_arrow_past,R_arrow_last,death_rate1,death_rate2, ax, *arrow_props[r])
ax2 = fig.add_axes([.645, .625, .3, .22])
# comuna = regiones_short[r]
comuna = region
ax2.plot(data[data.name==comuna]['MEAN'][1:])
ax2.fill_between(data[data.name==comuna].index[1:],
data[data.name==comuna]['Low_95'][1:], data[data.name==comuna]['High_95'][1:], alpha=.4)
ax2.hlines(data[data.name==comuna]['MEAN'][-14:].mean(), data[data.name==comuna].iloc[-14].name,data[data.name==comuna].iloc[-1].name, color='C4')
ax2.hlines(data[data.name==comuna]['MEAN'][-7:].mean(), data[data.name==comuna].iloc[-7].name,data[data.name==comuna].iloc[-1].name, color='C2')
ax2.hlines(1, data[data.name==comuna].iloc[1].name,data[data.name==comuna].iloc[-1].name, ls='--',color='k')
ax2.annotate('R_e 14d = {:.2f}'.format(data[data.name==comuna]['MEAN'][-14:].mean()), (.75,.7), color='C4',xycoords='axes fraction')
ax2.annotate('R_e 7d = {:.2f}'.format(data[data.name==comuna]['MEAN'][-7:].mean()), (.75,.65), color='C2',xycoords='axes fraction')
ax2.annotate('R_e inst. = {:.2f}'.format(data[data.name==comuna]['MEAN'][-1]), (.75,.60), color='k',xycoords='axes fraction')
matplotlib.pyplot.sca(ax2)
r_dates = pd.to_datetime(data.index[1:])
ticks_labels = [r_dates[i].strftime("%d-%m-%y") for i in range(len(r_dates))]
ax2.tick_params(axis='x',rotation=45, bottom=False, left=True, labelleft=True, labelbottom=True)
ax2.set_xticklabels(ticks_labels)#, fontdict = {'fontsize' : '8'})
plt.xticks(rotation=45)
ax2.tick_params(bottom=False, left=True, labelleft=True, labelbottom=True)
for n, label in enumerate(ax2.xaxis.get_ticklabels()):
if n % every_nth != 0:
label.set_visible(False)
ax2.set_ylabel('R efectivo')
ax2.set_ylim([0,3])
# if data != None
if region in subrep.index and region !="Aysén del General Carlos Ibáñez del Campo":
ax3 = fig.add_axes([.645, .335, .3, .22])
ax3.plot(dates,np.asarray(underreporting.loc[reg_num]['mean'])*100)
ax3.fill_between(dates,np.asarray(underreporting.loc[reg_num]['low'])*100,np.asarray(underreporting.loc[reg_num]['high'])*100, alpha=0.4)
ax3.tick_params(axis = 'x', rotation=45)
ax3.set_ylim([0,100])
ax3.set_ylabel('% Subreporte')
ax3.tick_params(bottom=False, left=True, labelleft=True, labelbottom=True)
color = 'purple'
m, l, h, i = asp_state(region, subrep)
pos = []
for j, ind in enumerate(i):
pos +=[dates.get_loc(ind)]
ax2 = ax3.twinx()
ax2.set_ylabel('Infectados sintomáticos activos probables', color='black', fontsize = 7)
p2, = ax2.plot(pos,m,color=color)
ax2.tick_params(axis='y', labelcolor='black')
ax2.set_ylim(bottom =0)
for n, label in enumerate(ax3.xaxis.get_ticklabels()):
if n % every_nth != 0:
label.set_visible(False)
filename = 'Report/Report_{}_RP{}.pdf'.format(report_day.replace('/','_'), r)
fig.savefig(self.pdf, format='pdf', dpi=1200)
plt.savefig('region'+region+'.png', format = 'png', dpi = 600)
pass
# PAGE 20
def add_metropolitana_page(self, report_day, pop, display, display_values, reg_display, reg_display_values, data, subrep, region_avg_rate,prevalencia_region, comun_per_region, muni_raw1, muni_raw2 ,weekly_prev1, weekly_prev2, R_arrow_past,R_arrow_last,death_rate1,death_rate2):
sns.set_context("paper", font_scale=.6)
logos = mpimg.imread('logos/uss_cinv_udd.png')
logo_sochimi = mpimg.imread('logos/logo_sochimi.png')
logo_fcv = mpimg.imread('logos/logos.png')
logofcv = mpimg.imread('logos/logo_fcv.png')
logofinis= mpimg.imread('logos/logo_finis.png')
every_nth = 21
dates = pd.to_datetime(subrep['date']['Metropolitana de Santiago']).strftime('%d/%m/%y')
## Encabezados, pies de página y leyendas
fig = plt.figure(figsize=(11, 8.5))
## Logos
fig.text(0.95,0.06, '©2020, Laboratorio de Biología Computacional, Fundación Ciencia & Vida', ha='right', fontsize='large')
ax_logo = fig.add_axes([.85,.875,.1,.1])
ax_logo.imshow(self.logofcv)
ax_logo.axis('off')
ax_cinv = fig.add_axes([-.03,.875,.25,.08])
ax_sochi = fig.add_axes([.775,.885,.07,.07])
ax_cinv.imshow(self.logos)
ax_sochi.imshow(self.logo_sochimi)
ax_cinv.axis('off')
ax_sochi.axis('off')
## Encabezado
region = 'Metropolitana de Santiago'
r = 15
mean = (1-subrep['mean']['Metropolitana de Santiago'][-1]) # reporte
if mean>1: mean = 1
low = (1-subrep['high']['Metropolitana de Santiago'][-1])
if low<0: low = 0
high = (1-subrep['low']['Metropolitana de Santiago'][-1])
if high > 1 : high = 1
fig.text(.5, .935, 'Región Metropolitana: Provincia de Santiago', horizontalalignment='center', verticalalignment='center', weight = 'bold', fontsize='xx-large')
fig.text(.5, .9, 'Datos últimos 14 días\nPrevalencia región: {} / Tasa región: {}%\nEstimación de infectados sintomáticos detectados: {:.0f}% ({:.0f}% - {:.0f}%)'.format('{:.2f}'.format(prevalencia_region.loc[3,'Metropolitana de Santiago']).replace('.',','), '{:.2f}'.format(region_avg_rate.loc[3,'Metropolitana de Santiago']*100).replace('.',','), mean*100,low*100,high*100),
horizontalalignment='center', verticalalignment='center', weight = 'bold', fontsize='x-large')
## Leyendas
fig.text(.187, .825, '1', fontsize='small')
fig.text(.2335, .825, '2', fontsize='small')
fig.text(.2775, .825, '3', fontsize='small')
fig.text(.3405, .825, '4', fontsize='small')
fig.text(.4225, .825, '5', fontsize='small')
fig.text(.4825, .825, '6', fontsize='small')
#fig.text(.5275, .825, '7', fontsize='small')
#fig.text(.5875, .825, '7', fontsize='small')
fig.text(.605, .27, 'Prevalencia \u2264 4', color='#00cc66', horizontalalignment='left', verticalalignment='center', weight = 'bold')
fig.text(.605, .26, '4 < Prevalencia < 5', color='#ffcc00', horizontalalignment='left', verticalalignment='center', weight = 'bold')
fig.text(.605, .25, 'Prevalencia \u2265 5', color='#ff0000', horizontalalignment='left', verticalalignment='center', weight = 'bold')
fig.text(.705, .27, 'Tasa \u2264 25%', color='#00cc66', horizontalalignment='left', verticalalignment='center', weight = 'bold')
fig.text(.705, .26, '25% < Tasa < 30%', color='#ffcc00', horizontalalignment='left', verticalalignment='center', weight = 'bold')
fig.text(.705, .25, 'Tasa \u2265 30%', color='#ff0000', horizontalalignment='left', verticalalignment='center', weight = 'bold')
fig.text(.805, .27, 'R_e \u2264 0,8', color='#00cc66', horizontalalignment='left', verticalalignment='center', weight = 'bold')
fig.text(.805, .26, '0,8 < R_e < 1,0', color='#ffcc00', horizontalalignment='left', verticalalignment='center', weight = 'bold')
fig.text(.805, .25, 'R_e \u2265 1,0', color='#ff0000', horizontalalignment='left', verticalalignment='center', weight = 'bold')
#fig.text(.605, .37, 'Movilidad remanente \u2264 30%', color='#00cc66', horizontalalignment='left', verticalalignment='center', weight = 'bold')
#fig.text(.605, .36, '30% < Movilidad remanente < 40%', color='#ffcc00', horizontalalignment='left', verticalalignment='center', weight = 'bold')
#fig.text(.605, .35, 'Movilidad remanente \u2265 40%', color='#ff0000', horizontalalignment='left', verticalalignment='center', weight = 'bold')
fig.text(0.605,0.06,
'1 Infectados activos / 10.000 habitantes.\n'+
'2 Tasa diaria de nuevos infectados (promedio acumulado).\n'+
'3 R_e últimos 14 días según Cori et al. (2019)\n'
'4 Datos epidemiológicos\nhttps://github.com/MinCiencia/Datos-COVID19\n'+
'5 De acuerdo a subreporte según\nhttps://cmmid.github.io/topics/covid19/global_cfr_estimates.html\n'+
'6 Fallecimientos acumulados COVID19 / 100.000 habitantes\n'+
#'7 Datos movilidad '+im_dates+' vs. 09/03-15/03.\n'+
# 'https://github.com/MinCiencia/Datos-COVID19, producto 33.\n'+
'7 Datos regionales incluyen casos de comuna desconocida\n'+'\n'+
'- ND no hay suficientes datos para calcular R_e.\n'+
#'- Uso de camas por Servicio de Salud al ' + sochi_date + ' según SOCHIMI.\n'+
'- Flechas R_e: cambio mayor/menor a 5% vs ultimos 7 días.\n'+
'- Otras flechas: cambio mayor/menor a 5% vs semana anterior.\n'
, ha='left',fontsize='large')
ax = fig.add_axes([.125, .01, .475, .84])
selection = pop[pop['province_name']=='Santiago'].index.values
self._make_table(display.loc[selection], display_values.loc[selection],
reg_display[reg_display.index==region].rename(index={region:'VALOR REGIONAL ⁷'}), reg_display_values[reg_display.index==region], ax, True)
self._add_arrows(display_values.loc[selection], muni_raw1, muni_raw2 ,weekly_prev1, weekly_prev2, R_arrow_past,R_arrow_last,death_rate1,death_rate2, ax, 0.21, .935, .18, .06, .29,.68,.905,.0315, .0205)
ax2 = fig.add_axes([.645, .625, .3, .22])#.645, .595, .3, .22])
comuna = regiones_short[r]
comuna = region
ax2.plot(data[data.name==comuna]['MEAN'][1:])
ax2.fill_between(data[data.name==comuna].index[1:],
data[data.name==comuna]['Low_95'][1:], data[data.name==comuna]['High_95'][1:], alpha=.4)
ax2.hlines(data[data.name==comuna]['MEAN'][-14:].mean(), data[data.name==comuna].iloc[-14].name,data[data.name==comuna].iloc[-1].name, color='C4')
ax2.hlines(data[data.name==comuna]['MEAN'][-7:].mean(), data[data.name==comuna].iloc[-7].name,data[data.name==comuna].iloc[-1].name, color='C2')
ax2.hlines(1, data[data.name==comuna].iloc[1].name,data[data.name==comuna].iloc[-1].name, ls='--',color='k')
ax2.annotate('R_e 14d = {:.2f}'.format(data[data.name==comuna]['MEAN'][-14:].mean()), (.75,.7), color='C4',xycoords='axes fraction')
ax2.annotate('R_e 7d = {:.2f}'.format(data[data.name==comuna]['MEAN'][-7:].mean()), (.75,.65), color='C2',xycoords='axes fraction')
ax2.annotate('R_e inst. = {:.2f}'.format(data[data.name==comuna]['MEAN'][-1]), (.75,.60), color='k',xycoords='axes fraction')
matplotlib.pyplot.sca(ax2)
plt.xticks(rotation=45)
ax2.tick_params(bottom=False, left=True, labelleft=True, labelbottom=True)
for n, label in enumerate(ax2.xaxis.get_ticklabels()):
if n % every_nth != 0:
label.set_visible(False)
ax2.set_ylabel('R efectivo')
ax2.set_ylim([0,3])
ax3 = fig.add_axes([.645, .335, .3, .22])
ax3.plot(dates,np.asarray(subrep['mean']['Metropolitana de Santiago'])*100)
ax3.fill_between(dates, np.asarray(subrep['low']['Metropolitana de Santiago'])*100, np.asarray(subrep['high']['Metropolitana de Santiago'])*100, alpha=0.4)
ax3.tick_params(axis = 'x', rotation=45)
ax3.set_ylim([0,100])
ax3.set_ylabel('% Subreporte')
ax3.tick_params(bottom=False, left=True, labelleft=True, labelbottom=True)
color = 'purple'
m, l, h, i = asp_state(region, subrep)
pos = []
for j, ind in enumerate(i):
pos +=[dates.get_loc(ind)]
ax2 = ax3.twinx()
ax2.set_ylabel('Infectados sintomáticos activos probables', color='black', fontsize = 7)
p2, = ax2.plot(pos,m,color=color)
ax2.tick_params(axis='y', labelcolor='black')
ax2.set_ylim(bottom =0)
for n, label in enumerate(ax3.xaxis.get_ticklabels()):
if n % every_nth != 0:
label.set_visible(False)
filename = 'Report/Report_{}_RP{}.pdf'.format(report_day.replace('/','_'), r)
fig.savefig(self.pdf, format='pdf', dpi=1200)
plt.savefig('metropolitana.png', format = 'png', dpi = 600)
pass
# PAGE 04
# def add_underreporting_page(self, national_underrep, report_day, slice_date):
def add_underreporting_page(self, national_underrep, report_day, slice_date, activos, chile_prvlnc, chile_avg_rate):
logos = mpimg.imread('logos/uss_cinv_udd.png')
logo_sochimi = mpimg.imread('logos/logo_sochimi.png')
logo_fcv = mpimg.imread('logos/logos.png')
logofcv = mpimg.imread('logos/logo_fcv.png')
logofinis= mpimg.imread('logos/logo_finis.png')
sns.set_context("paper", font_scale=.6)
#fig, axs = plt.subplots(6,1,figsize=(8.5, 13), gridspec_kw={'height_ratios': [0.5,15,0.1, 0.5,15,4.5]})
fig, axs = plt.subplots(7,1,figsize=(8.5, 13), gridspec_kw={'height_ratios': [0.5,0.5,15,2, 2,15,4.5]})
fig.text(0.9,0.04, '©2020, Laboratorio de Biología Computacional, Fundación Ciencia & Vida', ha='right')
#logo fund ciencia y vida
ax_logo = fig.add_axes([.8,.868,.1*1.2,.1*1.2])
ax_logo.imshow(self.logofcv)
ax_logo.axis('off')
# ax_cinv logos -> uss
ax_cinv = fig.add_axes([.05,.89,.25*0.7,.08*0.7])
ax_sochi = fig.add_axes([.74,.9,.05*1.2,.05*1.2])
ax_cinv.imshow(self.logos)
ax_sochi.imshow(self.logo_sochimi)
ax_cinv.axis('off')
ax_sochi.axis('off')
probables = (1-national_underrep['mean'][-1])
if probables<0: probables = 0
if probables>1: probables = 1
probables_bajo =(1 - national_underrep['low'][-1])
if probables_bajo <0: probables_bajo = 0
probables_alto = (1 - national_underrep['high'][-1])
if probables_alto>1: probables_alto = 1
activos = int(activos)
# fig.text(.5, .88, 'Trayectoria de subreporte a nivel nacional', horizontalalignment='center', verticalalignment='center', weight = 'bold', fontsize='x-large')
fig.text(.5, .9, 'Trayectoria de subreporte a nivel nacional\nPrevalencia País: {} / Tasa país: {}%\nEstimación de infectados sintomáticos detectados: {}% ({}% - {}%)\nInfectados activos: {} / Inf. Act. Probables: {} ~ {}'.format('{:.2f}'.format(chile_prvlnc.T.values[-1][0]).replace('.',','), '{:.2f}'.format(chile_avg_rate.values[-1]*100).replace('.',','), '{:.2f}'.format(probables*100).replace('.',','), '{:.2f}'.format(probables_bajo*100).replace('.',','), '{:.2f}'.format(probables_alto*100).replace('.',',') , '{:,}'.format(activos).replace(',','.'), '{:,}'.format(int(activos/probables_alto)).replace(',','.'),'{:,}'.format(int(activos/probables_bajo)).replace(',','.')), horizontalalignment='center', verticalalignment='center', weight = 'bold', fontsize='x-large')
ax_regions = {}
ax_coordinates = {}
axs[0].axis('off')
axs[1].axis('off')
axs[3].axis('off')
axs[4].axis('off')
#axs[4].axis('off')
axs[6].axis('off')
dates = pd.to_datetime(national_underrep['date']).strftime('%d-%m-%y')
p_under, = axs[2].plot(dates, np.asarray(national_underrep['mean'])*100, color ='#006699')
axs[2].fill_between(dates, np.asarray(national_underrep['low'])*100, np.asarray(national_underrep['high'])*100, alpha=.4, color ='#006699')
axs[2].set_ylabel('% Subreporte')
axs[2].set_ylim([0,100])
axs[2].set_yticks(np.arange(0, 101, 10))
axs[2].tick_params(axis='x',rotation=45)
#plt.xticks(rotation=45)
axs[2].tick_params(bottom=False, left=True, labelleft=True, labelbottom=True)
axs[2].grid(axis='y')
m, l, h, i = asp_national(national_underrep)
pos = []
for j, ind in enumerate(i):
pos +=[dates.get_loc(ind)]
ax2 = axs[2].twinx()
ax2.set_ylabel('Infectados sintomáticos activos probables', color='black', fontsize = 7)
p_act, = ax2.plot(pos,m,color='#df4d38')
ax2.fill_between(pos, l, h, alpha=.4, color='#df4d38')
ax2.set_yticks(np.arange(0, 300001, 30000))
ax2.set_yticklabels(["{:,}".format(x).replace(',','~').replace('~','.') for x in np.arange(0, 300001, 30000)])
ax2.tick_params(axis='y', labelcolor='black')
ax2.set_ylim(bottom =0)
axs[1].legend([p_under, p_act],["Porcentaje de subreporte", "Casos activos probables"], bbox_to_anchor=(0.29,1.85), fontsize = 8)
positivity = pcr_positivity_from_db(slice_date) # take out
dates = pd.to_datetime(positivity['Fecha'].values)
dates = dates.strftime('%d-%m-%y')
p2, = axs[5].plot(dates, 100*positivity['positividad pcr'].values, color='#f49819')
p1, = axs[5].plot(dates, 100*positivity['mediamovil_positividad_pcr'].values, color='#000000')
axs[5].set_ylabel('Positividad PCR %', color='black', fontsize = 7)
pos = []
axs[5].grid(axis='y')
axs[5].set_yticks(np.arange(0, 101, 10))
for j, ind in enumerate(i):
pos +=[dates.get_loc(ind)]
ax3 = axs[5].twinx()
p3, = ax3.plot(pos, m, color='#df4d38')
ax3.set_ylabel('Infectados sintomáticos activos probables', color='black', fontsize = 7)
ax3.fill_between(pos, l, h, alpha=.4, color='#df4d38')
# eje y con separación de miles
# ax3.set_yticks(["{:,}".format(x).replace(',','~').replace('~','.') for x in np.arange(0, 300001, 30000)])
ax3.set_yticks(np.arange(0, 300001, 30000))
ax3.set_yticklabels(["{:,}".format(x).replace(',','~').replace('~','.') for x in np.arange(0, 300001, 30000)])
ax3.set_ylim(bottom = 0)
axs[4].legend([p1, p2, p3],["Positividad PCR media movil 7 días", "Positividad PCR diaria", "Casos activos probables"], bbox_to_anchor=(0.37,0.75), fontsize = 8)
axs[4].set_title('Casos activos probables y positividad diaria de exámenes PCR a nivel nacional',loc='center', weight = 'bold', fontsize = 8)
axs[5].tick_params(axis='x',rotation=45)
axs[5].tick_params(bottom=False, left=True, labelleft=True, labelbottom=True)
if len(axs[2].xaxis.get_ticklabels())%2==0:
every_nth = 14
elif len(axs[2].xaxis.get_ticklabels())%2==1:
every_nth = 14
for n, label in enumerate(axs[2].xaxis.get_ticklabels()):
if n % every_nth != 0:
label.set_visible(False)
if len(axs[5].xaxis.get_ticklabels())%2==0:
every_nth = 14
elif len(axs[5].xaxis.get_ticklabels())%2==1:
every_nth = 14
for n, label in enumerate(axs[5].xaxis.get_ticklabels()):
if n % every_nth != 0:
label.set_visible(False)
#fig.tight_layout(h_pad = 0.1)
# fig.subplots_adjust(hspace=.5, top = 0.84)
filename = 'Report/Report_{}_national_underrep.pdf'.format(report_day.replace('/','_'))
fig.savefig(self.pdf, format='pdf', dpi=1200)
plt.savefig('subreporte.png', format = 'png', dpi = 600)
pass
# PAGE 02
def add_summary(self, reg_data, prevalencia_region, region_avg_rate, subr, R_reg,hs_occupation, report_date, national_prev, national_rate, national_underreporting, national_r):
hospital_available = False
UCI_available = True
if hospital_available:
_, camas_prev, camas_now = hs_occupation
if UCI_available:
UCI_prev, UCI_newest = load_uci_data()
reg_dict = {''}
first = reg_data[['Prevalencia', 'Tasa']].rename(index= {'Arica y Parinacota':'Arica', 'Aysén del General Carlos Ibáñez del Campo':'Aysén',
'Biobío':'Bio-Bío',"Libertador General Bernardo O'Higgins":"O'Higgins", 'Magallanes y de la Antártica Chilena': 'Magallanes', 'Metropolitana de Santiago':'Metropolitana'})
first['Región'] = first.index
first['Región'] = first.index
subrep_arrow = [subr['mean'][i][-1]-subr['mean'][i][-7] for i in subr.index]
data_sub = [subr['mean'][i][-1] for i in subr.index]
for j, item in enumerate(data_sub):
if item < 0:
data_sub[j] = 0
elif item > 1:
data_sub[j] = 1
Subreporte = pd.DataFrame(data = data_sub,index= subr.index, columns = ['mean'])
Subreporte = Subreporte.rename(index= {'Arica y Parinacota':'Arica', 'Aysén del General Carlos Ibáñez del Campo':'Aysén', 'Araucanía': 'La Araucanía',
'Biobío':'Bio-Bío',"Libertador General Bernardo O'Higgins":"O'Higgins", 'Magallanes y de la Antártica Chilena': 'Magallanes', 'Metropolitana de Santiago':'Metropolitana'})
#first['Subreporte'] = 1 - first['Subreporte']
first['Subreporte'] = Subreporte
first['Subreporte'] = first['Subreporte'].map('{:,.2%}'.format)
first['Subreporte'] = first['Subreporte'].apply(lambda x: x.replace('nan%','ND'))
R_reg.index.names = ["dates"]
last_day = R_reg.index[-1]
last_seven = list(R_reg.index[-7:])
last_fourteen =list(R_reg.index[-14:])
last_r = R_reg.loc[last_day]
last_r = last_r.groupby(last_r.name).mean()
last_r = last_r.rename(index= {'Arica y Parinacota':'Arica', 'Aysén del General Carlos Ibáñez del Campo':'Aysén', 'Araucanía': 'La Araucanía',
'Biobío':'Bio-Bío',"Libertador General Bernardo O'Higgins":"O'Higgins", 'Magallanes y de la Antártica Chilena': 'Magallanes', 'Metropolitana de Santiago':'Metropolitana'})
seven_r = R_reg.loc[last_seven]
seven_r = seven_r.groupby(seven_r.name).mean()
seven_r = seven_r.rename(index= {'Arica y Parinacota':'Arica', 'Aysén del General Carlos Ibáñez del Campo':'Aysén', 'Araucanía': 'La Araucanía',
'Biobío':'Bio-Bío',"Libertador General Bernardo O'Higgins":"O'Higgins", 'Magallanes y de la Antártica Chilena': 'Magallanes', 'Metropolitana de Santiago':'Metropolitana'})
fourteen_r = R_reg.loc[last_fourteen]
fourteen_r = fourteen_r.groupby(fourteen_r.name).mean()
fourteen_r = fourteen_r.rename(index= {'Arica y Parinacota':'Arica', 'Aysén del General Carlos Ibáñez del Campo':'Aysén', 'Araucanía': 'La Araucanía',
'Biobío':'Bio-Bío',"Libertador General Bernardo O'Higgins":"O'Higgins", 'Magallanes y de la Antártica Chilena': 'Magallanes', 'Metropolitana de Santiago':'Metropolitana'})
first['14 días'] = fourteen_r['MEAN'].map('{:,.2f}'.format)
first['7 días'] = seven_r['MEAN'].map('{:,.2f}'.format)
first['Último día'] = last_r['MEAN'].map('{:,.2f}'.format)
first = first[['Región', 'Prevalencia', 'Tasa', 'Subreporte', '14 días', '7 días', 'Último día' ]]
#first = first.apply(lambda x: x.str.replace('.',','))
########################################################################################
fig = plt.figure(figsize=(11, 8.5))
fig.text(0.95,0.06, '©2020, Laboratorio de Biología Computacional, Fundación Ciencia & Vida', ha='right', fontsize=8)
fig.text(0.0325, .900, 'Tabla resumen al '+report_date,
horizontalalignment='left', verticalalignment='center', weight = 'bold', fontsize='12')
fig.text(0.0325,0.195, 'Flechas en prevalencia y uso de camas indican cambio respecto a reporte anterior \n'
+'Prevalencia infectados activos / 10.000 habitantes. Códigos colores: verdes \u2264 4; 4 <amarillo<5; rojo \u2265 5(Criterio OMS)\n'
+'Tasa promedio acumulada de nuevos infectados últimos 14 días. Código colores: verdes \u2264 25%; 25% <amarillo< 30%; rojo \u2265 5\n'
+'Subreporte infectados sintomáticos. Código colores según media de subreporte: verde = ND y 0; 1 <amarillo< 10; rojo \u2265 10\n'
+'Código colores uso de camas: verde(fuera de riesgo) \u2264 25%; 75% <amarillo(estable)\u2264 85%; 75% <naranja(saturación)\u2264 85%; rojo(colapso) > 95% \n',
ha='left', fontsize=8)
########################################################################################
if hospital_available or UCI_available:
ax1_pos = [0.02, 0.0, 0.73, 0.9]
ax2_pos = [0.525, 0.0, 0.14, 0.9]
else:
delta = 0.35
ax1_pos = [0.02, 0.0, 0.73+delta, 0.9]
ax2_pos = [0.525+delta*0.7, 0.0, 0.25, 0.9]
ax1 = fig.add_axes(ax1_pos)
ax1.set_axis_off()
regions = ["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", "Nacional"]
first = first.reindex(regions)
first = first.replace({"Arica":"(15) Arica","Tarapacá":"(01) Tarapacá","Antofagasta": "(02) Antofagasta","Atacama":"(03) Atacama",
"Coquimbo":"(04) Coquimbo","Valparaíso":"(05) Valparaíso","O'Higgins": "(06) O'Higgins","Maule": "(07) Maule",
"Ñuble":"(08) Ñuble","Bio-Bío":"(16) Bio-Bío","La Araucanía": "(09) La Araucanía","Los Ríos":"(14) Los Ríos",
"Los Lagos":"(10) Los Lagos","Aysén":"(11) Aysén","Magallanes":"(12) Magallanes","Metropolitana":"(13) Metropolitana"})
data = np.ones((16,7))
nacional = pd.DataFrame({'Región' :['(N) Nacional'],
'Prevalencia': ['{:.2f}'.format(national_prev.T.values[-1][0]) ],
'Tasa': [ '{:.2f}'.format(national_rate.values[-1]*100)+'%'],
'Subreporte':['{:.2f}%'.format(national_underreporting['mean'][-1]*100)],
'14 días': ['{:.2f}'.format(national_r['MEAN'][-14:].mean())],
'7 días':['{:.2f}'.format(national_r['MEAN'][-7:].mean())],
'Último día':['{:.2f}'.format(national_r['MEAN'].values[-1])]}, index = ['Nacional'])
first =first.append(nacional)
first.dropna(inplace=True)
colLabels=['region', 'Camas Intermedio','Camas Intensivo','Número VMI','Pctes. Intermedio','Pctes. Intensivo','Pctes. VMI']
table1 = ax1.table(
cellText=first.values,
fontsize=2,
colLabels=first.columns,
colWidths=[.130,.090,.090,.090,.090,.090,.090],
cellColours=[['w', color_prvlnc_summary(float(first['Prevalencia'].iloc[c].replace(',','.'))),
color_rate_summary(float(first['Tasa'].iloc[c].replace(',','.')[:-1])/100),
color_underreporting_summary(first['Subreporte'].iloc[c].replace(',','.')[:-1]),
color_r0_summary(float(first['14 días'].iloc[c].replace(',','.'))),
color_r0_summary(float(first['7 días'].iloc[c].replace(',','.'))),
color_r0_summary(float(first['Último día'].iloc[c].replace(',','.'))) ] for c in range(17)],
cellLoc='center',
loc='upper left')
table1.auto_set_font_size(False)
table1.set_fontsize(7)
cellDict1 = table1.get_celld()
for i in range(0,len(colLabels)):
cellDict1[(0,i)].set_height(.15)
for j in range(1,len(data)+2):
cellDict1[(j,i)].set_height(.03)
for i in range(1,18):
cellDict1[i,0].set_text_props(ha ='left')
self._arrow_summary_1(prevalencia_region, region_avg_rate, national_prev, national_rate, subr, national_underreporting,ax1)
########################################################################################
ax2 = fig.add_axes(ax2_pos)
ax2.set_axis_off()
ax2.annotate( 'Situación \nEpidemiológica', xy=(0.18,0.84),
xycoords='axes fraction', ha='center', va='bottom',
fontweight = 'black',
rotation=90, size=8)
#for i in range 17 arrow_summary_1(first, second)
table2 = ax2.table(
cellText=[' ']*17,
fontsize=2,
#rowLabels=regions,
colLabels=[' '],
colWidths=[.111*2.5],
cellColours=[[color_epi(float(first['14 días'].iloc[c].replace(',','.')),
float(first['7 días'].iloc[c].replace(',','.')),
float(first['Último día'].iloc[c].replace(',','.')))] for c in range(17)],
cellLoc='center',
loc='upper left')
cellDict2 = table2.get_celld()
for i in range(0,1):
cellDict2[(0,i)].set_height(.15)
cellDict2[(0,i)].set_linewidth(2)
for j in range(1,len(data)+2):
cellDict2[(j,i)].set_height(.03)
cellDict2[(j,i)].set_linewidth(2)
########################################################################################
if hospital_available:
ax3 = fig.add_axes([0.595, 0.0, 0.50, 0.9])
ax3.set_axis_off()
self.arrow_summary_2(camas_prev, camas_now, ax3)
camas_num = camas_now.copy()
camas_now['Uso VMI'] =camas_now['Uso VMI'].map('{:,.2%}'.format)
camas_now['Uso Intermedias'] =camas_now['Uso Intermedias'].map('{:,.2%}'.format)
camas_now['Uso Intensivas'] =camas_now['Uso Intensivas'].map('{:,.2%}'.format)
table3 = ax3.table(
cellText=camas_now.values,
fontsize= 10,
rowLabels= ['15','01', '02', '03', '04', '05', '06', '07', '08', '16', '09', '14', '10', '11', '12', '13'],
colLabels=['UTI', 'UCI', 'VMI'],
colWidths=[.100*2,.100*2,.100*2],
cellColours=[[color_camas(camas_num['Uso Intermedias'].iloc[c]) ,
color_camas(camas_num['Uso Intensivas'].iloc[c]) ,
color_camas(camas_num['Uso VMI'].iloc[c] )] for c in range(16)],
# 'w','w']
cellLoc='center',
loc='upper left'
)
table3.auto_set_font_size(False)
table3.set_fontsize(7)
cellDict3 = table3.get_celld()
for i in range(0,3):
cellDict3[(0,i)].set_height(.15)
for j in range(1,len(data)+1):
cellDict3[(j,i)].set_height(.03)
for i in range(1,17):
cellDict3[(i,-1)].set_height(.03)
########################################################################################
ax4 = fig.add_axes([0.908, 0.0, 0.14, 0.9])
ax4.set_axis_off()
ax4.annotate(' Situación \nHospitalaría', xy=(0.2,0.855),
xycoords='axes fraction', ha='center', va='bottom',
fontweight = 'black',
rotation=90, size=8)
table4 = ax4.table(
cellText=[' ']*16,
fontsize=3,
colLabels=[' '],
colWidths=[.111*3],
cellColours=[[color_hos_sit(camas_num['Uso Intermedias'].iloc[c],
camas_num['Uso Intensivas'].iloc[c] ,
camas_num['Uso VMI'].iloc[c]) ] for c in range(16)],
cellLoc='center',
loc='upper left')
cellDict4 = table4.get_celld()
for i in range(0,1):
cellDict4[(0,i)].set_height(.15)
cellDict4[(0,i)].set_linewidth(2)
for j in range(1,len(data)+1):
cellDict4[(j,i)].set_height(.03)