clear all;clc;  %全程序循环
time = cputime;

%% parameters
n=800;
m=100;
windows = 6+1;  % instance + target
K = 50;
w = 1;

%% preliminary
input = importdata( 'train_20171215.txt' );
dd = input.data;
date = unique(dd(:,1));
data = zeros(length(date),3);
for i=1:length(date)
    temp = find( dd(:,1)==i );
    data(i,1) = i;
    data(i,3) = sum( dd(temp,4) );
    data(i,2) = mean( dd(temp,2) );
end

%% step1: verification and train datasets
for i=1:n
    train(i,1:windows-1) = data(2+i:i+windows,3) ;
    train(i,windows) = data(i+windows+1,3);
end
for i=1:m
    verification(i,1:windows-1) = data(2+n+i:n+i+windows,3);
    verification(i,windows) = data(i+windows+n+1,3);
end
[n,p] = size(train);
X = train(:,1:end-1);
label = train(:,end);
[m,p] = size(verification);
Xv = verification(:,1:end-1);
real = verification(:,end);

%% step2: k-means++ clustering / Recurrent Phase
[ C,index ] = ClusterOP( X,K,w );
[K,p] = size(C);
%% step3: metric matrix
for i=1:n
    D(i,:) = SimpleSide_vOP(X(i,:),C,w);
end
for i=1:m
    Dv(i,:) = SimpleSide_vOP(Xv(i,:),C,w);
end
temp = max(max(D));
D = D/temp;
Dv = Dv/temp;
save predata D Dv label real C;

%% step4: Harmonic Phase
d = 1;
x_input_domain = [0,1;0,1e+06];
Ehaha = @(gamma)OA(gamma,1); 
%[gamma, fx, X_sample, F_sample, Result] = IMGPO_default_run ( Ehaha, d, x_input_domain,200,1,1,1,1);
[gamma, fx] = IMGPO_default_run ( Ehaha, d, x_input_domain,100,1,1,1,1);

%% step5: Prediction
load predata.mat;
[ alpha,result(1,:),estimate ] = OptimizationAlpha( D,label,gamma );  %返还测评
[ result(2,:),prediction ] = forecasting( Dv, gamma, alpha, real );   %预测

time = cputime - time

figure;
plot(estimate,'blue');hold on; plot(label,'red');close all;
figure;
plot(prediction,'blue');hold on; plot(real,'red');
%save K50w1 train verification result gamma K C windows;

