/*-----------------------------------------------------------------------------

Copyright (C) 2005.

A. Ronald Gallant
Post Office Box 659
Chapel Hill NC 27514-0659
USA   

Permission to use, copy, modify, and distribute this software and its docu-
mentation for any purpose and without fee is hereby granted, provided that 
the above copyright notice appears in all copies and that both that copyright 
notice and this permission notice appear in supporting documentation.  This 
software is provided "as is" without any expressed or implied warranty.

-----------------------------------------------------------------------------*/

#include "libsmm.h"
#include "emm.h"

using namespace libsmm;
using namespace emm;
using namespace std;
using namespace scl;


den_val emm::generic_usrmod::likelihood(realmat& yhat, realmat& zhat) 
{
  if (!support(rho)) return den_val(false,-REAL_MAX);;

  INTEGER r = data.get_rows();
  INTEGER n = data.get_cols();

  if (r != 4) error("Error, generic_usrmod, likelihood, bad data");
  if (rho.get_rows() != 4) error("Error, generic_usrmod, likelihood, bad parm");

  realmat y = data("1","");
  realmat x = data("2:4","");

  REAL log_like = 0;
  for (INTEGER t=1; t<=n; ++t) {
    REAL z = rho[1] + rho[2]*x(1,t) + rho[3]*x(2,t) + rho[4]*x(3,t);
    REAL phat = exp(z)/(1.0 + exp(z));
    log_like += y[t]*log(phat) + (1.0 - y[t])*log(1.0 - phat);
  }

  return den_val(true,log_like);
}

bool emm::generic_usrmod::support(const realmat& parm) 
{
  return true; 
}

den_val emm::generic_usrmod::prior(const realmat& rho_in, const realmat& stats) 
{
  return den_val(true, 0.0);
}

emm::generic_usrmod::generic_usrmod
  (const realmat& dat, INTEGER len_mod_parm, INTEGER len_mod_func,
   const std::vector<std::string>& mod_pfvec,
   const std::vector<std::string>& mod_alvec, 
   std::ostream& detail)
: data(dat), rho(), lrho(len_mod_parm), lstats(1)
{ }

