%Harrison Fell
%Resources for the Future
%2011

% This code is utilized in the paper
% Fell, Harrison and Alan Haynie.  2012. "Spatial Competition with
% Changing Market Institutions," Journal of Applied Econometrics, 
% forthcoming.

%Descrpition: Calculates the moments for the spatial fixed effects model 
%with SAR errors and homoskedastic errors in an unbalanced panel.
function v = sarar_GMM_minCon(parms,Omega,u,Q,M)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Inputs:
%parms - 2x1 vector with error SAR coef and innovation variance.
%Omega - symmetric weighting matrix
%u - residuals from 2sls spatial model
%Q - NTxNT within transformation matrix
%M - NTxNT matrix with spatial weight matrices on diagonals
%N - Total number of cross-sectional units
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
lam = parms(1);
sig2 = parms(2);
NT = length(u);
I = eye(NT);
G = 1/NT*[u'*Q*(I-lam*M')*(I-lam*M)*Q*u;
    u'*Q*(I-lam*M')*M'*M*(I-lam*M)*Q*u;
    u'*Q*(I-lam*M')*M'*(I-lam*M)*Q*u];      

     
trM2 = trace(M'*Q*M);
g = [sig2*trace(Q)/NT; sig2*trM2/NT;0];
v = ((G-g)'*Omega*(G-g));
