Changelog
Source:NEWS.md
spatialkit 3.0.0
This release follows 2.0.0, published on CRAN on 2026-09-11. It adds a choice of the number of cells from the data (resolution_profile(), select_resolution()), pooled cell values with intervals as the default of summarize_by_cell(), density-weighted seeds as the default partition, and a GWR the package solves itself, without GWmodel. Read Breaking changes before upgrading a running analysis.
Breaking changes
Defaults that change results
summarize_by_cell()adds pooled values by default (estimate = "pooled"). Beside each mean it returns..pooled_*,..pooled_w_*and..pooled_target_*for every numeric response and predictor, and the attributes"pooled"and"intervals". Every column 2.0.0 returned is unchanged. The default call can now raise the warnings of the pooled values (spatialkit_pool_unavailable,spatialkit_pool_degenerate,spatialkit_pool_few_cells,spatialkit_no_structureand others), and small or unstructured layers raise several.estimate = "mean"leaves the pooled columns and their attributes out.get_voronoi_seeds(method = "kmeans")andvoronoi_seeds_kmeans()build density-weighted seeds by default (partition = "density"). Each point is weighted by its local density, so cells are small where observations are dense and hold about the same number of observations each once there are more cells than dense places. The seeds are the best of 3 k-means++ starts (kmeans_nstart = NULL,nstart = NULL). Every default call returns other seeds and other cells.partition = "kmeans"restoresstats::kmeans()from 10 random starts; on gridded locations its seeds can still differ, because the coordinates are now centred and scaled before clustering.voronoi_seeds_random()draws from the session’s random stream by default (set_seed = NULL). The 2.0.0 default, 456, returned the same seeding on every call, even inside a loop overset.seed().set_seed = 456restores the 2.0.0 seeds.area_of_applicability()weights the predictors by the model’s variable importance by default (weights = "auto"). It usespmax(importance, 0)when the model carries a finite importance for every predictor and has out-of-bag skill, and equal weights otherwise;params$weights_sourcesays which.weights = NULLrestores the equal weights of 2.0.0.area_of_applicability()measures location for models that predict from it. A GWR fit, a Bayesian GP fit and a random forest fitted withinclude_coords = TRUEget a location index (DI_location), and a point is inside only when it is inside on both indices. The location index refuses atrain_sfin a geographic CRS; project it or passcoords = "no". For a forest, a row outside on location isFALSEwhere a missing predictor made itNA.coords = "no"restores the 2.0.0 result for a GWR or Bayesian fit; for a forest it leaves the coordinates out of both indices.fit_rf_model()splits an unordered factor or character predictor withrespect.unordered.factors = "order". ranger’s default,"ignore", splits on the order in which the levels are stored, so forests with such a predictor change.$info$respect_unordered_factorsrecords the setting andprint()shows it. Passingrespect.unordered.factors = "ignore"through...restores the 2.0.0 forest.fit_bayesian_spatial_model()samples withadapt_delta = 0.99by default, up from 0.9.cv_bayes(),compare_models_cv()and any other call that leavescontrolunset do the same. At 0.9 ordinary layers left a few divergent transitions, and a single one setsconvergence_oktoFALSE. Sampling takes longer, and a fit at a given seed draws different values.control = list(adapt_delta = 0.9)restores the 2.0.0 setting.fit_bayesian_spatial_model(standardize_predictors = TRUE)scales its automatic slope prior to the response. The prior isnormal(0, 2.5 * sd(y))under an identity link andnormal(0, 2.5 * sd(log(y)))for the lognormal families; other links keepnormal(0, 5), the 2.0.0 prior for every family. On a response in dollars the fixed prior shrank a real slope to almost nothing.$info$b_priorrecords the prior used. Passingprior = brms::set_prior("normal(0, 5)", class = "b")restores the 2.0.0 prior.select_features_forward()accepts a candidate by the rulerule = "se". Its pooled gain must exceedtoland the mean of its per-fold gains must exceedse_mult(default 1) standard errors of that mean. With the 2.0.0 default,tol = 0, any gain was accepted, so the selections change.rule = "tol"restores the 2.0.0 test.determine_optimal_levels()returnsNAwhere its WSS curve has no elbow (on_no_elbow = "na"). The count it returned there was where the chord rule lands on a curve with no bend, about the square root ofmax_levelswhatever the points. A layer of one or two points, or of one location, also givesNA, where it gave 1. A warning of classspatialkit_no_elbowcarries the count.on_no_elbow = "warn"returns the count with that warning.estimate_sac_range()bins the variogram at adaptive lags (lags = "adaptive"). The first bin ends where the closestmax(50, n / 4)pairs lie and the rest widen geometrically to the cutoff. The 2.0.0 fifteen equal bins hid structure shorter than the first bin. Ranges, nuggets and the block sizes ofmake_folds(auto_range = TRUE)change.lags = "equal"restores the 2.0.0 bins.estimate_sac_range()tests for spatial structure before it returns a range (structure_alpha = 0.05). The test is Moran’s I of the modelled variable on its 2, 4, 8 and 16 nearest neighbours, Bonferroni-adjusted. When it finds none, the result isNAwith therejected_reason“no spatial structure detected at the nearest-neighbour scale”.structure_alpha = 1switches the test off.The GWR functions choose the default bandwidth by a search of their own. With
bandwidth = NULL,fit_gwr_model(),gwr_model_selection()andcv_gwr()score 16 log-spaced bandwidths and refine the best, whereGWmodel::bw.gwr()’s golden-section search returned a near-global bandwidth when AICc had two minima. When rows share a location, the search minimises the leave-one-location-out sum of squares, not AICc, with a warning of classspatialkit_gwr_repeated_locations.info$bandwidth_searchkeeps the scored curve. Supplyingbandwidthfixes it; no argument reruns the 2.0.0 search.plot_tessellation_map(labels = TRUE)reads the first ID column the layer has (label_col = NULL). The order ispoly_id,polygon_id,id,cell_idandgrid_id, the order in whichassign_features_to_polygons()reads a polygon layer’s IDs. The 2.0.0 default readgrid_idalone, which no layer the package builds carries, so it drew no labels.label_col = "grid_id"restores it.
Across the pipeline
- FNN moves from Suggests to Imports. The nearest-neighbour searches use it, the one behind the density partition among them. The package’s exact searches remain for a session in which FNN cannot be loaded; they give the same results in a time that grows with the square of the number of locations.
Measure spatial autocorrelation
estimate_sac_range()fits its variogram model without iteration. For each trial range the nugget and partial sill are solved exactly under gstat’s criterion, so the same layer gives the same verdict, range and nugget in any unit and row order. Every range and nugget moves a little, only the exponential family is fitted, and therejected_reason“variogram model did not converge” no longer occurs. No argument restores the 2.0.0 fit.estimate_sac_range()never returns the largest directional range in place of an all-pairs fit. Where the all-pairs fit identifies no range, or its range runs past the largest lag fitted, the result isNA. The directional ranges are still attached, andanisotropy_usedis alwaysFALSE. No argument restores the 2.0.0 result.estimate_sac_range()needs 30 distinct locations as well as 30 rows. Rows that share a location are one place to the variogram and to the test for structure. A layer of 30 or more rows at fewer distinct locations gets the unclassedNAwhoserejected_reasongives the count. Sosummarize_by_cell(deff = "variogram")falls back to Kish andmake_folds(auto_range = TRUE)builds geometric blocks on such layers. No argument restores the 2.0.0 result.estimate_sac_range()words onerejected_reasondifferently. Where fewer than three lag bins hold point pairs it reads “no variogram model could be fitted: fewer than three lag bins hold point pairs”, where 2.0.0 read “no variogram model could be fitted (singular fits)”. Both start “no variogram model could be fitted”, which a script can compare instead.
Choose a resolution
determine_optimal_levels()fits each count as the best of 25 k-means++ restarts, where 2.0.0 ranstats::kmeans(nstart = 5). Its WSS curve rose at one or two steps on clustered layouts, and the elbow rule could select such a bump. The elbow is now read on log-log axes and counts only where the curve sags clearly below a straight line. Counts can differ from 2.0.0’s, most on clustered layers. No argument restores the 2.0.0 sweep.determine_optimal_levels()keeps the criterion it is given. Supplying bothresponse_varandpredictor_varsswitched the defaultcriterion = "geometric"to"combined", also when"geometric"was named. Such a call now returns what the call without the two variables returns. Namingcriterion = "combined"takes the path of the switch; no argument restores its 2.0.0 ranking.determine_optimal_levels(criterion = "combined")ranks the counts around the elbow by the log-log sag of the WSS curve alone. Moran’s z of the cell means stays inattr(, "diagnostics")but no longer ranks: its |z| is near 0 at the coarsest counts it scores whatever the response, so it put the lowest count first. With an elbow the elbow comes first; with none the order is that of"geometric". No argument restores the 2.0.0 ranking.determine_optimal_levels(criterion = "morans_i")raises a warning of classspatialkit_diagnostic_ranking. It still ranks by Moran’s z of the cell means, which grows as cells get finer than the autocorrelation range and so favours fine counts whatever the data. The warning namesresolution_profile()andselect_resolution()as the alternative. The counts are unchanged.
Build the cells
build_tessellation(method = "voronoi")on seeds builds cells over the data the seeds stand for. Without a boundary, 2.0.0 clipped the cells to the seeds’ own hull, and the assignment dropped the observations outside it. The seeding functions now attach the boundary they drew in, or the hull of the points they clustered, asattr(, "cover"), and the cells are built over it. Passingboundarysets the extent; no argument restores the clip to the seeds’ hull.get_voronoi_seeds()stops on a number of starts that is not whole, such askmeans_nstart = 2.5, under the default density partition, with “kmeans_nstartmust be NULL or a single positive whole number of starts”. Withpartition = "kmeans"the call returns as in 2.0.0.
Assign and summarise
assign_features_to_polygons()stops on a duplicated or missing value in the polygon ID column. In 2.0.0 nine polygons keyed by a zone attribute calledid, which repeats, came back as three. When rows that share an ID are parts of one unit, merge them first, for example withdplyr::summarise(dplyr::group_by(polygons_sf, <ID column>)). No argument restores the 2.0.0 result.summarize_by_cell(deff = "variogram")falls back to"kish", not to the uncorrected standard error, when no usable variogram exists. A warning of classspatialkit_deff_fallbackgives the reason, and a new columndeff_methodnames the correction each row carries. A variogram refused for want of spatial structure gives a design effect of 1, with a warning of classspatialkit_deff_no_structurenaming the predictor columns.deff = 1gives the uncorrected standard errors.summarize_by_cell(deff = "kish")estimates one ICC per predictor. 2.0.0 pooled one ICC over every predictor listed, so listing a second predictor changed the first one’s standard error.attr(, "icc")$predandattr(, "deff_applied")$icc_predare vectors named by predictor. No argument restores the pooled ICC.summarize_by_cell(deff = "kish")returnsNAstandard errors for a column whose ICC cannot be estimated. That is a column with values in one cell only, or fewer than two cells holding two or more of its values. 2.0.0 returned the uncorrected standard errors under the corrected label...neff_*,..ci_*andcell_weightareNAin those cells too, and a warning of classspatialkit_icc_unavailablenames the columns.deff = 1gives the uncorrected standard errors.
Fit a model
fit_bayesian_spatial_model()sets$info$convergence_okby stricter checks. It isFALSEon any divergent transition, an R-hat above 1.05, an R-hat above 1.01 with fewer than 100 effective draws per chain, a bulk or tail effective sample size under 100 per chain, or an E-BFMI under 0.3. Short runs that passed in 2.0.0 can fail. One warning of classspatialkit_convergencenames each failed check and its remedy. No argument restores the 2.0.0 checks.fit_gwr_model()solves the local regressions itself, and GWmodel is no longer needed to fit, predict, cross-validate or select (spstill is). The solve is pivoted QR on predictors centred in each window. A coefficient a rank-deficient window cannot estimate isNA, with a warning of classspatialkit_gwr_rank_deficient, where 2.0.0 stopped the fit. On windows of full rank the results equalGWmodel::gwr.basic()’s to rounding.fit$engineis a list in GWmodel’s layout, not an object of classgwrm. No argument restores the 2.0.0 engine.new_spatial_fit()stops on a fit its methods cannot use. The error names the argument:data_sfmust be an sf object with a geometry column,response_varone attribute column,predictor_varsattribute columns other than the response, andformulamust hold the response on its left and use the columnspredictor_varsnames on its right. Afit_fnthat passedst_drop_geometry(train_sf)must passtrain_sf; a column derived insidefit_fnmust be added totrain_sfor left out ofpredictor_vars. No argument restores the 2.0.0 checks.
Check a fit in sample
-
The metrics frames gain
n_MAPEandn_SMAPE.model_metrics(),summary(),evaluate_insample(),compare_models()and theoverallandfold_metricsof thecv_*()functions andcompare_models_cv()carry the rows each percentage error was averaged over. The columns followAdj_R2, so code that addresses the metric columns by position is unaffected; code that pins the exact column set needs the two names.cv_bayes()’sfold_metricsandcompare_models()gainconvergence_okin the same way. No argument removes the new columns.
Cross-validate and compare
-
compare_models_cv()stops when it cannot build its shared fold set. In 2.0.0 it logged a line and fell back to each backend’s default blocks, so the comparison ran on folds the caller had not asked for. The error gives the reason. No argument restores the fallback.
Choose predictors
-
select_features_forward()gives every learner a baseline to beat. A forest or a GWR in 2.0.0 had none, so at least one variable was always selected. The baseline is now the learner’s own null model (a GWR fits one), the newnull_fn, or the mean of each training fold, and the selection can be empty. No argument restores the 2.0.0 behaviour.
Set options, catch conditions and clear caches
-
prep_model_data(),assign_features_to_polygons()andmake_folds()raise classed R warnings where they logged a line, sotryCatch(),withCallingHandlers()andoptions(warn = 2)see them. They cover rows dropped before a fit (spatialkit_rows_dropped), a constant predictor (spatialkit_constant_predictor), features in no polygon (spatialkit_unassigned) and fewer folds than asked for (spatialkit_k_reduced, with fieldsk_requestedandk).?"spatialkit-conditions"lists every class. No argument restores the log lines.
New features
New functions
resolution_profile()andselect_resolution()choose the number of cells from the data. By default the profile scores one size, about 4.5 observations per cell (obs_per_cell = "auto"), for pooled cell values (estimate = "auto").levelsorn_levelsgive a ladder of counts instead, scored by Mallows’ Cp, the reliability of the cell means, the WSS elbow and the leave-one-out error.select_resolution()reads a count off the profile with its flat region, andsummary()andplot()set the criteria side by side.get_voronoi_seeds(),voronoi_seeds_kmeans()andbuild_tessellation()take a profile or a selection as the count. Seevignette("resolution").cell_values_at()returns the value and interval of the cell at other locations, with each location’s distance from the nearest observation. Seevignette("cells").kriging_adequacy()computes, beside the plain means, what block kriging would give each cell from a fitted variogram: the kriged estimate and variance, the error variance of the plain mean under the same variogram (plain_var) and the share of it kriging removes (kr_gain), with a cross-validated check of the kriging variance. Seevignette("cells").sac_nugget()returns the nugget variance behind anestimate_sac_range()result. Seevignette("spatial-cross-validation").fold_separation()measures, for each fold, the distance from every held-out point to its nearest training point. Givenprediction_points, it sets those distances beside the distances from the locations to be predicted to the data, and says whether the cross-validated error tends to read low or high for that map. Seevignette("spatial-cross-validation").cv_block_size_sweep()runs one cross-validation at a ladder of block sizes, with random folds as the reference, and returns the error at each size with its fold-to-fold spread and the estimated autocorrelation range;plot()draws the curve. A fit budget (max_fits) refuses a sweep that would run past it. Seevignette("spatial-cross-validation").plot_cv_metrics()draws one point per fold for a metric of acv_*()orcompare_models_cv()result, sized by the held-out rows, with the pooled value as a dashed line.plot_calibration()draws the observed against the nominal coverage ofcv_bayes()’s predictive intervals, pooled and per fold. Seevignette("spatial-cross-validation").
Prepare the data
ensure_projected()gainspurpose = c("distance", "area")."area"chooses among equal-area projections, for densities or rates per cell. The CRS chosen for lon/lat input comes withattr(, "crs_choice"), the candidates and each one’s measured distance error, and projected input has its area distortion measured and logged as a warning above 1 percent.prep_model_data()records the rows it drops inattr(x, "dropped")(n,which,row_id,reason). Every fit carries the count as$info$n_dropped, and everycv_*()result asn_dropped. The prepared layer has the class"spatialkit_rows"after"sf";[and thedplyrrow verbs return it without the record.
Measure spatial autocorrelation
estimate_sac_range()gainsdetrend = c("ols", "reml")andreml_max_n. A variogram of least-squares residuals underestimates the range (Lark, Cullis and Welham 2006)."reml"fits the trend and an exponential-plus-nugget covariance together withnlme::gls(), on at mostreml_max_npoints. The default"ols"detrends as 2.0.0 did. nlme joins Suggests.estimate_sac_range()reads rows that share a location as one place: the test for structure uses the location means, pairs at zero separation enter no lag bin, and their semivariance is returned aszero_lag_semivariance. It refuses a variogram that falls with distance over its shorter lags, and a fitted range shorter than the shortest lag fitted, each with its ownrejected_reason.Every classed
estimate_sac_range()result carries its nugget (attr(, "nugget")), whether the nugget sits at the bound of the fit (nugget_at_bound), the shortest lag resolved (first_lag) and the semivariance of nearest-neighbour pairs (short_lag_semivariance). It also keeps the four directional variograms withdirectional_status. The result gains aplot()method, andprint()names the unit and the CRS of the range.
Choose a resolution
build_tessellation(approx_n_cells = ),get_voronoi_seeds(n = ),create_grid_polygons(target_cells = )andcreate_grid_polygons_cached(target_cells = )accept the ranked counts ofdetermine_optimal_levels()(the first is used), aselect_resolution()result or aresolution_profile(). Given a selection or a profile, the k-means seeding functions return the centres the profile scored.determine_optimal_levels()gainson_no_elbow = c("na", "warn", "error")andselect_on = c("all", "split")."split"reads the response on one of two spatially blocked halves and returns the row positions of both, so estimates can be made on the half the selection never saw.resolution_profile()andselect_features_forward()takeselect_ontoo. The model-aware criteria ofdetermine_optimal_levels()now run with a response and no predictors.
Build the cells
build_tessellation()andcreate_voronoi_polygons()gaincover, the observations or polygon the cells must hold when the seeds were made elsewhere. Seeds with neither a boundary nor a cover raise a warning of classspatialkit_no_cover. A hex or square lattice recordsparams$cells_occupiedandparams$cells_empty, and points snapped to a cell are recorded inparams$snapped.get_voronoi_seeds(method = "kmeans")andvoronoi_seeds_kmeans()gainpartition,init,density_poweranddensity_k;voronoi_seeds_kmeans()also gainsnstartanditer_max. A seeding that is not plain k-means from its own starts records itself inattr(, "partition"), andget_voronoi_seeds()returns its clustering asattr(, "kmeans").
Assign and summarise
assign_features_to_polygons()records the features no polygon holds asattr(, "unassigned")and the features a tie-break decided asattr(, "ties"). It names the column it read the polygon IDs from whenpolygon_id_colis absent, and the newquietsilences that message.summarize_by_cell()gainsestimate(pooled values by default),obs_level,conf_levelandarea. A pooled value is the cell’s mean pulled toward the mean of the observations in the 8 nearest cells.obs_leveladds a range for one further observation in the cell,conf_levela t interval for the cell mean, andarea = TRUEthe cell’s area and a point density, refused where the CRS distorts areas across the cells by more than 1 percent.attr(, "intervals")says what each interval covers.summarize_by_cell()returns more of what it computes: the Kish ICCs asattr(, "icc")whether or not they were applied, adeff_appliedcolumn whenever a design effect is requested, and underdeff = "variogram"the per-cell design effects asdeff_rows.
Make folds
make_folds()gainsmethod = "knndm", k-fold nearest-neighbour distance matching (Linnenbrink et al. 2024), which has no row limit;max_testfor"buffered_loo"and"nndm", which builds folds for a random subset of held-out points;blocks, a polygon layer to use as the blocks of"block_kfold"; andbalance_tol, the fold-size ratio above which it warns that the folds are imbalanced.make_folds(method = "block_kfold")returns the block design: ablock_idcolumn inassignment, andparams$blocks(the block polygons),params$block_sizesandparams$fold_blocks.plot_folds()draws the block outlines under the points (blocks = FALSEhides them), and its subtitle gives the size of the blocks built beside theblock_sizeasked for, in the CRS’s unit.
Fit a model
fit_bayesian_spatial_model()reports what its GP basis resolves ($info$gp_resolution) and gainsgp_resolutionto ask for a finer one. After sampling,$info$gp_adequacy$statussays whether the posterior shows structure the basis cannot represent, with a warning of classspatialkit_gp_adequacywhen it does.fit_gwr_model(predictor_vars = character(0))fits a local intercept alone, the baseline a GWR with predictors has to beat.gwr_model_selection()scores it as<none>and gainsdelta, and its result has aplot()method.predict()on a GWR fit warns, with classspatialkit_gwr_extrapolation, when a location lies beyond the reach of every training kernel.fit_gwr_model()surveys the collinearity of every fitting window (info$local_collinearity, with condition indices with and without the intercept), andplot(fit, type = "coefficients")maps one local coefficient, drawing the windows whose estimate is unstable hollow and grey (mask = FALSEdraws them plainly).fit_rf_model()gainsreplaceandsample_fraction, passed toranger::ranger()and recorded in$info. The defaults are ranger’s, so no forest changes.
Use a fitted model
coef()andpredict()on a GWR fit give standard errors.coef(fit, se = TRUE)returns the local estimates with their standard errors and t values, andpredict(fit, newdata, se.fit = TRUE)returnsse.fitandse.pred. Both follow GWmodel’s definitions, treat the bandwidth as known, and make no adjustment for the number of local tests.print(summary(fit))adds the effective number of parameters and a global least-squares fit on the same rows (info$global_ols).plot(fit, type = "variogram")draws the response’s own variogram beside the residual variogram (response = FALSEdraws the residuals alone).
Check a fit in sample
-
residual_morans_i()returns the weights it used as a one-line description (weights_summary) and the matrix itself only under the newkeep_weights = TRUE, and its result has aprint()method.
Cross-validate and compare
compare_models_cv()gainsblock_sizeandauto_range, passed to the shared folds; with the defaults the folds are those of 2.0.0. Itsoverallcarries the Bayesian GP’s interval coverage and mean CRPS when that model runs.Every
cv_*()result accounts for each fold and row:fold_status(one row per fold:"ok","error"with the error text,"skipped","dropped"or"worker_error"),orphan_rows,n_unknown_idsandn_dropped.cv_spatial(),cv_gwr(),cv_bayes(),cv_rf()andcompare_models_cv()gainmetrics, a scoring function of your own,function(y, yhat)returning a named numeric vector. It is applied per fold and to the pooled predictions, beside the built-in metrics.
Choose predictors
-
select_features_forward()gainsnull_fn, a function that fits the model with no predictors for a learner that cannot, andauto_rangefor its inner folds.historystarts with the step-0 row and gainsgain,fold_gainandfold_gain_se. The result gainsbaselineandfold_scores, carries the class"feature_selection", and has aplot()method.
Predict a surface
-
area_of_applicability()gainscategorical = c("refuse", "indicator", "drop")for factor and character predictors, andcoords, which sets whether location gets an index of its own. The result records thescalingof the predictors and the method of the folds its threshold came from (params$folds_method), and has aplot()method.
Bug fixes
Across the pipeline
Rows without a location were read as located, or stopped calls with a bare message. A row with an empty geometry, a coordinate that is
NA, not finite or beyond 1e150, or a latitude beyond 90 in a geographic CRS now has no location wherever the package reads one, before and after any move to another CRS.prep_model_data()and the fits drop and count it,make_folds(),estimate_sac_range()anddetermine_optimal_levels()leave it out,coerce_to_points()gives it an empty point,assign_features_to_polygons()leaves it unassigned, the seeders drop it, andplot_tessellation_map()andplot_folds()leave it out with a warning. Layers without such rows give the same results.Results on gridded locations changed with the unit and the origin of the coordinates. Where a point lay on a cell, block or kernel edge, or as near two neighbours, the last bits of its coordinates chose between them. The package now treats squared distances within one part in ten million as equal and breaks such ties in a fixed order (lower x, then lower y, then row). This applies to
assign_features_to_polygons(),build_tessellation(),create_grid_polygons(),make_folds()(block, buffered and NNDM folds),estimate_sac_range(),residual_morans_i(),predict_surface()and the boxcar kernel of the GWR functions.k-means seeds, Delaunay triangles and merged duplicates changed with the unit and the origin of the coordinates.
get_voronoi_seeds(),voronoi_seeds_kmeans(),build_tessellation(method = "triangles")andcreate_voronoi_polygons()now handstats::kmeans()and qhull the coordinates centred on their bounding box, divided by its diagonal and rounded to about a billionth of it, and merge points that round to one point there. On gridded locations the cells can differ from 2.0.0’s, and elsewhere the seeds can come in another order.build_tessellation(method = "triangles")no longer drops most points at UTM coordinates.A response or predictor far from zero, or in very small or very large units, lost its spread to rounding. Tests for a constant column used absolute floors, and least-squares fits lost a predictor at a large offset.
estimate_sac_range(),summarize_by_cell(),area_of_applicability(),residual_morans_i(),determine_optimal_levels(), the three fitters,select_features_forward()and the metrics now judge spread relative to the values, and centre a column whose centre is more than 1,000 times its spread. Results are those of the same values shifted to zero, to rounding.Coordinates or a response too far from zero for doubles to hold a millionth of their spread raised no warning.
make_folds(),assign_features_to_polygons(),create_grid_polygons(),create_voronoi_polygons(),build_tessellation()andclip_target_for()warn with classspatialkit_xy_imprecisewhere the spacing of doubles at the coordinates exceeds a millionth of the layer’s extent.prep_model_data(), and so every fit andcv_*()function, andestimate_sac_range()warn with classspatialkit_response_imprecisefor such a response. Both say to shift the values nearer zero.Several results depended on the order of the rows.
determine_optimal_levels(), then_maxsubsample ofestimate_sac_range(), thedeff_max_nsubsample ofsummarize_by_cell(deff = "variogram"), thenormalizer_max_nsubsample ofarea_of_applicability(), themax_nsubsample ofgp_lengthscale_bounds(), the sampleensure_projected()scores its candidates on, and the tie-breaks ofassign_features_to_polygons()now put the rows in a fixed order first. Any permutation of a layer gives the same result. Fold numbers no longer depend on the machine’s collation: character fold labels are sorted in C order.A layer that mixed XY and XYZ (or XYM) geometries, or whose geometries carry M, stopped calls or was read by its first row. sf and GEOS took the dimension of the first row, or stopped with “GEOS does not support XYM or XYZM geometries”. Every function now reads such layers in x and y. Where a copy of the caller’s rows comes back, as from
coerce_to_points()orensure_stable_poly_id(), it is XY, with a warning of classspatialkit_zm_dropped.fit_gwr_model()no longer mixes a Z coordinate into its distances.A layer whose geometry column has the class
sfc_GEOMETRYbut holds only points stopped most functions with sf’s “not implemented for objects of class sfc_GEOMETRY”.sf::st_cast(x, "GEOMETRY")builds such a column. The fits, thecv_*()functions,make_folds(),summarize_by_cell(), the seeders, the tessellation builders andpredict_surface()now read it as the same POINT or MULTIPOINT layer. A layer that mixes points with other geometry types is read as before.A layer without a CRS could be stamped with the wrong one. A layer whose coordinates cannot be longitude and latitude is refused a geographic CRS, with an error that names the argument; 2.0.0 stamped it, and drew cells in metres at “latitude” 4,000,000. When only one of the points and the boundary has a CRS, the tessellation builders read the other in it, with a warning, where they stopped on sf’s “st_crs(x) == st_crs(y) is not TRUE”.
create_voronoi_polygons()and the k-means seeders read CRS-less lon/lat points as lon/lat, asensure_projected()does.Lon/lat polygons that s2 refuses stopped calls with s2’s bare message, and some results changed with
sf::sf_use_s2().assign_features_to_polygons()stops with an error of classspatialkit_cells_degeneratethat names the rows and says to transform the polygons to a projected CRS.ensure_projected(),coerce_to_points()andensure_stable_poly_id()repair such polygons first. Areas, unions and sort keys in degrees are taken on the sphere whatever the session setting, so lwgeom is no longer needed with s2 off and the results are those of an s2 session.A move to another CRS that could not place a row returned it emptied or short of a vertex, with no warning.
harmonize_crs(),ensure_projected(target_crs = )and every function that moves a layer it is given into the CRS of its data now warn with classspatialkit_rows_unplaced, naming the rows and the argument. The rows come back as before.citation("spatialkit")gave the year it was called in, not the year of the release. It now reads the CRAN publication date, thenDate, then the build date.The plots’ size arguments did nothing on ggplot2 older than 3.4.0. Suggests now asks for ggplot2 (>= 3.4.0), and testthat (>= 3.1.7) for the test suite.
Prepare the data
coerce_to_points()ended the R session on an empty line feature, and on a lon/lat line its temporary projection could not place. An empty feature now gives an empty POINT, and a line the projection cannot place in full stops with an error of classspatialkit_features_degeneratethat offersmode = "centroid"ortmp_project = FALSE. A centroid that falls outside the bounding box of an invalid projected polygon stops with the same class.coerce_to_points()put the point of a lon/lat geometry written across longitude 180 on the far side of the globe. Points on the surface, box centres and planar centroids now read such a geometry’s longitudes from 0 to 360 and bring the point back into -180 to 180. sf’s warning “st_point_on_surface may not give correct results for longitude/latitude data” is no longer passed on, since the point lies on the polygon as?coerce_to_pointsdescribes.coerce_to_points()put line midpoints off the middle in a CRS whose unit sf has no name for.sf::st_line_sample()measures such a line in metres, so in a unit of 2 m a line’s midpoint landed at its end. The midpoint is now taken at half the planar length in the CRS’s own unit. Among parts of a MULTILINESTRING of equal greatest length, the midpoint lowest in x, then y, is taken. The error formode = "line_midpoint"namesmode, where it saidmethod.ensure_projected()chose its projection from rows that should not decide it. The candidates are now scored on a sample of the distinct locations sorted by coordinate. Pairs shorter than 1 mm, rows without a location and rows with Z or M coordinates (scored as their XY copy) no longer shape the score, and a candidate that cannot place every vertex is not chosen. Data wholly on one side of the equator get a Lambert azimuthal projection centred on the pole where it distorts distances less than Web Mercator. The chosen CRS can differ from 2.0.0’s on such layers.ensure_projected()stopped with “invalid crs” on some lon/lat layers. A layer whose box has no height and whose centre lies within 5 degrees of a pole gave an Albers candidate with a parallel beyond 90; such a candidate is now left out. Its warning on a layer across a pole, or with longitudes outside -180 to 180, gave an offset from the UTM zone’s central meridian beyond 180 degrees; the offset is now wrapped.harmonize_crs()refused an sf layer astarget_crs. An sf or sfc target now means its CRS. The tessellation builders take an sf layer ascrsin the same way.
Measure spatial autocorrelation
estimate_sac_range()drew itsn_maxsubsample over rows with nothing to model, and fitted the raw response when one value was infinite. Rows with a missing or non-finite response or predictor are now left out of the subsample, the detrending fit and the variogram, with a logged count.estimate_sac_range()returnedNAor an R error for a bad argument without naming it.cutoff,range_frac,n_maxandseedare checked, and a bad value is an error that names the argument;cutoffabove 1 andn_maxbelow 30 are errors. Withrange_fracbelow 1, the reason for a refused range no longer says that it exceeded the largest lag.print()on anestimate_sac_range()result showed a bare number. It now names the unit and the CRS of the range (“in metres of EPSG:32617”) and whether the variogram is of the response or of its residuals.
Choose a resolution
determine_optimal_levels()read a misspeltresponse_varorpredictor_varsas absent and changed the criterion. A named column that is not in the layer is now an error. A model-aware criterion given no predictors, or no response, says which is missing in an R warning.determine_optimal_levels()dropped Moran’s I when a few predictor values were missing. Rows with a missing or non-finite response or predictor now stay in the WSS sweep and the cells and are left out of Moran’s I, with a logged count.determine_optimal_levels()stopped one count short when locations repeat. Its cap is now the number of distinct locations. On five stations visited many times it warned of no cluster structure and returned other counts; it now returns the stations’ count first.determine_optimal_levels(criterion = "morans_i")gave a count different cells whentop_normax_levelschanged. Each count’s re-run is now seeded from one integer drawn before the sweep plus the count, so for oneset_seeda count gets the same cells in any window that holds it. Withset_seed = NULLthe re-runs no longer draw from the caller’s stream.determine_optimal_levels()returned 1 for a layer with no rows. It is now an error.
Build the cells
build_tessellation()with a geographiccrsbuilt every method in degrees. The cells are now built and indexed in the projected CRSensure_projected()picks, then returned in the geographic CRS with long edges densified, and Delaunay triangles hold their own points. Over a near-global boundary, where that CRS distorts areas by more than 1 percent,create_grid_polygons()and the hex and square lattices use the equal-area CRSensure_projected(purpose = "area")picks, not Web Mercator.build_tessellation()on cells in degrees held its snap tolerance in degrees against distances in metres, and stopped with “there is no package called ‘lwgeom’” with s2 off. The tolerance is now an arc of the sphere, and the snap is taken on the sphere whateversf::sf_use_s2()says.build_tessellation(method = "triangles")gave an empty triangulation for collinear points and recorded anapprox_n_cellsit had ignored. It now stops with a message that says the points are collinear and points tomethod = "voronoi", andparams$approx_n_cellsisNULL. A warning says thatapprox_n_cellsandcellsizesize only the hex and square lattices.build_tessellation()andcreate_voronoi_polygons()failed on a wholebuild_tessellation()result passed asboundarywith sf’s “no applicable method for ‘st_geometry’”. The error now says to pass its$boundary.clip_target_for()andmake_folds()refuse aboundarythat is not an sf or sfc layer by name.clip_target_for()returned the wrong target for points far from the origin, very close together or without a location. Far from the origin it returned disks around points whose bounding box it should return; points less than about 3e-153 apart got a point or an empty line; points none of which has a location stopped with “missing value where TRUE/FALSE needed”. The box is now read against its span, near-coincident points get the same disk as points at one location, and points with no location are refused. The message for points at one location gives the radius and its unit.create_grid_polygons()sized grids badly in three cases. A transect with sub-millimetre scatter got a sliver study area and a grid of many times the cells asked for; a box whose short side is below a millionth of the long side is now treated as degenerate. Hex cell size depended on which way the boundary lay. A side that is a whole number of cells got an extra row of slivers in some units. A clip that leaves no cell is now an error.create_grid_polygons()ignoredtarget_cells, with no warning, whencellsizeornwas also given.cellsizeandnstill win, and a logged warning now says thattarget_cellswas ignored.create_grid_polygons_cached()could return another site’s grid, or a grid that differs fromcreate_grid_polygons()’s. The cache key now hashes the CRS’s WKT and, for a grid returned in degrees, thesf::sf_use_s2()setting. Withcrsgiven, the cached grid is the oneensure_stable_poly_id(create_grid_polygons())returns.target_cellsdefaults toNULL, socellsize =orn =work without it.create_voronoi_polygons()andbuild_tessellation(method = "voronoi")grew a small layer’s hull too much in coarse units. The margin is 2 percent of the diagonal of the hull’s bounding box, but the diagonal was floored at 1 CRS unit, so a layer less than 1 unit across, such as a small layer in a kilometre CRS, grew by more. The margin is now 2 percent of the diagonal in every unit. Layers whose diagonal is 1 unit or more get the same cells.create_voronoi_polygons()andbuild_tessellation(method = "voronoi")withexpand > 0returned the boundary before it was grown, and dropped a clipped cell that also touched the boundary from outside, leaving its points in no cell. They now return the grown boundary and keep each cell’s polygonal part. A seed outside a boundary that is not convex gets its cell inindex, where it gotNA.ensure_stable_poly_id()failed on, or moved, valid polygons. It stopped on a cell that is valid in its own CRS and crosses itself in lon/lat, which also stoppedbuild_tessellation(method = "voronoi"). It moved the corners of valid polygons in degrees with s2 on, numbered a layer far from its CRS’s origin by the row order, and turned empty polygons into lines. It now repairs only the rows s2 or GEOS calls invalid, measures the rest as given, and returns empty polygons as they came.get_voronoi_seeds()ignoredseedsundermethod = "kmeans"and"random", andsample_pointsunder"random", with no warning. It now warns that the method ignores the argument. Random and k-means seeding on a lon/lat boundary no longer warn “install package lwgeom” on every call.plot_tessellation_map()failed at print on some columns. A fill column of units, Date, POSIXct or difftime values is now drawn on a continuous or time scale, a units label is drawn with its unit, and a cell with anNAID or an empty geometry gets no label. On lon/lat layers the labels no longer warn at print.voronoi_seeds_kmeans()gave the distinct positions as the reason for a clamp set by the number of points. The warning now uses the words ofget_voronoi_seeds()for the same clamp, and both give a count that is not whole as requested.voronoi_seeds_kmeans(k = ),voronoi_seeds_random(k = )and a malformedexpandare refused by name.voronoi_seeds_random()andget_voronoi_seeds()stopped, ran out of memory or never returned on some boundaries. They exhausted memory on a boundary whose bounding box is far larger than its area, stopped on a lon/lat boundary of small pieces far apart or with crossing edges, and never returned on a lon/lat ring along a parallel. Such boundaries are now sampled piece by piece, repaired, or refused at once with the remedy. A boundary row with a latitude beyond 90, or whose repair leaves no polygon, is refused or left out.
Assign and summarise
assign_features_to_polygons()let invalid polygons change the join. One invalid polygon switched the whole layer to another assignment rule, and the smallest-area tie-break took a polygon whose ring crosses itself as the smallest. Invalid features and cells are now repaired withsf::st_make_valid()for the join only, with a warning that counts them.assign_features_to_polygons()joined lon/lat features to projected cells on bent cell edges. The join now runs in the cells’ CRS whenever it is projected, and the features come back with their own geometry, so lon/lat points near a cell edge can change cell to match a join done in the projected CRS.assign_features_to_polygons()let the row order ofpolygons_sfdecide ties.tie_break = "smallest_area"decides equal areas by the lowest, then leftmost, centre, andlargest = TRUEdecides an exact tie in overlap bytie_break; a feature its rules cannot place is left unassigned with a warning of classspatialkit_ties_unresolved. Withlargest = TRUEa polygon feature that only touches the cells is unassigned, and sf’s “attribute variables are assumed to be spatially constant” warning is muffled.assign_features_to_polygons()dropped the features’ ownidcolumn when the cells were keyed byid. Only a column namedpolygon_id_colis replaced now. With s2 off in degrees the join no longer needs lwgeom.summarize_by_cell()let infinite values and malformed arguments through. An infinite value is now left out of every statistic of its column, with a warning of classspatialkit_nonfinite. Adeffthat is not a single finite number of at least 1 falls back to 1 with a warning, adeff_max_nbelow 2 is an error, and a misspelt or non-numericresponse_varor predictor, which was dropped, now raises a warning.summarize_by_cell(cells_sf = )lost or missed cells. A double cell ID of 100000 lost its cell, because whole numbers were written in scientific notation; they are now written in full. The cells are now searched for the ID columnsassign_features_to_polygons()writes, and a summarised ID that matches no cell is reported with a warning.summarize_by_cell(deff = "variogram")misread the variogram it was given. It read an anisotropic variogram as isotropic, ignored asacthat carried no variogram model, said “Falling back to deff = 1” for a rejectedsacand then applied a design effect, and corrected the response with a residual variogram. Each case now applies the model as gstat does, or says in a warning what it used instead.summarize_by_cell(deff = "variogram")mishandled empty points and calls without a value column. An empty point gave its cell a design effect of 1; such points now count towards their cell’s values and not towards its correlation. A call with no value column now returns the counts andcell_weight, where it stopped, and each cell’s correlation matrix is built fewer times.summarize_by_cell()recorded corrections wrongly. The rows with no cell ID got acell_weightof 0, a fixeddeffwith one populated cell recordedattr(, "deff_applied")$deffasNA, anddeff = "kish"recorded no correction when only the predictors were corrected. Each is now counted and recorded as for any other cell or correction.
Make folds
make_folds(drop_empty_blocks = FALSE)could return folds with no test points.kis now lowered to the number of blocks that hold points. Wherevermake_folds()returns fewer folds thank("random_kfold"with more folds than rows,"block_kfold"with fewer occupied blocks thank,"leave_location_out"with more folds than groups), its warning gives a setting that works.make_folds(method = "block_kfold")built uneven or degenerate grids. The automatic grid gave an east-west corridor more than twice the blocks of the same corridor running north-south; both now get the same count.block_nxorblock_nygiven alone was ignored and is now used, with the other derived from the extent. A boundary that is not rectangular left zero-area slivers as blocks; only the areal part of the grid is kept.make_folds()checked arguments with R’s own errors or not at all. A missingk, an invalidbuffer, anyblock_multiplier, and aunitsobject forbuffer,block_size,block_nx,block_ny,phiormin_trainare now refused by name. The refusal of a grid above 1,000,000 blocks names what produced it, where it blamed ablock_sizethe caller never passed.make_folds()gave its warnings about range and leakage too rarely, or with advice that failed. The leakage warning of"block_kfold"now fires whenever aresponse_varis available, since a range is estimated for it alone, and its advice gives settings that buildkfolds.auto_range = TRUEfalling back to geometric blocks,"buffered_loo"with a buffer that excludes no neighbour, and NNDM folds left short of their target bymin_trainnow raise R warnings.make_folds(method = "nndm")returned plain leave-one-out without a warning when the prediction points were nearer the data than leave-one-out reaches. A warning of classspatialkit_nndm_out_of_reachnow says that the cross-validated error is an upper bound for those locations. NNDM also frees its neighbour tables as soon as it has them, lowering its peak memory.plot_folds()failed at print when its layers disagreed on having a CRS. A layer without a CRS is now brought into the points’ CRS, asmake_folds()does: reprojected from lon/lat when its coordinates look like it, stamped with a warning otherwise.
Fit a model
fit_bayesian_spatial_model()accepted families and responses it could not score. A two-level factor response underbrms::bernoulli()is now refused before compiling,brms::categorical()andmixture()families fit, andpredict()on an ordinal or categorical fit stops with advice where it returnedNAas a “posterior draw failed”.cv_bayes()refuses the ordinal and categorical families before sampling any fold.fit_bayesian_spatial_model()returned fits it should have refused, and called an unchecked fit converged. A fit with no posterior draws is now an error, and a response of one value stops before compiling.check_convergence = FALSEsetsconvergence_oktoNA, where it readTRUE, and the convergence check no longer raises dozens of “The ESS has been capped” warnings.fit_bayesian_spatial_model()sizedgp_kfor the defaultgp_cwhatevergp_cwas set to. Withgp_k = NULLthe derivedgp_know matches thegp_cused. The cached fitted values of a fit can no longer come from another model.fit_gwr_model()judged collinearity on a predictor’s origin. It called windows collinear because of where a predictor’s units start (a temperature in kelvin against degrees C), never checked a one-predictor model, and raised false warnings for a predictor named twice. The global and local indices are now computed on centred predictors.fit_gwr_model()capped an adaptive bandwidth above the number of points with no warning, could choose a bandwidth at which a term is estimable at no location, and let local regressions that interpolate the data win on AICc. It now warns of the cap, skips such bandwidths, and reports the AICc of an interpolating fit asNA;gwr_model_selection()ranks such models last.fit_gwr_model()accepted a character or factor response. It now stops with “response ‘y’ is not numeric”, asfit_rf_model()andfit_bayesian_spatial_model()do. Below 20 points,bandwidth = NULLnow fits at the bandwidth the search chose.print()shows a fixed bandwidth with its unit and an adaptive one as a number of neighbours.fit_rf_model()hid ranger’s errors. ranger wrote its diagnosis to stderr and threw “User interrupt or internal error”; the error now carries ranger’s reason, andpredict()on a forest stops with it, where it returned allNA. A forest in which every tree sampled some rows, so they have no out-of-bag prediction, now warns with the count. Theinclude_coords = TRUEcaution prints once per session, also undercv_rf().A fit saved from
fit_rf_model()orfit_bayesian_spatial_model()carried its engine twice, through the environment of its formula. The formulas now carry the global environment, as one typed at the console does.
Use a fitted model
plot()on a fit failed in two cases. A customspatial_fitwithout aresiduals()method stopped with “could not extract residuals”; its residuals are now the response minusfitted(). The subtitle oftype = "variogram"ran off the figure, and is now wrapped.predict()on a GWR fit lost every prediction to one location it could not estimate. Predictions now come from the package’s own local regressions, one per new location, and only a location with no estimable prediction isNA, with a warning that counts them.predict()on a Bayesian GP fit let one row spoil the others. A row ofnewdatawith a factor level the model was not fitted with made every rowNA; now that row alone isNA, with a warning of classspatialkit_new_levels. On brms 2.17 to 2.22 one far-off row moved every prediction; the GP boundary is now held at its fitted value, and a row beyond it isNAwith a warning.
Check a fit in sample
compare_models()set unlike numbers side by side. It put LOOIC and AICc of fits on different rows, or of different responses, in one column, and out-of-bag forest metrics beside in-sample ones, unlabelled. Such columns are nowNAwith a warning, and ametric_basiscolumn says what each row is computed on. A significantly negative residual Moran’s I is no longer read as missed spatial structure.compare_models()andevaluate_insample()failed on a list holding nospatial_fit. Both now stop with an error that namesfits.compare_models(fits, newdata = )no longer labels training-residual Moran’s I as anewdatametric.model_metrics()and the scores read the response’s units. R² againstnewdataused another baseline than thecv_*()functions; it now uses the training mean. R², MAPE and RMSE wereNAor wrong for a response in very small or very large units, or whose squares overflow. A character or factor response is an error, where it gaven = 0and every metricNA, anddraws = TRUEis refused by name.residual_morans_i()accepted inputs it could not use.kwas not checked, aweightsmatrix withNAorInfaborted inside a guard, an empty geometry kept its row, and a custom fit without aresiduals()method had no statistic. Each is now refused by name or handled: empty rows are dropped with a count, and a custom fit is scored on the response minusfitted(), asplot()scores it.
Cross-validate and compare
compare_models_cv()ranked models scored on different rows. When the predicted rows differ, every model is now rescored on the rows all of them predicted, with a warning;overallcarriesn_pred. The shared blocks place polygon rows by the same point every model is fitted at.The
cv_*()functions ignoredblock_sizeandauto_range = TRUE, with no warning, whenfoldswas supplied. They now raise a warning of classspatialkit_fold_args_ignored.cv_rf(parallel = )prints its core-count message once.cv_bayes()rounded coverage levels to a whole percent, so close levels overwrote each other, and every CRPS wasNAabove 46,340 posterior draws. Columns are now named at full precision (coverage_97.5), a level outside (0, 1) or given twice is an error, and the CRPS is computed in double precision.cv_gwr(parallel = n)hung once a GWR had been fitted in the session. It now runs its folds one after another wheneverparallelwould fork, and says so in a warning.cv_spatial()checked too little of what a fold’s fit returns. It scored a fold’s predictions againstresponse_varwithout checking that the fit models it, failed after every fold when..per_rowcame back from some folds only, and let a..per_rowcolumn overwritepredictions. Each case now fails the fold or the call with a message, and the error of afold_info_fnis named infold_status$message.cv_spatial(),cv_rf(),cv_gwr()andcv_bayes()lost folds with no warning. When some folds failed,overallleft them out without a warning, and a parallel run discarded the folds that shared a worker with a failure. Each fold now runs in its own worker, and the functions warn, naming the failed folds and the rowsoverallcovers. Re-using a result’s$foldskeeps its fold numbers.cv_spatial()and the othercv_*()functions checked folds saved by spatialkit 2.0.0 by a rule thatsf::sf_use_s2()changed. Saved folds on lon/lat polygons were refused after the setting was toggled, folds built on a pointized copy of a polygon layer were refused as built from other data, and on data with a polygon s2 refuses they were applied without a check. The check now gives the same answer under either setting.
Choose predictors
gwr_model_selection()failed with bare messages on some inputs. A layer with no rows stopped with an sp error, a fixed bandwidth in the wrong units with “inv(): matrix is singular”, and an adaptive bandwidth was checked less strictly than infit_gwr_model(). Each is now refused infit_gwr_model()’s words.select_features_forward()could pick a variable for making folds fail. Every candidate is now scored on one fixed set of rows, a set that leaves any of them unpredicted scoresNAwith a warning, andhistorygainsn_pred.select_features_forward()did not say whenfit_fnignored the variables it was handed. Two predictor sets that score the same to the last digit at the first step now raise a warning that names the fix. The same data warning is no longer repeated for every candidate set.
Predict a surface
area_of_applicability()returned a threshold of 0 from repeat visits or duplicated training rows. Without folds a row’s reference is now its nearest row with different predictor values; with folds a threshold of 0 raises a warning of classspatialkit_aoa_zero_thresholdwith the remedy. Without FNN, exact copies of training rows get a distance of 0.area_of_applicability()marked some extrapolation as inside. Rows that differ from the training data on a predictor with no training variance now getDI = Infand count outside, and a fractionalchunk_sizeis refused. All-zero weights, whichpmax(importance, 0)gives when no predictor helped, now give equal weights with a warning, where they were refused.area_of_applicability()refused or misapplied folds. Folds built beforeprep_model_data()dropped a row stopped it with “fold 1 refers to rows outside 1:n”; the dropped rows are now taken out, as thecv_*()functions take them out. Folds built on other rows are refused with thecv_*()message, and character fold labels are numbered as there.predict_surface()built its grid and took covariates from the wrong points. A polygon grid took covariates from an arbitrary point in each cell, the automatic grid could lose a column or row and left part of the training extent uncovered to the east and north, and a reused grid kept its old.pred_se. The grid is now reduced to one point per cell, covers the box, and is centred on it.draws = TRUEis refused by name.
Set options, catch conditions and clear caches
Logging could abort or hide the package’s messages. A
loggerconfiguration made before loading the package could abort its functions and receive its log lines, and deleting the session’s temporary directory made every function that logs fail. Logging is now isolated and never aborts the caller, and logged cautions appear in knitted documents as R messages.create_grid_polygons_cached()kept an entry for everycache_envit was given after that environment was gone. A freshcache_envper call left one entry behind each time; a finalizer now removes it with its environment.
Documentation
The documentation is published as a website at https://elkronos.github.io/gis_modeling_toolkit/, with the home page, every help page grouped by pipeline step, the articles and this changelog. The articles are grouped as Get started, Step by step, Worked example and Help, and formulas on the help pages render as mathematics.
Eight articles join the North Carolina example: “Get started”, “Choosing a resolution”, “Building cells and summarising them”, “Spatial cross-validation”, “Fitting and checking models”, “Exporting and reporting results”, “Troubleshooting and performance” and “Terms used on these pages”. Those with code run when the site is built and skip the parts whose optional packages are absent.
vignette("spatialkit_nc_demo")is retitled “Worked example: North Carolina” and matches its own output. The site’s earlier Diagnostics article is split between the cells and models articles, and its address now leads to “Fitting and checking models”.The reference index follows the pipeline, from preparing the data to predicting a surface, and the “See also” of every help page lists the other functions in its section of the index. Three help topics are new:
?"spatialkit-geometry"(how input geometry is read),?"spatialkit-conditions"(every condition class, what it means and what to do) and?"spatialkit-options"(the two options that bound the package’s work).Ten numbered scripts are installed in
system.file("scripts", package = "spatialkit"), each covering one topic on a simulated field with known structure;00-run-all.Rruns them in order.SPATIALKIT_TOUR_OUTPUTwrites their figures to a folder andSPATIALKIT_TOUR_PAUSE = "no"skips the pause after each figure. The home page is generated fromREADME.Rmd, so its figures and numbers are computed when it is built.The help pages and articles describe a cross-validated error as the error at the distance the folds put between held-out points and their training data. Random folds give the error of predicting among the samples, and blocks give the error of predicting into gaps of their size. The pages no longer call random folds optimistic or the blocked score the one to report.
fold_separation()compares the folds with the locations of the map you will predict.?summarize_by_cellsays what..se_*covers at eachdeff: at the defaultdeff = 1, the cell’s own mean when its observations are spread through the cell; under"kish","variogram"or a number, the cell mean as an estimate of the population mean. The numbers are those of 2.0.0.?select_features_forwardsays that$scoreis the cross-validated metric of the winning set, which the selection itself flatters, and not an estimate of how the selected model performs. Running the selection insidecv_spatial()’sfit_fngives that estimate.?fit_bayesian_spatial_modelgains a section on spatial confounding, and?model_metricssays which metrics suit a response that is not Gaussian: RMSE and MAE suit any numeric response, andcv_bayes()’s CRPS and interval coverage are the proper scores for counts and bounded responses.
spatialkit 2.0.0
CRAN release: 2026-09-11
Everything below is relative to 1.0.0 (published on CRAN 2026-08-07). Three exported functions are removed and several defaults change results; read Breaking changes before upgrading.
These notes describe what changed for a user of 1.0.0.
Throughout, raises a warning means a genuine R warning(), which tryCatch(warning = ) catches, suppressWarnings() suppresses and options(warn = 2) escalates. Logs a warning means a logger message in the "spatialkit" namespace, which none of those touch.
Breaking changes
Corrections that change results
-
residual_morans_i()no longer puts weight on a point’s own residual.FNN::get.knn()reports a point’s OWN index among its neighbours whenever exact duplicate coordinates are present, which put1/kon the diagonal of a matrix Moran’s I is only defined for with a zero diagonal. On 40 sites x 4 repeats with a response carrying no spatial structure, 120 of 160 rows gained a self-weight, mean I came out at +0.086 against E[I] = -0.0063, and 77% of samples were “significant” at p < 0.05 against a nominal 5%. Repeat observations at one site are exactly whatmake_folds(method = "leave_location_out")is for. The dense fallback never had the fault, so the statistic also depended silently on whether FNN happened to be installed; the two paths now share one neighbour lookup and agree exactly.Requesting
k + 1neighbours and dropping self is not sufficient on its own; the slot self occupied displaced a genuine co-located neighbour and left a farther point standing in for it (75 of 400 retained pairs sat at distance 121 where a neighbour at distance 0 existed). Duplicate coordinates are now grouped and answered exactly. residual_morans_i()gains anullargument, defaulting to"auto". Model residuals are not exchangeable (they are orthogonal to the design matrix) so the classical randomisation moments are wrong for them. At n = 120 with six smooth covariates and independent errors, OLS residuals had mean I = -0.031 against the exchangeable E[I] = -0.008, and the z-score averaged -0.54 with sd 0.90 instead of 0 and 1. The Cliff & Ord (1981, sec. 8.3) regression-residual moments restore mean z = -0.09, sd 1.03 and a 4.3% rejection rate against a nominal 5%, and agree withspdep::lm.morantest()to machine precision (verified at 1e-16 through the public function)."auto"applies them only when the fit’s residuals really are the OLS residuals on the rebuilt design, which a forest’s and a working GWR’s are not; the null actually used is reported in the return value.summarize_by_cell()standard errors under a design effect were too small.s / sqrt(n / deff)corrects the mean’s variance for clustering but leavess^2biased low by the same clustering: for exchangeable correlation rho,E[s^2] = sigma^2 (n - deff)/(n - 1). The two errors compound. Measured 95% CI coverage at n = 20: 0.905 at rho = 0.3, 0.796 at rho = 0.6, 0.632 at rho = 0.8; after rescaling bysqrt((n-1)/(n-deff)), 0.952 / 0.952 / 0.953. Applies todeff = "kish",deff = "variogram"and a fixed numericdeff. The defaultdeff = 1path is bit-identical to before.determine_optimal_levels()ranks model-aware candidates on the standardised deviate, not on |Moran’s I|. E[I] and Var(I) both depend on the cell count, so |I| shrinks as k grows whether or not the finer tessellation captures anything. Over 300 replicates of a response with no spatial structure, mean |I| fell monotonically from 0.114 at k = 10 to 0.050 at k = 60; an |I| ranking prefers the largest candidate for arithmetic reasons alone. Candidates are now ordered by |z| using the Cliff & Ord residual moments (exact here, since the cell-level residuals are OLS residuals by construction); over the same runs z had mean ~0, sd ~1 and a 5% rejection rate of 0.040-0.057 at every k. The"diagnostics"attribute now carriesmoran_zalongsidemoran_i.-
estimate_sac_range()sweeps four azimuths, not two. A +/-22.5 degree window around 0 and 90 covers exactly 90 of the 180 distinct azimuths; every direction between 23 and 67 degrees, and between 113 and 157, fell into neither. On simulated fields with 3:1 anisotropy and a true major-axis range of 300, the estimate came back at 255 and 249 for major axes at 0 and 90 degrees but 151 and 147 at 45 and 135. Sincemake_folds(auto_range = TRUE)sizes blocks from this number, a diagonally oriented field silently got blocks half as wide as the correlation they were meant to separate.c(0, 45, 90, 135)tiles all 180 azimuths; the same fields now return 255 / 245 / 249 /- A direction whose variogram never reaches a sill is excluded rather than taken as a long range, and the
directionalattribute now has four named entries.
- A direction whose variogram never reaches a sill is excluded rather than taken as a long range, and the
fit_bayesian_spatial_model()’s calibrated length-scale prior never reached Stan.brms::set_prior(spec, class = "lscale")with nocoefis a global prior, and brms applies a global prior only to coefficients with no individual prior of their own; everylscalecoefficient always has one. brms dropped it with a note and Stan received brms’s defaults, which madegp_lengthscale_bounds(), the tail calibration and$info$gp_lscale_priordead weight. Confirmed withbrms::make_stancode(): the requested prior is absent under the global form and present under the coefficient-level form, which is now used.$info$gp_lscale_prioris read back frombrms::validate_prior(), so it records what brms will actually use.The GP basis was sized against the wrong domain measure. brms builds the boundary as
choose_L(x, c) = c * max(1, max(x) - min(x))over the pooled, column-centred covariates, the full range, not the per-axis half-range in which Riutort-Mayol et al. state their inequalities. Recovering the boundary frommake_standata()’s eigenvalues confirmsL = c * full rangeexactly at everyc, so the old convention built a boundary twice as wide asgp_kwas sized for: the GP was under-resolved, and$info$gp_ell_min(the diagnostic meant to catch exactly that) was twice too lenient to fire. Thecfloor is now brms’s own default 1.25 rather than 1.2.fitted()on agwr_fitcould return a coefficient surface. The search for GWmodel’s fitted-value column matched the whole candidate name vector with%in%and took the first hit in the SDF’s column order, and the local coefficients come first. A predictor namedfit,pred,prediction,fittedoryhattherefore returned its own coefficient column, silently: executed in-sample R^2 was -1.18 against a true 0.981, andresiduals(),summary(),model_metrics(),compare_models()and everycv_gwr()fold consumed it without a warning. The search now runs in preference order and excludes any candidate that is also a model term; all five colliding names now give R^2 = 0.981, identical to the renamed control.coef.gwr_fit()returned GWmodel’s whole SDF data slot: 15 columns for a two-predictor fit, of which 3 are coefficients and the rest are standard errors, t-values, the response, the fitted values, residuals andLocal_R2. It now returns the model terms only; reach forobject$engine$SDFfor the rest.estimate_sac_range()is reproducible, and no longer disturbs the caller’s RNG.seednow defaults to123Lrather thanNULL. Then_maxsubsample is an internal approximation, not part of the answer, and leaving it unseeded made the returned range differ between runs on identical input (19531 / 19589 / 19605 on three calls) while silently advancing the caller’s stream, andmake_folds(auto_range = TRUE)sizes its blocks from that number. Passseed = NULLfor the old behaviour.estimate_sac_range()rejects a non-numeric response.as.numeric()on a factor returns its level codes, so a factor response produced a variogram of an arbitrary integer relabelling of the categories and the estimated range changed when the levels were reordered (3700 against 2497 on the same data). Factors and character columns are now an error naming the column; logicals are read as 0/1.Fold sets built from a different dataset are refused. Fold splits are lists of
..row_idvalues, and row IDs areseq_len(nrow())unless supplied, so passingcv_gwr()afoldsobject built from another dataset of the same size applied cleanly; every ID matched, every fold was populated, and the model was scored on splits describing other observations.make_folds()now records a small projection-invariant row fingerprint inparams$row_probe, andcv_gwr(),cv_bayes(),cv_spatial()andcv_rf()error rather than proceed. Fold objects from earlier versions carry no fingerprint and are passed through unchecked.evaluate_insample()rejects duplicated names infits.modelis the keycompare_models()joins its metric and Moran’s I tables on, so two fits called"GWR"produced a 2x2 cross-join: four rows, every one carrying the first fit’s numbers, with the second fit never scored at all.fit_gwr_model()rejects a non-numeric predictor.gwr.basic()expands contrasts viamodel.matrix()and fits, butgwr.predict()does not and fails, so the model appeared to fit and then silently predicted allNA.fit_gwr_model()no longer rejects a two-valued continuous response. The “binary” error is now gated on the response being integer-like. A left-censored or saturated measurement (every observation at a detection limit or a ceiling) has two distinct values and is perfectly continuous; it now warns instead. The guard also runs once per fold insidecv_gwr(), where a small training fold can legitimately hold only two distinct values.fitted()returning the wrong length, or nothing, is now an error insummary()andmodel_metrics()rather than a plausible row count over an all-NAcomparison.new_spatial_fit()is the documented extension point, so a subclass with a missing or mis-sizedfitted()method is user-reachable.The cached
fitted()on abayesian_fitis stamped with thenand a digest of the data it was computed from. The cache environment has reference semantics (which is what makes it survive copy-on-modify) sofit2 <- fitgave both objects the same cache, and assigning different data to the copy returned the original’s values at the original’s length.make_folds()drops rows with empty or non-finite coordinates, with a logged warning naming the count, rather than letting anEMPTYPOINT reachblock_kfold’s nearest-block rescue and die with “replacement has length zero”.When every fold fails, the warning now names the first underlying error. Previously “all 5 folds failed” was the whole diagnosis even when the cause was simply that brms or GWmodel was not installed.
make_folds()records the CRS the folds were built in asparams$crs. Geographic input is projected byensure_projected()to a CRS the caller never chose, andblock_size,sac_rangeandbufferare lengths in that CRS..morans_i_for_k()returnsNAat or below nine cells, where every cell neighbours every other and Moran’s I collapses to exactly-1/(k-1)for any residual vector, a function of the cell count alone.residual_morans_i(fit, k = 1)works on machines without FNN.apply()simplified the length-1 result to a vector, making the neighbour index a 1 x n matrix and every row after the first out of bounds.summarize_by_cell(deff = "kish")under-estimated the predictor ICC by about a factor ofm. The pooled one-way ANOVA grouped themz-scored predictor columns under the same cell label, so independent per-column cell effects averaged away in the shared cell mean and the between-cell sum of squares shrank by ~1/m. Measured at true rho = 0.5 with m = 4: pooled ICC 0.12 against 0.495 per column, so every predictor SE was ~44% too small. The pooled group is now (variable, cell), which recovers 0.49.Design effects are built from what a column actually observes. A cell of 10 rows with 2 finite responses had its response SE formed at the 10-row design effect, then applied to a 2-observation mean: adding 8 NA-response rows moved the SE from 8.46 to 26.38. Each column’s design effect now uses its own non-missing count, with the mean pairwise correlation recomputed over the observed locations when a cell has NAs;
cell_weightis the effective count of the primary variable, not of rows (nstill counts rows).CRS-less coordinates get ONE interpretation, wherever they enter.
prep_model_data()assumed EPSG:4326 for CRS-less data that looked like lon/lat and projected it, while everypredict()method passed the fit’s CRS as a target, a branch that stamped it onto the raw numbers. The same rows sat in two different places, andpredict(fit, newdata = training rows)disagreed withfitted(fit)by up to one response SD (R² 0.98 in-sample, 0.64 via newdata). The heuristic is now a single function used by both branches; a fit records the assumption it was built under and replays it on CRS-lessnewdata. Two further symptoms of the same split, CRS-less LINESTRINGs aborting incoerce_to_points()(“crs not found”), and hex/squarebuild_tessellation()refusing input voronoi accepted, are fixed with it. The assumption is now announced with a real R warning.residual_morans_i()refuses a malformedweightsmatrix instead of silently substituting the default k-NN(8) matrix (I = 0.874 returned for four malformed shapes against 0.805 for the weights actually supplied).The fold-provenance fingerprint no longer refuses the caller’s own data. Three defects in the version introduced last pass: a character
..row_idwas coerced to all-NA(and matched row 1 everywhere); coordinates were compared as"%.7g"strings and flipped on the ~1 in 5000 that a reprojection moved by 5e-9°; and polygon input was probed after pointization, so a differentpointizein the cv call read as different data. Both sides now probe the geometry as supplied, keep IDs in their own type, and compare numerically within 1e-6°.n_folds_attemptedcounts the folds supplied. A fold whose test rows were all removed as incomplete vanished before fitting and was absent from both counts, so five supplied folds reported4/4. It is announced with a real warning.determine_optimal_levels()’s elbow uses the signed deviation below the chord.abs()let a concave bump above the chord (a k where k-means fell into a worse local optimum) win with the same magnitude.estimate_sac_range()returnsNAfor a constant variable (an exactly explained response, or a constant one) instead of a fitted “range” of 168 or 673 from a variogram that is identically zero.make_folds(auto_range = TRUE)no longer re-opens the unseeded subsample by forwarding its ownseed = NULL.fit_bayesian_spatial_model()attaches a user-supplied globallscaleprior at coefficient level, the same way it does its own, soset_prior(..., class = "lscale")reaches Stan instead of being discarded.fitted()on agwr_fitreturns the prediction when a predictor is namedprediction. The model-term exclusion added last pass was applied togwr.predict()’s SDF too, where coefficients are suffixed_coefand the column literally namedpredictionis the prediction;predict()returned allNA.Smaller: a logical response meets the same binary-response guard as
0/1;model_metrics()errors on a non-numeric response instead of returningn = 0;fitted.bayesian_fit()errors when the posterior cannot be drawn instead of returning silentNA;create_grid_polygons()refuses a grid abovemax_cells(default 1e6) up front;make_folds(method = "buffered_loo")states its guard in bytes (splits are ~4n² bytes; the old n = 20000 cap admitted 1.6 GB);-0and0are the same coordinate in the duplicate-aware k-NN;.morans_i_for_k()returns theNApair whenever the moments are unavailable.Documented warnings are now R warnings. Eight paths the manual described as warning only wrote a logger line, invisible to
tryCatch(warning = ),expect_warning()andoptions(warn = 2):residual_morans_i()returningNULL, the CRS assumption inensure_projected()and stamping inharmonize_crs(), GWR collinearity, seed clamping invoronoi_seeds_kmeans()/get_voronoi_seeds(), dropped rows inensure_stable_poly_id(), and the dropped column inassign_features_to_polygons(). Three deliberate methodological cautions (include_coords = TRUE,random_kfoldfeature selection, non-standardised Moran weights) stay logged and their documentation now says so.predict()on a Bayesian GP fit depended on which other rows shared the call. brms 2.x storesXgp,dmaxandcmeansin a fit’s GP basis but not the Hilbert-space boundaryL, sobrms:::.data_gp()recomputes it from whatever rowspredict()is handed. Every eigenfunction of the approximation therefore moved with the newdata bounding box while the fitted basis coefficients stayed put. Measured:Lwas 5.57 at fit time, 4.02 for a five-rownewdataand 3.63 for one row;predict_surface()on the same 10,000-cell grid differed by 1.78 betweenchunk_size = 5000(the documented default) and a single call; andcv_bayes(), which predicts each test fold separately, scored every fold against a basis the model was never fitted with.predict.bayesian_fit()now pins the boundary by appending the training coordinate extrema and dropping them again, so the chunked, fold-wise and single-call answers are identical.A predictor whose name is not a syntactic R name fitted a different model. Every backend builds its formula from these names, so a column called
"B5-B4"was fitted asB5 - B4(a different model, silently, with$predictor_varsstill reporting"B5-B4") and"band 4"died insidestr2lang()with a parser error naming no column.prep_model_data()now refuses such names up front and says which column and what to do about it. (Backticking is not a fix: thespcoercion GWmodel needs runs the names throughmake.names()anyway, after which the formula and the data disagree.)summarize_by_cell(deff = "kish")weighted the response with a predictor’s ICC. The fallback to the predictor ICC is for the case where no response was supplied; applying it whenever the response’s own ICC came out non-positive meant that merely adding a predictor to the call changed the response’s regression weight by a factor of 20, while the response SE was (correctly) left atdeff = 1.A column literally named
nwas summarised as the row count.dplyr::summarise()makes each new column visible to the expressions after it, so the row count shadowed a response or predictor namedn:resp_mean_ncame back equal ton, withsdandseNA, and no message.Variogram models are fitted with a nugget. A nugget-free model forces the curve through the origin, and gstat’s default
N/h^2weights buy that constraint by collapsing the range: with a 50% nugget the fitted range came back at about 0.45 of the truth, somake_folds(auto_range = TRUE)built blocks less than half the correlation length it reported.The directional maximum is used only when anisotropy is established. Splitting 180 degrees four ways leaves each directional variogram about a quarter of the point pairs, and the maximum of four noisy estimates is biased upward: on isotropic simulated fields the returned range ran about 40% above the truth and the “notable anisotropy” warning fired on the majority of them. An omnidirectional variogram is now fitted alongside and is the default answer; the directional maximum is used when all four directions fit, their ratio exceeds 1.5, and the widest stands more than 1.5x above the all-pairs estimate. On the package’s own test field (true range 80) the old rule returned 248 and the new one returns 84; genuine 3:1 anisotropy is still recovered.
predict()replays the CRS decision the fit was made under, including a negative one. When CRS-less training data were passed through as planar, nothing recorded that, so everypredict()re-ran the lon/lat heuristic onnewdataalone; and a subset of those same training rows, whose own bounding box sits inside the lon/lat envelope, was judged differently from the whole: taken for degrees, reprojected, and predicted about 1e6 m from where it was fitted.predict(fit, training_subset)disagreed withfitted(fit)[subset]by more than the response’s standard deviation whilepredict(fit, full_data)agreed exactly.Antimeridian data are no longer flattened onto EPSG:3857. A bounding box cannot distinguish global coverage from a layer straddling +/-180 degrees, but the coordinates can (one very large gap in the sorted longitudes). Web Mercator splits such a layer: two stations 41 km apart came out 40,068 km apart, destroying every distance downstream. Only genuinely global coverage now falls back to EPSG:3857.
The projection for a wide extent is chosen by measurement, not by rule of thumb. Albers standard parallels came from the bounding box while the conic/azimuthal branch came from the centroid latitude, so a trans-equatorial extent put the parallels either side of the equator: at
lat_1 = -lat_2PROJ refused the string outright andensure_projected(),make_folds()andbuild_tessellation()all aborted with an internal-looking “invalid crs”, and just short of it the projection distorted distances by 15.6% against the single UTM zone’s 1.65%. The candidates are now scored by projecting a sample of the data’s own points and comparing planar with geodesic distances, using WGS84 ellipsoidal distances (Vincenty), notsf::st_distance()’s s2 sphere, whose 0.24–0.56% gap from the ellipsoid is the size of the errors being ranked and mis-ordered the candidates on 16 of 40 random wide extents; the message reports both figures.fitted.gwr_fit()could return a coefficient surface. Which GWmodel call produced an SDF was inferred from its column names, so a predictor ending in_coefmade agwr.basic()SDF look like agwr.predict()one and switched off the model-term exclusion; with a second predictor namedyhat,fitted()then returned that predictor’s local coefficient surface (R2 -2.28 against 0.986) andresiduals(),summary()andmodel_metrics()followed it. The mode is now passed explicitly.A logical predictor supplied as text was silently mis-coded.
is.numeric,is.factorandis.characterare allFALSEfor a logical, so the type guard skipped it entirely: a"TRUE"/"FALSE"character column (what a CSV round trip produces) was factor-coded 1/2 against splits built on 0/1, sending every row to theTRUEside (correlation 0.21 with the correct predictions).compare_models_cv()scores every model on identical folds. The documented guarantee only held whenfoldswas supplied: withfolds = NULLeach backend built its own fromk,seed,block_sizeand the rest, so a per-modelblock_sizeput 104 of 150 rows in different folds for GWR and RF, andseed = NULLdid the same with no overrides at all. The folds are now built once, and the arguments that decide the split are protected.User weights with a non-zero diagonal. Every moment of Moran’s I assumes no observation is its own neighbour. A self-inclusive row-standardised kNN matrix (an easy thing to build by hand) rejected the null on 75% of white-noise residuals at a nominal 5%, with no condition raised. The diagonal is now zeroed with a warning.
build_tessellation()$indexno longer snaps outside points to the nearest cell. Points outside every cell were assigned to whichever was closest, so a summary built from the index counted all 40 points of a layer whose study area held 10, whileassign_features_to_polygons()on the same cells correctly reported 30 misses. Only a point within a thousandth of a cell width is snapped now; the rest areNA, and the count is logged.ensure_stable_poly_id()is stable across projections again. The sort key was the raw double centroid, so cells sharing an exactxin one CRS differed by ~1e-11 degrees after a round trip through another: 14 of 16 cells got a different ID depending on which CRS the layer arrived in, the exact failure the function exists to prevent. The key is now rounded to 7 decimals (about a centimetre).A numeric
deffis applied as the uniform inflation it is documented to be. TheE[s^2]correction the estimated design effects apply is derived from within-cell correlation and is unjustified for a constant the caller chose:deff = 2doubled a 3-point cell’s SE instead of multiplying it bysqrt(2), and returnedNAfor every cell withn <= deff.The Kish ICC guard matches its documentation. The docs promise “at least 2 cells with 2+ observations; falls back to
deff = 1otherwise”, and the check was onlyk >= 2, N >= 4: all-singleton cells give a within-group sum of squares of 0 and therefore an ICC of exactly 1, a design effect ofnfrom data carrying no within-cell information at all.gp_lengthscale_bounds()and the GP basis use two dimensions and unique locations.stats::dist()uses every column, so POINT Z geometry gave 3-D length-scale bounds in mixed units; andbrms::gp()defaults togr = TRUEand reduces its covariates to unique rows before taking the boundary, so replicated locations made the package’sS(and with itgp_cand the basis-adequacy thresholdgp_ell_min) wrong by that factor (0.68x with one heavily-sampled station).estimate_sac_range()andmake_folds()drop the Z dimension.gstat::variogram()andsf::st_distance()use every coordinate dimension, so an XYZ layer had its elevation folded into each lag: the returned “range” was a length in 3-D (413.6 against 136.8 for the same stations) while the block grid, the buffered-LOO buffer, NNDM’s neighbour distances andsummarize_by_cell()all work in 2-D map distance.determine_optimal_levels()returns the elbow first. Under the geometric criterion (the default, and the fallback every model-aware call takes below the nine-cell floor) the candidates came back sorted ascending, so the knee sat in the middle:k[1]andtop_n = 1, both documented as “the top-ranked candidate”, returned knee − 1 on every such call, and the help example answered1for two clearly separated clusters. The vector is now knee first, then its lower and upper neighbours, so position 1 means the same thing on both paths. The quick-start data’s answer moves from3 4 5to4 3 5. Same code in 1.0.0.-
estimate_sac_range()is invariant to rotating the layer. Two things were not. The lag cutoff was a fraction of the bounding-box diagonal, a property of the axes rather than of the points, which grows by up to √2 when the same layer is rotated 45°; it is now a fraction of the farthest pair (found on the convex hull), as the documentation always said. And the directional maximum is never preferred over a usable all-pairs fit. The 1.0.0 code returned the widest of two axis-aligned directions; the three hurdles later put in front of it (all four directions fitted, ratio above 1.5, maximum above 1.5× the all-pairs fit) still let the noise through; on one isotropic field rotated in 10° steps they “established” anisotropy in 14 of 18 orientations and returned ranges from 225 to 529, a 2.35× spread produced by nothing but the direction the axes pointed. The four directional ranges are still reported, as a diagnostic, in thedirectionalattribute;anisotropy_usedisTRUEonly when the all-pairs fit itself failed. A field known to be anisotropic should size its blocks frommax(attr(range, "directional"))explicitly, and the log line says so.The variogram fit itself no longer depends on gstat’s single starting value.
fit.variogram()starts the optimiser at a third of the longest lag; for a field whose range is a small fraction of the extent that start is ten times too long, and whether the iteration landed or collapsed to a singular model depended on floating-point details; the same 250-point field fitted on Linux and came back singular on an arm64 Mac, where the estimate then fell through to the directional maximum (315 against a true range of 80). Shorter and longer starting ranges are tried as well, the converged, non-singular fit with the smallest weighted sum of squares (gstat’s own criterion) is kept, and a converged spherical fit is preferred over an exponential one that did not converge. When no model fits at all (a flat, nugget-only variogram) theNAnow carries the empirical variogram, soplot(fit, type = "variogram")draws it and says why there is no range instead of refusing. residual_morans_i()splits tied neighbour distances. The k-nearest neighbour weights broke ties at the k-th distance by whichever point came first (in row order on the dense path, in kd-tree order under FNN) so the same data in a different row order gave a different I, z and p whenever observations shared a location (repeat visits), and on gridded data the answer depended on whether FNN was installed. Points tied at the k-th distance now share the remaining weight equally, on both paths, which is the only rule that is a function of the geometry alone; the matrix is row-standardised as before. Where no distances tie the weights equalspdep’s k-NN weights exactly; on repeat-visit data every co-located twin is retained with its share, and the statistic no longer changes when the rows are shuffled or when FNN is installed. Same code in 1.0.0.**
fit_gwr_model()‘s collinearity diagnostic is the scaled condition index, thresholded at 30.** It waskappa()on the raw, unscaled predictor matrix at 1e6; a number that depends on the predictors’ units, so rescaling a column changed it and the threshold was a threshold on nothing: a design with a scaled condition index of 1322, whose local coefficients ran from −86 to +150 around a true value of 2, raised nothing. Belsley’s index (every column scaled to unit length, intercept included, the ratio of the largest to the smallest singular value) is now computed for the global design and for each sampled local window, and the conventional 30 is the threshold in both. Expect the warning on designs that were silent before.
API and default changes
estimate_sac_range()returnsNAinstead of a number when the fitted range runs past the longest observed lag, or the optimiser stopped at its iteration limit. Such a range is unidentified, not long (the empirical variogram never reached a sill) and sizing blocks or design effects with it is worse than declining to. The refusal carriesrejected_rangeandrejected_reasonattributes and keeps the fitted variogram, soplot(type = "variogram")can draw it; the result is classedsac_range, so it prints as a bareNArather than dumping the fit to the console. Callers that fed the old number straight intomake_folds(block_size = )now need to handleNA; that is the point.Removed the legacy wrappers
evaluate_models(),evaluate_models_cv()andphi_prior_bounds(). Usecompare_models(),compare_models_cv()andgp_lengthscale_bounds().compare_models_cv()gains an"RF"branch and anrf_argsargument, so arangerforest can be compared against GWR and the Bayesian GP on identical folds. Unrecognised model names now raise a warning and are dropped, and a request with nothing recognised left is an error. Previously a bareintersect()discarded anything outsidec("GWR", "Bayesian")and fell back to GWR, somodels = "RF"silently ran GWR and reported it as the answer.coef()on aspatial_fitnow either returns coefficients or errors; it never returnsNULL.coef.gwr_fit()andcoef.bayesian_fit()used to returnNULLon failure, which is indistinguishable from “this model has no fixed effects”, solapply(fits, coef)quietly produced a short answer.coef.rf_fit()errors as before, since a forest has no coefficients; usefit$info$importance. See?new_spatial_fit.Every
predict()method errors when the number of predictions does not match the number of rows that survived cleaning. It used to recycle silently: two predictions for four clean rows produced a four-row answer.create_grid_polygons_cached()’s defaulttypeis now"square", matchingcreate_grid_polygons(). The two disagreed, so cached and uncached calls built different grids from the same arguments.build_tessellation()keepscell_idon"hex"and"square"grids instead of deleting it after indexing, so all four methods return the same ID column andplot_tessellation_map(fill_col = "cell_id")works on a grid.poly_idis retained alongside it.params$expandnow echoes the value passed rather than a hard-coded0; the grid and triangle methods still ignoreexpand, which is now documented.clip_target_for()projects lon/lat input before applyingexpand. The fraction-of-extent form was computed from a bounding box in degrees and handed tosf::st_buffer(), which readsdistas metres. The returned clip target is therefore in the projected CRS, not the input CRS, and says so.Voronoi, grid and triangle clipping union the boundary first. Against a multi-feature boundary,
st_intersection()split every straddling cell into one row per boundary feature and grafted the boundary’s attribute columns onto the result.predict.bayesian_fit(newdata = NULL)honourssummary,typeanddraws. It short-circuited tofitted(), which caches epred column means and nothing else, sosummary = "median"returned means andtype = "predict"returned expected values, silently.prep_model_data()acceptspredictor_vars = character(0), making intercept-only spatial GP models reachable fromfit_bayesian_spatial_model().fit_gwr_model()andfit_rf_model()reject an empty set explicitly.fit_bayesian_spatial_model(control = )is merged over the package defaults (adapt_delta = 0.9,max_treedepth = 12) rather than replacing them. Passinglist(max_treedepth = 15)silently droppedadapt_delta, the setting the divergence warning tells you to raise.cv_bayes()’spredictive_coverageis averaged across folds weighted by each fold’sn_pred. The per-fold values are means over that fold’s test rows, so an unweighted average is not the pooled quantity once fold sizes differ, andblock_kfoldtolerates a 3:1 imbalance before it even logs a warning.The three seeding functions (
get_voronoi_seeds(),voronoi_seeds_kmeans(),voronoi_seeds_random()) all emitseed_idandmethodcolumns, so they are drop-in interchangeable.get_voronoi_seeds()returns seeds in the boundary’s CRS for every method; per-branch alignment had made the final alignment block unreachable.Geometry-type checks require every geometry to be an accepted type, not merely one of them. A mixed POINT/POLYGON layer passed a POINT-only check.
ensure_projected()errors on atarget_crsthat does not resolve to a usable CRS, rather than returning the input unchanged and letting unprojected coordinates flow into distance and area computations.-
fit_bayesian_spatial_model()derives the GP basis count (gp_k) and boundary factor (gp_c) from the ratio of the estimated length-scale to the domain size, rather than from the number of observations.brms::gp()builds a full tensor grid, sogp(..x, ..y, k = gp_k)carriesgp_k^2basis functions;gp_kis the count per dimension. The previous rule reduced tomax(15, floor(sqrt(n)))for anynabove 45, makinggp_k^2identicallyn: at n = 10,000 the model carried 10,000 basis functions and an n × n design matrix, at which point the approximation was no longer approximating anything.Across the scenarios in
dev/baseline-structural.rdsthe derived value is 22–24 per dimension and largely independent ofn: at n = 2,000 the basis count falls from 1,936 to 576, at n = 10,000 from 10,000 to 529, and at n = 200 it rises, 15 to 23. It is a correction, not an optimisation, so results move in both directions.gp_cwas hard-coded at 1.5, too small whenever the length-scale exceeds roughly half the domain half-range; the derived value ranges 2.85–3.59 over the same scenarios. Passgp_kandgp_cexplicitly to restore the old behaviour. For scale, a 4-fold cross-validated fit at n = 2,000 with 2 chains × 1,000 iterations takes 1,186 s on the reference machine at cross-validated R² 0.927 (dev/baseline-accuracy.rds, 2026-08-20); no comparable timing was captured for 1.0.0, so none is quoted. The GP term is built with
scale = FALSE, changing the default result of every Bayesian fit.brms::gp()otherwise rescales its covariates so the maximum pairwise distance is 1 and reportslscalein that space, while this package standardises the coordinates itself and expresses the length-scale prior,gp_cand the basis adequacy threshold in those units. The two normalisations differed by roughly the maximum pairwise distance (~4.9 for standardised 2D coordinates), leaving the automatic prior about five times too diffuse, a likely contributor to divergent transitions and rejected initial values. There is now exactly one coordinate scaling.The GP fits one length-scale per coordinate axis (
gp_iso = FALSE), a second change to default Bayesian results. Coordinates are standardised per axis, so a single shared length-scale made the kernel anisotropic in the original CRS by the ratiosd(X)/sd(Y), a property of the sampling layout, not of the process. Passgp_iso = TRUEfor the previous behaviour; cost is unchanged, since the tensor grid isgp_k^2either way.The automatic GP length-scale prior is a calibrated inverse-gamma rather than
normal(0, sd), a third change to default Bayesian results. A half-normal on a positive parameter puts its mode at zero, so most of its mass sat at length-scales shorter than the basis can resolve, where the Hilbert-space approximation develops a funnel and the sampler diverges. The replacement pins 1% of its mass below the estimated lower bound and 1% above the upper. The two tail conditions have one exact solution (a one-dimensional root in the shape) and that is how it is found, so the calibration succeeds for any bounds withupper > lower; degenerate bounds fall back to the half-normal with a logged note. The prior applied is recorded in$info$gp_lscale_prior.ensure_projected()no longer forces continental-extent data into a single UTM zone. Transverse Mercator scale error grows quadratically with distance from the central meridian, so data spanning the contiguous United States carried distance errors of roughly 7.5% near the extent edge, propagating silently intoestimate_sac_range(),make_folds(block_kfold)block sizing, GWR bandwidth selection and the GP length-scale. Extents reaching more than 5° from the candidate zone’s central meridian now receive an equal-area projection centred on the data, with a logged explanation. Only longitude offset triggers the switch, sincecos(lat)shrinks the distance from the central meridian and a tall narrow north-south extent is UTM’s design case. (Which equal-area projection is no longer decided by latitude band; see The projection for a wide extent is chosen by measurement below, which also replaced the EPSG:3857 fallback for wide bounding boxes with antimeridian detection.) Passtarget_crsto override.Core counts follow the session’s
mc.coresopt-in, and are capped.fit_bayesian_spatial_model()’s documented default wascores = max(1L, parallel::detectCores() - 1L), andcv_*(parallel = TRUE)auto-detected the same way with no cap; 63 workers on a 64-core host, and a hard error wherever_R_CHECK_LIMIT_CORES_is set. The Bayesian default is nowgetOption("mc.cores", 1L); the auto-detect path is capped by that option when it is set; and every worker count, explicit or not, is capped at the machine’s core count (with a message) and at two underR CMD check.
Guards, messages and stricter input handling
prep_model_data()now drops rows whose geometry is empty or whose coordinates are not finite, and counts them in its existing log line.st_geometry_type()calls an EMPTY POINT a “POINT”, so nothing ever looked at the coordinates: such a row reached GWmodel as a rawspcoercion error naming no row,ranger(include_coords = TRUE)as “Missing data in columns”, and brms at predict time as an infinite GP boundary that made every basis function on the surfaceNaN. It also refuses a response listed among its own predictors, which was leakage in the forest, a silently reduced model in GWR, and duplicated rows plus a phantom<none>entry in the GWR selection table.make_folds()validatesk. A non-integerktruncated insiderep(floor(n/k), k): onlyfloor(k)folds were built, the last rows of the permutation landed in no test set, andkwas echoed back unchanged, solength(folds) != k.make_folds(block_kfold)refuses a grid it cannot build. There was no cap onnx * ny, soblock_sizein the wrong unit asked for 1e8-1e11 cells and exhausted memory; the message now names the implied cell count, the extent and the CRS units, ascreate_grid_polygons()already did.predict_surface()gained the same guard oncell_sizeandn_cells.Hand-built
foldsare checked. Train and test overlapping is not cross-validation (the model is fitted and scored on the same rows and the result is reported as a CV score: RMSE 0.50 against 0.97 for the same data properly split), and is now refused; fold IDs that name no row were dropped silently byna.omit(match())and are now counted and logged.The fold provenance probe tolerates a row it could not measure. It was taken before the empty-geometry filter, so it carried
NaNcoordinates and every latercv_*()call on the same data died with R’s internal “missing value where TRUE/FALSE needed”.estimate_sac_range()drops rows with unusable coordinates instead of returningNAfor the whole layer under the message “variogram model fit failed”, which blamed the fit rather than the row and disagreed withmake_folds()on the same data.GWR’s local collinearity spot-check now runs after the bandwidth is chosen, includes the intercept column, and treats a non-finite condition number as extreme. On the default path (
bandwidth = NULL) it used a stand-in window, so the documented warning never fired; without the intercept it could not see an indicator constant inside a window; andis.finite(cn) && cn > 1e6discarded exactly singular designs. A new post-fit warning counts local regressions that returned non-finite coefficients; previouslyfitted(),summary()andmodel_metrics()silently reported metrics computed from the survivors (n = 18 of 200, R2 = 0.96).fit_gwr_model()warns when a fixed bandwidth is implausibly small for the data’s extent. The bandwidth is a distance in the CRS the fit runs in, whichprep_model_data()may have chosen: 0.2 supplied for lon/lat data is 0.2 metres, and every local window came back empty with nothing raised. The argument’s documentation now says so.summary.spatial_fit()applies the same response-type guard asmodel_metrics(). A character response still producedn = 0and all-NAmetrics there, and a factor died insideabs().print.spatial_fit()prints the CRS (which its documentation has always promised) and oneFormulaline.sprintf()vectorised over a multi-elementdeparse(), so everybayesian_fitprinted its formula as two mangled fields; thegp()term this package builds is always long.summarize_by_cell()warns whencells_sfcarries duplicated IDs (each summary row is then repeated per matching cell, sosum(n)exceeds the number of points), and realigns every per-cell vector indeff_appliedafter the join, not onlydeff:$rbarwas left in pre-join order, sodeff[i]andrbar[i]described different cells.assign_features_to_polygons()warns when no feature falls in any polygon instead of returning an empty layer silently.create_grid_polygons(target_cells = )builds square cells fortype = "square".cellsize = c(w/nx, h/ny)forced an exact bbox tiling, so the cells were rectangles (aspect 10.5 on a 1000:1 strip). Fortype = "hex"a differingcellsize[2]is now collapsed with a warning before themax_cellsestimate, which used both components and was therefore off by their ratio.create_grid_polygons_cached()’s renumbering is documented: it appliesensure_stable_poly_id()andcreate_grid_polygons()does not, so the same cell carries a differentpoly_idfrom the two builders.get_voronoi_seeds(method = "kmeans")clusters in two dimensions and drops rows with unusable coordinates, matchingvoronoi_seeds_kmeans(). It used every column ofst_coordinates(), so POINT Z geometry was clustered in 3-D with elevation dominating, and an EMPTY POINT crashed insidekmeans().determine_optimal_levels()refuses a factor or character response, whichas.numeric()silently turned into level codes: re-ordering the levels of the same factor changed the chosen number of levels and everymoran_z.plot_tessellation_map()brings CRS-less layers into the plot’s CRS instead of passing them through to fail insideggplot_build()at print time with sf’s message, naming no layer; and it borrows a CRS from an overlay when the tessellation itself has none.Documentation corrected where it did not match behaviour:
ensure_projected()states how it chooses a projection for a wide extent (by centroid latitude when that entry was written, by measured distortion in this release) and that the choice is announced rather than silent;.looks_like_lonlat()’s two tests are a disjunction and the extent test decides first, so a small planar survey inside the lon/lat envelope IS taken for degrees; the trade and its reasoning are now stated;harmonize_crs()no longer claims to matchensure_projected()while doing something else;summarize_by_cell()states which estimand its standard errors are for (the grand mean, where measured coverage is 0.95, not the cell’s own mean, where the naive SE is the better estimate) and that the variogram path applies one correlation function to every column.A misspelt
newdatais an error, not an in-sample answer.model_metrics(),evaluate_insample()andcompare_models()forward...topredict(), which checks it only on the out-of-sample branch, somodel_metrics(fit, newdta = hold)silently took the in-sample branch and returned an RMSE of 1.086 where the held-out answer was 25.24, with the same return shape. Arguments in...with nonewdataare now refused by name.predict()on agwr_fitor abayesian_fitlikewise refuses unknown arguments instead of swallowing them;predict.rf_fit()accepts only ranger’s own predict arguments through....predict()enforces onenewdatacontract on all three fit classes. A baresfcdied inside two of them with R’s “argument must be coercible to non-negative integer”; a numeric-at-fit predictor that arrived as character (a CSV round-trip) was refused by name byrf_fitandbayesian_fitand returned all-NAwith a generic backend warning fromgwr_fit; a missing column was reported by two different functions in two wordings. All three now run the same check first, so the message is the same whichever fit is behind it.make_folds()validatesblock_sizethe way it validatesk: a single finite positive number, else an error naming the argument.NAand a length-2 vector used to die as internal R errors, and a negative, zero or character value was silently ignored, yet echoed back inparams$block_sizeas if it had been used. The grid-size guard also formats its own message: ablock_sizein the wrong unit could ask for a grid past 2³¹ cells on a side, which%drefused with “invalid format” instead of the documented refusal.estimate_sac_range()says which variable it modelled. A predictor name absent from the data was dropped silently byintersect(), and with every name unknown the raw response was modelled; somake_folds(auto_range = TRUE)sized blocks from a range of 88.5 instead of the residual range of 362.2 with nothing said. An unknown predictor is now an error, as it is everywhere else; a detrending fit that fails (an all-NAcolumn) raises a warning and falls back to the raw response; and a newdetrendedattribute records which was used.make_folds(block_kfold, boundary = )refuses a boundary containing none of the points (almost always two layers in different places, a CRS that could only be stamped) and raises a warning counting the points that fall outside a boundary that contains some, since the region is silently extended to cover them. The single-block error names what produced the grid (the block size,block_nx/block_ny, or the automatic grid) rather than always blamingblock_nx/block_ny, which the caller may never have passed.Rows that no fold names are reported. The
folds↔︎ data guard was one-directional: fold IDs naming no row were counted and dropped, but rows in the data that appear in no fold’s train or test set passed with no condition at any level: afoldsobject built onsite[1:45, ]and applied to all 90 rows scored 45 of them and reportedn_folds_attempted = n_folds_succeeded = 3. Everycv_*()now raises a warning with the count and an example row ID.User-facing conditions name the function the user called. The cross- validation path leaked two internal names into ordinary console output,
.remap_folds():and.cv_run_folds():, andcv_rf(), a wrapper aroundcv_spatial(), reported every message, warning and error incv_spatial()’s name. Thesf-input assertion shared by the tessellation and seeding functions said “Expected an sf object” with no function named; it now names the caller and, when handed a wholebuild_tessellation()result, says to pass its$cells.coerce_to_points(mode = "line_midpoint")’s MULTILINESTRING refusal is prefixed like every other.clear_grid_cache(cache_env = )removes only its own entries. It removed every binding in the environment it was handed and counted them all as “entries removed”, so a user who passed a project environment lost unrelated objects. Cache keys now carry aspatialkit_grid::prefix and nothing else is touched.summarize_by_cell(deff = "variogram")now uses every structured component of a nested variogram model, each weighted by its partial sill, which is the correlation the model implies (1 - gamma(h) / sill). It read the single largest component, so a user-builtNug + Exp + Sphmodel gave a correlation of 0.108 at 200 m wheregstat::variogramLine()implies 0.197, and the design effects and standard errors with it. Models fromestimate_sac_range()are single-component and are unaffected. A model of a family the function does not implement (Matern, power, circular, …) was silently read as exponential; it now falls back todeff = 1with a warning that names the family. Exponential, spherical and Gaussian are supported.cv_bayes()$predictions$yhat_sdis the posterior predictive standard deviation of each held-out row, from the same draws that give the coverage columns. It was an unconditionalNAplaceholder. It staysNAwhencompute_pred_intervals = FALSEor the draws failed for a fold, and it is documented.fit_gwr_model()refusesn <= p + 1observations with one error, before touching the backend. Such a fit cannot have a residual degree of freedom in any window;n = 2used to warn three times (“only 2 observations”, “fallback bandwidth”, “2 of 2 local regressions singular”) and return a fit whose fitted values were allNA.create_grid_polygons_cached()gainsmax_entries(default 50): once the cache holds that many grids, adding one evicts the earliest-added. It never evicted, so a loop over a thousand boundaries held every grid (about 2 MB per 2,500 cells) for the life of the session. Nothing but the grids is written into a caller-suppliedcache_env; the insertion order lives inside the package. The cache key also hashes the package version, so a cache that outlives an upgrade cannot serve a grid built by an oldercreate_grid_polygons().spatialkit_quiet()accepts aloggerthreshold as well asTRUE/FALSE, and the value it returns can be passed back:old <- spatialkit_quiet(); spatialkit_quiet(old)restores exactly the level that was in force.spatialkit_quiet(FALSE)put back the package default (WARN) whatever had been set, and the returned value was refused as “must be TRUE or FALSE”..onUnload()disarms bothloggerappenders, so thespatialkitlogger namespace no longer keeps pointing at the session’s temp-file path afterunloadNamespace("spatialkit")..onLoad()re-registers them.residual_morans_i()documents the second reason"residual"(and"auto") falls back to the randomisation null: fewer than four residual degrees of freedom, where the residual variance formula divides by(n - p)(n - p + 2)."residual"logs a warning when it does,"auto"does not, anddfis thenn - 1.estimate_sac_range()states what “effective range” is for each model, three times the range parameter for the exponential fit (95% of the sill), the range parameter itself for the spherical fallback (100%), and its return-value documentation matches the code: the no-model case (both fits singular) returns the classedNAwithrejected_reasonset, and only the cannot-even-start cases (nogstat, too few values, no variance, a degenerate extent) return a bareNA. Its example now demonstrates a fitted range on a simulated field with a known one (3 x 100 = 300), and a refusal on a field whose range the data cannot pin down.-
make_folds()documents whatblock_multiplierdoes (the automatic grid aims forblock_multiplier * kblocks, so each fold holds out about that many; 3 is a compromise, not a published constant), cites Roberts et al.- and
blockCV(Valavi et al. 2019) for sizing blocks from the autocorrelation range, and notes thatblockCVtakes the fitted variogram’s range parameter whereauto_rangetakes the effective range, three times that parameter for an exponential fit, so larger blocks.phiformethod = "nndm"is explained as Mila et al. (2022) define it: the autocorrelation range beyond which matching is unnecessary, whichestimate_sac_range()supplies.
- and
summarize_by_cell(deff = "kish")says which ICC estimator it is (ANOVA with Donner’sn0, not REML) and how far the two can differ on an unbalanced draw, so the difference is not read as a defect;area_of_applicability()’s training-DI sentence now says what the code does (each fold’s actual training rows, not “everything outside the fold”);?spatialkitno longer listscoef()among the methods all three backends share (a forest has none); the internal elbow helper no longer claims to match Kneedle, which it does not on shouldered curves; the GP basis diagnostic’s code comment attributes its 10% posterior-mass trigger to this package rather than to Riutort-Mayol et al. (2023).summary()on a fit printsR^2andAdj R^2in ASCII with aligned labels (the superscript two rendered asR<U+00B2>on non-UTF-8 consoles, andAdj R²=had no space);print()on a random forest likewise; the six console messages that carried an em dash use--.coef()on anrf_fitprefixes its errorcoef.rf_fit():like its siblings.get_voronoi_seeds(method = "kmeans")sizes its candidate cloud in double precision;50L * as.integer(n)overflowed toNAabove 42,949,672 seeds.README: the opening leakage example says it needs
ranger; the no-viable-models example is assigned so that it does not print every fold table on a machine that has the backends; theauto_rangeandcv_bayes()failure examples show every line the console actually prints; the installation table no longer suggests installinglooseparately (brmsinstalls and calls it); the “logged note” fromdetermine_optimal_levels()is identified as an INFO-level line in the session log file, not console output; the roxygen2 sentence no longer names a version or aRoxygenNotefield.The memory-guard test for
make_folds(block_kfold)stubs outsf::st_make_grid()for the two refused calls, so a regression of the guard fails fast by name instead of attempting an 8000 x 8000 grid.Every
cv_*()refuses a fold list whose splits carry notrain/testelement, with an error that names the problem. It readf$train/f$teststraight, gotNULLfor both, and built empty folds, so the row-coverage warning fired and blamed folds “built on a different or subsetted layer”, which was not the cause, and the run returned an all-NAoverallwithn_folds_succeeded = 0.area_of_applicability()had always refused the same input by name; the two now agree. When the splits look positional (two unnamed vectors each) the error says so and points at the fold label vector instead.The
foldsargument of everycv_*()documents all three shapes it accepts (amake_folds()result, a list oflist(train =, test =)splits, or a vector of fold labels), where the help listed only the first two. The label vector is what makes folds from another package usable directly:blockCV::cv_spatial()returns one as$folds_ids(its$folds_listholds two unnamed vectors per fold, which is the shape now refused by name).MAPEandSMAPEare documented as what they are: averages over the rows whose denominator is non-zero. Both have a denominator that can vanish (MAPEwhere the observation is zero,SMAPEwhere observation and prediction are both zero) and each drops those rows rather than returningInf, which is the right arithmetic but was reported nowhere. On a response taking exact zeros (counts, rainfall, abundance) the consequence is material: with 62 zeros out of 120,MAPEis an average over 58 rows presented as though it covered 120, andSMAPEdrops precisely the rows a well-fitted model got right, so it reads worse than the fit deserves. The new “Percentage errors on responses with zeros” section onmodel_metrics(), inherited byevaluate_insample(),compare_models(),compare_models_cv(),summary()and all fourcv_*(), says so, notes that thencolumn is the finite-pair count and not the row count either percentage error used, and points at RMSE/MAE/R-squared (and, for a Bayesian fit, CRPS and interval coverage) as the metrics unaffected by it. No computed value changes; returning the per-metric row count would alter the metric frame’s column set and is deferred.
Bug fixes
Data carrying no CRS works again throughout.
ensure_projected()now rejects atarget_crsthat does not resolve to a usable CRS (previously a typo silently made the call a no-op), but internal callers derive that target from another object,st_crs(training_data), and that object is allowed to have no CRS. PassingNA_crs_through turned every CRS-less workflow into a hard error:predict()on all three backends,make_folds(method = "nndm"),make_folds(boundary = ),prep_model_data(boundary = )andpredict_surface().cv_rf()was worse than an error; the per-foldpredict()threw, so every fold “failed” and$overallcame back withn_pred = 0andRMSE = NAbehind a generic warning. Internal call sites now passNULL(“choose one automatically”) when the source has no CRS; the user-facing validation is unchanged.build_tessellation(crs = ),create_voronoi_polygons(crs = )andcreate_grid_polygons(crs = )errored with sf’s “cannot transform sfc object with missing crs” whenever the input had no CRS, exactly the users most likely to passcrs =. Reprojection is impossible there, but assumption is not: the target CRS is now stamped on with a loud warning, matching whatensure_projected()already documents. Input that does carry a CRS is still reprojected, not relabelled.compare_models_cv()built its argument list withc(list(...), rf_args), so anygwr_args/rf_argsentry whose name collided with one the function sets itself produced two entries of that name anddo.call()died with “formal argument ‘seed’ matched by multiple actual arguments”. Sincecv_rf()has bothkandseedas formals,rf_args = list(seed = 3)(straight from the documented usage) was enough to trigger it. Extras now replace base entries by name.data_sf,response_var,predictor_varsandfoldsare protected and dropped with a warning, because a per-model override of those would silently make the models incomparable.compare_models()given a single barespatial_fitreported all-NAMoran’s I columns and logged “‘fit’ is not a spatial_fit object” once per component. Aspatial_fitis itself a list, so it passed theis.list()check and the loops then iterated the fit’s own components as though they were models. It is now wrapped into a one-element named list, exactly asevaluate_insample()already did.residual_morans_i()failed on its own documented fast path. WithFNNandMatrixinstalled the weights are a sparseMatrix, andbase::crossprod()does not S4-dispatch on thedgeMatrixthatW %*% residproduces, so the call died with “requires numeric/complex matrix/vector arguments”, takingcompare_models(), which calls it automatically, down with it. Rewritten assum(resid_c * (W %*% resid_c)), which is numerically identical and uses only dispatching primitives.determine_optimal_levels()carried the same bug.residual_morans_i()no longer errors on constant non-zero residuals: the degeneracy guard tested the raw sum of squares where Moran’s I is a function of the centred residuals, soVIcame outNaNandif (VI > 0)raised “missing value where TRUE/FALSE needed”. A non-finiteVIis handled too..build_knn_weights()’s n > 5,000 guard tests for bothFNNandMatrix. Keyed onFNNalone, an unbounded dense n × n allocation went through wheneverFNNwas present butMatrixwas not.assign_features_to_polygons()drops columns offeatures_sfthat would collide with the polygon ID column, with a logged warning.sf::st_join()suffixed them (poly_id.x/poly_id.y), which defeated the rename afterwards and left the result with no rows, reachable simply by re-assigning already-assigned points. A join that still fails to produce the ID column now errors and names the columns it did produce.summarize_by_cell()keeps the"deff_applied"attribute whencells_sfis supplied;dplyr::left_join()rebuilds attributes from itsxtemplate and dropped it. The per-cell vector is remapped onto the joined row order,NAfor cells holding no observations.summarize_by_cell()joins on the native ID type when both sides agree. Coercing unconditionally made the returned ID type depend on an unrelated argument and turned integer IDs into"1","10","2", …. A genuine class mismatch still coerces both to character and logs why.summarize_by_cell()coerces non-POINT geometry before computing a variogram-based design effect.sf::st_coordinates()returns one row per vertex, so a POLYGON or multi-vertex MULTIPOINT feature misaligned the coordinate matrix with the data and fed the wrong points into every cell.make_folds(method = "buffered_loo")errors when the buffer excludes so much of the data that no fold retains two training points. Those folds used to sail through and be dropped one at a time inside the CV loop, so the only symptom was a generic “all folds failed” warning at the very end.make_folds(method = "block_kfold")refuses a block size yielding a single block covering the whole extent; one fold with an empty training set, reported as a run that merely happened to scoreNA. An accepted autocorrelation range could trigger it:estimate_sac_range()rejects ranges above half the bounding-box diagonal while block construction needs half the width.make_folds()coerces MULTIPOINT geometry rather than merely accepting it, for thest_coordinates()reason above; every fold was misaligned silently.Cross-validation no longer renumbers folds.
.remap_folds()dropped unusable folds from a list, shifting every later fold’s index, sofold_metrics$foldandpredictions$foldstopped lining up withmake_folds()$assignment$fold. The original index is carried through. Folds left with fewer than two training rows are detected there and logged, instead of failing one at a time deeper in.cv_spatial()rejects afit_fnwhosepredict()returns the wrong number of values. Both the metric computation and the prediction frame recycled silently, so two predictions against four test rows yielded a four-row frame with metrics computed against fabricated pairs.Cross-validation under
parallel = TRUEreports a fold that died in a worker.parallel::mclapply()returns atry-errorrather thanNULL, which theNULLfilter kept, and the failure surfaced as “subscript out of bounds”.conditionMessage()has no method for atry-error, so the diagnostic branch itself threw; the condition is now taken from the object’s attribute.Cross-validation under
parallel = TRUEis reproducible fromseedand gives results identical toparallel = FALSE..cv_run_folds()calledparallel::mclapply()without seeding the fork streams, so each worker seeded itself from the clock and process ID. One seed per fold is now drawn in the parent, making each fold’s stream a function of(seed, fold index)alone.estimate_sac_range()rejects a singular variogram fit.gstat::fit.variogram()signals failure by settingattr(., "singular")and returning normally, so testing only for atry-errormade the spherical fallback unreachable and let a singular fit’srangeflow out as the estimated autocorrelation range, whichmake_folds(auto_range = TRUE)then sizes spatial blocks from..extract_gwr_values()requires every model-matrix column to match a column of GWmodel’sSDFbefore multiplying the local coefficients through. A partial match reconstructed a linear predictor missing one or more terms and returned it as the fitted value; plausible numbers that were simply wrong, feedingfitted(),residuals(),summary()and every metric with no warning. A non-numeric coefficient column is refused rather than coerced.fit_gwr_model()separates the three degenerate response cases. Folded together, an all-dropped dataset was reported as “binary (0 unique values)” and a constant response as “binary (1 unique value)”, while a genuinely binary non-integer response (1.5 / 2.5) failed the integer-like gate and passed unremarked.fit_gwr_model()andgwr_model_selection()validatebandwidth. Unvalidated,NAgave “missing value where TRUE/FALSE needed”, a length-2 vector gave “the condition has length > 1”, and withadaptive = FALSEa zero or negative distance reached GWmodel untouched.fit_gwr_model()’s local-collinearity spot-check no longer touches the RNG at all. It sampled its 30 locations from the global stream and fires only whenn > 30with at least two numeric predictors, so the same script produced different fold assignments depending on how many predictors a model happened to carry;cv_gwr()calls it once per fold. The 30 locations are now evenly spaced ranks of the observations ordered by x, then y, reproducible, independent of the row order, and drawing no random numbers.predict.gwr_fit()returns an all-NAvector when every row ofnewdatais dropped as incomplete, matching the other two backends, rather than surfacing a raw sf-to-Spatialcoercion error.predict.bayesian_fit()transformsnewdatato the training CRS before cleaning it, and derives the surviving rows from one sentinel column instead of a second, separately-maintained copy of the cleaning rules. It errors when a predictor standardised at fit time is absent fromnewdataor has arrived as character; silently skipping it handed brms an unscaled column against a model fitted on a scaled one. Its failure path returns a matrix whendraws = TRUE, honouring the documented return shape.plot()on aspatial_fiterrors when there are no finite residuals, instead of producing a uniformly grey map fromlimits = c(Inf, -Inf). A perfect fit is handled too: all-zero residuals gavelimits = c(0, 0), a degenerate diverging scale whose breaks collapse onto one value.plot_tessellation_map()logs a warning for afill_colthat is not present, instead of drawing an unfilled outline map with nothing to say anything had gone wrong; a mistypedlabel_colalready warned.xlim/ylimare validated, and thethemedefault moved out of the formals so a Suggests package never appears in an exported function’s default arguments.harmonize_crs()announces when it stamps a CRS rather than reprojecting.sf::st_set_crs()only relabels; the coordinates do not move.ensure_projected()already made that assumption loudly.coerce_to_points()rejects an EMPTY LINESTRING rather than misaligning the result.st_line_sample()yields no midpoint for one (and segfaults in sf 1.0.x), so the sampled midpoints stopped corresponding 1:1 with the rows they are scattered back into. A count check backstops any other divergence.evaluate_insample()errors on an unnamed list. The loop is overnames(fits), so an unnamed list iterated zero times and returnedNULLsilently;compare_models()then died inseq_len(nrow(...))nowhere near the cause.determine_optimal_levels()coerces MULTIPOINT geometry rather than admitting it, and errors on a factor or character predictor by name instead of dying insidecolMeans()with “‘x’ must be numeric”.create_grid_polygons()passes bothcellsizeandntosf::st_make_grid()when both are known;st_make_grid()does not ignorenin the presence ofcellsizefor square grids, and omitting it made sf recomputenx = ceiling(w / cellsize), which floating-point division pushes one past the intended count.nis parsed and validated once, up front, instead of being silently coerced toNULLin one branch and erroring in the other.The grid cache key no longer truncates
target_cells.as.integer()made 25.2 and 25.7 collide on one key, so the second call silently received the first one’s grid, and aNULLtarget_cellscollapsedpaste0()tocharacter(0), crashing the lookup.build_tessellation()normalises a CRS-lesspoints_sftoNULLrather thanNA_crs_, which is a list and so was not treated as “no CRS supplied” downstream. Hex and square grids are built in the points’ CRS, so the grid and the points no longer end up in different CRSs and break the point-to-cell index.build_tessellation(method = "triangles")triangulates the point set whengeometryis unavailable, viasf::st_triangulate()on the unioned points. The fallback previously triangulated the convex hull polygon, discarding every interior point. The result is still the Delaunay triangulation of the input; only the resolution of degenerate configurations can differ from qhull’s, and the logged warning now says so.ensure_stable_poly_id()logs a warning naming the geometry types when it drops non-polygonal rows, which it silently did before.voronoi_seeds_kmeans()andvoronoi_seeds_random()validate their inputs (voronoi_seeds_random()also accepts thesfcits documentation always promised), and clampingkto the number of distinct positions is logged.get_voronoi_seeds(method = "provided")logs a warning whenndisagrees withnrow(seeds), which it ignores.gp_lengthscale_bounds()validatescoords_xyandq_small. A vectorcoords_xyfailed inside.safe_dist()with “argument is of length zero” and an out-of-rangeq_smallinsidequantile(), neither naming the argument.fit_bayesian_spatial_model()validates the response before handing it to Stan, where nothing points back at the column, and validatesgp_k,gp_candcontrol. The inverse-gamma prior is written with%.10grather than%.6f: a small scale rounded to the literal"0.000000"and Stan rejectedinv_gamma(a, 0)from deep inside the model block. Tightly clustered coordinates get there. The half-normal fallback’s scale is guarded the same way.compare_models_cv()names, in a warning, anygwr_argsentry it drops.cv_gwr()has no..., so entries meant forfit_gwr_model()alone (e.g.longlat) were discarded silently and simply had no effect..compute_reg_metrics()errors on ay_train_meanthat is neither a scalar baseline nor one value per observation, instead of recycling it against the filtered response and silently distorting R².create_grid_polygons()no longer truncates the grid whencellsizeandnare both supplied. This changes results.sf::st_make_grid()does not ignorenwhencellsizeis given: for square grids it takes the cell dimensions fromcellsizeand the counts fromnx = n[1],ny = n[2], anchored at the bounding-box corner.cellsize = 25withn = 2on a 100 × 100 boundary therefore produced 4 cells covering 2,500 of 10,000 square units and silently left three quarters of the study area with no cells at all; and becauseclip = TRUEhad nothing outside the boundary to discard, the result looked like an ordinary, complete grid.cellsizenow wins,nis dropped with a logged warning naming what it would have done, and the same call returns 16 cells covering the whole boundary.nis still forwarded when the package derivedcellsizefrom it or fromtarget_cells, which is what the original code was written for: omitting it there lets sf recomputeceiling(w / cellsize)and floating-point division pushes the count one past the intended value.fit_gwr_model()no longer refuses a continuous response that happens to take two values. This changes results: fits that used to error now run. The guard rejected any response with exactly two distinct finite values as “binary” and pointed atGWmodel::ggwr.basic(family = "binomial"). Two distinct values is not the same thing as binary: a measurement censored at a detection limit or saturated at a ceiling (0.0031 / 12.7401) is perfectly continuous, Gaussian GWR on it is a well-defined least-squares problem, and the advice to switch to a binomial family is nonsense for such values. The hard stop is now gated on the response also being integer-like, which is what the surrounding code already used to separate coded categories from measurements. A two-valued non-integer response raises awarning()naming the two values and asking you to confirm it is genuinely continuous, then fits. This also mattered insidecv_gwr(), where the guard runs once per fold and a small training fold can legitimately hold only two distinct values.determine_optimal_levels()no longer reports a Moran’s I that is arithmetically fixed. This changes which cell counts it returns..morans_i_for_k()builds amin(8, n_cells - 1)-nearest-neighbour weight matrix, so at nine cells or fewer every cell neighbours every other one. The row-standardised matrix is then complete,W %*% e = -e/(n - 1)for any mean-zero residual vector, and Moran’s I collapses to exactly-1/(n_cells - 1)whatever the data are. That is not merely uninformative:|I| = 1/(n_cells - 1)falls monotonically in the number of cells, socriterion = "morans_i"ranked the largest evaluated candidate first every time, and"combined"carried the same tilt at half weight. Candidates below the floor now returnNA_real_and are excluded from the model-aware ranking; when none clears it (the usual outcome at the defaultmax_levels = 12, since the search evaluates a window around the elbow) the call falls back to the geometric ranking and logs a warning. Raisemax_levelsabove roughly 10 for the model-aware criteria to contribute at all.predictor_varsalso accepts logical columns now, read as 0/1, matchingfit_rf_model()/cv_rf()/predict(); factor and character predictors are still refused by name.residual_morans_i(fit, k = 1)no longer errors with “subscript out of bounds” on a machine withoutFNN. In the dense fallback the inner function returns a scalar atk = 1, soapply()simplified the neighbour table to a length-n vector andt()made it a 1 × n matrix; indexingnn_idx[i, ]then failed for everyi > 1. The result is now forced ton × k.make_folds()no longer dies on an empty or non-finite geometry.st_coordinates()yields one all-NArow per EMPTY POINT rather than zero rows, so a row-count check let them through:block_kfold’sst_intersects()returnedinteger(0),..block_idwentNA, and the nearest-block rescue aborted with “replacement has length zero”. Unusable rows are now dropped with a warning naming the count, after..row_idis stamped so the survivors keep their original row identities, and for every method rather than justblock_kfold;random_kfoldwould otherwise put an unplottable point in a fold, andnndmandbuffered_looboth feed the coordinates to distance code. The rescue itself usesvapply()rather thanapply(), so a point whose distances are allNAkeeps itsNAinstead of collapsing the assignment.points_sfwith no usable coordinates at all is an error naming that, not a downstream one.Every cross-validation wrapper names the cause when folds fail.
.cv_run_folds()returns each fold’s error text rather than a bareNULL, andcv_gwr(),cv_bayes()andcv_spatial()appendFirst error: ...to both the logged and the R-level “all N folds failed” message. Runningcv_bayes()withoutbrmsinstalled previously produced fivefold N fit failedwarnings and an all-NA$overallwithn_pred = 0in which the word “brms” never appeared.The package’s log lines no longer depend on the user’s global
loggerconfiguration.loggerseeds a new namespace from the global one, so the"spatialkit"namespace inherited whatever formatter the user had set before loading, and every logging helper handsloggeran already formatted string. Under a user’sformatter_sprintf, every package message containing a literal%, the CRS distortion figures inensure_projected(), the local collinearity percentage infit_gwr_model(), hard-errored with “too few arguments”, and because the helper logs before it raises the R warning, the warning the manual promises died with it. Under the defaultformatter_gluea{...}inside a fold error was re-evaluated. The namespace’s formatter is now pinned toformatter_paste, so the message logged is the message written.fit_bayesian_spatial_model(backend = "auto")chooses cmdstanr only when a CmdStan build is actually available. It chose it whenever the cmdstanr package could be loaded (a thin interface that is often installed without the toolchain it drives) so on such a machine every fit died inside the sampler with “CmdStan path has not been set yet. See ?set_cmdstan_path”. The package’s own weeklycheck-brmsjob was one such machine: it installs cmdstanr to satisfy Suggests and never builds CmdStan, and every scheduled run since the Stan smoke tests landed failed there. “auto” now falls back to rstan, which brms always brings, and logs the choice; an explicitbackend = "cmdstanr"with no usable build is an error that says to runcmdstanr::install_cmdstan().cv_bayes(seed = )reaches the sampler.fit_bayesian_spatial_model()carriesseed = 123and the per-foldfit_argsnever set it, so every fold of every run sampled from Stan seed 123 and changingseedchanged nothing on fixed folds. Each fold now draws its own sampler seed from the fold’s seeded stream, ascv_rf()does for the forest; aseedinfit_argsstill overrides it for every fold.cv_*(seed = NULL)is reproducible fromset.seed()underparallel > 1, as the README promised without qualification. Withseed = NULLno per-fold seeds were drawn, so each forked worker was seeded bymclapply()from the clock and the process ID; three runs after the sameset.seed(777)gave 0.5687, 0.5649 and 0.5623 while the sequential call was reproducible. The per-fold seeds are now drawn from the caller’s current stream (advancing it, as any RNG-consuming call would), so the sequential and parallel paths are the same function of the stateset.seed()left.Warnings raised inside a fold reach the caller from the parallel path. R conditions do not cross a fork, so under
parallel > 1every warning raised by the model, includingfit_gwr_model()’s documented integer-response warning, raised in every fold, reached nobody, while the numbers came back identical and the run looked like a clean version of the same analysis. The worker now collects them and the parent re-raises each distinct message once.cv_spatial()(and thereforecv_rf()) returns the same typed, zero-rowfold_metricsframe ascv_gwr()andcv_bayes()when every fold failed, sosubset(fold_metrics, RMSE < 5)works instead of erroring on a missing column.residual_morans_i()refusesklarge enough to make the neighbour matrix dense. The only size guard (n > 5000) applied to the dense fallback; with FNN and Matrix present,k >= n - 1allocatedn (n − 1)pairs unguarded. Requests above 2e7 pairs are now an error namingkandn.
New features
-
New
fit_rf_model()andcv_rf(): arangerrandom forest as a first-class backend, returning anrf_fitthat works withcv_spatial(),predict_surface(),area_of_applicability()andplot()like any other model. Three defaults are opinionated:include_coords = FALSE(a forest given the coordinates memorises location and fails wherever it has not been, Meyer et al. 2019, https://doi.org/10.1016/j.ecolmodel.2019.108815, and random CV does not catch it);fitted()returns out-of-bag predictions, sosummary()on anrf_fitis not comparable with the other backends and says so ($info$fitted_are_oob); and importance defaults to permutation rather than impurity, which is biased toward continuous and high-cardinality predictors (Strobl et al. 2007, https://doi.org/10.1186/1471-2105-8-25). Compare backends withcompare_models_cv(), which now has an RF branch.predict()on anrf_fitrefuses the type confusionsrangerwould otherwise absorb silently: a numeric-at-fit predictor supplied as text (which ranger factor-codes, then applies numeric split thresholds to the codes), a logical-at-fit predictor supplied as text, and a categorical level the forest was never grown with; the level set is not enough, since a spatial fold holding out a whole class leaves a level with no training rows. Arguments that make ranger return a matrix (predict.all = TRUE,type = "quantiles") are rejected rather than flattened column-major. A constant seed is supplied to ranger’s predict unless the caller passes one, so prediction does not consume the global RNG andpredict_surface(chunk_size = )(a performance knob) cannot shift later random draws.cv_rf(seed = )reaches the forest in every fold, and gainspointize. Passing ranger’s own spelling of an argument the wrapper already sets (num.trees,min.node.size,num.threads,mtry,importance,seed) through...is an error naming the wrapper argument to use, rather than reachingranger()twice.num_threadsdefaults togetOption("mc.cores", 1L)(one thread unless the session has opted in) for both the fit andpredict(), rather than ranger’s own default of every core on the machine, andcv_rf(parallel = )runs each forked fold’s forest on one thread unless told otherwise, so the worker count is never multiplied by a thread count. See?fit_rf_model. Every
cv_*()andcompare_models_cv()acceptfoldsas a vector of fold labels, one per row (such asmake_folds()$assignment$fold), in addition to amake_folds()result and a list oftrain/testsplits, the three shapesarea_of_applicability()already took. The label vector used to fail with R’s “$ operator is invalid for atomic vectors”.-
New
area_of_applicability(), implementing the dissimilarity index of Meyer & Pebesma (2021, https://doi.org/10.1111/2041-210X.13650). Predictors are centred and scaled on the training data’s own statistics, optionally weighted by variable importance (by the importance itself, not its square root, matchingCAST). A prediction point’s DI is its distance to the nearest training point in that space over the mean pairwise training distance, and the threshold is the outlier-removed maximum of the training data’s own DI. Pass themake_folds()result you actually validated with; the area is defined relative to a performance estimate, and a blocked estimate is a claim about predicting further away.A model fitted with
include_coords = TRUEis measured in coordinate space, since an index that ignores location would report a point far outside the training extent as inside on ordinary covariate values alone; weights for the two coordinate columns default to the mean of those supplied, as the caller has never seen them. Non-POINTnewdatais reduced to points, and a CRS present on one side is applied to the other. The zero-variance test is relative to each column’s magnitude rather than an absolute tolerance, so a predictor is not dropped for the unit it was recorded in. Categorical predictors are refused rather than dummy-coded; logicals are read as 0/1. Amake_folds()result is resolved by its..row_idvalues, which coincide with row positions only when the input carried no prior IDs. See?area_of_applicability. New
select_features_forward(): greedy forward feature selection with spatially blocked inner folds, which is the whole point of having it. Random inner folds inside blocked outer folds select variables that look predictive only because nearby points leak between train and test, and the outer loop then reports honest-looking numbers for a dishonestly chosen feature set.methoddefaults to"block_kfold"and logs a warning if set to"random_kfold". The empty set is scored first where the backend can fit it, so the first variable is judged against a null-model baseline rather than accepted unconditionally, andhistorycarries that baseline as astep = 0row. Every candidate set is scored on the same observations (the completeness filter matchesprep_model_data()exactly, finiteness test included, so a candidate carrying a singleInfcannot be preferred for having an easier subset), and the inner folds are built once, before the sweep, rather than rebuilt per candidate. Amax_fitsbudget guards against nesting a sweep inside leave-one-out outer folds. Where the backend cannot fit the empty set at all (fit_rf_model()andfit_gwr_model()both refuse a zero-lengthpredictor_vars), the probe is silent on the console: its per-fold failures go to the file trace only, rather than printing the same lines a genuinely failed run prints.New
gwr_model_selection(): wrapsGWmodel::gwr.model.selection()(Lu et al. 2014, https://doi.org/10.1080/10095020.2014.917453) and returns a ranked table instead of two loosely-coupled lists. It is the fast, in-sample counterpart toselect_features_forward(); the same forward search scored by AICc, read from the documentedc(bandwidth, AIC, AICc, RSS)layout of GWmodel’sGWR.df, which carries no column names; the result records whether the table arrived in that shape. Candidates must be numeric, anddmat_max_n = Infmeans always precompute the distance matrix. Both limitations are documented rather than papered over: one bandwidth is shared by every candidate (which is what makes the criteria comparable), and the null model is never evaluated, so the result always names at least one predictor. When it disagrees with the blocked estimate, believe the blocked estimate. See?gwr_model_selection.New
predict_surface(): builds a regular grid over the training extent (or a grid you supply), joins covariates, predicts in chunks and returnssf. Supportsboundaryclipping,cell_sizeor approximaten_cells, andse = TRUEfor a posterior-SD surface where the backend exposes draws.New
plot()method forspatial_fit, withtype = "residuals","observed_predicted"and"variogram"(the empirical residual variogram with the fitted model and effective range overlaid, so the fit can be judged rather than trusted). The variogram’s distance axis is labelled in the units of the CRS it was actually fitted in (metres of an auto-chosen zone for a lon/lat fit, not the caller’s degrees), it names the azimuth when a single direction is drawn, and a fit that did not converge says so in the caption. Newplot_folds()maps a fold scheme, which is the fastest way to see whether spatial blocks separate the data or are smaller than the autocorrelation range and therefore leaking.make_folds()gainsmethod = "leave_location_out", which keeps every observation from a location (named by the newgroup_var) in the same fold. Repeated measurements at one site were previously unrepresentable: random k-fold splits them across folds, so the model is scored partly on sites it trained on.make_folds()gainsmethod = "nndm", implementing the distance-matching principle of Milà et al. (2022, https://doi.org/10.1111/2041-210X.13851), as inCAST::nndm(). Rather than choosing abufferwith nothing to justify it, the exclusion around each held-out point is sized so the training-to-test distance distribution reproduces the distances from your actual prediction locations (the newprediction_points) to the training data. The procedure follows the paper’s iterative exclusion removal for removal and is deterministic: no random numbers are drawn, so the caller’s RNG is untouched, and ties in the nearest-neighbour distance (every mutual-nearest-neighbour pair, all of a regular grid) are broken by the point’s position rather than by its row index, so identical data give identical folds whatever order the rows arrive in (CASTbreaks them by row).params$target_median,params$realised_medianandparams$max_ecdf_excessrecord how close the match came, andmin_train(default 0.5) andphicontrol it. Matching is as close as the training configuration permits; the achievable distances are discrete order statistics. When prediction locations sit no further from the training data than training points sit from each other, plain leave-one-out already reproduces the target and nothing is excluded; that is the correct outcome. A non-POINTprediction_pointslayer is reduced to points first, since point-to-polygon distances are zero for any cell containing a training point and would collapse the scheme towards plain LOO.summarize_by_cell()gainsdeff = "variogram", computing a per-cell design effect from a fitted variogram rather than one pooled intra-class correlation. Fornpoints in a cell with correlation matrixRthe effective sample size of the mean isn^2 / sum(R), sodeff = sum(R) / n. This generalises the Kish option (a constant off-diagonal correlation recovers1 + (n - 1) * rhoexactly) but lets correlation decay with distance, which is what having fitted a variogram is for. Pass the fit via the newsacargument, or it is estimated whenresponse_varis supplied, and it is fitted to the response, not on OLS residuals, even whenpredictor_varsare listed: the..se_resp_*columns estimate the SE of the cell mean as an estimate of the response’s grand mean, so the correlation to correct for is the response’s own (measured grand-mean coverage 0.93 with the response variogram against 0.51 with the residual one on a field with a smooth predictor). Pass a residual variogram throughsacif that is the field you want. Large cells are subsampled atdeff_max_n(default 500), with the correlation scaled back to the cell’s own size. Asac_rangewhose fit was rejected carries no usable correlation function, so both the supplied and the internally estimated path fall back todeff = 1and say so rather than saturating the correlation at every within-cell distance. One correlation function is fitted and applied to every numeric column, response and predictors alike, because a variogram is a property of the field rather than of a variable type.fit_bayesian_spatial_model()supports intercept-only models (predictor_vars = character(0)): the response is explained by the intercept and the spatial GP alone, the natural null for asking how much of a surface is spatial structure rather than covariate effect.fit_bayesian_spatial_model()checks the posterior length-scale against the smallest scale the chosen basis can resolve and logs a warning when more than 10% of the posterior mass falls below it, the adequacy diagnostic recommended by Riutort-Mayol et al. (2023, https://doi.org/10.1007/s11222-022-10167-2), and what makes the smaller defaultgp_ksafe rather than merely cheaper.$infogainsgp_c,gp_n_basis,gp_ell_minandgp_lengthscale_bounds, andprint()on abayesian_fitandcv_bayes()’sfold_metricsreport the total basis count alongside the per-dimension rank.cv_spatial()raises a condition when folds fail, matchingcv_gwr()andcv_bayes(); an all-failingfit_fnpreviously returned an all-NAoveralland an emptyfold_metricswith nothing at R condition level. The result recordsn_folds_attemptedandn_folds_succeeded; compare them before trustingoverall.make_folds()records the CRS the folds were built in asparams$crs("EPSG:32632", an input string, or a WKT).block_sizeandsac_rangeare lengths in that CRS, which is not necessarily the one the caller passed: geographic input is projected byensure_projected()to a CRS chosen for the extent. Without the label the units of a recorded block size were not recoverable from the result.spatialkit_quiet()is a new exported helper. Bothlogger::log_appender()andlogger::log_threshold()default toindex = 1, which is the temp-file trace, so the two-line recipe in the README could not redirect or quieten the console echo (index 2); there was no documented way to silence the package. The README now says so too.
Documentation
estimate_sac_range()documents its three return shapes (a range, a rejected range, and no fit at all) and which attributes each carries.make_folds()documents thatkis not always honoured:buffered_looandnndmalways returnk = n, andblock_kfoldandleave_location_outlower it when the geometry or the grouping cannot support the request. Readfolds$k.new_spatial_fit()documents thecoef()contract;summary.spatial_fit()andmodel_metrics()document that their metrics are in-sample for agwr_fitand abayesian_fitbut out-of-bag for anrf_fit;prep_model_data()documents that the projected CRS is not an unconditional guarantee, sinceensure_projected()passes a CRS-less dataset through unchanged when its coordinates do not look like lon/lat.The vignette and
inst/scripts/example_nc_demo.Rread fit quality fromfit$metrics$r_squaredand CV results fromcv$summary$rmse. Neither field has ever existed. Becausesprintf()returnscharacter(0)when any argument has length zero, the reporting lines printed nothing rather than erroring, so the shipped vignette silently omitted every number it claimed to show. Both now usemodel_metrics()and$overall.The demo’s Voronoi tessellation was built from all 300 observations rather than from the 40 k-means seeds it computed one line earlier, one cell per observation, a nearest-neighbour interpolation rather than an aggregation, compared side by side against two ~50-cell grids. The seeds are now used.
The vignette builds as
rmarkdown::html_vignetterather thanhtml_document, guards itsggplot2andgeometryuse, demonstratessummarize_by_cell()instead of reimplementing it withgroup_by()/summarise(), and adds a spatial cross-validation section contrastingblock_kfoldagainstrandom_kfoldon the same data.The package-level help page (
?spatialkit) gains “The pipeline, in order” and “Where to start” sections, sohelp(package = "spatialkit")leads somewhere rather than presenting 40 exports in alphabetical order.Every exported function’s description now says when to reach for it rather than only what it does, and
@family/@seealsolinks connect each step of the pipeline to the one before and after it:assign_features_to_polygons()tosummarize_by_cell(),determine_optimal_levels()tobuild_tessellation(),new_spatial_fit()tocv_spatial(), and the two seeding functions to each other.create_voronoi_polygons()versuscreate_grid_polygons(), andvoronoi_seeds_kmeans()versusvoronoi_seeds_random(), each say which to pick and why.build_tessellation()documents thatboundaryis required formethod = "hex"andmethod = "square"(the grid methods have no extent of their own) and optional for"voronoi"and"triangles", which derive one from the points. The error existed; the requirement was not written down anywhere.create_grid_polygons()documents thattarget_cells,cellsizeandnare three ways of sizing one grid and that exactly one should be supplied, thatcellsizeis in the units of the working CRS, and thatcellsizetakes precedence overn.determine_optimal_levels()documents the nine-cell resolution floor on the model-aware criteria, why it exists, and that the whole call falls back to the geometric ranking when no candidate clears it.compare_models_cv()documents that dropping every requested backend is an error ("no viable models.") rather than an empty comparison, and that the returned frame carries only the models that actually ran, so callers should check which names are present rather than assuming one row per request.new_spatial_fit()documents the two obligations on a custom backend: return an object built by the constructor, and define apredict.<subclass>()method, becausecv_spatial()scores folds through thepredict()generic, so without one every fold fails.README. A new “Your own data” section shows both entry points,
st_read()for a spatial file andread.csv()+st_as_sf()for a table of coordinates, using thenc.shpdemo shapefile shipped withsfso it runs anywhere. The README previously manufactured every example inline with a hard-codedcrs = 32632and never showed data entering the package at all. A companion “CRS: what the numbers are in” subsection states that block sizes, buffers, bandwidths, variogram ranges andexpanddistances are in the units of the working CRS; that geographic input is projected automatically to a CRS chosen for the extent; and how to pin one.README. New guidance where none existed: how to choose among the four tessellation methods, how
kandblock_sizetrade off against the autocorrelation range, what to do whenestimate_sac_range()returnsNA, how to read a design effect, which model backend to reach for (with the recorded cost of each), and a “Troubleshooting” section covering the errors a new user actually hits first. A worked hex-grid example replaces the previous picture-only coverage of the grid methods.README. Three corrections. The
estimate_sac_range()example showed a rejected range printing its attributes, whichprint.sac_range()has not done since the attribute dump was removed; it now shows the bareNAand reads the attributes explicitly. Thedetermine_optimal_levels()passage claimed the residual-autocorrelation criterion was doing work at cell counts where it is arithmetically degenerate. The test-suite paragraph said “exactly one” test guards onbrms; six do, five of them additionally gated behindSPATIALKIT_TEST_BRMSso they never run in the matrix.inst/scripts/example_nc_demo.Rsaid EPSG:2264 was projected “so distances are metric”. Its unit is the US survey foot, which is what the script’s own “Autocorrelation range: %.0f ft” line reports. The comment now says planar, and names the unit every distance, bandwidth and block size in the script is in.Vignette.
print(rf_fit)andsummary(rf_fit)report the same OOB RMSE but different R² (0.4733 against 0.4715). The vignette now explains why:print.rf_fit()echoesranger’sr.squared(1 - MSE/var(y), unbiased n − 1 variance) whilesummary()recomputes1 - SS_res/SS_totfrom the same out-of-bag predictions with an n denominator, so the unexplained fractions differ by exactly n/(n − 1).Every exported function has runnable examples: the eleven that shipped without any (
clear_fitted_cache(),clear_grid_cache(),clip_target_for(),compare_models(),create_grid_polygons_cached(),ensure_stable_poly_id(),evaluate_insample(),harmonize_crs(),model_metrics(),voronoi_seeds_kmeans()andvoronoi_seeds_random()) gained one, and the two\dontrun{}blocks say why they cannot be run (a Stan toolchain and minutes of MCMC).residual_morans_i()’s default null is described correctly:null = "auto"uses the Cliff & Ord regression-residual moments whenever the residuals are OLS residuals on the rebuilt design, and the randomisation null otherwise; the README said “the randomisation variance” without qualification. The type-I error of a random forest’s residual test is attributed to what the package actually feeds it (out-of-bag residuals, which are honest out-of-sample errors with their own spatial structure) not to “shrunk in-sample residuals”.determine_optimal_levels()gives the real reason for its nine-cell floor (the standardised deviate is 0/0 there, so the criterion carries no information) rather than an argument from|I|that its own details section had just called wrong.summarize_by_cell()notes that the “use the naive SE for the cell’s own mean” advice is calibrated under uniform within-cell sampling.cv_gwr(bandwidth = )states its units and semantics like its siblings.quietis documented as “suppress this function’s progress messages” everywhere, with a pointer tospatialkit_quiet()for the console log echo it does not touch.README: the square-grid call returns 36 cells, not 32; the installation section no longer promises a specific version from CRAN; the resolution figure and the quick-start output are regenerated for the elbow-first ordering (
4 3 5,k = 4).The DESCRIPTION now cites the methods it implements (Lu et al. (2014) for
GWmodel, Riutort-Mayol et al. (2023) for the Hilbert space Gaussian process, Strobl et al. (2007) for the permutation importance, Mila et al. (2022) for NNDM folds and Meyer and Pebesma (2021) for the area of applicability), each with its DOI, and quotes only software names. The Riutort-Mayol reference onfit_bayesian_spatial_model()’s help page gives the article number (33, 17) rather than “33, 1”.No example is wrapped in
\donttest{}any more: the fifteen that were (every fit, cross-validation, comparison, plotting and surface example that needs a Suggests package) run unconditionally behind theirrequireNamespace()guards, the slowest in under 2 s. The two Stan examples (fit_bayesian_spatial_model(),cv_bayes()) keep\dontrun{}because they need a C++ toolchain and minutes of MCMC, and say so in a leading comment.
spatialkit 1.0.0
CRAN release: 2026-08-07
First CRAN release, published 2026-08-07.
- CRS management:
ensure_projected(),harmonize_crs(),coerce_to_points(),prep_model_data(). - Voronoi, hexagonal, square and Delaunay tessellation (
build_tessellation()and thecreate_*_polygons()functions), with boundary clipping, stable reproducible cell IDs (ensure_stable_poly_id()) and a memoised grid builder (create_grid_polygons_cached()). - Seeding (
get_voronoi_seeds(),voronoi_seeds_kmeans(),voronoi_seeds_random()) and resolution selection (determine_optimal_levels()). - Feature-to-polygon assignment (
assign_features_to_polygons()) and cell-level aggregation with design-effect-corrected standard errors (summarize_by_cell()). - GWR (
fit_gwr_model()) and Bayesian spatial Gaussian process (fit_bayesian_spatial_model()) backends behind a commonspatial_fitS3 class. - Spatial cross-validation:
make_folds()withrandom_kfold,block_kfoldandbuffered_loo;estimate_sac_range();cv_gwr(),cv_bayes()andcv_spatial(). - Model comparison and diagnostics:
compare_models(),compare_models_cv(),evaluate_insample(),residual_morans_i(). - Tessellation mapping (
plot_tessellation_map()) and scoped logging.