reduceTpm <-
function(transitionMatrix,G){
  
  gamma=transitionMatrix
  
  #number of sets in partition
  r = length(G)
  
  #number of states
  m=length(unlist(G))
  
  #set nu-matrix
  nu = mergeTpm(gamma,G)
  
  #set inner group probabilities
  pList = list()
  p0 = stat_distr(gamma)
  for(l in 1:r){
    pList[[l]] = numeric(length(G[[l]]))
    sumGroup_l = sum(p0[G[[l]]])
    pList[[l]] = p0[G[[l]]]/sumGroup_l
  }
  
  
  getGroupOfIndex = function(i,G){
    r=length(G)
    for(l in 1:r){
      if(any(G[[l]]==i)) return(l)  
    }
  }
  
  getPositionInGroup = function(i,G){  
    group = getGroupOfIndex(i,G)
    return(which(G[[group]]==i))  
  }
  
  #set gamma matrix back 
  gamma = NA * matrix(0,ncol=m,nrow=m)
  
  for(i in 1:m){
    for(j in 1:m){
      gamma[i,j] = nu[getGroupOfIndex(i,G),getGroupOfIndex(j,G)] * pList[[getGroupOfIndex(j,G)]][getPositionInGroup(j,G)]  
    }
  }
  
  return(gamma)
  
}
