/************************************
        Extended Kalman Filter
        Matrix operations

        V. Smidl, Z. Peroutka

Rev. 28.10.2010   (ZP)

26.10.2010      Prvni verze (VS)

26.10.2010      Upravena chyba v Thorton_fast - spatne shiftovani o vypoctu SIGMA.
27.10.2010      Pokus o odstraneni problemu v Thorton_fast - potize dela omezovani (orezavani) varianci.
28.10.2010      Drobne upravy v kodu.

*************************************/

#include "matrix_vs.h"
#include <math.h>

/* Matrix multiply Full matrix by upper diagonal matrix; */
void mmultAU(int16 *m1, int16 *up, int16 *result, unsigned int16 rows, unsigned int16 columns) {
    unsigned int16 i, j, k;
    int32 tmp_sum=0L; //in 15+qAU
    int16 *m2pom;
    int16 *m1pom=m1;
    int16 *respom=result;

    for (i=0; i<rows; i++) //rows of result
    {
        for (j=0; j<columns; j++) //columns of result
	{
            m2pom=up+j;//??

            for (k=0; k<j; k++) //inner loop up to "j" - U(j,j)==1;
            {
                tmp_sum+=((int32)(*(m1pom++))**m2pom)>>(15-qAU);
                m2pom+=columns;
            }
            // add the missing A(i,j)
            tmp_sum +=(int32)(*m1pom)<<qAU; // no need to shift
            m1pom-=(j); // shift back to first element

            *respom++=tmp_sum>>15;

            tmp_sum=0;
        }
        m1pom+=(columns);
    }
};


void bierman_fast(int16 *difz, int16 *xp, int16 *U, int16 *D, int16 *R, unsigned int16 dimy, unsigned int16 dimx )
{
    int16 alpha;
    int16 beta,lambda;
    int16 b[5]; // ok even for 4-dim state
    int16 *a; // in [0,1] -> q15
    unsigned int16 iy,j,i;

    int16 *b_j,*b_i;
    int16 *a_j;
    int16 *D_j;
    int16 *U_ij;
    int16 *x_i;

    int32 z_pom;
    int16 z_pom_int16;

    a = U; // iyth row of U
    for (iy=0; iy<dimy; iy++, a+=dimx) {
        // a is a row
        for (j=0,a_j=a,b_j=b,D_j=D; j<dimx; j++,b_j++,D_j++,a_j++)
            *b_j=((int32)(*D_j)*(*a_j))>>15;

        alpha = R[iy]; //\alpha = R+vDv = R+a*b
        // R in q15, a in q15, b=q15
//		gamma = (1<<15)/alpha; //(in q15)
        //min alpha = R[iy] = 164
        //max gamma = 0.0061 => gamma_ref = q7
        for (j=0,a_j=a,b_j=b,D_j=D; j<dimx; j++,a_j++,b_j++,D_j++) {
/*            beta=alpha;
            lambda = -((int32)(*a_j)<<15)/beta;
            alpha  += ((int32)(*a_j)*(*b_j))>>15;
            D[j] = ((int32)beta**D_j)/alpha;*/
/*xx*/
            lambda=alpha;
            alpha  += ((int32)(*a_j)*(*b_j))>>15;
            D[j] = ((int32)lambda**D_j)/alpha;
            z_pom_int16 = -((int32)(*a_j)<<15)/lambda;
/*xx*/

            if (*D_j==0) *D_j=1;

            for (i=0,b_i=b,U_ij=U+j; i<j; i++, b_i++,U_ij+=dimx) {
                beta   = *U_ij;
//                *U_ij +=  ((int32)lambda*(*b_i))>>15;		// puvodni reseni
                *U_ij -=  ((int32)(*a_j)*(*b_i))/lambda;         // pozadovane optimalni reseni
//                *U_ij -=  ((int32)((int16)((int32)(*a_j)<<15)/lambda)**b_i)>>15;	// tohle funguje - problem je s tim pretypovanim na (int16)
//				*U_ij -= (int16)((int32)(*a_j)*(*b_i))/lambda;
//				z_pom = (((int32)(*a_j)*(*b_i))/lambda);
/*  			    z_pom = (int32)(*U_ij)-(int16)((int32)(*a_j)*(*b_i))/lambda;
				if (z_pom > 32767) z_pom = 32767;
				if (z_pom < - 32768) z_pom = -32768;
				*U_ij = z_pom;                      /**/
//                *U_ij +=  ((int32)z_pom_int16*(*b_i))>>15;		// puvodni reseni - jen jina konstanta
                *b_i  +=  ((int32)beta*(*b_j))>>15;
            }
        }
        // no shift due to gamma
        for (i=0,x_i=xp,b_i=b; i<dimx; i++,x_i++,b_i++) {
            *x_i  += ((int32)difz[iy]*(*b_i))/alpha; // multiply by unscaled Kalman gain
        }
    }
}

