Class IBSDPopulation
- Direct Known Subclasses:
CDL.IBSPop
,NetGames.IBSPop
,RSP.IBSPop
,TBT.IBSPop
- Author:
- Christoph Hauert
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescription(package private) static class
A minimalstic helper class (or data structure) to represent a single directed link in the network structure. -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected double[]
The array with the total scores for each trait/strategic type.private IBSDPopulation.link[]
The array to keep track of all links along which a change in the population composition may occur.private int[]
Temporary storage for indices of individuals in group interactions.protected IBS.HasIBS.DGroups
For group interaction modulesmodule==groupmodule
holds andnull
otherwise.private int[]
Temporary storage for strategies/traits of individuals in group interactions.protected IBSD.Init
Type of initial configuration.int[]
The array with the initial number of individuals of each trait/strategic type.protected Discrete
The discrete module associated with this model.protected Mutation.Discrete
The mutation parameters.(package private) IBSDPopulation
The interaction partner/opponent of this populationopponent.getModule()==getModule().getOpponent()
.protected boolean
The flag to indicate whether optimizations of Moran processes are requested.protected IBS.HasIBS.DPairs
For pairwise interaction modulesmodule==pairmodule
holds andnull
otherwise.private int[]
Temporary storage for strategies/traits of individuals in small sub-group interactions.int[]
The array of individual strategies.protected int[]
The array for temporarily storing strategies during updates.int[]
The array with the total number of individuals of each trait/strategic type.private int[]
Temporary storage for the number of each strategy/type in group interactions.private double[]
Temporary storage for the scores of each strategy/type in group interactions.private double[]
Temporary storage for the scores of each strategy/type prior to the group interactions.Fields inherited from class IBSPopulation
adjustScores, competition, compGroup, consistencyCheckRequested, debugFocal, debugModel, debugModels, debugNModels, debugSame, distrMigrants, engine, fitness, groupScores, hasLookupTable, interaction, interactions, interGroup, isConsistent, isMultispecies, isNeutral, logger, map2fit, maxEffScoreIdx, maxFitness, maxScore, migrationType, minFitness, minScore, nMixedInter, nPopulation, nTraits, pAddwire, playerScoreAveraged, playerScoring, playerUpdate, pMigration, populationUpdate, pRewire, rng, scores, smallScores, staticmodule, sumFitness, syncFraction, tags, typeFitness, typeScores, VACANT
-
Constructor Summary
ConstructorsConstructorDescriptionIBSDPopulation
(EvoLudo engine, Discrete module) Creates a population of individuals with discrete traits for IBS simulations. -
Method Summary
Modifier and TypeMethodDescriptionvoid
adjustGameScoresAt
(int me) Adjust scores of focal playerme
and its neighbours (interaction partners).void
adjustPairGameScoresAt
(int me) Adjusts scores of focal individual with indexme
and its neighbors afterme
changed strategy.void
adjustScoreAt
(int index, double adjust) Adjust score of individual with indexindex
byadjust
and update all applicable helper variables, e.g.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).boolean
Check if population has converged.void
After a synchronous update step the new state must be copied back to become the current state.void
commitStrategyAt
(int me) The change of a strategy of the player atindex
is stored in a temporary variable and must be committed before proceeding.void
countTraits
(int[] counts, int[] traits, int offset, int len) Count the number of each trait in the arraytraits
starting atoffset
forlen
individuals.protected void
Override in subclass for example to mark those individuals in the GUI that were involved in the debug step.protected boolean
Check if scores can be adjusted rather than recalculated after an individual changed its strategy.void
encodeStrategies
(StringBuilder plist) Encode the strategies of all individuals in the IBS model in aplist
inspiredXML
string.private double
estimateVacantFrequency
(int type) Helper method to determine the frequency of vacant sites based on an estimate of the carrying capacity.private void
fillStripe
(int offset, int width, int trait) Helper method to initialize lattice structures with homogeneous stripes of each trait/strategic type.double
getFitnessAt
(int idx) Gets the fitness of the individual with indexidx
.void
getFitnessHistogramData
(double[][] bins) Generates a histogram of the fitness distribution in this population.getInit()
Gets the type of the initial configuration and its arguments.void
getInitialTraits
(double[] traits) Returns the initial trait(s) of this population in the arrayinit
.void
getMeanFitness
(double[] mean) Returns the mean fitness of this population in the arraymean
.void
getMeanTraits
(double[] mean) Returns the mean trait(s) of this population in the arraymean
.double
getMonoScore
(int type) Gets the score of individuals in a population that is monomorphic in traittype
.int
Gets current population size.double
getScoreAt
(int idx) Gets the score of the individual with indexidx
.Gets the status of the as a formatted string.int[]
Gets the count of each trait/strategic type.<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
.getTraitNameAt
(int idx) Gets the formatted name of the trait of the individual at siteindex
.Gets the traits of all individuals as indices.boolean
haveSameStrategy
(int a, int b) Check if individuals with indexa
and indexb
have the same strategies.void
init()
Initialize the model.protected void
Initial configuration with strategy frequencies as specified in arguments.protected void
Initial configuration that generates evolutionary kaleidoscopes for deterministic update rules.protected void
initMono()
Monomorphic initial configuration with specified trait (and frequency in modules that allow empty sites).private void
initMono
(int monoType, double monoFreq) Helper method for initializing monomorphic populations.protected int
Monomorphic initial configuration with a single mutant placed in a location chosen uniformly at random (uniform initialization, cosmic rays).protected void
Initial configuration with monomorphic stripes of each type to investigate invasion properties of one strategy into another with at least one instance of all possible pairings.protected int
Monomorphic initial configuration with a single mutant placed in a random location chosen with probability proprtional to the number of incoming links (temperature initialization, errors in reproduction).protected void
Initial configuration with uniform strategy frequencies of all active strategies.void
Convenience method during development to perform a number of consistency checks of the current state.boolean
Check if population is monomorphic.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 boolean
maybeMutateAt
(int focal, boolean switched) Consider mutating the trait of the focal individual with indexfocal
.protected void
maybeMutateMoran
(int source, int dest) Consider mutating the trait of the parent individual with indexsource
.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.private boolean
mouseSetHit
(int hit, int strategy) Process event from GUI: individual with indexhit
was hit by mouse (or tap) in order to set its strategy tostrategy
.double
mutateAt
(int focal) Mutate the strategy of the focal individual with indexfocal
.void
playGroupGameAt
(IBSGroup group) Play a group interaction with the individuals ingroup
.void
playPairGameAt
(IBSGroup group) Play a pairwise interaction with the individuals ingroup
.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.void
Prior to a synchronous update step the current state must be duplicated in preparation for processing the next step.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
restoreStrategies
(Plist plist) Restore the strategies of all individuals encoded in theplist
inspiredmap
ofkey, value
-pairs.void
Sets the type of the initial configuration and any accompanying arguments.boolean
setInitialTraits
(double[] init) Set the initial trait frequencies in the population.void
setOpponentPop
(IBSPopulation opponent) Set the interaction partner/opponent of this population.void
setScoreAt
(int index, double newscore, int inter) Sets the score of individual with indexindex
tonewscore
as the result ofinter
interactions.protected void
stripGroupVacancies
(IBSGroup group, int[] gStrat, int[] gIdxs) Eliminate vacant sites from the assembled group.protected int
stripVacancies
(int[] groupidx, int groupsize, int[] gStrat, int[] gIdxs) Process traits/strategic types while excluding vacant sites.private int
sum
(int start, int end) Helper method to determine the number of stripes required so that each trait/strategic type shares at least one interface with every other trait:nStripes = nTraits + 2 * sum(2, nTraits - 2)
.void
swapStrategies
(int a, int b) Swap strategies of individuals with indexa
and indexb
.void
updateFromModelAt
(int index, int modelPlayer) Update individual with indexme
and adopt the strategy of individual with indexyou
.protected void
Calculate scores in well-mixed populations as well as hierarchical structures with well-mixed units.boolean
updatePlayerBestResponse
(int me, int[] group, int size) Best-response update.protected double
updatePlayerEcologyAt
(int me) Perform a single ecological update of the individual with indexme
: Focal individual dies with probability proportional to the death rate.void
Perform a single, Moran (Birth-death) update for a random individual selected with a probability proportional to fitness.void
Perform a single Moran (death-Birth) update for a site selected uniformly at random.protected void
updatePlayerMoranDeathBirth
(boolean withSelf) The optimized Moran process for death-Birth and imitation updatating.void
Perform a single, Moran (imitate) update for a site selected uniformly at random.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.void
Update the count of each trait/strategic type.void
yalpGroupGameAt
(IBSGroup group) Counterpart ofIBSPopulation.playGroupGameAt(IBSGroup)
,IBSPopulation.playGameAt(int)
and/orIBSPopulation.playGameSyncAt(int)
.Methods inherited from class IBSPopulation
checkGeometry, createCompetitionGeometry, createInteractionGeometry, debugScores, debugUpdatePopulationAt, doBirthDeathMigration, doDeathBirthMigration, doDiffusionMigration, doMigration, doSyncMigration, encodeFitness, encodeGeometry, encodeInteractions, generateGeometry, getCompetitionGeometry, getCompGroup, getFitness, getFitnessData, getFitnessNameAt, getFitnessNameAt, getInteractionGeometry, getInteractionsAt, getInterGroup, getMaxScore, getMigrationProb, getMigrationType, getMinScore, getModule, getNMean, getPlayerScoreAveraged, getPlayerScoring, getPopulationUpdate, getScoreNameAt, getScores, getSyncFraction, getTagAt, getTagData, getTagNameAt, getTags, getTotalFitness, migrateMoran, mouseHitNode, mutate, nextBinomial, parseGeometry, pickFitFocalIndividual, pickFitFocalIndividual, pickFitNeighborAt, pickFitNeighborAt, pickFocalIndividual, pickFocalIndividual, pickFocalSite, pickFocalSite, pickNeighborSiteAt, playGameAt, playGameSyncAt, processScore, random01, random01d, random0n, random0N, randomGaussian, removeScoreAt, removeScoreAt, restoreGeometry, restoreInteractions, setAddwire, setConsistencyCheck, setMaxEffScoreIdx, setMigrationProb, setMigrationType, setPlayerScoreAveraged, setPlayerScoring, setPopulationUpdate, setRewire, setSyncFraction, setTagAt, srandom, step, swapScoresAt, updateEffScoreRange, updateFitnessAt, updateMinMaxScores, updatePlayerAsync, updatePlayerAsyncAt, updatePlayerAt, updatePlayerBest, updatePlayerBestHalf, updatePlayerEcology, updatePlayerMoranBirthDeathAt, updatePlayerMoranDeathBirthAt, updatePlayerMoranImitateAt, updatePlayerSwap, updateProportionalAbs, updateReplicatorHalf, updateReplicatorPlus, updateScoreAt, updateScoreAt, updateThermal
-
Field Details
-
module
The discrete module associated with this model.Note: This deliberately hides
IBSPopulation.module
. The two variables point to the same object but this setup avoids unnecessary casts because onlyDiscrete
modules generateIBSDPopulation
(s). -
pairmodule
For pairwise interaction modulesmodule==pairmodule
holds andnull
otherwise. Convenience field to reduce the number of (unnecessary) casts.- See Also:
-
groupmodule
For group interaction modulesmodule==groupmodule
holds andnull
otherwise. Convenience field to reduce the number of (unnecessary) casts.- See Also:
-
opponent
IBSDPopulation opponentThe interaction partner/opponent of this populationopponent.getModule()==getModule().getOpponent()
. In intra-species interactionsopponent==this
. Convenience field.Note: This deliberately hides
IBSPopulation.opponent
. The two variables point to the same object but this setup avoids unnecessary casts because onlyDiscrete
modules generateIBSDPopulation
(s). -
optimizeMoran
protected boolean optimizeMoranThe flag to indicate whether optimizations of Moran processes are requested.true
if optimizations for Moran process requested.Note:
- Optimizations are requested with the command line option
--optimize
(or-1
), seeIBSD.cloOptimize
. - Optimizations destroy the time line of events. Do not use if e.g. fixation times are of interest (but fine for fixation probabilities).
- Currently restricted to discrete strategies and structured populations,
where Moran type processes can be optimized by skipping events involving
individuals of the same type (see
maybeMutateMoran(int, int)
).
- Optimizations are requested with the command line option
-
mutation
The mutation parameters. -
strategies
public int[] strategiesThe array of individual strategies. -
strategiesScratch
protected int[] strategiesScratchThe array for temporarily storing strategies during updates. -
accuTypeScores
protected double[] accuTypeScoresThe array with the total scores for each trait/strategic type. -
strategiesTypeCount
public int[] strategiesTypeCountThe array with the total number of individuals of each trait/strategic type. -
initTypeCount
public int[] initTypeCountThe array with the initial number of individuals of each trait/strategic type. -
activeLinks
The array to keep track of all links along which a change in the population composition may occur. This is used for optimized Moran updating.- See Also:
-
groupStrat
private int[] groupStratTemporary storage for strategies/traits of individuals in group interactions. -
groupIdxs
private int[] groupIdxsTemporary storage for indices of individuals in group interactions. -
smallStrat
private int[] smallStratTemporary storage for strategies/traits of individuals in small sub-group interactions. -
traitCount
private int[] traitCountTemporary storage for the number of each strategy/type in group interactions. -
traitScore
private double[] traitScoreTemporary storage for the scores of each strategy/type in group interactions. -
traitTempScore
private double[] traitTempScoreTemporary storage for the scores of each strategy/type prior to the group interactions. -
init
Type of initial configuration.- See Also:
-
-
Constructor Details
-
Method Details
-
setOpponentPop
Description copied from class:IBSPopulation
Set the interaction partner/opponent of this population.- Overrides:
setOpponentPop
in classIBSPopulation
- Parameters:
opponent
- the interaction partner/opponent
-
getPopulationSize
public int getPopulationSize()Description copied from class:IBSPopulation
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.- Overrides:
getPopulationSize
in classIBSPopulation
- Returns:
- current population size
-
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.Allocates memory for optimized Moran process.
Discussions/extensions
groupScores
unused in IBSDPopulation. Merge withtraitScore
?- Overrides:
reset
in classIBSPopulation
- See Also:
-
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.Optimized Moran process: a significant speed boost is achieved when restricting events along links that potentially result in an actual change of the population composition, i.e. by focussing on those links that connect individuals of different strategies/traits. This destroys the time scale.
- Overrides:
updatePlayerMoranBirthDeath
in classIBSPopulation
- See Also:
-
updatePlayerMoranImitate
public void updatePlayerMoranImitate()Description copied from class:IBSPopulation
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.- Overrides:
updatePlayerMoranImitate
in classIBSPopulation
- See Also:
-
updatePlayerMoranDeathBirth
public void updatePlayerMoranDeathBirth()Description copied from class:IBSPopulation
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.- Overrides:
updatePlayerMoranDeathBirth
in classIBSPopulation
- See Also:
-
updatePlayerMoranDeathBirth
protected void updatePlayerMoranDeathBirth(boolean withSelf) The optimized Moran process for death-Birth and imitation updatating. A significant speed boost is achieved when restricting events along links that potentially result in an actual change of the population composition, i.e. by focussing on those links that connect individuals of different strategies/traits. This destroys the time scale.- Parameters:
withSelf
- the flag to indicate whether to include to focal individual- See Also:
-
updatePlayerEcologyAt
protected double updatePlayerEcologyAt(int me) Perform a single ecological update of the individual with indexme
:- Focal individual dies with probability proportional to the death rate.
- Otherwise, draw a random neighbour and, if unoccupied, place clonal offspring on neighboring site with probability proportional to fitness.
- Overrides:
updatePlayerEcologyAt
in classIBSPopulation
- Parameters:
me
- the index of the focal individual- Returns:
- time increment
-
updateFromModelAt
public void updateFromModelAt(int index, int modelPlayer) Description copied from class:IBSPopulation
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.
- Overrides:
updateFromModelAt
in classIBSPopulation
- Parameters:
index
- the index of the focal individualmodelPlayer
- the index of the model individual to adopt strategy from- See Also:
-
mutateAt
public double mutateAt(int focal) Description copied from class:IBSPopulation
Mutate the strategy of the focal individual with indexfocal
. The mutated strategy is committed and the scores updated.- Specified by:
mutateAt
in classIBSPopulation
- Parameters:
focal
- the index of the focal individual- Returns:
- the elapsed time in realtime units
-
maybeMutateAt
protected boolean maybeMutateAt(int focal, boolean switched) Description copied from class:IBSPopulation
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.
- Specified by:
maybeMutateAt
in classIBSPopulation
- 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 void maybeMutateMoran(int source, int dest) Description copied from class:IBSPopulation
Consider mutating the trait of the parent individual with indexsource
. The mutated strategy is committed and the scores updated.- Specified by:
maybeMutateMoran
in classIBSPopulation
- Parameters:
source
- the index of the parent individualdest
- the index of the location for the offspring placement
-
debugMarkChange
protected void debugMarkChange()Description copied from class:IBSPopulation
Override in subclass for example to mark those individuals in the GUI that were involved in the debug step.- Overrides:
debugMarkChange
in classIBSPopulation
-
haveSameStrategy
public boolean haveSameStrategy(int a, int b) Description copied from class:IBSPopulation
Check if individuals with indexa
and indexb
have the same strategies.- Specified by:
haveSameStrategy
in classIBSPopulation
- Parameters:
a
- the index of first individualb
- the index of second individual- Returns:
true
if the two individuals have the same strategies
-
isSameStrategy
public boolean isSameStrategy(int a) Description copied from class:IBSPopulation
Check if individual with indexa
has switched strategies.Note: this test is only meaningful before strategy gets committed.
- Specified by:
isSameStrategy
in classIBSPopulation
- Parameters:
a
- index of individual- Returns:
true
if strategy remained the same- See Also:
-
swapStrategies
public void swapStrategies(int a, int b) Description copied from class:IBSPopulation
Swap strategies of individuals with indexa
and indexb
.Note: the strategies still need to be committed.
- Specified by:
swapStrategies
in classIBSPopulation
- Parameters:
a
- the index of first individualb
- the index of second individual- See Also:
-
updateScoreAt
public void updateScoreAt(int index, double newscore, int incr) Description copied from class:IBSPopulation
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).
IBSPopulation.resetScoreAt(int)
deals with the focal site.
- Overrides:
updateScoreAt
in classIBSPopulation
- 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
(
-
setScoreAt
public void setScoreAt(int index, double newscore, int inter) Description copied from class:IBSPopulation
Sets the score of individual with indexindex
tonewscore
as the result ofinter
interactions. Also derives the corresponding fitness and adjustssumFitness
.Note: Assumes that
IBSPopulation.resetScores()
was called earlier (or at leastIBSPopulation.resetScoreAt(int)
for those sites thatsetScoreAt(int)
is used for updating their score).- Overrides:
setScoreAt
in classIBSPopulation
- Parameters:
index
- the index of the individualnewscore
- new score to setinter
- number of interactions
-
getScoreAt
public double getScoreAt(int idx) Description copied from class:IBSPopulation
Gets the score of the individual with indexidx
.- Overrides:
getScoreAt
in classIBSPopulation
- Parameters:
idx
- the index of the individual- Returns:
- the score of the individual
-
getFitnessAt
public double getFitnessAt(int idx) Description copied from class:IBSPopulation
Gets the fitness of the individual with indexidx
.- Overrides:
getFitnessAt
in classIBSPopulation
- Parameters:
idx
- the index of the individual- Returns:
- the fitness of the individual
-
resetScoreAt
public void resetScoreAt(int index) Description copied from class:IBSPopulation
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...- Overrides:
resetScoreAt
in classIBSPopulation
- Parameters:
index
- the index of the individual
-
resetScores
public void resetScores()Description copied from class:IBSPopulation
Reset scores and fitness of all individuals to zero.- Overrides:
resetScores
in classIBSPopulation
-
updateScores
public void updateScores()Update the scores of all individuals in the population.Note: Overridden to set scores in well-mixed populations more efficiently.
- Overrides:
updateScores
in classIBSPopulation
-
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
.
Note: Takes composition of entire population into account for
Geometry.Type#MEANFIELD
but only the reference neighborhood in structured populations.- Overrides:
updatePlayerBestResponse
in classIBSPopulation
- 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 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'?
Here we introduce the convention of a cyclic preference where strategies with lower indices are always preferred. For example, with
N
strategic types, strategy0
preferred over1
preferred over2
... preferred overN-1
preferred overN
preferred over0
, etc. This convention is arbitrary but seems to make sense for systems with cyclic dominance of strategies and such systems are most likely to produce evolutionary kaleidoscopes and only for those is this deterministic updating of crucial importance. For anything else, these are irrelevant quibbles.- Specified by:
preferredPlayerBest
in classIBSPopulation
- 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
-
stripGroupVacancies
Eliminate vacant sites from the assembled group.Important:
group.group
is untouchable! It may be a reference toGeometry.out[group.focal]
and hence any changes would actually alter the geometry!- Parameters:
group
- the group which potentially includes references to vacant sitesgStrat
- the array of strategies in the groupgIdxs
- the array of indices of the individuals in the group
-
stripVacancies
protected int stripVacancies(int[] groupidx, int groupsize, int[] gStrat, int[] gIdxs) Process traits/strategic types while excluding vacant sites.- Parameters:
groupidx
- the array of indices of the individuals in the groupgroupsize
- the size of the groupgStrat
- the array to store/return the traits/strategic typesgIdxs
- the array to store/return the pruned indexes- Returns:
- the size of the interaction group after pruning
-
playPairGameAt
Description copied from class:IBSPopulation
Play a pairwise interaction with the individuals ingroup
.- Specified by:
playPairGameAt
in classIBSPopulation
- Parameters:
group
- the group of individuals interacting in pairs
-
adjustScoreAt
public void adjustScoreAt(int index, double before, double after) Description copied from class:IBSPopulation
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.
- Specified by:
adjustScoreAt
in classIBSPopulation
- Parameters:
index
- the index of the individualbefore
- the score before adjustmentsafter
- the score after adjustments
-
adjustScoreAt
public void adjustScoreAt(int index, double adjust) Description copied from class:IBSPopulation
Adjust score of individual with indexindex
byadjust
and update all applicable helper variables, e.g.sumFitness
.- Specified by:
adjustScoreAt
in classIBSPopulation
- Parameters:
index
- the index of the individualadjust
- the score adjustment
-
adjustPairGameScoresAt
public void adjustPairGameScoresAt(int me) Description copied from class:IBSPopulation
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.
- Specified by:
adjustPairGameScoresAt
in classIBSPopulation
- Parameters:
me
- the index of the focal individual
-
playGroupGameAt
Description copied from class:IBSPopulation
Play a group interaction with the individuals ingroup
.- Specified by:
playGroupGameAt
in classIBSPopulation
- Parameters:
group
- the group of interacting individuals
-
yalpGroupGameAt
Description copied from class:IBSPopulation
Counterpart ofIBSPopulation.playGroupGameAt(IBSGroup)
,IBSPopulation.playGameAt(int)
and/orIBSPopulation.playGameSyncAt(int)
. Removes the payoffs of group interactions.- Specified by:
yalpGroupGameAt
in classIBSPopulation
- Parameters:
group
- the interaction group
-
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.
Overridden to allow for adjusting scores in well-mixed populations.
- Overrides:
adjustGameScoresAt
in classIBSPopulation
- Parameters:
me
- the index of the focal individual- See Also:
- This optimized method is only applicable if
-
updateMixedMeanScores
protected void updateMixedMeanScores()Calculate scores in well-mixed populations as well as hierarchical structures with well-mixed units. -
countTraits
public void countTraits(int[] counts, int[] traits, int offset, int len) Count the number of each trait in the arraytraits
starting atoffset
forlen
individuals. The result is stored incounts
.Note:
offset
is convenient for hierarchical structures and prevents copying parts of thestrategies
array.- Parameters:
counts
- the array to return the number of individuals with each trait/strategytraits
- the array with the strategies/traits of he individualsoffset
- the offset into the arraytraits
to start countinglen
- the number of individuals to count
-
resetStrategies
public void resetStrategies()Reset all strategies in preparation of the next update step. Simply an opportunity for customizations in subclasses.Reset the colors of recently changed strategies.
- Overrides:
resetStrategies
in classIBSPopulation
-
prepareStrategies
public void prepareStrategies()Description copied from class:IBSPopulation
Prior to a synchronous update step the current state must be duplicated in preparation for processing the next step.- Specified by:
prepareStrategies
in classIBSPopulation
- See Also:
-
commitStrategies
public void commitStrategies()After a synchronous update step the new state must be copied back to become the current state.For discrete modules, update the strategy count of each type and check if population reached a homogeneous state.
- Specified by:
commitStrategies
in classIBSPopulation
- See Also:
-
updateStrategiesTypeCount
public void updateStrategiesTypeCount()Update the count of each trait/strategic type.- See Also:
-
getStrategiesTypeCount
public int[] getStrategiesTypeCount()Gets the count of each trait/strategic type.- Returns:
- count of each trait/strategic type
-
isConsistent
public void isConsistent()Description copied from class:IBSPopulation
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.
- Overrides:
isConsistent
in classIBSPopulation
-
isMonomorphic
public boolean isMonomorphic()Description copied from class:IBSPopulation
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.
- Overrides:
isMonomorphic
in classIBSPopulation
- Returns:
true
if population is monomorphic- See Also:
-
checkConvergence
public boolean checkConvergence()Description copied from class:IBSPopulation
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.
- Specified by:
checkConvergence
in classIBSPopulation
- Returns:
true
if converged.
-
isVacantAt
public boolean isVacantAt(int index) Description copied from class:IBSPopulation
Check if site with indexindex
is occupied by an individual or vacant.Note: Assumes that strategies are committed.
- Overrides:
isVacantAt
in classIBSPopulation
- Parameters:
index
- the index of the individual/site to check- Returns:
true
if siteindex
is vacant
-
becomesVacantAt
public boolean becomesVacantAt(int index) Description copied from class:IBSPopulation
Check if site with indexindex
will become vacant in this time step.Note: Assumes that strategies are not committed.
- Overrides:
becomesVacantAt
in classIBSPopulation
- Parameters:
index
- the index of the individual/site to check- Returns:
true
if siteindex
will become vacant
-
commitStrategyAt
public void commitStrategyAt(int me) Description copied from class:IBSPopulation
The change of a strategy of the player atindex
is stored in a temporary variable and must be committed before proceeding.- Specified by:
commitStrategyAt
in classIBSPopulation
- Parameters:
me
- the index of the player that needs to have its new strategy committed
-
getMonoScore
public double getMonoScore(int type) Gets the score of individuals in a population that is monomorphic in traittype
.- Parameters:
type
- the trait type- Returns:
- the monomorphic score
-
getFitnessHistogramData
public void getFitnessHistogramData(double[][] bins) Description copied from class:IBSPopulation
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.
- Overrides:
getFitnessHistogramData
in classIBSPopulation
- Parameters:
bins
- the 2D array to store the histogram(s)
-
setInitialTraits
public boolean setInitialTraits(double[] init) Set the initial trait frequencies in the population. Switches the initialization type toIBSD.Init.Type.FREQUENCY
.- Parameters:
init
- the initial traits- Returns:
true
if the initialization was successful
-
getInitialTraits
public void getInitialTraits(double[] traits) Description copied from class:IBSPopulation
Returns the initial trait(s) of this population in the arrayinit
. Used by GUI to visualize the initial state of this IBS model.- Specified by:
getInitialTraits
in classIBSPopulation
- Parameters:
traits
- the array for returning the initial trait values- See Also:
-
getMeanTraits
public void getMeanTraits(double[] mean) Description copied from class:IBSPopulation
Returns the mean trait(s) of this population in the arraymean
. Used by GUI to visualize the current state of this IBS model.- Specified by:
getMeanTraits
in classIBSPopulation
- Parameters:
mean
- the array for returning the trait values- See Also:
-
getTraitData
Description copied from class:IBSPopulation
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
).- Specified by:
getTraitData
in classIBSPopulation
- 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 void getMeanFitness(double[] mean) Description copied from class:IBSPopulation
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 throughIBSPopulation.init()
orIBSPopulation.reset()
.- Specified by:
getMeanFitness
in classIBSPopulation
- Parameters:
mean
- the array for storing the mean fitness values- See Also:
-
getTraits
Gets the traits of all individuals as indices. Those with indices in[0, nTraits)
denote individuals that have not changed strategy since the previous report, while those in[nTraits, 2*nTraits)
have.- Returns:
- the traits
-
getTraitNameAt
Description copied from class:IBSPopulation
Gets the formatted name of the trait of the individual at siteindex
.- Specified by:
getTraitNameAt
in classIBSPopulation
- Parameters:
idx
- the index of the- Returns:
- the string describing the trait
-
getStatus
Description copied from class:IBSPopulation
Gets the status of the as a formatted string. This is typically used in the GUI to summarize the progress of the model.- Specified by:
getStatus
in classIBSPopulation
- Returns:
- the status of the population
-
check
public boolean check()Description copied from class:IBSPopulation
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.- Overrides:
check
in classIBSPopulation
- Returns:
true
if reset is required- See Also:
-
doAdjustScores
protected boolean doAdjustScores()Description copied from class:IBSPopulation
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
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).
- Specified by:
doAdjustScores
in classIBSPopulation
- Returns:
true
if adjusting scores is feasible- See Also:
-
init
public void init()Description copied from class:IBSPopulation
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
- Overrides:
init
in classIBSPopulation
- See Also:
-
initUniform
protected void initUniform()Initial configuration with uniform strategy frequencies of all active strategies.- See Also:
-
initFrequency
protected void initFrequency()Initial configuration with strategy frequencies as specified in arguments.- See Also:
-
initMono
protected void initMono()Monomorphic initial configuration with specified trait (and frequency in modules that allow empty sites).- See Also:
-
estimateVacantFrequency
private double estimateVacantFrequency(int type) Helper method to determine the frequency of vacant sites based on an estimate of the carrying capacity. In well-mixed populations this is , where is the death rate and the fitness of the resident type. Similarly, on regular graphs the carrying capacity is , where is the degree of the graph. Finally, on generic structures, the estimate of the carrying capacity is based on the average out-degree of all nodes.Note: residents in structured populations additionally have a characteristic distribution, which is not accounted for in this estimate.
- Parameters:
type
- the resident type- Returns:
- the estimated frequency of vacant sites
-
initMono
private void initMono(int monoType, double monoFreq) Helper method for initializing monomorphic populations. If the module admits vacant sites the frequency of individuals with the monomorphic trait is set tomonoFreq
.- Parameters:
monoType
- the monomorphic traitmonoFreq
- the frequency of the monomorphic trait
-
initMutant
protected int initMutant()Monomorphic initial configuration with a single mutant placed in a location chosen uniformly at random (uniform initialization, cosmic rays).- Returns:
- the location of the mutant
- See Also:
-
initTemperature
protected int initTemperature()Monomorphic initial configuration with a single mutant placed in a random location chosen with probability proprtional to the number of incoming links (temperature initialization, errors in reproduction).- Returns:
- the location of the mutant
- See Also:
-
initKaleidoscope
protected void initKaleidoscope()Initial configuration that generates evolutionary kaleidoscopes for deterministic update rules. Whether this is possible and and what kind of initial configurations are required depends on the module. Hence this method must be overriden in subclasses that admit kaleidoscopes.Note: requires the explicit adding of the key
IBSD.Init.Type.KALEIDOSCOPE
for IBS models. For example, addif (model instanceof IBSD) { CLOption clo = ((IBSDPopulation) getIBSPopulation()).getInit().clo; clo.addKey(Init.Type.KALEIDOSCOPE); }
toorg.evoludo.simulator.modules.Module#adjustCLO(org.evoludo.util.CLOParser)
.- See Also:
-
initStripes
protected void initStripes()Initial configuration with monomorphic stripes of each type to investigate invasion properties of one strategy into another with at least one instance of all possible pairings.- See Also:
-
fillStripe
private void fillStripe(int offset, int width, int trait) Helper method to initialize lattice structures with homogeneous stripes of each trait/strategic type.- Parameters:
offset
- the offset to the start of the stripewidth
- the width of the stripetrait
- the trait/stratgy of the stripe- See Also:
-
sum
private int sum(int start, int end) Helper method to determine the number of stripes required so that each trait/strategic type shares at least one interface with every other trait:nStripes = nTraits + 2 * sum(2, nTraits - 2)
. Procedure tested for2, 3, 4, 5
traits.- Parameters:
start
- the starting traitend
- the end trait- Returns:
- the number of traits
-
setInit
Sets the type of the initial configuration and any accompanying arguments. If eithertype
orargs
arenull
the respective current setting is preserved.- Parameters:
init
- the type and arguments of the initial configuration
-
getInit
Gets the type of the initial configuration and its arguments.- Returns:
- the type and arguments of the initial configuration
-
mouseHitNode
public boolean mouseHitNode(int hit, boolean alt) Description copied from class:IBSPopulation
Called from GUI if node/individual with indexidx
received a mouse click or tap and indicates whether thealt
-key had been pressed.- Overrides:
mouseHitNode
in classIBSPopulation
- Parameters:
hit
- the index of the nodealt
-true
if thealt
-key was pressed- Returns:
false
if no actions taken
-
mouseSetHit
private boolean mouseSetHit(int hit, int strategy) Process event from GUI: individual with indexhit
was hit by mouse (or tap) in order to set its strategy tostrategy
.- Parameters:
hit
- the index of the individual that was hit by mouse or tapstrategy
- the new strategy of the individual- Returns:
false
if no actions taken (should not happen)
-
restoreFitness
Restore the fitness of all individuals encoded in theplist
inspiredmap
ofkey, value
-pairs.Important: Strategies must already be restored!
- Overrides:
restoreFitness
in classIBSPopulation
- Parameters:
plist
- the map ofkey, value
-pairs- Returns:
true
if successful- See Also:
-
encodeStrategies
Description copied from class:IBSPopulation
Encode the strategies of all individuals in the IBS model in aplist
inspiredXML
string.- Specified by:
encodeStrategies
in classIBSPopulation
- Parameters:
plist
- theStringBuilder
to write the encoded state to- See Also:
-
restoreStrategies
Description copied from class:IBSPopulation
Restore the strategies of all individuals encoded in theplist
inspiredmap
ofkey, value
-pairs.- Specified by:
restoreStrategies
in classIBSPopulation
- Parameters:
plist
- the map ofkey, value
-pairs- Returns:
true
if successful- See Also:
-