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 classAbstractGeneticAlgorithm.FitnessContainerFor storing the fitness parameters.static classAbstractGeneticAlgorithm.GeneticAlgorithmJob<T extends AbstractGeneticAlgorithm>A job class specific to genetic algorithms.
-
Field Summary
Fields Modifier and Type Field Description protected intm_ActualNumChromactual number of chromosomes.protected doublem_BestFitnessthe best fitness so far.protected Rangem_BestRangestores the best range of attribtues.protected Objectm_BestSetupthe best setup so far.protected int[]m_BestWeightsthe best weights/bits so far.protected intm_CurrentIterationthe current iteration.protected booleanm_FavorZeroeswhether to favor 0s instead of 1s.protected double[]m_Fitnessthe fitness of the genes.protected HashSet<GeneticFitnessChangeListener>m_FitnessChangeListenersthe fitness change listeners.protected List<AbstractGeneticAlgorithm.FitnessContainer>m_FitnessHistorythe fitness history (from best to worst).protected BitSet[]m_Genesthe genes.protected AbstractInitialSetupsProviderm_InitialSetupsProviderthe initial setups provider.protected Stringm_InitialWeightsthe initial weights.protected Longm_LastNotificationTimethe timestamp the last notification got sent.protected intm_MaxFitnessHistorySizethe maximum size of the fitness history.protected intm_NotificationIntervalthe time period in seconds after which to notify "fitness" listeners.protected intm_NumChromnumber of chromosomes.protected intm_NumGenesnumber of genes per chromosome.protected intm_NumThreadsthe number of threads to use (-1 for #of cores).protected booleanm_Pausedwhether the algorithm is paused.protected Randomm_Randomthe random number generator.protected booleanm_Runningwhether the algorithm is still running.protected longm_Seedthe seed value.protected booleanm_Stoppedwhether the algorithm got stopped.protected AbstractStoppingCriterionm_StoppingCriterionthe 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 voidaddFitnessChangeListener(GeneticFitnessChangeListener l)Adds the given listener to its internal list of listeners.protected voidaddToFitnessHistory(AbstractGeneticAlgorithm.FitnessContainer container)Adds the fitness container to the history.StringbestRangeTipText()Returns the tip text for this property.abstract voidcalcFitness()Override the following function in sub-classes.protected voidcopyGene(int to, int from)Copies the values of one gene to another.voiddefineOptions()Adds options to the internal list of options.voiddoCrossovers()Performs cross-over.voiddoMutations()Performs mutations.voiddoMutations2()Performs mutations.StringfavorZeroesTipText()Returns the tip text for this property.static AbstractGeneticAlgorithmforCommandLine(String cmdline)Instantiates the genetic algorithm from the given commandline (i.e., classname and optional options).static AbstractGeneticAlgorithmforName(String classname, String[] options)Instantiates the genetic algorithm with the given options.StringgetBestRange()Returns the best range of attributes.doublegetCurrentFitness()Returns the currently best fitness.intgetCurrentIteration()Returns the current iteration.ObjectgetCurrentSetup()Returns the currently best setup.int[]getCurrentWeights()Returns the currently best weights/bits.protected AbstractInitialSetupsProvidergetDefaultInitialSetupsProvider()Returns the default initial setups provider.booleangetFavorZeroes()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).booleangetGene(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.AbstractInitialSetupsProvidergetInitialSetupsProvider()Returns the initial setups provider to use.StringgetInitialWeights()Returns the initial weights to use rather than random ones.intgetMaxFitnessHistorySize()Returns the maximum size for the fitness history.intgetNotificationInterval()Returns the currently set number of bits per gene.intgetNumChrom()Returns the number of chromosomes to use.intgetNumGenes()Returns the number of genes to use.intgetNumThreads()Returns the number of threads to use.longgetSeed()Returns the current seed value.AbstractStoppingCriteriongetStoppingCriterion()Returns the stopping criterion in use.booleanhasMoreZeroes(BitSet a, BitSet b)return if a has more zeroes than b.protected voidinit(int ch, int genes)Initializes the algorithm.protected voidinitialize()Initializes the members.StringinitialSetupsProviderTipText()Returns the tip text for this property.StringinitialWeightsTipText()Returns the tip text for this property.booleanisBetterFitness(double fitness)Checks whether the fitness is better.booleanisPaused()Returns whether the object is currently paused.booleanisRunning()Returns whether the algorithm is still running.booleanisStopped()Whether the execution has been stopped.protected voidlogChromosomes()Outputs the chromosomes (bits and fitness).StringmaxFitnessHistorySizeTipText()Returns the tip text for this property.StringnotificationIntervalTipText()Returns the tip text for this property.protected voidnotifyFitnessChangeListeners(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 voidnotifyFitnessChangeListeners(GeneticFitnessChangeEvent e)Notifies all the fitness change listeners of a change.StringnumChromTipText()Returns the tip text for this property.StringnumThreadsTipText()Returns the tip text for this property.voidpauseExecution()Pauses the execution.protected voidpostRun(String error)Further clean-ups in derived classes.protected voidpreRun()Further initializations in derived classes.voidremoveFitnessChangeListener(GeneticFitnessChangeListener l)Removes the given listener from its internal list of listeners.protected voidreset()Resets the genetic algorihtm.voidresumeExecution()Resumes the execution.Stringrun()Runs the genetic algorithm.static voidrunGeneticAlgorithm(Class env, Class genetic, String[] options)Runs the genetic algorithm with the given options.StringseedTipText()Returns the tip text for this property.protected voidsetBestRange(Range value)Sets the best range of attributes.voidsetBestRange(String value)Sets the best range of attributes.voidsetFavorZeroes(boolean value)Sets whether 0s are favored over 1s.voidsetGene(int chromosome, int gene, boolean value)Sets the value of the specified gene.voidsetGene(int chromosome, int gene, int value)Sets the value of the specified gene.voidsetInitialSetupsProvider(AbstractInitialSetupsProvider value)Sets the initial setups provider to use.voidsetInitialWeights(String value)Sets the initial weights to use rather than random ones.voidsetMaxFitnessHistorySize(int value)Sets the maximum size for the fitness history.booleansetNewFitness(double fitness, Object setup, int chromosome, int[] weights)Sets a fitness and keep it if better.voidsetNotificationInterval(int value)Sets the notification interval in seconds.voidsetNumChrom(int value)Sets the number of chromosomes to use.voidsetNumThreads(int value)Sets the number of threads to use.voidsetSeed(long value)Sets the seed value to use, resets the random number generator.voidsetStoppingCriterion(AbstractStoppingCriterion value)Sets the stopping criterion to use.AbstractGeneticAlgorithmshallowCopy()Returns a shallow copy of itself, i.e., based on the commandline options.AbstractGeneticAlgorithmshallowCopy(boolean expand)Returns a shallow copy of itself, i.e., based on the commandline options.voidsort()Sorts genes and fitness arrays according to fitness.voidstopExecution()Stops the execution of the algorithm.StringstoppingCriterionTipText()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:
initializein 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:
resetin classAbstractOptionHandler
-
defineOptions
public void defineOptions()
Adds options to the internal list of options.- Specified by:
defineOptionsin interfaceOptionHandler- Overrides:
defineOptionsin classAbstractOptionHandler
-
setNumThreads
public void setNumThreads(int value)
Sets the number of threads to use.- Specified by:
setNumThreadsin interfaceThreadLimiter- Parameters:
value- the number of threads: -1 = # of CPUs/cores
-
getNumThreads
public int getNumThreads()
Returns the number of threads to use.- Specified by:
getNumThreadsin 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:
setSeedin interfaceRandomizable- Parameters:
value- the seed to use
-
getSeed
public long getSeed()
Returns the current seed value.- Specified by:
getSeedin interfaceRandomizable- Returns:
- the seed value
-
seedTipText
public String seedTipText()
Returns the tip text for this property.- Specified by:
seedTipTextin 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:
stopExecutionin interfaceStoppable
-
isStopped
public boolean isStopped()
Whether the execution has been stopped.- Specified by:
isStoppedin interfaceStoppableWithFeedback- Returns:
- true if stopped
-
pauseExecution
public void pauseExecution()
Pauses the execution.- Specified by:
pauseExecutionin interfacePausable
-
isPaused
public boolean isPaused()
Returns whether the object is currently paused.
-
resumeExecution
public void resumeExecution()
Resumes the execution.- Specified by:
resumeExecutionin 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:
shallowCopyin 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:
shallowCopyin 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
-
-