A positive value of the residual shows an X value that is higher than expected at that death time.

def _compute_schoenfeld_within_strata(self, X, T, E, weights):
        """
        A positive value of the residual shows an X value that is higher than expected at that death time.
        """
        # TODO: the diff_against is gross
        # This uses Efron ties.

        n, d = X.shape

        if not np.any(E):
            # sometimes strata have no deaths. This means nothing is returned
            # in the below code.
            return np.zeros((n, d))

        # Init risk and tie sums to zero
        risk_phi, tie_phi = 0, 0
        risk_phi_x, tie_phi_x = np.zeros((1, d)), np.zeros((1, d))

        # Init number of ties and weights
        weight_count = 0.0
        tie_count = 0

        scores = weights * np.exp(np.dot(X, self.hazards_))

        diff_against = []

        schoenfeld_residuals = np.empty((0, d))

        # Iterate backwards to utilize recursive relationship
        for i in range(n - 1, -1, -1):
            # Doing it like this to preserve shape
            ti = T[i]
            ei = E[i]
            xi = X[i : i + 1]
            score = scores[i : i + 1]
            w = weights[i]

            # Calculate phi values
            phi_i = score
            phi_x_i = phi_i * xi

            # Calculate sums of Risk set
            risk_phi = risk_phi + phi_i
            risk_phi_x = risk_phi_x + phi_x_i

            # Calculate sums of Ties, if this is an event
            diff_against.append((xi, ei))
            if ei:

                tie_phi = tie_phi + phi_i
                tie_phi_x = tie_phi_x + phi_x_i

                # Keep track of count
                tie_count += 1  # aka death counts
                weight_count += w

            if i > 0 and T[i - 1] == ti:
                # There are more ties/members of the risk set
                continue
            elif tie_count == 0:
                for _ in diff_against:
                    schoenfeld_residuals = np.append(schoenfeld_residuals, np.zeros((1, d)), axis=0)
                diff_against = []
                continue

            # There was atleast one event and no more ties remain. Time to sum.
            weighted_mean = np.zeros((1, d))

            for l in range(tie_count):

                numer = risk_phi_x - l * tie_phi_x / tie_count
                denom = risk_phi - l * tie_phi / tie_count

                weighted_mean += numer / (denom * tie_count)

            for xi, ei in diff_against:
                schoenfeld_residuals = np.append(schoenfeld_residuals, ei * (xi - weighted_mean), axis=0)

            # reset tie values
            tie_count = 0
            weight_count = 0.0
            tie_phi = 0
            tie_phi_x = np.zeros((1, d))
            diff_against = []

        return schoenfeld_residuals[::-1]