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 3066, Thu Mar 19 14:27:05 2015 UTC
# Line 1  Line 1 
1                          /* Sparse matrices in compressed column-oriented form */                          /* Sparse matrices in compressed column-oriented form */
2    
3  #include "Csparse.h"  #include "Csparse.h"
4  #include "Tsparse.h"  #include "Tsparse.h"
5  #include "chm_common.h"  #include "chm_common.h"
# Line 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) if _one_ is numeric:
409                                 cha->xtype > 0 || chb->xtype > 0,
410                                 /*out sorted:*/ 1, &c);                                 /*out sorted:*/ 1, &c);
411      const char *cl_a = class_P(a), *cl_b = class_P(b);      const char *cl_a = class_P(a), *cl_b = class_P(b);
412      char diag[] = {'\0', '\0'};      char diag[] = {'\0', '\0'};
# Line 298  Line 456 
456      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2));
457      R_CheckStack();      R_CheckStack();
458    
459      chTr = cholmod_l_transpose((tr) ? chb : cha, chb->xtype, &c);      chTr = cholmod_transpose((tr) ? chb : cha, chb->xtype, &c);
460      chc = cholmod_l_ssmult((tr) ? cha : chTr, (tr) ? chTr : chb,      chc = cholmod_ssmult((tr) ? cha : chTr, (tr) ? chTr : chb,
461                           /*out_stype:*/ 0, cha->xtype, /*out sorted:*/ 1, &c);                           /*out_stype:*/ 0, cha->xtype, /*out sorted:*/ 1, &c);
462      cholmod_l_free_sparse(&chTr, &c);      cholmod_free_sparse(&chTr, &c);
463    
464      /* Preserve triangularity and unit-triangularity if appropriate;      /* Preserve triangularity and unit-triangularity if appropriate;
465       * see Csparse_Csparse_prod() for comments */       * see Csparse_Csparse_prod() for comments */
# Line 325  Line 483 
483  SEXP Csparse_dense_prod(SEXP a, SEXP b)  SEXP Csparse_dense_prod(SEXP a, SEXP b)
484  {  {
485      CHM_SP cha = AS_CHM_SP(a);      CHM_SP cha = AS_CHM_SP(a);
486      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix(b));      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix2(b, // transpose_if_vector =
487                                                 cha->ncol == 1));
488      CHM_DN chb = AS_CHM_DN(b_M);      CHM_DN chb = AS_CHM_DN(b_M);
489      CHM_DN chc = cholmod_l_allocate_dense(cha->nrow, chb->ncol, cha->nrow,      CHM_DN chc = cholmod_allocate_dense(cha->nrow, chb->ncol, cha->nrow,
490                                          chb->xtype, &c);                                          chb->xtype, &c);
491      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2));
492      double one[] = {1,0}, zero[] = {0,0};      double one[] = {1,0}, zero[] = {0,0};
493        int nprot = 2;
494      R_CheckStack();      R_CheckStack();
495        /* Tim Davis, please FIXME:  currently (2010-11) *fails* when  a  is a pattern matrix:*/
496      cholmod_l_sdmult(cha, 0, one, zero, chb, chc, &c);      if(cha->xtype == CHOLMOD_PATTERN) {
497            /* warning(_("Csparse_dense_prod(): cholmod_sdmult() not yet implemented for pattern./ ngCMatrix" */
498            /*        " --> slightly inefficient coercion")); */
499    
500            // This *fails* to produce a CHOLMOD_REAL ..
501            // CHM_SP chd = cholmod_l_copy(cha, cha->stype, CHOLMOD_REAL, &c);
502            // --> use our Matrix-classes
503            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
504            cha = AS_CHM_SP(da);
505        }
506        cholmod_sdmult(cha, 0, one, zero, chb, chc, &c);
507      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
508                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));
509      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
510                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));
511      UNPROTECT(2);      UNPROTECT(nprot);
512      return chm_dense_to_SEXP(chc, 1, 0, dn);      return chm_dense_to_SEXP(chc, 1, 0, dn);
513  }  }
514    
515  SEXP Csparse_dense_crossprod(SEXP a, SEXP b)  SEXP Csparse_dense_crossprod(SEXP a, SEXP b)
516  {  {
517      CHM_SP cha = AS_CHM_SP(a);      CHM_SP cha = AS_CHM_SP(a);
518      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix(b));      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix2(b, // transpose_if_vector =
519                                                 cha->nrow == 1));
520      CHM_DN chb = AS_CHM_DN(b_M);      CHM_DN chb = AS_CHM_DN(b_M);
521      CHM_DN chc = cholmod_l_allocate_dense(cha->ncol, chb->ncol, cha->ncol,      CHM_DN chc = cholmod_allocate_dense(cha->ncol, chb->ncol, cha->ncol,
522                                          chb->xtype, &c);                                          chb->xtype, &c);
523      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2)); int nprot = 2;
524      double one[] = {1,0}, zero[] = {0,0};      double one[] = {1,0}, zero[] = {0,0};
525      R_CheckStack();      R_CheckStack();
526        // -- see Csparse_dense_prod() above :
527      cholmod_l_sdmult(cha, 1, one, zero, chb, chc, &c);      if(cha->xtype == CHOLMOD_PATTERN) {
528            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
529            cha = AS_CHM_SP(da);
530        }
531        cholmod_sdmult(cha, 1, one, zero, chb, chc, &c);
532      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
533                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 1)));
534      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
535                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));
536      UNPROTECT(2);      UNPROTECT(nprot);
537      return chm_dense_to_SEXP(chc, 1, 0, dn);      return chm_dense_to_SEXP(chc, 1, 0, dn);
538  }  }
539    
# Line 376  Line 551 
551  #endif  #endif
552      CHM_SP chcp, chxt,      CHM_SP chcp, chxt,
553          chx = (trip ?          chx = (trip ?
554                 cholmod_l_triplet_to_sparse(cht, cht->nnz, &c) :                 cholmod_triplet_to_sparse(cht, cht->nnz, &c) :
555                 AS_CHM_SP(x));                 AS_CHM_SP(x));
556      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2));
557      R_CheckStack();      R_CheckStack();
558    
559      if (!tr) chxt = cholmod_l_transpose(chx, chx->xtype, &c);      if (!tr) chxt = cholmod_transpose(chx, chx->xtype, &c);
560      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);
561      if(!chcp) {      if(!chcp) {
562          UNPROTECT(1);          UNPROTECT(1);
563          error(_("Csparse_crossprod(): error return from cholmod_l_aat()"));          error(_("Csparse_crossprod(): error return from cholmod_aat()"));
564      }      }
565      cholmod_l_band_inplace(0, chcp->ncol, chcp->xtype, chcp, &c);      cholmod_band_inplace(0, chcp->ncol, chcp->xtype, chcp, &c);
566      chcp->stype = 1;      chcp->stype = 1;
567      if (trip) cholmod_l_free_sparse(&chx, &c);      if (trip) cholmod_free_sparse(&chx, &c);
568      if (!tr) cholmod_l_free_sparse(&chxt, &c);      if (!tr) cholmod_free_sparse(&chxt, &c);
569      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
570                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),
571                                          (tr) ? 0 : 1)));                                          (tr) ? 0 : 1)));
# Line 403  Line 578 
578      return chm_sparse_to_SEXP(chcp, 1, 0, 0, "", dn);      return chm_sparse_to_SEXP(chcp, 1, 0, 0, "", dn);
579  }  }
580    
581    /* Csparse_drop(x, tol):  drop entries with absolute value < tol, i.e,
582    *  at least all "explicit" zeros */
583  SEXP Csparse_drop(SEXP x, SEXP tol)  SEXP Csparse_drop(SEXP x, SEXP tol)
584  {  {
585      const char *cl = class_P(x);      const char *cl = class_P(x);
586      /* dtCMatrix, etc; [1] = the second character =?= 't' for triangular */      /* dtCMatrix, etc; [1] = the second character =?= 't' for triangular */
587      int tr = (cl[1] == 't');      int tr = (cl[1] == 't');
588      CHM_SP chx = AS_CHM_SP__(x);      CHM_SP chx = AS_CHM_SP__(x);
589      CHM_SP ans = cholmod_l_copy(chx, chx->stype, chx->xtype, &c);      CHM_SP ans = cholmod_copy(chx, chx->stype, chx->xtype, &c);
590      double dtol = asReal(tol);      double dtol = asReal(tol);
591      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
592      R_CheckStack();      R_CheckStack();
593    
594      if(!cholmod_l_drop(dtol, ans, &c))      if(!cholmod_drop(dtol, ans, &c))
595          error(_("cholmod_l_drop() failed"));          error(_("cholmod_drop() failed"));
596      return chm_sparse_to_SEXP(ans, 1,      return chm_sparse_to_SEXP(ans, 1,
597                                tr ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,                                tr ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,
598                                Rkind, tr ? diag_P(x) : "",                                Rkind, tr ? diag_P(x) : "",
# Line 424  Line 601 
601    
602  SEXP Csparse_horzcat(SEXP x, SEXP y)  SEXP Csparse_horzcat(SEXP x, SEXP y)
603  {  {
604      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);  #define CSPARSE_CAT(_KIND_)                                             \
605      int Rk_x = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0,      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);                  \
606          Rk_y = (chy->xtype != CHOLMOD_PATTERN) ? Real_kind(y) : 0,      R_CheckStack();                                                     \
607          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,     \
608      R_CheckStack();          Rk_y = (chy->xtype != CHOLMOD_PATTERN) ? Real_kind(y) : -3, Rkind; \
609        if(Rk_x == -3 || Rk_y == -3) { /* at least one of them is patter"n" */ \
610            if(Rk_x == -3 && Rk_y == -3) { /* fine */                       \
611            } else { /* only one is a patter"n"                             \
612                      * "Bug" in cholmod_horzcat()/vertcat(): returns patter"n" matrix if one of them is */ \
613                Rboolean ok;                                                \
614                if(Rk_x == -3) {                                            \
615                    ok = chm_MOD_xtype(CHOLMOD_REAL, chx, &c); Rk_x = 0;    \
616                } else if(Rk_y == -3) {                                     \
617                    ok = chm_MOD_xtype(CHOLMOD_REAL, chy, &c); Rk_y = 0;    \
618                } else                                                      \
619                    error(_("Impossible Rk_x/Rk_y in Csparse_%s(), please report"), _KIND_); \
620                if(!ok)                                                     \
621                    error(_("chm_MOD_xtype() was not successful in Csparse_%s(), please report"), \
622                          _KIND_);                                          \
623            }                                                               \
624        }                                                                   \
625        Rkind = /* logical if both x and y are */ (Rk_x == 1 && Rk_y == 1) ? 1 : 0
626    
627      /* TODO: currently drops dimnames - and we fix at R level */      CSPARSE_CAT("horzcat");
628      return chm_sparse_to_SEXP(cholmod_l_horzcat(chx, chy, 1, &c),      // TODO: currently drops dimnames - and we fix at R level;
629    
630        return chm_sparse_to_SEXP(cholmod_horzcat(chx, chy, 1, &c),
631                                1, 0, Rkind, "", R_NilValue);                                1, 0, Rkind, "", R_NilValue);
632  }  }
633    
634  SEXP Csparse_vertcat(SEXP x, SEXP y)  SEXP Csparse_vertcat(SEXP x, SEXP y)
635  {  {
636      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);      CSPARSE_CAT("vertcat");
637      int 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();  
638    
639      /* 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),  
640                                1, 0, Rkind, "", R_NilValue);                                1, 0, Rkind, "", R_NilValue);
641  }  }
642    
# Line 452  Line 644 
644  {  {
645      CHM_SP chx = AS_CHM_SP__(x);      CHM_SP chx = AS_CHM_SP__(x);
646      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
647      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);
648      R_CheckStack();      R_CheckStack();
649    
650      return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "",      return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "",
# Line 470  Line 662 
662      }      }
663      else { /* unit triangular (diag='U'): "fill the diagonal" & diag:= "N" */      else { /* unit triangular (diag='U'): "fill the diagonal" & diag:= "N" */
664          CHM_SP chx = AS_CHM_SP__(x);          CHM_SP chx = AS_CHM_SP__(x);
665          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);
666          double one[] = {1, 0};          double one[] = {1, 0};
667          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);
668          int uploT = (*uplo_P(x) == 'U') ? 1 : -1;          int uploT = (*uplo_P(x) == 'U') ? 1 : -1;
669          int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;          int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
670    
671          R_CheckStack();          R_CheckStack();
672          cholmod_l_free_sparse(&eye, &c);          cholmod_free_sparse(&eye, &c);
673          return chm_sparse_to_SEXP(ans, 1, uploT, Rkind, "N",          return chm_sparse_to_SEXP(ans, 1, uploT, Rkind, "N",
674                                    GET_SLOT(x, Matrix_DimNamesSym));                                    GET_SLOT(x, Matrix_DimNamesSym));
675      }      }
# Line 494  Line 686 
686      }      }
687      else { /* triangular with diag='N'): now drop the diagonal */      else { /* triangular with diag='N'): now drop the diagonal */
688          /* duplicate, since chx will be modified: */          /* duplicate, since chx will be modified: */
689          CHM_SP chx = AS_CHM_SP__(duplicate(x));          SEXP xx = PROTECT(duplicate(x));
690            CHM_SP chx = AS_CHM_SP__(xx);
691          int uploT = (*uplo_P(x) == 'U') ? 1 : -1,          int uploT = (*uplo_P(x) == 'U') ? 1 : -1,
692              Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;              Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
693          R_CheckStack();          R_CheckStack();
694    
695          chm_diagN2U(chx, uploT, /* do_realloc */ FALSE);          chm_diagN2U(chx, uploT, /* do_realloc */ FALSE);
696    
697          return chm_sparse_to_SEXP(chx, /*dofree*/ 0/* or 1 ?? */,          SEXP ans = chm_sparse_to_SEXP(chx, /*dofree*/ 0/* or 1 ?? */,
698                                    uploT, Rkind, "U",                                    uploT, Rkind, "U",
699                                    GET_SLOT(x, Matrix_DimNamesSym));                                    GET_SLOT(x, Matrix_DimNamesSym));
700            UNPROTECT(1);// only now !
701            return ans;
702      }      }
703  }  }
704    
# Line 529  Line 724 
724      if (csize >= 0 && !isInteger(j))      if (csize >= 0 && !isInteger(j))
725          error(_("Index j must be NULL or integer"));          error(_("Index j must be NULL or integer"));
726    
727      if (chx->stype) /* symmetricMatrix */  #define CHM_SUB(_M_, _i_, _j_)                                  \
728        cholmod_submatrix(_M_,                                      \
729                          (rsize < 0) ? NULL : INTEGER(_i_), rsize, \
730                          (csize < 0) ? NULL : INTEGER(_j_), csize, \
731                          TRUE, TRUE, &c)
732        CHM_SP ans;
733        if (!chx->stype) {/* non-symmetric Matrix */
734            ans = CHM_SUB(chx, i, j);
735        }
736        else {
737          /* for now, cholmod_submatrix() only accepts "generalMatrix" */          /* for now, cholmod_submatrix() only accepts "generalMatrix" */
738          chx = cholmod_l_copy(chx, /* stype: */ 0, chx->xtype, &c);          CHM_SP tmp = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);
739            ans = CHM_SUB(tmp, i, j);
740            cholmod_free_sparse(&tmp, &c);
741        }
742    
743      return chm_sparse_to_SEXP(cholmod_l_submatrix(chx,      // "FIXME": currently dropping dimnames, and adding them afterwards in R :
744                                  (rsize < 0) ? NULL : INTEGER(i), rsize,      /* // dimnames: */
745                                  (csize < 0) ? NULL : INTEGER(j), csize,      /* SEXP x_dns = GET_SLOT(x, Matrix_DimNamesSym), */
746                                                    TRUE, TRUE, &c),      /*  dn = PROTECT(allocVector(VECSXP, 2)); */
747                                1, 0, Rkind, "",      return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "", /* dimnames: */ R_NilValue);
                               /* FIXME: drops dimnames */ R_NilValue);  
