/
knit_printEquation.R
409 lines (385 loc) · 12.4 KB
/
knit_printEquation.R
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
#' @importFrom knitr knit_print
#' @export
knitr::knit_print
#' Extract the equations from an nlmixr2/rxode2 model to produce a 'LaTeX'
#' equation.
#'
#' @param x The model to extract equations from
#' @param ... Ignored
#' @param output The type of output to request (currently, just "equations")
#' @export
knit_print.nlmixr2FitCore <- function(x, ..., output = "equations") {
output <- match.arg(output)
if ("equations" %in% output) {
ret <-
paste0(
"\\begin{align*}\n",
paste(
extractEqHelper(x = x, ...),
collapse = " \\\\\n"
),
"\n\\end{align*}\n"
)
}
knitr::asis_output(ret)
}
#' @rdname knit_print.nlmixr2FitCore
#' @export
knit_print.rxUi <- function(x, ...) {
knit_print.nlmixr2FitCore(x, ...)
}
extractEqHelper <- function(x, ..., inModel) {
UseMethod("extractEqHelper")
}
# Ignore one (or more) items in a sequence. Typically used for {} and ()
extractEqHelperSeqDrop <- function(x, ..., inModel, dropIdx = 1) {
ret <- character()
retNames <- names(x)
for (idx in setdiff(seq_along(x), dropIdx)) {
ret <- c(ret, extractEqHelper(x[[idx]], name=retNames[[idx]], ..., inModel = inModel))
}
ret
}
# Generate something with a left and right hand side
extractEqHelperLhsRhs <- function(x, ..., inModel, prefix = "", middle, suffix = "", lhsForce = NULL, rhsForce = NULL) {
stopifnot(length(prefix) == 1)
stopifnot(length(middle) == 1)
stopifnot(length(suffix) == 1)
if (length(x) != 3) {
stop("extractEqHelperLhsRhs requires length of 3, please report a bug") # nocov
}
stopifnot(length(x) == 3)
if (!is.null(lhsForce)) {
lhs <- lhsForce
} else {
lhs <- extractEqHelper(x[[2]], ..., inModel = inModel)
}
if (!is.null(rhsForce)) {
rhs <- rhsForce
} else {
rhs <- extractEqHelper(x[[3]], ..., inModel = inModel)
}
stopifnot(length(lhs) == 1)
stopifnot(length(rhs) == 1)
paste0(prefix, lhs, middle, rhs, suffix)
}
extractEqHelper.nlmixr2FitCore <- function(x, ..., inModel) {
extractEqHelper(as.function(x), ..., inModel=FALSE)
}
extractEqHelper.rxUi <- function(x, ..., inModel, name) {
extractEqHelper(as.function(x), ..., inModel=FALSE)
}
extractEqHelper.function <- function(x, ..., inModel, name) {
extractEqHelper(methods::functionBody(x), ..., inModel=FALSE)
}
"extractEqHelper.{" <- function(x, ..., inModel, name) {
extractEqHelperSeqDrop(x, ..., inModel = inModel)
}
"extractEqHelper.(" <- function(x, ..., inModel, dropParen = FALSE, name) {
stopifnot(length(x) == 2)
if (dropParen) {
ret <- extractEqHelper(x[[2]], ..., inModel = inModel)
} else {
# This inherently respects inModel = FALSE because sprintf() with
# character(0) input returns character(0)
ret <-
sprintf(
"\\left(%s\\right)",
extractEqHelper(x[[2]], ..., inModel = inModel)
)
}
ret
}
matchesTemplate <- function(x, template) {
ret <- class(x) == class(template)
if (ret) {
if (length(x) == length(template)) {
if (length(x) > 1) {
for (idx in seq_along(x)) {
ret <- ret && matchesTemplate(x[[idx]], template[[idx]])
}
} else if (is.name(x)) {
if (as.character(template) != "name") {
# Check for a value if the name is not "name"
ret <- x == template
}
} else {
# Do nothing for numeric, character, etc.
}
} else {
ret <- FALSE
}
}
ret
}
isOdeAssign <- function(x) {
matchesTemplate(x[[2]], str2lang("d/dt(name)"))
}
# @param alignment gives the text to provide before the equal sign to align on
# the sign
# This function is named `extractEqHelperAssign` instead of `extractEqHelper.<-`
# to fix an R CMD check issue. It is used via the `extractEqHelper.default`
# function.
extractEqHelperAssign <- function(x, ..., inModel, alignment = "&", name) {
if (inModel) {
lhsForce <- NULL
rhsForce <- NULL
if (isOdeAssign(x)) {
cmtName <- as.character(x[[2]][[3]][[2]])
if (nchar(cmtName) > 1) {
# \: forces a medium space in LaTeX equations, do it for state names
# with more than one character.
spacesep <- " \\: "
} else {
spacesep <- ""
}
lhsForce <- sprintf("\\frac{d%s%s}{dt}", spacesep, cmtName)
rhsForce <- extractEqHelper(x[[3]], ..., inModel = inModel)
}
middleForce <- sprintf(" %s = ", alignment)
ret <-
extractEqHelperLhsRhs(
x, ..., inModel = inModel,
middle = middleForce,
lhsForce = lhsForce,
rhsForce = rhsForce
)
} else {
ret <- character()
}
ret
}
latexOpMap <-
list(
"<"="<",
"<="="{\\leq}",
"=="="{\\equiv}",
">="="{\\geq}",
">"=">",
"&"="{\\land}",
"&&"="{\\land}",
"|"="{\\lor}",
"||"="{\\lor}",
"!="="{\\ne}",
"!"="{\\lnot}"
)
extractEqHelper.call <- function(x, ..., inModel, name) {
if (inModel) {
if (is.name(x[[1]])) {
x1c <- as.character(x[[1]])
if (x1c %in% c("exp", "log")) {
stopifnot(length(x) == 2)
ret <-
sprintf(
"\\%s\\left(%s\\right)",
x1c,
extractEqHelper(x[[2]], ..., inModel = inModel)
)
stopifnot(length(ret) == 1)
} else if (x1c %in% c("<", "<=", "==", ">=", ">", "&", "&&", "|", "||", "!=")) {
# binary logical operators
ret <- extractEqHelperLhsRhs(x, ..., inModel = inModel, middle = latexOpMap[[x1c]])
} else if (x1c %in% "!") {
# unary logical operator
stopifnot(length(x) == 2)
ret <-
sprintf(
"%s %s",
latexOpMap[[x1c]],
extractEqHelper(x[[2]], ..., inModel = inModel)
)
} else if (x1c %in% c("+", "-")) {
if (length(x) == 2) {
# Handle unary plus and minus
ret <- sprintf("%s%s", x1c, extractEqHelper(x[[2]], ..., inModel = inModel))
} else if (length(x) == 3) {
# Handle binary plus and minus
ret <- extractEqHelperLhsRhs(x, ..., inModel = inModel, middle = x1c)
} else {
cli::cli_abort("Cannot handle addition or subtraction with length that is not 2 or 3") # nocov
}
} else if (x1c == "*") {
ret <- extractEqHelperLhsRhs(x, ..., inModel = inModel, middle = " {\\times} ")
} else if (x1c == "/") {
ret <-
extractEqHelperLhsRhs(
x, ..., inModel = inModel,
prefix = "\\frac{",
middle = "}{",
suffix = "}"
)
} else if (x1c %in% c("**", "^")) {
ret <-
extractEqHelperLhsRhs(
x, ..., inModel = inModel,
prefix = "{",
middle = "}^{",
suffix = "}"
)
} else if (x1c == "~") {
ret <-
extractEqHelperLhsRhs(
x, ...,
inModel = inModel,
middle = " & \\sim "
)
} else {
# A generic call that is printed using parentheses
ret <-
sprintf(
"%s(%s)",
x1c,
paste(
extractEqHelperSeqDrop(x, ..., inModel = inModel),
collapse = ", "
)
)
}
} else {
stop("a call that does not start with a name is in the model, please report a bug") # nocov
}
} else if (length(x) == 1) {
stop("a one-length call is not inModel, please report a bug") # nocov
} else {
if (is.name(x[[1]])) {
if (x[[1]] == as.name("model")) {
ret <- extractEqHelperSeqDrop(x, ..., inModel = TRUE, dropBrace = TRUE)
} else {
# When not in the model, calls don't matter unless they are `model()`
ret <- character()
}
} else {
stop("a call that does not start with a name does not have inModel set, please report a bug") # nocov
}
}
ret
}
extractEqHelper.name <- function(x, ..., inModel, underscoreToSubscript = FALSE, name) {
if (inModel) {
ret <- as.character(x)
if (underscoreToSubscript && grepl(x = ret, pattern = "_", fixed = TRUE)) {
firstSecondPattern <- "^(.*?)_(.*)$"
# The first underscore becomes a subscript
firstPart <- gsub(x = ret, pattern = firstSecondPattern, replacement = "\\1")
# Remaining underscores become commas
secondPartPrep <- gsub(x = ret, pattern = firstSecondPattern, replacement = "\\2")
secondPart <- gsub(x = secondPartPrep, pattern = "_", replacement = ", ", fixed = TRUE)
ret <- sprintf("%s_{%s}", firstPart, secondPart)
} else {
# Otherwise underscores are protected from LaTeX interpretation
ret <- gsub(x = ret, pattern = "_", replacement = "\\_", fixed = TRUE)
}
ret <- paste0("{", ret, "}")
} else {
ret <- character()
}
ret
}
extractEqHelper.numeric <- function(x, ..., inModel, name = NULL) {
if (inModel) {
ret <- format(x)
# Convert SI to exponents
patternSi <- "^([0-9]+(?:\\.[0-9]+)?)e([+-][0-9]+)$"
if (grepl(x = ret, pattern = patternSi)) {
base <- gsub(x = ret, pattern = patternSi, replacement = "\\1")
# as.numeric will remove the leading zeros
exponent <- as.numeric(gsub(x = ret, pattern = patternSi, replacement = "\\2"))
ret <- sprintf("%s \\times 10^{%d}", base, exponent)
}
if (!is.null(name) && !(name == "")) {
# Hopefully this is right; it occurs in named arguments to calls
ret <- sprintf("%s=%s", name, ret)
}
# Add braces to protect from combination with the prior command
ret <- paste0("{", ret, "}")
} else {
ret <- character()
}
ret
}
# copied from knitr:::escape_latex
escapeLatex <- function (x, newlines = FALSE, spaces = FALSE) {
x = gsub("\\\\", "\\\\textbackslash", x)
x = gsub("([#$%&_{}])", "\\\\\\1", x)
x = gsub("\\\\textbackslash", "\\\\textbackslash{}", x)
x = gsub("~", "\\\\textasciitilde{}", x)
x = gsub("\\^", "\\\\textasciicircum{}", x)
if (newlines)
x = gsub("(?<!\n)\n(?!\n)", "\\\\\\\\", x, perl = TRUE)
if (spaces)
x = gsub("(?<= ) ", "\\\\ ", x, perl = TRUE)
x
}
extractEqHelper.character <- function(x, ..., inModel, name = NULL) {
if (inModel) {
ret <- sprintf('\\text{"%s"}', escapeLatex(x))
if (!is.null(name) && !(name == "")) {
# Hopefully this is right; it occurs in named arguments to calls
ret <- sprintf("%s=%s", name, ret)
}
} else {
ret <- character()
}
ret
}
braceWrap <- function(x, ..., inModel, indent) {
if (inherits(x, "{")) {
innerPart <- extractEqHelperSeqDrop(x, ..., inModel = inModel, indent = indent + 1L)
ret <-
c(
"\\{",
paste(" &", innerPart),
"\\}"
)
} else {
ret <- extractEqHelper(x, ..., inModel = inModel)
}
ret
}
#' Generate LaTeX for if blocks
#'
#' @inheritParams extractEqHelper
#' @param firstIf tracks if this is the first if at the current indent level
#' @param indent tracks the current indention level
#' @noRd
extractEqHelper.if <- function(x, ..., inModel, alignment, indent = 0L, firstIf = 0L, name) {
# This is used at the same level as assignment
stopifnot(length(x) %in% c(3, 4))
# Generate the text for what is in the braces "{}" for this part of the if
# block
conditionalPart <- extractEqHelper(x[[2]], ..., inModel = inModel, alignment = "", indent = indent + 1L, firstIf = firstIf + 1L)
bracedPart <- braceWrap(x[[3]], ..., inModel = inModel, alignment = "", indent = indent + 1L, firstIf = firstIf + 1L)
if (length(x) == 4) {
appendPart <- extractEqHelper(x[[4]], ..., inModel = inModel, alignment = "", indent = indent, firstIf = firstIf + 1L)
appendPart[1] <-
sprintf(
" \\quad & \\mathrm{else} \\: %s",
gsub(x = appendPart[1], pattern = "&", replacement = "", fixed = TRUE)
)
} else {
appendPart <- NULL
}
firstPart <- sprintf("\\mathrm{if} & \\left(%s\\right) %s", conditionalPart, bracedPart[1])
lastPart <-
if (length(bracedPart) > 1) {
bracedPart[length(bracedPart)] <- paste(bracedPart[length(bracedPart)], appendPart[1])
c(bracedPart[-1], appendPart[-1])
} else {
appendPart
}
ret <- c(firstPart, lastPart)
ret
}
extractEqHelper.default <- function(x, ..., inModel) {
if (inherits(x, "<-") | inherits(x, "=")) {
# The assignment classes go via extractEqHelper.default to fix an R CMD
# check issue:
# Warning: 'extractEqHelper.<-'
# The argument of a replacement function which corresponds to the right
# hand side must be named 'value'.
ret <- extractEqHelperAssign(x, ..., inModel = inModel)
} else {
stop("cannot handle class, please report a bug: ", class(x)[1]) # nocov
}
ret
}