def leastsq_NxN(x, y, fit_offset=False, perc=None):
if perc is not None:<EOL><INDENT>if not fit_offset and isinstance(perc, (list, tuple)): perc = perc[<NUM_LIT:1>]<EOL>weights = csr_matrix(get_weight(x, y, perc)).astype(bool)<EOL>x, y = weights.multiply(x).tocsr(), weights.multiply(y).tocsr()<EOL><DEDENT>else:<EOL><INDENT>weights = None<EOL><DEDENT>with warnings.catch_warnings():<EOL><INDENT>warnings.simplefilter("<STR_LIT:ignore>")<EOL>xx_ = prod_sum_obs(x, x)<EOL>xy_ = prod_sum_obs(x, y)<EOL>if fit_offset:<EOL><INDENT>n_obs = x.shape[<NUM_LIT:0>] if weights is None else sum_obs(weights)<EOL>x_ = sum_obs(x) / n_obs<EOL>y_ = sum_obs(y) / n_obs<EOL>gamma = (xy_ / n_obs - x_ * y_) / (xx_ / n_obs - x_ ** <NUM_LIT:2>)<EOL>offset = y_ - gamma * x_<EOL>idx = offset < <NUM_LIT:0><EOL>gamma[idx] = xy_[idx] / xx_[idx]<EOL>offset = np.clip(offset, <NUM_LIT:0>, None)<EOL><DEDENT>else:<EOL><INDENT>gamma = xy_ / xx_<EOL>offset = np.zeros(x.shape[<NUM_LIT:1>])<EOL><DEDENT><DEDENT>offset[np.isnan(offset)], gamma[np.isnan(gamma)] = <NUM_LIT:0>, <NUM_LIT:0><EOL>return offset, gamma<EOL>
Solution to least squares: gamma = cov(X,Y) / var(X)