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

pkg/src/Csparse.c revision 1657, Wed Nov 1 16:29:53 2006 UTC pkg/Matrix/src/Csparse.c revision 2661, Wed Apr 6 06:55:54 2011 UTC
# Line 1  Line 1 
1                          /* Sparse matrices in compressed column-oriented form */                          /* Sparse matrices in compressed column-oriented form */
2  #include "Csparse.h"  #include "Csparse.h"
3    #include "Tsparse.h"
4  #include "chm_common.h"  #include "chm_common.h"
5    
6  SEXP Csparse_validate(SEXP x)  /** "Cheap" C version of  Csparse_validate() - *not* sorting : */
7    Rboolean isValid_Csparse(SEXP x)
8  {  {
9      /* NB: we do *NOT* check a potential 'x' slot here, at all */      /* NB: we do *NOT* check a potential 'x' slot here, at all */
10      SEXP pslot = GET_SLOT(x, Matrix_pSym),      SEXP pslot = GET_SLOT(x, Matrix_pSym),
11          islot = GET_SLOT(x, Matrix_iSym);          islot = GET_SLOT(x, Matrix_iSym);
12      int j, k, ncol, nrow, sorted,      int *dims = INTEGER(GET_SLOT(x, Matrix_DimSym)), j,
13            nrow = dims[0],
14            ncol = dims[1],
15            *xp = INTEGER(pslot),
16            *xi = INTEGER(islot);
17    
18        if (length(pslot) != dims[1] + 1)
19            return FALSE;
20        if (xp[0] != 0)
21            return FALSE;
22        if (length(islot) < xp[ncol]) /* allow larger slots from over-allocation!*/
23            return FALSE;
24        for (j = 0; j < xp[ncol]; j++) {
25            if (xi[j] < 0 || xi[j] >= nrow)
26                return FALSE;
27        }
28        for (j = 0; j < ncol; j++) {
29            if (xp[j] > xp[j + 1])
30                return FALSE;
31        }
32        return TRUE;
33    }
34    
35    SEXP Csparse_validate(SEXP x) {
36        return Csparse_validate_(x, FALSE);
37    }
38    
39    SEXP Csparse_validate2(SEXP x, SEXP maybe_modify) {
40        return Csparse_validate_(x, asLogical(maybe_modify));
41    }
42    
43    SEXP Csparse_validate_(SEXP x, Rboolean maybe_modify)
44    {
45        /* NB: we do *NOT* check a potential 'x' slot here, at all */
46        SEXP pslot = GET_SLOT(x, Matrix_pSym),
47            islot = GET_SLOT(x, Matrix_iSym);
48        Rboolean sorted, strictly;
49        int j, k,
50          *dims = INTEGER(GET_SLOT(x, Matrix_DimSym)),          *dims = INTEGER(GET_SLOT(x, Matrix_DimSym)),
51            nrow = dims[0],
52            ncol = dims[1],
53          *xp = INTEGER(pslot),          *xp = INTEGER(pslot),
54          *xi = INTEGER(islot);          *xi = INTEGER(islot);
55    
     nrow = dims[0];  
     ncol = dims[1];  
56      if (length(pslot) != dims[1] + 1)      if (length(pslot) != dims[1] + 1)
57          return mkString(_("slot p must have length = ncol(.) + 1"));          return mkString(_("slot p must have length = ncol(.) + 1"));
58      if (xp[0] != 0)      if (xp[0] != 0)
59          return mkString(_("first element of slot p must be zero"));          return mkString(_("first element of slot p must be zero"));
60      if (length(islot) != xp[ncol])      if (length(islot) < xp[ncol]) /* allow larger slots from over-allocation!*/
61          return          return
62              mkString(_("last element of slot p must match length of slots i and x"));              mkString(_("last element of slot p must match length of slots i and x"));
63      for (j = 0; j < length(islot); j++) {      for (j = 0; j < xp[ncol]; j++) {
64          if (xi[j] < 0 || xi[j] >= nrow)          if (xi[j] < 0 || xi[j] >= nrow)
65              return mkString(_("all row indices must be between 0 and nrow-1"));              return mkString(_("all row indices must be between 0 and nrow-1"));
66      }      }
67      sorted = TRUE;      sorted = TRUE; strictly = TRUE;
68      for (j = 0; j < ncol; j++) {      for (j = 0; j < ncol; j++) {
69          if (xp[j] > xp[j+1])          if (xp[j] > xp[j+1])
70              return mkString(_("slot p must be non-decreasing"));              return mkString(_("slot p must be non-decreasing"));
71          for (k = xp[j] + 1; k < xp[j + 1]; k++)          if(sorted) /* only act if >= 2 entries in column j : */
72              if (xi[k] < xi[k - 1]) sorted = FALSE;              for (k = xp[j] + 1; k < xp[j + 1]; k++) {
73                    if (xi[k] < xi[k - 1])
74                        sorted = FALSE;
75                    else if (xi[k] == xi[k - 1])
76                        strictly = FALSE;
77                }
78      }      }
79      if (!sorted) {      if (!sorted) {
80          cholmod_sparse *chx = as_cholmod_sparse(x);          if(maybe_modify) {
81          cholmod_sort(chx, &c);              CHM_SP chx = (CHM_SP) alloca(sizeof(cholmod_sparse));
82          Free(chx);              R_CheckStack();
83                as_cholmod_sparse(chx, x, FALSE, TRUE);/*-> cholmod_l_sort() ! */
84                /* as chx = AS_CHM_SP__(x)  but  ^^^^ sorting x in_place !!! */
85    
86                /* Now re-check that row indices are *strictly* increasing
87                 * (and not just increasing) within each column : */
88                for (j = 0; j < ncol; j++) {
89                    for (k = xp[j] + 1; k < xp[j + 1]; k++)
90                        if (xi[k] == xi[k - 1])
91                            return mkString(_("slot i is not *strictly* increasing inside a column (even after cholmod_l_sort)"));
92                }
93            } else { /* no modifying sorting : */
94                return mkString(_("row indices are not sorted within columns"));
95            }
96        } else if(!strictly) {  /* sorted, but not strictly */
97            return mkString(_("slot i is not *strictly* increasing inside a column"));
98        }
99        return ScalarLogical(1);
100    }
101    
102    SEXP Rsparse_validate(SEXP x)
103    {
104        /* NB: we do *NOT* check a potential 'x' slot here, at all */
105        SEXP pslot = GET_SLOT(x, Matrix_pSym),
106            jslot = GET_SLOT(x, Matrix_jSym);
107        Rboolean sorted, strictly;
108        int i, k,
109            *dims = INTEGER(GET_SLOT(x, Matrix_DimSym)),
110            nrow = dims[0],
111            ncol = dims[1],
112            *xp = INTEGER(pslot),
113            *xj = INTEGER(jslot);
114    
115        if (length(pslot) != dims[0] + 1)
116            return mkString(_("slot p must have length = nrow(.) + 1"));
117        if (xp[0] != 0)
118            return mkString(_("first element of slot p must be zero"));
119        if (length(jslot) < xp[nrow]) /* allow larger slots from over-allocation!*/
120            return
121                mkString(_("last element of slot p must match length of slots j and x"));
122        for (i = 0; i < length(jslot); i++) {
123            if (xj[i] < 0 || xj[i] >= ncol)
124                return mkString(_("all column indices must be between 0 and ncol-1"));
125        }
126        sorted = TRUE; strictly = TRUE;
127        for (i = 0; i < nrow; i++) {
128            if (xp[i] > xp[i+1])
129                return mkString(_("slot p must be non-decreasing"));
130            if(sorted)
131                for (k = xp[i] + 1; k < xp[i + 1]; k++) {
132                    if (xj[k] < xj[k - 1])
133                        sorted = FALSE;
134                    else if (xj[k] == xj[k - 1])
135                        strictly = FALSE;
136                }
137      }      }
138        if (!sorted)
139            /* cannot easily use cholmod_sort(.) ... -> "error out" :*/
140            return mkString(_("slot j is not increasing inside a column"));
141        else if(!strictly) /* sorted, but not strictly */
142            return mkString(_("slot j is not *strictly* increasing inside a column"));
143    
144      return ScalarLogical(1);      return ScalarLogical(1);
145  }  }
146    
147    
148    /* Called from ../R/Csparse.R : */
149    /* Can only return [dln]geMatrix (no symm/triang);
150     * FIXME: replace by non-CHOLMOD code ! */
151  SEXP Csparse_to_dense(SEXP x)  SEXP Csparse_to_dense(SEXP x)
152  {  {
153      cholmod_sparse *chxs = as_cholmod_sparse(x);      CHM_SP chxs = AS_CHM_SP__(x);
154      cholmod_dense *chxd = cholmod_sparse_to_dense(chxs, &c);      /* This loses the symmetry property, since cholmod_dense has none,
155         * BUT, much worse (FIXME!), it also transforms CHOLMOD_PATTERN ("n") matrices
156         * to numeric (CHOLMOD_REAL) ones : */
157        CHM_DN chxd = cholmod_sparse_to_dense(chxs, &c);
158        int Rkind = (chxs->xtype == CHOLMOD_PATTERN)? -1 : Real_kind(x);
159        R_CheckStack();
160    
161      Free(chxs);      return chm_dense_to_SEXP(chxd, 1, Rkind, GET_SLOT(x, Matrix_DimNamesSym));
     return chm_dense_to_SEXP(chxd, 1, Real_kind(x));  
162  }  }
163    
164    // FIXME: do not go via CHM (should not be too hard, to just *drop* the x-slot, right?
165  SEXP Csparse_to_nz_pattern(SEXP x, SEXP tri)  SEXP Csparse_to_nz_pattern(SEXP x, SEXP tri)
166  {  {
167      cholmod_sparse *chxs = as_cholmod_sparse(x);      CHM_SP chxs = AS_CHM_SP__(x);
168      cholmod_sparse      CHM_SP chxcp = cholmod_copy(chxs, chxs->stype, CHOLMOD_PATTERN, &c);
169          *chxcp = cholmod_copy(chxs, chxs->stype, CHOLMOD_PATTERN, &c);      int tr = asLogical(tri);
170      int uploT = 0; char *diag = "";      R_CheckStack();
171    
172      Free(chxs);      return chm_sparse_to_SEXP(chxcp, 1/*do_free*/,
173      if (asLogical(tri)) {       /* triangular sparse matrices */                                tr ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,
174          uploT = (strcmp(CHAR(asChar(GET_SLOT(x, Matrix_uploSym))), "U")) ?                                0, tr ? diag_P(x) : "",
             -1 : 1;  
         diag = CHAR(asChar(GET_SLOT(x, Matrix_diagSym)));  
     }  
     return chm_sparse_to_SEXP(chxcp, 1, uploT, 0, diag,  
175                                GET_SLOT(x, Matrix_DimNamesSym));                                GET_SLOT(x, Matrix_DimNamesSym));
176  }  }
177    
178  SEXP Csparse_to_matrix(SEXP x)  // n.CMatrix --> [dli].CMatrix  (not going through CHM!)
179    SEXP nz_pattern_to_Csparse(SEXP x, SEXP res_kind)
180    {
181        return nz2Csparse(x, asInteger(res_kind));
182    }
183    // n.CMatrix --> [dli].CMatrix  (not going through CHM!)
184    SEXP nz2Csparse(SEXP x, enum x_slot_kind r_kind)
185  {  {
186      cholmod_sparse *chxs = as_cholmod_sparse(x);      const char *cl_x = class_P(x);
187      cholmod_dense *chxd = cholmod_sparse_to_dense(chxs, &c);      if(cl_x[0] != 'n') error(_("not a 'n.CMatrix'"));
188        if(cl_x[2] != 'C') error(_("not a CsparseMatrix"));
189        int nnz = LENGTH(GET_SLOT(x, Matrix_iSym));
190        SEXP ans;
191        char *ncl = strdup(cl_x);
192        double *dx_x; int *ix_x;
193        ncl[0] = (r_kind == x_double ? 'd' :
194                  (r_kind == x_logical ? 'l' :
195                   /* else (for now):  r_kind == x_integer : */ 'i'));
196        PROTECT(ans = NEW_OBJECT(MAKE_CLASS(ncl)));
197        // create a correct 'x' slot:
198        switch(r_kind) {
199            int i;
200        case x_double: // 'd'
201            dx_x = REAL(ALLOC_SLOT(ans, Matrix_xSym, REALSXP, nnz));
202            for (i=0; i < nnz; i++) dx_x[i] = 1.;
203            break;
204        case x_logical: // 'l'
205            ix_x = LOGICAL(ALLOC_SLOT(ans, Matrix_xSym, LGLSXP, nnz));
206            for (i=0; i < nnz; i++) ix_x[i] = TRUE;
207            break;
208        case x_integer: // 'i'
209            ix_x = INTEGER(ALLOC_SLOT(ans, Matrix_xSym, INTSXP, nnz));
210            for (i=0; i < nnz; i++) ix_x[i] = 1;
211            break;
212    
213        default:
214            error(_("nz2Csparse(): invalid/non-implemented r_kind = %d"),
215                  r_kind);
216        }
217    
218        // now copy all other slots :
219        slot_dup(ans, x, Matrix_iSym);
220        slot_dup(ans, x, Matrix_pSym);
221        slot_dup(ans, x, Matrix_DimSym);
222        slot_dup(ans, x, Matrix_DimNamesSym);
223        if(ncl[1] != 'g') { // symmetric or triangular ...
224            slot_dup_if_has(ans, x, Matrix_uploSym);
225            slot_dup_if_has(ans, x, Matrix_diagSym);
226        }
227        UNPROTECT(1);
228        return ans;
229    }
230    
231      Free(chxs);  SEXP Csparse_to_matrix(SEXP x)
232      return chm_dense_to_matrix(chxd, 1,  {
233                                 GET_SLOT(x, Matrix_DimNamesSym));      return chm_dense_to_matrix(cholmod_sparse_to_dense(AS_CHM_SP__(x), &c),
234                                   1 /*do_free*/, GET_SLOT(x, Matrix_DimNamesSym));
235  }  }
236    
237  SEXP Csparse_to_Tsparse(SEXP x, SEXP tri)  SEXP Csparse_to_Tsparse(SEXP x, SEXP tri)
238  {  {
239      cholmod_sparse *chxs = as_cholmod_sparse(x);      CHM_SP chxs = AS_CHM_SP__(x);
240      cholmod_triplet *chxt = cholmod_sparse_to_triplet(chxs, &c);      CHM_TR chxt = cholmod_sparse_to_triplet(chxs, &c);
241      int uploT = 0;      int tr = asLogical(tri);
242      char *diag = "";      int Rkind = (chxs->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
243      int Rkind = (chxs->xtype == CHOLMOD_REAL) ? Real_kind(x) : 0;      R_CheckStack();
244    
245      Free(chxs);      return chm_triplet_to_SEXP(chxt, 1,
246      if (asLogical(tri)) {       /* triangular sparse matrices */                                 tr ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,
247          uploT = (*uplo_P(x) == 'U') ? -1 : 1;                                 Rkind, tr ? diag_P(x) : "",
         diag = diag_P(x);  
     }  
     return chm_triplet_to_SEXP(chxt, 1, uploT, Rkind, diag,  
248                                 GET_SLOT(x, Matrix_DimNamesSym));                                 GET_SLOT(x, Matrix_DimNamesSym));
249  }  }
250    
251  /* this used to be called  sCMatrix_to_gCMatrix(..)   [in ./dsCMatrix.c ]: */  /* this used to be called  sCMatrix_to_gCMatrix(..)   [in ./dsCMatrix.c ]: */
252  SEXP Csparse_symmetric_to_general(SEXP x)  SEXP Csparse_symmetric_to_general(SEXP x)
253  {  {
254      cholmod_sparse *chx = as_cholmod_sparse(x), *chgx;      CHM_SP chx = AS_CHM_SP__(x), chgx;
255      int Rkind = (chx->xtype == CHOLMOD_REAL) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
256        R_CheckStack();
257    
258      if (!(chx->stype))      if (!(chx->stype))
259          error(_("Nonsymmetric matrix in Csparse_symmetric_to_general"));          error(_("Nonsymmetric matrix in Csparse_symmetric_to_general"));
260      chgx = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);      chgx = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);
261      /* xtype: pattern, "real", complex or .. */      /* xtype: pattern, "real", complex or .. */
     Free(chx);  
262      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",
263                                GET_SLOT(x, Matrix_DimNamesSym));                                GET_SLOT(x, Matrix_DimNamesSym));
264  }  }
265    
266  SEXP Csparse_general_to_symmetric(SEXP x, SEXP uplo)  SEXP Csparse_general_to_symmetric(SEXP x, SEXP uplo)
267  {  {
268      cholmod_sparse *chx = as_cholmod_sparse(x), *chgx;      CHM_SP chx = AS_CHM_SP__(x), chgx;
269      int uploT = (*CHAR(asChar(uplo)) == 'U') ? -1 : 1;      int uploT = (*CHAR(STRING_ELT(uplo,0)) == 'U') ? 1 : -1;
270      int Rkind = (chx->xtype == CHOLMOD_REAL) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
271        R_CheckStack();
272    
273      chgx = cholmod_copy(chx, /* stype: */ uploT, chx->xtype, &c);      chgx = cholmod_copy(chx, /* stype: */ uploT, chx->xtype, &c);
274      /* xtype: pattern, "real", complex or .. */      /* xtype: pattern, "real", complex or .. */
     Free(chx);  
275      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",      return chm_sparse_to_SEXP(chgx, 1, 0, Rkind, "",
276                                GET_SLOT(x, Matrix_DimNamesSym));                                GET_SLOT(x, Matrix_DimNamesSym));
277  }  }
278    
279  SEXP Csparse_transpose(SEXP x, SEXP tri)  SEXP Csparse_transpose(SEXP x, SEXP tri)
280  {  {
281      cholmod_sparse *chx = as_cholmod_sparse(x);      /* TODO: lgCMatrix & igC* currently go via double prec. cholmod -
282      int Rkind = (chx->xtype == CHOLMOD_REAL) ? Real_kind(x) : 0;       *       since cholmod (& cs) lacks sparse 'int' matrices */
283      cholmod_sparse *chxt = cholmod_transpose(chx, (int) chx->xtype, &c);      CHM_SP chx = AS_CHM_SP__(x);
284        int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
285        CHM_SP chxt = cholmod_transpose(chx, chx->xtype, &c);
286      SEXP dn = PROTECT(duplicate(GET_SLOT(x, Matrix_DimNamesSym))), tmp;      SEXP dn = PROTECT(duplicate(GET_SLOT(x, Matrix_DimNamesSym))), tmp;
287      int uploT = 0; char *diag = "";      int tr = asLogical(tri);
288        R_CheckStack();
289    
     Free(chx);  
290      tmp = VECTOR_ELT(dn, 0);    /* swap the dimnames */      tmp = VECTOR_ELT(dn, 0);    /* swap the dimnames */
291      SET_VECTOR_ELT(dn, 0, VECTOR_ELT(dn, 1));      SET_VECTOR_ELT(dn, 0, VECTOR_ELT(dn, 1));
292      SET_VECTOR_ELT(dn, 1, tmp);      SET_VECTOR_ELT(dn, 1, tmp);
293      UNPROTECT(1);      UNPROTECT(1);
294      if (asLogical(tri)) {       /* triangular sparse matrices */      return chm_sparse_to_SEXP(chxt, 1, /* SWAP 'uplo' for triangular */
295          uploT = (*uplo_P(x) == 'U') ? -1 : 1;                                tr ? ((*uplo_P(x) == 'U') ? -1 : 1) : 0,
296          diag = diag_P(x);                                Rkind, tr ? diag_P(x) : "", dn);
     }  
     return chm_sparse_to_SEXP(chxt, 1, uploT, Rkind, diag, dn);  
297  }  }
298    
299  SEXP Csparse_Csparse_prod(SEXP a, SEXP b)  SEXP Csparse_Csparse_prod(SEXP a, SEXP b)
300  {  {
301      cholmod_sparse *cha = as_cholmod_sparse(a),      CHM_SP
302          *chb = as_cholmod_sparse(b);          cha = AS_CHM_SP(a),
303      cholmod_sparse *chc = cholmod_ssmult(cha, chb, 0, cha->xtype, 1, &c);          chb = AS_CHM_SP(b),
304      SEXP dn = allocVector(VECSXP, 2);          chc = cholmod_ssmult(cha, chb, /*out_stype:*/ 0,
305                                   /* values:= is_numeric (T/F) */ cha->xtype > 0,
306                                   /*out sorted:*/ 1, &c);
307        const char *cl_a = class_P(a), *cl_b = class_P(b);
308        char diag[] = {'\0', '\0'};
309        int uploT = 0;
310        SEXP dn = PROTECT(allocVector(VECSXP, 2));
311        R_CheckStack();
312    
313      Free(cha); Free(chb);  #ifdef DEBUG_Matrix_verbose
314        Rprintf("DBG Csparse_C*_prod(%s, %s)\n", cl_a, cl_b);
315    #endif
316    
317        /* Preserve triangularity and even unit-triangularity if appropriate.
318         * Note that in that case, the multiplication itself should happen
319         * faster.  But there's no support for that in CHOLMOD */
320    
321        /* UGLY hack -- rather should have (fast!) C-level version of
322         *       is(a, "triangularMatrix") etc */
323        if (cl_a[1] == 't' && cl_b[1] == 't')
324            /* FIXME: fails for "Cholesky","BunchKaufmann"..*/
325            if(*uplo_P(a) == *uplo_P(b)) { /* both upper, or both lower tri. */
326                uploT = (*uplo_P(a) == 'U') ? 1 : -1;
327                if(*diag_P(a) == 'U' && *diag_P(b) == 'U') { /* return UNIT-triag. */
328                    /* "remove the diagonal entries": */
329                    chm_diagN2U(chc, uploT, /* do_realloc */ FALSE);
330                    diag[0]= 'U';
331                }
332                else diag[0]= 'N';
333            }
334      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
335                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));
336      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
337                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), 1)));
338      return chm_sparse_to_SEXP(chc, 1, 0, 0, "", dn);      UNPROTECT(1);
339        return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);
340  }  }
341    
342  SEXP Csparse_Csparse_crossprod(SEXP a, SEXP b)  SEXP Csparse_Csparse_crossprod(SEXP a, SEXP b, SEXP trans)
343  {  {
344      cholmod_sparse *cha = as_cholmod_sparse(a),      int tr = asLogical(trans);
345          *chb = as_cholmod_sparse(b);      CHM_SP
346      cholmod_sparse *chta = cholmod_transpose(cha, 1, &c);          cha = AS_CHM_SP(a),
347      cholmod_sparse *chc = cholmod_ssmult(chta, chb, 0, cha->xtype, 1, &c);          chb = AS_CHM_SP(b),
348      SEXP dn = allocVector(VECSXP, 2);          chTr, chc;
349        const char *cl_a = class_P(a), *cl_b = class_P(b);
350        char diag[] = {'\0', '\0'};
351        int uploT = 0;
352        SEXP dn = PROTECT(allocVector(VECSXP, 2));
353        R_CheckStack();
354    
355      Free(cha); Free(chb); cholmod_free_sparse(&chta, &c);      chTr = cholmod_transpose((tr) ? chb : cha, chb->xtype, &c);
356        chc = cholmod_ssmult((tr) ? cha : chTr, (tr) ? chTr : chb,
357                             /*out_stype:*/ 0, cha->xtype, /*out sorted:*/ 1, &c);
358        cholmod_free_sparse(&chTr, &c);
359    
360        /* Preserve triangularity and unit-triangularity if appropriate;
361         * see Csparse_Csparse_prod() for comments */
362        if (cl_a[1] == 't' && cl_b[1] == 't')
363            if(*uplo_P(a) != *uplo_P(b)) { /* one 'U', the other 'L' */
364                uploT = (*uplo_P(b) == 'U') ? 1 : -1;
365                if(*diag_P(a) == 'U' && *diag_P(b) == 'U') { /* return UNIT-triag. */
366                    chm_diagN2U(chc, uploT, /* do_realloc */ FALSE);
367                    diag[0]= 'U';
368                }
369                else diag[0]= 'N';
370            }
371      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
372                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), (tr) ? 0 : 1)));
373      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
374                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), (tr) ? 0 : 1)));
375      return chm_sparse_to_SEXP(chc, 1, 0, 0, "", dn);      UNPROTECT(1);
376        return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);
377  }  }
378    
379  SEXP Csparse_dense_prod(SEXP a, SEXP b)  SEXP Csparse_dense_prod(SEXP a, SEXP b)
380  {  {
381      cholmod_sparse *cha = as_cholmod_sparse(a);      CHM_SP cha = AS_CHM_SP(a);
382      cholmod_dense *chb = as_cholmod_dense(PROTECT(mMatrix_as_dgeMatrix(b)));      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix(b));
383      cholmod_dense *chc =      CHM_DN chb = AS_CHM_DN(b_M);
384          cholmod_allocate_dense(cha->nrow, chb->ncol, cha->nrow, chb->xtype, &c);      CHM_DN chc = cholmod_allocate_dense(cha->nrow, chb->ncol, cha->nrow,
385      double alpha[] = {1,0}, beta[] = {0,0};                                          chb->xtype, &c);
386        SEXP dn = PROTECT(allocVector(VECSXP, 2));
387      cholmod_sdmult(cha, 0, alpha, beta, chb, chc, &c);      double one[] = {1,0}, zero[] = {0,0};
388      Free(cha); Free(chb);      int nprot = 2;
389      UNPROTECT(1);      R_CheckStack();
390      return chm_dense_to_SEXP(chc, 1, 0);      /* Tim Davis, please FIXME:  currently (2010-11) *fails* when  a  is a pattern matrix:*/
391        if(cha->xtype == CHOLMOD_PATTERN) {
392            /* warning(_("Csparse_dense_prod(): cholmod_sdmult() not yet implemented for pattern./ ngCMatrix" */
393            /*        " --> slightly inefficient coercion")); */
394    
395            // This *fails* to produce a CHOLMOD_REAL ..
396            // CHM_SP chd = cholmod_l_copy(cha, cha->stype, CHOLMOD_REAL, &c);
397            // --> use our Matrix-classes
398            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
399            cha = AS_CHM_SP(da);
400        }
401        cholmod_sdmult(cha, 0, one, zero, chb, chc, &c);
402        SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
403                       duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));
404        SET_VECTOR_ELT(dn, 1,
405                       duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));
406        UNPROTECT(nprot);
407        return chm_dense_to_SEXP(chc, 1, 0, dn);
408  }  }
409    
410  SEXP Csparse_dense_crossprod(SEXP a, SEXP b)  SEXP Csparse_dense_crossprod(SEXP a, SEXP b)
411  {  {
412      cholmod_sparse *cha = as_cholmod_sparse(a);      CHM_SP cha = AS_CHM_SP(a);
413      cholmod_dense *chb = as_cholmod_dense(PROTECT(mMatrix_as_dgeMatrix(b)));      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix(b));
414      cholmod_dense *chc =      CHM_DN chb = AS_CHM_DN(b_M);
415          cholmod_allocate_dense(cha->ncol, chb->ncol, cha->ncol, chb->xtype, &c);      CHM_DN chc = cholmod_allocate_dense(cha->ncol, chb->ncol, cha->ncol,
416      double alpha[] = {1,0}, beta[] = {0,0};                                          chb->xtype, &c);
417        SEXP dn = PROTECT(allocVector(VECSXP, 2)); int nprot = 2;
418      cholmod_sdmult(cha, 1, alpha, beta, chb, chc, &c);      double one[] = {1,0}, zero[] = {0,0};
419      Free(cha); Free(chb);      R_CheckStack();
420      UNPROTECT(1);      // -- see Csparse_dense_prod() above :
421      return chm_dense_to_SEXP(chc, 1, 0);      if(cha->xtype == CHOLMOD_PATTERN) {
422            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
423            cha = AS_CHM_SP(da);
424        }
425        cholmod_sdmult(cha, 1, one, zero, chb, chc, &c);
426        SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
427                       duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 1)));
428        SET_VECTOR_ELT(dn, 1,
429                       duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));
430        UNPROTECT(nprot);
431        return chm_dense_to_SEXP(chc, 1, 0, dn);
432  }  }
433    
434    /* Computes   x'x  or  x x' -- *also* for Tsparse (triplet = TRUE)
435       see Csparse_Csparse_crossprod above for  x'y and x y' */
436  SEXP Csparse_crossprod(SEXP x, SEXP trans, SEXP triplet)  SEXP Csparse_crossprod(SEXP x, SEXP trans, SEXP triplet)
437  {  {
438      int trip = asLogical(triplet),      int trip = asLogical(triplet),
439          tr   = asLogical(trans); /* gets reversed because _aat is tcrossprod */          tr   = asLogical(trans); /* gets reversed because _aat is tcrossprod */
440      cholmod_triplet  #ifdef AS_CHM_DIAGU2N_FIXED_FINALLY
441          *cht = trip ? as_cholmod_triplet(x) : (cholmod_triplet*) NULL;      CHM_TR cht = trip ? AS_CHM_TR(x) : (CHM_TR) NULL;
442      cholmod_sparse *chcp, *chxt,  #else /* workaround needed:*/
443          *chx = trip ? cholmod_triplet_to_sparse(cht, cht->nnz, &c)      SEXP xx = PROTECT(Tsparse_diagU2N(x));
444          : as_cholmod_sparse(x);      CHM_TR cht = trip ? AS_CHM_TR__(xx) : (CHM_TR) NULL;
445    #endif
446        CHM_SP chcp, chxt,
447            chx = (trip ?
448                   cholmod_triplet_to_sparse(cht, cht->nnz, &c) :
449                   AS_CHM_SP(x));
450      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2));
451        R_CheckStack();
452    
453      if (!tr)      if (!tr) chxt = cholmod_transpose(chx, chx->xtype, &c);
         chxt = cholmod_transpose(chx, chx->xtype, &c);  
