---
title: "Outcrossing Populations"
author: "[Statistical Genetics Lab](http://statgen.esalq.usp.br) <br/> Department of Genetics <br/> Luiz de Queiroz College of Agriculture <br/> University of São Paulo"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Outcrossing Populations}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r knitr_init, echo=FALSE, cache=FALSE}
library(knitr)
library(rmarkdown)

knitr::opts_chunk$set(collapse = TRUE,
                      comment = "#>",
                      fig.width = 6,
                      fig.height = 6,
                      fig.align = "center",
                      dev = "png",
                      dpi = 36,
                      cache = TRUE)

```

```{r, echo=FALSE, results='hide', message=FALSE}
library(onemap)
```

The following example is intended to show the usage of `OneMap`
functions for linkage mapping in outcrossing (non-inbred) populations.
With basic knowledge of R syntax, one should have no problems using
it. If you are not familiar with R, we recommend reading the vignette
[Introduction to R](https://htmlpreview.github.io/?https://github.com/augusto-garcia/onemap/blob/master/inst/doc/Introduction_R.html).

Hopefully these examples will be clear enough to help any user to
understand its functionality and start using it. You do not need to be
an expert in R to build your linkage map, but some concepts are
necessary and will help you through the process.

There is a github `OneMap` version which is constantly improved, we strong
recommend all users to try [this version](https://github.com/augusto-garcia/onemap). 
In `augusto-garcia/onemap` github page you can find instructions to install the package 
from github and also more fancy tutorials.

# Creating the data file

This step may be quite difficult, because the data file is not very
simple and some errors can occur while reading it. The input file
format is similar to that used by MAPMAKER/EXP (Lander et al., 1987),
so experienced users of genetic analysis software should be already
familiar with this scenario.

Basically, the input file is a text file, where the first line indicates the cross type and the second line provides information about the number of individuals, the number of markers, the presence of physical marker locations and the presence of phenotypic data. The third line contains sample IDs. Then, the genotype information is included separately for each marker. The
character `*` indicates the beginning of information input for a new
marker, followed by the marker name. Next, there is a code indicating the marker type, according to Wu's et al. (2002a)
notation. Actually, it is recommended to check Wu's et al. (2002a)
paper before using `OneMap`.

Marker types must be one of the following: `A.1`, `A.2`, `A.3`, `A.4`,
`B1.5`, `B2.6`, `B3.7`, `C.8`, `D1.9`, `D1.10`, `D1.11`, `D1.12`,
`D1.13`, `D2.14`, `D2.15`, `D2.16`, `D2.17` or `D2.18`, each one
corresponding to a row of the following table:

|     |       |           | Parent         |                |    Offspring   |             |
|-----|-------|:---------:|:--------------:|:--------------:|:--------------:|:-----------:|
|     |       | Crosstype | Cross          | Observed bands | Observed bands | Segregation |
| $A$ |       |         1 | $ab \times cd$ | $ab \times cd$ | $ac, ad, bc, bd$ | $1:1:1:1$ |
|     |       |         2 | $ab \times ac$ | $ab \times ac$ | $a, ac, ba, bc$ | $1:1:1:1$|
|     |       |         3 | $ab \times co$ | $ab \times c$  | $ac, a, bc,b$  | $1:1:1:1$ |
|     |       |         4 | $ao \times bo$ | $a  \times  b$ | $ab, a, b, o$  | $1:1:1:1$ |
|     |       |           |                |                |       |  |
| $B$ | $B_1$ |         5 | $ab \times ao$ | $ab \times a$  | $ab, 2a,b$ | $1:2:1$ |
|     | $B_2$ |         6 | $ao \times ab$ | $a \times ab$  | $ab,2a,b$  | $1:2:1$ |
|     | $B_3$ |         7 | $ab \times ab$ | $ab \times ab$ | $a, 2ab,b$ | $1:2:1$ |
|     |       |           |                |                |       |  |
| $C$ |       |         8 | $ao \times ao$ | $a \times a$   | $3a, o$        |  $3:1$      |
|     |       |           |                |                |       |  |
| $D$ | $D_1$ |         9 | $ab \times cc$ | $ab \times c$  | $ac, bc$       |  $1:1$      |
|     |       |        10 | $ab \times aa$ | $ab \times a$  | $a, ab$        |  $1:1$      |
|     |       |        11 | $ab \times oo$ | $ab \times o$  | $a, b$         |  $1:1$      |
|     |       |        12 | $bo \times aa$ | $b \times a$   | $ab, a$        |  $1:1$      |
|     |       |        13 | $ao \times oo$ | $a \times o$   | $a, o$         |  $1:1$      |
|     | $D_2$ |        14 | $cc \times ab$ | $c \times ab$  | $ac, bc$       |  $1:1$      |
|     |       |        15 | $aa \times ab$ | $a \times ab$  | $a, ab$        |  $1:1$      |
|     |       |        16 | $oo \times ab$ | $o \times ab$  | $a, b$         |  $1:1$      |
|     |       |        17 | $aa \times bo$ | $a \times b$   | $ab, a$        |  $1:1$      |
|     |       |        18 | $oo \times ao$ | $o \times a$   | $a, o$         |  $1:1$      |

Letters `A`, `B`, `C` and `D` indicate the segregation type (_i.e._,
`1:1:1:1`, `1:2:1`, `3:1` or `1:1`, respectively), while the number
after the dot (_e.g._, `A.1`) indicates the observed bands in the
offspring. The paper cited above gives details with respect to marker
types; we will not discuss them here, but it is easy to see that each
marker is classified based on the band patterns of parents and
progeny.

Finally, after each marker name, comes the genotype data for the
segregating population. The coding for marker genotypes used by
`OneMap` is also the same one proposed by Wu et al. (2002a) and the
possible values vary according to the specific marker type. Missing
data are indicated with the character `-` (minus sign) and an empty space separates the information for each individual. Phenotype information, if present, follows genotypic data with a similar structure. Details are found in the help of function `read_onemap`.

Here is an example of such file for 10 individuals and 5 markers (the three zeros in the second line indicate that there is no chromosome information, physical position information or phenotypic data, respectively). It
is very similar to a MAPMAKER/EXP file, but has additional information
about the crosstype.

```
data type outcross
10 5 0 0 0
I1 I2 I3 I4 I5 I6 I7 I8 I9 I10
*M1 B3.7 ab ab - ab b ab ab - ab b
*M2 D2.18 o - a a - o a - o o
*M3 D1.13 o a a o o - a o a o
*M4 A.4 ab b - ab a b ab b - a
*M5 D2.18 a a o - o o a o o o
```

Notice that once the marker type is identified, no variations of
symbols presented on the table for the **observed bands** is allowed.
For example, for `A.1`, only `ac`, `ad`, `bc` and `bd` genotypes are
expected (plus missing values). **We notice in FAQs that this is a
common mistake made by users, so please be careful**.

The input file must be saved in text format, with extensions like
`.raw`. It is a good idea to open the text file called
`onemap_example_out.raw` (available with `OneMap` and saved in the directory
you installed it) to see how this file should be. You can see where
`OneMap` is installed using the command

```{r, eval=FALSE}
system.file(package = "onemap")
``` 


# Importing data

Once the input file is created, the data can be loaded and saved into an R
`onemap` object. The function used to import data is named `read_onemap`. Its usage is quite simple:
 
```{r, eval=FALSE}
onemap_example_out <- read_onemap(dir = "C:/workingdirectory", inputfile = "onemap_example_out.raw")
```

The first argument is the directory where the input file is located,
so modify it accordingly. The second one is the data file name. In
this example, an object named `onemap_example_out` was created. If you leave
the argument `dir` blank, the file will be loaded from your `working
directory`.

You can change the working directory in R using function `setwd()` or
in the toolbar clicking `File -> Change dir`. If you set your working
directory to the one containing the input file, you can just type:


```{r, eval=FALSE}
onemap_example_out <- read_onemap(inputfile = "onemap_example_out.raw")
``` 

If no error has occurred, a message will display some basic
information about the data, such as number of individuals and number
of markers:

```{r, eval=FALSE, echo=FALSE}
onemap_example_out <- read_onemap(inputfile = system.file("extdata/onemap_example_out.raw", package = "onemap"))
``` 

Because this particular data set is distributed along with the
package, as an alternative you can load it typing

```{r}
data("onemap_example_out")
``` 

Loading the data creates an object of class `onemap`, which will
further be used in the analysis. R command `print` recognizes
objects of this class. Thus, if you type:

```{r, eval=FALSE}
onemap_example_out
```

you will see some information about the object:

```{r, echo=FALSE}
onemap_example_out
```

Also, you can use the `plot.onemap` function to see graphically markers genotypes:

```{r}
plot(onemap_example_out)
```

Changing the argument `all` to `FALSE`, the markers will be separed by their type. In this case, you can note that the graphic cells size will adapt to the number of markers of the same type. In other words, the greater is the number of markers with the same type, smaller are the cells for this type.

```{r}
plot(onemap_example_out, all = FALSE)
```

This function can take quite some time, depending on the
number of markers involved. More informations about this plot function can be found using `?plot.onemap`.

Also, you can see graphically the number of markers by segregattion pattern with the `plot_by_segreg_type` function:

```{r}
plot_by_segreg_type(onemap_example_out)
```


## Importing data from `VCF` file

If you are working with biallelic markers, as SNPs and indels (marker types B3.7, D1.10 or D2.15), in VCF (Variant Call Format) files, you can import information from `VCF` to `OneMap` using `onemap_read_vcfR` function.

With the `onemap_read_vcfR` you can convert the object from `vcfR` package directly to `onemap`. The `onemap_read_vcfR` function keeps chromosome and position information for each marker at the end of raw file.

We will use the same example file `vcf_example_out.vcf` to show how it works.

First, we convert the `VCF` file to `vcfR` object:

```{r, eval=FALSE}
library(vcfR)
vcfR.object <- read.vcfR(system.file("extdata/vcf_example_out.vcf", package = "onemap"))
```

As described in the `vcfR` package vignette, memory use is a important consideration when using `vcfR`. Depending of your dataset, the object created can be very large and occupy a lot of memory.

After, you can use `onemap_read_vcfR` function to convert this object to `onemap` object. The parameters used is the `vcfR.object` we just created, the identification of each parent (here you must define only one sample for each parent) and the cross type.

```{r, eval=FALSE}
vcf_example_out <- onemap_read_vcfR(vcfR.object = vcfR.object,
                                   parent1 = "P1", 
                                   parent2 = "P2", 
                                   cross = "outcross")
