You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mahout.apache.org by ro...@apache.org on 2010/02/13 20:08:05 UTC
svn commit: r909871 [6/7] - in
/lucene/mahout/trunk/examples/src/main/java/org/apache/mahout: analysis/
cf/taste/ejb/ cf/taste/example/ cf/taste/example/bookcrossing/
cf/taste/example/grouplens/ cf/taste/example/jester/
cf/taste/example/netflix/ classi...
Modified: lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/EuropeanDistanceLookup.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/EuropeanDistanceLookup.java?rev=909871&r1=909870&r2=909871&view=diff
==============================================================================
--- lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/EuropeanDistanceLookup.java (original)
+++ lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/EuropeanDistanceLookup.java Sat Feb 13 19:07:36 2010
@@ -24,302 +24,296 @@
import java.util.Map;
/**
- * This class contains data about cities in Europe and the distances
- * between them.
+ * This class contains data about cities in Europe and the distances between them.
*
* <br>
- * The original code is from <b>the Watchmaker project</b>
- * (https://watchmaker.dev.java.net/).
+ * The original code is from <b>the Watchmaker project</b> (https://watchmaker.dev.java.net/).
*/
-public final class EuropeanDistanceLookup implements DistanceLookup
-{
- private static final Map<String, Map<String, Integer>> DISTANCES = new HashMap<String, Map<String, Integer>>(15);
- static
- {
- // Distances are in km as the crow flies (from http://www.indo.com/distance/)
-
- Map<String, Integer> amsterdam = new HashMap<String, Integer>(20);
- amsterdam.put("Amsterdam", 0);
- amsterdam.put("Athens", 2162);
- amsterdam.put("Berlin", 576);
- amsterdam.put("Brussels", 171);
- amsterdam.put("Copenhagen", 622);
- amsterdam.put("Dublin", 757);
- amsterdam.put("Helsinki", 1506);
- amsterdam.put("Lisbon", 1861);
- amsterdam.put("London", 356);
- amsterdam.put("Luxembourg", 318);
- amsterdam.put("Madrid", 1477);
- amsterdam.put("Paris", 429);
- amsterdam.put("Rome", 1304);
- amsterdam.put("Stockholm", 1132);
- amsterdam.put("Vienna", 938);
- DISTANCES.put("Amsterdam", amsterdam);
-
- Map<String, Integer> athens = new HashMap<String, Integer>(20);
- athens.put("Amsterdam", 2162);
- athens.put("Athens", 0);
- athens.put("Berlin", 1801);
- athens.put("Brussels", 2089);
- athens.put("Copenhagen", 2140);
- athens.put("Dublin", 2860);
- athens.put("Helsinki", 2464);
- athens.put("Lisbon", 2854);
- athens.put("London", 2391);
- athens.put("Luxembourg", 1901);
- athens.put("Madrid", 2374);
- athens.put("Paris", 2097);
- athens.put("Rome", 1040);
- athens.put("Stockholm", 2410);
- athens.put("Vienna", 1280);
- DISTANCES.put("Athens", athens);
-
- Map<String, Integer> berlin = new HashMap<String, Integer>(20);
- berlin.put("Amsterdam", 576);
- berlin.put("Athens", 1801);
- berlin.put("Berlin", 0);
- berlin.put("Brussels", 648);
- berlin.put("Copenhagen", 361);
- berlin.put("Dublin", 1315);
- berlin.put("Helsinki", 1108);
- berlin.put("Lisbon", 2310);
- berlin.put("London", 929);
- berlin.put("Luxembourg", 595);
- berlin.put("Madrid", 1866);
- berlin.put("Paris", 877);
- berlin.put("Rome", 1185);
- berlin.put("Stockholm", 818);
- berlin.put("Vienna", 525);
- DISTANCES.put("Berlin", berlin);
-
- Map<String, Integer> brussels = new HashMap<String, Integer>(20);
- brussels.put("Amsterdam", 171);
- brussels.put("Athens", 2089);
- brussels.put("Berlin", 648);
- brussels.put("Brussels", 0);
- brussels.put("Copenhagen", 764);
- brussels.put("Dublin", 780);
- brussels.put("Helsinki", 1649);
- brussels.put("Lisbon", 1713);
- brussels.put("London", 321);
- brussels.put("Luxembourg", 190);
- brussels.put("Madrid", 1315);
- brussels.put("Paris", 266);
- brussels.put("Rome", 1182);
- brussels.put("Stockholm", 1284);
- brussels.put("Vienna", 917);
- DISTANCES.put("Brussels", brussels);
-
- Map<String, Integer> copenhagen = new HashMap<String, Integer>(20);
- copenhagen.put("Amsterdam", 622);
- copenhagen.put("Athens", 2140);
- copenhagen.put("Berlin", 361);
- copenhagen.put("Brussels", 764);
- copenhagen.put("Copenhagen", 0);
- copenhagen.put("Dublin", 1232);
- copenhagen.put("Helsinki", 885);
- copenhagen.put("Lisbon", 2477);
- copenhagen.put("London", 953);
- copenhagen.put("Luxembourg", 799);
- copenhagen.put("Madrid", 2071);
- copenhagen.put("Paris", 1028);
- copenhagen.put("Rome", 1540);
- copenhagen.put("Stockholm", 526);
- copenhagen.put("Vienna", 876);
- DISTANCES.put("Copenhagen", copenhagen);
-
- Map<String, Integer> dublin = new HashMap<String, Integer>(20);
- dublin.put("Amsterdam", 757);
- dublin.put("Athens", 2860);
- dublin.put("Berlin", 1315);
- dublin.put("Brussels", 780);
- dublin.put("Copenhagen", 1232);
- dublin.put("Dublin", 0);
- dublin.put("Helsinki", 2021);
- dublin.put("Lisbon", 1652);
- dublin.put("London", 469);
- dublin.put("Luxembourg", 961);
- dublin.put("Madrid", 1458);
- dublin.put("Paris", 787);
- dublin.put("Rome", 1903);
- dublin.put("Stockholm", 1625);
- dublin.put("Vienna", 1687);
- DISTANCES.put("Dublin", dublin);
-
- Map<String, Integer> helsinki = new HashMap<String, Integer>(20);
- helsinki.put("Amsterdam", 1506);
- helsinki.put("Athens", 2464);
- helsinki.put("Berlin", 1108);
- helsinki.put("Brussels", 1649);
- helsinki.put("Copenhagen", 885);
- helsinki.put("Dublin", 2021);
- helsinki.put("Helsinki", 0);
- helsinki.put("Lisbon", 3362);
- helsinki.put("London", 1823);
- helsinki.put("Luxembourg", 1667);
- helsinki.put("Madrid", 2949);
- helsinki.put("Paris", 1912);
- helsinki.put("Rome", 2202);
- helsinki.put("Stockholm", 396);
- helsinki.put("Vienna", 1439);
- DISTANCES.put("Helsinki", helsinki);
-
- Map<String, Integer> lisbon = new HashMap<String, Integer>(20);
- lisbon.put("Amsterdam", 1861);
- lisbon.put("Athens", 2854);
- lisbon.put("Berlin", 2310);
- lisbon.put("Brussels", 1713);
- lisbon.put("Copenhagen", 2477);
- lisbon.put("Dublin", 1652);
- lisbon.put("Helsinki", 3362);
- lisbon.put("Lisbon", 0);
- lisbon.put("London", 1585);
- lisbon.put("Luxembourg", 1716);
- lisbon.put("Madrid", 501);
- lisbon.put("Paris", 1452);
- lisbon.put("Rome", 1873);
- lisbon.put("Stockholm", 2993);
- lisbon.put("Vienna", 2300);
- DISTANCES.put("Lisbon", lisbon);
-
- Map<String, Integer> london = new HashMap<String, Integer>(20);
- london.put("Amsterdam", 356);
- london.put("Athens", 2391);
- london.put("Berlin", 929);
- london.put("Brussels", 321);
- london.put("Copenhagen", 953);
- london.put("Dublin", 469);
- london.put("Helsinki", 1823);
- london.put("Lisbon", 1585);
- london.put("London", 0);
- london.put("Luxembourg", 494);
- london.put("Madrid", 1261);
- london.put("Paris", 343);
- london.put("Rome", 1444);
- london.put("Stockholm", 1436);
- london.put("Vienna", 1237);
- DISTANCES.put("London", london);
-
- Map<String, Integer> luxembourg = new HashMap<String, Integer>(20);
- luxembourg.put("Amsterdam", 318);
- luxembourg.put("Athens", 1901);
- luxembourg.put("Berlin", 595);
- luxembourg.put("Brussels", 190);
- luxembourg.put("Copenhagen", 799);
- luxembourg.put("Dublin", 961);
- luxembourg.put("Helsinki", 1667);
- luxembourg.put("Lisbon", 1716);
- luxembourg.put("London", 494);
- luxembourg.put("Luxembourg", 0);
- luxembourg.put("Madrid", 1282);
- luxembourg.put("Paris", 294);
- luxembourg.put("Rome", 995);
- luxembourg.put("Stockholm", 1325);
- luxembourg.put("Vienna", 761);
- DISTANCES.put("Luxembourg", luxembourg);
-
- Map<String, Integer> madrid = new HashMap<String, Integer>(20);
- madrid.put("Amsterdam", 1477);
- madrid.put("Athens", 2374);
- madrid.put("Berlin", 1866);
- madrid.put("Brussels", 1315);
- madrid.put("Copenhagen", 2071);
- madrid.put("Dublin", 1458);
- madrid.put("Helsinki", 2949);
- madrid.put("Lisbon", 501);
- madrid.put("London", 1261);
- madrid.put("Luxembourg", 1282);
- madrid.put("Madrid", 0);
- madrid.put("Paris", 1050);
- madrid.put("Rome", 1377);
- madrid.put("Stockholm", 2596);
- madrid.put("Vienna", 1812);
- DISTANCES.put("Madrid", madrid);
-
- Map<String, Integer> paris = new HashMap<String, Integer>(20);
- paris.put("Amsterdam", 429);
- paris.put("Athens", 2097);
- paris.put("Berlin", 877);
- paris.put("Brussels", 266);
- paris.put("Copenhagen", 1028);
- paris.put("Dublin", 787);
- paris.put("Helsinki", 1912);
- paris.put("Lisbon", 1452);
- paris.put("London", 343);
- paris.put("Luxembourg", 294);
- paris.put("Madrid", 1050);
- paris.put("Paris", 0);
- paris.put("Rome", 1117);
- paris.put("Stockholm", 1549);
- paris.put("Vienna", 1037);
- DISTANCES.put("Paris", paris);
-
- Map<String, Integer> rome = new HashMap<String, Integer>(20);
- rome.put("Amsterdam", 1304);
- rome.put("Athens", 1040);
- rome.put("Berlin", 1185);
- rome.put("Brussels", 1182);
- rome.put("Copenhagen", 1540);
- rome.put("Dublin", 1903);
- rome.put("Helsinki", 2202);
- rome.put("Lisbon", 1873);
- rome.put("London", 1444);
- rome.put("Luxembourg", 995);
- rome.put("Madrid", 1377);
- rome.put("Paris", 1117);
- rome.put("Rome", 0);
- rome.put("Stockholm", 1984);
- rome.put("Vienna", 765);
- DISTANCES.put("Rome", rome);
-
- Map<String, Integer> stockholm = new HashMap<String, Integer>(20);
- stockholm.put("Amsterdam", 1132);
- stockholm.put("Athens", 2410);
- stockholm.put("Berlin", 818);
- stockholm.put("Brussels", 1284);
- stockholm.put("Copenhagen", 526);
- stockholm.put("Dublin", 1625);
- stockholm.put("Helsinki", 396);
- stockholm.put("Lisbon", 2993);
- stockholm.put("London", 1436);
- stockholm.put("Luxembourg", 1325);
- stockholm.put("Madrid", 2596);
- stockholm.put("Paris", 1549);
- stockholm.put("Rome", 1984);
- stockholm.put("Stockholm", 0);
- stockholm.put("Vienna", 1247);
- DISTANCES.put("Stockholm", stockholm);
-
- Map<String, Integer> vienna = new HashMap<String, Integer>(20);
- vienna.put("Amsterdam", 938);
- vienna.put("Athens", 1280);
- vienna.put("Berlin", 525);
- vienna.put("Brussels", 917);
- vienna.put("Copenhagen", 876);
- vienna.put("Dublin", 1687);
- vienna.put("Helsinki", 1439);
- vienna.put("Lisbon", 2300);
- vienna.put("London", 1237);
- vienna.put("Luxembourg", 761);
- vienna.put("Madrid", 1812);
- vienna.put("Paris", 1037);
- vienna.put("Rome", 765);
- vienna.put("Stockholm", 1247);
- vienna.put("Vienna", 0);
- DISTANCES.put("Vienna", vienna);
- }
-
- @Override
- public List<String> getKnownCities()
- {
- List<String> cities = new ArrayList<String>(DISTANCES.keySet());
- Collections.sort(cities);
- return cities;
- }
-
- @Override
- public int getDistance(String startingCity, String destinationCity)
- {
- return DISTANCES.get(startingCity).get(destinationCity);
- }
+public final class EuropeanDistanceLookup implements DistanceLookup {
+ private static final Map<String,Map<String,Integer>> DISTANCES = new HashMap<String,Map<String,Integer>>(15);
+ static {
+ // Distances are in km as the crow flies (from http://www.indo.com/distance/)
+
+ Map<String,Integer> amsterdam = new HashMap<String,Integer>(20);
+ amsterdam.put("Amsterdam", 0);
+ amsterdam.put("Athens", 2162);
+ amsterdam.put("Berlin", 576);
+ amsterdam.put("Brussels", 171);
+ amsterdam.put("Copenhagen", 622);
+ amsterdam.put("Dublin", 757);
+ amsterdam.put("Helsinki", 1506);
+ amsterdam.put("Lisbon", 1861);
+ amsterdam.put("London", 356);
+ amsterdam.put("Luxembourg", 318);
+ amsterdam.put("Madrid", 1477);
+ amsterdam.put("Paris", 429);
+ amsterdam.put("Rome", 1304);
+ amsterdam.put("Stockholm", 1132);
+ amsterdam.put("Vienna", 938);
+ EuropeanDistanceLookup.DISTANCES.put("Amsterdam", amsterdam);
+
+ Map<String,Integer> athens = new HashMap<String,Integer>(20);
+ athens.put("Amsterdam", 2162);
+ athens.put("Athens", 0);
+ athens.put("Berlin", 1801);
+ athens.put("Brussels", 2089);
+ athens.put("Copenhagen", 2140);
+ athens.put("Dublin", 2860);
+ athens.put("Helsinki", 2464);
+ athens.put("Lisbon", 2854);
+ athens.put("London", 2391);
+ athens.put("Luxembourg", 1901);
+ athens.put("Madrid", 2374);
+ athens.put("Paris", 2097);
+ athens.put("Rome", 1040);
+ athens.put("Stockholm", 2410);
+ athens.put("Vienna", 1280);
+ EuropeanDistanceLookup.DISTANCES.put("Athens", athens);
+
+ Map<String,Integer> berlin = new HashMap<String,Integer>(20);
+ berlin.put("Amsterdam", 576);
+ berlin.put("Athens", 1801);
+ berlin.put("Berlin", 0);
+ berlin.put("Brussels", 648);
+ berlin.put("Copenhagen", 361);
+ berlin.put("Dublin", 1315);
+ berlin.put("Helsinki", 1108);
+ berlin.put("Lisbon", 2310);
+ berlin.put("London", 929);
+ berlin.put("Luxembourg", 595);
+ berlin.put("Madrid", 1866);
+ berlin.put("Paris", 877);
+ berlin.put("Rome", 1185);
+ berlin.put("Stockholm", 818);
+ berlin.put("Vienna", 525);
+ EuropeanDistanceLookup.DISTANCES.put("Berlin", berlin);
+
+ Map<String,Integer> brussels = new HashMap<String,Integer>(20);
+ brussels.put("Amsterdam", 171);
+ brussels.put("Athens", 2089);
+ brussels.put("Berlin", 648);
+ brussels.put("Brussels", 0);
+ brussels.put("Copenhagen", 764);
+ brussels.put("Dublin", 780);
+ brussels.put("Helsinki", 1649);
+ brussels.put("Lisbon", 1713);
+ brussels.put("London", 321);
+ brussels.put("Luxembourg", 190);
+ brussels.put("Madrid", 1315);
+ brussels.put("Paris", 266);
+ brussels.put("Rome", 1182);
+ brussels.put("Stockholm", 1284);
+ brussels.put("Vienna", 917);
+ EuropeanDistanceLookup.DISTANCES.put("Brussels", brussels);
+
+ Map<String,Integer> copenhagen = new HashMap<String,Integer>(20);
+ copenhagen.put("Amsterdam", 622);
+ copenhagen.put("Athens", 2140);
+ copenhagen.put("Berlin", 361);
+ copenhagen.put("Brussels", 764);
+ copenhagen.put("Copenhagen", 0);
+ copenhagen.put("Dublin", 1232);
+ copenhagen.put("Helsinki", 885);
+ copenhagen.put("Lisbon", 2477);
+ copenhagen.put("London", 953);
+ copenhagen.put("Luxembourg", 799);
+ copenhagen.put("Madrid", 2071);
+ copenhagen.put("Paris", 1028);
+ copenhagen.put("Rome", 1540);
+ copenhagen.put("Stockholm", 526);
+ copenhagen.put("Vienna", 876);
+ EuropeanDistanceLookup.DISTANCES.put("Copenhagen", copenhagen);
+
+ Map<String,Integer> dublin = new HashMap<String,Integer>(20);
+ dublin.put("Amsterdam", 757);
+ dublin.put("Athens", 2860);
+ dublin.put("Berlin", 1315);
+ dublin.put("Brussels", 780);
+ dublin.put("Copenhagen", 1232);
+ dublin.put("Dublin", 0);
+ dublin.put("Helsinki", 2021);
+ dublin.put("Lisbon", 1652);
+ dublin.put("London", 469);
+ dublin.put("Luxembourg", 961);
+ dublin.put("Madrid", 1458);
+ dublin.put("Paris", 787);
+ dublin.put("Rome", 1903);
+ dublin.put("Stockholm", 1625);
+ dublin.put("Vienna", 1687);
+ EuropeanDistanceLookup.DISTANCES.put("Dublin", dublin);
+
+ Map<String,Integer> helsinki = new HashMap<String,Integer>(20);
+ helsinki.put("Amsterdam", 1506);
+ helsinki.put("Athens", 2464);
+ helsinki.put("Berlin", 1108);
+ helsinki.put("Brussels", 1649);
+ helsinki.put("Copenhagen", 885);
+ helsinki.put("Dublin", 2021);
+ helsinki.put("Helsinki", 0);
+ helsinki.put("Lisbon", 3362);
+ helsinki.put("London", 1823);
+ helsinki.put("Luxembourg", 1667);
+ helsinki.put("Madrid", 2949);
+ helsinki.put("Paris", 1912);
+ helsinki.put("Rome", 2202);
+ helsinki.put("Stockholm", 396);
+ helsinki.put("Vienna", 1439);
+ EuropeanDistanceLookup.DISTANCES.put("Helsinki", helsinki);
+
+ Map<String,Integer> lisbon = new HashMap<String,Integer>(20);
+ lisbon.put("Amsterdam", 1861);
+ lisbon.put("Athens", 2854);
+ lisbon.put("Berlin", 2310);
+ lisbon.put("Brussels", 1713);
+ lisbon.put("Copenhagen", 2477);
+ lisbon.put("Dublin", 1652);
+ lisbon.put("Helsinki", 3362);
+ lisbon.put("Lisbon", 0);
+ lisbon.put("London", 1585);
+ lisbon.put("Luxembourg", 1716);
+ lisbon.put("Madrid", 501);
+ lisbon.put("Paris", 1452);
+ lisbon.put("Rome", 1873);
+ lisbon.put("Stockholm", 2993);
+ lisbon.put("Vienna", 2300);
+ EuropeanDistanceLookup.DISTANCES.put("Lisbon", lisbon);
+
+ Map<String,Integer> london = new HashMap<String,Integer>(20);
+ london.put("Amsterdam", 356);
+ london.put("Athens", 2391);
+ london.put("Berlin", 929);
+ london.put("Brussels", 321);
+ london.put("Copenhagen", 953);
+ london.put("Dublin", 469);
+ london.put("Helsinki", 1823);
+ london.put("Lisbon", 1585);
+ london.put("London", 0);
+ london.put("Luxembourg", 494);
+ london.put("Madrid", 1261);
+ london.put("Paris", 343);
+ london.put("Rome", 1444);
+ london.put("Stockholm", 1436);
+ london.put("Vienna", 1237);
+ EuropeanDistanceLookup.DISTANCES.put("London", london);
+
+ Map<String,Integer> luxembourg = new HashMap<String,Integer>(20);
+ luxembourg.put("Amsterdam", 318);
+ luxembourg.put("Athens", 1901);
+ luxembourg.put("Berlin", 595);
+ luxembourg.put("Brussels", 190);
+ luxembourg.put("Copenhagen", 799);
+ luxembourg.put("Dublin", 961);
+ luxembourg.put("Helsinki", 1667);
+ luxembourg.put("Lisbon", 1716);
+ luxembourg.put("London", 494);
+ luxembourg.put("Luxembourg", 0);
+ luxembourg.put("Madrid", 1282);
+ luxembourg.put("Paris", 294);
+ luxembourg.put("Rome", 995);
+ luxembourg.put("Stockholm", 1325);
+ luxembourg.put("Vienna", 761);
+ EuropeanDistanceLookup.DISTANCES.put("Luxembourg", luxembourg);
+
+ Map<String,Integer> madrid = new HashMap<String,Integer>(20);
+ madrid.put("Amsterdam", 1477);
+ madrid.put("Athens", 2374);
+ madrid.put("Berlin", 1866);
+ madrid.put("Brussels", 1315);
+ madrid.put("Copenhagen", 2071);
+ madrid.put("Dublin", 1458);
+ madrid.put("Helsinki", 2949);
+ madrid.put("Lisbon", 501);
+ madrid.put("London", 1261);
+ madrid.put("Luxembourg", 1282);
+ madrid.put("Madrid", 0);
+ madrid.put("Paris", 1050);
+ madrid.put("Rome", 1377);
+ madrid.put("Stockholm", 2596);
+ madrid.put("Vienna", 1812);
+ EuropeanDistanceLookup.DISTANCES.put("Madrid", madrid);
+
+ Map<String,Integer> paris = new HashMap<String,Integer>(20);
+ paris.put("Amsterdam", 429);
+ paris.put("Athens", 2097);
+ paris.put("Berlin", 877);
+ paris.put("Brussels", 266);
+ paris.put("Copenhagen", 1028);
+ paris.put("Dublin", 787);
+ paris.put("Helsinki", 1912);
+ paris.put("Lisbon", 1452);
+ paris.put("London", 343);
+ paris.put("Luxembourg", 294);
+ paris.put("Madrid", 1050);
+ paris.put("Paris", 0);
+ paris.put("Rome", 1117);
+ paris.put("Stockholm", 1549);
+ paris.put("Vienna", 1037);
+ EuropeanDistanceLookup.DISTANCES.put("Paris", paris);
+
+ Map<String,Integer> rome = new HashMap<String,Integer>(20);
+ rome.put("Amsterdam", 1304);
+ rome.put("Athens", 1040);
+ rome.put("Berlin", 1185);
+ rome.put("Brussels", 1182);
+ rome.put("Copenhagen", 1540);
+ rome.put("Dublin", 1903);
+ rome.put("Helsinki", 2202);
+ rome.put("Lisbon", 1873);
+ rome.put("London", 1444);
+ rome.put("Luxembourg", 995);
+ rome.put("Madrid", 1377);
+ rome.put("Paris", 1117);
+ rome.put("Rome", 0);
+ rome.put("Stockholm", 1984);
+ rome.put("Vienna", 765);
+ EuropeanDistanceLookup.DISTANCES.put("Rome", rome);
+
+ Map<String,Integer> stockholm = new HashMap<String,Integer>(20);
+ stockholm.put("Amsterdam", 1132);
+ stockholm.put("Athens", 2410);
+ stockholm.put("Berlin", 818);
+ stockholm.put("Brussels", 1284);
+ stockholm.put("Copenhagen", 526);
+ stockholm.put("Dublin", 1625);
+ stockholm.put("Helsinki", 396);
+ stockholm.put("Lisbon", 2993);
+ stockholm.put("London", 1436);
+ stockholm.put("Luxembourg", 1325);
+ stockholm.put("Madrid", 2596);
+ stockholm.put("Paris", 1549);
+ stockholm.put("Rome", 1984);
+ stockholm.put("Stockholm", 0);
+ stockholm.put("Vienna", 1247);
+ EuropeanDistanceLookup.DISTANCES.put("Stockholm", stockholm);
+
+ Map<String,Integer> vienna = new HashMap<String,Integer>(20);
+ vienna.put("Amsterdam", 938);
+ vienna.put("Athens", 1280);
+ vienna.put("Berlin", 525);
+ vienna.put("Brussels", 917);
+ vienna.put("Copenhagen", 876);
+ vienna.put("Dublin", 1687);
+ vienna.put("Helsinki", 1439);
+ vienna.put("Lisbon", 2300);
+ vienna.put("London", 1237);
+ vienna.put("Luxembourg", 761);
+ vienna.put("Madrid", 1812);
+ vienna.put("Paris", 1037);
+ vienna.put("Rome", 765);
+ vienna.put("Stockholm", 1247);
+ vienna.put("Vienna", 0);
+ EuropeanDistanceLookup.DISTANCES.put("Vienna", vienna);
+ }
+
+ @Override
+ public List<String> getKnownCities() {
+ List<String> cities = new ArrayList<String>(EuropeanDistanceLookup.DISTANCES.keySet());
+ Collections.sort(cities);
+ return cities;
+ }
+
+ @Override
+ public int getDistance(String startingCity, String destinationCity) {
+ return EuropeanDistanceLookup.DISTANCES.get(startingCity).get(destinationCity);
+ }
}
Modified: lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/EvolutionaryTravellingSalesman.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/EvolutionaryTravellingSalesman.java?rev=909871&r1=909870&r2=909871&view=diff
==============================================================================
--- lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/EvolutionaryTravellingSalesman.java (original)
+++ lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/EvolutionaryTravellingSalesman.java Sat Feb 13 19:07:36 2010
@@ -17,8 +17,14 @@
package org.apache.mahout.ga.watchmaker.travellingsalesman;
-import org.apache.mahout.ga.watchmaker.MahoutFitnessEvaluator;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Random;
+
import org.apache.mahout.common.RandomUtils;
+import org.apache.mahout.ga.watchmaker.MahoutFitnessEvaluator;
import org.uncommons.maths.random.PoissonGenerator;
import org.uncommons.watchmaker.framework.CandidateFactory;
import org.uncommons.watchmaker.framework.ConcurrentEvolutionEngine;
@@ -35,68 +41,64 @@
import org.uncommons.watchmaker.framework.operators.ListOrderMutation;
import org.uncommons.watchmaker.framework.termination.GenerationCount;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Random;
-
/**
- * Evolutionary algorithm for finding (approximate) solutions to the travelling
- * salesman problem.
+ * Evolutionary algorithm for finding (approximate) solutions to the travelling salesman problem.
*
*
* <br>
- * The original code is from <b>the Watchmaker project</b>
- * (https://watchmaker.dev.java.net/).<br>
+ * The original code is from <b>the Watchmaker project</b> (https://watchmaker.dev.java.net/).<br>
* Modified to use Mahout whenever requested.
*/
-public class EvolutionaryTravellingSalesman implements
- TravellingSalesmanStrategy {
+public class EvolutionaryTravellingSalesman implements TravellingSalesmanStrategy {
private final DistanceLookup distances;
-
+
private final SelectionStrategy<? super List<String>> selectionStrategy;
-
+
private final int populationSize;
-
+
private final int eliteCount;
-
+
private final int generationCount;
-
+
private final boolean crossover;
-
+
private final boolean mutation;
-
+
private final boolean mahout;
-
+
/**
- * Creates an evolutionary Travelling Salesman solver with the specified
- * configuration.
+ * Creates an evolutionary Travelling Salesman solver with the specified configuration.
*
- * @param distances Information about the distances between cities.
- * @param selectionStrategy The selection implementation to use for the
- * evolutionary algorithm.
- * @param populationSize The number of candidates in the population of evolved
- * routes.
- * @param eliteCount The number of candidates to preserve via elitism at each
- * generation.
- * @param generationCount The number of iterations of evolution to perform.
- * @param crossover Whether or not to use a cross-over operator in the
- * evolution.
- * @param mutation Whether or not to use a mutation operator in the evolution.
- * @param mahout Whether or not to use Mahout for evaluation.
+ * @param distances
+ * Information about the distances between cities.
+ * @param selectionStrategy
+ * The selection implementation to use for the evolutionary algorithm.
+ * @param populationSize
+ * The number of candidates in the population of evolved routes.
+ * @param eliteCount
+ * The number of candidates to preserve via elitism at each generation.
+ * @param generationCount
+ * The number of iterations of evolution to perform.
+ * @param crossover
+ * Whether or not to use a cross-over operator in the evolution.
+ * @param mutation
+ * Whether or not to use a mutation operator in the evolution.
+ * @param mahout
+ * Whether or not to use Mahout for evaluation.
*/
public EvolutionaryTravellingSalesman(DistanceLookup distances,
- SelectionStrategy<? super List<String>> selectionStrategy,
- int populationSize, int eliteCount, int generationCount,
- boolean crossover, boolean mutation, boolean mahout) {
+ SelectionStrategy<? super List<String>> selectionStrategy,
+ int populationSize,
+ int eliteCount,
+ int generationCount,
+ boolean crossover,
+ boolean mutation,
+ boolean mahout) {
if (eliteCount < 0 || eliteCount >= populationSize) {
- throw new IllegalArgumentException(
- "Elite count must be non-zero and less than population size.");
+ throw new IllegalArgumentException("Elite count must be non-zero and less than population size.");
}
if (!crossover && !mutation) {
- throw new IllegalArgumentException(
- "At least one of cross-over or mutation must be selected.");
+ throw new IllegalArgumentException("At least one of cross-over or mutation must be selected.");
}
this.distances = distances;
this.selectionStrategy = selectionStrategy;
@@ -107,42 +109,40 @@
this.mutation = mutation;
this.mahout = mahout;
}
-
+
@Override
public String getDescription() {
String selectionName = selectionStrategy.getClass().getSimpleName();
- return (mahout ? "Mahout " : "") + "Evolution (pop: " + populationSize
- + ", gen: " + generationCount + ", elite: " + eliteCount + ", "
- + selectionName + ')';
+ return (mahout ? "Mahout " : "") + "Evolution (pop: " + populationSize + ", gen: " + generationCount
+ + ", elite: " + eliteCount + ", " + selectionName + ')';
}
-
+
/**
- * Calculates the shortest route using a generational evolutionary algorithm
- * with a single ordered mutation operator and truncation selection.
+ * Calculates the shortest route using a generational evolutionary algorithm with a single ordered mutation
+ * operator and truncation selection.
*
- * @param cities The list of destinations, each of which must be visited once.
- * @param progressListener Call-back for receiving the status of the algorithm
- * as it progresses.
- * @return The (approximate) shortest route that visits each of the specified
- * cities once.
+ * @param cities
+ * The list of destinations, each of which must be visited once.
+ * @param progressListener
+ * Call-back for receiving the status of the algorithm as it progresses.
+ * @return The (approximate) shortest route that visits each of the specified cities once.
*/
@Override
public List<String> calculateShortestRoute(Collection<String> cities,
- final ProgressListener progressListener) {
+ final ProgressListener progressListener) {
Random rng = RandomUtils.getRandom();
-
+
// Set-up evolution pipeline (cross-over followed by mutation).
List<EvolutionaryOperator<List<String>>> operators = new ArrayList<EvolutionaryOperator<List<String>>>(2);
if (crossover) {
operators.add(new ListOrderCrossover());
}
if (mutation) {
- operators.add(new ListOrderMutation(new PoissonGenerator(1.5, rng),
- new PoissonGenerator(1.5, rng)));
+ operators.add(new ListOrderMutation(new PoissonGenerator(1.5, rng), new PoissonGenerator(1.5, rng)));
}
-
+
EvolutionaryOperator<List<String>> pipeline = new EvolutionPipeline<List<String>>(operators);
-
+
CandidateFactory<List<String>> candidateFactory = new ListPermutationFactory<String>(
new LinkedList<String>(cities));
EvolutionEngine<List<String>> engine = getEngine(candidateFactory, pipeline, rng);
@@ -150,19 +150,16 @@
@Override
public void populationUpdate(PopulationData<? extends List<String>> data) {
if (progressListener != null) {
- progressListener
- .updateProgress(((double) data.getGenerationNumber() + 1)
- / generationCount * 100);
+ progressListener.updateProgress(((double) data.getGenerationNumber() + 1) / generationCount * 100);
}
}
});
- return engine.evolve(populationSize, eliteCount, new GenerationCount(
- generationCount));
+ return engine.evolve(populationSize, eliteCount, new GenerationCount(generationCount));
}
-
- private EvolutionEngine<List<String>> getEngine(
- CandidateFactory<List<String>> candidateFactory,
- EvolutionaryOperator<List<String>> pipeline, Random rng) {
+
+ private EvolutionEngine<List<String>> getEngine(CandidateFactory<List<String>> candidateFactory,
+ EvolutionaryOperator<List<String>> pipeline,
+ Random rng) {
if (mahout) {
// This is what we need to do to distribute the fitness evaluation.
// First create a STFitnessEvaluator that wraps our FitnessEvaluator
@@ -170,11 +167,11 @@
new RouteEvaluator(distances));
// Then use a SequentialEvolutionEngine instead of a StandaloneEvolutionEngine.
// Its parameters remain the same.
- return new SequentialEvolutionEngine<List<String>>(candidateFactory, pipeline,
- evaluator, selectionStrategy, rng);
+ return new SequentialEvolutionEngine<List<String>>(candidateFactory, pipeline, evaluator,
+ selectionStrategy, rng);
} else {
- return new ConcurrentEvolutionEngine<List<String>>(candidateFactory,
- pipeline, new RouteEvaluator(distances), selectionStrategy, rng);
+ return new ConcurrentEvolutionEngine<List<String>>(candidateFactory, pipeline, new RouteEvaluator(
+ distances), selectionStrategy, rng);
}
}
}
Modified: lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/ExecutionPanel.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/ExecutionPanel.java?rev=909871&r1=909870&r2=909871&view=diff
==============================================================================
--- lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/ExecutionPanel.java (original)
+++ lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/ExecutionPanel.java Sat Feb 13 19:07:36 2010
@@ -20,6 +20,7 @@
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionListener;
+
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
@@ -29,85 +30,74 @@
import javax.swing.SwingUtilities;
/**
- * Panel for controlling the execution of the Travelling Salesman applet.
- * Contains controls for starting and stopping the route-finding algorithms
- * and for displaying progress and results.
+ * Panel for controlling the execution of the Travelling Salesman applet. Contains controls for starting and
+ * stopping the route-finding algorithms and for displaying progress and results.
*
* <br>
- * The original code is from <b>the Watchmaker project</b>
- * (https://watchmaker.dev.java.net/).
+ * The original code is from <b>the Watchmaker project</b> (https://watchmaker.dev.java.net/).
*/
final class ExecutionPanel extends JPanel implements ProgressListener {
-
- private final JButton startButton;
- private final JTextArea output;
- private final JScrollPane scroller;
- private final JProgressBar progressBar;
-
- ExecutionPanel()
- {
- super(new BorderLayout());
- JPanel controlPanel = new JPanel(new BorderLayout());
- startButton = new JButton("Start");
- controlPanel.add(startButton, BorderLayout.WEST);
- progressBar = new JProgressBar(0, 100);
- controlPanel.add(progressBar, BorderLayout.CENTER);
- add(controlPanel, BorderLayout.NORTH);
- output = new JTextArea();
- output.setEditable(false);
- output.setLineWrap(true);
- output.setWrapStyleWord(true);
- output.setFont(new Font("Monospaced", Font.PLAIN, 12));
- scroller = new JScrollPane(output);
- scroller.setBorder(BorderFactory.createTitledBorder("Results"));
- add(scroller, BorderLayout.CENTER);
- }
-
-
- /**
- * Adds logic to the start button so that something happens when
- * it is clicked.
- * @param actionListener The action to perform when the button is
- * clicked.
- */
- public void addActionListener(ActionListener actionListener)
- {
- startButton.addActionListener(actionListener);
- }
-
-
- /**
- * Updates the position of the progress bar.
- */
- @Override
- public void updateProgress(final double percentComplete)
- {
- SwingUtilities.invokeLater(new Runnable()
- {
- @Override
- public void run()
- {
- progressBar.setValue((int) percentComplete);
- }
- });
- }
-
-
- /**
- * Appends the specified text to this panel's text area.
- * @param text The text to append.
- */
- public void appendOutput(String text)
- {
- output.append(text);
- }
-
-
- @Override
- public void setEnabled(boolean b)
- {
- startButton.setEnabled(b);
- scroller.setEnabled(b);
- super.setEnabled(b);
- }
+
+ private final JButton startButton;
+ private final JTextArea output;
+ private final JScrollPane scroller;
+ private final JProgressBar progressBar;
+
+ ExecutionPanel() {
+ super(new BorderLayout());
+ JPanel controlPanel = new JPanel(new BorderLayout());
+ startButton = new JButton("Start");
+ controlPanel.add(startButton, BorderLayout.WEST);
+ progressBar = new JProgressBar(0, 100);
+ controlPanel.add(progressBar, BorderLayout.CENTER);
+ add(controlPanel, BorderLayout.NORTH);
+ output = new JTextArea();
+ output.setEditable(false);
+ output.setLineWrap(true);
+ output.setWrapStyleWord(true);
+ output.setFont(new Font("Monospaced", Font.PLAIN, 12));
+ scroller = new JScrollPane(output);
+ scroller.setBorder(BorderFactory.createTitledBorder("Results"));
+ add(scroller, BorderLayout.CENTER);
+ }
+
+ /**
+ * Adds logic to the start button so that something happens when it is clicked.
+ *
+ * @param actionListener
+ * The action to perform when the button is clicked.
+ */
+ public void addActionListener(ActionListener actionListener) {
+ startButton.addActionListener(actionListener);
+ }
+
+ /**
+ * Updates the position of the progress bar.
+ */
+ @Override
+ public void updateProgress(final double percentComplete) {
+ SwingUtilities.invokeLater(new Runnable() {
+ @Override
+ public void run() {
+ progressBar.setValue((int) percentComplete);
+ }
+ });
+ }
+
+ /**
+ * Appends the specified text to this panel's text area.
+ *
+ * @param text
+ * The text to append.
+ */
+ public void appendOutput(String text) {
+ output.append(text);
+ }
+
+ @Override
+ public void setEnabled(boolean b) {
+ startButton.setEnabled(b);
+ scroller.setEnabled(b);
+ super.setEnabled(b);
+ }
}
Modified: lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/ItineraryPanel.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/ItineraryPanel.java?rev=909871&r1=909870&r2=909871&view=diff
==============================================================================
--- lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/ItineraryPanel.java (original)
+++ lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/ItineraryPanel.java Sat Feb 13 19:07:36 2010
@@ -26,91 +26,78 @@
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
+
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
/**
- * Component for selecting which cities are to be visited by the
- * travelling salesman.
+ * Component for selecting which cities are to be visited by the travelling salesman.
*
* <br>
- * The original code is from <b>the Watchmaker project</b>
- * (https://watchmaker.dev.java.net/).
+ * The original code is from <b>the Watchmaker project</b> (https://watchmaker.dev.java.net/).
*/
final class ItineraryPanel extends JPanel {
-
- private final Collection<JCheckBox> checkBoxes;
- private final JButton selectAllButton;
- private final JButton clearButton;
-
- ItineraryPanel(List<String> cities)
- {
- super(new BorderLayout());
-
- JPanel checkBoxPanel = new JPanel(new GridLayout(0, 1));
- checkBoxes = new ArrayList<JCheckBox>(cities.size());
- for (String city : cities)
- {
- JCheckBox checkBox = new JCheckBox(city, false);
- checkBoxes.add(checkBox);
- checkBoxPanel.add(checkBox);
- }
- add(checkBoxPanel, BorderLayout.CENTER);
-
- JPanel buttonPanel = new JPanel(new GridLayout(2, 1));
- selectAllButton = new JButton("Select All");
- buttonPanel.add(selectAllButton);
- clearButton = new JButton("Clear Selection");
- buttonPanel.add(clearButton);
- ActionListener buttonListener = new ActionListener()
- {
-
- @Override
- public void actionPerformed(ActionEvent actionEvent)
- {
- boolean select = actionEvent.getSource() == selectAllButton;
- for (JCheckBox checkBox : checkBoxes)
- {
- checkBox.setSelected(select);
- }
- }
- };
- selectAllButton.addActionListener(buttonListener);
- clearButton.addActionListener(buttonListener);
- add(buttonPanel, BorderLayout.SOUTH);
-
- setBorder(BorderFactory.createTitledBorder("Itinerary"));
+
+ private final Collection<JCheckBox> checkBoxes;
+ private final JButton selectAllButton;
+ private final JButton clearButton;
+
+ ItineraryPanel(List<String> cities) {
+ super(new BorderLayout());
+
+ JPanel checkBoxPanel = new JPanel(new GridLayout(0, 1));
+ checkBoxes = new ArrayList<JCheckBox>(cities.size());
+ for (String city : cities) {
+ JCheckBox checkBox = new JCheckBox(city, false);
+ checkBoxes.add(checkBox);
+ checkBoxPanel.add(checkBox);
}
-
-
- /**
- * Returns the cities that have been selected as part of the itinerary.
- */
- public Collection<String> getSelectedCities()
- {
- Set<String> cities = new TreeSet<String>();
- for (JCheckBox checkBox : checkBoxes)
- {
- if (checkBox.isSelected())
- {
- cities.add(checkBox.getText());
- }
+ add(checkBoxPanel, BorderLayout.CENTER);
+
+ JPanel buttonPanel = new JPanel(new GridLayout(2, 1));
+ selectAllButton = new JButton("Select All");
+ buttonPanel.add(selectAllButton);
+ clearButton = new JButton("Clear Selection");
+ buttonPanel.add(clearButton);
+ ActionListener buttonListener = new ActionListener() {
+
+ @Override
+ public void actionPerformed(ActionEvent actionEvent) {
+ boolean select = actionEvent.getSource() == selectAllButton;
+ for (JCheckBox checkBox : checkBoxes) {
+ checkBox.setSelected(select);
}
- return cities;
+ }
+ };
+ selectAllButton.addActionListener(buttonListener);
+ clearButton.addActionListener(buttonListener);
+ add(buttonPanel, BorderLayout.SOUTH);
+
+ setBorder(BorderFactory.createTitledBorder("Itinerary"));
+ }
+
+ /**
+ * Returns the cities that have been selected as part of the itinerary.
+ */
+ public Collection<String> getSelectedCities() {
+ Set<String> cities = new TreeSet<String>();
+ for (JCheckBox checkBox : checkBoxes) {
+ if (checkBox.isSelected()) {
+ cities.add(checkBox.getText());
+ }
}
-
-
- @Override
- public void setEnabled(boolean b)
- {
- for (JCheckBox checkBox : checkBoxes)
- {
- checkBox.setEnabled(b);
- }
- selectAllButton.setEnabled(b);
- clearButton.setEnabled(b);
- super.setEnabled(b);
+ return cities;
+ }
+
+ @Override
+ public void setEnabled(boolean b) {
+ for (JCheckBox checkBox : checkBoxes) {
+ checkBox.setEnabled(b);
}
+ selectAllButton.setEnabled(b);
+ clearButton.setEnabled(b);
+ super.setEnabled(b);
+ }
}
Modified: lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/ProgressListener.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/ProgressListener.java?rev=909871&r1=909870&r2=909871&view=diff
==============================================================================
--- lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/ProgressListener.java (original)
+++ lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/ProgressListener.java Sat Feb 13 19:07:36 2010
@@ -18,19 +18,18 @@
package org.apache.mahout.ga.watchmaker.travellingsalesman;
/**
- * Call-back interface for keeping track of the progress of a
- * {@link TravellingSalesmanStrategy} implementation.
+ * Call-back interface for keeping track of the progress of a {@link TravellingSalesmanStrategy}
+ * implementation.
*
* <br>
- * The original code is from <b>the Watchmaker project</b>
- * (https://watchmaker.dev.java.net/).
+ * The original code is from <b>the Watchmaker project</b> (https://watchmaker.dev.java.net/).
*/
-public interface ProgressListener
-{
- /**
- * Call-back method that informs the implementing object
- * of the current completion percentage.
- * @param percentComplete A percentage between 0 and 100.
- */
- void updateProgress(double percentComplete);
+public interface ProgressListener {
+ /**
+ * Call-back method that informs the implementing object of the current completion percentage.
+ *
+ * @param percentComplete
+ * A percentage between 0 and 100.
+ */
+ void updateProgress(double percentComplete);
}
Modified: lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/RouteEvaluator.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/RouteEvaluator.java?rev=909871&r1=909870&r2=909871&view=diff
==============================================================================
--- lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/RouteEvaluator.java (original)
+++ lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/RouteEvaluator.java Sat Feb 13 19:07:36 2010
@@ -17,66 +17,58 @@
package org.apache.mahout.ga.watchmaker.travellingsalesman;
-import org.uncommons.watchmaker.framework.FitnessEvaluator;
-
import java.util.List;
+import org.uncommons.watchmaker.framework.FitnessEvaluator;
+
/**
- * Fitness evalator that measures the total distance of a route in the travelling salesman
- * problem. The fitness score of a route is the total distance (in km). A route
- * is represented as a list of cities in the order that they will be visited.
- * The last leg of the journey is from the last city in the list back to the
+ * Fitness evalator that measures the total distance of a route in the travelling salesman problem. The
+ * fitness score of a route is the total distance (in km). A route is represented as a list of cities in the
+ * order that they will be visited. The last leg of the journey is from the last city in the list back to the
* first.
*
* <br>
- * The original code is from <b>the Watchmaker project</b>
- * (https://watchmaker.dev.java.net/).
+ * The original code is from <b>the Watchmaker project</b> (https://watchmaker.dev.java.net/).
*/
-public class RouteEvaluator implements FitnessEvaluator<List<String>>
-{
- private final DistanceLookup distances;
-
-
- /**
- * @param distances Provides distances between a set of cities.
- */
- public RouteEvaluator(DistanceLookup distances)
- {
- this.distances = distances;
- }
-
-
- /**
- * Calculates the length of an evolved route.
- * @param candidate The route to evaluate.
- * @param population {@inheritDoc}
- * @return The total distance (in kilometres) of a journey that visits
- * each city in order and returns to the starting point.
- */
- @Override
- public double getFitness(List<String> candidate,
- List<? extends List<String>> population)
- {
- int totalDistance = 0;
- int cityCount = candidate.size();
- for (int i = 0; i < cityCount; i++)
- {
- int nextIndex = i < cityCount - 1 ? i + 1 : 0;
- totalDistance += distances.getDistance(candidate.get(i),
- candidate.get(nextIndex));
- }
- return totalDistance;
- }
-
-
- /**
- * {@inheritDoc}
- * Returns false since shorter distances represent fitter candidates.
- * @return false
- */
- @Override
- public boolean isNatural()
- {
- return false;
+public class RouteEvaluator implements FitnessEvaluator<List<String>> {
+ private final DistanceLookup distances;
+
+ /**
+ * @param distances
+ * Provides distances between a set of cities.
+ */
+ public RouteEvaluator(DistanceLookup distances) {
+ this.distances = distances;
+ }
+
+ /**
+ * Calculates the length of an evolved route.
+ *
+ * @param candidate
+ * The route to evaluate.
+ * @param population
+ * {@inheritDoc}
+ * @return The total distance (in kilometres) of a journey that visits each city in order and returns to the
+ * starting point.
+ */
+ @Override
+ public double getFitness(List<String> candidate, List<? extends List<String>> population) {
+ int totalDistance = 0;
+ int cityCount = candidate.size();
+ for (int i = 0; i < cityCount; i++) {
+ int nextIndex = i < cityCount - 1 ? i + 1 : 0;
+ totalDistance += distances.getDistance(candidate.get(i), candidate.get(nextIndex));
}
+ return totalDistance;
+ }
+
+ /**
+ * {@inheritDoc} Returns false since shorter distances represent fitter candidates.
+ *
+ * @return false
+ */
+ @Override
+ public boolean isNatural() {
+ return false;
+ }
}
Modified: lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/StrategyPanel.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/StrategyPanel.java?rev=909871&r1=909870&r2=909871&view=diff
==============================================================================
--- lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/StrategyPanel.java (original)
+++ lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/StrategyPanel.java Sat Feb 13 19:07:36 2010
@@ -47,30 +47,27 @@
import org.uncommons.watchmaker.framework.selection.TruncationSelection;
/**
- * Panel for configuring a route-finding strategy for the travelling salesman
- * problem.
+ * Panel for configuring a route-finding strategy for the travelling salesman problem.
*
* <br>
- * The original code is from <b>the Watchmaker project</b>
- * (https://watchmaker.dev.java.net/).<br>
- * The <code>EvolutionPanel</code> has been modified to add a "distributed
- * (mahout)" JCheckBox.
+ * The original code is from <b>the Watchmaker project</b> (https://watchmaker.dev.java.net/).<br>
+ * The <code>EvolutionPanel</code> has been modified to add a "distributed (mahout)" JCheckBox.
*/
final class StrategyPanel extends JPanel {
-
+
private final DistanceLookup distances;
-
+
private final JRadioButton evolutionOption;
-
+
private final JRadioButton bruteForceOption;
-
+
private final EvolutionPanel evolutionPanel;
-
+
/**
* Creates a panel with components for controlling the route-finding strategy.
*
- * @param distances Data used by the strategy in order to calculate shortest
- * routes.
+ * @param distances
+ * Data used by the strategy in order to calculate shortest routes.
*/
StrategyPanel(DistanceLookup distances) {
super(new BorderLayout());
@@ -92,7 +89,7 @@
add(bruteForceOption, BorderLayout.SOUTH);
setBorder(BorderFactory.createTitledBorder("Route-Finding Strategy"));
}
-
+
public TravellingSalesmanStrategy getStrategy() {
if (bruteForceOption.isSelected()) {
return new BruteForceTravellingSalesman(distances);
@@ -100,7 +97,7 @@
return evolutionPanel.getStrategy();
}
}
-
+
@Override
public void setEnabled(boolean b) {
evolutionOption.setEnabled(b);
@@ -108,91 +105,92 @@
evolutionPanel.setEnabled(b && evolutionOption.isSelected());
super.setEnabled(b);
}
-
+
/**
* Panel of evolution controls.
*/
private final class EvolutionPanel extends JPanel {
private final JLabel populationLabel;
-
+
private final JSpinner populationSpinner;
-
+
private final JLabel elitismLabel;
-
+
private final JSpinner elitismSpinner;
-
+
private final JLabel generationsLabel;
-
+
private final JSpinner generationsSpinner;
-
+
private final JLabel selectionLabel;
-
+
private final JComboBox selectionCombo;
-
+
private final JCheckBox crossoverCheckbox;
-
+
private final JCheckBox mutationCheckbox;
-
+
private final JCheckBox distributedCheckbox;
-
+
EvolutionPanel() {
super(new FlowLayout(FlowLayout.LEFT, 0, 0));
JPanel innerPanel = new JPanel(new SpringLayout());
-
+
populationLabel = new JLabel("Population Size: ");
populationSpinner = new JSpinner(new SpinnerNumberModel(300, 2, 10000, 1));
populationLabel.setLabelFor(populationSpinner);
innerPanel.add(populationLabel);
innerPanel.add(populationSpinner);
-
+
elitismLabel = new JLabel("Elitism: ");
elitismSpinner = new JSpinner(new SpinnerNumberModel(3, 0, 10000, 1));
elitismLabel.setLabelFor(elitismSpinner);
innerPanel.add(elitismLabel);
innerPanel.add(elitismSpinner);
-
+
generationsLabel = new JLabel("Number of Generations: ");
- generationsSpinner = new JSpinner(
- new SpinnerNumberModel(100, 1, 10000, 1));
+ generationsSpinner = new JSpinner(new SpinnerNumberModel(100, 1, 10000, 1));
generationsLabel.setLabelFor(generationsSpinner);
innerPanel.add(generationsLabel);
innerPanel.add(generationsSpinner);
-
+
selectionLabel = new JLabel("Selection Strategy: ");
innerPanel.add(selectionLabel);
-
- SelectionStrategy<?>[] selectionStrategies = {
- new RankSelection(), new RouletteWheelSelection(),
- new StochasticUniversalSampling(), new TournamentSelection(new Probability(0.95)),
- new TruncationSelection(0.5)};
-
+
+ SelectionStrategy<?>[] selectionStrategies = {new RankSelection(), new RouletteWheelSelection(),
+ new StochasticUniversalSampling(),
+ new TournamentSelection(new Probability(0.95)),
+ new TruncationSelection(0.5)};
+
selectionCombo = new JComboBox(selectionStrategies);
selectionCombo.setRenderer(new DefaultListCellRenderer() {
@Override
- public Component getListCellRendererComponent(JList list, Object value,
- int index, boolean isSelected, boolean hasFocus) {
+ public Component getListCellRendererComponent(JList list,
+ Object value,
+ int index,
+ boolean isSelected,
+ boolean hasFocus) {
SelectionStrategy<?> strategy = (SelectionStrategy<?>) value;
String text = strategy.getClass().getSimpleName();
- return super.getListCellRendererComponent(list, text, index,
- isSelected, hasFocus);
+ return super.getListCellRendererComponent(list, text, index, isSelected, hasFocus);
}
});
selectionCombo.setSelectedIndex(selectionCombo.getItemCount() - 1);
innerPanel.add(selectionCombo);
-
+
crossoverCheckbox = new JCheckBox("Cross-over", true);
mutationCheckbox = new JCheckBox("Mutation", true);
distributedCheckbox = new JCheckBox("Distributed (Mahout)", false);
-
+
innerPanel.add(crossoverCheckbox);
innerPanel.add(mutationCheckbox);
innerPanel.add(distributedCheckbox);
innerPanel.add(new JLabel()); // pour avoir un nombre paire de components
-
+
SpringUtilities.makeCompactGrid(innerPanel, 6, 2, 30, 6, 6, 6);
add(innerPanel);
}
-
+
@Override
public void setEnabled(boolean b) {
populationLabel.setEnabled(b);
@@ -208,13 +206,12 @@
distributedCheckbox.setEnabled(b);
super.setEnabled(b);
}
-
+
public TravellingSalesmanStrategy getStrategy() {
return new EvolutionaryTravellingSalesman(distances,
- (SelectionStrategy<? super List<String>>) selectionCombo
- .getSelectedItem(), (Integer) populationSpinner.getValue(),
- (Integer) elitismSpinner.getValue(), (Integer) generationsSpinner
- .getValue(), crossoverCheckbox.isSelected(), mutationCheckbox
+ (SelectionStrategy<? super List<String>>) selectionCombo.getSelectedItem(),
+ (Integer) populationSpinner.getValue(), (Integer) elitismSpinner.getValue(),
+ (Integer) generationsSpinner.getValue(), crossoverCheckbox.isSelected(), mutationCheckbox
.isSelected(), distributedCheckbox.isSelected());
}
}
Modified: lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/TravellingSalesman.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/TravellingSalesman.java?rev=909871&r1=909870&r2=909871&view=diff
==============================================================================
--- lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/TravellingSalesman.java (original)
+++ lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/TravellingSalesman.java Sat Feb 13 19:07:36 2010
@@ -24,33 +24,30 @@
import java.util.Collection;
import java.util.List;
-import org.uncommons.swing.SwingBackgroundTask;
-import org.uncommons.watchmaker.framework.FitnessEvaluator;
-
import javax.swing.JApplet;
-import javax.swing.JPanel;
-import javax.swing.JOptionPane;
import javax.swing.JDialog;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
import javax.swing.WindowConstants;
+import org.uncommons.swing.SwingBackgroundTask;
+import org.uncommons.watchmaker.framework.FitnessEvaluator;
+
/**
- * Applet for comparing evolutionary and brute force approaches to the
- * Travelling Salesman problem.
+ * Applet for comparing evolutionary and brute force approaches to the Travelling Salesman problem.
*
- * The original code is from <b>the Watchmaker project</b>
- * (https://watchmaker.dev.java.net/). <br>
- * This class has been modified to add a main function that runs the JApplet
- * inside a JDialog.
+ * The original code is from <b>the Watchmaker project</b> (https://watchmaker.dev.java.net/). <br>
+ * This class has been modified to add a main function that runs the JApplet inside a JDialog.
*/
public final class TravellingSalesman extends JApplet {
private final ItineraryPanel itineraryPanel;
-
+
private final StrategyPanel strategyPanel;
-
+
private final ExecutionPanel executionPanel;
-
+
private final FitnessEvaluator<List<String>> evaluator;
-
+
/**
* Creates the applet and lays out its GUI.
*/
@@ -65,22 +62,21 @@
innerPanel.add(strategyPanel, BorderLayout.NORTH);
innerPanel.add(executionPanel, BorderLayout.CENTER);
add(innerPanel, BorderLayout.CENTER);
-
+
executionPanel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
Collection<String> cities = itineraryPanel.getSelectedCities();
if (cities.size() < 4) {
- JOptionPane.showMessageDialog(TravellingSalesman.this,
- "Itinerary must include at least 4 cities.", "Error",
- JOptionPane.ERROR_MESSAGE);
+ JOptionPane.showMessageDialog(TravellingSalesman.this, "Itinerary must include at least 4 cities.",
+ "Error", JOptionPane.ERROR_MESSAGE);
} else {
try {
setEnabled(false);
createTask(cities).execute();
} catch (IllegalArgumentException ex) {
- JOptionPane.showMessageDialog(TravellingSalesman.this, ex
- .getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
+ JOptionPane.showMessageDialog(TravellingSalesman.this, ex.getMessage(), "Error",
+ JOptionPane.ERROR_MESSAGE);
setEnabled(true);
}
}
@@ -88,45 +84,43 @@
});
validate();
}
-
+
/**
- * Helper method to create a background task for running the travelling
- * salesman algorithm.
+ * Helper method to create a background task for running the travelling salesman algorithm.
*
- * @param cities The set of cities to generate a route for.
- * @return A Swing task that will execute on a background thread and update
- * the GUI when it is done.
+ * @param cities
+ * The set of cities to generate a route for.
+ * @return A Swing task that will execute on a background thread and update the GUI when it is done.
*/
- private SwingBackgroundTask<List<String>> createTask(
- final Collection<String> cities) {
+ private SwingBackgroundTask<List<String>> createTask(final Collection<String> cities) {
final TravellingSalesmanStrategy strategy = strategyPanel.getStrategy();
return new SwingBackgroundTask<List<String>>() {
private long elapsedTime = 0;
-
+
@Override
protected List<String> performTask() {
long startTime = System.currentTimeMillis();
- List<String> result = strategy.calculateShortestRoute(cities,
- executionPanel);
+ List<String> result = strategy.calculateShortestRoute(cities, executionPanel);
elapsedTime = System.currentTimeMillis() - startTime;
return result;
}
-
+
@Override
protected void postProcessing(List<String> result) {
- executionPanel.appendOutput(createResultString(strategy
- .getDescription(), result, evaluator.getFitness(result, null),
- elapsedTime));
+ executionPanel.appendOutput(TravellingSalesman.createResultString(strategy.getDescription(), result,
+ evaluator.getFitness(result, null), elapsedTime));
setEnabled(true);
}
};
}
-
+
/**
* Helper method for formatting a result as a string for display.
*/
private static String createResultString(String strategyDescription,
- List<String> shortestRoute, double distance, long elapsedTime) {
+ List<String> shortestRoute,
+ double distance,
+ long elapsedTime) {
StringBuilder buffer = new StringBuilder();
buffer.append('[');
buffer.append(strategyDescription);
@@ -147,12 +141,12 @@
buffer.append(" seconds)\n\n");
return buffer.toString();
}
-
+
/**
* Toggles whether the controls are enabled for input or not.
*
- * @param b Enables the controls if this flag is true, disables them
- * otherwise.
+ * @param b
+ * Enables the controls if this flag is true, disables them otherwise.
*/
@Override
public void setEnabled(boolean b) {
@@ -161,16 +155,15 @@
executionPanel.setEnabled(b);
super.setEnabled(b);
}
-
+
public static void main(String[] args) {
- JDialog dialog = new JDialog((Frame) null, "Travelling Salesman Frame",
- true);
+ JDialog dialog = new JDialog((Frame) null, "Travelling Salesman Frame", true);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
-
+
dialog.getContentPane().add(new TravellingSalesman());
dialog.pack();
dialog.setLocationRelativeTo(null);
-
+
dialog.setVisible(true);
}
}
Modified: lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/TravellingSalesmanStrategy.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/TravellingSalesmanStrategy.java?rev=909871&r1=909870&r2=909871&view=diff
==============================================================================
--- lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/TravellingSalesmanStrategy.java (original)
+++ lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/ga/watchmaker/travellingsalesman/TravellingSalesmanStrategy.java Sat Feb 13 19:07:36 2010
@@ -21,29 +21,27 @@
import java.util.List;
/**
- * Defines methods that must be implemented by classes that provide solutions to
- * the Travelling Salesman problem.
+ * Defines methods that must be implemented by classes that provide solutions to the Travelling Salesman
+ * problem.
*
* <br>
- * The original code is from <b>the Watchmaker project</b>
- * (https://watchmaker.dev.java.net/).
+ * The original code is from <b>the Watchmaker project</b> (https://watchmaker.dev.java.net/).
*/
public interface TravellingSalesmanStrategy {
/**
* @return A description of the strategy.
*/
String getDescription();
-
+
/**
- * Calculates the shortest round trip distance that visits each of the
- * specified cities once and returns to the starting point.
+ * Calculates the shortest round trip distance that visits each of the specified cities once and returns to
+ * the starting point.
*
- * @param cities The destination that must each be visited for the route to be
- * valid.
- * @param progressListener A call-back for keeping track of the route-finding
- * algorithm's progress.
+ * @param cities
+ * The destination that must each be visited for the route to be valid.
+ * @param progressListener
+ * A call-back for keeping track of the route-finding algorithm's progress.
* @return The shortest route found for the given list of destinations.
*/
- List<String> calculateShortestRoute(Collection<String> cities,
- ProgressListener progressListener);
+ List<String> calculateShortestRoute(Collection<String> cities, ProgressListener progressListener);
}
Modified: lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/text/SequenceFilesFromDirectory.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/text/SequenceFilesFromDirectory.java?rev=909871&r1=909870&r2=909871&view=diff
==============================================================================
--- lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/text/SequenceFilesFromDirectory.java (original)
+++ lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/text/SequenceFilesFromDirectory.java Sat Feb 13 19:07:36 2010
@@ -37,28 +37,25 @@
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
-import org.apache.mahout.common.FileLineIterable;
import org.apache.mahout.common.CommandLineUtil;
-import org.slf4j.LoggerFactory;
+import org.apache.mahout.common.FileLineIterable;
import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
- * Converts a directory of text documents into SequenceFiles of Specified
- * chunkSize. This class takes in a parent directory containing sub folders of
- * text documents and recursively reads the files and creates the
- * {@link SequenceFile}s of docid => content. The docid is set as the relative
- * path of the document from the parent directory prepended with a specified
- * prefix. You can also specify the input encoding of the text files. The
- * content of the output SequenceFiles are encoded as UTF-8 text.
+ * Converts a directory of text documents into SequenceFiles of Specified chunkSize. This class takes in a
+ * parent directory containing sub folders of text documents and recursively reads the files and creates the
+ * {@link SequenceFile}s of docid => content. The docid is set as the relative path of the document from the
+ * parent directory prepended with a specified prefix. You can also specify the input encoding of the text
+ * files. The content of the output SequenceFiles are encoded as UTF-8 text.
*
*
*/
public final class SequenceFilesFromDirectory {
-
+
private transient static Logger log = LoggerFactory.getLogger(SequenceFilesFromDirectory.class);
- private static ChunkedWriter createNewChunkedWriter(int chunkSizeInMB,
- String outputDir) throws IOException {
+ private static ChunkedWriter createNewChunkedWriter(int chunkSizeInMB, String outputDir) throws IOException {
return new ChunkedWriter(chunkSizeInMB, outputDir);
}
@@ -91,9 +88,7 @@
this.outputDir = outputDir;
fs = FileSystem.get(conf);
currentChunkID = 0;
- writer =
- new SequenceFile.Writer(fs, conf, getPath(currentChunkID),
- Text.class, Text.class);
+ writer = new SequenceFile.Writer(fs, conf, getPath(currentChunkID), Text.class, Text.class);
}
private Path getPath(int chunkID) {
@@ -103,9 +98,7 @@
public void write(String key, String value) throws IOException {
if (currentChunkSize > maxChunkSizeInBytes) {
writer.close();
- writer =
- new SequenceFile.Writer(fs, conf, getPath(currentChunkID++),
- Text.class, Text.class);
+ writer = new SequenceFile.Writer(fs, conf, getPath(currentChunkID++), Text.class, Text.class);
currentChunkSize = 0;
}
@@ -127,9 +120,7 @@
private final ChunkedWriter writer;
private final Charset charset;
- public PrefixAdditionFilter(String prefix,
- ChunkedWriter writer,
- Charset charset) {
+ public PrefixAdditionFilter(String prefix, ChunkedWriter writer, Charset charset) {
this.prefix = prefix;
this.writer = writer;
this.charset = charset;
@@ -138,17 +129,15 @@
@Override
public boolean accept(File current) {
if (current.isDirectory()) {
- current.listFiles(new PrefixAdditionFilter(prefix
- + File.separator
- + current.getName(), writer, charset));
+ current.listFiles(new PrefixAdditionFilter(prefix + File.separator + current.getName(), writer,
+ charset));
} else {
try {
StringBuilder file = new StringBuilder();
for (String aFit : new FileLineIterable(current, charset, false)) {
file.append(aFit).append('\n');
}
- writer.write(prefix + File.separator + current.getName(), file
- .toString());
+ writer.write(prefix + File.separator + current.getName(), file.toString());
} catch (FileNotFoundException e) {
// Skip file.
@@ -167,47 +156,32 @@
ArgumentBuilder abuilder = new ArgumentBuilder();
GroupBuilder gbuilder = new GroupBuilder();
- Option parentOpt =
- obuilder.withLongName("input").withRequired(true).withArgument(
- abuilder.withName("input").withMinimum(1).withMaximum(1).create())
- .withDescription("The input dir containing the documents")
- .withShortName("i").create();
-
- Option outputDirOpt =
- obuilder.withLongName("output").withRequired(true).withArgument(
- abuilder.withName("output").withMinimum(1).withMaximum(1)
- .create()).withDescription("The output directory")
- .withShortName("o").create();
-
- Option chunkSizeOpt =
- obuilder.withLongName("chunkSize").withArgument(
- abuilder.withName("chunkSize").withMinimum(1).withMaximum(1)
- .create()).withDescription(
- "The chunkSize in MegaBytes. Defaults to 64")
- .withShortName("chunk").create();
-
- Option keyPrefixOpt =
- obuilder.withLongName("keyPrefix").withArgument(
- abuilder.withName("keyPrefix").withMinimum(1).withMaximum(1)
- .create()).withDescription(
- "The prefix to be prepended to the key").withShortName("prefix")
- .create();
-
- Option charsetOpt =
- obuilder.withLongName("charset").withRequired(true)
- .withArgument(
- abuilder.withName("charset").withMinimum(1).withMaximum(1)
- .create()).withDescription(
- "The name of the character encoding of the input files")
- .withShortName("c").create();
-
- Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h").create();
-
- Group group =
- gbuilder.withName("Options").withOption(keyPrefixOpt).withOption(
- chunkSizeOpt).withOption(charsetOpt).withOption(outputDirOpt).withOption(helpOpt)
- .withOption(parentOpt).create();
-
+ Option parentOpt = obuilder.withLongName("input").withRequired(true).withArgument(
+ abuilder.withName("input").withMinimum(1).withMaximum(1).create()).withDescription(
+ "The input dir containing the documents").withShortName("i").create();
+
+ Option outputDirOpt = obuilder.withLongName("output").withRequired(true).withArgument(
+ abuilder.withName("output").withMinimum(1).withMaximum(1).create()).withDescription(
+ "The output directory").withShortName("o").create();
+
+ Option chunkSizeOpt = obuilder.withLongName("chunkSize").withArgument(
+ abuilder.withName("chunkSize").withMinimum(1).withMaximum(1).create()).withDescription(
+ "The chunkSize in MegaBytes. Defaults to 64").withShortName("chunk").create();
+
+ Option keyPrefixOpt = obuilder.withLongName("keyPrefix").withArgument(
+ abuilder.withName("keyPrefix").withMinimum(1).withMaximum(1).create()).withDescription(
+ "The prefix to be prepended to the key").withShortName("prefix").create();
+
+ Option charsetOpt = obuilder.withLongName("charset").withRequired(true).withArgument(
+ abuilder.withName("charset").withMinimum(1).withMaximum(1).create()).withDescription(
+ "The name of the character encoding of the input files").withShortName("c").create();
+
+ Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h")
+ .create();
+
+ Group group = gbuilder.withName("Options").withOption(keyPrefixOpt).withOption(chunkSizeOpt).withOption(
+ charsetOpt).withOption(outputDirOpt).withOption(helpOpt).withOption(parentOpt).create();
+
try {
Parser parser = new Parser();
parser.setGroup(group);
@@ -218,23 +192,23 @@
}
File parentDir = new File((String) cmdLine.getValue(parentOpt));
String outputDir = (String) cmdLine.getValue(outputDirOpt);
-
+
int chunkSize = 64;
if (cmdLine.hasOption(chunkSizeOpt)) {
chunkSize = Integer.parseInt((String) cmdLine.getValue(chunkSizeOpt));
}
-
+
String prefix = "";
if (cmdLine.hasOption(keyPrefixOpt)) {
prefix = (String) cmdLine.getValue(keyPrefixOpt);
}
Charset charset = Charset.forName((String) cmdLine.getValue(charsetOpt));
SequenceFilesFromDirectory dir = new SequenceFilesFromDirectory();
-
+
dir.createSequenceFiles(parentDir, outputDir, prefix, chunkSize, charset);
} catch (OptionException e) {
log.error("Exception", e);
CommandLineUtil.printHelp(group);
- }
+ }
}
}
Modified: lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/text/WikipediaMapper.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/text/WikipediaMapper.java?rev=909871&r1=909870&r2=909871&view=diff
==============================================================================
--- lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/text/WikipediaMapper.java (original)
+++ lucene/mahout/trunk/examples/src/main/java/org/apache/mahout/text/WikipediaMapper.java Sat Feb 13 19:07:36 2010
@@ -37,17 +37,14 @@
import org.slf4j.LoggerFactory;
/**
- * Maps over Wikipedia xml format and output all document having the category
- * listed in the input category file
+ * Maps over Wikipedia xml format and output all document having the category listed in the input category
+ * file
*
*/
-public class WikipediaMapper extends MapReduceBase implements
- Mapper<LongWritable,Text,Text,Text> {
+public class WikipediaMapper extends MapReduceBase implements Mapper<LongWritable,Text,Text,Text> {
- private static final Logger log =
- LoggerFactory.getLogger(WikipediaMapper.class);
- private static final Pattern SPACE_NON_ALPHA_PATTERN =
- Pattern.compile("[\\s]");
+ private static final Logger log = LoggerFactory.getLogger(WikipediaMapper.class);
+ private static final Pattern SPACE_NON_ALPHA_PATTERN = Pattern.compile("[\\s]");
private static final String START_DOC = "<text xml:space=\"preserve\">";
private static final String END_DOC = "</text>";
private static final Pattern TITLE = Pattern.compile("<title>(.*)<\\/title>");
@@ -58,19 +55,17 @@
private boolean all;
@Override
- public void map(LongWritable key,
- Text value,
- OutputCollector<Text,Text> output,
- Reporter reporter) throws IOException {
+ public void map(LongWritable key, Text value, OutputCollector<Text,Text> output, Reporter reporter) throws IOException {
String content = value.toString();
- if (content.contains(REDIRECT))
+ if (content.contains(WikipediaMapper.REDIRECT)) {
return;
+ }
String document;
String title;
try {
- document = getDocument(content);
- title = getTitle(content);
+ document = WikipediaMapper.getDocument(content);
+ title = WikipediaMapper.getTitle(content);
} catch (RuntimeException e) {
reporter.getCounter("Wikipedia", "Parse errors").increment(1);
return;
@@ -78,24 +73,25 @@
if (!all) {
String catMatch = findMatchingCategory(document);
- if (catMatch.equals("Unknown"))
+ if (catMatch.equals("Unknown")) {
return;
+ }
}
document = StringEscapeUtils.unescapeHtml(document);
- output.collect(new Text(SPACE_NON_ALPHA_PATTERN.matcher(title).replaceAll(
- "_")), new Text(document));
+ output.collect(new Text(WikipediaMapper.SPACE_NON_ALPHA_PATTERN.matcher(title).replaceAll("_")),
+ new Text(document));
}
private static String getDocument(String xml) {
- int start = xml.indexOf(START_DOC) + START_DOC.length();
- int end = xml.indexOf(END_DOC, start);
+ int start = xml.indexOf(WikipediaMapper.START_DOC) + WikipediaMapper.START_DOC.length();
+ int end = xml.indexOf(WikipediaMapper.END_DOC, start);
return xml.substring(start, end);
}
private static String getTitle(String xml) {
- Matcher m = TITLE.matcher(xml);
+ Matcher m = WikipediaMapper.TITLE.matcher(xml);
String ret = "";
if (m.find()) {
ret = m.group(1);
@@ -112,8 +108,7 @@
if (endIndex >= document.length() || endIndex < 0) {
break;
}
- String category =
- document.substring(categoryIndex, endIndex).toLowerCase().trim();
+ String category = document.substring(categoryIndex, endIndex).toLowerCase().trim();
// categories.add(category.toLowerCase());
if (exactMatchOnly && inputCategories.contains(category)) {
return category;
@@ -135,9 +130,8 @@
if (inputCategories == null) {
Set<String> newCategories = new HashSet<String>();
- DefaultStringifier<Set<String>> setStringifier =
- new DefaultStringifier<Set<String>>(job, GenericsUtil
- .getClass(newCategories));
+ DefaultStringifier<Set<String>> setStringifier = new DefaultStringifier<Set<String>>(job,
+ GenericsUtil.getClass(newCategories));
String categoriesStr = setStringifier.toString(newCategories);
categoriesStr = job.get("wikipedia.categories", categoriesStr);
@@ -149,11 +143,7 @@
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
- log.info("Configure: Input Categories size: "
- + inputCategories.size()
- + " All: "
- + all
- + " Exact Match: "
- + exactMatchOnly);
+ WikipediaMapper.log.info("Configure: Input Categories size: " + inputCategories.size() + " All: " + all
+ + " Exact Match: " + exactMatchOnly);
}
}