// Compute scores for new leaf0 and leaf1, and add them to scoreList. private void computeNewLeafScores(SelectedSet selectedSet, int i, int j) { int NS = selectedSet.getN(); for (int a = 0; a < NS; a++) { Individual individual = selectedSet.getIndividual(a); IGraph iterator = decisionGraphs[i].getGraph(); while (!(iterator instanceof Leaf)) { // Iterator is a variable because we are still traversing the DG. int x = ((Variable) iterator).getVariable(); char alleleX = individual.getAllele(x); if (alleleX == '0') { iterator = ((Variable) iterator).getZero(); } else { iterator = ((Variable) iterator).getOne(); } } int itrPosition = decisionGraphs[i].getLeafs().indexOf((Leaf) iterator); if (itrPosition == j || itrPosition == j + 1) { // We've reached one of the new leafs. int mZero = ((Leaf) iterator).getMZero(); int mOne = ((Leaf) iterator).getMOne(); if (mZero > 0 && mOne > 0) { // It's still "interesting" to split. char alleleI = individual.getAllele(i); // Value of Xi in individual a. for (int split : splitList[i]) { char alleleS = individual.getAllele(split); // Value of Xsplit in individual a. if (alleleI == '0') { if (alleleS == '0') { ((Leaf) iterator).addPossibleSplitFrequency(0, split); // m00[split]++; } else { ((Leaf) iterator).addPossibleSplitFrequency(1, split); // m01[split]++; } } else if (alleleS == '0') { ((Leaf) iterator).addPossibleSplitFrequency(2, split); // m10[split]++; } else { ((Leaf) iterator).addPossibleSplitFrequency(3, split); // m11[split]++; } } } } } for (int a = 0; a <= 1; a++) { Leaf newLeaf = decisionGraphs[i].getLeaf(j + a); // The two new leafs are at positions 'j' and 'j+1'. int mZero = newLeaf.getMZero(); int mOne = newLeaf.getMOne(); if (mZero > 0 && mOne > 0) { for (int s : splitList[i]) { int m00 = newLeaf.getPossibleSplitFrequency(0, s); int m01 = newLeaf.getPossibleSplitFrequency(1, s); int m10 = newLeaf.getPossibleSplitFrequency(2, s); int m11 = newLeaf.getPossibleSplitFrequency(3, s); double scoreGain = bayesianMetric.computeScoreGain(mZero, mOne, m00, m01, m10, m11); newLeaf.setScoreGain(s, scoreGain); newLeaf.updateBestSplit( s, scoreGain); // Responsible for updating the value of the best split score gain in this // leaf. } } } // END: for(int a = 0 ...) } // END: computeNewLeafScores(...)
public Individual getIndividualCopy(int i) { // NOTE: Non shallow copy! Individual indiv = new Individual(); for (int j = 0; j < Problem.n; j++) { indiv.setAllele(j, individuals[i].getAllele(j)); } return indiv; }
public SimplePopulation getPopulation(BinaryString template) { SimplePopulation pop = new SimplePopulation(); for (Individual ind : individuals) { pop.addIndividual(ind.getSolution(template)); } return pop; }
public float computeFitness(Individual individual) { int six; float fit = 0; for (int i = 0; i < Problem.n; ) { // Empty increment six = Integer.parseInt(String.valueOf(individual.getAllele(i++))); six += Integer.parseInt(String.valueOf(individual.getAllele(i++))); six += Integer.parseInt(String.valueOf(individual.getAllele(i++))); six += Integer.parseInt(String.valueOf(individual.getAllele(i++))); six += Integer.parseInt(String.valueOf(individual.getAllele(i++))); six += Integer.parseInt(String.valueOf(individual.getAllele(i++))); six = Math.abs(six - 3); switch (six) { case 0: fit += 0.9; break; case 1: fit += 0.8; break; case 3: fit += 1; break; default: break; } } return fit; }
public float computeFitness(Individual individual) { for (int i = 0; i < Problem.n; ) { // Empty increment char c = individual.getAllele(i++); for (int j = 1; j < 6; j++) if (individual.getAllele(i++) != c) return (float) 0; } return (float) 1; }
public int compare(Individual individual_1, Individual individual_2) { if (individual_1.getRate() == individual_2.getRate()) { return 0; } else if (individual_1.getRate() < individual_2.getRate()) { return 1; } else { return -1; } }
// Generate chromosome using random permutations public Individual generateRandomChromosome() { Individual indiv = new Individual(); // Filling in the order for (int i = 0; i < Problem.customersNumber; i++) { indiv.getChromosome().add(i); } // And shuffling Collections.shuffle(indiv.getChromosome()); return indiv; }
// Calculate inidividuals fittness by comparing it to our candidate solution static int getFitness(Individual individual) { int fitness = 0; // Loop through our individuals genes and compare them to our cadidates for (int i = 0; i < individual.size() && i < solution.length; i++) { if (individual.getGene(i) == solution[i]) { fitness++; } } return fitness; }
public Individual run( EvolutionState state, SimpleProblemForm p, Individual x, int maxIter, ClusWrapperNonStatic objectClus) throws Exception { // talvez passe um individuo já com o genoma e score Random rand = new Random(); // IntegerVectorIndividual mutatedX = (IntegerVectorIndividual) deepClone(x); IntegerVectorIndividual mutatedX = (IntegerVectorIndividual) x.clone(); mutatedX.evaluated = false; double alpha = 0.95; // cálculo do alpha, percentual de diminuição da temperatura double t_final = 1; double t0 = Math.pow(alpha, maxIter + Math.log(t_final)); // estimar a temperatura inicial double temp_atual = t0; // tf = temperatura da vez int iter = 0; maxIter *= 2; while (iter < maxIter) { int[] genome = mutatedX.genome; genome = mutate(genome, 1 - iter / maxIter); // mutar o vetor mutatedX.setGenome(genome); ((ec.Problem) p).prepareToEvaluate(state, 0); System.out.print("Mutated Genoma: " + mutatedX.genome[0]); for (int i = 0; i < mutatedX.genomeLength(); i++) System.out.print("," + mutatedX.genome[i]); System.out.println(); p.evaluate(state, mutatedX, 0, 0, objectClus); ((ec.Problem) p).finishEvaluating(state, 0); double newF = mutatedX.fitness.fitness(); // adequar para minimizar o fitness float delta = (float) (x.fitness.fitness() - newF); if (delta < 0 || rand.nextDouble() < Math.exp(-(delta) / temp_atual)) { ((IntegerVectorIndividual) x).setGenome(mutatedX.getGenome()); x.evaluated = false; ((ec.Problem) p).prepareToEvaluate(state, 0); p.evaluate(state, x, 0, 0, objectClus); ((ec.Problem) p).finishEvaluating(state, 0); } iter += 1; temp_atual = temp_atual * alpha; } return x; }
public Individual getFittest() { Individual fittest = individuals[0]; // Loop through individuals to find fittest for (int i = 0; i < size(); i++) { if (fittest.getFitness() <= getIndividual(i).getFitness()) { fittest = getIndividual(i); } } return fittest; }
public float computeFitness(Individual individual) { int k; float fit = 0; for (int i = 0; i < Problem.n; ) { // Empty increment k = Integer.parseInt(String.valueOf(individual.getAllele(i++))); for (int j = 1; j < kay; j++) k += Integer.parseInt(String.valueOf(individual.getAllele(i++))); if (k < kay) fit += kay - 1 - k; else fit += kay; } return fit; }
public Population(int population_size, int chromosome_length, boolean initialize) { individuals = new Individual[population_size]; this.chromosome_length = chromosome_length; // Initialize population if (initialize) { for (int i = 0; i < size(); i++) { Individual ind = new Individual(); ind.generateIndividual(chromosome_length); saveIndividual(i, ind); } } }
public List<Family> getFamiliesTDT() { List<Family> families = new ArrayList<>(); Individual ind; for (Map.Entry<String, Individual> entry : this.individuals.entrySet()) { ind = entry.getValue(); if (ind.getFather() != null && ind.getMother() != null) { addIndividualToFamily(ind, ind.getFather(), ind.getMother(), families); } } return families; }
public boolean needsToRun(Run run, int generation) { Population pop = getPopulationFor(run, generation); int count = run.getIntProperty(GenetikConstants.POPULATION, Integer.MAX_VALUE, true); int scoreCount = 0; for (int i = 0, max = pop.size(); i < max; i++) { Individual ind = pop.get(i); if (ind.hasFitness() && ind.hasScores()) { scoreCount++; } } return scoreCount != count; }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Pedigree\n"); if (fields.size() > 0) { sb.append("fields = " + fields.keySet().toString() + "\n"); } for (Map.Entry<String, Set<Individual>> elem : this.families.entrySet()) { sb.append(elem.getKey() + "\n"); for (Individual ind : elem.getValue()) { sb.append("\t" + ind.toString() + "\n"); } } return sb.toString(); }
public static int getFitness(Individual gene, CityMap cm) { int fitness = 0; if (cm == null) { System.out.println("CityMap is NULL. Terminate 3"); System.exit(3); } for (int i = 0; i < gene.length(); i++) { int dist, city = gene.getItem(i), nextCity; if (i + 1 >= gene.length()) nextCity = gene.getItem(0); else nextCity = gene.getItem(i + 1); if (city == 0 || nextCity == 0) System.out.println(gene); dist = cm.getDist(city, nextCity); fitness += dist; } return fitness; }
public Individual(Individual individual) { this(individual.getLociPattern()); for (int i = 0; i < individual.getGenomeSize(); i++) { Object clonedLocus = null; try { clonedLocus = individual.getLocus(i).clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } if (getLociPattern().getLocusType(i) == LociPattern.LocusType.Fitness) { loci[i] = (FitnessLocus) clonedLocus; } else if (getLociPattern().getLocusType(i) == LociPattern.LocusType.Mutator) { loci[i] = (MutatorLocus) clonedLocus; } else if (getLociPattern().getLocusType(i) == LociPattern.LocusType.Recombination) { loci[i] = (RecombinationLocus) clonedLocus; } } }
public float computeFitness(Individual individual) { float fit = 0; for (int i = 0; i < Problem.n; ) { // Empty increment char a = individual.getAllele(i++); char b = individual.getAllele(i++); if (a == '1' && b == '1') fit += 0.9; if (a == '0' && b == '0') fit += 1; } return fit; }
public Individual[] generateChildren(Individual[] parents, Run run) { Individual parent = parents[0]; Individual retVal = parent.duplicate(); retVal.setId(parent.getId()); retVal.setParentOne(parent.getId()); retVal.setParentTwo(null); Individual[] children = {retVal}; return children; }
// Generate chromosome using greedy procedure from 22p. public Individual generateGreedyChromosome() { Individual indiv = new Individual(); Random random = new Random(); List<Integer> tempChromosome = new ArrayList<Integer>(Problem.customersNumber); for (int i = 0; i < Problem.customersNumber; i++) { tempChromosome.add(i); } while (!tempChromosome.isEmpty()) { int randIndex = (int) (random.nextInt(tempChromosome.size())); int randCustId = tempChromosome.get(randIndex); tempChromosome.remove(randIndex); indiv.getChromosome().add(randCustId); Point randCust = Problem.getCustomer(randCustId); while (true) { // Finding the nearest point double dist; double minDist = GA.EUCLIDEAN_RADIUS; // If the distance is greater than EUCLIDEAN_RADIUS, then this // point is not interesting anyway int nearestId = -1; for (Point p : Problem.customers) { dist = randCust.distanceTo(p); if (dist < minDist && dist > 0 && // To exclude itself !indiv.getChromosome().contains(p.getId())) { // Still not in list minDist = dist; nearestId = p.getId(); } } if (nearestId == -1) { // The nearest point is not exist break; } tempChromosome.remove((Object) nearestId); indiv.getChromosome().add(nearestId); randCust = Problem.getCustomer(nearestId); } } return indiv; }
public int compareTo(Individual arg) { // Compare by class name first: String first = getClass().getSimpleName(); String argFirst = arg.getClass().getSimpleName(); int firstCompare = first.compareTo(argFirst); if (firstCompare != 0) return firstCompare; if (name != null && arg.name != null) { int secondCompare = name.compareTo(arg.name); if (secondCompare != 0) return secondCompare; } return (arg.id < id ? -1 : (arg.id == id ? 0 : 1)); }
public float computeFitness(Individual individual) { int three; float fit = 0; for (int i = 0; i < Problem.n; ) { // Empty increment three = Integer.parseInt(String.valueOf(individual.getAllele(i++))); three += Integer.parseInt(String.valueOf(individual.getAllele(i++))); three += Integer.parseInt(String.valueOf(individual.getAllele(i++))); switch (three) { case 0: fit += 1; break; case 2: fit += 0.8; break; case 3: fit += 0.9; break; default: break; } } return fit; }
public void evaluate( final EvolutionState state, final Individual ind, final int subpopulation, final int threadnum) { if (!ind.evaluated) // don't bother reevaluating { // trees[0].child is the root double score = fitness(((GPIndividual) ind).trees[0].child, state); SimpleFitness f = ((SimpleFitness) ind.fitness); f.setFitness(state, score, false); ind.evaluated = true; } }
/** Saves an individual to disk under a given filename, in computer-readable format. */ public void storeIndividual(final EvolutionState state, String filename, Individual ind) { try { File file = openFile(state, filename); // PrintWriter writer = new PrintWriter(file); // ind.printIndividual(state, writer); // writer.close(); int log = state.output.addLog( file, Output.V_NO_GENERAL - 1, false, !state.parameters.getBoolean(new Parameter(P_COMPRESS), null, false), state.parameters.getBoolean(new Parameter(P_COMPRESS), null, false)); ind.printIndividual(state, log, Output.V_NO_GENERAL); state.output.message("Best Individual stored in " + filename); } catch (Exception e) { state.output.error("Exception " + e); } }
public static HomeFolder xmlToModel(fr.cg95.cvq.xml.common.HomeFolderType homeFolderType) { HomeFolder homeFolder = new HomeFolder(); homeFolder.setId(new Long(homeFolderType.getId())); homeFolder.setAdress(Address.xmlToModel(homeFolderType.getAddress())); IndividualType[] individualsArray = homeFolderType.getIndividualsArray(); Arrays.asList(individualsArray); List<Individual> individualsSet = new ArrayList<Individual>(); for (int i = 0; i < individualsArray.length; i++) { individualsSet.add(Individual.xmlToModel(individualsArray[i])); } homeFolder.setIndividuals(individualsSet); if (homeFolderType.getState() != null) homeFolder.setState(ActorState.forString(homeFolderType.getState().toString())); if (homeFolderType.getFamilyQuotient() != null) homeFolder.setFamilyQuotient(homeFolderType.getFamilyQuotient()); return homeFolder; }
public void evaluate( final EvolutionState state, final Individual ind, final int subpopulation, final int threadnum) { float accuracy = (float) 0.0; int i; double total_correct = 0; if (!ind.evaluated) // don't bother reevaluating { SVM_GP.setInd(ind); SVM_GP.setInput(input); SVM_GP.setProblem(this); SVM_GP.setStack(stack); SVM_GP.setState(state); SVM_GP.setSubpopulation(subpopulation); SVM_GP.setThreadnum(threadnum); double[] target = new double[prob.l]; SVM_GP.svm_cross_validation(prob, param, nr_fold, target); /*((GPIndividual)ind).trees[0].child.eval( state,threadnum,input,stack,((GPIndividual)ind),this);*/ // result = Math.abs(expectedResult - input.x); for (i = 0; i < prob.l; i++) if (target[i] == prob.y[i]) ++total_correct; accuracy = (float) (total_correct / prob.l); System.out.print("Cross Validation Accuracy = " + 100.0 * accuracy + "%\n"); } SimpleFitness f = ((SimpleFitness) ind.fitness); f.setFitness(state, accuracy, accuracy == 1.0); // the fitness better be KozaFitness! // KozaFitness f = ((KozaFitness)ind.fitness); // f.setStandardizedFitness(state,(float)accuracy); // f.hits = hits; ind.evaluated = true; }
public void evaluate( final EvolutionState state, final Individual ind, final int subpopulation, final int threadnum) { if (ca == null) ca = new CA(CA_WIDTH, NEIGHBORHOOD); // we always reevaluate // if (!ind.evaluated) // don't bother reevaluating { MajorityData input = (MajorityData) (this.input); int sum = 0; // extract the rule ((GPIndividual) ind) .trees[0].child.eval(state, threadnum, input, stack, ((GPIndividual) ind), this); int[] rule = ca.getRule(); for (int i = 0; i < 64; i++) rule[i] = (int) (((input.data0) >> i) & 0x1); for (int i = 64; i < 128; i++) rule[i] = (int) (((input.data1) >> (i - 64)) & 0x1); ca.setRule(rule); // for good measure though it doesn't matter for (int i = 0; i < NUM_TRIALS; i++) { // set up and run the CA ca.setVals(trials[i]); ca.step(STEPS, true); // extract the fitness if (all(ca.getVals(), majorities[i])) sum++; } SimpleFitness f = ((SimpleFitness) ind.fitness); f.setFitness(state, sum / (double) NUM_TRIALS, (sum == NUM_TRIALS)); ind.evaluated = true; } }
private void applyRule(int row, int column, Individual[][] a_lattice) { /* * TODO: clever way to do this with iteration * */ // placeholder Individual currentIndividual = a_lattice[row][column]; if (currentIndividual.state == 'I') { // infect neighbours Individual neighbour = getLeft(row, column, a_lattice); if (neighbour.getDiseaseState() == 'S' && Math.random() < beta) { // transmission happens neighbour.infect(); if (currentIndividual.isPrimaryCase) { this.countOfSecondaryInfections++; } } // update the time spent infected // if this time exceeds the infectious period then turn Removed ('R') currentIndividual.updateDiseaseState(); neighbour = getRight(row, column, a_lattice); if (neighbour.getDiseaseState() == 'S' && Math.random() < beta) { // transmission happens neighbour.infect(); if (currentIndividual.isPrimaryCase) { this.countOfSecondaryInfections++; } } // update the time spent infected // if this time exceeds the infectious period then turn Removed ('R') currentIndividual.updateDiseaseState(); neighbour = getDown(row, column, a_lattice); if (neighbour.getDiseaseState() == 'S' && Math.random() < beta) { // transmission happens neighbour.infect(); if (currentIndividual.isPrimaryCase) { this.countOfSecondaryInfections++; } } // update the time spent infected // if this time exceeds the infectious period then turn Removed ('R') currentIndividual.updateDiseaseState(); neighbour = getUp(row, column, a_lattice); if (neighbour.getDiseaseState() == 'S' && Math.random() < beta) { // transmission happens neighbour.infect(); if (currentIndividual.isPrimaryCase) { this.countOfSecondaryInfections++; } } // update the time spent infected // if this time exceeds the infectious period then turn Removed ('R') currentIndividual.updateDiseaseState(); neighbour = getUpLeft(row, column, a_lattice); if (neighbour.getDiseaseState() == 'S' && Math.random() < beta) { // transmission happens neighbour.infect(); if (currentIndividual.isPrimaryCase) { this.countOfSecondaryInfections++; } } neighbour = getDownLeft(row, column, a_lattice); if (neighbour.getDiseaseState() == 'S' && Math.random() < beta) { // transmission happens neighbour.infect(); if (currentIndividual.isPrimaryCase) { this.countOfSecondaryInfections++; } } neighbour = getUpRight(row, column, a_lattice); if (neighbour.getDiseaseState() == 'S' && Math.random() < beta) { // transmission happens neighbour.infect(); if (currentIndividual.isPrimaryCase) { this.countOfSecondaryInfections++; } } neighbour = getDownRight(row, column, a_lattice); if (neighbour.getDiseaseState() == 'S' && Math.random() < beta) { // transmission happens neighbour.infect(); if (currentIndividual.isPrimaryCase) { this.countOfSecondaryInfections++; } } } }
public void addIndividual(Individual newInd) { family.add(newInd); numIndividuals++; familyFitness.add(newInd.getFitness()); }
public DataPropertyStatementImpl(Individual individual) { if (individual != null) { this.individualURI = individual.getURI(); } }