tsa/ 0000775 0023567 0023567 00000000000 12264575422 012066 5 ustar schloegl schloegl tsa/src/ 0000775 0023567 0023567 00000000000 12264575422 012655 5 ustar schloegl schloegl tsa/src/Makefile 0000664 0023567 0023567 00000011160 12264575422 014314 0 ustar schloegl schloegl ####################################################
# Copyright 2010,2011,2012 Alois Schloegl
# This is part of the TSA-toolbox - a statistics and machine learning toolbox for data with and without missing values.
# http://pub.ist.ac.at/~schloegl/matlab/tsa/
####################################################
### modify directories according to your needs
# Define non-default octave-version
# Octave - global install (e.g. from debian package)
# OCTAVE_VERSION=
# Better alternative: define an OCTAVE_VERSION bash variable (or in .bashrc or .profile)
# OCTAVE_VERSION=-3.6.3
# Matlab configuration
# MATLABDIR = /usr/local/MATLAB/R2010b
# comment the following line if you use MATLAB on 32-bit operating system
MEX_OPTION += -largeArrayDims
# Mingw crosscompiler: available at http://www.nongnu.org/mingw-cross-env/
CROSS = $(HOME)/src/mxe.github.schloegl/usr/bin/i686-pc-mingw32
CROSS64 = $(HOME)/src/mxe.github.schloegl/usr/bin/x86_64-w64-mingw32
# include directory for Win32-Matlab include
W32MAT_INC = -I$(HOME)/bin/win32/Matlab/R2010b/extern/include/
W64MAT_INC = -I$(HOME)/bin/win64/Matlab/R2010b/extern/include/
# path to GNUMEX libraries, available from here http://sourceforge.net/projects/gnumex/
GNUMEX = $(HOME)/bin/win32/gnumex
GNUMEX64 = $(HOME)/bin/win64/gnumex
# building gnumex64 was difficult, these hints were quite useful:
# http://sourceforge.net/mailarchive/forum.php?thread_name=AANLkTinZvxgC9ezp2P3UCX_a7TAUYuVsp2U40MQUV6qr%40mail.gmail.com&forum_name=gnumex-users
# Instead of building "mex shortpath.c" and "mex uigetpath.c", I used empty m-functions within argout=argin;
####################################################
W32MAT_INC += -I$(subst /usr/bin/,/usr/,$(CROSS))/include/
W64MAT_INC += -I$(subst /usr/bin/,/usr/,$(CROSS64))/include/
LDLIBS_W32 = $(subst /usr/bin/,/usr/,$(CROSS))/lib/
LDLIBS_W64 = $(subst /usr/bin/,/usr/,$(CROSS64))/lib/
W32_LIBS = $(LDLIBS_W32)liblapack.a
W64_LIBS = $(LDLIBS_W64)liblapack.a
W32_LIBS += $(LDLIBS_W32)libblas.a
W64_LIBS += $(LDLIBS_W64)libblas.a
CC = gcc
CXX = g++
CFLAGS = -fopenmp -Wall -Wextra -Wconversion -O2 -fPIC
OCTMEX = mkoctfile$(OCTAVE_VERSION) --mex
RM = rm
MEX_OPTION += -lgomp CC\#$(CXX) CXX\#$(CXX) CFLAGS\#"$(CFLAGS)" CXXFLAGS\#"$(CFLAGS)"
MATMEX = $(MATLABDIR)/bin/mex $(MEX_OPTION)
PROGS = covm_mex.mex sumskipnan_mex.mex #
### per default only the mex-files for octave are built
mex4o octave: $(PROGS)
### Matlab configuration - search for a matlab directory if not defined above
ifndef MATLABDIR
ifneq ('',$(shell ls -1 /usr/local/MATLAB))
# use oldest, typically mex-files a compatible with newer Matlab versions
MATLABDIR=$(shell ls -dt1 /usr/local/MATLAB/R* |tail -1)
# alternatively, use latest matlab version
#MATLABDIR=$(shell ls -dt1 /usr/local/MATLAB/R* |head -1)
endif
endif
### if the MATLABDIR has been found or defined
ifneq ('',MATLABDIR)
ifneq ('',$(lshell ls -1 $(MATLABDIR)))
MEX_EXT = $(shell $(MATLABDIR)/bin/mexext)
mex4m matlab: $(patsubst %.mex, %.$(MEX_EXT), $(PROGS))
endif
endif
mexw32 win32: $(patsubst %.mex, %.mexw32, $(PROGS))
mexw64 win64: $(patsubst %.mex, %.mexw64, $(PROGS))
all: octave win32 win64 mex4m
clean:
-$(RM) *.o *.obj *.o64 core octave-core *.oct *~ *.mex*
#########################################################
# Octave, MATLAB on Linux
#########################################################
%.oct: %.cc
mkoctfile$(OCTAVE_VERSION) "$<"
%.mex: %.cpp
$(OCTMEX) "$<" -lgomp -llapack -lblas ## Octave
%.$(MEX_EXT): %.cpp
$(MATMEX) "$<" -lgomp -llapack -lblas ## Matlab
#########################################################
# MATLAB/WIN32
#########################################################
%.obj: %.cpp
$(CROSS)-$(CXX) -fopenmp -c -DMATLAB_MEX_FILE -x c++ -o "$@" $(W32MAT_INC) -O2 -DMX_COMPAT_32 "$<"
%.obj: %.c
$(CROSS)-$(CXX) -fopenmp -c -DMATLAB_MEX_FILE -x c++ -o "$@" $(W32MAT_INC) -O2 -DMX_COMPAT_32 "$<"
%.mexw32: %.obj
$(CROSS)-$(CXX) -shared $(GNUMEX)/mex.def -o "$@" -L$(GNUMEX) -s "$<" -llibmx -llibmex -llibmat -lcholmod -lgomp -lpthread -L$(LDLIBS_W32) -lblas -llapack
#########################################################
# MATLAB/WIN64
#########################################################
## ToDO: fix OpenMP support: currently -fopenmp causes Matlab to crash
%.o64: %.cpp
$(CROSS64)-$(CXX) -c -DMATLAB_MEX_FILE -x c++ -o "$@" $(W64MAT_INC) -O2 "$<"
%.o64: %.c
$(CROSS64)-$(CXX) -c -DMATLAB_MEX_FILE -x c++ -o "$@" $(W64MAT_INC) -O2 "$<"
%.mexw64: %.o64
$(CROSS64)-$(CXX) -shared $(GNUMEX64)/mex.def -o "$@" -L$(GNUMEX64) -s "$<" -llibmx -llibmex -llibmat -lcholmod -lgomp -lpthread -L$(LDLIBS_W64) -lblas -llapack
tsa/src/covm_mex.cpp 0000664 0023567 0023567 00000046125 12264575422 015206 0 ustar schloegl schloegl /*
//-------------------------------------------------------------------
// C-MEX implementation of COVM - this function is part of the NaN-toolbox.
//
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program 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 this program; if not, see .
//
//
// covm: in-product of matrices, NaN are skipped.
// usage:
// [cc,nn] = covm_mex(X,Y,flag,W);
//
// Input:
// - X:
// - Y: [optional], if empty, Y=X;
// - flag: if not empty, it is set to 1 if some NaN was observed
// - W: weight vector to compute weighted correlation
//
// Output:
// - CC = X' * sparse(diag(W)) * Y while NaN's are skipped
// - NN = real(~isnan(X)')*sparse(diag(W))*real(~isnan(Y)) count of valid (non-NaN) elements
// computed more efficiently
//
// $Id: covm_mex.cpp 8223 2011-04-20 09:16:06Z schloegl $
// Copyright (C) 2009,2010,2011 Alois Schloegl
// This function is part of the NaN-toolbox
// http://pub.ist.ac.at/~schloegl/matlab/NaN/
//
//-------------------------------------------------------------------
*/
#ifdef __GNUC__
#include
#endif
#include
#include "mex.h"
/*#define NO_FLAG*/
void mexFunction(int POutputCount, mxArray* POutput[], int PInputCount, const mxArray *PInputs[])
{
double *X0=NULL, *Y0=NULL, *W=NULL;
double *CC;
double *NN = NULL;
size_t rX,cX,rY,cY;
size_t i;
char flag_isNaN = 0;
int ACC_LEVEL;
/*********** check input arguments *****************/
// check for proper number of input and output arguments
if ((PInputCount <= 0) || (PInputCount > 5)) {
mexPrintf("usage: [CC,NN] = covm_mex(X [,Y [,flag [,W [,'E']]]])\n\n");
mexPrintf("Do not use COVM_MEX directly, use COVM instead. \n");
/*
mexPrintf("\nCOVM_MEX computes the covariance matrix of real matrices and skips NaN's\n");
mexPrintf("\t[CC,NN] = covm_mex(...)\n\t\t computes CC=X'*Y, NN contains the number of not-NaN elements\n");
mexPrintf("\t\t CC./NN is the unbiased covariance matrix\n");
mexPrintf("\t... = covm_mex(X,Y,...)\n\t\t computes CC=X'*sparse(diag(W))*Y, number of rows of X and Y must match\n");
mexPrintf("\t... = covm_mex(X,[], ...)\n\t\t computes CC=X'*sparse(diag(W))*X\n");
mexPrintf("\t... = covm_mex(...,flag,...)\n\t\t if flag is not empty, it is set to 1 if some NaN occured in X or Y\n");
mexPrintf("\t... = covm_mex(...,W)\n\t\t W to compute weighted covariance, number of elements must match the number of rows of X\n");
mexPrintf("\t\t if isempty(W), all weights are 1\n");
mexPrintf("\t[CC,NN]=covm_mex(X,Y,flag,W)\n");
*/ return;
}
if (POutputCount > 2)
mexErrMsgTxt("covm.MEX has 1 to 2 output arguments.");
// get 1st argument
if(mxIsDouble(PInputs[0]) && !mxIsComplex(PInputs[0]))
X0 = mxGetPr(PInputs[0]);
else
mexErrMsgTxt("First argument must be REAL/DOUBLE.");
rX = mxGetM(PInputs[0]);
cX = mxGetN(PInputs[0]);
// get 2nd argument
if (PInputCount > 1) {
if (!mxGetNumberOfElements(PInputs[1]))
; // Y0 = NULL;
else if (mxIsDouble(PInputs[1]) && !mxIsComplex(PInputs[1]))
Y0 = mxGetPr(PInputs[1]);
else
mexErrMsgTxt("Second argument must be REAL/DOUBLE.");
}
// get weight vector for weighted sumskipnan
if (PInputCount > 3) {
// get 4th argument
size_t nW = mxGetNumberOfElements(PInputs[3]);
if (!nW)
;
else if (nW == rX)
W = mxGetPr(PInputs[3]);
else
mexErrMsgTxt("number of elements in W must match numbers of rows in X");
}
#ifdef __GNUC__
ACC_LEVEL = 0;
{
mxArray *LEVEL = NULL;
int s = mexCallMATLAB(1, &LEVEL, 0, NULL, "flag_accuracy_level");
if (!s) {
ACC_LEVEL = (int) mxGetScalar(LEVEL);
}
mxDestroyArray(LEVEL);
}
// mexPrintf("Accuracy Level=%i\n",ACC_LEVEL);
#endif
if (Y0==NULL) {
Y0 = X0;
rY = rX;
cY = cX;
}
else {
rY = mxGetM(PInputs[1]);
cY = mxGetN(PInputs[1]);
}
if (rX != rY)
mexErrMsgTxt("number of rows in X and Y do not match");
/*********** create output arguments *****************/
POutput[0] = mxCreateDoubleMatrix(cX, cY, mxREAL);
CC = mxGetPr(POutput[0]);
if (POutputCount > 1) {
POutput[1] = mxCreateDoubleMatrix(cX, cY, mxREAL);
NN = mxGetPr(POutput[1]);
}
/*********** compute covariance *****************/
#if 0
/*------ version 1 ---------------------
this solution is slower than the alternative solution below
for transposed matrices, this might be faster.
*/
for (k=0; k 2) && mxGetNumberOfElements(PInputs[2])) {
// set FLAG_NANS_OCCURED
switch (mxGetClassID(PInputs[2])) {
case mxDOUBLE_CLASS:
*(double*)mxGetData(PInputs[2]) = 1.0;
break;
case mxSINGLE_CLASS:
*(float*)mxGetData(PInputs[2]) = 1.0;
break;
case mxLOGICAL_CLASS:
case mxCHAR_CLASS:
case mxINT8_CLASS:
case mxUINT8_CLASS:
*(char*)mxGetData(PInputs[2]) = 1;
break;
#ifdef __GNUC__
case mxINT16_CLASS:
case mxUINT16_CLASS:
*(uint16_t*)mxGetData(PInputs[2]) = 1;
break;
case mxINT32_CLASS:
case mxUINT32_CLASS:
*(uint32_t*)mxGetData(PInputs[2])= 1;
break;
case mxINT64_CLASS:
case mxUINT64_CLASS:
*(uint64_t*)mxGetData(PInputs[2]) = 1;
break;
case mxFUNCTION_CLASS:
case mxUNKNOWN_CLASS:
case mxCELL_CLASS:
case mxSTRUCT_CLASS:
#endif
default:
mexPrintf("Type of 3rd input argument cannot be used to return status of NaN occurence.");
}
}
#endif
#endif
}
tsa/src/sumskipnan_mex.cpp 0000664 0023567 0023567 00000060452 12264575422 016431 0 ustar schloegl schloegl
//-------------------------------------------------------------------
// C-MEX implementation of SUMSKIPNAN - this function is part of the NaN-toolbox.
//
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program 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 this program; if not, see .
//
//
// sumskipnan: sums all non-NaN values
// usage:
// [o,count,SSQ] = sumskipnan_mex(x,DIM,flag,W);
//
// SUMSKIPNAN uses two techniques to reduce errors:
// 1) long double (80bit) instead of 64-bit double is used internally
// 2) The Kahan Summation formula is used to reduce the error margin from N*eps to 2*eps
// The latter is only implemented in case of stride=1 (column vectors only, summation along 1st dimension).
//
// Input:
// - x data array
// - DIM (optional) dimension to sum
// - flag (optional) is actually an output argument telling whether some NaN was observed
// - W (optional) weight vector to compute weighted sum (default 1)
//
// Output:
// - o (weighted) sum along dimension DIM
// - count of valid elements
// - sums of squares
//
//
// $Id: sumskipnan_mex.cpp 12492 2014-01-10 13:34:15Z schloegl $
// Copyright (C) 2009,2010,2011 Alois Schloegl
// This function is part of the NaN-toolbox
// http://pub.ist.ac.at/~schloegl/matlab/NaN/
//
//-------------------------------------------------------------------
#include
#include
#include "mex.h"
inline int __sumskipnan2w__(double *data, size_t Ni, double *s, double *No, char *flag_anyISNAN, double *W);
inline int __sumskipnan3w__(double *data, size_t Ni, double *s, double *s2, double *No, char *flag_anyISNAN, double *W);
inline int __sumskipnan2wr__(double *data, size_t Ni, double *s, double *No, char *flag_anyISNAN, double *W);
inline int __sumskipnan3wr__(double *data, size_t Ni, double *s, double *s2, double *No, char *flag_anyISNAN, double *W);
inline int __sumskipnan2we__(double *data, size_t Ni, double *s, double *No, char *flag_anyISNAN, double *W);
inline int __sumskipnan3we__(double *data, size_t Ni, double *s, double *s2, double *No, char *flag_anyISNAN, double *W);
inline int __sumskipnan2wer__(double *data, size_t Ni, double *s, double *No, char *flag_anyISNAN, double *W);
inline int __sumskipnan3wer__(double *data, size_t Ni, double *s, double *s2, double *No, char *flag_anyISNAN, double *W);
//#define NO_FLAG
#ifdef tmwtypes_h
#if (MX_API_VER<=0x07020000)
typedef int mwSize;
#endif
#endif
void mexFunction(int POutputCount, mxArray* POutput[], int PInputCount, const mxArray *PInputs[])
{
const mwSize *SZ;
double* LInput;
double* LOutputSum;
double* LOutputCount;
double* LOutputSum2;
long double* LongOutputSum = NULL;
long double* LongOutputCount = NULL;
long double* LongOutputSum2 = NULL;
double x;
double* W = NULL; // weight vector
mwSize DIM = 0;
mwSize D1, D2, D3; // NN; //
mwSize ND, ND2; // number of dimensions: input, output
mwSize ix0, ix1, ix2; // index to input and output
mwSize j, l; // running indices
mwSize *SZ2; // size of output
char flag_isNaN = 0;
// check for proper number of input and output arguments
if ((PInputCount <= 0) || (PInputCount > 4))
mexErrMsgTxt("SUMSKIPNAN.MEX requires between 1 and 4 arguments.");
if (POutputCount > 4)
mexErrMsgTxt("SUMSKIPNAN.MEX has 1 to 3 output arguments.");
// get 1st argument
if(mxIsDouble(PInputs[0]) && !mxIsComplex(PInputs[0]))
LInput = mxGetPr(PInputs[0]);
else
mexErrMsgTxt("First argument must be REAL/DOUBLE.");
// get 2nd argument
if (PInputCount > 1) {
switch (mxGetNumberOfElements(PInputs[1])) {
case 0: x = 0.0; // accept empty element
break;
case 1: x = (mxIsNumeric(PInputs[1]) ? mxGetScalar(PInputs[1]) : -1.0);
break;
default:x = -1.0; // invalid
}
if ((x < 0) || (x > 65535) || (x != floor(x)))
mexErrMsgTxt("Error SUMSKIPNAN.MEX: DIM-argument must be a positive integer scalar");
DIM = (unsigned)floor(x);
}
// get size
ND = mxGetNumberOfDimensions(PInputs[0]);
// NN = mxGetNumberOfElements(PInputs[0]);
SZ = mxGetDimensions(PInputs[0]);
// if DIM==0 (undefined), look for first dimension with more than 1 element.
for (j = 0; (DIM < 1) && (j < ND); j++)
if (SZ[j]>1) DIM = j+1;
if (DIM < 1) DIM=1; // in case DIM is still undefined
ND2 = (ND>DIM ? ND : DIM); // number of dimensions of output
SZ2 = (mwSize*)mxCalloc(ND2, sizeof(mwSize)); // allocate memory for output size
for (j=0; j ND, add extra elements 1
SZ2[j] = 1;
for (j=0, D1=1; j 3) {
if (!mxGetNumberOfElements(PInputs[3]))
; // empty weight vector - no weighting
else if (mxGetNumberOfElements(PInputs[3])==D2)
W = mxGetPr(PInputs[3]);
else
mexErrMsgTxt("Error SUMSKIPNAN.MEX: length of weight vector does not match size of dimension");
}
int ACC_LEVEL = 0;
{
mxArray *LEVEL = NULL;
int s = mexCallMATLAB(1, &LEVEL, 0, NULL, "flag_accuracy_level");
if (!s) {
ACC_LEVEL = (int) mxGetScalar(LEVEL);
if ((D1>1) && (ACC_LEVEL>2))
mexWarnMsgTxt("Warning: Kahan summation not supported with stride > 1 !");
}
mxDestroyArray(LEVEL);
}
// mexPrintf("Accuracy Level=%i\n",ACC_LEVEL);
// create outputs
#define TYP mxDOUBLE_CLASS
POutput[0] = mxCreateNumericArray(ND2, SZ2, TYP, mxREAL);
LOutputSum = mxGetPr(POutput[0]);
if (D1!=1 && D2>0) LongOutputSum = (long double*) mxCalloc(D1*D3,sizeof(long double));
if (POutputCount >= 2) {
POutput[1] = mxCreateNumericArray(ND2, SZ2, TYP, mxREAL);
LOutputCount = mxGetPr(POutput[1]);
if (D1!=1 && D2>0) LongOutputCount = (long double*) mxCalloc(D1*D3,sizeof(long double));
}
if (POutputCount >= 3) {
POutput[2] = mxCreateNumericArray(ND2, SZ2, TYP, mxREAL);
LOutputSum2 = mxGetPr(POutput[2]);
if (D1!=1 && D2>0) LongOutputSum2 = (long double*) mxCalloc(D1*D3,sizeof(long double));
}
mxFree(SZ2);
if (!D1 || !D2 || !D3) // zero size array
; // do nothing
else if (D1==1) {
if (ACC_LEVEL<1) {
// double accuray, naive summation, error = N*2^-52
switch (POutputCount) {
case 0:
case 1:
#pragma omp parallel for schedule(dynamic)
for (l = 0; l DIM
for (l = 0; l DIM
for (l = 0; l DIM
for (l = 0; l 2) && mxGetNumberOfElements(PInputs[2])) {
// set FLAG_NANS_OCCURED
switch (mxGetClassID(PInputs[2])) {
case mxLOGICAL_CLASS:
case mxCHAR_CLASS:
case mxINT8_CLASS:
case mxUINT8_CLASS:
*(uint8_t*)mxGetData(PInputs[2]) = 1;
break;
case mxDOUBLE_CLASS:
*(double*)mxGetData(PInputs[2]) = 1.0;
break;
case mxSINGLE_CLASS:
*(float*)mxGetData(PInputs[2]) = 1.0;
break;
case mxINT16_CLASS:
case mxUINT16_CLASS:
*(uint16_t*)mxGetData(PInputs[2]) = 1;
break;
case mxINT32_CLASS:
case mxUINT32_CLASS:
*(uint32_t*)mxGetData(PInputs[2])= 1;
break;
case mxINT64_CLASS:
case mxUINT64_CLASS:
*(uint64_t*)mxGetData(PInputs[2]) = 1;
break;
case mxFUNCTION_CLASS:
case mxUNKNOWN_CLASS:
case mxCELL_CLASS:
case mxSTRUCT_CLASS:
default:
mexPrintf("Type of 3rd input argument not supported.");
}
}
#endif
}
#define stride 1
inline int __sumskipnan2w__(double *data, size_t Ni, double *s, double *No, char *flag_anyISNAN, double *W)
{
long double sum=0;
char flag=0;
// LOOP along dimension DIM
double *end = data + stride*Ni;
if (W) {
// with weight vector
long double count = 0.0;
do {
long double x = *data;
if (!isnan(x))
{
count += *W;
sum += *W*x;
}
#ifndef NO_FLAG
else
flag = 1;
#endif
data++; // stride=1
W++;
}
while (data < end);
*No = count;
} else {
// w/o weight vector
size_t countI = 0;
do {
long double x = *data;
if (!isnan(x))
{
countI++;
sum += x;
}
#ifndef NO_FLAG
else
flag = 1;
#endif
data++; // stride=1
}
while (data < end);
*No = (double)countI;
}
#ifndef NO_FLAG
if (flag && (flag_anyISNAN != NULL)) *flag_anyISNAN = 1;
#endif
*s = sum;
}
inline int __sumskipnan3w__(double *data, size_t Ni, double *s, double *s2, double *No, char *flag_anyISNAN, double *W)
{
long double sum=0;
long double msq=0;
char flag=0;
// LOOP along dimension DIM
double *end = data + stride*Ni;
if (W) {
// with weight vector
long double count = 0.0;
do {
long double x = *data;
if (!isnan(x)) {
count += *W;
long double t = *W*x;
sum += t;
msq += x*t;
}
#ifndef NO_FLAG
else
flag = 1;
#endif
data++; // stride=1
W++;
}
while (data < end);
*No = count;
} else {
// w/o weight vector
size_t countI = 0;
do {
long double x = *data;
if (!isnan(x)) {
countI++;
sum += x;
msq += x*x;
}
#ifndef NO_FLAG
else
flag = 1;
#endif
data++; // stride=1
}
while (data < end);
*No = (double)countI;
}
#ifndef NO_FLAG
if (flag && (flag_anyISNAN != NULL)) *flag_anyISNAN = 1;
#endif
*s = sum;
*s2 = msq;
}
inline int __sumskipnan2wr__(double *data, size_t Ni, double *s, double *No, char *flag_anyISNAN, double *W)
{
double sum=0;
char flag=0;
// LOOP along dimension DIM
double *end = data + stride*Ni;
if (W) {
// with weight vector
double count = 0.0;
do {
double x = *data;
if (!isnan(x))
{
count += *W;
sum += *W*x;
}
#ifndef NO_FLAG
else
flag = 1;
#endif
data++; // stride=1
W++;
}
while (data < end);
*No = count;
} else {
// w/o weight vector
size_t countI = 0;
do {
double x = *data;
if (!isnan(x))
{
countI++;
sum += x;
}
#ifndef NO_FLAG
else
flag = 1;
#endif
data++; // stride=1
}
while (data < end);
*No = (double)countI;
}
#ifndef NO_FLAG
if (flag && (flag_anyISNAN != NULL)) *flag_anyISNAN = 1;
#endif
*s = sum;
}
inline int __sumskipnan3wr__(double *data, size_t Ni, double *s, double *s2, double *No, char *flag_anyISNAN, double *W)
{
double sum=0;
double msq=0;
char flag=0;
// LOOP along dimension DIM
double *end = data + stride*Ni;
if (W) {
// with weight vector
double count = 0.0;
do {
double x = *data;
if (!isnan(x)) {
count += *W;
double t = *W*x;
sum += t;
msq += x*t;
}
#ifndef NO_FLAG
else
flag = 1;
#endif
data++; // stride=1
W++;
}
while (data < end);
*No = count;
} else {
// w/o weight vector
size_t countI = 0;
do {
double x = *data;
if (!isnan(x)) {
countI++;
sum += x;
msq += x*x;
}
#ifndef NO_FLAG
else
flag = 1;
#endif
data++; // stride=1
}
while (data < end);
*No = (double)countI;
}
#ifndef NO_FLAG
if (flag && (flag_anyISNAN != NULL)) *flag_anyISNAN = 1;
#endif
*s = sum;
*s2 = msq;
}
/***************************************
using Kahan's summation formula [1]
this gives more accurate results while the computational effort within the loop is about 4x as high
First tests show a penalty of about 40% in terms of computational time.
[1] David Goldberg,
What Every Computer Scientist Should Know About Floating-Point Arithmetic
ACM Computing Surveys, Vol 23, No 1, March 1991.
****************************************/
inline int __sumskipnan2we__(double *data, size_t Ni, double *s, double *No, char *flag_anyISNAN, double *W)
{
long double sum=0;
char flag=0;
// LOOP along dimension DIM
double *end = data + stride*Ni;
if (W) {
// with weight vector
long double count = 0.0;
long double rc=0.0, rn=0.0;
do {
long double x = *data;
long double t,y;
if (!isnan(x))
{
//count += *W; [1]
y = *W-rn;
t = count+y;
rn= (t-count)-y;
count= t;
//sum += *W*x; [1]
y = *W*x-rc;
t = sum+y;
rc= (t-sum)-y;
sum= t;
}
#ifndef NO_FLAG
else
flag = 1;
#endif
data++; // stride=1
W++;
}
while (data < end);
*No = count;
} else {
// w/o weight vector
size_t countI = 0;
long double rc=0.0;
do {
long double x = *data;
long double t,y;
if (!isnan(x))
{
countI++;
// sum += x; [1]
y = x-rc;
t = sum+y;
rc= (t-sum)-y;
sum= t;
}
#ifndef NO_FLAG
else
flag = 1;
#endif
data++; // stride=1
}
while (data < end);
*No = (double)countI;
}
#ifndef NO_FLAG
if (flag && (flag_anyISNAN != NULL)) *flag_anyISNAN = 1;
#endif
*s = sum;
}
inline int __sumskipnan3we__(double *data, size_t Ni, double *s, double *s2, double *No, char *flag_anyISNAN, double *W)
{
long double sum=0;
long double msq=0;
char flag=0;
// LOOP along dimension DIM
double *end = data + stride*Ni;
if (W) {
// with weight vector
long double count = 0.0;
long double rc=0.0, rn=0.0, rq=0.0;
do {
long double x = *data;
long double t,y;
if (!isnan(x)) {
//count += *W; [1]
y = *W-rn;
t = count+y;
rn= (t-count)-y;
count= t;
long double w = *W*x;
//sum += *W*x; [1]
y = *W*x-rc;
t = sum+y;
rc= (t-sum)-y;
sum= t;
// msq += x*w;
y = w*x-rq;
t = msq+y;
rq= (t-msq)-y;
msq= t;
}
#ifndef NO_FLAG
else
flag = 1;
#endif
data++; // stride=1
W++;
}
while (data < end);
*No = count;
} else {
// w/o weight vector
size_t countI = 0;
long double rc=0.0, rq=0.0;
do {
long double x = *data;
long double t,y;
if (!isnan(x)) {
countI++;
//sum += x; [1]
y = x-rc;
t = sum+y;
rc= (t-sum)-y;
sum= t;
// msq += x*x;
y = x*x-rq;
t = msq+y;
rq= (t-msq)-y;
msq= t;
}
#ifndef NO_FLAG
else
flag = 1;
#endif
data++; // stride=1
}
while (data < end);
*No = (double)countI;
}
#ifndef NO_FLAG
if (flag && (flag_anyISNAN != NULL)) *flag_anyISNAN = 1;
#endif
*s = sum;
*s2 = msq;
}
inline int __sumskipnan2wer__(double *data, size_t Ni, double *s, double *No, char *flag_anyISNAN, double *W)
{
double sum=0;
char flag=0;
// LOOP along dimension DIM
double *end = data + stride*Ni;
if (W) {
// with weight vector
double count = 0.0;
double rc=0.0, rn=0.0;
do {
double x = *data;
double t,y;
if (!isnan(x))
{
//count += *W; [1]
y = *W-rn;
t = count+y;
rn= (t-count)-y;
count= t;
//sum += *W*x; [1]
y = *W*x-rc;
t = sum+y;
rc= (t-sum)-y;
sum= t;
}
#ifndef NO_FLAG
else
flag = 1;
#endif
data++; // stride=1
W++;
}
while (data < end);
*No = count;
} else {
// w/o weight vector
size_t countI = 0;
double rc=0.0;
do {
double x = *data;
double t,y;
if (!isnan(x))
{
countI++;
// sum += x; [1]
y = x-rc;
t = sum+y;
rc= (t-sum)-y;
sum= t;
}
#ifndef NO_FLAG
else
flag = 1;
#endif
data++; // stride=1
}
while (data < end);
*No = (double)countI;
}
#ifndef NO_FLAG
if (flag && (flag_anyISNAN != NULL)) *flag_anyISNAN = 1;
#endif
*s = sum;
}
inline int __sumskipnan3wer__(double *data, size_t Ni, double *s, double *s2, double *No, char *flag_anyISNAN, double *W)
{
double sum=0;
double msq=0;
char flag=0;
// LOOP along dimension DIM
double *end = data + stride*Ni;
if (W) {
// with weight vector
double count = 0.0;
double rc=0.0, rn=0.0, rq=0.0;
do {
double x = *data;
double t,y;
if (!isnan(x)) {
//count += *W; [1]
y = *W-rn;
t = count+y;
rn= (t-count)-y;
count= t;
double w = *W*x;
//sum += *W*x; [1]
y = *W*x-rc;
t = sum+y;
rc= (t-sum)-y;
sum= t;
// msq += x*w;
y = w*x-rq;
t = msq+y;
rq= (t-msq)-y;
msq= t;
}
#ifndef NO_FLAG
else
flag = 1;
#endif
data++; // stride=1
W++;
}
while (data < end);
*No = count;
} else {
// w/o weight vector
size_t countI = 0;
double rc=0.0, rq=0.0;
do {
double x = *data;
double t,y;
if (!isnan(x)) {
countI++;
//sum += x; [1]
y = x-rc;
t = sum+y;
rc= (t-sum)-y;
sum= t;
// msq += x*x;
y = x*x-rq;
t = msq+y;
rq= (t-msq)-y;
msq= t;
}
#ifndef NO_FLAG
else
flag = 1;
#endif
data++; // stride=1
}
while (data < end);
*No = (double)countI;
}
#ifndef NO_FLAG
if (flag && (flag_anyISNAN != NULL)) *flag_anyISNAN = 1;
#endif
*s = sum;
*s2 = msq;
}
tsa/VERSION 0000664 0023567 0023567 00000000137 12264575422 013137 0 ustar schloegl schloegl # TSA-toolbox http://pub.ist.ac.at/~schloegl/matlab/tsa
# Version: 4.2.7
# Date: 2014-01-12
tsa/DESCRIPTION 0000664 0023567 0023567 00000000451 12264575422 013574 0 ustar schloegl schloegl Name: TSA
Version: 4.2.7
Date: 2014-01-12
Author: Alois Schloegl
Maintainer: Alois Schloegl
Title: The TSA-toolbox
Description: A toolbox for Time Series Analysis .
Depends: octave (> 2.9.0)
License: GPL version 3 or later
Url: http://pub.ist.ac.at/~schloegl/matlab/tsa
tsa/INDEX 0000664 0023567 0023567 00000001273 10625373341 012656 0 ustar schloegl schloegl tsa >> Time Series Analysis
Univariate (stationary) analysis
acovf
acorf
biacovf
bispec
durlev
lattice
rmle
pacf
parcor
invest0
invest1
selmo
selmo2
histo
histo2
histo3
hup
ucp
y2res
ar_spa
detrend
flix
Multivariate stationary analysis
mvar
mvfilter
mvfreqz
arfit2
histo4
Adaptive (time-varying) analysis
aar
aarmam
adim
amarma
mvaar
Conversions between forms
ac2poly
ac2rc
ar2rc
rc2ar
poly2ac
poly2ar
poly2rc
rc2ac
rc2poly
ar2poly
Utility functions
arcext
sinvest1
sbispec
flag_implicit_samplerate
Test suites
tsademo
bisdemo
invfdemo
tsa/COPYING 0000664 0023567 0023567 00000104513 11441754133 013117 0 ustar schloegl schloegl GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
tsa/doc/ 0000775 0023567 0023567 00000000000 12264575422 012633 5 ustar schloegl schloegl tsa/doc/README.TXT 0000664 0023567 0023567 00000003753 12263773327 014204 0 ustar schloegl schloegl TSA (Time Series Analysis) Toolbox 4.2
=======================================
The TSA toolbox is useful for analysing Time Series.
The methods are based on stochastic concepts and
maximum entropy methods. The programs should be compatible
to Matlab as well as Octave.
It includes
- Stochastic Signal processing
- Autoregressive Model Identification
- adaptive autoregressive modelling using Kalman filtering
- multivariate autoregressive modelling
- maximum entropy spectral estimation
- matched (inverse) filter design
- Histogram analysis
- Calcution of the entropy of a time series
- Non-linear analysis (3rd order statistics)
- Test for UnitCircle- and Hurwitz- Polynomials
- multiple signal processing
- Several criteria (AIC, BIC, FPE, MDL, SBC, CAT, PHI) for
model order selection an autoregressive model are included.
- Fast algorithms are used
- missing values (encoded as NaN's) are considered
Furthermore includes the toolbox a fast version of the Yule-Walker method
for estimating Autoregressive parameters, Autocorrelation Function (ACF),
Partial autocorrelation (PARCOR), reflection coefficients and some
other useful staff. Demo programs can be started with "demo" or "demotsa".
% This library is free software; you can redistribute it and/or
% modify it under the terms of the GNU Library General Public
% License as published by the Free Software Foundation; either
% Version 3 of the License, or (at your option) any later version.
%
% This library 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
% Library General Public License for more details.
%
% You should have received a copy of the GNU Library General Public
% License along with this library; if not, see
% .
Copyright (C) 1996-2003,2010,2012,2014 by Alois Schloegl
E-Mail: alois.schloegl@ist.ac.at
WWW: http://pub.ist.ac.at/~schloegl/matlab/tsa/
tsa/inst/ 0000775 0023567 0023567 00000000000 12264575422 013043 5 ustar schloegl schloegl tsa/inst/mvfreqz.m 0000664 0023567 0023567 00000023417 12244747160 014720 0 ustar schloegl schloegl function [S,h,PDC,COH,DTF,DC,pCOH,dDTF,ffDTF, pCOH2, PDCF, coh,GGC,Af,GPDC,GGC2, DCOH]=mvfreqz(B,A,C,N,Fs)
% MVFREQZ multivariate frequency response
% [S,h,PDC,COH,DTF,DC,pCOH,dDTF,ffDTF,pCOH2,PDCF,coh,GGC,Af,GPDC,GGC2,DCOH] = mvfreqz(B,A,C,f,Fs)
% [...] = mvfreqz(B,A,C,N,Fs)
%
% INPUT:
% =======
% A, B multivariate polynomials defining the transfer function
%
% a0*Y(n) = b0*X(n) + b1*X(n-1) + ... + bq*X(n-q)
% - a1*Y(n-1) - ... - ap*Y(:,n-p)
%
% A=[a0,a1,a2,...,ap] and B=[b0,b1,b2,...,bq] must be matrices of
% size Mx((p+1)*M) and Mx((q+1)*M), respectively.
%
% C is the covariance of the input noise X (i.e. D'*D if D is the mixing matrix)
% N if scalar, N is the number of frequencies
% if N is a vector, N are the designated frequencies.
% Fs sampling rate [default 2*pi]
%
% A,B,C and D can by obtained from a multivariate time series
% through the following commands:
% [AR,RC,PE] = mvar(Y,P);
% M = size(AR,1); % number of channels
% A = [eye(M),-AR];
% B = eye(M);
% C = PE(:,M*P+1:M*(P+1));
%
% Fs sampling rate in [Hz]
% (N number of frequencies for computing the spectrum, this will become OBSOLETE),
% f vector of frequencies (in [Hz])
%
%
% OUTPUT:
% =======
% S power spectrum
% h transfer functions, abs(h.^2) is the non-normalized DTF [11]
% PDC partial directed coherence [2]
% DC directed coupling [13]
% COH coherency (complex coherence) [5]
% DTF directed transfer function [3,13]
% pCOH partial coherence
% dDTF direct Directed Transfer function
% ffDTF full frequency Directed Transfer Function
% pCOH2 partial coherence - alternative method
% GGC a modified version of Geweke's Granger Causality [Geweke 1982]
% !!! it uses a Multivariate AR model, and computes the bivariate GGC as in [Bressler et al 2007].
% This is not the same as using bivariate AR models and GGC as in [Bressler et al 2007]
% Af Frequency transform of A(z), abs(Af.^2) is the non-normalized PDC [11]
% PDCF Partial Directed Coherence Factor [2]
% GPDC Generalized Partial Directed Coherence [9,10]
% DCOH directed coherence or Generalized DTF (GDTF) [12] (equ. 11a)
%
% see also: FREQZ, MVFILTER, MVAR
%
% REFERENCE(S):
% [1] H. Liang et al. Neurocomputing, 32-33, pp.891-896, 2000.
% [2] L.A. Baccala and K. Samashima, Biol. Cybern. 84,463-474, 2001.
% [3] A. Korzeniewska, et al. Journal of Neuroscience Methods, 125, 195-207, 2003.
% [4] Piotr J. Franaszczuk, Ph.D. and Gregory K. Bergey, M.D.
% Fast Algorithm for Computation of Partial Coherences From Vector Autoregressive Model Coefficients
% World Congress 2000, Chicago.
% [5] Nolte G, Bai O, Wheaton L, Mari Z, Vorbach S, Hallett M.
% Identifying true brain interaction from EEG data using the imaginary part of coherency.
% Clin Neurophysiol. 2004 Oct;115(10):2292-307.
% [6] Schlogl A., Supp G.
% Analyzing event-related EEG data with multivariate autoregressive parameters.
% (Eds.) C. Neuper and W. Klimesch,
% Progress in Brain Research: Event-related Dynamics of Brain Oscillations.
% Analysis of dynamics of brain oscillations: methodological advances. Elsevier.
% Progress in Brain Research 159, 2006, p. 135 - 147
% [7] Bressler S.L., Richter C.G., Chen Y., Ding M. (2007)
% Cortical fuctional network organization from autoregressive modelling of loal field potential oscillations.
% Statistics in Medicine, doi: 10.1002/sim.2935
% [8] Geweke J., 1982
% J.Am.Stat.Assoc., 77, 304-313.
% [9] L.A. Baccala, D.Y. Takahashi, K. Sameshima. (2006)
% Generalized Partial Directed Coherence.
% Submitted to XVI Congresso Brasileiro de Automatica, Salvador, Bahia.
% [10] L.A. Baccala, D.Y. Takahashi, K. Sameshima.
% Computer Intensive Testing for the Influence Between Time Series,
% Eds. B. Schelter, M. Winterhalder, J. Timmer:
% Handbook of Time Series Analysis - Recent Theoretical Developments and Applications
% Wiley, p.413, 2006.
% [11] M. Eichler
% On the evaluation of informatino flow in multivariate systems by the directed transfer function
% Biol. Cybern. 94: 469-482, 2006.
% [12] L. Faes, S. Erla, and G. Nollo, (2012)
% Measuring Connectivity in Linear Multivariate Processes: Definitions, Interpretation, and Practical Analysis
% Computational and Mathematical Methods in Medicine Volume 2012 (2012), Article ID 140513, 18 pages
% doi:10.1155/2012/140513
% [13] Maciej Kaminski, Mingzhou Ding, Wilson A. Truccolo, Steven L. Bressler
% Evaluating causal relations in neural systems: Granger causality,
% directed transfer function and statistical assessment of significance.
% Biol. Cybern. 85, 145-157 (2001)
%
% $Id: mvfreqz.m 12366 2013-11-25 22:25:52Z schloegl $
% Copyright (C) 1996-2008 by Alois Schloegl
% Copyright (C) 2013 Martin Billinger
% This is part of the TSA-toolbox. See also
% http://pub.ist.ac.at/~schloegl/matlab/tsa/
% http://octave.sourceforge.net/
% http://biosig.sourceforge.net/
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program 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 this program. If not, see .
[K1,K2] = size(A);
p = K2/K1-1;
%a=ones(1,p+1);
[K1,K2] = size(B);
q = K2/K1-1;
%b=ones(1,q+1);
if nargin<3
C = eye(K1,K1);
end;
if nargin<5,
Fs= 1;
end;
if nargin<4,
N = 512;
f = (0:N-1)*(Fs/(2*N));
end;
if all(size(N)==1),
fprintf(1,'Warning MVFREQZ: The forth input argument N is a scalar, this is ambigous.\n');
fprintf(1,' In the past, N was used to indicate the number of spectral lines. This might change.\n');
fprintf(1,' In future versions, it will indicate the spectral line.\n');
f = (0:N-1)*(Fs/(2*N));
else
f = N;
end;
N = length(f);
s = exp(i*2*pi*f/Fs);
z = i*2*pi/Fs;
h=zeros(K1,K1,N);
Af=zeros(K1,K1,N);
g=zeros(K1,K1,N);
S=zeros(K1,K1,N);
S1=zeros(K1,K1,N);
DTF=zeros(K1,K1,N);
COH=zeros(K1,K1,N);
%COH2=zeros(K1,K1,N);
PDC=zeros(K1,K1,N);
%PDC3=zeros(K1,K1,N);
PDCF = zeros(K1,K1,N);
pCOH = zeros(K1,K1,N);
GGC=zeros(K1,K1,N);
GGC2=zeros(K1,K1,N);
DCOH=zeros(K1,K1,N);
invC=inv(C);
tmp1=zeros(1,K1);
tmp2=zeros(1,K1);
M = zeros(K1,K1,N);
detG = zeros(N,1);
%D = sqrtm(C);
%iD= inv(D);
ddc2 = diag(diag(C).^(-1/2));
ddc2i = diag(diag(C).^(1/2));
for n=1:N,
atmp = zeros(K1);
for k = 1:p+1,
atmp = atmp + A(:,k*K1+(1-K1:0))*exp(z*(k-1)*f(n));
end;
% compensation of instantaneous correlation
% atmp = iD*atmp*D;
btmp = zeros(K1);
for k = 1:q+1,
btmp = btmp + B(:,k*K1+(1-K1:0))*exp(z*(k-1)*f(n));
end;
h(:,:,n) = atmp\btmp;
Af(:,:,n) = atmp/btmp;
S(:,:,n) = h(:,:,n)*C*h(:,:,n)'/Fs;
S1(:,:,n) = h(:,:,n)*h(:,:,n)';
ctmp = ddc2*atmp; %% used for GPDC
dtmp = h(:,:,n) * ddc2i; %% used for directed coherence (DCOH)
for k1 = 1:K1,
tmp = squeeze(atmp(:,k1));
tmp1(k1) = sqrt(tmp'*tmp);
tmp2(k1) = sqrt(tmp'*invC*tmp);
%tmp = squeeze(atmp(k1,:)');
%tmp3(k1) = sqrt(tmp'*tmp);
tmp = squeeze(ctmp(:,k1));
tmp3(k1) = sqrt(tmp'*tmp);
tmp = dtmp(k1,:);
tmp4(k1) = sqrt(tmp*tmp');
end;
PDCF(:,:,n) = abs(atmp)./tmp2(ones(1,K1),:);
PDC(:,:,n) = abs(atmp)./tmp1(ones(1,K1),:);
GPDC(:,:,n) = abs(ctmp)./tmp3(ones(1,K1),:);
%PDC3(:,:,n) = abs(atmp)./tmp3(:,ones(1,K1));
DCOH(:,:,n) = abs(dtmp) ./ tmp4(ones(1,K1),:)';
g = atmp/btmp;
G(:,:,n) = g'*invC*g;
detG(n) = det(G(:,:,n));
end;
if nargout<4, return; end;
%%%%% directed transfer function
for k1=1:K1;
DEN=sum(abs(h(k1,:,:)).^2,2);
for k2=1:K2;
%COH2(k1,k2,:) = abs(S(k1,k2,:).^2)./(abs(S(k1,k1,:).*S(k2,k2,:)));
COH(k1,k2,:) = (S(k1,k2,:))./sqrt(abs(S(k1,k1,:).*S(k2,k2,:)));
coh(k1,k2,:) = (S1(k1,k2,:))./sqrt(abs(S1(k1,k1,:).*S1(k2,k2,:)));
%DTF(k1,k2,:) = sqrt(abs(h(k1,k2,:).^2))./DEN;
DTF(k1,k2,:) = abs(h(k1,k2,:))./sqrt(DEN);
ffDTF(k1,k2,:) = abs(h(k1,k2,:))./sqrt(sum(DEN,3));
pCOH2(k1,k2,:) = abs(G(k1,k2,:).^2)./(G(k1,k1,:).*G(k2,k2,:));
%M(k2,k1,:) = ((-1)^(k1+k2))*squeeze(G(k1,k2,:))./detG; % oder ist M = G?
end;
end;
dDTF = pCOH2.*ffDTF;
if nargout<6, return; end;
DC = zeros(K1);
for k = 1:p,
DC = DC + A(:,k*K1+(1:K1)).^2;
end;
if nargout<13, return; end;
for k1=1:K1;
for k2=1:K2;
% Bivariate Granger Causality (similar to Bressler et al. 2007. )
GGC(k1,k2,:) = ((C(k1,k1)*C(k2,k2)-C(k1,k2)^2)/C(k2,k2))*real(h(k1,k2,:).*conj(h(k1,k2,:)))./abs(S(k2,k2,:));
%GGC2(k1,k2,:) = -log(1-((C(k1,k1)*C(k2,k2)-C(k1,k2)^2)/C(k2,k2))*real(h(k1,k2,:).*conj(h(k1,k2,:)))./S(k2,k2,:));
end;
end;
return;
if nargout<7, return; end;
for k1=1:K1;
for k2=1:K2;
M(k2,k1,:) = ((-1)^(k1+k2))*squeeze(G(k1,k2,:))./detG; % oder ist M = G?
end;
end;
for k1=1:K1;
for k2=1:K2;
pCOH(k1,k2,:) = abs(M(k1,k2,:).^2)./(M(k1,k1,:).*M(k2,k2,:));
end;
end;
tsa/inst/invest1.m 0000664 0023567 0023567 00000010746 12115040716 014606 0 ustar schloegl schloegl function [AutoCov,AutoCorr,ARPMX,E,C,s]=invest1(Y,Pmax,D);
% First Investigation of a signal (time series) - interactive
% [AutoCov,AutoCorr,ARPMX,E,CRITERIA,MOPS]=invest1(Y,Pmax,show);
%
% Y time series
% Pmax maximal order (optional)
% show optional; if given the parameters are shown
%
% AutoCov Autocorrelation
% AutoCorr normalized Autocorrelation
% PartACF Partial Autocorrelation
% E Error function E(p)
% CRITERIA curves of the various (see below) criteria,
% MOPS=[optFPE optAIC optBIC optSBC optMDL optCAT optPHI];
% optimal model order according to various criteria
%
% FPE Final Prediction Error (Kay, 1987)
% AIC Akaike Information Criterion (Marple, 1987)
% BIC Bayesian Akaike Information Criterion (Wei, 1994)
% SBC Schwartz's Bayesian Criterion (Wei, 1994)
% MDL Minimal Description length Criterion (Marple, 1987)
% CAT Parzen's CAT Criterion (Wei, 1994)
% PHI Phi criterion (Pukkila et al. 1988)
% minE order where E is minimal
%
% REFERENCES:
% P.J. Brockwell and R.A. Davis "Time Series: Theory and Methods", 2nd ed. Springer, 1991.
% S. Haykin "Adaptive Filter Theory" 3ed. Prentice Hall, 1996.
% M.B. Priestley "Spectral Analysis and Time Series" Academic Press, 1981.
% C.E. Shannon and W. Weaver "The mathematical theory of communication" University of Illinois Press, Urbana 1949 (reprint 1963).
% W.S. Wei "Time Series Analysis" Addison Wesley, 1990.
% optFPE order where FPE is minimal
% optAIC order where AIC is minimal
% optBIC order where BIC is minimal
% optSBC order where SBC is minimal
% optMDL order where MDL is minimal
% optCAT order where CAT is minimal
% optPHI order where PHI is minimal
% optRC2 max reflection coefficient larger than std-error
% $Id: invest1.m 11693 2013-03-04 06:40:14Z schloegl $
% Copyright (C) 1998-2002,2008,2010 by Alois Schloegl
% This is part of the TSA-toolbox. See also
% http://biosig-consulting.com/matlab/tsa/
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program 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 this program. If not, see .
N=length(Y);
[nr,nc]=size(Y);
if nc==1 Y=transpose(Y); nc=nr; nr=1; end;
if nargin<2 Pmax=min([100 nc/3]); end;
if exist('OCTAVE_VERSION'),
fprintf(2,'Warning INVEST1: DIFF-based optimization not possible\n');
%%% missing DIM-argument in DIFF.M
else
%tmp=Y-mean(Y,2)*ones(1,nc);
RMS(:,1) = mean(Y.^2,2);
Dmax = min(Pmax,5);
for k = 1:Dmax,
RMS(:,k+1) = mean(diff(Y,k,2).^2,2);
end;
[tmp, orderDIFF] = min(RMS,[],2);
% show a nice histogram
h = histo3(orderDIFF-1);
X = 0:Dmax; H = zeros(1,Dmax+1); for k=1:length(h.X), H(find(X==h.X(k)))=h.H(k); end;
%X = 0:Dmax; H = zeros(1,Dmax+1); for k=1:length(x), H(find(X==x(k)))=h(k); end;
bar(X,H);
drawnow;
if nargin>2
oD=0;
else
oD=input('Which order should be used for differentiating [default=0] ?: ');
end;
if oD>0
Y=diff(Y,oD,2);
end;
end;
[AutoCov, AutoCorr, ARPMX, E, NC] = invest0(Y,Pmax);
[FPE,AIC,BIC,SBC,MDL,CATcrit,PHI,optFPE,optAIC,optBIC,optSBC,optMDL,optCAT,optPHI,s,C] = selmo(E,NC);
if 0,
optRC2=zeros(nr+1,1);
for k=0:nr,
if k>0
optRC2(k+1)=max(find(abs(ARPMX(k,(1:Pmax).*(2:Pmax+1)/2))*sqrt(size(Y,2))>1));
else
optRC2(k+1)=max(find(mean(abs(ARPMX(:,(1:Pmax).*(2:Pmax+1)/2))*sqrt(size(Y,2)),2)>1));
end;
end;
%GERSCH=min(find(rc.^2<(0.05/1.05)));
s=[s optRC2];
end;
%CRITERIA=([FPE;AIC;BIC;SBC;MDL;CATcrit;PHI])';
MOPS = s(1:size(s,1),:); %[optFPE optAIC optBIC optSBC optMDL optCAT optPHI];
if nargin==3,
if size(ARPMX,2)==2*Pmax,
%invest1(eeg8s,30,'s');
AR=ARPMX(:,1:Pmax);
RC=ARPMX(:,Pmax+1:2*Pmax);
else
AR=ARPMX(:,Pmax/2*(Pmax-1)+(1:Pmax));
RC=ARPMX(:,(1:Pmax).*(2:Pmax+1)/2);
end;
oo=optBIC;
sinvest1;
end;
tsa/inst/histo.m 0000664 0023567 0023567 00000004223 12115040716 014334 0 ustar schloegl schloegl function [H,X]=histo(Y,Mode)
% HISTO calculates histogram for each column
% [H,X] = HISTO(Y,Mode)
%
% Mode
% 'rows' : frequency of each row
% '1x' : single bin-values
% 'nx' : separate bin-values for each column
% X are the bin-values
% H is the frequency of occurence of value X
%
% HISTO(Y) with no output arguments:
% plots the histogram bar(X,H)
%
% more histogram-based results can be obtained by HIST2RES2
%
% see also: HISTO, HISTO2, HISTO3, HISTO4
%
% REFERENCE(S):
% C.E. Shannon and W. Weaver "The mathematical theory of communication" University of Illinois Press, Urbana 1949 (reprint 1963).
% $Id: histo.m 11693 2013-03-04 06:40:14Z schloegl $
% Copyright (C) 1996-2002,2008 by Alois Schloegl
% This is part of the TSA-toolbox
% http://pub.ist.ac.at/~schloegl/matlab/tsa/
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program 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 this program. If not, see .
if nargin<2,
Mode='1x';
end;
Mode=lower(Mode);
if strcmp(Mode,'rows')
R = histo4(Y);
elseif strcmp(Mode,'column')
R = histo4(Y');
R.X = R.X';
elseif strcmp(Mode,'1x')
R = histo3(Y);
elseif strcmp(Mode,'nx')
R = histo2(Y);
end;
H = R.H;
X = R.X;
if nargout == 0,
if any(size(X)==1),
if exist('OCTAVE_VERSION')<5,
bar(R.X,R.H,'stacked');
else
bar(R.X,R.H);
end
else
warning('2-dim X-values not supported\n')
%bar3(R.X,R.H);
end;
end;
tsa/inst/durlev.m 0000664 0023567 0023567 00000010442 12115040716 014507 0 ustar schloegl schloegl function [MX,res,arg3] = durlev(AutoCov);
% function [AR,RC,PE] = durlev(ACF);
% function [MX,PE] = durlev(ACF);
% estimates AR(p) model parameter by solving the
% Yule-Walker with the Durbin-Levinson recursion
% for multiple channels
% INPUT:
% ACF Autocorrelation function from lag=[0:p]
%
% OUTPUT
% AR autoregressive model parameter
% RC reflection coefficients (= -PARCOR coefficients)
% PE remaining error variance
% MX transformation matrix between ARP and RC (Attention: needs O(p^2) memory)
% AR(:,K) = MX(:,K*(K-1)/2+(1:K));
% RC(:,K) = MX(:,(1:K).*(2:K+1)/2);
%
% All input and output parameters are organized in rows, one row
% corresponds to the parameters of one channel
%
% see also ACOVF ACORF AR2RC RC2AR LATTICE
%
% REFERENCES:
% Levinson N. (1947) "The Wiener RMS(root-mean-square) error criterion in filter design and prediction." J. Math. Phys., 25, pp.261-278.
% Durbin J. (1960) "The fitting of time series models." Rev. Int. Stat. Inst. vol 28., pp 233-244.
% P.J. Brockwell and R. A. Davis "Time Series: Theory and Methods", 2nd ed. Springer, 1991.
% S. Haykin "Adaptive Filter Theory" 3rd ed. Prentice Hall, 1996.
% M.B. Priestley "Spectral Analysis and Time Series" Academic Press, 1981.
% W.S. Wei "Time Series Analysis" Addison Wesley, 1990.
% $Id: durlev.m 11693 2013-03-04 06:40:14Z schloegl $
% Copyright (C) 1998-2002,2008 by Alois Schloegl
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program 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 this program. If not, see .
% Inititialization
[lr,lc]=size(AutoCov);
res=[AutoCov(:,1), zeros(lr,lc-1)];
d=zeros(lr,1);
if nargout<3 % needs O(p^2) memory
MX=zeros(lr,lc*(lc-1)/2);
idx=0;
idx1=0;
% Durbin-Levinson Algorithm
for K=1:lc-1,
%idx=K*(K-1)/2; %see below
% for L=1:lr, d(L)=arp(L,1:K-1)*transpose(AutoCov(L,K:-1:2));end; % Matlab 4.x, Octave
% d=sum(MX(:,idx+(1:K-1)).*AutoCov(:,K:-1:2),2); % Matlab 5.x
MX(:,idx+K)=(AutoCov(:,K+1)-sum(MX(:,idx1+(1:K-1)).*AutoCov(:,K:-1:2),2))./res(:,K);
%rc(:,K)=arp(:,K);
%if K>1 %for compatibility with OCTAVE 2.0.13
MX(:,idx+(1:K-1))=MX(:,idx1+(1:K-1))-MX(:,(idx+K)*ones(K-1,1)).*MX(:,idx1+(K-1:-1:1));
%end;
% for L=1:lr, d(L)=MX(L,idx+(1:K))*(AutoCov(L,K+1:-1:2).');end; % Matlab 4.x, Octave
% d=sum(MX(:,idx+(1:K)).*AutoCov(:,K+1:-1:2),2); % Matlab 5.x
res(:,K+1) = res(:,K).*(1-abs(MX(:,idx+K)).^2);
idx1=idx;
idx=idx+K;
end;
%arp=MX(:,K*(K-1)/2+(1:K));
%rc =MX(:,(1:K).*(2:K+1)/2);
else % needs O(p) memory
arp=zeros(lr,lc-1);
rc=zeros(lr,lc-1);
% Durbin-Levinson Algorithm
for K=1:lc-1,
% for L=1:lr, d(L)=arp(L,1:K-1)*transpose(AutoCov(L,K:-1:2));end; % Matlab 4.x, Octave
% d=sum(arp(:,1:K-1).*AutoCov(:,K:-1:2),2); % Matlab 5.x
arp(:,K) = (AutoCov(:,K+1)-sum(arp(:,1:K-1).*AutoCov(:,K:-1:2),2))./res(:,K); % Yule-Walker
rc(:,K) = arp(:,K);
%if K>1 %for compatibility with OCTAVE 2.0.13
arp(:,1:K-1)=arp(:,1:K-1)-arp(:,K*ones(K-1,1)).*arp(:,K-1:-1:1);
%end;
%for L=1:lr, d(L)=arp(L,1:K)*(AutoCov(L,K+1:-1:2).');end; % Matlab 4.x, Octave
% d=sum(arp(:,1:K).*AutoCov(:,K+1:-1:2),2); % Matlab 5.x
res(:,K+1) = res(:,K).*(1-abs(arp(:,K)).^2);
end;
% assign output arguments
arg3=res;
res=rc;
MX=arp;
end; %if
tsa/inst/ar2rc.m 0000664 0023567 0023567 00000006062 12115040716 014222 0 ustar schloegl schloegl function [MX,res,arg3] = ar2rc(ar);
% converts autoregressive parameters into reflection coefficients
% with the Durbin-Levinson recursion for multiple channels
% function [AR,RC,PE] = ar2rc(AR);
% function [MX,PE] = ar2rc(AR);
%
% INPUT:
% AR autoregressive model parameter
%
% OUTPUT
% AR autoregressive model parameter
% RC reflection coefficients (= -PARCOR coefficients)
% PE remaining error variance (relative to PE(1)=1)
% MX transformation matrix between ARP and RC (Attention: needs O(p^2) memory)
% AR = MX(:,K*(K-1)/2+(1:K));
% RC = MX(:,(1:K).*(2:K+1)/2);
%
% All input and output parameters are organized in rows, one row
% corresponds to the parameters of one channel
%
% see also ACOVF ACORF DURLEV RC2AR
%
% REFERENCES:
% P.J. Brockwell and R. A. Davis "Time Series: Theory and Methods", 2nd ed. Springer, 1991.
% S. Haykin "Adaptive Filter Theory" 3rd ed. Prentice Hall, 1996.
% M.B. Priestley "Spectral Analysis and Time Series" Academic Press, 1981.
% W.S. Wei "Time Series Analysis" Addison Wesley, 1990.
% $Id: ar2rc.m 11693 2013-03-04 06:40:14Z schloegl $
% Copyright (C) 1998-2002,2008 by Alois Schloegl
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program 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 this program. If not, see .
% Inititialization
[lr,lc]=size(ar);
res=[ones(lr,1) zeros(lr,lc)];
if nargout<3 % needs O(p^2) memory
MX=zeros(lr,lc*(lc+1)/2);
MX(:,lc*(lc-1)/2+(1:lc))=ar;
% Durbin-Levinson Algorithm
idx=lc*(lc-1)/2;
for K=lc:-1:2;
%idx=K*(K-1)/2; %see below
MX(:,(K-2)*(K-1)/2+(1:K-1)) = (MX(:,idx+(1:K-1)) + MX(:,(idx+K)*ones(K-1,1)).*MX(:,idx+(K-1:-1:1)))./((ones(lr,1)-abs(MX(:,idx+K)).^2)*ones(1,K-1));
idx=idx-K+1;
end;
for K=1:lc
idx=K*(K-1)/2; %see below
res(:,K+1) = res(:,K).*(1-abs(MX(:,idx+K)).^2);
end;
%arp=MX(:,K*(K-1)/2+(1:K));
%rc =MX(:,(1:K).*(2:K+1)/2);
else % needs O(p) memory
%ar=zeros(lr,lc);
rc=zeros(lr,lc);
rc(:,lc)=ar(:,lc);
MX=ar; % assign output
% Durbin-Levinson Algorithm
for K=lc-1:-1:1,
ar(:,1:K)=(ar(:,1:K)+ar(:,(K+1)*ones(K,1)).*ar(:,K:-1:1))./((ones(lr,1)-abs(ar(:,K+1)).^2)*ones(1,K));
rc(:,K)=ar(:,K);
end;
for K=1:lc,
res(:,K+1) = res(:,K) .* (1-abs(ar(:,K)).^2);
end;
% assign output arguments
arg3=res;
res=rc;
%MX=ar;
end; %if
tsa/inst/rc2ar.m 0000664 0023567 0023567 00000006517 12115040716 014227 0 ustar schloegl schloegl function [MX,res,arg3,acf] = rc2ar(rc);
% converts reflection coefficients into autoregressive parameters
% uses the Durbin-Levinson recursion for multiple channels
% function [AR,RC,PE,ACF] = rc2ar(RC);
% function [MX,PE] = rc2ar(RC);
%
% INPUT:
% RC reflection coefficients
%
% OUTPUT
% AR autoregressive model parameter
% RC reflection coefficients (= -PARCOR coefficients)
% PE remaining error variance (relative to PE(1)=1)
% MX transformation matrix between ARP and RC (Attention: needs O(p^2) memory)
% arp=MX(:,K*(K-1)/2+(1:K));
% rc =MX(:,(1:K).*(2:K+1)/2);
%
% All input and output parameters are organized in rows, one row
% corresponds to the parameters of one channel
%
% see also ACOVF ACORF DURLEV AR2RC
%
% REFERENCES:
% P.J. Brockwell and R. A. Davis "Time Series: Theory and Methods", 2nd ed. Springer, 1991.
% S. Haykin "Adaptive Filter Theory" 3rd ed. Prentice Hall, 1996.
% M.B. Priestley "Spectral Analysis and Time Series" Academic Press, 1981.
% W.S. Wei "Time Series Analysis" Addison Wesley, 1990.
% $Id: rc2ar.m 11693 2013-03-04 06:40:14Z schloegl $
% Copyright (c) 1996-2002,2007,2008 by Alois Schloegl
% This function is part of the TSA-toolbox
% http://pub.ist.ac.at/~schloegl/matlab/tsa/
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program 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 this program. If not, see .
% Inititialization
[lr,lc]=size(rc);
res=[ones(lr,1) zeros(lr,lc)];
if nargout<3 % needs O(p^2) memory
MX=zeros(lr,lc*(lc+1)/2);
idx=0;
% Durbin-Levinson Algorithm
for K=1:lc,
MX(:,idx+K)=rc(:,K);%(AutoCov(:,K+1)-d)./res(:,K);
%rc(:,K)=arp(:,K);
if K>1 %for compatibility with OCTAVE 2.0.13
MX(:,idx+(1:K-1))=MX(:,(K-2)*(K-1)/2+(1:K-1))-MX(:,(idx+K)*ones(K-1,1)).*MX(:,(K-2)*(K-1)/2+(K-1:-1:1));
end;
res(:,K+1) = res(:,K).*(1-abs(MX(:,idx+K)).^2);
idx=idx+K;
end;
%arp=MX(:,K*(K-1)/2+(1:K));
%rc =MX(:,(1:K).*(2:K+1)/2);
ACF=cumprod(ones(lr,lr)-rc.^2,2);
else % needs O(p) memory
ar=zeros(lr,lc);
acf=[ones(lr,1),zeros(lr,lc)];
%rc=RC; %zeros(lr,lc-1);
% Durbin-Levinson Algorithm
for K=1:lc,
acf(:,K) = -sum(acf(:,K:-1:1).*ar(:,1:K),2);
ar(:,K) = rc(:,K);
if K>1, %for compatibility with OCTAVE 2.0.13
ar(:,1:K-1) = ar(:,1:K-1) - ar(:,K*ones(K-1,1)) .* ar(:,K-1:-1:1);
end;
res(:,K+1) = res(:,K) .* (1-abs(ar(:,K)).^2);
end;
ACF=cumprod(ones(lr,lc)-rc.^2,2);
% assign output arguments
arg3=res;
res=rc;
MX=ar;
end; %if
tsa/inst/aar.m 0000664 0023567 0023567 00000026127 12115040716 013760 0 ustar schloegl schloegl function [a,e,REV,TOC,CPUTIME,ESU] = aar(y, Mode, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
% Calculates adaptive autoregressive (AAR) and adaptive autoregressive moving average estimates (AARMA)
% of real-valued data series using Kalman filter algorithm.
% [a,e,REV] = aar(y, mode, MOP, UC, a0, A, W, V);
%
% The AAR process is described as following
% y(k) - a(k,1)*y(t-1) -...- a(k,p)*y(t-p) = e(k);
% The AARMA process is described as following
% y(k) - a(k,1)*y(t-1) -...- a(k,p)*y(t-p) = e(k) + b(k,1)*e(t-1) + ... + b(k,q)*e(t-q);
%
% Input:
% y Signal (AR-Process)
% Mode is a two-element vector [aMode, vMode],
% aMode determines 1 (out of 12) methods for updating the co-variance matrix (see also [1])
% vMode determines 1 (out of 7) methods for estimating the innovation variance (see also [1])
% aMode=1, vmode=2 is the RLS algorithm as used in [2]
% aMode=-1, LMS algorithm (signal normalized)
% aMode=-2, LMS algorithm with adaptive normalization
%
% MOP model order, default [10,0]
% MOP=[p] AAR(p) model. p AR parameters
% MOP=[p,q] AARMA(p,q) model, p AR parameters and q MA coefficients
% UC Update Coefficient, default 0
% a0 Initial AAR parameters [a(0,1), a(0,2), ..., a(0,p),b(0,1),b(0,2), ..., b(0,q)]
% (row vector with p+q elements, default zeros(1,p) )
% A Initial Covariance matrix (positive definite pxp-matrix, default eye(p))
% W system noise (required for aMode==0)
% V observation noise (required for vMode==0)
%
% Output:
% a AAR(MA) estimates [a(k,1), a(k,2), ..., a(k,p),b(k,1),b(k,2), ..., b(k,q]
% e error process (Adaptively filtered process)
% REV relative error variance MSE/MSY
%
%
% Hint:
% The mean square (prediction) error of different variants is useful for determining the free parameters (Mode, MOP, UC)
%
% REFERENCE(S):
% [1] A. Schloegl (2000), The electroencephalogram and the adaptive autoregressive model: theory and applications.
% ISBN 3-8265-7640-3 Shaker Verlag, Aachen, Germany.
%
% More references can be found at
% http://pub.ist.ac.at/~schloegl/publications/
%
% $Id: aar.m 11693 2013-03-04 06:40:14Z schloegl $
% Copyright (C) 1998-2003 by Alois Schloegl
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program 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 this program. If not, see .
[nc,nr]=size(y);
%if nc=2 p=MOP(1); q=MOP(2); MOP=p+q;
end;
if nargin<4 UC=0; else UC= arg4; end;
a0=zeros(1,MOP);
A0=eye(MOP);
if nargin>4,
if all(size(arg5)==([1,1]*(MOP+1))); % extended covariance matrix of AAR parameters
a0 = arg5(1,2:size(arg5,2));
A0 = arg5(2:size(arg5,1),2:size(arg5,2)) - a0'*a0;
else
a0 = arg5;
if nargin>5
A0 = arg6;
end;
end;
end;
if nargin<7, W = []; else W = arg7; end;
if all(size(W)==MOP),
if aMode ~= 0,
fprintf(1,'aMode should be 0, because W is given.\n');
end;
elseif isempty(W),
if aMode == 0,
fprintf(1,'aMode must be non-zero, because W is not given.\n');
end;
elseif any(size(W)~=MOP),
fprintf(1,'size of W does not fit. It must be %i x %i.\n',MOP,MOP);
return;
end;
if nargin<8, V0 = []; else V0 = arg8; end;
if all(size(V0)==nr),
if vMode ~= 0,
fprintf(1,'vMode should be 0, because V is given.\n');
end;
elseif isempty(V0),
if aMode == 0,
fprintf(1,'vMode must be non-zero, because V is not given.\n');
end;
else
fprintf(1,'size of V does not fit. It must be 1x1.\n');
return;
end;
% if nargin<7 TH=3; else TH = arg7; end;
% TH=TH*var(y);
% TH=TH*mean(detrend(y,0).^2);
MSY=mean(detrend(y,0).^2);
e=zeros(nc,1);
Q=zeros(nc,1);
V=zeros(nc,1);
T=zeros(nc,1);
%DET=zeros(nc,1);
SPUR=zeros(nc,1);
ESU=zeros(nc,1);
a=a0(ones(nc,1),:);
%a=zeros(nc,MOP);
%b=zeros(nc,q);
mu=1-UC; % Patomaeki 1995
lambda=(1-UC); % Schloegl 1996
arc=poly((1-UC*2)*[1;1]);b0=sum(arc); % Whale forgettting factor for Mode=258,(Bianci et al. 1997)
dW=UC/MOP*eye(MOP); % Schloegl
%------------------------------------------------
% First Iteration
%------------------------------------------------
Y=zeros(MOP,1);
C=zeros(MOP);
%X=zeros(q,1);
at=a0;
A=A0;
E=y(1);
e(1)=E;
if ~isempty(V0)
V(1) = V0;
else
V(1) = (1-UC) + UC*E*E;
end;
ESU(1) = 1; %Y'*A*Y;
A1=zeros(MOP);A2=A1;
tic;CPUTIME=cputime;
%------------------------------------------------
% Update Equations
%------------------------------------------------
T0=2;
for t=T0:nc,
%Y=[y(t-1); Y(1:p-1); E ; Y(p+1:MOP-1)]
if t<=p Y(1:t-1)=y(t-1:-1:1); % Autoregressive
else Y(1:p)=y(t-1:-1:t-p);
end;
if t<=q Y(p+(1:t-1))=e(t-1:-1:1); % Moving Average
else Y(p+1:MOP)=e(t-1:-1:t-q);
end;
% Prediction Error
E = y(t) - a(t-1,:)*Y;
e(t) = E;
E2=E*E;
AY=A*Y;
esu=Y'*AY;
ESU(t)=esu;
if isnan(E),
a(t,:)=a(t-1,:);
else
V(t) = V(t-1)*(1-UC)+UC*E2;
if aMode == -1, % LMS
% V(t) = V(t-1)*(1-UC)+UC*E2;
a(t,:)=a(t-1,:) + (UC/MSY)*E*Y';
elseif aMode == -2, % LMS with adaptive estimation of the variance
a(t,:)=a(t-1,:) + UC/V(t)*E*Y';
else % Kalman filtering (including RLS)
if vMode==0, %eMode==4
Q(t) = (esu + V0);
elseif vMode==1, %eMode==4
Q(t) = (esu + V(t));
elseif vMode==2, %eMode==2
Q(t) = (esu + 1);
elseif vMode==3, %eMode==3
Q(t) = (esu + lambda);
elseif vMode==4, %eMode==1
Q(t) = (esu + V(t-1));
elseif vMode==5, %eMode==6
if E2>esu
V(t)=(1-UC)*V(t-1)+UC*(E2-esu);
else
V(t)=V(t-1);
end;
Q(t) = (esu + V(t));
elseif vMode==6, %eMode==7
if E2>esu
V(t)=(1-UC)*V(t-1)+UC*(E2-esu);
else
V(t)=V(t-1);
end;
Q(t) = (esu + V(t-1));
elseif vMode==7, %eMode==8
Q(t) = esu;
end;
k = AY / Q(t); % Kalman Gain
a(t,:) = a(t-1,:) + k'*E;
if aMode==0, %AMode=0
A = A - k*AY' + W; % Schloegl et al. 2003
elseif aMode==1, %AMode=1
A = (1+UC)*(A - k*AY'); % Schloegl et al. 1997
elseif aMode==2, %AMode=11
A = A - k*AY';
A = A + sum(diag(A))*dW;
elseif aMode==3, %AMode=5
A = A - k*AY' + sum(diag(A))*dW;
elseif aMode==4, %AMode=6
A = A - k*AY' + UC*eye(MOP); % Schloegl 1998
elseif aMode==5, %AMode=2
A = A - k*AY' + UC*UC*eye(MOP);
elseif aMode==6, %AMode=2
T(t)=(1-UC)*T(t-1)+UC*(E2-Q(t))/(Y'*Y);
A=A*V(t-1)/Q(t);
if T(t)>0 A=A+T(t)*eye(MOP); end;
elseif aMode==7, %AMode=6
T(t)=(1-UC)*T(t-1)+UC*(E2-Q(t))/(Y'*Y);
A=A*V(t)/Q(t);
if T(t)>0 A=A+T(t)*eye(MOP); end;
elseif aMode==8, %AMode=5
Q_wo = (Y'*C*Y + V(t-1));
C=A-k*AY';
T(t)=(1-UC)*T(t-1)+UC*(E2-Q_wo)/(Y'*Y);
if T(t)>0 A=C+T(t)*eye(MOP); else A=C; end;
elseif aMode==9, %AMode=3
A = A - (1+UC)*k*AY';
A = A + sum(diag(A))*dW;
elseif aMode==10, %AMode=7
A = A - (1+UC)*k*AY' + sum(diag(A))*dW;
elseif aMode==11, %AMode=8
A = A - (1+UC)*k*AY' + UC*eye(MOP); % Schloegl 1998
elseif aMode==12, %AMode=4
A = A - (1+UC)*k*AY' + UC*UC*eye(MOP);
elseif aMode==13
A = A - k*AY' + UC*diag(diag(A));
elseif aMode==14
A = A - k*AY' + (UC*UC)*diag(diag(A));
end;
end;
end;
end;
%a=a(end,:);
TOC = toc;
CPUTIME = cputime - CPUTIME;
%REV = (e'*e)/(y'*y);
REV = mean(e.*e)./mean(y.*y);
tsa/inst/ar_spa.m 0000664 0023567 0023567 00000007332 12115040716 014457 0 ustar schloegl schloegl function [w,A,B,R,P,F,ip] = ar_spa(ARP,nhz,E);
% AR_SPA decomposes an AR-spectrum into its compontents
% [w,A,B,R,P,F,ip] = ar_spa(AR,fs,E);
%
% INPUT:
% AR autoregressive parameters
% fs sampling rate, provide w and B in [Hz], if not given the result is in radians
% E noise level (mean square), gives A and F in units of E, if not given as relative amplitude
%
% OUTPUT
% w center frequency
% A Amplitude
% B bandwidth
% - less important output parameters -
% R residual
% P poles
% ip number of complex conjugate poles
% real(F) power, absolute values are obtained by multiplying with noise variance E(p+1)
% imag(F) assymetry, - " -
%
% All input and output parameters are organized in rows, one row
% corresponds to the parameters of one channel
%
% see also ACOVF ACORF DURLEV IDURLEV PARCOR YUWA
%
% REFERENCES:
% [1] Zetterberg L.H. (1969) Estimation of parameter for linear difference equation with application to EEG analysis. Math. Biosci., 5, 227-275.
% [2] Isaksson A. and Wennberg, A. (1975) Visual evaluation and computer analysis of the EEG - A comparison. Electroenceph. clin. Neurophysiol., 38: 79-86.
% [3] G. Florian and G. Pfurtscheller (1994) Autoregressive model based spectral analysis with application to EEG. IIG - Report Series, University of Technolgy Graz, Austria.
% $Id: ar_spa.m 11693 2013-03-04 06:40:14Z schloegl $
% Copyright (C) 1996-2003 by Alois Schloegl
% This is part of the TSA-toolbox see also:
% http://pub.ist.ac.at/~schloegl/matlab/tsa/
% http://octave.sf.net/
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program 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 this program. If not, see .
[NTR,pp]=size(ARP);
R=zeros(size(ARP));
P=zeros(size(ARP));
w=zeros(size(ARP));
A=zeros(size(ARP));
B=zeros(size(ARP));
F=zeros(size(ARP));
F1 = F;
for k = 1:NTR, %if ~mod(k,100),k, end;
[r,p,tmp] = residue(1,[1 -ARP(k,:)]);
[tmp,idx] = sort(-abs(r));
R(k,:) = r(idx)'; % Residual,
P(k,:) = p(idx)'; % Poles
%r(k,:)=roots([1 -ARP(k,:)])';
w(k,:) = angle(p(idx)'); % center frequency (in [radians])
A(k,:) = 1./abs(polyval([1 -ARP(k,:)],exp(i*w(k,:)))); % Amplitude
%A(k,:) = freqz(1,[1 -ARP(k,:)],w(k,:)); % Amplitude
%A2(k,:) = abs(r)'./abs(exp(i*w(k,:))-r'); % Amplitude
B(k,:) = -log(abs(p(idx)')); % Bandwidth
if nargout < 6,
elseif 0,
F(k,:) = (1+sign(imag(r(idx)')))./(polyval([-ARP(k,pp-1:-1:1).*(1:pp-1) pp],1./p(idx).').*polyval([-ARP(k,pp:-1:1) 1],p(idx).'));
elseif 1;
a3 = polyval([-ARP(k,pp-1:-1:1).*(1:pp-1), pp],1./p(idx).');
a = polyval([-ARP(k,pp:-1:1) 1],p(idx).');
%F(k,:) = (1+(imag(P(k,:))~=0))./(a.*a3);
F(k,:) = (1+sign(imag(P(k,:))))./(a.*a3);
end;
end;
A = A.*sqrt(E(:,ones(1,pp))/(2*pi*nhz));
if nargin>1,
if size(nhz,1)==1,
nhz = nhz(ones(NTR,1),:);
end;
w = w.*nhz(:,ones(1,pp))/(2*pi);
B = B.*nhz(:,ones(1,pp))/(2*pi);
end;
if nargin>2,
F = F.*E(:,ones(1,pp));
F1 = F1.*E(:,ones(1,pp));
end;
ip = sum(imag(P)~=0,2)/2;
return;
np(:,1) = sum(imag(P')==0)'; % number of real poles
np(:,2) = pp-np(:,1); % number of imaginary poles
tsa/inst/aarmam.m 0000664 0023567 0023567 00000017440 12115040716 014451 0 ustar schloegl schloegl function [z,e,REV,ESU,V,Z,SPUR] = aarmam(y, Mode, MOP, UC, z0, Z0, V0, W);
% Estimating Adaptive AutoRegressive-Moving-Average-and-mean model (includes mean term)
%
% !! This function is obsolete and is replaced by AMARMA
%
% [z,E,REV,ESU,V,Z,SPUR] = aarmam(y, mode, MOP, UC, z0, Z0, V0, W);
% Estimates AAR parameters with Kalman filter algorithm
% y(t) = sum_i(a_i(t)*y(t-i)) + m(t) + e(t) + sum_i(b_i(t)*e(t-i))
%
% State space model
% z(t) = G*z(t-1) + w(t) w(t)=N(0,W)
% y(t) = H*z(t) + v(t) v(t)=N(0,V)
%
% G = I,
% z = [m(t),a_1(t-1),..,a_p(t-p),b_1(t-1),...,b_q(t-q)];
% H = [1,y(t-1),..,y(t-p),e(t-1),...,e(t-q)];
% W = E{(z(t)-G*z(t-1))*(z(t)-G*z(t-1))'}
% V = E{(y(t)-H*z(t-1))*(y(t)-H*z(t-1))'}
%
%
% Input:
% y Signal (AR-Process)
% Mode determines the type of algorithm
%
% MOP Model order [m,p,q], default [0,10,0]
% m=1 includes the mean term, m=0 does not.
% p and q must be positive integers
% it is recommended to set q=0.
% UC Update Coefficient, default 0
% z0 Initial state vector
% Z0 Initial Covariance matrix
%
% Output:
% z AR-Parameter
% E error process (Adaptively filtered process)
% REV relative error variance MSE/MSY
%
% REFERENCE(S):
% [1] A. Schloegl (2000), The electroencephalogram and the adaptive autoregressive model: theory and applications.
% ISBN 3-8265-7640-3 Shaker Verlag, Aachen, Germany.
%
% More references can be found at
% http://pub.ist.ac.at/~schloegl/publications/
% $Id: aarmam.m 11693 2013-03-04 06:40:14Z schloegl $
% Copyright (C) 1998-2002,2008,2012 by Alois Schloegl
% This is part of the TSA-toolbox. See also
% http://pub.ist.ac.at/~schloegl/matlab/tsa/
% http://octave.sourceforge.net/
% http://biosig.sourceforge.net/
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program 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 this program. If not, see .
%#realonly
%#inbounds
warning('AARMAM is obsolete. Use AMARMA instead!')
[nc,nr]=size(y);
if nargin<2 Mode=0;
elseif ischar(Mode) Mode=bin2dec(Mode);
elseif isnan(Mode) return; end;
if nargin<3 MOP=[0,10,0]; end;
if length(MOP)==0, m=0;p=10; q=0; MOP=p;
elseif length(MOP)==1, m=0;p=MOP(1); q=0; MOP=p;
elseif length(MOP)==2, fprintf(1,'Error AMARMA: MOP is ambiguos\n');
elseif length(MOP)>2, m=MOP(1); p=MOP(2); q=MOP(3);MOP=m+p+q;
end;
if prod(size(Mode))>1
aMode=Mode(1);
eMode=Mode(2);
end;
%fprintf(1,['a' int2str(aMode) 'e' int2str(eMode) ' ']);
e=zeros(nc,1);
V=zeros(nc,1);V(1)=V0;
T=zeros(nc,1);
ESU=zeros(nc,1)+nan;
SPUR=zeros(nc,1)+nan;
z=z0(ones(nc,1),:);
arc=poly((1-UC*2)*[1;1]);b0=sum(arc); % Whale forgetting factor for Mode=258,(Bianci et al. 1997)
dW=UC/MOP*eye(MOP); % Schloegl
%------------------------------------------------
% First Iteration
%------------------------------------------------
H = zeros(MOP,1);
if m,
H(1) = 1;%M0;
if m~=1,
fprintf(2,'Warning AARMAM: m must be 0 or 1\n');
return;
end;
end;
if (p<0) || (q<0) || (round(p)~=p) || (round(q)~=q),
fprintf(2,'Error AARMAM: p and q must be positive integers\n');
return;
end;
E = 0;
Z = Z0;
zt= z0;
A1 = zeros(MOP); A2 = A1;
y_1=0;
%------------------------------------------------
% Update Equations
%------------------------------------------------
for t=1:nc,
% make measurement matrix
if 0,
if t>1,
y_1 = y(t-1);
end;
H=[1; y_1; H(m+(1:p-1)'); E(1:min(1,q-1)) ; H(p+m+(1:q-1)')]; % shift y and e
else % this seem to be slightly faster
if t<=p, H(m+(1:t-1)) = y(t-1:-1:1); % Autoregressive
else H(m+(1:p)) = y(t-1:-1:t-p);
end;
if t<=q, H(m+p+(1:t-1)) = e(t-1:-1:1); % Moving Average
else H(m+p+(1:q)) = e(t-1:-1:t-q);
end;
end;
% Prediction Error
E = y(t) - zt*H;
e(t) = E;
if ~isnan(E),
E2 = E*E;
AY = Z*H;
ESU(t) = H'*AY;
if eMode==1
V0 = V(t-1);
V(t) = V0*(1-UC)+UC*E2;
elseif eMode==2
V0 = 1;
V(t) = V0; %V(t-1)*(1-UC)+UC*E2;
elseif eMode==3
V0 = 1-UC;
V(t) = V0; %(t-1)*(1-UC)+UC*E2;
elseif eMode==4
V0 = V0*(1-UC)+UC*E2;
V(t) = V0;
elseif eMode==5
V(t)=V0;
%V0 = V0;
elseif eMode==6
if E2>ESU(t),
V0=(1-UC)*V0+UC*(E2-ESU(t));
end;
V(t)=V0;
elseif eMode==7
V0=V(t);
if E2>ESU(t)
V(t) = (1-UC)*V0+UC*(E2-ESU(t));
else
V(t) = V0;
end;
elseif eMode==8
V0=0;
V(t) = V0; % (t-1)*(1-UC)+UC*E2;
end;
k = AY / (ESU(t) + V0); % Kalman Gain
zt = zt + k'*E;
%z(t,:) = zt;
if aMode==2
T(t)=(1-UC)*T(t-1)+UC*(E2-Q(t))/(H'*H); % Roberts I 1998
Z=Z*V(t-1)/Q(t);
if T(t)>0 W=T(t)*eye(MOP); else W=zeros(MOP);end;
elseif aMode==5
Q_wo = (H'*C*H + V(t-1)); % Roberts II 1998
T(t)=(1-UC)*T(t-1)+UC*(E2-Q_wo)/(H'*H);
if T(t)>0 W=T(t)*eye(MOP); else W=zeros(MOP); end;
elseif aMode==6
T(t)=(1-UC)*T(t-1)+UC*(E2-Q(t))/(H'*H);
Z=Z*V(t)/Q(t);
if T(t)>0 W=T(t)*eye(MOP); else W=zeros(MOP); end;
elseif aMode==11
%Z = Z - k*AY';
W = sum(diag(Z))*dW;
elseif aMode==12
W = UC*UC*eye(MOP);
elseif aMode==13
W = UC*diag(diag(Z));
elseif aMode==14
W = (UC*UC)*diag(diag(Z));
elseif aMode==15
W = sum(diag(Z))*dW;
elseif aMode==16
W = UC*eye(MOP); % Schloegl 1998
%elseif aMode==17
%W=W;
end;
Z = Z - k*AY'; % Schloegl 1998
else
V(t) = V0;
end;
if any(any(isnan(W))), W=UC*Z;end;
z(t,:) = zt;
Z = Z + W; % Schloegl 1998
SPUR(t) = trace(Z);
end;
REV = mean(e.*e)/mean(y.*y);
if any(~isfinite(Z(:))), REV=inf; end;
tsa/inst/lattice.m 0000664 0023567 0023567 00000011747 12115040716 014644 0 ustar schloegl schloegl function [MX,PE,arg3] = lattice(Y,lc,Mode);
% Estimates AR(p) model parameter with lattice algorithm (Burg 1968)
% for multiple channels.
% If you have the NaN-tools, LATTICE.M can handle missing values (NaN),
%
% [...] = lattice(y [,Pmax [,Mode]]);
%
% [AR,RC,PE] = lattice(...);
% [MX,PE] = lattice(...);
%
% INPUT:
% y signal (one per row), can contain missing values (encoded as NaN)
% Pmax max. model order (default size(y,2)-1))
% Mode 'BURG' (default) Burg algorithm
% 'GEOL' geometric lattice
%
% OUTPUT
% AR autoregressive model parameter
% RC reflection coefficients (= -PARCOR coefficients)
% PE remaining error variance
% MX transformation matrix between ARP and RC (Attention: needs O(p^2) memory)
% AR(:,K) = MX(:, K*(K-1)/2+(1:K)); = MX(:,sum(1:K-1)+(1:K));
% RC(:,K) = MX(:,cumsum(1:K)); = MX(:,(1:K).*(2:K+1)/2);
%
% All input and output parameters are organized in rows, one row
% corresponds to the parameters of one channel
%
% see also ACOVF ACORF AR2RC RC2AR DURLEV SUMSKIPNAN
%
% REFERENCE(S):
% J.P. Burg, "Maximum Entropy Spectral Analysis" Proc. 37th Meeting of the Society of Exp. Geophysiscists, Oklahoma City, OK 1967
% J.P. Burg, "Maximum Entropy Spectral Analysis" PhD-thesis, Dept. of Geophysics, Stanford University, Stanford, CA. 1975.
% P.J. Brockwell and R. A. Davis "Time Series: Theory and Methods", 2nd ed. Springer, 1991.
% S. Haykin "Adaptive Filter Theory" 3rd ed. Prentice Hall, 1996.
% M.B. Priestley "Spectral Analysis and Time Series" Academic Press, 1981.
% W.S. Wei "Time Series Analysis" Addison Wesley, 1990.
% $Id: lattice.m 11693 2013-03-04 06:40:14Z schloegl $
% Copyright (C) 1996-2002,2008,2010 by Alois Schloegl
% This is part of the TSA-toolbox. See also
% http://biosig-consulting.com/matlab/tsa/
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program 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 this program. If not, see .
if nargin<3, Mode='BURG';
else Mode=upper(Mode(1:4));end;
BURG=~strcmp(Mode,'GEOL');
% Inititialization
[lr,N]=size(Y);
if nargin<2, lc=N-1; end;
F=Y;
B=Y;
[DEN,nn] = sumskipnan((Y.*Y),2);
PE = [DEN./nn,zeros(lr,lc)];
if nargout<3 % needs O(p^2) memory
MX = zeros(lr,lc*(lc+1)/2);
idx= 0;
% Durbin-Levinson Algorithm
for K=1:lc,
[TMP,nn] = sumskipnan(F(:,K+1:N).*B(:,1:N-K),2);
MX(:,idx+K) = TMP./DEN; %Burg
if K>1, %for compatibility with OCTAVE 2.0.13
MX(:,idx+(1:K-1))=MX(:,(K-2)*(K-1)/2+(1:K-1))-MX(:,(idx+K)*ones(K-1,1)).*MX(:,(K-2)*(K-1)/2+(K-1:-1:1));
end;
tmp = F(:,K+1:N) - MX(:,(idx+K)*ones(1,N-K)).*B(:,1:N-K);
B(:,1:N-K) = B(:,1:N-K) - MX(:,(idx+K)*ones(1,N-K)).*F(:,K+1:N);
F(:,K+1:N) = tmp;
[PE(:,K+1),nn] = sumskipnan([F(:,K+1:N).^2,B(:,1:N-K).^2],2);
if ~BURG,
[f,nf] = sumskipnan(F(:,K+1:N).^2,2);
[b,nb] = sumskipnan(B(:,1:N-K).^2,2);
DEN = sqrt(b.*f);
else
DEN = PE(:,K+1);
end;
idx=idx+K;
PE(:,K+1) = PE(:,K+1)./nn; % estimate of covariance
end;
else % needs O(p) memory
arp=zeros(lr,lc-1);
rc=zeros(lr,lc-1);
% Durbin-Levinson Algorithm
for K=1:lc,
[TMP,nn] = sumskipnan(F(:,K+1:N).*B(:,1:N-K),2);
arp(:,K) = TMP./DEN; %Burg
rc(:,K) = arp(:,K);
if K>1, % for compatibility with OCTAVE 2.0.13
arp(:,1:K-1) = arp(:,1:K-1) - arp(:,K*ones(K-1,1)).*arp(:,K-1:-1:1);
end;
tmp = F(:,K+1:N) - rc(:,K*ones(1,N-K)).*B(:,1:N-K);
B(:,1:N-K) = B(:,1:N-K) - rc(:,K*ones(1,N-K)).*F(:,K+1:N);
F(:,K+1:N) = tmp;
[PE(:,K+1),nn] = sumskipnan([F(:,K+1:N).^2,B(:,1:N-K).^2],2);
if ~BURG,
[f,nf] = sumskipnan(F(:,K+1:N).^2,2);
[b,nb] = sumskipnan(B(:,1:N-K).^2,2);
DEN = sqrt(b.*f);
else
DEN = PE(:,K+1);
end;
PE(:,K+1) = PE(:,K+1)./nn; % estimate of covariance
end;
% assign output arguments
arg3=PE;
PE=rc;
MX=arp;
end; %if
tsa/inst/covm.m 0000664 0023567 0023567 00000015600 12264575422 014167 0 ustar schloegl schloegl function [CC,NN] = covm(X,Y,Mode,W)
% COVM generates covariance matrix
% X and Y can contain missing values encoded with NaN.
% NaN's are skipped, NaN do not result in a NaN output.
% The output gives NaN only if there are insufficient input data
%
% COVM(X,Mode);
% calculates the (auto-)correlation matrix of X
% COVM(X,Y,Mode);
% calculates the crosscorrelation between X and Y
% COVM(...,W);
% weighted crosscorrelation
%
% Mode = 'M' minimum or standard mode [default]
% C = X'*X; or X'*Y correlation matrix
%
% Mode = 'E' extended mode
% C = [1 X]'*[1 X]; % l is a matching column of 1's
% C is additive, i.e. it can be applied to subsequent blocks and summed up afterwards
% the mean (or sum) is stored on the 1st row and column of C
%
% Mode = 'D' or 'D0' detrended mode
% the mean of X (and Y) is removed. If combined with extended mode (Mode='DE'),
% the mean (or sum) is stored in the 1st row and column of C.
% The default scaling is factor (N-1).
% Mode = 'D1' is the same as 'D' but uses N for scaling.
%
% C = covm(...);
% C is the scaled by N in Mode M and by (N-1) in mode D.
% [C,N] = covm(...);
% C is not scaled, provides the scaling factor N
% C./N gives the scaled version.
%
% see also: DECOVM, XCOVF
% $Id: covm.m 9032 2011-11-08 20:25:36Z schloegl $
% Copyright (C) 2000-2005,2009 by Alois Schloegl
% This function is part of the NaN-toolbox
% http://pub.ist.ac.at/~schloegl/matlab/NaN/
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.
%
% This program 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 this program; If not, see .
global FLAG_NANS_OCCURED;
if nargin<3,
W = [];
if nargin==2,
if isnumeric(Y),
Mode='M';
else
Mode=Y;
Y=[];
end;
elseif nargin==1,
Mode = 'M';
Y = [];
elseif nargin==0,
error('Missing argument(s)');
end;
elseif (nargin==3) && isnumeric(Y) && ~isnumeric(Mode);
W = [];
elseif (nargin==3) && ~isnumeric(Y) && isnumeric(Mode);
W = Mode;
Mode = Y;
Y = [];
elseif (nargin==4) && ~isnumeric(Mode) && isnumeric(Y);
; %% ok
else
error('invalid input arguments');
end;
Mode = upper(Mode);
[r1,c1]=size(X);
if ~isempty(Y)
[r2,c2]=size(Y);
if r1~=r2,
error('X and Y must have the same number of observations (rows).');
end;
else
[r2,c2]=size(X);
end;
persistent mexFLAG2;
persistent mexFLAG;
if isempty(mexFLAG2)
mexFLAG2 = exist('covm_mex','file');
end;
if isempty(mexFLAG)
mexFLAG = exist('sumskipnan_mex','file');
end;
if ~isempty(W)
W = W(:);
if (r1~=numel(W))
error('Error COVM: size of weight vector does not fit number of rows');
end;
%w = spdiags(W(:),0,numel(W),numel(W));
%nn = sum(W(:));
nn = sum(W);
else
nn = r1;
end;
if mexFLAG2 && mexFLAG && ~isempty(W),
%% the mex-functions here are much slower than the m-scripts below
%% however, the mex-functions support weighting of samples.
if isempty(FLAG_NANS_OCCURED),
%% mex-files require that FLAG_NANS_OCCURED is not empty,
%% otherwise, the status of NAN occurence can not be returned.
FLAG_NANS_OCCURED = logical(0); % default value
end;
if any(Mode=='D') || any(Mode=='E'),
[S1,N1] = sumskipnan(X,1,W);
if ~isempty(Y)
[S2,N2] = sumskipnan(Y,1,W);
else
S2 = S1; N2 = N1;
end;
if any(Mode=='D'), % detrending mode
X = X - ones(r1,1)*(S1./N1);
if ~isempty(Y)
Y = Y - ones(r1,1)*(S2./N2);
end;
end;
end;
[CC,NN] = covm_mex(real(X), real(Y), FLAG_NANS_OCCURED, W);
%% complex matrices
if ~isreal(X) && ~isreal(Y)
[iCC,inn] = covm_mex(imag(X), imag(Y), FLAG_NANS_OCCURED, W);
CC = CC + iCC;
end;
if isempty(Y) Y = X; end;
if ~isreal(X)
[iCC,inn] = covm_mex(imag(X), real(Y), FLAG_NANS_OCCURED, W);
CC = CC - i*iCC;
end;
if ~isreal(Y)
[iCC,inn] = covm_mex(real(X), imag(Y), FLAG_NANS_OCCURED, W);
CC = CC + i*iCC;
end;
if any(Mode=='D') && ~any(Mode=='1'), % 'D1'
NN = max(NN-1,0);
end;
if any(Mode=='E'), % extended mode
NN = [nn, N2; N1', NN];
CC = [nn, S2; S1', CC];
end;
elseif ~isempty(W),
error('Error COVM: weighted COVM requires sumskipnan_mex and covm_mex but it is not available');
%% weighted covm without mex-file support
%% this part is not working.
elseif ~isempty(Y),
if (~any(Mode=='D') && ~any(Mode=='E')), % if Mode == M
NN = real(X==X)'*real(Y==Y);
FLAG_NANS_OCCURED = any(NN(:)