######################################
##### Commandes Nature Index #########
######################################

####################################################################################
####################################################################################
################# PART A: Loading, stat fitting, simulation & scaling ##############
####################################################################################
####################################################################################

############################################################
### 1- Preparation of the data #############################
############################################################


###
### 1.1 Read the nature index data bases:
###

rm(list=ls())
source("NI_function.R")
nidata<-read.table("mountain_data.txt",h=T)
nidata$fyl<-as.character(nidata$fyl)
nidata$kom<-as.character(nidata$kom)
nidata$ind<-as.character(nidata$ind)
nidata$year<-as.character(nidata$year)
nidata$datatype<-as.character(nidata$datatype)

###
### 1.2 Read the indicator list, check compatibility
###

indiclist<-read.table("Indicatorlist_mountain.txt",h=T,sep=",")
indiclist$ind<-as.character(indiclist$ind)
indiclist$Ref_model<-as.character(indiclist$Ref_model)
indiclist$River_Lake<-as.character(indiclist$River_Lake)
indiclist$River_Lake[is.na(indiclist$River_Lake)]<-"RL"

### Verifying the compatibility between nidata$ind and indiclist$ind:
table(unique(nidata$ind)%in%indiclist$ind)       # Everything should be TRUE
list(sort(as.character(indiclist$ind)),sort(unique(nidata$ind)))
summary(sort(as.character(indiclist$ind))==sort(unique(nidata$ind)))

###
### 1.3 Read the area file, checking compatibility
###

areastat<-read.table("Area.txt",h=T)
areastat$kom<-as.character(areastat$kom)
areastat$fyl<-as.character(areastat$fyl)
areastat$part<-as.character(areastat$part)
table(unique(nidata$kom)%in%unique(areastat$kom)) # Everything should be TRUE

kommune<-as.character(areastat$kom)
fylke<-as.character(areastat$fyl)
komfyl<-data.frame(kom=kommune,fyl=fylke)
komfyl$kom<-as.character(areastat$kom)
komfyl$fyl<-as.character(areastat$fyl)
part<-areastat$part
indicator<-unique(indiclist$ind)
year<-unique(nidata$year)
type<-as.character(c("est","inf","sup"))

#### 1.4 duplicating some data

###
### Note : Here we duplicate some data because data representative for several county were entered once one time (to save data-entering time). However the same values have to be used in several places
###

tochange<-unique(nidata$ind[nidata$JOG==1])
tochange<-as.character(tochange)

for (k in tochange){
where<-unique(nidata$fyl[nidata$ind==k])
tot2<-nidata[1,]
tot2<-tot2[-1,]

if("Troms"%in%where) {
tot<-nidata[nidata$ind==k & nidata$kom=="BALSFJORD",] ### extracting data
essai<-tot
for (i in 1:88){
tot<-rbind(tot,essai)}                                ### replicating data (89 kommune in N)
newkom<-data.frame(kom=sort(rep(kommune[part=="N"],5)))
newkom$kom<-as.character(newkom$kom)                  ### changing the name of kommune and fylke
newkomfyl<-merge(newkom,komfyl)
tot$kom<-newkomfyl$kom
tot$fyl<-newkomfyl$fyl
tot2<-rbind(tot2,tot)                                 ### object containing duplicated data
}

if("Sør-Trøndelag"%in%where) {
tot<-nidata[nidata$ind==k & nidata$kom=="OPPDAL",]
essai<-tot
for (i in 1:85){
tot<-rbind(tot,essai)}
newkom<-data.frame(kom=sort(rep(kommune[part=="C"],5)))
newkom$kom<-as.character(newkom$kom)
newkomfyl<-merge(newkom,komfyl)
tot$kom<-newkomfyl$kom
tot$fyl<-newkomfyl$fyl
tot2<-rbind(tot2,tot)
}

if("Hordaland"%in%where) {
tot<-nidata[nidata$ind==k & nidata$kom=="ODDA",]
essai<-tot
for (i in 1:84){
tot<-rbind(tot,essai)}
newkom<-data.frame(kom=sort(rep(kommune[part=="W"],5)))
newkom$kom<-as.character(newkom$kom)
newkomfyl<-merge(newkom,komfyl)
tot$kom<-newkomfyl$kom
tot$fyl<-newkomfyl$fyl
tot2<-rbind(tot2,tot)
}

if("Vest-Agder"%in%where) {
tot<-nidata[nidata$ind==k & nidata$kom=="SIRDAL",]
essai<-tot
for (i in 1:62){
tot<-rbind(tot,essai)}
newkom<-data.frame(kom=sort(rep(kommune[part=="S"],5)))
newkom$kom<-as.character(newkom$kom)
newkomfyl<-merge(newkom,komfyl)
tot$kom<-newkomfyl$kom
tot$fyl<-newkomfyl$fyl
tot2<-rbind(tot2,tot)
}

if("Akershus"%in%where) {
tot<-nidata[nidata$ind==k & nidata$kom=="SKI",]
essai<-tot
for (i in 1:110){
tot<-rbind(tot,essai)}
newkom<-data.frame(kom=sort(rep(kommune[part=="E"],5)))
newkom$kom<-as.character(newkom$kom)
newkomfyl<-merge(newkom,komfyl)
tot$kom<-newkomfyl$kom
tot$fyl<-newkomfyl$fyl
tot2<-rbind(tot2,tot)
}

if("Finnmark"%in%where==T & "Troms"%in%where==F) {
tot<-nidata[nidata$ind==k & nidata$kom=="ALTA",]
essai<-tot
for (i in 1:18){
tot<-rbind(tot,essai)}
newkom<-data.frame(kom=sort(rep(kommune[fylke=="Finnmark"],5)))
newkom$kom<-as.character(newkom$kom)
newkomfyl<-merge(newkom,komfyl)
tot$kom<-newkomfyl$kom
tot$fyl<-newkomfyl$fyl
tot2<-rbind(tot2,tot)
}

if("Finnmark"%in%where==T & "Troms"%in%where==T) {
tot<-nidata[nidata$ind==k & nidata$kom=="ALTA",]
essai<-tot
for (i in 1:18){
tot<-rbind(tot,essai)}
newkom<-data.frame(kom=sort(rep(kommune[fylke=="Finnmark"],5)))
newkom$kom<-as.character(newkom$kom)
newkomfyl<-merge(newkom,komfyl)
tot$kom<-newkomfyl$kom
tot$fyl<-newkomfyl$fyl
tot2<-tot2[tot2$fyl!="Finnmark",]
tot2<-rbind(tot2,tot)
}

nidata<-nidata[nidata$ind!=k,]
nidata<-rbind(nidata,tot2)
}


