Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Архив3 / kursach_Khramov / курсач_Храмов / 637-Садчиков-19.docx
Скачиваний:
31
Добавлен:
07.08.2013
Размер:
259.19 Кб
Скачать

Приложение а. Текст программы

stacksize('max');

clear();

funcprot(0);

//====================================

printf("\n +++++++ Task 1 +++++++ \n");

x = fscanfMat('E:\data.txt'); // Reading file

// Correlation function

function [rez]=corr(x, t)

rez = 0;

k = abs(t);

n = length(x);

MX = mean(x);

for i = 1 : n - k

rez = rez + (x(i) - MX) * (x(i + k) - MX);

end;

rez = rez / (n - k);

endfunction

// Normalized correlation function

function [rez]=normCorr(x, t)

n = length(x);

dx = corr(x, 0);

rez = corr(x, t) / dx;

endfunction

// Calculating values of correlation function

function [rez]=corrValCalc(x, tmax)

rez = zeros(tmax + 1, 1);

for i = 0 : tmax

rez(i + 1) = corr(x, i);

end;

endfunction

// Calculating values of normalized correlation function

function [rez]=normCorrValCalc(x, tmax)

rez = zeros(tmax + 1, 1);

for i = 0 : tmax

rez(i + 1) = normCorr(x, i);

end;

endfunction

// Correlation diatance

function [rez]=corrDist(x, tmax)

for t = tmax : -1 : 0

if abs(normCorr(x, t)) >= 1 / %e

rez = t + 1;

break;

end;

end;

endfunction

// Drawing normalized correlation function plot

function []=plotNormCorrFunc(x, tmax, _style)

t = [0 : tmax];

r = normCorrValCalc(x, tmax);

plot2d(t, r, style = _style);

endfunction

//vector output

function []=printVec(str, x)

n = length(x);

printf(str);

for i = 1 : n

printf("%.4f", x(i));

if i < n then

printf("\t");

else

printf("\n");

end;

end;

if n == 0 then

printf("\n");

end;

endfunction

printf("Maximal value = %.4f\n", max(x));

printf("Minimal value = %.4f\n", min(x));

MX = mean(x); // Sample mean

printf("Sample mean = %.4f\n", MX);

DX = corr(x, 0); // Sample variance

printf("Sample variance = %.4f\n", DX);

T = corrDist(x, 50); // Correlation distance

printf("Correlation distance = %d\n", T);

plotNormCorrFunc(x, 15, 2);

xtitle('', 'Index number', 'Normalized correlation function');

printVec("\n Correlation function values: \n",corrValCalc(x, 15));

printVec("\n Normalized correlation function values: \n", normCorrValCalc(x, 15));

//====================================

printf("\n +++++++ Task 2 +++++++ \n");

// Calculating autoregression coefficients beta(1)...beta(M)

function [rez]=findBetas(x, M, N)

if M == 0 then

rez = [];

else

R = zeros(2 * M, 1);

for i = N - M + 1 : N + M

R(i + M - N) = corr(x, i);

end;

A = zeros(M, M); //matrix of linear system

b = zeros(M, 1); //Column of constant terms

for i = 1 : M

b(i) = -R(M + i);

for j = 1 : M

A(i, j) = R(M + i - j);

end;

end;

rez = linsolve(A, b);

end;

endfunction

// Calculating moving average coefficients alpha(0)...alpha(N)

// (first method)

function [rez]=findAlphas1(x, M, N, betas)

// Calculating correlation function values

R = corrValCalc(x, max(M, N));

//function for solving nonlinear system

function [rez]=funcToZero(alphas)

rez = zeros(N + 1, 1);

for i = 0 : N

rez(i + 1) = -R(i + 1); // Constant term

// Terms containing beta

for j = 1 : M

rez(i + 1) = rez(i + 1) + betas(j) * R(abs(j - i) + 1);

end;

RR = mutCorr(alphas, betas); // mutual correlation function

// Terms containing alpha

for j = i : N

rez(i + 1) = rez(i + 1) + alphas(j + 1) * RR(j - i + 1);

end;

end;

endfunction

// Solving nonlinear system

[rez, values, info] = fsolve([1 : N + 1], funcToZero);

if info == 4 then // solving failed - no solution

rez(1) = %nan;

end;

endfunction

// Calculating moving average coefficients alpha(0)...alpha(N)

// (second method)

function [rez]=findAlphas2(x, M, N, betas)

function [rez]=generateMovingAverage(x, betas)

n = length(x);

rez = zeros(n, 1);

for i = 1 : n