```

```{r, echo=FALSE}
data(vcf_example_out)
```

Depending of your dataset, this function can take some time to run.

After the convertion, we can save the `vcfR.object` as a `.RData` and to remove it from the workspace, once it can occupy a lot of memory and turn the other process too slow. 

```{r, eval=FALSE}
save(vcfR.object, file = "vcfR.object.RData") 
rm(vcfR.object)
```

From version 2.0.6 to 2.1.1005, OneMap had the `vcf2raw` function to convert `vcf` to `.raw`. Now, this function is defunct, but it can be replaced by a combination of `onemap_read_vcfR` and `write_onemap_raw` functions.

# Combining `OneMap` datasets

If you have more than one dataset of markers, all from the same cross type, you can use the function `combine_onemap` to merge them into only one `onemap` object.

In our example, we have two datasets: 

* first: `onemap_example_out` with 30 markers and 100 individuals
* second: `vcf_example_out` with 24 biallelic markers and 92 individuals.

The `combine_function` recognizes the correspondent individuals by the ID, thus, it is important define exactly same IDs to respective individuals in both `raw` files. Compared with the first file, the second file do not have markers informations for 8 individuals. The `combine_onemap` will complete those informations with NA.

In our examples, we have only genotypic information, but the function can also merge the phenotipic information if it exists.

```{r}
comb_example <- combine_onemap(onemap_example_out, vcf_example_out)
comb_example
```

The function arguments are the names of the `onemap` objects you want to combine.

Plotting markers genotypes from the outputted `onemap` object, we can see that there are more missing data `-` (black vertical lines) for some individuals, because they were missing in the second file.

```{r}
plot(comb_example)
```

# Find redundant markers

It is possible that there are redundant markers in your dataset, specially when dealing with too many markers. Redundant markers have the same genotypic informations that others markers, usually because didn't happen recombination events between each other. They will not increase informations to the map, but will increase computational effort during the map building. Therefore, it is a good pratice to remove them to build the map and, once the map is already builded, they can be added again.

First, we use the function `find_bins` to group the markers into bins according with their genotypic informations. In other words, markers with the same genotypic informations will be at the same bin.

```{r}
bins <- find_bins(comb_example, exact = FALSE)
bins
```

The first argument is the `onemap` object and the `exact` argument specify if only markers with exact same informations will be at the same bin. Using `FALSE` at this second argument, missing data will not be considered and the marker with the lowest amount of missing data will be the representative marker on the bin.

Our example dataset have only two redundant marker. We can create a new `onemap` object without them, using the `create_data_bins` function. This function keeps only the most representative marker of each bin from `bins` object.

```{r}
bins_example <- create_data_bins(comb_example, bins)
bins_example
```

The arguments for `create_data_bins` function are the `onemap` object and the object created by `find_bins` function.

# Exporting .raw file from onemap object

The functions `onemap_read_vcfR` generates new onemap objects without use a input `.raw` file. Also, the functions `combine_onemap` and `create_data_bins` manipulates the information of the original `.raw` file and creates a new data set. In both cases, you do not have a input file `.raw` that contains the same informations of the analysed data. If you want to create a new input file with the data set you are working after using this functions, you can use the function `write_onemap_raw`.  

```{r, eval=FALSE}
write_onemap_raw(comb_example, file.name = "new_dataset.raw", cross="outcross")
```

The file `new_dataset.raw` will be generated in your working directory. In our example, it contains only non-redundant markers from `onemap_example_out` and `vcf_example_out` data sets.

# Testing segregation pattern

For the map building process it is also important to know which markers have deviations in the expecteded segregation pattern. It can be a good pratice to remove them from the map building process, because they can adversely affect the map building, and, once the map is builded, they can be inserted.

The function `test_segregation_of_a_marker` performs chi-square test according with mendelian segregation to check if a specific marker is following the expected segregation pattern. 

```{r}
test_segregation_of_a_marker(bins_example, 4)
```

The arguments are the `onemap` object and the number of the marker you want to test.

You can also test all the markers in your `onemap` object using  the `test_segregation` function. The results can be viewed printing the output object of class `onemap_segreg_test`.

```{r}
segreg_test <- test_segregation(bins_example)
print(segreg_test)
```

The only argument of the function is a `onemap` object. 

Once we have the `onemap_segreg_test`object, the function `select_segreg` can be used to show only the markers considered with/without segregation distortion. By default, it uses as threshold for the test a global $\alpha=0.05$, corrected for multiple test with Bonferroni correction.

```{r}
select_segreg(segreg_test, distorted = TRUE) #to show the markers names with segregation distortion

