File: 00_Class.R

package info (click to toggle)
rmatrix 1.7-5-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 12,156 kB
  • sloc: ansic: 97,207; makefile: 280; sh: 165
file content (954 lines) | stat: -rw-r--r-- 35,821 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
## README:
##
## Validity methods should assume that methods for superclasses have passed,
## following validObject(). We should _not_ be testing, e.g., length(Dim),
## typeof(Dimnames), etc. repeatedly ...
##
## When checking whether a class is validated correctly, take care to follow
## the 'contains' recursively!!


## initialize() method for Matrix and MatrixFactorization, which both
## allow Dimnames[[i]] to be a vector of type other than "character"
## and furthermore to be a vector of length zero rather than NULL ...
.initialize <- function(.Object, ...) {
    .Object <- callNextMethod()
    ## Suboptimal if ...names() is NULL but that will "never"
    ## happen if ...length() is nonzero:
    if(...length() && any(...names() == "Dimnames"))
        .Object@Dimnames <- fixupDN(.Object@Dimnames)
    .Object
}

## new() does not work at build time because native symbols such as
## 'Matrix_validate' needed for validity checking are not available ...
.new <- function(cl, ...) {
    def <- getClassDef(cl)
    structure(def@prototype, class = def@className, ...)
}


########################################################################
##  1. Matrix
########################################################################

## ====== Virtual Subclasses ===========================================

## ------ The Mother Class 'Matrix' ------------------------------------

## Virtual class of all Matrix objects
setClass("Matrix",
         contains = "VIRTUAL",
         slots = c(Dim = "integer", Dimnames = "list"),
         prototype = list(Dim = integer(2L), Dimnames = list(NULL, NULL)),
         validity = function(object) .Call(Matrix_validate, object))

setMethod("initialize", c(.Object = "Matrix"),
          .initialize)


## ------ Virtual by structure -----------------------------------------

## Virtual class of general matrices
setClass("generalMatrix",
         contains = c("VIRTUAL", "Matrix"),
         slots = c(factors = "list"),
         validity = function(object) .Call(generalMatrix_validate, object))

## Virtual class of symmetric matrices
setClass("symmetricMatrix",
         contains = c("VIRTUAL", "Matrix"),
         slots = c(uplo = "character", factors = "list"),
         prototype = list(uplo = "U"),
         validity = function(object) .Call(symmetricMatrix_validate, object))

## Virtual class of triangular matrices
setClass("triangularMatrix",
         contains = c("VIRTUAL", "Matrix"),
         slots = c(uplo = "character", diag = "character"),
         prototype = list(uplo = "U", diag = "N"),
         validity = function(object) .Call(triangularMatrix_validate, object))


## ------ Virtual by kind ----------------------------------------------

## Virtual class of nonzero pattern matrices
## NB: only subclass ndenseMatrix requires an 'x' slot
setClass("nMatrix",
         contains = c("VIRTUAL", "Matrix"))

## Virtual class of logical matrices,
## * typically the result of comparisons, e.g., <dMatrix> <relop> <dMatrix>,
##   hence NA are allowed and distinct from TRUE, in contrast with nMatrix
setClass("lMatrix",
         contains = c("VIRTUAL", "Matrix"),
         slots = c(x = "logical"),
         validity = function(object) .Call(lMatrix_validate, object))

## Virtual class of integer matrices
setClass("iMatrix",
         contains = c("VIRTUAL", "Matrix"),
         slots = c(x = "integer"),
         validity = function(object) .Call(iMatrix_validate, object))

## Virtual class of double matrices
setClass("dMatrix",
         contains = c("VIRTUAL", "Matrix"),
         slots = c(x = "numeric"),
         validity = function(object) .Call(dMatrix_validate, object))

## Virtual class of complex matrices
## * initial 'z' is derived from the names of LAPACK routines
setClass("zMatrix",
         contains = c("VIRTUAL", "Matrix"),
         slots = c(x = "complex"),
         validity = function(object) .Call(zMatrix_validate, object))


## ------ Virtual Dense ------------------------------------------------

## Virtual class of dense matrices
## * includes "unpacked" _and_ "packed" matrices
## * included diagonal matrices until 0.999375-11 (2008-07)
setClass("denseMatrix",
         contains = c("VIRTUAL", "Matrix"))


## ...... Virtual Dense ... by storage .................................

