Exemple #1
0
/**
 * @brief Creates the admittance matrix.
 *
 *    @return 0 on success.
 */
static int econ_createGMatrix (void)
{
   int ret;
   int i, j;
   double R, Rsum;
   cs *M;
   StarSystem *sys;

   /* Create the matrix. */
   M = cs_spalloc( systems_nstack, systems_nstack, 1, 1, 1 );
   if (M == NULL)
      ERR("Unable to create CSparse Matrix.");

   /* Fill the matrix. */
   for (i=0; i < systems_nstack; i++) {
      sys   = &systems_stack[i];
      Rsum = 0.;

      /* Set some values. */
      for (j=0; j < sys->njumps; j++) {

         /* Get the resistances. */
         R     = econ_calcJumpR( sys, &systems_stack[sys->jumps[j]] );
         R     = 1./R; /* Must be inverted. */
         Rsum += R;

         /* Matrix is symetrical and non-diagonal is negative. */
         ret = cs_entry( M, i, sys->jumps[j], -R );
         if (ret != 1)
            WARN("Unable to enter CSparse Matrix Cell.");
         ret = cs_entry( M, sys->jumps[j], i, -R );
         if (ret != 1)
            WARN("Unable to enter CSparse Matrix Cell.");
      }

      /* Set the diagonal. */
      Rsum += 1./ECON_SELF_RES; /* We add a resistence for dampening. */
      cs_entry( M, i, i, Rsum );
   }

   /* Compress M matrix and put into G. */
   if (econ_G != NULL)
      cs_spfree( econ_G );
   econ_G = cs_compress( M );
   if (econ_G == NULL)
      ERR("Unable to create economy G Matrix.");

   /* Clean up. */
   cs_spfree(M);

   return 0;
}
Exemple #2
0
/* create an empty triplet matrix, insert 2 elements, print and free */
int main()
{
  CSparseMatrix *m = cs_spalloc(0,0,0,0,1); /* coo format */
  
  int info1 = 1-cs_entry(m, 3, 4, 1.0);
  int info2 = 1-cs_entry(m, 1, 2, 2.0);

  int info3 = 1-cs_print(m, 0);

  m=cs_spfree(m);

  int info4 = 1-(m==NULL);

  return info1+info2+info3+info4;
}
Exemple #3
0
returnValue ACADOcsparse::setMatrix(double *A_)
{
	int run1;
	int order = 0;

	if (dim <= 0)
		return ACADOERROR(RET_MEMBER_NOT_INITIALISED);
	if (nDense <= 0)
		return ACADOERROR(RET_MEMBER_NOT_INITIALISED);

	cs *C, *D;
	C = cs_spalloc(0, 0, 1, 1, 1);

	for (run1 = 0; run1 < nDense; run1++)
		cs_entry(C, index1[run1], index2[run1], A_[run1]);

	D = cs_compress(C);
	S = cs_sqr(order, D, 0);
	N = cs_lu(D, S, TOL);

	cs_spfree(C);
	cs_spfree(D);

	return SUCCESSFUL_RETURN;
}
Exemple #4
0
/* add an entry to triplet matrix only if value is not (nearly) null */
csi cs_zentry(CSparseMatrix *T, csi i, csi j, double x)
{
  if(fabs(x) >= DBL_EPSILON)
  {
    return cs_entry(T, i, j, x);
  }
  else
  {
    return 1;
  }
}
Exemple #5
0
cs* NN_subColumns_sp(cs* A, int c_left, int c_right)
{
    csi j,p,*Ap,*Ai;
    double *Ax;
    cs *T,*ret;

    Ap = A->p;
    Ai = A->i;
    Ax = A->x;
    if (!A) return (NULL) ;                             /* check inputs */
    T = cs_spalloc (0, 0, 1, 1, 1) ;                    /* allocate result */
    for(j=c_left; j<=c_right; j++) {
        for(p=Ap[j]; p<Ap[j+1]; p++) {
            if(!cs_entry(T, Ai[p], j-c_left, Ax[p])) return (cs_spfree(T));
        }
    }
    cs_entry(T,A->m-1,c_right-c_left,0.0);

    ret = cs_compress(T);
    cs_spfree(T);
    return ret;
}
Exemple #6
0
/* load a triplet matrix from a file */
cs *cs_load (FILE *f)
{
    int i, j ;
    double x ;
    cs *T ;
    if (!f) return (NULL) ;                             /* check inputs */
    T = cs_spalloc (0, 0, 1, 1, 1) ;                    /* allocate result */
    while (fscanf (f, "%d %d %lg\n", &i, &j, &x) == 3)
    {
        if (!cs_entry (T, i, j, x)) return (cs_spfree (T)) ;
    }
    return (T) ;
}
Exemple #7
0
/* load a triplet matrix from a file */
cs *cs_load (FILE *f)
{
    CS_INT i, j ;
    double x ;
#ifdef CS_COMPLEX
    double xi ;
#endif
    cs *T ;
    if (!f) return (NULL) ;                             /* check inputs */
    T = cs_spalloc (0, 0, 1, 1, 1) ;                    /* allocate result */
#ifdef CS_COMPLEX
    while (fscanf (f, ""CS_ID" "CS_ID" %lg %lg\n", &i, &j, &x, &xi) == 4)
#else
    while (fscanf (f, ""CS_ID" "CS_ID" %lg\n", &i, &j, &x) == 3)
#endif
    {
#ifdef CS_COMPLEX
        if (!cs_entry (T, i, j, x + xi*I)) return (cs_spfree (T)) ;
#else
        if (!cs_entry (T, i, j, x)) return (cs_spfree (T)) ;
#endif
    }
    return (T) ;
}
Exemple #8
0
static
cs *cs_frand (csi n, csi nel, csi s)
{
    csi ss = s*s, nz = nel*ss, e, i, j, *P ;
    cs *A, *T = cs_spalloc (n, n, nz, 1, 1) ;
    if (!T) return (NULL) ;
    P = cs_malloc (s, sizeof (csi)) ;
    if (!P) return (cs_spfree (T)) ;
    for (e = 0 ; e < nel ; e++)
    {
        for (i = 0 ; i < s ; i++) P [i] = rand () % n ;
        for (j = 0 ; j < s ; j++)
        {
            for (i = 0 ; i < s ; i++)
            {
                cs_entry (T, P [i], P [j], rand () / (double) RAND_MAX) ;
            }
        }
    }
    for (i = 0 ; i < n ; i++) cs_entry (T, i, i, 1) ;
    A = cs_compress (T) ;
    cs_spfree (T) ;
    return (cs_dupl (A) ? A : cs_spfree (A)) ;
}
Exemple #9
0
cs *cs_load(char *matrixFilename) {

	double i, j; /* use double for integers to avoid csi conflicts */
	double x;
	cs *T;
	FILE *matrixFilePtr;

	matrixFilePtr = fopen(matrixFilename, "r");
	if (matrixFilePtr == NULL) {

		fprintf(stderr, "Could not open output file %s for writing\n", matrixFilename);
		exit(EXIT_FAILURE);
	}

	T = cs_spalloc(0, 0, 1, 1, 1); /* allocate result */
	while (fscanf(matrixFilePtr, "%lg %lg %lg\n", &i, &j, &x) == 3) {
		if (!cs_entry(T, i, j, x))
			return (cs_spfree(T));
	}
	return (T);
}
Exemple #10
0
void* eigs_dsdrv2_init_cs( int n, const void *data_A, const void *data_M,
                           const EigsOpts_t *opts, cs_fact_type_t type )
{
    const cs *A = (const cs*) data_A;
    (void) data_M;
    cs *C, *B, *T;
    int i, f;
    cs_fact_t *fact;

    if (opts->sigma == 0.) {
        C = (cs*) A;
        f = 0;
    }
    else {
        /* Create Temoporary B matrix as the identity. */
        B = cs_spalloc( n, n, n, 1, 1 );
        for (i=0; i<n; i++)
            cs_entry( B, i, i, 1 );
        T = B;
        B = cs_compress( T );
        cs_spfree( T );

        /* C = A - sigma B */
        C = cs_add( A, B, 1.0, -opts->sigma );
        cs_spfree( B );
        f = 1;
    }

    /* Factorize C and keep factorization. */
    fact = cs_fact_init_type( C, type );

    if (f)
        cs_spfree(C);

    return fact;
}
/* 
    [C, [E]] = provaKoren (A,B), computes Corr(A,B), where A and B must be sparse.
    [C, [E]] = provaKoren (A,B,mode) computes Corr(A,b). If mode=0, the column average is calculated on common elements, otherwise column average is calculated on all non-zeros elements (DEFAULT)
        E is a matrix contaninng the number of common elements
*/
void mexFunction
(
    int nargout,
    mxArray *pargout [ ],
    int nargin,
    const mxArray *pargin [ ]
)
{
    CS_INT modeAllElement ;
    if (nargout > 2 || nargin < 2 || nargin > 3)
    {
        mexErrMsgTxt ("Usage: [C, [E]] = provaKoren (A,B,[mode=0])") ;
    }
    modeAllElement = (nargin > 2) ? mxGetScalar (pargin [2]) : 1 ; /* default = 1 */
    modeAllElement = (modeAllElement == 0) ? 0 : 1 ;
    if (modeAllElement && log) fprintf(stdout,"average computed on all non-zeros elements\n");

    cs_dl Amatrix, Bmatrix, *A, *B, *C;
    A = cs_dl_mex_get_sparse (&Amatrix, 0, 1, pargin [0]) ; /* get A */
    B = cs_dl_mex_get_sparse (&Bmatrix, 0, 1, pargin [1]) ; /* get B */

    UF_long i, p, pp, Am, An, Anzmax, Anz, *Ap, *Ai ; 
    UF_long j, q, qq, Bm, Bn, Bnzmax, Bnz, *Bp, *Bi ;
    double *Ax, *Bx;
    if (!A || !B) { if (log) printf ("(null)\n") ; return  ; }
   	Am = A->m ; 	An = A->n ; 	Ap = A->p ; 	Ai = A->i ; Ax = A->x ;	Anzmax = A->nzmax ; Anz = A->nz ;
   	Bm = B->m ; 	Bn = B->n ; 	Bp = B->p ; 	Bi = B->i ; Bx = B->x ;	Bnzmax = B->nzmax ; Bnz = B->nz ;
    if (log) fprintf(stdout,"A: mxn = %dx%d\n",Am,An);	
    if (log) fprintf(stdout,"B: mxn = %dx%d\n",Bm,Bn);	


    /* allocate result */       
    cs *corrMatrix = cs_spalloc (An, Bn, An*Bn, 1, 1) ;                    
    cs *commonElementMatrix = cs_spalloc (An, Bn, An*Bn, 1, 1) ;
     
    for (i = 0 ; i < An ; i++)
    {
        for (j = 0 ; j < Bn ; j++)
        {    
            p=Ap[i];
            q=Bp[j];
            pp = Ap[i+1];
            qq = Bp[j+1];
                               
            /* mean on common elements*/
            double meanA=0, meanB=0;
            long countElementsA=0, countElementsB=0;
            
            if (modeAllElement)
            {
                for (p=Ap[i] ; p<pp ; p++)
                {
                    meanA += Ax[p];   
                    countElementsA++; 
                }
                for (q=Bp[j] ; q<qq ; q++)
                {
                    meanB += Bx[q];   
                    countElementsB++; 
                }                
            }
            else
            {
                while (pp && qq && p<pp && q<qq)
                {
    /*                fprintf(stdout,"i=%d, j=%d, p=%d, q=%d, pp=%d, qq=%d, rowA=%d, rowB=%d \n",i,j,p,q,pp,qq,Ai[p],Bi[q]); */
                    if (Ai[p]==Bi[q])
                    {
                        meanA += Ax[p];
                        meanB += Bx[q];
                        countElementsA++;
                        countElementsB++;
    /*                    fprintf(stdout,"(%d,%d) - sum A = %f, sum B = %f \n",Ai[p],Bi[q],meanA,meanB); */
                        p++;
                        q++;
                        /* values Ax[p] and Bx[q] referring to the same row */ 
                    }
                    else if (Ai[p]>Bi[q])
                    {
                        q++;
                    }
                    else
                    {
                        p++;
                    }
                }
            }
            meanA = meanA / ((double)countElementsA);
            meanB = meanB / ((double)countElementsB);
/*            fprintf(stdout,"common elements = %d - mean A = %f, mean B = %f \n",countCommonElements,meanA,meanB); */
            
            /* correleation on common elements*/
            double corr;
            double corrNum=0, corrDenA=0, corrDenB=0;
            double entryA, entryB;            
            
            p=Ap[i];
            q=Bp[j];
            pp = Ap[i+1];
            qq = Bp[j+1];
            
            long countCommonElements=0;    
            while (pp && qq && p<pp && q<qq)
            {            
/*                fprintf(stdout,"i=%d, j=%d, p=%d, q=%d, pp=%d, qq=%d, rowA=%d, rowB=%d \n",i,j,p,q,pp,qq,Ai[p],Bi[q]); */
                if (Ai[p]==Bi[q])
                {
                    entryA=Ax[p]-meanA;
                    entryB=Bx[q]-meanB;
                    corrNum += entryA * entryB;
                    corrDenA += entryA*entryA;
                    corrDenB += entryB*entryB;
                    p++;
                    q++;
                    countCommonElements++;
                    /* values Ax[p] and Bx[q] referring to the same row */ 
                }
                else if (Ai[p]>Bi[q])
                {
                    q++;
                }
                else
                {
                    p++;
                }
            }
/*            fprintf(stdout,"corrNum=%f, corrDenA=%f, corrDenB=%f\n",corrNum,corrDenA,corrDenB); */
            corrDenA = (corrDenA==0) ? 1 : corrDenA;
            corrDenB = (corrDenB==0) ? 1 : corrDenB;
            corr = corrNum / (sqrt(corrDenA*corrDenB));
/*            fprintf(stdout,"corr(%d,%d)=%f\n",i,j,corr); */
            cs_entry(corrMatrix,i,j,corr);
            cs_entry(commonElementMatrix,i,j,countCommonElements);
        }
    }
    
        if (log) fprintf(stdout,"provaKoren: outputing computed matrices \n");
        corrMatrix=cs_compress(corrMatrix);
        pargout [0] = cs_dl_mex_put_sparse (&corrMatrix) ;               /* return C */
        if (nargout>1) 
        {
            commonElementMatrix=cs_compress(commonElementMatrix);
            pargout [1] = cs_dl_mex_put_sparse (&commonElementMatrix) ;               /* return E */
        }

}
Exemple #12
0
void addElementStampSparse( zeroCircuit *node, mnaSpSystem *system, cs *arrayA, hashTable *namTab, int row, int kPos)
{
	int posn1;
	int posn2;
	double tmp;

	struct linear_element *element;

	element = node->linElement;


	switch ( node->type )
	{
	case 0:
		switch( node->linElement->element )
		{
		case 1:

			if ( ( strcmp( node->linElement->connectors[0], "0\0" ) ) && ( strcmp( node->linElement->connectors[1], "0\0" ) ) )
			{
				//posn1 = findPlace ( node->linElement->connectors[0], &nodes );
				//posn2 = findPlace ( node->linElement->connectors[1], &nodes );
				posn1 = findHash ( namTab, node->linElement->connectors[0] );
				posn2 = findHash ( namTab, node->linElement->connectors[1] );

				tmp = (-1.0) * ( 1.0 / node->linElement->value);
				cs_entry(arrayA,posn1,posn2,tmp);
				cs_entry(arrayA,posn2,posn1,tmp);

			}

			if ( strcmp( node->linElement->connectors[0], "0\0" ) )
			{
				//posn1 = findPlace ( node->linElement->connectors[0], &nodes );
				posn1 = findHash ( namTab, node->linElement->connectors[0] );
				tmp = ( 1.0 / node->linElement->value );
				cs_entry(arrayA,posn1,posn1,tmp);
			}

			if ( strcmp( node->linElement->connectors[1], "0\0" ) )
			{
				//posn2 = findPlace ( node->linElement->connectors[1], &nodes );
				posn2 = findHash ( namTab, node->linElement->connectors[1] );
				tmp = ( 1.0 / node->linElement->value );
				cs_entry(arrayA,posn2,posn2,tmp);
			}

			break;
		case 3:

			if ( strcmp( node->linElement->connectors[0], "0\0" ) )
			{
				//posn1 = findPlace ( node->linElement->connectors[0], &nodes );
				posn1 = findHash ( namTab, node->linElement->connectors[0] );
				system->vector_B[posn1] += (-1.0) * element->value;
			}

			if ( strcmp( node->linElement->connectors[1], "0\0" ) )
			{
				//posn2 = findPlace ( node->linElement->connectors[1], &nodes );
				posn2 = findHash ( namTab, node->linElement->connectors[1] );
				system->vector_B[posn2] += element->value;
			}

			break;
		case 2: //case 2same as 5
		case 5:
			element->k = kPos;
			if (element->element == 2)
			{
				system->vector_B[ namTab->currPos -1 + kPos ] += element->value;

				//printf ( "bug ib B: %f\n", element->value );
			}


			if ( ( strcmp( node->linElement->connectors[0], "0\0" ) ) && ( strcmp( node->linElement->connectors[1], "0\0" ) ) )
			{
				//posn1 = findPlace ( element->connectors[0], &nodes );
				//posn2 = findPlace ( element->connectors[1], &nodes );
				posn1 = findHash ( namTab, node->linElement->connectors[0] );
				posn2 = findHash ( namTab, node->linElement->connectors[1] );

				cs_entry(arrayA,kPos + namTab->currPos -1,posn1,1.0);
				cs_entry(arrayA,kPos + namTab->currPos -1,posn2,-1.0);

				cs_entry(arrayA,posn1,kPos + namTab->currPos -1,1.0);
				cs_entry(arrayA,posn2,kPos + namTab->currPos -1,-1.0);
				break;

			}

			if ( strcmp( node->linElement->connectors[0], "0\0" ) )
			{
				//posn2 = findPlace ( element->connectors[1], &nodes );
				posn2 = findHash ( namTab, node->linElement->connectors[1] );

				cs_entry(arrayA,kPos + namTab->currPos -1,posn2,-1.0);
				cs_entry(arrayA,posn2,kPos + namTab->currPos -1,-1.0);

				break;
			}

			if ( strcmp( node->linElement->connectors[1], "0\0" ) )
			{
				//posn1 = findPlace ( element->connectors[0], &nodes );
				posn1 = findHash ( namTab, node->linElement->connectors[0] );

				cs_entry(arrayA,kPos + namTab->currPos -1,posn1,1.0);
				cs_entry(arrayA,posn1,kPos + namTab->currPos -1,1.0);

			}

			break;
		}

		break;
	case 1:
		//irrelevant
		break;
	}

}
Exemple #13
0
int main()
// -----------------------------------------------------------------------------
// This program uses the CSparse library to solve the matrix equation A x = b.
// The values used for the coefficient 'b' and the matrix 'A' are totally
// arbitrary in this example. 'A' is given a band-tridiagonal form, with
// additional entries in the upper right and lower right corners.
// -----------------------------------------------------------------------------
{
    //for a 10x10 array, but have 2 ghost cells in it for bcs
    const int M = 10002;
    const int N = 10002;
    const int P_size = 100;
    int i, j;
    //printf("here \n");

    double *matrix2 = (double*) malloc(M*N*sizeof(double));
    // Declare an MxN matrix which can hold up to three band-diagonals.
    struct cs_sparse *triplet = cs_spalloc(M, N, 6*N, 1, 1);
    
    cs_entry(triplet, 0, 0, 1.0); // Fill the corners with the value 1
    cs_entry(triplet, M-1, N-1, 1.0);
    
    // Fill the diagonal, and the band above and below the diagonal with some
    // values.
    double grid_spacing[2];
    grid_spacing[0] = 1.0/M;
    grid_spacing[1] = (2*Pi)/N;
    double r1 = 1.0;
    int position;
    for(i=0; i<M; i++){
        for(j=0; j<N; j++){
            position = (i*N) + j;
            matrix2[position] = 0.0;
        }
    }
    
    matrix2[0] = 1.0;
    matrix2[(M-1)*N + N-1] = 1.0;
    
    //printf("here");
    for (i=1; i<M-1; ++i) {
        //printf("%d \n", i);
        double a, b, c, d, e;
        double radius = r1 + ((i-1)*grid_spacing[0]);
        a = grid_spacing[1]*grid_spacing[1]*radius*(radius - grid_spacing[0]);
        b = grid_spacing[0]*grid_spacing[0];
        c = -2.0*((grid_spacing[1]*grid_spacing[1]*radius*radius) + (grid_spacing[0]*grid_spacing[0]));
        d = b;
        e = grid_spacing[1]*grid_spacing[1]*radius*(radius + grid_spacing[0]);
        if(i<=(P_size)){
            cs_entry(triplet,i, 0, a);
            matrix2[(i*N)] = a;
        }else{
            cs_entry(triplet,i, i-P_size,  a);
            matrix2[(i*N) + (i-P_size)] = a;
        }
        
        if(i>=(M-P_size - 1)){
            cs_entry(triplet,i, N-1, e);
            matrix2[(i*N) + N-1] = e;
        }else{
            cs_entry(triplet,i, i+P_size,  e);
            matrix2[(i*N) + (i + P_size)] = e ;
        }
        
        
        if((i-1)%P_size==0){
            cs_entry(triplet,i, i+(P_size-1),  b);
            matrix2[(i*N) + (i + P_size-1)] = b;
        }else{
            cs_entry(triplet,i, i-1, b);
            matrix2[(i*N) + (i-1)] = b;
        }
        
        if(i%P_size==0){
            cs_entry(triplet,i, i-(P_size - 1), d);
            matrix2[(i*N) + (i - P_size +1)] = d;
        }else{
            cs_entry(triplet,i, i+1, d);
            matrix2[(i*N) + (i +1)] = d ;

        }

        cs_entry(triplet, i, i, c);
        matrix2[(i*N) + i] = c;
    }
    
    // Declare and initialize the array of coefficients, 'b'.
    double *b = (double*) malloc(N*sizeof(double));
    double inner = 0.5;
    double outer =  1.5;
    b[0] = inner;
    b[N-1] = outer;
    for (i=1; i<N-1; ++i) {
        if((i-1)%P_size==0){
            b[i] = inner;
        }else if(i%P_size==0){
            b[i] = outer;
        }else{
            b[i] = 0.0;

        }
        
    }
    
    // Convert the triplet matrix into compressed column form, and use LU
    // decomposition to solve the system. Note that the vector 'b' of coefficients
    // overwritten to contain the solution vector 'x'.
    struct cs_sparse *matrix = cs_compress(triplet);
    cs_lusol(0, matrix, b, 1e-12);
    // Print the solution vector.
    output=fopen("trial3.txt", "w");

    for (i=0; i<P_size+1; ++i) {
        for(j=0; j<P_size+1; ++j){
            position = (i*P_size) + j;
            //printf(" m[%d] = %f", position, matrix2[position] );
            
            if(j==50){fprintf(output, "%+5.4e \n", b[i]);}

        }
        //printf("\n");
        //printf("b[%d] = %+5.4e\n", i, b[i]);
    }
    
    for (i=0; i<N; ++i) {
        //printf("b[%d] = %+5.4e\n", i, b[i]);
    }

    
    
    
    
    // Clean up memory usage.
    cs_spfree(triplet);
    cs_spfree(matrix);
    free(b);
    
    return 0;
}
Exemple #14
0
void computeMNASparse(){

	int i,j;
	int b=1;
	int n=hashNode_num-1;
	sizeA = (hashNode_num-1)+m2;
	

	//Initialize and Allocate memory for A,B,x

	A_sparse = cs_spalloc((hashNode_num-1)+m2,(hashNode_num-1)+m2, sizeA_sparse, 1, 1);
	
	if(TRAN==1)
		D_sparse = cs_spalloc((hashNode_num-1)+m2,(hashNode_num-1)+m2, sizeD_sparse, 1, 1);
		
	sizeB = (hashNode_num-1)+m2;
	B_sparse = (double *)calloc(sizeB,sizeof(double));
	x_sparse = (double *)calloc(sizeB,sizeof(double));

	//Check Resistors, compute the 1st (n-1 x n-1) part of A
	
	ResistorT *runnerR=rootR;

	while(runnerR!=NULL)
	{
		i=atoi(ht_get(hashtable,runnerR->pos_term));
		j=atoi(ht_get(hashtable,runnerR->neg_term));

		if(i!=0)
		{
		  cs_entry(A_sparse,i-1,i-1,1/runnerR->value);
		}
		if(j!=0)
		{
		  cs_entry(A_sparse,j-1,j-1,1/runnerR->value);
		}
		if(i!=0&&j!=0)
		{
		  cs_entry(A_sparse,i-1,j-1,-1/runnerR->value);
		  cs_entry(A_sparse,j-1,i-1,-1/runnerR->value);
		}
		runnerR=runnerR->next;
	}

	//Check Voltage Sources, compute 2nd (n-1 x m2) part of A and 2nd (m2x1) part of B
	
	VoltageSourceT *runnerV=rootV;
	while(runnerV != NULL)
	{

		i=atoi(ht_get(hashtable,runnerV->pos_term));		//get nodes of Voltage Source 
		j=atoi(ht_get(hashtable,runnerV->neg_term));
		
		if(i!=0)
		{
		  cs_entry(A_sparse,n-1+b,i-1,1.000);
		  cs_entry(A_sparse,i-1,n-1+b,1.000);
		}
		if(j!=0)
		{
		  cs_entry(A_sparse,n-1+b,j-1,-1.000);
		  cs_entry(A_sparse,j-1,n-1+b,-1.000);
		}
	      
	      if((i!=0)||(j!=0)){B_sparse[n-1+b]=runnerV->value;}	//Voltage value at B
	      b++;
	      runnerV= runnerV ->next;
	}

	//Check Inductors, compute 2nd (n-1 x m2) part of A

	InductorT *runnerL=rootL;
	while(runnerL != NULL)
	{
	      i = atoi(ht_get(hashtable,runnerL->pos_term));    //get nodes of Inductor 
	      j = atoi(ht_get(hashtable,runnerL->neg_term));
	
	      if(i!=0)
	      {
		cs_entry(A_sparse,n-1+b,i-1,1.000);
		cs_entry(A_sparse,i-1,n-1+b,1.000);
	      }
	      if(j!=0)
	      {
		cs_entry(A_sparse,n-1+b,j-1,-1.000);
		cs_entry(A_sparse,j-1,n-1+b,-1.000);
	      }
	      if(TRAN==1){
		cs_entry(D_sparse,n-1+b,n-1+b,-runnerL->value);
		cs_entry(D_sparse,n-1+b,n-1+b,-runnerL->value);
	      }
	      b++;
	      runnerL= runnerL ->next;
	}

	//Check Current Source, compute 1st (n-1 x 1) part of B
	
	CurrentSourceT *runnerI=rootI;
	while(runnerI != NULL)
	{
	      i = atoi(ht_get(hashtable,runnerI->pos_term));    //get nodes of Current Source
	      j = atoi(ht_get(hashtable,runnerI->neg_term));
	
	      if(i!=0)
	      {
		B_sparse[i-1]-=runnerI->value;
	      }
	      if(j!=0)
	      {
		B_sparse[j-1]+=runnerI->value;
	      }
	      
	      runnerI = runnerI ->next;
	
	}
	//Diatrexoume ti lista twn puknwtwn kai simplirwnoume katallila to 1o n-1 * n-1 kommati tou pinaka C
	if (TRAN==1){
		CapacitorT *runnerC=rootC;

		while(runnerC!=NULL){
			i=atoi(ht_get(hashtable,runnerC->pos_term));
			j=atoi(ht_get(hashtable,runnerC->neg_term));

			if(i!=0){
		  		cs_entry(D_sparse,i-1,i-1,runnerC->value);
			}
			if(j!=0){
		  		cs_entry(D_sparse,j-1,j-1,runnerC->value);
			}
			if(i!=0&&j!=0){
		  		cs_entry(D_sparse,i-1,j-1,-runnerC->value);
		  		cs_entry(D_sparse,j-1,i-1,-runnerC->value);
			}
			runnerC=runnerC->next;
		}
	}

	cs_print(A_sparse, "./SparseFiles/A_Sparse.txt", 0);
	if (TRAN==1)
		cs_print(D_sparse, "./SparseFiles/D_Sparse.txt", 0);

	//Afou exoume ftiaksei ton A (mna) se triplet morfi, ton metatrepoume se
	//compressed-column morfi kai eleutherwnoume ton xwro me tin palia morfi kai
	//sigxwneuoume ta diaforetika non zeros pou vriskontai stin idia thesi

	C_sparse = cs_compress(A_sparse);
	cs_spfree(A_sparse);
	cs_dupl(C_sparse);
	cs_print(C_sparse, "./SparseFiles/C_Sparse.txt", 0);

	if (TRAN==1){
	  E_sparse = cs_compress(D_sparse);
	  cs_spfree(D_sparse);
	  cs_dupl(E_sparse);
	  cs_print(E_sparse, "./SparseFiles/E_Sparsel.txt", 0);
	}
}
Exemple #15
0
/**
 * @brief Creates the penalty matrix of order k.
 * Returns the matrix Dk as a suite sparse style matrix.
 *
 * @param n                    number of observations
 * @param k                    order of the trendfilter
 * @param x                    locations of the responses
 * @return pointer to a csparse matrix
 * @see tf_calc_dktil
 */
