class_docstr: Class for fitting the Aalen-Johansen estimate for the cumulative incidence function in a competing risks framework.
  Treating competing risks as censoring can result in over-estimated cumulative density functions. Using the Kaplan
  Meier estimator with competing risks as censored is akin to estimating the cumulative density if all competing risks
  had been prevented.
  
  Aalen-Johansen cannot deal with tied times. We can get around this by randomly jittering the event times
  slightly. This will be done automatically and generates a warning.
  
  
  Parameters
  ----------
  alpha: float, option (default=0.05)
      The alpha value associated with the confidence intervals.
  
  jitter_level: float, option (default=0.00001)
      If tied event times are detected, event times are randomly changed by this factor.
  
  seed: int, option (default=None)
      To produce replicate results with tied event times, the numpy.random.seed can be specified in the function.
  
  calculate_variance: bool, option (default=True)
      By default, AalenJohansenFitter calculates the variance and corresponding confidence intervals. Due to how the
      variance is calculated, the variance must be calculated for each event time individually. This is
      computationally intensive. For some procedures, like bootstrapping, the variance is not necessary. To reduce
      computation time during these procedures, `calculate_variance` can be set to `False` to skip the variance
      calculation.
  
  Example
  -------
  
  .. code:: python
  
      from lifelines import AalenJohansenFitter
      from lifelines.datasets import load_waltons
      T, E = load_waltons()['T'], load_waltons()['E']
      ajf = AalenJohansenFitter(calculate_variance=True)
      ajf.fit(T, E, event_of_interest=1)
      ajf.cumulative_density_
      ajf.plot()
  
  
  References
  ----------
  If you are interested in learning more, we recommend the following open-access
  paper; Edwards JK, Hester LL, Gokhale M, Lesko CR. Methodologic Issues When Estimating Risks in
  Pharmacoepidemiology. Curr Epidemiol Rep. 2016;3(4):285-296.
docstr: Parameters
  ----------
    durations: an array or pd.Series of length n -- duration of subject was observed for
    event_observed: an array, or pd.Series, of length n. Integer indicator of distinct events. Must be
       only positive integers, where 0 indicates censoring.
    event_of_interest: integer -- indicator for event of interest. All other integers are considered competing events
       Ex) event_observed contains 0, 1, 2 where 0:censored, 1:lung cancer, and 2:death. If event_of_interest=1, then death (2)
       is considered a competing event. The returned cumulative incidence function corresponds to risk of lung cancer
    timeline: return the best estimate at the values in timelines (positively increasing)
    entry: an array, or pd.Series, of length n -- relative time when a subject entered the study. This is
       useful for left-truncated (not left-censored) observations. If None, all members of the population
       were born at time 0.
    label: a string to name the column of the estimate.
    alpha: the alpha value in the confidence intervals. Overrides the initializing
       alpha for this call to fit only.
    ci_labels: add custom column names to the generated confidence intervals
          as a length-2 list: [<lower-bound name>, <upper-bound name>]. Default: <label>_lower_<1-alpha/2>
    weights: n array, or pd.Series, of length n, if providing a weighted dataset. For example, instead
        of providing every subject as a single element of `durations` and `event_observed`, one could
        weigh subject differently.
  
  Returns
  -------
  self : AalenJohansenFitter
    self, with new properties like ``cumulative_incidence_``.