#########################################################################
#### 2 Estimate of the statistical law for each indicator ###############
#########################################################################

### Fitting stats and simulating data

###
### The following codes "mimic" the process by which data were entered: for all duplicated data, the same simulation set is applied.
### We also take into account the fact that some expert expressed uncertainty as 90 or 95% quantiles (instead of the 50% asked in the process)
### This may takes a few minutes anyway. Some warnings may be generated, because of troubles with fitting certain statistical law (gamma distribution for example). These warnings do not affect the results however. 
### 

nsimu<-99 ### Here I only use 99 simulations, because 999 simulations are only supported by 64-bits R version. Note that the results we present in the paper are based on 999 simulations

nidata$Etternavn<-as.character(nidata$Etternavn)
nidata$unic<-nidata$obs*1000000+nidata$low*1000+nidata$up
nidata$unic[nidata$obs==(-1)]<-(-1e9)
nidata$distrib<-"NAWAK"
nidata$mu<-NA
nidata$sig<-NA
num<-seq(1,nrow(nidata),1)
bootmat<-matrix((-1),nrow=nrow(nidata),ncol=nsimu)

for (e in unique(nidata$Etternavn)){
nidata_etter<-nidata[nidata$Etternavn==e,]

for (u in unique(nidata_etter$unic)){
nidata_unic<-nidata_etter[nidata_etter$unic==u,]
nidata_unic$distrib[nidata_unic$boot==F]<-"NoBoot"
testnoboot<-(length(unique(nidata_unic$distrib))==1 & unique(nidata_unic$distrib)=="NoBoot")

if(testnoboot==F){
obsval<-c(unique(nidata_unic$low[nidata_unic$boot==T]),unique(nidata_unic$obs[nidata_unic$boot==T]),unique(nidata_unic$up[nidata_unic$boot==T]))
proba1<-(1-unique(nidata_unic$CI[nidata_unic$boot==T])/100)/2
proba2<-1-proba1
proba<-c(proba1,proba2)
a<-try(estim.fct(obsval=obsval,proba=proba,type=unique(nidata_unic$type[nidata_unic$boot==T])),silent=T)
if (length(a)==1){a<-estimlight.fct(obsval=obsval,proba=proba,type=unique(nidata_unic$type[nidata_unic$boot==T]))}
nidata_unic$distrib[nidata_unic$boot==T]<-as.character(a$distrib)
nidata_unic$mu[nidata_unic$boot==T]<-a$mu
nidata_unic$sig[nidata_unic$boot==T]<-a$sig
}

distribset<-nidata_unic$distrib
nidata_etter[nidata_etter$unic==u,]<-nidata_unic
nidata[nidata$Etternavn==e,]<-nidata_etter

for (d in unique(distribset)){
nidata_distrib<-nidata_unic[nidata_unic$distrib==d,]
mu<-unique(nidata_distrib$mu)
sig<-unique(nidata_distrib$sig)
obs<-unique(nidata_distrib$obs)
num_distrib<-num[nidata$Etternavn==e & nidata$unic==u & nidata$distrib==d]
vec<-simulNI.fct(nsim=nsimu,distrib=d,mu=mu,sig=sig,obs=obs)
vec[vec==(-1)]<-1e16
vec[vec<0]<-0
vec[vec==1e16]<-(-1)
for (n in num_distrib){
bootmat[n,]<-vec
}}}}

save(nidata,file="nidata_mountain.R")   
save(bootmat,file="bootmat_mountain.R") 

################################################################
### 3 Stocking the observed and simulated data into an array. ##
################################################################

load(file="nidata_mountain.R")

### Stocking the observed data
stockni<-array(NA,c(length(indicator),length(kommune),length(year)))

for (i in 1:nrow(nidata)){
sel<-nidata[i,]
kom<-sel$kom
ind<-sel$ind
an<-sel$year
stockni[indicator==ind,kommune==kom,year==an]<-sel$obs}

### Adding "-1" when the indicator is thought to be present but no data have been entered. This is based on presence/absence info given by the expert in large regions.
indiclist$ind<-as.character(indiclist$ind)
for (i in indicator) {
if(indiclist$E[indiclist$ind==i]==1){ stockni[indicator==i,part=="E",][is.na(stockni[indicator==i,part=="E",])]<-(-1) }
if(indiclist$N[indiclist$ind==i]==1){ stockni[indicator==i,part=="N",][is.na(stockni[indicator==i,part=="N",])]<-(-1) }
if(indiclist$C[indiclist$ind==i]==1){ stockni[indicator==i,part=="C",][is.na(stockni[indicator==i,part=="C",])]<-(-1) }
if(indiclist$W[indiclist$ind==i]==1){ stockni[indicator==i,part=="W",][is.na(stockni[indicator==i,part=="W",])]<-(-1) }
if(indiclist$S[indiclist$ind==i]==1){ stockni[indicator==i,part=="S",][is.na(stockni[indicator==i,part=="S",])]<-(-1) }
}

### Removing data when the considered major habitat does not occur
selko<-kommune%in%areastat$kom[areastat$open_fjell==0] 
stockni[,selko,]<-NA

### Saving the observed data
save(stockni,file="stockni_mountain.R") 

### Stocking the data source
stocksource<-array(NA,c(length(indicator),length(kommune),length(year)))
nidata$source<-NA
nidata$source[nidata$datatype=="Beregnet_fra_data"]<-"D"  ### indicator estimates comes from data
nidata$source[nidata$datatype=="Data_fra_modeller"]<-"M"  ### indicator estimates comes from model
nidata$source[nidata$datatype=="Ekspertvurdering"]<-"E"   ### indicator estimates comes from expert judgement

for (i in 1:nrow(nidata)){
sel<-nidata[i,]
kom<-sel$kom
ind<-sel$ind
an<-sel$year
stocksource[indicator==ind,kommune==kom,year==an]<-sel$source}
stocksource[,selko,]<-NA
save(stocksource,file="stocksource_mountain.R")

### Stocking the simulated data

#memory.limit(size=4095) could be useful if you lack of memory.

rm(stockni)
load(file="bootmat_mountain.R") 
selko<-kommune%in%areastat$kom[areastat$open_fjell==0] 

stockboot=array(NA,dim=c(length(indicator),length(kommune),length(year),nsimu))
stockboot<-array(NA,c(length(indicator),length(kommune),length(year),nsimu)) 
for (i in 1:length(nidata$fyl)){
sel<-nidata[i,]
kom<-sel$kom
ind<-sel$ind
an<-sel$year
stockboot[indicator==ind,kommune==kom,year==an,]<-bootmat[i,]}

for (i in indicator) {
if(indiclist$E[indiclist$ind==i]==1){ stockboot[indicator==i,part=="E",,][is.na(stockboot[indicator==i,part=="E",,])]<-(-1) }
if(indiclist$N[indiclist$ind==i]==1){ stockboot[indicator==i,part=="N",,][is.na(stockboot[indicator==i,part=="N",,])]<-(-1) }
if(indiclist$C[indiclist$ind==i]==1){ stockboot[indicator==i,part=="C",,][is.na(stockboot[indicator==i,part=="C",,])]<-(-1) }
if(indiclist$W[indiclist$ind==i]==1){ stockboot[indicator==i,part=="W",,][is.na(stockboot[indicator==i,part=="W",,])]<-(-1) }
if(indiclist$S[indiclist$ind==i]==1){ stockboot[indicator==i,part=="S",,][is.na(stockboot[indicator==i,part=="S",,])]<-(-1) }
}

stockboot[,selko,,]<-NA

save(stockboot,file="stockboot_mountain.R")
rm(bootmat)

###################################################################################################
############################## 4 Scaling ##########################################################
###################################################################################################

####
#### Scaling the observed data
####

#### Creation of indexing object for year, split stockni into one array of reference and one array for data

load(file="stockni_mountain.R")

yearest<-year[-5]
stockref<-stockni[,,5]
stockest<-stockni[,,c(1,2,3,4)]

stockest[,,1][stockref==(-1)]<-(-1)     #### if (-1) in the reference condition: -> lack of knowledge.
stockest[,,2][stockref==(-1)]<-(-1)
stockest[,,3][stockref==(-1)]<-(-1)
stockest[,,4][stockref==(-1)]<-(-1)

stockT<-stockest

### Calculation according to optimal model
for (i in yearest){
stockT[,,yearest==i] <- 1 - abs((stockest[,,yearest==i]-stockref)/stockref)
stockT[,,yearest==i][stockT[,,yearest==i]<0]<-0}

### Calculation according to maximal model
for (i in yearest){
stockT[indicator%in%indicator[indiclist$Ref_model=="MAX"],,yearest==i][stockest[indicator%in%indicator[indiclist$Ref_model=="MAX"],,yearest==i]<stockref[indicator%in%indicator[indiclist$Ref_model=="MAX"],]] <- 1 }

### Calculation according to Low model
for (i in yearest){
stockT[indicator%in%indicator[indiclist$Ref_model=="LOW"],,yearest==i][stockest[indicator%in%indicator[indiclist$Ref_model=="LOW"],,yearest==i]>stockref[indicator%in%indicator[indiclist$Ref_model=="LOW"],]] <- 1 }

stockT[stockest==(-1)]<-(-1)
stockT[is.na(stockest)]<-NA
save(stockT,file="stockT_mountain.R")

#load(file="stockT_mountain.R")
stockT2<-stockT
stockT2[stockest==(-1)]<-NA             ### for calculation
save(stockT2,file="stockT2_mountain.R")

###
### Note: the object stockT2 is not used to compute NI values. But it may be useful for comparison or checking (everything is checked here, but any NI implementation with new data should carefully compare values being in stockT2 and stockbootT2).
###

####
#### Scaling the bootstrap samples
####

yearest<-year[-5]
rm(list=c("an","ind","selko","stockest","stockni","stockref","i","kom","sel","stockT"))
memory.limit(size=4095)
stockbootref<-stockboot[,,5,]
stockbootest<-stockboot[,,c(1,2,3,4),]
stockbootT<-stockbootest
rm(stockboot)

for (i in yearest){
stockbootT[,,yearest==i,] <- 1 - abs((stockbootest[,,yearest==i,]-stockbootref)/stockbootref)
stockbootT[,,yearest==i,][stockbootT[,,yearest==i,]<0]<-0}
for (i in yearest){
stockbootT[indicator%in%indicator[indiclist$Ref_model=="MAX"],,yearest==i,][stockbootest[indicator%in%indicator[indiclist$Ref_model=="MAX"],,yearest==i,]<stockbootref[indicator%in%indicator[indiclist$Ref_model=="MAX"],,]] <- 1 }
for (i in yearest){
stockbootT[indicator%in%indicator[indiclist$Ref_model=="LOW"],,yearest==i,][stockbootest[indicator%in%indicator[indiclist$Ref_model=="LOW"],,yearest==i,]>stockbootref[indicator%in%indicator[indiclist$Ref_model=="LOW"],,]] <- 1 }
stockbootT[stockbootest==(-1)]<-(-1)
stockbootT[is.na(stockbootest)]<-NA