## Virtual class of dense, "unpacked" matrices, s.t. length(.@x) == m*n
setClass("unpackedMatrix",
         contains = c("VIRTUAL", "denseMatrix"),
         validity = function(object) .Call(unpackedMatrix_validate, object))

## Virtual class of dense, "packed" matrices, s.t. length(.@x) == n*(n+1)/2
setClass("packedMatrix",
         contains = c("VIRTUAL", "denseMatrix"),
         slots = c(uplo = "character"),
         prototype = list(uplo = "U"),
         validity = function(object) .Call(packedMatrix_validate, object))


## ...... Virtual Dense ... by kind ....................................

## Virtual class of dense, nonzero pattern matrices
setClass("ndenseMatrix",
         contains = c("VIRTUAL", "nMatrix", "denseMatrix"),
         slots = c(x = "logical"),
         validity = function(object) .Call(nMatrix_validate, object))

## Virtual class of dense, logical matrices
setClass("ldenseMatrix",
         contains = c("VIRTUAL", "lMatrix", "denseMatrix"))

if(FALSE) { # --NOT YET--
## Virtual class of dense, integer matrices
setClass("idenseMatrix",
         contains = c("VIRTUAL", "iMatrix", "denseMatrix"))
} # --NOT YET--

## Virtual class of dense, double matrices
setClass("ddenseMatrix",
         contains = c("VIRTUAL", "dMatrix", "denseMatrix"))

if(FALSE) { # --NOT YET--
## Virtual class of dense, complex matrices
setClass("zdenseMatrix",
         contains = c("VIRTUAL", "zMatrix", "denseMatrix"))
} # --NOT YET--


## ------ Virtual Sparse -----------------------------------------------

## Virtual class of sparse matrices
## * includes diagonal matrices since 0.999375-11 (2008-07)
setClass("sparseMatrix",
         contains = c("VIRTUAL", "Matrix"))


## ...... Virtual Sparse ... by storage ................................

## Virtual class of sparse matrices in compressed sparse column (CSC) format
setClass("CsparseMatrix",
         contains = c("VIRTUAL", "sparseMatrix"),
         slots = c(i = "integer", p = "integer"),
         prototype = list(p = 0L), # to be valid
         validity = function(object) .Call(CsparseMatrix_validate, object))

## Virtual class of sparse matrices in compressed sparse row (CSR) format
setClass("RsparseMatrix",
         contains = c("VIRTUAL", "sparseMatrix"),
         slots = c(p = "integer", j = "integer"),
         prototype = list(p = 0L), # to be valid
         validity = function(object) .Call(RsparseMatrix_validate, object))

## Virtual class of sparse matrices in triplet format
setClass("TsparseMatrix",
         contains = c("VIRTUAL", "sparseMatrix"),
         slots = c(i = "integer", j = "integer"),
         validity = function(object) .Call(TsparseMatrix_validate, object))

## Virtual class of diagonal matrices
setClass("diagonalMatrix",
         contains = c("VIRTUAL", "sparseMatrix"),
         slots = c(diag = "character"),
         prototype = list(diag = "N"),
         validity = function(object) .Call(diagonalMatrix_validate, object))

if(FALSE) { # --NOT YET--
## These methods would allow initialization of zero matrices _without_ 'p',
## as in the call new("dgCMatrix", Dim = c(6L, 6L)).  However, they would
## also incur a small performance penalty on all other new("..[CR]Matrix")
## calls.
setMethod("initialize", c(.Object = "CsparseMatrix"),
          function(.Object, ...) {
              ## Suboptimal if ...names() is NULL or if 'Dim' is missing
              ## but that will "never" happen if ...length() is nonzero:
              if(...length() &&
                 all((nms <- ...names()) != "p") &&
                 length(w <- which(nms == "Dim")) &&
                 !is.character(validDim(d <- ...elt(w[1L]))))
                  callNextMethod(.Object, ..., p = integer(d[2L] + 1))
              else callNextMethod()
          })

setMethod("initialize", c(.Object = "RsparseMatrix"),
          function(.Object, ...) {
              ## Suboptimal if ...names() is NULL or if 'Dim' is missing
              ## but that will "never" happen if ...length() is nonzero:
              if(...length() &&
                 all((nms <- ...names()) != "p") &&
                 length(w <- which(nms == "Dim")) &&
                 !is.character(validDim(d <- ...elt(w[1L]))))
                  callNextMethod(.Object, ..., p = integer(d[1L] + 1))
              else callNextMethod()
          })
} # --NOT YET--