docstr_tok: ["Parameters","--","--","--","--","--","durations",":","an","array","or","pd.Series","of","length","n","--","duration","of","subject","was","observed","for","event_observed",":","an","array",",","or","pd.Series",",","of","length","n.","Integer","indicator","of","distinct","events",".","Must","be","only","positive","integers",",","where","0","indicates","censoring",".","event_of_interest",":","integer","--","indicator","for","event","of","interest",".","All","other","integers","are","considered","competing","events","Ex",")","event_observed","contains","0",",","1",",","2","where","0",":","censored",",","1",":","lung","cancer",",","and","2",":","death",".","If","event_of_interest=1",",","then","death","(","2",")","is","considered","a","competing","event",".","The","returned","cumulative","incidence","function","corresponds","to","risk","of","lung","cancer","timeline",":","return","the","best","estimate","at","the","values","in","timelines","(","positively","increasing",")","entry",":","an","array",",","or","pd.Series",",","of","length","n","--","relative","time","when","a","subject","entered","the","study",".","This","is","useful","for","left-truncated","(","not","left-censored",")","observations",".","If","None",",","all","members","of","the","population","were","born","at","time","0.","label",":","a","string","to","name","the","column","of","the","estimate",".","alpha",":","the","alpha","value","in","the","confidence","intervals",".","Overrides","the","initializing","alpha","for","this","call","to","fit","only",".","ci_labels",":","add","custom","column","names","to","the","generated","confidence","intervals","as","a","length-2","list",":","[","<","lower-bound","name",">",",","<","upper-bound","name",">","]",".","Default",":","<","label",">","_lower_","<","1-alpha\/2",">","weights",":","n","array",",","or","pd.Series",",","of","length","n",",","if","providing","a","weighted","dataset",".","For","example",",","instead","of","providing","every","subject","as","a","single","element","of","`","durations","`","and","`","event_observed","`",",","one","could","weigh","subject","differently",".","Returns","--","--","--","-","self",":","AalenJohansenFitter","self",",","with","new","properties","like","``","cumulative_incidence_","``","."]
code: def fit(
      self,
      durations,
      event_observed,
      event_of_interest,
      timeline=None,
      entry=None,
      label=None,
      alpha=None,
      ci_labels=None,
      weights=None,
  ):  # pylint: disable=too-many-arguments,too-many-locals
      """
      Parameters
      ----------
        durations: an array or pd.Series of length n -- duration of subject was observed for
        event_observed: an array, or pd.Series, of length n. Integer indicator of distinct events. Must be
           only positive integers, where 0 indicates censoring.
        event_of_interest: integer -- indicator for event of interest. All other integers are considered competing events
           Ex) event_observed contains 0, 1, 2 where 0:censored, 1:lung cancer, and 2:death. If event_of_interest=1, then death (2)
           is considered a competing event. The returned cumulative incidence function corresponds to risk of lung cancer
        timeline: return the best estimate at the values in timelines (positively increasing)
        entry: an array, or pd.Series, of length n -- relative time when a subject entered the study. This is
           useful for left-truncated (not left-censored) observations. If None, all members of the population
           were born at time 0.
        label: a string to name the column of the estimate.
        alpha: the alpha value in the confidence intervals. Overrides the initializing
           alpha for this call to fit only.
        ci_labels: add custom column names to the generated confidence intervals
              as a length-2 list: [<lower-bound name>, <upper-bound name>]. Default: <label>_lower_<1-alpha/2>
        weights: n array, or pd.Series, of length n, if providing a weighted dataset. For example, instead
            of providing every subject as a single element of `durations` and `event_observed`, one could
            weigh subject differently.
  
      Returns
      -------
      self : AalenJohansenFitter
        self, with new properties like ``cumulative_incidence_``.
      """
      # Checking for tied event times
      ties = self._check_for_duplicates(
          durations=durations, events=event_observed
      )
  
      if ties:
          warnings.warn(
              dedent(
                  """Tied event times were detected. The Aalen-Johansen estimator cannot handle tied event times.
                  To resolve ties, data is randomly jittered."""
              ),
              Warning,
          )
          durations = self._jitter(
              durations=pd.Series(durations),
              event=pd.Series(event_observed),
              jitter_level=self._jitter_level,
              seed=self._seed,
          )
  
      alpha = alpha if alpha else self.alpha
  
      # Creating label for event of interest & indicator for that event
      event_of_interest = int(event_of_interest)
      cmprisk_label = "CIF_" + str(event_of_interest)
      self.label_cmprisk = "observed_" + str(event_of_interest)
  
      # Fitting Kaplan-Meier for either event of interest OR competing risk
      km = KaplanMeierFitter().fit(
          durations,
          event_observed=event_observed,
          timeline=timeline,
          entry=entry,
          weights=weights,
      )
      aj = km.event_table
      aj["overall_survival"] = km.survival_function_
      aj["lagged_overall_survival"] = aj["overall_survival"].shift()
  
      # Setting up table for calculations and to return to user
      event_spec = pd.Series(event_observed) == event_of_interest
      (
          self.durations,
          self.event_observed,
          *_,
          event_table,
          weights,
      ) = _preprocess_inputs(
          durations=durations,
          event_observed=event_spec,
          timeline=timeline,
          entry=entry,
          weights=weights,
      )
      event_spec_times = event_table["observed"]
      event_spec_times = event_spec_times.rename(self.label_cmprisk)
      aj = pd.concat([aj, event_spec_times], axis=1).reset_index()
  
      # Estimator of Cumulative Incidence (Density) Function
      aj[cmprisk_label] = (
          aj[self.label_cmprisk]
          / aj["at_risk"]
          * aj["lagged_overall_survival"]
      ).cumsum()
      aj.loc[0, cmprisk_label] = 0  # Setting initial CIF to be zero
      aj = aj.set_index("event_at")
  
      # Setting attributes
      self._estimation_method = "cumulative_density_"
      self._estimate_name = "cumulative_density_"
      self.timeline = km.timeline
  
      self._label = coalesce(label, self._label, "AJ_estimate")
      self.cumulative_density_ = pd.DataFrame(aj[cmprisk_label])
  
      # Technically, cumulative incidence, but consistent with KaplanMeierFitter
      self.event_table = aj[
          [
              "removed",
              "observed",
              self.label_cmprisk,
              "censored",
              "entrance",
              "at_risk",
          ]
      ]  # Event table
  
      if self._calc_var:
          self.variance_, self.confidence_interval_ = self._bounds(
              aj["lagged_overall_survival"],
              alpha=alpha,
              ci_labels=ci_labels,
          )
      else:
          self.variance_, self.confidence_interval_ = None, None
  
      self.confidence_interval_cumulative_density_ = (
          self.confidence_interval_
      )
      return self
  
file_path: lifelines/lifelines/fitters/aalen_johansen_fitter.py
imports: from textwrap import dedent
  import numpy
  import pandas
  import warnings
  from lifelines.fitters import NonParametricUnivariateFitter
  from lifelines.utils import _preprocess_inputs, inv_normal_cdf, CensoringType, coalesce
  from lifelines import KaplanMeierFitter
  from lifelines.plotting import _plot_estimate
label_desc: Use image node_id 2 for calling the AalenJohansenFitter obj's underlying member method code with example usage: obj.fit(durations, event_observed, event_of_interest, timeline, entry, label, alpha, ci_labels, weights) and returns: self