echo on
clc

% This is a demonstration of the "nlpca" function. Just follow along and
% hit the return key when when you are ready to go on.

% This demo needs two data sets: demo1.dat and demo2.dat
% Now hit any key to continue 

pause

% Load the data into memory.

load dem1.mat

% This is a two-dimensional data set.
% x1 = sin(t) + e1
% x2 = cos(t) + e2
% where t in [0, pie/2], and e1, e2 are Gaussian noise N(0,0.1)

% To scale the data use the auto scale function.
[m,n]=size(demo1);
x1=zeros(m,1);
x2=zeros(m,1);

[ddemo1,mdemo1,sdemo1s]=auto(demo1);

% Let's plot the data.

echo off

plot(ddemo1(:,1),ddemo1(:,2),'o')
xlabel('X1')
ylabel('X2')
pause
echo on

% Let's see the first linear principal component.
% Now hit any key to continue

echo off
[u,s,v]=svd(ddemo1,0);
score=u*s;


x1(:,1)=score(:,1)*v(1,1);
x1(:,2)=score(:,1)*v(2,1);
hold on
plot(x1(:,1),x1(:,2),'+');
pause
echo on

% Now let's use "nlpca" function to get the first nonlinear principal
% component. Here the span = 20
% Hit any key to continue


ncom=1;
span=20;
[NN1,NN2,T,DataR]= npca1(ddemo1,span,ncom);

plot(DataR(:,1),DataR(:,2),'--')
pause

% We can see that nonlinear principal component achieves better results
% in terms of explained variations.

% Now let's consider a higher dimensional example.
 
% x1 = t1 +t2 + e1
% x2 = t1^2 + t2^2 - t1*t2 + e2
% x3 = t1^3 + 5*t2^2 -2*t1*t2 + e3
% x4 = t1 + 2*log(10*t2) + e4
% x5 = sin(t1*2*pie) + t2 + e5
% x6 = cos(t2*2*pie) - 2*t1 + e6

% t1 and t2 are uniformly distributed random numbers in [0,1]
% e1 to e6 are independent Gaussian noise N(0,0.01)

% Now let's load the data set, and take a look at it.
echo off
load dem2.mat
[ddemo2,mdemo2,sdemo2]=auto(demo2);
hold off
plot(ddemo2);
pause
echo on

% Data look quite messy.
% Let's do an nlpca calculation
% Hit any key to continue
echo off
span =20;
ncom=6;
[NN1,NN2,T,DataR]= npca1(ddemo2,span,ncom);
echo on

% We can see that most variation has been explained by the first two 
% nonlinear principal components. This result is consistent with the
% fact that there are only two latent dimensions for the data.

% Let's take a look at the nonlinear scores.

plot(T)

% It is clear that most variations are captured by the first two 
% nonlinear principal components.

