我正在为 Scala 中的 EA(进化算法)项目开发框架。在这一点上,我有一个实现通用 EA 代码的特征,并将诸如基因型转换和适应性测试之类的问题特定代码留给实现此特征的类。但是,由于测试不同的人口选择协议/策略,我不想在实际运行之前完全实现该特征。这给出了代码
trait EAProblem{
// common code ...
def fitness(ind:Individual):Double
def selectionStrategy(p: Population): List[(Individual, Double)]
def nextGeneration(p: Population): Population
}
/* Silly test problem */
abstract class OneMax(logPath: String) extends EAProblem {
def phenotype(ind:Individual) = {
ind.genotype
}
def fitness(ind: Individual): Double = {
ind.genotype.size.toFloat / ind.genotype.capacity
}
}
在运行时选择协议/策略:
object EASelectionStrategyProtocolDemo {
def main(args: Array[String]) {
val problem_impl = List[EAProblem](
// Full replacement
new OneMax("sigma_strat_full-rep_prot_onemax.log.dat") {
def selectionStrategy(p: Population): List[(Individual, Double)] =
SelectionStrategies.sigmaScalingMatingSelection(p)
def nextGeneration(p: Population): Population = SelectionProtocols.fullReplacement(p)
},
new OneMax("boltz_strat_full-rep_prot_onemax.log.dat") {
def selectionStrategy(p: Population): List[(Individual, Double)] =
SelectionStrategies.boltzmannSelection(p)
def nextGeneration(p: Population): Population = SelectionProtocols.fullReplacement(p)
})
for(problem <- problem_impl)
new Simulator(problem)
}
SelectionStrategies/SelectionProtocols 对象包含对 EAProblem 中其他代码的引用的clusures。
我现在想要的是使用反射(或其他一些机制)实例化其他抽象类的方法,比如 OneMax(我有很多)。伪代码:
val listOfClassNames = List("OneMax", "classA", "classB", ...)
for(className <- listOfClassNames){
class_sigma = Class.forname(className)
/*
Implement class_class with this code and instantiate it
def selectionStrategy(p: Population): List[(Individual, Double)] =
SelectionStrategies.sigmaScalingMatingSelection(p)
def nextGeneration(p: Population): Population = SelectionProtocols.fullReplacement(p)
*/
class_boltz = Class.forname(className)
/*
Implement class_boltz with this code and instantiate it
def selectionStrategy(p: Population): List[(Individual, Double)] =
SelectionStrategies.boltzmannSelection(p)
def nextGeneration(p: Population): Population = SelectionProtocols.fullReplacement(p)
*/
}