---
title: "Urban Foxes - t-LoCoH"
author: "Jill M. Shephard (j.shephard@murdoch.edu.au)"
date: "Last compiled on `r format(Sys.time(), '%d %B, %Y')`"
output:
  html_document: 
    df_print: paged
    toc: true
  pdf_document: default
  word_document:
    reference_docx: ./@Common Files/word-styles-reference-01.docx
knit: (function(input, ...) {
    rmarkdown::render(
        input,
        output_file = paste0(
            xfun::sans_ext(input), '-', Sys.Date(), '.html'
        ),
        output_dir = paste0("../markdownReport"),  
        envir = globalenv()
    )
  })
---
<br>

## File Description
Creates UD's for autocorrelated GPS data using t-LocoH using the *k*(with and without
time) method and the *a* method.

Original reference: #7322 - Lyons etal 2013

Lyons, A. J., W. C. Turner, and W. M. Getz. 2013. Home range plus: a space-time characterization of movement over real landscapes. Movement Ecology 2013.


Location to get t-LoCoH installation - Not available on CRAN or Github

install.packages("tlocoh", dependencies=TRUE, repos=c("http://R-Forge.R-project.org", "http://cran.cnr.berkeley.edu"))

```{r setup, include=TRUE}
knitr::opts_chunk$set(echo = TRUE)
here::here() #sets working directory 
# Set the working directory to the directory of the Project using the package 
# `here`.This is the equivalent to setting your working directory with
# setwd(), but is better as it links the working directory to the project
# directory and is therefore transferable between computers. 
# 
#list all libraries required in the script
#library(ggplot2)
library(tidyverse)
library(here)
library(ggmap)
library(ggplot2)
library(lubridate)
library(dismo)     #for gmap function
library(rgdal)     #to work with rasters
library(tlocoh)
library(sp)

```
<br> 

#### RData file
Load this if already have work in progress...
Note - make sure to update the name of this file if saving a more recent workspace
```{r}
#load(here("Foxes_tlocoh_fullscript.221121"))
```



#### Load Data
```{r read in data}
dataorig <- read_csv(here("./data/Tracking_foxes.csv"))
str(dataorig)
```
<br>

#### Clean the data

```{r}
#Check for duplicate locations in dataset
summary(duplicated(dataorig))

#make sure the data are ordered correctly by tag and date
#Sort data by ID and then datetime to make sure all data grouped together and 
#in correct order (to address error in code if needed)
dataorig <- dataorig[order(dataorig$ANIMALID,dataorig$DATETIMEmove),]

```

<br>

##Subset out all the individuals
```{r}
fox.cc <- dataorig %>% filter(ANIMALID == "CC")
fox.db <- dataorig %>% filter(ANIMALID == "DB")
fox.es <- dataorig %>% filter(ANIMALID == "ES")
fox.fj <- dataorig %>% filter(ANIMALID == "FJ")
fox.hx <- dataorig %>% filter(ANIMALID == "HX")
```

<br>
## FOX - CC - Working of the 'k' method

#### Apply posixct format to time and reduce the dataframe down to required columns.

As far as I'm aware the time data is already in local time so no transformation required
```{r}
#fox.cc$dt <- as.POSIXct(strptime(fox.cc$DATETIME, format="%d/%m/%Y %H:%M"))

fox.cc$dt <- as.POSIXct(fox.cc$DATETIME, format="%d/%m/%Y %H:%M", tz="Australia/Perth")

cc <- fox.cc[,c("LONGITUDE","LATITUDE","dt","ANIMALID")]
#rename cols
colnames(cc)[1:4] <- c("x","y","dt","id")
#check first 4 lines of the dataframe
cc[1:4,]

```

<br>

### Step 1 - Prepare the data in t-LoCoH format and create lxy object

give x and y a projection
This creates the first of a series of new dataframes that are joined. Pretty clunky way to do it 
but this is what is required in this program

```{r}
#sub-df 1 latlong
cc.sp.latlong <- SpatialPoints(cc[ , c("x","y")], proj4string=CRS("+proj=longlat +ellps=WGS84"))
cc.sp.utm <- spTransform(cc.sp.latlong, CRS("+proj=utm +south +zone=50 +ellps=WGS84")) 
cc.mat.utm <- coordinates(cc.sp.utm)
tail(cc.mat.utm)

#sub-df 2 local time - the data are already in this so just subset to follow naming format
cc.local <- as.POSIXct(cc$dt, tz="Australia/Perth")
local.tz <- "Australia/Perth"
cc.localtime <- as.POSIXct(format(cc.local, tz=local.tz), tz=local.tz)


#sub-df 3 id
cc.id <- cc[,c("id")]

#merge all the df in the correct tlocoh format and order 
cc.lxy <- xyt.lxy(xy=cc.mat.utm, dt=cc.localtime, id="cc", proj4string=CRS("+proj=utm +south +zone=50 +ellps=WGS84"))#, dup.dt.check=FALSE)

```
<br>

Explore the structure of the lxy object
```{r}
nrow(cc.lxy$pts)
summary(cc.lxy)
```
<br>

Plot out the movement trajectory
```{r}
plot(cc.lxy)
```
<br>

Display the distribution of locations by date, step length, and sampling interval.
```{r}
hist(cc.lxy)
```
<br>

Review the sampling frequency
```{r}
lxy.plot.freq(cc.lxy, cp=T)
```
<br>

### Space use model - *k* method - distance only (time not considered)

Construct a model of space-use without considering time (s=0). k=25 means that it is
considering the nearest 25 points to the parent point (at this stage its completely 
arbitrary). As we are not considering time these points are the nearest in space and as such 
may not necessarily be sequential. 
<br>

```{r}
cc.lxy <- lxy.nn.add(cc.lxy, s=0, k=25)
```

```{r}
summary(cc.lxy)
```
<br>

Save the lxy object for later analysis (when look at the time stuff)
```{r}
lxy.save(cc.lxy, dir="../data")
```
<br>

Make a kml to visualise the track on GoogleEarth so can get a feel for the animals movement.
This is easy but produces a pretty awful result. Doesn't appear to read the dt appropriately. 

Check out the t-locoh extension tutorial to see if there is a better way to do this.
```{r}
#lxy.exp.kml(cc.lxy, 'cc.lxy.151121.kml',compress = FALSE, pt.scale = 0.25, path.lwd = 3)
```
<br>


### Step 2 - Hull construction

The building blocks of all T-LoCoH analyses are hulls, which are simply minimum convex polygons constructed around each point from a set of nearest neighbors. Since we’ve already identified 25 nearest neighbors for each point, we can create hulls with up to 25 nearest neighbors each. We will use the tlocoh::lxy.lhs command to create an lhs object, the next in our progression.
```{r}
cc.lhs <- lxy.lhs(cc.lxy, k=3*3:8, s=0)
```
<br>

What we are doing here is creating 6 different hullsets with k values of 9, 12, 15, 18, 21, and 24 (note we are still setting s=0 because we are not considering the temporal component yet). It is useful to create a selection of hullsets so that we can compare them and choose the optimal one for our purposes. The downside of creating all of these extra hullsets is that it may take a little while to run. Once it is finished, we can get an idea of what areas are included in our hullsets using the tlocoh::plot command again. This time, we will specify that we want to plot the hulls and we’ll add all of the plots to a single page for easier comparison.
<br>

```{r}
plot(cc.lhs, hulls=TRUE, figs.per.page=6)
```
<br>

#### Create the isopleths
Isopleths are aggregations of hulls sorted in such a way as to reveal something about space use. The default settings for tlocoh::lhs.iso.add sorts hulls according to density, so the isopleths reflect the likelihood of occurrence, which is a proxy for intensity of use. Then we can plot these (using the iso=TRUE specification instead of hulls=TRUE) to see how they compare to one another and to the hullset plots.
```{r}
cc.lhs <- lhs.iso.add(cc.lhs)
```
<br>

```{r}
plot(cc.lhs, iso=TRUE, figs.per.page=6)
```
<br>

```{r}

plot(cc.lhs, iso=T, k=15, allpts=T, cex.allpts=0.1, col.allpts="gray90", ufipt=F)
```

Note: you can also produce the above plot without the pts. In this case just use:
plot(cc.lhs, iso=T, k=15, ufipt=F)

<br>

Two other plots can be used to evaluate the choice of *k* value. The first is the isopleth area curves, which will plot the area included in a set of different isopleth levels (ranging from 0.15 to 0.95 by 0.10). We want to check these plots to make sure that there are no sharp jumps between k values that indicate that a relatively small change in k results in a large increase in included area (likely a false commission). To look at this plot, we use the tlocoh::lhs.plot.isoarea command:

```{r}
lhs.plot.isoarea(cc.lhs)
```
<br>
There don’t appear to be any major jump (i.e., the curves are all resonably smooth, no matter the k value). This means we shouldn’t rule out any of the k values we have tested.

Next - look at the edge to area ratio. We are looking to exclude k values that result in very high edge:area ratios, which are indicative of the Swiss cheese pattern (i.e., many small holes). This is particularly important at some of the isopleths associated with the core area (0.35, 0.45, 0.55) where we would expect relatively few holes.
<br>

```{r}
lhs.plot.isoear(cc.lhs)
```

If the plots are too small in the RMarkdown window then put the code into the Console and 
view the plot in the plot window. Resize this area first so that the plot is nice and big.
Having run all the *k* values multiple time *k*=15 is actually the best. i.e. using a larger 
value of *k* doesnt really change how many of the grey dtps are included in the hulls.

Select this value for subsequent runs and save as an object
```{r}
cc.lhs.k15 <- lhs.select(cc.lhs, k=15)

lhs.save(cc.lhs.k15, dir="../data")
```
<br>

### Step 3 - Incorporate Time

If doing this step in another session then you need to load the lxy and lhs RData files that you saved above. Use the following syntax:

load('./data/cc.n900.2016-06-04.2016-08-02.lxy.02.RData')
load('./data/cc.n900.s0.k15.iso.lhs.02.RData')


create a new nearest neighbor set with a non-zero s parameter. That is, we are now creating a UD that incorporates time. In the first plot there are points in the same general areas that are colour coded differently. This means that they were in the same area but at different times so these points are not temporally related. In the s=0 calculations above this is ignored and therefore is not ecologically very informative. 

Firstly, need to select a 'decent' *s* value. To do this pick an *s* value such that 40-80% of the hulls are ‘time-selected.’ 
<br>

#### Select *s*
<br>
**This is Method 1**
```{r}
cc.lxy <- lxy.ptsh.add(cc.lxy)
```

This creates a set of 200 sample points, each with 10 nearest neighbors. This algorithm goes through a set of different s values and determines *what proportion of hulls are time-selected* (ptsh). Though this is a somewhat stochastic process, we can see that *s* values between approximately 0.0175 and 0.04 fall between proportions of time-selected hulls ranging from about 40-80%. Its more easily understood just by looking at the plot.
<br>

**Method 2**
Select a time interval that is ecologically relevant. We are interested in daily movement (e.g. night time foraging), so a 24hr cycle is OK - on the premise that points that are close together but more than 24hrs apart are not related. If you are thinking about longer temporal patterns (e.g. season), then you need to adjust the value accordingly. If you dont have a clue and are fishing for patterns then do this:

```{r}
lxy.plot.pt2ctr(cc.lxy)
```
<br>
and then do this:

```{r}
lxy.plot.sfinder(cc.lxy)
```
<br>
then do this:

```{r}
#note: 3600 = 1 hour (3600 seconds)
lxy.plot.sfinder(cc.lxy, delta.t=3600*c(12,24,36,48,54,60))
```
<br>
Both methods support an *s*=0.03 value at the scale of 24hrs. According to the manual these methods don't necessarily always converge. Apparently that is not an issue as the methods are extremely different. 
<br>


#### Create a new set of time selected NN

using *s*= 0.3 and retaining *k* = 25 (value used in the distance only method)

```{r}
cc.lxy <- lxy.nn.add(cc.lxy, s=0.03, k=25)
```

