\name{sbh}

\alias{sbh}

\title{Cross-Validated Survival Bump Hunting}

\description{
    Main end-user function for fitting a cross-validated Survival Bump Hunting (SBH) model.
    Returns a cross-validated \code{sbh} object, as generated by our 
    Patient Recursive Survival Peeling (PRSP) algorithm, containing cross-validated 
    estimates of end-points statistics of interest.
    Generates an object of class \code{sbh}.
}

\usage{
  sbh(X, 
      y, 
      delta, 
      B = 30, 
      K = 5, 
      A = 1000, 
      vs = TRUE, 
      vstype = "ppl",
      vsarg = "alpha=1,
               nalpha=1,
               nlambda=100,
               vscons=0.5",
      cv = TRUE, 
      cvtype = "combined", 
      cvarg = "alpha=0.01,
               beta=0.05,
               minn=5,
               L=NULL,
               peelcriterion=\"lrt\",
               cvcriterion=\"cer\"",
      pv = FALSE,
      decimals = 2, 
      onese = FALSE,
      probval = NULL, 
      timeval = NULL, 
      parallel.vs = FALSE,
      parallel.rep = FALSE,
      parallel.pv = FALSE,
      conf = NULL,
      verbose = TRUE, 
      seed = NULL)
}

\arguments{
    \item{X}{
        (\eqn{n} x \eqn{p}) \code{data.frame} or \code{numeric} \code{matrix} of \eqn{n} observations and 
        \eqn{p} input covariates. If a \code{data.frame} is provided, it will be coerced to a 
        \code{numeric} \code{matrix}. Discrete nominal covariates will be treated as ordinal variables.
    }
    \item{y}{
        \eqn{n}-\code{numeric} \code{vector} of observed times to event.
    }
    \item{delta}{
        \eqn{n}-\code{numeric} \code{vector} of observed status (censoring) indicator variable. 
    }
    \item{B}{
        Postitive \code{integer} of the number of replications of the cross-validation procedure. 
        Defaults to 30.
    }
    \item{K}{
        Postitive \code{integer} of the number of cross-validation folds (partitions) into which the observations (\eqn{n}) 
        should be randomly split. \code{K} must be bigger than 2 for a regular \code{K}-fold cross-validation procedure 
        to work and should be greater than 3  for a regular procedure to make sense; \code{K} \eqn{\in} \{5,...,10\} 
        is recommended; defaults to \code{K}=5. Setting \code{K} also specifies the type of cross-validation to be done:
        \itemize{
            \item{\code{K}} = 1 carries no cross-validation out, or set-value when \code{cv} = \code{FALSE} (see below).
            \item{\code{K}} \eqn{\in} \{2,...,\eqn{n-1}\} carries out \code{K}-fold cross-validation.
            \item{\code{K}} = \eqn{n} carries out leave-one-out cross-validation.
        }
    } 
    \item{A}{
        Positive \code{integer} of the number of permutations for the computation of cross-validated p-values. 
        Defaults to 1000. Ignored if \code{pv} is \code{FALSE}.
    }
    \item{vs}{
        \code{logical} scalar. Flag for optional variable (covariate) screening (pre-selection). 
        Defaults to \code{TRUE}.
    }
    \item{vstype}{
        \code{character} \code{vector} in \{"prsp", "pcqr", "ppl", "spca"\} specifying the variable screening 
        (pre-selection) procedure. Defaults to "ppl". Reset to \code{NA} if \code{vs} is \code{FALSE}.
    }
    \item{vsarg}{
        \code{Character} \code{vector} specifying the parameters of cross-validated variable screening 
        (pre-selection) procedure. Defaults to PPL with its suggested parameters values. 
        Note that \code{vsarg} comes as a characters string (between double quotes), 
        with comas separated values without white spaces. All the following parameters are ignored if 
        \code{vs} is \code{FALSE}\cr
        PRSP: 
        \itemize{
            \item{\code{alpha}} = fraction to peel off at each step. Suggests 0.01.
            \item{\code{beta}} = minimum support size resulting from the peeling sequence. Suggests 0.05.
            \item{\code{minn}} = minimum number of observation that we want to be able to detect in a box. Suggests 5.
            \item{\code{L}} = maximum peeling length in [1,\code{ceiling}(\code{log}(1/\eqn{n}) / \code{log}(1 - (1/\eqn{n})))]. 
                See details below. Suggests \code{ceiling}(\code{log}(\code{beta}) / \code{log}(1 - \code{alpha})/3).
            \item{\code{S}} = maximum variables screening size in [1,\eqn{p}] (i.e. the maximum cardinal subset of 
                top-screened variables), that is used for the cross-validation of the optimal number of screened variables. 
                Setting \code{S} to \code{NULL} will create a grid of \code{min}(\code{S}, \code{floor}(100 * \code{S}/\eqn{p}))
                values in [1,\code{floor}(\eqn{p}/10)] that will be used to determine the optimal number of screened variables. 
                Setting \code{S} to a single upper bound value in [1,\eqn{p}] will fix the number of screened variables up to it.
                Suggests \code{S}=\code{floor}(\eqn{p}/10) to reduce computational complexity.
            \item{\code{peelcriterion}} in \{"lhr", "lrt", "chs"\} standing for Log-Hazard Ratio (LHR), 
                Log-Rank Test (LRT), and Cumulative Hazard Summary (CHS), respectively, specifying 
                the peeling criterion used in the PRSP algorithm. Suggests "lrt".
            \item{\code{cvcriterion}} in \{"lhr", "lrt", "cer"\} standing for Log-Hazard Ratio (LHR),
                Log-Rank Test (LRT), and Concordance Error Rate (CER), respectively, specifying
                the cross-validation criterion used for tuning/optimizing the maximum variables screening 
                size in the PRSP variable screening procedure. Suggests "cer".
            \item{\code{vscons}} = \code{numeric} scalar in [1/\code{K}, 1], specifying the conservativeness of 
                the variable screening (pre-selection) procedure, where 1/\code{K} is the least conservative 
                and 1 is the most. Suggests 0.5.
        }
        PCQR: 
        \itemize{
            \item{\code{tau}} = quantile in [0, 0.5] used in the censored quantile regression model. 
                It is the tuning parameter of the censored quantile loss. It represents the conditional 
                censored quantile of the survival response to be estimated. It includes the absolute loss 
                when \code{tau}=0.5. Suggests 0.5.
            \item{\code{alpha}} = elasticnet mixing parameter in [0, 1] that controls the relative 
                contribution from the lasso and the ridge penalty. The penalty is defined as
                (1-\code{alpha})/2||\code{beta}||_2^2+\code{alpha}||\code{beta}||_1. 
                \code{alpha} = 1 is the lasso penalty, and \code{alpha} = 0 the ridge penalty. 
                If \code{alpha} is set to \code{NULL}, a vector of values of length \code{nalpha} is used,
                else \code{alpha} value is used and \code{nalpha} is set to 1. Suggests \code{alpha}=1 (lasso). 
            \item{\code{nalpha}} = number of elasticnet penalization alpha values to consider in the grid search. 
            Suggests 1 (see above: lasso).
            \item{\code{nlambda}} = number of elasticnet penalization lambda values to consider in the grid search. 
                Suggests 100.
            \item{\code{vscons}} = \code{numeric} scalar in [1/\code{K}, 1], specifying the conservativeness of 
                the variable screening (pre-selection) procedure, where 1/\code{K} is the least conservative 
                and 1 is the most. Suggests 0.5.
        }
        PPL: 
        \itemize{
            \item{\code{alpha}} = elasticnet mixing parameter in [0, 1] that controls the relative 
                contribution from the lasso and the ridge penalty. See R package \pkg{glmnet}. The penalty is 
                defined as (1-\code{alpha})/2||\code{beta}||_2^2+\code{alpha}||\code{beta}||_1.
                \code{alpha} = 1 is the lasso penalty, and \code{alpha} = 0 the ridge penalty. 
                If \code{alpha} is set to \code{NULL}, a vector of values of length \code{nalpha} is used,
                else \code{alpha} value is used and \code{nalpha} is set to 1. Suggests \code{alpha}=1 (lasso).
            \item{\code{nalpha}} = number of elasticnet penalization alpha values to consider in the grid search. 
                Suggests 1 (see above: lasso).
            \item{\code{nlambda}} = number of elasticnet penalization lambda values to consider in the grid search. 
                Suggests 100.
            \item{\code{vscons}} = \code{numeric} scalar in [1/\code{K}, 1], specifying the conservativeness of 
                the variable screening (pre-selection) procedure, where 1/\code{K} is the least conservative 
                and 1 is the most. Suggests 0.5.
        }
        SPCA: 
        \itemize{
            \item{\code{n.thres}} = number of thresholds to consider in the grid search. 
                It cannot be less than \eqn{n} (sample size). Suggests 20.
            \item{\code{n.pcs}} = number of cross-validation principal components to use in \{1,2,3\}. 
                It cannot be less than \eqn{n} (sample size) and more than \eqn{p} (dimensionality), 
                and will be reset to \code{n.pcs} = \eqn{p} - 1 otherwise. Suggests 3.
            \item{\code{n.var}} = minimum number of variables to include in determining range for threshold. 
                If cannot be more than \eqn{p} (dimensionality), and will be reset to \code{n.var} = \eqn{p} - 1 
                otherwise. Suggests 5.
            \item{\code{vscons}} = \code{numeric} scalar in [1/\code{K}, 1], specifying the conservativeness of 
                the variable screening (pre-selection) procedure, where 1/\code{K} is the least conservative 
                and 1 is the most. Suggests 0.5.
        }
    } 
    \item{cv}{
        \code{logical} scalar. Flag for optional cross-validation (CV) of parameters of variable screening 
        (pre-selection) and variable usage (selection) by PRSP algorithm. Defaults to \code{TRUE}. 
        If \code{FALSE}, no cross-validation at will be performed, the value of \code{K} 
        will be overwritten to 1, and traditional log-rank Mantel-Haenszel p-values will be computed,
        (using the Chi-Squared distribution with 1df for the null distribution) instead of
        log-rank permutation p-values (using the permutation distribution for the null distribution).
    }
    \item{cvtype}{
        \code{character} \code{vector} in \{"combined", "averaged"\} specifying the cross-validation technique.
        Defaults to "combined". Reset to \code{NA} if \code{cv} is \code{FALSE}.
    }
    \item{cvarg}{
        \code{character} \code{vector} describing the parameters used in the PRSP algorithm of the 
        Survival Bump Hunting function. Defaults to \cr "alpha=0.01,beta=0.05,minn=5,L=NULL,peelcriterion=\"lrt\",
        cvcriterion=\"cer\"". Note that \code{cvarg} comes as a characters string (between double quotes), 
        with comas separated values without white spaces.
        \itemize{ 
            \item{\code{alpha}} = fraction to peel off at each step. 
                Defaults to 0.01.
            \item{\code{beta}} = minimum support size resulting from the peeling sequence. 
                Defaults to 0.05.
            \item{\code{minn}} = minimum number of observation that we want to be able to detect in a box. 
                Defaults to 5.
            \item{\code{L}} = maximum peeling length in [1,\code{ceiling}(\code{log}(1/\eqn{n}) / \code{log}(1 - (1/\eqn{n})))]. 
                See details below. Defaults to \code{NULL}, that is, with automatic selection.
            \item{\code{peelcriterion}} in \{"lhr", "lrt", "chs"\} standing for Log-Hazard Ratio (LHR), 
                Log-Rank Test (LRT), and Cumulative Hazard Summary (CHS), respectively, specifying 
                the peeling criterion used in the PRSP algorithm. 
                Defaults to "lrt".
            \item{\code{cvcriterion}} in \{"lhr", "lrt", "cer"\} standing for Log-Hazard Ratio (LHR),
                Log-Rank Test (LRT), and Concordance Error Rate (CER), respectively, specifying
                the cross-validation criterion used for tuning/optimizing the peeling sequence length 
                (i.e. number of peeling steps) in the PRSP algorithm. 
                Defaults to "cer". Ignored if \code{cv} is \code{FALSE}.
        }
    }
    \item{pv}{
        \code{logical} scalar. Flag for computation of log-rank p-values. 
        Defaults to \code{FALSE}.
    }
    \item{decimals}{
        Positive \code{integer} of the number of user-specified significant decimals to output results.
        Defaults to 2.
    }
    \item{onese}{
        \code{logical} scalar. Flag for using the 1-standard error rule instead of extremum value of the cross-validation criterion 
        when tuning/optimizing model parameters. Defaults to \code{FALSE}.
    }
    \item{probval}{
        \code{numeric} scalar of the survival probability at which we want to get the endpoint box survival time. Defaults to NULL.
    }
    \item{timeval}{
        \code{numeric} scalar of the survival time at which we want to get the endpoint box survival probability. Defaults to NULL.
    }
    \item{parallel.vs}{
        \code{logical}. Is parallelization to be performed for variable screening? 
        Defaults to \code{FALSE}, because it is not implemented yet.
    }
    \item{parallel.rep}{
        \code{logical}. Is parallelization to be performed for replications? Defaults to \code{FALSE}.
    }
    \item{parallel.pv}{
        \code{logical}. Is parallelization to be performed for computation of log-rank p-values? Defaults to \code{FALSE}.
    }
    \item{conf}{
        \code{list} of 5 fields containing the parameters values needed for creating the parallel backend (cluster configuration).
        See details below for usage. Optional, defaults to \code{NULL}, but all fields are required if used:
        \itemize{
            \item \code{type} : \code{character} \code{vector} specifying the cluster type ("SOCKET", "MPI").
            \item \code{spec} : A specification (\code{character} \code{vector} or \code{integer} scalar) appropriate to the type of cluster.
            \item \code{homogeneous} : \code{logical} scalar to be set to \code{FALSE} for inhomogeneous clusters.
            \item \code{verbose} : \code{logical} scalar to be set to \code{FALSE} for quiet mode.
            \item \code{outfile} : \code{character} \code{vector} of an output log file name to direct the stdout and stderr
                  connection output from the workernodes. "" indicates no redirection.
        }
    }
    \item{verbose}{
        \code{logical} scalar. Is the output to be verbose? Optional, defaults to \code{TRUE}.
    }
    \item{seed}{
        Positive \code{integer} scalar of the user seed to reproduce all the results. Defaults to \code{NULL}.
    }
}

