Importing one dimensional dataset for Complete Spatial Randomness win spatstat - r

I have a set of one-dimensional data points (locations on a segment), and I would like to test for Complete Spatial randomness. I was planning to run Gest (nearest neighbor), Fest (empty space) and Kest (pairwise distances) functions on it.
I am not sure how I should import my data set though. I can use ppp by setting a second dimension to 0, e.g.:
myDistTEST<- data.frame(
col1= sample(x = 1:100, size = 50, replace = FALSE),
col2= paste('Event', 1:50, sep = ''), stringsAsFactors = FALSE)
myDistTEST<- myDistTEST[order(myDistTEST$col1),]
myPPPTest<- ppp(x = myDistTEST[,1], y = replicate(n = 50, expr = 0),
c(1,120), c(0,0))
But I am not sure it is the proper way to format my data. I have also tried to use lpp, but I am not sure how to set the linnet object. What would be the correct way to import my data?
Thank you for your kind attention.

It will be wrong to simply let y=0 for all your points and then proceed as if you had a point pattern in two dimensions. Your suggestion of using lpp is good. Regarding how to define the linnet and lpp try to look at my answer here.
I have considered making a small package to handle one dimensional patterns more easily in spatstat, but so far I have only started the package with a single function to make the definition of the appropriate lpp easier. If you feel adventurous you can install it from the GitHub repo via the remotes package:
remotes::install_github("rubak/spatstat.1d")
The single function you can use is called lpp1. It basically just wraps up the few steps described in the linked answer.

Related

NiftyReg apply nonlinear transform to points (brain MRI image registration )

