*! version 1  03 January 2012
************************************************************************************************************
* gausshermite2 : Estimate an integral of the form : f(x,y)g(x,y/mu,Sigma)dxdy where g(x,y/mu,Sigma) is the distribution function
* of the bivariate normal distribution of mean mu and covariance matrix  Sigma by Gauss Hermite quadratures
*
* Version 1: 03 January 2012
*
*
* Mohand Feddag, University of Nantes - France
* Mohand-Larbi.Feddag@univ-nantes.fr *
* News about this program : http://anaqol.free.fr
* FreeIRT Project : http://freeirt.free.fr
*
* Copyright 2012 Mohand Feddag
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*
************************************************************************************************************

program define gausshermite2,rclass
version 11
syntax anything [, Mu(string) Sigma(string)  Nodes(integer 12) Display]
tempfile gauss2
qui capture save `gauss2',replace
local save=0
if _rc==0 {
   qui save `gauss2',replace
   local save=1
}
if "`mu'"=="" {
   tempname mu
   matrix `mu'=[0,0]
}
if "`sigma'"=="" {
   tempname sigma
   matrix `sigma'=[1,0\0,1]
}
tokenize `anything'

drop _all
qui set obs `=`nodes'*`nodes''
tempname noeuds poids
qui ghquadm `nodes' `noeuds' `poids'

* Cholesky transformation for the covariance matrix sigma

matrix  C=cholesky(`sigma')
*matrix list C
local line=1
qui gen x1=.
qui gen x2=.
qui gen poids1=.
qui gen poids2=.
forvalues i=1/`nodes' {
   forvalues j=1/`nodes' {
      qui replace x1=`noeuds'[1,`i'] *(sqrt(2)*C[1,1])+`mu'[1,1] in `line'
       qui replace x2=`noeuds'[1,`i'] *(sqrt(2)*C[2,1])+`noeuds'[1,`j'] *(sqrt(2)*C[2,2])+`mu'[1,2] in `line'
      qui replace poids1=`poids'[1,`i'] in `line'
      qui replace poids2=`poids'[1,`j'] in `line'
      local ++line
   }
}

* Double somme du produit poids[i]*poids[j]*f(x1,x2) qui est affecté a la variable sum

qui gen f=poids1*poids2*(`1')/(_pi)
*list x1 x2  poids1 f (sqrt(2)*_pi)
qui su f
local sum=r(sum)
 return scalar int=`sum'

 if "`display'"!="" {
   di in green "int_R^2 (`1')g(x1,x2/mu=`mu',Sigma=`Sigma')dx1dx2=" in yellow %12.8f `sum'
}
drop _all
if `save'==1 {
   qui use `gauss2',clear
}
end