Giter VIP home page Giter VIP logo

spatstat's Introduction

spatstat

CRAN_Status_Badge GitHub R package version Travis-CI Build Status codecov.io appveyor build status

What is spatstat?

spatstat is a family of R packages for analysing spatial point pattern data (and other kinds of spatial data). It has extensive capabilities for exploratory analysis, statistical modelling, simulation and statistical inference.

See the website www.spatstat.org or read the book.

spatstat has been split into a family of packages

Originally there was a single package called spatstat. It grew so large that CRAN required us to split it into pieces.

The original spatstat has now been divided into a family of sub-packages:

Sub-package CRAN page GitHub repository Description
spatstat.utils CRAN_Status_Badge GitHub R package version Basic utilities
spatstat.data CRAN_Status_Badge GitHub R package version Datasets
spatstat.univar CRAN_Status_Badge GitHub R package version 🆕 Univariate probability distributions 🦘
spatstat.sparse CRAN_Status_Badge GitHub R package version Sparse arrays
spatstat.geom CRAN_Status_Badge GitHub R package version Spatial data classes; geometrical operations
spatstat.random CRAN_Status_Badge GitHub R package version Generation of random patterns
spatstat.explore CRAN_Status_Badge GitHub R package version Exploratory Data Analysis of spatial data
spatstat.model CRAN_Status_Badge GitHub R package version Parametric modelling and formal inference for spatial data
spatstat.linnet CRAN_Status_Badge GitHub R package version Spatial analysis on a linear network
spatstat CRAN_Status_Badge GitHub R package version Umbrella package

Click the green badge to visit the CRAN page which contains the current release of each sub-package. Click the blue badge to visit the GitHub repository for the current development version of the sub-package.

There still exists a package called spatstat, which is now an umbrella package that requires all the sub-packages listed above.

You can install and load the new spatstat family in virtually the same way as you would previously have installed and loaded the old spatstat package. When you install the new umbrella package spatstat, all the sub-packages listed above will be installed. When you load the new umbrella spatstat package in an R session, all the sub-packages listed above will be loaded or imported.

Extension packages

Additionally there are extension packages which contain more functionality. These packages are not automatically installed or loaded; the user must do that if these extra features are desired.

Extension package CRAN page GitHub repository Description
spatstat.gui CRAN_Status_Badge GitHub R package version Graphical interface
spatstat.Knet CRAN_Status_Badge GitHub R package version linear networks
spatstat.local CRAN_Status_Badge GitHub R package version Local (geographically weighted) models
spatstat.sphere Not yet published GitHub R package version Spherical data

Family portrait

The pink box marked spatstat contains all the code that will be installed when you install the spatstat umbrella package, and loaded or imported when you load the spatstat umbrella package.

The blue boxes are extension packages which must be installed and loaded separately.

Spatstat pieces

Future development

spatstat is the result of 30 years of software development and contains over 180,000 lines of code. It is still under development, motivated by the needs of researchers in many fields, and driven by innovations in statistical science. We welcome contributions of code, and suggestions for improvements.

spatstat's People

Contributors

aj4x-evil avatar antiphon avatar baddstats avatar biscio avatar michaelchirico avatar richierocks avatar rubak avatar t-pollington avatar ute avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

spatstat's Issues

win/window parameter name inconsistency

Some spatstat functions use win and some use window. Spatstat's defaults mean mistyping does not cause an error, but can generate a wrong window. And R's floppy parameter matching mean users often abbreviate parameter names and expect the right thing to happen.

Here x and y are some points in a disc(10):

ppp uses window:

> p = ppp(x,y, window=disc(10))
>

and using win fails (here with a warning, but possibly silently):

> p = ppp(x,y, win=disc(10))
Warning message:
299 points were rejected as lying outside the specified window 

because it uses a default (0,1) box window.

Conversely rpoispp uses win:

> p = rpoispp(10, win=disc(10))
> p
Planar point pattern: 3149 points
window: polygonal boundary
enclosing rectangle: [-10, 10] x [-10, 10] units

And using window fails silently by generating a pattern in a default 0,1 box:

> p = rpoispp(10, window=disc(10))
> p
Planar point pattern: 8 points
window: rectangle = [0, 1] x [0, 1] units

Could this inconsistency be patched up?

