int main(void) { cs *T, *A, *B; int m = 100, n = 3; T = cs_load(stdin); A = cs_compress(T); B = blkdiag(A, m, n); printf("B is %d x %d\n", B->m, B->n); sparseprint(B); cs_spfree(T); cs_spfree(A); cs_spfree(B); // Test the block diagonal feature // cs *T, *L, *Lt, *A, *X, *B; // css *S; // T = cs_load(stdin); // L = cs_compress(T); // Lt = cs_transpose(L, 1); // A = cs_multiply(L, Lt); // cs_spfree(T); // sparseprint(A); // S = cs_schol(0, A); // B = speye(A->n); // X = mldivide_chol(A, S, B); // sparseprint(X); }
/** * @brief Creates the penalty matrix D tilde of order k. * Returns the matrix Dk premultipied by a diagonal * matrix of weights. * * @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_dktil (int n, int k, const double * x) { cs * delta_k; cs * delta_k_cp; cs * Dk; cs * Dktil; int i; Dk = tf_calc_dk(n, k, x); /* Deal with k=0 separately */ if(k == 0) return Dk; /* Construct diagonal matrix of differences: */ delta_k = cs_spalloc(n-k, n-k, (n-k), 1, 1); for(i = 0; i < n - k; i++) { delta_k->p[i] = i; delta_k->i[i] = i; delta_k->x[i] = k / (x[k + i] - x[i]); } delta_k->nz = n-k; delta_k_cp = cs_compress(delta_k); Dktil = cs_multiply(delta_k_cp, Dk); cs_spfree(Dk); cs_spfree(delta_k); cs_spfree(delta_k_cp); return Dktil; }
void read_diag_blk(int argc, char* argv[], Diag_Blk* db){ int m,n,blk_n; double* blk; double* blk_lu; int* ipiv; cs* csblk; int van = atoi(argv[9]); int pvan = atoi(argv[10]); int nlevel = argc - 13; for(int ii = 0; ii < nlevel; ii++){ // printf("readcsMatrix: level = %d, size = %d\n",ii,db->blk_size[ii]);/// if((ii < db->sparse_level && db->blk_size[ii] < 1e4) || (van > pvan && ii == nlevel - 1)){ // coarse-lifted level readVector(argv[13 + ii],n,blk); blk_n = sqrt(n); blk_lu = new double[blk_n * blk_n]; ipiv = new int[blk_n]; for(int ii = 0; ii < n; ii++) blk_lu[ii] = blk[ii]; lu_init(blk_n,blk_n,blk_lu,ipiv); db->dense_blk[ii] = blk; db->dense_lu[ii] = blk_lu; db->ipiv[ii] = ipiv; db->blk_size[ii] = blk_n; }else{ readcsMatrix(argv[13+ii], csblk); db->sparse_blk[ii - db->sparse_level] = cs_compress(csblk); db->blk_size[ii] = csblk->n; cs_spfree(csblk); } } }
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; }
/* read a problem from a file; use %g for integers to avoid int conflicts */ problem *get_problem (FILE *f, double tol) { cs *T, *A, *C ; int sym, m, n, mn, nz1, nz2 ; problem *Prob ; Prob = cs_calloc (1, sizeof (problem)) ; if (!Prob) return (NULL) ; T = cs_load (f) ; /* load triplet matrix T from a file */ Prob->A = A = cs_compress (T) ; /* A = compressed-column form of T */ cs_spfree (T) ; /* clear T */ if (!cs_dupl (A)) return (free_problem (Prob)) ; /* sum up duplicates */ Prob->sym = sym = is_sym (A) ; /* determine if A is symmetric */ m = A->m ; n = A->n ; mn = CS_MAX (m,n) ; nz1 = A->p [n] ; cs_dropzeros (A) ; /* drop zero entries */ nz2 = A->p [n] ; if (tol > 0) cs_droptol (A, tol) ; /* drop tiny entries (just to test) */ Prob->C = C = sym ? make_sym (A) : A ; /* C = A + triu(A,1)', or C=A */ if (!C) return (free_problem (Prob)) ; printf ("\n--- Matrix: %g-by-%g, nnz: %g (sym: %g: nnz %g), norm: %8.2e\n", (double) m, (double) n, (double) (A->p [n]), (double) sym, (double) (sym ? C->p [n] : 0), cs_norm (C)) ; if (nz1 != nz2) printf ("zero entries dropped: %g\n", (double) (nz1 - nz2)); if (nz2 != A->p [n]) printf ("tiny entries dropped: %g\n", (double) (nz2 - A->p [n])) ; Prob->b = cs_malloc (mn, sizeof (double)) ; Prob->x = cs_malloc (mn, sizeof (double)) ; Prob->resid = cs_malloc (mn, sizeof (double)) ; return ((!Prob->b || !Prob->x || !Prob->resid) ? free_problem (Prob) : Prob) ; }
cs* NN_load_spdata(FILE* fp) { cs *triplet,*compressed; triplet = cs_load(fp); compressed = cs_compress(triplet); cs_spfree(triplet); return compressed; }
/** * @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; }
bool solve_sparse(int* px,int *py,double *pv,double *pB,int sz,int N) { cs a; a.m = a.n = N; a.nz = a.nzmax = sz; a.p = px; a.i = py; a.x = pv; cs *pa = cs_compress(&a); int nRet = cs_cholsol(1,pa,pB); cs_spfree(pa); return 0 != nRet; }
cs * formKKT(const AMatrix * A, const Settings * s) { /* ONLY UPPER TRIANGULAR PART IS STUFFED * forms column compressed KKT matrix * assumes column compressed form A matrix * * forms upper triangular part of [I A'; A -I] */ scs_int j, k, kk; cs * K_cs; /* I at top left */ const scs_int Anz = A->p[A->n]; const scs_int Knzmax = A->n + A->m + Anz; cs * K = cs_spalloc(A->m + A->n, A->m + A->n, Knzmax, 1, 1); #if EXTRAVERBOSE > 0 scs_printf("forming KKT\n"); #endif if (!K) { return NULL; } kk = 0; for (k = 0; k < A->n; k++) { K->i[kk] = k; K->p[kk] = k; K->x[kk] = s->rho_x; kk++; } /* A^T at top right : CCS: */ for (j = 0; j < A->n; j++) { for (k = A->p[j]; k < A->p[j + 1]; k++) { K->p[kk] = A->i[k] + A->n; K->i[kk] = j; K->x[kk] = A->x[k]; kk++; } } /* -I at bottom right */ for (k = 0; k < A->m; k++) { K->i[kk] = k + A->n; K->p[kk] = k + A->n; K->x[kk] = -1; kk++; } /* assert kk == Knzmax */ K->nz = Knzmax; K_cs = cs_compress(K); cs_spfree(K); return (K_cs); }
CSparseMatrix* NM_csc(NumericsMatrix *A) { if(!NM_sparse(A)->csc) { assert(A->matrix2); A->matrix2->csc = cs_compress(NM_triplet(A)); /* triplet -> csc * with allocation */ assert(A->matrix2->csc); NM_clearCSCTranspose(A); } return A->matrix2->csc; }
cs* CSBuilder::buildCS(int *buf_x,int *buf_y, double *buf_v) const { std::map<long,double>::const_iterator it = this->_elems.begin(); int i = 0; for(; it!=this->_elems.end(); ++i,++it) { int ik = it->first; double iv = it->second; buf_x[i] = ik % this->_ncols; buf_y[i] = ik / this->_ncols; buf_v[i] = iv; } cs c; c.m = this->_ncols; c.n = this->_nrows; c.nz = c.nzmax = this->_elems.size(); c.p = buf_x; c.i = buf_y; c.x = buf_v; return cs_compress(&c); }
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; }
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; }
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)) ; }
/* Alart & Curnier solver for sparse global problem */ void gfc3d_nonsmooth_Newton_AlartCurnier( GlobalFrictionContactProblem* problem, double *reaction, double *velocity, double *globalVelocity, int *info, SolverOptions* options) { assert(problem); assert(reaction); assert(velocity); assert(info); assert(options); assert(problem->dimension == 3); assert(options->iparam); assert(options->dparam); assert(problem->q); assert(problem->mu); assert(problem->M); assert(problem->H); assert(!problem->M->matrix0); // assert(problem->M->matrix1); assert(!options->iparam[4]); // only host /* M is square */ assert(problem->M->size0 == problem->M->size1); assert(problem->M->size0 == problem->H->size0); unsigned int iter = 0; unsigned int itermax = options->iparam[0]; unsigned int erritermax = options->iparam[7]; if (erritermax == 0) { /* output a warning here */ erritermax = 1; } assert(itermax > 0); assert(options->iparam[3] > 0); double tolerance = options->dparam[0]; assert(tolerance > 0); if (verbose > 0) printf("------------------------ GFC3D - _nonsmooth_Newton_AlartCurnier - Start with tolerance = %g\n", tolerance); /* sparse triplet storage */ NM_triplet(problem->M); NM_triplet(problem->H); unsigned int ACProblemSize = sizeOfPsi(NM_triplet(problem->M), NM_triplet(problem->H)); unsigned int globalProblemSize = (unsigned)NM_triplet(problem->M)->m; unsigned int localProblemSize = problem->H->size1; assert((int)localProblemSize == problem->numberOfContacts * problem->dimension); assert((int)globalProblemSize == problem->H->size0); /* size(velocity) == * Htrans*globalVelocity */ AlartCurnierFun3x3Ptr computeACFun3x3 = NULL; switch (options->iparam[10]) { case 0: { computeACFun3x3 = &computeAlartCurnierSTD; break; } case 1: { computeACFun3x3 = &computeAlartCurnierJeanMoreau; break; }; case 2: { computeACFun3x3 = &fc3d_AlartCurnierFunctionGenerated; break; } case 3: { computeACFun3x3 = &fc3d_AlartCurnierJeanMoreauFunctionGenerated; break; } } if(options->iparam[9] == 0) { /* allocate memory */ assert(options->dWork == NULL); assert(options->iWork == NULL); options->dWork = (double *) malloc( (localProblemSize + /* F */ 3 * localProblemSize + /* A */ 3 * localProblemSize + /* B */ localProblemSize + /* rho */ ACProblemSize + /* psi */ ACProblemSize + /* rhs */ ACProblemSize + /* tmp2 */ ACProblemSize + /* tmp3 */ ACProblemSize /* solution */) * sizeof(double)); /* XXX big hack here */ options->iWork = (int *) malloc( (3 * localProblemSize + /* iA */ 3 * localProblemSize + /* iB */ 3 * localProblemSize + /* pA */ 3 * localProblemSize) /* pB */ * sizeof(csi)); options->iparam[9] = 1; } assert(options->dWork != NULL); assert(options->iWork != NULL); double *F = options->dWork; double *A = F + localProblemSize; double *B = A + 3 * localProblemSize; double *rho = B + 3 * localProblemSize; double * psi = rho + localProblemSize; double * rhs = psi + ACProblemSize; double * tmp2 = rhs + ACProblemSize; double * tmp3 = tmp2 + ACProblemSize; double * solution = tmp3 + ACProblemSize; /* XXX big hack --xhub*/ csi * iA = (csi *)options->iWork; csi * iB = iA + 3 * localProblemSize; csi * pA = iB + 3 * localProblemSize; csi * pB = pA + 3 * localProblemSize; CSparseMatrix A_; CSparseMatrix B_; CSparseMatrix *J; A_.p = pA; B_.p = pB; A_.i = iA; B_.i = iB; init3x3DiagBlocks(problem->numberOfContacts, A, &A_); init3x3DiagBlocks(problem->numberOfContacts, B, &B_); J = cs_spalloc(NM_triplet(problem->M)->n + A_.m + B_.m, NM_triplet(problem->M)->n + A_.m + B_.m, NM_triplet(problem->M)->nzmax + 2*NM_triplet(problem->H)->nzmax + 2*A_.n + A_.nzmax + B_.nzmax, 1, 1); assert(A_.n == problem->H->size1); assert(A_.nz == problem->numberOfContacts * 9); assert(B_.n == problem->H->size1); assert(B_.nz == problem->numberOfContacts * 9); fc3d_AlartCurnierFunction( localProblemSize, computeACFun3x3, reaction, velocity, problem->mu, rho, F, A, B); csi Astart = initACPsiJacobian(NM_triplet(problem->M), NM_triplet(problem->H), &A_, &B_, J); assert(Astart > 0); assert(A_.m == A_.n); assert(B_.m == B_.n); assert(A_.m == problem->H->size1); // compute rho here for(unsigned int i = 0; i < localProblemSize; ++i) rho[i] = 1.; // direction for(unsigned int i = 0; i < ACProblemSize; ++i) rhs[i] = 0.; // quick hack to make things work // need to use the functions from NumericsMatrix --xhub NumericsMatrix *AA_work = createNumericsMatrix(NM_SPARSE, (int)J->m, (int)J->n); NumericsSparseMatrix* SM = newNumericsSparseMatrix(); SM->triplet = J; NumericsMatrix *AA = createNumericsMatrixFromData(NM_SPARSE, (int)J->m, (int)J->n, SM); info[0] = 1; /* update local velocity from global velocity */ /* an assertion ? */ cblas_dcopy(localProblemSize, problem->b, 1, velocity, 1); NM_tgemv(1., problem->H, globalVelocity, 1, velocity); double linear_solver_residual=0.0; while(iter++ < itermax) { /* compute psi */ ACPsi(problem, computeACFun3x3, globalVelocity, reaction, velocity, rho, psi); /* compute A & B */ fc3d_AlartCurnierFunction(localProblemSize, computeACFun3x3, reaction, velocity, problem->mu, rho, F, A, B); /* update J */ updateACPsiJacobian(NM_triplet(problem->M), NM_triplet(problem->H), &A_, &B_, J, Astart); /* rhs = -psi */ cblas_dcopy(ACProblemSize, psi, 1, rhs, 1); cblas_dscal(ACProblemSize, -1., rhs, 1); /* get compress column storage for linear ops */ CSparseMatrix* Jcsc = cs_compress(J); /* Solve: J X = -psi */ /* Solve: AWpB X = -F */ NM_copy(AA, AA_work); int info_solver = NM_gesv(AA_work, rhs); if (info_solver > 0) { fprintf(stderr, "------------------------ GFC3D - NSN_AC - solver failed info = %d\n", info_solver); break; info[0] = 2; CHECK_RETURN(!cs_check_triplet(NM_triplet(AA_work))); } /* Check the quality of the solution */ if (verbose > 0) { cblas_dcopy_msan(ACProblemSize, psi, 1, tmp3, 1); NM_gemv(1., AA, rhs, 1., tmp3); linear_solver_residual = cblas_dnrm2(ACProblemSize, tmp3, 1); /* fprintf(stderr, "fc3d esolve: linear equation residual = %g\n", */ /* cblas_dnrm2(problemSize, tmp3, 1)); */ /* for the component wise scaled residual: cf mumps & * http://www.netlib.org/lapack/lug/node81.html */ } /* line search */ double alpha = 1; /* set current solution */ for(unsigned int i = 0; i < globalProblemSize; ++i) { solution[i] = globalVelocity[i]; } for(unsigned int i = 0; i < localProblemSize; ++i) { solution[i+globalProblemSize] = velocity[i]; solution[i+globalProblemSize+localProblemSize] = reaction[i]; } DEBUG_EXPR_WE( for(unsigned int i = 0; i < globalProblemSize; ++i) { printf("globalVelocity[%i] = %6.4e\n",i,globalVelocity[i]); } for(unsigned int i = 0; i < localProblemSize; ++i) { printf("velocity[%i] = %6.4e\t",i,velocity[i]); printf("reaction[%i] = %6.4e\n",i,reaction[i]); } ); int info_ls = _globalLineSearchSparseGP(problem, computeACFun3x3, solution, rhs, globalVelocity, reaction, velocity, problem->mu, rho, F, psi, Jcsc, tmp2, &alpha, 100); cs_spfree(Jcsc); if(!info_ls) { cblas_daxpy(ACProblemSize, alpha, rhs, 1, solution, 1); } else { cblas_daxpy(ACProblemSize, 1, rhs, 1., solution, 1); } for(unsigned int e = 0 ; e < globalProblemSize; ++e) { globalVelocity[e] = solution[e]; } for(unsigned int e = 0 ; e < localProblemSize; ++e) { velocity[e] = solution[e+globalProblemSize]; } for(unsigned int e = 0; e < localProblemSize; ++e) { reaction[e] = solution[e+globalProblemSize+localProblemSize]; } options->dparam[1] = INFINITY; if(!(iter % erritermax)) { gfc3d_compute_error(problem, reaction, velocity, globalVelocity, tolerance, &(options->dparam[1])); } if(verbose > 0) printf("------------------------ GFC3D - NSN_AC - iteration %d, residual = %g, linear solver residual = %g, tolerance = %g \n", iter, options->dparam[1],linear_solver_residual, tolerance); if(options->dparam[1] < tolerance) { info[0] = 0; break; } }
cs *read_matrix(const char *filename, MM_typecode &matcode) { LogInfo("Reading Matrix from " << std::string(filename) << "\n"); FILE *file = fopen(filename, "r"); if (!file) { LogError("Error: Cannot read file " << std::string(filename) << "\n"); return NULL; } LogInfo("Reading Matrix Market banner..."); if (mm_read_banner(file, &matcode) != 0) { LogError("Error: Could not process Matrix Market banner\n"); fclose(file); return NULL; } if (!mm_is_matrix(matcode) || !mm_is_sparse(matcode) || mm_is_complex(matcode)) { LogError( "Error: Unsupported matrix format - Must be real and sparse\n"); fclose(file); return NULL; } Int M, N, nz; if ((mm_read_mtx_crd_size(file, &M, &N, &nz)) != 0) { LogError("Error: Could not parse matrix dimension and size.\n"); fclose(file); return NULL; } if (M != N) { LogError("Error: Matrix must be square.\n"); fclose(file); return NULL; } LogInfo("Reading matrix data...\n"); Int *I = (Int *)SuiteSparse_malloc(static_cast<size_t>(nz), sizeof(Int)); Int *J = (Int *)SuiteSparse_malloc(static_cast<size_t>(nz), sizeof(Int)); double *val = (double *)SuiteSparse_malloc(static_cast<size_t>(nz), sizeof(double)); if (!I || !J || !val) { LogError("Error: Ran out of memory in Mongoose::read_matrix\n"); SuiteSparse_free(I); SuiteSparse_free(J); SuiteSparse_free(val); fclose(file); return NULL; } mm_read_mtx_crd_data(file, M, N, nz, I, J, val, matcode); fclose(file); // Close the file for (Int k = 0; k < nz; k++) { --I[k]; --J[k]; if (mm_is_pattern(matcode)) val[k] = 1; } cs *A = (cs *)SuiteSparse_malloc(1, sizeof(cs)); if (!A) { LogError("Error: Ran out of memory in Mongoose::read_matrix\n"); SuiteSparse_free(I); SuiteSparse_free(J); SuiteSparse_free(val); return NULL; } A->nzmax = nz; A->m = M; A->n = N; A->p = J; A->i = I; A->x = val; A->nz = nz; LogInfo("Compressing matrix from triplet to CSC format...\n"); cs *compressed_A = cs_compress(A); cs_spfree(A); if (!compressed_A) { LogError("Error: Ran out of memory in Mongoose::read_matrix\n"); return NULL; } return compressed_A; }
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); } }
// Structure of the H tree defined by a matrix A consisting of 0, 1 and -1's cs * adjacency(int Np) { /* Size of A matrix dependent on Np: the number of levels of the local subtree * which is dependent on the number of cores and number of levels) Np = # levels - log2 (# cores), also Np = n_blocks(local) - 1 */ // Initialise the sparse matrix for filling cs *A, *T; int *Ti, *Tj; double *Tx; int m, n; m = POW_OF_2(Np-1) - 1; // number of rows of T n = POW_OF_2(Np) - 1; // number of cols of T T = cs_spalloc(m, n, 3*m, 1, 1); // create T with size m x n Ti = T->i; // array of ints: row indices (size nzmax = max number of entries) Tj = T->p; // array of ints: column indices (size nzmax = max number of entries) Tx = T->x; // array of doubles: numerical values (size nzmax = max number of entries) // Set the size of the lowest level grid int ncols = POW_OF_2((Np-1)/2); // equivalent to 2^((Np-1)/2) int nrows = POW_OF_2((Np-1)/2 + (Np-1)%2); int a, k = 0; int k1, k2 = 0; int row = 0; int col = POW_OF_2(Np-1); int xbranch = 0; // L loop: from bottom level up to the top of the tree (internal nodes) for (int L = Np - 1; L > 0; L--) { a = POW_OF_2(Np) - POW_OF_2(L+1); //b = (1 << N) - (1 << (L )); //c = (1 << N) - (1 << (L-1)); if (xbranch) { for (int j = 0; j < ncols; j+=2) { for (int i = 0; i < nrows; i++) { k1 = a + i + j*nrows; k2 = a + i + (j+1)*nrows; Ti[k] = row; Tj[k] = k1; Tx[k++] = 1; Ti[k] = row; Tj[k] = k2; Tx[k++] = 1; Ti[k] = row++; Tj[k] = col++; Tx[k++] = -1; } } ncols /= 2; } else { for (int j = 0; j < ncols; j++) { for (int i = 0; i < nrows; i+=2) { k1 = a + i + j*nrows; k2 = k1 + 1; Ti[k] = row; Tj[k] = k1; Tx[k++] = 1; Ti[k] = row; Tj[k] = k2; Tx[k++] = 1; Ti[k] = row++; Tj[k] = col++; Tx[k++] = -1; } } nrows /= 2; } xbranch = !xbranch; // switch xbranch 0 <--> 1 } T->nz = k; A = cs_compress(T); cs_spfree(T); //sparseprint(A); // good way to print sparse matrix! return A; }
int main(int argc, char *argv[]){ char c; int n=0, m=0; init(); FILE *fp=NULL; fp=fopen(argv[1],"r"); //Anoigma tou arxeiou if(fp==NULL){ //Elegxos an to arxeio anoikse kanonika, alliws termatismos.. printf("\nProblem opening file. Program terminated...\n"); return -1; } //Diavasma xaraktira kai antistoixi leitourgia analoga me auton (Provlepsi gia grammi sxoliwn kai gia telos arxeiou) c=fgetc(fp); do{ if(c=='V' || c=='v'){ m++; creatVoltList(fp); } else if(c=='I' || c=='i'){ creatAmberList(fp); } else if(c=='R' || c=='r'){ creatResistanceList(fp); } else if(c=='C' || c=='c'){ creatCapacitorList(fp); } else if(c=='L' || c=='l'){ m++; creatInductorList(fp); } else if(c=='D' || c=='d'){ creatDiodeList(fp); } else if(c=='M' || c=='m'){ creatMOSList(fp); } else if(c=='B' || c=='b'){ creatBJTList(fp); } else if(c=='%'){ c=fgetc(fp); while(c!='\n'&&(c!=EOF)){c=fgetc(fp);}/*MOVE TO NEXT LINE*/ } else if(c=='.'){ analysis(fp); } else{ } if(c!=EOF){c=fgetc(fp);} }while(!feof(fp)); fclose(fp); if(ground==0) { printf("No ground node! Program terminated!"); return -1; } else { printVoltList(rootV); printAmperList(rootI); printResistanceList(rootR); printCapacitorList(rootC); printInductorList(rootL); printDiodeList(rootD); printMosList(rootM); printBjttList(rootB); } n=count_nodes(); printf("\n m=%d , n=%d \n\n", m, n); int size=0; size = (n-1)+m; if(sparse_option == 0){ gsl_matrix* pinakasA = gsl_matrix_calloc(size,size); gsl_vector* pinakasB = gsl_vector_calloc(size); fill_matrix_A(pinakasA, pinakasB, n); fill_matrix_B(pinakasB); printf(" O pinakas A einai o: \n"); print2DMatrix(pinakasA, size); printf("\n O pinakas B einai o: \n"); print1DMatrix(pinakasB,size); printf("\n"); if(use_lu==1){ if(found_iter==1){ call_bi_cg(pinakasA, pinakasB, size); } else{ luDecomp(pinakasA, pinakasB, size); } } else if (use_cholesky==1){ if (found_iter==1){ call_cg(pinakasA, pinakasB, size); } else{ choleskyDecomp(pinakasA, pinakasB, size); } } } else { int i; cs* pinakasA_sparse = cs_spalloc(size,size,4*sparse_elements,1,1); double* pinakasB_sparse = (double *)calloc(size,sizeof(double)); double* pinakasX_sparse = (double *)calloc(size,sizeof(double)); fill_sparse_matrix_A(pinakasA_sparse, pinakasB_sparse,n); cs* pinakasC_sparse = cs_compress(pinakasA_sparse); cs_spfree(pinakasA_sparse); cs_dupl(pinakasC_sparse); if(use_lu==1){ if(found_iter==1){ call_bi_cg_sparse(pinakasC_sparse, pinakasB_sparse, pinakasX_sparse, size); } else{ luDecomp_sparse(pinakasC_sparse, pinakasB_sparse, pinakasX_sparse, size); } } else if (use_cholesky==1){ if (found_iter==1){ call_cg_sparse(pinakasC_sparse, pinakasB_sparse, pinakasX_sparse, size); } else{ choleskyDecomp_sparse(pinakasC_sparse, pinakasB_sparse, pinakasX_sparse, size); } } } return 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; }
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; }
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; }
/* [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 */ } }
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); }
mnaSpSystem *formatMnaTableSparse ( zeroCircuit *circuit, hashTable *names, int v_num, int l_num, int r_num, int i_num ) { int rows; int k_pos; int maxEstimated; zeroCircuit *cur; mnaSpSystem *finalSystem; cs *A, *Cm; //initialize k position k_pos = 0; finalSystem = ( mnaSpSystem * )malloc ( sizeof( mnaSpSystem ) ); rows = ( names->currPos ) + v_num + l_num ; //dimension of original matrix maxEstimated = 2 * ( 4 * r_num + 1 * v_num + 2 * i_num ); A = cs_spalloc(rows, rows, maxEstimated, 1, 1); if ( A == NULL ) { printf( "!!!WARNING!!! Table A was NOT allocated successfully\n" ); printf( "\t-Dimension of system to be allocated : %d\n\n", rows ); } //Transient Analysis : Build C if (cmdList->_transient == 1) { Cm = cs_spalloc(rows,rows,maxEstimated,1,1); } finalSystem->vector_B = (double *)calloc(rows, sizeof(double)); finalSystem->vector_X = (char **)malloc( rows * sizeof (char *) ); finalSystem->dim = rows; //for ( cur = circuit->next; (cur->linElement == NULL && cur->nonlinElement == NULL); cur = cur->next ) for( cur = circuit->next; ( (cur->linElement != NULL) || (cur->nonlinElement != NULL) ); cur = cur->next ) { if (( cur->linElement->element == 2 ) || ( cur->linElement->element == 5 )) //if element is voltage source or inductor { k_pos++; } addElementStampSparse ( cur, finalSystem, A, names, rows, k_pos ); //Transient Analysis : Build C if (cmdList->_transient == 1) { buildCSp( cur, Cm, names, k_pos); } } finalSystem->array_A = cs_compress(A); cs_dupl(finalSystem->array_A); cs_spfree(A); //Transient Analysis : Build C if (cmdList->_transient == 1) { finalSystem->array_C = cs_compress(Cm); cs_dupl(finalSystem->array_C); cs_spfree(Cm); } return ( finalSystem ); }