SCM Repository

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

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

pkg/src/Csparse.c revision 2279, Fri Oct 3 09:15:54 2008 UTC pkg/Matrix/src/Csparse.c revision 3066, Thu Mar 19 14:27:05 2015 UTC
# Line 1  Line 1
1                          /* Sparse matrices in compressed column-oriented form */                          /* Sparse matrices in compressed column-oriented form */
2
3  #include "Csparse.h"  #include "Csparse.h"
4  #include "Tsparse.h"  #include "Tsparse.h"
5  #include "chm_common.h"  #include "chm_common.h"
# Line 32  Line 33
33      return TRUE;      return TRUE;
34  }  }
35
36  SEXP Csparse_validate(SEXP x)  SEXP Csparse_validate(SEXP x) {
37  {      return Csparse_validate_(x, FALSE);
/* NB: we do *NOT* check a potential 'x' slot here, at all */
SEXP pslot = GET_SLOT(x, Matrix_pSym),
islot = GET_SLOT(x, Matrix_iSym);
Rboolean sorted, strictly;
int j, k,
*dims = INTEGER(GET_SLOT(x, Matrix_DimSym)),
nrow = dims[0],
ncol = dims[1],
*xp = INTEGER(pslot),
*xi = INTEGER(islot);

if (length(pslot) != dims[1] + 1)
return mkString(_("slot p must have length = ncol(.) + 1"));
if (xp[0] != 0)
return mkString(_("first element of slot p must be zero"));
if (length(islot) < xp[ncol]) /* allow larger slots from over-allocation!*/
return
mkString(_("last element of slot p must match length of slots i and x"));
for (j = 0; j < xp[ncol]; j++) {
if (xi[j] < 0 || xi[j] >= nrow)
return mkString(_("all row indices must be between 0 and nrow-1"));
38      }      }
sorted = TRUE; strictly = TRUE;
for (j = 0; j < ncol; j++) {
if (xp[j] > xp[j + 1])
return mkString(_("slot p must be non-decreasing"));
if(sorted) /* only act if >= 2 entries in column j : */
for (k = xp[j] + 1; k < xp[j + 1]; k++) {
if (xi[k] < xi[k - 1])
sorted = FALSE;
else if (xi[k] == xi[k - 1])
strictly = FALSE;
}
}
if (!sorted) {
CHM_SP chx = (CHM_SP) alloca(sizeof(cholmod_sparse));
R_CheckStack();
as_cholmod_sparse(chx, x, FALSE, TRUE); /* includes cholmod_sort() ! */
/* as chx = AS_CHM_SP__(x)  but  ^^^^  sorting x in_place (no copying)*/
39
/* Now re-check that row indices are *strictly* increasing
* (and not just increasing) within each column : */
for (j = 0; j < ncol; j++) {
for (k = xp[j] + 1; k < xp[j + 1]; k++)
if (xi[k] == xi[k - 1])
return mkString(_("slot i is not *strictly* increasing inside a column (even after cholmod_sort)"));
}
40
41      } else if(!strictly) {  /* sorted, but not strictly */  #define _t_Csparse_validate
42          return mkString(_("slot i is not *strictly* increasing inside a column"));  #include "t_Csparse_validate.c"
43
44    #define _t_Csparse_sort
45    #include "t_Csparse_validate.c"
46
47    // R: .validateCsparse(x, sort.if.needed = FALSE) :
48    SEXP Csparse_validate2(SEXP x, SEXP maybe_modify) {
49        return Csparse_validate_(x, asLogical(maybe_modify));
50      }      }
51      return ScalarLogical(1);
52    // R: Matrix:::.sortCsparse(x) :
53    SEXP Csparse_sort (SEXP x) {
54       int ok = Csparse_sort_2(x, TRUE); // modifying x directly
55       if(!ok) warning(_("Csparse_sort(x): x is not a valid (apart from sorting) CsparseMatrix"));
56       return x;
57  }  }
58
59  SEXP Rsparse_validate(SEXP x)  SEXP Rsparse_validate(SEXP x)
# Line 133  Line 101
101      return ScalarLogical(1);      return ScalarLogical(1);
102  }  }
103
104    /**
105  /* Called from ../R/Csparse.R : */   * From a CsparseMatrix, produce a dense one.
106  /* Can only return [dln]geMatrix (no symm/triang);   * Directly deals with symmetric, triangular and general.
107   * FIXME: replace by non-CHOLMOD code ! */   * Called from ../R/Csparse.R's  C2dense()
108  SEXP Csparse_to_dense(SEXP x)   *
109     * @param x a CsparseMatrix: currently all 9 of  "[dln][gst]CMatrix"
110     * @param symm_or_tri integer (NA, < 0, > 0, = 0) specifying the knowledge of the caller about x:
111     *      NA  : unknown => will be determined
112     *      = 0 : "generalMatrix" (not symm or tri);
113     *      < 0 : "triangularMatrix"
114     *      > 0 : "symmetricMatrix"
115     *
116     * @return a "denseMatrix"
117     */
118    SEXP Csparse_to_dense(SEXP x, SEXP symm_or_tri)
119  {  {
120      CHM_SP chxs = AS_CHM_SP__(x);      Rboolean is_sym, is_tri;
121      /* This loses the symmetry property, since cholmod_dense has none,      int is_sym_or_tri = asInteger(symm_or_tri),
122            ctype = 0; // <- default = "dgC"
123        static const char *valid[] = { MATRIX_VALID_Csparse, ""};
124        if(is_sym_or_tri == NA_INTEGER) { // find if  is(x, "symmetricMatrix") :
125            ctype = Matrix_check_class_etc(x, valid);
126            is_sym = (ctype % 3 == 1);
127            is_tri = (ctype % 3 == 2);
128        } else {
129            is_sym = is_sym_or_tri > 0;
130            is_tri = is_sym_or_tri < 0;
131            // => both are FALSE  iff  is_.. == 0
132            if(is_sym || is_tri)
133                ctype = Matrix_check_class_etc(x, valid);
134        }
135        CHM_SP chxs = AS_CHM_SP__(x);// -> chxs->stype = +- 1 <==> symmetric
136        R_CheckStack();
137        if(is_tri && *diag_P(x) == 'U') { // ==>  x := diagU2N(x), directly for chxs
138            CHM_SP eye = cholmod_speye(chxs->nrow, chxs->ncol, chxs->xtype, &c);
139            double one[] = {1, 0};
140            CHM_SP ans = cholmod_add(chxs, eye, one, one,
141                                     /* values: */ ((ctype / 3) != 2), // TRUE iff not "nMatrix"
142                                     TRUE, &c);
143            cholmod_free_sparse(&eye, &c);
144            chxs = cholmod_copy_sparse(ans, &c);
145            cholmod_free_sparse(&ans, &c);
146        }
147        /* The following loses the symmetry property, since cholmod_dense has none,
148       * BUT, much worse (FIXME!), it also transforms CHOLMOD_PATTERN ("n") matrices       * BUT, much worse (FIXME!), it also transforms CHOLMOD_PATTERN ("n") matrices
149       * to numeric (CHOLMOD_REAL) ones : */       * to numeric (CHOLMOD_REAL) ones {and we "revert" via chm_dense_to_SEXP()}: */
150      CHM_DN chxd = cholmod_sparse_to_dense(chxs, &c);      CHM_DN chxd = cholmod_sparse_to_dense(chxs, &c);
151      int Rkind = (chxs->xtype == CHOLMOD_PATTERN)? -1 : Real_kind(x);      int Rkind = (chxs->xtype == CHOLMOD_PATTERN)? -1 : Real_kind(x);
R_CheckStack();
152
153      return chm_dense_to_SEXP(chxd, 1, Rkind, GET_SLOT(x, Matrix_DimNamesSym));      SEXP ans = chm_dense_to_SEXP(chxd, 1, Rkind,GET_SLOT(x, Matrix_DimNamesSym));
154        // -> a [dln]geMatrix
155        if(is_sym) { // ==> want  [dln]syMatrix
156            const char cl1 = class_P(ans)[0];
157            PROTECT(ans);
158            SEXP aa = PROTECT(NEW_OBJECT(MAKE_CLASS((cl1 == 'd') ? "dsyMatrix" :
159                                                    ((cl1 == 'l') ? "lsyMatrix" : "nsyMatrix"))));
160            // No need to duplicate() as slots of ans are freshly allocated and ans will not be used
161            SET_SLOT(aa, Matrix_xSym,       GET_SLOT(ans, Matrix_xSym));
162            SET_SLOT(aa, Matrix_DimSym,     GET_SLOT(ans, Matrix_DimSym));
163            SET_SLOT(aa, Matrix_DimNamesSym,GET_SLOT(ans, Matrix_DimNamesSym));
164            SET_SLOT(aa, Matrix_uploSym, mkString((chxs->stype > 0) ? "U" : "L"));
165            UNPROTECT(2);
166            return aa;
167        }
168        else if(is_tri) { // ==> want  [dln]trMatrix
169            const char cl1 = class_P(ans)[0];
170            PROTECT(ans);
171            SEXP aa = PROTECT(NEW_OBJECT(MAKE_CLASS((cl1 == 'd') ? "dtrMatrix" :
172                                                    ((cl1 == 'l') ? "ltrMatrix" : "ntrMatrix"))));
173            // No need to duplicate() as slots of ans are freshly allocated and ans will not be used
174            SET_SLOT(aa, Matrix_xSym,       GET_SLOT(ans, Matrix_xSym));
175            SET_SLOT(aa, Matrix_DimSym,     GET_SLOT(ans, Matrix_DimSym));
176            SET_SLOT(aa, Matrix_DimNamesSym,GET_SLOT(ans, Matrix_DimNamesSym));
177            slot_dup(aa, x, Matrix_uploSym);
178            /* already by NEW_OBJECT(..) above:
179               SET_SLOT(aa, Matrix_diagSym, mkString("N")); */
180            UNPROTECT(2);
181            return aa;
182        }
183        else
184            return ans;
185  }  }
186
187    // FIXME: do not go via CHM (should not be too hard, to just *drop* the x-slot, right?
188  SEXP Csparse_to_nz_pattern(SEXP x, SEXP tri)  SEXP Csparse_to_nz_pattern(SEXP x, SEXP tri)
189  {  {
190      CHM_SP chxs = AS_CHM_SP__(x);      CHM_SP chxs = AS_CHM_SP__(x);
# Line 163  Line 198
198                                GET_SLOT(x, Matrix_DimNamesSym));                                GET_SLOT(x, Matrix_DimNamesSym));
199  }  }
200
201  SEXP Csparse_to_matrix(SEXP x)  // n.CMatrix --> [dli].CMatrix  (not going through CHM!)
202    SEXP nz_pattern_to_Csparse(SEXP x, SEXP res_kind)
203  {  {
204      return chm_dense_to_matrix(cholmod_sparse_to_dense(AS_CHM_SP__(x), &c),      return nz2Csparse(x, asInteger(res_kind));
205                                 1 /*do_free*/, GET_SLOT(x, Matrix_DimNamesSym));  }
206
207    // n.CMatrix --> [dli].CMatrix  (not going through CHM!)
208    // NOTE: use chm_MOD_xtype(() to change type of  'cholmod_sparse' matrix
209    SEXP nz2Csparse(SEXP x, enum x_slot_kind r_kind)
210    {
211        const char *cl_x = class_P(x);
212        if(cl_x[0] != 'n') error(_("not a 'n.CMatrix'"));
213        if(cl_x[2] != 'C') error(_("not a CsparseMatrix"));
214        int nnz = LENGTH(GET_SLOT(x, Matrix_iSym));
215        SEXP ans;
216        char *ncl = alloca(strlen(cl_x) + 1); /* not much memory required */
217        strcpy(ncl, cl_x);
218        double *dx_x; int *ix_x;
219        ncl[0] = (r_kind == x_double ? 'd' :
220                  (r_kind == x_logical ? 'l' :
221                   /* else (for now):  r_kind == x_integer : */ 'i'));
222        PROTECT(ans = NEW_OBJECT(MAKE_CLASS(ncl)));
223        // create a correct 'x' slot:
224        switch(r_kind) {
225            int i;
226        case x_double: // 'd'
227            dx_x = REAL(ALLOC_SLOT(ans, Matrix_xSym, REALSXP, nnz));
228            for (i=0; i < nnz; i++) dx_x[i] = 1.;
229            break;
230        case x_logical: // 'l'
231            ix_x = LOGICAL(ALLOC_SLOT(ans, Matrix_xSym, LGLSXP, nnz));
232            for (i=0; i < nnz; i++) ix_x[i] = TRUE;
233            break;
234        case x_integer: // 'i'
235            ix_x = INTEGER(ALLOC_SLOT(ans, Matrix_xSym, INTSXP, nnz));
236            for (i=0; i < nnz; i++) ix_x[i] = 1;
237            break;
238
239        default:
240            error(_("nz2Csparse(): invalid/non-implemented r_kind = %d"),
241                  r_kind);
242        }
243
244        // now copy all other slots :
245        slot_dup(ans, x, Matrix_iSym);
246        slot_dup(ans, x, Matrix_pSym);
247        slot_dup(ans, x, Matrix_DimSym);
248        slot_dup(ans, x, Matrix_DimNamesSym);
249        if(ncl[1] != 'g') { // symmetric or triangular ...
250            slot_dup_if_has(ans, x, Matrix_uploSym);
251            slot_dup_if_has(ans, x, Matrix_diagSym);
252        }
253        UNPROTECT(1);
254        return ans;
255    }
256
257    SEXP Csparse_to_matrix(SEXP x, SEXP chk, SEXP symm)
258    {
259        int is_sym = asLogical(symm);
260        if(is_sym == NA_LOGICAL) { // find if  is(x, "symmetricMatrix") :
261            static const char *valid[] = { MATRIX_VALID_Csparse, ""};
262            int ctype = Matrix_check_class_etc(x, valid);
263            is_sym = (ctype % 3 == 1);
264        }
265        return chm_dense_to_matrix(
266            cholmod_sparse_to_dense(AS_CHM_SP2(x, asLogical(chk)), &c),
267            1 /*do_free*/,
268            (is_sym
269             ? symmetric_DimNames(GET_SLOT(x, Matrix_DimNamesSym))
270             :                    GET_SLOT(x, Matrix_DimNamesSym)));
271    }
272
273    SEXP Csparse_to_vector(SEXP x)
274    {
275        return chm_dense_to_vector(cholmod_sparse_to_dense(AS_CHM_SP__(x), &c), 1);
276  }  }
277
278  SEXP Csparse_to_Tsparse(SEXP x, SEXP tri)  SEXP Csparse_to_Tsparse(SEXP x, SEXP tri)
# Line 183  Line 289
289                                 GET_SLOT(x, Matrix_DimNamesSym));                                 GET_SLOT(x, Matrix_DimNamesSym));
290  }  }
291
292  /* this used to be called  sCMatrix_to_gCMatrix(..)   [in ./dsCMatrix.c ]: */  SEXP Csparse_to_tCsparse(SEXP x, SEXP uplo, SEXP diag)
293    {
294        CHM_SP chxs = AS_CHM_SP__(x);
295        int Rkind = (chxs->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
296        R_CheckStack();
297        return chm_sparse_to_SEXP(chxs, /* dofree = */ 0,
298                                  /* uploT = */ (*CHAR(asChar(uplo)) == 'U')? 1: -1,
299                                   Rkind, /* diag = */ CHAR(STRING_ELT(diag, 0)),
300                                   GET_SLOT(x, Matrix_DimNamesSym));
301    }
302
303    SEXP Csparse_to_tTsparse(SEXP x, SEXP uplo, SEXP diag)
304    {
305        CHM_SP chxs = AS_CHM_SP__(x);
306        CHM_TR chxt = cholmod_sparse_to_triplet(chxs, &c);
307        int Rkind = (chxs->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
308        R_CheckStack();
309        return chm_triplet_to_SEXP(chxt, 1,
310                                  /* uploT = */ (*CHAR(asChar(uplo)) == 'U')? 1: -1,
311                                   Rkind, /* diag = */ CHAR(STRING_ELT(diag, 0)),
312                                   GET_SLOT(x, Matrix_DimNamesSym));
313    }
314
315
316  SEXP Csparse_symmetric_to_general(SEXP x)  SEXP Csparse_symmetric_to_general(SEXP x)
317  {  {
318      CHM_SP chx = AS_CHM_SP__(x), chgx;      CHM_SP chx = AS_CHM_SP__(x), chgx;
# Line 195  Line 324
324      chgx = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);      chgx = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);
325      /* xtype: pattern, "real", complex or .. */      /* xtype: pattern, "real", complex or .. */
326      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",
327                                GET_SLOT(x, Matrix_DimNamesSym));                                symmetric_DimNames(GET_SLOT(x, Matrix_DimNamesSym)));
328  }  }
329
330  SEXP Csparse_general_to_symmetric(SEXP x, SEXP uplo)  SEXP Csparse_general_to_symmetric(SEXP x, SEXP uplo, SEXP sym_dmns)
331  {  {
334            error(_("Csparse_general_to_symmetric(): matrix is not square!"));
335            return R_NilValue; /* -Wall */
336        }
337      CHM_SP chx = AS_CHM_SP__(x), chgx;      CHM_SP chx = AS_CHM_SP__(x), chgx;
338      int uploT = (*CHAR(STRING_ELT(uplo,0)) == 'U') ? 1 : -1;      int uploT = (*CHAR(asChar(uplo)) == 'U') ? 1 : -1;
339      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
340      R_CheckStack();      R_CheckStack();

341      chgx = cholmod_copy(chx, /* stype: */ uploT, chx->xtype, &c);      chgx = cholmod_copy(chx, /* stype: */ uploT, chx->xtype, &c);
342
343        SEXP dns = GET_SLOT(x, Matrix_DimNamesSym);
344        if(asLogical(sym_dmns))
345            dns = symmetric_DimNames(dns);
346        else if((!isNull(VECTOR_ELT(dns, 0)) &&
347                 !isNull(VECTOR_ELT(dns, 1))) ||
348                !isNull(getAttrib(dns, R_NamesSymbol))) {
349            /* symmetrize them if both are not NULL
350             * or names(dimnames(.)) is asymmetric : */
351            dns = PROTECT(duplicate(dns));
352            if(!equal_string_vectors(VECTOR_ELT(dns, 0),
353                                     VECTOR_ELT(dns, 1))) {
354                if(uploT == 1)
355                    SET_VECTOR_ELT(dns, 0, VECTOR_ELT(dns,1));
356                else
357                    SET_VECTOR_ELT(dns, 1, VECTOR_ELT(dns,0));
358            }
359            SEXP nms_dns = getAttrib(dns, R_NamesSymbol);
360            if(!isNull(nms_dns) &&  // names(dimnames(.)) :
361               !R_compute_identical(STRING_ELT(nms_dns, 0),
362                                    STRING_ELT(nms_dns, 1), 16)) {
363                if(uploT == 1)
364                    SET_STRING_ELT(nms_dns, 0, STRING_ELT(nms_dns,1));
365                else
366                    SET_STRING_ELT(nms_dns, 1, STRING_ELT(nms_dns,0));
367                setAttrib(dns, R_NamesSymbol, nms_dns);
368            }
369            UNPROTECT(1);
370        }
371      /* xtype: pattern, "real", complex or .. */      /* xtype: pattern, "real", complex or .. */
372      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "", dns);
GET_SLOT(x, Matrix_DimNamesSym));
373  }  }
374
375  SEXP Csparse_transpose(SEXP x, SEXP tri)  SEXP Csparse_transpose(SEXP x, SEXP tri)
# Line 225  Line 386
386      tmp = VECTOR_ELT(dn, 0);    /* swap the dimnames */      tmp = VECTOR_ELT(dn, 0);    /* swap the dimnames */
387      SET_VECTOR_ELT(dn, 0, VECTOR_ELT(dn, 1));      SET_VECTOR_ELT(dn, 0, VECTOR_ELT(dn, 1));
388      SET_VECTOR_ELT(dn, 1, tmp);      SET_VECTOR_ELT(dn, 1, tmp);
389        if(!isNull(tmp = getAttrib(dn, R_NamesSymbol))) { // swap names(dimnames(.)):
390            SEXP nms_dns = PROTECT(allocVector(VECSXP, 2));
391            SET_VECTOR_ELT(nms_dns, 1, STRING_ELT(tmp, 0));
392            SET_VECTOR_ELT(nms_dns, 0, STRING_ELT(tmp, 1));
393            setAttrib(dn, R_NamesSymbol, nms_dns);
394            UNPROTECT(1);
395        }
396      UNPROTECT(1);      UNPROTECT(1);
397      return chm_sparse_to_SEXP(chxt, 1, /* SWAP 'uplo' for triangular */      return chm_sparse_to_SEXP(chxt, 1, /* SWAP 'uplo' for triangular */
398                                tr ? ((*uplo_P(x) == 'U') ? -1 : 1) : 0,                                tr ? ((*uplo_P(x) == 'U') ? -1 : 1) : 0,
# Line 237  Line 405
405          cha = AS_CHM_SP(a),          cha = AS_CHM_SP(a),
406          chb = AS_CHM_SP(b),          chb = AS_CHM_SP(b),
407          chc = cholmod_ssmult(cha, chb, /*out_stype:*/ 0,          chc = cholmod_ssmult(cha, chb, /*out_stype:*/ 0,
408                               cha->xtype, /*out sorted:*/ 1, &c);                               // values:= is_numeric (T/F) if _one_ is numeric:
409                                 cha->xtype > 0 || chb->xtype > 0,
410                                 /*out sorted:*/ 1, &c);
411      const char *cl_a = class_P(a), *cl_b = class_P(b);      const char *cl_a = class_P(a), *cl_b = class_P(b);
412      char diag[] = {'\0', '\0'};      char diag[] = {'\0', '\0'};
413      int uploT = 0;      int uploT = 0;
414      SEXP dn = allocVector(VECSXP, 2);      SEXP dn = PROTECT(allocVector(VECSXP, 2));
415      R_CheckStack();      R_CheckStack();
416
417    #ifdef DEBUG_Matrix_verbose
418        Rprintf("DBG Csparse_C*_prod(%s, %s)\n", cl_a, cl_b);
419    #endif
420
421      /* Preserve triangularity and even unit-triangularity if appropriate.      /* Preserve triangularity and even unit-triangularity if appropriate.
422       * Note that in that case, the multiplication itself should happen       * Note that in that case, the multiplication itself should happen
423       * faster.  But there's no support for that in CHOLMOD */       * faster.  But there's no support for that in CHOLMOD */
# Line 265  Line 439
439                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));
440      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
441                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), 1)));
442        UNPROTECT(1);
443      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);
444  }  }
445
# Line 278  Line 453
453      const char *cl_a = class_P(a), *cl_b = class_P(b);      const char *cl_a = class_P(a), *cl_b = class_P(b);
454      char diag[] = {'\0', '\0'};      char diag[] = {'\0', '\0'};
455      int uploT = 0;      int uploT = 0;
456      SEXP dn = allocVector(VECSXP, 2);      SEXP dn = PROTECT(allocVector(VECSXP, 2));
457      R_CheckStack();      R_CheckStack();
458
459      chTr = cholmod_transpose((tr) ? chb : cha, chb->xtype, &c);      chTr = cholmod_transpose((tr) ? chb : cha, chb->xtype, &c);
# Line 297  Line 472
472              }              }
473              else diag[0]= 'N';              else diag[0]= 'N';
474          }          }

