%\documentclass{jss}
\documentclass[nojss]{jss}
\usepackage[OT1]{fontenc}
\usepackage[latin1]{inputenc}
\usepackage{graphicx}
\usepackage{amsmath}

%\usepackage{cite}
%\usepackage{draftwatermark}
%\SetWatermarkText{Very draft}
%\SetWatermarkScale{1.0}

%\usepackage{myVignette}

%dimensione figure
\setkeys{Gin}{width=0.8\textwidth}

%\VignetteIndexEntry{Higher order markov chains}
%\VignetteKeywords{vig4}
%\VignettePackage{markovchain}
% need no \usepackage{Sweave.sty}

%\SweaveOpts{prefix.string=Figures/fig}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% declarations for jss.cls %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% almost as usual


\author{Deepak Yadav, Tae Seung Kang, Giorgio Alfredo Spedicato}

\title{Higher, possibly multivariate, Order Markov Chains in \pkg{markovchain} package}

%% for pretty printing and a nice hypersummary also set:
\Plainauthor{Deepak Yadav, Tae Seung Kang, Giorgio Alfredo Spedicato} %% comma-separated
\Plaintitle{Higher, possibly multivariate, order Markov chains in markovchain package} %% without formatting
\Shorttitle{Higher order (multivariate) Markov chains} %% a short title (if necessary)
%% an abstract and keywords
\Abstract{The \pkg{markovchain} package contains functions to fit higher (possibly) multivariate order Markov chains. The functions are shown as well as simple exmaples}
\Keywords{Higher order Markov chains}
\Plainkeywords{Higher order Markov chains} %% without formatting

\Address{
  Deepak Yadav\\
  B-Tech student\\
  Computer Science and Engineering\\
  Indian Institute of Technology, Varanasi\\
  Uttar Pradesh - 221 005, India\\
  E-mail: \email{deepakyadav.iitbhu@gmail.com}\\


  Giorgio Alfredo Spedicato\\
  Ph.D C.Stat ACAS\\
  UnipolSai R\&D\\
  Via Firenze 11, Paderno Dugnano
  20037 Italy\\
  E-mail: \email{spedygiorgio@gmail.com}\\
  URL: \url{www.statisticaladvisor.com}\\
}

%% for those who use Sweave please include the following line (with % symbols):
%% need no \usepackage{Sweave.sty}

%% end of declarations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{document}
%\SweaveOpts{concordance=TRUE}

<<setup,echo=FALSE, results=hide>>=
	options(prompt = "R> ", continue = "+  ", 
			width = 70, useFancyQuotes = FALSE)
	set.seed(123)
@

\maketitle

\section{Higher Order Markov Chains}

Continuous time Markov chains are discussed in the CTMC vignette which is a part of the package.\\

An experimental \code{fitHigherOrder} function has been written in order to fit a higher order Markov chain (\cite{ching2013higher, ching2008higher}). 
It takes a sequence and the order as arguments and returns the frequency probability vector X of the given sequence and the parameters $\lambda_i$ with the transition probability matrices $Q_i$ for each order $i$.
Its quadratic programming problem is solved using \code{solnp} function of \pkg{Rsolnp}, \cite{pkg:Rsolnp}. 

<<higherOrder, keep.source=TRUE>>=
require(markovchain)
library(Rsolnp)
data(rain)
fitHigherOrder(rain$rain, 2)
fitHigherOrder(rain$rain, 3)
@

\section{Higher Order Multivariate Markov Chains}

\subsection{Introduction}

HOMMC model is used for modeling behaviour of multiple categorical sequences generated by similar sources. The main reference is \cite{ching2008higher}. Assume that there are s categorical sequences and each has possible states in M. In nth order MMC the state probability distribution of the jth sequence at time $t = r + 1$ depend on the state probability distribution of all the sequences (including itself) at times $t = r, r - 1, ..., r - n + 1$.

