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 3270, Fri Mar 23 08:50:48 2018 UTC
# Line 1  Line 1
1                          /* Sparse matrices in compressed column-oriented form */  /** @file Csparse.c
2     * The "CsparseMatrix" class from R package Matrix:
3     *
4     * Sparse matrices in compressed column-oriented form
5     */
6  #include "Csparse.h"  #include "Csparse.h"
7  #include "Tsparse.h"  #include "Tsparse.h"
8  #include "chm_common.h"  #include "chm_common.h"
# Line 32  Line 36
36      return TRUE;      return TRUE;
37  }  }
38
39  SEXP Csparse_validate(SEXP x)  SEXP Csparse_validate(SEXP x) {
40  {      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"));
41      }      }
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)*/
42
/* 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)"));
}
43
44      } else if(!strictly) {  /* sorted, but not strictly */  #define _t_Csparse_validate
45          return mkString(_("slot i is not *strictly* increasing inside a column"));  #include "t_Csparse_validate.c"
46
47    #define _t_Csparse_sort
48    #include "t_Csparse_validate.c"
49
50    // R: .validateCsparse(x, sort.if.needed = FALSE) :
51    SEXP Csparse_validate2(SEXP x, SEXP maybe_modify) {
52        return Csparse_validate_(x, asLogical(maybe_modify));
53      }      }
54      return ScalarLogical(1);
55    // R: Matrix:::.sortCsparse(x) :
56    SEXP Csparse_sort (SEXP x) {
57       int ok = Csparse_sort_2(x, TRUE); // modifying x directly
58       if(!ok) warning(_("Csparse_sort(x): x is not a valid (apart from sorting) CsparseMatrix"));
59       return x;
60  }  }
61
62  SEXP Rsparse_validate(SEXP x)  SEXP Rsparse_validate(SEXP x)
# Line 133  Line 104
104      return ScalarLogical(1);      return ScalarLogical(1);
105  }  }
106
107    /** @brief From a CsparseMatrix, produce a dense one.
108  /* Called from ../R/Csparse.R : */   *
109  /* Can only return [dln]geMatrix (no symm/triang);   * Directly deals with symmetric, triangular and general.
110   * FIXME: replace by non-CHOLMOD code ! */   * Called from ../R/Csparse.R's  C2dense()
111  SEXP Csparse_to_dense(SEXP x)   *
112     * @param x a CsparseMatrix: currently all 9 of  "[dln][gst]CMatrix"
113     * @param symm_or_tri integer (NA, < 0, > 0, = 0) specifying the knowledge of the caller about x:
114     *      NA  : unknown => will be determined
115     *      = 0 : "generalMatrix" (not symm or tri);
116     *      < 0 : "triangularMatrix"
117     *      > 0 : "symmetricMatrix"
118     *
119     * @return a "denseMatrix"
120     */
121    SEXP Csparse_to_dense(SEXP x, SEXP symm_or_tri)
122  {  {
123      CHM_SP chxs = AS_CHM_SP__(x);      Rboolean is_sym, is_tri;
124      /* This loses the symmetry property, since cholmod_dense has none,      int is_sym_or_tri = asInteger(symm_or_tri),
125            ctype = 0; // <- default = "dgC"
126        static const char *valid[] = { MATRIX_VALID_Csparse, ""};
127        if(is_sym_or_tri == NA_INTEGER) { // find if  is(x, "symmetricMatrix") :
128            ctype = R_check_class_etc(x, valid);
129            is_sym = (ctype % 3 == 1);
130            is_tri = (ctype % 3 == 2);
131        } else {
132            is_sym = is_sym_or_tri > 0;
133            is_tri = is_sym_or_tri < 0;
134            // => both are FALSE  iff  is_.. == 0
135            if(is_sym || is_tri)
136                ctype = R_check_class_etc(x, valid);
137        }
138        CHM_SP chxs = AS_CHM_SP__(x);// -> chxs->stype = +- 1 <==> symmetric
139        R_CheckStack();
140        if(is_tri && *diag_P(x) == 'U') { // ==>  x := diagU2N(x), directly for chxs
141            CHM_SP eye = cholmod_speye(chxs->nrow, chxs->ncol, chxs->xtype, &c);
142            double one[] = {1, 0};
143            CHM_SP ans = cholmod_add(chxs, eye, one, one,
144                                     /* values: */ ((ctype / 3) != 2), // TRUE iff not "nMatrix"
145                                     TRUE, &c);
146            cholmod_free_sparse(&eye, &c);
147            chxs = cholmod_copy_sparse(ans, &c);
148            cholmod_free_sparse(&ans, &c);
149        }
150        /* The following loses the symmetry property, since cholmod_dense has none,
151       * BUT, much worse (FIXME!), it also transforms CHOLMOD_PATTERN ("n") matrices       * BUT, much worse (FIXME!), it also transforms CHOLMOD_PATTERN ("n") matrices
152       * to numeric (CHOLMOD_REAL) ones : */       * to numeric (CHOLMOD_REAL) ones {and we "revert" via chm_dense_to_SEXP()}: */
153      CHM_DN chxd = cholmod_sparse_to_dense(chxs, &c);      CHM_DN chxd = cholmod_sparse_to_dense(chxs, &c);
154        /* FIXME: The above FAILS for prod(dim(.)) > INT_MAX
155         * ----
156         * TODO: use cholmod_l_* but also the 'cl' global ==> many changes in chm_common.[ch]
157         * >>>>>>>>>>> TODO <<<<<<<<<<<<
158         * CHM_DN chxd = cholmod_l_sparse_to_dense(chxs, &cl); */
159        //                   ^^^ important when prod(dim(.)) > INT_MAX
160      int Rkind = (chxs->xtype == CHOLMOD_PATTERN)? -1 : Real_kind(x);      int Rkind = (chxs->xtype == CHOLMOD_PATTERN)? -1 : Real_kind(x);
R_CheckStack();
161
162      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),
163                                     /* transp: */ FALSE);
164        // -> a [dln]geMatrix
165        if(is_sym) { // ==> want  [dln]syMatrix
166            const char cl1 = class_P(ans)[0];
167            PROTECT(ans);
168            SEXP aa = PROTECT(NEW_OBJECT(MAKE_CLASS((cl1 == 'd') ? "dsyMatrix" :
169                                                    ((cl1 == 'l') ? "lsyMatrix" : "nsyMatrix"))));
170            // No need to duplicate() as slots of ans are freshly allocated and ans will not be used
171            SET_SLOT(aa, Matrix_xSym,       GET_SLOT(ans, Matrix_xSym));
172            SET_SLOT(aa, Matrix_DimSym,     GET_SLOT(ans, Matrix_DimSym));
173            SET_SLOT(aa, Matrix_DimNamesSym,GET_SLOT(ans, Matrix_DimNamesSym));
174            SET_SLOT(aa, Matrix_uploSym, mkString((chxs->stype > 0) ? "U" : "L"));
175            UNPROTECT(2);
176            return aa;
177        }
178        else if(is_tri) { // ==> want  [dln]trMatrix
179            const char cl1 = class_P(ans)[0];
180            PROTECT(ans);
181            SEXP aa = PROTECT(NEW_OBJECT(MAKE_CLASS((cl1 == 'd') ? "dtrMatrix" :
182                                                    ((cl1 == 'l') ? "ltrMatrix" : "ntrMatrix"))));
183            // No need to duplicate() as slots of ans are freshly allocated and ans will not be used
184            SET_SLOT(aa, Matrix_xSym,       GET_SLOT(ans, Matrix_xSym));
185            SET_SLOT(aa, Matrix_DimSym,     GET_SLOT(ans, Matrix_DimSym));
186            SET_SLOT(aa, Matrix_DimNamesSym,GET_SLOT(ans, Matrix_DimNamesSym));
187            slot_dup(aa, x, Matrix_uploSym);
188            /* already by NEW_OBJECT(..) above:
189               SET_SLOT(aa, Matrix_diagSym, mkString("N")); */
190            UNPROTECT(2);
191            return aa;
192        }
193        else
194            return ans;
195  }  }
196
197  SEXP Csparse_to_nz_pattern(SEXP x, SEXP tri)  // FIXME: do not go via CHM (should not be too hard, to just *drop* the x-slot, right?
198    SEXP Csparse2nz(SEXP x, Rboolean tri)
199  {  {
200      CHM_SP chxs = AS_CHM_SP__(x);      CHM_SP chxs = AS_CHM_SP__(x);
201      CHM_SP chxcp = cholmod_copy(chxs, chxs->stype, CHOLMOD_PATTERN, &c);      CHM_SP chxcp = cholmod_copy(chxs, chxs->stype, CHOLMOD_PATTERN, &c);
int tr = asLogical(tri);
202      R_CheckStack();      R_CheckStack();
203
204      return chm_sparse_to_SEXP(chxcp, 1/*do_free*/,      return chm_sparse_to_SEXP(chxcp, 1/*do_free*/,
205                                tr ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,                                tri ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,
206                                0, tr ? diag_P(x) : "",                                /* Rkind: pattern */ 0,
207                                  /* diag = */ tri ? diag_P(x) : "",
208                                GET_SLOT(x, Matrix_DimNamesSym));                                GET_SLOT(x, Matrix_DimNamesSym));
209  }  }
210    SEXP Csparse_to_nz_pattern(SEXP x, SEXP tri)
211    {
212        int tr_ = asLogical(tri);
213        if(tr_ == NA_LOGICAL) {
214            warning(_("Csparse_to_nz_pattern(x, tri = NA): 'tri' is taken as TRUE"));
215            tr_ = TRUE;
216        }
217        return Csparse2nz(x, (Rboolean) tr_);
218    }
219
220    // n.CMatrix --> [dli].CMatrix  (not going through CHM!)
221    SEXP nz_pattern_to_Csparse(SEXP x, SEXP res_kind)
222    {
223        return nz2Csparse(x, asInteger(res_kind));
224    }
225
226    // n.CMatrix --> [dli].CMatrix  (not going through CHM!)
227    // NOTE: use chm_MOD_xtype(() to change type of  'cholmod_sparse' matrix
228    SEXP nz2Csparse(SEXP x, enum x_slot_kind r_kind)
229    {
230        const char *cl_x = class_P(x);
231        // quick check - if ok, fast
232        if(cl_x[0] != 'n' || cl_x[2] != 'C') {
233            // e.g. class = "A", from  setClass("A", contains = "ngCMatrix")
234            static const char *valid[] = { MATRIX_VALID_nCsparse, ""};
235            int ctype = R_check_class_etc(x, valid);
236            if(ctype < 0)
237                error(_("not a 'n.CMatrix'"));
238            else // fine : get a valid  cl_x  class_P()-like string :
239                cl_x = valid[ctype];
240        }
241        int nnz = LENGTH(GET_SLOT(x, Matrix_iSym));
242        SEXP ans;
243        char *ncl = alloca(strlen(cl_x) + 1); /* not much memory required */
244        strcpy(ncl, cl_x);
245        double *dx_x; int *ix_x;
246        ncl[0] = (r_kind == x_double ? 'd' :
247                  (r_kind == x_logical ? 'l' :
248                   /* else (for now):  r_kind == x_integer : */ 'i'));
249        PROTECT(ans = NEW_OBJECT_OF_CLASS(ncl));
250        // create a correct 'x' slot:
251        switch(r_kind) {
252            int i;
253        case x_double: // 'd'
254            dx_x = REAL(ALLOC_SLOT(ans, Matrix_xSym, REALSXP, nnz));
255            for (i=0; i < nnz; i++) dx_x[i] = 1.;
256            break;
257        case x_logical: // 'l'
258            ix_x = LOGICAL(ALLOC_SLOT(ans, Matrix_xSym, LGLSXP, nnz));
259            for (i=0; i < nnz; i++) ix_x[i] = TRUE;
260            break;
261        case x_integer: // 'i'
262            ix_x = INTEGER(ALLOC_SLOT(ans, Matrix_xSym, INTSXP, nnz));
263            for (i=0; i < nnz; i++) ix_x[i] = 1;
264            break;
265
266  SEXP Csparse_to_matrix(SEXP x)      default:
267            error(_("nz2Csparse(): invalid/non-implemented r_kind = %d"),
268                  r_kind);
269        }
270
271        // now copy all other slots :
272        slot_dup(ans, x, Matrix_iSym);
273        slot_dup(ans, x, Matrix_pSym);
274        slot_dup(ans, x, Matrix_DimSym);
275        slot_dup(ans, x, Matrix_DimNamesSym);
276        if(ncl[1] != 'g') { // symmetric or triangular ...
277            slot_dup_if_has(ans, x, Matrix_uploSym);
278            slot_dup_if_has(ans, x, Matrix_diagSym);
279        }
280        UNPROTECT(1);
281        return ans;
282    }
283
284    SEXP Csparse_to_matrix(SEXP x, SEXP chk, SEXP symm)
285  {  {
286      return chm_dense_to_matrix(cholmod_sparse_to_dense(AS_CHM_SP__(x), &c),      int is_sym = asLogical(symm);
287                                 1 /*do_free*/, GET_SLOT(x, Matrix_DimNamesSym));      if(is_sym == NA_LOGICAL) { // find if  is(x, "symmetricMatrix") :
288            static const char *valid[] = { MATRIX_VALID_Csparse, ""};
289            int ctype = R_check_class_etc(x, valid);
290            is_sym = (ctype % 3 == 1);
291        }
292        return chm_dense_to_matrix(
293            cholmod_sparse_to_dense(AS_CHM_SP2(x, asLogical(chk)), &c),
294            1 /*do_free*/,
295            (is_sym
296             ? symmetric_DimNames(GET_SLOT(x, Matrix_DimNamesSym))
297             :                    GET_SLOT(x, Matrix_DimNamesSym)));
298    }
299
300    SEXP Csparse_to_vector(SEXP x)
301    {
302        return chm_dense_to_vector(cholmod_sparse_to_dense(AS_CHM_SP__(x), &c), 1);
303  }  }
304
305  SEXP Csparse_to_Tsparse(SEXP x, SEXP tri)  SEXP Csparse_to_Tsparse(SEXP x, SEXP tri)
# Line 183  Line 316
316                                 GET_SLOT(x, Matrix_DimNamesSym));                                 GET_SLOT(x, Matrix_DimNamesSym));
317  }  }
318
319  /* this used to be called  sCMatrix_to_gCMatrix(..)   [in ./dsCMatrix.c ]: */  SEXP Csparse_to_tCsparse(SEXP x, SEXP uplo, SEXP diag)
320    {
321        CHM_SP chxs = AS_CHM_SP__(x);
322        int Rkind = (chxs->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
323        R_CheckStack();
324        return chm_sparse_to_SEXP(chxs, /* dofree = */ 0,
325                                  /* uploT = */ (*CHAR(asChar(uplo)) == 'U')? 1: -1,
326                                   Rkind, /* diag = */ CHAR(STRING_ELT(diag, 0)),
327                                   GET_SLOT(x, Matrix_DimNamesSym));
328    }
329
330    SEXP Csparse_to_tTsparse(SEXP x, SEXP uplo, SEXP diag)
331    {
332        CHM_SP chxs = AS_CHM_SP__(x);
333        CHM_TR chxt = cholmod_sparse_to_triplet(chxs, &c);
334        int Rkind = (chxs->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
335        R_CheckStack();
336        return chm_triplet_to_SEXP(chxt, 1,
337                                  /* uploT = */ (*CHAR(asChar(uplo)) == 'U')? 1: -1,
338                                   Rkind, /* diag = */ CHAR(STRING_ELT(diag, 0)),
339                                   GET_SLOT(x, Matrix_DimNamesSym));
340    }
341
342
343  SEXP Csparse_symmetric_to_general(SEXP x)  SEXP Csparse_symmetric_to_general(SEXP x)
344  {  {
345      CHM_SP chx = AS_CHM_SP__(x), chgx;      CHM_SP chx = AS_CHM_SP__(x), chgx;
# Line 193  Line 349
349      if (!(chx->stype))      if (!(chx->stype))
350          error(_("Nonsymmetric matrix in Csparse_symmetric_to_general"));          error(_("Nonsymmetric matrix in Csparse_symmetric_to_general"));
351      chgx = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);      chgx = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);
/* xtype: pattern, "real", complex or .. */
352      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",
353                                GET_SLOT(x, Matrix_DimNamesSym));                                symmetric_DimNames(GET_SLOT(x, Matrix_DimNamesSym)));
354  }  }
355
356  SEXP Csparse_general_to_symmetric(SEXP x, SEXP uplo)  SEXP Csparse_general_to_symmetric(SEXP x, SEXP uplo, SEXP sym_dmns)
357  {  {
360            error(_("Csparse_general_to_symmetric(): matrix is not square!"));
361            return R_NilValue; /* -Wall */
362        }
363      CHM_SP chx = AS_CHM_SP__(x), chgx;      CHM_SP chx = AS_CHM_SP__(x), chgx;
364      int uploT = (*CHAR(STRING_ELT(uplo,0)) == 'U') ? 1 : -1;      int uploT = (*CHAR(asChar(uplo)) == 'U') ? 1 : -1;
365      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
366      R_CheckStack();      R_CheckStack();

367      chgx = cholmod_copy(chx, /* stype: */ uploT, chx->xtype, &c);      chgx = cholmod_copy(chx, /* stype: */ uploT, chx->xtype, &c);
368      /* xtype: pattern, "real", complex or .. */
369      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",      SEXP dns = GET_SLOT(x, Matrix_DimNamesSym);
370                                GET_SLOT(x, Matrix_DimNamesSym));      if(asLogical(sym_dmns))
371            dns = symmetric_DimNames(dns);
372        else if((!isNull(VECTOR_ELT(dns, 0)) &&
373                 !isNull(VECTOR_ELT(dns, 1))) ||
374                !isNull(getAttrib(dns, R_NamesSymbol))) {
375            /* symmetrize them if both are not NULL
376             * or names(dimnames(.)) is asymmetric : */
377            dns = PROTECT(duplicate(dns));
378            if(!equal_string_vectors(VECTOR_ELT(dns, 0),
379                                     VECTOR_ELT(dns, 1))) {
380                if(uploT == 1)
381                    SET_VECTOR_ELT(dns, 0, VECTOR_ELT(dns,1));
382                else
383                    SET_VECTOR_ELT(dns, 1, VECTOR_ELT(dns,0));
384            }
385            SEXP nms_dns = getAttrib(dns, R_NamesSymbol);
386            if(!isNull(nms_dns) &&  // names(dimnames(.)) :
387               !R_compute_identical(STRING_ELT(nms_dns, 0),
388                                    STRING_ELT(nms_dns, 1), 16)) {
389                if(uploT == 1)
390                    SET_STRING_ELT(nms_dns, 0, STRING_ELT(nms_dns,1));
391                else
392                    SET_STRING_ELT(nms_dns, 1, STRING_ELT(nms_dns,0));
393                setAttrib(dns, R_NamesSymbol, nms_dns);
394            }
395            UNPROTECT(1);
396        }
397        /* Rkind: pattern, "real", complex or .. */
398        return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "", dns);
399  }  }
400
401  SEXP Csparse_transpose(SEXP x, SEXP tri)  SEXP Csparse_transpose(SEXP x, SEXP tri)
# Line 225  Line 412
412      tmp = VECTOR_ELT(dn, 0);    /* swap the dimnames */      tmp = VECTOR_ELT(dn, 0);    /* swap the dimnames */
413      SET_VECTOR_ELT(dn, 0, VECTOR_ELT(dn, 1));      SET_VECTOR_ELT(dn, 0, VECTOR_ELT(dn, 1));
414      SET_VECTOR_ELT(dn, 1, tmp);      SET_VECTOR_ELT(dn, 1, tmp);
415        tmp = PROTECT(getAttrib(dn, R_NamesSymbol));
416        if(!isNull(tmp)) { // swap names(dimnames(.)):
417            SEXP nms_dns = PROTECT(allocVector(VECSXP, 2));
418            SET_VECTOR_ELT(nms_dns, 1, STRING_ELT(tmp, 0));
419            SET_VECTOR_ELT(nms_dns, 0, STRING_ELT(tmp, 1));
420            setAttrib(dn, R_NamesSymbol, nms_dns);
421      UNPROTECT(1);      UNPROTECT(1);
422      return chm_sparse_to_SEXP(chxt, 1, /* SWAP 'uplo' for triangular */      }
423
424        SEXP ans = chm_sparse_to_SEXP(chxt, 1, /* SWAP 'uplo' for triangular */
425                                tr ? ((*uplo_P(x) == 'U') ? -1 : 1) : 0,                                tr ? ((*uplo_P(x) == 'U') ? -1 : 1) : 0,
426                                Rkind, tr ? diag_P(x) : "", dn);                                Rkind, tr ? diag_P(x) : "", dn);
427        UNPROTECT(2);
428        return ans;
429  }  }
430
431  SEXP Csparse_Csparse_prod(SEXP a, SEXP b)  /** @brief  A %*% B  - for matrices of class CsparseMatrix (R package "Matrix")
432     *
433     * @param a
434     * @param b
435     * @param bool_arith
436     *
437     * @return
438     *
439     * NOTA BENE:  cholmod_ssmult(A,B, ...) ->  ./CHOLMOD/MatrixOps/cholmod_ssmult.c
440     * ---------  computes a patter*n* matrix __always_ when
441     * *one* of A or B is pattern*n*, because of this (line 73-74):
442       ---------------------------------------------------------------------------
443        values = values &&
444            (A->xtype != CHOLMOD_PATTERN) && (B->xtype != CHOLMOD_PATTERN) ;
445       ---------------------------------------------------------------------------
446     * ==> Often need to copy the patter*n* to a *l*ogical matrix first !!!
447     */
448    SEXP Csparse_Csparse_prod(SEXP a, SEXP b, SEXP bool_arith)
449  {  {
450      CHM_SP      CHM_SP
451          cha = AS_CHM_SP(a),          cha = AS_CHM_SP(a),
452          chb = AS_CHM_SP(b),          chb = AS_CHM_SP(b), chc;
453          chc = cholmod_ssmult(cha, chb, /*out_stype:*/ 0,      R_CheckStack();
454                               cha->xtype, /*out sorted:*/ 1, &c);      static const char *valid_tri[] = { MATRIX_VALID_tri_Csparse, "" };
const char *cl_a = class_P(a), *cl_b = class_P(b);
455      char diag[] = {'\0', '\0'};      char diag[] = {'\0', '\0'};
456      int uploT = 0;      int uploT = 0, nprot = 1,
457      SEXP dn = allocVector(VECSXP, 2);          do_bool = asLogical(bool_arith); // TRUE / NA / FALSE
458        Rboolean
459            a_is_n = (cha->xtype == CHOLMOD_PATTERN),
460            b_is_n = (chb->xtype == CHOLMOD_PATTERN),
461            force_num = (do_bool == FALSE),
462            maybe_bool= (do_bool == NA_LOGICAL);
463
464    #ifdef DEBUG_Matrix_verbose
465        Rprintf("DBG Csparse_C*_prod(%s, %s)\n", class_P(a), class_P(b));
466    #endif
467
468        if(a_is_n && (force_num || (maybe_bool && !b_is_n))) {
469            /* coerce 'a' to  double;
470             * have no CHOLMOD function (pattern -> logical) --> use "our" code */
471            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
472            cha = AS_CHM_SP(da);
473            R_CheckStack();
474            a_is_n = FALSE;
475        }
476        else if(b_is_n && (force_num || (maybe_bool && !a_is_n))) {
477            // coerce 'b' to  double
478            SEXP db = PROTECT(nz2Csparse(b, x_double)); nprot++;
479            chb = AS_CHM_SP(db);
480      R_CheckStack();      R_CheckStack();
481            b_is_n = FALSE;
482        }
483        chc = cholmod_ssmult(cha, chb, /*out_stype:*/ 0,
484                             /* values : */ do_bool != TRUE,
485                             /* sorted = TRUE: */ 1, &c);
486
487      /* Preserve triangularity and even unit-triangularity if appropriate.      /* Preserve triangularity and even unit-triangularity if appropriate.
488       * Note that in that case, the multiplication itself should happen       * Note that in that case, the multiplication itself should happen
489       * faster.  But there's no support for that in CHOLMOD */       * faster.  But there's no support for that in CHOLMOD */
490
491      /* UGLY hack -- rather should have (fast!) C-level version of      if(R_check_class_etc(a, valid_tri) >= 0 &&
492       *       is(a, "triangularMatrix") etc */         R_check_class_etc(b, valid_tri) >= 0)
if (cl_a[1] == 't' && cl_b[1] == 't')
/* FIXME: fails for "Cholesky","BunchKaufmann"..*/
493          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. */
494              uploT = (*uplo_P(a) == 'U') ? 1 : -1;              uploT = (*uplo_P(a) == 'U') ? 1 : -1;
495              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 499
499              }              }
500              else diag[0]= 'N';              else diag[0]= 'N';
501          }          }
502
503        SEXP dn = PROTECT(allocVector(VECSXP, 2));
504      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
505                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));
506      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
507                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), 1)));
508        UNPROTECT(nprot);
509      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);
510  }  }
511
512  SEXP Csparse_Csparse_crossprod(SEXP a, SEXP b, SEXP trans)  /** @brief [t]crossprod (<Csparse>, <Csparse>)
513     *
514     * @param a a "CsparseMatrix" object
515     * @param b a "CsparseMatrix" object
516     * @param trans trans = FALSE:  crossprod(a,b)
517     *              trans = TRUE : tcrossprod(a,b)
518     * @param bool_arith logical (TRUE / NA / FALSE): Should boolean arithmetic be used.
519     *
520     * @return a CsparseMatrix, the (t)cross product of a and b.
521     */
522    SEXP Csparse_Csparse_crossprod(SEXP a, SEXP b, SEXP trans, SEXP bool_arith)
523  {  {
524      int tr = asLogical(trans);      int tr = asLogical(trans), nprot = 1,
525            do_bool = asLogical(bool_arith); // TRUE / NA / FALSE
526      CHM_SP      CHM_SP
527          cha = AS_CHM_SP(a),          cha = AS_CHM_SP(a),
528          chb = AS_CHM_SP(b),          chb = AS_CHM_SP(b),
529          chTr, chc;          chTr, chc;
530      const char *cl_a = class_P(a), *cl_b = class_P(b);      R_CheckStack();
531        static const char *valid_tri[] = { MATRIX_VALID_tri_Csparse, "" };
532      char diag[] = {'\0', '\0'};      char diag[] = {'\0', '\0'};
533      int uploT = 0;      int uploT = 0;
534      SEXP dn = allocVector(VECSXP, 2);      Rboolean
535            a_is_n = (cha->xtype == CHOLMOD_PATTERN),
536            b_is_n = (chb->xtype == CHOLMOD_PATTERN),
537            force_num = (do_bool == FALSE),
538            maybe_bool= (do_bool == NA_LOGICAL);
539
540        if(a_is_n && (force_num || (maybe_bool && !b_is_n))) {
541            // coerce 'a' to  double
542            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
543            cha = AS_CHM_SP(da);
544      R_CheckStack();      R_CheckStack();
545            // a_is_n = FALSE;
546        }
547        else if(b_is_n && (force_num || (maybe_bool && !a_is_n))) {
548            // coerce 'b' to  double
549            SEXP db = PROTECT(nz2Csparse(b, x_double)); nprot++;
550            chb = AS_CHM_SP(db);
551            R_CheckStack();
552            // b_is_n = FALSE;
553        }
554        else if(do_bool == TRUE) { // Want boolean arithmetic: sufficient if *one* is pattern:
555            if(!a_is_n && !b_is_n) {
556                // coerce 'a' to pattern
557                SEXP da = PROTECT(Csparse2nz(a, /* tri = */
558                                             R_check_class_etc(a, valid_tri) >= 0)); nprot++;
559                cha = AS_CHM_SP(da);
560                R_CheckStack();
561                // a_is_n = TRUE;
562            }
563        }
564      chTr = cholmod_transpose((tr) ? chb : cha, chb->xtype, &c);      chTr = cholmod_transpose((tr) ? chb : cha, chb->xtype, &c);
565      chc = cholmod_ssmult((tr) ? cha : chTr, (tr) ? chTr : chb,      chc = cholmod_ssmult((tr) ? cha : chTr, (tr) ? chTr : chb,
566                           /*out_stype:*/ 0, cha->xtype, /*out sorted:*/ 1, &c);                           /*out_stype:*/ 0, /* values : */ do_bool != TRUE,
567                             /* sorted = TRUE: */ 1, &c);
568      cholmod_free_sparse(&chTr, &c);      cholmod_free_sparse(&chTr, &c);
569
570      /* Preserve triangularity and unit-triangularity if appropriate;      /* Preserve triangularity and unit-triangularity if appropriate;
571       * see Csparse_Csparse_prod() for comments */       * see Csparse_Csparse_prod() for comments */
572      if (cl_a[1] == 't' && cl_b[1] == 't')      if(R_check_class_etc(a, valid_tri) >= 0 &&
573           R_check_class_etc(b, valid_tri) >= 0)
574          if(*uplo_P(a) != *uplo_P(b)) { /* one 'U', the other 'L' */          if(*uplo_P(a) != *uplo_P(b)) { /* one 'U', the other 'L' */
575              uploT = (*uplo_P(b) == 'U') ? 1 : -1;              uploT = (*uplo_P(b) == 'U') ? 1 : -1;
576              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 580
580              else diag[0]= 'N';              else diag[0]= 'N';
581          }          }
582
583        SEXP dn = PROTECT(allocVector(VECSXP, 2));
584      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
585                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), (tr) ? 0 : 1)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym),
586                                            (tr) ? 0 : 1)));
587      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
588                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), (tr) ? 0 : 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym),
589                                            (tr) ? 0 : 1)));
590        UNPROTECT(nprot);
591      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);
592  }  }
593
594  SEXP Csparse_dense_prod(SEXP a, SEXP b)  /**
595     * All (dense * sparse)  Matrix products and cross products
596     *
597     *   f( f(<Csparse>)  %*%  f(<dense>) )   where  f ()  is either t () [tranpose] or the identity.
598     *
599     * @param a CsparseMatrix  (n x m)
600     * @param b numeric vector, matrix, or denseMatrix (m x k) or (k x m)  if `transp` is '2' or 'B'
601     * @param transp character.
602     *        = " " : nothing transposed {apart from a}
603     *        = "2" : "transpose 2nd arg": use  t(b) instead of b (= 2nd argument)
604     *        = "c" : "transpose c":       Return  t(c) instead of c
605     *        = "B" : "transpose both":    use t(b) and return t(c) instead of c
606     * NB: For "2", "c", "B", need to transpose a *dense* matrix, B or C --> chm_transpose_dense()
607     *
608     * @return a dense matrix, the matrix product c = g(a,b) :
609     *
610     *                                                Condition (R)   Condition (C)
611     *   R notation            Math notation          cross  transp   t.a t.b t.ans
612     *   ~~~~~~~~~~~~~~~~~     ~~~~~~~~~~~~~~~~~~     ~~~~~~~~~~~~~   ~~~~~~~~~~~~~
613     *   c <-   a %*%   b      C :=      A B            .       " "    .   .   .
614     *   c <-   a %*% t(b)     C :=      A B'           .       "2"    .   |   .
615     *   c <- t(a %*%   b)     C := (A B)'  = B'A'      .       "c"    .   .   |
616     *   c <- t(a %*% t(b))    C := (A B')' = B A'      .       "B"    .   |   |
617     *
618     *   c <-   t(a) %*%   b   C :=      A'B           TRUE     " "    |   .   .
619     *   c <-   t(a) %*% t(b)  C :=      A'B'          TRUE     "2"    |   |   .
620     *   c <- t(t(a) %*%   b)  C := (A'B)'  = B'A      TRUE     "c"    |   .   |
621     *   c <- t(t(a) %*% t(b)) C := (A'B')' = B A      TRUE     "B"    |   |   |
622     */
623    SEXP Csp_dense_products(SEXP a, SEXP b,
624                            Rboolean transp_a, Rboolean transp_b, Rboolean transp_ans)
625  {  {
626      CHM_SP cha = AS_CHM_SP(a);      CHM_SP cha = AS_CHM_SP(a);
627      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix(b));      int a_nc = transp_a ? cha->nrow : cha->ncol,
628      CHM_DN chb = AS_CHM_DN(b_M);          a_nr = transp_a ? cha->ncol : cha->nrow;
629      CHM_DN chc = cholmod_allocate_dense(cha->nrow, chb->ncol, cha->nrow,      Rboolean
630                                          chb->xtype, &c);          maybe_transp_b = (a_nc == 1),
631      SEXP dn = PROTECT(allocVector(VECSXP, 2));          b_is_vector = FALSE;
632      double one[] = {1,0}, zero[] = {0,0};      /* NOTE: trans_b {<--> "use t(b) instead of b" }
633           ----  "interferes" with the  case automatic treatment of *vector* b.
634           In that case,  t(b) or b is used "whatever make more sense",
635           according to the general R philosophy of treating vectors in matrix products.
636        */
637
638        /* repeating a "cheap part" of  mMatrix_as_dgeMatrix2(b, .)  to see if
639         * we have a vector that we might 'transpose_if_vector' : */
640        static const char *valid[] = {"_NOT_A_CLASS_", MATRIX_VALID_ddense, ""};
641        /* int ctype = R_check_class_etc(b, valid);
642         * if (ctype > 0)   /.* a ddenseMatrix object */
643        if (R_check_class_etc(b, valid) < 0) {
644            // not a ddenseM*:  is.matrix() or vector:
645            b_is_vector = !isMatrix(b);
646        }
647
648        if(b_is_vector) {
649            /* determine *if* we want/need to transpose at all:
650             * if (length(b) == ncol(A)) have match: use dim = c(n, 1) (<=> do *not* transp);
651             *  otherwise, try to transpose: ok  if (ncol(A) == 1) [see also above]:  */
652            maybe_transp_b = (LENGTH(b) != a_nc);
653            // Here, we transpose already in mMatrix_as_dge*()  ==> don't do it later:
654            transp_b = FALSE;
655        }
656        SEXP b_M = PROTECT(mMatrix_as_dgeMatrix2(b, maybe_transp_b));
657
658        CHM_DN chb = AS_CHM_DN(b_M), b_t;
659      R_CheckStack();      R_CheckStack();
660        int ncol_b;
661        if(transp_b) { // transpose b:
662            b_t = cholmod_allocate_dense(chb->ncol, chb->nrow, chb->ncol, chb->xtype, &c);
663            chm_transpose_dense(b_t, chb);
664            ncol_b = b_t->ncol;
665        } else
666            ncol_b = chb->ncol;
667        // Result C {with dim() before it may be transposed}:
668        CHM_DN chc = cholmod_allocate_dense(a_nr, ncol_b, a_nr, chb->xtype, &c);
669        double one[] = {1,0}, zero[] = {0,0};
670        int nprot = 2;
671
672      cholmod_sdmult(cha, 0, one, zero, chb, chc, &c);      /* Tim Davis, please FIXME:  currently (2010-11) *fails* when  a  is a pattern matrix:*/
673      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      if(cha->xtype == CHOLMOD_PATTERN) {
674                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));          /* warning(_("Csparse_dense_prod(): cholmod_sdmult() not yet implemented for pattern./ ngCMatrix" */
675      SET_VECTOR_ELT(dn, 1,          /*        " --> slightly inefficient coercion")); */
676                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));          // This *fails* to produce a CHOLMOD_REAL ..
677      UNPROTECT(2);          // CHM_SP chd = cholmod_l_copy(cha, cha->stype, CHOLMOD_REAL, &cl);
678      return chm_dense_to_SEXP(chc, 1, 0, dn);
679            // --> use our Matrix-classes: they work:
680            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
681            cha = AS_CHM_SP(da);
682        }
683
684        /* cholmod_sdmult(A, transp, alpha, beta, X,  Y,  &c): depending on transp == 0 / != 0:
685         *  Y := alpha*(A*X) + beta*Y or alpha*(A'*X) + beta*Y;  here, alpha = 1, beta = 0:
686         *  Y := A*X  or  A'*X
687         *                       NB: always  <sparse> %*% <dense> !
688         */
689        cholmod_sdmult(cha, transp_a, one, zero, (transp_b ? b_t : chb), /* -> */ chc, &c);
690
691        SEXP dn = PROTECT(allocVector(VECSXP, 2));  /* establish dimnames */
692        SET_VECTOR_ELT(dn, transp_ans ? 1 : 0,
693                       duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), transp_a ? 1 : 0)));
694        SET_VECTOR_ELT(dn, transp_ans ? 0 : 1,
695                       duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym),
696                                            transp_b ? 0 : 1)));
697        if(transp_b) cholmod_free_dense(&b_t, &c);
698        UNPROTECT(nprot);
699        return chm_dense_to_SEXP(chc, 1, 0, dn, transp_ans);
700  }  }
701
702  SEXP Csparse_dense_crossprod(SEXP a, SEXP b)
703    SEXP Csparse_dense_prod(SEXP a, SEXP b, SEXP transp)
704  {  {
705      CHM_SP cha = AS_CHM_SP(a);      return
706      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix(b));          Csp_dense_products(a, b,
707      CHM_DN chb = AS_CHM_DN(b_M);                  /* transp_a = */ FALSE,
708      CHM_DN chc = cholmod_allocate_dense(cha->ncol, chb->ncol, cha->ncol,                  /* transp_b   = */ (*CHAR(asChar(transp)) == '2' || *CHAR(asChar(transp)) == 'B'),
709                                          chb->xtype, &c);                  /* transp_ans = */ (*CHAR(asChar(transp)) == 'c' || *CHAR(asChar(transp)) == 'B'));
710      SEXP dn = PROTECT(allocVector(VECSXP, 2));  }
double one[] = {1,0}, zero[] = {0,0};
R_CheckStack();
711
712      cholmod_sdmult(cha, 1, one, zero, chb, chc, &c);  SEXP Csparse_dense_crossprod(SEXP a, SEXP b, SEXP transp)
713      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */  {
714                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 1)));      return
715      SET_VECTOR_ELT(dn, 1,          Csp_dense_products(a, b,
716                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));                  /* transp_a = */ TRUE,
717      UNPROTECT(2);                  /* transp_b   = */ (*CHAR(asChar(transp)) == '2' || *CHAR(asChar(transp)) == 'B'),
718      return chm_dense_to_SEXP(chc, 1, 0, dn);                  /* transp_ans = */ (*CHAR(asChar(transp)) == 'c' || *CHAR(asChar(transp)) == 'B'));
719  }  }
720
721  /* Computes   x'x  or  x x' -- *also* for Tsparse (triplet = TRUE)
722     see Csparse_Csparse_crossprod above for  x'y and x y' */  /** @brief Computes   x'x  or  x x' -- *also* for Tsparse (triplet = TRUE)
723  SEXP Csparse_crossprod(SEXP x, SEXP trans, SEXP triplet)      see Csparse_Csparse_crossprod above for  x'y and x y'
724  {  */
725      int trip = asLogical(triplet),  SEXP Csparse_crossprod(SEXP x, SEXP trans, SEXP triplet, SEXP bool_arith)
726          tr   = asLogical(trans); /* gets reversed because _aat is tcrossprod */  {
727      CHM_TR cht = trip ? AS_CHM_TR(x) : (CHM_TR) NULL;      int tripl = asLogical(triplet),
728      CHM_SP chcp, chxt,          tr   = asLogical(trans), /* gets reversed because _aat is tcrossprod */
729          chx = (trip ?          do_bool = asLogical(bool_arith); // TRUE / NA / FALSE
730    #ifdef AS_CHM_DIAGU2N_FIXED_FINALLY
731        CHM_TR cht = tripl ? AS_CHM_TR(x) : (CHM_TR) NULL;  int nprot = 1;
732    #else /* workaround needed:*/
733        SEXP xx = PROTECT(Tsparse_diagU2N(x));
734        CHM_TR cht = tripl ? AS_CHM_TR__(xx) : (CHM_TR) NULL; int nprot = 2;
735    #endif
736        CHM_SP chcp, chxt, chxc,
737            chx = (tripl ?
738                 cholmod_triplet_to_sparse(cht, cht->nnz, &c) :                 cholmod_triplet_to_sparse(cht, cht->nnz, &c) :
739                 AS_CHM_SP(x));                 AS_CHM_SP(x));
740      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2));
741      R_CheckStack();      R_CheckStack();
742        Rboolean
743            x_is_n = (chx->xtype == CHOLMOD_PATTERN),
744            x_is_sym = chx->stype != 0,
745            force_num = (do_bool == FALSE);
746
747        if(x_is_n && force_num) {
748            // coerce 'x' to  double
749            SEXP dx = PROTECT(nz2Csparse(x, x_double)); nprot++;
750            chx = AS_CHM_SP(dx);
751            R_CheckStack();
752        }
753        else if(do_bool == TRUE && !x_is_n) { // Want boolean arithmetic; need patter[n]
754            // coerce 'x' to pattern
755            static const char *valid_tri[] = { MATRIX_VALID_tri_Csparse, "" };
756            SEXP dx = PROTECT(Csparse2nz(x, /* tri = */
757                                         R_check_class_etc(x, valid_tri) >= 0)); nprot++;
758            chx = AS_CHM_SP(dx);
759            R_CheckStack();
760        }
761
762      if (!tr) chxt = cholmod_transpose(chx, chx->xtype, &c);      if (!tr) chxt = cholmod_transpose(chx, chx->xtype, &c);
763      chcp = cholmod_aat((!tr) ? chxt : chx, (int *) NULL, 0, chx->xtype, &c);
764        if (x_is_sym) // cholmod_aat() does not like symmetric
765            chxc = cholmod_copy(tr ? chx : chxt, /* stype: */ 0,
766                                chx->xtype, &c);
767        // CHOLMOD/Core/cholmod_aat.c :
768        chcp = cholmod_aat(x_is_sym ? chxc : (tr ? chx : chxt),
769                           (int *) NULL, 0, /* mode: */ chx->xtype, &c);
770      if(!chcp) {      if(!chcp) {
771          UNPROTECT(1);          UNPROTECT(1);
772          error(_("Csparse_crossprod(): error return from cholmod_aat()"));          error(_("Csparse_crossprod(): error return from cholmod_aat()"));
773      }      }
774      cholmod_band_inplace(0, chcp->ncol, chcp->xtype, chcp, &c);      cholmod_band_inplace(0, chcp->ncol, chcp->xtype, chcp, &c);
775      chcp->stype = 1;      chcp->stype = 1; // symmetric
776      if (trip) cholmod_free_sparse(&chx, &c);      if (tripl) cholmod_free_sparse(&chx, &c);
777      if (!tr) cholmod_free_sparse(&chxt, &c);      if (!tr) cholmod_free_sparse(&chxt, &c);
778      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
779                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),
780                                          (tr) ? 0 : 1)));                                          (tr) ? 0 : 1)));
781      SET_VECTOR_ELT(dn, 1, duplicate(VECTOR_ELT(dn, 0)));      SET_VECTOR_ELT(dn, 1, duplicate(VECTOR_ELT(dn, 0)));
782      UNPROTECT(1);      UNPROTECT(nprot);
783        // FIXME: uploT for symmetric ?
784      return chm_sparse_to_SEXP(chcp, 1, 0, 0, "", dn);      return chm_sparse_to_SEXP(chcp, 1, 0, 0, "", dn);
785  }  }
786
787    /** @brief Csparse_drop(x, tol):  drop entries with absolute value < tol, i.e,
788     *  at least all "explicit" zeros. */
789  SEXP Csparse_drop(SEXP x, SEXP tol)  SEXP Csparse_drop(SEXP x, SEXP tol)
790  {  {
791      const char *cl = class_P(x);      const char *cl = class_P(x);
792      /* dtCMatrix, etc; [1] = the second character =?= 't' for triangular */      /* dtCMatrix, etc; [1] = the second character =?= 't' for triangular */
793      int tr = (cl[1] == 't');      int tr = (cl[1] == 't'); // FIXME - rather  R_check_class_etc(..)
794      CHM_SP chx = AS_CHM_SP__(x);      CHM_SP chx = AS_CHM_SP__(x);
795      CHM_SP ans = cholmod_copy(chx, chx->stype, chx->xtype, &c);      CHM_SP ans = cholmod_copy(chx, chx->stype, chx->xtype, &c);
796      double dtol = asReal(tol);      double dtol = asReal(tol);
# Line 396  Line 805
805                                GET_SLOT(x, Matrix_DimNamesSym));                                GET_SLOT(x, Matrix_DimNamesSym));
806  }  }
807
808    /** @brief Horizontal Concatenation -  cbind( <Csparse>,  <Csparse>)
809     */
810  SEXP Csparse_horzcat(SEXP x, SEXP y)  SEXP Csparse_horzcat(SEXP x, SEXP y)
811  {  {
812      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);  #define CSPARSE_CAT(_KIND_)                                             \
813      int Rkind = 0; /* only for "d" - FIXME */      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);                  \
814      R_CheckStack();      R_CheckStack();                                                     \
815        int Rk_x = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : x_pattern, \
816            Rk_y = (chy->xtype != CHOLMOD_PATTERN) ? Real_kind(y) : x_pattern, Rkind; \
817        if(Rk_x == x_pattern || Rk_y == x_pattern) { /* at least one of them is patter"n" */ \
818            if(Rk_x == x_pattern && Rk_y == x_pattern) { /* fine */         \
819            } else { /* only one is a patter"n"                             \
820                      * "Bug" in cholmod_horzcat()/vertcat():               \
821                      * returns patter"n" matrix if one of them is */       \
822                Rboolean ok;                                                \
823                if(Rk_x == x_pattern) {                                     \
824                    ok = chm_MOD_xtype(CHOLMOD_REAL, chx, &c); Rk_x = 0;    \
825                } else if(Rk_y == x_pattern) {                              \
826                    ok = chm_MOD_xtype(CHOLMOD_REAL, chy, &c); Rk_y = 0;    \
827                } else                                                      \
828                    error(_("Impossible Rk_x/Rk_y in Csparse_%s(), please report"), _KIND_); \
829                if(!ok)                                                     \
830                    error(_("chm_MOD_xtype() was not successful in Csparse_%s(), please report"), \
831                          _KIND_);                                          \
832            }                                                               \
833        }                                                                   \
834        Rkind = /* logical if both x and y are */ (Rk_x == 1 && Rk_y == 1) ? 1 : 0
835
836        CSPARSE_CAT("horzcat");
837        // TODO: currently drops dimnames - and we fix at R level;
838
/* FIXME: currently drops dimnames */
839      return chm_sparse_to_SEXP(cholmod_horzcat(chx, chy, 1, &c),      return chm_sparse_to_SEXP(cholmod_horzcat(chx, chy, 1, &c),
840                                1, 0, Rkind, "", R_NilValue);                                1, 0, Rkind, "", R_NilValue);
841  }  }
842
843    /** @brief Vertical Concatenation -  rbind( <Csparse>,  <Csparse>)
844     */
845  SEXP Csparse_vertcat(SEXP x, SEXP y)  SEXP Csparse_vertcat(SEXP x, SEXP y)
846  {  {
847      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);      CSPARSE_CAT("vertcat");
848      int Rkind = 0; /* only for "d" - FIXME */      // TODO: currently drops dimnames - and we fix at R level;
R_CheckStack();
849
/* FIXME: currently drops dimnames */
850      return chm_sparse_to_SEXP(cholmod_vertcat(chx, chy, 1, &c),      return chm_sparse_to_SEXP(cholmod_vertcat(chx, chy, 1, &c),
851                                1, 0, Rkind, "", R_NilValue);                                1, 0, Rkind, "", R_NilValue);
852  }  }
# Line 464  Line 897
897      }      }
898      else { /* triangular with diag='N'): now drop the diagonal */      else { /* triangular with diag='N'): now drop the diagonal */
899          /* duplicate, since chx will be modified: */          /* duplicate, since chx will be modified: */
900          CHM_SP chx = AS_CHM_SP__(duplicate(x));          SEXP xx = PROTECT(duplicate(x));
901            CHM_SP chx = AS_CHM_SP__(xx);
902          int uploT = (*uplo_P(x) == 'U') ? 1 : -1,          int uploT = (*uplo_P(x) == 'U') ? 1 : -1,
903              Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;              Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
904          R_CheckStack();          R_CheckStack();
905
906          chm_diagN2U(chx, uploT, /* do_realloc */ FALSE);          chm_diagN2U(chx, uploT, /* do_realloc */ FALSE);
907
908          return chm_sparse_to_SEXP(chx, /*dofree*/ 0/* or 1 ?? */,          SEXP ans = chm_sparse_to_SEXP(chx, /*dofree*/ 0/* or 1 ?? */,
909                                    uploT, Rkind, "U",                                    uploT, Rkind, "U",
910                                    GET_SLOT(x, Matrix_DimNamesSym));                                    GET_SLOT(x, Matrix_DimNamesSym));
911            UNPROTECT(1);// only now !
912            return ans;
913      }      }
914  }  }
915
916    /**
917     * Indexing aka subsetting : Compute  x[i,j], also for vectors i and j
918     * Working via CHOLMOD_submatrix, see ./CHOLMOD/MatrixOps/cholmod_submatrix.c
919     * @param x CsparseMatrix
920     * @param i row     indices (0-origin), or NULL (R, not C)
921     * @param j columns indices (0-origin), or NULL
922     *
923     * @return x[i,j]  still CsparseMatrix --- currently, this loses dimnames
924     */
925  SEXP Csparse_submatrix(SEXP x, SEXP i, SEXP j)  SEXP Csparse_submatrix(SEXP x, SEXP i, SEXP j)
926  {  {
927      CHM_SP chx = AS_CHM_SP__(x);      CHM_SP chx = AS_CHM_SP(x); /* << does diagU2N() when needed */
928      int rsize = (isNull(i)) ? -1 : LENGTH(i),      int rsize = (isNull(i)) ? -1 : LENGTH(i),
929          csize = (isNull(j)) ? -1 : LENGTH(j);          csize = (isNull(j)) ? -1 : LENGTH(j);
930      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
# Line 490  Line 935
935      if (csize >= 0 && !isInteger(j))      if (csize >= 0 && !isInteger(j))
936          error(_("Index j must be NULL or integer"));          error(_("Index j must be NULL or integer"));
937
938      return chm_sparse_to_SEXP(cholmod_submatrix(chx, INTEGER(i), rsize,      /* Must treat 'NA's in i[] and j[] here -- they are *not* treated by Cholmod!
939                                                  INTEGER(j), csize,       * haveNA := ...
940                                                  TRUE, TRUE, &c),         if(haveNA) {
941                                1, 0, Rkind, "",           a. i = removeNA(i); j =removeNA(j), and remember where they were
942                                /* FIXME: drops dimnames */ R_NilValue);           b. ans = CHM_SUB(.., i, j)
943             c. add NA rows and/or columns to 'ans' according to
944                place of NA's in i and/or j.
945           } else {
946             ans = CHM_SUB(.....)  // == current code
947  }  }
948         */
949    #define CHM_SUB(_M_, _i_, _j_)                                  \
950        cholmod_submatrix(_M_,                                      \
951                          (rsize < 0) ? NULL : INTEGER(_i_), rsize, \
952                          (csize < 0) ? NULL : INTEGER(_j_), csize, \
953                          TRUE, TRUE, &c)
954        CHM_SP ans;
955        if (!chx->stype) {/* non-symmetric Matrix */
956            ans = CHM_SUB(chx, i, j);
957        }
958        else { /* symmetric : "dsCMatrix";
959                  currently, cholmod_submatrix() only accepts "generalMatrix" */
960            CHM_SP tmp = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);
961            ans = CHM_SUB(tmp, i, j);
962            cholmod_free_sparse(&tmp, &c);
963        }
964
965        // "FIXME": currently dropping dimnames, and adding them afterwards in R :
966        /* // dimnames: */
967        /* SEXP x_dns = GET_SLOT(x, Matrix_DimNamesSym), */
968        /*  dn = PROTECT(allocVector(VECSXP, 2)); */
969        return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "", /* dimnames: */ R_NilValue);
970    }
971    #undef CHM_SUB
972
973    #define _d_Csp_
974    #include "t_Csparse_subassign.c"
975
976    #define _l_Csp_
977    #include "t_Csparse_subassign.c"
978
979    #define _i_Csp_
980    #include "t_Csparse_subassign.c"
981
982    #define _n_Csp_
983    #include "t_Csparse_subassign.c"
984
985    #define _z_Csp_
986    #include "t_Csparse_subassign.c"
987
988
989
990  SEXP Csparse_MatrixMarket(SEXP x, SEXP fname)  SEXP Csparse_MatrixMarket(SEXP x, SEXP fname)
991  {  {
# Line 524  Line 1014
1014   *   *
1015   * @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
1016   */   */
1017  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,
1018  /*                                ^^^^^^ FIXME[Generalize] to int / ... */  /*                                ^^^^^^ FIXME[Generalize] to int / ... */
1019                     SEXP resultKind)
1020  {  {
1021      const char* res_ch = CHAR(STRING_ELT(resultKind,0));      const char* res_ch = CHAR(STRING_ELT(resultKind,0));
1022      enum diag_kind { diag, diag_backpermuted, trace, prod, sum_log      enum diag_kind { diag, diag_backpermuted, trace, prod, sum_log, min, max, range
1023      } res_kind = ((!strcmp(res_ch, "trace")) ? trace :      } res_kind = ((!strcmp(res_ch, "trace")) ? trace :
1024                    ((!strcmp(res_ch, "sumLog")) ? sum_log :                    ((!strcmp(res_ch, "sumLog")) ? sum_log :
1025                     ((!strcmp(res_ch, "prod")) ? prod :                     ((!strcmp(res_ch, "prod")) ? prod :
1026                        ((!strcmp(res_ch, "min")) ? min :
1027                         ((!strcmp(res_ch, "max")) ? max :
1028                          ((!strcmp(res_ch, "range")) ? range :
1029                      ((!strcmp(res_ch, "diag")) ? diag :                      ((!strcmp(res_ch, "diag")) ? diag :
1030                       ((!strcmp(res_ch, "diagBack")) ? diag_backpermuted :                       ((!strcmp(res_ch, "diagBack")) ? diag_backpermuted :
1031                        -1)))));                           -1))))))));
1032      int i, n_x, i_from = 0;      int i, n_x, i_from;
1033      SEXP ans = PROTECT(allocVector(REALSXP,      SEXP ans = PROTECT(allocVector(REALSXP,
1034  /*                                 ^^^^  FIXME[Generalize] */  /*                                 ^^^^  FIXME[Generalize] */
1035                                     (res_kind == diag ||                                     (res_kind == diag ||
1036                                      res_kind == diag_backpermuted) ? n : 1));                                      res_kind == diag_backpermuted) ? n :
1037                                       (res_kind == range ? 2 : 1)));
1038      double *v = REAL(ans);      double *v = REAL(ans);
1039  /*  ^^^^^^      ^^^^  FIXME[Generalize] */  /*  ^^^^^^      ^^^^  FIXME[Generalize] */
1040
1041        i_from = (is_U ? -1 : 0);
1042
1043  #define for_DIAG(v_ASSIGN)                                              \  #define for_DIAG(v_ASSIGN)                                              \
1044      for(i = 0; i < n; i++, i_from += n_x) {                             \      for(i = 0; i < n; i++) {                                    \
1045          /* looking at i-th column */                                    \          /* looking at i-th column */                                    \
1046          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 */ \
1047            if( is_U) i_from += n_x;                                \
1048          v_ASSIGN;                                                       \          v_ASSIGN;                                                       \
1049            if(!is_U) i_from += n_x;                                \
1050      }      }
1051
1052      /* NOTA BENE: we assume  -- uplo = "L" i.e. lower triangular matrix      /* NOTA BENE: we assume  -- uplo = "L" i.e. lower triangular matrix
1053       *            for uplo = "U" (makes sense with a "dtCMatrix" !),       *            for uplo = "U" (makes sense with a "dtCMatrix" !),
1054       *            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],
1055       *            where nx = (x_p[i+1] - x_p[i])       *            where n_x = (x_p[i+1] - x_p[i])
1056       */       */
1057
1058      switch(res_kind) {      switch(res_kind) {
1059      case trace:      case trace: // = sum
1060          v[0] = 0.;          v[0] = 0.;
1061          for_DIAG(v[0] += x_x[i_from]);          for_DIAG(v[0] += x_x[i_from]);
1062          break;          break;
# Line 572  Line 1071
1071          for_DIAG(v[0] *= x_x[i_from]);          for_DIAG(v[0] *= x_x[i_from]);
1072          break;          break;
1073
1074        case min:
1075            v[0] = R_PosInf;
1076            for_DIAG(if(v[0] > x_x[i_from]) v[0] = x_x[i_from]);
1077            break;
1078
1079        case max:
1080            v[0] = R_NegInf;
1081            for_DIAG(if(v[0] < x_x[i_from]) v[0] = x_x[i_from]);
1082            break;
1083
1084        case range:
1085            v[0] = R_PosInf;
1086            v[1] = R_NegInf;
1087            for_DIAG(if(v[0] > x_x[i_from]) v[0] = x_x[i_from];
1088                     if(v[1] < x_x[i_from]) v[1] = x_x[i_from]);
1089            break;
1090
1091      case diag:      case diag:
1092          for_DIAG(v[i] = x_x[i_from]);          for_DIAG(v[i] = x_x[i_from]);
1093          break;          break;
# Line 579  Line 1095
1095      case diag_backpermuted:      case diag_backpermuted:
1096          for_DIAG(v[i] = x_x[i_from]);          for_DIAG(v[i] = x_x[i_from]);
1097
1098          warning(_("resultKind = 'diagBack' (back-permuted) is experimental"));          warning(_("%s = '%s' (back-permuted) is experimental"),
1099                    "resultKind", "diagBack");
1100          /* now back_permute : */          /* now back_permute : */
1101          for(i = 0; i < n; i++) {          for(i = 0; i < n; i++) {
1102              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 1105
1105          break;          break;
1106
1107      default: /* -1 from above */      default: /* -1 from above */
1108          error("diag_tC(): invalid 'resultKind'");          error(_("diag_tC(): invalid 'resultKind'"));
1109          /* Wall: */ ans = R_NilValue; v = REAL(ans);          /* Wall: */ ans = R_NilValue; v = REAL(ans);
1110      }      }
1111
# Line 600  Line 1117
1117   * Extract the diagonal entries from *triangular* Csparse matrix  __or__ a   * Extract the diagonal entries from *triangular* Csparse matrix  __or__ a
1118   * cholmod_sparse factor (LDL = TRUE).   * cholmod_sparse factor (LDL = TRUE).
1119   *   *
1120     * @param obj -- now a cholmod_sparse factor or a dtCMatrix
1121   * @param pslot  'p' (column pointer)   slot of Csparse matrix/factor   * @param pslot  'p' (column pointer)   slot of Csparse matrix/factor
1122   * @param xslot  'x' (non-zero entries) slot of Csparse matrix/factor   * @param xslot  'x' (non-zero entries) slot of Csparse matrix/factor
1123   * @param perm_slot  'perm' (= permutation vector) slot of corresponding CHMfactor;   * @param perm_slot  'perm' (= permutation vector) slot of corresponding CHMfactor;
# Line 608  Line 1126
1126   *   *
1127   * @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
1128   */   */
1129  SEXP diag_tC(SEXP pslot, SEXP xslot, SEXP perm_slot, SEXP resultKind)  SEXP diag_tC(SEXP obj, SEXP resultKind)
1130  {  {
1131
1132        SEXP
1133            pslot = GET_SLOT(obj, Matrix_pSym),
1134            xslot = GET_SLOT(obj, Matrix_xSym);
1135        Rboolean is_U = (R_has_slot(obj, Matrix_uploSym) &&
1136                         *CHAR(asChar(GET_SLOT(obj, Matrix_uploSym))) == 'U');
1137      int n = length(pslot) - 1, /* n = ncol(.) = nrow(.) */      int n = length(pslot) - 1, /* n = ncol(.) = nrow(.) */
1138          *x_p  = INTEGER(pslot),          *x_p  = INTEGER(pslot), pp = -1, *perm;
*perm = INTEGER(perm_slot);
1139      double *x_x = REAL(xslot);      double *x_x = REAL(xslot);
1140  /*  ^^^^^^        ^^^^ FIXME[Generalize] to INTEGER(.) / LOGICAL(.) / ... xslot !*/  /*  ^^^^^^        ^^^^ FIXME[Generalize] to INTEGER(.) / LOGICAL(.) / ... xslot !*/
1141
1142      return diag_tC_ptr(n, x_p, x_x, perm, resultKind);      if(R_has_slot(obj, Matrix_permSym))
1143            perm = INTEGER(GET_SLOT(obj, Matrix_permSym));
1144        else perm = &pp;
1145
1146        return diag_tC_ptr(n, x_p, x_x, is_U, perm, resultKind);
1147    }
1148
1149
1150    /**
1151     * Create a Csparse matrix object from indices and/or pointers.
1152     *
1153     * @param cls name of actual class of object to create
1154     * @param i optional integer vector of length nnz of row indices
1155     * @param j optional integer vector of length nnz of column indices
1156     * @param p optional integer vector of length np of row or column pointers
1157     * @param np length of integer vector p.  Must be zero if p == (int*)NULL
1158     * @param x optional vector of values
1159     * @param nnz length of vectors i, j and/or x, whichever is to be used
1160     * @param dims optional integer vector of length 2 to be used as
1161     *     dimensions.  If dims == (int*)NULL then the maximum row and column
1162     *     index are used as the dimensions.
1163     * @param dimnames optional list of length 2 to be used as dimnames
1164     * @param index1 indicator of 1-based indices
1165     *
1166     * @return an SEXP of class cls inheriting from CsparseMatrix.
1167     */
1168    SEXP create_Csparse(char* cls, int* i, int* j, int* p, int np,
1169                        void* x, int nnz, int* dims, SEXP dimnames,
1170                        int index1)
1171    {
1172        SEXP ans;
1173        int *ij = (int*)NULL, *tri, *trj, nrow = -1, ncol = -1;
1174        int xtype = -1;             /* -Wall */
1175        CHM_TR T;
1176        CHM_SP A;
1177
1178        if (np < 0 || nnz < 0)
1179            error(_("negative vector lengths not allowed: np = %d, nnz = %d"),
1180                  np, nnz);
1181        int mi = (i == (int*)NULL), // := missing 'i'
1182            mj = (j == (int*)NULL), // := missing 'j'
1183            mp = (p == (int*)NULL); // := missing 'p'
1184        if ((mi + mj + mp) != 1)
1185            error(_("exactly 1 of 'i', 'j' or 'p' must be NULL"));
1186        if (mp) {
1187            if (np) error(_("np = %d, must be zero when p is NULL"), np);
1188        } else {
1189            if (np) {               /* Expand p to form i or j */
1190                if (!(p[0])) error(_("p[0] = %d, should be zero"), p[0]);
1191                for (int ii = 0; ii < np; ii++)
1192                    if (p[ii] > p[ii + 1])
1193                        error(_("p must be non-decreasing"));
1194                if (p[np] != nnz)
1195                    error("p[np] = %d != nnz = %d", p[np], nnz);
1196                ij = Calloc(nnz, int);
1197                if (mi) {
1198                    i = ij;
1199                    nrow = np;
1200                } else {
1201                    j = ij;
1202                    ncol = np;
1203                }
1204                /* Expand p to 0-based indices */
1205                for (int ii = 0; ii < np; ii++)
1206                    for (int jj = p[ii]; jj < p[ii + 1]; jj++) ij[jj] = ii;
1207            } else {
1208                if (nnz)
1209                    error(_("Inconsistent dimensions: np = 0 and nnz = %d"),
1210                          nnz);
1211            }
1212        }
1213        /* calculate nrow and ncol */
1214        if (nrow < 0) {
1215            for (int ii = 0; ii < nnz; ii++) {
1216                int i1 = i[ii] + (index1 ? 0 : 1); /* 1-based index */
1217                if (i1 < 1) error(_("invalid row index at position %d"), ii);
1218                if (i1 > nrow) nrow = i1;
1219            }
1220        }
1221        if (ncol < 0) {
1222            for (int jj = 0; jj < nnz; jj++) {
1223                int j1 = j[jj] + (index1 ? 0 : 1);
1224                if (j1 < 1) error(_("invalid column index at position %d"), jj);
1225                if (j1 > ncol) ncol = j1;
1226            }
1227        }
1228        if (dims != (int*)NULL) {
1229            if (dims[0] > nrow) nrow = dims[0];
1230            if (dims[1] > ncol) ncol = dims[1];
1231        }
1232        /* check the class name */
1233        if (strlen(cls) != 8)
1234            error(_("strlen of cls argument = %d, should be 8"), strlen(cls));
1235        if (strcmp(cls + 2, "CMatrix"))
1236            error(_("cls = \"%s\" does not end in \"CMatrix\""), cls);
1237        switch(cls[0]) {
1238        case 'd':
1239        case 'l':
1240            xtype = CHOLMOD_REAL;
1241        break;
1242        case 'n':
1243            xtype = CHOLMOD_PATTERN;
1244            break;
1245        default:
1246            error(_("cls = \"%s\" must begin with 'd', 'l' or 'n'"), cls);
1247        }
1248        if (cls[1] != 'g')
1249            error(_("Only 'g'eneral sparse matrix types allowed"));
1250        /* allocate and populate the triplet */
1251        T = cholmod_allocate_triplet((size_t)nrow, (size_t)ncol, (size_t)nnz, 0,
1252                                     xtype, &c);
1253        T->x = x;
1254        tri = (int*)T->i;
1255        trj = (int*)T->j;
1256        for (int ii = 0; ii < nnz; ii++) {
1257            tri[ii] = i[ii] - ((!mi && index1) ? 1 : 0);
1258            trj[ii] = j[ii] - ((!mj && index1) ? 1 : 0);
1259        }
1260        /* create the cholmod_sparse structure */
1261        A = cholmod_triplet_to_sparse(T, nnz, &c);
1262        cholmod_free_triplet(&T, &c);
1263        /* copy the information to the SEXP */
1264        ans = PROTECT(NEW_OBJECT_OF_CLASS(cls));
1265    // FIXME: This has been copied from chm_sparse_to_SEXP in  chm_common.c
1266        /* allocate and copy common slots */
1267        nnz = cholmod_nnz(A, &c);
1268        dims = INTEGER(ALLOC_SLOT(ans, Matrix_DimSym, INTSXP, 2));
1269        dims[0] = A->nrow; dims[1] = A->ncol;
1270        Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_pSym, INTSXP, A->ncol + 1)), (int*)A->p, A->ncol + 1);
1271        Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_iSym, INTSXP, nnz)), (int*)A->i, nnz);
1272        switch(cls[0]) {
1273        case 'd':
1274            Memcpy(REAL(ALLOC_SLOT(ans, Matrix_xSym, REALSXP, nnz)), (double*)A->x, nnz);
1275            break;
1276        case 'l':
1277            error(_("code not yet written for cls = \"lgCMatrix\""));
1278        }
1279    /* FIXME: dimnames are *NOT* put there yet (if non-NULL) */
1280        cholmod_free_sparse(&A, &c);
1281        UNPROTECT(1);
1282        return ans;
1283    }
1284
1285    /**
1286     * Create a Csparse matrix object from a traditional R matrix
1287     *
1288     * @param x   traditional R matrix (numeric, logical, ...)
1289     * @param cls class (a string)
1290     *
1291     * @return an SEXP of a class inheriting from CsparseMatrix.
1292     */
1293    SEXP matrix_to_Csparse(SEXP x, SEXP cls)
1294    {
1295        if (!isMatrix(x))
1296            error(_("%s must be (traditional R) matrix"), "'x'");
1297        SEXP d_x  = getAttrib(x, R_DimSymbol),
1298            dn_x  = getAttrib(x, R_DimNamesSymbol);
1299        int nr = INTEGER(d_x)[0],
1300            nc = INTEGER(d_x)[1];
1301
1302        if (!(isString(cls) && LENGTH(cls) == 1))
1303            error(_("%s must be character string"), "'cls'");
1304        R_xlen_t ii, n = XLENGTH(x);
1305        int xtype = -1;
1306        if (n != ((R_xlen_t) nr) * nc)
1307            error(_("nrow * ncol = %d * %d must equal length(x) = %ld"), nr, nc, n);
1308
1309        const char *ccls = CHAR(STRING_ELT(cls, 0));
1310        if (strlen(ccls) != 9)
1311            error(_("strlen of cls argument = %d, should be 9"), strlen(ccls));
1312        if (strcmp(ccls + 2, "CMatrix"))
1313            error(_("cls = \"%s\" does not end in \"CMatrix\""), ccls);
1314        switch(ccls[0]) {
1315        case 'd':
1316        case 'l':
1317            xtype = CHOLMOD_REAL;
1318        break;
1319        case 'n':
1320            xtype = CHOLMOD_PATTERN;
1321            break;
1322        default:
1323            error(_("cls = \"%s\" must begin with 'd', 'l' or 'n' for now"), ccls);
1324        }
1325        /* if (ccls[1] != 'g') */
1326        /*  error(_("Only 'g'eneral sparse matrix types allowed")); */
1327
1328        SEXP ans = PROTECT(NEW_OBJECT_OF_CLASS(ccls));
1329        SET_SLOT(ans, Matrix_DimSym, d_x);
1330        SET_SLOT(ans, Matrix_DimNamesSym, (!isNull(dn_x) && LENGTH(dn_x) == 2)
1331                 ? duplicate(dn_x)
1332                 : allocVector(VECSXP, 2));
1333
1334        int nz = 0, // current number of nonzero entries
1335            nnz = imax2(256, imax2(nr,nc));/* nnz := final number of nonzero entries, yet unknown;
1337        int *rp = INTEGER(ALLOC_SLOT(ans, Matrix_pSym, INTSXP, nc + 1)),
1338            *ri = Calloc(nnz, int); // to become i slot -- of not-yet-known length nnz
1339
1340        rp[0] = 0; // always
1341
1342        switch(TYPEOF(x)) {
1343        case LGLSXP: {
1344            if(xtype == CHOLMOD_PATTERN) {
1345    #         define _PATTERN_x
1346    #         include "t_matrix_to_Csp.c"
1347            } else {
1348    #         define _LOGICAL_x
1349    #         include "t_matrix_to_Csp.c"
1350            }
1351            break;
1352        }
1353        case REALSXP: {
1354    #       define _DOUBLE_x
1355    #       include "t_matrix_to_Csp.c"
1356            break;
1357        }
1358    /* case INTSXP: we would have to use
1359            x = coerceVector(x, REALSXP));
1360       and then fall through to REALSXP case, but we must *not* modify 'x' here
1361       FIXME: use a macro or (inline?) function with argument (y), where
1362       -----  SEXP y = PROTECT(coerceVector(x, REALSXP))
1363
1364       ==> give error in INTSXP case, so caller (in R) must set  storage.mode(x) <- "double"
1365    */
1367        case INTSXP: {
1368    #       define _INTEGER_x
1369    #       include "t_matrix_to_Csp.c"
1370            break;
1371        }
1372    #endif
1374        case CPLXSXP: {
1375    #       define _COMPLEX_x
1376    #       include "t_matrix_to_Csp.c"
1377            break;
1378  }  }
1379    #endif
1380        default:
1381            error(_("%s must be a logical or double vector"), "'x'");
1382            break;
1383        }
1384
1385        Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_iSym,  INTSXP, nnz)), ri, nnz);
1386        Free(ri);
1387
1388        UNPROTECT(1);
1389        return ans;
1390    }
1391
1392
1393
1394

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