stockbootT2<-stockbootT
stockbootT2[stockbootest==(-1)]<-NA ### for calculation only
rm(stockbootref)
rm(stockbootest)

save(stockbootT,file="stockbootT_mountain.R")
save(stockbootT2,file="stockbootT2_mountain.R")

rm(list=ls())

###############################################################################
###############################################################################
################# PART B: Calculation of the NI for mountain ##################
###############################################################################
###############################################################################

###
### Note: It is possible to start here, without executing the previous commands, if they were properly executed once.
###

###############################################################################
#### 5 LOADING ################################################################
###############################################################################

rm(list=ls())
source("NI_function.R")

### 5.1 Read the indicator list, check compatibility

nsimu<-99

indiclist<-read.table("Indicatorlist_mountain.txt",h=T,sep=",")
indiclist$ind<-as.character(indiclist$ind)
indiclist$Ref_model<-as.character(indiclist$Ref_model)
indiclist$River_Lake<-as.character(indiclist$River_Lake)
indiclist$River_Lake[is.na(indiclist$River_Lake)]<-"RL"
indiclist$Taxon_detail<-as.character(indiclist$Taxon_detail)
indiclist$Taxon_detail[is.na(indiclist$Taxon_detail)]<-"NAWAK"

areastat<-read.table("Area.txt",h=T)
areastat$kom<-as.character(areastat$kom)
areastat$fyl<-as.character(areastat$fyl)
areastat$part<-as.character(areastat$part)

kommune<-as.character(areastat$kom)
fylke<-as.character(areastat$fyl)
komfyl<-data.frame(kom=kommune,fyl=fylke)
komfyl$kom<-as.character(areastat$kom)
komfyl$fyl<-as.character(areastat$fyl)
part<-areastat$part

indicator<-unique(indiclist$ind)
yearest<-c(1950,1990,2000,2010)
type<-as.character(c("est","inf","sup"))
spe<-indiclist$Mountain  

majhab<-areastat$open_fjell
majhab[seq(length(majhab)-3,length(majhab),1)]<-0 ## 0 value for the 4 oceanic communes
troph<-as.character(indiclist$Functional)
troph[11]<-"PP_gen"                               ## removing overskridelser_talegrenser_N_myr which is considered as "Extra-representative" only in Freshwater habitat, not in mountains

load(file="stockT2_mountain.R")
load(file="stocksource_mountain.R")
load(file="stockbootT2_mountain.R")
stocksource<-stocksource[,,seq(1,4,1)]            ### only the observed data

### 5.2 Minor corrections on the data ###############################################################

### The following command correct errors in the data set (e.g. indicators documented where they are absent, or indicators not documented where they should). These corrections result from the valisation process (fig 2)
### and only concern a few data.

toupdate<-c("jaktfalk","bergand","boltit","fjaereplytt","fjellvak","havelle","heilo","lappspurv","snospurv","kongeorn","smågnagere","lirype","fjellrype")
for (i in toupdate){
torem<-read.table(paste(i,".txt",sep=""),h=T)
stockT2[indicator==i,kommune%in%as.character(torem$x),]<-NA
stocksource[indicator==i,kommune%in%as.character(torem$x),]<-NA}

for (i in toupdate){
torem<-read.table(paste(i,".txt",sep=""),h=T)
stockbootT2[indicator==i,kommune%in%as.character(torem$x),,]<-NA
}

tofill<-c("SKÅNLAND","GRATANGEN","LAVANGEN","SALANGEN","DYRØY")
valfill<-c("NARVIK")
for (i in tofill){
stockT2[indicator=="vierkratt_areal",kommune==i,]<-stockT2[indicator=="vierkratt_areal",kommune=="NARVIK",]
stockbootT2[indicator=="vierkratt_areal",kommune==i,,]<-stockbootT2[indicator=="vierkratt_areal",kommune=="NARVIK",,]
}

total<-datab<-model<-expert<-array(0,c(length(indicator),length(kommune),length(yearest)))
total[stocksource!="N"]<-1
expert[stocksource=="E"]<-1
datab[stocksource=="D"]<-1
model[stocksource=="M"]<-1

total[is.na(stockT2)]<-NA
expert[is.na(stockT2)]<-NA
datab[is.na(stockT2)]<-NA
model[is.na(stockT2)]<-NA

### 5.3 weights at the commune level

presence<-stockT2
presence[!is.na(presence)]<-1
weight<-stockT2
for (y in yearest){
for (i in kommune){
essai<-data.frame(troph,spe,pres=presence[,kommune==i,yearest==y],indicator)
essai$pres[is.na(essai$pres)]<-0
essai$w<-NA
essai$troph<-as.character(essai$troph)
essai$indicator<-as.character(essai$indicator)
weight[,kommune==i,yearest==y]<-calweight.kommune(essai)}}

wstockT2<-weight*stockT2
wstockboot<-stockbootT2
for (i in 1:nsimu){wstockboot[,,,i]<-weight*wstockboot[,,,i]}

# number of documented indicator per municipality
nind50<-apply(presence[,,yearest==1950],c(2),sum,na.rm=T)
nind90<-apply(presence[,,yearest==1990],c(2),sum,na.rm=T)
nind00<-apply(presence[,,yearest==2000],c(2),sum,na.rm=T)
nind10<-apply(presence[,,yearest==2010],c(2),sum,na.rm=T)

image2<-image
library(splancs)
library(fields)
library(gstat)
library(gpclib)
library(maptools)

norway<-readShapePoly("Norway_utm33n")
shapekomnum<-norway@data$KOMM
polykom<-NULL
for (i in seq(1,length(shapekomnum))){
polykom[[i]]<-norway@polygons[[i]]@Polygons[[1]]@coords}