this adds another NN set to cc.lxy ie it includes it as another list. To view:
```{r}
summary(cc.lxy)
```
Note the huge difference in the rmax and amax values (perhaps better to use these methods than fixed k)
<br>


### Step3b - Alternate method to select *s*
<br>
Can also calculate *s* in the same way that calculated *k*. This next section follows the 
method to do this. I don't think its necessary as we have already used a decent method above but I 
will run through this method just to see if the choice is the same. 

```{r}
cc.lxy <- lxy.nn.add(cc.lxy, s=c(0.0003, 0.003, 0.03, 0.3), k=25)
```
```{r}
lxy.plot.mtdr(cc.lxy, k=10)
```

```{r}
lxy.plot.tspan(cc.lxy, k=10)
```

Comment from the tutorial "These methods still leave a great deal up to the researcher, which has its pros and cons, but at least you’ve got quite a few alternatives for selecting an ideal s value for your particular purposes". We’ll stick with our 0.03 value for now, but we’ll need to create a new lhs object using this parameter:

```{r}
cc.lhs.time <- lxy.lhs(cc.lxy, k=3*3:8, s=0.03)
```
<br>
Merge the hulls into isopleths

```{r}
cc.lhs.time <- lhs.iso.add(cc.lhs.time)
```
<br>
Plot the isopleths

```{r}
plot(cc.lhs.time, iso=TRUE, figs.per.page=6)
```
When I was going through these in R I changed the figs.per.page to =1 as its too hard to see things on the screen.
I'm not entirely sure that k=15 is the best but it is *better* than the other k's. I think maybe it might be a 
good idea to play with the other parameters *r* and *a*. 
<br>

Compare the with time version to the original distance only method

```{r distance only method - k}
cc.lhs.time.k15 <- lhs.select(cc.lhs.time, k=15)
plot(cc.lhs.k15, iso=TRUE, figs.per.page=1)
```
```{r time method - k}
plot(cc.lhs.time.k15, iso=TRUE, figs.per.page=1)
```

Save the time selected hullset to use with additional work if taking a break at this point.

```{r}
lhs.save(cc.lhs.time.k15, dir="../data")
```
<br>

#### Step 4 - Calc of hr area - Fixed k=15 method, *s*=0 and *S*=0.03

```{r calculation of area|dist only - k}
cc.isos <- isopleths(cc.lhs.k15)
cc.isos[[1]]@data
```


```{r calculation of area|time - k}
cc.time.isos <- isopleths(cc.lhs.time.k15)
cc.time.isos[[1]]@data
```


```{r}
cc.core <- cc.isos[[1]][ cc.isos[[1]][["iso.level"]]==0.5, ]
cc.hr <- cc.isos[[1]][ cc.isos[[1]][["iso.level"]]==0.95, ]

plot(cc.hr, border="blue")
plot(cc.core, border="red", add=T)
```

cc.time.isos <- isopleths(cc.lhs.time.k15)
cc.time.isos[[1]]@data


Plot calculation of area|time vis
```{r}
cc.time.core <- cc.time.isos[[1]][ cc.time.isos[[1]][["iso.level"]]==0.5, ]
cc.time.hr <- cc.time.isos[[1]][ cc.time.isos[[1]][["iso.level"]]==0.95, ]

plot(cc.time.hr, border="blue")
plot(cc.time.core, border="red", add=T)
```
<br>

## The 'a' method (Adaptive Method)
<br>
see p20 in the tlocoh_tutorial.pdf (in the help file)
<br>

Reasoning for using it:
The 'a' in a-method stands for adaptive, because this method is designed to reduce the number of neighbors used in areas where the points are thin and scattered. Neighbors are identified by summing up their cumulative distance from the parent point and stopping when you reach a. This may result in a many points being labeled as neighbors in a dense area (which is what you probably want), and just a few points in outlying areas (which is also what you want).

The workflow is the same as the k method, BUT deciding on a value of 'a' is not straightforward because:
1) a is a cumulative distance from the parent point to the nearest neighbors
2) if time is included, the 'distance' between points is the TSD space-time metric which is not a physical distance.

To assist in picking an appropriate value of 'a' the **auto.a** function is used. This computes the 'a' value such that p% of points get at least n nearest neighbours, where p and n are supplied by you.

So for example, if we like the results with k=15, we can use auto.a() to tell us the value of 'a' that will result in 98% of all points having 15 or more nearest neighbours.


```{r}
cc.a.lxy <- lxy.nn.add(cc.lxy, s=0.03, a=auto.a(nnn=15, ptp=0.98))
```
<br>
```{r}
summary(cc.a.lxy)
```

This summary output tells us that for *s*= 0.03, if *a* = 18286.1, that 98% of pts
will have at least 15 nn. 

You can now use this to set the range of *a* values to test to calculate the hullsets.
For example: could test *a* = 10000, 11000, ......20000, then view the isopleth plots
to see if happy or whether still need to fine tune things. This is really subjective,
but this is actually how its done.
<br>

#### Step 1 - Identify enough nn that each pt has enough nn identified for *a* = 20000

```{r}
cc.a.lxy <- lxy.nn.add(cc.a.lxy, s=0.03, a=21000)
```
<br>
```{r}
summary(cc.a.lxy)
```

#### Step 2 - Create a new hullset object using a values from 4000 to 20000.
<br>
At this point also add the isopleths; previously we did this as a seperate step

```{r}
cc.lhs.amixed <- lxy.lhs(cc.a.lxy, s=0.03, a=4:20*1000, iso.add=T)
```
<br>

#### Step 3 - Plot out the results

```{r}
plot(cc.lhs.amixed, hulls=TRUE,figs.per.page=6)
```
<br>

```{r}
plot(cc.lhs.amixed, iso=TRUE, figs.per.page=6)
```
<br>

#### Step 4 - Review the isopleth area and edge:area curves
<br>
to try an help with interpreting the which value of *a* is reasonable

```{r}
lhs.plot.isoarea(cc.lhs.amixed)
lhs.plot.isoear(cc.lhs.amixed)
```
<br>

This suggests that *a*= 15000 is pretty good

<br>


```{r}

plot(cc.lhs.amixed, hulls=T, a=15000, allpts=T, cex.allpts=0.1, col.allpts="gray10", ufipt=F)
plot(cc.lhs.amixed, iso=T, a=15000, allpts=T, cex.allpts=0.1, col.allpts="gray10", ufipt=F)

```
<br>

#### Step 5 - Calc of HR area


```{r }
# calculation of area|time|a method
cc.timea.isos <- isopleths(cc.lhs.amixed, a=20000)
cc.timea.isos[[1]]@data
```

The previous time fixed k method gave 50% as 26ha, 95% as 78ha
Here we have 32ha and 96ha


Calculation of area|time|a method with pts overlay
```{r}
cc.timea.core <- cc.timea.isos[[1]][ cc.timea.isos[[1]][["iso.level"]]==0.5, ]
cc.timea.hr <- cc.timea.isos[[1]][ cc.timea.isos[[1]][["iso.level"]]==0.95, ]

plot(cc.timea.hr, border="blue")
plot(cc.timea.core, border="red", add=T) 
plot(cc.lhs.amixed,a=15000, allpts=T, cex.allpts=0.1, col.allpts="gray10", ufipt=F, add=T)

```
<bw>

#### Step 6 - Generation of additional hull metrics
<bw>

##### *Elongation*
<br>

Generate the eccentricity of the bounding ellipsoids. This is used as a proxy of
elongation or directionality


```{r}
cc.lhs.amixed <- lhs.ellipses.add(cc.lhs.amixed)
```


```{r}
plot(cc.lhs.amixed, ellipses=T,figs.per.page=1)
```
Remember that according to the previous analysis that a=15000 is the plot that
is most reasonable

```{r}
summary(cc.lhs.amixed)
```




```{r}
cc.lhs.amixed <- lhs.iso.add(cc.lhs.amixed, sort.metric="ecc")
plot(cc.lhs.amixed, iso=T, iso.sort.metric="ecc")
plot(cc.lhs.amixed, a=15000, iso=T, iso.sort.metric="ecc") #just the a=15000 hullset
```
What this shows are the areas where cc was doing more directed movement - the red
areas.


##### *Time Use*
<br>
Revisitation - to each hull - the number of pts in the hull basically
Duration - to the hull - the amount of time spent in the hull

For example: Long duration might represent the importance of seasonal resources;
High revisitation rates may represent permanently available resources. But, high revisitation
and short duration may represent daily (or twice daily) trips to a water hole. What would 
a den look like then? ........would be inside core area...high revisitation and long duration?

We need to set a reasonable 'inter visit gap' (IVG). We are interested in a daily cycle (24hrs),
but so as not to lose behaviour that is 23hrs apart set the IVG at 12hrs. This is done in seconds.

```{r}
cc.lhs.amixed <- lhs.visit.add(cc.lhs.amixed, ivg=3600*12)
summary(cc.lhs.amixed)
```

nsv.43200 = the measure of revisitation and stands for number of separate visits for an inter-visit gap period of 43200 seconds.

mnlv.43200 = mean number of locations per visit, and is the measure of average duration.

```{r}
lhs.save(cc.lhs.amixed)  #nb. I move this RData file to the data folder manually
```

Next look at the various hull metrics

###### *Revisitation*
<br>

```{r}
hist(cc.lhs.amixed, a=15000, metric="nsv")
```
nb. there is a missing hull as 1pt is not included in the hull metric calculation i.e. it 
didnt fit the criteria for inclusion.

Basically this says that the majority of hulls were visited at a pretty high rate

To see what this looks like in real space plot the points:


```{r}
plot(cc.lhs.amixed,hpp=T, hpp.classify="nsv", ivg=3600*12, col.ramp="rainbow")

```

Make a zoomed version. aoi = area of interest. You have to put the plot call into the console and 
run it so that the plot appears in the 'PLots' window  and you can select the area of interest
by clicking the 'top left' and 'bottom right' to define the zoom area. 

You have to plot the next line from the console window (I have just told it to run a=15000), then 
run the aoi call:
plot(cc.lhs.amixed,hpp=T, hpp.classify="nsv", ivg=3600*12, col.ramp="rainbow") n.b. this plot all
a values, so you have to scroll through until you get the one of interest.

I have commented the line out at L637 as it interferes with the knit. Just uncomment to use
```{r}
# cc.aoi <- aoi()
```

```{r, 12hrs}
#plot(cc.lhs.amixed,hpp=T, hpp.classify="nsv", ivg=3600*12, col.ramp="rainbow", aoi=cc.aoi)
```
<br>


See if this looks much different if use an IVG of 20hrs

```{r}
cc.lhs.amixed20 <- lhs.visit.add(cc.lhs.amixed, ivg=3600*20)
summary(cc.lhs.amixed20)
```

```{r}
hist(cc.lhs.amixed20, a=15000, metric="nsv")
```

Well thats really interesting. 20hrs is way toooooooo long to. 12 hrs or maybe less(?) is suitable
for foxes. 


```{r, 20hrs}
plot(cc.lhs.amixed20,hpp=T, hpp.classify="nsv", ivg=3600*20, col.ramp="rainbow")
```


Extract out just the a=15000 hullset for the moment as having all the other ones
is distracting
```{r}
cc.lhs.a15000 <- lhs.select(cc.lhs.amixed, a = 15000, status = T)

```


have  a look at what visitation rate is by time of day. 

plot(cc.lhs.amixed,hpp=T, hpp.classify="nsv", ivg=3600*12, col.ramp="rainbow", aoi=cc.aoi)

```{r}
#plot(cc.lhs.amixed,hpp=T, hpp.classify="nsv", ivg=3600*12, col.ramp="rainbow", aoi=cc.aoi)
```

Make a zoomed version

Put the next line into the console so that the plot appears in the plot window 
>plot(cc.lhs.a15000,hpp=T, hpp.classify="dt.hour", ivg=3600*12, col.ramp = "rainbow")

run the next line in the console so that you can select the zoom area
>cc.aoi <- aoi()

Then re-run the plot call as usual including the aoi information

