Skip to content

Commit

Permalink
correcting bug from issue 8
Browse files Browse the repository at this point in the history
  • Loading branch information
JeremyGelb committed Nov 17, 2024
1 parent 4dd7cd1 commit bc4683d
Show file tree
Hide file tree
Showing 210 changed files with 4,809 additions and 927 deletions.
4 changes: 2 additions & 2 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Package: geocmeans
Type: Package
Title: Implementing Methods for Spatial Fuzzy Unsupervised Classification
Version: 0.3.4
Version: 0.3.4.1
Authors@R: c(
person("Jeremy", "Gelb", email = "jeremy.gelb@ucs.inrs.ca",role = c("aut", "cre"), comment = c(ORCID = "0000-0002-7114-2714")),
person("Philippe", "Apparicio", email="philippe.apparicio@ucs.inrs.ca", role=c("ctb"), comment = c(ORCID = "0000-0001-6466-9342"))
Expand Down Expand Up @@ -54,7 +54,7 @@ Suggests:
License: GPL-2
Encoding: UTF-8
LazyData: true
RoxygenNote: 7.2.3
RoxygenNote: 7.3.2
VignetteBuilder: knitr
Description: Provides functions to apply spatial fuzzy unsupervised classification, visualize and interpret results. This method is well suited when the user wants to analyze data with a fuzzy clustering algorithm and to account for the spatial dimension of the dataset. In addition, indexes for estimating the spatial consistency and classification quality are proposed.
The methods were originally proposed in the field of brain imagery (seed Cai and al. 2007 <doi:10.1016/j.patcog.2006.07.011> and Zaho and al. 2013 <doi:10.1016/j.dsp.2012.09.016>) and recently applied in geography (see Gelb and Apparicio <doi:10.4000/cybergeo.36414>).
Expand Down
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# geocmeans 0.3.4.1

Minor bug correction (issue #8)

# geocmeans 0.3.4

Final update before resubmitting to CRAN and to JOSS
Expand Down
4 changes: 2 additions & 2 deletions R/boostrap_clust_validation.R
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ boot_group_validation <- function(object, nsim = 1000, maxiter = 1000, tol = 0.0
rast <- object$rasters[[1]]
vec <- rep(NA, times = terra::ncell(rast))
vec[object$missing] <- object$Data[,i]
terra::values(rast, mat = FALSE) <- vec
terra::values(rast) <- vec
return(rast)
})
wdata <- calcWdataRaster(object$window, dataset, object$lag_method, object$missing)
Expand Down Expand Up @@ -244,7 +244,7 @@ boot_group_validation.mc <- function(object, nsim = 1000, maxiter = 1000, tol =
rast <- object$rasters[[1]]
vec <- rep(NA, times = terra::ncell(rast))
vec[object$missing] <- object$Data[,i]
terra::values(rast, mat = FALSE) <- vec
terra::values(rast) <- vec
return(rast)
})
wdata <- calcWdataRaster(object$window, dataset, object$lag_method, object$missing)
Expand Down
236 changes: 236 additions & 0 deletions R/compositional_methods.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
# # data(LyonIris)
# # AnalysisFields <-c("Lden","NO2","PM25","VegHautPrt","Pct0_14","Pct_65","Pct_Img",
# # "TxChom1564","Pct_brevet","NivVieMed")
# # dataset <- sf::st_drop_geometry(LyonIris[AnalysisFields])
# # queen <- spdep::poly2nb(LyonIris,queen=TRUE)
# # Wqueen <- spdep::nb2listw(queen,style="W")
# # result <- SFCMeans(dataset, Wqueen,k = 5, m = 1.5, alpha = 1.5, standardize = TRUE)
# #
# # library(compositions)
# #
# # x <- result$Belongings
# # listw <- Wqueen
# #
# #
# #
# # cmp_geary <- function(x, listw){
# #
# # cmp <- acomp(x)
# # x_clr <- as.matrix(clr(cmp))
# #
# # sums_ij <- sapply(1:nrow(x_clr), function(i){
# # ri <- x_clr[i,]
# # diffs <- sapply(listw$neighbours[[i]], function(j){
# # rj <- x_clr[j,]
# # sum((ri - rj) ** 2)
# # })
# # sub_sum <- sum(listw$weights[[i]] * diffs)
# # return(sub_sum)
# # })
# #
# # numerator <- (nrow(x_clr) - 1) * sum(sums_ij)
# # S0 <- sum(sapply(listw$weights, sum))
# # x_bar <- colMeans(x_clr)
# # diff_mean <- sum(c(sweep(x_clr, 2, x_bar, "-")**2))
# #
# # C <- numerator / (2*S0 * diff_mean)
# #
# # }
#
#
# spConsistency <- function(object, nblistw = NULL, window = NULL, nrep = 999, adj = FALSE, mindist = 1e-11, use_clr = FALSE) {
#
# if(inherits(object, "FCMres")){
# belongmat <- as.matrix(object$Belongings)
# if(object$isRaster & is.null(window)){
# window <- object$window
# if(is.null(window)){
# stop("impossible to find a window in the given object, please
# specify one by hand.")
# }
# }
# if(object$isRaster == FALSE & is.null(nblistw)){
# nblistw <- object$nblistw
# }
# }else{
# belongmat <- as.matrix(object)
# }
#
# # if we are not in raster mode
#
# if(is.null(window)){
#
# if(is.null(nblistw)){
# stop("The nblistw must be provided if spatial vector data is used")
# }
# weights <- nblistw$weights
# neighbours <- nblistw$neighbours
# ## calcul de l'inconsistence spatiale actuelle
#
# if(use_clr){
# belong_mat <- clr(acomp(belongmat))
# }
# # we could aslo use the Aitchison distance (https://ima.udg.edu/~barcelo/index_archivos/Measures_of_difference__Clustering.pdf)
# # this is simply done by calculating the clr transformation on the original data
# # belongmat <- log(belongmat)
# # belongmat <- sweep(belongmat, 1, rowMeans(belongmat), "-")
# # belongmat <- as.matrix(belongmat)
#
# obsdev <- sapply(1:nrow(belongmat), function(i) {
# row <- belongmat[i, ]
# idneighbour <- neighbours[[i]]
# neighbour <- belongmat[idneighbour, ]
# if (length(idneighbour) == 1){
# neighbour <- t(as.matrix(neighbour))
# }
# W <- weights[[i]]
# # we are using here the euclidean distance
# diff <- (neighbour-row[col(neighbour)])**2 * W
# tot <- sum(rowSums(diff))
# return(tot)
# })
#
# totalcons <- sum(obsdev)
#
# ## simulation de l'inconsistance spatiale
# belongmat <- t(belongmat)
# n <- ncol(belongmat)
# simulated <- vapply(1:nrep, function(d) {
# belong2 <- belongmat[,sample(n)]
# simvalues <- vapply(1:ncol(belong2), function(i) {
# row <- belong2[,i]
# idneighbour <- neighbours[[i]]
# neighbour <- belong2[,neighbours[[i]]]
# if (length(idneighbour) == 1){
# neighbour <- t(as.matrix(neighbour))
# }
# W <- weights[[i]]
# diff <- (neighbour-row)
# tot <- sum(diff^2 * W)
# return(tot)
# }, FUN.VALUE = 1)
# return(sum(simvalues))
# },FUN.VALUE = 1)
# ratio <- totalcons / simulated
#
# # if we are using a raster mode.
# }else{
# # we must calculate for each pixel its distance to its neighbours
# # on the membership matrix. So we will calculate the distance for each
# # raster in object$rasters and then sum them all group
# rastnames <- names(object$rasters)
# ok_names <- rastnames[grepl("group",rastnames, fixed = TRUE)]
# rasters <- object$rasters[ok_names]
# matrices <- lapply(rasters, terra::as.matrix, wide = TRUE)
# mat_dim <- dim(matrices[[1]])
#
# if(use_clr){
# big_mat <- do.call(cbind,lapply(matrices, c))
# big_mat <- clr(acomp(big_mat))
# matrices <- lapply(1:ncol(big_mat), function(i){
# mat <- big_mat[,i]
# dim(mat) <- mat_dim
# return(mat)
# })
# }
#
# # applying the
#
# if(adj){
# dataset <- lapply(1:ncol(object$Data), function(ic){
# vec1 <- object$Data[,ic]
# vec2 <- rep(NA,length(object$missing))
# vec2[object$missing] <- vec1
# rast <- object$rasters[[1]]
# terra::values(rast) <- vec2
# mat <- terra::as.matrix(rast, wide = TRUE)
# return(mat)
#
# })
# totalcons <- calc_raster_spinconsistency(matrices, window, adj, dataset, mindist = mindist)
#
# }else{
# totalcons <- calc_raster_spinconsistency(matrices,window)
# }
#
#
# # we must now do the same thing but with resampled values
# warning("Calculating the permutation for the spatial inconsistency
# when using raster can be long, depending on the raster size.
# Note that the high number of cell in a raster reduces the need of
# a great number of replications.")
# # creating a vector of ids for each cell in raster
# all_ids <- 1:terra::ncell(rasters[[1]])
#
# # converting the matrices (columns of membership matrix) into 1d vectors
# mem_vecs <- lapply(rasters, function(rast){
# mat <- terra::as.matrix(rast, wide = TRUE)
# dim(mat) <- NULL
# return(mat)
# })
#
# # if necessary, doing the same with the original data
# if(adj){
# data_vecs <- lapply(dataset, function(mat){
# vec <- mat
# dim(vec) <- NULL
# return(vec)
# })
# }
# # extracting the dimension of the raster
# #dim(terra::as.matrix(rasters[[1]]))
#
# # starting the simulations
# simulated <- sapply(1:nrep, function(i){
#
# # resampling the ids
# Ids <- sample(all_ids)
#
# # resampling the matrices of memberships
# new_matrices <- lapply(mem_vecs, function(vec){
# new_vec <- vec[Ids]
#
# # swapping the NA at their original place
# val_na <- new_vec[!object$missing]
# loc_na <- is.na(new_vec)
# new_vec[!object$missing] <- NA
# new_vec[loc_na] <- val_na
#
# dim(new_vec) <- mat_dim
# return(new_vec)
# })
#
# if(adj){
# # resampling the matrices of the data
# new_dataset <- lapply(data_vecs, function(vec){
# new_vec <- vec[Ids];
#
# # swapping the NA at their original place
# val_na <- new_vec[!object$missing]
# loc_na <- is.na(new_vec)
# new_vec[!object$missing] <- NA
# new_vec[loc_na] <- val_na
#
# dim(new_vec) <- mat_dim
# return(new_vec)
# })
# # calculating the index value
# inconsist <- calc_raster_spinconsistency(new_matrices, window, adj, new_dataset, mindist = mindist)
#
# }else{
# # calculating the index value
# inconsist <- calc_raster_spinconsistency(new_matrices, window)
# }
#
#
# return(inconsist)
# })
# ratio <- totalcons / simulated
# }
#
# return(list(Mean = mean(ratio), Median = quantile(ratio, probs = c(0.5)),
# prt05 = quantile(ratio, probs = c(0.05)),
# prt95 = quantile(ratio, probs = c(0.95)),
# samples = ratio,
# sum_diff = totalcons))
# }
7 changes: 2 additions & 5 deletions R/geocmeans.R
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,6 @@
#' Several indices are provided to assess the quality of a classification on the
#' semantic and spatial dimensions. To explore results, a shiny app is also
#' available
#'
#'
#' @docType package
#' @name geocmeans
#' @keywords internal
NULL
"_PACKAGE"