cs * tf_calc_dk (int n, int k, const double * x)
{
  long int i;

  int tk = 1; /* "this k" - will iterate until ts = k */

  cs * D1;
  cs * D1_cp;
  cs * Dk;
  cs * Dk_cp;
  cs * delta_k;
  cs * delta_k_cp;
  cs * D1_x_delta;
  cs * Dk_next;
  cs * T;
  cs * eye;

  /* Deal with k=0 separately */
  if(k == 0)
  {
    T = cs_spalloc (n, n, n, 1, 1) ;
    for (i = 0 ; i < n; i++) cs_entry (T, i, i, 1);
    eye = cs_compress (T);
    cs_spfree (T);
    return eye;
  }

  /* Contruct one 'full D1', which persists throughout
     and another copy as Dk */
  D1 = cs_spalloc(n-tk, n, (n-tk)*2, 1, 1);
  Dk = cs_spalloc(n-tk, n, (n-tk)*2, 1, 1);
  D1->nz = (n-tk)*2;
  Dk->nz = (n-tk)*2;
  for (i = 0; i < (n-tk)*2; i++)
  {
    D1->p[i] = (i+1) / 2;
    Dk->p[i] = D1->p[i];
    D1->i[i] = i / 2;
    Dk->i[i] = D1->i[i];
    D1->x[i] = -1 + 2*(i % 2);
    Dk->x[i] = D1->x[i];
  }

  /* Create a column compressed version of Dk, and
     delete the old copy */
  Dk_cp = cs_compress(Dk);
  cs_spfree(Dk);

  for (tk = 1; tk < k; tk++)
  {
    /* 'reduce' the virtual size of D1 to: (n-tk-1) x (n-tk),
       compress into compressed column, saving as D1_cp */
    D1->nz = (n-tk-1)*2;
    D1->m = n-tk-1;
    D1->n = n-tk;
    D1_cp = cs_compress(D1);

    /* Construct diagonal matrix of differences: */
    delta_k = cs_spalloc(n-tk, n-tk, (n-tk), 1, 1);
    for(i = 0; i < n - tk; i++)
    {
      delta_k->p[i] = i;
      delta_k->i[i] = i;
      delta_k->x[i] = tk / (x[tk + i] - x[i]);
    }
    delta_k->nz = n-tk;
    delta_k_cp = cs_compress(delta_k);
    D1_x_delta = cs_multiply(D1_cp, delta_k_cp);

    /* Execute the matrix multiplication */
    Dk_next = cs_multiply(D1_x_delta, Dk_cp);

    /* Free temporary cs matricies created in each loop */
    cs_spfree(D1_cp);
    cs_spfree(delta_k);
    cs_spfree(delta_k_cp);
    cs_spfree(D1_x_delta);
    cs_spfree(Dk_cp);
    Dk_cp = Dk_next;
  }

  cs_spfree(D1);
  return Dk_cp;
}
sparse_matrix* create_mna_sparse(LIST *list, sparse_vector** b, int* vector_len){

	int i;
	int rows;
	int columns;
	sparse_vector* vector = NULL;
	sparse_matrix* matrix = NULL;
	LIST_NODE* curr;

	int num_nodes = ht_get_num_nodes(list->hashtable);
	int* nodeids = (int*)malloc(sizeof(int) * num_nodes);
	if(!nodeids)
		return NULL;

	for( i = 0; i < num_nodes; i++)
		nodeids[i] = 0;

	int m2_elements_found = 0;       // # of elements in group 2

	/* allocate matrix and vector */
	rows    = list->hashtable->num_nodes + list->m2;
 	columns = list->hashtable->num_nodes + list->m2;

 	matrix =  cs_spalloc( rows , columns , DEFAULT_NZ , 1 , 1 );
 	if(!matrix)
 		return NULL;

 	vector = (sparse_vector*) malloc( sizeof(sparse_vector) * rows);
 	if( !vector){
 		cs_spfree(matrix);
 		return NULL;
 	} 		

 	for( curr = list->head ; curr; curr = curr->next){

 		/*
 		 * RESISTANCE ELEMENT
 		 */

 		if( curr->type == NODE_RESISTANCE_TYPE ){

  			double conductance = 1 / curr->node.resistance.value ;
 			long plus_node  = curr->node.resistance.node1 - 1;
 			long minus_node = curr->node.resistance.node2  - 1;
 			//printf("plus_node: %d minus_node: %d\n",plus_node,minus_node);
 			/* <+> is ground */
 		 	if( plus_node == -1 ){

 				//double value = gsl_matrix_get(tmp_matrix , minus_node , minus_node);
 				//value += conductance ; 
 				//gsl_matrix_set( tmp_matrix , minus_node , minus_node ,  value );
 				//printf("Adding to matrix element (%d,%d) value:%f\n\n",minus_node,minus_node,value);
 				if( !cs_entry(matrix, minus_node , minus_node , conductance) ){
 					fprintf(stderr, "Error while inserting element in sparse matrix\n");
 					free(vector);
 					cs_spfree(matrix);
 					return NULL;
 				}
 			}
 			/* <-> is ground */
 			else if ( minus_node == -1  ){

 				if( !cs_entry(matrix, plus_node , plus_node , conductance) ){
 					fprintf(stderr, "Error while inserting element in sparse matrix\n");
 					free(vector);
 					cs_spfree(matrix);
 					return NULL;
 				}
 			}
 			else {

 				/* <+> <+> */
 				if( !cs_entry(matrix, plus_node , plus_node , conductance) ){
 					fprintf(stderr, "Error while inserting element in sparse matrix\n");
 					free(vector);
 					cs_spfree(matrix);
 					return NULL;
 				}

 				/* <+> <-> */
 				if( !cs_entry(matrix, plus_node , minus_node , -conductance) ){
 					fprintf(stderr, "Error while inserting element in sparse matrix\n");
 					free(vector);
 					cs_spfree(matrix);
 					return NULL;
 				}

 				/* <-> <+> */
 				if( !cs_entry(matrix, minus_node , plus_node , -conductance) ){
 					fprintf(stderr, "Error while inserting element in sparse matrix\n");
 					free(vector);
 					cs_spfree(matrix);
 					return NULL;
 				}

 				/* <-> <-> */
 				if( !cs_entry(matrix, minus_node , minus_node , conductance) ){
 					fprintf(stderr, "Error while inserting element in sparse matrix\n");
 					free(vector);
 					cs_spfree(matrix);
 					return NULL;
 				}
 			}
		}
		/* 
 		 * CURRENT SOURCE
 		 */
 		else if( curr->type == NODE_SOURCE_I_TYPE ){

 			/* change only the vector */
 			double current = curr->node.source_i.value;
 			double value;

 			if( curr->node.source_i.node1 != 0 ){
 				/* ste <+> */
 				value  = vector[curr->node.source_i.node1 - 1 ];
 				value -= current;
 				vector[curr->node.source_i.node1 -1 ] =  value;
 			}

 			if( curr->node.source_i.node2 != 0 ){
 				/* <-> */
 				value  = vector[curr->node.source_i.node2 - 1 ];
 				value += current;
 				vector[curr->node.source_i.node2 -1 ] =  value;
 			}
 		}
 	 	/*
 		 * VOLTAGE SOURCE
 		 */
 		else if ( curr->type == NODE_SOURCE_V_TYPE  ){
 			m2_elements_found++;
 			int matrix_row = list->hashtable->num_nodes + m2_elements_found - 1;
 			curr->node.source_v.mna_row = matrix_row;

 			double value;
 			
 			/* set vector value */
 			value = vector[matrix_row];
 			value += curr->node.source_v.value;
 			vector[ matrix_row ] = value;

 			long plus_node  = curr->node.source_v.node1 - 1;
 			long minus_node = curr->node.source_v.node2 - 1;

 			//printf("Voltage %s plus = %d minus = %d matrix_row = %d\n", curr->node.source_v.name,plus_node,minus_node,matrix_row );

 			/* <+> */
 			if( plus_node != -1 ){
 				//if( nodeids[plus_node] == 0 ){
 					//printf("mphke plus node...\n");
 					if( !cs_entry(matrix, matrix_row , plus_node , 1.0 ) ){
 		 				fprintf(stderr, "Error while inserting element in sparse matrix\n");
 						free(vector);
 						cs_spfree(matrix);
 						return NULL;	
 					}
 					
 					if( !cs_entry(matrix, plus_node , matrix_row , 1.0 ) ){
 		 				fprintf(stderr, "Error while inserting element in sparse matrix\n");
 						free(vector);
 						cs_spfree(matrix);
 						return NULL;	
 					}
 					//nodeids[plus_node] = 1;
 				//}			
 			}

 			/* <-> */
 			if( minus_node != -1 ){
 				
 				//if( nodeids[minus_node] == 0 ){
 					//printf("mphke minus node...\n");
 					if( !cs_entry(matrix, matrix_row , minus_node , -1.0 ) ){
 		 				fprintf(stderr, "Error while inserting element in sparse matrix\n");
 						free(vector);
 						cs_spfree(matrix);
 						return NULL;	
 					}
 					if( !cs_entry(matrix, minus_node , matrix_row , -1.0 ) ){
 		 				fprintf(stderr, "Error while inserting element in sparse matrix\n");
 						free(vector);
 						cs_spfree(matrix);
 						return NULL;	
 					}
 					//nodeids[minus_node] = 1;
 				
 				//}
 			}	 
 		}

 		/*
 		 * Inductance
 		 */
 		else if ( curr->type == NODE_INDUCTANCE_TYPE  ){
 			m2_elements_found++;
 			int matrix_row = list->hashtable->num_nodes  + m2_elements_found - 1 ;
			

 			/* Change the matrix */
 			long plus_node  = curr->node.inductance.node1 - 1;
 			long minus_node = curr->node.inductance.node2 - 1;
 			// printf("Inductance %s plus = %d minus = %d\n matrix_row = %d\n", curr->node.inductance.name,plus_node,minus_node,matrix_row);

 			/* <+> */
 			if( plus_node != -1 ){
 				//if( nodeids[plus_node] == 0 ){
 					//printf("mphke inductance sto plus...\n");
 					if( !cs_entry(matrix, matrix_row , plus_node , 1.0) ){
 		 				fprintf(stderr, "Error while inserting element in sparse matrix\n");
 						free(vector);
 						cs_spfree(matrix);
 						return NULL;	
 					}

 					if( !cs_entry(matrix, plus_node , matrix_row , 1.0) ){
 		 				fprintf(stderr, "Error while inserting element in sparse matrix\n");
 						free(vector);
 						cs_spfree(matrix);
 						return NULL;	
 					}
 					//nodeids[plus_node] = 1;
 				//} 				
 			}
 			/* <-> */
 			if( minus_node != -1 ){
 				//if( nodeids[minus_node] == 0 ){
 					//printf("mpahke Inductance minus_node...\n");
 					if( !cs_entry(matrix, matrix_row , minus_node , -1.0 ) ){
 		 				fprintf(stderr, "Error while inserting element in sparse matrix\n");
 						free(vector);
 						cs_spfree(matrix);
 						return NULL;	
 					}
 					if( !cs_entry(matrix, minus_node , matrix_row , -1.0 ) ){
 		 				fprintf(stderr, "Error while inserting element in sparse matrix\n");
 						free(vector);
 						cs_spfree(matrix);
 						return NULL;	
 					}
 					//nodeids[minus_node] = 1;
 				//}
 			} 			
 		}
 	} 	

	matrix = cs_compress(matrix);
 	
 	/* remove duplicates */
 	if( !cs_dupl(matrix) ){
 		fprintf(stderr, "Sparse matrix: duplicates not removed \n");
 		cs_spfree(matrix);
 		free(vector);
 		return NULL;
 	}
	*vector_len = matrix->n;
 	*b = vector;

 	//cs_print(matrix,"sparse_matrix.txt",0);
 	return matrix;
}
int main ( void )
{
  cs *A;
  cs *AT;
  cs *C;
  cs *D;
  cs *Eye;
  int i;
  int m;
  cs *T;

  printf ( "\n" );
  printf ( "CS_DEMO1:\n" );
  printf ( "  Demonstration of the CSPARSE package.\n" );
/* 
  Load the triplet matrix T from standard input.
*/
  T = cs_load ( stdin );	
/*
  Print T.
*/
  printf ( "T:\n" ); 
  cs_print ( T, 0 );
/*
  A = compressed-column form of T.
*/
  A = cs_triplet ( T );
  printf ( "A:\n" ); 
  cs_print ( A, 0 );
/*
  Clear T.
*/
  cs_spfree ( T );
/*
  AT = A'.
*/ 
  AT = cs_transpose ( A, 1 );
  printf ( "AT:\n" ); 
  cs_print ( AT, 0 );
/*
  M = number of rows of A.
*/
  m = A->m;
/*
  Create triplet identity matrix.
*/
  T = cs_spalloc ( m, m, m, 1, 1 );

  for ( i = 0; i < m; i++ ) 
  {
    cs_entry ( T, i, i, 1 );
  }
/* 
  Eye = speye ( m ) 
*/
  Eye = cs_triplet ( T );
  cs_spfree ( T );
/* 
  Compute C = A * A'.
*/
  C = cs_multiply ( A, AT );		
/* 
  Compute D = C + Eye * norm (C,1).
*/
  D = cs_add ( C, Eye, 1, cs_norm ( C ) );   

  printf ( "D:\n" ); 
  cs_print ( D, 0 );
/* 
  Clear A, AT, C, D, Eye, 
*/
  cs_spfree ( A );			
  cs_spfree ( AT );
  cs_spfree ( C );
  cs_spfree ( D );
  cs_spfree ( Eye );
/*
  Terminate.
*/
  printf ( "\n" );
  printf ( "CS_DEMO1:\n" );
  printf ( "  Normal end of execution.\n" );

  return ( 0 );
}
void test_sparse_als_zero_order_only(TestFixture_T *pFix, gconstpointer pg) {
  int n_features = pFix->X->n;
  int k = 0;
  ffm_param param = {.n_iter = 1,
                     .warm_start = true,
                     .ignore_w = true,
                     .init_sigma = 0.1,
                     .SOLVER = SOLVER_ALS,
                     .TASK = TASK_REGRESSION};

  ffm_coef *coef = alloc_fm_coef(n_features, k, true);
  param.init_lambda_w = 0;

  sparse_fit(coef, pFix->X, NULL, pFix->y, NULL, param);
  // g_assert_cmpfloat(4466.666666, ==, coef->w_0);
  g_assert_cmpfloat(fabs(4466.666666 - coef->w_0), <, 1e-6);

  free_ffm_coef(coef);
}