rez(i) = x(i);

j = 1;

while j <= M & i - j > 0 do

rez(i) = rez(i) - betas(j) * x(i - j);

j = j + 1;

end;

end;

endfunction

// Generating y

y = generateMovingAverage(x, betas);

// Calculating correlation function R(n)

R = corrValCalc(y, N);

disp(R);

// function for solving nonlinear system

function [rez]=funcToZero(alpha)

rez = zeros(N + 1, 1);

for i = 0 : N

rez(i + 1) = -R(i + 1);

for j = 0 : N - i

rez(i + 1) = rez(i + 1) + alpha(j + 1) * alpha(j + i + 1);

end;

end;

endfunction

// Solving nonlinear system

[rez, values, info] = fsolve([1 : N + 1], funcToZero);

if info == 4 then // solving failed - no solution

rez(1) = %nan;

end;

endfunction

// Mutual correlation function

function [rez]=mutCorr(alphas, betas)

N = length(alphas) - 1;

M = length(betas);

rez = zeros(N + 1, 1);

for i = 0 : N

rez(i + 1) = alphas(i + 1);

m = min(i, M);

for j = 1 : m

rez(i + 1) = rez(i + 1) + betas(j) * rez(i - j + 1);

end;

end;

endfunction

// Stability check

function [rez]=isStable(betas)

n = length(betas);

select n

case 0 then

rez = %T;

case 1 then

rez = abs(betas(1)) < 1;

case 2 then

rez = abs(betas(2)) < 1 &..

abs(betas(1)) < 1 - betas(2);

case 3 then

rez = abs(betas(3)) < 1 &..

abs(betas(1) + betas(3)) < 1 - betas(2) &..

abs(betas(2) + betas(1) * betas(3)) < abs(1 - betas(3) ^ 2);

end;

endfunction

function []=dispAllModels

for M = 0 : 3

for N = 0 : 3

printf("(M, N) = (%d, %d)\n", M, N);

betas = findBetas(x, M, N);

if isStable(betas) == %F then

printf("unstable\n");

else

alphas = findAlphas1(x, M, N, betas);

if isnan(alphas(1)) == %T then

printf("no model\n");

else

printVec("alphas = ", alphas);

printVec("betas = ", betas);

end;

end;

printf("\n");

end;

end;

endfunction

dispAllModels;

//====================================

printf("\n +++++++ Task 3 +++++++ \n");

// Theoretiacal correlation function

function [rez]=theorCorr(alphas, betas, t)

M = length(betas);

N = length(alphas) - 1;

n = max(M + 1, N + 1);

RR = mutCorr(alphas, betas);

b = zeros(n, 1);

for i = 0 : N

for j = i : N

b(i + 1) = b(i + 1) + alphas(j + 1) * RR(j - i + 1);

end;

end;

A = zeros(n, n);

c = zeros(n, 1);

c(1) = -1;

c(2 : M + 1) = betas;

c(M + 2 : n) = 0;

for i = 1 : n

p = i;

k = i;

for j = 1 : n

if k > 0 then

A(i, j) = A(i, j) + c(k);

end;

if p <= n & p <> k then

A(i, j) = A(i, j) + c(p);

end;

p = p + 1;

k = k - 1;

end;

end;

R = linsolve(A, b);

if t + 1 < n then

rez = R(1 : t + 1);

else

rez = zeros(t + 1, 1);

rez(1 : n) = R(1 : n);

for i = n + 1 : t + 1

for j = 1 : M

rez(i) = rez(i) + betas(j) * rez(i - j);

end;

end;

end;

endfunction

//Normalized theoretical correlation function

function [rez]=theorNormCorr(alphas, betas, t)

rez = theorCorr(alphas, betas, t);

dx = rez(1);

rez = rez / dx;

endfunction

function []=plotTheorNormCorr(alphas, betas, tmax, _style)

t = [0 : tmax];

r = theorNormCorr(alphas, betas, tmax);

plot2d(t, r, style = _style);

endfunction

// Standart deviation

function [rez]=stdeviation(r1, r2, m)

rez = 0;

for i = 1 : m + 1

rez = rez + (r1(i) - r2(i)) ^ 2;

end;

endfunction

// Search of best models

function [EpsMatr, bestARparams, bestMAparams, bestARMAparams]=..

findBestModels(Mmax, Nmax)

// search of all deviations

EpsMatr = zeros(Mmax + 1, Nmax + 1);

for M = 0 : Mmax

for N = 0 : Nmax

betas = findBetas(x, M, N);