shapekomnum[247]<-(-1)
mask<-readShapePoly("ABAS_LAND_POLYGON")
load(file="maskkomnum.R")
polymask<-NULL
for (i in seq(1,length(maskkomnum))){
polymask[[i]]<-mask@polygons[[i]]@Polygons[[1]]@coords}

polynor<-read.table("polynor.txt",h=T,sep=",")
grid<-expand.grid(x=seq(min(polynor$x),max(polynor$x),10000),y=seq(min(polynor$y),max(polynor$y),10000))
seli<-inout(grid,polynor)
gridtot<-grid[seli,]
load(file="restrict.R")
seli<-inout(gridtot,restrict)
gridsel<-gridtot[seli,]


### 5.4 definition of thematic indexes :

###
### Note: All the following thematic indexes have been defined in tight collaboration with the experts responsible for mountain.
###

theme<-as.character(indiclist$Trophic_grp)

thema1<-indicator[theme%in%c("PP","Mi")]                             ### Plants, Moths, Lichens
thema2<-indicator[theme=="H"]                                        ### Herbivores
thema3<-indicator[theme=="IC"]                                       ### Intermediate consumers
thema4<-indicator[theme=="TP"]                                       ### Top predators
thema5<-"smågnagere"                                                 ### Small rodents
thema6<-c("smågnagere","lirype","fjellrype","jaktfalk","kongeorn")   ### Selected indicators belonging to the same trophic chain
thema7<-c("reinbeitelav","villrein")                                 ### Reindeers and forage lichen
thema8<-c("lappspurv","snospurv","steinskvett","heipiplerke")        ### Selected bird species used for monitoring
thema9<-"fjellvak"                                                   ### Rough-legged Buzzard
thema10<-"reinbeitelav"                                              ### Reindeer lichen
thema11<-"lirype"                                                    ### Willow ptarmigan
thema12<-"fjellrev"                                                  ### Arctic fox
thema13<-"villrein"                                                  ### Reindeer

themalist<-list(thema1,thema2,thema3,thema4,thema5,thema6,thema7,thema8,thema9,thema10,thema11,thema12,thema13)
thematitle<-c("Primary producers","Herbivores","Intermediate consumers","Top predators","Small rodents","Trophic cascade","Reindeer & lichens","TOV Birds","Rough-legged Buzzard","Reindeer lichen","Willow ptarmigan","Arctic fox","Reindeer")
date1<-c(1950,1990,2000,2010)
date2<-c(1990,2000,2010)
datelist<-list(date1,date1,date2,date2,date1,date1,date1,date2,date2,date1,date1,date1,date1)

########################################################################
#### 6 CALCULATIONS ####################################################
########################################################################

######### % Mountain per communes ######################################

###
### Note: we use "propm" to calculate the NI only in municipalities with at least 20% of their area in mountaineous habitat
###

propm<-areastat$open_fjell/areastat$area

###
### Note: The following calculation function also creates .txt files containing exact NI values with 95% confidence intervals.
###

### 6.1 calcul weighted NI trend & CI

nitrend<-calc.natureindex.fct(wstockboot,selko=propm>0.2,years=yearest,areaweight=areastat$terre,nsim=nsimu)
save(nitrend,file="NI_Trend_mountain_weighted_tot.R")

### 6.2 Weighted NI trend per region

nitrendE<-calc.natureindex.fct(wstockboot,selko=propm>0.2 & part=="E",years=yearest,areaweight=areastat$terre,nsim=nsimu)
nitrendN<-calc.natureindex.fct(wstockboot,selko=propm>0.2 & part=="N",years=yearest,areaweight=areastat$terre,nsim=nsimu)
nitrendS<-calc.natureindex.fct(wstockboot,selko=propm>0.2 & part=="S",years=yearest,areaweight=areastat$terre,nsim=nsimu)
nitrendW<-calc.natureindex.fct(wstockboot,selko=propm>0.2 & part=="W",years=yearest,areaweight=areastat$terre,nsim=nsimu)
nitrendC<-calc.natureindex.fct(wstockboot,selko=propm>0.2 & part=="C",years=yearest,areaweight=areastat$terre,nsim=nsimu)
save(nitrendE,file="NI_Trend_mountainE_weighted_tot.R")
save(nitrendN,file="NI_Trend_mountainN_weighted_tot.R")
save(nitrendS,file="NI_Trend_mountainS_weighted_tot.R")
save(nitrendW,file="NI_Trend_mountainW_weighted_tot.R")
save(nitrendC,file="NI_Trend_mountainC_weighted_tot.R")

### 6.3 calculation weighted NI for each municipality

valkom1950<-calc.NIkom.fct(an=1950,nsim=nsimu)
valkom1990<-calc.NIkom.fct(an=1990,nsim=nsimu)
valkom2000<-calc.NIkom.fct(an=2000,nsim=nsimu)
valkom2010<-calc.NIkom.fct(an=2010,nsim=nsimu)
valkom<-data.frame(v1950=valkom1950,v1990=valkom1990,v2000=valkom2000,v2010=valkom2010)
save(valkom,file="valkom_total.R")

### 6.4 calculation of NI for each municipality and each indicator

indkom1950<-calc.NIindkom.fct(1950,nsim=nsimu)
indkom1950[seq(431,434,1),]<-NA
indkom1990<-calc.NIindkom.fct(1990,nsim=nsimu)
indkom1990[seq(431,434,1),]<-NA
indkom2000<-calc.NIindkom.fct(2000,nsim=nsimu)
indkom2000[seq(431,434,1),]<-NA
indkom2010<-calc.NIindkom.fct(2010,nsim=nsimu)
indkom2010[seq(431,434,1),]<-NA
save(indkom1950,file="indkom_1950_mountain.R")
save(indkom1990,file="indkom_1990_mountain.R")
save(indkom2000,file="indkom_2000_mountain.R")
save(indkom2010,file="indkom_2010_mountain.R")

