# SCM Repository

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

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

revision 3066, Thu Mar 19 14:27:05 2015 UTC revision 3147, Thu Oct 29 16:56:10 2015 UTC
# Line 1  Line 1
1                          /* Sparse matrices in compressed column-oriented form */  /** @file Csparse.c
2     * The "CsparseMatrix" class from R package Matrix:
3     *
4     * Sparse matrices in compressed column-oriented form
5     */
6  #include "Csparse.h"  #include "Csparse.h"
7  #include "Tsparse.h"  #include "Tsparse.h"
8  #include "chm_common.h"  #include "chm_common.h"
# Line 101  Line 104
104      return ScalarLogical(1);      return ScalarLogical(1);
105  }  }
106
107  /**  /** @brief From a CsparseMatrix, produce a dense one.
108   * From a CsparseMatrix, produce a dense one.   *
109   * Directly deals with symmetric, triangular and general.   * Directly deals with symmetric, triangular and general.
110   * Called from ../R/Csparse.R's  C2dense()   * Called from ../R/Csparse.R's  C2dense()
111   *   *
# Line 122  Line 125
125          ctype = 0; // <- default = "dgC"          ctype = 0; // <- default = "dgC"
126      static const char *valid[] = { MATRIX_VALID_Csparse, ""};      static const char *valid[] = { MATRIX_VALID_Csparse, ""};
127      if(is_sym_or_tri == NA_INTEGER) { // find if  is(x, "symmetricMatrix") :      if(is_sym_or_tri == NA_INTEGER) { // find if  is(x, "symmetricMatrix") :
128          ctype = Matrix_check_class_etc(x, valid);          ctype = R_check_class_etc(x, valid);
129          is_sym = (ctype % 3 == 1);          is_sym = (ctype % 3 == 1);
130          is_tri = (ctype % 3 == 2);          is_tri = (ctype % 3 == 2);
131      } else {      } else {
# Line 130  Line 133
133          is_tri = is_sym_or_tri < 0;          is_tri = is_sym_or_tri < 0;
134          // => both are FALSE  iff  is_.. == 0          // => both are FALSE  iff  is_.. == 0
135          if(is_sym || is_tri)          if(is_sym || is_tri)
136              ctype = Matrix_check_class_etc(x, valid);              ctype = R_check_class_etc(x, valid);
137      }      }
138      CHM_SP chxs = AS_CHM_SP__(x);// -> chxs->stype = +- 1 <==> symmetric      CHM_SP chxs = AS_CHM_SP__(x);// -> chxs->stype = +- 1 <==> symmetric
139      R_CheckStack();      R_CheckStack();
# Line 150  Line 153
153      CHM_DN chxd = cholmod_sparse_to_dense(chxs, &c);      CHM_DN chxd = cholmod_sparse_to_dense(chxs, &c);
154      int Rkind = (chxs->xtype == CHOLMOD_PATTERN)? -1 : Real_kind(x);      int Rkind = (chxs->xtype == CHOLMOD_PATTERN)? -1 : Real_kind(x);
155
156      SEXP ans = chm_dense_to_SEXP(chxd, 1, Rkind,GET_SLOT(x, Matrix_DimNamesSym));      SEXP ans = chm_dense_to_SEXP(chxd, 1, Rkind, GET_SLOT(x, Matrix_DimNamesSym),
157                                     /* transp: */ FALSE);
158      // -> a [dln]geMatrix      // -> a [dln]geMatrix
159      if(is_sym) { // ==> want  [dln]syMatrix      if(is_sym) { // ==> want  [dln]syMatrix
160          const char cl1 = class_P(ans)[0];          const char cl1 = class_P(ans)[0];
# Line 185  Line 189
189  }  }
190
191  // FIXME: do not go via CHM (should not be too hard, to just *drop* the x-slot, right?  // FIXME: do not go via CHM (should not be too hard, to just *drop* the x-slot, right?
192  SEXP Csparse_to_nz_pattern(SEXP x, SEXP tri)  SEXP Csparse2nz(SEXP x, Rboolean tri)
193  {  {
194      CHM_SP chxs = AS_CHM_SP__(x);      CHM_SP chxs = AS_CHM_SP__(x);
195      CHM_SP chxcp = cholmod_copy(chxs, chxs->stype, CHOLMOD_PATTERN, &c);      CHM_SP chxcp = cholmod_copy(chxs, chxs->stype, CHOLMOD_PATTERN, &c);
int tr = asLogical(tri);
196      R_CheckStack();      R_CheckStack();
197
198      return chm_sparse_to_SEXP(chxcp, 1/*do_free*/,      return chm_sparse_to_SEXP(chxcp, 1/*do_free*/,
199                                tr ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,                                tri ? ((*uplo_P(x) == 'U') ? 1 : -1) : 0,
200                                0, tr ? diag_P(x) : "",                                /* Rkind: pattern */ 0,
201                                  /* diag = */ tri ? diag_P(x) : "",
202                                GET_SLOT(x, Matrix_DimNamesSym));                                GET_SLOT(x, Matrix_DimNamesSym));
203  }  }
204    SEXP Csparse_to_nz_pattern(SEXP x, SEXP tri)
205    {
206        int tr_ = asLogical(tri);
207        if(tr_ == NA_LOGICAL) {
208            warning(_("Csparse_to_nz_pattern(x, tri = NA): 'tri' is taken as TRUE"));
209            tr_ = TRUE;
210        }
211        return Csparse2nz(x, (Rboolean) tr_);
212    }
213
214  // n.CMatrix --> [dli].CMatrix  (not going through CHM!)  // n.CMatrix --> [dli].CMatrix  (not going through CHM!)
215  SEXP nz_pattern_to_Csparse(SEXP x, SEXP res_kind)  SEXP nz_pattern_to_Csparse(SEXP x, SEXP res_kind)
# Line 209  Line 222
222  SEXP nz2Csparse(SEXP x, enum x_slot_kind r_kind)  SEXP nz2Csparse(SEXP x, enum x_slot_kind r_kind)
223  {  {
224      const char *cl_x = class_P(x);      const char *cl_x = class_P(x);
225      if(cl_x[0] != 'n') error(_("not a 'n.CMatrix'"));      // quick check - if ok, fast
226      if(cl_x[2] != 'C') error(_("not a CsparseMatrix"));      if(cl_x[0] != 'n' || cl_x[2] != 'C') {
227            // e.g. class = "A", from  setClass("A", contains = "ngCMatrix")
228            static const char *valid[] = { MATRIX_VALID_nCsparse, ""};
229            int ctype = R_check_class_etc(x, valid);
230            if(ctype < 0)
231                error(_("not a 'n.CMatrix'"));
232            else // fine : get a valid  cl_x  class_P()-like string :
233                cl_x = valid[ctype];
234        }
235      int nnz = LENGTH(GET_SLOT(x, Matrix_iSym));      int nnz = LENGTH(GET_SLOT(x, Matrix_iSym));
236      SEXP ans;      SEXP ans;
237      char *ncl = alloca(strlen(cl_x) + 1); /* not much memory required */      char *ncl = alloca(strlen(cl_x) + 1); /* not much memory required */
# Line 259  Line 280
280      int is_sym = asLogical(symm);      int is_sym = asLogical(symm);
281      if(is_sym == NA_LOGICAL) { // find if  is(x, "symmetricMatrix") :      if(is_sym == NA_LOGICAL) { // find if  is(x, "symmetricMatrix") :
282          static const char *valid[] = { MATRIX_VALID_Csparse, ""};          static const char *valid[] = { MATRIX_VALID_Csparse, ""};
283          int ctype = Matrix_check_class_etc(x, valid);          int ctype = R_check_class_etc(x, valid);
284          is_sym = (ctype % 3 == 1);          is_sym = (ctype % 3 == 1);
285      }      }
286      return chm_dense_to_matrix(      return chm_dense_to_matrix(
# Line 399  Line 420
420                                Rkind, tr ? diag_P(x) : "", dn);                                Rkind, tr ? diag_P(x) : "", dn);
421  }  }
422
423  SEXP Csparse_Csparse_prod(SEXP a, SEXP b)  /** @brief  A %*% B  - for matrices of class CsparseMatrix (R package "Matrix")
424     *
425     * @param a
426     * @param b
427     * @param bool_arith
428     *
429     * @return
430     *
431     * NOTA BENE:  cholmod_ssmult(A,B, ...) ->  ./CHOLMOD/MatrixOps/cholmod_ssmult.c
432     * ---------  computes a patter*n* matrix __always_ when
433     * *one* of A or B is pattern*n*, because of this (line 73-74):
434       ---------------------------------------------------------------------------
435        values = values &&
436            (A->xtype != CHOLMOD_PATTERN) && (B->xtype != CHOLMOD_PATTERN) ;
437       ---------------------------------------------------------------------------
438     * ==> Often need to copy the patter*n* to a *l*ogical matrix first !!!
439     */
440    SEXP Csparse_Csparse_prod(SEXP a, SEXP b, SEXP bool_arith)
441  {  {
442      CHM_SP      CHM_SP
443          cha = AS_CHM_SP(a),          cha = AS_CHM_SP(a),
444          chb = AS_CHM_SP(b),          chb = AS_CHM_SP(b), chc;
chc = cholmod_ssmult(cha, chb, /*out_stype:*/ 0,
// values:= is_numeric (T/F) if _one_ is numeric:
cha->xtype > 0 || chb->xtype > 0,
/*out sorted:*/ 1, &c);
const char *cl_a = class_P(a), *cl_b = class_P(b);
char diag[] = {'\0', '\0'};
int uploT = 0;
SEXP dn = PROTECT(allocVector(VECSXP, 2));
445      R_CheckStack();      R_CheckStack();
446        static const char *valid_tri[] = { MATRIX_VALID_tri_Csparse, "" };
447        char diag[] = {'\0', '\0'};
448        int uploT = 0, nprot = 1,
449            do_bool = asLogical(bool_arith); // TRUE / NA / FALSE
450        Rboolean
451            a_is_n = (cha->xtype == CHOLMOD_PATTERN),
452            b_is_n = (chb->xtype == CHOLMOD_PATTERN),
453            force_num = (do_bool == FALSE),
454            maybe_bool= (do_bool == NA_LOGICAL);
455
456  #ifdef DEBUG_Matrix_verbose  #ifdef DEBUG_Matrix_verbose
457      Rprintf("DBG Csparse_C*_prod(%s, %s)\n", cl_a, cl_b);      Rprintf("DBG Csparse_C*_prod(%s, %s)\n", class_P(a), class_P(b));
458  #endif  #endif
459
460        if(a_is_n && (force_num || (maybe_bool && !b_is_n))) {
461            /* coerce 'a' to  double;
462             * have no CHOLMOD function (pattern -> logical) --> use "our" code */
463            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
464            cha = AS_CHM_SP(da);
465            R_CheckStack();
466            a_is_n = FALSE;
467        }
468        else if(b_is_n && (force_num || (maybe_bool && !a_is_n))) {
469            // coerce 'b' to  double
470            SEXP db = PROTECT(nz2Csparse(b, x_double)); nprot++;
471            chb = AS_CHM_SP(db);
472            R_CheckStack();
473            b_is_n = FALSE;
474        }
475        chc = cholmod_ssmult(cha, chb, /*out_stype:*/ 0,
476                             /* values : */ do_bool != TRUE,
477                             /* sorted = TRUE: */ 1, &c);
478
479      /* Preserve triangularity and even unit-triangularity if appropriate.      /* Preserve triangularity and even unit-triangularity if appropriate.
480       * Note that in that case, the multiplication itself should happen       * Note that in that case, the multiplication itself should happen
481       * faster.  But there's no support for that in CHOLMOD */       * faster.  But there's no support for that in CHOLMOD */
482
483      /* UGLY hack -- rather should have (fast!) C-level version of      if(R_check_class_etc(a, valid_tri) >= 0 &&
484       *       is(a, "triangularMatrix") etc */         R_check_class_etc(b, valid_tri) >= 0)
if (cl_a[1] == 't' && cl_b[1] == 't')
/* FIXME: fails for "Cholesky","BunchKaufmann"..*/
485          if(*uplo_P(a) == *uplo_P(b)) { /* both upper, or both lower tri. */          if(*uplo_P(a) == *uplo_P(b)) { /* both upper, or both lower tri. */
486              uploT = (*uplo_P(a) == 'U') ? 1 : -1;              uploT = (*uplo_P(a) == 'U') ? 1 : -1;
487              if(*diag_P(a) == 'U' && *diag_P(b) == 'U') { /* return UNIT-triag. */              if(*diag_P(a) == 'U' && *diag_P(b) == 'U') { /* return UNIT-triag. */
# Line 435  Line 491
491              }              }
492              else diag[0]= 'N';              else diag[0]= 'N';
493          }          }
494
495        SEXP dn = PROTECT(allocVector(VECSXP, 2));
496      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
497                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));
498      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
499                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), 1)));
500      UNPROTECT(1);      UNPROTECT(nprot);
501      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);
502  }  }
503
504  SEXP Csparse_Csparse_crossprod(SEXP a, SEXP b, SEXP trans)  /** @brief [t]crossprod (<Csparse>, <Csparse>)
505     *
506     * @param a a "CsparseMatrix" object
507     * @param b a "CsparseMatrix" object
508     * @param trans trans = FALSE:  crossprod(a,b)
509     *              trans = TRUE : tcrossprod(a,b)
510     * @param bool_arith logical (TRUE / NA / FALSE): Should boolean arithmetic be used.
511     *
512     * @return a CsparseMatrix, the (t)cross product of a and b.
513     */
514    SEXP Csparse_Csparse_crossprod(SEXP a, SEXP b, SEXP trans, SEXP bool_arith)
515  {  {
516      int tr = asLogical(trans);      int tr = asLogical(trans), nprot = 1,
517            do_bool = asLogical(bool_arith); // TRUE / NA / FALSE
518      CHM_SP      CHM_SP
519          cha = AS_CHM_SP(a),          cha = AS_CHM_SP(a),
520          chb = AS_CHM_SP(b),          chb = AS_CHM_SP(b),
521          chTr, chc;          chTr, chc;
522      const char *cl_a = class_P(a), *cl_b = class_P(b);      R_CheckStack();
523        static const char *valid_tri[] = { MATRIX_VALID_tri_Csparse, "" };
524      char diag[] = {'\0', '\0'};      char diag[] = {'\0', '\0'};
525      int uploT = 0;      int uploT = 0;
526      SEXP dn = PROTECT(allocVector(VECSXP, 2));      Rboolean
527      R_CheckStack();          a_is_n = (cha->xtype == CHOLMOD_PATTERN),
528            b_is_n = (chb->xtype == CHOLMOD_PATTERN),
529            force_num = (do_bool == FALSE),
530            maybe_bool= (do_bool == NA_LOGICAL);
531
532        if(a_is_n && (force_num || (maybe_bool && !b_is_n))) {
533            // coerce 'a' to  double
534            SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
535            cha = AS_CHM_SP(da);
536            R_CheckStack();
537            // a_is_n = FALSE;
538        }
539        else if(b_is_n && (force_num || (maybe_bool && !a_is_n))) {
540            // coerce 'b' to  double
541            SEXP db = PROTECT(nz2Csparse(b, x_double)); nprot++;
542            chb = AS_CHM_SP(db);
543            R_CheckStack();
544            // b_is_n = FALSE;
545        }
546        else if(do_bool == TRUE) { // Want boolean arithmetic: sufficient if *one* is pattern:
547            if(!a_is_n && !b_is_n) {
548                // coerce 'a' to pattern
549                SEXP da = PROTECT(Csparse2nz(a, /* tri = */
550                                             R_check_class_etc(a, valid_tri) >= 0)); nprot++;
551                cha = AS_CHM_SP(da);
552                R_CheckStack();
553                // a_is_n = TRUE;
554            }
555        }
556      chTr = cholmod_transpose((tr) ? chb : cha, chb->xtype, &c);      chTr = cholmod_transpose((tr) ? chb : cha, chb->xtype, &c);
557      chc = cholmod_ssmult((tr) ? cha : chTr, (tr) ? chTr : chb,      chc = cholmod_ssmult((tr) ? cha : chTr, (tr) ? chTr : chb,
558                           /*out_stype:*/ 0, cha->xtype, /*out sorted:*/ 1, &c);                           /*out_stype:*/ 0, /* values : */ do_bool != TRUE,
559                             /* sorted = TRUE: */ 1, &c);
560      cholmod_free_sparse(&chTr, &c);      cholmod_free_sparse(&chTr, &c);
561
562      /* Preserve triangularity and unit-triangularity if appropriate;      /* Preserve triangularity and unit-triangularity if appropriate;
563       * see Csparse_Csparse_prod() for comments */       * see Csparse_Csparse_prod() for comments */
564      if (cl_a[1] == 't' && cl_b[1] == 't')      if(R_check_class_etc(a, valid_tri) >= 0 &&
565           R_check_class_etc(b, valid_tri) >= 0)
566          if(*uplo_P(a) != *uplo_P(b)) { /* one 'U', the other 'L' */          if(*uplo_P(a) != *uplo_P(b)) { /* one 'U', the other 'L' */
567              uploT = (*uplo_P(b) == 'U') ? 1 : -1;              uploT = (*uplo_P(b) == 'U') ? 1 : -1;
568              if(*diag_P(a) == 'U' && *diag_P(b) == 'U') { /* return UNIT-triag. */              if(*diag_P(a) == 'U' && *diag_P(b) == 'U') { /* return UNIT-triag. */
# Line 472  Line 571
571              }              }
572              else diag[0]= 'N';              else diag[0]= 'N';
573          }          }
574
575        SEXP dn = PROTECT(allocVector(VECSXP, 2));
576      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
577                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), (tr) ? 0 : 1)));                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym),
578                                            (tr) ? 0 : 1)));
579      SET_VECTOR_ELT(dn, 1,      SET_VECTOR_ELT(dn, 1,
580                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym), (tr) ? 0 : 1)));                     duplicate(VECTOR_ELT(GET_SLOT(b, Matrix_DimNamesSym),
581      UNPROTECT(1);                                          (tr) ? 0 : 1)));
582        UNPROTECT(nprot);
583      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);      return chm_sparse_to_SEXP(chc, 1, uploT, /*Rkind*/0, diag, dn);
584  }  }
585
586  SEXP Csparse_dense_prod(SEXP a, SEXP b)  /**
587     * All (dense * sparse)  Matrix products and cross products
588     *
589     *   f( f(<Csparse>)  %*%  f(<dense>) )   where  f ()  is either t () [tranpose] or the identity.
590     *
591     * @param a CsparseMatrix  (n x m)
592     * @param b numeric vector, matrix, or denseMatrix (m x k) or (k x m)  if `transp` is '2' or 'B'
593     * @param transp character.
594     *        = " " : nothing transposed {apart from a}
595     *        = "2" : "transpose 2nd arg": use  t(b) instead of b (= 2nd argument)
596     *        = "c" : "transpose c":       Return  t(c) instead of c
597     *        = "B" : "transpose both":    use t(b) and return t(c) instead of c
598     * NB: For "2", "c", "B", need to transpose a *dense* matrix, B or C --> chm_transpose_dense()
599     *
600     * @return a dense matrix, the matrix product c = g(a,b) :
601     *
602     *                                                Condition (R)   Condition (C)
603     *   R notation            Math notation          cross  transp   t.a t.b t.ans
604     *   ~~~~~~~~~~~~~~~~~     ~~~~~~~~~~~~~~~~~~     ~~~~~~~~~~~~~   ~~~~~~~~~~~~~
605     *   c <-   a %*%   b      C :=      A B            .       " "    .   .   .
606     *   c <-   a %*% t(b)     C :=      A B'           .       "2"    .   |   .
607     *   c <- t(a %*%   b)     C := (A B)'  = B'A'      .       "c"    .   .   |
608     *   c <- t(a %*% t(b))    C := (A B')' = B A'      .       "B"    .   |   |
609     *
610     *   c <-   t(a) %*%   b   C :=      A'B           TRUE     " "    |   .   .
611     *   c <-   t(a) %*% t(b)  C :=      A'B'          TRUE     "2"    |   |   .
612     *   c <- t(t(a) %*%   b)  C := (A'B)'  = B'A      TRUE     "c"    |   .   |
613     *   c <- t(t(a) %*% t(b)) C := (A'B')' = B A      TRUE     "B"    |   |   |
614     */
615    SEXP Csp_dense_products(SEXP a, SEXP b,
616                            Rboolean transp_a, Rboolean transp_b, Rboolean transp_ans)
617  {  {
618      CHM_SP cha = AS_CHM_SP(a);      CHM_SP cha = AS_CHM_SP(a);
619      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix2(b, // transpose_if_vector =      int a_nc = transp_a ? cha->nrow : cha->ncol,
620                                               cha->ncol == 1));          a_nr = transp_a ? cha->ncol : cha->nrow;
621      CHM_DN chb = AS_CHM_DN(b_M);      Rboolean
622      CHM_DN chc = cholmod_allocate_dense(cha->nrow, chb->ncol, cha->nrow,          maybe_transp_b = (a_nc == 1),
623                                          chb->xtype, &c);          b_is_vector = FALSE;
624      SEXP dn = PROTECT(allocVector(VECSXP, 2));      /* NOTE: trans_b {<--> "use t(b) instead of b" }
625           ----  "interferes" with the  case automatic treatment of *vector* b.
626           In that case,  t(b) or b is used "whatever make more sense",
627           according to the general R philosophy of treating vectors in matrix products.
628        */
629
630        /* repeating a "cheap part" of  mMatrix_as_dgeMatrix2(b, .)  to see if
631         * we have a vector that we might 'transpose_if_vector' : */
632        static const char *valid[] = {"_NOT_A_CLASS_", MATRIX_VALID_ddense, ""};
633        /* int ctype = R_check_class_etc(b, valid);
634         * if (ctype > 0)   /.* a ddenseMatrix object */
635        if (R_check_class_etc(b, valid) < 0) {
636            // not a ddenseM*:  is.matrix() or vector:
637            b_is_vector = !isMatrix(b);
638        }
639
640        if(b_is_vector) {
641            /* determine *if* we want/need to transpose at all:
642             * if (length(b) == ncol(A)) have match: use dim = c(n, 1) (<=> do *not* transp);
643             *  otherwise, try to transpose: ok  if (ncol(A) == 1) [see also above]:  */
644            maybe_transp_b = (LENGTH(b) != a_nc);
645            // Here, we transpose already in mMatrix_as_dge*()  ==> don't do it later:
646            transp_b = FALSE;
647        }
648        SEXP b_M = PROTECT(mMatrix_as_dgeMatrix2(b, maybe_transp_b));
649
650        CHM_DN chb = AS_CHM_DN(b_M), b_t;
651        R_CheckStack();
652        int ncol_b;
653        if(transp_b) { // transpose b:
654            b_t = cholmod_allocate_dense(chb->ncol, chb->nrow, chb->ncol, chb->xtype, &c);
655            chm_transpose_dense(b_t, chb);
656            ncol_b = b_t->ncol;
657        } else
658            ncol_b = chb->ncol;
659        // Result C {with dim() before it may be transposed}:
660        CHM_DN chc = cholmod_allocate_dense(a_nr, ncol_b, a_nr, chb->xtype, &c);
661      double one[] = {1,0}, zero[] = {0,0};      double one[] = {1,0}, zero[] = {0,0};
662      int nprot = 2;      int nprot = 2;
663      R_CheckStack();
664      /* Tim Davis, please FIXME:  currently (2010-11) *fails* when  a  is a pattern matrix:*/      /* Tim Davis, please FIXME:  currently (2010-11) *fails* when  a  is a pattern matrix:*/
665      if(cha->xtype == CHOLMOD_PATTERN) {      if(cha->xtype == CHOLMOD_PATTERN) {
666          /* warning(_("Csparse_dense_prod(): cholmod_sdmult() not yet implemented for pattern./ ngCMatrix" */          /* warning(_("Csparse_dense_prod(): cholmod_sdmult() not yet implemented for pattern./ ngCMatrix" */
# Line 503  Line 672
672          SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;          SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
673          cha = AS_CHM_SP(da);          cha = AS_CHM_SP(da);
674      }      }
675      cholmod_sdmult(cha, 0, one, zero, chb, chc, &c);
676      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      /* cholmod_sdmult(A, transp, alpha, beta, X,  Y,  &c): depending on transp == 0 / != 0:
677                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 0)));       *  Y := alpha*(A*X) + beta*Y or alpha*(A'*X) + beta*Y;  here, alpha = 1, beta = 0:
678      SET_VECTOR_ELT(dn, 1,       *  Y := A*X  or  A'*X
679                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));       *                       NB: always  <sparse> %*% <dense> !
680         */
681        cholmod_sdmult(cha, transp_a, one, zero, (transp_b ? b_t : chb), /* -> */ chc, &c);
682
683        SEXP dn = PROTECT(allocVector(VECSXP, 2));  /* establish dimnames */
684        SET_VECTOR_ELT(dn, transp_ans ? 1 : 0,
685                       duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), transp_a ? 1 : 0)));
686        SET_VECTOR_ELT(dn, transp_ans ? 0 : 1,
687                       duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym),
688                                            transp_b ? 0 : 1)));
689        if(transp_b) cholmod_free_dense(&b_t, &c);
690      UNPROTECT(nprot);      UNPROTECT(nprot);
691      return chm_dense_to_SEXP(chc, 1, 0, dn);      return chm_dense_to_SEXP(chc, 1, 0, dn, transp_ans);
692  }  }
693
694  SEXP Csparse_dense_crossprod(SEXP a, SEXP b)
695    SEXP Csparse_dense_prod(SEXP a, SEXP b, SEXP transp)
696  {  {
697      CHM_SP cha = AS_CHM_SP(a);      return
698      SEXP b_M = PROTECT(mMatrix_as_dgeMatrix2(b, // transpose_if_vector =          Csp_dense_products(a, b,
699                                               cha->nrow == 1));                  /* transp_a = */ FALSE,
700      CHM_DN chb = AS_CHM_DN(b_M);                  /* transp_b   = */ (*CHAR(asChar(transp)) == '2' || *CHAR(asChar(transp)) == 'B'),
701      CHM_DN chc = cholmod_allocate_dense(cha->ncol, chb->ncol, cha->ncol,                  /* transp_ans = */ (*CHAR(asChar(transp)) == 'c' || *CHAR(asChar(transp)) == 'B'));
chb->xtype, &c);
SEXP dn = PROTECT(allocVector(VECSXP, 2)); int nprot = 2;
double one[] = {1,0}, zero[] = {0,0};
R_CheckStack();
// -- see Csparse_dense_prod() above :
if(cha->xtype == CHOLMOD_PATTERN) {
SEXP da = PROTECT(nz2Csparse(a, x_double)); nprot++;
cha = AS_CHM_SP(da);
702      }      }
703      cholmod_sdmult(cha, 1, one, zero, chb, chc, &c);
704      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */  SEXP Csparse_dense_crossprod(SEXP a, SEXP b, SEXP transp)
705                     duplicate(VECTOR_ELT(GET_SLOT(a, Matrix_DimNamesSym), 1)));  {
706      SET_VECTOR_ELT(dn, 1,      return
707                     duplicate(VECTOR_ELT(GET_SLOT(b_M, Matrix_DimNamesSym), 1)));          Csp_dense_products(a, b,
708      UNPROTECT(nprot);                  /* transp_a = */ TRUE,
709      return chm_dense_to_SEXP(chc, 1, 0, dn);                  /* transp_b   = */ (*CHAR(asChar(transp)) == '2' || *CHAR(asChar(transp)) == 'B'),
710                    /* transp_ans = */ (*CHAR(asChar(transp)) == 'c' || *CHAR(asChar(transp)) == 'B'));
711  }  }
712
713  /* Computes   x'x  or  x x' -- *also* for Tsparse (triplet = TRUE)
714     see Csparse_Csparse_crossprod above for  x'y and x y' */  /** @brief Computes   x'x  or  x x' -- *also* for Tsparse (triplet = TRUE)
715  SEXP Csparse_crossprod(SEXP x, SEXP trans, SEXP triplet)      see Csparse_Csparse_crossprod above for  x'y and x y'
716    */
717    SEXP Csparse_crossprod(SEXP x, SEXP trans, SEXP triplet, SEXP bool_arith)
718  {  {
719      int trip = asLogical(triplet),      int tripl = asLogical(triplet),
720          tr   = asLogical(trans); /* gets reversed because _aat is tcrossprod */          tr   = asLogical(trans), /* gets reversed because _aat is tcrossprod */
721            do_bool = asLogical(bool_arith); // TRUE / NA / FALSE
722  #ifdef AS_CHM_DIAGU2N_FIXED_FINALLY  #ifdef AS_CHM_DIAGU2N_FIXED_FINALLY
723      CHM_TR cht = trip ? AS_CHM_TR(x) : (CHM_TR) NULL;      CHM_TR cht = tripl ? AS_CHM_TR(x) : (CHM_TR) NULL;  int nprot = 1;
724  #else /* workaround needed:*/  #else /* workaround needed:*/
725      SEXP xx = PROTECT(Tsparse_diagU2N(x));      SEXP xx = PROTECT(Tsparse_diagU2N(x));
726      CHM_TR cht = trip ? AS_CHM_TR__(xx) : (CHM_TR) NULL;      CHM_TR cht = tripl ? AS_CHM_TR__(xx) : (CHM_TR) NULL; int nprot = 2;
727  #endif  #endif
728      CHM_SP chcp, chxt,      CHM_SP chcp, chxt, chxc,
729          chx = (trip ?          chx = (tripl ?
730                 cholmod_triplet_to_sparse(cht, cht->nnz, &c) :                 cholmod_triplet_to_sparse(cht, cht->nnz, &c) :
731                 AS_CHM_SP(x));                 AS_CHM_SP(x));
732      SEXP dn = PROTECT(allocVector(VECSXP, 2));      SEXP dn = PROTECT(allocVector(VECSXP, 2));
733      R_CheckStack();      R_CheckStack();
734        Rboolean
735            x_is_n = (chx->xtype == CHOLMOD_PATTERN),
736            x_is_sym = chx->stype != 0,
737            force_num = (do_bool == FALSE);
738
739        if(x_is_n && force_num) {
740            // coerce 'x' to  double
741            SEXP dx = PROTECT(nz2Csparse(x, x_double)); nprot++;
742            chx = AS_CHM_SP(dx);
743            R_CheckStack();
744        }
745        else if(do_bool == TRUE && !x_is_n) { // Want boolean arithmetic; need patter[n]
746            // coerce 'x' to pattern
747            static const char *valid_tri[] = { MATRIX_VALID_tri_Csparse, "" };
748            SEXP dx = PROTECT(Csparse2nz(x, /* tri = */
749                                         R_check_class_etc(x, valid_tri) >= 0)); nprot++;
750            chx = AS_CHM_SP(dx);
751            R_CheckStack();
752        }
753
754      if (!tr) chxt = cholmod_transpose(chx, chx->xtype, &c);      if (!tr) chxt = cholmod_transpose(chx, chx->xtype, &c);
755      chcp = cholmod_aat((!tr) ? chxt : chx, (int *) NULL, 0, chx->xtype, &c);
756        if (x_is_sym) // cholmod_aat() does not like symmetric
757            chxc = cholmod_copy(tr ? chx : chxt, /* stype: */ 0,
758                                chx->xtype, &c);
759        // CHOLMOD/Core/cholmod_aat.c :
760        chcp = cholmod_aat(x_is_sym ? chxc : (tr ? chx : chxt),
761                           (int *) NULL, 0, /* mode: */ chx->xtype, &c);
762      if(!chcp) {      if(!chcp) {
763          UNPROTECT(1);          UNPROTECT(1);
764          error(_("Csparse_crossprod(): error return from cholmod_aat()"));          error(_("Csparse_crossprod(): error return from cholmod_aat()"));
765      }      }
766      cholmod_band_inplace(0, chcp->ncol, chcp->xtype, chcp, &c);      cholmod_band_inplace(0, chcp->ncol, chcp->xtype, chcp, &c);
767      chcp->stype = 1;      chcp->stype = 1; // symmetric
768      if (trip) cholmod_free_sparse(&chx, &c);      if (tripl) cholmod_free_sparse(&chx, &c);
769      if (!tr) cholmod_free_sparse(&chxt, &c);      if (!tr) cholmod_free_sparse(&chxt, &c);
770      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */      SET_VECTOR_ELT(dn, 0,       /* establish dimnames */
771                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),                     duplicate(VECTOR_ELT(GET_SLOT(x, Matrix_DimNamesSym),
772                                          (tr) ? 0 : 1)));                                          (tr) ? 0 : 1)));
773      SET_VECTOR_ELT(dn, 1, duplicate(VECTOR_ELT(dn, 0)));      SET_VECTOR_ELT(dn, 1, duplicate(VECTOR_ELT(dn, 0)));
774  #ifdef AS_CHM_DIAGU2N_FIXED_FINALLY      UNPROTECT(nprot);
775      UNPROTECT(1);      // FIXME: uploT for symmetric ?
#else
UNPROTECT(2);
#endif
776      return chm_sparse_to_SEXP(chcp, 1, 0, 0, "", dn);      return chm_sparse_to_SEXP(chcp, 1, 0, 0, "", dn);
777  }  }
778
779  /* Csparse_drop(x, tol):  drop entries with absolute value < tol, i.e,  /** @brief Csparse_drop(x, tol):  drop entries with absolute value < tol, i.e,
780  *  at least all "explicit" zeros */   *  at least all "explicit" zeros. */
781  SEXP Csparse_drop(SEXP x, SEXP tol)  SEXP Csparse_drop(SEXP x, SEXP tol)
782  {  {
783      const char *cl = class_P(x);      const char *cl = class_P(x);
784      /* dtCMatrix, etc; [1] = the second character =?= 't' for triangular */      /* dtCMatrix, etc; [1] = the second character =?= 't' for triangular */
785      int tr = (cl[1] == 't');      int tr = (cl[1] == 't'); // FIXME - rather  R_check_class_etc(..)
786      CHM_SP chx = AS_CHM_SP__(x);      CHM_SP chx = AS_CHM_SP__(x);
787      CHM_SP ans = cholmod_copy(chx, chx->stype, chx->xtype, &c);      CHM_SP ans = cholmod_copy(chx, chx->stype, chx->xtype, &c);
788      double dtol = asReal(tol);      double dtol = asReal(tol);
# Line 599  Line 797
797                                GET_SLOT(x, Matrix_DimNamesSym));                                GET_SLOT(x, Matrix_DimNamesSym));
798  }  }
799
800    /** @brief Horizontal Concatenation -  cbind( <Csparse>,  <Csparse>)
801     */
802  SEXP Csparse_horzcat(SEXP x, SEXP y)  SEXP Csparse_horzcat(SEXP x, SEXP y)
803  {  {
804  #define CSPARSE_CAT(_KIND_)                                             \  #define CSPARSE_CAT(_KIND_)                                             \
# Line 631  Line 831
831                                1, 0, Rkind, "", R_NilValue);                                1, 0, Rkind, "", R_NilValue);
832  }  }
833
834    /** @brief Vertical Concatenation -  rbind( <Csparse>,  <Csparse>)
835     */
836  SEXP Csparse_vertcat(SEXP x, SEXP y)  SEXP Csparse_vertcat(SEXP x, SEXP y)
837  {  {
838      CSPARSE_CAT("vertcat");      CSPARSE_CAT("vertcat");
# Line 703  Line 905
905  }  }
906
907  /**  /**
908   * "Indexing" aka subsetting : Compute  x[i,j], also for vectors i and j   * Indexing aka subsetting : Compute  x[i,j], also for vectors i and j
909   * Working via CHOLMOD_submatrix, see ./CHOLMOD/MatrixOps/cholmod_submatrix.c   * Working via CHOLMOD_submatrix, see ./CHOLMOD/MatrixOps/cholmod_submatrix.c
910   * @param x CsparseMatrix   * @param x CsparseMatrix
911   * @param i row     indices (0-origin), or NULL (R's)   * @param i row     indices (0-origin), or NULL (R, not C)
912   * @param j columns indices (0-origin), or NULL   * @param j columns indices (0-origin), or NULL
913   *   *
914   * @return x[i,j]  still CsparseMatrix --- currently, this loses dimnames   * @return x[i,j]  still CsparseMatrix --- currently, this loses dimnames

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

 root@r-forge.r-project.org ViewVC Help Powered by ViewVC 1.0.0
Thanks to: