SCM

SCM Repository

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

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

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

revision 2586, Sun Jul 25 02:32:06 2010 UTC revision 3055, Sat Mar 14 21:12:03 2015 UTC
# Line 1  Line 1 
1                          /* Sparse matrices in compressed column-oriented form */                          /* Sparse matrices in compressed column-oriented form */
2    
3  #include "Csparse.h"  #include "Csparse.h"
4  #include "Tsparse.h"  #include "Tsparse.h"
5  #include "chm_common.h"  #include "chm_common.h"
# Line 36  Line 37 
37      return Csparse_validate_(x, FALSE);      return Csparse_validate_(x, FALSE);
38  }  }
39    
 SEXP Csparse_validate2(SEXP x, SEXP maybe_modify) {  
     return Csparse_validate_(x, asLogical(maybe_modify));  
 }  
40    
41  SEXP Csparse_validate_(SEXP x, Rboolean maybe_modify)  #define _t_Csparse_validate
42  {  #include "t_Csparse_validate.c"
     /* 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);  
43    
44      if (length(pslot) != dims[1] + 1)  #define _t_Csparse_sort
45          return mkString(_("slot p must have length = ncol(.) + 1"));  #include "t_Csparse_validate.c"
     if (xp[0] != 0)  
         return mkString(_("first element of slot p must be zero"));  
     if (length(islot) < xp[ncol]) /* allow larger slots from over-allocation!*/  
         return  
             mkString(_("last element of slot p must match length of slots i and x"));  
     for (j = 0; j < xp[ncol]; j++) {  
         if (xi[j] < 0 || xi[j] >= nrow)  
             return mkString(_("all row indices must be between 0 and nrow-1"));  
     }  
     sorted = TRUE; strictly = TRUE;  
     for (j = 0; j < ncol; j++) {  
         if (xp[j] > xp[j + 1])  
             return mkString(_("slot p must be non-decreasing"));  
         if(sorted) /* only act if >= 2 entries in column j : */  
             for (k = xp[j] + 1; k < xp[j + 1]; k++) {  
                 if (xi[k] < xi[k - 1])  
                     sorted = FALSE;  
                 else if (xi[k] == xi[k - 1])  
                     strictly = FALSE;  
             }  
     }  
     if (!sorted) {  
         if(maybe_modify) {  
             CHM_SP chx = (CHM_SP) alloca(sizeof(cholmod_sparse));  
             R_CheckStack();  
             as_cholmod_sparse(chx, x, FALSE, TRUE);/*-> cholmod_l_sort() ! */  
             /* as chx = AS_CHM_SP__(x)  but  ^^^^ sorting x in_place !!! */  
46    
47              /* Now re-check that row indices are *strictly* increasing  // R: .validateCsparse(x, sort.if.needed = FALSE) :
48               * (and not just increasing) within each column : */  SEXP Csparse_validate2(SEXP x, SEXP maybe_modify) {
49              for (j = 0; j < ncol; j++) {      return Csparse_validate_(x, asLogical(maybe_modify));
                 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)"));  
             }  
         } else { /* no modifying sorting : */  
             return mkString(_("row indices are not sorted within columns"));  
         }  
     } else if(!strictly) {  /* sorted, but not strictly */  
         return mkString(_("slot i is not *strictly* increasing inside a column"));  
50      }      }
51      return ScalarLogical(1);  
52    // R: Matrix:::.sortCsparse(x) :
53    SEXP Csparse_sort (SEXP x) {
54       int ok = Csparse_sort_2(x, TRUE); // modifying x directly
55       if(!ok) warning(_("Csparse_sort(x): x is not a valid (apart from sorting) CsparseMatrix"));
56       return x;
57  }  }
58    
59  SEXP Rsparse_validate(SEXP x)  SEXP Rsparse_validate(SEXP x)
# Line 136  Line 93 
93              }              }
94      }      }
95      if (!sorted)      if (!sorted)
96          /* cannot easily use cholmod_l_sort(.) ... -> "error out" :*/          /* cannot easily use cholmod_sort(.) ... -> "error out" :*/
97          return mkString(_("slot j is not increasing inside a column"));          return mkString(_("slot j is not increasing inside a column"));
98      else if(!strictly) /* sorted, but not strictly */      else if(!strictly) /* sorted, but not strictly */
99          return mkString(_("slot j is not *strictly* increasing inside a column"));          return mkString(_("slot j is not *strictly* increasing inside a column"));
# Line 144  Line 101 
101      return ScalarLogical(1);      return ScalarLogical(1);
102  }  }
103    
104    /**
105  /* Called from ../R/Csparse.R : */   * From a CsparseMatrix, produce a dense one.
106  /* Can only return [dln]geMatrix (no symm/triang);   * Directly deals with symmetric, triangular and general.
107   * FIXME: replace by non-CHOLMOD code ! */   * Called from ../R/Csparse.R's  C2dense()
108  SEXP Csparse_to_dense(SEXP x)   *
109     * @param x a CsparseMatrix: currently all 9 of  "[dln][gst]CMatrix"
110     * @param symm_or_tri integer (NA, < 0, > 0, = 0) specifying the knowledge of the caller about x:
111     *      NA  : unknown => will be determined
112     *      = 0 : "generalMatrix" (not symm or tri);
113     *      < 0 : "triangularMatrix"
114     *      > 0 : "symmetricMatrix"
115     *
116     * @return a "denseMatrix"
117     */
118    SEXP Csparse_to_dense(SEXP x, SEXP symm_or_tri)
119  {  {
120      CHM_SP chxs = AS_CHM_SP__(x);      Rboolean is_sym, is_tri;
121      /* This loses the symmetry property, since cholmod_dense has none,      int is_sym_or_tri = asInteger(symm_or_tri),
122            ctype = 0; // <- default = "dgC"
123        static const char *valid[] = { MATRIX_VALID_Csparse, ""};
124        if(is_sym_or_tri == NA_INTEGER) { // find if  is(x, "symmetricMatrix") :
125            ctype = Matrix_check_class_etc(x, valid);
126            is_sym = (ctype % 3 == 1);
127            is_tri = (ctype % 3 == 2);
128        } else {
129            is_sym = is_sym_or_tri > 0;
130            is_tri = is_sym_or_tri < 0;
131            // => both are FALSE  iff  is_.. == 0
132            if(is_sym || is_tri)
133                ctype = Matrix_check_class_etc(x, valid);
134        }
135        CHM_SP chxs = AS_CHM_SP__(x);// -> chxs->stype = +- 1 <==> symmetric
136        R_CheckStack();
137        if(is_tri && *diag_P(x) == 'U') { // ==>  x := diagU2N(x), directly for chxs
138            CHM_SP eye = cholmod_speye(chxs->nrow, chxs->ncol, chxs->xtype, &c);
139            double one[] = {1, 0};
140            CHM_SP ans = cholmod_add(chxs, eye, one, one,
141                                     /* values: */ ((ctype / 3) != 2), // TRUE iff not "nMatrix"
142                                     TRUE, &c);
143            cholmod_free_sparse(&eye, &c);
144            chxs = cholmod_copy_sparse(ans, &c);
145            cholmod_free_sparse(&ans, &c);
146        }
147        /* The following loses the symmetry property, since cholmod_dense has none,
148       * BUT, much worse (FIXME!), it also transforms CHOLMOD_PATTERN ("n") matrices       * BUT, much worse (FIXME!), it also transforms CHOLMOD_PATTERN ("n") matrices
149       * to numeric (CHOLMOD_REAL) ones : */       * to numeric (CHOLMOD_REAL) ones {and we "revert" via chm_dense_to_SEXP()}: */
150      CHM_DN chxd = cholmod_l_sparse_to_dense(chxs, &c);      CHM_DN chxd = cholmod_sparse_to_dense(chxs, &c);
151      int Rkind = (chxs->xtype == CHOLMOD_PATTERN)? -1 : Real_kind(x);      int Rkind = (chxs->xtype == CHOLMOD_PATTERN)? -1 : Real_kind(x);
     R_CheckStack();  
