Movatterモバイル変換


[0]ホーム

URL:


Type:Package
Title:Spatiotemporal Point Patterns Simulation
Version:1.3.4
Author:Monsuru Adepeju [cre, aut]
Maintainer:Monsuru Adepeju <monsuur2010@yahoo.com>
Description:Generates artificial point patterns marked by their spatial and temporal signatures. The resulting point cloud may exhibit inherent interactions between both signatures. The simulation integrates microsimulation (Holm, E., (2017)<doi:10.1002/9781118786352.wbieg0320>) and agent-based models (Bonabeau, E., (2002)<doi:10.1073/pnas.082080899>), beginning with the configuration of movement characteristics for the specified agents (referred to as 'walkers') and their interactions within the simulation environment. These interactions (Quaglietta, L. and Porto, M., (2019)<doi:10.1186/s40462-019-0154-8>) result in specific spatiotemporal patterns that can be visualized, analyzed, and used for various analytical purposes. Given the growing scarcity of detailed spatiotemporal data across many domains, this package provides an alternative data source for applications in social and life sciences.
Language:en-US
License:GPL-3
URL:https://github.com/MAnalytics/stppSim
BugReports:https://github.com/Manalytics/stppSim/issues/new/choose
Depends:R (≥ 4.1.0)
Encoding:UTF-8
LazyData:true
Imports:splancs, dplyr, tidyr, magrittr, sf, sp, ks, terra, raster,SiMRiv, data.table, tibble, stringr, lubridate, spatstat.geom,sparr, chron, ggplot2, geosphere, leaflet, methods, cowplot,gstat, otuSummary, progressr, future.apply
RoxygenNote:7.2.3
Suggests:knitr, rmarkdown, graphics, grDevices, utils
VignetteBuilder:knitr
Collate:'NRepeat.R' 'artif_spo.R' 'chull_poly.R' 'compare_areas.R''data.R' 'date_checker.R' 'extract_coords.R' 'gtp.R''make_grids.R' 'p_prob.R' 'poly_tester.R' 'walker.R''psim_artif.R' 'psim_real.R' 'snap_points_to_lines.R''space_restriction.R' 'stm.R' 'stp_learner.R'
NeedsCompilation:no
Packaged:2024-07-24 12:30:11 UTC; 55131065
Repository:CRAN
Date/Publication:2024-07-24 13:30:02 UTC

Near Repeat calculator using the Knox test

Description

This function uses the Knox test for space-timeclustering to quantify the spatio-temporalassociation between events (Credit: Wouter Steenbeek).

Usage

NRepeat(x, y, time, sds, tds, s_include.lowest = FALSE,s_right = FALSE, t_include.lowest = FALSE, t_right = FALSE,method = "manhattan", nrep = 999, saveSimulations = FALSE,future.seed = TRUE,...)

Arguments

x

a vector of x coordinates

y

a vector of y coordinates

time

a vector of time. This can be of type integer,numeric, or date

sds

A vector of break points of the spatial intervals.For example c(0,50,120,300) to specify spatial intervals from 0-50,50-120, 120-300 meters. Or c(0,50,100,Inf) to specify spatialintervals from 0-50, 50-100, and 100-Inf meters. (More accurately,on the scale of the provided x and y coordinates. For example,data may be projected in feet and thus the distances refer tofeet instead of meters).

tds

A vector of break points of the temporal intervals.For example c(0,2,4,Inf) to specify temporal intervals from0-2, 2-4, 4-Inf days.

s_include.lowest

the descriptions above are ambiguous onhow exactly the spatial break points are handled. For example,does c(0,100,200) refer to 0-100, 101-200? Or to 0-99 and100-199? s_include.lowest follows the arguments of cut (see ?cut).Logical, indicating if a spatial distance equal to the lowest(or highest, for right = FALSE) 'breaks' value should be included.Default = FALSE. See vignette("NearRepeat_breaks") for details.

s_right

logical, indicating if the spatial intervals shouldbe closed on the right (and open on the left) or vice versa.Default = FALSE. See vignette("NearRepeat_breaks") for details.

t_include.lowest

t_include.lowest follows the arguments ofcut (see ?cut). Logical, indicating if a temporal distance equalto the lowest (or highest, for right = FALSE) 'breaks' valueshould be included. Default = FALSE.

t_right

logical, indicating if the temporal intervals shouldbe closed on the right (and open on the left) or vice versa.Default = FALSE. See vignette("NearRepeat_breaks") for details.

method

The method to calculate the spatial distances betweencrime events. Methods possible as in the 'dist' function (see ?dist).Default is 'manhattan', which seems to be a fair approximation ofthe distance travelled by a road network. Alternatively, the usercan specify 'euclidean' to get the 'as the crow flies' distance.

nrep

The number of replications of the MonteCarlo simulation (default = 999).

saveSimulations

Should all simulated contingency tables besaved as a 3-dimensional array?Default = FALSE

future.seed

A logical or an integer (of length one or seven),or a list of length(X) with pre-generated random seeds. Default = TRUE.See R package future.apply for details.

...

(optional) Additional arguments passed to future_lapply()

Details

Further details available at:https://github.com/wsteenbeek/NearRepeat.

Value

An object of type "knox", i.e. a list with four tables.For each spatial and temporal distance combination,(1) The countsof observed crime pairs, (2) The Knox ratios based on the mean of thesimulations, (3) The Knox ratios based on the median of thesimulations, (4) p-values.

References

Steenbeek W. Near Repeat. R package version 0.1.1. 2018.URL: https://github.com/wsteenbeek/NearRepeat

Examples

## Not run: # Generate example data. Suppose x and y refer to meters distance.set.seed(10)(mydata <- data.frame(x = sample(x = 20, size = 20, replace = TRUE) * 20,                     y = sample(x = 20, size = 20, replace = TRUE) * 20,                     date = as.Date(sort(sample(20, size = 20, replace = TRUE)),                     origin = "2018-01-01")                     ))# Near Repeat calculation using 0-100 meters and 100-Inf meters, and three# temporal intervals of 2 daysset.seed(38673)NRepeat(x = mydata$x, y = mydata$y, time = mydata$date,           sds = c(0,100,Inf), tds = c(0,2,4))# Add a 'same repeat' spatial interval of 0.001 meters, and use Euclidean# distanceset.seed(38673)NRepeat(x = mydata$x, y = mydata$y, time = mydata$date,           sds = c(0,0.001,100,Inf), tds = c(0,2,4),           method = "euclidean")# Only do 99 replicationsset.seed(38673)NRepeat(x = mydata$x, y = mydata$y, time = mydata$date,           sds = c(0,0.001,100,Inf), tds = c(0,2,4),           method = "euclidean", nrep = 99)# The plot() function can be used to plot a Heat Map of Near Repeat results# based on p-valuesset.seed(4622)myoutput <- NRepeat(x = mydata$x, y = mydata$y, time = mydata$date,                       sds = c(0,100,200,300,400), td = c(0,1,2,3,4,5))# The default range of p-values that will be highlighted (0-.05) can be# adjusted using the 'pvalue_range' parameter. By default the Knox ratios# are printed in the cells, but this can be adjusted using the 'text'# parameter. The default is "knox_ratio". Possible values are "observed",# "knox_ratio", "knox_ratio_median", "pvalues", or NA.## End(Not run)

Artificial spatial origins

Description

Simulates spatial locations to serveas origins of walkers. If provided, spaces coveredby restriction features are avoided. Finalorigins are assigned probability valuesindicating the strengths of the origins.

Usage

artif_spo(poly, n_origin=50, restriction_feat = NULL,n_foci=5, foci_separation = 10, mfocal = NULL,conc_type = "nucleated", p_ratio)

Arguments

poly

(An sf or S4 object)a polygon shapefile defining the extentof the landscape

n_origin

number of locations to serve asorigins for walkers. Default:50.

restriction_feat

(An S4 object) optionalshapefile containing featuresin which walkers cannot walk through.Default:NULL.

n_foci

number of focal points amongst the originlocations. The origins to serve as focalpoints are based on random selection.n_foci must besmaller thann_origins.

foci_separation

a value from1 to100indicating the nearness of focal points to one another.A0 separation indicates that focal points are inclose proximityof one another, while a100 indicates focal points beingevenly distributed across space.

mfocal

the c(x, y) coordinates of a single point,representing a pre-definedmain focal point (origin)in the area. The default isNULL in which a randomcoordinate is chosen within thepolygon area.

conc_type

concentration of the rest of theorigins (non-focal origins) around the focal ones. The optionsare"nucleated" and"dispersed".

p_ratio

the smaller of thetwo terms of proportional ratios.For example, a value of20implies20:80 proportional ratios.

Details

The focal origins (n_foci) serve as the central locations(such as, city centres). Thefoci_separation indicatesthe nearness of focal origins from one another.Theconc_type argument allows a user to specifythe type of spatial concentration exhibited by the non-focalorigin around the focal ones.Ifrestriction_feat is provided, its features helpto prevent the occurrence of any events in the areasoccupied by the features.

Value

Returns a list detailing theproperties of the generated spatial originswith associatedstrength (probability) values.

Examples

#load boundary of Camdenload(file = system.file("extdata", "camden.rda",package="stppSim"))boundary = camden$boundary # get boundarylanduse <- camden$landusespo <- artif_spo(poly = boundary, n_origin = 50,restriction_feat = landuse, n_foci=5, foci_separation = 0,mfocal = NULL, conc_type = "dispersed", p_ratio=20)

Records of crimes of Camden Borough of London,UK, 2021 (Source: https://data.police.uk/data/)

Description

Data comprising 'Theft' and 'Criminal Damage'records of Camden Borough of London, UKfor the year 2021 (Source:⁠https://data.police.uk/⁠).Note: Police.uk data is aggregated at monthlyscale (yyyy-mm). But, the data provided here has beendisaggregated to daily scale by adding fake'daily' stamps (to giveyyyy-mm-dd). So, caution shouldbe taken when interpreting the results based onfull date.

Usage

camden_crimes

Format

A matrix containing four variables


Boundary surrounding a set of points

Description

Generates a boundary (polygon) arounda set of points, using Convex Hull technique(Eddy, W. F, 1977).

Usage

chull_poly(xycoords,crsys = NULL)

Arguments

xycoords

(matrix) A 2-columncoordinate vectors of points:x - the eastings,andy - the northing.

crsys

Optional string specifying the coordinatereference system (crs) of the resulting boundary, e.g.,the crs string "+proj=longlat +datum=WGS84" transformthe resulting boundary to wgs84 system.

Details

Draws an arbitrary boundary aroundspatial points by joining the outer-mostpoints by lines.

Value

Returns a "SpatialPolygonsDataFrame"object representing the boundarysurround the spatial points

References

Eddy, W. F. (1977).A new convex hull algorithm for planar sets.ACM Transactions on Mathematical Software,3, 398–403.10.1145/355759.355766.

Examples

data(xyt_data)#extract xy coordinates onlyxy <- matrix(as.numeric(xyt_data[,1:2]),,2)bry <- chull_poly(xy, crsys = NULL)#visualise result#plot(bry) #to plot#points(xy[,1], xy[,2], add=TRUE)

Compare two areas

Description

To compare the sizes of twoareas (boundary shapefiles).

Usage

compare_areas(area1, area2,display_output = FALSE)

Arguments

area1

(asspatialPolygons,spatialPolygonDataFrames, or⁠simple features⁠). the polygon object of thefirst area.

area2

(asspatialPolygons,spatialPolygonDataFrames, or⁠simple features⁠). the polygon object of thesecond area.

display_output

(logical) Whether to print outputin the console.Default:FALSE

Details

Compares the sizes of two areas (polygon shapefiles).The two shapefiles can be in anycrs,and any spatial object formats. If enabled, the output (a value)comparing the area of the two polygons is printed. This value canbe used to scale some specific spatial parameters, includingn_origin,s_threshold, andstep_length.

Value

Returns a plot and a text (string) comparingthe sizes of two areas.

Examples

#load 'area1' object - boundary of Camden, UKload(file = system.file("extdata", "camden.rda",package="stppSim"))camden_boundary = camden$boundary#load 'area2' - boundary of Birmingham, UKload(file = system.file("extdata", "birmingham_boundary.rda",package="stppSim"))#runcompare_areas(area1 = camden_boundary,area2 = birmingham_boundary, display_output = FALSE)

Date (Format) Checker

Description

Checks if date is in aspecified format (i.e.'yyyy-mm-dd').

Usage

date_checker(x)

Arguments

x

A date or a vector of date values

Details

Returns"TRUE" if alldate entries are in the specified format(⁠"yyyy-mm-dd⁠),andFALSE if at least one date is notin the format.

Value

Returns TRUE or FALSE

Examples

date_list_1 <- c("2021-09-12", "2016-xx-02","09/08/2012")date_checker(date_list_1)#> FALSE (Entries 2 and 3#are incorrect date inputs)date_list_2 <- c("2021-09-12", "1998-03-09")date_checker(date_list_2)#> TRUE

Coordinates extraction

Description

Extracts the bounding (edges) coordinatesof a polygon object.

Usage

extract_coords(poly)

Arguments

poly

(An sf or S4 object)A polygon shapefile.

Details

Given a spatial polygon object,the function extracts its bounding coordinates.

Value

Returns 2-column xy coordinatesrepresenting points of directionalchange along the boundary.

Examples

#load boundary of Camdenload(file = system.file("extdata", "camden.rda",package="stppSim"))boundary = camden$boundary # get boundaryextract_coords(poly=boundary)

Global temporal pattern (GTP)

Description

Models the global temporal pattern,as combining the long-term trend and seasonality.

Usage

gtp(start_date, trend = "stable",slope = NULL, shortTerm = "cyclical",fPeak = 90, show.plot =FALSE)

Arguments

start_date

the start date of the temporal pattern.The date should be in the format"yyyy-mm-dd".The GTP will normally cover a 1-year period.

trend

specifies the direction of thelong-term trend. Options are:"falling","stable",and"rising". Default value is:"stable".

slope

slope of the long-term trend whenan"rising" or"falling" trend is specified.Options:"gentle" or"steep". The default value isset asNULL for thestable trend.

shortTerm

type of short- to medium-termfluctuations (patterns) of the time series.Options are:`"cyclical"` and `"acyclical"`.Default is:`"cyclical"`.

fPeak

first seasonalpeak of cyclical short term. Default value is90.Set asNULL for"acyclical" short term pattern.

show.plot

(logical) Shows 'gtp'.Default isFALSE.

Details

Models the GTP for anchoring the temporaltrends and patterns of the point patterns to be simulated.

Value

Returns a time series (list) of 365data points representing1-year global temporal pattern.

Examples

gtp(start_date = "2020-01-01", trend = "stable",slope = NULL, shortTerm = "cyclical",fPeak = 90, show.plot = FALSE)

Make square grids

Description

Generates a system of square gridsover an area (boundary shapefile).

Usage

make_grids(poly, size = 350,show_output = FALSE, interactive = FALSE)

Arguments

poly

(asspatialPolygons,spatialPolygonDataFrames, or⁠simple features⁠). A polygon object overwhich square grids are to be created.

size

Size of square grids to becreated. For example, the inputsizefor a 350 by 350 square grids is350.

show_output

(logical) Display the output.Default:FALSE

interactive

(logical) to showinteractive map of the grids generated.Default:FALSE.

Details

Generates a square grid system in a shapefileformat (in the samecrs as the inputpoly).Ifinteractive argument isTRUE, an interactivemap is shown from which the centroid coordinatesof any grid can be displayed by hovering the mouseover the grid. If internet connection isavailable on the PC, a basemap (OpenStreetmap) isadded to help identify places.

Value

Returns a "SpatialPolygonsDataFrames" objectrepresenting a system of square grids coveringthe polygon area.

Examples

#load boundary of Camdenload(file = system.file("extdata", "camden.rda",package="stppSim"))boundary = camden$boundarymake_grids(poly=boundary, size = 350,show_output = FALSE, interactive = FALSE)

Proportional (probability) distribution

Description

Generates ann probabilityvalues in accordance with a specifiedproportional ratios.

Usage

p_prob(n,  p_ratio = 20)

Arguments

n

a number of data points.

p_ratio

the smaller of theterms of specified proportional ratios. For instance, for a30:70 ratio,p_ratio is equal to30.Default value is set as20. Validp_ratio valuesare: (5, 10, 20, 30, 40).

Details

Proportional ratios are used to divide thearea under curve (auc) of an exponential functionsuch that for any given percentage ratiosa:b, theauc is divided intob:a.

Value

Returns a dataframe witha probability field.

Examples

p_prob(n = 15,  p_ratio = 20)

Boundary coordinates

Description

Boundary coordinates of CamdenBorough of London

Usage

poly

Format

A dataframe containing one variable:


Geometry and CoordinateReference System test of a polygon

Description

Tests whether a polygonhas the correct geometry,namely;S4 orsf. Also, teststhat there is a valid projection attached tothe polygon.

Usage

poly_tester(poly)

Arguments

poly

(asspatialPolygons,spatialPolygonDataFrames, or⁠simple features⁠). A spatial polygon object.

Details

Returns an error message ifthe polygon is not in thecorrect geometry or CRS.

Value

Returns error messages, or mute

Examples

#load boundary of Camdenload(file = system.file("extdata", "camden.rda",package="stppSim"))boundary = camden$boundary # get boundarypoly_tester(poly=boundary)

Stpp from synthetic origins

Description

Generates spatiotemporalpoint patterns based on a set ofsynthesized origins.

Usage

psim_artif(n_events=1000, start_date = "2021-01-01",poly, netw = NULL, n_origin, restriction_feat=NULL, field,n_foci, foci_separation, mfocal = NULL, conc_type = "dispersed",p_ratio=20, s_threshold = 50, step_length = 20,trend = "stable", shortTerm = "cyclical", fPeak=90,s_band = c(0, 200),t_band = c(1, 5, 10),slope = NULL, interactive = FALSE, show.plot=FALSE, show.data=FALSE, ...)

Arguments

n_events

number of points(events) to simulate. Default:1000.A vector of integer values can be supplied, such as,c(a1,a2, ....)⁠, where ⁠a⁠1, ⁠a'2, ...represent different integer values.

start_date

the start date of the temporal pattern.The date should be in the format"yyyy-mm-dd".The 'gtp' will normally cover a 1-year period.

poly

(An sf or S4 object)a polygon shapefile defining the extent of the landscape.

netw

(An sf or S4 object)The network path of the landscape(e.g. road and/or street). Default:NULL.If provided each event is snapped to the closestnetwork path/segment.

n_origin

number of locations to serve asorigins for walkers. Default:50.

restriction_feat

(An S4 object) optionalshapefile containing featuresin which walkers cannot walk through.Default:NULL.

field

a number in the range of[0-1](i.e. restriction values) assignedto all features; orthe name of a numeric field to extract suchrestriction values for different classes offeature.Restriction value0 and1 indicate thelowest and the highest obstructions, respectively.Default:NULL.

n_foci

number of focal points amongst the originlocations. The origins to serve as focalpoints are based on random selection.n_foci must besmaller thann_origins.

foci_separation

a value from1 to100indicating the nearness of focal points to one another.A0 separation indicates that focal points are inclose proximityof one another, while a100 indicates focal points beingevenly distributed across space.

mfocal

the c(x, y) coordinates of a single point,representing a pre-definedmain focal point (origin)in the area. The default isNULL in which a randomcoordinate is chosen within thepolygon area.

conc_type

concentration of the rest of theorigins (non-focal origins) around the focal ones. The optionsare"nucleated" and"dispersed".

p_ratio

the smaller of thetwo terms of proportional ratios.For example, a value of20implies20:80 proportional ratios.

s_threshold

defines the spatialperception range of a walker at a givenlocation. Default:250 (in the samelinear unitas thepoly - polygon shapefile).

step_length

the maximum step takenby a walker from one point to the next.

trend

specifies the direction of thelong-term trend. Options are:"falling","stable",and"rising". Default value is:"stable".

shortTerm

type of short- to medium-termfluctuations (patterns) of the time series.Options are:`"cyclical"` and `"acyclical"`.Default is:`"cyclical"`.

fPeak

first seasonalpeak of cyclical short term. Default value is90.Only used for"cyclical" short term pattern.

s_band

distance bandwidth within whichthe event re-occurences are maximized (i.e.,interactions are maximum). Specified as a vector oftwo distance values. Default:c(0, 200).

t_band

temporal bandwidth within whichevent re-occurences are maximized (i.e., interactionsare maximum). Specified as a vector of values (in days)c(1, 5, 7, 14).

slope

slope of the long-term trend whenan"rising" or"falling" trend is specified.Options:"gentle" or"steep". The default value isset asNULL for thestable trend.

interactive

Whether to run the process ininteractive mode. Default isFALSE. IfTRUE,a user is able to preview the spatial and temporal modelsof the expected distribution of the final simulatedevents (points).

show.plot

(logical) Shows GTP.Default isFALSE.

show.data

(TRUE or FALSE) To show the outputdata. Default isFALSE.

...

additional arguments to pass fromgtp,walker andartif_spofunctions.

Details

Simulate artificial spatiotemporal patternsand interactions based user specifications.

Value

Returns a list of artificial spatiotemporalpoint patterns based on user-defined parameters.

Examples

## Not run: #load boundary and land use of Camden#load(file = system.file("extdata", "camden.rda",#package="stppSim"))#boundary = camden$boundary # get boundary#landuse = camden$landuse # get landuseboundary <- stppSim:::boundarylanduse <- stppSim:::landuse#In this example, we will use a minimal number of#'n_origin' (i.e. `20`) for faster computation:#simulate datasimulated_stpp <- psim_artif(n_events=200, start_date = "2021-01-01",poly=boundary, netw = NULL, n_origin=20, restriction_feat = NULL,field = NULL,n_foci=1, foci_separation = 10, mfocal = NULL,conc_type = "dispersed",p_ratio = 20, s_threshold = 50,step_length = 20,trend = "stable", shortTerm = "cyclical",fPeak=90, s_band = c(0, 200),t_band = c(1, 5, 10),slope = NULL, interactive = FALSE, show.plot=FALSE, show.data=FALSE)#If `n_events` is a vector of values,#retrieve the simulated data for the#corresponding vector element by using#`simulated_stpp[[enter-element-index-here]]`, e.g.,#to retrieve the first dataframe, use#simulated_stpp[[1]].#The above example simulates point patterns on#an unrestricted landscape. If set ,#`restriction_feat = landuse` and#`field = "restrVal"`, then the simulation#is performed on a restricted landscape.## End(Not run)

Stpp from real (sample) origins

Description

Generates spatiotemporal point patternfrom origins sampled based on real sample dataset.

Usage

psim_real(n_events, ppt, start_date = NULL, poly = NULL,netw = NULL, s_threshold = NULL, step_length = 20, n_origin=50,restriction_feat=NULL, field=NA,p_ratio=20, interactive = FALSE, s_range = 150,s_interaction = "medium", tolerance = 0.07,crsys = NULL)

Arguments

n_events

number of points(events) to simulate. Default:1000.A vector of integer values can be supplied, such as,c(a1,a2, ....)⁠, where ⁠a⁠1, ⁠a'2, ...represent different integer values.

ppt

A 3-column matrix or list containingx - eastings,y - northing, andt - time of occurrence(in the format: ‘yyyy-mm-dd’)

start_date

the start date of the temporal pattern.The date should be in the format"yyyy-mm-dd".The temporal pattern will normally cover1-year period.

poly

(An sf or S4 object)a polygon shapefile defining the extent of the landscape

netw

(An sf or S4 object)The network path of the landscape(e.g. road and/or street). Default:NULL.If provided each event is snapped to the closestnetwork path/segment.

s_threshold

defines the spatialperception range of a walker at a givenlocation. Default:250 (in the samelinear unitas thepoly - polygon shapefile).

step_length

the maximum step takenby a walker from one point to the next.

n_origin

number of locations to serve asorigins for walkers. Default:50.

restriction_feat

(An S4 object) optionalshapefile containing featuresin which walkers cannot walk through.Default:NULL.

field

a number in the range of[0-1](i.e. restriction values) assignedto all features; orthe name of a numeric field to extract suchrestriction values for different classes offeature.Restriction value0 and1 indicate thelowest and the highest obstructions, respectively.Default:NULL.

p_ratio

the smaller of thetwo terms of proportional ratios.For example, a value of20implies20:80 proportional ratios.

interactive

Whether to run the process ininteractive mode. Default isFALSE. IfTRUE,a user is able to preview the spatial and temporal modelsof the expected distribution of the final simulatedevents (points).

s_range

A value (in metres), not less than 150,specifying the maximum range of spatialinteraction across the space. For example, for 150m,the intervals of spatial interactions are created as(0, 50],(50 - 100], and(100-150],representing the "small", "medium", and "large",spatial interaction ranges, respectively. Ifs_range is set asNULL, simulationfocusses only on generating point pattern withsimilar spatiotemporal patterns as the sampledataset.

s_interaction

(string) indicating thetype of spatial interaction to detect.Default:"medium" (See parameter's_range')

tolerance

Pvalue to use for the extraction ofspace-time interaction in the sample data. Defaultvalue:0.05.

crsys

(string) the EPSG code of the projectionsystem of theppt coordinates. This is only used ifpoly argument isNULL.See "http://spatialreference.org/" for the list ofEPSG codes for different regions of the world.As an example, the EPSG code for the British National Gridprojection system is:"EPSG:27700".

Details

The spatial and temporal patterns andinteractions detected in sample datasetsare extrapolated to synthetise largerdata size. Details of the spatiotemporalinteractions detected in the sampledataset are provided. If the street networkof the area is provided, each point issnapped to its nearest street segment.

Value

A list of artificial spatiotemporalpoint patterns and interaction generated based on a sample(real) data.

References

Davies, T.M. and Hazelton, M.L. (2010), Adaptivekernel estimation of spatial relative risk,Statistics in Medicine, 29(23) 2423-2437.Terrell, G.R. (1990), The maximal smoothing principlein density estimation, Journal of theAmerican Statistical Association, 85, 470-477.

Examples

## Not run: data(camden_crimes)#subset 'theft' crimetheft <- camden_crimes[which(camden_crimes$type == "Theft"),]#specify the proportion of full data to usesample_size <- 0.3set.seed(1000)dat_sample <- theft[sample(1:nrow(theft),round((sample_size * nrow(theft)), digits=0),replace=FALSE),1:3]#plot(dat_sample$x, dat_sample$y) #preview#load boundary and land use of Camden#load(file = system.file("extdata", "camden.rda",#package="stppSim"))#landuse = camden$landuse # get landuselanduse <- stppSim:::landuse#simulate datasimulated_stpp <- psim_real(n_events=2000, ppt=dat_sample,start_date = NULL, poly = NULL, netw = NULL, s_threshold = NULL,step_length = 20, n_origin=20,restriction_feat = NULL, field=NULL,p_ratio=20, interactive = FALSE, s_range = 150,s_interaction = "medium", tolerance = 0.07,crsys = "EPSG:27700")#If `n_events` is a vector of values,#retrieve the simulated data for the#corresponding vector element by using#`simulated_stpp[[enter-element-index-here]]`, e.g.,#to retrieve the first dataframe, use#simulated_stpp[[1]].#The above example simulates point patterns on#an unrestricted landscape. If \code{restriction_feat = landuse} and \code{field = "restrVal"},then the simulation#is run with the landuse features as restrictions#on the landscape.## End(Not run)

Snapping point to network

Description

Snaps points to the nearest segmentof a network data.

Usage

snap_points_to_lines(points, lines,verbose = FALSE)

Arguments

points

point data (sf object)

lines

line/street/road network (sf object)

verbose

Whether to output processingmessages.

Details

Function snaps points (within 300m)to the nearest segment on a network. The remainingpoints outside 300m buffer are returned intheir original locations (Credit: Michal Kvasnicka)

Value

Point (sf object) with adjusted coordinatesto fit on the network data

Examples

#get line and point data#load(file = system.file("extdata", "camden.rda",#package="stppSim"))lines <- stppSim:::linespts <- stppSim:::ptsmy_points <- snap_points_to_lines(points=pts,lines=lines,verbose = FALSE)#preview result#ggplot()+#geom_sf(data = lines, col = 'red')+#geom_sf(data = pts, shape = 1)

Space restriction raster map

Description

Builds a space restriction mapfrom one or more shapefiles. A space restrictionraster map showing the restriction levelsof various features across the landscape.The function buildson raster- and SimRIv-packages.

Usage

space_restriction(shp, baseMap, res, binary = is.na(field),field = NA, background = 1)

Arguments

shp

shapefile object containingfeatures to serve as obstructions to the movementof walkers.

baseMap

if provided, a raster onto whichto stack the restriction features (shp).

res

the desired pixel resolution of theraster to be created, when baseMap is not provided.

binary

if TRUE, the shapefile will be rasterizedso that all features are assigned a value of0 (minimumrestriction level),and the background is assigned1(maximum restriction level).

field

a number in the range of[0-1](i.e. restriction values) assignedto all features; orthe name of a numeric field to extract suchrestriction values ([0 <= value < 1]for different classes of feature.Restriction value0 and1 indicate thelowest and the highest obstructions, respectively.Default:NULL.

background

the value in the range 0 and 1to assign to all pixels that are not coveredby any shapefile object.

Details

Helps to create a complete space restriction mapwith cell values ranging from 0(⁠minimum restriction level⁠) and 1(⁠maximum restriction level⁠). Allother areas not covered by any features are assigned the valueofbackground. When stacking additional features to existingbaseMap, only the areas covered by features are updated, whilethe remaining areas retain the original values ofbaseMap.

Value

Returns a raster map showing the restrictionlevels across the landscape.

References

  1. Paul Murrell (2019). rasterize: Rasterize GraphicalOutput. R package version 0.1.https://CRAN.R-project.org/package=rasterize

  2. Quaglietta L, Porto M (2019). SiMRiv: Individual-Based,Spatially-Explicit Simulation and Analysis of Multi-StateMovements in River Networks and Heterogeneous Landscapes.R package version 1.0.4, <URL:https://CRAN.R-project.org/package=SiMRiv>.

Examples

#load boundary of Camden and land use dataload(file = system.file("extdata", "camden.rda",package="stppSim"))boundary = camden$boundary # get boundaryrestrct_map <- space_restriction(shp = boundary,res = 20, binary = TRUE)#plot the result#plot(restrct_space)#Setting 'restrct_space' raster as basemap, the landuse#map can now be stacked onto the basemap as follows:landuse = camden$landuse # get landuserestrct_Landuse <- space_restriction(shp = landuse,baseMap = restrct_map,res = 20, field = "restrVal", background = 1)#plot(restrct_Landuse)

Spatial and temporal model

Description

To generate graphics depicting the spatialand temporal models of the final simulation

Usage

stm(pt, poly, df, crsys = NULL,display_output = FALSE)

Arguments

pt

a data frame with the first threefields being 'x', 'y', and 'z' information.

poly

(An sf or S4 object)a polygon shapefile defining the extent of a landscape.Default:NULL, in which the spatial extentofpt is utilized.

df

a vector or 1-column data frame containingvalues for the time series.

crsys

(string) the EPSG code of the projectionsystem of theppt coordinates. This only used ifpoly argument isNULL.See "http://spatialreference.org/" for the list ofEPSG codes for different regions of the world.As an example, the EPSG code for the British National Gridprojection system is:"EPSG:27700".

display_output

(logical) display the output.Default:FALSE

Details

Incorporated intopsim_artif andpsim_real functions to allow the preview ofthe spatial and the temporal model of the simulation.The spatial model is the strength distribution oforigin which is the likeness of the spatial patternsto be simulated. The temporal model is the previewof the trend and seasonal patterns to be expectedfrom the simulation.

Value

A graphics showing the spatial andtemporal model of the simulation.

Examples

## Not run: #load polygon shapefileload(file = system.file("extdata", "camden.rda",package="stppSim"))camden_boundary = camden$boundary#read xyz datadata(xyz)#create a time seriest <- seq(0,5,0.5)df <- data.frame(data = abs(min(sin(t))) + sin(t))#run functionstm(pt = xyz, poly=camden_boundary, df=df,crsys = NULL, display_output = FALSE)## End(Not run)

Learning the spatiotemporal properties ofa sample data

Description

Learns both the spatial and the temporalproperties of a real sample dataset.

Usage

stp_learner(ppt, start_date = NULL, poly = NULL,n_origin=50, p_ratio, gridSize = 150, s_range =  150,tolerance = 0.07,crsys = NULL, show.plot = FALSE)

Arguments

ppt

A 3-column matrix or list containingx - eastings,y - northing, andt - time of occurrence(in the format: ‘yyyy-mm-dd’).

start_date

the start date of the temporal pattern.The date should be in the format"yyyy-mm-dd".The temporal pattern will normallycover 1-year period.

poly

(An sf or S4 object)a polygon shapefile defining the extent of the landscape

n_origin

number of locations to serve asorigins for walkers. Default:50.

p_ratio

(an integer) The smaller of thetwo terms of a Pareto ratio.For example, a value of20implies a20:80 Pareto ratio.

gridSize

the size of square gridto use for discretizing the space.Default is:150.

s_range

A value (in metres), not less than 150,specifying the maximum range of spatialinteraction across the space. For example, for 150m,the intervals of spatial interactions are created as(0, 50],(50 - 100], and(100-150],representing the "small", "medium", and "large",spatial interaction ranges, respectively. Ifs_range is set asNULL, simulationfocusses only on generating point pattern withsimilar spatiotemporal patterns as the sampledataset.

tolerance

Pvalue to use for the extraction ofspace-time interaction in the sample data. Defaultvalue:0.07.

crsys

(string) the EPSG code of the projectionsystem of theppt coordinates. This only used ifpoly argument isNULL.See "http://spatialreference.org/" for the list ofEPSG codes for different regions of the world.As an example, the EPSG code for the British National Gridprojection system is:"EPSG:27700".

show.plot

(TRUE or FALSE) Whether to showsome displays.

Details

Returns an object of the classreal_spo,storing details of the spatiotemporalproperties of the sample data learnt.

Value

an object (list) containing specific spatialand temporal properties of a sample dataset.

References

Silverman, B.W., 2018. Density estimationfor statistics and data analysis. Routledge.

Examples

## Not run: #Goal: To learn the ST properties#of a sample data, for the purpose of#simulating the full dataset (see `psim_real`).data(camden_crimes)#subset 'theft' crimetheft <- camden_crimes[which(camden_crimes$type =="Theft"),1:3]#specify the proportion of full data to usesample_size <- 0.3set.seed(1000)dat_sample <- theft[sample(1:nrow(theft),round((sample_size * nrow(theft)), digits=0),replace=FALSE),]#plot(dat_sample$x, dat_sample$y) #previewstp_learner(dat_sample,start_date = NULL, poly = NULL, n_origin=50,p_ratio=20, gridSize = 150,s_range =  150, tolerance = 0.07,crsys = "EPSG:27700",show.plot = FALSE)## End(Not run)

A landscape walker

Description

A dynamic object capable of movingand avoiding obstacles on a landscape.

Usage

walker(n = 5, s_threshold = 250, step_length = 20,poly = NULL, restriction_feat=NULL, field = NA, coords=c(0,0),pt_itx = TRUE, show.plot = FALSE)

Arguments

n

number of eventsto be generated by a walker within atemporal bin.

s_threshold

defines the spatialperception range of a walker at a givenlocation. Default:250 (in the samelinear unitas thepoly - polygon shapefile).

step_length

the maximum step takenby a walker from one point to the next.

poly

(An sf or S4 object)a polygon shapefile defining theextent of the landscape

restriction_feat

(An S4 object) optionalshapefile containing featuresin which walkers cannot walk through.Default:NULL.

field

a number in the range of[0-1](i.e. restriction values) assignedto all features; orthe name of a numeric field to extract suchrestriction values for different classes offeature.Restriction value0 and1 indicate thelowest and the highest obstructions, respectively.Default:NULL.

coords

a vector of the form c(x, y) giving theinitial coordinates of a walker (i.e., coordinatesof origins).Default value isc(0,0) for anarbitrary square space.

pt_itx

To check whether any of thespecified initial origin coordinatesfalls outside the boundary.Default:TRUE.

show.plot

(TRUE or False) To show the time seriesplot. Default isFALSE.

Details

A walker is propelled by an in-built stochastictransition matrixand a specified set of spatial and temporalparameters. The transitionmatrix defines two states, namely; theexploratoryand aperformative states. A walker is capableof avoiding obstructions (i.e.,restriction_feat)if included. The resulting number of events may beslightly different from the valuen because of thestochastic process involved.

Value

Returns a trace of walker's path, and theresulting events.

References

Quaglietta L, Porto M (2019). SiMRiv: Individual-Based,Spatially-Explicit Simulation and Analysis of Multi-StateMovements in River Networks and Heterogeneous Landscapes_.R package version 1.0.4, <URL:https://CRAN.R-project.org/package=SiMRiv>.

Examples

#load boundary of Camdenload(file = system.file("extdata", "camden.rda",package="stppSim"))boundary = camden$boundary # get boundarywalkerpath <- walker(n = 5, s_threshold = 250, step_length = 20,poly = boundary, restriction_feat=NULL, field = NULL,coords = c(0,0), pt_itx = TRUE, show.plot = FALSE)#plot(walkerpath)

Spatiotemporal point data

Description

Example spatiotemporal point dataof a part of San Francisco City,California, US

Usage

xyt_data

Format

A matrix containing three variables


xyz data

Description

Example data with 'x', 'y',and a 'z' information

Usage

xyz

Format

A matrix containing three variables


[8]ページ先頭

©2009-2025 Movatter.jp