def leastsq_generalized(x, y, x2, y2, res_std=None, res2_std=None, fit_offset=False, fit_offset2=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>n_obs, n_var = x.shape<EOL>offset, offset_ss = np.zeros(n_var, dtype="<STR_LIT>"), np.zeros(n_var, dtype="<STR_LIT>")<EOL>gamma = np.ones(n_var, dtype="<STR_LIT>")<EOL>if (res_std is None) or (res2_std is None): res_std, res2_std = np.ones(n_var), np.ones(n_var)<EOL>ones, zeros = np.ones(n_obs), np.zeros(n_obs)<EOL>with warnings.catch_warnings():<EOL><INDENT>warnings.simplefilter("<STR_LIT:ignore>")<EOL>x, y = np.vstack((make_dense(x)/res_std, x2/res2_std)), np.vstack((make_dense(y)/res_std, y2/res2_std))<EOL><DEDENT>if fit_offset and fit_offset2:<EOL><INDENT>for i in range(n_var):<EOL><INDENT>A = np.c_[np.vstack((np.c_[ones/res_std[i], zeros], np.c_[zeros, ones/res2_std[i]])), x[:, i]]<EOL>offset[i], offset_ss[i], gamma[i] = np.linalg.pinv(A.T.dot(A)).dot(A.T.dot(y[:, i]))<EOL><DEDENT><DEDENT>elif fit_offset:<EOL><INDENT>for i in range(n_var):<EOL><INDENT>A = np.c_[np.hstack((ones/res_std[i], zeros)), x[:, i]]<EOL>offset[i], gamma[i] = np.linalg.pinv(A.T.dot(A)).dot(A.T.dot(y[:, i]))<EOL><DEDENT><DEDENT>elif fit_offset2:<EOL><INDENT>for i in range(n_var):<EOL><INDENT>A = np.c_[np.hstack((zeros, ones/res2_std[i])), x[:, i]]<EOL>offset_ss[i], gamma[i] = np.linalg.pinv(A.T.dot(A)).dot(A.T.dot(y[:, i]))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for i in range(n_var):<EOL><INDENT>A = np.c_[x[:, i]]<EOL>gamma[i] = np.linalg.pinv(A.T.dot(A)).dot(A.T.dot(y[:, i]))<EOL><DEDENT><DEDENT>offset[np.isnan(offset)] = <NUM_LIT:0><EOL>offset_ss[np.isnan(offset_ss)] = <NUM_LIT:0><EOL>gamma[np.isnan(gamma)] = <NUM_LIT:0><EOL>return offset, offset_ss, gamma<EOL>
Solution to the 2-dim generalized least squares: gamma = inv(X'QX)X'QY