select_segreg(segreg_test, distorted = FALSE) #to show the markers names without segregation distortion
```

It is not recommended, but you can define a different threshold value changing the `threshold` argument of the function `select_segreg`. 

For the next steps will be useful to know the numbers of each markers with segregation distortion, so then you can keep those out of your map building analysis. These numbers refer to the lines where markers are located on the data file.

To access the corresponding number for of this markers you can change the `numbers` argument:

```{r}
dist <- select_segreg(segreg_test, distorted = TRUE, numbers = TRUE) #to show the markers numbers with segregation distortion
dist

no_dist <- select_segreg(segreg_test, distorted = FALSE, numbers = TRUE) #to show the markers numbers without segregation distortion
no_dist
```

You can also see the results graphically by:

```{r}
plot(segreg_test)
```

# Strategies for this tutorial example

Now, we start the map building analysis. In this example we follow two different strategies:

* Using only recombinations informations.

* Using the recombinations and also the reference genome informations, once our example have `CHROM` and `POS` informations for some of the markers.

First, we will apply the strategy using only recombinations informations. In a second part of this tutorial we show a way to use also reference genome informations. At the and of our analysis we will be able to compare this two strategies drawing the resulted genetic maps.

# Using only recombinations informations

## Estimating two-point recombination fractions

To start the map building analysis, the first step is estimating the recombination
fraction between all pairs of markers, using two-point tests. 

The function `rf_2pts` uses as default values of LOD Score `3` and maximum recombination fraction `0.50`. You can change this values according with your dataset. Also, you can use the function `suggest_lod` to calculate a suggested LOD score considering that multiple tests are being performed.

```{r}
LOD_sug <- suggest_lod(bins_example)
LOD_sug
```

And apply this suggested value to the two-point tests:

```{r, twopoint, results='hide'}
twopts <- rf_2pts(bins_example, LOD = LOD_sug, max.rf = 0.5)
``` 

Although two-point tests were implemented in C language, which is usually much
faster than R, this step can take quite some time, depending on the
number of markers involved and their segregation type, because all
combinations will be estimated and tested. Besides, the results use a
lot of memory and a rather powerful computer is needed.

When the two-point analysis is finished, an object of class `rf_2pts`
is created. Typing

```{r, eval=FALSE}
twopts
```

will show a message with the criteria used in the analysis and some
other information:

```{r, echo=FALSE}
twopts
``` 

If you want to see the results for given markers, say `M1`
and `M3`, the command is:

```{r}
print(twopts, c("M1", "M3"))
``` 

Each line corresponds to a possible linkage phase. `CC` denotes coupling
phase in both parents, `CR` and `RC` denote coupling phase in parent 1
and 2, respectively, and repulsion in the other, and `RR`
denotes repulsion phase in both parents. Value `rf` is the maximum
likelihood estimate of the recombination fraction, with its corresponding
LOD Score.

## Assigning markers to linkage groups

Once the recombination fractions and linkage phases for all pairs of
markers have been estimated and tested, markers can be assigned to
linkage groups. To do this, first use the function `make_seq` to
create a sequence with the markers you want to assign. 

The function `make_seq` is used to create sequences from objects of
several kinds, as will be seen along this tutorial. 

Here, the object
is of class `rf_2pts` and the second argument specifies which markers
one wants to use. If one wants to use only a subset of
markers, say `M1` and `M2`, the option will be a vector with the corresponding numbers of the markers, as `c(1,2)`, you can also use a string `"all"` to specify that you want to analyze all markers. In our example, we will use the vector with the numbers of the markers with no segregation distortion.

```{r}
mark_no_dist <- make_seq(twopts, c(no_dist))
```

Because
the identification of the markers can be cumbersome, one should use
the function `marker type` to see their numbers, names and types:


```{r} 
marker_type(mark_no_dist)
``` 

The grouping step is very simple and can be done by using the function
`group`:

```{r}
LGs <- group(mark_no_dist)
```

For this function, optional arguments are `LOD` and `max.rf`, which
define thresholds to be used when assigning markers to linkage groups.
If none provided (default), criteria previously defined for the object
`twopts` are used.

The previous command generates an object of class `group` and the
command `print` for such object has two options. If you type:

```{r, eval=FALSE}
LGs
``` 

you will get detailed information about the groups, that is, all linkage
groups will be printed, displaying the names of markers in each one of
them.

```{r, echo=FALSE}
LGs
``` 

However, in case you just want to see some basic information (such as
the number of groups, number of linked markers, etc), use

```{r}
print(LGs, detailed = FALSE)
``` 

You can notice that all markers are linked to some linkage group. If
the LOD Score threshold is changed to a higher value, some markers are
kept unassigned:

```{r}
LGs <- group(mark_no_dist, LOD = 6)
LGs
``` 

Changing back to the previous criteria, now setting the maximum recombination fraction to 0.40:

```{r}
LGs <- group(mark_no_dist, LOD = LOD_sug, max.rf = 0.4)
LGs
``` 

## Genetic mapping of linkage group 3

Once marker assignment to linkage groups is finished, the mapping step
can take place. First of all, you must set the mapping function that
should be used to display the genetic map throughout the analysis. You
can choose between `Kosambi` or `Haldane` mapping functions. To use
Haldane, type

```{r, eval=FALSE}
set_map_fun(type = "haldane")
```

To use Kosambi

```{r, eval=FALSE}
set_map_fun(type = "kosambi")
```

If you do not set one of these functions, the kosambi is used as default.

Now, you must define which linkage group will be mapped. In another
words, a linkage group must be `extracted` from the object of class
`group`, in order to be mapped. For simplicity, we will start here
with the smallest one, which is linkage group 3. This can be easily
done using the following code:

```{r}
LG3 <- make_seq(LGs, 3)
```

The first argument (`LGs`) is an object of class `group` and the
second is a number indicating which linkage group will be extracted,
according to the results stored in object `LGs`. The object `LG3`,
generated by function `make_seq`, is of class `sequence`, showing that
this function can be used with several types of objects.

If you type

```{r, eval=FALSE}
LG3
``` 

you will see which markers are comprised in the sequence, and also
that no parameters have been estimated so far.

```{r, echo=FALSE}
LG3
``` 

To order these markers, one can use a two-point based algorithm such
as Seriation (Buetow and Chakravarti, 1987), Rapid Chain Delineation
(Doerge, 1996), Recombination Counting and Ordering (Van Os et al.,
2005) and Unidirectional Growth (Tan and Fu, 2006):
  
```{r,  results='hide'}
LG3_ser <- seriation(LG3)
LG3_rcd <- rcd(LG3)
LG3_rec <- record(LG3)
LG3_ug <- ug(LG3)
``` 

In this case, there are some differeces between algorithms results (results not shown).

To order by comparing all possible orders (exhaustive search), the
function `compare` can be used:

```{r, eval=TRUE,  results='hide'}
LG3_comp <- compare(LG3)
``` 

**WARNING: This algorithm can take some time to run, depending on marker types in
the linkage group. If you are working in a personal computer, without 
high capacity, we recommend using maximum of ten markers. **

If you have more markers in your group, we suggest to use the following explained approaches
`order_seq` or `mds_onemap`.

In the example, 
`LG3` contains only six markers. Two of them are of type D1 and one are
segregating in 3:1 fashion (type C). Thus, although the number 
of possible orders is relatively small (360), for each order there 
are various possible combinations of linkage phases. Also, the 
convergence of the EM algorithm takes considerably more time, because 
markers of type C and D are not very informative.

The first argument to the `compare` function is an object of class
`sequence` (the extracted group `LG3`), and the object generated by
this function is of class `compare`.

To see the results of the previous step, type

```{r}
LG3_comp
``` 

Remember that for outcrossing populations, one needs to estimate
marker order and also linkage phases between markers for a given
order. However, because two point analysis provides information
about linkage phases, this information is taken into consideration in
the `compare` function, reducing the number of combinations to be
evaluated. If a given linkage phase has LOD greater than 0.005 in the two point analysis, we assume that this phase is very unlikely and so does not need to be evaluated in the multipoint procedure used by `compare`. We did extensive simulations which showed that this is a good procedure.

By default, `OneMap` stores 50 orders, which may or may not be unique.
The value of `LOD` refers to the overall LOD Score, considering all
orders tested. `Nested LOD` refers to LOD Scores within a given order, that is, scores for different combinations of linkage phases for the same
marker order.

For example, order 1 has the largest value of log-likelihood and,
therefore, its LOD Score is zero for a given combination of linkage
phases (CC, CC, RR, RR). For this same order and other linkage phases, LOD Score is -5.20. Analyzing the results for order 2, notice that its highest LOD Score is very close to zero, indicating that this order is also quite plausible. Notice also that `Nested LOD` will always contain at least one zero value, corresponding to the best combination of phases for markers in a given order. Due to the information provided by two-point analysis, not all combinations are tested and that is the reason why the number of Nested LOD values is different for each order.

Unless one has some biological information, it is a good idea to
choose the order with the highest likelihood. The final map can then
be obtained with the command

```{r}
LG3_final <- make_seq(LG3_comp, 1, 1)
``` 

The first argument is the object of class `compare`. The second argument indicates which order is chosen: 1 is for the order with highest likelihood, 2 is for the second best, and so on. The third argument indicates which combination of phases is chosen for a given order: 1 also means the combination with highest likelihood among all combinations of phases (based on Nested LOD).

For simplicity, these values are defaults, so typing

```{r}
LG3_final <- make_seq(LG3_comp)
``` 

have the same effect.

To see the final map, type

```{r}
LG3_final
``` 

At the leftmost position, marker names are displayed. `Position` shows
the cumulative distance using the Kosambi mapping function. Finally,
`Parent 1` and `Parent 2` show the diplotypes of both parents, that
is, the combination in which alleles are arranged in the chromosomes, given the estimated linkage phase. Notation is the same as that used by Wu et al. (2002a). Details about how ordering algorithms can be chosen and used are presented by Mollinari et al. (2009).

A careful examination of the results can be done using the function `rf_graph_table` to provide graphical view:

```{r}
rf_graph_table(LG3_final)
```

With the default arguments, this functions plots the recombination fractions between the markers pointed in the axes. You can change the number of colors from `rainbow` pallete with the argument `n.colors`. Hot colors (more close to red) represents lower values of recombination fractions, as showed in the scale at right side of the graphic. White cells indicate combinations of markers for which the recombination fractions cannot be estimated (D1 and D2). If you want to analyze the LOD values between the markers, use `graph.LOD = TRUE`.

```{r}
rf_graph_table(LG3_final, graph.LOD = TRUE)
```

If you change the `inter` argument to `TRUE`,  you should also specify a output html file name in `html.file`. This html contains a iterative plolty graphic. If you hover the mouse cursor over the cells it shows some extra information about cells, as percentagem of missing data, marker name and type. The output html file is generated in your work directory and opens automatically in your internet browser.

```{r, eval=FALSE}
rf_graph_table(LG3_final, inter = TRUE, html.file = "LG3.html")
```

For example, passing on the cell corresponding to markers  M8 and M13, you can see their names (`M8` and `M13` ), types (`B3.7` and `C.8`), recombination fraction (`rf = 0.03`) and LOD Scores for each possible linkage phase. This is quite useful in helping to interpret the results.

If you want to see corresponding marker numbers (not the names) in the axis just change the argument `mrk.axis` to `numbers`. It can make the next steps easier.

```{r}
rf_graph_table(LG3_final, inter = FALSE, mrk.axis = "numbers")
```

The `rf_graph_table` can also be used to check the order of markers
based on the monotonicity of the matrix: as we get away from the
secondary diagonal, the recombination fraction values should increase.

Looking at the matrix, it is possible to see a gap between markers `M7` and `M18` (numbers 7 and 18). In some cases, gaps could indicate that the group must be divided at this position, but here `SNP18` (number 43) also show linkage with `M8`, which points that probabily it is only a gap. Adding more markers to this groups could fill this gap.

Changing other arguments of the function you can add/remove labels of the axes ('lab.xy') and add a title to the graph ('main').

```{r}
rf_graph_table(LG3_final, main = "LG3", inter = FALSE, n.colors = 7, lab.xy = c("markers", "markers"))
```

## Genetic mapping of linkage group 2

Now, let us map the markers in linkage group number 2.

 Again, `extract` that group from the object `LGs`:
 
```{r}
LG2 <- make_seq(LGs, 2)
LG2
``` 

Note that there are more than 10 markers in this group, so it is infeasible to
use the `compare` function with all of them because it will take a very
long time to proceed.

First, use `rcd` to get a preliminary order estimate:

```{r}
LG2_rcd <- rcd(LG2)
LG2_rcd
```

Use the `marker_type` function to check the segregation types of all
markers in this group:

```{r, , echo=TRUE}
marker_type(LG2)
``` 

Based on their segregation types and distribution on the preliminary
map, markers `M4`, `M20`, `M24`, `SNP22`, `SNP23`, `SNP24` and `SNP25` are the most
informative ones (type `A` is better, followed by type `B`). So,
let us create a framework of ordered markers using `compare` for the
most informative ones:

```{r, results='hide'}
LG2_init <- make_seq(twopts, c(4, 20, 24, 49,50,51))
``` 

Now, the first argument to `make_seq` is an object of class `rf_2pts`,
and the second argument is a vector of integers, specifying which
molecular markers comprise the sequence.

```{r, results='hide'}
LG2_comp <- compare(LG2_init)
```

Select the best order:

```{r}
LG2_frame <- make_seq(LG2_comp)
``` 

Also, we can obtain a useful diagnostic graphic using the function `rf_graph_table`.

```{r}
rf_graph_table(LG2_frame, mrk.axis = "numbers")
```

The graphic shows that there are two groups of markers, once `M20` and `M4` are far from the other markers. These markers could be in different linkage groups or they are distant in the same group. Adding more markers will give more informations to solve this issue.

Next, let us try to map the remaining markers, one at a time. Fist, we will try to add the remaining most informative markers. Starting with `SNP25`:

```{r, results='hide'}
LG2_extend <- try_seq(LG2_frame, 52)
```

```{r}
LG2_extend
``` 

Based on the LOD Scores, marker SNP25 is probably better located after `SNP22` (number 49). Detailed results can be seen with

```{r}
print(LG2_extend, 7)
```

The second argument indicates the position where to place the marker.
Note that the first allele arrangement is the most likely one.

It should be pointed out that the framework created by the function
`compare` (with `M20`, `M4`, `SNP24`, `SNP23`, `M24` and `SNP22`) could be in
reverse order (`SNP22`, `M24`, `SNP23`, `SNP24`, `M4` and `M20`) and still represent the
  same map.Thus, positioning of markers with the `try_seq` command can be
different in your computer. For example, here marker `SNP25` was better
placed at position 7; however if you obtain a reversed order, marker
`SNP25` would be better placed in position 1. In both cases the best
position for this marker is after `SNP22`.

We can better evaluate the order with `rf_graph_table`. It requires a object of `sequence` class with mapping informations.

```{r, echo=TRUE}
LG2_test <- make_seq(LG2_extend, 7, 1)
``` 

When using `make_seq` with an object of class `try`, the second
argument is the position on the map (according to the scale on the
right of the output) and the last argument indicates linkage phases
(defaults to 1, higher nested LOD).

```{r}
rf_graph_table(LG2_test, mrk.axis = "numbers")
```

We can see that `SNP25` (or marker 52) was positioned at the end of the sequence and the color pattern shows that it is strongly linked with its neighbors, indicating that it is well positioned, then we will maintain this marker at this position:

```{r}
LG2_frame <- LG2_test
```

Adding other markers, one by one (output not shown):

```{r, results='hide'}
LG2_extend <- try_seq(LG2_frame, 9)
LG2_frame <- make_seq(LG2_extend, 3)
LG2_extend <- try_seq(LG2_frame, 16)
LG2_frame <- make_seq(LG2_extend, 1)
LG2_extend <- try_seq(LG2_frame, 21)
LG2_frame <- make_seq(LG2_extend, 4)
LG2_extend <- try_seq(LG2_frame, 23)
LG2_frame <- make_seq(LG2_extend, 5)
LG2_extend <- try_seq(LG2_frame, 27)
LG2_frame <- make_seq(LG2_extend, 1)
LG2_extend <- try_seq(LG2_frame, 29)
LG2_frame <- make_seq(LG2_extend, 12)
LG2_extend <- try_seq(LG2_frame, 45)
LG2_frame <- make_seq(LG2_extend, 8)
LG2_extend <- try_seq(LG2_frame, 46)
LG2_frame <- make_seq(LG2_extend, 7)
LG2_extend <- try_seq(LG2_frame, 47)
LG2_frame <- make_seq(LG2_extend, 7)
LG2_extend <- try_seq(LG2_frame, 48)
LG2_final <- make_seq(LG2_extend, 10)
``` 

Checking graphically:

```{r}
rf_graph_table(LG2_final)
```

The process of adding markers sequentially can be automated with the
use of function `order_seq`.
  
```{r}
LG2_ord <- order_seq(LG2, n.init = 5, THRES = 3)
``` 

Basically, this function automates what the `try_seq` function does,
using some pre-defined rules. In the function, `n.init = 5` means that
five markers (the most informative ones) will be used in the `compare`
step; `THRES = 3` indicates that the `try_seq` step will only add
markers to the sequence which can be mapped with LOD Score greater
than 3.

*NOTE*: Although very useful, this function can be misleading,
 specially if there are not many fully informative markers, so use it
 carefully. Results can vary between multiple runs on the same markers, of course.
 
Check the final order:

```{r}
LG2_ord
```

Note that markers `9`, `16`, `29`, `46`, `47`, `48`, `51` and `52` could not be safely mapped to a single
position (`LOD Score > THRES` in absolute value). The output displays
the `safe` order and the most likely positions for markers not mapped,
where `***` indicates the most likely position and `*` corresponds to
other plausible positions.

To get the safe order (_i.e._, without markers `9`, `16`, `29`, `46`, `47`, `48`, `51` and `52`), use

```{r}
LG2_safe <- make_seq(LG2_ord, "safe")
```

and to get the order with all markers, use

```{r}
LG2_all <- make_seq(LG2_ord, "force")
LG2_all
```

Notice that, for this linkage group, the `forced` map obtained with
`order_seq` is different from that obtained with `compare` plus
`try_seq`. It depends of which markers we choose to try add first when doing
manually.

The `order_seq` function can also perform two rounds of the `try_seq`
algorithms, first using `THRES` and then `THRES - 1` as threshold.
This generally results in safe orders with more markers mapped, but
may take longer to run. To do this use the `touchdown` option:

```{r, results='hide'}
LG2_ord <- order_seq(LG2, n.init = 5, THRES = 3, touchdown = TRUE)
```

```{r}
LG2_ord
```

For this particular sequence, the `touchdown` step could map safely markers `46` and `52`, but this depends on the specific dataset.

```{r}
rf_graph_table(LG2_all, mrk.axis = "numbers")
```

Finally, to check for alternative orders (because we did not use
exhaustive search), use the `ripple_seq` function:

```{r}
ripple_seq(LG2_all, ws = 4, LOD = LOD_sug)
``` 

We should do this to any of the orders we found, either using
`try_seq` or `order_seq`. Here, we choose `LG2_all` for didactic purposes only. The second argument, `ws = 4`, means that
subsets (windows) of four markers will be permutated sequentially
(`4!` orders for each window), to search for other plausible orders.
The `LOD` argument means that only orders with LOD Score smaller than
3.68 will be printed.

The output shows sequences of four numbers, because `ws = 4`. They are
followed by an `OK` if there is no alternative order with LOD
Score smaller than `LOD = LOD_sug` in absolute value, or by a list of
alternative orders. In the example, some sequences showed
alternative orders with LOD smaller than `LOD = LOD_sug`. However, the best order was the original one (`LOD = 0.00`).

If there were an alternative order more likely than the original, one
should check the difference between these orders (and linkage phases). 

In some cases, even if there are no better alternative order suggested by `ripple_seq`, the graphic showed color pattern different of the expected. Then, we can remove 
doubtful markers (for this groups markers `23` and `29`) and try to positioned them again. First, we use the function `drop_marker` to remove selected marker of our sequence.

```{r}
LG2_test_seq <- drop_marker(LG2_all, c(23,29))
```

The function will provide a sequence with the same order of the estimated map (`LG2_all`). After, we should estimate the map again using this predefined order. For this we use the `map` function:

```{r}
(LG2_test_map <- map(LG2_test_seq))
```

Now we have the map without markers `23` and `51`. 

```{r}
rf_graph_table(LG2_test_map, mrk.axis = "numbers")
```

We use `try_seq` function to positioned them again:

```{r}
LG2_test_seq <- try_seq(LG2_test_map, 23)
LG2_test_23 <- make_seq(LG2_test_seq, 6)
LG2_test_seq <- try_seq(LG2_test_23, 29)
LG2_test_23_29 <- make_seq(LG2_test_seq, 12)

