demo_HSMM01.m 11.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
function demo_HSMM01
% Variable duration model implemented as a hidden semi-Markov model 
% (simplified version by encoding the state duration after EM).
%
% Writing code takes time. Polishing it and making it available to others takes longer! 
% If some parts of the code were useful for your research of for a better understanding 
% of the algorithms, please reward the authors by citing the related publications, 
% and consider making your own research available in this way.
%
% @article{Rozo16Frontiers,
%   author="Rozo, L. and Silv\'erio, J. and Calinon, S. and Caldwell, D. G.",
%   title="Learning Controllers for Reactive and Proactive Behaviors in Human-Robot Collaboration",
%   journal="Frontiers in Robotics and {AI}",
%   year="2016",
%   month="June",
%   volume="3",
%   number="30",
%   pages="1--11",
%   doi="10.3389/frobt.2016.00030"
% }
% 
% Copyright (c) 2015 Idiap Research Institute, http://idiap.ch/
% Written by Sylvain Calinon, http://calinon.ch/
% 
% This file is part of PbDlib, http://www.idiap.ch/software/pbdlib/
% 
% PbDlib is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License version 3 as
% published by the Free Software Foundation.
% 
% PbDlib is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with PbDlib. If not, see <http://www.gnu.org/licenses/>.

addpath('./m_fcts/');


%% Parameters
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
model.nbStates = 2; %Number of hidden states in the HSMM
nbData = 100; %Length of each trajectory
nbSamples = 10; %Number of demonstrations
minSigmaPd = 1E1; %Minimum variance of state duration (regularization term)


%% Load handwriting data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
demos=[];
load('data/2Dletters/V.mat');
Data=[];
for n=1:nbSamples
	s(n).Data = spline(1:size(demos{n}.pos,2), demos{n}.pos, linspace(1,size(demos{n}.pos,2),nbData)); %Resampling
	s(n).nbData = size(s(n).Data,2);
	Data = [Data s(n).Data]; 
end


%% Learning
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%model = init_GMM_kmeans(Data, model);
model = init_GMM_kbins(Data, model, nbSamples);

% %Random initialization
% model.Trans = rand(model.nbStates,model.nbStates);
% model.Trans = model.Trans ./ repmat(sum(model.Trans,2),1,model.nbStates);
% model.StatesPriors = rand(model.nbStates,1);
% model.StatesPriors = model.StatesPriors/sum(model.StatesPriors);

%Left-right model initialization
model.Trans = zeros(model.nbStates);
for i=1:model.nbStates-1
	model.Trans(i,i) = 1-(model.nbStates/nbData);
	model.Trans(i,i+1) = model.nbStates/nbData;
end
model.Trans(model.nbStates,model.nbStates) = 1.0;
model.StatesPriors = zeros(model.nbStates,1);
model.StatesPriors(1) = 1;
model.Priors = ones(model.nbStates,1);

[model, H] = EM_HMM(s, model);
%Removal of self-transition (for HSMM representation) and normalization
model.Trans = model.Trans - diag(diag(model.Trans)) + eye(model.nbStates)*realmin;
model.Trans = model.Trans ./ repmat(sum(model.Trans,2),1,model.nbStates);


%% Post-estimation of the state duration from data (for HSMM representation)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i=1:model.nbStates
	st(i).d=[];
end
[~,hmax] = max(H);
currState = hmax(1);
cnt = 1;
for t=1:length(hmax)
	if (hmax(t)==currState)
		cnt = cnt+1;
	else
		st(currState).d = [st(currState).d cnt];
		cnt = 1;
		currState = hmax(t);
	end
end
st(currState).d = [st(currState).d cnt];

%Compute state duration as Gaussian distribution
for i=1:model.nbStates
	model.Mu_Pd(1,i) = mean(st(i).d);
	model.Sigma_Pd(1,1,i) = cov(st(i).d) + minSigmaPd;
end


%% Reconstruction of states probability sequence
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
nbD = round(2 * nbData/model.nbStates); %Number of maximum duration step to consider in the HSMM (2 is a safety factor)

%Precomputation of duration probabilities 
for i=1:model.nbStates
	model.Pd(i,:) = gaussPDF([1:nbD], model.Mu_Pd(:,i), model.Sigma_Pd(:,:,i)); 
	%The rescaling formula below can be used to guarantee that the cumulated sum is one (to avoid the numerical issues)
	model.Pd(i,:) = model.Pd(i,:) / sum(model.Pd(i,:));
end