Summary function fails on fitted object when using method="logi"

Following on from the recent issue that was fixed in spatstat 1.47-0.034
where method="logi" did not support a data frame of covariates.
The function summary fails on the fitted model object, however printing the object by typing its name works.

Sorry I can't provide details of the error message as I am not a work, but he previous issue submission has a data set and code that could be used to test this.

Regards,
Kim Colyvas

Error for smooth residual plot of fitted Geyer model in plot.diagppm

Reported here with the following MWE:

library(spatstat)
#generate a pattern
pattern <- rpoispp(300)
#generate a covariate
cov <- rnoise(rgen = rnorm, dimyx=32, mean=2, sd=1, w = pattern$window)

#fit the model
fit <- ppm(pattern ~ cov, Geyer(r = 0.01, s = 0.02))

#plot diagnostics
diag <- diagnose.ppm(fit, type = "pearson", which = "all") #this works
diag <- diagnose.ppm(fit, type = "pearson", which = "smooth") #this doesn't

Adding plot.it = FALSE postpones the problem until plot.diagppm is called, so the error is probably hidden in there somewhere.

parallel envelope() ?

Hello all,

I am somehow newbie to the Spatstat package. I wonder if there is a way to improve the speed of running ppm model diagnostics using the envelope() function. For just 250 simulations of one of my models, it is expected to be finished in 9 hours!
My question is: is there a way to make it somehow faster using the multicore advantage of my processor? I am running a windows server virtual machine with 24 cores, is it possible to make such simulations in a parallel way (e.g. using foreach() or equivalent way) and then to collect the whole simulations once finished and having one envelope plot?

Thanks,
Ahmed

Issue 30 fix didn't work

Issue 30 concerned the failure of the summary command on a fitted object using ppm with method="logi".
See response below from issue 30. After installing spatstat 1.47-0.053 the command still failed.
Error in model.matrix.ppm(model) :
internal error: model matrix does not match glm data frame

Example code and data set attached.
LR bug example.R.txt
LR bug example.data.txt

[However the workaround suggestion about NA values did work and we were able to move the next step and found a data frame related issue failure with the envelope command which is the subject of another issue submission. "This occurs when the data frame contains NA values. (The NA's are dropped in some circumstances and retained in others, leading to a mismatch in the dimensions of data frames.) An immediate workaround is to remove data that contains NA's. Either remove columns of the data frame that contain NA values (and of course remove these variables from the model formula), or remove rows of the data frame that contain NA's and remove the corresponding data points from the quadrature scheme. This bug has been fixed in spatstat 1.47-0.050."]

Regards,
Kim

parres() function --- `Fitting algorithm for ‘glm’ did not converge` warning

Hello all,

I am having a problem with the parres() function, with a ppm model having interactions between covariates.

I am receiving an error like:
Error in parres(model = CurrPPM, covariate = "Var1")
The covariate ‘Var1’ cannot be separated from the covariates ‘Var2’ and ‘Var3’ in the model terms ‘Var1:Var2’ and ‘Var1:Var3’

While running the ppm model, I've used a formula like: as.formula(~(Var + Var2 + Var3)^2 + I(Var1^2) + I(Var2^2) + I(Var3^2)) to include all variables, their quadratic terms and all possible combinations. Then I've used the MASS:::stepAIC() function to select the best model out of the initial model. When I am trying to do some model diagnostics, it works fine except for the parres() function. The covariates were provided to the model as original variables, and I am using the formula mentioned above to include the interactions on the fly while running the model. i.e. I provided just a list of 3 real-valued pixel image (class: im) not the interactions or the quadratic terms and they were calculated properly while running the model. Is that the cause of the error message I am receiving? Should I prepare, as much as I need, real-valued pixel images (im) of the interactions and quadratic terms and provide them explicitly as covariates?

Another thing, I am always receiving a warning message of: *** Fitting algorithm for ‘glm’ did not converge *** even if the model takes somehow much time to process. I've tried to use something like: glm.control(maxit = 1000) but it does not help much. Is it ok to ignore this warning message? or I should do some other steps to avoid such warnings? In one of my cases, there is 81 points and 590083 dummy points. Is the number of points not enough to run a reasonable ppm model compared to the used number of dummy points?

Thanks,
Ahmed