## ...... Virtual Sparse ... by kind ...................................

## Virtual class of sparse, nonzero pattern matrices
## * these are the "pattern" matrices from "symbolic analysis" of sparse OPs
setClass("nsparseMatrix",
         contains = c("VIRTUAL", "nMatrix", "sparseMatrix"))

## Virtual class of sparse, logical matrices
setClass("lsparseMatrix",
         contains = c("VIRTUAL", "lMatrix", "sparseMatrix"))

if(FALSE) { # --NOT YET--
## Virtual class of sparse, integer matrices
setClass("isparseMatrix",
         contains = c("VIRTUAL", "iMatrix", "sparseMatrix"))
} # --NOT YET--

## Virtual class of sparse, double matrices
setClass("dsparseMatrix",
         contains = c("VIRTUAL", "dMatrix", "sparseMatrix"))

if(FALSE) { # --NOT YET--
## Virtual class of sparse, complex matrices
setClass("zsparseMatrix",
         contains = c("VIRTUAL", "zMatrix", "sparseMatrix"))
} # --NOT YET--


## ====== Non-Virtual Subclasses =======================================

## ------ Non-Virtual Dense --------------------------------------------

## ...... Dense, nonzero pattern .......................................

## Unpacked, general
setClass("ngeMatrix",
         contains = c("unpackedMatrix", "ndenseMatrix", "generalMatrix"))

## Unpacked, symmetric
setClass("nsyMatrix",
         contains = c("unpackedMatrix", "ndenseMatrix", "symmetricMatrix"))

## Unpacked, triangular
setClass("ntrMatrix",
         contains = c("unpackedMatrix", "ndenseMatrix", "triangularMatrix"))

## Packed, symmetric
setClass("nspMatrix",
         contains = c("packedMatrix", "ndenseMatrix", "symmetricMatrix"))

## Packed, triangular
setClass("ntpMatrix",
         contains = c("packedMatrix", "ndenseMatrix", "triangularMatrix"))


## ...... Dense, logical ...............................................

## Unpacked, general
setClass("lgeMatrix",
         contains = c("unpackedMatrix", "ldenseMatrix", "generalMatrix"))

## Unpacked, symmetric
setClass("lsyMatrix",
         contains = c("unpackedMatrix", "ldenseMatrix", "symmetricMatrix"))

## Unpacked, triangular
setClass("ltrMatrix",
         contains = c("unpackedMatrix", "ldenseMatrix", "triangularMatrix"))

## Packed, symmetric
setClass("lspMatrix",
         contains = c("packedMatrix", "ldenseMatrix", "symmetricMatrix"))

## Packed, triangular
setClass("ltpMatrix",
         contains = c("packedMatrix", "ldenseMatrix", "triangularMatrix"))


## ...... Dense, double ................................................

## Unpacked, general
setClass("dgeMatrix",
         contains = c("unpackedMatrix", "ddenseMatrix", "generalMatrix"))

## Unpacked, symmetric
setClass("dsyMatrix",
         contains = c("unpackedMatrix", "ddenseMatrix", "symmetricMatrix"))

## Unpacked, symmetric, positive semidefinite
setClass("dpoMatrix",
         contains = "dsyMatrix",
         validity = function(object) .Call(dpoMatrix_validate, object))

## Unpacked, symmetric, positive semidefinite, correlation
setClass("corMatrix",
         contains = "dpoMatrix",
         slots = c(sd = "numeric"),
         validity = function(object) .Call(corMatrix_validate, object))

## Unpacked, triangular
setClass("dtrMatrix",
         contains = c("unpackedMatrix", "ddenseMatrix", "triangularMatrix"))

## Packed, symmetric
setClass("dspMatrix",
         contains = c("packedMatrix", "ddenseMatrix", "symmetricMatrix"))

## Packed, symmetric, positive semidefinite
setClass("dppMatrix",
         contains = "dspMatrix",
         validity = function(object) .Call(dppMatrix_validate, object))

## Packed, symmetric, positive semidefinite, correlation
setClass("copMatrix",
         contains = "dppMatrix",
         slots = c(sd = "numeric"),
         validity = function(object) .Call(copMatrix_validate, object))

## Packed, triangular
setClass("dtpMatrix",
         contains = c("packedMatrix", "ddenseMatrix", "triangularMatrix"))


## ------ Non-Virtual Sparse -------------------------------------------

## ...... Sparse, nonzero pattern ......................................