void test_sparse_als_first_order_only(TestFixture_T *pFix, gconstpointer pg) {
  int n_features = pFix->X->n;
  int k = 0;
  ffm_param param = {.n_iter = 1,
                     .warm_start = true,
                     .ignore_w_0 = true,
                     .init_sigma = 0.1,
                     .SOLVER = SOLVER_ALS,
                     .TASK = TASK_REGRESSION};

  ffm_coef *coef = alloc_fm_coef(n_features, k, false);
  coef->w_0 = 0;
  param.init_lambda_w = 0;

  ffm_vector_set(coef->w, 0, 10);
  ffm_vector_set(coef->w, 1, 20);

  sparse_fit(coef, pFix->X, NULL, pFix->y, NULL, param);
  // hand calculated results 1660.57142857   -11.87755102
  g_assert_cmpfloat(fabs(1660.57142857 - ffm_vector_get(coef->w, 0)), <, 1e-8);
  g_assert_cmpfloat(fabs(-11.87755102 - ffm_vector_get(coef->w, 1)), <, 1e-8);

  free_ffm_coef(coef);
}

void test_sparse_als_second_order_only(TestFixture_T *pFix, gconstpointer pg) {
  int n_features = pFix->X->n;
  int k = 1;
  ffm_param param = {.n_iter = 1,
                     .warm_start = true,
                     .ignore_w_0 = true,
                     .ignore_w = true,
                     .init_sigma = 0.1,
                     .SOLVER = SOLVER_ALS,
                     .TASK = TASK_REGRESSION};

  ffm_coef *coef = alloc_fm_coef(n_features, k, false);
  coef->w_0 = 0;

  param.init_lambda_w = 0;
  param.init_lambda_V = 0;

  ffm_matrix_set(coef->V, 0, 0, 300);
  ffm_matrix_set(coef->V, 0, 1, 400);

  sparse_fit(coef, pFix->X, NULL, pFix->y, NULL, param);
  // hand calculated results  0.79866412  400.
  g_assert_cmpfloat(fabs(0.79866412 - ffm_matrix_get(coef->V, 0, 0)), <, 1e-8);
  g_assert_cmpfloat(fabs(400 - ffm_matrix_get(coef->V, 0, 1)), <, 1e-8);

  free_ffm_coef(coef);
}