748  }  }
749    
750    #define _d_Csp_
751    #include "t_Csparse_subassign.c"
752    
753    #define _l_Csp_
754    #include "t_Csparse_subassign.c"
755    
756    #define _i_Csp_
757    #include "t_Csparse_subassign.c"
758    
759    #define _n_Csp_
760    #include "t_Csparse_subassign.c"
761    
762    #define _z_Csp_
763    #include "t_Csparse_subassign.c"
764    
765    
766    
767  SEXP Csparse_MatrixMarket(SEXP x, SEXP fname)  SEXP Csparse_MatrixMarket(SEXP x, SEXP fname)
768  {  {
769      FILE *f = fopen(CHAR(asChar(fname)), "w");      FILE *f = fopen(CHAR(asChar(fname)), "w");
# Line 548  Line 771 
771      if (!f)      if (!f)
772          error(_("failure to open file \"%s\" for writing"),          error(_("failure to open file \"%s\" for writing"),
773                CHAR(asChar(fname)));                CHAR(asChar(fname)));
774      if (!cholmod_l_write_sparse(f, AS_CHM_SP(x),      if (!cholmod_write_sparse(f, AS_CHM_SP(x),
775                                (CHM_SP)NULL, (char*) NULL, &c))                                (CHM_SP)NULL, (char*) NULL, &c))
776          error(_("cholmod_l_write_sparse returned error code"));          error(_("cholmod_write_sparse returned error code"));
777      fclose(f);      fclose(f);
778      return R_NilValue;      return R_NilValue;
779  }  }
# Line 568  Line 791 
791   *   *
792   * @return  a SEXP, either a (double) number or a length n-vector of diagonal entries   * @return  a SEXP, either a (double) number or a length n-vector of diagonal entries
793   */   */
794  SEXP diag_tC_ptr(int n, int *x_p, double *x_x, int *perm, SEXP resultKind)  SEXP diag_tC_ptr(int n, int *x_p, double *x_x, Rboolean is_U, int *perm,
795  /*                                ^^^^^^ FIXME[Generalize] to int / ... */  /*                                ^^^^^^ FIXME[Generalize] to int / ... */
796                     SEXP resultKind)
797  {  {
798      const char* res_ch = CHAR(STRING_ELT(resultKind,0));      const char* res_ch = CHAR(STRING_ELT(resultKind,0));
799      enum diag_kind { diag, diag_backpermuted, trace, prod, sum_log      enum diag_kind { diag, diag_backpermuted, trace, prod, sum_log, min, max, range
800      } res_kind = ((!strcmp(res_ch, "trace")) ? trace :      } res_kind = ((!strcmp(res_ch, "trace")) ? trace :
801                    ((!strcmp(res_ch, "sumLog")) ? sum_log :                    ((!strcmp(res_ch, "sumLog")) ? sum_log :
802                     ((!strcmp(res_ch, "prod")) ? prod :                     ((!strcmp(res_ch, "prod")) ? prod :
803                        ((!strcmp(res_ch, "min")) ? min :
804                         ((!strcmp(res_ch, "max")) ? max :
805                          ((!strcmp(res_ch, "range")) ? range :
806                      ((!strcmp(res_ch, "diag")) ? diag :                      ((!strcmp(res_ch, "diag")) ? diag :
807                       ((!strcmp(res_ch, "diagBack")) ? diag_backpermuted :                       ((!strcmp(res_ch, "diagBack")) ? diag_backpermuted :
808                        -1)))));                           -1))))))));
809      int i, n_x, i_from = 0;      int i, n_x, i_from;
810      SEXP ans = PROTECT(allocVector(REALSXP,      SEXP ans = PROTECT(allocVector(REALSXP,
811  /*                                 ^^^^  FIXME[Generalize] */  /*                                 ^^^^  FIXME[Generalize] */
812                                     (res_kind == diag ||                                     (res_kind == diag ||
813                                      res_kind == diag_backpermuted) ? n : 1));                                      res_kind == diag_backpermuted) ? n :
814                                       (res_kind == range ? 2 : 1)));
815      double *v = REAL(ans);      double *v = REAL(ans);
816  /*  ^^^^^^      ^^^^  FIXME[Generalize] */  /*  ^^^^^^      ^^^^  FIXME[Generalize] */
817    
818        i_from = (is_U ? -1 : 0);
819    
820  #define for_DIAG(v_ASSIGN)                                              \  #define for_DIAG(v_ASSIGN)                                              \
821      for(i = 0; i < n; i++, i_from += n_x) {                             \      for(i = 0; i < n; i++) {                                    \
822          /* looking at i-th column */                                    \          /* looking at i-th column */                                    \
823          n_x = x_p[i+1] - x_p[i];/* #{entries} in this column */ \          n_x = x_p[i+1] - x_p[i];/* #{entries} in this column */ \
824            if( is_U) i_from += n_x;                                \
825          v_ASSIGN;                                                       \          v_ASSIGN;                                                       \
826            if(!is_U) i_from += n_x;                                \
827      }      }
828    
829      /* NOTA BENE: we assume  -- uplo = "L" i.e. lower triangular matrix      /* NOTA BENE: we assume  -- uplo = "L" i.e. lower triangular matrix
830       *            for uplo = "U" (makes sense with a "dtCMatrix" !),       *            for uplo = "U" (makes sense with a "dtCMatrix" !),
831       *            should use  x_x[i_from + (nx - 1)] instead of x_x[i_from],       *            should use  x_x[i_from + (n_x - 1)] instead of x_x[i_from],
832       *            where nx = (x_p[i+1] - x_p[i])       *            where n_x = (x_p[i+1] - x_p[i])
833       */       */
834    
835      switch(res_kind) {      switch(res_kind) {
836      case trace:      case trace: // = sum
837          v[0] = 0.;          v[0] = 0.;
838          for_DIAG(v[0] += x_x[i_from]);          for_DIAG(v[0] += x_x[i_from]);
839          break;          break;
# Line 616  Line 848 
848          for_DIAG(v[0] *= x_x[i_from]);          for_DIAG(v[0] *= x_x[i_from]);
849          break;          break;
850    
851        case min:
852            v[0] = R_PosInf;
853            for_DIAG(if(v[0] > x_x[i_from]) v[0] = x_x[i_from]);
854            break;
855    
856        case max:
857            v[0] = R_NegInf;
858            for_DIAG(if(v[0] < x_x[i_from]) v[0] = x_x[i_from]);
859            break;
860    
861        case range:
862            v[0] = R_PosInf;
863            v[1] = R_NegInf;
864            for_DIAG(if(v[0] > x_x[i_from]) v[0] = x_x[i_from];
865                     if(v[1] < x_x[i_from]) v[1] = x_x[i_from]);
866            break;
867    
868      case diag:      case diag:
869          for_DIAG(v[i] = x_x[i_from]);          for_DIAG(v[i] = x_x[i_from]);
870          break;          break;
# Line 623  Line 872 
872      case diag_backpermuted:      case diag_backpermuted:
873          for_DIAG(v[i] = x_x[i_from]);          for_DIAG(v[i] = x_x[i_from]);
874    
875          warning(_("resultKind = 'diagBack' (back-permuted) is experimental"));          warning(_("%s = '%s' (back-permuted) is experimental"),
876                    "resultKind", "diagBack");
877          /* now back_permute : */          /* now back_permute : */
878          for(i = 0; i < n; i++) {          for(i = 0; i < n; i++) {
879              double tmp = v[i]; v[i] = v[perm[i]]; v[perm[i]] = tmp;              double tmp = v[i]; v[i] = v[perm[i]]; v[perm[i]] = tmp;
# Line 644  Line 894 
894   * Extract the diagonal entries from *triangular* Csparse matrix  __or__ a   * Extract the diagonal entries from *triangular* Csparse matrix  __or__ a
895   * cholmod_sparse factor (LDL = TRUE).   * cholmod_sparse factor (LDL = TRUE).
896   *   *
897     * @param obj -- now a cholmod_sparse factor or a dtCMatrix
898   * @param pslot  'p' (column pointer)   slot of Csparse matrix/factor   * @param pslot  'p' (column pointer)   slot of Csparse matrix/factor
899   * @param xslot  'x' (non-zero entries) slot of Csparse matrix/factor   * @param xslot  'x' (non-zero entries) slot of Csparse matrix/factor
900   * @param perm_slot  'perm' (= permutation vector) slot of corresponding CHMfactor;   * @param perm_slot  'perm' (= permutation vector) slot of corresponding CHMfactor;
# Line 652  Line 903 
903   *   *
904   * @return  a SEXP, either a (double) number or a length n-vector of diagonal entries   * @return  a SEXP, either a (double) number or a length n-vector of diagonal entries
905   */   */
906  SEXP diag_tC(SEXP pslot, SEXP xslot, SEXP perm_slot, SEXP resultKind)  SEXP diag_tC(SEXP obj, SEXP resultKind)
907  {  {
908    
909        SEXP
910            pslot = GET_SLOT(obj, Matrix_pSym),
911            xslot = GET_SLOT(obj, Matrix_xSym);
912        Rboolean is_U = (R_has_slot(obj, Matrix_uploSym) &&
913                         *CHAR(asChar(GET_SLOT(obj, Matrix_uploSym))) == 'U');
914      int n = length(pslot) - 1, /* n = ncol(.) = nrow(.) */      int n = length(pslot) - 1, /* n = ncol(.) = nrow(.) */
915          *x_p  = INTEGER(pslot),          *x_p  = INTEGER(pslot), pp = -1, *perm;
         *perm = INTEGER(perm_slot);  
916      double *x_x = REAL(xslot);      double *x_x = REAL(xslot);
917  /*  ^^^^^^        ^^^^ FIXME[Generalize] to INTEGER(.) / LOGICAL(.) / ... xslot !*/  /*  ^^^^^^        ^^^^ FIXME[Generalize] to INTEGER(.) / LOGICAL(.) / ... xslot !*/
918    
919      return diag_tC_ptr(n, x_p, x_x, perm, resultKind);      if(R_has_slot(obj, Matrix_permSym))
920            perm = INTEGER(GET_SLOT(obj, Matrix_permSym));
921        else perm = &pp;
922    
923        return diag_tC_ptr(n, x_p, x_x, is_U, perm, resultKind);
924  }  }
925    
926    
927  /**  /**
928   * Create a Csparse matrix object from indices and/or pointers.   * Create a Csparse matrix object from indices and/or pointers.
929   *   *
# Line 764  Line 1025 
1025      if (cls[1] != 'g')      if (cls[1] != 'g')
1026          error(_("Only 'g'eneral sparse matrix types allowed"));          error(_("Only 'g'eneral sparse matrix types allowed"));
1027                                  /* allocate and populate the triplet */                                  /* allocate and populate the triplet */
1028      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,
1029                                      xtype, &c);                                      xtype, &c);
1030      T->x = x;      T->x = x;
1031      tri = (int*)T->i;      tri = (int*)T->i;
# Line 774  Line 1035 
1035          trj[ii] = j[ii] - ((!mj && index1) ? 1 : 0);          trj[ii] = j[ii] - ((!mj && index1) ? 1 : 0);
1036      }      }
1037                                  /* create the cholmod_sparse structure */                                  /* create the cholmod_sparse structure */
1038      A = cholmod_l_triplet_to_sparse(T, nnz, &c);      A = cholmod_triplet_to_sparse(T, nnz, &c);
1039      cholmod_l_free_triplet(&T, &c);      cholmod_free_triplet(&T, &c);
1040                                  /* copy the information to the SEXP */                                  /* copy the information to the SEXP */
1041      ans = PROTECT(NEW_OBJECT(MAKE_CLASS(cls)));      ans = PROTECT(NEW_OBJECT(MAKE_CLASS(cls)));
1042  /* 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
1043                                  /* allocate and copy common slots */                                  /* allocate and copy common slots */
1044      nnz = cholmod_l_nnz(A, &c);      nnz = cholmod_nnz(A, &c);
1045      dims = INTEGER(ALLOC_SLOT(ans, Matrix_DimSym, INTSXP, 2));      dims = INTEGER(ALLOC_SLOT(ans, Matrix_DimSym, INTSXP, 2));
1046      dims[0] = A->nrow; dims[1] = A->ncol;      dims[0] = A->nrow; dims[1] = A->ncol;
1047      Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_pSym, INTSXP, A->ncol + 1)), (int*)A->p, A->ncol + 1);      Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_pSym, INTSXP, A->ncol + 1)), (int*)A->p, A->ncol + 1);
# Line 792  Line 1053 
1053      case 'l':      case 'l':
1054          error(_("code not yet written for cls = \"lgCMatrix\""));          error(_("code not yet written for cls = \"lgCMatrix\""));
1055      }      }
1056      cholmod_l_free_sparse(&A, &c);  /* FIXME: dimnames are *NOT* put there yet (if non-NULL) */
1057        cholmod_free_sparse(&A, &c);
1058      UNPROTECT(1);      UNPROTECT(1);
1059      return ans;      return ans;
1060  }  }

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

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