Intersection between spatial lines and spatial polygon to identify - spatial

I am trying to identify the spatial lines that intersect with the polygon to eliminate them
I have tried various packages to do this work but all of them are giving the same error "Error in RGEOSBinPredFunc(spgeom1, spgeom2, byid, func) :
IllegalArgumentException: point array must contain 0 or >1 elements"
Spatial lines and polygon can be downloaded from this link https://drive.google.com/drive/folders/1CWzZzZucBjhfAthApnOGgSEL7dLXlPt5
library (rgeos)
lines_onland<-gIntersection(my.lines, polygons,byid=TRUE)
"Error in RGEOSBinPredFunc(spgeom1, spgeom2, byid, func) :
IllegalArgumentException: point array must contain 0 or >1 elements"
lines_onland<-gIntersect(my.lines, polygons,byid=TRUE)
"Error in RGEOSBinPredFunc(spgeom1, spgeom2, byid, func) :
IllegalArgumentException: point array must contain 0 or >1 elements"
library(raster)
lines_onland<- raster::intersect(my.lines, polygons)
Error in RGEOSBinPredFunc(spgeom1, spgeom2, byid, func) :
IllegalArgumentException: point array must contain 0 or >1 elements
Lines crossing land

Data
library(raster)
my.lines <- shapefile("my.lines.shp")
polygons <- shapefile("polygons.shp")
First find out where the error occurs
err <- NULL
for (i in 1:length(my.lines)) {
x <- try(raster::intersect(my.lines[i,], polygons))
if (class(x) == "try-error") {
err <- c(err, i)
}
}
err
#[1] 48 59 191 294
The error occurs for four lines that consist of a single location, which makes them invalid
geom(my.lines[err,])
# object part cump x y
#[1,] 1 1 1 -28.53502 38.53658
#[2,] 2 1 2 -28.53413 38.53638
#[3,] 3 1 3 -28.54550 38.53687
#[4,] 4 1 4 -28.53340 38.53602
Remove the invalid lines and things work as they should
x <- raster::intersect(my.lines[-err,], polygons)

Related

Transferring 2d boundaries onto its 1d grid