rf_graph_table(LG2_test_23_29, mrk.axis = "numbers")
```

Marker 23 keeped its previous position, but marker 29 was re-positioned, configuring now a gap between markers 47 and 50. We removed marker 29 of our map, because it color pattern are too different of expected. Then, our final map is:

```{r}
LG2_final <- LG2_test_23
LG2_final

rf_graph_table(LG2_final, mrk.axis = "numbers")
```

## Genetic mapping of linkage group 1

Finally, linkage group 1 (the largest one) will be analyzed. Extract markers:

```{r}
LG1 <- make_seq(LGs, 1)
``` 

Construct the linkage map, by automatically using try algorithm:

```{r, results='hide'}
LG1_ord <- order_seq(LG1, n.init = 6, touchdown = TRUE)
```

Notice that the second round of `try_seq` added markers `10`, `31`, `32`, `35`, `36`, `40` and `42`.

```{r}
LG1_ord
```

Now, get the order with all markers:

```{r}
(LG1_frame <- make_seq(LG1_ord, "force"))
``` 

Check the map graphically:

```{r}
rf_graph_table(LG1_frame, mrk.axis = "numbers")
```

Check for alternative orders:
```{r}
ripple_seq(LG1_frame)
``` 

No better order was observed. 

Alternatively, you can also use `mds_onemap` function to obtain a first draft for the markers order. The `mds_onemap` function makes a interface between `OneMap` and `MDSMap` package. The ordering approach presented in `MDSMap` provides a faster and efficient way of ordering markers using multi-dimensional scaling. The method also provides diagnostics graphics and parameters to find outliers to help users to filter the dataset. You can find more informations in `MDSMap` [vignette](https://CRAN.R-project.org/package=MDSMap). Here we will show a simple example of how it can be used for ordering our example markers from an outcrossing population.

```{r}
LG1_mds <- mds_onemap(LG1)
```

If you only specify the input sequence, mds_onemap will use the default parameters. It will generate MDSMap input file in `out.file` file and the `NULL.pdf` file with the diagnostic graphics in your work directory. Also, the default method used is the principal curves, know more about using `?mds_onemap` and reading the MDSMap [vignette]( https://CRAN.R-project.org/package=MDSMap). By default, we use the OneMap HMM approach to estimate the distances after the MDSMap ordered the markers, but you can have the default output from MDSMap setting `hmm = FALSE`.

```{r}
rf_graph_table(LG1_mds)
```

Based on the drafts from `order_seq` or/and `mds_onemap`, we can remove some doubtful markers accordinly with the graphic, try to positioned them again and decide if and where we will maintain them.

```{r}
LG1_test_seq <- drop_marker(LG1_frame, c(10,11,28,42))
LG1_test_map <- map(LG1_test_seq)
```

```{r}
rf_graph_table(LG1_test_map, mrk.axis = "numbers")
```

```{r, results='hide'}
LG1_extend <- try_seq(LG1_test_map,10)
LG1_test_map <- make_seq(LG1_extend,15) 
LG1_extend <- try_seq(LG1_test_map,11)
LG1_test <- make_seq(LG1_extend,23) # We choose to remove this marker
LG1_extend <- try_seq(LG1_test_map,28)
LG1_test_map <- make_seq(LG1_extend,16) 
LG1_extend <- try_seq(LG1_test_map,42)
LG1_final <- make_seq(LG1_extend,17) 
```

Print it:
```{r}
LG1_final
```

```{r}
rf_graph_table(LG1_final)
```

As an option, different algorithms to order markers could be applied: 

```{r, eval=FALSE}
LG1_ser <- seriation(LG1)
LG1_rcd <- rcd(LG1)
LG1_rec <- record(LG1)
LG1_ug  <- ug(LG1)
``` 

There are some differences between the results. Seriation did not
provide good results in this case. See Mollinari et al. (2009) for an
evaluation of these methods.

# Using the recombinations and the reference genome informations

In our example, we have reference genome chromosome and position informations for some of the markers, here we will examplify one method of using this informations to help build the genetic map.

With the `CHROM` informations in the input file, you can identify markers belonging to some chromosome using the function `make_seq` with the `rf_2pts` object. For example, assign the string `"1"` for the second argument to get chromosome 1 makers. The output sequence will be automatically ordered by `POS` informations.

```{r}
CHR1 <- make_seq(twopts, "1")
CHR1
CHR2 <- make_seq(twopts, "2")
CHR3 <- make_seq(twopts, "3")
```

## Adding markers with no reference genome informations

According to `CHROM` informations we have three defined linkage groups, now we can try to group the markers without chromossome informations to them using recombination informations. For this, we can use the function `group_seq`:

```{r}
CHR_mks <- group_seq(input.2pts = twopts, seqs = "CHROM", unlink.mks = mark_no_dist,
                      repeated = FALSE)
