-
Notifications
You must be signed in to change notification settings - Fork 0
/
epiworld.hpp
12784 lines (9734 loc) · 338 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
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 100000
#endif
#ifdef EPIWORLD_USE_OMP
#include <omp.h>
#else
#ifndef epiworld_double
#define epiworld_double float
#endif
#ifndef epiworld_fast_int
#define epiworld_fast_int std::int_fast16_t
#endif
#ifndef epiworld_fast_uint
#define epiworld_fast_uint std::uint_fast16_t
#endif
#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 Tool;
template<typename TSeq = EPI_DEFAULT_TSEQ>
class Entity;
template<typename TSeq>
using VirusPtr = std::shared_ptr< Virus< TSeq > >;
template<typename TSeq>
using ToolPtr = std::shared_ptr< Tool< TSeq > >;
template<typename TSeq>
using ToolFun = std::function<epiworld_double(Tool<TSeq>&,Agent<TSeq>*,VirusPtr<TSeq>,Model<TSeq>*)>;
template<typename TSeq>
using MixerFun = std::function<epiworld_double(Agent<TSeq>*,VirusPtr<TSeq>,Model<TSeq>*)>;
template<typename TSeq>
using MutFun = std::function<bool(Agent<TSeq>*,Virus<TSeq>&,Model<TSeq>*)>;
template<typename TSeq>
using PostRecoveryFun = std::function<void(Agent<TSeq>*,Virus<TSeq>&,Model<TSeq>*)>;
template<typename TSeq>
using VirusFun = std::function<epiworld_double(Agent<TSeq>*,Virus<TSeq>&,Model<TSeq>*)>;
template<typename TSeq>
using UpdateFun = std::function<void(Agent<TSeq>*,Model<TSeq>*)>;
template<typename TSeq>
using GlobalFun = std::function<void(Model<TSeq>*)>;
template<typename TSeq>
struct Action;
template<typename TSeq>
using ActionFun = std::function<void(Action<TSeq>&,Model<TSeq>*)>;
/**
* @brief Decides how to distribute viruses at initialization
*/
template<typename TSeq>
using VirusToAgentFun = std::function<void(Virus<TSeq>&,Model<TSeq>*)>;
/**
* @brief Decides how to distribute tools at initialization
*/
template<typename TSeq>
using ToolToAgentFun = std::function<void(Tool<TSeq>&,Model<TSeq>*)>;
/**
* @brief Decides how to distribute entities at initialization
*/
template<typename TSeq>
using EntityToAgentFun = std::function<void(Entity<TSeq>&,Model<TSeq>*)>;
/**
* @brief Action data for update an agent
*
* @tparam TSeq
*/
template<typename TSeq>
struct Action {
Agent<TSeq> * agent;
VirusPtr<TSeq> virus;
ToolPtr<TSeq> tool;
Entity<TSeq> * entity;
epiworld_fast_int new_status;
epiworld_fast_int queue;
ActionFun<TSeq> call;
int idx_agent;
int idx_object;
public:
/**
* @brief Construct a new Action 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_status_ Next status
* @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.
*/
Action(
Agent<TSeq> * agent_,
VirusPtr<TSeq> virus_,
ToolPtr<TSeq> tool_,
Entity<TSeq> * entity_,
epiworld_fast_int new_status_,
epiworld_fast_int queue_,
ActionFun<TSeq> call_,
int idx_agent_,
int idx_object_
) : agent(agent_), virus(virus_), tool(tool_), entity(entity_),
new_status(new_status_),
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
///@}
#ifdef EPI_DEBUG
#define EPI_DEBUG_NOTIFY_ACTIVE() \
printf_epiworld("[epiworld-debug] DEBUGGING ON (compiled with EPI_DEBUG defined)\n");
#define EPI_DEBUG_ALL_NON_NEGATIVE(vect) \
for (auto & v : vect) \
if (static_cast<double>(v) < 0.0) \
throw 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 std::logic_error("[epiworld-debug] 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 std::logic_error("[epiworld-debug] The sum of elements not reached."); \
}
#define EPI_DEBUG_VECTOR_MATCH_INT(a, b) \
if (a.size() != b.size()) \
throw std::length_error("[epiworld-debug] The vectors do not match size."); \
for (size_t _i = 0u; _i < a.size(); ++_i) \
if (a[_i] != b[_i]) \
throw std::logic_error("[epiworld-debug] The vectors do not match.");
#else
#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)
#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 (unsigned int 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
class QueueValues {
public:
static const int NoOne = 0;
static const int OnlySelf = 1;
static const int Everyone = 2;
};
#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 (unsigned int i = 1u; i < dat.size(); ++i)
hash ^= hasher(dat[i]) + 0x9e3779b9 + (hash<<6) + (hash>>2);
return hash;
}
};
template<typename Ta = epiworld_double, typename Tb = unsigned int>
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();
// 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() {
if (_n_sequences_created == 2)
throw std::logic_error("Maximum number of sequence created.");
return _n_sequences_created++ ? false : true;
}
template<>
inline int default_sequence() {
return _n_sequences_created++;
}
template<>
inline epiworld_double default_sequence() {
return static_cast<epiworld_double>(_n_sequences_created++);
}
template<>
inline std::vector<bool> default_sequence() {
if (_n_sequences_created == 2)
throw std::logic_error("Maximum number of sequence created.");
return {_n_sequences_created++ ? false : true};
}
template<>
inline std::vector<int> default_sequence() {
return {_n_sequences_created++};
}
template<>
inline std::vector<epiworld_double> default_sequence() {
return {static_cast<epiworld_double>(_n_sequences_created++)};
}
///@}
/**
* @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>
inline int roulette(
const std::vector< epiworld_double > & probs,
Model<TSeq> * m
)
{
// Step 1: Computing the prob on none
epiworld_double p_none = 1.0;
std::vector< int > certain_infection;
certain_infection.reserve(probs.size());
for (unsigned int p = 0u; p < probs.size(); ++p)
{
p_none *= (1.0 - probs[p]);
if (probs[p] > (1 - 1e-100))
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 (certain_infection.size() > 0)
return certain_infection[std::floor(r * certain_infection.size())];
// Step 2: Calculating the prob of none or single
std::vector< epiworld_double > probs_only_p(probs.size());
epiworld_double p_none_or_single = p_none;
for (unsigned int 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
epiworld_double cumsum = p_none/p_none_or_single;
if (r < cumsum)
return -1;
for (unsigned int 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);
}
return static_cast<int>(probs.size() - 1u);
}
template<typename TSeq>
inline int roulette(
unsigned int nelements,
Model<TSeq> * m
)
{
#ifdef EPI_DEBUG
if (nelements > m->array_double_tmp.size())
throw std::logic_error("Trying to sample from more data than there is in roulette!");
#endif
// Step 1: Computing the prob on none
epiworld_double p_none = 1.0;
unsigned int ncertain = 0u;
// std::vector< int > certain_infection;
for (unsigned int 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 (unsigned int 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 (unsigned int 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_) {
width = std::max(7, width_ - 7);
n = n_;
step_size = static_cast<epiworld_double>(width)/static_cast<epiworld_double>(n);
last_loc = 0;
i = 0;
}
inline void Progress::start()
{
for (int j = 0; j < (width); ++j)
{
printf_epiworld("_");
}
printf_epiworld("\n");
}
inline void Progress::next() {
if (i == 0)
start();
cur_loc = std::floor((++i) * step_size);
for (int j = 0; j < (cur_loc - last_loc); ++j)
{
printf_epiworld("|");
}
if (i >= n)
end();
last_loc = cur_loc;
}
inline void Progress::end() {
printf_epiworld(" done.\n");
}
#endif
/*//////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
End of -include/epiworld/progress.hpp-
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////*/
// #include "math/summary-stats.hpp"
/*//////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
Start of -include/epiworld/math/lfmcmc.hpp-
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////*/
#ifndef EPIWORLD_LFMCMC_HPP
#define EPIWORLD_LFMCMC_HPP
/*//////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
Start of -include/epiworld//math/lfmcmc/lfmcmc-bones.hpp-
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////*/
#ifndef EPIWORLD_LFMCMC_BONES_HPP
#define EPIWORLD_LFMCMC_BONES_HPP
#ifndef epiworld_double
#define epiworld_double float
#endif
template<typename TData>
class LFMCMC;
template<typename TData>
using LFMCMCSimFun = std::function<TData(const std::vector< epiworld_double >&,LFMCMC<TData>*)>;
template<typename TData>
using LFMCMCSummaryFun = std::function<void(std::vector< epiworld_double >&,const TData&,LFMCMC<TData>*)>;
template<typename TData>
using LFMCMCProposalFun = std::function<void(std::vector< epiworld_double >&,const std::vector< epiworld_double >&,LFMCMC<TData>*)>;
template<typename TData>
using LFMCMCKernelFun = std::function<epiworld_double(const std::vector< epiworld_double >&,const std::vector< epiworld_double >&,epiworld_double,LFMCMC<TData>*)>;
/**
* @brief Proposal function
* @param params_now Vector where to save the new parameters.
* @param params_prev Vector of reference parameters.
* @param m LFMCMC model.
* @tparam TData
*/
template<typename TData>
inline void proposal_fun_normal(
std::vector< epiworld_double >& params_now,
const std::vector< epiworld_double >& params_prev,
LFMCMC<TData>* m
);
/**
* @brief Factory for a reflective normal kernel
*
* @details Reflective kernel corrects proposals by forcing them to be
* within prespecified boundaries.
*
* @tparam TData
* @param scale Scale of the normal kernel
* @param lb Lower bound (applies the same to all parameters)
* @param ub Upper bound (applies the same to all parameters)
* @return LFMCMCProposalFun<TData>
*/
template<typename TData>
inline LFMCMCProposalFun<TData> make_proposal_norm_reflective(
epiworld_double scale,
epiworld_double lb = std::numeric_limits<epiworld_double>::min(),
epiworld_double ub = std::numeric_limits<epiworld_double>::max()
);
/**
* @brief Uniform proposal kernel
*
* Proposals are made within a radious 1 of the current
* state of the parameters.
*
* @param params_now Where to write the new parameters
* @param params_prev Reference parameters
* @tparam TData
* @param m LFMCMC model.
*/
template<typename TData>
inline void proposal_fun_unif(
std::vector< epiworld_double >& params_now,
const std::vector< epiworld_double >& params_prev,
LFMCMC<TData>* m
);
/**
* @brief Uses the uniform kernel with euclidean distance
*
* @param stats_now Vector of current statistics based on
* simulated data.
* @param stats_obs Vector of observed statistics
* @param epsilon Epsilon parameter
* @param m LFMCMC model.
* @return epiworld_double
*/
template<typename TData>
inline epiworld_double kernel_fun_uniform(
const std::vector< epiworld_double >& stats_now,
const std::vector< epiworld_double >& stats_obs,
epiworld_double epsilon,
LFMCMC<TData>* m
);
/**
* @brief Gaussian kernel
*
* @tparam TData
* @param epsilon
* @param m
* @return epiworld_double
*/
template<typename TData>
inline epiworld_double kernel_fun_gaussian(
const std::vector< epiworld_double >& stats_now,
const std::vector< epiworld_double >& stats_obs,
epiworld_double epsilon,
LFMCMC<TData>* m
);
/**
* @brief Likelihood-Free Markov Chain Monte Carlo
*
* @tparam TData Type of data that is generated
*/
template<typename TData>
class LFMCMC {
private:
// Random number sampling
std::shared_ptr< std::mt19937 > engine =
std::make_shared< std::mt19937 >();
std::shared_ptr< std::uniform_real_distribution<> > runifd =
std::make_shared< std::uniform_real_distribution<> >(0.0, 1.0);
std::shared_ptr< std::normal_distribution<> > rnormd =
std::make_shared< std::normal_distribution<> >(0.0);
std::shared_ptr< std::gamma_distribution<> > rgammad =
std::make_shared< std::gamma_distribution<> >();
// Process data
TData * observed_data;
// Information about the size of the problem
size_t n_samples;
size_t n_statistics;
size_t n_parameters;
epiworld_double epsilon;
std::vector< epiworld_double > params_now;
std::vector< epiworld_double > params_prev;
std::vector< epiworld_double > params_init;
std::vector< epiworld_double > observed_stats; ///< Observed statistics
std::vector< epiworld_double > sampled_params; ///< Sampled Parameters
std::vector< epiworld_double > sampled_stats; ///< Sampled statistics
std::vector< epiworld_double > sampled_stats_prob; ///< Sampled statistics
std::vector< bool > sampled_accepted; ///< Indicator of accepted statistics
std::vector< epiworld_double > accepted_params; ///< Posterior distribution (accepted samples)
std::vector< epiworld_double > accepted_stats; ///< Posterior distribution (accepted samples)
std::vector< epiworld_double > accepted_params_prob; ///< Posterior probability
std::vector< epiworld_double > drawn_prob; ///< Drawn probabilities (runif())
std::vector< TData > * sampled_data = nullptr;
// Functions
LFMCMCSimFun<TData> simulation_fun;
LFMCMCSummaryFun<TData> summary_fun;
LFMCMCProposalFun<TData> proposal_fun = proposal_fun_normal<TData>;
LFMCMCKernelFun<TData> kernel_fun = kernel_fun_uniform<TData>;
// Misc
std::vector< std::string > names_parameters;
std::vector< std::string > names_statistics;
std::chrono::time_point<std::chrono::steady_clock> time_start;
std::chrono::time_point<std::chrono::steady_clock> time_end;
// std::chrono::milliseconds
std::chrono::duration<epiworld_double,std::micro> time_elapsed =
std::chrono::duration<epiworld_double,std::micro>::zero();
inline void get_elapsed(
std::string unit,
epiworld_double * last_elapsed,
std::string * unit_abbr,
bool print
);
void chrono_start();
void chrono_end();
public:
void run(
std::vector< epiworld_double > param_init, size_t n_samples_, epiworld_double epsilon_);
LFMCMC() {};
LFMCMC(TData & observed_data_) : observed_data(&observed_data_) {};
~LFMCMC() {};
void set_observed_data(TData & observed_data_) {observed_data = &observed_data_;};
void set_proposal_fun(LFMCMCProposalFun<TData> fun);
void set_simulation_fun(LFMCMCSimFun<TData> fun);
void set_summary_fun(LFMCMCSummaryFun<TData> fun);
void set_kernel_fun(LFMCMCKernelFun<TData> fun);
/**
* @name Random number generation
*
* @param eng
*/
///@{
void set_rand_engine(std::mt19937 & eng);
std::mt19937 * get_rand_endgine();
void seed(unsigned int s);
void set_rand_gamma(epiworld_double alpha, epiworld_double beta);
epiworld_double runif();
epiworld_double rnorm();
epiworld_double rgamma();
epiworld_double runif(epiworld_double lb, epiworld_double ub);
epiworld_double rnorm(epiworld_double mean, epiworld_double sd);
epiworld_double rgamma(epiworld_double alpha, epiworld_double beta);
///@}
// Accessing parameters of the function
const size_t get_n_samples() {return n_samples;};
const size_t get_n_statistics() {return n_statistics;};
const size_t get_n_parameters() {return n_parameters;};
const epiworld_double get_epsilon() {return epsilon;};
const std::vector< epiworld_double > & get_params_now() {return params_now;};
const std::vector< epiworld_double > & get_params_prev() {return params_prev;};