\begin{equation}
x_{r+1}^{(j)} = \sum_{k=1}^{s}\sum_{h=1}^{n}\lambda_{jk}^{(h)}P_{h}^{(jk)}x_{r-h+1}^{(k)}, j = 1, 2, ..., s, r = n-1, n, ...
\end{equation} 

with initial distribution $x_{0}^{(k)}, x_{1}^{(k)}, ... , x_{n-1}^{(k)} (k = 1, 2, ... , s)$. Here

\begin{equation}
\lambda _{jk}^{(h)} \geq 0, 1\leq j, k\leq s, 1\leq h\leq  n \enspace and \enspace \sum_{k=1}^{s}\sum_{h=1}^{n} \lambda_{jk}^{(h)} = 1, j = 1, 2, 3, ... , s.
\end{equation} 

Now we will see the simpler representation of the model which will help us understand the result of \code{fitHighOrderMultivarMC} method.

\vspace{5mm}

Let $X_{r}^{(j)} = ((x_{r}^{(j)})^{T}, (x_{r-1}^{(j)})^{T}, ..., (x_{r-n+1}^{(j)})^{T})^{T} for \enspace j = 1, 2, 3, ... , s.$ Then

\vspace{5mm}

$\begin{pmatrix}
X_{r+1}^{(1)}\\ 
X_{r+1}^{(2)}\\ 
.\\ 
.\\ 
.\\ 
X_{r+1}^{(s)}
\end{pmatrix} = \begin{pmatrix}
 B^{11}&  B^{12}&  .&  .&  B^{1s}& \\ 
 B^{21}&  B^{22}&  .&  .&  B^{2s}& \\ 
 .&  .&  .&  .&  .& \\ 
 .&  .&  .&  .&  .& \\ 
 .&  .&  .&  .&  .& \\ 
 B^{s1}&  B^{s2}&  .&  .&  B^{ss}& \\ 
\end{pmatrix} \begin{pmatrix}
X_{r}^{(1)}\\ 
X_{r}^{(2)}\\ 
.\\ 
.\\ 
.\\ 
X_{r}^{(s)}
\end{pmatrix} where $

$B^{ii} = \begin{pmatrix}
 \lambda _{ii}^{(1)}P_{1}^{(ii)}&  \lambda _{ii}^{(2)}P_{2}^{(ii)}&  .&  .&  \lambda _{ii}^{(n)}P_{n}^{(ii)}& \\ 
 I&  0&  .&  .&  0& \\ 
 0&  I&  .&  .&  0& \\ 
 .&  .&  .&  .&  .& \\ 
 .&  .&  .&  .&  .& \\ 
 0&  .&  .&  I&  0& 
\end{pmatrix}_{mn*mn} and $

\vspace{5mm}

$B^{ij} = \begin{pmatrix}
 \lambda _{ij}^{(1)}P_{1}^{(ij)}&  \lambda _{ij}^{(2)}P_{2}^{(ij)}&  .&  .&  \lambda _{ij}^{(n)}P_{n}^{(ij)}& \\ 
 0&  0&  .&  .&  0& \\ 
 0&  0&  .&  .&  0& \\ 
 .&  .&  .&  .&  .& \\ 
 .&  .&  .&  .&  .& \\ 
 0&  .&  .&  0&  0& 
\end{pmatrix}_{mn*mn} when\enspace i\neq j. $ 

\vspace{5mm}

\subsection{Representation of parameters in the code} 

$P_{h}^{(ij)}$ is represented as $Ph(i,j)$ and $\lambda _{ij}^{(h)}$ as Lambdah(i,j). 
For example: $P_{2}^{(13)}$ as $P2(1,3)$ and $\lambda _{45}^{(3)}$ as Lambda3(4,5).

\subsection{Definition of HOMMC class}

<<label=hommcObject, echo=FALSE>>=
showClass("hommc")
@

