识别非自相交多边形

问题描述 投票:0回答:1

我有一个闪亮的应用程序,用户可以在其中定义多边形,但我想在多边形自相交时发出警告。

我做了下面的MWE。

polygon=data.frame(x_coord=c(1,2.5,7.5,6.75,4), y_coord=c(5,7,6.5,0.75,0.25))
polygon=data.frame(x_coord=c(1.5,2.5,7.5,5.5,4.5), y_coord=c(3,7,6.5,3,7.5))
not_intersect <- TRUE #how to define if the polygon self-intersects?
if (not_intersect==TRUE){
  P <- ggplot2::ggplot(polygon, ggplot2::aes(x=x_coord, y=y_coord)) +
       ggplot2::geom_polygon(fill="#99CCFF", color="red", alpha=0.25, linewidth=1, linetype=2) +
       ggplot2::geom_point(color="red", size=1.5) +
       ggplot2::scale_x_continuous(limits = c(0, 10), breaks = seq(0,10)) +
       ggplot2::scale_y_continuous(limits = c(0, 10), breaks = seq(0,10)) +
       ggplot2::theme_light()
  grDevices::pdf(file="test.pdf", height=6, width=6)
  print(P)
  grDevices::dev.off()
}

本质上,如果多边形像第一个多边形,我想绘制它:

但是如果它像第二个一样,我不想绘制它:

知道如何识别这两种类型的多边形吗? 谢谢!

r ggplot2 polygon
1个回答
0
投票

您可以使用

sf::st_is_valid()
检查一般有效性。我们可以设置
reason = TRUE
参数来特别检查自相交:

# The same polygons as in your question
polygon1 <- data.frame(x_coord = c(1, 2.5, 7.5, 6.75, 4), y_coord = c(5, 7, 6.5, 0.75, 0.25))
polygon2 <- data.frame(x_coord = c(1.5, 2.5, 7.5, 5.5, 4.5), y_coord = c(3, 7, 6.5, 3, 7.5))

library(sf)

not_intersect <- function(p) {
    p_is_valid <- list(as.matrix(p)) |>
        st_multilinestring() |>
        st_cast("POLYGON") |>
        st_is_valid(reason = TRUE)
    !any(startsWith(p_is_valid, "Self-intersection"))
}

not_intersect(polygon1) # TRUE
not_intersect(polygon2) # FALSE

顺便说一句,当函数名称包含否定时,我发现有点令人困惑。我会称之为

has_self_intersection()
。除了删除最后一行
!
之前的
any()
之外,定义将完全相同。那么你的代码将是,

if (!has_self_intersection(polygon)){
    # draw the plot
}

Steve McDonnel 的流行代码完整建议您列出“是”、“有”、“应该”或“可以”,但对于变量名称。

请参阅 Software Engineering Stack Exchange 上的如何命名返回布尔值的函数

© www.soinside.com 2019 - 2024. All rights reserved.