# 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 3069, Thu Mar 26 10:00:49 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"));
}
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;
}
38      }      }
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                                     /* transp: */ FALSE);
155        // -> a [dln]geMatrix
156        if(is_sym) { // ==> want  [dln]syMatrix
157            const char cl1 = class_P(ans)[0];
158            PROTECT(ans);
159            SEXP aa = PROTECT(NEW_OBJECT(MAKE_CLASS((cl1 == 'd') ? "dsyMatrix" :
160                                                    ((cl1 == 'l') ? "lsyMatrix" : "nsyMatrix"))));
161            // No need to duplicate() as slots of ans are freshly allocated and ans will not be used
162            SET_SLOT(aa, Matrix_xSym,       GET_SLOT(ans, Matrix_xSym));
163            SET_SLOT(aa, Matrix_DimSym,     GET_SLOT(ans, Matrix_DimSym));
164            SET_SLOT(aa, Matrix_DimNamesSym,GET_SLOT(ans, Matrix_DimNamesSym));
165            SET_SLOT(aa, Matrix_uploSym, mkString((chxs->stype > 0) ? "U" : "L"));
166            UNPROTECT(2);
167            return aa;
168        }
169        else if(is_tri) { // ==> want  [dln]trMatrix
170            const char cl1 = class_P(ans)[0];
171            PROTECT(ans);
172            SEXP aa = PROTECT(NEW_OBJECT(MAKE_CLASS((cl1 == 'd') ? "dtrMatrix" :
173                                                    ((cl1 == 'l') ? "ltrMatrix" : "ntrMatrix"))));
174            // No need to duplicate() as slots of ans are freshly allocated and ans will not be used
175            SET_SLOT(aa, Matrix_xSym,       GET_SLOT(ans, Matrix_xSym));
176            SET_SLOT(aa, Matrix_DimSym,     GET_SLOT(ans, Matrix_DimSym));
177            SET_SLOT(aa, Matrix_DimNamesSym,GET_SLOT(ans, Matrix_DimNamesSym));
178            slot_dup(aa, x, Matrix_uploSym);
179            /* already by NEW_OBJECT(..) above:
180               SET_SLOT(aa, Matrix_diagSym, mkString("N")); */
181            UNPROTECT(2);
182            return aa;
183        }
184        else
185            return ans;
186  }  }
187
188    // FIXME: do not go via CHM (should not be too hard, to just *drop* the x-slot, right?
189  SEXP Csparse_to_nz_pattern(SEXP x, SEXP tri)  SEXP Csparse_to_nz_pattern(SEXP x, SEXP tri)
190  {  {
191      CHM_SP chxs = AS_CHM_SP__(x);      CHM_SP chxs = AS_CHM_SP__(x);
# Line 159  Line 195
195
196      return chm_sparse_to_SEXP(chxcp, 1/*do_free*/,      return chm_sparse_to_SEXP(chxcp, 1/*do_free*/,
197                                tr ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,                                tr ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,
198                                0, tr ? diag_P(x) : "",                                /* Rkind: pattern */ 0,
199                                  /* diag = */ tr ? diag_P(x) : "",
200                                GET_SLOT(x, Matrix_DimNamesSym));                                GET_SLOT(x, Matrix_DimNamesSym));
201  }  }
202
203  SEXP Csparse_to_matrix(SEXP x)  // n.CMatrix --> [dli].CMatrix  (not going through CHM!)
204    SEXP nz_pattern_to_Csparse(SEXP x, SEXP res_kind)
205    {
206        return nz2Csparse(x, asInteger(res_kind));
207    }
208
209    // n.CMatrix --> [dli].CMatrix  (not going through CHM!)
210    // NOTE: use chm_MOD_xtype(() to change type of  'cholmod_sparse' matrix
211    SEXP nz2Csparse(SEXP x, enum x_slot_kind r_kind)
212    {
213        const char *cl_x = class_P(x);
214        if(cl_x[0] != 'n') error(_("not a 'n.CMatrix'"));
215        if(cl_x[2] != 'C') error(_("not a CsparseMatrix"));
216        int nnz = LENGTH(GET_SLOT(x, Matrix_iSym));
217        SEXP ans;
218        char *ncl = alloca(strlen(cl_x) + 1); /* not much memory required */
219        strcpy(ncl, cl_x);
220        double *dx_x; int *ix_x;
221        ncl[0] = (r_kind == x_double ? 'd' :
222                  (r_kind == x_logical ? 'l' :
223                   /* else (for now):  r_kind == x_integer : */ 'i'));
224        PROTECT(ans = NEW_OBJECT(MAKE_CLASS(ncl)));
225        // create a correct 'x' slot:
226        switch(r_kind) {
227            int i;
228        case x_double: // 'd'
229            dx_x = REAL(ALLOC_SLOT(ans, Matrix_xSym, REALSXP, nnz));
230            for (i=0; i < nnz; i++) dx_x[i] = 1.;
231            break;
232        case x_logical: // 'l'
233            ix_x = LOGICAL(ALLOC_SLOT(ans, Matrix_xSym, LGLSXP, nnz));
234            for (i=0; i < nnz; i++) ix_x[i] = TRUE;
235            break;
236        case x_integer: // 'i'
237            ix_x = INTEGER(ALLOC_SLOT(ans, Matrix_xSym, INTSXP, nnz));
238            for (i=0; i < nnz; i++) ix_x[i] = 1;
239            break;
240
241        default:
242            error(_("nz2Csparse(): invalid/non-implemented r_kind = %d"),
243                  r_kind);
244        }
245
246        // now copy all other slots :
247        slot_dup(ans, x, Matrix_iSym);
248        slot_dup(ans, x, Matrix_pSym);
249        slot_dup(ans, x, Matrix_DimSym);
250        slot_dup(ans, x, Matrix_DimNamesSym);
251        if(ncl[1] != 'g') { // symmetric or triangular ...
252            slot_dup_if_has(ans, x, Matrix_uploSym);
253            slot_dup_if_has(ans, x, Matrix_diagSym);
254        }
255        UNPROTECT(1);
256        return ans;
257    }
258
259    SEXP Csparse_to_matrix(SEXP x, SEXP chk, SEXP symm)
260    {
261        int is_sym = asLogical(symm);
262        if(is_sym == NA_LOGICAL) { // find if  is(x, "symmetricMatrix") :
263            static const char *valid[] = { MATRIX_VALID_Csparse, ""};
264            int ctype = Matrix_check_class_etc(x, valid);
265            is_sym = (ctype % 3 == 1);
266        }
267        return chm_dense_to_matrix(
268            cholmod_sparse_to_dense(AS_CHM_SP2(x, asLogical(chk)), &c),
269            1 /*do_free*/,
270            (is_sym
271             ? symmetric_DimNames(GET_SLOT(x, Matrix_DimNamesSym))
272             :                    GET_SLOT(x, Matrix_DimNamesSym)));
273    }
274
275    SEXP Csparse_to_vector(SEXP x)
276  {  {
277      return chm_dense_to_matrix(cholmod_sparse_to_dense(AS_CHM_SP__(x), &c),      return chm_dense_to_vector(cholmod_sparse_to_dense(AS_CHM_SP__(x), &c), 1);
1 /*do_free*/, GET_SLOT(x, Matrix_DimNamesSym));
278  }  }
279
280  SEXP Csparse_to_Tsparse(SEXP x, SEXP tri)  SEXP Csparse_to_Tsparse(SEXP x, SEXP tri)
# Line 183  Line 291
291                                 GET_SLOT(x, Matrix_DimNamesSym));                                 GET_SLOT(x, Matrix_DimNamesSym));
292  }  }
293
294  /* this used to be called  sCMatrix_to_gCMatrix(..)   [in ./dsCMatrix.c ]: */  SEXP Csparse_to_tCsparse(SEXP x, SEXP uplo, SEXP diag)
295    {
296        CHM_SP chxs = AS_CHM_SP__(x);
297        int Rkind = (chxs->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
298        R_CheckStack();
299        return chm_sparse_to_SEXP(chxs, /* dofree = */ 0,
300                                  /* uploT = */ (*CHAR(asChar(uplo)) == 'U')? 1: -1,
301                                   Rkind, /* diag = */ CHAR(STRING_ELT(diag, 0)),
302                                   GET_SLOT(x, Matrix_DimNamesSym));
303    }
304
305    SEXP Csparse_to_tTsparse(SEXP x, SEXP uplo, SEXP diag)
306    {
307        CHM_SP chxs = AS_CHM_SP__(x);
308        CHM_TR chxt = cholmod_sparse_to_triplet(chxs, &c);
309        int Rkind = (chxs->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
310        R_CheckStack();
311        return chm_triplet_to_SEXP(chxt, 1,
312                                  /* uploT = */ (*CHAR(asChar(uplo)) == 'U')? 1: -1,
313                                   Rkind, /* diag = */ CHAR(STRING_ELT(diag, 0)),
314                                   GET_SLOT(x, Matrix_DimNamesSym));
315    }
316
317
318  SEXP Csparse_symmetric_to_general(SEXP x)  SEXP Csparse_symmetric_to_general(SEXP x)
319  {  {
320      CHM_SP chx = AS_CHM_SP__(x), chgx;      CHM_SP chx = AS_CHM_SP__(x), chgx;
# Line 195  Line 326
326      chgx = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);      chgx = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);
327      /* xtype: pattern, "real", complex or .. */      /* xtype: pattern, "real", complex or .. */
328      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",
329                                GET_SLOT(x, Matrix_DimNamesSym));                                symmetric_DimNames(GET_SLOT(x, Matrix_DimNamesSym)));
330  }  }
331
332  SEXP Csparse_general_to_symmetric(SEXP x, SEXP uplo)  SEXP Csparse_general_to_symmetric(SEXP x, SEXP uplo, SEXP sym_dmns)
333  {  {
336            error(_("Csparse_general_to_symmetric(): matrix is not square!"));
337            return R_NilValue; /* -Wall */
338        }
339      CHM_SP chx = AS_CHM_SP__(x), chgx;      CHM_SP chx = AS_CHM_SP__(x), chgx;
340      int uploT = (*CHAR(STRING_ELT(uplo,0)) == 'U') ? 1 : -1;      int uploT = (*CHAR(asChar(uplo)) == 'U') ? 1 : -1;
341      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
342      R_CheckStack();      R_CheckStack();

343      chgx = cholmod_copy(chx, /* stype: */ uploT, chx->xtype, &c);      chgx = cholmod_copy(chx, /* stype: */ uploT, chx->xtype, &c);
344
345        SEXP dns = GET_SLOT(x, Matrix_DimNamesSym);
346        if(asLogical(sym_dmns))
347            dns = symmetric_DimNames(dns);
348        else if((!isNull(VECTOR_ELT(dns, 0)) &&
349                 !isNull(VECTOR_ELT(dns, 1))) ||
350                !isNull(getAttrib(dns, R_NamesSymbol))) {
351            /* symmetrize them if both are not NULL
352             * or names(dimnames(.)) is asymmetric : */
353            dns = PROTECT(duplicate(dns));
354            if(!equal_string_vectors(VECTOR_ELT(dns, 0),
355                                     VECTOR_ELT(dns, 1))) {
356                if(uploT == 1)
357                    SET_VECTOR_ELT(dns, 0, VECTOR_ELT(dns,1));
358                else
359                    SET_VECTOR_ELT(dns, 1, VECTOR_ELT(dns,0));
360            }
361            SEXP nms_dns = getAttrib(dns, R_NamesSymbol);
362            if(!isNull(nms_dns) &&  // names(dimnames(.)) :
363               !R_compute_identical(STRING_ELT(nms_dns, 0),
364                                    STRING_ELT(nms_dns, 1), 16)) {
365                if(uploT == 1)
366                    SET_STRING_ELT(nms_dns, 0, STRING_ELT(nms_dns,1));
367                else
368                    SET_STRING_ELT(nms_dns, 1, STRING_ELT(nms_dns,0));
369                setAttrib(dns, R_NamesSymbol, nms_dns);
370            }
371            UNPROTECT(1);
372        }
373      /* xtype: pattern, "real", complex or .. */      /* xtype: pattern, "real", complex or .. */
374      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "", dns);
GET_SLOT(x, Matrix_DimNamesSym));
375  }  }
376
377  SEXP Csparse_transpose(SEXP x, SEXP tri)  SEXP Csparse_transpose(SEXP x, SEXP tri)
# Line 225  Line 388
388      tmp = VECTOR_ELT(dn, 0);    /* swap the dimnames */      tmp = VECTOR_ELT(dn, 0);    /* swap the dimnames */
389      SET_VECTOR_ELT(dn, 0, VECTOR_ELT(dn, 1));      SET_VECTOR_ELT(dn, 0, VECTOR_ELT(dn, 1));
390      SET_VECTOR_ELT(dn, 1, tmp);      SET_VECTOR_ELT(dn, 1, tmp);
391        if(!isNull(tmp = getAttrib(dn, R_NamesSymbol))) { // swap names(dimnames(.)):
392            SEXP nms_dns = PROTECT(allocVector(VECSXP, 2));
393            SET_VECTOR_ELT(nms_dns, 1, STRING_ELT(tmp, 0));
394            SET_VECTOR_ELT(nms_dns, 0, STRING_ELT(tmp, 1));
395            setAttrib(dn, R_NamesSymbol, nms_dns);
396            UNPROTECT(1);
397        }
398      UNPROTECT(1);      UNPROTECT(1);
399      return chm_sparse_to_SEXP(chxt, 1, /* SWAP 'uplo' for triangular */      return chm_sparse_to_SEXP(chxt, 1, /* SWAP 'uplo' for triangular */
400                                tr ? ((*uplo_P(x) == 'U') ? -1 : 1) : 0,                                tr ? ((*uplo_P(x) == 'U') ? -1 : 1) : 0,
401                                Rkind, tr ? diag_P(x) : "", dn);                                Rkind, tr ? diag_P(x) : "", dn);
402  }  }
403
404  SEXP Csparse_Csparse_prod(SEXP a, SEXP b)  /* NOTA BENE:  cholmod_ssmult(A,B, ...) ->  ./CHOLMOD/MatrixOps/cholmod_ssmult.c
405     * ---------  computes a patter*n* matrix __always_ when
406     * *one* of A or B is pattern*n*, because of this (line 73-74):
407       ---------------------------------------------------------------------------
408        values = values &&
409            (A->xtype != CHOLMOD_PATTERN) && (B->xtype != CHOLMOD_PATTERN) ;
410       ---------------------------------------------------------------------------
411     * ==> Often need to copy the patter*n* to a *l*ogical matrix first !!!
412     */
413
414    SEXP Csparse_Csparse_prod(SEXP a, SEXP b, SEXP bool_arith)
415  {  {
416      CHM_SP      CHM_SP
417          cha = AS_CHM_SP(a),          cha = AS_CHM_SP(a),
418          chb = AS_CHM_SP(b),          chb = AS_CHM_SP(b), chc;
419          chc = cholmod_ssmult(cha, chb, /*out_stype:*/ 0,      R_CheckStack();
420                               cha->xtype, /*out sorted:*/ 1, &c);      // const char *cl_a = class_P(a), *cl_b = class_P(b);
421      const char *cl_a = class_P(a), *cl_b = class_P(b);      static const char *valid_tri[] = { MATRIX_VALID_tri_Csparse, "" };
422      char diag[] = {'\0', '\0'};      char diag[] = {'\0', '\0'};
423      int uploT = 0;      int uploT = 0, nprot = 1,
424      SEXP dn = allocVector(VECSXP, 2);          do_bool = asLogical(bool_arith); // TRUE / NA / FALSE
425        Rboolean
426            a_is_n = (cha->xtype == CHOLMOD_PATTERN),
427            b_is_n = (chb->xtype == CHOLMOD_PATTERN),
428            force_num = (do_bool == FALSE),
429            maybe_bool= (do_bool == NA_LOGICAL);
430
431    #ifdef DEBUG_Matrix_verbose
432        Rprintf("DBG Csparse_C*_prod(%s, %s)\n", class_P(a), class_P(b));
433    #endif
434
435        if(a_is_n && (force_num || (maybe_bool && !b_is_n))) {
436            /* coerce 'a' to  double;
437             * have no CHOLMOD function (pattern -> logical) --> use "our" code */
438            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
439            cha = AS_CHM_SP(da);
440            R_CheckStack();
441            a_is_n = FALSE;
442        }
443        else if(b_is_n && (force_num || (maybe_bool && !a_is_n))) {
444            // coerce 'b' to  double
445            SEXP db = PROTECT(nz2Csparse(b, x_double)); nprot++;
446            chb = AS_CHM_SP(db);
447      R_CheckStack();      R_CheckStack();
448            b_is_n = FALSE;
449        }
450        chc = cholmod_ssmult(cha, chb, /*out_stype:*/ 0,
451                             /* values : */ do_bool != TRUE,
452                             /* sorted = TRUE: */ 1, &c);
453
454      /* Preserve triangularity and even unit-triangularity if appropriate.      /* Preserve triangularity and even unit-triangularity if appropriate.
455       * Note that in that case, the multiplication itself should happen       * Note that in that case, the multiplication itself should happen
456       * faster.  But there's no support for that in CHOLMOD */       * faster.  But there's no support for that in CHOLMOD */
457
458      /* UGLY hack -- rather should have (fast!) C-level version of      if(Matrix_check_class_etc(a, valid_tri) >= 0 &&
459       *       is(a, "triangularMatrix") etc */         Matrix_check_class_etc(b, valid_tri) >= 0)
if (cl_a[1] == 't' && cl_b[1] == 't')
/* FIXME: fails for "Cholesky","BunchKaufmann"..*/
460          if(*uplo_P(a) == *uplo_P(b)) { /* both upper, or both lower tri. */          if(*uplo_P(a) == *uplo_P(b)) { /* both upper, or both lower tri. */
461              uploT = (*uplo_P(a) == 'U') ? 1 : -1;              uploT = (*uplo_P(a) == 'U') ? 1 : -1;
462              if(*diag_P(a) == 'U' && *diag_P(b) == 'U') { /* return UNIT-triag. */              if(*diag_P(a) == 'U' && *diag_P(b) == 'U') { /* return UNIT-triag. */
# Line 261  Line 466
466              }              }
467              else diag[0]= 'N';              else diag[0]= 'N';
468          }          }
469
470        SEXP dn = PROTECT(allocVector(VECSXP, 2));
471      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
472                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));
473      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
474                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), 1)));
475        UNPROTECT(nprot);
476      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);
477  }  }
478
479  SEXP Csparse_Csparse_crossprod(SEXP a, SEXP b, SEXP trans)  /* trans = FALSE:  crossprod(a,b)
480     * trans = TRUE : tcrossprod(a,b) */
481    SEXP Csparse_Csparse_crossprod(SEXP a, SEXP b, SEXP trans, SEXP bool_arith)
482  {  {
483      int tr = asLogical(trans);      int tr = asLogical(trans), nprot = 1,
484            do_bool = asLogical(bool_arith); // TRUE / NA / FALSE
485      CHM_SP      CHM_SP
486          cha = AS_CHM_SP(a),          cha = AS_CHM_SP(a),
487          chb = AS_CHM_SP(b),          chb = AS_CHM_SP(b),
488          chTr, chc;          chTr, chc;
489      const char *cl_a = class_P(a), *cl_b = class_P(b);      R_CheckStack();
490        // const char *cl_a = class_P(a), *cl_b = class_P(b);
491        static const char *valid_tri[] = { MATRIX_VALID_tri_Csparse, "" };
492      char diag[] = {'\0', '\0'};      char diag[] = {'\0', '\0'};
493      int uploT = 0;      int uploT = 0;
494      SEXP dn = allocVector(VECSXP, 2);      Rboolean
495            a_is_n = (cha->xtype == CHOLMOD_PATTERN),
496            b_is_n = (chb->xtype == CHOLMOD_PATTERN),
497            force_num = (do_bool == FALSE),
498            maybe_bool= (do_bool == NA_LOGICAL);
499
500        if(a_is_n && (force_num || (maybe_bool && !b_is_n))) {
501            // coerce 'a' to  double
502            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
503            cha = AS_CHM_SP(da);
504      R_CheckStack();      R_CheckStack();
505            a_is_n = FALSE;
506        }
507        else if(b_is_n && (force_num || (maybe_bool && !a_is_n))) {
508            // coerce 'b' to  double
509            SEXP db = PROTECT(nz2Csparse(b, x_double)); nprot++;
510            chb = AS_CHM_SP(db);
511            R_CheckStack();
512            b_is_n = FALSE;
513        }
514
515      chTr = cholmod_transpose((tr) ? chb : cha, chb->xtype, &c);      chTr = cholmod_transpose((tr) ? chb : cha, chb->xtype, &c);
516      chc = cholmod_ssmult((tr) ? cha : chTr, (tr) ? chTr : chb,      chc = cholmod_ssmult((tr) ? cha : chTr, (tr) ? chTr : chb,
517                           /*out_stype:*/ 0, cha->xtype, /*out sorted:*/ 1, &c);                           /*out_stype:*/ 0, /* values : */ do_bool != TRUE,
518                             /* sorted = TRUE: */ 1, &c);
519      cholmod_free_sparse(&chTr, &c);      cholmod_free_sparse(&chTr, &c);
520
521      /* Preserve triangularity and unit-triangularity if appropriate;      /* Preserve triangularity and unit-triangularity if appropriate;
522       * see Csparse_Csparse_prod() for comments */       * see Csparse_Csparse_prod() for comments */
523      if (cl_a[1] == 't' && cl_b[1] == 't')      if(Matrix_check_class_etc(a, valid_tri) >= 0 &&
524           Matrix_check_class_etc(b, valid_tri) >= 0)
525          if(*uplo_P(a) != *uplo_P(b)) { /* one 'U', the other 'L' */          if(*uplo_P(a) != *uplo_P(b)) { /* one 'U', the other 'L' */
526              uploT = (*uplo_P(b) == 'U') ? 1 : -1;              uploT = (*uplo_P(b) == 'U') ? 1 : -1;
527              if(*diag_P(a) == 'U' && *diag_P(b) == 'U') { /* return UNIT-triag. */              if(*diag_P(a) == 'U' && *diag_P(b) == 'U') { /* return UNIT-triag. */
# Line 298  Line 531
531              else diag[0]= 'N';              else diag[0]= 'N';
532          }          }
533
534        SEXP dn = PROTECT(allocVector(VECSXP, 2));
535      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
536                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), (tr) ? 0 : 1)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym),
537                                            (tr) ? 0 : 1)));
538      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
539                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), (tr) ? 0 : 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym),
540                                            (tr) ? 0 : 1)));
541        UNPROTECT(nprot);
542      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);
543  }  }
544
545  SEXP Csparse_dense_prod(SEXP a, SEXP b)  /**
546     * All (dense * sparse)  Matrix products and cross products
547     *
548     *   f( f(<Csparse>)  %*%  f(<dense>) )   for  f in {t(), identity()}
549     *
550     * @param a CsparseMatrix  (n x m)
551     * @param b numeric vector, matrix, or denseMatrix (m x k) or (k x m)  if `transp` is '2' or 'B'
552     * @param transp character.
553     *        = " " : nothing transposed {apart from a}
554     *        = "2" : "transpose 2nd arg": use  t(b) instead of b (= 2nd argument)
555     *        = "c" : "transpose c":       Return  t(c) instead of c
556     *        = "B" : "transpose both":    use t(b) and return t(c) instead of c
557     * NB: For "2", "c", "B", need to transpose a *dense* matrix, B or C --> chm_transpose_dense()
558     *
559     * @return a dense matrix, the matrix product c = g(a,b) :
560     *
561     *                                                Condition (R)   Condition (C)
562     *   R notation            Math notation          cross  transp   t.a t.b t.ans
563     *   ~~~~~~~~~~~~~~~~~     ~~~~~~~~~~~~~~~~~~     ~~~~~~~~~~~~~   ~~~~~~~~~~~~~
564     *   c <-   a %*%   b      C :=      A B            .       " "    .   .   .
565     *   c <-   a %*% t(b)     C :=      A B'           .       "2"    .   |   .
566     *   c <- t(a %*%   b)     C := (A B)'  = B'A'      .       "c"    .   .   |
567     *   c <- t(a %*% t(b))    C := (A B')' = B A'      .       "B"    .   |   |
568     *
569     *   c <-   t(a) %*%   b   C :=      A'B           TRUE     " "    |   .   .
570     *   c <-   t(a) %*% t(b)  C :=      A'B'          TRUE     "2"    |   |   .
571     *   c <- t(t(a) %*%   b)  C := (A'B)'  = B'A      TRUE     "c"    |   .   |
572     *   c <- t(t(a) %*% t(b)) C := (A'B')' = B A      TRUE     "B"    |   |   |
573     */
574    SEXP Csp_dense_products(SEXP a, SEXP b,
575                            Rboolean transp_a, Rboolean transp_b, Rboolean transp_ans)
576  {  {
577      CHM_SP cha = AS_CHM_SP(a);      CHM_SP cha = AS_CHM_SP(a);
578      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix(b));      int a_nc = transp_a ? cha->nrow : cha->ncol,
579      CHM_DN chb = AS_CHM_DN(b_M);          a_nr = transp_a ? cha->ncol : cha->nrow;
580      CHM_DN chc = cholmod_allocate_dense(cha->nrow, chb->ncol, cha->nrow,      Rboolean
581                                          chb->xtype, &c);          maybe_transp_b = (a_nc == 1),
582      SEXP dn = PROTECT(allocVector(VECSXP, 2));          b_is_vector = FALSE;
583      double one[] = {1,0}, zero[] = {0,0};      /* NOTE: trans_b {<--> "use t(b) instead of b" }
584           ----  "interferes" with the  case automatic treatment of *vector* b.
585           In that case,  t(b) or b is used "whatever make more sense",
586           according to the general R philosophy of treating vectors in matrix products.
587        */
588
589        /* repeating a "cheap part" of  mMatrix_as_dgeMatrix2(b, .)  to see if
590         * we have a vector that we might 'transpose_if_vector' : */
591        static const char *valid[] = {"_NOT_A_CLASS_", MATRIX_VALID_ddense, ""};
592        /* int ctype = Matrix_check_class_etc(b, valid);
593         * if (ctype > 0)   /.* a ddenseMatrix object */
594        if (Matrix_check_class_etc(b, valid) < 0) {
595            // not a ddenseM*:  is.matrix() or vector:
596            b_is_vector = !isMatrix(b);
597        }
598
599        if(b_is_vector) {
600            /* determine *if* we want/need to transpose at all:
601             * if (length(b) == ncol(A)) have match: use dim = c(n, 1) (<=> do *not* transp);
602             *  otherwise, try to transpose: ok  if (ncol(A) == 1) [see also above]:  */
603            maybe_transp_b = (LENGTH(b) != a_nc);
604            // Here, we transpose already in mMatrix_as_dge*()  ==> don't do it later:
605            transp_b = FALSE;
606        }
607        SEXP b_M = PROTECT(mMatrix_as_dgeMatrix2(b, maybe_transp_b));
608
609        CHM_DN chb = AS_CHM_DN(b_M), b_t;
610      R_CheckStack();      R_CheckStack();
611        int ncol_b;
612        if(transp_b) { // transpose b:
613            b_t = cholmod_allocate_dense(chb->ncol, chb->nrow, chb->ncol, chb->xtype, &c);
614            chm_transpose_dense(b_t, chb);
615            ncol_b = b_t->ncol;
616        } else
617            ncol_b = chb->ncol;
618        // Result C {with dim() before it may be transposed}:
619        CHM_DN chc = cholmod_allocate_dense(a_nr, ncol_b, a_nr, chb->xtype, &c);
620        double one[] = {1,0}, zero[] = {0,0};
621        int nprot = 2;
622
623      cholmod_sdmult(cha, 0, one, zero, chb, chc, &c);      /* Tim Davis, please FIXME:  currently (2010-11) *fails* when  a  is a pattern matrix:*/
624      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      if(cha->xtype == CHOLMOD_PATTERN) {
625                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));          /* warning(_("Csparse_dense_prod(): cholmod_sdmult() not yet implemented for pattern./ ngCMatrix" */
626      SET_VECTOR_ELT(dn, 1,          /*        " --> slightly inefficient coercion")); */
627                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));
628      UNPROTECT(2);          // This *fails* to produce a CHOLMOD_REAL ..
629      return chm_dense_to_SEXP(chc, 1, 0, dn);          // CHM_SP chd = cholmod_l_copy(cha, cha->stype, CHOLMOD_REAL, &c);
630            // --> use our Matrix-classes
631            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
632            cha = AS_CHM_SP(da);
633        }
634
635        /* cholmod_sdmult(A, transp, alpha, beta, X,  Y,  &c): depending on transp == 0 / != 0:
636         *  Y := alpha*(A*X) + beta*Y or alpha*(A'*X) + beta*Y;  here, alpha = 1, beta = 0:
637         *  Y := A*X  or  A'*X
638         *                       NB: always  <sparse> %*% <dense> !
639         */
640        cholmod_sdmult(cha, transp_a, one, zero, (transp_b ? b_t : chb), /* -> */ chc, &c);
641
642        SEXP dn = PROTECT(allocVector(VECSXP, 2));  /* establish dimnames */
643        SET_VECTOR_ELT(dn, transp_ans ? 1 : 0,
644                       duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), transp_a ? 1 : 0)));
645        SET_VECTOR_ELT(dn, transp_ans ? 0 : 1,
646                       duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym),
647                                            transp_b ? 0 : 1)));
648        if(transp_b) cholmod_free_dense(&b_t, &c);
649        UNPROTECT(nprot);
650        return chm_dense_to_SEXP(chc, 1, 0, dn, transp_ans);
651  }  }
652
653  SEXP Csparse_dense_crossprod(SEXP a, SEXP b)
654    SEXP Csparse_dense_prod(SEXP a, SEXP b, SEXP transp)
655  {  {
656      CHM_SP cha = AS_CHM_SP(a);      return
657      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix(b));          Csp_dense_products(a, b,
658      CHM_DN chb = AS_CHM_DN(b_M);                  /* transp_a = */ FALSE,
659      CHM_DN chc = cholmod_allocate_dense(cha->ncol, chb->ncol, cha->ncol,                  /* transp_b   = */ (*CHAR(asChar(transp)) == '2' || *CHAR(asChar(transp)) == 'B'),
660                                          chb->xtype, &c);                  /* transp_ans = */ (*CHAR(asChar(transp)) == 'c' || *CHAR(asChar(transp)) == 'B'));
661      SEXP dn = PROTECT(allocVector(VECSXP, 2));  }
double one[] = {1,0}, zero[] = {0,0};
R_CheckStack();
662
663      cholmod_sdmult(cha, 1, one, zero, chb, chc, &c);  SEXP Csparse_dense_crossprod(SEXP a, SEXP b, SEXP transp)
664      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */  {
665                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 1)));      return
666      SET_VECTOR_ELT(dn, 1,          Csp_dense_products(a, b,
667                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));                  /* transp_a = */ TRUE,
668      UNPROTECT(2);                  /* transp_b   = */ (*CHAR(asChar(transp)) == '2' || *CHAR(asChar(transp)) == 'B'),
669      return chm_dense_to_SEXP(chc, 1, 0, dn);                  /* transp_ans = */ (*CHAR(asChar(transp)) == 'c' || *CHAR(asChar(transp)) == 'B'));
670  }  }
671
672
673  /* Computes   x'x  or  x x' -- *also* for Tsparse (triplet = TRUE)  /* Computes   x'x  or  x x' -- *also* for Tsparse (triplet = TRUE)
674     see Csparse_Csparse_crossprod above for  x'y and x y' */     see Csparse_Csparse_crossprod above for  x'y and x y' */
675  SEXP Csparse_crossprod(SEXP x, SEXP trans, SEXP triplet)  SEXP Csparse_crossprod(SEXP x, SEXP trans, SEXP triplet, SEXP bool_arith)
676  {  {
677      int trip = asLogical(triplet),      int tripl = asLogical(triplet),
678          tr   = asLogical(trans); /* gets reversed because _aat is tcrossprod */          tr   = asLogical(trans), /* gets reversed because _aat is tcrossprod */
679      CHM_TR cht = trip ? AS_CHM_TR(x) : (CHM_TR) NULL;          do_bool = asLogical(bool_arith); // TRUE / NA / FALSE
680    #ifdef AS_CHM_DIAGU2N_FIXED_FINALLY
681        CHM_TR cht = tripl ? AS_CHM_TR(x) : (CHM_TR) NULL;  int nprot = 1;
682    #else /* workaround needed:*/
683        SEXP xx = PROTECT(Tsparse_diagU2N(x));
684        CHM_TR cht = tripl ? AS_CHM_TR__(xx) : (CHM_TR) NULL; int nprot = 2;
685    #endif
686      CHM_SP chcp, chxt,      CHM_SP chcp, chxt,
687          chx = (trip ?          chx = (tripl ?
688                 cholmod_triplet_to_sparse(cht, cht->nnz, &c) :                 cholmod_triplet_to_sparse(cht, cht->nnz, &c) :
689                 AS_CHM_SP(x));                 AS_CHM_SP(x));
690      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2));
691      R_CheckStack();      R_CheckStack();
692        Rboolean
693            x_is_n = (chx->xtype == CHOLMOD_PATTERN),
694            force_num = (do_bool == FALSE);
695
696        if(x_is_n && force_num) {
697            // coerce 'x' to  double
698            SEXP dx = PROTECT(nz2Csparse(x, x_double)); nprot++;
699            chx = AS_CHM_SP(dx);
700            R_CheckStack();
701        }
702
703      if (!tr) chxt = cholmod_transpose(chx, chx->xtype, &c);      if (!tr) chxt = cholmod_transpose(chx, chx->xtype, &c);
704      chcp = cholmod_aat((!tr) ? chxt : chx, (int *) NULL, 0, chx->xtype, &c);
705        chcp = cholmod_aat((!tr) ? chxt : chx, (int *) NULL, 0,
706                           /* mode: */ chx->xtype, &c);
707      if(!chcp) {      if(!chcp) {
708          UNPROTECT(1);          UNPROTECT(1);
709          error(_("Csparse_crossprod(): error return from cholmod_aat()"));          error(_("Csparse_crossprod(): error return from cholmod_aat()"));
710      }      }
711      cholmod_band_inplace(0, chcp->ncol, chcp->xtype, chcp, &c);      cholmod_band_inplace(0, chcp->ncol, chcp->xtype, chcp, &c);
712      chcp->stype = 1;      chcp->stype = 1; // symmetric
713      if (trip) cholmod_free_sparse(&chx, &c);      if (tripl) cholmod_free_sparse(&chx, &c);
714      if (!tr) cholmod_free_sparse(&chxt, &c);      if (!tr) cholmod_free_sparse(&chxt, &c);
715      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
716                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),
717                                          (tr) ? 0 : 1)));                                          (tr) ? 0 : 1)));
718      SET_VECTOR_ELT(dn, 1, duplicate(VECTOR_ELT(dn, 0)));      SET_VECTOR_ELT(dn, 1, duplicate(VECTOR_ELT(dn, 0)));
719      UNPROTECT(1);      UNPROTECT(nprot);
720        // FIXME: uploT for symmetric ?
721      return chm_sparse_to_SEXP(chcp, 1, 0, 0, "", dn);      return chm_sparse_to_SEXP(chcp, 1, 0, 0, "", dn);
722  }  }
723
724    /* Csparse_drop(x, tol):  drop entries with absolute value < tol, i.e,
725    *  at least all "explicit" zeros */
726  SEXP Csparse_drop(SEXP x, SEXP tol)  SEXP Csparse_drop(SEXP x, SEXP tol)
727  {  {
728      const char *cl = class_P(x);      const char *cl = class_P(x);
# Line 398  Line 744
744
745  SEXP Csparse_horzcat(SEXP x, SEXP y)  SEXP Csparse_horzcat(SEXP x, SEXP y)
746  {  {
747      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);  #define CSPARSE_CAT(_KIND_)                                             \
748      int Rkind = 0; /* only for "d" - FIXME */      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);                  \
749      R_CheckStack();      R_CheckStack();                                                     \
750        int Rk_x = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : -3,     \
751            Rk_y = (chy->xtype != CHOLMOD_PATTERN) ? Real_kind(y) : -3, Rkind; \
752        if(Rk_x == -3 || Rk_y == -3) { /* at least one of them is patter"n" */ \
753            if(Rk_x == -3 && Rk_y == -3) { /* fine */                       \
754            } else { /* only one is a patter"n"                             \
755                      * "Bug" in cholmod_horzcat()/vertcat(): returns patter"n" matrix if one of them is */ \
756                Rboolean ok;                                                \
757                if(Rk_x == -3) {                                            \
758                    ok = chm_MOD_xtype(CHOLMOD_REAL, chx, &c); Rk_x = 0;    \
759                } else if(Rk_y == -3) {                                     \
760                    ok = chm_MOD_xtype(CHOLMOD_REAL, chy, &c); Rk_y = 0;    \
761                } else                                                      \
762                    error(_("Impossible Rk_x/Rk_y in Csparse_%s(), please report"), _KIND_); \
763                if(!ok)                                                     \
764                    error(_("chm_MOD_xtype() was not successful in Csparse_%s(), please report"), \
765                          _KIND_);                                          \
766            }                                                               \
767        }                                                                   \
768        Rkind = /* logical if both x and y are */ (Rk_x == 1 && Rk_y == 1) ? 1 : 0
769
770        CSPARSE_CAT("horzcat");
771        // TODO: currently drops dimnames - and we fix at R level;
772
/* FIXME: currently drops dimnames */
773      return chm_sparse_to_SEXP(cholmod_horzcat(chx, chy, 1, &c),      return chm_sparse_to_SEXP(cholmod_horzcat(chx, chy, 1, &c),
774                                1, 0, Rkind, "", R_NilValue);                                1, 0, Rkind, "", R_NilValue);
775  }  }
776
777  SEXP Csparse_vertcat(SEXP x, SEXP y)  SEXP Csparse_vertcat(SEXP x, SEXP y)
778  {  {
779      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);      CSPARSE_CAT("vertcat");
780      int Rkind = 0; /* only for "d" - FIXME */      // TODO: currently drops dimnames - and we fix at R level;
R_CheckStack();
781
/* FIXME: currently drops dimnames */
782      return chm_sparse_to_SEXP(cholmod_vertcat(chx, chy, 1, &c),      return chm_sparse_to_SEXP(cholmod_vertcat(chx, chy, 1, &c),
783                                1, 0, Rkind, "", R_NilValue);                                1, 0, Rkind, "", R_NilValue);
784  }  }
# Line 464  Line 829
829      }      }
830      else { /* triangular with diag='N'): now drop the diagonal */      else { /* triangular with diag='N'): now drop the diagonal */
831          /* duplicate, since chx will be modified: */          /* duplicate, since chx will be modified: */
832          CHM_SP chx = AS_CHM_SP__(duplicate(x));          SEXP xx = PROTECT(duplicate(x));
833            CHM_SP chx = AS_CHM_SP__(xx);
834          int uploT = (*uplo_P(x) == 'U') ? 1 : -1,          int uploT = (*uplo_P(x) == 'U') ? 1 : -1,
835              Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;              Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
836          R_CheckStack();          R_CheckStack();
837
838          chm_diagN2U(chx, uploT, /* do_realloc */ FALSE);          chm_diagN2U(chx, uploT, /* do_realloc */ FALSE);
839
840          return chm_sparse_to_SEXP(chx, /*dofree*/ 0/* or 1 ?? */,          SEXP ans = chm_sparse_to_SEXP(chx, /*dofree*/ 0/* or 1 ?? */,
841                                    uploT, Rkind, "U",                                    uploT, Rkind, "U",
842                                    GET_SLOT(x, Matrix_DimNamesSym));                                    GET_SLOT(x, Matrix_DimNamesSym));
843            UNPROTECT(1);// only now !
844            return ans;
845      }      }
846  }  }
847
848    /**
849     * "Indexing" aka subsetting : Compute  x[i,j], also for vectors i and j
850     * Working via CHOLMOD_submatrix, see ./CHOLMOD/MatrixOps/cholmod_submatrix.c
851     * @param x CsparseMatrix
852     * @param i row     indices (0-origin), or NULL (R's)
853     * @param j columns indices (0-origin), or NULL
854     *
855     * @return x[i,j]  still CsparseMatrix --- currently, this loses dimnames
856     */
857  SEXP Csparse_submatrix(SEXP x, SEXP i, SEXP j)  SEXP Csparse_submatrix(SEXP x, SEXP i, SEXP j)
858  {  {
859      CHM_SP chx = AS_CHM_SP__(x);      CHM_SP chx = AS_CHM_SP(x); /* << does diagU2N() when needed */
860      int rsize = (isNull(i)) ? -1 : LENGTH(i),      int rsize = (isNull(i)) ? -1 : LENGTH(i),
861          csize = (isNull(j)) ? -1 : LENGTH(j);          csize = (isNull(j)) ? -1 : LENGTH(j);
862      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
# Line 490  Line 867
867      if (csize >= 0 && !isInteger(j))      if (csize >= 0 && !isInteger(j))
868          error(_("Index j must be NULL or integer"));          error(_("Index j must be NULL or integer"));
869
870      return chm_sparse_to_SEXP(cholmod_submatrix(chx, INTEGER(i), rsize,  #define CHM_SUB(_M_, _i_, _j_)                                  \
871                                                  INTEGER(j), csize,      cholmod_submatrix(_M_,                                      \
872                                                  TRUE, TRUE, &c),                        (rsize < 0) ? NULL : INTEGER(_i_), rsize, \
873                                1, 0, Rkind, "",                        (csize < 0) ? NULL : INTEGER(_j_), csize, \
874                                /* FIXME: drops dimnames */ R_NilValue);                        TRUE, TRUE, &c)
875  }      CHM_SP ans;
876        if (!chx->stype) {/* non-symmetric Matrix */
877            ans = CHM_SUB(chx, i, j);
878        }
879        else {
880            /* for now, cholmod_submatrix() only accepts "generalMatrix" */
881            CHM_SP tmp = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);
882            ans = CHM_SUB(tmp, i, j);
883            cholmod_free_sparse(&tmp, &c);
884        }
885
886        // "FIXME": currently dropping dimnames, and adding them afterwards in R :
887        /* // dimnames: */
888        /* SEXP x_dns = GET_SLOT(x, Matrix_DimNamesSym), */
889        /*  dn = PROTECT(allocVector(VECSXP, 2)); */
890        return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "", /* dimnames: */ R_NilValue);
891    }
892
893    #define _d_Csp_
894    #include "t_Csparse_subassign.c"
895
896    #define _l_Csp_
897    #include "t_Csparse_subassign.c"
898
899    #define _i_Csp_
900    #include "t_Csparse_subassign.c"
901
902    #define _n_Csp_
903    #include "t_Csparse_subassign.c"
904
905    #define _z_Csp_
906    #include "t_Csparse_subassign.c"
907
908
909
910  SEXP Csparse_MatrixMarket(SEXP x, SEXP fname)  SEXP Csparse_MatrixMarket(SEXP x, SEXP fname)
911  {  {
# Line 524  Line 934
934   *   *
935   * @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
936   */   */
937  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,
938  /*                                ^^^^^^ FIXME[Generalize] to int / ... */  /*                                ^^^^^^ FIXME[Generalize] to int / ... */
939                     SEXP resultKind)
940  {  {
941      const char* res_ch = CHAR(STRING_ELT(resultKind,0));      const char* res_ch = CHAR(STRING_ELT(resultKind,0));
942      enum diag_kind { diag, diag_backpermuted, trace, prod, sum_log      enum diag_kind { diag, diag_backpermuted, trace, prod, sum_log, min, max, range
943      } res_kind = ((!strcmp(res_ch, "trace")) ? trace :      } res_kind = ((!strcmp(res_ch, "trace")) ? trace :
944                    ((!strcmp(res_ch, "sumLog")) ? sum_log :                    ((!strcmp(res_ch, "sumLog")) ? sum_log :
945                     ((!strcmp(res_ch, "prod")) ? prod :                     ((!strcmp(res_ch, "prod")) ? prod :
946                        ((!strcmp(res_ch, "min")) ? min :
947                         ((!strcmp(res_ch, "max")) ? max :
948                          ((!strcmp(res_ch, "range")) ? range :
949                      ((!strcmp(res_ch, "diag")) ? diag :                      ((!strcmp(res_ch, "diag")) ? diag :
950                       ((!strcmp(res_ch, "diagBack")) ? diag_backpermuted :                       ((!strcmp(res_ch, "diagBack")) ? diag_backpermuted :
951                        -1)))));                           -1))))))));
952      int i, n_x, i_from = 0;      int i, n_x, i_from;
953      SEXP ans = PROTECT(allocVector(REALSXP,      SEXP ans = PROTECT(allocVector(REALSXP,
954  /*                                 ^^^^  FIXME[Generalize] */  /*                                 ^^^^  FIXME[Generalize] */
955                                     (res_kind == diag ||                                     (res_kind == diag ||
956                                      res_kind == diag_backpermuted) ? n : 1));                                      res_kind == diag_backpermuted) ? n :
957                                       (res_kind == range ? 2 : 1)));
958      double *v = REAL(ans);      double *v = REAL(ans);
959  /*  ^^^^^^      ^^^^  FIXME[Generalize] */  /*  ^^^^^^      ^^^^  FIXME[Generalize] */
960
961        i_from = (is_U ? -1 : 0);
962
963  #define for_DIAG(v_ASSIGN)                                              \  #define for_DIAG(v_ASSIGN)                                              \
964      for(i = 0; i < n; i++, i_from += n_x) {                             \      for(i = 0; i < n; i++) {                                    \
965          /* looking at i-th column */                                    \          /* looking at i-th column */                                    \
966          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 */ \
967            if( is_U) i_from += n_x;                                \
968          v_ASSIGN;                                                       \          v_ASSIGN;                                                       \
969            if(!is_U) i_from += n_x;                                \
970      }      }
971
972      /* NOTA BENE: we assume  -- uplo = "L" i.e. lower triangular matrix      /* NOTA BENE: we assume  -- uplo = "L" i.e. lower triangular matrix
973       *            for uplo = "U" (makes sense with a "dtCMatrix" !),       *            for uplo = "U" (makes sense with a "dtCMatrix" !),
974       *            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],
975       *            where nx = (x_p[i+1] - x_p[i])       *            where n_x = (x_p[i+1] - x_p[i])
976       */       */
977
978      switch(res_kind) {      switch(res_kind) {
979      case trace:      case trace: // = sum
980          v[0] = 0.;          v[0] = 0.;
981          for_DIAG(v[0] += x_x[i_from]);          for_DIAG(v[0] += x_x[i_from]);
982          break;          break;
# Line 572  Line 991
991          for_DIAG(v[0] *= x_x[i_from]);          for_DIAG(v[0] *= x_x[i_from]);
992          break;          break;
993
994        case min:
995            v[0] = R_PosInf;
996            for_DIAG(if(v[0] > x_x[i_from]) v[0] = x_x[i_from]);
997            break;
998
999        case max:
1000            v[0] = R_NegInf;
1001            for_DIAG(if(v[0] < x_x[i_from]) v[0] = x_x[i_from]);
1002            break;
1003
1004        case range:
1005            v[0] = R_PosInf;
1006            v[1] = R_NegInf;
1007            for_DIAG(if(v[0] > x_x[i_from]) v[0] = x_x[i_from];
1008                     if(v[1] < x_x[i_from]) v[1] = x_x[i_from]);
1009            break;
1010
1011      case diag:      case diag:
1012          for_DIAG(v[i] = x_x[i_from]);          for_DIAG(v[i] = x_x[i_from]);
1013          break;          break;
# Line 579  Line 1015
1015      case diag_backpermuted:      case diag_backpermuted:
1016          for_DIAG(v[i] = x_x[i_from]);          for_DIAG(v[i] = x_x[i_from]);
1017
1018          warning(_("resultKind = 'diagBack' (back-permuted) is experimental"));          warning(_("%s = '%s' (back-permuted) is experimental"),
1019                    "resultKind", "diagBack");
1020          /* now back_permute : */          /* now back_permute : */
1021          for(i = 0; i < n; i++) {          for(i = 0; i < n; i++) {
1022              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 1025
1025          break;          break;
1026
1027      default: /* -1 from above */      default: /* -1 from above */
1028          error("diag_tC(): invalid 'resultKind'");          error(_("diag_tC(): invalid 'resultKind'"));
1029          /* Wall: */ ans = R_NilValue; v = REAL(ans);          /* Wall: */ ans = R_NilValue; v = REAL(ans);
1030      }      }
1031
# Line 600  Line 1037
1037   * Extract the diagonal entries from *triangular* Csparse matrix  __or__ a   * Extract the diagonal entries from *triangular* Csparse matrix  __or__ a
1038   * cholmod_sparse factor (LDL = TRUE).   * cholmod_sparse factor (LDL = TRUE).
1039   *   *
1040     * @param obj -- now a cholmod_sparse factor or a dtCMatrix
1041   * @param pslot  'p' (column pointer)   slot of Csparse matrix/factor   * @param pslot  'p' (column pointer)   slot of Csparse matrix/factor
1042   * @param xslot  'x' (non-zero entries) slot of Csparse matrix/factor   * @param xslot  'x' (non-zero entries) slot of Csparse matrix/factor
1043   * @param perm_slot  'perm' (= permutation vector) slot of corresponding CHMfactor;   * @param perm_slot  'perm' (= permutation vector) slot of corresponding CHMfactor;
# Line 608  Line 1046
1046   *   *
1047   * @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
1048   */   */
1049  SEXP diag_tC(SEXP pslot, SEXP xslot, SEXP perm_slot, SEXP resultKind)  SEXP diag_tC(SEXP obj, SEXP resultKind)
1050  {  {
1051
1052        SEXP
1053            pslot = GET_SLOT(obj, Matrix_pSym),
1054            xslot = GET_SLOT(obj, Matrix_xSym);
1055        Rboolean is_U = (R_has_slot(obj, Matrix_uploSym) &&
1056                         *CHAR(asChar(GET_SLOT(obj, Matrix_uploSym))) == 'U');
1057      int n = length(pslot) - 1, /* n = ncol(.) = nrow(.) */      int n = length(pslot) - 1, /* n = ncol(.) = nrow(.) */
1058          *x_p  = INTEGER(pslot),          *x_p  = INTEGER(pslot), pp = -1, *perm;
*perm = INTEGER(perm_slot);
1059      double *x_x = REAL(xslot);      double *x_x = REAL(xslot);
1060  /*  ^^^^^^        ^^^^ FIXME[Generalize] to INTEGER(.) / LOGICAL(.) / ... xslot !*/  /*  ^^^^^^        ^^^^ FIXME[Generalize] to INTEGER(.) / LOGICAL(.) / ... xslot !*/
1061
1062      return diag_tC_ptr(n, x_p, x_x, perm, resultKind);      if(R_has_slot(obj, Matrix_permSym))
1063            perm = INTEGER(GET_SLOT(obj, Matrix_permSym));
1064        else perm = &pp;
1065
1066        return diag_tC_ptr(n, x_p, x_x, is_U, perm, resultKind);
1067    }
1068
1069
1070    /**
1071     * Create a Csparse matrix object from indices and/or pointers.
1072     *
1073     * @param cls name of actual class of object to create
1074     * @param i optional integer vector of length nnz of row indices
1075     * @param j optional integer vector of length nnz of column indices
1076     * @param p optional integer vector of length np of row or column pointers
1077     * @param np length of integer vector p.  Must be zero if p == (int*)NULL
1078     * @param x optional vector of values
1079     * @param nnz length of vectors i, j and/or x, whichever is to be used
1080     * @param dims optional integer vector of length 2 to be used as
1081     *     dimensions.  If dims == (int*)NULL then the maximum row and column
1082     *     index are used as the dimensions.
1083     * @param dimnames optional list of length 2 to be used as dimnames
1084     * @param index1 indicator of 1-based indices
1085     *
1086     * @return an SEXP of class cls inheriting from CsparseMatrix.
1087     */
1088    SEXP create_Csparse(char* cls, int* i, int* j, int* p, int np,
1089                        void* x, int nnz, int* dims, SEXP dimnames,
1090                        int index1)
1091    {
1092        SEXP ans;
1093        int *ij = (int*)NULL, *tri, *trj,
1094            mi, mj, mp, nrow = -1, ncol = -1;
1095        int xtype = -1;             /* -Wall */
1096        CHM_TR T;
1097        CHM_SP A;
1098
1099        if (np < 0 || nnz < 0)
1100            error(_("negative vector lengths not allowed: np = %d, nnz = %d"),
1101                  np, nnz);
1102        if (1 != ((mi = (i == (int*)NULL)) +
1103                  (mj = (j == (int*)NULL)) +
1104                  (mp = (p == (int*)NULL))))
1105            error(_("exactly 1 of 'i', 'j' or 'p' must be NULL"));
1106        if (mp) {
1107            if (np) error(_("np = %d, must be zero when p is NULL"), np);
1108        } else {
1109            if (np) {               /* Expand p to form i or j */
1110                if (!(p[0])) error(_("p[0] = %d, should be zero"), p[0]);
1111                for (int ii = 0; ii < np; ii++)
1112                    if (p[ii] > p[ii + 1])
1113                        error(_("p must be non-decreasing"));
1114                if (p[np] != nnz)
1115                    error("p[np] = %d != nnz = %d", p[np], nnz);
1116                ij = Calloc(nnz, int);
1117                if (mi) {
1118                    i = ij;
1119                    nrow = np;
1120                } else {
1121                    j = ij;
1122                    ncol = np;
1123                }
1124                /* Expand p to 0-based indices */
1125                for (int ii = 0; ii < np; ii++)
1126                    for (int jj = p[ii]; jj < p[ii + 1]; jj++) ij[jj] = ii;
1127            } else {
1128                if (nnz)
1129                    error(_("Inconsistent dimensions: np = 0 and nnz = %d"),
1130                          nnz);
1131            }
1132        }
1133        /* calculate nrow and ncol */
1134        if (nrow < 0) {
1135            for (int ii = 0; ii < nnz; ii++) {
1136                int i1 = i[ii] + (index1 ? 0 : 1); /* 1-based index */
1137                if (i1 < 1) error(_("invalid row index at position %d"), ii);
1138                if (i1 > nrow) nrow = i1;
1139            }
1140        }
1141        if (ncol < 0) {
1142            for (int jj = 0; jj < nnz; jj++) {
1143                int j1 = j[jj] + (index1 ? 0 : 1);
1144                if (j1 < 1) error(_("invalid column index at position %d"), jj);
1145                if (j1 > ncol) ncol = j1;
1146            }
1147        }
1148        if (dims != (int*)NULL) {
1149            if (dims[0] > nrow) nrow = dims[0];
1150            if (dims[1] > ncol) ncol = dims[1];
1151        }
1152        /* check the class name */
1153        if (strlen(cls) != 8)
1154            error(_("strlen of cls argument = %d, should be 8"), strlen(cls));
1155        if (!strcmp(cls + 2, "CMatrix"))
1156            error(_("cls = \"%s\" does not end in \"CMatrix\""), cls);
1157        switch(cls[0]) {
1158        case 'd':
1159        case 'l':
1160            xtype = CHOLMOD_REAL;
1161        break;
1162        case 'n':
1163            xtype = CHOLMOD_PATTERN;
1164            break;
1165        default:
1166            error(_("cls = \"%s\" must begin with 'd', 'l' or 'n'"), cls);
1167        }
1168        if (cls[1] != 'g')
1169            error(_("Only 'g'eneral sparse matrix types allowed"));
1170        /* allocate and populate the triplet */
1171        T = cholmod_allocate_triplet((size_t)nrow, (size_t)ncol, (size_t)nnz, 0,
1172                                     xtype, &c);
1173        T->x = x;
1174        tri = (int*)T->i;
1175        trj = (int*)T->j;
1176        for (int ii = 0; ii < nnz; ii++) {
1177            tri[ii] = i[ii] - ((!mi && index1) ? 1 : 0);
1178            trj[ii] = j[ii] - ((!mj && index1) ? 1 : 0);
1179        }
1180        /* create the cholmod_sparse structure */
1181        A = cholmod_triplet_to_sparse(T, nnz, &c);
1182        cholmod_free_triplet(&T, &c);
1183        /* copy the information to the SEXP */
1184        ans = PROTECT(NEW_OBJECT(MAKE_CLASS(cls)));
1185    // FIXME: This has been copied from chm_sparse_to_SEXP in  chm_common.c
1186        /* allocate and copy common slots */
1187        nnz = cholmod_nnz(A, &c);
1188        dims = INTEGER(ALLOC_SLOT(ans, Matrix_DimSym, INTSXP, 2));
1189        dims[0] = A->nrow; dims[1] = A->ncol;
1190        Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_pSym, INTSXP, A->ncol + 1)), (int*)A->p, A->ncol + 1);
1191        Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_iSym, INTSXP, nnz)), (int*)A->i, nnz);
1192        switch(cls[1]) {
1193        case 'd':
1194            Memcpy(REAL(ALLOC_SLOT(ans, Matrix_xSym, REALSXP, nnz)), (double*)A->x, nnz);
1195            break;
1196        case 'l':
1197            error(_("code not yet written for cls = \"lgCMatrix\""));
1198        }
1199    /* FIXME: dimnames are *NOT* put there yet (if non-NULL) */
1200        cholmod_free_sparse(&A, &c);
1201        UNPROTECT(1);
1202        return ans;
1203  }  }

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