Class IBSPopulation<M extends Module<?>, P extends IBSPopulation<?,?>>
- Type Parameters:
M- the module type controlling the population dynamicsP- the concrete population type used as opponent reference
- Direct Known Subclasses:
IBSDPopulation, IBSMCPopulation
Note: traits cannot be handled here because they are
represented by ints in discrete models but doubles in
continuous models.
- Author:
- Christoph Hauert
- See Also:
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected booleanOptimization: Flag to indicate whether adjusting instead of recalculating scores is possible.protected AbstractGeometryThe geometry of the competition graph.protected IBSGroupReference to the competition/reference/model group.(package private) booleanThe flag to indicate whether consistency checks on the state of the IBS model are requested.private double[]Conveninece variable to store cumulative probability distributions for replicator updating.protected intHelper variable to store index of focal individual (birth) that got updated during debug step.protected intHelper variable to store index of target individual (death) that got updated during debug step.protected int[]Helper variable to store array of indices of individual that served as models during debug step.protected intHelper variable to number of individual that served as models during debug step.protected booleanHelper flag to indicate an actual trait change during debug step.protected RNGDistribution.GeometricThe distribution to determine the number of migrants.protected EvoLudoThe pacemaker of all models.protected double[]The array of individual fitness values.private static final intThreshold population size for using the Gillespie optimization for picking individuals proportional to fitness.protected double[]Array to hold scores of individuals during payoff calculations.protected booleanOptimization: Flag to indicate whether lookup tables can be used.private static final StringString for formatting log messagesprotected AbstractGeometryThe geometry of the interaction graph.protected int[]The array of individual interaction counts.protected IBSGroupReference to the interaction group.protected booleanFlag to indicate whether the model entertains multiple species, i.e.protected booleanFlag to indicate whether dynamic is neutral, i.e.protected LoggerLogger for keeping track of and reporting events and issues.protected Map2FitnessThe map converting scores to fitness and vice versa.protected intOptimization: The index of the individual that currently holds the maximum score.protected doubleThe absolute maximum fitness in the population.protected doubleThe absolute maximum score in the population.protected IBS.MigrationTypeThe type of migration.protected doubleThe absolute minimum fitness in the population.protected doubleThe absolute minimum score in the population.protected MThe module associated with this population.protected MutationThe mutation parameters.(package private) intThe number of concistency issues encountered in the state of the IBS model.protected intOptimization: Number of interactions in well-mixed populations for update rules that take advantage ofIBSDPopulation.updateMixedScores().protected intThe size of the population.protected intThe number of traits in module.protected PThe interaction partner/opponent of this populationopponent.getModule()==getModule().getOpponent().protected booleantrueif optimizations for homogeneous populations requested.protected double[]The array containing the probabilities for adding links to the interaction and competition graphs.protected booleanFlag to indicate whether player scores are averaged (default) or accumulated.protected IBS.ScoringTypeFlag to indicate whether scores are reset whenever a player adopts the trait of another (default) or only if an actual change of trait occurred.(package private) PlayerUpdateThe update type of players.protected doubleThe probability of migration.(package private) PopulationUpdateThe population update.protected double[]The array containing the probabilities for rewiring links of the interaction and competition graphs.protected RNGDistributionThe shared random number generator to ensure reproducibility of results.protected double[]The array of individual scores.protected double[]Array to hold scores of individuals during payoff calculations for small groups (not all neighbours).protected Features.StaticConvenience field for static modules to avoid casts.protected doubleThe total fitness of the population.(package private) doubleThe fraction of the population that gets updated in synchronous updates.protected double[]The array of individual tags counts.protected double[]Optimization: the lookup table for fitness in well-mixed populations.protected double[]Optimization: the lookup table for scores in well-mixed populations.protected intThe index of vacant sites or-1if module does not support vacancies. -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedIBSPopulation(EvoLudo engine, M module) Creates a population of individuals for IBS simulations. -
Method Summary
Modifier and TypeMethodDescriptionvoidadjustGameScoresAt(int me) Adjust scores of focal playermeand its neighbours (interaction partners).abstract voidadjustPairGameScoresAt(int me) Adjusts scores of focal individual with indexmeand its neighbors aftermechanged trait.abstract voidadjustScoreAt(int index, double adjust) Adjust score of individual with indexindexbyadjustand update all applicable helper variables, e.g.abstract voidadjustScoreAt(int index, double before, double after) Adjust score of individual with indexindexfrombeforetoafterand update all applicable helper variables, e.g.booleanbecomesVacantAt(int index) Check if site with indexindexwill become vacant in this time step.booleancheck()Check all model parameters for consistency and adjust if necessary (and feasible).private voidCheck consistency when not using lookup tables.(package private) voidValidate competition sampling rules for well-mixed populations and adjust if required.(package private) voidCheck consistency of scores and fitness values for modules that implement Payoffs.booleanCheck if population has converged.private voidcheckFitnessSum(double sumFitnessStore) Check consistency of total fitness.(package private) booleanCheck the interaction and competition geometries for consistency and adjust if necessary (and feasible).(package private) booleanRewire the interaction and competition geometries if requested.private voidcheckIndividualConsistency(int n) Check consistency of scores for a single individual.(package private) booleancheckInteractions(int nGroup) Validate interaction structures and adjust incompatible settings.(package private) booleancheckLookupTable(int nGroup, boolean ephemeralScores) Check whether lookup tables for scores and fitness can be used.private voidCheck consistency of scores when using lookup tables.(package private) voidCheck consistency of migration settings and adjust if necessary (and feasible).private voidCheck consistency when scores are not adjusted.(package private) booleancheckNoLookupTable(boolean ephemeralScores) Free memory used for lookup tables and allocate arrays for scores, fitness and interactions.(package private) booleanCheck whether optimizations for homogeneous states can be used.(package private) booleancheckPayoffs(int nGroup) Check settings for modules implementing Payoffs.private voidcheckTraitScores(double[] typeScoresStore, double[] typeFitnessStore) Check consistency of scores for all traits.abstract voidcommitTraitAt(int index) The change of a trait of the player atindexis stored in a temporary variable and must be committed before proceeding.abstract voidAfter a synchronous update step the new state must be copied back to become the current state.protected voidOverride in subclass for example to mark those individuals in the GUI that were involved in the debug step.protected voiddebugScores(double hit) Log report if picking failed to shed better light on what might be the root cause for the failure.protected voiddebugUpdate(int me, int rGroupSize, double nProb, double norm, double choice) Log report if updating failed to shed better light on what might be the root cause for the failure.voiddebugUpdatePopulationAt(int focal) Update focal individual with indexfocalfor debugging.protected abstract booleanCheck if scores can be adjusted rather than recalculated after an individual changed its trait.voidPerform a birth-death migration, where a focal individual (selected proportional to fitness) produces a migrant offspring, which replaces another member of the population uniformly at random.voidPerform a death-birth migration, where a member of the population (selected uniformly at random) dies and the remaining individuals compete to repopulate the vacant site.voidPerform diffusion migration, which is implemented as two players swap their locations while leaving their respective neighbourhood structure untouched.voidPerform asynchronous migration.intPerform synchronous migration.voidencodeFitness(StringBuilder plist) Encode the fitness of all individuals in the IBS model in aplistinspiredXMLstring.voidencodeGeometry(StringBuilder plist) Encode the interaction and competition structures of the IBS model in aplistinspiredXMLstring.voidencodeInteractions(StringBuilder plist) Encode the interactions of all individuals in the IBS model in aplistinspiredXMLstring.abstract voidencodeTraits(StringBuilder plist) Encode the traits of all individuals in the IBS model in aplistinspiredXMLstring.private StringformatInfoAt(int focal, int model) Helper method to format information about updating the focal individual at indexfocalusing the model individual with indexmodel.Gets the competition geometry.Gets the competition/reference/model group.getFitness(int digits) Gets the fitness of all individuals with precisiondigits.doublegetFitnessAt(int idx) Gets the fitness of the individual with indexidx.<T> voidgetFitnessData(T[] colors, ColorMap.Gradient1D<T> colorMap) Returns the fitness of all individuals in this population coded as colors in the arraycolorsusing the mapcolorMap.voidgetFitnessHistogramData(double[][] bins) Generates a histogram of the fitness distribution in this population.getFitnessNameAt(int idx) Gets the formatted and prettyfied fitness of the individual with indexidxas a string.getFitnessNameAt(int idx, boolean pretty) Gets the formatted fitness of the individual with indexidxas a string.Gets the interaction geometry.intgetInteractionsAt(int idx) Gets the number of interactions of the individual with indexidx.Gets the interaction group.doubleReturns the maximum scoreminin this population, taking the population structure and payoff accounting into account.abstract double[]getMeanFitness(double[] mean) Returns the mean fitness of this population in the arraymean.abstract double[]getMeanTraits(double[] mean) Returns the mean trait(s) of this population in the arraymean.doubleGets the migration probability.Gets the type of migrations.doubleReturns the minimum scoreminin this population, taking the population structure and payoff accounting into account.Gets the module associated with this population.intgetNMean()Return the number of mean values for this population (for traits or fitness).(package private) intgetNMixedInteractions(int nGroup) Determine the number of interactions in well-mixed populations with lookup tables.booleanGets whether player scores are averaged (as opposed to accumulated).Gets the type for managing scores of individuals.intGets current population size.Gets the population update.doublegetScoreAt(int idx) Gets the score of the individual with indexidx.getScoreNameAt(int idx) Gets the formatted score of the individual with indexidx.getScores(int digits) Gets the scores of all individuals with precisiondigits.doubleGets the update rate of this species.abstract StringGets the status of the as a formatted string.doubleGet the fraction of the population that gets updated in synchronous updates.doublegetTagAt(int idx) Gets the tag of the individual with indexidx.<T> voidgetTagData(T[] colors, ColorMap<T> colorMap) Returns the tags of all individuals in this population coded as colors in the arraycolorsusing the mapcolorMap.getTagNameAt(int idx) Gets the formatted tag of the individual with indexidxas string.double[]getTags(double[] mem) Copies the tags of all individuals in the population and returns them in the arraymem.doubleGets the total fitness of the population.abstract <T> voidgetTraitData(T[] colors, ColorMap<T> colorMap) Returns the traits of all individuals in this population coded as colors in the arraycolorsusing the mapcolorMap.abstract StringgetTraitNameAt(int index) Gets the formatted name of the trait of the individual at siteindex.abstract booleanhaveSameTrait(int a, int b) Check if individuals with indexaand indexbhave the same traits.voidinit()Initialize the model.voidConvenience method during development to perform a number of consistency checks of the current state.booleanCheck if population is monomorphic.abstract booleanisSameTrait(int a) Check if individual with indexahas switched traits.booleanisVacantAt(int index) Check if site with indexindexis occupied by an individual or vacant.(package private) voidlogAccountingIssue(double actual, double expected) Log an accounting issue.(package private) voidlogAccountingIssue(String descr, double actual, double expected, String issue) Log an accounting issue.(package private) voidlogFitnessIssue(int idx, double actual, double expected) Log a fitness issue.(package private) voidlogMapIssue(int idx, double actual, double expected) Log a mapping issue.(package private) voidlogScoringIssue(int idx, double actual, double expected) Log a scoring issue.(package private) voidlogScoringIssue(int idx, double actual, String issue) Log a scoring issue.protected abstract booleanmaybeMutateAt(int focal, boolean switched) Consider mutating the trait of the focal individual with indexfocal.protected abstract voidmaybeMutateMoran(int source, int dest) Consider mutating the trait of the parent individual with indexsource.protected voidmigrateMoran(int source, int dest) Perform a single Moran update for the reproducing node with indexsourceand the node that gets replaced with indexdest.booleanmouseHitNode(int hit) Called from GUI if node/individual with indexidxreceived a mouse click or tap.booleanmouseHitNode(int hit, boolean alt) Called from GUI if node/individual with indexidxreceived a mouse click or tap and indicates whether thealt-key had been pressed.intmutate()Perform a mutation event.abstract intmutateAt(int focal) Mutate the trait of the focal individual with indexfocal.intnextBinomial(double p, int n) Draw a binomially distributed random integer.private intOptimize homogeneous population states by skipping to the next mutation event.private intHandle failed pick.private intpickFailed(double remainder) Handle failed pick and report details about failure.intDraws the index of a member of the population with a probability proportional to fitness.intpickFitFocalIndividual(int excl) Draws the index of a member of the population with a probability proportional to fitness but excluding the individual with the indexexcl.private intDraws the index of a member of the population with a probability proportional to fitness but assuming no vacant sites.private intpickFitFocalNoVacant(int excl) Draws the index of a member of the population with a probability proportional to fitness but assuming no vacant sites.private intpickFitFocalNoVacantGillespieOptimized(int excl) Draws the index of a member of the population with a probability proportional to fitness but assuming no vacant sites.private intDraws the index of a member of the population with a probability proportional to fitness but assuming vacant sites.private intpickFitFocalSkipVacant(int excl) Draws the index of a member of the population with a probability proportional to fitness but assuming vacant sites.private intpickFitFocalSkipVacantGillespieOptimized(int excl) Draws the index of a member of the population with a probability proportional to fitness but assuming vacant sites.protected intpickFitNeighborAt(int me) Pick a neighbour of the focal individualmewith probability proportional to their fitness.protected intpickFitNeighborAt(int me, boolean withSelf) Pick a neighbour of the focal individualmewith probability proportional to their fitness.private intpickFitNeighborNoVacantAt(int me, boolean withSelf) Pick a neighbour of the focal individualmewith probability proportional to their fitness assuming no vacant sites.private intpickFitNeighborSkipVacantAt(int me, boolean withSelf) Pick a neighbour of the focal individualmewith probability proportional to their fitness assuming vacant sites.private intpickFocalHead(int pick) Pick a focal individual uniformly at random starting from head.private intpickFocalHead(int pick, int excl) Pick a focal individual uniformly at random starting from head, excluding individualexcl.intDraws the index of a individual of the population uniformly at random.intpickFocalIndividual(int excl) Draws the index of a individual of the population uniformly at random but excluding the individual with indexexcl.intDraws the index of a site in the population uniformly at random, irrespective of whether it is occupied or not.intpickFocalSite(int excl) Draws the index of a site in the population uniformly at random, irrespective of whether it is occupied or not.private intPick a focal individual uniformly at random but skipping vacant sites.private intpickFocalSkipVacant(int excl) Pick a focal individual uniformly at random but excluding the individual with indexexcl.private intpickFocalTail(int pick) Pick a focal individual uniformly at random starting from tail.private intpickFocalTail(int pick, int excl) Pick a focal individual uniformly at random starting from tail, excluding individualexcl.intpickNeighborSiteAt(int me) Picks a neighbouring site of the focal individualmeuniformly at random.private intpickNeutralNeighbourAt(int me, boolean withSelf) Helper method to do picking under neutral conditions (no or negligible fitness differences).voidplayGameAt(int me) Update the score of individualme.voidplayGameSyncAt(int me) Update the score of individualme.abstract voidplayGroupGameAt(IBSGroup group) Play a group interaction with the individuals ingroup.abstract voidplayPairGameAt(IBSGroup group) Play a pairwise interaction with the individuals ingroup.abstract booleanpreferredPlayerBest(int me, int best, int sample) For deterministic updating with multiple traits (more than two), it must be specified which trait is the preferred one.abstract voidPrior to a synchronous update step the current state must be duplicated in preparation for processing the next step.protected doubleprocessScore(double score, int count) Process the accumulatedscorein this population, taking the updating into account.doublerandom01()Draw a uniformly distributed randomdoublefrom the semi-closed interval[0, 1)with 32bit resolution.intrandom0n(int n) Draw a uniformly distributed random integer number from the semi-closed interval[0, n).doublerandomGaussian(double mean, double sdev) Draw a Gaussian (normal) distributed randomdouble.voidremoveScoreAt(int index, double nilscore) Removes the scorenilscorebased on a single interaction from the individual with indexindex.voidremoveScoreAt(int index, double nilscore, int incr) Removes the scorenilscorebased onincrinteractions from the individual with indexindex.voidreset()Reset the model.(package private) voidresetEphemeral(int nGroup) Precalculate the number of interactions for ephemeral payoffs and store in the interactions array.(package private) voidEnsure that Moran type population updates have non-negative fitness values.voidresetScoreAt(int index) Reset score of individual at indexindex.voidReset scores and fitness of all individuals to zero.voidReset all traits in preparation of the next update step.booleanrestoreFitness(Plist plist) Restore the fitness of all individuals encoded in theplistinspiredmapofkey, value-pairs.booleanrestoreGeometry(Plist plist) Restore the interaction and competition structures encoded in theplistinspiredmapofkey, value-pairs.booleanrestoreInteractions(Plist plist) Restore the interactions of all individuals encoded in theplistinspiredmapofkey, value-pairs.abstract booleanrestoreTraits(Plist plist) Restore the traits of all individuals encoded in theplistinspiredmapofkey, value-pairs.private doublesecond(int excl) Find the second highest score.voidsetAddwire(double[] addwire) Set the probabilities for adding links to the interaction and competition graphs.voidsetConsistencyCheck(boolean check) Enable consistency checks of the state of the IBS model.(package private) voidSet the names of the interaction and competition geometries based on the module name and whether the geometries are the same or different.protected voidFind the index of the individual with the highest score.voidsetMigrationProb(double aValue) Sets the migration probability toaValue.voidSets the type of migrations totype.voidsetOpponentPop(IBSPopulation<?, ?> opponent) Set the interaction partner/opponent of this population.voidsetPlayerScoreAveraged(boolean aver) Sets whether scores of individuals are averaged over multiple interactions or accumulated.voidSets the type for managing scores of individuals.voidsetPopulationUpdate(PopulationUpdate populationUpdate) Sets the population update.voidsetRewire(double[] rewire) Set the probabilities for rewiring links of the interaction and competition graphs.voidsetScoreAt(int index, double newscore, int inter) Sets the score of individual with indexindextonewscoreas the result ofinterinteractions.voidsetSyncFraction(double sync) Set the fraction of the population that gets updated in synchronous updates.booleansetTagAt(int idx, double tag) Sets the tag of the individual with indexidx.intstep()Perform a single IBS step, i.e.voidswapScoresAt(int idxa, int idxb) Swap the scores (and fitness) of individuals with indicesidxaandidxb.abstract voidswapTraits(int a, int b) Swap traits of individuals with indexaand indexb.private doubletotFitnessNoVacant(int me) Compute total fitness of neighbours of individualmeassuming no vacant sites.private doubletotFitnessSkipVacant(int me) Compute total fitness of neighbours of individualmeassuming vacant sites.protected booleanupdateEffScoreRange(int index, double before, double after) Keep track of highest score through a reference to the corresponding individual.private booleanupdateFailed(int me, int rGroupSize, double nProb, double norm, double choice) Handle failed adoption decision and log diagnostic details before aborting.voidupdateFitnessAt(int idx) Update the fitness of the individual with indexidxby mapping its current score.voidupdateFromModelAt(int me, int you) Update individual with indexmeand adopt the trait of individual with indexyou.voidRetrieve and store extremal scores and fitnesses to reduce calls toModule.private intUpdate all individuals in the population once asynchronously.protected voidPerform a single, asynchronous update of the trait of a randomly selected individual.voidupdatePlayerAsyncAt(int me) Update the trait of the focal individual with indexme.booleanupdatePlayerAt(int me) Perform a single update of the individual with indexme.booleanupdatePlayerAt(int me, int[] refGroup, int rGroupSize) Perform a single update of the individual with indexmeusing therGroupSizemodels in the arrayrefGroup.protected booleanupdatePlayerBest(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexmeby adopting the trait of the best performing reference individual among therGroupSizemodels in the arrayrefGroup.protected booleanupdatePlayerBestHalf(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexmeby adopting the trait of the best performing reference individual among the therGroupSizemodels in the arrayrefGroup.booleanupdatePlayerBestResponse(int me, int[] group, int size) Best-response update.intPerform a single ecological update of an individual selected uniformly at random.protected intupdatePlayerEcologyAt(int index) Perform a single ecological update of the site with indexindex.voidPerform a single, Moran (Birth-death) update for a random individual selected with a probability proportional to fitness.protected voidupdatePlayerMoranBirthDeathAt(int parent) Perform a Moran (Birth-death) update for the focal individual with indexparentto produce a clonal offspring and replace one of the parent's neighbours selected uniformly at random.voidPerform a single Moran (death-Birth) update for a site selected uniformly at random.protected voidupdatePlayerMoranDeathBirthAt(int vacant) Perform a single Moran (death-Birth) update for the focal site with indexvacant.voidPerform a single, Moran (imitate) update for a site selected uniformly at random.protected voidupdatePlayerMoranImitateAt(int imitator) Update the focal individual with indeximitatorby comparing its own payoff and those of its neighbors.voidupdatePlayerSwap(int a, int b) Swap players in locationsaandb.protected booleanupdateProportionalAbs(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexmeby adopting the trait of one reference individual (including itself) among the therGroupSizemodels in the arrayrefGroupwith a probability proportional to their scores.private booleanupdateReplicator(int me, int[] refGroup, int rGroupSize, boolean betterOnly) Helper method for replicator type updates.protected booleanupdateReplicatorHalf(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexmeby adopting the trait of one reference individual among the therGroupSizemodels in the arrayrefGroup.private booleanupdateReplicatorNeutral(int me, int[] refGroup, int rGroupSize, boolean betterOnly) Replicator type update in the neutral case.private doubleupdateReplicatorNoise(int[] refGroup, int rGroupSize, double myFitness, boolean betterOnly) Replicator type update with noise.private doubleupdateReplicatorNoNoise(int[] refGroup, int rGroupSize, double myFitness, boolean betterOnly) Replicator type update without noise.protected booleanupdateReplicatorPlus(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexmeby adopting the trait of one reference individual among the therGroupSizemodels in the arrayrefGroup.protected voidupdateScoreAt(int me, boolean switched) Update the scores of the focal individual with indexme.voidupdateScoreAt(int index, double newscore) Update the score of the individual with indexindexby addingnewscorefrom single interaction.voidupdateScoreAt(int index, double newscore, int incr) Update the score of the individual with indexindexby adding (incr > 0or removing,incr < 0)newscoreas the result ofincrinteractions.voidUpdate the scores of all individuals in the population.private intUpdate all individuals in the population synchronously.private intUpdate a fraction of individuals in the population synchronously.protected booleanupdateThermal(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexmeby adopting the trait of one reference individual among the therGroupSizemodels in the arrayrefGroup.private doubleupdateThermalNoise(int me, int[] refGroup, int rGroupSize) Thermal update with noise.private doubleupdateThermalNoNoise(int me, int[] refGroup, int rGroupSize) Thermal update without noise.abstract voidyalpGroupGameAt(IBSGroup group)
-
Field Details
-
engine
The pacemaker of all models. Interface with the outside world. -
module
-
staticmodule
Convenience field for static modules to avoid casts. -
opponent
The interaction partner/opponent of this populationopponent.getModule()==getModule().getOpponent(). In intra-species interactionsopponent==this. Convenience field. -
logger
Logger for keeping track of and reporting events and issues. -
rng
The shared random number generator to ensure reproducibility of results.- See Also:
-
isMultispecies
protected boolean isMultispeciesFlag to indicate whether the model entertains multiple species, i.e.nSpecies>1. Convenience field. Reduces calls toModule. -
populationUpdate
PopulationUpdate populationUpdateThe population update. -
playerUpdate
-
vacantIdx
protected int vacantIdxThe index of vacant sites or-1if module does not support vacancies. Convenience field.- See Also:
-
nTraits
protected int nTraitsThe number of traits in module. Convenience field.- See Also:
-
interaction
The geometry of the interaction graph. -
interGroup
Reference to the interaction group. -
competition
The geometry of the competition graph. -
compGroup
Reference to the competition/reference/model group. -
playerScoreAveraged
protected boolean playerScoreAveragedFlag to indicate whether player scores are averaged (default) or accumulated.- See Also:
-
playerScoring
Flag to indicate whether scores are reset whenever a player adopts the trait of another (default) or only if an actual change of trait occurred.- See Also:
-
migrationType
The type of migration. -
pMigration
protected double pMigrationThe probability of migration. -
distrMigrants
The distribution to determine the number of migrants. -
cProbs
private double[] cProbsConveninece variable to store cumulative probability distributions for replicator updating.- See Also:
-
fitness
protected double[] fitnessThe array of individual fitness values.- See Also:
-
minFitness
protected double minFitnessThe absolute minimum fitness in the population. Convenience field used for fitness based picking of focal individuals or for the GUI for scaling graphs. -
maxFitness
protected double maxFitnessThe absolute maximum fitness in the population. Convenience field used for fitness based picking of focal individuals or for the GUI for scaling graphs. -
sumFitness
protected double sumFitnessThe total fitness of the population. Convenience field used for fitness based picking of focal individuals or for the GUI for scaling graphs. -
scores
protected double[] scoresThe array of individual scores.- See Also:
-
minScore
protected double minScoreThe absolute minimum score in the population. Even though largely replaced byminFitnessin simulations it remains a useful and often more intuitive quantity than fitness when visualizing results in the GUI. Convenience field. -
maxScore
protected double maxScoreThe absolute maximum score in the population. Even though largely replaced bymaxFitnessin simulations it remains a useful and often more intuitive quantity than fitness when visualizing results in the GUI. Convenience field. -
groupScores
protected double[] groupScoresArray to hold scores of individuals during payoff calculations. -
smallScores
protected double[] smallScoresArray to hold scores of individuals during payoff calculations for small groups (not all neighbours). -
interactions
protected int[] interactionsThe array of individual interaction counts. -
tags
protected double[] tagsThe array of individual tags counts. This can be used to trace ancestry. -
nMixedInter
protected int nMixedInterOptimization: Number of interactions in well-mixed populations for update rules that take advantage ofIBSDPopulation.updateMixedScores().nMixedInteris calculated ahead of time incheck(). -
typeScores
protected double[] typeScoresOptimization: the lookup table for scores in well-mixed populations. -
typeFitness
protected double[] typeFitnessOptimization: the lookup table for fitness in well-mixed populations. -
nPopulation
protected int nPopulationThe size of the population. Convenience field to reduce calls to module. -
map2fit
The map converting scores to fitness and vice versa. Convenience field to reduce calls to module. -
adjustScores
protected boolean adjustScoresOptimization: Flag to indicate whether adjusting instead of recalculating scores is possible.Notes:
- Adjusting scores is only feasible if all individuals have a fixed number
of interactions. For example, if all individuals always interact with all
their neighbours, see
IBSGroup.SamplingType.ALL. The only exception are well-mixed populations,GeometryType.WELLMIXED. With continuous traits all possible encounters would need to be considered, which is computationally not feasible. In contrast, for discrete traits separate calculations to determine the scores of each trait type are possible. - With random interactions the scores of individuals are based on variable sets of interaction partners and their numbers of interactions may vary.
- See Also:
- Adjusting scores is only feasible if all individuals have a fixed number
of interactions. For example, if all individuals always interact with all
their neighbours, see
-
hasLookupTable
protected boolean hasLookupTableOptimization: Flag to indicate whether lookup tables can be used. -
isNeutral
-
maxEffScoreIdx
protected int maxEffScoreIdxOptimization: The index of the individual that currently holds the maximum score. This allows more efficient fitness based picking.- See Also:
-
GILLESPIE_OPTIMIZATION_THRESHOLD
private static final int GILLESPIE_OPTIMIZATION_THRESHOLDThreshold population size for using the Gillespie optimization for picking individuals proportional to fitness.- See Also:
-
mutation
The mutation parameters. -
optimizeHomo
protected boolean optimizeHomotrueif optimizations for homogeneous populations requested.Note:
- optimizations can be requested with the command line option
--optimize, seeIBSD.cloOptimize. - currently restricted to discrete traits where homogeneous population
states can be skipped by deterministically introducing new mutant after an
geometrically (exponentially) distributed waiting time (see
IBSD). - requires small mutation rates.
- does not work for variable population sizes.
- optimizations can be requested with the command line option
-
debugFocal
protected int debugFocalHelper variable to store index of focal individual (birth) that got updated during debug step. -
debugSame
protected boolean debugSameHelper flag to indicate an actual trait change during debug step. -
debugModel
protected int debugModelHelper variable to store index of target individual (death) that got updated during debug step. -
debugModels
protected int[] debugModelsHelper variable to store array of indices of individual that served as models during debug step. -
debugNModels
protected int debugNModelsHelper variable to number of individual that served as models during debug step. -
pRewire
protected double[] pRewireThe array containing the probabilities for rewiring links of the interaction and competition graphs.- See Also:
-
pAddwire
protected double[] pAddwireThe array containing the probabilities for adding links to the interaction and competition graphs.- See Also:
-
nIssues
int nIssuesThe number of concistency issues encountered in the state of the IBS model.- See Also:
-
consistencyCheckRequested
boolean consistencyCheckRequestedThe flag to indicate whether consistency checks on the state of the IBS model are requested.- See Also:
-
INSTEAD_OF
-
syncFraction
double syncFractionThe fraction of the population that gets updated in synchronous updates.
-
-
Constructor Details
-
IBSPopulation
-
-
Method Details
-
getModule
Gets the module associated with this population.- Returns:
- the module associated with this population
-
setOpponentPop
Set the interaction partner/opponent of this population.- Parameters:
opponent- the interaction partner/opponent
-
getStatus
Gets the status of the as a formatted string. This is typically used in the GUI to summarize the progress of the model.- Returns:
- the status of the population
-
prepareTraits
public abstract void prepareTraits()Prior to a synchronous update step the current state must be duplicated in preparation for processing the next step.- See Also:
-
commitTraits
public abstract void commitTraits()After a synchronous update step the new state must be copied back to become the current state.- See Also:
-
commitTraitAt
public abstract void commitTraitAt(int index) The change of a trait of the player atindexis stored in a temporary variable and must be committed before proceeding.- Parameters:
index- the index of the player that needs to have its new trait committed
-
haveSameTrait
public abstract boolean haveSameTrait(int a, int b) Check if individuals with indexaand indexbhave the same traits.- Parameters:
a- the index of first individualb- the index of second individual- Returns:
trueif the two individuals have the same traits
-
isSameTrait
public abstract boolean isSameTrait(int a) Check if individual with indexahas switched traits.Note: this test is only meaningful before trait are committed.
- Parameters:
a- index of individual- Returns:
trueif trait remained unchanged- See Also:
-
swapTraits
public abstract void swapTraits(int a, int b) Swap traits of individuals with indexaand indexb.Note: the traits still need to be committed.
- Parameters:
a- the index of first individualb- the index of second individual- See Also:
-
playPairGameAt
Play a pairwise interaction with the individuals ingroup.- Parameters:
group- the group of individuals interacting in pairs
-
playGroupGameAt
Play a group interaction with the individuals ingroup.- Parameters:
group- the group of interacting individuals
-
adjustPairGameScoresAt
public abstract void adjustPairGameScoresAt(int me) Adjusts scores of focal individual with indexmeand its neighbors aftermechanged trait. Only works ifadjustScores==true.Important: new trait must not yet have been committed.
- Parameters:
me- the index of the focal individual
-
yalpGroupGameAt
Counterpart ofplayGroupGameAt(IBSGroup),playGameAt(int)and/orplayGameSyncAt(int). Removes the payoffs of group interactions.- Parameters:
group- the interaction group
-
adjustScoreAt
public abstract void adjustScoreAt(int index, double before, double after) Adjust score of individual with indexindexfrombeforetoafterand update all applicable helper variables, e.g.sumFitness.Important: Use only to adjust scores of individuals that did not change trait.
- Parameters:
index- the index of the individualbefore- the score before adjustmentsafter- the score after adjustments
-
adjustScoreAt
public abstract void adjustScoreAt(int index, double adjust) Adjust score of individual with indexindexbyadjustand update all applicable helper variables, e.g.sumFitness.- Parameters:
index- the index of the individualadjust- the score adjustment
-
updatePlayerBestResponse
public boolean updatePlayerBestResponse(int me, int[] group, int size) Best-response update.Important:
- The array
groupis untouchable because it may refer to the population structure. Any change would also permanently change the structure. - The best-response update must be implemented in subclasses that override this method. By default throws an error.
- Instead of overriding the method, subclasses may remove
PlayerUpdate.Type.BEST_RESPONSEfromPlayerUpdate#clo.
- Parameters:
me- the index of individual to updategroup- the array with indices of reference groupsize- the size of the reference group- Returns:
trueif trait changed (signaling score needs to be reset)
- The array
-
preferredPlayerBest
public abstract boolean preferredPlayerBest(int me, int best, int sample) For deterministic updating with multiple traits (more than two), it must be specified which trait is the preferred one.Summary: does 'me' prefer 'sample' over 'best'?
- Parameters:
me- the index of the focal individualbest- the index of the best performing individualsample- the index of the sample type- Returns:
trueifsampleis preferred overbest
-
isVacantAt
public boolean isVacantAt(int index) Check if site with indexindexis occupied by an individual or vacant.Note: Assumes that trait are committed.
- Parameters:
index- the index of the individual/site to check- Returns:
trueif siteindexis vacant
-
becomesVacantAt
public boolean becomesVacantAt(int index) Check if site with indexindexwill become vacant in this time step.Note: Assumes that trait are not committed.
- Parameters:
index- the index of the individual/site to check- Returns:
trueif siteindexwill become vacant
-
isMonomorphic
public boolean isMonomorphic()Check if population is monomorphic.Note: In models that admit vacant sites this does not imply a homogeneous (or absorbing) state of the population. Without vacant sites monomorphic states are absorbing, at least in the absence of mutations.
- Returns:
trueif population is monomorphic- See Also:
-
checkConvergence
public boolean checkConvergence()Check if population has converged. By defaulttrueif population is monomorphic and no (zero) mutations. However, different implementations may have different criteria for convergence.Note: This tends to be less restrictive than reaching an absorbing state. Typically convergence is used as a criterion to abort simulations.
- Returns:
trueif converged.
-
getTraitNameAt
Gets the formatted name of the trait of the individual at siteindex.- Parameters:
index- the index of the- Returns:
- the string describing the trait
-
getInteractionGeometry
Gets the interaction geometry.- Returns:
- the interaction geometry
-
getInterGroup
-
getCompetitionGeometry
Gets the competition geometry.- Returns:
- the competition geometry
-
getCompGroup
Gets the competition/reference/model group.- Returns:
- the competition/reference/model group
-
getPopulationUpdate
Gets the population update.- Returns:
- the population update
-
setPopulationUpdate
Sets the population update.- Parameters:
populationUpdate- the population update
-
getTotalFitness
public double getTotalFitness()Gets the total fitness of the population.- Returns:
- the total fitness
-
doSyncMigration
public int doSyncMigration()Perform synchronous migration.- Returns:
- the number of migrants
-
doMigration
public void doMigration()Perform asynchronous migration. -
doDiffusionMigration
public void doDiffusionMigration()Perform diffusion migration, which is implemented as two players swap their locations while leaving their respective neighbourhood structure untouched. -
updatePlayerSwap
public void updatePlayerSwap(int a, int b) Swap players in locationsaandb.- Parameters:
a- the index of the first individualb- the index of the second individual
-
doBirthDeathMigration
public void doBirthDeathMigration()Perform a birth-death migration, where a focal individual (selected proportional to fitness) produces a migrant offspring, which replaces another member of the population uniformly at random.Note: This is almost identical to Moran (birth-death) updating in well-mixed populations (only victim and migrant always different)
-
doDeathBirthMigration
public void doDeathBirthMigration()Perform a death-birth migration, where a member of the population (selected uniformly at random) dies and the remaining individuals compete to repopulate the vacant site. One competitor succeeds with a probability proportional proportional to fitness.Note: This is almost identical to Moran (birth-death) updating in well-mixed populations
-
pickFocalSite
public int pickFocalSite()Draws the index of a site in the population uniformly at random, irrespective of whether it is occupied or not.- Returns:
- the index of the picked site
-
pickFocalSite
public int pickFocalSite(int excl) Draws the index of a site in the population uniformly at random, irrespective of whether it is occupied or not.- Parameters:
excl- the index of the excluded site- Returns:
- the index of the picked site
-
pickFocalIndividual
public int pickFocalIndividual()Draws the index of a individual of the population uniformly at random. Vacant sites are skipped. In the absence of vacant sites this is equivalent topickFocalSite().Important: This method is highly time sensitive. Any optimization effort is worth making.
- Returns:
- the index of the picked individual
-
pickFocalSkipVacant
private int pickFocalSkipVacant()Pick a focal individual uniformly at random but skipping vacant sites.- Returns:
- the index of the picked individual
-
pickFocalSkipVacant
private int pickFocalSkipVacant(int excl) Pick a focal individual uniformly at random but excluding the individual with indexexcl.- Parameters:
excl- the index of the excluded individual- Returns:
- the index of the picked individual
-
pickFocalHead
private int pickFocalHead(int pick) Pick a focal individual uniformly at random starting from head.- Parameters:
pick- the pick index- Returns:
- the index of the picked individual
-
pickFocalHead
private int pickFocalHead(int pick, int excl) Pick a focal individual uniformly at random starting from head, excluding individualexcl.- Parameters:
pick- the pick indexexcl- the index of the excluded individual- Returns:
- the index of the picked individual
-
pickFocalTail
private int pickFocalTail(int pick) Pick a focal individual uniformly at random starting from tail.- Parameters:
pick- the pick index- Returns:
- the index of the picked individual
-
pickFocalTail
private int pickFocalTail(int pick, int excl) Pick a focal individual uniformly at random starting from tail, excluding individualexcl.- Parameters:
pick- the pick indexexcl- the index of the excluded individual- Returns:
- the index of the picked individual
-
pickFailed
private int pickFailed()Handle failed pick.- Returns:
- never returns control
-
pickFailed
private int pickFailed(double remainder) Handle failed pick and report details about failure.- Parameters:
remainder- remaining probability mass that failed to select an individual- Returns:
- never returns control
-
pickFocalIndividual
public int pickFocalIndividual(int excl) Draws the index of a individual of the population uniformly at random but excluding the individual with indexexcl. Vacant sites are skipped.Important: This method is highly time sensitive. Any optimization effort is worth making.
- Parameters:
excl- the index of the excluded individual- Returns:
- the index of the picked individual
-
pickFitFocalIndividual
public int pickFitFocalIndividual()Draws the index of a member of the population with a probability proportional to fitness.Note: scores must be
≥0Important: This method is highly time sensitive. Any optimization effort is worth making.
Discussions/extensions:
- Should picking include vacant sites, or not, or selectable?
- Currently vacant sites are excluded for fitness based picking but not for random picking.
- Perform more systematic analysis regarding the threshold population size
(currently
nPopulation ≥ 100) for the two Gillespie methods sometimes4*nPopulationtrials are needed, which seems too much...
- Returns:
- the index of the picked member
-
pickFitFocalNoVacant
private int pickFitFocalNoVacant()Draws the index of a member of the population with a probability proportional to fitness but assuming no vacant sites.Note: scores must be
≥0Important: This method is highly time sensitive. Any optimization effort is worth making.
- Returns:
- the index of the picked member
-
pickFitFocalSkipVacant
private int pickFitFocalSkipVacant()Draws the index of a member of the population with a probability proportional to fitness but assuming vacant sites.Note: scores must be
≥0Important: This method is highly time sensitive. Any optimization effort is worth making.
- Returns:
- the index of the picked member
-
pickFitFocalIndividual
public int pickFitFocalIndividual(int excl) Draws the index of a member of the population with a probability proportional to fitness but excluding the individual with the indexexcl.Note: scores must be
≥0Important: This method is highly time sensitive. Any optimization effort is worth making.
- Parameters:
excl- the index of the member that should be excluded from picking- Returns:
- the index of the picked member
-
pickFitFocalNoVacant
private int pickFitFocalNoVacant(int excl) Draws the index of a member of the population with a probability proportional to fitness but assuming no vacant sites.Note: scores must be
≥0Important: This method is highly time sensitive. Any optimization effort is worth making.
- Parameters:
excl- the index of the member that should be excluded from picking- Returns:
- the index of the picked member
-
pickFitFocalNoVacantGillespieOptimized
private int pickFitFocalNoVacantGillespieOptimized(int excl) Draws the index of a member of the population with a probability proportional to fitness but assuming no vacant sites.Note: scores must be
≥0Important: This method is highly time sensitive. Any optimization effort is worth making.
- Parameters:
excl- the index of the member that should be excluded from picking- Returns:
- the index of the picked member
-
pickFitFocalSkipVacant
private int pickFitFocalSkipVacant(int excl) Draws the index of a member of the population with a probability proportional to fitness but assuming vacant sites.Note: scores must be
≥0Important: This method is highly time sensitive. Any optimization effort is worth making.
- Parameters:
excl- the index of the member that should be excluded from picking- Returns:
- the index of the picked member
-
pickFitFocalSkipVacantGillespieOptimized
private int pickFitFocalSkipVacantGillespieOptimized(int excl) Draws the index of a member of the population with a probability proportional to fitness but assuming vacant sites.Note: scores must be
≥0Important: This method is highly time sensitive. Any optimization effort is worth making.
- Parameters:
excl- the index of the member that should be excluded from picking- Returns:
- the index of the picked member
-
second
private double second(int excl) Find the second highest score.- Parameters:
excl- the index of the member that should be excluded from picking- Returns:
- the second highest score
-
debugScores
protected void debugScores(double hit) Log report if picking failed to shed better light on what might be the root cause for the failure.- Parameters:
hit- the 'left-over fitness' from picking
-
pickFitNeighborAt
protected int pickFitNeighborAt(int me) Pick a neighbour of the focal individualmewith probability proportional to their fitness.- Parameters:
me- the index of the focal individual- Returns:
- the index of a neighbour
-
pickFitNeighborAt
protected int pickFitNeighborAt(int me, boolean withSelf) Pick a neighbour of the focal individualmewith probability proportional to their fitness. If the flagwithSelf==truethen the focal individual is included in the picking.- Parameters:
me- the index of the focal individualwithSelf- the flag whether to include self- Returns:
- the index of a neighbour
-
pickFitNeighborNoVacantAt
private int pickFitNeighborNoVacantAt(int me, boolean withSelf) Pick a neighbour of the focal individualmewith probability proportional to their fitness assuming no vacant sites. If the flagwithSelf==truethen the focal individual is included in the picking.- Parameters:
me- the index of the focal individualwithSelf- the flag whether to include self- Returns:
- the index of a neighbour
-
totFitnessNoVacant
private double totFitnessNoVacant(int me) Compute total fitness of neighbours of individualmeassuming no vacant sites.- Parameters:
me- the index of the focal individual- Returns:
- the total fitness of neighbours
-
pickFitNeighborSkipVacantAt
private int pickFitNeighborSkipVacantAt(int me, boolean withSelf) Pick a neighbour of the focal individualmewith probability proportional to their fitness assuming vacant sites. If the flagwithSelf==truethen the focal individual is included in the picking.- Parameters:
me- the index of the focal individualwithSelf- the flag whether to include self- Returns:
- the index of a neighbour
-
totFitnessSkipVacant
private double totFitnessSkipVacant(int me) Compute total fitness of neighbours of individualmeassuming vacant sites.- Parameters:
me- the index of the focal individual- Returns:
- the total fitness of neighbours
-
pickNeutralNeighbourAt
private int pickNeutralNeighbourAt(int me, boolean withSelf) Helper method to do picking under neutral conditions (no or negligible fitness differences). In well-mixed populations the picking includes the focal individual ifwithSelf==true. Otherwise picking never includesme.- Parameters:
me- the index of the focal individualwithSelf- the flag whether to include self- Returns:
- the index of a neighbour
-
pickNeighborSiteAt
public int pickNeighborSiteAt(int me) Picks a neighbouring site of the focal individualmeuniformly at random. This is where the focal individual places its offspring in the Moran process under Birth-death updating. The original Moran process refers to well-mixed (or mean-field) populations where the offspring can replace its parent (albeit with a small probability of \(o(1/N)\), where \(N\) is the population size). In contrast in the spatial Moran process the offspring replaces a neighbour of the parent.Notes:
- The parent is never picked.
- Vacant sites are picked with the same probability as occupied ones.
- Parameters:
me- the index of the focal individual- Returns:
- the index of a neighbour
- See Also:
-
updateFromModelAt
public void updateFromModelAt(int me, int you) Update individual with indexmeand adopt the trait of individual with indexyou.Note: method must be subclassed to deal with different data types of traits but should also include a call to super.
- Parameters:
me- the index of the focal individualyou- the index of the model individual to adopt trait from- See Also:
-
playGameSyncAt
public void playGameSyncAt(int me) Update the score of individualme.After initialization and for synchronized population updating this method is invoked (rather than
playGameAt(int)). The synchronous flag simply indicates that all players are going to be updated. For directed graphs this implies that incoming and outgoing links do not need to be treated separately because every outgoing link corresponds to an incoming link of another node.- Parameters:
me- the index of the focal individual
-
playGameAt
public void playGameAt(int me) Update the score of individualme. This method is called if adjusting scores is not an option. If sitemeis vacant do nothing.- Parameters:
me- the index of the focal individual- See Also:
-
adjustGameScoresAt
public void adjustGameScoresAt(int me) Adjust scores of focal playermeand its neighbours (interaction partners).Requirements/notes:
- This optimized method is only applicable if
IBSGroup.SamplingType.ALLis true and notGeometryType.WELLMIXED, i.e. if the interaction group includes all neighbors but not all other members of the population. - For pairwise interactions more efficient approaches are possible but those require direct access to the trait and are hence delegated to subclasses.
- Parameters:
me- the index of the focal individual- See Also:
- This optimized method is only applicable if
-
updateScoreAt
public void updateScoreAt(int index, double newscore) Update the score of the individual with indexindexby addingnewscorefrom single interaction.- Parameters:
index- the index of the individualnewscore- the new score of the individual
-
updateScoreAt
public void updateScoreAt(int index, double newscore, int incr) Update the score of the individual with indexindexby adding (incr > 0or removing,incr < 0)newscoreas the result ofincrinteractions.Important:
- Traits are already committed when adding scores
(
incr>0). - Traits are not committed when removing scores
(
incr<0). - This routine is never called for the focal site (i.e. the one that may have changed trait and hence where it matters whether traits are committed).
resetScoreAt(int)deals with the focal site.
- Parameters:
index- the index of the individualnewscore- score/payoff to add (incr>0) or subtract (incr<0)incr- number of interactions
- Traits are already committed when adding scores
(
-
updateFitnessAt
public void updateFitnessAt(int idx) Update the fitness of the individual with indexidxby mapping its current score. Keeps track ofsumFitness.Note: If
sumFitnessdecreases dramatically rounding errors become an issue. More specifically, ifsumFitnessis reduced to half or less, recalculate from scratch.- Parameters:
idx- the index of the individual
-
setScoreAt
public void setScoreAt(int index, double newscore, int inter) Sets the score of individual with indexindextonewscoreas the result ofinterinteractions. Also derives the corresponding fitness and adjustssumFitness.Note: Assumes that
resetScores()was called earlier (or at leastresetScoreAt(int)for those sites thatsetScoreAt(int)is used for updating their score).- Parameters:
index- the index of the individualnewscore- new score to setinter- number of interactions
-
removeScoreAt
public void removeScoreAt(int index, double nilscore) Removes the scorenilscorebased on a single interaction from the individual with indexindex.- Parameters:
index- the index of the individualnilscore- the score to remove- See Also:
-
removeScoreAt
public void removeScoreAt(int index, double nilscore, int incr) Removes the scorenilscorebased onincrinteractions from the individual with indexindex.- Parameters:
index- the index of the individualnilscore- the score to removeincr- the number of interactions to remove- See Also:
-
resetScoreAt
public void resetScoreAt(int index) Reset score of individual at indexindex.Important: traits must not yet have been committed.
Discussions/extensions:
Revise the entire trait updating procedure: it's inefficient to first reset scores then update traits then update score...- Parameters:
index- the index of the individual
-
swapScoresAt
public void swapScoresAt(int idxa, int idxb) Swap the scores (and fitness) of individuals with indicesidxaandidxb.- Parameters:
idxa- the index of the first individualidxb- the index of the second individual
-
resetScores
public void resetScores()Reset scores and fitness of all individuals to zero. -
updateScores
public void updateScores()Update the scores of all individuals in the population. -
getScoreAt
public double getScoreAt(int idx) Gets the score of the individual with indexidx.- Parameters:
idx- the index of the individual- Returns:
- the score of the individual
-
getFitnessAt
public double getFitnessAt(int idx) Gets the fitness of the individual with indexidx.- Parameters:
idx- the index of the individual- Returns:
- the fitness of the individual
-
updateEffScoreRange
protected boolean updateEffScoreRange(int index, double before, double after) Keep track of highest score through a reference to the corresponding individual.Discussions/extensions:
- Keeping track of the lowest performing individual is very costly because
the poor performers are much more likely to get updated. In contrast, the
maximum performer is least likely to get replaced. For example, in
cSDwith a well-mixed population of10'000spends>80%of CPU time hunting down the least performing individual! Besides, the minimum score is never used. The maximum score is only used for global, fitness based selection such as the Birth-death process. (room for optimization?) - For synchronous updates this method is not only wasteful but problematic because sites that are later updated experience different conditions.
- For constant fitness (
maxEffScoreIdx < 0) tracking the maximum is not needed. if (isVacantAt(index)) {...}is only executed ifafter == before, i.e. the code is almost dead... suspicious or ingenious?!
- Parameters:
index- the index of the individualbefore- the score before the updateafter- the score after the update- Returns:
trueif effective range of payoffs has changed (or, more precisely, if the reference individual has changed);falseotherwise.
- Keeping track of the lowest performing individual is very costly because
the poor performers are much more likely to get updated. In contrast, the
maximum performer is least likely to get replaced. For example, in
-
setMaxEffScoreIdx
protected void setMaxEffScoreIdx()Find the index of the individual with the highest score. -
step
public int step()Perform a single IBS step, i.e. update one individual for asynchronous updates or once the entire population for synchronous updates.Discussions/extensions
- Review migration. Exclusively used in Demes2x2. Should probably be treated as an independent event, in particular independent of population or player updates
- Implement Wright-Fisher update.
- How to scale realtime with multiple populations? How to define a generation if population sizes can vary?
updatePlayerEcology()returns time increment in realtime units. Everyone else does fine without...
- Returns:
- the number of elapsed realtime units
-
optimizeHomo
private int optimizeHomo()Optimize homogeneous population states by skipping to the next mutation event.- Returns:
- the number of elapsed realtime units
-
updateSyncAll
private int updateSyncAll()Update all individuals in the population synchronously.- Returns:
- the number of elapsed realtime units
-
updateSyncFraction
private int updateSyncFraction()Update a fraction of individuals in the population synchronously.- Returns:
- the number of elapsed realtime units
-
updateOnce
private int updateOnce()Update all individuals in the population once asynchronously.- Returns:
- the number of elapsed realtime units
-
getSpeciesUpdateRate
public double getSpeciesUpdateRate()Gets the update rate of this species. Only used in multi-species modules. Determines the relative rate at which this species is picked as compared to others.- Returns:
- the species update rate
- See Also:
-
mutate
public int mutate()Perform a mutation event. The focal individual is picked uniformly at random.- Returns:
- the number of elapsed realtime units
-
mutateAt
public abstract int mutateAt(int focal) Mutate the trait of the focal individual with indexfocal. The mutated trait is committed and the scores updated.- Parameters:
focal- the index of the focal individual- Returns:
- the number of elapsed realtime units
-
maybeMutateAt
protected abstract boolean maybeMutateAt(int focal, boolean switched) Consider mutating the trait of the focal individual with indexfocal. The trait of the focal individual is stored in the arraytraitsunless the focal individual switched trait. In that case the current trait is stored in the arraytraitsNext.Important: The trait is not committed regardless of whether a mutation occurred.
- Parameters:
focal- the index of the focal individualswitched-trueif the focal individual switched trait- Returns:
trueif the trait of the focal individual changed
-
maybeMutateMoran
protected abstract void maybeMutateMoran(int source, int dest) Consider mutating the trait of the parent individual with indexsource. The mutated trait is committed and the scores updated.- Parameters:
source- the index of the parent individualdest- the index of the location for the offspring placement
-
debugUpdatePopulationAt
public void debugUpdatePopulationAt(int focal) Update focal individual with indexfocalfor debugging.Notes:
- Must remain in sync with population updates in IBS and step().
- For debugging only; time not advanced.
- Parameters:
focal- the index of the individual to update
-
debugMarkChange
protected void debugMarkChange()Override in subclass for example to mark those individuals in the GUI that were involved in the debug step. -
formatInfoAt
Helper method to format information about updating the focal individual at indexfocalusing the model individual with indexmodel.- Parameters:
focal- the index of the focal individualmodel- the index of the model individual- Returns:
- the formatted information
-
updatePlayerAsync
protected void updatePlayerAsync()Perform a single, asynchronous update of the trait of a randomly selected individual. -
updatePlayerAsyncAt
public void updatePlayerAsyncAt(int me) Update the trait of the focal individual with indexme.- Parameters:
me- the index of the focal individual
-
updateScoreAt
protected void updateScoreAt(int me, boolean switched) Update the scores of the focal individual with indexme.- Parameters:
me- the index of the focal individualswitched-trueif the focal switched trait
-
updatePlayerMoranBirthDeath
public void updatePlayerMoranBirthDeath()Perform a single, Moran (Birth-death) update for a random individual selected with a probability proportional to fitness. This is the original Moran process where the offspring can replace the parent in well-mixed populations. For structured populations this corresponds to the spatial Moran process with Bd updating in Ohtsuki et al. Nature 2005.- See Also:
-
updatePlayerMoranBirthDeathAt
protected void updatePlayerMoranBirthDeathAt(int parent) Perform a Moran (Birth-death) update for the focal individual with indexparentto produce a clonal offspring and replace one of the parent's neighbours selected uniformly at random. This is the original Moran process where the offspring can replace the parent in well-mixed populations.- Parameters:
parent- the index of the parent
-
updatePlayerMoranDeathBirth
public void updatePlayerMoranDeathBirth()Perform a single Moran (death-Birth) update for a site selected uniformly at random. This corresponds to the spatial Moran process with dB updating in Ohtsuki et al. Nature 2005.- See Also:
-
updatePlayerMoranDeathBirthAt
protected void updatePlayerMoranDeathBirthAt(int vacant) Perform a single Moran (death-Birth) update for the focal site with indexvacant. One of its (incoming) neighbours succeeds, with a probability proportional to its fitness, in producing a clonal offspring and placing it at sitevacant.- Parameters:
vacant- the index of the vacant site
-
updatePlayerMoranImitate
public void updatePlayerMoranImitate()Perform a single, Moran (imitate) update for a site selected uniformly at random. This corresponds to imitate in Ohtsuki et al. Nature 2005.- See Also:
-
updatePlayerMoranImitateAt
protected void updatePlayerMoranImitateAt(int imitator) Update the focal individual with indeximitatorby comparing its own payoff and those of its neighbors. The focal individual imitates the trait of a neighbour (or keeps its own) with a probability proportional to the corresponding individual's fitness (including its own).- Parameters:
imitator- the index of the individual that reassesses its trait
-
migrateMoran
protected void migrateMoran(int source, int dest) Perform a single Moran update for the reproducing node with indexsourceand the node that gets replaced with indexdest. The three Moran variants (death-Birth, Birth-death and imitate) differ only in their selection of the individualssourceanddestand then call this method,migrateMoran(int, int).Note: Moran optimizations for discrete trait require access to this method.
- Parameters:
source- the index of the parent nodedest- the index of the node where the offspring is placed- See Also:
-
updatePlayerEcology
public int updatePlayerEcology()Perform a single ecological update of an individual selected uniformly at random.- Returns:
- the number of elapsed realtime units
-
updatePlayerEcologyAt
protected int updatePlayerEcologyAt(int index) Perform a single ecological update of the site with indexindex.Important: No default implementation is possible. Modules with ecological updates need to subclass
IBSPopulationand provide their own implementations.- Parameters:
index- the index of the focal site- Returns:
- the number of elapsed realtime units
-
updatePlayerAt
public boolean updatePlayerAt(int me) Perform a single update of the individual with indexme. Returnstrueif the individual adopted the trait of the reference individual. Does not imply that the trait changed in discrete modules. Whether the individuals score is reset depends onplayerScoring- Parameters:
me- the index of the focal individual- Returns:
trueif trait of reference adopted- See Also:
-
updatePlayerAt
public boolean updatePlayerAt(int me, int[] refGroup, int rGroupSize) Perform a single update of the individual with indexmeusing therGroupSizemodels in the arrayrefGroup. Returnstrueif the individual changed its trait to signal that the focal individual's score will need to be reset.- Parameters:
me- the index of the focal individualrefGroup- the group of reference individualsrGroupSize- the number of reference individuals- Returns:
trueif trait of reference adopted- See Also:
-
updatePlayerBest
protected boolean updatePlayerBest(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexmeby adopting the trait of the best performing reference individual among therGroupSizemodels in the arrayrefGroup. Returnstrueif the individual adopted the trait of the reference individual. Does not imply that the trait changed in discrete modules. Whether the individuals score is reset depends onplayerScoring.Notes:
- If the scores of two reference individuals tie but exceed the focal individual's score, expert advice is needed.
- If the focal individual's score is highest but ties with one or more reference individuals the focal individual keeps its trait.
- For the best update it does not matter whether scores are averaged or accumulated.
- Parameters:
me- the index of the focal individualrefGroup- the group of reference individualsrGroupSize- the number of reference individuals- Returns:
trueif trait of reference adopted- See Also:
-
updatePlayerBestHalf
protected boolean updatePlayerBestHalf(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexmeby adopting the trait of the best performing reference individual among the therGroupSizemodels in the arrayrefGroup. If the scores of two (or more) references or the score of the focal individual and one (or more) reference(s) tie, then a coin toss decides which trait to keep/adopt. Returnstrueif the individual adopted the trait of the reference individual. Does not imply that the trait changed in discrete modules. Whether the individuals score is reset depends onplayerScoring.Notes:
For the best update it does not matter whether scores are averaged or accumulated.- Parameters:
me- the index of the focal individualrefGroup- the group of reference individualsrGroupSize- the number of reference individuals- Returns:
trueif trait of reference adopted- See Also:
-
updateProportionalAbs
protected boolean updateProportionalAbs(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexmeby adopting the trait of one reference individual (including itself) among the therGroupSizemodels in the arrayrefGroupwith a probability proportional to their scores. Returnstrueif the individual adopted the trait of the reference individual. Does not imply that the trait changed in discrete modules. Whether the individuals score is reset depends onplayerScoring.- Parameters:
me- the index of the focal individualrefGroup- the group of reference individualsrGroupSize- the number of reference individuals- Returns:
trueif trait of reference adopted- See Also:
-
updateReplicatorPlus
protected boolean updateReplicatorPlus(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexmeby adopting the trait of one reference individual among the therGroupSizemodels in the arrayrefGroup. The focal individual \(i\) imitates the trait of a better performing reference individual \(j\) with a probability proportional to the difference in fitness: \[p_{i\to j} = \frac{(f_i-f_j)_+}\alpha,\] where \(\alpha\) denotes a normalization factor to ensure \(p_{i\to j}\in[0,1]\). Returnstrueif the individual adopted the trait of the reference individual. Does not imply that the trait changed in discrete modules. Whether the individuals score is reset depends onplayerScoring.- Parameters:
me- the index of the focal individualrefGroup- the group of reference individualsrGroupSize- the number of reference individuals- Returns:
trueif trait of reference adopted- See Also:
-
updateReplicatorHalf
protected boolean updateReplicatorHalf(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexmeby adopting the trait of one reference individual among the therGroupSizemodels in the arrayrefGroup. The focal individual \(i\) imitates the trait of a reference individual \(j\) with a probability proportional to the difference in fitness: \[p_{i\to j} = \frac{f_i-f_j}\alpha\] where \(\alpha\) denotes a normalization factor to ensure \(p_{i\to j}\in[0,1]\). This corresponds to the microscopic updating which recovers the standard replicator equation in the continuum limit. Returnstrueif the individual adopted the trait of the reference individual. Does not imply that the trait changed in discrete modules. Whether the individuals score is reset depends onplayerScoring.- Parameters:
me- the index of the focal individualrefGroup- the group of reference individualsrGroupSize- the number of reference individuals- Returns:
trueif trait of reference adopted- See Also:
-
updateReplicator
private boolean updateReplicator(int me, int[] refGroup, int rGroupSize, boolean betterOnly) Helper method for replicator type updates. Returnstrueif the individual adopted the trait of the reference individual. Does not imply that the trait changed in discrete modules. Whether the individuals score is reset depends onplayerScoring.- Parameters:
me- the index of the focal individualrefGroup- the group of reference individualsrGroupSize- the number of reference individualsbetterOnly- the flag to indicate whether only better performing reference individuals are considered- Returns:
trueif trait of reference adopted- See Also:
-
updateReplicatorNeutral
private boolean updateReplicatorNeutral(int me, int[] refGroup, int rGroupSize, boolean betterOnly) Replicator type update in the neutral case.- Parameters:
me- the index of the focal individualrefGroup- the group of reference individualsrGroupSize- the number of reference individualsbetterOnly- the flag to indicate whether only better performing reference individuals are considered- Returns:
trueif trait of reference adopted
-
updateReplicatorNoNoise
private double updateReplicatorNoNoise(int[] refGroup, int rGroupSize, double myFitness, boolean betterOnly) Replicator type update without noise.- Parameters:
refGroup- the group of reference individualsrGroupSize- the number of reference individualsmyFitness- the fitness of the focal individualbetterOnly- the flag to indicate whether only better performing reference individuals are considered- Returns:
- the probability of no adoption
-
updateReplicatorNoise
private double updateReplicatorNoise(int[] refGroup, int rGroupSize, double myFitness, boolean betterOnly) Replicator type update with noise.- Parameters:
refGroup- the group of reference individualsrGroupSize- the number of reference individualsmyFitness- the fitness of the focal individualbetterOnly- the flag to indicate whether only better performing reference individuals are considered- Returns:
- the probability of no adoption
-
updateThermal
protected boolean updateThermal(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexmeby adopting the trait of one reference individual among the therGroupSizemodels in the arrayrefGroup. The focal individual \(i\) imitates the trait of a reference individual \(j\) with a probability proportional to the difference in fitness: \[p_{i\to j} = \frac1{1+\exp(-(f_i-f_j)/T)}\] where \(T\) denotes the temperature (or noise) in adopting a trait. In the limit \(T\to\infty\) imitation reduces to a coin toss, \(p_{i\to j}=1/2\). In contrast, for \(T\to 0\) it converges to the step-function, with \(\Theta(x)=1\) for positive \(x\), \(\Theta(x)=0\) for \(x\) negative and \(\Theta(0)=1/2\). Returnstrueif the individual adopted the trait of the reference individual. Does not imply that the trait changed in discrete modules. Whether the individuals score is reset depends onplayerScoring.- Parameters:
me- the index of the focal individualrefGroup- the group of reference individualsrGroupSize- the number of reference individuals- Returns:
trueif trait of reference adopted- See Also:
-
updateThermalNoNoise
private double updateThermalNoNoise(int me, int[] refGroup, int rGroupSize) Thermal update without noise.- Parameters:
me- the index of the focal individualrefGroup- the group of reference individualsrGroupSize- the number of reference individuals- Returns:
- the probability of no adoption
-
updateThermalNoise
private double updateThermalNoise(int me, int[] refGroup, int rGroupSize) Thermal update with noise.- Parameters:
me- the index of the focal individualrefGroup- the group of reference individualsrGroupSize- the number of reference individuals- Returns:
- the probability of no adoption
-
updateFailed
private boolean updateFailed(int me, int rGroupSize, double nProb, double norm, double choice) Handle failed adoption decision and log diagnostic details before aborting.- Parameters:
me- the focal individual indexrGroupSize- number of reference individuals considerednProb- residual probability of no adoptionnorm- normalization constant for cumulative probabilitieschoice- sampled random number that failed to match a candidate- Returns:
- never returns control
-
debugUpdate
protected void debugUpdate(int me, int rGroupSize, double nProb, double norm, double choice) Log report if updating failed to shed better light on what might be the root cause for the failure.- Parameters:
me- the index of the focal individualrGroupSize- number of reference individuals considerednProb- residual probability of no adoptionnorm- normalization constant for cumulative probabilitieschoice- sampled random value that failed to match a candidate
-
getMinScore
public double getMinScore()Returns the minimum scoreminin this population, taking the population structure and payoff accounting into account.- Returns:
- the processed minimum score
-
getMaxScore
public double getMaxScore()Returns the maximum scoreminin this population, taking the population structure and payoff accounting into account.- Returns:
- the processed maximum score
-
processScore
protected double processScore(double score, int count) Process the accumulatedscorein this population, taking the updating into account. In heterogeneous networkscountmust refer to the highest degree for maximum scores and the lowest degree for minimum scores.- Parameters:
score- the minimum or maximum scorecount- the number of interactions for the score- Returns:
- the processed extremal score
-
updateMinMaxScores
public void updateMinMaxScores()Retrieve and store extremal scores and fitnesses to reduce calls toModule. -
check
public boolean check()Check all model parameters for consistency and adjust if necessary (and feasible). Returnstrueif adjustments require a reset. Free memory if possible and request a reset if new memory needs to be allocated.- Returns:
trueif reset is required- See Also:
-
checkGeometry
boolean checkGeometry()Check the interaction and competition geometries for consistency and adjust if necessary (and feasible).- Returns:
trueif reset is required
-
checkGeometryRewire
boolean checkGeometryRewire()Rewire the interaction and competition geometries if requested.- Returns:
trueif rewiring changed
-
setGeometryNames
void setGeometryNames()Set the names of the interaction and competition geometries based on the module name and whether the geometries are the same or different. -
checkMigration
void checkMigration()Check consistency of migration settings and adjust if necessary (and feasible). -
checkInteractions
boolean checkInteractions(int nGroup) Validate interaction structures and adjust incompatible settings.- Parameters:
nGroup- interaction group size- Returns:
trueif changes require a reset
-
checkPayoffs
boolean checkPayoffs(int nGroup) Check settings for modules implementing Payoffs.- Parameters:
nGroup- the interaction group size- Returns:
trueif reset is required
-
checkLookupTable
boolean checkLookupTable(int nGroup, boolean ephemeralScores) Check whether lookup tables for scores and fitness can be used. Free memory if possible and request a reset if the use of lookup tables has changed.- Parameters:
nGroup- the interaction group sizeephemeralScores- the flag for ephemeral scores- Returns:
trueif reset is required
-
checkNoLookupTable
boolean checkNoLookupTable(boolean ephemeralScores) Free memory used for lookup tables and allocate arrays for scores, fitness and interactions. Returnstrueif reset is required.- Parameters:
ephemeralScores- the flag for ephemeral scores- Returns:
trueif reset is required
-
getNMixedInteractions
int getNMixedInteractions(int nGroup) Determine the number of interactions in well-mixed populations with lookup tables.- Parameters:
nGroup- the interaction group size- Returns:
- the number of interactions
-
checkCompSampling
void checkCompSampling()Validate competition sampling rules for well-mixed populations and adjust if required. -
checkOptimizations
boolean checkOptimizations()Check whether optimizations for homogeneous states can be used. Disable if necessary (and log warnings).- Returns:
trueif reset is required
-
setRewire
public void setRewire(double[] rewire) Set the probabilities for rewiring links of the interaction and competition graphs.- Parameters:
rewire- the arraydouble[] {<interaction>, <competition>}
-
setAddwire
public void setAddwire(double[] addwire) Set the probabilities for adding links to the interaction and competition graphs.- Parameters:
addwire- the arraydouble[] {<interaction>, <competition>}
-
doAdjustScores
protected abstract boolean doAdjustScores()Check if scores can be adjusted rather than recalculated after an individual changed its trait. This requires that individuals interact with all their neighbours and that the structure of the population is not well-mixed. Some implementations may be able to extend adjustments to other structures. For example, adjusting scores is feasible in well-mixed populations for discrete traits.Requirements:
- Group.SAMPLING_ALL
- individuals need to be interacting with all their neighbours (not just a randomly selected subset).
- AbstractGeometry.MEANFIELD
- interactions with everyone are not feasible (impossible to model
efficiently), in general, for unstructured populations (subclasses can do
better, e.g. for discrete trait it is possible, see
IBSDPopulation.doAdjustScores()). - playerScoreReset
- if scores are reset whenever an individual adopts the trait of another (regardless of whether an actual trait change occurred) then the expected number of interactions of each individual remains constant over time (even though the interaction count may differ for individuals on heterogeneous structures).
- Returns:
trueif adjusting scores is feasible- See Also:
-
reset
public void reset()Reset the model. All parameters must be consistent at this point. Allocate memory and initialize the interaction and competition structures. If structures include random elements, e.g. random regular graphs, a new structure is generated. Generate initial configuration. Subclasses must override this method to allocate memory for the trait and call super.- See Also:
-
resetMoran
void resetMoran()Ensure that Moran type population updates have non-negative fitness values. Adjust the payoff-to-fitness mapping if necessary. -
resetEphemeral
void resetEphemeral(int nGroup) Precalculate the number of interactions for ephemeral payoffs and store in the interactions array.- Parameters:
nGroup- the group size
-
init
public void init()Initialize the model. All parameters must be consistent. Subclasses must override this method to generate the initial trait configuration and call super.Note: Initialization leaves the interaction and competition structures untouched
- See Also:
-
setConsistencyCheck
public void setConsistencyCheck(boolean check) Enable consistency checks of the state of the IBS model. Never use in production.- Parameters:
check-trueto request consistency checks
-
isConsistent
public void isConsistent()Convenience method during development to perform a number of consistency checks of the current state. Once an inconsistency is found there is no need to keep looking and no further checks are performed.Execution time is of little concern here. Never use in the final simulation code.
-
checkConsistentFitness
void checkConsistentFitness()Check consistency of scores and fitness values for modules that implement Payoffs. -
checkIndividualConsistency
private void checkIndividualConsistency(int n) Check consistency of scores for a single individual.- Parameters:
n- the index of the individual
-
checkLookupTableConsistency
private void checkLookupTableConsistency()Check consistency of scores when using lookup tables. -
checkTraitScores
private void checkTraitScores(double[] typeScoresStore, double[] typeFitnessStore) Check consistency of scores for all traits.- Parameters:
typeScoresStore- the stored type scorestypeFitnessStore- the stored type fitness
-
checkFitnessSum
private void checkFitnessSum(double sumFitnessStore) Check consistency of total fitness.- Parameters:
sumFitnessStore- the stored fitness sum
-
checkAdjustScoresConsistency
private void checkAdjustScoresConsistency()Check consistency when not using lookup tables. -
checkNoAdjustScoresConsistency
private void checkNoAdjustScoresConsistency()Check consistency when scores are not adjusted. -
logScoringIssue
Log a scoring issue.- Parameters:
idx- the index of the individualactual- the actual scoreissue- the issue description
-
logScoringIssue
void logScoringIssue(int idx, double actual, double expected) Log a scoring issue.- Parameters:
idx- the index of the individualactual- the actual scoreexpected- the expected score
-
logMapIssue
void logMapIssue(int idx, double actual, double expected) Log a mapping issue.- Parameters:
idx- the index of the individualactual- the actual scoreexpected- the expected score
-
logFitnessIssue
void logFitnessIssue(int idx, double actual, double expected) Log a fitness issue.- Parameters:
idx- the index of the individualactual- the actual fitnessexpected- the expected fitness
-
logAccountingIssue
void logAccountingIssue(double actual, double expected) Log an accounting issue.- Parameters:
actual- the actual valueexpected- the expected value
-
logAccountingIssue
-
resetTraits
public void resetTraits()Reset all traits in preparation of the next update step. Simply an opportunity for customizations in subclasses. -
getNMean
public int getNMean()Return the number of mean values for this population (for traits or fitness).Note: The number of mean traits in a model may differ from the number of traits in the corresponding module. This is the case for example for
GeometryType.SQUARE_NEUMANN_2NDwith two disjoint interaction or competition graphs.- Returns:
- the number of mean values
- See Also:
-
getMeanTraits
public abstract double[] getMeanTraits(double[] mean) Returns the mean trait(s) of this population in the arraymean. Used by GUI to visualize the current state of this IBS model.- Parameters:
mean- the array for returning the trait values- Returns:
- the array
meancontaining the mean trait values - See Also:
-
getTraitData
Returns the traits of all individuals in this population coded as colors in the arraycolorsusing the mapcolorMap. Used by GUI to visualize the current state of this IBS model. Colors are coded in different data types<T>depending on the runtime environment (GWT or JRE) as well as the graph (e.g.PopGraph2DorPopGraph3D).- Type Parameters:
T- the type of color data (StringorMeshLambertMaterialfor GWT andColorfor JRE).- Parameters:
colors- the array where the colors of all nodes are storedcolorMap- the map that converts traits into colors
-
getMeanFitness
public abstract double[] getMeanFitness(double[] mean) Returns the mean fitness of this population in the arraymean. Used by GUI to visualize the current state of this IBS model. Returnstrueif data point belongs to the same time series andfalseif a new series was started throughinit()orreset().- Parameters:
mean- the array for storing the mean fitness values- Returns:
- the array
meancontaining the mean fitness values - See Also:
-
getFitnessData
Returns the fitness of all individuals in this population coded as colors in the arraycolorsusing the mapcolorMap. Used by GUI to visualize the current state of this IBS model. Colors are coded in different data types<T>depending on the runtime environment (GWT or JRE) as well as the graph (e.g.PopGraph2DorPopGraph3D).- Type Parameters:
T- the type of color data (StringorMeshLambertMaterialfor GWT andColorfor JRE).- Parameters:
colors- the array where the colors of all nodes are storedcolorMap- the map that converts traits into colors
-
getFitnessHistogramData
public void getFitnessHistogramData(double[][] bins) Generates a histogram of the fitness distribution in this population. The result is returned in the arraybins.Notes:
binsis a 2D array because discrete models generate histograms for each trait separately.- By default generate a histogram of the scores in
bins[0]. - Consider moving to
IBSDPopulationandIBSCPopulationwith argumentsbins[][]andbins[], respectively.
- Parameters:
bins- the 2D array to store the histogram(s)
-
getScores
-
getScoreNameAt
Gets the formatted score of the individual with indexidx.- Parameters:
idx- the index of the individual- Returns:
- the formatted score
-
getFitness
-
getFitnessNameAt
Gets the formatted fitness of the individual with indexidxas a string. If the flagprettyis set the formatting is prettyfied by replacing the exponentEin scientific notation to a power of10.- Parameters:
idx- the index of the individualpretty- flag to prettify formatting- Returns:
- the formatted fitness
-
getFitnessNameAt
Gets the formatted and prettyfied fitness of the individual with indexidxas a string.- Parameters:
idx- the index of the individual- Returns:
- the formatted fitness
-
getInteractionsAt
public int getInteractionsAt(int idx) Gets the number of interactions of the individual with indexidx. Returns-1if siteidxis vacant or fitness is static, i.e. not based on interactions.- Parameters:
idx- the index of the individual- Returns:
- the number of interactions
-
getTags
public double[] getTags(double[] mem) Copies the tags of all individuals in the population and returns them in the arraymem.- Parameters:
mem- the array to copy the tags into- Returns:
- the array of tags
-
getTagData
Returns the tags of all individuals in this population coded as colors in the arraycolorsusing the mapcolorMap. Used by GUI to visualize the current state of this IBS model. Colors are coded in different data types<T>depending on the runtime environment (GWT or JRE) as well as the graph (e.g.PopGraph2DorPopGraph3D).- Type Parameters:
T- the type of color data (StringorMeshLambertMaterialfor GWT andColorfor JRE).- Parameters:
colors- the array where the colors of all nodes are storedcolorMap- the map that converts tags into colors
-
getTagAt
public double getTagAt(int idx) Gets the tag of the individual with indexidx.- Parameters:
idx- the index of the individual- Returns:
- the tag number
-
getTagNameAt
Gets the formatted tag of the individual with indexidxas string.- Parameters:
idx- the index of the individual- Returns:
- the tag as a string
-
setTagAt
public boolean setTagAt(int idx, double tag) Sets the tag of the individual with indexidx.- Parameters:
idx- the index of the individualtag- the new tag of the individual- Returns:
trueif the tag changed
-
getPopulationSize
public int getPopulationSize()Gets current population size. For most models with fixed population sizes this simply returns nPopulation. Ecological models with variable population sizes must override this method to return the actual population size.- Returns:
- current population size
-
setSyncFraction
public void setSyncFraction(double sync) Set the fraction of the population that gets updated in synchronous updates.- Parameters:
sync- the fraction that gets updated
-
getSyncFraction
public double getSyncFraction()Get the fraction of the population that gets updated in synchronous updates.- Returns:
- the fraction that gets updated
-
setMigrationType
Sets the type of migrations totype.- Parameters:
type- the new type of migrations
-
getMigrationType
Gets the type of migrations.- Returns:
- the type of migrations
-
setMigrationProb
public void setMigrationProb(double aValue) Sets the migration probability toaValue.- Parameters:
aValue- the new migration probability
-
getMigrationProb
public double getMigrationProb()Gets the migration probability.- Returns:
- the migration probability
-
setPlayerScoring
Sets the type for managing scores of individuals.- Parameters:
type- the type for managing scores- See Also:
-
getPlayerScoring
Gets the type for managing scores of individuals.- Returns:
trueif scores are always reset- See Also:
-
setPlayerScoreAveraged
public void setPlayerScoreAveraged(boolean aver) Sets whether scores of individuals are averaged over multiple interactions or accumulated.- Parameters:
aver- the flag to indicate whether scores are averaged
-
getPlayerScoreAveraged
public boolean getPlayerScoreAveraged()Gets whether player scores are averaged (as opposed to accumulated).- Returns:
trueif player scores are averaged.
-
mouseHitNode
public boolean mouseHitNode(int hit) Called from GUI if node/individual with indexidxreceived a mouse click or tap.- Parameters:
hit- the index of the node- Returns:
falseif no actions taken
-
mouseHitNode
public boolean mouseHitNode(int hit, boolean alt) Called from GUI if node/individual with indexidxreceived a mouse click or tap and indicates whether thealt-key had been pressed.- Parameters:
hit- the index of the nodealt-trueif thealt-key was pressed- Returns:
falseif no actions taken
-
encodeFitness
Encode the fitness of all individuals in the IBS model in aplistinspiredXMLstring.- Parameters:
plist- theStringBuilderto write the encoded state to- See Also:
-
restoreFitness
Restore the fitness of all individuals encoded in theplistinspiredmapofkey, value-pairs.- Parameters:
plist- the map ofkey, value-pairs- Returns:
trueif successful- See Also:
-
encodeInteractions
Encode the interactions of all individuals in the IBS model in aplistinspiredXMLstring.- Parameters:
plist- theStringBuilderto write the encoded state to- See Also:
-
restoreInteractions
Restore the interactions of all individuals encoded in theplistinspiredmapofkey, value-pairs.- Parameters:
plist- the map ofkey, value-pairs- Returns:
trueif successful- See Also:
-
encodeTraits
Encode the traits of all individuals in the IBS model in aplistinspiredXMLstring.- Parameters:
plist- theStringBuilderto write the encoded state to- See Also:
-
restoreTraits
Restore the traits of all individuals encoded in theplistinspiredmapofkey, value-pairs.- Parameters:
plist- the map ofkey, value-pairs- Returns:
trueif successful- See Also:
-
encodeGeometry
Encode the interaction and competition structures of the IBS model in aplistinspiredXMLstring.- Parameters:
plist- theStringBuilderto write the encoded state to- See Also:
-
restoreGeometry
Restore the interaction and competition structures encoded in theplistinspiredmapofkey, value-pairs.- Parameters:
plist- the map ofkey, value-pairs- Returns:
trueif successful- See Also:
-
random0n
public int random0n(int n) Draw a uniformly distributed random integer number from the semi-closed interval[0, n).- Parameters:
n- the upper limit of interval (exclusive)- Returns:
- the random integer number in
[0, n).
-
random01
public double random01()Draw a uniformly distributed randomdoublefrom the semi-closed interval[0, 1)with 32bit resolution. This is the default.- Returns:
- the random number in
[0, 1).
-
randomGaussian
public double randomGaussian(double mean, double sdev) Draw a Gaussian (normal) distributed randomdouble.- Parameters:
mean- the mean of the Gaussian distributionsdev- the standard deviation of the Gaussian distribution- Returns:
- the Gaussian random number
-
nextBinomial
public int nextBinomial(double p, int n) Draw a binomially distributed random integer.- Parameters:
p- the probability of successn- the number of trials- Returns:
- the number of successes
-