# SCM Repository

[matrix] Diff of /pkg/Matrix/src/Csparse.c
 [matrix] / pkg / Matrix / src / Csparse.c

# Diff of /pkg/Matrix/src/Csparse.c

revision 2646, Mon Feb 21 10:57:49 2011 UTC revision 2681, Mon Aug 1 20:43:16 2011 UTC
# Line 1  Line 1
1                          /* Sparse matrices in compressed column-oriented form */                          /* Sparse matrices in compressed column-oriented form */
2
3    #include <stdint.h> // C99 for int64_t
4  #include "Csparse.h"  #include "Csparse.h"
5  #include "Tsparse.h"  #include "Tsparse.h"
6  #include "chm_common.h"  #include "chm_common.h"
# Line 136  Line 138
138              }              }
139      }      }
140      if (!sorted)      if (!sorted)
141          /* cannot easily use cholmod_l_sort(.) ... -> "error out" :*/          /* cannot easily use cholmod_sort(.) ... -> "error out" :*/
142          return mkString(_("slot j is not increasing inside a column"));          return mkString(_("slot j is not increasing inside a column"));
143      else if(!strictly) /* sorted, but not strictly */      else if(!strictly) /* sorted, but not strictly */
144          return mkString(_("slot j is not *strictly* increasing inside a column"));          return mkString(_("slot j is not *strictly* increasing inside a column"));
# Line 154  Line 156
156      /* This loses the symmetry property, since cholmod_dense has none,      /* This loses the symmetry property, since cholmod_dense has none,
157       * BUT, much worse (FIXME!), it also transforms CHOLMOD_PATTERN ("n") matrices       * BUT, much worse (FIXME!), it also transforms CHOLMOD_PATTERN ("n") matrices
158       * to numeric (CHOLMOD_REAL) ones : */       * to numeric (CHOLMOD_REAL) ones : */
159      CHM_DN chxd = cholmod_l_sparse_to_dense(chxs, &c);      CHM_DN chxd = cholmod_sparse_to_dense(chxs, &c);
160      int Rkind = (chxs->xtype == CHOLMOD_PATTERN)? -1 : Real_kind(x);      int Rkind = (chxs->xtype == CHOLMOD_PATTERN)? -1 : Real_kind(x);
161      R_CheckStack();      R_CheckStack();
162
# Line 165  Line 167
167  SEXP Csparse_to_nz_pattern(SEXP x, SEXP tri)  SEXP Csparse_to_nz_pattern(SEXP x, SEXP tri)
168  {  {
169      CHM_SP chxs = AS_CHM_SP__(x);      CHM_SP chxs = AS_CHM_SP__(x);
170      CHM_SP chxcp = cholmod_l_copy(chxs, chxs->stype, CHOLMOD_PATTERN, &c);      CHM_SP chxcp = cholmod_copy(chxs, chxs->stype, CHOLMOD_PATTERN, &c);
171      int tr = asLogical(tri);      int tr = asLogical(tri);
172      R_CheckStack();      R_CheckStack();
173
# Line 230  Line 232
232
233  SEXP Csparse_to_matrix(SEXP x)  SEXP Csparse_to_matrix(SEXP x)
234  {  {
235      return chm_dense_to_matrix(cholmod_l_sparse_to_dense(AS_CHM_SP__(x), &c),      return chm_dense_to_matrix(cholmod_sparse_to_dense(AS_CHM_SP__(x), &c),
236                                 1 /*do_free*/, GET_SLOT(x, Matrix_DimNamesSym));                                 1 /*do_free*/, GET_SLOT(x, Matrix_DimNamesSym));
237  }  }
238
239  SEXP Csparse_to_Tsparse(SEXP x, SEXP tri)  SEXP Csparse_to_Tsparse(SEXP x, SEXP tri)
240  {  {
241      CHM_SP chxs = AS_CHM_SP__(x);      CHM_SP chxs = AS_CHM_SP__(x);
242      CHM_TR chxt = cholmod_l_sparse_to_triplet(chxs, &c);      CHM_TR chxt = cholmod_sparse_to_triplet(chxs, &c);
243      int tr = asLogical(tri);      int tr = asLogical(tri);
244      int Rkind = (chxs->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chxs->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
245      R_CheckStack();      R_CheckStack();
# Line 257  Line 259
259
260      if (!(chx->stype))      if (!(chx->stype))
261          error(_("Nonsymmetric matrix in Csparse_symmetric_to_general"));          error(_("Nonsymmetric matrix in Csparse_symmetric_to_general"));
262      chgx = cholmod_l_copy(chx, /* stype: */ 0, chx->xtype, &c);      chgx = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);
263      /* xtype: pattern, "real", complex or .. */      /* xtype: pattern, "real", complex or .. */
264      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",
265                                GET_SLOT(x, Matrix_DimNamesSym));                                GET_SLOT(x, Matrix_DimNamesSym));
# Line 270  Line 272
272      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
273      R_CheckStack();      R_CheckStack();
274
275      chgx = cholmod_l_copy(chx, /* stype: */ uploT, chx->xtype, &c);      chgx = cholmod_copy(chx, /* stype: */ uploT, chx->xtype, &c);
276      /* xtype: pattern, "real", complex or .. */      /* xtype: pattern, "real", complex or .. */
277      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",
278                                GET_SLOT(x, Matrix_DimNamesSym));                                GET_SLOT(x, Matrix_DimNamesSym));
# Line 282  Line 284
284       *       since cholmod (& cs) lacks sparse 'int' matrices */       *       since cholmod (& cs) lacks sparse 'int' matrices */
285      CHM_SP chx = AS_CHM_SP__(x);      CHM_SP chx = AS_CHM_SP__(x);
286      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
287      CHM_SP chxt = cholmod_l_transpose(chx, chx->xtype, &c);      CHM_SP chxt = cholmod_transpose(chx, chx->xtype, &c);
288      SEXP dn = PROTECT(duplicate(GET_SLOT(x, Matrix_DimNamesSym))), tmp;      SEXP dn = PROTECT(duplicate(GET_SLOT(x, Matrix_DimNamesSym))), tmp;
289      int tr = asLogical(tri);      int tr = asLogical(tri);
290      R_CheckStack();      R_CheckStack();
# Line 301  Line 303
303      CHM_SP      CHM_SP
304          cha = AS_CHM_SP(a),          cha = AS_CHM_SP(a),
305          chb = AS_CHM_SP(b),          chb = AS_CHM_SP(b),
306          chc = cholmod_l_ssmult(cha, chb, /*out_stype:*/ 0,          chc = cholmod_ssmult(cha, chb, /*out_stype:*/ 0,
307                                 /* values:= is_numeric (T/F) */ cha->xtype > 0,                                 /* values:= is_numeric (T/F) */ cha->xtype > 0,
308                                 /*out sorted:*/ 1, &c);                                 /*out sorted:*/ 1, &c);
309      const char *cl_a = class_P(a), *cl_b = class_P(b);      const char *cl_a = class_P(a), *cl_b = class_P(b);
# Line 352  Line 354
354      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2));
355      R_CheckStack();      R_CheckStack();
356
357      chTr = cholmod_l_transpose((tr) ? chb : cha, chb->xtype, &c);      chTr = cholmod_transpose((tr) ? chb : cha, chb->xtype, &c);
358      chc = cholmod_l_ssmult((tr) ? cha : chTr, (tr) ? chTr : chb,      chc = cholmod_ssmult((tr) ? cha : chTr, (tr) ? chTr : chb,
359                           /*out_stype:*/ 0, cha->xtype, /*out sorted:*/ 1, &c);                           /*out_stype:*/ 0, cha->xtype, /*out sorted:*/ 1, &c);
360      cholmod_l_free_sparse(&chTr, &c);      cholmod_free_sparse(&chTr, &c);
361
362      /* Preserve triangularity and unit-triangularity if appropriate;      /* Preserve triangularity and unit-triangularity if appropriate;
363       * see Csparse_Csparse_prod() for comments */       * see Csparse_Csparse_prod() for comments */
# Line 381  Line 383
383      CHM_SP cha = AS_CHM_SP(a);      CHM_SP cha = AS_CHM_SP(a);
384      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix(b));      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix(b));
385      CHM_DN chb = AS_CHM_DN(b_M);      CHM_DN chb = AS_CHM_DN(b_M);
386      CHM_DN chc = cholmod_l_allocate_dense(cha->nrow, chb->ncol, cha->nrow,      CHM_DN chc = cholmod_allocate_dense(cha->nrow, chb->ncol, cha->nrow,
387                                          chb->xtype, &c);                                          chb->xtype, &c);
388      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2));
389      double one[] = {1,0}, zero[] = {0,0};      double one[] = {1,0}, zero[] = {0,0};
# Line 398  Line 400
400          SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;          SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
401          cha = AS_CHM_SP(da);          cha = AS_CHM_SP(da);
402      }      }
403      cholmod_l_sdmult(cha, 0, one, zero, chb, chc, &c);      cholmod_sdmult(cha, 0, one, zero, chb, chc, &c);
404      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
405                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));
406      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
# Line 412  Line 414
414      CHM_SP cha = AS_CHM_SP(a);      CHM_SP cha = AS_CHM_SP(a);
415      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix(b));      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix(b));
416      CHM_DN chb = AS_CHM_DN(b_M);      CHM_DN chb = AS_CHM_DN(b_M);
417      CHM_DN chc = cholmod_l_allocate_dense(cha->ncol, chb->ncol, cha->ncol,      CHM_DN chc = cholmod_allocate_dense(cha->ncol, chb->ncol, cha->ncol,
418                                          chb->xtype, &c);                                          chb->xtype, &c);
419      SEXP dn = PROTECT(allocVector(VECSXP, 2)); int nprot = 2;      SEXP dn = PROTECT(allocVector(VECSXP, 2)); int nprot = 2;
420      double one[] = {1,0}, zero[] = {0,0};      double one[] = {1,0}, zero[] = {0,0};
# Line 422  Line 424
424          SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;          SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
425          cha = AS_CHM_SP(da);          cha = AS_CHM_SP(da);
426      }      }
427      cholmod_l_sdmult(cha, 1, one, zero, chb, chc, &c);      cholmod_sdmult(cha, 1, one, zero, chb, chc, &c);
428      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
429                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 1)));
430      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
# Line 445  Line 447
447  #endif  #endif
448      CHM_SP chcp, chxt,      CHM_SP chcp, chxt,
449          chx = (trip ?          chx = (trip ?
450                 cholmod_l_triplet_to_sparse(cht, cht->nnz, &c) :                 cholmod_triplet_to_sparse(cht, cht->nnz, &c) :
451                 AS_CHM_SP(x));                 AS_CHM_SP(x));
452      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2));
453      R_CheckStack();      R_CheckStack();
454
455      if (!tr) chxt = cholmod_l_transpose(chx, chx->xtype, &c);      if (!tr) chxt = cholmod_transpose(chx, chx->xtype, &c);
456      chcp = cholmod_l_aat((!tr) ? chxt : chx, (int *) NULL, 0, chx->xtype, &c);      chcp = cholmod_aat((!tr) ? chxt : chx, (int *) NULL, 0, chx->xtype, &c);
457      if(!chcp) {      if(!chcp) {
458          UNPROTECT(1);          UNPROTECT(1);
459          error(_("Csparse_crossprod(): error return from cholmod_l_aat()"));          error(_("Csparse_crossprod(): error return from cholmod_aat()"));
460      }      }
461      cholmod_l_band_inplace(0, chcp->ncol, chcp->xtype, chcp, &c);      cholmod_band_inplace(0, chcp->ncol, chcp->xtype, chcp, &c);
462      chcp->stype = 1;      chcp->stype = 1;
463      if (trip) cholmod_l_free_sparse(&chx, &c);      if (trip) cholmod_free_sparse(&chx, &c);
464      if (!tr) cholmod_l_free_sparse(&chxt, &c);      if (!tr) cholmod_free_sparse(&chxt, &c);
465      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
466                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),
467                                          (tr) ? 0 : 1)));                                          (tr) ? 0 : 1)));
# Line 480  Line 482
482      /* dtCMatrix, etc; [1] = the second character =?= 't' for triangular */      /* dtCMatrix, etc; [1] = the second character =?= 't' for triangular */
483      int tr = (cl[1] == 't');      int tr = (cl[1] == 't');
484      CHM_SP chx = AS_CHM_SP__(x);      CHM_SP chx = AS_CHM_SP__(x);
485      CHM_SP ans = cholmod_l_copy(chx, chx->stype, chx->xtype, &c);      CHM_SP ans = cholmod_copy(chx, chx->stype, chx->xtype, &c);
486      double dtol = asReal(tol);      double dtol = asReal(tol);
487      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
488      R_CheckStack();      R_CheckStack();
489
490      if(!cholmod_l_drop(dtol, ans, &c))      if(!cholmod_drop(dtol, ans, &c))
491          error(_("cholmod_l_drop() failed"));          error(_("cholmod_drop() failed"));
492      return chm_sparse_to_SEXP(ans, 1,      return chm_sparse_to_SEXP(ans, 1,
493                                tr ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,                                tr ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,
494                                Rkind, tr ? diag_P(x) : "",                                Rkind, tr ? diag_P(x) : "",
# Line 502  Line 504
504      R_CheckStack();      R_CheckStack();
505
506      /* TODO: currently drops dimnames - and we fix at R level */      /* TODO: currently drops dimnames - and we fix at R level */
507      return chm_sparse_to_SEXP(cholmod_l_horzcat(chx, chy, 1, &c),      return chm_sparse_to_SEXP(cholmod_horzcat(chx, chy, 1, &c),
508                                1, 0, Rkind, "", R_NilValue);                                1, 0, Rkind, "", R_NilValue);
509  }  }
510
# Line 515  Line 517
517      R_CheckStack();      R_CheckStack();
518
519      /* TODO: currently drops dimnames - and we fix at R level */      /* TODO: currently drops dimnames - and we fix at R level */
520      return chm_sparse_to_SEXP(cholmod_l_vertcat(chx, chy, 1, &c),      return chm_sparse_to_SEXP(cholmod_vertcat(chx, chy, 1, &c),
521                                1, 0, Rkind, "", R_NilValue);                                1, 0, Rkind, "", R_NilValue);
522  }  }
523
# Line 523  Line 525
525  {  {
526      CHM_SP chx = AS_CHM_SP__(x);      CHM_SP chx = AS_CHM_SP__(x);
527      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
528      CHM_SP ans = cholmod_l_band(chx, asInteger(k1), asInteger(k2), chx->xtype, &c);      CHM_SP ans = cholmod_band(chx, asInteger(k1), asInteger(k2), chx->xtype, &c);
529      R_CheckStack();      R_CheckStack();
530
531      return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "",      return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "",
# Line 541  Line 543
543      }      }
544      else { /* unit triangular (diag='U'): "fill the diagonal" & diag:= "N" */      else { /* unit triangular (diag='U'): "fill the diagonal" & diag:= "N" */
545          CHM_SP chx = AS_CHM_SP__(x);          CHM_SP chx = AS_CHM_SP__(x);
546          CHM_SP eye = cholmod_l_speye(chx->nrow, chx->ncol, chx->xtype, &c);          CHM_SP eye = cholmod_speye(chx->nrow, chx->ncol, chx->xtype, &c);
547          double one[] = {1, 0};          double one[] = {1, 0};
548          CHM_SP ans = cholmod_l_add(chx, eye, one, one, TRUE, TRUE, &c);          CHM_SP ans = cholmod_add(chx, eye, one, one, TRUE, TRUE, &c);
549          int uploT = (*uplo_P(x) == 'U') ? 1 : -1;          int uploT = (*uplo_P(x) == 'U') ? 1 : -1;
550          int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;          int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
551
552          R_CheckStack();          R_CheckStack();
553          cholmod_l_free_sparse(&eye, &c);          cholmod_free_sparse(&eye, &c);
554          return chm_sparse_to_SEXP(ans, 1, uploT, Rkind, "N",          return chm_sparse_to_SEXP(ans, 1, uploT, Rkind, "N",
555                                    GET_SLOT(x, Matrix_DimNamesSym));                                    GET_SLOT(x, Matrix_DimNamesSym));
556      }      }
# Line 602  Line 604
604
605      if (chx->stype) /* symmetricMatrix */      if (chx->stype) /* symmetricMatrix */
606          /* for now, cholmod_submatrix() only accepts "generalMatrix" */          /* for now, cholmod_submatrix() only accepts "generalMatrix" */
607          chx = cholmod_l_copy(chx, /* stype: */ 0, chx->xtype, &c);          chx = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);
608
609      return chm_sparse_to_SEXP(cholmod_l_submatrix(chx,      return chm_sparse_to_SEXP(cholmod_submatrix(chx,
610                                  (rsize < 0) ? NULL : INTEGER(i), rsize,                                  (rsize < 0) ? NULL : INTEGER(i), rsize,
611                                  (csize < 0) ? NULL : INTEGER(j), csize,                                  (csize < 0) ? NULL : INTEGER(j), csize,
612                                                    TRUE, TRUE, &c),                                                    TRUE, TRUE, &c),
# Line 612  Line 614
614                                /* FIXME: drops dimnames */ R_NilValue);                                /* FIXME: drops dimnames */ R_NilValue);
615  }  }
616
617    /**
618     * Subassignment:  x[i,j]  <- value
619     *
620     * @param x
621     * @param i_ integer row    index 0-origin vector (as returned from R .ind.prep2())
622     * @param j_ integer column index 0-origin vector
623     * @param value currently must be a dsparseVector {which is recycled if needed}
624     *
625     * @return a Csparse matrix like x, but with the values replaced
626     */
627    SEXP Csparse_subassign(SEXP x, SEXP i_, SEXP j_, SEXP value)
628    {
629        // TODO: for other classes consider using a trick as  RallocedReal() in ./chm_common.c
630        static const char
631            *valid_cM [] = { // the only ones, for "the moment". FIXME: extend (!)
632            "dgCMatrix",// 0
633            "dtCMatrix",// 1
634            ""},
635            // value: assume a  "dsparseVector" for now -- slots: (i, length, x)
636            *valid_spv[] = {"dsparseVector",
637                            ""};
638
639        int ctype_x = Matrix_check_class_etc(x, valid_cM),
640            ctype_v = Matrix_check_class_etc(value, valid_spv);
641        if (ctype_x < 0)
642            error(_("invalid class of 'x' in Csparse_subassign()"));
643        if (ctype_v < 0)
644            error(_("invalid class of 'value' in Csparse_subassign()"));
645
646        SEXP
647            islot   = GET_SLOT(x, Matrix_iSym),
648            dimslot = GET_SLOT(x, Matrix_DimSym),
649            i_cp = PROTECT(coerceVector(i_, INTSXP)),
650            j_cp = PROTECT(coerceVector(j_, INTSXP));
651            // for d.CMatrix and l.CMatrix  but not n.CMatrix:
652
653        int *dims = INTEGER(dimslot),
654            ncol = dims[1], /* nrow = dims[0], */
655            *i = INTEGER(i_cp), len_i = LENGTH(i_cp),
656            *j = INTEGER(j_cp), len_j = LENGTH(j_cp),
657            k,
658            nnz_x = LENGTH(islot);
659        int nnz = nnz_x;
660
661    #define MATRIX_SUBASSIGN_VERBOSE
662    // Temporary hack for debugging --- remove eventually -- FIXME
663    #ifdef MATRIX_SUBASSIGN_VERBOSE
664        Rboolean verbose = i[0] < 0;
665        if(verbose) i[0] = -i[0];
666    #endif
667
668        SEXP val_i_slot;
669        PROTECT(val_i_slot = coerceVector(GET_SLOT(value, Matrix_iSym), REALSXP));
670        double *val_i = REAL(val_i_slot);
671        int nnz_val =  LENGTH(GET_SLOT(value, Matrix_iSym));
672        // for dsparseVector only:
673        double *val_x =   REAL (GET_SLOT(value, Matrix_xSym));
674        int64_t len_val = (int64_t) asReal(GET_SLOT(value, Matrix_lengthSym));
675        /* llen_i = (int64_t) len_i; */
676
677        double z_ans = 0.;
678
679        SEXP ans;
680        /* Instead of simple "duplicate": PROTECT(ans = duplicate(x)) , build up: */
681        // Assuming that ans will have the same basic Matrix type as x :
682        ans = PROTECT(NEW_OBJECT(MAKE_CLASS(valid_cM[ctype_x])));
683        SET_SLOT(ans, Matrix_DimSym,      duplicate(dimslot));
684        SET_SLOT(ans, Matrix_DimNamesSym, duplicate(GET_SLOT(x, Matrix_DimNamesSym)));
685        SET_SLOT(ans, Matrix_pSym,        duplicate(GET_SLOT(x, Matrix_pSym)));
686        SEXP r_pslot = GET_SLOT(ans, Matrix_pSym);
687        // and assign the i- and x- slots at the end, as they are potentially modified
688        // not just in content, but also in their *length*
689        int *rp = INTEGER(r_pslot),
690            *ri = Calloc(nnz_x, int);       // to contain the final i - slot
691        // for d.CMatrix only:
692        double *rx = Calloc(nnz_x, double); // to contain the final x - slot
693        Memcpy(ri, INTEGER(islot), nnz_x);
694        Memcpy(rx, REAL(GET_SLOT(x, Matrix_xSym)), nnz_x);
695        // NB:  nnz_x : will always be the "current allocated length" of (i, x) slots
696        // --   nnz   : the current *used* length; always   nnz <= nnz_x
697
698        int jj, j_val = 0; // in "running" conceptionally through all value[i+ jj*len_i]
699        // values, we are "below"/"before" the (j_val)-th non-zero one.
700        // e.g. if value = (0,0,...,0), have nnz_val == 0, j_val must remain == 0
701        int64_t ii_val;// == "running" index (i + jj*len_i) % len_val for value[]
702        for(jj = 0, ii_val=0; jj < len_j; jj++) {
703            int j__ = j[jj];
704            /* int64_t j_l = jj * llen_i; */
705            R_CheckUserInterrupt();
706            for(int ii = 0; ii < len_i; ii++, ii_val++) {
707                int i__ = i[ii], p1, p2;
708                if(nnz_val && ii_val >= len_val) { // "recycle" indexing into value[]
709                    ii_val -= len_val; // = (ii + jj*len_i) % len_val
710                    j_val = 0;
711                }
712                int64_t ii_v1;//= ii_val + 1;
713                double v, /* := value[(ii + j_l) % len_val]
714                             = dsparseVector_sub((ii + j_l) % len_val,
715                                                 nnz_val, val_i, val_x, len_val)
716                          */
717                    M_ij;
718                int ind;
719                Rboolean have_entry = FALSE;
720
721                // note that rp[]'s may have *changed* even when 'j' remained!
722                // "FIXME": do this only *when* rp[] has changed
723                p1 = rp[j__], p2 = rp[j__ + 1];
724
725                // v :=  value[(ii + j_l) % len_val] = value[ii_val]
726                v = z_ans;
727                if(j_val < nnz_val) { // maybe find v := non-zero value[ii_val]
728                    ii_v1 = ii_val + 1;
729                    if(ii_v1 < val_i[j_val]) { // typical case: are still in zero-stretch
730                        v = z_ans; // v = 0
731                    } else if(ii_v1 == val_i[j_val]) { // have a match
732                        v = val_x[j_val];
733                        j_val++;// from now on, look at the next non-zero entry
734                    } else { //  ii_v1 > val_i[j_val]
735                        REprintf("programming thinko in Csparse_subassign(*, i=%d,j=%d): ii_v=%d, v@i[j_val=%ld]=%g\n",
736                                 i__,j__, ii_v1, j_val, val_i[j_val]);
737                        j_val++;// from now on, look at the next non-zero entry
738                    }
739                }
740                // --------------- M_ij := getM(i., j.) --------------------------------
741                M_ij = z_ans; // as in  ./t_sparseVector.c
742                for(ind = p1; ind < p2; ind++) {
743                    if(ri[ind] >= i__) {
744                        if(ri[ind] == i__) {
745                            M_ij = rx[ind];
746    #ifdef MATRIX_SUBASSIGN_VERBOSE
747                            if(verbose) REprintf("have entry x[%d, %d] = %g\n",
748                                                 i__, j__, M_ij);
749    #endif
750                            have_entry = TRUE;
751                        } else { // ri[ind] > i__
752    #ifdef MATRIX_SUBASSIGN_VERBOSE
753                            if(verbose)
754                                REprintf("@i > i__ = %d --> ind-- = %d\n", i__, ind);
755    #endif
756                        }
757                        break;
758                    }
759                }
760
761                //-- R:  if(getM(i., j.) != (v <- getV(ii, jj)))
762
763                if(M_ij != v) { // contents differ ==> value needs to be changed
764    #ifdef MATRIX_SUBASSIGN_VERBOSE
765                    if(verbose)
766                        REprintf("setting x[%d, %d] <- %g", i__,j__, v);
767    #endif
768                    // (otherwise: nothing to do):
769                    // setM(i__, j__, v)
770                    // ----------------------------------------------------------
771
772                    // Case I --------------------------------------------
773    /*              if(v == z_ans) { // remove x[i, j] = M_ij  which we know is *non*-zero */
774    //-------- Better (memory-management) *NOT* to remove, but rather at the very end
775    //         currently using  drop0() in R code
776    /*                  // we know : have_entry = TRUE ; */
777    /*                  //  ri[ind] == i__; M_ij = rx[ind]; */
778    /* #ifdef MATRIX_SUBASSIGN_VERBOSE */
779    /*                  if(verbose) */
780    /*                      REprintf(" rm ind=%d\n", ind); */
781    /* #endif */
782    /*                  // remove the 'ind'-th element from x@i and x@x : */
783    /*                  nnz-- ; */
784    /*                  for(k=ind; k < nnz; k++) { */
785    /*                      ri[k] = ri[k+1]; */
786    /*                      rx[k] = rx[k+1]; */
787    /*                  } */
788    /*                  for(k=j__ + 1; k <= ncol; k++) { */
789    /*                      rp[k] = rp[k] - 1; */
790    /*                  } */
791    /*              } */
792    /*              else  */
793                    if(have_entry) {
794                        // Case II ----- replace (non-empty) x[i,j] by v -------
795    #ifdef MATRIX_SUBASSIGN_VERBOSE
796                        if(verbose)
797                            REprintf(" repl.  ind=%d\n", ind);
798    #endif
799                        rx[ind] = v;
800                    } else {
801                        // Case III ---- v != 0 : insert v into "empty" x[i,j] ----
802
803                        // extend the  i  and  x  slot by one entry : ---------------------
804
805                        if(nnz+1 > nnz_x) { // need to reallocate:
806    #ifdef MATRIX_SUBASSIGN_VERBOSE
807                            if(verbose) REprintf(" Realloc()ing: nnz_x=%d", nnz_x);
808    #endif
809                            // do it "only" 1x,..4x at the very most increasing by the
810                            // nnz-length of "value":
811                            nnz_x += (1 + nnz_val / 4);
812    #ifdef MATRIX_SUBASSIGN_VERBOSE
813                            if(verbose) REprintf("(nnz_v=%d) --> %d ", nnz_val, nnz_x);
814    #endif
815                            // C doc on realloc() says that the old content is *preserve*d
816                            ri = Realloc(ri, nnz_x, int);
817                            rx = Realloc(rx, nnz_x, double);
818                        }
819
820                        // 3) fill them ...
821
822                        int i1 = ind;
823    #ifdef MATRIX_SUBASSIGN_VERBOSE
824                        if(verbose)
825                            REprintf(" INSERT p12=(%d,%d) -> ind=%d -> i1 = %d\n",
826                                     p1,p2, ind, i1);
827    #endif
828
829                        // shift the "upper values" *before* the insertion:
830                        for(int l = nnz-1; l >= i1; l--) {
831                            ri[l+1] = ri[l];
832                            rx[l+1] = rx[l];
833                        }
834                        ri[i1] = i__;
835                        rx[i1] = v;
836                        nnz++;
837
838                        // the columns j "right" of the current one :
839                        for(k=j__ + 1; k <= ncol; k++)
840                            rp[k]++;
841                    }
842                }
843    #ifdef MATRIX_SUBASSIGN_VERBOSE
844                else if(verbose) REprintf("M_ij == v = %g\n", v);
845    #endif
846            }// for( ii )
847        }// for( jj )
848
849        if(ctype_x == 1) { // triangularMatrix: copy the 'diag' and 'uplo' slots
850            SET_SLOT(ans, Matrix_uploSym, duplicate(GET_SLOT(x, Matrix_uploSym)));
851            SET_SLOT(ans, Matrix_diagSym, duplicate(GET_SLOT(x, Matrix_diagSym)));
852        }
853        // now assign the i- and x- slots,  free memory and return :
854        Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_iSym,  INTSXP, nnz)), ri, nnz);
855        Memcpy(   REAL(ALLOC_SLOT(ans, Matrix_xSym, REALSXP, nnz)), rx, nnz);
856        Free(ri);
857        Free(rx);
858        UNPROTECT(4);
859        return ans;
860    }
861
862  SEXP Csparse_MatrixMarket(SEXP x, SEXP fname)  SEXP Csparse_MatrixMarket(SEXP x, SEXP fname)
863  {  {
864      FILE *f = fopen(CHAR(asChar(fname)), "w");      FILE *f = fopen(CHAR(asChar(fname)), "w");
# Line 619  Line 866
866      if (!f)      if (!f)
867          error(_("failure to open file \"%s\" for writing"),          error(_("failure to open file \"%s\" for writing"),
868                CHAR(asChar(fname)));                CHAR(asChar(fname)));
869      if (!cholmod_l_write_sparse(f, AS_CHM_SP(x),      if (!cholmod_write_sparse(f, AS_CHM_SP(x),
870                                (CHM_SP)NULL, (char*) NULL, &c))                                (CHM_SP)NULL, (char*) NULL, &c))
871          error(_("cholmod_l_write_sparse returned error code"));          error(_("cholmod_write_sparse returned error code"));
872      fclose(f);      fclose(f);
873      return R_NilValue;      return R_NilValue;
874  }  }
# Line 835  Line 1082
1082      if (cls[1] != 'g')      if (cls[1] != 'g')
1083          error(_("Only 'g'eneral sparse matrix types allowed"));          error(_("Only 'g'eneral sparse matrix types allowed"));
1084                                  /* allocate and populate the triplet */                                  /* allocate and populate the triplet */
1085      T = cholmod_l_allocate_triplet((size_t)nrow, (size_t)ncol, (size_t)nnz, 0,      T = cholmod_allocate_triplet((size_t)nrow, (size_t)ncol, (size_t)nnz, 0,
1086                                      xtype, &c);                                      xtype, &c);
1087      T->x = x;      T->x = x;
1088      tri = (int*)T->i;      tri = (int*)T->i;
# Line 845  Line 1092
1092          trj[ii] = j[ii] - ((!mj && index1) ? 1 : 0);          trj[ii] = j[ii] - ((!mj && index1) ? 1 : 0);
1093      }      }
1094                                  /* create the cholmod_sparse structure */                                  /* create the cholmod_sparse structure */
1095      A = cholmod_l_triplet_to_sparse(T, nnz, &c);      A = cholmod_triplet_to_sparse(T, nnz, &c);
1096      cholmod_l_free_triplet(&T, &c);      cholmod_free_triplet(&T, &c);
1097                                  /* copy the information to the SEXP */                                  /* copy the information to the SEXP */
1098      ans = PROTECT(NEW_OBJECT(MAKE_CLASS(cls)));      ans = PROTECT(NEW_OBJECT(MAKE_CLASS(cls)));
1099  /* FIXME: This has been copied from chm_sparse_to_SEXP in chm_common.c */  /* FIXME: This has been copied from chm_sparse_to_SEXP in chm_common.c */
1100                                  /* allocate and copy common slots */                                  /* allocate and copy common slots */
1101      nnz = cholmod_l_nnz(A, &c);      nnz = cholmod_nnz(A, &c);
1102      dims = INTEGER(ALLOC_SLOT(ans, Matrix_DimSym, INTSXP, 2));      dims = INTEGER(ALLOC_SLOT(ans, Matrix_DimSym, INTSXP, 2));
1103      dims[0] = A->nrow; dims[1] = A->ncol;      dims[0] = A->nrow; dims[1] = A->ncol;
1104      Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_pSym, INTSXP, A->ncol + 1)), (int*)A->p, A->ncol + 1);      Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_pSym, INTSXP, A->ncol + 1)), (int*)A->p, A->ncol + 1);
# Line 864  Line 1111
1111          error(_("code not yet written for cls = \"lgCMatrix\""));          error(_("code not yet written for cls = \"lgCMatrix\""));
1112      }      }
1113  /* FIXME: dimnames are *NOT* put there yet (if non-NULL) */  /* FIXME: dimnames are *NOT* put there yet (if non-NULL) */
1114      cholmod_l_free_sparse(&A, &c);      cholmod_free_sparse(&A, &c);
1115      UNPROTECT(1);      UNPROTECT(1);
1116      return ans;      return ans;
1117  }  }

Legend:
 Removed from v.2646 changed lines Added in v.2681