#	d.hell <- as.matrix(d.hell)
#	Hell <- d.hell[y,]
#
#	Hell <- (sqrt(2)-Hell) / sqrt(2)
#	S <- specnumber(x)
#	Hell[!y & S==0] <- 0
#	res <-data.frame(Hell=Hell, S=S)
#	res
#}
#######################
abiotic$Subset <- factor(abiotic$Subset)
subsets <- levels(abiotic$Subset)
# res.BI <- data.frame(A=numeric(0),B=numeric(0),C=numeric(0),D=numeric(0), Hell = numeric(0), S=numeric(0))
# res.BI <- data.frame(A=numeric(0),B=numeric(0),B1=numeric(0),B2=numeric(0),C=numeric(0),C1=numeric(0),C2=numeric(0),D=numeric(0))
# 21/11/2016
# res.BI <-data.frame(A=numeric(0),B=numeric(0),B1=numeric(0),B2=numeric(0),C=numeric(0),C1=numeric(0),C2=numeric(0),D=numeric(0), B.ref=numeric(0), Score=numeric(0))
res.BI <- data.frame(A=numeric(0),B=numeric(0),C=numeric(0),D=numeric(0), B.ref=numeric(0), B.ref.prime=numeric(0), RugQ=numeric(0))
# 21/11/2016
for (i in subsets) {
biotic[abiotic$Subset==i, ] -> curr.bio
curr.bio <- curr.bio[,colSums(curr.bio)>0]
abiotic[abiotic$Subset==i, ] -> curr.abio
is.ref <- sum(curr.abio$Ref, na.rm=T)
if (is.na(is.ref)) {
warning(paste("NA's in Ref for subset: ",i, ". No Ref assumed."), call. =F)
is.ref <- 0
}
if (is.ref==1) {
# one reference station, compute values for each site,
# write.csv2(curr.bio, "curr.bio.csv")
# write.csv2(curr.abio, "curr.abio.csv")
refs <- as.logical (curr.abio$Ref)
tmp <- LS.wrap(curr.bio, refs, transfo)
#		tmp2 <- BVBI(curr.bio, refs)
#		tmp <- cbind(tmp, tmp2)
tmp
res.BI <- rbind(res.BI, tmp)
res.BI
} else if (is.ref > 1) {
# mulitple reference stations, compute each, take average
n <- nrow(curr.bio)
#	tmp <- data.frame(A=numeric(n),B=numeric(n),C=numeric(n),D=numeric(n))
# tmp <- data.frame(A=numeric(n),B=numeric(n),B1=numeric(n),B2=numeric(n),C=numeric(n),C1=numeric(n),C2=numeric(n),D=numeric(n))
# 21/11/2016
# tmp <- data.frame(A=numeric(n),B=numeric(n),B1=numeric(n),B2=numeric(n),C=numeric(n),C1=numeric(n),C2=numeric(n),D=numeric(n), B.ref=numeric(n), Score=numeric(n))
tmp <- data.frame(A=numeric(n),B=numeric(n),C=numeric(n),D=numeric(n), B.ref=numeric(n), B.ref.prime=numeric(n), RugQ=numeric(n))
# 21/11/2016
#	tmp2 <- data.frame(Hell=numeric(n), S=numeric(n))
refs <- as.logical (curr.abio$Ref)
refs.pos <- which(refs)
names.tmp <- rownames(curr.abio)
for(j in 1:is.ref) {
mult.refs <- logical(length(refs))
mult.refs[refs.pos[j]] <- TRUE
tmp <- tmp + LS.wrap(curr.bio, mult.refs, transfo)
#		tmp2 <- tmp2 + BVBI(curr.bio, mult.refs)
}
if(real.average) {
tmp <- tmp/is.ref
#			tmp2 <- tmp2/is.ref
} else {
tmp <- tmp/is.ref
tmp[curr.abio$Ref == 1, ] <- 0
tmp[curr.abio$Ref == 1, 1] <- 0.5
#			tmp2 <- tmp2/is.ref
#			tmp2$Hell[curr.abio$Ref == 1] <- 1
}
#		tmp <- cbind(tmp, tmp2)
rownames(tmp) <- names.tmp
res.BI <- rbind(res.BI, tmp)
} else {
warning(paste("No reference for subset: ", i, ". No computations.", sep=""), call.=F)
}
}
### fin for
res.abio <- abiotic[rownames(abiotic) %in% rownames(res.BI),]
results <- cbind(res.abio, res.BI)
S <- specnumber(biotic)
results$S <- S[rownames(abiotic) %in% rownames(res.BI)]
#
#results$Date <- as.Date(results$Date, "%d/%m/%Y")
#results$Year <- as.rformat(results$Date, "%Y"))
##############################
#DELTA Bval
#Portion rajout?e par C?line le 7 Juillet 2020
refsub<-subset(results,results$Ref==1)
moyref<-as.data.frame(tapply(refsub$RugQ,refsub$Subset,mean))
moyref$Subset<-rownames(moyref)
colnames(moyref)<-c('Mean','Subset')
results2<-left_join(results,moyref)
results2$Delta<-results2$RugQ-results2$Mean
###############
results2
1 - abs(max(results2$Mean)- results2$RugQ)
gpbi(biotic, abiotic$Refs, detail = TRUE)
biotic <- test.data
abiotic <- data.frame(Refs = c(1,1,1,0,0,0), Subset = "sub1")
# library(vegan)
# data(dune)
# biotic <- dune
# abiotic <- data.frame(Refs = c(1,1, rep(0,18)), Subset = "sub1")
##############
library(dplyr)
######
# do we take the real (TRUE) average with multiple reference or do we force all ref as "good" (FALSE)
real.average <- T
# do we want histogramms of the pressure by subset
pression.histo <- TRUE
# do we sort rows in both tables using "Subset" then "rownames()"
do.sort <- TRUE
# do we need to manage replicate samples ? , if so, specify max area for pooling before random selection and tolerance
# if set to TRUE modified biotic and abitic tables will be written to working directory
do.pool <- F
max.area <- 0.4
tolerance <- 0.1
# Choice of a transformation
#	0	:	none				#	rien
#	1	:	sqrt(x)				#	racine carr?e
#	2	:	sqrt(sqrt(x))		#	double racine carr?e
#	3	:	decostand(x, "pa")	#	pr?sence absence
transfo <- 0
# value for rows to remove
to.remove <- -999
################################################################################################################################################################
################################################################################################################################################################
################################################################################################################################################################
library(stringr)
library(ggplot2)
library(vegan)
######
# define functions
decompose.D.OG <- function(Y1, Y2, den.type=2)#
# Compare two surveys in time observed at T1 and T2:#
# Decompose the Ruzicka and percentage difference dissimilarities into A, B and C.#
##
# Parameters --#
# #
# Y1 : First survey data with sites in rows and species in columns. #
# Y2 : Second survey data with sites in rows and species in columns. #
# The sites and species must be the same in the two tables, and in the same order.#
# The files may contain species presence-absence or quantitative abundance data.#
# #
# den.type -- Denominator type for the indices#
#     1 : (A+B+C) as in the Ruzicka dissimilarity#
#     2 : (2A+B+C) as in the Percentage difference dissimilarity (alias Bray-Curtis)#
##
# Value (output of the function) --#
##
# out1 : A, B and C results, with sites in rows and A, B and C ins columns.#
# out2 : A,B,C,D divided by a denominator [either (A+B+C) or (2A+B+C)]; D = (B+C).#
##
# Details: Numerical results in output matrices --#
# A -- aj is the part of the abundance of species j that is common to the two survey vectors: aj = min(y1j, y2j). A is the sum of the aj values for all species in the group under study. #
# B -- bj is the part of the abundance of species j that is higher in survey 1 than in survey 2: bj = y1j ? y2j. B is the sum of the bj values for all species in the group under study, or the sum of the species losses between time 1 and time 2.#
# C -- cj is the part of the abundance of species j that is higher in survey 2 than in survey 1: cj = y2j ? y1j. C is the sum of the cj values for all species in the group under study, or the sum of the species gains between time 1 and time 2.#
##
# Example --#
# test1 = matrix(runif(50,0,100),10,5)#
# test2 = matrix(runif(50,0,100),10,5)#
# (res = decompose.D2(test1, test2, den.type=1))#
##
# License: GPL(>=2)#
# Author:: Pierre Legendre#
# Modified Olivier Gauthier, 27/04/2016
{#
### Internal function#
# den <- function(A,B,C,den.type) if(den.type==1) den=(A+B+C) else den=(2*A+B+C)#
den <- function(A,B,C,den.type) if(den.type==1) den=(A+B+C) else den=(2*A+B+C)
### End internal function#
##
n = nrow(Y1)#
p = ncol(Y1)#
if(nrow(Y2)!=n) stop("The data tables do not have the same number of rows")#
if(ncol(Y2)!=p) stop("The data tables do not have the same number of columns")#
##
# 21/11/2016
# ABC = c("A","B","B1","B2","C","C1","C2")        # A = similarity, B = losses, C = gains#
# ABCD = c("A","B","B1","B2","C","C1","C2","D", "B.ref", "Score")   # D = dissimilarity#
ABC = c("A","B","C")        # A = similarity, B = losses, C = gains#
ABCD = c("A","B","C","D", "B.ref", "B.ref.prime", "RugQ")   # D = dissimilarity#
##
# out1 = matrix(NA,n,7)#
# colnames(out1) = ABC#
# out2 = matrix(NA,n,10)#
# colnames(out2) = ABCD#
out1 = matrix(NA,n,3)#
colnames(out1) = ABC#
out2 = matrix(NA,n,7)#
colnames(out2) = ABCD#
# 21/11/2016
if(!is.null(rownames(Y1))) { #
rownames(out1)=rownames(out2)=rownames(Y1) #
} else {#
rownames(out1)=rownames(out2)=paste("Site",1:n,sep=".") }#
##
for(i in 1:n) {#
YY = rbind(Y1[i,], Y2[i,])#
A = sum(apply(YY,2,min)) # Sum of the minima; similarity#
tmp = YY[1,] - YY[2,]#
B = sum(tmp[tmp>0])      # Sum of the species losses between time 1 and time 2#
# 21/11/2016
# B1 <- sum(tmp[tmp>0 & YY[2,]==0]) # Sum of the species losses between time 1 and time 2 for vanished species#
# B2 <- sum(tmp[tmp>0 & YY[2,]>0]) # Sum of the species losses between time 1 and time 2 for species still present#
# 21/11/2016
C = -sum(tmp[tmp<0])     # Sum of the species gains between time 1 and time 2#
# 21/11/2016
# C1 <- -sum(tmp[tmp<0 & YY[1,]==0])     # Sum of the species gains between time 1 and time 2 for new species#
# C2 <- -sum(tmp[tmp<0 & YY[1,]>0])     # Sum of the species gains between time 1 and time 2 for species still present#
# 21/11/2016
D = B+C                  # Dissimilarity#
B.ref <- B
B.ref.prime <- B
# 21/11/2016
# out1[i,] = c(A,B,B1,B2,C,C1,C2)#
# out2[i,1:8] = c(A,B,B1,B2,C,C1,C2,D)/den(A,B,C,den.type)#
# out2[i,9] <- B.ref/sum(Y1[i,])
# out2[i,10] <- 0
out1[i,] = c(A,B,C)#
out2[i,1:4] = c(A,B,C,D)/den(A,B,C,den.type)#
#B.ref
out2[i,5] <- B.ref/sum(Y1[i,])
#B.ref.prime
denom <- YY[2,]
denom <- sum(Y1[i,]) + sum(denom[tmp>=0])
out2[i,6] <- B.ref.prime/denom
out2[i,7] <- designdist(YY, "J/A", "min")
# out2[i,6] <- 0
# # 21/11/2016
# 	if (out2[i,2] < 0.2) {
# 	}	else if ( 0.2 <= out2[i,2] & out2[i,2] < 0.5) {
# # 21/11/2016
# 		# out2[i,10] <- out2[i,10]+1
# 		out2[i,6] <- out2[i,6]+1
# # 21/11/2016
# 	}	else if ( out2[i,2] >= 0.5) {
# # 21/11/2016
# 		# out2[i,10] <- out2[i,10]+2
# 		out2[i,6] <- out2[i,6]+2
# # 21/11/2016
# 	}
# 21/11/2016
# if (out2[i,5] < 0.3) {
# }	else if ( 0.3 <= out2[i,5] & out2[i,5] < 0.6) {
# 	out2[i,10] <- out2[i,10]+1
# }	else if ( out2[i,5] >= 0.6) {
# 	out2[i,10] <- out2[i,10]+2
# }
# if (out2[i,8] > 0.95) {
# 	out2[i,10] <- out2[i,10]+1
# }
# if (out2[i,3] < 0.3) {
# }	else if ( 0.3 <= out2[i,3] & out2[i,3] < 0.6) {
# 	out2[i,6] <- out2[i,6]+1
# }	else if ( out2[i,3] >= 0.6) {
# 	out2[i,6] <- out2[i,6]+2
# }
# if (out2[i,4] > 0.95) {
# 	out2[i,6] <- out2[i,6]+1
# }
# 21/11/2016
}#
##
list(out1=out1, out2=out2)#
}
####
# OG
LS.wrap <- function (x,y, transfo) {
x <-as.data.frame(x)
if (transfo==0) {
print("No transformation")
} else if (transfo==1) {
x <- sqrt(x)
print("Square root transformation")
} else if (transfo==2) {
x <- sqrt(sqrt(x))
print("Double square root transformation")
} else if (transfo==3) {
x <- decostand(x, "pa")
print("Presence/absence transformation")
}
n <- nrow(x)
ref <- which(y)
#	res <- data.frame(A=numeric(0),B=numeric(0),C=numeric(0),D=numeric(0))
# res <- data.frame(A=numeric(0),B=numeric(0),B1=numeric(0),B2=numeric(0),C=numeric(0),C1=numeric(0),C2=numeric(0),D=numeric(0))
# 21/11/2016
# res <- data.frame(A=numeric(0),B=numeric(0),B1=numeric(0),B2=numeric(0),C=numeric(0),C1=numeric(0),C2=numeric(0),D=numeric(0), B.ref=numeric(0), Score=numeric(0))
res <- data.frame(A=numeric(0),B=numeric(0),C=numeric(0),D=numeric(0), B.ref=numeric(0), B.ref.prime=numeric(0), RugQ=numeric(0))
# 21/11/2016
for(i in 1:n) {
res <- rbind(res, decompose.D.OG(x[ref,], x[i,])$out2)
}
rownames(res) <- rownames(x)
S <- specnumber(x)
res$D[S==0] <- 1
# make it into a similarity # not anymore
# res <- 1 - res
res
}
#######################
#	BVBI  <- function(x,y,before=T,...){ ##
#	require(vegan)
#	x <- as.data.frame(x)
#	y <- as.logical(y)
#	rs <- rowSums(x)
#	if (!all(rs > 0)) {
#		warning("Danger ! Danger ! Time for a beer : Empty row(s) in faunal matrix")
#	}
#	# Hellinger
#	x.hell <-decostand(x, "hell")
#	d.hell <- dist(x.hell)
#	d.hell <- as.matrix(d.hell)
#	Hell <- d.hell[y,]
#
#	Hell <- (sqrt(2)-Hell) / sqrt(2)
#	S <- specnumber(x)
#	Hell[!y & S==0] <- 0
#	res <-data.frame(Hell=Hell, S=S)
#	res
#}
#######################
abiotic$Subset <- factor(abiotic$Subset)
subsets <- levels(abiotic$Subset)
# res.BI <- data.frame(A=numeric(0),B=numeric(0),C=numeric(0),D=numeric(0), Hell = numeric(0), S=numeric(0))
# res.BI <- data.frame(A=numeric(0),B=numeric(0),B1=numeric(0),B2=numeric(0),C=numeric(0),C1=numeric(0),C2=numeric(0),D=numeric(0))
# 21/11/2016
# res.BI <-data.frame(A=numeric(0),B=numeric(0),B1=numeric(0),B2=numeric(0),C=numeric(0),C1=numeric(0),C2=numeric(0),D=numeric(0), B.ref=numeric(0), Score=numeric(0))
res.BI <- data.frame(A=numeric(0),B=numeric(0),C=numeric(0),D=numeric(0), B.ref=numeric(0), B.ref.prime=numeric(0), RugQ=numeric(0))
# 21/11/2016
for (i in subsets) {
biotic[abiotic$Subset==i, ] -> curr.bio
curr.bio <- curr.bio[,colSums(curr.bio)>0]
abiotic[abiotic$Subset==i, ] -> curr.abio
is.ref <- sum(curr.abio$Ref, na.rm=T)
if (is.na(is.ref)) {
warning(paste("NA's in Ref for subset: ",i, ". No Ref assumed."), call. =F)
is.ref <- 0
}
if (is.ref==1) {
# one reference station, compute values for each site,
# write.csv2(curr.bio, "curr.bio.csv")
# write.csv2(curr.abio, "curr.abio.csv")
refs <- as.logical (curr.abio$Ref)
tmp <- LS.wrap(curr.bio, refs, transfo)
#		tmp2 <- BVBI(curr.bio, refs)
#		tmp <- cbind(tmp, tmp2)
tmp
res.BI <- rbind(res.BI, tmp)
res.BI
} else if (is.ref > 1) {
# mulitple reference stations, compute each, take average
n <- nrow(curr.bio)
#	tmp <- data.frame(A=numeric(n),B=numeric(n),C=numeric(n),D=numeric(n))
# tmp <- data.frame(A=numeric(n),B=numeric(n),B1=numeric(n),B2=numeric(n),C=numeric(n),C1=numeric(n),C2=numeric(n),D=numeric(n))
# 21/11/2016
# tmp <- data.frame(A=numeric(n),B=numeric(n),B1=numeric(n),B2=numeric(n),C=numeric(n),C1=numeric(n),C2=numeric(n),D=numeric(n), B.ref=numeric(n), Score=numeric(n))
tmp <- data.frame(A=numeric(n),B=numeric(n),C=numeric(n),D=numeric(n), B.ref=numeric(n), B.ref.prime=numeric(n), RugQ=numeric(n))
# 21/11/2016
#	tmp2 <- data.frame(Hell=numeric(n), S=numeric(n))
refs <- as.logical (curr.abio$Ref)
refs.pos <- which(refs)
names.tmp <- rownames(curr.abio)
for(j in 1:is.ref) {
mult.refs <- logical(length(refs))
mult.refs[refs.pos[j]] <- TRUE
tmp <- tmp + LS.wrap(curr.bio, mult.refs, transfo)
#		tmp2 <- tmp2 + BVBI(curr.bio, mult.refs)
}
if(real.average) {
tmp <- tmp/is.ref
#			tmp2 <- tmp2/is.ref
} else {
tmp <- tmp/is.ref
tmp[curr.abio$Ref == 1, ] <- 0
tmp[curr.abio$Ref == 1, 1] <- 0.5
#			tmp2 <- tmp2/is.ref
#			tmp2$Hell[curr.abio$Ref == 1] <- 1
}
#		tmp <- cbind(tmp, tmp2)
rownames(tmp) <- names.tmp
res.BI <- rbind(res.BI, tmp)
} else {
warning(paste("No reference for subset: ", i, ". No computations.", sep=""), call.=F)
}
}
### fin for
res.abio <- abiotic[rownames(abiotic) %in% rownames(res.BI),]
results <- cbind(res.abio, res.BI)
S <- specnumber(biotic)
results$S <- S[rownames(abiotic) %in% rownames(res.BI)]
#
#results$Date <- as.Date(results$Date, "%d/%m/%Y")
#results$Year <- as.rformat(results$Date, "%Y"))
##############################
#DELTA Bval
#Portion rajout?e par C?line le 7 Juillet 2020
refsub<-subset(results,results$Ref==1)
moyref<-as.data.frame(tapply(refsub$RugQ,refsub$Subset,mean))
moyref$Subset<-rownames(moyref)
colnames(moyref)<-c('Mean','Subset')
results2<-left_join(results,moyref)
results2$Delta<-results2$RugQ-results2$Mean
###############
results2
1 - abs(max(results2$Mean)- results2$RugQ)
gpbi(biotic, abiotic$Refs, detail = TRUE)
mean(c(1.00, 0.80, 0.75, 1.00, 1.00, 0.75, 1.00, 0.80, 1.00))
# Using only site 1 as a reference, details of the computations kept
gpbi(x = test.data, refs = 1, details = TRUE)
################################################################################
# Function gpbi computes the General Purpose Biotic Index (GPBI) as described in
# Labrune et al. (2021).
#
# Olivier Gauthier, olivier.gauthier@univ-brest.fr, May 2021.
#
# Usage
#           gpbi(x, refs, details = TRUE)
#
# Arguments:
#   x       : a matrix or data.frame containing the community data. rows are
#             sites/stations columns are species. x should contain species
#             absolute abondances.
#   refs    : either
#               1) a numeric vector of the same length as the number of
#               rows in x with 0 indicating a tested station and any other
#               value a reference station.
#               2) a logical vector of the same length as the number of
#               rows in x with FALSE for a tested station and TRUE for a
#               reference station.
#               3) a numeric vector giving the indices of the rows of x that
#               are reference stations.
#
#   details : should the output include results of intermediate computations
#             (TRUE) or not (FALSE, the default).
#
# Output
# * if details is FALSE (default), a vector with the GPBI values for each station
#   in x, including the reference station(s).
# * if details is TRUE, a list containing the following elements
#
#   A        : a matrix with the A values (shared individuals). Rows are
#              reference stations and columns are compared stations.
#
#   C        : a matrix with the C values (lost individuals). Rows are
#              reference stations and columns are compared stations.
#
#   Rquant   : a matrix with the Rquant = A / (A+C) values. Rows are
#              reference stations and columns are compared stations.
#
#   per.loss : the mean Rquant value in each station; i.e. a vector with
#              the mean values of the columns of Rquant.
#
#   ref.bar  : if there are multiple reference stations, the mean of all the
#              Rquant similarity matrix between the reference stations including
#              the diagonal; otherwise 1
#
#   GBPI     : a vector with the GPBI values for each station in x, including
#              the reference station(s)
################################################################################
gpbi <- function(x, refs, details = FALSE) {
x <- as.matrix(x)
if (length(refs) == nrow(x)) {
tmp <- as.logical(refs)
refs <- which(tmp == TRUE)
} else if (length(refs) > nrow(x)){
stop("ref must have fewer or the same number of elements as there are rows in the community matrix (x).")
}
n.refs <- length(refs)
if (n.refs <= 0)
stop("A minimum of one reference station is necessary to compute GPBI")
n.tests <- nrow(x)
ref.mat <- matrix(x[refs, ], nrow = n.refs)
test.mat <- x
if (n.refs == 1) {
ref.bar <- 1
} else {
dgpi.refs <- numeric(0)
for (i in 1:n.refs) {
for (j in 1:n.refs) {
A.refs <- apply(ref.mat[c(i,j), ], 2, min)
C.refs <- ifelse(ref.mat[i, ] - A.refs > 0, ref.mat[i, ] - A.refs, 0)
dgpi.refs <- c(dgpi.refs, sum(A.refs) / (sum(A.refs) + sum(C.refs)))
}
}
print(dgpi.refs)
ref.bar <- mean(dgpi.refs)
}
A.mat <- matrix(0, n.refs, n.tests)
C.mat <- matrix(0, n.refs, n.tests)
colnames(A.mat) <- colnames(C.mat) <- rownames(x)
rownames(A.mat) <- rownames(C.mat) <- rownames(x)[refs]
for (i in 1:n.refs) {
for (j in 1:n.tests) {
tmp <- rbind(ref.mat[i,], test.mat[j,])
A <- apply(tmp, 2, min)
C <- ifelse(tmp[1, ] - A > 0, tmp[1, ] - A, 0)
A.mat[i,j] <- sum(A)
C.mat[i,j] <- sum(C)
}
}
Rquant <- A.mat/(A.mat + C.mat)
per.loss <- colMeans(Rquant)
GPBI <- 1 - abs(ref.bar - per.loss)
if (details == TRUE) {
res <- list(A = A.mat, C = C.mat, Rquant = Rquant, per.loss = per.loss, ref.bar = ref.bar, GPBI = GPBI)
} else {
res <- GPBI
}
return(res)
}
gbpi(test.data, 1:2)
gpbi(test.data, 1:2)
gpbi(test.data, 1:2, TRUE)
