Spatial Point Pattern analysis, model-fitting, simulation, tests

Spatial Point Pattern analysis, model-fitting, simulation, tests [R logo]

Help pages for package `spatstat' version 1.11-3

A B C D E F G H I J K L M N O P Q R S T U V misc

-- --

spatstat-package The Spatstat Package

-- --

%mark% Set or Reset the Marks in a Point Pattern

-- A --

affine | Apply Affine Transformation
affine.owin | Apply Affine Transformation To Window
affine.ppp | Apply Affine Transformation To Point Pattern
affine.psp | Apply Affine Transformation To Line Segment Pattern
allstats | Calculate four standard summary functions of a point pattern.
alltypes | Calculate Statistic for All Types in a Multitype Point Pattern
amacrine | Hughes' Amacrine Cell Data
anemones | Beadlet Anemones Data
angles.psp | Orientation Angles of Line Segments
anova.ppm | ANOVA for Fitted Point Process Models
ants | Harkness-Isham ants' nests data
append.psp | Combine Two Line Segment Patterns
applynbd | Apply Function to Every Neighbourhood in a Point Pattern
area.owin | Area of a Window
as.im | Convert to Pixel Image
as.mask | Pixel Image Approximation of a Window
as.matrix.im | Convert Pixel Image to Matrix
as.owin | Convert Data To Class owin
as.ppp | Convert Data To Class ppp
as.psp | Convert Data To Class psp
as.rectangle | Window Frame

-- B --

bdist.pixels | Distance to Boundary of Window
bdist.points | Distance to Boundary of Window
bei | Tropical rain forest trees
betacells | Beta Ganglion Cells in Cat Retina
bounding.box | Bounding Box of a Window or Point Pattern
bounding.box.xy | Convex Hull of Points
bramblecanes | Hutchings' Bramble Canes data

-- C --

cells | Biological Cells Point Pattern
centroid.owin | Centroid of a window
chorley | Chorley-Ribble Cancer Data
clickpoly | Interactively Define a Polygon
clickppp | Interactively Add Points
coef.ppm | Coefficients of Fitted Point Process Model
compatible.fv | Test Whether Two Function Objects Are Compatible
compatible.im | Test Whether Two Pixel Images Are Compatible
complement.owin | Take Complement of a Window
concatxy | Concatenate x,y Coordinate Vectors
contour.im | Contour plot of pixel image
convexhull.xy | Convex Hull of Points
copper | Berman-Huntington points and lines data
corners | Corners of a rectangle
crossdist | Pairwise distances
crossdist.default | Pairwise distances between two different sets of points
crossdist.ppp | Pairwise distances between two different point patterns
crossdist.psp | Pairwise distances between two different line segment patterns
crossing.psp | Crossing Points of Two Line Segment Patterns
cut.im | Convert Pixel Image from Numeric to Factor
cut.ppp | Convert Point Pattern Marks from Numeric to Factor

-- D --

data.ppm | Extract Original Data from a Fitted Point Process Model
default.dummy | Generate a Default Pattern of Dummy Points
demopat | Artificial Data Point Pattern
density.ppp | Kernel Smoothed Intensity of Point Pattern
density.psp | Kernel Smoothing of Line Segment Pattern
density.splitppp | Kernel Smoothed Intensity of Split Point Pattern
diagnose.ppm | Diagnostic Plots for Fitted Point Process Model
diameter | Diameter of a Window
DiggleGratton | Diggle-Gratton model
dilate.owin | Dilate a Window
dirichlet.weights | Compute Quadrature Weights Based on Dirichlet Tessellation
disc | Circular Window
distmap | Distance Map
distmap.owin | Distance Map of Window
distmap.ppp | Distance Map of Point Pattern
distmap.psp | Distance Map of Line Segment Pattern
dummy.ppm | Extract Dummy Points Used to Fit a Point Process Model
duplicated.ppp | Determine Duplicated Points in a Spatial Point Pattern

-- E --

eem | Exponential Energy Marks
empty.space | Estimate the empty space function F
endpoints.psp | Endpoints of Line Segment Pattern
envelope | Simulation envelopes of summary function
erode.owin | Erode a Window
eroded.areas | Areas of Morphological Erosions
eval.fv | Evaluate Expression Involving Functions
eval.im | Evaluate Expression Involving Pixel Images
ewcdf | Weighted Empirical Cumulative Distribution Function
expand.owin | Expand Window By Factor

-- F --

fasp.object | Function Arrays for Spatial Patterns
Fest | Estimate the empty space function F
finpines | Pine saplings in Finland.
fitted.ppm | Fitted Conditional Intensity for Point Process Model
fv.object | Data Frames of Function Values

-- G --

ganglia | Beta Ganglion Cells in Cat Retina, Old Version
Gcross | Multitype Nearest Neighbour Distance Function (i-to-j)
Gdot | Multitype Nearest Neighbour Distance Function (i-to-any)
Gest | Nearest Neighbour Distance Function G
Geyer | Geyer's Saturation Point Process Model
Gmulti | Marked Nearest Neighbour Distance Function
gridcenters | Rectangular grid of points
gridcentres | Rectangular grid of points
gridweights | Compute Quadrature Weights Based on Grid Counts

-- H --

hamster | Aherne's hamster tumour data
harmonic | Basis for Harmonic Functions
hist.im | Histogram of Pixel Values in an Image
humberside | Humberside Data on Childhood Leukaemia and Lymphoma

-- I --

identify.ppp | Identify Points in a Point Pattern
Iest | Estimate the I-function
im | Create a Pixel Image Object
im.object | Class of Images
image.im | Plot a Pixel Image
inside.owin | Test Whether Points Are Inside A Window
interp.im | Interpolate a Pixel Image
intersect.owin | Intersection or Union of Two Windows
is.im | Test Whether An Object Is A Pixel Image
is.marked | Test Whether Marks Are Present
is.marked.ppm | Test Whether A Point Process Model is Marked
is.marked.ppp | Test Whether A Point Pattern is Marked
is.multitype | Test whether Object is Multitype
is.multitype.ppm | Test Whether A Point Process Model is Multitype
is.multitype.ppp | Test Whether A Point Pattern is Multitype
is.owin | Test Whether An Object Is A Window
is.ppm | Test Whether An Object Is A Fitted Point Process Model
is.ppp | Test Whether An Object Is A Point Pattern
is.subset.owin | Determine Whether One Window is Contained In Another

-- J --

japanesepines | Japanese Pines Point Pattern
Jcross | Multitype J Function (i-to-j)
Jdot | Multitype J Function (i-to-any)
Jest | Estimate the J-function
Jmulti | Marked J Function

-- K --

kaplan.meier | Kaplan-Meier Estimator using Histogram Data
Kcross | Multitype K Function (Cross-type)
Kcross.inhom | Inhomogeneous Cross K Function
Kdot | Multitype K Function (i-to-any)
Kdot.inhom | Inhomogeneous Multitype K Dot Function
Kest | K-function
Kest.fft | K-function using FFT
Kinhom | Inhomogeneous K-function
km.rs | Kaplan-Meier and Reduced Sample Estimator using Histograms
Kmeasure | Reduced Second Moment Measure
Kmulti | Marked K-Function
ks.test.ppm | Kolmogorov-Smirnov Test for Point Process Model

-- L --

lansing | Lansing Woods Point Pattern
lengths.psp | Lengths of Line Segments
LennardJones | The Lennard-Jones Potential
letterR | Window in Shape of Letter R
levelset | Level Set of a Pixel Image
lgcp.estK | Fit a Log-Gaussian Cox Point Process by Minimum Contrast
longleaf | Longleaf Pines Point Pattern
lurking | Lurking variable plot

-- M --

markcorr | Mark Correlation Function
markstat | Summarise Marks in Every Neighbourhood in a Point Pattern
matclust.estK | Fit the Matern Cluster Point Process by Minimum Contrast
mean.im | Mean Pixel Value in an Image
midpoints.psp | Midpoints of Line Segment Pattern
mincontrast | Method of Minimum Contrast
multiplicity.ppp | Count Multiplicity of Duplicate Points
MultiStrauss | The Multitype Strauss Point Process Model
MultiStraussHard | The Multitype/Hard Core Strauss Point Process Model

-- N --

nbextras | Point Patterns of New Brunswick Forest Fires
nbfires | Point Patterns of New Brunswick Forest Fires
nbw.rect | Point Patterns of New Brunswick Forest Fires
nearest.neighbour | Nearest Neighbour Distance Function G
nearest.raster.point | Find Pixel Nearest to a Given Point
nncorr | Nearest-Neighbour Correlation of Marked Point Pattern
nncross | Nearest Neighbour in Another Point Pattern
nndist | Nearest neighbour distances
nnwhich | Nearest neighbour
nztrees | New Zealand Trees Point Pattern

-- O --

Ord | Generic Ord Interaction model
ord.family | Ord Interaction Process Family
OrdThresh | Ord's Interaction model
owin | Create a Window
owin.object | Class owin

-- P --

pairdist | Pairwise distances
pairdist.default | Pairwise distances
pairdist.ppp | Pairwise distances
pairdist.psp | Pairwise distances between line segments
PairPiece | The Piecewise Constant Pairwise Interaction Point Process Model
pairsat.family | Saturated Pairwise Interaction Point Process Family
Pairwise | Generic Pairwise Interaction model
pairwise.family | Pairwise Interaction Process Family
pcf | Pair Correlation Function
pcf.fasp | Pair Correlation Function obtained from array of K functions
pcf.fv | Pair Correlation Function obtained from K Function
pcf.ppp | Pair Correlation Function of Point Pattern
persp.im | Perspective Plot of Pixel Image
plot.diagppm | Diagnostic Plots for Fitted Point Process Model
plot.fasp | Plot a Function Array
plot.fv | Plot Function Valuesn
plot.im | Plot a Pixel Image
plot.listof | Plot a List of Things
plot.owin | Plot a Spatial Window
plot.plotppm | Plot a plotppm Object Created by plot.ppm
plot.ppm | plot a Fitted Point Process Model
plot.ppp | plot a Spatial Point Pattern
plot.psp | plot a Spatial Line Segment Pattern
plot.quad | plot a Spatial Quadrature Scheme
plot.splitppp | Plot a List of Point Patterns
Poisson | Poisson Point Process Model
ppm | Fit Point Process Model to Data
ppm.object | Class of Fitted Point Process Models
ppp | Create a Point Pattern
ppp.object | Class of Point Patterns
pppdist | Optimal Match Between Two Point Patterns
predict.ppm | Prediction from a Fitted Point Process Model
print.im | Print Brief Details of an Image
print.owin | Print Brief Details of a Spatial Window
print.ppm | Print a Fitted Point Process Model
print.ppp | Print Brief Details of a Point Pattern Dataset
print.psp | Print Brief Details of a Line Segment Pattern Dataset
print.quad | Print a Quadrature Scheme
print.summary.im | Summarizing a Pixel Image
print.summary.ppm | Summarizing a Fitted Point Process Model
print.summary.quad | Summarizing a Quadrature Scheme
profilepl | Profile Maximum Pseudolikelihood
progressreport | Print Progress Reports
psp | Create a Line Segment Pattern
psp.object | Class of Line Segment Patterns

-- Q --

qqplot.ppm | Q-Q Plot of Residuals from Fitted Point Process Model
quad.object | Class of Quadrature Schemes
quad.ppm | Extract Quadrature Scheme Used to Fit a Point Process Model
quadrat.test | Chi-Squared Dispersion Test for Spatial Point Pattern Based on Quadrat Counts
quadratcount | Quadrat counting for a point pattern
quadscheme | Generate a Quadrature Scheme from a Point Pattern
quantile.im | Sample Quantiles of Pixel Image

-- R --

raster.x | Cartesian Coordinates for a Pixel Raster
raster.y | Cartesian Coordinates for a Pixel Raster
rcell | Simulate Baddeley-Silverman Cell Process
reach | Interaction Distance of a Point Process
reduced.sample | Reduced Sample Estimator using Histogram Data
redwood | California Redwoods Point Pattern (Ripley's Subset)
redwoodfull | California Redwoods Point Pattern (Entire Dataset)
rescale | Convert dataset to another unit of length
rescale.owin | Convert Window to Another Unit of Length
rescale.ppp | Convert Point Pattern to Another Unit of Length
rescale.psp | Convert Line Segment Pattern to Another Unit of Length
rescue.rectangle | Convert Window Back To Rectangle
residuals.ppm | Residuals for Fitted Point Process Model
residualspaper | Data and Code From JRSS Discussion Paper on Residuals
ripras | Estimate window from points alone
rlabel | Random Re-Labelling of Point Pattern
rMatClust | Simulate Matern Cluster Process
rMaternI | Simulate Matern Model I
rMaternII | Simulate Matern Model II
rmh | Simulate point patterns using the Metropolis-Hastings algorithm.
rmh.default | Simulate Point Process Models using the Metropolis-Hastings Algorithm.
rmh.ppm | Simulate from a Fitted Point Process Model
rmhcontrol | Set Control Parameters for Metropolis-Hastings Algorithm.
rmhmodel | Define Point Process Model for Metropolis-Hastings Simulation.
rmhmodel.default | Build Point Process Model for Metropolis-Hastings Simulation.
rmhmodel.list | Define Point Process Model for Metropolis-Hastings Simulation.
rmhmodel.ppm | Interpret Fitted Model for Metropolis-Hastings Simulation.
rmhstart | Determine Initial State for Metropolis-Hastings Simulation.
rmpoint | Generate N Random Multitype Points
rmpoispp | Generate Multitype Poisson Point Pattern
rNeymanScott | Simulate Neyman-Scott Process
rotate | Rotate
rotate.owin | Rotate a Window
rotate.ppp | Rotate a Point Pattern
rotate.psp | Rotate a Line Segment Pattern
rpoint | Generate N Random Points
rpoisline | Generate Poisson Random Line Process
rpoispp | Generate Poisson Point Pattern
rshift | Random Shift
rshift.ppp | Randomly Shift a Point Pattern
rshift.psp | Randomly Shift a Line Segment Pattern
rshift.splitppp | Randomly Shift a List of Point Patterns
rSSI | Simulate Simple Sequential Inhibition
rstrat | Simulate Stratified Random Point Pattern
rStrauss | Perfect Simulation of the Strauss Process
rsyst | Simulate systematic random point pattern
rthin | Random Thinning
rThomas | Simulate Thomas Process
runifdisc | Generate N Uniform Random Points in a Disc
runifpoint | Generate N Uniform Random Points

-- S --

Saturated | Saturated Pairwise Interaction model
scanpp | Read Point Pattern From Data File
selfcrossing.psp | Crossing Points in a Line Segment Pattern
setcov | Set Covariance of a Window
setmarks | Set or Reset the Marks in a Point Pattern
shift | Apply Vector Translation
shift.im | Apply Vector Translation To Pixel Image
shift.owin | Apply Vector Translation To Window
shift.ppp | Apply Vector Translation To Point Pattern
shift.psp | Apply Vector Translation To Line Segment Pattern
simdat | Simulated Point Pattern
Softcore | The Soft Core Point Process Model
solutionset | Evaluate Logical Expression Involving Pixel Images and Return Region Where Expression is True
spatstat | The Spatstat Package
spatstat.options | Internal Options in Spatstat Package
split.ppp | Divide Point Pattern into Sub-patterns
spokes | Spokes pattern of dummy points
spruces | Spruces Point Pattern
square | Square Window
Strauss | The Strauss Point Process Model
StraussHard | The Strauss / Hard Core Point Process Model
subset.fasp | Extract Subset of Function Array
subset.fv | Extract Subset of Function Values
subset.im | Extract Subset of Image
subset.ppp | Extract or Replace Subset of Point Pattern
subset.psp | Extract Subset of Line Segment Pattern
suffstat | Sufficient Statistic of Point Process Model
summary.im | Summarizing a Pixel Image
summary.listof | Summary of a List of Things
summary.owin | Summary of a Spatial Window
summary.ppm | Summarizing a Fitted Point Process Model
summary.ppp | Summary of a Point Pattern Dataset
summary.psp | Summary of a Line Segment Pattern Dataset
summary.quad | Summarizing a Quadrature Scheme
summary.splitppp | Summary of a Split Point Pattern
superimpose | Superimpose Several Point Patterns
swedishpines | Swedish Pines Point Pattern

-- T --

thomas.estK | Fit the Thomas Point Process by Minimum Contrast
trim.rectangle | Cut margins from rectangle

-- U --

union.owin | Intersection or Union of Two Windows
union.quad | Union of Data and Dummy Points
unique.ppp | Extract Unique Points from a Spatial Point Pattern
unit.square | Square Window
units | Name for Unit of Length
unmark | Remove Marks from a Marked Point Pattern
update.ppm | Update a Fitted Point Process Model

-- V --

vcov.ppm | Variance-Covariance Matrix for a Fitted Point Process Model
vertices | Vertices of a Window

-- misc --

[.fasp | Extract Subset of Function Array
[.fv | Extract Subset of Function Values
[.im | Extract Subset of Image
[.listof | Extract or Replace Subset of a List of Things
[.ppp | Extract or Replace Subset of Point Pattern
[.psp | Extract Subset of Line Segment Pattern
[.splitppp | Extract or Replace Sub-Patterns


The Spatstat Package

Description

This is a summary of the features of spatstat, a package in R for the statistical analysis of spatial point patterns.

Details

spatstat is a package for the statistical analysis of spatial data. Currently, it deals mainly with the analysis of patterns of points in the plane. The points may carry `marks', and the spatial region in which the points were recorded may have arbitrary shape.

The package supports

  • creation, manipulation and plotting of point patterns
  • exploratory data analysis
  • simulation of point process models
  • parametric model-fitting
  • hypothesis tests and diagnostics

The point process models to be fitted may be quite general Gibbs/Markov models; they may include spatial trend, dependence on covariates, and interpoint interactions of any order (i.e. not restricted to pairwise interactions). Models are specified by a formula in the R language, and are fitted using a single function ppm analogous to lm and glm. It is also possible to fit cluster process models by the method of minimum contrast.

Getting Started

Type demo(spatstat) for an overall demonstration of the package.

For a readable introduction to spatstat, see the paper by Baddeley and Turner (2005a), available online.

Type demo(data) to see all the datasets available in the package.

FUNCTIONS AND DATASETS

Following is a summary of the main functions and datasets in the spatstat package. Alternatively an alphabetical list of all functions and datasets is available by typing library(help=spatstat).

For further information on any of these, type help(name) where name is the name of the function or dataset.

Type demo(data) to see all the datasets installed with the package.

CONTENTS:

I. | Creating and manipulating data
II. | Exploratory Data Analysis
III. | Model fitting (cluster models)
IV. | Model fitting (Gibbs models)
V. | Tests and diagnostics
VI. | Documentation

I. CREATING AND MANIPULATING DATA

To create a point pattern:

ppp | create a point pattern from (x,y) and window information
 | ppp(x, y, xlim, ylim) for rectangular window
 | ppp(x, y, poly) for polygonal window
 | ppp(x, y, mask) for binary image window
as.ppp | convert other types of data to a ppp object
clickppp | interactively add points to a plot
setmarks, %mark% | attach/reassign marks to a point pattern

To simulate a random point pattern:

runifpoint | generate n independent uniform random points
rpoint | generate n independent random points
rmpoint | generate n independent multitype random points
rpoispp | simulate the (in)homogeneous Poisson point process
rmpoispp | simulate the (in)homogeneous multitype Poisson point process
runifdisc | generate n independent uniform random points in disc
rstrat | stratified random sample of points
rsyst | systematic random sample of points
rMaternI | simulate the Mat'ern Model I inhibition process
rMaternII | simulate the Mat'ern Model II inhibition process
rSSI | simulate Simple Sequential Inhibition process
rStrauss | simulate Strauss process (perfect simulation)
rNeymanScott | simulate a general Neyman-Scott process
rMatClust | simulate the Mat'ern Cluster process
rThomas | simulate the Thomas process
rthin | random thinning
rcell | simulate the Baddeley-Silverman cell process
rmh | simulate Gibbs point process using Metropolis-Hastings

To randomly change an existing point pattern:

rlabel | random (re)labelling of a multitype point pattern
rshift | random shift (including toroidal shifts)

Standard point pattern datasets:

Remember to say data(bramblecanes) etc.

amacrine | Austin Hughes' rabbit amacrine cells
anemones | Upton-Fingleton sea anemones data
ants | Harkness-Isham ant nests data
bei | Tropical rainforest trees
betacells | Waessle et al. cat retinal ganglia data
bramblecanes | Bramble Canes data
cells | Crick-Ripley biological cells data
chorley | Chorley-Ribble cancer data
copper | Berman-Huntington copper deposits data
demopat | Synthetic point pattern
finpines | Finnish Pines data
hamster | Aherne's hamster tumour data
humberside | North Humberside childhood leukaemia data
japanesepines | Japanese Pines data
lansing | Lansing Woods data
longleaf | Longleaf Pines data
nztrees | Mark-Esler-Ripley trees data
nbfires | New Brunswick fires data
redwood | Strauss-Ripley redwood saplings data
redwoodfull | Strauss redwood saplings data (full set)
residualspaper | Data from Baddeley et al (2005)
simdat | Simulated point pattern (inhomogeneous, with interaction)
spruces | Spruce trees in Saxonia
swedishpines | Strand-Ripley swedish pines data

To manipulate a point pattern:

plot.ppp | plot a point pattern (e.g. plot(X))
subset.ppp, "[.ppp" | extract or replace a subset of a point pattern
 | pp[subset]
 | pp[, subwindow]
superimpose | superimpose any number of point patterns
cut.ppp | discretise the marks in a point pattern
unmark | remove marks
setmarks | attach marks or reset marks
split.ppp | divide pattern into sub-patterns
rotate | rotate pattern
shift | translate pattern
affine | apply affine transformation
density.ppp | kernel smoothing
identify.ppp | interactively identify points
unique.ppp | remove duplicate points
duplicated.ppp | determine which points are duplicates

See spatstat.options to control plotting behaviour.

To create a window:

An object of class "owin" describes a spatial region (a window of observation).

owin | Create a window object
 | owin(xlim, ylim) for rectangular window
 | owin(poly) for polygonal window
 | owin(mask) for binary image window
as.owin | Convert other data to a window object
square | make a square window
disc | make a circular window
ripras | Ripley-Rasson estimator of window, given only the points
letterR | polygonal window in the shape of the {sf R} logo

To manipulate a window:

plot.owin | plot a window.
 | plot(W)
bounding.box | Find a tight bounding box for the window
erode.owin | erode window by a distance r
dilate.owin | dilate window by a distance r
complement.owin | invert (swap inside and outside)
rotate | rotate window
shift | translate window
affine | apply affine transformation

Digital approximations:

as.mask | Make a discrete pixel approximation of a given window
nearest.raster.point | map continuous coordinates to raster locations
raster.x | raster x coordinates
raster.y | raster y coordinates

See spatstat.options to control the approximation

Geometrical computations with windows:

intersect.owin | intersection of two windows
union.owin | union of two windows
inside.owin | determine whether a point is inside a window
area.owin | compute window's area
diameter | compute window frame's diameter
eroded.areas | compute areas of eroded windows
bdist.points | compute distances from data points to window boundary
bdist.pixels | compute distances from all pixels to window boundary
distmap.owin | distance transform image
centroid.owin | compute centroid (centre of mass) of window
is.subset.owin | determine whether one window contains another

Pixel images: An object of class "im" represents a pixel image. Such objects are returned by some of the functions in spatstat including Kmeasure, setcov and density.ppp.
im | create a pixel image
as.im | convert other data to a pixel image
as.matrix.im | convert pixel image to matrix
plot.im | plot a pixel image on screen as a digital image
contour.im | draw contours of a pixel image
persp.im | draw perspective plot of a pixel image
[.im | extract subset of pixel image
shift.im | apply vector shift to pixel image
X | print very basic information about image X
summary(X) | summary of image X
hist.im | histogram of image
mean.im | mean pixel value of image
quantile.im | quantiles of image
cut.im | convert numeric image to factor image
is.im | test whether an object is a pixel image
compatible.im | test whether two images have compatible dimensions
eval.im | evaluate any expression involving images
levelset | level set of an image
solutionset | region where an expression is true

Line segment patterns

An object of class "psp" represents a pattern of line segments.
psp | create a line segment pattern
as.psp | convert other data into a line segment pattern
plot.psp | plot a line segment pattern
print.psp | print basic information
summary.psp | print summary information
subset.psp |
[.psp | extract a subset of a line segment pattern
midpoints.psp | compute the midpoints of line segments
endpoints.psp | extract the endpoints of line segments
lengths.psp | compute the lengths of line segments
angles.psp | compute the orientation angles of line segments
rotate.psp | rotate a line segment pattern
shift.psp | shift a line segment pattern
affine.psp | apply an affine transformation
distmap.psp | compute the distance map of a line segment pattern
density.psp | kernel smoothing of line segments
selfcrossing.psp | find crossing points between line segments
crossing.psp | find crossing points between two line segment patterns

II. EXPLORATORY DATA ANALYSIS

Inspection of data:
summary(X) | print useful summary of point pattern X
X | print basic description of point pattern X
any(duplicated(X)) | check for duplicated points in pattern X

Summary statistics for a point pattern:
quadratcount | Quadrat counts
Fest | empty space function F
Gest | nearest neighbour distribution function G
Kest | Ripley's K-function
Jest | J-function J = (1-G)/(1-F)
pcf | pair correlation function
Kinhom | K for inhomogeneous point patterns
Kest.fft | fast K-function using FFT for large datasets
Kmeasure | reduced second moment measure
allstats | all four functions F, G, J, K
envelope | simulation envelopes for a summary function

Related facilities:
plot.fv | plot a summary function
eval.fv | evaluate any expression involving summary functions
nndist | nearest neighbour distances
nnwhich | find nearest neighbours
pairdist | distances between all pairs of points
crossdist | distances between points in two patterns
nncross | nearest neighbours between two point patterns
exactdt | distance from any location to nearest data point
distmap | distance map image
density.ppp | kernel smoothed density

Summary statistics for a multitype point pattern: A multitype point pattern is represented by an object X of class "ppp" with a component X$marks which is a factor.
Gcross,Gdot,Gmulti | multitype nearest neighbour distributions Gij, Gi.
Kcross,Kdot, Kmulti | multitype K-functions Kij, Ki.
Jcross,Jdot,Jmulti | multitype J-functions Jij,Ji.
alltypes | estimates of the above for all i,j pairs
Iest | multitype I-function
Kcross.inhom,Kdot.inhom | inhomogeneous counterparts of Kcross, Kdot

Summary statistics for a marked point pattern: A marked point pattern is represented by an object X of class "ppp" with a component X$marks. The entries in the vector X$marks may be numeric, complex, string or any other atomic type.
markcorr | mark correlation function
Gmulti | multitype nearest neighbour distribution
Kmulti | multitype K-function
Jmulti | multitype J-function

Alternatively use cut.ppp to convert a marked point pattern to a multitype point pattern.

Programming tools:
applynbd | apply function to every neighbourhood
 | in a point pattern
pppdist | find the optimal match between two point patterns

III. MODEL FITTING (CLUSTER MODELS)

Several kinds of clustered point process models can be fitted using the Method of Minimum Contrast.

thomas.estK | fit the Thomas process model
matclust.estK | fit the Matern Cluster process model
lgcp.estK | fit a log-Gaussian Cox process model
mincontrast | general algorithm for fitting models
 | by the method of minimum contrast

The Thomas and Matern models can also be simulated, using rThomas and rMatClust respectively.

IV. MODEL FITTING (GIBBS MODELS)

For a detailed explanation of how to fit models to point pattern data using spatstat, see Baddeley and Turner (2005b).

To fit a Gibbs point process model:

Model fitting in spatstat is performed mainly by the function ppm. Its result is an object of class "ppm".

Manipulating the fitted model:

plot.ppm | Plot the fitted model
predict.ppm | Compute the spatial trend
 | and conditional intensity
 | of the fitted point process model
coef.ppm | Extract the fitted model coefficients
fitted.ppm | Compute fitted conditional intensity at quadrature points
update.ppm | Update the fit
vcov.ppm | Variance-covariance matrix of estimates
rmh.ppm | Simulate from fitted model
print.ppm | Print basic information about a fitted model
summary.ppm | Summarise a fitted model
anova.ppm | Analysis of deviance

See spatstat.options to control plotting of fitted model.

To specify a point process model:

The first order ``trend'' of the model is written as an R language formula.

~1 | No trend (stationary)
~x | First order term λ(x,y) = exp(α + β x)
 | where x,y are Cartesian coordinates
~polynom(x,y,3) | Log-cubic polynomial trend
~harmonic(x,y,2) | Log-harmonic polynomial trend

The higher order (``interaction'') components are described by an object of class "interact". Such objects are created by:
Poisson() | the Poisson point process
Strauss() | the Strauss process
StraussHard() | the Strauss/hard core point process
Softcore() | pairwise interaction, soft core potential
PairPiece() | pairwise interaction, piecewise constant
DiggleGratton() | Diggle-Gratton potential
LennardJones() | Lennard-Jones potential
Pairwise() | pairwise interaction, user-supplied potential
Geyer() | Geyer's saturation process
Saturated() | Saturated pair model, user-supplied potential
OrdThresh() | Ord process, threshold potential
Ord() | Ord model, user-supplied potential
MultiStrauss() | multitype Strauss process
MultiStraussHard() | multitype Strauss/hard core process

Finer control over model fitting:

A quadrature scheme is represented by an object of class "quad".

quadscheme | generate a Berman-Turner quadrature scheme
 | for use by ppm
default.dummy | default pattern of dummy points
gridcentres | dummy points in a rectangular grid
rstrat | stratified random dummy pattern
spokes | radial pattern of dummy points
corners | dummy points at corners of the window
gridweights | quadrature weights by the grid-counting rule
dirichlet.weights | quadrature weights are Dirichlet tile areas
plot(Q) | plot quadrature scheme Q
print(Q) | print basic information about quadrature scheme Q
summary(Q) | summary of quadrature scheme Q

Simulation and goodness-of-fit for fitted models:

rmh.ppm | simulate realisations of a fitted model
envelope | compute simulation envelopes for a fitted model

V. TESTS AND DIAGNOSTICS

Classical hypothesis tests:

quadrat.test | chi^2 goodness-of-fit test on quadrat counts
envelope | critical envelope for Monte Carlo test of goodness-of-fit
anova.ppm | Analysis of Deviance for point process models

Diagnostic plots:

Residuals for a fitted point process model, and diagnostic plots based on the residuals, were introduced in Baddeley et al (2005).

Type demo(diagnose) for a demonstration of the diagnostics features.

diagnose.ppm | diagnostic plots for spatial trend
qqplot.ppm | diagnostic plot for interpoint interaction
residualspaper | examples from Baddeley et al (2005)

VI. DOCUMENTATION

The online manual entries are quite detailed and should be consulted first for information about a particular function.

The paper by Baddeley and Turner (2005a) describes the package. Baddeley and Turner (2005b) is a more detailed explanation of how to fit point process models to data.

Type citation("spatstat") to get these references.

Licence

This library and its documentation are usable under the terms of the "GNU General Public License", a copy of which is distributed with the package.

Acknowledgements

Marie-Colette van Lieshout, Kasper Klitgaard Berthelsen and Dominic Schuhmacher made substantial contributions of code. Additional contributions by Colin Beale, Brad Biggerstaff, Florent Bonneu, Jianbao Chen, Y.C. Chin, Peter Diggle, Stephen Eglen, Agnes Gault, Marc Genton, Pavel Grabarnik, C. Graf, Ute Hahn, Mandy Hering, Martin Bogsted Hansen, Martin Hazelton, Kurt Hornik, Robert John-Chandran, Jorge Mateu, Jesper Moller, Linda Stougaard Nielsen, Evgeni Parilov, Matt Reiter, Brian Ripley, Barry Rowlingson, Aila Sarkka, Katja Schladitz, Bryan Scott, Malte Spiess, Mark Stevenson, P. Surovy, Berwin Turlach, Andrew van Burgel and Selene Wong.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A. and Turner, R. (2005a) Spatstat: an R package for analyzing spatial point patterns. Journal of Statistical Software 12:6, 1–42. URL: www.jstatsoft.org, ISSN: 1548-7660.

Baddeley, A. and Turner, R. (2005b) Modelling spatial point patterns in R. In: A. Baddeley, P. Gregori, J. Mateu, R. Stoica, and D. Stoyan, editors, Case Studies in Spatial Point Pattern Modelling, Lecture Notes in Statistics number 185. Pages 23–74. Springer-Verlag, New York, 2006. ISBN: 0-387-28311-0.

Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005) Residual analysis for spatial point processes. Journal of the Royal Statistical Society, Series B 67, 617–666.

[Package spatstat version 1.11-3 Index]


Apply Affine Transformation

Description

Applies any affine transformation of the plane (linear transformation plus vector shift) to a plane geometrical object, such as a point pattern or a window.

Usage

  affine(X, ...)

Arguments

X | Any suitable dataset representing a two-dimensional object, such as a point pattern (object of class "ppp"), or a window (object of class "owin").
... | Arguments determining the affine transformation.

Details

This is generic. Methods are provided for point patterns (affine.ppp) and windows (affine.owin).

Value

Another object of the same type, representing the result of applying the affine transformation.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

affine.ppp, affine.owin, rotate, shift


Apply Affine Transformation To Window

Description

Applies any affine transformation of the plane (linear transformation plus vector shift) to a window.

Usage

  ## S3 method for class 'owin':
  affine(X, mat=diag(c(1,1)), vec=c(0,0), ...)

Arguments

X | Window (object of class "owin").
mat | Matrix representing a linear transformation.
vec | Vector of length 2 representing a translation.
... | Ignored

Details

The window is subjected first to the linear transformation represented by mat (multiplying on the left by mat), and then the result is translated by the vector vec.

The argument mat must be a nonsingular 2 * 2 matrix.

This is a method for the generic function affine.

Value

Another window (of class "owin") representing the result of applying the affine transformation.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

affine, affine.ppp, rotate, shift

Examples

  # shear transformation
  X <- affine(owin(), matrix(c(1,0,0.6,1),ncol=2))
  ## Not run:
  plot(X)

## End(Not run)


Apply Affine Transformation To Point Pattern

Description

Applies any affine transformation of the plane (linear transformation plus vector shift) to a point pattern.

Usage

 ## S3 method for class 'ppp':
 affine(X, mat=diag(c(1,1)), vec=c(0,0), ...)

Arguments

X | Point pattern (object of class "ppp").
mat | Matrix representing a linear transformation.
vec | Vector of length 2 representing a translation.
... | Ignored

Details

The point pattern, and its window, are subjected first to the linear transformation represented by mat (multiplying on the left by mat), and are then translated by the vector vec.

The argument mat must be a nonsingular 2 * 2 matrix.

This is a method for the generic function affine.

Value

Another point pattern (of class "ppp") representing the result of applying the affine transformation.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

affine, affine.owin, rotate, shift

Examples

  data(cells)
  # shear transformation
  X <- affine(cells, matrix(c(1,0,0.6,1),ncol=2))
  ## Not run:
  plot(X)
  # rescale y coordinates by factor 1.3
  plot(affine(cells, diag(c(1,1.3))))

## End(Not run)


Apply Affine Transformation To Line Segment Pattern

Description

Applies any affine transformation of the plane (linear transformation plus vector shift) to a line segment pattern.

Usage

 ## S3 method for class 'psp':
 affine(X, mat=diag(c(1,1)), vec=c(0,0), ...)

Arguments

X | Line Segment pattern (object of class "psp").
mat | Matrix representing a linear transformation.
vec | Vector of length 2 representing a translation.
... | Ignored

Details

The line segment pattern, and its window, are subjected first to the linear transformation represented by mat (multiplying on the left by mat), and are then translated by the vector vec.

The argument mat must be a nonsingular 2 * 2 matrix.

This is a method for the generic function affine.

Value

Another line segment pattern (of class "psp") representing the result of applying the affine transformation.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

affine, affine.owin, affine.ppp, rotate, shift

Examples

  oldpar <- par(mfrow=c(2,1))
  X <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
  plot(X, main="original")
  # shear transformation
  Y <- affine(X, matrix(c(1,0,0.6,1),ncol=2))
  plot(Y, "transformed")
  par(oldpar)
  #
  # rescale y coordinates by factor 0.2
  affine(X, diag(c(1,0.2)))


Calculate four standard summary functions of a point pattern.

Description

Calculates the F, G, J, and K summary functions for an unmarked point pattern. Returns them as a function array (of class "fasp", see fasp.object).

Usage

  allstats(pp, ..., dataname=NULL, verb=FALSE)

Arguments

pp | The observed point pattern, for which summary function estimates are required. An object of class "ppp". It must not be marked.
... | Optional arguments passed to the summary functions Fest, Gest, Jest and Kest.
dataname | A character string giving an optional (alternative) name for the point pattern.
verb | A logical value meaning ``verbose''. If TRUE, progress reports are printed during calculation.

Details

This computes four standard summary statistics for a point pattern: the empty space function F(r), nearest neighbour distance distribution function G(r), van Lieshout-Baddeley function J(r) and Ripley's function K(r). The real work is done by Fest, Gest, Jest and Kest respectively. Consult the help files for these functions for further information about the statistical interpretation of F, G, J and K.

If verb is TRUE, then ``progress reports'' (just indications of completion) are printed out when the calculations are finished for each of the four function types.

The overall title of the array of four functions (for plotting by plot.fasp) will be formed from the argument dataname. If this is not given, it defaults to the expression for pp given in the call to allstats.

Value

A function array (an object of class "fasp", see fasp.object). This can be plotted using plot.fasp.
The function array has dimensions 2 * 2 with the entries at positions [1,1], [1,2], [2,1] and [2,2] representing F(r), G(r), J(r) and K(r) respectively.
Each function entry fns[[i]] retains the format of the output of the relevant estimating routine Fest, Gest, Jest or Kest.
The default formulae for plotting these functions are cbind(km,theo) ~ r for F, G, and J, and cbind(trans,theo) ~ r for K.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

plot.fasp, fasp.object, Fest, Gest, Jest, Kest, alltypes

Examples

        data(swedishpines)
        a <- allstats(swedishpines,dataname="Swedish Pines")
        ## Not run:
        plot(a)
        plot(a, subset=list("r<=15","r<=15","r<=15","r<=50"))

## End(Not run)


Calculate Statistic for All Types in a Multitype Point Pattern

Description

Given a marked point pattern, this computes the estimates of a selected summary function (F,G, J or K) of the pattern, for all possible combinations of marks. It returns these functions in a list (an object of class "fasp") amenable to plotting by plot.fasp().

Usage

  alltypes(pp, fun="K",dataname=NULL,verb=FALSE)

Arguments

pp | The observed point pattern, for which summary function estimates are required. An object of class "ppp". If the pattern is not marked, the resulting ``array'' has dimensions 1 x 1.
fun | Character string indicating the summary function required. Options are "F", "G", "J", "K", "Gcross", "Jcross", "Kcross", "Gdot", "Jdot", "Kdot".
dataname | Character string giving an optional (alternative) name to the point pattern, different from what is given in the call. This name, if supplied, may be used by plot.fasp() in forming the title of the plot. If not supplied it defaults to the parsing of the argument supplied as pp in the call.
verb | Logical value, meaning ``verbose''. If verb is true then terse ``progress reports'' (just the values of the mark indices) are printed out when the calculations for that combination of marks are completed.

Details

This routine is a convenient way to analyse the dependence between types in a multitype point pattern. Suppose that the points have possible types 1,2,...,m and let X[i] denote the pattern of points of type i only.

If fun="F" then this routine calculates, for each possible type i, an estimate of the Empty Space Function F_i(r) of X[i]. See Fest for explanation of the empty space function.

If fun is "Gcross", "Jcross" or "Kcross", the routine calculates, for each pair of types (i,j), an estimate of the ``i-toj'' cross-type function G[i,j](r), J[i,j](r) or K[i,j](r) respectively describing the dependence between X[i] and X[j]. See Gcross, Jcross or Kcross respectively for explanation of these functions.

If fun is "Gdot", "Jdot" or "Kdot", the routine calculates, for each type i, an estimate of the ``i-to-any'' dot-type function G[i.](r), J[i.](r) or K[i.](r) respectively describing the dependence between X[i] and X. See Gdot, Jdot or Kdot respectively for explanation of these functions.

The letters "G", "J" and "K" are interpreted as abbreviations for "Gcross", "Jcross" and "Kcross" respectively, assumin the point pattern is marked. If the point pattern is unmarked, the appropriate function Fest, Jest or Kest is invoked instead.

Value

A function array (an object of class "fasp", see fasp.object). This can be plotted using plot.fasp.
If fun="F", the function array has dimensions m * 1 where m is the number of different marks in the point pattern. The entry at position [i,1] in this array is the result of applying Fest to the points of type i only.
If fun is "Gdot", "Jdot" or "Kdot", the function array again has dimensions m * 1. The entry at position [i,1] in this array is the result of Gdot(pp, i) or Jdot(pp, i) or Kdot(pp, i) respectively.
If fun is "Gcross", "Jcross" or "Kcross", (or their abbreviations "G", "J" or "K"), the function array has dimensions m * m. The [i,j] entry of the function array (for i != j) is the result of applying the function Gcross, Jcross or Kcross to the pair of types (i,j). The diagonal [i,i] entry of the function array is the result of applying the univariate function Gest, Jest or Kest to the points of type i only.
Each function entry fns[[i]] retains the format of the output of the relevant estimating routine Fest, Gest, Jest, Kest, Gcross, Jcross, Kcross, Gdot, Jdot, or Kdot.
The default formulae for plotting these functions are cbind(km,theo) ~ r for F, G, and J functions, and cbind(trans,theo) ~ r for K functions.

Note

Sizeable amounts of memory may be needed during the calculation.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

plot.fasp, fasp.object, allstats, Fest, Gest, Jest, Kest, Gcross, Jcross, Kcross, Gdot, Jdot, Kdot

Examples

   # bramblecanes (3 marks).
   data(bramblecanes)
   ## Not run:
   X.F <- alltypes(bramblecanes,fun="F",verb=TRUE)
   plot(X.F)
   X.G <- alltypes(bramblecanes,fun="G",verb=TRUE)
   X.J <- alltypes(bramblecanes,fun="J",verb=TRUE)
   X.K <- alltypes(bramblecanes,fun="K",verb=TRUE)
   X.Gd <- alltypes(bramblecanes,fun="Gdot",verb=TRUE)
   X.Jd <- alltypes(bramblecanes,fun="Jdot",verb=TRUE)
   X.Kd <- alltypes(bramblecanes,fun="Kdot",verb=TRUE)

## End(Not run)

   # Swedishpines (unmarked).
   data(swedishpines)

   X.K <- alltypes(swedishpines,fun="K")
   X.F <- alltypes(swedishpines,fun="F")
   X.G <- alltypes(swedishpines,fun="G")
   X.J <- alltypes(swedishpines,fun="J")

   # simulated data
   ## Not run:
   pp <- runifpoint(350, owin(c(0,1),c(0,1)))
   pp$marks <- factor(c(rep(1,50),rep(2,100),rep(3,200)))
   X.F <- alltypes(pp,fun="F",verb=TRUE,dataname="Fake Data")
   X.G <- alltypes(pp,fun="G",verb=TRUE,dataname="Fake Data")
   X.J <- alltypes(pp,fun="J",verb=TRUE,dataname="Fake Data")
   X.K <- alltypes(pp,fun="K",verb=TRUE,dataname="Fake Data")

## End(Not run)

   # A setting where you might REALLY want to use dataname:
   ## Not run:
   xxx <- alltypes(ppp(Melvin$x,Melvin$y,
                window=as.owin(c(5,20,15,50)),marks=clyde),
                fun="F",verb=TRUE,dataname="Melvin")

## End(Not run)


Hughes' Amacrine Cell Data

Description

Austin Hughes' data: a point pattern of displaced amacrine cells in the retina of a rabbit. A marked point pattern.

Usage

data(amacrine)

Format

An object of class "ppp" representing the point pattern of cell locations. Entries include
x | Cartesian x-coordinate of cell
y | Cartesian y-coordinate of cell
marks | factor with levels off and on
 | indicating ``off'' and ``on'' cells

See ppp.object for details of the format.

Notes

Austin Hughes' data: a point pattern of displaced amacrine cells in the retina of a rabbit. 152 ``on'' cells and 142 ``off'' cells in a rectangular sampling frame.

The true dimensions of the rectangle are 1060 by 662 microns. The coordinates here are scaled to a rectangle of height 1 and width 1060/662 = 1.601 so the unit of measurement is approximately 662 microns.

The data were analysed by Diggle (1986).

Source

Peter Diggle, personal communication

References

Diggle, P. J. (1986). Displaced amacrine cells in the retina of a rabbit: analysis of a bivariate spatial point pattern. J. Neurosci. Meth. 18, 115–125.


Beadlet Anemones Data

Description

These data give the spatial locations and diameters of sea anemones (beadlet anemone Actinia equina) in a sample plot on the north face of a boulder, well above low tide level, at Quiberon (Bretagne, France) in May 1976.

The data were originally described and discussed by Kooijman (1979a). Kooijman (1979b) shows a hand-drawn plot of the original data. The data are discussed by Upton and Fingleton (1985) as Example 1.8 on pages 64–67.

The anemones dataset is taken directly from Table 1.11 of Upton and Fingleton (1985). The coordinates and diameters are integer multiples of an idiosyncratic unit of length. The boundary is a rectangle 280 by 180 units.

Usage

data(anemones)

Format

anemones is an object of class "ppp" representing the point pattern of anemone locations. It is a marked point pattern with numeric marks representing anemone diameter. See ppp.object for details of the format.

Units

There is some confusion about the correct physical scale for these data. According to Upton and Fingleton (1985), one unit in the dataset is approximately 0.475 cm. According to Kooijman (1979a, 1979b) and also quoted by Upton and Fingleton (1985), the physical size of the sample plot was 14.5 by 9.75 cm. However if the data are plotted at this scale, they are too small for a rectangle of this size, and the appearance of the plot does not match the original hand-drawn plot in Kooijman (1979b). To avoid confusion, we have not assigned a unit scale to this dataset.

Source

Table 1.11 on pages 62–63 of Upton and Fingleton (1985), who acknowledge Kooijman (1979a) as the source.

References

Kooijman, S.A.L.M. (1979a) The description of point patterns. In Spatial and temporal analysis in ecology (ed. R.M. Cormack and J.K. Ord), International Cooperative Publishing House, Fairland, Maryland, USA. Pages 305–332.

Kooijman, S.A.L.M. (1979b) Inference about dispersal patterns. Acta Biotheoretica 28, 149–189.

Upton, G.J.G. and Fingleton, B. (1985) Spatial data analysis by example. Volume 1: Point pattern and quantitative data. John Wiley and Sons, Chichester.

Examples

  data(anemones)
  # plot diameters on same scale as x, y
  plot(anemones, markscale=0.5)


Orientation Angles of Line Segments

Description

Computes the orientation angle of each line segment in a line segment pattern.

Usage

  angles.psp(x, directed=FALSE)

Arguments

x | A line segment pattern (object of class "psp").
directed | Logical flag. See details.

Details

For each line segment, the angle of inclination to the x-axis (in radians) is computed, and the angles are returned as a numeric vector.

If directed=TRUE, the directed angle of orientation is computed. The angle respects the sense of direction from (x0,y0) to (x1,y1). The values returned are angles in the full range from -pi to pi. The angle is computed as atan2(y1-y0,x1-x0). See atan2.

If directed=FALSE, the undirected angle of orientation is computed. Angles differing by pi are regarded as equivalent. The values returned are angles in the range from 0 to pi. These angles are computed by first computing the directed angle, then adding pi to any negative angles.

Value

Numeric vector.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

summary.psp, midpoints.psp, lengths.psp

Examples

  a <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
  b <- angles.psp(a)


ANOVA for Fitted Point Process Models

Description

Performs analysis of deviance for two or more fitted point process models.

Usage

  ## S3 method for class 'ppm':
  anova(object, ..., test=NULL, override=FALSE)

Arguments

object | A fitted point process model (object of class "ppm").
... | One or more fitted point process models.
test | Character string, partially matching one of "Chisq", "F" or "Cp".
override | Logical flag indicating whether to proceed even when there is no statistical theory to support the calculation.

Details

This is a method for anova for fitted point process models (objects of class "ppm", usually generated by the model-fitting function ppm).

If the fitted models are all Poisson point processes, then this function performs an Analysis of Deviance of the fitted models. The output shows the deviance differences (i.e. 2 times log likelihood ratio), the difference in degrees of freedom, and (if test="Chi") the two-sided p-values for the chi-squared tests. Their interpretation is very similar to that in anova.glm.

If some of the fitted models are not Poisson point processes, then there is no statistical theory available to support a similar analysis. The function issues a warning, and (by default) returns a NULL value.

However if override=TRUE, then a kind of analysis of deviance table will be printed. The `deviance' differences in this table are equal to 2 times the differences in the maximised values of the log pseudolikelihood (see ppm). At the time of writing, there is no statistical theory to support inferential interpretation of log pseudolikelihood ratios. The override option is provided for research purposes only!

Value

An object of class "anova", or NULL.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppm

Examples

 data(swedishpines)
 mod0 <- ppm(swedishpines, ~1, Poisson())
 modx <- ppm(swedishpines, ~x, Poisson())
 anova.ppm(mod0, modx, test="Chi")


Harkness-Isham ants' nests data

Description

These data give the spatial locations of nests of two species of ants, Messor wasmanni and Cataglyphis bicolor, recorded by Professor R.D. Harkness at a site in northern Greece, and described in Harkness & Isham (1983). The full dataset (supplied here) has an irregular polygonal boundary, while most analyses have been confined to two rectangular subsets of the pattern (also supplied here).

The harvester ant M. wasmanni collects seeds for food and builds a nest composed mainly of seed husks. C. bicolor is a heat-tolerant desert foraging ant which eats dead insects and other arthropods. Interest focuses on whether there is evidence in the data for intra-species competition between Messor nests (i.e. competition for resources) and for preferential placement of Cataglyphis nests in the vicinity of Messor nests.

The full dataset is displayed in Figure 1 of Harkness & Isham (1983). See Usage below to produce a comparable plot. It comprises 97 nests (68 Messor and 29 Cataglyphis) inside an irregular convex polygonal boundary, together with annotations showing a foot track through the region, the boundary between field and scrub areas inside the region, and indicating the two rectangular subregions A and B used in their analysis.

Rectangular subsets of the data were analysed by Harkness & Isham (1983), Isham (1984), Takacs & Fiksel (1986), S"arkk"a (1993, section 5.3), H"ogmander and S"arkk"a (1999) and Baddeley & Turner (2000). The full dataset (inside its irregular boundary) was first analysed by Baddeley & Turner (2005b).

The dataset ants is the full point pattern enclosed by the irregular polygonal boundary. The x and y coordinates are eastings (E-W) and northings (N-S) scaled so that 1 unit equals 0.5 feet. This is a multitype point pattern object, each point carrying a mark indicating the ant species (with levels Cataglyphis and Messor).

The dataset ants.extra is a list of auxiliary information:

A and B
The subsets of the pattern within the rectangles A and B demarcated in Figure 1 of Harkness & Isham (1983). These are multitype point pattern objects.
ants.trackNE and ants.trackSW
coordinates of two straight lines bounding the foot track.
ants.fieldscrub
The endpoints of a straight line separating the regions of `field' and `scrub': scrub to the North and field to the South.
plot
A function, with no arguments, which produces a plot of the full dataset.

Usage

data(ants)

Format

ants is an object of class "ppp" representing the full point pattern of ants' nests. See ppp.object for details of the format. The coordinates are scaled so that 1 unit equals 0.5 feet. The points are marked by species (with levels Cataglyphis and Messor).

ants.extra is a list with entries

A
point pattern of class "ppp"
B
point pattern of class "ppp"
trackNE
data in format list(x=numeric(2),y=numeric(2)) giving the two endpoints of line markings
trackSW
data in format list(x=numeric(2),y=numeric(2)) giving the two endpoints of line markings
fieldscrub
data in format list(x=numeric(2),y=numeric(2)) giving the two endpoints of line markings
plot
Function with no arguments

Source

Harkness and Isham (1983). Nest coordinates kindly provided by Prof Valerie Isham. Polygon coordinates digitised by Adrian Baddeley from a reprint of Harkness & Isham (1983).

References

Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point patterns. Australian and New Zealand Journal of Statistics 42, 283–322.

Baddeley, A. and Turner, R. (2005a) Spatstat: an R package for analyzing spatial point patterns. Journal of Statistical Software 12:6, 1–42. URL: www.jstatsoft.org, ISSN: 1548-7660.

Baddeley, A. and Turner, R. (2005b) Modelling spatial point patterns in R. In: A. Baddeley, P. Gregori, J. Mateu, R. Stoica, and D. Stoyan, editors, Case Studies in Spatial Point Pattern Modelling, Lecture Notes in Statistics number 185. Pages 23–74. Springer-Verlag, New York, 2006. ISBN: 0-387-28311-0.

Harkness, R.D. and Isham, V. (1983) A bivariate spatial point pattern of ants' nests. Applied Statistics 32, 293–303.

H"ogmander, H. and S{"arkk"a}, A. (1999) Multitype spatial point patterns with hierarchical interactions. Biometrics 55, 1051–1058.

Isham, V.S. (1984) Multitype Markov point processes: some approximations. Proceedings of the Royal Society of London, Series A, 391, 39–53.

Takacs, R. and Fiksel, T. (1986) Interaction pair-potentials for a system of ants' nests. Biometrical Journal 28, 1007–1013.

S{"arkk"a}, A. (1993) Pseudo-likelihood approach for pair potential estimation of Gibbs processes. Number 22 in Jyv"askyl"a Studies in Computer Science, Economics and Statistics. University of Jyv"askyl"a, Finland.

Examples

  # Equivalent to Figure 1 of Harkness and Isham (1983)

  data(ants)
  ants.extra$plot()

  # Data in subrectangle A, rotated
  # Approximate data used by Sarkka (1993)

  angle <- atan(diff(ants.extra$fieldscrub$y)/diff(ants.extra$fieldscrub$x))
  plot(rotate(ants.extra$A, -angle))

  # Approximate window used by Takacs and Fiksel (1986)

  tfwindow <- bounding.box(ants$window)
  antsTF <- ppp(ants$x, ants$y, window=tfwindow)
  plot(antsTF)


Combine Two Line Segment Patterns

Description

Combine two line segment patterns into a single pattern.

Usage

  append.psp(A, B)

Arguments

A,B Line segment patterns (objects of class "psp").

Details

This function is used to superimpose two line segment patterns A and B.

The two patterns must have identical windows. If one pattern has marks, then the other must also have marks of the same type.

(To combine two point patterns, see superimpose).

Value

Another line segment pattern (object of class "psp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

psp, as.psp, superimpose,

Examples

  X <- psp(runif(20), runif(20), runif(20), runif(20),  window=owin())
  Y <- psp(runif(5), runif(5), runif(5), runif(5),  window=owin())
  append.psp(X,Y)


Apply Function to Every Neighbourhood in a Point Pattern

Description

Visit each point in a point pattern, find the neighbouring points, and apply a given function to them.

Usage

   applynbd(X, FUN, N, R, criterion, exclude=FALSE, ...)

Arguments

X | Point pattern. An object of class "ppp", or data which can be converted into this format by as.ppp.
FUN | Function to be applied to each neighbourhood. The arguments of FUN are described under Details.
N | Integer. If this argument is present, the neighbourhood of a point of X is defined to consist of the N points of X which are closest to it. This argument is incompatible with R and criterion.
R | Nonnegative numeric value. If this argument is present, the neighbourhood of a point of X is defined to consist of all points of X which lie within a distance R of it. This argument is incompatible with N and criterion.
criterion | Function. If this argument is present, the neighbourhood of a point of X is determined by evaluating this function. See under Details. This argument is incompatible with N and R.
exclude | Logical. If TRUE then the point currently being visited is excluded from its own neighbourhood.
... | extra arguments passed to the function FUN. They must be given in the form name=value.

Details

This is an analogue of apply for point patterns. It visits each point in the point pattern X, determines which points of X are ``neighbours'' of the current point, applies the function FUN to this neighbourhood, and collects the values returned by FUN.

The definition of ``neighbours'' depends on the arguments N, R and criterion, exactly one of which must be given. Also the argument exclude determines whether the current point is excluded from its own neighbourhood.

If N is given, then the neighbours of the current point are the N points of X which are closest to the current point (including the current point itself unless exclude=TRUE). If R is given, then the neighbourhood of the current point consists of all points of X which lie closer than a distance R from the current point. If criterion is given, then it must be a function with two arguments dist and drank which will be vectors of equal length. The interpretation is that dist[i] will be the distance of a point from the current point, and drank[i] will be the rank of that distance (the three points closest to the current point will have rank 1, 2 and 3). This function must return a logical vector of the same length as dist and drank whose i-th entry is TRUE if the corresponding point should be included in the neighbourhood. See the examples below.

Each point of X is visited; the neighbourhood of the current point is determined, and stored as a point pattern Y; then the function FUN is called as:

FUN(Y=Y, current=current, dists=dists, dranks=dranks, ...)

where current is a vector of length 2 giving the coordinates of the current point, dists is a vector of distances from the current point to each of the points in Y, dranks is a vector of the ranks of these distances with respect to the full point pattern X, and ... are the arguments passed from the call to applynbd.

The results of each call to FUN are collected and returned according to the usual rules for apply and its relatives. See Value above.

Note that FUN will be called exactly as described above, with each argument named explicitly. Care is required when writing the function FUN to ensure that the arguments will match up. See the Examples.

See markstat for a common use of this function.

Value

Similar to the result of apply. If each call to FUN returns a single numeric value, the result is a vector of dimension X$n, the number of points in X. If each call to FUN returns a vector of the same length m, then the result is a matrix of dimensions c(m,n); note the transposition of the indices, as usual for the family of apply functions. If the calls to FUN return vectors of different lengths, the result is a list of length X$n.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp.object, apply, markstat

Examples

  data(redwood)

  # count the number of points within radius 0.2 of each point of X
  nneighbours <- applynbd(redwood, R=0.2, function(Y, ...){Y$n-1})
  # equivalent to:
  nneighbours <- applynbd(redwood, R=0.2, function(Y, ...){Y$n}, exclude=TRUE)

  # compute the distance to the second nearest neighbour of each point
  secondnndist <- applynbd(redwood, N = 2,
                           function(dists, ...){max(dists)},
                           exclude=TRUE)

  # marked point pattern
  data(longleaf)

  # compute the median of the marks of all neighbours of a point
  # (see also 'markstat')
  dbh.med <- applynbd(longleaf, R=90, exclude=TRUE,
                 function(Y, ...) { median(Y$marks)})

  # ANIMATION explaining the definition of the K function
  # (arguments `fullpicture' and 'rad' are passed to FUN)

  ## Not run:
  showoffK <- function(Y, current, dists, dranks, fullpicture,rad) {
        plot(fullpicture, main="")
        points(Y, cex=2)
        u <- current
        points(u[1],u[2],pch="+",cex=3)
        theta <- seq(0,2*pi,length=100)
        polygon(u[1]+ rad * cos(theta),u[2]+rad*sin(theta))
        text(u[1]+rad/3,u[2]+rad/2,Y$n,cex=3)
        Sys.sleep(if(runif(1) < 0.1) 1.5 else 0.3)
        return(Y$n - 1)
  }
  applynbd(redwood, R=0.2, showoffK, fullpicture=redwood, rad=0.2, exclude=TRUE)

  # animation explaining the definition of the G function

  showoffG <- function(Y, current, dists, dranks, fullpicture) {
        plot(fullpicture, main="")
        points(Y, cex=2)
        u <- current
        points(u[1],u[2],pch="+",cex=3)
        v <- c(Y$x[1],Y$y[1])
        segments(u[1],u[2],v[1],v[2],lwd=2)
        w <- (u + v)/2
        nnd <- dists[1]
        text(w[1],w[2],round(nnd,3),cex=2)
        Sys.sleep(if(runif(1) < 0.1) 1.5 else 0.3)
        return(nnd)
  }

  data(cells)
  applynbd(cells, N=1, showoffG, exclude=TRUE, fullpicture=cells)
  ## End(Not run)


Area of a Window

Description

Computes the area of a window

Usage

 area.owin(w)

Arguments

w A window, whose area will be computed. This should be an object of class owin, or can be given in any format acceptable to as.owin().

Details

If the window W is of type "rectangle" or "polygonal", the area of this rectangular window is computed by analytic geometry. If W is of type "mask" the area of the discrete raster approximation of the window is computed by summing the binary image values and adjusting for pixel size.

Value

The numerical value of the area of the window.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin.object, as.owin

Examples

  w <- unit.square()
  area.owin(w)
       # returns 1.00000

  k <- 6
  theta <- 2 * pi * (0:(k-1))/k
  co <- cos(theta)
  si <- sin(theta)
  mas <- owin(c(-1,1), c(-1,1), poly=list(x=co, y=si))
  area.owin(mas)
      # returns approx area of k-gon

  mas <- as.mask(w, eps=0.01)
  X <- raster.x(mas)
  Y <- raster.y(mas)
  mas$m <- ((X - 0.5)^2 + (Y - 0.5)^2 <= 1)
  area.owin(mas)
       # returns 3.14 approx


Convert to Pixel Image

Description

Converts various kinds of data to a pixel image

Usage

  as.im(X, W=as.mask(as.owin(X), dimyx=dimyx), ..., dimyx=NULL)

Arguments

X | Data to be converted to a pixel image.
W | Window object which determines the spatial domain of the image
... | Additional arguments passed to X when X is a function.
dimyx | Optional. Dimensions for the pixel array. An integer, or vector of 2 integers c(ny, nx).

Details

This function converts the data X into a pixel image object of class "im" (see im.object).

Currently X may be any of the following:

  • a pixel image object, of class "im".
  • a window object, of class "owin" (see owin.object). The result is an image with all pixel entries equal to 1 inside the window X, and NA outside.
  • a single number (or a single logical, complex, factor or character value). The result is an image with all pixel entries equal to this constant value inside the window W (and NA outside). Argument W is required.
  • a function of the form function(x, y, ...) which is to be evaluated to yield the image pixel values. In this case, the additional argument W must be present. This window will be converted to a binary image mask. Then the function X will be evaluated in the form X(x, y, ...) where x and y are vectors containing the x and y coordinates of all the pixels in the image mask, and ... are any extra arguments given. This function must return a vector or factor of the same length as the input vectors, giving the pixel values.
  • a list with entries x, y, z in the format expected by the standard R functions image.default and contour.default. That is, z is a matrix of pixel values, x and y are vectors of x and y coordinates respectively, and z[i,j] is the pixel value for the location (x[i],y[j]).

The spatial domain (enclosing rectangle) of the pixel image is determined by the argument W. If W is absent, the spatial domain is determined by X. When X is a function or a single numerical value, W is required.

The pixel array dimensions of the final resulting image are determined by (in priority order)

  • the argument dimyx if present;
  • the pixel dimensions of the window W, if it is present and if it is a binary mask;
  • the pixel dimensions of X if it is an image, a binary mask, or a list(x,y,z);
  • the default pixel dimensions, controlled by spatstat.options.

Note that if dimyx is given, this will override the pixel dimensions of X if it has them. Thus, as.im can be used to change an image's pixel dimensions.

Value

An image object of class "im".

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

Examples

  data(demopat)
  # window object
  W <- demopat$window
  plot(W)
  Z <- as.im(W)
  image(Z)
  # function
  Z <- as.im(function(x,y) {x^2 + y^2}, unit.square())
  image(Z)
  # function with extra arguments
  f <- function(x, y, x0, y0) {
      sqrt((x - x0)^2 + (y-y0)^2)
  }
  Z <- as.im(f, unit.square(), x0=0.5, y0=0.5)
  image(Z)
  # Revisit the Sixties
  data(letterR)
  Z <- as.im(f, letterR, x0=2.5, y0=2)
  image(Z)
  # usual convention in S
  stuff <- list(x=1:10, y=1:10, z=matrix(1:100, nrow=10))
  Z <- as.im(stuff)
  # convert to finer grid
  Z <- as.im(Z, dimyx=256)


Pixel Image Approximation of a Window

Description

Obtain a discrete (pixel image) approximation of a given window

Usage

 as.mask(w, eps=NULL, dimyx=NULL, xy=NULL)

Arguments

w | A window (object of class "owin").
eps | (optional) width and height of pixels.
dimyx | (optional) pixel array dimensions
xy | (optional) pixel coordinates

Details

This function generates a rectangular grid of locations in the plane, tests whether each of these locations lies inside the window w, and stores the results as a binary pixel image or `mask' (an object of class "owin", see owin.object).

The most common use of this function is to approximate the shape of another window w by a binary pixel image. In this case, we will usually want to have a very fine grid of pixels.

This function can also be used to generate a coarsely-spaced grid of locations inside a window, for purposes such as subsampling and prediction.

The grid spacing and location are controlled by the arguments eps, dimyx and xy, which are mutually incompatible.

If eps is given, then the grid spacing will be approximately eps in both the x and y directions.

If dimyx is given, then the pixel grid will be an m x n rectangular grid where m, n are given by dimyx[2], dimyx[1] respectively. Warning: dimyx[1] is the number of pixels in the y direction, and dimyx[2] is the number in the x direction.

If xy is given, then this should be a structure containing two elements x and y which are the vectors of x and y coordinates of the margins of the grid. The pixel coordinates will be generated from these two vectors. In this case w may be omitted.

If neither eps nor dimyx nor xy is given, the pixel raster dimensions are obtained from spatstat.options("npixel").

There is no inverse of this function!

Value

A window (object of class "owin") of type "mask" representing a binary pixel image.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin.object, as.rectangle, spatstat.options

Examples

  w <- owin(c(0,10),c(0,10), poly=list(x=c(1,2,3,2,1), y=c(2,3,4,6,7)))
  ## Not run: plot(w)
  m <- as.mask(w)
  ## Not run: plot(m)
  x <- 1:9
  y <- seq(0.25, 9.75, by=0.5)
  m <- as.mask(w, xy=list(x=x, y=y))


Convert Pixel Image to Matrix

Description

Convert a pixel image to a matrix

Usage

  ## S3 method for class 'im':
  as.matrix(x, ...)

Arguments

x | A pixel image (object of class "im").
... | Ignored.

Details

This function takes the pixel image x and returns a matrix containing the pixel values.

It is handy when you want to extract a summary of the pixel values. See the Examples.

Value

A matrix.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

Examples

   # artificial image
   Z <- setcov(square(1))

   M <- as.matrix(Z)

   median(M)

   ## Not run:
   # plot the cumulative distribution function of pixel values
   plot(ecdf(as.matrix(Z)))

## End(Not run)


Convert Data To Class owin

Description

Converts data specifying an observation window in any of several formats, into an object of class "owin".

Usage

 as.owin(W, ..., fatal=TRUE)
 ## S3 method for class 'owin':
 as.owin(W, ..., fatal=TRUE)
 ## S3 method for class 'ppp':
 as.owin(W, ..., fatal=TRUE)
 ## S3 method for class 'ppm':
 as.owin(W, ..., fatal=TRUE)
 ## S3 method for class 'im':
 as.owin(W, ..., fatal=TRUE)
 ## Default S3 method:
 as.owin(W, ..., fatal=TRUE)

Arguments

W | Data specifying an observation window, in any of several formats described under Details below.
fatal | Logical flag determining what to do if the data cannot be converted to an observation window. See Details.
... | Ignored.

Details

The class "owin" is a way of specifying the observation window for a point pattern. See owin.object for an overview.

This function converts data in any of several formats into an object of class "owin" for use by the spatstat package. The argument W may be

  • an object of class "owin"
  • a structure with entries xrange, yrange specifying the x and y dimensions of a rectangle
  • a four-element vector (interpreted as (xmin, xmax, ymin, ymax)) specifying the x and y dimensions of a rectangle
  • a structure with entries xl, xu, yl, yu specifying the x and y dimensions of a rectangle as (xmin, xmax) = (xl, xu) and (ymin, ymax) = (yl, yu). This will accept objects of class spp used in the Venables and Ripley spatial library.
  • an object of class "ppp" representing a point pattern. In this case, the object's window structure will be extracted.
  • an object of class "im" representing a pixel image. In this case, a window of type "mask" will be returned, with the same pixel raster coordinates as the image. An image pixel value of NA, signifying that the pixel lies outside the window, is transformed into the logical value FALSE, which is the corresponding convention for window masks.
  • an object of class "ppm" representing a fitted point process model. In this case, as.owin extracts the original point pattern data to which the model was fitted, and returns the observation window of this point pattern.

If the argument W is not in one of these formats and cannot be converted to a window, then an error will be generated (if fatal=TRUE) or a value of NULL will be returned (if fatal=FALSE).

The function as.owin is generic, with methods for "owin", "im" and "ppp" as well as the default method.

Value

An object of class "owin" (see owin.object) specifying an observation window.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin.object, owin

Examples

 w <- as.owin(c(0,1,0,1))
 w <- as.owin(list(xrange=c(0,5),yrange=c(0,10)))
 # point pattern
 data(demopat)
 w <- as.owin(demopat)
 # image
 Z <- as.im(function(x,y) { x + 3}, unit.square())
 w <- as.owin(Z)

 # Venables & Ripley 'spatial' package
 require(spatial)
 towns <- ppinit("towns.dat")
 w <- as.owin(towns)
 detach(package:spatial)


Convert Data To Class ppp

Description

Tries to coerce any reasonable kind of data to a point pattern (an object of class "ppp") for use by the spatstat package).

Usage

  as.ppp(X, ..., fatal=TRUE)
  as.ppp(X, W, ..., fatal=TRUE)

Arguments

X | Data which will be converted into a point pattern
W | Data which define a window for the pattern when X does not contain a window
... | Ignored.
fatal | Logical value. See Details.

Details

Converts the dataset X to a point pattern (an object of class "ppp"; see ppp.object for an overview).

This function is normally used to convert an existing point pattern dataset, stored in another format, to the "ppp" format. To create a new point pattern from raw data such as x,y coordinates, it is normally easier to use the creator function ppp.

The dataset X may be:

  • an object of class "ppp"
  • an object of class "spp" as defined in the spatial library
  • an object of class "quad" representing a quadrature scheme (see quad.object)
  • a two-column matrix
  • a structure with entries x, y

In the last two cases, we need the second argument W which is converted to a window object by the function as.owin. In the first three cases, W will be ignored.

The argument fatal indicates what to do when W is missing and X contains no information about the window. If fatal=TRUE, a fatal error will be generated; if fatal=FALSE, the value NULL is returned.

An spp object is the representation of a point pattern in the spatial library. Our implementation recognises the following formats:

  • a structure with entries x, y xl, xu, yl, yu
  • a structure with entries x, y and area, where area is a structure with entries xl, xu, yl, yu
(used in spatial versions 1 to 6 and version 7.1 respectively) where x and y are vectors of equal length giving the point coordinates, and xl, xu, yl, yu are numbers giving the dimensions of a rectangular window.

The function as.ppp is generic, with methods for the classes "ppp", "quad", "matrix" and a default method.

Point pattern datasets can also be created by the function ppp.

Value

An object of class "ppp" (see ppp.object) describing the point pattern and its window of observation. The value NULL may also be returned; see Details.

Warnings

If the format of spp objects is changed in future versions of the spatial library, then as.ppp may not be able to interpret them. It currently handles all versions of spatial up to 7.1-4.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp, ppp.object, as.owin, owin.object

Examples

 ## Not run:
 plot(c(0,1),c(0,1),type="n")
 xy <- locator(20) # click on 20 points in plot window
 pp <- as.ppp(xy, c(0,1,0,1))

 w <- owin(c(0,1),c(0,1))
 plot(w)                      # neater
 xy <- locator(20)            # click on 20 points in plot window
 pp <- as.ppp(xy, w)

## End(Not run)

 xy <- matrix(runif(40), ncol=2)
 pp <- as.ppp(xy, c(0,1,0,1))

 # Venables-Ripley format
 require(spatial)
 towns <- ppinit("towns.dat")
 pp <- as.ppp(towns)   # converted to our format
 detach(package:spatial)


Convert Data To Class psp

Description

Tries to coerce any reasonable kind of data to a line segment pattern (an object of class "psp") for use by the spatstat package.

Usage

  as.psp(x, ..., from=NULL, to=NULL)
  ## S3 method for class 'psp':
  as.psp(x, ..., fatal=TRUE)
  ## S3 method for class 'data.frame':
  as.psp(x, ..., window=NULL, marks=NULL, fatal=TRUE)
  ## S3 method for class 'matrix':
  as.psp(x, ..., window=NULL, marks=NULL, fatal=TRUE)
  ## S3 method for class 'owin':
  as.psp(x, ..., fatal=TRUE)
  ## Default S3 method:
  as.psp(x, ..., window=NULL, marks=NULL, fatal=TRUE)

Arguments

x | Data which will be converted into a line segment pattern
window | Data which define a window for the pattern when x does not contain a window
... | Ignored.
marks | (Optional) vector of marks for the pattern
fatal | Logical value. See Details.
from,to | Point patterns (object of class "ppp") containing the first and second endpoints (respectively) of each segment. Incompatible with x.

Details

Converts the dataset x to a line segment pattern (an object of class "psp"; see psp.object for an overview).

This function is normally used to convert an existing line segment pattern dataset, stored in another format, to the "psp" format. To create a new point pattern from raw data such as x,y coordinates, it is normally easier to use the creator function psp.

The dataset x may be:

  • an object of class "psp"
  • a data frame with columns named x0, y0, x1, y1 that will be interpreted as the coordinates of the endpoints of the segments
  • a data frame or matrix with exactly 4 columns that will be interpreted as the coordinates x0, y0, x1, y1 of the endpoints of the segments
  • a data frame with columns named xmid, ymid, length, angle that will be interpreted as the coordinates of the segment midpoints, the lengths of the segments, and the orientations of the segments in radians
  • a structure with elements named x0, y0, x1, y1 or elements named xmid, ymid, length, angle which will be interpreted as above.
  • an object of class "owin" representing a spatial window; it must be of type "rectangle" or "polygonal". The boundary edges of the window will be extracted as a line segment pattern.

Alternatively, you may specify two point patterns from and to containing the first and second endpoints of the line segments.

The argument window is converted to a window object by the function as.owin.

The argument fatal indicates what to do when the data cannot be converted to a line segment pattern. If fatal=TRUE, a fatal error will be generated; if fatal=FALSE, the value NULL is returned.

The function as.psp is generic, with methods for the classes "psp", "data.frame", "matrix" and a default method.

Point pattern datasets can also be created by the function psp.

Value

An object of class "psp" (see psp.object) describing the line segment pattern and its window of observation. The value NULL may also be returned; see Details.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

psp, psp.object, as.owin, owin.object

Examples

   mat <- matrix(runif(40), ncol=4)
   a <- as.psp(mat, window=owin())
   stuff <- list(xmid=runif(10),
                 ymid=runif(10),
                 length=rep(0.1, 10),
                 angle=runif(10, 0, 2 * pi))
   a <- as.psp(stuff, window=owin())
   b <- as.psp(from=runifpoint(10), to=runifpoint(10))


Window Frame

Description

Get the window frame of an (irregular) window

Usage

 as.rectangle(...)

Arguments

... A window. Either an object of class "owin", or other data determining such a window. The argument(s) are passed to as.owin.

Details

This function just extracts the outer bounding rectangle of the window w as given by its elements xrange,yrange.

Use the function bounding.box to compute the smallest bounding rectangle.

Value

A window (object of class "owin") of type "rectangle" representing a rectangle.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin, as.owin, bounding.box

Examples

  w <- owin(c(0,10),c(0,10), poly=list(x=c(1,2,3,2,1), y=c(2,3,4,6,7)))
  r <- as.rectangle(w)
  # returns a 10 x 10 rectangle


Distance to Boundary of Window

Description

Computes the distances from each pixel in a window to the boundary of the window.

Usage

 bdist.pixels(w, ..., coords=TRUE)

Arguments

w | A window (object of class "owin").
... | Arguments passed to as.mask to determine the pixel resolution.
coords | Logical: if TRUE, the result can be displayed using persp, contour etc.

Details

This function computes, for each pixel u in the window w, the shortest distance dist(u, W') from u to the boundary of W.

If the window is not of type "mask" then it is first converted to that type. The arguments "..." are passed to as.mask to determine the pixel resolution.

Value

If coords is false, a matrix giving the distances from each pixel in the image raster to the boundary of the window. Rows of this matrix correspond to the y coordinate and columns to the x coordinate.
If coords is true, a list with three components x,y,z, where x,y are vectors of length m,n giving the x and y coordinates respectively, and z is an m x n matrix such that z[i,j] is the distance from (x[i],y[j]) to the boundary of the window. Rows of this matrix correspond to the x coordinate and columns to the y coordinate. This result can be plotted with persp, image or contour.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin.object, erode.owin, bdist.points,

Examples

  u <- owin(c(0,1),c(0,1))
  d <- bdist.pixels(u, eps=0.01)
  image(d)
  d <- bdist.pixels(u, eps=0.01, coords=FALSE)
  mean(d >= 0.1)
  # value is approx (1 - 2 * 0.1)^2 = 0.64


Distance to Boundary of Window

Description

Computes the distances from each point of a point pattern to the boundary of the window.

Usage

 bdist.points(X)

Arguments

X A point pattern (object of class "ppp").

Details

This function computes, for each point x[i] in the point pattern X, the shortest distance dist(x[i], W') from x[i] to the boundary of the window W of observation.

If the window X$window is of type "rectangle" or "polygonal", then these distances are computed by analytic geometry and are exact, up to rounding errors. If the window is of type "mask" then the distances are computed using the real-valued distance transform, which is an approximation with maximum error equal to the width of one pixel in the mask.

Value

A numeric vector, giving the distances from each point of the pattern to the boundary of the window.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp.object, erode.owin

Examples

  data(cells)
  d <- bdist.points(cells)


Tropical rain forest trees

Description

A point pattern giving the locations of 3605 trees in a tropical rain forest. Accompanied by covariate data giving the elevation (altitude) and slope of elevation in the study region.

Usage

data(bei)

Format

bei is an object of class "ppp" representing the point pattern of tree locations. See ppp.object for details of the format.

bei.extra is a list containing two pixel images, elev (elevation in metres) and grad (norm of elevation gradient). These pixel images are objects of class "im", see im.object.

Notes

The dataset bei gives the positions of 3605 trees of the species Beilschmiedia pendula (Lauraceae) in a 1000 by 500 metre rectangular sampling region in the tropical rainforest of Barro Colorado Island.

The accompanying dataset bei.extra gives information about the altitude (elevation) in the study region. It is a list containing two pixel images, elev (elevation in metres) and grad (norm of elevation gradient).

These data are part of a much larger dataset containing the positions of hundreds of thousands of trees belong to thousands of species; see Hubbell and Foster (1983), Condit, Hubbell and Foster (1996) and Condit (1998).

The present data were analysed by Moller and Waagepetersen (2006).

Source

Hubbell and Foster (1983), Condit, Hubbell and Foster (1996) and Condit (1998). Data files kindly supplied by Rasmus Waagepetersen. The data were collected in the forest dynamics plot of Barro Colorado Island. The study was made possible through the generous support of the U.S. National Science Foundation, the John D. and Catherine T. MacArthur Foundation, and the Smithsonian Tropical Research Institute.

References

Condit, R. (1998) Tropical Forest Census Plots. Springer-Verlag, Berlin and R.G. Landes Company, Georgetown, Texas.

Condit, R., Hubbell, S.P and Foster, R.B. (1996) Changes in tree species abundance in a neotropical forest: impact of climate change. Journal of Tropical Ecology 12, 231–256.

Hubbell, S.P and Foster, R.B. (1983) Diversity of canopy trees in a neotropical forest and implications for conservation. In: Tropical Rain Forest: Ecology and Management (eds. S.L. Sutton, T.C. Whitmore and A.C. Chadwick), Blackwell Scientific Publications, Oxford, 25–41.

Moller, J. and Waagepetersen, R.P. (2006) Modern statistics for spatial point processes. Research report R-2006-12, Department of Mathematical Sciences, Aalborg University, Denmark. ISSN 1601-7811. URL <www.math.aau.dk>


Beta Ganglion Cells in Cat Retina

Description

Point pattern of cells in the retina, each cell classified as `on' or `off'. A bivariate point pattern.

Usage

data(betacells)

Format

betacells is an object of class "ppp" representing the point pattern of cell locations. Entries include
x | Cartesian x-coordinate of cell
y | Cartesian y-coordinate of cell
marks | factor with levels off and on
 | indicating ``off'' and ``on'' cells

See ppp.object for details of the format. Cartesian coordinates are given in microns.

betacells.extra is a list with one component area which is the vector of areas (in square microns) of the cells in the pattern.

Notes

This is a new, corrected version of the old dataset ganglia. See below.

These data represent a pattern of beta-type ganglion cells in the retina of a cat recorded by W"assle et al. (1981). Beta cells are associated with the resolution of fine detail in the cat's visual system. They can be classified anatomically as ``on'' or ``off''.

Statistical independence of the arrangement of the ``on''- and ``off''-components would strengthen the evidence for Hering's (1878) `opponent theory' that there are two separate channels for sensing ``brightness'' and ``darkness''. See W"assle et al (1981). There is considerable current interest in the arrangement of cell mosaics in the retina, see Rockhill et al (2000).

The dataset is a multitype point pattern giving the locations and types (``on'' or ``off'') of beta cells observed in a rectangle of dimensions 750 x 990 microns. Coordinates are given in microns (thousandths of a millimetre).

The original source is Figure 6 of W"assle et al (1981), which is a manual drawing of the beta mosaic observed in a microscope field-of-view of a whole mount of the retina. Thus, all beta cells in the retina were effectively projected onto the same two-dimensional plane.

The data were scanned in 2004 by Stephen Eglen from Figure 6(a) of W"assle et al (1981). Image analysis software was used to identify the soma (cell body). The x,y location of each cell was taken to be the centroid of the soma. The type of each cell (``on'' or `off'') was identified by referring to Figures 6(b) and 6(d).

The area of each soma (in square microns) was also computed, and is provided in the dataset betacells.extra.

Note that this is a corrected version of the ganglia dataset provided in earlier versions of spatstat. The earlier data ganglia were not faithful to the scale in the original paper and contain some scanning errors.

Source

W"assle et al (1981), Figure 6(a), scanned and processed by Stephen Eglen S.J.Eglen@damtp.cam.ac.uk

References

Hering, E. (1878) Zur Lehre von Lichtsinn. Vienna.

Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

Rockhill, R.L., Euler, T. and Masland, R.H. (2000) Spatial order within but not between types of retinal neurons. Proc. Nat. Acad. Sci. USA 97(5), 2303–2307.

W"assle, H., Boycott, B. B. & Illing, R.-B. (1981). Morphology and mosaic of on- and off-beta cells in the cat retina and some functional considerations. Proc. Roy. Soc. London Ser. B 212, 177–195.

Examples

   data(betacells)
   plot(betacells)
   plot(betacells$window, main="beta cells")
   symbols(betacells$x, betacells$y,
       circles=sqrt(betacells.extra$area/pi),
       inches=FALSE, add=TRUE)


Bounding Box of a Window or Point Pattern

Description

Find the smallest rectangle containing a given window(s) or point pattern(s).

Usage

 bounding.box(...)

Arguments

... One or more windows (objects of class "owin"), pixel images (objects of class "im") or point patterns (objects of class "ppp").

Details

This function finds the smallest rectangle (with sides parallel to the coordinate axes) that contains all the given objects.

For a window (object of class "owin"), the bounding box is the smallest rectangle that contains all the vertices of the window (this is generally smaller than the enclosing frame, which is returned by as.rectangle).

For a point pattern (object of class "ppp"), the bounding box is the smallest rectangle that contains all the points of the pattern, and is computed by bounding.box.xy.

For a pixel image (object of class "im"), the image will be converted to a window using as.owin, and the bounding box of this window is obtained.

If the argument is a list of several objects, then this function finds the smallest rectangle that contains all the bounding boxes of the objects.

Value

A window (object of class "owin") of type "rectangle" representing a rectangle.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin, as.owin, as.rectangle bounding.box.xy

Examples

  w <- owin(c(0,10),c(0,10), poly=list(x=c(1,2,3,2,1), y=c(2,3,4,6,7)))
  r <- bounding.box(w)
  # returns rectangle [1,3] x [2,7]

  w2 <- unit.square()
  r <- bounding.box(w, w2)
  # returns rectangle [0,3] x [0,7]


Convex Hull of Points

Description

Computes the smallest rectangle containing a set of points.

Usage

bounding.box.xy(x, y=NULL)

Arguments

x | vector of x coordinates of observed points, or a 2-column matrix giving x,y coordinates, or a list with components x,y giving coordinates (such as a point pattern object of class "ppp".)
y | (optional) vector of y coordinates of observed points, if x is a vector.

Details

Given an observed pattern of points with coordinates given by x and y, this function finds the smallest rectangle, with sides parallel to the coordinate axes, that contains all the points, and returns it as a window.

Value

A window (an object of class "owin").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin, as.owin, convexhull.xy, ripras

Examples

  x <- runif(30)
  y <- runif(30)
  w <- bounding.box.xy(x,y)
  plot(owin(), main="bounding.box.xy(x,y)")
  plot(w, add=TRUE)
  points(x,y)

  X <- rpoispp(30)
  plot(X, main="bounding.box.xy(X)")
  plot(bounding.box.xy(X), add=TRUE)


Hutchings' Bramble Canes data

Description

Data giving the locations and ages of bramble canes in a field. A marked point pattern.

Usage

data(bramblecanes)

Format

An object of class "ppp" representing the point pattern of plant locations. Entries include
x | Cartesian x-coordinate of plant
y | Cartesian y-coordinate of plant
marks | factor with levels 0,1, 2 indicating age

See ppp.object for details of the format.

Notes

These data record the (x,y) locations and ages of bramble canes in a field 9 metres square, rescaled to the unit square. The canes were classified according to age as either newly emergent, one or two years old. These are encoded as marks 0, 1 and 2 respectively in the dataset.

The data were recorded and analysed by Hutchings (1979) and further analysed by Diggle (1981a, 1981b, 1983), Diggle and Milne (1983), and Van Lieshout and Baddeley (1999). All analyses found that the pattern of newly emergent canes exhibits clustering, which Hutchings attributes to ``vigorous vegetative reproduction''.

Source

Hutchings (1979), data published in Diggle (1983)

References

Diggle, P. J. (1981a) Some graphical methods in the analysis of spatial point patterns. In Interpreting multivariate data, V. Barnett (Ed.) John Wiley and Sons.

Diggle, P. J. (1981b). Statistical analysis of spatial point patterns. N.Z. Statist. 16, 22–41.

Diggle, P.J. (1983) Statistical analysis of spatial point patterns. Academic Press.

Diggle, P. J. and Milne, R. K. (1983) Bivariate Cox processes: some models for bivariate spatial point patterns. Journal of the Royal Statistical Soc. Series B 45, 11–21.

Hutchings, M. J. (1979) Standing crop and pattern in pure stands of Mercurialis perennis and Rubus fruticosus in mixed deciduous woodland. Oikos 31, 351–357.

Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.


Biological Cells Point Pattern

Description

The data record the locations of the centres of 42 biological cells observed under optical microscopy in a histological section. The microscope field-of-view has been rescaled to the unit square.

The data were recorded by F.H.C. Crick and B.D. Ripley, and analysed in Ripley (1977, 1981) and Diggle (1983). They are often used as a canonical example of an `ordered' point pattern.

Usage

data(cells)

Format

An object of class "ppp" representing the point pattern of cell centres. See ppp.object for details of the format.

Source

Crick and Ripley, see Ripley (1977)

References

Diggle, P.J. (1983) Statistical analysis of spatial point patterns. Academic Press.

Ripley, B.D. (1977) Modelling spatial patterns (with discussion). Journal of the Royal Statistical Society, Series B 39, 172–212.

Ripley, B.D. (1981) Spatial statistics. John Wiley and Sons.


Centroid of a window

Description

Computes the centroid (centre of mass) of a window

Usage

 centroid.owin(w)

Arguments

w A window

Details

The centroid of the window w is computed. The centroid (``centre of mass'') is the point whose x and y coordinates are the mean values of the x and y coordinates of all points in the window.

The argument w should be a window (an object of class "owin", see owin.object for details) or can be given in any format acceptable to as.owin().

The calculation uses an exact analytic formula for the case of polygonal windows.

Note that the centroid of a window is not necessarily inside the window. If the window is convex then it does contain its centroid.

Value

A list with components x, y giving the coordinates of the centroid of the window w.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin, as.owin

Examples

  w <- owin(c(0,1),c(0,1))
  centroid.owin(w)
  # returns 0.5, 0.5

  data(demopat)
  w <- demopat$window
  # an irregular window
  ## Not run:
  plot(w)
  # plot the window
  points(centroid.owin(w))
  # mark its centroid

## End(Not run)

  wapprox <- as.mask(w)
  # pixel approximation of window
  ## Not run:
  points(centroid.owin(wapprox))
  # should be indistinguishable

## End(Not run)


Chorley-Ribble Cancer Data

Description

Spatial locations of cases of cancer of the larynx and cancer of the lung, and the location of a disused industrial incinerator. A marked point pattern.

Usage

data(chorley)

Format

The dataset chorley is an object of class "ppp" representing a marked point pattern. Entries include
x | Cartesian x-coordinate of home address
y | Cartesian y-coordinate of home address
marks | factor with levels larynx and lung
 | indicating whether this is a case of cancer of the larynx
 | or cancer of the lung.

See ppp.object for details of the format.

The dataset chorley.extra is a list with two components. The first component plotit is a function which will plot the data in a sensible fashion. The second component incin is a list with entries x and y giving the location of the industrial incinerator.

Coordinates are given in kilometres, and the resolution is 100 metres (0.1 km)

Notes

The data give the precise domicile addresses of new cases of cancer of the larynx (58 cases) and cancer of the lung (978 cases), recorded in the Chorley and South Ribble Health Authority of Lancashire (England) between 1974 and 1983. The supplementary data give the location of a disused industrial incinerator.

The data were first presented and analysed by Diggle (1990). They have subsequently been analysed by Diggle and Rowlingson (1994) and Baddeley et al. (2005).

The aim is to assess evidence for an increase in the incidence of cancer of the larynx in the vicinity of the now-disused industrial incinerator. The lung cancer cases serve as a surrogate for the spatially-varying density of the susceptible population.

The data are represented as a marked point pattern, with the points giving the spatial location of each individual's home address and the marks identifying whether each point is a case of laryngeal cancer or lung cancer.

Coordinates are in kilometres, and the resolution is 100 metres (0.1 km).

The dataset chorley has a polygonal window with 132 edges which closely approximates the boundary of the Chorley and South Ribble Health Authority.

Source

Coordinates of cases were provided by the Chorley and South Ribble Health Authority, and were kindly supplied by Professor Peter Diggle. Region boundary was digitised by Adrian Baddeley, 2005, from a photograph of an Ordnance Survey map.

References

Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005) Residual analysis for spatial point processes. Journal of the Royal Statistical Society, Series B 67, 617–666.

Diggle, P. (1990) A point process modelling approach to raised incidence of a rare phenomenon in the vicinity of a prespecified point. Journal of the Royal Statistical Soc. Series A 153, 349-362.

Diggle, P. and Rowlingson, B. (1994) A conditional approach to point process modelling of elevated risk. Journal of the Royal Statistical Soc. Series A 157, 433-440.


Interactively Define a Polygon

Description

Allows the user to create a polygon by point-and-click in the display.

Usage

  clickpoly(add=FALSE, n=NULL, ...)

Arguments

add | Logical value indicating whether to create a new plot (add=FALSE) or draw over the existing plot (add=TRUE).
n | Number of vertices of the polygon (if this is predetermined).
... | Arguments passed to locator to control the interactive plot.

Details

This function allows the user to create a polygonal window by interactively clicking on the screen display.

The user is prompted to point the mouse at any desired locations for the polygon vertices, and click the left mouse button to add each point. Interactive input stops after n clicks (if n was given) or when the middle mouse button is pressed.

The return value is a window (object of class "owin") representing the polygon.

This function uses the R{} command locator to input the mouse clicks. It only works on screen devices such as ‘X11’, ‘windows’ and ‘quartz’. Arguments that can be passed to locator through ... include pch (plotting character), cex (character expansion factor) and col (colour). See locator and par.

Value

A window (object of class "owin") representing the polygon.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

identify.ppp, clickppp, locator


Interactively Add Points

Description

Allows the user to create a point pattern by point-and-click in the display.

Usage

  clickppp(n=NULL, win=square(1), types=NULL, ..., add=FALSE,
main=NULL, hook=NULL)

Arguments

n | Number of points to be added (if this is predetermined).
win | Window in which to create the point pattern. An object of class "owin".
types | Vector of types, when creating a multitype point pattern.
... | Optional extra arguments to be passed to locator to control the display.
add | Logical value indicating whether to create a new plot (add=FALSE) or draw over the existing plot (add=TRUE).
main | Main heading for plot.
hook | For internal use only. Do not use this argument.

Details

This function allows the user to create a point pattern by interactively clicking on the screen display.

First the window win is plotted on the current screen device. Then the user is prompted to point the mouse at any desired locations and click the left mouse button to add each point. Interactive input stops after n clicks (if n was given) or when the middle mouse button is pressed.

The return value is a point pattern containing the locations of all the clicked points inside the original window win, provided that all of the clicked locations were inside this window. Otherwise, the window is expanded to a box large enough to contain all the points (as well as containing the original window).

If the argument types is given, then a multitype point pattern will be created. The user is prompted to input the locations of points of type type[i], for each successive index i. (If the argument n was given, there will be n points of each type.) The return value is a multitype point pattern.

This function uses the R{} command locator to input the mouse clicks. It only works on screen devices such as ‘X11’, ‘windows’ and ‘quartz’. Arguments that can be passed to locator through ... include pch (plotting character), cex (character expansion factor) and col (colour). See locator and par.

Value

A point pattern (object of class "ppp").

Author(s)

Original by Dominic Schuhmacher. Adapted by Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

identify.ppp, locator, clickpoly


Coefficients of Fitted Point Process Model

Description

Given a point process model fitted to a point pattern, extract the coefficients of the fitted model. A method for coef.

Usage

  ## S3 method for class 'ppm':
  coef(object, ...)

Arguments

object | The fitted point process model (an object of class "ppm")
... | Ignored.

Details

This function is a method for the generic function coef.

The argument object must be a fitted point process model (object of class "ppm"). Such objects are produced by the maximum pseudolikelihood fitting algorithm ppm).

This function extracts the vector of coefficients of the fitted model. This is the estimate of the parameter vector theta such that the conditional intensity of the model is of the form

lambda(u,x) = exp(theta . S(u,x))

where S(u,x) is a (vector-valued) statistic.

For example, if the model object is the uniform Poisson process, then coef(object) will yield a single value (named "(Intercept)") which is the logarithm of the fitted intensity of the Poisson process.

Use print.ppm to print a more useful description of the fitted model.

Value

A vector containing the fitted coefficients.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

print.ppm, ppm.object, ppm

Examples

    data(cells)

    poi <- ppm(cells, ~1, Poisson())
    coef(poi)
    # This is the log of the fitted intensity of the Poisson process

    stra <- ppm(cells, ~1, Strauss(r=0.07), rbord=0.07)
    coef(stra)

    # The two entries "(Intercept)" and "Interaction"
    # are respectively log(beta) and log(gamma)
    # in the usual notation for Strauss(beta, gamma, r)


Test Whether Two Function Objects Are Compatible

Description

Tests whether two function objects (class "fv") are compatible.

Usage

  compatible.fv(A, B)

Arguments

A,B Function value objects (class "fv").

Details

An object of class "fv" is essentially a data frame containing several different statistical estimates of the same function. Such objects are returned by Kest and its relatives.

This function tests whether two such objects are compatible (so that, for example, they could be added or subtracted).

The functions are compatible if they have been evaluated at the same sequence of values of the argument r, and if the statistical estimates have the same names.

Value

Logical value: TRUE if the objects are compatible, and FALSE if they are not.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf


Test Whether Two Pixel Images Are Compatible

Description

Tests whether two pixel image objects have compatible dimensions.

Usage

compatible.im(A, B, tol=1e-6)

Arguments

A,B | Pixel images (objects of class "im").
tol | Tolerance factor

Details

This function tests whether the pixel images A and B have compatible pixel dimensions. They are compatible if they have the same number of rows and columns, the same physical pixel dimensions, and occupy the same rectangle in the plane.

The argument tol specifies the maximum tolerated error in the pixel coordinates, expressed as a fraction of the dimensions of a single pixel.

Value

Logical value: TRUE if the images are compatible, and FALSE if they are not.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf


Take Complement of a Window

Description

Take the set complement of a window, within its enclosing rectangle or in a larger rectangle.

Usage

 complement.owin(w, frame=as.rectangle(w))

Arguments

w | an object of class "owin" describing a window of observation for a point pattern.
frame | Optional. The enclosing rectangle, with respect to which the set complement is taken.

Details

This yields a window object (of class "owin", see owin.object) representing the set complement of w with respect to the rectangle frame.

By default, frame is the enclosing box of w (originally specified by the arguments xrange and yrange given to owin when w was created). If frame is specified, it must be a rectangle (an object of class "owin" whose type is "rectangle") and it must be larger than the enclosing box of w. This rectangle becomes the enclosing box for the resulting window.

If w is a rectangle, then frame must be specified. Otherwise an error will occur (since the complement of w in itself is empty).

For rectangular and polygonal windows, the complement is computed by reversing the sign of each boundary polygon, while for binary masks it is computed by negating the pixel values.

Value

Another object of class "owin" representing the complement of the window, i.e. the inside of the window becomes the outside.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin, owin.object

Examples

   # rectangular
   a <- owin(c(0,1),c(0,1))
   b <- owin(c(-1,2),c(-1,2))
   bmina <- complement.owin(a, frame=b)
   # polygonal
   data(demopat)
   w <- demopat$window
   outside <- complement.owin(w)
   # mask
   w <- as.mask(demopat$window)
   outside <- complement.owin(w)


Concatenate x,y Coordinate Vectors

concatxy(spatstat) R Documentation

Concatenate xy Coordinate Vectors

Description

Concatenate any number of pairs of x and y coordinate vectors.

Usage

  concatxy(...)

Arguments

... Any number of arguments, each of which is a structure containing elements x and y.

Details

This function can be used to superimpose two or more point patterns of unmarked points (but see also superimpose which is recommended).

It assumes that each of the arguments in ... is a structure containing (at least) the elements x and y. It concatenates all the x elements into a vector x, and similarly for y, and returns these concatenated vectors.

Value

A list with two components x and y, which are the concatenations of all the corresponding x and y vectors in the argument list.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

superimpose, quadscheme

Examples

  dat <- runifrect(30)
  xy <- list(x=runif(10),y=runif(10))
  new <- concatxy(dat, xy)


Contour plot of pixel image

Description

Generates a contour plot of a pixel image.

Usage

   ## S3 method for class 'im':
   contour(x, ..., main, axes=TRUE, add=FALSE)

Arguments

x | Pixel image to be plotted. An object of class "im".
main | Character string to be displayed as the main title.
axes | Logical. If TRUE, coordinate axes are plotted (with tick marks) around a region slightly larger than the image window. If FALSE, no axes are plotted, and a box is drawn tightly around the image window. Ignored if add=TRUE.
add | Logical. If FALSE, a new plot is created. If TRUE, the contours are drawn over the existing plot.
... | Other arguments passed to contour.default controlling the contour plot; see Details.

Details

This is a method for the generic contour function, for objects of the class "im".

An object of class "im" represents a pixel image; see im.object.

This function displays the values of the pixel image x as a contour plot on the current plot device, using equal scales on the x and y axes.

The appearance of the plot can be modified using any of the arguments listed in the help for contour.default. Useful ones include:

nlevels
Number of contour levels to plot.
drawlabels
Whether to label the contour lines with text.
col,lty,lwd
Colour, type, and width of contour lines.

See contour.default for a full list of these arguments.

The defaults for any of the abovementioned arguments can be reset using spatstat.options.

Value

none.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

im.object, plot.im, persp.im

Examples

   # an image
   Z <- setcov(owin())
   contour(Z)
   contour(Z, axes=FALSE)


Convex Hull of Points

Description

Computes the convex hull of a set of points in two dimensions.

Usage

convexhull.xy(x, y=NULL)

Arguments

x | vector of x coordinates of observed points, or a 2-column matrix giving x,y coordinates, or a list with components x,y giving coordinates (such as a point pattern object of class "ppp".)
y | (optional) vector of y coordinates of observed points, if x is a vector.

Details

Given an observed pattern of points with coordinates given by x and y, this function computes the convex hull of the points, and returns it as a window.

Value

A window (an object of class "owin").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin, as.owin, bounding.box.xy, ripras

Examples

  x <- runif(30)
  y <- runif(30)
  w <- convexhull.xy(x,y)
  plot(owin(), main="convexhull.xy(x,y)", lty=2)
  plot(w, add=TRUE)
  points(x,y)

  X <- rpoispp(30)
  plot(X, main="convexhull.xy(X)")
  plot(convexhull.xy(X), add=TRUE)


Berman-Huntington points and lines data

Description

These data come from an intensive geological survey of a 70 x 158 km region in central Queensland, Australia. They consist of 67 points representing copper ore deposits, and 146 line segments representing geological `lineaments'. Lineaments are linear features, visible on a satellite image, that are believed to consist largely of geological faults (Berman, 1986, p. 55). It would be of great interest to predict the occurrence of copper deposits from the lineament pattern, since the latter can easily be observed on satellite images.

These data were introduced and analysed by Berman (1986). They have also been studied by Berman and Turner (1992), Baddeley and Turner (2000, 2005), Foxall and Baddeley (2002) and Baddeley et al (2005).

Many analyses have been performed on the southern half of the data only. This subset is also provided.

Usage

data(copper)

Format

copper is a list with the following entries:

Points
a point pattern (object of class "ppp") representing the full point pattern of copper deposits. See ppp.object for details of the format.
Lines
a line segment pattern (object of class "psp") representing the lineaments in the full dataset. See psp.object for details of the format. given as a data frame with 4 columns (x1, y1, x2, y2).
SouthWindow
the window delineating the southern half of the study region. An object of class "owin".
SouthPoints
the point pattern of copper deposits in the southern half of the study region. An object of class "ppp".
SouthLines
the line segment pattern of the lineaments in the southern half of the study region. An object of class "psp".

Source

Dr J. Huntington. Coordinates kindly provided by Dr. Mark Berman and Dr. A. Green, CSIRO, Sydney, Australia.

References

Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point patterns. Australian and New Zealand Journal of Statistics 42, 283–322.

Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005) Residual analysis for spatial point processes. Journal of the Royal Statistical Society, Series B 67, 617–666.

Baddeley, A. and Turner, R. (2005) Modelling spatial point patterns in R. In: A. Baddeley, P. Gregori, J. Mateu, R. Stoica, and D. Stoyan, editors, Case Studies in Spatial Point Pattern Modelling, Lecture Notes in Statistics number 185. Pages 23–74. Springer-Verlag, New York, 2006. ISBN: 0-387-28311-0.

Berman, M. (1986). Testing for spatial association between a point process and another stochastic process. Applied Statistics 35, 54–62.

Berman, M. and Turner, T.R. (1992) Approximating point process likelihoods with GLIM. Applied Statistics 41, 31–38.

Foxall, R. and Baddeley, A. (2002) Nonparametric measures of association between a spatial point process and a random set, with geological applications. Applied Statistics 51, 165–182.

Examples

  data(copper)

  # Plot full dataset

  plot(copper$Points)
  plot(copper$Lines, add=TRUE)

  # Plot southern half of data
  plot(copper$SouthPoints)
  plot(copper$SouthLines, add=TRUE)

  ## Not run:
    Z <- distmap(copper$SouthLines)
    plot(Z)
    X <- copper$SouthPoints
    ppm(X, ~D, covariates=list(D=Z))

## End(Not run)


Corners of a rectangle

Description

Returns the four corners of a rectangle

Usage

 corners(window)

Arguments

window A window. An object of class owin, or data in any format acceptable to as.owin().

Details

This trivial function is occasionally convenient. If window is of type "rectangle" this returns the four corners of the window itself; otherwise, it returns the corners of the bounding rectangle of the window.

Value

A list with two components x and y, which are numeric vectors of length 4 giving the coordinates of the four corner points of the (bounding rectangle of the) window.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

quad.object, quadscheme

Examples

  w <- unit.square()
  corners(w)
       # returns list(x=c(0,1,0,1),y=c(0,0,1,1))


Pairwise distances

Description

Computes the distances between pairs of `things' taken from two different datasets.

Usage

  crossdist(X, Y, ...)

Arguments

X,Y | Two objects of the same class.
... | Additional arguments depending on the method.

Details

Given two datasets X and Y (representing either two point patterns or two line segment patterns) crossdist computes the Euclidean distance from each thing in the first dataset to each thing in the second dataset, and returns a matrix containing these distances.

The function crossdist is generic, with methods for point patterns (objects of class "ppp"), line segment patterns (objects of class "psp"), and a default method. See the documentation for crossdist.ppp, crossdist.psp or crossdist.default for further details.

Value

A matrix whose [i,j] entry is the distance from the i-th thing in the first dataset to the j-th thing in the second dataset.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/

See Also

crossdist.ppp, crossdist.psp, crossdist.default, pairdist, nndist


Pairwise distances between two different sets of points

Description

Computes the distances between each pair of points taken from two different sets of points.

Usage

  ## Default S3 method:
  crossdist(X, Y, x2, y2, ..., period=NULL, method="C")

Arguments

X,Y | Numeric vectors of equal length specifying the coordinates of the first set of points.
x2,y2 | Numeric vectors of equal length specifying the coordinates of the second set of points.
... | Ignored.
period | Optional. Dimensions for periodic edge correction.
method | String specifying which method of calculation to use. Values are "C" and "interpreted".

Details

Given two sets of points, this function computes the Euclidean distance from each point in the first set to each point in the second set, and returns a matrix containing these distances.

This is a method for the generic function crossdist.

This function expects X and Y to be numeric vectors of equal length specifying the coordinates of the first set of points. The arguments x2,y2 specify the coordinates of the second set of points.

Alternatively if period is given, then the distances will be computed in the `periodic' sense (also known as `torus' distance). The points will be treated as if they are in a rectangle of width period[1] and height period[2]. Opposite edges of the rectangle are regarded as equivalent.

The argument method is not normally used. It is retained only for checking the validity of the software. If method = "interpreted" then the distances are computed using interpreted R code only. If method="C" (the default) then C code is used. The C code is faster by a factor of 4.

Value

A matrix whose [i,j] entry is the distance from the i-th point in the first set of points to the j-th point in the second set of points.

Author(s)

Pavel Grabarnik pavel.grabar@issp.serpukhov.su and Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/

See Also

crossdist, crossdist.ppp, crossdist.psp, pairdist, nndist, Gest

Examples

   d <- crossdist(runif(7), runif(7), runif(12), runif(12))
   d <- crossdist(runif(7), runif(7), runif(12), runif(12), period=c(1,1))


Pairwise distances between two different point patterns

Description

Computes the distances between pairs of points taken from two different point patterns.

Usage

  ## S3 method for class 'ppp':
  crossdist(X, Y, ..., periodic=FALSE, method="C")

Arguments

X,Y | Point patterns (objects of class "ppp").
... | Ignored.
periodic | Logical. Specifies whether to apply a periodic edge correction.
method | String specifying which method of calculation to use. Values are "C" and "interpreted".

Details

Given two point patterns, this function computes the Euclidean distance from each point in the first pattern to each point in the second pattern, and returns a matrix containing these distances.

This is a method for the generic function crossdist for point patterns (objects of class "ppp").

This function expects two point patterns X and Y, and returns the matrix whose [i,j] entry is the distance from X[i] to Y[j].

Alternatively if periodic=TRUE, then provided the windows containing X and Y are identical and are rectangular, then the distances will be computed in the `periodic' sense (also known as `torus' distance): opposite edges of the rectangle are regarded as equivalent. This is meaningless if the window is not a rectangle.

The argument method is not normally used. It is retained only for checking the validity of the software. If method = "interpreted" then the distances are computed using interpreted R code only. If method="C" (the default) then C code is used. The C code is faster by a factor of 4.

Value

A matrix whose [i,j] entry is the distance from the i-th point in X to the j-th point in Y.

Author(s)

Pavel Grabarnik pavel.grabar@issp.serpukhov.su and Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/

See Also

crossdist, crossdist.default, crossdist.psp, pairdist, nndist, Gest

Examples

   data(cells)
   d <- crossdist(cells, runifpoint(6))
   d <- crossdist(cells, runifpoint(6), periodic=TRUE)


Pairwise distances between two different line segment patterns

Description

Computes the distances between all pairs of line segments taken from two different line segment patterns.

Usage

  ## S3 method for class 'psp':
  crossdist(X, Y, ..., method="Fortran")

Arguments

X,Y | Line segment patterns (objects of class "psp").
... | Ignored.
method | String specifying which method of calculation to use. Values are "Fortran" and "interpreted".

Details

This is a method for the generic function crossdist.

Given two line segment patterns, this function computes the distance from each line segment in the first pattern to each line segment in the second pattern, and returns a matrix containing these distances.

Distances are calculated using the Hausdorff metric. The Hausdorff distance between two line segments is the maximum distance from any point on one of the segments to the nearest point on the other segment.

The argument method is not normally used. It is retained only for checking the validity of the software. If method = "interpreted" then the distances are computed using interpreted R code only. If method="Fortran" (the default) then Fortran code is used. The Fortran code is several times faster.

Value

A matrix whose [i,j] entry is the distance from the i-th line segment in X to the j-th line segment in Y.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

pairdist, nndist, Gest

Examples

   L1 <- psp(runif(5), runif(5), runif(5), runif(5), owin())
   L2 <- psp(runif(10), runif(10), runif(10), runif(10), owin())
   D <- crossdist(L1, L2)
  #result is a 5 x 10 matrix


Crossing Points of Two Line Segment Patterns

Description

Finds any crossing points between two line segment patterns.

Usage

  crossing.psp(A,B)

Arguments

A,B Line segment patterns (objects of class "psp").

Details

This function finds any crossing points between the line segment patterns A and B.

A crossing point occurs whenever one of the line segments in A intersects one of the line segments in B, at a nonzero angle of intersection.

Value

Point pattern (object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

selfcrossing.psp, psp.object, ppp.object.

Examples

  a <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
  b <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
  plot(a, col="green", main="crossing.psp")
  plot(b, add=TRUE, col="blue")
  P <- crossing.psp(a,b)
  plot(P, add=TRUE, col="red")


Convert Pixel Image from Numeric to Factor

Description

Transform the values of a pixel image from numeric values into a factor.

Usage

  ## S3 method for class 'im':
  cut(x, ...)

Arguments

x | A pixel image. An object of class "im".
... | Arguments passed to cut.default. They determine the breakpoints for the mapping from numerical values to factor values. See cut.default.

Details

This simple function applies the generic cut operation to the pixel values of the image x. The range of pixel values is divided into several intervals, and each interval is associated with a level of a factor. The result is another pixel image, with the same window and pixel grid as x, but with the numeric value of each pixel discretised by replacing it by the factor level.

This function is a convenient way to inspect an image and to obtain summary statistics. See the examples.

To select a subset of an image, use the subset operator [.im instead.

Value

A pixel image (object of class "im") with pixel values that are a factor. See im.object.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

cut, im.object

Examples

  # artificial image data
  Z <- setcov(square(1))

  Y <- cut(Z, 3)
  Y <- cut(Z, breaks=seq(0,1,length=5))

  # cut at the quartiles
  # (divides the image into 4 equal areas)
  Y <- cut(Z, quantile(Z))


Convert Point Pattern Marks from Numeric to Factor

Description

Transform the marks of a marked point pattern from numeric values into a factor.

Usage

  ## S3 method for class 'ppp':
  cut(x, ...)

Arguments

x | A two-dimensional point pattern. An object of class "ppp". This should be a marked point pattern, and the marks would normally be numerical values.
... | Arguments passed to cut.default. They determine the breakpoints for the mapping from numerical values to factor values. See cut.default.

Details

This simple function applies the generic cut operation to the marks of the point pattern x. The range of values of the numerical marks is divided into several intervals, and each interval is associated with a level of a factor. The result is a marked point pattern, with the same window and point locations as x, but with the numeric mark of each point discretised by replacing it by the factor level.

This function is a convenient way to transform a marked point pattern which has numeric marks into a multitype point pattern, for example to plot it or analyse it. See the examples.

To select some points from a point pattern, use the subset operator [.ppp instead.

Value

A multitype point pattern, that is, a point pattern object (of class "ppp") with a marks vector that is a factor.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

cut, ppp.object

Examples

 data(longleaf)
 # Longleaf Pines data
 # the marks are positive real numbers indicating tree diameters.

 ## Not run:
 plot(longleaf)

## End(Not run)

 # cut the range of tree diameters into three intervals
 long3 <- cut(longleaf, 3)
 ## Not run:
 plot(long3)

## End(Not run)

 # adult trees defined to have diameter at least 30 cm
 long2 <- cut(longleaf, breaks=c(0,30,100), labels=c("Sapling", "Adult"))
 plot(long2)
 plot(long2, cols=c("green","blue"))


Extract Original Data from a Fitted Point Process Model

Description

Given a fitted point process model, this function extracts the original point pattern dataset to which the model was fitted.

Usage

  data.ppm(object)

Arguments

object fitted point process model (an object of class "ppm").

Details

An object of class "ppm" represents a point process model that has been fitted to data. It is typically produced by the model-fitting algorithm ppm. The object contains complete information about the original data point pattern to which the model was fitted. This function extracts the original data pattern.

See ppm.object for a list of all operations that can be performed on objects of class "ppm".

Value

A point pattern (object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppm.object, ppp.object

Examples

 data(cells)
 fit <- ppm(cells, ~1, Strauss(r=0.1), rbord=0.1)
 X <- data.ppm(fit)
 # 'X' is identical to 'cells'


Generate a Default Pattern of Dummy Points

Description

Generates a default pattern of dummy points for use in a quadrature scheme.

Usage

 default.dummy(X, nd, random=FALSE, ntile=NULL, npix=NULL, ..., verbose=FALSE)

Arguments

X | The observed data point pattern. An object of class "ppp" or in a format recognised by as.ppp()
nd | Optional. Integer, or integer vector of length 2, specifying an nd * nd or nd[1] * nd[2] rectangular array of dummy points.
random | Logical value. If TRUE, the dummy points are randomised.
ntile | Optional. Integer or pair of integers specifying the number of rows and columns of tiles used in the counting rule.
npix | Optional. Integer or pair of integers specifying the number of rows and columns of pixels used in computing approximate areas.
... | Ignored.
verbose | If TRUE, information about the construction of the quadrature scheme is printed.

Details

This function provides a sensible default for the dummy points in a quadrature scheme.

A quadrature scheme consists of the original data point pattern, an additional pattern of dummy points, and a vector of quadrature weights for all these points. See quad.object for further information about quadrature schemes.

If random is false (the default), then the function creates dummy points in an nd[1] by nd[1] rectangular grid. If random is true, then the frame of the window is divided into an nd[1] by nd[1] array of tiles, and one dummy point is generated at random inside each tile. In either case, the four corner points of the frame of the window are added. Then if the window is not rectangular, any dummy points lying outside it are deleted.

If nd is missing, a default value (depending on the data pattern X) is computed by default.ngrid.

Alternative functions for creating dummy patterns include corners, gridcentres, stratrand and spokes.

Value

A point pattern (an object of class "ppp", see ppp.object) containing the dummy points.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

quad.object, quadscheme, corners, gridcentres, stratrand, spokes

Examples

  data(simdat)
  P <- simdat
  D <- default.dummy(P, 100)
  ## Not run: plot(D)
  Q <- quadscheme(P, D, "grid")
  ## Not run: plot(union.quad(Q))


Artificial Data Point Pattern

Description

This is an artificial dataset, for use in testing and demonstrating the capabilities of the spatstat package. It is a multitype point pattern in an irregular polygonal window. There are two types of points. The window contains a polygonal hole.

Usage

data(demopat)

Format

An object of class "ppp" representing the point pattern.

See ppp.object for details of the format of a point pattern object.

Source

Adrian Baddeley


Kernel Smoothed Intensity of Point Pattern

Description

Compute a kernel smoothed intensity function from a point pattern.

Usage

  ## S3 method for class 'ppp':
  density(x, sigma, ..., weights, edge=TRUE, varcov=NULL)

Arguments

x | Point pattern (object of class "ppp") to be smoothed.
sigma | Standard deviation of isotropic Gaussian smoothing kernel.
weights | Optional vector of weights to be attached to the points. May include negative values.
... | Arguments passed to as.mask to determine the pixel resolution.
edge | Logical flag: if TRUE, apply edge correction.
varcov | Variance-covariance matrix of anisotropic Gaussian kernel. Incompatible with sigma.

Details

This is a method for the generic function density.

A kernel estimate of the intensity function of the point pattern is computed. The result is the convolution of the isotropic Gaussian kernel of standard deviation sigma with point masses at each of the data points. The default is to assign a unit weight to each point. If weights is present, the point masses have these weights (which may be signed real numbers).

If edge=TRUE, the intensity estimate is corrected for edge effect bias by dividing it by the convolution of the Gaussian kernel with the window of observation.

Instead of the isotropic Gaussian kernel with standard deviation sigma, the smoothing kernel may be chosen to be any Gaussian kernel, by giving the variance-covariance matrix varcov. The arguments sigma and varcov are incompatible. Also sigma may be a vector of length 2 giving the standard deviations of two independent Gaussian coordinates, thus equivalent to varcov = diag(sigma^2).

Computation is performed using the Fast Fourier Transform. Accuracy depends on the pixel resolution, controlled by the arguments ... passed to as.mask.

Value

A pixel image (object of class "im").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp.object, im.object

Examples

  data(cells)
  Z <- density.ppp(cells, 0.05)
  plot(Z)


Kernel Smoothing of Line Segment Pattern

Description

Compute a kernel smoothed intensity function from a line segment pattern.

Usage

  ## S3 method for class 'psp':
  density(x, sigma, ..., edge=TRUE)

Arguments

x | Line segment pattern (object of class "psp") to be smoothed.
sigma | Standard deviation of isotropic Gaussian smoothing kernel.
... | Extra arguments passed to as.mask which determine the resolution of the resulting image.
edge | Logical flag indicating whether to apply edge correction.

Details

This is a method for the generic function density.

A kernel estimate of the intensity of the line segment pattern is computed. The result is the convolution of the isotropic Gaussian kernel, of standard deviation sigma, with the line segments. Computation is performed analytically.

If edge=TRUE this result is adjusted for edge effects by dividing it by the convolution of the same Gaussian kernel with the observation window.

Value

A pixel image (object of class "im").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

psp.object, im.object, density

Examples

  L <- psp(runif(20),runif(20),runif(20),runif(20), window=owin())
  D <- density(L, sigma=0.03)
  plot(D, main="density(L)")
  plot(L, add=TRUE)


Kernel Smoothed Intensity of Split Point Pattern

Description

Compute a kernel smoothed intensity function for each of the components of a split point pattern.

Usage

  ## S3 method for class 'splitppp':
  density(x, ...)

Arguments

x | Split point pattern (object of class "splitppp" created by split.ppp) to be smoothed.
... | Arguments passed to density.ppp to control the smoothing, pixel resolution, edge correction etc.

Details

This is a method for the generic function density.

The argument x should be an object of class "splitppp", effectively a list of point patterns.

Typically x is obtained by applying the function split.ppp to a point pattern y by calling split(y). This splits the points of y into several sub-patterns.

A kernel estimate of the intensity function of each of the point patterns is computed using density.ppp.

The return value is a list, each of whose entries is a pixel image (object of class "im"). The return value also belongs to the class "listof" and can be plotted or printed.

Value

A list of pixel images (objects of class "im"). Can be plotted or printed.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp.object, im.object

Examples

  data(amacrine)
  Z <- density(split(amacrine), 0.05)
  plot(Z)


Deprecated spatstat functions

Description

Deprecated spatstat functions.

Usage

conspire(...)
ksmooth.ppp(x, sigma, ..., edge=TRUE)
mpl(Q, trend, interaction, data, correction, rbord, use.gam)
rtoro(X, which=NULL, radius=NULL, width=NULL, height=NULL)

Details

conspire has been replaced by plot.fv.

ksmooth.ppp has been replaced by density.ppp.

mpl has been replaced by ppm.

rtoro has been replaced by rshift.


Diagnostic Plots for Fitted Point Process Model

Description

Given a point process model fitted to a point pattern, produce diagnostic plots based on residuals.

Usage

  diagnose.ppm(object, ..., type="raw", which="all", sigma=NULL,
               rbord=reach(object), cumulative=TRUE,
               plot.it=TRUE, rv = NULL, compute.sd=TRUE,
               compute.cts=TRUE, typename, check=TRUE, repair=TRUE,
               oldstyle=FALSE)
  ## S3 method for class 'diagppm':
  plot(x, ..., which,
               plot.neg="image", plot.smooth="imagecontour",
               plot.sd=TRUE, spacing=0.1,
               srange=NULL, monochrome=FALSE, main=NULL)

Arguments

object | The fitted point process model (an object of class "ppm") for which diagnostics should be produced. This object is usually obtained from ppm.
type | String indicating the type of residuals or weights to be used. Current options are "eem" for the Stoyan-Grabarnik exponential energy weights, "raw" for the raw residuals, "inverse" for the inverse-lambda residuals, and "pearson" for the Pearson residuals. A partial match is adequate.
which | Character string or vector indicating the choice(s) of plots to be generated. Options are "all", "marks", "smooth", "x", "y" and "sum". Multiple choices may be given but must be matched exactly. See Details.
sigma | Bandwidth for kernel smoother in "smooth" option.
rbord | Width of border to avoid edge effects. The diagnostic calculations will be confined to those points of the data pattern which are at least rbord units away from the edge of the window.
cumulative | Logical flag indicating whether the lurking variable plots for the x and y coordinates will be the plots of cumulative sums of marks (cumulative=TRUE) or the plots of marginal integrals of the smoothed residual field (cumulative=FALSE).
plot.it | Logical value indicating whether plots should be shown. If plot.it=FALSE, the computed diagnostic quantities are returned without plotting them.
plot.neg | One of "discrete" or "image" indicating how the density part of the residual measure should be plotted.
plot.smooth | One of "image", "persp", "contour" or "imagecontour" indicating how the smoothed residual field should be plotted.
compute.sd,plot.sd | Logical values indicating whether error bounds should be computed and added to the "x" and "y" plots. The default is TRUE for Poisson models and FALSE for non-Poisson models. See Details.
rv | Usually absent. If this argument is present, the values of the residuals will not be calculated from the fitted model object but will instead be taken directly from this vector.
spacing | The spacing between plot panels (when a four-panel plot is generated) expressed as a fraction of the width of the window of the point pattern.
srange | Vector of length 2 that will be taken as giving the range of values of the smoothed residual field, when generating an image plot of this field. This is useful if you want to generate diagnostic plots for two different fitted models using the same colour map.
monochrome | Flag indicating whether images should be displayed in greyscale (suitable for publication) or in colour (suitable for the screen). The default is to display in colour.
check | Logical value indicating whether to check the internal format of object. If there is any possibility that this object has been restored from a dump file, or has otherwise lost track of the environment where it was originally computed, set check=TRUE.
repair | Logical value indicating whether to repair the internal format of object, if it is found to be damaged.
oldstyle | Logical flag indicating whether error bounds should be plotted using the approximation given in the original paper (oldstyle=TRUE), or using the correct asymptotic formula (oldstyle=FALSE).
x | The value returned from a previous call to diagnose.ppm. An object of class "diagppm".
typename | String to be used as the name of the residuals.
main | Main title for the plot.
... | Extra arguments, controlling either the resolution of the smoothed image (passed from diagnose.ppm to density.ppp) or the appearance of the plots (passed from diagnose.ppm to plot.diagppm and from plot.diagppm to plot.default).
compute.cts | Advanced use only.

Details

This function generates several diagnostic plots for a fitted point process model. The plots display the residuals from the fitted model (Baddeley et al, 2005) or alternatively the `exponential energy marks' (Stoyan and Grabarnik, 1991). These plots can be used to assess goodness-of-fit, to identify outliers in the data, and to reveal departures from the fitted model. See also the companion function qqplot.ppm.

The argument object must be a fitted point process model (object of class "ppm") typically produced by the maximum pseudolikelihood fitting algorithm ppm).

The argument type selects the type of residual or weight that will be computed. Current options are:

"eem":
exponential energy marks (Stoyan and Grabarnik, 1991) computed by eem. These are positive weights attached to the data points (i.e. the points of the point pattern dataset to which the model was fitted). If the fitted model is correct, then the sum of these weights for all data points in a spatial region B has expected value equal to the area of B. See eem for further explanation.
"raw", "inverse" or "pearson":
point process residuals (Baddeley et al, 2005) computed by the function residuals.ppm. These are residuals attached both to the data points and to some other points in the window of observation (namely, to the dummy points of the quadrature scheme used to fit the model). If the fitted model is correct, then the sum of the residuals in a spatial region B has mean zero. The options are
  • "raw": the raw residuals;
  • "inverse": the `inverse-lambda' residuals, a counterpart of the exponential energy weights;
  • "pearson": the Pearson residuals.

See residuals.ppm for further explanation.

The argument which selects the type of plot that is produced. Options are:

"marks":
plot the residual measure. For the exponential energy weights (type="eem") this displays circles centred at the points of the data pattern, with radii proportional to the exponential energy weights. For the residuals (type="raw", type="inverse" or type="pearson") this again displays circles centred at the points of the data pattern with radii proportional to the (positive) residuals, while the plotting of the negative residuals depends on the argument plot.neg. If plot.neg="image" then the negative part of the residual measure, which is a density, is plotted as a colour image. If plot.neg="discrete" then the discretised negative residuals (obtained by approximately integrating the negative density using the quadrature scheme of the fitted model) are plotted as squares centred at the dummy points with side lengths proportional to the (negative) residuals. [To control the size of the circles and squares, use the argument maxsize.]
"smooth":
plot a kernel-smoothed version of the residual measure. Each data or dummy point is taken to have a `mass' equal to its residual or exponential energy weight. (Note that residuals can be negative). This point mass is then replaced by a bivariate isotropic Gaussian density with standard deviation sigma. The value of the smoothed residual field at any point in the window is the sum of these weighted densities. If the fitted model is correct, this smoothed field should be flat, and its height should be close to 0 (for the residuals) or 1 (for the exponential energy weights). The field is plotted either as an image, contour plot or perspective view of a surface, according to the argument plot.smooth. The range of values of the smoothed field is printed if the option which="sum" is also selected.
"x":
produce a `lurking variable' plot for the x coordinate. This is a plot of h(x) against x (solid lines) and of E(h(x)) against x (dashed lines), where h(x) is defined below, and E(h(x)) denotes the expectation of h(x) assuming the fitted model is true.
  • if cumulative=TRUE then h(x) is the cumulative sum of the weights or residuals for all points which have X coordinate less than or equal to x. For the residuals E(h(x)) = 0, and for the exponential energy weights E(h(x)) = area of the subset of the window to the left of the line X=x.
  • if cumulative=FALSE then h(x) is the marginal integral of the smoothed residual field (see the case which="smooth" described above) on the x axis. This is approximately the derivative of the plot for cumulative=TRUE. The value of h(x) is computed by summing the values of the smoothed residual field over all pixels with the given x coordinate. For the residuals E(h(x)) = 0, and for the exponential energy weights E(h(x)) = length of the intersection between the observation window and the line X=x.

If plot.sd = TRUE, then superimposed on the lurking variable plot are the pointwise two-standard-deviation error limits for h(x) calculated for the inhomogeneous Poisson process. The default is plot.sd = TRUE for Poisson models and plot.sd = FALSE for non-Poisson models.

"y":
produce a similar lurking variable plot for the y coordinate.
"sum":
print the sum of the weights or residuals for all points in the window (clipped by a margin rbord if required) and the area of the same window. If the fitted model is correct the sum of the exponential energy weights should equal the area of the window, while the sum of the residuals should equal zero. Also print the range of values of the smoothed field displayed in the "smooth" case.
"all":
All four of the diagnostic plots listed above are plotted together in a two-by-two display. Top left panel is "marks" plot. Bottom right panel is "smooth" plot. Bottom left panel is "x" plot. Top right panel is "y" plot, rotated 90 degrees.

The argument rbord ensures there are no edge effects in the computation of the residuals. The diagnostic calculations will be confined to those points of the data pattern which are at least rbord units away from the edge of the window. The value of rbord should be greater than or equal to the range of interaction permitted in the model.

By default, the two-standard-deviation limits are calculated from the exact formula for the asymptotic variance of the residuals under the asymptotic normal approximation, equation (37) of Baddeley et al (2006). However, for compatibility with the original paper of Baddeley et al (2005), if oldstyle=TRUE, the two-standard-deviation limits are calculated using the innovation variance, an over-estimate of the true variance of the residuals.

The argument rv would normally be used only by experts. It enables the user to substitute arbitrary values for the residuals or marks, overriding the usual calculations. If rv is present, then instead of calculating the residuals from the fitted model, the algorithm takes the entries of the vector rv to be the values of the residuals or marks, and plots them in the manner appropriate to the type of residual or mark selected by type. The length of rv must equal the number of points in the original data point pattern (if type="eem") or the number of quadrature (data and dummy) points used to fit the model (if type="raw", type="inverse" or type="pearson").

The return value is an object of class "diagppm". There are methods for plot and print for such objects. See the Examples.

See also the companion functions qqplot.ppm, which produces a Q-Q plot of the residuals, and lurking, which produces lurking variable plots for any spatial covariate.

Value

An object of class "diagppm" which contains the coordinates needed to reproduce the selected plots. This object can be plotted using plot.diagppm and printed using print.diagppm.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005) Residual analysis for spatial point processes. Journal of the Royal Statistical Society, Series B 67, 617–666.

Baddeley, A., Moller, J. and Pakes, A.G. (2006) Properties of residuals for spatial point processes. To appear.

Stoyan, D. and Grabarnik, P. (1991) Second-order characteristics for stochastic structures connected with Gibbs point processes. Mathematische Nachrichten, 151:95–100.

See Also

residuals.ppm, eem, ppm.object, qqplot.ppm, lurking, ppm

Examples

    data(cells)
    fit <- ppm(cells, ~x, Strauss(r=0.15), rbord=0.15)
    diagnose.ppm(fit, rbord=0.15)
    diagnose.ppm(fit, type="pearson", rbord=0.15)
    diagnose.ppm(fit, rbord=0.15, which="marks")
    diagnose.ppm(fit, rbord=0.15, type="raw", plot.neg="discrete")

    # save the diagnostics and plot them later
    u <- diagnose.ppm(fit, rbord=0.15, plot.it=FALSE)
    plot(u)
    plot(u, which="marks")


Diameter of a Window

Description

Computes the diameter of a window

Usage

 diameter(w)

Arguments

w A window, whose diameter will be computed.

Details

This function computes the diameter of a window of arbitrary shape, i.e. the maximum distance between any two points in the window.

The argument w should be a window (an object of class "owin", see owin.object for details) or can be given in any format acceptable to as.owin().

Value

The numerical value of the diameter of the window.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin, as.owin

Examples

  w <- owin(c(0,1),c(0,1))
  diameter(w)
  # returns sqrt(2)
  data(letterR)
  diameter(letterR)


Diggle-Gratton model

Description

Creates an instance of the Diggle-Gratton pairwise interaction point process model, which can then be fitted to point pattern data.

Usage

  DiggleGratton(delta, rho)

Arguments

delta | lower threshold delta
rho | upper threshold rho

Details

Diggle and Gratton (1984, pages 208-210) introduced the pairwise interaction point process with pair potential h(t) of the form

h(t) = ((t - delta)/(rho - delta))^kappa, { } delta <= t <= rho

with h(t) = 0 for t < delta and h(t) = 1 for t > rho. Here delta, rho and kappa are parameters.

Note that we use the symbol kappa where Diggle and Gratton (1984) and Diggle, Gates and Stibbard (1987) use beta, since in spatstat we reserve the symbol beta for an intensity parameter.

The parameters must all be nonnegative, and must satisfy delta <= rho.

The potential is inhibitory, i.e. this model is only appropriate for regular point patterns. The strength of inhibition increases with kappa. For kappa=0 the model is a hard core process with hard core radius delta. For kappa=infinity the model is a hard core process with hard core radius rho.

The irregular parameters delta, rho must be given in the call to DiggleGratton, while the regular parameter kappa will be estimated.

Value

An object of class "interact" describing the interpoint interaction structure of a point process.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Diggle, P.J., Gates, D.J. and Stibbard, A. (1987) A nonparametric estimator for pairwise-interaction point processes. Biometrika 74, 763 – 770.

Diggle, P.J. and Gratton, R.J. (1984) Monte Carlo methods of inference for implicit statistical models. Journal of the Royal Statistical Society, series B 46, 193 – 212.

See Also

ppm, ppm.object, Pairwise

Examples

   data(cells)
   ppm(cells, ~1, DiggleGratton(0.05, 0.1))


Dilate a Window

Description

Perform morphological dilation of a window

Usage

 dilate.owin(w, r, ...)

Arguments

w | A window (object of class "owin".
r | positive number: the radius of dilation.
... | extra arguments to as.mask controlling the pixel resolution

Details

The morphological dilation of a set W by a distance r > 0 is the set consisting of all points lying at most r units away from W. Effectively, dilation adds a margin of width r onto the set W.

This function computes the dilation of the window w. If w is not a rectangle, it must be approximated by a binary pixel image, and the arguments "..." are passed to as.mask to determine the pixel resolution. There is a sensible default.

Value

Another object of class "owin" representing the dilated window.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin, as.owin

Examples

  w <- owin(c(0,1),c(0,1))
  v <- dilate.owin(w, 0.1)
  # returns rectangle [-0.1, 1.1] x [-0.1, 1.1]


Compute Quadrature Weights Based on Dirichlet Tessellation

Description

Computes quadrature weights for a given set of points, using the areas of tiles in the Dirichlet tessellation.

Usage

 dirichlet.weights(X, window=NULL, exact=TRUE, ...)

Arguments

X | Data defining a point pattern.
window | Default window for the point pattern
exact | Logical value. If TRUE, compute exact areas using the package deldir. If FALSE, compute approximate areas using a pixel raster.
... | Ignored.

Details

This function computes a set of quadrature weights for a given pattern of points (typically comprising both ``data'' and `dummy'' points). See quad.object for an explanation of quadrature weights and quadrature schemes.

The weights are computed using the Dirichlet tessellation. First X and (optionally) window are converted into a point pattern object. Then the Dirichlet tessellation of the points of X is computed. The weight attached to a point of X is the area of its Dirichlet tile (inside the window X$window).

If exact=TRUE the Dirichlet tessellation is computed exactly by the Lee-Schachter algorithm using the package deldir. Otherwise a pixel raster approximation is constructed and the areas are approximations to the true weights. In all cases the sum of the weights is equal to the area of the window.

Value

Vector of nonnegative weights for each point in X.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

quad.object, gridweights

Examples

  Q <- quadscheme(runifpoispp(10))
  X <- as.ppp(Q) # data and dummy points together
  w <- dirichlet.weights(X, exact=FALSE)


Circular Window

Description

Creates a circular window

Usage

 disc(radius=1, centre=c(0,0), ..., mask=FALSE, npoly=128)

Arguments

radius | Radius of the circle.
centre | Coordinates of the centre of the circle.
mask | Logical flag controlling the type of approximation to a perfect circle. See Details.
npoly | Number of edges of the polygonal approximation, if mask=FALSE.
... | Arguments passed to as.mask determining the pixel resolution, if mask=TRUE.

Details

This command creates a window object representing a disc, with the given radius and centre.

By default, the circle is approximated by a polygon with npoly edges.

If mask=TRUE, then the disc is approximated by a binary pixel mask. The resolution of the mask is controlled by the arguments ... which are passed to as.mask.

Value

An object of class "owin" (see owin.object) specifying a window.

Note

This function can also be used to generate regular polygons, by setting npoly to a small integer value. For example npoly=5 generates a pentagon and npoly=13 a triskaidecagon.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin.object, owin, as.mask

Examples

 # unit disc
 W <- disc()
 # disc of radius 3 centred at x=10, y=5
 W <- disc(3, c(10,5))
 #
 plot(disc())
 plot(disc(mask=TRUE))
 # nice smooth circle
 plot(disc(npoly=256))
 # how to control the resolution of the mask
 plot(disc(mask=TRUE, dimyx=256))
 # check accuracy of approximation
 area.owin(disc())/pi
 area.owin(disc(mask=TRUE))/pi


Distance Map

Description

Compute the distance map of an object. Generic.

Usage

  distmap(X, ...)

Arguments

X | Any suitable dataset representing a two-dimensional object, such as a point pattern (object of class "ppp"), or a window (object of class "owin").
... | Arguments passed to as.mask to control pixel resolution.

Details

The ``distance map'' of a set of points A is the function f whose value f(x) is defined for any two-dimensional location x as the shortest distance from x to A.

This function computes the distance map of the set X and returns the distance map as a pixel image.

This is generic. Methods are provided for point patterns (distmap.ppp) and windows (distmap.owin).

Value

A pixel image (object of class "im") whose grey scale values are the values of the distance map.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

distmap.ppp, distmap.owin

Examples

  data(cells)
  U <- distmap(cells)
  data(letterR)
  V <- distmap(letterR)
  ## Not run:
  plot(U)
  plot(V)

## End(Not run)


Distance Map of Window

Description

Computes the distance from each pixel to the nearest point in the given window.

Usage

  ## S3 method for class 'owin':
  distmap(X, ...)

Arguments

X | A window (object of class "owin").
... | Arguments passed to as.mask to control pixel resolution.

Details

The ``distance map'' of a window W is the function f whose value f(u) is defined for any two-dimensional location u as the shortest distance from u to W.

This function computes the distance map of the window X and returns the distance map as a pixel image. The greyscale value at a pixel u equals the distance from u to the nearest pixel in X.

Additionally, the return value has an attribute "bdry" which is also a pixel image. The grey values in "bdry" give the distance from each pixel to the bounding rectangle of the image.

If the window X is not already a pixellated window (a binary image mask), it is converted into one. The arguments ... control the pixel resolution in this case, but will otherwise be ignored.

This function is a method for the generic distmap.

Value

A pixel image (object of class "im") whose greyscale values are the values of the distance map. The return value has an attribute "bdry" which is a pixel image.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

distmap, distmap.ppp

Examples

  data(letterR)
  U <- distmap(letterR)
  ## Not run:
  plot(U)
  plot(attr(U, "bdry"))

## End(Not run)


Distance Map of Point Pattern

Description

Computes the distance from each pixel to the nearest point in the given point pattern.

Usage

  ## S3 method for class 'ppp':
  distmap(X, ...)

Arguments

X | A point pattern (object of class "ppp").
... | Arguments passed to as.mask to control pixel resolution.

Details

The ``distance map'' of a point pattern X is the function f whose value f(u) is defined for any two-dimensional location u as the shortest distance from u to X.

This function computes the distance map of the point pattern X and returns the distance map as a pixel image. The greyscale value at a pixel u equals the distance from u to the nearest point of the pattern X.

Additionally, the return value has two attributes, "index" and "bdry", which are also pixel images. The grey values in "bdry" give the distance from each pixel to the bounding rectangle of the image. The grey values in "index" are integers identifying which point of X is closest.

This is a method for the generic function distmap.

Value

A pixel image (object of class "im") whose greyscale values are the values of the distance map. The return value has attributes "index" and "bdry" which are also pixel images.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

distmap, distmap.owin

Examples

  data(cells)
  U <- distmap(cells)
  ## Not run:
  plot(U)
  plot(attr(U, "bdry"))
  plot(attr(U, "index"))

## End(Not run)


Distance Map of Line Segment Pattern

Description

Computes the distance from each pixel to the nearest line segment in the given line segment pattern.

Usage

  ## S3 method for class 'psp':
  distmap(X, ...)

Arguments

X | A line segment pattern (object of class "psp").
... | Arguments passed to as.mask to control pixel resolution.

Details

The ``distance map'' of a line segment pattern X is the function f whose value f(u) is defined for any two-dimensional location u as the shortest distance from u to X.

This function computes the distance map of the line segment pattern X and returns the distance map as a pixel image. The greyscale value at a pixel u equals the distance from u to the nearest line segment of the pattern X.

Additionally, the return value has two attributes, "index" and "bdry", which are also pixel images. The grey values in "bdry" give the distance from each pixel to the bounding rectangle of the image. The grey values in "index" are integers identifying which line segment of X is closest.

This is a method for the generic function distmap.

Value

A pixel image (object of class "im") whose greyscale values are the values of the distance map. The return value has attributes "index" and "bdry" which are also pixel images.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

distmap, distmap.owin, distmap.ppp

Examples

    a <- psp(runif(20),runif(20),runif(20),runif(20), window=owin())
    Z <- distmap(a)
    plot(Z)
    plot(a, add=TRUE)


Extract Dummy Points Used to Fit a Point Process Model

Description

Given a fitted point process model, this function extracts the `dummy points' of the quadrature scheme used to fit the model.

Usage

  dummy.ppm(object)

Arguments

object fitted point process model (an object of class "ppm").

Details

An object of class "ppm" represents a point process model that has been fitted to data. It is typically produced by the model-fitting algorithm ppm.

The ppm algorithm approximates the pseudolikelihood integral by a sum over a finite set of quadrature points, which is constructed by augmenting the original data point pattern by a set of ``dummy'' points. The fitted model object returned by ppm contains complete information about this quadrature scheme. See ppm or ppm.object for further information.

This function extracts the dummy points of the quadrature scheme. A typical use of this function would be to count the number of dummy points, to gauge the accuracy of the approximation to the exact pseudolikelihood.

See ppm.object for a list of all operations that can be performed on objects of class "ppm".

Value

A point pattern (object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppm.object, ppp.object, ppm

Examples

 data(cells)
 fit <- ppm(cells, ~1, Strauss(r=0.1), rbord=0.1)
 X <- dummy.ppm(fit)
 X$n
 # this is the number of dummy points in the quadrature scheme


Determine Duplicated Points in a Spatial Point Pattern

Description

Determines which points in a spatial point pattern are duplicates of previous points, and returns a logical vector.

Usage

 ## S3 method for class 'ppp':
 duplicated(x, ...)

Arguments

x | A spatial point pattern (object of class "ppp").
... | Ignored.

Details

This is a method for the generic function duplicated for point pattern datasets (of class "ppp", see ppp.object).

Two points in a point pattern are deemed to be identical if their x,y coordinates are the same, and their marks are also the same (if they carry marks). The Examples section illustrates how it is possible for a point pattern to contain a pair of identical points.

This function determines which points in x duplicate other points that appeared earlier in the sequence. It returns a logical vector with entries that are TRUE for duplicated points and FALSE for unique (non-duplicated) points.

Value

A logical vector of length equal to the number of points in x.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp.object, unique.ppp, multiplicity.ppp

Examples

   X <- ppp(c(1,1,0.5), c(2,2,1), window=square(3))
   duplicated(X)


Exponential Energy Marks

Description

Given a point process model fitted to a point pattern, compute the Stoyan-Grabarnik diagnostic ``exponential energy marks'' for the data points.

Usage

  eem(fit, check=TRUE)

Arguments

fit | The fitted point process model. An object of class "ppm".
check | Logical value indicating whether to check the internal format of fit. If there is any possibility that this object has been restored from a dump file, or has otherwise lost track of the environment where it was originally computed, set check=TRUE.

Details

Stoyan and Grabarnik (1991) proposed a diagnostic tool for point process models fitted to spatial point pattern data. Each point x_i of the data pattern X is given a `mark' or `weight'

m_i = frac 1 {hatλ(x_i,X)}

where hatλ(x_i,X) is the conditional intensity of the fitted model. If the fitted model is correct, then the sum of these marks for all points in a region B has expected value equal to the area of B.

The argument fit must be a fitted point process model (object of class "ppm"). Such objects are produced by the maximum pseudolikelihood fitting algorithm ppm). This fitted model object contains complete information about the original data pattern and the model that was fitted to it.

The value returned by eem is the vector of weights m_i associated with the points x_i of the original data pattern. The original data pattern (in corresponding order) can be extracted from fit using data.ppm.

The function diagnose.ppm produces a set of sensible diagnostic plots based on these weights.

Value

A vector containing the values of the exponential energy mark for each point in the pattern.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Stoyan, D. and Grabarnik, P. (1991) Second-order characteristics for stochastic structures connected with Gibbs point processes. Mathematische Nachrichten, 151:95–100.

See Also

diagnose.ppm, ppm.object, data.ppm, residuals.ppm, ppm

Examples

    data(cells)
    fit <- ppm(cells, ~x, Strauss(r=0.15), rbord=0.15)
    ee <- eem(fit)
    sum(ee)/area.owin(cells$window) # should be about 1 if model is correct
    Y <- setmarks(cells, ee)
    plot(Y, main="Cells data\n Exponential energy marks")


Endpoints of Line Segment Pattern

Description

Extracts the endpoints of each line segment in a line segment pattern.

Usage

  endpoints.psp(x, which="both")

Arguments

x | A line segment pattern (object of class "psp").
which | String specifying which endpoint or endpoints should be returned. See Details.

Details

This function extracts one endpoint, or both endpoints, from each of the line segments in x, and returns these points as a point pattern object.

The argument which determines which endpoint or endpoints of each line segment should be returned:

which="both"
(the default): both endpoints of each line segment are returned. The result is a point pattern with twice as many points as there are line segments in x.
which="first"
select the first endpoint of each line segment (returns the points with coordinates x$ends$x0, x$ends$y0).
which="second"
select the second endpoint of each line segment (returns the points with coordinates x$ends$x1, x$ends$y1).
which="left"
select the left-most endpoint (the endpoint with the smaller x coordinate) of each line segment.
which="right"
select the right-most endpoint (the endpoint with the greater x coordinate) of each line segment.
which="lower"
select the lower endpoint (the endpoint with the smaller y coordinate) of each line segment.
which="upper"
select the upper endpoint (the endpoint with the greater y coordinate) of each line segment.

The result is a point pattern. It also has an attribute "id" which is an integer vector identifying the segment which contributed each point.

Value

Point pattern (object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

psp.object, ppp.object, midpoints.psp

Examples

  a <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
  plot(a)
  b <- endpoints.psp(a, "left")
  plot(b, add=TRUE)


Simulation envelopes of summary function

Description

Computes simulation envelopes of a summary function.

Usage

  envelope(Y, fun=Kest, nsim=99, nrank=1, ...,
  simulate=NULL, verbose=TRUE, clipdata=TRUE,
  start=NULL,control=list(nrep=1e5,expand=1.5),
  transform=NULL,global=FALSE,ginterval=NULL, saveall=FALSE)

Arguments

Y | Either a point pattern (object of class "ppp") or a fitted point process model (object of class "ppm").
fun | Function that computes the desired summary statistic for a point pattern.
nsim | Number of simulated point patterns to be generated when computing the envelopes.
nrank | Integer. Rank of the envelope value amongst the nsim simulated values. A rank of 1 means that the minimum and maximum simulated values will be used.
... | Extra arguments passed to fun.
simulate | Optional. An expression. If this is present, then the simulated point patterns will be generated by evaluating this expression nsim times.
verbose | Logical flag indicating whether to print progress reports during the simulations.
clipdata | Logical flag indicating whether the data point pattern should be clipped to the same window as the simulated patterns, before the summary function for the data is computed. This should usually be TRUE to ensure that the data and simulations are properly comparable.
start,control | Optional. These specify the arguments start and control of rmh, giving complete control over the simulation algorithm.
transform | Optional. A transformation to be applied to the function values, before the envelopes are computed. An expression object (see Details).
global | Logical flag indicating whether envelopes should be pointwise (global=FALSE) or simultaneous (global=TRUE).
ginterval | Optional. A vector of length 2 specifying the interval of r values for the simultaneous critical envelopes. Only relevant if global=TRUE.
saveall | Logical flag indicating whether to save all the simulated curves.

Details

Simulation envelopes can be used to assess the goodness-of-fit of a point process model to point pattern data. See the References.

This function first generates nsim random point patterns in one of the following ways.

  • If Y is a point pattern (an object of class "ppp") and simulate=NULL, then this routine generates nsim simulations of Complete Spatial Randomness (i.e. nsim simulated point patterns each being a realisation of the uniform Poisson point process) with the same intensity as the pattern Y. (If Y is a multitype point pattern, then the simulated patterns are also given independent random marks; the probability distribution of the random marks is determined by the relative frequencies of marks in Y.)
  • If Y is a fitted point process model (an object of class "ppm") and simulate=NULL, then this routine generates nsim simulated realisations of that model.
  • If simulate is supplied, then it must be an expression. It will be evaluated nsim times to yield nsim point patterns.

The summary statistic fun is applied to each of these simulated patterns. Typically fun is one of the functions Kest, Gest, Fest, Jest, pcf, Kcross, Kdot, Gcross, Gdot, Jcross, Jdot, Kmulti, Gmulti, Jmulti or Kinhom. It may also be a character string containing the name of one of these functions.

The statistic fun can also be a user-supplied function; if so, then it must have arguments X and r like those in the functions listed above, and it must return an object of class "fv".

Upper and lower critical envelopes are computed in one of the following ways:

pointwise:
by default, envelopes are calculated pointwise (i.e. for each value of the distance argument r), by sorting the nsim simulated values, and taking the m-th lowest and m-th highest values, where m = nrank. For example if nrank=1, the upper and lower envelopes are the pointwise maximum and minimum of the simulated values.

The pointwise envelopes are not “confidence bands” for the true value of the function! Rather, they specify the critical points for a Monte Carlo test (Ripley, 1981). The test is constructed by choosing a fixed value of r, and rejecting the null hypothesis if the observed function value lies outside the envelope at this value of r. This test has exact significance level alpha = 2 * nrank/(1 + nsim).

simultaneous:
if global=TRUE, then the envelopes are determined as follows. First we calculate the theoretical mean value of the summary statistic (if we are testing CSR, the theoretical value is supplied by fun; otherwise we compute the average of all the simulated values and take this as an estimate of the theoretical mean value). Then, for each simulation, we compare the simulated curve to the theoretical curve, and compute the maximum absolute difference between them (over the interval of r values specified by ginterval). This gives a deviation value d[i] for each of the nsim simulations. Finally we take the m-th largest of the deviation values, where m=nrank, and call this dcrit. Then the simultaneous envelopes are of the form lo = theo - dcrit and hi = theo + dcrit where theo is the theoretical mean value. Simultaneous critical envelopes have constant width 2 * dcrit.

The simultaneous critical envelopes allow us to perform a different Monte Carlo test (Ripley, 1981). The test rejects the null hypothesis if the graph of the observed function lies outside the envelope at any value of r. This test has exact significance level alpha = nrank/(1 + nsim).

The return value is an object of class "fv" containing the summary function for the data point pattern and the upper and lower simulation envelopes. It can be plotted using plot.fv.

Arguments can be passed to the function fun through .... This makes it possible to select the edge correction used to calculate the summary statistic. See the Examples. Selecting only a single edge correction will make the code run much faster.

If Y is a fitted point process model, and simulate=NULL, then the model is simulated by running the Metropolis-Hastings algorithm rmh. Complete control over this algorithm is provided by the arguments start and control which are passed to rmh.

For simultaneous critical envelopes (global=TRUE) the following options are also useful:

ginterval
determines the interval of r values over which the deviation between curves is calculated. It should be a numeric vector of length 2. There is a sensible default (namely, the recommended plotting interval for fun(X)).
transform
specifies a transformation of the summary function fun that will be carried out before the deviations are computed. It must be an expression object using the symbol . to represent the function value. For example, the conventional way to normalise the K function (Ripley, 1981) is to transform it to the L function L(r) = sqrt(K(r)/pi) and this is implemented by setting transform=expression(sqrt(./pi)). Such transforms are only useful if global=TRUE.

It is also possible to extract the summary functions for each of the individual simulated point patterns, by setting saveall=TRUE. Then the return value also has an attribute "savedata" containing all the summary functions for the individual simulated patterns. It is an "fv" object containing functions named sim1, sim2, ... representing the nsim summary functions.

Value

An object of class "fv", see fv.object, which can be plotted directly using plot.fv.
Essentially a data frame containing columns

r | the vector of values of the argument r at which the summary function fun has been estimated
obs | values of the summary function for the data point pattern
lo | lower envelope of simulations
hi | upper envelope of simulations

If saveall=TRUE, the return value also has an attribute "savedata" which contains the summary functions computed for each of the nsim simulated patterns.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.

Diggle, P.J. Statistical analysis of spatial point patterns. Arnold, 2003.

Ripley, B.D. (1981) Spatial statistics. John Wiley and Sons.

Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.

Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of geometrical statistics. John Wiley and Sons.

See Also

fv.object, plot.fv, Kest, Gest, Fest, Jest, pcf, ppp, ppm

Examples

 data(simdat)
 X <- simdat

 # Envelope of K function under CSR
 ## Not run:
 plot(envelope(X))

## End(Not run)

 # Translation edge correction (this is also FASTER):
 ## Not run:
 plot(envelope(X, correction="translate"))

## End(Not run)

 # Envelope of K function for simulations from model
 data(cells)
 fit <- ppm(cells, ~1, Strauss(0.05))
 ## Not run:
 plot(envelope(fit))

## End(Not run)

 # Envelope of G function under CSR
 ## Not run:
 plot(envelope(X, Gest))

## End(Not run)

 # Envelope of L function under CSR
 #  L(r) = sqrt(K(r)/pi)
 ## Not run:
  E <- envelope(X, Kest)
  plot(E, sqrt(./pi) ~ r)

## End(Not run)

 # Simultaneous critical envelope for L function
 ## Not run:
  plot(envelope(X, Kest, transform=expression(sqrt(./pi)), global=TRUE))

## End(Not run)

 # How to pass arguments needed to compute the summary functions:
 # We want envelopes for Jcross(X, "A", "B")
 # where "A" and "B" are types of points in the dataset 'demopat'

 data(demopat)
 ## Not run:
 plot(envelope(demopat, Jcross, i="A", j="B"))

## End(Not run)

 # Use of `simulate'
 ## Not run:
 plot(envelope(cells, Gest, simulate=expression(runifpoint(42))))
 plot(envelope(cells, Gest, simulate=expression(rMaternI(100,0.02))))

## End(Not run)

 # Envelope under random toroidal shifts
 data(amacrine)
 ## Not run:
 plot(envelope(amacrine, Kcross, i="on", j="off",
               simulate=expression(rshift(amacrine, radius=0.25))))

## End(Not run)

 # Envelope under random shifts with erosion
 ## Not run:
 plot(envelope(amacrine, Kcross, i="on", j="off",
              simulate=expression(rshift(amacrine, radius=0.1, edge="erode"))))

## End(Not run)

 # Envelope of INHOMOGENEOUS K-function with fitted trend
## Not run:
 trend <- density.ppp(X, 1.5)
 plot(envelope(X, Kinhom, lambda=trend,
         simulate=expression(rpoispp(trend))))

## End(Not run)


Erode a Window

Description

Perform morphological erosion of a window

Usage

 erode.owin(w, r, shrink.frame=TRUE, ...)

Arguments

w | A window (object of class "owin".
r | positive number: the radius of erosion.
shrink.frame | logical: if TRUE, erode the bounding rectangle as well.
... | extra arguments to as.mask controlling the pixel resolution

Details

The morphological erosion of a set W by a distance r > 0 is the subset consisting of all points x in W such that the distance from x to the boundary of W is greater than or equal to r. In other words it is the result of trimming a margin of width r off the set W.

This function computes the erosion of the window w. If w is not a rectangle, it must be approximated by a binary pixel image, and the arguments "..." are passed to as.mask to determine the pixel resolution. There is a sensible default.

If shrink.frame is false, the resulting window is given the same outer, bounding rectangle as the original window w. If shrink.frame is true, the original bounding rectangle is also eroded by the same distance r.

To simply compute the area of the eroded window, use eroded.areas.

Value

Another object of class "owin" representing the eroded window.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin, as.owin, eroded.areas

Examples

  w <- owin(c(0,1),c(0,1))
  v <- erode.owin(w, 0.1)
  # returns rectangle [0.1, 0.9] x [0.1,0.9]
  ## Not run:
  v <- erode.owin(w, 0.6)
  #fails - erosion is empty

## End(Not run)


Areas of Morphological Erosions

Description

Computes the areas of successive morphological erosions of a window.

Usage

 eroded.areas(w, r)

Arguments

w | A window.
r | Numeric vector of radii at which erosions will be performed.

Details

This function computes the areas of the erosions of the window w by each of the radii r[i].

The morphological erosion of a set W by a distance r > 0 is the subset consisting of all points x in W such that the distance from x to the boundary of W is greater than or equal to r. In other words it is the result of trimming a margin of width r off the set W.

The argument r should be a vector of positive numbers. The argument w should be a window (an object of class "owin", see owin.object for details) or can be given in any format acceptable to as.owin().

Unless w is a rectangle, the computation is performed using a pixel raster approximation.

To compute the eroded window itself, use erode.owin.

Value

Numeric vector, of the same length as r, giving the areas of the successive erosions.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin, as.owin, erode.owin

Examples

  w <- owin(c(0,1),c(0,1))
  a <- eroded.areas(w, seq(0.01,0.49,by=0.01))


Evaluate Expression Involving Functions

Description

Evaluates any expression involving one or more function value (fv) objects, and returns another object of the same kind.

Usage

  eval.fv(expr)

Arguments

expr An expression.

Details

This is a wrapper to make it easier to perform pointwise calculations with the summary functions used in spatial statistics.

An object of class "fv" is essentially a data frame containing several different statistical estimates of the same function. Such objects are returned by Kest and its relatives.

For example, suppose X is an object of class "fv" containing several different estimates of the Ripley's K function K(r), evaluated at a sequence of values of r. Then eval.fv(X+3) effectively adds 3 to each function estimate in X, and returns the resulting object.

Suppose X and Y are two objects of class "fv" which are compatible (in particular they have the same vector of r values). Then eval.im(X + Y) will add the corresponding function values in X and Y, and return the resulting function.

In general, expr can be any expression involving (a) the names of objects of class "fv", (b) scalar constants, and (c) functions which are vectorised. See the Examples.

First eval.fv determines which of the variable names in the expression expr refer to objects of class "fv". Each such name is replaced by a vector containing the function values. The expression is then evaluated. The result should be a vector; it is taken as the new vector of function values.

The expression expr must be vectorised. There must be at least one object of class "fv" in the expression. All such objects must be compatible.

Value

Another object of class "fv".

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

fv.object, Kest

Examples

  # manipulating the K function
  X <- rpoispp(42)
  Ks <- Kest(X)

  eval.fv(Ks + 3)
  Ls <- eval.fv(sqrt(Ks/pi))

  # manipulating two K functions
  Y <- rpoispp(20)
  Kr <- Kest(Y)

  Kdif <- eval.fv(Ks - Kr)
  Z <- eval.fv(sqrt(Ks/pi) - sqrt(Kr/pi))


Evaluate Expression Involving Pixel Images

Description

Evaluates any expression involving one or more pixel images, and returns a pixel image.

Usage

  eval.im(expr)

Arguments

expr An expression.

Details

This function is a wrapper to make it easier to perform pixel-by-pixel calculations in an image.

Pixel images in spatstat are represented by objects of class "im" (see im.object). These are essentially matrices of pixel values, with extra attributes recording the pixel dimensions, etc.

Suppose X is a pixel image. Then eval.im(X+3) will add 3 to the value of every pixel in X, and return the resulting pixel image.

Suppose X and Y are two pixel images with compatible dimensions: they have the same number of pixels, the same physical size of pixels, and the same bounding box. Then eval.im(X + Y) will add the corresponding pixel values in X and Y, and return the resulting pixel image.

In general, expr can be any expression in the R language involving (a) the names of pixel images, (b) scalar constants, and (c) functions which are vectorised. See the Examples.

First eval.im determines which of the variable names in the expression expr refer to pixel images. Each such name is replaced by a matrix containing the pixel values. The expression is then evaluated. The result should be a matrix; it is taken as the matrix of pixel values.

The expression expr must be vectorised. There must be at least one pixel image in the expression. All images must have compatible dimensions.

Value

An image object of class "im".

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

as.im, compatible.im, im.object

Examples

  # test images
  X <- as.im(function(x,y) { x^2 - y^2 }, unit.square())
  Y <- as.im(function(x,y) { 3 * x + y }, unit.square())

  eval.im(X + 3)
  eval.im(X - Y)
  eval.im(abs(X - Y))
  Z <- eval.im(sin(X * pi) + Y)


Weighted Empirical Cumulative Distribution Function

Description

Compute a weighted version of the empirical cumulative distribution function.

Usage

ewcdf(x, weights = rep(1/length(x), length(x)))

Arguments

x | Numeric vector of observations.
weights | Numeric vector of non-negative weights for x.

Details

This is a modification of the standard function ecdf allowing the observations x to have weights.

The weighted e.c.d.f. (empirical cumulative distribution function) Fn is defined so that, for any real number y, the value of Fn(y) is equal to the total weight of all entries of x that are less than or equal to y. That is Fn(y) = sum(weights[x <= y]).

Thus Fn is a step function which jumps at the values of x. The height of the jump at a point y is the total weight of all entries in x number of tied observations at that value. Missing values are ignored.

If weights is omitted, the default is equivalent to ecdf(x).

Value

A function, of class "ecdf", inheriting from "stepfun".

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ecdf

Examples

   x <- rnorm(100)
   w <- runif(100)
   plot(ewcdf(x,w))


Expand Window By Factor

Description

Expands the bounding box of a window by a given factor.

Usage

 expand.owin(W, f=1)

Arguments

W | A window.
f | Scalar factor for expansion of the area of the window.

Details

The argument w should be a window (an object of class "owin", see owin.object for details) or can be given in any format acceptable to as.owin().

The bounding box of the window W is expanded by a scale factor equal to the square root of f in both the x and y directions, so that the area increases by a factor f. The centre of this expanded rectangle is the same as the centre of the original bounding box. The expanded rectangle is returned.

This quirky little function exists mainly for reference, as it is the rule for calculating window expansion in our implementation of the Metropolis-Hastings algorithm rmh.default.

For general transformations of the scale, location and orientation of a window, see shift, affine and rotate.

Value

A rectangular window.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin, as.owin, shift, rotate, affine

Examples

  w <- square(1)
  expand.owin(w, 9)
  # returns the square [-1,2] x [-1,2]


Function Arrays for Spatial Patterns

Description

A class "fasp" to represent a ``matrix'' of functions, amenable to plotting as a matrix of plot panels.

Details

An object of this class is a convenient way of storing (and later plotting, editing, etc) a set of functions f[i,j](r) of a real argument r, defined for each possible pair (i,j) of indices 1 <= i,j <= n. We may think of this as a matrix or array of functions f[i,j].

Function arrays are particularly useful in the analysis of a multitype point pattern (a point pattern in which the points are identified as belonging to separate types). We may want to compute a summary function for the points of type i only, for each of the possible types i. This produces a 1 * m array of functions. Alternatively we may compute a summary function for each possible pair of types (i,j). This produces an m * m array of functions.

For multitype point patterns the command alltypes will compute arrays of summary functions for each possible type or for each possible pair of types. For univariate (single-type) point patterns the command allstats will compute an array of different summary functions F, G, J, K for the same dataset. Both alltypes and allstats return an object of class "fasp".

There are methods for plot, print and "[" in this class. The plot method displays the entire array of functions. The method [.fasp selects a sub-array using the natural indices i,j.

An object of class "fasp" is a list containing at least the following components:

fns
A list of data frames, each representing one of the functions.
which
A matrix representing the spatial arrangement of the functions. If which[i,j] = k then the function represented by fns[[k]] should be plotted in the panel at position (i,j). If which[i,j] = NA then nothing is plotted in that position.
titles
A list of character strings, providing suitable plotting titles for the functions.
default.formulae
A list of default formulae for plotting each of the functions.
title
A character string, giving a default title for the array when it is plotted.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

alltypes, allstats, plot.fasp, [.fasp

Examples

  # unmarked point pattern
  data(swedishpines)

  a <- allstats(swedishpines,dataname="Swedish Pines")
  a
  plot(a)
  plot(a[1,])

  # multitype point pattern
  data(amacrine)
  a <- alltypes(amacrine, "G")
  plot(a)

  # select the row corresponding to cells of type "on"
  b <- a["on", ]
  plot(b)


Estimate the empty space function F

Description

Estimates the empty space function F(r) from a point pattern in a window of arbitrary shape.

Usage

Fest(X, eps, r=NULL, breaks=NULL)

Arguments

X | The observed point pattern, from which an estimate of F(r) will be computed. An object of class ppp, or data in any format acceptable to as.ppp().
eps | Optional. A positive number. The resolution of the discrete approximation to Euclidean distance (see below). There is a sensible default.
r | Optional. Numeric vector. The values of the argument r at which F(r) should be evaluated. There is a sensible default. First-time users are strongly advised not to specify this argument. See below for important conditions on r.
breaks | An alternative to the argument r. Not normally invoked by the user. See the Details section.

Details

The empty space function (also called the ``spherical contact distribution'' or the ``point-to-nearest-event'' distribution) of a stationary point process X is the cumulative distribution function F of the distance from a fixed point in space to the nearest point of X.

An estimate of F derived from a spatial point pattern dataset can be used in exploratory data analysis and formal inference about the pattern (Cressie, 1991; Diggle, 1983; Ripley, 1988). In exploratory analyses, the estimate of F is a useful statistic summarising the sizes of gaps in the pattern. For inferential purposes, the estimate of F is usually compared to the true value of F for a completely random (Poisson) point process, which is

F(r) = 1 - exp( - lambda * pi * r^2)

where lambda is the intensity (expected number of points per unit area). Deviations between the empirical and theoretical F curves may suggest spatial clustering or spatial regularity.

This algorithm estimates the empty space function F from the point pattern X. It assumes that X can be treated as a realisation of a stationary (spatially homogeneous) random spatial point process in the plane, observed through a bounded window. The window (which is specified in X) may have arbitrary shape.

The argument X is interpreted as a point pattern object (of class "ppp", see ppp.object) and can be supplied in any of the formats recognised by as.ppp.

The algorithm uses two discrete approximations which are controlled by the parameter eps and by the spacing of values of r respectively. (See below for details.) First-time users are strongly advised not to specify these arguments.

The estimation of F is hampered by edge effects arising from the unobservability of points of the random pattern outside the window. An edge correction is needed to reduce bias (Baddeley, 1998; Ripley, 1988). The two edge corrections implemented here are the border method or "reduced sample" estimator, and the spatial Kaplan-Meier estimator (Baddeley and Gill, 1997).

Our implementation makes essential use of the distance transform algorithm of image processing (Borgefors, 1986). A fine grid of pixels is created in the observation window. The Euclidean distance between two pixels is approximated by the length of the shortest path joining them in the grid, where a path is a sequence of steps between adjacent pixels, and horizontal, vertical and diagonal steps have length 1, 1 and sqrt(2) respectively in pixel units. If the pixel grid is sufficiently fine then this is an accurate approximation.

The parameter eps is the pixel width of the rectangular raster used to compute the distance transform (see below). It must not be too large: the absolute error in distance values due to discretisation is bounded by eps.

If eps is not specified, the function checks whether the window X$window contains pixel raster information. If so, then eps is set equal to the pixel width of the raster; otherwise, eps defaults to 1/100 of the width of the observation window.

The argument r is the vector of values for the distance r at which F(r) should be evaluated. It is also used to determine the breakpoints (in the sense of hist for the computation of histograms of distances. The reduced-sample and Kaplan-Meier estimators are computed from histogram counts. In the case of the Kaplan-Meier estimator this introduces a discretisation error which is controlled by the fineness of the breakpoints.

First-time users would be strongly advised not to specify r. However, if it is specified, r must satisfy r[1] = 0, and max(r) must be larger than the radius of the largest disc contained in the window. Furthermore, the spacing of successive r values must be very fine (ideally not greater than eps/4).

The algorithm also returns an estimate of the hazard rate function, lambda(r), of F(r). The hazard rate is defined by

lambda(r) = - (d/dr) log(1 - F(r))

The hazard rate of F has been proposed as a useful exploratory statistic (Baddeley and Gill, 1994). The estimate of lambda(r) given here is a discrete approximation to the hazard rate of the Kaplan-Meier estimator of F. Note that F is absolutely continuous (for any stationary point process X), so the hazard function always exists (Baddeley and Gill, 1997).

The naive empirical distribution of distances from each location in the window to the nearest point of the data pattern, is a biased estimate of F. However this is also returned by the algorithm, as it is sometimes useful in other contexts. Care should be taken not to use the uncorrected empirical F as if it were an unbiased estimator of F.

Value

An object of class "fv", see fv.object, which can be plotted directly using plot.fv.
Essentially a data frame containing six columns:

r | the values of the argument r at which the function F(r) has been estimated
rs | the ``reduced sample'' or ``border correction'' estimator of F(r)
km | the spatial Kaplan-Meier estimator of F(r)
hazard | the hazard rate lambda(r) of F(r) by the spatial Kaplan-Meier method
raw | the uncorrected estimate of F(r), i.e. the empirical distribution of the distance from a random point in the window to the nearest point of the data pattern X
theo | the theoretical value of F(r) for a stationary Poisson process of the same estimated intensity.

Warnings

The reduced sample (border method) estimator of F is pointwise approximately unbiased, but need not be a valid distribution function; it may not be a nondecreasing function of r. Its range is always within [0,1].

The spatial Kaplan-Meier estimator of F is always nondecreasing but its maximum value may be less than 1.

The estimate of lambda(r) returned by the algorithm is an approximately unbiased estimate for the integral of lambda() over the corresponding histogram cell. It may exhibit oscillations due to discretisation effects. We recommend modest smoothing, such as kernel smoothing with kernel width equal to the width of a histogram cell.

Note

Sizeable amounts of memory may be needed during the calculation.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A.J. Spatial sampling and censoring. In O.E. Barndorff-Nielsen, W.S. Kendall and M.N.M. van Lieshout (eds) Stochastic Geometry: Likelihood and Computation. Chapman and Hall, 1998. Chapter 2, pages 37-78.

Baddeley, A.J. and Gill, R.D. The empty space hazard of a spatial pattern. Research Report 1994/3, Department of Mathematics, University of Western Australia, May 1994.

Baddeley, A.J. and Gill, R.D. Kaplan-Meier estimators of interpoint distance distributions for spatial point processes. Annals of Statistics 25 (1997) 263-292.

Borgefors, G. Distance transformations in digital images. Computer Vision, Graphics and Image Processing 34 (1986) 344-371.

Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.

Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.

Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.

Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd edition. Springer Verlag, 1995.

See Also

Gest, Jest, Kest, km.rs, reduced.sample, kaplan.meier

Examples

   data(cells)
   Fc <- Fest(cells, 0.01)

   # Tip: don't use F for the left hand side!
   # That's an abbreviation for FALSE

   plot(Fc)

   # P-P style plot
   plot(Fc, cbind(km, theo) ~ theo)

   # The empirical F is above the Poisson F
   # indicating an inhibited pattern

   ## Not run:
   plot(Fc, . ~ theo)
   plot(Fc, asin(sqrt(.)) ~ asin(sqrt(theo)))

## End(Not run)


Pine saplings in Finland.

Description

The data record the locations of 126 pine saplings in a Finnish forest, their heights and their diameters.

The main dataset finpines is a marked point pattern containing the locations of the saplings marked by their heights. Additional data in finpines.extra record the sapling diameters.

Sapling locations are given in metres (to six significant digits); heights are in metres (rounded to the nearest 0.1 metre, except in one case to the nearest 0.05 metres); diameters are in centimetres (rounded to the nearest centimetre).

The data were recorded by Professor Seppo Kellomaki, Faculty of Forestry, University of Joensuu, Finland, and subsequently massaged by Professor Antti Penttinen, Department of Statistics, University of Jyv"askyl"a, Finland.

Originally the point locations were observed in polar coordinates with rather poor angular precision. Hence the coordinates are imprecise for large radius because of rounding errors: indeed the alignments can be observed by eye.

The data were manipulated by Prof Penttinen by making small angular perturbations at random. After this transformation, the original data (in a circular plot) were clipped to a square window, for convenience.

Professor Penttinen emphasises that the data were intended only for initial experimentation. They have some strange features. For example, if the height is less than 1.3 metres then the diameter can be uncertain. Also there are some very close pairs of points.

These data have subsequently been analysed by Van Lieshout (2004).

Usage

data(finpines)

Format

finpines is an object of class "ppp" representing the point pattern of sapling locations marked by their heights. See ppp.object for details of the format.

finpines.extra is a list with one component diameter which is a numeric vector containing the diameters of the points.

Source

Prof Antti Penttinen

References

Van Lieshout, M.N.M. (2004) A J-function for marked point patterns. Research Report PNA-R0404, June 2004. Centrum voor Wiskunde en Informatica (CWI), Amsterdam, 2004.

Examples

    data(finpines)
    plot(unmark(finpines), main="Finnish pines: locations")
    plot(finpines, main="locations and heights")
    plot(finpines %mark% finpines.extra$diameter, main="diameters")


Fitted Conditional Intensity for Point Process Model

Description

Given a point process model fitted to a point pattern, compute the fitted conditional intensity of the model at the points of the pattern, or at the points of the quadrature scheme used to fit the model.

Usage

  ## S3 method for class 'ppm':
  fitted(object, ..., type="lambda", dataonly=FALSE,
check=TRUE, repair=TRUE)

Arguments

object | The fitted point process model (an object of class "ppm")
... | Ignored.
type | String (partially matched) indicating whether the fitted value is the conditional intensity ("lambda") or the trend ("trend").
dataonly | Logical. If TRUE, then values will only be computed at the points of the data point pattern. If FALSE, then values will be computed at all the points of the quadrature scheme used to fit the model, including the points of the data point pattern.
check | Logical value indicating whether to check the internal format of object. If there is any possibility that this object has been restored from a dump file, or has otherwise lost track of the environment where it was originally computed, set check=TRUE.
repair | Logical value indicating whether to repair the internal format of object, if it is found to be damaged.

Details

The argument object must be a fitted point process model (object of class "ppm"). Such objects are produced by the model-fitting algorithm ppm).

This function evaluates the conditional intensity lambdahat(u,x) or spatial trend bhat(u) of the fitted point process model for certain locations u, where x is the original point pattern dataset to which the model was fitted.

The locations u at which the fitted conditional intensity/trend is evaluated, are the points of the quadrature scheme used to fit the model in ppm. They include the data points (the points of the original point pattern dataset x) and other ``dummy'' points in the window of observation.

Use predict.ppm to compute the fitted conditional intensity at other locations or with other values of the explanatory variables.

Value

A vector containing the values of the fitted conditional intensity or (if type="trend") the fitted spatial trend.
Entries in this vector correspond to the quadrature points (data or dummy points) used to fit the model. The quadrature points can be extracted from object by union.quad(quad.ppm(object)).

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005). Residual analysis for spatial point processes (with discussion). Journal of the Royal Statistical Society, Series B 67, 617–666.

See Also

ppm.object, ppm, predict.ppm

Examples

    data(cells)
    str <- ppm(cells, ~x, Strauss(r=0.15), rbord=0.15)
    lambda <- fitted(str)

    # extract quadrature points in corresponding order
    quadpoints <- union.quad(quad.ppm(str))

    # plot conditional intensity values
    # as circles centred on the quadrature points
    quadmarked <- setmarks(quadpoints, lambda)
    plot(quadmarked)


Data Frames of Function Values

Description

A class "fv" to support the convenient plotting of several estimates of the same function.

Details

An object of this class is a convenient way of storing and plotting several different estimates of the same function.

It is a data frame with extra attributes indicating the recommended way of plotting the function, and other information.

There are methods for print and plot for this class.

Objects of class "fv" are returned by Fest, Gest,Jest, and Kest.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

Fest, Gest, Jest, Kest

Examples

    data(cells)
    K <- Kest(cells)

    class(K)

    K  # prints a sensible summary

    plot(K)


Beta Ganglion Cells in Cat Retina, Old Version

ganglia(spatstat) R Documentation

Beta Ganglion Cells in Cat Retina Old Version

Description

Point pattern of retinal ganglion cells identified as `on' or `off'. A marked point pattern.

Usage

data(ganglia)

Format

An object of class "ppp" representing the point pattern of cell locations. Entries include
x | Cartesian x-coordinate of cell
y | Cartesian y-coordinate of cell
marks | factor with levels off and on
 | indicating ``off'' and ``on'' cells

See ppp.object for details of the format.

Notes

Important: these data are INCORRECT. See below.

The data represent a pattern of beta-type ganglion cells in the retina of a cat recorded in Figure 6(a) of W"assle et al. (1981).

The pattern was first analysed by W"assle et al (1981) using nearest neighbour distances. The data used in their analysis are not available.

The present dataset ganglia was scanned from Figure 6(a) of W"assle et al (1981) in the early 1990's, but we have no further information. This dataset is the one analysed by Van Lieshout and Baddeley (1999) using multitype J functions, and by Stoyan (1995) using second order methods (pair correlation and mark correlation).

It has now been discovered that these data are incorrect. They are not faithful to the scale in Figure 6 of W"assle et al (1981), and they contain some scanning errors. Hence they should not be used to address the original scientific question. They have been retained only for comparison with other analyses in the statistical literature.

A new, corrected dataset, scanned from the original microscope image, has been provided under the name betacells. Use that dataset for any further study.

Warnings

These data are incorrect. Use the new corrected dataset betacells.

Source

W"assle et al (1981), data supplied by Marie-Colette van Lieshout and attributed to Peter Diggle

References

Stoyan, D. (1995) Personal communication.

Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

W"assle, H., Boycott, B. B. & Illing, R.-B. (1981). Morphology and mosaic of on- and off-beta cells in the cat retina and some functional considerations. Proc. Roy. Soc. London Ser. B 212, 177–195.


Multitype Nearest Neighbour Distance Function (i-to-j)

Description

For a multitype point pattern, estimate the distribution of the distance from a point of type i to the nearest point of type j.

Usage

Gcross(X, i=1, j=2, r=NULL, breaks=NULL, ...)

Arguments

X | The observed point pattern, from which an estimate of the cross type distance distribution function Gij(r) will be computed. It must be a multitype point pattern (a marked point pattern whose marks are a factor). See under Details.
i | Number or character string identifying the type (mark value) of the points in X from which distances are measured.
j | Number or character string identifying the type (mark value) of the points in X to which distances are measured.
r | Optional. Numeric vector. The values of the argument r at which the distribution function Gij(r) should be evaluated. There is a sensible default. First-time users are strongly advised not to specify this argument. See below for important conditions on r.
breaks | An alternative to the argument r. Not normally invoked by the user. See the Details section.
... | Ignored.

Details

This function Gcross and its companions Gdot and Gmulti are generalisations of the function Gest to multitype point patterns.

A multitype point pattern is a spatial pattern of points classified into a finite number of possible ``colours'' or ``types''. In the spatstat package, a multitype pattern is represented as a single point pattern object in which the points carry marks, and the mark value attached to each point determines the type of that point.

The argument X must be a point pattern (object of class "ppp") or any data that are acceptable to as.ppp. It must be a marked point pattern, and the mark vector X$marks must be a factor. The arguments i and j will be interpreted as levels of the factor X$marks. (Warning: this means that an integer value i=3 will be interpreted as the 3rd smallest level, not the number 3).

The ``cross-type'' (type i to type j) nearest neighbour distance distribution function of a multitype point process is the cumulative distribution function Gij(r) of the distance from a typical random point of the process with type i the nearest point of type j.

An estimate of Gij(r) is a useful summary statistic in exploratory data analysis of a multitype point pattern. If the process of type i points were independent of the process of type j points, then Gij(r) would equal Fj(r), the empty space function of the type j points. For a multitype Poisson point process where the type i points have intensity lambda[i], we have

Gij(r) = 1 - exp( - lambda[j] * pi * r^2)

Deviations between the empirical and theoretical Gij curves may suggest dependence between the points of types i and j.

This algorithm estimates the distribution function Gij(r) from the point pattern X. It assumes that X can be treated as a realisation of a stationary (spatially homogeneous) random spatial point process in the plane, observed through a bounded window. The window (which is specified in X as X$window) may have arbitrary shape. Biases due to edge effects are treated in the same manner as in Gest.

The argument r is the vector of values for the distance r at which Gij(r) should be evaluated. It is also used to determine the breakpoints (in the sense of hist) for the computation of histograms of distances. The reduced-sample and Kaplan-Meier estimators are computed from histogram counts. In the case of the Kaplan-Meier estimator this introduces a discretisation error which is controlled by the fineness of the breakpoints.

First-time users would be strongly advised not to specify r. However, if it is specified, r must satisfy r[1] = 0, and max(r) must be larger than the radius of the largest disc contained in the window. Furthermore, the successive entries of r must be finely spaced.

The algorithm also returns an estimate of the hazard rate function, lambda(r), of Gij(r). This estimate should be used with caution as Gij(r) is not necessarily differentiable.

The naive empirical distribution of distances from each point of the pattern X to the nearest other point of the pattern, is a biased estimate of Gij. However this is also returned by the algorithm, as it is sometimes useful in other contexts. Care should be taken not to use the uncorrected empirical Gij as if it were an unbiased estimator of Gij.

Value

An object of class "fv" (see fv.object).
Essentially a data frame containing six numeric columns

r | the values of the argument r at which the function Gij(r) has been estimated
rs | the ``reduced sample'' or ``border correction'' estimator of Gij(r)
km | the spatial Kaplan-Meier estimator of Gij(r)
hazard | the hazard rate lambda(r) of Gij(r) by the spatial Kaplan-Meier method
raw | the uncorrected estimate of Gij(r), i.e. the empirical distribution of the distances from each point of type i to the nearest point of type j
theo | the theoretical value of Gij(r) for a marked Poisson process with the same estimated intensity (see below).

Warnings

The arguments i and j are interpreted as levels of the factor X$marks. Beware of the usual trap with factors: numerical values are not interpreted in the same way as character values. See the first example.

The function Gij does not necessarily have a density.

The reduced sample estimator of Gij is pointwise approximately unbiased, but need not be a valid distribution function; it may not be a nondecreasing function of r. Its range is always within [0,1].

The spatial Kaplan-Meier estimator of Gij is always nondecreasing but its maximum value may be less than 1.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.

Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.

Diggle, P. J. (1986). Displaced amacrine cells in the retina of a rabbit : analysis of a bivariate spatial point pattern. J. Neurosci. Meth. 18, 115–125.

Harkness, R.D and Isham, V. (1983) A bivariate spatial point pattern of ants' nests. Applied Statistics 32, 293–303

Lotwick, H. W. and Silverman, B. W. (1982). Methods for analysing spatial processes of several types of points. J. Royal Statist. Soc. Ser. B 44, 406–413.

Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.

Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd edition. Springer Verlag, 1995.

Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

See Also

Gdot, Gest, Gmulti

Examples

    data(betacells)
     # cat retina data
    G01 <- Gcross(betacells, "off", "on")
    plot(G01)

    # empty space function of `on' points
    ## Not run:
       F1 <- Fest(betacells[betacells == "on"], r = G01$r, eps=10.0)
       lines(F1$r, F1$km, lty=3)

## End(Not run)

    # synthetic example
    pp <- runifpoispp(50)
    pp <- pp %mark% factor(sample(0:1, pp$n, replace=TRUE))
    G <- Gcross(pp, "0", "1")   # note: "0" not 0


Multitype Nearest Neighbour Distance Function (i-to-any)

Description

For a multitype point pattern, estimate the distribution of the distance from a point of type i to the nearest other point of any type.

Usage

Gdot(X, i=1, r=NULL, breaks=NULL, ...)

Arguments

X | The observed point pattern, from which an estimate of the distance distribution function Gi.(r) will be computed. It must be a multitype point pattern (a marked point pattern whose marks are a factor). See under Details.
i | Number or character string identifying the type (mark value) of the points in X from which distances are measured.
r | Optional. Numeric vector. The values of the argument r at which the distribution function Gi.(r) should be evaluated. There is a sensible default. First-time users are strongly advised not to specify this argument. See below for important conditions on r.
breaks | An alternative to the argument r. Not normally invoked by the user. See the Details section.
... | Ignored.

Details

This function Gdot and its companions Gcross and Gmulti are generalisations of the function Gest to multitype point patterns.

A multitype point pattern is a spatial pattern of points classified into a finite number of possible ``colours'' or ``types''. In the spatstat package, a multitype pattern is represented as a single point pattern object in which the points carry marks, and the mark value attached to each point determines the type of that point.

The argument X must be a point pattern (object of class "ppp") or any data that are acceptable to as.ppp. It must be a marked point pattern, and the mark vector X$marks must be a factor. The argument will be interpreted as a level of the factor X$marks. (Warning: this means that an integer value i=3 will be interpreted as the 3rd smallest level, not the number 3).

The ``dot-type'' (type i to any type) nearest neighbour distance distribution function of a multitype point process is the cumulative distribution function Gi.(r) of the distance from a typical random point of the process with type i the nearest other point of the process, regardless of type.

An estimate of Gi.(r) is a useful summary statistic in exploratory data analysis of a multitype point pattern. If the type i points were independent of all other points, then Gi.(r) would equal Gii(r), the nearest neighbour distance distribution function of the type i points alone. For a multitype Poisson point process with total intensity lambda, we have

Gi.(r) = 1 - exp( - lambda * pi * r^2)

Deviations between the empirical and theoretical Gi. curves may suggest dependence of the type i points on the other points.

This algorithm estimates the distribution function Gi.(r) from the point pattern X. It assumes that X can be treated as a realisation of a stationary (spatially homogeneous) random spatial point process in the plane, observed through a bounded window. The window (which is specified in X as X$window) may have arbitrary shape. Biases due to edge effects are treated in the same manner as in Gest.

The argument r is the vector of values for the distance r at which Gi.(r) should be evaluated. It is also used to determine the breakpoints (in the sense of hist) for the computation of histograms of distances. The reduced-sample and Kaplan-Meier estimators are computed from histogram counts. In the case of the Kaplan-Meier estimator this introduces a discretisation error which is controlled by the fineness of the breakpoints.

First-time users would be strongly advised not to specify r. However, if it is specified, r must satisfy r[1] = 0, and max(r) must be larger than the radius of the largest disc contained in the window. Furthermore, the successive entries of r must be finely spaced.

The algorithm also returns an estimate of the hazard rate function, lambda(r), of Gi.(r). This estimate should be used with caution as Gi.(r) is not necessarily differentiable.

The naive empirical distribution of distances from each point of the pattern X to the nearest other point of the pattern, is a biased estimate of Gi.. However this is also returned by the algorithm, as it is sometimes useful in other contexts. Care should be taken not to use the uncorrected empirical Gi. as if it were an unbiased estimator of Gi..

Value

An object of class "fv" (see fv.object).
Essentially a data frame containing six numeric columns

r | the values of the argument r at which the function Gi.(r) has been estimated
rs | the ``reduced sample'' or ``border correction'' estimator of Gi.(r)
km | the spatial Kaplan-Meier estimator of Gi.(r)
hazard | the hazard rate lambda(r) of Gi.(r) by the spatial Kaplan-Meier method
raw | the uncorrected estimate of Gi.(r), i.e. the empirical distribution of the distances from each point of type i to the nearest other point of any type.
theo | the theoretical value of Gi.(r) for a marked Poisson process with the same estimated intensity (see below).

Warnings

The argument i is interpreted as a level of the factor X$marks. Beware of the usual trap with factors: numerical values are not interpreted in the same way as character values. See the first example.

The function Gi. does not necessarily have a density.

The reduced sample estimator of Gi. is pointwise approximately unbiased, but need not be a valid distribution function; it may not be a nondecreasing function of r. Its range is always within [0,1].

The spatial Kaplan-Meier estimator of Gi. is always nondecreasing but its maximum value may be less than 1.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.

Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.

Diggle, P. J. (1986). Displaced amacrine cells in the retina of a rabbit : analysis of a bivariate spatial point pattern. J. Neurosci. Meth. 18, 115–125.

Harkness, R.D and Isham, V. (1983) A bivariate spatial point pattern of ants' nests. Applied Statistics 32, 293–303

Lotwick, H. W. and Silverman, B. W. (1982). Methods for analysing spatial processes of several types of points. J. Royal Statist. Soc. Ser. B 44, 406–413.

Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.

Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd edition. Springer Verlag, 1995.

Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

See Also

Gcross, Gest, Gmulti

Examples

    data(betacells)
     # cat retina data
    G0. <- Gdot(betacells, "off")
    plot(G0.)

    # synthetic example
    pp <- runifpoispp(50)
    pp <- pp %mark% factor(sample(0:1, pp$n, replace=TRUE))
    G <- Gdot(pp, "0") # note: "0" not 0


Nearest Neighbour Distance Function G

Description

Estimates the nearest neighbour distance distribution function G(r) from a point pattern in a window of arbitrary shape.

Usage

Gest(X, r=NULL, breaks=NULL, ...)

Arguments

X | The observed point pattern, from which an estimate of G(r) will be computed. An object of class ppp, or data in any format acceptable to as.ppp().
r | Optional. Numeric vector. The values of the argument r at which G(r) should be evaluated. There is a sensible default. First-time users are strongly advised not to specify this argument. See below for important conditions on r.
breaks | An alternative to the argument r. Not normally invoked by the user. See the Details section.
... | Ignored.

Details

The nearest neighbour distance distribution function (also called the ``event-to-event'' or ``inter-event'' distribution) of a point process X is the cumulative distribution function G of the distance from a typical random point of X to the nearest other point of X.

An estimate of G derived from a spatial point pattern dataset can be used in exploratory data analysis and formal inference about the pattern (Cressie, 1991; Diggle, 1983; Ripley, 1988). In exploratory analyses, the estimate of G is a useful statistic summarising one aspect of the ``clustering'' of points. For inferential purposes, the estimate of G is usually compared to the true value of G for a completely random (Poisson) point process, which is

G(r) = 1 - exp( - lambda * pi * r^2)

where lambda is the intensity (expected number of points per unit area). Deviations between the empirical and theoretical G curves may suggest spatial clustering or spatial regularity.

This algorithm estimates the nearest neighbour distance distribution function G from the point pattern X. It assumes that X can be treated as a realisation of a stationary (spatially homogeneous) random spatial point process in the plane, observed through a bounded window. The window (which is specified in X as X$window) may have arbitrary shape.

The argument X is interpreted as a point pattern object (of class "ppp", see ppp.object) and can be supplied in any of the formats recognised by as.ppp().

The estimation of G is hampered by edge effects arising from the unobservability of points of the random pattern outside the window. An edge correction is needed to reduce bias (Baddeley, 1998; Ripley, 1988). The two edge corrections implemented here are the border method or ``reduced sample'' estimator, and the spatial Kaplan-Meier estimator (Baddeley and Gill, 1997).

The argument r is the vector of values for the distance r at which G(r) should be evaluated. It is also used to determine the breakpoints (in the sense of hist) for the computation of histograms of distances. The reduced-sample and Kaplan-Meier estimators are computed from histogram counts. In the case of the Kaplan-Meier estimator this introduces a discretisation error which is controlled by the fineness of the breakpoints.

First-time users would be strongly advised not to specify r. However, if it is specified, r must satisfy r[1] = 0, and max(r) must be larger than the radius of the largest disc contained in the window. Furthermore, the successive entries of r must be finely spaced.

The algorithm also returns an estimate of the hazard rate function, lambda(r), of G(r). The hazard rate is defined as the derivative

lambda(r) = - (d/dr) log(1 - G(r))

This estimate should be used with caution as G is not necessarily differentiable.

The naive empirical distribution of distances from each point of the pattern X to the nearest other point of the pattern, is a biased estimate of G. However this is also returned by the algorithm, as it is sometimes useful in other contexts. Care should be taken not to use the uncorrected empirical G as if it were an unbiased estimator of G.

To simply compute the nearest neighbour distance for each point in the pattern, use nndist. To determine which point is the nearest neighbour of a given point, use nnwhich.

Value

An object of class "fv", see fv.object, which can be plotted directly using plot.fv.
Essentially a data frame containing six columns:

r | the values of the argument r at which the function G(r) has been estimated
rs | the ``reduced sample'' or ``border correction'' estimator of G(r)
km | the spatial Kaplan-Meier estimator of G(r)
hazard | the hazard rate lambda(r) of G(r) by the spatial Kaplan-Meier method
raw | the uncorrected estimate of G(r), i.e. the empirical distribution of the distances from each point in the pattern X to the nearest other point of the pattern
theo | the theoretical value of G(r) for a stationary Poisson process of the same estimated intensity.

Warnings

The function G does not necessarily have a density. Any valid c.d.f. may appear as the nearest neighbour distance distribution function of a stationary point process.

The reduced sample estimator of G is pointwise approximately unbiased, but need not be a valid distribution function; it may not be a nondecreasing function of r. Its range is always within [0,1].

The spatial Kaplan-Meier estimator of G is always nondecreasing but its maximum value may be less than 1.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A.J. Spatial sampling and censoring. In O.E. Barndorff-Nielsen, W.S. Kendall and M.N.M. van Lieshout (eds) Stochastic Geometry: Likelihood and Computation. Chapman and Hall, 1998. Chapter 2, pages 37-78.

Baddeley, A.J. and Gill, R.D. Kaplan-Meier estimators of interpoint distance distributions for spatial point processes. Annals of Statistics 25 (1997) 263-292.

Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.

Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.

Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.

Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd edition. Springer Verlag, 1995.

See Also

nndist, nnwhich, Fest, Jest, Kest, km.rs, reduced.sample, kaplan.meier

Examples

  data(cells)
  G <- Gest(cells)
  plot(G)

  # P-P style plot
  plot(G, cbind(km,theo) ~ theo)

  # the empirical G is below the Poisson G,
  # indicating an inhibited pattern

  ## Not run:
     plot(G, . ~ r)
     plot(G, . ~ theo)
     plot(G, asin(sqrt(.)) ~ asin(sqrt(theo)))

## End(Not run)


Geyer's Saturation Point Process Model

Description

Creates an instance of Geyer's ``saturation point process'' model which can then be fitted to point pattern data.

Usage

  Geyer(r,sat)

Arguments

r | Interaction radius. A positive real number.
sat | Saturation threshold. A positive real number.

Details

Geyer (1999) introduced the ``saturation process'', a modification of the Strauss process (see Strauss) in which the total contribution to the potential from each point (from its pairwise interaction with all other points) is trimmed to a maximum value s. This model is implemented in the function Geyer().

The saturation point process with interaction radius r, saturation threshold s, and parameters beta and gamma, is the point process in which each point x[i] in the pattern X contributes a factor

beta gamma^min(s, t(x[i],X))

to the probability density of the point pattern, where t(x[i],X) denotes the number of ``close neighbours'' of x[i] in the pattern X. A close neighbour of x[i] is a point x[j] with j != i such that the distance between x[i] and x[j] is less than or equal to r.

If the saturation threshold s is set to infinity, this model reduces to the Strauss process (see Strauss) with interaction parameter gamma^2. If s = 0, the model reduces to the Poisson point process. If s is a finite positive number, then the interaction parameter gamma may take any positive value (unlike the case of the Strauss process), with values gamma < 1 describing an ``ordered'' or ``inhibitive'' pattern, and values gamma > 1 describing a ``clustered or ``attractive'' pattern.

The nonstationary saturation process is similar except that the value beta is replaced by a function beta(x[i]) of location.

The function ppm(), which fits point process models to point pattern data, requires an argument of class "interact" describing the interpoint interaction structure of the model to be fitted. The appropriate description of the saturation process interaction is yielded by Geyer(r, sat) where the arguments r and sat specify the Strauss interaction radius r and the saturation threshold s, respectively. See the examples below.

Note the only arguments are the interaction radius r and the saturation threshold sat. When r and sat are fixed, the model becomes an exponential family. The canonical parameters log(beta) and log(gamma) are estimated by ppm(), not fixed in Geyer().

Value

An object of class "interact" describing the interpoint interaction structure of Geyer's ``saturation point process'' with interaction radius r and saturation threshold sat.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Geyer, C.J. (1999) Likelihood Inference for Spatial Point Processes. Chapter 3 in O.E. Barndorff-Nielsen, W.S. Kendall and M.N.M. Van Lieshout (eds) Stochastic Geometry: Likelihood and Computation, Chapman and Hall / CRC, Monographs on Statistics and Applied Probability, number 80. Pages 79–140.

See Also

ppm, pairwise.family, ppm.object, Strauss

Examples

   data(cells)
   ppm(cells, ~1, Geyer(r=0.07, sat=2), rbord=0.07)
   # fit the stationary saturation process to `cells'


Marked Nearest Neighbour Distance Function

Description

For a marked point pattern, estimate the distribution of the distance from a typical point in subset I to the nearest point of subset J.

Usage

Gmulti(X, I, J, r=NULL, breaks=NULL, ..., disjoint=NULL)

Arguments

X | The observed point pattern, from which an estimate of the multitype distance distribution function GIJ(r) will be computed. It must be a marked point pattern. See under Details.
I | Subset of points of X from which distances are measured.
J | Subset of points in X to which distances are measured.
r | Optional. Numeric vector. The values of the argument r at which the distribution function GIJ(r) should be evaluated. There is a sensible default. First-time users are strongly advised not to specify this argument. See below for important conditions on r.
breaks | An alternative to the argument r. Not normally invoked by the user. See the Details section.
... | Ignored.
disjoint | Optional flag indicating whether the subsets I and J are disjoint. If missing, this value will be computed by inspecting the vectors I and J

.

Details

The function Gmulti generalises Gest (for unmarked point patterns) and Gdot and Gcross (for multitype point patterns) to arbitrary marked point patterns.

Suppose X[I], X[J] are subsets, possibly overlapping, of a marked point process. This function computes an estimate of the cumulative distribution function GIJ(r) of the distance from a typical point of X[I] to the nearest distinct point of X[J].

The argument X must be a point pattern (object of class "ppp") or any data that are acceptable to as.ppp.

The arguments I and J specify two subsets of the point pattern. They may be logical vectors of length equal to X$n, or integer vectors with entries in the range 1 to X$n, etc.

This algorithm estimates the distribution function GIJ(r) from the point pattern X. It assumes that X can be treated as a realisation of a stationary (spatially homogeneous) random spatial point process in the plane, observed through a bounded window. The window (which is specified in X as X$window) may have arbitrary shape. Biases due to edge effects are treated in the same manner as in Gest.

The argument r is the vector of values for the distance r at which GIJ(r) should be evaluated. It is also used to determine the breakpoints (in the sense of hist) for the computation of histograms of distances. The reduced-sample and Kaplan-Meier estimators are computed from histogram counts. In the case of the Kaplan-Meier estimator this introduces a discretisation error which is controlled by the fineness of the breakpoints.

First-time users would be strongly advised not to specify r. However, if it is specified, r must satisfy r[1] = 0, and max(r) must be larger than the radius of the largest disc contained in the window. Furthermore, the successive entries of r must be finely spaced.

The algorithm also returns an estimate of the hazard rate function, lambda(r), of GIJ(r). This estimate should be used with caution as GIJ(r) is not necessarily differentiable.

The naive empirical distribution of distances from each point of the pattern X to the nearest other point of the pattern, is a biased estimate of GIJ. However this is also returned by the algorithm, as it is sometimes useful in other contexts. Care should be taken not to use the uncorrected empirical GIJ as if it were an unbiased estimator of GIJ.

Value

An object of class "fv" (see fv.object).
Essentially a data frame containing six numeric columns

r | the values of the argument r at which the function GIJ(r) has been estimated
rs | the ``reduced sample'' or ``border correction'' estimator of GIJ(r)
km | the spatial Kaplan-Meier estimator of GIJ(r)
hazard | the hazard rate lambda(r) of GIJ(r) by the spatial Kaplan-Meier method
raw | the uncorrected estimate of GIJ(r), i.e. the empirical distribution of the distances from each point of type i to the nearest point of type j
theo | the theoretical value of GIJ(r) for a marked Poisson process with the same estimated intensity

Warnings

The function GIJ does not necessarily have a density.

The reduced sample estimator of GIJ is pointwise approximately unbiased, but need not be a valid distribution function; it may not be a nondecreasing function of r. Its range is always within [0,1].

The spatial Kaplan-Meier estimator of GIJ is always nondecreasing but its maximum value may be less than 1.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.

Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.

Diggle, P. J. (1986). Displaced amacrine cells in the retina of a rabbit : analysis of a bivariate spatial point pattern. J. Neurosci. Meth. 18, 115–125.

Harkness, R.D and Isham, V. (1983) A bivariate spatial point pattern of ants' nests. Applied Statistics 32, 293–303

Lotwick, H. W. and Silverman, B. W. (1982). Methods for analysing spatial processes of several types of points. J. Royal Statist. Soc. Ser. B 44, 406–413.

Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.

Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd edition. Springer Verlag, 1995.

Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

See Also

Gcross, Gdot, Gest

Examples

    data(longleaf)
     # Longleaf Pine data: marks represent diameter

    Gm <- Gmulti(longleaf, longleaf$marks <= 15, longleaf$marks >= 25)
    plot(Gm)


Rectangular grid of points

Description

Generates a rectangular grid of points in a window

Usage

 gridcentres(window, nx, ny)

Arguments

window | A window. An object of class owin, or data in any format acceptable to as.owin().
nx | Number of points in each row of the rectangular grid.
ny | Number of points in each column of the rectangular grid.

Details

This function creates a rectangular grid of points in the window.

The bounding rectangle of the window is divided into a regular nx * ny grid of rectangular tiles. The function returns the x,y coordinates of the centres of these tiles.

Note that some of these grid points may lie outside the window, if window is not of type "rectangle". The function inside.owin can be used to select those grid points which do lie inside the window. See the examples.

This function is useful in creating dummy points for quadrature schemes (see quadscheme) and for other miscellaneous purposes.

Value

A list with two components x and y, which are numeric vectors giving the coordinates of the points of the rectangular grid.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

quad.object, quadscheme, inside.owin, stratrand

Examples

  w <- unit.square()
  xy <- gridcentres(w, 10,15)
  ## Not run:
  plot(w)
  points(xy)

## End(Not run)

  bdry <- list(x=c(0.1,0.3,0.7,0.4,0.2),
               y=c(0.1,0.1,0.5,0.7,0.3))
  w <- owin(c(0,1), c(0,1), poly=bdry)
  xy <- gridcentres(w, 30, 30)
  ok <- inside.owin(xy$x, xy$y, w)
  ## Not run:
  plot(w)
  points(xy$x[ok], xy$y[ok])

## End(Not run)


Compute Quadrature Weights Based on Grid Counts

Description

Computes quadrature weights for a given set of points, using the ``counting weights'' for a grid of rectangular tiles.

Usage

 gridweights(X, ntile, ..., window=NULL, verbose=FALSE, npix=NULL, areas=NULL)

Arguments

X | Data defining a point pattern.
ntile | Number of tiles in each row and column of the rectangular grid. An integer vector of length 1 or 2.
... | Ignored.
window | Default window for the point pattern
verbose | Logical flag. If TRUE, information will be printed about the computation of the grid weights.
npix | Dimensions of pixel grid to use when computing a digital approximation to the tile areas.
areas | Vector of areas of the tiles, if they are already known.

Details

This function computes a set of quadrature weights for a given pattern of points (typically comprising both ``data'' and `dummy'' points). See quad.object for an explanation of quadrature weights and quadrature schemes.

The weights are computed by the ``counting weights'' rule based on a regular grid of rectangular tiles. First X and (optionally) window are converted into a point pattern object. Then the bounding rectangle of the window of the point pattern is divided into a regular ntile[1] * ntile[2] grid of rectangular tiles. The weight attached to a point of X is the area of the tile in which it lies, divided by the number of points of X lying in that tile.

For non-rectangular windows the tile areas are currently calculated by approximating the window as a binary mask. The accuracy of this approximation is controlled by npix, which becomes the argument dimyx of as.mask.

Value

Vector of nonnegative weights for each point in X.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

quad.object, dirichlet.weights

Examples

  Q <- quadscheme(runifpoispp(10))
  X <- as.ppp(Q) # data and dummy points together
  w <- gridweights(X, 10)
  w <- gridweights(X, c(10, 10))


Aherne's hamster tumour data

Description

Point pattern of cell nuclei in hamster kidney, each nucleus classified as either `dividing' or `pyknotic'. A multitype point pattern.

Usage

data(hamster)

Format

An object of class "ppp" representing the point pattern of cell locations. Entries include
x | Cartesian x-coordinate of cell
y | Cartesian y-coordinate of cell
marks | factor with levels "dividing" and "pyknotic".

See ppp.object for details of the format.

Notes

These data were presented and analysed by Diggle (1983, section 7.3).

The data give the positions of the centres of the nuclei of certain cells in a histological section of tissue from a laboratory-induced metastasising lymphoma in the kidney of a hamster.

The nuclei are classified as either "pyknotic" (corresponding to dying cells) or "dividing" (corresponding to cells arrested in metaphase, i.e. in the act of dividing). The background void is occupied by unrecorded, interphase cells in relatively large numbers.

The sampling window is a square, originally about 0.25 mm square in real units, which has been rescaled to the unit square.

Source

Dr W. A. Aherne, Department of Pathology, University of Newcastle-upon-Tyne, UK. Data supplied by Prof. Peter Diggle

References

Diggle, P.J. (1983) Statistical analysis of spatial point patterns. Academic Press.


Basis for Harmonic Functions

Description

Evaluates a basis for the harmonic polynomials in x and y of degree less than or equal to n.

Usage

   harmonic(x, y, n)

Arguments

x | Vector of x coordinates
y | Vector of y coordinates
n | Maximum degree of polynomial

Details

This function computes a basis for the harmonic polynomials in two variables x and y up to a given degree n and evaluates them at given x,y locations. It can be used in model formulas (for example in the model-fitting functions lm,glm,gam and ppm) to specify a linear predictor which is a harmonic function.

A function f(x,y) is harmonic if

(d/dx)^2 f + (d/dy)^2 f = 0.

The harmonic polynomials of degree less than or equal to n have a basis consisting of 2 n functions.

This function was implemented on a suggestion of P. McCullagh for fitting nonstationary spatial trend to point process models.

Value

A data frame with 2 * n columns giving the values of the basis functions at the coordinates. Each column is labelled by an algebraic expression for the corresponding basis function.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppm

Examples

   data(longleaf)
   X <- unmark(longleaf)
   # inhomogeneous point pattern

   # fit Poisson point process with log-cubic intensity
   fit.3 <- ppm(X, ~ polynom(x,y,3), Poisson())

   # fit Poisson process with log-cubic-harmonic intensity
   fit.h <- ppm(X, ~ harmonic(x,y,3), Poisson())

   # Likelihood ratio test
   lrts <- 2 * (fit.3$maxlogpl - fit.h$maxlogpl)
   x <- X$x
   y <- X$y
   df <- ncol(polynom(x,y,3)) - ncol(harmonic(x,y,3))
   pval <- 1 - pchisq(lrts, df=df)


Histogram of Pixel Values in an Image

Description

Computes and displays a histogram of the pixel values in a pixel image. The hist method for class "im".

Usage

  ## S3 method for class 'im':
  hist(x, ..., probability=FALSE)

Arguments

x | A pixel image (object of class "im").
... | Arguments passed to hist.default or barplot.
probability | Logical. If TRUE, the histogram will be normalised to give probabilities or probability densities.

Details

This function computes and (by default) displays a histogram of the pixel values in the image x.

An object of class "im" describes a pixel image. See im.object) for details of this class.

The function hist.im is a method for the generic function hist for the class "im".

Any arguments in ... are passed to hist.default (for numeric valued images) or barplot (for factor or logical images). For example, such arguments control the axes, and may be used to suppress the plotting.

Value

A single number.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

hist, hist.default, barplot, im.object, summary.im.

Examples

  X <- as.im(function(x,y) {x^2}, unit.square())
  hist(X)
  hist(cut(X,3))


Humberside Data on Childhood Leukaemia and Lymphoma

Description

Spatial locations of cases of childhood leukaemia and lymphoma, and randomly-selected controls, in North Humberside. A marked point pattern.

Usage

data(humberside)

Format

The dataset humberside is an object of class "ppp" representing a marked point pattern. Entries include
x | Cartesian x-coordinate of home address
y | Cartesian y-coordinate of home address
marks | factor with levels case and control
 | indicating whether this is a disease case
 | or a control.

See ppp.object for details of the format.

The dataset humberside.convex is an object of the same format, representing the same point pattern data, but contained in a larger, 5-sided convex polygon.

Notes

Cuzick and Edwards (1990) first presented and analysed these data.

The data record 62 cases of childhood leukaemia and lymphoma diagnosed in the North Humberside region of England between 1974 and 1986, together with 141 controls selected at random from the birth register for the same period.

The data are represented as a marked point pattern, with the points giving the spatial location of each individual's home address (actually, the centroid for the postal code) and the marks identifying cases and controls.

Coordinates are in multiples of 100 metres, and the resolution is 100 metres.

Two versions of the dataset are supplied, both containing the same point coordinates, but using different windows. The dataset humberside has a polygonal window with 102 edges which closely approximates the Humberside region, while humberside.convex has a convex 5-sided polygonal window originally used by Diggle and Chetwynd (1991) and shown in Figure 1 of that paper.

Source

Dr Ray Cartwright and Dr Freda Alexander. Published and analysed in Cuzick and Edwards (1990), see Table 1. Pentagonal boundary from Diggle and Chetwynd (1991), Figure 1. Point coordinates and pentagonal boundary supplied by Andrew Lawson. Detailed region boundary was digitised by Adrian Baddeley, 2005, from a reprint of Cuzick and Edwards (1990).

References

J. Cuzick and R. Edwards (1990) Spatial clustering for inhomogeneous populations. Journal of the Royal Statistical Society, series B, 52 (1990) 73-104.

P.J. Diggle and A.G. Chetwynd (1991) Second-order analysis of spatial clustering for inhomogeneous populations. Biometrics 47 (1991) 1155-1163.


Identify Points in a Point Pattern

Description

If a point pattern is plotted in the graphics window, this function will find the point of the pattern which is nearest to the mouse position, and print its mark value (or its serial number if there is no mark).

Usage

  ## S3 method for class 'ppp':
  identify(x, ...)

Arguments

x | A point pattern (object of class "ppp").
... | Arguments passed to identify.default.

Details

This is a method for the generic function identify for point pattern objects.

The point pattern x should first be plotted using plot.ppp. Then identify(x) reads the position of the graphics pointer each time the left mouse button is pressed. It then finds the point of the pattern x closest to the mouse position. If this closest point is sufficiently close to the mouse pointer, its index (and its mark if any) will be returned as part of the value of the call.

Each time a point of the pattern is identified, text will be displayed next to the point, showing its serial number (if x is unmarked) or its mark value (if x is marked).

Value

If x is unmarked, the result is a vector containing the serial numbers of the points in the pattern x that were identified. If x is marked, the result is a 2-column matrix, the first column containing the serial numbers and the second containing the marks for these points.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

identify, clickppp


Estimate the I-function

Description

Estimates the summary function I(r) for a multitype point pattern.

Usage

  Iest(X, eps=NULL, r=NULL, breaks=NULL)

Arguments

X | The observed point pattern, from which an estimate of I(r) will be computed. An object of class "ppp", or data in any format acceptable to as.ppp().
eps | the resolution of the discrete approximation to Euclidean distance (see below). There is a sensible default.
r | Optional. Numeric vector of values for the argument r at which I(r) should be evaluated. There is a sensible default. First-time users are strongly advised not to specify this argument. See below for important conditions on r.
breaks | An alternative to the argument r. Not normally invoked by the user. See Details section.

Details

The I function summarises the dependence between types in a multitype point process (Van Lieshout and Baddeley, 1999) It is based on the concept of the J function for an unmarked point process (Van Lieshout and Baddeley, 1996). See Jest for information about the J function.

The I function is defined as

I(r) = (sum p[i] Jii(r)) - J(r)

where J is the J function for the entire point process ignoring the marks, while Jii is the J function for the process consisting of points of type i only, and p[i] is the proportion of points which are of type i.

The I function is designed to measure dependence between points of different types, even if the points are not Poisson. Let X be a stationary multitype point process, and write X[i] for the process of points of type i. If the processes X[i] are independent of each other, then the I-function is identically equal to 0. Deviations I(r) < 1 or I(r) > 1 typically indicate negative and positive association, respectively, between types. See Van Lieshout and Baddeley (1999) for further information.

An estimate of I derived from a multitype spatial point pattern dataset can be used in exploratory data analysis and formal inference about the pattern. The estimate of I(r) is compared against the constant function 0. Deviations I(r) < 1 or I(r) > 1 may suggest negative and positive association, respectively.

This algorithm estimates the I-function from the multitype point pattern X. It assumes that X can be treated as a realisation of a stationary (spatially homogeneous) random spatial marked point process in the plane, observed through a bounded window.

The argument X is interpreted as a point pattern object (of class "ppp", see ppp.object) and can be supplied in any of the formats recognised by as.ppp(). It must be a multitype point pattern (it must have a marks vector which is a factor).

The function Jest is called to compute estimates of the J functions in the formula above. In fact three different estimates are computed using different edge corrections. See Jest for information.

Value

An object of class "fv", see fv.object, which can be plotted directly using plot.fv.
Essentially a data frame containing

r | the vector of values of the argument r at which the function I has been estimated
rs | the ``reduced sample'' or ``border correction'' estimator of I(r) computed from the border-corrected estimates of J functions
km | the spatial Kaplan-Meier estimator of I(r) computed from the Kaplan-Meier estimates of J functions
un | the uncorrected estimate of I(r) computed from the uncorrected estimates of J
theo | the theoretical value of I(r) for a stationary Poisson process: identically equal to 0

Note

Sizeable amounts of memory may be needed during the calculation.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Van Lieshout, M.N.M. and Baddeley, A.J. (1996) A nonparametric measure of spatial interaction in point patterns. Statistica Neerlandica 50, 344–361.

Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

See Also

Jest

Examples

   data(amacrine)
   Ic <- Iest(amacrine)
   plot(Ic, main="Amacrine Cells data")
   # values are below I= 0, suggesting negative association
   # between 'on' and 'off' cells.


Create a Pixel Image Object

Description

Creates an object of class "im" representing a two-dimensional pixel image.

Usage

  im(mat, xcol=seq(ncol(mat)), yrow=seq(nrow(mat)), lev=levels(mat),
   units=NULL)

Arguments

mat | matrix or vector containing the pixel values of the image.
xcol | vector of x coordinates for the pixel gid
yrow | vector of y coordinates for the pixel grid
lev | possible factor levels, if mat should be interpreted as a factor.
units | Optional. Name of unit of length. Either a single character string, or a vector of two character strings giving the singular and plural forms, respectively.

Details

This function creates an object of class "im" representing a two-dimensional pixel image. See im.object for details of this class.

The matrix mat contains the ‘greyscale’ values for a rectangular grid of pixels. Note carefully that the entry mat[i,j] gives the pixel value at the location (xcol[j],yrow[i]. That is, the row index of the matrix mat corresponds to increasing y coordinate, while the column index of mat corresponds to increasing x coordinate. Thus yrow has one entry for each row of mat and xcol has one entry for each column of mat. Under the usual convention in R, a correct display of the image would be obtained by transposing the matrix, e.g. image.default(xcol, yrow, t(mat)), if you wanted to do it by hand.

The entries of mat may be numeric (real or integer), complex, logical, character, or factor values. If mat is not a matrix, it will be converted into a matrix with nrow(mat) = length(yrow) and ncol(mat) = length(xcol).

R{} does not allow a matrix to have factor-valued entries. So to make a factor-valued image from raw data, you must supply mat as a factor vector and specify the arguments xcol and yrow to determine the dimensions of the image. See the examples. (Alternatively you can use the functions cut.im or eval.im to make factor-valued images from other images).

For a description of the methods available for pixel image objects, see im.object.

To convert other kinds of data to a pixel image (for example, functions or windows), use as.im.

Warnings

The internal representation of images is likely to change in future releases of spatstat. The safe way to extract pixel values from an image object is to use as.matrix.im or [.im.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

im.object, as.im, as.matrix.im, [.im, eval.im

Examples

   vec <- rnorm(1200)
   mat <- matrix(vec, nrow=30, ncol=40)
   whitenoise <- im(mat)
   whitenoise <- im(mat, xcol=seq(0,1,length=40), yrow=seq(0,1,length=30))
   whitenoise <- im(vec, xcol=seq(0,1,length=40), yrow=seq(0,1,length=30))
   plot(whitenoise)

   # FACTOR-VALUED IMAGES:
   cutvec <- cut(mat, 3)
   # although mat was a matrix, cutvec is a vector, with factor values
   cutwhite <- im(cutvec, xcol=seq(0,1,length=40), yrow=seq(0,1,length=30))
   # cutwhite is a factor-valued image
   plot(cutwhite)


Class of Images

Description

A class "im" to represent a two-dimensional pixel image.

Details

An object of this class represents a two-dimensional pixel image. It specifies

  • the dimensions of the rectangular array of pixels
  • x and y coordinates for the pixels
  • a numeric value (``grey value'') at each pixel

If X is an object of type im, it contains the following elements:
v | matrix of values
dim | dimensions of matrix v
xrange | range of x coordinates of image window
yrange | range of y coordinates of image window
xstep | width of one pixel
ystep | height of one pixel
xcol | vector of x coordinates of centres of pixels
yrow | vector of y coordinates of centres of pixels

Users are strongly advised not to manipulate these entries directly.

Objects of class "im" may be created by the functions im and as.im. Image objects are also returned by various functions including distmap, Kmeasure, setcov, eval.im and cut.im.

Image objects may be displayed using the methods plot.im, image.im, persp.im and contour.im. There are also methods print.im for printing information about an image, summary.im for summarising an image, mean.im for calculating the average pixel value, hist.im for plotting a histogram of pixel values, quantile.im for calculating quantiles of pixel values, and cut.im for dividing the range of pixel values into categories.

Pixel values in an image may be extracted using the subset operator [.im. To extract all pixel values from an image object, use as.matrix.im. The levels of a factor-valued image can be extracted and changed with levels and levels<-.

Calculations involving one or more images (for example, squaring all the pixel values in an image, converting numbers to factor levels, or subtracting one image from another) can often be done easily using eval.im. To find all pixels satisfying a certain constraint, use solutionset.

Note carefully that the entry v[i,j] gives the pixel value at the location (xcol[j],yrow[i]. That is, the row index of the matrix v corresponds to increasing y coordinate, while the column index of mat corresponds to increasing x coordinate. Thus yrow has one entry for each row of v and xcol has one entry for each column of v. Under the usual convention in R, a correct display of the image would be obtained by transposing the matrix, e.g. image.default(xcol, yrow, t(v)), if you wanted to do it by hand.

Warnings

The internal representation of images is likely to change in future releases of spatstat. Do not address the entries in an image directly. To extract all pixel values from an image object, use as.matrix.im.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

im, as.im, plot.im, persp.im, eval.im, [.im


Test Whether Points Are Inside A Window

Description

Test whether points lie inside or outside a given window.

Usage

 inside.owin(x, y, w)

Arguments

x | Vector of x coordinates of points to be tested.
y | Vector of y coordinates of points to be tested.
w | A window. This should be an object of class owin, or can be given in any format acceptable to as.owin().

Details

This function tests whether each of the points (x[i],y[i]) lies inside or outside the window w and returns TRUE if it is inside.

The boundary of the window is treated as being inside.

If w is of type "rectangle" or "polygonal", the algorithm uses analytic geometry (the discrete Stokes theorem). Computation time is linear in the number of points and (for polygonal windows) in the number of vertices of the boundary polygon. Boundary cases are correct to single precision accuracy.

If w is of type "mask" then the pixel closest to (x[i],y[i]) is tested. The results may be incorrect for points lying within one pixel diameter of the window boundary.

Value

Logical vector whose ith entry is TRUE if the corresponding point (x[i],y[i]) is inside w.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin.object, as.owin

Examples

  # hexagonal window
  k <- 6
  theta <- 2 * pi * (0:(k-1))/k
  co <- cos(theta)
  si <- sin(theta)
  mas <- owin(c(-1,1), c(-1,1), poly=list(x=co, y=si))
  ## Not run:
  plot(mas)

## End(Not run)

  # random points in rectangle
  x <- runif(30,min=-1, max=1)
  y <- runif(30,min=-1, max=1)

  ok <- inside.owin(x, y, mas)

  ## Not run:
  points(x[ok], y[ok])
  points(x[!ok], y[!ok], pch="x")

## End(Not run)


Internal spatstat functions

Description

Internal spatstat functions.

Usage

affinexy(X, mat = diag(c(1, 1)), vec = c(0, 0))
apply23sum(x)
area.xypolygon(polly)
AsymmHausdorff.psp(X, Y, method="Fortran")
as.breakpts(...)
as.fv(x)
as.polygonal(W)
as.units(s)
beachcolours(heightrange, sealevel, monochrome, ncolours)
bind.fv(x, y, labl, desc, preferred)
bdrylength.xypolygon(polly)
bdry.mask(W)
breakpts(val, maxi, even = FALSE, npos = NULL, step = NULL)
breakpts.from.r(r)
cartesian(pp, markset, fac = TRUE)
cellmiddles(W, nx, ny, npix, gi)
checkfields(X,L)
check.hist.lengths(hist,breaks)
check.named.vector(x, nam)
clip.psp(x, window, check=TRUE)
cliprect.psp(x, window)
clippoly.psp(s, window)
closepairs(X,rmax)
crosspairs(X,Y,rmax)
cobble.xy(x, y, f, fatal)
commasep(x)
countingweights(id, areas, check = TRUE)
damaged.ppm(object)
default.expand(object, m, epsilon)
default.clipwindow(object, epsilon)
default.n.tiling(X, nd, ntile, npix, verbose)
default.ntile(X)
diagnose.ppm.engine(object, ..., type="eem", typename, opt,
                         sigma=NULL, rbord = reach(object), compute.sd=TRUE,
                         compute.cts=TRUE, rv=NULL, oldstyle=FALSE)
discretise(x, xrange, nx)
distpl(p, l)
distppl(p, l)
distppll(p, l, mintype=0, method="Fortran", listit=FALSE)
divisors(n)
do.call.matched(fname, arglist, funargs, extrargs)
edge.Ripley(X, r, W, method)
edge.Trans(X, Y, W, exact, paired, trim)
ensure2vector(x)
equals.quad(Q)
eratosthenes(nmax)
erode.mask(w,r)
even.breaks.owin(w)
exactdt(X, ...)
exactPdt(w)
fasp(fns, titles, formulae, which, dataname, title)
findmarktype(x)
fii(interaction, coefs, Vnames)
FormatFaspFormulae(f, argname)
fv(x, argu, ylab, valu, fmla, alim, labl, desc, units)
greatest.common.divisor(n,m)
getfields(X, L, fatal = TRUE)
getglmfit(object)
gridindex(x, y, xrange, yrange, nx, ny)
handle.r.b.args(r = NULL, breaks = NULL, window, eps = NULL, rmaxdefault)
handle.rshift.args(W, ..., radius, width, height, edge, clip, edgedefault)
ho.engine(model, ..., nsim, nrmh, start, control, verb)
identical.formulae(x,y)
inside.xypolygon(pts, polly, test01 = TRUE, method="Fortran")
intersect.ranges(a,b)
intX.owin(w)
intX.xypolygon(polly)
intY.owin(w)
intY.xypolygon(polly)
is.cadlag(s)
is.data(Q)
is.fv(x)
is.interact(x)
## Default S3 method:
is.marked(...)
## S3 method for class 'quad':
is.marked(X, na.action="warn", ...)
## Default S3 method:
is.multitype(...)
## S3 method for class 'quad':
is.multitype(X, na.action="warn", ...)
is.poisson.interact(x)
is.poisson.ppm(x)
is.prime(n)
is.stationary.ppm(x)
km.rs(o, cc, d, breaks)
Kborder.engine(X, rmax, nr, correction, weights)
Kount(dIJ, bI, b, breaks)
Kwtsum(dIJ, bI, wIJ, b, w, breaks)
Kmulti.inhom(X, I, J, lambdaI, lambdaJ, ...,
         r=NULL, breaks=NULL,
         correction = c("border", "isotropic", "Ripley", "translate") ,
         lambdaIJ=NULL,
         Iname = "points satisfying condition I",
         Jname = "points satisfying condition J")
killinteraction(model)
least.common.multiple(n,m)
## S3 method for class 'im':
levels(x) <- value
lookup.im(Z, x, y, naok)
majorminorversion(v)
make.even.breaks(bmax, npos, bstep)
makeunits(sing, plur, mul)
markformat(x)
## S3 method for class 'ppp':
markformat(x)
## S3 method for class 'psp':
markformat(x)
markspace.integral(X)
marks(x, ...)
## S3 method for class 'ppp':
marks(x, ..., dfok)
## S3 method for class 'psp':
marks(x, ..., dfok)
## S3 method for class 'quad':
marks(x, dfok=FALSE, ...)
marks(x, ...) <- value
## S3 method for class 'ppp':
marks(x, dfok, ...) <- value
markappendop(x, y)
marksubset(x, index, format)
marksubsetop(x, i)
markreplicateop(x, n)
matcolall(x)
matcolany(x)
matcolsum(x)
matrixsample(mat, newdim, phase)
matrowall(x)
matrowany(x)
matrowsum(x)
maxflow(costm)
meanX.owin(w)
meanY.owin(w)
mkcor(d, ff, wt, Ef, rvals, method="smrep", ..., nwtsteps=500)
mpl.engine(Q, trend, interaction, ..., covariates, correction,
         rbord, use.gam, famille,
         forcefit, allcovar, callstring, precomputed, savecomputed, preponly)
mpl.get.covariates(covariates, locations, type)
mpl.prepare(Q, X, P, trend, interaction, covariates,
            want.trend, want.inter, correction, rbord, Pname,
            callstring, ..., allcovar, precomputed, savecomputed,
            vnamebase, vnameprefix)
MultiPair.checkmatrix(mat, n, name)
nearest.pixel(x, y, im)
newstyle.coeff.handling(object)
no.trend.ppm(x)
n.quad(Q)
outdated.interact(object)
overlap.owin(A,B)
overlap.trapezium(xa, ya, xb, yb, verb = FALSE)
overlap.xypolygon(P, Q)
owinpolycheck(W, verbose=TRUE)
param.quad(Q)
pixellate(x, ..., weights)
ploterodewin(W1, W2, col.edge, col.inside, ...)
ploterodeimage(W, Z, ..., Wcol, rangeZ, colsZ)
## S3 method for class 'minconfit':
plot(x, ...)
## S3 method for class 'pppmatching':
plot(x, addmatch = NULL, main = NULL, ...)
## S3 method for class 'profilepl':
plot(x, ..., add=FALSE, main=NULL, tag=TRUE, coeff=NULL, xvariable=NULL)
## S3 method for class 'qqppm':
plot(x, ..., limits=TRUE, monochrome=FALSE,
           limcol=if(monochrome) "black" else "red")
## S3 method for class 'quadratcount':
plot(x, ..., add, entries, dx, dy)
## S3 method for class 'quadrattest':
plot(x, ...)
polynom(x, ...)
pppdist.prohorov(X, Y, precision = 7)
pppmatching(X, Y, am, ty = "generic")
primefactors(n, prmax)
## S3 method for class 'diagppm':
print(x, ...)
## S3 method for class 'envelope':
print(x, ...)
## S3 method for class 'fasp':
print(x, ...)
## S3 method for class 'fii':
print(x, ...)
## S3 method for class 'fv':
print(x, ...)
## S3 method for class 'interact':
print(x, ..., family=TRUE, brief=FALSE)
## S3 method for class 'isf':
print(x, ...)
## S3 method for class 'minconfit':
print(x, ...)
## S3 method for class 'plotppm':
print(x, ...)
## S3 method for class 'pppmatching':
print(x, ...)
## S3 method for class 'profilepl':
print(x, ...)
## S3 method for class 'qqppm':
print(x, ...)
## S3 method for class 'rmhcontrol':
print(x, ...)
## S3 method for class 'rmhmodel':
print(x, ...)
## S3 method for class 'rmhstart':
print(x, ...)
## S3 method for class 'rmhseed':
print(x, ...)
## S3 method for class 'summary.fii':
print(x, ...)
## S3 method for class 'summary.listof':
print(x, ...)
## S3 method for class 'summary.owin':
print(x, ...)
## S3 method for class 'summary.ppp':
print(x, ..., dp=3)
## S3 method for class 'summary.psp':
print(x, ...)
## S3 method for class 'summary.splitppp':
print(x, ...)
## S3 method for class 'summary.units':
print(x, ...)
## S3 method for class 'units':
print(x, ...)
prolongseq(x, newrange)
quad(data, dummy, w, param)
quadrat.breaks(xr, yr, nx = 5, ny = nx, xbreaks = NULL, ybreaks = NULL)
quadrat.count.engine(x, y, xbreaks, ybreaks, weights)
quadrat.test.engine(X, nx, ny, xbreaks, ybreaks, ..., fit=NULL, Xname=NULL, fitname=NULL)
quadscheme.replicated(data, dummy, method = "grid", ...)
quadscheme.spatial(data, dummy, method = "grid", ...)
rasterx.im(x)
rastery.im(x)
reincarnate.interact(object)
rebound.ppp(x, ...)
rebound.psp(x, ...)
rebound.owin(w, rect)
## S3 method for class 'units':
rescale(X,s)
resid4plot(RES, plot.neg="image", plot.smooth="imagecontour",
           spacing=0.1, srange=NULL,monochrome=FALSE, main=NULL, ...)
resid1plot(RES, opt, plot.neg="image", plot.smooth="imagecontour",
              srange=NULL, monochrome=FALSE, main=NULL, ...)
resid1panel(observedX, observedV,
            theoreticalX, theoreticalV, theoreticalSD, xlab,ylab, ...)
resolve.defaults(..., .StripNull=FALSE)
restrict.mask(M, W)
reverse.xypolygon(p)
revcumsum(x)
rmax.rule(fun, W, lambda)
rotxy(X, angle = pi/2)
rmhResolveTypes(model, start, control)
## S3 method for class 'rmhcontrol':
rmhcontrol(control, ...)
## S3 method for class 'list':
rmhcontrol(control, ...)
rmhEngine(InfoList, ..., verbose, reseed, kitchensink, preponly)
## S3 method for class 'rmhmodel':
rmhmodel(model, ...)
rmhseed(iseed)
## S3 method for class 'rmhstart':
rmhstart(start, ...)
## S3 method for class 'list':
rmhstart(start, ...)
rmpoint.I.allim(n, f, types)
rpoint.multi(n, f, fmax=NULL, marks = NULL, win = unit.square(), giveup = 1000, verbose = FALSE)
runifpoispp(lambda, win = owin(c(0, 1), c(0, 1)))
runifrect(n, win = owin(c(0, 1), c(0, 1)))
second.moment.calc(x, sigma=NULL, edge=TRUE, what="Kmeasure", debug=FALSE,
..., varcov=NULL)
shiftxy(X, vec = c(0, 0))
spatstat.rawdata.location(...)
sp.foundclass(cname, inlist, formalname, argsgiven)
sp.foundclasses(cnames, inlist, formalname, argsgiven)
stratrand(window, nx, ny, k = 1)
suffloc(object)
suffstat.generic(model, X, callstring)
suffstat.poisson(model, X, callstring)
## S3 method for class 'envelope':
summary(object,...)
## S3 method for class 'fii':
summary(object,...)
## S3 method for class 'profilepl':
summary(object, ...)
## S3 method for class 'pppmatching':
summary(object, ...)
## S3 method for class 'units':
summary(object, ...)
sympoly(x, y, n)
termsinformula(x)
test.crossing.psp(A,B)
tilecentroids(W, nx, ny)
trim.mask(M, R)
## Default S3 method:
units(x)
## Default S3 method:
units(x) <- value
## S3 method for class 'interact':
update(object, ...)
valid.ppm(object, na.value)
validate.mask(w, fatal=TRUE)
validate.quad(Q, fatal, repair, announce)
variablesinformula(x)
versionstring.interact(object)
versionstring.ppm(object)
versionstring.spatstat()
verifyclass(X, C, N = deparse(substitute(X)), fatal = TRUE)
verify.xypolygon(p, fatal=TRUE)
whist(x,breaks,weights, trim, right)
w.quad(Q)
x.quad(Q)
y.quad(Q)
xypolyselfint(p, eps, proper, yesorno, checkinternal)
xypolygon2psp(p, w)

Details

These are usually not to be called by the user.


Interpolate a Pixel Image

Description

Interpolates the values of a pixel image at any desired location in the frame.

Usage

interp.im(Z, x, y)

Arguments

Z | Pixel image (object of class "im") with numeric or integer values.
x,y | Vectors of Cartesian coordinates.

Details

A value at each location (x[i],y[i]) will be interpolated using the pixel values of Z at the four surrounding pixel centres, by simple bilinear interpolation.

At the boundary (where (x[i],y[i]) is not surrounded by four pixel centres) the value at the nearest pixel is taken.

Value

Vector of interpolated values, with NA for points that lie outside the domain of the image.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

Examples

   opa <- par(mfrow=c(1,2))
   # coarse image
   V <- as.im(function(x,y) { x^2 + y }, owin(), dimyx=10)
   plot(V, main="coarse image", col=terrain.colors(256))

   # lookup value at location (0.5,0.5)
   V[list(x=0.5,y=0.5)]
   # interpolated value at location (0.5,0.5)
   interp.im(V, 0.5, 0.5)
   # true value is 0.75

   # how to obtain an interpolated image at a desired resolution
   U <- as.im(interp.im, W=owin(), Z=V, dimyx=256)
   plot(U, main="interpolated image", col=terrain.colors(256))
   par(opa)


Intersection or Union of Two Windows

Description

Yields the intersection or union of two windows.

Usage

   intersect.owin(A, B, ...)
   union.owin(A,B, ...)

Arguments

A | A window object (see Details).
B | A window object.
... | Optional arguments passed to as.mask to control the discretisation, if required.

Details

The function intersect.owin computes the intersection between the two windows A and B, while union.owin computes their union.

The arguments A and B must be window objects (either objects of class "owin", or data that can be coerced to this class by as.owin).

At present the intersection or union of two polygons is computed by discretising them, yielding a binary image mask.

If the intersection or union is empty, an error occurs.

Value

A window object.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

is.subset.owin, overlap.owin, bounding.box, owin.object

Examples

# rectangles
   u <- unit.square()
   v <- owin(c(0.5,3.5), c(0.4,2.5))
# polygon
   data(letterR)
# mask
   m <- as.mask(letterR)

# two rectangles
   intersect.owin(u, v)
   union.owin(u,v)

# polygon and rectangle
   intersect.owin(letterR, v)
   union.owin(letterR,v)

# mask and rectangle
   intersect.owin(m, v)
   union.owin(m,v)

# mask and polygon
   p <- rotate(v, 0.2)
   intersect.owin(m, p)
   union.owin(m,p)
#
   A <- letterR
   B <- rotate(letterR, 0.2)
   plot(bounding.box(A,B), main="intersection")
   w <- intersect.owin(A, B)
   plot(w, add=TRUE)
   plot(A, add=TRUE)
   plot(B, add=TRUE)

   plot(bounding.box(A,B), main="union")
   w <- union.owin(A,B)
   plot(w, add=TRUE)
   plot(A, add=TRUE)
   plot(B, add=TRUE)


Test Whether An Object Is A Pixel Image

Description

Tests whether its argument is a pixel image (object of class "im").

Usage

is.im(x)

Arguments

x Any object.

Details

This function tests whether the argument x is a pixel image object of class "im". For details of this class, see im.object.

The object is determined to be an image if it inherits from class "im".

Value

TRUE if x is a pixel image, otherwise FALSE.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf


Test Whether Marks Are Present

Description

Generic function to test whether a given object (usually a point pattern or something related to a point pattern) has ``marks'' attached to the points.

Usage

  is.marked(X, ...)

Arguments

X | Object to be inspected
... | Other arguments.

Details

``Marks'' are observations attached to each point of a point pattern. For example the longleaf dataset contains the locations of trees, each tree being marked by its diameter; the amacrine dataset gives the locations of cells of two types (on/off) and the type of cell may be regarded as a mark attached to the location of the cell.

Other objects related to point patterns, such as point process models, may involve marked points.

This function tests whether the object X contains or involves marked points. It is generic; methods are provided for point patterns (objects of class "ppp") and point process models (objects of class "ppm").

Value

Logical value, equal to TRUE if X is marked.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

is.marked.ppp, is.marked.ppm


Test Whether A Point Process Model is Marked

Description

Tests whether a fitted point process model involves ``marks'' attached to the points.

Usage

  ## S3 method for class 'ppm':
  is.marked(X, ...)

Arguments

X | Fitted point process model (object of class "ppm") usually obtained from ppm.
... | Ignored.

Details

``Marks'' are observations attached to each point of a point pattern. For example the longleaf dataset contains the locations of trees, each tree being marked by its diameter; the amacrine dataset gives the locations of cells of two types (on/off) and the type of cell may be regarded as a mark attached to the location of the cell.

The argument X is a fitted point process model (an object of class "ppm") typically obtained by fitting a model to point pattern data using ppm.

This function returns TRUE if the original data (to which the model X was fitted) were a marked point pattern.

Note that this is not the same as testing whether the model involves terms that depend on the marks (i.e. whether the fitted model ignores the marks in the data). Currently we have not implemented a test for this.

If this function returns TRUE, the implications are (for example) that any simulation of this model will require simulation of random marks as well as random point locations.

Value

Logical value, equal to TRUE if X is a model that was fitted to a marked point pattern dataset.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

is.marked, is.marked.ppp

Examples

   data(lansing)
   # Multitype point pattern --- trees marked by species

  fit1 <- ppm(lansing, ~ marks, Poisson())
  is.marked(fit1)
  # TRUE

  fit2 <- ppm(lansing, ~ 1, Poisson())
  is.marked(fit2)
  # TRUE

  data(cells)
  # Unmarked point pattern

  fit3 <- ppm(cells, ~ 1, Poisson())
  is.marked(fit3)
  # FALSE


Test Whether A Point Pattern is Marked

Description

Tests whether a point pattern has ``marks'' attached to the points.

Usage

  ## S3 method for class 'ppp':
  is.marked(X, na.action="warn", ...)

Arguments

X | Point pattern (object of class "ppp")
na.action | String indicating what to do if NA values are encountered amongst the marks. Options are "warn", "fatal" and "ignore".
... | Ignored.

Details

``Marks'' are observations attached to each point of a point pattern. For example the longleaf dataset contains the locations of trees, each tree being marked by its diameter; the amacrine dataset gives the locations of cells of two types (on/off) and the type of cell may be regarded as a mark attached to the location of the cell.

This function tests whether the point pattern X contains or involves marked points. It is a method for the generic function is.marked.

The argument na.action determines what action will be taken if the point pattern has a vector of marks but some or all of the marks are NA. Options are "fatal" to cause a fatal error; "warn" to issue a warning and then return TRUE; and "ignore" to take no action except returning TRUE.

Value

Logical value, equal to TRUE if X is a marked point pattern.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

is.marked, is.marked.ppm

Examples

   data(cells)
   is.marked(cells)  #FALSE
   data(longleaf)
   is.marked(longleaf) #TRUE


Test whether Object is Multitype

Description

Generic function to test whether a given object (usually a point pattern or something related to a point pattern) has ``marks'' attached to the points which classify the points into several types.

Usage

  is.multitype(X, ...)

Arguments

X | Object to be inspected
... | Other arguments.

Details

``Marks'' are observations attached to each point of a point pattern. For example the longleaf dataset contains the locations of trees, each tree being marked by its diameter; the amacrine dataset gives the locations of cells of two types (on/off) and the type of cell may be regarded as a mark attached to the location of the cell. Other objects related to point patterns, such as point process models, may involve marked points.

This function tests whether the object X contains or involves marked points, and that the marks are a factor.

For example, the amacrine dataset is multitype (there are two types of cells, on and off), but the longleaf dataset is not multitype (the marks are real numbers).

This function is generic; methods are provided for point patterns (objects of class "ppp") and point process models (objects of class "ppm").

Value

Logical value, equal to TRUE if X is multitype.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

is.multitype.ppp, is.multitype.ppm


Test Whether A Point Process Model is Multitype

Description

Tests whether a fitted point process model involves ``marks'' attached to the points that classify the points into several types.

Usage

  ## S3 method for class 'ppm':
  is.multitype(X, ...)

Arguments

X | Fitted point process model (object of class "ppm") usually obtained from ppm.
... | Ignored.

Details

``Marks'' are observations attached to each point of a point pattern. For example the longleaf dataset contains the locations of trees, each tree being marked by its diameter; the amacrine dataset gives the locations of cells of two types (on/off) and the type of cell may be regarded as a mark attached to the location of the cell.

The argument X is a fitted point process model (an object of class "ppm") typically obtained by fitting a model to point pattern data using ppm.

This function returns TRUE if the original data (to which the model X was fitted) were a multitype point pattern.

Note that this is not the same as testing whether the model involves terms that depend on the marks (i.e. whether the fitted model ignores the marks in the data). Currently we have not implemented a test for this.

If this function returns TRUE, the implications are (for example) that any simulation of this model will require simulation of random marks as well as random point locations.

Value

Logical value, equal to TRUE if X is a model that was fitted to a multitype point pattern dataset.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

is.multitype, is.multitype.ppp

Examples

   data(lansing)
   # Multitype point pattern --- trees marked by species

  fit1 <- ppm(lansing, ~ marks, Poisson())
  is.multitype(fit1)
  # TRUE

  fit2 <- ppm(lansing, ~ 1, Poisson())
  is.multitype(fit2)
  # TRUE

  data(cells)
  # Unmarked point pattern

  fit3 <- ppm(cells, ~ 1, Poisson())
  is.multitype(fit3)
  # FALSE


Test Whether A Point Pattern is Multitype

Description

Tests whether a point pattern has ``marks'' attached to the points which classify the points into several types.

Usage

  ## S3 method for class 'ppp':
  is.multitype(X, na.action="warn", ...)

Arguments

X | Point pattern (object of class "ppp")
na.action | String indicating what to do if NA values are encountered amongst the marks. Options are "warn", "fatal" and "ignore".
... | Ignored.

Details

``Marks'' are observations attached to each point of a point pattern. For example the longleaf dataset contains the locations of trees, each tree being marked by its diameter; the amacrine dataset gives the locations of cells of two types (on/off) and the type of cell may be regarded as a mark attached to the location of the cell.

This function tests whether the point pattern X contains or involves marked points, and that the marks are a factor. It is a method for the generic function is.multitype.

For example, the amacrine dataset is multitype (there are two types of cells, on and off), but the longleaf dataset is not multitype (the marks are real numbers).

The argument na.action determines what action will be taken if the point pattern has a vector of marks but some or all of the marks are NA. Options are "fatal" to cause a fatal error; "warn" to issue a warning and then return TRUE; and "ignore" to take no action except returning TRUE.

Value

Logical value, equal to TRUE if X is a multitype point pattern.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

is.multitype, is.multitype.ppm

Examples

   data(cells)
   is.multitype(cells)  #FALSE - no marks
   data(longleaf)
   is.multitype(longleaf) #FALSE - real valued marks
   data(amacrine)
   is.multitype(amacrine) #TRUE


Test Whether An Object Is A Window

Description

Checks whether its argument is a window (object of class "owin").

Usage

is.owin(x)

Arguments

x Any object.

Details

This function tests whether the object x is a window object of class "owin". See owin.object for details of this class.

The result is determined to be TRUE if x inherits from "owin", i.e. if x has "owin" amongst its classes.

Value

TRUE if x is a point pattern, otherwise FALSE.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf


Test Whether An Object Is A Fitted Point Process Model

Description

Checks whether its argument is a fitted point process model (object of class "ppm").

Usage

is.ppm(x)

Arguments

x Any object.

Details

This function tests whether the object x is a fitted point process model object of class "ppm". See ppm.object for details of this class.

Value

TRUE if x has "ppm" amongst its classes, otherwise FALSE.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf


Test Whether An Object Is A Point Pattern

Description

Checks whether its argument is a point pattern (object of class "ppp").

Usage

is.ppp(x)

Arguments

x Any object.

Details

This function tests whether the object x is a point pattern object of class "ppp". See ppm.object for details of this class.

The result is determined to be TRUE if x inherits from "ppp", i.e. if x has "ppp" amongst its classes.

Value

TRUE if x is a point pattern, otherwise FALSE.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf


Determine Whether One Window is Contained In Another

Description

Tests whether window A is a subset of window B.

Usage

is.subset.owin(A, B)

Arguments

A | A window object (see Details).
B | A window object (see Details).

Details

This function tests whether the window A is a subset of the window B.

The arguments A and B must be window objects (either objects of class "owin", or data that can be coerced to this class by as.owin).

Various algorithms are used, depending on the geometrical type of the two windows.

Note that if B is not rectangular, the algorithm proceeds by discretising A, converting it to a pixel mask using as.mask. In this case the resulting answer is only ``approximately correct''. The accuracy of the approximation can be controlled: see as.mask.

Value

Logical scalar; TRUE if A is a sub-window of B, otherwise FALSE.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

Examples

   w1 <- as.owin(c(0,1,0,1))
   w2 <- as.owin(c(-1,2,-1,2))
   is.subset.owin(w1,w2)  # Returns TRUE.
   is.subset.owin(w2,w1)  # Returns FALSE.


Japanese Pines Point Pattern

Description

The data give the locations of Japanese black pine saplings in a square sampling region in a natural forest. The observations were originally collected by Numata (1961).

These data are used as a standard example in the textbook of Diggle (2003); see pages 1, 14, 19, 22, 24, 56–57 and 61.

Usage

data(japanesepines)

Format

An object of class "ppp" representing the point pattern of tree locations in a 5.7 x 5.7 metre square, rescaled to the unit square and rounded to two decimal places.

See ppp.object for details of the format of a point pattern object.

Source

Diggle (2003), obtained from Numata (1961)

References

Diggle, P.J. (2003) Statistical Analysis of Spatial Point Patterns. Arnold Publishers.

Numata, M. (1961) Forest vegetation in the vicinity of Choshi. Coastal flora and vegetation at Choshi, Chiba Prefecture. IV. Bulletin of Choshi Marine Laboratory, Chiba University 3, 28–48 (in Japanese).


Multitype J Function (i-to-j)

Description

For a multitype point pattern, estimate the multitype J function summarising the interpoint dependence between points of type i and of type j.

Usage

Jcross(X, i=1, j=2, eps=NULL, r=NULL, breaks=NULL, ...)

Arguments

X | The observed point pattern, from which an estimate of the multitype J function Jij(r) will be computed. It must be a multitype point pattern (a marked point pattern whose marks are a factor). See under Details.
i | Number or character string identifying the type (mark value) of the points in X from which distances are measured.
j | Number or character string identifying the type (mark value) of the points in X to which distances are measured.
eps | A positive number. The resolution of the discrete approximation to Euclidean distance (see below). There is a sensible default.
r | Optional. Numeric vector. The values of the argument r at which the function Jij(r) should be evaluated. There is a sensible default. First-time users are strongly advised not to specify this argument. See below for important conditions on r.
breaks | An alternative to the argument r. Not normally invoked by the user. See the Details section.
... | Ignored.

Details

This function Jcross and its companions Jdot and Jmulti are generalisations of the function Jest to multitype point patterns.

A multitype point pattern is a spatial pattern of points classified into a finite number of possible ``colours'' or ``types''. In the spatstat package, a multitype pattern is represented as a single point pattern object in which the points carry marks, and the mark value attached to each point determines the type of that point.

The argument X must be a point pattern (object of class "ppp") or any data that are acceptable to as.ppp. It must be a marked point pattern, and the mark vector X$marks must be a factor. The argument i will be interpreted as a level of the factor X$marks. (Warning: this means that an integer value i=3 will be interpreted as the 3rd smallest level, not the number 3).

The ``type i to type j'' multitype J function of a stationary multitype point process X was introduced by Van lieshout and Baddeley (1999). It is defined by

Jij(r) = (1 - Gij(r))/(1-Fj(r))

where Gij(r) is the distribution function of the distance from a type i point to the nearest point of type j, and Fj(r) is the distribution function of the distance from a fixed point in space to the nearest point of type j in the pattern.

An estimate of Jij(r) is a useful summary statistic in exploratory data analysis of a multitype point pattern. If the subprocess of type i points is independent of the subprocess of points of type j, then Jij(r) = 1. Hence deviations of the empirical estimate of Jij from the value 1 may suggest dependence between types.

This algorithm estimates Jij(r) from the point pattern X. It assumes that X can be treated as a realisation of a stationary (spatially homogeneous) random spatial point process in the plane, observed through a bounded window. The window (which is specified in X as X$window) may have arbitrary shape. Biases due to edge effects are treated in the same manner as in Jest, using the Kaplan-Meier and border corrections. The main work is done by Gmulti and Fest.

The argument r is the vector of values for the distance r at which Jij(r) should be evaluated. The values of r must be increasing nonnegative numbers and the maximum r value must exceed the radius of the largest disc contained in the window.

Value

An object of class "fv" (see fv.object).
Essentially a data frame containing six numeric columns

J | the recommended estimator of Jij(r), currently the Kaplan-Meier estimator.
r | the values of the argument r at which the function Jij(r) has been estimated
km | the Kaplan-Meier estimator of Jij(r)
rs | the ``reduced sample'' or ``border correction'' estimator of Jij(r)
un | the ``uncorrected'' estimator of Jij(r) formed by taking the ratio of uncorrected empirical estimators of 1 - Gij(r) and 1 - Fj(r), see Gdot and Fest.
theo | the theoretical value of Jij(r) for a marked Poisson process, namely 1.

The result also has two attributes "G" and "F" which are respectively the outputs of Gcross and Fest for the point pattern.

Warnings

The argument i is interpreted as a level of the factor X$marks. Beware of the usual trap with factors: numerical values are not interpreted in the same way as character values. See the first example.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Van Lieshout, M.N.M. and Baddeley, A.J. (1996) A nonparametric measure of spatial interaction in point patterns. Statistica Neerlandica 50, 344–361.

Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

See Also

Jdot, Jest, Jmulti

Examples

     # Lansing woods data: 6 types of trees
    data(lansing)

    Jhm <- Jcross(lansing, "hickory", "maple")
    # diagnostic plot for independence between hickories and maples
    plot(Jhm)

    # synthetic example with two marks "a" and "b"
    pp <- runifpoispp(50)
    pp <- pp %mark% sample(c("a","b"), pp$n, replace=TRUE)
    J <- Jcross(pp, "a", "b")


Multitype J Function (i-to-any)

Description

For a multitype point pattern, estimate the multitype J function summarising the interpoint dependence between the type i points and the points of any type.

Usage

Jdot(X, i=1, eps=NULL, r=NULL, breaks=NULL, ...)

Arguments

X | The observed point pattern, from which an estimate of the multitype J function Ji.(r) will be computed. It must be a multitype point pattern (a marked point pattern whose marks are a factor). See under Details.
i | Number or character string identifying the type (mark value) of the points in X from which distances are measured.
eps | A positive number. The resolution of the discrete approximation to Euclidean distance (see below). There is a sensible default.
r | numeric vector. The values of the argument r at which the function Ji.(r) should be evaluated. There is a sensible default. First-time users are strongly advised not to specify this argument. See below for important conditions on r.
breaks | An alternative to the argument r. Not normally invoked by the user. See the Details section.
... | Ignored.

Details

This function Jdot and its companions Jcross and Jmulti are generalisations of the function Jest to multitype point patterns.

A multitype point pattern is a spatial pattern of points classified into a finite number of possible ``colours'' or ``types''. In the spatstat package, a multitype pattern is represented as a single point pattern object in which the points carry marks, and the mark value attached to each point determines the type of that point.

The argument X must be a point pattern (object of class "ppp") or any data that are acceptable to as.ppp. It must be a marked point pattern, and the mark vector X$marks must be a factor. The argument i will be interpreted as a level of the factor X$marks. (Warning: this means that an integer value i=3 will be interpreted as the 3rd smallest level, not the number 3).

The ``type i to any type'' multitype J function of a stationary multitype point process X was introduced by Van lieshout and Baddeley (1999). It is defined by

Ji.(r) = (1 - Gi.(r))/(1-F.(r))

where Gi.(r) is the distribution function of the distance from a type i point to the nearest other point of the pattern, and F.(r) is the distribution function of the distance from a fixed point in space to the nearest point of the pattern.

An estimate of Ji.(r) is a useful summary statistic in exploratory data analysis of a multitype point pattern. If the pattern is a marked Poisson point process, then Ji.(r) = 1. If the subprocess of type i points is independent of the subprocess of points of all types not equal to i, then Ji.(r) equals Jii(r), the ordinary J function (see Jest and Van Lieshout and Baddeley (1996)) of the points of type i. Hence deviations from zero of the empirical estimate of Ji.-Jii may suggest dependence between types.

This algorithm estimates Ji.(r) from the point pattern X. It assumes that X can be treated as a realisation of a stationary (spatially homogeneous) random spatial point process in the plane, observed through a bounded window. The window (which is specified in X as X$window) may have arbitrary shape. Biases due to edge effects are treated in the same manner as in Jest, using the Kaplan-Meier and border corrections. The main work is done by Gmulti and Fest.

The argument r is the vector of values for the distance r at which Ji.(r) should be evaluated. The values of r must be increasing nonnegative numbers and the maximum r value must exceed the radius of the largest disc contained in the window.

Value

An object of class "fv" (see fv.object).
Essentially a data frame containing six numeric columns

J | the recommended estimator of Ji.(r), currently the Kaplan-Meier estimator.
r | the values of the argument r at which the function Ji.(r) has been estimated
km | the Kaplan-Meier estimator of Ji.(r)
rs | the ``reduced sample'' or ``border correction'' estimator of Ji.(r)
un | the ``uncorrected'' estimator of Ji.(r) formed by taking the ratio of uncorrected empirical estimators of 1 - Gi.(r) and 1 - F.(r), see Gdot and Fest.
theo | the theoretical value of Ji.(r) for a marked Poisson process, namely 1.

The result also has two attributes "G" and "F" which are respectively the outputs of Gdot and Fest for the point pattern.

Warnings

The argument i is interpreted as a level of the factor X$marks. Beware of the usual trap with factors: numerical values are not interpreted in the same way as character values. See the first example.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Van Lieshout, M.N.M. and Baddeley, A.J. (1996) A nonparametric measure of spatial interaction in point patterns. Statistica Neerlandica 50, 344–361.

Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

See Also

Jcross, Jest, Jmulti

Examples

     # Lansing woods data: 6 types of trees
    data(lansing)

    Jh. <- Jdot(lansing, "hickory")
    plot(Jh.)
    # diagnostic plot for independence between hickories and other trees
    Jhh <- Jest(lansing[lansing$marks == "hickory", ])
    plot(Jhh, add=TRUE)

    # synthetic example with two marks "a" and "b"
    pp <- runifpoispp(50)
    pp <- pp %mark% sample(c("a","b"), pp$n, replace=TRUE)
    J <- Jdot(pp, "a")


Estimate the J-function

Description

Estimates the summary function J(r) for a point pattern in a window of arbitrary shape.

Usage

  Jest(X, eps=NULL, r=NULL, breaks=NULL)

Arguments

X | The observed point pattern, from which an estimate of J(r) will be computed. An object of class "ppp", or data in any format acceptable to as.ppp().
eps | the resolution of the discrete approximation to Euclidean distance (see below). There is a sensible default.
r | vector of values for the argument r at which J(r) should be evaluated. There is a sensible default. First-time users are strongly advised not to specify this argument. See below for important conditions on r.
breaks | An alternative to the argument r. Not normally invoked by the user. See Details section.

Details

The J function (Van Lieshout and Baddeley ,1996) of a stationary point process is defined as

J(r) = (1-G(r))/(1-F(r))

where G(r) is the nearest neighbour distance distribution function of the point process (see Gest) and F(r) is its empty space function (see Fest).

For a completely random (uniform Poisson) point process, the J-function is identically equal to 1. Deviations J(r) < 1 or J(r) > 1 typically indicate spatial clustering or spatial regularity, respectively. The J-function is one of the few characteristics that can be computed explicitly for a wide range of point processes. See Van Lieshout and Baddeley (1996), Baddeley et al (2000), Thonnes and Van Lieshout (1999) for further information.

An estimate of J derived from a spatial point pattern dataset can be used in exploratory data analysis and formal inference about the pattern. The estimate of J(r) is compared against the constant function 1. Deviations J(r) < 1 or J(r) > 1 may suggest spatial clustering or spatial regularity, respectively.

This algorithm estimates the J-function from the point pattern X. It assumes that X can be treated as a realisation of a stationary (spatially homogeneous) random spatial point process in the plane, observed through a bounded window. The window (which is specified in X as X$window) may have arbitrary shape.

The argument X is interpreted as a point pattern object (of class "ppp", see ppp.object) and can be supplied in any of the formats recognised by as.ppp().

The functions Fest and Gest are called to compute estimates of F(r) and G(r) respectively. These estimates are then combined by simply taking the ratio J(r) = (1-G(r))/(1-F(r)).

In fact three different estimates are computed using different edge corrections (Baddeley, 1998). The Kaplan-Meier estimate (returned as km) is the ratio J = (1-G)/(1-F) of the Kaplan-Meier estimates of 1-F and 1-G computed by Fest and Gest respectively. The reduced-sample or border corrected estimate (returned as rs) is the same ratio J = (1-G)/(1-F) of the border corrected estimates. These estimators are slightly biased for J, since they are ratios of approximately unbiased estimators. The logarithm of the Kaplan-Meier estimate is unbiased for log J.

The uncorrected estimate (returned as un) is the ratio J = (1-G)/(1-F) of the uncorrected (``raw'') estimates of the survival functions of F and G, which are the empirical distribution functions of the empty space distances Fest(X,...)$raw and of the nearest neighbour distances Gest(X,...)$raw. The uncorrected estimates of F and G are severely biased. However the uncorrected estimate of J is approximately unbiased (if the process is close to Poisson); it is insensitive to edge effects, and should be used when edge effects are severe (see Baddeley et al, 2000).

The algorithm for Fest uses two discrete approximations which are controlled by the parameter eps and by the spacing of values of r respectively. See Fest for details. First-time users are strongly advised not to specify these arguments.

Note that the value returned by Jest includes the output of Fest and Gest as attributes (see the last example below). If the user is intending to compute the F,G and J functions for the point pattern, it is only necessary to call Jest.

Value

An object of class "fv", see fv.object, which can be plotted directly using plot.fv.
Essentially a data frame containing

r | the vector of values of the argument r at which the function J has been estimated
J | the recommended estimate of J(r), which is the Kaplan-Meier estimate km
rs | the ``reduced sample'' or ``border correction'' estimator of J(r) computed from the border-corrected estimates of F and G
km | the spatial Kaplan-Meier estimator of J(r) computed from the Kaplan-Meier estimates of F and G
un | the uncorrected estimate of J(r) computed from the uncorrected estimates of F and G
theo | the theoretical value of J(r) for a stationary Poisson process: identically equal to 1
F | the output of Fest for this point pattern, containing three estimates of the empty space function F(r) and an estimate of its hazard function
G | the output of Gest for this point pattern, containing three estimates of the nearest neighbour distance distribution function G(r) and an estimate of its hazard function

Note

Sizeable amounts of memory may be needed during the calculation.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A.J. Spatial sampling and censoring. In O.E. Barndorff-Nielsen, W.S. Kendall and M.N.M. van Lieshout (eds) Stochastic Geometry: Likelihood and Computation. Chapman and Hall, 1998. Chapter 2, pages 37–78.

Baddeley, A.J. and Gill, R.D. The empty space hazard of a spatial pattern. Research Report 1994/3, Department of Mathematics, University of Western Australia, May 1994.

Baddeley, A.J. and Gill, R.D. Kaplan-Meier estimators of interpoint distance distributions for spatial point processes. Annals of Statistics 25 (1997) 263–292.

Baddeley, A., Kerscher, M., Schladitz, K. and Scott, B.T. Estimating the J function without edge correction. Statistica Neerlandica 54 (2000) 315–328.

Borgefors, G. Distance transformations in digital images. Computer Vision, Graphics and Image Processing 34 (1986) 344–371.

Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.

Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.

Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.

Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd edition. Springer Verlag, 1995.

Thonnes, E. and Van Lieshout, M.N.M, A comparative study on the power of Van Lieshout and Baddeley's J-function. Biometrical Journal 41 (1999) 721–734.

Van Lieshout, M.N.M. and Baddeley, A.J. A nonparametric measure of spatial interaction in point patterns. Statistica Neerlandica 50 (1996) 344–361.

See Also

Fest, Gest, Kest, km.rs, reduced.sample, kaplan.meier

Examples

   data(cells)
   J <- Jest(cells, 0.01)
   plot(J, main="cells data")
   # values are far above J= 1, indicating regular pattern

   data(redwood)
   J <- Jest(redwood, 0.01)
   plot(J, main="redwood data")
   # values are below J= 1, indicating clustered pattern


Marked J Function

Description

For a marked point pattern, estimate the multitype J function summarising dependence between the points in subset I and those in subset J.

Usage

  Jmulti(X, I, J, eps=NULL, r=NULL, breaks=NULL, ..., disjoint=NULL)

Arguments

X | The observed point pattern, from which an estimate of the multitype distance distribution function JIJ(r) will be computed. It must be a marked point pattern. See under Details.
I | Subset of points of X from which distances are measured.
J | Subset of points in X to which distances are measured.
eps | A positive number. The pixel resolution of the discrete approximation to Euclidean distance (see Jest). There is a sensible default.
r | numeric vector. The values of the argument r at which the distribution function JIJ(r) should be evaluated. There is a sensible default. First-time users are strongly advised not to specify this argument. See below for important conditions on r.
breaks | An alternative to the argument r. Not normally invoked by the user. See the Details section.
... | Ignored.
disjoint | Optional flag indicating whether the subsets I and J are disjoint. If missing, this value will be computed by inspecting the vectors I and J

.

Details

The function Jmulti generalises Jest (for unmarked point patterns) and Jdot and Jcross (for multitype point patterns) to arbitrary marked point patterns.

Suppose X[I], X[J] are subsets, possibly overlapping, of a marked point process. Define

JIJ(r) = (1 - GIJ(r))/(1 - FJ(r))

where FJ(r) is the cumulative distribution function of the distance from a fixed location to the nearest point of X[J], and GJ(r) is the distribution function of the distance from a typical point of X[I] to the nearest distinct point of X[J].

The argument X must be a point pattern (object of class "ppp") or any data that are acceptable to as.ppp.

The arguments I and J specify two subsets of the point pattern. They may be logical vectors of length equal to X$n, or integer vectors with entries in the range 1 to X$n, etc.

It is assumed that X can be treated as a realisation of a stationary (spatially homogeneous) random spatial point process in the plane, observed through a bounded window. The window (which is specified in X as X$window) may have arbitrary shape. Biases due to edge effects are treated in the same manner as in Jest.

The argument r is the vector of values for the distance r at which JIJ(r) should be evaluated. It is also used to determine the breakpoints (in the sense of hist) for the computation of histograms of distances. The reduced-sample and Kaplan-Meier estimators are computed from histogram counts. In the case of the Kaplan-Meier estimator this introduces a discretisation error which is controlled by the fineness of the breakpoints.

First-time users would be strongly advised not to specify r. However, if it is specified, r must satisfy r[1] = 0, and max(r) must be larger than the radius of the largest disc contained in the window. Furthermore, the successive entries of r must be finely spaced.

Value

An object of class "fv" (see fv.object).
Essentially a data frame containing six numeric columns

r | the values of the argument r at which the function JIJ(r) has been estimated
rs | the ``reduced sample'' or ``border correction'' estimator of JIJ(r)
km | the spatial Kaplan-Meier estimator of JIJ(r)
un | the uncorrected estimate of JIJ(r), formed by taking the ratio of uncorrected empirical estimators of 1 - GIJ(r) and 1 - FJ(r), see Gdot and Fest.
theo | the theoretical value of JIJ(r) for a marked Poisson process with the same estimated intensity, namely 1.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

See Also

Jcross, Jdot, Jest

Examples

    data(longleaf)
     # Longleaf Pine data: marks represent diameter

    Jm <- Jmulti(longleaf, longleaf$marks <= 15, longleaf$marks >= 25)
    plot(Jm)


Kaplan-Meier Estimator using Histogram Data

Description

Compute the Kaplan-Meier estimator of a survival time distribution function, from histogram data

Usage

  kaplan.meier(obs, nco, breaks, upperobs=0)

Arguments

obs | vector of n integers giving the histogram of all observations (censored or uncensored survival times)
nco | vector of n integers giving the histogram of uncensored observations (those survival times that are less than or equal to the censoring time)
breaks | Vector of n+1 breakpoints which were used to form both histograms.
upperobs | Number of observations beyond the rightmost breakpoint, if any.

Details

This function is needed mainly for internal use in spatstat, but may be useful in other applications where you want to form the Kaplan-Meier estimator from a huge dataset.

Suppose T[i] are the survival times of individuals i=1,...,M with unknown distribution function F(t) which we wish to estimate. Suppose these times are right-censored by random censoring times C[i]. Thus the observations consist of right-censored survival times T*[i] = min(T[i],C[i]) and non-censoring indicators D[i] = 1(T[i] <= C[i]) for each i.

If the number of observations M is large, it is efficient to use histograms. Form the histogram obs of all observed times T*[i]. That is, obs[k] counts the number of values T*[i] in the interval (breaks[k],breaks[k+1]] for k > 1 and [breaks[1],breaks[2]] for k = 1. Also form the histogram nco of all uncensored times, i.e. those T*[i] such that D[i]=1. These two histograms are the arguments passed to kaplan.meier.

The vectors km and lambda returned by kaplan.meier are (histogram approximations to) the Kaplan-Meier estimator of F(t) and its hazard rate lambda(t). Specifically, km[k] is an estimate of F(breaks[k+1]), and lambda[k] is an estimate of the average of lambda(t) over the interval (breaks[k],breaks[k+1]).

The histogram breaks must include 0. If the histogram breaks do not span the range of the observations, it is important to count how many survival times T*[i] exceed the rightmost breakpoint, and give this as the value upperobs.

Value

A list with two elements:

km | Kaplan-Meier estimate of the survival time c.d.f. F(t)
lambda | corresponding Nelson-Aalen estimate of the hazard rate lambda(t)

These are numeric vectors of length n.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

reduced.sample, km.rs


Multitype K Function (Cross-type)

Description

For a multitype point pattern, estimate the multitype K function which counts the expected number of points of type j within a given distance of a point of type i.

Usage

Kcross(X, i=1, j=2, r=NULL, breaks=NULL, correction, ...)

Arguments

X | The observed point pattern, from which an estimate of the cross type K function Kij(r) will be computed. It must be a multitype point pattern (a marked point pattern whose marks are a factor). See under Details.
i | Number or character string identifying the type (mark value) of the points in X from which distances are measured.
j | Number or character string identifying the type (mark value) of the points in X to which distances are measured.
r | numeric vector. The values of the argument r at which the distribution function Kij(r) should be evaluated. There is a sensible default. First-time users are strongly advised not to specify this argument. See below for important conditions on r.
breaks | An alternative to the argument r. Not normally invoked by the user. See the Details section.
correction | A character vector containing any selection of the options "border", "bord.modif", "isotropic", "Ripley" or "translate". It specifies the edge correction(s) to be applied.
... | Ignored.

Details

This function Kcross and its companions Kdot and Kmulti are generalisations of the function Kest to multitype point patterns.

A multitype point pattern is a spatial pattern of points classified into a finite number of possible ``colours'' or ``types''. In the spatstat package, a multitype pattern is represented as a single point pattern object in which the points carry marks, and the mark value attached to each point determines the type of that point.

The argument X must be a point pattern (object of class "ppp") or any data that are acceptable to as.ppp. It must be a marked point pattern, and the mark vector X$marks must be a factor. The arguments i and j will be interpreted as levels of the factor X$marks. (Warning: this means that an integer value i=3 will be interpreted as the 3rd smallest level, not the number 3).

The ``cross-type'' (type i to type j) K function of a stationary multitype point process X is defined so that lambda[j] Kij(r) equals the expected number of additional random points of type j within a distance r of a typical point of type i in the process X. Here lambda[j] is the intensity of the type j points, i.e. the expected number of points of type j per unit area. The function Kij is determined by the second order moment properties of X.

An estimate of Kij(r) is a useful summary statistic in exploratory data analysis of a multitype point pattern. If the process of type i points were independent of the process of type j points, then Kij(r) would equal pi * r^2. Deviations between the empirical Kij curve and the theoretical curve pi * r^2 may suggest dependence between the points of types i and j.

This algorithm estimates the distribution function Kij(r) from the point pattern X. It assumes that X can be treated as a realisation of a stationary (spatially homogeneous) random spatial point process in the plane, observed through a bounded window. The window (which is specified in X as X$window) may have arbitrary shape. Biases due to edge effects are treated in the same manner as in Kest, using the border correction.

The argument r is the vector of values for the distance r at which Kij(r) should be evaluated. The values of r must be increasing nonnegative numbers and the maximum r value must exceed the radius of the largest disc contained in the window.

The pair correlation function can also be applied to the result of Kcross; see pcf.

Value

An object of class "fv" (see fv.object).
Essentially a data frame containing numeric columns

r | the values of the argument r at which the function Kij(r) has been estimated
theo | the theoretical value of Kij(r) for a marked Poisson process, namely pi * r^2

together with a column or columns named "border", "bord.modif", "iso" and/or "trans", according to the selected edge corrections. These columns contain estimates of the function Kij(r) obtained by the edge corrections named.

Warnings

The arguments i and j are interpreted as levels of the factor X$marks. Beware of the usual trap with factors: numerical values are not interpreted in the same way as character values. See the first example.

The reduced sample estimator of Kij is pointwise approximately unbiased, but need not be a valid distribution function; it may not be a nondecreasing function of r. Its range is always within [0,1].

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.

Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.

Harkness, R.D and Isham, V. (1983) A bivariate spatial point pattern of ants' nests. Applied Statistics 32, 293–303

Lotwick, H. W. and Silverman, B. W. (1982). Methods for analysing spatial processes of several types of points. J. Royal Statist. Soc. Ser. B 44, 406–413.

Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.

Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd edition. Springer Verlag, 1995.

See Also

Kdot, Kest, Kmulti, pcf

Examples

    data(betacells)
     # cat retina data
    K01 <- Kcross(betacells, "off", "on")
    plot(K01)

    K10 <- Kcross(betacells, "on", "off")

    # synthetic example
    pp <- runifpoispp(50)
    pp <- pp %mark% factor(sample(0:1, pp$n, replace=TRUE))
    K <- Kcross(pp, "0", "1") # note: "0" not 0


Inhomogeneous Cross K Function

Description

For a multitype point pattern, estimate the inhomogeneous version of the cross K function, which counts the expected number of points of type j within a given distance of a point of type i, adjusted for spatially varying intensity.

Usage

Kcross.inhom(X, i=1, j=2, lambdaI, lambdaJ, ...,  r=NULL, breaks=NULL,
         correction = c("border", "isotropic", "Ripley", "translate") ,
lambdaIJ=NULL)

Arguments

X | The observed point pattern, from which an estimate of the inhomogeneous cross type K function Kij(r) will be computed. It must be a multitype point pattern (a marked point pattern whose marks are a factor). See under Details.
i | Number or character string identifying the type (mark value) of the points in X from which distances are measured.
j | Number or character string identifying the type (mark value) of the points in X to which distances are measured.
lambdaI | Values of the the estimated intensity of the sub-process of points of type i. Either a pixel image (object of class "im"), or a numeric vector containing the intensity values at each of the type i points in X.
lambdaJ | Values of the the estimated intensity of the sub-process of points of type j. Either a pixel image (object of class "im"), or a numeric vector containing the intensity values at each of the type j points in X.
r | Optional. Numeric vector giving the values of the argument r at which the cross K function Kij(r) should be evaluated. There is a sensible default. First-time users are strongly advised not to specify this argument. See below for important conditions on r.
breaks | Optional. An alternative to the argument r. Not normally invoked by the user. See the Details section.
correction | A character vector containing any selection of the options "border", "bord.modif", "isotropic", "Ripley" or "translate". It specifies the edge correction(s) to be applied.
... | Ignored.
lambdaIJ | Optional. A matrix containing estimates of the product of the intensities lambdaI and lambdaJ for each pair of points of types i and j respectively.

Details

This is a generalisation of the function Kcross to include an adjustment for spatially inhomogeneous intensity, in a manner similar to the function Kinhom.

The inhomogeneous cross-type K function is described by Moller and Waagepetersen (2003, pages 48-49 and 51-53).

Briefly, given a multitype point process, suppose the sub-process of points of type j has intensity function lambda[j](u) at spatial locations u. Suppose we place a mass of 1/lambda[j](z) at each point z of type j. Then the expected total mass per unit area is 1. The inhomogeneous ``cross-type'' K function K[ij]inhom(r) equals the expected total mass within a radius r of a point of the process of type i.

If the process of type i points were independent of the process of type j points, then K[ij]inhom(r) would equal pi * r^2. Deviations between the empirical Kij curve and the theoretical curve pi * r^2 suggest dependence between the points of types i and j.

The argument X must be a point pattern (object of class "ppp") or any data that are acceptable to as.ppp. It must be a marked point pattern, and the mark vector X$marks must be a factor.

The arguments i and j will be interpreted as levels of the factor X$marks. (Warning: this means that an integer value i=3 will be interpreted as the 3rd smallest level, not the number 3).

The argument lambdaI supplies the values of the intensity of the sub-process of points of type i. It may be either

a pixel image
(object of class "im") which gives the values of the type i intensity at all locations in the window containing X;
a numeric vector
containing the values of the type i intensity evaluated only at the data points of type i. The length of this vector must equal the number of type i points in X.

Similarly lambdaJ should contain estimated values of the intensity of the sub-process of points of type j. It may be either a pixel image or a numeric vector.

The optional argument lambdaIJ is for advanced use only. It is a matrix containing estimated values of the products of these two intensities for each pair of data points of types i and j respectively.

The argument r is the vector of values for the distance r at which Kij(r) should be evaluated. The values of r must be increasing nonnegative numbers and the maximum r value must exceed the radius of the largest disc contained in the window.

The argument correction chooses the edge correction as explained e.g. in Kest.

The pair correlation function can also be applied to the result of Kcross.inhom; see pcf.

Value

An object of class "fv" (see fv.object).
Essentially a data frame containing numeric columns

r | the values of the argument r at which the function Kij(r) has been estimated
theo | the theoretical value of Kij(r) for a marked Poisson process, namely pi * r^2

together with a column or columns named "border", "bord.modif", "iso" and/or "trans", according to the selected edge corrections. These columns contain estimates of the function Kij(r) obtained by the edge corrections named.

Warnings

The arguments i and j are interpreted as levels of the factor X$marks. Beware of the usual trap with factors: numerical values are not interpreted in the same way as character values.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Moller, J. and Waagepetersen, R. Statistical Inference and Simulation for Spatial Point Processes Chapman and Hall/CRC Boca Raton, 2003.

See Also

Kcross, Kinhom, pcf

Examples

    # Lansing Woods data
    data(lansing)
    lansing <- lansing[seq(1,lansing$n, by=10)]
    ma <- split(lansing)$maple
    wh <- split(lansing)$whiteoak

    # method (1): estimate intensities by nonparametric smoothing
    lambdaM <- density.ppp(ma, sigma=0.15)
    lambdaW <- density.ppp(wh, sigma=0.15)
    K <- Kcross.inhom(lansing, "whiteoak", "maple", lambdaW[wh], lambdaM[ma])
    K <- Kcross.inhom(lansing, "whiteoak", "maple", lambdaW,     lambdaM)

    # method (2): fit parametric intensity model
    fit <- ppm(lansing, ~marks * polynom(x,y,2))
    # evaluate fitted intensities at data points
    # (these are the intensities of the sub-processes of each type)
    inten <- fitted(fit, dataonly=TRUE)
    # split according to types of points
    lambda <- split(inten, lansing$marks)
    K <- Kcross.inhom(lansing, "whiteoak", "maple",
              lambda$whiteoak, lambda$maple)

    # synthetic example: type A points have intensity 50,
    #                    type B points have intensity 100 * x
    lamB <- as.im(function(x,y){50 + 100 * x}, owin())
    X <- superimpose(A=runifpoispp(50), B=rpoispp(lamB))
    XA <- split(X)$A
    XB <- split(X)$B
    K <- Kcross.inhom(X, "A", "B",
        lambdaI=rep(50, XA$n), lambdaJ=lamB[XB])
    K <- Kcross.inhom(X, "A", "B",
        lambdaI=as.im(50, X$window), lambdaJ=lamB)


Multitype K Function (i-to-any)

Description

For a multitype point pattern, estimate the multitype K function which counts the expected number of other points of the process within a given distance of a point of type i.

Usage

Kdot(X, i=1, r=NULL, breaks=NULL, correction, ...)

Arguments

X | The observed point pattern, from which an estimate of the multitype K function Ki.(r) will be computed. It must be a multitype point pattern (a marked point pattern whose marks are a factor). See under Details.
i | Number or character string identifying the type (mark value) of the points in X from which distances are measured.
r | numeric vector. The values of the argument r at which the distribution function Ki.(r) should be evaluated. There is a sensible default. First-time users are strongly advised not to specify this argument. See below for important conditions on r.
breaks | An alternative to the argument r. Not normally invoked by the user. See the Details section.
correction | A character vector containing any selection of the options "border", "bord.modif", "isotropic", "Ripley" or "translate". It specifies the edge correction(s) to be applied.
... | Ignored.

Details

This function Kdot and its companions Kcross and Kmulti are generalisations of the function Kest to multitype point patterns.

A multitype point pattern is a spatial pattern of points classified into a finite number of possible ``colours'' or ``types''. In the spatstat package, a multitype pattern is represented as a single point pattern object in which the points carry marks, and the mark value attached to each point determines the type of that point.

The argument X must be a point pattern (object of class "ppp") or any data that are acceptable to as.ppp. It must be a marked point pattern, and the mark vector X$marks must be a factor. The argument i will be interpreted as a level of the factor X$marks. (Warning: this means that an integer value i=3 will be interpreted as the 3rd smallest level, not the number 3).

The ``type i to any type'' multitype K function of a stationary multitype point process X is defined so that lambda Ki.(r) equals the expected number of additional random points within a distance r of a typical point of type i in the process X. Here lambda is the intensity of the process, i.e. the expected number of points of X per unit area. The function Ki. is determined by the second order moment properties of X.

An estimate of Ki.(r) is a useful summary statistic in exploratory data analysis of a multitype point pattern. If the subprocess of type i points were independent of the subprocess of points of all types not equal to i, then Ki.(r) would equal pi * r^2. Deviations between the empirical Ki. curve and the theoretical curve pi * r^2 may suggest dependence between types.

This algorithm estimates the distribution function Ki.(r) from the point pattern X. It assumes that X can be treated as a realisation of a stationary (spatially homogeneous) random spatial point process in the plane, observed through a bounded window. The window (which is specified in X as X$window) may have arbitrary shape. Biases due to edge effects are treated in the same manner as in Kest, using the border correction.

The argument r is the vector of values for the distance r at which Ki.(r) should be evaluated. The values of r must be increasing nonnegative numbers and the maximum r value must exceed the radius of the largest disc contained in the window.

The pair correlation function can also be applied to the result of Kdot; see pcf.

Value

An object of class "fv" (see fv.object).
Essentially a data frame containing numeric columns

r | the values of the argument r at which the function Ki.(r) has been estimated
theo | the theoretical value of Ki.(r) for a marked Poisson process, namely pi * r^2

together with a column or columns named "border", "bord.modif", "iso" and/or "trans", according to the selected edge corrections. These columns contain estimates of the function Ki.(r) obtained by the edge corrections named.

Warnings

The argument i is interpreted as a level of the factor X$marks. Beware of the usual trap with factors: numerical values are not interpreted in the same way as character values. See the first example.

The reduced sample estimator of Ki. is pointwise approximately unbiased, but need not be a valid distribution function; it may not be a nondecreasing function of r. Its range is always within [0,1].

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.

Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.

Harkness, R.D and Isham, V. (1983) A bivariate spatial point pattern of ants' nests. Applied Statistics 32, 293–303

Lotwick, H. W. and Silverman, B. W. (1982). Methods for analysing spatial processes of several types of points. J. Royal Statist. Soc. Ser. B 44, 406–413.

Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.

Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd edition. Springer Verlag, 1995.

See Also

Kdot, Kest, Kmulti, pcf

Examples

     # Lansing woods data: 6 types of trees
    data(lansing)

    ## Not run:
    Kh. <- Kdot(lansing, "hickory")

## End(Not run)

    # diagnostic plot for independence between hickories and other trees
    plot(Kh.)

    # synthetic example with two marks "a" and "b"
    pp <- runifpoispp(50)
    pp <- pp %mark% sample(c("a","b"), pp$n, replace=TRUE)
    K <- Kdot(pp, "a")


Inhomogeneous Multitype K Dot Function

Description

For a multitype point pattern, estimate the inhomogeneous version of the dot K function, which counts the expected number of points of any type within a given distance of a point of type i, adjusted for spatially varying intensity.

Usage

Kdot.inhom(X, i=1, lambdaI, lambdadot, ..., r=NULL, breaks=NULL,
         correction = c("border", "isotropic", "Ripley", "translate") ,
         lambdaIdot=NULL)

Arguments

X | The observed point pattern, from which an estimate of the inhomogeneous cross type K function Ki.(r) will be computed. It must be a multitype point pattern (a marked point pattern whose marks are a factor). See under Details.
i | Number or character string identifying the type (mark value) of the points in X from which distances are measured.
lambdaI | Values of the the estimated intensity of the sub-process of points of type i. Either a pixel image (object of class "im"), or a numeric vector containing the type i intensity values at each of the type i points in X.
lambdadot | Values of the the estimated intensity of the entire point process, Either a pixel image (object of class "im"), or a numeric vector containing the intensity values at each point in X.
... | Ignored.
r | Optional. Numeric vector giving the values of the argument r at which the cross K function Kij(r) should be evaluated. There is a sensible default. First-time users are strongly advised not to specify this argument. See below for important conditions on r.
breaks | Optional. An alternative to the argument r. Not normally invoked by the user. See the Details section.
correction | A character vector containing any selection of the options "border", "bord.modif", "isotropic", "Ripley" or "translate". It specifies the edge correction(s) to be applied.
lambdaIdot | Optional. A matrix containing estimates of the product of the intensities lambdaI and lambdadot for each pair of points, the first point of type i and the second of any type.

Details

This is a generalisation of the function Kdot to include an adjustment for spatially inhomogeneous intensity, in a manner similar to the function Kinhom.

Briefly, given a multitype point process, consider the points without their types, and suppose this unmarked point process has intensity function lambda(u) at spatial locations u. Suppose we place a mass of 1/lambda(z) at each point z of the process. Then the expected total mass per unit area is 1. The inhomogeneous ``dot-type'' K function K[i.]inhom(r) equals the expected total mass within a radius r of a point of the process of type i, discounting this point itself.

If the process of type i points were independent of the points of other types, then K[i.]inhom(r) would equal pi * r^2. Deviations between the empirical Ki. curve and the theoretical curve pi * r^2 suggest dependence between the points of types i and j for j != i.

The argument X must be a point pattern (object of class "ppp") or any data that are acceptable to as.ppp. It must be a marked point pattern, and the mark vector X$marks must be a factor.

The arguments i and j will be interpreted as levels of the factor X$marks. (Warning: this means that an integer value i=3 will be interpreted as the 3rd smallest level, not the number 3).

The argument lambdaI supplies the values of the intensity of the sub-process of points of type i. It may be either

a pixel image
(object of class "im") which gives the values of the type i intensity at all locations in the window containing X;
a numeric vector
containing the values of the type i intensity evaluated only at the data points of type i. The length of this vector must equal the number of type i points in X.

The argument lambdadot should contain estimated values of the intensity of the entire point process. It may be either a pixel image, or a numeric vector of length equal to the number of points in X.

For advanced use only, the optional argument lambdaIdot is a matrix containing estimated values of the products of these two intensities for each pair of points, the first point of type i and the second of any type.

The argument r is the vector of values for the distance r at which Ki.(r) should be evaluated. The values of r must be increasing nonnegative numbers and the maximum r value must exceed the radius of the largest disc contained in the window.

The argument correction chooses the edge correction as explained e.g. in Kest.

The pair correlation function can also be applied to the result of Kcross.inhom; see pcf.

Value

An object of class "fv" (see fv.object).
Essentially a data frame containing numeric columns

r | the values of the argument r at which the function Ki.(r) has been estimated
theo | the theoretical value of Ki.(r) for a marked Poisson process, namely pi * r^2

together with a column or columns named "border", "bord.modif", "iso" and/or "trans", according to the selected edge corrections. These columns contain estimates of the function Ki.(r) obtained by the edge corrections named.

Warnings

The argument i is interpreted as a level of the factor X$marks. Beware of the usual trap with factors: numerical values are not interpreted in the same way as character values.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Moller, J. and Waagepetersen, R. Statistical Inference and Simulation for Spatial Point Processes Chapman and Hall/CRC Boca Raton, 2003.

See Also

Kdot, Kinhom, Kcross.inhom, pcf

Examples

    # Lansing Woods data
    data(lansing)
    lansing <- lansing[seq(1,lansing$n, by=10)]
    ma <- split(lansing)$maple
    lg <- unmark(lansing)

    # Estimate intensities by nonparametric smoothing
    lambdaM <- density.ppp(ma, sigma=0.15)
    lambdadot <- density.ppp(lg, sigma=0.15)
    K <- Kdot.inhom(lansing, "maple", lambdaI=lambdaM[ma],
                                      lambdadot=lambdadot[lg])
    K <- Kdot.inhom(lansing, "maple", lambdaI=lambdaM,
                                      lambdadot=lambdadot)

    # synthetic example: type A points have intensity 50,
    #                    type B points have intensity 50 + 100 * x
    lamB <- as.im(function(x,y){50 + 100 * x}, owin())
    lamdot <- as.im(function(x,y) { 100 + 100 * x}, owin())
    X <- superimpose(A=runifpoispp(50), B=rpoispp(lamB))
    XB <- split(X)$B
    K <- Kdot.inhom(X, "B",  lambdaI=lamB[XB], lambdadot=lamdot[X])
    K <- Kdot.inhom(X, "B",  lambdaI=lamB,     lambdadot=lamdot)


K-function

Description

Estimates the reduced second moment function K(r) from a point pattern in a window of arbitrary shape.

Usage

  Kest(X, ..., r=NULL, breaks=NULL,
     correction=c("border", "isotropic", "Ripley", "translate"),
    nlarge=3000)

Arguments

X | The observed point pattern, from which an estimate of K(r) will be computed. An object of class "ppp", or data in any format acceptable to as.ppp().
... | Ignored.
r | Optional. Vector of values for the argument r at which K(r) should be evaluated. There is a sensible default.
breaks | Optional. An alternative to the argument r. Not normally invoked by the user. See the Details section.
correction | Optional. A character vector containing any selection of the options "none", "border", "bord.modif", "isotropic", "Ripley" or "translate". It specifies the edge correction(s) to be applied.
nlarge | Optional. Efficiency threshold. If the number of points exceeds nlarge, then only the border correction will be computed, using a fast algorithm.

Details

The K function (variously called ``Ripley's K-function'' and the ``reduced second moment function'') of a stationary point process X is defined so that lambda K(r) equals the expected number of additional random points within a distance r of a typical random point of X. Here lambda is the intensity of the process, i.e. the expected number of points of X per unit area. The K function is determined by the second order moment properties of X.

An estimate of K derived from a spatial point pattern dataset can be used in exploratory data analysis and formal inference about the pattern (Cressie, 1991; Diggle, 1983; Ripley, 1988). In exploratory analyses, the estimate of K is a useful statistic summarising aspects of inter-point ``dependence'' and ``clustering''. For inferential purposes, the estimate of K is usually compared to the true value of K for a completely random (Poisson) point process, which is K(r) = pi * r^2. Deviations between the empirical and theoretical K curves may suggest spatial clustering or spatial regularity.

This routine Kest estimates the K function of a stationary point process, given observation of the process inside a known, bounded window. The argument X is interpreted as a point pattern object (of class "ppp", see ppp.object) and can be supplied in any of the formats recognised by as.ppp().

The estimation of K is hampered by edge effects arising from the unobservability of points of the random pattern outside the window. An edge correction is needed to reduce bias (Baddeley, 1998; Ripley, 1988). The corrections implemented here are

border
the border method or ``reduced sample'' estimator (see Ripley, 1988). This is the least efficient (statistically) and the fastest to compute. It can be computed for a window of arbitrary shape.
isotropic/Ripley
Ripley's isotropic correction (see Ripley, 1988; Ohser, 1983). This is implemented for rectangular and polygonal windows (not for binary masks).
translate
Translation correction (Ohser, 1983). Implemented for all window geometries, but slow for complex windows.

Note that the estimator assumes the process is stationary (spatially homogeneous). For inhomogeneous point patterns, see Kinhom.

If the point pattern X contains more than about 3000 points, the isotropic and translation edge corrections can be computationally prohibitive. The computations for the border method are much faster, and are statistically efficient when there are large numbers of points. Accordingly, if the number of points in X exceeds the threshold nlarge, then only the border correction will be computed. Setting nlarge=Inf will prevent this from happening. Setting nlarge=0 is equivalent to selecting only the border correction with correction="border".

For instructional purposes, you can also set correction="none" to compute an estimate of the K function without edge correction. This estimate is biased and should not be used for data analysis.

The estimator Kest ignores marks. Its counterparts for multitype point patterns are Kcross, Kdot, and for general marked point patterns see Kmulti.

Some writers, particularly Stoyan (1994, 1995) advocate the use of the ``pair correlation function''

g(r) = K'(r)/ ( 2 * pi * r)

where K'(r) is the derivative of K(r). See pcf on how to estimate this function.

Value

An object of class "fv", see fv.object, which can be plotted directly using plot.fv.
Essentially a data frame containing columns

r | the vector of values of the argument r at which the function K has been estimated
theo | the theoretical value K(r) = pi * r^2 for a stationary Poisson process

together with columns named "border", "bord.modif", "iso" and/or "trans", according to the selected edge corrections. These columns contain estimates of the function K(r) obtained by the edge corrections named.

Warnings

The estimator of K(r) is approximately unbiased for each fixed r. Bias increases with r and depends on the window geometry. For a rectangular window it is prudent to restrict the r values to a maximum of 1/4 of the smaller side length of the rectangle. Bias may become appreciable for point patterns consisting of fewer than 15 points.

While K(r) is always a non-decreasing function, the estimator of K is not guaranteed to be non-decreasing. This is rarely a problem in practice.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A.J. Spatial sampling and censoring. In O.E. Barndorff-Nielsen, W.S. Kendall and M.N.M. van Lieshout (eds) Stochastic Geometry: Likelihood and Computation. Chapman and Hall, 1998. Chapter 2, pages 37–78.

Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.

Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.

Ohser, J. (1983) On estimators for the reduced second moment measure of point processes. Mathematische Operationsforschung und Statistik, series Statistics, 14, 63 – 71.

Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.

Stoyan, D, Kendall, W.S. and Mecke, J. (1995) Stochastic geometry and its applications. 2nd edition. Springer Verlag.

Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of geometrical statistics. John Wiley and Sons.

See Also

Fest, Gest, Jest, pcf, reduced.sample, Kcross, Kdot, Kinhom, Kmulti

Examples

 pp <- runifpoint(50)
 K <- Kest(pp)
 data(cells)
 K <- Kest(cells, correction="isotropic")
 plot(K)
 plot(K, main="K function for cells")
 # plot the L function
 plot(K, sqrt(iso/pi) ~ r)
 plot(K, sqrt(./pi) ~ r, ylab="L(r)", main="L function for cells")


K-function using FFT

Description

Estimates the reduced second moment function K(r) from a point pattern in a window of arbitrary shape, using the Fast Fourier Transform.

Usage

  Kest.fft(X, sigma, r=NULL, breaks=NULL)

Arguments

X | The observed point pattern, from which an estimate of K(r) will be computed. An object of class "ppp", or data in any format acceptable to as.ppp().
sigma | standard deviation of the isotropic Gaussian smoothing kernel.
r | vector of values for the argument r at which K(r) should be evaluated. There is a sensible default.
breaks | An alternative to the argument r. Not normally invoked by the user. See Details.

Details

This is an alternative to the function Kest for estimating the K function. It may be useful for very large patterns of points.

Whereas Kest computes the distance between each pair of points analytically, this function discretises the point pattern onto a rectangular pixel raster and applies Fast Fourier Transform techniques to estimate K(t). The hard work is done by the function Kmeasure.

The result is an approximation whose accuracy depends on the resolution of the pixel raster. The resolution is controlled by setting the parameter npixel in spatstat.options.

Value

An object of class "fv" (see fv.object).
Essentially a data frame containing columns

r | the vector of values of the argument r at which the function K has been estimated
border | the estimates of K(r) for these values of r
theo | the theoretical value K(r) = pi * r^2 for a stationary Poisson process

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.

Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.

Ohser, J. (1983) On estimators for the reduced second moment measure of point processes. Mathematische Operationsforschung und Statistik, series Statistics, 14, 63 – 71.

Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.

Stoyan, D, Kendall, W.S. and Mecke, J. (1995) Stochastic geometry and its applications. 2nd edition. Springer Verlag.

Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of geometrical statistics. John Wiley and Sons.

See Also

Kest, Kmeasure, spatstat.options

Examples

 pp <- runifpoint(10000)
 ## Not run:
 spatstat.options(npixel=512)

## End(Not run)

 Kpp <- Kest.fft(pp, 0.01)
 plot(Kpp)


Inhomogeneous K-function

Description

Estimates the inhomogeneous K function of a non-stationary point pattern.

Usage

  Kinhom(X, lambda, ..., r = NULL, breaks = NULL,
    correction=c("border", "bord.modif", "isotropic", "translate"),
    nlarge = 1000, lambda2, sigma=NULL, varcov=NULL)

Arguments

X | The observed data point pattern, from which an estimate of the inhomogeneous K function will be computed. An object of class "ppp" or in a format recognised by as.ppp()
lambda | Optional. Values of the estimated intensity function. Either a vector giving the intensity values at the points of the pattern X, or a pixel image (object of class "im") giving the intensity values at all locations.
... | Extra arguments. Ignored if lambda is present. Passed to density.ppp if lambda is omitted.
r | vector of values for the argument r at which the inhomogeneous K function should be evaluated. Not normally given by the user; there is a sensible default.
breaks | An alternative to the argument r. Not normally invoked by the user. See Details.
correction | A character vector containing any selection of the options "border", "bord.modif", "isotropic", "Ripley" or "translate". It specifies the edge correction(s) to be applied.
nlarge | Optional. Efficiency threshold. If the number of points exceeds nlarge, then only the border correction will be computed, using a fast algorithm.
lambda2 | Advanced use only. Matrix containing estimates of the products lambda(x[i]) * lambda(x[j]) of the intensities at each pair of data points x[i] and x[j].
sigma,varcov | Optional arguments passed to density.ppp to control the smoothing bandwidth, when lambda is estimated by kernel smoothing.

Details

This computes a generalisation of the K function for inhomogeneous point patterns, proposed by Baddeley, Moller and Waagepetersen (2000).

The ``ordinary'' K function (variously known as the reduced second order moment function and Ripley's K function), is described under Kest. It is defined only for stationary point processes.

The inhomogeneous K function Kinhom(r) is a direct generalisation to nonstationary point processes. Suppose x is a point process with non-constant intensity lambda(u) at each location u. Define Kinhom(r) to be the expected value, given that u is a point of x, of the sum of all terms 1/lambda(u)lambda(x[j]) over all points x[j] in the process separated from u by a distance less than r. This reduces to the ordinary K function if lambda() is constant. If x is an inhomogeneous Poisson process with intensity function lambda(u), then Kinhom(r) = pi * r^2.

This allows us to inspect a point pattern for evidence of interpoint interactions after allowing for spatial inhomogeneity of the pattern. Values Kinhom(r) > pi * r^2 are suggestive of clustering.

The argument lambda should supply the (estimated) values of the intensity function lambda. It may be either

a numeric vector
containing the values of the intensity function at the points of the pattern X.
a pixel image
(object of class "im") assumed to contain the values of the intensity function at all locations in the window.
omitted:
if lambda is omitted, then it will be estimated using a `leave-one-out' kernel smoother.

If lambda is a numeric vector, then its length should be equal to the number of points in the pattern X. The value lambda[i] is assumed to be the the (estimated) value of the intensity lambda(x[i]) for the point x[i] of the pattern X. Each value must be a positive number; NA's are not allowed.

If lambda is a pixel image, the domain of the image should cover the entire window of the point pattern. If it does not (which may occur through discretisation error), then the point pattern will be trimmed to a smaller region where the lambda values are defined. (A warning will be issued in this case.)

If lambda is omitted, then it will be estimated using a `leave-one-out' kernel smoother, as described in Baddeley, Moller and Waagepetersen (2000). The estimate lambda[i] for the point X[i] is computed by removing X[i] from the point pattern, applying kernel smoothing to the remaining points using density.ppp, and evaluating the smoothed intensity at the point X[i]. The smoothing kernel bandwidth is controlled by the arguments sigma and varcov, which are passed to density.ppp along with any extra arguments.

Edge corrections are used to correct bias in the estimation of Kinhom. Each edge-corrected estimate of Kinhom(r) is of the form

K^inhom(r)= sum[i] sum[j] 1(d[i,j] <= r) * e(x[i],x[j],r)/(lambda(x[i]) * lambda(x[j]))

where d[i,j] is the distance between points x[i] and x[j], and e(x[i],x[j],r) is an edge correction factor. For the `border' correction,

1(b[i] > r)/(sum[j] 1(b[j] > r)/lambda(x[j]))

where b[i] is the distance from x[i] to the boundary of the window. For the `modified border' correction,

1(b[i] > r)/area(W [-] r)

where W [-] r is the eroded window obtained by trimming a margin of width r from the border of the original window. For the `translation' correction,

1/area(W intersect (W + x[j]-x[i]))

and for the `isotropic' correction,

1/(area(W) g(x[i],x[j]))

where g(x[i],x[j]) is the fraction of the circumference of the circle with centre x[i] and radius ||x[i]-x[j]|| which lies inside the window.

If the point pattern X contains more than about 1000 points, the isotropic and translation edge corrections can be computationally prohibitive. The computations for the border method are much faster, and are statistically efficient when there are large numbers of points. Accordingly, if the number of points in X exceeds the threshold nlarge, then only the border correction will be computed. Setting nlarge=Inf will prevent this from happening. Setting nlarge=0 is equivalent to selecting only the border correction with correction="border".

The pair correlation function can also be applied to the result of Kinhom; see pcf.

Value

An object of class "fv" (see fv.object).
Essentially a data frame containing at least the following columns,

r | the vector of values of the argument r at which the pair correlation function g(r) has been estimated
theo | vector of values of pi * r^2, the theoretical value of Kinhom(r) for an inhomogeneous Poisson process

and containing additional columns according to the choice specified in the correction argument. The additional columns are named border, trans and iso and give the estimated values of Kinhom(r) using the border correction, translation correction, and Ripley isotropic correction, respectively.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A., Moller, J. and Waagepetersen, R. (2000) Non- and semiparametric estimation of interaction in inhomogeneous point patterns. Statistica Neerlandica 54, 329–350.

See Also

Kest, pcf

Examples

  data(lansing)
  # inhomogeneous pattern of maples
  X <- unmark(split(lansing)$maple)

  # (1) intensity function estimated by model-fitting
  # Fit spatial trend: polynomial in x and y coordinates
  fit <- ppm(X, ~ polynom(x,y,2), Poisson())
  # (a) predict intensity values at points themselves,
  #     obtaining a vector of lambda values
  lambda <- predict(fit, locations=X, type="trend")
  # inhomogeneous K function
  Ki <- Kinhom(X, lambda)
  plot(Ki)
  # (b) predict intensity at all locations,
  #     obtaining a pixel image
  lambda <- predict(fit, type="trend")
  Ki <- Kinhom(X, lambda)
  plot(Ki)

  # (2) intensity function estimated by heavy smoothing
  Ki <- Kinhom(X, sigma=0.1)
  plot(Ki)

  # (3) simulated data: known intensity function
  lamfun <- function(x,y) { 50 + 100 * x }
  # inhomogeneous Poisson process
  Y <- rpoispp(lamfun, 150, owin())
  # evaluate intensity at points of pattern
  lambda <- lamfun(Y$x, Y$y)
  # inhomogeneous K function
  Ki <- Kinhom(Y, lambda)
  plot(Ki)

  # How to make simulation envelopes:
  #      Example shows method (2)
  ## Not run:
  smo <- density.ppp(X, sigma=0.1)
  Ken <- envelope(X, Kinhom, nsim=99,
                  simulate=expression(rpoispp(smo)),
                  sigma=0.1, correction="trans")
  plot(Ken)

## End(Not run)


Kaplan-Meier and Reduced Sample Estimator using Histograms

Description

Compute the Kaplan-Meier and Reduced Sample estimators of a survival time distribution function, using histogram techniques

Usage

  km.rs(o, cc, d, breaks)

Arguments

o | vector of observed survival times
cc | vector of censoring times
d | vector of non-censoring indicators
breaks | Vector of breakpoints to be used to form histograms.

Details

This function is needed mainly for internal use in spatstat, but may be useful in other applications where you want to form the Kaplan-Meier estimator from a huge dataset.

Suppose T[i] are the survival times of individuals i=1,...,M with unknown distribution function F(t) which we wish to estimate. Suppose these times are right-censored by random censoring times C[i]. Thus the observations consist of right-censored survival times T*[i] = min(T[i],C[i]) and non-censoring indicators D[i] = 1(T[i] <= C[i]) for each i.

The arguments to this function are vectors o, cc, d of observed values of T*[i], C[i] and D[i] respectively. The function computes histograms and forms the reduced-sample and Kaplan-Meier estimates of F(t) by invoking the functions kaplan.meier and reduced.sample. This is efficient if the lengths of o, cc, d (i.e. the number of observations) is large.

The vectors km and hazard returned by kaplan.meier are (histogram approximations to) the Kaplan-Meier estimator of F(t) and its hazard rate lambda(t). Specifically, km[k] is an estimate of F(breaks[k+1]), and lambda[k] is an estimate of the average of lambda(t) over the interval (breaks[k],breaks[k+1]). This approximation is exact only if the survival times are discrete and the histogram breaks are fine enough to ensure that each interval (breaks[k],breaks[k+1]) contains only one possible value of the survival time.

The vector rs is the reduced-sample estimator, rs[k] being the reduced sample estimate of F(breaks[k+1]). This value is exact, i.e. the use of histograms does not introduce any approximation error in the reduced-sample estimator.

Value

A list with five elements

rs | Reduced-sample estimate of the survival time c.d.f. F(t)
km | Kaplan-Meier estimate of the survival time c.d.f. F(t)
hazard | corresponding Nelson-Aalen estimate of the hazard rate lambda(t)
r | values of t for which F(t) is estimated
breaks | the breakpoints vector

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

reduced.sample, kaplan.meier


Reduced Second Moment Measure

Description

Estimates the reduced second moment measure Kappa from a point pattern in a window of arbitrary shape.

Usage

  Kmeasure(X, sigma, edge=TRUE, ..., varcov=NULL)

Arguments

X | The observed point pattern, from which an estimate of Kappa will be computed. An object of class "ppp", or data in any format acceptable to as.ppp().
sigma | Standard deviation sigma of the Gaussian smoothing kernel. Incompatible with varcov.
edge | logical value indicating whether an edge correction should be applied.
... | Ignored.
varcov | Variance-covariance matrix of the Gaussian smoothing kernel. Incompatible with sigma.

Details

The reduced second moment measure Kappa of a stationary point process X is defined so that, for a `typical' point x of the process, the expected number of other points y of the process such that the vector y - x lies in a region A, equals lambda Kappa(A). Here lambda is the intensity of the process, i.e. the expected number of points of X per unit area.

The more familiar K-function K(t) is just the value of the reduced second moment measure for each disc centred at the origin; that is, K(t) = Kappa(b(0,t)).

An estimate of Kappa derived from a spatial point pattern dataset can be useful in exploratory data analysis. Its advantage over the K-function is that it is also sensitive to anisotropy and directional effects.

This function computes an estimate of Kappa from a point pattern dataset X, which is assumed to be a realisation of a stationary point process, observed inside a known, bounded window. Marks are ignored.

The algorithm approximates the point pattern and its window by binary pixel images, introduces a Gaussian smoothing kernel and uses the Fast Fourier Transform fft to form a density estimate of Kappa. The calculation corresponds to the edge correction known as the ``translation correction''.

The Gaussian smoothing kernel may be specified by either of the arguments sigma or varcov. If sigma is a single number, this specifies an isotropic Gaussian kernel with standard deviation sigma on each coordinate axis. If sigma is a vector of two numbers, this specifies a Gaussian kernel with standard deviation sigma[1] on the x axis, standard deviation sigma[2] on the y axis, and zero correlation between the x and y axes. If varcov is given, this specifies the variance-covariance matrix of the Gaussian kernel. There do not seem to be any well-established rules for selecting the smoothing kernel in this context.

The density estimate of Kappa is returned in the form of a real-valued pixel image. Pixel values are estimates of the integral of the second moment density over the pixel. (The uniform Poisson process would have values identically equal to a where a is the area of a pixel.) Sums of pixel values over a desired region A are estimates of the value of Kappa(A). The image x and y coordinates are on the same scale as vector displacements in the original point pattern window. The point x=0, y=0 corresponds to the `typical point'. A peak in the image near (0,0) suggests clustering; a dip in the image near (0,0) suggests inhibition; peaks or dips at other positions suggest possible periodicity.

Value

A real-valued pixel image (an object of class "im", see im.object) whose pixel values are estimates of the value of the reduced second moment measure for each pixel (i.e. estimates of the integral of the second moment density over each pixel).

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Stoyan, D, Kendall, W.S. and Mecke, J. (1995) Stochastic geometry and its applications. 2nd edition. Springer Verlag.

Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of geometrical statistics. John Wiley and Sons.

See Also

Kest, spatstat.options, im.object

Examples

 data(cells)
 image(Kmeasure(cells, 0.05))
 # shows pronounced dip around origin consistent with strong inhibition
 data(redwood)
 image(Kmeasure(redwood, 0.03), col=grey(seq(1,0,length=32)))
 # shows peaks at several places, reflecting clustering and ?periodicity


Marked K-Function

Description

For a marked point pattern, estimate the multitype K function which counts the expected number of points of subset J within a given distance from a typical point in subset I.

Usage

Kmulti(X, I, J, r=NULL, breaks=NULL, correction, ...)

Arguments

X | The observed point pattern, from which an estimate of the multitype K function KIJ(r) will be computed. It must be a marked point pattern. See under Details.
I | Subset index specifying the points of X from which distances are measured.
J | Subset index specifying the points in X to which distances are measured.
r | numeric vector. The values of the argument r at which the multitype K function KIJ(r) should be evaluated. There is a sensible default. First-time users are strongly advised not to specify this argument. See below for important conditions on r.
breaks | An alternative to the argument r. Not normally invoked by the user. See the Details section.
correction | A character vector containing any selection of the options "border", "bord.modif", "isotropic", "Ripley" or "translate". It specifies the edge correction(s) to be applied.
... | Ignored.

Details

The function Kmulti generalises Kest (for unmarked point patterns) and Kdot and Kcross (for multitype point patterns) to arbitrary marked point patterns.

Suppose X[I], X[J] are subsets, possibly overlapping, of a marked point process. The multitype K function is defined so that lambda[J] KIJ(r) equals the expected number of additional random points of X[J] within a distance r of a typical point of X[I]. Here lambda[J] is the intensity of X[J] i.e. the expected number of points of X[J] per unit area. The function KIJ is determined by the second order moment properties of X.

The argument X must be a point pattern (object of class "ppp") or any data that are acceptable to as.ppp.

The arguments I and J specify two subsets of the point pattern. They may be logical vectors of length equal to X$n, or integer vectors with entries in the range 1 to X$n, etc.

The argument r is the vector of values for the distance r at which KIJ(r) should be evaluated. It is also used to determine the breakpoints (in the sense of hist) for the computation of histograms of distances.

First-time users would be strongly advised not to specify r. However, if it is specified, r must satisfy r[1] = 0, and max(r) must be larger than the radius of the largest disc contained in the window.

This algorithm assumes that X can be treated as a realisation of a stationary (spatially homogeneous) random spatial point process in the plane, observed through a bounded window. The window (which is specified in X as X$window) may have arbitrary shape.

Biases due to edge effects are treated in the same manner as in Kest. The edge corrections implemented here are

border
the border method or ``reduced sample'' estimator (see Ripley, 1988). This is the least efficient (statistically) and the fastest to compute. It can be computed for a window of arbitrary shape.
isotropic/Ripley
Ripley's isotropic correction (see Ripley, 1988; Ohser, 1983). This is currently implemented only for rectangular windows.
translate
Translation correction (Ohser, 1983). Implemented for all window geometries.

The pair correlation function pcf can also be applied to the result of Kmulti.

Value

An object of class "fv" (see fv.object).
Essentially a data frame containing numeric columns

r | the values of the argument r at which the function KIJ(r) has been estimated
theo | the theoretical value of KIJ(r) for a marked Poisson process, namely pi * r^2

together with a column or columns named "border", "bord.modif", "iso" and/or "trans", according to the selected edge corrections. These columns contain estimates of the function KIJ(r) obtained by the edge corrections named.

Warnings

The function KIJ is not necessarily differentiable.

The border correction (reduced sample) estimator of KIJ used here is pointwise approximately unbiased, but need not be a nondecreasing function of r, while the true KIJ must be nondecreasing.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Cressie, N.A.C. Statistics for spatial data. John Wiley and Sons, 1991.

Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 1983.

Diggle, P. J. (1986). Displaced amacrine cells in the retina of a rabbit : analysis of a bivariate spatial point pattern. J. Neurosci. Meth. 18, 115–125.

Harkness, R.D and Isham, V. (1983) A bivariate spatial point pattern of ants' nests. Applied Statistics 32, 293–303

Lotwick, H. W. and Silverman, B. W. (1982). Methods for analysing spatial processes of several types of points. J. Royal Statist. Soc. Ser. B 44, 406–413.

Ripley, B.D. Statistical inference for spatial processes. Cambridge University Press, 1988.

Stoyan, D, Kendall, W.S. and Mecke, J. Stochastic geometry and its applications. 2nd edition. Springer Verlag, 1995.

Van Lieshout, M.N.M. and Baddeley, A.J. (1999) Indices of dependence between types in multivariate point patterns. Scandinavian Journal of Statistics 26, 511–532.

See Also

Kcross, Kdot, Kest, pcf

Examples

    data(longleaf)
     # Longleaf Pine data: marks represent diameter

    K <- Kmulti(longleaf, longleaf$marks <= 15, longleaf$marks >= 25)
    plot(K)


Kolmogorov-Smirnov Test for Point Process Model

Description

Performs a Kolmogorov-Smirnov test of goodness-of-fit of a Poisson point process model. The test compares the observed and predicted distributions of the values of a spatial covariate.

Usage

ks.test.ppm(model, covariate, ...)

Arguments

model | A fitted point process model (object of class "ppm").
covariate | The spatial covariate on which the test will be based. An image (object of class "im") or a function.
... | Arguments passed to ks.test to control the test.

Details

This function performs a goodness-of-fit test of a fitted point process model. The observed distribution of the values of a spatial covariate at the data points, and the predicted distribution of the same values under the model, are compared using the Kolmogorov-Smirnov test.

The argument model should be a fitted point process model (object of class "ppm"). It should be a Poisson point process.

The argument covariate should be either a function(x,y) or a pixel image (object of class "im" containing the values of a spatial function. If covariate is an image, it should have numeric values, and its domain should cover the observation window of the model. If covariate is a function, it should expect two arguments x and y which are vectors of coordinates, and it should return a numeric vector of the same length as x and y.

First the original data point pattern is extracted from model. The values of the covariate at these data points are collected.

The predicted distribution of the values of the covariate under the fitted model is computed as follows. The values of the covariate at all locations in the observation window are evaluated, weighted according to the point process intensity of the fitted model, and compiled into a cumulative distribution function F using ewcdf.

The probability integral transformation is then applied: the values of the covariate at the original data points are transformed by the predicted cumulative distribution function F into numbers between 0 and 1. If the model is correct, these numbers are i.i.d. uniform random numbers. The Kolmogorov-Smirnov test of uniformity is applied using ks.test.

This test was apparently first described (in the context of spatial data) by Berman (1986). See also Baddeley et al (2005).

Value

An object of class "htest" containing the results of the test. See ks.test for details.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005) Residual analysis for spatial point processes. Journal of the Royal Statistical Society, Series B 67, 617–666.

Berman, M. (1986) Testing for spatial association between a point process and another stochastic process. Applied Statistics 35, 54–62.

See Also

ks.test, quadrat.test, ppm

Examples

   # nonuniform Poisson process
   X <- rpoispp(function(x,y) { 100 * exp(x) }, win=square(1))
   # fit uniform Poisson process
   fit0 <- ppm(X, ~1)
   # fit correct nonuniform Poisson process
   fit1 <- ppm(X, ~x)

   # test covariate = x coordinate
   xcoord <- function(x,y) { x }

   # test wrong model
   ks.test.ppm(fit0, xcoord)
   # test right model
   ks.test.ppm(fit1, xcoord)


Lansing Woods Point Pattern

Description

Locations and botanical classification of trees in Lansing Woods.

The data come from an investigation of a 924 ft x 924 ft (19.6 acre) plot in Lansing Woods, Clinton County, Michigan USA by D.J. Gerrard. The data give the locations of 2251 trees and their botanical classification (into hickories, maples, red oaks, white oaks, black oaks and miscellaneous trees). The original plot size (924 x 924 feet) has been rescaled to the unit square.

Usage

data(lansing)

Format

An object of class "ppp" representing the point pattern of tree locations. Entries include
x | Cartesian x-coordinate of tree
y | Cartesian y-coordinate of tree
marks | factor with levels indicating species of each tree

The levels of marks are blackoak, hickory, maple, misc, redoak and whiteoak. See ppp.object for details of the format of a point pattern object.

Notes

Source

References

Besag, J. (1978) Some methods of statistical analysis for spatial data. Bull. Internat. Statist. Inst. 44, 77–92.

Cox, T.F. (1976) The robust estimation of the density of a forest stand using a new conditioned distance method. Biometrika 63, 493–500.

Cox, T.F. (1979) A method for mapping the dense and sparse regions of a forest stand. Applied Statistics 28, 14–19.

Cox, T.F. and Lewis, T. (1976) A conditioned distance ratio method for analysing spatial patterns. Biometrika 63, 483–492.

Diggle, P.J. (1979a) The detection of random heterogeneity in plant populations. Biometrics 33, 390–394.

Diggle, P.J. (1979b) Statistical methods for spatial point patterns in ecology. Spatial and temporal analysis in ecology. R.M. Cormack and J.K. Ord (eds.) Fairland: International Co-operative Publishing House. pages 95–150.

Diggle, P.J. (1981) Some graphical methods in the analysis of spatial point patterns. In Interpreting Multivariate Data. V. Barnett (eds.) John Wiley and Sons. Pages 55–73.

Diggle, P.J. (1983) Statistical analysis of spatial point patterns. Academic Press.

Gerrard, D.J. (1969) Competition quotient: a new measure of the competition affecting individual forest trees. Research Bulletin 20, Agricultural Experiment Station, Michigan State University.

Lotwick, H.W. (1981) Spatial stochastic point processes. PhD thesis, University of Bath, UK.

Ord, J.K. (1978) How many trees in a forest? Mathematical Scientist 3, 23–33.


Lengths of Line Segments

Description

Computes the length of each line segment in a line segment pattern.

Usage

  lengths.psp(x)

Arguments

x A line segment pattern (object of class "psp").

Details

The length of each line segment is computed and the lengths are returned as a numeric vector.

Value

Numeric vector.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

summary.psp, midpoints.psp, angles.psp

Examples

  a <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
  b <- lengths.psp(a)


The Lennard-Jones Potential

Description

Creates the Lennard-Jones pairwise interaction structure which can then be fitted to point pattern data.

Usage

  LennardJones()

Details

In a pairwise interaction point process with the Lennard-Jones pair potential, each pair of points in the point pattern, a distance d apart, contributes a factor

exp( - (sigma/d)^12 + tau (sigma/d)^6)

to the probability density, where sigma and tau are positive parameters to be estimated.

See Examples for a plot of this expression.

This potential causes very strong inhibition between points at short range, and attraction between points at medium range. Roughly speaking, sigma controls the scale of both types of interaction, and tau determines the strength of attraction. The potential switches from inhibition to attraction at d=sigma/tau^(1/6). Maximum attraction occurs at distance d = (2/tau)^(1/6) sigma and the maximum achieved is exp((tau^2)/4). Interaction is negligible for distances d > 2 * sigma * max(1, tau^(1/6)).

This potential is used (in a slightly different parameterisation) to model interactions between uncharged molecules in statistical physics.

The function ppm(), which fits point process models to point pattern data, requires an argument of class "interact" describing the interpoint interaction structure of the model to be fitted. The appropriate description of the Lennard-Jones pairwise interaction is yielded by the function LennardJones(). See the examples below.

The ``canonical regular parameters'' estimated by ppm are theta1 = sigma^12 and theta2 = tau * sigma^6.

Value

An object of class "interact" describing the Lennard-Jones interpoint interaction structure.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppm, pairwise.family, ppm.object

Examples

   X <- rpoispp(100)
   ppm(X, ~1, LennardJones(), correction="translate")
   # Typically yields very small values for theta_1, theta_2
   # so the values of sigma, tau may not be sensible
##########
   # How to plot the pair potential function (exponentiated)
   plotLJ <- function(sigma, tau) {
        dmax <- 2 * sigma * max(1, tau)^(1/6)
        d <- seq(dmax * 0.0001, dmax, length=1000)
        plot(d, exp(- (sigma/d)^12 + tau * (sigma/d)^6), type="l",
                ylab="Lennard-Jones",
                main=substitute(list(sigma==s, tau==t),
                     list(s=sigma,t=tau)))
        abline(h=1, lty=2)
   }
   plotLJ(1,1)


Window in Shape of Letter R

Description

A window in the shape of the capital letter R, for use in demonstrations.

Usage

 data(letterR)

Format

An object of class "owin" representing the capital letter R, in the same font as the R package logo. See owin.object for details of the format.

Source

Adrian Baddeley


Level Set of a Pixel Image

Description

Given a pixel image, find all pixels which have values less than a specified threshold value (or greater than a threshold, etc), and assemble these pixels into a window.

Usage

  levelset(X, thresh, compare="<=")

Arguments

X | A pixel image (object of class "im")
thresh | Threshold value. A single number or value compatible with the pixel values in X
compare | Character string specifying one of the comparison operators "<", ">", "==", "<=", ">=", "!=".

Details

If X is a pixel image with numeric values, then levelset(X, thresh) finds the region of space where the pixel values are less than or equal to the threshold value thresh. This region is returned as a spatial window.

The argument compare specifies how the pixel values should be compared with the threshold value. Instead of requiring pixel values to be less than or equal to thresh, you can specify that they must be less than (<), greater than (>), equal to (==), greater than or equal to (>=), or not equal to (!=) the threshold value thresh.

If X has non-numeric pixel values (for example, logical or factor values) it is advisable to use only the comparisons == and !=, unless you really know what you are doing.

For more complicated logical comparisons, see solutionset.

Value

A spatial window (object of class "owin", see owin.object) containing the pixels satisfying the constraint.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

im.object, as.owin, solutionset.

Examples

  # test image
  X <- as.im(function(x,y) { x^2 - y^2 }, unit.square())

  W <- levelset(X, 0.2)
  W <- levelset(X, -0.3, ">")

  # compute area of level set
  area.owin(levelset(X, 0.1))


Fit a Log-Gaussian Cox Point Process by Minimum Contrast

Description

Fits a log-Gaussian Cox point process model (with exponential covariance function) to a point pattern dataset by the Method of Minimum Contrast.

Usage

lgcp.estK(X, startpar=list(sigma2=1,alpha=1), lambda=NULL,
q = 1/4, p = 2, rmin = NULL, rmax = NULL)

Arguments

X | Data to which the model will be fitted. Either a point pattern or a summary statistic. See Details.
startpar | Vector of starting values for the parameters of the log-Gaussian Cox process model.
lambda | Optional. An estimate of the intensity of the point process.
q,p | Optional. Exponents for the contrast criterion.
rmin, rmax | Optional. The interval of r values for the contrast criterion.

Details

This algorithm fits a log-Gaussian Cox point process model to a point pattern dataset by the Method of Minimum Contrast, using the K function.

The argument X can be either

a point pattern:
An object of class "ppp" representing a point pattern dataset. The K function of the point pattern will be computed using Kest, and the method of minimum contrast will be applied to this.
a summary statistic:
An object of class "fv" containing the values of a summary statistic, computed for a point pattern dataset. The summary statistic should be the K function, and this object should have been obtained by a call to Kest or one of its relatives.

The algorithm fits a log-Gaussian Cox point process (LGCP) model to X, by finding the parameters of the LGCP model which give the closest match between the theoretical K function of the LGCP model and the observed K function. For a more detailed explanation of the Method of Minimum Contrast, see mincontrast.

The model fitted is a stationary, isotropic log-Gaussian Cox process with exponential covariance (Moller and Waagepetersen, 2003, pp. 72-76). To define this process we start with a stationary Gaussian random field Z in the two-dimensional plane, with constant mean mu and covariance function

c(r) = sigma^2 * exp(-r/alpha)

where sigma^2 and alpha are parameters. Given Z, we generate a Poisson point process Y with intensity function lambda(u) = exp(Z(u)) at location u. Then Y is a log-Gaussian Cox process.

The theoretical K-function of the LGCP is

K(r) = integral from 0 to r of (2 * pi * s * exp(sigma^2 * exp(-s/alpha))) ds.

The theoretical intensity of the LGCP is

lambda= exp(mu + sigma^2/2).

In this algorithm, the Method of Minimum Contrast is first used to find optimal values of the parameters sigma^2 and alpha^2. Then the remaining parameter mu is inferred from the estimated intensity lambda.

If the argument lambda is provided, then this is used as the value of lambda. Otherwise, if X is a point pattern, then lambda will be estimated from X. If X is a summary statistic and lambda is missing, then the intensity lambda cannot be estimated, and the parameter mu will be returned as NA.

The remaining arguments rmin,rmax,q,p control the method of minimum contrast; see mincontrast.

Value

An object of class "minconfit". There are methods for printing and plotting this object. It contains the following main components:

par | Vector of fitted parameter values.
fit | Function value table (object of class "fv") containing the observed values of the summary statistic (observed) and the theoretical values of the summary statistic computed from the fitted model parameters.

Author(s)

Rasmus Waagepetersen rw@math.auc.dk. Adapted for spatstat by Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/

References

Moller, J. and Waagepetersen, R. (2003). Statistical Inference and Simulation for Spatial Point Processes. Chapman and Hall/CRC, Boca Raton.

Waagepetersen, R. (2006). An estimation function approach to inference for inhomogeneous Neyman-Scott processes. Submitted.

See Also

lgcp.estK, matclust.estK, mincontrast, Kest

Examples

    data(redwood)
    u <- lgcp.estK(redwood, c(sigma2=0.1, alpha=1))
    u
    plot(u)


Longleaf Pines Point Pattern

Description

Locations and sizes of Longleaf pine trees. A marked point pattern.

The data record the locations and diameters of 584 Longleaf pine (Pinus palustris) trees in a 200 x 200 metre region in southern Georgia (USA). They were collected and analysed by Platt, Evans and Rathbun (1988).

This is a marked point pattern; the mark associated with a tree is its diameter at breast height (dbh), a convenient measure of its size. Several analyses have considered only the ``adult'' trees which are conventionally defined as those trees with dbh greater than or equal to 30 cm.

The pattern is regarded as spatially inhomogeneous.

Usage

data(longleaf)

Format

An object of class "ppp" representing the point pattern of tree locations. Entries include
x | Cartesian x-coordinate of tree
y | Cartesian y-coordinate of tree
marks | diameter at breast height, in centimetres.

See ppp.object for details of the format of a point pattern object.

Source

Platt, Evans and Rathbun (1988)

References

Platt, W. J., Evans, G. W. and Rathbun, S. L. (1988) The population dynamics of a long-lived Conifer (Pinus palustris). The American Naturalist 131, 491–525.

Rathbun, S. L. and Cressie, N. (1994) A space-time survival point process for a longleaf pine forest in southern Georgia. Journal of the American Statistical Association 89, 1164–1173.


Lurking variable plot

Description

Plot spatial point process residuals against a covariate

Usage

lurking(object, covariate, type="eem",
                    cumulative=TRUE,
                    clipwindow=default.clipwindow(object),
                    rv,
                    plot.sd, plot.it=TRUE,
                    typename,
                    covname,
                    oldstyle=FALSE, ...)

Arguments

object | The fitted point process model (an object of class "ppm") for which diagnostics should be produced. This object is usually obtained from ppm.
covariate | The covariate against which residuals should be plotted. Either a numeric vector, a pixel image, or an expression. See Details below.
type | String indicating the type of residuals or weights to be computed. Choices include "eem", "raw", "inverse" and "pearson". See diagnose.ppm for all possible choices.
cumulative | Logical flag indicating whether to plot a cumulative sum of marks (cumulative=TRUE) or the derivative of this sum, a marginal density of the smoothed residual field (cumulative=FALSE).
clipwindow | If not NULL this argument indicates that residuals shall only be computed inside a subregion of the window containing the original point pattern data. Then clipwindow should be a window object of class "owin".
rv | Usually absent. If this argument is present, the values of the residuals will not be calculated from the fitted model object but will instead be taken directly from this vector.
plot.sd | Logical value indicating whether error bounds should be added to plot. The default is TRUE for Poisson models and FALSE for non-Poisson models. See Details.
plot.it | Logical value indicating whether plots should be shown. If plot.it=FALSE, only the computed coordinates for the plots are returned. See Value.
typename | Usually absent. If this argument is present, it should be a string, and will be used (in the axis labels of plots) to describe the type of residuals.
covname | A string name for the covariate, to be used in axis labels of plots.
oldstyle | Logical flag indicating whether error bounds should be plotted using the approximation given in the original paper (oldstyle=TRUE), or using the correct asymptotic formula (oldstyle=FALSE).
... | Arguments passed to smooth.spline for the estimation of the derivatives in the case cumulative=FALSE.

Details

This function generates a `lurking variable' plot for a fitted point process model. Residuals from the model represented by object are plotted against the covariate specified by covariate. This plot can be used to reveal departures from the fitted model, in particular, to reveal that the point pattern depends on the covariate.

First the residuals from the fitted model (Baddeley et al, 2004) are computed at each quadrature point, or alternatively the `exponential energy marks' (Stoyan and Grabarnik, 1991) are computed at each data point. The argument type selects the type of residual or weight. See diagnose.ppm for options and explanation.

A lurking variable plot for point processes (Baddeley et al, 2004) displays either the cumulative sum of residuals/weights (if cumulative = TRUE) or a kernel-weighted average of the residuals/weights (if cumulative = FALSE) plotted against the covariate. The empirical plot (solid lines) is shown together with its expected value assuming the model is true (dashed lines) and optionally also the pointwise two-standard-deviation limits (dotted lines).

To be more precise, let Z(u) denote the value of the covariate at a spatial location u.

  • If cumulative=TRUE then we plot H(z) against z, where H(z) is the sum of the residuals over all quadrature points where the covariate takes a value less than or equal to z, or the sum of the exponential energy weights over all data points where the covariate takes a value less than or equal to z.
  • If cumulative=FALSE then we plot h(z) against z, where h(z) is the derivative of H(z), computed approximately by spline smoothing.

For the point process residuals E(H(z)) = 0, while for the exponential energy weights E(H(z)) = area of the subset of the window satisfying Z(u) <= z.

If the empirical and theoretical curves deviate substantially from one another, the interpretation is that the fitted model does not correctly account for dependence on the covariate. The correct form (of the spatial trend part of the model) may be suggested by the shape of the plot.

If plot.sd = TRUE, then superimposed on the lurking variable plot are the pointwise two-standard-deviation error limits for H(x) calculated for the inhomogeneous Poisson process. The default is plot.sd = TRUE for Poisson models and plot.sd = FALSE for non-Poisson models.

By default, the two-standard-deviation limits are calculated from the exact formula for the asymptotic variance of the residuals under the asymptotic normal approximation, equation (37) of Baddeley et al (2006). However, for compatibility with the original paper of Baddeley et al (2005), if oldstyle=TRUE, the two-standard-deviation limits are calculated using the innovation variance, an over-estimate of the true variance of the residuals.

The argument object must be a fitted point process model (object of class "ppm") typically produced by the maximum pseudolikelihood fitting algorithm ppm).

The argument covariate is either a numeric vector, a pixel image, or an R language expression. If it is a numeric vector, it is assumed to contain the values of the covariate for each of the quadrature points in the fitted model. The quadrature points can be extracted by quad.ppm(object).

If covariate is a pixel image, it is assumed to contain the values of the covariate at each location in the window. The values of this image at the quadrature points will be extracted.

Alternatively, if covariate is an expression, it will be evaluated in the same environment as the model formula used in fitting the model object. It must yield a vector of the same length as the number of quadrature points. The expression may contain the terms x and y representing the cartesian coordinates, and may also contain other variables that were available when the model was fitted. Certain variable names are reserved words; see ppm.

Note that lurking variable plots for the x and y coordinates are also generated by diagnose.ppm, amongst other types of diagnostic plots. This function is more general in that it enables the user to plot the residuals against any chosen covariate that may have been present.

Value

A list containing two dataframes empirical and theoretical. The first dataframe empirical contains columns covariate and value giving the coordinates of the lurking variable plot. The second dataframe theoretical contains columns covariate, mean and sd giving the coordinates of the plot of the theoretical mean and standard deviation.

References

Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005) Residual analysis for spatial point processes. Journal of the Royal Statistical Society, Series B 67, 617–666.

Baddeley, A., Moller, J. and Pakes, A.G. (2006) Properties of residuals for spatial point processes. To appear.

Stoyan, D. and Grabarnik, P. (1991) Second-order characteristics for stochastic structures connected with Gibbs point processes. Mathematische Nachrichten, 151:95–100.

See Also

residuals.ppm, diagnose.ppm, residuals.ppm, qqplot.ppm, eem, ppm

Examples

  data(nztrees)
  fit <- ppm(nztrees, ~x, Poisson())
  lurking(fit, expression(x))
  lurking(fit, expression(x), cumulative=FALSE)


Mark Correlation Function

Description

Estimate the marked correlation function of a marked point pattern.

Usage

markcorr(X, f = function(m1, m2) { m1 * m2}, r=NULL,
         correction=c("isotropic", "Ripley", "translate"),
         method="density", ...)

Arguments

X | The observed point pattern. An object of class "ppp" or something acceptable to as.ppp.
f | Function f used in the definition of the mark correlation function. There is a sensible default that depends on the kind of marks in X.
r | numeric vector. The values of the argument r at which the mark correlation function rho_f(r) should be evaluated. There is a sensible default.
correction | A character vector containing any selection of the options "isotropic", "Ripley" or "translate". It specifies the edge correction(s) to be applied.
method | A character vector indicating the user's choice of density estimation technique to be used. Options are "density", "loess", "sm" and "smrep".
... | Arguments passed to the density estimation routine (density, loess or sm.density) selected by method.

Details

The mark correlation function rho_f(r) of a marked point process X is a measure of the dependence between the marks of two points of the process a distance r apart. It is informally defined as

rho_f(r) = E[f(M1,M2)]/E[f(M,M')]

where E[ ] denotes expectation and M1,M2 are the marks attached to two points of the process separated by a distance r, while M,M' are independent realisations of the marginal distribution of marks.

Here f is any function f(m1,m2) with two arguments which are possible marks of the pattern, and which returns a nonnegative real value. Common choices of f are: for continuous real-valued marks,

f(m1,m2)= m1 * m2

for discrete marks (multitype point patterns),

f(m1,m2)= (m1 == m2)

and for marks taking values in [0,2 * pi),

f(m1,m2) = sin(m1-m2)

.

Note that rho_f(r) is not a ``correlation'' in the usual statistical sense. It can take any nonnegative real value. The value 1 suggests ``lack of correlation'': if the marks attached to the points of X are independent and identically distributed, then rho_f(r) = 1. The interpretation of values larger or smaller than 1 depends on the choice of function f.

The argument X must be a point pattern (object of class "ppp") or any data that are acceptable to as.ppp. It must be a marked point pattern.

The argument f determines the function to be applied to pairs of marks. It has a sensible default, which depends on the kind of marks in X. If the marks are numeric values, then f <- function(m1, m2) { m1 * m2} computes the product of two marks. If the marks are a factor (i.e. if X is a multitype point pattern) then f <- function(m1, m2) { m1 == m2} yields the value 1 when the two marks are equal, and 0 when they are unequal. These are the conventional definitions for numerical marks and multitype points respectively.

Alternatively the argument f may be specified by the user. It must be a function, accepting two arguments m1 and m2 which are vectors of equal length containing mark values (of the same type as the marks of X). It must return a vector of numeric values of the same length as m1 and m2. The values must be non-negative, and NA values are not permitted.

The argument r is the vector of values for the distance r at which rho_f(r) is estimated.

This algorithm assumes that X can be treated as a realisation of a stationary (spatially homogeneous) random spatial point process in the plane, observed through a bounded window. The window (which is specified in X as X$window) may have arbitrary shape.

Biases due to edge effects are treated in the same manner as in Kest. The edge corrections implemented here are

isotropic/Ripley
Ripley's isotropic correction (see Ripley, 1988; Ohser, 1983). This is implemented only for rectangular and polygonal windows (not for binary masks).
translate
Translation correction (Ohser, 1983). Implemented for all window geometries, but slow for complex windows.

Note that the estimator assumes the process is stationary (spatially homogeneous).

The numerator and denominator of the mark correlation function (in the expression above) are estimated using density estimation techniques. The user can choose between

"density"
which uses the standard kernel density estimation routine density, and works only for evenly-spaced r values;
"loess"
which uses the function loess in the package modreg;
"sm"
which uses the function sm.density in the package sm and is extremely slow;
"smrep"
which uses the function sm.density in the package sm and is relatively fast, but may require manual control of the smoothing parameter hmult.

Value

An object of class "fv" (see fv.object).
Essentially a data frame containing numeric columns

r | the values of the argument r at which the mark correlation function rho_f(r) has been estimated
theo | the theoretical value of rho_f(r) when the marks attached to different points are independent, namely 1

together with a column or columns named "iso" and/or "trans", according to the selected edge corrections. These columns contain estimates of the function rho_f(r) obtained by the edge corrections named.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of geometrical statistics. John Wiley and Sons.

See Also

Kest, Kmulti

Examples

    # CONTINUOUS-VALUED MARKS:
    # (1) Longleaf Pine data
    # marks represent tree diameter
    data(longleaf)
    # Subset of this large pattern
    swcorner <- owin(c(0,100),c(0,100))
    sub <- longleaf[ , swcorner]
    # mark correlation function
    mc <- markcorr(sub)
    plot(mc)

    # (2) simulated data with independent marks
    X <- rpoispp(100)
    X <- X %mark% runif(X$n)
    Xc <- markcorr(X)
    plot(Xc)

    # MULTITYPE DATA:
    # Hughes' amacrine data
    # Cells marked as 'on'/'off'
    data(amacrine)
    # (3) Kernel density estimate with Epanecnikov kernel
    # (as proposed by Stoyan & Stoyan)
    M <- markcorr(amacrine, function(m1,m2) {m1==m2},
                  correction="translate", method="density",
                  kernel="epanechnikov")
    plot(M)
    # Note: kernel="epanechnikov" comes from help(density)

    # (4) Same again with explicit control over bandwidth
    M <- markcorr(amacrine,
                  correction="translate", method="density",
                  kernel="epanechnikov", bw=0.02)
    # see help(density) for correct interpretation of 'bw'


Summarise Marks in Every Neighbourhood in a Point Pattern

Description

Visit each point in a point pattern, find the neighbouring points, and summarise their marks

Usage

   markstat(X, fun, N, R, ...)

Arguments

X | A marked point pattern. An object of class "ppp".
fun | Function to be applied to the vector of marks.
N | Integer. If this argument is present, the neighbourhood of a point of X is defined to consist of the N points of X which are closest to it. This argument is incompatible with R.
R | Nonnegative numeric value. If this argument is present, the neighbourhood of a point of X is defined to consist of all points of X which lie within a distance R of it. This argument is incompatible with N.
... | extra arguments passed to the function fun. They must be given in the form name=value.

Details

This algorithm visits each point in the point pattern X, determines which points of X are ``neighbours'' of the current point, extracts the marks of these neighbouring points, applies the function fun to the marks, and collects the value or values returned by fun.

The definition of ``neighbours'' depends on the arguments N and R, exactly one of which must be given.

If N is given, then the neighbours of the current point are the N points of X which are closest to the current point (including the current point itself). If R is given, then the neighbourhood of the current point consists of all points of X which lie closer than a distance R from the current point.

Each point of X is visited; the neighbourhood of the current point is determined; the marks of these points are extracted as a vector v; then the function fun is called as:

fun(v, ...)

where ... are the arguments passed from the call to markstat.

The results of each call to fun are collected and returned according to the usual rules for apply and its relatives. See Value above.

This function is just a convenient wrapper for a common use of the function applynbd. For more complex tasks, see applynbd.

Value

Similar to the result of apply. if each call to fun returns a single numeric value, the result is a vector of dimension X$n, the number of points in X. If each call to fun returns a vector of the same length m, then the result is a matrix of dimensions c(m,n); note the transposition of the indices, as usual for the family of apply functions. If the calls to fun return vectors of different lengths, the result is a list of length X$n.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

applynbd, ppp.object, apply

Examples

  data(longleaf)

  # average diameter of 5 closest neighbours of each tree
  md <- markstat(longleaf, mean, N=5)

  # range of diameters of trees within 10 metre radius
  rd <- markstat(longleaf, range, R=10)


Fit the Matern Cluster Point Process by Minimum Contrast

Description

Fits the Matern Cluster point process to a point pattern dataset by the Method of Minimum Contrast.

Usage

matclust.estK(X, startpar=c(kappa=1,R=1), lambda=NULL,
            q = 1/4, p = 2, rmin = NULL, rmax = NULL)

Arguments

X | Data to which the Matern Cluster model will be fitted. Either a point pattern or a summary statistic. See Details.
startpar | Vector of starting values for the parameters of the Matern Cluster process.
lambda | Optional. An estimate of the intensity of the point process.
q,p | Optional. Exponents for the contrast criterion.
rmin, rmax | Optional. The interval of r values for the contrast criterion.

Details

This algorithm fits the Matern Cluster point process model to a point pattern dataset by the Method of Minimum Contrast, using the K function.

The argument X can be either

a point pattern:
An object of class "ppp" representing a point pattern dataset. The K function of the point pattern will be computed using Kest, and the method of minimum contrast will be applied to this.
a summary statistic:
An object of class "fv" containing the values of a summary statistic, computed for a point pattern dataset. The summary statistic should be the K function, and this object should have been obtained by a call to Kest or one of its relatives.

The algorithm fits the Matern Cluster point process to X, by finding the parameters of the Matern Cluster model which give the closest match between the theoretical K function of the Matern Cluster process and the observed K function. For a more detailed explanation of the Method of Minimum Contrast, see mincontrast.

The Matern Cluster point process is described in Moller and Waagepetersen (2003, p. 62). It is a cluster process formed by taking a pattern of parent points, generated according to a Poisson process with intensity kappa, and around each parent point, generating a random number of offspring points, such that the number of offspring of each parent is a Poisson random variable with mean mu, and the locations of the offspring points of one parent are independent and uniformly distributed inside a circle of radius R centred on the parent point.

The theoretical K-function of the Matern Cluster process is

K(r) = pi r^2 + h(r/(2*R))/kappa

where

h(z) = 2 + (1/pi) * ((8 * z^2 - 4) * arccos(z) - 2 * arcsin(z) + 4 * z * sqrt((1 - z^2)^3) - 6 * z * sqrt(1 - z^2))

for z <= 1, and h(z) = 1 for z > 1. The theoretical intensity of the Matern Cluster process is lambda=kappa* mu.

In this algorithm, the Method of Minimum Contrast is first used to find optimal values of the parameters kappa and R. Then the remaining parameter mu is inferred from the estimated intensity lambda.

If the argument lambda is provided, then this is used as the value of lambda. Otherwise, if X is a point pattern, then lambda will be estimated from X. If X is a summary statistic and lambda is missing, then the intensity lambda cannot be estimated, and the parameter mu will be returned as NA.

The remaining arguments rmin,rmax,q,p control the method of minimum contrast; see mincontrast.

The Matern Cluster process can be simulated, using rMatClust.

Value

An object of class "minconfit". There are methods for printing and plotting this object. It contains the following main components:

par | Vector of fitted parameter values.
fit | Function value table (object of class "fv") containing the observed values of the summary statistic (observed) and the theoretical values of the summary statistic computed from the fitted model parameters.

Author(s)

Rasmus Waagepetersen rw@math.auc.dk Adapted for spatstat by Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/

References

Moller, J. and Waagepetersen, R. (2003). Statistical Inference and Simulation for Spatial Point Processes. Chapman and Hall/CRC, Boca Raton.

Waagepetersen, R. (2006). An estimation function approach to inference for inhomogeneous Neyman-Scott processes. Submitted.

See Also

lgcp.estK, thomas.estK, mincontrast, Kest, rMatClust to simulate the fitted model.

Examples

    data(redwood)
    u <- matclust.estK(redwood, c(kappa=10, R=0.1))
    u
    plot(u)


Mean Pixel Value in an Image

Description

Calculates the mean of the pixel values in a pixel image. The mean method for class "im".

Usage

  ## S3 method for class 'im':
  mean(x, ...)

Arguments

x | A pixel image (object of class "im").
... | Arguments passed to mean.default.

Details

This function calculates the mean value of the pixels in the image x.

An object of class "im" describes a pixel image. See im.object) for details of this class.

The function mean.im is a method for the generic function mean for the class "im".

If the image x is logical-valued, the mean value of x is the fraction of pixels that have the value TRUE. If the image x is factor-valued, then the mean of x is the mean of the integer codes of the pixel values.

Any arguments in ... are passed to mean.default. In particular, using the argument trim will compute the trimmed mean, as explained in the help for mean.default.

Other information about an image can be obtained using summary.im.

Value

A single number.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

mean, mean.default, im.object, summary.im.

Examples

  X <- as.im(function(x,y) {x^2}, unit.square())
  mean(X)
  mean(X, trim=0.05)


Midpoints of Line Segment Pattern

Description

Computes the midpoints of each line segment in a line segment pattern.

Usage

  midpoints.psp(x)

Arguments

x A line segment pattern (object of class "psp").

Details

The midpoint of each line segment is computed.

Value

Point pattern (object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

summary.psp, lengths.psp, angles.psp

Examples

  a <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
  b <- midpoints.psp(a)


Method of Minimum Contrast

Description

A general algorithm for fitting theoretical point process models to point pattern data by the Method of Minimum Contrast.

Usage

mincontrast(observed, theoretical, startpar, ...,
          ctrl=list(q = 1/4, p = 2, rmin=NULL, rmax=NULL),
          fvlab=list(label=NULL, desc="minimum contrast fit"),
          explain=list(dataname=NULL, modelname=NULL, fname=NULL))

Arguments

observed | Summary statistic, computed for the data. An object of class "fv".
theoretical | An R language function that calculates the theoretical expected value of the summary statistic, given the model parameters. See Details.
startpar | Vector of initial values of the parameters of the point process model (passed to theoretical).
... | Additional arguments passed to the function theoretical.
ctrl | Optional. List of arguments controlling the optimisation. See Details.
fvlab | Optional. List containing some labels for the return value. See Details.
explain | Optional. List containing strings that give a human-readable description of the model, the data and the summary statistic.

Details

This function is a general algorithm for fitting point process models by the Method of Minimum Contrast. If you want to fit the Thomas process, see thomas.estK. If you want to fit a log-Gaussian Cox process, see lgcp.estK. If you want to fit the Matern cluster process, see matclust.estK.

The Method of Minimum Contrast (Diggle and Gratton, 1984) is a general technique for fitting a point process model to point pattern data. First a summary function (typically the K function) is computed from the data point pattern. Second, the theoretical expected value of this summary statistic under the point process model is derived (if possible, as an algebraic expression involving the parameters of the model) or estimated from simulations of the model. Then the model is fitted by finding the optimal parameter values for the model to give the closest match between the theoretical and empirical curves.

The argument observed should be an object of class "fv" (see fv.object) containing the values of a summary statistic computed from the data point pattern. Usually this is the function K(r) computed by Kest or one of its relatives.

The argument theoretical should be a user-supplied function that computes the theoretical expected value of the summary statistic. It must have an argument named par that will be the vector of parameter values for the model (the length and format of this vector are determined by the starting values in startpar). The function theoretical should also expect a second argument (the first argument other than par) containing values of the distance r for which the theoretical value of the summary statistic K(r) should be computed. The value returned by theoretical should be a vector of the same length as the given vector of r values.

The argument ctrl determines the contrast criterion (the objective function that will be minimised). The algorithm minimises the criterion

D(theta) = integral from rmin to rmax of abs(Fhat(r)^q - F(theta,r)^q)^p

where theta is the vector of parameters of the model, Fhat(r) is the observed value of the summary statistic computed from the data, F(theta,r) is the theoretical expected value of the summary statistic, and p,q are two exponents. The default is q = 1/4, p=2 so that the contrast criterion is the integrated squared difference between the fourth roots of the two functions (Waagepetersen, 2006).

The other arguments just make things print nicely. The argument fvlab contains labels for the component fit of the return value. The argument explain contains human-readable strings describing the data, the model and the summary statistic.

Value

An object of class "minconfit". There are methods for printing and plotting this object. It contains the following components:

par | Vector of fitted parameter values.
fit | Function value table (object of class "fv") containing the observed values of the summary statistic (observed) and the theoretical values of the summary statistic computed from the fitted model parameters.
opt | The return value from the optimizer optim.
crtl | The control parameters of the algorithm.
info | List of explanatory strings.

Author(s)

Rasmus Waagepetersen rw@math.auc.dk, adapted for spatstat by Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/

References

Diggle, P.J. and Gratton, R.J. (1984) Monte Carlo methods of inference for implicit statistical models. Journal of the Royal Statistical Society, series B 46, 193 – 212.

Moller, J. and Waagepetersen, R. (2003). Statistical Inference and Simulation for Spatial Point Processes. Chapman and Hall/CRC, Boca Raton.

Waagepetersen, R. (2006). An estimation function approach to inference for inhomogeneous Neyman-Scott processes. Submitted.

See Also

lgcp.estK, matclust.estK, thomas.estK,


Count Multiplicity of Duplicate Points

Description

Counts the number of duplicates for each point in a spatial point pattern.

Usage

 multiplicity.ppp(x)

Arguments

x A spatial point pattern (object of class "ppp").

Details

Two points in a point pattern are deemed to be identical if their x,y coordinates are the same, and their marks are also the same (if they carry marks). The Examples section illustrates how it is possible for a point pattern to contain a pair of identical points.

For each point in x, this function counts how many points are identical to it, and returns the vector of counts.

Value

A vector of integers (multiplicities) of length equal to the number of points in x.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp.object, duplicated.ppp, unique.ppp

Examples

   X <- ppp(c(1,1,0.5), c(2,2,1), window=square(3))
   m <- multiplicity.ppp(X)

   # unique points in X, marked by multiplicity
   first <- !duplicated(X)
   Y <- X[first] %mark% m[first]


The Multitype Strauss Point Process Model

Description

Creates an instance of the multitype Strauss point process model which can then be fitted to point pattern data.

Usage

  MultiStrauss(types, radii)

Arguments

types | Vector of all possible types (i.e. the possible levels of the marks variable in the data)
radii | Matrix of interaction radii

Details

The (stationary) multitype Strauss process with m types, with interaction radii r[i,j] and parameters beta[j] and gamma[i,j] is the pairwise interaction point process in which each point of type j contributes a factor beta[j] to the probability density of the point pattern, and a pair of points of types i and j closer than r[i,j] units apart contributes a factor gamma[i,j] to the density.

The nonstationary multitype Strauss process is similar except that the contribution of each individual point x[i] is a function beta(x[i]) of location and type, rather than a constant beta.

The function ppm(), which fits point process models to point pattern data, requires an argument of class "interact" describing the interpoint interaction structure of the model to be fitted. The appropriate description of the multitype Strauss process pairwise interaction is yielded by the function MultiStrauss(). See the examples below.

The matrix radii must be symmetric, with entries which are either positive numbers or NA. A value of NA indicates that no interaction term should be included for this combination of types.

Note that only the interaction radii are specified in MultiStrauss. The canonical parameters log(beta[j]) and log(gamma[i,j]) are estimated by ppm(), not fixed in Strauss().

Value

An object of class "interact" describing the interpoint interaction structure of the multitype Strauss process with interaction radii radii[i,j].

Warnings

The argument types is interpreted as a set of factor levels. That is, in order that ppm can fit the multitype Strauss model correctly to a point pattern X, this must be a marked point pattern; the mark vector X$marks must be a factor; and the argument types must equal levels(X$marks).

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppm, pairwise.family, ppm.object, Strauss

Examples

   r <- matrix(c(1,2,2,1), nrow=2,ncol=2)
   MultiStrauss(1:2, r)
   # prints a sensible description of itself
   data(betacells)
   r <- 30.0 * matrix(c(1,2,2,1), nrow=2,ncol=2)
   ppm(betacells, ~1, MultiStrauss(c("off","on"), r), rbord=60.0)
   # fit the stationary multitype Strauss process to `betacells'
   ppm(betacells, ~polynom(x,y,3), MultiStrauss(c("off","on"), r), rbord=60.0)
   # fit a nonstationary Strauss process with log-cubic polynomial trend


The Multitype/Hard Core Strauss Point Process Model

Description

Creates an instance of the multitype/hard core Strauss point process model which can then be fitted to point pattern data.

Usage

  MultiStraussHard(types, iradii, hradii)

Arguments

types | Vector of all possible types (i.e. the possible levels of the marks variable in the data)
iradii | Matrix of interaction radii
hradii | Matrix of hard core radii

Details

This is a hybrid of the multitype Strauss process (see MultiStrauss) and the hard core process (case gamma = 0 of the Strauss process). A pair of points of types i and j must not lie closer than h[i,j] units apart; if the pair lies more than h[i,j] and less than r[i,j] units apart, it contributes a factor gamma[i,j] to the probability density.

The matrices iradii and hradii must be symmetric, with entries which are either positive numbers or NA. A value of NA indicates that no interaction term should be included for this combination of types.

Note that only the interaction radii and hardcore radii are specified in MultiStraussHard. The canonical parameters log(beta[j]) and log(gamma[i,j]) are estimated by ppm(), not fixed in MultiStraussHard().

Value

An object of class "interact" describing the interpoint interaction structure of the multitype/hard core Strauss process with interaction radii iradii[i,j] and hard core radii hradii[i,j].

Warnings

The argument types is interpreted as a set of factor levels. That is, in order that ppm can fit the multitype Strauss model correctly to a point pattern X, this must be a marked point pattern; the mark vector X$marks must be a factor; and the argument types must equal levels(X$marks).

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppm, pairwise.family, ppm.object, MultiStrauss, Strauss

Examples

   r <- matrix(3, nrow=2,ncol=2)
   h <- matrix(c(1,2,2,1), nrow=2,ncol=2)
   MultiStraussHard(1:2, r, h)
   # prints a sensible description of itself
   data(betacells)
   r <- 30.0 * matrix(c(1,2,2,1), nrow=2,ncol=2)
   h <- 15.0 * matrix(c(NA,1,1,NA), nrow=2,ncol=2)
   ppm(betacells, ~1, MultiStraussHard(c("off","on"), r, h), rbord=60.0)
   # fit the stationary multitype hardcore Strauss process to `betacells'


Point Patterns of New Brunswick Forest Fires

Description

Point patterns created from yearly records, provided by the New Brunswick Department of Natural Resources, of all fires falling under their jurisdiction for the years 1987 to 2003 inclusive (with the year 1988 omitted until further notice).

Usage

data(nbfires)

Format

Executing data(nbfires) creates three objects: nbfires, nbextras, and nbw.rect.

The object nbfires is a marked point pattern (an object of class "ppp") consisting of all of the fires in the years 1987 to 2003 inclusive, with the omission of 1988. The marks consist of the last two digits of the years, with the string nbfires. prepended. Patterns for individual years can be extracted using the function split.ppp(). (See ``Examples''.)

The object nbextras is a list of data frames, with names extras.87, ..., extras.03. The columns of these data frames provide ``extra'' information about the fires. (See ``Details''.)

The object nbw.rect is a rectangular window which covers central New Brunswick. It is provided for use in illustrative and ``practice'' calculations inasmuch as the use of a rectangular window simplifies some computations considerably.

Details

The coordinates of the fire locations were provided in terms of latitude and longitude, to the nearest minute of arc. These were converted to New Brunswick stereographic projection coordinates (Thomson, Mephan and Steeves, 1977) which was the coordinate system in which the map of New Brunswick — which constitutes the observation window for the pattern — was obtained. The conversion was done using a C program kindly provided by Jonathan Beaudoin of the Department of Geodesy and Geomatics, University of New Brunswick.

Finally the data and window were rescaled since the use of the New Brunswick stereographic projection coordinate system resulted in having to deal with coordinates which are expressed as very large integers with a bewildering number of digits. Amongst other things, these huge numbers tended to create very untidy axis labels on graphs. The width of the bounding box of the window was made equal to 1000 (nameless) units. In addition the lower left hand corner of this bounding box was shifted to the origin. The height of the bounding box was changed proportionately, resulting in a value of approximately 959.

The window for the fire patterns comprises 6 polygonal components, consisting of mainland New Brunswick and the 5 largest islands. Some lakes which should form holes in the mainland component are currently missing; this problem will be remedied in future releases. The window was formed by ``simplifying'' the map that was originally obtained. The simplification consisted in reducing (using an interactive visual technique) the number of polygon edges in each component. For instance the number of edges in the mainland component was reduced from over 138,000 to 500.

For some purposes it is probably better to use a discretized (mask type) window. See ``Examples''.

Because of the coarseness of the coordinates of the original data (1 minute of longitude is approximately 1 kilometer at the latitude of New Brunswick), data entry errors, and the simplification of the observation window, many of the original fire locations appeared to be outside of the window. This problem was addressed by shifting the location of the ``outsider'' points slightly, or deleting them, as seemed appropriate.

The columns of the data frames comprising nbextras are

    fire.type
    A code for the type of fire with 1 = forest, 2 = grass, 3 = dump, and 4 = other.
    dis.date
    The discovery date of the fire, which is the nearest possible surrogate for the start date of the fire. These columns are of class Date and have the format yyyy-mm-dd
    dis.time
    The discovery time (time of day) of the fire, on a 24 hour clock. These columns are of mode character and have the format HH:MM.
    dis.julian
    The discovery date and time of the fire, expressed in ``Julian days'', i.e. as a decimal fraction representing the number of days since the beginning of the year (midnight 31 December).
    out.date
    The date on which the fire was judged to be ``out''.
    out.time
    The time of day on a 24 hour clock, at which the fire was judged to be ``out''.
    out.julian
    The date and time at which the fire was judged to be ``out'', expressed in Julian days.
    cause
    General cause of the fire, coded as
1 = railroads,
2 = unknown,
3 = miscellaneous,
4 = lightening,
5 = forest industry,
6 = incendiary,
7 = recreation,
8 = resident,
9 = other industry.
Causes 2, 4, and 6 are designated as ``final'' by the New
Brunswick Department of Natural Resources, meaning
(it seems) ``that's all there is to it''.  Other causes
are apparently intended to be refined by being combined
with ``source of ignition''.
    ign.src
    Source of ignition, coded as
1 = cigarette/match/pipe/ashes,
2 = burning without a permit,
3 = burning with a permit,
4 = prescribed burn,
5 = wood spark,
6 = machine spark,
7 = campfire,
8 = chainsaw,
9 = machinery,
10 = vehicle accident,
11 = railroad accident,
12 = wheelbox on railcars,
13 = hot flakes off railcar wheels,
14 = dump (i.e. fire escaping from a dump),
15 = ashes (briquettes, burning garbage, etc.)
    fnl.size
    The final size of the fire (area burned) in hectares, to the nearest 10th hectare.

Note that due to data entry errors some of the ``out dates'' and ``out times'' in the original data sets were actually earlier than the corresponding ``discovery dates'' and ``discover times''. In such cases all corresponding entries of the extras data frame (i.e. dis.date, dis.time, dis.julian, out.date, out.time, and out.julian) were set equal to NA. Also, some of the dates and times were missing (equal to NA) in the original data sets.

Source

The data were kindly provided by the New Brunswick Department of Natural Resources. Special thanks are due to Jefferey Betts for a great deal of assistance.

References

Turner, Rolf (2007) Point patterns of forest fire locations. To appear in Environmental and Ecological Statistics.

Thomson, D. B., Mephan, M. P., and Steeves, R. R. (1977) The stereographic double projection. Technical Report 46, University of New Brunswick, Fredericton, N. B., Canada URL: gge.unb.ca/Pubs/Pubs.html.

Examples

## Not run:
data(nbfires)
X <- split(nbfires) # Create a list of yearly point patterns.
attach(X)           # Make the individual point patterns accessible.
attach(nbextras)    # Make the individual `extras' accessible.
ftyp <- extras.00$fire.type
Y.00 <- nbfires.00[ftyp==1 | ftyp==2] # Pick out forest and grass fires.
stt  <- extras.00$dis.julian[ftyp==1 | ftyp==2]
fin  <- extras.00$out.julian[ftyp==1 | ftyp==2]
Y.00 <- setmarks(Y.00,fin-stt) # Mark the pattern with fire duration.
plot(Y.00)
#
nbw.mask <- as.mask(nbfires$window, dimyx=500)
plot(nbw.mask, col=c("green", "white"))
plot(nbfires$window, border="red", add=TRUE)
#
plot(unmark(Y.00)[nbw.rect], add=TRUE)
plot(nbw.rect,add=TRUE,border="blue")
#
K.00 <- Kest(Y.00)
plot(K.00)
## End(Not run)


Find Pixel Nearest to a Given Point

Description

Given cartesian coordinates, find the nearest pixel.

Usage

 nearest.raster.point(x,y,w, indices=TRUE)

Arguments

x | Numeric vector of x coordinates of any points
y | Numeric vector of y coordinates of any points
w | A window (an object of class "owin") of type "mask" representing a binary pixel image.
indices | Logical flag indicating whether to return the row and column indices, or the actual x,y coordinates.

Details

The argument w should be a window (an object of class "owin", see owin.object for details) of type "mask". This represents a binary pixel image.

The arguments x and y should be numeric vectors of equal length. They are interpreted as the coordinates of points in space. For each point (x[i], y[i]), the function finds the nearest pixel in the grid of pixels for w.

If indices=TRUE, this function returns a list containing two vectors rr and cc giving row and column positions (in the image matrix). For the location (x[i],y[i]) the nearest pixel is at row rr[i] and column cc[i] of the image.

If indices=FALSE, the function returns a list containing two vectors x and y giving the actual coordinates of the pixels.

Value

If indices=TRUE, a list containing two vectors rr and cc giving row and column positions (in the image matrix). If indices=FALSE, a list containing vectors x and y giving actual coordinates of the pixels.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin.object, as.mask

Examples

  w <- owin(c(0,1), c(0,1), mask=matrix(TRUE, 100,100))  # 100 x 100 grid
  nearest.raster.point(0.5, 0.3, w)
  nearest.raster.point(0.5, 0.3, w, indices=FALSE)


Nearest-Neighbour Correlation of Marked Point Pattern

Description

Computes the nearest-neighbour correlation of a marked point pattern.

Usage

     nncorr(X,
            f = function(m1, m2) { m1 * m2 },
            ...,
            use = "all.obs", method = c("pearson", "kendall", "spearman"))

Arguments

X | The observed point pattern. An object of class "ppp".
f | Function f used in the definition of the nearest neighbour correlation.
... | Extra arguments passed to f.
use,method | Arguments passed to the standard correlation function cor.

Details

The nearest neighbour correlation nbar of a marked point process X is a number measuring the dependence between the mark of a typical point and the mark of its nearest neighbour.

Three different values are computed: the unnormalised, normalised, and classical correlations.

The unnormalised nearest neighbour correlation (Stoyan and Stoyan, 1994, section 14.7) is defined as

nbar[f] = E[f(M, M*)]

where E[] denotes mean value, M is the mark attached to a typical point of the point process, and M* is the mark attached to its nearest neighbour (i.e. the nearest other point of the point process).

Here f is any function f(m1,m2) with two arguments which are possible marks of the pattern, and which returns a nonnegative real value. Common choices of f are: for continuous real-valued marks,

f(m1,m2)= m1 * m2

for discrete marks (multitype point patterns),

f(m1,m2)= (m1 == m2)

and for marks taking values in [0,2 * pi),

f(m1,m2) = sin(m1-m2).

For example, in the second case, the unnormalised nearest neighbour correlation nbar[f] equals the proportion of points in the pattern which have the same mark as their nearest neighbour.

Note that nbar[f] is not a ``correlation'' in the usual statistical sense. It can take values greater than 1.

We can define a normalised nearest neighbour correlation by

mbar[f] = E[f(M,M*)]/E[f(M,M')]

where again M is the mark attached to a typical point, M* is the mark attached to its nearest neighbour, and M' is an independent copy of M with the same distribution. This normalisation is also not a ``correlation'' in the usual statistical sense, but is normalised so that the value 1 suggests ``lack of correlation'': if the marks attached to the points of X are independent and identically distributed, then mbar[f] = 1. The interpretation of values larger or smaller than 1 depends on the choice of function f.

Finally if the marks of X are real numbers, we can also compute the classical correlation, that is, the correlation coefficient of the two random variables M and M*. The classical correlation has a value between -1 and 1. Values close to -1 or 1 indicate strong dependence between the marks.

This function computes the unnormalised and normalised nearest neighbour correlations, and the classical correlation if appropriate.

The argument X must be a point pattern (object of class "ppp") and must be a marked point pattern.

The argument f must be a function, accepting two arguments m1 and m2 which are vectors of equal length containing mark values (of the same type as the marks of X). It must return a vector of numeric values of the same length as m1 and m2. The values must be non-negative.

The arguments use and method control the calculation of the classical correlation using cor, as explained in the help file for cor.

Other arguments may be passed to f through the ... argument.

This algorithm assumes that X can be treated as a realisation of a stationary (spatially homogeneous) random spatial point process in the plane, observed through a bounded window. The window (which is specified in X as X$window) may have arbitrary shape. Biases due to edge effects are treated using the ‘border method’ edge correction.

Value

Labelled vector of length 2 or 3 containing the unnormalised and normalised nearest neighbour correlations, and the classical correlation if appropriate.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of geometrical statistics. John Wiley and Sons.

Examples

  data(finpines)
  nncorr(finpines)
  # heights of neighbouring trees are slightly negatively correlated

  data(amacrine)
  nncorr(amacrine, function(m1, m2) { m1 == m2})
  # neighbouring cells are usually of different type


Nearest Neighbour in Another Point Pattern

Description

Given two point patterns X and Y, finds the nearest neighbour in Y of each point of X.

Usage

  nncross(X, Y, iX=NULL, iY=NULL)

Arguments

X, Y | Two point patterns (objects of class "ppp").
iX, iY | Optional identifiers, used to test whether a point in X is identical to a point in Y. See Details

Details

Given two point patterns X and Y this function finds, for each point of X, the nearest point of Y. The distance between these points is also computed.

The return value is a data frame, with rows corresponding to the points of X. The first column gives the nearest neighbour distances (i.e. the ith entry is the distance from the ith point of X to the nearest point of Y). The second column gives the indices of the nearest neighbours (i.e. the ith entry is the index of the nearest point in Y.)

Note that this function is not symmetric in X and Y. To find the nearest neighbour in X of each point in Y, just use nncross(Y,X).

The arguments iX and iY are used when the two point patterns X and Y have some points in common. In this situation nncross(X, Y) would return some zero distances. To avoid this, attach a unique integer identifier to each point, such that two points are identical if their identifying numbers are equal. Let iX be the vector of identifier values for the points in X, and iY the vector of identifiers for points in Y. Then the code will only compare two points if they have different values of the identifier. See the Examples.

Value

A data frame with two columns:

dist | Nearest neighbour distance
which | Nearest neighbour index in Y

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

Examples

  # two different point patterns
  X <- runifpoint(15)
  Y <- runifpoint(20)
  N <- nncross(X,Y)$which
  # note that length(N) = 15
  plot(superimpose(X=X,Y=Y), main="nncross", cols=c("red","blue"))
  arrows(X$x, X$y, Y[N]$x, Y[N]$y, length=0.15)

  # two patterns with some points in common
  Z <- runifpoint(50)
  X <- Z[1:30]
  Y <- Z[20:50]
  iX <- 1:30
  iY <- 20:50
  N <- nncross(X,Y, iX, iY)$which
  plot(superimpose(X=X, Y=Y), main="nncross", cols=c("red","blue"))
  arrows(X$x, X$y, Y[N]$x, Y[N]$y, length=0.15)


Nearest neighbour distances

Description

Computes the distance from each point to its nearest neighbour in a point pattern.

Usage

  nndist(X, ..., method="C")
  ## S3 method for class 'ppp':
  nndist(X, ..., method="C")
  ## Default S3 method:
  nndist(X, Y=NULL, ..., method="C")

Arguments

X,Y | Arguments specifying the locations of a set of points. For nndist.ppp, the argument X should be a point pattern (object of class "ppp"). For nndist.default, typically X and Y would be numeric vectors of equal length. Alternatively Y may be omitted and X may be a list with two components x and y, or a matrix with two columns.
... | Ignored by nndist.ppp and nndist.default.
method | String specifying which method of calculation to use. Values are "C" and "interpreted".

Details

This function computes the Euclidean distance from each point in a point pattern to its nearest neighbour (the nearest other point of the pattern).

The function nndist is generic, with a method for point patterns (objects of class "ppp") and a default method.

The method for point patterns expects a single point pattern argument X and returns the vector of its nearest neighbour distances.

The default method expects that X and Y will determine the coordinates of a set of points. Typically X and Y would be numeric vectors of equal length. Alternatively Y may be omitted and X may be a list with two components named x and y, or a matrix or data frame with two columns.

The argument method is not normally used. It is retained only for checking the validity of the software. If method = "interpreted" then the distances are computed using interpreted R code only. If method="C" (the default) then C code is used. The C code is faster by two to three orders of magnitude and uses much less memory.

If there is only one point (if x has length 1), then a nearest neighbour distance of Inf is returned. If there are no points (if x has length zero) a numeric vector of length zero is returned.

To identify which point is the nearest neighbour of a given point, use nnwhich.

To use the nearest neighbour distances for statistical inference, it is often advisable to use the edge-corrected empirical distribution, computed by Gest.

To find the nearest neighbour distances from one point pattern to another point pattern, use nncross.

Value

Numeric vector of the nearest neighbour distances for each point.

Warnings

An infinite value is returned if there is only one point in the point pattern.

Author(s)

Pavel Grabarnik pavel.grabar@issp.serpukhov.su and Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/

See Also

pairdist, Gest, nnwhich, nncross.

Examples

   data(cells)
   d <- nndist(cells)

   x <- runif(100)
   y <- runif(100)
   d <- nndist(x, y)

   # Stienen diagram
   plot(cells %mark% (nndist(cells)/2), markscale=1)


Nearest neighbour

Description

Finds the nearest neighbour of each point in a point pattern.

Usage

  nnwhich(X, ..., method="C")
  ## S3 method for class 'ppp':
  nnwhich(X, ..., method="C")
  ## Default S3 method:
  nnwhich(X, Y=NULL, ..., method="C")

Arguments

X,Y | Arguments specifying the locations of a set of points. For nnwhich.ppp, the argument X should be a point pattern (object of class "ppp"). For nnwhich.default, typically X and Y would be numeric vectors of equal length. Alternatively Y may be omitted and X may be a list with two components x and y, or a matrix with two columns.
... | Ignored by nnwhich.ppp and nnwhich.default.
method | String specifying which method of calculation to use. Values are "C" and "interpreted".

Details

For each point in the given point pattern, this function finds its nearest neighbour (the nearest other point of the pattern). It returns a vector giving, for each point, the index of the point's nearest neghbour.

The function nnwhich is generic, with a method for point patterns (objects of class "ppp") and a default method.

The method for point patterns expects a single point pattern argument X. The default method expects that X and Y will determine the coordinates of a set of points. Typically X and Y would be numeric vectors of equal length. Alternatively Y may be omitted and X may be a list with two components named x and y, or a matrix or data frame with two columns.

The argument method is not normally used. It is retained only for checking the validity of the software. If method = "interpreted" then the distances are computed using interpreted R code only. If method="C" (the default) then C code is used. The C code is faster by two to three orders of magnitude and uses much less memory.

If there is only one point (if x has length 1), then the nearest neighbour is undefined, and a value of NA is returned. If there are no points (if x has length zero) a numeric vector of length zero is returned.

To evaluate the distance between a point and its nearest neighbour, use nndist.

To find the nearest neighbours from one point pattern to another point pattern, use nncross.

Value

Integer vector giving, for each point, the index of its nearest neighour.

Warnings

A value of NA is returned if there is only one point in the point pattern.

Author(s)

Pavel Grabarnik pavel.grabar@issp.serpukhov.su and Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/

See Also

nndist, nncross

Examples

   oldpar <- par(mfrow=c(2,1))
   data(cells)
   plot(cells)
   m <- nnwhich(cells)

   # plot nearest neighbour links
   b <- cells[m]
   arrows(cells$x, cells$y, b$x, b$y, angle=15, length=0.15, col="red")

   # find points which are the neighbour of their neighbour
   self <- (m[m] == seq(m))
   # plot them
   A <- cells[self]
   B <- cells[m[self]]
   plot(cells)
   segments(A$x, A$y, B$x, B$y)
   par(oldpar)


New Zealand Trees Point Pattern

Description

The data give the locations of trees in a forest plot.

They were collected by Mark and Esler (1970) and were extracted and analysed by Ripley (1981, pp. 169-175). They represent the positions of 86 trees in a forest plot approximately 140 by 85 feet.

Ripley discarded from his analysis the eight trees at the right-hand edge of the plot (which appear to be part of a planted border) and trimmed the window by a 5-foot margin accordingly.

Usage

data(nztrees)

Format

An object of class "ppp" representing the point pattern of tree locations. The Cartesian coordinates are in feet.

See ppp.object for details of the format of a point pattern object.

Note

To trim a 5-foot margin off the window, type nzsub <- nztrees[ , owin(c(0,148),c(0,95)) ]

Source

Mark and Esler (1970), Ripley (1981).

References

Ripley, B.D. (1981) Spatial statistics. John Wiley and Sons.

Mark, A.F. and Esler, A.E. (1970) An assessment of the point-centred quarter method of plotless sampling in some New Zealand forests. Proceedings of the New Zealand Ecological Society 17, 106–110.


Generic Ord Interaction model

Description

Creates an instance of an Ord-type interaction point process model which can then be fitted to point pattern data.

Usage

  Ord(pot, name)

Arguments

pot | An S language function giving the user-supplied interaction potential.
name | Character string.

Details

Ord's point process model (Ord, 1977) is a Gibbs point process of infinite order. Each point x[i] in the point pattern x contributes a factor g(a[i]) where a[i] = a(x[i], x) is the area of the tile associated with x[i] in the Dirichlet tessellation of x.

Ord (1977) proposed fitting this model to forestry data when g(a) has a simple ``threshold'' form. That model is implemented in our function OrdThresh. The present function Ord implements the case of a completely general Ord potential g(a) specified as an S language function pot.

This is experimental.

Value

An object of class "interact" describing the interpoint interaction structure of a point process.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point patterns. Australian and New Zealand Journal of Statistics 42, 283–322.

Ord, J.K. (1977) Contribution to the discussion of Ripley (1977).

Ord, J.K. (1978) How many trees in a forest? Mathematical Scientist 3, 23–33.

Ripley, B.D. (1977) Modelling spatial patterns (with discussion). Journal of the Royal Statistical Society, Series B, 39, 172 – 212.

See Also

ppm, ppm.object, OrdThresh


Ord Interaction Process Family

Description

An object describing the family of all Ord interaction point processes

Details

Advanced Use Only!

This structure would not normally be touched by the user. It describes the family of point process models introduced by Ord (1977).

If you need to create a specific Ord-type model for use in analysis, use the function OrdThresh or Ord.

Anyway, ord.family is an object of class "isf" containing a function ord.family$eval for evaluating the sufficient statistics of any Ord type point process model taking an exponential family form.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point patterns. Australian and New Zealand Journal of Statistics 42, 283–322.

Ord, J.K. (1977) Contribution to the discussion of Ripley (1977).

Ord, J.K. (1978) How many trees in a forest? Mathematical Scientist 3, 23–33.

Ripley, B.D. (1977) Modelling spatial patterns (with discussion). Journal of the Royal Statistical Society, Series B, 39, 172 – 212.

See Also

pairwise.family, pairsat.family, Poisson, Pairwise, PairPiece, Strauss, StraussHard, Softcore, Geyer, Saturated, Ord, OrdThresh


Ord's Interaction model

Description

Creates an instance of Ord's point process model which can then be fitted to point pattern data.

Usage

  OrdThresh(r)

Arguments

r Positive number giving the threshold value for Ord's model.

Details

Ord's point process model (Ord, 1977) is a Gibbs point process of infinite order. Each point x[i] in the point pattern x contributes a factor g(a[i]) where a[i] = a(x[i], x) is the area of the tile associated with x[i] in the Dirichlet tessellation of x. The function g is simply g(a) = 1 if a >= r and g(a) = gamma < 1 if a < r, where r is called the threshold value.

This function creates an instance of Ord's model with a given value of r. It can then be fitted to point process data using ppm.

Value

An object of class "interact" describing the interpoint interaction structure of a point process.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point patterns. Australian and New Zealand Journal of Statistics 42, 283–322.

Ord, J.K. (1977) Contribution to the discussion of Ripley (1977).

Ord, J.K. (1978) How many trees in a forest? Mathematical Scientist 3, 23–33.

Ripley, B.D. (1977) Modelling spatial patterns (with discussion). Journal of the Royal Statistical Society, Series B, 39, 172 – 212.

See Also

ppm, ppm.object


Create a Window

Description

Creates an object of class "owin" representing an observation window in the two-dimensional plane

Usage

  owin(xrange=c(0,1), yrange=c(0,1), ..., poly=NULL, mask=NULL, units=NULL)

Arguments

xrange | x coordinate limits of enclosing box
yrange | y coordinate limits of enclosing box
... | Ignored.
poly | Optional. Polygonal boundary of window. Incompatible with mask.
mask | Optional. Logical matrix giving binary image of window. Incompatible with poly.
units | Optional. Name of unit of length. Either a single character string, or a vector of two character strings giving the singular and plural forms, respectively.

Details

In the spatstat library, a point pattern dataset must include information about the window of observation. This is represented by an object of class "owin". See owin.object for an overview.

To create a window in its own right, users would normally invoke owin, although sometimes as.owin may be convenient.

A window may be rectangular, polygonal, or a mask (a binary image).

  • rectangular windows: If only xrange and yrange are given, then the window will be rectangular, with its x and y coordinate dimensions given by these two arguments (which must be vectors of length 2). If no arguments are given at all, the default is the unit square with dimensions xrange=c(0,1) and yrange=c(0,1).
  • polygonal windows: If poly is given, then the window will be polygonal.
    • single polygon: If poly is a structure with two component vectors x and y of equal length, then these vectors are interpreted as the cartesian coordinates of the vertices of a polygon circumscribing the window. The vertices must be listed anticlockwise. No vertex should be repeated (i.e. do not repeat the first vertex).
    • multiple polygons or holes: If poly is a list, each entry poly[[i]] of which is a structure with two component vectors x and y of equal length, then the successive list members poly[[i]] are interpreted as separate polygons which together make up the boundary of the window. The vertices of each polygon must be listed anticlockwise if the polygon is part of the external boundary, but clockwise if the polygon is the boundary of a hole in the window. Again, do not repeat any vertex.
  • binary masks: If mask is given, then the window will be a binary image. The argument mask should be a logical matrix such that mask[i,j] is TRUE if the point (x[j],y[i]) belongs to the window, and FALSE if it does not. Note carefully that rows of mask correspond to the y coordinate, and columns to the x coordinate. Here x and y are vectors of x and y coordinates equally spaced over xrange and yrange respectively.
To create a window which is mathematically defined by inequalities in the Cartesian coordinates, use raster.x() and raster.y() as in the examples below.

Functions square and disc will create square and circular windows, respectively.

Value

An object of class "owin" describing a window in the two-dimensional plane.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

square, disc, owin.object, as.owin, complement.owin, ppp.object, ppp

Examples

  w <- owin()
  w <- owin(c(0,1), c(0,1))
  # the unit square

  w <- owin(c(10,20), c(10,30), units=c("foot","feet"))
  # a rectangle of dimensions 10 x 20 feet
  # with lower left corner at (10,10)

  # polygon (diamond shape)
  w <- owin(poly=list(x=c(0.5,1,0.5,0),y=c(0,1,2,1)))
  w <- owin(c(0,1), c(0,2), poly=list(x=c(0.5,1,0.5,0),y=c(0,1,2,1)))

  # polygon with hole
  ho <- owin(poly=list(list(x=c(0,1,1,0), y=c(0,0,1,1)),
                       list(x=c(0.6,0.4,0.4,0.6), y=c(0.2,0.2,0.4,0.4))))

  w <- owin(c(-1,1), c(-1,1), mask=matrix(TRUE, 100,100))
          # 100 x 100 image, all TRUE
  X <- raster.x(w)
  Y <- raster.y(w)
  wm <- owin(w$xrange, w$yrange, mask=(X^2 + Y^2 <= 1))
          # discrete approximation to the unit disc

  ## Not run:
  plot(c(0,1),c(0,1),type="n")
  bdry <- locator()
  # click the vertices of a polygon (anticlockwise)

## End(Not run)

  w <- owin(poly=bdry)
  ## Not run: plot(w)

 ## Not run:
 im <- as.logical(matrix(scan("myfile"), nrow=128, ncol=128))
 # read in an arbitrary 128 x 128 digital image from text file
 rim <- im[, 128:1]
 # Assuming it was given in row-major order in the file
 # i.e. scanning left-to-right in rows from top-to-bottom,
 # the use of matrix() has effectively transposed rows & columns,
 # so to convert it to our format just reverse the column order.
 w <- owin(mask=rim)
 plot(w)
 # display it to check!

## End(Not run)


Class owin

Description

A class owin to define the ``observation window'' of a point pattern

Details

In the spatstat library, a point pattern dataset must include information about the window or region in which the pattern was observed. A window is described by an object of class "owin". Windows of arbitrary shape are supported.

An object of class "owin" has one of three types:
"rectangle": | a rectangle in the two-dimensional plane with edges parallel to the axes
"polygonal": | a region whose boundary is a polygon or several polygons. The region may have holes and may consist of several disconnected pieces.
"mask": | a binary image (a logical matrix) set to TRUE for pixels inside the window and FALSE outside the window.

Objects of class "owin" may be created by the function owin and converted from other types of data by the function as.owin.

They may be manipulated by the functions as.rectangle, as.mask, complement.owin, rotate, shift, affine, erode.owin, and erode.mask.

Geometrical calculations available for windows include area.owin, bounding.box, diameter, eroded.areas, bdist.points, bdist.pixels, and even.breaks.owin. The mapping between continuous coordinates and pixel raster indices is facilitated by the functions raster.x, raster.y and nearest.raster.point.

There is a plot method for window objects, plot.owin. This may be useful if you wish to plot a point pattern's window without the points for graphical purposes.

There are also methods for summary and print.

Warnings

In a window of type "mask", the row index corresponds to increasing y coordinate, and the column index corresponds to increasing x coordinate.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin, as.owin, as.rectangle, as.mask, summary.owin, print.owin, complement.owin, erode.owin, affine.owin, shift.owin, rotate.owin, raster.x, raster.y, nearest.raster.point, plot.owin, area.owin, bounding.box, diameter, eroded.areas, bdist.points, bdist.pixels

Examples

 w <- owin()
 w <- owin(c(0,1), c(0,1))
 # the unit square

 w <- owin(c(0,1), c(0,2))
 ## Not run:
 plot(w)
 # plots edges of a box 1 unit x 2 units
 v <- locator()
 # click on points in the plot window
 # to be the vertices of a polygon
 # traversed in anticlockwise order
 u <- owin(c(0,1), c(0,2), poly=v)
 plot(u)
 # plots polygonal boundary using polygon()
 plot(as.mask(u, eps=0.02))
 # plots discrete pixel approximation to polygon

## End(Not run)


Pairwise distances

Description

Computes the matrix of distances between all pairs of `things' in a dataset

Usage

  pairdist(X, ...)

Arguments

X | Object specifying the locations of a set of `things' (such as a set of points or a set of line segments).
... | Further arguments depending on the method.

Details

Given a dataset X and Y (representing either a point pattern or a line segment pattern) pairdist computes the distance between each pair of `things' in the dataset, and returns a matrix containing these distances.

The function pairdist is generic, with methods for point patterns (objects of class "ppp"), line segment patterns (objects of class "psp") and a default method. See the documentation for pairdist.ppp, pairdist.psp or pairdist.default for details.

Value

A square matrix whose [i,j] entry is the distance between the `things' numbered i and j.

Author(s)

Pavel Grabarnik pavel.grabar@issp.serpukhov.su and Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/

See Also

pairdist.ppp, pairdist.psp, pairdist.default, crossdist, nndist, Kest


Pairwise distances

Description

Computes the matrix of distances between all pairs of points in a set of points

Usage

  ## Default S3 method:
  pairdist(X, Y=NULL, ..., period=NULL, method="C")

Arguments

X,Y | Arguments specifying the coordinates of a set of points. Typically X and Y would be numeric vectors of equal length. Alternatively Y may be omitted and X may be a list with two components x and y, or a matrix with two columns.
... | Ignored.
period | Optional. Dimensions for periodic edge correction.
method | String specifying which method of calculation to use. Values are "C" and "interpreted". Usually not specified.

Details

Given the coordinates of a set of points, this function computes the Euclidean distances between all pairs of points, and returns the matrix of distances. It is a method for the generic function pairdist.

The arguments X and Y must determine the coordinates of a set of points. Typically X and Y would be numeric vectors of equal length. Alternatively Y may be omitted and X may be a list with two components named x and y, or a matrix or data frame with two columns.

Alternatively if period is given, then the distances will be computed in the `periodic' sense (also known as `torus' distance). The points will be treated as if they are in a rectangle of width period[1] and height period[2]. Opposite edges of the rectangle are regarded as equivalent.

The argument method is not normally used. It is retained only for checking the validity of the software. If method = "interpreted" then the distances are computed using interpreted R code only. If method="C" (the default) then C code is used. The C code is somewhat faster.

Value

A square matrix whose [i,j] entry is the distance between the points numbered i and j.

Author(s)

Pavel Grabarnik pavel.grabar@issp.serpukhov.su and Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/

See Also

crossdist, nndist, Kest

Examples

   x <- runif(100)
   y <- runif(100)
   d <- pairdist(x, y)
   d <- pairdist(cbind(x,y))
   d <- pairdist(x, y, period=c(1,1))


Pairwise distances

Description

Computes the matrix of distances between all pairs of points in a point pattern.

Usage

  ## S3 method for class 'ppp':
  pairdist(X, ..., periodic=FALSE, method="C")

Arguments

X | A point pattern (object of class "ppp").
... | Ignored.
periodic | Logical. Specifies whether to apply a periodic edge correction.
method | String specifying which method of calculation to use. Values are "C" and "interpreted". Usually not specified.

Details

This is a method for the generic function pairdist.

Given a point pattern X (an object of class "ppp"), this function computes the Euclidean distances between all pairs of points in X, and returns the matrix of distances.

Alternatively if periodic=TRUE and the window containing X is a rectangle, then the distances will be computed in the `periodic' sense (also known as `torus' distance): opposite edges of the rectangle are regarded as equivalent. This is meaningless if the window is not a rectangle.

The argument method is not normally used. It is retained only for checking the validity of the software. If method = "interpreted" then the distances are computed using interpreted R code only. If method="C" (the default) then C code is used. The C code is somewhat faster.

Value

A square matrix whose [i,j] entry is the distance between the points numbered i and j.

Author(s)

Pavel Grabarnik pavel.grabar@issp.serpukhov.su and Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/

See Also

pairdist, pairdist.default, pairdist.psp, crossdist, nndist, Kest

Examples

   data(cells)
   d <- pairdist(cells)
   d <- pairdist(cells, periodic=TRUE)


Pairwise distances between line segments

Description

Computes the matrix of distances between all pairs of line segments in a line segment pattern.

Usage

  ## S3 method for class 'psp':
  pairdist(X, ..., method="Fortran")

Arguments

X | A line segment pattern (object of class "psp").
... | Ignored.
method | String specifying which method of calculation to use. Values are "Fortran" and "interpreted". Usually not specified.

Details

This function computes the distance between each pair of line segments in X, and returns the matrix of distances.

This is a method for the generic function pairdist for the class "psp".

Distances are calculated using the Hausdorff metric. The Hausdorff distance between two line segments is the maximum distance from any point on one of the segments to the nearest point on the other segment.

The argument method is not normally used. It is retained only for checking the validity of the software. If method = "interpreted" then the distances are computed using interpreted R code only. If method="Fortran" (the default) then Fortran code is used. The Fortran code is somewhat faster.

Value

A square matrix whose [i,j] entry is the distance between the line segments numbered i and j.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

crossdist, nndist, pairdist.ppp

Examples

   L <- psp(runif(10), runif(10), runif(10), runif(10), owin())
   D <- pairdist(L)


The Piecewise Constant Pairwise Interaction Point Process Model

Description

Creates an instance of a pairwise interaction point process model with piecewise constant potential function. The model can then be fitted to point pattern data.

Usage

  PairPiece(r)

Arguments

r vector of jump points for the potential function

Details

A pairwise interaction point process in a bounded region is a stochastic point process with probability density of the form

f(x_1,...,x_n) = alpha . product { b(x[i]) } product { h(x_i, x_j) }

where x[1],...,x[n] represent the points of the pattern. The first product on the right hand side is over all points of the pattern; the second product is over all unordered pairs of points of the pattern.

Thus each point x[i] of the pattern contributes a factor b(x[i]) to the probability density, and each pair of points x[i], x[j] contributes a factor h(x[i], x[j]) to the density.

The pairwise interaction term h(u, v) is called piecewise constant if it depends only on the distance between u and v, say h(u,v) = H(||u-v||), and H is a piecewise constant function (a function which is constant except for jumps at a finite number of places).

The function ppm(), which fits point process models to point pattern data, requires an argument of class "interact" describing the interpoint interaction structure of the model to be fitted. The appropriate description of the piecewise constant pairwise interaction is yielded by the function PairPiece(). See the examples below.

The entries of r must be strictly increasing, positive numbers. They are interpreted as the points of discontinuity of H. It is assumed that H(s) =1 for all s > rmax where rmax is the maximum value in r. Thus the model has as many regular parameters (see ppm) as there are entries in r. The i-th regular parameter theta[i] is the logarithm of the value of the interaction function H on the interval [r[i-1],r[i]).

If r is a single number, this model is similar to the Strauss process, see Strauss. The difference is that in PairPiece the interaction function is continuous on the right, while in Strauss it is continuous on the left.

The analogue of this model for multitype point processes has not yet been implemented.

Value

An object of class "interact" describing the interpoint interaction structure of a point process. The process is a pairwise interaction process, whose interaction potential is piecewise constant, with jumps at the distances given in the vector r.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppm, pairwise.family, ppm.object, Strauss rmh.ppm

Examples

   PairPiece(c(0.1,0.2))
   # prints a sensible description of itself
   data(cells)
   ppm(cells, ~1, PairPiece(r = c(0.05, 0.1, 0.2)), rbord=0.2)
   # fit a stationary piecewise constant pairwise interaction process
   ppm(cells, ~polynom(x,y,3), PairPiece(c(0.05, 0.1)), rbord=0.1)
   # nonstationary process with log-cubic polynomial trend


Saturated Pairwise Interaction Point Process Family

Description

An object describing the Saturated Pairwise Interaction family of point process models

Details

Advanced Use Only!

This structure would not normally be touched by the user. It describes the ``saturated pairwise interaction'' family of point process models.

If you need to create a specific interaction model for use in spatial pattern analysis, use the function Saturated() or the one existing implementation of a model in this family, Geyer().

Geyer (1999) introduced the ``saturation process'', a modification of the Strauss process in which the total contribution to the potential from each point (from its pairwise interaction with all other points) is trimmed to a maximum value c. This model is implemented in the function Geyer().

The present class pairsat.family is the extension of this saturation idea to all pairwise interactions. Note that the resulting models are no longer pairwise interaction processes - they have interactions of infinite order.

pairsat.family is an object of class "isf" containing a function pairwise$eval for evaluating the sufficient statistics of any saturated pairwise interaction point process model in which the original pair potentials take an exponential family form.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Geyer, C.J. (1999) Likelihood Inference for Spatial Point Processes. Chapter 3 in O.E. Barndorff-Nielsen, W.S. Kendall and M.N.M. Van Lieshout (eds) Stochastic Geometry: Likelihood and Computation, Chapman and Hall / CRC, Monographs on Statistics and Applied Probability, number 80. Pages 79–140.

See Also

pairwise.family, Geyer


Generic Pairwise Interaction model

Description

Creates an instance of a pairwise interaction point process model which can then be fitted to point pattern data.

Usage

  Pairwise(pot, name, par, parnames, printfun)

Arguments

pot | An S language function giving the user-supplied pairwise interaction potential.
name | Character string.
par | List of numerical values for irregular parameters
parnames | Vector of names of irregular parameters
printfun | Do not specify this argument: for internal use only.

Details

Advanced use only.

This code constructs a member of the pairwise interaction family pairwise.family with arbitrary pairwise interaction potential given by the user.

The function pot must take as its first argument a matrix of interpoint distances, and evaluate the potential for each of these distances. The result must be either a matrix with the same dimensions as its input, or an array with its first two dimensions the same as its input (the latter case corresponds to a vector-valued potential).

If irregular parameters are present, then the second argument to pot should be a vector of the same type as par giving those parameter values.

Value

An object of class "interact" describing the interpoint interaction structure of a point process.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppm, pairwise.family, ppm.object

Examples

   #This is the same as StraussHard(r=0.7,h=0.2)
   strpot <- function(d,par) {
         r <- par$r
         h <- par$h
         value <- (d <= r)
         value[d < h] <- -Inf
         value
   }
   mySH <- Pairwise(strpot, "StraussHard", list(r=0.7,h=0.2),
           c("interaction distance r", "hard core distance c"))
   data(cells)
   ppm(cells, ~ 1, mySH)


Pairwise Interaction Process Family

Description

An object describing the family of all pairwise interaction point processes

Details

Advanced Use Only!

This structure would not normally be touched by the user. It describes the pairwise interaction family of point process models.

If you need to create a specific pairwise interaction model for use in modelling, use the function Pairwise or one of the existing functions (listed below, starting with a capital letter).

Anyway, pairwise.family is an object of class "isf" containing a function pairwise$eval for evaluating the sufficient statistics of any pairwise interaction point process model taking an exponential family form.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

pairsat.family, ord.family, Poisson, Pairwise, PairPiece, Strauss, StraussHard, Softcore, Geyer, Saturated, Ord, OrdThresh


Pair Correlation Function

Description

Estimate the pair correlation function.

Usage

 pcf(X, ...)

Arguments

X | Either the observed data point pattern, or an estimate of its K function, or an array of multitype K functions (see Details).
... | Other arguments passed to the appropriate method.

Details

The pair correlation function of a stationary point process is

g(r) = K'(r)/ ( 2 * pi * r)

where K'(r) is the derivative of K(r), the reduced second moment function (aka ``Ripley's K function'') of the point process. See Kest for information about K(r). For a stationary Poisson process, the pair correlation function is identically equal to 1. Values g(r) < 1 suggest inhibition between points; values greater than 1 suggest clustering.

We also apply the same definition to other variants of the classical K function, such as the multitype K functions (see Kcross, Kdot) and the inhomogeneous K function (see Kinhom). For all these variants, the benchmark value of K(r) = pi * r^2 corresponds to g(r) = 1.

This routine computes an estimate of g(r) either directly from a point pattern, or indirectly from an estimate of K(r) or one of its variants.

This function is generic, with methods for the classes "ppp", "fv" and "fasp".

If X is a point pattern (object of class "ppp") then the pair correlation function is estimated using a traditional kernel smoothing method (Stoyan and Stoyan, 1994). See pcf.ppp for details.

If X is a function value table (object of class "fv"), then it is assumed to contain estimates of the K function or one of its variants (typically obtained from Kest or Kinhom). This routine computes an estimate of g(r) using smoothing splines to approximate the derivative. See pcf.fv for details.

If X is a function value array (object of class "fasp"), then it is assumed to contain estimates of several K functions (typically obtained from Kmulti or alltypes). This routine computes an estimate of g(r) for each cell in the array, using smoothing splines to approximate the derivatives. See pcf.fasp for details.

Value

Either a function value table (object of class "fv", see fv.object) representing a pair correlation function, or a function array (object of class "fasp", see fasp.object) representing an array of pair correlation functions.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of geometrical statistics. John Wiley and Sons.

See Also

pcf.ppp, pcf.fv, pcf.fasp, Kest, Kinhom, Kcross, Kdot, Kmulti, alltypes

Examples

  # ppp object
  data(simdat)

  p <- pcf(simdat)
  plot(p)

  # fv object
  K <- Kest(simdat)
  p2 <- pcf(K)
  plot(p2)

  # multitype pattern; fasp object
  data(betacells)

  p <- pcf(alltypes(betacells, "K"))
  plot(p)


Pair Correlation Function obtained from array of K functions

Description

Estimates the (bivariate) pair correlation functions of a point pattern, given an array of (bivariate) K functions.

Usage

 ## S3 method for class 'fasp':
 pcf(X, ..., method="c")

Arguments

X | An array of multitype K functions (object of class "fasp").
... | Arguments controlling the smoothing spline function smooth.spline.
method | Letter "a", "b", "c" or "d" indicating the method for deriving the pair correlation function from the K function.

Details

The pair correlation function of a stationary point process is

g(r) = K'(r)/ ( 2 * pi * r)

where K'(r) is the derivative of K(r), the reduced second moment function (aka ``Ripley's K function'') of the point process. See Kest for information about K(r). For a stationary Poisson process, the pair correlation function is identically equal to 1. Values g(r) < 1 suggest inhibition between points; values greater than 1 suggest clustering.

We also apply the same definition to other variants of the classical K function, such as the multitype K functions (see Kcross, Kdot) and the inhomogeneous K function (see Kinhom). For all these variants, the benchmark value of K(r) = pi * r^2 corresponds to g(r) = 1.

This routine computes an estimate of g(r) from an array of estimates of K(r) or its variants, using smoothing splines to approximate the derivatives. It is a method for the generic function pcf.

The argument X should be a function array (object of class "fasp", see fasp.object) containing several estimates of K functions. This should have been obtained from alltypes with the argument fun="K".

The smoothing spline operations are performed by smooth.spline and predict.smooth.spline from the modreg library. Four numerical methods are available:

  • "a" apply smoothing to K(r), estimate its derivative, and plug in to the formula above;
  • "b" apply smoothing to Y(r) = K(r)/(2 * pi * r) constraining Y(0) = 0, estimate the derivative of Y, and solve;
  • "c" apply smoothing to Y(r) = K(r)/(pi * r^2) constraining Z(0)=1, estimate its derivative, and solve.
  • "d" apply smoothing to V(r) = sqrt(K(r)), estimate its derivative, and solve.

Method "c" seems to be the best at suppressing variability for small values of r. However it effectively constrains g(0) = 1. If the point pattern seems to have inhibition at small distances, you may wish to experiment with method "b" which effectively constrains g(0)=0. Method "a" seems comparatively unreliable.

Useful arguments to control the splines include the smoothing tradeoff parameter spar and the degrees of freedom df. See smooth.spline for details.

Value

A function array (object of class "fasp", see fasp.object) representing an array of pair correlation functions. This can be thought of as a matrix Y each of whose entries Y[i,j] is a function value table (class "fv") representing the pair correlation function between points of type i and points of type j.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Stoyan, D, Kendall, W.S. and Mecke, J. (1995) Stochastic geometry and its applications. 2nd edition. Springer Verlag.

Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of geometrical statistics. John Wiley and Sons.

See Also

Kest, Kinhom, Kcross, Kdot, Kmulti, alltypes, smooth.spline, predict.smooth.spline

Examples

  # multitype point pattern
  data(betacells)

  KK <- alltypes(betacells, "K")
  p <- pcf.fasp(KK, spar=0.5, method="b")
  plot(p)
  # short range inhibition between all types
  # strong inhibition between "on" and "off"


Pair Correlation Function obtained from K Function

Description

Estimates the pair correlation function of a point pattern, given an estimate of the K function.

Usage

  ## S3 method for class 'fv':
  pcf(X, ..., method="c")

Arguments

X | An estimate of the K function or one of its variants. An object of class "fv".
... | Arguments controlling the smoothing spline function smooth.spline.
method | Letter "a", "b", "c" or "d" indicating the method for deriving the pair correlation function from the K function.

Details

The pair correlation function of a stationary point process is

g(r) = K'(r)/ ( 2 * pi * r)

where K'(r) is the derivative of K(r), the reduced second moment function (aka ``Ripley's K function'') of the point process. See Kest for information about K(r). For a stationary Poisson process, the pair correlation function is identically equal to 1. Values g(r) < 1 suggest inhibition between points; values greater than 1 suggest clustering.

We also apply the same definition to other variants of the classical K function, such as the multitype K functions (see Kcross, Kdot) and the inhomogeneous K function (see Kinhom). For all these variants, the benchmark value of K(r) = pi * r^2 corresponds to g(r) = 1.

This routine computes an estimate of g(r) from an estimate of K(r) or its variants, using smoothing splines to approximate the derivative. It is a method for the generic function pcf for the class "fv".

The argument X should be an estimated K function, given as a function value table (object of class "fv", see fv.object). This object should be the value returned by Kest, Kcross, Kmulti or Kinhom.

The smoothing spline operations are performed by smooth.spline and predict.smooth.spline from the modreg library. Four numerical methods are available:

  • "a" apply smoothing to K(r), estimate its derivative, and plug in to the formula above;
  • "b" apply smoothing to Y(r) = K(r)/(2 * pi * r) constraining Y(0) = 0, estimate the derivative of Y, and solve;
  • "c" apply smoothing to Y(r) = K(r)/(pi * r^2) constraining Z(0)=1, estimate its derivative, and solve.
  • "d" apply smoothing to V(r) = sqrt(K(r)), estimate its derivative, and solve.

Method "c" seems to be the best at suppressing variability for small values of r. However it effectively constrains g(0) = 1. If the point pattern seems to have inhibition at small distances, you may wish to experiment with method "b" which effectively constrains g(0)=0. Method "a" seems comparatively unreliable.

Useful arguments to control the splines include the smoothing tradeoff parameter spar and the degrees of freedom df. See smooth.spline for details.

Value

A function value table (object of class "fv", see fv.object) representing a pair correlation function.
Essentially a data frame containing (at least) the variables

r | the vector of values of the argument r at which the pair correlation function g(r) has been estimated
pcf | vector of values of g(r)

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Stoyan, D, Kendall, W.S. and Mecke, J. (1995) Stochastic geometry and its applications. 2nd edition. Springer Verlag.

Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of geometrical statistics. John Wiley and Sons.

See Also

pcf, pcf.ppp, Kest, Kinhom, Kcross, Kdot, Kmulti, alltypes, smooth.spline, predict.smooth.spline

Examples

  # univariate point pattern
  data(simdat)

  K <- Kest(simdat)
  p <- pcf.fv(K, spar=0.5, method="b")
  plot(p, main="pair correlation function for simdat")
  # indicates inhibition at distances r < 0.3


Pair Correlation Function of Point Pattern

Description

Estimates the pair correlation function of a point pattern using kernel methods.

Usage

  ## S3 method for class 'ppp':
  pcf(X, ..., r = NULL, kernel="epanechnikov", bw=NULL, stoyan=0.15,
                    correction=c("translate", "ripley"))

Arguments

X | A point pattern (object of class "ppp").
r | Vector of values for the argument r at which g(r) should be evaluated. There is a sensible default.
kernel | Choice of smoothing kernel, passed to density.
bw | Bandwidth for smoothing kernel, passed to density.
... | Other arguments passed to the kernel density estimation function density.
stoyan | Bandwidth coefficient; see Details.
correction | Choice of edge correction.

Details

The pair correlation function of a stationary point process is

g(r) = K'(r)/ ( 2 * pi * r)

where K'(r) is the derivative of K(r), the reduced second moment function (aka ``Ripley's K function'') of the point process. See Kest for information about K(r). For a stationary Poisson process, the pair correlation function is identically equal to 1. Values g(r) < 1 suggest inhibition between points; values greater than 1 suggest clustering.

This routine computes an estimate of g(r) by the kernel smoothing method (Stoyan and Stoyan (1994), pages 284–285). By default, their recommendations are followed exactly.

If correction="translate" then the translation correction is used. The estimate is given in equation (15.15), page 284 of Stoyan and Stoyan (1994).

If correction="ripley" then Ripley's isotropic edge correction is used; the estimate is given in equation (15.18), page 285 of Stoyan and Stoyan (1994).

If correction=c("translate", "ripley") then both estimates will be computed.

The choice of smoothing kernel is controlled by the argument kernel which is passed to density. The default is the Epanechnikov kernel, recommended by Stoyan and Stoyan (1994, page 285).

The bandwidth of the smoothing kernel can be controlled by the argument bw. Its precise interpretation is explained in the documentation for density. For the Epanechnikov kernel, the argument bw is equivalent to h/sqrt(5).

Stoyan and Stoyan (1994, page 285) recommend using the Epanechnikov kernel with support [-h,h] chosen by the rule of thumn h = c/sqrt(lambda), where lambda is the (estimated) intensity of the point process, and c is a constant in the range from 0.1 to 0.2. See equation (15.16). If bw is missing, then this rule of thumb will be applied. The argument stoyan determines the value of c.

The argument r is the vector of values for the distance r at which g(r) should be evaluated. There is a sensible default. If it is specified, r must be a vector of increasing numbers starting from r[1] = 0, and max(r) must not exceed half the diameter of the window.

Value

A function value table (object of class "fv"). Essentially a data frame containing the variables

r | the vector of values of the argument r at which the pair correlation function g(r) has been estimated
theo | vector of values equal to 1, the theoretical value of g(r) for the Poisson process
trans | vector of values of g(r) estimated by translation correction
ripley | vector of values of g(r) estimated by Ripley isotropic correction

as required.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of geometrical statistics. John Wiley and Sons.

See Also

Kest, pcf, density

Examples

  data(simdat)

  p <- pcf(simdat)
  plot(p, main="pair correlation function for simdat")
  # indicates inhibition at distances r < 0.3


Perspective Plot of Pixel Image

Description

Displays a perspective plot of a pixel image.

Usage

  ## S3 method for class 'im':
  persp(x, ..., colmap=NULL)

Arguments

x | The pixel image to be plotted. An object of class "im" (see im.object).
... | Extra arguments passed to persp.default to control the display.
colmap | Optional data controlling the colour map. See Details.

Details

This is the persp method for the class "im".

The pixel image x must have real or integer values. These values are treated as heights of a surface, and the surface is displayed as a perspective plot on the current plot device, using equal scales on the x and y axes.

The optional argument colmap gives an easy way to display different altitudes in different colours (if this is what you want). If colmap is a character vector, then the range of altitudes in the perspective plot will be divided into length(colmap) intervals, and those parts of the surface which lie in a particular altitude range will be assigned the corresponding colour from colmap. Alternatively if colmap is a list with entries breaks and col, then colmap$breaks determines the breakpoints of the altitude intervals, and colmap$col provides the corresponding colours.

Graphical parameters controlling the perspective plot are passed through the ... arguments directly to the function persp.default. See the examples in persp.default or in demo(persp).

Value

Returns the 3D transformation matrix returned by persp.default.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

im.object, plot.im, contour.im

Examples

   # an image
   Z <- setcov(owin())
   persp(Z, colmap=terrain.colors(128), axes=FALSE, shade=0.3)


Plot a Function Array

Description

Plots an array of summary functions, usually associated with a point pattern, stored in an object of class "fasp". A method for plot.

Usage

   ## S3 method for class 'fasp':
   plot(x,formule=NULL, ...,
                        subset=NULL, title=NULL, samex=TRUE)

Arguments

x | An object of class "fasp" representing a function array.
formule | A formula or list of formulae indicating what variables are to be plotted against what variable. Each formula is either an R language formula object, or a string that can be parsed as a formula. If formule is a list, its k-th component should be applicable to the (i,j)-th plot where x$which[i,j]=k. If the formula is left as NULL, then plot.fasp attempts to use the component default.formula of x. If that component is NULL as well, it gives up.
subset | A logical vector, or a vector of indices, or an expression or a character string, or a list of such, indicating a subset of the data to be included in each plot. If subset is a list, its k-th component should be applicable to the (i,j)-th plot where x$which[i,j]=k.
title | Overall title for the plot.
samex | Logical flag indicating whether all individual plots should have the same x axis limits. This makes it easier to compare the plots. It can only be set to FALSE if you are using the default plot style (i.e. only when formule is missing).
... | Arguments passed to plot.fv to control the individual plot panels.

Details

An object of class "fasp" represents an array of summary functions, usually associated with a point pattern. See fasp.object for details. Such an object might be created, for example, by alltypes or allstats.

The function plot.fasp is a method for plot. It calls plot.fv to plot the individual panels.

For information about the interpretation of the arguments formule and subset, see plot.fv.

Arguments that are often passed through ... include col to control the colours of the different lines in a panel, and lty and lwd to control the line type and line width of the different lines in a panel. See plot.fv.

The argument title, if present, will determine the overall title of the plot. If it is absent, it defaults to x$title. Titles for the individual plot panels will be taken from x$titles.

Value

None.

Warnings

(Each component of) the subset argument may be a logical vector (of the same length as the vectors of data which are extracted from x), or a vector of indices, or an expression such as expression(r<=0.2), or a text string, such as "r<=0.2".

Attempting a syntax such as subset = r<=0.2 (without wrapping r<=0.2 either in quote marks or in expression()) will cause this function to fall over.

Variables referred to in any formula must exist in the data frames stored in x. What the names of these variables are will of course depend upon the nature of x.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

alltypes, allstats, plot.fv, fasp.object

Examples

   ## Not run:
   # Bramble Canes data.
   data(bramblecanes)

   X.G <- alltypes(bramblecanes,type="G",dataname="Bramblecanes",verb=TRUE)
   plot(X.G)
   plot(X.G,subset="r<=0.2")
   plot(X.G,formule=cbind(asin(sqrt(km)),
                    asin(sqrt(theo))) ~ asin(sqrt(theo)))
       plot(X.G,fo=cbind(km-theo,0)~r,"r<=0.2")

   # Swedish pines.
   data(swedishpines)
   X <- allstats(swedishpines,dataname="Swedish Pines")
   plot(X,subset=list("r<=20","r<=20","r<=20","r<=50"))

   # Simulated data.
   pp <- runifpoint(350, owin(c(0,1),c(0,1)))
   pp$marks <- factor(c(rep(1,50),rep(2,100),rep(3,200)))
   X.K <- alltypes(pp,type="K",verb=TRUE,dataname="Fake Data")
   plot(X.K,fo=cbind(border,theo)~theo,"theo<=0.75")
   ## End(Not run)


Plot Function Valuesn

Description

Plot method for the class "fv".

Usage

 ## S3 method for class 'fv':
 plot(x, fmla, ..., subset=NULL, lty=NULL, col=NULL, lwd=NULL,
           xlim=NULL, ylim=NULL, xlab=NULL, ylab=NULL)

Arguments

x | An object of class "fv", containing the variables to be plotted or variables from which the plotting coordinates can be computed.
fmla | an R language formula determining which variables or expressions are plotted. Either a formula object, or a string that can be parsed as a formula.
subset | (optional) subset of rows of the data frame that will be plotted.
lty | (optional) numeric vector of values of the graphical parameter lty controlling the line style of each plot.
col | (optional) numeric vector of values of the graphical parameter col controlling the colour of each plot.
lwd | (optional) numeric vector of values of the graphical parameter lwd controlling the line width of each plot.
xlim | (optional) range of x axis
ylim | (optional) range of y axis
xlab | (optional) label for x axis
ylab | (optional) label for y axis
... | Extra arguments passed to plot.default.

Details

This is the plot method for the class "fv".

The use of the argument fmla is like plot.formula, but offers some extra functionality.

The left and right hand sides of fmla are evaluated in the data frame x, and the results are plotted against each other (the left side on the y axis against the right side on the x axis). Both left and right sides may be variables in the data frame or expressions in these variables.

Multiple curves may be specified by a single formula of the form cbind(y1,y2,...,yn) ~ x, where x,y1,y2,...,yn are expressions involving the variables in the data frame. Each of the variables y1,y2,...,yn in turn will be plotted against x. See the examples.

A convenient abbreviation is the symbol . which can be used in the formula to represent all the variables in the data frame (other than the function argument itself). See the examples.

The value returned by this plot function indicates the meaning of the line types and colours in the plot. It can be used to make a suitable legend for the plot. See the examples.

Value

Either NULL, or a data frame giving the meaning of the different line types and colours.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

fv.object, Kest

Examples

   data(cells)
   K <- Kest(cells)
   # K is an object of class "fv"

   plot(K, iso ~ r)                # plots iso against r

   plot(K, sqrt(iso/pi) ~ r)   # plots sqrt(iso/r)  against r

   plot(K, cbind(iso,theo) ~ r)   # plots iso against r  AND theo against r

   plot(K, .  ~ r)            # plots all available estimates of K against r

   plot(K, sqrt(./pi) ~ r)   # plots all estimates of L-function
                             # L(r) = sqrt(K(r)/pi)

   plot(K, cbind(iso,theo) ~ r, col=c(2,3))
                                   # plots iso against r  in colour 2
                                   # and theo against r in colour 3

   plot(K, iso ~ r, subset=quote(r < 0.2))
                                   # plots iso against r for r < 10

   # making a legend
   v <- plot(K, . ~ r, ylab="K(r)")
   legend(0.05, 0.15, legend=row.names(v), lty=v$lty, col=v$col)


Plot a Pixel Image

Description

Plot a pixel image.

Usage

  ## S3 method for class 'im':
  plot(x, ..., ribbon=TRUE, ribsep=0.15, ribwid=0.05, ribn=1024)

Arguments

x | The pixel image to be plotted. An object of class "im" (see im.object).
... | Extra arguments passed to image to control the plot.
ribbon | Logical flag indicating whether to display a ribbon showing the colour map.
ribsep | Factor controlling the space between the ribbon and the image.
ribwid | Factor controlling the width of the ribbon.
ribn | Number of different values to display in the ribbon.

Details

This is the plot method for the class "im". [It is also the image method for "im".]

The pixel image x is displayed on the current plot device, using equal scales on the x and y axes.

If ribbon=TRUE, a legend will be plotted at the right of the image. The legend consists of a colour ribbon and an axis with tick-marks, showing the correspondence between the pixel values and the colour map.

Arguments ribsep, ribwid, ribn control the appearance of the ribbon. The width of the ribbon is ribwid times the size of the pixel image, where `size' means the larger of the width and the height. The distance separating the ribbon and the image is ribsep times the size of the pixel image. The ribbon contains ribn different numerical values, evenly spaced between the minimum and maximum pixel values in the image x, rendered according to the chosen colour map.

Graphical parameters controlling the display of both the pixel image and the ribbon are passed through the ... arguments directly to the function image.default. In particular, the colour map is controlled by the argument col. See the examples in image.default.

To suppress the axis tick marks and labels, set axes=FALSE.

Value

none.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

im.object, contour.im, persp.im

Examples

   # an image
   Z <- setcov(owin())
   plot(Z)
   plot(Z, col=terrain.colors(128), axes=FALSE)


Plot a List of Things

Description

Plots a list of things

Usage

  ## S3 method for class 'listof':
  plot(x, ..., main, arrange=TRUE, nrows=NULL, ncols=NULL)

Arguments

x | An object of the class "listof". Essentially a list of objects.
... | Arguments passed to plot when generating each plot panel.
main | Overall heading for the plot.
arrange | Logical flag indicating whether to plot the objects side-by-side on a single page (arrange=TRUE) or plot them individually in a succession of frames (arrange=FALSE).
nrows,ncols | Optional. The number of rows/columns in the plot layout (assuming arrange=TRUE). You can specify either or both of these numbers.

Details

This is the plot method for the class "listof".

An object of class "listof" (defined in the base R package) represents a list of objects, all belonging to a common class. The base R package defines a method for printing these objects, print.listof, but does not define a method for plot. So here we have provided a method for plot.

In the spatstat package, the function density.splitppp produces an object of class "listof", essentially a list of pixel images. These images can be plotted in a nice arrangement using plot.listof. See the Example.

Value

Null.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

print.listof, density.splitppp

Examples

# Multitype point pattern
 data(amacrine)
 plot(density(split(amacrine)))


Plot a Spatial Window

Description

Plot a two-dimensional window of observation for a spatial point pattern

Usage

 ## S3 method for class 'owin':
 plot(x, main, add=FALSE, ..., box, edge=0.04)

Arguments

x | The window to be plotted. An object of class owin, or data which can be converted into this format by as.owin().
main | text to be displayed as a title above the plot.
add | logical flag: if TRUE, draw the window in the current plot; if FALSE, generate a new plot.
... | extra arguments passed to the generic plot function.
box | logical flag; if TRUE, plot the enclosing rectangular box
edge | nonnegative number; the plotting region will have coordinate limits that are 1 + edge times as large as the limits of the rectangular box that encloses the pattern.

Details

This is the plot method for the class owin. The action is to plot the boundary of the window on the current plot device, using equal scales on the x and y axes.

If the window x is of type "rectangle" or "polygonal", the boundary of the window is plotted as a polygon or series of polygons. If x is of type "mask" the discrete raster approximation of the window is displayed as a binary image (white inside the window, black outside).

Graphical parameters controlling the display (e.g. setting the colours) may be passed directly via the ... arguments, or indirectly reset using spatstat.options.

When x is of type "rectangle" or "polygonal", it is plotted by the R function polygon. To control the appearance (colour, fill density, line density etc) of the polygon plot, determine the required argument of polygon and pass it through ... For example, to draw the polygon border in green, use the argument border="green".

When x is of type "mask", it is plotted by image.default. The appearance of the image plot can be controlled by passing arguments to image.default through .... The default appearance can also be changed by setting the parameter par.binary of spatstat.options.

Value

none.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin.object, plot.ppp, polygon, image.default, spatstat.options

Examples

## Not run:
  # rectangular window
   data(nztrees)
   plot(nztrees$window)
   abline(v=148, lty=2)

  # polygonal window
  plot(c(0,1),c(0,1),type="n")
  bdry <- locator()
  # click the vertices of a polygon (anticlockwise)
  w <- owin(c(0,1), c(0,1), poly=bdry)
  plot(w)

  # binary mask
  we <- erode.owin(w, 0.05, FALSE)
  plot(we)
  spatstat.options(par.binary=list(col=grey(c(0.5,1))))
  plot(we)
## End(Not run)


Plot a plotppm Object Created by plot.ppm

Description

The function plot.ppm produces objects which specify plots of fitted point process models. The function plot.plotppm carries out the actual plotting of these objects.

Usage

  ## S3 method for class 'plotppm':
  plot(x, data = NULL, trend = TRUE, cif = TRUE, pause = interactive(),
             how = c("persp", "image", "contour"), ...)

Arguments

x | An object of class plotppm produced by plot.ppm()
data | The point pattern (an object of class ppp) to which the point process model was fitted (by code{ppm()}).
trend | Logical scalar; should the trend component of the fitted model be plotted?
cif | Logical scalar; should the complete conditional intensity of the fitted model be plotted?
pause | Logical scalar indicating whether to pause with a prompt after each plot. Set pause=FALSE if plotting to a file.
how | Character string or character vector indicating the style or styles of plots to be performed.
... | Extra arguments to the plotting functions persp, image and contour.

Details

If argument data is supplied then the point pattern will be superimposed on the image and contour plots.

Sometimes a fitted model does not have a trend component, or the trend component may constitute all of the conditional intensity (if the model is Poisson). In such cases the object x will not contain a trend component, or will contain only a trend component. This will also be the case if one of the arguments trend and cif was set equal to FALSE in the call to plot.ppm() which produced x. If this is so then only the item which is present will be plotted. Explicitly setting trend=TRUE, or cif=TRUE, respectively, will then give an error.

Value

None.

Warning

Arguments which are passed to persp, image, and contour via the ... argument get passed to any of the other functions listed in the how argument, and won't be recognized by them. This leads to a lot of annoying but harmless warning messages. Arguments to persp may be supplied via spatstat.options() which alleviates the warning messages in this instance.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

plot.ppm()

Examples

 ## Not run:
 data(cells)
 Q <- quadscheme(cells)
 m <- ppm(Q, ~1, Strauss(0.05))
 mpic <- plot(m)
 # Perspective plot only, with altered parameters:
  plot(mpic,how="persp", theta=-30,phi=40,d=4)
 # All plots, with altered parameters for perspective plot:
 spatstat.options(par.persp=list(theta=-30,phi=40,d=4))
 plot(mpic)

## End(Not run)


plot a Fitted Point Process Model

Description

Given a fitted point process model obtained by ppm, create spatial trend and conditional intensity surfaces of the model, in a form suitable for plotting, and (optionally) plot these surfaces.

Usage

  ## S3 method for class 'ppm':
  plot(x, ngrid = c(40,40), superimpose = TRUE,
                  trend = TRUE, cif = TRUE, pause = interactive(),
                  how=c("persp","image", "contour"), plot.it = TRUE,
                  locations = NULL, covariates=NULL, ...)

Arguments

x | A fitted point process model, typically obtained from the model-fitting algorithm ppm. An object of class "ppm".
ngrid | The dimensions for a grid on which to evaluate, for plotting, the spatial trend and conditional intensity. A vector of 1 or 2 integers. If it is of length 1, ngrid is replaced by c(ngrid,ngrid).
superimpose | logical flag; if TRUE (and if plot=TRUE) the original data point pattern will be superimposed on the plots.
trend | logical flag; if TRUE, the spatial trend surface will be produced.
cif | logical flag; if TRUE, the conditional intensity surface will be produced.
pause | logical flag indicating whether to pause with a prompt after each plot. Set pause=FALSE if plotting to a file. (This flag is ignored if plot=FALSE).
how | character string or character vector indicating the style or styles of plots to be performed. Ignored if plot=FALSE.
plot.it | logical scalar; should a plot be produced immediately?
locations | If present, this determines the locations of the pixels at which predictions are computed. It must be a binary pixel image (an object of class "owin" with type "mask"). (Incompatible with ngrid).
covariates | Values of external covariates required by the fitted model. Passed to predict.ppm.
... | extra arguments to the plotting functions persp, image and contour.

Details

This is the plot method for the class "ppm" (see ppm.object for details of this class).

It invokes predict.ppm to compute the spatial trend and conditional intensity of the fitted point process model. See predict.ppm for more explanation about spatial trend and conditional intensity.

The default action is to create a rectangular grid of points in (the bounding box of) the observation window of the data point pattern, and evaluate the spatial trend and conditional intensity of the fitted spatial point process model x at these locations. If the argument locations= is supplied, then the spatial trend and conditional intensity are calculated at the grid of points specified by this argument.

The argument locations, if present, should be a binary image mask (an object of class "owin" and type "mask"). This determines a rectangular grid of locations, or a subset of such a grid, at which predictions will be computed. Binary image masks are conveniently created using as.mask.

The argument covariates gives the values of any spatial covariates at the prediction locations. If the trend formula in the fitted model involves spatial covariates (other than the Cartesian coordinates x, y) then covariates is required.

The argument covariates has the same format and interpretation as in predict.ppm. It may be either a data frame (the number of whose rows must match the number of pixels in locations multiplied by the number of possible marks in the point pattern), or a list of images. If argument locations is not supplied, and covariates is supplied, then it must be a list of images.

If the fitted model was a marked (multitype) point process, then predictions are made for each possible mark value in turn.

If the fitted model had no spatial trend, then the default is to omit calculating this (flat) surface, unless trend=TRUE is set explicitly.

If the fitted model was Poisson, so that there were no spatial interactions, then the conditional intensity and spatial trend are identical, and the default is to omit the conditional intensity, unless cif=TRUE is set explicitly.

If plot.it=TRUE then plot.plotppm() is called upon to plot the class plotppm object which is produced. (That object is also returned, silently.)

Plots are produced successively using persp, image and contour (or only a selection of these three, if how is given). Extra graphical parameters controlling the display may be passed directly via the arguments ... or indirectly reset using spatstat.options.

Value

An object of class plotppm. Such objects may be plotted by plot.plotppm().
This is a list with components named trend and cif, either of which may be missing. They will be missing if the corresponding component does not make sense for the model, or if the corresponding argument was set equal to FALSE.
Both trend and cif are lists of images. If the model is an unmarked point process, then they are lists of length 1, so that trend[[1]] is an image of the spatial trend and cif[[1]] is an image of the conditional intensity.
If the model is a marked point process, then trend[[i]] is an image of the spatial trend for the mark m[i], and cif[[1]] is an image of the conditional intensity for the mark m[i], where m is the vector of levels of the marks.

Warnings

See warnings in predict.ppm.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

plot.plotppm, ppm, ppm.object, predict.ppm, print.ppm, persp, image, contour, plot, spatstat.options

Examples

 ## Not run:
 data(cells)
 m <- ppm(cells, ~1, Strauss(0.05))
 pm <- plot(m) # The object ``pm'' will be plotted as well as saved
               # for future plotting.

## End(Not run)


plot a Spatial Point Pattern

Description

Plot a two-dimensional spatial point pattern

Usage

 ## S3 method for class 'ppp':
 plot(x, main, ..., chars, cols, use.marks=TRUE, add=FALSE,
maxsize, markscale)

Arguments

x | The spatial point pattern to be plotted. An object of class "ppp", or data which can be converted into this format by as.ppp().
main | text to be displayed as a title above the plot.
... | extra arguments that will be passed to the plotting functions plot.default, points and/or symbols.
chars | plotting character(s) used to plot points.
cols | the colour(s) used to plot points.
use.marks | logical flag; if TRUE, plot points using a different plotting symbol for each mark; if FALSE, only the locations of the points will be plotted, using points().
add | logical flag; if TRUE, just the points are plotted, over the existing plot. A new plot is not created, and the window is not plotted.
maxsize | maximum size of the circles/squares plotted when x is a marked point pattern with numerical marks. Incompatible with markscale.
markscale | physical scale factor determining the sizes of the circles/squares plotted when x is a marked point pattern with numerical marks. Incompatible with maxsize.

Details

This is the plot method for point pattern datasets (of class "ppp", see ppp.object).

First the observation window x$window is plotted. Then the points themselves are plotted, in a fashion that depends on their marks, as follows.

unmarked point pattern:
If the point pattern does not have marks, or if use.marks = FALSE, then the locations of all points will be plotted using a single plot character
multitype point pattern:
If x$marks is a factor, then each level of the factor is represented by a different plot character.
continuous marks:
If x$marks is a numeric vector, the marks are rescaled to the unit interval and each point is represented by a circle with radius proportional to the rescaled mark (if the value is positive) or a square with side proportional to the absolute value of the rescaled mark (if the value is negative).
other kinds of marks:
If x$marks is neither numeric nor a factor, then each possible mark will be represented by a different plotting character. The default is to represent the ith smallest mark value by points(..., pch=i).

Plotting of the window x$window is performed by plot.owin. This plot may be modified through the ... arguments. In particular the extra argument border determines the colour of the window.

Plotting of the points themselves is performed by the function points, except for the case of continuous marks, where it is performed by symbols. Their plotting behaviour may be modified through the ... arguments.

The argument chars determines the plotting character or characters used to display the points (in all cases except for the case of continuous marks). For an unmarked point pattern, this should be a single integer or character determining a plotting character (see par("pch")). For a multitype point pattern, chars should be a vector of integers or characters, of the same length as levels(x$marks), and then the ith level or type will be plotted using character chars[i].

If chars is absent, but there is an extra argument pch, then this will determine the plotting character for all points.

The argument cols determines the colour or colours used to display the points. For an unmarked point pattern, or a marked point pattern with continuous marks, this should be a character string determining a colour. For a multitype point pattern, cols should be a character vector, of the same length as levels(x$marks). The ith level or type will be plotted using colour cols[i].

If cols is absent, the colour used to plot all the points may be determined by the extra argument fg (for multitype point patterns) or the extra argument col (for all other cases). Note that col will also reset the colour of the window.

The arguments maxsize and markscale incompatible. They control the physical size of the circles and squares which represent the marks in a point pattern with continuous marks. If markscale is given, then a mark value of m is plotted as a circle of radius m * markscale (if m is positive) or a square of side abs(m) * markscale (if m is negative). If maxsize is given, then the largest mark in absolute value, mmax=max(abs(x$marks)), will be scaled to have physical size maxsize.

The user can set the default values of these plotting parameters using spatstat.options("par.points").

The value returned by this plot function can be used to make a suitable legend, as shown in the examples.

Value

NULL, or a vector giving the correspondence between mark values and plotting characters.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp.object, plot, par, points, plot.owin, symbols

Examples

   data(cells)
   plot(cells)

   plot(cells, pch=16)

   # make the plotting symbols larger (for publication at reduced scale)
   plot(cells, cex=2)

   # set it in spatstat.options
   oldopt <- spatstat.options(par.points=list(cex=2))
   plot(cells)
   spatstat.options(oldopt)

   # multitype
   data(lansing)
   plot(lansing)

   # marked by a real number
   data(longleaf)
   plot(longleaf)

   # just plot the points
   plot(longleaf, use.marks=FALSE)
   plot(unmark(longleaf)) # equivalent

   # controlling COLOURS of points
   plot(cells, cols="blue")
   plot(lansing, cols=c("black", "yellow", "green",
                        "blue","red","pink"))
   plot(longleaf, fg="blue")

   # make window purple
   plot(lansing, border="purple")
   # make everything purple
   plot(lansing, border="purple", cols="purple", col.main="purple")

   # controlling PLOT CHARACTERS
   plot(lansing, chars = 11:16)
   plot(lansing, chars = c("o","h","m",".","o","o"))

   # controlling MARK SCALE
   plot(longleaf, markscale=0.1)

   # draw circles of DIAMETER equal to nearest neighbour distance
   plot(cells %mark% nndist(cells), markscale=1/2)

   # making the legend
   data(amacrine)
   v <- plot(amacrine)
   legend(0.2, 1.2, pch=v, legend=names(v))


plot a Spatial Line Segment Pattern

Description

Plot a two-dimensional line segment pattern

Usage

  ## S3 method for class 'psp':
  plot(x, ..., add=FALSE)

Arguments

x | The line segment pattern to be plotted. An object of class "psp", or data which can be converted into this format by as.psp().
... | extra arguments that will be passed to the plotting functions segments (to plot the segments) and plot.owin (to plot the observation window).
add | Logical. If TRUE, the current plot is not erased; the segments are plotted on top of the current plot, and the window is not plotted.

Details

This is the plot method for line segment pattern datasets (of class "psp", see psp.object). It plots both the observation window x$window and the line segments themselves.

Plotting of the window x$window is performed by plot.owin. This plot may be modified through the ... arguments.

Plotting of the points themselves is performed by the standard R function segments. Its plotting behaviour may also be modified through the ... arguments.

Value

NULL

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

psp.object, plot, par, plot.owin, symbols

Examples

   a <- psp(runif(20), runif(20), runif(20), runif(20), window=owin())
   plot(a)
   plot(a, main="My title")
   plot(a, col="blue")
   plot(a, lwd=3)


plot a Spatial Quadrature Scheme

Description

Plot a two-dimensional spatial quadrature scheme.

Usage

  ## S3 method for class 'quad':
  plot(x, ..., main=deparse(substitute(x)), dum=list())

Arguments

x | The spatial quadrature scheme to be plotted. An object of class "quad".
... | extra arguments controlling the plotting of the data points of the quadrature scheme.
dum | list of extra arguments controlling the plotting of the dummy points of the quadrature scheme. See below.
main | text to be displayed as a title above the plot.

Details

This is the plot method for quadrature schemes (objects of class "quad", see quad.object).

First the data points of the quadrature scheme are plotted (in their observation window) using plot.ppp with any arguments specified in ...

Then the dummy points of the quadrature scheme are plotted using plot.ppp with any arguments specified in dum.

By default the dummy points are superimposed onto the plot of data points. This can be overridden by including the argument add=FALSE in the list dum as shown in the examples. In this case the data and dummy point patterns are plotted separately.

See par and plot.ppp for other possible arguments controlling the plots.

Value

NULL.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

quad.object, plot.ppp, par

Examples

   data(nztrees)
   Q <- quadscheme(nztrees)

   plot(Q, main="NZ trees: quadrature scheme")

   oldpar <- par(mfrow=c(2,1))
   plot(Q, main="NZ trees", dum=list(add=FALSE))
   par(oldpar)


Plot a List of Point Patterns

Description

Plots a list of point patterns.

Usage

  ## S3 method for class 'splitppp':
  plot(x, ..., main, arrange=TRUE, nrows=NULL, ncols=NULL)

Arguments

x | A named list of point patterns, typically obtained from split.ppp.
... | Arguments passed to plot.ppp which control the appearance of each plot panel.
main | Overall heading for the plot.
arrange | Logical flag indicating whether to plot the point patterns side-by-side on a single page (arrange=TRUE) or plot them individually in a succession of frames (arrange=FALSE).
nrows,ncols | Optional. The number of rows/columns in the plot layout (assuming arrange=TRUE). You can specify either or both of these numbers.

Details

This is the plot method for the class "splitppp". It is typically used to plot the result of the function split.ppp but it may also be used to plot any list of point patterns created by the user.

The argument x should be a named list of point patterns (objects of class "ppp", see ppp.object). Each of these point patterns will be plotted in turn using plot.ppp.

Value

Null.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

split.ppp, plot.ppp, ppp.object

Examples

# Multitype point pattern
 data(amacrine)
 plot(split(amacrine))


Poisson Point Process Model

Description

Creates an instance of the Poisson point process model which can then be fitted to point pattern data.

Usage

 Poisson()

Details

The function ppm(), which fits point process models to point pattern data, requires an argument interaction of class "interact" describing the interpoint interaction structure of the model to be fitted. The appropriate description of the Poisson process is provided by the value of the function Poisson().

This works for all types of Poisson processes including multitype and nonstationary Poisson processes.

Value

An object of class "interact" describing the interpoint interaction structure of the Poisson point process (namely, there are no interactions).

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

Strauss, StraussHard

Examples

 data(nztrees)
 ppm(nztrees, ~1, Poisson())
 # fit the stationary Poisson process to 'nztrees'
 # no edge correction needed

 data(longleaf)

 longadult <- longleaf[longleaf$marks >= 30, ]
 longadult <- unmark(longadult)
 ppm(longadult, ~ x, Poisson())
 # fit the nonstationary Poisson process
 # with intensity lambda(x,y) = exp( a + bx)

 data(lansing)
 # trees marked by species

 ppm(lansing, ~ marks, Poisson())
 # fit stationary marked Poisson process
 # with different intensity for each species

## Not run:
 ppm(lansing, ~ marks * polynom(x,y,3), Poisson())
## End(Not run)
 # fit nonstationary marked Poisson process
 # with different log-cubic trend for each species


Fit Point Process Model to Data

Description

Fits a point process model to an observed point pattern

Usage

 ppm(Q, trend=~1, interaction=NULL, ..., covariates=NULL,
 correction="border", rbord=0, use.gam=FALSE, method="mpl",
 forcefit=FALSE, nsim=100, nrmh=1e5,
        start=NULL,
         control=list(nrep=nrmh),
         verb=TRUE)

Arguments

Q | A data point pattern (of class "ppp") to which the model will be fitted, or a quadrature scheme (of class "quad") containing this pattern.
trend | An R formula object specifying the spatial trend to be fitted. The default formula, ~1, indicates the model is stationary and no trend is to be fitted.
interaction | An object of class "interact" describing the point process interaction structure, or NULL indicating that a Poisson process (stationary or nonstationary) should be fitted.
... | Ignored.
covariates | The values of any spatial covariates (other than the Cartesian coordinates) required by the model. Either a data frame, or a list of images. See Details.
correction | The name of the edge correction to be used. The default is "border" indicating the border correction. Other possibilities may include "Ripley", "isotropic", "translate" and "none", depending on the interaction.
rbord | If correction = "border" this argument specifies the distance by which the window should be eroded for the border correction.
use.gam | Logical flag; if TRUE then computations are performed using gam instead of glm.
method | The method used to fit the model. Options are "mpl" for the method of Maximum PseudoLikelihood, and "ho" for the Huang-Ogata approximate maximum likelihood method.
forcefit | Logical flag for internal use. If forcefit=FALSE, some trivial models will be fitted by a shortcut. If forcefit=TRUE, the generic fitting method will always be used.
nsim | Number of simulated realisations to generate (for method="ho")
nrmh | Number of Metropolis-Hastings iterations for each simulated realisation (for method="ho")
start,control | Arguments passed to rmh controlling the behaviour of the Metropolis-Hastings algorithm (for method="ho")
verb | Logical flag indicating whether to print progress reports (for method="ho")

Details

This function fits a point process model to an observed point pattern. The model may include spatial trend, interpoint interaction, and dependence on covariates.

basic use:
In basic use, Q is a point pattern dataset (an object of class "ppp") to which we wish to fit a model.

The syntax of ppm() is closely analogous to the R functions glm and gam. The analogy is:
glm | ppm
formula | trend
family | interaction

The point process model to be fitted is specified by the arguments trend and interaction which are respectively analogous to the formula and family arguments of glm().

Systematic effects (spatial trend and/or dependence on spatial covariates) are specified by the argument trend. This is an R formula object, which may be expressed in terms of the Cartesian coordinates x, y, the marks marks, or the variables in covariates (if supplied), or both. It specifies the logarithm of the first order potential of the process. The formula should not use any names beginning with .mpl as these are reserved for internal use. If trend is absent or equal to the default, ~1, then the model to be fitted is stationary (or at least, its first order potential is constant).

Stochastic interactions between random points of the point process are defined by the argument interaction. This is an object of class "interact" which is initialised in a very similar way to the usage of family objects in glm and gam. The families currently available are: Poisson, Strauss, StraussHard, MultiStrauss, MultiStraussHard, Softcore, DiggleGratton, Pairwise, PairPiece, Geyer, LennardJones, Saturated, OrdThresh, and Ord. See the examples below.

If interaction is missing or NULL, then the model to be fitted has no interpoint interactions, that is, it is a Poisson process (stationary or nonstationary according to trend). In this case the method of maximum pseudolikelihood coincides with maximum likelihood.

The fitted point process model returned by this function can be printed (by the print method print.ppm) to inspect the fitted parameter values. If a nonparametric spatial trend was fitted, this can be extracted using the predict method predict.ppm.

Models with covariates:
To fit a model involving spatial covariates other than the Cartesian coordinates x and y, the values of the covariates should be supplied in the argument covariates. Note that it is not sufficient to have observed the covariate only at the points of the data point pattern; the covariate must also have been observed at other locations in the window.

The argument covariates, if supplied, should be either a list of images, or a data frame.

Typically covariates is a list of images, each image giving the values of a spatial covariate at a fine grid of locations. The argument covariates should then be a named list, with the names corresponding to the names of covariates in the model formula trend. Each entry in the list must be an image object (of class "im", see im.object). The software will look up the pixel values of each image at the required locations (quadrature points). In this case the argument Q may be either a quadrature scheme or a point pattern.

The variable names x, y and marks are reserved for the Cartesian coordinates and the mark values, and these should not be used for variables in covariates.

If covariates is a data frame, Q must be a quadrature scheme (see under Quadrature Schemes below). Then covariates must have as many rows as there are points in Q. The ith row of covariates should contain the values of spatial variables which have been observed at the ith point of Q.

Quadrature schemes:
In advanced use, Q may be a `quadrature scheme'. This was originally just a technicality but it has turned out to have practical uses, as we explain below.

Quadrature schemes are required for our implementation of the method of maximum pseudolikelihood. The definition of the pseudolikelihood involves an integral over the spatial window containing the data. In practice this integral must be approximated by a finite sum over a set of quadrature points. We use the technique of Baddeley and Turner (2000), a generalisation of the Berman-Turner (1992) device. In this technique the quadrature points for the numerical approximation include all the data points (points of the observed point pattern) as well as additional `dummy' points.

A quadrature scheme is an object of class "quad" (see quad.object) which specifies both the data point pattern and the dummy points for the quadrature scheme, as well as the quadrature weights associated with these points. If Q is simply a point pattern (of class "ppp", see ppp.object) then it is interpreted as specifying the data points only; a set of dummy points specified by default.dummy() is added, and the default weighting rule is invoked to compute the quadrature weights.

Finer quadrature schemes (i.e. those with more dummy points) generally yield a better approximation, at the expense of higher computational load. Complete control over the quadrature scheme is possible. See quadscheme for an overview.

A practical advantage of quadrature schemes arises when we want to fit a model involving covariates (e.g. soil pH). Suppose we have only been able to observe the covariates at a small number of locations. Suppose cov.dat is a data frame containing the values of the covariates at the data points (i.e. cov.dat[i,] contains the observations for the ith data point) and cov.dum is another data frame (with the same columns as cov.dat) containing the covariate values at another set of points whose locations are given by the point pattern Y. Then setting Q = quadscheme(X,Y) combines the data points and dummy points into a quadrature scheme, and covariates = rbind(cov.dat, cov.dum) combines the covariate data frames. We can then fit the model by calling ppm(Q, ..., covariates).

Model-fitting technique:
The model may be fitted either by the method of maximum pseudolikelihood (Besag, 1975) or by the approximate maximum likelihood method of Huang and Ogata (1999). Maximum pseudolikelihood is much faster, but has poorer statistical properties.

In either case, the algorithm will begin by fitting the model by maximum pseudolikelihood. By default the algorithm returns the maximum pseudolikelihood fit.

Maximum pseudolikelihood is equivalent to maximum likelihood for Poisson point processes.

Note that the method of maximum pseudolikelihood is believed to be inefficient and biased for point processes with strong interpoint interactions. In such cases, the Huang-Ogata approximate maximum likelihood method should be used, although maximum pseudolikelihood may also be used profitably for model selection in the initial phases of modelling.

Huang-Ogata method:
If method="ho" then the model will be fitted using the Huang-Ogata (1999) approximate maximum likelihood method. First the model is fitted by maximum pseudolikelihood as described above, yielding an initial estimate of the parameter vector theta0. From this initial model, nsim simulated realisations are generated. The score and Fisher information of the model at theta=theta0 are estimated from the simulated realisations. Then one step of the Fisher scoring algorithm is taken, yielding an updated estimate theta1. The corresponding model is returned.

Simulated realisations are generated using rmh. The iterative behaviour of the Metropolis-Hastings algorithm is controlled by the arguments start and control which are passed to rmh.

As a shortcut, the argument nrmh determines the number of Metropolis-Hastings iterations run to produce one simulated realisation (if control is absent). Also if start is absent or equal to NULL, it defaults to list(n.start=N) where N is the number of points in the data point pattern.

Edge correction
Edge correction should be applied to the sufficient statistics of the model, to reduce bias. The argument correction is the name of an edge correction method. The default correction="border" specifies the border correction, in which the quadrature window (the domain of integration of the pseudolikelihood) is obtained by trimming off a margin of width rbord from the observation window of the data pattern. Not all edge corrections are implemented (or implementable) for arbitrary windows. Other options depend on the argument interaction, but these generally include correction="periodic" (the periodic or toroidal edge correction in which opposite edges of a rectangular window are identified) and correction="translate" (the translation correction, see Baddeley 1998 and Baddeley and Turner 2000). For pairwise interaction models there is also Ripley's isotropic correction, identified by correction="isotropic" or "Ripley".

Value

An object of class "ppm" describing a fitted point process model.
The fitted parameters can be obtained just by printing this object. Fitted spatial trends can be extracted using the predict method for this object (see predict.ppm).
See ppm.object for details of the format of this object.

Warnings

The implementation of the Huang-Ogata method is experimental.

See the comments above about the possible inefficiency and bias of the maximum pseudolikelihood estimator.

The accuracy of the Berman-Turner approximation to the pseudolikelihood depends on the number of dummy points used in the quadrature scheme. The number of dummy points should at least equal the number of data points.

The parameter values of the fitted model do not necessarily determine a valid point process. Some of the point process models are only defined when the parameter values lie in a certain subset. For example the Strauss process only exists when the interaction parameter gamma is less than or equal to 1, corresponding to a value of ppm()$theta[2] less than or equal to 0. The current version of ppm maximises the pseudolikelihood without constraining the parameters, and does not apply any checks for sanity after fitting the model.

The trend formula should not use any variable names beginning with the prefixes .mpl or Interaction as these names are reserved for internal use. The data frame covariates should have as many rows as there are points in Q. It should not contain variables called x, y or marks as these names are reserved for the Cartesian coordinates and the marks.

If the model formula involves one of the functions poly(), bs() or ns() (e.g. applied to spatial coordinates x and y), the fitted coefficients can be misleading. The resulting fit is not to the raw spatial variates (x, x^2, x*y, etc.) but to a transformation of these variates. The transformation is implemented by poly() in order to achieve better numerical stability. However the resulting coefficients are appropriate for use with the transformed variates, not with the raw variates. This affects the interpretation of the constant term in the fitted model, logbeta. Conventionally, beta is the background intensity, i.e. the value taken by the conditional intensity function when all predictors (including spatial or ``trend'' predictors) are set equal to 0. However the coefficient actually produced is the value that the log conditional intensity takes when all the predictors, including the transformed spatial predictors, are set equal to 0, which is not the same thing.

Worse still, the result of predict.ppm can be completely wrong if the trend formula contains one of the functions poly(), bs() or ns(). This is a weakness of the underlying function predict.glm.

If you wish to fit a polynomial trend, we offer an alternative to poly(), namely polynom(), which avoids the difficulty induced by transformations. It is completely analogous to poly except that it does not orthonormalise. The resulting coefficient estimates then have their natural interpretation and can be predicted correctly. Numerical stability may be compromised.

Values of the maximised pseudolikelihood are not comparable if they have been obtained with different values of rbord.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A. and Turner, R. Practical maximum pseudolikelihood for spatial point patterns. Australian and New Zealand Journal of Statistics 42 (2000) 283–322.

Berman, M. and Turner, T.R. Approximating point process likelihoods with GLIM. Applied Statistics 41 (1992) 31–38.

Besag, J. Statistical analysis of non-lattice data. The Statistician 24 (1975) 179-195.

Diggle, P.J., Fiksel, T., Grabarnik, P., Ogata, Y., Stoyan, D. and Tanemura, M. On parameter estimation for pairwise interaction processes. International Statistical Review 62 (1994) 99-117.

Huang, F. and Ogata, Y. Improvements of the maximum pseudo-likelihood estimators in various spatial statistical models. Journal of Computational and Graphical Statistics 8 (1999) 510-530.

Jensen, J.L. and Moeller, M. Pseudolikelihood for exponential family models of spatial point processes. Annals of Applied Probability 1 (1991) 445–461.

Jensen, J.L. and Kuensch, H.R. On asymptotic normality of pseudo likelihood estimates for pairwise interaction processes, Annals of the Institute of Statistical Mathematics 46 (1994) 475-486.

See Also

ppp, quadscheme, ppm.object, Poisson, Strauss, StraussHard, MultiStrauss, MultiStraussHard, Softcore, DiggleGratton, Pairwise, PairPiece, Geyer, LennardJones, Saturated, OrdThresh, Ord

Examples

 data(nztrees)
 ppm(nztrees)
 # fit the stationary Poisson process
 # to point pattern 'nztrees'

 Q <- quadscheme(nztrees)
 ppm(Q)
 # equivalent.

 ppm(nztrees, ~ x)
 # fit the nonstationary Poisson process
 # with intensity function lambda(x,y) = exp(a + bx)
 # where x,y are the Cartesian coordinates
 # and a,b are parameters to be estimated

 ppm(nztrees, ~ polynom(x,2))
 # fit the nonstationary Poisson process
 # with intensity function lambda(x,y) = exp(a + bx + cx^2)

 library(splines)
 ppm(nztrees, ~ bs(x,df=3))
 #       WARNING: do not use predict.ppm() on this result
 # Fits the nonstationary Poisson process
 # with intensity function lambda(x,y) = exp(B(x))
 # where B is a B-spline with df = 3

 ppm(nztrees, ~1, Strauss(r=10), rbord=10)
 # Fit the stationary Strauss process with interaction range r=10
 # using the border method with margin rbord=10

 ppm(nztrees, ~ x, Strauss(13), correction="periodic")
 # Fit the nonstationary Strauss process with interaction range r=13
 # and exp(first order potential) =  activity = beta(x,y) = exp(a+bx)
 # using the periodic correction.

# Huang-Ogata fit:
## Not run: ppm(nztrees, ~1, Strauss(r=10), rbord=10, method="ho")

 # COVARIATES
 #
 X <- rpoispp(42)
 weirdfunction <- function(x,y){ 10 * x^2 + runif(length(x))}
 Zimage <- as.im(weirdfunction, unit.square())
 #
 # (a) covariate values in pixel image
 ppm(X, ~ y + Z, covariates=list(Z=Zimage))
 #
 # (b) covariate values in data frame
 Q <- quadscheme(X)
 xQ <- x.quad(Q)
 yQ <- y.quad(Q)
 Zvalues <- weirdfunction(xQ,yQ)
 ppm(Q, ~ y + Z, covariates=data.frame(Z=Zvalues))
 # Note Q not X

 ## MULTITYPE POINT PROCESSES ###
 data(lansing)
 # Multitype point pattern --- trees marked by species

 # fit stationary marked Poisson process
 # with different intensity for each species
## Not run: ppm(lansing, ~ marks, Poisson())

 # fit nonstationary marked Poisson process
 # with different log-cubic trend for each species
## Not run: ppm(lansing, ~ marks * polynom(x,y,3), Poisson())


Class of Fitted Point Process Models

Description

A class ppm to represent a fitted stochastic model for a point process. The output of ppm.

Details

An object of class ppm represents a stochastic point process model that has been fitted to a point pattern dataset. Typically it is the output of the model fitter, ppm.

There are methods print.ppm, plot.ppm, predict.ppm, fitted.ppm and coef.ppm for the generic functions print, plot, predict, fitted and coef respectively.

See also (for example) Strauss to understand how to specify a point process model with unknown parameters.

Information about the data (to which the model was fitted) can be extracted using data.ppm, dummy.ppm and quad.ppm.

If you really need to get at the internals, a ppm object contains at least the following entries:
coef | the fitted regular parameters (as returned by glm)
trend | the trend formula or NULL
interaction | the point process interaction family (an object of class "interact") or NULL
Q | the quadrature scheme used
maxlogpl | the maximised value of log pseudolikelihood
correction | name of edge correction method used

See ppm for explanation of these concepts. The irregular parameters (e.g. the interaction radius of the Strauss process) are encoded in the interaction entry. However see the Warnings.

Warnings

The internal representation may change in the next few releases of the spatstat package.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppm, coef.ppm, fitted.ppm, print.ppm, predict.ppm, plot.ppm.

Examples

  data(cells)
  fit <- ppm(cells, ~ x, Strauss(0.1), correction="periodic")
  fit
  coef(fit)
  ## Not run:
  pred <- predict(fit)

## End(Not run)
  pred <- predict(fit, ngrid=20, type="trend")
  ## Not run:
  plot(fit)

## End(Not run)


Create a Point Pattern

Description

Creates an object of class "ppp" representing a point pattern dataset in the two-dimensional plane.

Usage

  ppp(x,y, ..., window, marks, check=TRUE)

Arguments

x | Vector of x coordinates of data points
y | Vector of y coordinates of data points
window | window of observation, an object of class "owin"
... | arguments passed to owin to create the window, if window is missing
marks | (optional) vector of mark values
check | Logical flag indicating whether to check that all the (x,y) points lie inside the specified window. Do not set this to FALSE unless you are sure that this check is unnecessary.

Details

In the spatstat library, a point pattern dataset is described by an object of class "ppp". This function creates such objects.

The vectors x and y must be numeric vectors of equal length. They are interpreted as the cartesian coordinates of the points in the pattern.

A point pattern dataset is assumed to have been observed within a specific region of the plane called the observation window. An object of class "ppp" representing a point pattern contains information specifying the observation window. This window must always be specified when creating a point pattern dataset; there is intentionally no default action of ``guessing'' the window dimensions from the data points alone.

You can specify the observation window in several (mutually exclusive) ways:

  • xrange, yrange specify a rectangle with these dimensions;
  • poly specifies a polygonal boundary. If the boundary is a single polygon then poly must be a list with components x,y giving the coordinates of the vertices. If the boundary consists of several disjoint polygons then poly must be a list of such lists so that poly[[i]]$x gives the x coordinates of the vertices of the ith boundary polygon.
  • mask specifies a binary pixel image with entries that are TRUE if the corresponding pixel is inside the window.
  • window is an object of class "owin" (see owin.object) specifying the window.

The arguments xrange, yrange or poly or mask are passed to the window creator function owin for interpretation. See owin for further details.

The argument window, if given, must be an object of class "owin". It is a full description of the window geometry, and could have been obtained from owin or as.owin, or by just extracting the observation window of another point pattern, or by manipulating such windows. See owin or the Examples below.

The points with coordinates x and y must lie inside the specified window, in order to define a valid object of this class. Any points which do not lie inside the window will be removed from the point pattern, and a warning will be issued. The rejected points are still accessible, as an attribute of the point pattern called "rejects", but will be ignored by all other functions except link{plot.ppp}.

The optional argument marks is given if the point pattern is marked, i.e. if each data point carries additional information. For example, points which are classified into two or more different types, or colours, may be regarded as having a mark which identifies which colour they are. Data recording the locations and heights of trees in a forest can be regarded as a marked point pattern where the mark is the tree height.

In the current implementation, marks must be a vector, of the same length as x and y, which is interpreted so that marks[i] is the mark attached to the point (x[i],y[i]). If the mark is a real number then marks should be a numeric vector, while if the mark takes only a finite number of possible values (e.g. colours or types) then marks should be a factor.

See ppp.object for a description of the class "ppp".

Users would normally invoke ppp to create a point pattern, but the functions as.ppp and scanpp may sometimes be convenient.

Value

An object of class "ppp" describing a point pattern in the two-dimensional plane (see ppp.object).

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp.object, as.ppp, owin.object, owin, as.owin

Examples

  # some arbitrary coordinates in [0,1]
  x <- runif(20)
  y <- runif(20)

  # the following are equivalent
  X <- ppp(x, y, c(0,1), c(0,1))
  X <- ppp(x, y)
  X <- ppp(x, y, window=owin(c(0,1),c(0,1)))

  ## Not run: plot(X)

  # marks
  m <- sample(1:2, 20, replace=TRUE)
  m <- factor(m, levels=1:2)
  X <- ppp(x, y, c(0,1), c(0,1), marks=m)
  ## Not run: plot(X)

  # polygonal window
  X <- ppp(x, y, poly=list(x=c(0,10,0), y=c(0,0,10)))
  ## Not run: plot(X)

  # copy the window from another pattern
  data(cells)
  X <- ppp(x, y, window=cells$window)


Class of Point Patterns

Description

A class "ppp" to represent a two-dimensional point pattern. Includes information about the window in which the pattern was observed. Optionally includes marks.

Details

This class represents a two-dimensional point pattern dataset. It specifies

  • the locations of the points
  • the window in which the pattern was observed
  • optionally, a ``mark'' attached to each point (extra information such as a type label).

If X is an object of type ppp, it contains the following elements:
x | vector of x coordinates of data points
y | vector of y coordinates of data points
n | number of points
window | window of observation
 | (an object of class owin)
marks | optional vector of marks

Users are strongly advised not to manipulate these entries directly.

Objects of class "ppp" may be created by the function ppp and converted from other types of data by the function as.ppp. Note that you must always specify the window of observation; there is intentionally no default action of ``guessing'' the window dimensions from the data points alone.

Standard point pattern datasets provided with the package include amacrine, betacells, bramblecanes, cells, demopat, ganglia, lansing, longleaf, nztrees, redwood, simdat and swedishpines. Use data(xxx) to access the dataset xxx.

Point patterns may be scanned from your own data files by scanpp or by using read.table and as.ppp.

They may be manipulated by the functions subset.ppp, [.ppp and superimpose.

Point pattern objects can be plotted just by typing plot(X) which invokes the plot method for point pattern objects, plot.ppp. See plot.ppp for further information.

There are also methods for summary and print for point patterns. Use summary(X) to see a useful description of the data.

Patterns may be generated at random by runifpoint, rpoispp, rMaternI, rMaternII, rSSI, rNeymanScott, rMatClust, and rThomas.

Most functions which are intended to operate on a window (of class owin) will, if presented with a ppp object instead, automatically extract the window information from the point pattern.

Warnings

The internal representation of marks is likely to change in the next release of this package.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin, ppp, as.ppp, [.ppp

Examples

  x <- runif(100)
  y <- runif(100)
  X <- ppp(x, y, c(0,1),c(0,1))
  X
  ## Not run: plot(X)
  mar <- sample(1:3, 100, replace=TRUE)
  mm <- ppp(x, y, c(0,1), c(0,1), marks=mar)
  ## Not run: plot(mm)
  # points with mark equal to 2
  ss <- mm[ mm$marks == 2 , ]
  ## Not run: plot(ss)
  # left half of pattern 'mm'
  lu <- owin(c(0,0.5),c(0,1))
  mmleft <- mm[ , lu]
  ## Not run: plot(mmleft)
  ## Not run:
  # input data from file
  qq <- scanpp("my.table", unit.square())

  # interactively build a point pattern
  plot(unit.square())
  X <- as.ppp(locator(10), unit.square())
  plot(X)
  ## End(Not run)


Optimal Match Between Two Point Patterns

Description

Given two point patterns, find the optimal match between them.

Usage

  pppdist(X, Y, q = 1, precision = 7, show.rprimal = FALSE, belowone = TRUE, timelag = 0)

Arguments

X,Y | Two point patterns (objects of class "ppp").
q | Exponent of the Wasserstein distance (or Inf for the Prohorov distance).
precision | Index controlling accuracy of algorithm. Interpoint distances will be rounded to the nearest multiple of 10^(-precision).
show.rprimal | Logical. Whether to display a plot showing the iterative solution of the restricted primal problem.
belowone | Logical. Experimental use only. Indicates whether to rescale the distances by a fudge factor.
timelag | Time lag, in seconds, between successive displays of the iterative solution of the restricted primal problem.

Details

Finds the matching between the point patterns X and Y which minimises the sum of the distances between matched points (if q=1), the maximum distance between matched points (if q=Inf), and in general the 1/qth power of the sum of the qth powers of the distances between matched points. If q < 1 this is known as the Wasserstein distance, and if q = infty it is the Prohorov distance.

For finite exponents q, there is a fast C algorithm, which will handle patterns of 100 points without difficulty, but should not be used with thousands of points. If show.rprimal=TRUE, slower interpreted code is used to demonstrate the algorithm. For q=Inf, even slower interpreted R code is used, and this works only for very small point patterns.

Value

An object of class pppmatching that represents the matching. There are methods for plot, print and summary for this class.

Author(s)

Dominic Schuhmacher.

See Also

Examples

   X <- runifpoint(42)
   Y <- runifpoint(42)
   pppdist(X, Y)
   pppdist(X[1:10], Y[1:10], q=Inf)


Prediction from a Fitted Point Process Model

Description

Given a fitted point process model obtained by ppm, evaluate the spatial trend and the conditional intensity of the model at new locations.

Usage

   ## S3 method for class 'ppm':
   predict(object, window, ngrid=NULL, locations=NULL,
   covariates=NULL, type="trend", ..., check=TRUE, repair=TRUE)

Arguments

object | A fitted point process model, typically obtained from the model-fitting algorithm ppm. An object of class "ppm" (see ppm.object).
window | window delimiting the locations where predictions should be computed. Defaults to the window of the original data used to fit the model object.
ngrid | dimensions (either (ngrid[1] by ngrid[2] or ngrid by ngrid) of a rectangular grid of locations inside window where predictions should be computed. (Incompatible with locations)
locations | data giving the x,y coordinates (and marks, if required) at which predictions should be computed. Either a data frame or a binary image mask. (Incompatible with ngrid)
covariates | Values of external covariates required by the model. Either a data frame or a list of images. See Details.
type | character string. Indicates which property of the fitted model should be predicted. Options are "trend" for the spatial trend, and "cif" or "lambda" for the conditional intensity.
... | Ignored.
check | Logical value indicating whether to check the internal format of object. If there is any possibility that this object has been restored from a dump file, or has otherwise lost track of the environment where it was originally computed, set check=TRUE.
repair | Logical value indicating whether to repair the internal format of object, if it is found to be damaged.

Details

This function computes the spatial trend and the conditional intensity of a fitted spatial point process model. See Baddeley and Turner (2000) for explanation and examples.

Given a point pattern dataset, we may fit a point process model to the data using the model-fitting algorithm ppm. This returns an object of class "ppm" representing the fitted point process model (see ppm.object). The parameter estimates in this fitted model can be read off simply by printing the ppm object. The spatial trend and conditional intensity of the fitted model are evaluated using this function predict.ppm.

The default action is to create a rectangular grid of points in the observation window of the data point pattern, and evaluate the spatial trend and conditional intensity at these locations.

Note that by ``spatial trend'' we mean the (exponentiated) first order potential and not the intensity of the process. [For example if we fit the stationary Strauss process with parameters beta and gamma, then the spatial trend is constant and equal to beta. ] The conditional intensity lambda(u,X) of the fitted model is evaluated at each required spatial location u, with respect to the data point pattern X.

If the argument ngrid is present, then predictions are performed at an ngrid by ngrid pixel grid of locations in the window window. The result of prediction will be a pixel image or images.

If locations is present, then predictions will be performed at the spatial locations given by this dataset. The result of prediction will be either a vector of values or a pixel image or a list of images, depending on the format of locations.

The argument locations may be either a data frame or list specifying arbitrary locations, or a binary image mask (an object of class "owin" with type "mask") specifying (a subset of) a rectangular grid of locations.

If locations is a data frame or list, then it must contain vectors locations$x and locations$y specifying the x,y coordinates of the prediction locations. Additionally, if the model is a marked point process, then locations must also contain a factor locations$marks specifying the marks of the prediction locations. These vectors must have equal length. The result of prediction will be a vector of predicted values, of the same length.

If locations is a binary image mask, then prediction will be performed at each pixel in this binary image where the pixel value is TRUE (in other words, at each pixel that is inside the window). If the fitted model is an unmarked point process, then the result of prediction will be an image. If the fitted model is a marked point process, then prediction will be performed for each possible value of the mark at each such location, and the result of prediction will be a list of images, one for each mark value.

If neither ngrid nor locations is given, then ngrid is assumed. It defaults to 50.

The argument covariates gives the values of any spatial covariates at the prediction locations. If the trend formula in the fitted model involves spatial covariates (other than the Cartesian coordinates x, y) then covariates is required.

The format and use of covariates are analogous to those of the argument of the same name in ppm. It is either a data frame or a list of images.

If covariates is a list of images, then the names of the entries should correspond to the names of covariates in the model formula trend. Each entry in the list must be an image object (of class "im", see im.object). The software will look up the pixel values of each image at the quadrature points.

If covariates is a data frame, then the ith row of covariates is assumed to contain covariate data for the ith location. When locations is a data frame, this just means that each row of covariates contains the covariate data for the location specified in the corresponding row of locations. When locations is a binary image mask, the row covariates[i,] must correspond to the location x[i],y[i] where x = as.vector(raster.x(locations)) and y = as.vector(raster.y(locations)).

Note that if you only want to use prediction in order to generate a plot of the predicted values, it may be easier to use plot.ppm which calls this function and plots the results.

Value

If locations is given and is a data frame: a vector of predicted values for the spatial locations (and marks, if required) given in locations.
If ngrid is given, or if locations is given and is a binary image mask: If object is an unmarked point process, the result is an image object (of class "im", see im.object) containing the predictions. If object is a multitype point process, the result is a list of images, containing the predictions for each type at the same grid of locations.
The ``predicted values'' are either values of the spatial trend (if type="trend") or values of the conditional intensity (if type="cif" or type="lambda").

Warnings

The current implementation invokes predict.glm so that prediction is wrong if the trend formula in object involves terms in ns(), bs() or poly(). This is a weakness of predict.glm itself!

Error messages may be very opaque, as they tend to come from deep in the workings of predict.glm. If you are passing the covariates argument and the function crashes, it is advisable to start by checking that all the conditions listed above are satisfied.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A. and Turner, R. Practical maximum pseudolikelihood for spatial point patterns. Australian and New Zealand Journal of Statistics 42 (2000) 283–322.

Berman, M. and Turner, T.R. Approximating point process likelihoods with GLIM. Applied Statistics 41 (1992) 31–38.

See Also

ppm, ppm.object, plot.ppm, print.ppm, fitted.ppm

Examples

  data(cells)
  m <- ppm(cells, ~ polynom(x,y,2), Strauss(0.05), rbord=0.05)
  trend <- predict(m, type="trend")
  ## Not run:
  image(trend)
  points(cells)

## End(Not run)
  cif <- predict(m, type="cif")
  ## Not run:
  persp(cif)

## End(Not run)


Print Brief Details of an Image

Description

Prints a very brief description of a pixel image object.

Usage

  ## S3 method for class 'im':
  print(x, ...)

Arguments

x | Pixel image (object of class "im").
... | Ignored.

Details

A very brief description of the pixel image x is printed.

This is a method for the generic function print.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

print, im.object, summary.im

Examples

  data(letterR)
  U <- as.im(letterR)
  U


Print Brief Details of a Spatial Window

Description

Prints a very brief description of a window object.

Usage

  ## S3 method for class 'owin':
  print(x, ...)

Arguments

x | Window (object of class "owin").
... | Ignored.

Details

A very brief description of the window x is printed.

This is a method for the generic function print.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

print, print.ppp, summary.owin

Examples

  owin()  # the unit square

  data(demopat)
  W <- demopat$window
  W                    # just says it is polygonal
  as.mask(W)           # just says it is a binary image


Print a Fitted Point Process Model

Description

Default print method for a fitted point process model.

Usage

 ## S3 method for class 'ppm':
 print(x,...)

Arguments

x | A fitted point process model, typically obtained from the model-fittingg algorithm ppm. An object of class "ppm".
... | Ignored.

Details

This is the print method for the class "ppm". It prints information about the fitted model in a sensible format.

See ppm.object for details of the class "ppm".

Value

none.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppm, ppm.object, plot.ppm, predict.ppm

Examples

 ## Not run:
 data(cells)
 Q <- quadscheme(cells)
 m <- ppm(Q, ~1, Strauss(0.05))
 m

## End(Not run)


Print Brief Details of a Point Pattern Dataset

Description

Prints a very brief description of a point pattern dataset.

Usage

  ## S3 method for class 'ppp':
  print(x, ...)

Arguments

x | Point pattern (object of class "ppp").
... | Ignored.

Details

A very brief description of the point pattern x is printed.

This is a method for the generic function print.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

print, print.owin, summary.ppp

Examples

  data(cells)      # plain vanilla point pattern
  cells

  data(lansing)    # multitype point pattern
  lansing

  data(longleaf)    # numeric marks
  longleaf

  data(demopat)     # weird polygonal window
  demopat


Print Brief Details of a Line Segment Pattern Dataset

Description

Prints a very brief description of a line segment pattern dataset.

Usage

  ## S3 method for class 'psp':
  print(x, ...)

Arguments

x | Line segment pattern (object of class "psp").
... | Ignored.

Details

A very brief description of the line segment pattern x is printed.

This is a method for the generic function print.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

print, print.owin, summary.psp

Examples

  a <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
  a


Print a Quadrature Scheme

Description

print method for a quadrature scheme.

Usage

 ## S3 method for class 'quad':
 print(x,...)

Arguments

x | A quadrature scheme object, typically obtained from quadscheme. An object of class "quad".
... | Ignored.

Details

This is the print method for the class "quad". It prints simple information about the quadrature scheme.

See quad.object for details of the class "quad".

Value

none.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

quadscheme, quad.object, plot.quad, summary.quad

Examples

 data(cells)
 Q <- quadscheme(cells)
 Q


Profile Maximum Pseudolikelihood

Description

Fits point process models by profile maximum pseudolikelihood

Usage

profilepl(s, f, ..., rbord = NULL, verbose = TRUE)

Arguments

s | Data frame containing values of the irregular parameters over which the profile pseudolikelihood will be computed.
f | Function (such as Strauss) that generates an interpoint interaction object, given the values of the irregular parameters.
... | Data passed to ppm to fit the model.
rbord | Radius for border correction (same for all models). If omitted, this will be computed from the interactions.
verbose | Logical flag indicating whether to print progress reports.

Details

The model-fitting function ppm fits point process models to point pattern data. However, only the ‘regular’ parameters of the model can be fitted by ppm. The model may also depend on ‘irregular’ parameters that must be fixed in any call to ppm.

This function profilepl is a wrapper which finds the values of the irregular parameters that give the best fit. It uses the method of maximum profile pseudolikelihood.

The argument f would typically be one of the functions Strauss, StraussHard, Softcore, DiggleGratton, Geyer, LennardJones or OrdThresh. For the moment, assume this is so.

The argument s must be a data frame whose columns contain values of the irregular parameters. The names of the columns of s must match the argument names of f.

To apply the method of profile maximum pseudolikelihood, each row of s will be taken in turn; the parameter values in this row will be passed to f, resulting in an interaction object. Then ppm will be applied to the data ... using this interaction; this results in a fitted point process model. The value of the log pseudolikelihood from this model is stored. After all rows of s have been processed in this way, the row giving the maximum value of log pseudolikelihood will be found.

The object returned by profilepl contains the profile pseudolikelihood function, the best fitting model, and other data. It can be plotted (yielding a plot of the log pseudolikelihood values against the irregular parameters) or printed (yielding information about the best fitting values of the irregular parameters).

In general, f may be any function that will return an interaction object (object of class "interact") that can be used in a call to ppm. Each argument of f must be a single value.

Value

An object of class "profilepl". There are methods for plot and print for this class.
The components of the object include

fit | Best-fitting model
param | The data frame s

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

Examples

    data(cells)

    # one irregular parameter
    s <- data.frame(r=seq(0.05,0.15, by=0.01))

    ps <- profilepl(s, Strauss, cells)
    ps
    plot(ps)

    # two irregular parameters
    s <- expand.grid(r=seq(0.05,0.15, by=0.01),sat=1:3)

    pg <- profilepl(s, Geyer, cells)
    pg
    plot(pg)
    ## Not run:
    pg$fit

## End(Not run)


Print Progress Reports

Description

Prints Progress Reports during a loop or iterative calculation.

Usage

progressreport(i, n, every = max(1, ceiling(n/100)), nperline = min(charsperline, every * ceiling(charsperline/(every + 3))), charsperline = 60)

Arguments

i | Integer. The current iteration number (from 1 to n).
n | Integer. The (maximum) number of iterations to be computed.
every | Optional integer. The number of iterations between successive reports.
nperline | Optional integer. The maximum number of reports to be printed per line of output.
charsperline | Optional integer. The number of characters in a line of output.

Details

This is a convenient function for reporting progress during an iterative sequence of calculations or a suite of simulations.

Value

Null.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

Examples

  for(i in 1:40) progressreport(i, 40)


Create a Line Segment Pattern

Description

Creates an object of class "psp" representing a line segment pattern in the two-dimensional plane.

Usage

  psp(x0,y0, x1, y1, window, marks=NULL)

Arguments

x0 | Vector of x coordinates of first endpoint of each segment
y0 | Vector of y coordinates of first endpoint of each segment
x1 | Vector of x coordinates of second endpoint of each segment
y1 | Vector of y coordinates of second endpoint of each segment
window | window of observation, an object of class "owin"
marks | (optional) vector of mark values

Details

In the spatstat library, a spatial pattern of line segments is described by an object of class "psp". This function creates such objects.

The vectors x0, y0, x1 and y1 must be numeric vectors of equal length. They are interpreted as the cartesian coordinates of the endpoints of the line segments.

A line segment pattern is assumed to have been observed within a specific region of the plane called the observation window. An object of class "psp" representing a point pattern contains information specifying the observation window. This window must always be specified when creating a point pattern dataset; there is intentionally no default action of ``guessing'' the window dimensions from the data points alone.

The argument window must be an object of class "owin". It is a full description of the window geometry, and could have been obtained from owin or as.owin, or by just extracting the observation window of another dataset, or by manipulating such windows. See owin or the Examples below.

The optional argument marks is given if the line segment pattern is marked, i.e. if each line segment carries additional information. For example, line segments which are classified into two or more different types, or colours, may be regarded as having a mark which identifies which colour they are.

In the current implementation, marks must be a vector, of the same length as x0, which is interpreted so that marks[i] is the mark attached to the ith line segment. If the mark is a real number then marks should be a numeric vector, while if the mark takes only a finite number of possible values (e.g. colours or types) then marks should be a factor.

See psp.object for a description of the class "psp".

Users would normally invoke psp to create a line segment pattern, and the function as.psp to convert data in another format into a line segment pattern.

Value

An object of class "psp" describing a line segment pattern in the two-dimensional plane (see psp.object).

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

psp.object, as.psp, owin.object, owin, as.owin

Examples

  X <- psp(runif(20), runif(20), runif(20), runif(20),  window=owin())


Class of Line Segment Patterns

Description

A class "psp" to represent a spatial pattern of line segments in the plane. Includes information about the window in which the pattern was observed. Optionally includes marks.

Details

An object of this class represents a two-dimensional pattern of line segments. It specifies

  • the locations of the line segments (both endpoints)
  • the window in which the pattern was observed
  • optionally, a ``mark'' attached to each line segment (extra information such as a type label).

If X is an object of type psp, it contains the following elements:
ends | data frame with entries x0, y0, x1, y1
 | giving coordinates of segment endpoints
window | window of observation
 | (an object of class owin)
n | number of line segments
marks | optional vector of marks

Users are strongly advised not to manipulate these entries directly.

Objects of class "psp" may be created by the function psp and converted from other types of data by the function as.psp. Note that you must always specify the window of observation; there is intentionally no default action of ``guessing'' the window dimensions from the line segments alone.

Subsets of a line segment pattern may be obtained by the functions subset.psp, [.psp and clip.psp.

Line segment pattern objects can be plotted just by typing plot(X) which invokes the plot method for line segment pattern objects, plot.psp. See plot.psp for further information.

There are also methods for summary and print for line segment patterns. Use summary(X) to see a useful description of the data.

Utilities for line segment patterns include midpoints.psp (to compute the midpoints of each segment), lengths.psp, (to compute the length of each segment), angles.psp, (to compute the angle of orientation of each segment), and distmap.psp to compute the distance map of a line segment pattern.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

psp, as.psp, [.psp

Examples

# creating
    a <- psp(runif(20),runif(20),runif(20),runif(20), window=owin())
# converting from other formats
    a <- as.psp(matrix(runif(80), ncol=4), window=owin())
    a <- as.psp(data.frame(x0=runif(20), y0=runif(20),
                            x1=runif(20), y1=runif(20)), window=owin())
# clipping
    w <- owin(c(0.1,0.7), c(0.2, 0.8))
    b <- clip.psp(a, w)
    b <- a[, w]
# the last two lines are equivalent.


Q-Q Plot of Residuals from Fitted Point Process Model

Description

Given a point process model fitted to a point pattern, produce a Q-Q plot based on residuals from the model.

Usage

  qqplot.ppm(fit, nsim=100, expr=NULL, ..., type="raw",
             style="mean", fast=TRUE, verbose=TRUE, plot.it=TRUE,
             dimyx=NULL, nrep=if(fast) 5e4 else 1e5,
             control=list(nrep=nrep,expand=default.expand(fit),
                          periodic=(as.owin(fit)$type=="rectangle")),
             saveall=FALSE,
             monochrome=FALSE,
             limcol=if(monochrome) "black" else "red",
             maxerr=max(100, ceiling(nsim/10)),
             check=TRUE, repair=TRUE)

Arguments

fit | The fitted point process model, which is to be assessed using the Q-Q plot. An object of class "ppm". Smoothed residuals obtained from this fitted model will provide the ``data'' quantiles for the Q-Q plot.
nsim | The number of simulations from the ``reference'' point process model.
expr | Determines the simulation mechanism which provides the ``theoretical'' quantiles for the Q-Q plot. See Details.
... | Arguments passed to diagnose.ppm influencing the computation of residuals.
type | String indicating the type of residuals or weights to be used. Current options are "eem" for the Stoyan-Grabarnik exponential energy weights, "raw" for the raw residuals, "inverse" for the inverse-lambda residuals, and "pearson" for the Pearson residuals. A partial match is adequate.
style | Character string controlling the type of Q-Q plot. Options are "classical" and "mean". See Details.
fast | Logical flag controlling the speed and accuracy of computation. Use fast=TRUE for interactive use and fast=FALSE for publication standard plots. See Details.
verbose | Logical flag controlling whether the algorithm prints progress reports during long computations.
plot.it | Logical flag controlling whether the function produces a plot or simply returns a value (silently).
dimyx | Dimensions of the pixel grid on which the smoothed residual field will be calculated. A vector of two integers.
nrep | If control is absent, then nrep gives the number of iterations of the Metropolis-Hastings algorithm that should be used to generate one simulation of the fitted point process.
control | List of parameters controlling the Metropolis-Hastings algorithm rmh which generates each simulated realisation from the model (unless the model is Poisson). This list becomes the argument control of rmh.default. It overrides nrep.
saveall | Logical flag indicating whether to save all the intermediate calculations.
monochrome | Logical flag indicating whether the plot should be in black and white (monochrome=TRUE), or in colour (monochrome=FALSE).
limcol | String. The colour to be used when plotting the 95-percent limit curves.
maxerr | Maximum number of failures tolerated while generating simulated realisations. See Details.
check | Logical value indicating whether to check the internal format of fit. If there is any possibility that this object has been restored from a dump file, or has otherwise lost track of the environment where it was originally computed, set check=TRUE.
repair | Logical value indicating whether to repair the internal format of fit, if it is found to be damaged.

Details

This function generates a Q-Q plot of the residuals from a fitted point process model. It is an addendum to the suite of diagnostic plots produced by the function diagnose.ppm, kept separate because it is computationally intensive. The quantiles of the theoretical distribution are estimated by simulation.

In classical statistics, a Q-Q plot of residuals is a useful diagnostic for checking the distributional assumptions. Analogously, in spatial statistics, a Q-Q plot of the (smoothed) residuals from a fitted point process model is a useful way to check the interpoint interaction part of the model (Baddeley et al, 2005). The systematic part of the model (spatial trend, covariate effects, etc) is assessed using other plots made by diagnose.ppm.

The argument fit represents the fitted point process model. It must be an object of class "ppm" (typically produced by the maximum pseudolikelihood fitting algorithm ppm). Residuals will be computed for this fitted model using residuals.ppm, and the residuals will be kernel-smoothed to produce a ``residual field''. The values of this residual field will provide the ``data'' quantiles for the Q-Q plot.

The argument expr is not usually specified. It provides a way to modify the ``theoretical'' or ``reference'' quantiles for the Q-Q plot.

In normal usage we set expr=NULL. The default is to generate nsim simulated realisations of the fitted model fit, re-fit this model to each of the simulated patterns, evaluate the residuals from these fitted models, and use the kernel-smoothed residual field from these fitted models as a sample from the reference distribution for the Q-Q plot.

In advanced use, expr may be an expression. It will be re-evaluated nsim times, and should include random computations so that the results are not identical each time. The result of evaluating expr should be either a point pattern (object of class "ppp") or a fitted point process model (object of class "ppm"). If the value is a point pattern, then the original fitted model fit will be fitted to this new point pattern using update.ppm, to yield another fitted model. Smoothed residuals obtained from these nsim fitted models will yield the ``theoretical'' quantiles for the Q-Q plot.

Simulation is performed (if expr=NULL) using the Metropolis-Hastings algorithm rmh. Each simulated realisation is the result of running the Metropolis-Hastings algorithm from an independent random starting state each time. The iterative and termination behaviour of the Metropolis-Hastings algorithm are governed by the argument control. See rmhcontrol for information about this argument. As a shortcut, the argument nrep determines the number of Metropolis-Hastings iterations used to generate each simulated realisation, if control is absent.

By default, simulations are generated in an expanded window. Use the argument control to change this, as explained in the section on Warning messages.

The argument type selects the type of residual or weight that will be computed. For options, see diagnose.ppm.

The argument style determines the type of Q-Q plot. It is highly recommended to use the default, style="mean".

style="classical"
The quantiles of the residual field for the data (on the y axis) are plotted against the quantiles of the pooled simulations (on the x axis). This plot is biased, and therefore difficult to interpret, because of strong autocorrelations in the residual field and the large differences in sample size.
style="mean"
The order statistics of the residual field for the data are plotted against the sample means, over the nsim simulations, of the corresponding order statistics of the residual field for the simulated datasets. Dotted lines show the 2.5 and 97.5 percentiles, over the nsim simulations, of each order statistic.

The argument fast is a simple way to control the accuracy and speed of computation. If fast=FALSE, the residual field is computed on a fine grid of pixels (by default 100 by 100 pixels, see below) and the Q-Q plot is based on the complete set of order statistics (usually 10,000 quantiles). If fast=TRUE, the residual field is computed on a coarse grid (at most 40 by 40 pixels) and the Q-Q plot is based on the percentiles only. This is about 7 times faster. It is recommended to use fast=TRUE for interactive data analysis and fast=FALSE for definitive plots for publication.

The argument dimyx gives full control over the resolution of the pixel grid used to calculate the smoothed residuals. Its interpretation is the same as the argument dimyx to the function as.mask. Note that dimyx[1] is the number of pixels in the y direction, and dimyx[2] is the number in the x direction. If dimyx is not present, then the default pixel grid dimensions are controlled by spatstat.options("npixel").

Since the computation is so time-consuming, qqplot.ppm returns a list containing all the data necessary to re-display the Q-Q plot. It is advisable to assign the result of qqplot.ppm to something (or use .Last.value if you forgot to.) The return value is an object of class "qqppm". There are methods for plot.qqppm and print.qqppm. See the Examples.

The argument saveall is usually set to FALSE. If saveall=TRUE, then the intermediate results of calculation for each simulated realisation are saved and returned. The return value includes a 3-dimensional array sim containing the smoothed residual field images for each of the nsim realisations. When saveall=TRUE, the return value is an object of very large size, and should not be saved on disk.

Errors may occur during the simulation process, because random data are generated. For example:

  • one of the simulated patterns may be empty.
  • one of the simulated patterns may cause an error in the code that fits the point process model.
  • the user-supplied argument expr may have a bug.

Empty point patterns do not cause a problem for the code, but they are reported. Other problems that would lead to a crash are trapped; the offending simulated data are discarded, and the simulation is retried. The argument maxerr determines the maximum number of times that such errors will be tolerated (mainly as a safeguard against an infinite loop).

Value

An object of class "qqppm" containing the information needed to reproduce the Q-Q plot. Entries x and y are numeric vectors containing quantiles of the simulations and of the data, respectively.

Side Effects

Produces a Q-Q plot if plot.it is TRUE.

Warning messages

A warning message will be issued if any of the simulations trapped an error (a potential crash).

A warning message will be issued if all, or many, of the simulated point patterns are empty. This usually indicates a problem with the simulation procedure.

The default behaviour of qqplot.ppm is to simulate patterns on an expanded window (specified through the argument control) in order to avoid edge effects. The model's trend is extrapolated over this expanded window. If the trend is strongly inhomogeneous, the extrapolated trend may have very large (or even infinite) values. This can cause the simulation algorithm to produce empty patterns.

The only way to suppress this problem entirely is to prohibit the expansion of the window, by setting the control argument to something like control=list(nrep=1e6, expand=1). Here expand=1 means there will be no expansion. See rmhcontrol for more information about the argument control.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005) Residual analysis for spatial point processes. Journal of the Royal Statistical Society, Series B 67, 617–666.

Stoyan, D. and Grabarnik, P. (1991) Second-order characteristics for stochastic structures connected with Gibbs point processes. Mathematische Nachrichten, 151:95–100.

See Also

diagnose.ppm, lurking, residuals.ppm, eem, ppm.object, ppm, rmh, rmhcontrol

Examples

    data(cells)

    fit <- ppm(cells, ~1, Poisson())
    diagnose.ppm(fit)  # no suggestion of departure from stationarity
    ## Not run: qqplot.ppm(fit, 80)  # strong evidence of non-Poisson interaction

    ## Not run:
diagnose.ppm(fit, type="pearson")
    qqplot.ppm(fit, type="pearson")
## End(Not run)

    ###########################################
    ## oops, I need the plot coordinates
    mypreciousdata <- .Last.value
    ## Not run: mypreciousdata <- qqplot.ppm(fit, type="pearson")

    plot(mypreciousdata)

    ######################################################
    # Q-Q plots based on fixed n
    # The above QQ plots used simulations from the (fitted) Poisson process.
    # But I want to simulate conditional on n, instead of Poisson
    # Do this by setting rmhcontrol(p=1)
    fixit <- list(p=1)
    ## Not run: qqplot.ppm(fit, 100, control=fixit)

    ######################################################
    # Inhomogeneous Poisson data
    X <- rpoispp(function(x,y){1000 * exp(-3*x)}, 1000)
    plot(X)
    # Inhomogeneous Poisson model
    fit <- ppm(X, ~x, Poisson())
    ## Not run: qqplot.ppm(fit, 100)

    # conclusion: fitted inhomogeneous Poisson model looks OK

    ######################################################
    # Advanced use of 'expr' argument
    #
    # set the initial conditions in Metropolis-Hastings algorithm
    #
    expr <- expression(rmh(fit, start=list(n.start=42), verbose=FALSE))
    ## Not run: qqplot.ppm(fit, 100, expr)


Class of Quadrature Schemes

Description

A class "quad" to represent a quadrature scheme.

Details

A (finite) quadrature scheme is a list of quadrature points u[j] and associated weights w[j] which is used to approximate an integral by a finite sum:

integral(f(x) dx) ~= sum( f(u[j]) w[j] )

Given a point pattern dataset, a Berman-Turner quadrature scheme is one which includes all these data points, as well as a nonzero number of other (``dummy'') points.

These quadrature schemes are used to approximate the pseudolikelihood of a point process, in the method of Baddeley and Turner (2000) (see Berman and Turner (1992)). Accuracy and computation time both increase with the number of points in the quadrature scheme.

An object of class "quad" represents a Berman-Turner quadrature scheme. It can be passed as an argument to the model-fitting function ppm, which requires a quadrature scheme.

An object of this class contains at least the following elements:
data: | an object of class "ppp"
 | giving the locations (and marks) of the data points.
dummy: | an object of class "ppp"
 | giving the locations (and marks) of the dummy points.
w: | vector of nonnegative weights for the quadrature points

Users are strongly advised not to manipulate these entries directly.

The domain of quadrature is specified by dummy$window while the observation window (if this needs to be specified separately) is taken to be data$window.

The weights vector w may also have an attribute attr(w, "zeroes") equivalent to the logical vector (w == 0). If this is absent then all points are known to have positive weights.

To create an object of class "quad", users would typically call the high level function quadscheme. (They are actually created by the low level function quad.)

Entries are extracted from a "quad" object by the functions x.quad, y.quad, w.quad and marks.quad, which extract the x coordinates, y coordinates, weights, and marks, respectively. The function n.quad returns the total number of quadrature points (dummy plus data).

An object of class "quad" can be converted into an ordinary point pattern by the function union.quad which simply takes the union of the data and dummy points.

Quadrature schemes can be plotted using plot.quad (a method for the generic plot).

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

quadscheme, ppm


Extract Quadrature Scheme Used to Fit a Point Process Model

Description

Given a fitted point process model, this function extracts the quadrature scheme used to fit the model.

Usage

  quad.ppm(object)

Arguments

object fitted point process model (an object of class "ppm").

Details

An object of class "ppm" represents a point process model that has been fitted to data. It is typically produced by the model-fitting algorithm ppm.

The ppm algorithm approximates the pseudolikelihood integral by a sum over a finite set of quadrature points, which is constructed by augmenting the original data point pattern by a set of ``dummy'' points. The fitted model object returned by ppm contains complete information about this quadrature scheme. See ppm or ppm.object for further information.

This function extracts the quadrature scheme. A typical use of this function would be to inspect the quadrature scheme (points and weights) to gauge the accuracy of the approximation to the exact pseudolikelihood.

See ppm.object for a list of all operations that can be performed on objects of class "ppm". See quad.object for a list of all operations that can be performed on objects of class "quad".

Value

A quadrature scheme (object of class "quad").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppm.object, quad.object, ppm

Examples

 data(cells)
 fit <- ppm(cells, ~1, Strauss(r=0.1), rbord=0.1)
 Q <- quad.ppm(fit)
 ## Not run: plot(Q)
 Q$data$n
 Q$dummy$n


Chi-Squared Dispersion Test for Spatial Point Pattern Based on Quadrat Counts

Description

Performs a chi-squared test of Complete Spatial Randomness for a given point pattern, based on quadrat counts. Alternatively performs a chi-squared goodness-of-fit test of a fitted inhomogeneous Poisson model.

Usage

quadrat.test(X, ...)
## S3 method for class 'ppp':
quadrat.test(X, nx=5, ny=nx, xbreaks=NULL, ybreaks=NULL, ...)
## S3 method for class 'ppm':
quadrat.test(X, nx=5, ny=nx, xbreaks=NULL, ybreaks=NULL, ...)

Arguments

X | A point pattern (object of class "ppp") to be subjected to the goodness-of-fit test. Alternatively a fitted point process model (object of class "ppm") to be tested.
nx,ny | Numbers of quadrats in the x and y directions. Incompatible with xbreaks and ybreaks.
xbreaks | Optional. Numeric vector giving the x coordinates of the boundaries of the quadrats. Incompatible with nx.
ybreaks | Optional. Numeric vector giving the y coordinates of the boundaries of the quadrats. Incompatible with ny.
... | Ignored.

Details

These functions perform chi^2 tests of goodness-of-fit for a point process model, based on quadrat counts.

The function quadrat.test is generic, with methods for point patterns (class "ppp") and point process models (class "ppm").

  • if X is a point pattern, we test the null hypothesis that the data pattern is a realisation of Complete Spatial Randomness (the uniform Poisson point process).
  • If X is a fitted point process model, then it should be a Poisson point process model. The data to which this model was fitted are extracted from the model object, and are treated as the data point pattern for the test. We test the null hypothesis that the data pattern is a realisation of the (inhomogeneous) Poisson point process specified by X.

In both cases, the window of observation is divided into rectangular tiles, and the number of data points in each tile is counted, as described in quadratcount. The expected number of points in each quadrat is also calculated, as determined by CSR (in the first case) or by the fitted model (in the second case). Then we perform the chi^2 test of goodness-of-fit to the quadrat counts.

The return value is an object of class "htest". Printing the object gives comprehensible output about the outcome of the test.

The return value also belongs to the special class "quadrat.test". Plotting the object will display the quadrats, annotated by their observed and expected counts and the Pearson residuals. See the examples.

Value

An object of class "htest". See chisq.test for explanation.
The return value is also an object of the special class "quadrat.test", and there is a plot method for this class. See the examples.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

quadratcount, chisq.test, ks.test.ppm.

To test a Poisson point process model against a specific alternative, use anova.ppm.

Examples

  data(simdat)
  quadrat.test(simdat)
  quadrat.test(simdat, 4)

  # fitted model: inhomogeneous Poisson
  fitx <- ppm(simdat, ~x, Poisson())
  quadrat.test(fitx)

  te <- quadrat.test(simdat, 4)
  residuals(te)  # Pearson residuals

  plot(te)

  plot(simdat, pch="+", col="green", cex=1.2, lwd=2)
  plot(te, add=TRUE, col="red", cex=1.5, lty=2, lwd=3)

  sublab <- eval(substitute(expression(p[chi^2]==z),
                       list(z=signif(te$p.value,3))))
  title(sub=sublab, cex.sub=3)


Quadrat counting for a point pattern

Description

Divides window into quadrats and counts the numbers of points in each quadrat.

Usage

  quadratcount(X, nx=5, ny=nx, xbreaks, ybreaks)

Arguments

X | A point pattern (object of class "ppp").
nx,ny | Numbers of quadrats in the x and y directions. Incompatible with xbreaks and ybreaks.
xbreaks | Numeric vector giving the x coordinates of the boundaries of the quadrats. Incompatible with nx.
ybreaks | Numeric vector giving the y coordinates of the boundaries of the quadrats. Incompatible with ny.

Details

Quadrat counting is an elementary technique for analysing spatial point patterns. See Diggle (2003).

The window containing the point pattern X is divided into an nx * ny grid of rectangular tiles or `quadrats'. The number of points of X falling in each quadrat is counted. These numbers are returned as a contingency table.

If xbreaks is given, it should be a numeric vector giving the x coordinates of the quadrat boundaries. If it is not given, it defaults to a sequence of nx+1 values equally spaced over the range of x coordinates in the window X$window.

Similarly if ybreaks is given, it should be a numeric vector giving the y coordinates of the quadrat boundaries. It defaults to a vector of ny+1 values equally spaced over the range of y coordinates in the window. The lengths of xbreaks and ybreaks may be different.

The algorithm counts the number of points of X falling in each quadrat, and returns these counts as a contingency table. The [i,j] entry in the contingency table is the point count for the quadrat with coordinates (xbreaks[i],xbreaks[i+1]) by (ybreaks[i], ybreaks[i+1]).

The return value is a table which can be printed neatly. The return value is also a member of the special class "quadratcount". Plotting the object will display the quadrats, annotated by their counts. See the examples.

To perform a chi-squared test based on the quadrat counts, use quadrat.test.

Value

A contingency table containing the number of points in each quadrat.
The table is also an object of the special class "quadratcount" and there is a plot method for this class.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Diggle, P.J. Statistical analysis of spatial point patterns. Academic Press, 2003.

Stoyan, D. and Stoyan, H. (1994) Fractals, random shapes and point fields: methods of geometrical statistics. John Wiley and Sons.

See Also

quadrat.test

Examples

 X <- runifpoint(50)
 quadratcount(X)
 quadratcount(X, 4, 5)
 quadratcount(X, xbreaks=c(0, 0.3, 1), ybreaks=c(0, 0.4, 0.8, 1))
 qX <-  quadratcount(X, 4, 5)

 # plotting:
 plot(X, pch="+")
 plot(qX, add=TRUE, col="red", cex=1.5, lty=2)


Generate a Quadrature Scheme from a Point Pattern

Description

Generates a quadrature scheme (an object of class "quad") from point patterns of data and dummy points.

Usage

 quadscheme(data, dummy, method="grid", ...)

Arguments

data | The observed data point pattern. An object of class "ppp" or in a format recognised by as.ppp()
dummy | The pattern of dummy points for the quadrature. An object of class "ppp" or in a format recognised by as.ppp() Defaults to default.dummy(data, ...)
method | The name of the method for calculating quadrature weights: either "grid" or "dirichlet".
... | Parameters of the weighting method (see below) and parameters for constructing the dummy points if necessary.

Details

This is the primary method for producing a quadrature schemes for use by ppm.

The function ppm fits a point process model to an observed point pattern using the Berman-Turner quadrature approximation (Berman and Turner, 1992; Baddeley and Turner, 2000) to the pseudolikelihood of the model. It requires a quadrature scheme consisting of the original data point pattern, an additional pattern of dummy points, and a vector of quadrature weights for all these points. Such quadrature schemes are represented by objects of class "quad". See quad.object for a description of this class.

Quadrature schemes are created by the function quadscheme. The arguments data and dummy specify the data and dummy points, respectively. There is a sensible default for the dummy points (provided by default.dummy). Alternatively the dummy points may be specified arbitrarily and given in any format recognised by as.ppp. There are also functions for creating dummy patterns including corners, gridcentres, stratrand and spokes.

The quadrature region is the region over which we are integrating, and approximating integrals by finite sums. If dummy is a point pattern object (class "ppp") then the quadrature region is taken to be dummy$window. If dummy is just a list of x, y coordinates then the quadrature region defaults to the observation window of the data pattern, data$window.

If dummy is missing, then the optional arguments (for ...) include an argument nd. An nd[1] by nd[2] grid of dummy points is generated by default.dummy.

If method = "grid" then the optional arguments (for ...) are (nd, ntile). The quadrature region (see below) is divided into an ntile[1] by ntile[2] grid of rectangular tiles. The weight for each quadrature point is the area of a tile divided by the number of quadrature points in that tile.

If method="dirichlet" then the optional arguments are (exact=TRUE, nd). The quadrature points (both data and dummy) are used to construct the Dirichlet tessellation. The quadrature weight of each point is the area of its Dirichlet tile inside the quadrature region. If exact == TRUE then this area is computed exactly using the package deldir; otherwise it is computed approximately by discretisation.

Value

An object of class "quad" describing the quadrature scheme (data points, dummy points, and quadrature weights) suitable as the argument Q of the function ppm() for fitting a point process model.
The quadrature scheme can be inspected using the print and plot methods for objects of class "quad".

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A. and Turner, R. Practical maximum pseudolikelihood for spatial point patterns. Australian and New Zealand Journal of Statistics 42 (2000) 283–322.

Berman, M. and Turner, T.R. Approximating point process likelihoods with GLIM. Applied Statistics 41 (1992) 31–38.

See Also

ppm, as.ppp, quad.object, gridweights, dirichlet.weights, corners, gridcentres, stratrand, spokes

Examples

  data(simdat)

  # grid weights
  Q <- quadscheme(simdat)
  Q <- quadscheme(simdat, method="grid")
  Q <- quadscheme(simdat, nd=50)           # 1 dummy point per tile
  Q <- quadscheme(simdat, ntile=25, nd=50) # 4 dummy points per tile

  # Dirichlet weights
  Q <- quadscheme(simdat, method="dirichlet", exact=FALSE)

  # random dummy pattern
  ## Not run:
  D <- runifpoint(250, simdat$window)
  Q <- quadscheme(simdat, D, method="dirichlet", exact=FALSE)

## End(Not run)

  # polygonal window
  data(demopat)
  X <- unmark(demopat)
  Q <- quadscheme(X)

  # mask window
  X$window <- as.mask(X$window)
  Q <- quadscheme(X)


Sample Quantiles of Pixel Image

Description

Compute the sample quantiles of the pixel values of a given pixel image.

Usage

## S3 method for class 'im':
quantile(x, ...)

Arguments

x | A pixel image. An object of class "im".
... | Optional arguments passed to quantile.default. They determine the probabilities for which quantiles should be computed. See quantile.default.

Details

This simple function applies the generic quantile operation to the pixel values of the image x.

This function is a convenient way to inspect an image and to obtain summary statistics. See the examples.

Value

A vector of quantiles.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

quantile, cut.im, im.object

Examples

# artificial image data
Z <- setcov(square(1))

# find the quartiles
quantile(Z)

# find the deciles
quantile(Z, probs=(0:10)/10)


Cartesian Coordinates for a Pixel Raster

Description

Returns a matrix giving the x (or y) coordinates of each pixel in a binary pixel image.

Usage

 raster.x(w)
 raster.y(w)

Arguments

w A window (an object of class "owin") of type "mask" representing a binary pixel image.

Details

The argument w should be a window (an object of class "owin", see owin.object for details). A window of type "mask" represents a binary pixel image. This function returns a matrix of the same dimensions as the binary pixel image itself, with entries giving the x coordinate (for raster.x) or y coordinate (for raster.y) of each pixel in the image.

Value

A matrix of the same dimensions as the pixel grid in w, and giving the value of the x (or y) coordinate of each pixel in the raster.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin, as.mask

Examples

  u <- owin(c(-1,1),c(-1,1)) # square of side 2
  w <- as.mask(u, eps=0.01) # 200 x 200 grid
  X <- raster.x(w)
  Y <- raster.y(w)
  disc <- owin(c(-1,1), c(-1,1), mask=(X^2 + Y^2 <= 1))
  ## Not run: plot(disc)
  # approximation to the unit disc


Simulate Baddeley-Silverman Cell Process

Description

Generates a random point pattern, a simulated realisation of the Baddeley-Silverman cell process model.

Usage

 rcell(win=square(1), nx, ny=nx, dx=NULL, dy=NULL)

Arguments

win | A window. An object of class owin, or data in any format acceptable to as.owin().
dx | Width of the cells. Incompatible with nx.
dy | Height of the cells. Incompatible with ny.
nx | Number of columns of cells in the window. Incompatible with dx.
ny | Number of rows of cells in the window. Incompatible with dy.

Details

This function generates a simulated realisation of the “cell process” (Baddeley and Silverman, 1984), a random point process with the same second-order properties as the uniform Poisson process. In particular, the K function of this process is identical to the K function of the uniform Poisson process (aka Complete Spatial Randomness). The same holds for the pair correlation function and all other second-order properties. The cell process is a counterexample to the claim that the K function completely characterises a point pattern.

A cell process is generated by dividing space into equal rectangular tiles. In each tile, a random number N of points is placed, where N takes the values 0, 1 and 10 with probabilities 1/10, 8/9 and 1/90 respectively. The points within a tile are independent and uniformly distributed in that tile, and the numbers of points in different tiles are independent random integers.

In the function rcell the tile dimensions are determined by the quantities dx, dy if they are present. If they are absent, then the grid spacing is determined so that there will be nx columns and ny rows of tiles in the bounding rectangle of win. The cell process is then generated in these tiles.

Some of the resulting random points may lie outside the window win: if they do, they are deleted. The result is a point pattern inside the window win.

Value

A point pattern (object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A.J. and Silverman, B.W. (1984) A cautionary example on the use of second-order methods for analyzing point patterns. Biometrics 40, 1089-1094.

See Also

rstrat, rsyst, runifpoint, Kest

Examples

  X <- rcell(nx=15)
  plot(X)
  plot(Kest(X))


Interaction Distance of a Point Process

Description

Computes the interaction distance of a point process.

Usage

  reach(x, ...)
  ## S3 method for class 'ppm':
  reach(x, ..., epsilon=0)
  ## S3 method for class 'interact':
  reach(x, ...)
  ## S3 method for class 'rmhmodel':
  reach(x, ...)

Arguments

x | Either a fitted point process model (object of class "ppm"), an interpoint interaction (object of class "interact") or a point process model for simulation (object of class "rmhmodel").
epsilon | Numerical threshold below which interaction is treated as zero. See details.
... | Other arguments are ignored.

Details

The `interaction distance' or `interaction range' of a point process model is the smallest distance D such that any two points in the process which are separated by a distance greater than D do not interact with each other.

For example, the interaction range of a Strauss process (see Strauss) with parameters beta,gamma,r is equal to r, unless gamma=1 in which case the model is Poisson and the interaction range is 0. The interaction range of a Poisson process is zero. The interaction range of the Ord threshold process (see OrdThresh) is infinite, since two points may interact at any distance apart.

The function reach(x) is generic, with methods for the case where x is

  • a fitted point process model (object of class "ppm", usually obtained from the model-fitting function ppm);
  • an interpoint interaction structure (object of class "interact"), created by one of the functions Poisson, Strauss, StraussHard, MultiStrauss, MultiStraussHard, Softcore, DiggleGratton, Pairwise, PairPiece, Geyer, LennardJones, Saturated, OrdThresh or Ord;
  • a point process model for simulation (object of class "rmhmodel"), usually obtained from rmhmodel.

When x is an "interact" object, reach(x) returns the maximum possible interaction range for any point process model with interaction structure given by x. For example, reach(Strauss(0.2)) returns 0.2.

When x is a "ppm" object, reach(x) returns the interaction range for the point process model represented by x. For example, a fitted Strauss process model with parameters beta,gamma,r will return either 0 or r, depending on whether the fitted interaction parameter gamma is equal or not equal to 1.

For some point process models, such as the soft core process (see Softcore), the interaction distance is infinite, because the interaction terms are positive for all pairs of points. A practical solution is to compute the distance at which the interaction contribution from a pair of points falls below a threshold epsilon, on the scale of the log conditional intensity. This is done by setting the argument epsilon to a positive value.

Value

The interaction distance, or NA if this cannot be computed from the information given.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppm, Poisson, Strauss, StraussHard, MultiStrauss, MultiStraussHard, Softcore, DiggleGratton, Pairwise, PairPiece, Geyer, LennardJones, Saturated, OrdThresh, Ord, rmhmodel

Examples

    reach(Poisson())
    # returns 0

    reach(Strauss(r=7))
    # returns 7
    data(swedishpines)
    fit <- ppm(swedishpines, ~1, Strauss(r=7))
    reach(fit)
    # returns 7

    reach(OrdThresh(42))
    # returns Inf

    reach(MultiStrauss(1:2, matrix(c(1,3,3,1),2,2)))
    # returns 3


Reduced Sample Estimator using Histogram Data

Description

Compute the Reduced Sample estimator of a survival time distribution function, from histogram data

Usage

  reduced.sample(nco, cen, ncc, show=FALSE, uppercen=0)

Arguments

nco | vector of counts giving the histogram of uncensored observations (those survival times that are less than or equal to the censoring time)
cen | vector of counts giving the histogram of censoring times
ncc | vector of counts giving the histogram of censoring times for the uncensored observations only
uppercen | number of censoring times greater than the rightmost histogram breakpoint (if there are any)
show | Logical value controlling the amount of detail returned by the function value (see below)

Details

This function is needed mainly for internal use in spatstat, but may be useful in other applications where you want to form the reduced sample estimator from a huge dataset.

Suppose T[i] are the survival times of individuals i=1,...,M with unknown distribution function F(t) which we wish to estimate. Suppose these times are right-censored by random censoring times C[i]. Thus the observations consist of right-censored survival times T*[i] = min(T[i],C[i]) and non-censoring indicators D[i] = 1(T[i] <= C[i]) for each i.

If the number of observations M is large, it is efficient to use histograms. Form the histogram cen of all censoring times C[i]. That is, obs[k] counts the number of values C[i] in the interval (breaks[k],breaks[k+1]] for k > 1 and [breaks[1],breaks[2]] for k = 1. Also form the histogram nco of all uncensored times, i.e. those T*[i] such that D[i]=1, and the histogram of all censoring times for which the survival time is uncensored, i.e. those C[i] such that D[i]=1. These three histograms are the arguments passed to kaplan.meier.

The return value rs is the reduced-sample estimator of the distribution function F(t). Specifically, rs[k] is the reduced sample estimate of F(breaks[k+1]). The value is exact, i.e. the use of histograms does not introduce any approximation error.

Note that, for the results to be valid, either the histogram breaks must span the censoring times, or the number of censoring times that do not fall in a histogram cell must have been counted in uppercen.

Value

If show = FALSE, a numeric vector giving the values of the reduced sample estimator. If show=TRUE, a list with three components which are vectors of equal length,

rs | Reduced sample estimate of the survival time c.d.f. F(t)
numerator | numerator of the reduced sample estimator
denominator | denominator of the reduced sample estimator

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

kaplan.meier, km.rs


California Redwoods Point Pattern (Ripley's Subset)

Description

Locations of 62 seedlings and saplings of California redwood trees.

The data represent the locations of 62 seedlings and saplings of California redwood trees in a square sampling region. They originate from Strauss (1975); the present data are a subset extracted by Ripley (1977) in a subregion that has been rescaled to a unit square.

There are many further analyses of this dataset. It is often used as a canonical example of a clustered point pattern (see e.g. Diggle, 1983).

The original, full redwood dataset is supplied in the spatstat library as redwoodfull.

Usage

data(redwood)

Format

An object of class "ppp" representing the point pattern of tree locations. The window has been rescaled to the unit square.

See ppp.object for details of the format of a point pattern object.

Source

Strauss (1975), subset extracted by Ripley (1977)

References

Diggle, P.J. (1983) Statistical analysis of spatial point patterns. Academic Press.

Ripley, B.D. (1977) Modelling spatial patterns (with discussion). Journal of the Royal Statistical Society, Series B 39, 172–212.

Strauss, D.J. (1975) A model for clustering. Biometrika 63, 467–475.

See Also

redwoodfull


California Redwoods Point Pattern (Entire Dataset)

Description

These data represent the locations of 195 seedlings and saplings of California redwood trees in a square sampling region. They were described and analysed by Strauss (1975). This is the ``full'' dataset; most writers have analysed a subset extracted by Ripley (1977) which is available as redwood.

Strauss (1975) divided the sampling region into two subregions I and II demarcated by a diagonal line across the region. The spatial pattern appears to be slightly regular in region I and strongly clustered in region II.

The dataset redwoodfull contains the full point pattern of 195 trees. The auxiliary information about the subregions is contained in redwoodfull.extra, which is a list with entries
diag | The coordinates of the diagonal boundary
 | between regions I and II
regionI | Region I as a window object
regionII | Region II as a window object
regionR | Ripley's subrectangle (approximate)
plot | Function to plot the full data and auxiliary markings

Ripley (1977) extracted a subset of these data, containing 62 points, lying within a square subregion which overlaps regions I and II. He rescaled the data to the unit square. This has been re-analysed many times, and is the dataset usually known as ``the redwood data'' in the spatial statistics literature. The exact dataset used by Ripley is supplied in the spatstat library as redwood. There are some minor inconsistencies with redwood since it originates from a different digitisation.

The approximate position of the square chosen by Ripley within the redwoodfull pattern is indicated by the window redwoodfull.extra$regionR.

Usage

data(redwoodfull)

Format

The dataset redwoodfull is an object of class "ppp" representing the point pattern of tree locations. The window has been rescaled to the unit square. See ppp.object for details of the format of a point pattern object.

The dataset redwoodfull.extra is a list with entries
diag | coordinates of endpoints of a line,
 | in format list(x=numeric(2),y=numeric(2))
regionI | a window object
regionII | a window object
regionR | a window object
plot | Function with no arguments

Source

Strauss (1975). The plot of the data published by Strauss (1975) was scanned and digitised by Sandra Pereira, University of Western Australia, 2002.

References

Diggle, P.J. (1983) Statistical analysis of spatial point patterns. Academic Press.

Ripley, B.D. (1977) Modelling spatial patterns (with discussion). Journal of the Royal Statistical Society, Series B 39, 172–212.

Strauss, D.J. (1975) A model for clustering. Biometrika 63, 467–475.

See Also

redwood

Examples

       data(redwoodfull)
       plot(redwoodfull)
       redwoodfull.extra$plot()
       # extract the pattern in region II
       redwoodII <- redwoodfull[, redwoodfull.extra$regionII]


Convert dataset to another unit of length

Description

Converts between different units of length in a spatial dataset, such as a point pattern or a window.

Usage

  rescale(X, s)

Arguments

X | Any suitable dataset representing a two-dimensional object, such as a point pattern (object of class "ppp"), or a window (object of class "owin").
s | Conversion factor: the new units are s times the old units.

Details

This is generic. Methods are provided for point patterns (rescale.ppp) and windows (rescale.owin).

The spatial coordinates in the dataset X will be re-expressed in terms of a new unit of length that is s times the current unit of length given in X.

Value

Another object of the same type, representing the same data, but expressed in the new units.

Note

The result of this operation is equivalent to the original dataset. If you want to actually change the coordinates by a linear transformation, producing a dataset that is not equivalent to the original one, use affine.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

units, rescale.ppp, rescale.owin, affine, rotate, shift


Convert Window to Another Unit of Length

Description

Converts a window to another unit of length.

Usage

  ## S3 method for class 'owin':
  rescale(X, s)

Arguments

X | Window (object of class "owin").
s | Conversion factor: the new units are s times the old units.

Details

This is a method for the generic function rescale.

The spatial coordinates in the window X (and its window) will be re-expressed in terms of a new unit of length that is s times the current unit of length given in X. (Thus, the coordinate values are divided by s, while the unit value is multiplied by s).

The result is a window representing the same region of space, but re-expressed in a different unit.

Value

Another window object (of class "owin") representing the same window, but expressed in the new units.

Note

The result of this operation is equivalent to the original window. If you want to actually change the coordinates by a linear transformation, producing a window that is larger or smaller than the original one, use affine.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

units, rescale, rescale.owin, affine, rotate, shift

Examples

  data(swedishpines)
  W <- swedishpines$window
  W
# coordinates are in decimetres (0.1 metre)
# convert to metres
  rescale(W, 10)


Convert Point Pattern to Another Unit of Length

Description

Converts a point pattern dataset to another unit of length.

Usage

 ## S3 method for class 'ppp':
 rescale(X, s)

Arguments

X | Point pattern (object of class "ppp").
s | Conversion factor: the new units are s times the old units.

Details

This is a method for the generic function rescale.

The spatial coordinates in the point pattern X (and its window) will be re-expressed in terms of a new unit of length that is s times the current unit of length given in X. (Thus, the coordinate values are divided by s, while the unit value is multiplied by s).

The result is a point pattern representing the same data but re-expressed in a different unit.

Mark values are unchanged.

Value

Another point pattern (of class "ppp"), representing the same data, but expressed in the new units.

Note

The result of this operation is equivalent to the original point pattern. If you want to actually change the coordinates by a linear transformation, producing a point pattern that is not equivalent to the original one, use affine.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

units, rescale, rescale.owin, affine, rotate, shift

Examples

# Bramble Canes data: 1 unit = 9 metres
  data(bramblecanes)
# convert to metres
  bram <- rescale(bramblecanes, 1/9)


Convert Line Segment Pattern to Another Unit of Length

Description

Converts a line segment pattern dataset to another unit of length.

Usage

 ## S3 method for class 'psp':
 rescale(X, s)

Arguments

X | Line segment pattern (object of class "psp").
s | Conversion factor: the new units are s times the old units.

Details

This is a method for the generic function rescale.

The spatial coordinates in the line segment pattern X (and its window) will be re-expressed in terms of a new unit of length that is s times the current unit of length given in X. (Thus, the coordinate values are divided by s, while the unit value is multiplied by s).

The result is a line segment pattern representing the same data but re-expressed in a different unit.

Mark values are unchanged.

Value

Another line segment pattern (of class "psp"), representing the same data, but expressed in the new units.

Note

The result of this operation is equivalent to the original segment pattern. If you want to actually change the coordinates by a linear transformation, producing a segment pattern that is not equivalent to the original one, use affine.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

units, affine, rotate, shift

Examples

   data(copper)
   X <- copper$Lines
   X
   # data are in km
   # convert to metres
   rescale(X, 1/1000)


Convert Window Back To Rectangle

Description

Determines whether the given window is really a rectangle aligned with the coordinate axes, and if so, converts it to a rectangle object.

Usage

 rescue.rectangle(W)

Arguments

W A window (object of class "owin").

Details

This function decides whether the window W is actually a rectangle aligned with the coordinate axes. This will be true if W is

  • a rectangle (window object of type "rectangle");
  • a polygon (window object of type "polygonal" with a single polygonal boundary) that is a rectangle aligned with the coordinate axes;
  • a binary mask (window object of type "mask") in which all the pixel entries are TRUE.

If so, the function returns this rectangle, a window object of type "rectangle". If not, the function returns W.

Value

Another object of class "owin" representing the same window.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

as.owin, owin.object

Examples

  w <- owin(poly=list(x=c(0,1,1,0),y=c(0,0,1,1)))
  rw <- rescue.rectangle(w)

  w <- as.mask(unit.square())
  rw <- rescue.rectangle(w)


Residuals for Fitted Point Process Model

Description

Given a point process model fitted to a point pattern, compute residuals.

Usage

  ## S3 method for class 'ppm':
  residuals(object, type="raw", ..., check=TRUE,
                fittedvalues=fitted.ppm(object, check=check))

Arguments

object | The fitted point process model (an object of class "ppm") for which residuals should be calculated.
type | String indicating the type of residuals to be calculated. Current options are "raw", "inverse" and "pearson". A partial match is adequate.
... | Ignored.
check | Logical value indicating whether to check the internal format of object. If there is any possibility that this object has been restored from a dump file, or has otherwise lost track of the environment where it was originally computed, set check=TRUE.
fittedvalues | Vector of fitted values for the conditional intensity at the quadrature points, from which the residuals will be computed. For expert use only.

Details

This function computes several kinds of residuals for the fit of a point process model to a spatial point pattern dataset (Baddeley et al, 2005). Use diagnose.ppm to produce diagnostic plots based on these residuals.

The argument object must be a fitted point process model (object of class "ppm"). Such objects are produced by the maximum pseudolikelihood fitting algorithm ppm). This fitted model object contains complete information about the original data pattern.

Residuals are attached both to the data points and to some other points in the window of observation (namely, to the dummy points of the quadrature scheme used to fit the model). If the fitted model is correct, then the sum of the residuals over all (data and dummy) points in a spatial region B has mean zero. For further explanation, see Baddeley et al (2005).

The type of residual is chosen by the argument type. Current options are

"raw":
the raw residuals

r[j] = z[j] - w[j] lambda[j]

at the quadrature points u[j], where z[j] is the indicator equal to 1 if u[j] is a data point and 0 if u[j] is a dummy point; w[j] is the quadrature weight attached to u[j]; and

lambda[j] = lambda(u[j],x)

is the conditional intensity of the fitted model at u[j]. These are the spatial analogue of the martingale residuals of a one-dimensional counting process.

"inverse":
the `inverse-lambda' residuals (Baddeley et al, 2005)

rI[j] = r[j]/lambda[j] = z[j]/lambda[j] - w[j]

obtained by dividing the raw residuals by the fitted conditional intensity. These are a counterpart of the exponential energy marks (see eem).

"pearson":
the Pearson residuals (Baddeley et al, 2005)

rP[j] = r[j]/sqrt(lambda[j]) = z[j]/sqrt(lambda[j]) - w[j] sqrt(lambda[j])

obtained by dividing the raw residuals by the square root of the fitted conditional intensity. The Pearson residuals are standardised, in the sense that if the model (true and fitted) is Poisson, then the sum of the Pearson residuals in a spatial region B has variance equal to the area of B.

Use diagnose.ppm to produce diagnostic plots based on these residuals.

Value

A vector containing the (discretised) residuals.
Entries in this vector correspond to the quadrature points (data or dummy points) used to fit the model. The quadrature points can be extracted from object by union.quad(quad.ppm(object)).

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005) Residual analysis for spatial point processes. Journal of the Royal Statistical Society, Series B 67, 617–666.

See Also

diagnose.ppm, ppm.object, ppm

Examples

    data(cells)
    fit <- ppm(cells, ~x, Strauss(r=0.15), rbord=0.15)

    rp <- residuals.ppm(fit, type="pe")
    sum(rp) # should be close to 0

    # extract quadrature points to which the residuals correspond
    quadpoints <- union.quad(quad.ppm(fit))

    # plot residuals as marks attached to the quadrature points
    quadmarked <- setmarks(quadpoints, rp)
    plot(quadmarked)


Data and Code From JRSS Discussion Paper on Residuals

Description

This dataset contains the point patterns used as examples in the paper of Baddeley et al (2005). [Figure 2 is already available in spatstat as the copper dataset.]

R code is also provided to reproduce all the Figures displayed in Baddeley et al (2005). The component plotfig is a function, which can be called with a numeric or character argument specifying the Figure or Figures that should be plotted. See the Examples.

Usage

data(residualspaper)

Format

residualspaper is a list with the following components:

Fig1
The locations of Japanese pine seedlings and saplings from Figure 1 of the paper. A point pattern (object of class "ppp").
Fig3
The Chorley-Ribble data from Figure 3 of the paper. A list with three components, lung, larynx and incin. Each is a matrix with 2 columns giving the coordinates of the lung cancer cases, larynx cancer cases, and the incinerator, respectively. Coordinates are Eastings and Northings in km.
Fig4a
The synthetic dataset in Figure 4 (a) of the paper.
Fig4b
The synthetic dataset in Figure 4 (b) of the paper.
Fig4c
The synthetic dataset in Figure 4 (c) of the paper.
Fig11
The covariate displayed in Figure 11. A pixel image (object of class "im") whose pixel values are distances to the nearest line segment in the copper data.
plotfig
A function which will compute and plot any of the Figures from the paper. The argument of plotfig is either a numeric vector or a character vector, specifying the Figure or Figures to be plotted. See the Examples.

Source

Figure 1: Prof M. Numata. Data kindly supplied by Professor Y. Ogata with kind permission of Prof M. Tanemura.

Figure 3: Professor P.J. Diggle (rescaled by Adrian Baddeley)

Figure 4 (a,b,c): Adrian Baddeley

References

Baddeley, A., Turner, R., Moller, J. and Hazelton, M. (2005) Residual analysis for spatial point processes. Journal of the Royal Statistical Society, Series B 67, 617–666.

Examples

## Not run:
  data(residualspaper)

  X <- residualspaper$Fig4a
  summary(X)
  plot(X)

  # reproduce all Figures
  residualspaper$plotfig()

  # reproduce Figures 1 to 10
  residualspaper$plotfig(1:10)

  # reproduce Figure 7 (a)
  residualspaper$plotfig("7a")
## End(Not run)


Estimate window from points alone

Description

Given an observed pattern of points, computes the Ripley-Rasson estimate of the spatial domain from which they came.

Usage

 ripras(x, y=NULL, shape="convex")

Arguments

x | vector of x coordinates of observed points, or a 2-column matrix giving x,y coordinates, or a list with components x,y giving coordinates (such as a point pattern object of class "ppp".)
y | (optional) vector of y coordinates of observed points, if x is a vector.
shape | String indicating the type of window to be estimated: either "convex" or "rectangle".

Details

Given an observed pattern of points with coordinates given by x and y, this function computes an estimate due to Ripley and Rasson (1977) of the spatial domain from which the points came.

The points are assumed to have been generated independently and uniformly distributed inside an unknown domain D.

If shape="convex" (the default), the domain D is assumed to be a convex set. The maximum likelihood estimate of D is the convex hull of the points (computed by convexhull.xy). Analogously to the problems of estimating the endpoint of a uniform distribution, the MLE is not optimal. Ripley and Rasson's estimator is a rescaled copy of the convex hull, centred at the centroid of the convex hull. The scaling factor is 1/sqrt{1 - frac m n} where n is the number of data points and m the number of vertices of the convex hull.

If shape="rectangle", the domain D is assumed to be a rectangle with sides parallel to the coordinate axes. The maximum likelihood estimate of D is the bounding box of the points (computed by bounding.box.xy). The Ripley-Rasson estimator is a rescaled copy of the bounding box, with scaling factor 1/sqrt{1 - frac 4 n} where n is the number of data points, centred at the centroid of the bounding box.

Value

A window (an object of class "owin").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Ripley, B.D. and Rasson, J.-P. (1977) Finding the edge of a Poisson forest. Journal of Applied Probability, 14, 483 – 491.

See Also

owin, as.owin, bounding.box.xy, convexhull.xy

Examples

  x <- runif(30)
  y <- runif(30)
  w <- ripras(x,y)
  plot(owin(), main="ripras(x,y)")
  plot(w, add=TRUE)
  points(x,y)

  X <- rpoispp(15)
  plot(X, main="ripras(X)")
  plot(ripras(X), add=TRUE)

  # two points insufficient
  ripras(c(0,1),c(0,0))
  # triangle
  ripras(c(0,1,0.5), c(0,0,1))
  # three collinear points
  ripras(c(0,0,0), c(0,1,2))


Random Re-Labelling of Point Pattern

Description

Randomly allocates marks to a point pattern, or permutes the existing marks, or resamples from the existing marks.

Usage

   rlabel(X, labels=marks(X), permute=TRUE)

Arguments

X | Point pattern (object of class "ppp").
labels | Vector of values from which the new marks will be drawn at random. Defaults to the vector of existing marks.
permute | Logical value indicating whether to generate new marks by randomly permuting labels or by drawing a random sample with replacement.

Details

This very simple function allocates random marks to an existing point pattern X. It is useful for hypothesis testing purposes.

In the simplest case, the command rlabel(X) yields a point pattern obtained from X by randomly permuting the marks of the points.

If permute=TRUE, then labels should be a vector of length equal to the number of points in X. The result of rlabel will be a point pattern with locations given by X and marks given by a random permutation of labels (i.e. a random sample without replacement).

If permute=FALSE, then labels may be a vector of any length. The result of rlabel will be a point pattern with locations given by X and marks given by a random sample from labels (with replacement).

Value

A marked point pattern.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

setmarks to assign arbitrary marks.

Examples

   data(amacrine)

   # Randomly permute the marks "on" and "off"
   # Result always has 142 "off" and 152 "on"
   Y <- rlabel(amacrine)

   # randomly allocate marks "on" and "off"
   # with probabilities p(off) = 0.48, p(on) = 0.52
   Y <- rlabel(amacrine, permute=FALSE)

   # randomly allocate marks "A" and "B" with equal probability
   data(cells)
   Y <- rlabel(cells, labels=factor(c("A", "B")), permute=FALSE)


Simulate Matern Cluster Process

Description

Generate a random point pattern, a simulated realisation of the Mat'ern Cluster Process.

Usage

 rMatClust(kappa, r, mu, win = owin(c(0,1),c(0,1)))

Arguments

kappa | Intensity of the Poisson process of cluster centres. A single positive number, a function, or a pixel image.
r | Radius parameter of the clusters.
mu | Mean number of points per cluster.
win | Window in which to simulate the pattern. An object of class "owin" or something acceptable to as.owin.

Details

This algorithm generates a realisation of Mat'ern's cluster process inside the window win. The process is constructed by first generating a Poisson point process of ``parent'' points with intensity kappa. Then each parent point is replaced by a random cluster of points, the number of points in each cluster being random with a Poisson (mu) distribution, and the points being placed independently and uniformly inside a disc of radius r centred on the parent point.

In this implementation, parent points are not restricted to lie in the window; the parent process is effectively the uniform Poisson process on the infinite plane.

Value

The simulated point pattern (an object of class "ppp").
Additionally, some intermediate results of the simulation are returned as attributes of this point pattern. See rNeymanScott.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

rpoispp, rThomas, rNeymanScott

Examples

 pp <- rMatClust(10, 0.05, 4)


Simulate Matern Model I

Description

Generate a random point pattern, a simulated realisation of the Mat'ern Model I inhibition process model.

Usage

 rMaternI(kappa, r, win = owin(c(0,1),c(0,1)))

Arguments

kappa | Intensity of the Poisson process of proposal points. A single positive number.
r | Inhibition distance.
win | Window in which to simulate the pattern. An object of class "owin" or something acceptable to as.owin.

Details

This algorithm generates a realisation of Mat'ern's Model I inhibition process inside the window win.

The process is constructed by first generating a uniform Poisson point process of ``proposal'' points with intensity kappa inside the window. A proposal point is deleted if it lies within r units' distance of another proposal point. Otherwise it is retained. The retained points constitute Mat'ern's Model I.

Value

The simulated point pattern (an object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

rpoispp, rMatClust

Examples

 pp <- rMaternI(20, 0.05)


Simulate Matern Model II

Description

Generate a random point pattern, a simulated realisation of the Mat'ern Model II inhibition process.

Usage

 rMaternII(kappa, r, win = owin(c(0,1),c(0,1)))

Arguments

kappa | Intensity of the Poisson process of proposal points. A single positive number.
r | Inhibition distance.
win | Window in which to simulate the pattern. An object of class "owin" or something acceptable to as.owin.

Details

This algorithm generates a realisation of Mat'ern's Model II inhibition process inside the window win.

The process is constructed by first generating a uniform Poisson point process of ``proposal'' points with intensity kappa inside the window. Then each proposal point is marked by an ``arrival time'', a number uniformly distributed in [0,1] independently of other variables.

A proposal point is deleted if it lies within r units' distance of another proposal point that has an earlier arrival time. Otherwise it is retained. The retained points constitute Mat'ern's Model II.

The difference between Mat'ern's Model I and II is the italicised statement above. Model II has a higher intensity for the same parameter values.

Value

The simulated point pattern (an object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

rpoispp, rMatClust, rMaternI

Examples

 pp <- rMaternII(20, 0.05)


Simulate point patterns using the Metropolis-Hastings algorithm.

Description

Generic function for running the Metropolis-Hastings algorithm to produce simulated realisations of a point process model.

Usage

rmh(model, ...)

Arguments

model | The point process model to be simulated.
... | Further arguments controlling the simulation.

Details

The Metropolis-Hastings algorithm can be used to generate simulated realisations from a wide range of spatial point processes. For caveats, see below.

The function rmh is generic; it has methods rmh.ppm (for objects of class "ppm") and rmh.default (the default). The actual implementation of the Metropolis-Hastings algorithm is contained in rmh.default. For details of its use, see rmh.ppm or rmh.default.

[If the model is a Poisson process, then Metropolis-Hastings is not used; the Poisson model is generated directly using rpoispp or rmpoispp.]

In brief, the Metropolis-Hastings algorithm is a Markov Chain, whose states are spatial point patterns, and whose limiting distribution is the desired point process. After running the algorithm for a very large number of iterations, we may regard the state of the algorithm as a realisation from the desired point process.

However, there are difficulties in deciding whether the algorithm has run for ``long enough''. The convergence of the algorithm may indeed be extremely slow. No guarantees of convergence are given!

While it is fashionable to decry the Metropolis-Hastings algorithm for its poor convergence and other properties, it has the advantage of being easy to implement for a wide range of models.

Value

A point pattern, in the form of an object of class "ppp". See rmh.default for details.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

rmh.default

Examples

    # See examples in rmh.default and rmh.ppm


Simulate Point Process Models using the Metropolis-Hastings Algorithm.

Description

Generates a random point pattern, simulated from a chosen point process model, using the Metropolis-Hastings algorithm.

Usage

## Default S3 method:
rmh(model, start, control, verbose=TRUE, ...)

Arguments

model | Data specifying the point process model that is to be simulated.
start | Data determining the initial state of the algorithm.
control | Data controlling the iterative behaviour and termination of the algorithm.
verbose | Logical flag indicating whether to print progress reports.
... | Further arguments which will be passed to any trend functions in model.

Details

This function generates simulated realisations from any of a range of spatial point processes, using the Metropolis-Hastings algorithm. It is the default method for the generic function rmh.

This function executes a Metropolis-Hastings algorithm with birth, death and shift proposals as described in Geyer and Moller (1994).

The argument model specifies the point process model to be simulated. It is either a list, or an object of class "rmhmodel", with the following components:

cif
A character string specifying the choice of interpoint interaction for the point process.
par
Parameter values for the conditional intensity function.
w
(Optional) window in which the pattern is to be generated. An object of class "owin", or data acceptable to as.owin.
trend
Data specifying the spatial trend in the model, if it has a trend. This may be a function, a pixel image (of class "im"), (or a list of functions or images if the model is multitype).

If the trend is a function or functions, any auxiliary arguments ... to rmh.default will be passed to these functions, which should be of the form function(x, y, ...).

types
List of possible types, for a multitype point process.

For full details of these parameters, see rmhmodel.

The argument start determines the initial state of the Metropolis-Hastings algorithm. It is either a list, or an object of class "rmhstart", with the following components:

n.start
Number of points in the initial point pattern. A single integer, or a vector of integers giving the numbers of points of each type in a multitype point pattern. Incompatible with x.start.
x.start
Initial point pattern configuration. Incompatible with n.start.

x.start may be a point pattern (an object of class "ppp"), or data which can be coerced to this class by as.ppp, or an object with components x and y, or a two-column matrix. In the last two cases, the window for the pattern is determined by model$w. In the first two cases, if model$w is also present, then the final simulated pattern will be clipped to the window model$w.

iseed
(Optional) seed for random number generator. A triple of integers. Should not be specified in normal usage!

For full details of these parameters, see rmhstart.

The third argument control controls the simulation procedure, iterative behaviour, and termination of the Metropolis-Hastings algorithm. It is either a list, or an object of class "rmhcontrol", with components:

p
The probability of proposing a ``shift'' (as opposed to a birth or death) in the Metropolis-Hastings algorithm.
q
The conditional probability of proposing a death (rather than a birth) given that birth/death has been chosen over shift.
nrep
The number of repetitions or iterations to be made by the Metropolis-Hastings algorithm. It should be large.
expand
Either a numerical expansion factor, or a window (object of class "owin"). Indicates that the process is to be simulated on a larger domain than the original data window w, then clipped to w when the algorithm has finished.

If the model has a trend, then in order for expansion to be feasible, the trend must be given either as a function, or an image whose bounding box is large enough to contain the expanded window.

periodic
A logical scalar; if periodic is TRUE we simulate a process on the torus formed by identifying opposite edges of a rectangular window.
ptypes
A vector of probabilities (summing to 1) to be used in assigning a random type to a new point.
fixall
A logical scalar specifying whether to condition on the number of points of each type.
nverb
An integer specifying how often ``progress reports'' (which consist simply of the number of repetitions completed) should be printed out. If nverb is left at 0, the default, the simulation proceeds silently.

For full details of these parameters, see rmhcontrol.

It is possible to simulate the model conditionally upon the number of points, or in the case of multitype processes, upon the number of points of each type. To condition upon the total number of points, set control$p (the probability of a shift) equal to 1. The number of points is then determined by the starting state, which may be specified either by setting start$n.start to be a scalar, or by setting the initial pattern start$x.start.

To condition upon the number of points of each type, set control$p equal to 1 and control$fixall to be TRUE. The number of points is then determined by the starting state, which may be specified either by setting start$n.start to be an integer vector, or by setting the initial pattern start$x.start.

When we simulate conditionally, no expansion of the window is possible.

Value

A point pattern (an object of class "ppp", see ppp.object).
The returned value has an attribute info containing modified versions of the arguments model, start, and control which together specify the exact simulation procedure.

Warnings

There is never a guarantee that the Metropolis-Hastings algorithm has converged to its limiting distribution.

If start$x.start is specified then expand is set equal to 1 and simulation takes place in x.start$window. Any specified value for expand is simply ignored.

The presence of both a component w of model and a non-null value for x.start$window makes sense ONLY if w is contained in x.start$window.

For multitype processes make sure that, even if there is to be no trend corresponding to a particular type, there is still a component (a NULL component) for that type, in the list.

Extensions

The argument model$cif matches the name of a Fortran subroutine which calculates the conditional intensity function for the model. It is intended that more options will be added in the future. The very brave user could try to add her own. Note that in addition to writing Fortran code for the new conditional intensity function, the user would have to modify the code in the files cif.f and rmh.default.R appropriately. (And of course re-install the spatstat package so as to update the dynamically loadable shared object spatstat.so.)

Note that the lookup conditional intensity function permits the simulation (in theory, to any desired degree of approximation) of any pairwise interaction process for which the interaction depends only on the distance between the pair of points.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point patterns. Australian and New Zealand Journal of Statistics 42, 283 – 322.

Diggle, P. J. (2003) Statistical Analysis of Spatial Point Patterns (2nd ed.) Arnold, London.

Diggle, P.J. and Gratton, R.J. (1984) Monte Carlo methods of inference for implicit statistical models. Journal of the Royal Statistical Society, series B 46, 193 – 212.

Diggle, P.J., Gates, D.J., and Stibbard, A. (1987) A nonparametric estimator for pairwise-interaction point processes. Biometrika 74, 763 – 770.

Geyer, C.J. and M{o}ller, J. (1994) Simulation procedures and likelihood inference for spatial point processes. Scandinavian Journal of Statistics 21, 359–373.

Geyer, C.J. (1999) Likelihood Inference for Spatial Point Processes. Chapter 3 in O.E. Barndorff-Nielsen, W.S. Kendall and M.N.M. Van Lieshout (eds) Stochastic Geometry: Likelihood and Computation, Chapman and Hall / CRC, Monographs on Statistics and Applied Probability, number 80. Pages 79–140.

See Also

rmh, rmh.ppm, rStrauss, ppp, ppm, Strauss, Softcore, StraussHard, MultiStrauss, MultiStraussHard, DiggleGratton

Examples

   ## Not run:
   nr   <- 1e5
   nv  <- 5000

## End(Not run)

   set.seed(961018)

   # Strauss process.
   mod01 <- list(cif="strauss",par=c(beta=2,gamma=0.2,r=0.7),
                 w=c(0,10,0,10))
   X1.strauss <- rmh(model=mod01,start=list(n.start=80),
                     control=list(nrep=nr,nverb=nv))

   # Strauss process, conditioning on n = 80:
   X2.strauss <- rmh(model=mod01,start=list(n.start=80),
                     control=list(p=1,nrep=nr,nverb=nv))

   # Strauss process equal to pure hardcore:
   mod02 <- list(cif="strauss",par=c(beta=2,gamma=0,r=0.7),w=c(0,10,0,10))
   X3.strauss <- rmh(model=mod02,start=list(n.start=60,iseed=c(42,17,69)),
                     control=list(nrep=nr,nverb=nv))

   # Strauss process in a polygonal window.
   x     <- c(0.55,0.68,0.75,0.58,0.39,0.37,0.19,0.26,0.42)
   y     <- c(0.20,0.27,0.68,0.99,0.80,0.61,0.45,0.28,0.33)
   mod03 <- list(cif="strauss",par=c(beta=2000,gamma=0.6,r=0.07),
                w=owin(poly=list(x=x,y=y)))
   X4.strauss <- rmh(model=mod03,start=list(n.start=90),
                     control=list(nrep=nr,nverb=nv))

   # Strauss process in a polygonal window, conditioning on n = 80.
   X5.strauss <- rmh(model=mod03,start=list(n.start=90),
                     control=list(p=1,nrep=nr,nverb=nv))

   # Strauss process, starting off from X4.strauss, but with the
   # polygonal window replace by a rectangular one.  At the end,
   # the generated pattern is clipped to the original polygonal window.
   xxx <- X4.strauss
   xxx$window <- as.owin(c(0,1,0,1))
   X6.strauss <- rmh(model=mod03,start=list(x.start=xxx),
                     control=list(nrep=nr,nverb=nv))

   # Strauss with hardcore:
   mod04 <- list(cif="straush",par=c(beta=2,gamma=0.2,r=0.7,hc=0.3),
                w=c(0,10,0,10))
   X1.straush <- rmh(model=mod04,start=list(n.start=70),
                     control=list(nrep=nr,nverb=nv))

   # Another Strauss with hardcore (with a perhaps surprising result):
   mod05 <- list(cif="straush",par=c(beta=80,gamma=0.36,r=45,hc=2.5),
                w=c(0,250,0,250))
   X2.straush <- rmh(model=mod05,start=list(n.start=250),
                     control=list(nrep=nr,nverb=nv))

   # Pure hardcore (identical to X3.strauss).
   mod06 <- list(cif="straush",par=c(beta=2,gamma=1,r=1,hc=0.7),
                w=c(0,10,0,10))
   X3.straush <- rmh(model=mod06,start=list(n.start=60, iseed=c(42,17,69)),
                     control=list(nrep=nr,nverb=nv))

   # Soft core:
   par3 <- c(0.8,0.1,0.5)
   w    <- c(0,10,0,10)
   mod07 <- list(cif="sftcr",par=c(beta=0.8,sigma=0.1,kappa=0.5),
                w=c(0,10,0,10))
   X.sftcr <- rmh(model=mod07,start=list(n.start=70),
                  control=list(nrep=nr,nverb=nv))

   # Multitype Strauss:
   beta <- c(0.027,0.008)
   gmma <- matrix(c(0.43,0.98,0.98,0.36),2,2)
   r    <- matrix(c(45,45,45,45),2,2)
   mod08 <- list(cif="straussm",par=list(beta=beta,gamma=gmma,radii=r),
                w=c(0,250,0,250))
   X1.straussm <- rmh(model=mod08,start=list(n.start=80),
                      control=list(ptypes=c(0.75,0.25),nrep=nr,nverb=nv))

   # Multitype Strauss conditioning upon the total number
   # of points being 80:
   X2.straussm <- rmh(model=mod08,start=list(n.start=80),
                      control=list(p=1,ptypes=c(0.75,0.25),nrep=nr,
                                   nverb=nv))

   # Conditioning upon the number of points of type 1 being 60
   # and the number of points of type 2 being 20:
   X3.straussm <- rmh(model=mod08,start=list(n.start=c(60,20)),
                      control=list(fixall=TRUE,p=1,ptypes=c(0.75,0.25),
                                   nrep=nr,nverb=nv))

   # Multitype Strauss hardcore:
   rhc  <- matrix(c(9.1,5.0,5.0,2.5),2,2)
   mod09 <- list(cif="straushm",par=list(beta=beta,gamma=gmma,
                iradii=r,hradii=rhc),w=c(0,250,0,250))
   X.straushm <- rmh(model=mod09,start=list(n.start=80),
                     control=list(ptypes=c(0.75,0.25),nrep=nr,nverb=nv))

   # Multitype Strauss hardcore with trends for each type:
   beta  <- c(0.27,0.08)
   tr3   <- function(x,y){x <- x/250; y <- y/250;
                           exp((6*x + 5*y - 18*x^2 + 12*x*y - 9*y^2)/6)
                         }
                         # log quadratic trend
   tr4   <- function(x,y){x <- x/250; y <- y/250;
                         exp(-0.6*x+0.5*y)}
                        # log linear trend
   mod10 <- list(cif="straushm",par=list(beta=beta,gamma=gmma,
                 iradii=r,hradii=rhc),w=c(0,250,0,250),
                 trend=list(tr3,tr4))
   X1.straushm.trend <- rmh(model=mod10,start=list(n.start=350),
                            control=list(ptypes=c(0.75,0.25),
                            nrep=nr,nverb=nv))

   # Multitype Strauss hardcore with trends for each type, given as images:
   bigwin <- square(250)
   i1 <- as.im(tr3, bigwin)
   i2 <- as.im(tr4, bigwin)
   mod11 <- list(cif="straushm",par=list(beta=beta,gamma=gmma,
                 iradii=r,hradii=rhc),w=bigwin,
                 trend=list(i1,i2))
   X2.straushm.trend <- rmh(model=mod11,start=list(n.start=350),
                            control=list(ptypes=c(0.75,0.25),expand=1,
                            nrep=nr,nverb=nv))

   # Diggle, Gates, and Stibbard:
   mod12 <- list(cif="dgs",par=c(beta=3600,rho=0.08),w=c(0,1,0,1))
   X.dgs <- rmh(model=mod12,start=list(n.start=300),
                control=list(nrep=nr,nverb=nv))

   # Diggle-Gratton:
   mod13 <- list(cif="diggra",
                 par=c(beta=1800,kappa=3,delta=0.02,rho=0.04),
                 w=square(1))
   X.diggra <- rmh(model=mod13,start=list(n.start=300),
                   control=list(nrep=nr,nverb=nv))

   # Geyer:
   mod14 <- list(cif="geyer",par=c(beta=1.25,gamma=1.6,r=0.2,sat=4.5),
                 w=c(0,10,0,10))
   X1.geyer <- rmh(model=mod14,start=list(n.start=200),
                   control=list(nrep=nr,nverb=nv))

   # Geyer; same as a Strauss process with parameters
   # (beta=2.25,gamma=0.16,r=0.7):

   mod15 <- list(cif="geyer",par=c(beta=2.25,gamma=0.4,r=0.7,sat=10000),
                 w=c(0,10,0,10))
   X2.geyer <- rmh(model=mod15,start=list(n.start=200),
                   control=list(nrep=nr,nverb=nv))

   mod16 <- list(cif="geyer",par=c(beta=8.1,gamma=2.2,r=0.08,sat=3))
   data(redwood)
   X3.geyer <- rmh(model=mod16,start=list(x.start=redwood),
                   control=list(periodic=TRUE,nrep=nr,nverb=nv))

   # Geyer, starting from the redwood data set, simulating
   # on a torus, and conditioning on n:
   X4.geyer <- rmh(model=mod16,start=list(x.start=redwood),
                   control=list(p=1,periodic=TRUE,nrep=nr,nverb=nv))

   # Lookup (interaction function h_2 from page 76, Diggle (2003)):
      r <- seq(from=0,to=0.2,length=101)[-1] # Drop 0.
      h <- 20*(r-0.05)
      h[r<0.05] <- 0
      h[r>0.10] <- 1
      mod17 <- list(cif="lookup",par=list(beta=4000,h=h,r=r),w=c(0,1,0,1))
      X.lookup <- rmh(model=mod17,start=list(n.start=100),
                      control=list(nrep=nr,nverb=nv))

   # Strauss with trend
   tr <- function(x,y){x <- x/250; y <- y/250;
                           exp((6*x + 5*y - 18*x^2 + 12*x*y - 9*y^2)/6)
                         }
   beta <- 0.3
   gmma <- 0.5
   r    <- 45
   mod17 <- list(cif="strauss",par=c(beta=beta,gamma=gmma,r=r),w=c(0,250,0,250),
                 trend=tr3)
   X1.strauss.trend <- rmh(model=mod17,start=list(n.start=90),
                           control=list(nrep=nr,nverb=nv))


Simulate from a Fitted Point Process Model

Description

Given a point process model fitted to data, generate a random simulation of the model, using the Metropolis-Hastings algorithm.

Usage

## S3 method for class 'ppm':
rmh(model,start=NULL,
               control=rmhcontrol(),
               ..., verbose=TRUE, project=TRUE)

Arguments

model | A fitted point process model (object of class "ppm", see ppm.object) which it is desired to simulate. This fitted model is usually the result of a call to ppm. See Details below.
start | Data determining the initial state of the Metropolis-Hastings algorithm. See rmhstart for description of these arguments. Defaults to list(x.start=data.ppm(model))
control | Data controlling the running of the Metropolis-Hastings algorithm. See rmhcontrol for description of these arguments.
... | Further arguments passed to rmh.default.
verbose | Logical flag indicating whether to print progress reports.
project | Logical flag indicating what to do if the fitted model is invalid (in the sense that the values of the fitted coefficients do not specify a valid point process). If project=TRUE the closest valid model will be simulated; if project=FALSE an error will occur.

Details

This function generates simulated realisations from a point process model that has been fitted to point pattern data. It is a method for the generic function rmh for the class "ppm" of fitted point process models. To simulate other kinds of point process models, see rmh or rmh.default.

The argument model describes the fitted model. It must be an object of class "ppm" (see ppm.object), and will typically be the result of a call to the point process model fitting function ppm.

The current implementation enables simulation from any fitted model involving the interactions DiggleGratton, Geyer, MultiStrauss, MultiStraussHard, PairPiece, Poisson, Strauss, StraussHard and Softcore, including nonstationary models. See the examples.

It is possible that the fitted coefficients of a point process model may be ``illegal'', i.e. that there may not exist a mathematically well-defined point process with the given parameter values. For example, a Strauss process with interaction parameter gamma > 1 does not exist, but the model-fitting procedure used in ppm will sometimes produce values of gamma greater than 1. In such cases, if project=FALSE then an error will occur, while if project=TRUE then rmh.ppm will find the nearest legal model and simulate this model instead. (The nearest legal model is obtained by projecting the vector of coefficients onto the set of valid coefficient vectors. The result is usually the Poisson process with the same fitted intensity.)

The arguments start and control are lists of parameters determining the initial state and the iterative behaviour, respectively, of the Metropolis-Hastings algorithm. They are passed directly to rmhstart and rmhcontrol respectively. See rmhstart and rmhcontrol for details of these parameters.

Note that if you specify control$expand > 1 (so that the model will be simulated on a window larger than the original data window) then the model must be capable of extrapolation to this larger window. This excludes models which depend on external covariates.

After extracting the relevant information from the fitted model object model, rmh.ppm simply invokes the default rmh algorithm rmh.default, unless the model is Poisson.

If the model is Poisson then the Metropolis-Hastings algorithm is not needed, and the model is simulated directly, using one of rpoispp, rmpoispp, rpoint or rmpoint.

See rmh.default for further information about the implementation, or about the Metropolis-Hastings algorithm.

Value

A point pattern (an object of class "ppp"; see ppp.object).

Warnings

See Warnings in rmh.default.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

rmh, rmhmodel, rmhcontrol, rmhstart, rmh.default, ppp.object, ppm, PairPiece, Poisson, Strauss, StraussHard, Softcore, Geyer, DiggleGratton

Examples

   data(swedishpines)
   X <- swedishpines
   plot(X, main="Swedish Pines data")

   # Poisson process
   fit <- ppm(X, ~1, Poisson())
   Xsim <- rmh(fit)
   plot(Xsim, main="simulation from fitted Poisson model")

   # Strauss process
   fit <- ppm(X, ~1, Strauss(r=7), rbord=7)
   Xsim <- rmh(fit, control=list(nrep=1e3))
   plot(Xsim, main="simulation from fitted Strauss model")

   ## Not run:
   # Strauss process simulated on a larger window
   # then clipped to original window
   Xsim <- rmh(fit, control=list(nrep=1e3, expand=2, periodic=TRUE))

   # Strauss - hard core process
   fit <- ppm(X, ~1, StraussHard(r=7,hc=2), rbord=7)
   Xsim <- rmh(fit, start=list(n.start=X$n), control=list(nrep=1e3))
   plot(Xsim, main="simulation from fitted Strauss hard core model")

   # Geyer saturation process
   fit <- ppm(X, ~1, Geyer(r=7,sat=2), rbord=7)
   Xsim <- rmh(fit, start=list(n.start=X$n), control=list(nrep=1e3))
   plot(Xsim, main="simulation from fitted Geyer model")

   # soft core interaction process
   Q <- quadscheme(X, nd=50)
   fit <- ppm(Q, ~1, Softcore(kappa=0.1))
   Xsim <- rmh(fit, start=list(n.start=X$n), control=list(nrep=1e3))
   plot(Xsim, main="simulation from fitted Soft Core model")

   data(cells)
   plot(cells)
   # Diggle-Gratton pairwise interaction model
   fit <- ppm(cells, ~1, DiggleGratton(0.05, 0.1))
   Xsim <- rmh(fit, start=list(n.start=cells$n), control=list(nrep=1e3))
   plot(Xsim, main="simulation from fitted Diggle-Gratton model")

   X <- rSSI(0.05, 100)
   plot(X, main="new data")

   # piecewise-constant pairwise interaction function
   fit <- ppm(X, ~1, PairPiece(seq(0.02, 0.1, by=0.01)))
   Xsim <- rmh(fit, control=list(nrep=1e3))
   plot(Xsim, main="simulation from fitted pairwise model")

   # marked point pattern
   data(amacrine)
   Y <- amacrine
   plot(Y, main="Amacrine data")

   # marked Poisson models
   fit <- ppm(Y)
   Ysim <- rmh(fit)
   plot(Ysim, main="simulation from ppm(Y)")

   fit <- ppm(Y,~marks)
   Ysim <- rmh(fit)
   plot(Ysim, main="simulation from ppm(Y, ~marks)")

   fit <- ppm(Y,~polynom(x,y,2))
   Ysim <- rmh(fit)
   plot(Ysim, main="simulation from ppm(Y, ~polynom(x,y,2))")

   fit <- ppm(Y,~marks+polynom(x,y,2))
   Ysim <- rmh(fit)
   plot(Ysim, main="simulation from ppm(Y, ~marks+polynom(x,y,2))")

   fit <- ppm(Y,~marks*polynom(x,y,2))
   Ysim <- rmh(fit)
   plot(Ysim, main="simulation from ppm(Y, ~marks*polynom(x,y,2))")

   # multitype Strauss models
   MS <- MultiStrauss(types = levels(Y$marks),
                      radii=matrix(0.07, ncol=2, nrow=2))
   fit <- ppm(Y, ~marks, MS)
   Ysim <- rmh(fit, control=list(nrep=1e3))
   plot(Ysim, main="simulation from fitted Multitype Strauss")

   fit <- ppm(Y,~marks*polynom(x,y,2), MS)
   Ysim <- rmh(fit, control=list(nrep=1e3))
   plot(Ysim, main="simulation from fitted inhomogeneous Multitype Strauss")
   ## End(Not run)


Set Control Parameters for Metropolis-Hastings Algorithm.

Description

Sets up a list of parameters controlling the iterative behaviour of the Metropolis-Hastings algorithm.

Usage

   rmhcontrol(control, ...)
   ## Default S3 method:
   rmhcontrol(control=NULL, ..., p=0.9, q=0.5, nrep=5e5,
                      expand=NULL, periodic=FALSE, ptypes=NULL,
                      fixall=FALSE, nverb=0)

Arguments

control | An existing list of control parameters in some other format. Incompatible with the arguments listed below.
... | There should be no other arguments.
p | Probability of proposing a shift (as against a birth/death)
q | Conditional probability of proposing a death given that a birth or death will be proposed
nrep | Total number of steps (proposals) of Metropolis-Hastings algorithm that should be run
expand | Either a numerical expansion factor, or a window (object of class "owin"), specifying that simulations are to be performed in a domain larger than the original data window, then clipped to the original data window.
periodic | (Logical) whether to simulate ``periodically'', i.e. on a torus formed by identifying opposite edges of a rectangle.
ptypes | For multitype point processes, the distribution of the mark attached to a new random point (when a birth is proposed)
fixall | (Logical) for multitype point processes, whether to fix the number of points of each type.
nverb | Progress reports will be printed every nverb iterations

Details

The Metropolis-Hastings algorithm, implemented as rmh, generates simulated realisations of point process models. This function rmhcontrol sets up a list of parameters which control the iterative behaviour and termination of the Metropolis-Hastings algorithm, for use in a subsequent call to rmh. It also checks that the parameters are valid.

(A separate function rmhstart determines the initial state of the algorithm, and rmhmodel determines the model to be simulated.)

The algorithm control parameters should be specified either by the first argument control or by the other arguments p, q etc.

If control is specified, it may be a list of parameter values (with components named p, q etc, having the same interpretation as described below) or an object of class "rmhcontrol" obtained by a previous call to rmhcontrol.

The parameters are as follows:

p
The probability of proposing a ``shift'' (as opposed to a birth or death) in the Metropolis-Hastings algorithm.

If p = 1 then the algorithm only alters existing points, so the number of points never changes, i.e. we are simulating conditionally upon the number of points. The number of points is determined by the initial state (specified by rmhstart).

If p=1 and fixall=TRUE and the model is a multitype point process model, then the algorithm only shifts the locations of existing points and does not alter their marks (types). This is equivalent to simulating conditionally upon the number of points of each type. These numbers are again specified by the initial state.

If p = 1 then no expansion of the simulation window is allowed (see expand below).

q
The conditional probability of proposing a death (rather than a birth) given that a shift is not proposed. This is of course ignored if p is equal to 1.
nrep
The number of repetitions or iterations to be made by the Metropolis-Hastings algorithm. It should be large.
expand
Either a numerical expansion factor, or a window (object of class "owin"). Indicates that the process is to be simulated on a larger domain than the original data window w, then clipped to w when the algorithm has finished. This would often be done in order to approximate the simulation of a stationary process (Geyer, 1999) or more generally a process existing in the whole plane, rather than just in the window w.

If expand is a window object, it is taken as the larger domain in which simulation is performed. If expand is numeric, it is interpreted as the factor by which the area of the enclosing box of the window w is to be expanded (i.e. width and height are stretched by the same factor sqrt(area)). The expansion is computed by the function expand.owin.

If expand equals 1 then no expansion is performed. Any value of expand smaller than 1 is ignored and treated as 1.

Expansion is not permitted if the number of points has been fixed by setting p = 1 or if the starting configuration has been specified via the argument x.start in rmhstart. In these cases expand defaults to 1.

Otherwise, expand defaults to 2.

periodic
A logical scalar; if periodic is TRUE we simulate a process on the torus formed by identifying opposite edges of a rectangular window. This window could be the ``original'' window if that window is rectangular, or the bounding box of that window, or an expansion of the bounding box (when expand is greater than 1). In the latter two cases the simulated pattern is clipped to the original window.
ptypes
A vector of probabilities (summing to 1) to be used in assigning a random type to a new point. Defaults to a vector each of whose entries is 1/nt where nt is the number of types for the process. Convergence of the simulation algorithm should be improved if ptypes is close to the relative frequencies of the types which will result from the simulation.
fixall
A logical scalar specifying whether to condition on the number of points of each type. Meaningful only if a marked process is being simulated, and if p = 1. A warning message is given if fixall is set equal to TRUE when it is not meaningful.
nverb
An integer specifying how often ``progress reports'' (which consist simply of the number of repetitions completed) should be printed out. If nverb is left at 0, the default, the simulation proceeds silently.

Value

An object of class "rmhcontrol", which is essentially a list of parameter values for the algorithm.
There is a print method for this class, which prints a sensible description of the parameters chosen.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Geyer, C.J. (1999) Likelihood Inference for Spatial Point Processes. Chapter 3 in O.E. Barndorff-Nielsen, W.S. Kendall and M.N.M. Van Lieshout (eds) Stochastic Geometry: Likelihood and Computation, Chapman and Hall / CRC, Monographs on Statistics and Applied Probability, number 80. Pages 79–140.

See Also

rmh, rmhmodel, rmhstart, expand.owin

Examples

   # parameters given as named arguments
   c1 <- rmhcontrol(p=0.3,periodic=TRUE,nrep=1e6,nverb=1e5)

   # parameters given as a list
   liz <- list(p=0.9, nrep=1e4)
   c2 <- rmhcontrol(liz)

   # parameters given in rmhcontrol object
   c3 <- rmhcontrol(c1)


Define Point Process Model for Metropolis-Hastings Simulation.

Description

Builds a description of a point process model for use in simulating the model by the Metropolis-Hastings algorithm.

Usage

  rmhmodel(...)

Arguments

... Arguments specifying the point process model in some format.

Details

Simulated realisations of many point process models can be generated using the Metropolis-Hastings algorithm rmh. The algorithm requires the model to be specified in a particular format: an object of class "rmhmodel".

The function rmhmodel takes a description of a point process model in some other format, and converts it into an object of class "rmhmodel". It also checks that the parameters of the model are valid.

The function rmhmodel is generic, with methods for

fitted point process models:
an object of class "ppm", obtained by a call to the model-fitting function ppm. See rmhmodel.ppm.
lists:
a list of parameter values in a certain format. See rmhmodel.list.
default:
parameter values specified as separate arguments to .... See rmhmodel.default.

Value

An object of class "rmhmodel", which is essentially a list of parameter values for the model.
There is a print method for this class, which prints a sensible description of the model chosen.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Diggle, P. J. (2003) Statistical Analysis of Spatial Point Patterns (2nd ed.) Arnold, London.

Diggle, P.J. and Gratton, R.J. (1984) Monte Carlo methods of inference for implicit statistical models. Journal of the Royal Statistical Society, series B 46, 193 – 212.

Diggle, P.J., Gates, D.J., and Stibbard, A. (1987) A nonparametric estimator for pairwise-interaction point processes. Biometrika 74, 763 – 770. Scandinavian Journal of Statistics 21, 359–373.

Geyer, C.J. (1999) Likelihood Inference for Spatial Point Processes. Chapter 3 in O.E. Barndorff-Nielsen, W.S. Kendall and M.N.M. Van Lieshout (eds) Stochastic Geometry: Likelihood and Computation, Chapman and Hall / CRC, Monographs on Statistics and Applied Probability, number 80. Pages 79–140.

See Also

rmhmodel.ppm, rmhmodel.default, rmhmodel.list, rmh, rmhcontrol, rmhstart, ppm, Strauss, Softcore, StraussHard, MultiStrauss, MultiStraussHard, DiggleGratton, PairPiece


Build Point Process Model for Metropolis-Hastings Simulation.

Description

Builds a description of a point process model for use in simulating the model by the Metropolis-Hastings algorithm.

Usage

  ## Default S3 method:
  rmhmodel(...,
         cif=NULL, par=NULL, w=NULL, trend=NULL, types=NULL)

Arguments

... | Ignored.
cif | Character string specifying the choice of model
par | Parameters of the model
w | Spatial window in which to simulate
trend | Specification of the trend in the model
types | A vector of factor levels defining the possible marks, for a multitype process.

Details

The generic function rmhmodel takes a description of a point process model in some format, and converts it into an object of class "rmhmodel" so that simulations of the model can be generated using the Metropolis-Hastings algorithm rmh.

This function rmhmodel.default is the default method. It builds a description of the point process model from the simple arguments listed.

The argument cif is a character string specifying the choice of interpoint interaction for the point process. The current options are

'strauss'
The Strauss process
'straush'
The Strauss process with hard core
'sftcr'
The Softcore process
'straussm'
The multitype Strauss process
'straushm'
Multitype Strauss process with hard core
'dgs'
Diggle, Gates and Stibbard (1987) process
'diggra'
Diggle and Gratton (1984) process
'geyer'
Saturation process (Geyer, 1999).
'lookup'
General isotropic pairwise interaction process, with the interaction function specified via a ``lookup table''.

The argument par supplies parameter values appropriate to the conditional intensity function being invoked. These are:

strauss:
(Strauss process.) A named vector with components beta,gamma,r which are respectively the ``base'' intensity, the pair-wise interaction parameter and the interaction radius. Note that gamma must be less than or equal to 1. (Note that there is also an algorithm for perfect simulation of the Strauss process, rStrauss)
straush:
(Strauss process with hardcore.) A named vector with entries beta,gamma,r,hc where beta, gamma, and r are as for the Strauss process, and hc is the hardcore radius. Of course hc must be less than r.
sftcr:
(Softcore process.) A named vector with components beta,sigma,kappa. Again beta is a ``base'' intensity. The pairwise interaction between two points u != v is

-(sigma/||u-v||)^(2/kappa)

Note that it is necessary that 0 < kappa <1.

straussm:
(Multitype Strauss process.) A named list with components
  • beta: A vector of ``base'' intensities, one for each possible type.
  • gamma: A symmetric matrix of interaction parameters, with gamma_ij pertaining to the interaction between type i and type j.
  • radii: A symmetric matrix of interaction radii, with entries r_ij pertaining to the interaction between type i and type j.
straushm:
(Multitype Strauss process with hardcore.) A named list with components beta and gamma as for straussm and two ``radii'' components:
  • iradii: the interaction radii
  • hradii: the hardcore radii

which are both symmetric matrices of nonnegative numbers. The entries of hradii must be less than the corresponding entries of iradii.

dgs:
(Diggle, Gates, and Stibbard process. See Diggle, Gates, and Stibbard (1987)) A named vector with components beta and rho. This process has pairwise interaction function equal to

e(t) = sin^2((pi * t)/(2 * rho))

for t < rho, and equal to 1 for t >= rho.

diggra:
(Diggle-Gratton process. See Diggle and Gratton (1984) and Diggle, Gates and Stibbard (1987).) A named vector with components beta, kappa, delta and rho. This process has pairwise interaction function e(t) equal to 0 for t < delta, equal to

((t-delta)/(rho-delta))^kappa

for delta <= t < rho, and equal to 1 for t >= rho. Note that here we use the symbol kappa where Diggle, Gates, and Stibbard use beta since we reserve the symbol beta for an intensity parameter.

geyer:
(Geyer's saturation process. See Geyer (1999).) A named vector with components beta, gamma, r, and sat. The components beta, gamma, r are as for the Strauss model, and sat is the ``saturation'' parameter. The model is Geyer's ``saturation'' point process model, a modification of the Strauss process in which we effectively impose an upper limit (sat) on the number of neighbours which will be counted as close to a given point.

Explicitly, a saturation point process with interaction radius r, saturation threshold s, and parameters beta and gamma, is the point process in which each point x[i] in the pattern X contributes a factor

beta gamma^min(s,t(x[i],X))

to the probability density of the point pattern, where t(x[i],X) denotes the number of ``r-close neighbours'' of x[i] in the pattern X.

If the saturation threshold s is infinite, the Geyer process reduces to a Strauss process with interaction parameter gamma^2 rather than gamma.

lookup:
(Arbitrary pairwise interaction process with isotropic interaction.) A named list with components beta, r, and h, or just with components beta and h.

This model is the pairwise interaction process with an isotropic interaction given by any chosen function H. Each pair of points x[i], x[j] in the point pattern contributes a factor H(d(x[i],x[j])) to the probability density, where d denotes distance and H is the pair interaction function.

The component beta is a (positive) scalar which determines the ``base'' intensity of the process.

In this implementation, H must be a step function. It is specified by the user in one of two ways.

  • as a vector of values: If r is present, then r is assumed to give the locations of jumps in the function H, while the vector h gives the corresponding values of the function.

    Specifically, the interaction function H(t) takes the value h[1] for distances t in the interval [0, r[1]); takes the value h[i] for distances t in the interval [r[i-1], r[i]) where i = 2, ..., n; and takes the value 1 for t >= r[n]. Here n denotes the length of r.

    The components r and h must be numeric vectors of equal length. The r values must be strictly positive, and sorted in increasing order.

    The entries of h must be non-negative. If any entry of h is greater than 1, then the entry h[1] must be 0 (otherwise the specified process is non-existent).

    Greatest efficiency is achieved if the values of r are equally spaced.

    [Note: The usage of r and h has changed from the previous usage in spatstat versions 1.4-7 to 1.5-1, in which ascending order was not required, and in which the first entry of r had to be 0.]

  • as a stepfun object: If r is absent, then h must be an object of class "stepfun" specifying a step function. Such objects are created by stepfun.

    The stepfun object h must be right-continuous (which is the default using stepfun.)

    The values of the step function must all be nonnegative. The values must all be less than 1 unless the function is identically zero on some initial interval [0,r). The rightmost value (the value of h(t) for large t) must be equal to 1.

    Greatest efficiency is achieved if the jumps (the ``knots'' of the step function) are equally spaced.

The optional argument trend determines the spatial trend in the model, if it has one. It should be a function or image (or a list of such, if the model is multitype) to provide the value of the trend at an arbitrary point.

trend given as a function:
A trend function may be a function of any number of arguments, but the first two must be the eqn{x,y} coordinates of a point. Auxiliary arguments may be passed to the trend function at the time of simulation, via the ... argument to rmh.

The function must be vectorized. That is, it must be capable of accepting vector valued x and y arguments. Put another way, it must be capable of calculating the trend value at a number of points, simultaneously, and should return the vector of corresponding trend values.

trend given as an image:
An image (see im.object) provides the trend values at a grid of points in the observation window and determines the trend value at other points as the value at the nearest grid point.

Note that the trend or trends must be non-negative; no checking is done for this.

The optional argument w specifies the window in which the pattern is to be generated. If specified, it must be in a form which can be coerced to an object of class owin by as.owin.

The optional argument types specifies the possible types in a multitype point process. If the model being simulated is multitype, and types is not specified, then this vector defaults to 1:ntypes where ntypes is the number of types.

Value

An object of class "rmhmodel", which is essentially a list of parameter values for the model.
There is a print method for this class, which prints a sensible description of the model chosen.

Warnings in Respect of “lookup”

The syntax of rmh.default in respect of the lookup cif has changed from the previous release of spatstat (versions 1.4-7 to 1.5-1). Read the Details carefully. In particular it is now required that the first entry of the r component of par be strictly positive. (This is the opposite of what was required in the previous release, which was that this first entry had to be 0.)

It is also now required that the entries of r be sorted into ascending order. (In the previous release it was assumed that the entries of r and h were in corresponding order and the two vectors were sorted commensurately. It was decided that this is dangerous sand unnecessary.)

Note that if you specify the lookup pairwise interaction function via stepfun() the arguments x and y which are passed to stepfun() are slightly different from r and h: length(y) is equal to 1+length(x); the final entry of y must be equal to 1 — i.e. this value is explicitly supplied by the user rather than getting tacked on internally.

The step function returned by stepfun() must be right continuous (this is the default behaviour of stepfun()) otherwise an error is given.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Diggle, P. J. (2003) Statistical Analysis of Spatial Point Patterns (2nd ed.) Arnold, London.

Diggle, P.J. and Gratton, R.J. (1984) Monte Carlo methods of inference for implicit statistical models. Journal of the Royal Statistical Society, series B 46, 193 – 212.

Diggle, P.J., Gates, D.J., and Stibbard, A. (1987) A nonparametric estimator for pairwise-interaction point processes. Biometrika 74, 763 – 770. Scandinavian Journal of Statistics 21, 359–373.

Geyer, C.J. (1999) Likelihood Inference for Spatial Point Processes. Chapter 3 in O.E. Barndorff-Nielsen, W.S. Kendall and M.N.M. Van Lieshout (eds) Stochastic Geometry: Likelihood and Computation, Chapman and Hall / CRC, Monographs on Statistics and Applied Probability, number 80. Pages 79–140.

See Also

rmh, rmhcontrol, rmhstart, ppm, Strauss, Softcore, StraussHard, MultiStrauss, MultiStraussHard, DiggleGratton, PairPiece

Examples

   # Strauss process:
   mod01 <- rmhmodel(cif="strauss",par=c(beta=2,gamma=0.2,r=0.7),
                 w=c(0,10,0,10))
   # The above could also be simulated using 'rStrauss'

   # Strauss with hardcore:
   mod04 <- rmhmodel(cif="straush",par=c(beta=2,gamma=0.2,r=0.7,hc=0.3),
                w=owin(c(0,10),c(0,5)))

   # Soft core:
   par3 <- c(0.8,0.1,0.5)
   w    <- square(10)
   mod07 <- rmhmodel(cif="sftcr",
                     par=c(beta=0.8,sigma=0.1,kappa=0.5),
                     w=w)

   # Multitype Strauss:
   beta <- c(0.027,0.008)
   gmma <- matrix(c(0.43,0.98,0.98,0.36),2,2)
   r    <- matrix(c(45,45,45,45),2,2)
   mod08 <- rmhmodel(cif="straussm",
                     par=list(beta=beta,gamma=gmma,radii=r),
                     w=square(250))
   # specify types
   mod09 <- rmhmodel(cif="straussm",
                     par=list(beta=beta,gamma=gmma,radii=r),
                     w=square(250),
                     types=c("A", "B"))

   # Multitype Strauss hardcore with trends for each type:
   beta  <- c(0.27,0.08)
   ri    <- matrix(c(45,45,45,45),2,2)
   rhc  <- matrix(c(9.1,5.0,5.0,2.5),2,2)
   tr3   <- function(x,y){x <- x/250; y <- y/250;
                           exp((6*x + 5*y - 18*x^2 + 12*x*y - 9*y^2)/6)
                         }
                         # log quadratic trend
   tr4   <- function(x,y){x <- x/250; y <- y/250;
                         exp(-0.6*x+0.5*y)}
                        # log linear trend
   mod10 <- rmhmodel(cif="straushm",par=list(beta=beta,gamma=gmma,
                 iradii=ri,hradii=rhc),w=c(0,250,0,250),
                 trend=list(tr3,tr4))

   # Lookup (interaction function h_2 from page 76, Diggle (2003)):
      r <- seq(from=0,to=0.2,length=101)[-1] # Drop 0.
      h <- 20*(r-0.05)
      h[r<0.05] <- 0
      h[r>0.10] <- 1
      mod17 <- rmhmodel(cif="lookup",par=list(beta=4000,h=h,r=r),w=c(0,1,0,1))


Define Point Process Model for Metropolis-Hastings Simulation.

Description

Given a list of parameters, builds a description of a point process model for use in simulating the model by the Metropolis-Hastings algorithm.

Usage

   ## S3 method for class 'list':
   rmhmodel(model, ...)

Arguments

model | A list of parameters. See Details.
... | There should be no other arguments.

Details

The generic function rmhmodel takes a description of a point process model in some format, and converts it into an object of class "rmhmodel" so that simulations of the model can be generated using the Metropolis-Hastings algorithm rmh.

This function rmhmodel.list is the method for lists. The argument model should be a named list of parameters of the form

list(cif, par, w, trend, types)

where cif and par are required and the others are optional. For details about these components, see rmhmodel.default.

Value

An object of class "rmhmodel", which is essentially a validated list of parameter values for the model.
There is a print method for this class, which prints a sensible description of the model chosen.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Diggle, P. J. (2003) Statistical Analysis of Spatial Point Patterns (2nd ed.) Arnold, London.

Diggle, P.J. and Gratton, R.J. (1984) Monte Carlo methods of inference for implicit statistical models. Journal of the Royal Statistical Society, series B 46, 193 – 212.

Diggle, P.J., Gates, D.J., and Stibbard, A. (1987) A nonparametric estimator for pairwise-interaction point processes. Biometrika 74, 763 – 770. Scandinavian Journal of Statistics 21, 359–373.

Geyer, C.J. (1999) Likelihood Inference for Spatial Point Processes. Chapter 3 in O.E. Barndorff-Nielsen, W.S. Kendall and M.N.M. Van Lieshout (eds) Stochastic Geometry: Likelihood and Computation, Chapman and Hall / CRC, Monographs on Statistics and Applied Probability, number 80. Pages 79–140.

See Also

rmhmodel, rmhmodel.default, rmhmodel.ppm, rmh, rmhcontrol, rmhstart, ppm, Strauss, Softcore, StraussHard, MultiStrauss, MultiStraussHard, DiggleGratton, PairPiece

Examples

   # Strauss process:
   mod01 <- list(cif="strauss",par=c(beta=2,gamma=0.2,r=0.7),
                 w=c(0,10,0,10))
   mod01 <- rmhmodel(mod01)

   # Strauss with hardcore:
   mod04 <- list(cif="straush",par=c(beta=2,gamma=0.2,r=0.7,hc=0.3),
                w=owin(c(0,10),c(0,5)))
   mod04 <- rmhmodel(mod04)

   # Soft core:
   par3 <- c(0.8,0.1,0.5)
   w    <- square(10)
   mod07 <- list(cif="sftcr",
                     par=c(beta=0.8,sigma=0.1,kappa=0.5),
                     w=w)
   mod07 <- rmhmodel(mod07)

   # Multitype Strauss:
   beta <- c(0.027,0.008)
   gmma <- matrix(c(0.43,0.98,0.98,0.36),2,2)
   r    <- matrix(c(45,45,45,45),2,2)
   mod08 <- list(cif="straussm",
                     par=list(beta=beta,gamma=gmma,radii=r),
                     w=square(250))
   mod08 <- rmhmodel(mod08)

   # specify types
   mod09 <- rmhmodel(list(cif="straussm",
                     par=list(beta=beta,gamma=gmma,radii=r),
                     w=square(250),
                     types=c("A", "B")))

   # Multitype Strauss hardcore with trends for each type:
   beta  <- c(0.27,0.08)
   ri    <- matrix(c(45,45,45,45),2,2)
   rhc  <- matrix(c(9.1,5.0,5.0,2.5),2,2)
   tr3   <- function(x,y){x <- x/250; y <- y/250;
                           exp((6*x + 5*y - 18*x^2 + 12*x*y - 9*y^2)/6)
                         }
                         # log quadratic trend
   tr4   <- function(x,y){x <- x/250; y <- y/250;
                         exp(-0.6*x+0.5*y)}
                        # log linear trend
   mod10 <- list(cif="straushm",par=list(beta=beta,gamma=gmma,
                 iradii=ri,hradii=rhc),w=c(0,250,0,250),
                 trend=list(tr3,tr4))
   mod10 <- rmhmodel(mod10)

   # Lookup (interaction function h_2 from page 76, Diggle (2003)):
   r <- seq(from=0,to=0.2,length=101)[-1] # Drop 0.
   h <- 20*(r-0.05)
   h[r<0.05] <- 0
   h[r>0.10] <- 1
   mod17 <- list(cif="lookup",par=list(beta=4000,h=h,r=r),w=c(0,1,0,1))
   mod17 <- rmhmodel(mod17)


Interpret Fitted Model for Metropolis-Hastings Simulation.

Description

Converts a fitted point process model into a format that can be used to simulate the model by the Metropolis-Hastings algorithm.

Usage

  ## S3 method for class 'ppm':
  rmhmodel(model, win, ..., verbose=TRUE, project=TRUE,
                         control=rmhcontrol())

Arguments

model | Fitted point process model (object of class "ppm").
win | Optional. Window in which the simulations should be generated.
... | Ignored.
verbose | Logical flag indicating whether to print progress reports while the model is being converted.
project | Logical flag indicating what to do if the fitted model does not correspond to a valid point process. See Details.
control | Parameters determining the iterative behaviour of the simulation algorithm. Passed to rmhcontrol.

Details

The generic function rmhmodel takes a description of a point process model in some format, and converts it into an object of class "rmhmodel" so that simulations of the model can be generated using the Metropolis-Hastings algorithm rmh.

This function rmhmodel.ppm is the method for the class "ppm" of fitted point process models.

The argument model should be a fitted point process model (object of class "ppm") typically obtained from the model-fitting function ppm. This will be converted into an object of class "rmhmodel".

The optional argument win specifies the window in which the pattern is to be generated. If specified, it must be in a form which can be coerced to an object of class owin by as.owin.

Not all fitted point process models obtained from ppm can be simulated. We have not yet implemented simulation code for the LennardJones and OrdThresh models.

It is also possible that a fitted point process model obtained from ppm may not correspond to a valid point process. For example a fitted model with the Strauss interpoint interaction may have any value of the interaction parameter gamma; however the Strauss process is not well-defined for gamma > 1 (Kelly and Ripley, 1976).

The argument project determines what to do in such cases. If project=FALSE, a fatal error will occur. If project=TRUE, the fitted model parameters will be adjusted to the nearest values which do correspond to a valid point process. For example a Strauss process with gamma > 1 will be projected to a Strauss process with gamma = 1, equivalent to a Poisson process.

Value

An object of class "rmhmodel", which is essentially a list of parameter values for the model.
There is a print method for this class, which prints a sensible description of the model chosen.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Diggle, P. J. (2003) Statistical Analysis of Spatial Point Patterns (2nd ed.) Arnold, London.

Diggle, P.J. and Gratton, R.J. (1984) Monte Carlo methods of inference for implicit statistical models. Journal of the Royal Statistical Society, series B 46, 193 – 212.

Geyer, C.J. (1999) Likelihood Inference for Spatial Point Processes. Chapter 3 in O.E. Barndorff-Nielsen, W.S. Kendall and M.N.M. Van Lieshout (eds) Stochastic Geometry: Likelihood and Computation, Chapman and Hall / CRC, Monographs on Statistics and Applied Probability, number 80. Pages 79–140.

Kelly, F.P. and Ripley, B.D. (1976) On Strauss's model for clustering. Biometrika 63, 357–360.

See Also

rmhmodel, rmhmodel.list, rmhmodel.default, rmh, rmhcontrol, rmhstart, ppm, Strauss, Softcore, StraussHard, MultiStrauss, MultiStraussHard, DiggleGratton, PairPiece

Examples

  data(cells)
  fit <- ppm(cells, ~1, Strauss(0.07))
  mod1 <- rmhmodel(fit)

  fit2 <- ppm(cells, ~1, Geyer(0.07, 2))
  mod2 <- rmhmodel(fit2)

 # Then rmh(mod1), etc


Determine Initial State for Metropolis-Hastings Simulation.

Description

Builds a description of the initial state for the Metropolis-Hastings algorithm.

Usage

   rmhstart(start, ...)
   ## Default S3 method:
   rmhstart(start=NULL, ..., n.start=NULL, x.start=NULL, iseed)

Arguments

start | An existing description of the initial state in some format. Incompatible with the arguments listed below.
... | There should be no other arguments.
n.start | Number of initial points (to be randomly generated). Incompatible with x.start.
x.start | Initial point pattern configuration. Incompatible with n.start.
iseed | Vector of 3 integers determining the initial state of the random number generator. This argument should not be specified, in normal use.

Details

Simulated realisations of many point process models can be generated using the Metropolis-Hastings algorithm implemented in rmh.

This function rmhstart creates a full description of the initial state of the Metropolis-Hastings algorithm, including possibly the initial state of the random number generator, for use in a subsequent call to rmh. It also checks that the initial state is valid.

The initial state should be specified either by the first argument start or by the other arguments n.start, x.start etc.

If start is a list, then it should have components named n.start or x.start and optionally iseed, with the same interpretation as described below.

The arguments are:

n.start
The number of ``initial'' points to be randomly (uniformly) generated in the simulation window w. Incompatible with x.start.

For a multitype point process, n.start may be a vector (of length equal to the number of types) giving the number of points of each type to be generated.

If expansion of the simulation window is selected (see the argument expand to rmhcontrol), then n.start will be multiplied by the expansion factor (ratio of the areas of the expanded window and original window).

For faster convergence of the Metropolis-Hastings algorithm, the value of n.start should be roughly equal to (an educated guess at) the expected number of points which will be generated inside the window.

x.start
Initial point pattern configuration. Incompatible with n.start.

x.start may be a point pattern (an object of class ppp), or an object which can be coerced to this class by as.ppp, or a dataset containing vectors x and y.

If x.start is specified, then expansion of the simulation window (the argument expand of rmhcontrol) is not permitted.

iseed
Seed for the random number generator. A vector of three integers.

If given, this seed will fix the initial state of the random number generator in any subsequent call to rmh.

This should only be done if it is desired to repeat the algorithm with exactly the same sequence of random numbers!

The parameters n.start and x.start are incompatible.

Value

An object of class "rmhstart", which is essentially a list of parameters describing the initial point pattern and (optionally) the initial state of the random number generator.
There is a print method for this class, which prints a sensible description of the initial state.

Warnings

If iseed is specified, this will fix the initial state of the random number generator in any subsequent call to rmh.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

rmh, rmhcontrol, rmhmodel

Examples

   # 30 random points
   a <- rmhstart(n.start=30)

   # a particular point pattern
   data(cells)
   b <- rmhstart(x.start=cells)

   # set the seed
   d <- rmhstart(n.start=30, iseed=c(42, 4, 2))


Generate N Random Multitype Points

Description

Generate a random multitype point pattern with a fixed number of points, or a fixed number of points of each type.

Usage

 rmpoint(n, f=1, fmax=NULL, win=unit.square(),
         types, ptypes,
         ..., giveup=1000, verbose=FALSE)

Arguments

n | Number of marked points to generate. Either a single number specifying the total number of points, or a vector specifying the number of points of each type.
f | The probability density of the multitype points, usually un-normalised. Either a constant, a vector, a function f(x,y,m, ...), a pixel image, a list of functions f(x,y,...) or a list of pixel images.
fmax | An upper bound on the values of f. If missing, this number will be estimated.
win | Window in which to simulate the pattern. Ignored if f is a pixel image or list of pixel images.
types | All the possible types for the multitype pattern.
ptypes | Optional vector of probabilities for each type.
... | Arguments passed to f if it is a function.
giveup | Number of attempts in the rejection method after which the algorithm should stop trying to generate new points.
verbose | Flag indicating whether to report details of performance of the simulation algorithm.

Details

This function generates random multitype point patterns consisting of a fixed number of points.

Three different models are available:

I. Random location and type:
If n is a single number and the argument ptypes is missing, then n independent, identically distributed random multitype points are generated. Their locations (x[i],y[i]) and types m[i] have joint probability density proportional to f(x,y,m).
II. Random type, and random location given type:
If n is a single number and ptypes is given, then n independent, identically distributed random multitype points are generated. Their types m[i] have probability distribution ptypes. Given the types, the locations (x[i],y[i]) have conditional probability density proportional to f(x,y,m).
III. Fixed types, and random location given type:
If n is a vector, then we generate n[i] independent, identically distributed random points of type types[i]. For points of type m the conditional probability density of location (x,y) is proportional to f(x,y,m).

Note that the density f is normalised in different ways in Model I and Models II and III. In Model I the normalised joint density is g(x,y,m)=f(x,y,m)/Z where

Z = sum_[m] integral lambda(x,y,m) dx dy

while in Models II and III the normalised conditional density is g(x,y|m) = f(x,y,m)/Z[m] where

Z[m] = integral lambda(x,y,m) dx dy.

In Model I, the marginal distribution of types is p[m] = Z[m]/Z.

The unnormalised density f may be specified in any of the following ways.

single number:
If f is a single number, the conditional density of location given type is uniform. That is, the points of each type are uniformly distributed. In Model I, the marginal distribution of types is also uniform (all possible types have equal probability).
vector:
If f is a numeric vector, the conditional density of location given type is uniform. That is, the points of each type are uniformly distributed. In Model I, the marginal distribution of types is proportional to the vector f. In Model II, the marginal distribution of types is ptypes, that is, the values in f are ignored.
function:
If f is a function, it will be called in the form f(x,y,m,...) at spatial location (x,y) for points of type m. In Model I, the joint probability density of location and type is proportional to f(x,y,m,...). In Models II and III, the conditional probability density of location (x,y) given type m is proportional to f(x,y,m,...). The function f must work correctly with vectors x, y and m, returning a vector of function values. (Note that m will be a factor with levels types.) The value fmax must be given and must be an upper bound on the values of f(x,y,m,...) for all locations (x, y) inside the window win and all types m. The argument types must be given.
list of functions:
If f is a list of functions, then the functions will be called in the form f[[i]](x,y,...) at spatial location (x,y) for points of type types[i]. In Model I, the joint probability density of location and type is proportional to f[[m]](x,y,...). In Models II and III, the conditional probability density of location (x,y) given type m is proportional to f[[m]](x,y,...). The function f[[i]] must work correctly with vectors x and y, returning a vector of function values. The value fmax must be given and must be an upper bound on the values of f[[i]](x,y,...) for all locations (x, y) inside the window win. The argument types defaults to seq(f).
pixel image:
If f is a pixel image object of class "im" (see im.object), the unnormalised density at a location (x,y) for points of any type is equal to the pixel value of f for the pixel nearest to (x,y). In Model I, the marginal distribution of types is uniform. The argument win is ignored; the window of the pixel image is used instead. The argument types must be given.
list of pixel images:
If f is a list of pixel images, then the image f[[i]] determines the density values of points of type types[i]. The argument win is ignored; the window of the pixel image is used instead. The argument types defaults to factor(seq(f)).

The implementation uses the rejection method. For Model I, rmpoispp is called repeatedly until n points have been generated. It gives up after giveup calls if there are still fewer than n points. For Model II, the types are first generated according to ptypes, then the locations of the points of each type are generated using rpoint. For Model III, the locations of the points of each type are generated using rpoint.

Value

The simulated point pattern (an object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp.object, owin.object

Examples

abc <- c("a","b","c")

##### Model I

rmpoint(25, types=abc)
rmpoint(25, 1, types=abc)
# 25 points, equal probability for each type, uniformly distributed locations

rmpoint(25, function(x,y,m) {rep(1, length(x))}, types=abc)
# same as above
rmpoint(25, list(function(x,y){rep(1, length(x))},
                 function(x,y){rep(1, length(x))},
                 function(x,y){rep(1, length(x))}),
             types=abc)
# same as above

rmpoint(25, function(x,y,m) { x }, types=abc)
# 25 points, equal probability for each type,
# locations nonuniform with density proportional to x

rmpoint(25, function(x,y,m) { ifelse(m == "a", 1, x) }, types=abc)
rmpoint(25, list(function(x,y) { rep(1, length(x)) },
                function(x,y) { x },
                function(x,y) { x }),
                types=abc)
# 25 points, UNEQUAL probabilities for each type,
# type "a" points uniformly distributed,
# type "b" and "c" points nonuniformly distributed.

##### Model II

rmpoint(25, 1, types=abc, ptypes=rep(1,3)/3)
rmpoint(25, 1, types=abc, ptypes=rep(1,3))
# 25 points, equal probability for each type,
# uniformly distributed locations

rmpoint(25, function(x,y,m) {rep(1, length(x))}, types=abc, ptypes=rep(1,3))
# same as above
rmpoint(25, list(function(x,y){rep(1, length(x))},
                 function(x,y){rep(1, length(x))},
                 function(x,y){rep(1, length(x))}),
             types=abc, ptypes=rep(1,3))
# same as above

rmpoint(25, function(x,y,m) { x }, types=abc, ptypes=rep(1,3))
# 25 points, equal probability for each type,
# locations nonuniform with density proportional to x

rmpoint(25, function(x,y,m) { ifelse(m == "a", 1, x) }, types=abc, ptypes=rep(1,3))
# 25 points, EQUAL probabilities for each type,
# type "a" points uniformly distributed,
# type "b" and "c" points nonuniformly distributed.

###### Model III

rmpoint(c(12, 8, 4), 1, types=abc)
# 12 points of type "a",
# 8 points of type "b",
# 4 points of type "c",
# each uniformly distributed

rmpoint(c(12, 8, 4), function(x,y,m) { ifelse(m=="a", 1, x)}, types=abc)
rmpoint(c(12, 8, 4), list(function(x,y) { rep(1, length(x)) },
                               function(x,y) { x },
                               function(x,y) { x }),
             types=abc)

# 12 points of type "a", uniformly distributed
# 8 points of type "b", nonuniform
# 4 points of type "c", nonuniform

#########

## Randomising an existing point pattern:
data(demopat)
X <- demopat

# same numbers of points of each type, uniform random locations (Model III)
rmpoint(table(X$marks), 1, types=levels(X$marks), win=X$window)

# same total number of points, distribution of types estimated from X,
# uniform random locations (Model II)
rmpoint(X$n, 1, types=levels(X$marks), win=X$window,
       ptypes=table(X$marks))


Generate Multitype Poisson Point Pattern

Description

Generate a random point pattern, a realisation of the (homogeneous or inhomogeneous) multitype Poisson process.

Usage

 rmpoispp(lambda, lmax=NULL, win, types, ...)

Arguments

lambda | Intensity of the multitype Poisson process. Either a single positive number, a vector, a function(x,y,m, ...), a pixel image, a list of functions function(x,y, ...), or a list of pixel images.
lmax | An upper bound for the value of lambda. May be omitted
win | Window in which to simulate the pattern. An object of class "owin" or something acceptable to as.owin. Ignored if lambda is a pixel image or list of images.
types | All the possible types for the multitype pattern.
... | Arguments passed to lambda if it is a function.

Details

This function generates a realisation of the marked Poisson point process with intensity lambda.

Note that the intensity function lambda(x,y,m) is the average number of points of type m per unit area near the location (x,y). Thus a marked point process with a constant intensity of 10 and three possible types will have an average of 30 points per unit area, with 10 points of each type on average.

The intensity function may be specified in any of the following ways.

single number:
If lambda is a single number, then this algorithm generates a realisation of the uniform marked Poisson process inside the window win with intensity lambda for each type. The total intensity of points of all types is lambda * length(types). The argument types must be given and determines the possible types in the multitype pattern.
vector:
If lambda is a numeric vector, then this algorithm generates a realisation of the stationary marked Poisson process inside the window win with intensity lambda[i] for points of type types[i]. The total intensity of points of all types is sum(lambda). The argument types defaults to seq(lambda).
function:
If lambda is a function, the process has intensity lambda(x,y,m,...) at spatial location (x,y) for points of type m. The function lambda must work correctly with vectors x, y and m, returning a vector of function values. (Note that m will be a factor with levels equal to types.) The value lmax, if present, must be an upper bound on the values of lambda(x,y,m,...) for all locations (x, y) inside the window win and all types m. The argument types must be given.
list of functions:
If lambda is a list of functions, the process has intensity lambda[[i]](x,y,...) at spatial location (x,y) for points of type types[i]. The function lambda[[i]] must work correctly with vectors x and y, returning a vector of function values. The value lmax, if given, must be an upper bound on the values of lambda(x,y,...) for all locations (x, y) inside the window win. The argument types defaults to seq(lambda).
pixel image:
If lambda is a pixel image object of class "im" (see im.object), the intensity at a location (x,y) for points of any type is equal to the pixel value of lambda for the pixel nearest to (x,y). The argument win is ignored; the window of the pixel image is used instead. The argument types must be given.
list of pixel images:
If lambda is a list of pixel images, then the image lambda[[i]] determines the intensity of points of type types[i]. The argument win is ignored; the window of the pixel image is used instead. The argument types defaults to seq(lambda).

If lmax is missing, an approximate upper bound will be calculated.

To generate an inhomogeneous Poisson process the algorithm uses ``thinning'': it first generates a uniform Poisson process of intensity lmax for points of each type m, then randomly deletes or retains each point independently, with retention probability p(x,y,m) = lambda(x,y)/lmax.

Value

The simulated multitype point pattern (an object of class "ppp" with a component marks which is a factor).

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp.object, owin.object

Examples

 # uniform bivariate Poisson process with total intensity 100 in unit square
 pp <- rmpoispp(50, types=c("a","b"))

 # stationary bivariate Poisson process with intensity A = 30, B = 70
 pp <- rmpoispp(c(30,70), types=c("A","B"))
 pp <- rmpoispp(c(30,70))

 # works in any window
 data(letterR)
 pp <- rmpoispp(c(30,70), win=letterR, types=c("A","B"))

 # inhomogeneous lambda(x,y,m)
 # note argument 'm' is a factor
 lam <- function(x,y,m) { 50 * (x^2 + y^3) * ifelse(m=="A", 2, 1)}
 pp <- rmpoispp(lam, win=letterR, types=c("A","B"))
 # extra arguments
 lam <- function(x,y,m,scal) { scal * (x^2 + y^3) * ifelse(m=="A", 2, 1)}
 pp <- rmpoispp(lam, win=letterR, types=c("A","B"), scal=50)

 # list of functions lambda[[i]](x,y)
 lams <- list(function(x,y){50 * x^2}, function(x,y){20 * abs(y)})
 pp <- rmpoispp(lams, win=letterR, types=c("A","B"))
 pp <- rmpoispp(lams, win=letterR)
 # functions with extra arguments
 lams <- list(function(x,y,scal){5 * scal * x^2},
              function(x,y, scal){2 * scal * abs(y)})
 pp <- rmpoispp(lams, win=letterR, types=c("A","B"), scal=10)
 pp <- rmpoispp(lams, win=letterR, scal=10)

 # florid example
 lams <- list(function(x,y){
                           100*exp((6*x + 5*y - 18*x^2 + 12*x*y - 9*y^2)/6)
                         }
                         # log quadratic trend
              ,
              function(x,y){
                                   100*exp(-0.6*x+0.5*y)
                         }
                        # log linear trend
              )
  X <- rmpoispp(lams, win=unit.square(), types=c("on", "off"))

 # pixel image
 Z <- as.im(function(x,y){30 * (x^2 + y^3)}, letterR)
 pp <- rmpoispp(Z, types=c("A","B"))

 # list of pixel images
 ZZ <- list(
          as.im(function(x,y){20 * (x^2 + y^3)}, letterR),
          as.im(function(x,y){40 * (x^3 + y^2)}, letterR))
 pp <- rmpoispp(ZZ, types=c("A","B"))
 pp <- rmpoispp(ZZ)


Simulate Neyman-Scott Process

Description

Generate a random point pattern, a realisation of the Neyman-Scott cluster process.

Usage

 rNeymanScott(kappa, rmax, rcluster, win = owin(c(0,1),c(0,1)), ..., lmax=NULL)

Arguments

kappa | Intensity of the Poisson process of cluster centres. A single positive number, a function, or a pixel image.
rmax | Maximum radius of a random cluster.
rcluster | A function which generates random clusters.
win | Window in which to simulate the pattern. An object of class "owin" or something acceptable to as.owin.
... | Arguments passed to rcluster
lmax | Optional. Upper bound on the values of kappa when kappa is a function or pixel image.

Details

This algorithm generates a realisation of the general Neyman-Scott process, with the cluster mechanism given by the function rcluster. The clusters must have a finite maximum possible radius rmax.

First, the algorithm generates a Poisson point process of ``parent'' points with intensity kappa. Here kappa may be a single positive number, a function kappa(x, y), or a pixel image object of class "im" (see im.object). See rpoispp for details.

Second, each parent point is replaced by a random cluster of points, created by calling the function rcluster. These clusters are combined together to yield a single point pattern which is then returned as the result of rNeymanScott.

The function rcluster should expect to be called as rcluster(xp[i],yp[i],...) for each parent point at a location (xp[i],yp[i]). The return value of rcluster should be a list with elements x,y which are vectors of equal length giving the absolute x and y coordinates of the points in the cluster.

If required, the intermediate stages of the simulation (the parents and the individual clusters) can also be extracted from the return value of rNeymanScott through the attributes "parents" and "parentid". The attribute "parents" is the point pattern of parent points. The attribute "parentid" is an integer vector specifying the parent for each of the points in the simulated pattern.

Value

The simulated point pattern (an object of class "ppp").
Additionally, some intermediate results of the simulation are returned as attributes of this point pattern: see Details.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

rpoispp, rThomas, rMatClust

Examples

  nclust <-  function(x0, y0, radius, n) {
                           return(runifdisc(n, radius, centre=c(x0, y0)))
                         }
  X <- rNeymanScott(10, 0.2, nclust, radius=0.2, n=5)


Rotate

Description

Applies a rotation to any two-dimensional object, such as a point pattern or a window.

Usage

  rotate(X, ...)

Arguments

X | Any suitable dataset representing a two-dimensional object, such as a point pattern (object of class "ppp"), or a window (object of class "owin").
... | Data specifying the rotation.

Details

This is generic. Methods are provided for point patterns (rotate.ppp) and windows (rotate.owin).

Value

Another object of the same type, representing the result of rotating X through the specified angle.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

rotate.ppp, rotate.owin


Rotate a Window

Description

Rotates a window

Usage

 ## S3 method for class 'owin':
 rotate(X, angle=pi/2, ...)

Arguments

X | A window (object of class "owin").
angle | Angle of rotation.
... | Ignored.

Details

Rotates the window by the specified angle. Angles are measured in radians, anticlockwise. The default is to rotate the window 90 degrees anticlockwise. The centre of rotation is the origin.

Rotation of binary image masks is not yet implemented.

Value

Another object of class "owin" representing the rotated window.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin.object

Examples

  w <- owin(c(0,1),c(0,1))
  v <- rotate(w, pi/3)
  ## Not run:
  plot(v)

## End(Not run)


Rotate a Point Pattern

Description

Rotates a point pattern

Usage

 ## S3 method for class 'ppp':
 rotate(X, angle=pi/2, ...)

Arguments

X | A point pattern (object of class "ppp").
angle | Angle of rotation.
... | Ignored.

Details

The points of the pattern, and the window of observation, are rotated about the origin by the angle specified. Angles are measured in radians, anticlockwise. The default is to rotate the pattern 90 degrees anticlockwise. If the points carry marks, these are preserved.

Rotation of binary image masks is not yet implemented.

Value

Another object of class "ppp" representing the rotated point pattern.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp.object, rotate.owin

Examples

  data(cells)
  X <- rotate(cells, pi/3)
  ## Not run:
  plot(X)

## End(Not run)


Rotate a Line Segment Pattern

Description

Rotates a line segment pattern

Usage

 ## S3 method for class 'psp':
 rotate(X, angle=pi/2, ...)

Arguments

X | A line segment pattern (object of class "psp").
angle | Angle of rotation.
... | Ignored.

Details

The line segments of the pattern, and the window of observation, are rotated about the origin by the angle specified. Angles are measured in radians, anticlockwise. The default is to rotate the pattern 90 degrees anticlockwise. If the line segments carry marks, these are preserved.

Rotation of binary image masks is not yet implemented.

Value

Another object of class "psp" representing the rotated line segment pattern.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

psp.object, rotate.owin, rotate.ppp

Examples

  oldpar <- par(mfrow=c(2,1))
  X <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
  plot(X, main="original")
  Y <- rotate(X, pi/4)
  plot(Y, "rotated")
  par(oldpar)


Generate N Random Points

Description

Generate a random point pattern containing n independent, identically distributed random points with any specified distribution.

Usage

 rpoint(n, f, fmax=NULL, win=unit.square(), ..., giveup=1000, verbose=FALSE)

Arguments

n | Number of points to generate.
f | The probability density of the points, possibly un-normalised. Either a constant, a function f(x,y,...), or a pixel image object.
fmax | An upper bound on the values of f. If missing, this number will be estimated.
win | Window in which to simulate the pattern. Ignored if f is a pixel image.
... | Arguments passed to the function f.
giveup | Number of attempts in the rejection method after which the algorithm should stop trying to generate new points.
verbose | Flag indicating whether to report details of performance of the simulation algorithm.

Details

This function generates n independent, identically distributed random points with common probability density proportional to f.

The argument f may be

a numerical constant:
uniformly distributed random points will be generated.
a function:
random points will be generated in the window win with probability density proportional to f(x,y,...) where x and y are the cartesian coordinates. The function f must accept two vectors of coordinates x,y and return the corresponding vector of function values. Additional arguments ... of any kind may be passed to the function.
a pixel image:
if f is a pixel image object of class "im" (see im.object) then random points will be generated in the window of this pixel image, with probability density proportional to the pixel values of f.

The algorithm is as follows:

  • If f is a constant, we invoke runifpoint.
  • If f is a function, then we use the rejection method. Proposal points are generated from the uniform distribution. A proposal point (x,y) is accepted with probability f(x,y,...)/fmax and otherwise rejected. The algorithm continues until n points have been accepted. It gives up after giveup * n proposals if there are still fewer than n points.
  • If f is a pixel image, then a random sequence of pixels is selected (using sample) with probabilities proportional to the pixel values of f. Then for each pixel in the sequence we generate a uniformly distributed random point in that pixel.

The algorithm for pixel images is more efficient than that for functions.

Value

The simulated point pattern (an object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp.object, owin.object, runifpoint

Examples

 # 100 uniform random points in the unit square
 X <- rpoint(100)

 # 100 random points with probability density proportional to x^2 + y^2
 X <- rpoint(100, function(x,y) { x^2 + y^2}, 1)

 # `fmax' may be omitted
 X <- rpoint(100, function(x,y) { x^2 + y^2})

 # irregular window
 data(letterR)
 X <- rpoint(100, function(x,y) { x^2 + y^2}, win=letterR)

 # make a pixel image
 Z <- setcov(letterR)
 # 100 points with density proportional to pixel values
 X <- rpoint(100, Z)


Generate Poisson Random Line Process

Description

Generate a random pattern of line segments obtained from the Poisson line process.

Usage

 rpoisline(lambda, win=owin())

Arguments

lambda | Intensity of the Poisson line process. A positive number.
win | Window in which to simulate the pattern. An object of class "owin" or something acceptable to as.owin. Currently, the window must be a rectangle.

Details

This algorithm generates a realisation of the uniform Poisson line process, and clips it to the window win.

Currently win must be a rectangle.

The argument lambda must be a positive number. It controls the intensity of the process. The expected number of lines intersecting a convex region of the plane is equal to lambda times the perimeter length of the region. The expected total length of the lines crossing a region of the plane is equal to lambda * pi times the area of the region.

Value

A line segment pattern (an object of class "psp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

psp

Examples

 # uniform Poisson line process with intensity 10,
 # clipped to the unit square
 rpoisline(10)


Generate Poisson Point Pattern

Description

Generate a random point pattern using the (homogeneous or inhomogeneous) Poisson process. Includes CSR (complete spatial randomness).

Usage

 rpoispp(lambda, lmax, win, ...)

Arguments

lambda | Intensity of the Poisson process. Either a single positive number, a function(x,y, ...), or a pixel image.
lmax | An upper bound for the value of lambda(x,y), if lambda is a function.
win | Window in which to simulate the pattern. An object of class "owin" or something acceptable to as.owin. Ignored if lambda is a pixel image.
... | Arguments passed to lambda if it is a function.

Details

If lambda is a single number, then this algorithm generates a realisation of the uniform Poisson process (also known as Complete Spatial Randomness, CSR) inside the window win with intensity lambda (points per unit area).

If lambda is a function, then this algorithm generates a realisation of the inhomogeneous Poisson process with intensity function lambda(x,y,...) at spatial location (x,y) inside the window win. The function lambda must work correctly with vectors x and y. The value lmax must be given and must be an upper bound on the values of lambda(x,y,...) for all locations (x, y) inside the window win.

If lambda is a pixel image object of class "im" (see im.object), this algorithm generates a realisation of the inhomogeneous Poisson process with intensity equal to the pixel values of the image. (The value of the intensity function at an arbitrary location is the pixel value of the nearest pixel.) The argument win is ignored; the window of the pixel image is used instead.

To generate an inhomogeneous Poisson process the algorithm uses ``thinning'': it first generates a uniform Poisson process of intensity lmax, then randomly deletes or retains each point, independently of other points, with retention probability p(x,y) = lambda(x,y)/lmax.

Value

The simulated point pattern (an object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp.object, owin.object

Examples

 # uniform Poisson process with intensity 100 in the unit square
 pp <- rpoispp(100)

 # uniform Poisson process with intensity 1 in a 10 x 10 square
 pp <- rpoispp(1, win=owin(c(0,10),c(0,10)))
 # plots should look similar !

 # inhomogeneous Poisson process in unit square
 # with intensity lambda(x,y) = 100 * exp(-3*x)
 # Intensity is bounded by 100
 pp <- rpoispp(function(x,y) {100 * exp(-3*x)}, 100)

 # How to tune the coefficient of x
 lamb <- function(x,y,a) { 100 * exp( - a * x)}
 pp <- rpoispp(lamb, 100, a=3)

 # pixel image
 Z <- as.im(function(x,y){100 * sqrt(x+y)}, unit.square())
 pp <- rpoispp(Z)


Random Shift

Description

Randomly shifts the points of a point pattern or line segment pattern. Generic.

Usage

   rshift(X, ...)

Arguments

X | Pattern to be subjected to a random shift. A point pattern (class "ppp"), a line segment pattern (class "psp") or an object of class "splitppp".
... | Arguments controlling the generation of the random shift vector, or specifying which parts of the pattern will be shifted.

Details

This operation applies a random shift (vector displacement) to the points in a point pattern, or to the segments in a line segment pattern.

The argument X may be

  • a point pattern (an object of class "ppp")
  • a line segment pattern (an object of class "psp")
  • an object of class "splitppp" (basically a list of point patterns, obtained from split.ppp).

The function rshift is generic, with methods for the three classes "ppp", "psp" and "splitppp".

See the help pages for these methods, rshift.ppp, rshift.psp and rshift.splitppp, for further information.

Value

An object of the same type as X.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

rshift.ppp, rshift.psp, rshift.splitppp


Randomly Shift a Point Pattern

Description

Randomly shifts the points of a point pattern.

Usage

   ## S3 method for class 'ppp':
   rshift(X, ..., which=NULL, group)

Arguments

X | Point pattern to be subjected to a random shift. An object of class "ppp"
... | Arguments that determine the random shift. See Details.
group | Optional. Factor specifying a grouping of the points of X, or NULL indicating that all points belong to the same group. Each group will be shifted together, and separately from other groups. By default, points in a marked point pattern are grouped according to their mark values, while points in an unmarked point pattern are treated as a single group.
which | Optional. Identifies which groups of the pattern will be shifted, while other groups are not shifted. A vector of levels of group.

Details

This operation randomly shifts the locations of the points in a point pattern.

The function rshift is generic. This function rshift.ppp is the method for point patterns.

The most common use of this function is to shift the points in a multitype point pattern. By default, points of the same type are shifted in parallel (i.e. points of a common type are shifted by a common displacement vector), and independently of other types. This is useful for testing the hypothesis of independence of types (the null hypothesis that the sub-patterns of points of each type are independent point processes).

In general the points of X are divided into groups, then the points within a group are shifted by a common random displacement vector. Different groups of points are shifted independently. The grouping is determined as follows:

  • If the argument group is present, then this determines the grouping.
  • Otherwise, if X is a multitype point pattern, the marks determine the grouping.
  • Otherwise, all points belong to a single group.

The argument group should be a factor, of length equal to the number of points in X. Alternatively group may be NULL, which specifies that all points of X belong to a single group.

By default, every group of points will be shifted. The argument which indicates that only some of the groups should be shifted, while other groups should be left unchanged. which must be a vector of levels of group (for example, a vector of types in a multitype pattern) indicating which groups are to be shifted.

The displacement vector, i.e. the vector by which the data points are shifted, is generated at random. Parameters that control the randomisation and the handling of edge effects are passed through the ... argument. They are

radius,width,height
Parameters of the random shift vector.
edge
String indicating how to deal with edges of the pattern. Options are "torus", "erode" and "none".
clip
Optional. Window to which the final point pattern should be clipped.

If the window is a rectangle, the default behaviour is to generate a displacement vector at random with equal probability for all possible displacements. This means that the x and y coordinates of the displacement vector are independent random variables, uniformly distributed over the range of possible coordinates.

Alternatively, the displacement vector can be generated by another random mechanism, controlled by the arguments radius, width and height.

rectangular:
if width and height are given, then the displacement vector is uniformly distributed in a rectangle of these dimensions, centred at the origin. The maximum possible displacement in the x direction is width/2. The maximum possible displacement in the y direction is height/2. The x and y displacements are independent. (If width and height are actually equal to the dimensions of the observation window, then this is equivalent to the default.)
radial:
if radius is given, then the displacement vector is generated by choosing a random point inside a disc of the given radius, centred at the origin, with uniform probability density over the disc. Thus the argument radius determines the maximum possible displacement distance. The argument radius is incompatible with the arguments width and height.

The argument edge controls what happens when a shifted point lies outside the window of X. Options are:

"none":
Points shifted outside the window of X simply disappear.
"torus":
Toroidal or periodic boundary. Treat opposite edges of the window as identical, so that a point which disappears off the right-hand edge will re-appear at the left-hand edge. This is called a ``toroidal shift'' because it makes the rectangle topologically equivalent to the surface of a torus (doughnut).

The window must be a rectangle. Toroidal shifts are undefined if the window is non-rectangular.

"erode":
Clip the point pattern to a smaller window.

If the random displacements are generated by a radial mechanism (see above), then the window of X is eroded by a distance equal to the value of the argument radius, using erode.owin.

If the random displacements are generated by a rectangular mechanism, then the window of X is (if it is not rectangular) eroded by a distance max(height,width) using erode.owin; or (if it is rectangular) trimmed by a margin of width width at the left and right sides and trimmed by a margin of height height at the top and bottom.

The rationale for this is that the clipping window is the largest window for which edge effects can be ignored.

The optional argument clip specifies a smaller window to which the pattern should be restricted.

Value

A point pattern (object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

rshift, rshift.psp

Examples

   data(amacrine)

   # random toroidal shift
   # shift "on" and "off" points separately
   X <- rshift(amacrine)

   # shift "on" points and leave "off" points fixed
   X <- rshift(amacrine, which="on")

   # shift all points simultaneously
   X <- rshift(amacrine, group=NULL)

   # maximum displacement distance 0.1 units
   X <- rshift(amacrine, radius=0.1)

   # shift with erosion
   X <- rshift(amacrine, radius=0.1, edge="erode")


Randomly Shift a Line Segment Pattern

Description

Randomly shifts the segments in a line segment pattern.

Usage

   ## S3 method for class 'psp':
   rshift(X, ..., group=NULL, which=NULL)

Arguments

X | Line segment pattern to be subjected to a random shift. An object of class "psp".
... | Arguments controlling the randomisation and the handling of edge effects. See rshift.ppp.
group | Optional. Factor specifying a grouping of the line segments of X, or NULL indicating that all line segments belong to the same group. Each group will be shifted together, and separately from other groups.
which | Optional. Identifies which groups of the pattern will be shifted, while other groups are not shifted. A vector of levels of group.

Details

This operation randomly shifts the locations of the line segments in a line segment pattern.

The function rshift is generic. This function rshift.psp is the method for line segment patterns.

The line segments of X are first divided into groups, then the line segments within a group are shifted by a common random displacement vector. Different groups of line segments are shifted independently. If the argument group is present, then this determines the grouping. Otherwise, all line segments belong to a single group.

The argument group should be a factor, of length equal to the number of line segments in X. Alternatively group may be NULL, which specifies that all line segments of X belong to a single group.

By default, every group of line segments will be shifted. The argument which indicates that only some of the groups should be shifted, while other groups should be left unchanged. which must be a vector of levels of group indicating which groups are to be shifted.

The displacement vector, i.e. the vector by which the data line segments are shifted, is generated at random. The default behaviour is to generate a displacement vector at random with equal probability for all possible displacements. This means that the x and y coordinates of the displacement vector are independent random variables, uniformly distributed over the range of possible coordinates.

Alternatively, the displacement vector can be generated by another random mechanism, controlled by the arguments radius, width and height.

rectangular:
if width and height are given, then the displacement vector is uniformly distributed in a rectangle of these dimensions, centred at the origin. The maximum possible displacement in the x direction is width/2. The maximum possible displacement in the y direction is height/2. The x and y displacements are independent. (If width and height are actually equal to the dimensions of the observation window, then this is equivalent to the default.)
radial:
if radius is given, then the displacement vector is generated by choosing a random line segment inside a disc of the given radius, centred at the origin, with uniform probability density over the disc. Thus the argument radius determines the maximum possible displacement distance. The argument radius is incompatible with the arguments width and height.

The argument edge controls what happens when a shifted line segment lies partially or completely outside the window of X. Currently the only option is "erode" which specifies that the segments will be clipped to a smaller window.

The optional argument clip specifies a smaller window to which the pattern should be restricted.

Value

A line segment pattern (object of class "psp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

rshift, rshift.ppp

Examples

  X <- psp(runif(20), runif(20), runif(20), runif(20),  window=owin())
  Y <- rshift(X, radius=0.1)


Randomly Shift a List of Point Patterns

Description

Randomly shifts each point pattern in a list of point patterns.

Usage

   ## S3 method for class 'splitppp':
   rshift(X, ..., which=seq(X))

Arguments

X | An object of class "splitppp". Basically a list of point patterns.
... | Parameters controlling the generation of the random shift vector and the handling of edge effects. See rshift.ppp.
which | Optional. Identifies which patterns will be shifted, while other patterns are not shifted. Any valid subset index for X.

Details

This operation applies a random shift to each of the point patterns in the list X.

The function rshift is generic. This function rshift.splitppp is the method for objects of class "splitppp", which are essentially lists of point patterns, created by the function split.ppp.

By default, every pattern in the list X will be shifted. The argument which indicates that only some of the patterns should be shifted, while other groups should be left unchanged. which can be any valid subset index for X.

Each point pattern in the list X (or each pattern in X[which]) is shifted by a random displacement vector. The shifting is performed by rshift.ppp.

See the help page for rshift.ppp for details of the other arguments.

Value

Another object of class "splitppp".

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

rshift, rshift.ppp

Examples

   data(amacrine)
   Y <- split(amacrine)

   # random toroidal shift
   # shift "on" and "off" points separately
   X <- rshift(Y)

   # shift "on" points and leave "off" points fixed
   X <- rshift(Y, which="on")

   # maximum displacement distance 0.1 units
   X <- rshift(Y, radius=0.1)

   # shift with erosion
   X <- rshift(Y, radius=0.1, edge="erode")


Simulate Simple Sequential Inhibition

Description

Generate a random point pattern, a realisation of the Simple Sequential Inhibition (SSI) process.

Usage

 rSSI(r, n, win = owin(c(0,1),c(0,1)), giveup = 1000)

Arguments

r | Inhibition distance.
n | Number of points to generate.
win | Window in which to simulate the pattern. An object of class "owin" or something acceptable to as.owin.
giveup | Number of rejected proposals after which the algorithm should terminate.

Details

This algorithm generates a realisation of the Simple Sequential Inhibition point process inside the window win.

Starting with an empty window, the algorithm adds points one-by-one. Each new point is generated uniformly in the window and independently of preceding points. If the new point lies closer than r units from an existing point, then it is rejected and another random point is generated.

The algorithm terminates either when the desired number n of points is reached, or when the current point configuration has not changed for giveup iterations.

Value

The simulated point pattern (an object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

rpoispp, rMaternI, rMaternII

Examples

 pp <- rSSI(0.05, 200)
 ## Not run: plot(pp)


Simulate Stratified Random Point Pattern

Description

Generates a ``stratified random'' pattern of points in a window, by dividing the window into rectangular tiles and placing k random points independently in each tile.

Usage

 rstrat(win=square(1), nx, ny=nx, k = 1)

Arguments

win | A window. An object of class owin, or data in any format acceptable to as.owin().
nx | Number of tiles in each column.
ny | Number of tiles in each row.
k | Number of random points to generate in each tile.

Details

This function generates a random pattern of points in a ``stratified random'' sampling design. It can be useful for generating random spatial sampling points.

The bounding rectangle of win is divided into a regular nx * ny grid of rectangular tiles. In each tile, k random points are generated independently with a uniform distribution in that tile.

Some of these grid points may lie outside the window win: if they do, they are deleted.

The result is a point pattern inside the window win.

This function is useful in creating dummy points for quadrature schemes (see quadscheme) as well as in simulating random point patterns.

Value

A point pattern (object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

rsyst, runifpoint, quadscheme

Examples

  X <- rstrat(nx=10)
  plot(X)

  # polygonal boundary
  data(letterR)
  X <- rstrat(letterR, 5, 10, k=3)
  plot(X)


Perfect Simulation of the Strauss Process

Description

Generate a random pattern of points, a simulated realisation of the Strauss process, using a perfect simulation algorithm.

Usage

  rStrauss(beta, gamma = 1, R = 0, W = owin())

Arguments

beta | intensity parameter (a positive number).
gamma | interaction parameter (a number between 0 and 1, inclusive).
R | interaction radius (a non-negative number).
W | window (object of class "owin") in which to generate the random pattern. Currently this must be a rectangular window.

Details

This function generates a realisation of the Strauss point process in the window W using a ‘perfect simulation’ algorithm.

The Strauss process (Strauss, 1975; Kelly and Ripley, 1976) is a model for spatial inhibition, ranging from a strong `hard core' inhibition to a completely random pattern according to the value of gamma.

The Strauss process with interaction radius R and parameters beta and gamma is the pairwise interaction point process with probability density

f(x_1,...,x_n) = alpha . beta^n(x) gamma^s(x)

where x[1],...,x[n] represent the points of the pattern, n(x) is the number of points in the pattern, s(x) is the number of distinct unordered pairs of points that are closer than R units apart, and alpha is the normalising constant. Intuitively, each point of the pattern contributes a factor beta to the probability density, and each pair of points closer than r units apart contributes a factor gamma to the density.

The interaction parameter gamma must be less than or equal to 1 in order that the process be well-defined (Kelly and Ripley, 1976). This model describes an ``ordered'' or ``inhibitive'' pattern. If gamma=1 it reduces to a Poisson process (complete spatial randomness) with intensity beta. If gamma=0 it is called a ``hard core process'' with hard core radius R/2, since no pair of points is permitted to lie closer than R units apart.

The simulation algorithm used to generate the point pattern is ‘dominated coupling from the past’ as implemented by Berthelsen and Moller (2002, 2003). This is a ‘perfect simulation’ or ‘exact simulation’ algorithm, so called because the output of the algorithm is guaranteed to have the correct probability distribution exactly (unlike the Metropolis-Hastings algorithm used in rmh, whose output is only approximately correct).

The implementation is currently experimental.

There is a tiny chance that the algorithm will run out of space before it has terminated. If this occurs, an error message will be generated.

Value

A point pattern (object of class "ppp").

Author(s)

Kasper Klitgaard Berthelsen k.berthelsen@lancaster.ac.uk, adapted for spatstat by Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/

References

Berthelsen, K.K. and Moller, J. (2002) A primer on perfect simulation for spatial point processes. Bulletin of the Brazilian Mathematical Society 33, 351-367.

Berthelsen, K.K. and Moller, J. (2003) Likelihood and non-parametric Bayesian MCMC inference for spatial point processes based on perfect simulation and path sampling. Scandinavian Journal of Statistics 30, 549-564.

Kelly, F.P. and Ripley, B.D. (1976) On Strauss's model for clustering. Biometrika 63, 357–360.

Moller, J. and Waagepetersen, R. (2003). Statistical Inference and Simulation for Spatial Point Processes. Chapman and Hall/CRC.

Strauss, D.J. (1975) A model for clustering. Biometrika 63, 467–475.

See Also

rmh

Examples

   X <- rStrauss(0.05,0.2,1.5,square(141.4))
   Z <- rStrauss(100,0.7,0.05)


Simulate systematic random point pattern

Description

Generates a ``systematic random'' pattern of points in a window, consisting of a grid of equally-spaced points with a random common displacement.

Usage

 rsyst(win=square(1), nx, ny=nx, dx=NULL, dy=NULL)

Arguments

win | A window. An object of class owin, or data in any format acceptable to as.owin().
dx | Spacing of grid points in x direction. Incompatible with nx.
dy | Spacing of grid points in y direction. Incompatible with ny.
nx | Number of columns of grid points in the window. Incompatible with dx.
ny | Number of rows of grid points in the window. Incompatible with dy.

Details

This function generates a “systematic random” pattern of points in the window win. The pattern consists of a rectangular grid of points with a random common displacement.

The grid spacing is determined by the distances dx, dy if they are present. If they are absent, then the grid spacing is determined so that there will be nx columns and ny rows of grid points in the bounding rectangle of win.

The grid is then given a random displacement (the common displacement of the grid points is a uniformly distributed random vector in the tile of dimensions dx, dy).

Some of the resulting grid points may lie outside the window win: if they do, they are deleted. The result is a point pattern inside the window win.

This function is useful in creating dummy points for quadrature schemes (see quadscheme) as well as in simulating random point patterns.

Value

A point pattern (object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

rstrat, runifpoint, quadscheme

Examples

  X <- rsyst(nx=10)
  plot(X)

  # polygonal boundary
  data(letterR)
  X <- rsyst(letterR, 5, 10)
  plot(X)


Random Thinning

Description

Applies independent random thinning to a point pattern.

Usage

rthin(X, P, ...)

Arguments

X | A point pattern (object of class "ppp") that will be thinned.
P | Data giving the retention probabilities, i.e. the probability that each point in X will be retained. Either a single number, or a vector of numbers, or a function(x,y), or a pixel image (object of class "im").
... | Additional arguments passed to P, if it is a function.

Details

In a random thinning operation, each point of the pattern X is randomly either deleted or retained (i.e. not deleted). The result is a point pattern, consisting of those points of X that were retained.

Independent random thinning means that the retention/deletion of each point is independent of other points.

The argument P determines the probability of retaining each point. It may be

a single number,
so that each point will be retained with the same probability P;
a vector of numbers,
so that the ith point of X will be retained with probability P[i];
a function P(x,y),
so that a point at a location (x,y) will be retained with probability P(x,y);
a pixel image,
containing values of the retention probability for all locations in a region encompassing the point pattern.

If P is a function, it should be ‘vectorised’, that is, it should accept vector arguments x,y and should yield a numeric vector of the same length. The function may have extra arguments which are passed through the ... argument.

Value

A point pattern (object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Examples

  data(redwood)
  plot(redwood, main="thinning")

  # delete 20% of points
  Y <- rthin(redwood, 0.8)
  points(Y, col="green", cex=1.4)

  # function
  f <- function(x,y) { ifelse(x < 0.4, 1, 0.5) }
  Y <- rthin(redwood, f)

  # pixel image
  Z <- as.im(f, redwood$window)
  Y <- rthin(redwood, Z)


Simulate Thomas Process

Description

Generate a random point pattern, a realisation of the Thomas cluster process.

Usage

 rThomas(kappa, sigma, mu, win = owin(c(0,1),c(0,1)))

Arguments

kappa | Intensity of the Poisson process of cluster centres. A single positive number.
sigma | Standard deviation of displacement of a point from its cluster centre.
mu | Expected number of points per cluster.
win | Window in which to simulate the pattern. An object of class "owin" or something acceptable to as.owin.

Details

This algorithm generates a realisation of the Thomas process, a special case of the Neyman-Scott process.

The algorithm generates a uniform Poisson point process of ``parent'' points with intensity kappa. Then each parent point is replaced by a random cluster of points, the number of points per cluster being Poisson (mu) distributed, and their positions being isotropic Gaussian displacements from the cluster parent location.

Value

The simulated point pattern (an object of class "ppp").
Additionally, some intermediate results of the simulation are returned as attributes of this point pattern. See rNeymanScott.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

rpoispp, rMatClust, rNeymanScott

Examples

  X <- rThomas(10, 0.2, 5)


Generate N Uniform Random Points in a Disc

Description

Generate a random point pattern containing n independent uniform random points in a circular disc.

Usage

 runifdisc(n, radius=1, centre=c(0,0), ...)

Arguments

n | Number of points.
radius | Radius of the circle.
centre | Coordinates of the centre of the circle.
... | Arguments passed to disc controlling the accuracy of approximation to the circle.

Details

This function generates n independent random points, uniformly distributed in a circular disc.

It is faster (for a circular window) than the general code used in runifpoint.

To generate random points in an ellipse, first generate points in a circle using runifdisc, then transform to an ellipse using affine, as shown in the examples.

To generate random points in other windows, use runifpoint. To generate non-uniform random points, use rpoint.

Value

The simulated point pattern (an object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

disc, runifpoint, rpoint

Examples

 # 100 random points in the unit disc
 plot(runifdisc(100))
 # 42 random points in the ellipse with major axis 3 and minor axis 1
 X <- runifdisc(42)
 Y <- affine(X, mat=diag(c(3,1)))
 plot(Y)


Generate N Uniform Random Points

Description

Generate a random point pattern containing n independent uniform random points.

Usage

 runifpoint(n, win=owin(c(0,1),c(0,1)), giveup=1000)

Arguments

n | Number of points.
win | Window in which to simulate the pattern. An object of class "owin" or something acceptable to as.owin.
giveup | Number of attempts in the rejection method after which the algorithm should stop trying to generate new points.

Details

This function generates n independent random points, uniformly distributed in the window win. (For nonuniform distributions, see rpoint.)

The algorithm depends on the type of window, as follows:

  • If win is a rectangle then n independent random points, uniformly distributed in the rectangle, are generated by assigning uniform random values to their cartesian coordinates.
  • If win is a binary image mask, then a random sequence of pixels is selected (using sample) with equal probabilities. Then for each pixel in the sequence we generate a uniformly distributed random point in that pixel.
  • If win is a polygonal window, the algorithm uses the rejection method. It finds a rectangle enclosing the window, generates points in this rectangle, and tests whether they fall in the desired window. It gives up when giveup * n tests have been performed without yielding n successes.

The algorithm for binary image masks is faster than the rejection method but involves discretisation.

Value

The simulated point pattern (an object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp.object, owin.object, rpoispp, rpoint

Examples

 # 100 random points in the unit square
 pp <- runifpoint(100)
 # irregular window
 data(letterR)
 # polygonal
 pp <- runifpoint(100, letterR)
 # binary image mask
 pp <- runifpoint(100, as.mask(letterR))


Saturated Pairwise Interaction model

Description

Experimental.

Usage

  Saturated(pot, name)

Arguments

pot | An S language function giving the user-supplied pairwise interaction potential.
name | Character string.

Details

This is experimental. It constructs a member of the ``saturated pairwise'' family pairsat.family.

Value

An object of class "interact" describing the interpoint interaction structure of a point process.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppm, pairsat.family, ppm.object


Read Point Pattern From Data File

Description

Reads a point pattern dataset from a text file.

Usage

   scanpp(filename, window, header=TRUE, dir="", multitype=FALSE)

Arguments

filename | String name of the file containing the coordinates of the points in the point pattern, and their marks if any.
window | Window for the point pattern. An object of class "owin".
header | Logical flag indicating whether the first line of the file contains headings for the columns. Passed to read.table.
dir | String containing the path name of the directory in which filename is to be found. Default is the current directory.
multitype | Logical flag indicating whether marks are to be interpreted as a factor (multitype = TRUE) or as numerical values (multitype = FALSE).

Details

This simple function reads a point pattern dataset from a file containing the cartesian coordinates of its points, and optionally the mark values for these points.

The file identified by filename in directory dir should be a text file that can be read using read.table. Thus, each line of the file (except possibly the first line) contains data for one point in the point pattern. Data are arranged in columns. There should be either two columns (for an unmarked point pattern) or three columns (for a marked point pattern).

If header=FALSE then the first two columns of data will be interpreted as the x and y coordinates of points. A third column, if present, will be interpreted as containing the marks for these points. The marks will be converted to a factor if multitype = TRUE.

If header=TRUE then the first line of the file should contain string names for each of the columns of data. If there are columns named x and y then these will be taken as the cartesian coordinates, and any remaining column will be taken as the marks. If there are no columns named x and y then the first and second columns will be taken as the cartesian coordinates.

Note that there is intentionally no default for window. The window of observation should be specified. If you really need to estimate the window, use the Ripley-Rasson estimator ripras.

Value

A point pattern (an object of class "ppp", see ppp.object).

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp.object, ppp, as.ppp, ripras


Crossing Points in a Line Segment Pattern

Description

Finds any crossing points between the line segments in a line segment pattern.

Usage

  selfcrossing.psp(A)

Arguments

A Line segment pattern (object of class "psp").

Details

This function finds any crossing points between different line segments in the line segment pattern A.

A crossing point occurs whenever one of the line segments in A intersects another line segment in A, at a nonzero angle of intersection.

Value

Point pattern (object of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

crossing.psp, psp.object, ppp.object.

Examples

  a <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
  plot(a, col="green", main="selfcrossing.psp")
  P <- selfcrossing.psp(a)
  plot(P, add=TRUE, col="red")


Set Covariance of a Window

Description

Computes the set covariance function of a window.

Usage

 setcov(W, ...)

Arguments

W | A window (object of class "owin".
... | Optional arguments passed to as.mask to control the pixel resolution.

Details

The set covariance function of a region W in the plane is the function C(v) defined for each vector v as the area of the intersection between W and W+v, where W+v is the set obtained by shifting (translating) W by v.

We may interpret C(v) as the area of the set of all points x in W such that x+v also lies in W.

This command computes a discretised approximation to the set covariance function of any plane region W represented as a window object (of class "owin", see owin.object). The return value is a pixel image (object of class "im") whose greyscale values are values of the set covariance function.

The set covariance is computed using the Fast Fourier Transform, unless W is a rectangle, when an exact formula is used.

Value

A pixel image (an object of class "im") representing the set covariance function of W.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin, as.owin, erode.owin

Examples

  w <- owin(c(0,1),c(0,1))
  v <- setcov(w)
  plot(v)


Set or Reset the Marks in a Point Pattern

Description

Create a marked point pattern from given point locations and given marks.

Usage

  setmarks(X, m)
  X %mark% m

Arguments

X | Point pattern (object of class "ppp")
m | Vector of mark values (of any atomic mode)

Details

This function is a shortcut which creates a marked point pattern from a given point pattern X and a given vector m by attaching the marks in m to the locations of the points in X.

If X is already a marked point pattern, then its marks are ignored and replaced by the values in m.

If m is a single value, then all points will be given this mark value. Otherwise, m must be a vector of length equal to the number of points in X, and the point X[i] will receive the mark m[i].

Use unmark to remove marks. Use ppp to create point patterns in more general situations.

Value

Marked point pattern (object of class "ppp") identical to X except that it has marks equal to m.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

unmark, ppp.object, is.marked, is.marked.ppp

Examples

   data(cells)

   m <- runif(cells$n)

   Y <- setmarks(cells, m)
   Y <- cells %mark% m
   # equivalent

   ## Not run: plot(Y)
   is.marked(Y)  #TRUE


Apply Vector Translation

Description

Applies a vector shift of the plane to a geometrical object, such as a point pattern or a window.

Usage

  shift(X, ...)

Arguments

X | Any suitable dataset representing a two-dimensional object, such as a point pattern (object of class "ppp"), or a window (object of class "owin").
... | Arguments determining the shift vector.

Details

This is generic. Methods are provided for point patterns (shift.ppp) and windows (shift.owin).

The object is translated by the vector vec.

Value

Another object of the same type, representing the result of applying the shift.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

shift.ppp, shift.owin, rotate, affine


Apply Vector Translation To Pixel Image

Description

Applies a vector shift to a pixel image

Usage

 ## S3 method for class 'im':
 shift(X, vec=c(0,0), ...)

Arguments

X | Pixel image (object of class "im").
vec | Vector of length 2 representing a translation.
... | Ignored

Details

The spatial location of each pixel in the image is translated by the vector vec. This is a method for the generic function shift.

Value

Another pixel image (of class "im") representing the result of applying the vector shift.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

shift

Examples

 # make up an image
 X <- setcov(unit.square())
 plot(X)

 Y <- shift(X, c(10,10))
 plot(Y)
 # no discernible difference except coordinates are different


Apply Vector Translation To Window

Description

Applies a vector shift to a window

Usage

 ## S3 method for class 'owin':
 shift(X, vec=c(0,0), ...)

Arguments

X | Window (object of class "owin").
vec | Vector of length 2 representing a translation.
... | Ignored

Details

The window is translated by the vector vec. This is a method for the generic function shift.

Value

Another window (of class "owin") representing the result of applying the vector shift.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

shift, shift.ppp, rotate, affine

Examples

  W <- owin(c(0,1),c(0,1))
  X <- shift(W, c(2,3))
  ## Not run:
  plot(W)
  # no discernible difference except coordinates are different

## End(Not run)


Apply Vector Translation To Point Pattern

Description

Applies a vector shift to a point pattern.

Usage

 ## S3 method for class 'ppp':
 shift(X, vec=c(0,0), ...)

Arguments

X | Point pattern (object of class "ppp").
vec | Vector of length 2 representing a translation.
... | Ignored

Details

The point pattern, and its window, are translated by the vector vec.

This is a method for the generic function shift.

Value

Another point pattern (of class "ppp") representing the result of applying the vector shift.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

shift, shift.owin, rotate, affine

Examples

  data(cells)
  X <- shift(cells, c(2,3))
  ## Not run:
  plot(X)
  # no discernible difference except coordinates are different

## End(Not run)
  plot(cells, pch=16)
  plot(shift(cells, c(0.03,0.03)), add=TRUE)


Apply Vector Translation To Line Segment Pattern

Description

Applies a vector shift to a line segment pattern.

Usage

 ## S3 method for class 'psp':
 shift(X, vec=c(0,0), ...)

Arguments

X | Line Segment pattern (object of class "psp").
vec | Vector of length 2 representing a translation.
... | Ignored

Details

The line segment pattern, and its window, are translated by the vector vec.

This is a method for the generic function shift.

Value

Another line segment pattern (of class "psp") representing the result of applying the vector shift.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

shift, shift.owin, shift.ppp, rotate, affine

Examples

  X <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
  plot(X, col="red")
  Y <- shift(X, c(0.05,0.05))
  plot(Y, add=TRUE, col="blue")


Simulated Point Pattern

Description

This point pattern data set was simulated (using the Metropolis-Hastings algorithm) from a model fitted to the Numata Japanese black pine data set referred to in Baddeley and Turner (2000).

Usage

data(simdat)

Format

An object of class "ppp" in a square window of size 10 by 10 units.

See ppp.object for details of the format of a point pattern object.

Source

Rolf Turner rolf@math.unb.ca

References

Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point patterns. Australian and New Zealand Journal of Statistics 42, 283–322.


The Soft Core Point Process Model

Description

Creates an instance of the Soft Core point process model which can then be fitted to point pattern data.

Usage

  Softcore(kappa)

Arguments

kappa The exponent kappa of the Soft Core interaction

Details

The (stationary) Soft Core point process with parameters beta and sigma and exponent kappa is the pairwise interaction point process in which each point contributes a factor beta to the probability density of the point pattern, and each pair of points contributes a factor

exp( - (sigma/d)^(2/kappa) )

to the density, where d is the distance between the two points.

Thus the process has probability density

f(x_1,...,x_n) = alpha . beta^n(x) exp( - sum (sigma/||x[i]-x[j]||)^(2/kappa))

where x[1],...,x[n] represent the points of the pattern, n(x) is the number of points in the pattern, alpha is the normalising constant, and the sum on the right hand side is over all unordered pairs of points of the pattern.

This model describes an ``ordered'' or ``inhibitive'' process, with the interpoint interaction decreasing smoothly with distance. The strength of interaction is controlled by the parameter sigma, a positive real number, with larger values corresponding to stronger interaction; and by the exponent kappa in the range (0,1), with larger values corresponding to weaker interaction. If sigma = 0 the model reduces to the Poisson point process. If sigma > 0, the process is well-defined only for kappa in (0,1). The limit of the model as kappa -> 0 is the hard core process with hard core distance h=sigma.

The nonstationary Soft Core process is similar except that the contribution of each individual point x[i] is a function beta(x[i]) of location, rather than a constant beta.

The function ppm(), which fits point process models to point pattern data, requires an argument of class "interact" describing the interpoint interaction structure of the model to be fitted. The appropriate description of the Soft Core process pairwise interaction is yielded by the function Softcore(). See the examples below.

Note the only argument is the exponent kappa. When kappa is fixed, the model becomes an exponential family with canonical parameters log(beta) and

log(gamma) = (2/kappa) log(sigma)

The canonical parameters are estimated by ppm(), not fixed in Softcore().

Value

An object of class "interact" describing the interpoint interaction structure of the Soft Core process with exponent kappa.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Ogata, Y, and Tanemura, M. (1981). Estimation of interaction potentials of spatial point patterns through the maximum likelihood procedure. Annals of the Institute of Statistical Mathematics, B 33, 315–338.

Ogata, Y, and Tanemura, M. (1984). Likelihood analysis of spatial point patterns. Journal of the Royal Statistical Society, series B 46, 496–518.

See Also

ppm, pairwise.family, ppm.object

Examples

   data(cells)
   ppm(cells, ~1, Softcore(kappa=0.5), rbord=0)
   # fit the stationary Soft Core process to `cells'


Evaluate Logical Expression Involving Pixel Images and Return Region Where Expression is True

Description

Given a logical expression involving one or more pixel images, find all pixels where the expression is true, and assemble these pixels into a window.

Usage

  solutionset(...)

Arguments

... An expression in the R language, involving one or more pixel images.

Details

Given a logical expression involving one or more pixel images, this function will find all pixels where the expression is true, and assemble these pixels into a spatial window.

Pixel images in spatstat are represented by objects of class "im" (see im.object). These are essentially matrices of pixel values, with extra attributes recording the pixel dimensions, etc.

Suppose X is a pixel image. Then eval.im(abs(X) > 3) will find all the pixels in X for which the pixel value is greater than 3 in absolute value, and return a window containing all these pixels.

Suppose X and Y are two pixel images with compatible dimensions: they have the same number of pixels, the same physical size of pixels, and the same bounding box. Then eval.im(X > Y) will find all pixels for which the pixel value of X is greater than the corresponding pixel value of Y, and return a window containing these pixels.

In general, expr can be any logical expression involving (a) the names of pixel images, (b) scalar constants, and (c) functions which are vectorised. See the Examples.

The expression expr is evaluated by eval.im. The expression expr must be vectorised. There must be at least one pixel image in the expression. All images must have compatible dimensions.

Value

A spatial window (object of class "owin", see owin.object).

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

im.object, owin.object, eval.im, levelset

Examples

  # test images
  X <- as.im(function(x,y) { x^2 - y^2 }, unit.square())
  Y <- as.im(function(x,y) { 3 * x + y  - 1}, unit.square())

  W <- solutionset(abs(X) > 0.1)
  W <- solutionset(X > Y)
  W <- solutionset(X + Y >= 1)

  area.owin(solutionset(X < Y))


Internal Options in Spatstat Package

Description

Allows the user to examine and reset the values of global parameters which control actions in the spatstat package.

Usage

  spatstat.options(...)

Arguments

... Either empty, or a succession of parameter names in quotes, or a succession of name=value pairs. See below for the parameter names.

Details

This function allows the user to examine and reset the values of global parameters which control actions in the spatstat package. It is analogous to the system function options.

The global parameters are:

npixel
Controls the number of pixels in the discrete approximation of an irregular window by a binary pixel image as created by as.mask. Either an integer or a pair of integers giving the number of pixels in the x and y directions.
maxedgewt
Edge correction weights will be trimmed so as not to exceed this value. This applies to the weights computed by edge.Trans or edge.Ripley and used in Kest and its relatives.
par.binary
List of arguments to be passed to the function image when displaying a binary image mask (in plot.owin or plot.ppp). Typically used to reset the colours of foreground and background.
par.persp
List of arguments to be passed to the function persp when displaying a real-valued image, such as the fitted surfaces in plot.ppm.
par.points
List of arguments controlling the plotting of point patterns by plot.ppp.
par.contour
List of arguments controlling contour plots of pixel images by contour.im.
ndummy.min
Controls the number of dummy points in a quadrature scheme created by default.dummy. Either an integer or a pair of integers giving the number of dummy points in the x and y directions.

If no arguments are given, the current values of all parameters are returned, in a list.

If one parameter name is given, the current value of this parameter is returned (not in a list, just the value).

If several parameter names are given, the current values of these parameters are returned, in a list.

If name=value pairs are given, the named parameters are reset to the given values, and the previous values of these parameters are returned, in a list.

Value

Either a list of parameters and their values, or a single value. See Details.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

options

Examples

  spatstat.options()

  spatstat.options("npixel")
  spatstat.options(npixel=150)
  spatstat.options(npixel=c(100,200))

  spatstat.options(par.binary=list(col=grey(c(0.5,1))))

  spatstat.options(par.persp=list(theta=-30,phi=40,d=4))
  # see help(persp.default) for other options


Divide Point Pattern into Sub-patterns

Description

Divides a point pattern into several sub-patterns, according to their marks, or according to any user-specified grouping.

Usage

  ## S3 method for class 'ppp':
  split(x, f = marks(x), drop=FALSE, un=NULL, ...)
  ## S3 method for class 'ppp':
  split(x, f = marks(x), drop=FALSE, un=missing(f), ...) <- value

Arguments

x | A two-dimensional point pattern. An object of class "ppp".
f | Factor determining the grouping.
drop | Logical. Determines whether empty groups will be deleted.
un | Logical. Determines whether subpatterns will be unmarked (i.e. whether marks will be removed from the points in each subpattern).
... | Other arguments are ignored.
value | List of point patterns.

Details

The function split.ppp divides up the points of the point pattern x into several sub-patterns according to the levels of the factor f. The result is a list of point patterns, one for each level of f.

If f is present, it must be a factor, and its length must equal the number of points in x. The levels of f determine the destination of each point in x. The ith point of x will be placed in the sub-pattern split.ppp(x)$l where l = f[i].

If f is missing, then x must be a multitype point pattern (a marked point pattern whose marks vector is a factor). Then the effect is that the points of each type are separated into different point patterns.

Some of the sub-patterns created by the split may be empty. If drop=TRUE, then empty sub-patterns will be deleted from the list. If drop=FALSE then they are retained.

The argument un determines how to handle marks in the case where x is a marked point pattern. If un=TRUE then the marks of the points will be discarded when they are split into groups, while if un=FALSE then the marks will be retained.

The result of split.ppp has class "splitppp" and can be plotted using plot.splitppp.

The assignment function split<-.ppp updates the point pattern x so that it satisfies split(x, f, drop, un) = value. The argument value is expected to be a list of point patterns, one for each level of f. These point patterns are expected to be compatible in the sense that they all have the same window, and either they are all unmarked or they all have marks of the same kind.

Splitting can also be undone by the function superimpose.

Value

The value of split.ppp is a list of point patterns. The components of the list are named by the levels of f.
The assignment form split<-.ppp returns the updated point pattern x.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

cut.ppp, plot.splitppp, superimpose, ppp.object

Examples

# Multitype point pattern: separate into types
 data(amacrine)
 u <- split(amacrine)

# plot them
 plot(split(amacrine))

# the following are equivalent:
 amon <- split(amacrine)$on
 amon <- unmark(amacrine[amacrine$marks == "on"])

# the following are equivalent:
 amon <- split(amacrine, un=FALSE)$on
 amon <- amacrine[amacrine$marks == "on"]

# Scramble the locations of the 'on' cells
 u <- split(amacrine)
 u$on <- runifpoint(amon$n, amon$window)
 split(amacrine) <- u

# Point pattern with continuous marks
 data(longleaf)

 # cut the range of tree diameters into three intervals
 long3 <- cut.ppp(longleaf, 3)
 # now split them
 long3split <- split(long3)

# Unmarked point pattern
  data(swedishpines)
# cut & split according to nearest neighbour distance
  f <- cut(nndist(swedishpines), 3)
  u <- split(swedishpines, f)


Spokes pattern of dummy points

Description

Generates a pattern of dummy points in a window, given a data point pattern. The dummy points lie on the radii of circles emanating from each data point.

Usage

 spokes(x, y, nrad = 3, nper = 3, fctr = 1.5, Mdefault = 1)

Arguments

x | Vector of x coordinates of data points, or a list with components x and y, or a point pattern (an object of class ppp).
y | Vector of y coordinates of data points. Ignored unless x is a vector.
nrad | Number of radii emanating from each data point.
nper | Number of dummy points per radius.
fctr | Scale factor. Length of largest spoke radius is fctr * M where M is the mean nearest neighbour distance for the data points.
Mdefault | Value of M to be used if x has length 1.

Details

This function is useful in creating dummy points for quadrature schemes (see quadscheme).

Given the data points, the function creates a collection of nrad * nper * length(x) dummy points.

Around each data point (x[i],y[i]) there are nrad * nper dummy points, lying on nrad radii emanating from (x[i],y[i]), with nper dummy points equally spaced along each radius.

The (equal) spacing of dummy points along each radius is controlled by the factor fctr. The distance from a data point to the furthest of its associated dummy points is fctr * M where M is the mean nearest neighbour distance for the data points.

If there is only one data point the nearest neighbour distance is infinite, so the value Mdefault will be used in place of M.

If x is a point pattern, then the value returned is also a point pattern, which is clipped to the window of x. Hence there may be fewer than nrad * nper * length(x) dummy points in the pattern returned.

Value

If argument x is a point pattern, a point pattern with window equal to that of x. Otherwise a list with two components x and y. In either case the components x and y of the value are numeric vectors giving the coordinates of the dummy points.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

quad.object, quadscheme, inside.owin, gridcentres, stratrand

Examples

  dat <- runifrect(10)
  ## Not run:
  plot(dat)

## End(Not run)
  dum <- spokes(dat$x, dat$y)
  ## Not run:
  points(dum$x, dum$y, pch=".")

## End(Not run)
  Q <- quadscheme(dat, dum)


Spruces Point Pattern

Description

The data give the locations of Norwegian spruce trees in a natural forest stand in Saxonia, Germany. Each tree is marked with its diameter at breast height.

Usage

data(spruces)

Format

An object of class "ppp" representing the point pattern of tree locations in a 56 x 38 metre sampling region. Each tree is marked with its diameter at breast height. All values are given in metres.

See ppp.object for details of the format of a point pattern object. The marks are numeric.

These data have been analysed by Fiksel (1984, 1988), Stoyan et al (1987), Penttinen et al (1992) and Goulard et al (1996).

Source

Stoyan et al (1987). Original source unknown.

References

Fiksel, T. (1984) Estimation of parameterized pair potentials of marked and nonmarked Gibbsian point processes. Elektron. Informationsverarb. u. Kybernet. 20, 270–278.

Fiksel, T. (1988) Estimation of interaction potentials of Gibbsian point processes. Statistics 19, 77-86

Goulard, M., S"arkk"a, A. and Grabarnik, P. (1996) Parameter estimation for marked {G}ibbs point processes through the maximum pseudolikelihood method. Scandinavian Journal of Statistics 23, 365–379.

Penttinen, A., Stoyan, D. and Henttonen, H. (1992) Marked point processes in forest statistics. Forest Science 38, 806–824.

Stoyan, D., Kendall, W.S. and Mecke, J. (1987) Stochastic Geometry and its Applications. Wiley.

Examples

     data(spruces)
     plot(spruces)
     # To reproduce Goulard et al. Figure 3
     plot(spruces, maxsize=5*max(spruces$marks))
     plot(unmark(spruces), add=TRUE)


Square Window

Description

Creates a square window

Usage

 square(r=1)
 unit.square()

Arguments

r The side length of the square.

Details

square is a shortcut for creating a window object representing the square [0,r] * [0,r]. It is equivalent to the command owin(c(0,r),c(0,r)).

unit.square creates the unit square [0,1] * [0,1]. It is equivalent to square(1) or square() or owin(c(0,1),c(0,1)).

These commands are included mainly to improve the readability of some code.

Value

An object of class "owin" (see owin.object) specifying a window.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin.object, owin

Examples

 W <- square(10)


The Strauss Point Process Model

Description

Creates an instance of the Strauss point process model which can then be fitted to point pattern data.

Usage

  Strauss(r)

Arguments

r The interaction radius of the Strauss process

Details

The (stationary) Strauss process with interaction radius r and parameters beta and gamma is the pairwise interaction point process in which each point contributes a factor beta to the probability density of the point pattern, and each pair of points closer than r units apart contributes a factor gamma to the density.

Thus the probability density is

f(x_1,...,x_n) = alpha . beta^n(x) gamma^s(x)

where x[1],...,x[n] represent the points of the pattern, n(x) is the number of points in the pattern, s(x) is the number of distinct unordered pairs of points that are closer than r units apart, and alpha is the normalising constant.

The interaction parameter gamma must be less than or equal to 1 so that this model describes an ``ordered'' or ``inhibitive'' pattern.

The nonstationary Strauss process is similar except that the contribution of each individual point x[i] is a function beta(x[i]) of location, rather than a constant beta.

The function ppm(), which fits point process models to point pattern data, requires an argument of class "interact" describing the interpoint interaction structure of the model to be fitted. The appropriate description of the Strauss process pairwise interaction is yielded by the function Strauss(). See the examples below.

Note the only argument is the interaction radius r. When r is fixed, the model becomes an exponential family. The canonical parameters log(beta) and log(gamma) are estimated by ppm(), not fixed in Strauss().

Value

An object of class "interact" describing the interpoint interaction structure of the Strauss process with interaction radius r.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppm, pairwise.family, ppm.object

Examples

   Strauss(r=0.1)
   # prints a sensible description of itself
   data(cells)
   ppm(cells, ~1, Strauss(r=0.07), rbord=0.07)
   # fit the stationary Strauss process to `cells'
   ppm(cells, ~polynom(x,y,3), Strauss(r=0.07), rbord=0.1)
   # fit a nonstationary Strauss process with log-cubic polynomial trend


The Strauss / Hard Core Point Process Model

Description

Creates an instance of the ``Strauss/ hard core'' point process model which can then be fitted to point pattern data.

Usage

  StraussHard(r, hc)

Arguments

r | The interaction radius of the Strauss interaction
hc | The hard core distance

Details

A Strauss/hard core process with interaction radius r, hard core distance h < r, and parameters beta and gamma, is a pairwise interaction point process in which

  • distinct points are not allowed to come closer than a distance h apart
  • each pair of points closer than r units apart contributes a factor gamma to the probability density.

This is a hybrid of the Strauss process and the hard core process.

The probability density is zero if any pair of points is closer than h units apart, and otherwise equals

f(x_1,...,x_n) = alpha . beta^n(x) gamma^s(x)

where x[1],...,x[n] represent the points of the pattern, n(x) is the number of points in the pattern, s(x) is the number of distinct unordered pairs of points that are closer than r units apart, and alpha is the normalising constant.

The interaction parameter gamma may take any positive value (unlike the case for the Strauss process). If gamma = 1, the process reduces to a classical hard core process. If gamma < 1, the model describes an ``ordered'' or ``inhibitive'' pattern. If gamma > 1, the model is ``ordered'' or ``inhibitive'' up to the distance h, but has an ``attraction'' between points lying at distances in the range between h and r.

The function ppm(), which fits point process models to point pattern data, requires an argument of class "interact" describing the interpoint interaction structure of the model to be fitted. The appropriate description of the Strauss/hard core process pairwise interaction is yielded by the function StraussHard(). See the examples below.

The canonical parameter log(gamma) is estimated by ppm(), not fixed in StraussHard().

Value

An object of class "interact" describing the interpoint interaction structure of the ``Strauss/hard core'' process with Strauss interaction radius r and hard core distance hc.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

References

Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point patterns. Australian and New Zealand Journal of Statistics 42, 283–322.

Ripley, B.D. (1981) Spatial statistics. John Wiley and Sons.

Strauss, D.J. (1975) A model for clustering. Biometrika 63, 467–475.

See Also

ppm, pairwise.family, ppm.object

Examples

   StraussHard(r=1,hc=0.02)
   # prints a sensible description of itself

   data(cells)
   ppm(cells, ~1, StraussHard(r=0.1, hc=0.05), rbord=0.1)
   # fit the stationary Strauss/hard core  process to `cells'

   ppm(cells, ~ polynom(x,y,3), StraussHard(r=0.1, hc=0.05), rbord=0.1)
   # fit a nonstationary Strauss/hard core process
   # with log-cubic polynomial trend


Extract Subset of Function Array

Description

Extract a subset of a function array (an object of class "fasp").

Usage

  ## S3 method for class 'fasp':
  x[I, J, drop, ...]

Arguments

x | A function array. An object of class "fasp".
I | any valid expression for a subset of the row indices of the array.
J | any valid expression for a subset of the column indices of the array.
drop, ... | Ignored.

Details

A function array can be regarded as a matrix whose entries are functions. See fasp.object for an explanation of function arrays.

This routine extracts a sub-array according to the usual conventions for matrix indexing.

Value

A function array (of class "fasp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

fasp.object

Examples

 # Lansing woods data - multitype points with 6 types
 data(lansing)

 # compute 6 x 6 array of all cross-type K functions
 a <- alltypes(lansing, "K")

 # extract first three marks only
 b <- a[1:3,1:3]
 ## Not run: plot(b)
 # subset pertaining to hickories
 h <- a[levels(lansing$marks) == "hickory", ]
 ## Not run: plot(h)


Extract Subset of Function Values

Description

Extract a subset of an object of class "fv".

Usage

  ## S3 method for class 'fv':
  x[i, j, ..., drop=FALSE]

Arguments

x | a function value object, of class "fv" (see fv.object). Essentially a data frame.
i | any appropriate subset index. Selects a subset of the rows of the data frame, i.e. a subset of the domain of the function(s) represented by x.
j | any appropriate subset index for the columns of the data frame. Selects some of the functions present in x.
drop, ... | Ignored.

Details

This is a method for "[" for the class "fv". It is very similar to [.data.frame except for a few extra checks on the sanity of the result.

Value

A function value object (of class "fv").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

fv.object

Examples

 data(cells)
 K <- Kest(cells)

 # discard the estimates of K(r) for r  > 0.1
 Ksub <- K[K$r <= 0.1, ]

 # discard the border method estimator
 Ksub <- K[ , names(K) != "border"]


Extract Subset of Image

Description

Extract a subset or subregion of a pixel image.

Usage

  ## S3 method for class 'im':
  x[i, drop=TRUE, ...]

Arguments

x | A two-dimensional pixel image. An object of class "im".
i | Object defining the subregion or subset to be extracted. Either a spatial window (an object of class "owin") or a point pattern (an object of class "ppp") or something that can be converted to a point pattern by as.ppp.
... | Ignored.
drop | Logical value. Locations in w that lie outside the spatial domain of the image X return a pixel value of NA if drop=FALSE, and are omitted if drop=TRUE.

Details

This function extracts a subset of the pixel values in a pixel image. (To reassign the pixel values, see [<-.im).

The image X must be an object of class "im" representing a pixel image defined inside a rectangle in two-dimensional space (see im.object).

The subset to be extracted is determined by the argument i. If i is a spatial window (an object of class "owin"), the values of the image inside this window are extracted (after first clipping the window to the spatial domain of the image if necessary). If i is a point pattern (an object of class "ppp"), then the values of the pixel image at the points of this pattern are extracted.

At locations outside the spatial domain of the image, the pixel value is undefined, and is taken to be NA. The logical argument drop determines whether such NA values will be returned or omitted. It also influences the format of the return value.

If i is a point pattern (or something that can be converted to a point pattern by as.ppp such as a list of x,y coordinates), then X[i, drop=FALSE] is a numeric vector containing the pixel values at each of the points of the pattern. Its length is equal to the number of points in the pattern i. It may contain NAs corresponding to points which lie outside the spatial domain of the image X. By contrast, X[i] or X[i, drop=TRUE] contains only those pixel values which are not NA. It may be shorter.

If i is a spatial window then X[i, drop=FALSE] is another pixel image of the same dimensions as X obtained by setting all pixels outside the window i to have value NA. When the result is displayed by plot.im the effect is that the pixel image X is clipped to the window i.

If i is a spatial window which is not a rectangle (i$type != "rectangle") then X[i, drop=TRUE] is a numeric vector containing the pixel values for all pixels that lie inside the window i.

If i is a rectangle (a spatial window with i$type = "rectangle") then X[i, drop=TRUE] is a pixel image. The spatial domain of this image is the intersection of i with the spatial domain of X.

Value

Either a pixel image or a vector of pixel values. See Details.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

im.object, [<-.im, ppp.object, as.ppp, owin.object, plot.im

Examples

 # make up an image
 X <- setcov(unit.square())
 plot(X)

 # a rectangular subset
 W <- owin(c(0,0.5),c(0.2,0.8))
 Y <- X[W]
 plot(Y)

 # a polygonal subset
 data(letterR)
 R <- affine(letterR, diag(c(1,1)/2), c(-2,-0.7))
 Y <- X[R, drop=FALSE]
 plot(Y)

 # a point pattern
 P <- rpoispp(20)
 Y <- X[P]

 # look up a specified location
 X[list(x=0.1,y=0.2)]


Extract or Replace Subset of a List of Things

Description

Extract or replace a subset of a list of things.

Usage

  ## S3 method for class 'listof':
  x[i]
  ## S3 method for class 'listof':
  x[i] <- value

Arguments

x | An object of class "listof" representing a list of things which all belong to one class.
i | Subset index. Any valid subset index in the usual R sense.
value | Replacement value for the subset.

Details

These are subset methods for the class "listof".

The argument x should be an object of class "listof" representing a list of things that all belong to one class.

The methods extract or replace a designated subset of x, and return an object of class "listof".

Value

Another object of class "listof".

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

plot.listof, summary.listof

Examples

   x <- list(A=runif(10), B=runif(10), C=runif(10))
   class(x) <- c("listof", class(x))
   x[1:2]
   x[1] <- list(A=rnorm(10))


Extract or Replace Subset of Point Pattern

Description

Extract or replace a subset of a point pattern. Extraction has the effect of thinning the points and/or or trimming the window.

Usage

  ## S3 method for class 'ppp':
  x[i, j, drop, ...]
  ## S3 method for class 'ppp':
  x[i, j] <- value

Arguments

x | A two-dimensional point pattern. An object of class "ppp".
i | Subset index. Either a valid subset index in the usual R sense, indicating which points should be retained, or a window (an object of class "owin") delineating a subset of the original observation window.
value | Replacement value for the subset. A point pattern.
j | Redundant. Included for backward compatibility.
drop, ... | Ignored. These arguments are required for compatibility with the generic function.

Details

These functions extract a designated subset of a point pattern, or replace the designated subset with another point pattern.

The function [.ppp is a method for [ for the class "ppp". It extracts a designated subset of a point pattern, either by ``thinning'' (retaining/deleting some points of a point pattern) or ``trimming'' (reducing the window of observation to a smaller subregion and retaining only those points which lie in the subregion) or both.

The pattern will be ``thinned'' if i is a subset index in the usual R sense: either a numeric vector of positive indices (identifying the points to be retained), a numeric vector of negative indices (identifying the points to be deleted) or a logical vector of length equal to the number of points in the point pattern x. In the latter case, the points (x$x[i], x$y[i]) for which subset[i]=TRUE will be retained, and the others will be deleted.

The pattern will be ``trimmed'' if i is an object of class "owin" specifying a window of observation. The points of x lying inside the new window will be retained.

The function [<-.ppp is a method for [<- for the class "ppp". It replaces the designated subset with the point pattern value. The subset of x to be replaced is designated by the argument i as above.

The replacement point pattern value must lie inside the window of the original pattern x. The ordering of points in x will be preserved if the replacement pattern value has the same number of points as the subset to be replaced. Otherwise the ordering is unpredictable.

If the original pattern x has marks, then the replacement pattern value must also have marks, of the same type.

Use the function unmark to remove marks from a marked point pattern.

Use the function split.ppp to select those points in a marked point pattern which have a specified mark.

Value

A point pattern (of class "ppp").

Warnings

The function does not check whether window is a subset of x$window. Nor does it check whether value lies inside x$window.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp.object, owin.object, unmark, split.ppp, cut.ppp

Examples

 data(longleaf)
 # Longleaf pines data
 ## Not run:
 plot(longleaf)

## End(Not run)

 # adult trees defined to have diameter at least 30 cm
 adult <- (longleaf$marks >= 30)
 longadult <- longleaf[adult]
 ## Not run:
 plot(longadult)

## End(Not run)
 # note that the marks are still retained.
 # Use unmark(longadult) to remove the marks

 # New Zealand trees data
 data(nztrees)
 ## Not run:
 plot(nztrees)          # plot shows a line of trees at the far right
 abline(v=148, lty=2)   # cut along this line

## End(Not run)
 nzw <- owin(c(0,148),c(0,95)) # the subwindow
 # trim dataset to this subwindow
 nzsub <- nztrees[nzw]
 ## Not run:
 plot(nzsub)

## End(Not run)

 # Redwood data
 data(redwood)
 ## Not run:
 plot(redwood)

## End(Not run)
 # Random thinning: delete 60% of data
 retain <- (runif(redwood$n) < 0.4)
 thinred <- redwood[retain]
 ## Not run:
 plot(thinred)

## End(Not run)
 # Scramble 60% of data
 modif <- (runif(redwood$n) < 0.6)
 scramble <- function(x) { runifpoint(x$n, x$window) }
 redwood[modif] <- scramble(redwood[modif])

 # Lansing woods data - multitype points
 data(lansing)

 # Hickory trees
  hicks <- split(lansing)$hickory

 # Trees in subwindow
  win <- owin(c(0.3, 0.6),c(0.2, 0.5))
  lsub <- lansing[win]

 # Scramble the locations of trees in subwindow, retaining their marks
  lansing[win] <- scramble(lsub) %mark% (lsub$marks)


Extract Subset of Line Segment Pattern

Description

Extract a subset of a line segment pattern.

Usage

  ## S3 method for class 'psp':
  x[i, j, drop, ...]

Arguments

x | A two-dimensional line segment pattern. An object of class "psp".
i | Subset index. Either a valid subset index in the usual R sense, indicating which segments should be retained, or a window (an object of class "owin") delineating a subset of the original observation window.
j | Redundant - included for backward compatibility.
drop | Ignored. Required for compatibility with generic function.
... | Ignored.

Details

These functions extract a designated subset of a line segment pattern.

The function [.psp is a method for [ for the class "psp". It extracts a designated subset of a line segment pattern, either by ``thinning'' (retaining/deleting some line segments of a line segment pattern) or ``trimming'' (reducing the window of observation to a smaller subregion and clipping the line segments to this boundary) or both.

The pattern will be ``thinned'' if subset is specified. The line segments designated by subset will be retained. Here subset can be a numeric vector of positive indices (identifying the line segments to be retained), a numeric vector of negative indices (identifying the line segments to be deleted) or a logical vector of length equal to the number of line segments in the line segment pattern x. In the latter case, the line segments for which subset[i]=TRUE will be retained, and the others will be deleted.

The pattern will be ``trimmed'' if window is specified. This should be an object of class owin specifying a window of observation to which the line segment pattern x will be trimmed. Line segments of x lying inside the new window will be retained unchanged. Line segments lying partially inside the new window and partially outside it will be clipped so that they lie entirely inside.

Both ``thinning'' and ``trimming'' can be performed together.

Value

A line segment pattern (of class "psp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

psp.object, owin.object

Examples

    a <- psp(runif(20),runif(20),runif(20),runif(20), window=owin())
    plot(a)
  # thinning
    id <- sample(c(TRUE, FALSE), 20, replace=TRUE)
    b <- a[id]
    plot(b, add=TRUE, lwd=3)
 # trimming
    plot(a)
    w <- owin(c(0.1,0.7), c(0.2, 0.8))
    b <- a[,w]
    plot(b, add=TRUE, col="red")


Extract or Replace Sub-Patterns

Description

Extract or replace some of the sub-patterns in a split point pattern.

Usage

  ## S3 method for class 'splitppp':
  x[i]
  ## S3 method for class 'splitppp':
  x[i] <- value

Arguments

x | An object of class "splitppp", representing a point pattern separated into a list of sub-patterns.
i | Subset index. Any valid subset index in the usual R sense.
value | Replacement value for the subset. A list of point patterns.

Details

These are subset methods for the class "splitppp".

The argument x should be an object of class "splitppp", representing a point pattern that has been separated into a list of sub-patterns. It is created by split.ppp.

The methods extract or replace a designated subset of the list x, and return an object of class "splitppp".

Value

Another object of class "splitppp".

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

split.ppp, plot.splitppp, summary.splitppp

Examples

  data(amacrine)  # multitype point pattern
  y <- split(amacrine)
  y[1]
  y["off"]
  y[1] <- list(runifpoint(42, amacrine$window))


Reset Values in Subset of Image

Description

Reset the values in a subset of a pixel image.

Usage

  ## S3 method for class 'im':
  x[i] <- value

Arguments

x | A two-dimensional pixel image. An object of class "im".
i | Object defining the subregion or subset to be extracted. Either a spatial window (an object of class "owin") or a point pattern (an object of class "ppp") or something that can be converted into a point pattern by as.ppp.
value | Vector of replacement values (short vectors will be recycled).

Details

This function changes some of the pixel values in a pixel image. The image X must be an object of class "im" representing a pixel image defined inside a rectangle in two-dimensional space (see im.object).

The subset to be changed is determined by the argument i. If i is a spatial window (an object of class "owin"), the values of the image inside this window are changed. If i is a point pattern (an object of class "ppp", or something that can be converted into a point pattern by as.ppp), then the values of the pixel image at the points of this pattern are changed.

Value

The image x with the values replaced.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

im.object, [.im, ppp.object, as.ppp, owin.object

Examples

 # make up an image
 X <- setcov(unit.square())
 plot(X)

 # a rectangular subset
 W <- owin(c(0,0.5),c(0.2,0.8))
 X[W] <- 2
 plot(X)

 # a polygonal subset
 data(letterR)
 R <- affine(letterR, diag(c(1,1)/2), c(-2,-0.7))
 X[R] <- 3
 plot(X)

 # a point pattern
 P <- rpoispp(20)
 X[P] <- 10
 plot(X)

 # change pixel value at a specific location
 X[list(x=0.1,y=0.2)] <- 7


Sufficient Statistic of Point Process Model

Description

The canonical sufficient statistic of a point process model is evaluated for a given point pattern.

Usage

  suffstat(model, X)

Arguments

model | A fitted point process model (object of class "ppm").
X | A point pattern (object of class "ppp").

Details

The canonical sufficient statistic of model is evaluated for the point pattern X. This computation is useful for various Monte Carlo methods.

Here model should be a point process model (object of class "ppm", see ppm.object), typically obtained from the model-fitting function ppm. The argument X should be a point pattern (object of class "ppp").

Every point process model fitted by ppm has a probability density of the form

f(x) = Z(theta) exp(theta * S(x))

where x denotes a typical realisation (i.e. a point pattern), theta is the vector of model coefficients, Z(theta) is a normalising constant, and S(x) is a function of the realisation x, called the ``canonical sufficient statistic'' of the model.

For example, the stationary Poisson process has canonical sufficient statistic S(x)=n(x), the number of points in x. The stationary Strauss process with interaction range r (and no edge correction) has canonical sufficient statistic S(x)=(n(x),d(x)) where d(x) is the number of pairs of points in x which are closer than a distance r to each other.

suffstat(model, X) returns the value of S(x), where S is the canonical sufficient statistic associated with model, evaluated when x is the given point pattern X. The result is a numeric vector, with entries which correspond to the entries of the coefficient vector coef(model).

The sufficient statistic S does not depend on the fitted coefficients of the model. However it does depend on the irregular parameters which are fixed in the original call to ppm, for example, the interaction range r of the Strauss process. The sufficient statistic also depends on the edge correction that was used to fit the model.

Non-finite values of the sufficient statistic (NA or -Inf) may be returned if the point pattern X is not a possible realisation of the model (i.e. if X has zero probability of occurring under model for all values of the canonical coefficients theta).

Value

A numeric vector of sufficient statistics. The entries correspond to the model coefficients coef(model).

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppm

Examples

    data(swedishpines)
    fitS <- ppm(swedishpines, ~1, Strauss(7))
    X <- rpoispp(summary(swedishpines)$intensity, win=swedishpines$window)
    suffstat(fitS, X)


Summarizing a Pixel Image

Description

summary method for class "im".

Usage

  ## S3 method for class 'im':
  summary(object, ...)
  ## S3 method for class 'im':
  print.summary(x, ...)

Arguments

object | A pixel image.
... | Ignored.
x | Object of class "summary.im" as returned by summary.im.

Details

This is a method for the generic summary for the class "im". An object of class "im" describes a pixel image. See im.object) for details of this class.

summary.im extracts information about the pixel image, and print.summary.im prints this information in a comprehensible format.

In normal usage, print.summary.im is invoked implicitly when the user calls summary.im without assigning its value to anything. See the examples.

The information extracted by summary.im includes

range
The range of the image values.
mean
The mean of the image values.
integral
The ``integral'' of the image values, calculated as the sum of the image values multiplied by the area of one pixel.
dim
The dimensions of the pixel array: dim[1] is the number of rows in the array, corresponding to the y coordinate.

Value

summary.im returns an object of class "summary.im", while print.summary.im returns NULL.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

Examples

  # make an image
  X <- as.im(function(x,y) {x^2}, unit.square())
  # summarize it
  summary(X)
  # save the summary
  s <- summary(X)
  # print it
  print(X)
  s
  # extract stuff
  X$dim
  X$range
  X$integral


Summary of a List of Things

Description

Prints a useful summary of each item in a list of things.

Usage

 ## S3 method for class 'listof':
 summary(object, ...)

Arguments

object | An object of class "listof".
... | Ignored.

Details

This is a method for the generic function summary.

An object of the class "listof" is effectively a list of things which are all of the same class.

This function extracts a useful summary of each of the items in the list.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

summary, plot.listof

Examples

  x <- list(A=runif(10), B=runif(10), C=runif(10))
  class(x) <- c("listof", class(x))
  summary(x)


Summary of a Spatial Window

Description

Prints a useful description of a window object.

Usage

  ## S3 method for class 'owin':
  summary(object, ...)

Arguments

object | Window (object of class "owin").
... | Ignored.

Details

A useful description of the window object is printed.

This is a method for the generic function summary.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

summary, summary.ppp, print.owin

Examples

  summary(owin())  # the unit square

  data(demopat)
  W <- demopat$window  # weird polygonal window
  summary(W)           # describes it

  summary(as.mask(W))  # demonstrates current pixel resolution


Summarizing a Fitted Point Process Model

Description

summary method for class "ppm".

Usage

  ## S3 method for class 'ppm':
  summary(object, ..., quick=FALSE)
  ## S3 method for class 'ppm':
  print.summary(x, ...)

Arguments

object | A fitted point process model.
... | Ignored.
quick | Logical flag controlling the scope of the summary.
x | Object of class "summary.ppm" as returned by summary.ppm.

Details

This is a method for the generic summary for the class "ppm". An object of class "ppm" describes a fitted point process model. See ppm.object) for details of this class.

summary.ppm extracts information about the type of model that has been fitted, the data to which the model was fitted, and the values of the fitted coefficients. (If quick=TRUE then only the information about the type of model is extracted.)

print.summary.ppm prints this information in a comprehensible format.

In normal usage, print.summary.ppm is invoked implicitly when the user calls summary.ppm without assigning its value to anything. See the examples.

Value

summary.ppm returns an object of class "summary.ppm", while print.summary.ppm returns NULL.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

Examples

  # invent some data
  X <- rpoispp(42)
  # fit a model to it
  fit <- ppm(X, ~x, Strauss(r=0.1))
  # summarize the fitted model
  summary(fit)
  # `quick' option
  summary(fit, quick=TRUE)

  # save the full summary
  s <- summary(fit)
  # print it
  print(s)
  s
  # extract stuff
  names(s)
  s$args$correction
  s$name
  s$trend$value

  ## Not run:
  # multitype pattern
  data(demopat)
  fit <- ppm(demopat, ~marks, Poisson())
  summary(fit)

## End(Not run)


Summary of a Point Pattern Dataset

Description

Prints a useful summary of a point pattern dataset.

Usage

 ## S3 method for class 'ppp':
 summary(object, ..., checkdup=TRUE)

Arguments

object | Point pattern (object of class "ppp").
... | Ignored.
checkdup | Logical value indicating whether to check for the presence of duplicate points.

Details

A useful summary of the point pattern object is printed.

This is a method for the generic function summary.

If checkdup=TRUE, the pattern will be checked for the presence of dublicate points, using duplicated.ppp. This can be time-consuming if the pattern contains many points, so the checking can be disabled by setting checkdup=FALSE.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

summary, summary.owin, print.ppp

Examples

  data(cells)      # plain vanilla point pattern
  summary(cells)

  data(lansing)    # multitype point pattern

  summary(lansing) # tabulates frequencies of each mark

  data(longleaf)    # numeric marks

  summary(longleaf) # prints summary.default(x$marks)

  data(demopat)     # weird polygonal window
  summary(demopat)  # describes it


Summary of a Line Segment Pattern Dataset

Description

Prints a useful summary of a line segment pattern dataset.

Usage

  ## S3 method for class 'psp':
  summary(object, ...)

Arguments

object | Line segment pattern (object of class "psp").
... | Ignored.

Details

A useful summary of the line segment pattern object is printed.

This is a method for the generic function summary.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

summary, summary.owin, print.psp

Examples

  a <- psp(runif(10), runif(10), runif(10), runif(10), window=owin())
  summary(a)  # describes it


Summarizing a Quadrature Scheme

Description

summary method for class "quad".

Usage

  ## S3 method for class 'quad':
  summary(object, ..., checkdup=FALSE)
  ## S3 method for class 'quad':
  print.summary(x, ..., dp=3)

Arguments

object | A quadrature scheme.
... | Ignored.
checkdup | Logical value indicating whether to test for duplicated points.
dp | Number of significant digits to print.
x | Object of class "summary.quad" returned by summary.quad.

Details

This is a method for the generic summary for the class "quad". An object of class "quad" describes a quadrature scheme, used to fit a point process model. See quad.object) for details of this class.

summary.quad extracts information about the quadrature scheme, and print.summary.quad prints this information in a comprehensible format.

In normal usage, print.summary.quad is invoked implicitly when the user calls summary.quad without assigning its value to anything. See the examples.

Value

summary.quad returns an object of class "summary.quad", while print.summary.quad returns NULL.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

Examples

  # make a quadrature scheme
  Q <- quadscheme(rpoispp(42))
  # summarize it
  summary(Q)
  # save the summary
  s <- summary(Q)
  # print it
  print(s)
  s
  # extract total quadrature weight
  s$w$all$sum


Summary of a Split Point Pattern

Description

Prints a useful summary of a split point pattern.

Usage

 ## S3 method for class 'splitppp':
 summary(object, ...)

Arguments

object | Split point pattern (object of class "splitppp", effectively a list of point patterns, usually created by split.ppp).
... | Ignored.

Details

This is a method for the generic function summary.

An object of the class "splitppp" is effectively a list of point patterns (objects of class "ppp") representing different sub-patterns of an original point pattern.

This function extracts a useful summary of each of the sub-patterns.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

summary, split, split.ppp

Examples

  data(amacrine)      # multitype point pattern
  summary(split(amacrine))


Superimpose Several Point Patterns

Description

Superimpose any number of point patterns.

Usage

  superimpose(..., W)

Arguments

... | Any number of arguments, each of which represents a point pattern. Each argument must be either a point pattern object (of class "ppp") or a structure containing elements x and y.
W | Optional. Window for the resulting point pattern. An object of class "owin", or something acceptable to as.owin.

Details

This function is used to superimpose two or more point patterns (see also concatxy).

Each of the arguments in ... is either a point pattern object (of class "ppp") or a structure containing (at least) the elements x and y. The point patterns are not required to have the same window of observation.

The window for the superimposed point pattern is specified by W. Its default value is the union of the windows of all the point patterns.

If any of the arguments is a marked point pattern, then all of them must be. In that case, the result is also a marked point pattern.

If the arguments are given in the form name=value, then the names will be used as marks attached to the corresponding points. See the last line in the Examples.

Value

A point pattern (object of class "ppp") representing the superposition (union) of all the point patterns.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

concatxy, quadscheme

Examples

  dat <- runifrect(30)
  xy <- list(x=runif(10),y=runif(10))
  new <- superimpose(dat, xy)
  ## Not run: plot(new)

  # how to make a 2-type point pattern with types "a" and "b"
  u <- superimpose(a = rpoispp(10), b = rpoispp(20))

  # how to make a 2-type point pattern with types 1 and 2
  u <- superimpose("1" = rpoispp(10), "2" = rpoispp(20))


Swedish Pines Point Pattern

Description

The data give the locations of pine saplings in a Swedish forest.

Usage

data(swedishpines)

Format

An object of class "ppp" representing the point pattern of tree locations in a 10 x 10 metre square. Cartesian coordinates are in decimetres (multiples of 0.1 metre).

See ppp.object for details of the format of a point pattern object.

Note

For previous analyses see Ripley (1981, pp. 172-175), Venables and Ripley (1997, p. 483), Baddeley and Turner (2000).

Source

Strand (1975), Ripley (1981)

References

Baddeley, A. and Turner, R. (2000) Practical maximum pseudolikelihood for spatial point patterns. Australian and New Zealand Journal of Statistics 42, 283–322.

Ripley, B.D. (1981) Spatial statistics. John Wiley and Sons.

Strand, L. (1972). A model for stand growth. {IUFRO} Third Conference Advisory Group of Forest Statisticians, INRA, Institut National de la Recherche Agronomique, Paris. Pages 207–216.

Venables, W.N. and Ripley, B.D. (1997) Modern applied statistics with S-PLUS. Second edition. Springer Verlag.


Fit the Thomas Point Process by Minimum Contrast

Description

Fits the Thomas point process to a point pattern dataset by the Method of Minimum Contrast.

Usage

thomas.estK(X, startpar=c(kappa=1,sigma2=1), lambda=NULL,
            q = 1/4, p = 2, rmin = NULL, rmax = NULL)

Arguments

X | Data to which the Thomas model will be fitted. Either a point pattern or a summary statistic. See Details.
startpar | Vector of starting values for the parameters of the Thomas process.
lambda | Optional. An estimate of the intensity of the point process.
q,p | Optional. Exponents for the contrast criterion.
rmin, rmax | Optional. The interval of r values for the contrast criterion.

Details

This algorithm fits the Thomas point process model to a point pattern dataset by the Method of Minimum Contrast, using the K function.

The argument X can be either

a point pattern:
An object of class "ppp" representing a point pattern dataset. The K function of the point pattern will be computed using Kest, and the method of minimum contrast will be applied to this.
a summary statistic:
An object of class "fv" containing the values of a summary statistic, computed for a point pattern dataset. The summary statistic should be the K function, and this object should have been obtained by a call to Kest or one of its relatives.

The algorithm fits the Thomas point process to X, by finding the parameters of the Thomas model which give the closest match between the theoretical K function of the Thomas process and the observed K function. For a more detailed explanation of the Method of Minimum Contrast, see mincontrast.

The Thomas point process is described in Moller and Waagepetersen (2003, pp. 61–62). It is a cluster process formed by taking a pattern of parent points, generated according to a Poisson process with intensity kappa, and around each parent point, generating a random number of offspring points, such that the number of offspring of each parent is a Poisson random variable with mean mu, and the locations of the offspring points of one parent are independent and isotropically Normally distributed around the parent point with standard deviation sigma.

The theoretical K-function of the Thomas process is

K(r) = pi r^2 + (1 - exp(-r^2/(4 sigma^2)))/kappa.

The theoretical intensity of the Thomas process is lambda=kappa* mu.

In this algorithm, the Method of Minimum Contrast is first used to find optimal values of the parameters kappa and sigma^2. Then the remaining parameter mu is inferred from the estimated intensity lambda.

If the argument lambda is provided, then this is used as the value of lambda. Otherwise, if X is a point pattern, then lambda will be estimated from X. If X is a summary statistic and lambda is missing, then the intensity lambda cannot be estimated, and the parameter mu will be returned as NA.

The remaining arguments rmin,rmax,q,p control the method of minimum contrast; see mincontrast.

The Thomas process can be simulated, using rThomas.

Value

An object of class "minconfit". There are methods for printing and plotting this object. It contains the following main components:

par | Vector of fitted parameter values.
fit | Function value table (object of class "fv") containing the observed values of the summary statistic (observed) and the theoretical values of the summary statistic computed from the fitted model parameters.

Author(s)

Rasmus Waagepetersen rw@math.auc.dk Adapted for spatstat by Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/

References

Moller, J. and Waagepetersen, R. (2003). Statistical Inference and Simulation for Spatial Point Processes. Chapman and Hall/CRC, Boca Raton.

Waagepetersen, R. (2006). An estimation function approach to inference for inhomogeneous Neyman-Scott processes. Submitted.

See Also

lgcp.estK, matclust.estK, mincontrast, Kest, rThomas to simulate the fitted model.

Examples

    data(redwood)
    u <- thomas.estK(redwood, c(kappa=10, sigma2=0.1))
    u
    plot(u)


Cut margins from rectangle

Description

Trims a margin from a rectangle.

Usage

 trim.rectangle(W, xmargin=0, ymargin=xmargin)

Arguments

W | A window (object of class "owin"). Must be of type "rectangle".
xmargin | Width of horizontal margin to be trimmed. A single nonnegative number, or a vector of length 2 indicating margins of unequal width at left and right.
ymargin | Height of vertical margin to be trimmed. A single nonnegative number, or a vector of length 2 indicating margins of unequal width at bottom and top.

Details

This is a simple convenience function to trim off a margin of specified width and height from each side of a rectangular window. Unequal margins can also be trimmed.

Value

Another object of class "owin" representing the window after margins are trimmed.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin.object

Examples

  w <- square(10)
  # trim a margin of width 1 from all four sides
  square9 <- trim.rectangle(w, 1)

  # trim margin of width 3 from the right side
  # and margin of height 4 from top edge.
  v <- trim.rectangle(w, c(0,3), c(0,4))


Union of Data and Dummy Points

Description

Combines the data and dummy points of a quadrature scheme into a single point pattern.

Usage

 union.quad(Q)

Arguments

Q A quadrature scheme (an object of class "quad").

Details

The argument Q should be a quadrature scheme (an object of class "quad", see quad.object for details).

This function combines the data and dummy points of Q into a single point pattern. If either the data or the dummy points are marked, the result is a marked point pattern.

The function as.ppp will perform the same task.

Value

A point pattern (of class "ppp").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

quad.object, as.ppp

Examples

  data(simdat)
  Q <- quadscheme(simdat, default.dummy(simdat))
  U <- union.quad(Q)
  ## Not run: plot(U)
  # equivalent:
  U <- as.ppp(Q)


Extract Unique Points from a Spatial Point Pattern

Description

Removes any points that are identical to other points in a spatial point pattern.

Usage

 ## S3 method for class 'ppp':
 unique(x, ...)

Arguments

x | A spatial point pattern (object of class "ppp").
... | Ignored.

Details

This is a method for the generic function unique for point pattern datasets (of class "ppp", see ppp.object).

Two points in a point pattern are deemed to be identical if their x,y coordinates are the same, and their marks are also the same (if they carry marks). The Examples section illustrates how it is possible for a point pattern to contain a pair of identical points.

This function removes duplicate points in x, and returns a point pattern.

Value

Another point pattern object.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp.object, duplicated.ppp, multiplicity.ppp

Examples

   X <- ppp(c(1,1,0.5), c(2,2,1), window=square(3))
   unique(X)


Name for Unit of Length

Description

Inspect or change the name of the unit of length in a spatial dataset.

Usage

units(x)
## S3 method for class 'ppp':
units(x)
## S3 method for class 'psp':
units(x)
## S3 method for class 'owin':
units(x)
## S3 method for class 'im':
units(x)
units(x) <- value
## S3 method for class 'ppp':
units(x) <- value
## S3 method for class 'psp':
units(x) <- value
## S3 method for class 'owin':
units(x) <- value
## S3 method for class 'im':
units(x) <- value

Arguments

x | A spatial dataset. Either a point pattern (object of class "ppp"), a line segment pattern (object of class "psp"), a window (object of class "owin") or a pixel image (object of class "im").
value | Name of the unit of length. See Details.

Details

Spatial datasets in the spatstat package may include the name of the unit of length. This name is used when printing or plotting the dataset, and in some other applications.

units(x) extracts this name, and units(x) <- value sets the name to value.

A valid name is either

  • a single character string
  • a vector of two character strings giving the singular and plural forms of the unit name
  • a list of length 3, containing two character strings giving the singular and plural forms of the basic unit, and a number specifying the multiple of this unit.

Value

The return value of units is an object of class "units" containing the name of the unit of length in x. There are methods for print and summary.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin, ppp

Examples

  X <- runifpoint(20)

  # if the unit of length is 1 metre:
  units(X) <- c("metre", "metres")

  # if the unit of length is 6 inches:
  units(X) <- list("inch", "inches", 6)


Remove Marks from a Marked Point Pattern

Description

Removes the mark information from a marked point pattern

Usage

 unmark(X)

Arguments

X A point pattern. Either an object of class "ppp" or anything acceptable to as.ppp.

Details

This is simply a convenience for those occasions in which we want to remove the marks from a marked point pattern.

Value

A point pattern (of class "ppp") with any mark information deleted.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

ppp.object, as.ppp

Examples

  data(lansing)
  hicks <- lansing[lansing$marks == "hickory", ]
  ## Not run:
  plot(hicks)  # still a marked point pattern, but only 1 value of marks
  plot(unmark(hicks)) # unmarked

## End(Not run)


Update a Fitted Point Process Model

Description

update method for class "ppm".

Usage

  ## S3 method for class 'ppm':
  update(object, ..., fixdummy=TRUE, use.internal=NULL)

Arguments

object | An existing fitted point process model, typically produced by ppm.
... | Arguments to be updated in the new call to ppm.
fixdummy | Logical flag indicating whether the quadrature scheme for the call to ppm should use the same set of dummy points as that in the original call.
use.internal | Optional. Logical flag indicating whether the model should be refitted using the internally saved data (use.internal=TRUE) or by re-evaluating these data in the current frame (use.internal=FALSE).

Details

This is a method for the generic function update for the class "ppm". An object of class "ppm" describes a fitted point process model. See ppm.object) for details of this class.

update.ppm will modify the point process model specified by object according to the new arguments given, then re-fit it. The actual re-fitting is performed by the model-fitting function ppm.

If you are comparing several model fits to the same data, or fits of the same model to different data, it is strongly advisable to use update.ppm rather than trying to fit them by hand. This is because update.ppm re-fits the model in a way which is comparable to the original fit.

The arguments ... are matched to the formal arguments of ppm as follows.

First, all the named arguments in ... are matched with the formal arguments of ppm. Use name=NULL to remove the argument name from the call.

Second, any unnamed arguments in ... are matched with formal arguments of ppm if the matching is obvious from the class of the object. Thus ... may contain

  • exactly one argument of class "ppp" or "quad", which will be interpreted as the named argument Q;
  • exactly one argument of class "formula", which will be interpreted as the named argument trend;
  • exactly one argument of class "interact", which will be interpreted as the named argument interaction;
  • exactly one argument of class "data.frame", which will be interpreted as the named argument covariates.

When fixdummy=FALSE, calling update.ppm is exactly the same as calling ppm with the updated arguments. However, the original and updated models are not strictly comparable (for example, their pseudolikelihoods are not strictly comparable) unless they used the same set of dummy points for the quadrature scheme. Setting fixdummy=TRUE ensures that the re-fitting will be performed using the same set of dummy points. This is highly recommended.

The value of use.internal determines where to find data to re-evaluate the model (data for the arguments mentioned in the original call to ppm that are not overwritten by arguments to update.ppm).

If use.internal=FALSE, then arguments to ppm are re-evaluated in the frame where you call update.ppm. This is like the behaviour of the other methods for update. This means that if you have changed any of the objects referred to in the call, these changes will be taken into account. Also if the original call to ppm included any calls to random number generators, these calls will be recomputed, so that you will get a different outcome of the random numbers.

If use.internal=TRUE, then arguments to ppm are extracted from internal data stored inside the current fitted model object. This is useful if you don't want to re-evaluate anything. It is also necessary if if object has been restored from a dump file using load or source. In such cases, we have lost the environment in which object was fitted, and data cannot be re-evaluated.

By default, if use.internal is missing, update.ppm will re-evaluate the arguments if this is possible, and use internal data if not.

Value

Another fitted point process model (object of class "ppm").

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

Examples

  data(nztrees)
  data(cells)

  # fit the stationary Poisson process
  fit <- ppm(nztrees, ~ 1)

  # fit a nonstationary Poisson process
  fitP <- update(fit, trend=~x)
  fitP <- update(fit, ~x)

  # fit a stationary Strauss process
  fitS <- update(fit, interaction=Strauss(13))
  fitS <- update(fit, Strauss(13))

  # oops, forgot the edge correction
  fitS <- update(fitS, rbord=13)

  # re-fit the model to a subset
  # of the original point pattern
  nzw <- owin(c(0,148),c(0,95))
  nzsub <- nztrees[,nzw]
  fut <- update(fitS, Q=nzsub)
  fut <- update(fitS, nzsub)

  # WARNING: the point pattern argument is called 'Q'

  ranfit <- ppm(rpoispp(42), ~1, Poisson())
  ranfit
  # different random data!
  update(ranfit)
  # the original data
  update(ranfit, use.internal=TRUE)


Variance-Covariance Matrix for a Fitted Point Process Model

Description

Returns the variance-covariance matrix of the estimates of the parameters of a fitted point process model.

Usage

  ## S3 method for class 'ppm':
  vcov(object, ..., what = "vcov", verbose = TRUE, gamaction="warn")

Arguments

object | A fitted point process model (an object of class "ppm".)
... | Ignored.
what | Character string (partially-matched) that specifies what matrix is returned. Options are "vcov" for the variance-covariance matrix, "corr" for the correlation matrix, and "fisher" or "Fisher" for the Fisher information matrix.
verbose | Logical. If TRUE, a message will be printed if various minor problems are encountered.
gamaction | String indicating what to do if object was fitted by gam. Options are "fatal", "warn" and "silent".

Details

This function computes the asymptotic variance-covariance matrix of the estimates of the canonical parameters in the point process model object. It is a method for the generic function vcov.

object should be an object of class "ppm", typically produced by ppm.

The canonical parameters of the fitted model object are the quantities returned by coef.ppm(object). The function vcov calculates the variance-covariance matrix for these parameters.

The argument what provides three options:

what="vcov"
return the variance-covariance matrix of the parameter estimates
what="corr"
return the correlation matrix of the parameter estimates
what="fisher"
return the observed Fisher information matrix.

In all three cases, the result is a square matrix. The rows and columns of the matrix correspond to the canonical parameters given by coef.ppm(object). The row and column names of the matrix are also identical to the names in coef.ppm(object).

For models fitted by maximum pseudolikelihood (which is the default in ppm), the current implementation only works for Poisson point processes. The calculations are based on standard asymptotic theory for the maximum likelihood estimator. The observed Fisher information matrix of the fitted model object is first computed, by summing over the Berman-Turner quadrature points in the fitted model. The asymptotic variance-covariance matrix is calculated as the inverse of the observed Fisher information. The correlation matrix is then obtained by normalising.

For models fitted by the Huang-Ogata method (method="ho" in the call to ppm), the implementation works for all models. A Monte Carlo estimate of the Fisher information matrix is calculated using the results of the original fit.

The argument verbose makes it possible to suppress some diagnostic messages.

The asymptotic theory is not correct if the model was fitted using gam (by calling ppm with use.gam=TRUE). The argument gamaction determines what to do in this case. If gamaction="fatal", an error is generated. If gamaction="warn", a warning is issued and the calculation proceeds using the incorrect theory for the parametric case, which is probably a reasonable approximation in many applications. If gamaction="silent", the calculation proceeds without a warning.

Value

A square matrix.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

Examples

  X <- rpoispp(42)
  fit <- ppm(X, ~ x + y)
  vcov(fit)
  vcov(fit, what="Fish")


Vertices of a Window

Description

Finds the vertices of a window

Usage

 vertices(w)

Arguments

w A window.

Details

This function computes the vertices (`corners') of a spatial window.

The argument w should be a window (an object of class "owin", see owin.object for details).

If w is a rectangle, the coordinates of the four corner points are returned.

If w is a polygonal window (consisting of one or more polygons), the coordinates of the vertices of all polygons are returned.

If w is a binary mask, then a `boundary pixel' is defined to be a pixel inside the window which has at least one neighbour outside the window. The coordinates of the centres of all boundary pixels are returned.

Value

A list with components x and y giving the coordinates of the vertices.

Author(s)

Adrian Baddeley adrian@maths.uwa.edu.au http://www.maths.uwa.edu.au/~adrian/ and Rolf Turner rolf@math.unb.ca http://www.math.unb.ca/~rolf

See Also

owin.object.

Examples

  data(letterR)
  vert <- vertices(letterR)

  plot(letterR, main="Polygonal vertices")
  points(vert)
  plot(letterR, main="Boundary pixels")
  points(vertices(as.mask(letterR)))