void test_sparse_als_all_interactions(TestFixture_T *pFix, gconstpointer pg) {
  int n_features = pFix->X->n;
  int k = 1;
  ffm_param param = {.n_iter = 1,
                     .warm_start = true,
                     .ignore_w_0 = false,
                     .ignore_w = false,
                     .init_sigma = 0.1,
                     .SOLVER = SOLVER_ALS,
                     .TASK = TASK_REGRESSION};

  ffm_coef *coef = alloc_fm_coef(n_features, k, false);
  coef->w_0 = 0;

  ffm_vector_set(coef->w, 0, 10);
  ffm_vector_set(coef->w, 1, 20);

  ffm_matrix_set(coef->V, 0, 0, 300);
  ffm_matrix_set(coef->V, 0, 1, 400);

  sparse_fit(coef, pFix->X, NULL, pFix->y, NULL, param);
  // hand calculated results checked with libfm
  g_assert_cmpfloat(fabs(-1755643.33333 - coef->w_0), <, 1e-5);
  g_assert_cmpfloat(fabs(-191459.71428571 - ffm_vector_get(coef->w, 0)), <,
                    1e-6);
  g_assert_cmpfloat(fabs(30791.91836735 - ffm_vector_get(coef->w, 1)), <, 1e-6);
  g_assert_cmpfloat(fabs(253.89744249 - ffm_matrix_get(coef->V, 0, 0)), <,
                    1e-6);
  g_assert_cmpfloat(fabs(400 - ffm_matrix_get(coef->V, 0, 1)), <, 1e-6);

  param.n_iter = 99;
  sparse_fit(coef, pFix->X, NULL, pFix->y, NULL, param);

  g_assert_cmpfloat(fabs(210911.940403 - coef->w_0), <, 1e-7);
  g_assert_cmpfloat(fabs(-322970.68313639 - ffm_vector_get(coef->w, 0)), <,
                    1e-6);
  g_assert_cmpfloat(fabs(51927.60978978 - ffm_vector_get(coef->w, 1)), <, 1e-6);
  g_assert_cmpfloat(fabs(94.76612018 - ffm_matrix_get(coef->V, 0, 0)), <, 1e-6);
  g_assert_cmpfloat(fabs(400 - ffm_matrix_get(coef->V, 0, 1)), <, 1e-6);

  free_ffm_coef(coef);
}