```{r}
#plot(cc.lhs.a15000,hpp=T, hpp.classify="dt.hour", ivg=3600*12, col.ramp = "rainbow", aoi = cc.aoi)
```
Definitely a time signature here. Would be interesting to play with the IVG and get a better
idea of the data to ID 'dens' or rest spots.

Though to be honest I think I may prefer recurse for this type of analysis. 



Or by month


```{r}
plot(cc.lhs.a15000,hpp=T, hpp.classify="dt.month", ivg=3600*12, col.ramp = "rainbow")
```
make a zoomed version of the mass of points

```{r}
#cc.aoi <- aoi()
```


```{r}
#plot(cc.lhs.a15000,hpp=T, hpp.classify="dt.month", ivg=3600*12, col.ramp = "rainbow", aoi = cc.aoi)
```

Doesnt show anything particularly interesting. 

Anyway, can plug in any metric you like from the below list to explore the data. 

However, alot of these metrics are calculated on the fly and not saved in the hull metrics file.



### Available Hulls Metrics - List.

There is another pdf that is interesting for hull metric calculations:

https://tlocoh.r-forge.r-project.org/tips/exploring_time_use_metrics.html


To save hull metrics as dataframes that can be used for other things see:

file:///C:/Users/20120252/Dropbox%20(Personal)/Statistics/R%20Vignettes/t-LoCoH/hull-metrics.nb.html
This also has instructions about how to calculate various metrics.

These are all the hull metrics available in this hullset (the list will only generate the
metrics that have been calculated  - so it may not be an exhaustive list)

hm.expr()  #use this call in the console
  Hull Metrics 
  dt           date of the parent point
  dt.month     month of the parent point
  dt.hour      hour of the day of the parent point
  tspan        time span of nearest neighbors
  area         area
  nnn          number of nearest neighbors
  nep          number of enclosed points
  ecc          eccentricity of the bounding ellipse, see lhs.ellipses.add
  par          perimeter:area ratio
  perim        perimeter
  nsv          visitation rate (requires 'ivg'), see lhs.visit.add
  nnsv         normalized visitation rate (requires 'ivg'), see lhs.visit.add
  mnlv         duration of visit (requires 'ivg'), see lhs.visit.add
  nmnlv        normalized duration of visit (requires 'ivg'), see lhs.visit.add
  nsr          revisitation rate (requires 'ta.min', 'ta.max'), see lhs.revisit.add
  pep          proportion of enclosed points (requires 'pep.var', 'pep.val'), see lhs.pep.add
  pep.mcol     proportion of enclosed points, see lhs.pep.add
  npep         proportion of enclosed points normalized by area (requires 'pep.var', 'pep.val'), see lhs.pep.add
  anv          ancillary variable (requires 'anv')
  scg.enc.mean avg speed of enclosed points
  scg.nn.mean  avg speed of nearest neighbors
  scg.enc.sd   stdev of the speed of enclosed points
  scg.nn.sd    stdev of the speed of nearest neighbors
  so.count     number of overlapping hulls (requires 'hs2'), see lhs.so.add
  so.dtmin     min time diff of overlapping hulls (requires 'hs2'), see lhs.so.add
  to.mcd       mean centroid distance of temporally overlapping hulls (requires 'hs2'), see lhs.to.add

```{r}
hull.tod.scatter <- lhs.plot.scatter(cc.lhs.a15000, x.axis="nsv", y.axis ="dt.hour", col="spiral", bg="black")
hull.tod.scatter
```


###### *Duration of visit*


```{r}
hist(cc.lhs.a15000, metric= "mnlv")
```

```{r}
plot(cc.lhs.a15000, hpp=T, hpp.classify="mnlv", col.ramp="rainbow")
```

Zoomed version

```{r}
#plot(cc.lhs.a15000, hpp=T, hpp.classify="mnlv", col.ramp="rainbow", aoi = cc.aoi)
```



Create a scatterplot of hull revisitation and duration


```{r}
hsp <- lhs.plot.scatter(cc.lhs.a15000, x="nsv", y="mnlv", col="spiral", bg="black")
```


```{r}
plot(cc.lhs.a15000, hpp=T, hsp=hsp, hpp.classify="hsp")
```


Create a scatterplot of time of day and duration


```{r}
toddur <- lhs.plot.scatter(cc.lhs.a15000, x="dt.hour", y="mnlv", col="spiral", bg="black")
```


```{r}
plot(cc.lhs.a15000, hpp=T, hsp=toddur, hpp.classify="hsp")
```


You can export all the data from the hull with lhs.exp.csv. Unfortunately this 
does not export the lat/long information or a bunch of other metrics that are calculated
on the fly. Below I have also exported the data as a
shapefile which includes this data. 

```{r}
lhs.exp.csv(cc.lhs.a15000, csv.save = T, dir = "../data", hm ="all", status = T)
```

Export the data as a shapefile

```{r}
lhs.exp.shp(cc.lhs.a15000, hpp = T, hulls = T, iso = T, dir = "../tlocohShapefiles")
```

<br>
<br>






## FOX - DB - example to sort out the script (Working of the 'k' method)

#### Apply posix format to time and reduce the dataframe down to required columns.

As far as I'm aware the time data is already in local time so no transformation required
```{r}
#fox.db$dt <- as.POSIXct(strptime(fox.db$DATETIME, format="%d/%m/%Y %H:%M"))

fox.db$dt <- as.POSIXct(fox.db$DATETIME, format="%d/%m/%Y %H:%M", tz="Australia/Perth")

db <- fox.db[,c("LONGITUDE","LATITUDE","dt","ANIMALID")]
#rename cols
colnames(db)[1:4] <- c("x","y","dt","id")
#check first 4 lines of the dataframe
db[1:4,]

```

<br>

### Step 1 - Prepare the data in t-LoCoH format and create lxy object

give x and y a projection
This creates the first of a series of new dataframes that are joined. Pretty clunky way to do it 
but this is what is required in this program

```{r}
#sub-df 1 latlong
db.sp.latlong <- SpatialPoints(db[ , c("x","y")], proj4string=CRS("+proj=longlat +ellps=WGS84"))
db.sp.utm <- spTransform(db.sp.latlong, CRS("+proj=utm +south +zone=50 +ellps=WGS84")) 
db.mat.utm <- coordinates(db.sp.utm)
tail(db.mat.utm)

#sub-df 2 local time - the data are already in this so just subset to follow naming format
db.local <- as.POSIXct(db$dt, tz="Australia/Perth")
local.tz <- "Australia/Perth"
db.localtime <- as.POSIXct(format(db.local, tz=local.tz), tz=local.tz)


#sub-df 3 id
db.id <- db[,c("id")]

#merge all the df in the correct tlocoh format and order 
db.lxy <- xyt.lxy(xy=db.mat.utm, dt=db.localtime, id="db", proj4string=CRS("+proj=utm +south +zone=50 +ellps=WGS84"))#, dup.dt.check=FALSE)

```
<br>

Explore the structure of the lxy object
```{r}
nrow(db.lxy$pts)
summary(db.lxy)
```
<br>

Plot out the movement trajectory
```{r}
plot(db.lxy)
```
<br>

Display the distribution of locations by date, step length, and sampling interval.
```{r}
hist(db.lxy)
```
<br>

Review the sampling frequency
```{r}
lxy.plot.freq(db.lxy, cp=T)
```
<br>

### Space use model - distance only (time not considered)

Construct a model of space-use without considering time (s=0). k=25 means that it is
considering the nearest 25 points to the parent point (at this stage its completely 
arbitrary). As we are not considering time these points are the nearest in space and as such 
may not necessarily be sequential. 
<br>

```{r}
db.lxy <- lxy.nn.add(db.lxy, s=0, k=25)
```

```{r}
summary(db.lxy)
```
<br>

Save the lxy object for later analysis (when look at the time stuff)
```{r}
lxy.save(db.lxy, dir="../data")
```
<br>

Make a kml to visualise the track on GoogleEarth so can get a feel for the animals movement.
This is easy but produces a pretty awful result. Doesn't appear to read the dt appropriately. 
Gives and enddate in 2021
Check our the t-locoh extension tutorial to see if there is a better way to do this.
```{r}
lxy.exp.kml(db.lxy, 'db.lxy.191121.kml',compress = FALSE, pt.scale = 0.25, path.lwd = 3)
```
<br>


### Step 2 - Hull construction

The building blocks of all T-LoCoH analyses are hulls, which are simply minimum convex polygons constructed around each point from a set of nearest neighbors. Since we’ve already identified 25 nearest neighbors for each point, we can create hulls with up to 25 nearest neighbors each. We will use the tlocoh::lxy.lhs command to create an lhs object, the next in our progression.
```{r}
db.lhs <- lxy.lhs(db.lxy, k=3*3:8, s=0)
```
<br>

What we are doing here is creating 6 different hullsets with k values of 9, 12, 15, 18, 21, and 24 (note we are still setting s=0 because we are not considering the temporal component yet). It is useful to create a selection of hullsets so that we can compare them and choose the optimal one for our purposes. The downside of creating all of these extra hullsets is that it may take a little while to run. Once it is finished, we can get an idea of what areas are included in our hullsets using the tlocoh::plot command again. This time, we will specify that we want to plot the hulls and we’ll add all of the plots to a single page for easier comparison.
<br>

```{r}
plot(db.lhs, hulls=TRUE, figs.per.page=6)
```
<br>

#### Create the isopleths
Isopleths are aggregations of hulls sorted in such a way as to reveal something about space use. The default settings for tlocoh::lhs.iso.add sorts hulls according to density, so the isopleths reflect the likelihood of occurrence, which is a proxy for intensity of use. Then we can plot these (using the iso=TRUE specification instead of hulls=TRUE) to see how they compare to one another and to the hullset plots.
```{r}
db.lhs <- lhs.iso.add(db.lhs)
```
<br>

```{r}
plot(db.lhs, iso=TRUE, figs.per.page=6)
```
<br>

```{r}

plot(db.lhs, iso=T, k=15, allpts=T, cex.allpts=0.1, col.allpts="gray10", ufipt=F)
```

Note: you can also produce the above plot without the pts. In this case just use:
plot(cc.lhs, iso=T, k=15, ufipt=F).
I originally ran this with k=18 which looked ok mapping this iso's but when I ran
the plots below it looks like k=15 might be better. 

<br>

Two other plots can be used to evaluate the choice of *k* value. The first is the isopleth area curves, which will plot the area included in a set of different isopleth levels (ranging from 0.15 to 0.95 by 0.10). We want to check these plots to make sure that there are no sharp jumps between k values that indicate that a relatively small change in k results in a large increase in included area (likely a false commission). To look at this plot, we use the tlocoh::lhs.plot.isoarea command:

```{r}
lhs.plot.isoarea(db.lhs)
```
<br>
There's a bit of a jump after 15.... 

Next - look at the edge to area ratio. We are looking to exclude k values that result in very high edge:area ratios, which are indicative of the Swiss cheese pattern (i.e., many small holes). This is particularly important at some of the isopleths associated with the core area (0.35, 0.45, 0.55) where we would expect relatively few holes.
<br>

```{r}
lhs.plot.isoear(db.lhs)
```

If the plots are too small in the RMarkdown window then put the code into the Console and 
view the plot in the plot window. Resize this area first so that the plot is nice and big.
Having run all the *k* values multiple time *k*=15 is actually the best. i.e. using a larger 
value of *k* doesnt really change how many of the grey dtps are included in the hulls.

Select this value for subsequent runs and save as an object
```{r}
db.lhs.k15 <- lhs.select(db.lhs, k=15)

lhs.save(db.lhs.k15, dir="../data")
```
<br>

### Step 3 - Incorporate Time

If doing this step in another session then you need to load the lxy and lhs RData files that you saved above. Use the following syntax:

load('./data/db.n562.2016-07-08.2016-08-02.lxy.01.RData')
load('./data/db.n562.s0.k15.iso.lhs.01.RData')


