#!/usr/bin/env Rscript

# Clear out the entire workspace.
rm(list = ls())

# Load the package.
install.packages(devtools)
devtools::install_github("mckaylab/TSPmap")
library(TSPmap)

# Directory of LKH and Concorde executables.
# You must install these
# LKH... http://www.akira.ruc.dk/~keld/research/LKH/
# Concorde... http://www.math.uwaterloo.ca/tsp/concorde.html
# Relpace the strings below with the path to the executable files for these programs after you download/install them
LKHexePath = "/path/to/LKH_executable"
Concordepath = "/path/to/concorde_executable"

strainName = "simdata"

# change the path below to the simulated data file that you want to make a linkage map of
rawdata = readFile("/path/to/simulated_data_file.tsv", classificationFlag = FALSE, transpose = FALSE)

# set the number of expected chromosomes for the organism (here we it is 5)
numChromosomes = 5

# remove duplicate markers (100% identical between lines)
# This is optional, and was not done wtih the simulated datasets in order to make even comparisions between methods
# Unhash the 2 lines below to remove duplicates
# duplicates = finddups(rawdata, threshold = 100)
# rawdata = removedups(rawdata, duplicates)

# calculate recombination frequency between markers
rfmat = computeRFmat(rawdata, TRUE)

# Determine the rf inflation cutoff by choosing the value in each row that 85% of the rf values are below.
# This value is used to cap the rf matrix.
defaultpsum = 0.40    # Default value.
percentilesum = defaultpsum

percentilesum = 0
percentilecutoff = 0.15
for(i in 1:length(rfmat[,1]))
{
  percentilesum = percentilesum + quantile(rfmat[i,], percentilecutoff)
}
percentilesum = percentilesum/length(rfmat[,1])

# Set max allowable value of percentilesum.
if(percentilesum > defaultpsum)
{
  percentilesum = defaultpsum
}

rfmat = capRFmat(rfmat, percentilesum, capval = 0.5)

# create raw clusters of markers based om recombination frequency (warning message is OK)
rawclusters = autoClusterMST(rawdata, rfmat, numChromosomes, LKHexePath, internalRfThreshold = 0.4)

# merge raw clusters of markers (warning message is OK)
mergedclusters = autoMergeClusters(rawclusters, rfmat, LKHexePath, numChromosomes, rfCap = percentilesum, rawdata=rawdata)

# Create final order of markers in each cluster using Concorde.
# this loop also saves each linkage group [i] to a file "TSPmap_chromosome_[i].tsv in your current working directory.
finalMap = list()
for(i in 1:length(mergedclusters))
{
  temp = createMap(rawdata, rfmat, mergedclusters[i], Concordepath)
  finalMap = c(finalMap,list(temp))
  write.table(temp, file=paste0("TSPmap_chromosome", i, ".tsv"), sep="\t", row.names=F, na="-")
}