if isStable(betas) == %F then

EpsMatr(M + 1, N + 1) = %inf; // unstable

else

alphas = findAlphas1(x, M, N, betas);

if isnan(alphas(1)) == %T then

EpsMatr(M + 1, N + 1) = %nan; // do not exist

else

theor_r = theorNormCorr(alphas, betas, 10);

r = normCorrValCalc(x, 10);

EpsMatr(M + 1, N + 1) = stdeviation(r, theor_r, 10);

end;

end;

end;

end;

// best AR

bestARparams = zeros(1, 2);

AReps = EpsMatr(1, 1);

for M = 1 : Mmax

if EpsMatr(M + 1, 1) < AReps then

AReps = EpsMatr(M + 1, 1);

bestARparams(1) = M;

end;

end;

// best MA

bestMAparams = zeros(1, 2);

MAeps = EpsMatr(1, 1);

for N = 1 : Nmax

if EpsMatr(1, N + 1) < MAeps then

MAeps = EpsMatr(1, N + 1);

bestMAparams(2) = N;

end;

end;

// best ARMA

bestARMAparams = zeros(1, 2);

if AReps < MAeps then

ARMAeps = AReps;

bestARMAparams = bestARparams;

else

ARMAeps = MAeps;

bestARMAparams = bestMAparams;

end;

for M = 1 : Mmax

for N = 1 : Nmax

if EpsMatr(M + 1, N + 1) < ARMAeps then

ARMAeps = EpsMatr(M + 1, N + 1);

bestARMAparams = [M, N];

end;

end;

end;

endfunction

// best models

[EpsMatr, bestARparams, bestMAparams, bestARMAparams] = ..

findBestModels(3, 3);

// Displays matrix

function []=printMtr(str, A)

[m, n] = size(A);

printf(str + "\n");

for i = 1 : m

for j = 1 : n

printf("%.4f", A(i, j));

if j < n then

printf("\t");

else

printf("\n");

end;

end;

end;

endfunction

printMtr("Theoretical error of ARMA(M, N) models:", EpsMatr);

printf("\nParams of best AR (M, N) model = (%d, %d)\n", ..

bestARparams(1), bestARparams(2));

printf("Params of best MA (M, N) model = (%d, %d)\n", ..

bestMAparams(1), bestMAparams(2));

printf("Params of best ARMA (M, N) model = (%d, %d)\n", ..

bestARMAparams(1), bestARMAparams(2));

// AR

betasAR = ..

findBetas(x, bestARparams(1), bestARparams(2));

alphasAR = ..

findAlphas1(x, bestARparams(1), bestARparams(2), betasAR);

// MA

betasMA = ..

findBetas(x, bestMAparams(1), bestMAparams(2));

alphasMA = ..

findAlphas1(x, bestMAparams(1), bestMAparams(2), betasMA);

// ARMA

betasARMA = ..

findBetas(x, bestARMAparams(1), bestARMAparams(2));

alphasARMA = ..

findAlphas1(x, bestARMAparams(1), bestARMAparams(2), betasARMA);

scf(1);

plotTheorNormCorr(alphasAR, betasAR, 15, 2);

xtitle('', 'Index number', 'Normalized correlation function');

scf(2);

plotTheorNormCorr(alphasMA, betasMA, 15, 2);

xtitle('', 'Index number', 'Normalized correlation function');

scf(3);

plotTheorNormCorr(alphasARMA, betasARMA, 15, 2);

xtitle('', 'Index number', 'Normalized correlation function');

//====================================

printf("\n +++++++ Task 4 +++++++ \n");

// Spectral density of ARMA model

function [ans]=ARMASpecPowDens(alphas, betas, w)

N = length(alphas) - 1;

M = length(betas);

a = 0;

for k = 0 : N

a = a + alphas(k + 1) * exp(%i * w * k);

end;

b = 1;

for k = 1 : M

b = b - betas(k) * exp(%i * w * k);

end;

ans = (abs((a / b)) ^ 2) / theorCorr(alphas, betas, 0);

endfunction

// Power spectral density

function [ans]=specPowDens(R, w)

n = length(R);

ans = R(1);

for k = 1 : n - 1

ans = ans + 2 * R(k + 1) * cos(w * k);

end;

ans = ans / R(1);

endfunction

// Calculationg values of power spectral density

function [ans]=ARMASpecPowDensValCalc(alphas, betas, step)

n = int(%pi / step) + 1;

ans = zeros(n, 1);

w = 0;

for i = 1 : n

ans(i) = ARMASpecPowDens(alphas, betas, w);

