Debian Codegraph @

R/simulate_cvd.R

raw
1 #' Simulate Color Vision Deficiency
2 #'
3 #' Transformation of R colors by simulating color vision deficiencies,
4 #' based on a CVD transform matrix.
5 #'
6 #' Using the physiologically-based model for simulating color vision deficiency (CVD)
7 #' of Machado et al. (2009), different kinds of limitations can be
8 #' emulated: deuteranope (green cone cells defective), protanope (red cone cells defective),
9 #' and tritanope (blue cone cells defective).
10 #' The workhorse function to do so is \code{simulate_cvd} which can take any vector
11 #' of valid R colors and transform them according to a certain CVD transformation
12 #' matrix (see \code{\link{cvd}}) and transformation equation.
13 #'
14 #' The functions \code{deutan}, \code{protan}, and \code{tritan} are the high-level functions for
15 #' simulating the corresponding kind of colorblindness with a given severity.
16 #' Internally, they all call \code{simulate_cvd} along with a (possibly interpolated)
17 #' version of the matrices from \code{\link{cvd}}. Matrix interpolation can be carried out with
18 #' the function \code{interpolate_cvd_transform} (see examples).
19 #'
20 #' If input \code{col} is a matrix with three rows named \code{R}, \code{G}, and
21 #' \code{B} (top down) they are interpreted as Red-Green-Blue values within the
22 #' range \code{[0-255]}. Then the CVD transformation is applied directly to these
23 #' coordinates avoiding any further conversions.
24 #'
25 #' Finally, if \code{col} is a formal \code{\link[colorspace]{color-class}} object, then its
26 #' coordinates are transformed to (s)RGB coordinates, as described above, and returned as a formal
27 #' object of the same class after the color vision deficiency simulation.
28 #'
29 #' Up to version 2.0-3 of the package, the CVD transformations had been applied
30 #' directly to the gamma-corrected sRGB coordinates (corresponding to the hex coordinates
31 #' of the colors), following the illustrations of Machado et al. (2009). However,
32 #' the paper implicitly relies on a linear RGB space (see page 1294, column 1) where their
33 #' linear matrix transformations for simulating color vision deficiencies are applied.
34 #' Therefore, starting from version 2.1-0 of the package, a new argument \code{linear = TRUE}
35 #' has been added that first maps the provided colors to linearized RGB coordinates, applies
36 #' the color vision deficiency transformation, and then maps back to gamma-corrected sRGB
37 #' coordinates. Optionally, \code{linear = FALSE} can be used to restore the behavior
38 #' from previous versions. For most colors the difference between the two strategies is
39 #' negligible but for some highly-saturated colors it becomes more noticable, e.g., for
40 #' red, purple, or orange.
41 #'
42 #' @param col vector of R colors. Can be any of the three kinds of R colors,
43 #' i.e., either a color name (an element of \code{\link[grDevices]{colors}}), a hexadecimal (hex)
44 #' string of the form \code{"#rrggbb"} or \code{"#rrggbbaa"} (see \code{\link[grDevices]{rgb}}), or
45 #' an integer \code{i} meaning \code{palette()[i]}. Additionally, \code{col} can be
46 #' a formal \code{\link[colorspace]{color-class}} object or a matrix with three named
47 #' rows (or columns) containing R/G/B (0-255) values.
48 #' @param severity numeric. Severity of the color vision defect, a number between 0 and 1.
49 #' @param cvd_transform numeric 3x3 matrix, specifying the color vision deficiency transform matrix.
50 #' @param linear logical. Should the color vision deficiency transformation be applied to the
51 #' linearized RGB coordinates (default)? If \code{FALSE}, the transformation is applied to the
52 #' gamma-corrected sRGB coordinates (which was the default up to version 2.0-3 of the package).
53 #' @param cvd list of cvd transformation matrices. See \code{\link{cvd}} for available options.
54 #'
55 #' @return A color object as specified in the input \code{col} (hexadecimal string, RGB matrix,
56 #' or formal color class) with simulated color vision deficiency.
57 #'
58 #' @references Machado GM, Oliveira MM, Fernandes LAF (2009).
59 #' \dQuote{A Physiologically-Based Model for Simulation of Color Vision Deficiency.}
60 #' \emph{IEEE Transactions on Visualization and Computer Graphics}. \bold{15}(6), 1291--1298.
61 #' \doi{10.1109/TVCG.2009.113}
62 #' Online version with supplements at
63 #' \url{http://www.inf.ufrgs.br/~oliveira/pubs_files/CVD_Simulation/CVD_Simulation.html}.
64 #'
65 #' Zeileis A, Fisher JC, Hornik K, Ihaka R, McWhite CD, Murrell P, Stauffer R, Wilke CO (2020).
66 #' \dQuote{colorspace: A Toolbox for Manipulating and Assessing Colors and Palettes.}
67 #' \emph{Journal of Statistical Software}, \bold{96}(1), 1--49.
68 #' \doi{10.18637/jss.v096.i01}
69 #' @keywords colors cvd colorblind
70 #' @seealso \code{\link{cvd}}
71 #' @export
72 #' @examples
73 #' # simulate color-vision deficiency by calling `simulate_cvd` with specified matrix
74 #' simulate_cvd(c("#005000", "blue", "#00BB00"), tritanomaly_cvd["6"][[1]])
75 #'
76 #' # simulate color-vision deficiency by calling the shortcut high-level function
77 #' tritan(c("#005000", "blue", "#00BB00"), severity = 0.6)
78 #'
79 #' # simulate color-vision deficiency by calling `simulate_cvd` with interpolated cvd matrix
80 #' simulate_cvd(c("#005000", "blue", "#00BB00"),
81 #' interpolate_cvd_transform(tritanomaly_cvd, severity = 0.6))
82 #'
83 #' # apply CVD directly on wide RGB matrix (with R/G/B channels in rows)
84 #' RGB <- diag(3) * 255
85 #' rownames(RGB) <- c("R", "G", "B")
86 #' deutan(RGB)
87 #'
88 #' @importFrom grDevices col2rgb
89 simulate_cvd <- function(col, cvd_transform, linear = TRUE) {
90 ## determine input type
91 input_type <- if (inherits(col, "color")) {
92 ## S4 colorspace class
93 "colorspace"
94 } else if (is.matrix(col)) {
95 ## named RGB matrix (0-255)
96 "matrix"
97 } else if (is.character(col) && (all(substr(col, 1L, 1L) == "#") & all(nchar(col) %in% c(7L, 9L)))) {
98 ## all hex
99 "hex"
100 } else {
101 ## assume built-in colors
102 "other"
103 }
104
105 ## prismatic colors class is character + class attribute
106 prismatic <- input_type == "hex" && inherits(col, "colors")
107
108 ## indexes of missing values (if hex)
109 NAidx <- NULL
110
111 ## convert input to wide RGB matrix (0-255)
112 if (input_type == "colorspace") {
113
114 color_class <- class(col)
115 col <- t(coords(as(col, if(linear) "RGB" else "sRGB"))) * 255
116
117 } else if (input_type == "matrix") {
118
119 if(NROW(col) != 3L && NCOL(col) == 3L && all(toupper(colnames(col)) == c("R", "G", "B"))) {
120 col <- t(col)
121 transpose <- TRUE
122 } else {
123 transpose <- FALSE
124 }
125 stopifnot(all(toupper(rownames(col)) == c("R", "G", "B")))
126
127 } else if (input_type == "hex") {
128
129 # Save transparency value for later
130 alpha <- substr(col, 8L, 9L)
131 # keep indices of NA colors
132 NAidx <- which(is.na(col))
133 col[] <- substr(col[], 1L, 7L)
134 col <- col2rgb(col)
135
136 } else {
137
138 # keep indices of NA colors
139 NAidx <- which(is.na(col))
140 col <- col2rgb(col, alpha = TRUE)
141 ## extract alpha values (if non-FF)
142 alpha <- format(as.hexmode(col[4L, ]), width = 2L, upper.case = TRUE)
143 alpha[alpha == "FF"] <- ""
144 ## retain only RGB
145 col <- col[1L:3L, ]
146
147 }
148
149 if (linear && input_type %in% c("hex", "other")) {
150 sRGB_to_linearRGB <- function(x) {
151 x <- x/255
152 y <- ((x + 0.055)/1.055)^2.4
153 small <- x <= 0.03928
154 y[small] <- x[small]/12.92
155 return(y * 255)
156 }
157 col <- sRGB_to_linearRGB(col)
158 }
159
160 ## transform color
161 RGB <- cvd_transform %*% col
162 rownames(RGB) <- c("R", "G", "B")
163
164 ## bound RGB values
165 RGB[RGB < 0] <- 0
166 RGB[RGB > 255] <- 255
167
168 if (linear && input_type %in% c("hex", "other")) {
169 linearRGB_to_sRGB <- function(y) {
170 y <- y/255
171 x <- 1.055 * y^(1/2.4) - 0.055
172 small <- y <= 0.03928/12.92
173 x[small] <- 12.92 * y[small]
174 return(x * 255)
175 }
176 RGB <- linearRGB_to_sRGB(RGB)
177 }
178
179 ## convert back to input type
180 if (input_type == "colorspace") {
181 col <- t(RGB/255)
182 col <- if(linear) RGB(col) else sRGB(col)
183 col <- as(col, color_class)
184 } else if (input_type == "matrix") {
185 col <- if(transpose) t(RGB) else RGB
186 } else {
187 RGB <- round(RGB)
188 col <- rgb(t(RGB[1L:3L, , drop = FALSE]), maxColorValue = 255, names = colnames(RGB))
189 col[] <- paste(col[], alpha, sep = "")
190 if(length(NAidx) > 0L) col[NAidx] <- NA
191 if(prismatic) attr(col, "class") <- "colors"
192 }
193
194 return(col)
195 }
196
197 #' @rdname simulate_cvd
198 #' @export
199 deutan <- function(col, severity = 1, linear = TRUE) {
200 simulate_cvd(col, cvd_transform = interpolate_cvd_transform(deutanomaly_cvd, severity), linear = linear)
201 }
202
203 #' @rdname simulate_cvd
204 #' @export
205 protan <- function(col, severity = 1, linear = TRUE) {
206 simulate_cvd(col, cvd_transform = interpolate_cvd_transform(protanomaly_cvd, severity), linear = linear)
207 }
208
209 #' @rdname simulate_cvd
210 #' @export
211 tritan <- function(col, severity = 1, linear = TRUE) {
212 simulate_cvd(col, cvd_transform = interpolate_cvd_transform(tritanomaly_cvd, severity), linear = linear)
213 }
214
215 #' @rdname simulate_cvd
216 #' @export
217 interpolate_cvd_transform <- function(cvd, severity = 1) {
218 if (severity <= 0) {
219 cvd[[1]]
220 } else if (severity >= 1) {
221 cvd[[11]]
222 } else {
223 s <- 10*severity
224 i1 <- floor(s)
225 i2 <- ceiling(s)
226 if (i1 == i2) {
227 cvd[[i1+1]]
228 }
229 else {
230 (i2-s)*cvd[[i1+1]] + (s-i1)*cvd[[i2+1]]
231 }
232 }
233 }