void test_sparse_als_first_order_interactions(TestFixture_T *pFix,
                                              gconstpointer pg) {
  ffm_vector *y_pred = ffm_vector_calloc(5);

  int n_features = pFix->X->n;
  int k = 0;
  ffm_coef *coef = alloc_fm_coef(n_features, k, false);
  ffm_param param = {.n_iter = 500,
                     .init_sigma = 0.1,
                     .SOLVER = SOLVER_ALS,
                     .TASK = TASK_REGRESSION};
  sparse_fit(coef, pFix->X, NULL, pFix->y, NULL, param);
  sparse_predict(coef, pFix->X, y_pred);

  /* reference values from sklearn LinearRegression
  y_pred:  [ 321.05084746  346.6779661   -40.15254237  321.05084746
  790.37288136]
  coef: [  69.6779661   152.16949153]
  mse: 3134.91525424 */
  g_assert_cmpfloat(fabs(321.05084746 - ffm_vector_get(y_pred, 0)), <, 1e-6);
  g_assert_cmpfloat(fabs(346.6779661 - ffm_vector_get(y_pred, 1)), <, 1e-6);
  g_assert_cmpfloat(fabs(-40.15254237 - ffm_vector_get(y_pred, 2)), <, 1e-6);
  g_assert_cmpfloat(fabs(321.05084746 - ffm_vector_get(y_pred, 3)), <, 1e-6);
  g_assert_cmpfloat(fabs(790.37288136 - ffm_vector_get(y_pred, 4)), <, 1e-6);

  ffm_vector_free(y_pred);
  free_ffm_coef(coef);
}

