Sunday, January 13, 2013

PGM3 - Observe Evidence

# ObserveEvidence Modify a vector of factors given some evidence.
ObserveEvidence <- function(F, E)  {
for ( i in 1: nrow(E)){
    v <- E[i, 1]; # variable
    x <- E[i, 2]; # value
 
    #Check validity of evidence
    if (x == 0){
     cat('Evidence not set for variable', v);
     continue;
    }
 
    for (j in 1:length(F)){
     # Does factor contain variable?
     indx = match(v, F[[j]]$var);
     if (!is.na(indx)){
      # Check validity of evidence
         if (x > F[[j]]$card[indx] || x < 0 ){
           cat('Invalid evidence X_' , v, ' = ', x);
         }
 
      map <- F[[j]]$var == v;    
      assignments <- IndexToAssignment(F[[j]]$card);
      indxx = (assignments[, map] == x);
      assignments$val <- F[[j]]$val;
      assignments$val[!indxx] <- 0;
      F[[j]]$val <- assignments$val;  
     }
    }
  }
return(F)
}

#case 1;
F.1 <- list(var=c(1), card=c(2), val=c(0.11, 0.89));
F.2 <- list(var=c(2, 1), card=c(2, 2), val=c(0.59, 0.41, 0.22, 0.78));
F.3 <- list(var=c(3, 2), card=c(2, 2), val=c(0, 0.61, 0, 0));
F <- list(F.1, F.2, F.3)
E <- matrix(c(2, 1, 3, 2), byrow = T, nrow = 2)
ObserveEvidence(F, E);

#case 2;
Z = list(var=c(3, 2, 1), card=c(2, 2, 3), val=c(0.25, 0.35, 0.08, 0.16, 0.05, 0.07, 0, 0, 0.15, 0.21, 0.09, 0.18));
Z <- list(Z);
E <- matrix(c(3, 1), byrow = T, nrow = 1)
ObserveEvidence(Z, E);

No comments:

Post a Comment