152    
153      return chm_dense_to_SEXP(chxd, 1, Rkind, GET_SLOT(x, Matrix_DimNamesSym));      SEXP ans = chm_dense_to_SEXP(chxd, 1, Rkind,GET_SLOT(x, Matrix_DimNamesSym));
154        // -> a [dln]geMatrix
155        if(is_sym) { // ==> want  [dln]syMatrix
156            const char cl1 = class_P(ans)[0];
157            PROTECT(ans);
158            SEXP aa = PROTECT(NEW_OBJECT(MAKE_CLASS((cl1 == 'd') ? "dsyMatrix" :
159                                                    ((cl1 == 'l') ? "lsyMatrix" : "nsyMatrix"))));
160            // No need to duplicate() as slots of ans are freshly allocated and ans will not be used
161            SET_SLOT(aa, Matrix_xSym,       GET_SLOT(ans, Matrix_xSym));
162            SET_SLOT(aa, Matrix_DimSym,     GET_SLOT(ans, Matrix_DimSym));
163            SET_SLOT(aa, Matrix_DimNamesSym,GET_SLOT(ans, Matrix_DimNamesSym));
164            SET_SLOT(aa, Matrix_uploSym, mkString((chxs->stype > 0) ? "U" : "L"));
165            UNPROTECT(2);
166            return aa;
167        }
168        else if(is_tri) { // ==> want  [dln]trMatrix
169            const char cl1 = class_P(ans)[0];
170            PROTECT(ans);
171            SEXP aa = PROTECT(NEW_OBJECT(MAKE_CLASS((cl1 == 'd') ? "dtrMatrix" :
172                                                    ((cl1 == 'l') ? "ltrMatrix" : "ntrMatrix"))));
173            // No need to duplicate() as slots of ans are freshly allocated and ans will not be used
174            SET_SLOT(aa, Matrix_xSym,       GET_SLOT(ans, Matrix_xSym));
175            SET_SLOT(aa, Matrix_DimSym,     GET_SLOT(ans, Matrix_DimSym));
176            SET_SLOT(aa, Matrix_DimNamesSym,GET_SLOT(ans, Matrix_DimNamesSym));
177            slot_dup(aa, x, Matrix_uploSym);
178            /* already by NEW_OBJECT(..) above:
179               SET_SLOT(aa, Matrix_diagSym, mkString("N")); */
180            UNPROTECT(2);
181            return aa;
182        }
183        else
184            return ans;
185  }  }
186    
187    // FIXME: do not go via CHM (should not be too hard, to just *drop* the x-slot, right?
188  SEXP Csparse_to_nz_pattern(SEXP x, SEXP tri)  SEXP Csparse_to_nz_pattern(SEXP x, SEXP tri)
189  {  {
190      CHM_SP chxs = AS_CHM_SP__(x);      CHM_SP chxs = AS_CHM_SP__(x);
191      CHM_SP chxcp = cholmod_l_copy(chxs, chxs->stype, CHOLMOD_PATTERN, &c);      CHM_SP chxcp = cholmod_copy(chxs, chxs->stype, CHOLMOD_PATTERN, &c);
192      int tr = asLogical(tri);      int tr = asLogical(tri);
193      R_CheckStack();      R_CheckStack();
194    
# Line 174  Line 198 
198                                GET_SLOT(x, Matrix_DimNamesSym));                                GET_SLOT(x, Matrix_DimNamesSym));
199  }  }
200    
201  SEXP Csparse_to_matrix(SEXP x)  // n.CMatrix --> [dli].CMatrix  (not going through CHM!)
202    SEXP nz_pattern_to_Csparse(SEXP x, SEXP res_kind)
203    {
204        return nz2Csparse(x, asInteger(res_kind));
205    }
206    
207    // n.CMatrix --> [dli].CMatrix  (not going through CHM!)
208    // NOTE: use chm_MOD_xtype(() to change type of  'cholmod_sparse' matrix
209    SEXP nz2Csparse(SEXP x, enum x_slot_kind r_kind)
210  {  {
211      return chm_dense_to_matrix(cholmod_l_sparse_to_dense(AS_CHM_SP__(x), &c),      const char *cl_x = class_P(x);
212                                 1 /*do_free*/, GET_SLOT(x, Matrix_DimNamesSym));      if(cl_x[0] != 'n') error(_("not a 'n.CMatrix'"));
213        if(cl_x[2] != 'C') error(_("not a CsparseMatrix"));
214        int nnz = LENGTH(GET_SLOT(x, Matrix_iSym));
215        SEXP ans;
216        char *ncl = alloca(strlen(cl_x) + 1); /* not much memory required */
217        strcpy(ncl, cl_x);
218        double *dx_x; int *ix_x;
219        ncl[0] = (r_kind == x_double ? 'd' :
220                  (r_kind == x_logical ? 'l' :
221                   /* else (for now):  r_kind == x_integer : */ 'i'));
222        PROTECT(ans = NEW_OBJECT(MAKE_CLASS(ncl)));
223        // create a correct 'x' slot:
224        switch(r_kind) {
225            int i;
226        case x_double: // 'd'
227            dx_x = REAL(ALLOC_SLOT(ans, Matrix_xSym, REALSXP, nnz));
228            for (i=0; i < nnz; i++) dx_x[i] = 1.;
229            break;
230        case x_logical: // 'l'
231            ix_x = LOGICAL(ALLOC_SLOT(ans, Matrix_xSym, LGLSXP, nnz));
232            for (i=0; i < nnz; i++) ix_x[i] = TRUE;
233            break;
234        case x_integer: // 'i'
235            ix_x = INTEGER(ALLOC_SLOT(ans, Matrix_xSym, INTSXP, nnz));
236            for (i=0; i < nnz; i++) ix_x[i] = 1;
237            break;
238    
239        default:
240            error(_("nz2Csparse(): invalid/non-implemented r_kind = %d"),
241                  r_kind);
242        }
243    
244        // now copy all other slots :
245        slot_dup(ans, x, Matrix_iSym);
246        slot_dup(ans, x, Matrix_pSym);
247        slot_dup(ans, x, Matrix_DimSym);
248        slot_dup(ans, x, Matrix_DimNamesSym);
249        if(ncl[1] != 'g') { // symmetric or triangular ...
250            slot_dup_if_has(ans, x, Matrix_uploSym);
251            slot_dup_if_has(ans, x, Matrix_diagSym);
252        }
253        UNPROTECT(1);
254        return ans;
255    }
256    
257    SEXP Csparse_to_matrix(SEXP x, SEXP chk, SEXP symm)
258    {
259        int is_sym = asLogical(symm);
260        if(is_sym == NA_LOGICAL) { // find if  is(x, "symmetricMatrix") :
261            static const char *valid[] = { MATRIX_VALID_Csparse, ""};
262            int ctype = Matrix_check_class_etc(x, valid);
263            is_sym = (ctype % 3 == 1);
264        }
265        return chm_dense_to_matrix(
266            cholmod_sparse_to_dense(AS_CHM_SP2(x, asLogical(chk)), &c),
267            1 /*do_free*/,
268            (is_sym
269             ? symmetric_DimNames(GET_SLOT(x, Matrix_DimNamesSym))
270             :                    GET_SLOT(x, Matrix_DimNamesSym)));
271    }
272    
273    SEXP Csparse_to_vector(SEXP x)
274    {
275        return chm_dense_to_vector(cholmod_sparse_to_dense(AS_CHM_SP__(x), &c), 1);
276  }  }
277    
278  SEXP Csparse_to_Tsparse(SEXP x, SEXP tri)  SEXP Csparse_to_Tsparse(SEXP x, SEXP tri)
279  {  {
280      CHM_SP chxs = AS_CHM_SP__(x);      CHM_SP chxs = AS_CHM_SP__(x);
281      CHM_TR chxt = cholmod_l_sparse_to_triplet(chxs, &c);      CHM_TR chxt = cholmod_sparse_to_triplet(chxs, &c);
282      int tr = asLogical(tri);      int tr = asLogical(tri);
283      int Rkind = (chxs->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chxs->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
284      R_CheckStack();      R_CheckStack();
# Line 194  Line 289 
289                                 GET_SLOT(x, Matrix_DimNamesSym));                                 GET_SLOT(x, Matrix_DimNamesSym));
290  }  }
291    
292  /* this used to be called  sCMatrix_to_gCMatrix(..)   [in ./dsCMatrix.c ]: */  SEXP Csparse_to_tCsparse(SEXP x, SEXP uplo, SEXP diag)
293    {
294        CHM_SP chxs = AS_CHM_SP__(x);
295        int Rkind = (chxs->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
296        R_CheckStack();
297        return chm_sparse_to_SEXP(chxs, /* dofree = */ 0,
298                                  /* uploT = */ (*CHAR(asChar(uplo)) == 'U')? 1: -1,
299                                   Rkind, /* diag = */ CHAR(STRING_ELT(diag, 0)),
300                                   GET_SLOT(x, Matrix_DimNamesSym));
301    }
302    
303    SEXP Csparse_to_tTsparse(SEXP x, SEXP uplo, SEXP diag)
304    {
305        CHM_SP chxs = AS_CHM_SP__(x);
306        CHM_TR chxt = cholmod_sparse_to_triplet(chxs, &c);
307        int Rkind = (chxs->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
308        R_CheckStack();
309        return chm_triplet_to_SEXP(chxt, 1,
310                                  /* uploT = */ (*CHAR(asChar(uplo)) == 'U')? 1: -1,
311                                   Rkind, /* diag = */ CHAR(STRING_ELT(diag, 0)),
312                                   GET_SLOT(x, Matrix_DimNamesSym));
313    }
314    
315    
316  SEXP Csparse_symmetric_to_general(SEXP x)  SEXP Csparse_symmetric_to_general(SEXP x)
317  {  {
318      CHM_SP chx = AS_CHM_SP__(x), chgx;      CHM_SP chx = AS_CHM_SP__(x), chgx;
# Line 203  Line 321 
321    
322      if (!(chx->stype))      if (!(chx->stype))
323          error(_("Nonsymmetric matrix in Csparse_symmetric_to_general"));          error(_("Nonsymmetric matrix in Csparse_symmetric_to_general"));
324      chgx = cholmod_l_copy(chx, /* stype: */ 0, chx->xtype, &c);      chgx = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);
325      /* xtype: pattern, "real", complex or .. */      /* xtype: pattern, "real", complex or .. */
326      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",
327                                GET_SLOT(x, Matrix_DimNamesSym));                                symmetric_DimNames(GET_SLOT(x, Matrix_DimNamesSym)));
328  }  }
329    
330  SEXP Csparse_general_to_symmetric(SEXP x, SEXP uplo)  SEXP Csparse_general_to_symmetric(SEXP x, SEXP uplo, SEXP sym_dmns)
331  {  {
332        int *adims = INTEGER(GET_SLOT(x, Matrix_DimSym)), n = adims[0];
333        if(n != adims[1]) {
334            error(_("Csparse_general_to_symmetric(): matrix is not square!"));
335            return R_NilValue; /* -Wall */
336        }
337      CHM_SP chx = AS_CHM_SP__(x), chgx;      CHM_SP chx = AS_CHM_SP__(x), chgx;
338      int uploT = (*CHAR(STRING_ELT(uplo,0)) == 'U') ? 1 : -1;      int uploT = (*CHAR(asChar(uplo)) == 'U') ? 1 : -1;
339      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
340      R_CheckStack();      R_CheckStack();
341        chgx = cholmod_copy(chx, /* stype: */ uploT, chx->xtype, &c);
342    
343      chgx = cholmod_l_copy(chx, /* stype: */ uploT, chx->xtype, &c);      SEXP dns = GET_SLOT(x, Matrix_DimNamesSym);
344        if(asLogical(sym_dmns))
345            dns = symmetric_DimNames(dns);
346        else if((!isNull(VECTOR_ELT(dns, 0)) &&
347                 !isNull(VECTOR_ELT(dns, 1))) ||
348                !isNull(getAttrib(dns, R_NamesSymbol))) {
349            /* symmetrize them if both are not NULL
350             * or names(dimnames(.)) is asymmetric : */
351            dns = PROTECT(duplicate(dns));
352            if(!equal_string_vectors(VECTOR_ELT(dns, 0),
353                                     VECTOR_ELT(dns, 1))) {
354                if(uploT == 1)
355                    SET_VECTOR_ELT(dns, 0, VECTOR_ELT(dns,1));
356                else
357                    SET_VECTOR_ELT(dns, 1, VECTOR_ELT(dns,0));
358            }
359            SEXP nms_dns = getAttrib(dns, R_NamesSymbol);
360            if(!isNull(nms_dns) &&  // names(dimnames(.)) :
361               !R_compute_identical(STRING_ELT(nms_dns, 0),
362                                    STRING_ELT(nms_dns, 1), 16)) {
363                if(uploT == 1)
364                    SET_STRING_ELT(nms_dns, 0, STRING_ELT(nms_dns,1));
365                else
366                    SET_STRING_ELT(nms_dns, 1, STRING_ELT(nms_dns,0));
367                setAttrib(dns, R_NamesSymbol, nms_dns);
368            }
369            UNPROTECT(1);
370        }
371      /* xtype: pattern, "real", complex or .. */      /* xtype: pattern, "real", complex or .. */
372      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "", dns);
                               GET_SLOT(x, Matrix_DimNamesSym));  
