-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathepiworld.hpp
21329 lines (16357 loc) · 563 KB
/
epiworld.hpp
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
#include <vector>
#include <functional>
#include <memory>
#include <stdexcept>
#include <random>
#include <fstream>
#include <string>
#include <map>
#include <unordered_map>
#include <chrono>
#include <climits>
#include <cstdint>
#include <algorithm>
#include <regex>
#ifndef EPIWORLD_HPP
#define EPIWORLD_HPP
/* Versioning */
#define EPIWORLD_VERSION_MAJOR 0
#define EPIWORLD_VERSION_MINOR 7
#define EPIWORLD_VERSION_PATCH 0
static const int epiworld_version_major = EPIWORLD_VERSION_MAJOR;
static const int epiworld_version_minor = EPIWORLD_VERSION_MINOR;
static const int epiworld_version_patch = EPIWORLD_VERSION_PATCH;
namespace epiworld {
/*//////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
Start of -include/epiworld/config.hpp-
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////*/
#ifndef EPIWORLD_CONFIG_HPP
#define EPIWORLD_CONFIG_HPP
#ifndef printf_epiworld
#define printf_epiworld fflush(stdout);printf
#endif
#ifndef EPIWORLD_MAXNEIGHBORS
#define EPIWORLD_MAXNEIGHBORS 1048576
#endif
#if defined(_OPENMP) || defined(__OPENMP)
#include <omp.h>
// #else
// #define omp_get_thread_num() 0
// #define omp_set_num_threads() 1
#endif
#ifndef epiworld_double
#define epiworld_double float
#endif
#ifndef epiworld_fast_int
#define epiworld_fast_int long long int
#endif
#ifndef epiworld_fast_uint
#define epiworld_fast_uint unsigned long long int
#endif
#define EPI_DEFAULT_TSEQ int
template<typename TSeq = EPI_DEFAULT_TSEQ>
class Model;
template<typename TSeq = EPI_DEFAULT_TSEQ>
class Agent;
template<typename TSeq = EPI_DEFAULT_TSEQ>
class PersonTools;
template<typename TSeq = EPI_DEFAULT_TSEQ>
class Virus;
template<typename TSeq = EPI_DEFAULT_TSEQ>
class Viruses;
template<typename TSeq = EPI_DEFAULT_TSEQ>
class Viruses_const;
template<typename TSeq = EPI_DEFAULT_TSEQ>
class Tool;
template<typename TSeq = EPI_DEFAULT_TSEQ>
class Tools;
template<typename TSeq = EPI_DEFAULT_TSEQ>
class Tools_const;
template<typename TSeq = EPI_DEFAULT_TSEQ>
class Entity;
template<typename TSeq = EPI_DEFAULT_TSEQ>
using VirusPtr = std::shared_ptr< Virus< TSeq > >;
template<typename TSeq = EPI_DEFAULT_TSEQ>
using ToolPtr = std::shared_ptr< Tool< TSeq > >;
template<typename TSeq = EPI_DEFAULT_TSEQ>
using ToolFun = std::function<epiworld_double(Tool<TSeq>&,Agent<TSeq>*,VirusPtr<TSeq>,Model<TSeq>*)>;
template<typename TSeq = EPI_DEFAULT_TSEQ>
using MixerFun = std::function<epiworld_double(Agent<TSeq>*,VirusPtr<TSeq>,Model<TSeq>*)>;
template<typename TSeq = EPI_DEFAULT_TSEQ>
using MutFun = std::function<bool(Agent<TSeq>*,Virus<TSeq>&,Model<TSeq>*)>;
template<typename TSeq = EPI_DEFAULT_TSEQ>
using PostRecoveryFun = std::function<void(Agent<TSeq>*,Virus<TSeq>&,Model<TSeq>*)>;
template<typename TSeq = EPI_DEFAULT_TSEQ>
using VirusFun = std::function<epiworld_double(Agent<TSeq>*,Virus<TSeq>&,Model<TSeq>*)>;
template<typename TSeq = EPI_DEFAULT_TSEQ>
using UpdateFun = std::function<void(Agent<TSeq>*,Model<TSeq>*)>;
template<typename TSeq = EPI_DEFAULT_TSEQ>
using GlobalFun = std::function<void(Model<TSeq>*)>;
template<typename TSeq>
struct Event;
template<typename TSeq = EPI_DEFAULT_TSEQ>
using EventFun = std::function<void(Event<TSeq>&,Model<TSeq>*)>;
/**
* @brief Decides how to distribute viruses at initialization
*/
template<typename TSeq = EPI_DEFAULT_TSEQ>
using VirusToAgentFun = std::function<void(Virus<TSeq>&,Model<TSeq>*)>;
/**
* @brief Decides how to distribute tools at initialization
*/
template<typename TSeq = EPI_DEFAULT_TSEQ>
using ToolToAgentFun = std::function<void(Tool<TSeq>&,Model<TSeq>*)>;
/**
* @brief Decides how to distribute entities at initialization
*/
template<typename TSeq = EPI_DEFAULT_TSEQ>
using EntityToAgentFun = std::function<void(Entity<TSeq>&,Model<TSeq>*)>;
/**
* @brief Event data for update an agent
*
* @tparam TSeq
*/
template<typename TSeq = EPI_DEFAULT_TSEQ>
struct Event {
Agent<TSeq> * agent;
VirusPtr<TSeq> virus;
ToolPtr<TSeq> tool;
Entity<TSeq> * entity;
epiworld_fast_int new_state;
epiworld_fast_int queue;
EventFun<TSeq> call;
int idx_agent;
int idx_object;
public:
/**
* @brief Construct a new Event object
*
* All the parameters are rather optional.
*
* @param agent_ Agent over who the action will happen
* @param virus_ Virus to add
* @param tool_ Tool to add
* @param virus_idx Index of virus to be removed (if needed)
* @param tool_idx Index of tool to be removed (if needed)
* @param new_state_ Next state
* @param queue_ Efect on the queue
* @param call_ The action call (if needed)
* @param idx_agent_ Location of agent in object.
* @param idx_object_ Location of object in agent.
*/
Event(
Agent<TSeq> * agent_,
VirusPtr<TSeq> virus_,
ToolPtr<TSeq> tool_,
Entity<TSeq> * entity_,
epiworld_fast_int new_state_,
epiworld_fast_int queue_,
EventFun<TSeq> call_,
int idx_agent_,
int idx_object_
) : agent(agent_), virus(virus_), tool(tool_), entity(entity_),
new_state(new_state_),
queue(queue_), call(call_), idx_agent(idx_agent_), idx_object(idx_object_) {
return;
};
};
/**
* @name Constants in epiworld
*
* @details The following are the default values some probabilities and
* rates take when no value has been specified in the model.
*/
///@{
#ifndef DEFAULT_TOOL_CONTAGION_REDUCTION
#define DEFAULT_TOOL_CONTAGION_REDUCTION 0.0
#endif
#ifndef DEFAULT_TOOL_TRANSMISSION_REDUCTION
#define DEFAULT_TOOL_TRANSMISSION_REDUCTION 0.0
#endif
#ifndef DEFAULT_TOOL_RECOVERY_ENHANCER
#define DEFAULT_TOOL_RECOVERY_ENHANCER 0.0
#endif
#ifndef DEFAULT_TOOL_DEATH_REDUCTION
#define DEFAULT_TOOL_DEATH_REDUCTION 0.0
#endif
#ifndef EPI_DEFAULT_VIRUS_PROB_INFECTION
#define EPI_DEFAULT_VIRUS_PROB_INFECTION 1.0
#endif
#ifndef EPI_DEFAULT_VIRUS_PROB_RECOVERY
#define EPI_DEFAULT_VIRUS_PROB_RECOVERY 0.1428
#endif
#ifndef EPI_DEFAULT_VIRUS_PROB_DEATH
#define EPI_DEFAULT_VIRUS_PROB_DEATH 0.0
#endif
#ifndef EPI_DEFAULT_INCUBATION_DAYS
#define EPI_DEFAULT_INCUBATION_DAYS 7.0
#endif
///@}
#ifdef EPI_DEBUG
#define EPI_DEBUG_PRINTF printf_epiworld
#define EPI_DEBUG_ERROR(etype, msg) \
(etype)("[[epi-debug]] (error) " + std::string(msg));
#define EPI_DEBUG_NOTIFY_ACTIVE() \
EPI_DEBUG_PRINTF("DEBUGGING ON (compiled with EPI_DEBUG defined)%s\n", "");
#define EPI_DEBUG_ALL_NON_NEGATIVE(vect) \
for (auto & v : vect) \
if (static_cast<double>(v) < 0.0) \
throw EPI_DEBUG_ERROR(std::logic_error, "A negative value not allowed.");
#define EPI_DEBUG_SUM_DBL(vect, num) \
double _epi_debug_sum = 0.0; \
for (auto & v : vect) \
{ \
_epi_debug_sum += static_cast<double>(v);\
if (_epi_debug_sum > static_cast<double>(num)) \
throw EPI_DEBUG_ERROR(std::logic_error, "The sum of elements not reached."); \
}
#define EPI_DEBUG_SUM_INT(vect, num) \
int _epi_debug_sum = 0; \
for (auto & v : vect) \
{ \
_epi_debug_sum += static_cast<int>(v);\
if (_epi_debug_sum > static_cast<int>(num)) \
throw EPI_DEBUG_ERROR(std::logic_error, "The sum of elements not reached."); \
}
#define EPI_DEBUG_VECTOR_MATCH_INT(a, b, c) \
if (a.size() != b.size()) {\
EPI_DEBUG_PRINTF("In '%s'", std::string(c).c_str()); \
EPI_DEBUG_PRINTF("Size of vector a: %lu\n", (a).size());\
EPI_DEBUG_PRINTF("Size of vector b: %lu\n", (b).size());\
throw EPI_DEBUG_ERROR(std::length_error, "The vectors do not match size."); \
}\
for (int _i = 0; _i < static_cast<int>(a.size()); ++_i) \
if (a[_i] != b[_i]) {\
EPI_DEBUG_PRINTF("In '%s'", std::string(c).c_str()); \
EPI_DEBUG_PRINTF("Iterating the last 5 values%s:\n", ""); \
for (int _j = std::max(0, static_cast<int>(_i) - 4); _j <= _i; ++_j) \
{ \
EPI_DEBUG_PRINTF( \
"a[%i]: %i; b[%i]: %i\n", \
_j, \
static_cast<int>(a[_j]), \
_j, static_cast<int>(b[_j])); \
} \
throw EPI_DEBUG_ERROR(std::logic_error, "The vectors do not match."); \
}
#define EPI_DEBUG_FAIL_AT_TRUE(a,b) \
if (a) \
{\
throw EPI_DEBUG_ERROR(std::logic_error, b); \
}
#define epiexception(a) std::logic_error
#else
#define EPI_DEBUG_PRINTF(fmt, ...)
#define EPI_DEBUG_ERROR(fmt, ...)
#define EPI_DEBUG_NOTIFY_ACTIVE()
#define EPI_DEBUG_ALL_NON_NEGATIVE(vect)
#define EPI_DEBUG_SUM_DBL(vect, num)
#define EPI_DEBUG_SUM_INT(vect, num)
#define EPI_DEBUG_VECTOR_MATCH_INT(a, b, c)
#define EPI_DEBUG_FAIL_AT_TRUE(a, b) \
if (a) \
return false;
#define epiexception(a) a
#endif
#if defined(EPI_DEBUG_NO_THREAD_ID) || (!defined(__OPENMP) && !defined(_OPENMP))
#define EPI_GET_THREAD_ID() 0
#else
#define EPI_GET_THREAD_ID() omp_get_thread_num()
#endif
#endif
/*//////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
End of -include/epiworld/config.hpp-
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////*/
/*//////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
Start of -include/epiworld/epiworld-macros.hpp-
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////*/
#ifndef EPIWORLD_MACROS_HPP
#define EPIWORLD_MACROS_HPP
/**
* @brief Helper macro to define a new tool
*
*/
#define EPI_NEW_TOOL(fname,tseq) inline epiworld_double \
(fname)(\
epiworld::Tool< tseq > & t, \
epiworld::Agent< tseq > * p, \
std::shared_ptr<epiworld::Virus< tseq >> v, \
epiworld::Model< tseq > * m\
)
/**
* @brief Create a Tool within a function
*
*/
#define EPI_NEW_TOOL_LAMBDA(funname,tseq) \
epiworld::ToolFun<tseq> funname = \
[](epiworld::Tool<tseq> & t, \
epiworld::Agent<tseq> * p, \
std::shared_ptr<epiworld::Virus<tseq>> v, \
epiworld::Model<tseq> * m) -> epiworld_double
/**
* @brief Helper macro for accessing model parameters
*
*/
#define EPI_PARAMS(i) m->operator()(i)
/**
* @brief Helper macro for defining Mutation Functions
*
*/
#define EPI_NEW_MUTFUN(funname,tseq) inline bool \
(funname)(\
epiworld::Agent<tseq> * p, \
epiworld::Virus<tseq> & v, \
epiworld::Model<tseq> * m )
#define EPI_NEW_MUTFUN_LAMBDA(funname,tseq) \
epiworld::MutFun<tseq> funname = \
[](epiworld::Agent<tseq> * p, \
epiworld::Virus<tseq> & v, \
epiworld::Model<tseq> * m) -> void
#define EPI_NEW_POSTRECOVERYFUN(funname,tseq) inline void \
(funname)( \
epiworld::Agent<tseq> * p, \
epiworld::Virus<tseq> & v, \
epiworld::Model<tseq> * m\
)
#define EPI_NEW_POSTRECOVERYFUN_LAMBDA(funname,tseq) \
epiworld::PostRecoveryFun<tseq> funname = \
[](epiworld::Agent<tseq> * p, \
epiworld::Virus<tseq> & v , \
epiworld::Model<tseq> * m) -> void
#define EPI_NEW_VIRUSFUN(funname,tseq) inline epiworld_double \
(funname)( \
epiworld::Agent<tseq> * p, \
epiworld::Virus<tseq> & v, \
epiworld::Model<tseq> * m\
)
#define EPI_NEW_VIRUSFUN_LAMBDA(funname,TSeq) \
epiworld::VirusFun<TSeq> funname = \
[](epiworld::Agent<TSeq> * p, \
epiworld::Virus<TSeq> & v, \
epiworld::Model<TSeq> * m) -> epiworld_double
#define EPI_RUNIF() m->runif()
#define EPIWORLD_RUN(a) \
if (a.get_verbose()) \
{ \
printf_epiworld("Running the model...\n");\
} \
for (epiworld_fast_uint niter = 0; niter < a.get_ndays(); ++niter)
#define EPI_TOKENPASTE(a,b) a ## b
#define MPAR(num) *(m->EPI_TOKENPASTE(p,num))
#define EPI_NEW_UPDATEFUN(funname,tseq) inline void \
(funname)(epiworld::Agent<tseq> * p, epiworld::Model<tseq> * m)
#define EPI_NEW_UPDATEFUN_LAMBDA(funname,tseq) \
epiworld::UpdateFun<tseq> funname = \
[](epiworld::Agent<tseq> * p, epiworld::Model<tseq> * m) -> void
#define EPI_NEW_GLOBALFUN(funname,tseq) inline void \
(funname)(epiworld::Model<tseq>* m)
#define EPI_NEW_GLOBALFUN_LAMBDA(funname,tseq) \
epiworld::GlobalFun<tseq> funname = \
[](epiworld::Model<tseq>* m) -> void
#define EPI_NEW_ENTITYTOAGENTFUN(funname,tseq) inline void \
(funname)(epiworld::Entity<tseq> & e, epiworld::Model<tseq> * m)
#define EPI_NEW_ENTITYTOAGENTFUN_LAMBDA(funname,tseq) \
epiworld::EntityToAgentFun<tseq> funname = \
[](epiworld::Entity<tseq> & e, epiworld::Model<tseq> * m) -> void
#endif
/*//////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
End of -include/epiworld/epiworld-macros.hpp-
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////*/
/*//////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
Start of -include/epiworld/misc.hpp-
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////*/
#ifndef EPIWORLD_MISC_HPP
#define EPIWORLD_MISC_HPP
template<typename TSeq>
class Model;
template<typename TSeq>
class Agent;
// Relevant for anything using vecHasher function ------------------------------
/**
* @brief Vector hasher
* @tparam T
*/
template <typename T>
struct vecHasher {
std::size_t operator()(std::vector< T > const& dat) const noexcept {
std::hash< T > hasher;
std::size_t hash = hasher(dat[0u]);
// ^ makes bitwise XOR
// 0x9e3779b9 is a 32 bit constant (comes from the golden ratio)
// << is a shift operator, something like lhs * 2^(rhs)
if (dat.size() > 1u)
for (epiworld_fast_uint i = 1u; i < dat.size(); ++i)
hash ^= hasher(dat[i]) + 0x9e3779b9 + (hash<<6) + (hash>>2);
return hash;
}
};
template<typename Ta = epiworld_double, typename Tb = epiworld_fast_uint>
using MapVec_type = std::unordered_map< std::vector< Ta >, Tb, vecHasher<Ta>>;
/**
* @name Default sequence initializers
*
* @details
* If the user does not provide a default sequence, this function is used when
* a sequence needs to be initialized. Some examples: `Agent`, `Virus`, and
* `Tool` need a default sequence.
*
* @tparam TSeq
* @return TSeq
*/
///@{
template<typename TSeq = int>
inline TSeq default_sequence(int seq_count);
// Making it 'static' so that we don't have problems when including the
// header. This is important during the linkage, e.g., in R.
// See https://en.cppreference.com/w/cpp/language/storage_duration#Linkage
// static int _n_sequences_created = 0;
template<>
inline bool default_sequence(int seq_count) {
if (seq_count == 2)
throw std::logic_error("Maximum number of sequence created.");
return seq_count++ ? false : true;
}
template<>
inline int default_sequence(int seq_count) {
return seq_count++;
}
template<>
inline epiworld_double default_sequence(int seq_count) {
return static_cast<epiworld_double>(seq_count++);
}
template<>
inline std::vector<bool> default_sequence(int seq_count) {
if (seq_count == 2)
throw std::logic_error("Maximum number of sequence created.");
return {seq_count++ ? false : true};
}
template<>
inline std::vector<int> default_sequence(int seq_count) {
return {seq_count++};
}
template<>
inline std::vector<epiworld_double> default_sequence(int seq_count) {
return {static_cast<epiworld_double>(seq_count++)};
}
///@}
/**
* @brief Check whether `a` is included in `b`
*
* @tparam Ta Type of `a`. Could be int, epiworld_double, etc.
* @param a Scalar of class `Ta`.
* @param b Vector `std::vector` of class `Ta`.
* @return `true` if `a in b`, and `false` otherwise.
*/
template<typename Ta>
inline bool IN(const Ta & a, const std::vector< Ta > & b) noexcept
{
for (const auto & i : b)
if (a == i)
return true;
return false;
}
/**
* @brief Conditional Weighted Sampling
*
* @details
* The sampling function will draw one of `{-1, 0,...,probs.size() - 1}` in a
* weighted fashion. The probabilities are drawn given that either one or none
* of the cases is drawn; in the latter returns -1.
*
* @param probs Vector of probabilities.
* @param m A `Model`. This is used to draw random uniform numbers.
* @return int If -1 then it means that none got sampled, otherwise the index
* of the entry that got drawn.
*/
template<typename TSeq = EPI_DEFAULT_TSEQ, typename TDbl = epiworld_double >
inline int roulette(
const std::vector< TDbl > & probs,
Model<TSeq> * m
)
{
// Step 1: Computing the prob on none
TDbl p_none = 1.0;
std::vector< int > certain_infection;
certain_infection.reserve(probs.size());
for (epiworld_fast_uint p = 0u; p < probs.size(); ++p)
{
p_none *= (1.0 - probs[p]);
if (probs[p] > (1 - 1e-100))
certain_infection.push_back(p);
}
TDbl r = static_cast<TDbl>(m->runif());
// If there are one or more probs that go close to 1, sample
// uniformly
if (certain_infection.size() > 0)
return certain_infection[std::floor(r * certain_infection.size())];
// Step 2: Calculating the prob of none or single
std::vector< TDbl > probs_only_p(probs.size());
TDbl p_none_or_single = p_none;
for (epiworld_fast_uint p = 0u; p < probs.size(); ++p)
{
probs_only_p[p] = probs[p] * (p_none / (1.0 - probs[p]));
p_none_or_single += probs_only_p[p];
}
// Step 3: Roulette
TDbl cumsum = p_none/p_none_or_single;
if (r < cumsum)
{
return -1;
}
for (epiworld_fast_uint p = 0u; p < probs.size(); ++p)
{
// If it yield here, then bingo, the individual will acquire the disease
cumsum += probs_only_p[p]/(p_none_or_single);
if (r < cumsum)
return static_cast<int>(p);
}
#ifdef EPI_DEBUG
printf_epiworld("[epi-debug] roulette::cumsum = %.4f\n", cumsum);
#endif
return static_cast<int>(probs.size() - 1u);
}
template<typename TSeq>
inline int roulette(std::vector< double > & probs, Model<TSeq> * m)
{
return roulette<TSeq, double>(probs, m);
}
template<typename TSeq>
inline int roulette(std::vector< float > & probs, Model<TSeq> * m)
{
return roulette<TSeq, float>(probs, m);
}
template<typename TSeq>
inline int roulette(
epiworld_fast_uint nelements,
Model<TSeq> * m
)
{
if ((nelements * 2) > m->array_double_tmp.size())
{
throw std::logic_error(
"Trying to sample from more data than there is in roulette!" +
std::to_string(nelements) + " vs " +
std::to_string(m->array_double_tmp.size())
);
}
// Step 1: Computing the prob on none
epiworld_double p_none = 1.0;
epiworld_fast_uint ncertain = 0u;
// std::vector< int > certain_infection;
for (epiworld_fast_uint p = 0u; p < nelements; ++p)
{
p_none *= (1.0 - m->array_double_tmp[p]);
if (m->array_double_tmp[p] > (1 - 1e-100))
m->array_double_tmp[nelements + ncertain++] = p;
// certain_infection.push_back(p);
}
epiworld_double r = m->runif();
// If there are one or more probs that go close to 1, sample
// uniformly
if (ncertain > 0u)
return m->array_double_tmp[nelements + std::floor(ncertain * r)]; // certain_infection[std::floor(r * certain_infection.size())];
// Step 2: Calculating the prob of none or single
// std::vector< epiworld_double > probs_only_p;
epiworld_double p_none_or_single = p_none;
for (epiworld_fast_uint p = 0u; p < nelements; ++p)
{
m->array_double_tmp[nelements + p] =
m->array_double_tmp[p] * (p_none / (1.0 - m->array_double_tmp[p]));
p_none_or_single += m->array_double_tmp[nelements + p];
}
// Step 3: Roulette
epiworld_double cumsum = p_none/p_none_or_single;
if (r < cumsum)
return -1;
for (epiworld_fast_uint p = 0u; p < nelements; ++p)
{
// If it yield here, then bingo, the individual will acquire the disease
cumsum += m->array_double_tmp[nelements + p]/(p_none_or_single);
if (r < cumsum)
return static_cast<int>(p);
}
return static_cast<int>(nelements - 1u);
}
#endif
/*//////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
End of -include/epiworld/misc.hpp-
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////*/
/*//////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
Start of -include/epiworld/progress.hpp-
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////*/
#ifndef EPIWORLD_PROGRESS_HPP
#define EPIWORLD_PROGRESS_HPP
#ifndef EPIWORLD_PROGRESS_BAR_WIDTH
#define EPIWORLD_PROGRESS_BAR_WIDTH 80
#endif
/**
* @brief A simple progress bar
*/
class Progress {
private:
int width; ///< Total width size (number of bars)
int n; ///< Total number of iterations
epiworld_double step_size; ///< Size of the step
int last_loc; ///< Last location of the bar
int cur_loc; ///< Last location of the bar
int i; ///< Current iteration step
public:
Progress() {};
Progress(int n_, int width_);
~Progress() {};
void start();
void next();
void end();
};
inline Progress::Progress(int n_, int width_) {
if (n_ < 0)
throw std::invalid_argument("n must be greater or equal than 0.");
if (width_ <= 0)
throw std::invalid_argument("width must be greater than 0");
width = std::max(7, width_ - 7);
n = n_;
step_size = n == 0? width : static_cast<epiworld_double>(width)/
static_cast<epiworld_double>(n);
last_loc = 0;
i = 0;
}
inline void Progress::start()
{
#ifndef EPI_DEBUG
for (int j = 0; j < (width); ++j)
{
printf_epiworld("_");
}
printf_epiworld("\n");
#endif
}
inline void Progress::next() {
if (i == 0)
start();
cur_loc = std::floor((++i) * step_size);
#ifndef EPI_DEBUG
for (int j = 0; j < (cur_loc - last_loc); ++j)
{
printf_epiworld("|");
}
#endif
if (i >= n)
end();
last_loc = cur_loc;
}
inline void Progress::end() {
#ifndef EPI_DEBUG
printf_epiworld(" done.\n");
#endif
}
#endif
/*//////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
End of -include/epiworld/progress.hpp-
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////*/
/*//////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
Start of -include/epiworld/math/distributions.hpp-
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////*/
#ifndef EPIWORLD_MATH_DISTRIBUTIONS_HPP
#define EPIWORLD_MATH_DISTRIBUTIONS_HPP
// Implementing the factorial function
/**
* @brief Compute the log of the factorial
*
* @param n Number
*
* @return The log of the factorial
*/
inline double log_factorial(int n)
{
if (n == 0)
return 0.0;
return std::log(static_cast<double>(n)) + log_factorial(n-1);
}
/**
* @brief Compute the Poisson probability
*
* @param k Number of events
* @param lambda Rate
* @param max_n Maximum number of events
* @param as_log Return the log of the probability
*
* @return The Poisson probability
*/
inline double dpois(
int k,
double lambda,
int max_n = 100,
bool as_log = false
)
{
if (max_n < k)
throw std::runtime_error("max_n must be greater than k");
double res = k * std::log(lambda) - lambda - log_factorial(
std::min(k, max_n)
);
return as_log ? res : std::exp(res);
}
/**
* @brief Compute the probability of the generation interval
*
* @details
* If `p_0_approx` is negative, it will be computed using the Poisson
* distribution. If `normalizing` is negative, it will be computed on the fly
*
* @param g Generation interval
* @param S Population size
* @param p_c Probability of contact
* @param p_i Probability of infection
* @param p_r Probability of recovery
* @param p_0_approx Approximation of the probability of not being infected
* @param normalizing Normalizing constant
* @param max_contacts Maximum number of contacts
* @param max_days Maximum number of days
*
* @return The probability of the generation interval
*
*/
inline double dgenint(
int g,
double S,
double p_c,
double p_i,
double p_r,
double & p_0_approx,
double & normalizing,
int max_contacts = 200,
int max_days = 200
) {
if ((g < 1) || (g > max_days))
return 0.0;
if (p_0_approx < 0.0)
{
p_0_approx = 0.0;
for (int i = 0; i < max_contacts; ++i)
{
p_0_approx += std::exp(
dpois(i, S * p_c, max_contacts, true) +
std::log(1.0 - p_i) * static_cast<double>(i)
);
}
}
double g_dbl = static_cast<double>(g);
if (normalizing < 0.0)
{
normalizing = 1.0;
double log1_p_r = std::log(1.0 - p_r);
double log_p_r = std::log(p_r);
double log_p_0_approx = std::log(p_0_approx);
for (int i = 1; i <= max_days; ++i)
{
double i_dbl = static_cast<double>(i);
normalizing -= std::exp(
log1_p_r * (i_dbl - 1.0) +
log_p_r +
log_p_0_approx * (i_dbl - 1.0)
);
}
}
return std::exp(
std::log(1 - p_r) * (g_dbl)+
std::log(p_0_approx) * (g_dbl - 1.0) +
std::log(1.0 - p_0_approx) -
std::log(normalizing)
);
}
// Mean of the generation interval
/**
* @brief Compute the mean of the generation interval
* @param S Population size.
* @param p_c Probability of contact.
* @param p_i Probability of infection.
* @param p_r Probability of recovery.
* @param max_days Maximum number of days.