# Authors: Fuyu Frank Xu and Kate Beard, School of Computing and Information Science, University of Maine, Orono, Maine
# Function name: STS.eventize().
# This function can be used to eventize a univariate spatial time series matrix with a given threshold. This threshold can be either a user
# specified numerical value or a percentile. This function deals with events without considering magnitude, which is equivalent to
# binarization. If considering variations or levels within an individual event, please refer to STS.eventize1(), STS.eventize2() and STS.eventize3().
# Description of variables: evtDef--event definition, takes either percentile or absolute value for threshold with the default percentile 0.95.
# event: takes either "greater" or "lower" depending on how to define the event greater or lower than the threshold.
# Modified date: May, 2019
STS.eventize <- function(data,evtDef="percentile",thres=0.95,event="greater"){
# ----------------------------------------------- Test for errors if input data is not matrix format ------------------------------
#
if(!is.matrix(data)){
print("!--------------------- ERROR #001 -----------------!")
print("! Input data file 'data' is not a matrix! !")
print("!----------------------------------------------------!")
return()}
# ----------------------------------------------- Eventization --------------------------------------------------------------------
if(evtDef=="percentile"){
if(event=="greater"){
data[data>=quantile(data,thres,na.rm=TRUE)]=1
data[data<quantile(data,thres,na.rm=TRUE)]=0
} # end if greater
if(event=="smaller"){
data[data<=quantile(data,thres,na.rm=TRUE)]=1
data[data>quantile(data,thres,na.rm=TRUE)]=0
} # end if smaller
} # end if percentile
if(evtDef=="absolute"){
if(event=="greater"){
data[data>=thres]=1
data[data<thres]=0
} # end if greater
if(event=="smaller"){
data[data<=thres]=1
data[data>thres]=0
} # end if smaller
} # end if absolute
return(data)
} # end function STS.eventize