373  }  }
374    
375  SEXP Csparse_transpose(SEXP x, SEXP tri)  SEXP Csparse_transpose(SEXP x, SEXP tri)
# Line 228  Line 378 
378       *       since cholmod (& cs) lacks sparse 'int' matrices */       *       since cholmod (& cs) lacks sparse 'int' matrices */
379      CHM_SP chx = AS_CHM_SP__(x);      CHM_SP chx = AS_CHM_SP__(x);
380      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
381      CHM_SP chxt = cholmod_l_transpose(chx, chx->xtype, &c);      CHM_SP chxt = cholmod_transpose(chx, chx->xtype, &c);
382      SEXP dn = PROTECT(duplicate(GET_SLOT(x, Matrix_DimNamesSym))), tmp;      SEXP dn = PROTECT(duplicate(GET_SLOT(x, Matrix_DimNamesSym))), tmp;
383      int tr = asLogical(tri);      int tr = asLogical(tri);
384      R_CheckStack();      R_CheckStack();
# Line 236  Line 386 
386      tmp = VECTOR_ELT(dn, 0);    /* swap the dimnames */      tmp = VECTOR_ELT(dn, 0);    /* swap the dimnames */
387      SET_VECTOR_ELT(dn, 0, VECTOR_ELT(dn, 1));      SET_VECTOR_ELT(dn, 0, VECTOR_ELT(dn, 1));
388      SET_VECTOR_ELT(dn, 1, tmp);      SET_VECTOR_ELT(dn, 1, tmp);
389        if(!isNull(tmp = getAttrib(dn, R_NamesSymbol))) { // swap names(dimnames(.)):
390            SEXP nms_dns = PROTECT(allocVector(VECSXP, 2));
391            SET_VECTOR_ELT(nms_dns, 1, STRING_ELT(tmp, 0));
392            SET_VECTOR_ELT(nms_dns, 0, STRING_ELT(tmp, 1));
393            setAttrib(dn, R_NamesSymbol, nms_dns);
394            UNPROTECT(1);
395        }
396      UNPROTECT(1);      UNPROTECT(1);
397      return chm_sparse_to_SEXP(chxt, 1, /* SWAP 'uplo' for triangular */      return chm_sparse_to_SEXP(chxt, 1, /* SWAP 'uplo' for triangular */
398                                tr ? ((*uplo_P(x) == 'U') ? -1 : 1) : 0,                                tr ? ((*uplo_P(x) == 'U') ? -1 : 1) : 0,
# Line 247  Line 404 
404      CHM_SP      CHM_SP
405          cha = AS_CHM_SP(a),          cha = AS_CHM_SP(a),
406          chb = AS_CHM_SP(b),          chb = AS_CHM_SP(b),
407          chc = cholmod_l_ssmult(cha, chb, /*out_stype:*/ 0,          chc = cholmod_ssmult(cha, chb, /*out_stype:*/ 0,
408                                 /* values:= is_numeric (T/F) */ cha->xtype > 0,                                 /* values:= is_numeric (T/F) */ cha->xtype > 0,
409                                 /*out sorted:*/ 1, &c);                                 /*out sorted:*/ 1, &c);
410      const char *cl_a = class_P(a), *cl_b = class_P(b);      const char *cl_a = class_P(a), *cl_b = class_P(b);
# Line 298  Line 455 
455      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2));
456      R_CheckStack();      R_CheckStack();
457    
458      chTr = cholmod_l_transpose((tr) ? chb : cha, chb->xtype, &c);      chTr = cholmod_transpose((tr) ? chb : cha, chb->xtype, &c);
459      chc = cholmod_l_ssmult((tr) ? cha : chTr, (tr) ? chTr : chb,      chc = cholmod_ssmult((tr) ? cha : chTr, (tr) ? chTr : chb,
460                           /*out_stype:*/ 0, cha->xtype, /*out sorted:*/ 1, &c);                           /*out_stype:*/ 0, cha->xtype, /*out sorted:*/ 1, &c);
461      cholmod_l_free_sparse(&chTr, &c);      cholmod_free_sparse(&chTr, &c);
462    
463      /* Preserve triangularity and unit-triangularity if appropriate;      /* Preserve triangularity and unit-triangularity if appropriate;
464       * see Csparse_Csparse_prod() for comments */       * see Csparse_Csparse_prod() for comments */
# Line 325  Line 482 
482  SEXP Csparse_dense_prod(SEXP a, SEXP b)  SEXP Csparse_dense_prod(SEXP a, SEXP b)
483  {  {
484      CHM_SP cha = AS_CHM_SP(a);      CHM_SP cha = AS_CHM_SP(a);
485      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix(b));      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix2(b, // transpose_if_vector =
486                                                 cha->ncol == 1));
487      CHM_DN chb = AS_CHM_DN(b_M);      CHM_DN chb = AS_CHM_DN(b_M);
488      CHM_DN chc = cholmod_l_allocate_dense(cha->nrow, chb->ncol, cha->nrow,      CHM_DN chc = cholmod_allocate_dense(cha->nrow, chb->ncol, cha->nrow,
489                                          chb->xtype, &c);                                          chb->xtype, &c);
490      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2));
491      double one[] = {1,0}, zero[] = {0,0};      double one[] = {1,0}, zero[] = {0,0};
492        int nprot = 2;
493      R_CheckStack();      R_CheckStack();
494        /* Tim Davis, please FIXME:  currently (2010-11) *fails* when  a  is a pattern matrix:*/
495      cholmod_l_sdmult(cha, 0, one, zero, chb, chc, &c);      if(cha->xtype == CHOLMOD_PATTERN) {
496            /* warning(_("Csparse_dense_prod(): cholmod_sdmult() not yet implemented for pattern./ ngCMatrix" */
497            /*        " --> slightly inefficient coercion")); */
498    
499            // This *fails* to produce a CHOLMOD_REAL ..
500            // CHM_SP chd = cholmod_l_copy(cha, cha->stype, CHOLMOD_REAL, &c);
501            // --> use our Matrix-classes
502            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
503            cha = AS_CHM_SP(da);
504        }
505        cholmod_sdmult(cha, 0, one, zero, chb, chc, &c);
506      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
507                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));
508      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
509                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));
510      UNPROTECT(2);      UNPROTECT(nprot);
511      return chm_dense_to_SEXP(chc, 1, 0, dn);      return chm_dense_to_SEXP(chc, 1, 0, dn);
512  }  }
513    
514  SEXP Csparse_dense_crossprod(SEXP a, SEXP b)  SEXP Csparse_dense_crossprod(SEXP a, SEXP b)
515  {  {
516      CHM_SP cha = AS_CHM_SP(a);      CHM_SP cha = AS_CHM_SP(a);
517      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix(b));      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix2(b, // transpose_if_vector =
518                                                 cha->nrow == 1));
519      CHM_DN chb = AS_CHM_DN(b_M);      CHM_DN chb = AS_CHM_DN(b_M);
520      CHM_DN chc = cholmod_l_allocate_dense(cha->ncol, chb->ncol, cha->ncol,      CHM_DN chc = cholmod_allocate_dense(cha->ncol, chb->ncol, cha->ncol,
521                                          chb->xtype, &c);                                          chb->xtype, &c);
522      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2)); int nprot = 2;
523      double one[] = {1,0}, zero[] = {0,0};      double one[] = {1,0}, zero[] = {0,0};
524      R_CheckStack();      R_CheckStack();
525        // -- see Csparse_dense_prod() above :
526      cholmod_l_sdmult(cha, 1, one, zero, chb, chc, &c);      if(cha->xtype == CHOLMOD_PATTERN) {
527            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
528            cha = AS_CHM_SP(da);
529        }
530        cholmod_sdmult(cha, 1, one, zero, chb, chc, &c);
531      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
532                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 1)));
533      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
534                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));
535      UNPROTECT(2);      UNPROTECT(nprot);
536      return chm_dense_to_SEXP(chc, 1, 0, dn);      return chm_dense_to_SEXP(chc, 1, 0, dn);
537  }  }
538    
# Line 376  Line 550 
550  #endif  #endif
551      CHM_SP chcp, chxt,      CHM_SP chcp, chxt,
552          chx = (trip ?          chx = (trip ?
553                 cholmod_l_triplet_to_sparse(cht, cht->nnz, &c) :                 cholmod_triplet_to_sparse(cht, cht->nnz, &c) :
554                 AS_CHM_SP(x));                 AS_CHM_SP(x));
555      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2));
556      R_CheckStack();      R_CheckStack();
557    
558      if (!tr) chxt = cholmod_l_transpose(chx, chx->xtype, &c);      if (!tr) chxt = cholmod_transpose(chx, chx->xtype, &c);
559      chcp = cholmod_l_aat((!tr) ? chxt : chx, (int *) NULL, 0, chx->xtype, &c);      chcp = cholmod_aat((!tr) ? chxt : chx, (int *) NULL, 0, chx->xtype, &c);
560      if(!chcp) {      if(!chcp) {
561          UNPROTECT(1);          UNPROTECT(1);
562          error(_("Csparse_crossprod(): error return from cholmod_l_aat()"));          error(_("Csparse_crossprod(): error return from cholmod_aat()"));
563      }      }
564      cholmod_l_band_inplace(0, chcp->ncol, chcp->xtype, chcp, &c);      cholmod_band_inplace(0, chcp->ncol, chcp->xtype, chcp, &c);
565      chcp->stype = 1;      chcp->stype = 1;
566      if (trip) cholmod_l_free_sparse(&chx, &c);      if (trip) cholmod_free_sparse(&chx, &c);
567      if (!tr) cholmod_l_free_sparse(&chxt, &c);      if (!tr) cholmod_free_sparse(&chxt, &c);
568      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
569                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),
570                                          (tr) ? 0 : 1)));                                          (tr) ? 0 : 1)));
# Line 403  Line 577 
577      return chm_sparse_to_SEXP(chcp, 1, 0, 0, "", dn);      return chm_sparse_to_SEXP(chcp, 1, 0, 0, "", dn);
578  }  }
579    
580    /* Csparse_drop(x, tol):  drop entries with absolute value < tol, i.e,
581    *  at least all "explicit" zeros */
582  SEXP Csparse_drop(SEXP x, SEXP tol)  SEXP Csparse_drop(SEXP x, SEXP tol)
583  {  {
584      const char *cl = class_P(x);      const char *cl = class_P(x);
585      /* dtCMatrix, etc; [1] = the second character =?= 't' for triangular */      /* dtCMatrix, etc; [1] = the second character =?= 't' for triangular */
586      int tr = (cl[1] == 't');      int tr = (cl[1] == 't');
587      CHM_SP chx = AS_CHM_SP__(x);      CHM_SP chx = AS_CHM_SP__(x);
588      CHM_SP ans = cholmod_l_copy(chx, chx->stype, chx->xtype, &c);      CHM_SP ans = cholmod_copy(chx, chx->stype, chx->xtype, &c);
589      double dtol = asReal(tol);      double dtol = asReal(tol);
590      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
591      R_CheckStack();      R_CheckStack();
592    
593      if(!cholmod_l_drop(dtol, ans, &c))      if(!cholmod_drop(dtol, ans, &c))
594          error(_("cholmod_l_drop() failed"));          error(_("cholmod_drop() failed"));
595      return chm_sparse_to_SEXP(ans, 1,      return chm_sparse_to_SEXP(ans, 1,
596                                tr ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,                                tr ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,
597                                Rkind, tr ? diag_P(x) : "",                                Rkind, tr ? diag_P(x) : "",
# Line 424  Line 600 
600    
601  SEXP Csparse_horzcat(SEXP x, SEXP y)  SEXP Csparse_horzcat(SEXP x, SEXP y)
602  {  {
603      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);  #define CSPARSE_CAT(_KIND_)                                             \
604      int Rk_x = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0,      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);                  \
605          Rk_y = (chy->xtype != CHOLMOD_PATTERN) ? Real_kind(y) : 0,      R_CheckStack();                                                     \
606          Rkind = /* logical if both x and y are */ (Rk_x == 1 && Rk_y == 1) ? 1 : 0;      int Rk_x = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : -3,     \
607      R_CheckStack();          Rk_y = (chy->xtype != CHOLMOD_PATTERN) ? Real_kind(y) : -3, Rkind; \
608        if(Rk_x == -3 || Rk_y == -3) { /* at least one of them is patter"n" */ \
609            if(Rk_x == -3 && Rk_y == -3) { /* fine */                       \
610            } else { /* only one is a patter"n"                             \
611                      * "Bug" in cholmod_horzcat()/vertcat(): returns patter"n" matrix if one of them is */ \
612                Rboolean ok;                                                \
613                if(Rk_x == -3) {                                            \
614                    ok = chm_MOD_xtype(CHOLMOD_REAL, chx, &c); Rk_x = 0;    \
615                } else if(Rk_y == -3) {                                     \
616                    ok = chm_MOD_xtype(CHOLMOD_REAL, chy, &c); Rk_y = 0;    \
617                } else                                                      \
618                    error(_("Impossible Rk_x/Rk_y in Csparse_%s(), please report"), _KIND_); \
619                if(!ok)                                                     \
620                    error(_("chm_MOD_xtype() was not successful in Csparse_%s(), please report"), \
621                          _KIND_);                                          \
622            }                                                               \
623        }                                                                   \
624        Rkind = /* logical if both x and y are */ (Rk_x == 1 && Rk_y == 1) ? 1 : 0
625    
626      /* TODO: currently drops dimnames - and we fix at R level */      CSPARSE_CAT("horzcat");
627      return chm_sparse_to_SEXP(cholmod_l_horzcat(chx, chy, 1, &c),      // TODO: currently drops dimnames - and we fix at R level;
628    
629        return chm_sparse_to_SEXP(cholmod_horzcat(chx, chy, 1, &c),
630                                1, 0, Rkind, "", R_NilValue);                                1, 0, Rkind, "", R_NilValue);
631  }  }
632    
633  SEXP Csparse_vertcat(SEXP x, SEXP y)  SEXP Csparse_vertcat(SEXP x, SEXP y)
634  {  {
635      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);      CSPARSE_CAT("vertcat");
636      int Rk_x = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0,      // TODO: currently drops dimnames - and we fix at R level;
         Rk_y = (chy->xtype != CHOLMOD_PATTERN) ? Real_kind(y) : 0,  
         Rkind = /* logical if both x and y are */ (Rk_x == 1 && Rk_y == 1) ? 1 : 0;  
     R_CheckStack();  
637    
638      /* TODO: currently drops dimnames - and we fix at R level */      return chm_sparse_to_SEXP(cholmod_vertcat(chx, chy, 1, &c),
     return chm_sparse_to_SEXP(cholmod_l_vertcat(chx, chy, 1, &c),  
639                                1, 0, Rkind, "", R_NilValue);                                1, 0, Rkind, "", R_NilValue);
640  }  }
641    
# Line 452  Line 643 
643  {  {
644      CHM_SP chx = AS_CHM_SP__(x);      CHM_SP chx = AS_CHM_SP__(x);
645      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
646      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);
647      R_CheckStack();      R_CheckStack();
648    
649      return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "",      return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "",
# Line 470  Line 661 
661      }      }
662      else { /* unit triangular (diag='U'): "fill the diagonal" & diag:= "N" */      else { /* unit triangular (diag='U'): "fill the diagonal" & diag:= "N" */
663          CHM_SP chx = AS_CHM_SP__(x);          CHM_SP chx = AS_CHM_SP__(x);
664          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);
665          double one[] = {1, 0};          double one[] = {1, 0};
666          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);
667          int uploT = (*uplo_P(x) == 'U') ? 1 : -1;          int uploT = (*uplo_P(x) == 'U') ? 1 : -1;
668          int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;          int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
669    
670          R_CheckStack();          R_CheckStack();
671          cholmod_l_free_sparse(&eye, &c);          cholmod_free_sparse(&eye, &c);
672          return chm_sparse_to_SEXP(ans, 1, uploT, Rkind, "N",          return chm_sparse_to_SEXP(ans, 1, uploT, Rkind, "N",
673                                    GET_SLOT(x, Matrix_DimNamesSym));                                    GET_SLOT(x, Matrix_DimNamesSym));
674      }      }
# Line 494  Line 685 
685      }      }
686      else { /* triangular with diag='N'): now drop the diagonal */      else { /* triangular with diag='N'): now drop the diagonal */
687          /* duplicate, since chx will be modified: */          /* duplicate, since chx will be modified: */
688          CHM_SP chx = AS_CHM_SP__(duplicate(x));          SEXP xx = PROTECT(duplicate(x));
689            CHM_SP chx = AS_CHM_SP__(xx);
690          int uploT = (*uplo_P(x) == 'U') ? 1 : -1,          int uploT = (*uplo_P(x) == 'U') ? 1 : -1,
691              Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;              Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
692          R_CheckStack();          R_CheckStack();
693    
694          chm_diagN2U(chx, uploT, /* do_realloc */ FALSE);          chm_diagN2U(chx, uploT, /* do_realloc */ FALSE);
695    
696          return chm_sparse_to_SEXP(chx, /*dofree*/ 0/* or 1 ?? */,          SEXP ans = chm_sparse_to_SEXP(chx, /*dofree*/ 0/* or 1 ?? */,
697                                    uploT, Rkind, "U",                                    uploT, Rkind, "U",
698                                    GET_SLOT(x, Matrix_DimNamesSym));                                    GET_SLOT(x, Matrix_DimNamesSym));
699            UNPROTECT(1);// only now !
700            return ans;
701      }      }
702  }  }
703    
# Line 529  Line 723 
723      if (csize >= 0 && !isInteger(j))      if (csize >= 0 && !isInteger(j))
724          error(_("Index j must be NULL or integer"));          error(_("Index j must be NULL or integer"));
725    
726      if (chx->stype) /* symmetricMatrix */  #define CHM_SUB(_M_, _i_, _j_)                                  \
727        cholmod_submatrix(_M_,                                      \
728                          (rsize < 0) ? NULL : INTEGER(_i_), rsize, \
729                          (csize < 0) ? NULL : INTEGER(_j_), csize, \
730                          TRUE, TRUE, &c)
731        CHM_SP ans;
732        if (!chx->stype) {/* non-symmetric Matrix */
733            ans = CHM_SUB(chx, i, j);
734        }
735        else {
736          /* for now, cholmod_submatrix() only accepts "generalMatrix" */          /* for now, cholmod_submatrix() only accepts "generalMatrix" */
737          chx = cholmod_l_copy(chx, /* stype: */ 0, chx->xtype, &c);          CHM_SP tmp = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);
738            ans = CHM_SUB(tmp, i, j);
739            cholmod_free_sparse(&tmp, &c);
740        }
741    
742      return chm_sparse_to_SEXP(cholmod_l_submatrix(chx,      // "FIXME": currently dropping dimnames, and adding them afterwards in R :
743                                  (rsize < 0) ? NULL : INTEGER(i), rsize,      /* // dimnames: */
744                                  (csize < 0) ? NULL : INTEGER(j), csize,      /* SEXP x_dns = GET_SLOT(x, Matrix_DimNamesSym), */
745                                                    TRUE, TRUE, &c),      /*  dn = PROTECT(allocVector(VECSXP, 2)); */
746                                1, 0, Rkind, "",      return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "", /* dimnames: */ R_NilValue);
                               /* FIXME: drops dimnames */ R_NilValue);  