create a new nearest neighbor set with a non-zero s parameter. That is, we are now creating a UD that incorporates time. In the first plot there are points in the same general areas that are colour coded differently. This means that they were in the same area but at different times so these points are not temporally related. In the s=0 calculations above this is ignored and therefore is not ecologically very informative. 

Firstly, need to select a 'decent' *s* value. To do this pick an *s* value such that 40-80% of the hulls are ‘time-selected.’ 
<br>

#### Select *s*
<br>
**This is Method 1**
```{r}
db.lxy <- lxy.ptsh.add(db.lxy)
```

This creates a set of 200 sample points, each with 10 nearest neighbors. This algorithm goes through a set of different s values and determines *what proportion of hulls are time-selected* (ptsh). Though this is a somewhat stochastic process, we can see that *s* values between approximately 0.01 and 0.08 fall between proportions of time-selected hulls ranging from about 40-80%. Its more easily understood just by looking at the plot.
<br>

**Method 2**
Select a time interval that is ecologically relevant. We are interested in daily movement (e.g. night time foraging), so a 24hr cycle is OK - on the premise that points that are close together but more than 24hrs apart are not related. If you are thinking about longer temporal patterns (e.g. season), then you need to adjust the value accordingly. If you dont have a clue and are fishing for patterns then do this:

```{r}
lxy.plot.pt2ctr(db.lxy)
```
<br>
and then do this:

```{r}
lxy.plot.sfinder(db.lxy)
```
<br>
then do this:

```{r}
#note: 3600 = 1 hour (3600 seconds)
lxy.plot.sfinder(db.lxy, delta.t=3600*c(12,24,36,48,54,60))
```
<br>
Both methods support an *s*=0.03 value at the scale of 24hrs. According to the manual these methods don't necessarily always converge. Apparently that is not an issue as the methods are extremely different. 
<br>


#### Create a new set of time selected NN

using *s*= 0.6 (not really sure about this. Basing it on the first graph L 976, and retaining *k* = 25
(value used in the distance only method)

```{r}
db.lxy <- lxy.nn.add(db.lxy, s=0.06, k=25)
```

this adds another NN set to db.lxy ie it includes it as another list. To view:
```{r}
summary(db.lxy)
```
Note the huge difference in the rmax and amax values (perhaps better to use these methods than fixed k)
<br>


### Step3b - Alternate method to select *s*
<br>
Can also calculate *s* in the same way that calculated *k*. This next section follows the 
method to do this. I don't think its necessary as we have already used a decent method above but I 
will run through this method just to see if the choice is the same. 

```{r}
db.lxy <- lxy.nn.add(db.lxy, s=c(0.0006, 0.006, 0.06, 0.6), k=25)
```
```{r}
lxy.plot.mtdr(db.lxy, k=10)
```

```{r}
lxy.plot.tspan(db.lxy, k=10)
```

Comment from the tutorial "These methods still leave a great deal up to the researcher, which has its pros and cons, but at least you’ve got quite a few alternatives for selecting an ideal s value for your particular purposes". We’ll stick with our 0.06 value for now, but we’ll need to create a new lhs object using this parameter:

```{r}
db.lhs.time <- lxy.lhs(db.lxy, k=3*3:8, s=0.06)
```
<br>
Merge the hulls into isopleths

```{r}
db.lhs.time <- lhs.iso.add(db.lhs.time)
```
<br>
Plot the isopleths

```{r}
plot(db.lhs.time, iso=TRUE, figs.per.page=6)
```
When I was going through these in R I changed the figs.per.page to =1 as its too hard to see things on the screen.
I'm not entirely sure that k=15 is the best but it is *better* than the other k's. I think maybe it might be a good idea to play with the other parameters *r* and *a*. 
<br>

Compare with time version to the original distance only method

```{r}
db.lhs.time.k15 <- lhs.select(db.lhs.time, k=15) #distance only
plot(db.lhs.k15, iso=TRUE, figs.per.page=1)
```
```{r}
plot(db.lhs.time.k15, iso=TRUE, figs.per.page=1) #with time
```

Save the time selected hullset to use with additional work if taking a break at this point.

```{r}
#lhs.save(db.lhs.time.k15, dir="../data")
```
<br>

#### Step 4 - Calc of hr area - Fixed k=15 method, *s*=0 and *S*=0.06

```{r, calculation of area|dist only db}
db.isos <- isopleths(db.lhs.k15)
db.isos[[1]]@data
```


```{r, calculation of area|time db}
db.time.isos <- isopleths(db.lhs.time.k15)
db.time.isos[[1]]@data
```


```{r}
db.core <- db.isos[[1]][ db.isos[[1]][["iso.level"]]==0.5, ]
db.hr <- db.isos[[1]][ db.isos[[1]][["iso.level"]]==0.95, ]

plot(db.hr, border="blue")
plot(db.core, border="red", add=T)
```

db.time.isos <- isopleths(db.lhs.time.k15)
db.time.isos[[1]]@data


Plot calculation of area|time vis
```{r}
db.time.core <- db.time.isos[[1]][ db.time.isos[[1]][["iso.level"]]==0.5, ]
db.time.hr <- db.time.isos[[1]][ db.time.isos[[1]][["iso.level"]]==0.95, ]

plot(db.time.hr, border="blue")
plot(db.time.core, border="red", add=T)
```
<br>

## The 'a' method (Adaptive Method)
<br>
see p20 in the tlocoh_tutorial.pdf (in the help file)
<br>

Reasoning for using it:
The 'a' in a-method stands for adaptive, because this method is designed to reduce the number of neighbors used in areas where the points are thin and scattered. Neighbors are identified by summing up their cumulative distance from the parent point and stopping when you reach a. This may result in a many points being labeled as neighbors in a dense area (which is what you probably want), and just a few points in outlying areas (which is also what you want).

The workflow is the same as the k method, BUT deciding on a value of 'a' is not straightforward because:
1) a is a cumulative distance from the parent point to the nearest neighbors
2) if time is included, the 'distance' between points is the TSD space-time metric which is not a physical distance.

To assist in picking an appropriate value of 'a' the **auto.a** function is used. This computes the 'a' value such that p% of points get at least n nearest neighbours, where p and n are supplied by you.

So for example, if we like the results with k=15, we can use auto.a() to tell us the value of 'a' that will result in 98% of all points having 15 or more nearest neighbours.


```{r}
db.a.lxy <- lxy.nn.add(db.lxy, s=0.06, a=auto.a(nnn=15, ptp=0.98))
```
<br>
```{r}
summary(db.a.lxy)
```

This summary output tells us that for *s*= 0.06, if *a* = 21129.9, that 98% of pts
will have at least 15 nn. 

You can now use this to set the range of *a* values to test to calculate the hullsets.
For example: could test *a* = 12000, 13000, ......23000, then view the isopleth plots
to see if happy or whether still need to fine tune things. This is really subjective,
but this is actually how its done!
<br>

#### Step 1 - Identify enough nn that each pt has enough nn identified for *a* = 20000

```{r}
db.a.lxy <- lxy.nn.add(db.a.lxy, s=0.06, a=23000)
```
<br>
```{r}
summary(cc.a.lxy)
```

#### Step 2 - Create a new hullset object using a values from 8000 to 25000.
<br>
At this point also add the isopleths; previously we did this as a seperate step

```{r}
db.lhs.amixed <- lxy.lhs(db.a.lxy, s=0.06, a=8:25*1000, iso.add=T)
```
<br>

#### Step 3 - Plot out the results

```{r}
plot(db.lhs.amixed, hulls=TRUE,figs.per.page=6)
```
<br>

```{r}
plot(db.lhs.amixed, iso=TRUE, figs.per.page=6)
```
<br>

#### Step 4 - Review the isopleth area and edge:area curves
<br>
to try an help with interpreting the which value of *a* is reasonable

```{r}
lhs.plot.isoarea(db.lhs.amixed)
lhs.plot.isoear(db.lhs.amixed)
```
<br>

This suggests that *a*= 19000 should be used instead of a = 21000

<br>


```{r}

plot(db.lhs.amixed, hulls=T, a=19000, allpts=T, cex.allpts=0.1, col.allpts="gray10", ufipt=F)
plot(db.lhs.amixed, iso=T, a=19000, allpts=T, cex.allpts=0.1, col.allpts="gray10", ufipt=F)

```
<br>

#### Step 5 - Calc of HR area


```{r}
# calculation of area|time|a method
db.timea.isos <- isopleths(db.lhs.amixed, a=19000)
db.timea.isos[[1]]@data
```

The previous time fixed k method gave 50% as 7.5ha, 95% as 50.4ha
Here we have 49ha and 60ha

**Fill these data results into hr2.area1.xlsx in the atm project**



```{r}
#Calculation of area|time|a method with pts overlay
db.timea.core <- db.timea.isos[[1]][ db.timea.isos[[1]][["iso.level"]]==0.5, ]
db.timea.hr <- db.timea.isos[[1]][ db.timea.isos[[1]][["iso.level"]]==0.95, ]

plot(db.timea.hr, border="blue")
plot(db.timea.core, border="red", add=T) 
plot(db.lhs.amixed,a=19000, allpts=T, cex.allpts=0.1, col.allpts="gray10", ufipt=F, add=T)

```
<bw>







## FOX - ES - example to sort out the script (Working of the 'k' method)

#### Apply posix format to time and reduce the dataframe down to required columns.

As far as I'm aware the time data is already in local time so no transformation required
```{r}
#fox.db$dt <- as.POSIXct(strptime(fox.db$DATETIME, format="%d/%m/%Y %H:%M"))

fox.es$dt <- as.POSIXct(fox.es$DATETIME, format="%d/%m/%Y %H:%M", tz="Australia/Perth")

es <- fox.es[,c("LONGITUDE","LATITUDE","dt","ANIMALID")]
#rename cols
colnames(es)[1:4] <- c("x","y","dt","id")
#check first 4 lines of the dataframe
es[1:4,]

```

<br>

### Step 1 - Prepare the data in t-LoCoH format and create lxy object

give x and y a projection
This creates the first of a series of new dataframes that are joined. Pretty clunky way to do it 
but this is what is required in this program

```{r}
#sub-df 1 latlong
es.sp.latlong <- SpatialPoints(es[ , c("x","y")], proj4string=CRS("+proj=longlat +ellps=WGS84"))
es.sp.utm <- spTransform(es.sp.latlong, CRS("+proj=utm +south +zone=50 +ellps=WGS84")) 
es.mat.utm <- coordinates(es.sp.utm)
tail(es.mat.utm)

#sub-df 2 local time - the data are already in this so just subset to follow naming format
es.local <- as.POSIXct(es$dt, tz="Australia/Perth")
local.tz <- "Australia/Perth"
es.localtime <- as.POSIXct(format(es.local, tz=local.tz), tz=local.tz)


#sub-df 3 id
es.id <- es[,c("id")]

#merge all the df in the correct tlocoh format and order 
es.lxy <- xyt.lxy(xy=es.mat.utm, dt=es.localtime, id="es", proj4string=CRS("+proj=utm +south +zone=50 +ellps=WGS84"))#, dup.dt.check=FALSE)

```
<br>

Explore the structure of the lxy object
```{r}
nrow(es.lxy$pts)
summary(es.lxy)
```
<br>

Plot out the movement trajectory
```{r}
plot(es.lxy)
```
<br>

Display the distribution of locations by date, step length, and sampling interval.
```{r}
hist(es.lxy)
```
<br>

Review the sampling frequency
```{r}
lxy.plot.freq(es.lxy, cp=T)
```
<br>

### Space use model - distance only (time not considered)

Construct a model of space-use without considering time (s=0). k=25 means that it is
considering the nearest 25 points to the parent point (at this stage its completely 
arbitrary). As we are not considering time these points are the nearest in space and as such 
may not necessarily be sequential. 
<br>

```{r}
es.lxy <- lxy.nn.add(es.lxy, s=0, k=25)
```

```{r}
summary(es.lxy)
```
<br>

Save the lxy object for later analysis (when look at the time stuff)
```{r}
lxy.save(es.lxy, dir="../data")
```
<br>