Any element of \code{hommc} class is comprised by following slots:
\begin{enumerate}
  \item {states}: a character vector, listing the states for which transition probabilities are defined.
  \item {byrow}: a logical element, indicating whether transition probabilities are shown by row or by column.
  \item {order}: order of Multivariate Markov chain.
  \item {P}: an array of all transition matrices.
  \item {Lambda}: a vector to store the weightage of each transition matrix.
  \item {name}: optional character element to name the HOMMC
\end{enumerate}

\subsection{How to create an object of class HOMMC}

<<label=hommcCreate, echo=TRUE>>=
states <- c('a', 'b')
P <- array(dim = c(2, 2, 4), dimnames = list(states, states))
P[ , , 1] <- matrix(c(1/3, 2/3, 1, 0), byrow = FALSE, nrow = 2, ncol = 2)

P[ , , 2] <- matrix(c(0, 1, 1, 0), byrow = FALSE, nrow = 2, ncol = 2)

P[ , , 3] <- matrix(c(2/3, 1/3, 0, 1), byrow = FALSE, nrow = 2, ncol = 2)

P[ , , 4] <- matrix(c(1/2, 1/2, 1/2, 1/2), byrow = FALSE, nrow = 2, ncol = 2)

Lambda <- c(.8, .2, .3, .7)

hob <- new("hommc", order = 1, Lambda = Lambda, P = P, states = states, 
           byrow = FALSE, name = "FOMMC")
hob
@

\subsection{Fit HOMMC}

\code{fitHighOrderMultivarMC} method is available to fit HOMMC. Below are the 3 parameters of this method.

\begin{enumerate}
  \item {seqMat}: a character matrix or a data frame, each column represents a categorical sequence.
  \item {order}: order of Multivariate Markov chain. Default is 2.
  \item {Norm}: Norm to be used. Default is 2.
\end{enumerate}



\section{A Marketing Example} 

We tried to replicate the example found in \cite{ching2008higher} for an application of HOMMC. A soft-drink company in Hong Kong is facing an in-house problem of production planning and inventory control. A pressing issue is the storage space of its central warehouse, which often finds itself in the state of overflow or near capacity. The company is thus in urgent needs to study the interplay between the storage space requirement and the overall growing sales demand. The product can be classified into six possible states (1, 2, 3, 4, 5, 6) according to their sales volumes. All products are labeled as 1 = no sales volume, 2 = very slow-moving (very low sales volume), 3 = slow-moving, 4 = standard, 5 = fast-moving or 6 = very fast-moving (very high sales volume). Such labels are useful from both marketing and production planning points of view. The data is cointaind in \code{sales} object.

<<hommsales, keep.source=TRUE>>=
data(sales)
head(sales)
@


The company would also like to predict sales demand for an important customer in order to
minimize its inventory build-up. More importantly, the company can understand the sales pattern
of this customer and then develop a marketing strategy to deal with this customer. Customer's sales demand sequences of five important products of the company for a year. We expect sales demand sequences generated by the same customer to be correlated to each other. Therefore by exploring these relationships, one can obtain a better higher-order multivariate Markov model for such demand sequences, hence obtain better prediction rules.

In \cite{ching2008higher} application, they choose the order arbitrarily to be eight, i.e., n = 8. We first estimate all
the transition probability matrices $P_{h}^{(ij)}$ and we also have the estimates of the stationary probability distributions of the five products:.

$\widehat{\boldsymbol{x}}^{(1)} = \begin{pmatrix}
0.0818&  0.4052&  0.0483&  0.0335& 0.0037& 0.4275 
\end{pmatrix}^{\boldsymbol{T}}$

$\widehat{\boldsymbol{x}}^{(2)} = \begin{pmatrix}
0.3680&  0.1970&  0.0335&  0.0000& 0.0037& 0.3978 
\end{pmatrix}^{\boldsymbol{T}}$

$\widehat{\boldsymbol{x}}^{(3)} = \begin{pmatrix}
0.1450&  0.2045&  0.0186&  0.0000& 0.0037& 0.6283 
\end{pmatrix}^{\boldsymbol{T}}$