```

The function works as the function `group`, but considering preexisting sequences. Setting `seqs` argument with the string `"CHROM"`, it will considered the preexisting sequences according to `CHROM` information. You can also indicate others preexisting sequences if it make sense for your study. For that, you should inform a list with objects of class `sequences`, as the example:

```{r, eval=FALSE}
CHR_mks <- group_seq(input.2pts = twopts, seqs = list(CHR1=CHR1, CHR2=CHR2, CHR3=CHR3), 
                      unlink.mks = mark_no_dist, repeated = FALSE)
```

In this case, the command had the same effect of the previous, because we indicate chromossome sequences, but others sequences can be used.

The `unlink.mks` argument receive a object of class `sequence`, this define which markers will be tested to group with the sequences in `seqs`. In our example, we will indicate only the markers with no segregation distortion, using the sequence `mark_no_dist`. It is also possible to use the string `"all"` to test all the remining markers at the `rf_2pts` object. 

In some cases, the same marker can group to more than one sequence, those markers will be considered `repeated`. We can choose if we want to remove or not (`FALSE/TRUE`) them of the output sequences, with the argument `repeated`. Anyway, their numbers will be informed at the list `repeateds` in the output object. 
In the example case, there are no repeated markers. However, if they exists, it could indicate that their groups actually constitute the same group. Also, genotyping erros can generate repeated markers. Anyway, they deserves better investigations. 

We can access detailed information about the results just printing:

```{r}
CHR_mks
```

Also, we can access the numbers of repeated markers with:

```{r}
CHR_mks$repeated
```

The same way, we can access the output sequences:

```{r}
CHR_mks$sequences$CHR1
# or
CHR_mks$sequences[[1]]
```

For this function, optional arguments are `LOD` and `max.rf`, which
define thresholds to be used when assigning markers to linkage groups.
If none provided (default), criteria previously defined for the object
`rf_2pts` are used.

Now we can order the markers in each group as we made before in ([Genetic mapping of linkage group 1,2 and 3](#genetic-mapping-of-linkage-group-3)). As showed, we can choose different approaches to order the markers. 

To order those groups, first we will use `order_seq` function to access a preliminary order and after, we will edit some markers position or remove some of them according with they color pattern in `rf_graph_table` graphic, and other parameters as likelihood and map size. 

## Genetic mapping of linkage group 1 (with reference genome informations)

```{r, results='hide'}
CHR1_frame <- mds_onemap(CHR_mks$sequences$CHR1)
# or
CHR1_ord <- order_seq(CHR_mks$sequences$CHR1)
CHR1_frame <- make_seq(CHR1_ord, "force")
```

```{r, eval=FALSE}
rf_graph_table(CHR1_frame) # graphic not showed
```

The group is similar to that builded before with only recombinations informations. We will better explore differences in a latter step. Only marker `11` do not follow exactly the expected color pattern, then we will try to repositioned it.

```{r}
CHR1_test_seq <- drop_marker(CHR1_frame, 11)
CHR1_test_map <- map(CHR1_test_seq)
CHR1_add11_seq <- try_seq(CHR1_test_map, 11)
CHR1_add11 <- make_seq(CHR1_add11_seq, 25) # marker 11 was placed at the same position as before
```

Based in those results, we decide to not include marker 11 in our map.

```{r}
CHR1_test_map
```

```{r}
rf_graph_table(CHR1_test_map) 
```

```{r}
CHR1_final <- CHR1_test_map
```

Checking for better orders:

```{r}
ripple_seq(CHR1_final)
```

## Genetic mapping of linkage group 2 (with reference genome informations)

```{r, results='hide'}
CHR2_frame <- mds_onemap(CHR_mks$sequences$CHR2)
# or
CHR2_ord <- order_seq(CHR_mks$sequences$CHR2)
CHR2_frame <- make_seq(CHR2_ord, "force")
```

```{r, eval=FALSE}
rf_graph_table(CHR2_frame) # graphic not showed
```

As did before, we will not change markers positions of this group.

```{r}
CHR2_final <- CHR2_frame
```

## Genetic mapping of linkage group 3 (with reference genome informations)

```{r, results='hide'}
CHR3_frame <- mds_onemap(CHR_mks$sequences$CHR3)
# or
CHR3_ord <- order_seq(CHR_mks$sequences$CHR3)
CHR3_frame <- make_seq(CHR3_ord, "force")
```

```{r, eval=FALSE}
rf_graph_table(CHR3_frame, mrk.axis = "numbers") # graphic not showed
```

Here, marker `29` have color pattern too different of the expected, removing it could influentiate in other markers ordering. Then we will remove them and search for a new order.

```{r, results='hide'}
CHR3_test_seq <- drop_marker(CHR3_frame, c(29))
CHR3_test_ord <- order_seq(CHR3_test_seq)
CHR3_test_map <- make_seq(CHR3_test_ord, "force")
```

```{r, eval=FALSE}
rf_graph_table(CHR3_test_map, mrk.axis = "numbers") #graphic not showed
```

Trying to add markers `23`, `27` and `29` again.

```{r, results='hide'}
CHR3_add29_seq <- try_seq(CHR3_test_map, 29)
CHR3_add29 <- make_seq(CHR3_add29_seq, 12) # Marker 29 increase the map size disproportionately, it was removed from the map
```

```{r}
CHR3_final <- CHR3_test_map
rf_graph_table(CHR3_final, inter = FALSE)
```

Checking for better orders:

```{r}
ripple_seq(CHR3_final)
```


# Drawing the genetic maps

Once all linkage groups were obtained using both strategies, we can draw a map for each strategy using the function `draw_map`. Since version 2.1.1007, OneMap has a new version of `draw_map`, called `draw_map2`. The new function draws elegant linkage groups, and presents new arguments to personalize your draw.

If you prefer the old function, we also keep it. Follow examples how to use both of them.

## Draw_map

Drawing map builded with only recombinations informations

```{r, echo=TRUE, fig=TRUE}
map1 <- list(LG1_final, LG2_final, LG3_final)
draw_map(map1, names = TRUE, grid = TRUE, cex.mrk = 0.7)
```

Drawing map builded with reference genome and  recombinations informations

```{r, echo=TRUE, fig=TRUE}
map2 <- list(CHR1_final, CHR2_final, CHR3_final)
draw_map(map2, names = TRUE, grid = TRUE, cex.mrk = 0.7)
``` 

We also can draw a maps comparing corresponding linkage groups in each strategy:

```{r, width = 9.5, height = 9.5}
CHR1_comp <- list(LG1_final, CHR1_final)
draw_map(CHR1_comp, names = TRUE, grid = TRUE, cex.mrk = 0.7)
```

Markers `M1` and `SNP2` are in different position between the strategies results for CHR1.

```{r, width = 9.5, height = 9.5}
CHR2_comp <- list(LG3_final, CHR2_final)
draw_map(CHR2_comp, names = TRUE, grid = TRUE, cex.mrk = 0.7)
```

Both strategies produced the same result for CHR2 (the map are only inverted).

```{r, width = 9.5, height = 9.5}
CHR3_comp <- list(LG2_final, CHR3_final)
draw_map(CHR3_comp, names = TRUE, grid = TRUE, cex.mrk = 0.7)
``` 

There are a invertion between markers `SNP17` and `SNP18` and the marker `M29` was removed in te second strategy.

Or groups alone:

```{r}
draw_map(CHR1_final, names = TRUE, grid = TRUE, cex.mrk = 0.7)
``` 

Function `draw_map` draws a very simple graphic
representation of the genetic map. More recently, we developed a new version called `draw_map2` that draws a more sophisticated figure. Furthermore, once the distances and the
linkage phases are estimated, other map figures can be drawn by the
user with any appropriate software. There are several free software
that can be used, such as `MapChart` (Voorrips, 2002).

## Draw_map2

The same figures did with `draw_map` can be done with `draw_map2` function. But it has different capacities and arguments. Here are some examples, but you can find more options in the help page `?write_map2`.

Drawing map builded with only recombinations informations

```{r, echo=TRUE, results='hide', eval=FALSE}
draw_map2(LG1_final, LG2_final, LG3_final, main = "Only with linkage information", 
          group.names = c("LG1", "LG2", "LG3"))
```

```{r, echo=FALSE, results='hide'}
draw_map2(LG1_final, LG2_final, LG3_final, main = "Only with linkage information", 
          group.names = c("LG1", "LG2", "LG3"), output = "map1.png")
```

<img src="map1.png" width="300" height="500">


The figure will be saved in your work directory with the default name `map.eps`. You can change the file name and extension specifing them in the argument `output`.

Drawing map builded with reference genome and  recombinations informations

```{r, echo=TRUE, results='hide', eval=FALSE}
draw_map2(CHR1_final, CHR2_final, CHR3_final, output= "map_ref.pdf", 
          col.group = "#58A4B0",
         col.mark= "#335C81")
``` 

```{r, echo=TRUE, results='hide', echo=FALSE}
draw_map2(CHR1_final, CHR2_final, CHR3_final, output= "map_ref.png", 
          col.group = "#58A4B0",
         col.mark= "#335C81")
``` 

<img src="map_ref.png" width="600" height="600">

With the argument `tag`, we can highlight some markers with other color. The arguments `col.group`, `col.mark` and `col.tag` can be changed to personalize the color of the groups, the markers, and the highlighted markers, respctivelly. 

We also can draw a maps comparing corresponding linkage groups in each strategy:

```{r, results='hide', eval=FALSE}
draw_map2(LG1_final, CHR1_final, output = "map_comp.pdf", tag = c("M1","SNP2"))
```

```{r, results='hide', echo=FALSE}
draw_map2(LG1_final, CHR1_final, output = "map_comp.png", tag = c("M1","SNP2"))
```

<img src="map_comp.png" width="200" height="500">

Markers `M1` and `SNP2` are in different position between the strategies results for CHR1. When defining marker names in `tag` argument, all markers with these name will be highlighted no matter in which group it/they is/are.


```{r, results='hide', eval=FALSE}
draw_map2(LG2_final, CHR3_final, tag= c("SNP17", "SNP18", "M29"), main = "Chromosome 3", 
          group.names = c("Only linkage", "With genome"), centered = TRUE, output = "map_comp2.pdf")