%Slow reconstruction of states sequence based on standard computation
%(in the iteration, a scaling factor c is used to avoid numerical underflow issues in HSMM, see Levinson'1986) 
h = zeros(model.nbStates,nbData);
c = zeros(nbData,1); %scaling factor to avoid numerical issues
c(1)=1; %Initialization of scaling factor
for t=1:nbData
	for i=1:model.nbStates
		if t<=nbD
% 			oTmp = 1; %Observation probability for generative purpose
			oTmp = prod(c(1:t) .* gaussPDF(s(1).Data(:,1:t), model.Mu(:,i), model.Sigma(:,:,i))); %Observation probability for standard HSMM
			h(i,t) = model.StatesPriors(i) * model.Pd(i,t) * oTmp;
		end
		for d=1:min(t-1,nbD)
% 			oTmp = 1; %Observation probability for generative purpose
			oTmp = prod(c(t-d+1:t) .* gaussPDF(s(1).Data(:,t-d+1:t), model.Mu(:,i), model.Sigma(:,:,i))); %Observation probability for standard HSMM	
			h(i,t) = h(i,t) + h(:,t-d)' * model.Trans(:,i) * model.Pd(i,d) * oTmp;
		end
	end
	c(t+1) = 1/sum(h(:,t)); %Update of scaling factor
end
h = h ./ repmat(sum(h,1),model.nbStates,1);


% %Fast reconstruction of sequence for HSMM (version based on position and duration information)
% h = zeros(model.nbStates,nbData);
% [bmx, ALPHA, S, h(:,1)] = hsmm_fwd_init_hsum(s(1).Data(:,1), model);
% for t=2:nbData
% 	[bmx, ALPHA, S, h(:,t)] = hsmm_fwd_step_hsum(s(1).Data(:,t), model, bmx, ALPHA, S);
% end


% %Fast reconstruction of sequence for HSMM (version based on only duration information)
% h = zeros(model.nbStates,nbData);
% [ALPHA, S, h(:,1)] = hsmm_fwd_init_ts(model);
% for t=2:nbData
% 	[ALPHA, S, h(:,t)] = hsmm_fwd_step_ts(model, ALPHA, S);
% end
% h = h ./ repmat(sum(h,1),model.nbStates,1);


% %Manual reconstruction of sequence for HSMM based on stochastic sampling 
% nbSt=0; currTime=0; iList=[];
% h = zeros(model.nbStates,nbData);
% while currTime<nbData
% 	nbSt = nbSt+1;
% 	if nbSt==1
% 		[~,iList(1)] = max(model.StatesPriors.*rand(model.nbStates,1));
% 		h1 = ones(1,nbData);
% 	else
% 		h1 = [zeros(1,currTime), cumsum(model.Pd(iList(end-1),:)), ones(1,max(nbData-currTime-nbD,0))];
% 		currTime = currTime + round(model.Mu_Pd(1,iList(end-1)));
% 	end
% 	h2 = [ones(1,currTime), 1-cumsum(model.Pd(iList(end),:)), zeros(1,max(nbData-currTime-nbD,0))];
% 	h(iList(end),:) = h(iList(end),:) + min([h1(1:nbData); h2(1:nbData)]);
% 	[~,iList(end+1)] = max(model.Trans(iList(end),:).*rand(1,model.nbStates));
% end
% h = h ./ repmat(sum(h,1),model.nbStates,1);


% %% Plots
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% figure('PaperPosition',[0 0 18 4.5],'position',[10,10,1300,450],'color',[1 1 1]); 
% %xx = round(linspace(1,64,model.nbStates));
% %clrmap = colormap('jet')*0.5;
% %clrmap = min(clrmap(xx,:),.9);
% clrmap = lines(model.nbStates);
% 
% %Spatial plot of the data
% subplot(2,4,[1,5]); hold on;
% for i=1:model.nbStates
% 	plotGMM(model.Mu(:,i), model.Sigma(:,:,i), clrmap(i,:), .6);
% end
% plot(Data(1,:), Data(2,:), '.', 'color', [.6 .6 .6]);
% %xlabel('$x_1$','fontsize',14,'interpreter','latex'); ylabel('$x_2$','fontsize',14,'interpreter','latex');
% %axis equal; axis square;
% axis tight; axis off;
% 
% %Timeline plot of the duration probabilities
% subplot(2,4,[2:4]); hold on;
% for i=1:model.nbStates
% 	yTmp = model.Pd(i,:) / max(model.Pd(i,:));
% 	patch([1, 1:nbD, nbD], [0, yTmp, 0], clrmap(i,:), 'EdgeColor', 'none', 'facealpha', .6);
% 	plot(1:nbD, yTmp, 'linewidth', 2, 'color', clrmap(i,:));
% end
% set(gca,'xtick',[10:10:nbD],'fontsize',8); axis([1 nbData 0 1]);
% ylabel('$Pd/Pd_{max}$','fontsize',16,'interpreter','latex');
% 
% %Timeline plot of the state sequence probabilities
% subplot(2,4,[6:8]); hold on;
% for i=1:model.nbStates
% 	patch([1, 1:nbData, nbData], [0, h(i,:), 0], clrmap(i,:), 'EdgeColor', 'none', 'facealpha', .6);
% 	plot(1:nbData, h(i,:), 'linewidth', 2, 'color', clrmap(i,:));
% end
% set(gca,'xtick',[10:10:nbData],'fontsize',8); axis([1 nbData 0 1]);
% xlabel('$t$','fontsize',16,'interpreter','latex'); 
% ylabel('$h$','fontsize',16,'interpreter','latex');
% 
% %% Plot transition graph
% figure('color',[1 1 1]); hold on; axis off;
% plotHSMM(model.Trans, model.StatesPriors, model.Pd);

% %% Additional plot 
% figure('PaperPosition',[0 0 36 12],'position',[10,10,1300,400],'color',[1 1 1]); 
% clrmap = lines(model.nbStates);
% %Spatial plot of the data
% subplot(1,4,1); axis off; hold on; 
% for i=1:model.nbStates
% 	plotGMM(model.Mu(:,i), model.Sigma(:,:,i), clrmap(i,:), 1);
% end
% plot(Data(1,:), Data(2,:), '.', 'color', [.3 .3 .3]);
% axis tight; axis equal;
% %GMM
% subplot(1,4,2); axis off; hold on; title('GMM','fontsize',20);
% %Plot nodes
% graphRadius = 1;
% nodeRadius = .2;
% nodePts = 40;
% nodeAngle = linspace(pi,2*pi+pi,model.nbStates+1);
% %nodeAngle = linspace(pi/2,2*pi+pi/2,model.nbStates+1);
% for i=1:model.nbStates
% 	nodePos(:,i) = [cos(nodeAngle(i)); sin(nodeAngle(i))] * graphRadius;
% end
% for i=1:model.nbStates
% 	a = linspace(0,2*pi,nodePts);
% 	meshTmp = [cos(a); sin(a)] * nodeRadius + repmat(nodePos(:,i),1,nodePts);
% 	patch(meshTmp(1,:), meshTmp(2,:), clrmap(i,:),'edgecolor',clrmap(i,:)*0.5, 'facealpha', 1,'edgealpha', 1);
% 	text(nodePos(1,i),nodePos(2,i),num2str(i),'HorizontalAlignment','center','FontWeight','bold','fontsize',20);
% end
% axis equal; axis([-1 1 -1 1]*1.9); 
% %HMM
% subplot(1,4,3); axis off; hold on; title('HMM','fontsize',20);
% plotHMM(model.Trans, model.StatesPriors);
% axis([-1 1 -1 1]*1.9); 
% %HSMM
% subplot(1,4,4); axis off; hold on; title('HSMM','fontsize',20); 
% plotHSMM(model.Trans, model.StatesPriors, model.Pd);
% axis([-1 1 -1 1]*1.9);


%% Plots
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure('position',[10,10,1300,600],'color',[1 1 1]); 
clrmap = lines(model.nbStates);
%Spatial plot of the data
subplot(3,2,[1,3]); axis off; hold on; 
plot(Data(1,:), Data(2,:), '.', 'color', [.3 .3 .3]);
for i=1:model.nbStates
	plotGMM(model.Mu(:,i), model.Sigma(:,:,i), clrmap(i,:), .6);
end
axis tight; axis equal;
%HSMM transition and state duration plot
subplot(3,2,[2,4]); axis off; hold on; 
plotHSMM(model.Trans, model.StatesPriors, model.Pd);
axis([-1 1 -1 1]*1.9);
%Timeline plot of the state sequence probabilities
subplot(3,2,[5,6]); hold on;
for i=1:model.nbStates
	patch([1, 1:nbData, nbData], [0, h(i,:), 0], clrmap(i,:), ...
		'linewidth', 2, 'EdgeColor', max(clrmap(i,:)-0.2,0), 'facealpha', .6, 'edgealpha', .6);
end
set(gca,'xtick',[10:10:nbData],'fontsize',8); axis([1 nbData 0 1.1]);
xlabel('t','fontsize',16); 
ylabel('h_i','fontsize',16);


%print('-dpng','graphs/demo_HSMM01.png'); 
pause;
close all;

% % Saving .txt files
% model.varnames{1} = 'x1';
% model.varnames{2} = 'x2';
% HSMMtoText(model, 'test2');