'Returns the hazard-weighted average of covariate values for
subjects who are at-risk at a particular time.
Parameters
params : ndarray
Parameter vector
Returns
averages : list of ndarrays
averages[stx][i,:] is a row vector containing the weighted
average values (for all the covariates) of at-risk
subjects a the i^th largest observed failure time in
stratum `stx`, using the hazard multipliers as weights.
Notes
Used to calculate leverages and score residuals.'

def weighted_covariate_averages(self, params):

    surv = self.surv
    averages = []
    (xp0, xp1) = (0.0, 0.0)
    for stx in range(surv.nstrat):
        uft_ix = surv.ufailt_ix[stx]
        exog_s = surv.exog_s[stx]
        nuft = len(uft_ix)
        average_s = np.zeros((len(uft_ix), exog_s.shape[1]), dtype=np.float64)
        linpred = np.dot(exog_s, params)
        if (surv.offset_s is not None):
            linpred += surv.offset_s[stx]
        linpred -= linpred.max()
        e_linpred = np.exp(linpred)
        for i in range(nuft)[::(-1)]:
            ix = surv.risk_enter[stx][i]
            xp0 += e_linpred[ix].sum()
            xp1 += np.dot(e_linpred[ix], exog_s[ix, :])
            average_s[i, :] = (xp1 / xp0)
            ix = surv.risk_exit[stx][i]
            xp0 -= e_linpred[ix].sum()
            xp1 -= np.dot(e_linpred[ix], exog_s[ix, :])
        averages.append(average_s)
    return averages
