CPD Results
The following document contains the results of PMD's CPD 7.14.0.
Duplications
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithDoubleTournament.java | Samples | 129 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithProportionalTournament.java | Samples | 128 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithSRT.java | Samples | 134 |
.survivorSelectionPolicy(doubleTournament)
.build())
.combinationPolicy(ProgramRandomCombine.build())
.mutationPolicies(ProgramRandomMutate.of(0.10),
ProgramRandomPrune.of(0.12),
NodeReplacement.of(0.05),
ProgramApplyRules.of(SimplificationRules.SIMPLIFY_RULES))
.optimization(Optimization.MINIMIZE) // <3>
.termination(or(ofMaxGeneration(200), ofFitnessAtMost(0.00001)))
.fitness(computeFitness);
final EAConfiguration<Double> eaConfiguration = eaConfigurationBuilder.build();
// end::ea_config[]
final var eaExecutionContextBuilder = GPEAExecutionContexts.<Double>forGP(random);
EAExecutionContexts.enrichForScalarFitness(eaExecutionContextBuilder);
eaExecutionContextBuilder.populationSize(populationSize);
eaExecutionContextBuilder.numberOfPartitions(Math.max(1,
Runtime.getRuntime()
.availableProcessors() - 1));
eaExecutionContextBuilder.addEvolutionListeners(
EvolutionListeners.ofLogTopN(logger, 5, Comparator.<Double>reverseOrder(), (genotype) -> {
final TreeChromosome<Operation<?>> chromosome = (TreeChromosome<Operation<?>>) genotype.getChromosome(0);
final TreeNode<Operation<?>> root = chromosome.getRoot();
return TreeNodeUtils.toStringTreeNode(root);
}),
SymbolicRegressionUtils.csvLoggerDouble(csvFilename,
evolutionStep -> evolutionStep.fitness(),
evolutionStep -> (double) evolutionStep.individual()
.getChromosome(0, TreeChromosome.class)
.getSize()));
final EAExecutionContext<Double> eaExecutionContext = eaExecutionContextBuilder.build();
final EASystem<Double> eaSystem = EASystemFactory.from(eaConfiguration, eaExecutionContext);
final EvolutionResult<Double> evolutionResult = eaSystem.evolve();
final Genotype bestGenotype = evolutionResult.bestGenotype();
final TreeChromosome<Operation<?>> bestChromosome = (TreeChromosome<Operation<?>>) bestGenotype.getChromosome(0);
logger.info("Best genotype: {}", bestChromosome.getRoot());
logger.info("Best genotype - pretty print: {}", TreeNodeUtils.toStringTreeNode(bestChromosome.getRoot()));
}
public static void main(String[] args) throws IOException {
/**
* Parse CLI
*/
final CommandLineParser parser = new DefaultParser();
final Options options = new Options();
options.addOption(PARAM_DEST_CSV, LONG_PARAM_DEST_CSV, true, "destination csv file");
options.addOption(PARAM_POPULATION_SIZE, LONG_PARAM_POPULATION_SIZE, true, "Population size");
String csvFilename = DEFAULT_DEST_CSV;
int populationSize = DEFAULT_POPULATION_SIZE;
try {
final CommandLine line = parser.parse(options, args);
if (line.hasOption(PARAM_DEST_CSV)) {
csvFilename = line.getOptionValue(PARAM_DEST_CSV);
}
if (line.hasOption(PARAM_POPULATION_SIZE)) {
populationSize = Integer.parseInt(line.getOptionValue(PARAM_POPULATION_SIZE));
}
} catch (ParseException exp) {
cliError(options, "Unexpected exception:" + exp.getMessage());
}
logger.info("Population size: {}", populationSize);
logger.info("CSV output located at {}", csvFilename);
FileUtils.forceMkdirParent(new File(csvFilename));
final var symbolicRegression = new SymbolicRegressionWithDoubleTournament(); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithMOO.java | Samples | 153 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithMOOSPEA2.java | Samples | 178 |
.get(1)));
final EAExecutionContext<FitnessVector<Double>> eaExecutionContext = eaExecutionContextBuilder.build();
final EASystem<FitnessVector<Double>> eaSystem = EASystemFactory.from(eaConfiguration, eaExecutionContext);
final EvolutionResult<FitnessVector<Double>> evolutionResult = eaSystem.evolve();
final Genotype bestGenotype = evolutionResult.bestGenotype();
final TreeChromosome<Operation<?>> bestChromosome = (TreeChromosome<Operation<?>>) bestGenotype.getChromosome(0);
logger.info("Best genotype: {}", bestChromosome.getRoot());
logger.info("Best genotype - pretty print: {}", TreeNodeUtils.toStringTreeNode(bestChromosome.getRoot()));
final int depthIdx = 1;
for (int i = 0; i < 15; i++) {
final int depth = i;
final Optional<Integer> optIdx = IntStream.range(0,
evolutionResult.fitness()
.size())
.boxed()
.filter((idx) -> evolutionResult.fitness()
.get(idx)
.get(depthIdx) == depth)
.sorted((a, b) -> Double.compare(evolutionResult.fitness()
.get(a)
.get(0),
evolutionResult.fitness()
.get(b)
.get(0)))
.findFirst();
optIdx.stream()
.forEach((idx) -> {
final TreeChromosome<Operation<?>> treeChromosome = (TreeChromosome<Operation<?>>) evolutionResult
.population()
.get(idx)
.getChromosome(0);
logger.info("Best genotype for depth {} - score {} -> {}",
depth,
evolutionResult.fitness()
.get(idx)
.get(0),
TreeNodeUtils.toStringTreeNode(treeChromosome.getRoot()));
});
}
}
public static void main(String[] args) throws IOException {
/**
* Parse CLI
*/
final CommandLineParser parser = new DefaultParser();
final Options options = new Options();
options.addOption(PARAM_DEST_CSV, LONG_PARAM_DEST_CSV, true, "destination csv file");
options.addOption(PARAM_POPULATION_SIZE, LONG_PARAM_POPULATION_SIZE, true, "Population size");
String csvFilename = DEFAULT_DEST_CSV;
int populationSize = DEFAULT_POPULATION_SIZE;
try {
final CommandLine line = parser.parse(options, args);
if (line.hasOption(PARAM_DEST_CSV)) {
csvFilename = line.getOptionValue(PARAM_DEST_CSV);
}
if (line.hasOption(PARAM_POPULATION_SIZE)) {
populationSize = Integer.parseInt(line.getOptionValue(PARAM_POPULATION_SIZE));
}
} catch (ParseException exp) {
cliError(options, "Unexpected exception:" + exp.getMessage());
}
logger.info("Population size: {}", populationSize);
logger.info("CSV output located at {}", csvFilename);
FileUtils.forceMkdirParent(new File(csvFilename));
final var symbolicRegression = new SymbolicRegressionWithMOO(); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithConstantParsimonyPressure.java | Samples | 115 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithDoubleTournament.java | Samples | 137 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithProportionalTournament.java | Samples | 136 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithSRT.java | Samples | 142 |
.termination(or(ofMaxGeneration(200), ofFitnessAtMost(20.0d))) // <3>
.fitness(computeFitness);
final EAConfiguration<Double> eaConfiguration = eaConfigurationBuilder.build();
// end::ea_config[]
final var eaExecutionContextBuilder = GPEAExecutionContexts.<Double>forGP(random);
EAExecutionContexts.enrichForScalarFitness(eaExecutionContextBuilder);
eaExecutionContextBuilder.populationSize(populationSize);
eaExecutionContextBuilder.numberOfPartitions(Math.max(1,
Runtime.getRuntime()
.availableProcessors() - 1));
eaExecutionContextBuilder.addEvolutionListeners(
EvolutionListeners.ofLogTopN(logger, 5, Comparator.<Double>reverseOrder(), (genotype) -> {
final TreeChromosome<Operation<?>> chromosome = (TreeChromosome<Operation<?>>) genotype.getChromosome(0);
final TreeNode<Operation<?>> root = chromosome.getRoot();
return TreeNodeUtils.toStringTreeNode(root);
}),
SymbolicRegressionUtils.csvLoggerDouble(csvFilename,
evolutionStep -> evolutionStep.fitness(),
evolutionStep -> (double) evolutionStep.individual()
.getChromosome(0, TreeChromosome.class)
.getSize()));
final EAExecutionContext<Double> eaExecutionContext = eaExecutionContextBuilder.build();
final EASystem<Double> eaSystem = EASystemFactory.from(eaConfiguration, eaExecutionContext);
final EvolutionResult<Double> evolutionResult = eaSystem.evolve();
final Genotype bestGenotype = evolutionResult.bestGenotype();
final TreeChromosome<Operation<?>> bestChromosome = (TreeChromosome<Operation<?>>) bestGenotype.getChromosome(0);
logger.info("Best genotype: {}", bestChromosome.getRoot());
logger.info("Best genotype - pretty print: {}", TreeNodeUtils.toStringTreeNode(bestChromosome.getRoot()));
}
public static void main(String[] args) throws IOException {
/**
* Parse CLI
*/
final CommandLineParser parser = new DefaultParser();
final Options options = new Options();
options.addOption(PARAM_DEST_CSV, LONG_PARAM_DEST_CSV, true, "destination csv file");
options.addOption(PARAM_POPULATION_SIZE, LONG_PARAM_POPULATION_SIZE, true, "Population size");
String csvFilename = DEFAULT_DEST_CSV;
int populationSize = DEFAULT_POPULATION_SIZE;
try {
final CommandLine line = parser.parse(options, args);
if (line.hasOption(PARAM_DEST_CSV)) {
csvFilename = line.getOptionValue(PARAM_DEST_CSV);
}
if (line.hasOption(PARAM_POPULATION_SIZE)) {
populationSize = Integer.parseInt(line.getOptionValue(PARAM_POPULATION_SIZE));
}
} catch (ParseException exp) {
cliError(options, "Unexpected exception:" + exp.getMessage());
}
logger.info("Population size: {}", populationSize);
logger.info("CSV output located at {}", csvFilename);
FileUtils.forceMkdirParent(new File(csvFilename));
final var symbolicRegression = new SymbolicRegressionWithConstantParsimonyPressure(); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithMOO.java | Samples | 67 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithMOOSPEA2.java | Samples | 69 |
formatter.printHelp(SymbolicRegressionWithMOO.class.getSimpleName(), options);
System.exit(-1);
}
@SuppressWarnings("unchecked")
public void run(String csvFilename, int populationSize) {
Validate.isTrue(StringUtils.isNotBlank(csvFilename));
Validate.isTrue(populationSize > 0);
final Random random = new Random();
final Program program = SymbolicRegressionUtils.buildProgram(random);
final Comparator<Genotype> deduplicator = (a, b) -> TreeNodeUtils.compare(a, b, 0);
// tag::compute_fitness[]
final Fitness<FitnessVector<Double>> computeFitness = (genoType) -> {
final TreeChromosome<Operation<?>> chromosome = (TreeChromosome<Operation<?>>) genoType.getChromosome(0);
final Double[][] inputs = new Double[100][1];
for (int i = 0; i < 100; i++) {
inputs[i][0] = (i - 50) * 1.2;
}
double mse = 0;
for (final Double[] input : inputs) {
final double x = input[0];
final double expected = SymbolicRegressionUtils.evaluate(x);
final Object result = ProgramUtils.execute(chromosome, input);
if (Double.isFinite(expected)) {
final Double resultDouble = (Double) result;
if (Double.isFinite(resultDouble)) {
mse += (expected - resultDouble) * (expected - resultDouble);
} else {
mse += 1_000_000_000;
}
}
}
return Double.isFinite(mse) ? new FitnessVector<Double>(mse / 100.0,
(double) chromosome.getRoot()
.getSize())
: new FitnessVector<Double>(Double.MAX_VALUE, Double.MAX_VALUE);
};
// end::compute_fitness[]
// tag::ea_config[]
final var eaConfigurationBuilder = new EAConfiguration.Builder<FitnessVector<Double>>();
eaConfigurationBuilder.chromosomeSpecs(ProgramTreeChromosomeSpec.of(program)) // <1>
.parentSelectionPolicy(TournamentNSGA2Selection.ofFitnessVector(2, 3, deduplicator)) // <2>
.replacementStrategy(Elitism.builder() // <3> | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithConstantParsimonyPressure.java | Samples | 130 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithTarpeianMethod.java | Samples | 132 |
final TreeChromosome<Operation<?>> chromosome = (TreeChromosome<Operation<?>>) genotype.getChromosome(0);
final TreeNode<Operation<?>> root = chromosome.getRoot();
return TreeNodeUtils.toStringTreeNode(root);
}),
SymbolicRegressionUtils.csvLoggerDouble(csvFilename,
evolutionStep -> evolutionStep.fitness(),
evolutionStep -> (double) evolutionStep.individual()
.getChromosome(0, TreeChromosome.class)
.getSize()));
final EAExecutionContext<Double> eaExecutionContext = eaExecutionContextBuilder.build();
final EASystem<Double> eaSystem = EASystemFactory.from(eaConfiguration, eaExecutionContext);
final EvolutionResult<Double> evolutionResult = eaSystem.evolve();
final Genotype bestGenotype = evolutionResult.bestGenotype();
final TreeChromosome<Operation<?>> bestChromosome = (TreeChromosome<Operation<?>>) bestGenotype.getChromosome(0);
logger.info("Best genotype: {}", bestChromosome.getRoot());
logger.info("Best genotype - pretty print: {}", TreeNodeUtils.toStringTreeNode(bestChromosome.getRoot()));
}
public static void main(String[] args) throws IOException {
/**
* Parse CLI
*/
final CommandLineParser parser = new DefaultParser();
final Options options = new Options();
options.addOption(PARAM_DEST_CSV, LONG_PARAM_DEST_CSV, true, "destination csv file");
options.addOption(PARAM_POPULATION_SIZE, LONG_PARAM_POPULATION_SIZE, true, "Population size");
String csvFilename = DEFAULT_DEST_CSV;
int populationSize = DEFAULT_POPULATION_SIZE;
try {
final CommandLine line = parser.parse(options, args);
if (line.hasOption(PARAM_DEST_CSV)) {
csvFilename = line.getOptionValue(PARAM_DEST_CSV);
}
if (line.hasOption(PARAM_POPULATION_SIZE)) {
populationSize = Integer.parseInt(line.getOptionValue(PARAM_POPULATION_SIZE));
}
} catch (ParseException exp) {
cliError(options, "Unexpected exception:" + exp.getMessage());
}
logger.info("Population size: {}", populationSize);
logger.info("CSV output located at {}", csvFilename);
FileUtils.forceMkdirParent(new File(csvFilename));
final var symbolicRegression = new SymbolicRegressionWithConstantParsimonyPressure(); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithDoubleTournament.java | Samples | 152 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithTarpeianMethod.java | Samples | 132 |
final TreeChromosome<Operation<?>> chromosome = (TreeChromosome<Operation<?>>) genotype.getChromosome(0);
final TreeNode<Operation<?>> root = chromosome.getRoot();
return TreeNodeUtils.toStringTreeNode(root);
}),
SymbolicRegressionUtils.csvLoggerDouble(csvFilename,
evolutionStep -> evolutionStep.fitness(),
evolutionStep -> (double) evolutionStep.individual()
.getChromosome(0, TreeChromosome.class)
.getSize()));
final EAExecutionContext<Double> eaExecutionContext = eaExecutionContextBuilder.build();
final EASystem<Double> eaSystem = EASystemFactory.from(eaConfiguration, eaExecutionContext);
final EvolutionResult<Double> evolutionResult = eaSystem.evolve();
final Genotype bestGenotype = evolutionResult.bestGenotype();
final TreeChromosome<Operation<?>> bestChromosome = (TreeChromosome<Operation<?>>) bestGenotype.getChromosome(0);
logger.info("Best genotype: {}", bestChromosome.getRoot());
logger.info("Best genotype - pretty print: {}", TreeNodeUtils.toStringTreeNode(bestChromosome.getRoot()));
}
public static void main(String[] args) throws IOException {
/**
* Parse CLI
*/
final CommandLineParser parser = new DefaultParser();
final Options options = new Options();
options.addOption(PARAM_DEST_CSV, LONG_PARAM_DEST_CSV, true, "destination csv file");
options.addOption(PARAM_POPULATION_SIZE, LONG_PARAM_POPULATION_SIZE, true, "Population size");
String csvFilename = DEFAULT_DEST_CSV;
int populationSize = DEFAULT_POPULATION_SIZE;
try {
final CommandLine line = parser.parse(options, args);
if (line.hasOption(PARAM_DEST_CSV)) {
csvFilename = line.getOptionValue(PARAM_DEST_CSV);
}
if (line.hasOption(PARAM_POPULATION_SIZE)) {
populationSize = Integer.parseInt(line.getOptionValue(PARAM_POPULATION_SIZE));
}
} catch (ParseException exp) {
cliError(options, "Unexpected exception:" + exp.getMessage());
}
logger.info("Population size: {}", populationSize);
logger.info("CSV output located at {}", csvFilename);
FileUtils.forceMkdirParent(new File(csvFilename));
final var symbolicRegression = new SymbolicRegressionWithDoubleTournament(); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithProportionalTournament.java | Samples | 151 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithTarpeianMethod.java | Samples | 132 |
final TreeChromosome<Operation<?>> chromosome = (TreeChromosome<Operation<?>>) genotype.getChromosome(0);
final TreeNode<Operation<?>> root = chromosome.getRoot();
return TreeNodeUtils.toStringTreeNode(root);
}),
SymbolicRegressionUtils.csvLoggerDouble(csvFilename,
evolutionStep -> evolutionStep.fitness(),
evolutionStep -> (double) evolutionStep.individual()
.getChromosome(0, TreeChromosome.class)
.getSize()));
final EAExecutionContext<Double> eaExecutionContext = eaExecutionContextBuilder.build();
final EASystem<Double> eaSystem = EASystemFactory.from(eaConfiguration, eaExecutionContext);
final EvolutionResult<Double> evolutionResult = eaSystem.evolve();
final Genotype bestGenotype = evolutionResult.bestGenotype();
final TreeChromosome<Operation<?>> bestChromosome = (TreeChromosome<Operation<?>>) bestGenotype.getChromosome(0);
logger.info("Best genotype: {}", bestChromosome.getRoot());
logger.info("Best genotype - pretty print: {}", TreeNodeUtils.toStringTreeNode(bestChromosome.getRoot()));
}
public static void main(String[] args) throws IOException {
/**
* Parse CLI
*/
final CommandLineParser parser = new DefaultParser();
final Options options = new Options();
options.addOption(PARAM_DEST_CSV, LONG_PARAM_DEST_CSV, true, "destination csv file");
options.addOption(PARAM_POPULATION_SIZE, LONG_PARAM_POPULATION_SIZE, true, "Population size");
String csvFilename = DEFAULT_DEST_CSV;
int populationSize = DEFAULT_POPULATION_SIZE;
try {
final CommandLine line = parser.parse(options, args);
if (line.hasOption(PARAM_DEST_CSV)) {
csvFilename = line.getOptionValue(PARAM_DEST_CSV);
}
if (line.hasOption(PARAM_POPULATION_SIZE)) {
populationSize = Integer.parseInt(line.getOptionValue(PARAM_POPULATION_SIZE));
}
} catch (ParseException exp) {
cliError(options, "Unexpected exception:" + exp.getMessage());
}
logger.info("Population size: {}", populationSize);
logger.info("CSV output located at {}", csvFilename);
FileUtils.forceMkdirParent(new File(csvFilename));
final var symbolicRegression = new SymbolicRegressionWithProportionalTournament(); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithSRT.java | Samples | 157 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithTarpeianMethod.java | Samples | 132 |
final TreeChromosome<Operation<?>> chromosome = (TreeChromosome<Operation<?>>) genotype.getChromosome(0);
final TreeNode<Operation<?>> root = chromosome.getRoot();
return TreeNodeUtils.toStringTreeNode(root);
}),
SymbolicRegressionUtils.csvLoggerDouble(csvFilename,
evolutionStep -> evolutionStep.fitness(),
evolutionStep -> (double) evolutionStep.individual()
.getChromosome(0, TreeChromosome.class)
.getSize()));
final EAExecutionContext<Double> eaExecutionContext = eaExecutionContextBuilder.build();
final EASystem<Double> eaSystem = EASystemFactory.from(eaConfiguration, eaExecutionContext);
final EvolutionResult<Double> evolutionResult = eaSystem.evolve();
final Genotype bestGenotype = evolutionResult.bestGenotype();
final TreeChromosome<Operation<?>> bestChromosome = (TreeChromosome<Operation<?>>) bestGenotype.getChromosome(0);
logger.info("Best genotype: {}", bestChromosome.getRoot());
logger.info("Best genotype - pretty print: {}", TreeNodeUtils.toStringTreeNode(bestChromosome.getRoot()));
}
public static void main(String[] args) throws IOException {
/**
* Parse CLI
*/
final CommandLineParser parser = new DefaultParser();
final Options options = new Options();
options.addOption(PARAM_DEST_CSV, LONG_PARAM_DEST_CSV, true, "destination csv file");
options.addOption(PARAM_POPULATION_SIZE, LONG_PARAM_POPULATION_SIZE, true, "Population size");
String csvFilename = DEFAULT_DEST_CSV;
int populationSize = DEFAULT_POPULATION_SIZE;
try {
final CommandLine line = parser.parse(options, args);
if (line.hasOption(PARAM_DEST_CSV)) {
csvFilename = line.getOptionValue(PARAM_DEST_CSV);
}
if (line.hasOption(PARAM_POPULATION_SIZE)) {
populationSize = Integer.parseInt(line.getOptionValue(PARAM_POPULATION_SIZE));
}
} catch (ParseException exp) {
cliError(options, "Unexpected exception:" + exp.getMessage());
}
logger.info("Population size: {}", populationSize);
logger.info("CSV output located at {}", csvFilename);
FileUtils.forceMkdirParent(new File(csvFilename));
final var symbolicRegression = new SymbolicRegressionWithSRT(); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/mixturemodel/ClusteringUtils.java | Samples | 36 |
| net/bmahe/genetics4j/samples/mixturemodel/ClusteringUtils.java | Samples | 86 |
final var fChromosome = genotype.getChromosome(0, DoubleChromosome.class);
final int[] clusters = new int[samples.length];
final double[] bestProb = new double[samples.length];
for (int c = 0; c < clusters.length; c++) {
clusters[c] = 0;
bestProb[c] = Double.MIN_VALUE;
}
double sumAlpha = 0.0f;
int k = 0;
while (k < fChromosome.getSize()) {
sumAlpha += fChromosome.getAllele(k);
k += distributionNumParameters;
}
int i = 0;
int clusterIndex = 0;
while (i < fChromosome.getSize()) {
final double alpha = fChromosome.getAllele(i) / sumAlpha;
final double[] mean = new double[] { fChromosome.getAllele(i + 1), fChromosome.getAllele(i + 2) };
final double[][] covariance = new double[][] {
{ fChromosome.getAllele(i + 3) - 15, fChromosome.getAllele(i + 4) - 15 },
{ fChromosome.getAllele(i + 4) - 15, fChromosome.getAllele(i + 5) - 15 } };
try {
final var multivariateNormalDistribution = new MultivariateNormalDistribution(mean, covariance);
for (int j = 0; j < samples.length; j++) {
float likelyhood = (float) (alpha * multivariateNormalDistribution.density(samples[j]));
if (clusters[j] < 0 || bestProb[j] < likelyhood) {
bestProb[j] = likelyhood;
clusters[j] = clusterIndex;
}
}
} catch (NonPositiveDefiniteMatrixException | SingularMatrixException | MathUnsupportedOperationException e) {
}
i += distributionNumParameters;
clusterIndex++;
}
return clusters;
}
public static int[] assignClustersFloatChromosome(final int distributionNumParameters, final double[][] samples, | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithDoubleTournament.java | Samples | 69 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithSRT.java | Samples | 69 |
formatter.printHelp(SymbolicRegressionWithDoubleTournament.class.getSimpleName(), options);
System.exit(-1);
}
@SuppressWarnings("unchecked")
public void run(String csvFilename, int populationSize) {
Validate.isTrue(StringUtils.isNotBlank(csvFilename));
Validate.isTrue(populationSize > 0);
final Random random = new Random();
final Program program = SymbolicRegressionUtils.buildProgram(random);
// tag::compute_fitness[]
final Double[][] inputs = new Double[100][1];
for (int i = 0; i < 100; i++) {
inputs[i][0] = (i - 50) * 1.2;
}
final Fitness<Double> computeFitness = (genoType) -> {
final TreeChromosome<Operation<?>> chromosome = (TreeChromosome<Operation<?>>) genoType.getChromosome(0);
double mse = 0;
for (final Double[] input : inputs) {
final double x = input[0];
final double expected = SymbolicRegressionUtils.evaluate(x);
final Object result = ProgramUtils.execute(chromosome, input);
if (Double.isFinite(expected)) {
final Double resultDouble = (Double) result;
mse += Double.isFinite(resultDouble) ? (expected - resultDouble) * (expected - resultDouble)
: 1_000_000_000;
}
}
return Double.isFinite(mse) ? mse / 100.0d : Double.MAX_VALUE;
};
// end::compute_fitness[]
// tag::double_tournament[]
final Comparator<Individual<Double>> parsimonyComparator = (a, b) -> {
final var treeChromosomeA = a.genotype()
.getChromosome(0, TreeChromosome.class);
final var treeChromosomeB = b.genotype()
.getChromosome(0, TreeChromosome.class);
return Integer.compare(treeChromosomeA.getSize(), treeChromosomeB.getSize()); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithConstantParsimonyPressure.java | Samples | 67 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithTarpeianMethod.java | Samples | 67 |
formatter.printHelp(SymbolicRegressionWithConstantParsimonyPressure.class.getSimpleName(), options);
System.exit(-1);
}
@SuppressWarnings("unchecked")
public void run(String csvFilename, int populationSize) {
Validate.isTrue(StringUtils.isNotBlank(csvFilename));
Validate.isTrue(populationSize > 0);
final Random random = new Random();
final Program program = SymbolicRegressionUtils.buildProgram(random);
// tag::compute_fitness[]
final Fitness<Double> computeFitness = (genoType) -> {
final TreeChromosome<Operation<?>> chromosome = (TreeChromosome<Operation<?>>) genoType.getChromosome(0);
final Double[][] inputs = new Double[100][1];
for (int i = 0; i < 100; i++) {
inputs[i][0] = (i - 50) * 1.2;
}
double mse = 0;
for (final Double[] input : inputs) {
final double x = input[0];
final double expected = SymbolicRegressionUtils.evaluate(x);
final Object result = ProgramUtils.execute(chromosome, input);
if (Double.isFinite(expected)) {
final Double resultDouble = (Double) result;
mse += Double.isFinite(resultDouble) ? (expected - resultDouble) * (expected - resultDouble)
: 1_000_000_000;
}
}
return Double.isFinite(mse) ? mse / 100.0 + 1.5 * chromosome.getSize() : Double.MAX_VALUE; // <1> | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithConstantParsimonyPressure.java | Samples | 67 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithProportionalTournament.java | Samples | 69 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithTarpeianMethod.java | Samples | 67 |
formatter.printHelp(SymbolicRegressionWithConstantParsimonyPressure.class.getSimpleName(), options);
System.exit(-1);
}
@SuppressWarnings("unchecked")
public void run(String csvFilename, int populationSize) {
Validate.isTrue(StringUtils.isNotBlank(csvFilename));
Validate.isTrue(populationSize > 0);
final Random random = new Random();
final Program program = SymbolicRegressionUtils.buildProgram(random);
// tag::compute_fitness[]
final Fitness<Double> computeFitness = (genoType) -> {
final TreeChromosome<Operation<?>> chromosome = (TreeChromosome<Operation<?>>) genoType.getChromosome(0);
final Double[][] inputs = new Double[100][1];
for (int i = 0; i < 100; i++) {
inputs[i][0] = (i - 50) * 1.2;
}
double mse = 0;
for (final Double[] input : inputs) {
final double x = input[0];
final double expected = SymbolicRegressionUtils.evaluate(x);
final Object result = ProgramUtils.execute(chromosome, input);
if (Double.isFinite(expected)) {
final Double resultDouble = (Double) result;
mse += Double.isFinite(resultDouble) ? (expected - resultDouble) * (expected - resultDouble)
: 1_000_000_000;
}
}
return Double.isFinite(mse) ? mse / 100.0 + 1.5 * chromosome.getSize() : Double.MAX_VALUE; // <1> | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/gp/mutation/NodeReplacementMutator.java | Genetic Programming | 139 |
| net/bmahe/genetics4j/gp/mutation/ProgramRandomPruneMutator.java | Genetic Programming | 69 |
}
}
@Override
public Genotype mutate(final long generation, final Genotype original) {
Validate.isTrue(generation >= 0);
Objects.requireNonNull(original);
if (randomGenerator.nextDouble() < populationMutationProbability == false) {
return original;
}
final Chromosome[] newChromosomes = new Chromosome[original.getSize()];
final Chromosome[] chromosomes = original.getChromosomes();
for (int chromosomeIndex = 0; chromosomeIndex < chromosomes.length; chromosomeIndex++) {
final ChromosomeSpec chromosomeSpec = eaConfiguration.getChromosomeSpec(chromosomeIndex);
final Chromosome chromosome = chromosomes[chromosomeIndex];
if (chromosomeSpec instanceof ProgramTreeChromosomeSpec == false) {
throw new IllegalArgumentException("This mutator does not support chromosome specs " + chromosomeSpec);
}
if (chromosome instanceof TreeChromosome<?> == false) {
throw new IllegalArgumentException(
"This mutator does not support chromosome of type " + chromosome.getClass()
.getSimpleName());
}
final ProgramTreeChromosomeSpec programTreeChromosomeSpec = (ProgramTreeChromosomeSpec) chromosomeSpec;
final TreeChromosome<Operation<?>> treeChromosome = (TreeChromosome<Operation<?>>) chromosome;
final int chromosomeSize = treeChromosome.getSize();
if (chromosomeSize > 2) {
final int cutPoint = randomGenerator.nextInt(chromosomeSize - 1) + 1;
final TreeNode<Operation<?>> root = treeChromosome.getRoot();
final TreeNode<Operation<?>> newRoot = duplicateAndReplaceNode(programTreeChromosomeSpec.program(), | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/core/selection/SelectiveRefinementTournamentSelector.java | Core | 33 |
| net/bmahe/genetics4j/gp/selection/DoubleTournamentSelector.java | Genetic Programming | 36 |
this.randomGenerator = _randomGenerator;
}
protected Individual<T> randomIndividual(final List<Genotype> population, final List<T> fitnessScore) {
Objects.requireNonNull(population);
Objects.requireNonNull(fitnessScore);
Validate.isTrue(fitnessScore.size() > 0);
Validate.isTrue(population.size() == fitnessScore.size());
final int candidateIndex = randomGenerator.nextInt(fitnessScore.size());
return Individual.of(population.get(candidateIndex), fitnessScore.get(candidateIndex));
}
protected Individual<T> selectForFitness(final AbstractEAConfiguration<T> eaConfiguration,
final Comparator<Individual<T>> fitnessComparator, final int numCandidates, final List<Genotype> population,
final List<T> fitnessScore) {
Objects.requireNonNull(population);
Objects.requireNonNull(fitnessScore);
Validate.isTrue(fitnessScore.isEmpty() == false);
return IntStream.range(0, numCandidates)
.boxed()
.map(i -> randomIndividual(population, fitnessScore))
.max((a, b) -> fitnessComparator.compare(a, b))
.get();
}
protected Individual<T> selectForRefinement(final Comparator<Individual<T>> refinementComparator, | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/clustering/FitnessUtils.java | Samples | 132 |
| net/bmahe/genetics4j/samples/clustering/FitnessUtils.java | Samples | 165 |
public final static Fitness<Double> computeFitness(final int numDataPoints, final double[][] data,
double[][] distances, final int numClusters) {
Validate.notNull(data);
Validate.notNull(distances);
Validate.isTrue(numDataPoints > 0);
Validate.isTrue(numDataPoints == data.length);
Validate.isTrue(numDataPoints == distances.length);
Validate.isTrue(numClusters > 0);
return (genoType) -> {
final double[][] clusters = PhenotypeUtils.toPhenotype(genoType);
final int[] closestClusterIndex = assignDataToClusters(data, distances, clusters);
final Map<Integer, Set<Integer>> clusterToMembers = new HashMap<>();
for (int i = 0; i < numDataPoints; i++) {
final var members = clusterToMembers.computeIfAbsent(closestClusterIndex[i], k -> new HashSet<>());
members.add(i);
}
double sum_si = 0.0;
for (int i = 0; i < numDataPoints; i++) {
sum_si += computeSilhouetteScore(data, distances, numClusters, clusterToMembers, closestClusterIndex, i);
} | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/mixturemodel/ClusteringUtils.java | Samples | 133 |
| net/bmahe/genetics4j/samples/mixturemodel/ClusteringUtils.java | Samples | 160 |
public static void persistClusters(final float[] x, final float[] y, final int[] cluster, final String filename)
throws IOException {
Validate.isTrue(x.length == y.length);
Validate.isTrue(x.length == cluster.length);
logger.info("Saving clusters to CSV: {}", filename);
final CSVPrinter csvPrinter;
try {
csvPrinter = CSVFormat.DEFAULT.withAutoFlush(true)
.withHeader(new String[] { "cluster", "x", "y" })
.print(Path.of(filename), StandardCharsets.UTF_8);
} catch (IOException e) {
logger.error("Could not open {}", filename, e);
throw new RuntimeException("Could not open file " + filename, e);
}
for (int i = 0; i < cluster.length; i++) {
try {
csvPrinter.printRecord(cluster[i], x[i], y[i]);
} catch (IOException e) {
throw new RuntimeException("Could not write data", e);
}
}
csvPrinter.close(true);
}
// TODO fix duplication
public static void persistClusters(final double[] x, final double[] y, final int[] cluster, final String filename) | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/mixturemodel/MooCPU.java | Samples | 83 |
| net/bmahe/genetics4j/samples/mixturemodel/SingleObjectiveMethod.java | Samples | 78 |
final float alpha = fChromosome.getAllele(i) / sumAlpha;
if (alpha > 0.0001) {
final double[] mean = new double[] { fChromosome.getAllele(i + 1), fChromosome.getAllele(i + 2) };
final double[][] covariances = new double[][] {
{ fChromosome.getAllele(i + 3) - 15, fChromosome.getAllele(i + 4) - 15 },
{ fChromosome.getAllele(i + 4) - 15, fChromosome.getAllele(i + 5) - 15 } };
try {
final var multivariateNormalDistribution = new MultivariateNormalDistribution(mean, covariances);
for (int j = 0; j < samples.length; j++) {
final var density = multivariateNormalDistribution.density(samples[j]);
likelyhoods[j] += alpha * density;
}
} catch (NonPositiveDefiniteMatrixException | MathUnsupportedOperationException
| SingularMatrixException e) {
}
}
i += distributionNumParameters;
} | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithConstantParsimonyPressure.java | Samples | 149 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithMOO.java | Samples | 197 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithMOOSPEA2.java | Samples | 222 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithProportionalTournament.java | Samples | 170 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithSRT.java | Samples | 176 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithTarpeianMethod.java | Samples | 152 |
}
public static void main(String[] args) throws IOException {
/**
* Parse CLI
*/
final CommandLineParser parser = new DefaultParser();
final Options options = new Options();
options.addOption(PARAM_DEST_CSV, LONG_PARAM_DEST_CSV, true, "destination csv file");
options.addOption(PARAM_POPULATION_SIZE, LONG_PARAM_POPULATION_SIZE, true, "Population size");
String csvFilename = DEFAULT_DEST_CSV;
int populationSize = DEFAULT_POPULATION_SIZE;
try {
final CommandLine line = parser.parse(options, args);
if (line.hasOption(PARAM_DEST_CSV)) {
csvFilename = line.getOptionValue(PARAM_DEST_CSV);
}
if (line.hasOption(PARAM_POPULATION_SIZE)) {
populationSize = Integer.parseInt(line.getOptionValue(PARAM_POPULATION_SIZE));
}
} catch (ParseException exp) {
cliError(options, "Unexpected exception:" + exp.getMessage());
}
logger.info("Population size: {}", populationSize);
logger.info("CSV output located at {}", csvFilename);
FileUtils.forceMkdirParent(new File(csvFilename));
final var symbolicRegression = new SymbolicRegressionWithConstantParsimonyPressure(); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithDoubleTournament.java | Samples | 171 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithMOO.java | Samples | 197 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithMOOSPEA2.java | Samples | 222 |
}
public static void main(String[] args) throws IOException {
/**
* Parse CLI
*/
final CommandLineParser parser = new DefaultParser();
final Options options = new Options();
options.addOption(PARAM_DEST_CSV, LONG_PARAM_DEST_CSV, true, "destination csv file");
options.addOption(PARAM_POPULATION_SIZE, LONG_PARAM_POPULATION_SIZE, true, "Population size");
String csvFilename = DEFAULT_DEST_CSV;
int populationSize = DEFAULT_POPULATION_SIZE;
try {
final CommandLine line = parser.parse(options, args);
if (line.hasOption(PARAM_DEST_CSV)) {
csvFilename = line.getOptionValue(PARAM_DEST_CSV);
}
if (line.hasOption(PARAM_POPULATION_SIZE)) {
populationSize = Integer.parseInt(line.getOptionValue(PARAM_POPULATION_SIZE));
}
} catch (ParseException exp) {
cliError(options, "Unexpected exception:" + exp.getMessage());
}
logger.info("Population size: {}", populationSize);
logger.info("CSV output located at {}", csvFilename);
FileUtils.forceMkdirParent(new File(csvFilename));
final var symbolicRegression = new SymbolicRegressionWithDoubleTournament(); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithMOO.java | Samples | 130 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithMOOSPEA2.java | Samples | 128 |
.anyMatch(fv -> fv.get(0) <= 0.000001 && fv.get(1) <= 20))) // <4> .fitness(computeFitness); final EAConfiguration<FitnessVector<Double>> eaConfiguration = eaConfigurationBuilder.build(); // end::ea_config[] // tag::eae_moo[] final var eaExecutionContextBuilder = GPEAExecutionContexts.<FitnessVector<Double>>forGP(random); // end::eae_moo[] eaExecutionContextBuilder.populationSize(populationSize); eaExecutionContextBuilder.numberOfPartitions(Math.max(1, Runtime.getRuntime() .availableProcessors() - 3)); eaExecutionContextBuilder.addEvolutionListeners( EvolutionListeners.ofLogTopN(logger, 5, Comparator.<FitnessVector<Double>, Double>comparing(fv -> fv.get(0)) .reversed(), (genotype) -> TreeNodeUtils.toStringTreeNode(genotype, 0)), SymbolicRegressionUtils.csvLogger(csvFilename, evolutionStep -> evolutionStep.fitness() .get(0), evolutionStep -> evolutionStep.fitness() .get(1))); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/core/combination/singlepointarithmetic/IntChromosomeSinglePointArithmetic.java | Core | 24 |
| net/bmahe/genetics4j/core/combination/singlepointcrossover/IntChromosomeSinglePointCrossover.java | Core | 21 |
}
@Override
public List<Chromosome> combine(final AbstractEAConfiguration<T> eaConfiguration, final Chromosome chromosome1,
final T firstParentFitness, final Chromosome chromosome2, final T secondParentFitness) {
Validate.notNull(chromosome1);
Validate.notNull(chromosome2);
Validate.isInstanceOf(IntChromosome.class, chromosome1);
Validate.isInstanceOf(IntChromosome.class, chromosome2);
Validate.isTrue(chromosome1.getNumAlleles() == chromosome2.getNumAlleles());
final int alleleSplit = randomGenerator.nextInt(chromosome1.getNumAlleles());
final IntChromosome intChromosome1 = (IntChromosome) chromosome1;
final IntChromosome intChromosome2 = (IntChromosome) chromosome2;
final int numAlleles = chromosome1.getNumAlleles();
final int[] firstChildValues = new int[numAlleles];
final int[] secondChildValues = new int[numAlleles];
for (int i = 0; i < numAlleles; i++) { | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithConstantParsimonyPressure.java | Samples | 76 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithEnforcedMaxDepth.java | Samples | 42 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithProportionalTournament.java | Samples | 78 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithTarpeianMethod.java | Samples | 76 |
final Random random = new Random();
final Program program = SymbolicRegressionUtils.buildProgram(random);
// tag::compute_fitness[]
final Fitness<Double> computeFitness = (genoType) -> {
final TreeChromosome<Operation<?>> chromosome = (TreeChromosome<Operation<?>>) genoType.getChromosome(0);
final Double[][] inputs = new Double[100][1];
for (int i = 0; i < 100; i++) {
inputs[i][0] = (i - 50) * 1.2;
}
double mse = 0;
for (final Double[] input : inputs) {
final double x = input[0];
final double expected = SymbolicRegressionUtils.evaluate(x);
final Object result = ProgramUtils.execute(chromosome, input);
if (Double.isFinite(expected)) { | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/moo/nsga2/impl/NSGA2Selector.java | Multi-Objective Optimization | 50 |
| net/bmahe/genetics4j/moo/nsga2/impl/TournamentNSGA2Selector.java | Multi-Objective Optimization | 54 |
final Comparator<Genotype> individualDeduplicator = nsga2Selection.deduplicate()
.get();
final Set<Genotype> seenGenotype = new TreeSet<>(individualDeduplicator);
for (int i = 0; i < population.size(); i++) {
final Genotype genotype = population.get(i);
final T fitness = fitnessScore.get(i);
if (seenGenotype.add(genotype)) {
individuals.add(genotype, fitness);
}
}
} else {
for (int i = 0; i < population.size(); i++) {
final Genotype genotype = population.get(i);
final T fitness = fitnessScore.get(i);
individuals.add(genotype, fitness);
}
}
logger.debug("Selecting {} individuals from a population of {}", numIndividuals, individuals.size());
final int numberObjectives = nsga2Selection.numberObjectives(); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithConstantParsimonyPressure.java | Samples | 81 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithMOO.java | Samples | 83 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithMOOSPEA2.java | Samples | 85 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithProportionalTournament.java | Samples | 83 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithTarpeianMethod.java | Samples | 81 |
final Fitness<Double> computeFitness = (genoType) -> {
final TreeChromosome<Operation<?>> chromosome = (TreeChromosome<Operation<?>>) genoType.getChromosome(0);
final Double[][] inputs = new Double[100][1];
for (int i = 0; i < 100; i++) {
inputs[i][0] = (i - 50) * 1.2;
}
double mse = 0;
for (final Double[] input : inputs) {
final double x = input[0];
final double expected = SymbolicRegressionUtils.evaluate(x);
final Object result = ProgramUtils.execute(chromosome, input);
if (Double.isFinite(expected)) {
final Double resultDouble = (Double) result; | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/gp/mutation/NodeReplacementMutator.java | Genetic Programming | 152 |
| net/bmahe/genetics4j/gp/mutation/ProgramRandomMutateMutator.java | Genetic Programming | 91 |
| net/bmahe/genetics4j/gp/mutation/ProgramRandomPruneMutator.java | Genetic Programming | 82 |
final Chromosome[] chromosomes = original.getChromosomes();
for (int chromosomeIndex = 0; chromosomeIndex < chromosomes.length; chromosomeIndex++) {
final ChromosomeSpec chromosomeSpec = eaConfiguration.getChromosomeSpec(chromosomeIndex);
final Chromosome chromosome = chromosomes[chromosomeIndex];
if (chromosomeSpec instanceof ProgramTreeChromosomeSpec == false) {
throw new IllegalArgumentException("This mutator does not support chromosome specs " + chromosomeSpec);
}
if (chromosome instanceof TreeChromosome<?> == false) {
throw new IllegalArgumentException(
"This mutator does not support chromosome of type " + chromosome.getClass()
.getSimpleName());
}
final ProgramTreeChromosomeSpec programTreeChromosomeSpec = (ProgramTreeChromosomeSpec) chromosomeSpec;
final TreeChromosome<Operation<?>> treeChromosome = (TreeChromosome<Operation<?>>) chromosome;
final int chromosomeSize = treeChromosome.getSize();
if (chromosomeSize > 2) {
final int cutPoint = randomGenerator.nextInt(chromosomeSize - 1) + 1; | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithConstantParsimonyPressure.java | Samples | 135 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithEnforcedMaxDepth.java | Samples | 103 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithProportionalTournament.java | Samples | 156 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithSRT.java | Samples | 162 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithTarpeianMethod.java | Samples | 137 |
SymbolicRegressionUtils.csvLoggerDouble(csvFilename,
evolutionStep -> evolutionStep.fitness(),
evolutionStep -> (double) evolutionStep.individual()
.getChromosome(0, TreeChromosome.class)
.getSize()));
final EAExecutionContext<Double> eaExecutionContext = eaExecutionContextBuilder.build();
final EASystem<Double> eaSystem = EASystemFactory.from(eaConfiguration, eaExecutionContext);
final EvolutionResult<Double> evolutionResult = eaSystem.evolve();
final Genotype bestGenotype = evolutionResult.bestGenotype();
final TreeChromosome<Operation<?>> bestChromosome = (TreeChromosome<Operation<?>>) bestGenotype.getChromosome(0);
logger.info("Best genotype: {}", bestChromosome.getRoot());
logger.info("Best genotype - pretty print: {}", TreeNodeUtils.toStringTreeNode(bestChromosome.getRoot()));
}
public static void main(String[] args) throws IOException { | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithDoubleTournament.java | Samples | 157 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithEnforcedMaxDepth.java | Samples | 103 |
SymbolicRegressionUtils.csvLoggerDouble(csvFilename,
evolutionStep -> evolutionStep.fitness(),
evolutionStep -> (double) evolutionStep.individual()
.getChromosome(0, TreeChromosome.class)
.getSize()));
final EAExecutionContext<Double> eaExecutionContext = eaExecutionContextBuilder.build();
final EASystem<Double> eaSystem = EASystemFactory.from(eaConfiguration, eaExecutionContext);
final EvolutionResult<Double> evolutionResult = eaSystem.evolve();
final Genotype bestGenotype = evolutionResult.bestGenotype();
final TreeChromosome<Operation<?>> bestChromosome = (TreeChromosome<Operation<?>>) bestGenotype.getChromosome(0);
logger.info("Best genotype: {}", bestChromosome.getRoot());
logger.info("Best genotype - pretty print: {}", TreeNodeUtils.toStringTreeNode(bestChromosome.getRoot()));
}
public static void main(String[] args) throws IOException { | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/core/replacement/DeleteNLastImpl.java | Core | 26 |
| net/bmahe/genetics4j/core/replacement/GenerationalReplacementImpl.java | Core | 24 |
this.offspringSelector = _offspringSelector;
}
@Override
public Population<T> select(final AbstractEAConfiguration<T> eaConfiguration, final long generation,
final int numIndividuals, final List<Genotype> population, final List<T> populationScores,
final List<Genotype> offsprings, final List<T> offspringScores) {
Objects.requireNonNull(eaConfiguration);
Validate.isTrue(generation >= 0);
Validate.isTrue(numIndividuals > 0);
Objects.requireNonNull(population);
Objects.requireNonNull(populationScores);
Validate.isTrue(population.size() == populationScores.size());
Objects.requireNonNull(offsprings);
Objects.requireNonNull(offspringScores);
Validate.isTrue(offsprings.size() == offspringScores.size());
final Comparator<T> populationComparator = eaConfiguration.fitnessComparator(); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/gp/mutation/NodeReplacementMutator.java | Genetic Programming | 151 |
| net/bmahe/genetics4j/gp/mutation/ProgramRulesApplicatorMutator.java | Genetic Programming | 90 |
final Chromosome[] newChromosomes = new Chromosome[original.getSize()];
final Chromosome[] chromosomes = original.getChromosomes();
for (int chromosomeIndex = 0; chromosomeIndex < chromosomes.length; chromosomeIndex++) {
final ChromosomeSpec chromosomeSpec = eaConfiguration.getChromosomeSpec(chromosomeIndex);
final Chromosome chromosome = chromosomes[chromosomeIndex];
if (chromosomeSpec instanceof ProgramTreeChromosomeSpec == false) {
throw new IllegalArgumentException("This mutator does not support chromosome specs " + chromosomeSpec);
}
if (chromosome instanceof TreeChromosome<?> == false) {
throw new IllegalArgumentException(
"This mutator does not support chromosome of type " + chromosome.getClass()
.getSimpleName());
}
final ProgramTreeChromosomeSpec programTreeChromosomeSpec = (ProgramTreeChromosomeSpec) chromosomeSpec;
final TreeChromosome<Operation<?>> treeChromosome = (TreeChromosome<Operation<?>>) chromosome;
final int chromosomeSize = treeChromosome.getSize(); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/gp/mutation/ProgramRandomPruneMutator.java | Genetic Programming | 81 |
| net/bmahe/genetics4j/gp/mutation/ProgramRulesApplicatorMutator.java | Genetic Programming | 90 |
final Chromosome[] newChromosomes = new Chromosome[original.getSize()];
final Chromosome[] chromosomes = original.getChromosomes();
for (int chromosomeIndex = 0; chromosomeIndex < chromosomes.length; chromosomeIndex++) {
final ChromosomeSpec chromosomeSpec = eaConfiguration.getChromosomeSpec(chromosomeIndex);
final Chromosome chromosome = chromosomes[chromosomeIndex];
if (chromosomeSpec instanceof ProgramTreeChromosomeSpec == false) {
throw new IllegalArgumentException("This mutator does not support chromosome specs " + chromosomeSpec);
}
if (chromosome instanceof TreeChromosome<?> == false) {
throw new IllegalArgumentException(
"This mutator does not support chromosome of type " + chromosome.getClass()
.getSimpleName());
}
final ProgramTreeChromosomeSpec programTreeChromosomeSpec = (ProgramTreeChromosomeSpec) chromosomeSpec;
final TreeChromosome<Operation<?>> treeChromosome = (TreeChromosome<Operation<?>>) chromosome;
final int chromosomeSize = treeChromosome.getSize(); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/core/replacement/DeleteNLastImpl.java | Core | 27 |
| net/bmahe/genetics4j/moo/spea2/replacement/SPEA2ReplacementStrategyImplementor.java | Multi-Objective Optimization | 305 |
}
@Override
public Population<T> select(final AbstractEAConfiguration<T> eaConfiguration, final long generation,
final int numIndividuals, final List<Genotype> population, final List<T> populationScores,
final List<Genotype> offsprings, final List<T> offspringScores) {
Objects.requireNonNull(eaConfiguration);
Validate.isTrue(generation >= 0);
Validate.isTrue(numIndividuals > 0);
Objects.requireNonNull(population);
Objects.requireNonNull(populationScores);
Validate.isTrue(population.size() == populationScores.size());
Objects.requireNonNull(offsprings);
Objects.requireNonNull(offspringScores);
Validate.isTrue(offsprings.size() == offspringScores.size());
final Comparator<T> populationComparator = eaConfiguration.fitnessComparator(); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithEnforcedMaxDepth.java | Samples | 46 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithMOO.java | Samples | 83 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithMOOSPEA2.java | Samples | 85 |
final Fitness<Double> computeFitness = (genoType) -> {
final TreeChromosome<Operation<?>> chromosome = (TreeChromosome<Operation<?>>) genoType.getChromosome(0);
final Double[][] inputs = new Double[100][1];
for (int i = 0; i < 100; i++) {
inputs[i][0] = (i - 50) * 1.2;
}
double mse = 0;
for (final Double[] input : inputs) {
final double x = input[0];
final double expected = SymbolicRegressionUtils.evaluate(x);
final Object result = ProgramUtils.execute(chromosome, input);
if (Double.isFinite(expected)) { | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/core/replacement/DeleteNLastImpl.java | Core | 27 |
| net/bmahe/genetics4j/core/replacement/ElitismImpl.java | Core | 32 |
| net/bmahe/genetics4j/core/replacement/GenerationalReplacementImpl.java | Core | 25 |
| net/bmahe/genetics4j/moo/spea2/replacement/SPEA2ReplacementStrategyImplementor.java | Multi-Objective Optimization | 305 |
}
@Override
public Population<T> select(final AbstractEAConfiguration<T> eaConfiguration, final long generation,
final int numIndividuals, final List<Genotype> population, final List<T> populationScores,
final List<Genotype> offsprings, final List<T> offspringScores) {
Objects.requireNonNull(eaConfiguration);
Validate.isTrue(generation >= 0);
Validate.isTrue(numIndividuals > 0);
Objects.requireNonNull(population);
Objects.requireNonNull(populationScores);
Validate.isTrue(population.size() == populationScores.size());
Objects.requireNonNull(offsprings);
Objects.requireNonNull(offspringScores);
Validate.isTrue(offsprings.size() == offspringScores.size()); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/gp/program/FullProgramGenerator.java | Genetic Programming | 57 |
| net/bmahe/genetics4j/gp/program/GrowProgramGenerator.java | Genetic Programming | 58 |
Class[] acceptedTypes = currentNode.acceptedTypes();
for (int i = 0; i < acceptedTypes.length; i++) {
final Class acceptedType = acceptedTypes[i];
final TreeNode<Operation<?>> operation = generate(program, acceptedType, maxDepth, 1);
currentTreeNode.addChild(operation);
}
return currentTreeNode;
}
@Override
public <T, U> TreeNode<Operation<T>> generate(final Program program, final int maxDepth, final Class<U> rootType) {
Validate.notNull(program);
Validate.notNull(rootType);
Validate.isTrue(maxDepth > 0);
return generate(program, rootType, maxDepth, 0);
}
} | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/gp/math/SimplificationRules.java | Genetic Programming | 130 |
| net/bmahe/genetics4j/gp/math/SimplificationRules.java | Genetic Programming | 273 |
if (isOperation(t, Functions.NAME_SUB) == false) {
return false;
}
if (hasChildOperation(t, 0, Terminals.TYPE_INPUT) == false) {
return false;
}
if (hasChildOperation(t, 1, Terminals.TYPE_INPUT) == false) {
return false;
}
final InputOperation<?> firstInput = (InputOperation<Double>) t.getChild(0)
.getData();
final InputOperation<?> secondInput = (InputOperation<Double>) t.getChild(1)
.getData();
return firstInput.index() == secondInput.index();
}, (program, t) -> {
final InputSpec inputSpec = program.inputSpec();
final OperationFactory coefficientFactory = OperationFactories | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/gp/mutation/ProgramRandomMutateMutator.java | Genetic Programming | 88 |
| net/bmahe/genetics4j/gp/mutation/TrimTreeMutator.java | Genetic Programming | 84 |
logger.trace("Mutating genotype {}", originalGenotype);
final Chromosome[] newChromosomes = new Chromosome[originalGenotype.getSize()];
final Chromosome[] chromosomes = originalGenotype.getChromosomes();
for (int chromosomeIndex = 0; chromosomeIndex < chromosomes.length; chromosomeIndex++) {
final ChromosomeSpec chromosomeSpec = eaConfiguration.getChromosomeSpec(chromosomeIndex);
final Chromosome chromosome = chromosomes[chromosomeIndex];
if (chromosomeSpec instanceof ProgramTreeChromosomeSpec == false) {
throw new IllegalArgumentException("This mutator does not support chromosome specs " + chromosomeSpec);
}
if (chromosome instanceof TreeChromosome<?> == false) {
throw new IllegalArgumentException(
"This mutator does not support chromosome of type " + chromosome.getClass()
.getSimpleName());
}
final ProgramTreeChromosomeSpec programTreeChromosomeSpec = (ProgramTreeChromosomeSpec) chromosomeSpec;
final TreeChromosome<Operation<?>> treeChromosome = (TreeChromosome<Operation<?>>) chromosome; | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithDoubleTournament.java | Samples | 91 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithProportionalTournament.java | Samples | 90 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithSRT.java | Samples | 91 |
double mse = 0;
for (final Double[] input : inputs) {
final double x = input[0];
final double expected = SymbolicRegressionUtils.evaluate(x);
final Object result = ProgramUtils.execute(chromosome, input);
if (Double.isFinite(expected)) {
final Double resultDouble = (Double) result;
mse += Double.isFinite(resultDouble) ? (expected - resultDouble) * (expected - resultDouble)
: 1_000_000_000;
}
}
return Double.isFinite(mse) ? mse / 100.0d : Double.MAX_VALUE;
};
// end::compute_fitness[]
// tag::double_tournament[]
final Comparator<Individual<Double>> parsimonyComparator = (a, b) -> {
final var treeChromosomeA = a.genotype() | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/clustering/IOUtils.java | Samples | 102 |
| net/bmahe/genetics4j/samples/clustering/IOUtils.java | Samples | 129 |
public static void persistDataPoints(final double[][] data, final String filename) throws IOException {
Validate.notBlank(filename);
logger.info("Saving data to CSV: {}", filename);
final int numDataPoints = data.length;
final CSVPrinter csvPrinter;
try {
csvPrinter = CSVFormat.DEFAULT.withAutoFlush(true)
.withHeader(new String[] { "cluster", "x", "y" })
.print(Path.of(filename), StandardCharsets.UTF_8);
} catch (IOException e) {
logger.error("Could not open {}", filename, e);
throw new RuntimeException("Could not open file " + filename, e);
}
for (int i = 0; i < numDataPoints; i++) {
try {
csvPrinter.printRecord((int) data[i][2], data[i][0], data[i][1]); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/gp/program/FullProgramGenerator.java | Genetic Programming | 17 |
| net/bmahe/genetics4j/gp/program/StdProgramGenerator.java | Genetic Programming | 21 |
OperationFactory currentNode = depth < maxDepth - 1 ? programHelper.pickRandomFunction(program, acceptedType)
: programHelper.pickRandomTerminal(program, acceptedType);
final Operation<T> currentOperation = currentNode.build(program.inputSpec());
final TreeNode<Operation<T>> currentTreeNode = new TreeNode<>(currentOperation);
final Class[] acceptedTypes = currentNode.acceptedTypes();
for (int i = 0; i < acceptedTypes.length; i++) {
final Class childAcceptedType = acceptedTypes[i];
final TreeNode<Operation<T>> operation = generate(program, childAcceptedType, maxDepth, depth + 1);
currentTreeNode.addChild(operation);
}
return currentTreeNode;
}
public FullProgramGenerator(final ProgramHelper _programHelper) { | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/core/selection/ProportionalTournamentSelector.java | Core | 28 |
| net/bmahe/genetics4j/core/selection/TournamentSelector.java | Core | 27 |
Validate.isInstanceOf(ProportionalTournament.class, _selectionPolicy);
Objects.requireNonNull(_randomGenerator);
this.selectionPolicy = _selectionPolicy;
this.randomGenerator = _randomGenerator;
}
@Override
public Population<T> select(final AbstractEAConfiguration<T> eaConfiguration, final long generation,
final int numIndividuals, final List<Genotype> population, final List<T> fitnessScore) {
Objects.requireNonNull(eaConfiguration);
Objects.requireNonNull(population);
Objects.requireNonNull(fitnessScore);
Validate.isTrue(generation >= 0);
Validate.isTrue(numIndividuals > 0);
Validate.isTrue(population.size() == fitnessScore.size());
@SuppressWarnings("unchecked")
final ProportionalTournament<T> proportionalTournament = (ProportionalTournament<T>) selectionPolicy; | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/moo/nsga2/impl/NSGA2Selector.java | Multi-Objective Optimization | 33 |
| net/bmahe/genetics4j/moo/nsga2/impl/TournamentNSGA2Selector.java | Multi-Objective Optimization | 37 |
}
@Override
public Population<T> select(final AbstractEAConfiguration<T> eaConfiguration, final long generation,
final int numIndividuals, final List<Genotype> population, final List<T> fitnessScore) {
Objects.requireNonNull(eaConfiguration);
Objects.requireNonNull(population);
Objects.requireNonNull(fitnessScore);
Validate.isTrue(generation >= 0);
Validate.isTrue(numIndividuals > 0);
Validate.isTrue(population.size() == fitnessScore.size());
logger.debug("Incoming population size is {}", population.size());
final Population<T> individuals = new Population<>();
if (nsga2Selection.deduplicate() | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/gp/program/FullProgramGenerator.java | Genetic Programming | 17 |
| net/bmahe/genetics4j/gp/program/GrowProgramGenerator.java | Genetic Programming | 18 |
| net/bmahe/genetics4j/gp/program/StdProgramGenerator.java | Genetic Programming | 21 |
OperationFactory currentNode = depth < maxDepth - 1 ? programHelper.pickRandomFunction(program, acceptedType)
: programHelper.pickRandomTerminal(program, acceptedType);
final Operation<T> currentOperation = currentNode.build(program.inputSpec());
final TreeNode<Operation<T>> currentTreeNode = new TreeNode<>(currentOperation);
final Class[] acceptedTypes = currentNode.acceptedTypes();
for (int i = 0; i < acceptedTypes.length; i++) {
final Class childAcceptedType = acceptedTypes[i];
final TreeNode<Operation<T>> operation = generate(program, childAcceptedType, maxDepth, depth + 1);
currentTreeNode.addChild(operation);
}
return currentTreeNode;
}
public FullProgramGenerator(final ProgramHelper _programHelper) { | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/gp/mutation/ProgramRandomMutateMutator.java | Genetic Programming | 91 |
| net/bmahe/genetics4j/gp/mutation/ProgramRulesApplicatorMutator.java | Genetic Programming | 91 |
final Chromosome[] chromosomes = originalGenotype.getChromosomes();
for (int chromosomeIndex = 0; chromosomeIndex < chromosomes.length; chromosomeIndex++) {
final ChromosomeSpec chromosomeSpec = eaConfiguration.getChromosomeSpec(chromosomeIndex);
final Chromosome chromosome = chromosomes[chromosomeIndex];
if (chromosomeSpec instanceof ProgramTreeChromosomeSpec == false) {
throw new IllegalArgumentException("This mutator does not support chromosome specs " + chromosomeSpec);
}
if (chromosome instanceof TreeChromosome<?> == false) {
throw new IllegalArgumentException(
"This mutator does not support chromosome of type " + chromosome.getClass()
.getSimpleName());
}
final ProgramTreeChromosomeSpec programTreeChromosomeSpec = (ProgramTreeChromosomeSpec) chromosomeSpec;
final TreeChromosome<Operation<?>> treeChromosome = (TreeChromosome<Operation<?>>) chromosome;
final int chromosomeSize = treeChromosome.getSize(); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/gpu/spec/fitness/cldata/StaticDataLoaders.java | GPU | 79 |
| net/bmahe/genetics4j/gpu/spec/fitness/cldata/StaticDataLoaders.java | GPU | 107 |
final double[] dataLinear = new double[data.length * numColumns];
for (int i = 0; i < data.length; i++) {
if (data[i].length != numColumns) {
throw new IllegalArgumentException(
String.format("Got %d columns for index %d. Should have been %d", data[i].length, i, numColumns));
}
final int baseIndex = i * numColumns;
for (int j = 0; j < numColumns; j++) {
dataLinear[baseIndex + j] = data[i][j];
}
}
return of(dataLinear, readOnly);
}
/**
* Expect an evenly shaped data
*
* @param data
* @param readOnly
* @return
*/
public static StaticDataLoader ofLinearize(final float[][] data, final boolean readOnly) { | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/gp/math/SimplificationRules.java | Genetic Programming | 66 |
| net/bmahe/genetics4j/gp/math/SimplificationRules.java | Genetic Programming | 87 |
| net/bmahe/genetics4j/gp/math/SimplificationRules.java | Genetic Programming | 108 |
final public static Rule ADD_TWO_COEFFCIENTS = ImmutableRule.of((t) -> isOperation(t, Functions.NAME_ADD)
&& hasChildOperation(t, 0, Terminals.TYPE_COEFFICIENT) && hasChildOperation(t, 1, Terminals.TYPE_COEFFICIENT),
(program, t) -> {
final InputSpec inputSpec = program.inputSpec();
final CoefficientOperation<Double> firstCoefficient = getChildAs(t, 0, CoefficientOperation.class);
final Double firstValue = firstCoefficient.value();
final CoefficientOperation<Double> secondCoefficient = getChildAs(t, 1, CoefficientOperation.class);
final Double secondValue = secondCoefficient.value();
final OperationFactory coefficientFactory = OperationFactories
.ofCoefficient(Terminals.TYPE_COEFFICIENT, Double.class, firstValue + secondValue); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithMOO.java | Samples | 122 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithMOOSPEA2.java | Samples | 120 |
.build()) .combinationPolicy(ProgramRandomCombine.build()) .mutationPolicies(MultiMutations .of(ProgramRandomMutate.of(0.15 * 3), ProgramRandomPrune.of(0.15 * 3), NodeReplacement.of(0.15 * 3)), ProgramApplyRules.of(SimplificationRules.SIMPLIFY_RULES)) .optimization(Optimization.MINIMIZE) .termination(Terminations.or(Terminations.<FitnessVector<Double>>ofMaxGeneration(200), (eaConfiguration, generation, population, fitness) -> fitness.stream() .anyMatch(fv -> fv.get(0) <= 0.000001 && fv.get(1) <= 20))) // <4> | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/gp/math/SimplificationRules.java | Genetic Programming | 66 |
| net/bmahe/genetics4j/gp/math/SimplificationRules.java | Genetic Programming | 644 |
final public static Rule ADD_TWO_COEFFCIENTS = ImmutableRule.of((t) -> isOperation(t, Functions.NAME_ADD)
&& hasChildOperation(t, 0, Terminals.TYPE_COEFFICIENT) && hasChildOperation(t, 1, Terminals.TYPE_COEFFICIENT),
(program, t) -> {
final InputSpec inputSpec = program.inputSpec();
final CoefficientOperation<Double> firstCoefficient = getChildAs(t, 0, CoefficientOperation.class);
final Double firstValue = firstCoefficient.value();
final CoefficientOperation<Double> secondCoefficient = getChildAs(t, 1, CoefficientOperation.class);
final Double secondValue = secondCoefficient.value();
final OperationFactory coefficientFactory = OperationFactories
.ofCoefficient(Terminals.TYPE_COEFFICIENT, Double.class, firstValue + secondValue); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/moo/nsga2/spec/NSGA2Selection.java | Multi-Objective Optimization | 85 |
| net/bmahe/genetics4j/moo/nsga2/spec/TournamentNSGA2Selection.java | Multi-Objective Optimization | 96 |
final int numberObjectives, final Comparator<Genotype> deduplicate) {
final var builder = new Builder<FitnessVector<U>>();
builder.objectiveComparator((m) -> (a, b) -> Double.compare(a.get(m)
.doubleValue(),
b.get(m)
.doubleValue()))
.distance((a, b, m) -> Math.abs(b.get(m)
.doubleValue()
- a.get(m)
.doubleValue()))
.numberObjectives(numberObjectives)
.deduplicate(Optional.ofNullable(deduplicate)); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/core/combination/multipointarithmetic/DoubleChromosomeMultiPointArithmetic.java | Core | 35 |
| net/bmahe/genetics4j/core/combination/multipointarithmetic/IntChromosomeMultiPointArithmetic.java | Core | 35 |
Validate.isInstanceOf(DoubleChromosome.class, chromosome2); Validate.isTrue(chromosome1.getNumAlleles() == chromosome2.getNumAlleles()); Validate.isTrue(multiPointArithmeticPolicy.numCrossovers() < chromosome1.getNumAlleles()); Validate.isTrue(multiPointArithmeticPolicy.numCrossovers() < chromosome2.getNumAlleles()); final int numCrossovers = multiPointArithmeticPolicy.numCrossovers(); final double alpha = multiPointArithmeticPolicy.alpha(); final int[] alleleSplits = randomGenerator.ints(0, chromosome1.getNumAlleles()) .distinct() .limit(numCrossovers) .sorted() .toArray(); final DoubleChromosome doubleChromosome1 = (DoubleChromosome) chromosome1; | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/core/combination/multipointarithmetic/IntChromosomeMultiPointArithmetic.java | Core | 69 |
| net/bmahe/genetics4j/core/combination/singlepointarithmetic/IntChromosomeSinglePointArithmetic.java | Core | 49 |
if (useChromosome1) {
firstChildValues[i] = (int) (alpha * firstAllele + (1 - alpha) * secondAllele);
secondChildValues[i] = (int) ((1 - alpha) * firstAllele + alpha * secondAllele);
} else {
firstChildValues[i] = (int) ((1 - alpha) * firstAllele + alpha * secondAllele);
secondChildValues[i] = (int) (alpha * firstAllele + (1 - alpha) * secondAllele);
}
}
return List.of(
new IntChromosome(numAlleles, intChromosome1.getMinValue(), intChromosome2.getMaxValue(), firstChildValues), | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/gpu/spec/fitness/cldata/StaticDataLoaders.java | GPU | 79 |
| net/bmahe/genetics4j/gpu/spec/fitness/cldata/StaticDataLoaders.java | GPU | 145 |
final double[] dataLinear = new double[data.length * numColumns];
for (int i = 0; i < data.length; i++) {
if (data[i].length != numColumns) {
throw new IllegalArgumentException(
String.format("Got %d columns for index %d. Should have been %d", data[i].length, i, numColumns));
}
final int baseIndex = i * numColumns;
for (int j = 0; j < numColumns; j++) {
dataLinear[baseIndex + j] = data[i][j];
}
}
return of(dataLinear, readOnly);
}
/**
* Expect an evenly shaped data
*
* @param data
* @param readOnly
* @return
*/
public static StaticDataLoader ofLinearize(final float[][] data, final boolean readOnly) { | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/core/combination/multipointarithmetic/DoubleChromosomeMultiPointArithmetic.java | Core | 46 |
| net/bmahe/genetics4j/core/combination/multipointcrossover/DoubleChromosomeMultiPointCrossover.java | Core | 43 |
.limit(numCrossovers)
.sorted()
.toArray();
final DoubleChromosome doubleChromosome1 = (DoubleChromosome) chromosome1;
final DoubleChromosome doubleChromosome2 = (DoubleChromosome) chromosome2;
final int numAlleles = chromosome1.getNumAlleles();
final double[] firstChildValues = new double[numAlleles];
final double[] secondChildValues = new double[numAlleles];
boolean useChromosome1 = true;
int splitIndex = 0;
for (int i = 0; i < doubleChromosome1.getNumAlleles(); i++) {
if (splitIndex < alleleSplits.length && i == alleleSplits[splitIndex]) {
splitIndex++;
useChromosome1 = !useChromosome1;
} | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/core/combination/multipointarithmetic/FloatChromosomeMultiPointArithmetic.java | Core | 46 |
| net/bmahe/genetics4j/core/combination/multipointcrossover/FloatChromosomeMultiPointCrossover.java | Core | 43 |
.limit(numCrossovers)
.sorted()
.toArray();
final FloatChromosome floatChromosome1 = (FloatChromosome) chromosome1;
final FloatChromosome floatChromosome2 = (FloatChromosome) chromosome2;
final int numAlleles = chromosome1.getNumAlleles();
final float[] firstChildValues = new float[numAlleles];
final float[] secondChildValues = new float[numAlleles];
boolean useChromosome1 = true;
int splitIndex = 0;
for (int i = 0; i < floatChromosome1.getNumAlleles(); i++) {
if (splitIndex < alleleSplits.length && i == alleleSplits[splitIndex]) {
splitIndex++;
useChromosome1 = !useChromosome1;
} | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/core/combination/multipointarithmetic/IntChromosomeMultiPointArithmetic.java | Core | 46 |
| net/bmahe/genetics4j/core/combination/multipointcrossover/IntChromosomeMultiPointCrossover.java | Core | 43 |
.limit(numCrossovers)
.sorted()
.toArray();
final IntChromosome intChromosome1 = (IntChromosome) chromosome1;
final IntChromosome intChromosome2 = (IntChromosome) chromosome2;
final int numAlleles = chromosome1.getNumAlleles();
final int[] firstChildValues = new int[numAlleles];
final int[] secondChildValues = new int[numAlleles];
boolean useChromosome1 = true;
int splitIndex = 0;
for (int i = 0; i < intChromosome1.getNumAlleles(); i++) {
if (splitIndex < alleleSplits.length && i == alleleSplits[splitIndex]) {
splitIndex++;
useChromosome1 = !useChromosome1;
} | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/gpu/spec/fitness/cldata/StaticDataLoaders.java | GPU | 79 |
| net/bmahe/genetics4j/gpu/spec/fitness/cldata/StaticDataLoaders.java | GPU | 173 |
final double[] dataLinear = new double[data.length * numColumns];
for (int i = 0; i < data.length; i++) {
if (data[i].length != numColumns) {
throw new IllegalArgumentException(
String.format("Got %d columns for index %d. Should have been %d", data[i].length, i, numColumns));
}
final int baseIndex = i * numColumns;
for (int j = 0; j < numColumns; j++) {
dataLinear[baseIndex + j] = data[i][j];
}
}
return of(dataLinear, readOnly);
}
/**
* Expect an evenly shaped data
*
* @param data
* @param readOnly
* @return
*/
public static StaticDataLoader ofLinearize(final float[][] data, final boolean readOnly) { | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithConstantParsimonyPressure.java | Samples | 115 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithTarpeianMethod.java | Samples | 116 |
.termination(or(ofMaxGeneration(200), ofFitnessAtMost(20.0d))) // <3>
.fitness(computeFitness);
final EAConfiguration<Double> eaConfiguration = eaConfigurationBuilder.build();
// end::ea_config[]
final var eaExecutionContextBuilder = GPEAExecutionContexts.<Double>forGP(random);
EAExecutionContexts.enrichForScalarFitness(eaExecutionContextBuilder);
eaExecutionContextBuilder.populationSize(populationSize);
eaExecutionContextBuilder.numberOfPartitions(Math.max(1,
Runtime.getRuntime()
.availableProcessors() - 1));
eaExecutionContextBuilder.addEvolutionListeners(
EvolutionListeners.ofLogTopN(logger, 5, Comparator.<Double>reverseOrder(), (genotype) -> {
final TreeChromosome<Operation<?>> chromosome = (TreeChromosome<Operation<?>>) genotype.getChromosome(0); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithConstantParsimonyPressure.java | Samples | 123 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithEnforcedMaxDepth.java | Samples | 91 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithProportionalTournament.java | Samples | 144 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithSRT.java | Samples | 150 |
eaExecutionContextBuilder.populationSize(populationSize);
eaExecutionContextBuilder.numberOfPartitions(Math.max(1,
Runtime.getRuntime()
.availableProcessors() - 1));
eaExecutionContextBuilder.addEvolutionListeners(
EvolutionListeners.ofLogTopN(logger, 5, Comparator.<Double>reverseOrder(), (genotype) -> {
final TreeChromosome<Operation<?>> chromosome = (TreeChromosome<Operation<?>>) genotype.getChromosome(0);
final TreeNode<Operation<?>> root = chromosome.getRoot();
return TreeNodeUtils.toStringTreeNode(root);
}),
SymbolicRegressionUtils.csvLoggerDouble(csvFilename, | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithDoubleTournament.java | Samples | 145 |
| net/bmahe/genetics4j/samples/symbolicregression/SymbolicRegressionWithEnforcedMaxDepth.java | Samples | 91 |
eaExecutionContextBuilder.populationSize(populationSize);
eaExecutionContextBuilder.numberOfPartitions(Math.max(1,
Runtime.getRuntime()
.availableProcessors() - 1));
eaExecutionContextBuilder.addEvolutionListeners(
EvolutionListeners.ofLogTopN(logger, 5, Comparator.<Double>reverseOrder(), (genotype) -> {
final TreeChromosome<Operation<?>> chromosome = (TreeChromosome<Operation<?>>) genotype.getChromosome(0);
final TreeNode<Operation<?>> root = chromosome.getRoot();
return TreeNodeUtils.toStringTreeNode(root);
}),
SymbolicRegressionUtils.csvLoggerDouble(csvFilename, | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/moo/nsga2/spec/NSGA2Selection.java | Multi-Objective Optimization | 21 |
| net/bmahe/genetics4j/moo/nsga2/spec/TournamentNSGA2Selection.java | Multi-Objective Optimization | 22 |
public abstract class NSGA2Selection<T extends Comparable<T>> implements SelectionPolicy {
/**
* Number of objectives
*
* @return
*/
@Value.Parameter
public abstract int numberObjectives();
/**
* Override the dominance operator.
* <p>If not specified, it assumes the default comparator conforms to the Pareto dominance relation
*
* @return
*/
@Value.Default
public Comparator<T> dominance() {
return (a, b) -> a.compareTo(b);
}
/**
* Comparator used for deduplication of solution prior to processing
* <p>If not specified, it defaults to not do any deduplication
*
* @return
*/
@Value.Default
public Optional<Comparator<Genotype>> deduplicate() {
return Optional.empty();
}
/**
* Sort T based on the objective passed as a parameter
*
* @return
*/
@Value.Parameter
public abstract Function<Integer, Comparator<T>> objectiveComparator();
/**
* Define how to compute distances between fitness scores along their objectives
*
* @return Distance computation method
*/
@Value.Parameter
public abstract ObjectiveDistance<T> distance(); | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/core/combination/multipointcrossover/DoubleChromosomeMultiPointCrossover.java | Core | 63 |
| net/bmahe/genetics4j/core/combination/singlepointcrossover/DoubleChromosomeSinglePointCrossover.java | Core | 43 |
if (useChromosome1) {
firstChildValues[i] = doubleChromosome1.getAllele(i);
secondChildValues[i] = doubleChromosome2.getAllele(i);
} else {
firstChildValues[i] = doubleChromosome2.getAllele(i);
secondChildValues[i] = doubleChromosome1.getAllele(i);
}
}
/**
* TODO Should the min/max values be extended based on the lowest/highest values?
*/
final double minValue = doubleChromosome1.getMinValue();
final double maxValue = doubleChromosome2.getMaxValue();
return List.of(new DoubleChromosome(numAlleles, minValue, maxValue, firstChildValues),
new DoubleChromosome(numAlleles, minValue, maxValue, secondChildValues));
}
} | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/core/combination/multipointcrossover/FloatChromosomeMultiPointCrossover.java | Core | 63 |
| net/bmahe/genetics4j/core/combination/singlepointcrossover/FloatChromosomeSinglePointCrossover.java | Core | 43 |
if (useChromosome1) {
firstChildValues[i] = floatChromosome1.getAllele(i);
secondChildValues[i] = floatChromosome2.getAllele(i);
} else {
firstChildValues[i] = floatChromosome2.getAllele(i);
secondChildValues[i] = floatChromosome1.getAllele(i);
}
}
/**
* TODO Should the min/max values be extended based on the lowest/highest values?
*/
final float minValue = floatChromosome1.getMinValue();
final float maxValue = floatChromosome2.getMaxValue();
return List.of(new FloatChromosome(numAlleles, minValue, maxValue, firstChildValues),
new FloatChromosome(numAlleles, minValue, maxValue, secondChildValues));
}
} | ||
| File | Project | Line |
|---|---|---|
| net/bmahe/genetics4j/gp/program/FullProgramGenerator.java | Genetic Programming | 52 |
| net/bmahe/genetics4j/gp/program/StdProgramGenerator.java | Genetic Programming | 55 |
final OperationFactory currentNode = programHelper.pickRandomFunction(program);
final Operation currentOperation = currentNode.build(program.inputSpec());
final TreeNode<Operation<?>> currentTreeNode = new TreeNode<>(currentOperation);
Class[] acceptedTypes = currentNode.acceptedTypes();
for (int i = 0; i < acceptedTypes.length; i++) {
final Class acceptedType = acceptedTypes[i];
final TreeNode<Operation<?>> operation = generate(program, acceptedType, maxDepth, 1);
currentTreeNode.addChild(operation);
}
return currentTreeNode;
}
@Override
public <T, U> TreeNode<Operation<T>> generate(final Program program, final int maxDepth, final Class<U> rootType) { | ||