/**
 * GQ(lambda): off-policy learning algorithm
 * @author Adam White
 */

#include <stdlib.h>

#include "GQlambda.h"

/* Private functions */
double dot(const double v1[], const double v2[], const int n);

void init_GQlambda(struct gqlambda * gq, int n) {
    gq->n = n;
    gq->theta = calloc(n,sizeof(double));
    gq->w = calloc(n,sizeof(double));
    gq->e = calloc(n,sizeof(double));
}

/**
 * Inputs::
 *   phi - feature vector corresponding to action A_t in state S_t
 *   phi_bar - expected next state feature vector corresponding to a \in A and S_t+1
 *   lambda - elegibility trace parameter [0,1]
 *   gamma - discount factor [0,1]
 *   R - transient reward
 *   rho - ratio of target policy to behaviour policy [0,1]
 *   I - set of interest for S_t, S_t [0,1]
 **/
void GQlearn(struct gqlambda * gq, const double phi[], const double phi_bar[], const double lambda, const double gamma, const double R, const double rho, const double I) {
    double alpha = 0.0001, eta = 1.0; //step size parameters
    double delta, dot_w_phi, dot_w_e;
    int i;

    delta = R + gamma*dot(gq->theta,phi_bar,gq->n) - dot(gq->theta,phi,gq->n);

    for (i=0; i<gq->n; i++)
      gq->e[i] = rho*gq->e[i] + I*phi[i];

    dot_w_e = dot(gq->w,gq->e,gq->n);
    dot_w_phi = dot(gq->w,phi,gq->n);

    for (i=0; i<gq->n; i++) {
      gq->theta[i] += alpha * (delta*gq->e[i] - gamma*(1-lambda)*dot_w_e*phi_bar[i]);
      gq->w[i] += alpha*eta * (delta*gq->e[i] - dot_w_phi*phi[i]);
      gq->e[i] *= gamma*lambda;
    }
}

void delete_GQlambda(struct gqlambda * gq) {
    if (gq == NULL)
        return;
    if (gq->theta != NULL) free(gq->theta);
    if (gq->w != NULL) free(gq->w);
    if (gq->e != NULL) free(gq->e);
}


/*********** Private functions ****************/
double dot(const double v1[], const double v2[], const int n) {
    double sum = 0;
    int i;

    for (i=0; i<n; i++)
      sum += v1[i]*v2[i];
    return sum;
}