I have a matrix defined mxn 128x128. And I have translated my 2d x,y positions onto this 1D matrix grid. My 2d coordinates accept positions using numbers 0->127 i.e. any combo in ranges {x=0,y=0}-->{x=127,y=127}. I'm implementing algorithms that take the neighboring positions of these nodes. Specifically the 8 surrounding positions of distance i (lets say i=1). So considering node={0,0}, my neighbours are generated by adding these vectors to said node:
two_d_nodes={
{0,i*1},{0,-i*1},{-i*1,0},{i*1,0},
{i*1,i*1},{i*1,-i*1},{-i*1,-i*1},{-i*1,i*1}
}
In terms of 2d though I am excluding neighbours outside the boundary. So in the above for node={0,0}, only neighours {0,1},{1,1}{1,0} are generated. Setting the boundary is basically just implementing some form of:
if x>=0 and y>=0 and x<=127 and y<=127 then...
The 1d translation of node={0,0} is node={0} and my vector additions translated to 1d are:
one_d_nodes={{128},{-128},{-1},{1},{129},{-127},{-129},{127}}
However the relationship with the 2d boundary expressions doesn't hold true here. Or at least I don't know how to translate it. In response I tried generating all the loose cases of the grid:
{0,127,16256,16383} --the 4 corner positions
node%128==0 --right-side boundary
node%128==1 --left-side boundary
node>1 and node<128 --top-side boundary
node>127*128 and node<128*128 --bottom-side boundary
Then tried implementing special cases....where I just ignored generating the specific out of bounds neighbours. That was messy, and didn't even work for some reason. Regardless I feel I am missing a much cleaner method.
So my question is: How do I translate my 2d boundaries onto my 1d grid for the purposes of only generating neighbours within the boundary?
The following is in regards to the answer below:
function newmatrix(node) --node={x=0,y=0}
local matrix={}
add(matrix,{(node.y<<8)+node.x}) --matrix= {{0},...}
--lets say [1 2 3] is a width=3; height=1 matrix,
--then the above line maps my 2d coord to a matrix of width=256, height=128
matrix.height, matrix.width = #node,#node[1] --1,1
return matrix
end
function indexmatrix(matrix, r,c)
if r > 1 and r <= matrix.height and c > 1 and c <= matrix.width then
return matrix[matrix.width * r + c]
else
return false
end
end
function getneighbors(matrix, r, c)
local two_d_nodes={
{0,1},{0,-1},{-1,0},{1,0},
{1,1},{1,-1},{-1,-1},{-1,1}
}
local neighbors = {}
for index, node in ipairs(two_d_nodes) do
table.insert(neighbors, indexmatrix(matrix, r + node[1], c + node[2]))
end
return neighbors
end
--Usage:
m={x=0,y=0}
matrix=newmatrix(m) --{{0}}
--here's where I'm stuck, cause idk what r and c are
--normally I'd grab my neighbors next....
neighbors=getneighbors(matrix)
--then I have indexmatrix for...?
--my understanding is that I am using indexmatrix to
--check if the nieghbors are within the bounds or not, is that right?
--can you illustrate how it would work for my code here, it should
--toss out anything with x less then 0 and y less than 0. Same as in OP's ex
indexmatrix(matrix) ---not sure what to do here
Attempt 2 in regards to the comment sections below:
function indexmatrix(matrix, x ,y)
if x > 1 and x <= matrix['height'] and y > 1 and y <= matrix['width'] then
return matrix[matrix['width'] * x + y]
else
return false
end
end
function getneighbors(matrix, pos_x, pos_y)
local two_d_nodes={
{0,1},{0,-1},{-1,0},{1,0},
{1,1},{1,-1},{-1,-1},{-1,1}
}
local neighbors = {}
for _, node in ipairs(two_d_nodes) do
add(neighbors, indexmatrix(matrix, pos_x + node[1], pos_y + node[2]))
end
return neighbors
end
matrix={} --128 columns/width, 128 rows/height
for k=1,128 do
add(matrix,{}) ----add() is same as table.insert()
for i=1,128 do
matrix[k][i]=i
end
end
id_matrix={{}} --{ {1...16k}}
for j=1,128*128 do
id_matrix[1][j]=j
end
id_matrix.height, id_matrix.width = 128,128
position={x=0,y=0}
neighbors = getNeighbors(matrix, position.x, position.y)
Attempt 3: A working dumbed down version of the code given. Not what I wanted at all.
function indexmatrix(x,y)
if x>=0 and y>=0 and x<127 and y<127 then
return 128 * x + y
else
return false
end
end
function getneighbors(posx,posy)
local two_d_nodes={
{0,1},{0,-1},{-1,0},{1,0},
{1,1},{1,-1},{-1,-1},{-1,1}
}
local neighbors = {}
for _, node in pairs(two_d_nodes) do
add(neighbors, indexmatrix(posx+node[1], posy + node[2]))
end
return neighbors
end
pos={x=0,y=10}
neighbors = getneighbors(pos.x,pos.y)
Edit: The equation to map 2D coordinates to 1D, y = mx + z, is a function of two variables. It is not possible for a multivariable equation to have a single solution unless a system of equations is given that gets x or z in terms of the other variable. Because x and z are independent of one another, the short answer to the question is: no
Instead, the constraints on x and z must be used to ensure integrity of the 1D coordinates.
What follows is an example of how to work with a 1D array as if it were a 2D matrix.
Let's say we have a constructor that maps a 2D table to a 1D matrix
local function newMatrix(m) -- m is 128x128 Matrix
local Matrix = {}
--logic to map m to 1D array
-- ...
return Matrix -- Matrix is m 1x16384 Array
end
The numeric indices are reserved, but we can add non-numeric keys to store information about the matrix. Let's store the number of rows and columns as height and width. We can do this in the constructor
local function newMatrix(m)
local Matrix = {}
--logic to map to 1D array
-- ...
-- Store row and column info in the matrix
Matrix.height, Matrix.width = #m, #m[1] -- Not the best way
return Matrix
end
Although the matrix is now a 1x16384 array, we can create a function that allows us to interact with the 1D array like it's still a 2D matrix. This function will get the value of a position in the matrix, but we return false/nil if the indices are out of bounds.
To be clear, the formula to map 2D coordinates to a 1D coordinate for a matrix, and can be found here:
1D position = 2D.x * Matrix-Width + 2D.y
And here's what that function could look like:
local function indexMatrix(Matrix, r,c)
if r >= 1 and r <= Matrix.height and c >= 1 and c <= Matrix.width then
return Matrix[Matrix.width * r + c] -- the above formula
else
return false -- out of bounds
end
end
We can now index our Matrix with any bounds without fear of returning an incorrect element.
Finally, we can make a function to grab the neighbors given a 2D position. In this function, we add vectors to the given 2D position to get surrounding positions, and then index the matrix using the indexMatrix function. Because indexMatrix checks if a 2D position is within the bounds of the original Matrix (before it was converted), we only get neighbors that exist.
local function getNeighbors(Matrix, r, c) -- r,c = row, column (2D position)
local two_d_nodes={
{0,1},{0,-1},{-1,0},{1,0},
{1,1},{1,-1},{-1,-1},{-1,1}
}
local neighbors = {}
for index, node in ipairs(two_d_nodes) do
-- Add each vector to the given position and get the node from the Matrix
table.insert(neighbors, indexMatrix(Matrix, r + node[1], c + node[2]))
end
return neighbors
end
You can either skip elements that return false from indexMatrix or remove them after the fact. Or anything else that sounds better to you (this code is not great, it's just meant to be an example). Wrap it in a for i ... do loop and you can go out an arbitrary distance.
I hope I haven't assumed too much and that this is helpful. Just know it's not foolproof (the # operator stops counting at the first nil, for instance)
Edit: Usage
Matrix = {
{1,2,3...128}, -- row 1
{1,2,3...128},
...
{1,2,3...128}, -- row 128
}
Array = newMatrix(Matrix) -- Convert to 1D Array ({1,2,3,...,16384})
--Array.width = 128, Array.height = 128
position = {x=0, y=0}
neighbors = getNeighbors(Array, position.x, position.y)
-- neighbors is: {{0,1}, false, false, {1,0}, {1,1}, false, false, false}

SystemVerilog constraint for mapping between two 2D arrays

There are two MxN 2D arrays:
rand bit [M-1:0] src [N-1:0];
rand bit [M-1:0] dst [N-1:0];
Both of them will be randomized separately so that they both have P number of 1'b1 in them and rest are 1'b0.
A third MxN array of integers named 'map' establishes a one to one mapping between the two arrays 'src' and 'dst'.
rand int [M-1:0] map [N-1:0];
Need a constraint for 'map' such that after randomization, for each element of src[i][j] where src[i][j] == 1'b1, map[i][j] == M*k+l when dst[k][l] == 1. The k and l must be unique for each non-zero element of map.
To give an example:
Let M = 3 and N = 2.
Let src be
[1 0 1
0 1 0]
Let dst be
[0 1 1
1 0 0]
Then one possible randomization of 'map' will be:
[3 0 1
0 2 0]
In the above map:
3 indicates pointing from src[0,0] to dst[1,0] (3 = 1*M+0)
1 indicates pointing from src[0,2] to dst[0,1] (1 = 0*M+1)
2 indicates pointing from src[1,1] to dst[0,2] (2 = 0*M+2)
This is very difficult to express as a SystemVerilog constraint because
there is no way to conditionally select elements of an array to be unique
You cannot have random variables as part of index expression to an array element.
Since you are randomizing src and dst separately, it might be easier to compute the pointers and then randomly choose the pointers to fill in the map.
module top;
parameter M=3,N=4,P=4;
bit [M-1:0] src [N];
bit [M-1:0] dst [N];
int map [N][M];
int pointers[$];
initial begin
assert( randomize(src) with {src.sum() with ($countones(item)) == P;} );
assert( randomize(dst) with {dst.sum() with ($countones(item)) == P;} );
foreach(dst[K,L]) if (dst[K][L]) pointers.push_back(K*M+L);
pointers.shuffle();
foreach(map[I,J]) map[I][J] = pointers.pop_back();
$displayb("%p\n%p",src,dst);
$display("%p",map);
end
endmodule

st_buffer multipoint with different distance

I have a sfc_multipoint object and want to use st_buffer but with different distances for every single point in the multipoint object.
Is that possible?
The multipoint object are coordinates.
table = data
Every coordinate point (in the table in "lon" and "lat") should have a buffer with a different size. This buffer size is containt in the table in row "dist".
The table is called data.
This is my code:
library(sf)
coords <- matrix(c(data$lon,data$lat), ncol = 2)
tt <- st_multipoint(coords)
sfc <- st_sfc(tt, crs = 4326)
dt <- st_sf(data.frame(geom = sfc))
web <- st_transform(dt, crs = 3857)
geom <- st_geometry(web)
buf <- st_buffer(geom, dist = data$dist)
But it uses just the first dist of (0.100).
This is the result. Just really small buffers.
small buffer
For visualization see this picture. It´s just an example to show that the buffer should get bigger. example result
I think that he problem here is in how you are "creating" the points dataset.
Replicating your code with dummy data, doing this:
library(sf)
data <- data.frame(lat = c(0,1,2,3), lon = c(0,1,2,3), dist = c(0.1,0.2,0.3, 0.4))
coords <- matrix(c(data$lon,data$lat), ncol = 2)
tt <- st_multipoint(coords)
does not give you multiple points, but a single MULTIPOINT feature:
tt
#> MULTIPOINT (0 0, 1 1, 2 2, 3 3)
Therefore, only a single buffer distance can be "passed" to it and you get:
plot(sf::st_buffer(tt, data$dist))
To solve the problem, you need probably to build the point dataset differently. For example, using:
tt <- st_as_sf(data, coords = c("lon", "lat"))
gives you:
tt
#> Simple feature collection with 4 features and 1 field
#> geometry type: POINT
#> dimension: XY
#> bbox: xmin: 0 ymin: 0 xmax: 3 ymax: 3
#> epsg (SRID): NA
#> proj4string: NA
#> dist geometry
#> 1 0.1 POINT (0 0)
#> 2 0.2 POINT (1 1)
#> 3 0.3 POINT (2 2)
#> 4 0.4 POINT (3 3)
You see that tt is now a simple feature collection made of 4 points, on which buffering with multiple distances will indeed work:
plot(sf::st_buffer(tt, data$dist))
HTH!

TikZ: plotting data file with missing values

I have this data:
data2 is missing the third point. So I thought, I'd define two different x columns and assign data2 to x2.
Problem: the third point of data1 goes up to 3 in the compiled graphic. If I have different and more values, points start to go anywhere, but not where they belong.
That is the code I've used:
\addplot[only marks, mark = diamond, color = orange, mark size = 3pt]
table[x=x1, y=data1]{example.dat};
\addlegendentry{data1};
\addplot[only marks, mark = square, color = gray, mark size = 3pt]
table[x=x2, y=data2]{example.dat};
\addlegendentry{data2};
\addplot[only marks, mark = o, color = blue, mark size = 3pt]
table[x=x1, y=data3]{example.dat};
\addlegendentry{data3};
And this is the graph I get:
Thanks a lot!
Btw. in the real data one data set is missing a x/y value in the middle of the data. I hope that doesn't matter compared to my example.
pgfplots is interpreting 2 tabs as a single separator. Thus, it sees the data file as:
x1 x2 data1 data2 data3
0 0 1 2 3
1 1 1 2 3
2 1 3
Solution 1. You can replace empty cells with NaN. pgfplots will interpret this correctly:
x1 x2 data1 data2 data3
0 0 1 2 3
1 1 1 2 3
2 nan 1 nan 3
Solution 2. Use another type of separator (e.g., semicolons or commas):
\begin{filecontents*}{example.csv}
x1;x2;data1;data2;data3
0;0;1;2;3
1;1;1;2;3
2;;1;;3
\end{filecontents*}
\pgfplotstableread[col sep = semicolon]{example.csv}\mydata
\begin{document}
...
Here I've included the data file in the TeX file, but it should also work with a separate data file.

Simple Matrix multiplication in opencv fails

I do the following
Mat xOld,xNew;
for(uint i=0;i<inliers.size();i++){
if(inliers[i]){
double xOld_arr[3]={kpOld[i].pt.x,kpOld[i].pt.y,1};
double xNew_arr[3]={kpNew[i].pt.x,kpNew[i].pt.y,1};
Mat xo(1,3,CV_64FC1,xOld_arr),xn(1,3,CV_64FC1,xNew_arr);
xNew.push_back(xn);
xOld.push_back(xo);
}
}
xNew=xNew.t();
cout<<F.size()<<" "<<xNew.size();
Mat t=xNew*F;
Output is
[3 x 3] [24 x 3]OpenCV Error: Assertion failed (a_size.width == len) in gemm, file /home/flex/test/opencv/modules/core/src/matmul.cpp, line 1537
terminate called after throwing an instance of 'cv::Exception'
what(): /home/flex/test/opencv/modules/core/src/matmul.cpp:1537: error: (-215) a_size.width == len in function gemm
What am I missing? when I multiply matrix shouldn't it be correct. Cause xNew has same colums and F same Rows?
what type is F?
so F is 3 rows, 3 cols. xNew (after transpose) is 3 rows, 24 cols. Now you try to multiply (matrix notation: rows x columns) 3x24 * 3x3 which is not defined. Matrix multiplication is size: N x M * M x O => NxO matrix. So you should be able to multiply both matrices if you don't transpose, but I can't tell you whether that is the multiplication you want.
Maybe the confusion is in this line: xn(1,3,CV_64FC1,xNew_arr) here you create a matrix with 1 row and 3 columns and later add this row to xNew.

Resources