Class PDE

All Implemented Interfaces:
Discrete, CLOProvider
Direct Known Subclasses:
Advection

public class PDE extends ODE
Numerical integration of partial differential equations for reaction-diffusion systems based on Euler's method (fixed step size)

Important: Currently multi-species modules are not supported by PDE models.

Author:
Christoph Hauert
  • Field Details

    • module

      protected Module module
      Convenience variable: module associated with this model (useful as long as PDE models are restricted to single species).
    • supervisor

      protected PDESupervisor supervisor
      The supervisor for the integration of the reaction-diffusion process. This abstraction is required due to incompatibilities between JRE and GWT implementations. In particular, JRE allows for parallel execution of certain steps, while GWT uses a scheduling mechanism.
      See Also:
    • space

      protected Geometry space
      Geometry representing the spatial dimensions of this PDE.
    • density

      protected double[][] density
      Density distribution of traits as a 2D array. The first entry refers to the index of the node (e.g. location on lattice) and the second entry refers to the different traits at that location. space defines the geometric arrangement of the nodes.

      Note: this variable is protected to allow direct access from PDESupervisor for efficiency reasons.

    • next

      protected double[][] next
      The next density/frequency distribution of traits as a 2D array. The first entry refers to the index of the node (e.g. location on lattice) and the second entry refers to the different traits at that location. space defines the geometric arrangement of the nodes.

      Note: this variable is protected to allow direct access from PDESupervisor for efficiency reasons.

    • fitness

      protected double[][] fitness
      Fitness distribution of traits as a 2D array. The first entry refers to the index of the node (e.g. location on lattice) and the second entry refers to the different traits at that location. space defines the geometric arrangement of the nodes.

      Note: this variable is protected to allow direct access from PDESupervisor for efficiency reasons.

    • initType

      protected PDE.InitType initType
      Type of initial configuration for each species.

      Note: this variable is deliberately hiding a field from ODE because PDE models have their own initialization types. Make sure initType is not accessed through calls to super. Since PDE's currently support only single species models initType is a scalar field.

      See Also:
    • discretization

      protected int discretization
      Discretization of space as the total number of spatial units. For example, for a square lattice the dimensions are sqrt(discretization)×sqrt(discretization).
      See Also:
    • linext

      protected double linext
      The linear extension of the lattice.
      See Also:
    • diffcoeff

      protected double[] diffcoeff
      The array of diffusion coefficients for each trait.
      See Also:
    • requestSymmetric

      boolean requestSymmetric
      The flag indicating whether preservation of symmetry in the dynamics is requested. The model may not be able to honour the request because it requires that the spatial structure permits preservation of symmetry, i.e. the underlying spatial geometry represents a lattice.
      See Also:
    • isSymmetric

      boolean isSymmetric
      The flag indicating whether the dynamics is symmetric. This requires that symmetry preservation was requested, i.e. requestSymmetric==true and that the spatial structure permits preservation of symmetry, i.e. the underlying spatial geometry represents a lattice.
      See Also:
    • minDensity

      protected double[] minDensity
      The array containing the minimum densities of each trait. Used to set the color range when retrieving the density data.
      See Also:
    • maxDensity

      protected double[] maxDensity
      The array containing the maximum densities of each trait. Used to set the color range when retrieving the density data.
      See Also:
    • meanDensity

      protected double[] meanDensity
      The array containing the mean densities of each trait.
      See Also:
    • minFitness

      protected double[] minFitness
      The array containing the minimum fitness of each trait. Used to set the color range when retrieving the density data.
      See Also:
    • maxFitness

      protected double[] maxFitness
      The array containing the maximum fitness of each trait. Used to set the color range when retrieving the density data.
      See Also:
    • meanFitness

      protected double[] meanFitness
      The array containing the mean fitness of each trait.
      See Also:
    • dependent

      protected int dependent
      The index of the dependent trait. Dependent traits make only sense in replicator type model with frequencies, i.e. normalized states. The dependent trait is the one that gets derived from the changes in all others in order to maintain normalization.

      Note: This is a simple helper variable and shortcut for dependents[0], which makes sense as long as this model cannot deal with multi-species modules.

      See Also:
    • alpha

      protected double[] alpha
      Helper variable to store the effective diffusion terms. This depends not only on the diffusion coefficients diffcoeff but also on the time increment dt and the linear extension, linext.
      See Also:
    • sorting

      Comparator<double[]> sorting
      In order to preserve symmetry the densities of neighbouring cells in the diffusion step need to be sorted. The sorting criteria are essentially irrelevant as long as they are consistently applied.
    • gwtHalt

      double gwtHalt
      The generation when the model execution is halted next. This is needed to keep track of halting for asynchronous execution in GWT.
    • cloPdeN

      public final CLOption cloPdeN
      Command line option to set the discretization as the total number of spatial units to use for the numerical integration of the PDE.
      See Also:
    • cloPdeL

      public final CLOption cloPdeL
      Command line option to set the linear extension. This is only meaningful lattice type geometries.
      See Also:
    • cloPdeDiffusion

      public final CLOption cloPdeDiffusion
      Command line option to set the diffusion coefficients.
      See Also:
    • cloPdeSymmetric

      public final CLOption cloPdeSymmetric
      Command line option to request preservation of symmetry. If request cannot be honoured a warning is issued.
      See Also:
  • Constructor Details

    • PDE

      public PDE(EvoLudo engine)
      Constructs a new model for the numerical integration of the system of partial differential equations representing the dynamics specified by the Module module using the EvoLudo pacemaker engine to control the numerical evaluations. The integrator implements reaction-diffusion steps based on Euler's method (fixed step size).

      Important: for reproducibility the shared random number generator should be used (in PDE's only used to generate random initial configurations).

      Note: requires a supervisor that matches the implementation, i.e. JRE or GWT, respectively, to properly deal with multiple threads or scheduling.

      Parameters:
      engine - the pacemaker for running the model
      See Also:
  • Method Details

    • getGeometry

      public Geometry getGeometry()
      Gets the geometry representing the spatial structure of this PDE.
      Returns:
      the geometry of the PDE
    • load

      public void load()
      Description copied from class: Model
      Milestone: Load this model and allocate resources (if applicable).
      Overrides:
      load in class ODE
      See Also:
    • unload

      public void unload()
      Description copied from class: Model
      Milestone: Unload this model and free resources (if applicable).
      Overrides:
      unload in class ODE
      See Also:
    • check

      public boolean check()
      Description copied from class: Model
      Check consistency of parameters and adjust if necessary (and possible). All issues and modifications should be reported through logger. Some parameters can be adjusted while the model remains active or even while running, whereas others require a reset. An example of the former category is in general simple adjustments of payoffs, while an example of the latter category is a change of the population structure.
      Overrides:
      check in class ODE
      Returns:
      true if reset required
      See Also:
    • reset

      public void reset()
      Description copied from class: Model
      Milestone: Reset this model
      Overrides:
      reset in class ODE
      See Also:
    • update

      public void update()
      Update this model. For example called after initialization and when parameters changed.

      For PDEs simply delegate to supervisor for dealing with multiple threads (JRE) or scheduling (GWT).

      Overrides:
      update in class ODE
      See Also:
    • useScheduling

      public boolean useScheduling()
      Description copied from class: Model
      GWT models run asynchronously and long running tasks require scheduling to maintain responsive user interface. In contrast, JRE provides a multi-threaded environment, which allows to run multiple threads synchronously. This parallel execution results in an significant speed-boost (for PDE calculations).
      Overrides:
      useScheduling in class Model
      Returns:
      true if model calculations are asynchronous
    • next

      public boolean next()
      Advance model by one step. The details of what happens during one step depends on the models Type as well as its Mode.

      Implementation Notes:

      Before:
      1. yt current state
      2. ft current fitness
      3. dyt current derivatives fitness
      4. dtTry size of time step attempting to make
      After:
      1. yt next state
      2. ft next fitness
      3. dyt next derivatives
      4. yout contains previous state (i.e. yt when entering method)
      5. stepTaken the time between yt and yout

      For PDEs simply delegate to supervisor for dealing with multiple threads (JRE) or scheduling (GWT).

      Overrides:
      next in class ODE
      Returns:
      true if next() can be called again. Typically false is returned if the model requires attention, such as the following conditions:
      • the model has converged
      • the model turned monomorphic (stops only if requested)
      • a statistics sample is available
      • a preset time has been reached
      See Also:
    • react

      public double react(int start, int end)
      Reaction step. Update cells with indices between start (including) and end (excluding) and return the accumulated/total change in state.

      Note: At the end, the state in density is unchanged, the new density distribution is in next and the fitness matching density is updated.

      Important: must be thread safe for JRE. In particular, no memory can be shared with anyone else!

      Parameters:
      start - the index of the first cell (including)
      end - the index of the last cell (excluding)
      Returns:
      the accumulated change in state
    • updateFitness

      public void updateFitness(double[] min, double[] max, double[] mean)
      Update minimum, maximum and mean fitnesses during to reaction step. In multi threaded settings each worker reports the minima min, maxima max, and the total mean fitness (for the calculation of the mean) of the PDE units it is responsible for.
      Parameters:
      min - the array with fitness minima
      max - the array with fitness maxima
      mean - the array with fitness means
    • normalizeMeanFitness

      public void normalizeMeanFitness()
      Normalizes the mean fitnesses after the reaction step is complete.
    • resetFitness

      public void resetFitness()
      Resets minimum, maximum and mean fitnesses prior to reaction step.
    • diffuse

      public void diffuse(int start, int end)
      Diffusion step. Update cells with indices between start (including) and end (excluding). In order to preserve symmetry, if requested and possible, the neighbouring cells are sorted according to their density before the diffusion step is performed. The sorting is fairly expensive in terms of CPU time but it doesn't matter whether the sorting is ascending or descending.

      Note: At the end, the state in next is unchanged, the new density distribution is in density and the fitness is untouched/unused.

      Important: must be thread safe for JRE. In particular, no memory can be shared with anyone else!

      Parameters:
      start - the index of the first cell (including)
      end - the index of the last cell (excluding)
    • resetDensity

      public void resetDensity()
      Resets minimum, maximum and mean density prior to diffusion step.
    • setDensity

      public void setDensity()
      Initializes minimum, maximum and mean density based on current state.
    • updateDensity

      public void updateDensity(double[] min, double[] max, double[] mean)
      Update minimum, maximum and mean density during to reaction step. In multi threaded settings each worker reports the minima min, maxima max, and the total mean density (for the calculation of the mean) of the PDE units it is responsible for.
      Parameters:
      min - the array with density minima
      max - the array with density maxima
      mean - the array with density means
    • normalizeMeanDensity

      public void normalizeMeanDensity()
      Normalizes the mean density after the diffusion step is complete.
    • getMeanTraits

      public boolean getMeanTraits(double[] mean)
      Description copied from class: Model
      Collect and return mean trait values for all species.

      NOTE: this is a convenience method for multi-species modules to retrieve states efficiently for further processing or visualization.

      Overrides:
      getMeanTraits in class ODE
      Parameters:
      mean - the array for storing the mean trait values
      Returns:
      true if this and previous data point should be connected, i.e. no reset had been requested in the mean time.
    • getMeanTraits

      public boolean getMeanTraits(int id, double[] mean)
      Description copied from class: Model
      Return mean trait values for species with ID id.
      Overrides:
      getMeanTraits in class ODE
      Parameters:
      id - the species identifier
      mean - the array for storing the mean trait values
      Returns:
      true if this and the previous data point should be connected, i.e. no reset had been requested in the mean time.
    • getMeanTraitAt

      public double[] getMeanTraitAt(int id, int idx)
      Description copied from class: Model
      Return mean trait values at location idx for species with ID id.

      Note: optional implementation; currently makes sense only for local dynamics in PDE models.

      IMPORTANT: the returned array is live and should not be altered.

      Overrides:
      getMeanTraitAt in class Model
      Parameters:
      id - the species identifier
      idx - the index of the location
      Returns:
      array of mean trait values
    • getTraitNameAt

      public String getTraitNameAt(int id, int idx)
      Description copied from class: Model
      Gets the formatted trait names at location idx for species with ID id. The formatting may include HTML tags. Used by GUI for example to show trait names in tooltips.

      Note: optional implementation. Currently makes sense only for IBS models and local dynamics in PDE models.

      Overrides:
      getTraitNameAt in class Model
      Parameters:
      id - the species identifier
      idx - the index of the location
      Returns:
      description of traits at idx
    • getTraitData

      public <T> void getTraitData(int ID, T[] colors, ColorMap<T> colorMap)
      Description copied from class: ODE
      Unused interface method.
      Overrides:
      getTraitData in class ODE
      Type Parameters:
      T - color data type. Color for PopGraph2D and PopGraph2D as well as MeshLambertMaterial for PopGraph3D
      Parameters:
      ID - the species identifier
      colors - the array for storing the colors for individuals
      colorMap - the map for translating individual traits into colors
    • getMeanFitness

      public boolean getMeanFitness(int id, double[] mean)
      Description copied from class: Model
      Gets the mean fitness values for species with ID id. The result is stored and returned in mean. Used by GUI to visualize local dynamics at idx.
      Overrides:
      getMeanFitness in class ODE
      Parameters:
      id - the species identifier
      mean - the array for storing the mean fitness values
      Returns:
      true if this and the previous data point should be connected, i.e. no reset had been requested in the mean time.
    • getMeanFitnessAt

      public double[] getMeanFitnessAt(int id, int idx)
      Description copied from class: Model
      Gets the mean fitness(es) of this model at location idx. Used by GUI to visualize local dynamics at idx.

      Note: optional implementation. Currently makes sense only for local dynamics in PDE models.

      IMPORTANT: the returned array is live and should not be altered.

      Overrides:
      getMeanFitnessAt in class Model
      Parameters:
      id - the species identifier
      idx - the location of the fitness values
      Returns:
      the array of mean fitness values
    • getFitnessNameAt

      public String getFitnessNameAt(int id, int idx)
      Description copied from class: Model
      Gets the fitness at location idx for species with ID id as a formatted string. The formatting may include HTML tags. Used by GUI for example to show fitness in tooltips.

      Note: optional implementation. Currently makes sense only for IBS and PDE models.

      Overrides:
      getFitnessNameAt in class Model
      Parameters:
      id - the species identifier
      idx - the index of the location
      Returns:
      the fitness as a formatted string
    • getFitnessData

      public <T> void getFitnessData(int id, T[] colors, ColorMap.Gradient1D<T> colorMap)
      Description copied from class: Model
      Translates fitness data into colors using ColorMap colorMap. Used by GUI to visualize current state of model.
      Overrides:
      getFitnessData in class ODE
      Type Parameters:
      T - color data type. Color for PopGraph2D and PopGraph2D as well as MeshLambertMaterial for PopGraph3D
      Parameters:
      id - the species identifier
      colors - the array for storing color values
      colorMap - the map to use for translating traits to colors
    • getFitnessHistogramData

      public void getFitnessHistogramData(int id, double[][] bins)
      Description copied from class: Model
      Generates a histogram of fitness data and returns the result in the provided array bins. For Discrete modules a fitness histogram is returned for each trait separately. For Continuous modules there is, in general, only a single fitness dimension.
      Overrides:
      getFitnessHistogramData in class ODE
      Parameters:
      id - the species identifier
      bins - the array for storing histogram. For Discrete modules this is always one dimensional
    • getStatus

      public String getStatus()
      Description copied from class: Model
      Returns status message from model. Typically this is a string summarizing the current state of the simulation. For example, models with discrete strategy sets (such as 2x2 games, see TBT) return the average frequencies of each strategy type in the population(s), see IBSDPopulation. Similarly, models with continuous strategies (such as continuous snowdrift games, see CSD) return the mean, minimum and maximum trait value(s) in the population(s), see IBSMCPopulation. The status message is displayed along the bottom of the GUI.

      Note: if the model runs into difficulties, problems should be reported through the logging mechanism. Messages with severity Level.WARNING or higher are displayed in the status of the GUI and override status messages returned here.

      Overrides:
      getStatus in class ODE
      Returns:
      status of active model
    • isMonomorphic

      public boolean isMonomorphic()
      Description copied from class: ODE
      Check if population is monomorphic. Note, in multi-species modules all species need to be monomorphic.
      Overrides:
      isMonomorphic in class ODE
      Returns:
      true if criteria for monomorphic state passed
    • setDiscretization

      public void setDiscretization(int d)
      Sets the number of units used to discretize the spatial dimensions for numerical integration of the PDE.
      Parameters:
      d - the number of units
      See Also:
    • getDiscretization

      public int getDiscretization()
      Gets the number of units used to discretize the spatial dimensions for numerical integration of the PDE.
      Returns:
      the number of units to discretize spatial
    • setLinearExtension

      public void setLinearExtension(double l)
      Sets the linear extension of the lattice.

      Note: For geometries other than 1D, 2D or 3D lattices the meaning of this parameter is unclear/undefined.

      Parameters:
      l - the linear extension of the lattice
      See Also:
    • getLinearExtension

      public double getLinearExtension()
      Gets the linear extension of the lattice.

      Note: For geometries other than 1D, 2D or 3D lattices the meaning of this parameter is unclear/undefined.

      Returns:
      the linear extension
    • setDiffusion

      public void setDiffusion(double[] dc)
      Sets the diffusion coefficients for each trait.
      Parameters:
      dc - the array of diffusion coefficients
      See Also:
    • getDiffusion

      public double[] getDiffusion()
      Gets the diffusion coefficients for all traits as an array.
      Returns:
      the array of diffusion coefficients
    • setSymmetric

      public void setSymmetric(boolean symmetric)
      Sets whether symmetries should be preserved. Not all models may be able to honour the request. For example PDE is only able to preserve symmetries in the diffusion step if the Geometry.isLattice() returns true.
      Parameters:
      symmetric - the request to preserve symmetry
    • getSymmetric

      public boolean getSymmetric()
      Gets whether preservation of symmetry was requested. Not all models may be able to honour the request.
      Returns:
      true if symmetry preservation was requested
      See Also:
    • isSymmetric

      public boolean isSymmetric()
      Gets whether the model preserves symmetry. Requires that symmetry preservation is requested and the model is able to honour the request.
      Returns:
      true if symmetry is preserved
    • incrementTime

      public boolean incrementTime(double incr)
      Increments time by incr. This is used by the PDESupervisor to report back on the progress.
      Parameters:
      incr - the time that has elapsed
      Returns:
      true to continue and false to request a stop
    • setConverged

      public void setConverged()
      Indicates that the numerical integration has converged to a homogeneous state. This is used by the PDESupervisor to report back on the progress.
    • permitsTimeReversal

      public boolean permitsTimeReversal()
      Checks if time reversal is permitted. By default returns false. Only few models are capable of time reversal.

      ODE and SDE models return true by default.

      Due to diffusion PDE models do not permit time reversal.

      Overrides:
      permitsTimeReversal in class ODE
      Returns:
      true if time reversal permissible.
      See Also:
    • init

      public void init()
      Description copied from class: Model
      Milestone: Initialize this model
      Overrides:
      init in class ODE
      See Also:
    • scaleDensity

      private void scaleDensity(double[] d, double scale)
      Helper method to scale the density vector d by the scalar factor scale. The scalar must lie in \((0, 1)\) such that the initial densities/frequencies represent the maximum.
      Parameters:
      d - the density vector to scale
      scale - the scaling factor
    • parse

      public boolean parse(String arg)
      Parse initializer string arg. Determine type of initialization and process its arguments as appropriate.

      Note: Not possible to perform parsing in CLODelegate of ODE.cloInit because PDE model provide their own PDE.InitTypes.

      Overrides:
      parse in class ODE
      Parameters:
      arg - the arguments to parse
      Returns:
      true if parsing successful
      See Also:
    • initDiffusion

      public void initDiffusion(double deltat)
      Helper method to initialize the effective rate of diffusion for the time increment dt.

      Note: This method needs to be public to permit access by PDESupervisorGWT and PDESupervisorJRE

      Parameters:
      deltat - the time increment for diffusion
    • checkDt

      void checkDt()
      Helper method to check whether the time increment, ODE.dt, is acceptable. If it is too large the diffusion step runs into numerical issues. If dt needs to be decreased a warning is emitted.
    • calcInvDeltaX

      double calcInvDeltaX()
      Helper method to calculate 1 / dx for different lattice geometries.
      Returns:
      the 1 / dx for the current geometry.
    • minmaxmean

      static void minmaxmean(double[] data, double[] min, double[] max, double[] mean)
      Utility method to update the trait minimum, maximum and mean based on the provided data array.
      Parameters:
      data - the data to process
      min - the array with the minima of each trait
      max - the array with the maxima of each trait
      mean - the array with the trait means
    • collectCLO

      public void collectCLO(CLOParser parser)
      Description copied from interface: CLOProvider
      All providers of command line options must implement this method to collect their options.

      Each command line option is (uniquely) identified by it's name (see CLOption.getName()), which corresponds to the long version of the option. If an attempt is made to add an option with a name that already exists, the parser issues a warning and ignores the option. Thus, in general, implementing subclasses should first register their options and call super.collectCLO(CLOParser) at the end such that subclasses are able to override command line options specified in a parental class.

      Override this method in subclasses to add further command line options. Subclasses must make sure that they include a call to super.

      Specified by:
      collectCLO in interface CLOProvider
      Overrides:
      collectCLO in class ODE
      Parameters:
      parser - the reference to parser that manages command line options
      See Also:
    • encodeState

      public void encodeState(StringBuilder plist)
      Description copied from class: Model
      Encode the state of the model in a plist inspired XML string. This allows to save the state and restore later with the exact same results as when continuing to run the model. This even allows to switch from JRE to GWT or back and obtain identical results!
      Overrides:
      encodeState in class ODE
      Parameters:
      plist - the StringBuilder to write the encoded state to
      See Also:
    • restoreState

      public boolean restoreState(Plist plist)
      Description copied from class: Model
      Restore the state encoded in the plist inspired map of key, value-pairs.
      Overrides:
      restoreState in class ODE
      Parameters:
      plist - the map of key, value-pairs
      Returns:
      true if successful
      See Also:
    • encodeGeometry

      void encodeGeometry(StringBuilder plist)
      Encodes the geometry of the spatial structure for this PDE in the form of a plist string.
      Parameters:
      plist - the string builder for the encoded state
    • restoreGeometry

      boolean restoreGeometry(Plist plist)
      Restores the geometry of the spatial structure encoded in plist.
      Parameters:
      plist - the encoded state
      Returns:
      true if successful
    • encodeStrategies

      void encodeStrategies(StringBuilder plist)
      Description copied from class: ODE
      Encodes state of the model in the form of a plist string.
      Overrides:
      encodeStrategies in class ODE
      Parameters:
      plist - the string builder for the encoded state
    • restoreStrategies

      public boolean restoreStrategies(Plist plist)
      Description copied from class: ODE
      Restores the state encoded in plist.
      Overrides:
      restoreStrategies in class ODE
      Parameters:
      plist - the encoded state
      Returns:
      true if successful
    • encodeFitness

      public void encodeFitness(StringBuilder plist)
      Description copied from class: ODE
      Encodes the fitness of the model in the form of a plist string.
      Overrides:
      encodeFitness in class ODE
      Parameters:
      plist - the string builder for the encoded state
    • restoreFitness

      public boolean restoreFitness(Plist plist)
      Description copied from class: ODE
      Restores the fitness encoded in plist.
      Overrides:
      restoreFitness in class ODE
      Parameters:
      plist - the encoded state
      Returns:
      true if successful