<commit_before>/*
 * Copyright 2014 Ghent University, Bayer CropScience.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jamesframework.core.search.algo;

import java.util.concurrent.TimeUnit;
import org.jamesframework.core.problems.objectives.evaluations.PenalizedEvaluation;
import org.jamesframework.core.subset.SubsetSolution;
import org.jamesframework.core.search.NeighbourhoodSearch;
import org.jamesframework.core.search.Search;
import org.jamesframework.core.search.SearchTestTemplate;
import org.jamesframework.core.search.listeners.SearchListener;
import org.jamesframework.test.stubs.NeverSatisfiedConstraintStub;
import org.jamesframework.test.stubs.NeverSatisfiedPenalizingConstraintStub;
import org.jamesframework.test.util.TestConstants;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Before;

/**
 * Test Metropolis search algorithm.
 * 
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 */
public class MetropolisSearchTest extends SearchTestTemplate {

    // Metropolis searches
    private MetropolisSearch<SubsetSolution> searchLowTemp;
    private MetropolisSearch<SubsetSolution> searchMedTemp;
    private MetropolisSearch<SubsetSolution> searchHighTemp;
    
    // temperatures
    private final double LOW_TEMP  = 0.0000001;
    private final double MED_TEMP  = 0.001;
    private final double HIGH_TEMP = 10.0;
    
    // maximum runtime
    private final long SINGLE_RUN_RUNTIME = 500;
    private final long MULTI_RUN_RUNTIME = 20;
    private final TimeUnit MAX_RUNTIME_TIME_UNIT = TimeUnit.MILLISECONDS;
    
    // number of runs in multi run tests
    private final int NUM_RUNS = 5;
    
    /**
     * Print message when starting tests.
     */
    @BeforeClass
    public static void setUpClass() {
        System.out.println("# Testing MetropolisSearch ...");
        SearchTestTemplate.setUpClass();
    }

    /**
     * Print message when tests are complete.
     */
    @AfterClass
    public static void tearDownClass() {
        System.out.println("# Done testing MetropolisSearch!");
    }
    
    @Override
    @Before
    public void setUp(){
        // call super
        super.setUp();
        // create Metropolis searches
        searchLowTemp = new MetropolisSearch<>(problem, neigh, LOW_TEMP);
        searchMedTemp = new MetropolisSearch<>(problem, neigh, MED_TEMP);
        searchHighTemp = new MetropolisSearch<>(problem, neigh, HIGH_TEMP);
    }
    
    @After
    public void tearDown(){
        // dispose searches
        searchLowTemp.dispose();
        searchMedTemp.dispose();
        searchHighTemp.dispose();
    }

    /**
     * Test single run.
     */
    @Test
    public void testSingleRun() {
        System.out.println(" - test single run");
        // single run
        System.out.format("   - low temperature (T = %.7f)\n", LOW_TEMP);
        singleRunWithMaxRuntime(searchLowTemp, SINGLE_RUN_RUNTIME, MAX_RUNTIME_TIME_UNIT);
        System.out.format("   - medium temperature (T = %.7f)\n", MED_TEMP);
        singleRunWithMaxRuntime(searchMedTemp, SINGLE_RUN_RUNTIME, MAX_RUNTIME_TIME_UNIT);
        System.out.format("   - high temperature (T = %.7f)\n", HIGH_TEMP);
        singleRunWithMaxRuntime(searchHighTemp, SINGLE_RUN_RUNTIME, MAX_RUNTIME_TIME_UNIT);
    }
    
    /**
     * Test single run with unsatisfiable constraint.
     */<commit_msg>improved test coverage for Metropolis search<commit_after>/*
 * Copyright 2014 Ghent University, Bayer CropScience.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jamesframework.core.search.algo;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.jamesframework.core.problems.objectives.evaluations.PenalizedEvaluation;
import org.jamesframework.core.subset.SubsetSolution;
import org.jamesframework.core.search.NeighbourhoodSearch;
import org.jamesframework.core.search.Search;
import org.jamesframework.core.search.SearchTestTemplate;
import org.jamesframework.core.search.listeners.SearchListener;
import org.jamesframework.core.search.neigh.Move;
import org.jamesframework.core.search.neigh.Neighbourhood;
import org.jamesframework.test.stubs.NeverSatisfiedConstraintStub;
import org.jamesframework.test.stubs.NeverSatisfiedPenalizingConstraintStub;
import org.jamesframework.test.util.TestConstants;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Before;

/**
 * Test Metropolis search algorithm.
 * 
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 */
public class MetropolisSearchTest extends SearchTestTemplate {

    // Metropolis searches
    private MetropolisSearch<SubsetSolution> searchLowTemp;
    private MetropolisSearch<SubsetSolution> searchMedTemp;
    private MetropolisSearch<SubsetSolution> searchHighTemp;
    
    // temperatures
    private final double LOW_TEMP  = 0.0000001;
    private final double MED_TEMP  = 0.001;
    private final double HIGH_TEMP = 10.0;
    
    // maximum runtime
    private final long SINGLE_RUN_RUNTIME = 500;
    private final long MULTI_RUN_RUNTIME = 20;
    private final TimeUnit MAX_RUNTIME_TIME_UNIT = TimeUnit.MILLISECONDS;
    