$\widehat{\boldsymbol{x}}^{(4)} = \begin{pmatrix}
0.0000&  0.3569&  0.1338&  0.1896& 0.0632& 0.2565
\end{pmatrix}^{\boldsymbol{T}}$

$\widehat{\boldsymbol{x}}^{(5)} = \begin{pmatrix}
0.0000&  0.3569&  0.1227&  0.2268& 0.0520& 0.2416
\end{pmatrix}^{\boldsymbol{T}}$

By solving the corresponding linear programming problems, we obtain the following higher-order
multivariate Markov chain model:

\vspace{3mm}

$\boldsymbol{x}_{r+1}^{(1)} = \boldsymbol{P}_{1}^{(12)}\boldsymbol{x}_{r}^{(2)}$

$\boldsymbol{x}_{r+1}^{(2)} = 0.6364\boldsymbol{P}_{1}^{(22)}\boldsymbol{x}_{r}^{(2)} + 
0.3636\boldsymbol{P}_{3}^{(22)}\boldsymbol{x}_{r}^{(2)}$

$\boldsymbol{x}_{r+1}^{(3)} = \boldsymbol{P}_{1}^{(35)}\boldsymbol{x}_{r}^{(5)}$

$\boldsymbol{x}_{r+1}^{(4)} = 0.2994\boldsymbol{P}_{8}^{(42)}\boldsymbol{x}_{r}^{(2)} + 
0.4324\boldsymbol{P}_{1}^{(45)}\boldsymbol{x}_{r}^{(5)} + 0.2681\boldsymbol{P}_{2}^{(45)}\boldsymbol{x}_{r}^{(5)}$

$\boldsymbol{x}_{r+1}^{(5)} = 0.2718\boldsymbol{P}_{8}^{(52)}\boldsymbol{x}_{r}^{(2)} + 
0.6738\boldsymbol{P}_{1}^{(54)}\boldsymbol{x}_{r}^{(4)} + 0.0544\boldsymbol{P}_{2}^{(55)}\boldsymbol{x}_{r}^{(5)}$

\vspace{3mm}

According to the constructed 8th order multivariate Markov model, Products A and B are
closely related. In particular, the sales demand of Product A depends strongly on Product B.
The main reason is that the chemical nature of Products A and B is the same, but they have
different packaging for marketing purposes. Moreover, Products B, C, D and E are closely related.
Similarly, products C and E have the same product flavor, but different packaging. In this model,
it is interesting to note that both Product D and E quite depend on Product B at order of 8, this
relationship is hardly to be obtained in conventional Markov model owing to huge amount of
parameters. The results show that higher-order multivariate Markov model is quite significant to
analyze the relationship of sales demand.


<<label=hommcFit>>=
# fit 8th order multivariate markov chain
object <- fitHighOrderMultivarMC(sales, order = 8, Norm = 2)
@

We choose to show only results shown in the paper. We see that $\lambda$ values are quite close, but not equal, to those shown in the original paper.

<<label=result, echo=FALSE>>=
i <- c(1, 2, 2, 3, 4, 4, 4, 5, 5, 5)
j <- c(2, 2, 2, 5, 2, 5, 5, 2, 4, 5)
k <- c(1, 1, 3, 1, 8, 1, 2, 8, 1, 2)

if(object@byrow == TRUE) {
    direction <- "(by rows)" 
} else {
    direction <- "(by cols)" 
}

cat("Order of multivariate markov chain =", object@order, "\n")
cat("states =", object@states, "\n")

cat("\n")
cat("List of Lambda's and the corresponding transition matrix", direction,":\n")

for(p in 1:10) {
  t <- 8*5*(i[p]-1) + (j[p]-1)*8
  cat("Lambda", k[p], "(", i[p], ",", j[p], ") : ", object@Lambda[t+k[p]],"\n", sep = "")
  cat("P", k[p], "(", i[p], ",", j[p], ") : \n", sep = "")
  print(object@P[, , t+k[p]])
  cat("\n")
}  
  
@


\bibliography{markovchainBiblio}





\end{document}