-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathSymWorld.h
More file actions
1463 lines (1319 loc) · 52.5 KB
/
Copy pathSymWorld.h
File metadata and controls
1463 lines (1319 loc) · 52.5 KB
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
#ifndef SYM_WORLD_H
#define SYM_WORLD_H
#include "SpatialStructure.h"
#include "../../Empirical/include/emp/Evolve/World.hpp"
#include "../../Empirical/include/emp/data/DataFile.hpp"
#include "../../Empirical/include/emp/Evolve/Systematics.hpp"
#include "../../Empirical/include/emp/math/random_utils.hpp"
#include "../../Empirical/include/emp/math/Random.hpp"
#include "../../Empirical/include/emp/matching/MatchBin.hpp"
#include "../spatial_utils.h"
#include "../Organism.h"
#include <cstdlib>
#include <set>
#include <math.h>
#include <unordered_map>
namespace taxon_t {
using info_t = double;
using base_taxon_t = emp::Taxon<info_t, datastruct::TaxonDataBase>;
using host_taxon_t = emp::Taxon<info_t, datastruct::HostTaxonData>;
using sym_taxon_t = emp::Taxon<info_t, datastruct::SymbiontTaxonData>;
}
class SymWorld : public emp::World<Organism> {
public:
using base_world_t = emp::World<Organism>;
// takes an organism (to classify), and returns an int (the org's taxon)
using fun_calc_info_t = std::function<taxon_t::info_t(Organism &)>;
using tag_t = emp::BitSet<TAG_LENGTH>;
using tag_metric_t = emp::BaseMetric<tag_t, tag_t>;
using pop_t = typename emp::World<Organism>::pop_t;
using host_systematics_t = emp::Systematics<Organism, taxon_t::info_t, datastruct::HostTaxonData>;
using sym_systematics_t = emp::Systematics<Organism, taxon_t::info_t, datastruct::SymbiontTaxonData>;
enum class SPATIAL_STRUCT_MODE { WELL_MIXED, GRID, LOAD };
static const std::unordered_map<std::string, SPATIAL_STRUCT_MODE> spatial_struct_mode_cfg_mapping;
enum class PHYLO_TAXON_TYPE { INTERACTION_VALUE_BINNED, INTERACTION_VALUE_EXACT, TAG, INDIVIDUAL };
static const std::unordered_map<std::string, PHYLO_TAXON_TYPE> phylo_taxon_type_cfg_mapping;
enum class TAG_METRIC_TYPE { HAMMING, STREAK, HASH };
static const std::unordered_map<std::string, TAG_METRIC_TYPE> tag_metric_type_cfg_mapping;
protected:
/**
*
* Purpose: Represents the total resources in the world. This can be set with SetTotalRes()
*
*/
int total_res = -1;
/**
*
* Purpose: Represents the free living sym environment, parallel to "pop" for hosts
*
*/
pop_t sym_pop;
/**
*
* Purpose: Represents the set of organisms which have been unlinked from
* their standard managing structures and need to be deleted at the end
* of every update.
*
*/
emp::vector<emp::Ptr<Organism>> graveyard = {};
/**
*
* Purpose: Represents a standard function object which determines which taxon an organism belongs to.
*
*/
fun_calc_info_t calc_host_info_fun;
/**
*
* Purpose: Represents a standard function object which determines which taxon a symbiont belongs to.
*
*/
fun_calc_info_t calc_sym_info_fun;
/**
*
* Purpose: Represents the configuration settings for a particular run.
*
*/
emp::Ptr<SymConfigBase> my_config = NULL;
/**
*
* Purpose: Represents the systematics object tracking hosts.
*
*/
emp::Ptr<host_systematics_t> host_sys;
/**
*
* Purpose: Represents the systematics object tracking symbionts.
*
*/
emp::Ptr<sym_systematics_t> sym_sys;
/**
* Purpose: Tracks world configuration for phylogeny taxon type.
*/
PHYLO_TAXON_TYPE phylo_taxon_type;
/**
*
* Purpose: Represents the tag distance calculator.
*
*/
emp::Ptr<tag_metric_t> tag_metric;
/**
* Purpose: Tracks world configuration for tag metric type.
*/
TAG_METRIC_TYPE tag_metric_type;
/**
*
* Purpose: Maintains population's spatial structure represented as a graph,
* except when using a well-mixed population (this is not used to
* store a fully connected graph for efficiency reasons).
*/
SpatialStructure spatial_structure;
/**
*
* Purpose: Tracks whether spatial structure has been configured
*
*/
bool setup_spatial_structure = false;
/**
* Purpose: Stores which spatial structure mode the world is configured as.
*/
SPATIAL_STRUCT_MODE spatial_struct_mode;
emp::Ptr<emp::DataMonitor<double, emp::data::Histogram>> data_node_hostintval; // New() reallocates this pointer
emp::Ptr<emp::DataMonitor<double, emp::data::Histogram>> data_node_symintval;
emp::Ptr<emp::DataMonitor<double, emp::data::Histogram>> data_node_freesymintval;
emp::Ptr<emp::DataMonitor<double, emp::data::Histogram>> data_node_hostedsymintval;
emp::Ptr<emp::DataMonitor<double, emp::data::Histogram>> data_node_syminfectchance;
emp::Ptr<emp::DataMonitor<double, emp::data::Histogram>> data_node_freesyminfectchance;
emp::Ptr<emp::DataMonitor<double, emp::data::Histogram>> data_node_hostedsyminfectchance;
emp::Ptr<emp::DataMonitor<double, emp::data::Histogram>> data_node_tag_dist;
emp::Ptr<emp::DataMonitor<double, emp::data::Histogram>> data_node_within_host_variance; // for alpha diversity
emp::Ptr<emp::DataMonitor<double, emp::data::Histogram>> data_node_within_host_mean; // for beta diversity
emp::Ptr<emp::DataMonitor<size_t>> data_node_host_repro_count;
emp::Ptr<emp::DataMonitor<size_t>> data_node_sym_repro_count;
emp::Ptr<emp::DataMonitor<double>> data_node_host_towards_partner_rate;
emp::Ptr<emp::DataMonitor<double>> data_node_host_from_partner_rate;
emp::Ptr<emp::DataMonitor<double>> data_node_sym_towards_partner_rate;
emp::Ptr<emp::DataMonitor<double>> data_node_sym_from_partner_rate;
emp::Ptr<emp::DataMonitor<double>> data_node_host_permissiveness;
emp::Ptr<emp::DataMonitor<int>> data_node_host_tag_richness;
emp::Ptr<emp::DataMonitor<double>> data_node_host_tag_shannon;
emp::Ptr<emp::DataMonitor<int>> data_node_symbiont_tag_richness;
emp::Ptr<emp::DataMonitor<double>> data_node_symbiont_tag_shannon;
emp::Ptr<emp::DataMonitor<int>> data_node_hostcount;
emp::Ptr<emp::DataMonitor<int>> data_node_symcount;
emp::Ptr<emp::DataMonitor<int>> data_node_freesymcount;
emp::Ptr<emp::DataMonitor<int>> data_node_hostedsymcount;
emp::Ptr<emp::DataMonitor<int>> data_node_uninf_hosts;
emp::Ptr<emp::DataMonitor<double, emp::data::Histogram>> data_node_attempts_horiztrans;
emp::Ptr<emp::DataMonitor<double, emp::data::Histogram>> data_node_tagfail_horiztrans;
emp::Ptr<emp::DataMonitor<double, emp::data::Histogram>> data_node_sizefail_horiztrans;
emp::Ptr<emp::DataMonitor<double, emp::data::Histogram>> data_node_successes_horiztrans;
emp::Ptr<emp::DataMonitor<double, emp::data::Histogram>> data_node_attempts_verttrans;
emp::Ptr<emp::DataMonitor<double, emp::data::Histogram>> data_node_successes_verttrans;
// the taxon IDs of the first mutualistic pair (where BOTH sym and host are mutualistic)
uint64_t first_mut_sym = 0;
uint64_t first_mut_host = 0;
emp::Signal<void()> on_analyze_population_sig;
// SetupHosts and SetupSymbionts are protected because they assume that
// SetupSpatialStructure has been called prior to hosts/symbionts getting setup.
virtual void SetupHosts(long unsigned int* POP_SIZE);
virtual void SetupSymbionts(long unsigned int* total_syms);
/**
* Input: The size_t representing the world's new width;
* the size_t representing the world's new height.
*
* Output: None
*
* Purpose: To overwrite the Empirical resize so that sym_pop is also resized
*/
void Resize(size_t new_width, size_t new_height) {
const size_t new_size = new_width * new_height;
Resize(new_size);
pop_sizes.resize(2);
pop_sizes[0] = new_width; pop_sizes[1] = new_height;
}
/**
* Input: The size_t representing the new size of the world
*
* Output: None
*
* Purpose: To override the Empirical Resize function with
* a single-arg method that can be used for AddOrgAt vector
* expansions
*/
void Resize(size_t new_size) {
// TODO: Update to include organism removal?
pop.resize(new_size);
sym_pop.resize(new_size);
}
/**
* Purpose: Internal setup helper function to hold setup-time configuration for
* different spatial structure modes.
*/
void SetupSpatialStructure();
/**
* Purpose: Internal setup helper function used by SetupSpatialStructure().
*/
void SetupSpatialStructure_WellMixed();
/**
* Purpose: Internal setup helper function used by SetupSpatialStructure().
*/
void SetupSpatialStructure_Grid();
/**
* Purpose: Internal setup helper function used by SetupSpatialStructure().
*/
void SetupSpatialStructure_Load();
void SetupPhylogenyTracking();
void SetupTagMatching();
public:
/**
* Input: The world's random seed and a pointer to this world's config object
*
* Output: None
*
* Purpose: To construct an instance of SymWorld
*/
SymWorld(emp::Random& _random, emp::Ptr<SymConfigBase> _config) :
emp::World<Organism>(_random)
{
fun_print_org = [](Organism& org, std::ostream& os) {
//os << PrintHost(&org);
os << "This doesn't work currently";
};
my_config = _config;
total_res = my_config->LIMITED_RES_TOTAL();
emp_assert(!(my_config->TAG_MATCHING() && my_config->FREE_LIVING_SYMS()));
if (my_config->PHYLOGENY()) {
SetupPhylogenyTracking();
}
if (my_config->TAG_MATCHING()) {
SetupTagMatching();
}
}
/**
* Input: None
*
* Output: None
*
* Purpose: To destruct the objects belonging to SymWorld to conserve memory.
*/
virtual ~SymWorld() {
if (data_node_hostintval) data_node_hostintval.Delete();
if (data_node_symintval) data_node_symintval.Delete();
if (data_node_freesymintval) data_node_freesymintval.Delete();
if (data_node_hostedsymintval) data_node_hostedsymintval.Delete();
if (data_node_syminfectchance) data_node_syminfectchance.Delete();
if (data_node_freesyminfectchance) data_node_freesyminfectchance.Delete();
if (data_node_hostedsyminfectchance) data_node_hostedsyminfectchance.Delete();
if (data_node_within_host_mean) data_node_within_host_mean.Delete();
if (data_node_within_host_variance) data_node_within_host_variance.Delete();
if (data_node_host_repro_count) data_node_host_repro_count.Delete();
if (data_node_sym_repro_count) data_node_sym_repro_count.Delete();
if (data_node_host_towards_partner_rate) data_node_host_towards_partner_rate.Delete();
if (data_node_host_from_partner_rate) data_node_host_from_partner_rate.Delete();
if (data_node_sym_towards_partner_rate) data_node_sym_towards_partner_rate.Delete();
if (data_node_sym_from_partner_rate) data_node_sym_from_partner_rate.Delete();
if (data_node_host_permissiveness) data_node_host_permissiveness.Delete();
if (data_node_host_tag_richness) data_node_host_tag_richness.Delete();
if (data_node_host_tag_shannon) data_node_host_tag_shannon.Delete();
if (data_node_symbiont_tag_richness) data_node_symbiont_tag_richness.Delete();
if (data_node_symbiont_tag_shannon) data_node_symbiont_tag_shannon.Delete();
if (data_node_hostcount) data_node_hostcount.Delete();
if (data_node_symcount) data_node_symcount.Delete();
if (data_node_tag_dist) data_node_tag_dist.Delete();
if (data_node_freesymcount) data_node_freesymcount.Delete();
if (data_node_hostedsymcount) data_node_hostedsymcount.Delete();
if (data_node_uninf_hosts) data_node_uninf_hosts.Delete();
if (data_node_attempts_horiztrans) data_node_attempts_horiztrans.Delete();
if (data_node_tagfail_horiztrans) data_node_tagfail_horiztrans.Delete();
if (data_node_sizefail_horiztrans) data_node_sizefail_horiztrans.Delete();
if (data_node_successes_horiztrans) data_node_successes_horiztrans.Delete();
if (data_node_attempts_verttrans) data_node_attempts_verttrans.Delete();
if (data_node_successes_verttrans) data_node_successes_verttrans.Delete();
for (size_t i = 0; i < sym_pop.size(); i++) { //host population deletion is handled by empirical world destructor
if (sym_pop[i]) {
DoSymDeath(i);
}
}
if (my_config->PHYLOGENY()) { //host systematic deletion is handled by empirical world destructor
Clear(); // delete hosts here so that hosted symbionts get
// deleted and unlinked from the sym_sys
sym_sys.Delete();
}
if (my_config->TAG_MATCHING()) {
tag_metric.Delete();
}
}
/**
* Input: Boolean indicating whether world uses synchronous generations or not.
*
* Output: None.
*
* Purpose: Overrides Empirical World's SetPopStruct_Mixed function in order to
* prevent a location from being considered its own neighbor.
*/
void SetPopStruct_Mixed(bool synchronous_gen=false) {
emp::World<Organism>::SetPopStruct_Mixed(synchronous_gen);
// For well-mixed, we need to alter the Empirical World neighbor finding to not allow the current location to be returned.
// H/t to Kai Johnson for suggestion to exclude upper cell and swap it in if needed
// Neighbors are anywhere in the same population except the pos.
fun_get_neighbor = [this](emp::WorldPosition pos) {
if (pop.size() <= 1 ) return emp::WorldPosition(); // if there are no neighbors, return an invalid position
// leave out the last cell and swap it in if potential_neighbor is the same as pos
size_t potential_neighbor = GetRandomCellID(0, pop.size()-1);
if (potential_neighbor == pos.GetIndex()) {
potential_neighbor = pop.size() - 1;
}
return pos.SetIndex(potential_neighbor);
};
// Neighbors are anywhere in same population, so all organisms are neighbors except for the focal organism.
// This might not actually need to be changed for SymWorld, but consistency seemed important
fun_is_neighbor = [](emp::WorldPosition pos1, emp::WorldPosition pos2) {
if ((pos1.GetPopID() == pos2.GetPopID()) && (pos1.GetIndex() == pos2.GetIndex())) return false;
else return true;
};
}
/**
* Input: Boolean indicating whether world is using synchronous generations or not.
*
* Output: None
*
* Purpose: Configures a custom population structure using the spatial_structure
* object to define neighbors for each position. Note: this function
* assumes that spatial_structure has already been configured. (which
* is done in SetupSpatialStructure_Load())
*/
void SetPopStruct_Custom(bool synchronous_gen = false) {
const size_t max_world_size = spatial_structure.GetNumPositions();
Resize(max_world_size);
// Mirrors Empirical world's SetPopStruct functions.
pop_sizes.resize(0);
is_synchronous = synchronous_gen;
is_space_structured = true;
is_pheno_structured = false;
// -- Setup Functions --
// Inject into a random position in the world
fun_find_inject_pos = [this](emp::Ptr<Organism> new_org) {
(void) new_org;
return emp::WorldPosition(
GetRandom().GetUInt(spatial_structure.GetNumPositions())
);
};
// Setup neighbors function
fun_get_neighbor = [this](emp::WorldPosition pos) {
auto neighbor = spatial_structure.GetRandomNeighbor(GetRandom(), pos.GetIndex());
// If no valid neighbors, return invalid position.
if (!neighbor) {
return emp::WorldPosition();
}
// Must be a valid neighbor.
emp_assert(neighbor.value() < GetSize());
return pos.SetIndex(neighbor.value());
};
fun_is_neighbor = [this](emp::WorldPosition pos1, emp::WorldPosition pos2) {
// NOTE: Order matters for spatial_structure.
const bool one_to_two = spatial_structure.IsConnected(
pos1.GetIndex(),
pos2.GetIndex()
);
const bool two_to_one = spatial_structure.IsConnected(
pos2.GetIndex(),
pos1.GetIndex()
);
return one_to_two || two_to_one;
};
// NOTE: This is what's happening in other structure modes (copied from World's set structure functions),
// but do we actually want to override to use graveyard?
fun_kill_org = [this]() {
const size_t kill_id = GetRandom().GetUInt(spatial_structure.GetNumPositions());
emp_assert(kill_id < GetSize());
RemoveOrgAt(kill_id);
return kill_id;
};
// Adapted from World.h SetPopStruct_Grid
if (synchronous_gen) {
// Place births in a neighboring position in the new grid.
fun_find_birth_pos = [this](
emp::Ptr<Organism> new_org,
emp::WorldPosition parent_pos
) {
emp_assert(new_org); // New organism must exist.
emp::WorldPosition next_pos = fun_get_neighbor(parent_pos); // Place near parent.
return next_pos.SetPopID(1); // Adjust position to next pop and place..
};
SetAttribute("SynchronousGen", "True");
} else {
// Asynchronous: always go to a neighbor in current population.
fun_find_birth_pos = [this](
emp::Ptr<Organism> new_org,
emp::WorldPosition parent_pos
) {
return emp::WorldPosition(fun_get_neighbor(parent_pos)); // Place org in existing population.
};
SetAttribute("SynchronousGen", "False");
}
SetAttribute("PopStruct", "Custom");
SetSynchronousSystematics(synchronous_gen);
}
/**
* Input: None
*
* Output: The pop_t value that represents the world's population.
*
* Purpose: To get the world's population of organisms.
*/
pop_t& GetPop() { return pop; }
/**
* Input: None
*
* Output: const pop_t reference to the world's population.
*
* Purpose: To get a const reference to the world's population of organisms.
*/
const pop_t& GetPop() const { return pop; }
/**
* Input: None
*
* Output: The pop_t value that represent the world's symbiont
* population.
*
* Purpose: To get the world's symbiont population.
*/
pop_t& GetSymPop() { return sym_pop; }
/**
* Input: None
*
* Output: const reference to pop_t that represents the world's symbiont
* population.
*
* Purpose: To get a const reference to the world's symbiont population.
*/
const pop_t& GetSymPop() const { return sym_pop; }
/**
* Input: None
*
* Output: The world's spatial structure mode.
*
* Purpose: Get the world's currently configured spatial structure mode.
* Spatial structure mode is configured on setup. It is intentionally
* not able to be modified by a setter function.
*/
SPATIAL_STRUCT_MODE GetSpatialStructureMode() const { return spatial_struct_mode; }
/**
* Input: None
*
* Output: Boolean indicating if the world is configured in well-mixed population
* structure mode.
*/
bool IsWellMixedPopStruct() { return spatial_struct_mode == SPATIAL_STRUCT_MODE::WELL_MIXED; }
/**
* Input: None
*
* Output: Boolean indicating if the world is configured in grid population
* structure mode.
*/
bool IsGridPopStruct() { return spatial_struct_mode == SPATIAL_STRUCT_MODE::GRID; }
/**
* Input: None
*
* Output: Boolean indicating if the world is configured in custom population
* structure mode.
*/
bool IsCustomPopStruct() { return spatial_struct_mode == SPATIAL_STRUCT_MODE::LOAD; }
/**
* Input: None
*
* Output: Spatial structure object used to manage spatial connectivity in custom
* population structure mode.
*
* Purpose: Get custom population structure. Only relevant when in custom
* population structure mode.
*/
const SpatialStructure& GetCustomPopStructure() const {
return spatial_structure;
}
/**
* Input: None
*
* Output: TAG_METRIC_TYPE indicating current tag metric being used.
*/
TAG_METRIC_TYPE GetTagMetricType() const { return tag_metric_type; }
/**
* Input: None
*
* Output: PHYLO_TAXON_TYPE indicating current phylogeny taxon type.
*/
PHYLO_TAXON_TYPE GetPhylogenyTaxonType() const { return phylo_taxon_type; }
/**
* Input: A pointer to the tag distance metric object
*
* Output: None
*
* Purpose: To set the world's tag distance calculator
*/
void SetTagMetric(emp::Ptr<tag_metric_t> _in) {
tag_metric = _in;
}
/**
* Input: None
*
* Output: A pointer to the tag distance metric object
*
* Purpose: To get the world's tag distance calculator
*/
emp::Ptr<tag_metric_t> GetTagMetric() {
return tag_metric;
}
double CalcTagMetric(const tag_t& tag_a, const tag_t& tag_b) const {
return (*tag_metric)(tag_a, tag_b);
}
/**
* Input: None
*
* Output: A reference to the world graveyard.
*
* Purpose: To get the world's graveyard.
*/
emp::vector<emp::Ptr<Organism>>& GetGraveyard() { return graveyard; }
/**
* Input: None
*
* Output: The configuration used for this world.
*
* Purpose: Allows accessing the world's config.
*/
const emp::Ptr<SymConfigBase> GetConfig() const { return my_config; }
// AML: A little nicer to work with:
// const SymConfigBase& GetConfig() const { return *my_config; }
/**
* Input: None
*
* Output: The boolean representing if vertical transmission will occur
*
* Purpose: To determine if vertical transmission will occur
*/
bool WillTransmit() {
bool result = GetRandom().GetDouble(0.0, 1.0) < my_config->VERTICAL_TRANSMISSION();
return result;
}
/**
* Input: None
*
* Output: The systematic object tracking hosts
*
* Purpose: To retrieve the host systematic
*/
emp::Ptr<host_systematics_t> GetHostSys() {
return host_sys;
}
/**
* Input: None
*
* Output: The systematic object tracking hosts
*
* Purpose: To retrieve the symbiont systematic
*/
emp::Ptr<sym_systematics_t> GetSymSys() {
return sym_sys;
}
/**
* Input: None
*
* Output: The standard function object that determines which bin hosts
* should belong to depending on their interaction value
*
* Purpose: To classify hosts based on their interaction value.
*/
fun_calc_info_t GetCalcHostInfoFun() {
// NOTE: Probably don't want one of the taxon type modes defined separately from
// others?
emp_assert(calc_host_info_fun);
return calc_host_info_fun;
}
/**
* Input: None
*
* Output: The standard function object that determines which bin symbionts
* should belong to depending on their interaction value
*
* Purpose: To classify symbionts based on their interaction value.
*/
fun_calc_info_t GetCalcSymInfoFun() {
emp_assert(calc_sym_info_fun);
// By default the sym info function is the same as the host one,
// but separating them allows us to change the sym info function
// to something else if we need to.
if (!calc_sym_info_fun) {
calc_sym_info_fun = GetCalcHostInfoFun();
}
return calc_sym_info_fun;
}
/**
* Input: The symbiont to be added to the systematic
*
* Output: the taxon the symbiont is added to.
*
* Purpose: To add a symbiont to the systematic and to set it to track its taxon
*/
emp::Ptr<taxon_t::base_taxon_t> AddSymToSystematic(
emp::Ptr<Organism> sym,
emp::Ptr<taxon_t::base_taxon_t> parent_taxon=nullptr
) {
emp::Ptr<taxon_t::base_taxon_t> taxon = sym_sys->AddOrg(
*sym,
emp::WorldPosition(0, 0),
parent_taxon.Cast<taxon_t::sym_taxon_t>()
).Cast<taxon_t::base_taxon_t>();
sym->SetTaxon(taxon);
return taxon;
}
/**
* Input: The amount of resources an organism wants from the world.
*
* Output: If there are unlimited resources or the total resources are greater than those requested,
* returns the amount of desired resources.
* If total_res is less than the desired resources, but greater than 0,
* then total_res will be returned. If none of these are true, then 0 will be returned.
*
* Purpose: To determine how many resources to distribute to each organism.
*/
float PullResources(float desired_resources) {
// if LIMITED_RES_TOTAL == -1, unlimited, even if limited resources was on before
if (total_res == -1 || my_config->LIMITED_RES_TOTAL() == -1) {
return desired_resources;
} else {
if (total_res>=desired_resources) {
total_res = total_res - desired_resources;
return desired_resources;
} else if (total_res>0) {
float resources_to_return = total_res;
total_res = 0.0;
return resources_to_return;
} else {
return 0.0;
}
}
}
/**
* Input: An organism pointer to add to the graveyard
*
* Output: None
*
* Purpose: To add organisms to the graveyard (also sets it to dead)
*/
virtual void SendToGraveyard(emp::Ptr<Organism> org) {
emp_assert(
org != nullptr,
"Tried to send a null organism to the graveyard."
);
org->SetDead();
graveyard.push_back(org);
}
/**
* Input: The pointer to the new organism;
* the world position of the location to add
* the new organism.
*
* Output: None
*
* Purpose: To overwrite the empirical AddOrgAt function to permit syms to
* be added into sym_pop. Only existing positions allowed; does not grow population
* capacity.
*/
void AddOrgAt(emp::Ptr<Organism> new_org, emp::WorldPosition pos, emp::WorldPosition p_pos=emp::WorldPosition()) {
emp_assert(new_org); // The new organism must exist.
emp_assert(pos.IsValid()); // Position must be legal.
// SYMBIONTS have position in the overall world as their ID
// HOSTS have position in the overall world as their index
new_org->SetLocation(pos);
if (new_org->IsHost()) { // if the org is a host, use the empirical addorgat function
emp_assert(pos.GetIndex() < pop.size());
emp::World<Organism>::AddOrgAt(new_org, pos, p_pos);
if (new_org->HasSym()) {
// Sometimes we add the symbionts before putting the organism into the world, which messes up the syms' location
for (size_t j = 0; j < new_org->GetSymbionts().size(); j++) {
emp::Ptr<Organism> cur_sym = new_org->GetSymbionts()[j];
cur_sym->SetLocation(emp::WorldPosition(j+1, pos.GetIndex()));
}
}
} else { // if it is not a host, then add it to the sym population
emp_assert(pos.GetPopID() < sym_pop.size());
// for symbionts, their place in their host's world is indicated by their ID
size_t pos_id = pos.GetPopID();
// run before-placement actions
before_placement_sig.Trigger(*new_org, pos_id);
// place symbiont
if (!sym_pop[pos_id]) {
++num_orgs;
} else {
SendToGraveyard(sym_pop[pos_id]); // don't delete it yet, that can cause a seg fault
}
//set the cell to point to the new sym
sym_pop[pos_id] = new_org;
}
}
// Overriding World's DoBirth to take a pointer instead of a reference
// Because it takes a pointer, it doesn't support birthing multiple copies
/**
* Input: (1) The pointer to the organism that is being birthed;
* (2) The size_t location of the parent organism.
*
* Output: The WorldPosition of the position of the new organism.
*
* Purpose: To introduce new organisms to the world.
*/
emp::WorldPosition DoBirth(emp::Ptr<Organism> new_org, emp::WorldPosition p_pos) {
size_t parent_pos = p_pos.GetIndex();
before_repro_sig.Trigger(parent_pos);
emp::WorldPosition pos; // Position of each offspring placed.
offspring_ready_sig.Trigger(*new_org, parent_pos);
pos = fun_find_birth_pos(new_org, parent_pos);
if (pos.IsValid() && (pos.GetIndex() != parent_pos)) {
//Add to the specified position, overwriting what may exist there
AddOrgAt(new_org, pos, parent_pos);
if (my_config->PHYLOGENY() && my_config->TRACK_PHYLOGENY_INTERACTIONS()) {
datastruct::TaxonDataBase& my_data = new_org->GetTaxon()->GetData();
datastruct::HostTaxonData* d = static_cast<datastruct::HostTaxonData*>(&my_data);
for (auto sym : new_org->GetSymbionts()) {
d->AddInteraction(sym->GetTaxon());
if (first_mut_host == 0 && new_org->GetIntVal() > 0 && sym->GetIntVal() > 0) {
first_mut_host = new_org->GetTaxon()->GetID();
first_mut_sym = sym->GetTaxon()->GetID();
}
}
}
} else {
new_org.Delete();
} // Otherwise delete the organism.
return pos;
}
/**
* Input: The world position of the host to perform death upon
*
* Output: None
*
* Purpose: To overwrite the empirical DoDeath function to permit cleanup
* of false-start (<1 update duration) host taxa when unpruned trees are
* being recorded.
*/
void DoDeath(const emp::WorldPosition pos) {
if (my_config->PHYLOGENY()) {
emp::Ptr<taxon_t::host_taxon_t> taxon = host_sys->GetTaxonAt(pos);
if (my_config->STORE_EXTINCT() && taxon->GetOriginationTime() == GetUpdate() && taxon->GetTotalOffspring() == 0) {
host_sys->RemoveOrg(pos);
host_sys->outside_taxa.erase(taxon);
taxon.Delete();
}
}
emp::World<Organism>::DoDeath(pos);
}
/**
* Input: The size_t value representing the location whose neighbors
* are being searched.
*
* Output: If there are no occupied neighboring positions, -1 will be returned.
* If there are occupied neighboring positions, then the location of one
* occupied position will be returned.
*
* Purpose: To determine the location of a valid occupied neighboring position.
*/
int GetNeighborHost(size_t id) {
// Attempt to use GetRandomNeighborPos first, since it's much faster
for (size_t i = 0; i < 3; i++) {
emp::WorldPosition neighbor = GetRandomNeighborPos(id);
if (neighbor.IsValid() && IsOccupied(neighbor)) {
return neighbor.GetIndex();
}
}
// Then enumerate all occupied neighbors, in case many neighbors are unoccupied
const emp::vector<size_t> valid_neighbors{GetValidNeighborOrgIDs(id)};
if (valid_neighbors.empty()) {
return -1;
} else {
const int rand_index = GetRandom().GetUInt(0, valid_neighbors.size());
return valid_neighbors[rand_index];
}
}
// Overwrite emp::World get valid neighbor org ids to account for different
// spatial structure modes.
/**
* Purpose: returns vector of valid, occupied neighboring positions from position ID
*/
emp::vector<size_t> GetValidNeighborOrgIDs(size_t id) {
emp::vector<size_t> neighbor_ids;
switch(spatial_struct_mode) {
case SPATIAL_STRUCT_MODE::WELL_MIXED:
// In well-mixed mode, use base neighbor organism ids
return base_world_t::GetValidNeighborOrgIDs(id);
case SPATIAL_STRUCT_MODE::GRID: {
const size_t grid_width = my_config->WORLD_WIDTH();
const size_t grid_height = my_config->WORLD_HEIGHT();
using dir_t = spatial_utils::GRID_DIR;
emp_assert(GetSize() == grid_width * grid_height);
// emp world uses a 8-neighborhood grid
for (dir_t dir : spatial_utils::grid_directions) {
const size_t neighbor_id = spatial_utils::GetGridNeighbor(
id,
dir,
grid_width,
grid_height
);
// This check is copied over from emp::World's version of this function.
if ((bool) (pop[neighbor_id].Raw())) {
neighbor_ids.emplace_back(neighbor_id);
}
}
return neighbor_ids;
}
case SPATIAL_STRUCT_MODE::LOAD: {
const auto& neighboring_positions = spatial_structure.GetNeighbors(id);
for (size_t neighbor_id : neighboring_positions) {
// This check is copied over from emp::World's version of this function.
if ((bool) (pop[neighbor_id].Raw())) {
neighbor_ids.emplace_back(neighbor_id);
}
}
return neighbor_ids;
}
default:
emp_error("Unknown spatial structure mode");
return neighbor_ids;
}
}
/**
* Input: The pointer to a host that will be added to the world.
* This function assumes that the pop vector has been resized.
*
* Output: None
*
* Purpose: To add a host to the world at a random location.
*/
void InjectHost(emp::Ptr<Organism> new_host) {
AddOrgAt(new_host, emp::WorldPosition(GetRandomCellID()));
}
/**
* Input: The pointer to an organism that will be injected into the world.
*
* Output: None
*
* Purpose: To add a symbiont to the world, either into a host or into a sym world cell.
*/
void InjectSymbiont(emp::Ptr<Organism> new_sym) {
size_t new_loc;
if (my_config->PHYLOGENY()) {
// NOTE: Is it intended to add to phylogeny even when inject fails?
AddSymToSystematic(new_sym);
}
if (!my_config->FREE_LIVING_SYMS()) {
new_loc = GetRandomOrgID();
// If the position is acceptable, add the sym to the host in that position
if (IsOccupied(new_loc)) {
const bool success = pop[new_loc]->AddSymbiont(new_sym) != 0;
if (success) {
if (my_config->TAG_MATCHING()) {
new_sym->SetTag(pop[new_loc]->GetTag());
}
if (my_config->PHYLOGENY() && my_config->TRACK_PHYLOGENY_INTERACTIONS()) {
datastruct::HostTaxonData* d = static_cast<datastruct::HostTaxonData*>(&pop[new_loc]->GetTaxon()->GetData());
d->AddInteraction(new_sym->GetTaxon());
}
}
} else {
new_sym.Delete();
}
} else {
new_loc = GetRandomCellID();
// if the position is within bounds, add the sym to it
if (new_loc < sym_pop.size()) {
AddOrgAt(new_sym, emp::WorldPosition(0, new_loc));
} else {
new_sym.Delete();
}
}
}
//Definitions of data node functions, expanded in DataNodes.h
virtual void CreateDataFiles();
void MapPhylogenyInteractions();
void WritePhylogenyFile(const std::string& filename);
void WriteOrgDumpFile(const std::string& filename);
void WriteTagMatrixFile(const std::string& filename);
void WriteDominantPhylogenyFiles(const std::string& filename);
emp::Ptr<emp::Taxon<taxon_t::info_t>> GetDominantSymTaxon();
emp::Ptr<emp::Taxon<taxon_t::info_t>> GetDominantHostTaxon();
emp::vector<emp::Ptr<emp::Taxon<taxon_t::info_t>>> GetDominantFreeHostedSymTaxon();
emp::DataFile& SetupSymIntValFile(const std::string& filename);
emp::DataFile& SetupHostIntValFile(const std::string& filename);
emp::DataFile& SetupFreeLivingSymFile(const std::string& filename);
emp::DataFile& SetupReproHistFile(const std::string& filename);
emp::DataFile& SetupTransmissionFile(const std::string& filename);
emp::DataFile& SetupTagDistFile(const std::string& filename);
emp::DataFile& SetupSymDiversityFile(const std::string& filename);
virtual void SetupTransmissionFileColumns(emp::DataFile& file);
virtual void SetupHostFileColumns(emp::DataFile& file);
emp::DataMonitor<int>& GetHostCountDataNode();
emp::DataMonitor<int>& GetSymCountDataNode();
emp::DataMonitor<int>& GetCountHostedSymsDataNode();
emp::DataMonitor<int>& GetCountFreeSymsDataNode();