### 6.5 Trend Thematic index

for (i in 1:13){
nitrend_thema<-calc.themaindex.fct(stockbootT2,nsim=nsimu,selko=propm>0.2,years=datelist[[i]],areaweight=areastat$terre,thema=themalist[[i]])
save(nitrend_thema,file=paste("nitrend_thema",i,"mountain.R"))}

### 6.6 Maps thematic indexes

for (i in 1:13){
valkom_thema_1950<-calc.NIkom.thema.fct(an=1950,terre=T,thema=themalist[[i]],nsim=nsimu)
valkom_thema_1990<-calc.NIkom.thema.fct(an=1990,terre=T,thema=themalist[[i]],nsim=nsimu)
valkom_thema_2000<-calc.NIkom.thema.fct(an=2000,terre=T,thema=themalist[[i]],nsim=nsimu)
valkom_thema_2010<-calc.NIkom.thema.fct(an=2010,terre=T,thema=themalist[[i]],nsim=nsimu)
valkom_thema<-data.frame(v1950=valkom_thema_1950,v1990=valkom_thema_1990,v2000=valkom_thema_2000,v2010=valkom_thema_2010)
save(valkom_thema,file=paste("valkom_thema",i,".R"))}

### 6.7 Maps of change

###
### Note: this function calculate the probability that the NI value in a given locality at a date t2 is lower than at the date t1 (see the very end of the "Nature Index calculation" section)
### In this example, we compare 2010 and 1990 
###

valkom_diff<-calc.NIkomdiff.fct(an1=1990,an2=2010,terre=T,nsim=nsimu)
save(valkom_diff, file="valkom_diff_mountain_9010.R")

#############################################################################
#### 7 FIGURES ##############################################################
#############################################################################

### 7.1 % Mountain per communes 

grid<-gridtot
propm<-areastat$open_fjell/areastat$area
valkom<-propm
tiff(file="NI_mountain area.tiff",res=200,height=20,width=20,unit="cm")
show.NI.fct(valkom=valkom,nind=NA,minind=NA,majhab=majhab,minhab=NA,main="% Mountain areas",breakcol=c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9),namecol=rev(tim.colors(10)),valcol=c("<0.1","0.1-0.2","0.2-0.3","0.3-0.4","0.4-0.5","0.5-0.6","0.6-0.7","0.7-0.8","0.8-0.9",">0.9"),showborder="yes",interp="no")
dev.off()

### 7.2 Map the scaled values of all indicators. display NI for each municipality and each indicator

###
### Note: this will result in a quite big file (25Mb) because of the numerous maps and polygons. Easy to compress with winrar however.
###

load(file="indkom_1950_mountain.R")
load(file="indkom_1990_mountain.R")
load(file="indkom_2000_mountain.R")
load(file="indkom_2010_mountain.R")
tiff(file="NI_mountain individuals indicators.tiff",res=100,height=120,width=100,unit="cm")
par(mfrow=c(12,10),mar=c(1,1,1,1))
for (i in 1:length(indicator)){
show.NI.fct(valkom=indkom1950[,i],nind=NA,minind=NA,majhab=propm,minhab=0.2,main=paste(c(indicator[i],"1950")),breakcol=c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9),namecol=rev(tim.colors(10)),valcol=c("<0.1","0.1-0.2","0.2-0.3","0.3-0.4","0.4-0.5","0.5-0.6","0.6-0.7","0.7-0.8","0.8-0.9",">0.9"),showborder="yes",interp="no")
show.NI.fct(valkom=indkom1990[,i],nind=NA,minind=NA,majhab=propm,minhab=0.2,main=paste(c(indicator[i],"1990")),breakcol=c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9),namecol=rev(tim.colors(10)),valcol=c("<0.1","0.1-0.2","0.2-0.3","0.3-0.4","0.4-0.5","0.5-0.6","0.6-0.7","0.7-0.8","0.8-0.9",">0.9"),showborder="yes",interp="no")
show.NI.fct(valkom=indkom2000[,i],nind=NA,minind=NA,majhab=propm,minhab=0.2,main=paste(c(indicator[i],"2000")),breakcol=c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9),namecol=rev(tim.colors(10)),valcol=c("<0.1","0.1-0.2","0.2-0.3","0.3-0.4","0.4-0.5","0.5-0.6","0.6-0.7","0.7-0.8","0.8-0.9",">0.9"),showborder="yes",interp="no")
show.NI.fct(valkom=indkom2010[,i],nind=NA,minind=NA,majhab=propm,minhab=0.2,main=paste(c(indicator[i],"2010")),breakcol=c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9),namecol=rev(tim.colors(10)),valcol=c("<0.1","0.1-0.2","0.2-0.3","0.3-0.4","0.4-0.5","0.5-0.6","0.6-0.7","0.7-0.8","0.8-0.9",">0.9"),showborder="yes",interp="no")
}
dev.off()

### 7.3 calcul weighted NI trend & CI

load(file="NI_Trend_mountain_weighted_tot.R")
tiff(file="NI_mountain trend.tiff",res=200,height=20,width=20,unit="cm")
display.natureindex.fct(nitrend,years=yearest,main="Fjell",limy=c(0,1))
dev.off()

load(file="NI_Trend_mountainE_weighted_tot.R")
load(file="NI_Trend_mountainN_weighted_tot.R")
load(file="NI_Trend_mountainW_weighted_tot.R")
load(file="NI_Trend_mountainS_weighted_tot.R")
load(file="NI_Trend_mountainC_weighted_tot.R")

