@staticmethod
    def _conditional_sum_squares(endog, k_ar, polynomial_ar, k_ma,
                                 polynomial_ma, k_trend=0, trend_data=None):
        k = 2 * k_ma
        r = max(k + k_ma, k_ar)

        k_params_ar = 0 if k_ar == 0 else len(polynomial_ar.nonzero()[0]) - 1
        k_params_ma = 0 if k_ma == 0 else len(polynomial_ma.nonzero()[0]) - 1

        residuals = None
        if k_ar + k_ma + k_trend > 0:
            # If we have MA terms, get residuals from an AR(k) model to use
            # as data for conditional sum of squares estimates of the MA
            # parameters
            if k_ma > 0:
                Y = endog[k:]
                X = lagmat(endog, k, trim='both')
                params_ar = np.linalg.pinv(X).dot(Y)
                residuals = Y - np.dot(X, params_ar)

            # Run an ARMA(p,q) model using the just computed residuals as data
            Y = endog[r:]

            X = np.empty((Y.shape[0], 0))
            if k_trend > 0:
                if trend_data is None:
                    raise ValueError('Trend data must be provided if'
                                     ' `k_trend` > 0.')
                X = np.c_[X, trend_data[:(-r if r > 0 else None), :]]
            if k_ar > 0:
                cols = polynomial_ar.nonzero()[0][1:] - 1
                X = np.c_[X, lagmat(endog, k_ar)[r:, cols]]
            if k_ma > 0:
                cols = polynomial_ma.nonzero()[0][1:] - 1
                X = np.c_[X, lagmat(residuals, k_ma)[r-k:, cols]]

            # Get the array of [ar_params, ma_params]
            params = np.linalg.pinv(X).dot(Y)
            residuals = Y - np.dot(X, params)

        # Default output
        params_trend = []
        params_ar = []
        params_ma = []
        params_variance = []

        # Get the params
        offset = 0
        if k_trend > 0:
            params_trend = params[offset:k_trend + offset]
            offset += k_trend
        if k_ar > 0:
            params_ar = params[offset:k_params_ar + offset]
            offset += k_params_ar
        if k_ma > 0:
            params_ma = params[offset:k_params_ma + offset]
            offset += k_params_ma
        if residuals is not None:
            params_variance = (residuals[k_params_ma:]**2).mean()

        return (params_trend, params_ar, params_ma,
                params_variance)
dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/tsa/statespace/sarimax.py/SARIMAX._conditional_sum_squares/original