public static void main(String[] args) { String sampleFile = args[0]; String solutionFile = args[1]; // Parse the first argument as the city input file and the second as the // tour solution file if (args.length != 2) { usage(); System.exit(-1); } CitySet cities = CitySet.LoadFromUrl(new File(sampleFile).toURI().toString()); try { Tour t = Tour.parseTour(new FileInputStream(new File(solutionFile)), cities); // Print sentinel value if this is not a valid permutation if (!t.isValidPermutation()) { System.err.println("Not a valid permutation of cities"); System.out.println(-1); return; } // In the error-free case, only print the value we care about System.out.println(t.evaluate()); } catch (Exception ex) { System.err.println("Cannot evaluate solution: " + ex.getMessage()); System.out.println(-1); } }
/** @param args */ public static void main(String[] args) throws IOException { // Parse the first argument as the input file and the second as the output file if (args.length != 2) { usage(); System.exit(1); } CitySet cities = CitySet.LoadFromUrl(new File(args[0]).toURI().toString()); // Take the first city // Find the closest city, add it, then iterate Set<Integer> usedCities = new HashSet<Integer>(); Tour currentTour = new Tour(cities); List<City> cityList = new ArrayList<City>(); for (City c : cities) { cityList.add(c); } double[][] distances = calculateAllDistances(cityList); int currentIndex = 0; usedCities.add(currentIndex); while (usedCities.size() < cities.size()) { currentTour.addCity(cityList.get(currentIndex).ID); int nextCity = findClosestCity(currentIndex, distances, usedCities); currentIndex = nextCity; usedCities.add(currentIndex); } currentTour.addCity(cityList.get(currentIndex).ID); currentTour.saveTour(new FileOutputStream(new File(args[1]))); }
public void initializeForJtfRestart() { jtfModelPattern = null; jtfRandomCount = 0; jtlRandomCount = 0; jtodRandomCount = 0; inmtfRandomCount = 0; inmtlRandomCount = 0; inmtodRandomCount = 0; awfRandomCount = 0; awlRandomCount = 0; awtodRandomCount = 0; stfRandomCount = 0; stlRandomCount = 0; initializeWindows(); if (jointTours != null) { for (Tour t : jointTours) { t.clearStopModelResults(); } } for (int i = 1; i < persons.length; i++) persons[i].initializeForJtfRestart(); jointTours = null; }
public Tour createRandomTour() { Tour tour = new Tour(); List<City> newPath = new ArrayList<>(); int tourSize = allCities.size(); int index; Set<Integer> seen = new HashSet<>(); City city; newPath.add(allCities.get(0)); // System.out.println("** " + allCities.get(0).getName()); for (int i = 1; i < tourSize; i++) { index = (int) (Math.random() * tourSize); while (index == 0 || seen.contains(index)) { // System.out.println("in " + index); index = (int) (Math.random() * tourSize); } seen.add(index); city = allCities.get(index); // System.out.println("** " + index + " " + allCities.get(index).getName()); newPath.add(city); } // System.out.println(""); if (allCities.size() > 1) { // System.out.println("** last :" + allCities.get(0).getName()); newPath.add(allCities.get(0)); } tour.setPath(newPath); return tour; }
/** * Met à jour le joueur courant et le retourne * * @return joueur suivant */ public Joueur joueurSuivant() { Joueur j = this.getJoueurCourant(); if (j == joueur1) { tour.setJoueurCourant(joueur2); return joueur2; } else { tour.setJoueurCourant(joueur1); return joueur1; } }
// Gets the best tour in the population public Tour getFittest() { Tour fittest = tours[0]; // Loop through individuals to find fittest for (int i = 1; i < populationSize(); i++) { if (fittest.getFitness() <= getTour(i).getFitness()) { fittest = getTour(i); } } return fittest; }
/** Routine graphique de la fin d'une Action */ public void IhmFinAction() { ihmjeu.getCommande3().setVisible(false); ihmjeu.remove(ihmjeu.getCommande3()); ihmjeu.getCommande2().setVisible(true); ihmjeu.getContentPane().add(ihmjeu.getCommande2(), BorderLayout.SOUTH); if (tour.isMultipleAction() && !tour.finMultipleAction()) ihmjeu.getCommande2().actionMultiple(); ihmjeu.afficherTerminal("Selectionner une Commande"); this.setPhase(Phase.NORMAL); }
@Override public void evaluate(Solution solution) { Tour tour = toTour(solution); // apply the heuristic and save the modified tour heuristic.apply(tour); fromTour(solution, tour); solution.setObjective(0, tour.distance(instance)); }
// Construct a population public Population(int populationSize, boolean initialise) { tours = new Tour[populationSize]; // If we need to initialise a population of tours do so if (initialise) { // Loop and create individuals for (int i = 0; i < populationSize(); i++) { Tour newTour = new Tour(); newTour.generateIndividual(); saveTour(i, newTour); } } }
public void scheduleJointTourTimeWindows(Tour t, int start, int end) { int[] participatingPersonIndices = t.getPersonNumArray(); for (int i : participatingPersonIndices) { Person person = persons[i]; person.scheduleWindow(start, end); } }
public boolean[] getAvailableJointTourTimeWindows(Tour t, int[] altStarts, int[] altEnds) { int[] participatingPersonIndices = t.getPersonNumArray(); // availability array for each person boolean[][] availability = new boolean[participatingPersonIndices.length][]; for (int i = 0; i < participatingPersonIndices.length; i++) { int personNum = participatingPersonIndices[i]; Person person = persons[personNum]; // availability array is 1-based indexing availability[i] = new boolean[altStarts.length + 1]; for (int k = 1; k <= altStarts.length; k++) { int start = altStarts[k - 1]; int end = altEnds[k - 1]; availability[i][k] = person.isWindowAvailable(start, end); } } boolean[] jointAvailability = new boolean[availability[0].length]; for (int k = 0; k < jointAvailability.length; k++) { jointAvailability[k] = true; for (int i = 0; i < participatingPersonIndices.length; i++) { if (!availability[i][k]) { jointAvailability[k] = false; break; } } } return jointAvailability; }
public List<Tourentag> selectTourentag(Tour tour) throws SQLException, ClassNotFoundException { List<Tourentag> list = new ArrayList<Tourentag>(); Connection c = PostgreSQL_DAOFactory.getConnection(); Statement s = c.createStatement(); if (tour == null || tour.getId() <= 0) { return list; } StringBuffer sb = new StringBuffer("select * from " + TABLE_NAME); sb.append(" where "); sb.append(COLUMN_ID_TOUR); sb.append(" = "); sb.append(tour.getId()); ResultSet rs = s.executeQuery(sb.toString()); while (rs.next()) { Tourentag tt = new Tourentag(tour); tt.setTag(rs.getInt(COLUMN_TAG)); tt.setBeschreibung(rs.getString(COLUMN_BESCHREIBUNG)); tt.setDate(rs.getDate(COLUMN_DATUM)); tt.setHmAufstieg(rs.getInt(COLUMN_HMAUFSTIEG)); tt.setHmAbstieg(rs.getInt(COLUMN_HMABSTIEG)); tt.setGehzeit(rs.getDouble(COLUMN_GEHZEIT)); tt.setSchwierigkeiten(rs.getString(COLUMN_SCHWIERIGKT)); tt.setBilddatei(rs.getString(COLUMN_BILDDATEI)); tt.setBildttitel(rs.getString(COLUMN_BILTITEL)); int region = rs.getInt(COLUMN_REGION); DAOFactory daof = DAOFactory.getDAOFactory(DAOFactory.POSTGRESQL); PostgreSQL_RegionDAO regionDao = (PostgreSQL_RegionDAO) daof.getRegionDAO(); Region r = (Region) (regionDao.selectRegion(region)).get(0); tt.setRegion(r); list.add(tt); } rs.close(); return list; }
/** * Converts a MOEA Framework solution to a {@link Tour}. * * @param solution the MOEA Framework solution * @return the tour defined by the solution */ public static Tour toTour(Solution solution) { int[] permutation = EncodingUtils.getPermutation(solution.getVariable(0)); // increment values since TSP nodes start at 1 for (int i = 0; i < permutation.length; i++) { permutation[i]++; } return Tour.createTour(permutation); }
/** * Saves a {@link Tour} into a MOEA Framework solution. * * @param solution the MOEA Framework solution * @param tour the tour */ public static void fromTour(Solution solution, Tour tour) { int[] permutation = tour.toArray(); // decrement values to get permutation for (int i = 0; i < permutation.length; i++) { permutation[i]--; } EncodingUtils.setPermutation(solution.getVariable(0), permutation); }
public void initializeForAwfRestart() { awfRandomCount = 0; awlRandomCount = 0; awtodRandomCount = 0; stfRandomCount = 0; stlRandomCount = 0; initializeWindows(); if (jointTours != null) { for (Tour t : jointTours) { for (int i : t.getPersonNumArray()) persons[i].scheduleWindow(t.getTourDepartPeriod(), t.getTourArrivePeriod()); t.clearStopModelResults(); } } for (int i = 1; i < persons.length; i++) persons[i].initializeForAwfRestart(); }
// returns a tour containing the shortest path TwoOpt finds public Tour findShortestPath(Graph g) { numVertices = g.numVertices(); Tour start = g.getRandomTour(); Tour comparison; int c = 1; while (c > 0) { c = 0; for (int i = 0; i < numVertices; i++) { for (int j = 0; j < i; j++) { comparison = new Tour(neighborVertexSet(start.verticesSoFar(), j, i), g); // System.out.printf("%s", comparison.toString()); if (comparison.getLength() < start.getLength()) { start = comparison; c++; } } } } return start; }
public void createJointTourArray(Tour tour1, Tour tour2) { jointTours = new Tour[2]; tour1.setTourOrigMgra(homeMgra); tour1.setTourDestMgra(0); tour1.setTourId(0); tour2.setTourOrigMgra(homeMgra); tour2.setTourDestMgra(0); tour2.setTourId(1); jointTours[0] = tour1; jointTours[1] = tour2; }
public static void main(String[] args) throws IOException { TSPInstance problem = new TSPInstance(new File("./data/tsp/gr120.tsp")); problem.addTour(new File("./data/tsp/gr120.opt.tour")); TSPPanel panel = new TSPPanel(problem); for (int i = 0; i < 20; i++) { panel.displayTour( Tour.createRandomTour(problem.getDimension()), new Color(128, 128, 128, 64)); } panel.displayTour(problem.getTours().get(0), Color.RED, new BasicStroke(2.0f)); JFrame frame = new JFrame(problem.getName()); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(panel, BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setSize(500, 400); frame.setLocationRelativeTo(null); frame.setVisible(true); }
public int getMaxJointTimeWindow(Tour t) { // get array of person array indices participating in joint tour int[] participatingPersonIndices = t.getPersonNumArray(); // create an array to hold time window arrays for each participant int[][] personWindows = new int[participatingPersonIndices.length][]; // get time window arrays for each participant int k = 0; for (int i : participatingPersonIndices) personWindows[k++] = persons[i].getTimeWindows(); int count = 0; ; int maxCount = 0; // loop over time window intervals for (int w = 1; w < personWindows[0].length; w++) { // loop over party; determine if interval is available for everyone in party; boolean available = true; for (k = 0; k < personWindows.length; k++) { if (personWindows[k][w] > 0) { available = false; break; } } // if available for whole party, increment count; determine maximum continous time window // available to whole party. if (available) { count++; if (count > maxCount) maxCount = count; } else { count = 0; } } return maxCount; }
public static void main(String[] args) { // check for optional command-line argument that turns on animation int delay = -1; if (args.length > 0) delay = Integer.parseInt(args[0]); // get dimensions int w = StdIn.readInt(); int h = StdIn.readInt(); StdDraw.setCanvasSize(w, h); StdDraw.setXscale(0, w); StdDraw.setYscale(0, h); // turn on animation mode StdDraw.show(0); // run smallest insertion heuristic Tour tour = new Tour(); while (!StdIn.isEmpty()) { double x = StdIn.readDouble(); double y = StdIn.readDouble(); Point p = new Point(x, y); tour.insertSmallest(p); if (delay > -1) { StdDraw.clear(); tour.draw(); StdDraw.text(100, 0, "" + tour.distance()); StdDraw.show(delay); } } // draw to standard draw tour.draw(); StdDraw.show(0); // print tour to standard output System.out.println("Tour distance = " + tour.distance()); tour.show(); }
@Override public void buildTrans() { tour.setTrans(new LocalTransport("LIMO", 200.00)); }
/** * Solves this TSPLIB instance while displaying a GUI showing the optimization progress. * * @param instance the TSPLIB instance to solve */ public static void solve(TSPInstance instance) { TSPPanel panel = new TSPPanel(instance); panel.setAutoRepaint(false); // create other components on the display StringBuilder progress = new StringBuilder(); JTextArea progressText = new JTextArea(); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); splitPane.setTopComponent(panel); splitPane.setBottomComponent(new JScrollPane(progressText)); splitPane.setDividerLocation(300); splitPane.setResizeWeight(1.0); // display the panel on a window JFrame frame = new JFrame(instance.getName()); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(splitPane, BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setSize(500, 400); frame.setLocationRelativeTo(null); frame.setIconImages(Settings.getIconImages()); frame.setVisible(true); // create the optimization problem and evolutionary algorithm Problem problem = new TSPProblem(instance); Properties properties = new Properties(); properties.setProperty("swap.rate", "0.7"); properties.setProperty("insertion.rate", "0.9"); properties.setProperty("pmx.rate", "0.4"); Algorithm algorithm = AlgorithmFactory.getInstance().getAlgorithm("NSGAII", properties, problem); int iteration = 0; // now run the evolutionary algorithm while (frame.isVisible()) { algorithm.step(); iteration++; // clear existing tours in display panel.clearTours(); // display population with light gray lines if (algorithm instanceof EvolutionaryAlgorithm) { EvolutionaryAlgorithm ea = (EvolutionaryAlgorithm) algorithm; for (Solution solution : ea.getPopulation()) { panel.displayTour(toTour(solution), lightGray); } } // display current optimal solutions with red line Tour best = toTour(algorithm.getResult().get(0)); panel.displayTour(best, Color.RED, new BasicStroke(2.0f)); progress.insert(0, "Iteration " + iteration + ": " + best.distance(instance) + "\n"); progressText.setText(progress.toString()); // repaint the TSP display panel.repaint(); } }
@Override protected synchronized void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // get the display data NodeCoordinates displayData = null; if (DisplayDataType.COORD_DISPLAY.equals(problem.getDisplayDataType())) { displayData = (NodeCoordinates) problem.getDistanceTable(); } else { displayData = problem.getDisplayData(); } // first determine bounds of the data boolean isGeographical = EdgeWeightType.GEO.equals(problem.getEdgeWeightType()); double left = Double.POSITIVE_INFINITY; double right = Double.NEGATIVE_INFINITY; double bottom = Double.POSITIVE_INFINITY; double top = Double.NEGATIVE_INFINITY; for (int i = 1; i <= displayData.size(); i++) { Node node = displayData.get(i); double[] position = toDisplayCoordinates(node, isGeographical); left = Math.min(left, position[0]); right = Math.max(right, position[0]); bottom = Math.min(bottom, position[1]); top = Math.max(top, position[1]); } // calculate the bounds of the drawing int displayWidth = getWidth(); int displayHeight = getHeight(); double scaleX = (displayWidth - insets.right - insets.left) / (right - left); double scaleY = (displayHeight - insets.top - insets.bottom) / (top - bottom); double scale = Math.min(scaleX, scaleY); double offsetX = (displayWidth - insets.right - insets.left - scale * (right - left)) / 2.0; double offsetY = (displayHeight - insets.top - insets.bottom - scale * (top - bottom)) / 2.0; // draw the tours for (Entry<Tour, TourDisplaySetting> entry : tours.entrySet()) { Tour tour = entry.getKey(); TourDisplaySetting displaySettings = entry.getValue(); g2.setPaint(displaySettings.getPaint()); g2.setStroke(displaySettings.getStroke()); for (int i = 0; i < tour.size(); i++) { Node node1 = displayData.get(tour.get(i)); Node node2 = displayData.get(tour.get(i + 1)); double[] position1 = toDisplayCoordinates(node1, isGeographical); double[] position2 = toDisplayCoordinates(node2, isGeographical); Line2D line = new Line2D.Double( displayWidth - (offsetX + scale * (position1[0] - left) + insets.left), displayHeight - (offsetY + scale * (position1[1] - bottom) + insets.bottom), displayWidth - (offsetX + scale * (position2[0] - left) + insets.left), displayHeight - (offsetY + scale * (position2[1] - bottom) + insets.bottom)); g2.draw(line); } } // draw the nodes g2.setColor(getForeground()); for (int i = 1; i <= displayData.size(); i++) { Node node = displayData.get(i); double[] position = toDisplayCoordinates(node, isGeographical); Ellipse2D point = new Ellipse2D.Double( displayWidth - (offsetX + scale * (position[0] - left) + insets.left) - (nodeWidth / 2.0), displayHeight - (offsetY + scale * (position[1] - bottom) + insets.bottom) - (nodeWidth / 2.0), nodeWidth, nodeWidth); g2.fill(point); g2.draw(point); } }
/** * Retourne un booléen si l'action est finie * * @return <code>true</code> si l'action est finie; <code>false</code> sinon */ public boolean isAction() { return tour.isAction(); }
/** * Retourne un booléen si l'action est multiple * * @return <code>true</code> si l'action est multiple; <code>false</code> sinon */ public boolean isMultipleAction() { return tour.isMultipleAction(); }
/** * Retourne un booléen si le placement est finie * * @return <code>true</code> si le placement est finie; <code>false</code> sinon */ public boolean isPlacé() { return tour.isPlacé(); }
@Override public void buildHotel() { tour.setHotel(new Hotel("Strosphere", 400.00)); }
private void showMap() { Tour tour = TourModel.getTour(); TourMapActivity.launch(this, tour.getDefaultTourMapItems(), tour.getPathGeoPoints(), false); }
public void buildAirline() { tour.setAirline(new Airline("UA777", 200.00)); }
@Override public void buildANewTour() { tour = new Tour("Las Vegas - 1/8~14/8"); tour.setCap(10); tour.setTemp(100); }