void test_sparse_als_second_interactions(TestFixture_T *pFix,
                                         gconstpointer pg) {
  ffm_vector *y_pred = ffm_vector_calloc(5);

  int n_features = pFix->X->n;
  int k = 2;
  ffm_coef *coef = alloc_fm_coef(n_features, k, false);
  ffm_param param = {.n_iter = 1000, .init_sigma = 0.1, .SOLVER = SOLVER_ALS};
  sparse_fit(coef, pFix->X, NULL, pFix->y, NULL, param);
  sparse_predict(coef, pFix->X, y_pred);

  /* reference values from sklearn LinearRegression
  y_pred: [ 298.  266.   29.  298.  848.]
  coeff: [  9.   2.  40.]
  mse: 4.53374139449e-27 */
  g_assert_cmpfloat(fabs(298 - ffm_vector_get(y_pred, 0)), <, 1e-4);
  g_assert_cmpfloat(fabs(266 - ffm_vector_get(y_pred, 1)), <, 1e-4);
  g_assert_cmpfloat(fabs(29 - ffm_vector_get(y_pred, 2)), <, 1e-3);
  g_assert_cmpfloat(fabs(298 - ffm_vector_get(y_pred, 3)), <, 1e-4);
  g_assert_cmpfloat(fabs(848.0 - ffm_vector_get(y_pred, 4)), <, 1e-4);

  ffm_vector_free(y_pred);
  free_ffm_coef(coef);
}

