该代码旨在分析沿每条折线的点位置。
它在 ttl_ln
小时有效。
但是当整个折线要素加载完毕(超过 300,000 条折线)时,Rgui 会自动关闭。
我通过添加 bool
test_tag
进行了一些测试。当 test_tag
为 true
时,Rgui 关闭发生,当 false
时,则可以仅使用 subset()
并在循环中重复矩阵创建来处理 300,000。所以可能不是因为使用了 subset()
或 matrix()
。
使用 Rcpp 中定义的 scale_to_grid()
时会关闭。
shp_file = 'some_ply.shp'
shp_1 = sf::st_read(shp_file)
shp_2 = sf::st_coordinates(shp_1)
ttl_ln = nrow(shp_1)
for (ln in c(1:ttl_ln)){
shp_3 = subset(shp_2, shp_2[,3] == ln)
# field 1 is coordinate X
# field 2 is coordinate Y
# field 3 is Line ID created by sf package
em_mat = matrix(0, nrow = 200, ncol=200)
if(test_tag){
# manipulations on points are followed
# a groupe of functions defined in a Rcpp file
# are used. They can be successfully compiled.
new_mat = scale_to_grid(shp_3, em_mat, t1, t2, t3, t4)
# t1, t2, t3, t4 are numbers with double type in Rcpp file.
}
}
以下是 Rcpp 中的代码。
// [[Rcpp::export]]
NumericMatrix scale_to_grid(NumericMatrix shp,
NumericMatrix mat,
double o_x, double o_y,
double u_x, double u_y){
// mat : the matrix of grid
int ptr;
int nbr = shp.nrow();
int ind_x, ind_y;
double slope, new_x, new_y;
// go through each point, expect the last one (i.e. ptr < nbr -1)
for(ptr=0;ptr<nbr-1;ptr++){
ind_x = trunc((shp(ptr,0)-o_x)/u_x);
ind_y = trunc((shp(ptr,1)-o_y)/u_y);
mat(ind_x, ind_y)++;
if(abs(shp(ptr+1,0) - shp(ptr,0)) > u_x){
// the difference in x value is greater than the grid unit width
// there must be grid to fill with value '1'
slope = (shp(ptr+1,1) - shp(ptr,1)) / (shp(ptr+1,0) - shp(ptr,0));
// initialise
new_x = shp(ptr,0);
new_y = shp(ptr,1);
while(abs(new_x - shp(ptr+1,0)) > u_x){
if(shp(ptr+1,0) - shp(ptr,0) > 0){
new_x = new_x + u_x;
new_y = new_y + u_x * slope;
}else{
new_x = new_x - u_x;
new_y = new_y - u_x * slope;
}
ind_x = trunc((new_x-o_x)/u_x);
ind_y = trunc((new_y-o_y)/u_y);
mat(ind_x, ind_y)++;
}
}
}
return mat;}