All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.evosuite.ga.metaheuristics.mosa.MOSA Maven / Gradle / Ivy

The newest version!
/**
 *
 * This file is part of EvoSuite.
 *
 * EvoSuite is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3.0 of the License, or
 * (at your option) any later version.
 *
 * EvoSuite is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with EvoSuite. If not, see .
 */
package org.evosuite.ga.metaheuristics.mosa;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.evosuite.Properties;
import org.evosuite.Properties.Criterion;
import org.evosuite.coverage.exception.ExceptionCoverageFactory;
import org.evosuite.coverage.exception.ExceptionCoverageTestFitness;
import org.evosuite.ga.Chromosome;
import org.evosuite.ga.ChromosomeFactory;
import org.evosuite.ga.FitnessFunction;
import org.evosuite.ga.metaheuristics.GeneticAlgorithm;
import org.evosuite.ga.metaheuristics.lips.BudgetConsumptionMonitor;
import org.evosuite.ga.metaheuristics.mosa.comparators.OnlyCrowdingComparator;
import org.evosuite.rmi.ClientServices;
import org.evosuite.statistics.RuntimeVariable;
import org.evosuite.testcase.TestChromosome;
import org.evosuite.testcase.TestFitnessFunction;
import org.evosuite.testsuite.TestSuiteChromosome;
import org.evosuite.testsuite.TestSuiteFitnessFunction;
import org.evosuite.utils.ArrayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Implementation of the MOSA (Many-Objective Sorting Algorithm) described in the ICST'15 paper ...
 * 
 * @author Annibale Panichella, Fitsum M. Kifetew
 *
 * @param 
 */
public class MOSA extends AbstractMOSA {

	private static final long serialVersionUID = 146182080947267628L;

	private static final Logger logger = LoggerFactory.getLogger(MOSA.class);

	/** Map used to store the covered test goals (keys of the map) and the corresponding covering test cases (values of the map) **/
	protected Map, T> archive = new LinkedHashMap, T>();

	/** Boolean vector to indicate whether each test goal is covered or not. **/
	protected Set> uncoveredGoals = new LinkedHashSet>();

	/** Crowding distance measure to use */
	protected CrowdingDistance distance = new CrowdingDistance();
	
	/** Object used to keep track of the execution time needed to reach the maximum coverage */
	protected BudgetConsumptionMonitor budgetMonitor;
	
	/**
	 * Constructor based on the abstract class {@link AbstractMOSA}
	 * @param factory
	 */
	public MOSA(ChromosomeFactory factory) {
		super(factory);
		budgetMonitor = new BudgetConsumptionMonitor();
	}

	/** {@inheritDoc} */
	@Override
	protected void evolve() {
		List offspringPopulation = breedNextGeneration();

		// Create the union of parents and offSpring
		List union = new ArrayList();
		union.addAll(population);
		union.addAll(offspringPopulation);

		// Ranking the union
		logger.debug("Union Size =" + union.size());
		// Ranking the union using the best rank algorithm (modified version of the non dominated sorting algorithm
		ranking.computeRankingAssignment(union, uncoveredGoals);

		// add to the archive the new covered goals (and the corresponding test cases)
		//this.archive.putAll(ranking.getNewCoveredGoals());

		int remain = population.size();
		int index = 0;
		List front = null;
		population.clear();

		// Obtain the next front
		front = ranking.getSubfront(index);

		while ((remain > 0) && (remain >= front.size()) && !front.isEmpty()) {
			// Assign crowding distance to individuals
			distance.fastEpsilonDominanceAssignment(front, uncoveredGoals);
			// Add the individuals of this front
			population.addAll(front);

			// Decrement remain
			remain = remain - front.size();

			// Obtain the next front
			index++;
			if (remain > 0) {
				front = ranking.getSubfront(index);
			} // if
		} // while

		// Remain is less than front(index).size, insert only the best one
		if (remain > 0 && !front.isEmpty()) { // front contains individuals to insert
			distance.fastEpsilonDominanceAssignment(front, uncoveredGoals);
			Collections.sort(front, new OnlyCrowdingComparator());
			for (int k = 0; k < remain; k++) {
				population.add(front.get(k));
			} // for

			remain = 0;
		} // if
		currentIteration++;
		//logger.error("");
		//logger.error("N. fronts = "+ranking.getNumberOfSubfronts());
		//logger.debug("1* front size = "+ranking.getSubfront(0).size());
		//logger.debug("2* front size = "+ranking.getSubfront(1).size());
		//logger.error("Covered goals = "+this.archive.size());
		//logger.error("Uncovered goals = "+uncoveredGoals.size());
		//logger.debug("Generation=" + currentIteration + " Population Size=" + population.size() + " Archive size=" + archive.size());
	}



	/** {@inheritDoc} */
	@Override
	@SuppressWarnings("unchecked")
	protected void calculateFitness(T c) {
		for (FitnessFunction fitnessFunction : this.fitnessFunctions) {
			double value = fitnessFunction.getFitness(c);
			if (value == 0.0) {
				//((TestChromosome)c).addCoveredGoals(fitnessFunction);
				updateArchive(c, fitnessFunction);
			}
		}
		if (ArrayUtil.contains(Properties.CRITERION, Criterion.EXCEPTION)){
			// if one of the coverage criterion is Criterion.EXCEPTION,
			// then we have to analyze the results of the execution do look
			// for generated exceptions
			List list = deriveCoveredExceptions(c);
			for (ExceptionCoverageTestFitness exp : list){
				// new covered exceptions (goals) have to be added to the archive
				updateArchive(c, (FitnessFunction) exp);
				if (!fitnessFunctions.contains(exp)){
					// let's update the list of fitness functions 
					this.fitnessFunctions.add((FitnessFunction) exp);
					// let's update the newly discovered exceptions to ExceptionCoverageFactory 
					ExceptionCoverageFactory.getGoals().put(exp.toString(), exp);
				}
			}
		}
		notifyEvaluation(c);
		// update the time needed to reach the max coverage
		budgetMonitor.checkMaxCoverage(this.archive.keySet().size());
	}

	/** {@inheritDoc} */
	@Override
	public void generateSolution() {
		logger.info("executing generateSolution function");

		// keep track of covered goals
		for (FitnessFunction goal : fitnessFunctions) {
			uncoveredGoals.add(goal);
		}

		//initialize population
		if (population.isEmpty())
			initializePopulation();

		// Calculate dominance ranks and crowding distance
		ranking.computeRankingAssignment(population, this.uncoveredGoals);
		for (int i = 0; i this.fitnessFunctions (see {@link GeneticAlgorithm}).
	 * 
	 * @return "SuiteChromosome" directly consumable by the Progress Monitor.
	 */
	@Override @SuppressWarnings("unchecked")
	public T getBestIndividual() {
		List archiveContent = this.getArchive();
		if (archiveContent.isEmpty()) {
			return (T) new TestSuiteChromosome();
		}

		TestSuiteChromosome best = new TestSuiteChromosome();
		for (T test : archiveContent) {
			best.addTest((TestChromosome) test);
		}
		// compute overall fitness and coverage
		double coverage = ((double) this.getNumberOfCoveredGoals()) / ((double) this.fitnessFunctions.size());
		for (TestSuiteFitnessFunction suiteFitness : suiteFitnesses){
			best.setCoverage(suiteFitness, coverage);
			best.setFitness(suiteFitness,  this.fitnessFunctions.size() - this.getNumberOfCoveredGoals());
		}
		//suiteFitness.getFitness(best);
		return (T) best;
	}

	protected double numberOfCoveredTargets(){
		return this.archive.keySet().size();
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy