labeling/ coloring elements/segments of a linnet object - spatstat

I have 3 related questions for plots in spatstat:
How do I label the segment of a linnet. for example just the id of the element
How do I label co-variate attached to segment of linnet on a plot
How to control width of an segment of linnet in a plot based on: a covariate or for example I want the thickness of the segment proportional to number of points realized on that segment from a point process on a network. So if a process generates 10 points on a line segment and 5 points on second segment, I would like to plot first segment twice wider than second segment.
I found examples in the book - Spatial Point Patterns - but they indicate use of image or kernel density to control the width of a segment. I am using linfun for a inhomogenous process and I did not find a method to color or control line width in my plot or to label the plot.
An example of small square:
library(spatstat)
v<-ppp(x=c(50,100,100,50), y=c(50,50,100,100),c(0,150), c(0,150)) #vertices
edg<-matrix(c(1,2,3,4,2,3,4,1), ncol=2) #edges
L<-linnet(v, edges=edg) #create a linnet
z<-c(11,22,33,44) # create covariate
Zfun <- linfun(function(x,y,seg,tp) { seg }, L)
plot(Zfun)
# I added some marks
marks(x) <- runif(npoints(x), 3, 4)
Thank you

You can do everything by creating a suitable function of class linfun.
As an example, take the network L <- simplenet.
For question 1:
f <- linfun(function(x,y,seg,tp) { seg }, L)
plot(f)
The function f returns the segment ID number of the segment containing the specified point. This number runs from 1 to nsegments(L).
For question 2, suppose you have a vector Z giving the value of a covariate for each segment of the network (assuming the covariate value is constant on each segment). I'll take the example Z <- runif(nsegments(L)). Then
g <- linfun(function(x,y,seg,tp) { Z[seg] }, L)
plot(g)
For question 3,
plot(g, style="width")
See help(plot.linfun) and help(plot.linim) (basically plot.linfun converts the function to a pixel image, and then calls plot.linim).

Related

Custom smoothing kernel

I would like to use Smooth.ppp in spatstat to calculate a sort of "moving average" according to a specific function. The specific distance-dependent weights I would like to use are given by a function wt; for simplicity
wt=function(x,y) exp(-1e5*(x-y)^2)
In the extreme case where wt=kernel, I'd expect no smoothing (ie input marks = smoothed estimates). I'm wondering what I am mis-understanding here about the kernel and how it is applied?
remotes::install_github("spatstat/spatstat.core")
n=4; PPP=ppp(rep(1:n,each=n),rep(1:n,n), c(1,n),c(1,n), marks=1:n^2);
smo=Smooth.ppp(PPP,cutoff=2,kernel=wt,at="points")
rbind(marks(PPP),smo)
(I'm using the latest spatstat build to allow estimates at points using a custom kernel)
This example may have been misinterpreted.
The kernel should be a function(x, y) in the R language which gives the value, at a spatial location (x,y), of the kernel centred at the origin (0,0). Generally the kernel takes its largest values when (x,y) is close to (0,0), and drops to zero when (x,y) is far from (0,0).
The function wt defined in your example has values close to 1 along the diagonal line x = y, and drops to zero rapidly away from the diagonal.
That is unusual. It means that a data point at location (a,b) will be 'smoothed' along the infinite line through the data point with unit slope, with equation y = x + b-a, rather than being smoothed over a region close to (a,b) as it normally would.
The example point pattern PPP consists of points along the diagonal y=x.
The smoothed value at a data point is the weighted average of the mark values at all data points, with weights proportional to the kernel value. In your example, the kernel value for each pair of data points, wt(x1-x2, y1-y2), is equal to 1 because all the data and query points lie on the same line with slope 1.
The kernel weights are all equal in this example, so the smoothed values should all be equal to the average mark value, if leaveoneout=FALSE, and if leaveoneout=TRUE then the smoothed value at data point i is the average of the mark values at the data points excluding point i.

using Geopandas, How to randomly select in each polygon 5 Points by sampling method

I want to select 5 Points in each polygon based on random sampling method. And required 5 points co-ordinates(Lat,Long) in each polygon for identify which crop is grawn.
Any ideas for do this using geopandas?
Many thanks.
My suggestion involves sampling random x and y coordinates within the shape's bounding box and then checking whether the sampled point is actually within the shape. If the sampled point is within the shape then return it, otherwise repeat until a point within the shape is found. For sampling, we can use the uniform distribution, such that all points in the shape have the same probability of being sampled. Here is the function:
from shapely.geometry import Point
def random_point_in_shp(shp):
within = False
while not within:
x = np.random.uniform(shp.bounds[0], shp.bounds[2])
y = np.random.uniform(shp.bounds[1], shp.bounds[3])
within = shp.contains(Point(x, y))
return Point(x,y)
and here's an example how to apply this function to an example GeoDataFrame called geo_df to get 5 random points for each entry:
for num in range(5):
geo_df['Point{}'.format(num)] = geo_df['geometry'].apply(random_point_in_shp)
There might be more efficient ways to do this, but depending on your application the algorithm could be sufficiently fast. With my test file, which contains ~2300 entries, generating five random points for each entry took around 15 seconds on my machine.

How to read output of SmileBASIC SPCHK?

I'm trying to get the XY coordinates of a moving sprite in SmileBASIC, and I can't figure it out. I have the single variable returned from SPCHK, but when I print it, I get a single number '4' constantly as the sprite moves. How do I get each bit?
From the documentation:
Return Values for SPCHK
|b00| XY-coordinates (1), #CHKXY
|b01| Z-coordinates (2), #CHKZ
|b02| UV-coordinates (4), #CHKUV
|b03| Definition number (8), #CHKI
|b04| Rotation (16), #CHKR
|b05| Magnification XY (32), #CHKS
|b06| Display color (64), #CHKC
|b07| Variable (128), #CHKV
For each bit, a target is assigned (If 0 is assigned for all bits, animation is being stopped)
SPCHK only tells you which properties are currently being animated, not their values.
To get the actual position, you can use SPOFS id OUT x,y
Example:
SPSET 0,17
SPANIM 0,"XY",-10,100,100
WAIT 5
SPOFS 0 OUT X,Y
?X,Y 'should be 50,50

How to plot contour maps and display average of the mark(associated with x,y) for each contour level

I have a contour map in spatstat generated from the intensity function of a point pattern X (like "location of the trees"). Each x,y coordinates in this point pattern is marked with a corresponding third vector (like "diameter of the tree").
-->cf image (of course the vertical lines representing the tree can be omitted)
I would like to display the average of the mark (diameter) in each level of the contour with different colors. Suggestions?
Thanks!
You are effectively asking for a kind of nonparametric regression.
Here is a quick-and-dirty calculation using the function rhohat and demonstrated on the longleaf dataset.
First calculate the intensity estimate: Z <- density(longleaf) yielding an image Z. Next treat Z as a covariate in calls to the rhohat command:
f <- rhohat(unmark(longleaf), Z)
and
g <- rhohat(unmark(longleaf), Z, weights=marks(longleaf)).
Now take the ratio, h <- eval.fv(g/f) and plot it, plot(h). This shows the estimated average tree diameter as a function of the forest density. To apply this function h to the original contours of Z you would first convert h to a true function by H <- as.function(h) then evaluate hZ <- eval.im(H(Z)) and finally plot(hZ).

How to set data values on a vtkStructuredGrid

I'm trying to fill in a structured grid with an analytical field, but despite reading the vtk docs, I haven't found out how to actually set scalar values at the grid points or the set the spacing/origin info of the grid. Starting from the code below, how do I
associate spatial information with the grid (ie cell 0,0,0 is at coordinates 0,0,0, the spacing is dx in every direction)
associate scalar values with each grid point. To start, I just need one, but eventually I'd like to store 3 pieces of data at each point (not a vector, 3 distinct scalars).
grid = vtk.vtkStructuredGrid()
numPoints = int((maxGrid - minGrid)/dx)
grid.SetDimensions(numPoints, numPoints, numPoints)
In VTK there are 3 types of "structured" grids, vtkImageData (vtkUniformGrid derives from this), vtkRectilinearGrid, and vtkStructuredGrid. They are all structured in the sense that the topology is set. vtkImageData has constant spacing between points and is axis aligned, vtkRectilinearGrid is axis aligned but can vary the spacing in each axis direction, and vtkStructuredGrid has arbitrarily located points (cells may not be valid though).
For what you want to do you should do:
from vtk import *
dx = 2.0
grid = vtkImageData()
grid.SetOrigin(0, 0, 0) # default values
grid.SetSpacing(dx, dx, dx)
grid.SetDimensions(5, 8, 10) # number of points in each direction
# print grid.GetNumberOfPoints()
# print grid.GetNumberOfCells()
array = vtkDoubleArray()
array.SetNumberOfComponents(1) # this is 3 for a vector
array.SetNumberOfTuples(grid.GetNumberOfPoints())
for i in range(grid.GetNumberOfPoints()):
array.SetValue(i, 1)
grid.GetPointData().AddArray(array)
# print grid.GetPointData().GetNumberOfArrays()
array.SetName("unit array")

Resources