Debian Codegraph @

R/symbolic_units.R

raw
1
2 .symbolic_units <- function(numerator, denominator = vector("character")) {
3 structure(list(numerator = numerator,
4 denominator = denominator),
5 class = "symbolic_units")
6 }
7
8 .multiply_symbolic_units <- function(value, e1, e2) {
9 numerator <- sort(c(e1$numerator, e2$numerator))
10 denominator <- sort(c(e1$denominator, e2$denominator))
11 .simplify_units(value, .symbolic_units(numerator, denominator))
12 }
13
14 .invert_symbolic_units <- function(e) {
15 .symbolic_units(e$denominator, e$numerator)
16 }
17
18 .divide_symbolic_units <- function(value, e1, e2) {
19 .multiply_symbolic_units(value, e1, .invert_symbolic_units(e2))
20 }
21
22 .same_units <- function(e1, e2) {
23 identical(e1$numerator, e2$numerator) && identical(e1$denominator, e2$denominator)
24 }
25
26 # Inside the group generic functions we do have .Generic even if the diagnostics
27 # think we do not.
28 # !diagnostics suppress=.Generic
29 #' @export
30 Ops.symbolic_units <- function(e1, e2) {
31 if (nargs() == 1)
32 stop(paste("unary", .Generic, "not defined for \"units\" objects"))
33
34 eq <- switch(.Generic, "==" = , "!=" = TRUE, FALSE)
35 if (eq) {
36 if (.Generic == "==")
37 .same_units(e1, e2)
38 else
39 !.same_units(e1, e2)
40 } else
41 stop(paste("operation", .Generic, "not allowed for symbolic operators")) # nocov
42 }
43
44 #' The "unit" type for vectors that are actually dimension-less.
45 #' @export
46 unitless <- .symbolic_units(vector("character"), vector("character"))
47
48 .pretty_print_sequence <- function(terms, op, neg_power = FALSE, sep = "") {
49 pwr_op <- if (op == " ") "" else "^"
50 sym <- unique(terms)
51 pwr <- tabulate(factor(terms, sym))
52 if (neg_power) pwr <- pwr * -1
53
54 for (i in seq_along(sym)) if (pwr[i] != 1)
55 sym[i] <- paste(sym[i], pwr[i], sep = pwr_op)
56
57 s <- matrix(c(sym, rep(paste0(op, sep), length(sym)-1), ""), nrow=length(sym))
58 if (!units_options("strict_tokenizer"))
59 s[sym >= "0" & sym <= "9", 2] <- ""
60 paste0(t(s), collapse="")
61 }
62
63 #' @export
64 as.character.symbolic_units <- function(x, ...,
65 neg_power = units_options("negative_power"),
66 escape_units = FALSE, prod_sep = "*", plot_sep = "") {
67 sep <- plot_sep
68
69 numerator <- x$numerator[x$numerator != "1"]
70 denominator <- x$denominator[x$denominator != "1"]
71 if (escape_units) {
72 numerator <- unlist(Map(function(name) paste0("`", name, "`", sep = ""), numerator))
73 denominator <- unlist(Map(function(name) paste0("`", name, "`", sep = ""), denominator))
74 }
75
76 if (x == unitless) { # xxx
77 u <- if (escape_units)
78 unlist(Map(function(name) paste0("`", name, "`", sep = ""),
79 units_options("unitless_symbol")))
80 else
81 units_options("unitless_symbol")
82 return(u)
83 }
84
85 num_str <- denom_str <- character(0)
86
87 num_str <- if (length(numerator) > 0)
88 .pretty_print_sequence(numerator, prod_sep, FALSE, plot_sep)
89 else if (! neg_power) "1" # only denominator: 1/(cm^2*h)
90
91 if (length(denominator) > 0) {
92 sep <- if (neg_power)
93 paste0(prod_sep, plot_sep) else "/"
94 denom_str <- .pretty_print_sequence(denominator, prod_sep, neg_power, plot_sep)
95 if (!neg_power && length(unique(denominator)) > 1)
96 denom_str <- paste0("(", denom_str, ")")
97 }
98
99 if (length(num_str) == 0)
100 denom_str
101 else if (length(denom_str) == 0)
102 num_str
103 else
104 paste(num_str, denom_str, sep = sep)
105 }
106
107 .simplify_units <- function(value, sym_units) {
108 # from R >= 3.5
109 isFALSE <- function(x) is.logical(x) && length(x) == 1L && !is.na(x) && !x
110
111 if (isFALSE(.units.simplify())) {
112 value = unclass(value)
113 units(value) = sym_units
114 return(value)
115 }
116
117 # This is just a brute force implementation that takes each element in the
118 # numerator and tries to find a value in the denominator that can be converted
119 # to the same unit. It modifies "value" to rescale the nominator to the denominator
120 # before removing matching units.
121
122 drop_ones = function(u) u[ u != "1" ]
123 class(value) <- "units"
124
125 new_numerator <- drop_ones(sym_units$numerator)
126 new_denominator <- drop_ones(sym_units$denominator)
127 delete_num <- c()
128 for (i in seq_along(new_numerator)) {
129 str1 <- new_numerator[i]
130
131 for (j in seq_along(new_denominator)) {
132 str2 <- new_denominator[j]
133
134 if (ud_are_same(str1, str2)) {
135 attr(value, "units") <- units(as_units(str1))
136 units(value) <- str2
137 delete_num <- c(delete_num, i)
138 new_denominator <- new_denominator[-j]
139 break
140 }
141
142 }
143 }
144 if (length(delete_num) > 0)
145 new_numerator <- new_numerator[-delete_num]
146
147 as_units(drop_units(value), .symbolic_units(new_numerator, new_denominator))
148 }
149
150 #' Convert units to their base units
151 #'
152 #' Convert the units of a \code{units} object to their base units, as defined by
153 #' the udunits database (SI units).
154 #'
155 #' @param x object of class \code{units}.
156 #' @param simplify logical; if TRUE (default), the resulting units are simplified.
157 #' @param keep_fraction logical; if TRUE (default), the result is kept as a fraction.
158 #'
159 #' @return object of class \code{units} with units converted to base units.
160 #' @export
161 #'
162 #' @examples
163 #' x <- set_units(32, mJ/g)
164 #' convert_to_base(x)
165 #' convert_to_base(x, keep_fraction=FALSE)
166 #' convert_to_base(x, simplify=FALSE)
167 #' convert_to_base(x, simplify=FALSE, keep_fraction=FALSE)
168 convert_to_base <- function(x, simplify = TRUE, keep_fraction = TRUE) {
169 stopifnot(inherits(x, "units"))
170
171 u_strBase <- function(u_str, simplify) {
172 u_new <- ud_parse(u_str, names=FALSE, definition=TRUE, ascii=TRUE)
173 u_new <- strsplit(x = u_new, split = " @ ")[[1]][1]
174 u_new <- strsplit(x = u_new, split = " ")[[1]]
175 u_new <- u_new[length(u_new)]
176
177 if (simplify)
178 u_new <- ud_parse(u_new, names=FALSE, definition=FALSE, ascii=TRUE)
179 gsub(".", " ", u_new, fixed = TRUE)
180 }
181
182 u <- vapply(units(x), paste0, character(1L), collapse = "*", recycle0=TRUE)
183 u[u == ""] <- "1"
184
185 u["numerator"] <- sprintf("(%s)", u["numerator"])
186 u["denominator"] <- sprintf("(%s)", u["denominator"])
187
188 if (!keep_fraction) u <- paste(u, collapse = "/")
189
190 u_base <- vapply(u, u_strBase, character(1L), simplify = simplify)
191
192 if (keep_fraction) {
193 is_unitless <- u_base == "1"
194
195 u_base["numerator"] <- sprintf("(%s)", u_base["numerator"])
196 u_base["denominator"] <- sprintf("(%s)-1", u_base["denominator"])
197
198 u_base <- paste(u_base[!is_unitless], collapse = " ")
199 }
200
201 set_units(x, u_base, mode = "standard")
202 }