Class IBSPopulation
- Direct Known Subclasses:
IBSDPopulation
,IBSMCPopulation
Note: strategies/traits cannot be handled here because
they are represented by int
s in discrete models but double
s
in continuous models.
- Author:
- Christoph Hauert
- See Also:
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected boolean
Optimization: Flag to indicate whether adjusting instead of recalculating scores is possible.protected Geometry
The geometry of the competition graph.protected IBSGroup
Reference to the competition/reference/model group.(package private) boolean
The 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 int
Helper variable to store index of focal individual (birth) that got updated during debug step.protected int
Helper 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 int
Helper variable to number of individual that served as models during debug step.protected boolean
Helper flag to indicate an actual trait change during debug step.protected RNGDistribution.Geometric
The distribution to determine the number of migrants.protected EvoLudo
The pacemaker of all models.protected double[]
The array of individual fitness values.protected double[]
Array to hold scores of individuals during payoff calculations.protected boolean
Optimization: Flag to indicate whether lookup tables can be used.protected Geometry
The geometry of the interaction graph.protected int[]
The array of individual interaction counts.protected IBSGroup
Reference to the interaction group.(package private) boolean
The flag to indicate whether the state of the IBS model is consistent.protected boolean
Flag to indicate whether the model entertains multiple species, i.e.protected boolean
Flag to indicate whether dynamic is neutral, i.e.protected Logger
Logger for keeping track of and reporting events and issues.protected Map2Fitness
The map converting scores to fitness and vice versa.protected int
Optimization: The index of the individual that currently holds the maximum score.protected double
The absolute maximum fitness in the population.protected double
The absolute maximum score in the population.protected IBS.MigrationType
The type of migration.protected double
The absolute minimum fitness in the population.protected double
The absolute minimum score in the population.protected Module
The module associated with this model.protected int
Optimization: Number of interactions in well-mixed populations for update rules that take advantage ofIBSDPopulation.updateMixedMeanScores()
.protected int
The size of the population.protected int
The number of traits in module.(package private) IBSPopulation
The interaction partner/opponent of this populationopponent.getModule()==getModule().getOpponent()
.protected double[]
The array containing the probabilities for adding links to the interaction and competition graphs.protected boolean
Flag to indicate whether player scores are averaged (default) or accumulated.protected IBS.ScoringType
Flag to indicate whether scores are reset whenever a player adopts the strategy of another (default) or only if an actual strategy change occurred.(package private) PlayerUpdate
The update type of players.protected double
The probability of migration.(package private) PopulationUpdate
The population update.protected double[]
The array containing the probabilities for rewiring links of the interaction and competition graphs.protected RNGDistribution
The 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.Static
Convenience field for static modules to avoid casts.protected double
The total fitness of the population.(package private) double
The 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 int
The index of vacant sites or-1
if module does not support vacancies. -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotected
IBSPopulation
(EvoLudo engine, Module module) Creates a population of individuals for IBS simulations. -
Method Summary
Modifier and TypeMethodDescriptionvoid
adjustGameScoresAt
(int me) Adjust scores of focal playerme
and its neighbours (interaction partners).abstract void
adjustPairGameScoresAt
(int me) Adjusts scores of focal individual with indexme
and its neighbors afterme
changed strategy.abstract void
adjustScoreAt
(int index, double adjust) Adjust score of individual with indexindex
byadjust
and update all applicable helper variables, e.g.abstract void
adjustScoreAt
(int index, double before, double after) Adjust score of individual with indexindex
frombefore
toafter
and update all applicable helper variables, e.g.boolean
becomesVacantAt
(int index) Check if site with indexindex
will become vacant in this time step.boolean
check()
Check all model parameters for consistency and adjust if necessary (and feasible).abstract boolean
Check if population has converged.boolean
checkGeometry
(Geometry geom) Provide opportunity/hook for subclasses to introduce new geometries.abstract void
After a synchronous update step the new state must be copied back to become the current state.abstract void
commitStrategyAt
(int index) The change of a strategy of the player atindex
is stored in a temporary variable and must be committed before proceeding.Creates a new instance of the competition or imitation structure, if needed.Creates a new instance of the interaction structure, if needed.protected void
Override in subclass for example to mark those individuals in the GUI that were involved in the debug step.protected void
debugScores
(double hit) Log report if picking failed to shed better light on what might be the root cause for the failure.void
debugUpdatePopulationAt
(int focal) Update focal individual with indexfocal
for debugging.protected abstract boolean
Check if scores can be adjusted rather than recalculated after an individual changed its strategy.void
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.void
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.void
Perform diffusion migration, which is implemented as two players swap their locations while leaving their respective neighbourhood structure untouched.void
Perform asynchronous migration.int
Perform synchronous migration.void
encodeFitness
(StringBuilder plist) Encode the fitness of all individuals in the IBS model in aplist
inspiredXML
string.void
encodeGeometry
(StringBuilder plist) Encode the interaction and competition structures of the IBS model in aplist
inspiredXML
string.void
encodeInteractions
(StringBuilder plist) Encode the interactions of all individuals in the IBS model in aplist
inspiredXML
string.abstract void
encodeStrategies
(StringBuilder plist) Encode the strategies of all individuals in the IBS model in aplist
inspiredXML
string.private String
formatInfoAt
(int focal, int model) Helper method to format information about updating the focal individual at indexfocal
using the model individual with indexmodel
.boolean
generateGeometry
(Geometry geom) Provide opportunity/hook for subclasses to introduce new geometries.Gets the structure of competition or imitations.Gets the competition/reference/model group.getFitness
(int digits) Gets the fitness of all individuals with precisiondigits
.double
getFitnessAt
(int idx) Gets the fitness of the individual with indexidx
.<T> void
getFitnessData
(T[] colors, ColorMap.Gradient1D<T> colorMap) Returns the fitness of all individuals in this population coded as colors in the arraycolors
using the mapcolorMap
.void
getFitnessHistogramData
(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 indexidx
as a string.getFitnessNameAt
(int idx, boolean pretty) Gets the formatted fitness of the individual with indexidx
as a string.abstract void
getInitialTraits
(double[] init) Returns the initial trait(s) of this population in the arrayinit
.Gets the structure of interactions.int
getInteractionsAt
(int idx) Gets the number of interactions of the individual with indexidx
.Gets the interaction group.double
Returns the maximum scoremin
in this population, taking the population structure and payoff accounting into account.abstract void
getMeanFitness
(double[] mean) Returns the mean fitness of this population in the arraymean
.abstract void
getMeanTraits
(double[] mean) Returns the mean trait(s) of this population in the arraymean
.double
Gets the migration probability.Gets the type of migrations.double
Returns the minimum scoremin
in this population, taking the population structure and payoff accounting into account.Gets the module asociated with this population.int
getNMean()
Return the number of mean values for this population (for traits or fitness).boolean
Gets whether player scores are averaged (as opposed to accumulated).Gets the type for managing scores of individuals.int
Gets current population size.Gets the population update.double
getScoreAt
(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
.abstract String
Gets the status of the as a formatted string.double
Get the fraction of the population that gets updated in synchronous updates.double
getTagAt
(int idx) Gets the tag of the individual with indexidx
.<T> void
getTagData
(T[] colors, ColorMap<T> colorMap) Returns the tags of all individuals in this population coded as colors in the arraycolors
using the mapcolorMap
.getTagNameAt
(int idx) Gets the formatted tag of the individual with indexidx
as string.double[]
getTags
(double[] mem) Copies the tags of all individuals in the population and returns them in the arraymem
.double
Gets the total fitness of the population.abstract <T> void
getTraitData
(T[] colors, ColorMap<T> colorMap) Returns the traits of all individuals in this population coded as colors in the arraycolors
using the mapcolorMap
.abstract String
getTraitNameAt
(int index) Gets the formatted name of the trait of the individual at siteindex
.abstract boolean
haveSameStrategy
(int a, int b) Check if individuals with indexa
and indexb
have the same strategies.void
init()
Initialize the model.void
Convenience method during development to perform a number of consistency checks of the current state.boolean
Check if population is monomorphic.abstract boolean
isSameStrategy
(int a) Check if individual with indexa
has switched strategies.boolean
isVacantAt
(int index) Check if site with indexindex
is occupied by an individual or vacant.protected abstract boolean
maybeMutateAt
(int focal, boolean switched) Consider mutating the trait of the focal individual with indexfocal
.protected abstract void
maybeMutateMoran
(int source, int dest) Consider mutating the trait of the parent individual with indexsource
.protected void
migrateMoran
(int source, int dest) Perform a single Moran update for the reproducing node with indexsource
and the node that gets replaced with indexdest
.boolean
mouseHitNode
(int hit) Called from GUI if node/individual with indexidx
received a mouse click or tap.boolean
mouseHitNode
(int hit, boolean alt) Called from GUI if node/individual with indexidx
received a mouse click or tap and indicates whether thealt
-key had been pressed.double
mutate()
Perform a mutation event.abstract double
mutateAt
(int focal) Mutate the strategy of the focal individual with indexfocal
.int
nextBinomial
(double p, int n) Draw a binomially distributed random integer.boolean
parseGeometry
(Geometry geom, String arg) Provide opportunity/hook for subclasses to introduce new geometries.int
Draws the index of a member of the population with a probability proportional to fitness.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
.protected int
pickFitNeighborAt
(int me) Pick a neighbour of the focal individualme
with probability proportional to their fitness.protected int
pickFitNeighborAt
(int me, boolean withSelf) Pick a neighbour of the focal individualme
with probability proportional to their fitness.private int
pickFocal
(int excl) Pick a focal individual uniformly at random but excluding the individual with indexexcl
.int
Draws the index of a individual of the population uniformly at random.int
pickFocalIndividual
(int excl) Draws the index of a individual of the population uniformly at random but excluding the individual with indexexcl
.int
Draws the index of a site in the population uniformly at random, irrespective of whether it is occupied or not.int
pickFocalSite
(int excl) Draws the index of a site in the population uniformly at random, irrespective of whether it is occupied or not.protected int
pickNeighborSiteAt
(int me) Picks a neighbouring site of the focal individualme
uniformly at random.private int
pickNeutralNeighbourAt
(int me, boolean withSelf) Helper method to do picking under neutral conditions (no or negligible fitness differences).void
playGameAt
(int me) Update the score of individualme
.void
playGameSyncAt
(int me) Update the score of individualme
.abstract void
playGroupGameAt
(IBSGroup group) Play a group interaction with the individuals ingroup
.abstract void
playPairGameAt
(IBSGroup group) Play a pairwise interaction with the individuals ingroup
.abstract boolean
preferredPlayerBest
(int me, int best, int sample) For deterministic updating with multiple strategies (more than two), it must be specified which strategy is the preferred one.abstract void
Prior to a synchronous update step the current state must be duplicated in preparation for processing the next step.protected double
processScore
(double score, boolean max) Process the accumulatedscore
in this population, taking the updating into account.double
random01()
Draw a uniformly distributed randomdouble
from the semi-closed interval[0, 1)
with 32bit resolution.double
Draw a uniformly distributed randomdouble
from the semi-closed interval[0, 1)
with maximal 53bit resolution.int
random0n
(int n) Draw a uniformly distributed random integer number from the semi-closed interval[0, n)
.int
random0N
(int n) Draw a uniformly distributed random integer number from the closed interval[0, n]
.double
randomGaussian
(double mean, double sdev) Draw a Gaussian (normal) distributed randomdouble
.void
removeScoreAt
(int index, double nilscore) Removes the scorenilscore
based on a single interaction from the individual with indexindex
.void
removeScoreAt
(int index, double nilscore, int incr) Removes the scorenilscore
based onincr
interactions from the individual with indexindex
.void
reset()
Reset the model.void
resetScoreAt
(int index) Reset score of individual at indexindex
.void
Reset scores and fitness of all individuals to zero.void
Reset all strategies in preparation of the next update step.boolean
restoreFitness
(Plist plist) Restore the fitness of all individuals encoded in theplist
inspiredmap
ofkey, value
-pairs.boolean
restoreGeometry
(Plist plist) Restore the interaction and competition structures encoded in theplist
inspiredmap
ofkey, value
-pairs.boolean
restoreInteractions
(Plist plist) Restore the interactions of all individuals encoded in theplist
inspiredmap
ofkey, value
-pairs.abstract boolean
restoreStrategies
(Plist plist) Restore the strategies of all individuals encoded in theplist
inspiredmap
ofkey, value
-pairs.private double
second
(int excl) Find the second highest score.void
setAddwire
(double[] addwire) Set the probabilities for adding links to the interaction and competition graphs.void
setConsistencyCheck
(boolean check) Enable consistency checks of the state of the IBS model.protected void
Find the index of the individual with the highest score.void
setMigrationProb
(double aValue) Sets the migration probability toaValue
.void
Sets the type of migrations totype
.void
setOpponentPop
(IBSPopulation opponent) Set the interaction partner/opponent of this population.void
setPlayerScoreAveraged
(boolean aver) Sets whether scores of individuals are averaged over multiple interactions or accumulated.void
Sets the type for managing scores of individuals.void
setPopulationUpdate
(PopulationUpdate populationUpdate) Sets the population update.void
setRewire
(double[] rewire) Set the probabilities for rewiring links of the interaction and competition graphs.void
setScoreAt
(int index, double newscore, int inter) Sets the score of individual with indexindex
tonewscore
as the result ofinter
interactions.void
setSyncFraction
(double sync) Set the fraction of the population that gets updated in synchronous updates.boolean
setTagAt
(int idx, double tag) Sets the tag of the individual with indexidx
.void
srandom
(long s) Set the seed of the random number generator for competition simulation runs.double
step()
Perform a single IBS step, i.e.void
swapScoresAt
(int idxa, int idxb) Swap the scores (and fitness) of individuals with indicesidxa
andidxb
.abstract void
swapStrategies
(int a, int b) Swap strategies of individuals with indexa
and indexb
.protected boolean
updateEffScoreRange
(int index, double before, double after) Keep track of highest score through a reference to the corresponding individual.void
updateFitnessAt
(int idx) Update the fitness of the individual with indexidx
by mapping its current score.void
updateFromModelAt
(int me, int you) Update individual with indexme
and adopt the strategy of individual with indexyou
.void
Retrieve and store extremal scores and fitnesses to reduce calls toModule
.protected void
Perform a single, asynchronous update of the strategy of a randomly selected individual.void
updatePlayerAsyncAt
(int me) Update the strategy of the focal individual with indexme
.boolean
updatePlayerAt
(int me) Perform a single update of the individual with indexme
.private boolean
updatePlayerAt
(int me, int[] refGroup, int rGroupSize) Perform a single update of the individual with indexme
using therGroupSize
models in the arrayrefGroup
.protected boolean
updatePlayerBest
(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexme
by adopting the strategy of the best performing reference individual among therGroupSize
models in the arrayrefGroup
.protected boolean
updatePlayerBestHalf
(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexme
by adopting the strategy of the best performing reference individual among the therGroupSize
models in the arrayrefGroup
.boolean
updatePlayerBestResponse
(int me, int[] group, int size) Best-response update.double
Perform a single ecological update of an individual selected uniformly at random.protected double
updatePlayerEcologyAt
(int index) Perform a single ecological update of the site with indexindex
.void
Perform a single, Moran (Birth-death) update for a random individual selected with a probability proportional to fitness.protected void
updatePlayerMoranBirthDeathAt
(int parent) Perform a Moran (Birth-death) update for the focal individual with indexparent
to produce a clonal offspring and replace one of the parent's neighbours selected uniformly at random.void
Perform a single Moran (death-Birth) update for a site selected uniformly at random.protected void
updatePlayerMoranDeathBirthAt
(int vacant) Perform a single Moran (death-Birth) update for the focal site with indexvacant
.void
Perform a single, Moran (imitate) update for a site selected uniformly at random.protected void
updatePlayerMoranImitateAt
(int imitator) Update the focal individual with indeximitator
by comparing its own payoff and those of its neighbors.void
updatePlayerSwap
(int a, int b) Swap players in locationsa
andb
.protected boolean
updateProportionalAbs
(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexme
by adopting the strategy of one reference individual (including itself) among the therGroupSize
models in the arrayrefGroup
with a probability proportional to their scores.private boolean
updateReplicator
(int me, int[] refGroup, int rGroupSize, boolean betterOnly) Helper method for replicator type updates.protected boolean
updateReplicatorHalf
(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexme
by adopting the strategy of one reference individual among the therGroupSize
models in the arrayrefGroup
.protected boolean
updateReplicatorPlus
(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexme
by adopting the strategy of one reference individual among the therGroupSize
models in the arrayrefGroup
.protected void
updateScoreAt
(int me, boolean switched) Update the scores of the focal individual with indexme
.void
updateScoreAt
(int index, double newscore) Update the score of the individual with indexindex
by addingnewscore
from single interaction.void
updateScoreAt
(int index, double newscore, int incr) Update the score of the individual with indexindex
by adding (incr > 0
or removing,incr < 0
)newscore
as the result ofincr
interactions.void
Update the scores of all individuals in the population.protected boolean
updateThermal
(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexme
by adopting the strategy of one reference individual among the therGroupSize
models in the arrayrefGroup
.abstract void
yalpGroupGameAt
(IBSGroup group)
-
Field Details
-
engine
The pacemaker of all models. Interface with the outside world. -
module
The module associated with this model. -
staticmodule
Convenience field for static modules to avoid casts. -
opponent
IBSPopulation opponentThe 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
PlayerUpdate playerUpdateThe update type of players. Convenience field.- See Also:
-
VACANT
protected int VACANTThe index of vacant sites or-1
if 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 strategy of another (default) or only if an actual strategy change 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 byminFitness
in 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 bymaxFitness
in 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.updateMixedMeanScores()
.nMixedInter
is 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,Geometry.Type.MEANFIELD
. 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
protected boolean 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:
-
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:
-
isConsistent
boolean isConsistentThe flag to indicate whether the state of the IBS model is consistent.- See Also:
-
consistencyCheckRequested
boolean consistencyCheckRequestedThe flag to indicate whether consistency checks on the state of the IBS model are requested.- See Also:
-
syncFraction
double syncFractionThe fraction of the population that gets updated in synchronous updates.
-
-
Constructor Details
-
IBSPopulation
Creates a population of individuals for IBS simulations.- Parameters:
engine
- the pacemaker for running the modelmodule
- the module that defines the game
-
-
Method Details
-
getModule
Gets the module asociated 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
-
prepareStrategies
public abstract void prepareStrategies()Prior to a synchronous update step the current state must be duplicated in preparation for processing the next step.- See Also:
-
commitStrategies
public abstract void commitStrategies()After a synchronous update step the new state must be copied back to become the current state.- See Also:
-
commitStrategyAt
public abstract void commitStrategyAt(int index) The change of a strategy of the player atindex
is stored in a temporary variable and must be committed before proceeding.- Parameters:
index
- the index of the player that needs to have its new strategy committed
-
haveSameStrategy
public abstract boolean haveSameStrategy(int a, int b) Check if individuals with indexa
and indexb
have the same strategies.- Parameters:
a
- the index of first individualb
- the index of second individual- Returns:
true
if the two individuals have the same strategies
-
isSameStrategy
public abstract boolean isSameStrategy(int a) Check if individual with indexa
has switched strategies.Note: this test is only meaningful before strategy gets committed.
- Parameters:
a
- index of individual- Returns:
true
if strategy remained the same- See Also:
-
swapStrategies
public abstract void swapStrategies(int a, int b) Swap strategies of individuals with indexa
and indexb
.Note: the strategies 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 indexme
and its neighbors afterme
changed strategy. Only works ifadjustScores==true
.Important: new strategy 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 indexindex
frombefore
toafter
and update all applicable helper variables, e.g.sumFitness
.Important: Use only to adjust scores of individuals that did not change strategy.
- 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 indexindex
byadjust
and 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
group
is 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_RESPONSE
fromPlayerUpdate#clo
.
- Parameters:
me
- the index of individual to updategroup
- the array with indices of reference groupsize
- the size of the reference group- Returns:
true
if strategy 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 strategies (more than two), it must be specified which strategy 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:
true
ifsample
is preferred overbest
-
isVacantAt
public boolean isVacantAt(int index) Check if site with indexindex
is occupied by an individual or vacant.Note: Assumes that strategies are committed.
- Parameters:
index
- the index of the individual/site to check- Returns:
true
if siteindex
is vacant
-
becomesVacantAt
public boolean becomesVacantAt(int index) Check if site with indexindex
will become vacant in this time step.Note: Assumes that strategies are not committed.
- Parameters:
index
- the index of the individual/site to check- Returns:
true
if siteindex
will 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:
true
if population is monomorphic- See Also:
-
checkConvergence
public abstract boolean checkConvergence()Check if population has converged. By defaulttrue
if 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:
true
if 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
-
getInterGroup
Gets the interaction group.- Returns:
- the interaction group
-
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 locationsa
andb
.- 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
-
pickFocal
private int pickFocal(int excl) Pick a focal individual uniformly at random but excluding the individual with indexexcl
. Helper method.- Parameters:
excl
- the index of the excluded individual- Returns:
- the index of the picked individual
-
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
≥0
Important: 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*nPopulation
trials are needed, which seems too much...
- 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
≥0
Important: 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 individualme
with 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 individualme
with probability proportional to their fitness. If the flagwithSelf==true
then 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
-
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
protected int pickNeighborSiteAt(int me) Picks a neighbouring site of the focal individualme
uniformly 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 indexme
and adopt the strategy of individual with indexyou
.Note: method must be subclassed to deal with different data types of strategies but should also include a call to super.
- Parameters:
me
- the index of the focal individualyou
- the index of the model individual to adopt strategy 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 siteme
is vacant do nothing.- Parameters:
me
- the index of the focal individual- See Also:
-
adjustGameScoresAt
public void adjustGameScoresAt(int me) Adjust scores of focal playerme
and its neighbours (interaction partners).Requirements/notes:
- This optimized method is only applicable if
IBSGroup.SamplingType.ALL
is true and notGeometry.Type.MEANFIELD
, 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 stratgies 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 indexindex
by addingnewscore
from 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 indexindex
by adding (incr > 0
or removing,incr < 0
)newscore
as the result ofincr
interactions.Important:
- Strategies are already committed when adding scores
(
incr>0
). - Strategies 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 strategy and hence where it matters whether strategies 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
- Strategies are already committed when adding scores
(
-
updateFitnessAt
public void updateFitnessAt(int idx) Update the fitness of the individual with indexidx
by mapping its current score. Keeps track ofsumFitness
.Note: If
sumFitness
decreases dramatically rounding errors become an issue. More specifically, ifsumFitness
is 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 indexindex
tonewscore
as the result ofinter
interactions. 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 scorenilscore
based 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 scorenilscore
based onincr
interactions 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: Strategies must not yet have been committed.
Discussions/extensions:
Revise the entire strategy updating procedure: it's inefficient to first reset scores then update strategies 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 indicesidxa
andidxb
.- 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
cSD
with a well-mixed population of10'000
spends>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:
true
if effective range of payoffs has changed (or, more precisely, if the reference individual has changed);false
otherwise.
- 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 double 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 elapsed time in realtime units
-
mutate
public double mutate()Perform a mutation event. The focal individual is picked uniformly at random.- Returns:
- the elapsed time in realtime units
-
mutateAt
public abstract double mutateAt(int focal) Mutate the strategy of the focal individual with indexfocal
. The mutated strategy is committed and the scores updated.- Parameters:
focal
- the index of the focal individual- Returns:
- the elapsed time in realtime units
-
maybeMutateAt
protected abstract boolean maybeMutateAt(int focal, boolean switched) Consider mutating the trait of the focal individual with indexfocal
. The strategy of the focal individual is stored in the arraystrategies
unless the focal individual switched strategy. In that case the current strategy is stored in the arraystrategyScratch
.Important: The trait is not committed regardless of whether a mutation occurred.
- Parameters:
focal
- the index of the focal individualswitched
-true
if the focal individual switched strategy- Returns:
true
if 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 strategy 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 indexfocal
for 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 indexfocal
using 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 strategy of a randomly selected individual. -
updatePlayerAsyncAt
public void updatePlayerAsyncAt(int me) Update the strategy 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
-true
if the focal switched strategy
-
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 indexparent
to 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 the imitate strategy in Ohtsuki et al. Nature 2005.- See Also:
-
updatePlayerMoranImitateAt
protected void updatePlayerMoranImitateAt(int imitator) Update the focal individual with indeximitator
by comparing its own payoff and those of its neighbors. The focal individual imitates the strategy 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 strategy
-
migrateMoran
protected void migrateMoran(int source, int dest) Perform a single Moran update for the reproducing node with indexsource
and the node that gets replaced with indexdest
. The three Moran variants (death-Birth, Birth-death and imitate) differ only in their selection of the individualssource
anddest
and then call this method,migrateMoran(int, int)
.Note: Moran optimizations for discrete strategies 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 double updatePlayerEcology()Perform a single ecological update of an individual selected uniformly at random.- Returns:
- real-time increment
-
updatePlayerEcologyAt
protected double 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
IBSPopulation
and provide their own implementations.- Parameters:
index
- the index of the focal site- Returns:
- real-time increment
-
updatePlayerAt
public boolean updatePlayerAt(int me) Perform a single update of the individual with indexme
. Returnstrue
if 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:
true
if trait of reference adopted- See Also:
-
updatePlayerAt
private boolean updatePlayerAt(int me, int[] refGroup, int rGroupSize) Perform a single update of the individual with indexme
using therGroupSize
models in the arrayrefGroup
. Returnstrue
if the individual changed its strategy 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:
true
if trait of reference adopted- See Also:
-
updatePlayerBest
protected boolean updatePlayerBest(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexme
by adopting the strategy of the best performing reference individual among therGroupSize
models in the arrayrefGroup
. Returnstrue
if 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 strategy.
- 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:
true
if trait of reference adopted- See Also:
-
updatePlayerBestHalf
protected boolean updatePlayerBestHalf(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexme
by adopting the strategy of the best performing reference individual among the therGroupSize
models 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 strategy to keep/adopt. Returnstrue
if 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:
true
if trait of reference adopted- See Also:
-
updateProportionalAbs
protected boolean updateProportionalAbs(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexme
by adopting the strategy of one reference individual (including itself) among the therGroupSize
models in the arrayrefGroup
with a probability proportional to their scores. Returnstrue
if 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:
true
if trait of reference adopted- See Also:
-
updateReplicatorPlus
protected boolean updateReplicatorPlus(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexme
by adopting the strategy of one reference individual among the therGroupSize
models in the arrayrefGroup
. The focal individual \(i\) imitates the strategy 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]\). Returnstrue
if 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:
true
if trait of reference adopted- See Also:
-
updateReplicatorHalf
protected boolean updateReplicatorHalf(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexme
by adopting the strategy of one reference individual among the therGroupSize
models in the arrayrefGroup
. The focal individual \(i\) imitates the strategy 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. Returnstrue
if 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:
true
if trait of reference adopted- See Also:
-
updateReplicator
private boolean updateReplicator(int me, int[] refGroup, int rGroupSize, boolean betterOnly) Helper method for replicator type updates. Returnstrue
if 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:
true
if trait of reference adopted- See Also:
-
updateThermal
protected boolean updateThermal(int me, int[] refGroup, int rGroupSize) Updates the focal individual with indexme
by adopting the strategy of one reference individual among the therGroupSize
models in the arrayrefGroup
. The focal individual \(i\) imitates the strategy 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 strategy. 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\). Returnstrue
if 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:
true
if trait of reference adopted- See Also:
-
getMinScore
public double getMinScore()Returns the minimum scoremin
in this population, taking the population structure and payoff accounting into account.- Returns:
- the processed minimum score
-
getMaxScore
public double getMaxScore()Returns the maximum scoremin
in this population, taking the population structure and payoff accounting into account.- Returns:
- the processed maximum score
-
processScore
protected double processScore(double score, boolean max) Process the accumulatedscore
in this population, taking the updating into account.- Parameters:
score
- the minimum or maximum scoremax
-true
if score is maximum- 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). Returnstrue
if adjustments require a reset. Free memory if possible and request a reset if new memory needs to be allocated.- Returns:
true
if reset is required- See Also:
-
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 strategy. 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/strategies.Requirements:
- Group.SAMPLING_ALL
- individuals need to be interacting with all their neighbours (not just a randomly selected subset).
- Geometry.MEANFIELD
- interactions with everyone are not feasible (impossible to model
efficiently), in general, for unstructured populations (subclasses can do
better, e.g. for discrete strategies it is possible, see
IBSDPopulation.doAdjustScores()
). - playerScoreReset
- if scores are reset whenever an individual adopts the strategy of another (regardless of whether an actual strategy 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:
true
if 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 strategies and call super.- See Also:
-
init
public void init()Initialize the model. All parameters must be consistent. Subclasses must override this method to generate the initial strategy 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
-true
to 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.
-
resetStrategies
public void resetStrategies()Reset all strategies in preparation of the next update step. Simply an opportunity for customizations in subclasses. -
getInitialTraits
public abstract void getInitialTraits(double[] init) Returns the initial trait(s) of this population in the arrayinit
. Used by GUI to visualize the initial state of this IBS model.- Parameters:
init
- the array for returning the initial trait values- See Also:
-
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
Geometry.Type.SQUARE_NEUMANN_2ND
with two disjoint interaction or competition graphs.- Returns:
- the number of mean values
- See Also:
-
getMeanTraits
public abstract void 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- See Also:
-
getTraitData
Returns the traits of all individuals in this population coded as colors in the arraycolors
using 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.PopGraph2D
orPopGraph3D
).- Type Parameters:
T
- the type of color data (String
orMeshLambertMaterial
for GWT andColor
for JRE).- Parameters:
colors
- the array where the colors of all nodes are storedcolorMap
- the map that converts traits into colors
-
getMeanFitness
public abstract void 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. Returnstrue
if data point belongs to the same time series andfalse
if a new series was started throughinit()
orreset()
.- Parameters:
mean
- the array for storing the mean fitness values- See Also:
-
getFitnessData
Returns the fitness of all individuals in this population coded as colors in the arraycolors
using 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.PopGraph2D
orPopGraph3D
).- Type Parameters:
T
- the type of color data (String
orMeshLambertMaterial
for GWT andColor
for 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:
bins
is 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
IBSDPopulation
andIBSCPopulation
with argumentsbins[][]
andbins[]
, respectively.
- Parameters:
bins
- the 2D array to store the histogram(s)
-
getScores
Gets the scores of all individuals with precisiondigits
. Scores of vacant sites are reported as 0d/0d.- Parameters:
digits
- the number of digits for the scores- Returns:
- the formatted scores
-
getScoreNameAt
Gets the formatted score of the individual with indexidx
.- Parameters:
idx
- the index of the individual- Returns:
- the formatted score
-
getFitness
Gets the fitness of all individuals with precisiondigits
. Fitness of vacant sites are reported as 0d/0d.- Parameters:
digits
- the number of digits for the scores- Returns:
- the formatted fitness
-
getFitnessNameAt
Gets the formatted fitness of the individual with indexidx
as a string. If the flagpretty
is set the formatting is prettyfied by replacing the exponentE
in 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 indexidx
as 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-1
if siteidx
is 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 arraycolors
using 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.PopGraph2D
orPopGraph3D
).- Type Parameters:
T
- the type of color data (String
orMeshLambertMaterial
for GWT andColor
for 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 indexidx
as 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:
true
if 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
-
getInteractionGeometry
Gets the structure of interactions.- Returns:
- the interaction structure
-
createInteractionGeometry
Creates a new instance of the interaction structure, if needed.- Returns:
- the interaction structure
-
getCompetitionGeometry
Gets the structure of competition or imitations.- Returns:
- the competition structure
-
createCompetitionGeometry
Creates a new instance of the competition or imitation structure, if needed.- Returns:
- the competition structure
-
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:
true
if 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:
true
if player scores are averaged.
-
parseGeometry
Provide opportunity/hook for subclasses to introduce new geometries.- Parameters:
geom
- the current empty/uninitialized geometryarg
- the commandline argument- Returns:
true
if parsing was successful- See Also:
-
checkGeometry
Provide opportunity/hook for subclasses to introduce new geometries.- Parameters:
geom
- the geometry to check- Returns:
true
if checks were successful- See Also:
-
generateGeometry
Provide opportunity/hook for subclasses to introduce new geometries.- Parameters:
geom
- the geometry to initialize- Returns:
true
if generation of structure was successful- See Also:
-
mouseHitNode
public boolean mouseHitNode(int hit) Called from GUI if node/individual with indexidx
received a mouse click or tap.- Parameters:
hit
- the index of the node- Returns:
false
if no actions taken
-
mouseHitNode
public boolean mouseHitNode(int hit, boolean alt) Called from GUI if node/individual with indexidx
received a mouse click or tap and indicates whether thealt
-key had been pressed.- Parameters:
hit
- the index of the nodealt
-true
if thealt
-key was pressed- Returns:
false
if no actions taken
-
encodeFitness
Encode the fitness of all individuals in the IBS model in aplist
inspiredXML
string.- Parameters:
plist
- theStringBuilder
to write the encoded state to- See Also:
-
restoreFitness
Restore the fitness of all individuals encoded in theplist
inspiredmap
ofkey, value
-pairs.- Parameters:
plist
- the map ofkey, value
-pairs- Returns:
true
if successful- See Also:
-
encodeInteractions
Encode the interactions of all individuals in the IBS model in aplist
inspiredXML
string.- Parameters:
plist
- theStringBuilder
to write the encoded state to- See Also:
-
restoreInteractions
Restore the interactions of all individuals encoded in theplist
inspiredmap
ofkey, value
-pairs.- Parameters:
plist
- the map ofkey, value
-pairs- Returns:
true
if successful- See Also:
-
encodeStrategies
Encode the strategies of all individuals in the IBS model in aplist
inspiredXML
string.- Parameters:
plist
- theStringBuilder
to write the encoded state to- See Also:
-
restoreStrategies
Restore the strategies of all individuals encoded in theplist
inspiredmap
ofkey, value
-pairs.- Parameters:
plist
- the map ofkey, value
-pairs- Returns:
true
if successful- See Also:
-
encodeGeometry
Encode the interaction and competition structures of the IBS model in aplist
inspiredXML
string.- Parameters:
plist
- theStringBuilder
to write the encoded state to- See Also:
-
restoreGeometry
Restore the interaction and competition structures encoded in theplist
inspiredmap
ofkey, value
-pairs.- Parameters:
plist
- the map ofkey, value
-pairs- Returns:
true
if successful- See Also:
-
srandom
public void srandom(long s) Set the seed of the random number generator for competition simulation runs.- Parameters:
s
- the seed for random number generator
-
random0N
public int random0N(int n) Draw a uniformly distributed random integer number from the closed interval[0, n]
.- Parameters:
n
- the upper limit of interval (inclusive)- Returns:
- the random integer number in
[0, n]
.
-
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 randomdouble
from the semi-closed interval[0, 1)
with 32bit resolution. This is the default.- Returns:
- the random number in
[0, 1)
.
-
random01d
public double random01d()Draw a uniformly distributed randomdouble
from the semi-closed interval[0, 1)
with maximal 53bit resolution.Note: takes twice as long as regular precision.
- 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
-