``` 

```{r, results='hide', echo=FALSE}
draw_map2(LG2_final, CHR3_final, tag= c("SNP17", "SNP18", "M29"), main = "Chromosome 3", 
          group.names = c("Only linkage", "With genome"), centered = TRUE, output = "map_comp2.png")
``` 

<img src="map_comp2.png" width="200" height="500">

There are a invertion between markers `SNP17` and `SNP18` and the marker `M29` was removed in te second strategy.


# Map estimation for an arbitrary order

If, for any reason, one wants to estimate parameters for a given
linkage map (_e.g._, for other orders on published papers), it is
possible to define a sequence and use the `map` function. For example,
for markers `M30`, `M12`, `M3`, `M14` and `M2`, in this order, use
  
```{r}
any_seq <- make_seq(twopts, c(30, 12, 3, 14, 2))
(any_seq_map <- map(any_seq))
``` 

This is a subset of the first linkage group. When used this way, the `map`
function searches for the best combination of phases between markers
and prints the results.

Furthermore, a sequence can also have user-defined linkage phases. The
next example shows (incorrect) phases used for the same order of
markers:

```{r, eval=FALSE}
any_seq <- make_seq(twopts, c(30, 12, 3, 14, 2), phase = c(4, 1, 4, 3))
(any_seq_map <- map(any_seq))
``` 

If one needs to add or drop markers from a predefined sequence,
functions `add_marker` and `drop_marker` can be used. For example, to
add markers 4 to 8 to `any_seq`.

```{r}
(any_seq <- add_marker(any_seq, 4:8))
```

Removing markers 3, 4, 5, 12 and 30 from `any_seq`:

```{r}
(any_seq <- drop_marker(any_seq, c(3, 4, 5, 12, 30)))
```

After that, the map needs to be re-estimated.

# Session Info

```{r}
sessionInfo()
```


# References

Buetow, K. H., Chakravarti, A. Multipoint gene mapping using
seriation. I. General methods. **_American Journal of Human
Genetics_** 41, 180-188, 1987.

Doerge, R.W. Constructing genetic maps by rapid chain delineation.
**_Journal of Agricultural Genomics_** 2, 1996.

Mollinari, M., Margarido, G. R. A., Vencovsky, R. and Garcia, A. A. F.
Evaluation of algorithms used to order markers on genetics maps.
**_Heredity_** 103, 494-502, 2009.

Tan, Y., Fu, Y. A novel method for estimating linkage maps.
**_Genetics_** 173, 2383-2390, 2006.

Van Os H, Stam P, Visser R.G.F., Van Eck H.J. RECORD: a novel method
for ordering loci on a genetic linkage map. **_Theor Appl Genet_**
112, 30-40, 2005.

Voorrips, R.E. MapChart: software for the graphical presentation of
linkage maps and QTLs. **_Journal of Heredity_** 93, 77-78, 2002.

Wu, R., Ma, C.X., Painter, I. and Zeng, Z.-B. Simultaneous maximum
likelihood estimation of linkage and linkage phases in outcrossing
species. **_Theoretical Population Biology_** 61, 349-363, 2002a.

Wu, R., Ma, C.-X., Wu, S. S. and Zeng, Z.-B. Linkage mapping of
sex-specific differences. **_Genetical Research_** 79, 85-96, 2002b.
