Class IBSDPopulation
- Direct Known Subclasses:
CDL.IBSPop,IBSPop,NetGames.IBSPop,RSP.IBSPop,SIR.IBSPop,TBT.IBSPop
- Author:
- Christoph Hauert
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescription(package private) static classA 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.protected boolean[]The array indicating which traits are active.private IBSDPopulation.link[]The array to keep track of all links along which a change in the population composition may occur.protected IBS.HasIBS.DGroupsFor group interaction modulesmodule==groupmoduleholds andnullotherwise.protected IBSD.InitType of initial configuration.int[]The array with the initial number of individuals of each trait.protected DiscreteThe discrete module associated with this model.protected Mutation.DiscreteThe mutation parameters.protected IBSDPopulationThe interaction partner/opponent of this populationopponent.getModule()==getModule().getOpponent().protected booleanThe flag to indicate whether optimizations of Moran processes are requested.protected IBS.HasIBS.DPairsFor pairwise interaction modulesmodule==pairmoduleholds andnullotherwise.private int[]Temporary storage for the number of each trait in group interactions.private int[]Temporary storage for indices of individuals in group interactions.private double[]Temporary storage for the scores of each trait prior to the group interactions.private int[]Temporary storage for traits of individuals in group interactions.private double[]Temporary storage for the scores of each trait in group interactions.private int[]The array of individual traits.int[]The array with the total number of individuals of each trait.protected int[]The array for temporarily storing traits during updates.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 TypeMethodDescriptionvoidadjustGameScoresAt(int me) Adjust scores of focal playermeand its neighbours (interaction partners).voidadjustPairGameScoresAt(int me) Adjusts scores of focal individual with indexmeand its neighbors aftermechanged trait.voidadjustScoreAt(int index, double adjust) Adjust score of individual with indexindexbyadjustand update all applicable helper variables, e.g.voidadjustScoreAt(int index, double before, double after) Adjust score of individual with indexindexfrombeforetoafterand update all applicable helper variables, e.g.booleanbecomesVacantAt(int index) Check if site with indexindexwill become vacant in this time step.booleancheck()Check all model parameters for consistency and adjust if necessary (and feasible).booleanCheck if population has converged.voidcommitTraitAt(int me) The change of a trait of the player atindexis stored in a temporary variable and must be committed before proceeding.voidAfter a synchronous update step the new state must be copied back to become the current state.voidcountTraits(int[] counts, int[] myTraits, int offset, int len) Count the number of each trait in the arraytraitsstarting atoffsetforlenindividuals.protected voidOverride in subclass for example to mark those individuals in the GUI that were involved in the debug step.protected booleanCheck if scores can be adjusted rather than recalculated after an individual changed its trait.voidencodeTraits(StringBuilder plist) Encode the traits of all individuals in the IBS model in aplistinspiredXMLstring.private doubleestimateVacantFrequency(int type) Helper method to determine the frequency of vacant sites based on an estimate of the carrying capacity.private voidfillStripe(int offset, int width, int trait) Helper method to initialize lattice structures with homogeneous stripes of each trait.doublegetFitnessAt(int idx) Gets the fitness of the individual with indexidx.voidgetFitnessHistogramData(double[][] bins) Generates a histogram of the fitness distribution in this population.getInit()Gets the type of the initial configuration and its arguments.voidgetInitialTraits(double[] inittraits) Returns the initial trait(s) of this population in the arrayinit.voidgetMeanFitness(double[] mean) Returns the mean fitness of this population in the arraymean.voidgetMeanTraits(double[] mean) Returns the mean trait(s) of this population in the arraymean.doublegetMonoScore(int type) Gets the score of individuals in a population that is monomorphic in traittype.intGets current population size.doublegetScoreAt(int idx) Gets the score of the individual with indexidx.Gets the status of the as a formatted string.intgetTraitAt(int idx) Gets the trait of the individual with indexidx.<T> voidgetTraitData(T[] colors, ColorMap<T> colorMap) Returns the traits of all individuals in this population coded as colors in the arraycolorsusing 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.int[]Gets the count of each trait.booleanhaveSameTrait(int a, int b) Check if individuals with indexaand indexbhave the same traits.voidinit()Initialize the model.protected voidInitial configuration with trait frequencies as specified in arguments.protected voidInitial configuration that generates evolutionary kaleidoscopes for deterministic update rules.protected voidinitMono()Monomorphic initial configuration with specified trait (and frequency in modules that allow empty sites).voidinitMono(int monoType) Initialize monomorphic population with traitmonoType.voidinitMono(int monoType, double monoFreq) Initialize monomorphic population with traitmonoType.protected intMonomorphic initial configuration with a single mutant placed in a location chosen uniformly at random (uniform initialization, cosmic rays).protected voidInitial configuration with monomorphic stripes of each type to investigate invasion properties of one trait into another with at least one instance of all possible pairings.protected intMonomorphic 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 voidInitial configuration with uniform trait frequencies of all active traits.voidConvenience method during development to perform a number of consistency checks of the current state.booleanCheck if population is monomorphic.booleanisSameTrait(int a) Check if individual with indexahas switched traits.booleanisVacantAt(int index) Check if site with indexindexis occupied by an individual or vacant.protected booleanmaybeMutateAt(int focal, boolean switched) Consider mutating the trait of the focal individual with indexfocal.protected voidmaybeMutateMoran(int source, int dest) Consider mutating the trait of the parent individual with indexsource.booleanmouseHitNode(int hit, boolean alt) Called from GUI if node/individual with indexidxreceived a mouse click or tap and indicates whether thealt-key had been pressed.private booleanmouseSetHit(int hit, int trait) Process event from GUI: individual with indexhitwas hit by mouse (or tap) in order to set its trait totrait.intmutateAt(int focal) Mutate the trait of the focal individual with indexfocal.voidplayGroupGameAt(IBSGroup group) Play a group interaction with the individuals ingroup.voidplayPairGameAt(IBSGroup group) Play a pairwise interaction with the individuals ingroup.booleanpreferredPlayerBest(int me, int best, int sample) For deterministic updating with multiple traits (more than two), it must be specified which trait is the preferred one.voidPrior to a synchronous update step the current state must be duplicated in preparation for processing the next step.voidreset()Reset the model.voidresetScoreAt(int index) Reset score of individual at indexindex.voidReset scores and fitness of all individuals to zero.voidReset all traits in preparation of the next update step.booleanrestoreFitness(Plist plist) Restore the fitness of all individuals encoded in theplistinspiredmapofkey, value-pairs.booleanrestoreTraits(Plist plist) Restore the traits of all individuals encoded in theplistinspiredmapofkey, value-pairs.voidSets the type of the initial configuration and any accompanying arguments.booleansetInitialTraits(double[] init) Set the initial trait frequencies in the population.booleansetNextTraitAt(int idx, int trait) Sets the next trait of the individual with indexidxtotrait.voidsetOpponentPop(IBSPopulation opponent) Set the interaction partner/opponent of this population.voidsetScoreAt(int index, double newscore, int inter) Sets the score of individual with indexindextonewscoreas the result ofinterinteractions.voidsetTraitAt(int idx, int trait) Sets the trait of the individual with indexidxtotrait.protected voidstripGroupVacancies(IBSGroup group, int[] gTraits, int[] gIdxs) Eliminate vacant sites from the assembled group.protected intstripVacancies(int[] groupidx, int groupsize, int[] gTraits, int[] gIdxs) Process traits while excluding vacant sites.private intsum(int start, int end) Helper method to determine the number of stripes required so that each trait shares at least one interface with every other trait:nStripes = nTraits + 2 * sum(2, nTraits - 2).voidswapTraits(int a, int b) Swap traits of individuals with indexaand indexb.voidupdateFromModelAt(int index, int modelPlayer) Update individual with indexmeand adopt the trait of individual with indexyou.protected voidCalculate scores in well-mixed populations as well as hierarchical structures with well-mixed units.booleanupdatePlayerBestResponse(int me, int[] group, int size) Best-response update.protected intupdatePlayerEcologyAt(int me) Perform a single ecological update of the individual with indexme: Focal individual dies with probability proportional to the death rate.voidPerform a single, Moran (Birth-death) update for a random individual selected with a probability proportional to fitness.voidPerform a single Moran (death-Birth) update for a site selected uniformly at random.protected voidupdatePlayerMoranDeathBirth(boolean withSelf) The optimized Moran process for death-Birth and imitation updatating.voidPerform a single, Moran (imitate) update for a site selected uniformly at random.voidupdateScoreAt(int index, double newscore, int incr) Update the score of the individual with indexindexby adding (incr > 0or removing,incr < 0)newscoreas the result ofincrinteractions.voidUpdate the scores of all individuals in the population.voidUpdate the count of each trait.voidyalpGroupGameAt(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, getSpeciesUpdateRate, 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, 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 onlyDiscretemodules generateIBSDPopulation(s). -
pairmodule
For pairwise interaction modulesmodule==pairmoduleholds andnullotherwise. Convenience field to reduce the number of (unnecessary) casts.- See Also:
-
groupmodule
For group interaction modulesmodule==groupmoduleholds andnullotherwise. Convenience field to reduce the number of (unnecessary) casts.- See Also:
-
opponent
The 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 onlyDiscretemodules generateIBSDPopulation(s). -
optimizeMoran
protected boolean optimizeMoranThe flag to indicate whether optimizations of Moran processes are requested.trueif 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 traits 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. -
traits
private int[] traitsThe array of individual traits. -
traitsNext
protected int[] traitsNextThe array for temporarily storing traits during updates. -
active
protected boolean[] activeThe array indicating which traits are active. Convenience field to reduce calls to module. -
accuTypeScores
protected double[] accuTypeScoresThe array with the total scores for each trait. -
traitsCount
public int[] traitsCountThe array with the total number of individuals of each trait. -
initCount
public int[] initCountThe array with the initial number of individuals of each trait. -
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:
-
tmpTraits
private int[] tmpTraitsTemporary storage for traits of individuals in group interactions. -
tmpGroup
private int[] tmpGroupTemporary storage for indices of individuals in group interactions. -
tmpCount
private int[] tmpCountTemporary storage for the number of each trait in group interactions. -
tmpTraitScore
private double[] tmpTraitScoreTemporary storage for the scores of each trait in group interactions. -
tmpScore
private double[] tmpScoreTemporary storage for the scores of each trait prior to the group interactions. -
init
Type of initial configuration.- See Also:
-
-
Constructor Details
-
IBSDPopulation
Creates a population of individuals with discrete traits for IBS simulations.- Parameters:
engine- the pacemaker for running the modelmodule- the module that defines the game
-
-
Method Details
-
setOpponentPop
Description copied from class:IBSPopulationSet the interaction partner/opponent of this population.- Overrides:
setOpponentPopin classIBSPopulation- Parameters:
opponent- the interaction partner/opponent
-
getPopulationSize
public int getPopulationSize()Description copied from class:IBSPopulationGets 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:
getPopulationSizein 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 trait and call super.Allocates memory for optimized Moran process.
Discussions/extensions
groupScoresunused in IBSDPopulation. Merge withtraitScore?- Overrides:
resetin 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 traits. This destroys the time scale.
- Overrides:
updatePlayerMoranBirthDeathin classIBSPopulation- See Also:
-
updatePlayerMoranImitate
public void updatePlayerMoranImitate()Description copied from class:IBSPopulationPerform a single, Moran (imitate) update for a site selected uniformly at random. This corresponds to imitate in Ohtsuki et al. Nature 2005.- Overrides:
updatePlayerMoranImitatein classIBSPopulation- See Also:
-
updatePlayerMoranDeathBirth
public void updatePlayerMoranDeathBirth()Description copied from class:IBSPopulationPerform 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:
updatePlayerMoranDeathBirthin 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 traits. This destroys the time scale.- Parameters:
withSelf- the flag to indicate whether to include to focal individual- See Also:
-
updatePlayerEcologyAt
protected int 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:
updatePlayerEcologyAtin classIBSPopulation- Parameters:
me- the index of the focal site- Returns:
- the number of elapsed realtime units
-
updateFromModelAt
public void updateFromModelAt(int index, int modelPlayer) Description copied from class:IBSPopulationUpdate individual with indexmeand adopt the trait of individual with indexyou.Note: method must be subclassed to deal with different data types of traits but should also include a call to super.
- Overrides:
updateFromModelAtin classIBSPopulation- Parameters:
index- the index of the focal individualmodelPlayer- the index of the model individual to adopt trait from- See Also:
-
mutateAt
public int mutateAt(int focal) Description copied from class:IBSPopulationMutate the trait of the focal individual with indexfocal. The mutated trait is committed and the scores updated.- Specified by:
mutateAtin classIBSPopulation- Parameters:
focal- the index of the focal individual- Returns:
- the number of elapsed realtime units
-
maybeMutateAt
protected boolean maybeMutateAt(int focal, boolean switched) Description copied from class:IBSPopulationConsider mutating the trait of the focal individual with indexfocal. The trait of the focal individual is stored in the arraytraitsunless the focal individual switched trait. In that case the current trait is stored in the arraytraitsNext.Important: The trait is not committed regardless of whether a mutation occurred.
- Specified by:
maybeMutateAtin classIBSPopulation- Parameters:
focal- the index of the focal individualswitched-trueif the focal individual switched trait- Returns:
trueif the trait of the focal individual changed
-
maybeMutateMoran
protected void maybeMutateMoran(int source, int dest) Description copied from class:IBSPopulationConsider mutating the trait of the parent individual with indexsource. The mutated trait is committed and the scores updated.- Specified by:
maybeMutateMoranin 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:IBSPopulationOverride in subclass for example to mark those individuals in the GUI that were involved in the debug step.- Overrides:
debugMarkChangein classIBSPopulation
-
haveSameTrait
public boolean haveSameTrait(int a, int b) Description copied from class:IBSPopulationCheck if individuals with indexaand indexbhave the same traits.- Specified by:
haveSameTraitin classIBSPopulation- Parameters:
a- the index of first individualb- the index of second individual- Returns:
trueif the two individuals have the same traits
-
isSameTrait
public boolean isSameTrait(int a) Description copied from class:IBSPopulationCheck if individual with indexahas switched traits.Note: this test is only meaningful before trait are committed.
- Specified by:
isSameTraitin classIBSPopulation- Parameters:
a- index of individual- Returns:
trueif trait remained unchanged- See Also:
-
swapTraits
public void swapTraits(int a, int b) Description copied from class:IBSPopulationSwap traits of individuals with indexaand indexb.Note: the traits still need to be committed.
- Specified by:
swapTraitsin 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:IBSPopulationUpdate the score of the individual with indexindexby adding (incr > 0or removing,incr < 0)newscoreas the result ofincrinteractions.Important:
- Traits are already committed when adding scores
(
incr>0). - Traits are not committed when removing scores
(
incr<0). - This routine is never called for the focal site (i.e. the one that may have changed trait and hence where it matters whether traits are committed).
IBSPopulation.resetScoreAt(int)deals with the focal site.
- Overrides:
updateScoreAtin classIBSPopulation- Parameters:
index- the index of the individualnewscore- score/payoff to add (incr>0) or subtract (incr<0)incr- number of interactions
- Traits are already committed when adding scores
(
-
setScoreAt
public void setScoreAt(int index, double newscore, int inter) Description copied from class:IBSPopulationSets the score of individual with indexindextonewscoreas the result ofinterinteractions. 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:
setScoreAtin 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:IBSPopulationGets the score of the individual with indexidx.- Overrides:
getScoreAtin classIBSPopulation- Parameters:
idx- the index of the individual- Returns:
- the score of the individual
-
getFitnessAt
public double getFitnessAt(int idx) Description copied from class:IBSPopulationGets the fitness of the individual with indexidx.- Overrides:
getFitnessAtin classIBSPopulation- Parameters:
idx- the index of the individual- Returns:
- the fitness of the individual
-
getTraitAt
public int getTraitAt(int idx) Gets the trait of the individual with indexidx. The trait is an index in[0,nTraits).- Parameters:
idx- the index of the individual- Returns:
- the trait of the individual
- See Also:
-
setTraitAt
public void setTraitAt(int idx, int trait) Sets the trait of the individual with indexidxtotrait. The trait is an index in[0,nTraits).- Parameters:
idx- the index of the individualtrait- the new trait- See Also:
-
setNextTraitAt
public boolean setNextTraitAt(int idx, int trait) Sets the next trait of the individual with indexidxtotrait. The trait is an index in[0,nTraits).- Parameters:
idx- the index of the individualtrait- the new trait- Returns:
trueif the trait changed- See Also:
-
resetScoreAt
public void resetScoreAt(int index) Description copied from class:IBSPopulationReset score of individual at indexindex.Important: traits must not yet have been committed.
Discussions/extensions:
Revise the entire trait updating procedure: it's inefficient to first reset scores then update traits then update score...- Overrides:
resetScoreAtin classIBSPopulation- Parameters:
index- the index of the individual
-
resetScores
public void resetScores()Description copied from class:IBSPopulationReset scores and fitness of all individuals to zero.- Overrides:
resetScoresin 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:
updateScoresin classIBSPopulation
-
updatePlayerBestResponse
public boolean updatePlayerBestResponse(int me, int[] group, int size) Best-response update.Important:
- The array
groupis untouchable because it may refer to the population structure. Any change would also permanently change the structure. - The best-response update must be implemented in subclasses that override this method. By default throws an error.
- Instead of overriding the method, subclasses may remove
PlayerUpdate.Type.BEST_RESPONSEfromPlayerUpdate#clo.
Note: Takes composition of entire population into account for
Geometry.Type#MEANFIELDbut only the reference neighborhood in structured populations.- Overrides:
updatePlayerBestResponsein classIBSPopulation- Parameters:
me- the index of individual to updategroup- the array with indices of reference groupsize- the size of the reference group- Returns:
trueif trait changed (signaling score needs to be reset)
- The array
-
preferredPlayerBest
public boolean preferredPlayerBest(int me, int best, int sample) For deterministic updating with multiple traits (more than two), it must be specified which trait is the preferred one.Summary: does 'me' prefer 'sample' over 'best'?
Here we introduce the convention of a cyclic preference where traits with lower indices are always preferred. For example, with
Ntraits, trait0is preferred over1preferred over2... preferred overN-1preferred overNpreferred over0, etc. This convention is arbitrary but makes sense for systems with cyclic dominance of traits 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:
preferredPlayerBestin classIBSPopulation- Parameters:
me- the index of the focal individualbest- the index of the best performing individualsample- the index of the sample type- Returns:
trueifsampleis preferred overbest
-
stripGroupVacancies
Eliminate vacant sites from the assembled group.Important:
group.groupis 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 sitesgTraits- the array of traits in the groupgIdxs- the array of indices of the individuals in the group
-
stripVacancies
protected int stripVacancies(int[] groupidx, int groupsize, int[] gTraits, int[] gIdxs) Process traits while excluding vacant sites.- Parameters:
groupidx- the array of indices of the individuals in the groupgroupsize- the size of the groupgTraits- the array to store/return the traitsgIdxs- the array to store/return the pruned indexes- Returns:
- the size of the interaction group after pruning
-
playPairGameAt
Description copied from class:IBSPopulationPlay a pairwise interaction with the individuals ingroup.- Specified by:
playPairGameAtin classIBSPopulation- Parameters:
group- the group of individuals interacting in pairs
-
adjustScoreAt
public void adjustScoreAt(int index, double before, double after) Description copied from class:IBSPopulationAdjust score of individual with indexindexfrombeforetoafterand update all applicable helper variables, e.g.sumFitness.Important: Use only to adjust scores of individuals that did not change trait.
- Specified by:
adjustScoreAtin 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:IBSPopulationAdjust score of individual with indexindexbyadjustand update all applicable helper variables, e.g.sumFitness.- Specified by:
adjustScoreAtin classIBSPopulation- Parameters:
index- the index of the individualadjust- the score adjustment
-
adjustPairGameScoresAt
public void adjustPairGameScoresAt(int me) Description copied from class:IBSPopulationAdjusts scores of focal individual with indexmeand its neighbors aftermechanged trait. Only works ifadjustScores==true.Important: new trait must not yet have been committed.
- Specified by:
adjustPairGameScoresAtin classIBSPopulation- Parameters:
me- the index of the focal individual
-
playGroupGameAt
Description copied from class:IBSPopulationPlay a group interaction with the individuals ingroup.- Specified by:
playGroupGameAtin classIBSPopulation- Parameters:
group- the group of interacting individuals
-
yalpGroupGameAt
Description copied from class:IBSPopulationCounterpart ofIBSPopulation.playGroupGameAt(IBSGroup),IBSPopulation.playGameAt(int)and/orIBSPopulation.playGameSyncAt(int). Removes the payoffs of group interactions.- Specified by:
yalpGroupGameAtin classIBSPopulation- Parameters:
group- the interaction group
-
adjustGameScoresAt
public void adjustGameScoresAt(int me) Adjust scores of focal playermeand its neighbours (interaction partners).Requirements/notes:
- This optimized method is only applicable if
IBSGroup.SamplingType.ALLis true and 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 trait and are hence delegated to subclasses.
Overridden to allow for adjusting scores in well-mixed populations.
- Overrides:
adjustGameScoresAtin 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[] myTraits, int offset, int len) Count the number of each trait in the arraytraitsstarting atoffsetforlenindividuals. The result is stored incounts.Note:
offsetis convenient for hierarchical structures and prevents copying parts of thetraitsarray.- Parameters:
counts- the array to return the number of individuals with each traitmyTraits- the array with the traits of the individualsoffset- the offset into the arraytraitsto start countinglen- the number of individuals to count
-
resetTraits
public void resetTraits()Reset all traits in preparation of the next update step. Simply an opportunity for customizations in subclasses.Reset the colors of recently changed trait.
- Overrides:
resetTraitsin classIBSPopulation
-
prepareTraits
public void prepareTraits()Description copied from class:IBSPopulationPrior to a synchronous update step the current state must be duplicated in preparation for processing the next step.- Specified by:
prepareTraitsin classIBSPopulation- See Also:
-
commitTraits
public void commitTraits()After a synchronous update step the new state must be copied back to become the current state.For discrete modules, update the trait count of each type and check if population reached a homogeneous state.
- Specified by:
commitTraitsin classIBSPopulation- See Also:
-
updateTraitCount
public void updateTraitCount()Update the count of each trait.- See Also:
-
getTraitsCount
public int[] getTraitsCount()Gets the count of each trait.- Returns:
- the array with the numbers of each trait
-
isConsistent
public void isConsistent()Description copied from class:IBSPopulationConvenience 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:
isConsistentin classIBSPopulation
-
isMonomorphic
public boolean isMonomorphic()Description copied from class:IBSPopulationCheck 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:
isMonomorphicin classIBSPopulation- Returns:
trueif population is monomorphic- See Also:
-
checkConvergence
public boolean checkConvergence()Description copied from class:IBSPopulationCheck if population has converged. By defaulttrueif population is monomorphic and no (zero) mutations. However, different implementations may have different criteria for convergence.Note: This tends to be less restrictive than reaching an absorbing state. Typically convergence is used as a criterion to abort simulations.
- Specified by:
checkConvergencein classIBSPopulation- Returns:
trueif converged.
-
isVacantAt
public boolean isVacantAt(int index) Description copied from class:IBSPopulationCheck if site with indexindexis occupied by an individual or vacant.Note: Assumes that trait are committed.
- Overrides:
isVacantAtin classIBSPopulation- Parameters:
index- the index of the individual/site to check- Returns:
trueif siteindexis vacant
-
becomesVacantAt
public boolean becomesVacantAt(int index) Description copied from class:IBSPopulationCheck if site with indexindexwill become vacant in this time step.Note: Assumes that trait are not committed.
- Overrides:
becomesVacantAtin classIBSPopulation- Parameters:
index- the index of the individual/site to check- Returns:
trueif siteindexwill become vacant
-
commitTraitAt
public void commitTraitAt(int me) Description copied from class:IBSPopulationThe change of a trait of the player atindexis stored in a temporary variable and must be committed before proceeding.- Specified by:
commitTraitAtin classIBSPopulation- Parameters:
me- the index of the player that needs to have its new trait 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:IBSPopulationGenerates a histogram of the fitness distribution in this population. The result is returned in the arraybins.Notes:
binsis a 2D array because discrete models generate histograms for each trait separately.- By default generate a histogram of the scores in
bins[0]. - Consider moving to
IBSDPopulationandIBSCPopulationwith argumentsbins[][]andbins[], respectively.
- Overrides:
getFitnessHistogramDatain 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:
trueif the initialization was successful
-
getInitialTraits
public void getInitialTraits(double[] inittraits) Returns the initial trait(s) of this population in the arrayinit. Used by GUI to visualize the initial state of this IBS model.- Parameters:
inittraits- the array for returning the initial trait values- See Also:
-
getMeanTraits
public void getMeanTraits(double[] mean) Description copied from class:IBSPopulationReturns the mean trait(s) of this population in the arraymean. Used by GUI to visualize the current state of this IBS model.- Specified by:
getMeanTraitsin classIBSPopulation- Parameters:
mean- the array for returning the trait values- See Also:
-
getTraitData
Description copied from class:IBSPopulationReturns the traits of all individuals in this population coded as colors in the arraycolorsusing the mapcolorMap. Used by GUI to visualize the current state of this IBS model. Colors are coded in different data types<T>depending on the runtime environment (GWT or JRE) as well as the graph (e.g.PopGraph2DorPopGraph3D).- Specified by:
getTraitDatain classIBSPopulation- Type Parameters:
T- the type of color data (StringorMeshLambertMaterialfor GWT andColorfor JRE).- Parameters:
colors- the array where the colors of all nodes are storedcolorMap- the map that converts traits into colors
-
getMeanFitness
public void getMeanFitness(double[] mean) Description copied from class:IBSPopulationReturns the mean fitness of this population in the arraymean. Used by GUI to visualize the current state of this IBS model. Returnstrueif data point belongs to the same time series andfalseif a new series was started throughIBSPopulation.init()orIBSPopulation.reset().- Specified by:
getMeanFitnessin 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 traits since the previous report, while those in[nTraits, 2*nTraits)have.- Returns:
- the traits
-
getTraitNameAt
Description copied from class:IBSPopulationGets the formatted name of the trait of the individual at siteindex.- Specified by:
getTraitNameAtin classIBSPopulation- Parameters:
idx- the index of the- Returns:
- the string describing the trait
-
getStatus
Description copied from class:IBSPopulationGets the status of the as a formatted string. This is typically used in the GUI to summarize the progress of the model.- Specified by:
getStatusin classIBSPopulation- Returns:
- the status of the population
-
check
public boolean check()Description copied from class:IBSPopulationCheck all model parameters for consistency and adjust if necessary (and feasible). Returnstrueif adjustments require a reset. Free memory if possible and request a reset if new memory needs to be allocated.- Overrides:
checkin classIBSPopulation- Returns:
trueif reset is required- See Also:
-
doAdjustScores
protected boolean doAdjustScores()Description copied from class:IBSPopulationCheck if scores can be adjusted rather than recalculated after an individual changed its trait. This requires that individuals interact with all their neighbours and that the structure of the population is not well-mixed. Some implementations may be able to extend adjustments to other structures. For example, adjusting scores is feasible in well-mixed populations for discrete traits.Requirements:
- Group.SAMPLING_ALL
- individuals need to be interacting with all their neighbours (not just a randomly selected subset).
- 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 trait it is possible, see
doAdjustScores()). - playerScoreReset
- if scores are reset whenever an individual adopts the trait of another (regardless of whether an actual trait change occurred) then the expected number of interactions of each individual remains constant over time (even though the interaction count may differ for individuals on heterogeneous structures).
- Specified by:
doAdjustScoresin classIBSPopulation- Returns:
trueif adjusting scores is feasible- See Also:
-
init
public void init()Description copied from class:IBSPopulationInitialize the model. All parameters must be consistent. Subclasses must override this method to generate the initial trait configuration and call super.Note: Initialization leaves the interaction and competition structures untouched
- Overrides:
initin classIBSPopulation- See Also:
-
initUniform
protected void initUniform()Initial configuration with uniform trait frequencies of all active traits.- See Also:
-
initFrequency
protected void initFrequency()Initial configuration with trait 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 \(1-d/r\), where \(d\) is the death rate and \(r\) the fitness of the resident type. Similarly, on regular graphs the carrying capacity is \(1-(k-1)d/(r(k-1)-d)\), where \(k\) 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
public void initMono(int monoType) Initialize monomorphic population with traitmonoType.- Parameters:
monoType- the monomorphic trait
-
initMono
public void initMono(int monoType, double monoFreq) Initialize monomorphic population with traitmonoType. 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.KALEIDOSCOPEfor 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 trait 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.- Parameters:
offset- the offset to the start of the stripewidth- the width of the stripetrait- the trait 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 shares at least one interface with every other trait:nStripes = nTraits + 2 * sum(2, nTraits - 2). Procedure tested for2, 3, 4, 5traits.- 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 eithertypeorargsarenullthe 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:IBSPopulationCalled from GUI if node/individual with indexidxreceived a mouse click or tap and indicates whether thealt-key had been pressed.- Overrides:
mouseHitNodein classIBSPopulation- Parameters:
hit- the index of the nodealt-trueif thealt-key was pressed- Returns:
falseif no actions taken
-
mouseSetHit
private boolean mouseSetHit(int hit, int trait) Process event from GUI: individual with indexhitwas hit by mouse (or tap) in order to set its trait totrait.- Parameters:
hit- the index of the individual that was hit by mouse or taptrait- the new trait of the individual- Returns:
falseif no actions taken (should not happen)
-
restoreFitness
Restore the fitness of all individuals encoded in theplistinspiredmapofkey, value-pairs.Important: traits must already be restored!
- Overrides:
restoreFitnessin classIBSPopulation- Parameters:
plist- the map ofkey, value-pairs- Returns:
trueif successful- See Also:
-
encodeTraits
Description copied from class:IBSPopulationEncode the traits of all individuals in the IBS model in aplistinspiredXMLstring.- Specified by:
encodeTraitsin classIBSPopulation- Parameters:
plist- theStringBuilderto write the encoded state to- See Also:
-
restoreTraits
Description copied from class:IBSPopulationRestore the traits of all individuals encoded in theplistinspiredmapofkey, value-pairs.- Specified by:
restoreTraitsin classIBSPopulation- Parameters:
plist- the map ofkey, value-pairs- Returns:
trueif successful- See Also:
-