## NB: Unlike [^n]sparseMatrix (below), there is no 'x' slot to validate here.

## CSC, general
setClass("ngCMatrix",
         contains = c("CsparseMatrix", "nsparseMatrix", "generalMatrix"))

## CSC, symmetric
setClass("nsCMatrix",
         contains = c("CsparseMatrix", "nsparseMatrix", "symmetricMatrix"),
         validity = function(object) .Call(sCMatrix_validate, object))

## CSC, triangular
setClass("ntCMatrix",
         contains = c("CsparseMatrix", "nsparseMatrix", "triangularMatrix"),
         validity = function(object) .Call(tCMatrix_validate, object))

## CSR, general
setClass("ngRMatrix",
         contains = c("RsparseMatrix", "nsparseMatrix", "generalMatrix"))

## CSR, symmetric
setClass("nsRMatrix",
         contains = c("RsparseMatrix", "nsparseMatrix", "symmetricMatrix"),
         validity = function(object) .Call(sRMatrix_validate, object))

## CSR, triangular
setClass("ntRMatrix",
         contains = c("RsparseMatrix", "nsparseMatrix", "triangularMatrix"),
         validity = function(object) .Call(tRMatrix_validate, object))

## Triplet general
setClass("ngTMatrix",
         contains = c("TsparseMatrix", "nsparseMatrix", "generalMatrix"))

## Triplet, symmetric
setClass("nsTMatrix",
         contains = c("TsparseMatrix", "nsparseMatrix", "symmetricMatrix"),
         validity = function(object) .Call(sTMatrix_validate, object))

## Triplet, triangular
setClass("ntTMatrix",
         contains = c("TsparseMatrix", "nsparseMatrix", "triangularMatrix"),
         validity = function(object) .Call(tTMatrix_validate, object))

## Diagonal
setClass("ndiMatrix",
         contains = c("diagonalMatrix", "nMatrix"),
         slots = c(x = "logical"),
         validity = function(object) .Call(nMatrix_validate, object))


## ...... Sparse, logical ..............................................

## CSC, general
setClass("lgCMatrix",
         contains = c("CsparseMatrix", "lsparseMatrix", "generalMatrix"),
         validity = function(object) .Call(xgCMatrix_validate, object))

## CSC, symmetric
setClass("lsCMatrix",
         contains = c("CsparseMatrix", "lsparseMatrix", "symmetricMatrix"),
         validity = function(object) .Call(xsCMatrix_validate, object))

## CSC, triangular
setClass("ltCMatrix",
         contains = c("CsparseMatrix", "lsparseMatrix", "triangularMatrix"),
         validity = function(object) .Call(xtCMatrix_validate, object))

## CSR, general
setClass("lgRMatrix",
         contains = c("RsparseMatrix", "lsparseMatrix", "generalMatrix"),
         validity = function(object) .Call(xgRMatrix_validate, object))

## CSR, symmetric
setClass("lsRMatrix",
         contains = c("RsparseMatrix", "lsparseMatrix", "symmetricMatrix"),
         validity = function(object) .Call(xsRMatrix_validate, object))

## CSR, triangular
setClass("ltRMatrix",
         contains = c("RsparseMatrix", "lsparseMatrix", "triangularMatrix"),
         validity = function(object) .Call(xtRMatrix_validate, object))

## Triplet, general
setClass("lgTMatrix",
         contains = c("TsparseMatrix", "lsparseMatrix", "generalMatrix"),
         validity = function(object) .Call(xgTMatrix_validate, object))

## Triplet, symmetric
setClass("lsTMatrix",
         contains = c("TsparseMatrix", "lsparseMatrix", "symmetricMatrix"),
         validity = function(object) .Call(xsTMatrix_validate, object))

## Triplet, triangular
setClass("ltTMatrix",
         contains = c("TsparseMatrix", "lsparseMatrix", "triangularMatrix"),
         validity = function(object) .Call(xtTMatrix_validate, object))

## Diagonal
setClass("ldiMatrix",
         contains = c("diagonalMatrix", "lMatrix"))


## ...... Sparse, double ...............................................

## CSC, general
setClass("dgCMatrix",
         contains = c("CsparseMatrix", "dsparseMatrix", "generalMatrix"),
         validity = function(object) .Call(xgCMatrix_validate, object))

## CSC, symmetric
setClass("dsCMatrix",
         contains = c("CsparseMatrix", "dsparseMatrix", "symmetricMatrix"),
         validity = function(object) .Call(xsCMatrix_validate, object))