4 changes: 2 additions & 2 deletions R/shinyapp.R
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ sp_clust_explorer <- function(object = NULL, spatial = NULL, membership = NULL,
## prepare the leaflet maps in the first pannel ***************************************

mymap <- leaflet(height = "600px") %>%
addProviderTiles(leaflet::providers$Stamen.TonerBackground, group = "Toner Lite", layerId = "back1") %>%
addProviderTiles(leaflet::providers$Stadia.StamenTonerBackground, group = "Toner Lite", layerId = "back1") %>%
addProviderTiles(leaflet::providers$OpenStreetMap, group = "Open Street Map", layerId = "back2")

if(rasterMode == FALSE){
Expand Down Expand Up @@ -434,7 +434,7 @@ sp_clust_explorer <- function(object = NULL, spatial = NULL, membership = NULL,

## preparing the map for the third pannel ***************************************
uncertainMap <- leaflet(height = "600px") %>%
addProviderTiles(leaflet::providers$Stamen.TonerBackground, group = "Toner Lite", layerId = "back1") %>%
addProviderTiles(leaflet::providers$Stadia.StamenTonerBackground, group = "Toner Lite", layerId = "back1") %>%
addProviderTiles(leaflet::providers$OpenStreetMap, group = "Open Street Map", layerId = "back2")

if(rasterMode == FALSE){
Expand Down
11 changes: 11 additions & 0 deletions R/spatial_indices.R
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,13 @@ spConsistency <- function(object, nblistw = NULL, window = NULL, nrep = 999, adj
weights <- nblistw$weights
neighbours <- nblistw$neighbours
## calcul de l'inconsistence spatiale actuelle

# we could aslo use the Aitchison distance (https://ima.udg.edu/~barcelo/index_archivos/Measures_of_difference__Clustering.pdf)
# this is simply done by calculating the clr transformation on the original data
# belongmat <- log(belongmat)
# belongmat <- sweep(belongmat, 1, rowMeans(belongmat), "-")
# belongmat <- as.matrix(belongmat)

obsdev <- sapply(1:nrow(belongmat), function(i) {
row <- belongmat[i, ]
idneighbour <- neighbours[[i]]
Expand All @@ -95,6 +102,7 @@ spConsistency <- function(object, nblistw = NULL, window = NULL, nrep = 999, adj
neighbour <- t(as.matrix(neighbour))
}
W <- weights[[i]]
# we are using here the euclidean distance
diff <- (neighbour-row[col(neighbour)])**2 * W
tot <- sum(rowSums(diff))
return(tot)
Expand Down Expand Up @@ -134,6 +142,9 @@ spConsistency <- function(object, nblistw = NULL, window = NULL, nrep = 999, adj
matrices <- lapply(rasters, terra::as.matrix, wide = TRUE)
mat_dim <- dim(matrices[[1]])


# applying the

if(adj){
dataset <- lapply(1:ncol(object$Data), function(ic){
vec1 <- object$Data[,ic]
Expand Down
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@
<!-- badges: start -->

[![R-CMD-check](https://github.com/JeremyGelb/geocmeans/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/JeremyGelb/geocmeans/actions/workflows/R-CMD-check.yaml)
[![](https://img.shields.io/badge/devel%20version-0.3.4-green.svg)](https://github.com/JeremyGelb/geocmeans)
[![](https://img.shields.io/badge/devel%20version-0.3.4.1-green.svg)](https://github.com/JeremyGelb/geocmeans)
[![](https://www.r-pkg.org/badges/version/geocmeans?color=blue)](https://cran.r-project.org/package=geocmeans)
[![](http://cranlogs.r-pkg.org/badges/grand-total/geocmeans?color=blue)](https://cran.r-project.org/package=geocmeans)
[![Codecov test
coverage](https://codecov.io/gh/JeremyGelb/geocmeans/branch/master/graph/badge.svg)](https://app.codecov.io/gh/JeremyGelb/geocmeans?branch=master)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.8316593.svg)](https://doi.org/10.5281/zenodo.8316593)

<!-- badges: end -->

The website of the package is available
Expand Down Expand Up @@ -144,8 +146,12 @@ There is also a shiny app that can be used to go deeper in the result
interpretation. It requires the packages `shiny`, `leaflet`, `bslib`,
`plotly`, `shinyWidgets`, `car`.

![Alt
Text](https://raw.githubusercontent.com/JeremyGelb/geocmeans/master/.github/gif/app_viz.gif)
<figure>
<img
src="https://raw.githubusercontent.com/JeremyGelb/geocmeans/master/.github/gif/app_viz.gif"
alt="Alt Text" />
<figcaption aria-hidden="true">Alt Text</figcaption>
</figure>

#### Spatial diagnostic

Expand Down
Binary file modified data/LyonIris.rda
Binary file not shown.
Loading

0 comments on commit bc4683d

Please sign in to comment.