-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsimulation.cpp
More file actions
2287 lines (1906 loc) · 103 KB
/
Copy pathsimulation.cpp
File metadata and controls
2287 lines (1906 loc) · 103 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
#include "simulation.h"
#include "version.h"
#include <QRandomGenerator>
#include <QMessageBox>
#include <QElapsedTimer>
#include <QTimer>
#include <QCoreApplication>
simulation::simulation(int runsCon, const simulationVariables *simSettingsCon, bool *error, MainWindow *theMainWindowCon, bool calculateStripUninformativeFactorRunningCon)
{
/***** Set up GUI, and working log *****/
theMainWindow = theMainWindowCon;
runs = runsCon;
simSettings = simSettingsCon;
if ((simSettings->genomeSize < simSettings->fitnessSize) || (simSettings->genomeSize < simSettings->speciesSelectSize))
{
warning("Error", "Genome size is smaller than fitness or species select size, failed to initialise simulation");
*error = true;
qInfo("Simulation initialisation error 1");
return;
}
//Setup function returns false if failed, else true
if (!setupSaveDirectory())
{
warning("Error", "Can't set up save directory, failed to initialise simulation");
*error = true;
qInfo("Simulation initialisation error 2");
return;
}
if (simSettings->writeRunningLog)
if (!setupSaveDirectory("TREvoSim_running_log_"))
{
warning("Permissions issue", "Unable to set up write log folder. Will terminate.");
*error = true;
return;
}
//Get system max rand
maxRand = QRandomGenerator::max();
/***** Apply settings *****/
//In some settings, genome size or mask number etc. will change - but this risks messing with a global. Other variables can change due to rounding from multiplying/dividing by float. Hence keep copy of the actual values and reset at end to make sure nothing changes
runGenomeSize = simSettings->genomeSize;
runSelectSize = simSettings->speciesSelectSize;
runFitnessSize = simSettings->fitnessSize;
runFitnessTarget = simSettings->fitnessTarget;
int runMaskNumber = simSettings->maskNumber;
runEnvironmentNumber = simSettings->environmentNumber;
runSpeciesDifference = simSettings->speciesDifference;
runMixingProbabilityOneToZero = simSettings->mixingProbabilityOneToZero;
runMixingProbabilityZeroToOne = simSettings->mixingProbabilityZeroToOne;
// Initialise variables
speciesCount = 0, iterations = 0;
informativeCharacters = 0;
// If stripping uninformative characters, in order to have the requested char # need to over-generate, and then subsample to requested value
calculateStripUninformativeFactorRunning = calculateStripUninformativeFactorRunningCon;
if (simSettings->stripUninformative && !calculateStripUninformativeFactorRunning)
{
double stripUninformativeFactorLocal = simSettings->stripUninformativeFactor;
if (stripUninformativeFactorLocal < 1.5) stripUninformativeFactorLocal = 5;
double runGenomeSizeDouble = static_cast<double>(runGenomeSize);
runGenomeSizeDouble *= stripUninformativeFactorLocal;
runGenomeSize = static_cast<int>(runGenomeSizeDouble);
double runSelectSizeDouble = static_cast<double>(runSelectSize);
runSelectSizeDouble *= stripUninformativeFactorLocal;
runSelectSize = static_cast<int>(runSelectSizeDouble);
double runFitnessSizeDouble = static_cast<double>(runFitnessSize);
runFitnessSizeDouble *= stripUninformativeFactorLocal;
runFitnessSize = static_cast<int>(runFitnessSizeDouble);
double runFitnessTargetDouble = static_cast<double>(runFitnessTarget);
runFitnessTargetDouble *= stripUninformativeFactorLocal;
runFitnessTarget = static_cast<int>(runFitnessTargetDouble);
//I suspect it makes sense to do this so it still hits expected behaviour - but note that that means we can't guaruntee species difference if stripping uninformative characters
double runSpeciesDifferenceDouble = static_cast<double>(runSpeciesDifference);
runSpeciesDifferenceDouble *= stripUninformativeFactorLocal;
runSpeciesDifference = static_cast<int>(runSpeciesDifferenceDouble);
}
/***** Setup and populate playing field *****/
for (int p = 0; p < simSettings->playingfieldNumber; p++) playingFields.append(new playingFieldStructure);
//This should either be to playingfieldSize if PFs do not expand
if (!simSettings->expandingPlayingfield)
for (auto p : std::as_const(playingFields))
for (int i = 0; i < simSettings->playingfieldSize; i++)
p->playingField.append(new Organism(runGenomeSize, simSettings->stochasticLayer));
//Or just one, if they do expand
else
for (auto p : std::as_const(playingFields))
p->playingField.append(new Organism(runGenomeSize, simSettings->stochasticLayer));
//Note organisms are populated here, but actually set during the initialisation function
/***** Setup and populate masks *****/
//Playing field comprise environments - initialise and attach these
for (auto p : std::as_const(playingFields))
for (int k = 0; k < runEnvironmentNumber; k++)
if (k == 0 || simSettings->environmentType != ENVIRONMENT_TYPE_MATCHING_PEAKS)
p->environments.append(Environment(*simSettings));
//If we need to make sure fitness peaks are the same height, we send the constructor the previously created environment
else p->environments.append(Environment(p->environments[0], true));
//Check for error in initialisation
bool initialisationError = false;
for (auto p : std::as_const(playingFields))
for (auto e : std::as_const(p->environments))
if (e.error)
{
warning("Mask initialisation error", "There was an error initialising the masks and the simulation was not able to run. Email RJG.");
*error = true;
return;
}
//If playing field masks should start the same, copy of playing fields over
if (simSettings->playingfieldNumber > 1 && simSettings->playingfieldMasksMode != MASKS_MODE_INDEPENDENT)
for (int p = 1; p < simSettings->playingfieldNumber; p++)
playingFields[p]->environments = playingFields[0]->environments;
/***** Set up stuff for perturbations and ecosystem engineers *****/
perturbationStart = 0, perturbationEnd = 0, perturbationOccurring = 0;
ecosystemEngineeringOccurring = 0;
}
bool simulation::run()
{
QString aliveRecordString ("Alive record is taken at the end of each iteration, so any species which have gone extinct during that iteration due to mixing or overwriting from a setling new Organism will not feature on the alive list.\nEach line lists: Iteration\tPlaying field\tSpecies alive\n\n");
QTextStream aliveRecordTextStream(&aliveRecordString);
Organism bestOrganism = initialise();
//Add current fitness to the fitness record of the organism
bestOrganism.fitnessRecord.append(bestOrganism.fitness);
//Populate playing field with clones
quint32 notFound = static_cast<quint32>(-1);
if (static_cast<quint32>(bestOrganism.fitness) == notFound)
{
warning("Oops", "This has not initialised this correctly. Please try different settings or email RJG.");
return false;
}
else for (auto p : std::as_const(playingFields))
for (auto o : std::as_const(p->playingField)) *o = bestOrganism;
\
if (simSettings->test == 3) return true;
//Species list to store details of each new species
QVector <Organism *> speciesList;
// Above is also the first species, obvs.
speciesList.append(new Organism(runGenomeSize, simSettings->stochasticLayer));
*speciesList[0] = *playingFields[0]->playingField[0];
//It is also not extinct
extinctList.append(false);
//Create string to record tree in parantheses format
QString TNTstring;
//Need to run loop until hit species number or iteration number - track using a bool
bool simulationComplete = false;
//Need to track when EE are first applied in order to apply with known frequency
int EEstart = 0;
QElapsedTimer timer;
timer.start();
int lastGUIUpdate = 0;
/************* Start simulation *************/
do
{
//Pause if required....
if (theMainWindow != nullptr)
while (theMainWindow->pauseFlag == true && !theMainWindow->escapePressed)
qApp->processEvents();
if (theMainWindow != nullptr)
if (theMainWindow->escapePressed)
{
clearVectors(playingFields, speciesList);
return false;
}
int playingFieldNumber = -1;
//Do the iteration for all playing fields
for (auto pf : std::as_const(playingFields))
{
/******** Sort playing field by fitness *****/
//std::sort(playingField.begin(),playingField.end(),[](const Organism* OL, const Organism* OR){return OL->fitness<OR->fitness;});
//qSort(playingField.begin(),playingField.end());
//This has been removed, because sorting not strictly required - quicker option selected of going doing dice toss, then going down list, finding fittest, etc.
//If recycled needs to be updted to work with multiple playing fields.
//Need to keep track of which playing field we're on for calling fitness function - for now
playingFieldNumber++;
//If we have enough species from speciation in playing field one, no need to run this all again (and causes a crash thanks to printing to screen)
if (simSettings->runMode == RUN_MODE_TAXON && speciesCount == simSettings->runForTaxa - 1) break;
int select = coinToss(pf);
//Need to duplicate one
Organism progeny = *pf->playingField[select];
mutateOrganism(progeny, pf);
int parentSpecies = pf->playingField[select]->speciesID;
//If we're using an expanding playingfield there is always one individual in playingfield, and they don't disppear until the end of a run
//Hence instead we define extinction in functional terms - i.e. when they were last selected for replication
if (simSettings->expandingPlayingfield)
{
progeny.extinct = iterations;
//We need to do this for parent species as well as this selected individual (otherwise tree will have negative brnch lengths)
speciesList[parentSpecies]->extinct = iterations;
}
//Reminder, in initialise prog genome is set equal to genome
bool isNewSpecies = checkForSpeciation(&progeny, runSelectSize, runSpeciesDifference, simSettings->speciationMode);
/************* New species *************/
//Assymetry of tree changes with level of difference below, plus balance between rate of mutation of environment and Organism
if (isNewSpecies)
{
//Update iteration counter on the parent species in the species list
speciesList[parentSpecies]->cladogenesis = iterations;
//New species iterates species count and does organism end of new species things
newSpecies(progeny, *pf->playingField[select], pf);
//Keeping species list within main object, hence below
//Set parent to record last child species
speciesList[parentSpecies]->children.append(speciesCount);
//Add to species list
speciesList.append(new Organism(runGenomeSize, simSettings->stochasticLayer));
*speciesList[speciesCount] = progeny;
//Update tree string, write to GUI. First sort out zero padding.
updateTNTstring(TNTstring, progeny.parentSpeciesID, progeny.speciesID);
//Add to the end of the pf if we are in expand mode - a new species always adds to end of PF
if (simSettings->expandingPlayingfield) pf->playingField.append(new Organism(runGenomeSize, simSettings->stochasticLayer));
}
//We will place progeny in playing field at position overwrite
int overwrite = calculateOverwrite(pf, progeny.speciesID);
//Overwrite the thing
*pf->playingField[overwrite] = progeny;
}
/************* Update displays etc. *************/
//Increase iteration count
iterations++;
/************* Mutate environment then update fitness *************/
for (auto p : playingFields)
for (auto &e : p->environments)
{
bool mutateSuccess = e.mutate();
if (!mutateSuccess)
{
warning("Error in mutate environment", "There has been an error mutating the environment. Please contact RJG.");
return false;
}
}
//If playing field masks should be the same, copy of playing fields over
if (simSettings->playingfieldNumber > 1 && simSettings->playingfieldMasksMode == MASKS_MODE_IDENTICAL)
for (int p = 1; p < simSettings->playingfieldNumber; p++)
playingFields[p]->environments = playingFields[0]->environments;
//Calculate fitness
if (!simSettings->noSelection)
for (int p = 0; p < simSettings->playingfieldNumber; p++)
for (int i = 0; i < playingFields[p]->playingField.count(); i++)
{
int newFitness = fitness(playingFields[p], playingFields[p]->playingField[i], runFitnessTarget);
playingFields[p]->playingField[i]->fitness = newFitness;
//This happens every iteration and updates the fitness record of the instantaneous fitness as the simulation progresses
playingFields[p]->playingField[i]->fitnessRecord.append(newFitness);
if (!simSettings->recordAllFitnesses && playingFields[p]->playingField[i]->fitnessRecord.length() > simSettings->fitnessWindowSize)
playingFields[p]->playingField[i]->fitnessRecord.removeFirst();
//If we have a mean fitness mode, we need to overwrite the fitness with the mean through time
if (simSettings->fitnessMode == FITNESS_MODE_MEAN)
{
int geoMean = meanFitness(playingFields[p]->playingField[i]);
//Assign the geometric mean if it is better
if (geoMean < playingFields[p]->playingField[i]->fitness)
{
playingFields[p]->playingField[i]->fitness = geoMean;
playingFields[p]->playingField[i]->lastFitnessMode = LAST_FITNESS_MEAN;
}
else playingFields[p]->playingField[i]->lastFitnessMode = LAST_FITNESS_MINIMUM;
}
}
/************* Playing field mixing *************/
//Implement mixing between playing fields if required - do check for extinction at same time
if (simSettings->playingfieldNumber > 1 && simSettings->mixing) applyPlayingfieldMixing(speciesList);
/************* Check for extinction *************/
//Check and record species genome if it is last surviving instance, for both extinction and speciation.
//Some redundancy here, but easier approach than waiting for extinction then recovering genome
// For each species, Loop through playing field and count and when one instance of a species exists, overwrite genome in species list, and update display
QHash<QString, QVector <int> > extinct = checkForExtinct(speciesList);
for (auto s : std::as_const(extinct))
{
speciesExtinction(speciesList[s[0]], playingFields[s[1]]->playingField[s[2]], (iterations + 1), simSettings->genomeOnExtinction, simSettings->stochasticLayer);
}
/************* Work out halfway point *************/
bool halfway = false;
if (simSettings->runMode == RUN_MODE_TAXON && (speciesCount >= simSettings->runForTaxa / 2)) halfway = true;
else if (simSettings->runMode == RUN_MODE_ITERATION && (iterations >= simSettings->runForIterations / 2)) halfway = true;
/************* Apply perturbations *************/
if (halfway && (simSettings->environmentType == ENVIRONMENT_TYPE_PERTURBATION || simSettings->mixingPerturbation) && perturbationOccurring < 2)
{
applyPerturbation();
}
/************* Apply ecosystem engineering *************/
int iterationsSinceEEapplications = iterations - EEstart;
if (halfway && simSettings->ecosystemEngineers && iterationsSinceEEapplications % simSettings->ecosystemEngineeringFrequency == 0)
{
ecosystemEngineeringOccurring++;
if (ecosystemEngineeringOccurring == 1)
{
EEstart = iterations;
if (simSettings->writeEE)
if (!setupSaveDirectory("Ecosystem_engineers_"))
{
warning("Permissions issue", "Unable to set up ecosystem engineer folder. Will terminate.");
return false;
}
}
if (ecosystemEngineeringOccurring == 1 || (ecosystemEngineeringOccurring > 1 && simSettings->ecosystemEngineersArePersistent)) applyEcosystemEngineering(speciesList, simSettings->writeEE);
}
/************* Check if simulation is complete *************/
if (simSettings->runMode == RUN_MODE_TAXON && (speciesCount + 1) == simSettings->runForTaxa) simulationComplete = true;
else if (simSettings->runMode == RUN_MODE_ITERATION && iterations == simSettings->runForIterations) simulationComplete = true;
/************* Write GUI if not running in parallel *************/
if (theMainWindow != nullptr)
{
//Update GUI every five milliseconds
if ((timer.elapsed() - lastGUIUpdate) > 5)
{
writeGUI(speciesList);
lastGUIUpdate = timer.elapsed();
}
}
/************* Write alive record *************/
QVector <QVector <int> > speciesAlive;
for (int n = 0; n < simSettings->playingfieldNumber; n++)
{
speciesAlive.append(QVector <int> ());
for (int i = 0; i < playingFields[n]->playingField.count(); i++)
{
bool found = false;
for (int j = 0; j < speciesAlive[n].length(); j++)
if (speciesAlive[n][j] == playingFields[n]->playingField[i]->speciesID)found = true;
if (!found)speciesAlive[n].append(playingFields[n]->playingField[i]->speciesID);
}
}
for (int i = 0; i < simSettings->playingfieldNumber; i++)
{
aliveRecordTextStream << iterations << "\t" << i << "\t";
for (int j = 0; j < speciesAlive[i].length(); j++)aliveRecordTextStream << speciesAlive[i][j] << "\t";
aliveRecordTextStream << "\n";
}
/************* Write running log *************/
if (simSettings->writeRunningLog && (iterations % simSettings->runningLogFrequency == 0) && !calculateStripUninformativeFactorRunning)
{
//We need to do most of the text processing here, as many of the things we may want to report in a running log are local in scope to the run function
//Text is stored in the simulation settings as runningLogString
QString logTextOut = simSettings->runningLogString;
if (logTextOut.contains("||Unresolvable||") || logTextOut.contains( "||Identical||"))
{
int unresolvableCount = 0;
QString unresolvableTaxonGroups;
checkForUnresolvableTaxa(speciesList, unresolvableTaxonGroups, unresolvableCount);
logTextOut.replace("||Unresolvable||", unresolvableTaxonGroups, Qt::CaseInsensitive);
logTextOut.replace("||Identical||", QString::number(unresolvableCount), Qt::CaseInsensitive);
}
if (logTextOut.contains("||Uninformative||"))
{
//Work out which are uninformative- create list
QList <int> uninformativeCoding;
QList <int> uninformativeNonCoding;
//Test for informative
checkForUninformative(speciesList, uninformativeCoding, uninformativeNonCoding);
int uninformativeNumber = uninformativeCoding.length() + uninformativeNonCoding.length();
logTextOut.replace("||Uninformative||", QString::number(uninformativeNumber), Qt::CaseInsensitive);
}
if (logTextOut.contains("||Alive_Record||"))
{
QString aliveRecordIterationString;
for (int i = 0; i < simSettings->playingfieldNumber; i++)
for (int j = 0; j < speciesAlive[i].length(); j++)
aliveRecordIterationString.append(QString(QString::number(speciesAlive[i][j]) + "\t"));
logTextOut.replace("||Alive_Record||", aliveRecordIterationString);
}
logTextOut.replace("||TNT_Tree||", TNTstring, Qt::CaseInsensitive);
logTextOut.replace("||MrBayes_Tree||", printNewickWithBranchLengths(0, speciesList, false), Qt::CaseInsensitive);
logTextOut.replace("||Stochastic_Matrix||", printStochasticMatrix(speciesList, simSettings->stochasticLayer), Qt::CaseInsensitive);
logTextOut.replace("||Ecosystem_Engineers||", printEcosystemEngineers(speciesList), Qt::CaseInsensitive);
logTextOut.replace("||Character_Number||", QString::number(runGenomeSize), Qt::CaseInsensitive);
logTextOut.replace("||Taxon_Number||", QString::number(speciesList.length()), Qt::CaseInsensitive);
logTextOut.replace("||Count||", doPadding(runs, 3));
logTextOut.replace("||Matrix||", printMatrix(speciesList), Qt::CaseInsensitive);
logTextOut.replace("||Matrix_fitness_history||", printMatrixFitnessHistory(speciesList), Qt::CaseInsensitive);
logTextOut.replace("||Time||", printTime(), Qt::CaseInsensitive);
logTextOut.replace("||Settings||", simSettings->printSettings(), Qt::CaseInsensitive);
logTextOut.replace("||Iteration||", QString::number(iterations), Qt::CaseInsensitive);
logTextOut.replace("||Root||", printGenomeString(&bestOrganism), Qt::CaseInsensitive);
logTextOut.replace("||PlayingField_Number||", QString::number(simSettings->playingfieldNumber), Qt::CaseInsensitive);
logTextOut.replace("||PlayingField_Size||", QString::number(simSettings->playingfieldSize), Qt::CaseInsensitive);
logTextOut.replace("||PlayingField||", printPlayingField(playingFields), Qt::CaseInsensitive);
logTextOut.replace("||PlayingField_semiconcise||", printPlayingFieldSemiconcise(playingFields), Qt::CaseInsensitive);
logTextOut.replace("||PlayingField_concise||", printPlayingFieldConcise(playingFields), Qt::CaseInsensitive);
logTextOut.replace("||PlayingField_genomes_concise||", printPlayingFieldGenomesConcise(playingFields), Qt::CaseInsensitive);
logTextOut.replace("||PlayingField_fitness_history||", printPlayingFieldFitnessHistory(playingFields), Qt::CaseInsensitive);
logTextOut.replace("||Masks||", printMasks(playingFields), Qt::CaseInsensitive);
QString fitnessHistory("Fitness history of playingfield:,");
QTextStream out(&fitnessHistory);
for (auto p : std::as_const(playingFields))
for (auto org : p->playingField)
{
if (org->lastFitnessMode == LAST_FITNESS_MEAN) out << "MEAN,";
else if (org->lastFitnessMode == LAST_FITNESS_MINIMUM) out << "MIN,";
else out << "ERROR,";
}
fitnessHistory.chop(1);
logTextOut.replace("||FitnessHistoryList||", fitnessHistory, Qt::CaseInsensitive);
bool writeRunningLogSuccess = writeRunningLog(iterations, logTextOut);
if (theMainWindow != nullptr)
{
if (!writeRunningLogSuccess)
{
warning("Permissions issue", QString("Failed to write running log at iteration %1 - check permissions.").arg(iterations));
return false;
}
}
}
}
while (!simulationComplete);
/************* Mop up writing genome for any organisms still alive under genomeOnExtinction and for extinction/branch lengths *************/
//QVector list for each species ID
QVector <int> alive;
//For alive organisms need to record genome of one that is alive (rather than when it was born - in extreme case zero could not have died and have genome from beginning of run)
//Best to record one of the fittest - hence on this occasion, for ease, going to sort playing field
//Only works with c++ 11 thanks to lamda - hence addition of CONFIG += c++11 in .pro
for (int p = 0; p < simSettings->playingfieldNumber; p++) std::sort(playingFields[p]->playingField.begin(), playingFields[p]->playingField.end(), [](const Organism * OL, const Organism * OR)
{
return OL->fitness < OR->fitness;
});
//Go down playing fields
for (auto pf : std::as_const(playingFields))
for (auto o : std::as_const(pf->playingField))
{
int flag = 0;
//Check if the entry on playing field has previously been recorded/updated - if so ignore
for (int i = 0; i < alive.length(); i++)if (alive[i] == o->speciesID)flag = 1;
if (flag == 0)
{
//Update the extinction and if required, genome.
int species = o->speciesID;
alive.append(species);
if (simSettings->genomeOnExtinction)
{
for (int k = 0; k < runGenomeSize; k++)speciesList[species]->genome[k] = o->genome[k];
}
//If expanding playingfield everything will be alive - thus extinction recorded differently
if (!simSettings->expandingPlayingfield)speciesList[species]->extinct = iterations;
}
}
//Everything is extinct now - update this prior to GUI
for (auto &s : extinctList) s = true;
if (theMainWindow != nullptr) writeGUI(speciesList);
/************* Strip uninformative characters, if required *************/
//Needed to make a decision here and arbitrarily decide how to deal with partations used for defining fitness, species, and the whole genome.
//At present split into two partitions - that used for fitness calculation, and that not, and treat individually.
//Don't think preserving that partition used for species definition is so important, so ignoring - but may well prove to be wrong.
//Work out which are uninformative - create list
QList <int> uninformativeCoding;
QList <int> uninformativeNonCoding;
//Test for informative characters - this is a seperate operation to actually stripping them
checkForUninformative(speciesList, uninformativeCoding, uninformativeNonCoding);
int uninformativeNumber = uninformativeCoding.length() + uninformativeNonCoding.length();
informativeCharacters = runGenomeSize - uninformativeNumber;
//If calculateStripUninformativeFactor is running, all we care about is uninformativeCharacters, so return here
if (calculateStripUninformativeFactorRunning) return true;
if (theMainWindow != nullptr && !simSettings->stripUninformative && uninformativeNumber > 0)
{
QString statusString =
QString ("There are %1 uninformative characters in your matrix, and the software is not set to strip these out. This is not necessarily a problem, but I thought you should know.").arg(
uninformativeNumber);
theMainWindow->setStatus(statusString);
}
//Strip the characters if requried
if (simSettings->stripUninformative)
{
//Check whether we have enough coding and non coding characters
bool requiredCharacterNumber = checkForCharacterNumber(uninformativeCoding, uninformativeNonCoding);
if (!requiredCharacterNumber && !simSettings->test)
{
if (theMainWindow != nullptr)
{
QString label = "It seems there are not enough informative characters to pull this off.\n\n"
"By default, TREvoSim over generates characters by a factor of 5x before trying to strip down to those that are parsimony uninformative. "
"Under your current settings (in which the strip uninformative factor is " + QString::number(simSettings->stripUninformativeFactor) +
") TREvoSim has not managed to recover enough informative characters. It has only recovered " + QString::number(speciesList[0]->genome.size()) +
" characters. Choosing the menu option \'Recalculate uninformative factor for current settings\' will allow you to recalculate this factor for the current settings, and \'Set uninformative factor' will allow you to set it manually to a large number.\n\n"
"Alternatively, this may be a one off - you could try running a batch of 1, and the program will try repeatedly with these settings - though after ten or more repeats you may want to cancel and change the settings.";
warning("Oops", label);
}
clearVectors(playingFields, speciesList);
return false;
}
bool stripped = stripUninformativeCharacters(speciesList, uninformativeCoding, uninformativeNonCoding);
if (!stripped)
{
clearVectors(playingFields, speciesList);
return false;
}
}
/******** Check for intrisnically unresolvable clades *****/
int unresolvableCount = 0;
QString unresolvableTaxonGroups;
bool unresolvable = checkForUnresolvableTaxa(speciesList, unresolvableTaxonGroups, unresolvableCount);
if (!unresolvable) return false;
/************* Write files *************/
QHash<QString, QString> outValues;
outValues["TNTstring"] = TNTstring;
outValues["aliveRecordString"] = aliveRecordString;
outValues["unresolvableTaxonGroups"] = unresolvableTaxonGroups;
outValues["MrBayes_Tree"] = printNewickWithBranchLengths(0, speciesList, false);
outValues["Stochastic_Matrix"] = printStochasticMatrix(speciesList, simSettings->stochasticLayer);
outValues["Ecosystem_Engineers"] = printEcosystemEngineers(speciesList);
outValues["Uninformative"] = QString::number(uninformativeNumber);
outValues["Identical"] = QString::number(unresolvableCount);
outValues["Character_Number"] = QString::number(runGenomeSize);
outValues["Taxon_Number"] = QString::number(speciesList.length());
outValues["Count"] = doPadding(runs, 3);
outValues["Root"] = printGenomeString(&bestOrganism);
outValues["PlayingField_Number"] = QString::number(simSettings->playingfieldNumber);
outValues["PlayingField_Size"] = QString::number(simSettings->playingfieldSize);
if (simSettings->writeFileOne && simSettings->test == 0)
if (!writeFile(simSettings->logFileNameBase01, simSettings->logFileExtension01, simSettings->logFileString01, outValues, speciesList))
{
warning("Error!", "Error opening output file 1 to write to.");
clearVectors(playingFields, speciesList);
return false;
}
if (simSettings->writeFileTwo && simSettings->test == 0)
if (!writeFile(simSettings->logFileNameBase02, simSettings->logFileExtension02, simSettings->logFileString02, outValues, speciesList))
{
warning("Error!", "Error opening output file 2 to write to.");
clearVectors(playingFields, speciesList);
return false;
}
QString fileNameString03;
fileNameString03 = simSettings->logFileNameBase03;
fileNameString03.append(doPadding(runs, 3));
fileNameString03.append(simSettings->logFileExtension03);
fileNameString03.prepend(savePathDirectory.absolutePath() + QDir::separator());
if (simSettings->writeTree && simSettings->test == 0)
{
//File 03 is tree file in .nex format - without zero padding
QFile file03(fileNameString03);
if (!file03.open(QIODevice::WriteOnly | QIODevice::Text))
{
warning("Error!", "Error opening treefile to write to.");
clearVectors(playingFields, speciesList);
return false;
}
QTextStream file03TextStream(&file03);
QString logFileString03Tmp(simSettings->logFileString03);
logFileString03Tmp.replace("||Time||", printTime());
logFileString03Tmp.replace("||Settings||", simSettings->printSettings());
file03TextStream << logFileString03Tmp;
for (int i = 0; i < speciesList.count(); i++)
{
file03TextStream << (QString("%1").arg(i + 1));
file03TextStream << "\t\t" << "Species_" << doPadding(i, paddingAmount(speciesList.length())) << ",\n";
}
file03TextStream << "\t\t;\n\ntree tree1 = [&R]";
QString newickString(printNewickWithBranchLengths(0, speciesList, true));
// Remove text for phangorn
newickString.remove("Species_000");
newickString.remove("Species_00");
newickString.remove("Species_0");
newickString.remove("Species_");
file03TextStream << newickString << ";\n\nEND;";
file03.close();
}
//Sort memory
if (simSettings->test == 0)
{
clearVectors(playingFields, speciesList);
}
return true;
}
/************** Simulation functions *************/
Organism simulation::initialise()
{
/***** Initialise the playing field with an individual near a fitness peak *****/
//Want first organism to start somewhere near a fitness peak else short runs will just be a move towards a peak, I think - and not reflect ongoing evolutionary change
//Obviously this is *not* the case for radiations e.g. terrestrialisation. But those are relatively rarer, I guess?
//Worth thinking about anyway...
//Note here that if stochastic layer is enabled, initialise organism calls the mapping function from the initialisation - no need to do it here
//Record min (best) fitness
quint32 minimumFitness = static_cast<quint32>(-1);
Organism bestOrganism = *playingFields[0]->playingField[0];
int count = 0;
if (simSettings->playingfieldNumber < 2 || simSettings->playingfieldMasksMode != MASKS_MODE_INDEPENDENT)
{
if (!simSettings->randomSeed)
{
if (simSettings->environmentType != ENVIRONMENT_TYPE_MATCHING_PEAKS)
do
{
//First organism - initialise and fill playing field with it
if (simSettings->stochasticLayer) playingFields[0]->playingField[0]->initialise(runGenomeSize, simSettings->stochasticMap);
else playingFields[0]->playingField[0]->initialise(runGenomeSize);
playingFields[0]->playingField[0]->fitness = fitness(playingFields[0], playingFields[0]->playingField[0], runFitnessTarget);
if (static_cast<quint32>(playingFields[0]->playingField[0]->fitness) < minimumFitness)
{
bestOrganism = *playingFields[0]->playingField[0];
minimumFitness = static_cast<quint32>(bestOrganism.fitness);
}
count++;
}
while (count < 200);
//If we have match fitness peaks, we probably want our individuals to have similar fitnesses across environment
else
{
quint32 minimumSumDifferences = ~0;
do
{
//First organism - initialise and fill playing field with it
if (simSettings->stochasticLayer) playingFields[0]->playingField[0]->initialise(runGenomeSize, simSettings->stochasticMap);
else playingFields[0]->playingField[0]->initialise(runGenomeSize);
//Work out fitnesses for all environments - to see if they are the same
QVector <int> fitnesses;
for (int i = 0; i < runEnvironmentNumber; i++) fitnesses.append(fitness(playingFields[0], playingFields[0]->playingField[0], runFitnessTarget));
int sumOfDifferences = 0;
for (int i = 0; i < fitnesses.length() - 1; i++) sumOfDifferences += qAbs(fitnesses[i] - fitnesses[i + 1]);
//Then work out overall fitness
playingFields[0]->playingField[0]->fitness = fitness(playingFields[0], playingFields[0]->playingField[0], runFitnessTarget);
//We care most about having similar fitnesses - work towards getting identical fitnesses on all playingfields
if (static_cast<quint32>(sumOfDifferences) < minimumSumDifferences)
{
bestOrganism = *playingFields[0]->playingField[0];
minimumFitness = static_cast<quint32>(bestOrganism.fitness);
minimumSumDifferences = static_cast<quint32>(sumOfDifferences);
}
//If, however, the sum of the differences is the same (most likely zero) - then we want the smallest
else if ((static_cast<quint32>(sumOfDifferences) == minimumSumDifferences) && (static_cast<quint32>(playingFields[0]->playingField[0]->fitness) < minimumFitness))
{
bestOrganism = *playingFields[0]->playingField[0];
minimumFitness = static_cast<quint32>(bestOrganism.fitness);
}
count++;
}
while (count < 2000);
}
}
else
{
if (simSettings->stochasticLayer) playingFields[0]->playingField[0]->initialise(runGenomeSize, simSettings->stochasticMap);
else playingFields[0]->playingField[0]->initialise(runGenomeSize);
bestOrganism = *playingFields[0]->playingField[0];
}
}
//Need to initialise sensibly if there are different masks for different playing fields
else
{
if (theMainWindow != nullptr) theMainWindow->setStatus("Initialialising simulation - given the non-identical masks, this will take a few seconds.");
qApp->processEvents();
if (theMainWindow != nullptr) theMainWindow->addProgressBar(0, 5000);
do
{
//First organism - initialise and fill playing field with it
if (simSettings->stochasticLayer) playingFields[0]->playingField[0]->initialise(runGenomeSize, simSettings->stochasticMap);
else playingFields[0]->playingField[0]->initialise(runGenomeSize);
playingFields[0]->playingField[0]->fitness = fitness(playingFields[0], playingFields[0]->playingField[0], runFitnessTarget);
//Given that playing field masks are different, now we need to initialise with the best organism we can for all.
//Currently implemented using the best mean fitness of all organisms tried
QVector <int> fitnesses;
for (auto p : std::as_const(playingFields)) fitnesses.append(fitness(p, p->playingField[0], runFitnessTarget));
double meanFitness = 0;
for (auto i : fitnesses) meanFitness += i;
meanFitness = static_cast<double>(meanFitness) / static_cast<double>(fitnesses.count());
if (static_cast<quint32>(meanFitness) < minimumFitness)
{
bestOrganism = *playingFields[0]->playingField[0];
minimumFitness = static_cast<quint32>(meanFitness);
}
count++;
if (count % 100 == 0 && theMainWindow != nullptr) theMainWindow->setProgressBar(count);
}
while (count < 5000);
if (theMainWindow != nullptr) theMainWindow->hideProgressBar();
}
return bestOrganism;
}
int simulation::coinToss(const playingFieldStructure *pf)
{
//Which organism to select
int select = -1;
if (simSettings->noSelection) select = QRandomGenerator::global()->bounded(pf->playingField.count());
else
{
//Move down the list and select one - make it likely it is near the top, so has good fitness (i.e. near level zero)
//Currently 50% chance it'll choose the first, and so on, a la coin toss
int marker = 0;
//Note that simSettings->selectionCoinToss is a double - hence all the casting below
while (static_cast<double>(QRandomGenerator::global()->generate()) > (static_cast<double>(maxRand) / simSettings->selectionCoinToss)) if (++ marker >= pf->playingField.count())marker = 0;
//Do this by using marker to work out which nth value from fittest we want to select, then find where this is in playing field and assign to array
QVector <bool> ignoreList(pf->playingField.count(), false);
QVector <int> foundPool;
bool found = false;
int foundCount = 0;
while (found == false)
{
//Find the correct genome to duplicate, rather than sorting
int smallest[2] {(runGenomeSize * 5), 0};
for (int i = 0; i < pf->playingField.count(); i++)
{
//Go through playing field and find smallest fitness, and record how many there are of this.
if (!ignoreList[i])
{
if (pf->playingField[i]->fitness < smallest[0])
{
smallest[0] = pf->playingField[i]->fitness;
smallest[1] = 1;
}
else if (pf->playingField[i]->fitness == smallest[0])
smallest[1]++;
}
}
foundCount += smallest[1];
//If you need to get e.g. position #2, then the number you have to find is 3 - 0,1 and 2, hence >
if (foundCount > marker)found = true;
for (int i = 0; i < pf->playingField.count(); i++)
{
//If found smallest, add all organisms with best fit to environment to a list to select between
if (found && pf->playingField[i]->fitness == smallest[0])foundPool.append(i);
else if (!found && pf->playingField[i]->fitness == smallest[0])ignoreList[i] = true;
}
}
//Sort out found pool here - create select from a random member of the found pool
//Random number up to size of pool
int integerPointSelect = QRandomGenerator::global()->bounded(foundPool.count());
select = foundPool[integerPointSelect];
}
return select;
}
void simulation::mutateOrganism(Organism &progeny, const playingFieldStructure *pf)
{
//Mutate
int temporaryFitness = progeny.fitness;
//Work out number - need 4x if stochastic layer present
double mutations = 0.0;
if (simSettings->stochasticLayer) mutations = (static_cast<double>(runGenomeSize * 4) / 100.) * simSettings->organismMutationRate;
else mutations = (static_cast<double>(runGenomeSize ) / 100.) * simSettings->organismMutationRate;
double organismMutationIntegral = static_cast<int>(mutations);
double fractional = modf(mutations, &organismMutationIntegral);
int mutationNumber = static_cast<int>(organismMutationIntegral);
//Due to rounding the above always results in fewer mutations than would be expected - the -110 below ensures an average of 1 mutation per 100 base pairs
if (QRandomGenerator::global()->generateDouble() < fractional ) mutationNumber++;
QVector <int> SNPs;
//Apply mutation - note that this does allow multiple hits (and therefore potentially no change) as currently implemented
for (int i = 0; i < mutationNumber; i++)
{
//Scale random number to genome size
int mutationPositionInteger = 0;
if (simSettings->stochasticLayer) mutationPositionInteger = QRandomGenerator::global()->bounded(runGenomeSize * 4);
else mutationPositionInteger = QRandomGenerator::global()->bounded(runGenomeSize);
SNPs.append(QRandomGenerator::global()->bounded(runGenomeSize));
if (simSettings->stochasticLayer) progeny.stochasticGenome[mutationPositionInteger] = !progeny.stochasticGenome[mutationPositionInteger];
else progeny.genome[mutationPositionInteger] = !progeny.genome[mutationPositionInteger];
}
if (simSettings->stochasticLayer) progeny.mapFromStochastic(simSettings->stochasticMap);
//Update fitness
progeny.fitness = fitness(pf, &progeny, runFitnessTarget);
//Undo mutations if discard deleterious is on, and new fitness is worse than old
if (simSettings->discardDeleterious && (temporaryFitness < progeny.fitness))
{
if (simSettings->stochasticLayer)
{
for (int i = 0; i < SNPs.count(); i++)progeny.stochasticGenome[SNPs[i]] = !progeny.stochasticGenome[SNPs[i]];
progeny.mapFromStochastic(simSettings->stochasticMap);
}
else for (int i = 0; i < SNPs.count(); i++)progeny.genome[SNPs[i]] = !progeny.genome[SNPs[i]];
}
}
void simulation::updateTNTstring(QString &TNTstring, int progParentSpeciesID, int progSpeciesID)
{
QString progenySpeciesID;
if (simSettings->runMode == RUN_MODE_TAXON) progenySpeciesID = doPadding(progParentSpeciesID, paddingAmount(simSettings->runForTaxa));
else progenySpeciesID = doPadding(progParentSpeciesID, 4);
QString speciesID;
if (simSettings->runMode == RUN_MODE_TAXON) speciesID = doPadding(progSpeciesID, paddingAmount(simSettings->runForTaxa));
else speciesID = doPadding(progSpeciesID, 4);
//Then write string
//If first iteration, write manually so as to avoid starting with excess brackets.
if (speciesCount == 1 && simSettings->runForTaxa < 100 && simSettings->runMode == RUN_MODE_TAXON) TNTstring = "(00 01)";
else if (speciesCount == 1 && simSettings->runForTaxa < 1000 && simSettings->runMode == RUN_MODE_TAXON)TNTstring = "(000 001)";
else if (speciesCount == 1) TNTstring = "(0000 0001)";
else
{
//Then split string at the ancestral species - first search for the progenator
int position = TNTstring.indexOf(progenySpeciesID);
//You should never find a bracket or not find anything
if (position < 1) warning("Eesh", "You shouldn't see this. There's been an error writing the tree string. Please contact RJG in the hope he can sort this out.");
// Split tree file at this point, into left, and right of position.
QString treeLeft = TNTstring.left(position);
QString treeRight = TNTstring.right(TNTstring.length() - (position + progenySpeciesID.length()));
//Strip spaces if required - is not for TNT...
//if(treeLeft.at(treeLeft.length()-1)==' ')treeLeft.remove(treeLeft.length()-1,1);
//if(treeRight.at(0)==' ')treeRight.remove(0,1);
//Build new string
QString ins = QString("(%1 %2)").arg(progenySpeciesID, speciesID);
TNTstring = treeLeft + ins + treeRight;
}
}
//This returns the number in the playingfield that needs to be overwritten
int simulation::calculateOverwrite(const playingFieldStructure *pf, const int speciesNumber)
{
int overwrite = -1;
//First we can deal with expanding playingfield cases
//In both (new species or not) we have overwrite our chosen species in the playingfield
if (simSettings->expandingPlayingfield) overwrite = speciesNumber;
//Then this is not the case, we can deal with the non expanding playingfield cases
//We have the option of a random overwrite
else if (simSettings->randomOverwrite)
{
overwrite = QRandomGenerator::global()->bounded(pf->playingField.count());
if (overwrite == pf->playingField.count()) overwrite = pf->playingField.count() - 1;
}
//Or overwriting the least fit (or one of the least fit)
else
{
//Now settle by overwriting least fit one, or if >1 lowest fitness, but overwriting a randomly chosen one of these.
QVector <int> deletePool;
int lowestFitness = -1;
//Find lowest fitness in playing field
for (auto o : pf->playingField)
if (o->fitness > lowestFitness)
lowestFitness = o->fitness;
//Write list of least fit organisms
for (int i = 0; i < pf->playingField.count(); i++)
if (pf->playingField[i]->fitness == lowestFitness)deletePool.append(i);
if (deletePool.count() == 1) overwrite = deletePool[0];
else
{
//Scale random number to size of pool
int deletePositionInteger = QRandomGenerator::global()->bounded(deletePool.count());
overwrite = deletePool[deletePositionInteger];
}
}
return overwrite;
}
void simulation::applyPerturbation()
{
if (perturbationOccurring == 0)
{
//Sort variables
perturbationStart = iterations;
perturbationEnd = (iterations / 10) + iterations;
perturbationOccurring++;
//Set up mixing perturbation if required
if (simSettings->mixingPerturbation)
{
runMixingProbabilityOneToZero *= 10;
runMixingProbabilityZeroToOne *= 10;
}
//Set up environmental perturbation if required
if (simSettings->environmentType == ENVIRONMENT_TYPE_PERTURBATION && perturbationOccurring == 0)
{
for (auto pf : std::as_const(playingFields))
for (int k = 0; k < runEnvironmentNumber; k++)
pf->environments[k].setUpPerturbation(perturbationStart, perturbationEnd);
//Copy over if identical
if (simSettings->playingfieldNumber > 1 && simSettings->playingfieldMasksMode == MASKS_MODE_IDENTICAL)