## CSC, triangular
setClass("dtCMatrix",
         contains = c("CsparseMatrix", "dsparseMatrix", "triangularMatrix"),
         validity = function(object) .Call(xtCMatrix_validate, object))

## CSR, general
setClass("dgRMatrix",
         contains = c("RsparseMatrix", "dsparseMatrix", "generalMatrix"),
         validity = function(object) .Call(xgRMatrix_validate, object))

## CSR, symmetric
setClass("dsRMatrix",
         contains = c("RsparseMatrix", "dsparseMatrix", "symmetricMatrix"),
         validity = function(object) .Call(xsRMatrix_validate, object))

## CSR, triangular
setClass("dtRMatrix",
         contains = c("RsparseMatrix", "dsparseMatrix", "triangularMatrix"),
         validity = function(object) .Call(xtRMatrix_validate, object))

## Triplet, general
setClass("dgTMatrix",
         contains = c("TsparseMatrix", "dsparseMatrix", "generalMatrix"),
         validity = function(object) .Call(xgTMatrix_validate, object))

## Triplet, symmetric
setClass("dsTMatrix",
         contains = c("TsparseMatrix", "dsparseMatrix", "symmetricMatrix"),
         validity = function(object) .Call(xsTMatrix_validate, object))

## Triplet, triangular
setClass("dtTMatrix",
         contains = c("TsparseMatrix", "dsparseMatrix", "triangularMatrix"),
         validity = function(object) .Call(xtTMatrix_validate, object))

## Diagonal
setClass("ddiMatrix",
         contains = c("diagonalMatrix", "dMatrix"))

if(FALSE) { # TODO
## CSC, symmetic, positive semidefinite
setClass("dpCMatrix",
         contains = "dsCMatrix",
         validity = function(object) TODO("test positive semidefiniteness"))

## CSR, symmetic, positive semidefinite
setClass("dpRMatrix",
         contains = "dsRMatrix",
         validity = function(object) TODO("test positive semidefiniteness"))

## Triplet, symmetic, positive semidefinite
setClass("dpTMatrix",
         contains = "dsTMatrix",
         validity = function(object) TODO("test positive semidefiniteness"))
} # TODO


## ...... Sparse, index ................................................

## Row or column index
setClass("indMatrix",
         contains = "sparseMatrix",
         slots = c(perm = "integer", margin = "integer"),
         prototype = list(margin = 1L), # to be valid
         validity = function(object) .Call(indMatrix_validate, object))

## Row or column permutation
setClass("pMatrix",
         contains = "indMatrix",
         validity = function(object) .Call(pMatrix_validate, object))


########################################################################
##  2. MatrixFactorization
########################################################################

## ------ The Mother Class "MatrixFactorization" -----------------------

setClass("MatrixFactorization",
         contains = "VIRTUAL",
         slots = c(Dim = "integer", Dimnames = "list"),
         prototype = list(Dim = integer(2L), Dimnames = list(NULL, NULL)),
         validity = function(object).Call(MatrixFactorization_validate, object))

setMethod("initialize", c(.Object = "MatrixFactorization"),
          .initialize)


## ------ LU -----------------------------------------------------------

setClass("LU",
         contains = c("VIRTUAL", "MatrixFactorization"))

## Inherit most aspects of dgeMatrix without extending it

setClass("denseLU",
         contains = "LU",
         slots = c(x = "numeric", perm = "integer"),
         validity = function(object) {
             object. <- new("dgeMatrix")
             object.@Dim <- object@Dim
             object.@Dimnames <- object@Dimnames
             object.@x <- object@x
             if(is.character(valid <- validObject(object., test = TRUE)))
                 valid
             else .Call(denseLU_validate, object)
         })

setClass("sparseLU",
         contains = "LU",
         slots = c(L = "dtCMatrix", U = "dtCMatrix",
                   p = "integer", q = "integer"),
         prototype = list(L = .new("dtCMatrix", uplo = "L")),
         validity = function(object) .Call(sparseLU_validate, object))


## ------ QR -----------------------------------------------------------

setClass("QR",
         contains = c("VIRTUAL", "MatrixFactorization"))

if(FALSE) {
## MJ: It would nice to have symmetry with LU, but then we would need
##     to define methods already available for S3 class 'qr'.  Still ...
setClass("denseQR",
         contains = "QR",
         ## based on S3 class 'qr':
         slots = c(qr = "numeric", qraux = "numeric",
                   rank = "integer", pivot = "integer",
                   useLAPACK = "logical"),
         validity = function(object) .Call(denseQR_validate, object))
}