Make a kml to visualise the track on GoogleEarth so can get a feel for the animals movement.
This is easy but produces a pretty awful result. Doesn't appear to read the dt appropriately. 
Gives and enddate in 2021
Check our the t-locoh extension tutorial to see if there is a better way to do this.
For some reason I cant get this to save in a folder so it will go into the script folder by default.
```{r}
lxy.exp.kml(es.lxy, 'es.lxy.221121.kml',compress = FALSE, pt.scale = 0.25, path.lwd = 3)
```
<br>


### Step 2 - Hull construction

The building blocks of all T-LoCoH analyses are hulls, which are simply minimum convex polygons constructed around each point from a set of nearest neighbors. Since we’ve already identified 25 nearest neighbors for each point, we can create hulls with up to 25 nearest neighbors each. We will use the tlocoh::lxy.lhs command to create an lhs object, the next in our progression.
```{r}
es.lhs <- lxy.lhs(es.lxy, k=3*3:8, s=0)
```
<br>

What we are doing here is creating 6 different hullsets with k values of 9, 12, 15, 18, 21, and 24 (note we are still setting s=0 because we are not considering the temporal component yet). It is useful to create a selection of hullsets so that we can compare them and choose the optimal one for our purposes. The downside of creating all of these extra hullsets is that it may take a little while to run. Once it is finished, we can get an idea of what areas are included in our hullsets using the tlocoh::plot command again. This time, we will specify that we want to plot the hulls and we’ll add all of the plots to a single page|or loads of pages(!) for easier comparison.
<br>

```{r}
plot(es.lhs, hulls=TRUE, figs.per.page=1) #if want multiple plots/page then increase No. ie. page = 6
```
<br>

#### Create the isopleths
Isopleths are aggregations of hulls sorted in such a way as to reveal something about space use. The default settings for tlocoh::lhs.iso.add sorts hulls according to density, so the isopleths reflect the likelihood of occurrence, which is a proxy for intensity of use. Then we can plot these (using the iso=TRUE specification instead of hulls=TRUE) to see how they compare to one another and to the hullset plots.
```{r}
es.lhs <- lhs.iso.add(es.lhs)
```
<br>

```{r}
plot(es.lhs, iso=TRUE, figs.per.page=1)
```
<br>

```{r}

plot(es.lhs, iso=T, k=21, allpts=T, cex.allpts=0.1, col.allpts="gray80", ufipt=F)
```

Note: you can also produce the above plot without the pts. In this case just use:
plot(es.lhs, iso=T, k=24, ufipt=F).
######ignore - I originally ran this with k=18 which looked ok mapping this iso's but when I ran
######ignore - the plots below it looks like k=15 might be better. 

<br>

Two other plots can be used to evaluate the choice of *k* value. The first is the isopleth area curves, which will plot the area included in a set of different isopleth levels (ranging from 0.15 to 0.95 by 0.10). We want to check these plots to make sure that there are no sharp jumps between k values that indicate that a relatively small change in k results in a large increase in included area (likely a false commission). To look at this plot, we use the tlocoh::lhs.plot.isoarea command:

```{r}
lhs.plot.isoarea(es.lhs)
```
<br>
There's a bit of a jump after 15.... 

Next - look at the edge to area ratio. We are looking to exclude k values that result in very high edge:area ratios, which are indicative of the Swiss cheese pattern (i.e., many small holes). This is particularly important at some of the isopleths associated with the core area (0.35, 0.45, 0.55) where we would expect relatively few holes.
<br>

```{r}
lhs.plot.isoear(es.lhs)
```

If the plots are too small in the RMarkdown window then put the code into the Console and 
view the plot in the plot window. Resize this area first so that the plot is nice and big.
Having run all the *k* values multiple times *k*=18 is actually the best. i.e. using a larger 
value of *k* doesnt really change how many of the grey dtps are included in the hulls.

Select this value for subsequent runs and save as an object
```{r}
es.lhs.k18 <- lhs.select(es.lhs, k=18)

lhs.save(es.lhs.k18, dir="../data")
```
<br>

### Step 3 - Incorporate Time

If doing this step in another session then you need to load the lxy and lhs RData files that you saved above. Use the following syntax:

load('./data/es.n1873.2016-01-15.2016-03-15.lxy.03.RData') # es.lxy
load('./data/es.n1873.s0.k18.iso.lhs.02.RData')  # es.lhs.k18


create a new nearest neighbor set with a non-zero s parameter. That is, we are now creating a UD that incorporates time. In the first plot there are points in the same general areas that are colour coded differently. This means that they were in the same area but at different times so these points are not temporally related. In the s=0 calculations above this is ignored and therefore is not ecologically very informative. 

Firstly, need to select a 'decent' *s* value. To do this pick an *s* value such that 40-80% of the hulls are ‘time-selected.’ 
<br>

#### Select *s*
<br>
**This is Method 1**
```{r}
es.lxy <- lxy.ptsh.add(es.lxy)
```

This creates a set of 200 sample points, each with 10 nearest neighbors. This algorithm goes through a set of different s values and determines *what proportion of hulls are time-selected* (ptsh). Though this is a somewhat stochastic process, we can see that *s* values between approximately 0.006 and 0.012 fall between proportions of time-selected hulls ranging from about 40-80%. Its more easily understood just by looking at the plot.
<br>

**Method 2**
Select a time interval that is ecologically relevant. We are interested in daily movement (e.g. night time foraging), so a 24hr cycle is OK - on the premise that points that are close together but more than 24hrs apart are not related. If you are thinking about longer temporal patterns (e.g. season), then you need to adjust the value accordingly. If you dont have a clue and are fishing for patterns then do this:

```{r}
lxy.plot.pt2ctr(es.lxy)
```
<br>
and then do this:

```{r}
lxy.plot.sfinder(es.lxy)
```
<br>
then do this:

```{r}
#note: 3600 = 1 hour (3600 seconds)
lxy.plot.sfinder(es.lxy, delta.t=3600*c(12,24,36,48,54,60))
```
<br>
Both methods support an *s*=0.0012 value at the scale of 24hrs. According to the manual these methods don't necessarily always converge. Apparently that is not an issue as the methods are extremely different. 
<br>


#### Create a new set of time selected NN

using *s*= 0.0012 (not really sure about this. Basing it on the the average sort of result among graphs, and retaining *k* = 25
(value used in the distance only method)

```{r}
es.lxy <- lxy.nn.add(es.lxy, s=0.0012, k=18)
```

this adds another NN set to db.lxy ie it includes it as another list. To view:
```{r}
summary(es.lxy)
```
Note the huge difference in the rmax and amax values (perhaps better to use these methods than fixed k)
<br>

**At this stage selecting k=18 and s=0.0012**



### Step3b - Alternate method to select *s*
<br>
Can also calculate *s* in the same way that calculated *k*. This next section follows the 
method to do this. I don't think its necessary as we have already used a decent method above but I 
will run through this method just to see if the choice is the same. 

```{r}
es.lxy <- lxy.nn.add(es.lxy, s=c(0.0001, 0.001, 0.01, 0.1), k=18)
```
```{r}
lxy.plot.mtdr(es.lxy, k=18)
```

```{r}
lxy.plot.tspan(es.lxy, k=18)
```

Comment from the tutorial "These methods still leave a great deal up to the researcher, which has its pros and cons, but at least you’ve got quite a few alternatives for selecting an ideal s value for your particular purposes". We’ll stick with our 0.0012 value for now, but we’ll need to create a new lhs object using this parameter:

```{r}
es.lhs.time <- lxy.lhs(es.lxy, k=3*3:8, s=0.0012)
```
<br>
Merge the hulls into isopleths

```{r}
es.lhs.time <- lhs.iso.add(es.lhs.time)
```
<br>
Plot the isopleths

```{r}
plot(es.lhs.time, iso=TRUE, figs.per.page=1)
```
When I was going through these in R I changed the figs.per.page to =1 as its too hard to see things on the screen.
I'm not entirely sure that k=15 is the best but it is *better* than the other k's. I think maybe it might be a good idea to play with the other parameters *r* and *a*. 
<br>

Compare with time version to the original distance only method

```{r}
# distance only method
plot(es.lhs.k18, iso=TRUE, figs.per.page=1)
```
```{r}
# time method
es.lhs.time.k18 <- lhs.select(es.lhs.time, k=18)
plot(es.lhs.time.k18, iso=TRUE, figs.per.page=1)
```

Save the time selected hullset to use with additional work if taking a break at this point.

```{r}
lhs.save(es.lhs.time.k18, dir="../data")
```
<br>

#### Step 4 - Calc of hr area - Fixed k=18 method, *s*=0 and *S*=0.0012

```{r }
# calculation of area|dist only
es.isos <- isopleths(es.lhs.k18)
es.isos[[1]]@data
```



```{r}
# calculation of area|time
es.time.isos <- isopleths(es.lhs.time.k18)
es.time.isos[[1]]@data
```


```{r}
es.core <- es.isos[[1]][ es.isos[[1]][["iso.level"]]==0.5, ]
es.hr <- es.isos[[1]][ es.isos[[1]][["iso.level"]]==0.95, ]

plot(es.hr, border="blue")
plot(es.core, border="red", add=T)
```

es.time.isos <- isopleths(es.lhs.time.k15)
es.time.isos[[1]]@data


Plot calculation of area|time vis
```{r}
es.time.core <- es.time.isos[[1]][ es.time.isos[[1]][["iso.level"]]==0.5, ]
es.time.hr <- es.time.isos[[1]][ es.time.isos[[1]][["iso.level"]]==0.95, ]

plot(es.time.hr, border="blue")
plot(es.time.core, border="red", add=T)
```
<br>

## The 'a' method (Adaptive Method)
<br>
see p20 in the tlocoh_tutorial.pdf (in the help file)
<br>

Reasoning for using it:
The 'a' in a-method stands for adaptive, because this method is designed to reduce the number of neighbors used in areas where the points are thin and scattered. Neighbors are identified by summing up their cumulative distance from the parent point and stopping when you reach a. This may result in a many points being labeled as neighbors in a dense area (which is what you probably want), and just a few points in outlying areas (which is also what you want).

The workflow is the same as the k method, BUT deciding on a value of 'a' is not straightforward because:
1) a is a cumulative distance from the parent point to the nearest neighbors
2) if time is included, the 'distance' between points is the TSD space-time metric which is not a physical distance.

To assist in picking an appropriate value of 'a' the **auto.a** function is used. This computes the 'a' value such that p% of points get at least n nearest neighbours, where p and n are supplied by you.

So for example, if we like the results with k=15, we can use auto.a() to tell us the value of 'a' that will result in 98% of all points having 15 or more nearest neighbours.


```{r}
es.a.lxy <- lxy.nn.add(es.lxy, s=0.0012, a=auto.a(nnn=18, ptp=0.98))
```
<br>
```{r}
summary(es.a.lxy)
```

This summary output tells us that for *s*= 0.0012, if *a* = 1988.2, that 98% of pts
will have at least 18 nn. 

You can now use this to set the range of *a* values to test to calculate the hullsets.
For example: could test *a* = 1200, 1300, ......2400, then view the isopleth plots
to see if happy or whether still need to fine tune things. This is really subjective,
but this is actually how its done!
<br>

#### Step 1 - Identify enough nn that each pt has enough nn identified for *a* = 1988

```{r}
es.a.lxy <- lxy.nn.add(es.a.lxy, s=0.0012, a=2400)
```
<br>
```{r}
summary(es.a.lxy)
```

#### Step 2 - Create a new hullset object using a values from 1200 to 2400.
<br>
At this point also add the isopleths; previously we did this as a seperate step

```{r}
es.lhs.amixed <- lxy.lhs(es.a.lxy, s=0.0012, a=12:24*100, iso.add=T)
```
<br>

#### Step 3 - Plot out the results

```{r}
plot(es.lhs.amixed, hulls=TRUE,figs.per.page=6)
```
<br>

```{r}
plot(es.lhs.amixed, iso=TRUE, figs.per.page=6)
```
<br>

#### Step 4 - Review the isopleth area and edge:area curves
<br>
to try an help with interpreting the which value of *a* is reasonable

```{r}
lhs.plot.isoarea(es.lhs.amixed)
lhs.plot.isoear(es.lhs.amixed)
```
<br>

This suggests that *a*= 1988.2 is probably OK so I will use a = 2000

<br>


```{r}

plot(es.lhs.amixed, hulls=T, a=2000, allpts=T, cex.allpts=0.1, col.allpts="gray10", ufipt=F)
plot(es.lhs.amixed, iso=T, a=2000, allpts=T, cex.allpts=0.1, col.allpts="gray10", ufipt=F)

```
<br>

#### Step 5 - Calc of HR area


```{r}
# calculation of area|time|a method
es.timea.isos <- isopleths(es.lhs.amixed, a=2000)
es.timea.isos[[1]]@data
```

The previous time fixed k method gave 50% as 7.5ha, 95% as 50.4ha
Here we have 49ha and 60ha

**Fill these data results into hr2.area1.xlsx in the atm project**


Calculation of area|time|a method with pts overlay
```{r}
es.timea.core <- es.timea.isos[[1]][ es.timea.isos[[1]][["iso.level"]]==0.5, ]
es.timea.hr <- es.timea.isos[[1]][ es.timea.isos[[1]][["iso.level"]]==0.95, ]


plot(es.timea.hr, border="blue")
plot(es.lhs.amixed,a=2000, allpts=T, cex.allpts=0.1, col.allpts="gray90", ufipt=F, add=T)
plot(es.timea.core, border="red", add=T)
```
<bw>



## FOX - HX 

#### Apply posix format to time and reduce the dataframe down to required columns.

As far as I'm aware the time data is already in local time so no transformation required
```{r}
#fox.db$dt <- as.POSIXct(strptime(fox.db$DATETIME, format="%d/%m/%Y %H:%M"))

fox.hx$dt <- as.POSIXct(fox.hx$DATETIME, format="%d/%m/%Y %H:%M", tz="Australia/Perth")

hx <- fox.hx[,c("LONGITUDE","LATITUDE","dt","ANIMALID")]
#rename cols
colnames(hx)[1:4] <- c("x","y","dt","id")
#check first 4 linhx of the dataframe
hx[1:4,]

```

<br>

### Step 1 - Prepare the data in t-LoCoH format and create lxy object

give x and y a projection
This creates the first of a series of new dataframes that are joined. Pretty clunky way to do it 
but this is what is required in this program

```{r}
#sub-df 1 latlong
hx.sp.latlong <- SpatialPoints(hx[ , c("x","y")], proj4string=CRS("+proj=longlat +ellps=WGS84"))
hx.sp.utm <- spTransform(hx.sp.latlong, CRS("+proj=utm +south +zone=50 +ellps=WGS84")) 
hx.mat.utm <- coordinates(hx.sp.utm)
tail(hx.mat.utm)

#sub-df 2 local time - the data are already in this so just subset to follow naming format
hx.local <- as.POSIXct(hx$dt, tz="Australia/Perth")
local.tz <- "Australia/Perth"
hx.localtime <- as.POSIXct(format(hx.local, tz=local.tz), tz=local.tz)


#sub-df 3 id
hx.id <- hx[,c("id")]

#merge all the df in the correct tlocoh format and order 
hx.lxy <- xyt.lxy(xy=hx.mat.utm, dt=hx.localtime, id="hx", proj4string=CRS("+proj=utm +south +zone=50 +ellps=WGS84"))#, dup.dt.check=FALSE)

```
<br>

Explore the structure of the lxy object
```{r}
nrow(hx.lxy$pts)
summary(hx.lxy)
```
<br>

Plot out the movement trajectory
```{r}
plot(hx.lxy)
```
<br>

Display the distribution of locations by date, step length, and sampling interval.
```{r}
hist(hx.lxy)
```
<br>

Review the sampling frequency
```{r}
lxy.plot.freq(hx.lxy, cp=T)
```
<br>

### Space use model - distance only (time not considered)

Construct a model of space-use without considering time (s=0). k=25 means that it is
considering the nearest 25 points to the parent point (at this stage its completely 
arbitrary). As we are not considering time these points are the nearest in space and as such 
may not necessarily be sequential. 
<br>

```{r}
hx.lxy <- lxy.nn.add(hx.lxy, s=0, k=25)
```

```{r}
summary(hx.lxy)
```
<br>

Save the lxy object for later analysis (when look at the time stuff)
```{r}
lxy.save(hx.lxy, dir="../data")
```
<br>

Make a kml to visualise the track on GoogleEarth so can get a feel for the animals movement.
This is easy but produces a pretty awful result. Doesn't appear to read the dt appropriately. 
Gives and enddate in 2021
Check our the t-locoh extension tutorial to see if there is a better way to do this.
For some reason I cant get this to save in a folder so it will go into the script folder by default.
```{r}
lxy.exp.kml(hx.lxy, 'hx.lxy.221121.kml',compress = FALSE, pt.scale = 0.25, path.lwd = 3)
```
<br>



### Step 2 - Hull construction

The building blocks of all T-LoCoH analyses are hulls, which are simply minimum convex polygons constructed around each point from a set of nearest neighbors. Since we’ve already identified 25 nearest neighbors for each point, we can create hulls with up to 25 nearest neighbors each. We will use the tlocoh::lxy.lhs command to create an lhs object, the next in our progression.
```{r}
hx.lhs <- lxy.lhs(hx.lxy, k=3*3:8, s=0)
```
<br>

What we are doing here is creating 6 different hullsets with k values of 9, 12, 15, 18, 21, and 24 (note we are still setting s=0 because we are not considering the temporal component yet). It is useful to create a selection of hullsets so that we can compare them and choose the optimal one for our purposes. The downside of creating all of these extra hullsets is that it may take a little while to run. Once it is finished, we can get an idea of what areas are included in our hullsets using the tlocoh::plot command again. This time, we will specify that we want to plot the hulls and we’ll add all of the plots to a single page|or loads of pages(!) for easier comparison.
<br>

```{r}
plot(hx.lhs, hulls=TRUE, figs.per.page=1) #if want multiple plots/page then increase No. ie. page = 6
```
<br>

#### Create the isopleths
Isopleths are aggregations of hulls sorted in such a way as to reveal something about space use. The default settings for tlocoh::lhs.iso.add sorts hulls according to density, so the isopleths reflect the likelihood of occurrence, which is a proxy for intensity of use. Then we can plot these (using the iso=TRUE specification instead of hulls=TRUE) to see how they compare to one another and to the hullset plots.
```{r}
hx.lhs <- lhs.iso.add(hx.lhs)
```
<br>

```{r}
plot(hx.lhs, iso=TRUE, figs.per.page=1)
```
<br>

```{r}

plot(hx.lhs, iso=T, k=21, allpts=T, cex.allpts=0.1, col.allpts="gray80", ufipt=F)
```

Note: you can also produce the above plot without the pts. In this case just use:
plot(es.lhs, iso=T, k=24, ufipt=F).
######ignore - I originally ran this with k=18 which looked ok mapping this iso's but when I ran
######ignore - the plots below it looks like k=15 might be better. 

<br>

Two other plots can be used to evaluate the choice of *k* value. The first is the isopleth area curves, which will plot the area included in a set of different isopleth levels (ranging from 0.15 to 0.95 by 0.10). We want to check these plots to make sure that there are no sharp jumps between k values that indicate that a relatively small change in k results in a large increase in included area (likely a false commission). To look at this plot, we use the tlocoh::lhs.plot.isoarea command:

```{r}
lhs.plot.isoarea(hx.lhs)
```
<br>
There's a bit of a jump after 15.... 

Next - look at the edge to area ratio. We are looking to exclude k values that result in very high edge:area ratios, which are indicative of the Swiss cheese pattern (i.e., many small holes). This is particularly important at some of the isopleths associated with the core area (0.35, 0.45, 0.55) where we would expect relatively few holes.
<br>

```{r}
lhs.plot.isoear(hx.lhs)
```

If the plots are too small in the RMarkdown window then put the code into the Console and 
view the plot in the plot window. Resize this area first so that the plot is nice and big.
Having run all the *k* values multiple times *k*=15 is actually the best. i.e. using a larger 
value of *k* doesnt really change how many of the grey dtps are included in the hulls.

Select this value for subsequent runs and save as an object
```{r}
hx.lhs.k15 <- lhs.select(hx.lhs, k=15)

lhs.save(hx.lhs.k15, dir="../data")
```
<br>

### Step 3 - Incorporate Time

If doing this step in another session then you need to load the lxy and lhs RData files that you saved above. Use the following syntax:

load('./data/es.n1873.2016-01-15.2016-03-15.lxy.03.RData') # es.lxy #change to hx
load('./data/es.n1873.s0.k18.iso.lhs.02.RData')  # es.lhs.k18       #change to hx


create a new nearest neighbor set with a non-zero s parameter. That is, we are now creating a UD that incorporates time. In the first plot there are points in the same general areas that are colour coded differently. This means that they were in the same area but at different times so these points are not temporally related. In the s=0 calculations above this is ignored and therefore is not ecologically very informative. 

Firstly, need to select a 'decent' *s* value. To do this pick an *s* value such that 40-80% of the hulls are ‘time-selected.’ 
<br>

#### Select *s*
<br>
**This is Method 1**
```{r}
hx.lxy <- lxy.ptsh.add(hx.lxy)
```

This creates a set of 200 sample points, each with 10 nearest neighbors. This algorithm goes through a set of different s values and determines *what proportion of hulls are time-selected* (ptsh). Though this is a somewhat stochastic process, we can see that *s* values between approximately 0.01 and 0.05 fall between proportions of time-selected hulls ranging from about 40-80%. Its more easily understood just by looking at the plot.
<br>

**Method 2**
Select a time interval that is ecologically relevant. We are interested in daily movement (e.g. night time foraging), so a 24hr cycle is OK - on the premise that points that are close together but more than 24hrs apart are not related. If you are thinking about longer temporal patterns (e.g. season), then you need to adjust the value accordingly. If you dont have a clue and are fishing for patterns then do this:

```{r}
lxy.plot.pt2ctr(hx.lxy)
```
<br>
and then do this:

```{r}
lxy.plot.sfinder(hx.lxy)
```
<br>
then do this:

```{r}
#note: 3600 = 1 hour (3600 seconds)
lxy.plot.sfinder(hx.lxy, delta.t=3600*c(12,24,36,48,54,60))
```
<br>
Both methods support an *s*=0.01 value at the scale of 24hrs. According to the manual these methods don't necessarily always converge. Apparently that is not an issue as the methods are extremely different. 
<br>


#### Create a new set of time selected NN

