-
Notifications
You must be signed in to change notification settings - Fork 1
/
script-seir_simple_patch-v-0.6.py
3685 lines (3317 loc) · 151 KB
/
script-seir_simple_patch-v-0.6.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
#!/usr/bin/env python
# SEIR without demography (no vital dynamics)
# VERSION NOTEBOOK
##################################################################
# This porgrame started as the PYTHON version of program 2.6 #
# from page 41 of #
# "Modeling Infectious Disease in humans and animals" #
# by Keeling & Rohani #
# #
# It is the SEIR epidemic with no births nor deaths. #l
# Note we no-longer explicitly model the recovered class. #
##################################################################
########################################################################
# Modified by carlos j dommar - [email protected] #
# to adapt it to a simple 2-patch model #
# - modification log #
# #
# - pending udate info for version 0.6 #
# #
# - v. 0.4.7: #
# * I check that densities are used instread of absolut #
# population sizes #
# * Implemente a Block Random Network Model to model the #
# political structure in the network #
# * Once parameterized the BRNM then simulate epidemics on reali #
# -zations drwan form the parameterized and validated BRNM #
# * Draw conclusions and write the paper. #
# #
# - I use similar parameters as used in the notebooki #
# simple_metapopulation_SEIR_plus_mosquito_v0.0.1 in order to test #
# real value parameters for chikungunya #
# - In this version I test the three patches model #
# - In this version I use the real conection data from openflights.org #
# to build up the mobility matrix 'M', I use real population sizes, #
# of the Caribbena region of interest for the CHIKV outbreak #
# - This is the same as the version 0.4 but a bit more clean #
# - in this version I include a new node: Saint Martin and use the #
# information given by the airport http://www.saintmartin-airport.com #
# to update the conection mobility matrix. This should be important #
# because the first reported local transmission in the Caribbean was #
# reported precisely in Sanint Martin #
# version 0.4.5: #
# - add Tycho data for comparison and calibration of the theoretical #
# - MODEL TWEAKER: this is a no-frills code that produces only the #
# theoretical aggragated curve and it compares against the (Tycho) #
# observed data. The goal is to have a clear nd simple code to #
# calibrate the theoretcial model with the observations by tweaking #
# the parameters #
# - SCENARIOS: #
# a) randomize the conections Saint Martin #
# (first island infected) and loop for several realizations. #
# The goal is to check whether the pattern of sequnces is hold
# #
# b) Random seeding of the diseases in any island while keeping
# the topology and #
# several realizations - check whether the sequential #
# pattern holds #
# #
# c) connect Saint Martin with all of the other islands (Xavi's #
# idea -?) #
# #
# d) Random network with the same number of nodes and links of #
# the obeserved one. #
# #
# version 0.6. #
# #
########################################################################
########################################################################
#__author__ = """carlos j dommar ~ carlos.dommar_at_ ic3.cat"""
# Preambule:
import os
import scipy.integrate as spi
import numpy as np
import pylab as pl
import pandas as pd
import networkx as nx
import seaborn
import time
#%matplotlib inline
start = time.time()
#################################################################################
########################## MY FUNCTIONS #########################################
#################################################################################
#################################################################################
# F_AIRPORTS(DATA_PROJECT_FOLDER)
def f_airports(data_project_folder):
"""
this function receives a path variable where the data is located
and gives back a pandas dataframe with airports by label
and their connections.
"""
## use for both Ingold and Lenovo:
# airports = pd.read_csv('~/' +data_project_folder+ 'data\airports.csv')
airports = pd.read_csv('data/airports.csv')
# Load the outcome from the albert's script 'connection_matrix.py' (report path)
## use the following path for the Lenovo laptop:
airports_df = pd.read_csv('data/island_connections_caribbean_3.csv')
# cleaning off some unnecesary header off the dataframe
airports_df = airports_df.drop('Unnamed: 0',1)
airports_df.index = airports_df.columns
return airports_df
#################################################################################
# F_LATLON_DF()
def f_latlon_df():
"""
this function recieves nothing (the path to the data is identical both in
Ingold and in my laptop), and gives back a pandas dataframe with the
countries, their number tag from the original data frame, ther coordinates,
political, region, etc.
"""
## use for both Ingold and Lenovo:
airports = pd.read_csv('data/airports.csv')
# Some cleaning and editing of the database is needed:
airports.ix[2821, 'Country'] = 'Bonaire'
airports.ix[2822, 'Country'] = 'Curacao'
airports.ix[2823, 'Country'] = 'Sint Eustatius'
airports.ix[2824, 'Country'] = 'Sint Maarten'
airports.ix[4137, 'Country'] = 'Saba'
airports.ix[5331, 'Country'] = 'Saint Barthelemy'
# Create a simple DF with airports with latitudes and longitudes:
columns = ['name', 'city', 'country', 'lat', 'lon']
index = my_airports_df.index
# DF for lat and long of selected airports:
latlonglobal_df = pd.DataFrame(index=index, columns=columns)
for i in latlonglobal_df.index:
name = airports[airports['Airport ID'] == np.int(i)]['Name'].iloc[0]
city = airports[airports['Airport ID'] == np.int(i)]['City'].iloc[0]
country = airports[airports['Airport ID'] == np.int(i)]['Country'].iloc[0]
lat = airports[airports['Airport ID'] == np.int(i)]['Latitude'].iloc[0]
lon = airports[airports['Airport ID'] == np.int(i)]['Longitude'].iloc[0]
latlonglobal_df.set_value(i, 'name', name)
latlonglobal_df.set_value(i, 'city', city)
latlonglobal_df.set_value(i, 'country', country)
latlonglobal_df.set_value(i, 'lat', lat)
latlonglobal_df.set_value(i, 'lon', lon)
del columns, index, lat, lon, i, name, city
print ('----------------------------------------------')
print ('The countries in the region of interest are the following:')
print ('')
print (latlonglobal_df['country'].drop_duplicates())
print ('')
print ('')
print ('They are '), latlonglobal_df['country'].drop_duplicates().shape[0], \
(' countries')
# Add an attriute for 'political region' to the data frame:
latlonglobal_df['political_region'] = pd.Series(data=None)
# 'political_region' can e either. 'french', 'anglo', 'latin', 'dutch'
# print latlonglobal_df.head()
# now we assign the political regions
for i in latlonglobal_df['country']:
if (i == 'Puerto Rico') or (i == 'Dominican Republic') \
or (i =='Cuba') or (i == 'Colombia') or (i == 'Venezuela') \
or (i == 'Mexico') or (i == 'Brazil') \
or(i=='Nicaragua') or (i=='Panama') \
or (i=='Costa Rica') or (i == 'Haiti'):
latlonglobal_df.ix[latlonglobal_df['country'] \
== i, 'political_region'] = 'latin'
elif (i == 'Jamaica') or (i == 'Cayman Islands') \
or (i == 'Antigua and Barbuda') or (i == 'Grenada') \
or (i == 'Barbados') or (i == 'Virgin Islands') \
or (i == 'Saint Kitts and Nevis') or (i == 'Anguilla') \
or (i =='Trinidad and Tobago') or (i == 'Jamaica') \
or (i=='British Virgin Islands')\
or (i == 'Saint Vincent and the Grenadines') or (i =='Montserrat') \
or (i=='Bahamas') or (i == 'Turks and Caicos Islands') \
or (i =='Dominica') or (i =='Saint Lucia') or (i =='Montserrat') \
or (i == 'Guyana'):
latlonglobal_df.ix[latlonglobal_df['country'] \
== i, 'political_region'] = 'anglo'
elif (i == 'Martinique') or (i =='Guadeloupe') or (i =='Saint Barthelemy') \
or (i == 'French Guiana') or (i == 'Haiti'):
latlonglobal_df.ix[latlonglobal_df['country'] \
== i, 'political_region'] = 'french'
elif (i =='Aruba') or (i == 'Suriname') or (i == 'Bonaire') \
or (i == 'Sint Eustatius') or (i == 'Curacao') \
or (i == 'Sint Maarten') or (i == 'Saba'):
latlonglobal_df.ix[latlonglobal_df['country'] \
== i, 'political_region'] = 'dutch'
return latlonglobal_df
#################################################################################
# F_GRAPH(DF, LATLONGLOBAL_DF)
def f_graph(df, latlonglobal_df): # rough network model
"""
this function receives 'df', a pandas' dataframe coming out the function
'my_aiports()', and a pandas's dataframe coming out the function
'latlong_df()' and gives back a networkx object with teh final network model
for the flight connection of the area selected in the Albert's script
the funtion returns a networkx object with the model of the observed
flight connection
"""
# New method to create the graphs
G = nx.DiGraph(np.asarray(df)) # direct method
new_nodes = np.asarray(df.columns) # new nodes
mapping = {} # dict
count = 0
for i in G.node:
mapping[i] = new_nodes[count]
count = count + 1
del count, new_nodes
# new graph with relabeld nodes:
G = nx.relabel_nodes(G, mapping)
# add some information to the nodes
for i in df.index: # = my_aiports.columns
G.add_node(i,
airport_name = \
latlonglobal_df[latlonglobal_df.index==i]['name'][0],
city = \
latlonglobal_df[latlonglobal_df.index==i]['city'][0],
country = \
latlonglobal_df[latlonglobal_df.index==i]['country'][0],
lat = \
latlonglobal_df[latlonglobal_df.index==i]['lat'][0],
lon = \
latlonglobal_df[latlonglobal_df.index==i]['lon'][0],
political_region = \
latlonglobal_df[latlonglobal_df.index==i]\
['political_region'][0],
color = 'Gray',
)
# remove isolates nodes:
G.remove_nodes_from(nx.isolates(G))
# setting the nodes some centrality attributes:
bb = nx.betweenness_centrality(G)
nx.set_node_attributes(G, 'betweeness', bb)
del bb
degree = nx.degree(G) # dict with nodes and corresponding degree
# Set color of nodes by political regions for visualizations purposes
# Set the node attribute a different color per region:
for i in G.nodes():
if G.node[i]['political_region'] == 'latin':
G.node[i]['color'] = 'Peru'
elif G.node[i]['political_region'] == 'dutch':
G.node[i]['color'] = 'OrangeRed'
elif G.node[i]['political_region'] == 'anglo':
G.node[i]['color'] = 'DarkGreen'
elif G.node[i]['political_region'] == 'french':
G.node[i]['color'] = 'DarkBlue'
# Make a list with the color of the nodes per region using list comprehesion:
color_of_nodes = [G.node[i]['color'] for i in G.nodes()]
return G
#################################################################################
# F_DATAFRAME(MY_G, MY_AIRPORTS_DF, MY_LATLONG_DF)
def f_dataframe(my_g, my_airports_df, my_latlong_df):
"""
this function receives:
- a networkx object (usually coming out the function 'f_graph()')
- a pandas data frame object with all selected airports (usually comming
out the function 'f_airports()')
- a pandas data frame object with all selected airports (usually coming
out of the function 'f_latlon_df()')
this function gives back: a pandas data frame object with corrected and
aggregated connections by countries rather than by airports
"""
############################
# DATA GROUPED BY COUNTRY: #
############################
# make a list of the locations involved at the level of country/island:
countries = []
for i in my_g.nodes():
countries.append(my_g.node[i].get('country'))
# drop duplicates countries:
# trick: use 'set'. A set is something that can't possibly have duplicates:
countries = list(set(countries))
# Correction: I need to add Saint Martin
countries.append('Saint Martin')
# The connecivity matrix is first computes as a Pandas
# Data Frame object ''
countries_df = pd.DataFrame(data=0, \
index=countries, columns=countries, dtype=int)
# Then
origin = str()
destiny = str()
for i in range(0, len(my_airports_df)):
airport_ID = my_airports_df.index[i]
if my_airports_df.iloc[i].sum() != 0:
origin = my_latlong_df[my_latlong_df.index \
== airport_ID]['country'][0]
for j in range(0, len(my_airports_df)):
if my_airports_df.iloc[i,j] != 0: #there's a connection in (i,j)
destination_ID = my_airports_df.columns.values[j]
destiny = my_latlong_df[my_latlong_df.index \
== destination_ID]['country'][0]
if origin != destiny:
#print 'Two different countries are connected!'
countries_df.ix[origin,destiny] \
= countries_df.ix[origin,destiny] \
+ my_airports_df.iloc[i,j]
destiny = list()
origin = list()
# check that the diagonal of 'countries_df' must be zero:
for i in range(0,len(countries_df)):
for j in range(0,len(countries_df)):
if i == j and countries_df.iloc[i,j] != 0:
print ('ALERT DIAGONAL NOT ZERO')
del i, j, origin, destiny, airport_ID
#return countries_df
# Correcting Saint Martin connections:
# according the airport website http://www.saintmartin-airport.com
# Saint Martin has conection with Martinique, Saint Barthelemy,
# Guadalope, Saint Lucia, Santo Domingo (Puerto Rico), and Miami (USA):
# with Saint Barthelemy: 1
# with Martinique: 2
# with Saint Lucia: 1
# with Guadeloupe: 2
# with Puerto Rico: 1
# with Miami (USA): 2
countries_df.ix['Saint Martin', 'Saint Barthelemy'] = 1
countries_df.ix['Saint Barthelemy', 'Saint Martin'] = 1
countries_df.ix['Saint Martin', 'Martinique'] = 2
countries_df.ix['Martinique', 'Saint Martin'] = 2
countries_df.ix['Saint Martin', 'Saint Lucia'] = 1
countries_df.ix['Saint Lucia', 'Saint Martin'] = 1
countries_df.ix['Saint Martin', 'Guadeloupe'] = 2
countries_df.ix['Guadeloupe', 'Saint Martin'] = 2
countries_df.ix['Saint Martin', 'Puerto Rico'] = 1
countries_df.ix['Puerto Rico', 'Saint Martin'] = 1
return countries_df
################################################################################
# F_REDUCED_G(MYDF, MY_G)
def f_reduced_g(mydf, my_g, pop_rescale):
"""
this function receives in the following order:
- mydf: pandas data frame with the definite countries and their
connections
- my_g: netwokx object with connection of ALL airports
this function gives back:
- a networkx object with the definite (reduced) network model by country.
"""
#mydf = countries_df # finally the mydf dataframe with the selected area
# The connectivity matrix as a numpy array:
M = np.asarray(mydf)
# new more clear line --- I had to transpose the matrix to get H right:
H = nx.from_numpy_matrix(np.matrix.transpose(M))
mapping = {} # dict
count = 0
# I need this piece of code again:
countries = []
for i in my_g.nodes():
countries.append(my_g.node[i].get('country'))
# drop duplicates countries:
# trick: use 'set'. A set is something that can't possibly have duplicates:
countries = list(set(countries))
# Correction: I need to add Saint Martin
countries.append('Saint Martin')
for i in range(0, len(countries)):
mapping[i] = countries[count]
count = count + 1
del count
H = nx.relabel_nodes(H, mapping)
# add attributes to H
for i in H.nodes():
for j in my_g.nodes():
if i == my_g.node[j].get('country'):
# print 'yes, I found ', i, j
H.add_node(i, color = my_g.node[j].get('color'), \
political_region = my_g.node[j].get('political_region'))
break
#for Saint Martin:
H.add_node('Saint Martin', color = 'DarkBlue', political_region = 'french')
pop = pd.read_csv("data/locations_populations.csv")
# Add population sizes and densities to the graph H:
for i in H.nodes():
for j in pop['location']:
if i == j:
H.node[i]['pop_size'] = \
np.float(pop[pop['location'] == j]['pop_size'])
H.node[i]['density'] = \
np.float(pop[pop['location'] == j]['density'])
# TEST: rescaling population sizes: #
# This snippet calibrate the magnitude of the number of infectious cases #
# by decreasing the population size exposed to the infection #
for i in H.nodes(): #
H.node[i]['pop_size'] = H.node[i]['pop_size'] * pop_rescale
# setting the nodes some centrality attributes:
bb = nx.betweenness_centrality(H)
nx.set_node_attributes(H, 'betweeness', bb)
del bb, i, j
# REMARK: There are airports from some countries that have no connection with \
# other airports in the chosen area. These may be airports in the borders of \
# the regions which connections goe sto some other locations outside the chosen\
# area and for that reason they appear as to be islotaed conountries. The \
# following code helps us to indentify these countries.
count = 0
for i in mydf.index:
# the country appears as having no connections with others in the area
if mydf.ix[i,:].sum() == 0:
print ('The airports of the country '), i, \
(' of the chosen area seems to have no connection with the rest.')
count = count + 1
print ('-----------------------------')
print ('There are '), count, (' such countries in the chosen area.')
print ('-----------------------------')
del count, i
# adding a tocuh of color:
color_of_nodes = [H.node[i]['color'] for i in H.nodes()]
return H
#################################################################################
# THE SEIR EQUATIONS: F_DIFF_EQS(YO, T, M, BETA, GAMMA, SIGMA)
def f_diff_eqs(Y0, t, epi_classes, M, beta, sigma, gamma):
patches = M.shape[0]
leap = epi_classes * (patches - 1) + 1 # patches = is the number of patches
# I need to keep track explicitely on the total population sizes
S = Y0[0:leap:epi_classes]
E = Y0[1:leap+1:epi_classes]
I = Y0[2:leap+2:epi_classes]
R = Y0[3:leap+3:epi_classes]
N = Y0[4:leap+4:epi_classes] # never used!
dS = -beta*S*I/(S+E+I+R)
dE = beta*S*I/(S+E+I+R) - sigma*E
dI = sigma*E - gamma*I
dR = gamma*I
# Update with migration rates:
# For all dS's:
for i in range(0,len(dS)):
dS[i] = dS[i] \
- M[i,:].sum()*S[i]/(S[i]+E[i]+I[i]+R[i])\
+ (np.squeeze(np.asarray(M[:,i]))*S/(S+E+I+R)).sum()
# For all dE's:
for i in range(0,len(dE)):
dE[i] = dE[i] \
- M[i,:].sum()*E[i]/(S[i]+E[i]+I[i]+R[i])\
+ (np.squeeze(np.asarray(M[:,i]))*E/(S+E+I+R)).sum()
# For all dI's:
for i in range(0,len(dI)):
dI[i] = dI[i] \
- M[i,:].sum()*I[i]/(S[i]+E[i]+I[i]+R[i])\
+ (np.squeeze(np.asarray(M[:,i]))*I/(S+E+I+R)).sum()
# For all dR's
for i in range(0,len(dR)):
dR[i] = dR[i] \
- M[i,:].sum()*R[i]/(S[i]+E[i]+I[i]+R[i])\
+ (np.squeeze(np.asarray(M[:,i]))*R/(S+E+I+R)).sum()
f = [dS, dE, dI, dR, (dS+dE+dI+dR)]
# put f in the right order:
f_temp = list()
patches = M.shape[0] #number of patches
for p in range(0, patches):
for i in f:
f_temp.append(i[p])
f = f_temp # update f with the rightly sorted one
f_temp = list() # reset f_temp
return f # return to odeint
##################################################################################
## F_PLOT_OBSERVED_CHIK(DATA_PROJECT_FOLDER)
#def f_plot_observed_chik(data_project_folder):
# """
# this function receives:
# - a path variable 'data_project_folder',
# and it gives back:
# - a complete plot of the time seris of the oberved chik incidence
# data found at the pointed directory
# """
# df = pd.read_csv('~/'+data_project_folder+'/non-in-repo/data_tycho/data_tycho/Chikungunya_file_28August2014_Tycho_b.csv')
#
# # reaplce the cells with '\N' by 0:
# df.replace(r'\N', 0, inplace=True) # http://stackoverflow.com/questions/1347791/unicode-error-unicodeescape-codec-cant-decode-bytes-cannot-open-text-file
#
# # Getting the types right:
# df[['YEAR', 'WEEK', 'Week_conf_cases']] = df[['YEAR', 'WEEK', 'Week_conf_cases']].astype(int)
# df['Cum_sus_cases'] = df['Cum_sus_cases'].astype(int)
# df['Week_conf_cases'] = df['Week_conf_cases'].astype(int)
# df['Cum_conf_cases'] = df['Cum_conf_cases'].astype(int)
# df['Week_import_cases'] = df['Week_import_cases'].astype(int)
# df['Cum_import_cases'] = df['Cum_import_cases'].astype(int)
# df['Week_deaths'] = df['Week_deaths'].astype(int)
# df['Cum_deaths'] = df['Cum_deaths'].astype(int)
# df['Population'] = df['Population'].astype(int)
# df['Week_Sus_Cases'] = df['Week_Sus_Cases'].astype(int)
# df['COUNTRY'] = df['COUNTRY'].astype(str)
# df['Incidence_sus_cases'] = df['Incidence_sus_cases'].astype(float)
# df['Incidence_conf_cases'] = df['Incidence_conf_cases'].astype(float)
#
# ## transforming negative data to absolute value:
# ## Example:
# #df.loc[df['COUNTRY'] == 'Virgin Islands, U.S.', 'Week_conf_cases']
# #virgin_islands_us = df.loc[df['COUNTRY'] == 'Virgin Islands, U.S.', 'Week_conf_cases']
# # function (inside a function! :-o):
# def neg2abs(x):
# if x < 0:
# return np.abs(x)
# else:
# return x
#
# #virgin_islands_us.apply(neg2abs)
# ## THERE'S TWO OPTIONS:
# ## 1. take the absolute value of all negative\
# ## observations (assuming the the negative symbol is a mistake)
# df.ix[df.Week_conf_cases < 0, 'Week_conf_cases'] = \
# df.ix[df.Week_conf_cases < 0, 'Week_conf_cases'].apply(neg2abs)
#
# ## 2. set all negative observations to zero (assuming it is a mistake):
# #df.ix[df.Week_conf_cases < 0, 'Week_conf_cases'] = 0
#
#
# ##################################################
# ## TRANSFORMING ISO WEEK NUMBERS INTO PANDAS TIME:
# ##################################################
from isoweek import Week
# #test:
# d = Week(2011, 51).sunday()
# #print d
# #print 'TRANFORMING ISO WEEK NUMBERS INTO PANDAS TIME: test OK'
# del d
#
# # CREATING PROPPER TIME SERIES OF OBSERVED DATA FROM THE TYCHO DATA BASE:
# ## create two lists: 'country' with country names and 'all_dates' with corresponding
# ## time indexes for observations
# count = 0
# country = []
# all_dates = []
# for x in df['COUNTRY'].drop_duplicates():
# if x != 0: # horrible hack here
# iso_week = np.asarray(df[df['COUNTRY'] == x][['YEAR','WEEK']])
# fecha = [Week(i[0], i[1]).sunday() for i in iso_week]
# # print count, ' -- ', x, fecha
# country.append(x)
# all_dates.append(fecha)
# count = count + 1
# # print ''
# del fecha
# del iso_week
#
# # create dictionary to relate country and time indexes
# dates_dict = {}
# countries_and_dates = zip(country, all_dates)
# for country, all_dates in countries_and_dates:
# dates_dict[country] = all_dates
# del countries_and_dates, all_dates
#
#
# # now the same but for a dictionary with the time series objects:
# count = 0
# country = []
# time_series = []
# for x in df['COUNTRY'].drop_duplicates():
# if x != 0: # horrible hack
# ts = pd.Series(np.asarray(df[df['COUNTRY'] == \
# x]['Week_conf_cases']), dates_dict[x])
# # print count, ts
# country.append(x)
# time_series.append(ts)
# count = count + 1
# del ts
#
# # create dictionary to relate country and time series
# time_series_dict = {}
# countries_and_ts = zip(country, time_series)
# for country, time_series in countries_and_ts:
# time_series_dict[country] = time_series
# del countries_and_ts, time_series
#
# ## PROPERLY PLOT.SUM OF TIME SERIES WITH DIFFERENT LENGTHS
# # if the series are in the 'time_series_dict' dictionary:
# frame = pd.DataFrame(time_series_dict)
# # print frame.head()
#
# # Since different length are, in this particular, the result of
# # different starting times of the series, the appearing NaNs
# # mean that no cases where recorded in that dates. So we make them equals to zero:
# frame.fillna(0, inplace=True)
# # print frame.head()
#
# ## Print test:
# ## [frame[i].plot(linewidth=4, alpha=.35, \
# ## figsize=(15,7)) for i in df['COUNTRY'].drop_duplicates()]
# #
# # Aggregate all oberved (Tycho) time series
# initial_country = df['COUNTRY'].drop_duplicates()[0]
# TS_total = frame[initial_country]
#
# for i in df['COUNTRY'].drop_duplicates():
# if i != initial_country:
# TS_total = TS_total + frame[i]
#
# del country
#
# pl.figure(figsize=(15,7))
# TS_total.plot(linewidth=6, alpha=.85, color='Crimson', figsize=(15,7))
# pl.title('Aggregated observed cases -Tycho', fontsize=20)
# pl.xlabel('time (weeks)', fontsize=20)
# #pl.savefig("./figures/Tycho_data.png",dpi=400, orientation='landscape')
#
# return(TS_total)
#################################################################################
# F_PLOT_OBSERVED_CHIK_INDV(DATA_PROJECT_FOLDER)
def f_plot_observed_chik_indv(data_project_folder):
"""
this function receives:
- a path variable 'data_project_folder',
and it gives back:
- a pandas.core.frame.DataFrame object that works a dictionary where the
keys are the name of the nodes/locations and values as time series
objects with oserved chik cases
"""
df = pd.read_csv('data/Chikungunya_file_28August2014_Tycho_b.csv')
# reaplce the cells with '\N' by 0:
df.replace(r'\N', 0, inplace=True) # http://stackoverflow.com/questions/1347791/unicode-error-unicodeescape-codec-cant-decode-bytes-cannot-open-text-file
# Getting the types right:
df[['YEAR', 'WEEK', 'Week_conf_cases']] = df[['YEAR', 'WEEK', 'Week_conf_cases']].astype(int)
df['Cum_sus_cases'] = df['Cum_sus_cases'].astype(int)
df['Week_conf_cases'] = df['Week_conf_cases'].astype(int)
df['Cum_conf_cases'] = df['Cum_conf_cases'].astype(int)
df['Week_import_cases'] = df['Week_import_cases'].astype(int)
df['Cum_import_cases'] = df['Cum_import_cases'].astype(int)
df['Week_deaths'] = df['Week_deaths'].astype(int)
df['Cum_deaths'] = df['Cum_deaths'].astype(int)
df['Population'] = df['Population'].astype(int)
df['Week_Sus_Cases'] = df['Week_Sus_Cases'].astype(int)
df['COUNTRY'] = df['COUNTRY'].astype(str)
df['Incidence_sus_cases'] = df['Incidence_sus_cases'].astype(float)
df['Incidence_conf_cases'] = df['Incidence_conf_cases'].astype(float)
# pd.Timedelta(weeks=np.float64(1))
## transforming negative data to absolute value:
## Example:
#df.loc[df['COUNTRY'] == 'Virgin Islands, U.S.', 'Week_conf_cases']
#virgin_islands_us = df.loc[df['COUNTRY'] == 'Virgin Islands, U.S.', 'Week_conf_cases']
# function (inside a function! :-o):
def neg2abs(x):
if x < 0:
return np.abs(x)
else:
return x
#virgin_islands_us.apply(neg2abs)
## THERE'S TWO OPTIONS:
## 1. take the absolute value of all negative\
## observations (assuming the the negative symbol is a mistake)
df.ix[df.Week_conf_cases < 0, 'Week_conf_cases'] = \
df.ix[df.Week_conf_cases < 0, 'Week_conf_cases'].apply(neg2abs)
## 2. set all negative observations to zero (assuming it is a mistake):
#df.ix[df.Week_conf_cases < 0, 'Week_conf_cases'] = 0
##################################################
## TRANSFORMING ISO WEEK NUMBERS INTO PANDAS TIME:
##################################################
from isoweek import Week
#test:
d = Week(2011, 51).sunday()
#print d
#print 'TRANFORMING ISO WEEK NUMBERS INTO PANDAS TIME: test OK'
del d
# CREATING PROPPER TIME SERIES OF OBSERVED DATA FROM THE TYCHO DATA BASE:
## create two lists: 'country' with country names and 'all_dates' with corresponding
## time indexes for observations
count = 0
country = []
all_dates = []
for x in df['COUNTRY'].drop_duplicates():
if x != 0 : # horrible hack here
iso_week = np.asarray(df[df['COUNTRY'] == x][['YEAR','WEEK']])
fecha = [Week(i[0], i[1]).sunday() for i in iso_week]
# print count, ' -- ', x, fecha
country.append(x)
all_dates.append(fecha)
count = count + 1
# print ''
del fecha
del iso_week
# create dictionary to relate country and time indexes
dates_dict = {}
countries_and_dates = zip(country, all_dates)
for country, all_dates in countries_and_dates:
dates_dict[country] = all_dates
del countries_and_dates, all_dates
# now the same but for a dictionary with the time series objects:
count = 0
country = []
time_series = []
for x in df['COUNTRY'].drop_duplicates():
if x != 0: # horrible hack
ts = pd.Series(np.asarray(df[df['COUNTRY'] == \
x]['Week_conf_cases']), dates_dict[x])
# print count, ts
country.append(x)
time_series.append(ts)
count = count + 1
del ts
# create dictionary to relate country and time series
time_series_dict = {}
countries_and_ts = zip(country, time_series)
for country, time_series in countries_and_ts:
time_series_dict[country] = time_series
del countries_and_ts, time_series
## PROPERLY PLOT.SUM OF TIME SERIES WITH DIFFERENT LENGTHS
# if the series are in the 'time_series_dict' dictionary:
frame = pd.DataFrame(time_series_dict)
# print frame.head()
# Since different length are, in this particular, the result of
# different starting times of the series, the appearing NaNs
# mean that no cases where recorded in that dates. So we make them equals to zero:
frame.fillna(0, inplace=True)
# print frame.head()
return(frame)
#################################################################################
# F_AGGREGATED_TS_OBSERVED_CHIK(DATA_PROJECT_FOLDER)
def f_aggregated_ts_observed_chik(data_project_folder):
"""
this function receives a path variable and gives back a ts object (pandas
time series) with the aggregated incidence data (first stages)
reported by Tycho for the 2013 Caribbean outbreak of CHIKV
"""
df = pd.read_csv('data/Chikungunya_file_28August2014_Tycho_b.csv')
# reaplce the cells with '\N' by 0:
df.replace(r'\N', 0, inplace=True)
# Getting the types right:
df[['YEAR', 'WEEK', 'Week_conf_cases']] = df[['YEAR', 'WEEK', 'Week_conf_cases']].astype(int)
df['Cum_sus_cases'] = df['Cum_sus_cases'].astype(int)
df['Week_conf_cases'] = df['Week_conf_cases'].astype(int)
df['Cum_conf_cases'] = df['Cum_conf_cases'].astype(int)
df['Week_import_cases'] = df['Week_import_cases'].astype(int)
df['Cum_import_cases'] = df['Cum_import_cases'].astype(int)
df['Week_deaths'] = df['Week_deaths'].astype(int)
df['Cum_deaths'] = df['Cum_deaths'].astype(int)
df['Population'] = df['Population'].astype(int)
df['Week_Sus_Cases'] = df['Week_Sus_Cases'].astype(int)
df['COUNTRY'] = df['COUNTRY'].astype(str)
df['Incidence_sus_cases'] = df['Incidence_sus_cases'].astype(float)
df['Incidence_conf_cases'] = df['Incidence_conf_cases'].astype(float)
## transforming negative data to absolute value:
## Example:
#df.loc[df['COUNTRY'] == 'Virgin Islands, U.S.', 'Week_conf_cases']
#virgin_islands_us = df.loc[df['COUNTRY'] == 'Virgin Islands, U.S.', 'Week_conf_cases']
# function (inside a function! :-o):
def neg2abs(x):
if x < 0:
return np.abs(x)
else:
return x
#virgin_islands_us.apply(neg2abs)
## THERE'S TWO OPTIONS:
## 1. take the absolute value of all negative\
## observations (assuming the the negative symbol is a mistake)
df.ix[df.Week_conf_cases < 0, 'Week_conf_cases'] = \
df.ix[df.Week_conf_cases < 0, 'Week_conf_cases'].apply(neg2abs)
## 2. set all negative observations to zero (assuming it is a mistake):
#df.ix[df.Week_conf_cases < 0, 'Week_conf_cases'] = 0
##################################################
## TRASFORMING ISO WEEK NUMBERS INTO PANDAS TIME:
##################################################
from isoweek import Week
#test:
d = Week(2011, 51).sunday()
#print d
#print 'TRANSFORMING ISO WEEK NUMBERS INTO PANDAS TIME: test OK'
del d
# CREATING PROPPER TIME SERIES OF OBSERVED DATA FROM THE TYCHO DATA BASE:
## create two lists: 'country' with country names and 'all_dates' with corresponding
## time indexes for observations
count = 0
country = []
all_dates = []
for x in df['COUNTRY'].drop_duplicates():
if x != 0: # horrible hack here
iso_week = np.asarray(df[df['COUNTRY'] == x][['YEAR','WEEK']])
fecha = [Week(i[0], i[1]).sunday() for i in iso_week]
# print count, ' -- ', x, fecha
country.append(x)
all_dates.append(fecha)
count = count + 1
# print ''
del fecha
del iso_week
# create dictionary to relate country and time indexes
dates_dict = {}
countries_and_dates = zip(country, all_dates)
for country, all_dates in countries_and_dates:
dates_dict[country] = all_dates
del countries_and_dates, all_dates
# now the same but for a dictionary with the time series objects:
count = 0
country = []
time_series = []
for x in df['COUNTRY'].drop_duplicates():
if x != 0: # horrible hack
ts = pd.Series(np.asarray(df[df['COUNTRY'] == \
x]['Week_conf_cases']), dates_dict[x])
# print count, ts
country.append(x)
time_series.append(ts)
count = count + 1
del ts
# create distionary to relate country and time series
time_series_dict = {}
countries_and_ts = zip(country, time_series)
for country, time_series in countries_and_ts:
time_series_dict[country] = time_series
del countries_and_ts, time_series
## PROPERLY PLOT.SUM OF TIME SERIES WITH DIFFERENT LENGTHS
# if the series are in the 'time_series_dict' dictionary:
frame = pd.DataFrame(time_series_dict)
# Since different length are, in this particular, the result of
# different starting times of the series, the appearing NaNs
# mean that no cases where recorded in that dates. So we make them equals to zero:
frame.fillna(0, inplace=True)
# print frame.head()
## Print test:
## [frame[i].plot(linewidth=4, alpha=.35, \
## figsize=(15,7)) for i in df['COUNTRY'].drop_duplicates()]
#
# Aggregate all oberved (Tycho) time series
initial_country = df['COUNTRY'].drop_duplicates()[0]
TS_total = frame[initial_country]
for i in df['COUNTRY'].drop_duplicates():
if i != initial_country:
TS_total = TS_total + frame[i]
del country
return (TS_total)
#################################################################################
# F_YO_CONSTRUCTOR(H node)
def f_yo_constructor(H, node):
"""
this function receives:
- a netowrkx object that represents the oberved connection flights and
the name (string) of the node where to start the infection
this functiongives back:
- an Y0 array with the initial condition for ode solver.
"""
# initial vector
patches = H.number_of_nodes()*epi_classes # # of patches
Y0 = np.zeros(patches)
# fill the initial vector:
N0 = np.zeros(shape=(H.number_of_nodes()), dtype=float)
count = 0
for i in H.nodes():
# N0[count] = H.node[i]['density'] # for densities
N0[count] = H.node[i]['pop_size'] # for pop_sizes
count = count + 1
del count
count = 0
for n in N0:
Y0[count] = n # for class S
Y0[count+4] = n # for class N
count = count + 5
del count, N0
## correction for Saint Martin:
# vector position for the asked node:
pos = H.nodes().index(node)
s_pos = epi_classes * pos
i_pos = s_pos + 2
Y0[s_pos] = Y0[s_pos] - 1 # S = S - 1
Y0[i_pos] = Y0[i_pos] + 1 # I = I + 1
return(Y0)
#################################################################################
## def f_sample_solution(my_observed_chik_ts, my_sol)
def f_sample_solution(my_observed_chik_ts, my_sol):
"""
this function recieves:
- a pandas time series object, representing the observed data
- a pandas time series object, representing the solution
this function gives back:
- a pandas time series with a reduced vector solution with only data
points corresponding to the obeserved datae for comparison purposes
"""
## need to transform the ts index to a DatetimeIndex to be able to extract
## later the values by date
#my_observed_chik_ts.index = pd.DatetimeIndex(my_observed_chik_ts.index)
my_reduced_sol = pd.Series()
for i in my_observed_chik_ts.index:
my_reduced_sol[i] = my_sol[str(i)].mean()
return(my_reduced_sol)
#################################################################################
## def f_vector_distance(vector1, vector2)
def f_vector_distance(vector1, vector2):
"""
this function compute the distance between any two real-valued vectors
"""
dist = 0
#while len(vector1) == len(vector2):
for i in np.arange(0, len(vector1)):
dist = dist + (vector1[i] - vector2[i])**2
#else:
# print ("vector 1 and vector tw of the f_vector_distance functionmust be of equal length")
return(np.sqrt(dist))
#################################################################################
# r_squared (y_obs, y_model)
def r_squared (y_obs, y_model): # according to wikipedia
"""
NOTE: seemingly this function should not be applied to nonlinear models (!)
this function receives:
- an observed vector, y_obs
- a modeled or estimated vector, y_model.
this funtions gives back the Coeffiecient of Determination according the
Wikipedia definition
"""
SSTot = 0. # total sum of squares
SSReg = 0. # regression sum of squares