setClass("sparseQR",
         contains = "QR",
         slots = c(beta = "numeric", V = "dgCMatrix", R = "dgCMatrix",
                   p = "integer", q = "integer"),
         validity = function(object) .Call(sparseQR_validate, object))


## ------ Bunch-Kaufman ------------------------------------------------

setClass("BunchKaufmanFactorization",
         contains = c("VIRTUAL", "MatrixFactorization"))

## Inherit most aspects of dt[rp]Matrix without extending them

setClass("BunchKaufman",
         contains = "BunchKaufmanFactorization",
         slots = c(uplo = "character", x = "numeric", perm = "integer"),
         prototype = list(uplo = "U"),
         validity = function(object) {
             object. <- new("dtrMatrix")
             object.@Dim <- object@Dim
             object.@Dimnames <- object@Dimnames
             object.@uplo <- object@uplo
             object.@x <- object@x
             if(is.character(valid <- validObject(object., test = TRUE)))
                 valid
             else .Call(BunchKaufman_validate, object)
         })

setClass("pBunchKaufman",
         contains = "BunchKaufmanFactorization",
         slots = c(uplo = "character", x = "numeric", perm = "integer"),
         prototype = list(uplo = "U"),
         validity = function(object) {
             object. <- new("dtpMatrix")
             object.@Dim <- object@Dim
             object.@Dimnames <- object@Dimnames
             object.@uplo <- object@uplo
             object.@x <- object@x
             if(is.character(valid <- validObject(object., test = TRUE)))
                 valid
             else .Call(pBunchKaufman_validate, object)
         })


## ------ Cholesky -----------------------------------------------------

setClass("CholeskyFactorization",
         contains = c("VIRTUAL", "MatrixFactorization"))


## ...... Dense ........................................................

## Inherit most aspects of dt[rp]Matrix without extending them

setClass("Cholesky",
         contains = "CholeskyFactorization",
         slots = c(uplo = "character", x = "numeric", perm = "integer"),
         prototype = list(uplo = "U"),
         validity = function(object) {
             object. <- new("dtrMatrix")
             object.@Dim <- object@Dim
             object.@Dimnames <- object@Dimnames
             object.@uplo <- object@uplo
             object.@x <- object@x
             if(is.character(valid <- validObject(object., test = TRUE)))
                 valid
             else .Call(Cholesky_validate, object)
         })

setClass("pCholesky",
         contains = "CholeskyFactorization",
         slots = c(uplo = "character", x = "numeric", perm = "integer"),
         prototype = list(uplo = "U"),
         validity = function(object) {
             object. <- new("dtpMatrix")
             object.@Dim <- object@Dim
             object.@Dimnames <- object@Dimnames
             object.@uplo <- object@uplo
             object.@x <- object@x
             if(is.character(valid <- validObject(object., test = TRUE)))
                 valid
             else .Call(pCholesky_validate, object)
         })


## ...... Sparse .......................................................

## FIXME? simplicial symbolic factorization is specified entirely by
##        'colcount' and 'perm' ...
##        should 'p', 'i', 'nz', 'nxt', 'prv' slots all be emtpy ??
##        see comments in ../src/CHOLMOD/Core/cholmod_change_factor.c

## S4 representation of C struct 'cholmod_factor',
## from header ../src/CHOLMOD/Include/cholmod_core.h
setClass("CHMfactor",
         contains = c("VIRTUAL", "CholeskyFactorization"),
         slots = c(type = "integer", colcount = "integer", perm = "integer"),
         validity = function(object) .Call(CHMfactor_validate, object))

## Simplicial factorization
setClass("CHMsimpl",
         contains = c("VIRTUAL", "CHMfactor"),
         slots = c(p = "integer", i = "integer", nz = "integer",
                   nxt = "integer", prv = "integer"),
         prototype = list(type = c(0L, 1L, 0L, 1L, 0L, 0L),
                          p = 0L, nxt = c(-1L, 0L), prv = c(1L, -1L)),
         validity = function(object) .Call(CHMsimpl_validate, object))

setClass("nCHMsimpl",
         contains = "CHMsimpl")
setClass("dCHMsimpl",
         contains = "CHMsimpl",
         slots = c(x = "numeric"),
         validity = function(object) .Call(dCHMsimpl_validate, object))