tiff(file="NI_mountain trend region.tiff",res=200,height=20,width=20,unit="cm")
par(mfrow=c(3,2),mar=c(2,2,2,2))
display.natureindex.fct(nitrendE,years=yearest,main="Fjell - Østlandet",limy=c(0,1))
display.natureindex.fct(nitrendS,years=yearest,main="Fjell - Sørlandet",limy=c(0,1))
display.natureindex.fct(nitrendW,years=yearest,main="Fjell - Vestlandet",limy=c(0,1))
display.natureindex.fct(nitrendC,years=yearest,main="Fjell - Midt-Norge",limy=c(0,1))
display.natureindex.fct(nitrendN,years=yearest,main="Fjell - Nord-Norge",limy=c(0,1))
dev.off()

### 7.4 Thematic NItrend

tiff(file="NI_mountain trend thema.tiff",res=100,height=40,width=40,unit="cm")
par(mfrow=c(4,4),mar=c(2,2,2,2),cex=1.5)
for (i in 1:13) {
load(file=paste("nitrend_thema",i,"mountain.R"))
display.natureindex.fct(nitrend_thema,years=datelist[[i]],main=thematitle[i],limy=c(0,1))}
dev.off()

### 7.5 Maps of NIvalues

load(file="valkom_total.R")

# 7.5.1 Non interpolated map 

tiff(file="NI_mountain map_municipality.tiff",res=200,height=20,width=80,unit="cm")
par(mfrow=c(1,4),mar=c(1,1,1,1),cex=2.5)
show.NI.fct(valkom=valkom$v1950,nind=NA,minind=NA,majhab=propm,minhab=0.2,main="Mountain 1950",breakcol=c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9),namecol=rev(tim.colors(10)),valcol=c("<0.1","0.1-0.2","0.2-0.3","0.3-0.4","0.4-0.5","0.5-0.6","0.6-0.7","0.7-0.8","0.8-0.9",">0.9"),showborder="yes",interp="no")
show.NI.fct(valkom=valkom$v1990,nind=NA,minind=NA,majhab=propm,minhab=0.2,main="Mountain 1950",breakcol=c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9),namecol=rev(tim.colors(10)),valcol=c("<0.1","0.1-0.2","0.2-0.3","0.3-0.4","0.4-0.5","0.5-0.6","0.6-0.7","0.7-0.8","0.8-0.9",">0.9"),showborder="yes",interp="no")
show.NI.fct(valkom=valkom$v2000,nind=NA,minind=NA,majhab=propm,minhab=0.2,main="Mountain 1950",breakcol=c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9),namecol=rev(tim.colors(10)),valcol=c("<0.1","0.1-0.2","0.2-0.3","0.3-0.4","0.4-0.5","0.5-0.6","0.6-0.7","0.7-0.8","0.8-0.9",">0.9"),showborder="yes",interp="no")
show.NI.fct(valkom=valkom$v2010,nind=NA,minind=NA,majhab=propm,minhab=0.2,main="Mountain 1950",breakcol=c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9),namecol=rev(tim.colors(10)),valcol=c("<0.1","0.1-0.2","0.2-0.3","0.3-0.4","0.4-0.5","0.5-0.6","0.6-0.7","0.7-0.8","0.8-0.9",">0.9"),showborder="yes",interp="no")
dev.off()

# 7.5.2 Interpolated map 

grid<-gridsel   #prediction grid in moutains area

tiff(file="NI_mountain map_interpolated.tiff",res=200,height=20,width=80,unit="cm")
par(mfrow=c(1,4),mar=c(1,1,1,1),cex=2.5)
show.NI.fct(valkom=valkom$v1950,nind=NA,minind=NA,majhab=propm,minhab=0.2,main="Mountain 1950",interp="yes",minleg=0.1,maxleg=1,isoligne=T,levelw=c(5),levelb=seq(0.1,0.9,0.1),interprow=115,interpcol=145)
show.NI.fct(valkom=valkom$v1990,nind=NA,minind=NA,majhab=propm,minhab=0.2,main="Mountain 1990",interp="yes",minleg=0.1,maxleg=1,isoligne=T,levelw=c(5),levelb=seq(0.1,0.9,0.1),interprow=115,interpcol=145)
show.NI.fct(valkom=valkom$v2000,nind=NA,minind=NA,majhab=propm,minhab=0.2,main="Mountain 2000",interp="yes",minleg=0.1,maxleg=1,isoligne=T,levelw=c(5),levelb=seq(0.1,0.9,0.1),interprow=115,interpcol=145)
show.NI.fct(valkom=valkom$v2010,nind=NA,minind=NA,majhab=propm,minhab=0.2,main="Mountain 2010",interp="yes",minleg=0.1,maxleg=1,isoligne=T,levelw=c(5),levelb=seq(0.1,0.9,0.1),interprow=115,interpcol=145)
dev.off()

### 7.6 Maps thematic index 

tiff(file="NI_mountain map_thema1_13.tiff",res=100,height=130,width=40,unit="cm")  #### Here the resolution is degraded so that to avoid too heavy picture
par(mfrow=c(13,4),mar=c(1,1,1,1),cex=1)

for (i in 1:13){
load(file=paste("valkom_thema",i,".R"))
show.NI.fct(valkom=valkom_thema$v1950,nind=NA,minind=NA,majhab=propm,minhab=0.2,main=paste(thematitle[i],"1950"),breakcol=c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9),namecol=rev(tim.colors(10)),valcol=c("<0.1","0.1-0.2","0.2-0.3","0.3-0.4","0.4-0.5","0.5-0.6","0.6-0.7","0.7-0.8","0.8-0.9",">0.9"),showborder="yes",interp="no")
show.NI.fct(valkom=valkom_thema$v1990,nind=NA,minind=NA,majhab=propm,minhab=0.2,main=paste(thematitle[i],"1990"),breakcol=c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9),namecol=rev(tim.colors(10)),valcol=c("<0.1","0.1-0.2","0.2-0.3","0.3-0.4","0.4-0.5","0.5-0.6","0.6-0.7","0.7-0.8","0.8-0.9",">0.9"),showborder="yes",interp="no")
show.NI.fct(valkom=valkom_thema$v2000,nind=NA,minind=NA,majhab=propm,minhab=0.2,main=paste(thematitle[i],"2000"),breakcol=c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9),namecol=rev(tim.colors(10)),valcol=c("<0.1","0.1-0.2","0.2-0.3","0.3-0.4","0.4-0.5","0.5-0.6","0.6-0.7","0.7-0.8","0.8-0.9",">0.9"),showborder="yes",interp="no")
show.NI.fct(valkom=valkom_thema$v2010,nind=NA,minind=NA,majhab=propm,minhab=0.2,main=paste(thematitle[i],"2010"),breakcol=c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9),namecol=rev(tim.colors(10)),valcol=c("<0.1","0.1-0.2","0.2-0.3","0.3-0.4","0.4-0.5","0.5-0.6","0.6-0.7","0.7-0.8","0.8-0.9",">0.9"),showborder="yes",interp="no")
}
dev.off()

