SCM

SCM Repository

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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

pkg/src/Csparse.c revision 2175, Wed Apr 23 11:23:50 2008 UTC pkg/Matrix/src/Csparse.c revision 2677, Sat Jun 25 19:18:12 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"
7    
8  SEXP Csparse_validate(SEXP x)  /** "Cheap" C version of  Csparse_validate() - *not* sorting : */
9    Rboolean isValid_Csparse(SEXP x)
10    {
11        /* NB: we do *NOT* check a potential 'x' slot here, at all */
12        SEXP pslot = GET_SLOT(x, Matrix_pSym),
13            islot = GET_SLOT(x, Matrix_iSym);
14        int *dims = INTEGER(GET_SLOT(x, Matrix_DimSym)), j,
15            nrow = dims[0],
16            ncol = dims[1],
17            *xp = INTEGER(pslot),
18            *xi = INTEGER(islot);
19    
20        if (length(pslot) != dims[1] + 1)
21            return FALSE;
22        if (xp[0] != 0)
23            return FALSE;
24        if (length(islot) < xp[ncol]) /* allow larger slots from over-allocation!*/
25            return FALSE;
26        for (j = 0; j < xp[ncol]; j++) {
27            if (xi[j] < 0 || xi[j] >= nrow)
28                return FALSE;
29        }
30        for (j = 0; j < ncol; j++) {
31            if (xp[j] > xp[j + 1])
32                return FALSE;
33        }
34        return TRUE;
35    }
36    
37    SEXP Csparse_validate(SEXP x) {
38        return Csparse_validate_(x, FALSE);
39    }
40    
41    SEXP Csparse_validate2(SEXP x, SEXP maybe_modify) {
42        return Csparse_validate_(x, asLogical(maybe_modify));
43    }
44    
45    SEXP Csparse_validate_(SEXP x, Rboolean maybe_modify)
46  {  {
47      /* NB: we do *NOT* check a potential 'x' slot here, at all */      /* NB: we do *NOT* check a potential 'x' slot here, at all */
48      SEXP pslot = GET_SLOT(x, Matrix_pSym),      SEXP pslot = GET_SLOT(x, Matrix_pSym),
# Line 23  Line 62 
62      if (length(islot) < xp[ncol]) /* allow larger slots from over-allocation!*/      if (length(islot) < xp[ncol]) /* allow larger slots from over-allocation!*/
63          return          return
64              mkString(_("last element of slot p must match length of slots i and x"));              mkString(_("last element of slot p must match length of slots i and x"));
65      for (j = 0; j < length(islot); j++) {      for (j = 0; j < xp[ncol]; j++) {
66          if (xi[j] < 0 || xi[j] >= nrow)          if (xi[j] < 0 || xi[j] >= nrow)
67              return mkString(_("all row indices must be between 0 and nrow-1"));              return mkString(_("all row indices must be between 0 and nrow-1"));
68      }      }
# Line 31  Line 70 
70      for (j = 0; j < ncol; j++) {      for (j = 0; j < ncol; j++) {
71          if (xp[j] > xp[j+1])          if (xp[j] > xp[j+1])
72              return mkString(_("slot p must be non-decreasing"));              return mkString(_("slot p must be non-decreasing"));
73          if(sorted)          if(sorted) /* only act if >= 2 entries in column j : */
74              for (k = xp[j] + 1; k < xp[j + 1]; k++) {              for (k = xp[j] + 1; k < xp[j + 1]; k++) {
75                  if (xi[k] < xi[k - 1])                  if (xi[k] < xi[k - 1])
76                      sorted = FALSE;                      sorted = FALSE;
# Line 40  Line 79 
79              }              }
80      }      }
81      if (!sorted) {      if (!sorted) {
82          CHM_SP chx = AS_CHM_SP(x);          if(maybe_modify) {
83                CHM_SP chx = (CHM_SP) alloca(sizeof(cholmod_sparse));
84          R_CheckStack();          R_CheckStack();
85                as_cholmod_sparse(chx, x, FALSE, TRUE);/*-> cholmod_l_sort() ! */
86                /* as chx = AS_CHM_SP__(x)  but  ^^^^ sorting x in_place !!! */
87    
         cholmod_sort(chx, &c);  
88          /* Now re-check that row indices are *strictly* increasing          /* Now re-check that row indices are *strictly* increasing
89           * (and not just increasing) within each column : */           * (and not just increasing) within each column : */
90          for (j = 0; j < ncol; j++) {          for (j = 0; j < ncol; j++) {
91              for (k = xp[j] + 1; k < xp[j + 1]; k++)              for (k = xp[j] + 1; k < xp[j + 1]; k++)
92                  if (xi[k] == xi[k - 1])                  if (xi[k] == xi[k - 1])
93                      return mkString(_("slot i is not *strictly* increasing inside a column (even after cholmod_sort)"));                          return mkString(_("slot i is not *strictly* increasing inside a column (even after cholmod_l_sort)"));
94                }
95            } else { /* no modifying sorting : */
96                return mkString(_("row indices are not sorted within columns"));
97          }          }
   
98      } else if(!strictly) {  /* sorted, but not strictly */      } else if(!strictly) {  /* sorted, but not strictly */
99          return mkString(_("slot i is not *strictly* increasing inside a column"));          return mkString(_("slot i is not *strictly* increasing inside a column"));
100      }      }
# Line 109  Line 152 
152   * FIXME: replace by non-CHOLMOD code ! */   * FIXME: replace by non-CHOLMOD code ! */
153  SEXP Csparse_to_dense(SEXP x)  SEXP Csparse_to_dense(SEXP x)
154  {  {
155      CHM_SP chxs = AS_CHM_SP(x);      CHM_SP chxs = AS_CHM_SP__(x);
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 : */
# Line 120  Line 163 
163      return chm_dense_to_SEXP(chxd, 1, Rkind, GET_SLOT(x, Matrix_DimNamesSym));      return chm_dense_to_SEXP(chxd, 1, Rkind, GET_SLOT(x, Matrix_DimNamesSym));
164  }  }
165    
166    // FIXME: do not go via CHM (should not be too hard, to just *drop* the x-slot, right?
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_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();
# Line 133  Line 177 
177                                GET_SLOT(x, Matrix_DimNamesSym));                                GET_SLOT(x, Matrix_DimNamesSym));
178  }  }
179    
180    // n.CMatrix --> [dli].CMatrix  (not going through CHM!)
181    SEXP nz_pattern_to_Csparse(SEXP x, SEXP res_kind)
182    {
183        return nz2Csparse(x, asInteger(res_kind));
184    }
185    // n.CMatrix --> [dli].CMatrix  (not going through CHM!)
186    SEXP nz2Csparse(SEXP x, enum x_slot_kind r_kind)
187    {
188        const char *cl_x = class_P(x);
189        if(cl_x[0] != 'n') error(_("not a 'n.CMatrix'"));
190        if(cl_x[2] != 'C') error(_("not a CsparseMatrix"));
191        int nnz = LENGTH(GET_SLOT(x, Matrix_iSym));
192        SEXP ans;
193        char *ncl = strdup(cl_x);
194        double *dx_x; int *ix_x;
195        ncl[0] = (r_kind == x_double ? 'd' :
196                  (r_kind == x_logical ? 'l' :
197                   /* else (for now):  r_kind == x_integer : */ 'i'));
198        PROTECT(ans = NEW_OBJECT(MAKE_CLASS(ncl)));
199        // create a correct 'x' slot:
200        switch(r_kind) {
201            int i;
202        case x_double: // 'd'
203            dx_x = REAL(ALLOC_SLOT(ans, Matrix_xSym, REALSXP, nnz));
204            for (i=0; i < nnz; i++) dx_x[i] = 1.;
205            break;
206        case x_logical: // 'l'
207            ix_x = LOGICAL(ALLOC_SLOT(ans, Matrix_xSym, LGLSXP, nnz));
208            for (i=0; i < nnz; i++) ix_x[i] = TRUE;
209            break;
210        case x_integer: // 'i'
211            ix_x = INTEGER(ALLOC_SLOT(ans, Matrix_xSym, INTSXP, nnz));
212            for (i=0; i < nnz; i++) ix_x[i] = 1;
213            break;
214    
215        default:
216            error(_("nz2Csparse(): invalid/non-implemented r_kind = %d"),
217                  r_kind);
218        }
219    
220        // now copy all other slots :
221        slot_dup(ans, x, Matrix_iSym);
222        slot_dup(ans, x, Matrix_pSym);
223        slot_dup(ans, x, Matrix_DimSym);
224        slot_dup(ans, x, Matrix_DimNamesSym);
225        if(ncl[1] != 'g') { // symmetric or triangular ...
226            slot_dup_if_has(ans, x, Matrix_uploSym);
227            slot_dup_if_has(ans, x, Matrix_diagSym);
228        }
229        UNPROTECT(1);
230        return ans;
231    }
232    
233  SEXP Csparse_to_matrix(SEXP x)  SEXP Csparse_to_matrix(SEXP x)
234  {  {
235      return chm_dense_to_matrix(cholmod_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_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;
# Line 156  Line 253 
253  /* this used to be called  sCMatrix_to_gCMatrix(..)   [in ./dsCMatrix.c ]: */  /* this used to be called  sCMatrix_to_gCMatrix(..)   [in ./dsCMatrix.c ]: */
254  SEXP Csparse_symmetric_to_general(SEXP x)  SEXP Csparse_symmetric_to_general(SEXP x)
255  {  {
256      CHM_SP chx = AS_CHM_SP(x), chgx;      CHM_SP chx = AS_CHM_SP__(x), chgx;
257      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
258      R_CheckStack();      R_CheckStack();
259    
# Line 170  Line 267 
267    
268  SEXP Csparse_general_to_symmetric(SEXP x, SEXP uplo)  SEXP Csparse_general_to_symmetric(SEXP x, SEXP uplo)
269  {  {
270      CHM_SP chx = AS_CHM_SP(x), chgx;      CHM_SP chx = AS_CHM_SP__(x), chgx;
271      int uploT = (*CHAR(STRING_ELT(uplo,0)) == 'U') ? 1 : -1;      int uploT = (*CHAR(STRING_ELT(uplo,0)) == 'U') ? 1 : -1;
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();
# Line 185  Line 282 
282  {  {
283      /* TODO: lgCMatrix & igC* currently go via double prec. cholmod -      /* TODO: lgCMatrix & igC* currently go via double prec. cholmod -
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_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;
# Line 204  Line 301 
301  SEXP Csparse_Csparse_prod(SEXP a, SEXP b)  SEXP Csparse_Csparse_prod(SEXP a, SEXP b)
302  {  {
303      CHM_SP      CHM_SP
304          cha = AS_CHM_SP(Csparse_diagU2N(a)),          cha = AS_CHM_SP(a),
305          chb = AS_CHM_SP(Csparse_diagU2N(b)),          chb = AS_CHM_SP(b),
306          chc = cholmod_ssmult(cha, chb, /*out_stype:*/ 0,          chc = cholmod_ssmult(cha, chb, /*out_stype:*/ 0,
307                               cha->xtype, /*out sorted:*/ 1, &c);                                 /* values:= is_numeric (T/F) */ cha->xtype > 0,
308                                   /*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);
310      char diag[] = {'\0', '\0'};      char diag[] = {'\0', '\0'};
311      int uploT = 0;      int uploT = 0;
312      SEXP dn = allocVector(VECSXP, 2);      SEXP dn = PROTECT(allocVector(VECSXP, 2));
313      R_CheckStack();      R_CheckStack();
314    
315    #ifdef DEBUG_Matrix_verbose
316        Rprintf("DBG Csparse_C*_prod(%s, %s)\n", cl_a, cl_b);
317    #endif
318    
319      /* Preserve triangularity and even unit-triangularity if appropriate.      /* Preserve triangularity and even unit-triangularity if appropriate.
320       * Note that in that case, the multiplication itself should happen       * Note that in that case, the multiplication itself should happen
321       * faster.  But there's no support for that in CHOLMOD */       * faster.  But there's no support for that in CHOLMOD */
# Line 235  Line 337 
337                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));
338      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
339                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), 1)));
340        UNPROTECT(1);
341      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);
342  }  }
343    
# Line 242  Line 345 
345  {  {
346      int tr = asLogical(trans);      int tr = asLogical(trans);
347      CHM_SP      CHM_SP
348          cha = AS_CHM_SP(Csparse_diagU2N(a)),          cha = AS_CHM_SP(a),
349          chb = AS_CHM_SP(Csparse_diagU2N(b)),          chb = AS_CHM_SP(b),
350          chTr, chc;          chTr, chc;
351      const char *cl_a = class_P(a), *cl_b = class_P(b);      const char *cl_a = class_P(a), *cl_b = class_P(b);
352      char diag[] = {'\0', '\0'};      char diag[] = {'\0', '\0'};
353      int uploT = 0;      int uploT = 0;
354      SEXP dn = allocVector(VECSXP, 2);      SEXP dn = PROTECT(allocVector(VECSXP, 2));
355      R_CheckStack();      R_CheckStack();
356    
357      chTr = cholmod_transpose((tr) ? chb : cha, chb->xtype, &c);      chTr = cholmod_transpose((tr) ? chb : cha, chb->xtype, &c);
# Line 267  Line 370 
370              }              }
371              else diag[0]= 'N';              else diag[0]= 'N';
372          }          }
   