## Supernodal factorization
setClass("CHMsuper",
         contains = c("VIRTUAL", "CHMfactor"),
         slots = c(super = "integer", pi = "integer", px = "integer",
                   s = "integer"),
         prototype = list(type = c(0L, 1L, 1L, 1L, 0L, 0L),
                          super = 0L, pi = 0L, px = 0L),
         validity = function(object) .Call(CHMsuper_validate, object))

setClass("nCHMsuper",
         contains = "CHMsuper")
setClass("dCHMsuper",
         contains = "CHMsuper",
         slots = c(x = "numeric"),
         validity = function(object) .Call(dCHMsuper_validate, object))


## ------ Schur --------------------------------------------------------

setClass("SchurFactorization",
         contains = c("VIRTUAL", "MatrixFactorization"))

setClass("Schur",
         contains = "SchurFactorization",
         slots = c(Q = "Matrix", T = "Matrix", EValues = "vector"),
         prototype = list(Q = .new("dgeMatrix"), T = .new("dgeMatrix"),
                          EValues = double(0L)),
         validity = function(object) .Call(Schur_validate, object))


########################################################################
##  3. sparseVector
########################################################################

## ------ The Mother Class 'sparseVector' ------------------------------

setClass("sparseVector",
         contains = "VIRTUAL",
         slots = c(length = "numeric", i = "numeric"), # 1-based index!
         prototype = list(length = 0),
         validity = function(object) .Call(sparseVector_validate, object))

## Allow users to do new("[nlidz]sparseVector", i=, x=) with unsorted 'i'
setMethod("initialize", c(.Object = "sparseVector"),
          function(.Object, i, x, ...) {
              if(has.x <- !missing(x))
                  x <- x # MJ: why is this necessary?
              if(!missing(i)) {
                  i.uns <- is.unsorted(i, strictly = TRUE)
                  i <-
                      if(is.na(i.uns) || !i.uns)
                          i
                      else {
                          ## we know that there are no NA, and the order of
                          ## ties does not matter (since ties are an error),
                          ## hence it is safe to use "quick" here
                          m <- if(is.integer(length(i))) "radix" else "quick"
                          if(.hasSlot(.Object, "x") && has.x) {
                              s <- sort.int(i, method = m, index.return = TRUE)
                              x <- x[s$ix]
                              s$x
                          } else sort.int(i, method = m)
                      }
              }
              callNextMethod()
          })


## ------ Non-Virtual Subclasses ---------------------------------------

setClass("nsparseVector",
         contains = "sparseVector")

setClass("lsparseVector",
         contains = "sparseVector",
         slots = c(x = "logical"),
         validity = function(object) .Call(lsparseVector_validate, object))

setClass("isparseVector",
         contains = "sparseVector",
         slots = c(x = "integer"),
         validity = function(object) .Call(isparseVector_validate, object))

setClass("dsparseVector",
         contains = "sparseVector",
         slots = c(x = "numeric"),
         validity = function(object) .Call(dsparseVector_validate, object))

setClass("zsparseVector",
         contains = "sparseVector",
         slots = c(x = "complex"),
         validity = function(object) .Call(zsparseVector_validate, object))


########################################################################
##  4. Index and more "miscellaneous" classes, but _not_ class unions
########################################################################

## Idea: represent x = c(seq(from1, to1, by1), seq(from2, to2, by2), ...)
##       as list(first = x[1L], rle = rle(diff(x)))
setOldClass("rle")
setClass("rleDiff",
         ## MJ: simpler would be slots = c(first=, lengths=, values=) ...
         slots = c(first = "numeric", rle = "rle"),
         prototype = list(first = integer(0L), rle = rle(integer(0L))),
         validity = function(object) {
             if(length(object@first) != 1L)
                 "'first' slot does not have length 1"
             else if(!is.list(rle <- object@rle))
                 "'rle' slot is not a list"
             else if(length(rle) != 2L)
                 "'rle' slot does not have length 2"
             else if(is.null(nms <- names(rle)) ||
                     anyNA(match(nms, c("lengths", "values"))))
                 "'rle' slot does not have names \"lengths\", \"values\""
             else if(!is.numeric(lens <- rle$lengths))
                 "'lengths' is not numeric"
             else if(!is.numeric(vals <- rle$values))
                 "'values' is not numeric"
             else if(length(lens) != length(vals))
                 "'lengths' and 'values' do not have equal length"
             else if(length(lens) == 0L)
                 TRUE
             else if(anyNA(lens))
                 "'lengths' contains NA"
             else if(is.double(lens)) {
                 if(!(all(is.finite(r <- range(lens))) &&
                      all(lens == trunc(lens))))
                     "'lengths' is not integer-valued"
                 else if(r[1L] < 1)
                     "'lengths' is not positive"
                 else TRUE
             } else {
                 if(min(lens) < 1L)
                     "'lengths' is not positive"
                 else TRUE
             }
         })