### 7.7 Maps of change between 1990 - 2010

###
### Note: the two following maps may be uneasy to interpret. The first one displays the average difference of NI value per municipality between 1990 and 2010.
### Negative (yellow) values indicate decrease, positive (blue) values indicate increase. The second one displays the probability that the observed change
### is significant, i.e. the probability for each municipality that NI values in 2010 are lower than in 1990. Municipalities in red are those for which the probability
### is > 0.95. Municipalities in orange are those for which the probability is > 0.9. municipality in lightblue and blue are municipality where a decrease is not probable at all (p<0.1 and 0.05 respectively), 
### in other word municipality where an increase in NI values between 1990 and 2010 is the most probable. Municipalities in white are characterised by non-significant changes.
### See the end of "Nature Index calculation" section in the paper for further details.
###

load("valkom_diff_mountain_9010.R")

tiff(file="NI_mountain map change 1990-2010.tiff",res=200,height=20,width=20,unit="cm")
par(mfrow=c(1,1),mar=c(2,2,2,2))
show.NI.fct(valkom=valkom_diff$valkom,nind=NA,minind=NA,majhab=propm,minhab=0.2,main="NI2010 - NI1990",breakcol=c(-0.1,-0.05,0,0.05,0.1),namecol=c("red","orange","yellow","lightgreen","cyan","blue"),valcol=c("-0.1 and less","-0.1 to -0.05","-0.05 to 0","0 to +0.05","0.05 to 0.1","more than +0.1"),showborder="yes",interp="no",negval=T)
dev.off()

tiff(file="NI_mountain map change pval.tiff",res=200,height=20,width=20,unit="cm")
par(mfrow=c(1,1),mar=c(2,2,2,2))
show.NI.fct(valkom=valkom_diff$pval,nind=NA,minind=NA,majhab=propm,minhab=0.2,main="Probability that NI2010 < NI1990",breakcol=c(0.05,0.1,0.9,0.95),namecol=c("blue","lightblue","white","orange","red"),valcol=c("P<0.05","P<0.1","0.1<P<0.9","P>0.9","P>0.95"),showborder="yes",interp="no",negval=T)
dev.off()

### 7.8 Barplots Missing knowledge

nexp<-ndat<-nmod<-NULL
for (i in unique(part)){
for (j in yearest){

nexp<-c(nexp,mean(apply(expert[,part==i & kommune%in%kommune[seq(1,430,1)],yearest==j],c(2),sum,na.rm=T)))
ndat<-c(ndat,mean(apply(datab[,part==i & kommune%in%kommune[seq(1,430,1)],yearest==j],c(2),sum,na.rm=T)))
nmod<-c(nmod,mean(apply(model[,part==i & kommune%in%kommune[seq(1,430,1)],yearest==j],c(2),sum,na.rm=T)))
}}

tiff(file="Missing_mountain_part.tiff",res=200,height=15,width=20,unit="cm")

mat<-rbind(nexp,ndat)
mat<-rbind(mat,nmod)
rownames(mat)<-c("Expert-based estimate","Data-based estimate","Model-based estimate")
barplot(mat,main="fjell",ylab="Mean number of documented indicator per municipality",xlab="",space=c(0.25,rep(c(0.25,0.25,0.25,1),4)),col=c("grey","white","black"),names.arg=rep(c("1950","1990","2000","2010"),5),cex.names=0.75,ylim=c(0,ceiling(max(apply(mat,2,sum))+10)),legend=T,las=2)
text(3.25,max(apply(mat,2,sum))+2,"East")
text(9,max(apply(mat,2,sum))+2,"South")
text(14.75,max(apply(mat,2,sum))+2,"West")
text(20.5,max(apply(mat,2,sum))+2,"Center")
text(26.25,max(apply(mat,2,sum))+2,"North")
dev.off()

##################################################################
########## 8 Data exploration ####################################
##################################################################

###
### Note: the following commands are masked to do not hamper the automatic execution of the whole file.
###

#load(file="valkom_total.R")

#show.NI.fct(valkom=valkom$v2010,nind=NA,minind=NA,majhab=majhab,minhab=NA,main="Mountain 1950",breakcol=c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9),namecol=rev(tim.colors(10)),valcol=c("<0.1","0.1-0.2","0.2-0.3","0.3-0.4","0.4-0.5","0.5-0.6","0.6-0.7","0.7-0.8","0.8-0.9",">0.9"),showborder="yes",interp="no")

#whichweight.fct(2010)                ### then draw a polygon around the municipality you want to check (right clic to end)
#whichindicator.fct(2010)             ### idem
#NIdetail.fct(2010)                   ### idem
#zoomNI.fct(valkomzoom=valkom$v2010)  ### idem. If the selected area is not a square, the plot will be stretched.

#########################################################################################################################################################################
### Thank you very much and remember: It's a long way to the top if you wanna rock'n'roll (AC/DC 1976) ##################################################################
#########################################################################################################################################################################