Errors occur when methods for 'ppm' objects are applied to the results of 'subfits'

Users report errors arising when

  1. A model is fitted to several point patterns using mppm
  2. Models for each individual point pattern are extracted using subfits
  3. A function designed for ppm objects (e.g. predict.ppm, simulate.ppm, diagnose.ppm, qqplot.ppm) is applied to one of the results of subfits.

We are investigating this.

If you encounter this problem, please post details, including the spatstat version number

no method or default for coercing “SpatialPolygons” to “owin”

Hi,
I tried to reprodcue the example in the vignette in order to convert an object of type SpatialPolygons to a single object of class owin.

X <- readOGR(...)
class(X)
[1] "SpatialPolygonsDataFrame"
attr(,"package")
[1] "sp"

X <- as(X, "SpatialPolygons")
class(X)
[1] "SpatialPolygons"
attr(,"package")
[1] "sp"

as(X, "owin")
 Show Traceback
Error in as(X, "owin") : no method or default for coercing “SpatialPolygons” to “owin”

What am I doing wrong?
Thanks.

rmh-simulation of ppm fit in an alternative window (1.41-1)

spatstat version 1.41-1
R version 3.1.2

Trying to simulate a fitted model in an alternative window gives me an error.

Example:

library(spatstat)
x <- rpoispp(100)
f <- ppm(x~1, i=StraussHard(0.1))
Wnew <- as.owin(c(0,2,0,2))
simulate(f, w=Wnew)
Error in runifpoint(npts.free, w.sim, ...) : 
  argument 3 matches multiple formal arguments

rmh(f, w=Wnew)
Error in rmh.default(model = list(cif = "straush", par = list(gamma = 0.96592610760324,  : 
  Expanded simulation window does not contain model window

pool.fv fails with long list

pool.fv fails if it is applied to a list of many objects.

X <- rpoispp(30, nsim=200)
PCF <- anylapply(X, pcf)
MeanPcf <- pool(PCF)

Error in (function (fmt, ...) :
'fmt' length exceeds maximal format length 8192

A workaround will be found.

problem with dirichlet function

From "Spatial Point Patterns" page 122:

X = runifpoint(10)
V = dirichlet(X)

     PLEASE NOTE:  The components "delsgs" and "summary" of the
 object returned by deldir() are now DATA FRAMES rather than
 matrices (as they were prior to release 0.0-18).
 See help("deldir").
 
     PLEASE NOTE: The process that deldir() uses for determining
 duplicated points has changed from that used in version
 0.0-9 of this package (and previously). See help("deldir").

Error in .Fortran("master", x = as.double(x), y = as.double(y), rw = as.double(rw),  : 
  "master" not available for .Fortran() for package "deldir"
Error in .Fortran("master", x = as.double(x), y = as.double(y), rw = as.double(rw),  : 
  "master" not available for .Fortran() for package "deldir"
In addition: Warning message:
deldir failed; re-trying with slight perturbation of coordinates. 
Warning message:
deldir failed even after perturbation of coordinates. 

The error note is verbose, but I still don't know how to run the dirichlet function on X.

Sys.info():

                                             sysname                                              release                                              version                                             nodename 
                                             "Linux"                                   "4.8.0-42-generic" "#45~16.04.1-Ubuntu SMP Thu Mar 9 14:10:58 UTC 2017"                                      "henk-N24-25BU" 
                                             machine                                                login                                                 user                                       effective_user 
                                            "x86_64"                                            "unknown"                                               "henk"                                               "henk" 

Error in mpl.prepare(.........

Hi all,
I am receiving this error message:
"Error in mpl.prepare(Q, X, P, trend, interaction, covariates, want.trend, :
interaction evaluator did not return a matrix"

When trying to run an area-interaction model using this code:
plike <- profilepl(rs, AreaInter, Q, trend=int.form, covariates=int.list)

[I am following the code mentioned in the supplementary materials of the under-publication of Renner et al. about point process models and presence-only SDM - The same chunks of code worked before few weeks ago but with repeating the same code again I receive the error stated above]

Any help is appreciated,
Thanks,
Ahmed

Plot coordinates (image device) flipped on MacOSX

A user of the ImageJ forum asked a question about a particle analysis and I recommended the use of spatstat:

http://forum.imagej.net/t/number-of-particles-in-clusters/2587

I flipped the y-coordinates for an ImageJ display.

This works fine on Windows. However if i apply the same command on MacOSX the flipped coordinates are not applied to the density plot. If I select a *.pdf device instead of an image device (tested with *.tiff and *.png) the density plot is flipped.

Here the reproducible example whereas the density plot on MacOSX is not flipped according to the plot template:

library(spatstat)

#Create a spatstat point pattern from a ImageJ Particle analysis!
X<- ppp(Particles$X, Particles$Y, c(0,imageSizeX), c(0,imageSizeY))
W <- Window(X)
#Plot is visualized in ImageJ (Java) coordinates so we need an inverted coordinate parent plot!
plot(W, ylim=rev(W$yrange),main=NULL)
#Add a density plot
plot(density(X,adjust=0.2),add=T)
#Add the points!
plot(X, add=T)
#Add axis and title in custom font size!
axis(1,cex.axis=2)
axis(2, cex.axis=2)
title(main="Density",xlab="Width", ylab="Height", cex.lab=1.5,cex.main=3) 

Spatstat version: 1.46.1

vcov.mppm struggles with 'id'

The result of vcov.mppm has the wrong format if the model has an interaction term which depends on the id variable. This causes an error in anova.mppm.
Example

  h <- hyperframe(X=waterstriders)
  fitP <-mppm(X ~ id, h)
  fitS <- mppm(X ~ id, h, Strauss(2), iformula=~Interaction * id)
  vcov(fitS)
  anova(fitP, fitS)

object 'SpatstatVersion' not found

I'll get the following error calling profilepl and mppm functions within a custom package:

Error in get(name, envir = .spEnv) : object 'SpatstatVersion' not found
Calls: <Anonymous> ... versionstring.spatstat -> getSpatstatVariable -> get

disconnected networks

pairdist.lpp, crossdist.lpp and nndist.lpp currently give an error if the network is not connected. Bug fix is under development.

FR: offer control over type of output in empty pixellate.ppp?

This is closely related to what I'm trying to accomplish in #44.

In this line, pixellate.ppp forces its output type when presented an empty ppp to be numeric:

sapply(as.data.frame(pixellate(ppp(xrange = 0:1, yrange = 0:1))), class)
#         x         y     value 
# "numeric" "numeric" "numeric"

However, I need to combine the resultant data.frame (actually, data.table) with some ppp that have value as integer:

sapply(as.data.frame(pixellate(ppp(x = .5, y = .5, yrange = 0:1, xrange = 0:1))), class)
#         x         y     value 
# "numeric" "numeric" "integer" 

Specifically, the following operation fails:

library(data.table)
DT = data.table(x = c(NA, .5), y = c(NA, .5), ID = c(1, 2))
DT[ , as.data.table(pixellate(
  if (all(is.na(x)))
    ppp(xrange = 0:1, yrange = 0:1)
  else 
    ppp(x = x, y = y, xrange = 0:1, yrange = 0:1),
  eps = c(1/3, 1/3))), by = ID]

Error in [.data.table(DT, , as.data.table(pixellate(if (all(is.na(x))) ppp(xrange = 0:1, :
Column 3 of result for group 2 is type 'integer' but expecting type 'double'. Column types must be consistent for each group.

Either of two solutions that spatstat could implement would be greatly appreciated:

  • Offer a user-facing option to control what type pixellate.ppp casts for value when faced with an empty ppp
  • Change the default in the aforementioned line to as.im(0L, W) (this seems more natural to me anyway -- though I don't know the full gamut of use cases for pixellateing empty ppps, so maybe I'm missing something)

LinearK failing on disconnected network

Problem located while answering this question on SO and I suspect the problem is that a component has no points.

library(spatstat)
#> Loading required package: nlme
#> Loading required package: rpart
#> 
#> spatstat 1.52-1.005       (nickname: 'Frame Dragging') 
#> For an introduction to spatstat, type 'beginner'
l <- thinNetwork(simplenet, retainedges = c(-3,-10))
#> Warning: Network is not connected
set.seed(42)
X <- runiflpp(2, l)
plot(X)

linearK(X)
#> Error in retainedges[dat$seg]: invalid subscript type 'list'

Export units and print.units etc as S3 class/methods?

spatstat has a conflict with r-quantities/units that also affects r-spatial/sf and other packages that use units.

The issue is that spatstat::print.units() conflicts with the units:::print.units() method. The latter is exported as a S3 method for a "units" class. Example:

library("units")

# works
set_units(1000, "m")
print(set_units(1000, "m"))

library("spatstat")

# error
set_units(1000, "m")
print(set_units(1000, "m"))

# but this works
units:::print.units(set_units(1000, "m"))

Changing the order in which the packages are loaded does not fix the error, possibly because spatstat's [foo].units functions are not exported as S3 methods (see r-spatial/sf#523). And there is no warning about the conflict when the packages are loaded, only for spatstat::as.units:

> library("units")
> library("spatstat")
Loading required package: spatstat.data
Loading required package: nlme
Loading required package: rpart

spatstat 1.53-2       (nickname: ‘Quantum Entanglement’) 
For an introduction to spatstat, type ‘beginner’ 


Attaching package: ‘spatstat’

The following object is masked from ‘package:units’:

    as.units

Same issue at r-quantities/units#66.

Bug in plot.lpp for patterns with multiple marks

library(spatstat)
X <- runiflpp(2, simplenet)
marks(X) <- cbind(m1 = 1:2, m2 = 3:4)
plot(X

This gives an error since plot.lpp expects that marks are a data.frame but in fact they are a hyperframe in this case. The (first) problematic line is here:
https://github.com/spatstat/spatstat/blob/master/R/lpp.R#L110

Two obvious fix strategies:

  1. Allow this to be a hyperframe (but these can be hard to plot in general).
  2. Coerce to data.frame and warn about requested columns left out due to this.

This caused problems in this question on SO.

Spatial logistic regression failure

The attached example is from a study to determine if there are any covariates that might explain the locations chosen by calling male frogs around the perimeter ponds. The sampling process involved finding calling frogs (presence) and recording covariate values for each frog. Then moving away from those locations using a random process and recording covariate values at those new locations. If any calling frogs were present in these new locations they were recorded too, but I think the expectation was many of these randomly chosen locations would represent the absences.
So it seemed that a spatial logistic regression would be an appropriate analysis due to the comparison of covariate values between presence and absence sites

We (Ian Renner mainly and I) have tried to set up the attached code in accord with the example in the spatstat book but if fails at the modelling step with error message

Error in mpl.get.covariates(covariates, U, "quadrature points", covfunargs) :
Each entry in the list 'covariates' should be an image, a function, a window, a tessellation or a single number

There are warnings when running the code about duplicate records but we did not think this would the reason for the failure of the model step.

LR bug example .data.txt
LR bug example.R.txt

pres = ppp(x = presX, y = presY, window = pond.w)
Warning message:
In ppp(x = presX, y = presY, window = pond.w) :
data contain duplicated points
abs = ppp(x = absX, y = absY, window = pond.w)
Warning message:
In ppp(x = absX, y = absY, window = pond.w) :
data contain duplicated points

Any help would be appreciated,
Kim Colyvas
[email protected]

ppp lose attributes when manipulated

Subsetting and other manipulations make point patterns lose some of their attributes. For cluster point processes, it means they lose their parents and become orphans. Is this behaviour intended?

X <- rMatClust(10, 0.05, 4)
attributes(X)
attributes(X[square(1)])
attributes(shift(X, c(0,0)))

If necessary, backwards compatibility could e.g. be ensured by a spatstat option keep.ppp.attributes that defaults to FALSE.

wrong description in nndist.Rd?

Dear developers,

the example

data(ants)
aggregate(nnda, by=list(from=marks(ants)), mean)

results in:

         from Cataglyphis   Messor
1 Cataglyphis    67.47011 36.27306
2      Messor    59.02549 46.12532

and is described as:

# The mean distance from a Messor nest to
# the nearest other Messor nest is 59.02549 units

At least in my understanding, this seems to be incorrect, and is supported when calculating "by hand":

lapply(split(ants), function(x) mean(nndist(x)))
$Cataglyphis
[1] 67.47011

$Messor
[1] 46.12532

Hence, the correct description would be

# The mean distance from a Messor nest to
# the nearest other Messor nest is 46.12532 units

or

# The mean distance from a Messor nest to
# the nearest Cataglyphis nest is 59.02549 units

Bug in plot.kppm when fitting method != "mincon"

In this line:

spatstat/R/kppm.R

Line 1109 in 1e55b2e

((what == "cluster") & (Fit$mcfit$internal$model == "lgcp")) |

we get a logical(0) when the model isn't fitted via minimum contrast. Either we need to add a check for is.null or make another more robust way to check things here (e.g. a new function clustertype that extracts the cluster type from a kppm object).

funxy() tampers with one-liners

spatstat 1.45-0 made funxy more and less general at the same time. The problem is that the new magic manipulation of the supplied function f assumes body(f) to be a call of "{". One-liners such as f = function (x,y) sqrt(x^2+y^2) yield wrong results (without a warning or error message)! It took me a while to trace back this problem when trying to reproduce an analysis originally conducted with spatstat 1.44-1. Here is a small example illustrating the erroneous behaviour:

fxy1 <- funxy(function (x, y) sqrt(x^2+y^2), letterR)
body(fxy1)[[length(body(fxy1))]]  # sqrt() is missing!!!

fxy2 <- funxy(function (x, y) {sqrt(x^2+y^2)}, letterR)
body(fxy2)[[length(body(fxy2))]]  # correct

par(mfrow=c(1,2)); plot(fxy1); plot(fxy2)

To correctly manipulate f in funxy one either needs to differentiate these two cases (as I do in surveillance:::add.on.exit defined here) or, maybe simpler, to ensure first that f is a call of { and then proceed as in the current version of funxy. I came up with the following auxiliary function to do this pre-checking of f:

curlyf <- function (f)
{
    f <- match.fun(f)
    if (is.primitive(f)) { # body(f) is NULL
        stop("not implemented for primitive functions")
    }
    obody <- body(f)
    if (is.call(obody) && identical(as.name("{"), obody[[1L]])) {
        return(f)
    } else {
        ## body(f) is a symbol or a single call like sqrt(x^2 + y^2)
        body(f) <- as.call(c(as.name("{"), obody))
        return(f)
    }
}

I am not sure how to deal with primitive functions, but these are unlikely to be used in the funxy context.

DOCS: rescale doc issue

The docs for rescale say parameter s is "Conversion factor: the new units are s times the old units.".

As noted below, however, "For example if X is a dataset giving coordinates in metres, then rescale(X,1000) will divide the coordinate values by 1000 to obtain coordinates in kilometres, and the unit name will be changed from "metres" to "1000 metres". Similarly rescale(X, 1000, "km") will divide the coordinate values by 1000 to obtain coordinates in kilometres, and the unit name will be changed to "km"."

So new units are old units DIVIDED by s, no?

is pixellate/ppp _guaranteed_ to return sorted coordinates?

I'm running a routine basically equivalent to:

library(spatstat)
DF = as.data.frame(pixellate(humberside))

It would be very helpful if I could be assured that x and y in the result are sorted, but I don't see this anywhere in the documentation (?as.data.frame.im, ?pixellate.ppp, ?ppp and ?ppp.object are all quiet on this point).

But it appears to be true empirically... basically, I want to know if this always holds true for data.frames resulting from im/ppp objects:

identical(DF, DF[order(DF$x, DF$y), ])

kernel names in density function don't match with function

kernel names in density function help:
kernel = c("gaussian", "epanechnikov", "rectangular", "triangular", "biweight", "cosine", "optcosine")

Error: Unrecognised choice of kernel ‘biweight’ (options are ‘gaussian’, ‘epanechnikov’, ‘quartic’ and ‘disc’)
density(redwood, bw.ppl, kernel = "biweight") # works

documentation update: ppp/check should also be turned off to suppress duplicate point warnings

Hey,

I have been using ppp on some data that I know contains duplicated coordinates. I'm fine with this, and was looking to see if ppp has an argument to ignore warning me about this.

A read of ?ppp suggests that it's not the case, so I was resigned to using suppressWarnings, but I checked the code of ppp and I see:

    if (check && anyDuplicated(pp)) 
        warning("data contain duplicated points")

Thus it seems the check argument has a second undocumented use to suppress this warning. So I guess it should be added to the manual page.

Thanks!

spatstat fails package checker using the latest version of RandomFields

spatstat fails the package checker if the latest versions of RandomFields (3.1.24) and RandomFieldsUtils (0.3.3) are installed.

However, spatstat can be installed without error, and runs without error.

The problem only arises in the checking process when the RandomFields namespace is attached but the RandomFields package is not loaded.

A fix has been identified.

Irregular window in idw function

When idw is used on a point pattern with non-rectangular window the result is returned in the entire frame of the window. Is there a reason to have this behaviour? If so, we should include an example of extracting the relevant region of the returned image(s) in the help file. See http://stackoverflow.com/q/35617548/3341769 for an example.

Smooth.ppp crashes if marks are NA

Maybe we should handle this example

df <- data.frame(x=runif(3), y=runif(3), m = c(1, 2, NA))
X <- as.ppp(df, W=owin())
Smooth(X)

more gracefully than this:

Error in (function (x, values, sigma, ..., weights = NULL, varcov = NULL,  : 
  NA/NaN/Inf in foreign function call (arg 4)
In addition: Warning messages:
1: some mark values are NA in the point pattern X 
2: some mark values are NA in the point pattern X 
3: some mark values are NA in the point pattern X 

user supplied pixel grid for density.ppp

I have noticed some unexpected behaviour in density.ppp. I use the humberside data for illustration. I am aware that it does not make much sense to choose sigma so small for this data set, but for my own data it does make sense and the issue remains.

If I say

xi <- unmark(humberside)
d <- density(xi, sigma=1)
plot(d)

everything runs as expected. However, if I supply my own pixel grid to compute the density via

xcoor <- seq(4690, 5415, 5)
ycoor <- seq(4150, 4760, 5)
d2 <- density(xi, sigma=1, xy=list(x=xcoor, y=ycoor))
plot(d2)

we see a lot of mass getting concentrated in one single pixel. I could understand this (to some extent) if the intersection of the pixel with the observation window were tiny, but from plotting the boundary with plot(xi$window,add=TRUE) it seems that it is not. The issue seems to disappear if we make sigma somewhat larger, but becomes much more pronounced if we make it smaller.

Since sigma is small I could live in fact with not doing an edge correction. However, if I say

d3 <- density(xi, sigma=1, xy=list(x=xcoor,y=ycoor), edge=FALSE)
plot(d3)

the visual impression looks fine, but the scaling becomes wrong (set sigma=0.1 and observe how the density values increase by a factor of 10).

envelope-function and pre-simulated patterns: Number of patterns not recognized

The envelope-function assumes that the user gives pattern-lists of length 99.

library(spatstat)
x <- rpoispp(100)
f <- ppm(x, i = Strauss(0.001))
sims <- simulate(f, nsim = 5)

envelope(x, pcf, simulate = sims)
#Error in envelopeEngine(X = X, fun = fun, simul = simrecipe, nsim = nsim,  : 
#  Number of simulations (99) exceeds number of point pattern datasets supplied

envelope(x, pcf, simulate = sims, nsim = length(sims))
# no error

R 3.2.1
spatstat 1.42.2.2

Make as.solist work for single object?

At the moment the following fails:

library(spatstat)
as.solist(cells)

The problem is in line 104 of solist.R.
However, in some functions it can be convenient to ask the user to supply either a single spatial object or a list of spatial objects and then make sure it is a solist (with either one or several components) before proceeding. I suggest to replace line 104 by

  if(!is.list(x) | is.sob(x))

which makes it work, and doesn't have any negative consequences that I can spot.

Error message related to nchar

A user reports that in spatstat 1.42-2, running under R 3.2.0, the following error message arises:

Error in prepareTitle(....): 4 arguments passed to .Internal(nchar) which requires 3

Multiple marks in lpp

In lpp a data.frame of marks is saved as a hyperframe in the internal ppx format. In plot.lpp we call as.ppp which generates an error since ppp doesn't allow a hyperframe of marks:

library(spatstat)
X <- chicago
marks(X) <- data.frame(m1 = marks(chicago), m2 = 0)
plot(X)
Error in `marks<-.ppp`(`*tmp*`, value = marks(X)) : 
  Hyperframes of marks are not supported in ppp objects; use ppx

Add argument to solist and as.solist?

In simulation algorithms we typically make a list of ppps and then assign names paste("Simulation", 1:n) and then call as.solist. Sometimes (runifpoispp(1, drop = FALSE)) the names are forgotten so they end up being "Component 1" etc. Given many return points in simulation code could it be convenient to have an argument to control the names in solist and as.solist? E.g.

as.solist(mylist, .NameTemplate = "Simulation")
solist(myobj1, myobj2, .NameTemplate = "My name")

rmh.ppm not working with fitted Lennard-Jones model

There appears to be a bug in translating the parameters from the ppm-object to the rmhmodel-object for the Lennard-Jones process.

set.seed(10)
xi <- rpoispp(50)
model <- ppm(xi~1, LennardJones(), rbord=0.1)
rmhmodel(model)

This throws the error ‘epsilon’ should be a single number. It seems the culprits are lines 24/25 in rmhmodel.ppm.R. The parameter sigma for rmh is taken by partial matching from the "irregular parameter" sigma0 of model (which already is not correct) and the parameter epsilon gets assigned NULL because no such partial match exists.

Methods for function head()

We could consider methods for head() for spatstat classes. At the moment head.default is dispatched for most classes and it doesn't do the right thing. E.g. cells is internally a list of length 5 so head(cells, n) with n>5 will incorrectly return a ppp containing the first 5 points of cells. A marked ppp has 6 elements so for e.g. Chorley it works as expected up to 6. Similarly with unmarked and marked psp objects you get at most either 4 or 5 segments in the result of head.

envelope() with fun=F3est

When I use envelope() with fun = F3est and specify rmax, then the estimated F-functions unexpectedly "jump" at the very last r-value.

sim <- rpoispp3(lambda = 500)
F.env <- envelope(Y = sim, fun = F3est, rmax = 0.1)
plot.envelope(F.env, xlim = c(0, 0.1))

Spatstat version: 1.47-0.005
R version: 3.3.1

FR: Don't error ppp when all coordinates are NA

I've got a situation where I'd like to feed all-NA coordinates to ppp (I have a loop where some subsets may be "empty" in the sense of not having any data).

The following works just as expected and accomplishes all I want (I later pixellate this and get the 0s out that I want)

ppp(xrange = 0:1, yrange = 0:1)

But this is an error:

ppp(x = NA_real_, y = NA_real_, xrange = 0:1, yrange = 0:1)

Error in ppp(x = NA_real_, y = NA_real_, xrange = 0:1, yrange = 0:1) :
all coordinate values are NA or NaN

I don't see a reason for the latter to error given the former works just fine (at worst, throw a warning).

Now, I need to throw a test into my code a la:

pixellate(if (all(is.na(xrange))) ppp(xrange = ...) else ppp(x = ....))

Which is considerably more dense/verbose/inscrutable

Mathematical operations on 'linim' and 'linfun' may be biased

Mathematical operations such as the mean and median, performed on objects of class 'linim' (pixel image on a linear network) and 'linfun' (function on a linear network), may give biased results because of the way that the network is sampled.

A fix is being investigated.

Question: why depend on >= 3.3.0?

I tried searching the news for why spatstat now depends on 3.3.0 or higher, but came up short.

I am trying to use it on a server where I don't have root privileges to upgrade R that runs 3.2.3... I lied and edited the DESCRIPTION so that it would install. Now I'm wondering what problems this might cause exactly -- if it's limited to a few functionalities, it probably won't cause any issues.

Thanks!

Feature Request: as.GridTopology.ppp

Hi, I've got a problem where I'd like to convert a ppp object to a GridTopology object in order to facilitate using splancs::spkernel2d.

Unfortunately I'm relying on sort of ad-hoc methods of creating equivalent ppp and GridTopology objects; it would be nice to have a formal method for converting between the two.

subfits incorrect for multitype replicated patterns

If a Gibbs model is fitted to replicated, multitype, point pattern data using mppm, and subfits is applied to this model, the resulting ppm objects have incorrect values of the fitted coefficients. Example:

XX <- as.solist(replicate(3, rthin(amacrine, 0.8), simplify=FALSE))
H <- hyperframe(X=XX)
M <- MultiStrauss(matrix(0.1, 2, 2), levels(marks(amacrine)))
fit <- mppm(X ~ 1, H, M)
coef(fit)
sapply(subfits(fit), coef)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.