// Thorton procedure - Kalman predictive variance in UD
void thorton(int16 *U, int16 *D, int16 *PSIU, int16 *Q, int16 *G, int16 *Dold, unsigned int16 rows) {
	thorton_fast(U, D, PSIU, Q, G, Dold, rows);
}
	
// Thorton procedure - Kalman predictive variance in UD
void thorton_fast(int16 *U, int16 *D, int16 *PSIU, int16 *Q, int16 *G, int16 *Dold, unsigned int16 rows) {
    unsigned int16 i,j,k;
    // copy D to Dold
    int16 *Dold_i,*Dold_k;
    int16 *D_i;
    int16 *PSIU_ij,*PSIU_ik,*PSIU_jk;
    int16 *Q_jj,*Q_ii,*Q_kk;
    int16 *U_ji;
    int16 *G_ik,*G_jk;
    int16 irows,jrows;
    int32 sigma; // in qAU+15!!
    int32 z;

    for (i=0,Dold_i=Dold,D_i=D;i<rows;i++,Dold_i++,D_i++) {
        *Dold_i=*D_i;
    }

    // initialize G = eye()
    G_ik= G;
    *G_ik++=32767;
    for (i=0;i<rows-1;i++) {
        // clean elem before diag
        for (k=0; k<rows; k++) {
            *G_ik++=0;
        }
        *G_ik++=32767;
    }
    // eye created

    for (i=rows-1, Dold_i=Dold+i, D_i=D+i;
            1; i--, Dold_i--,D_i--) { // stop if i==0 at the END!
        irows=i*rows;
        sigma = 0;
        for (k=0, PSIU_ik=PSIU+irows,Dold_k=Dold;
                k<rows; k++, PSIU_ik++,Dold_k++) {
			sigma += (((int32)(*PSIU_ik)**PSIU_ik)>>(qAU))*(*Dold_k);
        }
        sigma += (int32)(*(Q+i+irows))<<qAU;
        for (j=i+1, G_ik=G+irows+i+1; j<rows; j++,G_ik++) {
            sigma += (((int32)(*G_ik)**G_ik)>>16)**(Q+j+j*rows);
        }

		if (sigma>((int32)1<<(qAU+15))) {
			*D_i = 32767;
//			*(Dold+i)-=*(Q+i+irows);
		} else {
			*D_i=sigma>>qAU;
		}
        if (*D_i==0) *D_i=1;

        for (j=0;j<i;j++) {
            jrows = j*rows;

            sigma =0;
            for (k=0, PSIU_ik=PSIU+irows, PSIU_jk=PSIU+jrows, Dold_k=Dold;
                    k<rows; k++, PSIU_ik++, PSIU_jk++, Dold_k++) {

				sigma += ((((int32)(*PSIU_ik)**PSIU_jk)>>qAU)**Dold_k);
            }

            for (k=i,G_ik=G+irows+i,G_jk=G+jrows+i,Q_kk=Q+k*rows+k;
                    k<rows;k++,G_ik++,G_jk++,Q_kk+=rows+1) {
                sigma += ((((int32)*G_ik)**G_jk)>>16)**Q_kk;
            }

            z=(sigma/(*D_i))<<(15-qAU); // shift to q15
            if (z>32767) z=32767;
            if (z<-32768) z=-32768;

            U_ji=U+jrows+i;
            *U_ji = (int16)z;


            for (k=0,PSIU_ik=PSIU+irows,PSIU_jk=PSIU+jrows;
                    k<rows;k++,PSIU_ik++,PSIU_jk++) {
                *PSIU_jk -= ((int32)*U_ji**PSIU_ik)>>15;
            }

            for (k=0,G_jk=G+jrows,G_ik=G+irows;
                    k<rows;k++, G_jk++, G_ik++) {
                *G_jk -=  ((int32)*U_ji**G_ik)>>15;
            }

        }
		if (i==0) return;
    }
}

/* square root of 0<a<1 using taylor at 0.5 in q15*/
int16 int_sqrt(int16 x) {
	double xd(double(x)/32768.);
	return round(sqrt(xd)*32768);

    //sqrt(x) == 1/2*2^(1/2)+1/2*2^(1/2)*(x-1/2)-1/4*2^(1/2)*(x-1/2)^2
    //         = k1 + k1*(x-0.5) - k2*(x-0.5)(x-0.5);
#define k1 23170 //0.5*sqrt(2)*32768
#define k2 11585 //0.25*sqrt(2)*32768

    int16 tmp;
    if (x>6554) {
        int16 xm05=x-16384;
        tmp = ((long)k1*xm05)>>15;
        tmp-=(((long(k2)*xm05)>>15)*xm05)>>15;
        tmp +=k1;
    } else {
        tmp = 4*x;
        tmp-=long(8*x)*x>>15;
    }
    return tmp;
}

void householder(int16 *Ch /*= int16 *PSICh*/, int16 *Q, unsigned int16 dimx) {
    int16 k,j,i;
    int16 alpha,beta;
    int32  sigma; // 2*qCh
    int32  tmp_long;
    int16 B[25];//Q in qCh
    int16 w[5];
    int16 v[5];

    // copy Q to B
    for (i=0;i<dimx*dimx;i++)
    {
        B[i]=Q[i]>>(15-qCh);
    }

    for (k=dimx-1; k>=0; k--)
    {
        sigma=0;
        for (j=0;j<dimx;j++)
        {
            sigma+=((long)B[k*dimx+j]*B[k*dimx+j]);
        }
        for (j=0;j<=k;j++)
        {
            sigma+=((long)Ch[k*dimx+j]*Ch[k*dimx+j]);
        }
        
        //alpha in qCh
        alpha = (int)(sqrt((double)sigma)+0.5);   // predelat pro DSP

		sigma=0;
        for (j=0;j<dimx;j++) {
            w[j]=B[k*dimx+j];
            sigma+=(long)w[j]*w[j];
        }
        for (j=0; j<=k;j++) {
            if (j==k) {
                v[j]=Ch[k*dimx+j]-alpha;
            } else {
                v[j]=Ch[k*dimx+j];
            }
            sigma+=(long)v[j]*v[j];
        }
        
        alpha=sigma>>(qCh+1); // alpha = sigma /2;
        if (alpha==0) alpha =1;

        for (i=0;i<=k;i++) {
            sigma=0;
            for (j=0;j<dimx;j++) {
                sigma+=((long)B[i*dimx+j]*w[j]);
            }
            for (j=0;j<=k;j++) {
                sigma+=(long)Ch[i*dimx+j]*v[j];
            }

            sigma = sigma >> 15;               // navrat do Q15
          //  if (sigma>32767)sigma=32767;
			
            for (j=0;j<dimx;j++) 
            {
				tmp_long=B[i*dimx+j]-(sigma*w[j])/alpha;
				if (tmp_long>32767) {
					B[i*dimx+j]=32767;
				} else {
					if (tmp_long<-32767){
						B[i*dimx+j]=-32767;
					} else {
						B[i*dimx+j]=tmp_long;
					}
				}			
            };
            
            for (j=0;j<=k;j++)
            {
                tmp_long=Ch[i*dimx+j]-(sigma*v[j])/alpha;
				if (tmp_long>32767) {
					Ch[i*dimx+j]=32767;
				} else {
					if (tmp_long<-32767){
						Ch[i*dimx+j]=-32767;
					} else {
						Ch[i*dimx+j]=tmp_long;
					}
				}
			}
        }
    }

}

