001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 package org.apache.commons.math.genetics; 018 019 import static org.junit.Assert.*; 020 021 import java.util.ArrayList; 022 import java.util.List; 023 024 import org.junit.Test; 025 026 public class ChromosomeTest { 027 028 @Test 029 public void testCompareTo() { 030 Chromosome c1 = new Chromosome() { 031 public double fitness() { 032 return 0; 033 } 034 }; 035 Chromosome c2 = new Chromosome() { 036 public double fitness() { 037 return 10; 038 } 039 }; 040 Chromosome c3 = new Chromosome() { 041 public double fitness() { 042 return 10; 043 } 044 }; 045 046 assertTrue(c1.compareTo(c2) < 0); 047 assertTrue(c2.compareTo(c1) > 0); 048 assertEquals(0,c3.compareTo(c2)); 049 assertEquals(0,c2.compareTo(c3)); 050 } 051 052 private abstract static class DummyChromosome extends Chromosome { 053 private final int repr; 054 055 public DummyChromosome(final int repr) { 056 this.repr = repr; 057 } 058 @Override 059 protected boolean isSame(Chromosome another) { 060 return ((DummyChromosome) another).repr == repr; 061 } 062 } 063 064 @Test 065 public void testFindSameChromosome() { 066 Chromosome c1 = new DummyChromosome(1) { 067 public double fitness() { 068 return 1; 069 } 070 }; 071 Chromosome c2 = new DummyChromosome(2) { 072 public double fitness() { 073 return 2; 074 } 075 }; 076 Chromosome c3 = new DummyChromosome(3) { 077 public double fitness() { 078 return 3; 079 } 080 }; 081 Chromosome c4 = new DummyChromosome(1) { 082 public double fitness() { 083 return 5; 084 } 085 }; 086 Chromosome c5 = new DummyChromosome(15) { 087 public double fitness() { 088 return 15; 089 } 090 }; 091 092 List<Chromosome> popChr = new ArrayList<Chromosome>(); 093 popChr.add(c1); 094 popChr.add(c2); 095 popChr.add(c3); 096 Population pop = new ListPopulation(popChr,3) { 097 public Population nextGeneration() { 098 // not important 099 return null; 100 } 101 }; 102 103 assertNull(c5.findSameChromosome(pop)); 104 assertEquals(c1, c4.findSameChromosome(pop)); 105 106 c4.searchForFitnessUpdate(pop); 107 assertEquals(1, c4.getFitness(),0); 108 } 109 110 } 111