    // number of runs in multi run tests
    private final int NUM_RUNS = 5;
    
    /**
     * Print message when starting tests.
     */
    @BeforeClass
    public static void setUpClass() {
        System.out.println("# Testing MetropolisSearch ...");
        SearchTestTemplate.setUpClass();
    }

    /**
     * Print message when tests are complete.
     */
    @AfterClass
    public static void tearDownClass() {
        System.out.println("# Done testing MetropolisSearch!");
    }
    
    @Override
    @Before
    public void setUp(){
        // call super
        super.setUp();
        // create Metropolis searches
        searchLowTemp = new MetropolisSearch<>(problem, neigh, LOW_TEMP);
        searchMedTemp = new MetropolisSearch<>(problem, neigh, MED_TEMP);
        searchHighTemp = new MetropolisSearch<>(problem, neigh, HIGH_TEMP);
    }
    
    @After
    public void tearDown(){
        // dispose searches
        searchLowTemp.dispose();
        searchMedTemp.dispose();
        searchHighTemp.dispose();
    }

    @Test
    public void testConstructor(){
        
        System.out.println(" - test constructor");
        
        boolean thrown;
                
        thrown = false;
        try {
            new MetropolisSearch<>(problem, neigh, 0.0);
        } catch (IllegalArgumentException ex){
            thrown = true;
        }
        assertTrue(thrown);
        
        thrown = false;
        try {
            new MetropolisSearch<>(problem, neigh, -1.0);
        } catch (IllegalArgumentException ex){
            thrown = true;
        }
        assertTrue(thrown);
        
    }
    
    @Test
    public void testSetTemperature(){
        System.out.println(" - test setTemperature");
        
        boolean thrown;
        
        thrown = false;
        try {
            searchLowTemp.setTemperature(0.0);
        } catch (IllegalArgumentException ex){
            thrown = true;
        }
        assertTrue(thrown);
        
        thrown = false;
        try {
            searchLowTemp.setTemperature(-1.0);
        } catch (IllegalArgumentException ex){
            thrown = true;
        }
        assertTrue(thrown);
    }
    
    @Test
    public void testSetTemperatureScaleFactor(){
        System.out.println(" - test setTemperatureScaleFactor");
        
        boolean thrown;
        
        thrown = false;
        try {
            searchLowTemp.setTemperatureScaleFactor(0.0);
        } catch (IllegalArgumentException ex){
            thrown = true;
        }
        assertTrue(thrown);
        
        thrown = false;
        try {
            searchLowTemp.setTemperatureScaleFactor(-1.0);
        } catch (IllegalArgumentException ex){
            thrown = true;
        }
        assertTrue(thrown);
    }
    
    /**
     * Test single run.
     */
    @Test
    public void testSingleRun() {
        System.out.println(" - test single run");
        // single run
        System.out.format("   - low temperature (T = %.7f)\n", LOW_TEMP);
        singleRunWithMaxRuntime(searchLowTemp, SINGLE_RUN_RUNTIME, MAX_RUNTIME_TIME_UNIT);
        System.out.format("   - medium temperature (T = %.7f)\n", MED_TEMP);
        singleRunWithMaxRuntime(searchMedTemp, SINGLE_RUN_RUNTIME, MAX_RUNTIME_TIME_UNIT);
        System.out.format("   - high temperature (T = %.7f)\n", HIGH_TEMP);
        singleRunWithMaxRuntime(searchHighTemp, SINGLE_RUN_RUNTIME, MAX_RUNTIME_TIME_UNIT);
    }
    
    @Test
    public void testEmptyNeighbourhood() {
        System.out.println(" - test with empty neighbourhood");
        // create empty neighbourhood
        Neighbourhood<SubsetSolution> emptyNeigh = new Neighbourhood<SubsetSolution>() {
            @Override
            public Move<? super SubsetSolution> getRandomMove(SubsetSolution solution) {
                return null;
            }
            @Override
            public List<? extends Move<? super SubsetSolution>> getAllMoves(SubsetSolution solution) {
                return Collections.emptyList();
            }
        };
        // set in searches
        searchLowTemp.setNeighbourhood(emptyNeigh);
        searchMedTemp.setNeighbourhood(emptyNeigh);
        searchHighTemp.setNeighbourhood(emptyNeigh);
        // run searches
        searchLowTemp.start();
        searchMedTemp.start();
        searchHighTemp.start();
        // verify: stopped after first step
        assertEquals(1, searchLowTemp.getSteps());
        assertEquals(1, searchMedTemp.getSteps());
        assertEquals(1, searchHighTemp.getSteps());
    }
    
    /**
     * Test single run with unsatisfiable constraint.
     */
{'fraction_non_alphanumeric': 0.09364487680698245, 'fraction_numerical': 0.007182471133739431, 'mean_word_length': 2.727549983056591, 'pattern_counts': {'":': 0, '<': 30, '<?xml version=': 0, '>': 30, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3837720', 'n_tokens_mistral': 3165, 'n_tokens_neox': 3063, 'n_words': 760}