747  }  }
748    
749    #define _d_Csp_
750    #include "t_Csparse_subassign.c"
751    
752    #define _l_Csp_
753    #include "t_Csparse_subassign.c"
754    
755    #define _i_Csp_
756    #include "t_Csparse_subassign.c"
757    
758    #define _n_Csp_
759    #include "t_Csparse_subassign.c"
760    
761    #define _z_Csp_
762    #include "t_Csparse_subassign.c"
763    
764    
765    
766  SEXP Csparse_MatrixMarket(SEXP x, SEXP fname)  SEXP Csparse_MatrixMarket(SEXP x, SEXP fname)
767  {  {
768      FILE *f = fopen(CHAR(asChar(fname)), "w");      FILE *f = fopen(CHAR(asChar(fname)), "w");
# Line 548  Line 770 
770      if (!f)      if (!f)
771          error(_("failure to open file \"%s\" for writing"),          error(_("failure to open file \"%s\" for writing"),
772                CHAR(asChar(fname)));                CHAR(asChar(fname)));
773      if (!cholmod_l_write_sparse(f, AS_CHM_SP(x),      if (!cholmod_write_sparse(f, AS_CHM_SP(x),
774                                (CHM_SP)NULL, (char*) NULL, &c))                                (CHM_SP)NULL, (char*) NULL, &c))
775          error(_("cholmod_l_write_sparse returned error code"));          error(_("cholmod_write_sparse returned error code"));
776      fclose(f);      fclose(f);
777      return R_NilValue;      return R_NilValue;
778  }  }
# Line 568  Line 790 
790   *   *
791   * @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
792   */   */
793  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,
794  /*                                ^^^^^^ FIXME[Generalize] to int / ... */  /*                                ^^^^^^ FIXME[Generalize] to int / ... */
795                     SEXP resultKind)
796  {  {
797      const char* res_ch = CHAR(STRING_ELT(resultKind,0));      const char* res_ch = CHAR(STRING_ELT(resultKind,0));
798      enum diag_kind { diag, diag_backpermuted, trace, prod, sum_log      enum diag_kind { diag, diag_backpermuted, trace, prod, sum_log, min, max, range
799      } res_kind = ((!strcmp(res_ch, "trace")) ? trace :      } res_kind = ((!strcmp(res_ch, "trace")) ? trace :
800                    ((!strcmp(res_ch, "sumLog")) ? sum_log :                    ((!strcmp(res_ch, "sumLog")) ? sum_log :
801                     ((!strcmp(res_ch, "prod")) ? prod :                     ((!strcmp(res_ch, "prod")) ? prod :
802                        ((!strcmp(res_ch, "min")) ? min :
803                         ((!strcmp(res_ch, "max")) ? max :
804                          ((!strcmp(res_ch, "range")) ? range :
805                      ((!strcmp(res_ch, "diag")) ? diag :                      ((!strcmp(res_ch, "diag")) ? diag :
806                       ((!strcmp(res_ch, "diagBack")) ? diag_backpermuted :                       ((!strcmp(res_ch, "diagBack")) ? diag_backpermuted :
807                        -1)))));                           -1))))))));
808      int i, n_x, i_from = 0;      int i, n_x, i_from;
809      SEXP ans = PROTECT(allocVector(REALSXP,      SEXP ans = PROTECT(allocVector(REALSXP,
810  /*                                 ^^^^  FIXME[Generalize] */  /*                                 ^^^^  FIXME[Generalize] */
811                                     (res_kind == diag ||                                     (res_kind == diag ||
812                                      res_kind == diag_backpermuted) ? n : 1));                                      res_kind == diag_backpermuted) ? n :
813                                       (res_kind == range ? 2 : 1)));
814      double *v = REAL(ans);      double *v = REAL(ans);
815  /*  ^^^^^^      ^^^^  FIXME[Generalize] */  /*  ^^^^^^      ^^^^  FIXME[Generalize] */
816    
817        i_from = (is_U ? -1 : 0);
818    
819  #define for_DIAG(v_ASSIGN)                                              \  #define for_DIAG(v_ASSIGN)                                              \
820      for(i = 0; i < n; i++, i_from += n_x) {                             \      for(i = 0; i < n; i++) {                                    \
821          /* looking at i-th column */                                    \          /* looking at i-th column */                                    \
822          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 */ \
823            if( is_U) i_from += n_x;                                \
824          v_ASSIGN;                                                       \          v_ASSIGN;                                                       \
825            if(!is_U) i_from += n_x;                                \
826      }      }
827    
828      /* NOTA BENE: we assume  -- uplo = "L" i.e. lower triangular matrix      /* NOTA BENE: we assume  -- uplo = "L" i.e. lower triangular matrix
829       *            for uplo = "U" (makes sense with a "dtCMatrix" !),       *            for uplo = "U" (makes sense with a "dtCMatrix" !),
830       *            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],
831       *            where nx = (x_p[i+1] - x_p[i])       *            where n_x = (x_p[i+1] - x_p[i])
832       */       */
833    
834      switch(res_kind) {      switch(res_kind) {
835      case trace:      case trace: // = sum
836          v[0] = 0.;          v[0] = 0.;
837          for_DIAG(v[0] += x_x[i_from]);          for_DIAG(v[0] += x_x[i_from]);
838          break;          break;
# Line 616  Line 847 
847          for_DIAG(v[0] *= x_x[i_from]);          for_DIAG(v[0] *= x_x[i_from]);
848          break;          break;
849    
850        case min:
851            v[0] = R_PosInf;
852            for_DIAG(if(v[0] > x_x[i_from]) v[0] = x_x[i_from]);
853            break;
854    
855        case max:
856            v[0] = R_NegInf;
857            for_DIAG(if(v[0] < x_x[i_from]) v[0] = x_x[i_from]);
858            break;
859    
860        case range:
861            v[0] = R_PosInf;
862            v[1] = R_NegInf;
863            for_DIAG(if(v[0] > x_x[i_from]) v[0] = x_x[i_from];
864                     if(v[1] < x_x[i_from]) v[1] = x_x[i_from]);
865            break;
866    
867      case diag:      case diag:
868          for_DIAG(v[i] = x_x[i_from]);          for_DIAG(v[i] = x_x[i_from]);
869          break;          break;
# Line 623  Line 871 
871      case diag_backpermuted:      case diag_backpermuted:
872          for_DIAG(v[i] = x_x[i_from]);          for_DIAG(v[i] = x_x[i_from]);
873    
874          warning(_("resultKind = 'diagBack' (back-permuted) is experimental"));          warning(_("%s = '%s' (back-permuted) is experimental"),
875                    "resultKind", "diagBack");
876          /* now back_permute : */          /* now back_permute : */
877          for(i = 0; i < n; i++) {          for(i = 0; i < n; i++) {
878              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 644  Line 893 
893   * Extract the diagonal entries from *triangular* Csparse matrix  __or__ a   * Extract the diagonal entries from *triangular* Csparse matrix  __or__ a
894   * cholmod_sparse factor (LDL = TRUE).   * cholmod_sparse factor (LDL = TRUE).
895   *   *
896     * @param obj -- now a cholmod_sparse factor or a dtCMatrix
897   * @param pslot  'p' (column pointer)   slot of Csparse matrix/factor   * @param pslot  'p' (column pointer)   slot of Csparse matrix/factor
898   * @param xslot  'x' (non-zero entries) slot of Csparse matrix/factor   * @param xslot  'x' (non-zero entries) slot of Csparse matrix/factor
899   * @param perm_slot  'perm' (= permutation vector) slot of corresponding CHMfactor;   * @param perm_slot  'perm' (= permutation vector) slot of corresponding CHMfactor;
# Line 652  Line 902 
902   *   *
903   * @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
904   */   */
905  SEXP diag_tC(SEXP pslot, SEXP xslot, SEXP perm_slot, SEXP resultKind)  SEXP diag_tC(SEXP obj, SEXP resultKind)
906  {  {
907    
908        SEXP
909            pslot = GET_SLOT(obj, Matrix_pSym),
910            xslot = GET_SLOT(obj, Matrix_xSym);
911        Rboolean is_U = (R_has_slot(obj, Matrix_uploSym) &&
912                         *CHAR(asChar(GET_SLOT(obj, Matrix_uploSym))) == 'U');
913      int n = length(pslot) - 1, /* n = ncol(.) = nrow(.) */      int n = length(pslot) - 1, /* n = ncol(.) = nrow(.) */
914          *x_p  = INTEGER(pslot),          *x_p  = INTEGER(pslot), pp = -1, *perm;
         *perm = INTEGER(perm_slot);  
915      double *x_x = REAL(xslot);      double *x_x = REAL(xslot);
916  /*  ^^^^^^        ^^^^ FIXME[Generalize] to INTEGER(.) / LOGICAL(.) / ... xslot !*/  /*  ^^^^^^        ^^^^ FIXME[Generalize] to INTEGER(.) / LOGICAL(.) / ... xslot !*/
917    
918      return diag_tC_ptr(n, x_p, x_x, perm, resultKind);      if(R_has_slot(obj, Matrix_permSym))
919            perm = INTEGER(GET_SLOT(obj, Matrix_permSym));
920        else perm = &pp;
921    
922        return diag_tC_ptr(n, x_p, x_x, is_U, perm, resultKind);
923  }  }
924    
925    
926  /**  /**
927   * Create a Csparse matrix object from indices and/or pointers.   * Create a Csparse matrix object from indices and/or pointers.
928   *   *
# Line 764  Line 1024 
1024      if (cls[1] != 'g')      if (cls[1] != 'g')
1025          error(_("Only 'g'eneral sparse matrix types allowed"));          error(_("Only 'g'eneral sparse matrix types allowed"));
1026                                  /* allocate and populate the triplet */                                  /* allocate and populate the triplet */
1027      T = cholmod_l_allocate_triplet((size_t)nrow, (size_t)ncol, (size_t)nnz, 0,      T = cholmod_allocate_triplet((size_t)nrow, (size_t)ncol, (size_t)nnz, 0,
1028                                      xtype, &c);                                      xtype, &c);
1029      T->x = x;      T->x = x;
1030      tri = (int*)T->i;      tri = (int*)T->i;
# Line 774  Line 1034 
1034          trj[ii] = j[ii] - ((!mj && index1) ? 1 : 0);          trj[ii] = j[ii] - ((!mj && index1) ? 1 : 0);
1035      }      }
1036                                  /* create the cholmod_sparse structure */                                  /* create the cholmod_sparse structure */
1037      A = cholmod_l_triplet_to_sparse(T, nnz, &c);      A = cholmod_triplet_to_sparse(T, nnz, &c);
1038      cholmod_l_free_triplet(&T, &c);      cholmod_free_triplet(&T, &c);
1039                                  /* copy the information to the SEXP */                                  /* copy the information to the SEXP */
1040      ans = PROTECT(NEW_OBJECT(MAKE_CLASS(cls)));      ans = PROTECT(NEW_OBJECT(MAKE_CLASS(cls)));
1041  /* FIXME: This has been copied from chm_sparse_to_SEXP in chm_common.c */  // FIXME: This has been copied from chm_sparse_to_SEXP in  chm_common.c
1042                                  /* allocate and copy common slots */                                  /* allocate and copy common slots */
1043      nnz = cholmod_l_nnz(A, &c);      nnz = cholmod_nnz(A, &c);
1044      dims = INTEGER(ALLOC_SLOT(ans, Matrix_DimSym, INTSXP, 2));      dims = INTEGER(ALLOC_SLOT(ans, Matrix_DimSym, INTSXP, 2));
1045      dims[0] = A->nrow; dims[1] = A->ncol;      dims[0] = A->nrow; dims[1] = A->ncol;
1046      Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_pSym, INTSXP, A->ncol + 1)), (int*)A->p, A->ncol + 1);      Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_pSym, INTSXP, A->ncol + 1)), (int*)A->p, A->ncol + 1);
# Line 792  Line 1052 
1052      case 'l':      case 'l':
1053          error(_("code not yet written for cls = \"lgCMatrix\""));          error(_("code not yet written for cls = \"lgCMatrix\""));
1054      }      }
1055      cholmod_l_free_sparse(&A, &c);  /* FIXME: dimnames are *NOT* put there yet (if non-NULL) */
1056        cholmod_free_sparse(&A, &c);
1057      UNPROTECT(1);      UNPROTECT(1);
1058      return ans;      return ans;
1059  }  }

Legend:
Removed from v.2586  
changed lines
  Added in v.3055

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