void carlson(int16 *difz, int16 *xp, int16 *Ch, int16 *R, unsigned int16 dimy, unsigned int16 dimx ) {
    int16 alpha,beta,gamma;
    int16 delta, eta,epsilon,zeta,sigma,tau;
    int16 i,j,iy;
    int16 w[5];
	int32 tmp_long;

    for (iy=0; iy<dimy; iy++)
    {
        alpha=R[iy];
        delta = difz[iy];

        for (j=0;j<dimx;j++)
        {
            sigma=Ch[iy*dimx+j];
            beta=alpha;
            alpha+=((long)sigma*sigma)>>15;
//			double ab=(double)alpha*beta/32768./32768.;
//			double s_ab=sqrt(ab);
            gamma=(int)(sqrt((double)((long)alpha*beta))+0.5);            // predelat v DSP
            //gamma = round(s_ab*(1<<15));
//            eta=((long)beta<<15) / gamma;
            //zeta=(long(sigma)<<15)/ gamma;
            w[j]=0;
            for (i=0;i<=j;i++) {
                tau=Ch[i*dimx+j];
				tmp_long=((long)beta*Ch[i*dimx+j] -(long)sigma*w[i])/gamma;
				if (tmp_long>32767) {
					Ch[i*dimx+j]=32767;
				} else {
					if (tmp_long<-32767){
						Ch[i*dimx+j]=-32767;
					} else {
						Ch[i*dimx+j]=tmp_long;
					}
				}
				
                w[i]+=((long)tau*sigma)>>15;
            }
        }

        //epsilon=(long(difz)<<15) / (alpha); // q15*q13/q13 = q15
        for (i=0;i<dimx;i++) {
            xp[i]+=((long)w[i]*delta)/alpha;
        }
    }
}

/* perform Householder update of Ch matrix using PSI*Ch , Q, */
extern void givens(int16 *Ch /*= int16 *PSICh*/, int16 *Q, unsigned int16 dimx){
	int16 i,j,k;
	int16 rho,s,c,tau;
	int32  tmp_long;

	int16 A[25];//beware
	// copy Q to A
	for (i=0;i<dimx*dimx;i++) {
		A[i]=Q[i]>>(15-qCh);
	}


	for (i=dimx-1; i>=0; i--){
		for (j=0; j<dimx; j++) {
			tmp_long=(long)Ch[i*dimx+i]*Ch[i*dimx+i]+long(A[i*dimx+j])*A[i*dimx+j];
			if (tmp_long>0){
				rho=sqrt(double(tmp_long));
				s=(long(A[i*dimx+j])<<15)/rho;
				c=(long(Ch[i*dimx+i])<<15)/rho;
				for (k=0;k<=i; k++){
					tau=(long(c)*A[k*dimx+j]-long(s)*Ch[k*dimx+i])>>15;
					Ch[k*dimx +i]=(long(s)*A[k*dimx+j]+long(c)*Ch[k*dimx+i])>>15;
					A[k*dimx +j]=tau;
				}
			}
		}

		for (j=0; j<i; j++){
			tmp_long=(long(Ch[i*dimx+i])*Ch[i*dimx+i]+long(Ch[i*dimx+j])*Ch[i*dimx+j]);
			if (tmp_long>0){
				rho=sqrt((double)(tmp_long));
				s=(long(Ch[i*dimx+j])<<15)/rho;
				c=(long(Ch[i*dimx+i])<<15)/rho;
				for (k=0; k<=i; k++){
					tau=(long(c)*Ch[k*dimx+j]-long(s)*Ch[k*dimx+i])>>15;
					Ch[k*dimx+i]=(long(s)*Ch[k*dimx+j]+long(c)*Ch[k*dimx+i])>>15;
					Ch[k*dimx+j]=tau;
				}
			}
		}

	}
}

/* Matrix multiply Full matrix by upper diagonal matrix; */
void mmultACh(int16 *m1, int16 *up, int16 *result, unsigned int16 rows, unsigned int16 columns) {
	unsigned int16 i, j, k;
	int32 tmp_sum=0L;
	int16 *m2pom;
	int16 *m1pom=m1;
	int16 *respom=result;
	
	for (i=0; i<rows; i++) //rows of result
    {
		for (j=0; j<columns; j++) //columns of result
        {
			m2pom=up+j;//??
			
			for (k=0; k<=j; k++) //inner loop up to "j" - U(j,j)==1;
            {
				tmp_sum+=(int32)(*(m1pom++))**m2pom;
				m2pom+=columns;
			}
			m1pom-=(j+1); // shift back to first element
			
			*respom++=tmp_sum>>15;
			
			tmp_sum=0;
		}
		m1pom+=(columns);
	}
}