w = min(w + step, %pi);

end;

endfunction

// calculates values of sample power spectral density

function [ans]=getSpecPowDensValues(x, tmax, step)

n = int(%pi / step) + 1;

R = corrValCalc(x, tmax);

ans = zeros(n, 1);

w = 0;

for i = 1 : n

ans(i) = specPowDens(R, w);

w = min(w + step, %pi);

end;

endfunction

// ARMA power spectral density plot

function []=plotARMASpecPowDens(alphas, betas, step, _style)

w = [0 : step : %pi];

Fi = ARMASpecPowDensValCalc(alphas, betas, step);

plot2d(w, Fi, style = _style);

endfunction

// sample power spectral density plot

function []=plotSpecPowDens(x, tmax, step, _style)

w = [0 : step : %pi];

Fi = getSpecPowDensValues(x, tmax, step);

plot2d(w, Fi, style = _style);

endfunction

//imitation (from task 5)

function [imt]=imitate(alphas, betas, MX, tmax)

defect = 1000;

imt = zeros(tmax + defect + 1, 1);

xi = grand(tmax + defect + 1, 1, 'nor', 0, 1);

N = length(alphas) - 1;

M = length(betas);

for k = 1 : tmax + defect + 1,

imt(k) = 0;

for i = 0 : N,

if (k - i > 0) then

imt(k) = imt(k) + alphas(i+1) * xi(k - i);

end;

end;

for j = 1 : M,

if (k - j > 0) then

imt(k) = imt(k) + betas(j) * imt(k - j);

end;

end;

end;

imt = imt(defect + 2 : tmax + defect + 1) + MX;

endfunction;

imitAR = imitate(alphasAR, betasAR, MX, 6000);

imitMA = imitate(alphasMA, betasMA, MX, 6000);

imitARMA = imitate(alphasARMA, betasARMA, MX, 6000);

scf(4);

plotARMASpecPowDens(alphasAR, betasAR, 0.01, 3);

plotSpecPowDens(x, 30, 0.01, 5);

plotSpecPowDens(imitAR, 30, 0.01, 2);

legends(['Source', 'AR(' + string(bestARparams(1)) + ')','Imitation'],[5, 3, 2], opt='ur');

xtitle('', 'Frequency', 'Normalized power spectral density');

scf(5);

plotARMASpecPowDens(alphasMA, betasMA, 0.01, 3);

plotSpecPowDens(x, 30, 0.01, 5);

plotSpecPowDens(imitMA, 30, 0.01, 2);

legends(['Source', 'MA(' + string(bestMAparams(2)) + ')','Imitation'],[5, 3, 2], opt='ur');

xtitle('', 'Frequency', 'Normalized power spectral density');

scf(6);

plotARMASpecPowDens(alphasARMA, betasARMA, 0.01, 3);

plotSpecPowDens(x, 30, 0.01, 5);

plotSpecPowDens(imitARMA, 30, 0.01, 2);

legends(['Source', 'ARMA(' + string(bestARMAparams(1)) + ',' + string(bestARMAparams(2)) + ')','Imitation'],[5, 3, 2], opt='ur');

xtitle('', 'Frequency', 'Normalized power spectral density');

//====================================

printf("\n +++++++ Task 5 +++++++ \n");

// plot realization of <count> values

// plots additional lines for standart deviation and MX

// if params = true

function []=plotReal(x, count, _style, params)

n = min(count, length(x));

plot2d([1 : n], x(1 : n), style = _style);

if params == %T then

mx = mean(x);

sigmaX = sqrt(corr(x, 0));

plot2d([1 : n], ones(count, 1) * mx, 1);

plot2d([1 : n], ones(count, 1) * (mx - sigmaX), 15);

plot2d([1 : n], ones(count, 1) * (mx + sigmaX), 15);

end;

endfunction

scf(7);

plotReal(x, 80, 5, %T);

plotReal(imitAR, 80, 2, %F);

legends(['Source', 'AR(' + string(bestARparams(1)) + ')','Average','St. deviation'],[5, 2, 1, 16], opt='ll');

xtitle('', 'Index number', 'Random sequence values');

scf(8);

plotReal(x, 80, 5, %T);

plotReal(imitMA, 80, 2, %F);

legends(['Source', 'MA(' + string(bestMAparams(2)) + ')','Average','St. deviation'],[2, 5, 1, 16], opt='ll');

xtitle('', 'Index number', 'Random sequence values');

scf(9);

plotReal(x, 80, 5, %T);

plotReal(imitARMA, 80, 2, %F);