373      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
374                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), (tr) ? 0 : 1)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), (tr) ? 0 : 1)));
375      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
376                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), (tr) ? 0 : 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), (tr) ? 0 : 1)));
377        UNPROTECT(1);
378      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);
379  }  }
380    
381  SEXP Csparse_dense_prod(SEXP a, SEXP b)  SEXP Csparse_dense_prod(SEXP a, SEXP b)
382  {  {
383      CHM_SP cha = AS_CHM_SP(Csparse_diagU2N(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_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};
390        int nprot = 2;
391      R_CheckStack();      R_CheckStack();
392        /* Tim Davis, please FIXME:  currently (2010-11) *fails* when  a  is a pattern matrix:*/
393        if(cha->xtype == CHOLMOD_PATTERN) {
394            /* warning(_("Csparse_dense_prod(): cholmod_sdmult() not yet implemented for pattern./ ngCMatrix" */
395            /*        " --> slightly inefficient coercion")); */
396    
397            // This *fails* to produce a CHOLMOD_REAL ..
398            // CHM_SP chd = cholmod_l_copy(cha, cha->stype, CHOLMOD_REAL, &c);
399            // --> use our Matrix-classes
400            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
401            cha = AS_CHM_SP(da);
402        }
403      cholmod_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,
407                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));
408      UNPROTECT(2);      UNPROTECT(nprot);
409      return chm_dense_to_SEXP(chc, 1, 0, dn);      return chm_dense_to_SEXP(chc, 1, 0, dn);
410  }  }
411    
412  SEXP Csparse_dense_crossprod(SEXP a, SEXP b)  SEXP Csparse_dense_crossprod(SEXP a, SEXP b)
413  {  {
414      CHM_SP cha = AS_CHM_SP(Csparse_diagU2N(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_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));      SEXP dn = PROTECT(allocVector(VECSXP, 2)); int nprot = 2;
420      double one[] = {1,0}, zero[] = {0,0};      double one[] = {1,0}, zero[] = {0,0};
421      R_CheckStack();      R_CheckStack();
422        // -- see Csparse_dense_prod() above :
423        if(cha->xtype == CHOLMOD_PATTERN) {
424            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
425            cha = AS_CHM_SP(da);
426        }
427      cholmod_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,
431                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));
432      UNPROTECT(2);      UNPROTECT(nprot);
433      return chm_dense_to_SEXP(chc, 1, 0, dn);      return chm_dense_to_SEXP(chc, 1, 0, dn);
434  }  }
435    
# Line 321  Line 439 
439  {  {
440      int trip = asLogical(triplet),      int trip = asLogical(triplet),
441          tr   = asLogical(trans); /* gets reversed because _aat is tcrossprod */          tr   = asLogical(trans); /* gets reversed because _aat is tcrossprod */
442      CHM_TR cht = trip ? AS_CHM_TR(Tsparse_diagU2N(x)) : (CHM_TR) NULL;  #ifdef AS_CHM_DIAGU2N_FIXED_FINALLY
443        CHM_TR cht = trip ? AS_CHM_TR(x) : (CHM_TR) NULL;
444    #else /* workaround needed:*/
445        SEXP xx = PROTECT(Tsparse_diagU2N(x));
446        CHM_TR cht = trip ? AS_CHM_TR__(xx) : (CHM_TR) NULL;
447    #endif
448      CHM_SP chcp, chxt,      CHM_SP chcp, chxt,
449          chx = (trip ?          chx = (trip ?
450                 cholmod_triplet_to_sparse(cht, cht->nnz, &c) :                 cholmod_triplet_to_sparse(cht, cht->nnz, &c) :
451                 AS_CHM_SP(Csparse_diagU2N(x)));                 AS_CHM_SP(x));
452      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2));
453      R_CheckStack();      R_CheckStack();
454    
# Line 343  Line 466 
466                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),
467                                          (tr) ? 0 : 1)));                                          (tr) ? 0 : 1)));
468      SET_VECTOR_ELT(dn, 1, duplicate(VECTOR_ELT(dn, 0)));      SET_VECTOR_ELT(dn, 1, duplicate(VECTOR_ELT(dn, 0)));
469    #ifdef AS_CHM_DIAGU2N_FIXED_FINALLY
470      UNPROTECT(1);      UNPROTECT(1);
471    #else
472        UNPROTECT(2);
473    #endif
474      return chm_sparse_to_SEXP(chcp, 1, 0, 0, "", dn);      return chm_sparse_to_SEXP(chcp, 1, 0, 0, "", dn);
475  }  }
476    
477    /* Csparse_drop(x, tol):  drop entries with absolute value < tol, i.e,
478    *  at least all "explicit" zeros */
479  SEXP Csparse_drop(SEXP x, SEXP tol)  SEXP Csparse_drop(SEXP x, SEXP tol)
480  {  {
481      const char *cl = class_P(x);      const char *cl = class_P(x);
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_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;
# Line 368  Line 497 
497    
498  SEXP Csparse_horzcat(SEXP x, SEXP y)  SEXP Csparse_horzcat(SEXP x, SEXP y)
499  {  {
500      CHM_SP chx = AS_CHM_SP(x), chy = AS_CHM_SP(y);      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);
501      int Rkind = 0; /* only for "d" - FIXME */      int Rk_x = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0,
502            Rk_y = (chy->xtype != CHOLMOD_PATTERN) ? Real_kind(y) : 0,
503            Rkind = /* logical if both x and y are */ (Rk_x == 1 && Rk_y == 1) ? 1 : 0;
504      R_CheckStack();      R_CheckStack();
505    
506      /* FIXME: currently drops dimnames */      /* TODO: currently drops dimnames - and we fix at R level */
507      return chm_sparse_to_SEXP(cholmod_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    
511  SEXP Csparse_vertcat(SEXP x, SEXP y)  SEXP Csparse_vertcat(SEXP x, SEXP y)
512  {  {
513      CHM_SP chx = AS_CHM_SP(x), chy = AS_CHM_SP(y);      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);
514      int Rkind = 0; /* only for "d" - FIXME */      int Rk_x = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0,
515            Rk_y = (chy->xtype != CHOLMOD_PATTERN) ? Real_kind(y) : 0,
516            Rkind = /* logical if both x and y are */ (Rk_x == 1 && Rk_y == 1) ? 1 : 0;
517      R_CheckStack();      R_CheckStack();
518    
519      /* FIXME: currently drops dimnames */      /* TODO: currently drops dimnames - and we fix at R level */
520      return chm_sparse_to_SEXP(cholmod_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    
524  SEXP Csparse_band(SEXP x, SEXP k1, SEXP k2)  SEXP Csparse_band(SEXP x, SEXP k1, SEXP k2)
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_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();
# Line 409  Line 542 
542          return (x);          return (x);
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_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_add(chx, eye, one, one, TRUE, TRUE, &c);          CHM_SP ans = cholmod_add(chx, eye, one, one, TRUE, TRUE, &c);
# Line 434  Line 567 
567      }      }
568      else { /* triangular with diag='N'): now drop the diagonal */      else { /* triangular with diag='N'): now drop the diagonal */
569          /* duplicate, since chx will be modified: */          /* duplicate, since chx will be modified: */
570          CHM_SP chx = AS_CHM_SP(duplicate(x));          CHM_SP chx = AS_CHM_SP__(duplicate(x));
571          int uploT = (*uplo_P(x) == 'U') ? 1 : -1,          int uploT = (*uplo_P(x) == 'U') ? 1 : -1,
572              Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;              Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
573          R_CheckStack();          R_CheckStack();
# Line 447  Line 580 
580      }      }
581  }  }
582    
583    /**
584     * "Indexing" aka subsetting : Compute  x[i,j], also for vectors i and j
585     * Working via CHOLMOD_submatrix, see ./CHOLMOD/MatrixOps/cholmod_submatrix.c
586     * @param x CsparseMatrix
587     * @param i row     indices (0-origin), or NULL (R's)
588     * @param j columns indices (0-origin), or NULL
589     *
590     * @return x[i,j]  still CsparseMatrix --- currently, this loses dimnames
591     */
592  SEXP Csparse_submatrix(SEXP x, SEXP i, SEXP j)  SEXP Csparse_submatrix(SEXP x, SEXP i, SEXP j)
593  {  {
594      CHM_SP chx = AS_CHM_SP(x);      CHM_SP chx = AS_CHM_SP(x); /* << does diagU2N() when needed */
595      int rsize = (isNull(i)) ? -1 : LENGTH(i),      int rsize = (isNull(i)) ? -1 : LENGTH(i),
596          csize = (isNull(j)) ? -1 : LENGTH(j);          csize = (isNull(j)) ? -1 : LENGTH(j);
597      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
# Line 460  Line 602 
602      if (csize >= 0 && !isInteger(j))      if (csize >= 0 && !isInteger(j))
603          error(_("Index j must be NULL or integer"));          error(_("Index j must be NULL or integer"));
604    
605      return chm_sparse_to_SEXP(cholmod_submatrix(chx, INTEGER(i), rsize,      if (chx->stype) /* symmetricMatrix */
606                                                  INTEGER(j), csize,          /* for now, cholmod_submatrix() only accepts "generalMatrix" */
607            chx = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);
608    
609        return chm_sparse_to_SEXP(cholmod_submatrix(chx,
610                                    (rsize < 0) ? NULL : INTEGER(i), rsize,
611                                    (csize < 0) ? NULL : INTEGER(j), csize,
612                                                  TRUE, TRUE, &c),                                                  TRUE, TRUE, &c),
613                                1, 0, Rkind, "",                                1, 0, Rkind, "",
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 [] = {"dgCMatrix",// the only one, for "the moment", .. TODO
632                            ""},
633            *valid_spv[] = {"dsparseVector",
634                            ""};
635    
636        int ctype = Matrix_check_class_etc(x, valid_cM);
637        if (ctype < 0)
638            error(_("invalid class of 'x' in Csparse_subassign()"));
639        // value: assume a  "dsparseVector" for now -- slots: (i, length, x)
640        ctype = Matrix_check_class_etc(value, valid_spv);
641        if (ctype < 0)
642            error(_("invalid class of 'value' in Csparse_subassign()"));
643    
644        SEXP
645            islot   = GET_SLOT(x, Matrix_iSym),
646            dimslot = GET_SLOT(x, Matrix_DimSym),
647            i_cp = PROTECT(coerceVector(i_, INTSXP)),
648            j_cp = PROTECT(coerceVector(j_, INTSXP));
649            // for d.CMatrix and l.CMatrix  but not n.CMatrix:
650    
651        int *dims = INTEGER(dimslot),
652            ncol = dims[1], /* nrow = dims[0], */
653            *i = INTEGER(i_cp), len_i = LENGTH(i_cp),
654            *j = INTEGER(j_cp), len_j = LENGTH(j_cp),
655            k,
656            nnz_x = LENGTH(islot);
657        int nnz = nnz_x;
658    
659    #define MATRIX_SUBASSIGN_VERBOSE
660    // Temporary hack for debugging --- remove eventually -- FIXME
661    #ifdef MATRIX_SUBASSIGN_VERBOSE
662        Rboolean verbose = i[0] < 0;
663        if(verbose) i[0] = -i[0];
664    #endif
665    
666        SEXP val_i_slot;
667        PROTECT(val_i_slot = coerceVector(GET_SLOT(value, Matrix_iSym), REALSXP));
668        double *val_i = REAL(val_i_slot);
669        int nnz_val =  LENGTH(GET_SLOT(value, Matrix_iSym));
670        // for dsparseVector only:
671        double *val_x =   REAL (GET_SLOT(value, Matrix_xSym));
672        int64_t len_val = (int64_t) asReal(GET_SLOT(value, Matrix_lengthSym));
673        /* llen_i = (int64_t) len_i; */
674    
675        double z_ans = 0.;
676    
677        SEXP ans;
678        /* Instead of simple "duplicate": PROTECT(ans = duplicate(x)) , build up: */
679        ans = PROTECT(NEW_OBJECT(MAKE_CLASS("dgCMatrix" /* <- TODO*/)));
680        SET_SLOT(ans, Matrix_DimSym,      duplicate(dimslot));
681        SET_SLOT(ans, Matrix_DimNamesSym, duplicate(GET_SLOT(x, Matrix_DimNamesSym)));
682        SET_SLOT(ans, Matrix_pSym,        duplicate(GET_SLOT(x, Matrix_pSym)));
683        SEXP r_pslot = GET_SLOT(ans, Matrix_pSym);
684        // and assign the i- and x- slots at the end, as they are potentially modified
685        // not just in content, but also in their *length*
686        int *rp = INTEGER(r_pslot),
687            *ri = Calloc(nnz_x, int);       // to contain the final i - slot
688        // for d.CMatrix only:
689        double *rx = Calloc(nnz_x, double); // to contain the final x - slot
690        Memcpy(ri, INTEGER(islot), nnz_x);
691        Memcpy(rx, REAL(GET_SLOT(x, Matrix_xSym)), nnz_x);
692        // NB:  nnz_x : will always be the "current allocated length" of (i, x) slots
693        // --   nnz   : the current *used* length; always   nnz <= nnz_x
694    
695        int jj, j_val = 0; // in "running" conceptionally through all value[i+ jj*len_i]
696        // values, we are "below"/"before" the (j_val)-th non-zero one.
697        // e.g. if value = (0,0,...,0), have nnz_val == 0, j_val must remain == 0
698        int64_t ii_val;// == "running" index (i + jj*len_i) % len_val for value[]
699        for(jj = 0, ii_val=0; jj < len_j; jj++) {
700            int j__ = j[jj];
701            /* int64_t j_l = jj * llen_i; */
702            R_CheckUserInterrupt();
703            for(int ii = 0; ii < len_i; ii++, ii_val++) {
704                int i__ = i[ii], p1, p2;
705                if(nnz_val && ii_val >= len_val) { // "recycle" indexing into value[]
706                    ii_val -= len_val; // = (ii + jj*len_i) % len_val
707                    j_val = 0;
708                }
709                int64_t ii_v1;//= ii_val + 1;
710                double v, /* := value[(ii + j_l) % len_val]
711                             = dsparseVector_sub((ii + j_l) % len_val,
712                                                 nnz_val, val_i, val_x, len_val)
713                          */
714                    M_ij;
715                int ind;
716                Rboolean have_entry = FALSE;
717    
718                // note that rp[]'s may have *changed* even when 'j' remained!
719                // "FIXME": do this only *when* rp[] has changed
720                p1 = rp[j__], p2 = rp[j__ + 1];
721    
722                // v :=  value[(ii + j_l) % len_val] = value[ii_val]
723                v = z_ans;
724                if(j_val < nnz_val) { // maybe find v := non-zero value[ii_val]
725                    ii_v1 = ii_val + 1;
726                    if(ii_v1 < val_i[j_val]) { // typical case: are still in zero-stretch
727                        v = z_ans; // v = 0
728                    } else if(ii_v1 == val_i[j_val]) { // have a match
729                        v = val_x[j_val];
730                        j_val++;// from now on, look at the next non-zero entry
731                    } else { //  ii_v1 > val_i[j_val]
732                        REprintf("programming thinko in Csparse_subassign(*, i=%d,j=%d): ii_v=%d, v@i[j_val=%ld]=%g\n",
733                                 i__,j__, ii_v1, j_val, val_i[j_val]);
734                        j_val++;// from now on, look at the next non-zero entry
735                    }
736                }
737                // --------------- M_ij := getM(i., j.) --------------------------------
738                M_ij = z_ans; // as in  ./t_sparseVector.c
739                for(ind = p1; ind < p2; ind++) {
740                    if(ri[ind] >= i__) {
741                        if(ri[ind] == i__) {
742                            M_ij = rx[ind];
743    #ifdef MATRIX_SUBASSIGN_VERBOSE
744                            if(verbose) REprintf("have entry x[%d, %d] = %g\n",
745                                                 i__, j__, M_ij);
746    #endif
747                            have_entry = TRUE;
748                        } else { // ri[ind] > i__
749    #ifdef MATRIX_SUBASSIGN_VERBOSE
750                            if(verbose)
751                                REprintf("@i > i__ = %d --> ind-- = %d\n", i__, ind);
752    #endif
753                        }
754                        break;
755                    }
756                }
757    
758                //-- R:  if(getM(i., j.) != (v <- getV(ii, jj)))
759    
760                if(M_ij != v) { // contents differ ==> value needs to be changed
761    #ifdef MATRIX_SUBASSIGN_VERBOSE
762                    if(verbose)
763                        REprintf("setting x[%d, %d] <- %g", i__,j__, v);
764    #endif
765                    // (otherwise: nothing to do):
766                    // setM(i__, j__, v)
767                    // ----------------------------------------------------------
768    
769                    // Case I --------------------------------------------
770    /*              if(v == z_ans) { // remove x[i, j] = M_ij  which we know is *non*-zero */
771    /*                  // we know : have_entry = TRUE ; */
772    /*                  //  ri[ind] == i__; M_ij = rx[ind]; */
773    /* #ifdef MATRIX_SUBASSIGN_VERBOSE */
774    /*                  if(verbose) */
775    /*                      REprintf(" rm ind=%d\n", ind); */
776    /* #endif */
777    /*                  // remove the 'ind'-th element from x@i and x@x : */
778    /*                  nnz-- ; */
779    /*                  for(k=ind; k < nnz; k++) { */
780    /*                      ri[k] = ri[k+1]; */
781    /*                      rx[k] = rx[k+1]; */
782    /*                  } */
783    /*                  for(k=j__ + 1; k <= ncol; k++) { */
784    /*                      rp[k] = rp[k] - 1; */
785    /*                  } */
786    /*              } */
787    /*              else  */
788                    if(have_entry) {
789                        // Case II ----- replace (non-empty) x[i,j] by v -------
790    #ifdef MATRIX_SUBASSIGN_VERBOSE
791                        if(verbose)
792                            REprintf(" repl.  ind=%d\n", ind);
793    #endif
794                        rx[ind] = v;
795                    } else {
796                        // Case III ---- v != 0 : insert v into "empty" x[i,j] ----
797    
798                        // extend the  i  and  x  slot by one entry : ---------------------
799    
800                        if(nnz+1 > nnz_x) { // need to reallocate:
801    #ifdef MATRIX_SUBASSIGN_VERBOSE
802                            if(verbose) REprintf(" Realloc()ing: nnz_x=%d", nnz_x);
803    #endif
804                            // do it "only" 1x,..4x at the very most increasing by the
805                            // nnz-length of "value":
806                            nnz_x += (1 + nnz_val / 4);
807    #ifdef MATRIX_SUBASSIGN_VERBOSE
808                            if(verbose) REprintf("(nnz_v=%d) --> %d ", nnz_val, nnz_x);
809    #endif
810                            // C doc on realloc() says that the old content is *preserve*d
811                            ri = Realloc(ri, nnz_x, int);
812                            rx = Realloc(rx, nnz_x, double);
813                        }
814    
815                        // 3) fill them ...
816    
817                        int i1 = ind;
818    #ifdef MATRIX_SUBASSIGN_VERBOSE
819                        if(verbose)
820                            REprintf(" INSERT p12=(%d,%d) -> ind=%d -> i1 = %d\n",
821                                     p1,p2, ind, i1);
822    #endif
823    
824                        // shift the "upper values" *before* the insertion:
825                        for(int l = nnz-1; l >= i1; l--) {
826                            ri[l+1] = ri[l];
827                            rx[l+1] = rx[l];
828                        }
829                        ri[i1] = i__;
830                        rx[i1] = v;
831                        nnz++;
832    
833                        // the columns j "right" of the current one :
834                        for(k=j__ + 1; k <= ncol; k++)
835                            rp[k]++;
836                    }
837                }
838    #ifdef MATRIX_SUBASSIGN_VERBOSE
839                else if(verbose) REprintf("M_ij == v = %g\n", v);
840    #endif
841            }// for( ii )
842        }// for( jj )
843    
844        // now assign the i- and x- slots,  free memory and return :
845        Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_iSym,  INTSXP, nnz)), ri, nnz);
846        Memcpy(   REAL(ALLOC_SLOT(ans, Matrix_xSym, REALSXP, nnz)), rx, nnz);
847        Free(ri);
848        Free(rx);
849        UNPROTECT(4);
850        return ans;
851    }
852    
853  SEXP Csparse_MatrixMarket(SEXP x, SEXP fname)  SEXP Csparse_MatrixMarket(SEXP x, SEXP fname)
854  {  {
855      FILE *f = fopen(CHAR(asChar(fname)), "w");      FILE *f = fopen(CHAR(asChar(fname)), "w");
# Line 474  Line 857 
857      if (!f)      if (!f)
858          error(_("failure to open file \"%s\" for writing"),          error(_("failure to open file \"%s\" for writing"),
859                CHAR(asChar(fname)));                CHAR(asChar(fname)));
860      if (!cholmod_write_sparse(f, AS_CHM_SP(Csparse_diagU2N(x)),      if (!cholmod_write_sparse(f, AS_CHM_SP(x),
861                                (CHM_SP)NULL, (char*) NULL, &c))                                (CHM_SP)NULL, (char*) NULL, &c))
862          error(_("cholmod_write_sparse returned error code"));          error(_("cholmod_write_sparse returned error code"));
863      fclose(f);      fclose(f);
# Line 558  Line 941 
941          break;          break;
942    
943      default: /* -1 from above */      default: /* -1 from above */
944          error("diag_tC(): invalid 'resultKind'");          error(_("diag_tC(): invalid 'resultKind'"));
945          /* Wall: */ ans = R_NilValue; v = REAL(ans);          /* Wall: */ ans = R_NilValue; v = REAL(ans);
946      }      }
947    
# Line 588  Line 971 
971    
972      return diag_tC_ptr(n, x_p, x_x, perm, resultKind);      return diag_tC_ptr(n, x_p, x_x, perm, resultKind);
973  }  }
974    
975    /**
976     * Create a Csparse matrix object from indices and/or pointers.
977     *
978     * @param cls name of actual class of object to create
979     * @param i optional integer vector of length nnz of row indices
980     * @param j optional integer vector of length nnz of column indices
981     * @param p optional integer vector of length np of row or column pointers
982     * @param np length of integer vector p.  Must be zero if p == (int*)NULL
983     * @param x optional vector of values
984     * @param nnz length of vectors i, j and/or x, whichever is to be used
985     * @param dims optional integer vector of length 2 to be used as
986     *     dimensions.  If dims == (int*)NULL then the maximum row and column
987     *     index are used as the dimensions.
988     * @param dimnames optional list of length 2 to be used as dimnames
989     * @param index1 indicator of 1-based indices
990     *
991     * @return an SEXP of class cls inheriting from CsparseMatrix.
992     */
993    SEXP create_Csparse(char* cls, int* i, int* j, int* p, int np,
994                        void* x, int nnz, int* dims, SEXP dimnames,
995                        int index1)
996    {
997        SEXP ans;
998        int *ij = (int*)NULL, *tri, *trj,
999            mi, mj, mp, nrow = -1, ncol = -1;
1000        int xtype = -1;             /* -Wall */
1001        CHM_TR T;
1002        CHM_SP A;
1003    
1004        if (np < 0 || nnz < 0)
1005            error(_("negative vector lengths not allowed: np = %d, nnz = %d"),
1006                  np, nnz);
1007        if (1 != ((mi = (i == (int*)NULL)) +
1008                  (mj = (j == (int*)NULL)) +
1009                  (mp = (p == (int*)NULL))))
1010            error(_("exactly 1 of 'i', 'j' or 'p' must be NULL"));
1011        if (mp) {
1012            if (np) error(_("np = %d, must be zero when p is NULL"), np);
1013        } else {
1014            if (np) {               /* Expand p to form i or j */
1015                if (!(p[0])) error(_("p[0] = %d, should be zero"), p[0]);
1016                for (int ii = 0; ii < np; ii++)
1017                    if (p[ii] > p[ii + 1])
1018                        error(_("p must be non-decreasing"));
1019                if (p[np] != nnz)
1020                    error("p[np] = %d != nnz = %d", p[np], nnz);
1021                ij = Calloc(nnz, int);
1022                if (mi) {
1023                    i = ij;
1024                    nrow = np;
1025                } else {
1026                    j = ij;
1027                    ncol = np;
1028                }
1029                /* Expand p to 0-based indices */
1030                for (int ii = 0; ii < np; ii++)
1031                    for (int jj = p[ii]; jj < p[ii + 1]; jj++) ij[jj] = ii;
1032            } else {
1033                if (nnz)
1034                    error(_("Inconsistent dimensions: np = 0 and nnz = %d"),
1035                          nnz);
1036            }
1037        }
1038        /* calculate nrow and ncol */
1039        if (nrow < 0) {
1040            for (int ii = 0; ii < nnz; ii++) {
1041                int i1 = i[ii] + (index1 ? 0 : 1); /* 1-based index */
1042                if (i1 < 1) error(_("invalid row index at position %d"), ii);
1043                if (i1 > nrow) nrow = i1;
1044            }
1045        }
1046        if (ncol < 0) {
1047            for (int jj = 0; jj < nnz; jj++) {
1048                int j1 = j[jj] + (index1 ? 0 : 1);
1049                if (j1 < 1) error(_("invalid column index at position %d"), jj);
1050                if (j1 > ncol) ncol = j1;
1051            }
1052        }
1053        if (dims != (int*)NULL) {
1054            if (dims[0] > nrow) nrow = dims[0];
1055            if (dims[1] > ncol) ncol = dims[1];
1056        }
1057        /* check the class name */
1058        if (strlen(cls) != 8)
1059            error(_("strlen of cls argument = %d, should be 8"), strlen(cls));
1060        if (!strcmp(cls + 2, "CMatrix"))
1061            error(_("cls = \"%s\" does not end in \"CMatrix\""), cls);
1062        switch(cls[0]) {
1063        case 'd':
1064        case 'l':
1065            xtype = CHOLMOD_REAL;
1066        break;
1067        case 'n':
1068            xtype = CHOLMOD_PATTERN;
1069            break;
1070        default:
1071            error(_("cls = \"%s\" must begin with 'd', 'l' or 'n'"), cls);
1072        }
1073        if (cls[1] != 'g')
1074            error(_("Only 'g'eneral sparse matrix types allowed"));
1075        /* allocate and populate the triplet */
1076        T = cholmod_allocate_triplet((size_t)nrow, (size_t)ncol, (size_t)nnz, 0,
1077                                     xtype, &c);
1078        T->x = x;
1079        tri = (int*)T->i;
1080        trj = (int*)T->j;
1081        for (int ii = 0; ii < nnz; ii++) {
1082            tri[ii] = i[ii] - ((!mi && index1) ? 1 : 0);
1083            trj[ii] = j[ii] - ((!mj && index1) ? 1 : 0);
1084        }
1085        /* create the cholmod_sparse structure */
1086        A = cholmod_triplet_to_sparse(T, nnz, &c);
1087        cholmod_free_triplet(&T, &c);
1088        /* copy the information to the SEXP */
1089        ans = PROTECT(NEW_OBJECT(MAKE_CLASS(cls)));
1090    /* FIXME: This has been copied from chm_sparse_to_SEXP in chm_common.c */
1091        /* allocate and copy common slots */
1092        nnz = cholmod_nnz(A, &c);
1093        dims = INTEGER(ALLOC_SLOT(ans, Matrix_DimSym, INTSXP, 2));
1094        dims[0] = A->nrow; dims[1] = A->ncol;
1095        Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_pSym, INTSXP, A->ncol + 1)), (int*)A->p, A->ncol + 1);
1096        Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_iSym, INTSXP, nnz)), (int*)A->i, nnz);
1097        switch(cls[1]) {
1098        case 'd':
1099            Memcpy(REAL(ALLOC_SLOT(ans, Matrix_xSym, REALSXP, nnz)), (double*)A->x, nnz);
1100            break;
1101        case 'l':
1102            error(_("code not yet written for cls = \"lgCMatrix\""));
1103        }
1104    /* FIXME: dimnames are *NOT* put there yet (if non-NULL) */
1105        cholmod_free_sparse(&A, &c);
1106        UNPROTECT(1);
1107        return ans;
1108    }

Legend:
Removed from v.2175  
changed lines
  Added in v.2677

root@r-forge.r-project.org
ViewVC Help
Powered by ViewVC 1.0.0  
Thanks to:
Vienna University of Economics and Business University of Wisconsin - Madison Powered By FusionForge