\details{
    At this point, the main function \code{sbh} relies on an optional variable screening (pre-selection) procedure that is run 
    before the variable usage (selection) procedure is done by our PRSP algorithm. User can choose between four possible procedures:
    \itemize{
        \item Patient Recursive Survival Peeling (PRSP) (by univariate screening of our algorithm)
        \item Penalized Censored Quantile Regression (PCQR) (by Semismooth Newton Coordinate Descent fiting algorithm adapted from package \pkg{hqreg})
        \item Penalized Partial Likelihood (PPL) (by Elasticnet Regularization adapted from package \pkg{glmnet})
        \item Supervised Principal Component Analysis (SPCA) (by Supervised Principal Component adapted from package \pkg{superpc})
    }
    There is no default, but it is recommended to use PPL or SPCA for computational efficiency. Variable screening (pre-selection) is done 
    by computing occurrence frequencies of top-ranking variables over the cross-validation folds and replicates. 
    The conservativeness of the procedure is controled by the argument \code{vscons}. Example of calls for pre-selection are as follows:
    \itemize{
        \item{`1.0` represents a presence in all the folds (unanimity vote)}
        \item{`0.5` represents a presence in at least half of the folds (majority vote)}
        \item{`1/\code{K}` represents a presence in at least one of the folds (minority vote)}
    }
    Although any value in the interval [1/\code{K},1] is accepted, we recommand using the interval [1/\code{K},1/2] to avoid excessive 
    conservativeness. Final variable usage (selection) is done after running our PRSP algorithm on previously screened variables 
    by collecting those variables that have the maximum occurrence frequency in each peeling step over cross-validation folds and replicates.
    
    In the PRSP algorithm, the maximal number of peeling steps is determined either by \code{alpha} and \code{beta} metaparameters or 
    the smallest possible fraction of the training data, i.e. \eqn{\frac{1}{n}}:
    \itemize{
        \item{\code{ceiling}(\code{log}(\code{beta}) / \code{log}(1 - \code{alpha})) : \code{alpha} and \code{beta} are fixed by user}
        \item{\code{ceiling}(\code{log}(1/\eqn{n}) / \code{log}(1 - \code{alpha}))   : \code{alpha} is fixed by user and \code{beta} is fixed by data}
        \item{\code{ceiling}(\code{log}(\code{beta}) / \code{log}(1 - (1/\eqn{n})))  : \code{alpha} is fixed by data and \code{beta} is fixed by user}
        \item{\code{ceiling}(\code{log}(1/\eqn{n}) / \code{log}(1 - (1/\eqn{n})))    : \code{alpha} and \code{beta} are fixed by data}
    }
    If \code{L} is not used to specify a fixed number of peeling steps (i.e. \code{NULL}), then \code{beta} and \code{minn} are used in 
    the stopping rule instead.

    If a cross-validation is requested, the function performs a supervised (stratified) random splitting of the data based on the outcome, 
    which is in that case the \code{delta} argument. This is because it is desireable that the data splitting balances the class 
    distributions of the outcome (events) within the cross-validation splits. For each screening method and for building (by PRSP algorithm) 
    the final Survival Bump Hunting (SBH) model, all model tuning parameters are simultaneously estimated by cross-validation. 
    The function offers a number of options for the cross-validation to be perfomed: the number of replications \code{B}; the type of technique; 
    the peeling criterion; and the optimization criterion.
    
    The returned S3-class \code{sbh} object contains cross-validated estimates of all the decision-rules of used (selected) covariates and 
    all other statistical quantities of interest at each iteration of the peeling sequence (inner loop of the PRSP algorithm).
    This enables the graphical display of results of profiling curves for model tuning, peeling trajectories, covariate traces and 
    survival distributions (see plotting functions for more details).

    In case replicated cross-validations are performed, a "summary report" of the outputs is done over the \code{B} replicates as follows:
    \itemize{
        \item Even thought the PRSP algorithm uses only one covariate at a time at each peeling step, the reported matrix of 
              "Replicated CV" box decision rules may show more than one covariate being used in a given step, because these decision rules 
              are averaged over the \code{B} replicates (see equation #21 in Dazard et al. 2016).
        \item However, the reported "Replicated CV" trace values are computed (at each peeling step) as a \emph{single} modal trace value of 
              covariate usage over the \code{B} replicates. This is also reflected in the reported "Replicated CV" importance and usage plots 
              of covariate traces.
        \item The reported "Replicated CV" box membership indicators are computed (at each peeling step) as the point-wise majority vote over 
              the \code{B} replicates (right-hand side of equation #22 in Dazard et al. 2016).
        \item The reported "Replicated CV" box support vector and corresponding box sample size are computed (at each peeling step) based on 
              the above "Replicated CV" box membership indicators (i.e. \emph{not} as equation #23 in Dazard et al. 2016).
    }
    
    If the computation of log-rank \emph{p}-values is desired, then running with the parallelization option is strongly advised 
    as it may take a while. In case of large (\eqn{p > n}) or very large (\eqn{p >> n}) datasets, it is also highly recommended to use the 
    parallelization option. 
  
    The function \code{sbh} relies on the R package \pkg{parallel} to create a parallel backend within an R session, enabling access to a cluster
    of compute cores and/or nodes on a local and/or remote machine(s) and scaling-up with the number of CPU cores available and efficient parallel 
    execution. To run a procedure in parallel (with parallel RNG), argument \code{parallel} is to be set to \code{TRUE} and argument \code{conf} 
    is to be specified (i.e. non \code{NULL}). Argument \code{conf} uses the options described in function \code{makeCluster} of the R packages 
    \pkg{parallel} and \pkg{snow}. \pkg{PRIMsrc} supports two types of communication mechanisms between master and worker processes: 
    'Socket' or  'Message-Passing Interface' ('MPI'). In \pkg{PRIMsrc}, parallel 'Socket' clusters use sockets communication mechanisms only 
    (no forking) and are therefore available on all platforms, including Windows, while parallel 'MPI' clusters use high-speed interconnects 
    mechanism in networks of computers (with distributed memory) and are therefore available only in these architectures. A parallel 'MPI' 
    cluster also requires R package \pkg{Rmpi} to be installed. Value \code{type} is used to setup a cluster of type 'Socket' ("SOCKET") 
    or 'MPI' ("MPI"), respectively. Depending on this type, values of \code{spec} are to be used alternatively:
    \itemize{
        \item For 'Socket' clusters (\code{conf$type="SOCKET"}), \code{spec} should be a \code{character} \code{vector} naming the hosts on which 
              to run the job; it can default to a unique local machine, in which case, one may use the unique host name "localhost".
              Each host name can potentially be repeated to the number of CPU cores available on the local machine.
              It can also be an \code{integer} scalar specifying the number of processes to spawn on the local machine; 
              or a list of machine specifications if you have ssh installed (a character value named host specifying the name or address of the host to use).
        \item For 'MPI' clusters (\code{conf$type="MPI"}), \code{spec} should be an \code{integer} scalar 
              specifying the total number of processes to be spawned across the network of available nodes, counting the workernodes and masternode.
    }
    The actual creation of the cluster, its initialization, and closing are all done internally. For more details, 
    see the reference manual of R package \pkg{snow} and examples below.

    When random number generation is needed, the creation of separate streams of parallel RNG per node is done internally by 
    distributing the stream states to the nodes. For more details, see the vignette of R package \pkg{parallel}. 
    The use of a seed allows to reproduce the results within the same type of session: the same seed will reproduce the same results within 
    a non-parallel session or within a parallel session, but it will not necessarily give the exact same results (up to sampling variability)
    between a non-parallelized and parallelized session due to the difference of management of the seed between the two (see parallel RNG and 
    value of returned seed below).
}

\value{
    Object of \code{class} \code{sbh} (Patient Recursive Survival Peeling)
    \code{list} containing the following 21 fields:
    \item{X}{\code{numeric} \code{matrix} of original dataset.}
    \item{y}{\code{numeric} \code{vector} of observed failure / survival times.}
    \item{delta}{\code{numeric} \code{vector} of observed event indicator in \{1,0\}.}
    \item{B}{positive \code{integer} of the number of replications used in the cross-validation procedure.}
    \item{K}{positive \code{integer} of the number of folds used in the cross-validation procedure.}
    \item{A}{positive \code{integer} of the number of permutations used for the computation of log-rank p-values.}
    \item{vs}{\code{logical} scalar of returned flag of optional variable pre-selection.}
    \item{vstype}{\code{character} \code{vector} of the optional variable pre-selection procdure used.}
    \item{vsarg}{\code{character} \code{vector} of the parameters used in the pre-selection procedure.}
    \item{cv}{\code{logical} scalar of returned flag of optional cross-validation.}
    \item{cvtype}{\code{character} \code{vector} of the cross-validation technique used.}
    \item{cvarg}{\code{character} \code{vector} of the parameters used in the Survival Bump Hunting procedure.}
    \item{pv}{\code{logical} scalar of returned flag of optional computation of log-rank p-values.}
    \item{onese}{\code{logical} scalar of returned flag of 1-standard error rule.}
    \item{decimals}{\code{integer} of the number of user-specified significant decimals.}
    \item{probval}{\code{Numeric} scalar of survival probability used.}
    \item{timeval}{\code{Numeric} scalar of survival time used.}
    \item{cvprofiles}{\code{list} of 10 fields of cross-validated tuning profiles and estimates,
        each of length \code{B} (one for each replicate):
        \itemize{
            \item{cv.varprofiles: \code{numeric} \code{matrix} of cross-validation criterion used for tuning/optimizing  
                the variable screening size in the PRSP variable screening (pre-selection) procedure (\code{NULL} otherwise). 
                Values are by columns (peeling steps) and replicates (rows).}
            \item{cv.varprofiles.mean: \code{numeric} \code{vector} of means (across replicates) of the above cross-validation 
                criterion by peeling steps.}
            \item{cv.varprofiles.se: \code{numeric} \code{vector} of standard errors (across replicates) of the above cross-validation 
                criterion by peeling steps.}
            \item{cv.varset.opt: \code{numeric} scalar of optimal variable screening size according to the extremum.}
            \item{cv.varset.1se: \code{numeric} scalar of optimal variable screening size according to 1SE rule.}
            \item{cv.stepprofiles: \code{numeric} \code{matrix} of cross-validation criterion used for tuning/optimizing  
                the peeling sequence length (i.e. number of peeling steps) in the PRSP algorithm. 
                Values are by columns (peeling steps) and replicates (rows).}
            \item{cv.stepprofiles.mean: \code{numeric} \code{vector} of means (across replicates) of the above cross-validation 
                criterion by peeling steps.}
            \item{cv.stepprofiles.se: \code{numeric} \code{vector} of standard errors (across replicates) of the above cross-validation 
                criterion by peeling steps.}
            \item{cv.nsteps.opt: \code{numeric} scalar of optimal number of peeling steps according to the extremum.}
            \item{cv.nsteps.1se: \code{numeric} scalar of optimal number of peeling steps according to 1SE rule.}
        }
    }
    \item{cvfit}{\code{list} with 12 fields of cross-validated SBH output estimates,
        each of length \code{B} (one for each replicate):
        \itemize{
            \item{cv.maxsteps: \code{numeric} scalar of maximal number of peeling steps over the replicates.}
            \item{cv.nsteps: \code{numeric} scalar of optimal number of peeling steps according to the optimization criterion.}
            \item{cv.boxind: \code{logical} \code{matrix} in {\code{TRUE}, \code{FALSE}} of individual observation box membership 
                indicator (columns) for all peeling steps (rows).}
            \item{cv.boxind.size: \code{numeric} \code{vector} of box sample size for all peeling steps.}
            \item{cv.boxind.support: \code{numeric} \code{vector} of box support for all peeling steps.}
            \item{cv.rules: \code{data.frame} of decision rules on the covariates (columns) for all peeling steps (rows).}
            \item{cv.screened: \code{numeric} \code{vector} of screened (pre-selected) covariates, indexed in reference to original index.}
            \item{cv.trace: \code{numeric} \code{vector} of the modal trace values of covariate usage for all peeling steps.}
            \item{cv.sign: \code{numeric} \code{vector} in \{-1,+1\} of directions of peeling for all used (selected) covariates.} 
            \item{cv.used: \code{numeric} \code{vector} of covariates used (selected) for peeling, indexed in reference to original index.}
            \item{cv.stats: \code{numeric} \code{matrix} of box endpoint quantities of interest (columns) for all peeling steps (rows).}
            \item{cv.pval: \code{list} with 2 fields of two \code{vectors}. 
                The first \code{pval} is a \code{numeric} \code{vector} for log-rank p-values of separation of survival distributions,
                The second \code{seed} is is an \code{integer} scalar if parallelization is used, or an \code{integer} \code{vector} 
                of \code{A} values, one for each permutation, if parallelization is not used.}
        }
    }
    \item{success}{\code{logical} scalar of the returned flag of success at fitting the SBH model.}
    \item{seed}{User seed. An \code{integer} scalar if parallelization is used, or an \code{integer} \code{vector} 
        of \code{B} values, one for each replication, if parallelization is not used.}
}

\author{
    \itemize{
        \item "Jean-Eudes Dazard, Ph.D." \email{jean-eudes.dazard@case.edu}
        \item "Michael Choe, M.D." \email{mjc206@case.edu}
        \item "Michael LeBlanc, Ph.D." \email{mleblanc@fhcrc.org}
        \item "Alberto Santana, MBA." \email{ahs4@case.edu}
    }
    Maintainer: "Jean-Eudes Dazard, Ph.D." \email{jean-eudes.dazard@case.edu}
}

\references{
    \itemize{
        \item Dazard J-E. and Rao J.S. (2017).
              "\emph{Variable Selection Strategies for High-Dimensional Survival Bump Hunting using Recursive Peeling Methods.}"
              (in prep).
        \item Yi C. and Huang J. (2016).
              "\emph{Semismooth Newton Coordinate Descent Algorithm for Elastic-Net Penalized Huber Loss Regression and Quantile Regression}."
              J. Comp Graph. Statistics, DOI: 10.1080/10618600.2016.1256816.
        \item Dazard J-E., Choe M., LeBlanc M. and Rao J.S. (2016).
              "\emph{Cross-validation and Peeling Strategies for Survival Bump Hunting using Recursive Peeling Methods.}"
              Statistical Analysis and Data Mining, 9(1):12-42.
        \item Dazard J-E., Choe M., LeBlanc M. and Rao J.S. (2015).
              "\emph{R package PRIMsrc: Bump Hunting by Patient Rule Induction Method for Survival, Regression and Classification.}"
              In JSM Proceedings, Statistical Programmers and Analysts Section. Seattle, WA, USA.
              American Statistical Association IMS - JSM, p. 650-664.
        \item Dazard J-E., Choe M., LeBlanc M. and Rao J.S. (2014).
              "\emph{Cross-Validation of Survival Bump Hunting by Recursive Peeling Methods.}"
              In JSM Proceedings, Survival Methods for Risk Estimation/Prediction Section. Boston, MA, USA.
              American Statistical Association IMS - JSM, p. 3366-3380.
        \item Dazard J-E. and J.S. Rao (2010).
              "\emph{Local Sparse Bump Hunting.}"
              J. Comp Graph. Statistics, 19(4):900-92.
    }
}

\section{Acknowledgments}{
    This work made use of the High Performance Computing Resource in the Core Facility for Advanced Research Computing at Case Western Reserve University. 
    This project was partially funded by the National Institutes of Health NIH - National Cancer Institute (R01-CA160593) to J-E. Dazard and J.S. Rao.
}

\note{
    Unique end-user function for fitting the Survival Bump Hunting model.
}

\keyword{Exploratory Survival/Risk Analysis}
\keyword{Survival/Risk Estimation & Prediction}
\keyword{Non-Parametric Method}
\keyword{Cross-Validation}
\keyword{Bump Hunting}
\keyword{Rule-Induction Method}

\seealso{
    \itemize{
        \item \code{makeCluster} (R package \pkg{parallel})
        \item \code{glmnet}, \code{cv.glmnet} (R package \pkg{glmnet})
        \item \code{hqreg}, \code{cv.hqreg} (R package \pkg{hqreg})
        \item \code{superpc.cv} (R package \pkg{superpc})
    }
}

\examples{
#===================================================
# Loading the library and its dependencies
#===================================================
library("PRIMsrc")

\dontrun{
    #===================================================
    # PRIMsrc Package news
    #===================================================
    PRIMsrc.news()
    
    #===================================================
    # PRIMsrc Package citation
    #===================================================
    citation("PRIMsrc")
    
    #===================================================
    # Demo with a synthetic dataset
    # Use help for descriptions
    #===================================================
    data("Synthetic.1", package="PRIMsrc")
    ?Synthetic.1
}

#===================================================
# Simulated dataset #1 (n=250, p=3)
# Peeling criterion = LRT
# Cross-Validation criterion = LRT
# With Combined Cross-Validation (RCCV)
# Without Replications (B = 1)
# Without variable screening (pre-selection)
# Without computation of log-rank permutation p-values
# Without parallelization
#===================================================
synt1 <- sbh(X = Synthetic.1[ , -c(1,2), drop=FALSE],
             y = Synthetic.1[ ,1, drop=TRUE],
             delta = Synthetic.1[ ,2, drop=TRUE],
             B = 1,
             K = 3,
             vs = FALSE,
             cv = TRUE,
             cvtype = "combined",
             cvarg = "alpha=0.10,
                      beta=0.05,
                      minn=5,
                      L=NULL,
                      peelcriterion=\"lrt\",
                      cvcriterion=\"lrt\"",
             pv = FALSE,
             decimals = 2,
             onese = FALSE,
             probval = 0.5,
             timeval = NULL,
             parallel.vs = FALSE,
             parallel.rep = FALSE,
             parallel.pv = FALSE,
             conf = NULL,
             verbose = FALSE,
             seed = 123)

summary(object = synt1)
print(x = synt1)

n <- 100
p <- length(synt1$cvfit$cv.used)
x <- matrix(data = runif(n = n*p, min = 0, max = 1),
            nrow = n, ncol = p, byrow = FALSE,
            dimnames=list(1:n, paste("X", 1:p, sep="")))
synt1.pred <- predict(object = synt1,
                      newdata = x,
                      steps = synt1$cvfit$cv.nsteps)

plot(x = synt1,
     main = paste("Scatter plot for model #1", sep=""),
     proj = c(1,2), splom = TRUE, boxes = TRUE,
     steps = synt1$cvfit$cv.nsteps,
     pch = 16, cex = 0.5, col = 2,
     col.box = 2, lty.box = 2, lwd.box = 1,
     add.legend = TRUE, device = NULL)
     
plot_profile(object = synt1,
             main = "Cross-validated tuning profiles for model #1",
             pch=20, col=1, lty=1, lwd=0.5, cex=0.5,
             add.sd = TRUE, add.legend = TRUE, add.profiles = TRUE,
             device = NULL, file = "Profile Plot", path=getwd(),
             horizontal = FALSE, width = 8.5, height = 5.0)

plot_boxtraj(object = synt1,
             main = paste("Cross-validated peeling trajectories for model #1", sep=""),
             col=1, lty=1, lwd=0.5, cex=0.5,
             toplot = synt1$cvfit$cv.used,
             device = NULL, file = "Trajectory Plots", path=getwd(),
             horizontal = FALSE, width = 8.5, height = 8.5)

plot_boxtrace(object = synt1,
              main = paste("Cross-validated trace plots for model #1", sep=""),
              xlab = "Box Mass", ylab = "Covariate Range (centered)",
              col=1, lty=1, lwd=0.5, cex=0.5,
              toplot = synt1$cvfit$cv.used,
              center = TRUE, scale = FALSE,
              device = NULL, file = "Covariate Trace Plots", path=getwd(),
              horizontal = FALSE, width = 8.5, height = 8.5)

plot_boxkm(object = synt1,
           main = paste("Cross-validated probability curves for model #1", sep=""),
           xlab = "Time", ylab = "Probability",
           col=2, lty=1, lwd=0.5, cex=0.5,
           device = NULL, file = "Survival Plots", path=getwd(),
           horizontal = TRUE, width = 11.5, height = 8.5)

\dontrun{
    #===================================================
    # Examples of parallel backend parametrization 
    #===================================================
    if (require("parallel")) {
       print("'parallel' is attached correctly \n")
    } else {
       stop("'parallel' must be attached first \n")
    }
    #===================================================
    # Example #1 - Quad core PC 
    # Running WINDOWS with SOCKET communication
    #===================================================
    cpus <- parallel::detectCores(logical = TRUE)
    conf <- list("spec" = rep("localhost", cpus),
                 "type" = "SOCKET",
                 "homo" = TRUE,
                 "verbose" = TRUE,
                 "outfile" = "")
    #===================================================
    # Example #2 - Master node + 3 Worker nodes cluster
    # Running LINUX with SOCKET communication
    # All nodes equipped with identical setups of 
    # multicores (8 core CPUs per machine for a total of 32)
    #===================================================
    masterhost <- Sys.getenv("HOSTNAME")
    slavehosts <- c("compute-0-0", "compute-0-1", "compute-0-2")
    nodes <- length(slavehosts) + 1
    cpus <- 8
    conf <- list("spec" = c(rep(masterhost, cpus),
                            rep(slavehosts, cpus)),
                 "type" = "SOCKET",
                 "homo" = TRUE,
                 "verbose" = TRUE,
                 "outfile" = "")
    #===================================================
    # Example #3 - Multinode of multicore per node cluster
    # Running LINUX with SLURM scheduler and MPI communication
    # Below, variable 'cpus' is the total number 
    # of requested core CPUs, which is specified from  
    # within a SLURM script.
    #===================================================
    if (require("Rmpi")) {
        print("'Rmpi' is attached correctly \n")
    } else {
        stop("'Rmpi' must be attached first \n")
    }
    cpus <- as.numeric(Sys.getenv("SLURM_NTASKS"))
    conf <- list("spec" = cpus,
                 "type" = "MPI",
                 "homo" = TRUE,
                 "verbose" = TRUE,
                 "outfile" = "")
    #===================================================
    # Simulated dataset #1 (n=250, p=3)
    # Peeling criterion = LRT
    # Cross-Validation criterion = LRT
    # With Combined Cross-Validation (RCCV)
    # With Replications (B = 30)
    # With variable screening (pre-selection) (PPL)
    # With computation of log-rank permutation p-values
    # With parallelization
    #===================================================                         
    synt1 <- sbh(X = Synthetic.1[ , -c(1,2), drop=FALSE],
                 y = Synthetic.1[ ,1, drop=TRUE],
                 delta = Synthetic.1[ ,2, drop=TRUE],
                 B = 30,
                 K = 5,
                 A = 1000,
                 vs = TRUE,
                 vstype = "ppl",
                 vsarg = "alpha=1,
                          nalpha=1,
                          nlambda=100,
                          vscons=0.5",
                 cv = TRUE,
                 cvtype = "combined",
                 cvarg = "alpha=0.01,
                          beta=0.05,
                          minn=5,
                          L=NULL,
                          peelcriterion=\"lrt\",
                          cvcriterion=\"lrt\"",
                 pv = TRUE,
                 decimals = 2,
                 onese = FALSE,
                 probval = 0.5,
                 timeval = NULL,
                 parallel.vs = FALSE,
                 parallel.rep = TRUE,
                 parallel.pv = TRUE,
                 conf = conf,
                 verbose = TRUE,
                 seed = 123)
}
}
