%% Process description
% Transfer function to state-space
Kp = 0.703; Tp = 1.62;
ysP = 7.5; usP = 1.5;  % The standard point
G1 = tf([Kp], [Tp 1],'InputDelay', 10.0); G1d = c2d(G1,1,'zoh');
[Ap,Bp,Cp,Dp] = ssdata(G1d);  % Convert tf to state-space

% Input range
inp_range = 1:0.01:4;

%% Generate steady-state images
% Set-up
NoI_SS = 1; % Total number of images to be generated

% Image properties
img_size = 300;

% Initialization
track = 1;
figure('Units','pixels','Position',[10 10 img_size img_size]);

% Generate
while track <= NoI_SS
    N_int = randi([2,5]);
    int = 1:N_int;
    coin = zeros(1,length(int));
    coin(N_int) = 0; % Steady-state
    for i = 1:(N_int-1)
        coin(i) = randi([0,1]);
    end
    
    time_lim = 100;
    time_rangeS = 20:30; time_rangeT = 5:30;
    time = zeros(1,length(int));
    time_rangeS1 = time_rangeS; time_rangeS1 = time_rangeS1(randperm(length(time_rangeS)));
    time_res = time_lim - time_rangeS1(1);
    time_oth = rand(1,N_int-1); time_oth = time_res*time_oth/sum(time_oth);
    
    if N_int-2 > 0
        for j = 1:(N_int-1)
            time_oth(j) = round(time_oth(j));
        end
        
        for m = 2:(N_int-1)
            time_oth(m) = time_oth(m) + time_oth(m-1);
        end
        
        time_f = [coin(1)*ones(1,time_oth(1))];
        for n = 2:(N_int-1)
            time_f = [time_f, coin(n)*ones(1,(time_oth(n)-time_oth(n-1)))];
        end
        time_f = [time_f, zeros(1,100-time_oth(end))];
    else
        time_f = [coin(1)*ones(1,time_res), zeros(1,time_rangeS1(1))];
    end
    
    % Select steady-state input
    inp_range1 = inp_range; inp_range1 = inp_range1(randperm(length(inp_range1)));
    inp_sim = inp_range1(1);
    
    % Select transient input
    inp_range2 = 1:0.2:4;
    % Initialize input-output
    inp_plot = []; out_plot = []; time_plot = 1:1:time_lim;
    time_sim = 1; inp = inp_sim;
    state = inv(1-Ap)*Bp*(inp-usP); out = ysP + Cp*state;
    
    % Simulation
    while time_sim <= time_lim
        if time_f(time_sim) == 1
            inp = inp;
        else
            inp_range2 = inp_range2(randperm(length(inp_range2)));
            inp = inp_range2(1);
        end
            
        state = Ap*state + Bp*(inp-usP); out = ysP + Cp*state;
        inp_plot = [inp_plot,inp]; out_plot = [out_plot,out];
        time_sim = time_sim + 1;
    end
    
    out_plot = out_plot + sqrt(0.05^2)*randn(size(out_plot));
    % Plot
    clf
    fig_name = sprintf('TSfig %d',track);
    plot(time_plot,out_plot)%,20,'filled') % Default dot size 36
    xlim([1 110]); ylim([5 10]);
    
    % Save
    path = 'C:\Users\DELL\Desktop\CNN\Code\Exper2\TS';
    saveas(gcf,fullfile(path,fig_name),'jpeg')
    clf
    
    % Next image
    track = track + 1;
end
