Package adams.opt.genetic
Class AbstractGeneticAlgorithm
- java.lang.Object
-
- adams.core.logging.LoggingObject
-
- adams.core.logging.CustomLoggingLevelObject
-
- adams.core.option.AbstractOptionHandler
-
- adams.opt.genetic.AbstractGeneticAlgorithm
-
- All Implemented Interfaces:
Destroyable
,GlobalInfoSupporter
,LoggingLevelHandler
,LoggingSupporter
,OptionHandler
,Pausable
,Randomizable
,ShallowCopySupporter<AbstractGeneticAlgorithm>
,SizeOfHandler
,Stoppable
,StoppableWithFeedback
,ThreadLimiter
,Serializable
- Direct Known Subclasses:
AbstractClassifierBasedGeneticAlgorithm
,PackDataGeneticAlgorithm
public abstract class AbstractGeneticAlgorithm extends AbstractOptionHandler implements Randomizable, StoppableWithFeedback, Pausable, ThreadLimiter, ShallowCopySupporter<AbstractGeneticAlgorithm>
Base class for genetic algorithms.- Author:
- Dale (dale at cs dot waikato dot ac dot nz)
- See Also:
- Serialized Form
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
AbstractGeneticAlgorithm.FitnessContainer
For storing the fitness parameters.static class
AbstractGeneticAlgorithm.GeneticAlgorithmJob<T extends AbstractGeneticAlgorithm>
A job class specific to genetic algorithms.
-
Field Summary
Fields Modifier and Type Field Description protected int
m_ActualNumChrom
actual number of chromosomes.protected double
m_BestFitness
the best fitness so far.protected Range
m_BestRange
stores the best range of attribtues.protected Object
m_BestSetup
the best setup so far.protected int[]
m_BestWeights
the best weights/bits so far.protected int
m_CurrentIteration
the current iteration.protected boolean
m_FavorZeroes
whether to favor 0s instead of 1s.protected double[]
m_Fitness
the fitness of the genes.protected HashSet<GeneticFitnessChangeListener>
m_FitnessChangeListeners
the fitness change listeners.protected List<AbstractGeneticAlgorithm.FitnessContainer>
m_FitnessHistory
the fitness history (from best to worst).protected BitSet[]
m_Genes
the genes.protected AbstractInitialSetupsProvider
m_InitialSetupsProvider
the initial setups provider.protected String
m_InitialWeights
the initial weights.protected Long
m_LastNotificationTime
the timestamp the last notification got sent.protected int
m_MaxFitnessHistorySize
the maximum size of the fitness history.protected int
m_NotificationInterval
the time period in seconds after which to notify "fitness" listeners.protected int
m_NumChrom
number of chromosomes.protected int
m_NumGenes
number of genes per chromosome.protected int
m_NumThreads
the number of threads to use (-1 for #of cores).protected boolean
m_Paused
whether the algorithm is paused.protected Random
m_Random
the random number generator.protected boolean
m_Running
whether the algorithm is still running.protected long
m_Seed
the seed value.protected boolean
m_Stopped
whether the algorithm got stopped.protected AbstractStoppingCriterion
m_StoppingCriterion
the stopping criterion.-
Fields inherited from class adams.core.option.AbstractOptionHandler
m_OptionManager
-
Fields inherited from class adams.core.logging.LoggingObject
m_Logger, m_LoggingIsEnabled, m_LoggingLevel
-
-
Constructor Summary
Constructors Constructor Description AbstractGeneticAlgorithm()
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description void
addFitnessChangeListener(GeneticFitnessChangeListener l)
Adds the given listener to its internal list of listeners.protected void
addToFitnessHistory(AbstractGeneticAlgorithm.FitnessContainer container)
Adds the fitness container to the history.String
bestRangeTipText()
Returns the tip text for this property.abstract void
calcFitness()
Override the following function in sub-classes.protected void
copyGene(int to, int from)
Copies the values of one gene to another.void
defineOptions()
Adds options to the internal list of options.void
doCrossovers()
Performs cross-over.void
doMutations()
Performs mutations.void
doMutations2()
Performs mutations.String
favorZeroesTipText()
Returns the tip text for this property.static AbstractGeneticAlgorithm
forCommandLine(String cmdline)
Instantiates the genetic algorithm from the given commandline (i.e., classname and optional options).static AbstractGeneticAlgorithm
forName(String classname, String[] options)
Instantiates the genetic algorithm with the given options.String
getBestRange()
Returns the best range of attributes.double
getCurrentFitness()
Returns the currently best fitness.int
getCurrentIteration()
Returns the current iteration.Object
getCurrentSetup()
Returns the currently best setup.int[]
getCurrentWeights()
Returns the currently best weights/bits.protected AbstractInitialSetupsProvider
getDefaultInitialSetupsProvider()
Returns the default initial setups provider.boolean
getFavorZeroes()
Returns whether 0s are favored over 1s.double[]
getFitness()
Returns the current fitness values.List<AbstractGeneticAlgorithm.FitnessContainer>
getFitnessHistory()
Returns the fitness history (best to worst).boolean
getGene(int chromosome, int gene)
Returns the value of the specified gene.static String[]
getGeneticAlgorithms()
Returns a list with classnames of genetic algorithms.List<int[]>
getInitialSetups()
Provides the initial gene setup.AbstractInitialSetupsProvider
getInitialSetupsProvider()
Returns the initial setups provider to use.String
getInitialWeights()
Returns the initial weights to use rather than random ones.int
getMaxFitnessHistorySize()
Returns the maximum size for the fitness history.int
getNotificationInterval()
Returns the currently set number of bits per gene.int
getNumChrom()
Returns the number of chromosomes to use.int
getNumGenes()
Returns the number of genes to use.int
getNumThreads()
Returns the number of threads to use.long
getSeed()
Returns the current seed value.AbstractStoppingCriterion
getStoppingCriterion()
Returns the stopping criterion in use.boolean
hasMoreZeroes(BitSet a, BitSet b)
return if a has more zeroes than b.protected void
init(int ch, int genes)
Initializes the algorithm.protected void
initialize()
Initializes the members.String
initialSetupsProviderTipText()
Returns the tip text for this property.String
initialWeightsTipText()
Returns the tip text for this property.boolean
isBetterFitness(double fitness)
Checks whether the fitness is better.boolean
isPaused()
Returns whether the object is currently paused.boolean
isRunning()
Returns whether the algorithm is still running.boolean
isStopped()
Whether the execution has been stopped.protected void
logChromosomes()
Outputs the chromosomes (bits and fitness).String
maxFitnessHistorySizeTipText()
Returns the tip text for this property.String
notificationIntervalTipText()
Returns the tip text for this property.protected void
notifyFitnessChangeListeners(double fitness, Object setup, int[] weights)
Sends out a notification to all listeners that the fitness has changed, if notifications is wanted and due.protected void
notifyFitnessChangeListeners(GeneticFitnessChangeEvent e)
Notifies all the fitness change listeners of a change.String
numChromTipText()
Returns the tip text for this property.String
numThreadsTipText()
Returns the tip text for this property.void
pauseExecution()
Pauses the execution.protected void
postRun(String error)
Further clean-ups in derived classes.protected void
preRun()
Further initializations in derived classes.void
removeFitnessChangeListener(GeneticFitnessChangeListener l)
Removes the given listener from its internal list of listeners.protected void
reset()
Resets the genetic algorihtm.void
resumeExecution()
Resumes the execution.String
run()
Runs the genetic algorithm.static void
runGeneticAlgorithm(Class env, Class genetic, String[] options)
Runs the genetic algorithm with the given options.String
seedTipText()
Returns the tip text for this property.protected void
setBestRange(Range value)
Sets the best range of attributes.void
setBestRange(String value)
Sets the best range of attributes.void
setFavorZeroes(boolean value)
Sets whether 0s are favored over 1s.void
setGene(int chromosome, int gene, boolean value)
Sets the value of the specified gene.void
setGene(int chromosome, int gene, int value)
Sets the value of the specified gene.void
setInitialSetupsProvider(AbstractInitialSetupsProvider value)
Sets the initial setups provider to use.void
setInitialWeights(String value)
Sets the initial weights to use rather than random ones.void
setMaxFitnessHistorySize(int value)
Sets the maximum size for the fitness history.boolean
setNewFitness(double fitness, Object setup, int chromosome, int[] weights)
Sets a fitness and keep it if better.void
setNotificationInterval(int value)
Sets the notification interval in seconds.void
setNumChrom(int value)
Sets the number of chromosomes to use.void
setNumThreads(int value)
Sets the number of threads to use.void
setSeed(long value)
Sets the seed value to use, resets the random number generator.void
setStoppingCriterion(AbstractStoppingCriterion value)
Sets the stopping criterion to use.AbstractGeneticAlgorithm
shallowCopy()
Returns a shallow copy of itself, i.e., based on the commandline options.AbstractGeneticAlgorithm
shallowCopy(boolean expand)
Returns a shallow copy of itself, i.e., based on the commandline options.void
sort()
Sorts genes and fitness arrays according to fitness.void
stopExecution()
Stops the execution of the algorithm.String
stoppingCriterionTipText()
Returns the tip text for this property.-
Methods inherited from class adams.core.option.AbstractOptionHandler
cleanUpOptions, destroy, finishInit, getDefaultLoggingLevel, getOptionManager, globalInfo, loggingLevelTipText, newOptionManager, setLoggingLevel, toCommandLine, toString
-
Methods inherited from class adams.core.logging.LoggingObject
configureLogger, getLogger, getLoggingLevel, initializeLogging, isLoggingEnabled, sizeOf
-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface adams.core.logging.LoggingLevelHandler
getLoggingLevel
-
-
-
-
Field Detail
-
m_NumThreads
protected int m_NumThreads
the number of threads to use (-1 for #of cores).
-
m_NumGenes
protected int m_NumGenes
number of genes per chromosome. NB: must be initialized by the algorithm!
-
m_NumChrom
protected int m_NumChrom
number of chromosomes.
-
m_ActualNumChrom
protected int m_ActualNumChrom
actual number of chromosomes.
-
m_StoppingCriterion
protected AbstractStoppingCriterion m_StoppingCriterion
the stopping criterion.
-
m_CurrentIteration
protected int m_CurrentIteration
the current iteration.
-
m_Genes
protected BitSet[] m_Genes
the genes.
-
m_Fitness
protected double[] m_Fitness
the fitness of the genes.
-
m_BestRange
protected Range m_BestRange
stores the best range of attribtues.
-
m_FavorZeroes
protected boolean m_FavorZeroes
whether to favor 0s instead of 1s.
-
m_Seed
protected long m_Seed
the seed value.
-
m_InitialSetupsProvider
protected AbstractInitialSetupsProvider m_InitialSetupsProvider
the initial setups provider.
-
m_InitialWeights
protected String m_InitialWeights
the initial weights.
-
m_Random
protected Random m_Random
the random number generator.
-
m_Running
protected boolean m_Running
whether the algorithm is still running.
-
m_Stopped
protected boolean m_Stopped
whether the algorithm got stopped.
-
m_Paused
protected boolean m_Paused
whether the algorithm is paused.
-
m_NotificationInterval
protected int m_NotificationInterval
the time period in seconds after which to notify "fitness" listeners.
-
m_MaxFitnessHistorySize
protected int m_MaxFitnessHistorySize
the maximum size of the fitness history.
-
m_LastNotificationTime
protected Long m_LastNotificationTime
the timestamp the last notification got sent.
-
m_FitnessChangeListeners
protected HashSet<GeneticFitnessChangeListener> m_FitnessChangeListeners
the fitness change listeners.
-
m_FitnessHistory
protected List<AbstractGeneticAlgorithm.FitnessContainer> m_FitnessHistory
the fitness history (from best to worst).
-
m_BestFitness
protected double m_BestFitness
the best fitness so far.
-
m_BestSetup
protected Object m_BestSetup
the best setup so far.
-
m_BestWeights
protected int[] m_BestWeights
the best weights/bits so far.
-
-
Method Detail
-
initialize
protected void initialize()
Initializes the members.- Overrides:
initialize
in classAbstractOptionHandler
-
reset
protected void reset()
Resets the genetic algorihtm. Derived classes must call this method in set-methods of parameters to assure the invalidation of previously generated data.- Overrides:
reset
in classAbstractOptionHandler
-
defineOptions
public void defineOptions()
Adds options to the internal list of options.- Specified by:
defineOptions
in interfaceOptionHandler
- Overrides:
defineOptions
in classAbstractOptionHandler
-
setNumThreads
public void setNumThreads(int value)
Sets the number of threads to use.- Specified by:
setNumThreads
in interfaceThreadLimiter
- Parameters:
value
- the number of threads: -1 = # of CPUs/cores
-
getNumThreads
public int getNumThreads()
Returns the number of threads to use.- Specified by:
getNumThreads
in interfaceThreadLimiter
- Returns:
- the number of threads: -1 = # of CPUs/cores
-
numThreadsTipText
public String numThreadsTipText()
Returns the tip text for this property.- Returns:
- tip text for this property suitable for displaying in the GUI or for listing the options.
-
setBestRange
protected void setBestRange(Range value)
Sets the best range of attributes.- Parameters:
value
- the range
-
setBestRange
public void setBestRange(String value)
Sets the best range of attributes.- Parameters:
value
- the range
-
getBestRange
public String getBestRange()
Returns the best range of attributes.- Returns:
- the range
-
bestRangeTipText
public String bestRangeTipText()
Returns the tip text for this property.- Returns:
- tip text for this property suitable for displaying in the GUI or for listing the options.
-
setSeed
public void setSeed(long value)
Sets the seed value to use, resets the random number generator.- Specified by:
setSeed
in interfaceRandomizable
- Parameters:
value
- the seed to use
-
getSeed
public long getSeed()
Returns the current seed value.- Specified by:
getSeed
in interfaceRandomizable
- Returns:
- the seed value
-
seedTipText
public String seedTipText()
Returns the tip text for this property.- Specified by:
seedTipText
in interfaceRandomizable
- Returns:
- tip text for this property suitable for displaying in the GUI or for listing the options.
-
getDefaultInitialSetupsProvider
protected AbstractInitialSetupsProvider getDefaultInitialSetupsProvider()
Returns the default initial setups provider.- Returns:
- the default
-
setInitialSetupsProvider
public void setInitialSetupsProvider(AbstractInitialSetupsProvider value)
Sets the initial setups provider to use.- Parameters:
value
- the provider
-
getInitialSetupsProvider
public AbstractInitialSetupsProvider getInitialSetupsProvider()
Returns the initial setups provider to use.- Returns:
- the provider
-
initialSetupsProviderTipText
public String initialSetupsProviderTipText()
Returns the tip text for this property.- Returns:
- tip text for this property suitable for displaying in the GUI or for listing the options.
-
setInitialWeights
public void setInitialWeights(String value)
Sets the initial weights to use rather than random ones.- Parameters:
value
- the initial weights
-
getInitialWeights
public String getInitialWeights()
Returns the initial weights to use rather than random ones.- Returns:
- the initial weights
-
initialWeightsTipText
public String initialWeightsTipText()
Returns the tip text for this property.- Returns:
- tip text for this property suitable for displaying in the GUI or for listing the options.
-
setFavorZeroes
public void setFavorZeroes(boolean value)
Sets whether 0s are favored over 1s.- Parameters:
value
- if true then 0s are favored over 1s
-
getFavorZeroes
public boolean getFavorZeroes()
Returns whether 0s are favored over 1s.- Returns:
- true if 0s are favored over 1s
-
favorZeroesTipText
public String favorZeroesTipText()
Returns the tip text for this property.- Returns:
- tip text for this property suitable for displaying in the GUI or for listing the options.
-
getNumGenes
public int getNumGenes()
Returns the number of genes to use.- Returns:
- the number
-
setNumChrom
public void setNumChrom(int value)
Sets the number of chromosomes to use.- Parameters:
value
- the number
-
getNumChrom
public int getNumChrom()
Returns the number of chromosomes to use.- Returns:
- the number
-
numChromTipText
public String numChromTipText()
Returns the tip text for this property.- Returns:
- tip text for this property suitable for displaying in the GUI or for listing the options.
-
setStoppingCriterion
public void setStoppingCriterion(AbstractStoppingCriterion value)
Sets the stopping criterion to use.- Parameters:
value
- the criterion
-
getStoppingCriterion
public AbstractStoppingCriterion getStoppingCriterion()
Returns the stopping criterion in use.- Returns:
- the criterion
-
stoppingCriterionTipText
public String stoppingCriterionTipText()
Returns the tip text for this property.- Returns:
- tip text for this property suitable for displaying in the GUI or for listing the options.
-
setNotificationInterval
public void setNotificationInterval(int value)
Sets the notification interval in seconds.- Parameters:
value
- the interval in seconds
-
getNotificationInterval
public int getNotificationInterval()
Returns the currently set number of bits per gene.- Returns:
- the number of bits
-
notificationIntervalTipText
public String notificationIntervalTipText()
Returns the tip text for this property.- Returns:
- tip text for this property suitable for displaying in the GUI or for listing the options.
-
setMaxFitnessHistorySize
public void setMaxFitnessHistorySize(int value)
Sets the maximum size for the fitness history.- Parameters:
value
- the maximum size, <1 = unlimited
-
getMaxFitnessHistorySize
public int getMaxFitnessHistorySize()
Returns the maximum size for the fitness history.- Returns:
- the maximum size, <1 = unlimited
-
maxFitnessHistorySizeTipText
public String maxFitnessHistorySizeTipText()
Returns the tip text for this property.- Returns:
- tip text for this property suitable for displaying in the GUI or for listing the options.
-
getCurrentIteration
public int getCurrentIteration()
Returns the current iteration.- Returns:
- the iteration
-
stopExecution
public void stopExecution()
Stops the execution of the algorithm.- Specified by:
stopExecution
in interfaceStoppable
-
isStopped
public boolean isStopped()
Whether the execution has been stopped.- Specified by:
isStopped
in interfaceStoppableWithFeedback
- Returns:
- true if stopped
-
pauseExecution
public void pauseExecution()
Pauses the execution.- Specified by:
pauseExecution
in interfacePausable
-
isPaused
public boolean isPaused()
Returns whether the object is currently paused.
-
resumeExecution
public void resumeExecution()
Resumes the execution.- Specified by:
resumeExecution
in interfacePausable
-
isRunning
public boolean isRunning()
Returns whether the algorithm is still running.- Returns:
- true if the algorithm is still running
-
getFitness
public double[] getFitness()
Returns the current fitness values.- Returns:
- the fitness values
-
init
protected void init(int ch, int genes)
Initializes the algorithm.- Parameters:
ch
- the chromosomegenes
- the number of genes
-
getGene
public boolean getGene(int chromosome, int gene)
Returns the value of the specified gene.- Parameters:
chromosome
- the chromosome indexgene
- the gene index- Returns:
- true if gene is active
-
setGene
public void setGene(int chromosome, int gene, int value)
Sets the value of the specified gene.- Parameters:
chromosome
- the chromosome indexgene
- the gene indexvalue
- the value to set, 0=clear, otherwise activate it
-
setGene
public void setGene(int chromosome, int gene, boolean value)
Sets the value of the specified gene.- Parameters:
chromosome
- the chromosome indexgene
- the gene indexvalue
- false=clear, true=activate it
-
hasMoreZeroes
public boolean hasMoreZeroes(BitSet a, BitSet b)
return if a has more zeroes than b.- Parameters:
a
- the first geneb
- the second gene- Returns:
- true if a has more zeroes than b
-
sort
public void sort()
Sorts genes and fitness arrays according to fitness.
-
doCrossovers
public void doCrossovers()
Performs cross-over.
-
copyGene
protected void copyGene(int to, int from)
Copies the values of one gene to another.- Parameters:
to
- the gene to copy tofrom
- the gene to copy from
-
doMutations
public void doMutations()
Performs mutations.
-
doMutations2
public void doMutations2()
Performs mutations.
-
calcFitness
public abstract void calcFitness()
Override the following function in sub-classes.
-
isBetterFitness
public boolean isBetterFitness(double fitness)
Checks whether the fitness is better.- Parameters:
fitness
- the new fitness- Returns:
- true if the new fitness is better
-
addToFitnessHistory
protected void addToFitnessHistory(AbstractGeneticAlgorithm.FitnessContainer container)
Adds the fitness container to the history. Automatically prunes the size of the history.- Parameters:
container
- the container to add
-
setNewFitness
public boolean setNewFitness(double fitness, Object setup, int chromosome, int[] weights)
Sets a fitness and keep it if better.- Parameters:
fitness
- the new fitnesssetup
- the new setupchromosome
- the chromosome responsibleweights
- the new weights- Returns:
- true if the new fitness was better
-
getCurrentFitness
public double getCurrentFitness()
Returns the currently best fitness.- Returns:
- the best fitness so far
-
getCurrentSetup
public Object getCurrentSetup()
Returns the currently best setup.- Returns:
- the best setup so far
-
getCurrentWeights
public int[] getCurrentWeights()
Returns the currently best weights/bits.- Returns:
- the best weights/bits so far
-
getFitnessHistory
public List<AbstractGeneticAlgorithm.FitnessContainer> getFitnessHistory()
Returns the fitness history (best to worst).- Returns:
- the history
-
preRun
protected void preRun()
Further initializations in derived classes.
-
logChromosomes
protected void logChromosomes()
Outputs the chromosomes (bits and fitness).
-
run
public String run()
Runs the genetic algorithm.- Returns:
- null if successfully finished, otherwise error message
-
postRun
protected void postRun(String error) throws Exception
Further clean-ups in derived classes.- Parameters:
error
- null if successful, otherwise error message- Throws:
Exception
- if something goes wrong
-
addFitnessChangeListener
public void addFitnessChangeListener(GeneticFitnessChangeListener l)
Adds the given listener to its internal list of listeners.- Parameters:
l
- the listener to add
-
removeFitnessChangeListener
public void removeFitnessChangeListener(GeneticFitnessChangeListener l)
Removes the given listener from its internal list of listeners.- Parameters:
l
- the listener to remove
-
notifyFitnessChangeListeners
protected void notifyFitnessChangeListeners(GeneticFitnessChangeEvent e)
Notifies all the fitness change listeners of a change.- Parameters:
e
- the event to send
-
notifyFitnessChangeListeners
protected void notifyFitnessChangeListeners(double fitness, Object setup, int[] weights)
Sends out a notification to all listeners that the fitness has changed, if notifications is wanted and due.- Parameters:
fitness
- the fitnesssetup
- the setupweights
- the weights
-
getInitialSetups
public List<int[]> getInitialSetups()
Provides the initial gene setup.- Returns:
- the genes (0s and 1s)
-
shallowCopy
public AbstractGeneticAlgorithm shallowCopy()
Returns a shallow copy of itself, i.e., based on the commandline options.- Specified by:
shallowCopy
in interfaceShallowCopySupporter<AbstractGeneticAlgorithm>
- Returns:
- the shallow copy
-
shallowCopy
public AbstractGeneticAlgorithm shallowCopy(boolean expand)
Returns a shallow copy of itself, i.e., based on the commandline options.- Specified by:
shallowCopy
in interfaceShallowCopySupporter<AbstractGeneticAlgorithm>
- Parameters:
expand
- whether to expand variables to their current values- Returns:
- the shallow copy
-
runGeneticAlgorithm
public static void runGeneticAlgorithm(Class env, Class genetic, String[] options)
Runs the genetic algorithm with the given options.- Parameters:
env
- the environment class to usegenetic
- the genetic algorithm to runoptions
- the options to set
-
getGeneticAlgorithms
public static String[] getGeneticAlgorithms()
Returns a list with classnames of genetic algorithms.- Returns:
- the genetic algorithm classnames
-
forName
public static AbstractGeneticAlgorithm forName(String classname, String[] options)
Instantiates the genetic algorithm with the given options.- Parameters:
classname
- the classname of the genetic algorithm to instantiateoptions
- the options for the genetic algorithm- Returns:
- the instantiated genetic algorithm or null if an error occurred
-
forCommandLine
public static AbstractGeneticAlgorithm forCommandLine(String cmdline)
Instantiates the genetic algorithm from the given commandline (i.e., classname and optional options).- Parameters:
cmdline
- the classname (and optional options) of the genetic algorithm to instantiate- Returns:
- the instantiated genetic algorithm or null if an error occurred
-
-