void test_sparse_mcmc_second_interactions(TestFixture_T *pFix,
                                          gconstpointer pg) {
  int n_features = pFix->X->n;
  int n_samples = pFix->X->m;
  int k = 2;
  ffm_coef *coef = alloc_fm_coef(n_features, k, false);
  ffm_vector *y_pred = ffm_vector_calloc(n_samples);
  ffm_param param = {.n_iter = 100,
                     .init_sigma = 0.1,
                     .SOLVER = SOLVER_MCMC,
                     .TASK = TASK_REGRESSION,
                     .rng_seed = 1234};
  sparse_fit(coef, pFix->X, pFix->X, pFix->y, y_pred, param);

  g_assert_cmpfloat(ffm_r2_score(pFix->y, y_pred), >, .98);

  ffm_vector_free(y_pred);
  free_ffm_coef(coef);
}

void test_sparse_mcmc_second_interactions_classification(TestFixture_T *pFix,
                                                         gconstpointer pg) {
  int n_features = pFix->X->n;
  int n_samples = pFix->X->m;
  int k = 2;
  ffm_vector_make_labels(pFix->y);
  ffm_coef *coef = alloc_fm_coef(n_features, k, false);
  ffm_vector *y_pred = ffm_vector_calloc(n_samples);
  ffm_param param = {.n_iter = 10,
                     .init_sigma = 0.1,
                     .SOLVER = SOLVER_MCMC,
                     .TASK = TASK_CLASSIFICATION};
  sparse_fit(coef, pFix->X, pFix->X, pFix->y, y_pred, param);

  g_assert_cmpfloat(ffm_vector_accuracy(pFix->y, y_pred), >=, .98);

  ffm_vector_free(y_pred);
  free_ffm_coef(coef);
}

void test_train_test_of_different_size(TestFixture_T *pFix, gconstpointer pg) {
  int n_features = pFix->X->n;
  int k = 2;

  int n_samples_short = 3;
  int m = n_samples_short;
  int n = n_features;
  cs *X = cs_spalloc(m, n, m * n, 1, 1); /* create triplet identity matrix */
  cs_entry(X, 0, 0, 6);
  cs_entry(X, 0, 1, 1);
  cs_entry(X, 1, 0, 2);
  cs_entry(X, 1, 1, 3);
  cs_entry(X, 2, 0, 3);
  cs *X_csc = cs_compress(X); /* A = compressed-column form of T */
  cs *X_t = cs_transpose(X_csc, 1);
  cs_spfree(X);

  ffm_vector *y = ffm_vector_calloc(n_samples_short);
  // y [ 298 266 29 298 848 ]
  y->data[0] = 298;
  y->data[1] = 266;
  y->data[2] = 29;

  ffm_coef *coef = alloc_fm_coef(n_features, k, false);
  ffm_vector *y_pred = ffm_vector_calloc(n_samples_short);

  ffm_param param = {.n_iter = 20, .init_sigma = 0.01};
  // test: train > test

  param.SOLVER = SOLVER_ALS;
  sparse_fit(coef, pFix->X, NULL, pFix->y, NULL, param);
  sparse_predict(coef, X_csc, y_pred);
  param.TASK = TASK_CLASSIFICATION;
  sparse_fit(coef, pFix->X, NULL, pFix->y, NULL, param);
  sparse_predict(coef, X_csc, y_pred);

  param.SOLVER = SOLVER_MCMC;
  param.TASK = TASK_CLASSIFICATION;
  sparse_fit(coef, pFix->X, X_csc, pFix->y, y_pred, param);
  param.TASK = TASK_REGRESSION;
  sparse_fit(coef, pFix->X, X_csc, pFix->y, y_pred, param);

  // test: train < test
  param.SOLVER = SOLVER_MCMC;
  param.TASK = TASK_CLASSIFICATION;
  sparse_fit(coef, X_csc, pFix->X, y_pred, pFix->y, param);
  param.TASK = TASK_REGRESSION;
  sparse_fit(coef, X_csc, pFix->X, y_pred, pFix->y, param);

  param.SOLVER = SOLVER_ALS;
  sparse_fit(coef, X_csc, NULL, y_pred, NULL, param);
  sparse_predict(coef, pFix->X, pFix->y);
  param.TASK = TASK_CLASSIFICATION;
  sparse_fit(coef, X_csc, NULL, y_pred, NULL, param);
  sparse_predict(coef, pFix->X, pFix->y);

  ffm_vector_free(y_pred);
  free_ffm_coef(coef);
  cs_spfree(X_t);
  cs_spfree(X_csc);
}