475      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
476                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), (tr) ? 0 : 1)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), (tr) ? 0 : 1)));
477      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
478                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), (tr) ? 0 : 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), (tr) ? 0 : 1)));
479        UNPROTECT(1);
480      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);
481  }  }
482
483  SEXP Csparse_dense_prod(SEXP a, SEXP b)  SEXP Csparse_dense_prod(SEXP a, SEXP b)
484  {  {
485      CHM_SP cha = AS_CHM_SP(a);      CHM_SP cha = AS_CHM_SP(a);
486      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix(b));      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix2(b, // transpose_if_vector =
487                                                 cha->ncol == 1));
488      CHM_DN chb = AS_CHM_DN(b_M);      CHM_DN chb = AS_CHM_DN(b_M);
489      CHM_DN chc = cholmod_allocate_dense(cha->nrow, chb->ncol, cha->nrow,      CHM_DN chc = cholmod_allocate_dense(cha->nrow, chb->ncol, cha->nrow,
490                                          chb->xtype, &c);                                          chb->xtype, &c);
491      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2));
492      double one[] = {1,0}, zero[] = {0,0};      double one[] = {1,0}, zero[] = {0,0};
493        int nprot = 2;
494      R_CheckStack();      R_CheckStack();
495        /* Tim Davis, please FIXME:  currently (2010-11) *fails* when  a  is a pattern matrix:*/
496        if(cha->xtype == CHOLMOD_PATTERN) {
497            /* warning(_("Csparse_dense_prod(): cholmod_sdmult() not yet implemented for pattern./ ngCMatrix" */
498            /*        " --> slightly inefficient coercion")); */
499
500            // This *fails* to produce a CHOLMOD_REAL ..
501            // CHM_SP chd = cholmod_l_copy(cha, cha->stype, CHOLMOD_REAL, &c);
502            // --> use our Matrix-classes
503            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
504            cha = AS_CHM_SP(da);
505        }
506      cholmod_sdmult(cha, 0, one, zero, chb, chc, &c);      cholmod_sdmult(cha, 0, one, zero, chb, chc, &c);
507      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
508                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));
509      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
510                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));
511      UNPROTECT(2);      UNPROTECT(nprot);
512      return chm_dense_to_SEXP(chc, 1, 0, dn);      return chm_dense_to_SEXP(chc, 1, 0, dn);
513  }  }
514
515  SEXP Csparse_dense_crossprod(SEXP a, SEXP b)  SEXP Csparse_dense_crossprod(SEXP a, SEXP b)
516  {  {
517      CHM_SP cha = AS_CHM_SP(a);      CHM_SP cha = AS_CHM_SP(a);
518      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix(b));      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix2(b, // transpose_if_vector =
519                                                 cha->nrow == 1));
520      CHM_DN chb = AS_CHM_DN(b_M);      CHM_DN chb = AS_CHM_DN(b_M);
521      CHM_DN chc = cholmod_allocate_dense(cha->ncol, chb->ncol, cha->ncol,      CHM_DN chc = cholmod_allocate_dense(cha->ncol, chb->ncol, cha->ncol,
522                                          chb->xtype, &c);                                          chb->xtype, &c);
523      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2)); int nprot = 2;
524      double one[] = {1,0}, zero[] = {0,0};      double one[] = {1,0}, zero[] = {0,0};
525      R_CheckStack();      R_CheckStack();
526        // -- see Csparse_dense_prod() above :
527        if(cha->xtype == CHOLMOD_PATTERN) {
528            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
529            cha = AS_CHM_SP(da);
530        }
531      cholmod_sdmult(cha, 1, one, zero, chb, chc, &c);      cholmod_sdmult(cha, 1, one, zero, chb, chc, &c);
532      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
533                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 1)));
534      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
535                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));
536      UNPROTECT(2);      UNPROTECT(nprot);
537      return chm_dense_to_SEXP(chc, 1, 0, dn);      return chm_dense_to_SEXP(chc, 1, 0, dn);
538  }  }
539
# Line 351  Line 543
543  {  {
544      int trip = asLogical(triplet),      int trip = asLogical(triplet),
545          tr   = asLogical(trans); /* gets reversed because _aat is tcrossprod */          tr   = asLogical(trans); /* gets reversed because _aat is tcrossprod */
546    #ifdef AS_CHM_DIAGU2N_FIXED_FINALLY
547      CHM_TR cht = trip ? AS_CHM_TR(x) : (CHM_TR) NULL;      CHM_TR cht = trip ? AS_CHM_TR(x) : (CHM_TR) NULL;
548    #else /* workaround needed:*/
549        SEXP xx = PROTECT(Tsparse_diagU2N(x));
550        CHM_TR cht = trip ? AS_CHM_TR__(xx) : (CHM_TR) NULL;
551    #endif
552      CHM_SP chcp, chxt,      CHM_SP chcp, chxt,
553          chx = (trip ?          chx = (trip ?
554                 cholmod_triplet_to_sparse(cht, cht->nnz, &c) :                 cholmod_triplet_to_sparse(cht, cht->nnz, &c) :
# Line 373  Line 570
570                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),
571                                          (tr) ? 0 : 1)));                                          (tr) ? 0 : 1)));
572      SET_VECTOR_ELT(dn, 1, duplicate(VECTOR_ELT(dn, 0)));      SET_VECTOR_ELT(dn, 1, duplicate(VECTOR_ELT(dn, 0)));
573    #ifdef AS_CHM_DIAGU2N_FIXED_FINALLY
574      UNPROTECT(1);      UNPROTECT(1);
575    #else
576        UNPROTECT(2);
577    #endif
578      return chm_sparse_to_SEXP(chcp, 1, 0, 0, "", dn);      return chm_sparse_to_SEXP(chcp, 1, 0, 0, "", dn);
579  }  }
580
581    /* Csparse_drop(x, tol):  drop entries with absolute value < tol, i.e,
582    *  at least all "explicit" zeros */
583  SEXP Csparse_drop(SEXP x, SEXP tol)  SEXP Csparse_drop(SEXP x, SEXP tol)
584  {  {
585      const char *cl = class_P(x);      const char *cl = class_P(x);
# Line 398  Line 601
601
602  SEXP Csparse_horzcat(SEXP x, SEXP y)  SEXP Csparse_horzcat(SEXP x, SEXP y)
603  {  {
604      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);  #define CSPARSE_CAT(_KIND_)                                             \
605      int Rkind = 0; /* only for "d" - FIXME */      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);                  \
606      R_CheckStack();      R_CheckStack();                                                     \
607        int Rk_x = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : -3,     \
608            Rk_y = (chy->xtype != CHOLMOD_PATTERN) ? Real_kind(y) : -3, Rkind; \
609        if(Rk_x == -3 || Rk_y == -3) { /* at least one of them is patter"n" */ \
610            if(Rk_x == -3 && Rk_y == -3) { /* fine */                       \
611            } else { /* only one is a patter"n"                             \
612                      * "Bug" in cholmod_horzcat()/vertcat(): returns patter"n" matrix if one of them is */ \
613                Rboolean ok;                                                \
614                if(Rk_x == -3) {                                            \
615                    ok = chm_MOD_xtype(CHOLMOD_REAL, chx, &c); Rk_x = 0;    \
616                } else if(Rk_y == -3) {                                     \
617                    ok = chm_MOD_xtype(CHOLMOD_REAL, chy, &c); Rk_y = 0;    \
618                } else                                                      \
619                    error(_("Impossible Rk_x/Rk_y in Csparse_%s(), please report"), _KIND_); \
620                if(!ok)                                                     \
621                    error(_("chm_MOD_xtype() was not successful in Csparse_%s(), please report"), \
622                          _KIND_);                                          \
623            }                                                               \
624        }                                                                   \
625        Rkind = /* logical if both x and y are */ (Rk_x == 1 && Rk_y == 1) ? 1 : 0
626
627        CSPARSE_CAT("horzcat");
628        // TODO: currently drops dimnames - and we fix at R level;
629
/* FIXME: currently drops dimnames */
630      return chm_sparse_to_SEXP(cholmod_horzcat(chx, chy, 1, &c),      return chm_sparse_to_SEXP(cholmod_horzcat(chx, chy, 1, &c),
631                                1, 0, Rkind, "", R_NilValue);                                1, 0, Rkind, "", R_NilValue);
632  }  }
633
634  SEXP Csparse_vertcat(SEXP x, SEXP y)  SEXP Csparse_vertcat(SEXP x, SEXP y)
635  {  {
636      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);      CSPARSE_CAT("vertcat");
637      int Rkind = 0; /* only for "d" - FIXME */      // TODO: currently drops dimnames - and we fix at R level;
R_CheckStack();
638
/* FIXME: currently drops dimnames */
639      return chm_sparse_to_SEXP(cholmod_vertcat(chx, chy, 1, &c),      return chm_sparse_to_SEXP(cholmod_vertcat(chx, chy, 1, &c),
640                                1, 0, Rkind, "", R_NilValue);                                1, 0, Rkind, "", R_NilValue);
641  }  }
# Line 464  Line 686
686      }      }
687      else { /* triangular with diag='N'): now drop the diagonal */      else { /* triangular with diag='N'): now drop the diagonal */
688          /* duplicate, since chx will be modified: */          /* duplicate, since chx will be modified: */
689          CHM_SP chx = AS_CHM_SP__(duplicate(x));          SEXP xx = PROTECT(duplicate(x));
690            CHM_SP chx = AS_CHM_SP__(xx);
691          int uploT = (*uplo_P(x) == 'U') ? 1 : -1,          int uploT = (*uplo_P(x) == 'U') ? 1 : -1,
692              Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;              Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
693          R_CheckStack();          R_CheckStack();
694
695          chm_diagN2U(chx, uploT, /* do_realloc */ FALSE);          chm_diagN2U(chx, uploT, /* do_realloc */ FALSE);
696
697          return chm_sparse_to_SEXP(chx, /*dofree*/ 0/* or 1 ?? */,          SEXP ans = chm_sparse_to_SEXP(chx, /*dofree*/ 0/* or 1 ?? */,
698                                    uploT, Rkind, "U",                                    uploT, Rkind, "U",
699                                    GET_SLOT(x, Matrix_DimNamesSym));                                    GET_SLOT(x, Matrix_DimNamesSym));
700            UNPROTECT(1);// only now !
701            return ans;
702      }      }
703  }  }
704
705    /**
706     * "Indexing" aka subsetting : Compute  x[i,j], also for vectors i and j
707     * Working via CHOLMOD_submatrix, see ./CHOLMOD/MatrixOps/cholmod_submatrix.c
708     * @param x CsparseMatrix
709     * @param i row     indices (0-origin), or NULL (R's)
710     * @param j columns indices (0-origin), or NULL
711     *
712     * @return x[i,j]  still CsparseMatrix --- currently, this loses dimnames
713     */
714  SEXP Csparse_submatrix(SEXP x, SEXP i, SEXP j)  SEXP Csparse_submatrix(SEXP x, SEXP i, SEXP j)
715  {  {
716      CHM_SP chx = AS_CHM_SP__(x);      CHM_SP chx = AS_CHM_SP(x); /* << does diagU2N() when needed */
717      int rsize = (isNull(i)) ? -1 : LENGTH(i),      int rsize = (isNull(i)) ? -1 : LENGTH(i),
718          csize = (isNull(j)) ? -1 : LENGTH(j);          csize = (isNull(j)) ? -1 : LENGTH(j);
719      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
# Line 490  Line 724
724      if (csize >= 0 && !isInteger(j))      if (csize >= 0 && !isInteger(j))
725          error(_("Index j must be NULL or integer"));          error(_("Index j must be NULL or integer"));
726
727      return chm_sparse_to_SEXP(cholmod_submatrix(chx, INTEGER(i), rsize,  #define CHM_SUB(_M_, _i_, _j_)                                  \
728                                                  INTEGER(j), csize,      cholmod_submatrix(_M_,                                      \
729                                                  TRUE, TRUE, &c),                        (rsize < 0) ? NULL : INTEGER(_i_), rsize, \
730                                1, 0, Rkind, "",                        (csize < 0) ? NULL : INTEGER(_j_), csize, \
731                                /* FIXME: drops dimnames */ R_NilValue);                        TRUE, TRUE, &c)
732  }      CHM_SP ans;
733        if (!chx->stype) {/* non-symmetric Matrix */
734            ans = CHM_SUB(chx, i, j);
735        }
736        else {
737            /* for now, cholmod_submatrix() only accepts "generalMatrix" */
738            CHM_SP tmp = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);
739            ans = CHM_SUB(tmp, i, j);
740            cholmod_free_sparse(&tmp, &c);
741        }
742
743        // "FIXME": currently dropping dimnames, and adding them afterwards in R :
744        /* // dimnames: */
745        /* SEXP x_dns = GET_SLOT(x, Matrix_DimNamesSym), */
746        /*  dn = PROTECT(allocVector(VECSXP, 2)); */
747        return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "", /* dimnames: */ R_NilValue);
748    }
749
750    #define _d_Csp_
751    #include "t_Csparse_subassign.c"
752
753    #define _l_Csp_
754    #include "t_Csparse_subassign.c"
755
756    #define _i_Csp_
757    #include "t_Csparse_subassign.c"
758
759    #define _n_Csp_
760    #include "t_Csparse_subassign.c"
761
762    #define _z_Csp_
763    #include "t_Csparse_subassign.c"
764
765
766
767  SEXP Csparse_MatrixMarket(SEXP x, SEXP fname)  SEXP Csparse_MatrixMarket(SEXP x, SEXP fname)
768  {  {
# Line 524  Line 791
791   *   *
792   * @return  a SEXP, either a (double) number or a length n-vector of diagonal entries   * @return  a SEXP, either a (double) number or a length n-vector of diagonal entries
793   */   */
794  SEXP diag_tC_ptr(int n, int *x_p, double *x_x, int *perm, SEXP resultKind)  SEXP diag_tC_ptr(int n, int *x_p, double *x_x, Rboolean is_U, int *perm,
795  /*                                ^^^^^^ FIXME[Generalize] to int / ... */  /*                                ^^^^^^ FIXME[Generalize] to int / ... */
796                     SEXP resultKind)
797  {  {
798      const char* res_ch = CHAR(STRING_ELT(resultKind,0));      const char* res_ch = CHAR(STRING_ELT(resultKind,0));
799      enum diag_kind { diag, diag_backpermuted, trace, prod, sum_log      enum diag_kind { diag, diag_backpermuted, trace, prod, sum_log, min, max, range
800      } res_kind = ((!strcmp(res_ch, "trace")) ? trace :      } res_kind = ((!strcmp(res_ch, "trace")) ? trace :
801                    ((!strcmp(res_ch, "sumLog")) ? sum_log :                    ((!strcmp(res_ch, "sumLog")) ? sum_log :
802                     ((!strcmp(res_ch, "prod")) ? prod :                     ((!strcmp(res_ch, "prod")) ? prod :
803                        ((!strcmp(res_ch, "min")) ? min :
804                         ((!strcmp(res_ch, "max")) ? max :
805                          ((!strcmp(res_ch, "range")) ? range :
806                      ((!strcmp(res_ch, "diag")) ? diag :                      ((!strcmp(res_ch, "diag")) ? diag :
807                       ((!strcmp(res_ch, "diagBack")) ? diag_backpermuted :                       ((!strcmp(res_ch, "diagBack")) ? diag_backpermuted :
808                        -1)))));                           -1))))))));
809      int i, n_x, i_from = 0;      int i, n_x, i_from;
810      SEXP ans = PROTECT(allocVector(REALSXP,      SEXP ans = PROTECT(allocVector(REALSXP,
811  /*                                 ^^^^  FIXME[Generalize] */  /*                                 ^^^^  FIXME[Generalize] */
812                                     (res_kind == diag ||                                     (res_kind == diag ||
813                                      res_kind == diag_backpermuted) ? n : 1));                                      res_kind == diag_backpermuted) ? n :
814                                       (res_kind == range ? 2 : 1)));
815      double *v = REAL(ans);      double *v = REAL(ans);
816  /*  ^^^^^^      ^^^^  FIXME[Generalize] */  /*  ^^^^^^      ^^^^  FIXME[Generalize] */
817
818        i_from = (is_U ? -1 : 0);
819
820  #define for_DIAG(v_ASSIGN)                                              \  #define for_DIAG(v_ASSIGN)                                              \
821      for(i = 0; i < n; i++, i_from += n_x) {                             \      for(i = 0; i < n; i++) {                                    \
822          /* looking at i-th column */                                    \          /* looking at i-th column */                                    \
823          n_x = x_p[i+1] - x_p[i];/* #{entries} in this column */ \          n_x = x_p[i+1] - x_p[i];/* #{entries} in this column */ \
824            if( is_U) i_from += n_x;                                \
825          v_ASSIGN;                                                       \          v_ASSIGN;                                                       \
826            if(!is_U) i_from += n_x;                                \
827      }      }
828
829      /* NOTA BENE: we assume  -- uplo = "L" i.e. lower triangular matrix      /* NOTA BENE: we assume  -- uplo = "L" i.e. lower triangular matrix
830       *            for uplo = "U" (makes sense with a "dtCMatrix" !),       *            for uplo = "U" (makes sense with a "dtCMatrix" !),
831       *            should use  x_x[i_from + (nx - 1)] instead of x_x[i_from],       *            should use  x_x[i_from + (n_x - 1)] instead of x_x[i_from],
832       *            where nx = (x_p[i+1] - x_p[i])       *            where n_x = (x_p[i+1] - x_p[i])
833       */       */
834
835      switch(res_kind) {      switch(res_kind) {
836      case trace:      case trace: // = sum
837          v[0] = 0.;          v[0] = 0.;
838          for_DIAG(v[0] += x_x[i_from]);          for_DIAG(v[0] += x_x[i_from]);
839          break;          break;
# Line 572  Line 848
848          for_DIAG(v[0] *= x_x[i_from]);          for_DIAG(v[0] *= x_x[i_from]);
849          break;          break;
850
851        case min:
852            v[0] = R_PosInf;
853            for_DIAG(if(v[0] > x_x[i_from]) v[0] = x_x[i_from]);
854            break;
855
856        case max:
857            v[0] = R_NegInf;
858            for_DIAG(if(v[0] < x_x[i_from]) v[0] = x_x[i_from]);
859            break;
860
861        case range:
862            v[0] = R_PosInf;
863            v[1] = R_NegInf;
864            for_DIAG(if(v[0] > x_x[i_from]) v[0] = x_x[i_from];
865                     if(v[1] < x_x[i_from]) v[1] = x_x[i_from]);
866            break;
867
868      case diag:      case diag:
869          for_DIAG(v[i] = x_x[i_from]);          for_DIAG(v[i] = x_x[i_from]);
870          break;          break;
# Line 579  Line 872
872      case diag_backpermuted:      case diag_backpermuted:
873          for_DIAG(v[i] = x_x[i_from]);          for_DIAG(v[i] = x_x[i_from]);
874
875          warning(_("resultKind = 'diagBack' (back-permuted) is experimental"));          warning(_("%s = '%s' (back-permuted) is experimental"),
876                    "resultKind", "diagBack");
877          /* now back_permute : */          /* now back_permute : */
878          for(i = 0; i < n; i++) {          for(i = 0; i < n; i++) {
879              double tmp = v[i]; v[i] = v[perm[i]]; v[perm[i]] = tmp;              double tmp = v[i]; v[i] = v[perm[i]]; v[perm[i]] = tmp;
# Line 588  Line 882
882          break;          break;
883
884      default: /* -1 from above */      default: /* -1 from above */
885          error("diag_tC(): invalid 'resultKind'");          error(_("diag_tC(): invalid 'resultKind'"));
886          /* Wall: */ ans = R_NilValue; v = REAL(ans);          /* Wall: */ ans = R_NilValue; v = REAL(ans);
887      }      }
888
# Line 600  Line 894
894   * Extract the diagonal entries from *triangular* Csparse matrix  __or__ a   * Extract the diagonal entries from *triangular* Csparse matrix  __or__ a
895   * cholmod_sparse factor (LDL = TRUE).   * cholmod_sparse factor (LDL = TRUE).
896   *   *
897     * @param obj -- now a cholmod_sparse factor or a dtCMatrix
898   * @param pslot  'p' (column pointer)   slot of Csparse matrix/factor   * @param pslot  'p' (column pointer)   slot of Csparse matrix/factor
899   * @param xslot  'x' (non-zero entries) slot of Csparse matrix/factor   * @param xslot  'x' (non-zero entries) slot of Csparse matrix/factor
900   * @param perm_slot  'perm' (= permutation vector) slot of corresponding CHMfactor;   * @param perm_slot  'perm' (= permutation vector) slot of corresponding CHMfactor;
# Line 608  Line 903
903   *   *
904   * @return  a SEXP, either a (double) number or a length n-vector of diagonal entries   * @return  a SEXP, either a (double) number or a length n-vector of diagonal entries
905   */   */
906  SEXP diag_tC(SEXP pslot, SEXP xslot, SEXP perm_slot, SEXP resultKind)  SEXP diag_tC(SEXP obj, SEXP resultKind)
907  {  {
908
909        SEXP
910            pslot = GET_SLOT(obj, Matrix_pSym),
911            xslot = GET_SLOT(obj, Matrix_xSym);
912        Rboolean is_U = (R_has_slot(obj, Matrix_uploSym) &&
913                         *CHAR(asChar(GET_SLOT(obj, Matrix_uploSym))) == 'U');
914      int n = length(pslot) - 1, /* n = ncol(.) = nrow(.) */      int n = length(pslot) - 1, /* n = ncol(.) = nrow(.) */
915          *x_p  = INTEGER(pslot),          *x_p  = INTEGER(pslot), pp = -1, *perm;
*perm = INTEGER(perm_slot);
916      double *x_x = REAL(xslot);      double *x_x = REAL(xslot);
917  /*  ^^^^^^        ^^^^ FIXME[Generalize] to INTEGER(.) / LOGICAL(.) / ... xslot !*/  /*  ^^^^^^        ^^^^ FIXME[Generalize] to INTEGER(.) / LOGICAL(.) / ... xslot !*/
918
919      return diag_tC_ptr(n, x_p, x_x, perm, resultKind);      if(R_has_slot(obj, Matrix_permSym))
920            perm = INTEGER(GET_SLOT(obj, Matrix_permSym));
921        else perm = &pp;
922
923        return diag_tC_ptr(n, x_p, x_x, is_U, perm, resultKind);
924    }
925
926
927    /**
928     * Create a Csparse matrix object from indices and/or pointers.
929     *
930     * @param cls name of actual class of object to create
931     * @param i optional integer vector of length nnz of row indices
932     * @param j optional integer vector of length nnz of column indices
933     * @param p optional integer vector of length np of row or column pointers
934     * @param np length of integer vector p.  Must be zero if p == (int*)NULL
935     * @param x optional vector of values
936     * @param nnz length of vectors i, j and/or x, whichever is to be used
937     * @param dims optional integer vector of length 2 to be used as
938     *     dimensions.  If dims == (int*)NULL then the maximum row and column
939     *     index are used as the dimensions.
940     * @param dimnames optional list of length 2 to be used as dimnames
941     * @param index1 indicator of 1-based indices
942     *
943     * @return an SEXP of class cls inheriting from CsparseMatrix.
944     */
945    SEXP create_Csparse(char* cls, int* i, int* j, int* p, int np,
946                        void* x, int nnz, int* dims, SEXP dimnames,
947                        int index1)
948    {
949        SEXP ans;
950        int *ij = (int*)NULL, *tri, *trj,
951            mi, mj, mp, nrow = -1, ncol = -1;
952        int xtype = -1;             /* -Wall */
953        CHM_TR T;
954        CHM_SP A;
955
956        if (np < 0 || nnz < 0)
957            error(_("negative vector lengths not allowed: np = %d, nnz = %d"),
958                  np, nnz);
959        if (1 != ((mi = (i == (int*)NULL)) +
960                  (mj = (j == (int*)NULL)) +
961                  (mp = (p == (int*)NULL))))
962            error(_("exactly 1 of 'i', 'j' or 'p' must be NULL"));
963        if (mp) {
964            if (np) error(_("np = %d, must be zero when p is NULL"), np);
965        } else {
966            if (np) {               /* Expand p to form i or j */
967                if (!(p[0])) error(_("p[0] = %d, should be zero"), p[0]);
968                for (int ii = 0; ii < np; ii++)
969                    if (p[ii] > p[ii + 1])
970                        error(_("p must be non-decreasing"));
971                if (p[np] != nnz)
972                    error("p[np] = %d != nnz = %d", p[np], nnz);
973                ij = Calloc(nnz, int);
974                if (mi) {
975                    i = ij;
976                    nrow = np;
977                } else {
978                    j = ij;
979                    ncol = np;
980                }
981                /* Expand p to 0-based indices */
982                for (int ii = 0; ii < np; ii++)
983                    for (int jj = p[ii]; jj < p[ii + 1]; jj++) ij[jj] = ii;
984            } else {
985                if (nnz)
986                    error(_("Inconsistent dimensions: np = 0 and nnz = %d"),
987                          nnz);
988            }
989        }
990        /* calculate nrow and ncol */
991        if (nrow < 0) {
992            for (int ii = 0; ii < nnz; ii++) {
993                int i1 = i[ii] + (index1 ? 0 : 1); /* 1-based index */
994                if (i1 < 1) error(_("invalid row index at position %d"), ii);
995                if (i1 > nrow) nrow = i1;
996            }
997        }
998        if (ncol < 0) {
999            for (int jj = 0; jj < nnz; jj++) {
1000                int j1 = j[jj] + (index1 ? 0 : 1);
1001                if (j1 < 1) error(_("invalid column index at position %d"), jj);
1002                if (j1 > ncol) ncol = j1;
1003            }
1004        }
1005        if (dims != (int*)NULL) {
1006            if (dims[0] > nrow) nrow = dims[0];
1007            if (dims[1] > ncol) ncol = dims[1];
1008        }
1009        /* check the class name */
1010        if (strlen(cls) != 8)
1011            error(_("strlen of cls argument = %d, should be 8"), strlen(cls));
1012        if (!strcmp(cls + 2, "CMatrix"))
1013            error(_("cls = \"%s\" does not end in \"CMatrix\""), cls);
1014        switch(cls[0]) {
1015        case 'd':
1016        case 'l':
1017            xtype = CHOLMOD_REAL;
1018        break;
1019        case 'n':
1020            xtype = CHOLMOD_PATTERN;
1021            break;
1022        default:
1023            error(_("cls = \"%s\" must begin with 'd', 'l' or 'n'"), cls);
1024        }
1025        if (cls[1] != 'g')
1026            error(_("Only 'g'eneral sparse matrix types allowed"));
1027        /* allocate and populate the triplet */
1028        T = cholmod_allocate_triplet((size_t)nrow, (size_t)ncol, (size_t)nnz, 0,
1029                                     xtype, &c);
1030        T->x = x;
1031        tri = (int*)T->i;
1032        trj = (int*)T->j;
1033        for (int ii = 0; ii < nnz; ii++) {
1034            tri[ii] = i[ii] - ((!mi && index1) ? 1 : 0);
1035            trj[ii] = j[ii] - ((!mj && index1) ? 1 : 0);
1036        }
1037        /* create the cholmod_sparse structure */
1038        A = cholmod_triplet_to_sparse(T, nnz, &c);
1039        cholmod_free_triplet(&T, &c);
1040        /* copy the information to the SEXP */
1041        ans = PROTECT(NEW_OBJECT(MAKE_CLASS(cls)));
1042    // FIXME: This has been copied from chm_sparse_to_SEXP in  chm_common.c
1043        /* allocate and copy common slots */
1044        nnz = cholmod_nnz(A, &c);
1045        dims = INTEGER(ALLOC_SLOT(ans, Matrix_DimSym, INTSXP, 2));
1046        dims[0] = A->nrow; dims[1] = A->ncol;
1047        Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_pSym, INTSXP, A->ncol + 1)), (int*)A->p, A->ncol + 1);
1048        Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_iSym, INTSXP, nnz)), (int*)A->i, nnz);
1049        switch(cls[1]) {
1050        case 'd':
1051            Memcpy(REAL(ALLOC_SLOT(ans, Matrix_xSym, REALSXP, nnz)), (double*)A->x, nnz);
1052            break;
1053        case 'l':
1054            error(_("code not yet written for cls = \"lgCMatrix\""));
1055        }
1056    /* FIXME: dimnames are *NOT* put there yet (if non-NULL) */
1057        cholmod_free_sparse(&A, &c);
1058        UNPROTECT(1);
1059        return ans;
1060  }  }

Legend:
 Removed from v.2279 changed lines Added in v.3066