% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/R-grid.R
\name{detect_grid_type}
\alias{detect_grid_type}
\title{Detect the grid type (square vs hexagonal) from spatial coordinates}
\usage{
detect_grid_type(
  df,
  coords = c("x", "y"),
  k = 12,
  tolerance = 0.1,
  verbose = TRUE
)
}
\arguments{
\item{df}{A data.frame containing spatial coordinates.}

\item{coords}{Character vector of length 2 giving the coordinate column
names.
  Default is `c("x","y")`.}

\item{k}{Integer. Number of neighbors to consider (internally uses `k + 1`
to include the point itself, then removes it). Default is 12.}

\item{tolerance}{Numeric. Tolerance for matching the characteristic ratio to
\eqn{\sqrt{2}} or \eqn{\sqrt{3}}. Default is 0.1.}

\item{verbose}{Logical. If `TRUE`, prints diagnostic messages. Default is
`TRUE`.}
}
\value{
A list with:
\describe{
  \item{grid_type}{One of `"square"`, `"hexagonal"`, or `"unknown"`.}
  \item{step}{Estimated grid step size (median nearest-neighbor distance).}
\item{median_ratio}{Median normalized distance ratio in the (1.2, 2.0)
range.}
}
}
\description{
This function inspects k-nearest-neighbor distances in a 2D coordinate set to
infer whether the points lie on a **square** or **hexagonal** lattice.
}
\details{
The method:
\enumerate{
  \item Computes the nearest-neighbor distance for each point and uses the
  median of those distances as an estimate of the grid step size.
  \item Normalizes all neighbor distances by this step size.
  \item Looks for a characteristic secondary distance peak:
  \itemize{
    \item square grid: ratio \eqn{\approx \sqrt{2}}
    \item hexagonal grid: ratio \eqn{\approx \sqrt{3}}
  }
}


The grid step size is estimated as the median of the per-point
nearest-neighbor
distance. The "median distance ratio" is computed from normalized neighbor
distances restricted to the interval (1.2, 2.0), which tends to capture the
second-shell distances on regular grids.
}
\examples{
# --- Example 1: square grid ---
sq <- expand.grid(x = 0:9, y = 0:9)
res_sq <- detect_grid_type(sq, coords = c("x","y"), k = 12, tolerance = 0.1)
res_sq$grid_type

# --- Example 2: hexagonal grid (pointy-top axial-like layout) ---
nx <- 10; ny <- 10
hex <- expand.grid(i = 0:(nx-1), j = 0:(ny-1))
hex$x <- hex$i + 0.5 * (hex$j \%\% 2)
hex$y <- (sqrt(3)/2) * hex$j
hex <- hex[, c("x","y")]
res_hex <- detect_grid_type(hex, coords = c("x","y"), k = 12, tolerance =
0.1)
res_hex$grid_type

}