void test_sparse_als_generated_data(void) {
  int n_features = 10;
  int n_samples = 100;
  int k = 2;

  TestFixture_T *data = makeTestFixture(124, n_samples, n_features, k);

  ffm_vector *y_pred = ffm_vector_calloc(n_samples);

  ffm_coef *coef = alloc_fm_coef(n_features, k, false);
  ffm_param param = {.n_iter = 50, .init_sigma = 0.01, .SOLVER = SOLVER_ALS};
  param.init_lambda_w = 23.5;
  param.init_lambda_V = 23.5;
  sparse_fit(coef, data->X, NULL, data->y, NULL, param);
  sparse_predict(coef, data->X, y_pred);

  g_assert_cmpfloat(ffm_r2_score(data->y, y_pred), >, 0.85);

  ffm_vector_free(y_pred);
  free_ffm_coef(coef);
  TestFixtureDestructor(data, NULL);
}

void test_hyerparameter_sampling(void) {
  ffm_rng *rng = ffm_rng_seed(12345);

  int n_features = 20;
  int n_samples = 150;
  int k = 1;  // don't just change k, the rank is hard coded in the test
              // (ffm_vector_get(coef->lambda_V, 0);)

  int n_replication = 40;
  int n_draws = 1000;
  ffm_vector *alpha_rep = ffm_vector_calloc(n_replication);
  ffm_vector *lambda_w_rep = ffm_vector_calloc(n_replication);
  ffm_vector *lambda_V_rep = ffm_vector_calloc(n_replication);
  ffm_vector *mu_w_rep = ffm_vector_calloc(n_replication);
  ffm_vector *mu_V_rep = ffm_vector_calloc(n_replication);
  ffm_vector *err = ffm_vector_alloc(n_samples);

  for (int j = 0; j < n_replication; j++) {
    TestFixture_T *data = makeTestFixture(124, n_samples, n_features, k);
    ffm_coef *coef = data->coef;

    sparse_predict(coef, data->X, err);
    ffm_vector_scale(err, -1);
    ffm_vector_add(err, data->y);

    // make sure that distribution is converged bevore selecting
    // reference / init values
    for (int l = 0; l < 50; l++) sample_hyper_parameter(coef, err, rng);

    double alpha_init = coef->alpha;
    double lambda_w_init = coef->lambda_w;
    double lambda_V_init = ffm_vector_get(coef->lambda_V, 0);
    double mu_w_init = coef->mu_w;
    double mu_V_init = ffm_vector_get(coef->mu_V, 0);

    double alpha_count = 0;
    double lambda_w_count = 0, lambda_V_count = 0;
    double mu_w_count = 0, mu_V_count = 0;

    for (int l = 0; l < n_draws; l++) {
      sample_hyper_parameter(coef, err, rng);
      if (alpha_init > coef->alpha) alpha_count++;
      if (lambda_w_init > coef->lambda_w) lambda_w_count++;
      if (lambda_V_init > ffm_vector_get(coef->lambda_V, 0)) lambda_V_count++;
      if (mu_w_init > coef->mu_w) mu_w_count++;
      if (mu_V_init > ffm_vector_get(coef->mu_V, 0)) mu_V_count++;
    }
    ffm_vector_set(alpha_rep, j, alpha_count / (n_draws + 1));
    ffm_vector_set(lambda_w_rep, j, lambda_w_count / (n_draws + 1));
    ffm_vector_set(lambda_V_rep, j, lambda_V_count / (n_draws + 1));
    ffm_vector_set(mu_w_rep, j, mu_w_count / (n_draws + 1));
    ffm_vector_set(mu_V_rep, j, mu_V_count / (n_draws + 1));

    TestFixtureDestructor(data, NULL);
  }
  double chi_alpha = 0;
  for (int i = 0; i < n_replication; i++)
    chi_alpha +=
        ffm_pow_2(gsl_cdf_ugaussian_Qinv(ffm_vector_get(alpha_rep, i)));
  g_assert_cmpfloat(gsl_ran_chisq_pdf(chi_alpha, n_replication), <, .05);

  double chi_lambda_w = 0;
  for (int i = 0; i < n_replication; i++)
    chi_lambda_w +=
        ffm_pow_2(gsl_cdf_ugaussian_Qinv(ffm_vector_get(lambda_w_rep, i)));
  g_assert_cmpfloat(gsl_ran_chisq_pdf(chi_lambda_w, n_replication), <, .05);

  double chi_lambda_V = 0;
  for (int i = 0; i < n_replication; i++)
    chi_lambda_V +=
        ffm_pow_2(gsl_cdf_ugaussian_Qinv(ffm_vector_get(lambda_V_rep, i)));
  g_assert_cmpfloat(gsl_ran_chisq_pdf(chi_lambda_V, n_replication), <, .05);

  double chi_mu_w = 0;
  for (int i = 0; i < n_replication; i++)
    chi_mu_w += ffm_pow_2(gsl_cdf_ugaussian_Qinv(ffm_vector_get(mu_w_rep, i)));
  g_assert_cmpfloat(gsl_ran_chisq_pdf(chi_mu_w, n_replication), <, .05);

  double chi_mu_V = 0;
  for (int i = 0; i < n_replication; i++)
    chi_mu_V += ffm_pow_2(gsl_cdf_ugaussian_Qinv(ffm_vector_get(mu_V_rep, i)));
  g_assert_cmpfloat(gsl_ran_chisq_pdf(chi_mu_V, n_replication), <, .05);

  ffm_vector_free_all(alpha_rep, lambda_w_rep, lambda_V_rep, mu_w_rep, mu_V_rep,
                      err);
  ffm_rng_free(rng);
}
Exemple #19
0
void buildCSp ( zeroCircuit *node, cs *arrayC, hashTable *namTab, int kPos )
{
	int posn1;
	int posn2;
	double tmp;

	struct linear_element *element;

	element = node->linElement;


	switch ( node->type )
	{
	case 0:
		switch( node->linElement->element )
		{
		case 4:
			if ( ( strcmp( node->linElement->connectors[0], "0\0" ) ) && ( strcmp( node->linElement->connectors[1], "0\0" ) ) )
			{
				//posn1 = findPlace ( node->linElement->connectors[0], &nodes );
				//posn2 = findPlace ( node->linElement->connectors[1], &nodes );

				posn1 = findHash ( namTab, node->linElement->connectors[0] );
				posn2 = findHash ( namTab, node->linElement->connectors[1] );

				tmp = (-1.0) * node->linElement->value;
				cs_entry(arrayC,posn1,posn2,tmp);
				cs_entry(arrayC,posn2,posn1,tmp);

			}

			if ( strcmp( node->linElement->connectors[0], "0\0" ) )
			{
				//posn1 = findPlace ( node->linElement->connectors[0], &nodes );
				posn1 = findHash ( namTab, node->linElement->connectors[0] );
				tmp = node->linElement->value;
				cs_entry(arrayC,posn1,posn1,tmp);
			}

			if ( strcmp( node->linElement->connectors[1], "0\0" ) )
			{
				//posn2 = findPlace ( node->linElement->connectors[1], &nodes );
				posn2 = findHash ( namTab, node->linElement->connectors[1] );
				tmp = node->linElement->value;
				cs_entry(arrayC,posn2,posn2,tmp);
			}

			break;

		case 5:

			tmp = -node->linElement->value;
			cs_entry(arrayC, kPos + namTab->currPos - 1, kPos + namTab->currPos - 1, tmp);
			break;
		}
		break;

	case 1:
		//irrelevant
		break;
	}

}