I would like to apply transformations to a set of points using existing nonlinear transformations from niftyreg. How can I do this?
I created the transformations by registering a subject to a template with Niftyreg https://www.nitrc.org/projects/niftyreg/. and also found an example how to do it in RNiftyReg (R version of Niftyreg):
result <- applyTransform(transform, x, interpolation = 3L, nearest = FALSE, internal = FALSE)
https://github.com/Borda/BIRL/blob/master/scripts/Rscript/RNiftyReg_elastic.r
There are now three things I can think of that could help me:
find the command of the niftyreg toolbox that does what applyTransform in the R package does.
understand what applyTransform does and recreate it with python or bash. Unfortunately I could not understand the line in the R function that performs the registration. (see below)
run applyTransform in R, but there I have currently the problem, that I can only run this function with a internal image, meaning the registration has to be produced with R, but I would like to use the ones I already computed.
applyTransform function (transform, x, interpolation = 3L, nearest = FALSE, internal = FALSE)
result <- .Call(C_transformPoints, transform, points, isTRUE(nearest))
newPoints <- sapply(seq_len(nrow(points)), function(i) {if (length(result[[i]]) == nDims) return(result[[i]])
What is C_transformPoints ? my attempts to google it were not successful..
If anyone already did this or knows if this is possible, that would help me a lot!

Fit a bezier curve to spatial lines objects in R

I'm trying to made a flow map in R, which so far I've managed to do, but due to my map only covering the space of one country gcIntermediate from the geosphere will create spatial lines for me, but they have no curve.
I thought maybe I could add a bezier curve to my lines, but I'm having zero luck with working out how I might do that.
long <- runif(10000, 49.92332, 55.02101) #Random co-ordinates
lat <- runif(10000, -6.30217, 1.373248) # Random co-ordinates
df <- as.data.frame.matrix(data.frame(Lat.1 = sample(lat, 10),
Long.1 = sample(long, 10),
Lat.2 = sample(lat, 10),
Long.2 = sample(long, 10))) # Dataframe of flow beginning to flow end
lines <- gcIntermediate(df[,c("Long.1", "Lat.1")], df[,c("Long.2", "Lat.2")], 500, addStartEnd = TRUE) #Create spatial lines with the geosphere package
plot(lines) #Some very straight lines
My problem comes when setting a start and end point for the bezier line, as the function in the bezier package only seems to accept one value for start and one for end, which given each point needs two values (long, lat) to define it I'm a bit stumped by.
I won't bore you with all of the different things I've tried with the bezier package (as none of them worked), here are some things that didn't work
bezier(sep(0,1,100), lines, lines$Long.1~lines$Lat.1, lines$Long.2~lines$Lat.2) # Won't accept a line object and I don't think Long.1 etc exist anymore
bezier(sep(0,1,100), df, df$Long.1~df$Lat.1, df$Long.2~df$Lat.2) #Hoped that if I used a formula syntax I could combine the long/lat of the starting and ending points respectively (I can't)
Has anyone got any insight on this? It's quite frustrating being so close and yet so far.

Data format in soil.spec package in R

I would like to use the trans function of soil.spec package to transform spectra using continuum removal. But I don't understand data format of raw spectra "raw"
the function example is:
trans(raw, tr = "continuum removed", order = , gap = )
Could someone show me an example of "raw" matrix
for continuum removal you can alternatively use the prospectr package
require(prospectr)
data(NIRsoil)
If your spectral data is in absorbance units then:
crt <- continuumRemoval(X = NIRsoil$spc, type = 'A')
matplot(x = colnames(NIRsoil$spc), y = t(crt),
type = "l", lty = 1,
xlab = "Wavelengths (nm)",
ylab = "Absorbance (CR)",
col = palette(gray(seq(0, 0.9, len = 25))))
If the spectral data is in reflectance units the type argument must be set to 'R'.
I have to say the soil.spec package is very weak on documentation. But, based on this quote from one of the I/O tools,
read.spc reads binary spectral spc-files from a folder into R. The
spectra can be made compatible (see details in make.comp) either to
the first sample wavebands or to the standard wavebands of the ICRAF
spectral lab. Information from the scanning method is gathered to
check on spectral comparability. The default has been set to ICRAF
spectral bands
My suspicion is that you need to have your files in whatever "spectral spc-files" format is, assuming that is an industry standard. Best bet may be to contact the package maintainer directly.
To obtain continuum removal transformation on your spectra using the soil.spec library, proceed as follows:
Prepare the raw spectra table and ensure its columns contains the spectral data to be transformed. Remove all non-spectral columns and ensure that no missing values.
Make the column names of raw spectra table to numeric format.
Proceed to run the transformation as shown below
raw.cw <- trans(raw,tr="continuum removed", order=1, gap=21)
raw.cw contains the raw spectra prior to the transformation, and the transformed spectra matrix now in your case continuum removed and the transformation method used.
To see these three objects run:
names(raw.cw)
raw.cw is an arbitrary object name assigned to the results obtained via other trans function.
Your continuum removed spectra is extracted from the results using the standard syntax as used in R system:
cw.spectra<-raw.cw$trans
We are updating the documentation of the soil.spec package and some of these explanations will be included as we release the next updated version which will bring additional functionalities for handling spectral data.
Kindly let me know if this helps but if you face any difficult with following this guideline to get the expected results, I will be glad to help.
Best,
Andrew
ICRAF

Use Rcartogram on a SpatialPolygonsDataFrame object

I'm trying to do the same thing asked in this question, Cartogram + choropleth map in R, but starting from a SpatialPolygonsDataFrame and hoping to end up with the same type of object.
I could save the object as a shapefile, use scapetoad, reopen it and convert back, but I'd rather have it all within R so that the procedure is fully reproducible, and so that I can code dozens of variations automatically.
I've forked the Rcartogram code on github and added my efforts so far here.
Essentially what this demo does is create a SpatialGrid over the map, look up the population density at each point of the grid and convert this to a density matrix in the format required for cartogram() to work on. So far so good.
But, how to interpolate the original map points based on the output of cartogram()?
There are two problems here. The first is to get the map and grid into the same units to allow interpolation. The second is to access every point of every polygon, interpolate it, and keep them all in right order.
The grid is in grid units and the map is in projected units (in the case of the example longlat). Either the grid must be projected into longlat, or the map into grid units. My thought is to make a fake CRS and use this along with the spTransform() function in package(rgdal), since this handles every point in the object with minimal fuss.
Accessing every point is difficult because they are several layers down into the SpPDF object: object>polygons>Polygons>lines>coords I think. Any ideas how to access these while keeping the structure of the overall map intact?
This problem can be solved with the getcartr package, available on Chris Brunsdon's GitHub, as beautifully explicated in this blog post.
The quick.carto function does exactly what you want -- takes a SpatialPolygonsDataFrame as input and has a SpatialPolygonsDataFrame as output.
Reproducing the essence of the example in the blog post here in case the link goes dead, with my own style mixed in & typos fixed:
(Shapefile; World Bank population data)
library(getcartr)
library(maptools)
library(data.table)
world <- readShapePoly("TM_WORLD_BORDERS-0.3.shp")
#I use data.table, see blog post if you want a base approach;
# data.table wonks may be struck by the following step as seeming odd;
# see here: http://stackoverflow.com/questions/32380338
# and here: https://github.com/Rdatatable/data.table/issues/1310
# for some background on what's going on.
world#data <- setDT(world#data)
world.pop <- fread("sp.pop.totl_Indicator_en_csv_v2.csv",
select = c("Country Code", "2013"),
col.names = c("ISO3", "pop"))
world#data[world.pop, Population := as.numeric(i.pop), on = "ISO3"]
#calling quick.carto has internal calls to the
# necessary functions from Rcartogram
world.carto <- quick.carto(world, world$Population, blur = 0)
#plotting with a color scale
x <- world#data[!is.na(Population), log10(Population)]
ramp <- colorRampPalette(c("navy", "deepskyblue"))(21L)
xseq <- seq(from = min(x), to = max(x), length.out = 21L)
#annoying to deal with NAs...
cols <- ramp[sapply(x, function(y)
if (length(z <- which.min(abs(xseq - y)))) z else NA)]
plot(world.carto, col = cols,
main = paste0("Cartogram of the World's",
" Population by Country (2013)"))

R/ImageJ: Measuring shortest distance between points and curves

I have some experience with R as a statistics platform, but am inexperienced in image based maths. I have a series of photographs (tiff format, px/µm is known) with holes and irregular curves. I'd like to measure the shortest distance between a hole and the closest curve for that particular hole. I'd like to do this for each hole in a photograph. The holes are not regular either, so maybe I'd need to tell the program what are holes and what are curves (ImageJ has a point and segmented line functions).
Any ideas how to do this? Which package should I use in R? Would you recommend another program for this kind of task?
EDIT: Doing this is now possible using sclero package. The package is currently available on GitHub and the procedure is described in detail in the tutorial. Just to illustrate, I use an example from the tutorial:
library(devtools)
install_github("MikkoVihtakari/sclero", dependencies = TRUE)
library(sclero)
path <- file.path(system.file("extdata", package = "sclero"), "shellspots.zip")
dat <- read.ijdata(path, scale = 0.7812, unit = "um")
shell <- convert.ijdata(dat)
aligned <- spot.dist(shell)
plot(aligned)
It is also possible to add sample spot sizes using the functions provided by the sclero package. Please see Section 2.5 in the tutorial.
There's a tool for edge detection written for Image J that might help you first find the holes and the lines, and clarify them. You find it at
http://imagejdocu.tudor.lu/doku.php?id=plugin:filter:edge_detection:start
Playing around with the settings for the tresholding and the hysteresis can help in order to get the lines and holes found. It's difficult to tell whether this has much chance of working without seeing your actual photographs, but a colleague of mine had good results using this tool on FRAP images. I programmed a ImageJ tool that can calculate recoveries in FRAP analysis based on those images. You might get some ideas for yourself when looking at the code (see: http://imagejdocu.tudor.lu/doku.php?id=plugin:analysis:frap_normalization:start )
The only way I know you can work with images, is by using EBImage that's contained in the bioconductor system. The package Rimage is orphaned, so is no longer maintained.
To find the shortest distance: once you have the coordinates of the lines and holes, you can go for the shotgun approach : calculate the distances between all points and the line, and then take the minimum. An illustration about that in R :
x <- -100:100
x2 <- seq(-70,-50,length.out=length(x)/4)
a.line <- list(x = x,
y = 4*x + 5)
a.hole <- list(
x = c(x2,rev(x2)),
y = c(200 + sqrt(100-(x2+60)^2),
rev(200 - sqrt(100-(x2+60)^2)))
)
plot(a.line,type='l')
lines(a.hole,col='red')
calc.distance <- function(line,hole){
mline <- matrix(unlist(line),ncol=2)
mhole <- matrix(unlist(hole),ncol=2)
id1 <- rep(1:nrow(mline),nrow(mhole))
id2 <- rep(1:nrow(mhole), each=nrow(mline))
min(
sqrt(
(mline[id1,1]-mhole[id2,1])^2 +
(mline[id1,2]-mhole[id2,2])^2
)
)
}
Then :
> calc.distance(a.line,a.hole)
[1] 95.51649
Which you can check mathematically by deriving the equations from the circle and the line. This goes fast enough if you don't have millions of points describing thousands of lines and holes.

Resources