using *s*= 0.01 (actually the range was 0.01 - 0.05.....so maybe run a series of these, and retaining *k* = 25 (value used in the distance only method)

```{r}
hx.lxy <- lxy.nn.add(hx.lxy, s=0.01, k=25)
```

this adds another NN set to hx.lxy ie it includes it as another list. To view:
```{r}
summary(hx.lxy)
```
Note the huge difference in the rmax and amax values (perhaps better to use these methods than fixed k)
<br>

**At this stage selecting k=25 and s=0.01**



### Step3b - Alternate method to select *s*
<br>
Can also calculate *s* in the same way that calculated *k*. This next section follows the 
method to do this. I don't think its necessary as we have already used a decent method above but I 
will run through this method just to see if the choice is the same. 

```{r}
hx.lxy <- lxy.nn.add(hx.lxy, s=c(0.0001, 0.001, 0.01, 0.1), k=25)
```
```{r}
lxy.plot.mtdr(hx.lxy, k=25)
```

```{r}
lxy.plot.tspan(hx.lxy, k=25)
```

Comment from the tutorial "These methods still leave a great deal up to the researcher, which has its pros and cons, but at least you’ve got quite a few alternatives for selecting an ideal s value for your particular purposes". We’ll stick with our 0.0012 value for now, but we’ll need to create a new lhs object using this parameter:

```{r}
hx.lhs.time <- lxy.lhs(hx.lxy, k=3*3:8, s=0.01)
```
<br>
Merge the hulls into isopleths

```{r}
hx.lhs.time <- lhs.iso.add(hx.lhs.time)
```
<br>
Plot the isopleths

```{r}
plot(hx.lhs.time, iso=TRUE, figs.per.page=1)
```
When I was going through these in R I changed the figs.per.page to =1 as its too hard to see things on the screen.
I'm not entirely sure that k=15 is the best but it is *better* than the other k's. I think maybe it might be a good idea to play with the other parameters *r* and *a*. 
<br>

Compare with time version to the original distance only method

```{r}
# distance only method
plot(hx.lhs.k15, iso=TRUE, figs.per.page=1)
```
```{r}
# time method
hx.lhs.time.k15 <- lhs.select(hx.lhs.time, k=15)
plot(hx.lhs.time.k15, iso=TRUE, figs.per.page=1)
```

Save the time selected hullset to use with additional work if taking a break at this point.

```{r}
lhs.save(hx.lhs.time.k15, dir="../data")
```
<br>

#### Step 4 - Calc of hr area - Fixed k=15 method, *s*=0 and *S*=0.01

```{r}
# calculation of area|dist only
hx.isos <- isopleths(hx.lhs.k15)
hx.isos[[1]]@data
```



```{r}
# calculation of area|time
hx.time.isos <- isopleths(hx.lhs.time.k15)
hx.time.isos[[1]]@data
```


```{r}
hx.core <- hx.isos[[1]][ hx.isos[[1]][["iso.level"]]==0.5, ]
hx.hr <- hx.isos[[1]][ hx.isos[[1]][["iso.level"]]==0.95, ]

plot(hx.hr, border="blue")
plot(hx.core, border="red", add=T)
```

es.time.isos <- isopleths(es.lhs.time.k15)
es.time.isos[[1]]@data


Plot calculation of area|time vis
```{r}
hx.time.core <- hx.time.isos[[1]][ hx.time.isos[[1]][["iso.level"]]==0.5, ]
hx.time.hr <- hx.time.isos[[1]][ hx.time.isos[[1]][["iso.level"]]==0.95, ]

plot(hx.time.hr, border="blue")
plot(hx.time.core, border="red", add=T)
```
<br>

## The 'a' method (Adaptive Method)
<br>
see p20 in the tlocoh_tutorial.pdf (in the help file)
<br>

Reasoning for using it:
The 'a' in a-method stands for adaptive, because this method is designed to reduce the number of neighbours used in areas where the points are thin and scattered. Neighbours are identified by summing up their cumulative distance from the parent point and stopping when you reach a. This may result in a many points being labelled as neighbours in a dense area (which is what you probably want), and just a few points in outlying areas (which is also what you want).

The workflow is the same as the k method, BUT deciding on a value of 'a' is not straightforward because:
1) a is a cumulative distance from the parent point to the nearest neighbors
2) if time is included, the 'distance' between points is the TSD space-time metric which is not a physical distance.

To assist in picking an appropriate value of 'a' the **auto.a** function is used. This computes the 'a' value such that p% of points get at least n nearest neighbours, where p and n are supplied by you.

So for example, if we like the results with k=15, we can use auto.a() to tell us the value of 'a' that will result in 98% of all points having 15 or more nearest neighbours.


```{r}
hx.a.lxy <- lxy.nn.add(hx.lxy, s=0.01, a=auto.a(nnn=15, ptp=0.98))
```
<br>
```{r}
summary(hx.a.lxy)
```

This summary output tells us that for *s*= 0.01, if *a* = 8258, that 98% of pts
will have at least 18 nn. 

You can now use this to set the range of *a* values to test to calculate the hullsets.
For example: could test *a* = 6000, 7000, ......12000, then view the isopleth plots
to see if happy or whether still need to fine tune things. This is really subjective,
but this is actually how its done!
<br>

#### Step 1 - Identify enough nn that each pt has enough nn identified for *a* = 8258

```{r}
hx.a.lxy <- lxy.nn.add(hx.a.lxy, s=0.01, a=12000)
```
<br>
```{r}
summary(hx.a.lxy)
```

#### Step 2 - Create a new hullset object using a values from 1200 to 2400.
<br>
At this point also add the isopleths; previously we did this as a seperate step

```{r}
hx.lhs.amixed <- lxy.lhs(hx.a.lxy, s=0.01, a=6:12*1000, iso.add=T)
```
<br>

#### Step 3 - Plot out the results

```{r}
plot(hx.lhs.amixed, hulls=TRUE,figs.per.page=6)
```
<br>

```{r}
plot(hx.lhs.amixed, iso=TRUE, figs.per.page=6)
```
<br>

#### Step 4 - Review the isopleth area and edge:area curves
<br>
to try an help with interpreting which value of *a* is reasonable

```{r}
lhs.plot.isoarea(hx.lhs.amixed)
lhs.plot.isoear(hx.lhs.amixed)
```
<br>

This suggests that *a*= 8000 is probably OK 

<br>


```{r}

plot(hx.lhs.amixed, hulls=T, a=8000, allpts=T, cex.allpts=0.1, col.allpts="gray10", ufipt=F)
plot(hx.lhs.amixed, iso=T, a=8000, allpts=T, cex.allpts=0.1, col.allpts="gray10", ufipt=F)

```
<br>

#### Step 5 - Calc of HR area


```{r}
# calculation of area|time|a method
hx.timea.isos <- isopleths(hx.lhs.amixed, a=8000)
hx.timea.isos[[1]]@data
```

The previous time fixed k method gave 50% as 6.9ha, 95% as 82.9ha
Here we have 43.8ha and 147ha

**Fill these data results into hr2.area1.xlsx in the atm project**


Calculation of area|time|a method with pts overlay
```{r}
hx.timea.core <- hx.timea.isos[[1]][ hx.timea.isos[[1]][["iso.level"]]==0.5, ]
hx.timea.hr <- hx.timea.isos[[1]][ hx.timea.isos[[1]][["iso.level"]]==0.95, ]


plot(hx.timea.hr, border="blue")
plot(hx.lhs.amixed,a=8000, allpts=T, cex.allpts=0.1, col.allpts="gray90", ufipt=F, add=T)
plot(hx.timea.core, border="red", add=T)
```
<bw>



## FOX - FJ 

#### Apply posix format to time and reduce the dataframe down to required columns.

As far as I'm aware the time data is already in local time so no transformation required
```{r}
#fox.db$dt <- as.POSIXct(strptime(fox.db$DATETIME, format="%d/%m/%Y %H:%M"))

fox.fj$dt <- as.POSIXct(fox.fj$DATETIME, format="%d/%m/%Y %H:%M", tz="Australia/Perth")

fj <- fox.fj[,c("LONGITUDE","LATITUDE","dt","ANIMALID")]
#rename cols
colnames(fj)[1:4] <- c("x","y","dt","id")
#check first 4 linfj of the dataframe
fj[1:4,]

```

<br>

### Step 1 - Prepare the data in t-LoCoH format and create lxy object

give x and y a projection
This creates the first of a series of new dataframes that are joined. Pretty clunky way to do it 
but this is what is required in this program

```{r}
#sub-df 1 latlong
fj.sp.latlong <- SpatialPoints(fj[ , c("x","y")], proj4string=CRS("+proj=longlat +ellps=WGS84"))
fj.sp.utm <- spTransform(fj.sp.latlong, CRS("+proj=utm +south +zone=50 +ellps=WGS84")) 
fj.mat.utm <- coordinates(fj.sp.utm)
tail(fj.mat.utm)

#sub-df 2 local time - the data are already in this so just subset to follow naming format
fj.local <- as.POSIXct(fj$dt, tz="Australia/Perth")
local.tz <- "Australia/Perth"
fj.localtime <- as.POSIXct(format(fj.local, tz=local.tz), tz=local.tz)


#sub-df 3 id
fj.id <- fj[,c("id")]

#merge all the df in the correct tlocoh format and order 
fj.lxy <- xyt.lxy(xy=fj.mat.utm, dt=fj.localtime, id="fj", proj4string=CRS("+proj=utm +south +zone=50 +ellps=WGS84"))#, dup.dt.check=FALSE)

```
<br>

Explore the structure of the lxy object
```{r}
nrow(fj.lxy$pts)
summary(fj.lxy)
```
<br>

Plot out the movement trajectory
```{r}
plot(fj.lxy)
```
<br>

Display the distribution of locations by date, step length, and sampling interval.
```{r}
hist(fj.lxy)
```
<br>

Review the sampling frequency
```{r}
lxy.plot.freq(fj.lxy, cp=T)
```
<br>

### Space use model - distance only (time not considered)

Construct a model of space-use without considering time (s=0). k=25 means that it is
considering the nearest 25 points to the parent point (at this stage its completely 
arbitrary). As we are not considering time these points are the nearest in space and as such 
may not necessarily be sequential. 
<br>

```{r}
fj.lxy <- lxy.nn.add(fj.lxy, s=0, k=25)
```

```{r}
summary(fj.lxy)
```
<br>

Save the lxy object for later analysis (when look at the time stuff)
```{r}
lxy.save(fj.lxy, dir="../data")
```
<br>

Make a kml to visualise the track on GoogleEarth so can get a feel for the animals movement.
This is easy but produces a pretty awful result. Doesn't appear to read the dt appropriately. 
Gives and enddate in 2021
Check our the t-locoh extension tutorial to see if there is a better way to do this.
For some reason I cant get this to save in a folder so it will go into the script folder by default.
```{r}
lxy.exp.kml(fj.lxy, 'fj.lxy.231121.kml',compress = FALSE, pt.scale = 0.25, path.lwd = 3)
```
<br>



### Step 2 - Hull construction

The building blocks of all T-LoCoH analyses are hulls, which are simply minimum convex polygons constructed around each point from a set of nearest neighbors. Since we’ve already identified 25 nearest neighbors for each point, we can create hulls with up to 25 nearest neighbors each. We will use the tlocoh::lxy.lhs command to create an lhs object, the next in our progression.
```{r}
fj.lhs <- lxy.lhs(fj.lxy, k=3*3:8, s=0)
```
<br>

What we are doing here is creating 6 different hullsets with k values of 9, 12, 15, 18, 21, and 24 (note we are still setting s=0 because we are not considering the temporal component yet). It is useful to create a selection of hullsets so that we can compare them and choose the optimal one for our purposes. The downside of creating all of these extra hullsets is that it may take a little while to run. Once it is finished, we can get an idea of what areas are included in our hullsets using the tlocoh::plot command again. This time, we will specify that we want to plot the hulls and we’ll add all of the plots to a single page|or loads of pages(!) for easier comparison.
<br>

```{r}
plot(fj.lhs, hulls=TRUE, figs.per.page=1) #if want multiple plots/page then increase No. ie. page = 6
```
<br>

#### Create the isopleths
Isopleths are aggregations of hulls sorted in such a way as to reveal something about space use. The default settings for tlocoh::lhs.iso.add sorts hulls according to density, so the isopleths reflect the likelihood of occurrence, which is a proxy for intensity of use. Then we can plot these (using the iso=TRUE specification instead of hulls=TRUE) to see how they compare to one another and to the hullset plots.
```{r}
fj.lhs <- lhs.iso.add(fj.lhs)
```
<br>

```{r}
plot(fj.lhs, iso=TRUE, figs.per.page=1)
```
<br>

```{r}

plot(fj.lhs, iso=T, k=21, allpts=T, cex.allpts=0.1, col.allpts="gray80", ufipt=F)
```

Note: you can also produce the above plot without the pts. In this case just use:
plot(es.lhs, iso=T, k=24, ufipt=F).
######ignore - I originally ran this with k=18 which looked ok mapping this iso's but when I ran
######ignore - the plots below it looks like k=15 might be better. 

<br>