legends(['Source', 'ARMA(' + string(bestARMAparams(1)) + ', ' + string(bestARMAparams(2)) + ')','Average','St. deviation'],[5, 2, 1, 16], opt='ll');

xtitle('', 'Index number', 'Random sequence values');

//====================================

printf("\n +++++++ Task 6 +++++++ \n");

// plotting normalized correlation functuons

scf(10);

plotNormCorrFunc(x, 10, 5);

plotTheorNormCorr(alphasAR, betasAR, 10, 2);

plotNormCorrFunc(imitAR, 10, 15);

//plot2d([0 : 10], ones(11, 1) * (-1) / %e, style = 8);

legends(['Source','Imitation','AR(' + string(bestARparams(1)) + ')'],[5, 2, 15], opt='ur');

xtitle('', 'Index number', 'Normalized correlation function');

scf(11);

plotNormCorrFunc(x, 10, 5);

plotTheorNormCorr(alphasMA, betasMA, 10, 2);

plotNormCorrFunc(imitMA, 10, 15);

//plot2d([0 : 10], ones(11, 1) * (-1) / %e, style = 8);

legends(['Source','Imitation','MA(' + string(bestMAparams(2)) + ')'],[5, 2, 15], opt='ur');

xtitle('', 'Index number', 'Normalized correlation function');

scf(12);

plotNormCorrFunc(x, 10, 5);

plotTheorNormCorr(alphasARMA, betasARMA, 10, 2);

plotNormCorrFunc(imitARMA, 10, 15);

//plot2d([0 : 10], ones(11, 1) * (-1) / %e, style = 8);

legends(['Source','Imitation','ARMA(' + string(bestARMAparams(1)) + ', ' + string(bestARMAparams(2)) + ')'],[5, 2, 15], opt='ur');

xtitle('', 'Index number', 'Normalized correlation function');

// calculating all necessary parameters

// sample min

minX = min(x);

minAR = min(imitAR);

minMA = min(imitMA);

minARMA = min(imitARMA);

// sample max

maxX = max(x);

maxAR = max(imitAR);

maxMA = max(imitMA);

maxARMA = max(imitARMA);

// sample mean

mx = mean(x);

mAR = mean(imitAR);

mMA = mean(imitMA);

mARMA = mean(imitARMA);

// sample variance

dx = corr(x,0);

dAR = corr(imitAR, 0);

dMA = corr(imitMA, 0);

dARMA = corr(imitARMA, 0);

// standart deviations

sigmaX = sqrt(dx);

sigmaAR = sqrt(dAR);

sigmaMA = sqrt(dMA);

sigmaARMA = sqrt(dARMA);

// Normalized correlation functions

r = normCorrValCalc(x, 15);

r_AR = normCorrValCalc(imitAR, 15);

r_MA = normCorrValCalc(imitMA, 15);

r_ARMA = normCorrValCalc(imitARMA, 15);

theor_r_AR = theorNormCorr(alphasAR, betasAR, 15);

theor_r_MA = theorNormCorr(alphasMA, betasMA, 15);

theor_r_ARMA = theorNormCorr(alphasARMA, betasARMA, 15);

// output

printVec("\n Mins: (source, AR, MA, ARMA):\n", [minX, minAR, minMA, minARMA]);

printVec("\n Maxs: (source, AR, MA, ARMA):\n",[maxX, maxAR, maxMA, maxARMA]);

printVec("\n Means: (source, AR, MA, ARMA):\n",[mx, mAR, mMA, mARMA]);

printVec("\n Variances (source, AR, MA, ARMA):\n", [dx, dAR, dMA, dARMA]);

printVec("\n Standart deviations: (source, AR, MA, ARMA):\n", [sigmaX, sigmaAR, sigmaMA, sigmaARMA]);

printMtr("\n Normalized correlation function values:\n" + ..

"(source, theor AR, sample AR, theor MA, samle MA, theor ARMA, samle ARMA)",[r, theor_r_AR, r_AR, theor_r_MA, r_MA, theor_r_ARMA, r_ARMA]);

// standart deviations for correlation functions

deviations = [stdeviation(r, r, 10),stdeviation(r, theor_r_AR, 15),stdeviation(r, r_AR, 15),stdeviation(r, theor_r_MA, 15),stdeviation(r, r_MA, 15),stdeviation(r, theor_r_ARMA, 15),stdeviation(r, r_ARMA, 15)];

printVec("\n St. Deviation for correlation functions:\n", deviations);

Соседние файлы в папке курсач_Храмов