class_docstr: This class implements fitting Cox's time-varying proportional hazard model:
  
      .. math::  h(t|x(t)) = h_0(t)\exp((x(t)-\overline{x})'\beta)
  
  Parameters
  ----------
  alpha: float, optional (default=0.05)
     the level in the confidence intervals.
  penalizer: float, optional
      the coefficient of an L2 penalizer in the regression
  
  Attributes
  ----------
  params_ : Series
      The estimated coefficients. Changed in version 0.22.0: use to be ``.hazards_``
  hazard_ratios_ : Series
      The exp(coefficients)
  confidence_intervals_ : DataFrame
      The lower and upper confidence intervals for the hazard coefficients
  event_observed: Series
      The event_observed variable provided
  weights: Series
      The event_observed variable provided
  variance_matrix_ : DataFrame
      The variance matrix of the coefficients
  strata: list | str
      the strata provided
  standard_errors_: Series
      the standard errors of the estimates
  baseline_cumulative_hazard_: DataFrame
  baseline_survival_: DataFrame
class_docstr_tok: ["This","class","implements","fitting","Cox","'s","time-varying","proportional","hazard","model",":","..","math",":",":","h","(","t|x","(","t",")",")","=","h_0","(","t",")","\\exp","(","(","x","(","t",")","-\\overline","{","x","}",")","'\\beta",")","Parameters","--","--","--","--","--","alpha",":","float",",","optional","(","default=0.05",")","the","level","in","the","confidence","intervals",".","penalizer",":","float",",","optional","the","coefficient","of","an","L2","penalizer","in","the","regression","Attributes","--","--","--","--","--","params_",":","Series","The","estimated","coefficients",".","Changed","in","version","0.22.0",":","use","to","be","``",".hazards_","``","hazard_ratios_",":","Series","The","exp","(","coefficients",")","confidence_intervals_",":","DataFrame","The","lower","and","upper","confidence","intervals","for","the","hazard","coefficients","event_observed",":","Series","The","event_observed","variable","provided","weights",":","Series","The","event_observed","variable","provided","variance_matrix_",":","DataFrame","The","variance","matrix","of","the","coefficients","strata",":","list","|","str","the","strata","provided","standard_errors_",":","Series","the","standard","errors","of","the","estimates","baseline_cumulative_hazard_",":","DataFrame","baseline_survival_",":","DataFrame"]
docstr: Newton Raphson algorithm for fitting CPH model.
  
  Parameters
  ----------
  df: DataFrame
  stop_times_events: DataFrame
       meta information about the subjects history
  show_progress: bool, optional (default: True)
      to show verbose output of convergence
  step_size: float
      > 0 to determine a starting step size in NR algorithm.
  precision: float
      the algorithm stops if the norm of delta between
      successive positions is less than ``precision``.
  r_precision: float, optional
      the algorithms stops if the relative decrease in log-likelihood
      between successive iterations goes below ``r_precision``.
  
  Returns
  --------
  beta: (1,d) numpy array.
docstr_tok: ["Newton","Raphson","algorithm","for","fitting","CPH","model",".","Parameters","--","--","--","--","--","df",":","DataFrame","stop_times_events",":","DataFrame","meta","information","about","the","subjects","history","show_progress",":","bool",",","optional","(","default",":","True",")","to","show","verbose","output","of","convergence","step_size",":","float",">","0","to","determine","a","starting","step","size","in","NR","algorithm",".","precision",":","float","the","algorithm","stops","if","the","norm","of","delta","between","successive","positions","is","less","than","``","precision","``",".","r_precision",":","float",",","optional","the","algorithms","stops","if","the","relative","decrease","in","log-likelihood","between","successive","iterations","goes","below","``","r_precision","``",".","Returns","--","--","--","--","beta",":","(","1",",","d",")","numpy","array","."]
code: def _newton_raphson_for_efron_model(
      self,
      df,
      events,
      start,
      stop,
      weights,
      show_progress=False,
      step_size=0.95,
      precision=1e-8,
      r_precision=1e-9,
      max_steps=50,
      initial_point=None,
  ):  # pylint: disable=too-many-arguments,too-many-locals,too-many-branches,too-many-statements
      """
      Newton Raphson algorithm for fitting CPH model.
  
      Parameters
      ----------
      df: DataFrame
      stop_times_events: DataFrame
           meta information about the subjects history
      show_progress: bool, optional (default: True)
          to show verbose output of convergence
      step_size: float
          > 0 to determine a starting step size in NR algorithm.
      precision: float
          the algorithm stops if the norm of delta between
          successive positions is less than ``precision``.
      r_precision: float, optional
          the algorithms stops if the relative decrease in log-likelihood
          between successive iterations goes below ``r_precision``.
  
      Returns
      --------
      beta: (1,d) numpy array.
      """
      assert (
          precision <= 1.0
      ), "precision must be less than or equal to 1."
  
      # soft penalizer functions, from https://www.cs.ubc.ca/cgi-bin/tr/2009/TR-2009-19.pdf
      soft_abs = (
          lambda x, a: 1
          / a
          * (anp.logaddexp(0, -a * x) + anp.logaddexp(0, a * x))
      )
      penalizer = (
          lambda beta, a: n
          * (
              self.penalizer
              * (
                  self.l1_ratio * (soft_abs(beta, a))
                  + 0.5 * (1 - self.l1_ratio) * (beta**2)
              )
          ).sum()
      )
      d_penalizer = elementwise_grad(penalizer)
      dd_penalizer = elementwise_grad(d_penalizer)
  
      n, d = df.shape
  
      # make sure betas are correct size.
      if initial_point is not None:
          beta = initial_point
      else:
          beta = np.zeros((d,))
  
      i = 0
      converging = True
      ll, previous_ll = 0, 0
      start_time = time.time()
  
      step_sizer = StepSizer(step_size)
      step_size = step_sizer.next()
  
      while converging:
          i += 1
  
          if self.strata is None:
              h, g, ll = self._get_gradients(
                  df.values,
                  events.values,
                  start.values,
                  stop.values,
                  weights.values,
                  beta,
              )
          else:
              g = np.zeros_like(beta)
              h = np.zeros((d, d))
              ll = 0
              for _h, _g, _ll in self._partition_by_strata_and_apply(
                  df,
                  events,
                  start,
                  stop,
                  weights,
                  self._get_gradients,
                  beta,
              ):
                  g += _g
                  h += _h
                  ll += _ll
  
          if i == 1 and np.all(beta == 0):
              # this is a neat optimization, the null partial likelihood
              # is the same as the full partial but evaluated at zero.
              # if the user supplied a non-trivial initial point, we need to delay this.
              self._log_likelihood_null = ll
  
          if (
              isinstance(self.penalizer, np.ndarray)
              or self.penalizer > 0
          ):
              ll -= penalizer(beta, 1.5**i)
              g -= d_penalizer(beta, 1.5**i)
              h[np.diag_indices(d)] -= dd_penalizer(beta, 1.5**i)
  
          try:
              # reusing a piece to make g * inv(h) * g.T faster later
              inv_h_dot_g_T = spsolve(-h, g, assume_a="pos")
          except ValueError as e:
              if "infs or NaNs" in str(e):
                  raise ConvergenceError(
                      """hessian or gradient contains nan or inf value(s). Convergence halted. Please see the following tips in the lifelines documentation:
  https://lifelines.readthedocs.io/en/latest/Examples.html#problems-with-convergence-in-the-cox-proportional-hazard-model
  """,
                      e,
                  )
              else:
                  # something else?
                  raise e
          except LinAlgError as e:
              raise ConvergenceError(
                  """Convergence halted due to matrix inversion problems. Suspicion is high colinearity. Please see the following tips in the lifelines documentation:
  https://lifelines.readthedocs.io/en/latest/Examples.html#problems-with-convergence-in-the-cox-proportional-hazard-model
  """,
                  e,
              )
  
          delta = step_size * inv_h_dot_g_T
  
          if np.any(np.isnan(delta)):
              raise ConvergenceError(
                  """delta contains nan value(s). Convergence halted. Please see the following tips in the lifelines documentation:
  https://lifelines.readthedocs.io/en/latest/Examples.html#problems-with-convergence-in-the-cox-proportional-hazard-model
  """
              )
          # Save these as pending result
          hessian, gradient = h, g
          norm_delta = norm(delta)
          newton_decrement = g.dot(inv_h_dot_g_T) / 2
  
          if show_progress:
              print(
                  "\rIteration %d: norm_delta = %.2e, step_size = %.4f, log_lik = %.5f, newton_decrement = %.2e, seconds_since_start = %.1f"
                  % (
                      i,
                      norm_delta,
                      step_size,
                      ll,
                      newton_decrement,
                      time.time() - start_time,
                  )
              )
  
          # convergence criteria
          if norm_delta < precision:
              converging, completed = False, True
          elif (
              previous_ll > 0
              and abs(ll - previous_ll) / (-previous_ll) < r_precision
          ):
              # this is what R uses by default with r_precision=1e-9
              converging, completed = False, True
          elif newton_decrement < precision:
              converging, completed = False, True
          elif i >= max_steps:
              # 50 iterations steps with N-R is a lot.
              # Expected convergence is less than 10 steps
              converging, completed = False, False
          elif step_size <= 0.0001:
              converging, completed = False, False
          elif abs(ll) < 0.0001 and norm_delta > 1.0:
              warnings.warn(
                  "The log-likelihood is getting suspiciously close to 0 and the delta is still large. There may be complete separation in the dataset. This may result in incorrect inference of coefficients. \
  See https://stats.stackexchange.com/questions/11109/how-to-deal-with-perfect-separation-in-logistic-regression\n",
                  ConvergenceWarning,
              )
              converging, completed = False, False
  
          step_size = step_sizer.update(norm_delta).next()
  
          beta += delta
  
      if show_progress and completed:
          print("Convergence completed after %d iterations." % (i))
      elif show_progress and not completed:
          print("Convergence failed. See any warning messages.")
  
      # report to the user problems that we detect.
      if completed and norm_delta > 0.1:
          warnings.warn(
              "Newton-Raphson convergence completed but norm(delta) is still high, %.3f. This may imply non-unique solutions to the maximum likelihood. Perhaps there is colinearity or complete separation in the dataset?"
              % norm_delta,
              ConvergenceWarning,
          )
      elif not completed:
          warnings.warn(
              "Newton-Raphson failed to converge sufficiently in %d steps."
              % max_steps,
              ConvergenceWarning,
          )
  
      return beta, ll, hessian
  
imports: from datetime import datetime
  import warnings
  import time
  from typing import Optional
  import numpy
  import pandas
  from scipy import stats
  from numpy.linalg import norm, inv
  from numpy import sum
  from scipy.linalg import solve, LinAlgError
  from autograd import elementwise_grad
  from autograd import numpy
  from lifelines.fitters import SemiParametricRegressionFitter
  from lifelines.fitters.mixins import ProportionalHazardMixin
  from lifelines.utils.printer import Printer
  from lifelines.statistics import _chisq_test_p_value, StatisticalResult
  from lifelines.exceptions import ConvergenceError, ConvergenceWarning
  from lifelines.utils import _get_index, _to_list, check_for_numeric_dtypes_or_raise, check_low_var, check_complete_separation_low_variance, check_for_immediate_deaths, check_for_instantaneous_events_at_time_zero, check_for_instantaneous_events_at_death_time, check_for_nonnegative_intervals, pass_for_numeric_dtypes_or_raise_array, inv_normal_cdf, normalize, StepSizer, check_nans_or_infs, string_rjustify, coalesce
  from lifelines import utils
label_desc: Use image node_id 10 for calling the CoxTimeVaryingFitter obj's underlying member method code with example usage: obj._newton_raphson_for_efron_model(df, events, start, stop, weights, show_progress, step_size, precision, r_precision, max_steps, initial_point) and returns: beta,  ll,  hessian