## Idea: represent x = c(seq(from1, to1, by1), seq(from2, to2, by2), ...)
##       as rbind(c(from1, from2, ...), c(to1, to2, ...), c(by1, by2, ...))
## MM: (2010-03-04) more efficient than "rleDiff" [TODO: write rleDiff<->seqMat]
## MJ: (2022-09-06) data.frame(from, to, by) could be _handled_ more efficiently
setClass("seqMat",
         contains = "matrix",
         prototype = matrix(integer(0L), nrow = 3L, ncol = 0L),
         validity = function(object) {
             if(!is.numeric(object))
                 "matrix is not numeric"
             else if(nrow(object) != 3L)
                 "matrix does not have 3 rows"
             else if(anyNA(object))
                 "matrix contains NA"
             else if(is.double(object) && !(all(is.finite(range(object))) &&
                                            all(object == trunc(object))))
                 "matrix is not integer-valued"
             else {
                 from <- object[1L, ]
                 to   <- object[2L, ]
                 by   <- object[3L, ]
                 if(any((from < to & by <= 0) | (from > to & by >= 0)))
                     "degenerate sequence(s): sign(to - from) != sign(by)"
                 else TRUE
             }
         })

## Idea: _ab_stract index
## MJ: (2022-09-06) why not just
##     setClassUnion("abIndex", members = c("numeric", "rleDiff", "seqMat")) ?
setClass("abIndex",
         slots = c(kind = "character", x = "numeric", rleD = "rleDiff"),
         prototype = list(kind = "int32", x = integer(0L)),
         validity = function(object) {
             ## MJ: should 'rleD' be "empty" if kind != "rleDiff" ?
             if(length(kind <- object@kind) != 1L)
                 "'kind' slot does not have length 1"
             else switch(kind,
                         "int32" =
                             if(is.integer(object@x))
                                 TRUE
                             else "kind=\"int32\" but 'x' slot is not of type \"integer\"",
                         "double" =
                             if(is.double(object@x))
                                 TRUE
                             else "kind=\"double\" but 'x' slot is not of type \"double\"",
                         "rleDiff" =
                             if(length(object@x) == 0L)
                                 TRUE
                             else "kind=\"rleDiff\" but 'x' slot is nonempty",
                         ## otherwise:
                         "'kind' is not \"int32\", \"double\", or \"rleDiff\"")
         })


########################################################################
##  5. Class unions
########################################################################

## MJ: aim to deprecate and eventually remove these
##     (except perhaps 'index')

setClassUnion("atomicVector",
              members = c("raw", "logical", "numeric", "complex", "character"))
setClassUnion("index",
              members = c(       "logical", "numeric",            "character"))
setClassUnion("numLike",
              members = c(       "logical", "numeric"                        ))
setClassUnion("number",
              members = c(                  "numeric", "complex"             ))
setClassUnion("replValue",
              members = c("raw", "logical", "numeric", "complex"             ))

## Removing these entirely in Matrix 1.7-0 invalidates class definitions
## serialized in existing installations of the following packages:
##
##  [1] CVXR                 FinNet               GENLIB
##  [4] MSnbase              MachineShop          MatrixModels
##  [7] SeuratObject         SingleCellExperiment WoodburyMatrix
## [10] apcluster            arules               chromVAR
## [13] conText              copula               destiny
## [16] distrom              genomation           hypr
## [19] iGraphMatch          kebabs               mcompanion
## [22] pcts                 podkat               qpgraph
## [25] quadrupen            quanteda             quanteda.textstats
## [28] saeRobust            scuttle              snpStats
## [31] softImpute           spflow               xcms
##
## Define stubs so that the serialized class definitions do not cause S4
## machinery to throw warnings or errors.  Remove the stubs once binaries
## in most repositories seem to have been rebuilt under Matrix 1.7-0.
setClass("compMatrix")
setClass("pcorMatrix")
setClassUnion("replValueSp")

rm(.new, .initialize)