454      chcp = cholmod_aat((!tr) ? chxt : chx, (int *) NULL, 0, chx->xtype, &c);      chcp = cholmod_aat((!tr) ? chxt : chx, (int *) NULL, 0, chx->xtype, &c);
455      if(!chcp)      if(!chcp) {
456            UNPROTECT(1);
457          error(_("Csparse_crossprod(): error return from cholmod_aat()"));          error(_("Csparse_crossprod(): error return from cholmod_aat()"));
458        }
459      cholmod_band_inplace(0, chcp->ncol, chcp->xtype, chcp, &c);      cholmod_band_inplace(0, chcp->ncol, chcp->xtype, chcp, &c);
460      chcp->stype = 1;      chcp->stype = 1;
461      if (trip) {      if (trip) cholmod_free_sparse(&chx, &c);
         cholmod_free_sparse(&chx, &c);  
         Free(cht);  
     } else {  
         Free(chx);  
     }  
462      if (!tr) cholmod_free_sparse(&chxt, &c);      if (!tr) cholmod_free_sparse(&chxt, &c);
463                                  /* create dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
     SET_VECTOR_ELT(dn, 0,  
464                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),
465                                          (tr) ? 1 : 0)));                                          (tr) ? 0 : 1)));
466      SET_VECTOR_ELT(dn, 1, duplicate(VECTOR_ELT(dn, 0)));      SET_VECTOR_ELT(dn, 1, duplicate(VECTOR_ELT(dn, 0)));
467    #ifdef AS_CHM_DIAGU2N_FIXED_FINALLY
468      UNPROTECT(1);      UNPROTECT(1);
469    #else
470        UNPROTECT(2);
471    #endif
472      return chm_sparse_to_SEXP(chcp, 1, 0, 0, "", dn);      return chm_sparse_to_SEXP(chcp, 1, 0, 0, "", dn);
473  }  }
474    
475    /* Csparse_drop(x, tol):  drop entries with absolute value < tol, i.e,
476    *  at least all "explicit" zeros */
477  SEXP Csparse_drop(SEXP x, SEXP tol)  SEXP Csparse_drop(SEXP x, SEXP tol)
478  {  {
479      cholmod_sparse *chx = as_cholmod_sparse(x),      const char *cl = class_P(x);
480          *ans = cholmod_copy(chx, chx->stype, chx->xtype, &c);      /* dtCMatrix, etc; [1] = the second character =?= 't' for triangular */
481        int tr = (cl[1] == 't');
482        CHM_SP chx = AS_CHM_SP__(x);
483        CHM_SP ans = cholmod_copy(chx, chx->stype, chx->xtype, &c);
484      double dtol = asReal(tol);      double dtol = asReal(tol);
485      int Rkind = (chx->xtype == CHOLMOD_REAL) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
486        R_CheckStack();
487    
488      if(!cholmod_drop(dtol, ans, &c))      if(!cholmod_drop(dtol, ans, &c))
489          error(_("cholmod_drop() failed"));          error(_("cholmod_drop() failed"));
490      Free(chx);      return chm_sparse_to_SEXP(ans, 1,
491      /* FIXME: currently drops dimnames */                                tr ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,
492      return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "", R_NilValue);                                Rkind, tr ? diag_P(x) : "",
493                                  GET_SLOT(x, Matrix_DimNamesSym));
494  }  }
495    
   
496  SEXP Csparse_horzcat(SEXP x, SEXP y)  SEXP Csparse_horzcat(SEXP x, SEXP y)
497  {  {
498      cholmod_sparse *chx = as_cholmod_sparse(x),      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);
499          *chy = as_cholmod_sparse(y), *ans;      int Rk_x = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0,
500      int Rkind = 0; /* only for "d" - FIXME */          Rk_y = (chy->xtype != CHOLMOD_PATTERN) ? Real_kind(y) : 0,
501            Rkind = /* logical if both x and y are */ (Rk_x == 1 && Rk_y == 1) ? 1 : 0;
502      ans = cholmod_horzcat(chx, chy, 1, &c);      R_CheckStack();
503      Free(chx); Free(chy);  
504      /* FIXME: currently drops dimnames */      /* TODO: currently drops dimnames - and we fix at R level */
505      return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "", R_NilValue);      return chm_sparse_to_SEXP(cholmod_horzcat(chx, chy, 1, &c),
506                                  1, 0, Rkind, "", R_NilValue);
507  }  }
508    
509  SEXP Csparse_vertcat(SEXP x, SEXP y)  SEXP Csparse_vertcat(SEXP x, SEXP y)
510  {  {
511      cholmod_sparse *chx = as_cholmod_sparse(x),      CHM_SP chx = AS_CHM_SP__(x), chy = AS_CHM_SP__(y);
512          *chy = as_cholmod_sparse(y), *ans;      int Rk_x = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0,
513      int Rkind = 0; /* only for "d" - FIXME */          Rk_y = (chy->xtype != CHOLMOD_PATTERN) ? Real_kind(y) : 0,
514            Rkind = /* logical if both x and y are */ (Rk_x == 1 && Rk_y == 1) ? 1 : 0;
515      ans = cholmod_vertcat(chx, chy, 1, &c);      R_CheckStack();
516      Free(chx); Free(chy);  
517      /* FIXME: currently drops dimnames */      /* TODO: currently drops dimnames - and we fix at R level */
518      return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "", R_NilValue);      return chm_sparse_to_SEXP(cholmod_vertcat(chx, chy, 1, &c),
519                                  1, 0, Rkind, "", R_NilValue);
520  }  }
521    
522  SEXP Csparse_band(SEXP x, SEXP k1, SEXP k2)  SEXP Csparse_band(SEXP x, SEXP k1, SEXP k2)
523  {  {
524      cholmod_sparse *chx = as_cholmod_sparse(x), *ans;      CHM_SP chx = AS_CHM_SP__(x);
525      int Rkind = (chx->xtype == CHOLMOD_REAL) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
526        CHM_SP ans = cholmod_band(chx, asInteger(k1), asInteger(k2), chx->xtype, &c);
527        R_CheckStack();
528    
529      ans = cholmod_band(chx, asInteger(k1), asInteger(k2), chx->xtype, &c);      return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "",
530      Free(chx);                                GET_SLOT(x, Matrix_DimNamesSym));
     return chm_sparse_to_SEXP(ans, 1, 0, Rkind, "", R_NilValue);  
531  }  }
532    
533  SEXP Csparse_diagU2N(SEXP x)  SEXP Csparse_diagU2N(SEXP x)
534  {  {
535      cholmod_sparse *chx = as_cholmod_sparse(x);      const char *cl = class_P(x);
536      cholmod_sparse *eye = cholmod_speye(chx->nrow, chx->ncol, chx->xtype, &c);      /* dtCMatrix, etc; [1] = the second character =?= 't' for triangular */
537        if (cl[1] != 't' || *diag_P(x) != 'U') {
538            /* "trivially fast" when not triangular (<==> no 'diag' slot),
539               or not *unit* triangular */
540            return (x);
541        }
542        else { /* unit triangular (diag='U'): "fill the diagonal" & diag:= "N" */
543            CHM_SP chx = AS_CHM_SP__(x);
544            CHM_SP eye = cholmod_speye(chx->nrow, chx->ncol, chx->xtype, &c);
545      double one[] = {1, 0};      double one[] = {1, 0};
546      cholmod_sparse *ans = cholmod_add(chx, eye, one, one, TRUE, TRUE, &c);          CHM_SP ans = cholmod_add(chx, eye, one, one, TRUE, TRUE, &c);
547      int uploT = (strcmp(CHAR(asChar(GET_SLOT(x, Matrix_uploSym))), "U")) ?          int uploT = (*uplo_P(x) == 'U') ? 1 : -1;
548          -1 : 1;          int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
     int Rkind = (chx->xtype == CHOLMOD_REAL) ? Real_kind(x) : 0;  
549    
550      Free(chx); cholmod_free_sparse(&eye, &c);          R_CheckStack();
551            cholmod_free_sparse(&eye, &c);
552      return chm_sparse_to_SEXP(ans, 1, uploT, Rkind, "N",      return chm_sparse_to_SEXP(ans, 1, uploT, Rkind, "N",
553                                duplicate(GET_SLOT(x, Matrix_DimNamesSym)));                                    GET_SLOT(x, Matrix_DimNamesSym));
554        }
555    }
556    
557    SEXP Csparse_diagN2U(SEXP x)
558    {
559        const char *cl = class_P(x);
560        /* dtCMatrix, etc; [1] = the second character =?= 't' for triangular */
561        if (cl[1] != 't' || *diag_P(x) != 'N') {
562            /* "trivially fast" when not triangular (<==> no 'diag' slot),
563               or already *unit* triangular */
564            return (x);
565        }
566        else { /* triangular with diag='N'): now drop the diagonal */
567            /* duplicate, since chx will be modified: */
568            CHM_SP chx = AS_CHM_SP__(duplicate(x));
569            int uploT = (*uplo_P(x) == 'U') ? 1 : -1,
570                Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
571            R_CheckStack();
572    
573            chm_diagN2U(chx, uploT, /* do_realloc */ FALSE);
574    
575            return chm_sparse_to_SEXP(chx, /*dofree*/ 0/* or 1 ?? */,
576                                      uploT, Rkind, "U",
577                                      GET_SLOT(x, Matrix_DimNamesSym));
578        }
579  }  }
580    
581    /**
582     * "Indexing" aka subsetting : Compute  x[i,j], also for vectors i and j
583     * Working via CHOLMOD_submatrix, see ./CHOLMOD/MatrixOps/cholmod_submatrix.c
584     * @param x CsparseMatrix
585     * @param i row     indices (0-origin), or NULL (R's)
586     * @param j columns indices (0-origin), or NULL
587     *
588     * @return x[i,j]  still CsparseMatrix --- currently, this loses dimnames
589     */
590  SEXP Csparse_submatrix(SEXP x, SEXP i, SEXP j)  SEXP Csparse_submatrix(SEXP x, SEXP i, SEXP j)
591  {  {
592      cholmod_sparse *chx = as_cholmod_sparse(x);      CHM_SP chx = AS_CHM_SP(x); /* << does diagU2N() when needed */
593      int rsize = (isNull(i)) ? -1 : LENGTH(i),      int rsize = (isNull(i)) ? -1 : LENGTH(i),
594          csize = (isNull(j)) ? -1 : LENGTH(j);          csize = (isNull(j)) ? -1 : LENGTH(j);
595      int Rkind = (chx->xtype == CHOLMOD_REAL) ? Real_kind(x) : 0;      int Rkind = (chx->xtype != CHOLMOD_PATTERN) ? Real_kind(x) : 0;
596        R_CheckStack();
597    
598      if (rsize >= 0 && !isInteger(i))      if (rsize >= 0 && !isInteger(i))
599          error(_("Index i must be NULL or integer"));          error(_("Index i must be NULL or integer"));
600      if (csize >= 0 && !isInteger(j))      if (csize >= 0 && !isInteger(j))
601          error(_("Index j must be NULL or integer"));          error(_("Index j must be NULL or integer"));
602      return chm_sparse_to_SEXP(cholmod_submatrix(chx, INTEGER(i), rsize,  
603                                                  INTEGER(j), csize,      if (chx->stype) /* symmetricMatrix */
604            /* for now, cholmod_submatrix() only accepts "generalMatrix" */
605            chx = cholmod_copy(chx, /* stype: */ 0, chx->xtype, &c);
606    
607        return chm_sparse_to_SEXP(cholmod_submatrix(chx,
608                                    (rsize < 0) ? NULL : INTEGER(i), rsize,
609                                    (csize < 0) ? NULL : INTEGER(j), csize,
610                                                  TRUE, TRUE, &c),                                                  TRUE, TRUE, &c),
611                                1, 0, Rkind, "", R_NilValue);                                1, 0, Rkind, "",
612                                  /* FIXME: drops dimnames */ R_NilValue);
613    }
614    
615    /**
616     * Subassignment:  x[i,j]  <- value
617     *
618     * @param x
619     * @param i_ integer row    index 0-origin vector (as returned from R .ind.prep2())
620     * @param j_ integer column index 0-origin vector
621     * @param value currently must be a dsparseVector {which is recycled if needed}
622     *
623     * @return a Csparse matrix like x, but with the values replaced
624     */
625    SEXP Csparse_subassign(SEXP x, SEXP i_, SEXP j_, SEXP value)
626    {
627        static const char
628            *valid_cM [] = {"dgCMatrix",// the only one, for "the moment", more later
629                            ""},
630            *valid_spv[] = {"dsparseVector",
631                            ""};
632    
633        int ctype = Matrix_check_class_etc(x, valid_cM);
634        if (ctype < 0)
635            error(_("invalid class of 'x' in Csparse_subassign()"));
636        // value: assume a  "dsparseVector" for now -- slots: (i, length, x)
637        ctype = Matrix_check_class_etc(value, valid_spv);
638        if (ctype < 0)
639            error(_("invalid class of 'value' in Csparse_subassign()"));
640    
641        SEXP ans,
642            pslot = GET_SLOT(x, Matrix_pSym),
643            islot = GET_SLOT(x, Matrix_iSym),
644            i_cp = PROTECT((TYPEOF(i_) == INTSXP) ?
645                           duplicate(i_) : coerceVector(i_, INTSXP)),
646            j_cp = PROTECT((TYPEOF(j_) == INTSXP) ?
647                           duplicate(j_) : coerceVector(j_, INTSXP)),
648            // for d.CMatrix and l.CMatrix  but not n.CMatrix
649            xslot = GET_SLOT(x, Matrix_xSym);
650    
651        int *dims = INTEGER(GET_SLOT(x, Matrix_DimSym)),
652            nrow = dims[0],
653            ncol = dims[1],
654            *xp = INTEGER(pslot),
655            *xi = INTEGER(islot),
656            *ii = INTEGER(i_cp), len_i = LENGTH(i_cp),
657            *jj = INTEGER(j_cp), len_j = LENGTH(j_cp),
658            i, j, k;
659        int    *val_i = INTEGER(GET_SLOT(value, Matrix_iSym));
660        double *val_x =   REAL (GET_SLOT(value, Matrix_xSym));
661        int len_val = asInteger(GET_SLOT(value, Matrix_lengthSym));
662        int p_last = xp[0];
663    
664        // for d.CMatrix only:
665        double *xx = REAL(xslot);
666        double ind; // the index that goes all the way from 1:(len_i * len_j)
667    
668        PROTECT(ans = duplicate(x));
669        for(j = 0; j < ncol; j++) {
670        }
671        UNPROTECT(3);
672        return ans;
673    }
674    
675    SEXP Csparse_MatrixMarket(SEXP x, SEXP fname)
676    {
677        FILE *f = fopen(CHAR(asChar(fname)), "w");
678    
679        if (!f)
680            error(_("failure to open file \"%s\" for writing"),
681                  CHAR(asChar(fname)));
682        if (!cholmod_write_sparse(f, AS_CHM_SP(x),
683                                  (CHM_SP)NULL, (char*) NULL, &c))
684            error(_("cholmod_write_sparse returned error code"));
685        fclose(f);
686        return R_NilValue;
687    }
688    
689    
690    /**
691     * Extract the diagonal entries from *triangular* Csparse matrix  __or__ a
692     * cholmod_sparse factor (LDL = TRUE).
693     *
694     * @param n  dimension of the matrix.
695     * @param x_p  'p' (column pointer) slot contents
696     * @param x_x  'x' (non-zero entries) slot contents
697     * @param perm 'perm' (= permutation vector) slot contents; only used for "diagBack"
698     * @param resultKind a (SEXP) string indicating which kind of result is desired.
699     *
700     * @return  a SEXP, either a (double) number or a length n-vector of diagonal entries
701     */
702    SEXP diag_tC_ptr(int n, int *x_p, double *x_x, int *perm, SEXP resultKind)
703    /*                                ^^^^^^ FIXME[Generalize] to int / ... */
704    {
705        const char* res_ch = CHAR(STRING_ELT(resultKind,0));
706        enum diag_kind { diag, diag_backpermuted, trace, prod, sum_log
707        } res_kind = ((!strcmp(res_ch, "trace")) ? trace :
708                      ((!strcmp(res_ch, "sumLog")) ? sum_log :
709                       ((!strcmp(res_ch, "prod")) ? prod :
710                        ((!strcmp(res_ch, "diag")) ? diag :
711                         ((!strcmp(res_ch, "diagBack")) ? diag_backpermuted :
712                          -1)))));
713        int i, n_x, i_from = 0;
714        SEXP ans = PROTECT(allocVector(REALSXP,
715    /*                                 ^^^^  FIXME[Generalize] */
716                                       (res_kind == diag ||
717                                        res_kind == diag_backpermuted) ? n : 1));
718        double *v = REAL(ans);
719    /*  ^^^^^^      ^^^^  FIXME[Generalize] */
720    
721    #define for_DIAG(v_ASSIGN)                                              \
722        for(i = 0; i < n; i++, i_from += n_x) {                             \
723            /* looking at i-th column */                                    \
724            n_x = x_p[i+1] - x_p[i];/* #{entries} in this column */ \
725            v_ASSIGN;                                                       \
726        }
727    
728        /* NOTA BENE: we assume  -- uplo = "L" i.e. lower triangular matrix
729         *            for uplo = "U" (makes sense with a "dtCMatrix" !),
730         *            should use  x_x[i_from + (nx - 1)] instead of x_x[i_from],
731         *            where nx = (x_p[i+1] - x_p[i])
732         */
733    
734        switch(res_kind) {
735        case trace:
736            v[0] = 0.;
737            for_DIAG(v[0] += x_x[i_from]);
738            break;
739    
740        case sum_log:
741            v[0] = 0.;
742            for_DIAG(v[0] += log(x_x[i_from]));
743            break;
744    
745        case prod:
746            v[0] = 1.;
747            for_DIAG(v[0] *= x_x[i_from]);
748            break;
749    
750        case diag:
751            for_DIAG(v[i] = x_x[i_from]);
752            break;
753    
754        case diag_backpermuted:
755            for_DIAG(v[i] = x_x[i_from]);
756    
757            warning(_("resultKind = 'diagBack' (back-permuted) is experimental"));
758            /* now back_permute : */
759            for(i = 0; i < n; i++) {
760                double tmp = v[i]; v[i] = v[perm[i]]; v[perm[i]] = tmp;
761                /*^^^^ FIXME[Generalize] */
762            }
763            break;
764    
765        default: /* -1 from above */
766            error(_("diag_tC(): invalid 'resultKind'"));
767            /* Wall: */ ans = R_NilValue; v = REAL(ans);
768        }
769    
770        UNPROTECT(1);
771        return ans;
772    }
773    
774    /**
775     * Extract the diagonal entries from *triangular* Csparse matrix  __or__ a
776     * cholmod_sparse factor (LDL = TRUE).
777     *
778     * @param pslot  'p' (column pointer)   slot of Csparse matrix/factor
779     * @param xslot  'x' (non-zero entries) slot of Csparse matrix/factor
780     * @param perm_slot  'perm' (= permutation vector) slot of corresponding CHMfactor;
781     *                   only used for "diagBack"
782     * @param resultKind a (SEXP) string indicating which kind of result is desired.
783     *
784     * @return  a SEXP, either a (double) number or a length n-vector of diagonal entries
785     */
786    SEXP diag_tC(SEXP pslot, SEXP xslot, SEXP perm_slot, SEXP resultKind)
787    {
788        int n = length(pslot) - 1, /* n = ncol(.) = nrow(.) */
789            *x_p  = INTEGER(pslot),
790            *perm = INTEGER(perm_slot);
791        double *x_x = REAL(xslot);
792    /*  ^^^^^^        ^^^^ FIXME[Generalize] to INTEGER(.) / LOGICAL(.) / ... xslot !*/
793    
794        return diag_tC_ptr(n, x_p, x_x, perm, resultKind);
795    }
796    
797    /**
798     * Create a Csparse matrix object from indices and/or pointers.
799     *
800     * @param cls name of actual class of object to create
801     * @param i optional integer vector of length nnz of row indices
802     * @param j optional integer vector of length nnz of column indices
803     * @param p optional integer vector of length np of row or column pointers
804     * @param np length of integer vector p.  Must be zero if p == (int*)NULL
805     * @param x optional vector of values
806     * @param nnz length of vectors i, j and/or x, whichever is to be used
807     * @param dims optional integer vector of length 2 to be used as
808     *     dimensions.  If dims == (int*)NULL then the maximum row and column
809     *     index are used as the dimensions.
810     * @param dimnames optional list of length 2 to be used as dimnames
811     * @param index1 indicator of 1-based indices
812     *
813     * @return an SEXP of class cls inheriting from CsparseMatrix.
814     */
815    SEXP create_Csparse(char* cls, int* i, int* j, int* p, int np,
816                        void* x, int nnz, int* dims, SEXP dimnames,
817                        int index1)
818    {
819        SEXP ans;
820        int *ij = (int*)NULL, *tri, *trj,
821            mi, mj, mp, nrow = -1, ncol = -1;
822        int xtype = -1;             /* -Wall */
823        CHM_TR T;
824        CHM_SP A;
825    
826        if (np < 0 || nnz < 0)
827            error(_("negative vector lengths not allowed: np = %d, nnz = %d"),
828                  np, nnz);
829        if (1 != ((mi = (i == (int*)NULL)) +
830                  (mj = (j == (int*)NULL)) +
831                  (mp = (p == (int*)NULL))))
832            error(_("exactly 1 of 'i', 'j' or 'p' must be NULL"));
833        if (mp) {
834            if (np) error(_("np = %d, must be zero when p is NULL"), np);
835        } else {
836            if (np) {               /* Expand p to form i or j */
837                if (!(p[0])) error(_("p[0] = %d, should be zero"), p[0]);
838                for (int ii = 0; ii < np; ii++)
839                    if (p[ii] > p[ii + 1])
840                        error(_("p must be non-decreasing"));
841                if (p[np] != nnz)
842                    error("p[np] = %d != nnz = %d", p[np], nnz);
843                ij = Calloc(nnz, int);
844                if (mi) {
845                    i = ij;
846                    nrow = np;
847                } else {
848                    j = ij;
849                    ncol = np;
850                }
851                /* Expand p to 0-based indices */
852                for (int ii = 0; ii < np; ii++)
853                    for (int jj = p[ii]; jj < p[ii + 1]; jj++) ij[jj] = ii;
854            } else {
855                if (nnz)
856                    error(_("Inconsistent dimensions: np = 0 and nnz = %d"),
857                          nnz);
858            }
859        }
860        /* calculate nrow and ncol */
861        if (nrow < 0) {
862            for (int ii = 0; ii < nnz; ii++) {
863                int i1 = i[ii] + (index1 ? 0 : 1); /* 1-based index */
864                if (i1 < 1) error(_("invalid row index at position %d"), ii);
865                if (i1 > nrow) nrow = i1;
866            }
867        }
868        if (ncol < 0) {
869            for (int jj = 0; jj < nnz; jj++) {
870                int j1 = j[jj] + (index1 ? 0 : 1);
871                if (j1 < 1) error(_("invalid column index at position %d"), jj);
872                if (j1 > ncol) ncol = j1;
873            }
874        }
875        if (dims != (int*)NULL) {
876            if (dims[0] > nrow) nrow = dims[0];
877            if (dims[1] > ncol) ncol = dims[1];
878        }
879        /* check the class name */
880        if (strlen(cls) != 8)
881            error(_("strlen of cls argument = %d, should be 8"), strlen(cls));
882        if (!strcmp(cls + 2, "CMatrix"))
883            error(_("cls = \"%s\" does not end in \"CMatrix\""), cls);
884        switch(cls[0]) {
885        case 'd':
886        case 'l':
887            xtype = CHOLMOD_REAL;
888        break;
889        case 'n':
890            xtype = CHOLMOD_PATTERN;
891            break;
892        default:
893            error(_("cls = \"%s\" must begin with 'd', 'l' or 'n'"), cls);
894        }
895        if (cls[1] != 'g')
896            error(_("Only 'g'eneral sparse matrix types allowed"));
897        /* allocate and populate the triplet */
898        T = cholmod_allocate_triplet((size_t)nrow, (size_t)ncol, (size_t)nnz, 0,
899                                     xtype, &c);
900        T->x = x;
901        tri = (int*)T->i;
902        trj = (int*)T->j;
903        for (int ii = 0; ii < nnz; ii++) {
904            tri[ii] = i[ii] - ((!mi && index1) ? 1 : 0);
905            trj[ii] = j[ii] - ((!mj && index1) ? 1 : 0);
906        }
907        /* create the cholmod_sparse structure */
908        A = cholmod_triplet_to_sparse(T, nnz, &c);
909        cholmod_free_triplet(&T, &c);
910        /* copy the information to the SEXP */
911        ans = PROTECT(NEW_OBJECT(MAKE_CLASS(cls)));
912    /* FIXME: This has been copied from chm_sparse_to_SEXP in chm_common.c */
913        /* allocate and copy common slots */
914        nnz = cholmod_nnz(A, &c);
915        dims = INTEGER(ALLOC_SLOT(ans, Matrix_DimSym, INTSXP, 2));
916        dims[0] = A->nrow; dims[1] = A->ncol;
917        Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_pSym, INTSXP, A->ncol + 1)), (int*)A->p, A->ncol + 1);
918        Memcpy(INTEGER(ALLOC_SLOT(ans, Matrix_iSym, INTSXP, nnz)), (int*)A->i, nnz);
919        switch(cls[1]) {
920        case 'd':
921            Memcpy(REAL(ALLOC_SLOT(ans, Matrix_xSym, REALSXP, nnz)), (double*)A->x, nnz);
922            break;
923        case 'l':
924            error(_("code not yet written for cls = \"lgCMatrix\""));
925        }
926    /* FIXME: dimnames are *NOT* put there yet (if non-NULL) */
927        cholmod_free_sparse(&A, &c);
928        UNPROTECT(1);
929        return ans;
930  }  }

Legend:
Removed from v.1657  
changed lines
  Added in v.2661

root@r-forge.r-project.org
ViewVC Help
Powered by ViewVC 1.0.0  
Thanks to:
Vienna University of Economics and Business Powered By FusionForge