Class IBSPopulation

Object
IBSPopulation
Direct Known Subclasses:
IBSDPopulation, IBSMCPopulation

public abstract class IBSPopulation extends Object
The core class for individual based simulations. Manages the population, including keeping track of the payoffs and fitness of individuals.

Note: strategies/traits cannot be handled here because they are represented by ints in discrete models but doubles in continuous models.

Author:
Christoph Hauert
See Also:
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    protected boolean
    Optimization: Flag to indicate whether adjusting instead of recalculating scores is possible.
    protected Geometry
    The geometry of the competition graph.
    protected IBSGroup
    Reference to the competition/reference/model group.
    (package private) boolean
    The flag to indicate whether consistency checks on the state of the IBS model are requested.
    private double[]
    Conveninece variable to store cumulative probability distributions for replicator updating.
    protected int
    Helper variable to store index of focal individual (birth) that got updated during debug step.
    protected int
    Helper variable to store index of target individual (death) that got updated during debug step.
    protected int[]
    Helper variable to store array of indices of individual that served as models during debug step.
    protected int
    Helper variable to number of individual that served as models during debug step.
    protected boolean
    Helper flag to indicate an actual trait change during debug step.
    The distribution to determine the number of migrants.
    protected EvoLudo
    The pacemaker of all models.
    protected double[]
    The array of individual fitness values.
    protected double[]
    Array to hold scores of individuals during payoff calculations.
    protected boolean
    Optimization: Flag to indicate whether lookup tables can be used.
    protected Geometry
    The geometry of the interaction graph.
    protected int[]
    The array of individual interaction counts.
    protected IBSGroup
    Reference to the interaction group.
    (package private) boolean
    The flag to indicate whether the state of the IBS model is consistent.
    protected boolean
    Flag to indicate whether the model entertains multiple species, i.e.
    protected boolean
    Flag to indicate whether dynamic is neutral, i.e.
    protected Logger
    Logger for keeping track of and reporting events and issues.
    protected Map2Fitness
    The map converting scores to fitness and vice versa.
    protected int
    Optimization: The index of the individual that currently holds the maximum score.
    protected double
    The absolute maximum fitness in the population.
    protected double
    The absolute maximum score in the population.
    The type of migration.
    protected double
    The absolute minimum fitness in the population.
    protected double
    The absolute minimum score in the population.
    protected Module
    The module associated with this model.
    protected int
    Optimization: Number of interactions in well-mixed populations for update rules that take advantage of IBSDPopulation.updateMixedMeanScores().
    protected int
    The size of the population.
    protected int
    The number of traits in module.
    (package private) IBSPopulation
    The interaction partner/opponent of this population opponent.getModule()==getModule().getOpponent().
    protected double[]
    The array containing the probabilities for adding links to the interaction and competition graphs.
    protected boolean
    Flag to indicate whether player scores are averaged (default) or accumulated.
    protected IBS.ScoringType
    Flag to indicate whether scores are reset whenever a player adopts the strategy of another (default) or only if an actual strategy change occurred.
    (package private) PlayerUpdate
    The update type of players.
    protected double
    The probability of migration.
    (package private) PopulationUpdate
    The population update.
    protected double[]
    The array containing the probabilities for rewiring links of the interaction and competition graphs.
    protected RNGDistribution
    The shared random number generator to ensure reproducibility of results.
    protected double[]
    The array of individual scores.
    protected double[]
    Array to hold scores of individuals during payoff calculations for small groups (not all neighbours).
    protected Features.Static
    Convenience field for static modules to avoid casts.
    protected double
    The total fitness of the population.
    (package private) double
    The fraction of the population that gets updated in synchronous updates.
    protected double[]
    The array of individual tags counts.
    protected double[]
    Optimization: the lookup table for fitness in well-mixed populations.
    protected double[]
    Optimization: the lookup table for scores in well-mixed populations.
    protected int
    The index of vacant sites or -1 if module does not support vacancies.
  • Constructor Summary

    Constructors
    Modifier
    Constructor
    Description
    protected
    IBSPopulation(EvoLudo engine, Module module)
    Creates a population of individuals for IBS simulations.
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    Adjust scores of focal player me and its neighbours (interaction partners).
    abstract void
    Adjusts scores of focal individual with index me and its neighbors after me changed strategy.
    abstract void
    adjustScoreAt(int index, double adjust)
    Adjust score of individual with index index by adjust and update all applicable helper variables, e.g.
    abstract void
    adjustScoreAt(int index, double before, double after)
    Adjust score of individual with index index from before to after and update all applicable helper variables, e.g.
    boolean
    becomesVacantAt(int index)
    Check if site with index index will become vacant in this time step.
    boolean
    Check all model parameters for consistency and adjust if necessary (and feasible).
    abstract boolean
    Check if population has converged.
    boolean
    Provide opportunity/hook for subclasses to introduce new geometries.
    abstract void
    After a synchronous update step the new state must be copied back to become the current state.
    abstract void
    commitStrategyAt(int index)
    The change of a strategy of the player at index is stored in a temporary variable and must be committed before proceeding.
    Creates a new instance of the competition or imitation structure, if needed.
    Creates a new instance of the interaction structure, if needed.
    protected void
    Override in subclass for example to mark those individuals in the GUI that were involved in the debug step.
    protected void
    debugScores(double hit)
    Log report if picking failed to shed better light on what might be the root cause for the failure.
    void
    Update focal individual with index focal for debugging.
    protected abstract boolean
    Check if scores can be adjusted rather than recalculated after an individual changed its strategy.
    void
    Perform a birth-death migration, where a focal individual (selected proportional to fitness) produces a migrant offspring, which replaces another member of the population uniformly at random.
    void
    Perform a death-birth migration, where a member of the population (selected uniformly at random) dies and the remaining individuals compete to repopulate the vacant site.
    void
    Perform diffusion migration, which is implemented as two players swap their locations while leaving their respective neighbourhood structure untouched.
    void
    Perform asynchronous migration.
    int
    Perform synchronous migration.
    void
    Encode the fitness of all individuals in the IBS model in a plist inspired XML string.
    void
    Encode the interaction and competition structures of the IBS model in a plist inspired XML string.
    void
    Encode the interactions of all individuals in the IBS model in a plist inspired XML string.
    abstract void
    Encode the strategies of all individuals in the IBS model in a plist inspired XML string.
    private String
    formatInfoAt(int focal, int model)
    Helper method to format information about updating the focal individual at index focal using the model individual with index model.
    boolean
    Provide opportunity/hook for subclasses to introduce new geometries.
    Gets the structure of competition or imitations.
    Gets the competition/reference/model group.
    getFitness(int digits)
    Gets the fitness of all individuals with precision digits.
    double
    getFitnessAt(int idx)
    Gets the fitness of the individual with index idx.
    <T> void
    getFitnessData(T[] colors, ColorMap.Gradient1D<T> colorMap)
    Returns the fitness of all individuals in this population coded as colors in the array colors using the map colorMap.
    void
    getFitnessHistogramData(double[][] bins)
    Generates a histogram of the fitness distribution in this population.
    Gets the formatted and prettyfied fitness of the individual with index idx as a string.
    getFitnessNameAt(int idx, boolean pretty)
    Gets the formatted fitness of the individual with index idx as a string.
    abstract void
    getInitialTraits(double[] init)
    Returns the initial trait(s) of this population in the array init.
    Gets the structure of interactions.
    int
    Gets the number of interactions of the individual with index idx.
    Gets the interaction group.
    double
    Returns the maximum score min in this population, taking the population structure and payoff accounting into account.
    abstract void
    getMeanFitness(double[] mean)
    Returns the mean fitness of this population in the array mean.
    abstract void
    getMeanTraits(double[] mean)
    Returns the mean trait(s) of this population in the array mean.
    double
    Gets the migration probability.
    Gets the type of migrations.
    double
    Returns the minimum score min in this population, taking the population structure and payoff accounting into account.
    Gets the module asociated with this population.
    int
    Return the number of mean values for this population (for traits or fitness).
    boolean
    Gets whether player scores are averaged (as opposed to accumulated).
    Gets the type for managing scores of individuals.
    int
    Gets current population size.
    Gets the population update.
    double
    getScoreAt(int idx)
    Gets the score of the individual with index idx.
    getScoreNameAt(int idx)
    Gets the formatted score of the individual with index idx.
    getScores(int digits)
    Gets the scores of all individuals with precision digits.
    abstract String
    Gets the status of the as a formatted string.
    double
    Get the fraction of the population that gets updated in synchronous updates.
    double
    getTagAt(int idx)
    Gets the tag of the individual with index idx.
    <T> void
    getTagData(T[] colors, ColorMap<T> colorMap)
    Returns the tags of all individuals in this population coded as colors in the array colors using the map colorMap.
    getTagNameAt(int idx)
    Gets the formatted tag of the individual with index idx as string.
    double[]
    getTags(double[] mem)
    Copies the tags of all individuals in the population and returns them in the array mem.
    double
    Gets the total fitness of the population.
    abstract <T> void
    getTraitData(T[] colors, ColorMap<T> colorMap)
    Returns the traits of all individuals in this population coded as colors in the array colors using the map colorMap.
    abstract String
    getTraitNameAt(int index)
    Gets the formatted name of the trait of the individual at site index.
    abstract boolean
    haveSameStrategy(int a, int b)
    Check if individuals with index a and index b have the same strategies.
    void
    Initialize the model.
    void
    Convenience method during development to perform a number of consistency checks of the current state.
    boolean
    Check if population is monomorphic.
    abstract boolean
    Check if individual with index a has switched strategies.
    boolean
    isVacantAt(int index)
    Check if site with index index is occupied by an individual or vacant.
    protected abstract boolean
    maybeMutateAt(int focal, boolean switched)
    Consider mutating the trait of the focal individual with index focal.
    protected abstract void
    maybeMutateMoran(int source, int dest)
    Consider mutating the trait of the parent individual with index source.
    protected void
    migrateMoran(int source, int dest)
    Perform a single Moran update for the reproducing node with index source and the node that gets replaced with index dest.
    boolean
    mouseHitNode(int hit)
    Called from GUI if node/individual with index idx received a mouse click or tap.
    boolean
    mouseHitNode(int hit, boolean alt)
    Called from GUI if node/individual with index idx received a mouse click or tap and indicates whether the alt-key had been pressed.
    double
    Perform a mutation event.
    abstract double
    mutateAt(int focal)
    Mutate the strategy of the focal individual with index focal.
    int
    nextBinomial(double p, int n)
    Draw a binomially distributed random integer.
    boolean
    Provide opportunity/hook for subclasses to introduce new geometries.
    int
    Draws the index of a member of the population with a probability proportional to fitness.
    int
    Draws the index of a member of the population with a probability proportional to fitness but excluding the individual with the index excl.
    protected int
    Pick a neighbour of the focal individual me with probability proportional to their fitness.
    protected int
    pickFitNeighborAt(int me, boolean withSelf)
    Pick a neighbour of the focal individual me with probability proportional to their fitness.
    private int
    pickFocal(int excl)
    Pick a focal individual uniformly at random but excluding the individual with index excl.
    int
    Draws the index of a individual of the population uniformly at random.
    int
    Draws the index of a individual of the population uniformly at random but excluding the individual with index excl.
    int
    Draws the index of a site in the population uniformly at random, irrespective of whether it is occupied or not.
    int
    pickFocalSite(int excl)
    Draws the index of a site in the population uniformly at random, irrespective of whether it is occupied or not.
    protected int
    Picks a neighbouring site of the focal individual me uniformly at random.
    private int
    pickNeutralNeighbourAt(int me, boolean withSelf)
    Helper method to do picking under neutral conditions (no or negligible fitness differences).
    void
    playGameAt(int me)
    Update the score of individual me.
    void
    Update the score of individual me.
    abstract void
    Play a group interaction with the individuals in group.
    abstract void
    Play a pairwise interaction with the individuals in group.
    abstract boolean
    preferredPlayerBest(int me, int best, int sample)
    For deterministic updating with multiple strategies (more than two), it must be specified which strategy is the preferred one.
    abstract void
    Prior to a synchronous update step the current state must be duplicated in preparation for processing the next step.
    protected double
    processScore(double score, boolean max)
    Process the accumulated score in this population, taking the updating into account.
    double
    Draw a uniformly distributed random double from the semi-closed interval [0, 1) with 32bit resolution.
    double
    Draw a uniformly distributed random double from the semi-closed interval [0, 1) with maximal 53bit resolution.
    int
    random0n(int n)
    Draw a uniformly distributed random integer number from the semi-closed interval [0, n).
    int
    random0N(int n)
    Draw a uniformly distributed random integer number from the closed interval [0, n].
    double
    randomGaussian(double mean, double sdev)
    Draw a Gaussian (normal) distributed random double.
    void
    removeScoreAt(int index, double nilscore)
    Removes the score nilscore based on a single interaction from the individual with index index.
    void
    removeScoreAt(int index, double nilscore, int incr)
    Removes the score nilscore based on incr interactions from the individual with index index.
    void
    Reset the model.
    void
    resetScoreAt(int index)
    Reset score of individual at index index.
    void
    Reset scores and fitness of all individuals to zero.
    void
    Reset all strategies in preparation of the next update step.
    boolean
    Restore the fitness of all individuals encoded in the plist inspired map of key, value-pairs.
    boolean
    Restore the interaction and competition structures encoded in the plist inspired map of key, value-pairs.
    boolean
    Restore the interactions of all individuals encoded in the plist inspired map of key, value-pairs.
    abstract boolean
    Restore the strategies of all individuals encoded in the plist inspired map of key, value-pairs.
    private double
    second(int excl)
    Find the second highest score.
    void
    setAddwire(double[] addwire)
    Set the probabilities for adding links to the interaction and competition graphs.
    void
    setConsistencyCheck(boolean check)
    Enable consistency checks of the state of the IBS model.
    protected void
    Find the index of the individual with the highest score.
    void
    setMigrationProb(double aValue)
    Sets the migration probability to aValue.
    void
    Sets the type of migrations to type.
    void
    Set the interaction partner/opponent of this population.
    void
    setPlayerScoreAveraged(boolean aver)
    Sets whether scores of individuals are averaged over multiple interactions or accumulated.
    void
    Sets the type for managing scores of individuals.
    void
    Sets the population update.
    void
    setRewire(double[] rewire)
    Set the probabilities for rewiring links of the interaction and competition graphs.
    void
    setScoreAt(int index, double newscore, int inter)
    Sets the score of individual with index index to newscore as the result of inter interactions.
    void
    setSyncFraction(double sync)
    Set the fraction of the population that gets updated in synchronous updates.
    boolean
    setTagAt(int idx, double tag)
    Sets the tag of the individual with index idx.
    void
    srandom(long s)
    Set the seed of the random number generator for competition simulation runs.
    double
    Perform a single IBS step, i.e.
    void
    swapScoresAt(int idxa, int idxb)
    Swap the scores (and fitness) of individuals with indices idxa and idxb.
    abstract void
    swapStrategies(int a, int b)
    Swap strategies of individuals with index a and index b.
    protected boolean
    updateEffScoreRange(int index, double before, double after)
    Keep track of highest score through a reference to the corresponding individual.
    void
    updateFitnessAt(int idx)
    Update the fitness of the individual with index idx by mapping its current score.
    void
    updateFromModelAt(int me, int you)
    Update individual with index me and adopt the strategy of individual with index you.
    void
    Retrieve and store extremal scores and fitnesses to reduce calls to Module.
    protected void
    Perform a single, asynchronous update of the strategy of a randomly selected individual.
    void
    Update the strategy of the focal individual with index me.
    boolean
    Perform a single update of the individual with index me.
    private boolean
    updatePlayerAt(int me, int[] refGroup, int rGroupSize)
    Perform a single update of the individual with index me using the rGroupSize models in the array refGroup.
    protected boolean
    updatePlayerBest(int me, int[] refGroup, int rGroupSize)
    Updates the focal individual with index me by adopting the strategy of the best performing reference individual among the rGroupSize models in the array refGroup.
    protected boolean
    updatePlayerBestHalf(int me, int[] refGroup, int rGroupSize)
    Updates the focal individual with index me by adopting the strategy of the best performing reference individual among the the rGroupSize models in the array refGroup.
    boolean
    updatePlayerBestResponse(int me, int[] group, int size)
    Best-response update.
    double
    Perform a single ecological update of an individual selected uniformly at random.
    protected double
    Perform a single ecological update of the site with index index.
    void
    Perform a single, Moran (Birth-death) update for a random individual selected with a probability proportional to fitness.
    protected void
    Perform a Moran (Birth-death) update for the focal individual with index parent to produce a clonal offspring and replace one of the parent's neighbours selected uniformly at random.
    void
    Perform a single Moran (death-Birth) update for a site selected uniformly at random.
    protected void
    Perform a single Moran (death-Birth) update for the focal site with index vacant.
    void
    Perform a single, Moran (imitate) update for a site selected uniformly at random.
    protected void
    Update the focal individual with index imitator by comparing its own payoff and those of its neighbors.
    void
    updatePlayerSwap(int a, int b)
    Swap players in locations a and b.
    protected boolean
    updateProportionalAbs(int me, int[] refGroup, int rGroupSize)
    Updates the focal individual with index me by adopting the strategy of one reference individual (including itself) among the the rGroupSize models in the array refGroup with a probability proportional to their scores.
    private boolean
    updateReplicator(int me, int[] refGroup, int rGroupSize, boolean betterOnly)
    Helper method for replicator type updates.
    protected boolean
    updateReplicatorHalf(int me, int[] refGroup, int rGroupSize)
    Updates the focal individual with index me by adopting the strategy of one reference individual among the the rGroupSize models in the array refGroup.
    protected boolean
    updateReplicatorPlus(int me, int[] refGroup, int rGroupSize)
    Updates the focal individual with index me by adopting the strategy of one reference individual among the the rGroupSize models in the array refGroup.
    protected void
    updateScoreAt(int me, boolean switched)
    Update the scores of the focal individual with index me.
    void
    updateScoreAt(int index, double newscore)
    Update the score of the individual with index index by adding newscore from single interaction.
    void
    updateScoreAt(int index, double newscore, int incr)
    Update the score of the individual with index index by adding (incr &gt; 0 or removing, incr &lt; 0) newscore as the result of incr interactions.
    void
    Update the scores of all individuals in the population.
    protected boolean
    updateThermal(int me, int[] refGroup, int rGroupSize)
    Updates the focal individual with index me by adopting the strategy of one reference individual among the the rGroupSize models in the array refGroup.
    abstract void

    Methods inherited from class Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • engine

      protected EvoLudo engine
      The pacemaker of all models. Interface with the outside world.
    • module

      protected Module module
      The module associated with this model.
    • staticmodule

      protected Features.Static staticmodule
      Convenience field for static modules to avoid casts.
    • opponent

      IBSPopulation opponent
      The interaction partner/opponent of this population opponent.getModule()==getModule().getOpponent(). In intra-species interactions opponent==this. Convenience field.
    • logger

      protected Logger logger
      Logger for keeping track of and reporting events and issues.
    • rng

      protected RNGDistribution rng
      The shared random number generator to ensure reproducibility of results.
      See Also:
    • isMultispecies

      protected boolean isMultispecies
      Flag to indicate whether the model entertains multiple species, i.e. nSpecies&gt;1. Convenience field. Reduces calls to Module.
    • populationUpdate

      PopulationUpdate populationUpdate
      The population update.
    • playerUpdate

      PlayerUpdate playerUpdate
      The update type of players. Convenience field.
      See Also:
    • VACANT

      protected int VACANT
      The index of vacant sites or -1 if module does not support vacancies. Convenience field.
      See Also:
    • nTraits

      protected int nTraits
      The number of traits in module. Convenience field.
      See Also:
    • interaction

      protected Geometry interaction
      The geometry of the interaction graph.
    • interGroup

      protected IBSGroup interGroup
      Reference to the interaction group.
    • competition

      protected Geometry competition
      The geometry of the competition graph.
    • compGroup

      protected IBSGroup compGroup
      Reference to the competition/reference/model group.
    • playerScoreAveraged

      protected boolean playerScoreAveraged
      Flag to indicate whether player scores are averaged (default) or accumulated.
      See Also:
    • playerScoring

      protected IBS.ScoringType playerScoring
      Flag to indicate whether scores are reset whenever a player adopts the strategy of another (default) or only if an actual strategy change occurred.
      See Also:
    • migrationType

      protected IBS.MigrationType migrationType
      The type of migration.
    • pMigration

      protected double pMigration
      The probability of migration.
    • distrMigrants

      protected RNGDistribution.Geometric distrMigrants
      The distribution to determine the number of migrants.
    • cProbs

      private double[] cProbs
      Conveninece variable to store cumulative probability distributions for replicator updating.
      See Also:
    • fitness

      protected double[] fitness
      The array of individual fitness values.
      See Also:
    • minFitness

      protected double minFitness
      The absolute minimum fitness in the population. Convenience field used for fitness based picking of focal individuals or for the GUI for scaling graphs.
    • maxFitness

      protected double maxFitness
      The absolute maximum fitness in the population. Convenience field used for fitness based picking of focal individuals or for the GUI for scaling graphs.
    • sumFitness

      protected double sumFitness
      The total fitness of the population. Convenience field used for fitness based picking of focal individuals or for the GUI for scaling graphs.
    • scores

      protected double[] scores
      The array of individual scores.
      See Also:
    • minScore

      protected double minScore
      The absolute minimum score in the population. Even though largely replaced by minFitness in simulations it remains a useful and often more intuitive quantity than fitness when visualizing results in the GUI. Convenience field.
    • maxScore

      protected double maxScore
      The absolute maximum score in the population. Even though largely replaced by maxFitness in simulations it remains a useful and often more intuitive quantity than fitness when visualizing results in the GUI. Convenience field.
    • groupScores

      protected double[] groupScores
      Array to hold scores of individuals during payoff calculations.
    • smallScores

      protected double[] smallScores
      Array to hold scores of individuals during payoff calculations for small groups (not all neighbours).
    • interactions

      protected int[] interactions
      The array of individual interaction counts.
    • tags

      protected double[] tags
      The array of individual tags counts. This can be used to trace ancestry.
    • nMixedInter

      protected int nMixedInter
      Optimization: Number of interactions in well-mixed populations for update rules that take advantage of IBSDPopulation.updateMixedMeanScores(). nMixedInter is calculated ahead of time in check().
    • typeScores

      protected double[] typeScores
      Optimization: the lookup table for scores in well-mixed populations.
    • typeFitness

      protected double[] typeFitness
      Optimization: the lookup table for fitness in well-mixed populations.
    • nPopulation

      protected int nPopulation
      The size of the population. Convenience field to reduce calls to module.
    • map2fit

      protected Map2Fitness map2fit
      The map converting scores to fitness and vice versa. Convenience field to reduce calls to module.
    • adjustScores

      protected boolean adjustScores
      Optimization: Flag to indicate whether adjusting instead of recalculating scores is possible.

      Notes:

      1. Adjusting scores is only feasible if all individuals have a fixed number of interactions. For example, if all individuals always interact with all their neighbours, see IBSGroup.SamplingType.ALL. The only exception are well-mixed populations, Geometry.Type.MEANFIELD. With continuous traits all possible encounters would need to be considered, which is computationally not feasible. In contrast, for discrete traits separate calculations to determine the scores of each trait type are possible.
      2. With random interactions the scores of individuals are based on variable sets of interaction partners and their numbers of interactions may vary.
      See Also:
    • hasLookupTable

      protected boolean hasLookupTable
      Optimization: Flag to indicate whether lookup tables can be used.
    • isNeutral

      protected boolean isNeutral
      Flag to indicate whether dynamic is neutral, i.e. no selection acting on the different traits. The dynamic is considered neutral if maxScore-minScore<1e-8.
    • maxEffScoreIdx

      protected int maxEffScoreIdx
      Optimization: The index of the individual that currently holds the maximum score. This allows more efficient fitness based picking.
      See Also:
    • debugFocal

      protected int debugFocal
      Helper variable to store index of focal individual (birth) that got updated during debug step.
    • debugSame

      protected boolean debugSame
      Helper flag to indicate an actual trait change during debug step.
    • debugModel

      protected int debugModel
      Helper variable to store index of target individual (death) that got updated during debug step.
    • debugModels

      protected int[] debugModels
      Helper variable to store array of indices of individual that served as models during debug step.
    • debugNModels

      protected int debugNModels
      Helper variable to number of individual that served as models during debug step.
    • pRewire

      protected double[] pRewire
      The array containing the probabilities for rewiring links of the interaction and competition graphs.
      See Also:
    • pAddwire

      protected double[] pAddwire
      The array containing the probabilities for adding links to the interaction and competition graphs.
      See Also:
    • isConsistent

      boolean isConsistent
      The flag to indicate whether the state of the IBS model is consistent.
      See Also:
    • consistencyCheckRequested

      boolean consistencyCheckRequested
      The flag to indicate whether consistency checks on the state of the IBS model are requested.
      See Also:
    • syncFraction

      double syncFraction
      The fraction of the population that gets updated in synchronous updates.
  • Constructor Details

    • IBSPopulation

      protected IBSPopulation(EvoLudo engine, Module module)
      Creates a population of individuals for IBS simulations.
      Parameters:
      engine - the pacemaker for running the model
      module - the module that defines the game
  • Method Details

    • getModule

      public Module getModule()
      Gets the module asociated with this population.
      Returns:
      the module associated with this population
    • setOpponentPop

      public void setOpponentPop(IBSPopulation opponent)
      Set the interaction partner/opponent of this population.
      Parameters:
      opponent - the interaction partner/opponent
    • getStatus

      public abstract String getStatus()
      Gets the status of the as a formatted string. This is typically used in the GUI to summarize the progress of the model.
      Returns:
      the status of the population
    • prepareStrategies

      public abstract void prepareStrategies()
      Prior to a synchronous update step the current state must be duplicated in preparation for processing the next step.
      See Also:
    • commitStrategies

      public abstract void commitStrategies()
      After a synchronous update step the new state must be copied back to become the current state.
      See Also:
    • commitStrategyAt

      public abstract void commitStrategyAt(int index)
      The change of a strategy of the player at index is stored in a temporary variable and must be committed before proceeding.
      Parameters:
      index - the index of the player that needs to have its new strategy committed
    • haveSameStrategy

      public abstract boolean haveSameStrategy(int a, int b)
      Check if individuals with index a and index b have the same strategies.
      Parameters:
      a - the index of first individual
      b - the index of second individual
      Returns:
      true if the two individuals have the same strategies
    • isSameStrategy

      public abstract boolean isSameStrategy(int a)
      Check if individual with index a has switched strategies.

      Note: this test is only meaningful before strategy gets committed.

      Parameters:
      a - index of individual
      Returns:
      true if strategy remained the same
      See Also:
    • swapStrategies

      public abstract void swapStrategies(int a, int b)
      Swap strategies of individuals with index a and index b.

      Note: the strategies still need to be committed.

      Parameters:
      a - the index of first individual
      b - the index of second individual
      See Also:
    • playPairGameAt

      public abstract void playPairGameAt(IBSGroup group)
      Play a pairwise interaction with the individuals in group.
      Parameters:
      group - the group of individuals interacting in pairs
    • playGroupGameAt

      public abstract void playGroupGameAt(IBSGroup group)
      Play a group interaction with the individuals in group.
      Parameters:
      group - the group of interacting individuals
    • adjustPairGameScoresAt

      public abstract void adjustPairGameScoresAt(int me)
      Adjusts scores of focal individual with index me and its neighbors after me changed strategy. Only works if adjustScores==true.

      Important: new strategy must not yet have been committed.

      Parameters:
      me - the index of the focal individual
    • yalpGroupGameAt

      public abstract void yalpGroupGameAt(IBSGroup group)
      Counterpart of playGroupGameAt(IBSGroup), playGameAt(int) and/or playGameSyncAt(int). Removes the payoffs of group interactions.
      Parameters:
      group - the interaction group
    • adjustScoreAt

      public abstract void adjustScoreAt(int index, double before, double after)
      Adjust score of individual with index index from before to after and update all applicable helper variables, e.g. sumFitness.

      Important: Use only to adjust scores of individuals that did not change strategy.

      Parameters:
      index - the index of the individual
      before - the score before adjustments
      after - the score after adjustments
    • adjustScoreAt

      public abstract void adjustScoreAt(int index, double adjust)
      Adjust score of individual with index index by adjust and update all applicable helper variables, e.g. sumFitness.
      Parameters:
      index - the index of the individual
      adjust - the score adjustment
    • updatePlayerBestResponse

      public boolean updatePlayerBestResponse(int me, int[] group, int size)
      Best-response update.

      Important:

      1. The array group is untouchable because it may refer to the population structure. Any change would also permanently change the structure.
      2. The best-response update must be implemented in subclasses that override this method. By default throws an error.
      3. Instead of overriding the method, subclasses may remove PlayerUpdate.Type.BEST_RESPONSE from PlayerUpdate#clo.
      Parameters:
      me - the index of individual to update
      group - the array with indices of reference group
      size - the size of the reference group
      Returns:
      true if strategy changed (signaling score needs to be reset)
    • preferredPlayerBest

      public abstract boolean preferredPlayerBest(int me, int best, int sample)
      For deterministic updating with multiple strategies (more than two), it must be specified which strategy is the preferred one.

      Summary: does 'me' prefer 'sample' over 'best'?

      Parameters:
      me - the index of the focal individual
      best - the index of the best performing individual
      sample - the index of the sample type
      Returns:
      true if sample is preferred over best
    • isVacantAt

      public boolean isVacantAt(int index)
      Check if site with index index is occupied by an individual or vacant.

      Note: Assumes that strategies are committed.

      Parameters:
      index - the index of the individual/site to check
      Returns:
      true if site index is vacant
    • becomesVacantAt

      public boolean becomesVacantAt(int index)
      Check if site with index index will become vacant in this time step.

      Note: Assumes that strategies are not committed.

      Parameters:
      index - the index of the individual/site to check
      Returns:
      true if site index will become vacant
    • isMonomorphic

      public boolean isMonomorphic()
      Check if population is monomorphic.

      Note: In models that admit vacant sites this does not imply a homogeneous (or absorbing) state of the population. Without vacant sites monomorphic states are absorbing, at least in the absence of mutations.

      Returns:
      true if population is monomorphic
      See Also:
    • checkConvergence

      public abstract boolean checkConvergence()
      Check if population has converged. By default true if population is monomorphic and no (zero) mutations. However, different implementations may have different criteria for convergence.

      Note: This tends to be less restrictive than reaching an absorbing state. Typically convergence is used as a criterion to abort simulations.

      Returns:
      true if converged.
    • getTraitNameAt

      public abstract String getTraitNameAt(int index)
      Gets the formatted name of the trait of the individual at site index.
      Parameters:
      index - the index of the
      Returns:
      the string describing the trait
    • getInterGroup

      public IBSGroup getInterGroup()
      Gets the interaction group.
      Returns:
      the interaction group
    • getCompGroup

      public IBSGroup getCompGroup()
      Gets the competition/reference/model group.
      Returns:
      the competition/reference/model group
    • getPopulationUpdate

      public PopulationUpdate getPopulationUpdate()
      Gets the population update.
      Returns:
      the population update
    • setPopulationUpdate

      public void setPopulationUpdate(PopulationUpdate populationUpdate)
      Sets the population update.
      Parameters:
      populationUpdate - the population update
    • getTotalFitness

      public double getTotalFitness()
      Gets the total fitness of the population.
      Returns:
      the total fitness
    • doSyncMigration

      public int doSyncMigration()
      Perform synchronous migration.
      Returns:
      the number of migrants
    • doMigration

      public void doMigration()
      Perform asynchronous migration.
    • doDiffusionMigration

      public void doDiffusionMigration()
      Perform diffusion migration, which is implemented as two players swap their locations while leaving their respective neighbourhood structure untouched.
    • updatePlayerSwap

      public void updatePlayerSwap(int a, int b)
      Swap players in locations a and b.
      Parameters:
      a - the index of the first individual
      b - the index of the second individual
    • doBirthDeathMigration

      public void doBirthDeathMigration()
      Perform a birth-death migration, where a focal individual (selected proportional to fitness) produces a migrant offspring, which replaces another member of the population uniformly at random.

      Note: This is almost identical to Moran (birth-death) updating in well-mixed populations (only victim and migrant always different)

    • doDeathBirthMigration

      public void doDeathBirthMigration()
      Perform a death-birth migration, where a member of the population (selected uniformly at random) dies and the remaining individuals compete to repopulate the vacant site. One competitor succeeds with a probability proportional proportional to fitness.

      Note: This is almost identical to Moran (birth-death) updating in well-mixed populations

    • pickFocalSite

      public int pickFocalSite()
      Draws the index of a site in the population uniformly at random, irrespective of whether it is occupied or not.
      Returns:
      the index of the picked site
    • pickFocalSite

      public int pickFocalSite(int excl)
      Draws the index of a site in the population uniformly at random, irrespective of whether it is occupied or not.
      Parameters:
      excl - the index of the excluded site
      Returns:
      the index of the picked site
    • pickFocalIndividual

      public int pickFocalIndividual()
      Draws the index of a individual of the population uniformly at random. Vacant sites are skipped. In the absence of vacant sites this is equivalent to pickFocalSite().

      Important: This method is highly time sensitive. Any optimization effort is worth making.

      Returns:
      the index of the picked individual
    • pickFocal

      private int pickFocal(int excl)
      Pick a focal individual uniformly at random but excluding the individual with index excl. Helper method.
      Parameters:
      excl - the index of the excluded individual
      Returns:
      the index of the picked individual
    • pickFocalIndividual

      public int pickFocalIndividual(int excl)
      Draws the index of a individual of the population uniformly at random but excluding the individual with index excl. Vacant sites are skipped.

      Important: This method is highly time sensitive. Any optimization effort is worth making.

      Parameters:
      excl - the index of the excluded individual
      Returns:
      the index of the picked individual
    • pickFitFocalIndividual

      public int pickFitFocalIndividual()
      Draws the index of a member of the population with a probability proportional to fitness.

      Note: scores must be ≥0

      Important: This method is highly time sensitive. Any optimization effort is worth making.

      Discussions/extensions:

      1. Should picking include vacant sites, or not, or selectable?
      2. Currently vacant sites are excluded for fitness based picking but not for random picking.
      3. Perform more systematic analysis regarding the threshold population size (currently nPopulation &geq; 100) for the two Gillespie methods sometimes 4*nPopulation trials are needed, which seems too much...
      Returns:
      the index of the picked member
    • pickFitFocalIndividual

      public int pickFitFocalIndividual(int excl)
      Draws the index of a member of the population with a probability proportional to fitness but excluding the individual with the index excl.

      Note: scores must be ≥0

      Important: This method is highly time sensitive. Any optimization effort is worth making.

      Parameters:
      excl - the index of the member that should be excluded from picking
      Returns:
      the index of the picked member
    • second

      private double second(int excl)
      Find the second highest score.
      Parameters:
      excl - the index of the member that should be excluded from picking
      Returns:
      the second highest score
    • debugScores

      protected void debugScores(double hit)
      Log report if picking failed to shed better light on what might be the root cause for the failure.
      Parameters:
      hit - the 'left-over fitness' from picking
    • pickFitNeighborAt

      protected int pickFitNeighborAt(int me)
      Pick a neighbour of the focal individual me with probability proportional to their fitness.
      Parameters:
      me - the index of the focal individual
      Returns:
      the index of a neighbour
    • pickFitNeighborAt

      protected int pickFitNeighborAt(int me, boolean withSelf)
      Pick a neighbour of the focal individual me with probability proportional to their fitness. If the flag withSelf==true then the focal individual is included in the picking.
      Parameters:
      me - the index of the focal individual
      withSelf - the flag whether to include self
      Returns:
      the index of a neighbour
    • pickNeutralNeighbourAt

      private int pickNeutralNeighbourAt(int me, boolean withSelf)
      Helper method to do picking under neutral conditions (no or negligible fitness differences). In well-mixed populations the picking includes the focal individual if withSelf==true. Otherwise picking never includes me.
      Parameters:
      me - the index of the focal individual
      withSelf - the flag whether to include self
      Returns:
      the index of a neighbour
    • pickNeighborSiteAt

      protected int pickNeighborSiteAt(int me)
      Picks a neighbouring site of the focal individual me uniformly at random. This is where the focal individual places its offspring in the Moran process under Birth-death updating. The original Moran process refers to well-mixed (or mean-field) populations where the offspring can replace its parent (albeit with a small probability of \(o(1/N)\), where \(N\) is the population size). In contrast in the spatial Moran process the offspring replaces a neighbour of the parent.

      Notes:

      1. The parent is never picked.
      2. Vacant sites are picked with the same probability as occupied ones.
      Parameters:
      me - the index of the focal individual
      Returns:
      the index of a neighbour
      See Also:
    • updateFromModelAt

      public void updateFromModelAt(int me, int you)
      Update individual with index me and adopt the strategy of individual with index you.

      Note: method must be subclassed to deal with different data types of strategies but should also include a call to super.

      Parameters:
      me - the index of the focal individual
      you - the index of the model individual to adopt strategy from
      See Also:
    • playGameSyncAt

      public void playGameSyncAt(int me)
      Update the score of individual me.

      After initialization and for synchronized population updating this method is invoked (rather than playGameAt(int)). The synchronous flag simply indicates that all players are going to be updated. For directed graphs this implies that incoming and outgoing links do not need to be treated separately because every outgoing link corresponds to an incoming link of another node.

      Parameters:
      me - the index of the focal individual
    • playGameAt

      public void playGameAt(int me)
      Update the score of individual me. This method is called if adjusting scores is not an option. If site me is vacant do nothing.
      Parameters:
      me - the index of the focal individual
      See Also:
    • adjustGameScoresAt

      public void adjustGameScoresAt(int me)
      Adjust scores of focal player me and its neighbours (interaction partners).

      Requirements/notes:

      1. This optimized method is only applicable if IBSGroup.SamplingType.ALL is true and not Geometry.Type.MEANFIELD, i.e. if the interaction group includes all neighbors but not all other members of the population.
      2. For pairwise interactions more efficient approaches are possible but those require direct access to the stratgies and are hence delegated to subclasses.
      Parameters:
      me - the index of the focal individual
      See Also:
    • updateScoreAt

      public void updateScoreAt(int index, double newscore)
      Update the score of the individual with index index by adding newscore from single interaction.
      Parameters:
      index - the index of the individual
      newscore - the new score of the individual
    • updateScoreAt

      public void updateScoreAt(int index, double newscore, int incr)
      Update the score of the individual with index index by adding (incr &gt; 0 or removing, incr &lt; 0) newscore as the result of incr interactions.

      Important:

      1. Strategies are already committed when adding scores (incr>0).
      2. Strategies are not committed when removing scores (incr<0).
      3. 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).
      4. resetScoreAt(int) deals with the focal site.
      Parameters:
      index - the index of the individual
      newscore - score/payoff to add (incr>0) or subtract (incr<0)
      incr - number of interactions
    • updateFitnessAt

      public void updateFitnessAt(int idx)
      Update the fitness of the individual with index idx by mapping its current score. Keeps track of sumFitness.

      Note: If sumFitness decreases dramatically rounding errors become an issue. More specifically, if sumFitness is reduced to half or less, recalculate from scratch.

      Parameters:
      idx - the index of the individual
    • setScoreAt

      public void setScoreAt(int index, double newscore, int inter)
      Sets the score of individual with index index to newscore as the result of inter interactions. Also derives the corresponding fitness and adjusts sumFitness.

      Note: Assumes that resetScores() was called earlier (or at least resetScoreAt(int) for those sites that setScoreAt(int) is used for updating their score).

      Parameters:
      index - the index of the individual
      newscore - new score to set
      inter - number of interactions
    • removeScoreAt

      public void removeScoreAt(int index, double nilscore)
      Removes the score nilscore based on a single interaction from the individual with index index.
      Parameters:
      index - the index of the individual
      nilscore - the score to remove
      See Also:
    • removeScoreAt

      public void removeScoreAt(int index, double nilscore, int incr)
      Removes the score nilscore based on incr interactions from the individual with index index.
      Parameters:
      index - the index of the individual
      nilscore - the score to remove
      incr - the number of interactions to remove
      See Also:
    • resetScoreAt

      public void resetScoreAt(int index)
      Reset score of individual at index index.

      Important: Strategies must not yet have been committed.

      Discussions/extensions:

      Revise the entire strategy updating procedure: it's inefficient to first reset scores then update strategies then update score...
      Parameters:
      index - the index of the individual
    • swapScoresAt

      public void swapScoresAt(int idxa, int idxb)
      Swap the scores (and fitness) of individuals with indices idxa and idxb.
      Parameters:
      idxa - the index of the first individual
      idxb - the index of the second individual
    • resetScores

      public void resetScores()
      Reset scores and fitness of all individuals to zero.
    • updateScores

      public void updateScores()
      Update the scores of all individuals in the population.
    • getScoreAt

      public double getScoreAt(int idx)
      Gets the score of the individual with index idx.
      Parameters:
      idx - the index of the individual
      Returns:
      the score of the individual
    • getFitnessAt

      public double getFitnessAt(int idx)
      Gets the fitness of the individual with index idx.
      Parameters:
      idx - the index of the individual
      Returns:
      the fitness of the individual
    • updateEffScoreRange

      protected boolean updateEffScoreRange(int index, double before, double after)
      Keep track of highest score through a reference to the corresponding individual.

      Discussions/extensions:

      1. Keeping track of the lowest performing individual is very costly because the poor performers are much more likely to get updated. In contrast, the maximum performer is least likely to get replaced. For example, in cSD with a well-mixed population of 10'000 spends >80% of CPU time hunting down the least performing individual! Besides, the minimum score is never used. The maximum score is only used for global, fitness based selection such as the Birth-death process. (room for optimization?)
      2. For synchronous updates this method is not only wasteful but problematic because sites that are later updated experience different conditions.
      3. For constant fitness (maxEffScoreIdx &lt; 0) tracking the maximum is not needed.
      4. if (isVacantAt(index)) {...} is only executed if after == before, i.e. the code is almost dead... suspicious or ingenious?!
      Parameters:
      index - the index of the individual
      before - the score before the update
      after - the score after the update
      Returns:
      true if effective range of payoffs has changed (or, more precisely, if the reference individual has changed); false otherwise.
    • setMaxEffScoreIdx

      protected void setMaxEffScoreIdx()
      Find the index of the individual with the highest score.
    • step

      public double step()
      Perform a single IBS step, i.e. update one individual for asynchronous updates or once the entire population for synchronous updates.

      Discussions/extensions

      1. Review migration. Exclusively used in Demes2x2. Should probably be treated as an independent event, in particular independent of population or player updates
      2. Implement Wright-Fisher update.
      3. How to scale realtime with multiple populations? How to define a generation if population sizes can vary?
      4. updatePlayerEcology() returns time increment in realtime units. Everyone else does fine without...
      Returns:
      the elapsed time in realtime units
    • mutate

      public double mutate()
      Perform a mutation event. The focal individual is picked uniformly at random.
      Returns:
      the elapsed time in realtime units
    • mutateAt

      public abstract double mutateAt(int focal)
      Mutate the strategy of the focal individual with index focal. The mutated strategy is committed and the scores updated.
      Parameters:
      focal - the index of the focal individual
      Returns:
      the elapsed time in realtime units
    • maybeMutateAt

      protected abstract boolean maybeMutateAt(int focal, boolean switched)
      Consider mutating the trait of the focal individual with index focal. The strategy of the focal individual is stored in the array strategies unless the focal individual switched strategy. In that case the current strategy is stored in the array strategyScratch.

      Important: The trait is not committed regardless of whether a mutation occurred.

      Parameters:
      focal - the index of the focal individual
      switched - true if the focal individual switched strategy
      Returns:
      true if the trait of the focal individual changed
    • maybeMutateMoran

      protected abstract void maybeMutateMoran(int source, int dest)
      Consider mutating the trait of the parent individual with index source. The mutated strategy is committed and the scores updated.
      Parameters:
      source - the index of the parent individual
      dest - the index of the location for the offspring placement
    • debugUpdatePopulationAt

      public void debugUpdatePopulationAt(int focal)
      Update focal individual with index focal for debugging.

      Notes:

      • Must remain in sync with population updates in IBS and step().
      • For debugging only; time not advanced.
      Parameters:
      focal - the index of the individual to update
    • debugMarkChange

      protected void debugMarkChange()
      Override in subclass for example to mark those individuals in the GUI that were involved in the debug step.
    • formatInfoAt

      private String formatInfoAt(int focal, int model)
      Helper method to format information about updating the focal individual at index focal using the model individual with index model.
      Parameters:
      focal - the index of the focal individual
      model - the index of the model individual
      Returns:
      the formatted information
    • updatePlayerAsync

      protected void updatePlayerAsync()
      Perform a single, asynchronous update of the strategy of a randomly selected individual.
    • updatePlayerAsyncAt

      public void updatePlayerAsyncAt(int me)
      Update the strategy of the focal individual with index me.
      Parameters:
      me - the index of the focal individual
    • updateScoreAt

      protected void updateScoreAt(int me, boolean switched)
      Update the scores of the focal individual with index me.
      Parameters:
      me - the index of the focal individual
      switched - true if the focal switched strategy
    • updatePlayerMoranBirthDeath

      public void updatePlayerMoranBirthDeath()
      Perform a single, Moran (Birth-death) update for a random individual selected with a probability proportional to fitness. This is the original Moran process where the offspring can replace the parent in well-mixed populations. For structured populations this corresponds to the spatial Moran process with Bd updating in Ohtsuki et al. Nature 2005.
      See Also:
    • updatePlayerMoranBirthDeathAt

      protected void updatePlayerMoranBirthDeathAt(int parent)
      Perform a Moran (Birth-death) update for the focal individual with index parent to produce a clonal offspring and replace one of the parent's neighbours selected uniformly at random. This is the original Moran process where the offspring can replace the parent in well-mixed populations.
      Parameters:
      parent - the index of the parent
    • updatePlayerMoranDeathBirth

      public void updatePlayerMoranDeathBirth()
      Perform a single Moran (death-Birth) update for a site selected uniformly at random. This corresponds to the spatial Moran process with dB updating in Ohtsuki et al. Nature 2005.
      See Also:
    • updatePlayerMoranDeathBirthAt

      protected void updatePlayerMoranDeathBirthAt(int vacant)
      Perform a single Moran (death-Birth) update for the focal site with index vacant. One of its (incoming) neighbours succeeds, with a probability proportional to its fitness, in producing a clonal offspring and placing it at site vacant.
      Parameters:
      vacant - the index of the vacant site
    • updatePlayerMoranImitate

      public void updatePlayerMoranImitate()
      Perform a single, Moran (imitate) update for a site selected uniformly at random. This corresponds to the imitate strategy in Ohtsuki et al. Nature 2005.
      See Also:
    • updatePlayerMoranImitateAt

      protected void updatePlayerMoranImitateAt(int imitator)
      Update the focal individual with index imitator by comparing its own payoff and those of its neighbors. The focal individual imitates the strategy of a neighbour (or keeps its own) with a probability proportional to the corresponding individual's fitness (including its own).
      Parameters:
      imitator - the index of the individual that reassesses its strategy
    • migrateMoran

      protected void migrateMoran(int source, int dest)
      Perform a single Moran update for the reproducing node with index source and the node that gets replaced with index dest. The three Moran variants (death-Birth, Birth-death and imitate) differ only in their selection of the individuals source and dest and then call this method, migrateMoran(int, int).

      Note: Moran optimizations for discrete strategies require access to this method.

      Parameters:
      source - the index of the parent node
      dest - the index of the node where the offspring is placed
      See Also:
    • updatePlayerEcology

      public double updatePlayerEcology()
      Perform a single ecological update of an individual selected uniformly at random.
      Returns:
      real-time increment
    • updatePlayerEcologyAt

      protected double updatePlayerEcologyAt(int index)
      Perform a single ecological update of the site with index index.

      Important: No default implementation is possible. Modules with ecological updates need to subclass IBSPopulation and provide their own implementations.

      Parameters:
      index - the index of the focal site
      Returns:
      real-time increment
    • updatePlayerAt

      public boolean updatePlayerAt(int me)
      Perform a single update of the individual with index me. Returns true if the individual adopted the trait of the reference individual. Does not imply that the trait changed in discrete modules. Whether the individuals score is reset depends on playerScoring
      Parameters:
      me - the index of the focal individual
      Returns:
      true if trait of reference adopted
      See Also:
    • updatePlayerAt

      private boolean updatePlayerAt(int me, int[] refGroup, int rGroupSize)
      Perform a single update of the individual with index me using the rGroupSize models in the array refGroup. Returns true if the individual changed its strategy to signal that the focal individual's score will need to be reset.
      Parameters:
      me - the index of the focal individual
      refGroup - the group of reference individuals
      rGroupSize - the number of reference individuals
      Returns:
      true if trait of reference adopted
      See Also:
    • updatePlayerBest

      protected boolean updatePlayerBest(int me, int[] refGroup, int rGroupSize)
      Updates the focal individual with index me by adopting the strategy of the best performing reference individual among the rGroupSize models in the array refGroup. Returns true if the individual adopted the trait of the reference individual. Does not imply that the trait changed in discrete modules. Whether the individuals score is reset depends on playerScoring.

      Notes:

      1. If the scores of two reference individuals tie but exceed the focal individual's score, expert advice is needed.
      2. If the focal individual's score is highest but ties with one or more reference individuals the focal individual keeps its strategy.
      3. For the best update it does not matter whether scores are averaged or accumulated.
      Parameters:
      me - the index of the focal individual
      refGroup - the group of reference individuals
      rGroupSize - the number of reference individuals
      Returns:
      true if trait of reference adopted
      See Also:
    • updatePlayerBestHalf

      protected boolean updatePlayerBestHalf(int me, int[] refGroup, int rGroupSize)
      Updates the focal individual with index me by adopting the strategy of the best performing reference individual among the the rGroupSize models in the array refGroup. If the scores of two (or more) references or the score of the focal individual and one (or more) reference(s) tie, then a coin toss decides which strategy to keep/adopt. Returns true if the individual adopted the trait of the reference individual. Does not imply that the trait changed in discrete modules. Whether the individuals score is reset depends on playerScoring.

      Notes:

      For the best update it does not matter whether scores are averaged or accumulated.
      Parameters:
      me - the index of the focal individual
      refGroup - the group of reference individuals
      rGroupSize - the number of reference individuals
      Returns:
      true if trait of reference adopted
      See Also:
    • updateProportionalAbs

      protected boolean updateProportionalAbs(int me, int[] refGroup, int rGroupSize)
      Updates the focal individual with index me by adopting the strategy of one reference individual (including itself) among the the rGroupSize models in the array refGroup with a probability proportional to their scores. Returns true if the individual adopted the trait of the reference individual. Does not imply that the trait changed in discrete modules. Whether the individuals score is reset depends on playerScoring.
      Parameters:
      me - the index of the focal individual
      refGroup - the group of reference individuals
      rGroupSize - the number of reference individuals
      Returns:
      true if trait of reference adopted
      See Also:
    • updateReplicatorPlus

      protected boolean updateReplicatorPlus(int me, int[] refGroup, int rGroupSize)
      Updates the focal individual with index me by adopting the strategy of one reference individual among the the rGroupSize models in the array refGroup. The focal individual \(i\) imitates the strategy of a better performing reference individual \(j\) with a probability proportional to the difference in fitness: \[p_{i\to j} = \frac{(f_i-f_j)_+}\alpha,\] where \(\alpha\) denotes a normalization factor to ensure \(p_{i\to j}\in[0,1]\). Returns true if the individual adopted the trait of the reference individual. Does not imply that the trait changed in discrete modules. Whether the individuals score is reset depends on playerScoring.
      Parameters:
      me - the index of the focal individual
      refGroup - the group of reference individuals
      rGroupSize - the number of reference individuals
      Returns:
      true if trait of reference adopted
      See Also:
    • updateReplicatorHalf

      protected boolean updateReplicatorHalf(int me, int[] refGroup, int rGroupSize)
      Updates the focal individual with index me by adopting the strategy of one reference individual among the the rGroupSize models in the array refGroup. The focal individual \(i\) imitates the strategy of a reference individual \(j\) with a probability proportional to the difference in fitness: \[p_{i\to j} = \frac{f_i-f_j}\alpha\] where \(\alpha\) denotes a normalization factor to ensure \(p_{i\to j}\in[0,1]\). This corresponds to the microscopic updating which recovers the standard replicator equation in the continuum limit. Returns true if the individual adopted the trait of the reference individual. Does not imply that the trait changed in discrete modules. Whether the individuals score is reset depends on playerScoring.
      Parameters:
      me - the index of the focal individual
      refGroup - the group of reference individuals
      rGroupSize - the number of reference individuals
      Returns:
      true if trait of reference adopted
      See Also:
    • updateReplicator

      private boolean updateReplicator(int me, int[] refGroup, int rGroupSize, boolean betterOnly)
      Helper method for replicator type updates. Returns true if the individual adopted the trait of the reference individual. Does not imply that the trait changed in discrete modules. Whether the individuals score is reset depends on playerScoring.
      Parameters:
      me - the index of the focal individual
      refGroup - the group of reference individuals
      rGroupSize - the number of reference individuals
      betterOnly - the flag to indicate whether only better performing reference individuals are considered
      Returns:
      true if trait of reference adopted
      See Also:
    • updateThermal

      protected boolean updateThermal(int me, int[] refGroup, int rGroupSize)
      Updates the focal individual with index me by adopting the strategy of one reference individual among the the rGroupSize models in the array refGroup. The focal individual \(i\) imitates the strategy of a reference individual \(j\) with a probability proportional to the difference in fitness: \[p_{i\to j} = \frac1{1+\exp(-(f_i-f_j)/T)}\] where \(T\) denotes the temperature (or noise) in adopting a strategy. In the limit \(T\to\infty\) imitation reduces to a coin toss, \(p_{i\to j}=1/2\). In contrast, for \(T\to 0\) it converges to the step-function, with \(\Theta(x)=1\) for positive \(x\), \(\Theta(x)=0\) for \(x\) negative and \(\Theta(0)=1/2\). Returns true if the individual adopted the trait of the reference individual. Does not imply that the trait changed in discrete modules. Whether the individuals score is reset depends on playerScoring.
      Parameters:
      me - the index of the focal individual
      refGroup - the group of reference individuals
      rGroupSize - the number of reference individuals
      Returns:
      true if trait of reference adopted
      See Also:
    • getMinScore

      public double getMinScore()
      Returns the minimum score min in this population, taking the population structure and payoff accounting into account.
      Returns:
      the processed minimum score
    • getMaxScore

      public double getMaxScore()
      Returns the maximum score min in this population, taking the population structure and payoff accounting into account.
      Returns:
      the processed maximum score
    • processScore

      protected double processScore(double score, boolean max)
      Process the accumulated score in this population, taking the updating into account.
      Parameters:
      score - the minimum or maximum score
      max - true if score is maximum
      Returns:
      the processed extremal score
    • updateMinMaxScores

      public void updateMinMaxScores()
      Retrieve and store extremal scores and fitnesses to reduce calls to Module.
    • check

      public boolean check()
      Check all model parameters for consistency and adjust if necessary (and feasible). Returns true if adjustments require a reset. Free memory if possible and request a reset if new memory needs to be allocated.
      Returns:
      true if reset is required
      See Also:
    • setRewire

      public void setRewire(double[] rewire)
      Set the probabilities for rewiring links of the interaction and competition graphs.
      Parameters:
      rewire - the array double[] {<interaction>, <competition>}
    • setAddwire

      public void setAddwire(double[] addwire)
      Set the probabilities for adding links to the interaction and competition graphs.
      Parameters:
      addwire - the array double[] {<interaction>, <competition>}
    • doAdjustScores

      protected abstract boolean doAdjustScores()
      Check if scores can be adjusted rather than recalculated after an individual changed its strategy. This requires that individuals interact with all their neighbours and that the structure of the population is not well-mixed. Some implementations may be able to extend adjustments to other structures. For example, adjusting scores is feasible in well-mixed populations for discrete traits/strategies.

      Requirements:

      Group.SAMPLING_ALL
      individuals need to be interacting with all their neighbours (not just a randomly selected subset).
      Geometry.MEANFIELD
      interactions with everyone are not feasible (impossible to model efficiently), in general, for unstructured populations (subclasses can do better, e.g. for discrete strategies it is possible, see IBSDPopulation.doAdjustScores()).
      playerScoreReset
      if scores are reset whenever an individual adopts the strategy of another (regardless of whether an actual strategy change occurred) then the expected number of interactions of each individual remains constant over time (even though the interaction count may differ for individuals on heterogeneous structures).
      Returns:
      true if adjusting scores is feasible
      See Also:
    • reset

      public void reset()
      Reset the model. All parameters must be consistent at this point. Allocate memory and initialize the interaction and competition structures. If structures include random elements, e.g. random regular graphs, a new structure is generated. Generate initial configuration. Subclasses must override this method to allocate memory for the strategies and call super.
      See Also:
    • init

      public void init()
      Initialize the model. All parameters must be consistent. Subclasses must override this method to generate the initial strategy configuration and call super.

      Note: Initialization leaves the interaction and competition structures untouched

      See Also:
    • setConsistencyCheck

      public void setConsistencyCheck(boolean check)
      Enable consistency checks of the state of the IBS model. Never use in production.
      Parameters:
      check - true to request consistency checks
    • isConsistent

      public void isConsistent()
      Convenience method during development to perform a number of consistency checks of the current state. Once an inconsistency is found there is no need to keep looking and no further checks are performed.

      Execution time is of little concern here. Never use in the final simulation code.

    • resetStrategies

      public void resetStrategies()
      Reset all strategies in preparation of the next update step. Simply an opportunity for customizations in subclasses.
    • getInitialTraits

      public abstract void getInitialTraits(double[] init)
      Returns the initial trait(s) of this population in the array init. Used by GUI to visualize the initial state of this IBS model.
      Parameters:
      init - the array for returning the initial trait values
      See Also:
    • getNMean

      public int getNMean()
      Return the number of mean values for this population (for traits or fitness).

      Note: The number of mean traits in a model may differ from the number of traits in the corresponding module. This is the case for example for Geometry.Type.SQUARE_NEUMANN_2ND with two disjoint interaction or competition graphs.

      Returns:
      the number of mean values
      See Also:
    • getMeanTraits

      public abstract void getMeanTraits(double[] mean)
      Returns the mean trait(s) of this population in the array mean. Used by GUI to visualize the current state of this IBS model.
      Parameters:
      mean - the array for returning the trait values
      See Also:
    • getTraitData

      public abstract <T> void getTraitData(T[] colors, ColorMap<T> colorMap)
      Returns the traits of all individuals in this population coded as colors in the array colors using the map colorMap. 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 or PopGraph3D).
      Type Parameters:
      T - the type of color data (String or MeshLambertMaterial for GWT and Color for JRE).
      Parameters:
      colors - the array where the colors of all nodes are stored
      colorMap - the map that converts traits into colors
    • getMeanFitness

      public abstract void getMeanFitness(double[] mean)
      Returns the mean fitness of this population in the array mean. Used by GUI to visualize the current state of this IBS model. Returns true if data point belongs to the same time series and false if a new series was started through init() or reset().
      Parameters:
      mean - the array for storing the mean fitness values
      See Also:
    • getFitnessData

      public <T> void getFitnessData(T[] colors, ColorMap.Gradient1D<T> colorMap)
      Returns the fitness of all individuals in this population coded as colors in the array colors using the map colorMap. 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 or PopGraph3D).
      Type Parameters:
      T - the type of color data (String or MeshLambertMaterial for GWT and Color for JRE).
      Parameters:
      colors - the array where the colors of all nodes are stored
      colorMap - the map that converts traits into colors
    • getFitnessHistogramData

      public void getFitnessHistogramData(double[][] bins)
      Generates a histogram of the fitness distribution in this population. The result is returned in the array bins.

      Notes:

      1. bins is a 2D array because discrete models generate histograms for each trait separately.
      2. By default generate a histogram of the scores in bins[0].
      3. Consider moving to IBSDPopulation and IBSCPopulation with arguments bins[][] and bins[], respectively.
      Parameters:
      bins - the 2D array to store the histogram(s)
    • getScores

      public String getScores(int digits)
      Gets the scores of all individuals with precision digits. Scores of vacant sites are reported as 0d/0d.
      Parameters:
      digits - the number of digits for the scores
      Returns:
      the formatted scores
    • getScoreNameAt

      public String getScoreNameAt(int idx)
      Gets the formatted score of the individual with index idx.
      Parameters:
      idx - the index of the individual
      Returns:
      the formatted score
    • getFitness

      public String getFitness(int digits)
      Gets the fitness of all individuals with precision digits. Fitness of vacant sites are reported as 0d/0d.
      Parameters:
      digits - the number of digits for the scores
      Returns:
      the formatted fitness
    • getFitnessNameAt

      public String getFitnessNameAt(int idx, boolean pretty)
      Gets the formatted fitness of the individual with index idx as a string. If the flag pretty is set the formatting is prettyfied by replacing the exponent E in scientific notation to a power of 10.
      Parameters:
      idx - the index of the individual
      pretty - flag to prettify formatting
      Returns:
      the formatted fitness
    • getFitnessNameAt

      public String getFitnessNameAt(int idx)
      Gets the formatted and prettyfied fitness of the individual with index idx as a string.
      Parameters:
      idx - the index of the individual
      Returns:
      the formatted fitness
    • getInteractionsAt

      public int getInteractionsAt(int idx)
      Gets the number of interactions of the individual with index idx. Returns -1 if site idx is vacant or fitness is static, i.e. not based on interactions.
      Parameters:
      idx - the index of the individual
      Returns:
      the number of interactions
    • getTags

      public double[] getTags(double[] mem)
      Copies the tags of all individuals in the population and returns them in the array mem.
      Parameters:
      mem - the array to copy the tags into
      Returns:
      the array of tags
    • getTagData

      public <T> void getTagData(T[] colors, ColorMap<T> colorMap)
      Returns the tags of all individuals in this population coded as colors in the array colors using the map colorMap. 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 or PopGraph3D).
      Type Parameters:
      T - the type of color data (String or MeshLambertMaterial for GWT and Color for JRE).
      Parameters:
      colors - the array where the colors of all nodes are stored
      colorMap - the map that converts tags into colors
    • getTagAt

      public double getTagAt(int idx)
      Gets the tag of the individual with index idx.
      Parameters:
      idx - the index of the individual
      Returns:
      the tag number
    • getTagNameAt

      public String getTagNameAt(int idx)
      Gets the formatted tag of the individual with index idx as string.
      Parameters:
      idx - the index of the individual
      Returns:
      the tag as a string
    • setTagAt

      public boolean setTagAt(int idx, double tag)
      Sets the tag of the individual with index idx.
      Parameters:
      idx - the index of the individual
      tag - the new tag of the individual
      Returns:
      true if the tag changed
    • getPopulationSize

      public int getPopulationSize()
      Gets current population size. For most models with fixed population sizes this simply returns nPopulation. Ecological models with variable population sizes must override this method to return the actual population size.
      Returns:
      current population size
    • setSyncFraction

      public void setSyncFraction(double sync)
      Set the fraction of the population that gets updated in synchronous updates.
      Parameters:
      sync - the fraction that gets updated
    • getSyncFraction

      public double getSyncFraction()
      Get the fraction of the population that gets updated in synchronous updates.
      Returns:
      the fraction that gets updated
    • setMigrationType

      public void setMigrationType(IBS.MigrationType type)
      Sets the type of migrations to type.
      Parameters:
      type - the new type of migrations
    • getMigrationType

      public IBS.MigrationType getMigrationType()
      Gets the type of migrations.
      Returns:
      the type of migrations
    • setMigrationProb

      public void setMigrationProb(double aValue)
      Sets the migration probability to aValue.
      Parameters:
      aValue - the new migration probability
    • getMigrationProb

      public double getMigrationProb()
      Gets the migration probability.
      Returns:
      the migration probability
    • getInteractionGeometry

      public Geometry getInteractionGeometry()
      Gets the structure of interactions.
      Returns:
      the interaction structure
    • createInteractionGeometry

      public Geometry createInteractionGeometry()
      Creates a new instance of the interaction structure, if needed.
      Returns:
      the interaction structure
    • getCompetitionGeometry

      public Geometry getCompetitionGeometry()
      Gets the structure of competition or imitations.
      Returns:
      the competition structure
    • createCompetitionGeometry

      public Geometry createCompetitionGeometry()
      Creates a new instance of the competition or imitation structure, if needed.
      Returns:
      the competition structure
    • setPlayerScoring

      public void setPlayerScoring(IBS.ScoringType type)
      Sets the type for managing scores of individuals.
      Parameters:
      type - the type for managing scores
      See Also:
    • getPlayerScoring

      public IBS.ScoringType getPlayerScoring()
      Gets the type for managing scores of individuals.
      Returns:
      true if scores are always reset
      See Also:
    • setPlayerScoreAveraged

      public void setPlayerScoreAveraged(boolean aver)
      Sets whether scores of individuals are averaged over multiple interactions or accumulated.
      Parameters:
      aver - the flag to indicate whether scores are averaged
    • getPlayerScoreAveraged

      public boolean getPlayerScoreAveraged()
      Gets whether player scores are averaged (as opposed to accumulated).
      Returns:
      true if player scores are averaged.
    • parseGeometry

      public boolean parseGeometry(Geometry geom, String arg)
      Provide opportunity/hook for subclasses to introduce new geometries.
      Parameters:
      geom - the current empty/uninitialized geometry
      arg - the commandline argument
      Returns:
      true if parsing was successful
      See Also:
    • checkGeometry

      public boolean checkGeometry(Geometry geom)
      Provide opportunity/hook for subclasses to introduce new geometries.
      Parameters:
      geom - the geometry to check
      Returns:
      true if checks were successful
      See Also:
    • generateGeometry

      public boolean generateGeometry(Geometry geom)
      Provide opportunity/hook for subclasses to introduce new geometries.
      Parameters:
      geom - the geometry to initialize
      Returns:
      true if generation of structure was successful
      See Also:
    • mouseHitNode

      public boolean mouseHitNode(int hit)
      Called from GUI if node/individual with index idx received a mouse click or tap.
      Parameters:
      hit - the index of the node
      Returns:
      false if no actions taken
    • mouseHitNode

      public boolean mouseHitNode(int hit, boolean alt)
      Called from GUI if node/individual with index idx received a mouse click or tap and indicates whether the alt-key had been pressed.
      Parameters:
      hit - the index of the node
      alt - true if the alt-key was pressed
      Returns:
      false if no actions taken
    • encodeFitness

      public void encodeFitness(StringBuilder plist)
      Encode the fitness of all individuals in the IBS model in a plist inspired XML string.
      Parameters:
      plist - the StringBuilder to write the encoded state to
      See Also:
    • restoreFitness

      public boolean restoreFitness(Plist plist)
      Restore the fitness of all individuals encoded in the plist inspired map of key, value-pairs.
      Parameters:
      plist - the map of key, value-pairs
      Returns:
      true if successful
      See Also:
    • encodeInteractions

      public void encodeInteractions(StringBuilder plist)
      Encode the interactions of all individuals in the IBS model in a plist inspired XML string.
      Parameters:
      plist - the StringBuilder to write the encoded state to
      See Also:
    • restoreInteractions

      public boolean restoreInteractions(Plist plist)
      Restore the interactions of all individuals encoded in the plist inspired map of key, value-pairs.
      Parameters:
      plist - the map of key, value-pairs
      Returns:
      true if successful
      See Also:
    • encodeStrategies

      public abstract void encodeStrategies(StringBuilder plist)
      Encode the strategies of all individuals in the IBS model in a plist inspired XML string.
      Parameters:
      plist - the StringBuilder to write the encoded state to
      See Also:
    • restoreStrategies

      public abstract boolean restoreStrategies(Plist plist)
      Restore the strategies of all individuals encoded in the plist inspired map of key, value-pairs.
      Parameters:
      plist - the map of key, value-pairs
      Returns:
      true if successful
      See Also:
    • encodeGeometry

      public void encodeGeometry(StringBuilder plist)
      Encode the interaction and competition structures of the IBS model in a plist inspired XML string.
      Parameters:
      plist - the StringBuilder to write the encoded state to
      See Also:
    • restoreGeometry

      public boolean restoreGeometry(Plist plist)
      Restore the interaction and competition structures encoded in the plist inspired map of key, value-pairs.
      Parameters:
      plist - the map of key, value-pairs
      Returns:
      true if successful
      See Also:
    • srandom

      public void srandom(long s)
      Set the seed of the random number generator for competition simulation runs.
      Parameters:
      s - the seed for random number generator
    • random0N

      public int random0N(int n)
      Draw a uniformly distributed random integer number from the closed interval [0, n].
      Parameters:
      n - the upper limit of interval (inclusive)
      Returns:
      the random integer number in [0, n].
    • random0n

      public int random0n(int n)
      Draw a uniformly distributed random integer number from the semi-closed interval [0, n).
      Parameters:
      n - the upper limit of interval (exclusive)
      Returns:
      the random integer number in [0, n).
    • random01

      public double random01()
      Draw a uniformly distributed random double from the semi-closed interval [0, 1) with 32bit resolution. This is the default.
      Returns:
      the random number in [0, 1).
    • random01d

      public double random01d()
      Draw a uniformly distributed random double from the semi-closed interval [0, 1) with maximal 53bit resolution.

      Note: takes twice as long as regular precision.

      Returns:
      the random number in [0, 1).
    • randomGaussian

      public double randomGaussian(double mean, double sdev)
      Draw a Gaussian (normal) distributed random double.
      Parameters:
      mean - the mean of the Gaussian distribution
      sdev - the standard deviation of the Gaussian distribution
      Returns:
      the Gaussian random number
    • nextBinomial

      public int nextBinomial(double p, int n)
      Draw a binomially distributed random integer.
      Parameters:
      p - the probability of success
      n - the number of trials
      Returns:
      the number of successes