Two other plots can be used to evaluate the choice of *k* value. The first is the isopleth area curves, which will plot the area included in a set of different isopleth levels (ranging from 0.15 to 0.95 by 0.10). We want to check these plots to make sure that there are no sharp jumps between k values that indicate that a relatively small change in k results in a large increase in included area (likely a false commission). To look at this plot, we use the tlocoh::lhs.plot.isoarea command:

```{r}
lhs.plot.isoarea(fj.lhs)
```
<br>
Hmm..this is pretty flat 

Next - look at the edge to area ratio. We are looking to exclude k values that result in very high edge:area ratios, which are indicative of the Swiss cheese pattern (i.e., many small holes). This is particularly important at some of the isopleths associated with the core area (0.35, 0.45, 0.55) where we would expect relatively few holes.
<br>

```{r}
lhs.plot.isoear(fj.lhs)
```

If the plots are too small in the RMarkdown window then put the code into the Console and 
view the plot in the plot window. Resize this area first so that the plot is nice and big.
Having run all the *k* values multiple times *k*=15 is actually the best. i.e. using a larger 
value of *k* doesnt really change how many of the grey dtps are included in the hulls.

Select this value for subsequent runs and save as an object
```{r}
fj.lhs.k15 <- lhs.select(fj.lhs, k=15)

lhs.save(fj.lhs.k15, dir="../data")
```
<br>

### Step 3 - Incorporate Time

If doing this step in another session then you need to load the lxy and lhs RData files that you saved above. Use the following syntax:

load('./data/es.n1873.2016-01-15.2016-03-15.lxy.03.RData') # es.lxy #change to fj
load('./data/es.n1873.s0.k18.iso.lhs.02.RData')  # es.lhs.k18       #change to fj


create a new nearest neighbor set with a non-zero s parameter. That is, we are now creating a UD that incorporates time. In the first plot there are points in the same general areas that are colour coded differently. This means that they were in the same area but at different times so these points are not temporally related. In the s=0 calculations above this is ignored and therefore is not ecologically very informative. 

Firstly, need to select a 'decent' *s* value. To do this pick an *s* value such that 40-80% of the hulls are ‘time-selected.’ 
<br>

#### Select *s*
<br>
**This is Method 1**
```{r}
fj.lxy <- lxy.ptsh.add(fj.lxy)  #proportion of time selected hulls
```

This creates a set of 200 sample points, each with 10 nearest neighbors. This algorithm goes through a set of different s values and determines *what proportion of hulls are time-selected* (ptsh). Though this is a somewhat stochastic process, we can see that *s* values between approximately 0.01 and 0.06 fall between proportions of time-selected hulls ranging from about 40-80%. Its more easily understood just by looking at the plot.
<br>

**Method 2**
Select a time interval that is ecologically relevant. We are interested in daily movement (e.g. night time foraging), so a 24hr cycle is OK - on the premise that points that are close together but more than 24hrs apart are not related. If you are thinking about longer temporal patterns (e.g. season), then you need to adjust the value accordingly. If you dont have a clue and are fishing for patterns then do this:

```{r}
lxy.plot.pt2ctr(fj.lxy)
```
<br>
and then do this:

```{r}
lxy.plot.sfinder(fj.lxy)
```
<br>
then do this:

```{r}
#note: 3600 = 1 hour (3600 seconds)
lxy.plot.sfinder(fj.lxy, delta.t=3600*c(12,24,36,48,54,60))
```
<br>
Both methods support an *s*=0.05 to 0.06 value at the scale of 24hrs. According to the manual these methods don't necessarily always converge. Apparently that is not an issue as the methods are extremely different. 
<br>


#### Create a new set of time selected NN

using *s*= 0.05 (actually the range was 0.01 - 0.06.....so maybe run a series of these, and retaining *k* = 25 (value used in the distance only method)

```{r}
fj.lxy <- lxy.nn.add(fj.lxy, s=0.05, k=25)
```

this adds another NN set to fj.lxy ie it includes it as another list. To view:
```{r}
summary(fj.lxy)
```
Note the huge difference in the rmax and amax values (perhaps better to use these methods than fixed k)
<br>

**At this stage selecting k=25 and s=0.05**



### Step3b - Alternate method to select *s*
<br>
Can also calculate *s* in the same way that calculated *k*. This next section follows the 
method to do this. I don't think its necessary as we have already used a decent method above but I 
will run through this method just to see if the choice is the same. 

```{r}
fj.lxy <- lxy.nn.add(fj.lxy, s=c(0.0005, 0.005, 0.05, 0.5), k=25)
```
```{r}
lxy.plot.mtdr(fj.lxy, k=25)
```

```{r}
lxy.plot.tspan(fj.lxy, k=25)
```

Comment from the tutorial "These methods still leave a great deal up to the researcher, which has its pros and cons, but at least you’ve got quite a few alternatives for selecting an ideal s value for your particular purposes". We’ll stick with our 0.0012 value for now, but we’ll need to create a new lhs object using this parameter:

```{r}
fj.lhs.time <- lxy.lhs(fj.lxy, k=3*3:8, s=0.05)
```
<br>
Merge the hulls into isopleths

```{r}
fj.lhs.time <- lhs.iso.add(fj.lhs.time)
```
<br>
Plot the isopleths

```{r}
plot(fj.lhs.time, iso=TRUE, figs.per.page=1)
```
When I was going through these in R I changed the figs.per.page to =1 as its too hard to see things on the screen.
I'm not entirely sure that k=15 is the best but it is *better* than the other k's. I think maybe it might be a good idea to play with the other parameters *r* and *a*. 
<br>

Compare with time version to the original distance only method

```{r}
# distance only method
plot(fj.lhs.k15, iso=TRUE, figs.per.page=1)
```
```{r}
# time method
fj.lhs.time.k15 <- lhs.select(fj.lhs.time, k=15)
plot(fj.lhs.time.k15, iso=TRUE, figs.per.page=1)
```

Save the time selected hullset to use with additional work if taking a break at this point.

```{r}
lhs.save(fj.lhs.time.k15, dir="../data")
```
<br>

#### Step 4 - Calc of hr area - Fixed k=15 method, *s*=0 and *S*=0.05

```{r}
# calculation of area|dist only
fj.isos <- isopleths(fj.lhs.k15)
fj.isos[[1]]@data
```



```{r}
# calculation of area|time
fj.time.isos <- isopleths(fj.lhs.time.k15)
fj.time.isos[[1]]@data
```


```{r}
fj.core <- fj.isos[[1]][ fj.isos[[1]][["iso.level"]]==0.5, ]
fj.hr <- fj.isos[[1]][ fj.isos[[1]][["iso.level"]]==0.95, ]

plot(fj.hr, border="blue")
plot(fj.core, border="red", add=T)
```

es.time.isos <- isopleths(es.lhs.time.k15)
es.time.isos[[1]]@data


Plot calculation of area|time vis
```{r}
fj.time.core <- fj.time.isos[[1]][ fj.time.isos[[1]][["iso.level"]]==0.5, ]
fj.time.hr <- fj.time.isos[[1]][ fj.time.isos[[1]][["iso.level"]]==0.95, ]

plot(fj.time.hr, border="blue")
plot(fj.time.core, border="red", add=T)
```
<br>

## The 'a' method (Adaptive Method)
<br>
see p20 in the tlocoh_tutorial.pdf (in the help file)
<br>

Reasoning for using it:
The 'a' in a-method stands for adaptive, because this method is designed to reduce the number of neighbours used in areas where the points are thin and scattered. Neighbours are identified by summing up their cumulative distance from the parent point and stopping when you reach a. This may result in a many points being labelled as neighbours in a dense area (which is what you probably want), and just a few points in outlying areas (which is also what you want).

The workflow is the same as the k method, BUT deciding on a value of 'a' is not straightforward because:
1) a is a cumulative distance from the parent point to the nearest neighbors
2) if time is included, the 'distance' between points is the TSD space-time metric which is not a physical distance.

To assist in picking an appropriate value of 'a' the **auto.a** function is used. This computes the 'a' value such that p% of points get at least n nearest neighbours, where p and n are supplied by you.

So for example, if we like the results with k=15, we can use auto.a() to tell us the value of 'a' that will result in 98% of all points having 15 or more nearest neighbours.


```{r}
fj.a.lxy <- lxy.nn.add(fj.lxy, s=0.05, a=auto.a(nnn=15, ptp=0.98))
```
<br>
```{r}
summary(fj.a.lxy)
```

This summary output tells us that for *s*= 0.05, if *a* = 34349, that 98% of pts
will have at least 15 nn. 

You can now use this to set the range of *a* values to test to calculate the hullsets.
For example: could test *a* = 28000, 29000, ......36000, then view the isopleth plots
to see if happy or whether still need to fine tune things. This is really subjective,
but this is actually how its done!
<br>

#### Step 1 - Identify enough nn that each pt has enough nn identified for *a* = 34349

```{r}
fj.a.lxy <- lxy.nn.add(fj.a.lxy, s=0.05, a=36000)
```
<br>
```{r}
summary(fj.a.lxy)
```

#### Step 2 - Create a new hullset object using a values from 28000 to 36000.
<br>
At this point also add the isopleths; previously we did this as a seperate step

```{r}
fj.lhs.amixed <- lxy.lhs(fj.a.lxy, s=0.05, a=28:36*1000, iso.add=T)
```
<br>

#### Step 3 - Plot out the results

```{r}
plot(fj.lhs.amixed, hulls=TRUE,figs.per.page=1)
```
<br>

```{r}
plot(fj.lhs.amixed, iso=TRUE, figs.per.page=1)
```
<br>

#### Step 4 - Review the isopleth area and edge:area curves
<br>
to try an help with interpreting which value of *a* is reasonable

```{r}
lhs.plot.isoarea(fj.lhs.amixed)
lhs.plot.isoear(fj.lhs.amixed)
```
<br>

This suggests that *a*= 34000 is probably OK 

<br>


```{r}

plot(fj.lhs.amixed, hulls=T, a=34000, allpts=T, cex.allpts=0.1, col.allpts="gray10", ufipt=F)
plot(fj.lhs.amixed, iso=T, a=34000, allpts=T, cex.allpts=0.1, col.allpts="gray10", ufipt=F)

```
<br>

#### Step 5 - Calc of HR area


```{r}
# calculation of area|time|a method
fj.timea.isos <- isopleths(fj.lhs.amixed, a=34000)
fj.timea.isos[[1]]@data
```

The previous time fixed k method gave 50% as 129.11ha, 95% as 1398.47ha
Here we have 717ha and 3930ha

**Fill these data results into hr2.area1.xlsx in the atm project**


Calculation of area|time|a method with pts overlay
```{r}
fj.timea.core <- fj.timea.isos[[1]][ fj.timea.isos[[1]][["iso.level"]]==0.5, ]
fj.timea.hr <- fj.timea.isos[[1]][ fj.timea.isos[[1]][["iso.level"]]==0.95, ]


plot(fj.timea.hr, border="blue")
plot(fj.lhs.amixed,a=34000, allpts=T, cex.allpts=0.1, col.allpts="gray90", ufipt=F, add=T)
plot(fj.timea.core, border="red", add=T)
```
<bw>


**____ Run this next section to get all the session info | citations etc.**


Run this call to get all the information about the version of R running and the 
packages used.
```{r, eval = T }
devtools::session_info()
```


If you need to source citations for different packages then use this command. You 
can do multiple packages by seperating them with commas. NB. if this doesnt work 
for multiple pkgs use the next example:
```{r, eval=FALSE}
print(citation("name of package"), style = "text")
```


For more than one package. Note: you'll need session_infor() to get the pkg versions
```{r, eval=FALSE}
library(purrr)

c("pkg 1", "pkg 2", "pkg 3") %>%
  map(citation) %>%
  print(style = "text")
```





----------------------------------------------

Then move on to the tutorial:
../Statistics/MovEco-R-Workshop-master/MovEco-R-Workshop-master/Materials/Day4/TLoCoH_and_Beyond.html

This has the method to calculate HR isopleth sizes at 50% and 95% as well as overlap btw animals 
and much more. 


See other references throughout the script about additional resources.
I have all this information stored under ./vignettes/tlocoh










