File: TOUR.R

package info (click to toggle)
r-cran-tsp 1.1-6-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,128 kB
  • sloc: ansic: 277; sh: 13; makefile: 2
file content (67 lines) | stat: -rw-r--r-- 1,972 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#######################################################################
# TSP - Traveling Salesperson Problem 
# Copyrigth (C) 2011 Michael Hahsler and Kurt Hornik
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.



TOUR <- function(x, method=NA, tsp=NULL){
  if(inherits(x, "TOUR")) return(x)
  
  x <- as.TOUR(x)
  attr(x, "method") <- as.character(method)
  if(!is.null(tsp)){
    attr(x, "tour_length") <- tour_length(x, tsp)
    names(x) <- labels(tsp)[x]
  }
  
  x
}

## coercion
as.TOUR <- function(object) UseMethod("as.TOUR")
as.TOUR.numeric <-  function(object){
  l <- labels(object)	    ### preserve lables
  object <- as.integer(object)
  names(object) <- l
  as.TOUR(object)
}
as.TOUR.integer <- function(object){
  
  ## check tour
  if(any(object < 1) || any(object > length(object)) || any(is.na(object))) 
    stop("tour contains illegal elements.")
  
  if(any(duplicated(object))) stop("tour indices are not unique.")
  
  class(object) <- c("TOUR", class(object))
  object
}



## helper for tour

print.TOUR <- function(x, ...){
  
  cat("object of class", sQuote(class(x)[1]), "\n")
  cat("result of method", sQuote(attr(x, "method")), "for", 
    length(x), "cities\n")
  if(!is.null(attr(x, "tour_length")))
    cat("tour length:", attr(x, "tour_length"), "\n")
  else 
    cat("tour length: unknown\n")
}