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 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
|
---
title: "Extending the SummarizedExperiment class"
author: Aaron Lun
date: "Revised: 30 October, 2018"
output:
BiocStyle::html_document:
toc: true
toc_float: true
vignette: >
%\VignetteIndexEntry{2. Extending the SummarizedExperiment class}
%\VignetteEngine{knitr::rmarkdown}
\usepackage[utf8]{inputenc}
---
```{r, echo=FALSE, results="hide"}
knitr::opts_chunk$set(error=FALSE, warning=FALSE, message=FALSE)
```
```{r, echo=FALSE}
library(SummarizedExperiment)
library(testthat)
```
# Motivation
A large number of Bioconductor packages contain extensions of the
standard `SummarizedExperiment` class from the
[SummarizedExperiment][] package. This allows developers to take
advantage of the power of the `SummarizedExperiment` representation
for synchronising data and metadata, while still accommodating
specialized data structures for particular scientific applications.
This document is intended to provide a developer-level "best
practices" reference for the creation of these derived classes.
# Deriving a simple class
## Overview
To introduce various concepts, we will start off with a simple derived
class that does not add any new slots. This is occasionally useful
when additional constraints need to be placed on the derived class.
In this example, we will assume that we want our class to minimally
hold a `"counts"` assay that contains non-negative
values^[For simplicity's sake, we won't worry about enforcing integer type, as fractional values are possible, e.g., when dealing with expected counts.].
## Defining the class and its constructor
We name our new class `CountSE` and define it using the `setClass`
function from the _methods_ package, as is conventionally done for all
S4 classes. We use Roxygen's `#'` tags to trigger the generation of
import/export statements in the `NAMESPACE` of our package.
```{r}
#' @export
#' @import methods
#' @importClassesFrom SummarizedExperiment SummarizedExperiment
.CountSE <- setClass("CountSE", contains="SummarizedExperiment")
```
We define a constructor that accepts a count matrix to create a
`CountSE` object. We use `...` to pass further arguments to the
`SummarizedExperiment` constructor, which allows us to avoid
re-specifying all its arguments.
```{r}
#' @export
#' @importFrom SummarizedExperiment SummarizedExperiment
CountSE <- function(counts, ...) {
se <- SummarizedExperiment(list(counts=counts), ...)
.CountSE(se)
}
```
## Defining a validity method
We define a validity method that enforces the constraints that we
described earlier. This is done by defining a validity function using
`setValidity2` from the [S4Vectors][]
package^[This allows us to turn off the validity checks in internal functions where intermediate objects may not be valid within the scope of the function.].
Returning a string indicates that there is a problem and triggers an
error in the R session.
```{r}
setValidity2("CountSE", function(object) {
msg <- NULL
if (assayNames(object)[1] != "counts") {
msg <- c(msg, "'counts' must be first assay")
}
if (min(assay(object)) < 0) {
msg <- c(msg, "negative values in 'counts'")
}
if (is.null(msg)) {
TRUE
} else msg
})
```
The constructor yields the expected output when counts are provided:
```{r}
CountSE(matrix(rpois(100, lambda=1), ncol=5))
```
... and an (expected) error otherwise:
```{r, error=TRUE}
CountSE(matrix(rnorm(100), ncol=5))
```
## Defining a getter method
A generic is a group of functions with the same name that operate on
different classes. Upon calling the generic on an object, the S4
dispatch system will choose the most appropriate function to use based
on the object class. This allows users and developers to write code
that is agnostic to the type of input class.
Let's say that it is of particular scientific interest to obtain the
counts with a flipped sign. We observe that there are no existing
generics that do this task, e.g., in [BiocGenerics][] or
[S4Vectors][]^[If you have an idea for a generally applicable generic that is not yet available, please contact the Bioconductor core team.].
Instead, we define a new generic `negcounts`:
```{r}
#' @export
setGeneric("negcounts", function(x, ...) standardGeneric("negcounts"))
```
We then define a specific method for our `CountSE`
class^[The `...` in the generic function definition means that custom arguments like `withDimnames=` can be provided for specific methods, if necessary.]:
```{r}
#' @export
#' @importFrom SummarizedExperiment assay
setMethod("negcounts", "CountSE", function(x, withDimnames=TRUE) {
-assay(x, withDimnames=withDimnames)
})
```
If any other developers need to compute negative counts for their own
classes, they can simply use the `negcounts` generic defined in our
package.
## Some comments on package organization
It is convention to put all class definitions (i.e., the `setClass`
statement) in a file named `AllClasses.R`, all new generic definitions
in a file named `AllGenerics.R`, and all method definitions in files
that are alphanumerically ordered below the first two. This is
because R collates files by alphanumeric order when building a
package. It is critical that the collation (and definition) of the
classes and generics occurs **before** that of the corresponding
methods, otherwise errors will occur. If alphanumeric ordering is
inappropriate, developers can manually specify the collation order
using `Collate:` in the `DESCRIPTION` file - see
[Writing R Extensions][R-exts] for more details.
[R-exts]: https://cran.r-project.org/doc/manuals/r-release/R-exts.html#The-DESCRIPTION-file
# Deriving a class with custom slots
## Class definition
In practice, most derived classes will need to store
application-specific data structures. For the rest of this document,
we will be considering the derivation of a class with custom slots to
hold such structures. First, we consider 1D data structures:
- `rowVec`: 1:1 mapping from each value to a row of the
`SummarizedExperiment`.
- `colVec`: 1:1 mapping from each value to a column of the
`SummarizedExperiment`.
Any 1D structure can be used if it supports `length`, `c`,
`[` and `[<-`. For simplicity, we will use integer vectors for the `*.vec`
slots.
We also consider some 2D data structures:
- `rowToRowMat`: 1:1 mapping from each row to a row of the
`SummarizedExperiment`.
- `colToColMat`: 1:1 mapping from each column to a column of the
`SummarizedExperiment`.
- `rowToColMat`: 1:1 mapping from each row to a column of the
`SummarizedExperiment`.
- `colToRowMat`: 1:1 mapping from each column to a row of the
`SummarizedExperiment`.
Any 2D structure can be used if it supports `nrow`, `ncol`, `cbind`, `rbind`,
`[` and `[<-`. For simplicity, we will use (numeric) matrices for the `*.mat`
slots.
Definition of the class is achieved using `setClass`, using the `slots=`
argument to specify the new custom slots^[It does no harm to repeat the Roxygen tags, which explicitly specifies the imports required for each class and function.].
```{r}
#' @export
#' @import methods
#' @importClassesFrom SummarizedExperiment SummarizedExperiment
.ExampleClass <- setClass("ExampleClass",
slots= representation(
rowVec="integer",
colVec="integer",
rowToRowMat="matrix",
colToColMat="matrix",
rowToColMat="matrix",
colToRowMat="matrix"
),
contains="SummarizedExperiment"
)
```
## Defining the constructor
The constructor should provide some arguments for setting the new
slots in the derived class definition. The default values should be
set such that calling the constructor without any arguments returns a
valid `ExampleClass` object.
```{r}
#' @export
#' @importFrom SummarizedExperiment SummarizedExperiment
ExampleClass <- function(
rowVec=integer(0),
colVec=integer(0),
rowToRowMat=matrix(0,0,0),
colToColMat=matrix(0,0,0),
rowToColMat=matrix(0,0,0),
colToRowMat=matrix(0,0,0),
...)
{
se <- SummarizedExperiment(...)
.ExampleClass(se, rowVec=rowVec, colVec=colVec,
rowToRowMat=rowToRowMat, colToColMat=colToColMat,
rowToColMat=rowToColMat, colToRowMat=colToRowMat)
}
```
## Creating getter methods
### For 1D data structures
We define some getter generics for the custom slots containing the 1D
structures.
```{r}
#' @export
setGeneric("rowVec", function(x, ...) standardGeneric("rowVec"))
#' @export
setGeneric("colVec", function(x, ...) standardGeneric("colVec"))
```
We then define the class-specific methods for these generics. Note
the `withDimnames=TRUE` argument, which enforces consistency between
the names of the extracted object and the original
`SummarizedExperiment`. It is possible to turn this off for greater
efficiency, e.g., for internal usage where names are not necessary.
```{r}
#' @export
setMethod("rowVec", "ExampleClass", function(x, withDimnames=TRUE) {
out <- x@rowVec
if (withDimnames)
names(out) <- rownames(x)
out
})
#' @export
setMethod("colVec", "ExampleClass", function(x, withDimnames=TRUE) {
out <- x@colVec
if (withDimnames)
names(out) <- colnames(x)
out
})
```
### For 2D data structures
We repeat this process for the 2D structures.
```{r}
#' @export
setGeneric("rowToRowMat", function(x, ...) standardGeneric("rowToRowMat"))
#' @export
setGeneric("colToColMat", function(x, ...) standardGeneric("colToColMat"))
#' @export
setGeneric("rowToColMat", function(x, ...) standardGeneric("rowToColMat"))
#' @export
setGeneric("colToRowMat", function(x, ...) standardGeneric("colToRowMat"))
```
Again, we define class-specific methods for these generics.
```{r}
#' @export
setMethod("rowToRowMat", "ExampleClass", function(x, withDimnames=TRUE) {
out <- x@rowToRowMat
if (withDimnames)
rownames(out) <- rownames(x)
out
})
#' @export
setMethod("colToColMat", "ExampleClass", function(x, withDimnames=TRUE) {
out <- x@colToColMat
if (withDimnames)
colnames(out) <- colnames(x)
out
})
#' @export
setMethod("rowToColMat", "ExampleClass", function(x, withDimnames=TRUE) {
out <- x@rowToColMat
if (withDimnames)
rownames(out) <- colnames(x)
out
})
#' @export
setMethod("colToRowMat", "ExampleClass", function(x, withDimnames=TRUE) {
out <- x@colToRowMat
if (withDimnames)
colnames(out) <- rownames(x)
out
})
```
### For `SummarizedExperiment` slots
The getter methods defined in [SummarizedExperiment][] can be directly
used to retrieve data from slots in the base class. These should
generally not require any re-defining for a derived class. However,
if it is necessary, the methods should use `callNextMethod`
internally. This will call the method for the base
`SummarizedExperiment` class, the output of which can be modified as
required.
```{r}
#' @export
#' @importMethodsFrom SummarizedExperiment rowData
setMethod("rowData", "ExampleClass", function(x, ...) {
out <- callNextMethod()
# Do something extra here.
out$extra <- runif(nrow(out))
# Returning the rowData object.
out
})
```
## Defining the validity method
We use `setValidity2` to define a validity function for
`ExampleClass`. We use the previously defined getter functions to
retrieve the slot values rather than using `@`. This is generally a
good idea to keep the interface separate from the
implementation^[This protects against changes to the slot names, and simplifies development when the storage mode differs from the conceptual meaning of the data, e.g., for efficiency purposes.].
We also set `withDimnames=FALSE` in our getter calls, as consistent
naming is not necessary for internal functions.
```{r}
#' @importFrom BiocGenerics NCOL NROW
setValidity2("ExampleClass", function(object) {
NR <- NROW(object)
NC <- NCOL(object)
msg <- NULL
# 1D
if (length(rowVec(object, withDimnames=FALSE)) != NR) {
msg <- c(msg, "'rowVec' should have length equal to the number of rows")
}
if (length(colVec(object, withDimnames=FALSE)) != NC) {
msg <- c(
msg, "'colVec' should have length equal to the number of columns"
)
}
# 2D
if (NROW(rowToRowMat(object, withDimnames=FALSE)) != NR) {
msg <- c(
msg, "'nrow(rowToRowMat)' should be equal to the number of rows"
)
}
if (NCOL(colToColMat(object, withDimnames=FALSE)) != NC) {
msg <- c(
msg, "'ncol(colToColMat)' should be equal to the number of columns"
)
}
if (NROW(rowToColMat(object, withDimnames=FALSE)) != NC) {
msg <- c(
msg, "'nrow(rowToColMat)' should be equal to the number of columns"
)
}
if (NCOL(colToRowMat(object, withDimnames=FALSE)) != NR) {
msg <- c(
msg, "'ncol(colToRowMat)' should be equal to the number of rows"
)
}
if (length(msg)) {
msg
} else TRUE
})
```
We use the `NCOL` and `NROW` methods from [BiocGenerics][] as these
support various Bioconductor objects, whereas the base methods do not.
## Creating a `show` method
The default `show` method will only display information about the
`SummarizedExperiment` slots. We can augment it to display some
relevant aspects of the custom slots. This is done by calling the
base `show` method before printing additional fields as necessary.
```{r}
#' @export
#' @importMethodsFrom SummarizedExperiment show
setMethod("show", "ExampleClass", function(object) {
callNextMethod()
cat(
"rowToRowMat has ", ncol(rowToRowMat(object)), " columns\n",
"colToColMat has ", nrow(colToColMat(object)), " rows\n",
"rowToColMat has ", ncol(rowToRowMat(object)), " columns\n",
"colToRowMat has ", ncol(rowToRowMat(object)), " rows\n",
sep=""
)
})
```
## Creating setter methods
### For 1D data structures
We define some setter methods for the custom slots containing the 1D
structures. Again, this usually requires the creation of new
generics.
```{r}
#' @export
setGeneric("rowVec<-", function(x, ..., value) standardGeneric("rowVec<-"))
#' @export
setGeneric("colVec<-", function(x, ..., value) standardGeneric("colVec<-"))
```
We define the class-specific methods for these generics. Note that
use of `validObject` to ensure that the assigned input is still valid.
```{r}
#' @export
setReplaceMethod("rowVec", "ExampleClass", function(x, value) {
x@rowVec <- value
validObject(x)
x
})
#' @export
setReplaceMethod("colVec", "ExampleClass", function(x, value) {
x@colVec <- value
validObject(x)
x
})
```
### For 2D data structures
We repeat this process for the 2D structures.
```{r}
#' @export
setGeneric("rowToRowMat<-", function(x, ..., value)
standardGeneric("rowToRowMat<-")
)
#' @export
setGeneric("colToColMat<-", function(x, ..., value)
standardGeneric("colToColMat<-")
)
#' @export
setGeneric("rowToColMat<-", function(x, ..., value)
standardGeneric("rowToColMat<-")
)
#' @export
setGeneric("colToRowMat<-", function(x, ..., value)
standardGeneric("colToRowMat<-")
)
```
Again, we define class-specific methods for these generics.
```{r}
#' @export
setReplaceMethod("rowToRowMat", "ExampleClass", function(x, value) {
x@rowToRowMat <- value
validObject(x)
x
})
#' @export
setReplaceMethod("colToColMat", "ExampleClass", function(x, value) {
x@colToColMat <- value
validObject(x)
x
})
#' @export
setReplaceMethod("rowToColMat", "ExampleClass", function(x, value) {
x@rowToColMat <- value
validObject(x)
x
})
#' @export
setReplaceMethod("colToRowMat", "ExampleClass", function(x, value) {
x@colToRowMat <- value
validObject(x)
x
})
```
### For `SummarizedExperiment` slots
Again, we can use the setter methods defined in
[SummarizedExperiment][] to modify slots in the base class. These
should generally not require any re-defining. However, if it is
necessary, the methods should use `callNextMethod` internally:
```{r}
#' @export
#' @importMethodsFrom SummarizedExperiment "rowData<-"
setReplaceMethod("rowData", "ExampleClass", function(x, ..., value) {
y <- callNextMethod() # returns a modified ExampleClass
# Do something extra here.
message("hi!\n")
y
})
```
### Other types of modifying functions
Imagine that we want to write a function that returns a modified
`ExampleClass`, e.g., where the signs of the `*.vec` fields are
reversed. For example, we will pretend that we want to write a
`normalize` function, using the generic from [BiocGenerics][].
```{r}
#' @export
#' @importFrom BiocGenerics normalize
setMethod("normalize", "ExampleClass", function(object) {
# do something exciting, i.e., flip the signs
new.row <- -rowVec(object, withDimnames=FALSE)
new.col <- -colVec(object, withDimnames=FALSE)
BiocGenerics:::replaceSlots(object, rowVec=new.row,
colVec=new.col, check=FALSE)
})
```
We use `BiocGenerics:::replaceSlots` instead of the setter methods
that we defined above. This is because our setters perform validity
checks that are unnecessary if we know that the modification cannot
alter the validity of the object. The `replaceSlots` function allows
us to skip these validity checks (`check=FALSE`) for greater
efficiency.
## Enabling subsetting operations
### Getting a subset
A key strength of the `SummarizedExperiment` class is that subsetting
is synchronized across the various (meta)data fields. This avoids
book-keeping errors and guarantees consistency throughout an
interactive analysis session. We need to ensure that the values in
our custom slots are also subsetted.
```{r}
#' @export
setMethod("[", "ExampleClass", function(x, i, j, drop=TRUE) {
rv <- rowVec(x, withDimnames=FALSE)
cv <- colVec(x, withDimnames=FALSE)
rrm <- rowToRowMat(x, withDimnames=FALSE)
ccm <- colToColMat(x, withDimnames=FALSE)
rcm <- rowToColMat(x, withDimnames=FALSE)
crm <- colToRowMat(x, withDimnames=FALSE)
if (!missing(i)) {
if (is.character(i)) {
fmt <- paste0("<", class(x), ">[i,] index out of bounds: %s")
i <- SummarizedExperiment:::.SummarizedExperiment.charbound(
i, rownames(x), fmt
)
}
i <- as.vector(i)
rv <- rv[i]
rrm <- rrm[i,,drop=FALSE]
crm <- crm[,i,drop=FALSE]
}
if (!missing(j)) {
if (is.character(j)) {
fmt <- paste0("<", class(x), ">[,j] index out of bounds: %s")
j <- SummarizedExperiment:::.SummarizedExperiment.charbound(
j, colnames(x), fmt
)
}
j <- as.vector(j)
cv <- cv[j]
ccm <- ccm[,j,drop=FALSE]
rcm <- rcm[j,,drop=FALSE]
}
out <- callNextMethod()
BiocGenerics:::replaceSlots(out, rowVec=rv, colVec=cv,
rowToRowMat=rrm, colToColMat=ccm,
rowToColMat=rcm, colToRowMat=crm, check=FALSE)
})
```
Note the special code for handling character indices, and the use of
`callNextMethod` to subset the base `SummarizedExperiment` slots.
### Assigning a subset
Subset assignment can be similarly performed, though the signature
needs to be specified so that the replacement value is of the same
class. This is generally necessary for sensible replacement of the
custom slots.
```{r}
#' @export
setReplaceMethod("[", c("ExampleClass", "ANY", "ANY", "ExampleClass"),
function(x, i, j, ..., value) {
rv <- rowVec(x, withDimnames=FALSE)
cv <- colVec(x, withDimnames=FALSE)
rrm <- rowToRowMat(x, withDimnames=FALSE)
ccm <- colToColMat(x, withDimnames=FALSE)
rcm <- rowToColMat(x, withDimnames=FALSE)
crm <- colToRowMat(x, withDimnames=FALSE)
if (!missing(i)) {
if (is.character(i)) {
fmt <- paste0("<", class(x), ">[i,] index out of bounds: %s")
i <- SummarizedExperiment:::.SummarizedExperiment.charbound(
i, rownames(x), fmt
)
}
i <- as.vector(i)
rv[i] <- rowVec(value, withDimnames=FALSE)
rrm[i,] <- rowToRowMat(value, withDimnames=FALSE)
crm[,i] <- colToRowMat(value, withDimnames=FALSE)
}
if (!missing(j)) {
if (is.character(j)) {
fmt <- paste0("<", class(x), ">[,j] index out of bounds: %s")
j <- SummarizedExperiment:::.SummarizedExperiment.charbound(
j, colnames(x), fmt
)
}
j <- as.vector(j)
cv[j] <- colVec(value, withDimnames=FALSE)
ccm[,j] <- colToColMat(value, withDimnames=FALSE)
rcm[j,] <- rowToColMat(value, withDimnames=FALSE)
}
out <- callNextMethod()
BiocGenerics:::replaceSlots(out, rowVec=rv, colVec=cv,
rowToRowMat=rrm, colToColMat=ccm,
rowToColMat=rcm, colToRowMat=crm, check=FALSE)
})
```
## Defining combining methods
### By row
We need to define a `rbind` method for our custom class. This is done
by combining the custom per-row slots across class instances.
```{r}
#' @export
setMethod("rbind", "ExampleClass", function(..., deparse.level=1) {
args <- list(...)
all.rv <- lapply(args, rowVec, withDimnames=FALSE)
all.rrm <- lapply(args, rowToRowMat, withDimnames=FALSE)
all.crm <- lapply(args, colToRowMat, withDimnames=FALSE)
all.rv <- do.call(c, all.rv)
all.rrm <- do.call(rbind, all.rrm)
all.crm <- do.call(cbind, all.crm)
# Checks for identical column state.
ref <- args[[1]]
ref.cv <- colVec(ref, withDimnames=FALSE)
ref.ccm <- colToColMat(ref, withDimnames=FALSE)
ref.rcm <- rowToColMat(ref, withDimnames=FALSE)
for (x in args[-1]) {
if (!identical(ref.cv, colVec(x, withDimnames=FALSE))
|| !identical(ref.ccm, colToColMat(x, withDimnames=FALSE))
|| !identical(ref.rcm, rowToColMat(x, withDimnames=FALSE)))
{
stop("per-column values are not compatible")
}
}
old.validity <- S4Vectors:::disableValidity()
S4Vectors:::disableValidity(TRUE)
on.exit(S4Vectors:::disableValidity(old.validity))
out <- callNextMethod()
BiocGenerics:::replaceSlots(out, rowVec=all.rv,
rowToRowMat=all.rrm, colToRowMat=all.crm,
check=FALSE)
})
```
We check the other per-column slots across all elements to ensure that
they are the same. This protects the user against combining
incompatible objects. However, depending on the application, this may
not be necessary (or too costly) for all slots, in which case it can
be limited to critical slots.
We also use the `disableValidity` method to avoid the validity check
in the base `cbind` method. This is because the object is technically
invalid when the base slots are combined but before it is updated with
the new combined values for the custom slots. The `on.exit` call
ensures that the original validity setting is restored upon exit of
the function.
### By column
We similarly define a `cbind` method to handle the custom slots.
```{r}
#' @export
setMethod("cbind", "ExampleClass", function(..., deparse.level=1) {
args <- list(...)
all.cv <- lapply(args, colVec, withDimnames=FALSE)
all.ccm <- lapply(args, colToColMat, withDimnames=FALSE)
all.rcm <- lapply(args, rowToColMat, withDimnames=FALSE)
all.cv <- do.call(c, all.cv)
all.ccm <- do.call(cbind, all.ccm)
all.rcm <- do.call(rbind, all.rcm)
# Checks for identical column state.
ref <- args[[1]]
ref.rv <- rowVec(ref, withDimnames=FALSE)
ref.rrm <- rowToRowMat(ref, withDimnames=FALSE)
ref.crm <- colToRowMat(ref, withDimnames=FALSE)
for (x in args[-1]) {
if (!identical(ref.rv, rowVec(x, withDimnames=FALSE))
|| !identical(ref.rrm, rowToRowMat(x, withDimnames=FALSE))
|| !identical(ref.crm, colToRowMat(x, withDimnames=FALSE)))
{
stop("per-row values are not compatible")
}
}
old.validity <- S4Vectors:::disableValidity()
S4Vectors:::disableValidity(TRUE)
on.exit(S4Vectors:::disableValidity(old.validity))
out <- callNextMethod()
BiocGenerics:::replaceSlots(out, colVec=all.cv,
colToColMat=all.ccm, rowToColMat=all.rcm,
check=FALSE)
})
```
## Defining coercion methods
### Coercion from `SummarizedExperiment`
We define a method to coerce `SummarizedExperiment` objects into our new `ExampleClass` class.
```{r}
#' @exportMethods coerce
setAs("SummarizedExperiment", "ExampleClass", function(from) {
new("ExampleClass", from,
rowVec=integer(nrow(from)),
colVec=integer(ncol(from)),
rowToRowMat=matrix(0,nrow(from),0),
colToColMat=matrix(0,0,ncol(from)),
rowToColMat=matrix(0,ncol(from),0),
colToRowMat=matrix(0,0,nrow(from)))
})
```
... which works as expected:
```{r}
se <- SummarizedExperiment(matrix(rpois(100, lambda=1), ncol=5))
as(se, "CountSE")
```
This was not strictly necessary for our previous `CountSE` class as no new slots were added.
Of course, developers can still explicitly write a conversion method perform additional work to achieve a "sensible" conversion -
for example, one might take the absolute values of all entries of the first matrix to ensure that the `CountSE` is valid for all input `SummarizedExperiment` objects.
### Deriving from a `RangedSummarizedExperiment`
Note that, if we were deriving from a `RangedSummarizedExperiment` (e.g., for some `ExampleClassRanged`),
it would be necessary to define explicit conversions from both `RangedSummarizedExperiment` _and_ `SummarizedExperment` to `ExampleClassRanged`.
In theory, we should only have to define a conversion from `RangedSummarizedExperiment` to `ExampleClassRanged` -
then, any attempt to convert from a `SummarizedExperiment` to `ExampleClassRanged` would:
1. Use the existing `SummarizedExperiment` to `RangedSummarizedExperiment` converter defined in `r Biocpkg("SummarizedExperiment")`, and then
2. Use the new `RangedSummarizedExperiment` to `ExampleClassRanged` converter that we just defined.
Unfortunately, in cases involving conversion to non-direct subclasses, the S4 system automatically creates methods for any conversions that are not explicitly defined.
This means that the correct "chain" of methods listed above is not used when converting from a `SummarizedExperiment` to a `ExampleClassRanged` object.
The automatically generated method is used instead, which may not yield a valid object when the specifics of the conversion are ignored.
We avoid this scenario by explicitly defining converters for both `SummarizedExperiment` and `RangedSummarizedExperiment` to `ExampleClassRanged`.
# Unit testing procedures
## Overview
We test our new methods using the `expect_*` functions from the
[testthat][] package. Each function will test an expression and will
raise an error if the output is not as expected. This can be used to
construct unit tests for the `tests/` subdirectory of the package.
Unit testing ensures that the methods behave as expected, especially
after any refactoring that may be performed in the future.
For testing, we will construct an instance of `ExampleClass` that has
10 rows and 7 columns:
```{r}
RV <- 1:10
CV <- sample(50, 7)
RRM <- matrix(runif(30), nrow=10)
CCM <- matrix(rnorm(14), ncol=7)
RCM <- matrix(runif(21), nrow=7)
CRM <- matrix(rnorm(20), ncol=10)
thing <- ExampleClass(rowVec=RV, colVec=CV,
rowToRowMat=RRM, colToColMat=CCM,
rowToColMat=RCM, colToRowMat=CRM,
assays=list(counts=matrix(rnorm(70), nrow=10)),
colData=DataFrame(whee=LETTERS[1:7]),
rowData=DataFrame(yay=letters[1:10])
)
```
We will also add some row and column names, which will come in handy
later.
```{r}
rownames(thing) <- paste0("FEATURE_", seq_len(nrow(thing)))
colnames(thing) <- paste0("SAMPLE_", seq_len(ncol(thing)))
thing
```
## Constructor
We test that the `thing` object we constructed is valid:
```{r}
expect_true(validObject(thing))
```
Another useful set of unit tests involves checking that the default
constructors (internal and exported) yield valid objects:
```{r}
expect_true(validObject(.ExampleClass())) # internal
expect_true(validObject(ExampleClass())) # exported
```
We can also verify that the validity method fails on invalid objects:
```{r}
expect_error(ExampleClass(rowVec=1), "rowVec")
expect_error(ExampleClass(colVec=1), "colVec")
expect_error(ExampleClass(rowToRowMat=rbind(1)), "rowToRowMat")
expect_error(ExampleClass(colToColMat=rbind(1)), "colToColMat")
expect_error(ExampleClass(rowToColMat=rbind(1)), "rowToColMat")
expect_error(ExampleClass(colToRowMat=rbind(1)), "colToRowMat")
```
Finally, we check that the coercion method yields a valid object.
```{r}
se <- as(thing, "SummarizedExperiment")
conv <- as(se, "ExampleClass")
expect_true(validObject(conv))
```
## Getters
Testing the 1D getter methods:
```{r}
expect_identical(names(rowVec(thing)), rownames(thing))
expect_identical(rowVec(thing, withDimnames=FALSE), RV)
expect_identical(names(colVec(thing)), colnames(thing))
expect_identical(colVec(thing, withDimnames=FALSE), CV)
```
Testing the 2D getter methods:
```{r}
expect_identical(rowToRowMat(thing, withDimnames=FALSE), RRM)
expect_identical(rownames(rowToRowMat(thing)), rownames(thing))
expect_identical(colToColMat(thing, withDimnames=FALSE), CCM)
expect_identical(colnames(colToColMat(thing)), colnames(thing))
expect_identical(rowToColMat(thing, withDimnames=FALSE), RCM)
expect_identical(rownames(rowToColMat(thing)), colnames(thing))
expect_identical(colToRowMat(thing, withDimnames=FALSE), CRM)
expect_identical(colnames(colToRowMat(thing)), rownames(thing))
```
Testing the custom `rowData` method:
```{r}
expect_true("extra" %in% colnames(rowData(thing)))
```
## Setters
Testing the 1D setter methods:
```{r}
rowVec(thing) <- 0:9
expect_equivalent(rowVec(thing), 0:9)
colVec(thing) <- 7:1
expect_equivalent(colVec(thing), 7:1)
```
Testing the 2D setter methods:
```{r}
old <- rowToRowMat(thing)
rowToRowMat(thing) <- -old
expect_equivalent(rowToRowMat(thing), -old)
old <- colToColMat(thing)
colToColMat(thing) <- 2 * old
expect_equivalent(colToColMat(thing), 2 * old)
old <- rowToColMat(thing)
rowToColMat(thing) <- old + 1
expect_equivalent(rowToColMat(thing), old + 1)
old <- colToRowMat(thing)
colToRowMat(thing) <- old / 10
expect_equivalent(colToRowMat(thing), old / 10)
```
Testing our custom `rowData<-` method:
```{r}
expect_message(rowData(thing) <- 1, "hi")
```
We ensure that we can successfully trigger errors on the validity
method:
```{r}
expect_error(rowVec(thing) <- 0, "rowVec")
expect_error(colVec(thing) <- 0, "colVec")
expect_error(rowToRowMat(thing) <- rbind(0), "rowToRowMat")
expect_error(colToColMat(thing) <- rbind(0), "colToColMat")
expect_error(rowToColMat(thing) <- rbind(0), "rowToColMat")
expect_error(colToRowMat(thing) <- rbind(0), "colToRowMat")
```
## Other modifying functions
We test our new `normalize` method:
```{r}
modified <- normalize(thing)
expect_equal(rowVec(modified), -rowVec(thing))
expect_equal(colVec(modified), -colVec(thing))
```
## Subsetting methods
Subsetting by row:
```{r}
subbyrow <- thing[1:5,]
expect_identical(rowVec(subbyrow), rowVec(thing)[1:5])
expect_identical(rowToRowMat(subbyrow), rowToRowMat(thing)[1:5,])
expect_identical(colToRowMat(subbyrow), colToRowMat(thing)[,1:5])
# columns unaffected...
expect_identical(colVec(subbyrow), colVec(thing))
expect_identical(colToColMat(subbyrow), colToColMat(thing))
expect_identical(rowToColMat(subbyrow), rowToColMat(thing))
```
Subsetting by column:
```{r}
subbycol <- thing[,1:2]
expect_identical(colVec(subbycol), colVec(thing)[1:2])
expect_identical(colToColMat(subbycol), colToColMat(thing)[,1:2])
expect_identical(rowToColMat(subbycol), rowToColMat(thing)[1:2,])
# rows unaffected...
expect_identical(rowVec(subbycol), rowVec(thing))
expect_identical(rowToRowMat(subbycol), rowToRowMat(thing))
expect_identical(colToRowMat(subbycol), colToRowMat(thing))
```
Checking that subsetting to create an empty object is possible:
```{r}
norow <- thing[0,]
expect_true(validObject(norow))
expect_identical(nrow(norow), 0L)
nocol <- thing[,0]
expect_true(validObject(nocol))
expect_identical(ncol(nocol), 0L)
```
Subset assignment:
```{r}
modified <- thing
modified[1:5,1:2] <- thing[5:1,2:1]
rperm <- c(5:1, 6:nrow(thing))
expect_identical(rowVec(modified), rowVec(thing)[rperm])
expect_identical(rowToRowMat(modified), rowToRowMat(thing)[rperm,])
expect_identical(colToRowMat(modified), colToRowMat(thing)[,rperm])
cperm <- c(2:1, 3:ncol(thing))
expect_identical(colVec(modified), colVec(thing)[cperm])
expect_identical(colToColMat(modified), colToColMat(thing)[,cperm])
expect_identical(rowToColMat(modified), rowToColMat(thing)[cperm,])
```
Checking that we obtain the same object after trivial assignment
operations:
```{r}
modified <- thing
modified[0,] <- thing[0,]
expect_equal(modified, thing)
modified[1,] <- thing[1,]
expect_equal(modified, thing)
modified[,0] <- thing[,0]
expect_equal(modified, thing)
modified[,1] <- thing[,1]
expect_equal(modified, thing)
```
We double-check that we can get an error upon invalid assignment:
```{r}
expect_error(modified[1,1] <- thing[0,0], "replacement has length zero")
```
## Combining methods
Combining by row:
```{r}
combined <- rbind(thing, thing)
rtwice <- rep(seq_len(nrow(thing)), 2)
expect_identical(rowVec(combined), rowVec(thing)[rtwice])
expect_identical(rowToRowMat(combined), rowToRowMat(thing)[rtwice,])
expect_identical(colToRowMat(combined), colToRowMat(thing)[,rtwice])
# Columns are unaffected:
expect_identical(colVec(combined), colVec(thing))
expect_identical(colToColMat(combined), colToColMat(thing))
expect_identical(rowToColMat(combined), rowToColMat(thing))
```
And combining by column. We use `test_equivalent` here for
simplicity, as column names are altered to preserve uniqueness.
```{r}
combined <- cbind(thing, thing)
ctwice <- rep(seq_len(ncol(thing)), 2)
expect_equivalent(colVec(combined), colVec(thing)[ctwice])
expect_equivalent(colToColMat(combined), colToColMat(thing)[,ctwice])
expect_equivalent(rowToColMat(combined), rowToColMat(thing)[ctwice,])
# Rows are unaffected:
expect_equivalent(rowVec(combined), rowVec(thing))
expect_equivalent(rowToRowMat(combined), rowToRowMat(thing))
expect_equivalent(colToRowMat(combined), colToRowMat(thing))
```
Checking that we get the same object if we combine a single object or
an empty object:
```{r}
expect_equal(thing, rbind(thing))
expect_equal(thing, rbind(thing, thing[0,]))
expect_equal(thing, cbind(thing))
expect_equal(thing, cbind(thing, thing[,0]))
```
And checking that the compatibility errors are properly thrown:
```{r}
expect_error(rbind(thing, thing[,ncol(thing):1]), "not compatible")
expect_error(cbind(thing, thing[nrow(thing):1,]), "not compatible")
```
# Documentation
We suggest creating at least two separate documentation (i.e. `*.Rd`)
files. The first file would document the class and the constructor:
```
\name{ExampleClass class}
\alias{ExampleClass-class}
\alias{ExampleClass}
\title{The ExampleClass class}
\description{An overview of the ExampleClass class and constructor.}
\usage{
ExampleClass(rowVec=integer(0), colVec=integer(0),
# etc., etc., I won't write it all out here.
)
}
\arguments{
\item{rowVec}{An integer vector mapping to the rows, representing
something important.}
\item{colVec}{An integer vector mapping to the columns, representing
something else that's important.}
% And so on...
}
\details{
% Some context on why this class and its slots are necessary.
The ExampleClass provides an example of how to derive from the
SummarizedExperiment class. Its slots have no scientific meaning and
are purely for demonstration purposes.
}
```
The second file would document all of the individual methods:
```
\name{ExampleClass methods}
% New generics:
\alias{rowVec}
\alias{rowVec,ExampleClass-method}
\alias{rowVec<-}
\alias{rowVec<-,ExampleClass-method}
%% And so on...
% Already have a generic:
\alias{[,ExampleClass-method}
\alias{[,ExampleClass,ANY-method}
\alias{[,ExampleClass,ANY,ANY-method}
\alias{rbind,ExampleClass-method}
%% And so on...
\title{ExampleClass methods}
\description{Methods for the ExampleClass class.}
\usage{
\S4method{rowVec}{ExampleClass}(x, withDimnames=FALSE)
\S4method{rowVec}{ExampleClass}(x) <- value
\S4method{[}{ExampleClass}(x, i, j, drop=TRUE)
\S4method{rbind}{ExampleClass}(..., , i, j, drop=TRUE)
%% And so on...
}
\arguments{
\item{x}{An ExampleClass object.}
\item{withDimnames}{A logical scalar indicating whether dimension names
from \code{x} should be returned.}
\item{value}{
For \code{rowVec}, an integer vector of length equal to the number of
rows.
For \code{colVec}, an integer vector of length equal to the number of
columns.
}
%% And so on...
}
\section{Accessors}{
% Add some details about accessor behaviour here.
}
\section{Subsetting}{
% Add some details about subsetting behaviour here.
}
\section{Combining}{
% Add some details about combining behaviour here.
}
```
# Session information
```{r}
sessionInfo()
```
[BiocGenerics]: https://bioconductor.org/packages/BiocGenerics
[S4Vectors]: https://bioconductor.org/packages/S4Vectors
[SummarizedExperiment]: https://bioconductor.org/packages/SummarizedExperiment
[testthat]: https://cran.r-project.org/package=testthat
|