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 2299, Fri Oct 17 16:07:38 2008 UTC pkg/Matrix/src/Csparse.c revision 3147, Thu Oct 29 16:56:10 2015 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_l_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_l_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 125  Line 96
96              }              }
97      }      }
98      if (!sorted)      if (!sorted)
99          /* cannot easily use cholmod_l_sort(.) ... -> "error out" :*/          /* cannot easily use cholmod_sort(.) ... -> "error out" :*/
100          return mkString(_("slot j is not increasing inside a column"));          return mkString(_("slot j is not increasing inside a column"));
101      else if(!strictly) /* sorted, but not strictly */      else if(!strictly) /* sorted, but not strictly */
102          return mkString(_("slot j is not *strictly* increasing inside a column"));          return mkString(_("slot j is not *strictly* increasing inside a column"));
# 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_l_sparse_to_dense(chxs, &c);      CHM_DN chxd = cholmod_sparse_to_dense(chxs, &c);
154      int Rkind = (chxs->xtype == CHOLMOD_PATTERN)? -1 : Real_kind(x);      int Rkind = (chxs->xtype == CHOLMOD_PATTERN)? -1 : Real_kind(x);
R_CheckStack();
155
156      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),
157                                     /* transp: */ FALSE);
158        // -> a [dln]geMatrix
159        if(is_sym) { // ==> want  [dln]syMatrix
160            const char cl1 = class_P(ans)[0];
161            PROTECT(ans);
162            SEXP aa = PROTECT(NEW_OBJECT(MAKE_CLASS((cl1 == 'd') ? "dsyMatrix" :
163                                                    ((cl1 == 'l') ? "lsyMatrix" : "nsyMatrix"))));
164            // No need to duplicate() as slots of ans are freshly allocated and ans will not be used
165            SET_SLOT(aa, Matrix_xSym,       GET_SLOT(ans, Matrix_xSym));
166            SET_SLOT(aa, Matrix_DimSym,     GET_SLOT(ans, Matrix_DimSym));
167            SET_SLOT(aa, Matrix_DimNamesSym,GET_SLOT(ans, Matrix_DimNamesSym));
168            SET_SLOT(aa, Matrix_uploSym, mkString((chxs->stype > 0) ? "U" : "L"));
169            UNPROTECT(2);
170            return aa;
171        }
172        else if(is_tri) { // ==> want  [dln]trMatrix
173            const char cl1 = class_P(ans)[0];
174            PROTECT(ans);
175            SEXP aa = PROTECT(NEW_OBJECT(MAKE_CLASS((cl1 == 'd') ? "dtrMatrix" :
176                                                    ((cl1 == 'l') ? "ltrMatrix" : "ntrMatrix"))));
177            // No need to duplicate() as slots of ans are freshly allocated and ans will not be used
178            SET_SLOT(aa, Matrix_xSym,       GET_SLOT(ans, Matrix_xSym));
179            SET_SLOT(aa, Matrix_DimSym,     GET_SLOT(ans, Matrix_DimSym));
180            SET_SLOT(aa, Matrix_DimNamesSym,GET_SLOT(ans, Matrix_DimNamesSym));
181            slot_dup(aa, x, Matrix_uploSym);
182            /* already by NEW_OBJECT(..) above:
183               SET_SLOT(aa, Matrix_diagSym, mkString("N")); */
184            UNPROTECT(2);
185            return aa;
186        }
187        else
188            return ans;
189  }  }
190
191  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?
192    SEXP Csparse2nz(SEXP x, Rboolean tri)
193  {  {
194      CHM_SP chxs = AS_CHM_SP__(x);      CHM_SP chxs = AS_CHM_SP__(x);
195      CHM_SP chxcp = cholmod_l_copy(chxs, chxs->stype, CHOLMOD_PATTERN, &c);      CHM_SP chxcp = cholmod_copy(chxs, chxs->stype, CHOLMOD_PATTERN, &c);
int tr = asLogical(tri);
196      R_CheckStack();      R_CheckStack();
197
198      return chm_sparse_to_SEXP(chxcp, 1/*do_free*/,      return chm_sparse_to_SEXP(chxcp, 1/*do_free*/,
199                                tr ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,                                tri ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,
200                                0, tr ? diag_P(x) : "",                                /* Rkind: pattern */ 0,
201                                  /* diag = */ tri ? diag_P(x) : "",
202                                GET_SLOT(x, Matrix_DimNamesSym));                                GET_SLOT(x, Matrix_DimNamesSym));
203  }  }
204    SEXP Csparse_to_nz_pattern(SEXP x, SEXP tri)
205    {
206        int tr_ = asLogical(tri);
207        if(tr_ == NA_LOGICAL) {
208            warning(_("Csparse_to_nz_pattern(x, tri = NA): 'tri' is taken as TRUE"));
209            tr_ = TRUE;
210        }
211        return Csparse2nz(x, (Rboolean) tr_);
212    }
213
214    // n.CMatrix --> [dli].CMatrix  (not going through CHM!)
215    SEXP nz_pattern_to_Csparse(SEXP x, SEXP res_kind)
216    {
217        return nz2Csparse(x, asInteger(res_kind));
218    }
219
220    // n.CMatrix --> [dli].CMatrix  (not going through CHM!)
221    // NOTE: use chm_MOD_xtype(() to change type of  'cholmod_sparse' matrix
222    SEXP nz2Csparse(SEXP x, enum x_slot_kind r_kind)
223    {
224        const char *cl_x = class_P(x);
225        // quick check - if ok, fast
226        if(cl_x[0] != 'n' || cl_x[2] != 'C') {
227            // e.g. class = "A", from  setClass("A", contains = "ngCMatrix")
228            static const char *valid[] = { MATRIX_VALID_nCsparse, ""};
229            int ctype = R_check_class_etc(x, valid);
230            if(ctype < 0)
231                error(_("not a 'n.CMatrix'"));
232            else // fine : get a valid  cl_x  class_P()-like string :
233                cl_x = valid[ctype];
234        }
235        int nnz = LENGTH(GET_SLOT(x, Matrix_iSym));
236        SEXP ans;
237        char *ncl = alloca(strlen(cl_x) + 1); /* not much memory required */
238        strcpy(ncl, cl_x);
239        double *dx_x; int *ix_x;
240        ncl[0] = (r_kind == x_double ? 'd' :
241                  (r_kind == x_logical ? 'l' :
242                   /* else (for now):  r_kind == x_integer : */ 'i'));
243        PROTECT(ans = NEW_OBJECT(MAKE_CLASS(ncl)));
244        // create a correct 'x' slot:
245        switch(r_kind) {
246            int i;
247        case x_double: // 'd'
248            dx_x = REAL(ALLOC_SLOT(ans, Matrix_xSym, REALSXP, nnz));
249            for (i=0; i < nnz; i++) dx_x[i] = 1.;
250            break;
251        case x_logical: // 'l'
252            ix_x = LOGICAL(ALLOC_SLOT(ans, Matrix_xSym, LGLSXP, nnz));
253            for (i=0; i < nnz; i++) ix_x[i] = TRUE;
254            break;
255        case x_integer: // 'i'
256            ix_x = INTEGER(ALLOC_SLOT(ans, Matrix_xSym, INTSXP, nnz));
257            for (i=0; i < nnz; i++) ix_x[i] = 1;
258            break;
259
260        default:
261            error(_("nz2Csparse(): invalid/non-implemented r_kind = %d"),
262                  r_kind);
263        }
264
265  SEXP Csparse_to_matrix(SEXP x)      // now copy all other slots :
266        slot_dup(ans, x, Matrix_iSym);
267        slot_dup(ans, x, Matrix_pSym);
268        slot_dup(ans, x, Matrix_DimSym);
269        slot_dup(ans, x, Matrix_DimNamesSym);
270        if(ncl[1] != 'g') { // symmetric or triangular ...
271            slot_dup_if_has(ans, x, Matrix_uploSym);
272            slot_dup_if_has(ans, x, Matrix_diagSym);
273        }
274        UNPROTECT(1);
275        return ans;
276    }
277
278    SEXP Csparse_to_matrix(SEXP x, SEXP chk, SEXP symm)
279    {
280        int is_sym = asLogical(symm);
281        if(is_sym == NA_LOGICAL) { // find if  is(x, "symmetricMatrix") :
282            static const char *valid[] = { MATRIX_VALID_Csparse, ""};
283            int ctype = R_check_class_etc(x, valid);
284            is_sym = (ctype % 3 == 1);
285        }
286        return chm_dense_to_matrix(
287            cholmod_sparse_to_dense(AS_CHM_SP2(x, asLogical(chk)), &c),
288            1 /*do_free*/,
289            (is_sym
290             ? symmetric_DimNames(GET_SLOT(x, Matrix_DimNamesSym))
291             :                    GET_SLOT(x, Matrix_DimNamesSym)));
292    }
293
294    SEXP Csparse_to_vector(SEXP x)
295  {  {
296      return chm_dense_to_matrix(cholmod_l_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));
297  }  }
298
299  SEXP Csparse_to_Tsparse(SEXP x, SEXP tri)  SEXP Csparse_to_Tsparse(SEXP x, SEXP tri)
300  {  {
301      CHM_SP chxs = AS_CHM_SP__(x);      CHM_SP chxs = AS_CHM_SP__(x);
302      CHM_TR chxt = cholmod_l_sparse_to_triplet(chxs, &c);      CHM_TR chxt = cholmod_sparse_to_triplet(chxs, &c);
303      int tr = asLogical(tri);      int tr = asLogical(tri);
304      int Rkind = (chxs->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chxs->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
305      R_CheckStack();      R_CheckStack();
# Line 183  Line 310
310                                 GET_SLOT(x, Matrix_DimNamesSym));                                 GET_SLOT(x, Matrix_DimNamesSym));
311  }  }
312
313  /* this used to be called  sCMatrix_to_gCMatrix(..)   [in ./dsCMatrix.c ]: */  SEXP Csparse_to_tCsparse(SEXP x, SEXP uplo, SEXP diag)
314    {
315        CHM_SP chxs = AS_CHM_SP__(x);
316        int Rkind = (chxs->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
317        R_CheckStack();
318        return chm_sparse_to_SEXP(chxs, /* dofree = */ 0,
319                                  /* uploT = */ (*CHAR(asChar(uplo)) == 'U')? 1: -1,
320                                   Rkind, /* diag = */ CHAR(STRING_ELT(diag, 0)),
321                                   GET_SLOT(x, Matrix_DimNamesSym));
322    }
323
324    SEXP Csparse_to_tTsparse(SEXP x, SEXP uplo, SEXP diag)
325    {
326        CHM_SP chxs = AS_CHM_SP__(x);
327        CHM_TR chxt = cholmod_sparse_to_triplet(chxs, &c);
328        int Rkind = (chxs->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
329        R_CheckStack();
330        return chm_triplet_to_SEXP(chxt, 1,
331                                  /* uploT = */ (*CHAR(asChar(uplo)) == 'U')? 1: -1,
332                                   Rkind, /* diag = */ CHAR(STRING_ELT(diag, 0)),
333                                   GET_SLOT(x, Matrix_DimNamesSym));
334    }
335
336
337  SEXP Csparse_symmetric_to_general(SEXP x)  SEXP Csparse_symmetric_to_general(SEXP x)
338  {  {
339      CHM_SP chx = AS_CHM_SP__(x), chgx;      CHM_SP chx = AS_CHM_SP__(x), chgx;
# Line 192  Line 342
342
343      if (!(chx->stype))      if (!(chx->stype))
344          error(_("Nonsymmetric matrix in Csparse_symmetric_to_general"));          error(_("Nonsymmetric matrix in Csparse_symmetric_to_general"));
345      chgx = cholmod_l_copy(chx, /* stype: */ 0, chx->xtype, &c);      chgx = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);
346      /* xtype: pattern, "real", complex or .. */      /* xtype: pattern, "real", complex or .. */
347      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",
348                                GET_SLOT(x, Matrix_DimNamesSym));                                symmetric_DimNames(GET_SLOT(x, Matrix_DimNamesSym)));
349  }  }
350
351  SEXP Csparse_general_to_symmetric(SEXP x, SEXP uplo)  SEXP Csparse_general_to_symmetric(SEXP x, SEXP uplo, SEXP sym_dmns)
352  {  {
355            error(_("Csparse_general_to_symmetric(): matrix is not square!"));
356            return R_NilValue; /* -Wall */
357        }
358      CHM_SP chx = AS_CHM_SP__(x), chgx;      CHM_SP chx = AS_CHM_SP__(x), chgx;
359      int uploT = (*CHAR(STRING_ELT(uplo,0)) == 'U') ? 1 : -1;      int uploT = (*CHAR(asChar(uplo)) == 'U') ? 1 : -1;
360      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
361      R_CheckStack();      R_CheckStack();
362        chgx = cholmod_copy(chx, /* stype: */ uploT, chx->xtype, &c);
363
364      chgx = cholmod_l_copy(chx, /* stype: */ uploT, chx->xtype, &c);      SEXP dns = GET_SLOT(x, Matrix_DimNamesSym);
365        if(asLogical(sym_dmns))
366            dns = symmetric_DimNames(dns);
367        else if((!isNull(VECTOR_ELT(dns, 0)) &&
368                 !isNull(VECTOR_ELT(dns, 1))) ||
369                !isNull(getAttrib(dns, R_NamesSymbol))) {
370            /* symmetrize them if both are not NULL
371             * or names(dimnames(.)) is asymmetric : */
372            dns = PROTECT(duplicate(dns));
373            if(!equal_string_vectors(VECTOR_ELT(dns, 0),
374                                     VECTOR_ELT(dns, 1))) {
375                if(uploT == 1)
376                    SET_VECTOR_ELT(dns, 0, VECTOR_ELT(dns,1));
377                else
378                    SET_VECTOR_ELT(dns, 1, VECTOR_ELT(dns,0));
379            }
380            SEXP nms_dns = getAttrib(dns, R_NamesSymbol);
381            if(!isNull(nms_dns) &&  // names(dimnames(.)) :
382               !R_compute_identical(STRING_ELT(nms_dns, 0),
383                                    STRING_ELT(nms_dns, 1), 16)) {
384                if(uploT == 1)
385                    SET_STRING_ELT(nms_dns, 0, STRING_ELT(nms_dns,1));
386                else
387                    SET_STRING_ELT(nms_dns, 1, STRING_ELT(nms_dns,0));
388                setAttrib(dns, R_NamesSymbol, nms_dns);
389            }
390            UNPROTECT(1);
391        }
392      /* xtype: pattern, "real", complex or .. */      /* xtype: pattern, "real", complex or .. */
393      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "", dns);
GET_SLOT(x, Matrix_DimNamesSym));
394  }  }
395
396  SEXP Csparse_transpose(SEXP x, SEXP tri)  SEXP Csparse_transpose(SEXP x, SEXP tri)
# Line 217  Line 399
399       *       since cholmod (& cs) lacks sparse 'int' matrices */       *       since cholmod (& cs) lacks sparse 'int' matrices */
400      CHM_SP chx = AS_CHM_SP__(x);      CHM_SP chx = AS_CHM_SP__(x);
401      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
402      CHM_SP chxt = cholmod_l_transpose(chx, chx->xtype, &c);      CHM_SP chxt = cholmod_transpose(chx, chx->xtype, &c);
403      SEXP dn = PROTECT(duplicate(GET_SLOT(x, Matrix_DimNamesSym))), tmp;      SEXP dn = PROTECT(duplicate(GET_SLOT(x, Matrix_DimNamesSym))), tmp;
404      int tr = asLogical(tri);      int tr = asLogical(tri);
405      R_CheckStack();      R_CheckStack();
# Line 225  Line 407
407      tmp = VECTOR_ELT(dn, 0);    /* swap the dimnames */      tmp = VECTOR_ELT(dn, 0);    /* swap the dimnames */
408      SET_VECTOR_ELT(dn, 0, VECTOR_ELT(dn, 1));      SET_VECTOR_ELT(dn, 0, VECTOR_ELT(dn, 1));
409      SET_VECTOR_ELT(dn, 1, tmp);      SET_VECTOR_ELT(dn, 1, tmp);
410        if(!isNull(tmp = getAttrib(dn, R_NamesSymbol))) { // swap names(dimnames(.)):
411            SEXP nms_dns = PROTECT(allocVector(VECSXP, 2));
412            SET_VECTOR_ELT(nms_dns, 1, STRING_ELT(tmp, 0));
413            SET_VECTOR_ELT(nms_dns, 0, STRING_ELT(tmp, 1));
414            setAttrib(dn, R_NamesSymbol, nms_dns);
415            UNPROTECT(1);
416        }
417      UNPROTECT(1);      UNPROTECT(1);
418      return chm_sparse_to_SEXP(chxt, 1, /* SWAP 'uplo' for triangular */      return chm_sparse_to_SEXP(chxt, 1, /* SWAP 'uplo' for triangular */
419                                tr ? ((*uplo_P(x) == 'U') ? -1 : 1) : 0,                                tr ? ((*uplo_P(x) == 'U') ? -1 : 1) : 0,
420                                Rkind, tr ? diag_P(x) : "", dn);                                Rkind, tr ? diag_P(x) : "", dn);
421  }  }
422
423  SEXP Csparse_Csparse_prod(SEXP a, SEXP b)  /** @brief  A %*% B  - for matrices of class CsparseMatrix (R package "Matrix")
424     *
425     * @param a
426     * @param b
427     * @param bool_arith
428     *
429     * @return
430     *
431     * NOTA BENE:  cholmod_ssmult(A,B, ...) ->  ./CHOLMOD/MatrixOps/cholmod_ssmult.c
432     * ---------  computes a patter*n* matrix __always_ when
433     * *one* of A or B is pattern*n*, because of this (line 73-74):
434       ---------------------------------------------------------------------------
435        values = values &&
436            (A->xtype != CHOLMOD_PATTERN) && (B->xtype != CHOLMOD_PATTERN) ;
437       ---------------------------------------------------------------------------
438     * ==> Often need to copy the patter*n* to a *l*ogical matrix first !!!
439     */
440    SEXP Csparse_Csparse_prod(SEXP a, SEXP b, SEXP bool_arith)
441  {  {
442      CHM_SP      CHM_SP
443          cha = AS_CHM_SP(a),          cha = AS_CHM_SP(a),
444          chb = AS_CHM_SP(b),          chb = AS_CHM_SP(b), chc;
445          chc = cholmod_l_ssmult(cha, chb, /*out_stype:*/ 0,      R_CheckStack();
446                               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);
447      char diag[] = {'\0', '\0'};      char diag[] = {'\0', '\0'};
448      int uploT = 0;      int uploT = 0, nprot = 1,
449      SEXP dn = allocVector(VECSXP, 2);          do_bool = asLogical(bool_arith); // TRUE / NA / FALSE
450        Rboolean
451            a_is_n = (cha->xtype == CHOLMOD_PATTERN),
452            b_is_n = (chb->xtype == CHOLMOD_PATTERN),
453            force_num = (do_bool == FALSE),
454            maybe_bool= (do_bool == NA_LOGICAL);
455
456    #ifdef DEBUG_Matrix_verbose
457        Rprintf("DBG Csparse_C*_prod(%s, %s)\n", class_P(a), class_P(b));
458    #endif
459
460        if(a_is_n && (force_num || (maybe_bool && !b_is_n))) {
461            /* coerce 'a' to  double;
462             * have no CHOLMOD function (pattern -> logical) --> use "our" code */
463            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
464            cha = AS_CHM_SP(da);
465            R_CheckStack();
466            a_is_n = FALSE;
467        }
468        else if(b_is_n && (force_num || (maybe_bool && !a_is_n))) {
469            // coerce 'b' to  double
470            SEXP db = PROTECT(nz2Csparse(b, x_double)); nprot++;
471            chb = AS_CHM_SP(db);
472      R_CheckStack();      R_CheckStack();
473            b_is_n = FALSE;
474        }
475        chc = cholmod_ssmult(cha, chb, /*out_stype:*/ 0,
476                             /* values : */ do_bool != TRUE,
477                             /* sorted = TRUE: */ 1, &c);
478
479      /* Preserve triangularity and even unit-triangularity if appropriate.      /* Preserve triangularity and even unit-triangularity if appropriate.
480       * Note that in that case, the multiplication itself should happen       * Note that in that case, the multiplication itself should happen
481       * faster.  But there's no support for that in CHOLMOD */       * faster.  But there's no support for that in CHOLMOD */
482
483      /* UGLY hack -- rather should have (fast!) C-level version of      if(R_check_class_etc(a, valid_tri) >= 0 &&
484       *       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"..*/
485          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. */
486              uploT = (*uplo_P(a) == 'U') ? 1 : -1;              uploT = (*uplo_P(a) == 'U') ? 1 : -1;
487              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 491
491              }              }
492              else diag[0]= 'N';              else diag[0]= 'N';
493          }          }
494
495        SEXP dn = PROTECT(allocVector(VECSXP, 2));
496      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
497                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));
498      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
499                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), 1)));
500        UNPROTECT(nprot);
501      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);
502  }  }
503
504  SEXP Csparse_Csparse_crossprod(SEXP a, SEXP b, SEXP trans)  /** @brief [t]crossprod (<Csparse>, <Csparse>)
505     *
506     * @param a a "CsparseMatrix" object
507     * @param b a "CsparseMatrix" object
508     * @param trans trans = FALSE:  crossprod(a,b)
509     *              trans = TRUE : tcrossprod(a,b)
510     * @param bool_arith logical (TRUE / NA / FALSE): Should boolean arithmetic be used.
511     *
512     * @return a CsparseMatrix, the (t)cross product of a and b.
513     */
514    SEXP Csparse_Csparse_crossprod(SEXP a, SEXP b, SEXP trans, SEXP bool_arith)
515  {  {
516      int tr = asLogical(trans);      int tr = asLogical(trans), nprot = 1,
517            do_bool = asLogical(bool_arith); // TRUE / NA / FALSE
518      CHM_SP      CHM_SP
519          cha = AS_CHM_SP(a),          cha = AS_CHM_SP(a),
520          chb = AS_CHM_SP(b),          chb = AS_CHM_SP(b),
521          chTr, chc;          chTr, chc;
522      const char *cl_a = class_P(a), *cl_b = class_P(b);      R_CheckStack();
523        static const char *valid_tri[] = { MATRIX_VALID_tri_Csparse, "" };
524      char diag[] = {'\0', '\0'};      char diag[] = {'\0', '\0'};
525      int uploT = 0;      int uploT = 0;
526      SEXP dn = allocVector(VECSXP, 2);      Rboolean
527            a_is_n = (cha->xtype == CHOLMOD_PATTERN),
528            b_is_n = (chb->xtype == CHOLMOD_PATTERN),
529            force_num = (do_bool == FALSE),
530            maybe_bool= (do_bool == NA_LOGICAL);
531
532        if(a_is_n && (force_num || (maybe_bool && !b_is_n))) {
533            // coerce 'a' to  double
534            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
535            cha = AS_CHM_SP(da);
536      R_CheckStack();      R_CheckStack();
537            // a_is_n = FALSE;
538      chTr = cholmod_l_transpose((tr) ? chb : cha, chb->xtype, &c);      }
539      chc = cholmod_l_ssmult((tr) ? cha : chTr, (tr) ? chTr : chb,      else if(b_is_n && (force_num || (maybe_bool && !a_is_n))) {
540                           /*out_stype:*/ 0, cha->xtype, /*out sorted:*/ 1, &c);          // coerce 'b' to  double
541      cholmod_l_free_sparse(&chTr, &c);          SEXP db = PROTECT(nz2Csparse(b, x_double)); nprot++;
542            chb = AS_CHM_SP(db);
543            R_CheckStack();
544            // b_is_n = FALSE;
545        }
546        else if(do_bool == TRUE) { // Want boolean arithmetic: sufficient if *one* is pattern:
547            if(!a_is_n && !b_is_n) {
548                // coerce 'a' to pattern
549                SEXP da = PROTECT(Csparse2nz(a, /* tri = */
550                                             R_check_class_etc(a, valid_tri) >= 0)); nprot++;
551                cha = AS_CHM_SP(da);
552                R_CheckStack();
553                // a_is_n = TRUE;
554            }
555        }
556        chTr = cholmod_transpose((tr) ? chb : cha, chb->xtype, &c);
557        chc = cholmod_ssmult((tr) ? cha : chTr, (tr) ? chTr : chb,
558                             /*out_stype:*/ 0, /* values : */ do_bool != TRUE,
559                             /* sorted = TRUE: */ 1, &c);
560        cholmod_free_sparse(&chTr, &c);
561
562      /* Preserve triangularity and unit-triangularity if appropriate;      /* Preserve triangularity and unit-triangularity if appropriate;
563       * see Csparse_Csparse_prod() for comments */       * see Csparse_Csparse_prod() for comments */
564      if (cl_a[1] == 't' && cl_b[1] == 't')      if(R_check_class_etc(a, valid_tri) >= 0 &&
565           R_check_class_etc(b, valid_tri) >= 0)
566          if(*uplo_P(a) != *uplo_P(b)) { /* one 'U', the other 'L' */          if(*uplo_P(a) != *uplo_P(b)) { /* one 'U', the other 'L' */
567              uploT = (*uplo_P(b) == 'U') ? 1 : -1;              uploT = (*uplo_P(b) == 'U') ? 1 : -1;
568              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 572
572              else diag[0]= 'N';              else diag[0]= 'N';
573          }          }
574
575        SEXP dn = PROTECT(allocVector(VECSXP, 2));
576      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
577                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), (tr) ? 0 : 1)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym),
578                                            (tr) ? 0 : 1)));
579      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
580                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), (tr) ? 0 : 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym),
581                                            (tr) ? 0 : 1)));
582        UNPROTECT(nprot);
583      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);
584  }  }
585
586  SEXP Csparse_dense_prod(SEXP a, SEXP b)  /**
587     * All (dense * sparse)  Matrix products and cross products
588     *
589     *   f( f(<Csparse>)  %*%  f(<dense>) )   where  f ()  is either t () [tranpose] or the identity.
590     *
591     * @param a CsparseMatrix  (n x m)
592     * @param b numeric vector, matrix, or denseMatrix (m x k) or (k x m)  if `transp` is '2' or 'B'
593     * @param transp character.
594     *        = " " : nothing transposed {apart from a}
595     *        = "2" : "transpose 2nd arg": use  t(b) instead of b (= 2nd argument)
596     *        = "c" : "transpose c":       Return  t(c) instead of c
597     *        = "B" : "transpose both":    use t(b) and return t(c) instead of c
598     * NB: For "2", "c", "B", need to transpose a *dense* matrix, B or C --> chm_transpose_dense()
599     *
600     * @return a dense matrix, the matrix product c = g(a,b) :
601     *
602     *                                                Condition (R)   Condition (C)
603     *   R notation            Math notation          cross  transp   t.a t.b t.ans
604     *   ~~~~~~~~~~~~~~~~~     ~~~~~~~~~~~~~~~~~~     ~~~~~~~~~~~~~   ~~~~~~~~~~~~~
605     *   c <-   a %*%   b      C :=      A B            .       " "    .   .   .
606     *   c <-   a %*% t(b)     C :=      A B'           .       "2"    .   |   .
607     *   c <- t(a %*%   b)     C := (A B)'  = B'A'      .       "c"    .   .   |
608     *   c <- t(a %*% t(b))    C := (A B')' = B A'      .       "B"    .   |   |
609     *
610     *   c <-   t(a) %*%   b   C :=      A'B           TRUE     " "    |   .   .
611     *   c <-   t(a) %*% t(b)  C :=      A'B'          TRUE     "2"    |   |   .
612     *   c <- t(t(a) %*%   b)  C := (A'B)'  = B'A      TRUE     "c"    |   .   |
613     *   c <- t(t(a) %*% t(b)) C := (A'B')' = B A      TRUE     "B"    |   |   |
614     */
615    SEXP Csp_dense_products(SEXP a, SEXP b,
616                            Rboolean transp_a, Rboolean transp_b, Rboolean transp_ans)
617  {  {
618      CHM_SP cha = AS_CHM_SP(a);      CHM_SP cha = AS_CHM_SP(a);
619      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix(b));      int a_nc = transp_a ? cha->nrow : cha->ncol,
620      CHM_DN chb = AS_CHM_DN(b_M);          a_nr = transp_a ? cha->ncol : cha->nrow;
621      CHM_DN chc = cholmod_l_allocate_dense(cha->nrow, chb->ncol, cha->nrow,      Rboolean
622                                          chb->xtype, &c);          maybe_transp_b = (a_nc == 1),
623      SEXP dn = PROTECT(allocVector(VECSXP, 2));          b_is_vector = FALSE;
624      double one[] = {1,0}, zero[] = {0,0};      /* NOTE: trans_b {<--> "use t(b) instead of b" }
625           ----  "interferes" with the  case automatic treatment of *vector* b.
626           In that case,  t(b) or b is used "whatever make more sense",
627           according to the general R philosophy of treating vectors in matrix products.
628        */
629
630        /* repeating a "cheap part" of  mMatrix_as_dgeMatrix2(b, .)  to see if
631         * we have a vector that we might 'transpose_if_vector' : */
632        static const char *valid[] = {"_NOT_A_CLASS_", MATRIX_VALID_ddense, ""};
633        /* int ctype = R_check_class_etc(b, valid);
634         * if (ctype > 0)   /.* a ddenseMatrix object */
635        if (R_check_class_etc(b, valid) < 0) {
636            // not a ddenseM*:  is.matrix() or vector:
637            b_is_vector = !isMatrix(b);
638        }
639
640        if(b_is_vector) {
641            /* determine *if* we want/need to transpose at all:
642             * if (length(b) == ncol(A)) have match: use dim = c(n, 1) (<=> do *not* transp);
643             *  otherwise, try to transpose: ok  if (ncol(A) == 1) [see also above]:  */
644            maybe_transp_b = (LENGTH(b) != a_nc);
645            // Here, we transpose already in mMatrix_as_dge*()  ==> don't do it later:
646            transp_b = FALSE;
647        }
648        SEXP b_M = PROTECT(mMatrix_as_dgeMatrix2(b, maybe_transp_b));
649
650        CHM_DN chb = AS_CHM_DN(b_M), b_t;
651      R_CheckStack();      R_CheckStack();
652        int ncol_b;
653        if(transp_b) { // transpose b:
654            b_t = cholmod_allocate_dense(chb->ncol, chb->nrow, chb->ncol, chb->xtype, &c);
655            chm_transpose_dense(b_t, chb);
656            ncol_b = b_t->ncol;
657        } else
658            ncol_b = chb->ncol;
659        // Result C {with dim() before it may be transposed}:
660        CHM_DN chc = cholmod_allocate_dense(a_nr, ncol_b, a_nr, chb->xtype, &c);
661        double one[] = {1,0}, zero[] = {0,0};
662        int nprot = 2;
663
664      cholmod_l_sdmult(cha, 0, one, zero, chb, chc, &c);      /* Tim Davis, please FIXME:  currently (2010-11) *fails* when  a  is a pattern matrix:*/
665      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      if(cha->xtype == CHOLMOD_PATTERN) {
666                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));          /* warning(_("Csparse_dense_prod(): cholmod_sdmult() not yet implemented for pattern./ ngCMatrix" */
667      SET_VECTOR_ELT(dn, 1,          /*        " --> slightly inefficient coercion")); */
668                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));
669      UNPROTECT(2);          // This *fails* to produce a CHOLMOD_REAL ..
670      return chm_dense_to_SEXP(chc, 1, 0, dn);          // CHM_SP chd = cholmod_l_copy(cha, cha->stype, CHOLMOD_REAL, &c);
671            // --> use our Matrix-classes
672            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
673            cha = AS_CHM_SP(da);
674        }
675
676        /* cholmod_sdmult(A, transp, alpha, beta, X,  Y,  &c): depending on transp == 0 / != 0:
677         *  Y := alpha*(A*X) + beta*Y or alpha*(A'*X) + beta*Y;  here, alpha = 1, beta = 0:
678         *  Y := A*X  or  A'*X
679         *                       NB: always  <sparse> %*% <dense> !
680         */
681        cholmod_sdmult(cha, transp_a, one, zero, (transp_b ? b_t : chb), /* -> */ chc, &c);
682
683        SEXP dn = PROTECT(allocVector(VECSXP, 2));  /* establish dimnames */
684        SET_VECTOR_ELT(dn, transp_ans ? 1 : 0,
685                       duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), transp_a ? 1 : 0)));
686        SET_VECTOR_ELT(dn, transp_ans ? 0 : 1,
687                       duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym),
688                                            transp_b ? 0 : 1)));
689        if(transp_b) cholmod_free_dense(&b_t, &c);
690        UNPROTECT(nprot);
691        return chm_dense_to_SEXP(chc, 1, 0, dn, transp_ans);
692  }  }
693
694  SEXP Csparse_dense_crossprod(SEXP a, SEXP b)
695    SEXP Csparse_dense_prod(SEXP a, SEXP b, SEXP transp)
696  {  {
697      CHM_SP cha = AS_CHM_SP(a);      return
698      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix(b));          Csp_dense_products(a, b,
699      CHM_DN chb = AS_CHM_DN(b_M);                  /* transp_a = */ FALSE,
700      CHM_DN chc = cholmod_l_allocate_dense(cha->ncol, chb->ncol, cha->ncol,                  /* transp_b   = */ (*CHAR(asChar(transp)) == '2' || *CHAR(asChar(transp)) == 'B'),
701                                          chb->xtype, &c);                  /* transp_ans = */ (*CHAR(asChar(transp)) == 'c' || *CHAR(asChar(transp)) == 'B'));
702      SEXP dn = PROTECT(allocVector(VECSXP, 2));  }
double one[] = {1,0}, zero[] = {0,0};
R_CheckStack();
703
704      cholmod_l_sdmult(cha, 1, one, zero, chb, chc, &c);  SEXP Csparse_dense_crossprod(SEXP a, SEXP b, SEXP transp)
705      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */  {
706                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 1)));      return
707      SET_VECTOR_ELT(dn, 1,          Csp_dense_products(a, b,
708                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));                  /* transp_a = */ TRUE,
709      UNPROTECT(2);                  /* transp_b   = */ (*CHAR(asChar(transp)) == '2' || *CHAR(asChar(transp)) == 'B'),
710      return chm_dense_to_SEXP(chc, 1, 0, dn);                  /* transp_ans = */ (*CHAR(asChar(transp)) == 'c' || *CHAR(asChar(transp)) == 'B'));
711  }  }
712
713  /* Computes   x'x  or  x x' -- *also* for Tsparse (triplet = TRUE)
714     see Csparse_Csparse_crossprod above for  x'y and x y' */  /** @brief Computes   x'x  or  x x' -- *also* for Tsparse (triplet = TRUE)
715  SEXP Csparse_crossprod(SEXP x, SEXP trans, SEXP triplet)      see Csparse_Csparse_crossprod above for  x'y and x y'
716  {  */
717      int trip = asLogical(triplet),  SEXP Csparse_crossprod(SEXP x, SEXP trans, SEXP triplet, SEXP bool_arith)
718          tr   = asLogical(trans); /* gets reversed because _aat is tcrossprod */  {
719      CHM_TR cht = trip ? AS_CHM_TR(x) : (CHM_TR) NULL;      int tripl = asLogical(triplet),
720      CHM_SP chcp, chxt,          tr   = asLogical(trans), /* gets reversed because _aat is tcrossprod */
721          chx = (trip ?          do_bool = asLogical(bool_arith); // TRUE / NA / FALSE
722                 cholmod_l_triplet_to_sparse(cht, cht->nnz, &c) :  #ifdef AS_CHM_DIAGU2N_FIXED_FINALLY
723        CHM_TR cht = tripl ? AS_CHM_TR(x) : (CHM_TR) NULL;  int nprot = 1;
724    #else /* workaround needed:*/
725        SEXP xx = PROTECT(Tsparse_diagU2N(x));
726        CHM_TR cht = tripl ? AS_CHM_TR__(xx) : (CHM_TR) NULL; int nprot = 2;
727    #endif
728        CHM_SP chcp, chxt, chxc,
729            chx = (tripl ?
730                   cholmod_triplet_to_sparse(cht, cht->nnz, &c) :
731                 AS_CHM_SP(x));                 AS_CHM_SP(x));
732      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2));
733      R_CheckStack();      R_CheckStack();
734        Rboolean
735            x_is_n = (chx->xtype == CHOLMOD_PATTERN),
736            x_is_sym = chx->stype != 0,
737            force_num = (do_bool == FALSE);
738
739        if(x_is_n && force_num) {
740            // coerce 'x' to  double
741            SEXP dx = PROTECT(nz2Csparse(x, x_double)); nprot++;
742            chx = AS_CHM_SP(dx);
743            R_CheckStack();
744        }
745        else if(do_bool == TRUE && !x_is_n) { // Want boolean arithmetic; need patter[n]
746            // coerce 'x' to pattern
747            static const char *valid_tri[] = { MATRIX_VALID_tri_Csparse, "" };
748            SEXP dx = PROTECT(Csparse2nz(x, /* tri = */
749                                         R_check_class_etc(x, valid_tri) >= 0)); nprot++;
750            chx = AS_CHM_SP(dx);
751            R_CheckStack();
752        }
753
754        if (!tr) chxt = cholmod_transpose(chx, chx->xtype, &c);
755
756      if (!tr) chxt = cholmod_l_transpose(chx, chx->xtype, &c);      if (x_is_sym) // cholmod_aat() does not like symmetric
757      chcp = cholmod_l_aat((!tr) ? chxt : chx, (int *) NULL, 0, chx->xtype, &c);          chxc = cholmod_copy(tr ? chx : chxt, /* stype: */ 0,
758                                chx->xtype, &c);
759        // CHOLMOD/Core/cholmod_aat.c :
760        chcp = cholmod_aat(x_is_sym ? chxc : (tr ? chx : chxt),
761                           (int *) NULL, 0, /* mode: */ chx->xtype, &c);
762      if(!chcp) {      if(!chcp) {
763          UNPROTECT(1);          UNPROTECT(1);
764          error(_("Csparse_crossprod(): error return from cholmod_l_aat()"));          error(_("Csparse_crossprod(): error return from cholmod_aat()"));
765      }      }
766      cholmod_l_band_inplace(0, chcp->ncol, chcp->xtype, chcp, &c);      cholmod_band_inplace(0, chcp->ncol, chcp->xtype, chcp, &c);
767      chcp->stype = 1;      chcp->stype = 1; // symmetric
768      if (trip) cholmod_l_free_sparse(&chx, &c);      if (tripl) cholmod_free_sparse(&chx, &c);
769      if (!tr) cholmod_l_free_sparse(&chxt, &c);      if (!tr) cholmod_free_sparse(&chxt, &c);
770      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
771                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),
772                                          (tr) ? 0 : 1)));                                          (tr) ? 0 : 1)));
773      SET_VECTOR_ELT(dn, 1, duplicate(VECTOR_ELT(dn, 0)));      SET_VECTOR_ELT(dn, 1, duplicate(VECTOR_ELT(dn, 0)));
774      UNPROTECT(1);      UNPROTECT(nprot);
775        // FIXME: uploT for symmetric ?
776      return chm_sparse_to_SEXP(chcp, 1, 0, 0, "", dn);      return chm_sparse_to_SEXP(chcp, 1, 0, 0, "", dn);
777  }  }
778
779    /** @brief Csparse_drop(x, tol):  drop entries with absolute value < tol, i.e,
780     *  at least all "explicit" zeros. */
781  SEXP Csparse_drop(SEXP x, SEXP tol)  SEXP Csparse_drop(SEXP x, SEXP tol)
782  {  {
783      const char *cl = class_P(x);      const char *cl = class_P(x);
784      /* dtCMatrix, etc; [1] = the second character =?= 't' for triangular */      /* dtCMatrix, etc; [1] = the second character =?= 't' for triangular */
785      int tr = (cl[1] == 't');      int tr = (cl[1] == 't'); // FIXME - rather  R_check_class_etc(..)
786      CHM_SP chx = AS_CHM_SP__(x);      CHM_SP chx = AS_CHM_SP__(x);
787      CHM_SP ans = cholmod_l_copy(chx, chx->stype, chx->xtype, &c);      CHM_SP ans = cholmod_copy(chx, chx->stype, chx->xtype, &c);
788      double dtol = asReal(tol);      double dtol = asReal(tol);
789      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
790      R_CheckStack();      R_CheckStack();
791
792      if(!cholmod_l_drop(dtol, ans, &c))      if(!cholmod_drop(dtol, ans, &c))
793          error(_("cholmod_l_drop() failed"));          error(_("cholmod_drop() failed"));
794      return chm_sparse_to_SEXP(ans, 1,      return chm_sparse_to_SEXP(ans, 1,
795                                tr ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,                                tr ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,
796                                Rkind, tr ? diag_P(x) : "",                                Rkind, tr ? diag_P(x) : "",
797                                GET_SLOT(x, Matrix_DimNamesSym));                                GET_SLOT(x, Matrix_DimNamesSym));
798  }  }
799
800    /** @brief Horizontal Concatenation -  cbind( <Csparse>,  <Csparse>)
801     */
802  SEXP Csparse_horzcat(SEXP x, SEXP y)  SEXP Csparse_horzcat(SEXP x, SEXP y)
803  {  {
804      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);  #define CSPARSE_CAT(_KIND_)                                             \
805      int Rkind = 0; /* only for "d" - FIXME */      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);                  \
806      R_CheckStack();      R_CheckStack();                                                     \
807        int Rk_x = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : -3,     \
808            Rk_y = (chy->xtype != CHOLMOD_PATTERN) ? Real_kind(y) : -3, Rkind; \
809        if(Rk_x == -3 || Rk_y == -3) { /* at least one of them is patter"n" */ \
810            if(Rk_x == -3 && Rk_y == -3) { /* fine */                       \
811            } else { /* only one is a patter"n"                             \
812                      * "Bug" in cholmod_horzcat()/vertcat(): returns patter"n" matrix if one of them is */ \
813                Rboolean ok;                                                \
814                if(Rk_x == -3) {                                            \
815                    ok = chm_MOD_xtype(CHOLMOD_REAL, chx, &c); Rk_x = 0;    \
816                } else if(Rk_y == -3) {                                     \
817                    ok = chm_MOD_xtype(CHOLMOD_REAL, chy, &c); Rk_y = 0;    \
818                } else                                                      \
819                    error(_("Impossible Rk_x/Rk_y in Csparse_%s(), please report"), _KIND_); \
820                if(!ok)                                                     \
821                    error(_("chm_MOD_xtype() was not successful in Csparse_%s(), please report"), \
822                          _KIND_);                                          \
823            }                                                               \
824        }                                                                   \
825        Rkind = /* logical if both x and y are */ (Rk_x == 1 && Rk_y == 1) ? 1 : 0
826
827      /* FIXME: currently drops dimnames */      CSPARSE_CAT("horzcat");
828      return chm_sparse_to_SEXP(cholmod_l_horzcat(chx, chy, 1, &c),      // TODO: currently drops dimnames - and we fix at R level;
829
830        return chm_sparse_to_SEXP(cholmod_horzcat(chx, chy, 1, &c),
831                                1, 0, Rkind, "", R_NilValue);                                1, 0, Rkind, "", R_NilValue);
832  }  }
833
834    /** @brief Vertical Concatenation -  rbind( <Csparse>,  <Csparse>)
835     */
836  SEXP Csparse_vertcat(SEXP x, SEXP y)  SEXP Csparse_vertcat(SEXP x, SEXP y)
837  {  {
838      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);      CSPARSE_CAT("vertcat");
839      int Rkind = 0; /* only for "d" - FIXME */      // TODO: currently drops dimnames - and we fix at R level;
R_CheckStack();
840
841      /* FIXME: currently drops dimnames */      return chm_sparse_to_SEXP(cholmod_vertcat(chx, chy, 1, &c),
return chm_sparse_to_SEXP(cholmod_l_vertcat(chx, chy, 1, &c),
842                                1, 0, Rkind, "", R_NilValue);                                1, 0, Rkind, "", R_NilValue);
843  }  }
844
# Line 422  Line 846
846  {  {
847      CHM_SP chx = AS_CHM_SP__(x);      CHM_SP chx = AS_CHM_SP__(x);
848      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
849      CHM_SP ans = cholmod_l_band(chx, asInteger(k1), asInteger(k2), chx->xtype, &c);      CHM_SP ans = cholmod_band(chx, asInteger(k1), asInteger(k2), chx->xtype, &c);
850      R_CheckStack();      R_CheckStack();
851
852      return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "",      return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "",
# Line 440  Line 864
864      }      }
865      else { /* unit triangular (diag='U'): "fill the diagonal" & diag:= "N" */      else { /* unit triangular (diag='U'): "fill the diagonal" & diag:= "N" */
866          CHM_SP chx = AS_CHM_SP__(x);          CHM_SP chx = AS_CHM_SP__(x);
867          CHM_SP eye = cholmod_l_speye(chx->nrow, chx->ncol, chx->xtype, &c);          CHM_SP eye = cholmod_speye(chx->nrow, chx->ncol, chx->xtype, &c);
868          double one[] = {1, 0};          double one[] = {1, 0};
869          CHM_SP ans = cholmod_l_add(chx, eye, one, one, TRUE, TRUE, &c);          CHM_SP ans = cholmod_add(chx, eye, one, one, TRUE, TRUE, &c);
870          int uploT = (*uplo_P(x) == 'U') ? 1 : -1;          int uploT = (*uplo_P(x) == 'U') ? 1 : -1;
871          int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;          int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
872
873          R_CheckStack();          R_CheckStack();
874          cholmod_l_free_sparse(&eye, &c);          cholmod_free_sparse(&eye, &c);
875          return chm_sparse_to_SEXP(ans, 1, uploT, Rkind, "N",          return chm_sparse_to_SEXP(ans, 1, uploT, Rkind, "N",
876                                    GET_SLOT(x, Matrix_DimNamesSym));                                    GET_SLOT(x, Matrix_DimNamesSym));
877      }      }
# Line 464  Line 888
888      }      }
889      else { /* triangular with diag='N'): now drop the diagonal */      else { /* triangular with diag='N'): now drop the diagonal */
890          /* duplicate, since chx will be modified: */          /* duplicate, since chx will be modified: */
891          CHM_SP chx = AS_CHM_SP__(duplicate(x));          SEXP xx = PROTECT(duplicate(x));
892            CHM_SP chx = AS_CHM_SP__(xx);
893          int uploT = (*uplo_P(x) == 'U') ? 1 : -1,          int uploT = (*uplo_P(x) == 'U') ? 1 : -1,
894              Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;              Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
895          R_CheckStack();          R_CheckStack();
896
897          chm_diagN2U(chx, uploT, /* do_realloc */ FALSE);          chm_diagN2U(chx, uploT, /* do_realloc */ FALSE);
898
899          return chm_sparse_to_SEXP(chx, /*dofree*/ 0/* or 1 ?? */,          SEXP ans = chm_sparse_to_SEXP(chx, /*dofree*/ 0/* or 1 ?? */,
900                                    uploT, Rkind, "U",                                    uploT, Rkind, "U",
901                                    GET_SLOT(x, Matrix_DimNamesSym));                                    GET_SLOT(x, Matrix_DimNamesSym));
902            UNPROTECT(1);// only now !
903            return ans;
904      }      }
905  }  }
906
907    /**
908     * Indexing aka subsetting : Compute  x[i,j], also for vectors i and j
909     * Working via CHOLMOD_submatrix, see ./CHOLMOD/MatrixOps/cholmod_submatrix.c
910     * @param x CsparseMatrix
911     * @param i row     indices (0-origin), or NULL (R, not C)
912     * @param j columns indices (0-origin), or NULL
913     *
914     * @return x[i,j]  still CsparseMatrix --- currently, this loses dimnames
915     */
916  SEXP Csparse_submatrix(SEXP x, SEXP i, SEXP j)  SEXP Csparse_submatrix(SEXP x, SEXP i, SEXP j)
917  {  {
918      CHM_SP chx = AS_CHM_SP__(x);      CHM_SP chx = AS_CHM_SP(x); /* << does diagU2N() when needed */
919      int rsize = (isNull(i)) ? -1 : LENGTH(i),      int rsize = (isNull(i)) ? -1 : LENGTH(i),
920          csize = (isNull(j)) ? -1 : LENGTH(j);          csize = (isNull(j)) ? -1 : LENGTH(j);
921      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
# Line 490  Line 926
926      if (csize >= 0 && !isInteger(j))      if (csize >= 0 && !isInteger(j))
927          error(_("Index j must be NULL or integer"));          error(_("Index j must be NULL or integer"));
928
929      return chm_sparse_to_SEXP(cholmod_l_submatrix(chx, INTEGER(i), rsize,  #define CHM_SUB(_M_, _i_, _j_)                                  \
930                                                  INTEGER(j), csize,      cholmod_submatrix(_M_,                                      \
931                                                  TRUE, TRUE, &c),                        (rsize < 0) ? NULL : INTEGER(_i_), rsize, \
932                                1, 0, Rkind, "",                        (csize < 0) ? NULL : INTEGER(_j_), csize, \
933                                /* FIXME: drops dimnames */ R_NilValue);                        TRUE, TRUE, &c)
934  }      CHM_SP ans;
935        if (!chx->stype) {/* non-symmetric Matrix */
936            ans = CHM_SUB(chx, i, j);
937        }
938        else {
939            /* for now, cholmod_submatrix() only accepts "generalMatrix" */
940            CHM_SP tmp = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);
941            ans = CHM_SUB(tmp, i, j);
942            cholmod_free_sparse(&tmp, &c);
943        }
944
945        // "FIXME": currently dropping dimnames, and adding them afterwards in R :
946        /* // dimnames: */
947        /* SEXP x_dns = GET_SLOT(x, Matrix_DimNamesSym), */
948        /*  dn = PROTECT(allocVector(VECSXP, 2)); */
949        return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "", /* dimnames: */ R_NilValue);
950    }
951
952    #define _d_Csp_
953    #include "t_Csparse_subassign.c"
954
955    #define _l_Csp_
956    #include "t_Csparse_subassign.c"
957
958    #define _i_Csp_
959    #include "t_Csparse_subassign.c"
960
961    #define _n_Csp_
962    #include "t_Csparse_subassign.c"
963
964    #define _z_Csp_
965    #include "t_Csparse_subassign.c"
966
967
968
969  SEXP Csparse_MatrixMarket(SEXP x, SEXP fname)  SEXP Csparse_MatrixMarket(SEXP x, SEXP fname)
970  {  {
# Line 504  Line 973
973      if (!f)      if (!f)
974          error(_("failure to open file \"%s\" for writing"),          error(_("failure to open file \"%s\" for writing"),
975                CHAR(asChar(fname)));                CHAR(asChar(fname)));
976      if (!cholmod_l_write_sparse(f, AS_CHM_SP(x),      if (!cholmod_write_sparse(f, AS_CHM_SP(x),
977                                (CHM_SP)NULL, (char*) NULL, &c))                                (CHM_SP)NULL, (char*) NULL, &c))
978          error(_("cholmod_l_write_sparse returned error code"));          error(_("cholmod_write_sparse returned error code"));
979      fclose(f);      fclose(f);
980      return R_NilValue;      return R_NilValue;
981  }  }
# Line 524  Line 993
993   *   *
994   * @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
995   */   */
996  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,
997  /*                                ^^^^^^ FIXME[Generalize] to int / ... */  /*                                ^^^^^^ FIXME[Generalize] to int / ... */
998                     SEXP resultKind)
999  {  {
1000      const char* res_ch = CHAR(STRING_ELT(resultKind,0));      const char* res_ch = CHAR(STRING_ELT(resultKind,0));
1001      enum diag_kind { diag, diag_backpermuted, trace, prod, sum_log      enum diag_kind { diag, diag_backpermuted, trace, prod, sum_log, min, max, range
1002      } res_kind = ((!strcmp(res_ch, "trace")) ? trace :      } res_kind = ((!strcmp(res_ch, "trace")) ? trace :
1003                    ((!strcmp(res_ch, "sumLog")) ? sum_log :                    ((!strcmp(res_ch, "sumLog")) ? sum_log :
1004                     ((!strcmp(res_ch, "prod")) ? prod :                     ((!strcmp(res_ch, "prod")) ? prod :
1005                        ((!strcmp(res_ch, "min")) ? min :
1006                         ((!strcmp(res_ch, "max")) ? max :
1007                          ((!strcmp(res_ch, "range")) ? range :
1008                      ((!strcmp(res_ch, "diag")) ? diag :                      ((!strcmp(res_ch, "diag")) ? diag :
1009                       ((!strcmp(res_ch, "diagBack")) ? diag_backpermuted :                       ((!strcmp(res_ch, "diagBack")) ? diag_backpermuted :
1010                        -1)))));                           -1))))))));
1011      int i, n_x, i_from = 0;      int i, n_x, i_from;
1012      SEXP ans = PROTECT(allocVector(REALSXP,      SEXP ans = PROTECT(allocVector(REALSXP,
1013  /*                                 ^^^^  FIXME[Generalize] */  /*                                 ^^^^  FIXME[Generalize] */
1014                                     (res_kind == diag ||                                     (res_kind == diag ||
1015                                      res_kind == diag_backpermuted) ? n : 1));                                      res_kind == diag_backpermuted) ? n :
1016                                       (res_kind == range ? 2 : 1)));
1017      double *v = REAL(ans);      double *v = REAL(ans);
1018  /*  ^^^^^^      ^^^^  FIXME[Generalize] */  /*  ^^^^^^      ^^^^  FIXME[Generalize] */
1019
1020        i_from = (is_U ? -1 : 0);
1021
1022  #define for_DIAG(v_ASSIGN)                                              \  #define for_DIAG(v_ASSIGN)                                              \
1023      for(i = 0; i < n; i++, i_from += n_x) {                             \      for(i = 0; i < n; i++) {                                    \
1024          /* looking at i-th column */                                    \          /* looking at i-th column */                                    \
1025          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 */ \
1026            if( is_U) i_from += n_x;                                \
1027          v_ASSIGN;                                                       \          v_ASSIGN;                                                       \
1028            if(!is_U) i_from += n_x;                                \
1029      }      }
1030
1031      /* NOTA BENE: we assume  -- uplo = "L" i.e. lower triangular matrix      /* NOTA BENE: we assume  -- uplo = "L" i.e. lower triangular matrix
1032       *            for uplo = "U" (makes sense with a "dtCMatrix" !),       *            for uplo = "U" (makes sense with a "dtCMatrix" !),
1033       *            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],
1034       *            where nx = (x_p[i+1] - x_p[i])       *            where n_x = (x_p[i+1] - x_p[i])
1035       */       */
1036
1037      switch(res_kind) {      switch(res_kind) {
1038      case trace:      case trace: // = sum
1039          v[0] = 0.;          v[0] = 0.;
1040          for_DIAG(v[0] += x_x[i_from]);          for_DIAG(v[0] += x_x[i_from]);
1041          break;          break;
# Line 572  Line 1050
1050          for_DIAG(v[0] *= x_x[i_from]);          for_DIAG(v[0] *= x_x[i_from]);
1051          break;          break;
1052
1053        case min:
1054            v[0] = R_PosInf;
1055            for_DIAG(if(v[0] > x_x[i_from]) v[0] = x_x[i_from]);
1056            break;
1057
1058        case max:
1059            v[0] = R_NegInf;
1060            for_DIAG(if(v[0] < x_x[i_from]) v[0] = x_x[i_from]);
1061            break;
1062
1063        case range:
1064            v[0] = R_PosInf;
1065            v[1] = R_NegInf;
1066            for_DIAG(if(v[0] > x_x[i_from]) v[0] = x_x[i_from];
1067                     if(v[1] < x_x[i_from]) v[1] = x_x[i_from]);
1068            break;
1069
1070      case diag:      case diag:
1071          for_DIAG(v[i] = x_x[i_from]);          for_DIAG(v[i] = x_x[i_from]);
1072          break;          break;
# Line 579  Line 1074
1074      case diag_backpermuted:      case diag_backpermuted:
1075          for_DIAG(v[i] = x_x[i_from]);          for_DIAG(v[i] = x_x[i_from]);
1076
1077          warning(_("resultKind = 'diagBack' (back-permuted) is experimental"));          warning(_("%s = '%s' (back-permuted) is experimental"),
1078                    "resultKind", "diagBack");
1079          /* now back_permute : */          /* now back_permute : */
1080          for(i = 0; i < n; i++) {          for(i = 0; i < n; i++) {
1081              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 1084
1084          break;          break;
1085
1086      default: /* -1 from above */      default: /* -1 from above */
1087          error("diag_tC(): invalid 'resultKind'");          error(_("diag_tC(): invalid 'resultKind'"));
1088          /* Wall: */ ans = R_NilValue; v = REAL(ans);          /* Wall: */ ans = R_NilValue; v = REAL(ans);
1089      }      }
1090
# Line 600  Line 1096
1096   * Extract the diagonal entries from *triangular* Csparse matrix  __or__ a   * Extract the diagonal entries from *triangular* Csparse matrix  __or__ a
1097   * cholmod_sparse factor (LDL = TRUE).   * cholmod_sparse factor (LDL = TRUE).
1098   *   *
1099     * @param obj -- now a cholmod_sparse factor or a dtCMatrix
1100   * @param pslot  'p' (column pointer)   slot of Csparse matrix/factor   * @param pslot  'p' (column pointer)   slot of Csparse matrix/factor
1101   * @param xslot  'x' (non-zero entries) slot of Csparse matrix/factor   * @param xslot  'x' (non-zero entries) slot of Csparse matrix/factor
1102   * @param perm_slot  'perm' (= permutation vector) slot of corresponding CHMfactor;   * @param perm_slot  'perm' (= permutation vector) slot of corresponding CHMfactor;
# Line 608  Line 1105
1105   *   *
1106   * @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
1107   */   */
1108  SEXP diag_tC(SEXP pslot, SEXP xslot, SEXP perm_slot, SEXP resultKind)  SEXP diag_tC(SEXP obj, SEXP resultKind)
1109  {  {
1110
1111        SEXP
1112            pslot = GET_SLOT(obj, Matrix_pSym),
1113            xslot = GET_SLOT(obj, Matrix_xSym);
1114        Rboolean is_U = (R_has_slot(obj, Matrix_uploSym) &&
1115                         *CHAR(asChar(GET_SLOT(obj, Matrix_uploSym))) == 'U');
1116      int n = length(pslot) - 1, /* n = ncol(.) = nrow(.) */      int n = length(pslot) - 1, /* n = ncol(.) = nrow(.) */
1117          *x_p  = INTEGER(pslot),          *x_p  = INTEGER(pslot), pp = -1, *perm;
*perm = INTEGER(perm_slot);
1118      double *x_x = REAL(xslot);      double *x_x = REAL(xslot);
1119  /*  ^^^^^^        ^^^^ FIXME[Generalize] to INTEGER(.) / LOGICAL(.) / ... xslot !*/  /*  ^^^^^^        ^^^^ FIXME[Generalize] to INTEGER(.) / LOGICAL(.) / ... xslot !*/
1120
1121      return diag_tC_ptr(n, x_p, x_x, perm, resultKind);      if(R_has_slot(obj, Matrix_permSym))
1122            perm = INTEGER(GET_SLOT(obj, Matrix_permSym));
1123        else perm = &pp;
1124
1125        return diag_tC_ptr(n, x_p, x_x, is_U, perm, resultKind);
1126    }
1127
1128
1129    /**
1130     * Create a Csparse matrix object from indices and/or pointers.
1131     *
1132     * @param cls name of actual class of object to create
1133     * @param i optional integer vector of length nnz of row indices
1134     * @param j optional integer vector of length nnz of column indices
1135     * @param p optional integer vector of length np of row or column pointers
1136     * @param np length of integer vector p.  Must be zero if p == (int*)NULL
1137     * @param x optional vector of values
1138     * @param nnz length of vectors i, j and/or x, whichever is to be used
1139     * @param dims optional integer vector of length 2 to be used as
1140     *     dimensions.  If dims == (int*)NULL then the maximum row and column
1141     *     index are used as the dimensions.
1142     * @param dimnames optional list of length 2 to be used as dimnames
1143     * @param index1 indicator of 1-based indices
1144     *
1145     * @return an SEXP of class cls inheriting from CsparseMatrix.
1146     */
1147    SEXP create_Csparse(char* cls, int* i, int* j, int* p, int np,
1148                        void* x, int nnz, int* dims, SEXP dimnames,
1149                        int index1)
1150    {
1151        SEXP ans;
1152        int *ij = (int*)NULL, *tri, *trj,
1153            mi, mj, mp, nrow = -1, ncol = -1;
1154        int xtype = -1;             /* -Wall */
1155        CHM_TR T;
1156        CHM_SP A;
1157
1158        if (np < 0 || nnz < 0)
1159            error(_("negative vector lengths not allowed: np = %d, nnz = %d"),
1160                  np, nnz);
1161        if (1 != ((mi = (i == (int*)NULL)) +
1162                  (mj = (j == (int*)NULL)) +
1163                  (mp = (p == (int*)NULL))))
1164            error(_("exactly 1 of 'i', 'j' or 'p' must be NULL"));
1165        if (mp) {
1166            if (np) error(_("np = %d, must be zero when p is NULL"), np);
1167        } else {
1168            if (np) {               /* Expand p to form i or j */
1169                if (!(p[0])) error(_("p[0] = %d, should be zero"), p[0]);
1170                for (int ii = 0; ii < np; ii++)
1171                    if (p[ii] > p[ii + 1])
1172                        error(_("p must be non-decreasing"));
1173                if (p[np] != nnz)
1174                    error("p[np] = %d != nnz = %d", p[np], nnz);
1175                ij = Calloc(nnz, int);
1176                if (mi) {
1177                    i = ij;
1178                    nrow = np;
1179                } else {
1180                    j = ij;
1181                    ncol = np;
1182                }
1183                /* Expand p to 0-based indices */
1184                for (int ii = 0; ii < np; ii++)
1185                    for (int jj = p[ii]; jj < p[ii + 1]; jj++) ij[jj] = ii;
1186            } else {
1187                if (nnz)
1188                    error(_("Inconsistent dimensions: np = 0 and nnz = %d"),
1189                          nnz);
1190            }
1191        }
1192        /* calculate nrow and ncol */
1193        if (nrow < 0) {
1194            for (int ii = 0; ii < nnz; ii++) {
1195                int i1 = i[ii] + (index1 ? 0 : 1); /* 1-based index */
1196                if (i1 < 1) error(_("invalid row index at position %d"), ii);
1197                if (i1 > nrow) nrow = i1;
1198            }
1199        }
1200        if (ncol < 0) {
1201            for (int jj = 0; jj < nnz; jj++) {
1202                int j1 = j[jj] + (index1 ? 0 : 1);
1203                if (j1 < 1) error(_("invalid column index at position %d"), jj);
1204                if (j1 > ncol) ncol = j1;
1205            }
1206        }
1207        if (dims != (int*)NULL) {
1208            if (dims[0] > nrow) nrow = dims[0];
1209            if (dims[1] > ncol) ncol = dims[1];
1210        }
1211        /* check the class name */
1212        if (strlen(cls) != 8)
1213            error(_("strlen of cls argument = %d, should be 8"), strlen(cls));
1214        if (!strcmp(cls + 2, "CMatrix"))
1215            error(_("cls = \"%s\" does not end in \"CMatrix\""), cls);
1216        switch(cls[0]) {
1217        case 'd':
1218        case 'l':
1219            xtype = CHOLMOD_REAL;
1220        break;
1221        case 'n':
1222            xtype = CHOLMOD_PATTERN;
1223            break;
1224        default:
1225            error(_("cls = \"%s\" must begin with 'd', 'l' or 'n'"), cls);
1226        }
1227        if (cls[1] != 'g')
1228            error(_("Only 'g'eneral sparse matrix types allowed"));
1229        /* allocate and populate the triplet */
1230        T = cholmod_allocate_triplet((size_t)nrow, (size_t)ncol, (size_t)nnz, 0,
1231                                     xtype, &c);
1232        T->x = x;
1233        tri = (int*)T->i;
1234        trj = (int*)T->j;
1235        for (int ii = 0; ii < nnz; ii++) {
1236            tri[ii] = i[ii] - ((!mi && index1) ? 1 : 0);
1237            trj[ii] = j[ii] - ((!mj && index1) ? 1 : 0);
1238        }
1239        /* create the cholmod_sparse structure */
1240        A = cholmod_triplet_to_sparse(T, nnz, &c);
1241        cholmod_free_triplet(&T, &c);
1242        /* copy the information to the SEXP */
1243        ans = PROTECT(NEW_OBJECT(MAKE_CLASS(cls)));
1244    // FIXME: This has been copied from chm_sparse_to_SEXP in  chm_common.c
1245        /* allocate and copy common slots */
1246        nnz = cholmod_nnz(A, &c);
1247        dims = INTEGER(ALLOC_SLOT(ans, Matrix_DimSym, INTSXP, 2));
1248        dims[0] = A->nrow; dims[1] = A->ncol;
1249        Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_pSym, INTSXP, A->ncol + 1)), (int*)A->p, A->ncol + 1);
1250        Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_iSym, INTSXP, nnz)), (int*)A->i, nnz);
1251        switch(cls[1]) {
1252        case 'd':
1253            Memcpy(REAL(ALLOC_SLOT(ans, Matrix_xSym, REALSXP, nnz)), (double*)A->x, nnz);
1254            break;
1255        case 'l':
1256            error(_("code not yet written for cls = \"lgCMatrix\""));
1257        }
1258    /* FIXME: dimnames are *NOT* put there yet (if non-NULL) */
1259        cholmod_free_sparse(&A, &c);
1260        UNPROTECT(1);
1261        return ans;
1262  }  }

Legend:
 Removed from v.2299 changed lines Added in v.3147