content
stringlengths
0
14.9M
filename
stringlengths
44
136
--- title: "Standards in Different Regulatory Agencies" output: rmarkdown::html_vignette: toc: true check_title: TRUE vignette: > %\VignetteIndexEntry{Standards in Different Regulatory Agencies} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- # Motivation The `xportr` package is designed to help clinical programmers create `CDISC` compliant `xpt` files. It provides the functionality to associate metadata information to a local R data frame, perform data set level validation checks, and convert into a transport v5 file (`xpt`). However, technical requirements related to the `xpt` files can change across different regulatory agencies. This vignette aims to start to provide a clear and concise summary of the differences between the agencies for the `xpt` files. Further updates will come with later package releases. The following section will delve into various technical specifications as per [FDA](https://www.fda.gov/media/153632/download), [NMPA](https://www.nmpa.gov.cn/directory/web/nmpa/images/obbSqc7vwdm0ssrU0enKb7dtd29u9a4tbzUrdTyo6jK1NDQo6mhty5wZGY=.pdf), and [PMDA](https://www.pmda.go.jp/files/000247157.pdf) guidelines. ### File name - character #### XPT <img src="../man/figures/xpt.png" style="height: 34px;"/> The first character must be an English letter (A, B, C, . . ., Z) or underscore (_). Subsequent characters can be letters, numeric digits (0, 1, . . ., 9), or underscores. You can use uppercase or lowercase letters. Blanks cannot appear in SAS names. Special characters, except for the underscore, are not allowed. #### FDA <img src="../man/figures/fda.jpg" style="height: 20px;"/> Dataset in the transport file should be named the same as the transport file. Variable names, as well as variable and dataset labels should include American Standard Code for Information Interchange (ASCII) text codes only. Dataset names should contain only lowercase letters, numbers, and must start with a letter. #### NMPA <img src="../man/figures/nmpa.png" style="height: 27px;"/> The file name and the dataset name must be the same for the SDTM and ADaM datasets. The Japanese dataset and alphanumeric dataset must be identical in structure, except for the data lengths of the Japanese items and the corresponding alphanumeric character sequence #### PMDA <img src="../man/figures/pmda.png" style="height: 20px;"/> Information has not yet been collected. *** ### File name - length #### XPT <img src="../man/figures/xpt.png" style="height: 34px;"/> maximum length of 8 bytes #### FDA <img src="../man/figures/fda.jpg" style="height: 20px;"/> 8 characters #### NMPA <img src="../man/figures/nmpa.png" style="height: 27px;"/> \- #### PMDA <img src="../man/figures/pmda.png" style="height: 20px;"/> Information has not yet been collected. *** ### Variable name #### XPT <img src="../man/figures/xpt.png" style="height: 34px;"/> The name can contain letters of the Latin alphabet, numerals, or underscores. The name cannot contain blanks or special characters except for the underscore. The name must begin with a letter of the Latin alphabet (A–Z, a–z) or the underscore. #### FDA <img src="../man/figures/fda.jpg" style="height: 20px;"/> Variable names, as well as variable and dataset labels should include American Standard Code for Information Interchange (ASCII) text codes only. Variable names should contain only uppercase letters, numbers, and must start with a letter #### NMPA <img src="../man/figures/nmpa.png" style="height: 27px;"/> The Japanese dataset and alphanumeric dataset must be identical in structure, except for the data lengths of the Japanese items and the corresponding alphanumeric character sequence #### PMDA <img src="../man/figures/pmda.png" style="height: 20px;"/> Information has not yet been collected. *** ### Variable length #### XPT <img src="../man/figures/xpt.png" style="height: 34px;"/> 8 bytes #### FDA <img src="../man/figures/fda.jpg" style="height: 20px;"/> 8 characters #### NMPA <img src="../man/figures/nmpa.png" style="height: 27px;"/> \- #### PMDA <img src="../man/figures/pmda.png" style="height: 20px;"/> Information has not yet been collected. *** ### Label character #### XPT <img src="../man/figures/xpt.png" style="height: 34px;"/> \- #### FDA <img src="../man/figures/fda.jpg" style="height: 20px;"/> Variable names, as well as variable and dataset labels should include American Standard Code for Information Interchange (ASCII) text codes only. Do not submit study data with the following special characters in variable and dataset labels: 1. Unbalanced apostrophe, e.g., "Parkinson's" 2. Unbalanced single and double quotation marks 3. Unbalanced parentheses, braces or brackets, e.g.,`(`, `{`and `[` #### NMPA <img src="../man/figures/nmpa.png" style="height: 27px;"/> The Japanese dataset and alphanumeric dataset must be identical in structure, except for the data lengths of the Japanese items and the corresponding alphanumeric character sequence #### PMDA <img src="../man/figures/pmda.png" style="height: 20px;"/> For eSubmission in China, one of the requirements is to translate the foreign language data package (e.g., English) to Chinese. Variable labels, dataset labels, MedDRA, WHO Drug terms, primary endpoint-related code lists, etc., need to be translated from English to Chinese. *** ### Label length #### XPT <img src="../man/figures/xpt.png" style="height: 34px;"/> 40 bytes #### FDA <img src="../man/figures/fda.jpg" style="height: 20px;"/> 40 characters #### NMPA <img src="../man/figures/nmpa.png" style="height: 27px;"/> \- #### PMDA <img src="../man/figures/pmda.png" style="height: 20px;"/> Information has not yet been collected. *** ### Values character #### XPT <img src="../man/figures/xpt.png" style="height: 34px;"/> \- #### FDA <img src="../man/figures/fda.jpg" style="height: 20px;"/> Variable values are the most broadly compatible with software and operating systems when they are restricted to ASCII text codes (printable values below 128). Use UTF-8 for extending character sets; however, the use of extended mappings is not recommended. Transcoding errors, variable length errors, and lack of software support for multi byte UTF-8 encodings can result in incorrect character display and variable value truncation. #### NMPA <img src="../man/figures/nmpa.png" style="height: 27px;"/> If variables had been collected in Japanese and there is a risk of losing certain information by translating it into English, the descriptions in Japanese are necessary and appropriate, and data written in Japanese (hereinafter referred to as Japanese data) may be submitted. In the Japanese dataset, only the Japanese items should be Japanese and the rest should be alphanumeric(=ASCII) data, similar to that in the alphanumeric dataset. #### PMDA <img src="../man/figures/pmda.png" style="height: 20px;"/> For eSubmission in China, one of the requirements is to translate the foreign language data package (e.g., English) to Chinese. Variable labels, dataset labels, MedDRA, WHO Drug terms, primary endpoint-related code lists, etc., need to be translated from English to Chinese. *** ### Values length #### XPT <img src="../man/figures/xpt.png" style="height: 34px;"/> 200 bytes #### FDA <img src="../man/figures/fda.jpg" style="height: 20px;"/> The allotted length for each column containing character (text) data should be set to the maximum length of the variable used across all datasets in the study except for supplementary qualification datasets. #### NMPA <img src="../man/figures/nmpa.png" style="height: 27px;"/> \- #### PMDA <img src="../man/figures/pmda.png" style="height: 20px;"/> Information has not yet been collected. *** ### Format #### XPT <img src="../man/figures/xpt.png" style="height: 34px;"/> SAS format #### FDA <img src="../man/figures/fda.jpg" style="height: 20px;"/> SAS format #### NMPA <img src="../man/figures/nmpa.png" style="height: 27px;"/> \- #### PMDA <img src="../man/figures/pmda.png" style="height: 20px;"/> Information has not yet been collected. *** ### Type #### XPT <img src="../man/figures/xpt.png" style="height: 34px;"/> Numeric and character #### FDA <img src="../man/figures/fda.jpg" style="height: 20px;"/> \- #### NMPA <img src="../man/figures/nmpa.png" style="height: 27px;"/> \- #### PMDA <img src="../man/figures/pmda.png" style="height: 20px;"/> \- *** ### File size #### XPT <img src="../man/figures/xpt.png" style="height: 34px;"/> \- #### FDA <img src="../man/figures/fda.jpg" style="height: 20px;"/> 5 GB #### NMPA <img src="../man/figures/nmpa.png" style="height: 27px;"/> To be consulted if sponsors have datasets >= 5 GB No requirement to split datasets #### PMDA <img src="../man/figures/pmda.png" style="height: 20px;"/> Information has not yet been collected.
/scratch/gouwar.j/cran-all/cranData/xportr/vignettes/agency_standards.Rmd
--- title: "Deep Dive into xportr" output: rmarkdown::html_vignette: toc: true check_title: TRUE vignette: > %\VignetteIndexEntry{Deep Dive into xportr} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = " " ) options(cli.num_colors = 1) library(DT) ``` ```{r, include=FALSE} # Used to control str() output later on local({ hook_output <- knitr::knit_hooks$get("output") knitr::knit_hooks$set(output = function(x, options) { if (!is.null(options$max.height)) { options$attr.output <- c( options$attr.output, sprintf('style="max-height: %s;"', options$max.height) ) } hook_output(x, options) }) }) ``` ```{css, echo=FALSE} /* Used to control DT outputs */ .text-left { text-align: left; } ``` # Introduction This vignette will explore in detail all the possibilities of the `{xportr}` package for applying information from a metadata object to an R created dataset using the core `{xportr}` functions. We will also explore the following: * What goes in a Submission to a Health Authority, and what role does `{xportr}` play in that Submission? * What is `{xportr}` validating behind the scenes? * Breakdown of `{xportr}` and a ADaM dataset specification file. * Using `options()` and `xportr_metadata()` to enhance your `{xportr}` experience. * Understanding the warning and error messages for each `{xportr}` function. * A brief discussion on future work. **NOTE:** We use the phrase _metadata object_ throughout this package. A _metadata object_ can either be a specification file read into R as a dataframe or a `{metacore}` object. The _metadata object_ created via the `{metacore}` package has additional features not covered here, but at its core is using a specification file. However, `{xportr}` will work with either a dataframe or a `{metacore}` object. # What goes in a Submission to a Health Authority? Quite a bit! We will focus on the data deliverables and supporting documentation needed for a successful submission to a Health Authority and how `{xportr}` can play a key role. We will briefly look at three parts: 1) Study Data Standardization Plan 2) SDTM Data Package 3) ADaM Data Package ## Study Data Standardization Plan The Study Data Standardization Plan (SDSP) establishes and documents a plan for describing the data standardization approach for clinical and nonclinical studies within a development program. The SDSP also assists the FDA in identifying potential data standardization issues early in the development program. We hope the brevity of this section does not belie the huge importance of this document. Please see [Study Data Standardisation Plan (SDSP) Package](https://advance.phuse.global/display/WEL/Study+Data+Standardisation+Plan+%28SDSP%29+Package) maintained by the [PHUSE working group](https://advance.phuse.global/display/WEL/Welcome+to+the+PHUSE+Advance+Hub). However, we want to focus more on the actual data and how `{xportr}` can play a role in the submission. ## SDTM and ADaM Data Packages __SDTM:__ The primary pieces of the SDTM package are the SDTM annotated case report forms (acrf.pdf), the data definitions document (define.xml), the Study Data Reviewer's Guide (sdrg.pdf) and the datasets in xpt Version 5 format. The Version 5 xpt file is the **required** submission format for all datasets going to the Health Authorities. __ADaM:__ The key components of the ADaM package are very similar to SDTM package with a few additions: define.xml, Analysis Study Data Reviewer's Guide (adrg.pdf), Analysis Results Metadata (analysis-results-metadata.pdf) and datasets as Version 5 xpt format. As both Data Packages need compliant `xpt` files, we feel that `{xportr}` can play a pivotal role here. The core functions in `{xportr}` can be used to apply information from the _metadata object_ to the datasets giving users feedback on the quality of the metadata and data. `xportr_write()` can then be used to write out the final dataset as an `xpt` file, which can be submitted to a Health Authority. ## What is `{xportr}` validating in these Data Packages? The `xpt` Version 5 files form the backbone of any successful Submission and are govern by quite a lot of rules and suggested guidelines. As you are preparing your data packages for submission the suite of core `{xportr}` functions, plus `xportr_write()`, helps to check that your datasets are submission compliant. The package checks many of the latest rules laid out in the [Study Data Technical Conformance Guide](https://www.fda.gov/regulatory-information/search-fda-guidance-documents/study-data-technical-conformance-guide-technical-specifications-document), but please note that it is not yet an exhaustive list of checks. We envision that users are also submitting their `xpts` and metadata to additional validation software. Each of the core `{xportr}` functions for applying labels, types, formats, order and lengths provides feedback to users on submission compliance. However, a final check is implemented when `xportr_write()` is called to create the `xpt`. `xportr_write()` calls [`xpt_validate()`](https://github.com/atorus-research/xportr/blob/231e959b84aa0f1e71113c85332de33a827e650a/R/utils-xportr.R#L174), which is a behind the scenes/non-exported function that does a final check for compliance. At the time of `{xportr} v0.3.0` we are checking the following when a user writes out an `xpt` file.: <img src="../man/figures/xpt_validate.png" alt="validate" style="width: calc(100% - 2px); padding: 0; margin: 0;"/> # {xportr} in action In this section, we are going to explore the 5 core `{xportr}` functions using: * `data("adsl_xportr", package = "xportr")` - An ADSL ADaM dataset from the Pilot 3 Submission to the FDA * `data("var_spec", package = "xportr")` - The ADSL ADaM Specification File from the Pilot 3 Submission to the FDA We will focus on warning and error messaging with contrived examples from these functions by manipulating either the datasets or the specification files. **NOTE:** We have made the ADSL and Spec available in this package. Users can find additional datasets and specification files on our [repo](https://github.com/atorus-research/xportr) in the `example_data_specs` folder. This is to keep the package to a minimum size. ## Using `options()` and `xportr_metadata()` to enhance your experience. Before we dive into the functions, we want to point out some quality of life utilities to make your `xpt` generation life a little bit easier. * `options()` * `xportr_options()` * `xportr_metadata()` **NOTE:** As long as you have a well-defined _metadata object_ you do NOT need to use `options()` or `xportr_metadata()`, but we find these handy to use and think they deserve a quick mention! ## You've got `options()` or `xportr_options()` `{xportr}` is built with certain assumptions around specification column names and information in those columns. We have found that each company specification file can differ slightly from our assumptions. For example, one company might call a column `Variables`, another `Variable` and another `variables`. Rather than trying to regex ourselves out of this situation, we have introduced `options()`. `options()` allows users to control those assumptions inside `{xportr}` functions based on their needs. Additionally, we have a helper function `xportr_options()` which works just like the `options()` but, it can also be used to get the current state of the xportr options. Let's take a look at our example specification file names available in this package. We can see that all the columns start with an upper case letter and have spaces in several of them. We could convert all the column names to lower case and deal with the spacing using some `{dplyr}` functions or base R, or we could just use `options()`! ```{r, message = FALSE} library(xportr) library(dplyr) library(haven) data("adsl_xportr", "var_spec", "dataset_spec", package = "xportr") colnames(var_spec) ADSL <- adsl_xportr ``` By using `options()` or `xportr_options()` at the beginning of our script we can tell `{xportr}` what the valid names are (see chunk below). Please note that before we set the options the package assumed every thing was in lowercase and there were no spaces in the names. After running `options()` or `xportr_options()`, `{xportr}` sees the column `Variable` as the valid name rather than `variable`. You can inspect `xportr_options` function docs to look at additional options. ```{r, eval = FALSE} xportr_options( xportr.variable_name = "Variable", xportr.label = "Label", xportr.type_name = "Data Type", xportr.format = "Format", xportr.length = "Length", xportr.order_name = "Order" ) # Or alternatively options( xportr.variable_name = "Variable", xportr.label = "Label", xportr.type_name = "Data Type", xportr.format = "Format", xportr.length = "Length", xportr.order_name = "Order" ) ``` ## Are we being too verbose? One final note on the options. 4 of the core `{xportr}` functions have the ability to set messaging as `"none", "message", "warn", "stop"`. Setting each of these in all your calls can be a bit repetitive. You can use `options()` or `xportr_options()` to set these at a higher level and avoid this repetition. ```{r, eval = FALSE} # Default verbose is set to `none` xportr_options( xportr.format_verbose = "none", xportr.label_verbose = "none", xportr.length_verbose = "none", xportr.type_verbose = "none" ) xportr_options( xportr.format_verbose = "none", # Disables any messaging, keeping the console output clean xportr.label_verbose = "message", # Sends a standard message to the console xportr.length_verbose = "warn", # Sends a warning message to the console xportr.type_verbose = "stop" # Stops execution and sends an error message to the console ) ``` ## Going meta Each of the core `{xportr}` functions requires several inputs: A valid dataframe, a metadata object and a domain name, along with optional messaging. For example, here is a simple call using all of the functions. As you can see, a lot of information is repeated in each call. ```{r, eval = FALSE} ADSL %>% xportr_type(var_spec, "ADSL", "message") %>% xportr_length(var_spec, "ADSL", verbose = "message") %>% xportr_label(var_spec, "ADSL", "message") %>% xportr_order(var_spec, "ADSL", "message") %>% xportr_format(var_spec, "ADSL") %>% xportr_df_label(dataset_spec, "ADSL") %>% xportr_write("adsl.xpt") ``` To help reduce these repetitive calls, we have created `xportr_metadata()`. A user can just **set** the _metadata object_ and the Domain name in the first call, and this will be passed on to the other functions. Much cleaner! ```{r, eval = FALSE} ADSL %>% xportr_metadata(var_spec, "ADSL") %>% xportr_type() %>% xportr_length(length_source = "metadata") %>% xportr_label() %>% xportr_order() %>% xportr_format() %>% xportr_df_label(dataset_spec) %>% xportr_write("adsl.xpt") ``` ## Warnings and Errors For the next six sections, we are going to explore the Warnings and Errors messages generated by the `{xportr}` core functions. To better explore these, we will either manipulate the ADaM dataset or specification file to help showcase the ability of the `{xportr}` functions to detect issues. **NOTE:** We have made the ADSL, `xportr::adsl`, and Specification File, `xportr::var_spec`, available in this package. Users can find additional datasets and specification files on our [repo](https://github.com/atorus-research/xportr) in the `example_data_specs` folder. ### Setting up our metadata object First, let's read in the specification file and call it `var_spec`. Note that we are not using `options()` here. We will do some slight manipulation to the column names by doing all lower case, and changing `Data Type` to `type` and making the Order column numeric. You can also use `options()` for this step as well. The `var_spec` object has five dataset specification files stacked on top of each other. We will make use of the `ADSL` subset of `var_spec`. You can make use of the Search field above the dataset column to subset the specification file for `ADSL` Similarly, we can read the Dataset spec file and call it `dataset_spec`. ```{r} var_spec <- var_spec %>% rename(type = "Data Type") %>% rename_with(tolower) dataset_spec <- dataset_spec %>% rename(label = "Description") %>% rename_with(tolower) ``` ```{r, echo = FALSE} columns2hide <- c( "significant digits", "mandatory", "assigned value", "codelist", "common", "origin", "pages", "method", "predecessor", "role", "comment", "developer notes" ) datatable( var_spec %>% select(-all_of(columns2hide)), rownames = FALSE, filter = "top", options = list( dom = "Bfrtip", columnDefs = list( list( width = "10px", targets = c("order", "length", "format", "type", "dataset", "variable") ), list( className = "text-left", targets = c("label") ) ), searching = FALSE, autoWidth = TRUE ) ) %>% formatStyle(0, target = "row", color = "black", backgroundColor = "white", fontWeight = "500", lineHeight = "85%", textAlign = "center", fontSize = ".875em" # same as code ) ``` ## `xportr_type()` We are going to explore the type column in the metadata object. A submission to a Health Authority should only have character and numeric types in the data. In the `ADSL` data we have several columns that are in the Date type: `TRTSDT`, `TRTEDT`, `SCRFDT`, `EOSDT`, `FRVDT`, `RANDDT`, `DTHDT`, `LSTALVDT` - under the hood these are actually numeric values and will be left as is. We will change one variable type to a [factor variable](https://forcats.tidyverse.org/), which is a common data structure in R, to give us some educational opportunities to see `xportr_type()` in action. ```{r} adsl_fct <- ADSL %>% mutate(STUDYID = as_factor(STUDYID)) ``` ```{r, echo = FALSE} adsl_glimpse <- adsl_fct %>% select(STUDYID, TRTSDT, TRTEDT, SCRFDT, EOSDT, FRVDT, RANDDT, DTHDT, LSTALVDT) ``` ```{r, echo = FALSE} glimpse(adsl_glimpse) ``` ```{r, echo = TRUE} adsl_type <- xportr_type(.df = adsl_fct, metadata = var_spec, domain = "ADSL", verbose = "warn") ``` ```{r, echo = FALSE} adsl_type_glimpse <- adsl_type %>% select(STUDYID, TRTSDT, TRTEDT, SCRFDT, EOSDT, FRVDT, RANDDT, DTHDT, LSTALVDT) ``` Success! As we can see below, `xportr_type()` applied the types from the metadata object to the `STUDYID` variables converting to the proper type. The functions in `{xportr}` also display this coercion to the user in the console, which is seen above. ```{r, echo = TRUE} glimpse(adsl_type_glimpse) ``` Note that `xportr_type(verbose = "warn")` was set so the function has provided feedback, which would show up in the console, on which variables were converted as a warning message. However, you can set `verbose = "stop"` so that the types are not applied if the data does not match what is in the specification file. Using `verbose = "stop"` will instantly stop the processing of this function and not create the object. A user will need to alter the variables in their R script before using `xportr_type()` ```{r, echo = TRUE, error = TRUE} adsl_type <- xportr_type(.df = adsl_fct, metadata = var_spec, domain = "ADSL", verbose = "stop") ``` ## `xportr_length()` There are two sources of length (data-driven and spec-driven): - Data-driven length: max length for character columns and 8 for other data types - Spec-driven length: from the metadata 1. Users can either specify the length in the metadata or leave it blank for data-driven length. 2. When the length is missing in the metadata, the data-driven length will be applied. Next we will use `xportr_length()` to apply the length column of the _metadata object_ to the `ADSL` dataset. Using the `str()` function we have displayed all the variables with their attributes. You can see that each variable has a label, but there is no information on the lengths of the variable. ```{r, max.height='300px', attr.output='.numberLines', echo = FALSE} str(ADSL) ``` ```{r, echo = TRUE} adsl_length <- xportr_length( .df = ADSL, metadata = var_spec, domain = "ADSL", verbose = "warn", length_source = "metadata" ) ``` Using `xportr_length()` with `verbose = "warn"` we can apply the length column to all the columns in the dataset. The function detects that two variables, `TRTDUR` and `DCREASCD` are missing from the metadata file. Note that the variables have slight misspellings in the dataset and metadata, which is a great catch! However, lengths are still applied with TRTDUR being give a length of 8 and DCREASCD a length of 200. Using the `str()` function, you can see below that `xportr_length()` successfully applied all the lengths of the variable to the variables in the dataset. ```{r, max.height='300px', attr.output='.numberLines', echo = FALSE} str(adsl_length) ``` Just like we did for `xportr_type()`, setting `verbose = "stop"` immediately stops R from processing the lengths. Here the function detects the missing variables and will not apply any lengths to the dataset until corrective action is applied. ```{r, echo = TRUE, error = TRUE} adsl_length <- xportr_length( .df = ADSL, metadata = var_spec, domain = "ADSL", verbose = "stop", length_source = "metadata" ) ``` ## `xportr_label()` As you are creating your dataset in R you will often find that R removes the label of your variable. Using `xportr_label()` you can easily re-apply all your labels to your variables in one quick action. For this example, we are going to manipulate both the metadata and the `ADSL` dataset: * The metadata will have the variable `TRTSDT` label be greater than 40 characters. * The `ADSL` dataset will have all its labels stripped from it. Remember in the length example, the labels were on the original dataset as seen in the `str()` output. ```{r, echo = TRUE} var_spec_lbl <- var_spec %>% mutate(label = if_else(variable == "TRTSDT", "Length of variable label must be 40 characters or less", label )) adsl_lbl <- ADSL adsl_lbl <- haven::zap_label(ADSL) ``` We have successfully removed all the labels. ```{r, max.height='300px', attr.output='.numberLines', echo = FALSE} str(adsl_lbl) ``` Using `xportr_label()` we will apply all the labels from our metadata to the dataset. Please note again that we are using `verbose = "warn"` and the same two issues for `TRTDUR` and `DCREASCD` are reported as missing from the metadata file. An additional message is sent around the `TRTSDT` label having a length of greater than 40. ```{r} adsl_lbl <- xportr_label(.df = adsl_lbl, metadata = var_spec_lbl, domain = "ADSL", verbose = "warn") ``` Success! All labels have been applied that are present in the both the metadata and the dataset. However, please note that the `TRTSDT` variable has had the label with characters greater than 40 **applied** to the dataset and the `TRTDUR` and `DCREASCD` have empty variable labels. ```{r, max.height='300px', attr.output='.numberLines', echo = FALSE} str(adsl_lbl) ``` Just like we did for the other functions, setting `verbose = "stop"` immediately stops R from processing the labels. Here the function detects the mismatches between the variables and labels as well as the label that is greater than 40 characters. As this stops the process, none of the labels will be applied to the dataset until corrective action is applied. ```{r, echo = TRUE, error = TRUE} adsl_label <- xportr_label(.df = adsl_lbl, metadata = var_spec_lbl, domain = "ADSL", verbose = "stop") ``` ## `xportr_order()` The order of the dataset can greatly increase readability of the dataset for downstream stakeholders. For example, having all the treatment related variables or analysis variables grouped together can help with inspection and understanding of the dataset. `xportr_order()` can take the order information from the metadata and apply it to your dataset. ```{r} adsl_ord <- xportr_order(.df = ADSL, metadata = var_spec, domain = "ADSL", verbose = "warn") ``` Readers are encouraged to inspect the dataset and metadata to see the past order and updated order after calling the function. Note the messaging from `xportr_order()`: * Variables not in the metadata are moved to the end * Variables not in order are re-ordered and a message is printed out on which ones were re-ordered. ```{r, echo = TRUE, error = TRUE} adsl_ord <- xportr_order(.df = ADSL, metadata = var_spec, domain = "ADSL", verbose = "stop") ``` Just like we did for the other functions, setting `verbose = "stop"` immediately stops R from processing the order. If variables or metadata are missing from either, the re-ordering will not process until corrective action is performed. ## `xportr_format()` Formats play an important role in the SAS language and have a column in specification files. Being able to easily apply formats into your `xpt` file will allow downstream users of SAS to quickly format the data appropriately when reading into a SAS-based system. `xportr_format()` can take these formats and apply them. Please reference `xportr_length()` or `xportr_label()` to note the missing `attr()` for formats in our `ADSL` dataset. This example is slightly different from previous examples. You will need to use `xportr_type()` to coerce R Date variables and others types to character or numeric. Only then can you use `xportr_format()` to apply the format column to the dataset. ```{r, echo = TRUE} adsl_fmt <- ADSL %>% xportr_type(metadata = var_spec, domain = "ADSL", verbose = "warn") %>% xportr_format(metadata = var_spec, domain = "ADSL") ``` Success! We have taken the metadata formats and applied them to the dataset. Please inspect variables like `TRTSDT` or `DISONSDT` to see the `DATE9.` format being applied. ```{r, max.height='300px', attr.output='.numberLines', echo = FALSE} str(adsl_fmt) ``` At the time of `{xportr} v0.3.0` we have not implemented any warnings or error messaging for this function. However, `xportr_write()` through `xpt_validate()` will check that formats applied are valid SAS formats. ## `xportr_write()` Finally, we want to write out an `xpt` dataset with all our metadata applied. We will make use of `xportr_metadata()` to reduce repetitive metadata and domain specifications. We will use default option for verbose, which is just `message` and so not set anything for `verbose`. In `xportr_write()` we will specify the path, which will just be our current working directory, set the dataset label and toggle the `strict_checks` to be `FALSE`. It is also note worthy that you can set the dataset label using the `xportr_df_label` and a `dataset_spec` which will be used by the `xportr_write()` ```{r, echo = TRUE, error = TRUE} ADSL %>% xportr_metadata(var_spec, "ADSL") %>% xportr_type() %>% xportr_length(length_source = "metadata") %>% xportr_label() %>% xportr_order() %>% xportr_format() %>% xportr_df_label(dataset_spec) %>% xportr_write(path = "adsl.xpt", strict_checks = FALSE) ``` Success! We have applied types, lengths, labels, ordering and formats to our dataset. Note the messages written out to the console. Remember the `TRTDUR` and `DCREASCD` and how these are not present in the metadata, but in the dataset. This impacts the messaging for lengths and labels where `{xportr}` is printing out some feedback to us on the two issues. 5 types are coerced, as well as 36 variables re-ordered. Note that `strict_checks` was set to `FALSE`. The next two examples showcase the `strict_checks = TRUE` option in `xportr_write()` where we will look at formats and labels. ```{r, echo = TRUE, error = TRUE} ADSL %>% xportr_write(path = "adsl.xpt", metadata = dataset_spec, domain = "ADSL", strict_checks = TRUE) ``` As there at several `---DT` type variables, `xportr_write()` detects the lack of formats being applied. To correct this remember you can use `xportr_type()` and `xportr_format()` to apply formats to your xpt dataset. Below we have manipulated the labels to again be greater than 40 characters for `TRTSDT`. We have turned off `xportr_label()` verbose options to only produce a message. However, `xportr_write()` with `strict_checks = TRUE` will error out as this is one of the many `xpt_validate()` checks going on behind the scenes. ```{r, echo = TRUE, error = TRUE} var_spec_lbl <- var_spec %>% mutate(label = if_else(variable == "TRTSDT", "Length of variable label must be 40 characters or less", label )) ADSL %>% xportr_metadata(var_spec_lbl, "ADSL") %>% xportr_label() %>% xportr_type() %>% xportr_format() %>% xportr_df_label(dataset_spec) %>% xportr_write(path = "adsl.xpt", strict_checks = TRUE) ``` ## `xportr()` Too many functions to call? Simplify with `xportr()`. It bundles all core `xportr` functions for writing to `xpt`. ```{r, echo = TRUE, error = TRUE} xportr( ADSL, var_metadata = var_spec, df_metadata = dataset_spec, domain = "ADSL", verbose = "none", path = "adsl.xpt" ) ``` `xportr()` is equivalent to calling the following functions individually: ```{r, echo = TRUE, error = TRUE} ADSL %>% xportr_metadata(var_spec, "ADSL") %>% xportr_type() %>% xportr_length(length_source = "metadata") %>% xportr_label() %>% xportr_order() %>% xportr_format() %>% xportr_df_label(dataset_spec) %>% xportr_write(path = "adsl.xpt", strict_checks = FALSE) ``` ## Future Work `{xportr}` is still undergoing development. We hope to produce more vignettes and functions that will allow users to bulk process multiple datasets as well as have examples of piping `xpt` files and related documentation to a validation software service. As always, please let us know of any feature requests, documentation updates or bugs on [our GitHub repo](https://github.com/Atorus-Research/xportr/issues).
/scratch/gouwar.j/cran-all/cranData/xportr/vignettes/deepdive.Rmd
--- title: "Getting Started" output: rmarkdown::html_vignette: toc: true check_title: TRUE vignette: > %\VignetteIndexEntry{Getting Started} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = " " ) library(DT) options(cli.num_colors = 1) ``` ```{r, include=FALSE} options(width = 60) local({ hook_output <- knitr::knit_hooks$get("output") knitr::knit_hooks$set(output = function(x, options) { if (!is.null(options$max.height)) { options$attr.output <- c( options$attr.output, sprintf('style="max-height: %s;"', options$max.height) ) } hook_output(x, options) }) }) ``` ```{r, include=FALSE} knitr::knit_hooks$set(output = function(x, options) { if (!is.null(options$max_height)) { paste('<pre style = "max-height:', options$max_height, '; float: left; width: 775px; overflow-y: auto;">', x, "</pre>", sep = "" ) } else { x } }) ``` ```{r, include=FALSE} datatable_template <- function(input_data) { datatable( input_data, rownames = FALSE, options = list( autoWidth = FALSE, scrollX = TRUE, pageLength = 5, lengthMenu = c(5, 10, 15, 20) ) ) %>% formatStyle( 0, target = "row", color = "black", backgroundColor = "white", fontWeight = "500", lineHeight = "85%", fontSize = ".875em" # same as code ) } ``` # Getting Started with xportr The demo will make use of a small `ADSL` dataset available with the `xportr` package and has the following features: * 306 observations * 51 variables * Data types other than character and numeric * Missing labels on variables * Missing label for data set * Order of variables not following specification file * Formats missing To create a fully compliant v5 xpt `ADSL` dataset, that was developed using R, we will need to apply the 6 main functions within the `xportr` package: * `xportr_type()` * `xportr_length()` * `xportr_order()` * `xportr_format()` * `xportr_label()` * `xportr_write()` ```{r, eval = TRUE, message = FALSE, warning = FALSE} # Loading packages library(dplyr) library(labelled) library(xportr) library(readxl) # Loading in our example data data("adsl_xportr", package = "xportr") ``` ```{r, echo = FALSE} datatable_template(adsl_xportr) ``` # Preparing your Specification Files In order to make use of the functions within `{xportr}` you will need to create an R data frame that contains your specification file. You will most likely need to do some pre-processing of your spec sheets after loading in the spec files for them to work appropriately with the `xportr` functions. Please see our example spec sheets in `system.file(file.path("specs", "ADaM_spec.xlsx"), package = "xportr")` to see how `xportr` expects the specification sheets. ```{r} var_spec <- read_xlsx( system.file(file.path("specs/", "ADaM_spec.xlsx"), package = "xportr"), sheet = "Variables" ) %>% rename(type = "Data Type") %>% rename_with(tolower) ``` Below is a quick snapshot of the specification file pertaining to the `ADSL` data set, which we will make use of in the 6 `{xportr}` function calls below. Take note of the order, label, type, length and format columns. ```{r, echo = FALSE, eval = TRUE} var_spec_view <- var_spec %>% filter(dataset == "ADSL") datatable_template(var_spec_view) ``` # xportr_type() **NOTE:** We make use of `str()` to expose the attributes (length, labels, formats, type) of the datasets. We have suppressed these calls for the sake of brevity. In order to be compliant with transport v5 specifications an `xpt` file can only have two data types: character and numeric/dbl. Currently the `ADSL` data set has chr, dbl, time, factor and date. ```{r, max_height = "200px", echo = FALSE} str(adsl_xportr) ``` Using `xportr_type()` and the supplied specification file, we can *coerce* the variables in the `ADSL` set to be either numeric or character. ```{r, echo = TRUE} adsl_type <- xportr_type(adsl_xportr, var_spec, domain = "ADSL", verbose = "message") ``` Now all appropriate types have been applied to the dataset as seen below. ```{r, max_height = "200px", echo = FALSE} str(adsl_type) ``` # xportr_length() Next we can apply the lengths from a variable level specification file to the data frame. `xportr_length()` will identify variables that are missing from your specification file. The function will also alert you to how many lengths have been applied successfully. Before we apply the lengths lets verify that no lengths have been applied to the original dataframe. ```{r, max_height = "200px", echo = FALSE} str(adsl_xportr) ``` No lengths have been applied to the variables as seen in the printout - the lengths would be in the `attr()` part of each variables. Let's now use `xportr_length()` to apply our lengths from the specification file. ```{r} adsl_length <- adsl_xportr %>% xportr_length(var_spec, domain = "ADSL", verbose = "message") ``` ```{r, max_height = "200px", echo = FALSE} str(adsl_length) ``` Note the additional `attr(*, "width")=` after each variable with the width. These have been directly applied from the specification file that we loaded above! # xportr_order() Please note that the order of the `ADSL` variables, see above, does not match the specification file `order` column. We can quickly remedy this with a call to `xportr_order()`. Note that the variable `SITEID` has been moved as well as many others to match the specification file order column. Variables not in the spec are moved to the end of the data and a message is written to the console. ```{r, echo = TRUE} adsl_order <- xportr_order(adsl_xportr, var_spec, domain = "ADSL", verbose = "message") ``` ```{r, echo = FALSE} datatable_template(adsl_order) ``` # xportr_format() Now we apply formats to the dataset. These will typically be `DATE9.`, `DATETIME20` or `TIME5`, but many others can be used. Notice that in the `ADSL` dataset there are 8 Date/Time variables and they are missing formats. Here we just take a peak at a few `TRT` variables, which have a `NULL` format. ```{r, max_height = "200px", echo = FALSE} adsl_fmt_pre <- adsl_xportr %>% select(TRTSDT, TRTEDT, TRTSDTM, TRTEDTM) tribble( ~Variable, ~Format, "TRTSDT", attr(adsl_fmt_pre$TRTSDT, which = "format"), "TRTEDT", attr(adsl_fmt_pre$TRTEDT, which = "format"), "TRTSDTM", attr(adsl_fmt_pre$TRTSDTM, which = "format"), "TRTEDTM", attr(adsl_fmt_pre$TRTEDTM, which = "format") ) ``` Using our `xportr_format()` we can apply our formats to the dataset. ```{r} adsl_fmt <- adsl_xportr %>% xportr_format(var_spec, domain = "ADSL") ``` ```{r, max_height = "200px", echo = FALSE} adsl_fmt_post <- adsl_fmt %>% select(TRTSDT, TRTEDT, TRTSDTM, TRTEDTM) tribble( ~Variable, ~Format, "TRTSDT", attr(adsl_fmt_post$TRTSDT, which = "format"), "TRTEDT", attr(adsl_fmt_post$TRTEDT, which = "format"), "TRTSDTM", attr(adsl_fmt_post$TRTSDTM, which = "format"), "TRTEDTM", attr(adsl_fmt_post$TRTEDTM, which = "format") ) ``` **NOTE:** You can use `attr(data$variable, which = "format")` to inspect formats applied to a dataframe. The above output has these individual calls bound together for easier viewing. # xportr_label() Please observe that our `ADSL` dataset is missing many variable labels. Sometimes these labels can be lost while using R's function. However, a CDISC compliant data set needs to have each variable with a label. ```{r, max_height = "200px", echo = FALSE} adsl_no_lbls <- haven::zap_label(adsl_xportr) str(adsl_no_lbls) ``` Using the `xport_label` function we can take the specifications file and label all the variables available. `xportr_label` will produce a warning message if you the variable in the data set is not in the specification file. ```{r} adsl_lbl <- adsl_xportr %>% xportr_label(var_spec, domain = "ADSL", "message") ``` ```{r, max_height = "200px"} str(adsl_lbl) ``` # xportr_write() Finally, we arrive at exporting the R data frame object as a `xpt` file with `xportr_write()`. The `xpt` file will be written directly to your current working directory. To make it more interesting, we have put together all six functions with the magrittr pipe, `%>%`. A user can now apply types, length, variable labels, formats, data set label and write out their final xpt file in one pipe! Appropriate warnings and messages will be supplied to a user to the console for any potential issues before sending off to standard clinical data set validator application or data reviewers. ```{r} adsl_xportr %>% xportr_type(var_spec, "ADSL", "message") %>% xportr_length(var_spec, "ADSL", verbose = "message") %>% xportr_label(var_spec, "ADSL", "message") %>% xportr_order(var_spec, "ADSL", "message") %>% xportr_format(var_spec, "ADSL") %>% xportr_write("adsl.xpt") ``` That's it! We now have a `xpt` file created in R with all appropriate types, lengths, labels, ordering and formats from our specification file. If you are interested in exploring more of the custom warnings and error messages as well as more background on `xpt` generation be sure to check out the [Deep Dive](deepdive.html) User Guide. As always, we welcome your feedback. If you spot a bug, would like to see a new feature, or if any documentation is unclear - submit an issue on [xportr's GitHub page](https://github.com/atorus-research/xportr/issues).
/scratch/gouwar.j/cran-all/cranData/xportr/vignettes/xportr.Rmd
#' \code{xpose_data} examples #' #' @description Moxonidine \code{xpose_data} example. #' #' @format An \code{xpose_data} object #' #' @source \href{https://link.springer.com/article/10.1023/A:1020561807903}{Moxonidine model}: #' Assumption Testing in Population Pharmacokinetic Models: Illustrated with an Analysis of #' Moxonidine Data from Congestive Heart Failure Patients. Journal of Pharmacokinetics and #' Biopharmaceutics. 26(2):207–246 (1998). #' #' @examples #' print(xpdb_ex_pk) #' #' @name xpdb_ex_pk NULL
/scratch/gouwar.j/cran-all/cranData/xpose/R/examples.R
#' Create options for data import #' #' @description Provide a list of options to the general plotting functions such as #' \code{xplot_scatter} in order to create appropriate data input for ggplot2. #' #' @param .problem The problem to be used, by default returns the last one. #' @param .subprob The subproblem to be used, by default returns the last one. #' @param .method The estimation method to be used, by default returns the last one. #' @param .source Define the location of the data in the xpdb. Should be either 'data' #' to use the output tables or the name of an output file attached to the xpdb. #' @param simtab Only used when 'data' is defined as the source and `.problem` is default. Should the data be coming #' from an estimation or a simulation table. #' @param filter A function used to filter the data e.g. filter = function(x) x[x$TIME > 20, ] where x is the data. #' @param tidy Logical, whether the data should be transformed to tidy data. #' @param index_col Only used when 'tidy' is defined a \code{TRUE} and \code{value_col} is \code{NULL}. #' Column names to use as index when tidying the data. #' @param value_col Only used when 'tidy' is defined a \code{TRUE} and \code{index_col} is \code{NULL}. #' Column names to be stacked when tidying the data. #' @param post_processing A function used to modify the data after it has been tidied up e.g. post_processing = function(x) #' dplyr::mutate(.data = x, variable = as.factor(.$variable)) where x is the tidy data. #' #' @seealso \code{\link{xplot_distrib}} \code{\link{xplot_qq}} \code{\link{xplot_scatter}} #' #' @examples #' data_opt(.problem = 1, .source = 'data', simtab = TRUE) #' #' @export data_opt <- function(.problem = NULL, .subprob = NULL, .method = NULL, .source = 'data', simtab = FALSE, filter = NULL, tidy = FALSE, index_col = NULL, value_col = NULL, post_processing = NULL) { list(problem = .problem, subprob = .subprob, method = .method, source = .source, simtab = simtab, filter = filter, tidy = tidy, index_col = index_col, value_col = value_col, post_processing = post_processing) } #' Create functions to drop non observation records #' #' @description Create shortcut functions on the fly to remove records #' not associated with an observation. #' #' @param xpdb An xpose database object. #' @param .problem The $problem number to be used. #' @param quiet Should messages be displayed to the console. #' #' @return A function #' #' @keywords internal #' @export only_obs <- function(xpdb, .problem, quiet) { mdv_var <- xp_var(xpdb, .problem, type = c('evid', 'mdv'), silent = TRUE)$col[1] fun <- function(x) {} if (!is.null(mdv_var)) { string <- c('Filtering data by ', mdv_var, ' == 0') body(fun) <- bquote({ msg(.(string), .(quiet)) x[as.vector(x[, .(mdv_var)] == 0), ] }) } else { string <- c('No `evid` or `mdv` variable available to filter the data.') body(fun) <- bquote({ msg(.(string), .(quiet)) x }) } fun } #' Create functions for data deduplication #' #' @description Create shortcut functions on the fly to remove duplicated records in data. #' #' @param xpdb An xpose database object. #' @param .problem The $problem number to be used. #' @param facets The plot faceting variable. The `facets` variables along with the `id` column #' type will be as grouping factors during data deduplication process. #' @param quiet Should messages be displayed to the console. #' #' @return A function #' #' @keywords internal #' @export only_distinct <- function(xpdb, .problem, facets, quiet) { if (is.formula(facets)) facets <- all.vars(facets) vars <- c(xp_var(xpdb, .problem, type = c('id'))$col[1], facets) fun <- function(x) {} body(fun) <- bquote({ var_stg <- .(vars) # Silently remove "variable" when not in the data if ('variable' %in% var_stg && !'variable' %in% colnames(x)) { var_stg <- var_stg[-which(var_stg == 'variable')] } msg_stg <- c('Removing duplicated rows based on: ', stringr::str_c(var_stg, collapse = ', ')) msg(msg_stg, .(quiet)) dplyr::distinct(.data = x, !!!rlang::syms(var_stg), .keep_all = TRUE) }) fun } #' Reorder factors by numerical order #' #' @description Will for example convert `ETA(1)` to 1 create factors then generate labels #' by wrapping the digits with prefix and suffix. #' #' @param prefix A prefix to be added in front of the factor digits. #' @param suffix A suffix to be added after the factor digits. #' #' @return A modified tibble #' #' @keywords internal #' @export reorder_factors <- function(prefix, suffix = NULL) { if (!is.na(prefix)) { # Sort and reformat factors function(x) { x %>% dplyr::mutate(variable = as.numeric(gsub('\\D', '', .$variable))) %>% dplyr::mutate(variable = factor(.$variable, levels = sort(unique(.$variable)), labels = stringr::str_c(prefix, sort(unique(.$variable)), suffix))) } } else { # Only sort factors function(x) { levels <- x %>% dplyr::distinct(!!rlang::sym('variable')) %>% dplyr::mutate(variable_order = substring(.$variable, 1, 2)) %>% dplyr::mutate(variable_order = dplyr::case_when(.$variable_order == 'TH' ~ 1, .$variable_order == 'OM' ~ 2, .$variable_order == 'SI' ~ 3, TRUE ~ 0)) %>% dplyr::arrange_at(.vars = 'variable_order') dplyr::mutate(.data = x, variable = factor(x$variable, levels = levels$variable)) } } } #' Fetch data #' #' @description Main internal function to get the data from different source and #' prepare it for plotting. Arguments are usually provided by `data_opt()`. #' #' @inheritParams data_opt #' @param xpdb An xpose database object. #' @param quiet Should messages be displayed to the console. #' #' @return A tibble #' #' @keywords internal #' @export fetch_data <- function(xpdb, .problem = NULL, .subprob = NULL, .method = NULL, .source = 'data', simtab = FALSE, filter = NULL, tidy = FALSE, index_col = NULL, value_col = NULL, post_processing = NULL, quiet = FALSE) { if (.source == 'data') { if (is.null(.problem)) .problem <- last_data_problem(xpdb, simtab) if (is.na(.problem)) { stop(c('No data associated with $prob no.', .problem, ' could be found.'), call. = FALSE) } data <- get_data(xpdb, .problem = .problem) msg(c('Using data from $prob no.', .problem), quiet) } else { if (!any(xpdb$files$extension == .source)) { stop(c('File extension `.', .source, '` not found in model output files.'), call. = FALSE) } if (is.null(.problem)) .problem <- last_file_problem(xpdb, .source) if (is.null(.subprob)) .subprob <- last_file_subprob(xpdb, .source, .problem) if (is.null(.method)) .method <- last_file_method(xpdb, .source, .problem, .subprob) data <- get_file(xpdb, file = NULL, ext = .source, .problem = .problem, .subprob = .subprob, .method = .method, quiet = TRUE) msg(c('Using ', xpdb$files$name[xpdb$files$extension == .source][1] , ' $prob no.', .problem, ', subprob no.', .subprob, ', method ', .method, '.'), quiet) } if (is.function(filter)) data <- filter(data) if (tidy) { if (!is.null(value_col)) { index_col <- colnames(data)[!colnames(data) %in% value_col] } dplyr::if_else(length(index_col) > 5, stringr::str_c(stringr::str_c(index_col[1:5], collapse = ', '), '... and', length(index_col) - 5 , 'more variables', sep = ' '), stringr::str_c(index_col , collapse = ', ')) %>% {msg(c('Tidying data by ', .), quiet)} data <- tidyr::gather(data = data, key = 'variable', value = 'value', !!!rlang::syms(colnames(data)[!colnames(data) %in% index_col])) } if (is.function(post_processing)) data <- post_processing(data) # Add metadata to output attributes(data) <- c(attributes(data), list(problem = .problem, simtab = simtab, subprob = .subprob, method = .method, source = .source)) data }
/scratch/gouwar.j/cran-all/cranData/xpose/R/fetch_data.R
#' List NONMEM output tables #' #' @description List NONMEM output tables file names from a \code{nm_model} object. #' #' @param nm_model An xpose nm_model object generated with \code{\link{read_nm_model}}. #' #' @seealso \code{\link{read_nm_model}}, \code{\link{read_nm_tables}} #' @examples #' \dontrun{ #' read_nm_model(file = 'run001.lst') %>% #' list_nm_tables() #' } #' #' @export list_nm_tables <- function(nm_model = NULL) { if (is.null(nm_model) || !is.nm.model(nm_model)) { stop('Object of class `nm_model` required.', call. = FALSE) } # Prepare null object to be returned if no $table is found null_object <- as.nm.table.list(dplyr::tibble(problem = -1, file = '', firstonly = NA, simtab = NA)) # Get NM code associated with the tables table_list <- nm_model %>% dplyr::filter(.$problem > 0, .$subroutine == 'tab') if (nrow(table_list) == 0) return(null_object) table_list <- table_list %>% dplyr::group_by_at(.vars = c('problem', 'level')) %>% tidyr::nest() %>% dplyr::ungroup() %>% dplyr::mutate(string = purrr::map_chr(.$data, ~stringr::str_c(.$code, collapse = ' '))) %>% dplyr::mutate(file = stringr::str_match(.$string, '\\s+FILE\\s*=\\s*([^\\s]+)')[, 2]) %>% dplyr::filter(!is.na(.$file)) if (nrow(table_list) == 0) return(null_object) # Find table names and firstonly option table_list <- table_list %>% dplyr::mutate(file = file_path(attr(nm_model, 'dir'), .$file), firstonly = stringr::str_detect(.$string, 'FIRSTONLY')) %>% dplyr::select(dplyr::one_of('problem', 'file', 'firstonly')) # Prep simtab flag sim_flag <- nm_model %>% dplyr::filter(.$problem > 0) %>% dplyr::group_by_at(.vars = 'problem') %>% tidyr::nest() %>% dplyr::ungroup() %>% dplyr::mutate(simtab = purrr::map_lgl(.$data, ~!any(stringr::str_detect(.$subroutine, 'est')))) %>% dplyr::select(dplyr::one_of(c('problem', 'simtab'))) # Merge and output table_list %>% dplyr::left_join(sim_flag, by = 'problem') %>% as.nm.table.list() }
/scratch/gouwar.j/cran-all/cranData/xpose/R/list_nm_tables.R
#' Manually define nonmem tables to be imported #' #' @description Manually provide names of the table files to be imported by \code{xpose_data}. #' #' @param tab_names Provide the name of the tables to import e.g. 'sdtab', 'patab', 'cotab', #' 'catab' for NONMEM. #' @param tab_suffix Default is '', but can be changed to any character string to be used as #' suffix in the table names. #' @param sim_suffix Default is 'sim', but can be changed to any character string to be used as #' suffix in the simulation table names e.g. sdtab001sim. #' #' @details #' In order to be imported manually, table names must follow the following convention: #' \code{<tab_names><runno><tab/sim_suffix>} e.g. sdtab001sim. When the argument `file` is used in #' \code{xpose_data}, the \code{<runno>} part is guessed by taking the portion of the string starting #' by any digit and ending at the file extension e.g. \code{file = run001a.mod} will guess <runno> as #' `001a`. If no valid <runno> can be guessed, xpose will return an error. In this case it is advised #' to use the \code{xpose_data} argument `runno` directly rather than `file` hence preventing xpose #' from having to guess <runno>. #' #' Note that with manual table import xpose still reads in the NONMEM model file in order to generate #' the run summary. #' #' @seealso \code{\link{xpose_data}} #' @examples #' \dontrun{ #' # Import all names specified by default as in xpose4 #' xpose_data(runno = '001', manual_import = manual_nm_import()) #' #' # Import a specific table name #' xpose_data(runno = '001', manual_import = manual_nm_import(tab_names = 'mytab')) #' } #' @export manual_nm_import <- function(tab_names = c('sdtab', 'mutab', 'patab', 'catab', 'cotab', 'mytab', 'extra', 'xptab', 'cwtab'), tab_suffix = '', sim_suffix = 'sim') { list(tab_suffix = tab_suffix, sim_suffix = sim_suffix, tab_names = tab_names) } #' Creates an nm_table_list from manually defined table name patterns #' #' @param runno Run number to be used to generate model file name. #' @param file Model file name containing the file extension. #' @param dir Location of the model files. #' @param tab_list A list of table definition generated by `manual_nm_import`. #' #' @return A `nm_table_list` #' #' @keywords internal #' @export list_nm_tables_manual <- function(runno = NULL, file = NULL, dir = NULL, tab_list) { if (is.null(runno)) { # Attempt to guess runno if file has been used runno <- stringr::str_match(string = update_extension(file, ''), pattern = '\\d.+$')[1,] if (is.na(runno)) { stop('Failed to guess `runno` from `file` argument. Check ?manual_nm_import for help.', call. = FALSE) } } file_path(dir, stringr::str_c(tab_list$tab_names, runno)) %>% dplyr::tibble(problem = 1, file = ., firstonly = FALSE, simtab = NA) %>% tidyr::expand(problem = .$problem, file = .$file, firstonly = .$firstonly, simtab = c(FALSE, TRUE)) %>% dplyr::mutate(file = dplyr::if_else(.$simtab, stringr::str_c(.$file, tab_list$sim_suffix), stringr::str_c(.$file, tab_list$tab_suffix))) %>% dplyr::filter(file.exists(.$file)) %>% as.nm.table.list() }
/scratch/gouwar.j/cran-all/cranData/xpose/R/manual_import.R
#' Compartment kinetics #' #' @description Plot of the change in compartment amounts over the independent variable #' #' @inheritParams dv_vs_pred #' @param drop_fixed Should columns that only have a single unique value #' (i.e. fixed) be dropped. #' #' @inheritSection xplot_scatter Layers mapping #' @inheritSection xplot_scatter Faceting #' @inheritSection xplot_scatter Template titles #' @seealso \code{\link{xplot_scatter}} #' @examples #' amt_vs_idv(xpdb_ex_pk, nrow = 2, ncol = 1) #' #' @export amt_vs_idv <- function(xpdb, mapping = NULL, group = 'ID', drop_fixed = TRUE, type = 'l', title = 'Compartments amount vs. @x | @run', subtitle = 'Ofv: @ofv', caption = '@dir', tag = NULL, log = NULL, facets, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (missing(facets)) facets <- add_facet_var(facets = xpdb$xp_theme$facets, variable = 'variable') extra_args <- list(...) if (!any(names(extra_args) == 'nrow')) extra_args$nrow <- 3 if (!any(names(extra_args) == 'ncol')) extra_args$ncol <- 3 amt_col <- xp_var(xpdb, .problem, type = 'a')$col if (drop_fixed) { amt_col <- drop_fixed_cols(xpdb, .problem, cols = amt_col, quiet = quiet) } if (is.null(amt_col)) { stop('No compartment amount column found in the xpdb data index.', call. = FALSE) } do.call('xplot_scatter', c(extra_args, list(xpdb = xpdb, group = group, quiet = quiet, opt = data_opt(.problem = .problem, filter = function(x) { dplyr::select_if(.tbl = x, .predicate = function(x) dplyr::n_distinct(x) > 1) }, tidy = TRUE, value_col = amt_col, post_processing = reorder_factors(prefix = 'Comp. ')), mapping = aes_c(aes(x = .data[[xp_var(xpdb, .problem, type = 'idv')$col]], y = .data[["value"]]), mapping), type = type, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::")))) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/plot_amt.R
#' Distribution plots of ETA and parameters #' #' @description Histograms and density plots of the ETA and parameter values. #' #' @inheritParams dv_vs_pred #' @param type String setting the type of plot to be used. Can be histogram 'h', #' density 'd', rug 'r' or any combination of the three. #' @param guide Should the guide (e.g. reference distribution) be displayed. #' @param drop_fixed Should columns that only have a single unique value #' (i.e. fixed) be dropped. #' #' @inheritSection xplot_distrib Layers mapping #' @inheritSection xplot_scatter Faceting #' @inheritSection xplot_scatter Template titles #' @seealso \code{\link{xplot_distrib}} #' @examples #' # Histogram of parameters #' prm_distrib(xpdb_ex_pk, type = 'h') #' #' # Density plot of etas with a rug #' eta_distrib(xpdb_ex_pk, type = 'dr') #' #' # Histogram of different residuals #' res_distrib(xpdb_ex_pk, type = 'hr', res = c('IWRES', 'CWRES')) #' #' # Density plot of continuous covariates #' cov_distrib(xpdb_ex_pk, type = 'd') #' @name distrib_plot #' @export prm_distrib <- function(xpdb, mapping = NULL, drop_fixed = TRUE, type = 'hr', title = 'Parameter distribution | @run', subtitle = 'Based on @nind individuals', caption = '@dir', tag = NULL, log = NULL, guide = FALSE, facets, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (missing(facets)) facets <- add_facet_var(facets = xpdb$xp_theme$facets, variable = 'variable') prm_col <- xp_var(xpdb, .problem, type = 'param')$col if (drop_fixed) { prm_col <- drop_fixed_cols(xpdb, .problem, cols = prm_col, quiet = quiet) } if (is.null(prm_col)) { stop('No parameter column found in the xpdb data index.', call. = FALSE) } xplot_distrib(xpdb = xpdb, quiet = quiet, opt = data_opt(.problem = .problem, filter = only_distinct(xpdb, .problem, facets, quiet), tidy = TRUE, value_col = prm_col), mapping = aes_c(aes(x = .data[["value"]]), mapping), type = type, guide = guide, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), ...) } #' @rdname distrib_plot #' @export eta_distrib <- function(xpdb, mapping = NULL, drop_fixed = TRUE, type = 'hr', title = 'Eta distribution | @run', subtitle = 'Based on @nind individuals, Eta shrink: @etashk', caption = '@dir', tag = NULL, log = NULL, guide = FALSE, facets, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (missing(facets)) facets <- add_facet_var(facets = xpdb$xp_theme$facets, variable = 'variable') eta_col <- xp_var(xpdb, .problem, type = 'eta')$col if (drop_fixed) { eta_col <- drop_fixed_cols(xpdb, .problem, cols = eta_col, quiet = quiet) } if (is.null(eta_col)) { stop('No eta column found in the xpdb data index.', call. = FALSE) } if (software(xpdb) == 'nonmem') { post_processing_eta <- reorder_factors(prefix = 'ETA(', suffix = ')') } else { post_processing_eta <- NULL } xplot_distrib(xpdb = xpdb, quiet = quiet, opt = data_opt(.problem = .problem, filter = only_distinct(xpdb, .problem, facets, quiet), tidy = TRUE, value_col = eta_col, post_processing = post_processing_eta), mapping = aes_c(aes(x = .data[["value"]]), mapping), type = type, guide = guide, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), ...) } #' @param res Only used for \code{res_distrib}. Defines the type of residual to be used. Default is "CWRES". #' @rdname distrib_plot #' @export res_distrib <- function(xpdb, mapping = NULL, res = 'CWRES', type = 'hr', title = '@x distribution | @run', subtitle = 'Based on @nobs observations', caption = '@dir', tag = NULL, log = NULL, guide = FALSE, facets, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (is.null(xp_var(xpdb, .problem, col = res))) { stop('No ', stringr::str_c(res, collapse = ', '), ' column found in the xpdb data index.', call. = FALSE) } if (length(res) > 1) { if (missing(facets)) facets <- add_facet_var(facets = xpdb$xp_theme$facets, variable = 'variable') opt <- data_opt(.problem = .problem, filter = only_obs(xpdb, .problem, quiet), tidy = TRUE, value_col = res) vars <- aes_c(aes(x = .data[["value"]]), mapping) } else { if (missing(facets)) facets <- xpdb$xp_theme$facets opt <- data_opt(.problem = .problem, filter = only_obs(xpdb, .problem, quiet)) vars <- aes_c(aes(x = .data[[toupper(res)]]), mapping) } xplot_distrib(xpdb = xpdb, quiet = quiet, opt = opt, mapping = vars, type = type, guide = guide, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), ...) } #' @rdname distrib_plot #' @export cov_distrib <- function(xpdb, mapping = NULL, drop_fixed = TRUE, type = 'hr', title = 'Continuous covariates distribution | @run', subtitle = 'Based on @nind individuals', caption = '@dir', tag = NULL, log = NULL, guide = FALSE, facets, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (missing(facets)) facets <- add_facet_var(facets = xpdb$xp_theme$facets, variable = 'variable') cov_col <- xp_var(xpdb, .problem, type = 'contcov')$col if (drop_fixed) { cov_col <- drop_fixed_cols(xpdb, .problem, cols = cov_col, quiet = quiet) } if (is.null(cov_col)) { stop('No continuous covariate column found in the xpdb data index.', call. = FALSE) } xplot_distrib(xpdb = xpdb, quiet = quiet, opt = data_opt(.problem = .problem, filter = only_distinct(xpdb, .problem, facets, quiet), tidy = TRUE, value_col = cov_col), mapping = aes_c(aes(x = .data[["value"]]), mapping), type = type, guide = guide, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), ...) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/plot_distribution.R
#' Observations plotted against model predictions #' #' @description Plot of observations (DV) vs population predictions (PRED), #' individual predictions (IPRED) or conditional population predictions (CPRED). #' #' @param xpdb An xpose database object. #' @param mapping List of aesthetics mappings to be used for the xpose plot #' (e.g. \code{point_color}). #' @param group Grouping variable to be used for lines. #' @param type String setting the type of plot to be used. Can be points 'p', #' line 'l', smooth 's' and text 't' or any combination of the four. #' @param title Plot title. Use \code{NULL} to remove. #' @param subtitle Plot subtitle. Use \code{NULL} to remove. #' @param caption Page caption. Use \code{NULL} to remove. #' @param tag Plot identification tag. Use \code{NULL} to remove. #' @param log String assigning logarithmic scale to axes, can be either '', #' 'x', y' or 'xy'. #' @param guide Enable guide display (e.g. unity line). #' @param facets Either a character string to use \code{\link[ggforce]{facet_wrap_paginate}} #' or a formula to use \code{\link[ggforce]{facet_grid_paginate}}. #' @param .problem The $problem number to be used. By default returns #' the last estimation problem. #' @param quiet Logical, if \code{FALSE} messages are printed to the console. #' @param ... Any additional aesthetics to be passed on \code{xplot_scatter}. #' #' @inheritSection xplot_scatter Layers mapping #' @inheritSection xplot_scatter Faceting #' @inheritSection xplot_scatter Template titles #' @seealso \code{\link{xplot_scatter}} #' @examples #' dv_vs_pred(xpdb_ex_pk) #' #' dv_vs_ipred(xpdb_ex_pk) #' #' @name dv_vs_pred #' @export dv_vs_ipred <- function(xpdb, mapping = NULL, group = 'ID', type = 'pls', title = '@y vs. @x | @run', subtitle = 'Ofv: @ofv, Eps shrink: @epsshk', caption = '@dir', tag = NULL, log = NULL, guide = TRUE, facets, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (missing(facets)) facets <- xpdb$xp_theme$facets xplot_scatter(xpdb = xpdb, group = group, quiet = quiet, opt = data_opt(.problem = .problem, filter = only_obs(xpdb, .problem, quiet)), mapping = aes_c(aes(x = .data[[xp_var(xpdb, .problem, type = 'ipred')$col]], y = .data[[xp_var(xpdb, .problem, type = 'dv')$col]]), mapping), type = type, guide = guide, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), guide_slope = 1, ...) } #' @rdname dv_vs_pred #' @export dv_vs_pred <- function(xpdb, mapping = NULL, group = 'ID', type = 'pls', title = '@y vs. @x | @run', subtitle = 'Ofv: @ofv', caption = '@dir', tag = NULL, log = NULL, guide = TRUE, facets, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (missing(facets)) facets <- xpdb$xp_theme$facets xplot_scatter(xpdb = xpdb, group = group, quiet = quiet, opt = data_opt(.problem = .problem, filter = only_obs(xpdb, .problem, quiet)), mapping = aes_c(aes(x = .data[[xp_var(xpdb, .problem, type = 'pred')$col]], y = .data[[xp_var(xpdb, .problem, type = 'dv')$col]]), mapping), type = type, guide = guide, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), guide_slope = 1, ...) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/plot_gof.R
#' Observations, individual predictions and population predictions plotted against #' the independent variable for every individual #' #' @description Observations (DV), individual predictions (IPRED) and population predictions #' (PRED) plotted against the independent variable for every individual #' #' @inheritParams dv_vs_pred #' @param color Changes the **lines, points and text** color. Should be a vector of 3 values #' (i.e. DV, IPRED, PRED). This \code{color} argument is a special case in xpose as it applies #' to three different layers (\code{geom_line}, \code{geom_point} and \code{geom_text}). This #' special case is due to the fact that in ggplot2 it is not possible to have two different #' color scales for different layers. #' @param point_alpha Points alpha, should be a vector of 3 values (i.e. DV, IPRED, PRED). #' @param line_linetype Lines linetype, should be a vector of 3 values (i.e. DV, IPRED, PRED). #' @inheritSection xplot_scatter Layers mapping #' @inheritSection xplot_scatter Faceting #' @inheritSection xplot_scatter Template titles #' @seealso \code{\link{xplot_scatter}} #' @examples #' \dontrun{ #' # Basic example #' ind_plots(xpdb_ex_pk, page = 1, #' ncol = 2, nrow = 2) #' } #' @export ind_plots <- function(xpdb, mapping = NULL, group = 'variable', type = 'lp', title = 'Individual plots | @run', subtitle = 'Ofv: @ofv, Eps shrink: @epsshk', caption = '@dir | Page @page of @lastpage', tag = NULL, log = NULL, facets, .problem, quiet, color = c('grey60', 'deepskyblue4', 'deepskyblue3'), point_alpha = c(0.8, 0, 0), line_linetype = c('blank', 'solid', '55'), ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (missing(facets)) facets <- add_facet_var(facets = xpdb$xp_theme$facets, variable = xp_var(xpdb, .problem, type = 'id')$col) extra_args <- list(...) if (!any(names(extra_args) == 'nrow')) extra_args$nrow <- 3 if (!any(names(extra_args) == 'ncol')) extra_args$ncol <- 3 if (any(names(extra_args) %in% c('line_color', 'point_color', 'text_color'))) { warning('In ind_plots the argument `color` should be used instead of `line/point/text_color`.', call. = FALSE) } variable_names <- xp_var(xpdb, .problem, type = c('dv', 'pred', 'ipred'))$col do.call('xplot_scatter', c(extra_args, list(xpdb = xpdb, group = group, quiet = quiet, opt = data_opt(.problem = .problem, tidy = TRUE, filter = only_obs(xpdb, .problem, quiet), value_col = variable_names, post_processing = function(x) { dplyr::mutate(.data = x, variable = factor(x$variable, levels = variable_names)) }), mapping = aes_c(aes( x = .data[[xp_var(xpdb, .problem, type = 'idv')$col]], y = .data[["value"]], line_color = .data[["variable"]], text_color = .data[["variable"]], line_linetype = .data[["variable"]], point_color = .data[["variable"]], point_alpha = .data[["variable"]]), mapping), type = type, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::")))) + scale_alpha_manual(values = point_alpha) + scale_color_manual(values = color) + scale_linetype_manual(values = line_linetype) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/plot_individuals.R
#' Parameter value or gradient vs. iterations #' #' @description Change of parameter value or gradient vs. iterations. #' #' @inheritParams dv_vs_pred #' @param .subprob The sub-problem number to be used. By default returns #' the last sub-problem associated with the selected problem. #' @param .method The estimation method to be used, by default returns the last one for each file #' #' @inheritSection xplot_scatter Layers mapping #' @inheritSection xplot_scatter Faceting #' @inheritSection xplot_scatter Template titles #' @seealso \code{\link{xplot_scatter}} #' @examples #' prm_vs_iteration(xpdb_ex_pk) #' #' grd_vs_iteration(xpdb_ex_pk) #' #' @name minimization_plots #' @export prm_vs_iteration <- function(xpdb, mapping = NULL, group = 'variable', type = 'l', title = 'Parameter @y vs. @x | @run', subtitle = 'Method: @method, minimization time: @runtime\nTermination message: @term', caption = '@dir', tag = NULL, log = NULL, guide = FALSE, facets, .problem, .subprob, .method, quiet, ...) { # Check input check_xpdb(xpdb, check = 'files') if (missing(.problem)) .problem <- last_file_problem(xpdb, 'ext') if (missing(.subprob)) .subprob <- last_file_subprob(xpdb, 'ext', .problem) if (missing(.method)) .method <- last_file_method(xpdb, ext = 'ext', .problem = .problem, .subprob = .subprob) check_problem(.problem, .subprob, .method) if (missing(quiet)) quiet <- xpdb$options$quiet if (missing(facets)) facets <- 'variable' x_var <- 'ITERATION' msg(c('Parameters non-varying across ', x_var, ' not shown.'), quiet) xplot_scatter(xpdb = xpdb, group = group, quiet = quiet, opt = data_opt(.problem = .problem, .subprob = .subprob, .method = .method, .source = 'ext', filter = function(x) { x <- x %>% dplyr::filter(!!rlang::sym(x_var) >= 0) %>% dplyr::select_if(.predicate = function(x) dplyr::n_distinct(x) > 1) if (ncol(x[, colnames(x) != x_var]) == 0) { stop('No parameters varying across ', x_var, ' were found.', call. = FALSE) } x }, tidy = TRUE, index_col = x_var, post_processing = reorder_factors(prefix = NA)), mapping = aes_c(aes(x = .data[[x_var]], y = .data[["value"]]), mapping), type = type, guide = guide, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), scales = 'free_y', ...) } #' @rdname minimization_plots #' @export grd_vs_iteration <- function(xpdb, mapping = NULL, group = 'variable', type = 'l', title = 'Gradient @y vs. @x | @run', subtitle = 'Method: @method, minimization time: @runtime\nTermination message: @term', caption = '@dir', tag = NULL, log = NULL, guide = FALSE, facets, .problem, .subprob, .method, quiet, ...) { # Check input check_xpdb(xpdb, check = 'files') if (missing(.problem)) .problem <- last_file_problem(xpdb, 'grd') if (missing(.subprob)) .subprob <- last_file_subprob(xpdb, 'grd', .problem) if (missing(.method)) .method <- last_file_method(xpdb, ext = 'grd', .problem = .problem, .subprob = .subprob) check_problem(.problem, .subprob, .method) if (missing(quiet)) quiet <- xpdb$options$quiet if (missing(facets)) facets <- 'variable' x_var <- 'ITERATION' msg(c('Parameters non-varying across ', x_var, ' not shown.'), quiet) xplot_scatter(xpdb = xpdb, group = group, quiet = quiet, opt = data_opt(.problem = .problem, .subprob = .subprob, .method = .method, .source = 'grd', filter = function(x) { x <- x %>% dplyr::filter(!!rlang::sym(x_var) >= 0) %>% dplyr::select_if(.predicate = function(x) dplyr::n_distinct(x) > 1) if (ncol(x[, colnames(x) != x_var]) == 0) { stop('No parameters varying across ', x_var, ' were found.', call. = FALSE) } x }, tidy = TRUE, index_col = x_var, post_processing = reorder_factors(prefix = 'GRD(', suffix = ')')), mapping = aes_c(aes(x = .data[[x_var]], y = .data[["value"]]), mapping), type = type, guide = guide, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), scales = 'free_y', ...) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/plot_minimization.R
#' QQ plots of ETA and residuals #' #' @description QQ plots of the ETA and model residuals. #' #' @inheritParams dv_vs_pred #' @param type String setting the type of plot. Can only be points 'p'. #' @param guide Should the guide (e.g. reference line) be displayed. #' @param drop_fixed Should columns that only have a single unique value #' (i.e. fixed) be dropped. #' #' @inheritSection xplot_qq Layers mapping #' @inheritSection xplot_scatter Faceting #' @inheritSection xplot_scatter Template titles #' @seealso \code{\link{xplot_distrib}} #' @examples #' # QQ plot of parameters #' prm_qq(xpdb_ex_pk) #' #' # QQ plot of eta #' eta_qq(xpdb_ex_pk) #' #' # QQ plot of residuals #' res_qq(xpdb_ex_pk, res = c('IWRES', 'CWRES')) #' #' # QQ plot of continuous covariates #' cov_qq(xpdb_ex_pk) #' #' @name qq_plot #' @export prm_qq <- function(xpdb, mapping = NULL, drop_fixed = TRUE, type = 'p', title = 'QQ plot of parameters | @run', subtitle = 'Based on @nind individuals', caption = '@dir', tag = NULL, log = NULL, guide = TRUE, facets, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (missing(facets)) facets <- add_facet_var(facets = xpdb$xp_theme$facets, variable = 'variable') prm_col <- xp_var(xpdb, .problem, type = 'param')$col if (drop_fixed) { prm_col <- drop_fixed_cols(xpdb, .problem, cols = prm_col, quiet = quiet) } if (is.null(prm_col)) { stop('No parameter column found in the xpdb data index.', call. = FALSE) } xplot_qq(xpdb = xpdb, quiet = quiet, opt = data_opt(.problem = .problem, filter = only_distinct(xpdb, .problem, facets, quiet), tidy = TRUE, value_col = prm_col), mapping = aes_c(aes(sample = .data[["value"]]), mapping), type = type, guide = guide, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), xscale_name = 'Quantiles of normal', yscale_name = 'Quantiles of parameter', ...) } #' @rdname qq_plot #' @export eta_qq <- function(xpdb, mapping = NULL, drop_fixed = TRUE, type = 'p', title = 'QQ plot of etas | @run', subtitle = 'Based on @nind individuals, Eta shrink: @etashk', caption = '@dir', tag = NULL, log = NULL, guide = TRUE, facets, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (missing(facets)) facets <- add_facet_var(facets = xpdb$xp_theme$facets, variable = 'variable') eta_col <- xp_var(xpdb, .problem, type = 'eta')$col if (drop_fixed) { eta_col <- drop_fixed_cols(xpdb, .problem, cols = eta_col, quiet = quiet) } if (is.null(eta_col)) { stop('No eta column found in the xpdb data index.', call. = FALSE) } if (software(xpdb) == 'nonmem') { post_processing_eta <- reorder_factors(prefix = 'ETA(', suffix = ')') } else { post_processing_eta <- NULL } xplot_qq(xpdb = xpdb, quiet = quiet, opt = data_opt(.problem = .problem, filter = only_distinct(xpdb, .problem, facets, quiet), tidy = TRUE, value_col = eta_col, post_processing = post_processing_eta), mapping = aes_c(aes(sample = .data[["value"]]), mapping), type = type, guide = guide, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), xscale_name = 'Quantiles of normal', yscale_name = 'Quantiles of eta', ...) } #' @param res Only used for \code{res_qq}. Defines the type of residual to be used. Default is "CWRES". #' @rdname qq_plot #' @export res_qq <- function(xpdb, mapping = NULL, res = 'CWRES', type = 'p', title = 'QQ plot of @sample | @run', subtitle = 'Based on @nobs observations', caption = '@dir', tag = NULL, log = NULL, guide = TRUE, facets, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (is.null(xp_var(xpdb, .problem, col = res))) { stop('No ', stringr::str_c(res, collapse = ', '), ' column found in the xpdb data index.', call. = FALSE) } if (length(res) > 1) { if (missing(facets)) facets <- add_facet_var(facets = xpdb$xp_theme$facets, variable = 'variable') opt <- data_opt(.problem = .problem, filter = only_obs(xpdb, .problem, quiet), tidy = TRUE, value_col = res) vars <- aes_c(aes(sample = .data[["value"]]), mapping) } else { if (missing(facets)) facets <- xpdb$xp_theme$facets opt <- data_opt(.problem = .problem, filter = only_obs(xpdb, .problem, quiet)) vars <- aes_c(aes(sample = .data[[toupper(res)]]), mapping) } xplot_qq(xpdb = xpdb, quiet = quiet, opt = opt, mapping = vars, type = type, guide = guide, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), ...) + labs(x = 'Quantiles of normal', y = 'Quantiles of @sample') } #' @name qq_plot #' @export cov_qq <- function(xpdb, mapping = NULL, drop_fixed = TRUE, type = 'p', title = 'QQ plot of continuous covariates | @run', subtitle = 'Based on @nind individuals', caption = '@dir', tag = NULL, log = NULL, guide = TRUE, facets, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (missing(facets)) facets <- add_facet_var(facets = xpdb$xp_theme$facets, variable = 'variable') cov_col <- xp_var(xpdb, .problem, type = 'contcov')$col if (drop_fixed) { cov_col <- drop_fixed_cols(xpdb, .problem, cols = cov_col, quiet = quiet) } if (is.null(cov_col)) { stop('No continuous covariate column found in the xpdb data index.', call. = FALSE) } xplot_qq(xpdb = xpdb, quiet = quiet, opt = data_opt(.problem = .problem, filter = only_distinct(xpdb, .problem, facets, quiet), tidy = TRUE, value_col = cov_col), mapping = aes_c(aes(sample = .data[["value"]]), mapping), type = type, guide = guide, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), xscale_name = 'Quantiles of normal', yscale_name = 'Quantiles of covariate', ...) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/plot_qq.R
#' Residuals plotted against population predictions #' #' @description Model residuals plotted against population predictions (PRED). #' #' The residuals can be one of: #' \itemize{ #' \item RES: model residuals #' \item WRES: weighted model residuals #' \item CWRES: conditional weighted model residuals #' \item EWRES/ECWRES: Monte Carlo based model residuals #' \item NPDE: Normalized prediction distribution error #' } #' #' @inheritParams dv_vs_pred #' @param res Type of residual to be used. Default is "CWRES". #' @inheritSection xplot_scatter Layers mapping #' @inheritSection xplot_scatter Faceting #' @inheritSection xplot_scatter Template titles #' @seealso \code{\link{xplot_scatter}} #' @examples #' # Standard residual #' res_vs_pred(xpdb_ex_pk, res = c('IWRES', 'CWRES')) #' #' # Absolute value of the residuals #' absval_res_vs_pred(xpdb_ex_pk, res = 'CWRES') #' #' @export res_vs_pred <- function(xpdb, mapping = NULL, res = 'CWRES', group = 'ID', type = 'pls', title = '@y vs. @x | @run', subtitle = 'Ofv: @ofv', caption = '@dir', tag = NULL, log = NULL, guide = TRUE, facets, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (length(res) > 1) { if (missing(facets)) facets <- add_facet_var(facets = xpdb$xp_theme$facets, variable = 'variable') opt <- data_opt(.problem = .problem, filter = only_obs(xpdb, .problem, quiet), tidy = TRUE, value_col = res) vars <- aes_c(aes( x = .data[[xp_var(xpdb, .problem, type = 'pred')$col]], y = .data[["value"]]), mapping) } else { if (missing(facets)) facets <- xpdb$xp_theme$facets opt <- data_opt(.problem = .problem, filter = only_obs(xpdb, .problem, quiet)) vars <- aes_c(aes( x = .data[[xp_var(xpdb, .problem, type = 'pred')$col]], y = .data[[toupper(res)]]), mapping) } xplot_scatter(xpdb = xpdb, group = group, quiet = quiet, opt = opt, mapping = vars, type = type, guide = guide, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), guide_slope = 0, ...) } #' @rdname res_vs_pred #' @export absval_res_vs_pred <- function(xpdb, mapping = NULL, res = 'CWRES', group = 'ID', type = 'pls', title = '@y vs. @x | @run', subtitle = 'Ofv: @ofv', caption = '@dir', tag = NULL, log = NULL, guide = FALSE, facets, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (length(res) > 1) { if (missing(facets)) facets <- add_facet_var(facets = xpdb$xp_theme$facets, variable = 'variable') opt <- data_opt(.problem = .problem, filter = only_obs(xpdb, .problem, quiet), tidy = TRUE, value_col = res) vars <- aes_c(aes(x = .data[[xp_var(xpdb, .problem, type = 'pred')$col]], y = abs(.data[["value"]])), mapping) } else { if (missing(facets)) facets <- xpdb$xp_theme$facets opt <- data_opt(.problem = .problem, filter = only_obs(xpdb, .problem, quiet)) vars <- aes_c(aes(x = .data[[xp_var(xpdb, .problem, type = 'pred')$col]], y = abs(.data[[toupper(res)]])), mapping) } xplot_scatter(xpdb = xpdb, group = group, quiet = quiet, opt = opt, mapping = vars, type = type, guide = guide, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), guide_slope = 0, ...) } #' Residuals plotted against the independent variable #' #' @description Model residuals plotted against the independent variable (IDV). #' #' The residuals can be one of: #' \itemize{ #' \item RES: model residuals #' \item WRES: weighted model residuals #' \item CWRES: conditional weighted model residuals #' \item EWRES/ECWRES: Monte Carlo based model residuals #' \item NPDE: Normalized prediction distribution error #' } #' #' @inheritParams dv_vs_pred #' @param res Type of residual to be used. Default is "CWRES". #' @inheritSection xplot_scatter Layers mapping #' @inheritSection xplot_scatter Template titles #' @seealso \code{\link{xplot_scatter}} #' @examples #' # Standard residual #' res_vs_idv(xpdb_ex_pk, res = c('IWRES', 'CWRES')) #' #' # Absolute value of the residuals #' absval_res_vs_idv(xpdb_ex_pk, res = 'CWRES') #' #' @export res_vs_idv <- function(xpdb, mapping = NULL, res = 'CWRES', group = 'ID', type = 'pls', title = '@y vs. @x | @run', subtitle = 'Ofv: @ofv', caption = '@dir', tag = NULL, log = NULL, guide = TRUE, facets, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (length(res) > 1) { if (missing(facets)) facets <- add_facet_var(facets = xpdb$xp_theme$facets, variable = 'variable') opt <- data_opt(.problem = .problem, filter = only_obs(xpdb, .problem, quiet), tidy = TRUE, value_col = res) vars <- aes_c(aes(x = .data[[xp_var(xpdb, .problem, type = 'idv')$col]], y = .data[["value"]]), mapping) } else { if (missing(facets)) facets <- xpdb$xp_theme$facets opt <- data_opt(.problem = .problem, filter = only_obs(xpdb, .problem, quiet)) vars <- aes_c(aes(x = .data[[xp_var(xpdb, .problem, type = 'idv')$col]], y = .data[[toupper(res)]]), mapping) } xplot_scatter(xpdb = xpdb, group = group, quiet = quiet, opt = opt, mapping = vars, type = type, guide = guide, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), guide_slope = 0, ...) } #' @rdname res_vs_idv #' @export absval_res_vs_idv <- function(xpdb, mapping = NULL, res = 'CWRES', group = 'ID', type = 'pls', title = '@y vs. @x | @run', subtitle = 'Ofv: @ofv', caption = '@dir', tag = NULL, log = NULL, guide = FALSE, facets, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (length(res) > 1) { if (missing(facets)) facets <- add_facet_var(facets = xpdb$xp_theme$facets, variable = 'variable') opt <- data_opt(.problem = .problem, filter = only_obs(xpdb, .problem, quiet), tidy = TRUE, value_col = res) vars <- aes_c(aes(x = .data[[xp_var(xpdb, .problem, type = 'idv')$col]], y = abs(.data[["value"]])), mapping) } else { if (missing(facets)) facets <- xpdb$xp_theme$facets opt <- data_opt(.problem = .problem, filter = only_obs(xpdb, .problem, quiet)) vars <- aes_c(aes(x = .data[[xp_var(xpdb, .problem, type = 'idv')$col]], y = abs(.data[[toupper(res)]])), mapping) } xplot_scatter(xpdb = xpdb, group = group, quiet = quiet, opt = opt, mapping = vars, type = type, guide = guide, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), guide_slope = 0, ...) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/plot_residuals.R
#' Observations and model predictions plotted against the independent variable #' #' @description Plot of observations (DV), individual model predictions (IPRED) #' and/or population predictions (PRED) plotted against the independent variable (IDV). #' #' @inheritParams dv_vs_pred #' @inheritSection xplot_scatter Layers mapping #' @inheritSection xplot_scatter Faceting #' @inheritSection xplot_scatter Template titles #' @seealso \code{\link{xplot_scatter}} #' @examples #' dv_vs_idv(xpdb_ex_pk) #' #' ipred_vs_idv(xpdb_ex_pk) #' #' pred_vs_idv(xpdb_ex_pk) #' #' dv_preds_vs_idv(xpdb_ex_pk) #' #' @name pred_vs_idv #' @export dv_vs_idv <- function(xpdb, mapping = NULL, group = 'ID', type = 'pls', title = '@y vs. @x | @run', subtitle = 'Ofv: @ofv', caption = '@dir', tag = NULL, log = NULL, facets, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (missing(facets)) facets <- xpdb$xp_theme$facets xplot_scatter(xpdb = xpdb, group = group, quiet = quiet, opt = data_opt(.problem = .problem, filter = only_obs(xpdb, .problem, quiet)), mapping = aes_c(aes(x = .data[[xp_var(xpdb, .problem, type = 'idv')$col]], y = .data[[xp_var(xpdb, .problem, type = 'dv')$col]]), mapping), type = type, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), ...) } #' @name pred_vs_idv #' @export ipred_vs_idv <- function(xpdb, mapping = NULL, group = 'ID', type = 'pls', facets, title = '@y vs. @x | @run', subtitle = 'Ofv: @ofv, Eps shrink: @epsshk', caption = '@dir', tag = NULL, log = NULL, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (missing(facets)) facets <- xpdb$xp_theme$facets xplot_scatter(xpdb = xpdb, group = group, quiet = quiet, opt = data_opt(.problem = .problem, filter = only_obs(xpdb, .problem, quiet)), mapping = aes_c(aes(x = .data[[xp_var(xpdb, .problem, type = 'idv')$col]], y = .data[[xp_var(xpdb, .problem, type = 'ipred')$col]]), mapping), type = type, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), ...) } #' @name pred_vs_idv #' @export pred_vs_idv <- function(xpdb, mapping = NULL, group = 'ID', type = 'pls', facets, title = '@y vs. @x | @run', subtitle = 'Ofv: @ofv', caption = '@dir', tag = NULL, log = NULL, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (missing(facets)) facets <- xpdb$xp_theme$facets xplot_scatter(xpdb = xpdb, group = group, quiet = quiet, opt = data_opt(.problem = .problem, filter = only_obs(xpdb, .problem, quiet)), mapping = aes_c(aes(x = .data[[xp_var(xpdb, .problem, type = 'idv')$col]], y = .data[[xp_var(xpdb, .problem, type = 'pred')$col]]), mapping), type = type, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), ...) } #' Observations, individual model predictions and model prediction #' plotted against the independent variable #' #' @rdname pred_vs_idv #' @export dv_preds_vs_idv <- function(xpdb, mapping = NULL, group = 'ID', type = 'pls', facets, title = 'Observations, Individual and Population Predictions vs. @x | @run', subtitle = 'Ofv: @ofv, Eps shrink: @epsshk', caption = '@dir', tag = NULL, log = NULL, .problem, quiet, ...) { # Check input check_xpdb(xpdb, check = 'data') if (missing(.problem)) .problem <- default_plot_problem(xpdb) check_problem(.problem, .subprob = NULL, .method = NULL) if (missing(quiet)) quiet <- xpdb$options$quiet if (missing(facets)) facets <- add_facet_var(facets = xpdb$xp_theme$facets, variable = 'variable') xplot_scatter(xpdb = xpdb, group = group, quiet = quiet, opt = data_opt(.problem = .problem, tidy = TRUE, filter = only_obs(xpdb, .problem, quiet), value_col = xp_var(xpdb, .problem, type = c('dv', 'pred', 'ipred'))$col), mapping = aes_c(aes(x = .data[[xp_var(xpdb, .problem, type = 'idv')$col]], y = .data[["value"]]), mapping), type = type, guide = FALSE, facets = facets, xscale = check_scales('x', log), yscale = check_scales('y', log), title = title, subtitle = subtitle, caption = caption, tag = tag, plot_name = stringr::str_remove(deparse(match.call()[[1]]), "(\\w+\\.*)+::"), ...) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/plot_spaghetti.R
#' Visual predictive checks #' #' @description Generate visual predictive checks (VPC) #' #' @param xpdb An xpose database object. #' @param vpc_type Only used when multiple vpc data are present in the same xpdb. The type of #' vpc to be created. Can be one of can be one of: 'continuous', 'categorical', #' 'censored' or 'time-to-event'. #' @param smooth Should the bins be smoothed (connect bin midpoints, default) or shown as rectangular boxes. #' @param mapping List of aesthetics mappings to be used for the xpose plot #' (e.g. \code{point_color}). #' @param type String setting the type of plot to be used. Can be points 'p', #' line 'l', area 'a', rug 'r' and text 't' or any combination of the five. #' @param facets Either a character string to use \link[ggplot2]{facet_wrap} #' or a formula to use \link[ggplot2]{facet_grid}. #' @param title Plot title. Use \code{NULL} to remove. #' @param subtitle Plot subtitle. Use \code{NULL} to remove. #' @param caption Page caption. Use \code{NULL} to remove. #' @param tag Plot identification tag. Use \code{NULL} to remove. #' @param log String assigning logarithmic scale to axes, can be either '', #' 'x', y' or 'xy'. #' @param guide Enable guide display in vpc continuous (e.g. lloq and uloq lines). #' @param area_fill Shaded areas filling color, should be a vector of 3 values (i.e. low, med, high). #' @param line_linetype Lines linetype, should be a vector of 3 values (i.e. low, med, high). #' @param quiet Logical, if \code{FALSE} messages are printed to the console. #' @param ... any additional aesthetics. #' #' @inheritParams update_themes #' #' @section Layers mapping: #' Plots can be customized by mapping arguments to specific layers. The naming convention is #' layer_option where layer is one of the names defined in the list below and option is #' any option supported by this layer e.g. point_color = 'blue', area_fill = 'green', etc. #' \itemize{ #' \item point: options to \code{geom_point} #' \item line: options to \code{geom_line} #' \item area: options to \code{geom_ribbon} (smooth = TRUE) or \code{geom_rect} (smooth = FALSE) #' \item rug: options to \code{geom_rug} #' \item text: options to \code{geom_text} #' \item guide: options to \code{geom_hline} #' \item xscale: options to \code{scale_x_continuous} or \code{scale_x_log10} #' \item yscale: options to \code{scale_y_continuous} or \code{scale_y_log10} #' } #' @inheritSection xplot_scatter Faceting #' @inheritSection xplot_scatter Template titles #' @seealso \code{\link{vpc_data}} #' @examples #' xpdb_ex_pk %>% #' vpc_data(opt = vpc_opt(n_bins = 7)) %>% #' vpc() #' @export vpc <- function(xpdb, vpc_type = NULL, mapping = NULL, smooth = TRUE, type = 'alpr', title = 'Visual predictive checks | @run', subtitle = 'Number of simulations: @vpcnsim, confidence interval: @vpcci%', caption = '@vpcdir', tag = NULL, log = NULL, guide = TRUE, gg_theme, xp_theme, facets, quiet, area_fill = c('steelblue3', 'grey60', 'steelblue3'), line_linetype = c('93', 'solid', '93'), ...) { # Check input check_xpdb(xpdb, check = 'special') if (missing(quiet)) quiet <- xpdb$options$quiet # Fetch data if (!any(xpdb$special$method == 'vpc')) { stop('No VPC data available. Please refer to the function `vpc_data()` function.', call. = FALSE) } else if (sum(xpdb$special$method == 'vpc') > 1) { if (is.null(vpc_type)) { stop('Several VPC data are associated with this xpdb. Please use the argument `vpc_type`.', call. = FALSE) } else { vpc_type <- match.arg(vpc_type, choices = c('continuous', 'categorical', 'censored', 'time-to-event')) if (!vpc_type %in% xpdb$special[xpdb$special$method == 'vpc', ]$type) { stop(c('No data are available for ', vpc_type, ' VPC. Change `vpc_type` to one of: ', stringr::str_c(xpdb$special[xpdb$special$method == 'vpc', ]$type, collapse = ', '), '.'), call. = FALSE) } vpc_dat <- xpdb$special[xpdb$special$method == 'vpc' & xpdb$special$type == vpc_type, ] } } else { if (!is.null(vpc_type) && !stringr::str_detect(xpdb$special$type, vpc_type)) { stop(c('No data are available for ', vpc_type, ' VPC. Change `vpc_type` to ', xpdb$special[xpdb$special$method == 'vpc', ]$type, '.'), call. = FALSE) } vpc_dat <- xpdb$special[xpdb$special$method == 'vpc', ] vpc_type <- vpc_dat$type } vpc_prob <- vpc_dat$problem vpc_dat <- vpc_dat$data[[1]] # Check that all faceting variable are present vpc_dat if (missing(facets)) facets <- vpc_dat$facets if (is.formula(facets)) { stratify <- all.vars(facets) } else { stratify <- facets } if (!all(stratify %in% colnames(vpc_dat$vpc_dat) & stratify %in% colnames(vpc_dat$aggr_obs))) { unique(c(stratify[!stratify %in% colnames(vpc_dat$vpc_dat)], stratify[!stratify %in% colnames(vpc_dat$aggr_obs)])) %>% stringr::str_c(collapse = ', ') %>% {stop('Faceting variable: ', ., ' not found. Use `stratify` to add a stratification variable in vpc_data().', call. = FALSE)} } # Check type check_plot_type(type, allowed = c('a', 'l', 'p', 'r', 't')) # Assign xp_theme if (!missing(xp_theme)) xpdb <- update_themes(xpdb = xpdb, xp_theme = xp_theme) # Assign gg_theme if (missing(gg_theme)) { gg_theme <- xpdb$gg_theme } else { gg_theme <- update_themes(xpdb = xpdb, gg_theme = gg_theme)$gg_theme } if (is.function(gg_theme)) { gg_theme <- do.call(gg_theme, args = list()) } # Create ggplot base if (is.null(mapping)) mapping <- aes() xp <- ggplot(data = NULL, mapping) + gg_theme # Add shadded areas if (stringr::str_detect(type, stringr::fixed('a', ignore_case = TRUE))) { if (smooth) { xp <- xp + xp_geoms(mapping = aes_c(aes(area_x = .data[["bin_mid"]], area_ymin = .data[["low"]], area_ymax = .data[["up"]], area_group = .data[["group"]], area_fill = .data[["Simulations"]]), mapping), xp_theme = xpdb$xp_theme, name = 'area', ggfun = 'geom_ribbon', area_data = vpc_dat$vpc_dat, ...) } else { if (vpc_dat$psn_bins) { warning('Using `smooth = FALSE` along with `psn_bins = TRUE` may yield to misaligned obs and sim data.', ' Check the output carefully or use `vpc_data(psn_bins = FALSE)`', call. = FALSE) } xp <- xp + xp_geoms(mapping = aes_c(aes(area_xmin = .data[["bin_min"]], area_xmax = .data[["bin_max"]], area_ymin = .data[["low"]], area_ymax = .data[["up"]], area_group = .data[["group"]], area_fill = .data[["Simulations"]]), mapping), xp_theme = xpdb$xp_theme, name = 'area', ggfun = 'geom_rect', area_data = vpc_dat$vpc_dat, ...) } } # Add lines if (stringr::str_detect(type, stringr::fixed('l', ignore_case = TRUE))) { xp <- xp + xp_geoms(mapping = aes_c(aes(line_x = .data[["bin_mid"]], line_y = .data[["value"]], line_group = .data[["group"]], line_linetype = .data[["Observations"]]), mapping), xp_theme = xpdb$xp_theme, name = 'line', ggfun = 'geom_line', line_data = vpc_dat$aggr_obs, ...) } # Add points if (stringr::str_detect(type, stringr::fixed('p', ignore_case = TRUE))) { if (vpc_dat$type == 'continuous') { xp <- xp + xp_geoms(mapping = aes_c(aes(point_x = .data[["idv"]], point_y = .data[["dv"]]), mapping), xp_theme = xpdb$xp_theme, name = 'point', ggfun = 'geom_point', point_data = vpc_dat$obs, ...) } else { warning('Points (type = \'p\') can only be added with continuous VPC.', call. = FALSE) } } # Add text if (stringr::str_detect(type, stringr::fixed('t', ignore_case = TRUE))) { if (vpc_dat$type == 'continuous') { xp <- xp + xp_geoms(mapping = aes_c(aes(text_x = .data[["idv"]], text_y = .data[["dv"]], text_label = .data[["id"]]), mapping), xp_theme = xpdb$xp_theme, name = 'text', ggfun = 'geom_text', text_data = vpc_dat$obs, ...) } else { warning('Text (type = \'t\') can only be added with continuous VPC.', call. = FALSE) } } # Add guides if (guide && vpc_type == 'continuous' && (!is.null(vpc_dat$lloq) | !is.null(vpc_dat$uloq))) { xp <- xp + xp_geoms(xp_theme = xpdb$xp_theme, name = 'guide', ggfun = 'geom_hline', guide_yintercept = purrr::flatten_dbl(vpc_dat[c('lloq','uloq')]), ...) } # Define scales xp <- xp + labs(x = vpc_dat$obs_cols[['idv']], y = vpc_dat$obs_cols[['dv']]) + xp_geoms(mapping = mapping, xp_theme = xpdb$xp_theme, name = 'xscale', ggfun = stringr::str_c('scale_x_', check_scales('x', log)), ...) + xp_geoms(mapping = mapping, xp_theme = xpdb$xp_theme, name = 'yscale', ggfun = stringr::str_c('scale_y_', check_scales('y', log)), ...) # Add rug if (stringr::str_detect(type, stringr::fixed('r', ignore_case = TRUE))) { extra_arg <- list(...) if (!'rug_sides' %in% names(extra_arg)) extra_arg$rug_sides <- 't' xp <- xp + do.call('xp_geoms', c(extra_arg, list(mapping = aes_c(aes(rug_x = .data[["idv"]]), mapping), xp_theme = xpdb$xp_theme, name = 'rug', ggfun = 'geom_rug', rug_data = vpc_dat$aggr_obs %>% dplyr::distinct(!!!rlang::syms(c('bin', stratify)), .keep_all = TRUE) %>% dplyr::filter(!is.na(.$bin)) %>% tidyr::gather(key = 'edges', value = 'idv', dplyr::one_of('bin_min', 'bin_max')) %>% dplyr::distinct(!!!rlang::syms(c(stratify, 'idv')), .keep_all = TRUE)) )) } # Define panels if (!is.null(facets)) { xp <- xp + xpose_panels(xp_theme = xpdb$xp_theme, extra_args = c(list(facets = facets), list(...))) } # Add labels xp <- xp + labs(title = title, subtitle = subtitle, caption = caption) if (utils::packageVersion('ggplot2') >= '3.0.0') { xp <- xp + labs(tag = tag) } # Add limits whenever needed if (vpc_dat$type == 'categorical') xp <- xp + coord_cartesian(ylim = c(0, 1)) # Add color scales xp <- xp + scale_fill_manual(values = area_fill) + scale_linetype_manual(values = line_linetype) # Add metadata to plots xp$xpose <- dplyr::tibble(problem = vpc_prob, subprob = 0L, descr = c('VPC directory', 'Number of simulations for VPC', 'VPC confidence interval', 'VPC prediction interval', 'VPC lower limit of quantification', 'VPC upper limit of quantification'), label = c('vpcdir', 'vpcnsim', 'vpcci', 'vpcpi', 'vpclloq', 'vpculoq'), value = c(vpc_dat$vpc_dir, vpc_dat$nsim, 100*diff(vpc_dat$opt$ci), 100*diff(vpc_dat$opt$pi), ifelse(is.null(vpc_dat$lloq), 'na', vpc_dat$lloq), ifelse(is.null(vpc_dat$uloq), 'na', vpc_dat$uloq))) %>% dplyr::bind_rows(xpdb$summary) %>% {list(fun = stringr::str_c('vpc_', vpc_dat$type), summary = ., problem = vpc_prob, quiet = quiet, xp_theme = xpdb$xp_theme[stringr::str_c(c('title', 'subtitle', 'caption', 'tag'), '_suffix')])} # Ouptut the plot as.xpose.plot(xp) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/plot_vpc.R
#' Print an xpose_data object #' #' @description This function returns to the console a list of the files and options #' attached to an \code{\link{xpose_data}} object. #' #' @param x An \code{xpose_data} object generated with \code{\link{xpose_data}}. #' @param ... Ignored in this function #' #' @method print xpose_data #' @examples #' # Using the print function #' print(xpdb_ex_pk) #' #' # Or simply by writing the xpdb name #' xpdb_ex_pk #' #' @export print.xpose_data <- function(x, ...) { # Summarize estimation tables names if (!is.null(x$data) && any(!x$data$simtab)) { tab_names <- x$data %>% dplyr::filter(.$simtab == FALSE) %>% dplyr::mutate(grouping = 1:n()) %>% dplyr::group_by_at(.vars = 'grouping') %>% tidyr::nest() %>% dplyr::ungroup() %>% dplyr::mutate(string = purrr::map_chr(.$data, summarize_table_names)) %>% {stringr::str_c(.$string, collapse = '\n ')} } else { tab_names <- '<none>' } # Summarize simulation tables names if (!is.null(x$data) && any(x$data$simtab)) { sim_names <- x$data %>% dplyr::filter(.$simtab == TRUE) %>% dplyr::mutate(grouping = 1:n()) %>% dplyr::group_by_at(.vars = 'grouping') %>% tidyr::nest() %>% dplyr::ungroup() %>% dplyr::mutate(string = purrr::map_chr(.$data, summarize_table_names)) %>% {stringr::str_c(.$string, collapse = '\n ')} } else { sim_names <- '<none>' } # Summarize file names if (!is.null(x$files)) { out_names <- x$files %>% dplyr::distinct(!!rlang::sym('name'), .keep_all = TRUE) %>% dplyr::arrange_at(.vars = 'name') %>% {stringr::str_c(.$name, ifelse(.$modified, ' (modified)', ''), collapse = ', ')} } else { out_names <- '<none>' } # Summarize special table names if (!is.null(x$special)) { special_names <- stringr::str_c(x$special$method, ' ', x$special$type, ' (#', x$special$problem, ifelse(x$special$modified, ', modified', ''), ')', collapse = ', ') } else { special_names <- '<none>' } # Summarize options opt_names <- x$options %>% purrr::map_if(.p = is.null, .f = function(x) {'NULL'}) %>% {stringr::str_c(names(.), unlist(.), sep = ' = ', collapse = ', ')} cat(x$summary$value[x$summary$label == 'file'], 'overview:', '\n - Software:', x$summary$value[x$summary$label %in% c('software', 'version') & x$summary$value != 'na'], stringr::str_c('\n - Attached files (memory usage ', format(utils::object.size(x), units = 'auto'), '):'), '\n + obs tabs:', tab_names, '\n + sim tabs:', sim_names, '\n + output files:', out_names, '\n + special:', special_names, '\n - gg_theme:', attr(x$gg_theme, 'theme'), '\n - xp_theme:', attr(x$xp_theme, 'theme'), '\n - Options:', opt_names) } summarize_table_names <- function(dat) { purrr::map(dat$index, ~.$table) %>% purrr::flatten_chr() %>% sort() %>% unique() %>% stringr::str_c(collapse = ', ') %>% {stringr::str_c('$prob no.', dat$problem, ifelse(dat$modified, ' (modified)', ''), ': ', .)} }
/scratch/gouwar.j/cran-all/cranData/xpose/R/print_xpose_data.R
#' Draw an xpose_plot object #' #' @description This function explicitly draw an xpose_plot and interprets keywords #' contained in labels. #' #' @param x An \code{xpose_plot} object. #' @param page The page number to be drawn. Can be specified as vector or range #' of integer values. #' @param ... Options to be passed on to the ggplot2 print method. #' #' @method print xpose_plot #' @examples #' my_plot <- dv_vs_ipred(xpdb_ex_pk) + #' labs(title = 'A label with keywords: @nind individuals & @nobs observations') #' # Using the print function #' print(my_plot) #' #' # Or simply by writting the plot object name #' my_plot #' #' @export print.xpose_plot <- function(x, page, ...) { # Parse template titles if (is.xpose.plot(x)) { # Add prefix to title subtitle, caption and tags x$labels$title <- append_suffix(x$xpose, x$labels$title, 'title') x$labels$subtitle <- append_suffix(x$xpose, x$labels$subtitle, 'subtitle') x$labels$caption <- append_suffix(x$xpose, x$labels$caption, 'caption') if (utils::packageVersion('ggplot2') >= '3.0.0') { x$labels$tag <- append_suffix(x$xpose, x$labels$tag, 'tag') } # Get the mapping variables keywords and values var_map <- x$mapping %>% as.character() %>% stringr::str_remove(pattern = "^~") %>% ## Improve parsing since we now have to use the .data[["var"]] format in aes() ifelse(stringr::str_detect(., "\\.data\\[\\[\"\\w+\"]]"), yes = stringr::str_remove_all(., "(\\.data\\[\\[\")|(\"]])"), no = .) %>% purrr::set_names(names(x$mapping)) # Process the keywords x$labels <- x$labels %>% purrr::map_if(stringr::str_detect(., '@'), .f = parse_title, xpdb = x$xpose, problem = x$xpose$problem, quiet = x$xpose$quiet, ignore_key = c('page', 'lastpage'), extra_key = c('plotfun', 'timeplot', names(var_map)), extra_value = c(x$xpose$fun, format(Sys.time(), "%a %b %d %X %Z %Y"), var_map)) } # Print multiple pages if (class(x$facet)[1] %in% c('FacetWrapPaginate', 'FacetGridPaginate')) { # Get total number of pages #page_tot <- n_pages(repair_facet(x)) page_tot <- n_pages(x) # Get and check the page number to be drawn if (!missing(page)) { page_2_draw <- page } else if (!is.null(x$facet$params$page)) { page_2_draw <- x$facet$params$page } else { page_2_draw <- 1:page_tot } if (any(page_2_draw > page_tot)) { page_2_draw <- page_2_draw[page_2_draw <= page_tot] if (length(page_2_draw) == 0) { stop('All `page` element exceeded the total (', page_tot, ') number of pages.', call. = FALSE) } warning('`page` contained elements exceeding the total (', page_tot, ') number of pages. These were ignored.', call. = FALSE) } # Prevent issue with facet_repair when page = NULL x$facet$params$page <- page_2_draw # Begin multiple page ploting n_page_2_draw <- length(page_2_draw) if (interactive() && !x$xpose$quiet) { message('Rendering ', n_page_2_draw, ' selected page(s) out of ', page_tot, '.') } if (n_page_2_draw == 1) { x %>% paginate(page_2_draw, page_tot) %>% #repair_facet() %>% print.ggplot(...) } else { if (interactive() && !x$xpose$quiet) { pb <- utils::txtProgressBar(min = 0, max = n_page_2_draw, style = 3) # Create progress bar } for (p in seq_along(page_2_draw)) { x$facet$params$page <- page_2_draw[p] x %>% paginate(page_2_draw[p], page_tot) %>% #repair_facet() %>% print.ggplot(...) if (interactive() && !x$xpose$quiet) { utils::setTxtProgressBar(pb, value = p) # Update progress bar } } if (interactive() && !x$xpose$quiet) close(pb) # Prevent ggforce from droping multiple pages value x$facet$params$page <- page_2_draw } } else { if (!missing(page)) warning('Faceting not set. Ignoring `page` argument.', call. = FALSE) # Warn for big plots panel_tot <- n_panels(x) if (panel_tot > 20) { msg(c('The faceting resulted in ', panel_tot, ' panels. The plot may take a while to render.'), quiet = x$xpose$quiet) } # Print without multiple pages x %>% paginate(page_2_draw = 1, page_tot = 1) %>% #repair_facet() %>% print.ggplot(...) } } #' Import print ggplot method #' @keywords internal print.ggplot <- get('print.ggplot', envir = asNamespace('ggplot2')) # Add page number to pages paginate <- function(plot, page_2_draw, page_tot) { plot$labels <- plot$labels %>% purrr::map_if(.p = ~!is.null(.) && stringr::str_detect(., '@(page|lastpage)'), .f = parse_title, xpdb = plot$xpose, problem = plot$xpose$problem, quiet = plot$xpose$quiet, extra_key = c('page', 'lastpage'), extra_value = c(as.character(page_2_draw), page_tot)) plot } # Temporary fix for ggforce facet_wrap_paginate (may) # repair_facet <- function(x) { # if (class(x$facet)[1] == 'FacetWrapPaginate' && # !'nrow' %in% names(x$facet$params)) { # x$facet$params$nrow <- x$facet$params$max_row # } # x # } # Calculate the total number of pages n_pages <- function(plot) { if (utils::packageVersion('ggplot2') <= '2.2.1') { page <- ggplot_build(plot)$layout$panel_layout$page } else { page <- ggplot_build(plot)$layout$layout$page } if (!is.null(page)) { max(page) } else { 0L } } # Calculate the total number of panels n_panels <- function(plot) { if (utils::packageVersion('ggplot2') <= '2.2.1') { page <- ggplot_build(plot)$layout$panel_layout } else { page <- ggplot_build(plot)$layout$layout } if (!is.null(page)) { nrow(page) } else { 0L } }
/scratch/gouwar.j/cran-all/cranData/xpose/R/print_xpose_plot.R
#' Display a parameter estimates to the console #' #' @description Display parameter estimates from an xpdb object to the console. #' #' @inheritParams get_prm #' @seealso \code{\link{get_prm}}, #' @examples #' \dontrun{ #' # Store the parameter table #' prm <- get_prm(xpdb_ex_pk, .problem = 1) #' #' # Display parameters to the console #' prm_table(xpdb_ex_pk, .problem = 1) #' } #' @export prm_table <- function(xpdb, .problem = NULL, .subprob = NULL, .method = NULL, digits = 4, transform = TRUE, show_all = FALSE) { x <- get_prm(xpdb = xpdb, .problem = .problem, .subprob = .subprob, .method = .method, digits = digits, transform = transform, show_all = show_all, quiet = TRUE) if (transform) { cat('\nReporting transformed parameters:\nFor the OMEGA and SIGMA matrices, values are reported as standard deviations for the diagonal elements and as correlations for the off-diagonal elements. The relative standard errors (RSE) for OMEGA and SIGMA are reported on the approximate standard deviation scale (SE/variance estimate)/2. Use `transform = FALSE` to report untransformed parameters.\n') } else { cat('\nReporting untransformed parameters:\nFor the OMEGA and SIGMA matrices, values are reported as variances for the diagonal elements and as covariances for the off-diagonal elements.\n') } # Convert single prm_df to list if (dplyr::is.tbl(x)) x <- list(x) # Generate output to console purrr::map(.x = x, function(prm, transform) { prm_attr <- attributes(prm) uncertainty_lab <- ifelse(transform, 'RSE', 'SE') if (!transform) prm$rse <- prm$se header <- dplyr::tibble(name = 'Parameter', label = 'Label', value = 'Value', rse = uncertainty_lab, fixed = ' ') cat('\nEstimates for $prob no.', prm_attr$problem, ', subprob no.', prm_attr$subprob, ', method ', prm_attr$method, '\n', sep = '') prm %>% dplyr::mutate_all(.funs = 'as.character') %>% dplyr::mutate(fixed = ifelse(.$fixed, 'fix', ' ')) %>% {dplyr::bind_rows(header, .)} %>% dplyr::mutate(name = stringr::str_pad(.$name, max(nchar(.$name)), 'right'), label = stringr::str_pad(.$label, max(nchar(.$label)), 'right'), value = stringr::str_pad(.$value, max(nchar(.$value)), 'right'), rse = ifelse(is.na(.$rse), ' - ', .$rse)) %>% dplyr::mutate(string = stringr::str_c('', .$name, .$label, .$value, .$fixed, .$rse, sep = ' ')) %>% {purrr::flatten_chr(.[,'string'])} %>% cat(sep = '\n') }, transform = transform) %>% invisible() }
/scratch/gouwar.j/cran-all/cranData/xpose/R/prm_table.R
#' NONMEM output file import function #' #' @description Quickly import NONMEM output files into R. #' #' @param runno Run number to be evaluated. #' @param prefix Prefix of the model file names. #' @param ext A vector of the file extension to import. By default '.ext', '.cor', '.cov', '.phi', '.grd', '.shk' #' files are listed. #' @param file Names of the model output file to be imported. Alternative argument to \code{prefix}, #' \code{runno} and \code{ext}. #' @param dir Location of the model files. #' @param quiet Logical, if \code{FALSE} messages are printed to the console. #' #' @inheritSection xpose_data File path generation #' @seealso \code{\link{xpose_data}}, \code{\link{read_nm_tables}} #' @examples #' \dontrun{ #' # Using the `file` argument to import a model file: #' ext_file <- read_nm_files(file = 'run001.ext', dir = 'models') #' #' # Using the `runno` argument to import a model file: #' ext_file <- read_nm_files(runno = '001', ext = '.ext', dir = 'models') #' } #' @export read_nm_files <- function(runno = NULL, prefix = 'run', ext = c('.ext', '.cor', '.cov', '.phi', '.grd', '.shk'), file = NULL, dir = NULL, quiet = FALSE) { # Check inputs if (is.null(runno) && is.null(file)) { stop('Argument `runno` or `file` required.', call. = FALSE) } if (missing(quiet)) quiet <- !interactive() # Check for readr lazy loading if (readr::should_read_lazy() & .Platform$OS.type == "windows") { warning("Using lazy loading in `readr` on Windows can cause unexpected behavior and is not recommended with `xpose`.", call. = FALSE) } # Generate full paths if (!is.null(runno)) { full_path <- file_path(dir, stringr::str_c(prefix, runno, make_extension(ext))) } else { full_path <- file_path(dir, file) } full_path <- sort(unique(full_path)) bases <- basename(full_path) msg('\nLooking for nonmem output files', quiet) if (!any(file.exists(full_path))) { stop('No output files could be found.', call. = FALSE) } msg(c('Reading: ', stringr::str_c(bases[file.exists(full_path)], collapse = ', ')), quiet) out <- full_path %>% dplyr::tibble(path = ., name = basename(.)) %>% dplyr::filter(file.exists(.$path)) %>% dplyr::mutate(grouping = 1:n(), raw = purrr::map(.$path, .f = readr::read_lines)) %>% dplyr::group_by_at(.vars = 'grouping') %>% tidyr::nest() %>% dplyr::ungroup() %>% dplyr::mutate(tmp = purrr::map(.$data, .f = parse_nm_files, quiet)) %>% dplyr::mutate(drop = purrr::map_lgl(.$tmp, is.null)) if (all(out$drop)) stop('No output file imported.', call. = FALSE) out %>% dplyr::filter(!.$drop) %>% tidyr::unnest(dplyr::one_of('data')) %>% tidyr::unnest(dplyr::one_of('tmp')) %>% dplyr::mutate(extension = get_extension(.$name, dot = FALSE), modified = FALSE) %>% dplyr::select(dplyr::one_of('name', 'extension', 'problem', 'subprob', 'method', 'data', 'modified')) } #' Parse NONMEM output files #' #' @description Function parsing NONMEM output files from their #' raw input. #' #' @param dat A list containing the raw data as vector of strings (`dat$raw`) #' and their respective file names (`dat$name`). #' @param quiet Logical, if \code{FALSE} messages are printed to the console. #' #' @return A tibble containing the parsed `data` along with `name`, `problem`, #' `subprob`, and `method`. #' #' @keywords internal #' @export parse_nm_files <- function(dat, quiet) { if (length(unlist(dat$raw)) == 0) { tab_rows <- NULL } else { x <- dplyr::tibble( raw = unlist(dat$raw), problem = NA_character_, subprob = NA_character_, method = NA_character_, header = FALSE ) tab_rows <- which(stringr::str_detect(x$raw, '^\\s*TABLE NO')) } if (length(tab_rows) == 0) { warning(c('Dropped `', dat$name, '` due to inappropriate format.'), call. = FALSE) return() } x[tab_rows, ]$problem <- stringr::str_match(x[tab_rows, ]$raw, '\\s+Problem=(\\d+)')[,2] ## Give stacked estimation methods a unique subproblem number ## Note: this allows the use of the same estimation method several times within one $PROBLEM x <- dplyr::mutate(x, subprob = cumsum(duplicated(!!rlang::sym("problem")) & !is.na(!!rlang::sym("problem"))) + 1) x[tab_rows, ]$method <- dplyr::case_when(stringr::str_detect(x[tab_rows, ]$raw, 'First Order Conditional') ~ 'foce', stringr::str_detect(x[tab_rows, ]$raw, 'First Order') ~ 'fo', stringr::str_detect(x[tab_rows, ]$raw, 'Laplacian Conditional') ~ 'lce', stringr::str_detect(x[tab_rows, ]$raw, 'Iterative Two Stage') ~ 'its', stringr::str_detect(x[tab_rows, ]$raw, 'Importance Sampling') ~ 'imp', stringr::str_detect(x[tab_rows, ]$raw, 'Stochastic Approximation') ~ 'saem', stringr::str_detect(x[tab_rows, ]$raw, 'Markov-Chain') ~ 'bayes', TRUE ~ 'na') # Assumes that header are always present x[tab_rows + 1, ]$header <- TRUE # Guess column separator from the first problem only sep <- dplyr::case_when( stringr::str_detect(x[tab_rows[1] + 1, ]$raw, ';[A-z]+') ~ ';[A-z]|[A-z];', stringr::str_detect(x[tab_rows[1] + 1, ]$raw, ',[A-z]+') ~ ',[A-z]|[A-z],', TRUE ~ '\\s+') x %>% tidyr::fill(dplyr::one_of('problem', 'subprob', 'method')) %>% dplyr::slice(-tab_rows) %>% dplyr::mutate(problem = as.numeric(.$problem), subprob = as.numeric(.$subprob), raw = stringr::str_trim(.$raw, side = 'both')) %>% dplyr::group_by_at(.vars = c('problem', 'subprob', 'method')) %>% tidyr::nest() %>% dplyr::ungroup() %>% dplyr::mutate(data = purrr::map(.$data, .f = raw_to_tibble, sep = sep, file = dat$name)) } #' Convert raw strings to tibble #' #' @description Convert raw data strings to a tibble format. #' #' @param x A list containing the raw data as vector of strings (`x$raw`). #' @param sep A separator which will be used to create columns. #' @param file The name of the file to be parsed. #' #' @return A tibble. #' #' @keywords internal #' @export raw_to_tibble <- function(x, sep, file) { header <- x$raw[x$header] %>% stringr::str_split(pattern = sep) %>% purrr::flatten_chr() if (any(is.na(header))) { warning(c('Issue encountered while parsing ', file, '.'), call. = FALSE) return() } x[!x$header, ] %>% tidyr::separate(col = 'raw', sep = sep, into = header) %>% dplyr::select(-ncol(.)) %>% dplyr::mutate_if(colnames(.) != 'NAME', as.numeric) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/read_nm_files.R
#' NONMEM model file parser #' #' @description Parse NONMEM model files in R format #' #' @inheritParams xpose_data #' @inheritSection xpose_data File path generation #' #' @details #' A NONMEM model output file (i.e. .lst, .out or .res) should preferably be provided to \code{read_nm_model} to allow for a more extensive xpose #' summary. However in some cases these output files may not contain the model code, thus preventing xpose from identifying the associated output #' tables names. In such cases xpose will attempt to read the associated model file (i.e. .mod or .ctl) instead to find the model code. Note: it #' is important that between the naming convention between the NONMEM output and the model file remains consistent e.g. run001.lst should be #' associated with run001.mod. #' #' @seealso \code{\link{xpose_data}}, \code{\link{read_nm_tables}} #' @return A \code{\link[dplyr]{tibble}} of class \code{model} containing the following columns: #' \itemize{ #' \item problem: a numeric identifier for the $PROBLEM associated with the code. #' \item level: a unique numeric identifier to each subroutine block associated with the code. #' \item subroutine: a character identifier named after the 3 first letters of the subroutine name e.g. '$THETA' and #' '$TABLE' will become 'the' and 'tab' respectively. In addition all output from the .lst is labeled 'lst', the general nonmem #' output e.g. NM-TRAN messages are labelled 'oth'. With priors thp, tpv, omp, opd, sip, spd abbreviations are given to the THETAP, #' THETAPV, OMEGAP, etc. #' \item code: the code without comments or subroutine names e.g. '$THETA 0.5 ; TVCL' will return '0.5'. #' \item comment: the last comment of a record e.g. '0.5 ; Clearance (L/h) ; TVCL' will return 'TVCL'. #' } #' #' @examples #' \dontrun{ #' # Using the `file` argument to import a model file: #' nm_model <- read_nm_model(file = 'run001.lst', dir = 'models') #' #' # Using the `runno` argument to import a model file: #' nm_model <- read_nm_model(runno = '001', ext = '.lst', dir = 'models') #' } #' #' @export read_nm_model <- function(runno = NULL, prefix = 'run', ext = '.lst', file = NULL, dir = NULL, check_ext = TRUE) { if (is.null(runno) && is.null(file)) { stop('Argument `runno` or `file` required.', call. = FALSE) } if (!is.null(runno)) { ext <- make_extension(ext) full_path <- file_path(dir, stringr::str_c(prefix, runno, ext)) } else { ext <- get_extension(file) full_path <- file_path(dir, file) } if (check_ext & !ext %in% c('.lst', '.out', '.res', '.mod', '.ctl')) { stop( paste( 'NONMEM model file extension should be one of .lst, .out, .res, .mod or .ctl. If you want to use the', ext ,'extension anyway use `check_ext = FALSE`'), call. = FALSE) } if (!file.exists(full_path)) { stop('Model file ', basename(full_path), ' not found.', call. = FALSE) } # Check for readr lazy loading if (readr::should_read_lazy() & .Platform$OS.type == "windows") { warning("Using lazy loading in `readr` on Windows can cause unexpected behavior and is not recommended for `xpose`.", call. = FALSE) } model <- readr::read_lines(full_path) if (!any(stringr::str_detect(model, '^\\s*\\$PROB')) && ext %in% c('.lst', '.out', '.res')) { # Attempts to recover the model code from model file rather than in the nonmem output file full_path <- update_extension(full_path, c('.mod', '.ctl')) full_path <- full_path[file.exists(full_path)] if (any(file.exists(full_path))) { warning(c('No model code found in `', ext, '` NONMEM output file importing `', get_extension(full_path)[1], '` instead.'), call. = FALSE) model <- readr::read_lines(full_path[1]) } } # Return error if input is bad if (!any(stringr::str_detect(model, '^\\s*\\$PROB'))) { stop(basename(full_path), ' is not a NONMEM model.', call. = FALSE) } model <- dplyr::tibble(code = model) %>% dplyr::filter(!stringr::str_detect(.$code, '^;[^;]*$|^$')) %>% dplyr::mutate(code = stringr::str_replace_all(.$code, '\\t+|\\s{2,}', ' ')) %>% dplyr::mutate( problem = findInterval(seq_along(.$code), which(stringr::str_detect(.$code, '^\\s*\\$PROB'))), level = findInterval(seq_along(.$code), which(stringr::str_detect(.$code, '^\\s*\\$.+'))), subroutine = stringr::str_match(.$code, '^\\s*\\$(\\w+)')[, 2]) %>% tidyr::fill(dplyr::one_of('subroutine')) # Generate abbreviated subroutine names special <- c('THETAI', 'THETAR', 'THETAP', 'THETAPV', 'OMEGAP', 'OMEGAPD', 'SIGMAP', 'SIGMAPD') match_special <- match(model$subroutine[model$subroutine %in% special], special) model$subroutine[model$subroutine %in% special] <- c('thi', 'thr', 'thp', 'tpv', 'omp', 'opd', 'sip', 'spd')[match_special] model$subroutine <- stringr::str_extract(tolower(model$subroutine), '[a-z]{1,3}') # Format lst part if (any(stringr::str_detect(model$code, 'NM-TRAN MESSAGES'))) { lst_rows <- which(stringr::str_detect(model$code, 'NM-TRAN MESSAGES')):nrow(model) model[lst_rows,] <- model %>% dplyr::slice(lst_rows) %>% dplyr::mutate(problem = findInterval(seq_along(.$problem), which(stringr::str_detect(.$code, '^\\s*PROBLEM NO\\.:\\s*\\d+$')))) %>% dplyr::mutate(level = 1 + .$level[1] + .$problem, subroutine = 'lst') } # Handle other special cases if (any(stringr::str_detect(model$code, '#CPUT'))) { cput_row <- which(stringr::str_detect(model$code, '#CPUT')) model[cput_row, 'problem'] <- 0 model[cput_row:nrow(model), 'level'] <- model[cput_row:nrow(model), ]$level + 1 } if (any(stringr::str_detect(model$code, 'Stop Time'))) { end_rows <- which(stringr::str_detect(model$code, 'Stop Time')):nrow(model) model[end_rows, 'problem'] <- 0 model[end_rows, 'level'] <- model[end_rows[1], ]$level + 1 } model[is.na(model$subroutine) | (model$problem == 0 & model$subroutine == 'lst'), 'subroutine'] <- 'oth' # Remove subroutine names from the code model$code <- stringr::str_replace(model$code, '^\\s*\\$\\w+\\s*', '') # Remove empty rows but $PROBLEM model <- model[!stringr::str_detect(model$code, '^(\\s|\\t)*$') | model$subroutine == 'pro', ] # Create comment column code_rows <- !model$subroutine %in% c('lst', 'oth') | model$level == 0 model[code_rows, 'comment'] <- stringr::str_match(model[code_rows, ]$code, ';\\s*(.*)\\s*$')[, 2] model[code_rows, 'code'] <- stringr::str_replace(model[code_rows, ]$code, '\\s*;.*$', '') # Remove na values and output tidyr::replace_na(model, replace = list(code = '', comment = '')) %>% dplyr::select(dplyr::one_of('problem', 'level', 'subroutine', 'code', 'comment')) %>% dplyr::mutate(problem = as.integer(.$problem), level = as.integer(.$level)) %>% structure(file = basename(full_path), dir = dirname(full_path), software = 'nonmem', class = c('nm_model', class(.))) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/read_nm_model.R
#' NONMEM output table import function #' #' @description Quickly import NONMEM output tables into R. This function automatically #' detects the optimal settings to import the tables from nonmem. #' #' @param file A character vector of path to the files or a \code{nm_table_list} object created with \code{list_nm_tables}. #' @param dir Location of the model files. #' @param combined Logical value indicating whether multiple tables should be combined into a single one. If the number of rows #' does not match an error will be returned. #' @param rm_duplicates Logical value indicating whether duplicated columns should be removed. #' @param quiet Logical, if \code{FALSE} messages are printed to the console. #' @param simtab If \code{TRUE} only reads in simulation tables, if \code{FALSE} only reads estimation tables. #' Default \code{NULL} reads all tables. #' @param ziptab If \code{TRUE} search for the tables that have been compressed and renamed ´<file>.zip'. #' @param ... Additional arguments to be passed to the \code{\link[readr]{read_table}} or \code{\link[readr]{read_csv}} functions. #' #' @section Table format requirement: #' When using \code{read_nm_tables} with the \code{combined} argument set to \code{FALSE} an \code{ID} column #' must be present in all data tables. When \code{combined} is set to \code{TRUE} instead an \code{ID} column must be #' present in at least one table for each problem and for each `firstonly` category. \code{ID} columns are required #' to properly combine/merge tables and removing \code{NA} records. If the \code{ID} column is missing from a table and #' \code{combined = FALSE} \code{read_nm_tables} will return the following warning: \code{Unknown variables: `ID`}. While #' the data is returned beware that \code{NA} records might be left in the data and the output should be checked carefully. #' If \code{combined = TRUE} \code{read_nm_tables} xpose is more strict and will return the following warning instead: #' \code{Dropped `<tablenames>` due to missing required `ID` column.}. #' #' @examples #' \dontrun{ #' # Import tables manually and return them as a list of individual tables #' nm_tables <- read_nm_tables(file = c('sdtab001', 'patab001'), #' dir = 'models', combined = FALSE) #' #' # Import tables manually and return them as a single merged table #' nm_tables <- read_nm_tables(file = c('sdtab001', 'patab001'), #' dir = 'models', combined = TRUE) #' #' # Import tables automatically (used internally by xpose_data()) #' nm_tables <- read_nm_model(file = 'run001.lst', dir = 'models') %>% #' list_nm_tables() %>% #' read_nm_tables() #' #' # Passing arguments to readr via `...` #' # (e.g. import columns as character and only first 10 rows) #' nm_tables <- read_nm_tables(file = 'sdtab001', dir = 'models', #' col_type = readr::cols(.default = 'c'), #' n_max = 10) #' #' } #' @export read_nm_tables <- function(file = NULL, dir = NULL, combined = TRUE, rm_duplicates = TRUE, quiet = FALSE, simtab = NULL, ziptab = TRUE, ...) { # Check inputs if (is.null(file)) stop('Argument `file` required.', call. = FALSE) if (!is.null(file) && !is.nm.table.list(file)) { file <- dplyr::tibble(problem = 1, file = file_path(dir, file), firstonly = FALSE, simtab = FALSE) } user_mode <- !is.nm.table.list(file) # Filter tables if needed if (!is.null(simtab)) file <- file[file$simtab == simtab, ] msg('\nLooking for nonmem output tables.', quiet) # Check that file exists if (is.null(file) || !any(file.exists(file$file))) { stop('No table files could be found.', call. = FALSE) } if (any(duplicated(file$file))) { stop('No table imported due to duplicated names.', call. = FALSE) } # Check for readr lazy loading if (readr::should_read_lazy() & .Platform$OS.type == "windows") { warning("Using lazy loading in `readr` on Windows can cause unexpected behavior and is not recommended for `xpose`.", call. = FALSE) } tables <- file[file.exists(file$file), ] # Search for compressed tables if (ziptab) { tables_zip <- file[!file.exists(file$file), ] if (nrow(tables_zip) > 0) { tables_zip$file <- stringr::str_c(tables_zip$file, '.zip') tables_zip <- tables_zip[file.exists(tables_zip$file), ] if (nrow(tables_zip) > 0) { tables <- tables %>% dplyr::bind_rows(tables_zip) %>% dplyr::arrange_at(.vars = c('problem', 'file')) } } } # Print reading messages tables %>% dplyr::mutate(grouping = 1:n(), name = stringr::str_c(basename(.$file), dplyr::if_else(.$firstonly, ' (firstonly)', ''))) %>% dplyr::group_by_at(.vars = c('problem', 'simtab')) %>% tidyr::nest() %>% dplyr::ungroup() %>% dplyr::mutate(string = purrr::map_chr(.$data, ~stringr::str_c(.$name, collapse = ', '))) %>% {stringr::str_c(.$string, ' [$prob no.', .$problem, dplyr::if_else(.$simtab, ', simulation', ''), ']', collapse = '\n ')} %>% {msg(c('Reading: ', .), quiet)} # Collect options for table import tables <- tables %>% dplyr::mutate(top = purrr::map(.$file, ~readr::read_lines(file = ., n_max = 3)), grouping = 1:n()) %>% dplyr::group_by_at(.vars = 'grouping') %>% tidyr::nest() %>% dplyr::ungroup() %>% dplyr::mutate(args = purrr::map(.x = .$data, .f = read_args, quiet, ...)) %>% tidyr::unnest(dplyr::one_of('data')) %>% tidyr::unnest(dplyr::one_of('args')) %>% dplyr::mutate(name = basename(.$file)) %>% dplyr::select(dplyr::one_of('problem', 'name', 'simtab', 'firstonly', 'fun', 'params')) if (nrow(tables) == 0) stop('No table imported.', call. = FALSE) # Read in data tables <- tables %>% dplyr::bind_cols(tables %>% dplyr::select(dplyr::one_of(c('fun', 'params'))) %>% dplyr::mutate(table = purrr::map2(.x = .$fun, .y = .$params, .f = do.call)) %>% dplyr::pull(table) %>% dplyr::tibble(data = .)) if (!combined) { return(purrr::set_names(x = purrr::map(tables$data, ~tidyr::drop_na(., dplyr::one_of('ID'))), nm = tables$name)) } # Index datasets tables <- tables %>% dplyr::mutate(grouping = 1:n()) %>% dplyr::group_by_at(.vars = 'grouping') ## TEMP handling if (tidyr_new_interface()) { tables <- tables %>% tidyr::nest(tmp = -dplyr::one_of('grouping')) } else { tables <- tables %>% tidyr::nest(.key = 'tmp') } ## END TEMP tables <- tables %>% dplyr::ungroup() %>% dplyr::mutate(index = purrr::map(.$tmp, index_table), nrow = purrr::map_dbl(.$tmp, ~nrow(.$data[[1]]))) %>% tidyr::unnest(dplyr::one_of('tmp')) %>% dplyr::ungroup() # Combine tables with same number of rows tables <- tables %>% dplyr::group_by_at(.vars = c('problem', 'simtab', 'firstonly')) ## TEMP handling if (tidyr_new_interface()) { tables <- tables %>% tidyr::nest(tmp = -dplyr::one_of('problem', 'simtab', 'firstonly')) } else { tables <- tables %>% tidyr::nest(.key = 'tmp') } ## END TEMP tables <- tables %>% dplyr::ungroup() %>% dplyr::mutate(out = purrr::map(.$tmp, combine_tables)) %>% tidyr::unnest(dplyr::one_of('out')) %>% dplyr::select(dplyr::one_of('problem', 'simtab', 'firstonly', 'data', 'index')) if (nrow(tables) == 0) stop('No table imported.', call. = FALSE) # Remove duplicated columns to decrease xpdb size if (rm_duplicates) { tables <- tables %>% dplyr::mutate(grouping = 1:n()) %>% dplyr::group_by_at(.vars = 'grouping') ## TEMP handling if (tidyr_new_interface()) { tables <- tables %>% tidyr::nest(tmp = -dplyr::one_of('grouping')) } else { tables <- tables %>% tidyr::nest(.key = 'tmp') } ## END TEMP tables <- tables %>% dplyr::ungroup() %>% dplyr::mutate(out = purrr::map(.$tmp, ~dplyr::select(.$data[[1]], dplyr::one_of(unique(unlist(.$index[[1]]$col)))))) %>% tidyr::unnest(dplyr::one_of('tmp')) %>% dplyr::select(dplyr::one_of('problem', 'simtab', 'firstonly', 'index', 'out')) %>% dplyr::rename(!!rlang::sym('data') := dplyr::one_of('out')) } # Merge firsonly tables with main tables if (any(tables$firstonly)) { msg('Consolidating tables with `firstonly`', quiet) tables <- tables %>% dplyr::group_by_at(.vars = c('problem', 'simtab')) ## TEMP handling if (tidyr_new_interface()) { tables <- tables %>% tidyr::nest(tmp = -dplyr::one_of('problem', 'simtab')) } else { tables <- tables %>% tidyr::nest(.key = 'tmp') } ## END TEMP tables <- tables %>% dplyr::ungroup() %>% dplyr::mutate(out = purrr::map(.$tmp, merge_firstonly, quiet)) %>% tidyr::unnest(dplyr::one_of('out')) %>% dplyr::select(dplyr::one_of('problem', 'simtab', 'data', 'index')) } if (nrow(tables) == 0) stop('No table imported.', call. = FALSE) # Convert catcov, id, occ, dvid to factor tables <- tables %>% dplyr::mutate(grouping = .$problem) %>% dplyr::group_by_at(.vars = 'grouping') ## TEMP handling if (tidyr_new_interface()) { tables <- tables %>% tidyr::nest(tmp = -dplyr::one_of('grouping')) } else { tables <- tables %>% tidyr::nest(.key = 'tmp') } ## END TEMP tables <- tables %>% dplyr::ungroup() %>% dplyr::mutate(tmp = purrr::map(.$tmp, function(x) { col_to_factor <- colnames(x$data[[1]]) %in% x$index[[1]]$col[x$index[[1]]$type %in% c('catcov', 'id', 'occ', 'dvid')] x$data[[1]] <- dplyr::mutate_if(x$data[[1]], col_to_factor, as.factor) x })) %>% tidyr::unnest(dplyr::one_of('tmp')) %>% dplyr::mutate(modified = FALSE) %>% dplyr::select(dplyr::one_of('problem', 'simtab', 'index', 'data', 'modified')) # If user mode return simple tibble as only 1 problem should be used if (user_mode) return(tables$data[[1]]) tables } #' Define data import functions #' #' @param fun Abbreviated `readr` data import function. #' Can be `csv`, `csv2` or `table`. #' #' @return A data import function. #' #' @keywords internal #' @export read_funs <- function(fun) { if (utils::packageVersion("readr") > "1.4.0") { c(csv = readr::read_csv, csv2 = readr::read_csv2, table = readr::read_table)[fun] } else { c(csv = readr::read_csv, csv2 = readr::read_csv2, table = readr::read_table2)[fun] } } #' Define data import arguments #' #' @param x A list containing a the 3 first records of a #' dataset under `[[1]]`. #' @param quiet Should messages be displayed to the console. #' @param col_types Defines the type of each column to be passed to #' the `readr` import function. #' @param na Character string defining the values to be treated as `NA`. #' @param comment Character string defining the value to mark comments. #' @param skip Number of rows to be skipped before reading the data. #' @param ... Additional arguments to be passed to the `readr` function #' #' @return A list of 2 levels fun (the import function) and params (a list #' of arguments to be used when calling fun). #' #' @keywords internal #' @export read_args <- function(x, quiet, col_types = readr::cols(.default = 'd'), na = 'NA', comment = 'TABLE', skip = 1, ...) { top <- x$top[[1]] if (is.na(top[3]) || !stringr::str_detect(top[3], '\\d+E[+-]\\d+\\s*')) { warning(c('Dropped: ', basename(x$file), ' due to unexpected data format'), call. = FALSE) return(dplyr::tibble(fun = list(), params = list())) } fun <- dplyr::case_when(stringr::str_detect(top[3], '\\d,\\d+E[+-]\\d+\\s*;') ~ 'csv2', stringr::str_detect(top[3], '\\d.\\d+E[+-]\\d+\\s*,') ~ 'csv', TRUE ~ 'table') skip_h <- dplyr::if_else(stringr::str_detect(top[1], 'TABLE NO\\.\\s+\\d'), 1, 0) if (!stringr::str_detect(top[1 + skip_h], '[A-z]{2,}+')) { warning(c('Dropped: ', basename(x$file), ' due to missing headers.'), call. = FALSE) return(dplyr::tibble(fun = list(), params = list())) } col_names <- top[1 + skip_h] %>% stringr::str_trim(side = 'both') %>% stringr::str_split(pattern = dplyr::case_when(fun == 'csv' ~ ',', fun == 'csv2' ~ ';', fun == 'table' ~ '\\s+')) %>% purrr::flatten_chr() %>% stringr::str_trim() dplyr::tibble(fun = read_funs(fun), params = list(list(file = x$file, skip = skip, comment = comment, na = c(na, col_names), col_names = col_names, col_types = col_types, ...))) } #' Combine tables #' #' @param x A list containing the tables (`x$data`) to be #' combined, their names (`x$name`), their number of rows (`x$nrow`) #' and their respective index (`x$index`). #' #' @return A list containing `data` and `index` of the combined table. #' #' @keywords internal #' @export combine_tables <- function(x) { # Check for matching length if (length(unique(x$nrow)) > 1) { warning(c('Dropped ', stringr::str_c('`', x$name, '`', collapse = ', '), ' due to missmatch in row number.'), call. = FALSE) return(dplyr::tibble(data = list(), index = list())) } # Check for ID column if (!any(purrr::map_lgl(x$index, ~any(.$type == 'id')))) { warning(c('Dropped ', stringr::str_c('`', x$name, '`', collapse = ', '), ' due to missing required `ID` column.'), call. = FALSE) return(dplyr::tibble(data = list(), index = list())) } # Prepare the combined data # Note: here the data may contain duplicated columns so # we de-duplicate them in base R to avoid errors # with the tidyverse. tmp_df <- do.call("cbind", unname(x$data)) tmp_df <- tmp_df[, which(!duplicated(names(tmp_df))) ] %>% tibble::as_tibble() %>% tidyr::drop_na(dplyr::one_of('ID')) %>% list() # Combine tables dplyr::tibble(data = tmp_df, index = list(dplyr::bind_rows(x$index))) } #' Merge firstonly table with full length tables #' #' @param x A list containing the tables (`x$data`) to be #' merged, the firstonly flag (`x$firstonly`) and the #' indexes (`x$index`). #' @param quiet Should messages be displayed to the console. #' #' @return A list containing `data` and `index` of the merged table. #' #' @keywords internal #' @export merge_firstonly <- function(x, quiet) { if (nrow(x) == 1) { # No merge needed return(dplyr::tibble(data = x$data, index = x$index)) } else if (nrow(x) != 2) { warning(c(' * Something went wrong while consolidating: ', stringr::str_c(x[x$firstonly == TRUE, ]$index[[1]]$tables, collapse = ', ')), call. = FALSE) return(dplyr::tibble(data = list(), index = list())) } xdata <- x$data[x$firstonly == FALSE][[1]] ydata <- x$data[x$firstonly == TRUE][[1]] by_vars <- intersect(colnames(xdata), colnames(ydata)) msg(c(' * Joining by: ', stringr::str_c(by_vars, collapse = ', ')), quiet) dplyr::tibble(data = list(dplyr::left_join(x = xdata, y = ydata, by = by_vars)), index = x$index %>% dplyr::bind_rows() %>% list()) } #' Index table columns #' #' @param x A list containing the tables (`x$data`) to be #' combined along with their respective names (`x$name`). #' #' @return A tibble of the index. #' #' @keywords internal #' @export index_table <- function(x) { tab_type <- dplyr::case_when( stringr::str_detect(tolower(x$name), 'patab') ~ 'param', # model parameters stringr::str_detect(tolower(x$name), 'catab') ~ 'catcov', # categorical covariate stringr::str_detect(tolower(x$name), 'cotab') ~ 'contcov', # continuous covariate TRUE ~ 'na') x$data[[1]] %>% colnames() %>% dplyr::tibble(table = x$name, col = ., type = NA_character_, label = NA_character_, # Feature to be added in future releases units = NA_character_) %>% # Feature to be added in future releases dplyr::mutate(type = dplyr::case_when( .$col == 'ID' ~ 'id', .$col == 'DV' ~ 'dv', .$col == 'TIME' ~ 'idv', .$col == 'OCC' ~ 'occ', .$col == 'DVID' ~ 'dvid', .$col == 'AMT' ~ 'amt', .$col == 'MDV' ~ 'mdv', .$col == 'EVID' ~ 'evid', .$col == 'IPRED' ~ 'ipred', .$col == 'PRED' ~ 'pred', .$col %in% c('RES', 'WRES', 'CWRES', 'IWRES', 'EWRES', 'NPDE') ~ 'res', stringr::str_detect(.$col, 'ETA\\d+|ET\\d+') ~ 'eta', stringr::str_detect(.$col, '^A\\d+$') ~ 'a', TRUE ~ tab_type)) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/read_nm_tables.R
summarise_nm_model <- function(file, model, software, rounding) { sum <- dplyr::bind_rows( sum_software(software), # Software name sum_version(model, software), # Software version sum_file(file), # Model file sum_run(file), # Model run (model file without extension) sum_directory(file), # Model directory sum_reference(model, software), # Reference model sum_timestart(model, software), # Run start time sum_timestop(model, software), # Run stop time sum_probn(model, software), # Problem no. sum_label(model, software), # Model label sum_description(model, software), # Model description sum_input_data(model, software), # Model input data used sum_nobs(model, software), # Number of observations sum_nind(model, software), # Number of individuals sum_nsim(model, software), # Number of simulations sum_simseed(model, software), # Simulation seed sum_subroutine(model, software), # Des solver sum_runtime(model, software), # Estimation runtime sum_covtime(model, software), # Covariance matrix runtime sum_term(model, software), # Run termination message sum_warnings(model, software), # Run warnings (e.g. boundary) sum_errors(model, software), # Run errors (e.g termination error) sum_nsig(model, software), # Number of significant digits sum_condn(model, software, rounding), # Condition number sum_nesample(model, software), # Number of esample sum_esampleseed(model, software), # esample seed number sum_ofv(model, software), # Objective function value sum_method(model, software), # Estimation method or sim sum_shk(model, software, 'eps', rounding), # Epsilon shrinkage sum_shk(model, software, 'eta', rounding) # Eta shrinkage ) # Complete missing cases for consistency tmp <- sum %>% dplyr::filter(.$problem != 0) if (nrow(tmp) == 0) return(sum) tmp %>% tidyr::complete(!!!rlang::syms(c('problem', 'label')), fill = list(subprob = 0, value = 'na')) %>% dplyr::bind_rows(dplyr::filter(sum, sum$problem == 0)) %>% dplyr::arrange_at(.vars = c('problem', 'label', 'subprob')) %>% dplyr::mutate(descr = dplyr::case_when( .$label == 'software' ~ 'Software', .$label == 'version' ~ 'Software version', .$label == 'file' ~ 'Run file', .$label == 'run' ~ 'Run number', .$label == 'dir' ~ 'Run directory', .$label == 'ref' ~ 'Reference model', .$label == 'probn' ~ 'Problem number', .$label == 'timestart' ~ 'Run start time', .$label == 'timestop' ~ 'Run stop time', .$label == 'descr' ~ 'Run description', .$label == 'label' ~ 'Run label', .$label == 'data' ~ 'Input data', .$label == 'nobs' ~ 'Number of observations', .$label == 'nind' ~ 'Number of individuals', .$label == 'nsim' ~ 'Number of simulations', .$label == 'simseed' ~ 'Simulation seed', .$label == 'subroutine' ~ 'ADVAN', .$label == 'runtime' ~ 'Estimation runtime', .$label == 'covtime' ~ 'Covariance step runtime', .$label == 'term' ~ 'Termination message', .$label == 'warnings' ~ 'Run warnings', .$label == 'errors' ~ 'Run errors', .$label == 'nsig' ~ 'Number of significant digits', .$label == 'condn' ~ 'Condition number', .$label == 'nesample' ~ 'Number of ESAMPLE', .$label == 'esampleseed' ~ 'ESAMPLE seed number', .$label == 'ofv' ~ 'Objective function value', .$label == 'method' ~ 'Estimation method', .$label == 'epsshk' ~ 'Epsilon shrinkage', .$label == 'etashk' ~ 'Eta shrinkage')) %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'descr', 'label', 'value')) } # Default template for function output sum_tpl <- function(label, value) { dplyr::tibble(problem = 0, subprob = 0, label = label, value = value) } # Software name sum_software <- function(software) { sum_tpl('software', software) } # Software version sum_version <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::filter(.$problem == 0) %>% dplyr::filter(stringr::str_detect(.$code, 'NONLINEAR MIXED EFFECTS MODEL PROGRAM')) if (nrow(x) == 0) return(sum_tpl('version', 'na')) sum_tpl('version', stringr::str_match(x$code, 'VERSION\\s+(.+)$')[, 2]) } } # Model file name sum_file <- function(file) { sum_tpl('file', basename(file)) } # Model run name sum_run <- function(file) { sum_tpl('run', update_extension(basename(file), '')) } # Model file directory sum_directory <- function(file) { sum_tpl('dir', dirname(file)) } # Reference model sum_reference <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::filter(.$problem == 0) %>% dplyr::filter(stringr::str_detect(tolower(.$comment), stringr::regex('based on\\s*:', ignore_case = TRUE))) if (nrow(x) == 0) return(sum_tpl('ref', 'na')) sum_tpl('ref', stringr::str_match(x$comment, ':\\s*(.+)$')[1, 2]) # Note: only take the first match } } # Run start time sum_timestart <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::slice(1) %>% dplyr::filter(stringr::str_detect(.$code, '\\s+\\d{2}:\\d{2}:\\d{2}\\s+')) if (nrow(x) == 0) return(sum_tpl('timestart', 'na')) sum_tpl('timestart', x$code) } } # Run stop time sum_timestop <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::slice(nrow(model)) %>% dplyr::filter(stringr::str_detect(.$code, '\\s+\\d{2}:\\d{2}:\\d{2}\\s+')) if (nrow(x) == 0) return(sum_tpl('timestop', 'na')) sum_tpl('timestop', x$code) } } # Problem no. sum_probn <- function(model, software) { if (software == 'nonmem') { x <- unique(model$problem[model$problem != 0]) if (length(x) == 0) return(sum_tpl('probn', 'na')) dplyr::tibble( problem = x, subprob = 0, label = 'probn', value = as.character(x)) } } # Model Label sum_label <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::filter(.$subroutine == 'pro') if (nrow(x) == 0) return(sum_tpl('label', 'na')) x %>% dplyr::mutate(subprob = 0, label = 'label', value = as.character(.$code)) %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'label', 'value')) } } # Model description sum_description <- function(model, software) { if (software == 'nonmem') { x <- dplyr::filter(.data = model, model$level == 0) start <- which(stringr::str_detect(tolower(x$comment), stringr::regex('2.\\s*description\\s*:', ignore_case = TRUE))) if (length(start) == 1) { end <- which(stringr::str_detect(tolower(x$comment), '(3|x\\d)\\.\\s*\\w+')) end <- end[(end - start) > 0] end <- ifelse(length(end) == 0, nrow(x), min(end) - 1) x <- dplyr::slice(.data = x, seq(start, end)) %>% {stringr::str_replace(.$comment, '^\\s*;\\s*', '')} %>% stringr::str_c(collapse = ' ') %>% {sum_tpl('descr', stringr::str_match(., ':\\s*(.+)$')[, 2])} return(value = x) } sum_tpl('descr', 'na') } } # Input data sum_input_data <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::filter(.$subroutine == 'dat') %>% dplyr::distinct(!!rlang::sym('level'), .keep_all = TRUE) # Assumes that the data is on the first row if (nrow(x) == 0) return(sum_tpl('data', 'na')) x %>% dplyr::mutate(subprob = 0, label = 'data', value = stringr::str_match(.$code, '^\\s*?([^\\s]+)\\s+')[, 2]) %>% # Note: only take the first match dplyr::select(dplyr::one_of('problem', 'subprob', 'label', 'value')) } } # Number of observations sum_nobs <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::filter(.$subroutine == 'lst') %>% dplyr::filter(stringr::str_detect(.$code, stringr::fixed('TOT. NO. OF OBS RECS'))) if (nrow(x) == 0) return(sum_tpl('nobs', 'na')) x %>% dplyr::mutate(subprob = 0, label = 'nobs', value = stringr::str_extract(.$code, '\\d+')) %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'label', 'value')) } } # Number of individuals sum_nind <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::filter(.$subroutine == 'lst') %>% dplyr::filter(stringr::str_detect(.$code, stringr::fixed('TOT. NO. OF INDIVIDUALS'))) if (nrow(x) == 0) return(sum_tpl('nind', 'na')) x %>% dplyr::mutate(subprob = 0, label = 'nind', value = stringr::str_extract(.$code, '\\d+')) %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'label', 'value')) } } # Simulation number sum_nsim <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::filter(.$subroutine == 'sim') %>% dplyr::filter(stringr::str_detect(.$code, stringr::fixed('NSUB'))) if (nrow(x) == 0) return(sum_tpl('nsim', 'na')) x %>% dplyr::mutate(subprob = 0, label = 'nsim', value = stringr::str_match(.$code, 'NSUB.*=\\s*(\\d+)')[, 2]) %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'label', 'value')) } } # Simulation seed sum_simseed <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::filter(.$subroutine == 'sim') %>% dplyr::filter(stringr::str_detect(.$code, '\\(\\d+\\)')) if (nrow(x) == 0) return(sum_tpl('simseed', 'na')) x %>% dplyr::mutate(subprob = 0, label = 'simseed', value = stringr::str_match(.$code, '\\((\\d+)\\)')[, 2]) %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'label', 'value')) } } # DES solver sum_subroutine <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::filter(.$subroutine == 'sub') %>% dplyr::filter(stringr::str_detect(.$code, stringr::fixed('ADVAN'))) if (nrow(x) == 0) return(sum_tpl('subroutine', 'na')) x %>% dplyr::mutate(subprob = 0, label = 'subroutine', value = stringr::str_match(.$code, 'ADVAN(\\d+)')[, 2]) %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'label', 'value')) } } # Estimation runtime sum_runtime <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::filter(.$subroutine == 'lst') %>% dplyr::filter(stringr::str_detect(.$code, 'Elapsed estimation\\s+time')) if (nrow(x) == 0) return(sum_tpl('runtime', 'na')) x %>% dplyr::group_by_at(.vars = 'problem') %>% dplyr::mutate(subprob = (1:n()) - 1) %>% dplyr::ungroup() %>% dplyr::mutate(label = 'runtime', value = as.ctime(stringr::str_match(.$code, '([\\.\\d]+)')[, 2])) %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'label', 'value')) } } # Covariance matrix runtime sum_covtime <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::filter(.$subroutine == 'lst') %>% dplyr::filter(stringr::str_detect(.$code, 'Elapsed covariance\\s+time in seconds:\\s+\\d')) if (nrow(x) == 0) return(sum_tpl('covtime', 'na')) x %>% dplyr::mutate(subprob = 0, label = 'covtime', value = as.ctime(stringr::str_match(.$code, '([\\.\\d]+)')[, 2])) %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'label', 'value')) } } # Run termination sum_term <- function(model, software) { if (software == 'nonmem') { x <- dplyr::filter(model, model$subroutine == 'lst') start <- which(stringr::str_detect(x$code, stringr::fixed('0MINIMIZATION'))) end <- which(stringr::str_detect(x$code, stringr::fixed(" NO. OF FUNCTION EVALUATIONS USED:"))) if (length(start) == 0 | length(end) == 0 | length(start)!=length(end)) return(sum_tpl('term', 'na')) x %>% dplyr::slice(purrr::map2(start, end, ~seq(.x,.y)) %>% purrr::flatten_int()) %>% dplyr::group_by_at(.vars = 'problem') %>% tidyr::nest() %>% dplyr::ungroup() %>% dplyr::mutate(value = purrr::map_chr(.$data, function(y) { drop <- min(which(stringr::str_detect(y$code, 'NO. OF'))) dplyr::slice(.data = y, seq(1, (drop - 1))) %>% {stringr::str_trim(.$code)} %>% stringr::str_trunc(width = 56) %>% stringr::str_c(collapse = '\n') %>% stringr::str_replace('0MINIM', 'MINIM')})) %>% dplyr::mutate(subprob = 0, label = 'term') %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'label', 'value')) } } # Run warnings (e.g. boundary) sum_warnings <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::filter(.$subroutine == 'oth') %>% dplyr::filter(stringr::str_detect(.$code, 'WARNINGS AND ERRORS|\\(WARNING')) if (nrow(x) == 0) return(sum_tpl('warnings', 'na')) x %>% dplyr::mutate(problem = stringr::str_match(.$code, 'FOR PROBLEM\\s+(\\d+)')[, 2]) %>% tidyr::fill(!!rlang::sym('problem')) %>% dplyr::mutate(problem = as.numeric(.$problem)) %>% dplyr::filter(!stringr::str_detect(.$code, 'FOR PROBLEM\\s+(\\d+)')) %>% dplyr::mutate(code = stringr::str_trim(.$code)) %>% dplyr::mutate(code = stringr::str_trunc(.$code, width = 56)) %>% dplyr::distinct(!!!rlang::syms(c('problem', 'code'))) %>% dplyr::group_by_at(.vars = 'problem') %>% tidyr::nest() %>% dplyr::ungroup() %>% dplyr::mutate(value = purrr::map_chr(.$data, ~stringr::str_c(.$code, collapse = '\n'))) %>% dplyr::mutate(subprob = 0, label = 'warnings') %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'label', 'value')) } } # Run errors (e.g termination error) sum_errors <- function(model, software) { if (software == 'nonmem') { sum_tpl('errors', 'na') # To be added } } # Number of significant digits sum_nsig <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::filter(.$subroutine == 'lst') %>% dplyr::filter(stringr::str_detect(.$code, stringr::fixed('NO. OF SIG. DIGITS'))) if (nrow(x) == 0) return(sum_tpl('nsig', 'na')) x %>% dplyr::mutate(subprob = 0, label = 'nsig', value = stringr::str_match(.$code, ':\\s+([\\.\\d]+)')[, 2]) %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'label', 'value')) } } # Condition number sum_condn <- function(model, software, rounding) { if (software == 'nonmem') { x <- model %>% dplyr::filter(.$subroutine == 'lst') %>% dplyr::slice(which(stringr::str_detect(.$code, stringr::fixed('EIGENVALUES OF COR'))) + 4) if (nrow(x) == 0) return(sum_tpl('condn', 'na')) x %>% dplyr::group_by_at(.vars = 'problem') %>% tidyr::nest() %>% dplyr::ungroup() %>% dplyr::mutate(subprob = 0, label = 'condn', value = purrr::map_chr(.$data, function(x) { stringr::str_trim(x$code, side = 'both') %>% stringr::str_split(pattern = '\\s+') %>% purrr::flatten_chr() %>% as.numeric() %>% {max(.)/min(.)} %>% round(digits = rounding) %>% as.character()})) %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'label', 'value')) } } # Number of ESAMPLE (i.e. NPDE) sum_nesample <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::filter(.$subroutine == 'tab') %>% dplyr::filter(stringr::str_detect(.$code, stringr::fixed('ESAMPLE'))) if (nrow(x) == 0) return(sum_tpl('nesample', 'na')) x %>% dplyr::mutate(subprob = 0, label = 'nesample', value = stringr::str_match(.$code, 'ESAMPLE\\s*=\\s*(\\d+)')[, 2]) %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'label', 'value')) } } # ESAMPLE seed number sum_esampleseed <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::filter(.$subroutine == 'tab') %>% dplyr::filter(stringr::str_detect(.$code, stringr::fixed('SEED'))) if (nrow(x) == 0) return(sum_tpl('esampleseed', 'na')) x %>% dplyr::mutate(subprob = 0, label = 'esampleseed', value = stringr::str_match(.$code, 'SEED\\s*=\\s*(\\d+)')[, 2]) %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'label', 'value')) } } # Objective function value sum_ofv <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::filter(.$subroutine == 'lst') %>% dplyr::filter(stringr::str_detect(.$code, stringr::fixed('#OBJV'))) if (nrow(x) == 0) return(sum_tpl('ofv', 'na')) x %>% dplyr::mutate(value = stringr::str_match(.$code, '\\*\\s+(.+)\\s+\\*')[, 2]) %>% dplyr::group_by_at(.vars = 'problem') %>% dplyr::mutate(subprob = (1:n()) - 1, label = 'ofv') %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'label', 'value')) %>% dplyr::ungroup() } } # Estimation method or sim sum_method <- function(model, software) { if (software == 'nonmem') { x <- model %>% dplyr::filter(.$subroutine %in% c('sim', 'est')) %>% dplyr::filter(stringr::str_detect(.$code, '(?<!RAN)METH|NSUB')) if (nrow(x) == 0) return(sum_tpl('method', 'na')) x %>% dplyr::mutate(value = stringr::str_match(.$code, '(?<!RAN)METH[OD]*\\s*=\\s*([^\\s]+)')[, 2], inter = stringr::str_detect(.$code, '\\sINTER'), lapl = stringr::str_detect(.$code, '\\sLAPLA'), like = stringr::str_detect(.$code, '\\sLIKE')) %>% dplyr::mutate(value = dplyr::if_else(.$subroutine == 'sim', 'sim', .$value)) %>% dplyr::mutate(value = dplyr::case_when(.$value %in% c('0', 'ZERO') ~ 'FO', .$value == '1' ~ 'FOCE', stringr::str_detect(.$value, 'COND') ~ 'FOCE', TRUE ~ tolower(.$value))) %>% dplyr::mutate(value = stringr::str_c(stringr::str_to_lower(.$value), dplyr::if_else(.$inter, '-i', ''), dplyr::if_else(.$lapl, ' laplacian', ''), dplyr::if_else(.$like, ' likelihood', ''))) %>% dplyr::group_by_at(.vars = 'problem') %>% dplyr::mutate(subprob = (1:n()) - 1, label = 'method') %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'label', 'value')) %>% dplyr::ungroup() } } # Epsilon/Eta shrinkage sum_shk <- function(model, software, type, rounding) { if (software == 'nonmem') { # Get shrinkage from: 1) psn, 2) shr file 3) nonmem lst ## Method 3 (worse one) x <- model %>% dplyr::filter(.$subroutine == 'lst') %>% dplyr::group_by_at(.vars = 'problem') %>% tidyr::nest() %>% dplyr::ungroup() %>% dplyr::mutate(start = purrr::map_int(.x = .$data, .f = function(x) { stringr::str_c(stringr::str_to_upper(type), 'SHRINK[^V]') %>% stringr::regex(ignore_case = TRUE) %>% {stringr::str_detect(string = x$code, pattern = .)} %>% which() %>% {ifelse(length(.) == 0, NA_integer_, .)} })) %>% filter(!is.na(.$start)) if (nrow(x) == 0) return(sum_tpl(stringr::str_c(type, 'shk'), 'na')) x <- x %>% dplyr::mutate(rows = purrr::map2(.x = .$data, .y = .$start, .f = function(x, start) { x$code[start:nrow(x)] %>% {start + (which.max(stringr::str_detect(., '^\\s+\\D')[-1]) - 1)} %>% {seq(start, .)}})) %>% dplyr::mutate(code = purrr::map2_chr(.x = .$data, .y = .$rows, ~stringr::str_c(.x$code[.y], collapse = ' '))) %>% dplyr::mutate(code = stringr::str_match(.$code, '\\Q(%)\\E:*\\s*(.+)')[, 2]) %>% dplyr::mutate(code = stringr::str_split(.$code, '\\s+')) %>% dplyr::mutate(value = purrr::map(.$code, ~round(as.numeric(.), digits = rounding)), grouping = purrr::map(.$code, ~stringr::str_c(' [', 1:length(.), ']', sep = ''))) %>% dplyr::group_by_at(.vars = 'problem') %>% dplyr::mutate(subprob = (1:n()) - 1) %>% dplyr::ungroup() ## TEMP handling if (tidyr_new_interface()) { x <- x %>% tidyr::unnest(cols = dplyr::one_of('value', 'grouping')) } else { x <- x %>% tidyr::unnest(dplyr::one_of('value', 'grouping')) } ## END TEMP x %>% dplyr::filter(.$value != 100) %>% dplyr::mutate(value = stringr::str_c(.$value, .$grouping)) %>% dplyr::group_by_at(.vars = c('problem', 'subprob')) %>% tidyr::nest() %>% dplyr::ungroup() %>% dplyr::mutate(label = stringr::str_c(type, 'shk'), value = purrr::map_chr(.$data, ~stringr::str_c(.$value, collapse = ', '))) %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'label', 'value')) %>% dplyr::ungroup() } }
/scratch/gouwar.j/cran-all/cranData/xpose/R/summarise_nm_model.R
#' Summarizing xpose_data #' #' @description This function returns a summary of an \code{\link{xpose_data}} #' to the console. #' @param object An \code{xpose_data} object generated with \code{\link{xpose_data}}. #' @param .problem The problem to be used, by default returns the last one for each label. #' @param ... Ignored in this function #' #' @method summary xpose_data #' @examples #' summary(xpdb_ex_pk) #' #' @export summary.xpose_data <- function(object, .problem = NULL, ...) { order <- c('software', 'version', 'dir', 'file', 'run', 'ref', 'descr', 'timestart', 'timestop', 'probn', 'label', 'data', 'nind', 'nobs', 'subroutine', 'method', 'term', 'runtime', 'ofv', 'nsig', 'covtime', 'condn','etashk', 'epsshk', 'nsim', 'simseed', 'nesample', 'esampleseed', 'errors', 'warnings') out <- get_summary(object, .problem, only_last = FALSE) %>% dplyr::filter(.$value != 'na') %>% dplyr::slice(order(match(.$label, order))) %>% dplyr::group_by_at(.vars = c('problem', 'label', 'descr')) %>% tidyr::nest() %>% dplyr::ungroup() %>% dplyr::mutate(value = purrr::map_chr(.$data, function(x) { if (nrow(x) == 1) return(x$value) value <- stringr::str_c(x$value, ' (subprob no.', x$subprob, ')', sep = '') stringr::str_c(value, collapse = '\n') })) %>% dplyr::mutate(descr = stringr::str_pad(.$descr, width = max(nchar(.$descr)) + 2, 'right'), label = stringr::str_pad(.$label, width = max(nchar(.$label)), 'right'), value = stringr::str_replace_all(.$value, '\n', stringr::str_pad('\n', max(nchar(.$descr)) + max(nchar(.$label)) + 9, 'right'))) %>% dplyr::mutate(descr = stringr::str_c(.$descr, '@', .$label, '')) %>% dplyr::mutate(string = stringr::str_c(' -', .$descr, ':', .$value, sep = ' '), grouping = as.character(.$problem)) %>% dplyr::group_by_at(.vars = 'grouping') %>% tidyr::nest() %>% dplyr::ungroup() %>% {purrr::map(.$data, function(x) { x <- dplyr::filter(.data = x, !stringr::str_detect(x$descr, 'Problem number')) if (x$problem[1] == 0) { lab <- '[Global information]' } else { lab_row <- which(stringr::str_detect(x$descr, stringr::fixed('Run label'))) lab <- stringr::str_c('[', x$value[lab_row], ']', sep = '') x <- x[-lab_row, ] } cat('\nSummary for problem no.', x$problem[1], lab, '\n') cat(x$string, sep = '\n') })} }
/scratch/gouwar.j/cran-all/cranData/xpose/R/summary_xpose_data.R
#' Template titles #' #' @description Template titles can be used to create highly informative diagnostics plots. #' They can be applied to any plot title, subtitle, caption and the filename when saving #' with the \code{\link{xpose_save}} function. #' #' Template titles are defined via a single string containing key variables staring #' with a @ (e.g. @ofv) which will be replaced by their actual value when rendering the plot. #' For example '@run, @nobs observations in @nind subjects' would become 'run001, #' 1022 observations in 74 subjects' #' #' Many key variables are available: #' \describe{ #' \item{@condn}{Condition number} #' \item{@covtime}{Covariance matrix runtime} #' \item{@data}{Model input data used} #' \item{@descr}{Model description} #' \item{@dir}{Model directory} #' \item{@epsshk}{Epsilon shrinkage} #' \item{@errors}{Run errors (e.g termination error)} #' \item{@esampleseed}{ESAMPLE seed number (used in NPDE)} #' \item{@etashk}{Eta shrinkage} #' \item{@file}{Model file name} #' \item{@label}{Model label} #' \item{@method}{Estimation method or sim} #' \item{@nesample}{Number of ESAMPLE (used in NPDE)} #' \item{@nind}{Number of individuals} #' \item{@nobs}{Number of observations} #' \item{@nsig}{Number of significant digits} #' \item{@nsim}{Number of simulations} #' \item{@ofv}{Objective function value} #' \item{@page and @lastpage}{Are respectively the page number and the number #' of the last page when faceting on multiple pages} #' \item{@probn}{Problem number} #' \item{@plotfun}{Name of the plot function} #' \item{@ref}{Reference model} #' \item{@run}{Model run name} #' \item{@runtime}{Estimation/Sim runtime} #' \item{@software}{Software used (e.g. NONMEM)} #' \item{@simseed}{Simulation seed} #' \item{@subroutine}{Differential equation solver} #' \item{@timestart}{Run start time} #' \item{@timestop}{Run stop time} #' \item{@timeplot}{Time of the plot rendering} #' \item{@term}{Termination message} #' \item{@version}{Software version (e.g. 7.3)} #' \item{@vpcci}{VPC confidence interval} #' \item{@vpcdir}{VPC data directory} #' \item{@vpclloq}{VPC lower limit of quantification} #' \item{@vpcnsim}{Number of simulations for VPC} #' \item{@vpcpi}{VPC prediction interval} #' \item{@vpculoq}{VPC upper limit of quantification} #' \item{@warnings}{Run warnings (e.g. boundary)} #' \item{@x @y etc.}{Name of any ggplot2 variable used for mapping in an \code{aes()} type function} #' } #' @seealso \link{xpose_save} #' @examples #' # Defined when creating a plot #' dv_vs_ipred(xpdb_ex_pk, #' title = '@x vs. @y', #' subtitle = '@ofv, @nind subjects, @nobs obs.', #' caption = '@run, @descr') #' #' # Any label can be modified later on #' dv_vs_ipred(xpdb_ex_pk, aes(point_color = SEX, #' line_color = SEX)) + #' labs(title = 'This runs is: @descr', #' color = 'Color scale for @run', #' x = 'IPRED for @nind subjects', #' subtitle = NULL) #' #' @name template_titles NULL
/scratch/gouwar.j/cran-all/cranData/xpose/R/template_titles.R
#' Check tidyr version #' #' @description Check the version of tidyr to handle the gap between v0.8.3 and v1.0.0 #' #' @return the package version of tidyr #' #' @keywords internal #' @export tidyr_new_interface <- function() { utils::packageVersion("tidyr") > "0.8.99" }
/scratch/gouwar.j/cran-all/cranData/xpose/R/temporary.R
#' An additional set of themes for ggplot2 #' #' @description An additional set of complete ggplot2 themes intended to make ggplot2 more readable #' when used in presentation or publications. These themes also bring the \code{legend_position} option #' without having to call the ggplot2 theme() function to modify a complete theme. #' #' \itemize{ #' \item \code{theme_bw2}: Black and white theme inspired by a theme from Gunnar Yngman. #' \item \code{theme_readable}: Light grey theme, with dimmed background and grid lines #' intended to bring the focus on the data. #' } #' #' @param base_size Base font size. #' @param base_family Base font family. #' @param legend_position The position of legends defined as 'none', 'left', #' 'right', 'bottom', 'top', or a two-element numeric vector. #' #' @examples #' # With the gg_theme theme_readable() (default) #' dv_vs_ipred(xpdb_ex_pk, facets = 'SEX') #' #' # With the gg_theme theme_bw2() #' xpdb_ex_pk %>% #' update_themes(gg_theme = theme_bw2()) %>% #' dv_vs_ipred(facets = 'SEX') #' #' @name gg_themes #' @export theme_bw2 <- function(base_size = 11, base_family = '', legend_position = 'right') { ## ggplot2 v3.4.0 compatibility fix ## Fix to avoid triggering R CMD check errors element_line <- function(linewidth = NULL, ...) { if (utils::packageVersion("ggplot2") > "3.3.6") { asNamespace("ggplot2")$element_line(linewidth = linewidth, ...) } else { asNamespace("ggplot2")$element_line(size = linewidth, ...) } } element_rect <- function(linewidth = NULL, ...) { if (utils::packageVersion("ggplot2") > "3.3.6") { asNamespace("ggplot2")$element_rect(linewidth = linewidth, ...) } else { asNamespace("ggplot2")$element_rect(size = linewidth, ...) } } theme_bw(base_size = base_size, base_family = base_family) %+replace% theme(plot.title = element_text(face = 'bold', size = rel(1.2), hjust = 0, vjust = 1, margin = margin(b = base_size/2 * 1.2)), strip.text = element_text(color = 'white', size = rel(0.8)), strip.background = element_rect(color = 'black', fill = 'black'), legend.position = legend_position, legend.key = element_blank(), panel.grid.minor = element_blank(), panel.grid.major = element_line(color = 'grey90', linewidth = 0.25), plot.margin = grid::unit(c(0.01 ,0.01, 0.01, 0.01), 'npc'), panel.background = element_rect(color = 'black', fill = 'white', linewidth = 0.1), complete = TRUE) } #' @rdname gg_themes #' @export theme_readable <- function(base_size = 11, base_family = '', legend_position = 'right') { ## ggplot2 v3.4.0 compatibility fix ## Fix to avoid triggering R CMD check errors element_line <- function(linewidth = NULL, ...) { if (utils::packageVersion("ggplot2") > "3.3.6") { asNamespace("ggplot2")$element_line(linewidth = linewidth, ...) } else { asNamespace("ggplot2")$element_line(size = linewidth, ...) } } theme_gray(base_size = base_size, base_family = base_family) %+replace% theme(plot.title = element_text(face = 'bold', size = rel(1.2), hjust = 0, vjust = 1, margin = margin(b = base_size/2 * 1.2)), strip.background = element_rect(color = NA, fill = 'grey88'), axis.text = element_text(size = rel(0.8), colour = 'black'), legend.position = legend_position, legend.key = element_blank(), panel.background = element_rect(color = NA, fill = 'grey95'), panel.grid.minor = element_blank(), panel.grid.major = element_line(color = 'grey88', linewidth = 0.25), plot.margin = grid::unit(c(0.01 ,0.01, 0.01, 0.01), 'npc'), complete = TRUE) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/themes_gg.R
#' A set of xpose themes #' #' @description xpose themes are used to consistently apply a set of preference for the plot geoms #' (e.g. color scales, point size, etc.) whereas ggplot2 theme focus on the plot background, axes, #' titles etc. #' #' \itemize{ #' \item \code{theme_xp_default}: The default xp_theme in xpose #' \item \code{theme_xp_xpose4}: An xp_theme that makes xpose look like xpose4. #' } #' #' @examples #' # With the xp_theme theme_xp_default() (default) #' dv_vs_ipred(xpdb_ex_pk, facets = 'SEX') #' #' # With the xp_theme theme_xp_xpose4() #' xpdb_ex_pk %>% #' update_themes(xp_theme = theme_xp_xpose4()) %>% #' dv_vs_ipred(facets = 'SEX') #' #' @name xp_themes #' @export theme_xp_default <- function() { tmp_theme <- list( # General rounding = 1, title_suffix = '', subtitle_suffix = '', caption_suffix = '', tag_suffix = '', # Panels facets = NULL, ncol = NULL, nrow = NULL, page = NULL, scales = 'free', shrink = TRUE, labeller = labeller(.default = label_both, .multi_line = FALSE), as.table = TRUE, switch = NULL, drop = TRUE, dir = 'h', strip.position = 'top', margins = FALSE, space = 'fixed', byrow = TRUE, # Guide guide_alpha = 1, guide_color = 'grey70', guide_linetype = 'solid', guide_linewidth = 0.8, # Line line_alpha = 0.7, line_color = 'grey20', line_linetype = 'solid', line_linewidth = 0.5, # Point point_alpha = 0.7, point_color = 'grey20', point_fill = NA, point_shape = 19, point_size = 2.5, point_stroke = 0, # Smooth smooth_alpha = 0.4, smooth_color = 'deepskyblue2', smooth_fill = 'deepskyblue2', smooth_linetype = 1, smooth_method = 'loess', smooth_se = FALSE, smooth_linewidth = 1, smooth_weight = 1, # Text text_alpha = 0.7, text_angle = 0, text_color = 'grey33', text_family = '', text_fontface = 'plain', text_lineheight = 1.2, text_size = 3.1, text_hjust = 0.5, # Change not recommended if type = 't' is used text_vjust = 0.5, # Change not recommended if type = 't' is used # Density density_alpha = 0.6, density_color = NA, density_fill = 'grey35', density_weight = 1, density_linewidth = 0.5, density_linetype = 1, # Histogram histogram_alpha = 0.6, histogram_color = NA, histogram_fill = 'grey35', histogram_linewidth = 0.5, histogram_bins = 10, # Rug rug_alpha = 0.8, rug_color = 'grey35', rug_linetype = 1, rug_linewidth = 0.3, # Area area_alpha = 0.6, area_color = NA, area_fill = 'grey35', area_linewidth = 0.5, area_linetype = 1 ) ## ggplot2 v3.4.0 compatibility fix if (utils::packageVersion("ggplot2") < "3.4.0") { names(tmp_theme)[names(tmp_theme) == "line_linewidth"] <- "line_size" names(tmp_theme)[names(tmp_theme) == "rug_linewidth"] <- "rug_size" names(tmp_theme)[names(tmp_theme) == "area_linewidth"] <- "area_size" names(tmp_theme)[names(tmp_theme) == "smooth_linewidth"] <- "smooth_size" names(tmp_theme)[names(tmp_theme) == "abline_linewidth"] <- "abline_size" names(tmp_theme)[names(tmp_theme) == "density_linewidth"] <- "density_size" names(tmp_theme)[names(tmp_theme) == "histogram_linewidth"] <- "histogram_size" } as.xpose.theme(tmp_theme) } #' @rdname xp_themes #' @export theme_xp_xpose4 <- function() { tmp_theme <- list( # General rounding = 1, title_suffix = '', subtitle_suffix = '', caption_suffix = '', tag_suffix = '', # Panels facets = NULL, ncol = NULL, nrow = NULL, page = NULL, scales = 'free', shrink = TRUE, labeller = labeller(.default = label_both, .multi_line = FALSE), as.table = TRUE, switch = NULL, drop = TRUE, dir = 'h', strip.position = 'top', margins = FALSE, space = 'fixed', byrow = TRUE, # Guide guide_alpha = NA, guide_color = 'black', guide_linetype = 'solid', guide_linewidth = 0.5, # Line line_alpha = NA, line_color = 'blue', line_linetype = 'solid', line_linewidth = 0.5, # Point point_alpha = NA, point_color = 'blue', point_fill = NA, point_shape = 1, point_size = 2, point_stroke = 0.5, # Smooth smooth_alpha = NA, smooth_color = 'red', smooth_fill = 'red', smooth_linetype = 1, smooth_method = 'loess', smooth_se = FALSE, smooth_linewidth = 1, smooth_weight = 1, # Text text_alpha = NA, text_angle = 0, text_color = 'black', text_family = '', text_fontface = 'plain', text_lineheight = 1.2, text_size = 3.1, text_hjust = 0.5, # Change not recommended if type = 't' is used text_vjust = 0.5, # Change not recommended if type = 't' is used # Density density_alpha = NA, density_color = 'black', density_fill = NA, density_weight = 1, density_linewidth = 0.5, density_linetype = 2, # Histogram histogram_alpha = NA, histogram_color = 'black', histogram_fill = 'cyan', histogram_linewidth = 0.5, histogram_bins = 10, # Rug rug_alpha = NA, rug_color = 'black', rug_linetype = 1, rug_linewidth = 0.3, # Area area_alpha = NA, area_color = NA, area_fill = 'grey35', area_linewidth = 0.5, area_linetype = 1 ) ## ggplot2 v3.4.0 compatibility fix if (utils::packageVersion("ggplot2") < "3.4.0") { names(tmp_theme)[names(tmp_theme) == "line_linewidth"] <- "line_size" names(tmp_theme)[names(tmp_theme) == "rug_linewidth"] <- "rug_size" names(tmp_theme)[names(tmp_theme) == "area_linewidth"] <- "area_size" names(tmp_theme)[names(tmp_theme) == "smooth_linewidth"] <- "smooth_size" names(tmp_theme)[names(tmp_theme) == "abline_linewidth"] <- "abline_size" names(tmp_theme)[names(tmp_theme) == "density_linewidth"] <- "density_size" names(tmp_theme)[names(tmp_theme) == "histogram_linewidth"] <- "histogram_size" } as.xpose.theme(tmp_theme) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/themes_xp.R
#' Mean and variance of tranformed parameters #' #' @description The function calculates the mean and variance of function of parameters #' #' @param formula A formula describing the transformation. #' @param mu Vector of mean values for the variables in formula. #' @param sigma Covariance matrix for the variables in formula. #' @param method A string indicating which method to use for the calculation. #' @param samples Number of Monte-Carlo samples for method "mc" #' #' @return A list with entries `mean`, `variance` and `rse` #' @examples #' # Mean, variance and rse for sqrt of variable with mean 1 and variance 0.01 #' transform_prm(~sqrt(a), mu = c(a = 1), sigma = c(a = 0.01)) #' #' @keywords internal #' @export transform_prm <- function(formula, mu, sigma, method = 'delta', samples = 1000) { if (!rlang::is_formula(formula)) { stop('Argument `formula` needs to be a formula', call. = FALSE) } variables <- all.vars(formula) if (!all(variables %in% names(mu))) { stop('A mean value needs to be supplied for each variable.', call. = FALSE) } # if(NROW(sigma)!=length(variables) || NCOL(sigma)!=length(variables)) { # stop('Argument `sigma` needs to be a matrix with size equal to the number of variables.', call. = FALSE) # } ex <- formula[[2]] if (NROW(sigma) == 1) { tmp <- diag(sigma, NROW(sigma)) rownames(tmp) <- colnames(tmp) <- names(sigma) sigma <- tmp } if (!all(variables %in% rownames(sigma))) { stop('A variance value needs to be supplied for each variable.', call. = FALSE) } # ensure mu and sigma have same order as variable list mu <- mu[variables, drop = FALSE] sigma <- sigma[variables, variables, drop = FALSE] if (method == 'delta') { t_mean <- stats::deriv(ex, variables) %>% eval(envir = as.list(mu)) grad <- attr(t_mean, 'gradient') attr(t_mean, 'gradient') <- NULL t_var <- {grad %*% sigma %*% t(grad)}[1, 1] return(list(mean = t_mean, variance = t_var, rse = sqrt(t_var)/t_mean)) } else if (method == 'mc') { if (!requireNamespace('mvtnorm', quietly = TRUE)) { stop('Package `mvtnorm` needs to installed for this method to work.', call. = FALSE) } mvtnorm::rmvnorm(samples, mean = mu, sigma = sigma) %>% tibble::as_tibble() %>% dplyr::mutate(f = eval(ex, .)) %>% dplyr::summarize(mean = mean(.$f, na.rm = TRUE), variance = stats::var(.$f, na.rm = TRUE)) %>% dplyr::mutate(rse = sqrt(.$variance)/.$mean) %>% purrr::transpose() %>% dplyr::first() } else { stop('Method ', method, ' is not available.', call. = FALSE) } }
/scratch/gouwar.j/cran-all/cranData/xpose/R/transform_parameters.R
#' Create xpose theme #' #' @description Create an xpose theme. This function will update the theme of an #' xpdb object. All plots generated with this xpdb will automatically use the #' defined xpose (\code{xp_theme}) and ggplot2 (\code{gg_theme}) themes. #' #' @param xpdb An \code{xpose_data} object generated with #' \code{\link{xpose_data}}. #' @param gg_theme A complete ggplot2 theme object (e.g. #' \code{\link[ggplot2]{theme_classic}}), a function returning a complete #' ggplot2 theme, or a change to the current \code{gg_theme}. #' @param xp_theme A complete xpose theme object (e.g. #' \code{\link{theme_xp_default}}) or a list of modifications to the current #' \code{xp_theme} (e.g. \code{list(point_color = 'red', line_linetype = #' 'dashed')}). #' @param quiet Logical, if \code{FALSE} messages are printed to the console. #' #' @examples #' # Before default theme #' dv_vs_ipred(xpdb_ex_pk, facets = 'SEX') #' #' # Updating the gg_theme and xp_theme #' xpdb_ex_pk %>% #' update_themes(gg_theme = theme(legend.position = 'top'), #' xp_theme = list(point_color = 'blue', #' line_color = 'blue')) %>% #' dv_vs_ipred(facets = 'SEX') #' #' @export update_themes <- function(xpdb = NULL, gg_theme = NULL, xp_theme = NULL, quiet) { # Check input check_xpdb(xpdb, check = FALSE) if (missing(quiet)) quiet <- xpdb$options$quiet # Replace/Update gg_theme if (is.function(gg_theme) || is.theme(gg_theme)) { if (is.function(gg_theme) || attr(gg_theme, 'complete')) { attr(gg_theme, 'theme') <- as.character(substitute(gg_theme)) xpdb$gg_theme <- gg_theme } else if (is.function(xpdb$gg_theme)) { gg_theme_attr <- paste(attr(xpdb$gg_theme, 'theme'), '(modified)') xpdb$gg_theme <- do.call(xpdb$gg_theme, args = list()) + gg_theme attr(xpdb$gg_theme, 'theme') <- gg_theme_attr } else { attr(xpdb$gg_theme, 'theme') <- paste(attr(xpdb$gg_theme, 'theme'), '(modified)') xpdb$gg_theme <- xpdb$gg_theme + gg_theme } } else if (!is.null(gg_theme) & !is.theme(gg_theme)) { msg('`gg_theme` argument not used. Reason: invalid input.', quiet) } # Replace/Update xp_theme if (!is.null(xp_theme)) { if (is.xpose.theme(xp_theme)) { attr(xp_theme, 'theme') <- as.character(substitute(xp_theme)) xpdb$xp_theme <- xp_theme } else if (!is.null(names(xp_theme))) { for (x in seq_along(xp_theme)) { xpdb$xp_theme[[names(xp_theme[x])]] <- xp_theme[[x]] # Beware drops NULL elements } attr(xpdb$xp_theme, 'theme') <- paste(attr(xpdb$xp_theme, 'theme'), '(modified)') xpdb$xp_theme <- as.xpose.theme(xpdb$xp_theme) } else { msg('`xp_theme` argument not used. Reason: invalid input.', quiet) } } as.xpdb(xpdb) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/update_themes.R
#' @importFrom dplyr filter #' @export dplyr::filter #' @importFrom dplyr slice #' @export dplyr::slice #' @importFrom dplyr distinct #' @export dplyr::distinct #' @importFrom dplyr mutate #' @export dplyr::mutate #' @importFrom dplyr select #' @export dplyr::select #' @importFrom dplyr rename #' @export dplyr::rename #' @importFrom dplyr group_by #' @export dplyr::group_by #' @importFrom dplyr ungroup #' @export dplyr::ungroup #' @importFrom dplyr summarize #' @export dplyr::summarize #' @importFrom dplyr summarise #' @export dplyr::summarise #' @importFrom purrr %>% #' @export purrr::`%>%` #' @importFrom ggforce facet_wrap_paginate #' @export ggforce::facet_wrap_paginate #' @importFrom ggforce facet_grid_paginate #' @export ggforce::facet_grid_paginate #' Test for xpose_theme class #' #' @description Reports whether x is an `xpose_theme` object #' #' @param x An object to be tested. #' #' @return Logical value, `TRUE` for `xpose_theme` class #' and `FALSE` otherwise. #' #' @keywords internal #' @export is.xpose.theme <- function(x) { inherits(x, 'xpose_theme') } #' Convert an object to `xpose_theme` class #' #' @description Adds `xpose_theme` attribute to an object #' #' @param x An object to be modified. #' #' @return x with `xpose_theme` class. #' #' @keywords internal #' @export as.xpose.theme <- function(x) { if (!is.xpose.theme(x)) { structure(x, class = c('xpose_theme', 'uneval')) } else { x } } #' Test for xpose_data class #' #' @description Reports whether x is an `xpose_data` object #' #' @param x An object to be tested. #' #' @return Logical value, `TRUE` for `xpose_data` class #' and `FALSE` otherwise. #' #' @keywords internal #' @export is.xpdb <- function(x) { inherits(x, 'xpose_data') } #' Convert an object to `xpose_data` class #' #' @description Adds `xpose_data` attribute to an object #' #' @param x An object to be modified. #' #' @return x with `xpose_data` class. #' #' @keywords internal #' @export as.xpdb <- function(x) { if (!is.xpdb(x)) { structure(x, class = c('xpose_data', 'uneval')) } else { x } } #' Test for nm_model class #' #' @description Reports whether x is a `nm_model` object #' #' @param x An object to be tested. #' #' @return Logical value, `TRUE` for `nm_model` class #' and `FALSE` otherwise. #' #' @keywords internal #' @export is.nm.model <- function(x) { inherits(x, 'nm_model') } #' Test for nm_table_list class #' #' @description Reports whether x is a `nm_table_list` object #' #' @param x An object to be tested. #' #' @return Logical value, `TRUE` for `nm_table_list` class #' and `FALSE` otherwise. #' #' @keywords internal #' @export is.nm.table.list <- function(x) { inherits(x, 'nm_table_list') } #' Convert an object to `nm_table_list` class #' #' @description Adds `nm_table_list` attribute to an object #' #' @param x An object to be modified. #' #' @return x with `nm_table_list` class. #' #' @keywords internal #' @export as.nm.table.list <- function(x) { if (!is.nm.table.list(x)) { structure(x, class = c('nm_table_list', class(x))) } else { x } } #' Test for xpose_plot class #' #' @description Reports whether x is a `xpose_plot` object #' #' @param x An object to be tested. #' #' @return Logical value, `TRUE` for `xpose_plot` class #' and `FALSE` otherwise. #' #' @keywords internal #' @export is.xpose.plot <- function(x) { inherits(x, 'xpose_plot') } #' Convert an object to `xpose_plot` class #' #' @description Adds `xpose_plot` attribute to an object #' #' @param x An object to be modified. #' #' @return x with `xpose_plot` class. #' #' @keywords internal #' @export as.xpose.plot <- function(x) { if (!is.xpose.plot(x)) { structure(x, class = c('xpose_plot', class(x))) } else { x } } #' Test for formula class #' #' @description Reports whether x is a `formula` object #' #' @param x An object to be tested. #' #' @return Logical value, `TRUE` for `formula` class #' and `FALSE` otherwise. #' #' @keywords internal #' @export is.formula <- function(x) { inherits(x, 'formula') } #' Time converter #' #' @description Convert seconds to hh:mm:ss #' #' @param x A string ('character' or 'numeric') of time in seconds. #' #' @return A string of time in `hh:mm:ss`. #' #' @keywords internal #' @export as.ctime <- function(x) { x <- round(as.numeric(x), 0) sprintf("%02d:%02d:%02d", x %/% 3600, x %% 3600 %/% 60, x %% 60) } #' Message function #' #' @description Message function with quiet option inspired from `ronkeizer/vpc`. #' #' @param txt A string for the message. #' @param quiet Should messages be displayed to the console. #' #' @return Silent when quiet is `TRUE` or a message is quiet is `FALSE`. #' #' @keywords internal #' @export msg <- function(txt, quiet = TRUE) { if (!quiet) message(txt) } #' Generate clean file paths #' #' @description Wrapper around `file.path` that cleans trailing forward #' slash and missing `dir`. #' #' @param dir A string or vector of strings containing the directory path. #' @param file A file name or vector containing the file names. #' #' @return A string or vector of string of the full file path. #' #' @keywords internal #' @export file_path <- function(dir, file) { if (is.null(dir)) return(file) # Remove trailing forward slash dir <- stringr::str_replace(dir, '\\/+$', '') file.path(dir, file) } #' Get file extension #' #' @description Extract file extension from the filename string. #' #' @param x A string or vector of strings containing the filenames with the extension. #' @param dot Logical, if `TRUE` the returned value will contain the #' dot (e.g `.mod`) else only the extension itself will be returned (e.g. `mod`). #' #' @return A string or vector of string of the file(s) extension. #' #' @keywords internal #' @export get_extension <- function(x, dot = TRUE) { x <- stringr::str_extract(x, '\\.[[:alnum:]]+$') x[is.na(x)] <- '' if (!dot) x <- stringr::str_replace_all(x, '\\.', '') x } #' Generate extension string #' #' @description Generate consistent extension strings by adding dot #' prefix whenever necessary. #' #' @param x A string or vector of strings containing the extension to be standardized. #' #' @return A string or vector of strings of extension(s). #' #' @keywords internal #' @export make_extension <- function(x) { dplyr::if_else(!stringr::str_detect(x, '^\\..+'), stringr::str_c('.', x), x) } #' Update file extension #' #' @description Change the extension of a file. #' #' @param x A string or vector of strings containing the file name to be modified. #' @param ext A string or vector of strings containing the name of the new extension(s). #' #' @return A string or vector of strings of file name(s). #' #' @keywords internal #' @export update_extension <- function(x, ext) { stringr::str_replace(x, '\\.[[:alnum:]]+$', ext) } #' Get software from the xpdb #' #' @description Get the name of the modeling softwre on which the xpdb was created #' #' @param xpdb An xpose database object. #' #' @return The name of a modeling tool. #' #' @keywords internal #' @export software <- function(xpdb) { x <- get_summary(xpdb) x <- x$value[x$label == 'software'] if (is.null(x)) x <- 'na' x }
/scratch/gouwar.j/cran-all/cranData/xpose/R/utils.R
#' List available variables #' #' @description Function listing all available variables in an xpdb object. #' #' @param xpdb An \code{xpose_data} object from which the model code will be extracted. #' @param .problem The problem to be used, by lists all available problems. #' #' @seealso \code{\link{set_var_types}} #' @examples #' list_vars(xpdb_ex_pk) #' @export list_vars <- function(xpdb, .problem = NULL) { # Check input check_xpdb(xpdb, check = 'data') x <- xpdb$data if (!is.null(.problem)) { if (!all(.problem %in% x$problem)) { stop('Problem no.', stringr::str_c(.problem[!.problem %in% x$problem], collapse = ', '), ' not found in the data.', call. = FALSE) } x <- x[x$problem %in% .problem, ] } order <- c('id', 'dv', 'idv', 'dvid', 'occ', 'amt', 'evid', 'mdv', 'pred', 'ipred', 'param', 'eta', 'res', 'catcov', 'contcov', 'a', 'na') x <- x %>% dplyr::mutate(grouping = as.integer(.$problem)) %>% dplyr::group_by_at(.vars = 'grouping') %>% tidyr::nest() %>% dplyr::ungroup() %>% {purrr::map(.$data, function(df) { cat('\nList of available variables for problem no.', df$problem[1], '\n') df$index[[1]] %>% dplyr::group_by_at(.vars = 'type') %>% tidyr::nest() %>% dplyr::ungroup() %>% dplyr::mutate(string = purrr::map_chr(.$data, ~stringr::str_c(unique(.$col), collapse = ', ')), descr = dplyr::case_when(.$type == 'id' ~ 'Subject identifier (id)', .$type == 'occ' ~ 'Occasion flag (occ)', .$type == 'na' ~ 'Not attributed (na)', .$type == 'amt' ~ 'Dose amount (amt)', .$type == 'idv' ~ 'Independent variable (idv)', .$type == 'ipred' ~ 'Model individual predictions (ipred)', .$type == 'pred' ~ 'Model typical predictions (pred)', .$type == 'res' ~ 'Residuals (res)', .$type == 'evid' ~ 'Event identifier (evid)', .$type == 'dv' ~ 'Dependent variable (dv)', .$type == 'catcov' ~ 'Categorical covariates (catcov)', .$type == 'contcov' ~ 'Continuous covariates (contcov)', .$type == 'param' ~ 'Model parameter (param)', .$type == 'eta' ~ 'Eta (eta)', .$type == 'a' ~ 'Compartment amounts (a)', .$type == 'dvid' ~ 'DV identifier (dvid)', .$type == 'mdv' ~ 'Missing dependent variable (mdv)')) %>% dplyr::mutate(descr = stringr::str_pad(.$descr, 37, 'right')) %>% dplyr::slice(order(match(.$type, order))) %>% {stringr::str_c(' -', .$descr, ':', .$string, sep = ' ')} %>% cat(sep = '\n')})} }
/scratch/gouwar.j/cran-all/cranData/xpose/R/vars_list.R
#' Set variable type, label or units #' #' @description Function designed to change the type, label or unit associated with variables. #' #' @param xpdb An \code{xpose_data} object. #' @param .problem The problem number to which the edits will be applied. #' @param ... Specifications of the edits to be made to the xpdb index. Edits are made as #' type and variable pairs e.g. idv = 'TAD' will assign TAD to the type idv (independent variable). #' @param auto_factor With \code{set_var_types} only. If \code{TRUE} new columns assigned to the type 'catcov' will be converted to #' factor. #' @param quiet Logical, if \code{FALSE} messages are printed to the console. #' #' @section Recognized variable types: #' \itemize{ #' \item a: Compartments' amount #' \item amt: Dose amount #' \item catcov: Categorical covariate #' \item contcov: Continuous covariate #' \item dv: Dependent variable #' \item dvid: DV identifier #' \item eta: Eta #' \item evid: Event identifier #' \item id: Subject identifier #' \item idv: Independent variable #' \item ipred: Individual model predictions #' \item mdv: Missing dependent variable #' \item na: Not attributed #' \item occ: Occasion flag #' \item param: Model parameter #' \item pred: Typical model predictions #' \item res: Residuals #' } #' #' @return An xpose_data object #' @seealso \code{\link{list_vars}} #' @examples #' # Change variable type #' xpdb_2 <- set_var_types(xpdb_ex_pk, .problem = 1, idv = 'TAD') #' #' # Change labels #' xpdb_2 <- set_var_labels(xpdb_2, .problem = 1, ALAG1 = 'Lag time', CL = 'Clearance', V = 'Volume') #' #' # Change units #' xpdb_2 <- set_var_units(xpdb_2, .problem = 1, ALAG1 = 'h', CL = 'L/h', V = 'L') #' #' @name set_vars #' @export set_var_types <- function(xpdb, .problem = NULL, ..., auto_factor = TRUE, quiet) { # Check input check_xpdb(xpdb, check = 'data') if (missing(quiet)) quiet <- xpdb$options$quiet dat <- xpdb$data if (!is.null(.problem) && !all(.problem %in% dat$problem)) { stop('Problem no.', stringr::str_c(.problem[!.problem %in% dat$problem], collapse = ', '), ' not found in model output data.', call. = FALSE) } if (is.null(.problem)) .problem <- unique(dat$problem) args <- c(...) if (is.null(args)) return(xpdb) args <- args %>% dplyr::tibble(col = ., type = names(.)) %>% dplyr::mutate(type = stringr::str_replace(.$type, '\\d$', '')) dat <- dat %>% dplyr::mutate(grouping = .$problem) %>% dplyr::group_by_at(.vars = 'grouping') ## TEMP handling if (tidyr_new_interface()) { dat <- dat %>% tidyr::nest(tmp = -dplyr::one_of('grouping')) } else { dat <- dat %>% tidyr::nest(.key = 'tmp') } ## END TEMP xpdb$data <- dat %>% dplyr::ungroup() %>% dplyr::mutate(out = purrr::map_if(.$tmp, .$grouping %in% .problem, function(x, args, quiet) { # Get the index index <- x$index[[1]] # Check for missmatches if (any(!args$col %in% index$col)) { warning(c('In $prob no.', x$problem, ' columns: ', stringr::str_c(args$col[!args$col %in% index$col], collapse = ', '), ' not present in the data.'), call. = FALSE) args <- dplyr::filter(.data = args, args$col %in% index$col) } # Remove previous index when only one variable can be used at the time single_type <- c('amt', 'dv', 'dvid', 'evid', 'id', 'idv', 'ipred', 'mdv', 'pred') single_type <- single_type[single_type %in% args$type] if (length(single_type) > 0) index$type[index$type %in% single_type] <- 'na' # Replace the matching values for (repl in 1:nrow(args)) { index$type[index$col == args$col[repl]] <- args$type[repl] } x$index[[1]] <- index # Change categorical covariates to factor if (any(args$type == 'catcov') && auto_factor) { col_to_factor <- colnames(x$data[[1]]) %in% args$col[args$type == 'catcov'] x$data[[1]] <- x$data[[1]] %>% dplyr::mutate_if(col_to_factor, as.factor) } # Output new index x }, args = args, quiet = quiet)) %>% tidyr::unnest(dplyr::one_of('out')) %>% dplyr::select(dplyr::one_of('problem', 'simtab', 'index', 'data', 'modified')) as.xpdb(xpdb) } set_var_generic <- function(xpdb, .problem = NULL, what = NULL, ..., quiet) { # Check input check_xpdb(xpdb, check = 'data') if (missing(quiet)) quiet <- xpdb$options$quiet dat <- xpdb$data if (!is.null(.problem) && !all(.problem %in% dat$problem)) { stop('Problem no.', stringr::str_c(.problem[!.problem %in% dat$problem], collapse = ', '), ' not found in model output data.', call. = FALSE) } if (is.null(.problem)) .problem <- unique(dat$problem) args <- c(...) if (is.null(args)) return(xpdb) args <- dplyr::tibble(col = names(args), variable = args) dat <- dat %>% dplyr::mutate(grouping = .$problem) %>% dplyr::group_by_at(.vars = 'grouping') ## TEMP handling if (tidyr_new_interface()) { dat <- dat %>% tidyr::nest(tmp = -dplyr::one_of('grouping')) } else { dat <- dat %>% tidyr::nest(.key = 'tmp') } ## END TEMP xpdb$data <- dat %>% dplyr::ungroup() %>% dplyr::mutate(out = purrr::map_if(.$tmp, .$grouping %in% .problem, function(x, args, quiet) { # Get the index index <- x$index[[1]] # Check for missmatches if (any(!args$col %in% index$col)) { warning(c('In $prob no.', x$problem, ' columns: ', stringr::str_c(args$col[!args$col %in% index$col], collapse = ', '), ' not present in the data.'), call. = FALSE) args <- dplyr::filter(.data = args, args$col %in% index$col) } # Replace the matching values index[match(args$col, index$col), what] <- args$variable x$index[[1]] <- index # Output new index x }, args = args, quiet = quiet)) %>% tidyr::unnest(dplyr::one_of('out')) %>% dplyr::select(dplyr::one_of('problem', 'simtab', 'index', 'data', 'modified')) as.xpdb(xpdb) } #' @rdname set_vars #' @export set_var_labels <- function(xpdb, .problem = NULL, ..., quiet) { set_var_generic(xpdb = xpdb, .problem = .problem, quiet = quiet, what = 'label', ...) } #' @rdname set_vars #' @export set_var_units <- function(xpdb, .problem = NULL, ..., quiet) { set_var_generic(xpdb = xpdb, .problem = .problem, quiet = quiet, what = 'units', ...) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/vars_set.R
#' Visual predictive checks data #' #' @description Generate visual predictive checks (VPC) data #' #' @param xpdb An xpose database object. #' @param opt A list of options regarding binning, pi and ci computation. #' For more information see \code{\link{vpc_opt}}. #' @param stratify Either a character string or a formula to stratify the data. For 'categorical' vpcs the #' stratification fixed to the different categories. #' @param vpc_type A string specifying the type of VPC to be created, can be one of: #' 'continuous', 'categorical', 'censored' or 'time-to-event'. #' @param psn_folder Specify a PsN-generated VPC-folder. #' @param psn_bins Only used with argument \code{psn_folder}. If \code{TRUE} bins will be inputed from the #' PsN vpc_bins.txt file. If \code{FALSE} (default) bins will be re-calculated in R. Note that when #' \code{psn_bins = TRUE} only the first bin array will be used and applied to all panels as it is not #' currently possible to define per panel binning in xpose. In addition when \code{psn_bins = TRUE} is #' used along with \code{vpc(smooth = FALSE)} the observations lines may not be centered in the bins. #' Check the output carefully. #' @param obs_problem Alternative to the option `psn_folder`. The $problem number to #' be used for observations. By default returns the last estimation problem. #' @param sim_problem Alternative to the option `psn_folder`. The $problem number to #' be used for simulations. By default returns the last simulation problem. #' @param quiet Logical, if \code{FALSE} messages are printed to the console. #' #' @seealso \code{\link{vpc}} \code{\link{vpc_opt}} #' @examples #' \dontrun{ #' xpdb_ex_pk %>% #' vpc_data() %>% #' vpc() #' } #' @export vpc_data <- function(xpdb, opt, stratify, vpc_type = c('continuous', 'categorical', 'censored', 'time-to-event'), psn_folder = NULL, psn_bins = FALSE, obs_problem = NULL, sim_problem = NULL, quiet) { # Check input check_xpdb(xpdb, check = ifelse(is.null(psn_folder), 'data', FALSE)) if (missing(quiet)) quiet <- xpdb$options$quiet if (missing(opt)) opt <- vpc_opt() vpc_type <- match.arg(arg = vpc_type, choices = c('continuous', 'categorical', 'censored', 'time-to-event')) # Get raw data msg(c('\nVPC ', vpc_type, ' ', rep('-', 30 - nchar(vpc_type)), '\n1. Gathering data & settings'), quiet) if (is.null(psn_folder)) { # When using xpdb tables if (is.null(obs_problem)) obs_problem <- last_data_problem(xpdb, simtab = FALSE) if (is.null(sim_problem)) sim_problem <- last_data_problem(xpdb, simtab = TRUE) msg(c('Using xpdb simulation problem ', ifelse(is.na(sim_problem), '<na>', sim_problem), ' and observation problem ', ifelse(is.na(obs_problem), '<na>', obs_problem), '.'), quiet) obs_data <- get_data(xpdb, .problem = obs_problem) sim_data <- get_data(xpdb, .problem = sim_problem) if (is.null(opt$obs_cols)) { obs_cols <- xp_var(xpdb, obs_problem, type = c('id', 'idv', 'dv', 'pred')) obs_cols <- purrr::set_names(as.list(obs_cols$col), nm = obs_cols$type) } if (is.null(opt$sim_cols)) { sim_cols <- xp_var(xpdb, sim_problem, type = c('id', 'idv', 'dv', 'pred')) sim_cols <- purrr::set_names(as.list(sim_cols$col), nm = sim_cols$type) } vpc_nsim <- xpdb %>% get_summary(sim_problem) %>% {dplyr::filter(.data = ., .$label == 'nsim')$value} } else { # When using PsN parsed_psn_vpc <- psn_vpc_parser(xpdb = xpdb, psn_folder = psn_folder, psn_bins = psn_bins, opt = opt, quiet = quiet) obs_data <- parsed_psn_vpc$obs_data obs_cols <- parsed_psn_vpc$obs_cols sim_data <- parsed_psn_vpc$sim_data sim_cols <- parsed_psn_vpc$sim_cols opt <- parsed_psn_vpc$opt psn_folder <- parsed_psn_vpc$psn_folder vpc_nsim <- parsed_psn_vpc$nsim } if (is.null(obs_data) && is.null(sim_data)) { stop('No data table found.', call. = FALSE) } # Get info on stratification if (missing(stratify)) { if (is.null(psn_folder)) { stratify <- NULL } else { stratify <- get_psn_vpc_strat(parsed_psn_vpc$psn_cmd) } } if (vpc_type == 'categorical') stratify <- add_facet_var(stratify, 'group') facets <- stratify if (is.formula(stratify)) stratify <- all.vars(stratify) if (!is.null(stratify)) { msg(c('Setting stratifying variable to ', stringr::str_c(stratify, collapse = ', ')), quiet) } # Messages for lloq and uloq if (!is.null(opt$lloq)) msg(c('Setting lloq to ', opt$lloq, '.'), quiet) if (!is.null(opt$uloq)) msg(c('Setting uloq to ', opt$uloq, '.'), quiet) # Generate vpc data msg('\n2. Computing VPC data', quiet) if (vpc_type == 'continuous') { vpc_dat <- vpc::vpc(obs = obs_data, sim = sim_data, psn_folder = NULL, bins = opt$bins, n_bins = opt$n_bins, bin_mid = opt$bin_mid, obs_cols = obs_cols, sim_cols = sim_cols, stratify = stratify, pred_corr = opt$pred_corr, pred_corr_lower_bnd = opt$pred_corr_lower_bnd, pi = opt$pi, ci = opt$ci, uloq = opt$uloq, lloq = opt$lloq, smooth = FALSE, vpcdb = TRUE, verbose = !quiet) } else if (vpc_type == 'categorical') { vpc_dat <- vpc::vpc_cat(obs = obs_data, sim = sim_data, psn_folder = NULL, bins = opt$bins, n_bins = opt$n_bins, bin_mid = opt$bin_mid, obs_cols = obs_cols, sim_cols = sim_cols, ci = opt$ci, uloq = opt$uloq, lloq = opt$lloq, smooth = FALSE, vpcdb = TRUE, verbose = !quiet) } else if (vpc_type == 'censored') { # TEMPORARY check compatibility of versions if (utils::packageVersion("dplyr") > "0.8.5" & utils::packageVersion("vpc") < "1.2.1") { stop(paste0("`dplyr` (v", utils::packageVersion("dplyr"), ") and `vpc` (v", utils::packageVersion("vpc"), ") are not compatible with each other."), call. = FALSE) } vpc_dat <- vpc::vpc_cens(obs = obs_data, sim = sim_data, psn_folder = NULL, bins = opt$bins, n_bins = opt$n_bins, bin_mid = opt$bin_mid, obs_cols = obs_cols, sim_cols = sim_cols, stratify = stratify, ci = opt$ci, uloq = opt$uloq, lloq = opt$lloq, smooth = FALSE, vpcdb = TRUE, verbose = !quiet) } else { stop('Time-to-event VPC are not yet available in xpose.', call. = FALSE) # vpc_dat <- vpc::vpc_tte(obs = obs_data, sim = sim_data, psn_folder = NULL, bins = opt$bins, # n_bins = opt$n_bins, obs_cols = obs_cols, sim_cols = sim_cols, stratify = stratify, # ci = opt$ci, smooth = FALSE, rtte = opt$rtte, rtte_calc_diff = opt$rtte_calc_diff, # events = opt$events, kmmc = opt$kmmc, reverse_prob = opt$reverse_prob, # as_percentage = opt$as_percentage, vpcdb = TRUE, verbose = !quiet) } # Assign a problem number to the vpc if (!is.null(xpdb$special$problem)) { if (!is.null(xpdb$special) && length(xpdb$special$problem[xpdb$special$method == 'vpc' & xpdb$special$type == vpc_type])) { vpc_prob <- xpdb$special$problem[xpdb$special$method == 'vpc' & xpdb$special$type == vpc_type] # Overwrite } else { vpc_prob <- max(xpdb$special$problem) + 1 # Add new problem } } else { vpc_prob <- ifelse(!is.null(xpdb$data$problem), max(xpdb$data$problem) + 1, 1) # Start new numbering } # Format vpc output xpdb$special <- vpc_dat %>% purrr::discard(names(.) %in% c('sim', 'stratify_original', 'stratify_color', 'facet', 'as_percentage', 'xlab', 'ylab', 'labeller')) %>% purrr::map_at('vpc_dat', function(x) { x <- x %>% dplyr::ungroup() %>% dplyr::mutate_all(.funs = unname) %>% # remove warning in gather tidyr::gather(key = 'tmp', value = 'value', dplyr::matches('\\.(low|med|up)')) %>% tidyr::separate(col = !!rlang::sym('tmp'), into = c('Simulations', 'ci'), sep = '\\.') %>% tidyr::spread(key = 'ci', value = 'value') %>% dplyr::ungroup() if (vpc_type == 'continuous') { x <- dplyr::mutate(.data = x, Simulations = factor(x$Simulations, levels = c('q5', 'q50', 'q95'), labels = c(stringr::str_c(min(opt$pi)*100, 'th percentile'), 'Median', stringr::str_c(max(opt$pi)*100, 'th percentile')))) } else { x <- dplyr::mutate(.data = x, Simulations = factor(x$Simulations, levels = 'q50', labels = 'Median')) } if ('strat2' %in% colnames(x)) { x$strat1 <- stringr::str_replace(x$strat1, stringr::str_c(vpc_dat$stratify[1], '='), '') x$strat2 <- stringr::str_replace(x$strat2, stringr::str_c(vpc_dat$stratify[2], '='), '') colnames(x)[colnames(x) == 'strat1'] <- vpc_dat$stratify[1] colnames(x)[colnames(x) == 'strat2'] <- vpc_dat$stratify[2] } else if (!is.null(vpc_dat$stratify)) { x[, vpc_dat$stratify] <- stringr::str_replace(x$strat, stringr::str_c(vpc_dat$stratify, '='), '') } dplyr::mutate(.data = x, group = as.numeric(interaction(x$strat, x$Simulations))) }) %>% purrr::map_at('aggr_obs', function(x) { if (vpc_type == 'continuous') { x <- x %>% dplyr::ungroup() %>% dplyr::mutate_all(.funs = unname) %>% # remove warning in gather tidyr::gather(key = 'Observations', value = 'value', dplyr::one_of('obs5', 'obs50', 'obs95')) %>% dplyr::mutate(Observations = factor(.$Observations, levels = c('obs5', 'obs50', 'obs95'), labels = c(stringr::str_c(min(opt$pi)*100, 'th percentile'), 'Median', stringr::str_c(max(opt$pi)*100, 'th percentile')))) } else { x <- x %>% dplyr::ungroup() %>% tidyr::gather(key = 'Observations', value = 'value', dplyr::one_of('obs50')) %>% dplyr::mutate(Observations = factor(.$Observations, levels = 'obs50', labels = 'Median')) } if ('strat2' %in% colnames(x)) { x$strat1 <- stringr::str_replace(x$strat1, stringr::str_c(vpc_dat$stratify[1], '='), '') x$strat2 <- stringr::str_replace(x$strat2, stringr::str_c(vpc_dat$stratify[2], '='), '') colnames(x)[colnames(x) == 'strat1'] <- vpc_dat$stratify[1] colnames(x)[colnames(x) == 'strat2'] <- vpc_dat$stratify[2] } else if (!is.null(vpc_dat$stratify)) { x[, vpc_dat$stratify] <- stringr::str_replace(x$strat, stringr::str_c(vpc_dat$stratify, '='), '') } dplyr::mutate(.data = x, group = as.numeric(interaction(x$strat, x$Observations))) }) %>% c(list(opt = opt, psn = ifelse(!is.null(psn_folder), TRUE, FALSE), psn_bins = psn_bins, vpc_dir = ifelse(!is.null(psn_folder), psn_folder, xpdb$options$dir), facets = facets, obs_problem = obs_problem, sim_problem = sim_problem, obs_cols = obs_cols, sim_cols = sim_cols, nsim = vpc_nsim)) %>% {dplyr::tibble(problem = vpc_prob, method = 'vpc', type = vpc_type, data = list(.), modified = FALSE)} %>% {dplyr::bind_rows(xpdb$special, .)} %>% dplyr::distinct(!!!rlang::syms(c('problem', 'method', 'type')), .keep_all = TRUE) msg('\nVPC done', quiet) as.xpdb(xpdb) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/vpc_data.R
#' Generate a list of options for VPC data generation #' #' @description Provide a list of options to \code{vpc_data} function. #' #' @param bins Binning method, can be one of 'density', 'time', 'data', 'none', or one of the approaches #' available in \code{classInterval()} such as 'jenks' (default), 'pretty', or a numeric vector specifying #' the bin separators. #' @param n_bins When using the 'auto' binning method, what number of bins to aim for. #' @param bin_mid Specify how to is the mid bin value calculated, can be either 'mean' for the mean of all #' timepoints (default) or 'middle' to use the average of the bin boundaries. #' @param pred_corr Option reserved to continuous VPC. Logical, should a prediction correction (pcVPC) of the data be used. #' @param pred_corr_lower_bnd Option reserved to continuous VPC. Lower bound for the prediction-correction. #' @param pi Option reserved to continuous VPC. Simulated prediction interval to plot. Default is c(0.05, 0.95). #' @param ci Confidence interval around the percentiles to plot. Default is c(0.05, 0.95) #' @param lloq Number or NULL indicating lower limit of quantification. Default is NULL. #' @param uloq Number or NULL indicating upper limit of quantification. Default is NULL. #' @param rtte Option reserved to time-to-event VPC. Is the data repeated time-to-event (RTTE) \code{TRUE} or #' single time-to-event (TTE) \code{FALSE}. #' @param rtte_calc_diff Option reserved to time-to-event VPC. Should the time be recalculated? When simulating in NONMEM, #' you will probably need to set this to \code{TRUE} to recalculate the TIME to the relative time between events (unless you #' output the time difference between events and specify that as independent variable in the index. #' @param kmmc Option reserved to time-to-event VPC. Either NULL for regular TTE VPC (default), or a variable name #' for a KMMC plot (e.g. 'WT'). #' @param events Option reserved to time-to-event VPC. Numeric vector describing which events to show a VPC for when #' repeated TTE data, e.g. c(1:4). Default is \code{NULL}, which shows all events. #' @param reverse_prob Option reserved to time-to-event VPC. Should the probability be reversed (i.e. plot 1-probability). #' @param as_percentage Should the Y-scale be in percent (0-100) \code{TRUE} (default), or standard (0-1) \code{FALSE}. #' #' @seealso \code{\link{vpc}} \code{\link{vpc_data}} #' #' @examples #' vpc_opt() #' #' @export vpc_opt <- function(bins = 'jenks', n_bins = 'auto', bin_mid = 'mean', pred_corr = FALSE, pred_corr_lower_bnd = 0, pi = c(0.025, 0.975), ci = c(0.025, 0.975), lloq = NULL, uloq = NULL, rtte = FALSE, rtte_calc_diff = TRUE, events = NULL, kmmc = NULL, reverse_prob = FALSE, as_percentage = TRUE) { list(bins = bins, n_bins = n_bins, bin_mid = bin_mid, pred_corr = pred_corr, pred_corr_lower_bnd = pred_corr_lower_bnd, pi = pi, ci = ci, lloq = lloq, uloq = uloq, rtte = rtte, rtte_calc_diff = rtte_calc_diff, events = events, kmmc = kmmc, reverse_prob = reverse_prob, as_percentage = as_percentage, usr_call = names(match.call()[-1])) } # Gets strata info from PsN command get_psn_vpc_strat <- function(psn_cmd) { if (stringr::str_detect(psn_cmd, '-stratify_on')) { psn_cmd %>% {stringr::str_match(string = ., pattern = '-stratify_on=\\s*([^\\s]+)')[1, 2]} %>% stringr::str_split(',') %>% purrr::flatten_chr() } } # Gets vpc options from PsN directory psn_vpc_parser <- function(xpdb, psn_folder, psn_bins, opt, quiet) { psn_folder <- parse_title(string = psn_folder, xpdb = xpdb, quiet = quiet, problem = default_plot_problem(xpdb)) if (!dir.exists(psn_folder)) { stop('The `psn_folder`:', psn_folder, ' could not be found.', call. = FALSE) } msg('Importing PsN generated data', quiet) if (!dir.exists(file_path(psn_folder, 'm1')) & file.exists(file_path(psn_folder, 'm1.zip'))) { msg('Unziping PsN m1 folder', quiet) utils::unzip(zipfile = file_path(psn_folder, 'm1.zip'), exdir = file_path(psn_folder, '')) unzip <- TRUE } else { unzip <- FALSE } obs_data <- read_nm_tables(file = dir(file_path(psn_folder, 'm1'), pattern = 'original.npctab')[1], dir = file.path(psn_folder, 'm1'), quiet = TRUE) sim_data <- read_nm_tables(file = dir(file_path(psn_folder, 'm1'), pattern = 'simulation.1.npctab')[1], dir = file.path(psn_folder, 'm1'), quiet = TRUE) if (unzip) unlink(x = file_path(psn_folder, 'm1'), recursive = TRUE, force = TRUE) # Getting multiple options form the psn command if (file.exists(file_path(psn_folder, 'version_and_option_info.txt'))) { # Get list of options from PsN psn_opt <- readr::read_lines(file = file_path(psn_folder, 'version_and_option_info.txt')) psn_cmd <- psn_opt[which(stringr::str_detect(psn_opt, '^Command:')) + 1] psn_opt <- dplyr::tibble(raw = psn_opt[stringr::str_detect(psn_opt,'^-')]) %>% tidyr::separate(col = 'raw', into = c('arg', 'value'), sep = '=') %>% dplyr::mutate(arg = stringr::str_replace(.$arg, '^-', '')) # Sets obs and sim cols obs_cols <- list(id = 'ID', idv = psn_opt$value[psn_opt$arg == 'idv'], dv = psn_opt$value[psn_opt$arg == 'dv'], pred = 'PRED') sim_cols <- obs_cols # Sets additional options if (!any(opt$usr_call == 'pred_corr')) { pred_corr <- as.logical(as.numeric(psn_opt$value[psn_opt$arg == 'predcorr'])) if (!is.na(pred_corr)) opt$pred_corr <- pred_corr } if (!any(opt$usr_call == 'lloq')) { lloq <- as.numeric(psn_opt$value[psn_opt$arg == 'lloq']) if (length(lloq) > 0 && !is.na(lloq)) opt$lloq <- lloq } if (!any(opt$usr_call == 'uloq')) { uloq <- as.numeric(psn_opt$value[psn_opt$arg == 'uloq']) if (length(uloq) > 0 && !is.na(uloq)) opt$uloq <- uloq } # Get number of samples [would be better to compute and use IREP in the future] nsim <- ifelse(!stringr::str_detect(psn_cmd, '-sampl'), 'na', stringr::str_match(psn_cmd, '-sampl[a-z]+=\\s*([^\\s]+)')[1, 2]) } else { msg('PsN file `version_and_option_info.txt` not found. Using default options.', quiet) obs_cols <- c(id = 'ID', idv = 'TIME', dv = 'DV', pred = 'PRED') sim_cols <- obs_cols } if (file.exists(file_path(psn_folder, 'vpc_bins.txt')) && !any(opt$usr_call == 'bins') && psn_bins) { psn_bins <- readr::read_lines(file = file_path(psn_folder, 'vpc_bins.txt')) %>% .[nchar(.) > 0] %>% utils::tail(n = 1) %>% stringr::str_replace('^.+=', '') %>% {stringr::str_split(., ':')[[1]]} %>% {stringr::str_split(., ',')} %>% purrr::map(~as.numeric(.x)) if (!any(is.na(psn_bins[[1]]))) { opt$bins <- psn_bins[[1]] # vpc does not handle panel based binning yet so take the first one msg(c('Using PsN-defined binning', ifelse(length(unique(psn_bins)) == 1 , '', '. Only a single bin_array (i.e. first) can be used by xpose.')), quiet) } else { warning('Failed to read PsN-defined binning.', call. = FALSE) } } list(obs_data = obs_data, obs_cols = obs_cols, sim_data = sim_data, sim_cols = sim_cols, opt = opt, psn_folder = psn_folder, psn_cmd = psn_cmd, nsim = nsim) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/vpc_helpers.R
#' Access model code #' #' @description Access model code from an xpdb object. #' #' @param xpdb An \code{xpose_data} object from which the model code will be extracted. #' @param .problem The problem to be used, in addition, problem 0 is attributed to #' general output (e.g. NM-TRAN warnings in NONMEM). By default returns the #' entire code. #' @return A tibble of the parsed model. #' @seealso \code{\link{xpose_data}}, \code{\link{read_nm_model}} #' @examples #' parsed_model <- get_code(xpdb_ex_pk) #' parsed_model #' #' @export get_code <- function(xpdb, .problem = NULL) { check_xpdb(xpdb, check = 'code') x <- xpdb$code if (!is.null(.problem)) { if (!all(.problem %in% x$problem)) { stop('$prob no.', stringr::str_c(.problem[!.problem %in% x$problem], collapse = ', '), ' not found in model code.', call. = FALSE) } x <- x[x$problem %in% .problem, ] } x } #' Access model output table data #' #' @description Access model output table data from an xpdb object. #' #' @param xpdb An \code{xpose_data} object from which the model output file data will be extracted. #' @param table Name of the output table to be extracted from the xpdb e.g. 'sdtab001'. Alternative to #' the `.problem` argument. #' @param .problem Accesses all tables from the specified problem. Alternative to the `table` argument. #' @param quiet Logical, if \code{FALSE} messages are printed to the console. #' #' @return By default returns data from the last estimation problem. If only simulation problems are present #' then the data from last simulation will be returned instead. Object returned as tibble for single #' tables/problems or a named list for multiple tables/problems. #' #' @seealso \code{\link{list_data}}, \code{\link{xpose_data}}, \code{\link{read_nm_tables}} #' @examples #' # By table name #' sdtab <- get_data(xpdb_ex_pk, 'sdtab001') #' sdtab #' #' # By problem #' tables <- get_data(xpdb_ex_pk, .problem = 1) #' tables #' #' # Tip to list available tables in the xpdb #' print(xpdb_ex_pk) #' #' @export get_data <- function(xpdb, table = NULL, .problem = NULL, quiet) { check_xpdb(xpdb, check = 'data') if (missing(quiet)) quiet <- xpdb$options$quiet if (is.null(table) && is.null(.problem)) { .problem <- default_plot_problem(xpdb) msg(c('Returning data from $prob no.', .problem), quiet) } if (!is.null(table) && !is.null(.problem)) { stop('Arguments `table` and `.problem` cannot be used together.', call. = FALSE) } if (!is.null(.problem) && is.na(.problem)) return() # For internal use x <- xpdb$data if (!is.null(.problem)) { # When selecting tables based on problem level if (!all(.problem %in% x$problem)) { stop('$prob no.', stringr::str_c(.problem[!.problem %in% x$problem], collapse = ', '), ' not found in model output data.', call. = FALSE) } x <- x$data[x$problem %in% .problem] if (length(.problem) > 1) { purrr::set_names(x, stringr::str_c('problem_', sort(.problem), sep = '')) } else { x[[1]] } } else { # When selecting tables based on their name full_index <- x %>% dplyr::select(dplyr::one_of('problem', 'index')) %>% tidyr::unnest(dplyr::one_of('index')) if (any(!table %in% full_index$table)) { stop(stringr::str_c(table[!table %in% full_index$table], collapse = ', '), ' not found in model output data.', call. = FALSE) } x <- full_index[full_index$table %in% table, ] %>% dplyr::group_by_at(.vars = c('problem', 'table')) ## TEMP handling if (tidyr_new_interface()) { x <- x %>% tidyr::nest(tmp = -dplyr::one_of('problem', 'table')) } else { x <- x %>% tidyr::nest(.key = 'tmp') } ## END TEMP x <- x %>% dplyr::ungroup() %>% dplyr::mutate(cols = purrr::map(.$tmp, ~.$col)) %>% dplyr::group_by_at(.vars = 'table') ## TEMP handling if (tidyr_new_interface()) { x <- x %>% tidyr::nest(tmp = -dplyr::one_of('table')) } else { x <- x %>% tidyr::nest(.key = 'tmp') } ## END TEMP x <- x %>% dplyr::ungroup() %>% dplyr::mutate(out = purrr::map(.$tmp, function(y) { xpdb$data[xpdb$data$problem == y$problem, ]$data[[1]][, y$cols[[1]]] })) if (length(unique(x$table)) > 1) { purrr::set_names(x$out, x$table) } else { x$out[[nrow(x)]] } } } #' Access model output file data #' #' @description Access model output file data from an xpdb object. #' #' @param xpdb An \code{xpose_data} object from which the model output file data will be extracted. #' @param file Full name of the file to be extracted from the xpdb e.g. 'run001.phi'. Alternative to the 'ext' argument. #' @param ext Extension of the file to be extracted from the xpdb e.g. 'phi'. Alternative to the 'file' argument. #' @param .problem The problem to be used, by default returns the last one for each file. #' @param .subprob The subproblem to be used, by default returns the last one for each file. #' @param .method The estimation method to be used (e.g. 'foce', 'imp', 'saem'), by default returns the #' last one for each file. #' @param quiet Logical, if \code{FALSE} messages are printed to the console. #' #' @return A tibble for single file or a named list for multiple files. #' @seealso \code{\link{list_files}}, \code{\link{xpose_data}}, \code{\link{read_nm_files}} #' @examples #' # Single file (returns a tibble) #' ext_file <- get_file(xpdb_ex_pk, file = 'run001.ext') #' ext_file #' #' # Multiple files (returns a list) #' files <- get_file(xpdb_ex_pk, file = c('run001.ext', 'run001.phi')) #' files #' #' # Tip to list available files in the xpdb #' print(xpdb_ex_pk) #' #' @export get_file <- function(xpdb, file = NULL, ext = NULL, .problem = NULL, .subprob = NULL, .method = NULL, quiet) { check_xpdb(xpdb, check = 'files') if (missing(quiet)) quiet <- xpdb$options$quiet if (is.null(file) && is.null(ext)) { stop('Argument `file` or `ext` required.', call. = FALSE) } if (!is.null(file) && !is.null(ext)) { stop('Argument `file` and `ext` should not be used simultaneously.', call. = FALSE) } # Get file name from extension if (!is.null(ext)) { file <- unique(xpdb$files$name[xpdb$files$extension %in% ext]) if (length(file) == 0) { stop('File extension ', stringr::str_c(ext[!ext %in% xpdb$files$extension], collapse = ', '), ' not found in model output files.', call. = FALSE) } } # Filter by file if (any(!file %in% xpdb$files$name)) { stop(stringr::str_c(file[!file %in% xpdb$files$name], collapse = ', '), ' not found in model output files.', call. = FALSE) } x <- xpdb$files[xpdb$files$name %in% file, ] # Filter by $problem if (is.null(.problem)) { .problem <- last_file_problem(xpdb, ext = x$extension) } else if (!all(.problem %in% x$problem)) { stop('$prob no.', stringr::str_c(.problem[!.problem %in% x$problem], collapse = ', '), ' not found in ', stringr::str_c(unique(x$name), collapse = ', '), ' files.', call. = FALSE) } x <- x[x$problem %in% .problem, ] # Filter by sub-problem if (is.null(.subprob)) { .subprob <- last_file_subprob(xpdb, ext = x$extension, .problem = .problem) } else if (!all(.subprob %in% x$subprob)) { stop('Subprob no.', stringr::str_c(.subprob[!.subprob %in% x$subprob], collapse = ', '), ' not found in ', stringr::str_c(unique(x$name), collapse = ', '), ' files.', call. = FALSE) } x <- x[x$subprob %in% .subprob, ] # Filter by method if (is.null(.method)) { .method <- last_file_method(xpdb, ext = x$extension, .problem = .problem, .subprob = .subprob) } else if (!all(.method %in% x$method)) { stop('Method ', stringr::str_c(.method[!.method %in% x$method], collapse = ', '), ' not found in ', stringr::str_c(unique(x$name), collapse = ', ') , ' files.', call. = FALSE) } x <- x[x$method %in% .method, ] # Prepare output if (nrow(x) > 1) { msg(c('Returning data from ', stringr::str_c(unique(x$name), collapse = ', ')), quiet) x$data %>% purrr::set_names(stringr::str_c(x$name, '_prob_', x$problem, '_subprob_', x$subprob, '_', x$method)) %>% return() } else { msg(c('Returning data from ', x$name, ', $prob no.', x$problem , ', subprob no.', x$subprob, ', method ', x$method), quiet) return(x$data[[1]]) } } #' Access model summary data #' #' @description Access model summary data from an xpdb object. #' #' @param xpdb An \code{xpose_data} object from which the summary data will be extracted. #' @param .problem The .problem to be used, by default returns the last one for each label. #' @param .subprob The subproblem to be used, by default returns the last one for each label. #' @param only_last Logical, if \code{TRUE} only the last record for each label is returned in case #' of multiple problem and/or subproblem. If \code{FALSE} all values are returned. #' #' @return A tibble of model summary. #' @seealso \code{\link{xpose_data}}, \code{\link{template_titles}}, \code{\link{summary.xpose_data}} #' @examples #' run_summary <- get_summary(xpdb_ex_pk) #' run_summary #' #' @export get_summary <- function(xpdb, .problem = NULL, .subprob = NULL, only_last = FALSE) { check_xpdb(xpdb, check = 'summary') x <- xpdb$summary # Filter by $problem if (!is.null(.problem)) { if (!all(.problem %in% x$problem)) { stop('$prob no.', stringr::str_c(.problem[!.problem %in% x$problem], collapse = ', '), ' not found in model summary.', call. = FALSE) } x <- x[x$problem %in% .problem, ] } # Filter by sub-problem if (!is.null(.subprob)) { if (!all(.subprob %in% x$subprob)) { stop('Subprob no.', stringr::str_c(.subprob[!.subprob %in% x$subprob], collapse = ', '), ' not found in model summary.', call. = FALSE) } x <- x[x$subprob %in% .subprob, ] } # Remove duplicates if (only_last) x <- x[!duplicated(x$label, fromLast = TRUE), ] x } #' Access model parameters #' #' @description Access model parameter estimates from an xpdb object. #' #' @param xpdb An \code{xpose_data} object from which the model output file data will be extracted. #' @param .problem The problem to be used, by default returns the last one for each file. #' @param .subprob The subproblem to be used, by default returns the last one for each file. #' @param .method The estimation method to be used, by default returns the last one for each file #' @param digits The number of significant digits to be displayed. #' @param transform Should diagonal OMEGA and SIGMA elements be transformed to standard deviation and #' off diagonal elements be transformed to correlations. #' @param show_all Logical, whether the 0 fixed off-diagonal elements should be removed from the output. #' @param quiet Logical, if \code{FALSE} messages are printed to the console. #' #' @return A tibble for single problem/subprob or a named list for multiple problem|subprob. #' @seealso \code{\link{prm_table}} #' @examples #' # Store the parameter table #' prm <- get_prm(xpdb_ex_pk, .problem = 1) #' #' # Display parameters to the console #' prm_table(xpdb_ex_pk, .problem = 1) #' #' @export get_prm <- function(xpdb, .problem = NULL, .subprob = NULL, .method = NULL, digits = 4, transform = TRUE, show_all = FALSE, quiet) { check_xpdb(xpdb, check = 'files') if (missing(quiet)) quiet <- xpdb$options$quiet prm_df <- xpdb$files if (!any(prm_df$extension == 'ext')) { stop('File extension `ext` not found in model output files.' , call. = FALSE) } if (is.null(.problem)) .problem <- last_file_problem(xpdb, ext = 'ext') if (is.null(.subprob)) .subprob <- last_file_subprob(xpdb, ext = 'ext', .problem = .problem) if (is.null(.method)) .method <- last_file_method(xpdb, ext = 'ext', .problem = .problem, .subprob = .subprob) prm_df <- prm_df %>% dplyr::filter(.$extension %in% c('ext', 'cov'), .$problem %in% .problem, .$subprob %in% .subprob, .$method %in% .method) if (!any(prm_df$extension == 'ext')) { stop('No parameter estimates found for $prob no.', stringr::str_c(.problem, collapse = '/'), ', subprob no. ', stringr::str_c(.subprob, collapse = '/'), ', method ', stringr::str_c(.method, collapse = '/'), '.', call. = FALSE) } prm_df <- prm_df %>% dplyr::select(-dplyr::one_of('name', 'modified')) %>% tidyr::spread(key = 'extension', value = 'data') msg(c('Returning parameter estimates from $prob no.', stringr::str_c(unique(prm_df$problem), collapse = ', '), ', subprob no.', stringr::str_c(unique(prm_df$subprob), collapse = ', '), ', method ', stringr::str_c(unique(prm_df$method), collapse = ', ')), quiet) prm_df <- prm_df %>% dplyr::mutate(prm_names = purrr::map(.x = as.list(.$problem), .f = function(x, code) { # Collect parameter names from the model code code <- code[code$problem == x & nchar(code$code) > 0,] list(theta = code$comment[code$subroutine == 'the'], omega = code[code$subroutine == 'ome', ] %>% dplyr::filter(!(stringr::str_detect(.$code, 'BLOCK\\(\\d+\\)(?!.*SAME)') & .$comment == '')) %>% {purrr::flatten_chr(.[, 'comment'])}, sigma = code$comment[code$subroutine == 'sig']) }, code = xpdb$code)) %>% purrr::transpose() %>% purrr::map(.f = function(data) { prm_mean <- grab_iter(ext = data$ext, iter = -1000000000) prm_se <- grab_iter(ext = data$ext, iter = -1000000001) prm_fix <- grab_iter(ext = data$ext, iter = -1000000006) if (all(is.na(prm_fix))) { warning('Iteration `-1000000006` not found in the `.ext` file. Assuming no fixed parameters, check the output carefully.', call. = FALSE) prm_fix[is.na(prm_fix)] <- 0 } if (transform) { if (!is.null(data$cov)) { # build covariance matrix from `.cov` file prm_cov <- as.data.frame(data$cov) %>% tibble::column_to_rownames('NAME') %>% as.matrix() } else { # build covariance matrix from `.ext` se prm_cov <- diag(prm_se)^2 attr(prm_cov, 'dimnames') <- list(names(prm_se), names(prm_se)) # No warning when .ext SE not available if (!all(is.na(prm_se))) { warning('Covariance matrix (`.cov`) not available, RSE for covariance parameters will be incorrect.', call. = FALSE) } } # obtain transformation formulas prm_trans_formula <- get_prm_transformation_formulas(names(prm_mean)) # transform parameters & calculate var, rse for transformation prms <- purrr::map_df(prm_trans_formula, ~transform_prm(.x, mu = prm_mean, sigma = prm_cov, method = 'delta')) %>% dplyr::mutate(se = sqrt(.$variance)) } else { prms <- dplyr::tibble(mean = purrr::flatten_dbl(prm_mean), se = purrr::flatten_dbl(prm_se)) %>% dplyr::mutate(rse = .$se/abs(.$mean)) } prms <- prms %>% dplyr::mutate(fixed = as.logical(as.numeric(prm_fix)), name = names(prm_mean)) %>% dplyr::mutate(type = dplyr::case_when(stringr::str_detect(.$name, 'THETA') ~ 'the', stringr::str_detect(.$name, 'OMEGA') ~ 'ome', stringr::str_detect(.$name, 'SIGMA') ~ 'sig'), number = stringr::str_replace_all(.$name, '[^\\d,]+', ''), se = ifelse(.$fixed, NA_real_, as.numeric(.$se)), rse = ifelse(.$fixed, NA_real_, abs(as.numeric(.$rse)))) %>% tidyr::separate(col = 'number', into = c('m', 'n'), sep = ',', fill = 'right') %>% dplyr::mutate(diagonal = dplyr::if_else(.$m == .$n, TRUE, FALSE)) %>% dplyr::rename(!!rlang::sym('value') := !!rlang::sym('mean')) %>% dplyr::mutate(label = '', value = signif(.$value, digits = digits), se = signif(.$se, digits = digits), rse = signif(.$rse, digits = digits), n = as.numeric(.$n), m = as.numeric(.$m), order = dplyr::case_when(type == 'the' ~ 1, type == 'ome' ~ 2, TRUE ~ 3)) %>% dplyr::arrange_at(.vars = 'order') %>% dplyr::select(dplyr::one_of('type', 'name', 'label', 'value', 'se', 'rse', 'fixed', 'diagonal', 'm', 'n')) # Assign THETA labels n_theta <- sum(prms$type == 'the') theta_names <- data$prm_names$theta if (n_theta != length(theta_names)) { warning('[$prob no.', data$problem, ', subprob no.', data$subprob, ', ', data$method, '] $THETA labels did not match the number of THETAs in the `.ext` file.', call. = FALSE) } else { prms$label[prms$type == 'the'] <- theta_names } # Assign OMEGA labels n_omega <- sum(prms$type == 'ome' & prms$diagonal, na.rm = TRUE) omega_names <- data$prm_names$omega if (n_omega != length(omega_names)) { warning('[$prob no.', data$problem, ', subprob no.', data$subprob, ', ', data$method, '] $OMEGA labels did not match the number of OMEGAs in the `.ext` file.', call. = FALSE) } else { prms$label[prms$type == 'ome' & prms$diagonal] <- omega_names } # Assign SIGMA labels n_sigma <- sum(prms$type == 'sig' & prms$diagonal, na.rm = TRUE) sigma_names <- data$prm_names$sigma if (n_sigma != length(sigma_names)) { warning('[$prob no.', data$problem, ', subprob no.', data$subprob, ', ', data$method, '] $SIGMA labels did not match the number of SIGMAs in the `.ext` file.', call. = FALSE) } else { prms$label[prms$type == 'sig' & prms$diagonal] <- sigma_names } # Filter_all if (!show_all) { prms <- dplyr::filter(.data = prms, !(prms$type %in% c('ome', 'sig') & prms$value == 0 & !prms$diagonal)) } # Add metadata to output structure(.Data = prms, file = 'ext', problem = data$problem, subprob = data$subprob, method = data$method) }) # Format output if (length(prm_df) == 1) prm_df <- prm_df[[1]] structure(prm_df, class = c('xpose_prm', class(prm_df))) } #' Grab parameter for a given iteration number #' @param ext parameter vs. iteration table #' @param iter iteration number #' #' @keywords internal #' @export grab_iter <- function(ext, iter) { out <- ext %>% dplyr::filter(.$ITERATION == iter) %>% dplyr::select(-dplyr::one_of('ITERATION', 'OBJ')) if (nrow(out) == 0) out[1,] <- NA_real_ purrr::flatten(out) } #' Generate default transformation formulas for parameters #' #' @param prm_names Vector of parameter names as found in .ext #' #' @return List of formulas decribing the transformation #' @keywords internal #' @export get_prm_transformation_formulas <- function(prm_names) { prm_names %>% purrr::set_names() %>% purrr::map_if(~stringr::str_detect(.x, "^THETA"), ~substitute(~par, list(par = rlang::sym(.x)))) %>% purrr::map_if(~purrr::is_character(.x) && stringr::str_detect(.x, '^(OMEGA|SIGMA)\\((\\d+),\\2\\)$'), ~substitute(~sqrt(par), list(par = rlang::sym(.x)))) %>% purrr::map_if(~purrr::is_character(.x) && stringr::str_detect(.x, '^(OMEGA|SIGMA)\\(\\d+,\\d+\\)$'), ~substitute(~cov/(sqrt(var1)*sqrt(var2)), list(cov = rlang::sym(.x), var1 = stringr::str_replace(.x, '\\((\\d+),(\\d+)\\)', '(\\1,\\1)') %>% rlang::sym(), var2 = stringr::str_replace(.x, '\\((\\d+),(\\d+)\\)', '(\\2,\\2)') %>% rlang::sym()))) } #' Access special model data #' #' @description Access special model data from an xpdb object. #' #' @param xpdb An \code{xpose_data} object from which the special data will be extracted. #' @param .problem The problem to be used, by default returns the last one. #' @param quiet Logical, if \code{FALSE} messages are printed to the console. #' #' @return A list. #' @seealso \code{\link{list_special}}, \code{\link{xpose_data}} #' @examples #' special <- get_summary(xpdb_ex_pk) #' special #' #' @export get_special <- function(xpdb, .problem = NULL, quiet) { check_xpdb(xpdb, check = 'special') if (missing(quiet)) quiet <- xpdb$options$quiet x <- xpdb$special if (is.null(.problem)) .problem <- max(x$problem) if (!all(.problem %in% x$problem)) { stop('$prob no.', stringr::str_c(.problem[!.problem %in% x$problem], collapse = ', '), ' not found in special data.', call. = FALSE) } x <- x[x$problem %in% .problem, ] if (length(.problem) > 1) { purrr::set_names(x$data, stringr::str_c('problem_', x$problem, '_', x$method, '_', x$type)) } else { msg(c('Returning ', x$method, ' ' , x$type, ' data from $prob no.', x$problem), quiet) x$data[[1]] } }
/scratch/gouwar.j/cran-all/cranData/xpose/R/xpdb_access.R
#' Subset datasets in an xpdb #' #' @description Use \code{filter()} to select rows/cases where conditions are true. #' Unlike base subsetting, rows where the condition evaluates to NA are dropped. #' Use \code{slice()} to select row/cases by their position #' #' @inheritParams edit_xpose_data #' @method filter xpose_data #' @examples #' # Subset by condition #' xpdb_ex_pk %>% #' filter(DV < 1, .problem = 1) %>% #' dv_vs_ipred() #' #' # Subset by positions #' xpdb_ex_pk %>% #' slice(1:100, .problem = 1) %>% #' dv_vs_ipred() #' #' # Deduplicate rows #' xpdb_ex_pk %>% #' distinct(TIME, .problem = 1) %>% #' dv_vs_ipred() #' @name subset_xpdb #' @export filter.xpose_data <- function(.data, ..., .problem, .source, .where) { edit_xpose_data(.fun = dplyr::filter, .fname = 'filter', .data = .data, .problem = .problem, .source = .source, .where = .where, ...) } #' @method slice xpose_data #' @name subset_xpdb #' @export slice.xpose_data <- function(.data, ..., .problem, .source, .where) { edit_xpose_data(.fun = dplyr::slice, .fname = 'slice', .data = .data, .problem = .problem, .source = .source, .where = .where, ...) } #' @method distinct xpose_data #' @name subset_xpdb #' @export distinct.xpose_data <- function(.data, ..., .problem, .source, .where) { edit_xpose_data(.fun = function(.data, ...) {dplyr::distinct(.data, ..., .keep_all = TRUE)}, .fname = 'distinct', .data = .data, .problem = .problem, .source = .source, .where = .where, ...) } #' Add, remove or rename variables in an xpdb #' #' @description \code{mutate()} adds new variables and preserves existing ones. #' \code{select()} keeps only the listed variables; \code{rename()} keeps all variables. #' #' @inheritParams edit_xpose_data #' @method mutate xpose_data #' @examples #' # Mutate columns #' xpdb_ex_pk %>% #' mutate(lnDV = log(DV), #' sim_count = irep(ID), #' .problem = 1) %>% #' dv_vs_idv(aes(y = lnDV)) #' #' # Rename/select columns #' xpdb_ex_pk %>% #' select(ID:TAD, DV, EVID) %>% #' rename(TSLD = TAD) %>% #' dv_vs_idv(aes(x = TSLD)) #' @name modify_xpdb #' @export mutate.xpose_data <- function(.data, ..., .problem, .source, .where) { edit_xpose_data(.fun = dplyr::mutate, .fname = 'mutate', .data = .data, .problem = .problem, .source = .source, .where = .where, ...) } #' @method select xpose_data #' @name modify_xpdb #' @export select.xpose_data <- function(.data, ..., .problem, .source, .where) { edit_xpose_data(.fun = dplyr::select, .fname = 'select', .data = .data, .problem = .problem, .source = .source, .where = .where, ...) } #' @method rename xpose_data #' @name modify_xpdb #' @export rename.xpose_data <- function(.data, ..., .problem, .source, .where) { edit_xpose_data(.fun = dplyr::rename, .fname = 'rename', .data = .data, .problem = .problem, .source = .source, .where = .where, ...) } #' Group/ungroup and summarize variables in an xpdb #' #' @description \code{group_by()} takes an existing table and converts it into a #' grouped table where operations are performed "by group". \code{ungroup()} removes grouping. #' \code{summarize()} reduces multiple values down to a single value. #' #' @inheritParams edit_xpose_data #' @param x Same as .data (used for consistency with dplyr functions). #' @method group_by xpose_data #' @examples #' # Create a distribution plot of Cmax #' xpdb_ex_pk %>% #' group_by(ID, SEX, .problem = 1) %>% #' summarize(CMAX = max(DV), .problem = 1) %>% #' ungroup(.problem = 1) %>% #' xplot_distrib(aes(x = CMAX, density_fill = SEX), type = 'dr') #' #' @name summarise_xpdb #' @export group_by.xpose_data <- function(.data, ..., .problem, .source, .where) { edit_xpose_data(.fun = dplyr::group_by, .fname = 'group_by', .data = .data, .problem = .problem, .source = .source, .where = .where, ...) } #' @method ungroup xpose_data #' @name summarise_xpdb #' @export ungroup.xpose_data <- function(x, ..., .problem, .source, .where) { edit_xpose_data(.fun = dplyr::ungroup, .fname = 'ungroup', .data = x, .problem = .problem, .source = .source, .where = .where, ...) } #' @method summarise xpose_data #' @name summarise_xpdb #' @export summarise.xpose_data <- function(.data, ..., .problem, .source, .where) { edit_xpose_data(.fun = dplyr::summarise, .fname = 'summarise', .data = .data, .problem = .problem, .source = .source, .where = .where, ...) } #' @method summarize xpose_data #' @name summarise_xpdb #' @export summarize.xpose_data <- summarise.xpose_data #' Master xpdb editing function #' #' @description Generic function used to build dedicated editing functions #' #' @param .fun An editing function to be applied to the data. #' @param .fname The name of the editing function. #' @param .data An xpose database object. #' @param .problem The problem from which the data will be modified #' @param .source The source of the data in the xpdb. Can either be 'data' or an output #' file extension e.g. 'phi'. #' @param .where A vector of element names to be edited in special (e.g. #' \code{.where = c('vpc_dat', 'aggr_obs')} with vpc). #' @param ... Name-value pairs of expressions. Use \code{NULL} to drop a variable. #' #' These arguments are automatically quoted and evaluated in the #' context of the data frame. They support unquoting and splicing. #' See the dplyr vignette("programming") for an introduction to these concepts. #' @keywords internal #' @export edit_xpose_data <- function(.fun, .fname, .data, ..., .problem, .source, .where) { # Check input xpdb <- .data # Avoids issues with dplyr arguments if (missing(.source)) .source <- 'data' if (length(.source) > 1) stop('Argument `.source` should be of length 1.', call. = FALSE) check_xpdb(xpdb, check = .source) # Direct filter to specified source if (.source == 'data') { if (missing(.problem)) .problem <- all_data_problem(xpdb) if (!all(.problem %in% all_data_problem(xpdb))) { stop('Problem no.', stringr::str_c(.problem[!.problem %in% xpdb[['data']]$problem], collapse = ', '), ' not found in model output data.', call. = FALSE) } check_quo_vars(xpdb = xpdb, ..., .source = .source, .problem = .problem) # do dplyr operation outside of mutate to avoid problems with n() xpdb[['data']]$data <- purrr::map_if(xpdb[['data']]$data, xpdb[['data']]$problem %in% .problem, .f = .fun, !!!rlang::enquos(...)) xpdb[['data']] <- xpdb[['data']] %>% dplyr::mutate(modified = dplyr::if_else(.$problem %in% .problem, TRUE, .$modified)) if (.fname %in% c('mutate', 'select', 'rename')) { xpdb[['data']] <- xpdb_index_update(xpdb = xpdb, .problem = .problem) # Update index } } else if (.source == 'special') { if (missing(.problem)) { .problem <- max(xpdb[['special']]$problem) msg(c('Changes will be applied to `special` $prob no.', .problem), quiet = FALSE) } if (!all(.problem %in% xpdb[['special']]$problem)) { stop('Problem no.', stringr::str_c(.problem[!.problem %in% xpdb[['special']]$problem], collapse = ', '), ' not found in `special` data.', call. = FALSE) } check_quo_vars(xpdb = xpdb, ..., .source = .source, .problem = .problem) xpdb[['special']] <- xpdb[['special']] %>% dplyr::group_by_at(.vars = 'problem') ## TEMP handling if (tidyr_new_interface()) { xpdb[['special']] <- xpdb[['special']] %>% tidyr::nest(tmp = -dplyr::one_of('problem')) %>% dplyr::ungroup() } else { xpdb[['special']] <- xpdb[['special']] %>% tidyr::nest(.key = 'tmp') %>% dplyr::ungroup() } ## END TEMP xpdb[['special']]$tmp <- purrr::map_if(.x = xpdb[['special']]$tmp, .p = xpdb[['special']]$problem %in% .problem, .f = function(.x, .fun, .where, ...) { if (.x$method == 'vpc') { if (any(!.where %in% names(.x$data[[1]]))) { warning('elements ', stringr::str_c(.where[!.where %in% names(.x$data[[1]])], collapse = ', '), ' not found in ', .x$method, ' ', .x$type, call. = FALSE) } .x$data[[1]] <- .x$data[[1]] %>% purrr::map_at(.at = .where, .f = .fun, ...) .x$modified <- TRUE return(.x) } else { stop('edits of `', .x$method, '` data are not yet supported in xpose.', call. = FALSE) } }, .fun = .fun, .where = .where, !!!rlang::enquos(...)) xpdb[['special']] <- xpdb[['special']] %>% tidyr::unnest(dplyr::one_of('tmp')) } else { if (missing(.problem)) .problem <- max(xpdb[['files']]$problem) if (!all(.source %in% xpdb[['files']]$extension)) { stop('File extension ', stringr::str_c(.source[!.source %in% xpdb[['files']]$extension], collapse = ', '), ' not found in model output files.', call. = FALSE) } if (!all(.problem %in% xpdb[['files']]$problem[xpdb[['files']]$extension %in% .source])) { stop('Problem no.', stringr::str_c(.problem[!.problem %in% xpdb[['files']]$problem], collapse = ', '), ' not found in model output files.', call. = FALSE) } check_quo_vars(xpdb = xpdb, ..., .source = .source, .problem = .problem) xpdb[['files']]$data <- purrr::map_if(.x = xpdb[['files']]$data, .p = xpdb[['files']]$problem %in% .problem & xpdb[['files']]$extension %in% .source, .f = .fun, !!!rlang::enquos(...)) xpdb[['files']] <- xpdb[['files']] %>% dplyr::mutate(modified = dplyr::if_else(.$problem %in% .problem & .$extension %in% .source, TRUE, .$modified)) } as.xpdb(xpdb) } #' Update data index #' #' @description Function dedicated to update the data index after modifications. #' #' @param xpdb An xpose database object from which the index will be updated. #' @param .problem The problem from which the index will be updated. #' #' @keywords internal #' @export xpdb_index_update <- function(xpdb, .problem) { dat <- xpdb[['data']] %>% dplyr::group_by_at(.vars = 'problem') ## TEMP handling if (tidyr_new_interface()) { dat <- dat %>% tidyr::nest(tmp = -dplyr::one_of('problem')) } else { dat <- dat %>% tidyr::nest(.key = 'tmp') } ## END TEMP dat %>% dplyr::ungroup() %>% dplyr::mutate(tmp = purrr::map_if(.$tmp, xpdb[['data']]$problem %in% .problem, function(x) { col_names <- colnames(x$data[[1]]) # Drop columns not present in data anymore x$index[[1]] <- x$index[[1]] %>% dplyr::filter(.$col %in% col_names) # Add new columns found in data add_cols <- col_names[!col_names %in% x$index[[1]]$col] if (length(add_cols) > 0) { x$index[[1]] <- x$index[[1]] %>% dplyr::bind_rows( dplyr::tibble(table = 'na', col = add_cols, type = 'na', label = NA_character_, units = NA_character_)) } x })) %>% tidyr::unnest(dplyr::one_of('tmp')) } #' Check quoted variables #' #' @description Ensure that variables used in quos are present in the #' data and return informative error messages otherwise. #' #' @param xpdb An xpose database object. #' @param ... Name-value pairs of expressions. #' @param .problem The problem from which the data will be modified #' @param .source The source of the data in the xpdb. Can either be 'data' or an output #' file extension e.g. 'phi'. #' #' @return Silent if checks are successful, returns errors otherwise. #' #' @keywords internal #' @export check_quo_vars <- function(xpdb, ..., .source, .problem) { if (.source == 'special') return(invisible()) quo_vars <- rlang::enquos(...) %>% purrr::map(all.vars) %>% purrr::flatten_chr() if (length(quo_vars) > 0) { if (.source == 'data') { tmp <- xpdb$data[xpdb$data$problem %in% .problem, ] } else { tmp <- xpdb$files[xpdb$files$extension %in% .source & xpdb$files$problem %in% .problem, ] } tmp <- dplyr::mutate(.data = tmp, missing = purrr::map(tmp$data, ~stringr::str_c(quo_vars[!quo_vars %in% colnames(.)], collapse = ', ')), error = purrr::map_lgl(tmp$data, ~any(!quo_vars %in% colnames(.)))) if (any(tmp$error)) { tmp %>% dplyr::filter(.$error) %>% dplyr::mutate(string = stringr::str_c('missing: ', .$missing, ' variables in ', ifelse(.source == 'data', '', stringr::str_c('`', .source, '` file ')), '$prob no.', .$problem, '.')) %>% {stop(stringr::str_c(.$string, collapse = '\n '), call. = FALSE)} } } } #' Add simulation counter #' #' @description Add a column containing a simulation counter (irep). A new simulation is counted everytime #' a value in x is lower than its previous value. #' #' @param x The column to be used for computing simulation number, usually the ID column. #' @param quiet Logical, if \code{FALSE} messages are printed to the console. #' #' @examples #' xpdb_ex_pk_2 <- xpdb_ex_pk %>% #' mutate(sim_id = irep(ID), .problem = 2) #' #' @export irep <- function(x, quiet = FALSE) { if (missing(x)) stop('argument "x" is missing, with no default', call. = FALSE) if (is.factor(x)) x <- as.numeric(as.character(x)) x <- dplyr::if_else(dplyr::lag(x, default = x[1]) > x, 1, 0) x <- cumsum(x) + 1 msg(c('irep: ', max(x), ' simulations found.'), quiet) x }
/scratch/gouwar.j/cran-all/cranData/xpose/R/xpdb_edits.R
#' List available datasets #' #' @description Function providing a detailed listing of all available datasets in an xpdb object. #' #' @param xpdb An \code{xpose_data} object to be evaluated #' @seealso \code{\link{get_data}}, \code{\link{get_file}}, \code{\link{get_special}} #' @examples #' # List output tables data #' list_data(xpdb_ex_pk) #' #' # List output files data #' list_files(xpdb_ex_pk) #' #' # List special data #' xpdb_ex_pk %>% #' vpc_data(quiet = TRUE) %>% #' list_special() #' #' @name list_xpdb #' @export list_data <- function(xpdb) { check_xpdb(xpdb, check = 'data') xpdb$data %>% dplyr::select(dplyr::one_of('problem', 'simtab', 'data', 'modified')) %>% {utils::capture.output(print(.))} %>% {c('Data:', .[-1])} %>% cat(sep = '\n') } #' @name list_xpdb #' @export list_files <- function(xpdb) { check_xpdb(xpdb, check = 'files') xpdb$files %>% dplyr::select(dplyr::one_of('name', 'extension', 'problem', 'subprob', 'method', 'data', 'modified')) %>% {utils::capture.output(print(.))} %>% {c('Files:', .[-1])} %>% cat(sep = '\n') } #' @name list_xpdb #' @export list_special <- function(xpdb) { check_xpdb(xpdb, check = 'special') xpdb$special %>% dplyr::select(dplyr::one_of('problem', 'method', 'type', 'data', 'modified')) %>% {utils::capture.output(print(.))} %>% {c('Specials:', .[-1])} %>% cat(sep = '\n') }
/scratch/gouwar.j/cran-all/cranData/xpose/R/xpdb_list.R
#' Default xpose distribution plot function #' #' @description Manually generate distribution plots from an xpdb object. #' #' @inheritParams xplot_scatter #' @param type String setting the type of plot to be used. Can be histogram 'h', #' density 'd', rug 'r' or any combination of the three. #' @param guide Should the guide (e.g. reference distribution) be displayed. #' @section Layers mapping: #' Plots can be customized by mapping arguments to specific layers. The naming convention is #' layer_option where layer is one of the names defined in the list below and option is #' any option supported by this layer e.g. histogram_fill = 'blue', rug_sides = 'b', etc. #' \itemize{ #' \item histogram: options to \code{geom_histogram} #' \item density: options to \code{geom_density} #' \item rug: options to \code{geom_rug} #' \item xscale: options to \code{scale_x_continuous} or \code{scale_x_log10} #' \item yscale: options to \code{scale_y_continuous} or \code{scale_y_log10} #' } #' @inheritSection xplot_scatter Faceting #' @inheritSection xplot_scatter Template titles #' @seealso \code{\link{xplot_scatter}} \code{\link{xplot_qq}} #' #' @examples #' # A simple histogram #' xplot_distrib(xpdb_ex_pk, aes(x = WT), type = 'hr') #' #' # A simple density plot #' xplot_distrib(xpdb_ex_pk, aes(x = CWRES), type = 'dr') #' #' @export xplot_distrib <- function(xpdb, mapping = NULL, type = 'hr', guide = FALSE, xscale = 'continuous', yscale = 'continuous', title = NULL, subtitle = NULL, caption = NULL, tag = NULL, plot_name = 'density_plot', gg_theme, xp_theme, opt, quiet, ...) { # Check input check_xpdb(xpdb, check = FALSE) if (missing(quiet)) quiet <- xpdb$options$quiet # Fetch data if (missing(opt)) opt <- data_opt() data <- fetch_data(xpdb, quiet = quiet, .problem = opt$problem, .subprob = opt$subprob, .method = opt$method, .source = opt$source, simtab = opt$simtab, filter = opt$filter, tidy = opt$tidy, index_col = opt$index_col, value_col = opt$value_col, post_processing = opt$post_processing) if (is.null(data) || nrow(data) == 0) { stop('No data available for plotting. Please check the variable mapping and filering options.', call. = FALSE) } # Check type check_plot_type(type, allowed = c('d', 'h', 'r')) # Assign xp_theme if (!missing(xp_theme)) xpdb <- update_themes(xpdb = xpdb, xp_theme = xp_theme) # Assign gg_theme if (missing(gg_theme)) { gg_theme <- xpdb$gg_theme } else { gg_theme <- update_themes(xpdb = xpdb, gg_theme = gg_theme)$gg_theme } if (is.function(gg_theme)) { gg_theme <- do.call(gg_theme, args = list()) } # Create ggplot base xp <- ggplot(data = data, aes_filter(mapping, keep_only = c('x', 'y'))) + gg_theme # Add histogram if (stringr::str_detect(type, stringr::fixed('h', ignore_case = TRUE))) { xp <- xp + xp_geoms(mapping = mapping %>% aes_rename('y', 'histogram_y') %>% aes_c(fun_aes = aes(histogram_y = after_stat(!!rlang::sym("density")))), xp_theme = xpdb$xp_theme, name = 'histogram', ggfun = 'geom_histogram', ...) } # Add density if (stringr::str_detect(type, stringr::fixed('d', ignore_case = TRUE))) { xp <- xp + xp_geoms(mapping = mapping, xp_theme = xpdb$xp_theme, name = 'density', ggfun = 'geom_density', ...) } # Add rug if (stringr::str_detect(type, stringr::fixed('r', ignore_case = TRUE))) { xp <- xp + xp_geoms(mapping = aes_rename(mapping, 'x', 'rug_x'), xp_theme = xpdb$xp_theme, name = 'rug', ggfun = 'geom_rug', rug_inherit.aes = FALSE, rug_data = data, ...) } # Add reference distibution if (guide) { msg('Reference distribution not yet available.', TRUE) # xp <- xp + xp_geoms(xp_theme = xpdb$xp_theme, # name = 'guide', # ggfun = 'geom_line', # ...) } # Define scales xp <- xp + xp_geoms(mapping = mapping, xp_theme = xpdb$xp_theme, name = 'xscale', ggfun = paste0('scale_x_', xscale), ...) + xp_geoms(mapping = mapping, xp_theme = xpdb$xp_theme, name = 'yscale', ggfun = paste0('scale_y_', yscale), ...) # Define panels if (!is.null(list(...)[['facets']])) { xp <- xp + xpose_panels(xp_theme = xpdb$xp_theme, extra_args = list(...)) } # Add labels xp <- xp + labs(title = title, subtitle = subtitle, caption = caption) if (utils::packageVersion('ggplot2') >= '3.0.0') { xp <- xp + labs(tag = tag) } # Add metadata to plots xp$xpose <- list(fun = plot_name, summary = xpdb$summary, problem = attr(data, 'problem'), subprob = attr(data, 'subprob'), method = attr(data, 'method'), quiet = quiet, xp_theme = xpdb$xp_theme[stringr::str_c(c('title', 'subtitle', 'caption', 'tag'), '_suffix')]) # Ouptut the plot as.xpose.plot(xp) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/xplot_distrib.R
#' Check .problem, .subprob and .method #' #' @param .problem The problem to be checked. #' @param .subprob The subproblem to be checked. #' @param .method The estimation method to be checked. #' #' @keywords internal #' @export check_problem <- function(.problem, .subprob, .method) { bad_input <- list(.problem = .problem, .subprob = .subprob, .method = .method) %>% purrr::keep(.p = ~length(.x) > 1) %>% names() if (length(bad_input) > 0) { bad_input %>% stringr::str_c('`', ., '`', collapse = ', ') %>% {stop('Argument', ., ' must be of length 1.', call. = FALSE)} } } #' Check xpdb #' #' @param xpdb An xpose database object. #' @param check The `xpdb` slot to be checked, can be `data`, `files`, #' `summary`, `special`, `code`, a file name, or `FALSE`. IF `FALSE` the slot #' test will be skipped. #' #' @return Silent if successful check, else returns error. #' #' @keywords internal #' @export check_xpdb <- function(xpdb, check = 'data') { # Check the class if (!is.xpdb(xpdb)) { stop('Bad input to the argument `xpdb`', call. = FALSE) } skip <- ifelse(check == FALSE, TRUE, FALSE) check <- ifelse(!check %in% c('data', 'files', 'summary', 'special', 'code'), 'files', check) # Check for the presence of data if (!skip && is.null(xpdb[[check]])) { stop('No `', check, '` slot could be found in this xpdb.', call. = FALSE) } } #' Check plot `type` #' #' @param type A character string guiding the plot type. #' @param allowed A character vector of all allowed types e.g. `c('p', 'l')`. #' #' @return Silent if proper user input else warns for unrecognized `type`. #' #' @keywords internal #' @export check_plot_type <- function(type, allowed) { type <- stringr::str_extract_all(type, pattern = '.')[[1]] not_allowed <- type[!type %in% allowed] if (length(not_allowed) > 0) { warning('Plot type ', stringr::str_c('"',not_allowed, '"', collapse = ', '), ' not recognized.', call. = FALSE) } } #' Check plot scales #' #' @param scale The axis to be checked. Can be `x` or `y`. #' @param log A string to guide which axis (e.g. `x`, `y` or `xy`) should be #' plotted on log scale. #' #' @return A string taking `continuous` or `log10` as value. #' #' @keywords internal #' @export check_scales <- function(scale, log) { if (is.null(log)) return('continuous') ifelse(stringr::str_detect(string = log, pattern = scale), 'log10', 'continuous') } #' Append suffix contained in the `xp_theme` to titles #' #' @param xpdb An xpose database object. #' @param string A string to which the suffix will be appended. #' @param type A string determining what suffix type should be used #' in the `xp_theme`. Can be one of `title`, `subtitle`, `caption` or `tag`. #' #' @return The modified `string`. #' #' @keywords internal #' @export append_suffix <- function(xpdb, string = NULL, type = NULL) { if (is.null(string)) return() stringr::str_c(string, xpdb$xp_theme[[stringr::str_c(type, '_suffix')]], sep = '') } #' Parse keywords in string based on values contained in an xpdb #' #' @param string A string containing keywords (e.g. `@nobs`) to be parsed #' (e.g. title, label, etc.) using values stored in the `xpdb$summary`. #' @param xpdb An xpose database object. #' @param problem The $problem number to be used. #' @param quiet Should messages be displayed to the console. #' @param extra_key A vector of additional keywords not available in the `xpdb$summary`. #' @param extra_value A vector of values matching the order of `extra_key`. #' @param ignore_key A vector of keywords to be ignored i.e. warnings will not be returned. #' #' @return The parsed `string`. #' #' @keywords internal #' @export parse_title <- function(string, xpdb, problem, quiet, extra_key = NULL, extra_value = NULL, ignore_key = NULL) { # Extract keywords from the string keyword <- string %>% stringr::str_extract_all('@[[:alnum:]]+') %>% purrr::flatten_chr() %>% stringr::str_replace(stringr::fixed('@'), '') %>% subset(!. %in% ignore_key) # Get the associated values in the summart values <- xpdb$summary[xpdb$summary$problem %in% c(0, problem) & xpdb$summary$label %in% keyword, ] values <- values[!duplicated(values$label, fromLast = TRUE), ] # If needed add extra values e.g. in xpose_save if (!is.null(extra_key) && any(extra_key %in% keyword)) { values <- dplyr::bind_rows(values, dplyr::tibble(problem = 0, subp = 0, label = extra_key, value = extra_value)) } # Remove unmatched keywords from the list if (!all(keyword %in% values$label)) { keyword[!keyword %in% values$label & !keyword %in% ignore_key] %>% unique() %>% stringr::str_c(collapse = ', ') %>% {warning(c(., ' is not part of the available keywords. Check ?template_titles for a full list.'), call. = FALSE)} keyword <- keyword[keyword %in% values$label] } if (length(keyword) == 0) return(string) # Replaces values in the string string %>% stringr::str_replace_all(stringr::str_c('@', keyword, collapse = '|'), '${values$value[values$label == \"\\0\"]}') %>% stringr::str_replace_all('\\"@', '\\"') %>% stringr::str_interp() } #' Subset an `xp_theme` #' #' @param xp_theme An xpose theme list. #' @param regex A string used to find matching names in the `xp_theme` #' @param action A string used to determine the action of on the xp_theme. #' `keep` will subset the `xp_theme` to only the names matching the `regex`, #' while `drop` will drop the matches. #' #' @return A modified `xp_theme` #' #' @keywords internal #' @export filter_xp_theme <- function(xp_theme, regex = NULL, action = 'keep') { match <- stringr::str_detect(names(xp_theme), regex) if (action == 'drop') match <- !match xp_theme[match] } #' Get all data problems #' #' @param xpdb An xpose database object. #' #' @return The number of the all data problems as an integer #' vector. #' #' @keywords internal #' @export all_data_problem <- function(xpdb) { prob_n <- xpdb$data$problem if (length(prob_n) == 0) return(NA_integer_) unique(prob_n) } #' Get last data problem #' #' @description Used by several internal functions when the problem argument has not #' been supplied by the user. #' #' @param xpdb An xpose database object. #' @param simtab Logical if `TRUE` the last simulation problem is returned. If `FALSE` #' the last estimation problem is returned. #' #' @return The last estimation problem when `simtab = FALSE`, #' else the last simulation problem as an integer. #' #' @keywords internal #' @export last_data_problem <- function(xpdb, simtab = FALSE) { prob_n <- xpdb$data$simtab if (!simtab) prob_n <- !prob_n prob_n <- xpdb$data$problem[prob_n] if (length(prob_n) == 0) return(NA_integer_) max(prob_n) } #' Get the default data problem to be plotted #' #' @description Used by plot functions when the problem argument has not #' been supplied by the user. #' #' @param xpdb An xpose database object. #' #' @return The last estimation problem when at least one estimation problem is present, #' else the last simulation problem as an integer. #' #' @keywords internal #' @export default_plot_problem <- function(xpdb){ last_data_problem(xpdb, simtab = all(xpdb$data$simtab)) } #' Get all file problems #' #' @param xpdb An xpose database object. #' @param ext The file extension to be used. #' #' @return The number of the all file problems as an integer #' vector for the given file `ext`. #' #' @keywords internal #' @export all_file_problem <- function(xpdb, ext) { prob_n <- xpdb$files$problem[xpdb$files$extension %in% ext] prob_n <- unique(prob_n) if (length(prob_n) == 0) return(NA_integer_) prob_n } #' Get last file problem #' #' @param xpdb An xpose database object. #' @param ext The file extension to be used. #' #' @return The number of the last file problem as an integer #' for the given file `ext`. #' #' @keywords internal #' @export last_file_problem <- function(xpdb, ext) { prob_n <- all_file_problem(xpdb = xpdb, ext = ext) max(prob_n) } #' Get last file subproblem #' #' @param xpdb An xpose database object. #' @param ext The file extension to be used. #' @param .problem The $problem number to be used. #' #' @return The number of the last file subproblem as an integer #' for the given `.problem` and file `ext`. #' #' @keywords internal #' @export last_file_subprob <- function(xpdb, ext, .problem) { subprob_n <- xpdb$files$subprob[xpdb$files$extension %in% ext & xpdb$files$problem %in% .problem] subprob_n <- unique(subprob_n) if (length(subprob_n) == 0) return(NA_integer_) max(subprob_n) } #' Get last file estimation method #' #' @param xpdb An xpose database object. #' @param ext The file extension to be used. #' @param .problem The $problem number to be used. #' @param .subprob The subproblem number to be used. #' #' @return The number of the last file method as character #' for the given `.problem` and file `ext`. #' #' @keywords internal #' @export last_file_method <- function(xpdb, ext, .problem, .subprob) { method_n <- xpdb$files$method[xpdb$files$extension %in% ext & xpdb$files$problem %in% .problem & xpdb$files$subprob %in% .subprob] method_n <- unique(method_n) if (length(method_n) == 0) return(NA_integer_) method_n[length(method_n)] } #' Return names of columns having several unique values #' #' @param xpdb An xpose database object. #' @param .problem The $problem number to be used. #' @param cols A vector of column names to be checked. #' @param quiet Should messages be displayed to the console. #' #' @return A subset of `col` for which more than one single #' value was found in the data. #' #' @keywords internal #' @export drop_fixed_cols <- function(xpdb, .problem, cols, quiet) { if (is.null(cols)) return() # Get the column names to be removed cols_rm <- get_data(xpdb, .problem = .problem) %>% dplyr::select_at(cols) %>% dplyr::select_if(.predicate = function(x) length(unique(x)) == 1) %>% colnames() if (length(cols_rm) == 0) return(cols) # Get the column names to be kept cols <- dplyr::setdiff(x = cols, y = cols_rm) if (length(cols) == 0) { stop('No non-fixed variables available for plotting.', call. = FALSE) } # Print message dplyr::if_else(length(cols_rm) > 5, stringr::str_c(stringr::str_c(cols_rm[1:5], collapse = ', '), '... and', length(cols_rm) - 5 , 'more', sep = ' '), stringr::str_c(cols_rm , collapse = ', ')) %>% {msg(c('Dropped fixed variables ', .,'.'), quiet)} cols } #' Access xpdb index information for a given variable or variable type #' #' @param xpdb An xpose database object. #' @param .problem The $problem number to be used. #' @param col The column name to be searched in the index. Alternative to arg `type`. #' @param type The type of column to searched in the index. Alternative to `col`. #' @param silent Should the function be silent or return errors. #' #' @return A subset of the xpdb index as tibble with columns: #' col (column name), type (column type in the index), #' label (label associated with the column) and units #' (units associated with the column) #' #' @keywords internal #' @export xp_var <- function(xpdb, .problem, col = NULL, type = NULL, silent = FALSE) { if (!all(.problem %in% xpdb$data$problem)) { stop('$prob no.', stringr::str_c(.problem[!.problem %in% xpdb$data$problem], collapse = ', '), ' not found in model output data.', call. = FALSE) } index <- xpdb$data[xpdb$data$problem == .problem, ]$index[[1]] if (!is.null(type)) { index <- index[index$type %in% type, ] } else { index <- index[index$col %in% col, ] } if (nrow(index) == 0) { if (silent) return() stop('Column ', ifelse(!is.null(type), stringr::str_c('type ', stringr::str_c('`',type, '`', collapse = ', ')), stringr::str_c('`',col, '`', collapse = ', ')), ' not available in data for problem no.', .problem, '. Check `list_vars()` for an exhaustive list of available columns.', call. = FALSE) } index %>% dplyr::distinct(!!rlang::sym('col'), .keep_all = TRUE) %>% dplyr::select(dplyr::one_of('col', 'type', 'label', 'units')) %>% dplyr::arrange_at(.vars = c('type', 'col')) } #' Set new default value for ggplot2 aesthetics #' #' @param fun_aes Default ggplot2 aesthetics mapping defined for the function #' @param user_aes ggplot2 aesthetics mapping inputted by the user. These #' aesthetics will overwrite matching elements in `fun_aes`. #' #' @return ggplot2 aesthetics mapping #' #' @keywords internal #' @export aes_c <- function(fun_aes, user_aes) { if (is.null(user_aes)) return(fun_aes) aes <- c(fun_aes[!names(fun_aes) %in% names(user_aes)], user_aes) structure(aes, class = 'uneval') } #' Convenience function to easily filter ggplot2 aesthetics #' #' @param mapping ggplot2 aesthetics #' @param drop names of ggplot2 aesthetics to be removed from the `mapping`. #' Alternative to the `keep_only` argument. #' @param keep_only names of the only ggplot2 aesthetics to be kept in the #' `mapping`. Alternative to the `drop` argument. #' #' @return ggplot2 aesthetics mapping #' #' @keywords internal #' @export aes_filter <- function(mapping, drop = NULL, keep_only = NULL) { if (is.null(mapping)) return() if (!is.null(keep_only)) { aes <- mapping[names(mapping) %in% keep_only] } else { aes <- mapping[!names(mapping) %in% drop] } if (length(aes) == 0) return() aes } #' Convenience function to easily rename ggplot2 aesthetics #' #' @param mapping ggplot2 aesthetics #' @param from names of ggplot2 aesthetics to be renamed. Note: should match the #' order of arg `to`. #' @param to new names to be set for ggplot2 aesthetics. Note: should match the #' order of arg `from`. #' #' @return ggplot2 aesthetics mapping #' #' @keywords internal #' @export aes_rename <- function(mapping, from, to) { if (is.null(mapping)) return() if (!any(from %in% names(mapping))) return(mapping) names(mapping)[match(from, names(mapping))] <- to[which(from %in% names(mapping))] mapping } #' Add faceting variable #' #' @description Convenience function to add default faceting variable #' #' @param facets User input faceting variable as a character or formula. #' @param variable Default variable to be appended to variables in facets. #' #' @return facets as formula or character string. #' #' @keywords internal #' @export add_facet_var <- function(facets, variable = 'variable') { if (!is.formula(facets)) { c(variable, facets) } else { stats::update.formula(old = facets, new = stats::as.formula(stringr::str_c('~. + ', variable))) } }
/scratch/gouwar.j/cran-all/cranData/xpose/R/xplot_helpers.R
#' Default xpose QQ plot function #' #' @description Manually generate QQ plots from an xpdb object. #' #' @inheritParams xplot_scatter #' @param type String setting the type of plot to be used. Can only be points 'p'. #' @param guide Should the guide (e.g. reference line) be displayed. #' #' @section Layers mapping: #' Plots can be customized by mapping arguments to specific layers. The naming convention is #' layer_option where layer is one of the names defined in the list below and option is #' any option supported by this layer e.g. point_color = 'blue', etc. #' \itemize{ #' \item point: options to \code{geom_point} #' \item guide: options to \code{geom_abline} #' \item xscale: options to \code{scale_x_continuous} or \code{scale_x_log10} #' \item yscale: options to \code{scale_y_continuous} or \code{scale_y_log10} #' } #' @inheritSection xplot_scatter Faceting #' @inheritSection xplot_scatter Template titles #' @seealso \code{\link{xplot_scatter}} \code{\link{xplot_distrib}} #' #' @examples #' xplot_qq(xpdb_ex_pk, aes(sample = CWRES), guide = TRUE) #' #' @export xplot_qq <- function(xpdb, mapping = NULL, type = 'p', guide = FALSE, xscale = 'continuous', yscale = 'continuous', title = NULL, subtitle = NULL, caption = NULL, tag = NULL, plot_name = 'qq_plot', gg_theme, xp_theme, opt, quiet, ...) { # Check input check_xpdb(xpdb, check = FALSE) if (missing(quiet)) quiet <- xpdb$options$quiet # Fetch data if (missing(opt)) opt <- data_opt() data <- fetch_data(xpdb, quiet = quiet, .problem = opt$problem, .subprob = opt$subprob, .method = opt$method, .source = opt$source, simtab = opt$simtab, filter = opt$filter, tidy = opt$tidy, index_col = opt$index_col, value_col = opt$value_col, post_processing = opt$post_processing) if (is.null(data) || nrow(data) == 0) { stop('No data available for plotting. Please check the variable mapping and filering options.', call. = FALSE) } # Check type check_plot_type(type, allowed = 'p') # Assign xp_theme if (!missing(xp_theme)) xpdb <- update_themes(xpdb = xpdb, xp_theme = xp_theme) # Assign gg_theme if (missing(gg_theme)) { gg_theme <- xpdb$gg_theme } else { gg_theme <- update_themes(xpdb = xpdb, gg_theme = gg_theme)$gg_theme } if (is.function(gg_theme)) { gg_theme <- do.call(gg_theme, args = list()) } # Create ggplot base xp <- ggplot(data = data, mapping) + gg_theme # Add points (note: could not get geom_text to work with stat_qq) if (stringr::str_detect(type, stringr::fixed('p', ignore_case = TRUE))) { xp <- xp + xp_geoms(mapping = mapping, xp_theme = xpdb$xp_theme, name = 'point', ggfun = 'geom_point', point_stat = 'qq', ...) } # Add reference line if (guide) { if (utils::packageVersion('ggplot2') >= '3.0.0') { xp <- xp + xp_geoms(xp_theme = xpdb$xp_theme, name = 'guide', ggfun = 'geom_qq_line', ...) } else { warning('QQ guides are only available for ggplot2 >= 3.0.0.', call. = FALSE) } } # Define scales xp <- xp + xp_geoms(mapping = mapping, xp_theme = xpdb$xp_theme, name = 'xscale', ggfun = paste0('scale_x_', xscale), ...) + xp_geoms(mapping = mapping, xp_theme = xpdb$xp_theme, name = 'yscale', ggfun = paste0('scale_y_', yscale), ...) # Define panels if (!is.null(list(...)[['facets']])) { xp <- xp + xpose_panels(xp_theme = xpdb$xp_theme, extra_args = list(...)) } # Add labels xp <- xp + labs(title = title, subtitle = subtitle, caption = caption) if (utils::packageVersion('ggplot2') >= '3.0.0') { xp <- xp + labs(tag = tag) } # Add metadata to plots xp$xpose <- list(fun = plot_name, summary = xpdb$summary, problem = attr(data, 'problem'), subprob = attr(data, 'subprob'), method = attr(data, 'method'), quiet = quiet, xp_theme = xpdb$xp_theme[stringr::str_c(c('title', 'subtitle', 'caption', 'tag'), '_suffix')]) # Ouptut the plot as.xpose.plot(xp) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/xplot_qq.R
#' Default xpose scatter plot function #' #' @description Manually generate scatter plots from an xpdb object. #' #' @param xpdb An \code{xpose_data} object generated with \code{\link{xpose_data}}. #' @param mapping List of aesthetics mappings to be used for the xpose plot #' (e.g. \code{point_color}). #' @param group Grouping variable to be used for lines. #' @param type String setting the type of plot to be used. Can be line 'l', #' point 'p', smooth 's' and text 't' or any combination of the four. #' @param guide Should the guide (e.g. unity line) be displayed. #' @param xscale Scale type for x axis (e.g. 'continuous', 'discrete', 'log10'). #' @param yscale Scale type for y axis (e.g. 'continuous', 'discrete', 'log10'). #' @param title Plot title. Use \code{NULL} to remove. #' @param subtitle Plot subtitle. Use \code{NULL} to remove. #' @param caption Page caption. Use \code{NULL} to remove. #' @param tag Plot identification tag. Use \code{NULL} to remove. #' @param plot_name Name to be used by \code{xpose_save()} when saving the plot. #' @param opt A list of options in order to create appropriate data input for #' ggplot2. For more information see \code{\link{data_opt}}. #' @param quiet Logical, if \code{FALSE} messages are printed to the console. #' @param ... Any additional aesthetics. #' #' @inheritParams update_themes #' #' @section Layers mapping: #' Plots can be customized by mapping arguments to specific layers. The naming convention is #' layer_option where layer is one of the names defined in the list below and option is #' any option supported by this layer e.g. point_color = 'blue', smooth_method = 'lm', etc. #' \itemize{ #' \item point: options to \code{geom_point} #' \item line: options to \code{geom_line} #' \item guide: options to \code{geom_abline} #' \item smooth: options to \code{geom_smooth} #' \item text: options to \code{geom_text} #' \item xscale: options to \code{scale_x_continuous} or \code{scale_x_log10} #' \item yscale: options to \code{scale_y_continuous} or \code{scale_y_log10} #' } #' #' @section Faceting: #' Every xpose plot function has built-in faceting functionalities. Faceting arguments #' are passed to the functions \code{\link[ggforce]{facet_wrap_paginate}} when the \code{facets} #' argument is a character string (e.g. \code{facets = c('SEX', 'MED1')}) or #' \code{\link[ggforce]{facet_grid_paginate}} when facets is a formula (e.g. \code{facets = SEX~MED1}). #' All xpose plot functions accept all the arguments for the \code{\link[ggforce]{facet_wrap_paginate}} #' and \code{\link[ggforce]{facet_grid_paginate}} functions e.g. \code{dv_vs_ipred(xpdb_ex_pk, #' facets = SEX~MED1, ncol = 3, nrow = 3, page = 1, margins = TRUE, labeller = 'label_both')}. #' #' Faceting options can either be defined in plot functions (e.g. \code{dv_vs_ipred(xpdb_ex_pk, #' facets = 'SEX')}) or assigned globally to an xpdb object via the \code{xp_theme} (e.g. \code{xpdb #' <- update_themes(xpdb_ex_pk, xp_theme = list(facets = 'SEX'))}). In the latter example all plots #' generate from this xpdb will automatically be stratified by `SEX`. #' #' By default, some plot functions use a custom stratifying variable named `variable`, e.g. #' \code{eta_distrib()}. When using the \code{facets} argument, `variable` needs to be added manually #' e.g. \code{facets = c('SEX', 'variable')} or \code{facets = c('SEX', 'variable')}, but is optional, #' when using the \code{facets} argument in \code{xp_theme} variable is automatically added whenever needed. #' #' @section Template titles: #' Template titles can be used to create highly informative diagnostics plots. #' They can be applied to any plot title, subtitle, caption and tag. Template titles #' are defined via a single string containing key variables staring with a `@` (e.g. `@ofv`) #' which will be replaced by their actual value when rendering the plot. #' For example `'@run, @nobs observations in @nind subjects'` would become #' `'run001, 1022 observations in 74 subjects'`. The available key variables #' are listed under \code{\link{template_titles}}. #' #' @seealso \code{\link{xplot_distrib}} \code{\link{xplot_qq}} #' @examples #' xplot_scatter(xpdb_ex_pk, aes(x = IPRED, y = DV)) #' #' @export xplot_scatter <- function(xpdb, mapping = NULL, group = 'ID', type = 'pls', guide = FALSE, xscale = 'continuous', yscale = 'continuous', title = NULL, subtitle = NULL, caption = NULL, tag = NULL, plot_name = 'scatter_plot', gg_theme, xp_theme, opt, quiet, ...) { # Check input check_xpdb(xpdb, check = FALSE) if (missing(quiet)) quiet <- xpdb$options$quiet # Fetch data if (missing(opt)) opt <- data_opt() data <- fetch_data(xpdb, quiet = quiet, .problem = opt$problem, .subprob = opt$subprob, .method = opt$method, .source = opt$source, simtab = opt$simtab, filter = opt$filter, tidy = opt$tidy, index_col = opt$index_col, value_col = opt$value_col, post_processing = opt$post_processing) if (is.null(data) || nrow(data) == 0) { stop('No data available for plotting. Please check the variable mapping and filering options.', call. = FALSE) } # Check type check_plot_type(type, allowed = c('l', 'p', 's', 't')) # Assign xp_theme if (!missing(xp_theme)) xpdb <- update_themes(xpdb = xpdb, xp_theme = xp_theme) # Assign gg_theme if (missing(gg_theme)) { gg_theme <- xpdb$gg_theme } else { gg_theme <- update_themes(xpdb = xpdb, gg_theme = gg_theme)$gg_theme } if (is.function(gg_theme)) { gg_theme <- do.call(gg_theme, args = list()) } # Create ggplot base xp <- ggplot(data = data, mapping) + gg_theme # Add lines if (stringr::str_detect(type, stringr::fixed('l', ignore_case = TRUE))) { xp <- xp + xp_geoms(mapping = c(mapping, aes(line_group = .data[[group]])), xp_theme = xpdb$xp_theme, name = 'line', ggfun = 'geom_line', ...) } # Add points if (stringr::str_detect(type, stringr::fixed('p', ignore_case = TRUE))) { xp <- xp + xp_geoms(mapping = mapping, xp_theme = xpdb$xp_theme, name = 'point', ggfun = 'geom_point', ...) } # Add text if (stringr::str_detect(type, stringr::fixed('t', ignore_case = TRUE))) { xp <- xp + xp_geoms(mapping = c(mapping, aes(text_label = .data[[group]])), xp_theme = xpdb$xp_theme, name = 'text', ggfun = 'geom_text', ...) } # Add unity line if (guide) { xp <- xp + xp_geoms(xp_theme = xpdb$xp_theme, name = 'guide', ggfun = 'geom_abline', ...) } # Add smooth if (stringr::str_detect(type, stringr::fixed('s', ignore_case = TRUE))) { xp <- xp + xp_geoms(mapping = mapping, xp_theme = xpdb$xp_theme, name = 'smooth', ggfun = 'geom_smooth', ...) } # Define scales xp <- xp + xp_geoms(mapping = mapping, xp_theme = xpdb$xp_theme, name = 'xscale', ggfun = paste0('scale_x_', xscale), ...) + xp_geoms(mapping = mapping, xp_theme = xpdb$xp_theme, name = 'yscale', ggfun = paste0('scale_y_', yscale), ...) # Define panels if (!is.null(list(...)[['facets']])) { xp <- xp + xpose_panels(xp_theme = xpdb$xp_theme, extra_args = list(...)) } # Add labels xp <- xp + labs(title = title, subtitle = subtitle, caption = caption) if (utils::packageVersion('ggplot2') >= '3.0.0') { xp <- xp + labs(tag = tag) } # Add metadata to plots xp$xpose <- list(fun = plot_name, summary = xpdb$summary, problem = attr(data, 'problem'), subprob = attr(data, 'subprob'), method = attr(data, 'method'), quiet = quiet, xp_theme = xpdb$xp_theme[stringr::str_c(c('title', 'subtitle', 'caption', 'tag'), '_suffix')]) # Ouptut the plot as.xpose.plot(xp) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/xplot_scatter.R
#' xpose: graphical diagnostics for pharmacometric models #' #' @description xpose was designed as a ggplot2-based alternative to xpose4. This package aims to reduce the post #' processing burden and improve diagnostics commonly associated the development of non-linear mixed effect models. #' #' To learn more about xpose, visit our website: \url{https://uupharmacometrics.github.io/xpose/}. #' @import ggplot2 #' @importFrom dplyr n #' @importFrom rlang := #' @importFrom rlang .data #' @keywords internal "_PACKAGE"
/scratch/gouwar.j/cran-all/cranData/xpose/R/xpose.R
#' Import NONMEM output into R #' #' @description Gather model outputs into a R database #' #' @param runno Run number to be used to generate model file name. Used in #' combination with \code{prefix} and \code{ext}. #' @param prefix Prefix to be used to generate model file name. Used in #' combination with \code{runno} and \code{ext}. #' @param ext Extension to be used to generate model file name. Should be one of #' '.lst' (default), '.out', '.res', '.mod' or '.ctl' for NONMEM. #' @param file Model file name (preferably a '.lst' file) containing the file #' extension. Alternative to \code{prefix}, \code{runno} and \code{ext} #' arguments. #' @param dir Location of the model files. #' @param gg_theme A complete ggplot2 theme object (e.g. #' \code{\link[ggplot2]{theme_classic}}), or a function returning a complete #' ggplot2 theme. #' @param xp_theme A complete xpose theme object (e.g. #' \code{\link{theme_xp_default}}). #' @param simtab If \code{TRUE} only reads in simulation tables, if \code{FALSE} #' only reads estimation tables. Default \code{NULL} reads all tables. Option #' not compatible with manual_import. #' @param manual_import If \code{NULL} (default) the names of the output tables #' to import will be obtained from the model file. To manually import files as #' in previous versions of xpose, the check the function #' \code{\link{manual_nm_import}}. #' @param ignore Character vector be used to ignore the import/generation of: #' 'data', 'files', 'summary' or any combination of the three. #' @param check_ext Logical, if \code{TRUE} will provide an error message if the #' extension of the NONMEM input file is not one of '.lst', '.out', '.res', #' '.mod' or '.ctl' for NONMEM. If \code{FALSE} any file extension can be #' used. #' @param extra_files A vector of additional output file extensions to be #' imported. Default is '.ext', '.cov', '.cor', '.phi', '.grd' for NONMEM. #' @param quiet Logical, if \code{FALSE} messages are printed to the console. #' @param ... Additional arguments to be passed to the #' \code{\link{read_nm_tables}} functions. #' #' @section File path generation: The rules for model file names generation are #' as follow: \itemize{ #' \item with \code{runno}: the full path is generated as #' \code{<dir>/<prefix><runno>.<ext>} e.g. with \code{dir = 'model/pk'}, #' \code{prefix = 'run'}, \code{runno = '001'}, \code{ext = '.lst'} the #' resulting path would be \code{model/pk/run001.lst} #' \item with \code{file}: #' the full path is generated as \code{<dir>/<file>} e.g. with \code{dir = #' 'model/pk'}, \code{file = 'run001.lst'} the resulting path would also be #' \code{model/pk/run001.lst}. Note: in this case the file extension should be #' provided as part of the `file` argument. #' } #' #' @section Table format requirement: When importing data, an \code{ID} column #' must be present in at least one table for each problem and for each #' `firstonly` category. \code{ID} columns are required to properly #' combine/merge tables and removing \code{NA} records. If \code{ID} columns #' are missing xpose will return the following warning: \code{Dropped #' `<tablenames>` due to missing required `ID` column.} #' #' @examples #' \dontrun{ #' # Using the `file` argument to point to the model file: #' xpdb <- xpose_data(file = 'run001.lst', dir = 'models') #' #' # Using the `runno` argument to point to the model file: #' xpdb <- xpose_data(runno = '001', ext = '.lst', dir = 'models') #' #' # Using the `extra_files` argument to import specific output files only: #' xpdb <- xpose_data(file = 'run001.lst', dir = 'models', extra_files = c('.ext', '.phi')) #' #' # Using `ignore` to disable import of tables and output files: #' xpdb <- xpose_data(file = 'run001.lst', dir = 'models', ignore = c('data', 'files')) #' #' # Using `simtab` to disable import of simulation tables #' xpdb <- xpose_data(file = 'run001.lst', dir = 'models', simtab = FALSE) #' #' } #' #' @export xpose_data <- function(runno = NULL, prefix = 'run', ext = '.lst', file = NULL, dir = NULL, gg_theme = theme_readable, xp_theme = theme_xp_default(), simtab = NULL, manual_import = NULL, ignore = NULL, check_ext = TRUE, extra_files, quiet, ...) { # Check inputs if (is.null(runno) && is.null(file)) { stop('Argument `runno` or `file` required.', call. = FALSE) } if (!is.function(gg_theme) && (!is.theme(gg_theme) || !attr(gg_theme, 'complete'))) { stop('Argument `gg_theme` must be a full ggplot2 theme or a function returning a theme. To modify a pre-existing theme use update_themes() instead.', call. = FALSE) } if (!is.xpose.theme(xp_theme)) { stop('Argument `xp_theme` must be a full xpose theme. To modify a theme use update_themes() instead.', call. = FALSE) } if (missing(quiet)) quiet <- !interactive() # Check extensions if (!is.null(runno)) { ext <- make_extension(ext) full_path <- file_path(dir, stringr::str_c(prefix, runno, ext)) } else { ext <- get_extension(file) if (ext == '') stop('An extension should be provided in the `file` name.', call. = FALSE) full_path <- file_path(dir, file) } # List tables if (ext %in% c('.lst', '.out', '.res', '.mod', '.ctl') | !check_ext) { software <- 'nonmem' model_code <- read_nm_model(file = basename(full_path), dir = dirname(full_path), check_ext = check_ext) if (is.null(manual_import)) { tbl_names <- list_nm_tables(model_code) } else { tbl_names <- list_nm_tables_manual(runno = runno, file = basename(full_path), dir = dirname(full_path), tab_list = manual_import) } } else { stop(paste( 'Model file currently not supported by xpose. If you want to use the', ext ,'extension anyway use `check_ext = FALSE`'), call. = FALSE) } # Import estimation tables if ('data' %in% ignore) { msg('Ignoring data import.', quiet) data <- NULL } else if (software == 'nonmem') { data <- tryCatch(read_nm_tables(file = tbl_names, dir = NULL, quiet = quiet, simtab = simtab, ...), error = function(e) { warning(e$message, call. = FALSE) return() }) } # Generate model summary if ('summary' %in% ignore) { msg('Ignoring summary generation', quiet) summary <- NULL } else if (software == 'nonmem') { summary <- tryCatch(summarise_nm_model(file = full_path, model = model_code, software = software, rounding = xp_theme$rounding), error = function(e) { warning(c('Failed to create run summary. ', e$message), call. = FALSE) return() }) } # Import output files if ('files' %in% ignore) { msg('Ignoring output files import', quiet) out_files <- NULL } else if (software == 'nonmem') { if (missing(extra_files)) { extra_files <- c('.ext', '.cor', '.cov', '.phi', '.grd', '.shk') } else { extra_files <- make_extension(extra_files) } out_files <- full_path %>% basename() %>% update_extension(ext = extra_files) %>% {tryCatch(read_nm_files(file = ., dir = dirname(full_path), quiet = quiet), error = function(e) { warning(e$message, call. = FALSE) return() })} } # Label themes attr(gg_theme, 'theme') <- as.character(substitute(gg_theme)) attr(xp_theme, 'theme') <- as.character(substitute(xp_theme)) # Output xpose_data list(code = model_code, summary = summary, data = data, files = out_files, gg_theme = gg_theme, xp_theme = xp_theme, options = list(dir = dirname(full_path), quiet = quiet, manual_import = manual_import)) %>% structure(class = c('xpose_data', 'uneval')) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/xpose_data.R
#' Parse arguments from xpose to ggplot2 format #' #' @description Transform arguments from xpose (e.g. point_color) #' to ggplot2 (e.g. color) format. #' #' @param x A list of xpose plot aesthetics. #' @param name Name of the destination layer for the argument #' parsing (e.g. point). #' #' @return ggplot2 aesthetics for the layer defined in `name`. #' #' @keywords internal #' @export parse_arg <- function(x = NULL, name) { if (is.null(x)) return() x[stringr::str_detect(names(x), stringr::str_c('^', name, '_'))] %>% purrr::set_names(nm = stringr::str_replace(names(.), stringr::str_c(name, '_'), '')) %>% purrr::set_names(nm = stringr::str_replace(names(.), 'color', 'colour')) } #' Update `xpose_geoms` arguments #' #' @description Combine the arguments from the user and the `xp_theme`. #' #' @param thm_arg A subset of `xp_theme` used to test defaults. #' @param name Name of the destination layer for the argument #' parsing (e.g. point). #' @param ... User arguments. #' #' @return A list of arguments for the layer defined in `name`. #' #' @keywords internal #' @export update_args <- function(thm_arg, name, ...) { thm_arg <- parse_arg(x = thm_arg, name = name) usr_arg <- parse_arg(x = list(...), name = name) usr_changes <- intersect(names(thm_arg), names(usr_arg)) thm_arg[usr_changes] <- usr_arg[usr_changes] c(thm_arg, usr_arg[!names(usr_arg) %in% names(thm_arg)]) } #' ggplot2 layer call #' #' @description Function calling the ggplot2 layer function #' with its parsed arguments. #' #' @param arg A list of arguments for the target layer. #' @param mapping ggplot2 aesthetics for the target layer. #' @param ggfun Name of the ggplot2 layer function to be called. #' #' @return Output of the `ggfun` call. #' #' @keywords internal #' @export xp_map <- function(arg, mapping, ggfun) { x <- do.call(ggfun, arg[!names(arg) %in% names(mapping)]) if (!is.null(mapping)) x$mapping <- mapping x } #' Generic ggplot2 layer for `xpose_plots` #' #' @description Generic wrapper around ggplot2 layer functions. #' #' @param mapping ggplot2 aesthetics for the target layer. #' @param xp_theme An `xpose_theme` object. #' @param name Name of the destination layer for the argument #' parsing (e.g. point). #' @param ggfun Name of the ggplot2 layer function to be called. #' @param ... Additional arguments to be parsed and passed to the #' destination layer. #' #' @return Output of the `ggfun` call. #' #' @keywords internal #' @export xp_geoms <- function(mapping = NULL, xp_theme, name, ggfun, ...) { if (!is.null(mapping)) mapping <- parse_arg(mapping, name) thm_arg <- filter_xp_theme(xp_theme, stringr::str_c('^', name, '_')) arg <- update_args(thm_arg, name, ...) xp_map(arg, mapping, ggfun) } #' Generic panel function for `xpose_plots` #' #' @description Convenience wrapper around ggforce faceting functions. #' #' @param xp_theme An `xpose_theme` object. #' @param extra_args User arguments to be passed to the #' faceting functions. #' #' @return Output a `facet` layer. Layer will be `facet_wrap_paginate` if #' `facets` is a string, and `facet_grid_paginate` if `facets` is a formula. #' #' @keywords internal #' @export xpose_panels <- function(xp_theme, extra_args) { if (!is.formula(extra_args$facets)) { thm_arg <- xp_theme[c('facets', 'nrow', 'ncol', 'scales', 'shrink', 'labeller', 'as.table', 'drop', 'dir', 'switch', 'strip.position', 'page')] facet_fun <- 'facet_wrap_paginate' } else { thm_arg <- xp_theme[c('facets', 'margins', 'scales', 'space', 'shrink', 'labeller', 'as.table', 'switch', 'drop', 'ncol', 'nrow', 'page', 'byrow')] facet_fun <- 'facet_grid_paginate' } usr_changes <- intersect(names(thm_arg), names(extra_args)) class(thm_arg) <- 'list' thm_arg[usr_changes] <- extra_args[usr_changes] do.call(facet_fun, thm_arg) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/xpose_geom.R
#' Save xpose plot #' #' @description Built as a wrapper around \link[ggplot2]{ggsave}, this function #' facilitates the export of xpose plots. #' #' @param plot A xpose plot object. #' @param file A name with file extension (if device is \code{NULL}) to be given #' to the output file. Template variables such as \code{@run} (run number) and #' \code{@plotfun} (plot function) can be used to automatically name files #' e.g. \code{file = '@[email protected]'}. #' @param dir Directory under which the xpose plots will be saved. Template #' variables such as \code{@dir} can be used to generate template names. #' @param device Graphical device to use. Can be either be a device function #' (e.g. \code{\link{png}}), or one of 'eps', 'ps', 'tex' (pictex), 'pdf', #' 'jpeg', 'tiff', 'png', 'bmp', 'svg' or 'wmf' (windows only). #' @param scale Multiplicative scaling factor. #' @param width,height,units Plot size in in \code{units} ("in", "cm", "mm", or #' "px"). If not supplied, uses the size of current graphics device. #' @param dpi Plot resolution. Also accepts a string input: "retina" (320), #' "print" (300), or "screen" (72). Applies only to raster output types. #' @param limitsize When \code{TRUE} (the default), \code{xpose_save()} will not #' save images larger than 50x50 inches, to prevent the common error of #' specifying dimensions in pixels. #' @param bg Background color. If \code{NULL}, uses the \code{plot.background} #' fill value from the plot theme. #' @param ... Other arguments passed on to the graphics device function, as #' specified by \code{device}. #' #' @examples #' \dontrun{ #' xpdb_ex_pk %>% #' dv_vs_ipred() %>% #' xpose_save(file = file.path(tempdir(), "dv_vs_ipred_example.pdf")) #' } #' @export xpose_save <- function(plot = last_plot(), file = NULL, dir = NULL, device = NULL, scale = 1, width = 7, height = 6, units = c('in', 'cm', 'mm', "px"), dpi = 200, limitsize = TRUE, bg = NULL, ...) { if (is.null(plot)) { stop('Argument `plot` required.', call. = FALSE) } else if (is.null(file)) { stop('Argument `file` required.', call. = FALSE) } # Parse the dir and file arguments for keywords if (!is.null(dir)) { dir <- parse_title(string = dir, xpdb = plot$xpose, problem = plot$xpose$problem, quiet = plot$xpose$quiet, extra_key = 'plotfun', extra_value = plot$xpose$fun) } file <- parse_title(string = file, xpdb = plot$xpose, problem = plot$xpose$problem, quiet = plot$xpose$quiet, extra_key = 'plotfun', extra_value = plot$xpose$fun) # Add device to file if (!is.null(device) && !is.function(device) && !grepl('\\.[[:alnum:]]+$', file)) { file <- paste0(file, '.', device) } # Call ggsave ggsave( plot = plot, filename = file, path = dir, device = device, width = width, height = height, scale = scale, bg = bg, units = match.arg(units, c('in', 'cm', 'mm', "px")), dpi = dpi, limitsize = limitsize, ... ) }
/scratch/gouwar.j/cran-all/cranData/xpose/R/xpose_save.R
# .onAttach <- function(...) { # # if (!interactive()) return() # # text <- c('Note: the next xpose release (v0.5) will bring some major changes.\nIf you rely on xpose for your work, please keep an eye on our github:\nhttps://github.com/UUPharmacometrics/xpose') # # packageStartupMessage(sample(text, size = 1)) # } # Remove CRAN note on no visible binding for global variable utils::globalVariables('.')
/scratch/gouwar.j/cran-all/cranData/xpose/R/zzz.R
## ----include = FALSE------------------------------------------------------------------------------ library(xpose) options(width = 100) xpdb <- xpdb_ex_pk knitr::opts_chunk$set(out.width = '75%', comment = '', message = FALSE) ## ----demo print xpose_data------------------------------------------------------------------------ xpdb # or print(xpdb) ## ----demo get_code-------------------------------------------------------------------------------- code <- get_code(xpdb) code ## ----demo get_data-------------------------------------------------------------------------------- data <- get_data(xpdb, table = 'cotab001') data ## ----demo get_file-------------------------------------------------------------------------------- file <- get_file(xpdb, file = 'run001.ext') file ## ----demo get_prm--------------------------------------------------------------------------------- # Raw output for editing prm <- get_prm(xpdb, digits = 4) prm # Nicely formated table prm_table(xpdb, digits = 4) ## ----demo get_summary----------------------------------------------------------------------------- run_sum <- get_summary(xpdb, .problem = 0) run_sum
/scratch/gouwar.j/cran-all/cranData/xpose/inst/doc/access_xpdb_data.R
--- title: "Access the xpdb data" author: "Benjamin Guiastrennec" date: "`r format(Sys.time(), '%d %B, %Y')`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Access the xpdb data} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} library(xpose) options(width = 100) xpdb <- xpdb_ex_pk knitr::opts_chunk$set(out.width = '75%', comment = '', message = FALSE) ``` The xpose package was designed as a standardized interface between model outputs and R. Hence model output files can easily be imported in R and used to summarize data or create plots. ### Glimpse at the xpdb The files attached to an xpdb object can be displayed to the console simply by writing the xpdb name to the console or by using the `print()` function. Any of these files can be accessed from the xpdb using one of the functions listed below. ```{r demo print xpose_data} xpdb # or print(xpdb) ``` ### Access the model code The `get_code()` function can be used to access the parsed model code from the xpdb. This code was used to create the summary and find table names. The parsed code can be used to get additional information about the run. If the argument `.problem` is specified a subset of the code can be returned based on `$PROBLEM`. *Note that general code warnings and PsN outputs appended are listed as problem 0.* ```{r demo get_code} code <- get_code(xpdb) code ``` ### Access the output data The `get_data()` function can be used to access the imported table files. Tables can be accessed by `table` name or by `.problem`. In the latter a single dataset containing all aggregated tables is returned. If more than one `table` name or `.problem` number is provided a named list is returned. *Note when providing a table name it is not guaranteed that the table will be identical to its file (i.e. the order of the columns may have been changed and tables with `FIRSTONLY` will no longer be deduplicated).* ```{r demo get_data} data <- get_data(xpdb, table = 'cotab001') data ``` ### Access the run files The `get_file()` function can be used to access the imported output files. Files can be accessed by `file` name, by `.problem`, `.subprob` and/or `.method`. If more than one `file` name, `.problem`, `.subprob`, or `.method` is provided a named list is returned. ```{r demo get_file} file <- get_file(xpdb, file = 'run001.ext') file ``` ### Access the parameter estimates The `get_prm()` function can be used to access the parameter estimates. To get a nice parameter table printed to the console use the function `prm_table()` instead. The arguments `.problem`, `.subprob` and `.method` can be used to select the parameter estimates to output. ```{r demo get_prm} # Raw output for editing prm <- get_prm(xpdb, digits = 4) prm # Nicely formated table prm_table(xpdb, digits = 4) ``` ### Access the run summary The `get_summary()` function can be used to access the generated run summary from which the `template_titles`. If the argument `.problem` is specified a subset of the summary can be returned based on `$PROBLEM`. *Note that general summary information are listed as problem 0.* ```{r demo get_summary} run_sum <- get_summary(xpdb, .problem = 0) run_sum ```
/scratch/gouwar.j/cran-all/cranData/xpose/inst/doc/access_xpdb_data.Rmd
## ----include = FALSE------------------------------------------------------------------------------ library(xpose) xpdb <- xpdb_ex_pk %>% vpc_data(opt = vpc_opt(n_bins = 7)) %>% mutate(VAR = 1) knitr::opts_chunk$set(fig.dpi = 96, fig.align = 'center', fig.height = 4, fig.width = 4, out.width = '50%', comment = '', message = FALSE) ## ----demo type scatter, echo = FALSE, fig.height = 6, fig.width = 6, out.width = '75%'------------ gridExtra::grid.arrange( dv_vs_ipred(xpdb, title = "type = \'p\'", subtitle = NULL, caption = NULL, type = 'p'), dv_vs_ipred(xpdb, title = "type = \'l\'", subtitle = NULL, caption = NULL, type = 'l'), dv_vs_ipred(xpdb, title = "type = \'s\'", subtitle = NULL, caption = NULL, type = 's'), dv_vs_ipred(xpdb, title = "type = \'t\'", subtitle = NULL, caption = NULL, type = 't'), ncol = 2) ## ----demo type distrib, echo = FALSE, fig.height = 3.2, fig.width = 6, out.width = '75%'---------- gridExtra::grid.arrange( res_distrib(xpdb, title = "type = \'h\'", subtitle = NULL, caption = NULL, type = 'h'), res_distrib(xpdb, title = "type = \'d\'", subtitle = NULL, caption = NULL, type = 'd') + labs(y = NULL), res_distrib(xpdb, title = "type = \'r\'", subtitle = NULL, caption = NULL, type = 'r'), ncol = 3) ## ----demo type vpc, echo = FALSE, fig.height = 6, fig.width = 6, out.width = '75%'---------------- gridExtra::grid.arrange( vpc(xpdb, title = "type = \'a\'", subtitle = NULL, caption = NULL, type = 'a') + theme(legend.position = 'none') , vpc(xpdb, title = "type = \'l\'", subtitle = NULL, caption = NULL, type = 'l') + theme(legend.position = 'none'), vpc(xpdb, title = "type = \'p\'", subtitle = NULL, caption = NULL, type = 'p'), vpc(xpdb, title = "type = \'t\'", subtitle = NULL, caption = NULL, type = 't'), vpc(xpdb, title = "type = \'r\'", subtitle = NULL, caption = NULL, type = 'r'), ncol = 3) ## ----demo titles---------------------------------------------------------------------------------- # Using template titles dv_vs_ipred(xpdb, title = '@y vs. @x (@run, obj: @ofv)', subtitle = 'Based on: @nind subjects and @nobs records', caption = 'Dir: @dir') # Disabling all titles dv_vs_ipred(xpdb, title = NULL, subtitle = NULL, caption = NULL) # Edit title suffix from the xp_theme for a specific plot dv_vs_ipred(xpdb, title = 'A title', xp_theme = list(title_suffix = ' | a suffix for @run')) ## ----demo xpose_labs------------------------------------------------------------------------------ dv_vs_ipred(xpdb) + labs(title = '@descr', subtitle = NULL, caption = 'Based on @nobs observations', x = 'Individual model predictions (@x)', y = 'Observations (@y) for @nind subjects') ## ----demo aesthetics------------------------------------------------------------------------------ dv_vs_ipred(xpdb, # Change points aesthetics point_color = 'blue', point_alpha = 0.5, point_stroke = 0, point_size = 1.5, # Change lines aesthetics line_alpha = 0.5, line_linewidth = 0.5, line_color = 'orange', line_linetype = 'solid', # Change smooth aesthetics smooth_method = 'lm') ## ----demo mapping--------------------------------------------------------------------------------- dv_vs_ipred(xpdb, type = 'p', aes(point_color = SEX)) ## ----demo panels, fig.width = 6, fig.height = 6, out.width = '75%'-------------------------------- # Example with a string dv_vs_ipred(xpdb, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1, page = 1) # Example with a formula dv_vs_ipred(xpdb, facets = SEX~MED1, margins = TRUE) ## ----demo layers---------------------------------------------------------------------------------- dv_vs_ipred(xpdb) + geom_rug(alpha = 0.2, color = 'grey50', sides = 'lb', linewidth = 0.4) + annotate(geom = 'text', fontface = 'bold', color = 'darkred', size = 3, label = 'Toxic concentrations', x = 1.35, y = 1.75) + annotate(geom = 'rect', alpha = 0.2, fill = 'red', xmin = 1, xmax = Inf, ymin = 1, ymax = Inf) ## ----log-scales demo, warning=FALSE--------------------------------------------------------------- dv_vs_ipred(xpdb, log = 'xy', subtitle = 'Plot on log scale') ## ----scales-options demo-------------------------------------------------------------------------- dv_vs_ipred(xpdb, xscale_breaks = c(0.3, 0.8, 1.3), xscale_labels = c('Low', 'Med', 'High'), xscale_expand = c(0.2, 0), xscale_name = 'Individual model predictions') ## ----demo themes xpdb, eval = FALSE--------------------------------------------------------------- # # While creating the xpdb # xpdb <- xpose_data(runno = '001', # gg_theme = theme_minimal(), # xp_theme = theme_xp_xpose4()) # # # Update a pre-existing xpdb # xpdb <- update_themes(xpdb = xpdb, # gg_theme = theme_bw2(), # xp_theme = list(point_color = 'dodgerblue4', # line_color = 'dodgerblue4')) ## ----demo gg_theme, echo = FALSE, fig.height = 6, fig.width = 6, out.width = '75%'---------------- gridExtra::grid.arrange( dv_vs_ipred(xpdb, subtitle = 'theme_grey() [default in ggplot2]', title = NULL, caption = '', facet = 'VAR') + theme_grey(), dv_vs_ipred(xpdb, subtitle = 'theme_readable() [default in xpose]', title = NULL, caption = '', facet = 'VAR') + theme_readable(), dv_vs_ipred(xpdb, subtitle = 'theme_bw2()', title = NULL, caption = NULL, facet = 'VAR') + theme_bw2(), dv_vs_ipred(xpdb, subtitle = 'theme_dark()', title = NULL, caption = NULL, facet = 'VAR') + theme_dark(), ncol = 2) ## ----demo xp_theme, echo = FALSE, fig.height = 3.2, fig.width = 6, out.width = '75%'-------------- gridExtra::grid.arrange( dv_vs_ipred(update_themes(xpdb = xpdb, xp_theme = theme_xp_default()), subtitle = 'xp_theme = theme_xp_default()\nwith theme_bw2()', title = NULL, caption = '', facet = 'VAR') + theme_bw2(), dv_vs_ipred(update_themes(xpdb = xpdb, xp_theme = theme_xp_xpose4()), subtitle = 'xp_theme = theme_xp_xpose4()\nwith theme_bw2()', title = NULL, caption = '', facet = 'VAR') + theme_bw2(), ncol = 2)
/scratch/gouwar.j/cran-all/cranData/xpose/inst/doc/customize_plots.R
--- title: "Customize plots" author: "Benjamin Guiastrennec" date: "`r format(Sys.time(), '%d %B, %Y')`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Customize plots} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} library(xpose) xpdb <- xpdb_ex_pk %>% vpc_data(opt = vpc_opt(n_bins = 7)) %>% mutate(VAR = 1) knitr::opts_chunk$set(fig.dpi = 96, fig.align = 'center', fig.height = 4, fig.width = 4, out.width = '50%', comment = '', message = FALSE) ``` ### Plot type The option `type` allows to control how the data should be represented. #### Scatter plots In scatter plots `type` can be any combination of: points `'p'`, lines `'l'`, smooth `'s'`, text `'t'`. ```{r demo type scatter, echo = FALSE, fig.height = 6, fig.width = 6, out.width = '75%'} gridExtra::grid.arrange( dv_vs_ipred(xpdb, title = "type = \'p\'", subtitle = NULL, caption = NULL, type = 'p'), dv_vs_ipred(xpdb, title = "type = \'l\'", subtitle = NULL, caption = NULL, type = 'l'), dv_vs_ipred(xpdb, title = "type = \'s\'", subtitle = NULL, caption = NULL, type = 's'), dv_vs_ipred(xpdb, title = "type = \'t\'", subtitle = NULL, caption = NULL, type = 't'), ncol = 2) ``` #### Distribution plots In distribution plots `type` can be any combination of: histogram `'h'`, density `'d'`, or rug `'r'`. ```{r demo type distrib, echo = FALSE, fig.height = 3.2, fig.width = 6, out.width = '75%'} gridExtra::grid.arrange( res_distrib(xpdb, title = "type = \'h\'", subtitle = NULL, caption = NULL, type = 'h'), res_distrib(xpdb, title = "type = \'d\'", subtitle = NULL, caption = NULL, type = 'd') + labs(y = NULL), res_distrib(xpdb, title = "type = \'r\'", subtitle = NULL, caption = NULL, type = 'r'), ncol = 3) ``` #### VPCs In visual predictive checks plots `type` can be any combination of: areas `'a'`, lines `'l'`, points `'p'`, text `'t'` or rug `'r'`. ```{r demo type vpc, echo = FALSE, fig.height = 6, fig.width = 6, out.width = '75%'} gridExtra::grid.arrange( vpc(xpdb, title = "type = \'a\'", subtitle = NULL, caption = NULL, type = 'a') + theme(legend.position = 'none') , vpc(xpdb, title = "type = \'l\'", subtitle = NULL, caption = NULL, type = 'l') + theme(legend.position = 'none'), vpc(xpdb, title = "type = \'p\'", subtitle = NULL, caption = NULL, type = 'p'), vpc(xpdb, title = "type = \'t\'", subtitle = NULL, caption = NULL, type = 't'), vpc(xpdb, title = "type = \'r\'", subtitle = NULL, caption = NULL, type = 'r'), ncol = 3) ``` ### Visual guide The option `guide` can enable (`TRUE`) or disable (`FALSE`) the visual guide on the graphs such as the line of identity on the `dv_vs_ipred()` type plot or horizontal lines on residual plots (e.g. `res_vs_idv()`). ### Labels All xpose plots have by default an informative title, subtitle and caption. For example all plots using individual model predictions (IPRED) will display the epsilons' shrinkage. These titles can easily be edited as templates using @keywords which will be replaced by their actual value stored in the summary level of the `xpdb` object when rendering the plots. Keywords are defined by a word preceded by a `@` e.g. `'@ofv'`. A list of all available keyword can be accessed via `help('template_titles')`. The title, subtitle or caption can be disabled by setting them to `NULL`. Suffix can be automatically added to title, subtitle and caption of all plots. The suffixes can be defined in the `xp_theme`. #### From the plot functions ```{r demo titles} # Using template titles dv_vs_ipred(xpdb, title = '@y vs. @x (@run, obj: @ofv)', subtitle = 'Based on: @nind subjects and @nobs records', caption = 'Dir: @dir') # Disabling all titles dv_vs_ipred(xpdb, title = NULL, subtitle = NULL, caption = NULL) # Edit title suffix from the xp_theme for a specific plot dv_vs_ipred(xpdb, title = 'A title', xp_theme = list(title_suffix = ' | a suffix for @run')) ``` #### Using the `labs` function Labels can also modified later on by using the `ggplot2::labs()` function in combination with the ggplot2 `+` operator. ```{r demo xpose_labs} dv_vs_ipred(xpdb) + labs(title = '@descr', subtitle = NULL, caption = 'Based on @nobs observations', x = 'Individual model predictions (@x)', y = 'Observations (@y) for @nind subjects') ``` ### Modify aesthetics By default the aesthetics are read from the `xp_theme` level in the xpdb object but these can be modified in any plot function. xpose makes use of the `ggplot2` functions mapping for any layer (e.g. points, lines, etc.) however to direct the mapping to a specific layer, a prefix appealing to the targeted layer should be used. The format is defined as `layer_aesthetic = value`. Hence to change the color of points in ggplot2 the argument `color = 'green'` could be used in `geom_point()`, while in xpose the same could be achieved with `point_color = 'green'`. In basic goodness-of-fit plots, the layers have been named as: `point_xxx`, `line_xxx`, `smooth_xxx`, `guide_xxx`, `xscale_xxx`, `yscale_xxx` where `xxx` can be any option available in the `ggplot2` layers: `geom_point`, `geom_line`, `geom_smooth`, `geom_abline`, `scale_x_continuous`, etc. ```{r demo aesthetics} dv_vs_ipred(xpdb, # Change points aesthetics point_color = 'blue', point_alpha = 0.5, point_stroke = 0, point_size = 1.5, # Change lines aesthetics line_alpha = 0.5, line_linewidth = 0.5, line_color = 'orange', line_linetype = 'solid', # Change smooth aesthetics smooth_method = 'lm') ``` Aesthetics can also be defined mapped to a variable using the ggplot2 `aes()` function. ```{r demo mapping} dv_vs_ipred(xpdb, type = 'p', aes(point_color = SEX)) ``` ### Grouping variable The argument group defines the grouping variable to be used in the dataset __for the lines only__, by default group is defined to the column `'ID'`. To apply a grouping variable on any other layer, a manual mapping can be made using the argument `xxx_group = variable` ### Panels Panels (or faceting) can be created by using the `facets` argument as follows: * If `facets` is a string e.g `facets = "SEX"`, `ggforce::facet_wrap_paginate` will be used * If `facets` is a formula e.g `facets = SEX~MED1`, `ggforce::facet_grid_paginate` will be used ```{r demo panels, fig.width = 6, fig.height = 6, out.width = '75%'} # Example with a string dv_vs_ipred(xpdb, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1, page = 1) # Example with a formula dv_vs_ipred(xpdb, facets = SEX~MED1, margins = TRUE) ``` All xpose plot functions accept arguments for `facet_wrap_pagninate` and `facet_grid_paginate` (e.g. `ncol = 2`, `labeller = 'label_both'`, etc.). With the default xpose theme scales are set to `'free'` from one panel to another (`scales = 'free'`), this behavior can be changed with `scales = 'fixed'`, `'free_y'` or `'free_x'`. For more information on the available faceting options read the help of [`facet_wrap_paginate`](https://www.rdocumentation.org/packages/ggforce/versions/0.1.1/topics/facet_wrap_paginate) and [`facet_grid_paginate`](https://www.rdocumentation.org/packages/ggforce/versions/0.1.1/topics/facet_grid_paginate) from the package ggforce. ### Additional layers `xpose` offers the opportunity to add any additional layers from `ggplot2`. Hence, a `ggplot2::geom_rug()` layer could be added to the `dv_vs_ipred()` plot along with some annotations (`ggplot2::annotate()`). Note: the additional layers do not inherit from the xpose aesthetic mapping (i.e. colors or other options need to be defined in each layer as shown below). Layers can also be used to modify the aesthetics scales for example `ggplot2::scale_color_manual()`, or remove a legend `ggplot2::scale_fill_identity()`. ```{r demo layers} dv_vs_ipred(xpdb) + geom_rug(alpha = 0.2, color = 'grey50', sides = 'lb', linewidth = 0.4) + annotate(geom = 'text', fontface = 'bold', color = 'darkred', size = 3, label = 'Toxic concentrations', x = 1.35, y = 1.75) + annotate(geom = 'rect', alpha = 0.2, fill = 'red', xmin = 1, xmax = Inf, ymin = 1, ymax = Inf) ``` ### Scales options The argument `log` allows to log-transform the axes. Accepted values are `x`, `y` or `xy`. ```{r log-scales demo, warning=FALSE} dv_vs_ipred(xpdb, log = 'xy', subtitle = 'Plot on log scale') ``` Additional arguments can be provided to the scales via the mapping by using the naming convention `xscale_xxx` or `yscale_xxx` where `xxx` is the name of a `ggplot2` scale argument such as `name`, `breaks`, `labels`, `expand`. ```{r scales-options demo} dv_vs_ipred(xpdb, xscale_breaks = c(0.3, 0.8, 1.3), xscale_labels = c('Low', 'Med', 'High'), xscale_expand = c(0.2, 0), xscale_name = 'Individual model predictions') ``` ### Themes Theme in `xpose` are easily customizable. Themes are made up of two parts: - A `ggplot2` (`gg_theme`) theme controlling the aspect of the plot window - An `xpose` (`xp_theme`) theme controlling the aspect of the layers such as points or lines Themes can be attached to an `xpdb` when importing the data with `xpose_data()` or using the function `update_themes()` on an xpdb object. ```{r demo themes xpdb, eval = FALSE} # While creating the xpdb xpdb <- xpose_data(runno = '001', gg_theme = theme_minimal(), xp_theme = theme_xp_xpose4()) # Update a pre-existing xpdb xpdb <- update_themes(xpdb = xpdb, gg_theme = theme_bw2(), xp_theme = list(point_color = 'dodgerblue4', line_color = 'dodgerblue4')) ``` #### Examples of `gg_theme`: xpose brings two additional themes (`theme_readable()` and `theme_bw2()`), to those available in `ggplot2`. ```{r demo gg_theme, echo = FALSE, fig.height = 6, fig.width = 6, out.width = '75%'} gridExtra::grid.arrange( dv_vs_ipred(xpdb, subtitle = 'theme_grey() [default in ggplot2]', title = NULL, caption = '', facet = 'VAR') + theme_grey(), dv_vs_ipred(xpdb, subtitle = 'theme_readable() [default in xpose]', title = NULL, caption = '', facet = 'VAR') + theme_readable(), dv_vs_ipred(xpdb, subtitle = 'theme_bw2()', title = NULL, caption = NULL, facet = 'VAR') + theme_bw2(), dv_vs_ipred(xpdb, subtitle = 'theme_dark()', title = NULL, caption = NULL, facet = 'VAR') + theme_dark(), ncol = 2) ``` #### Examples of `xp_theme`: ```{r demo xp_theme, echo = FALSE, fig.height = 3.2, fig.width = 6, out.width = '75%'} gridExtra::grid.arrange( dv_vs_ipred(update_themes(xpdb = xpdb, xp_theme = theme_xp_default()), subtitle = 'xp_theme = theme_xp_default()\nwith theme_bw2()', title = NULL, caption = '', facet = 'VAR') + theme_bw2(), dv_vs_ipred(update_themes(xpdb = xpdb, xp_theme = theme_xp_xpose4()), subtitle = 'xp_theme = theme_xp_xpose4()\nwith theme_bw2()', title = NULL, caption = '', facet = 'VAR') + theme_bw2(), ncol = 2) ```
/scratch/gouwar.j/cran-all/cranData/xpose/inst/doc/customize_plots.Rmd
## ----include = FALSE------------------------------------------------------------------------------ library(xpose) options(width = 100) xpdb <- xpdb_ex_pk knitr::opts_chunk$set(fig.dpi = 96, fig.align = 'center', fig.height = 4, fig.width = 4, out.width = '75%', comment = '', message = FALSE)
/scratch/gouwar.j/cran-all/cranData/xpose/inst/doc/import_model_outputs.R
--- title: "Import model outputs" author: "Benjamin Guiastrennec" date: "`r format(Sys.time(), '%d %B, %Y')`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Import model outputs} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} library(xpose) options(width = 100) xpdb <- xpdb_ex_pk knitr::opts_chunk$set(fig.dpi = 96, fig.align = 'center', fig.height = 4, fig.width = 4, out.width = '75%', comment = '', message = FALSE) ``` ### The `xpose_data` function The function `xpose_data()` collects all model output files and table and organizes them into an R object commonly called `xpdb` for xpose data base. ``` r xpdb <- xpose_data(runno = '001') ``` ### Imported files #### NONMEM runs To make full use of the functionality offered by `xpose` the following NONMEM output files should be available: - `.lst/.out/.res`: used to collect information on the run (`template_titles`) as well as the output table names. Alternatively a model file (`.mod/.ctl`) can be used but some of the information in `template_titles` may not be available. - `.ext`: used to collect final parameter estimates and residual standard error (RSE) - `.phi`: used for the random effects and iOFV - `.cov`: used for the covariance matrix - `.cor`: used for the correlation matrix - `.grd`: used for the estimation gradients - `.shk`: used to compute random effect shrinkage `template_titles` - output and simulation tables: for the actual data When importing the files, xpose will return messages to the console and inform of any issue encountered during the import. ```r xpdb <- xpose_data(runno = '001') Looking for nonmem output tables Reading: sdtab001, catab001, cotab001, patab001 [$prob no.1] Looking for nonmem output files Reading: run001.cor, run001.cov, run001.ext, run001.grd, run001.phi ``` These messages can be silenced with the option `quiet = TRUE`. ##### `FIRSTONLY` tables xpose is compatible with the `$TABLE FIRSTONLY` option of NONMEM. The option `FIRSTONLY` only output the first record for each `ID` and hence can be used to decrease the size of output tables having no time-varying columns. During tables import xpose will merge `FIRSTONLY` tables with regular tables allowing seamless use of columns from `FIRSTONLY` in plots. ##### Compressed tables xpose makes use of the [readr](https://readr.tidyverse.org) which offers the advantages of 1) rapidly import big tables and 2) automatically import compressed table (e.g. sdtab001.zip) to increase storage capacity. #### Others NLME tools Coming with future releases... ### Structure of the `xpdb` object A typical `xpdb` object contains 8 levels namely: - `code`: the parsed model code - `summary`: contains key information regarding the model. All the information contained in the summary can be used as part of the `template_titles`. - `data`: contains all output and simulation tables as well as the column indexing - `files`: contains all output files - `special`: contains post-processed datasets used by functions like `vpc()` - `gg_theme`: an attached ggplot2 theme - `xp_theme`: an attached xpose theme - `options`: attached global options
/scratch/gouwar.j/cran-all/cranData/xpose/inst/doc/import_model_outputs.Rmd
## ----include = FALSE------------------------------------------------------------------------------ library(xpose) xpdb <- xpdb_ex_pk %>% set_var_types(idv = 'TIME') knitr::opts_chunk$set(fig.dpi = 96, fig.align = 'center', fig.height = 4, fig.width = 4, out.width = '50%', comment = '', message = FALSE) ## ----demo print xpose_data------------------------------------------------------------------------ xpdb # or print(xpdb) ## ----demo xpose summary--------------------------------------------------------------------------- summary(xpdb) ## ----demo prm_table------------------------------------------------------------------------------- prm_table(xpdb) ## ----demo list_vars------------------------------------------------------------------------------- list_vars(xpdb) ## ----eval = FALSE--------------------------------------------------------------------------------- # xpose_data(runno = '001') %>% # dv_vs_ipred() %>% # xpose_save(file = 'run001_dv_vs_ipred.pdf') ## ----change idv----------------------------------------------------------------------------------- # With the TIME default xpdb %>% dv_vs_idv() # After IDV reassignment xpdb %>% set_var_types(idv = 'TAD') %>% dv_vs_idv() ## ----demo basic gof------------------------------------------------------------------------------- # DV vs. IPRED plot dv_vs_ipred(xpdb) # CWRES vs. PRED plot res_vs_pred(xpdb, res = 'CWRES') ## ----eval = FALSE--------------------------------------------------------------------------------- # # Save the last generated plot # dv_vs_ipred(xpdb) # xpose_save(file = 'run001_dv_vs_ipred.pdf') # # # Template titles can also be used in filename and the directory # xpdb %>% # dv_vs_ipred() %>% # xpose_save(file = '@run_@plotfun_[@ofv].jpeg', dir = '@dir')
/scratch/gouwar.j/cran-all/cranData/xpose/inst/doc/introduction.R
--- title: "Introduction" author: "Benjamin Guiastrennec" date: "`r format(Sys.time(), '%d %B, %Y')`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} library(xpose) xpdb <- xpdb_ex_pk %>% set_var_types(idv = 'TIME') knitr::opts_chunk$set(fig.dpi = 96, fig.align = 'center', fig.height = 4, fig.width = 4, out.width = '50%', comment = '', message = FALSE) ``` ### Load xpose The first step is to load xpose in R with the following command: ```r library(xpose) ``` ### Import model output The function `xpose_data()` collects all model output files and table and organizes them into an R object commonly called `xpdb` which stands for "xpose database". ``` r xpdb <- xpose_data(runno = '001', dir = 'analysis/model/pk/') ``` ### Glimpse at the xpdb The files attached to an xpdb object can be displayed to the console simply by writing its name to the console or by using the `print()` function. ```{r demo print xpose_data} xpdb # or print(xpdb) ``` ### Model summary A summary of a model run can be displayed to the console by using the `summary()` function on an xpdb object. ```{r demo xpose summary} summary(xpdb) ``` ### Parameter estimates A table of parameter estimates can be displayed to the console by using the `prm_table()` function on an xpdb object. ```{r demo prm_table} prm_table(xpdb) ``` ### Listing variables A list of available variables for plotting can be displayed to the console by using the `list_vars()` function on an xpdb object. ```{r demo list_vars} list_vars(xpdb) ``` ### Pipes `xpose` makes use of the pipe operator `%>%` from the package [dplyr](https://dplyr.tidyverse.org). Pipes can be used to generate clear workflow. ```{r, eval = FALSE} xpose_data(runno = '001') %>% dv_vs_ipred() %>% xpose_save(file = 'run001_dv_vs_ipred.pdf') ``` ### Editing the xpdb Multiples edits can be made to the xpdb object. For instance the type (visible using the `list_vars()` function described above) of a variable can be changed. Hence the independent variable (idv) could be changed from `TIME` (default in NONMEM) to `TAD`. All plots using `idv` will then automatically use `TAD`. ```{r, change idv} # With the TIME default xpdb %>% dv_vs_idv() # After IDV reassignment xpdb %>% set_var_types(idv = 'TAD') %>% dv_vs_idv() ``` ### Generating plots Plotting functions are used as follows: ``` {r demo basic gof} # DV vs. IPRED plot dv_vs_ipred(xpdb) # CWRES vs. PRED plot res_vs_pred(xpdb, res = 'CWRES') ``` ### Saving plots The `xpose_save` function was designed to facilitate the export of xpose plots. The file extension is guessed from the file name and must match one of .pdf (default), .jpeg, .png, .bmp or .tiff. If no extension is provided as part of the file name a .pdf will be generated. Finally, if the `plot` argument is left empty `xpose_save` will automatically save the last plot that was created or modified. The `xpose_save()` function is compatible with templates titles and keywords such as `@run` for the run number and `@plotfun` for the name of the plotting function can be used to automatically name files. Learn more about the template titles keywords using `help('template_titles')`. ```{r, eval = FALSE} # Save the last generated plot dv_vs_ipred(xpdb) xpose_save(file = 'run001_dv_vs_ipred.pdf') # Template titles can also be used in filename and the directory xpdb %>% dv_vs_ipred() %>% xpose_save(file = '@run_@plotfun_[@ofv].jpeg', dir = '@dir') ```
/scratch/gouwar.j/cran-all/cranData/xpose/inst/doc/introduction.Rmd
## ----include = FALSE------------------------------------------------------------------------------ library(xpose) options(width = 100) xpdb <- xpdb_ex_pk knitr::opts_chunk$set(fig.dpi = 96, fig.align = 'center', fig.height = 4, fig.width = 6, out.width = '75%', comment = '', message = FALSE) ## ----demo panels, fig.height = 6------------------------------------------------------------------ # Example with a string dv_vs_ipred(xpdb, facets = c('SEX', 'MED1')) # Example with a formula dv_vs_ipred(xpdb, facets = SEX~MED1, margins = TRUE) ## ----message = FALSE------------------------------------------------------------------------------ dv_vs_ipred(xpdb, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1) ## ----messages = TRUE------------------------------------------------------------------------------ dv_vs_ipred(xpdb, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1, page = 1) ## ----eval = FALSE--------------------------------------------------------------------------------- # # Create an xpose_plot, by default page = 1 # p1 <- dv_vs_ipred(xpdb, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1) # # # Change the page to be drawn # print(p1, page = 2) ## ------------------------------------------------------------------------------------------------- dv_vs_ipred(xpdb, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1, page = 1, caption = 'Page @page of @lastpage') ## ------------------------------------------------------------------------------------------------- xpdb_numbered <- update_themes(xpdb, xp_theme = list(caption_suffix = ', page @page of @lastpage')) dv_vs_ipred(xpdb_numbered, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1, page = 2) ## ----eval = FALSE--------------------------------------------------------------------------------- # dv_vs_ipred(xpdb_numbered, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1) %>% # xpose_save(file = 'dv_vs_ipred_multiple.pdf') ## ----eval = FALSE--------------------------------------------------------------------------------- # dv_vs_ipred(xpdb_numbered, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1) %>% # xpose_save(file = '@run_@plotfun_%03d.png')
/scratch/gouwar.j/cran-all/cranData/xpose/inst/doc/multiple_pages.R
--- title: "Plots with multiple pages" author: "Benjamin Guiastrennec" date: "`r format(Sys.time(), '%d %B, %Y')`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Plots with multiple pages} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} library(xpose) options(width = 100) xpdb <- xpdb_ex_pk knitr::opts_chunk$set(fig.dpi = 96, fig.align = 'center', fig.height = 4, fig.width = 6, out.width = '75%', comment = '', message = FALSE) ``` # Bases of plot faceting Panels (or faceting) can be created by using the `facets` argument as follows: * If `facets` is a string e.g `facets = "SEX"`, facets will be created using `ggforce::`[`facet_wrap_paginate`](https://www.rdocumentation.org/packages/ggforce/versions/0.1.1/topics/facet_wrap_paginate) * If `facets` is a formula e.g `facets = SEX~MED1`, facets will be created using `ggforce::`[`facet_grid_paginate`](https://www.rdocumentation.org/packages/ggforce/versions/0.1.1/topics/facet_grid_paginate) ```{r demo panels, fig.height = 6} # Example with a string dv_vs_ipred(xpdb, facets = c('SEX', 'MED1')) # Example with a formula dv_vs_ipred(xpdb, facets = SEX~MED1, margins = TRUE) ``` All xpose plot functions accept arguments for `facet_wrap_pagninate` and `facet_grid_paginate` (e.g. `ncol = 2`, `labeller = 'label_both'`, etc.). With the default xpose theme scales are set to `'free'` from one panel to another (`scales = 'free'`), this behavior can be changed with `scales = 'fixed'`, `'free_y'` or `'free_x'`. # Faceting over multiple pages ## Setting the layout When the arguments `ncol` and `nrow` are set and under the condition that they are more panels to be drawn that can fit on a single page given the selected layout, the multiple page functionality will automatically be enabled. ```{r, message = FALSE} dv_vs_ipred(xpdb, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1) ``` ## Selecting pages By default all pages will be shown but this can be time consuming. To select only specific pages to be drawn, use the argument `page`. ```{r, messages = TRUE} dv_vs_ipred(xpdb, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1, page = 1) ``` It is also possible to change the page(s) to be drawn from an already existing `xpose_plot` object via the `print()` function. ```{r, eval = FALSE} # Create an xpose_plot, by default page = 1 p1 <- dv_vs_ipred(xpdb, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1) # Change the page to be drawn print(p1, page = 2) ``` ## Numbering pages To number pages the keywords `@page` and `@lastpage` can be used to respectively indicate the current page and the total number of pages. ```{r} dv_vs_ipred(xpdb, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1, page = 1, caption = 'Page @page of @lastpage') ``` To systematically number all generated plots a caption suffix can be defined in the `xp_theme`. ```{r} xpdb_numbered <- update_themes(xpdb, xp_theme = list(caption_suffix = ', page @page of @lastpage')) dv_vs_ipred(xpdb_numbered, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1, page = 2) ``` # Saving multiple pages plots Multiple pages graphs can simply be saved by using the `xpose_save()` function. ```{r, eval = FALSE} dv_vs_ipred(xpdb_numbered, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1) %>% xpose_save(file = 'dv_vs_ipred_multiple.pdf') ``` The `pdf` format can conveniently store multiple pages within a single document. However other graphical devices (e.g. `'png'`, `'jpg'`) can also be used, simply ensure to have a page counter (i.e. `'%03d'`) added the file name. ```{r, eval = FALSE} dv_vs_ipred(xpdb_numbered, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1) %>% xpose_save(file = '@run_@plotfun_%03d.png') ```
/scratch/gouwar.j/cran-all/cranData/xpose/inst/doc/multiple_pages.Rmd
## ----include = FALSE------------------------------------------------------------------------------ library(xpose) knitr::opts_chunk$set(fig.dpi = 96, fig.align = 'center', fig.height = 4, fig.width = 6, out.width = '75%', comment = '', message = FALSE) ## ------------------------------------------------------------------------------------------------- xpdb_ex_pk %>% vpc_data() %>% # Compute the vpc data vpc() # Plot the vpc ## ----warning = FALSE------------------------------------------------------------------------------ xpdb_w_vpc <- vpc_data(xpdb_ex_pk) # Compute and store VPC data xpdb_w_vpc # The vpc data is now listed under the xpdb "special" data vpc(xpdb_w_vpc) # Plot the vpc from the stored data ## ----eval = FALSE, warning = FALSE---------------------------------------------------------------- # xpdb_w_multi_vpc <- xpdb_ex_pk %>% # vpc_data(vpc_type = 'continuous', opt = vpc_opt(n_bins = 6, lloq = 0.1)) %>% # vpc_data(vpc_type = 'censored', opt = vpc_opt(n_bins = 6, lloq = 0.1)) # # vpc(xpdb_w_multi_vpc, vpc_type = 'continuous') # vpc(xpdb_w_multi_vpc, vpc_type = 'censored') ## ----eval = FALSE, warning = FALSE---------------------------------------------------------------- # xpdb_ex_pk %>% # vpc_data(vpc_type = 'censored', stratify = 'SEX', # opt = vpc_opt(bins = 'jenks', n_bins = 7, lloq = 0.5)) %>% # vpc() ## ------------------------------------------------------------------------------------------------- # View the xpdb content and data problems xpdb_ex_pk # Generate the vpc xpdb_ex_pk %>% vpc_data(vpc_type = 'continuous', obs_problem = 1, sim_problem = 2) %>% vpc() ## ----eval = FALSE--------------------------------------------------------------------------------- # xpdb_ex_pk %>% # vpc_data(psn_folder = '@dir/run001_vpc', psn_bins = TRUE) %>% # vpc()
/scratch/gouwar.j/cran-all/cranData/xpose/inst/doc/vpc.R
--- title: "Visual Predictive Checks (VPC)" author: "Benjamin Guiastrennec" date: "`r format(Sys.time(), '%d %B, %Y')`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Visual Predictive Checks (VPC)} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} library(xpose) knitr::opts_chunk$set(fig.dpi = 96, fig.align = 'center', fig.height = 4, fig.width = 6, out.width = '75%', comment = '', message = FALSE) ``` ### Disclosure The Visual predictive checks (VPC) shown below are only intended to demonstrate the various options available in xpose and should not be used as reference for modeling practice. Furthermore, the plots are only based on 20 simulations to minimize the computing time of the examples, the size of the `xpdb_ex_pk` object and of the xpose package in general. ### Introduction VPC can be created either by: 1. Using an xpdb containing a simulation and an estimation problem 2. Using a [PsN](https://uupharmacometrics.github.io/PsN/) generated VPC folder The VPC functionality in xpose is build around the [vpc R package](https://cran.r-project.org/package=vpc). For more details about the way the vpc package works, please check the [github repository](https://github.com/ronkeizer/vpc). ### Workflow The VPC computing and plotting parts have been separated into two distinct functions: `vpc_data()` and `vpc()` respectively. This allows to: * Optimize the speed when adjusting the graphics aesthetics * Adjust the VPC data (e.g. remove panels or factor labels) before plotting * Facilitate error debugging ```{r} xpdb_ex_pk %>% vpc_data() %>% # Compute the vpc data vpc() # Plot the vpc ``` The generated VPC data is stored in the xpdb under specials datasets and can be used later on. ```{r, warning = FALSE} xpdb_w_vpc <- vpc_data(xpdb_ex_pk) # Compute and store VPC data xpdb_w_vpc # The vpc data is now listed under the xpdb "special" data vpc(xpdb_w_vpc) # Plot the vpc from the stored data ``` Multiple VPC data can be stored in an xpdb, but only one of each `vpc_type`. ```{r, eval = FALSE, warning = FALSE} xpdb_w_multi_vpc <- xpdb_ex_pk %>% vpc_data(vpc_type = 'continuous', opt = vpc_opt(n_bins = 6, lloq = 0.1)) %>% vpc_data(vpc_type = 'censored', opt = vpc_opt(n_bins = 6, lloq = 0.1)) vpc(xpdb_w_multi_vpc, vpc_type = 'continuous') vpc(xpdb_w_multi_vpc, vpc_type = 'censored') ``` ### Common options #### Options in `vpc_data()` * The option `vpc_type` allows to specify the type of VPC to be computed: "continuous" (default), "categorical", "censored", "time-to-event". * The `stratify` options defines up to two stratifying variable to be used when computing the VPC data. The `stratify` variables can either be provided as a character vector (`stratify = c('SEX', 'MED1')`) or a formula (`stratify = SEX~MED1`) . The former will result in the use of `ggforce::facet_wrap_paginate()` and the latter of `ggforce::facet_grid_paginate()` when creating the plot. With "categorical" VPC the "group" variable will also be added by default. * More advanced options (i.e. binning, pi, ci, predcorr, lloq, etc.) are accessible via the `opt` argument. The `opt` argument expects the output from the `vpc_opt()` functions argument. ```{r, eval = FALSE, warning = FALSE} xpdb_ex_pk %>% vpc_data(vpc_type = 'censored', stratify = 'SEX', opt = vpc_opt(bins = 'jenks', n_bins = 7, lloq = 0.5)) %>% vpc() ``` #### Options in `vpc()` * The option `vpc_type` works similarly to `vpc_data()` and is only required if several VPC data are associated with the xpdb. * The option `smooth = TRUE/FALSE` allows to switch between smooth and squared shaded areas. * The plot VPC function works similarly to all other xpose functions to map and customize aesthetics. However in this case the `area_fill` and `line_linetype` each require three values for the low, median and high percentiles respectively. ### Creating VPC using the xpdb data To create VPC using the xpdb data, at least one simulation and one estimation problem need to present. Hence in the case of NONMEM the run used to generate the xpdb should contain several`$PROBLEM`. In `vpc_data()` the problem number can be specified for the observation (`obs_problem`) and the simulation (`sim_problem`). By default xpose picks the last one of each to generate the VPC. ```{r} # View the xpdb content and data problems xpdb_ex_pk # Generate the vpc xpdb_ex_pk %>% vpc_data(vpc_type = 'continuous', obs_problem = 1, sim_problem = 2) %>% vpc() ``` ### Creating the VPC using a PsN folder The `vpc_data()` contains an argument `psn_folder` which can be used to point to a [PsN](https://uupharmacometrics.github.io/PsN/) generated VPC folder. As in most xpose function `template_titles` keywords can be used to automatize the process e.g. `psn_folder = '@dir/@run_vpc'` where `@dir` and `@run` will be automatically translated to initial (i.e. when the xpdb was generated) run directory and run number `'analysis/models/pk/run001_vpc'`. In this case, the data will be read from the `/m1` sub-folder (or `m1.zip` if compressed). Note that [PsN](https://uupharmacometrics.github.io/PsN/) drops unused columns to reduce the simtab file size. Thus, in order to allow for more flexibility in R, it is recommended to use multiple stratifying variables (`-stratify_on=VAR1,VAR2`) and the prediction corrected (`-predcorr` adds the PRED column to the output) options in [PsN](https://uupharmacometrics.github.io/PsN/) to avoid having to rerun [PsN](https://uupharmacometrics.github.io/PsN/) to add these variables later on. In addition, `-dv`, `-idv`, `-lloq`, `-uloq`, `-predcorr` and `-stratify_on` [PsN](https://uupharmacometrics.github.io/PsN/) options are automatically applied to xpose VPC. The PsN generated binning can also applied to xpose VPC with the `vpc_data()` option `psn_bins = TRUE` (disabled by default). However [PsN](https://uupharmacometrics.github.io/PsN/) and the vpc package work slightly differently so the results may not be optimal and the output should be evaluated carefully. ```{r, eval = FALSE} xpdb_ex_pk %>% vpc_data(psn_folder = '@dir/run001_vpc', psn_bins = TRUE) %>% vpc() ```
/scratch/gouwar.j/cran-all/cranData/xpose/inst/doc/vpc.Rmd
--- title: "Access the xpdb data" author: "Benjamin Guiastrennec" date: "`r format(Sys.time(), '%d %B, %Y')`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Access the xpdb data} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} library(xpose) options(width = 100) xpdb <- xpdb_ex_pk knitr::opts_chunk$set(out.width = '75%', comment = '', message = FALSE) ``` The xpose package was designed as a standardized interface between model outputs and R. Hence model output files can easily be imported in R and used to summarize data or create plots. ### Glimpse at the xpdb The files attached to an xpdb object can be displayed to the console simply by writing the xpdb name to the console or by using the `print()` function. Any of these files can be accessed from the xpdb using one of the functions listed below. ```{r demo print xpose_data} xpdb # or print(xpdb) ``` ### Access the model code The `get_code()` function can be used to access the parsed model code from the xpdb. This code was used to create the summary and find table names. The parsed code can be used to get additional information about the run. If the argument `.problem` is specified a subset of the code can be returned based on `$PROBLEM`. *Note that general code warnings and PsN outputs appended are listed as problem 0.* ```{r demo get_code} code <- get_code(xpdb) code ``` ### Access the output data The `get_data()` function can be used to access the imported table files. Tables can be accessed by `table` name or by `.problem`. In the latter a single dataset containing all aggregated tables is returned. If more than one `table` name or `.problem` number is provided a named list is returned. *Note when providing a table name it is not guaranteed that the table will be identical to its file (i.e. the order of the columns may have been changed and tables with `FIRSTONLY` will no longer be deduplicated).* ```{r demo get_data} data <- get_data(xpdb, table = 'cotab001') data ``` ### Access the run files The `get_file()` function can be used to access the imported output files. Files can be accessed by `file` name, by `.problem`, `.subprob` and/or `.method`. If more than one `file` name, `.problem`, `.subprob`, or `.method` is provided a named list is returned. ```{r demo get_file} file <- get_file(xpdb, file = 'run001.ext') file ``` ### Access the parameter estimates The `get_prm()` function can be used to access the parameter estimates. To get a nice parameter table printed to the console use the function `prm_table()` instead. The arguments `.problem`, `.subprob` and `.method` can be used to select the parameter estimates to output. ```{r demo get_prm} # Raw output for editing prm <- get_prm(xpdb, digits = 4) prm # Nicely formated table prm_table(xpdb, digits = 4) ``` ### Access the run summary The `get_summary()` function can be used to access the generated run summary from which the `template_titles`. If the argument `.problem` is specified a subset of the summary can be returned based on `$PROBLEM`. *Note that general summary information are listed as problem 0.* ```{r demo get_summary} run_sum <- get_summary(xpdb, .problem = 0) run_sum ```
/scratch/gouwar.j/cran-all/cranData/xpose/vignettes/access_xpdb_data.Rmd
--- title: "Customize plots" author: "Benjamin Guiastrennec" date: "`r format(Sys.time(), '%d %B, %Y')`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Customize plots} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} library(xpose) xpdb <- xpdb_ex_pk %>% vpc_data(opt = vpc_opt(n_bins = 7)) %>% mutate(VAR = 1) knitr::opts_chunk$set(fig.dpi = 96, fig.align = 'center', fig.height = 4, fig.width = 4, out.width = '50%', comment = '', message = FALSE) ``` ### Plot type The option `type` allows to control how the data should be represented. #### Scatter plots In scatter plots `type` can be any combination of: points `'p'`, lines `'l'`, smooth `'s'`, text `'t'`. ```{r demo type scatter, echo = FALSE, fig.height = 6, fig.width = 6, out.width = '75%'} gridExtra::grid.arrange( dv_vs_ipred(xpdb, title = "type = \'p\'", subtitle = NULL, caption = NULL, type = 'p'), dv_vs_ipred(xpdb, title = "type = \'l\'", subtitle = NULL, caption = NULL, type = 'l'), dv_vs_ipred(xpdb, title = "type = \'s\'", subtitle = NULL, caption = NULL, type = 's'), dv_vs_ipred(xpdb, title = "type = \'t\'", subtitle = NULL, caption = NULL, type = 't'), ncol = 2) ``` #### Distribution plots In distribution plots `type` can be any combination of: histogram `'h'`, density `'d'`, or rug `'r'`. ```{r demo type distrib, echo = FALSE, fig.height = 3.2, fig.width = 6, out.width = '75%'} gridExtra::grid.arrange( res_distrib(xpdb, title = "type = \'h\'", subtitle = NULL, caption = NULL, type = 'h'), res_distrib(xpdb, title = "type = \'d\'", subtitle = NULL, caption = NULL, type = 'd') + labs(y = NULL), res_distrib(xpdb, title = "type = \'r\'", subtitle = NULL, caption = NULL, type = 'r'), ncol = 3) ``` #### VPCs In visual predictive checks plots `type` can be any combination of: areas `'a'`, lines `'l'`, points `'p'`, text `'t'` or rug `'r'`. ```{r demo type vpc, echo = FALSE, fig.height = 6, fig.width = 6, out.width = '75%'} gridExtra::grid.arrange( vpc(xpdb, title = "type = \'a\'", subtitle = NULL, caption = NULL, type = 'a') + theme(legend.position = 'none') , vpc(xpdb, title = "type = \'l\'", subtitle = NULL, caption = NULL, type = 'l') + theme(legend.position = 'none'), vpc(xpdb, title = "type = \'p\'", subtitle = NULL, caption = NULL, type = 'p'), vpc(xpdb, title = "type = \'t\'", subtitle = NULL, caption = NULL, type = 't'), vpc(xpdb, title = "type = \'r\'", subtitle = NULL, caption = NULL, type = 'r'), ncol = 3) ``` ### Visual guide The option `guide` can enable (`TRUE`) or disable (`FALSE`) the visual guide on the graphs such as the line of identity on the `dv_vs_ipred()` type plot or horizontal lines on residual plots (e.g. `res_vs_idv()`). ### Labels All xpose plots have by default an informative title, subtitle and caption. For example all plots using individual model predictions (IPRED) will display the epsilons' shrinkage. These titles can easily be edited as templates using @keywords which will be replaced by their actual value stored in the summary level of the `xpdb` object when rendering the plots. Keywords are defined by a word preceded by a `@` e.g. `'@ofv'`. A list of all available keyword can be accessed via `help('template_titles')`. The title, subtitle or caption can be disabled by setting them to `NULL`. Suffix can be automatically added to title, subtitle and caption of all plots. The suffixes can be defined in the `xp_theme`. #### From the plot functions ```{r demo titles} # Using template titles dv_vs_ipred(xpdb, title = '@y vs. @x (@run, obj: @ofv)', subtitle = 'Based on: @nind subjects and @nobs records', caption = 'Dir: @dir') # Disabling all titles dv_vs_ipred(xpdb, title = NULL, subtitle = NULL, caption = NULL) # Edit title suffix from the xp_theme for a specific plot dv_vs_ipred(xpdb, title = 'A title', xp_theme = list(title_suffix = ' | a suffix for @run')) ``` #### Using the `labs` function Labels can also modified later on by using the `ggplot2::labs()` function in combination with the ggplot2 `+` operator. ```{r demo xpose_labs} dv_vs_ipred(xpdb) + labs(title = '@descr', subtitle = NULL, caption = 'Based on @nobs observations', x = 'Individual model predictions (@x)', y = 'Observations (@y) for @nind subjects') ``` ### Modify aesthetics By default the aesthetics are read from the `xp_theme` level in the xpdb object but these can be modified in any plot function. xpose makes use of the `ggplot2` functions mapping for any layer (e.g. points, lines, etc.) however to direct the mapping to a specific layer, a prefix appealing to the targeted layer should be used. The format is defined as `layer_aesthetic = value`. Hence to change the color of points in ggplot2 the argument `color = 'green'` could be used in `geom_point()`, while in xpose the same could be achieved with `point_color = 'green'`. In basic goodness-of-fit plots, the layers have been named as: `point_xxx`, `line_xxx`, `smooth_xxx`, `guide_xxx`, `xscale_xxx`, `yscale_xxx` where `xxx` can be any option available in the `ggplot2` layers: `geom_point`, `geom_line`, `geom_smooth`, `geom_abline`, `scale_x_continuous`, etc. ```{r demo aesthetics} dv_vs_ipred(xpdb, # Change points aesthetics point_color = 'blue', point_alpha = 0.5, point_stroke = 0, point_size = 1.5, # Change lines aesthetics line_alpha = 0.5, line_linewidth = 0.5, line_color = 'orange', line_linetype = 'solid', # Change smooth aesthetics smooth_method = 'lm') ``` Aesthetics can also be defined mapped to a variable using the ggplot2 `aes()` function. ```{r demo mapping} dv_vs_ipred(xpdb, type = 'p', aes(point_color = SEX)) ``` ### Grouping variable The argument group defines the grouping variable to be used in the dataset __for the lines only__, by default group is defined to the column `'ID'`. To apply a grouping variable on any other layer, a manual mapping can be made using the argument `xxx_group = variable` ### Panels Panels (or faceting) can be created by using the `facets` argument as follows: * If `facets` is a string e.g `facets = "SEX"`, `ggforce::facet_wrap_paginate` will be used * If `facets` is a formula e.g `facets = SEX~MED1`, `ggforce::facet_grid_paginate` will be used ```{r demo panels, fig.width = 6, fig.height = 6, out.width = '75%'} # Example with a string dv_vs_ipred(xpdb, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1, page = 1) # Example with a formula dv_vs_ipred(xpdb, facets = SEX~MED1, margins = TRUE) ``` All xpose plot functions accept arguments for `facet_wrap_pagninate` and `facet_grid_paginate` (e.g. `ncol = 2`, `labeller = 'label_both'`, etc.). With the default xpose theme scales are set to `'free'` from one panel to another (`scales = 'free'`), this behavior can be changed with `scales = 'fixed'`, `'free_y'` or `'free_x'`. For more information on the available faceting options read the help of [`facet_wrap_paginate`](https://www.rdocumentation.org/packages/ggforce/versions/0.1.1/topics/facet_wrap_paginate) and [`facet_grid_paginate`](https://www.rdocumentation.org/packages/ggforce/versions/0.1.1/topics/facet_grid_paginate) from the package ggforce. ### Additional layers `xpose` offers the opportunity to add any additional layers from `ggplot2`. Hence, a `ggplot2::geom_rug()` layer could be added to the `dv_vs_ipred()` plot along with some annotations (`ggplot2::annotate()`). Note: the additional layers do not inherit from the xpose aesthetic mapping (i.e. colors or other options need to be defined in each layer as shown below). Layers can also be used to modify the aesthetics scales for example `ggplot2::scale_color_manual()`, or remove a legend `ggplot2::scale_fill_identity()`. ```{r demo layers} dv_vs_ipred(xpdb) + geom_rug(alpha = 0.2, color = 'grey50', sides = 'lb', linewidth = 0.4) + annotate(geom = 'text', fontface = 'bold', color = 'darkred', size = 3, label = 'Toxic concentrations', x = 1.35, y = 1.75) + annotate(geom = 'rect', alpha = 0.2, fill = 'red', xmin = 1, xmax = Inf, ymin = 1, ymax = Inf) ``` ### Scales options The argument `log` allows to log-transform the axes. Accepted values are `x`, `y` or `xy`. ```{r log-scales demo, warning=FALSE} dv_vs_ipred(xpdb, log = 'xy', subtitle = 'Plot on log scale') ``` Additional arguments can be provided to the scales via the mapping by using the naming convention `xscale_xxx` or `yscale_xxx` where `xxx` is the name of a `ggplot2` scale argument such as `name`, `breaks`, `labels`, `expand`. ```{r scales-options demo} dv_vs_ipred(xpdb, xscale_breaks = c(0.3, 0.8, 1.3), xscale_labels = c('Low', 'Med', 'High'), xscale_expand = c(0.2, 0), xscale_name = 'Individual model predictions') ``` ### Themes Theme in `xpose` are easily customizable. Themes are made up of two parts: - A `ggplot2` (`gg_theme`) theme controlling the aspect of the plot window - An `xpose` (`xp_theme`) theme controlling the aspect of the layers such as points or lines Themes can be attached to an `xpdb` when importing the data with `xpose_data()` or using the function `update_themes()` on an xpdb object. ```{r demo themes xpdb, eval = FALSE} # While creating the xpdb xpdb <- xpose_data(runno = '001', gg_theme = theme_minimal(), xp_theme = theme_xp_xpose4()) # Update a pre-existing xpdb xpdb <- update_themes(xpdb = xpdb, gg_theme = theme_bw2(), xp_theme = list(point_color = 'dodgerblue4', line_color = 'dodgerblue4')) ``` #### Examples of `gg_theme`: xpose brings two additional themes (`theme_readable()` and `theme_bw2()`), to those available in `ggplot2`. ```{r demo gg_theme, echo = FALSE, fig.height = 6, fig.width = 6, out.width = '75%'} gridExtra::grid.arrange( dv_vs_ipred(xpdb, subtitle = 'theme_grey() [default in ggplot2]', title = NULL, caption = '', facet = 'VAR') + theme_grey(), dv_vs_ipred(xpdb, subtitle = 'theme_readable() [default in xpose]', title = NULL, caption = '', facet = 'VAR') + theme_readable(), dv_vs_ipred(xpdb, subtitle = 'theme_bw2()', title = NULL, caption = NULL, facet = 'VAR') + theme_bw2(), dv_vs_ipred(xpdb, subtitle = 'theme_dark()', title = NULL, caption = NULL, facet = 'VAR') + theme_dark(), ncol = 2) ``` #### Examples of `xp_theme`: ```{r demo xp_theme, echo = FALSE, fig.height = 3.2, fig.width = 6, out.width = '75%'} gridExtra::grid.arrange( dv_vs_ipred(update_themes(xpdb = xpdb, xp_theme = theme_xp_default()), subtitle = 'xp_theme = theme_xp_default()\nwith theme_bw2()', title = NULL, caption = '', facet = 'VAR') + theme_bw2(), dv_vs_ipred(update_themes(xpdb = xpdb, xp_theme = theme_xp_xpose4()), subtitle = 'xp_theme = theme_xp_xpose4()\nwith theme_bw2()', title = NULL, caption = '', facet = 'VAR') + theme_bw2(), ncol = 2) ```
/scratch/gouwar.j/cran-all/cranData/xpose/vignettes/customize_plots.Rmd
--- title: "Import model outputs" author: "Benjamin Guiastrennec" date: "`r format(Sys.time(), '%d %B, %Y')`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Import model outputs} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} library(xpose) options(width = 100) xpdb <- xpdb_ex_pk knitr::opts_chunk$set(fig.dpi = 96, fig.align = 'center', fig.height = 4, fig.width = 4, out.width = '75%', comment = '', message = FALSE) ``` ### The `xpose_data` function The function `xpose_data()` collects all model output files and table and organizes them into an R object commonly called `xpdb` for xpose data base. ``` r xpdb <- xpose_data(runno = '001') ``` ### Imported files #### NONMEM runs To make full use of the functionality offered by `xpose` the following NONMEM output files should be available: - `.lst/.out/.res`: used to collect information on the run (`template_titles`) as well as the output table names. Alternatively a model file (`.mod/.ctl`) can be used but some of the information in `template_titles` may not be available. - `.ext`: used to collect final parameter estimates and residual standard error (RSE) - `.phi`: used for the random effects and iOFV - `.cov`: used for the covariance matrix - `.cor`: used for the correlation matrix - `.grd`: used for the estimation gradients - `.shk`: used to compute random effect shrinkage `template_titles` - output and simulation tables: for the actual data When importing the files, xpose will return messages to the console and inform of any issue encountered during the import. ```r xpdb <- xpose_data(runno = '001') Looking for nonmem output tables Reading: sdtab001, catab001, cotab001, patab001 [$prob no.1] Looking for nonmem output files Reading: run001.cor, run001.cov, run001.ext, run001.grd, run001.phi ``` These messages can be silenced with the option `quiet = TRUE`. ##### `FIRSTONLY` tables xpose is compatible with the `$TABLE FIRSTONLY` option of NONMEM. The option `FIRSTONLY` only output the first record for each `ID` and hence can be used to decrease the size of output tables having no time-varying columns. During tables import xpose will merge `FIRSTONLY` tables with regular tables allowing seamless use of columns from `FIRSTONLY` in plots. ##### Compressed tables xpose makes use of the [readr](https://readr.tidyverse.org) which offers the advantages of 1) rapidly import big tables and 2) automatically import compressed table (e.g. sdtab001.zip) to increase storage capacity. #### Others NLME tools Coming with future releases... ### Structure of the `xpdb` object A typical `xpdb` object contains 8 levels namely: - `code`: the parsed model code - `summary`: contains key information regarding the model. All the information contained in the summary can be used as part of the `template_titles`. - `data`: contains all output and simulation tables as well as the column indexing - `files`: contains all output files - `special`: contains post-processed datasets used by functions like `vpc()` - `gg_theme`: an attached ggplot2 theme - `xp_theme`: an attached xpose theme - `options`: attached global options
/scratch/gouwar.j/cran-all/cranData/xpose/vignettes/import_model_outputs.Rmd
--- title: "Introduction" author: "Benjamin Guiastrennec" date: "`r format(Sys.time(), '%d %B, %Y')`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} library(xpose) xpdb <- xpdb_ex_pk %>% set_var_types(idv = 'TIME') knitr::opts_chunk$set(fig.dpi = 96, fig.align = 'center', fig.height = 4, fig.width = 4, out.width = '50%', comment = '', message = FALSE) ``` ### Load xpose The first step is to load xpose in R with the following command: ```r library(xpose) ``` ### Import model output The function `xpose_data()` collects all model output files and table and organizes them into an R object commonly called `xpdb` which stands for "xpose database". ``` r xpdb <- xpose_data(runno = '001', dir = 'analysis/model/pk/') ``` ### Glimpse at the xpdb The files attached to an xpdb object can be displayed to the console simply by writing its name to the console or by using the `print()` function. ```{r demo print xpose_data} xpdb # or print(xpdb) ``` ### Model summary A summary of a model run can be displayed to the console by using the `summary()` function on an xpdb object. ```{r demo xpose summary} summary(xpdb) ``` ### Parameter estimates A table of parameter estimates can be displayed to the console by using the `prm_table()` function on an xpdb object. ```{r demo prm_table} prm_table(xpdb) ``` ### Listing variables A list of available variables for plotting can be displayed to the console by using the `list_vars()` function on an xpdb object. ```{r demo list_vars} list_vars(xpdb) ``` ### Pipes `xpose` makes use of the pipe operator `%>%` from the package [dplyr](https://dplyr.tidyverse.org). Pipes can be used to generate clear workflow. ```{r, eval = FALSE} xpose_data(runno = '001') %>% dv_vs_ipred() %>% xpose_save(file = 'run001_dv_vs_ipred.pdf') ``` ### Editing the xpdb Multiples edits can be made to the xpdb object. For instance the type (visible using the `list_vars()` function described above) of a variable can be changed. Hence the independent variable (idv) could be changed from `TIME` (default in NONMEM) to `TAD`. All plots using `idv` will then automatically use `TAD`. ```{r, change idv} # With the TIME default xpdb %>% dv_vs_idv() # After IDV reassignment xpdb %>% set_var_types(idv = 'TAD') %>% dv_vs_idv() ``` ### Generating plots Plotting functions are used as follows: ``` {r demo basic gof} # DV vs. IPRED plot dv_vs_ipred(xpdb) # CWRES vs. PRED plot res_vs_pred(xpdb, res = 'CWRES') ``` ### Saving plots The `xpose_save` function was designed to facilitate the export of xpose plots. The file extension is guessed from the file name and must match one of .pdf (default), .jpeg, .png, .bmp or .tiff. If no extension is provided as part of the file name a .pdf will be generated. Finally, if the `plot` argument is left empty `xpose_save` will automatically save the last plot that was created or modified. The `xpose_save()` function is compatible with templates titles and keywords such as `@run` for the run number and `@plotfun` for the name of the plotting function can be used to automatically name files. Learn more about the template titles keywords using `help('template_titles')`. ```{r, eval = FALSE} # Save the last generated plot dv_vs_ipred(xpdb) xpose_save(file = 'run001_dv_vs_ipred.pdf') # Template titles can also be used in filename and the directory xpdb %>% dv_vs_ipred() %>% xpose_save(file = '@run_@plotfun_[@ofv].jpeg', dir = '@dir') ```
/scratch/gouwar.j/cran-all/cranData/xpose/vignettes/introduction.Rmd
--- title: "Plots with multiple pages" author: "Benjamin Guiastrennec" date: "`r format(Sys.time(), '%d %B, %Y')`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Plots with multiple pages} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} library(xpose) options(width = 100) xpdb <- xpdb_ex_pk knitr::opts_chunk$set(fig.dpi = 96, fig.align = 'center', fig.height = 4, fig.width = 6, out.width = '75%', comment = '', message = FALSE) ``` # Bases of plot faceting Panels (or faceting) can be created by using the `facets` argument as follows: * If `facets` is a string e.g `facets = "SEX"`, facets will be created using `ggforce::`[`facet_wrap_paginate`](https://www.rdocumentation.org/packages/ggforce/versions/0.1.1/topics/facet_wrap_paginate) * If `facets` is a formula e.g `facets = SEX~MED1`, facets will be created using `ggforce::`[`facet_grid_paginate`](https://www.rdocumentation.org/packages/ggforce/versions/0.1.1/topics/facet_grid_paginate) ```{r demo panels, fig.height = 6} # Example with a string dv_vs_ipred(xpdb, facets = c('SEX', 'MED1')) # Example with a formula dv_vs_ipred(xpdb, facets = SEX~MED1, margins = TRUE) ``` All xpose plot functions accept arguments for `facet_wrap_pagninate` and `facet_grid_paginate` (e.g. `ncol = 2`, `labeller = 'label_both'`, etc.). With the default xpose theme scales are set to `'free'` from one panel to another (`scales = 'free'`), this behavior can be changed with `scales = 'fixed'`, `'free_y'` or `'free_x'`. # Faceting over multiple pages ## Setting the layout When the arguments `ncol` and `nrow` are set and under the condition that they are more panels to be drawn that can fit on a single page given the selected layout, the multiple page functionality will automatically be enabled. ```{r, message = FALSE} dv_vs_ipred(xpdb, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1) ``` ## Selecting pages By default all pages will be shown but this can be time consuming. To select only specific pages to be drawn, use the argument `page`. ```{r, messages = TRUE} dv_vs_ipred(xpdb, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1, page = 1) ``` It is also possible to change the page(s) to be drawn from an already existing `xpose_plot` object via the `print()` function. ```{r, eval = FALSE} # Create an xpose_plot, by default page = 1 p1 <- dv_vs_ipred(xpdb, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1) # Change the page to be drawn print(p1, page = 2) ``` ## Numbering pages To number pages the keywords `@page` and `@lastpage` can be used to respectively indicate the current page and the total number of pages. ```{r} dv_vs_ipred(xpdb, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1, page = 1, caption = 'Page @page of @lastpage') ``` To systematically number all generated plots a caption suffix can be defined in the `xp_theme`. ```{r} xpdb_numbered <- update_themes(xpdb, xp_theme = list(caption_suffix = ', page @page of @lastpage')) dv_vs_ipred(xpdb_numbered, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1, page = 2) ``` # Saving multiple pages plots Multiple pages graphs can simply be saved by using the `xpose_save()` function. ```{r, eval = FALSE} dv_vs_ipred(xpdb_numbered, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1) %>% xpose_save(file = 'dv_vs_ipred_multiple.pdf') ``` The `pdf` format can conveniently store multiple pages within a single document. However other graphical devices (e.g. `'png'`, `'jpg'`) can also be used, simply ensure to have a page counter (i.e. `'%03d'`) added the file name. ```{r, eval = FALSE} dv_vs_ipred(xpdb_numbered, facets = c('SEX', 'MED1'), ncol = 2, nrow = 1) %>% xpose_save(file = '@run_@plotfun_%03d.png') ```
/scratch/gouwar.j/cran-all/cranData/xpose/vignettes/multiple_pages.Rmd
--- title: "Visual Predictive Checks (VPC)" author: "Benjamin Guiastrennec" date: "`r format(Sys.time(), '%d %B, %Y')`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Visual Predictive Checks (VPC)} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} library(xpose) knitr::opts_chunk$set(fig.dpi = 96, fig.align = 'center', fig.height = 4, fig.width = 6, out.width = '75%', comment = '', message = FALSE) ``` ### Disclosure The Visual predictive checks (VPC) shown below are only intended to demonstrate the various options available in xpose and should not be used as reference for modeling practice. Furthermore, the plots are only based on 20 simulations to minimize the computing time of the examples, the size of the `xpdb_ex_pk` object and of the xpose package in general. ### Introduction VPC can be created either by: 1. Using an xpdb containing a simulation and an estimation problem 2. Using a [PsN](https://uupharmacometrics.github.io/PsN/) generated VPC folder The VPC functionality in xpose is build around the [vpc R package](https://cran.r-project.org/package=vpc). For more details about the way the vpc package works, please check the [github repository](https://github.com/ronkeizer/vpc). ### Workflow The VPC computing and plotting parts have been separated into two distinct functions: `vpc_data()` and `vpc()` respectively. This allows to: * Optimize the speed when adjusting the graphics aesthetics * Adjust the VPC data (e.g. remove panels or factor labels) before plotting * Facilitate error debugging ```{r} xpdb_ex_pk %>% vpc_data() %>% # Compute the vpc data vpc() # Plot the vpc ``` The generated VPC data is stored in the xpdb under specials datasets and can be used later on. ```{r, warning = FALSE} xpdb_w_vpc <- vpc_data(xpdb_ex_pk) # Compute and store VPC data xpdb_w_vpc # The vpc data is now listed under the xpdb "special" data vpc(xpdb_w_vpc) # Plot the vpc from the stored data ``` Multiple VPC data can be stored in an xpdb, but only one of each `vpc_type`. ```{r, eval = FALSE, warning = FALSE} xpdb_w_multi_vpc <- xpdb_ex_pk %>% vpc_data(vpc_type = 'continuous', opt = vpc_opt(n_bins = 6, lloq = 0.1)) %>% vpc_data(vpc_type = 'censored', opt = vpc_opt(n_bins = 6, lloq = 0.1)) vpc(xpdb_w_multi_vpc, vpc_type = 'continuous') vpc(xpdb_w_multi_vpc, vpc_type = 'censored') ``` ### Common options #### Options in `vpc_data()` * The option `vpc_type` allows to specify the type of VPC to be computed: "continuous" (default), "categorical", "censored", "time-to-event". * The `stratify` options defines up to two stratifying variable to be used when computing the VPC data. The `stratify` variables can either be provided as a character vector (`stratify = c('SEX', 'MED1')`) or a formula (`stratify = SEX~MED1`) . The former will result in the use of `ggforce::facet_wrap_paginate()` and the latter of `ggforce::facet_grid_paginate()` when creating the plot. With "categorical" VPC the "group" variable will also be added by default. * More advanced options (i.e. binning, pi, ci, predcorr, lloq, etc.) are accessible via the `opt` argument. The `opt` argument expects the output from the `vpc_opt()` functions argument. ```{r, eval = FALSE, warning = FALSE} xpdb_ex_pk %>% vpc_data(vpc_type = 'censored', stratify = 'SEX', opt = vpc_opt(bins = 'jenks', n_bins = 7, lloq = 0.5)) %>% vpc() ``` #### Options in `vpc()` * The option `vpc_type` works similarly to `vpc_data()` and is only required if several VPC data are associated with the xpdb. * The option `smooth = TRUE/FALSE` allows to switch between smooth and squared shaded areas. * The plot VPC function works similarly to all other xpose functions to map and customize aesthetics. However in this case the `area_fill` and `line_linetype` each require three values for the low, median and high percentiles respectively. ### Creating VPC using the xpdb data To create VPC using the xpdb data, at least one simulation and one estimation problem need to present. Hence in the case of NONMEM the run used to generate the xpdb should contain several`$PROBLEM`. In `vpc_data()` the problem number can be specified for the observation (`obs_problem`) and the simulation (`sim_problem`). By default xpose picks the last one of each to generate the VPC. ```{r} # View the xpdb content and data problems xpdb_ex_pk # Generate the vpc xpdb_ex_pk %>% vpc_data(vpc_type = 'continuous', obs_problem = 1, sim_problem = 2) %>% vpc() ``` ### Creating the VPC using a PsN folder The `vpc_data()` contains an argument `psn_folder` which can be used to point to a [PsN](https://uupharmacometrics.github.io/PsN/) generated VPC folder. As in most xpose function `template_titles` keywords can be used to automatize the process e.g. `psn_folder = '@dir/@run_vpc'` where `@dir` and `@run` will be automatically translated to initial (i.e. when the xpdb was generated) run directory and run number `'analysis/models/pk/run001_vpc'`. In this case, the data will be read from the `/m1` sub-folder (or `m1.zip` if compressed). Note that [PsN](https://uupharmacometrics.github.io/PsN/) drops unused columns to reduce the simtab file size. Thus, in order to allow for more flexibility in R, it is recommended to use multiple stratifying variables (`-stratify_on=VAR1,VAR2`) and the prediction corrected (`-predcorr` adds the PRED column to the output) options in [PsN](https://uupharmacometrics.github.io/PsN/) to avoid having to rerun [PsN](https://uupharmacometrics.github.io/PsN/) to add these variables later on. In addition, `-dv`, `-idv`, `-lloq`, `-uloq`, `-predcorr` and `-stratify_on` [PsN](https://uupharmacometrics.github.io/PsN/) options are automatically applied to xpose VPC. The PsN generated binning can also applied to xpose VPC with the `vpc_data()` option `psn_bins = TRUE` (disabled by default). However [PsN](https://uupharmacometrics.github.io/PsN/) and the vpc package work slightly differently so the results may not be optimal and the output should be evaluated carefully. ```{r, eval = FALSE} xpdb_ex_pk %>% vpc_data(psn_folder = '@dir/run001_vpc', psn_bins = TRUE) %>% vpc() ```
/scratch/gouwar.j/cran-all/cranData/xpose/vignettes/vpc.Rmd
#' Default VPC theme for 'xpose.nlmixr2' #' #' @description Default VPC theme for 'xpose.nlmixr2'. #' #' @return A list with 'vpc' theme specifiers. #' #' @importFrom vpc new_vpc_theme #' @importFrom xpose theme_xp_default #' #' @export nlmixr2_vpc_theme <- vpc::new_vpc_theme(list(obs_color = "#1F4E79", obs_size = 1, obs_median_color = "#1F4E79", obs_median_linetype = "solid", obs_median_size = 1, obs_alpha = .7, obs_shape = 1, obs_ci_color = "#1F4E79", obs_ci_linetype = "dashed", obs_ci_size = .5, sim_pi_fill = "#C00000", sim_pi_alpha = 0.15, sim_pi_color = "#1F4E79", sim_pi_linetype = 'dotted', sim_pi_size = 1, sim_median_fill = "#C00000", sim_median_alpha = 0.15, sim_median_color = "#1F4E79", sim_median_linetype = "dashed", sim_median_size = 1, bin_separators_color = "#000000" ) )
/scratch/gouwar.j/cran-all/cranData/xpose.nlmixr2/R/nlmixr_vpc_theme.R
#' Data summary function #' #' @description Convert 'nlmixr2' model output into an 'xpose' database #' #' @param obj nlmixr2 fit object to be evaluated #' @param model Model. Can be blank #' @param software Software that generated the model fit #' @param rounding Number of figures to round estimates to #' @param runname Name of the model object being converted #' #' @return A summary data object used by \link{xpose_data_nlmixr2}. #' #' @importFrom magrittr %>% #' @importFrom dplyr bind_rows filter mutate arrange_at case_when select one_of tibble #' @importFrom tidyr complete #' @importFrom rlang syms #' @importFrom methods is summarise_nlmixr2_model <- function(obj, model, software, rounding, runname) { sum <- dplyr::bind_rows( sum_nlmixr2_software(software), # Software name sum_nlmixr2_version(software), # Software version sum_nlmixr2_file(runname, software), # Model file sum_nlmixr2_run(obj, runname, software), # Model run sum_nlmixr2_directory(obj, software), # Model directory sum_nlmixr2_reference(model, software), # Reference model sum_nlmixr2_timestart(obj, model, software), # Run start time sum_nlmixr2_timestop(obj, model, software), # Run stop time sum_nlmixr2_probn(model, software), # Problem no. sum_nlmixr2_label(model, software), # Model label sum_nlmixr2_description(model, software), # Model description sum_nlmixr2_input_data(obj, model, software), # Model input data used sum_nlmixr2_nobs(model, software, obj), # Simulation seed sum_nlmixr2_subroutine(model, software), # Des solver sum_nlmixr2_runtime(model, software, obj, rounding), # Estimation runtime sum_nlmixr2_covtime(model, software, obj, rounding), # Covariance matrix runtime sum_nlmixr2_term(model, software), # Run termination message sum_nlmixr2_warnings(model, software), # Run warnings (e.g. boundary) sum_nlmixr2_errors(model, software), # Run errors (e.g termination error) sum_nlmixr2_nsig(model, software), # Number of significant digits sum_nlmixr2_condn(model, software, rounding), # Condition number sum_nlmixr2_nesample(model, software), # Number of esample sum_nlmixr2_esampleseed(model, software), # esample seed number sum_nlmixr2_ofv(model, software, obj, rounding), # Objective function value sum_nlmixr2_method(model, software, obj), # Estimation method or sim sum_nlmixr2_shk(model, software, 'eps', obj, rounding), # Epsilon shrinkage sum_nlmixr2_shk(model, software, 'eta', obj, rounding) # Eta shrinkage ) . = NULL problem <- label <- NULL # Complete missing cases for consistency tmp <- sum %>% dplyr::filter(.$problem != 0) if (nrow(tmp) == 0) return(sum) tmp %>% tidyr::complete(!!!rlang::syms(c('problem', 'label')), fill = list(subprob = 0, value = 'na')) %>% dplyr::bind_rows(dplyr::filter(sum, sum$problem == 0)) %>% dplyr::arrange_at(.vars = c('problem', 'label', 'subprob')) %>% dplyr::mutate(descr = dplyr::case_when( .$label == 'software' ~ 'Software', .$label == 'version' ~ 'Software version', .$label == 'file' ~ 'Run file', .$label == 'run' ~ 'Run number', .$label == 'dir' ~ 'Run directory', .$label == 'ref' ~ 'Reference model', .$label == 'probn' ~ 'Problem number', .$label == 'timestart' ~ 'Run start time', .$label == 'timestop' ~ 'Run stop time', .$label == 'descr' ~ 'Run description', .$label == 'label' ~ 'Run label', .$label == 'data' ~ 'Input data', .$label == 'nobs' ~ 'Number of observations', .$label == 'nind' ~ 'Number of individuals', .$label == 'nsim' ~ 'Number of simulations', .$label == 'simseed' ~ 'Simulation seed', .$label == 'subroutine' ~ 'ADVAN', .$label == 'runtime' ~ 'Estimation runtime', .$label == 'covtime' ~ 'Covariance step runtime', .$label == 'term' ~ 'Termination message', .$label == 'warnings' ~ 'Run warnings', .$label == 'errors' ~ 'Run errors', .$label == 'nsig' ~ 'Number of significant digits', .$label == 'condn' ~ 'Condition number', .$label == 'nesample' ~ 'Number of ESAMPLE', .$label == 'esampleseed' ~ 'ESAMPLE seed number', .$label == 'ofv' ~ 'Objective function value', .$label == 'method' ~ 'Estimation method', .$label == 'epsshk' ~ 'Epsilon shrinkage', .$label == 'etashk' ~ 'Eta shrinkage')) %>% dplyr::select(dplyr::one_of('problem', 'subprob', 'descr', 'label', 'value')) } # Default template for function output sum_tpl <- function(label, value) { dplyr::tibble(problem = 0, subprob = 0, label = label, value = value) } # Software name sum_nlmixr2_software <- function(software) { sum_tpl('software', software) } # Software version sum_nlmixr2_version <- function(software) { sum_tpl('version', as.character(utils::packageVersion('nlmixr2'))) } # Model object name sum_nlmixr2_file <- function(runname, software) { if (software == 'nlmixr2') { dplyr::tibble(problem = 1, subprob = 0, label = 'file', value = runname) } } # Model run name sum_nlmixr2_run <- function(obj, runname, software) { if (software == 'nlmixr2') { if(!is.null(obj$model.name)) { dplyr::tibble(problem = 1, subprob = 0, label = 'run', value = obj$model.name) } else { dplyr::tibble(problem = 1, subprob = 0, label = 'run', value = runname) } } } # Model file directory sum_nlmixr2_directory <- function(obj, software) { if (software == 'nlmixr2') { dplyr::tibble(problem = 1, subprob = 0, label = 'dir', value = getwd()) } } # Reference model sum_nlmixr2_reference <- function(model, software) { if (software == 'nlmixr2') { sum_tpl('ref', 'not implemented') } } # Run start time sum_nlmixr2_timestart <- function(obj, model, software) { if (software == 'nlmixr2') { dplyr::tibble(problem = 0, subprob = 0, label = 'timestart', value = as.character(obj$start.time)) } } # Run stop time sum_nlmixr2_timestop <- function(obj, model, software) { if (software == 'nlmixr2') { dplyr::tibble(problem = 0, subprob = 0, label = 'timestop', value = as.character(obj$stop.time)) } } # Problem no. sum_nlmixr2_probn <- function(model, software) { if (software == 'nlmixr2') { dplyr::tibble(problem = 1, subprob = 0, label = 'probn', value = '1') } } # Model Label sum_nlmixr2_label <- function(model, software) { if (software == 'nlmixr2') { dplyr::tibble(problem = 1, subprob = 0, label = 'label', value = 'na') } } # Model description sum_nlmixr2_description <- function(model, software) { if (software == 'nlmixr2') { sum_tpl('descr', 'not implemented') } } # Input data sum_nlmixr2_input_data <- function(obj, model, software) { if (software == 'nlmixr2') { if(!is.null(obj$data.name)) { dplyr::tibble(problem = 1, subprob = 0, label = 'data', value = obj$data.name) } else { sum_tpl('data', 'not available') } } } # Number of observations sum_nlmixr2_nobs <- function(model, software, obj) { if (software == 'nlmixr2') { dplyr::tibble(problem = 1, subprob = 0, label = 'nobs', value = as.character(obj$nobs)) } } # Number of individuals sum_nlmixr2_nind <- function(model, software, obj) { if (software == 'nlmixr2') { nind <- obj$nsub dplyr::tibble(problem = 1, subprob = 0, label = 'nind', value = as.character(nind)) } } # Simulation number sum_nlmixr2_nsim <- function(model, software) { if (software == 'nlmixr2') { sum_tpl('nsim', 'not implemented') } } # Simulation seed sum_nlmixr2_simseed <- function(obj, model, software) { if (software == 'nlmixr2') { dplyr::tibble(problem = 1, subprob = 0, label = 'seed', value = as.character(obj$seed)) } } # DES solver sum_nlmixr2_subroutine <- function(model, software) { if (software == 'nlmixr2') { dplyr::tibble(problem = 1, subprob = 0, label = 'subroutine', value = 'na') } } # Estimation runtime sum_nlmixr2_runtime <- function(model, software, obj, rounding) { if (software == 'nlmixr2') { rt <- 'na' if (is(obj, "nlmixr2FitData")) { rt <- sum(as.matrix(obj$time[, names(obj$time) != "covariance"])) } if (rt!='na') { dplyr::tibble(problem = 1, subprob = 0, label = 'runtime', value = as.character(round(rt, rounding))) } else { dplyr::tibble(problem = 1, subprob = 0, label = 'runtime', value = 'not available') } } } # Covariance matrix runtime sum_nlmixr2_covtime <- function(model, software, obj, rounding) { if (software == 'nlmixr2') { rt <- obj$time$covariance if (!is.null(rt)) { dplyr::tibble(problem = 1, subprob = 0, label = 'covtime', value = as.character(round(rt, rounding))) } else { dplyr::tibble(problem = 1, subprob = 0, label = 'covtime', value = 'not available') } } } # Run termination sum_nlmixr2_term <- function(model, software) { if (software == 'nlmixr2') { dplyr::tibble(problem = 1, subprob = 0, label = 'term', value = 'na') } } # Run warnings (e.g. boundary) sum_nlmixr2_warnings <- function(model, software) { if (software == 'nlmixr2') { # Can get warnings in $warnings dplyr::tibble(problem = 1, subprob = 0, label = 'warnings', value = 'na') } } # Run errors (e.g termination error) sum_nlmixr2_errors <- function(model, software) { if (software == 'nlmixr2') { sum_tpl('errors', 'na') } } # Number of significant digits sum_nlmixr2_nsig <- function(model, software) { if (software == 'nlmixr2') { dplyr::tibble(problem = 1, subprob = 0, label = 'nsig', value = 'na') } } # Condition number sum_nlmixr2_condn <- function(model, software, rounding) { if (software == 'nlmixr2') { dplyr::tibble(problem = 1, subprob = 0, label = 'condn', value = 'not implemented') } } # Number of ESAMPLE (i.e. NPDE) sum_nlmixr2_nesample <- function(model, software) { if (software == 'nlmixr2') { sum_tpl('nesample', 'na') } } # ESAMPLE seed number sum_nlmixr2_esampleseed <- function(model, software) { if (software == 'nlmixr2') { sum_tpl('esampleseed', 'na') } } # Objective function value sum_nlmixr2_ofv <- function(model, software, obj, rounding) { if (software == 'nlmixr2') { ofv <- obj$objective if(!is.null(ofv)) { dplyr::tibble(problem = 1, subprob = 0, label = 'ofv', value = as.character(round(ofv, digits=rounding))) } else { dplyr::tibble(problem = 1, subprob = 0, label = 'ofv', value = 'not available') } } } # Estimation method or sim sum_nlmixr2_method <- function(model, software, obj) { if (software == 'nlmixr2') { dplyr::tibble(problem = 1, subprob = 0, label = 'method', value = obj$est) } } # Epsilon/Eta shrinkage sum_nlmixr2_shk <- function(model, software, type, obj, rounding) { if (software == 'nlmixr2') { shk <- 'na' lab <- paste(type, 'shk', sep='') if (any("nlmixr2FitData" == class(obj))) { if(type=="eps") { shk <- paste(round((1 - stats::sd(obj$IWRES))*100, digits = rounding), "[1]", sep=" ") } if(type=="eta") { omega <- diag(obj$omega) d <- as.data.frame(obj[!duplicated(obj$ID),]) ## add ETA if missing if(!all(names(omega) %in% names(d))) { d <- merge(d, obj$eta) } ## account for 1-eta systems if(length(names(omega)) == 1) { d <- data.frame(eta = d[,names(d) %in% names(omega)]) names(d) <- names(omega) } else { d <- d[,names(d) %in% names(omega)] } eshr <- c() for (i in 1:length(omega)) { shr <- (1 - (stats::sd(d[,i]) / sqrt(omega[i])))*100 eshr <- c(eshr, round(shr, 3)) } shk <- paste(paste(round(eshr, digits = rounding), ' [', 1:length(eshr), ']', sep=''), collapse=', ') } } dplyr::tibble(problem = 1, subprob = 0, label = lab, value = shk) } }
/scratch/gouwar.j/cran-all/cranData/xpose.nlmixr2/R/summarise_nlmixr_model.R
#' Default 'nlmixr2' theme for 'xpose' #' #' @description Default 'nlmixr2' theme for 'xpose'. #' #' @return A list with 'xpose' theme specifiers. #' #' @importFrom ggplot2 labeller label_both #' @importFrom xpose theme_xp_default #' #' @export theme_xp_nlmixr2 <- function () { structure(list(rounding = 1, title_suffix = "", subtitle_suffix = "", caption_suffix = "", facets = NULL, ncol = NULL, nrow = NULL, page = NULL, scales = "free", shrink = TRUE, labeller = ggplot2::labeller(.default = ggplot2::label_both, .multi_line = FALSE), as.table = TRUE, switch = NULL, drop = TRUE, dir = "h", strip.position = "top", margins = FALSE, space = "fixed", byrow = TRUE, guide_alpha = NA, guide_color = "black", guide_linetype = "solid", guide_size = 0.5, line_alpha = 0.5, line_color = "#1F4E79", line_linetype = "solid", line_size = 0.5, point_alpha = 0.5, point_color = "#1F4E79", point_fill = NA, point_shape = 16, point_size = 2, point_stroke = 0.5, smooth_alpha = NA, smooth_color = "#C00000", smooth_fill = "#C00000", smooth_linetype = 1, smooth_method = "loess", smooth_se = FALSE, smooth_size = 1, smooth_weight = 1, text_alpha = NA, text_angle = 0, text_color = "black", text_family = "", text_fontface = "plain", text_lineheight = 1.2, text_size = 3.1, text_hjust = 0.5, text_vjust = 0.5, density_alpha = NA, density_color = "black", density_fill = NA, density_weight = 1, density_size = 0.5, density_linetype = 2, histogram_alpha = NA, histogram_color = "black", histogram_fill = "#1F4E79", histogram_size = 0.5, histogram_bins = 10, rug_alpha = NA, rug_color = "black", rug_linetype = 1, rug_size = 0.3, area_alpha = NA, area_color = NA, area_fill = "grey35", area_size = 0.5, area_linetype = 1), class = c("xpose_theme", "uneval")) }
/scratch/gouwar.j/cran-all/cranData/xpose.nlmixr2/R/theme_xp_nlmixr.R
#' Import nlmixr2 output into xpose object #' #' @description Convert 'nlmixr2' model output into an 'xpose' database. #' #' @param obj nlmixr2 fit object to be evaluated. #' @param pred Name of the population prediction variable to use for #' plotting. If unspecified, it will choose either "NPDE", #' "CWRES", and "RES" (in that order) if the column exists in the #' data. #' @param wres Name of the weighted residual variable to use for #' plotting. If unspecified, it will choose either "NPDE", #' "CWRES", and "RES" (in that order) if the column exists in the #' data. #' @param gg_theme A ggplot2 theme object. #' @param xp_theme An xpose theme or vector of modifications to the #' xpose theme (eg. \code{c(point_color = 'red', line_linetype = #' 'dashed')}). #' @param quiet Logical, if \code{FALSE} messages are printed to the #' console. #' @param skip Character vector be used to skip the import/generation #' of: 'data', 'files', 'summary' or any combination of the three. #' @param ... Additional arguments to be passed to the #' \code{\link[readr]{read_delim}} functions. #' #' @return An \code{\link[xpose]{xpose_data}} object suitable for use in 'xpose'. #' #' @importFrom nlmixr2est nlmixr2 #' @importFrom dplyr group_by mutate tibble case_when #' @importFrom tibble as_tibble #' @importFrom stringr str_detect #' @importFrom xpose theme_readable theme_xp_default #' @importFrom stats coef rnorm #' #' @examples #' \dontrun{ #' library(nlmixr2) #' #' one.cmt <- function() { #' ini({ #' ## You may label each parameter with a comment #' tka <- 0.45 # Ka #' tcl <- log(c(0, 2.7, 100)) # Log Cl #' ## This works with interactive models #' ## You may also label the preceding line with label("label text") #' tv <- 3.45; label("log V") #' ## the label("Label name") works with all models #' eta.ka ~ 0.6 #' eta.cl ~ 0.3 #' eta.v ~ 0.1 #' add.sd <- 0.7 #' }) #' model({ #' ka <- exp(tka + eta.ka) #' cl <- exp(tcl + eta.cl) #' v <- exp(tv + eta.v) #' linCmt() ~ add(add.sd) #' }) #' } #' #' theo_sd_fit <- nlmixr2(one.cmt, theo_sd, "focei", control=foceiControl(print=0)) #' #' xpdb <- xpose_data_nlmixr2(obj = theo_sd_fit) #'} #' #' @export xpose_data_nlmixr2 <- function(obj = NULL, pred = NULL, #"CPRED", wres = NULL, #"CWRES", gg_theme = theme_readable(), xp_theme = theme_xp_default(), quiet, skip = NULL, ...) { runname <- deparse(substitute(obj)) . = NULL ID = NULL RES = NULL DV = NULL PRED = NULL msg = NULL get_wres <- function(res, dv, pred) { suppressWarnings(res / (sqrt(stats::cov(dv, pred)))) } if (is.null(obj)) { stop('Argument `obj` required.', call. = FALSE) } if (missing(quiet)) quiet <- !interactive() if (!inherits(obj, "nlmixr2FitData")) { stop("Input object needs to be an nlmixr2 fit.") } mtype <- obj$est software <- "nlmixr2" if (is.null(wres)){ if (any(names(obj) == "CWRES")) { wres <- "CWRES" } else if (any(names(obj) == "NPDE")){ wres <- "NPDE" } else if (any(names(obj) == "RES")) { wres <- "RES" obj <- nlmixr2::addCwres(obj) if (any(names(obj) == "CWRES")){ wres <- "CWRES" warning(sprintf("Added CWRES to fit (using %s%s)...", crayon::blue("nlmixr2::"), crayon::yellow("addCwres"))) } else { warning(sprintf("Using RES; Consider adding NPDE (%s%s) to fit.", crayon::blue("nlmixr2::"), crayon::yellow("addNpde"))) } } } if (is.null(pred)){ if (any(names(obj) == "EPRED") & wres == "NPDE"){ pred <- "EPRED" } else if (any(names(obj) == "CPRED") & wres == "CWRES"){ pred <- "CPRED" } else if (any(names(obj) == "PRED") & wres == "RES"){ pred <- "PRED" } else if (any(names(obj) == "EPRED")){ pred <- "EPRED" } else if (any(names(obj) == "CPRED")){ pred <- "CPRED" } else if (any(names(obj) == "PRED")){ pred <- "PRED" } } if (any("nlmixr2FitData" == class(obj))) { data <- as.data.frame(obj) data_a <- data %>% dplyr::group_by(ID) data_a <- tibble::as_tibble(data_a) } if(!(wres %in% names(data_a))) { stop(paste(wres, ' not found in nlmixr2 fit object.', sep=""), call. = FALSE) } if(!(pred %in% names(data_a))) { stop(paste(pred, ' not found in nlmixr2 fit object.', sep=""), call. = FALSE) } if (!inherits(obj, "nlmixr2FitData")) { stop("needs to be a nlmixr2 fit object") } data_a <- obj$dataMergeInner names(data_a) <- toupper(names(data_a)) data_a <- data_a[, !duplicated(names(data_a))] full.dat <- data_a # check for ETAs # if(!any(stringr::str_detect(names(data_a), 'ETA\\d+|ET\\d+|eta.*'))) { # data_a <- merge(data_a, obj$eta) # } if(!all(names(diag(obj$omega)) %in% names(data_a))) { data_a <- merge(data_a, obj$eta) } if (!("EVID" %in% names(data_a))) { data_a$EVID <- 0 } #print(summary(data_a)) data <- NULL data_ind <- data_a %>% colnames() %>% dplyr::tibble(table = 'nlmixr2', col = ., type = NA_character_, label = NA_character_, # Feature to be added in future release units = NA_character_) %>% # Feature to be added in future release dplyr::mutate(type = dplyr::case_when( .$col == 'ID' ~ 'id', .$col == 'DV' ~ 'dv', .$col == 'TIME' ~ 'idv', .$col == 'OCC' ~ 'occ', .$col == 'DVID' ~ 'dvid', .$col == 'AMT' ~ 'amt', .$col == 'MDV' ~ 'mdv', .$col == 'EVID' ~ 'evid', .$col == 'IPRED' ~ 'ipred', .$col == pred ~ 'pred', .$col %in% c('RES', 'WRES', 'CWRES', 'IWRES', 'EWRES', 'NPDE','IRES','CRES') ~ 'res', .$col %in% c('WT','AGE','HT','BMI','LBM') ~ 'contcov', .$col %in% c('SEX','RACE') ~ 'catcov', .$col %in% c('CL','V','V1','V2','V3','Q','Q2','Q3','KA','K12','K21','K','K13','K31','K23','K32','K24','K42','K34','K43', 'cl','v','v1','v2','v3','q','q2','q3','ka','k12','k21','k','k13','k31','k23','k32','k24','k42','k34','k43', 'tcl','tv','tv1','tv2','tv3','tq','tq2','tq3','tka','tk12','tk21','tk','tk13','tk31','tk23','tk32','tk24','tk42','tk34','tk43') ~ 'param', stringr::str_detect(.$col, 'ETA\\d+|ET\\d+|eta.*') ~ 'eta')) data_ind$type[is.na(data_ind$type)] <- 'na' data <- list() data <- dplyr::tibble(problem = 1, simtab = F, index = list(data_ind), data = list(data_a), modified = F) # Generate model summary if ('summary' %in% skip) { msg('Skipping summary generation', quiet) summary <- NULL } else if (software == 'nlmixr2') { summary <- summarise_nlmixr2_model(obj, '', software, rounding = xp_theme$rounding, runname=runname) } # The weighted residuals are calculated by dividing the vector of each # individual's residuals (res_i) by the square root of the matrix of # covariances of that individual's data conditional on the population model: # # WRES_i = RES_i / SQRT(COV(data_i | F_pop)) # # This means that for each WRES calculated we include covariances between data # points of an individual. If the correlations between some of these data # points are negative then the resulting WRES could also be negative, while # the RES could be positive. # # -Andy files <- NULL if(mtype=="saem") { tracedat <- tibble::as_tibble(as.data.frame(obj$par.hist)) names(tracedat)[grep("iter", names(tracedat))] <- "ITERATION" files <- dplyr::tibble(name = deparse(substitute(obj)), extension = 'ext', problem = 1, subprob = 0, method = 'saem', data = list(tracedat), modified = FALSE) } # Label themes attr(gg_theme, 'theme') <- as.character(substitute(gg_theme)) attr(xp_theme, 'theme') <- as.character(substitute(xp_theme)) # Output xpose_data list(code = obj$uif, summary = summary, data = data, files = files, gg_theme = gg_theme, xp_theme = xp_theme, options = list(dir = NULL, quiet = quiet, manual_import = NULL), software = 'nlmixr2') %>% structure(class = c('xpose_data', 'uneval')) } #' @rdname xpose_data_nlmixr2 #' @export xpose_data_nlmixr <- xpose_data_nlmixr2
/scratch/gouwar.j/cran-all/cranData/xpose.nlmixr2/R/xpose_data_nlmixr.R
#' Extract or assign data from an xpose.data object. #' #' Extracts or assigns the data from the Data or SData slots in an "xpose.data" object. #' #' #' When using Data to assign a data.frame to the Data slot in the "xpose.data" #' object a number of things happen: #' #' Each column in the data.frame is checked and set to factor if the number of #' unique values are less than the value of Cat.levels (see #' \code{\link{xpose.prefs-class}}). #' #' It is checked which of the predefined xpose data variables that exists in #' the data.frame. The variable definitions that does not exist are set to NULL. #' #' The column identified by the \code{dv} xpose variable definition, is checked #' and set to factor if the number of unique values are less than or equal to #' the DV.Cat.levels (see \code{\link{xpose.prefs-class}}). #' #' Finally, each column name in the data.frame is checked for a label (see #' \code{\link{xpose.prefs-class}}). If it is non-existent, the label is set to #' the column name. #' #' When SData is used to assign a data.frame to the SData slot it is first #' checked that the number of rows in the SData data.frame is an even multiple #' of the number of rown in Data. Next, each column in the SData data.frame is #' assigned the same class as the corresponding column in the Data data.frame #' (it is required that the columns are the same in Data and SData). Finally, #' an extra column, "iter", is added to SData, which indicates the iteration #' number that each row belongs to. At the same time, the Nsim slot of the #' "xpose.data" object is set to the number of iterations (see #' \code{\link{nsim}}). #' #' @param object An "xpose.data" object #' @param inclZeroWRES Logical value indicating whether rows with WRES==0 #' should be included in the extracted data. #' @param onlyfirst Logical value indicating whether only the first line per #' individual should be included in the extracted data. #' @param subset Expression with which the extracted data should be subset (see #' \code{\link{xsubset}}) #' @param samp An integer between 1 and object@Nsim #' (see\code{\link{xpose.data-class}}) specifying which of the simulated data #' sets to extract from SData. #' @param quiet \code{TRUE or FALSE} if \code{FALSE} then some more information #' is printed out when adding data to an Xpose object. #' @param keep.structure \code{TRUE or FALSE} if\code{FALSE} then values are #' converted to continuous or categorical according to the rules set up by #' xpose using object@[email protected], object@[email protected] and the #' values in the "catab" file. #' @param value An R data.frame. #' @return Returns a data.frame from the Data or SData slots, excluding rows as #' indicated by the arguments. #' @author Niclas Jonsson #' @seealso \code{\link{xpose.data-class}},\code{\link{xpose.prefs-class}} #' @keywords methods #' @examples #' #' xpdb <- simpraz.xpdb #' #' ## Extract data #' my.dataframe <- Data(xpdb) #' #' ## Assign data #' Data(xpdb) <- my.dataframe #' #' ## Extract simulated data #' my.simulated.dataframe <- SData(xpdb) #' #' ## Assign simulated data #' SData(xpdb) <- my.simulated.dataframe #' #' @family data functions #' @name data_extract_or_assign NULL #' @describeIn data_extract_or_assign Extract data #' @export Data <- function(object, inclZeroWRES=FALSE, onlyfirst=FALSE, subset=NULL) { data <- object@Data if(!inclZeroWRES) { data <- data[data[,xvardef("wres",object)]!=0,] } if(onlyfirst) { data <- data[!duplicated(data[,xvardef("id",object)]),] } if(!is.null(subset)) { #attach(data) #on.exit(detach(data)) # data <- data[eval(parse(text=subset)),] #browser() #data <- data[eval(parse(text=paste("data$", subset))),] # fix subsets 22/3/06 data<-with(data,data[eval(parse(text=subset)),]) if(dim(data)[1]==0) return(NULL) } return(data) } #' @describeIn data_extract_or_assign assign data #' @export "Data<-" <- function(object,quiet=TRUE,keep.structure=F,value) { if(is.null(value)) { return(NULL) } object@Data <- value totab.nam <- names(value) # cat(totab.nam, "\n") ## define the important variables in the dataset singdef <- c("id","idlab","idv","dv","pred","ipred","iwres","wres","res","cwres") ## Check if all variable definitions exist in the data for(v in singdef) { if(is.null(xvardef(v,object))){ next } if(is.na(pmatch(xvardef(v,object), totab.nam))) { object@Prefs@Xvardef[[v]] <- NULL ## if DV undefined check what 4th from last in list files says ## must make sure no append is not called if(v=="dv"){ tab.names.list <- c(".sdtab.names.tmp",".patab.names.tmp",".catab.names.tmp",".cotab.names.tmp") append.list <- c("PRED","RES","WRES") dv.found <- FALSE for(vv in tab.names.list){ if(!dv.found){ if (file.exists(vv)){ tmp.list <- scan(vv, what="list", quiet=T) tmp.length <- length(tmp.list) if (all(tmp.list[(tmp.length-2):tmp.length]==append.list)){ object@Prefs@Xvardef[[v]] <- tmp.list[[tmp.length-3]] dv.found <- TRUE } } } } } ## IF TIME isn't in tables is TAD? if(v=="idv"){ if(!is.na(pmatch("TAD",totab.nam))){ object@Prefs@Xvardef[[v]] <- "TAD" } else { if(!is.na(pmatch("CP",totab.nam))){ object@Prefs@Xvardef[[v]] <- "CP" } } } } } ## sort out covariates and parameters ## look at the difference between the names in singdef ## and the names in *.tmp files if (file.exists(".patab.names.tmp")) { xparms <- setdiff(scan(".patab.names.tmp", what="list", quiet=T), sapply(singdef, xvardef, object)) ##unlink("patab.names.txt") } else { xparms <- NULL } if (file.exists(".catab.names.tmp")) { xcatcovs <- setdiff(scan(".catab.names.tmp", what="list", quiet=T), sapply(singdef, xvardef, object)) ##unlink("catab.names.txt") } else { xcatcovs <- NULL } if (file.exists(".cotab.names.tmp")) { xconcovs <- setdiff(scan(".cotab.names.tmp", what="list", quiet=T), sapply(singdef, xvardef, object)) ##unlink("cotab.names.txt") } else { xconcovs <- NULL } if (!is.null(xcatcovs)) { if (!is.null(xconcovs)) { xcovs <- c(xcatcovs, xconcovs) } else { xcovs <- xcatcovs } } else { if (!is.null(xconcovs)) { xcovs <- xconcovs } else { xcovs <- NULL } } ## check for categorical variables if(!keep.structure){ for(v in totab.nam) { if (!is.na(match("TIME",v))) next if (!is.na(match("TAD",v))) next if (!is.na(match("CP",v))) next if (!is.na(match("PRED",v))) next if (!is.na(match("IPRE",v))) next if (!is.na(match("IPRED",v))) next num <- length(unique(object@Data[,v])) if(is.null(xvardef("dv",object))){ if(num <= object@[email protected]) { if(!is.factor(object@Data[,v])){ if(!quiet){ cat("\n Inferring that ",v," is categorical (",num," levels).\n",sep="") cat(" Transforming",v,"from continuous to categorical\n",sep=" ") } object@Data[,v] <- as.factor(object@Data[,v]) } } else { if(is.factor(object@Data[,v])){ if(!quiet){ cat("\n Inferring that",v,"is continuous.\n",sep=" ") cat(" Transforming",v,"from categorical to continuous\n",sep=" ") } object@Data[,v] <- as.numeric(levels(object@Data[,v]))[object@Data[,v]] } } } else { if(is.na(match(xvardef("dv",object), v))) { if(num <= object@[email protected]) { if(!is.factor(object@Data[,v])){ if(!quiet){ cat("\n Inferring that ",v," is categorical (",num," levels).\n",sep="") cat(" Transforming",v,"from continuous to categorical\n",sep=" ") } object@Data[,v] <- as.factor(object@Data[,v]) } } else { if(is.factor(object@Data[,v])){ if(!quiet){ cat("\n Inferring that",v,"is continuous.\n",sep=" ") cat(" Transforming",v,"from categorical to continuous\n",sep=" ") } object@Data[,v] <- as.numeric(levels(object@Data[,v]))[object@Data[,v]] } } } else { if(num <= object@[email protected]) { if(!is.factor(object@Data[,v])){ if(!quiet){ cat("\n Inferring that DV is categorical (",num," levels).\n",sep="") cat(" Transforming DV from continuous to categorical\n") } object@Data[,v] <- as.factor(object@Data[,v]) } } else { if(is.factor(object@Data[,v])){ if(!quiet){ cat("\n Inferring that DV is continuous.\n",sep="") cat(" Transforming DV from categorical to continuous\n") } object@Data[,v] <- as.numeric(levels(object@Data[,v]))[object@Data[,v]] } } } } } if(is.factor(object@Data[,xvardef("dv",object)])){ for (v in totab.nam){ num <- length(unique(object@Data[,v])) if (!is.na(match("PRED",v)) | !is.na(match("IPRE",v)) | !is.na(match("IPRED",v))) { if(!quiet){ cat("\n Inferring that ",v," is categorical (",num," levels).\n",sep="") cat(" Transforming",v,"from continuous to categorical\n",sep=" ") } object@Data[,v] <- as.factor(object@Data[,v]) } } } else { for (v in totab.nam){ if (!is.na(match("PRED",v)) | !is.na(match("IPRE",v)) | !is.na(match("IPRED",v))) { if(is.factor(object@Data[,v])){ if(!quiet){ cat("\n Inferring that",v,"is continuous.\n",sep=" ") cat(" Transforming",v,"from categorical to continuous\n",sep=" ") } object@Data[,v] <- as.numeric(levels(object@Data[,v]))[object@Data[,v]] } } } } } for(v in xcatcovs) { object@Data[,v] <- as.factor(object@Data[,v]) } if (is.null(xparms)) { ep <- c() for(v in xvardef("parms",object)) { if(!is.na(pmatch(v, totab.nam))) { ep <- c(v,ep) } } object@Prefs@Xvardef[["parms"]] <- ep } else { object@Prefs@Xvardef[["parms"]] <- xparms } ep <- c() for(v in xvardef("tvparms",object)) { if(!is.na(pmatch(v, totab.nam))) { ep <- c(v,ep) } } object@Prefs@Xvardef[["tvparms"]] <- ep ep <- c() ranpar.loc <- grep("^ETA",totab.nam) if (length(ranpar.loc)!=0){ ep <- totab.nam[ranpar.loc] } ## for(v in xvardef("ranpar",object)) { ## if(!is.na(pmatch(v, totab.nam))) { ## ep <- c(v,ep) ## } ## } if ((is.vector(ep)) || (is.vector(ep))) { object@Prefs@Xvardef[["ranpar"]] <- sort(ep) } else { object@Prefs@Xvardef[["ranpar"]] <- ep } ## ep <- c() ## for(v in xvardef("cat.cov",object)) { ## if(!is.na(pmatch(v, totab.nam))) { ## ep <- c(v,ep) ## object@Data[,v] <- as.factor(object@Data[,v]) ## } ## } ## object@Prefs@Xvardef[["cat.cov"]] <- ep if (is.null(xcovs)) { ep <- c() for(v in xvardef("covariates",object)) { if(!is.na(pmatch(v, totab.nam))) { ep <- c(v,ep) } } object@Prefs@Xvardef[["covariates"]] <- ep } else { object@Prefs@Xvardef[["covariates"]] <- xcovs } ## Fix the labels for(v in totab.nam) { if(is.null(xlabel(v,object))) { object@Prefs@Labels[[v]] <- v } } return(object) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/Data.R
#' Internal functions for the VPC #' #' Internal functions for the VPC #' #' @aliases setup.PPI #' @param object Xpose object #' @param inclZeroWRES Include row sof data with WRES=0 #' @param onlyfirst Use only first data for each individual #' @param samp sample number #' @param PI.subset Prediction interval subset #' @param subscripts subscripts #' @param PI.bin.table prediction interval binning table #' @param panel.number panel number #' @param PPI Plot prediction intervals #' @param PI.mirror Prediction interval mirror #' @param PIlimits Prediction interval limits #' @param tmp.table temporary table #' @param \dots Extra options passed to arguments #' @return Returned to \code{\link{xpose.VPC}} #' @keywords internal "find.right.table" <- function(object, inclZeroWRES, onlyfirst, samp, PI.subset, subscripts, PI.bin.table, panel.number, ... ){ tmp.table <- NULL ## choose the right conditioning variable if(!is.null(samp)) { data <- SData(object,inclZeroWRES,onlyfirst=onlyfirst,samp=samp,subset=PI.subset) } else { data <- Data(object,inclZeroWRES,onlyfirst=onlyfirst,subset=PI.subset) } tmp.data <- data[subscripts,] stratas <- PI.bin.table[[length(PI.bin.table)]] num.stratas <- length(stratas) ## first check if the panel.number is the same as the VPC strata number tmp.strata=stratas[panel.number] dim.sub.data <- dim(subset(tmp.data,eval(parse(text=tmp.strata)))) if (dim.sub.data[1] == dim(tmp.data)[1]){ tmp.table <- PI.bin.table[[panel.number]] } else { cat(paste("The conditioning variable for the plot\n")) cat(paste(" and the conditioning variable from the VPC file\n")) cat(paste(" are not in the same order. Searching for the right \n")) cat(paste(" prediction interval values to use \n")) cat(paste("\n")) for(i in 1:num.stratas){ if (is.null(tmp.table)){ tmp.strata=stratas[i] tmp.strata=gsub(" = ", " == ",tmp.strata) dim.sub.data <- dim(subset(tmp.data,eval(parse(text=tmp.strata)))) if (dim.sub.data[1] == dim(tmp.data)[1]){ tmp.table <- PI.bin.table[[i]] } } } } return(tmp.table) } #' @rdname find.right.table "setup.PPI" <- function(PIlimits, PI.mirror, tmp.table, ... ){ #browser() ci.indx <- grep("*.CI.*",names(tmp.table)) #names(tmp.table)[[ci.indx[[1]]]] ci.val <- sub("(\\d*)\\.CI\\..*","\\1",names(tmp.table)[[ci.indx[[1]]]],perl=TRUE) sim.bin.table.cols <- paste(PIlimits*100,"sim",sep=".") real.bin.table.cols <- paste(PIlimits*100,"real",sep=".") sim.ci.upper.bin.table.cols <- paste(ci.val,"CI.for",PIlimits*100,"to",sep=".") sim.ci.lower.bin.table.cols <- paste(ci.val,"CI.for",PIlimits*100,"from",sep=".") sim.bin.table.cols.50 <- paste(50,"sim",sep=".") real.bin.table.cols.50 <- paste(50,"real",sep=".") sim.ci.upper.bin.table.cols.50 <- paste(ci.val,"CI.for",50,"to",sep=".") sim.ci.lower.bin.table.cols.50 <- paste(ci.val,"CI.for",50,"from",sep=".") sim.bin.table.cols.mean <- paste("mean","sim",sep=".") real.bin.table.cols.mean <- paste("mean","real",sep=".") sim.ci.upper.bin.table.cols.mean <- paste(ci.val,"CI.for","mean","to",sep=".") sim.ci.lower.bin.table.cols.mean <- paste(ci.val,"CI.for","mean","from",sep=".") sim.bin.table.cols.delta.mean <- paste("delta.mean","sim",sep=".") real.bin.table.cols.delta.mean <- paste("delta.mean","real",sep=".") sim.ci.upper.bin.table.cols.delta.mean <- paste(ci.val,"CI.for","delta.mean","to",sep=".") sim.ci.lower.bin.table.cols.delta.mean <- paste(ci.val,"CI.for","delta.mean","from",sep=".") mir.bin.table.cols <- NULL mir.bin.table.cols.50 <- NULL mir.bin.table.cols.mean <- NULL mir.bin.table.cols.delta.mean <- NULL mir.names.lower <- NULL mir.names.upper <- NULL mir.names.median <- NULL mir.names.mean <- NULL mir.names.delta.mean <- NULL if (!is.null(PI.mirror)) { ## what sort of mirror do we have? if(is.logical(PI.mirror)) { PI.mirror <- 1 } mir.list <- c() for (j in 1:PI.mirror){ mir.list <- c(mir.list,paste("mirror",j,sep=".")) } final.mir.list <- c() for (j in 1:length(PIlimits)){ final.mir.list <- c(final.mir.list, paste(PIlimits[j]*100,mir.list,sep=".") ) } mir.bin.table.cols <- final.mir.list mir.bin.table.cols.50 <- paste("50",mir.list,sep=".") mir.bin.table.cols.mean <- paste("mean",mir.list,sep=".") mir.bin.table.cols.delta.mean <- paste("delta.mean",mir.list,sep=".") mir.names.lower <- paste(mir.list,"lower",sep=".") mir.names.upper <- paste(mir.list,"upper",sep=".") mir.names.median <- paste(mir.list,"median",sep=".") mir.names.mean <- paste(mir.list,"mean",sep=".") mir.names.delta.mean <- paste(mir.list,"delta.mean",sep=".") } PPI <- tmp.table[c(sim.bin.table.cols, sim.bin.table.cols.50, sim.ci.lower.bin.table.cols, sim.ci.upper.bin.table.cols, sim.ci.lower.bin.table.cols.50, sim.ci.upper.bin.table.cols.50, real.bin.table.cols, real.bin.table.cols.50, mir.bin.table.cols, mir.bin.table.cols.50, "lower","upper")] names(PPI) <- c("lower","upper","median", "lower.ci.lower","upper.ci.lower", "lower.ci.upper","upper.ci.upper", "median.ci.lower","median.ci.upper", "real.lower","real.upper","real.median", mir.names.lower,mir.names.upper,mir.names.median, "Xlower","Xupper") if(length(grep("mean",names(tmp.table)))!=0){ PPI["mean"] <- tmp.table[c(sim.bin.table.cols.mean)] PPI["mean.ci.lower"] <- tmp.table[c(sim.ci.lower.bin.table.cols.mean)] PPI["mean.ci.upper"] <- tmp.table[c(sim.ci.upper.bin.table.cols.mean)] PPI["real.mean"] <- tmp.table[c(real.bin.table.cols.mean)] PPI["mir.names.mean"] <- tmp.table[c(mir.bin.table.cols.mean)] } if(length(grep("delta.mean",names(tmp.table)))!=0){ PPI["delta.mean"] <- tmp.table[c(sim.bin.table.cols.delta.mean)] PPI["delta.mean.ci.lower"] <- tmp.table[c(sim.ci.lower.bin.table.cols.delta.mean)] PPI["delta.mean.ci.upper"] <- tmp.table[c(sim.ci.upper.bin.table.cols.delta.mean)] PPI["real.delta.mean"] <- tmp.table[c(real.bin.table.cols.delta.mean)] PPI["mir.names.delta.mean"] <- tmp.table[c(mir.bin.table.cols.delta.mean)] } return(PPI) } #' @rdname find.right.table "get.polygon.regions" <- function(PPI, PI.mirror, ... ){ XU <- PPI$Xupper XL <- PPI$Xlower YU <- PPI$upper YL <- PPI$lower #YMean <- PPI$mean Ymed <- PPI$median if(length(grep("mean",names(PPI)))!=0) Ymean <- PPI$mean if(length(grep("delta.mean",names(PPI)))!=0) Ydelta.mean <- PPI$delta.mean YUU <- PPI$upper.ci.upper YUL <- PPI$upper.ci.lower YLU <- PPI$lower.ci.upper YLL <- PPI$lower.ci.lower YMU <- PPI$median.ci.upper YML <- PPI$median.ci.lower if(length(grep("mean",names(PPI)))!=0){ YmeanU <- PPI$mean.ci.upper YmeanL <- PPI$mean.ci.lower } if(length(grep("delta.mean",names(PPI)))!=0){ Ydelta.meanU <- PPI$delta.mean.ci.upper Ydelta.meanL <- PPI$delta.mean.ci.lower } YUR <- PPI$real.upper YLR <- PPI$real.lower YmedR <- PPI$real.median if(length(grep("mean",names(PPI)))!=0) YmeanR <- PPI$real.mean if(length(grep("delta.mean",names(PPI)))!=0) Ydelta.meanR <- PPI$real.delta.mean if (!is.null(PI.mirror)) { YUM <- PPI[grep("mirror.*upper",names(PPI))] YLM <- PPI[grep("mirror.*lower",names(PPI))] YmedM <- PPI[grep("mirror.*median",names(PPI))] if(length(grep("mean",names(PPI)))!=0) YmeanM <- PPI[grep("mirror.*mean",names(PPI))] if(length(grep("delta.mean",names(PPI)))!=0) Ydelta.meanM <- PPI[grep("mirror.*delta.mean",names(PPI))] #YUM <- PPI[mir.names.upper] #YLM <- PPI[mir.names.lower] #YmedM <- PPI[mir.names.median] } ## Niclas method ##tmpx <- c(XU,rev(XU)) ##tmpy <- c(YU,rev(YL)) if(all(is.na(XL))){ # there are points and not bins x.recs <- c(XU,rev(XU)) y.recs <- c(YU,rev(YL)) y.up.recs <- c(YUU,rev(YUL)) y.down.recs <- c(YLU,rev(YLL)) y.med.recs <- c(YMU,rev(YML)) if(length(grep("mean",names(PPI)))!=0) y.mean.recs <- c(YmeanU,rev(YmeanL)) if(length(grep("delta.mean",names(PPI)))!=0) y.delta.mean.recs <- c(Ydelta.meanU,rev(Ydelta.meanL)) } else { # there are bins YU.rec <- YU YL.rec <- YL YUU.rec <- YUU YUL.rec <- YUL YLU.rec <- YLU YLL.rec <- YLL YMU.rec <- YMU YML.rec <- YML if(length(grep("mean",names(PPI)))!=0){ YmeanU.rec <- YmeanU YmeanL.rec <- YmeanL } if(length(grep("delta.mean",names(PPI)))!=0){ Ydelta.meanU.rec <- Ydelta.meanU Ydelta.meanL.rec <- Ydelta.meanL } XU.rec <- XU XL.rec <- XL ## adjust bins of zero length if(any(XL==XU)){ for(i in 1:length(XL)){ if(XL[i]==XU[i]){ if(i!=1 & i!=length(XL)){ XU.rec[i] <- XU[i]+0.05*(XU[i+1]-XU[i]) XL.rec[i+1] <- XU.rec[i] XL.rec[i] <- XL[i]-0.05*(XL[i]-XL[i-1]) XU.rec[i-1] <- XL.rec[i] } if(i==1){ XU.rec[i] <- XU[i]+0.1*(XU[i+1]-XU[i]) XL.rec[i+1] <- XU.rec[i] } if(i==length(XL)){ XL.rec[i] <- XL[i]-0.1*(XL[i]-XL[i-1]) XU.rec[i-1] <- XL.rec[i] } } } } change.pt <- sort(c(XL,XU)) X.tot <- NULL YU.tot <- NULL YL.tot <- NULL YU.cur <- NULL YL.cur <- NULL for(i in 2:length(change.pt)){ int.val.x <- (change.pt[i]-change.pt[i-1])/2 ##if(change.pt[i]==change.pt.cur){ # X.tot <- c(X.tot,change.pt[i]) #} ## get x values X.tot <- c(X.tot,change.pt[i]) ## if(i==1 | i==length(change.pt)){ ## X.tot <- c(X.tot,change.pt[i]) ## } else { ## X.tot <- c(X.tot,change.pt[i]) ## YU.tot <- c(YU.tot,YU.cur) ## YL.tot <- c(YL.tot,YL.cur) ## } ## get y values ## check if bin is on or not bins.on <- (change.pt[i]<=XU & change.pt[i]>XL) if(i==1) bins.on[1] <- (change.pt[i]<=XU[1] & change.pt[i]>=XL[1]) YU.cur <- mean(YU[bins.on]) YL.cur <- mean(YL[bins.on]) YU.tot <- c(YU.tot,YU.cur) YL.tot <- c(YL.tot,YL.cur) } x.recs <- c(X.tot,rev(X.tot)) y.recs <- c(YU.tot,rev(YL.tot)) x.recs <- as.vector(t(cbind(XL.rec,XU.rec,XU.rec,XL.rec,NA))) y.recs <- as.vector(t(cbind(YU.rec,YU.rec,YL.rec,YL.rec,NA))) y.up.recs <- as.vector(t(cbind(YUU.rec,YUU.rec,YUL.rec,YUL.rec,NA))) y.down.recs <- as.vector(t(cbind(YLU.rec,YLU.rec,YLL.rec,YLL.rec,NA))) y.med.recs <- as.vector(t(cbind(YMU.rec,YMU.rec,YML.rec,YML.rec,NA))) if(length(grep("mean",names(PPI)))!=0){ y.mean.recs <- as.vector(t(cbind(YmeanU.rec,YmeanU.rec,YmeanL.rec,YmeanL.rec,NA))) } if(length(grep("delta.mean",names(PPI)))!=0){ y.delta.mean.recs <- as.vector(t(cbind(Ydelta.meanU.rec,Ydelta.meanU.rec,Ydelta.meanL.rec,Ydelta.meanL.rec,NA))) } } ret <- list(x.recs=x.recs, y.recs=y.recs, y.up.recs=y.up.recs, y.down.recs=y.down.recs, y.med.recs=y.med.recs) if(length(grep("mean",names(PPI)))!=0) ret <- c(ret, "y.mean.recs"=list(y.mean.recs)) if(length(grep("delta.mean",names(PPI)))!=0) ret <- c(ret, "y.delta.mean.recs"=list(y.delta.mean.recs)) return(ret) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/PI.helper.R
#' @describeIn data_extract_or_assign extract simulated data #' @export SData <- function(object, inclZeroWRES=FALSE, onlyfirst=FALSE, subset=NULL, samp=NULL) { data <- object@SData if(is.null(data)) return(NULL) if(!is.null(samp)) { data <- data[data$iter==samp,] # something is wrong with this line #cat(samp) if(is.null(data)) return(NULL) } if(!inclZeroWRES) { data <- data[data[,xvardef("wres",object)]!=0,] } if(onlyfirst) { id <- xvardef("id",object) ind <- paste(data[,id],data$iter,sep="") data<- data[!duplicated(ind),] } if(!is.null(subset)) { #on.exit(detach(data)) #attach(data) # data <- data[eval(parse(text=subset)),] #data <- data[eval(parse(text=paste("data$", subset))),] # fix subsets 22/3/06 data<-with(data,data[eval(parse(text=subset)),]) if(dim(data)[1]==0) return(NULL) } return(data) } #' @describeIn data_extract_or_assign assign simulated data #' @export "SData<-" <- function(object,value) { Snro <- dim(value)[1] Dnro <- dim(Data(object,inclZeroWRES=TRUE))[1] if(Dnro == 0) return("Data should be set before SData!") ## Check to see if the length of the SData is an even multiplier ## of the xData. if (!is.null(Snro)) { if(regexpr("\\.",as.character(Snro/Dnro)) !=-1) { cat("The length of the Data and the SData do not match!\n") return(object) } nams <- names(Data(object)) for(n in nams) { #class(value[,n]) <- class(Data(object)[,n]) if (is.factor(Data(object)[,n])) { value[,n] <- as.factor(value[,n]) } } nsim(object) <- Snro/Dnro ## Check to see if WRES is all zero. This would indicate that ## ONLYSIM was used during the simulation in NONMEM. In this case ## many plots will fail. A fix to this is to replace the WRES ## column in SData with a column that is zero where the WRES in ## Data is zero and 1 otherwise. if(!any(value$WRES !=0)) { Data.wres <- Data(object,inclZeroWRES=TRUE)[,"WRES"] SData.wres <- rep(Data.wres,Snro/Dnro) SData.wres <- ifelse(SData.wres==0,0,1) value$WRES <- SData.wres } ## Add a column with a number indicating each simulated data set value[,"iter"] <- sort(rep(1:nsim(object),Dnro)) object@SData <- value return(object) } else { return(NULL) } }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/SData.R
setClassUnion("character_or_NULL",c("character","NULL")) setClassUnion("character_or_numeric",c("character","numeric")) setClassUnion("numeric_or_NULL",c("numeric","NULL")) setClassUnion("data.frame_or_NULL",c("data.frame","NULL")) setClassUnion("list_or_NULL",c("list","NULL")) #setClassUnion("lang or numeric",c("vector","numeric","list")) setClassUnion("logical_or_numeric",c("logical","numeric")) #' Class "xpose.prefs" #' #' An object of the "xpose.prefs" class holds information about all the #' variable and graphical preferences for a particular "xpose.data" object. #' #' #' @name xpose.prefs-class #' @aliases xpose.prefs-class character_or_numeric-class #' @docType class #' @section Objects from the Class: Objects can be created by calls of the form #' \code{new("xpose.prefs",...)} but this is usually not necessary since the #' "xpose.prefs" object is created at the same time as the "xpose.data" object. #' @author Niclas Jonsson & Andrew Hooker #' @seealso \code{\link{xvardef}}, \code{\link{xlabel}}, \code{\link{xsubset}}, #' \code{\link{Data}}, \code{\link{SData}}, \code{\link{xpose.data}}, #' \code{\link{read.nm.tables}}, \code{\link{xpose.data-class}}, #' \code{\link{xpose.gam}} #' @keywords classes #' @export setClass("xpose.prefs", #representation = slots = c(Xvardef = "list", Labels = "list", Graph.prefs = "list", Miss = "numeric", Cat.levels = "numeric", DV.Cat.levels = "numeric", Subset = "character_or_NULL", Gam.prefs = "list", Bootgam.prefs = "list" ), prototype=list( Xvardef = list( id = "ID", idlab = "ID", idv = "TIME", occ = "OCC", dv = "DV", pred = "PRED", ipred = "IPRED", iwres = "IWRES", wres = "WRES", cwres = "CWRES", res = "RES", parms = c("CL","V","V1","V2","V3","Q","Q1","Q2","Q3","KA", "ETA1","ETA2","ETA3","ETA4","ETA5","ETA6","ETA7", "ETA8","ETA9","ET10","ET11","ET12","ET13","ET14", "ET15","ET16","ET17","ET18","ET19","ET20"), covariates = c("GENO","SEX","RACE","DOSE","FLAG","DAY","PAT", "GEND","AGE","WT","HT","CRCL","CLCR"), ranpar = c("ETA1","ETA2","ETA3","ETA4","ETA5","ETA6","ETA7", "ETA8","ETA9","ET10","ET11","ET12","ET13","ET14","ET15", "ET16","ET17","ET18","ET19","ET20"), tvparms = c("TVCL","TVV","TVV1","TVV2","TVV3","TVQ","TVQ1", "TVQ2","TVQ3","TVKA") ), Labels = list( OCC = "Occasion", TIME = "Time", PRED = "Population predictions", IPRED = "Individual predictions", IPRE = "Individual predictions", WRES = "Weighted residuals", CWRES = "Conditional weighted residuals", IWRES = "Individual weighted residuals", IWRE = "Individual weighted residuals", DV = "Observations", RES = "Residuals", CL = "Clearance", V = "Volume", TAD = "Time after dose" ), Graph.prefs = list( type = "b" , pch = 1 , cex = 0.8 , lty = 1 , lwd = 1 , col = 4 , fill = "lightblue", grid = FALSE , aspect = "fill" , ## By arguments condvar = NULL, byordfun = "median" , ordby = NULL , shingnum = 6 , shingol = 0.5 , ## Abline settings abline = NULL , abllwd = 1 , ablcol = 1 , abllty = 1, ## Smooth settings smooth = NULL , smlwd = 2 , smcol = "red" , smlty = 1 , smspan = 2/3 , smdegr = 1, ## Lm settings lmline = NULL, lmlwd = 2, lmcol = 2, lmlty = 1, ## Superpose line settings suline = NULL, sulwd = 2, sucol = 3, sulty = 1, suspan = 2/3, sudegr = 1, ## Text label settings, ids = FALSE, idsmode= NULL, idsext = 0.05, ## In each end idscex = 0.7, idsdir = "both", ## Dilution stuff dilfrac = 0.7, diltype = NULL, dilci = 0.95, ## Prediction interval stuff PIuplty = 2, PIdolty = 2, PImelty = 1, PIuptyp = "l", PIdotyp = "l", PImetyp = "l", PIupcol = "black", PIdocol = "black", PImecol = "black", PIuplwd = 2, PIdolwd = 2, PImelwd = 2, PIupltyR = 1, PIdoltyR = 1, PImeltyR = 2, PIuptypR = "l", PIdotypR = "l", PImetypR = "l", PIupcolR = "blue", PIdocolR = "blue", PImecolR = "blue", PIuplwdR = 2, PIdolwdR = 2, PImelwdR = 2, PIupltyM = 1, PIdoltyM = 1, PImeltyM = 2, PIuptypM = "l", PIdotypM = "l", PImetypM = "l", PIupcolM = "darkgreen", PIdocolM = "darkgreen", PImecolM = "darkgreen", PIuplwdM = 0.5, PIdolwdM = 0.5, PImelwdM = 0.5, PIarcol = "lightgreen", PIlimits=c(0.025,0.975), ## Categorical x-variable bwhoriz = FALSE, bwratio = 1.5, bwvarwid = FALSE, bwdotpch = 16, bwdotcol = "black", bwdotcex = 1, bwreccol = "blue", bwrecfill= "transparent", bwreclty = 1, bwreclwd = 1, bwumbcol = "blue", bwumblty = 1, bwumblwd = 1, bwoutcol ="blue" , bwoutcex = 0.8, bwoutpch = 1, ##Histogram settings hicol = 5,#"blue", hiborder = "black", hilty = 1, hilwd = 1, hidlty = 2, hidlwd = 2, hidcol = 1 ), Miss = -99, Cat.levels = 4, DV.Cat.levels = 7, Subset = NULL, Gam.prefs = list( onlyfirst=TRUE, wts=FALSE, start.mod=NULL, steppit=TRUE, disp = NULL, nmods=3, smoother1=0, smoother2=1, smoother3="ns", smoother4="ns", arg1=NULL, arg2=NULL, arg3="df=2", arg4="df=3", excl1=NULL, excl2=NULL, excl3=NULL, excl4=NULL, extra=NULL, plot.ids=TRUE, medianNorm=TRUE ), Bootgam.prefs = list(n = 100, algo = "fluct.ratio", conv.value = as.numeric(1.04), check.interval = as.numeric(20), start.check = as.numeric(50), liif = as.numeric(0.2), ljif.conv = as.numeric(25), seed = NULL, start.mod = NULL, excluded.ids = NULL ) ) ) #' Class xpose.data #' #' The xpose.data class is the fundamental data object in Xpose 4. It contains #' the data and preferences used in the creation of the Xpose plots and #' analyses. #' #' #' @name xpose.data-class #' @aliases xpose.data-class numeric_or_NULL-class data.frame_or_NULL-class #' @docType class #' @section Objects from the Class: Objects are most easily created by the #' \code{xpose.data} function, which reads the appropriate NONMEM table files #' and populates the slots of the object. #' @author Niclas Jonsson and Andrew Hooker #' @seealso \code{\link{xpose.data}}, \code{\link{Data}}, \code{\link{SData}} #' \code{\link{read.nm.tables}}, \code{\link{xpose.prefs-class}} #' @keywords classes #' @export setClass("xpose.data", slots=c(Data = "data.frame_or_NULL", SData = "data.frame_or_NULL", Data.firstonly = "data.frame_or_NULL", SData.firstonly = "data.frame_or_NULL", Runno = "character_or_numeric", Nsim = "numeric_or_NULL", Doc = "character_or_NULL", Prefs = "xpose.prefs" ), prototype=list(Data = NULL, SData = NULL, Data.firstonly = NULL, SData.firstonly = NULL, Nsim = NULL, Runno = NULL, Doc = NULL)#, #validity = test.xpose.data ) #' Class for creating multiple plots in xpose #' #' @slot plotList A list of lattice plots #' @slot plotTitle The plot title #' @slot prompt Should prompts be used #' @slot new.first.window Create a new first window? #' @slot max.plots.per.page How many plots per page? #' @slot title The title #' @slot mirror Are there mirror plots to create #' @slot bql.layout Should we use bql.layout #' @aliases list_or_NULL-class logical_or_numeric-class character_or_NULL-class #' #' @export setClass("xpose.multiple.plot",#where=.GlobalEnv, slots=c(plotList = "list_or_NULL", plotTitle = "character_or_NULL", prompt = "logical", new.first.window = "logical", max.plots.per.page = "numeric", title = "list", ##title.x = "xptmp", ##title.y = "lang or numeric", ##title.just = "vector", ##title.gp = "lang or numeric", mirror = "logical_or_numeric", bql.layout = "logical" ), prototype=list(plotList = NULL, plotTitle= NULL, prompt = FALSE, new.first.window = FALSE, max.plots.per.page = 4, title = list( title.x = unit(0.5, "npc"), title.y = unit(0.5, "npc"), title.gp= gpar(cex=1.2,fontface="bold"),#,font=2), title.just = c("center","center") ), ##title.x = unit(0.5, "npc"), ##title.y = c(unit(0.5, "npc")), ##title.just = c("center","center"), ##title.gp = list(cex=1.2,fontface="bold",font=2), mirror = FALSE, bql.layout = FALSE ) ) # Method for printing multiple xpose plots # @export # setMethod("print",signature(x="xpose.multiple.plot"),print.xpose.multiple.plot) # Method for showing multiple xpose plots # setMethod("show","xpose.multiple.plot",function(object) print(x=object))
/scratch/gouwar.j/cran-all/cranData/xpose4/R/aaa-classes.R
#' Absolute conditional weighted residuals vs covariates for Xpose 4 #' #' This creates a stack of box and whisker plot of absolute population #' conditional weighted residuals (|CWRES|) vs covariates, and is a specific #' function in Xpose 4. It is a wrapper encapsulating arguments to the #' code\link{xpose.plot.bw} function. Most of the options take their default #' values from xpose.data object but may be overridden by supplying them as #' arguments. #' #' Each of the covariates in the Xpose data object, as specified in #' \code{object@Prefs@Xvardef$Covariates}, is evaluated in turn, creating a #' stack of plots. #' #' Conditional weighted residuals (CWRES) require some extra steps to #' calculate. See \code{\link{compute.cwres}} for details. #' #' A wide array of extra options controlling box-and-whisker plots are #' available. See \code{\link{xpose.plot.bw}} for details. #' #' @param object An xpose.data object. #' @param xlb A string giving the label for the x-axis. \code{NULL} if none. #' @param main The title of the plot. If \code{"Default"} then a default title #' is plotted. Otherwise the value should be a string like \code{"my title"} or #' \code{NULL} for no plot title. #' @param \dots Other arguments passed to \code{\link{xpose.plot.bw}}. #' @return Returns a stack of box-and-whisker plots of |CWRES| vs covariates. #' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins #' @seealso \code{\link{xpose.plot.bw}}, \code{\link{xpose.panel.bw}}, #' \code{\link{compute.cwres}}, \code{\link[lattice]{bwplot}}, #' \code{\link{xpose.prefs-class}}, \code{\link{xpose.data-class}} #' @keywords methods #' @examples #' ## Here we load the example xpose database #' xpdb <- simpraz.xpdb #' #' absval.cwres.vs.cov.bw(xpdb) #' #' #' @export #' @family specific functions absval.cwres.vs.cov.bw <- function(object, xlb = "|CWRES|", main="Default", ...) { if (is.null(xvardef("covariates", object))) { return(cat("Covariates are not properly set in the database!\n")) } if(is.null(xvardef("cwres",object))) { return(cat("There are no CWRES defined in the database!\n")) } ## create list for plots number.of.plots <- 0 for (i in xvardef("covariates", object)) { number.of.plots <- number.of.plots + 1 } plotList <- vector("list",number.of.plots) ## loop through covariates plot.num <- 0 # initialize plot number for (i in xvardef("covariates", object)) { xplot <- xpose.plot.bw(xvardef("cwres",object), i, object, main=NULL, xlb=xlb, binvar = i, funx="abs", pass.plot.list = TRUE, ...) plot.num <- plot.num+1 plotList[[plot.num]] <- xplot } default.plot.title <- paste("|",xlabel(xvardef("cwres",object),object),"| vs ", "Covariates", sep="") plotTitle <- xpose.multiple.plot.title(object=object, plot.text = default.plot.title, main=main, ...) obj <- xpose.multiple.plot(plotList,plotTitle,...) return(obj) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.cwres.vs.cov.bw.R
# Xpose 4 # An R-based population pharmacokinetic/ # pharmacodynamic model building aid for NONMEM. # Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson. # Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins, # Mats O. Karlsson and E. Niclas Jonsson. # Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and # E. Niclas Jonsson. # This file is a part of Xpose 4. # Xpose 4 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. A copy can be cound in the R installation # directory under \share\licenses. If not, see http://www.gnu.org/licenses/. #' Absolute population conditional weighted residuals vs population predictions #' for Xpose 4 #' #' This is a plot of absolute population conditional weighted residuals #' (|CWRES|) vs population predictions (PRED), a specific function in Xpose 4. #' It is a wrapper encapsulating arguments to the \code{xpose.plot.default} #' function. Most of the options take their default values from xpose.data #' object but may be overridden by supplying them as arguments. #' #' Conditional weighted residuals (CWRES) require some extra steps to #' calculate. See \code{\link{compute.cwres}} for details. #' #' A wide array of extra options controlling xyplots are available. See #' \code{\link{xpose.plot.default}} for details. #' #' @param object An xpose.data object. #' @param idsdir Direction for displaying point labels. The default is "up", #' since we are displaying absolute values. #' @param type Type of plot. The default is points only ("p"), but lines ("l") #' and both ("b") are also available. #' @param smooth Logical value indicating whether an x-y smooth should be #' superimposed. The default is TRUE. #' @param \dots Other arguments passed to \code{link{xpose.plot.default}}. #' @return Returns an xyplot of |CWRES| vs PRED. #' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins #' @seealso \code{\link{xpose.plot.default}}, #' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}}, #' \code{\link{xpose.prefs-class}}, \code{\link{compute.cwres}}, #' \code{\link{xpose.data-class}} #' @keywords methods #' @examples #' #' \dontrun{ #' ## We expect to find the required NONMEM run and table files for run #' ## 5 in the current working directory #' xpdb5 <- xpose.data(5) #' } #' #' ## Here we load the example xpose database #' data(simpraz.xpdb) #' xpdb <- simpraz.xpdb #' #' ## A vanilla plot #' absval.cwres.vs.pred(xpdb) #' #' ## A conditioning plot #' absval.cwres.vs.pred(xpdb, by="HCTZ") #' #' ## Custom heading and axis labels #' absval.cwres.vs.pred(xpdb, main="My conditioning plot", ylb="|CWRES|", xlb="PRED") #' #' ## Custom colours and symbols, no IDs #' absval.cwres.vs.pred(xpdb, cex=0.6, pch=3, col=1, ids=FALSE) #' #' #' @export absval.cwres.vs.pred #' @family specific functions "absval.cwres.vs.pred" <- function(object, idsdir="up", type="p", smooth=TRUE, ...) { if(is.null(xvardef("cwres",object)) || is.null(xvardef("pred",object))) { cat("The required (CWRES and PRED) variables are not set in the database!\n") return() } xplot <- xpose.plot.default(xvardef("pred",object), xvardef("cwres",object), object, funy="abs", idsdir=idsdir, type=type, smooth=smooth, ...) return(xplot) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.cwres.vs.pred.R
# Xpose 4 # An R-based population pharmacokinetic/ # pharmacodynamic model building aid for NONMEM. # Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson. # Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins, # Mats O. Karlsson and E. Niclas Jonsson. # Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and # E. Niclas Jonsson. # This file is a part of Xpose 4. # Xpose 4 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. A copy can be cound in the R installation # directory under \share\licenses. If not, see http://www.gnu.org/licenses/. #' Absolute value of the conditional weighted residuals vs. population #' predictions, conditioned on covariates, for Xpose 4 #' #' This is a plot of absolute population conditional weighted residuals #' (|CWRES|) vs population predictions (PRED) conditioned by covariates, a #' specific function in Xpose 4. It is a wrapper encapsulating arguments to the #' \code{xpose.plot.default} function. Most of the options take their default #' values from xpose.data object but may be overridden by supplying them as #' arguments. #' #' Each of the covariates in the Xpose data object, as specified in #' \code{object@Prefs@Xvardef$Covariates}, is evaluated in turn, creating a #' stack of plots. #' #' The \code{main} argument is not supported owing to the multiple plots #' generated by the function. #' #' Conditional weighted residuals (CWRES) require some extra steps to #' calculate. See \code{\link{compute.cwres}} for details. #' #' A wide array of extra options controlling xyplots are available. See #' \code{\link{xpose.plot.default}} for details. #' #' @inheritParams dv.vs.ipred.by.cov #' @param object An xpose.data object. #' @param ylb A string giving the label for the y-axis. \code{NULL} if none. #' @param idsdir Direction for displaying point labels. The default is "up", #' since we are displaying absolute values. #' @param type Type of plot. The default is points only ("p"), but lines ("l") #' and both ("b") are also available. #' @param smooth Logical value indicating whether an x-y smooth should be #' superimposed. The default is TRUE. #' @param main The title of the plot. If \code{"Default"} then a default title #' is plotted. Otherwise the value should be a string like \code{"my title"} or #' \code{NULL} for no plot title. #' @param \dots Other arguments passed to \code{link{xpose.plot.default}}. #' @return Returns a stack of xyplots of |CWRES| vs PRED, conditioned on #' covariates. #' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins #' @seealso \code{\link{absval.cwres.vs.pred}}, #' \code{\link{xpose.plot.default}}, \code{\link{xpose.panel.default}}, #' \code{\link[lattice]{xyplot}}, \code{\link{xpose.prefs-class}}, #' \code{\link{compute.cwres}}, \code{\link{xpose.data-class}} #' @keywords methods #' @examples #' #' absval.cwres.vs.pred.by.cov(simpraz.xpdb, covs=c("HCTZ","WT"), max.plots.per.page=2) #' #' @export #' @family specific functions absval.cwres.vs.pred.by.cov <- function(object, covs="Default", ylb = "|CWRES|", type="p", smooth=TRUE, idsdir="up", main="Default", ...) { if(is.null(check.vars(c("pred","cwres"), object,silent=FALSE))) { return() } # handle covs argument if(all(covs == "Default")) { if(is.null(check.vars(c("covariates"),object))) return(NULL) covs <- xvardef("covariates", object) } else { if(is.null(check.vars(covs,object))) return(NULL) } ## create plot list plotList <- vector("list",length(covs)) plot.num <- 0 # initialize plot number for (i in covs) { xplot <- xpose.plot.default(xvardef("pred",object), xvardef("cwres",object), object, main=NULL, funy="abs", ylb=ylb, type=type, smooth=smooth, by=i, idsdir=idsdir, pass.plot.list = TRUE, ...) plot.num <- plot.num+1 plotList[[plot.num]] <- xplot } default.plot.title <- paste("|",xlabel(xvardef("cwres",object),object), "| \nvs ", xlabel(xvardef("pred",object),object), sep="") plotTitle <- xpose.multiple.plot.title(object=object, plot.text = default.plot.title, main=main, ...) obj <- xpose.multiple.plot(plotList,plotTitle,...) return(obj) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.cwres.vs.pred.by.cov.R
#' Model comparison plots, of absolute differences in goodness-of-fit #' predictors against covariates, for Xpose 4 #' #' These functions plot absolute differences in PRED, IPRED, WRES, CWRES and #' IWRES against covariates for two specified model fits. #' #' Conditional weighted residuals (CWRES) may require some extra steps to #' calculate. See \code{\link{compute.cwres}} for details. #' #' A wide array of extra options controlling xyplots are available. See #' \code{\link{xpose.plot.default}} for details. #' #' @param object An xpose.data object. #' @param object.ref An xpose.data object. If not supplied, the user will be #' prompted. #' @param type 1-character string giving the type of plot desired. The #' following values are possible, for details, see 'plot': '"p"' for points, #' '"l"' for lines, '"o"' for over-plotted points and lines, '"b"', '"c"') for #' (empty if '"c"') points joined by lines, '"s"' and '"S"' for stair steps and #' '"h"' for histogram-like vertical lines. Finally, '"n"' does not produce #' any points or lines. #' @param ylb A string giving the label for the y-axis. \code{NULL} if none. #' @param main The title of the plot. If \code{"Default"} then a default title #' is plotted. Otherwise the value should be a string like \code{"my title"} or #' \code{NULL} for no plot title. #' @param \dots Other arguments passed to \code{link{xpose.plot.default}}. #' @return Returns a stack of plots comprising comparisons of PRED, IPRED, WRES #' (or CWRES) and IWRES for the two specified runs. #' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins #' @seealso \code{\link{xpose.plot.default}}, #' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}}, #' \code{\link{compute.cwres}}, \code{\link{xpose.prefs-class}}, #' \code{\link{xpose.data-class}} #' @keywords methods #' @examples #' #' \dontrun{ #' ## We expect to find the required NONMEM run and table files for runs #' ## 5 and 6 in the current working directory #' xpdb5 <- xpose.data(5) #' xpdb6 <- xpose.data(6) #' #' ## A basic dWRES plot, without prompts #' absval.dwres.vs.cov.model.comp(xpdb5, xpdb6) #' #' ## Custom colours and symbols, no user IDs #' absval.dpred.vs.cov.model.comp(xpdb5, xpdb6, cex=0.6, pch=8, col=1, ids=NULL) #' } #' #' #' @name absval_delta_vs_cov_model_comp #' @family specific functions NULL #' @describeIn absval_delta_vs_cov_model_comp The absolute differences in individual predictions #' against covariates for two specified model fits. #' @export #' #' #' #' "absval.dcwres.vs.cov.model.comp" <- function(object, object.ref = NULL, type = NULL, ylb=expression(paste("|", Delta, "CWRES|")), main="Default", #subset= xsubset(object), #ref.default = ".ref.db", ...) { if (is.null(object.ref)) { ref.list <- get.refrunno() if(exists(".ref.db")){ object.ref <- eval(parse(text=".ref.db")) } else { return() } if(any(is.null(ref.list))) return() } #ref.db <- ref.list$ref.db #ref.runno <- ref.list$ref.runno if(dim(object@Data)[1] != dim(object.ref@Data)[1]) { cat("The current database and the reference database do not have\n") cat("the same number of lines!\n") return() } if ((is.null(xvardef("idlab",object))) || (is.null(xvardef("cwres",object)))) { cat("The required variables (ID label, CWRES) are not set in the database!\n") return() } if(any(is.null(xvardef("covariates",object)))) { return(cat("No covariates found in the current database!\n")) } object@Data$dCWRES <- abs(object@Data[,xvardef("cwres", object)] - object.ref@Data[,xvardef("cwres", object.ref)]) #object@Data[,xvardef("pred", object)] <- abs(object@Data[,xvardef("pred", object)]) ## create list for plots number.of.plots <- 0 for (i in xvardef("covariates", object)) { number.of.plots <- number.of.plots + 1 } plotList <- vector("list",number.of.plots) plot.num <- 0 # initialize plot number for (i in xvardef("covariates", object)) { ## |dPRED| vs covariates ##xlb <- i ##ylb <- paste("|dCWRES| (Run ", object@Runno, " - Run ",object.ref@Runno,")",sep="") ##main <- paste(ylb, " vs ", xlb, sep="") if (is.null(type)) { if (!is.factor(object@Data[,i])) { type <- "p" } else { type = object@[email protected]$type } } xplot <- xpose.plot.default(i, "dCWRES", object, ##xlb = xlb, ylb = ylb, #main = NULL, type = type, pass.plot.list = TRUE, #subset=subset, ...) plot.num <- plot.num+1 plotList[[plot.num]] <- xplot } ## |dPRED| vs covariates default.plot.title <- paste("|CWRES_(Run", object@Runno, ") - CWRES_(Run",object.ref@Runno, ")| vs. Covariates",sep="") plotTitle <- xpose.multiple.plot.title(object=object, plot.text = default.plot.title, no.runno=TRUE, main=main, ...) obj <- xpose.multiple.plot(plotList,plotTitle,...) return(obj) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.dcwres.vs.cov.model.comp.R
#' @describeIn absval_delta_vs_cov_model_comp The absolute differences in individual predictions #' against covariates for two specified model fits. #' @export "absval.dipred.vs.cov.model.comp" <- function(object, object.ref = NULL, type = NULL, ylb=expression(paste("|", Delta, "IPRED|")), main="Default", #ref.default = ".ref.db", ...) { if (is.null(object.ref)) { ref.list <- get.refrunno() if(exists(".ref.db")){ object.ref <- eval(parse(text=".ref.db")) } else { return() } if(any(is.null(ref.list))) return() } #ref.db <- ref.list$ref.db #ref.runno <- ref.list$ref.runno if(dim(object@Data)[1] != dim(object.ref@Data)[1]) { cat("The current database and the reference database do not have\n") cat("the same number of lines!\n") return() } if ((is.null(xvardef("idlab",object))) || (is.null(xvardef("ipred",object)))) { cat("The required variables (ID label, IPRED) are not set in the database!\n") return() } if(any(is.null(xvardef("covariates",object)))) { return(cat("No covariates found in the current database!\n")) } object@Data$dIPRED <- abs(object@Data[,xvardef("ipred", object)] - object.ref@Data[,xvardef("ipred", object.ref)]) ##object@Data[,xvardef("pred", object)] <- abs(object@Data[,xvardef("pred", object)]) ## create list for plots number.of.plots <- 0 for (i in xvardef("covariates", object)) { number.of.plots <- number.of.plots + 1 } plotList <- vector("list",number.of.plots) plot.num <- 0 # initialize plot number for (i in xvardef("covariates", object)) { if (is.null(type)) { if (!is.factor(object@Data[,i])) { type <- "p" } else { type = object@[email protected]$type } } xplot <- xpose.plot.default(i, "dIPRED", object, #xlb = xlb, ylb = ylb, #main = main, type = type, pass.plot.list=TRUE,, main=NULL, ...) plot.num <- plot.num+1 plotList[[plot.num]] <- xplot } ## |dPRED| vs covariates default.plot.title <- paste("|IPRED_(Run", object@Runno, ") - IPRED_(Run",object.ref@Runno, ")| vs. Covariates",sep="") plotTitle <- xpose.multiple.plot.title(object=object, plot.text = default.plot.title, no.runno=TRUE, main=main, ...) obj <- xpose.multiple.plot(plotList,plotTitle,...) return(obj) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.dipred.vs.cov.model.comp.R
# Xpose 4 # An R-based population pharmacokinetic/ # pharmacodynamic model building aid for NONMEM. # Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson. # Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins, # Mats O. Karlsson and E. Niclas Jonsson. # Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and # E. Niclas Jonsson. # This file is a part of Xpose 4. # Xpose 4 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. A copy can be cound in the R installation # directory under \share\licenses. If not, see http://www.gnu.org/licenses/. #' @describeIn absval_delta_vs_cov_model_comp The absolute differences in individual weighted #' residuals #' against covariates for two specified model fits. #' @export "absval.diwres.vs.cov.model.comp" <- function(object, object.ref = NULL, type = NULL, ylb=expression(paste("|", Delta, "IWRES|")), main="Default", #ref.default = ".ref.db", ...) { if (is.null(object.ref)) { ref.list <- get.refrunno() if(exists(".ref.db")){ object.ref <- eval(parse(text=".ref.db")) } else { return() } if(any(is.null(ref.list))) return() } #ref.db <- ref.list$ref.db #ref.runno <- ref.list$ref.runno if(dim(object@Data)[1] != dim(object.ref@Data)[1]) { cat("The current database and the reference database do not have\n") cat("the same number of lines!\n") return() } if ((is.null(xvardef("idlab",object))) || (is.null(xvardef("iwres",object)))) { cat("The required variables (ID label, IWRES) are not set in the database!\n") return() } if(any(is.null(xvardef("covariates",object)))) { return(cat("No covariates found in the current database!\n")) } object@Data$dIWRES <- abs(object@Data[,xvardef("iwres", object)] - object.ref@Data[,xvardef("iwres", object.ref)]) ##object@Data[,xvardef("pred", object)] <- abs(object@Data[,xvardef("pred", object)]) ## create list for plots number.of.plots <- 0 for (i in xvardef("covariates", object)) { number.of.plots <- number.of.plots + 1 } plotList <- vector("list",number.of.plots) plot.num <- 0 # initialize plot number for (i in xvardef("covariates", object)) { if (is.null(type)) { if (!is.factor(object@Data[,i])) { type <- "p" } else { type = object@[email protected]$type } } xplot <- xpose.plot.default(i, "dIWRES", object, #xlb = xlb, ylb = ylb, #main = main, type = type, pass.plot.list=TRUE,, main=NULL, ...) plot.num <- plot.num+1 plotList[[plot.num]] <- xplot } ## |dPRED| vs covariates default.plot.title <- paste("|IWRES_(Run", object@Runno, ") - IWRES_(Run",object.ref@Runno, ")| vs. Covariates",sep="") plotTitle <- xpose.multiple.plot.title(object=object, plot.text = default.plot.title, no.runno=TRUE, main=main, ...) obj <- xpose.multiple.plot(plotList,plotTitle,...) return(obj) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.diwres.vs.cov.model.comp.R
# Xpose 4 # An R-based population pharmacokinetic/ # pharmacodynamic model building aid for NONMEM. # Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson. # Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins, # Mats O. Karlsson and E. Niclas Jonsson. # Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and # E. Niclas Jonsson. # This file is a part of Xpose 4. # Xpose 4 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. A copy can be cound in the R installation # directory under \share\licenses. If not, see http://www.gnu.org/licenses/. #' @describeIn absval_delta_vs_cov_model_comp The absolute differences in population predictions #' against covariates for two specified model fits. #' @export "absval.dpred.vs.cov.model.comp" <- function(object, object.ref = NULL, type = NULL, ylb=expression(paste("|", Delta, "PRED|")), main="Default", #ref.default = ".ref.db", ...) { if (is.null(object.ref)) { ref.list <- get.refrunno() if(exists(".ref.db")){ object.ref <- eval(parse(text=".ref.db")) } else { return() } if(any(is.null(ref.list))) return() } #ref.db <- ref.list$ref.db #ref.runno <- ref.list$ref.runno if(dim(object@Data)[1] != dim(object.ref@Data)[1]) { cat("The current database and the reference database do not have\n") cat("the same number of lines!\n") return() } if ((is.null(xvardef("idlab",object))) || (is.null(xvardef("pred",object)))) { cat("The required variables (ID label, PRED) are not set in the database!\n") return() } if(any(is.null(xvardef("covariates",object)))) { return(cat("No covariates found in the current database!\n")) } object@Data$dPRED <- abs(object@Data[,xvardef("pred", object)] - object.ref@Data[,xvardef("pred", object.ref)]) #object@Data[,xvardef("pred", object)] <- abs(object@Data[,xvardef("pred", object)]) ## create list for plots number.of.plots <- 0 for (i in xvardef("covariates", object)) { number.of.plots <- number.of.plots + 1 } plotList <- vector("list",number.of.plots) plot.num <- 0 # initialize plot number for (i in xvardef("covariates", object)) { if (is.null(type)) { if (!is.factor(object@Data[,i])) { type <- "p" } else { type = object@[email protected]$type } } xplot <- xpose.plot.default(i, "dPRED", object, #xlb = xlb, ylb = ylb, #main = main, type = type, pass.plot.list=TRUE,, main=NULL, ...) plot.num <- plot.num+1 plotList[[plot.num]] <- xplot } ## |dPRED| vs covariates default.plot.title <- paste("|PRED_(Run", object@Runno, ") - PRED_(Run",object.ref@Runno, ")| vs. Covariates",sep="") plotTitle <- xpose.multiple.plot.title(object=object, plot.text = default.plot.title, no.runno=TRUE, main=main, ...) obj <- xpose.multiple.plot(plotList,plotTitle,...) return(obj) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.dpred.vs.cov.model.comp.R
# Xpose 4 # An R-based population pharmacokinetic/ # pharmacodynamic model building aid for NONMEM. # Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson. # Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins, # Mats O. Karlsson and E. Niclas Jonsson. # Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and # E. Niclas Jonsson. # This file is a part of Xpose 4. # Xpose 4 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. A copy can be cound in the R installation # directory under \share\licenses. If not, see http://www.gnu.org/licenses/. #' @describeIn absval_delta_vs_cov_model_comp The absolute differences in #' population weighted residuals #' against covariates for two specified model fits. #' @export "absval.dwres.vs.cov.model.comp" <- function(object, object.ref = NULL, type = NULL, ylb=expression(paste("|", Delta, "WRES|")), main="Default", #ref.default = ".ref.db", ...) { if (is.null(object.ref)) { ref.list <- get.refrunno() if(exists(".ref.db")){ object.ref <- eval(parse(text=".ref.db")) } else { return() } if(any(is.null(ref.list))) return() } #ref.db <- ref.list$ref.db #ref.runno <- ref.list$ref.runno if(dim(object@Data)[1] != dim(object.ref@Data)[1]) { cat("The current database and the reference database do not have\n") cat("the same number of lines!\n") return() } if ((is.null(xvardef("idlab",object))) || (is.null(xvardef("wres",object)))) { cat("The required variables (ID label, WRES) are not set in the database!\n") return() } if(any(is.null(xvardef("covariates",object)))) { return(cat("No covariates found in the current database!\n")) } object@Data$dWRES <- abs(object@Data[,xvardef("wres", object)] - object.ref@Data[,xvardef("wres", object.ref)]) ##object@Data[,xvardef("pred", object)] <- abs(object@Data[,xvardef("pred", object)]) ## create list for plots number.of.plots <- 0 for (i in xvardef("covariates", object)) { number.of.plots <- number.of.plots + 1 } plotList <- vector("list",number.of.plots) plot.num <- 0 # initialize plot number for (i in xvardef("covariates", object)) { if (is.null(type)) { if (!is.factor(object@Data[,i])) { type <- "p" } else { type = object@[email protected]$type } } xplot <- xpose.plot.default(i, "dWRES", object, #xlb = xlb, ylb = ylb, #main = main, type = type, pass.plot.list=TRUE,, main=NULL, ...) plot.num <- plot.num+1 plotList[[plot.num]] <- xplot } ## |dPRED| vs covariates default.plot.title <- paste("|WRES_(Run", object@Runno, ") - WRES_(Run",object.ref@Runno, ")| vs. Covariates",sep="") plotTitle <- xpose.multiple.plot.title(object=object, plot.text = default.plot.title, no.runno=TRUE, main=main, ...) xpose.multiple.plot.default(plotList,plotTitle=default.plot.title,...) invisible() }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.dwres.vs.cov.model.comp.R
#' Absolute population weighted residuals vs population predictions, and #' absolute individual weighted residuals vs individual predictions, for Xpose #' 4 #' #' This is a matrix plot of absolute population weighted residuals (|CWRES|) vs #' population predictions (PRED) and absolute individual weighted residuals #' (|IWRES|) vs individual predictions (IPRED), a specific function in Xpose 4. #' It is a wrapper encapsulating arguments to the \code{absval.cwres.vs.pred} #' and \code{absval.iwres.vs.ipred} functions. #' #' The plots created by the \code{absval.wres.vs.pred} and #' \code{absval.iwres.vs.ipred} functions are presented side by side for #' comparison. #' #' A wide array of extra options controlling xyplots are available. See #' \code{\link{xpose.plot.default}} for details. #' #' @aliases absval.iwres.wres.vs.ipred.pred absval.iwres.cwres.vs.ipred.pred #' @param object An xpose.data object. #' @param main The title of the plot. If \code{"Default"} then a default title #' is plotted. Otherwise the value should be a string like \code{"my title"} or #' \code{NULL} for no plot title. #' @param \dots Other arguments passed to \code{link{xpose.plot.default}}. #' @return Returns a compound plot. #' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins #' @seealso \code{\link{absval.wres.vs.pred}}, #' \code{\link{absval.iwres.vs.ipred}}, \code{\link{xpose.plot.default}}, #' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}}, #' \code{\link{xpose.prefs-class}}, \code{\link{xpose.data-class}} #' @examples #' #' ## Here we load the example xpose database #' xpdb <- simpraz.xpdb #' #' ## A vanilla plot #' absval.iwres.wres.vs.ipred.pred(xpdb) #' absval.iwres.cwres.vs.ipred.pred(xpdb) #' #' ## Custom colours and symbols #' absval.iwres.cwres.vs.ipred.pred(xpdb, cex=0.6, pch=8, col=1) #' #' @export #' @family specific functions absval.iwres.cwres.vs.ipred.pred <- function(object, ##aspect="fill", main="Default", ...) { if(is.null(check.vars(c("pred","cwres","iwres","ipred"), object,silent=FALSE))) { return() } num.of.plots <- 2 plotList <- vector("list",num.of.plots) plot1 <- absval.cwres.vs.pred(object,main=NULL, ##aspect=aspect, pass.plot.list=TRUE, ...) plot2 <- absval.iwres.vs.ipred(object,main=NULL, ##aspect=aspect, pass.plot.list=TRUE, ...) plotList[[1]] <- plot1 plotList[[2]] <- plot2 default.plot.title <- "(Conditional) Weighted residuals vs. Predictions" plotTitle <- xpose.multiple.plot.title(object=object, plot.text = default.plot.title, main=main, ...) obj <- xpose.multiple.plot(plotList,plotTitle,...) return(obj) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.iwres.cwres.vs.ipred.pred.R
#' box and whisker plots of the absolute value of the #' individual weighted residuals vs. covariates #' #' #' @inheritParams xpose.plot.default #' #' @return An xpose.multiple.plot object #' @export #' #' #' @family specific functions absval.iwres.vs.cov.bw <- function(object, xlb = "|iWRES|", #ylb = NULL, #onlyfirst=FALSE, #inclZeroWRES=FALSE, #subset=xsubset(object), #seed = NULL, #bins = 10, #samp = NULL, #prompt = TRUE, main="Default", ...) { if(any(is.null(xvardef("covariates",object)))) { return(cat("There are no covariates defined in the database!\n")) } ## create list for plots number.of.plots <- 0 for (i in xvardef("covariates", object)) { number.of.plots <- number.of.plots + 1 } plotList <- vector("list",number.of.plots) plot.num <- 0 # initialize plot number for (i in xvardef("covariates", object)) { xplot <- xpose.plot.bw(xvardef("iwres",object), i, xlb = xlb, object, main = NULL, ids=FALSE, binvar = i, funx="abs", pass.plot.list = TRUE, ...) plot.num <- plot.num+1 plotList[[plot.num]] <- xplot } default.plot.title <- paste("|",xlabel(xvardef("iwres",object),object), "| vs ", "Covariates", sep="") plotTitle <- xpose.multiple.plot.title(object=object, plot.text = default.plot.title, main=main, ...) obj <- xpose.multiple.plot(plotList,plotTitle,...) return(obj) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.iwres.vs.cov.bw.R
#' absolute value of the #' individual weighted residuals vs. the independent variable #' #' #' @inheritParams xpose.plot.default #' @inheritParams xpose.panel.default #' #' @return A lattice object #' @export #' #' #' @family specific functions absval.iwres.vs.idv <- function(object, ylb = "|iWRES|", smooth = TRUE, idsdir = "up", type = "p", ...) { if(is.null(check.vars(c("idv","iwres"), object,silent=FALSE))) { return() } xplot <- xpose.plot.default(xvardef("idv",object), xvardef("iwres",object), object, ylb=ylb, funy="abs", idsdir=idsdir, smooth=smooth, type = type, ...) return(xplot) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.iwres.vs.idv.R
# Xpose 4 # An R-based population pharmacokinetic/ # pharmacodynamic model building aid for NONMEM. # Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson. # Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins, # Mats O. Karlsson and E. Niclas Jonsson. # Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and # E. Niclas Jonsson. # This file is a part of Xpose 4. # Xpose 4 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. A copy can be cound in the R installation # directory under \share\licenses. If not, see http://www.gnu.org/licenses/. #' Absolute individual weighted residuals vs individual predictions for Xpose 4 #' #' This is a plot of absolute individual weighted residuals (|IWRES|) vs #' individual predictions (IPRED), a specific function in Xpose 4. It is a #' wrapper encapsulating arguments to the \code{xpose.plot.default} function. #' Most of the options take their default values from xpose.data object but may #' be overridden by supplying them as arguments. #' #' A wide array of extra options controlling xyplots are available. See #' \code{\link{xpose.plot.default}} for details. #' #' @param object An xpose.data object. #' @param ylb A string giving the label for the y-axis. \code{NULL} if none. #' @param idsdir Direction for displaying point labels. The default is "up", #' since we are displaying absolute values. #' @param type Type of plot. The default is points only ("p"), but lines ("l") #' and both ("b") are also available. #' @param ids Should id values be displayed? #' @param smooth Logical value indicating whether an x-y smooth should be #' superimposed. The default is TRUE. #' @param \dots Other arguments passed to \code{link{xpose.plot.default}}. #' @return Returns an xyplot of |IWRES| vs IPRED. #' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins #' @seealso \code{\link{xpose.plot.default}}, #' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}}, #' \code{\link{xpose.prefs-class}}, \code{\link{xpose.data-class}}, #' \code{\link{runsum}} #' @keywords methods #' @examples #' #' ## Here we load the example xpose database #' data(simpraz.xpdb) #' xpdb <- simpraz.xpdb #' #' ## A vanilla plot #' absval.iwres.vs.ipred(xpdb) #' #' ## A conditioning plot #' absval.iwres.vs.ipred(xpdb, by="HCTZ") #' #' ## Custom heading and axis labels #' absval.iwres.vs.ipred(xpdb, main="My conditioning plot", ylb="|IWRES|", xlb="IPRED") #' #' ## Custom colours and symbols, no IDs #' absval.iwres.vs.ipred(xpdb, cex=0.6, pch=3, col=1, ids=FALSE) #' #' #' @export absval.iwres.vs.ipred #' @family specific functions "absval.iwres.vs.ipred" <- function(object, ylb = "|iWRES|", type="p", ids = FALSE, idsdir = "up", smooth = TRUE, ...) { if(is.null(xvardef("iwres",object)) || is.null(xvardef("ipred",object))) { cat("The required variables are not set in the data base\n") return() } xplot <- xpose.plot.default(xvardef("ipred",object), xvardef("iwres",object), ylb = ylb, funy = "abs", type= type, ids = ids, idsdir=idsdir, smooth=smooth, object, ...) return(xplot) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.iwres.vs.ipred.R
# Xpose 4 # An R-based population pharmacokinetic/ # pharmacodynamic model building aid for NONMEM. # Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson. # Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins, # Mats O. Karlsson and E. Niclas Jonsson. # Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and # E. Niclas Jonsson. # This file is a part of Xpose 4. # Xpose 4 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. A copy can be cound in the R installation # directory under \share\licenses. If not, see http://www.gnu.org/licenses/. #' Absolute individual weighted residuals vs individual predictions, #' conditioned on covariates, for Xpose 4 #' #' This is a plot of absolute individual weighted residuals (|IWRES|) vs #' individual predictions (IPRED) conditioned by covariates, a specific #' function in Xpose 4. It is a wrapper encapsulating arguments to the #' \code{xpose.plot.default} function. Most of the options take their default #' values from xpose.data object but may be overridden by supplying them as #' arguments. #' #' Each of the covariates in the Xpose data object, as specified in #' \code{object@Prefs@Xvardef$Covariates}, is evaluated in turn, creating a #' stack of plots. #' #' A wide array of extra options controlling xyplots are available. See #' \code{\link{xpose.plot.default}} for details. #' #' @param object An xpose.data object. #' @param ylb A string giving the label for the y-axis. \code{NULL} if none. #' @param idsdir Direction for displaying point labels. The default is "up", #' since we are displaying absolute values. #' @param type Type of plot. The default is points only ("p"), but lines ("l") #' and both ("b") are also available. #' @param smooth Logical value indicating whether an x-y smooth should be #' superimposed. The default is TRUE. #' @param main The title of the plot. If \code{"Default"} then a default title #' is plotted. Otherwise the value should be a string like \code{"my title"} or #' \code{NULL} for no plot title. #' @param \dots Other arguments passed to \code{link{xpose.plot.default}}. #' @return Returns a stack of xyplots of |IWRES| vs IPRED, conditioned by #' covariates. #' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins #' @seealso \code{\link{absval.iwres.vs.ipred}}, #' \code{\link{xpose.plot.default}}, \code{\link[lattice]{xyplot}}, #' \code{\link{xpose.prefs-class}}, \code{\link{xpose.data-class}} #' @keywords methods #' @examples #' #' \dontrun{ #' ## We expect to find the required NONMEM run and table files for run #' ## 5 in the current working directory #' xpdb5 <- xpose.data(5) #' #' ## Here we load the example xpose database #' data(simpraz.xpdb) #' xpdb <- simpraz.xpdb #' #' ## A vanilla plot #' absval.iwres.vs.ipred.by.cov(xpdb) #' #' ## Custom axis labels #' absval.iwres.vs.ipred.by.cov(xpdb, ylb="|IWRES|", xlb="IPRED") #' #' ## Custom colours and symbols, no IDs #' absval.iwres.vs.ipred.by.cov(xpdb, cex=0.6, pch=3, col=1, ids=FALSE) #' } #' @export absval.iwres.vs.ipred.by.cov #' @family specific functions "absval.iwres.vs.ipred.by.cov" <- function(object, #xlb = NULL, ylb = "|IWRES|", #onlyfirst=FALSE, #inclZeroWRES=FALSE, #subset=xsubset(object), #mirror=FALSE, #seed = NULL, idsdir="up", type="p", smooth=TRUE, #prompt = TRUE, main="Default", ...) { if(is.null(xvardef("iwres",object)) || is.null(xvardef("ipred",object))) { return(cat("The required (IWRES and IPRED) variables are not set in the database!\n")) } if(any(is.null(xvardef("covariates",object)))) { return(cat("There are no covariates defined in the database!\n")) } ## create list for plots number.of.plots <- 0 for (i in xvardef("covariates", object)) { number.of.plots <- number.of.plots + 1 } plotList <- vector("list",number.of.plots) plot.num <- 0 # initialize plot number for (i in xvardef("covariates", object)) { xplot <- xpose.plot.default(xvardef("ipred",object), xvardef("iwres",object), object, main=NULL, funy="abs", #xlb = xlb, ylb=ylb, idsdir=idsdir, type=type, smooth=smooth, by=i, pass.plot.list=TRUE, #subset=subset, ...) plot.num <- plot.num+1 plotList[[plot.num]] <- xplot } default.plot.title <- paste("|",xlabel(xvardef("iwres",object),object),"| vs ", xlabel(xvardef("ipred",object),object), sep="") plotTitle <- xpose.multiple.plot.title(object=object, plot.text = default.plot.title, main=main, ...) obj <- xpose.multiple.plot(plotList,plotTitle,...) return(obj) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.iwres.vs.ipred.by.cov.R
# Xpose 4 # An R-based population pharmacokinetic/ # pharmacodynamic model building aid for NONMEM. # Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson. # Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins, # Mats O. Karlsson and E. Niclas Jonsson. # Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and # E. Niclas Jonsson. # This file is a part of Xpose 4. # Xpose 4 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. A copy can be cound in the R installation # directory under \share\licenses. If not, see http://www.gnu.org/licenses/. #' Absolute individual weighted residuals vs population predictions or #' independent variable for Xpose 4 #' #' This is a plot of absolute individual weighted residuals (|IWRES|) vs #' individual predictions (PRED) or independent variable (IDV), specific #' functions in Xpose 4. These functions are wrappers encapsulating arguments #' to the \code{xpose.plot.default} function. Most of the options take their #' default values from xpose.data object but may be overridden by supplying #' them as arguments. #' #' A wide array of extra options controlling xyplots are available. See #' \code{\link{xpose.plot.default}} for details. #' #' @param object An xpose.data object. #' @param ylb A string giving the label for the y-axis. \code{NULL} if none. #' @param idsdir Direction for displaying point labels. The default is "up", #' since we are displaying absolute values. #' @param type Type of plot. The default is points only ("p"), but lines ("l") #' and both ("b") are also available. #' @param smooth Logical value indicating whether an x-y smooth should be #' superimposed. The default is TRUE. #' @param \dots Other arguments passed to \code{link{xpose.plot.default}}. #' @return Returns an xyplot of |IWRES| vs PRED or |IWRES| vs IDV. #' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins #' @seealso \code{\link{xpose.plot.default}}, #' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}}, #' \code{\link{xpose.prefs-class}}, \code{\link{xpose.data-class}} #' @keywords methods #' @examples #' #' \dontrun{ #' ## We expect to find the required NONMEM run and table files for run #' ## 5 in the current working directory #' xpdb5 <- xpose.data(5) #' } #' #' ## Here we load the example xpose database #' data(simpraz.xpdb) #' xpdb <- simpraz.xpdb #' #' ## A vanilla plot #' absval.iwres.vs.pred(xpdb) #' #' ## A conditioning plot #' absval.iwres.vs.pred(xpdb, by="HCTZ") #' #' ## Custom heading and axis labels #' absval.iwres.vs.pred(xpdb, main="My conditioning plot", ylb="|IWRES|", xlb="PRED") #' #' ## Custom colours and symbols, no IDs #' absval.iwres.vs.pred(xpdb, cex=0.6, pch=3, col=1, ids=FALSE) #' #' #' #' @export absval.iwres.vs.pred #' @family specific functions "absval.iwres.vs.pred" <- function(object, ylb = "|IWRES|", smooth = TRUE, idsdir = "up", type = "p", ...) { if(is.null(xvardef("iwres",object)) || is.null(xvardef("pred",object))) { cat("The required variables are not set in the database!\n") return() } xplot <- xpose.plot.default(xvardef("pred",object), xvardef("iwres",object), object, ylb=ylb, funy="abs", idsdir=idsdir, smooth=smooth, type = type, ...) return(xplot) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.iwres.vs.pred.R
#' @export #' @describeIn absval.iwres.cwres.vs.ipred.pred absolute population weighted residuals (|WRES|) vs #' population predictions (PRED) and absolute individual weighted residuals #' (|IWRES|) vs individual predictions (IPRED) #' #' @family specific functions absval.iwres.wres.vs.ipred.pred <- function(object, ##aspect="fill", main="Default", ...) { if(is.null(check.vars(c("pred","wres","iwres","ipred"), object,silent=FALSE))) { return() } num.of.plots <- 2 plotList <- vector("list",num.of.plots) plot1 <- absval.wres.vs.pred(object,main=NULL, ##aspect=aspect, pass.plot.list=TRUE, ...) plot2 <- absval.iwres.vs.ipred(object,main=NULL, ##aspect=aspect, pass.plot.list=TRUE, ...) plotList[[1]] <- plot1 plotList[[2]] <- plot2 default.plot.title <- "Weighted residuals vs. Predictions" plotTitle <- xpose.multiple.plot.title(object=object, plot.text = default.plot.title, main=main, ...) obj <- xpose.multiple.plot(plotList,plotTitle,...) return(obj) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.iwres.wres.vs.ipred.pred.R
# Xpose 4 # An R-based population pharmacokinetic/ # pharmacodynamic model building aid for NONMEM. # Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson. # Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins, # Mats O. Karlsson and E. Niclas Jonsson. # Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and # E. Niclas Jonsson. # This file is a part of Xpose 4. # Xpose 4 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. A copy can be cound in the R installation # directory under \share\licenses. If not, see http://www.gnu.org/licenses/. ## Added by Justin Wilkins ## 20/10/2005 #' Absolute weighted residuals vs covariates for Xpose 4 #' #' This creates a stack of box and whisker plot of absolute population weighted #' residuals (|WRES| or |iWRES|) vs covariates. It is a wrapper encapsulating #' arguments to the \code{xpose.plot.bw} function. Most of the options take #' their default values from the xpose.data object but may be overridden by #' supplying them as arguments. #' #' Each of the covariates in the Xpose data object, as specified in #' \code{object@Prefs@Xvardef$Covariates}, is evaluated in turn, creating a #' stack of plots. #' #' A wide array of extra options controlling box-and-whisker plots are #' available. See \code{\link{xpose.plot.bw}} for details. #' #' @param object An xpose.data object. #' @param xlb A string giving the label for the x-axis. \code{NULL} if none. #' @param main The title of the plot. If \code{"Default"} then a default title #' is plotted. Otherwise the value should be a string like \code{"my title"} or #' \code{NULL} for no plot title. #' @param \dots Other arguments passed to \code{\link{xpose.plot.bw}}. #' @return Returns a stack of box-and-whisker plots of |WRES| vs covariates. #' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins #' @seealso \code{\link{xpose.plot.bw}}, \code{\link{xpose.panel.bw}}, #' \code{\link[lattice]{bwplot}}, \code{\link{xpose.prefs-class}}, #' \code{\link{xpose.data-class}} #' @keywords methods #' @examples #' #' \dontrun{ #' ## We expect to find the required NONMEM run and table files for run #' ## 5 in the current working directory #' xpdb5 <- xpose.data(5) #' #' ## Here we load the example xpose database #' data(simpraz.xpdb) #' xpdb <- simpraz.xpdb #' #' ## A vanilla plot #' absval.wres.vs.cov.bw(xpdb) #' #' ## A custom plot #' absval.wres.vs.cov.bw(xpdb, bwdotcol="white", #' bwdotpch=15, #' bwreccol="red", #' bwrecfill="red", #' bwumbcol="red", #' bwoutpch=5, #' bwoutcol="black") #' #' ## A vanilla plot using IWRES #' absval.iwres.vs.cov.bw(xpdb) #' } #' #' @export absval.wres.vs.cov.bw #' @family specific functions "absval.wres.vs.cov.bw" <- function(object, xlb = "|WRES|", #ylb = NULL, #onlyfirst=FALSE, #inclZeroWRES=FALSE, #subset=xsubset(object), #seed = NULL, #bins = 10, #samp = NULL, #prompt = TRUE, main="Default", ...) { if(any(is.null(xvardef("covariates",object)))) { return(cat("There are no covariates defined in the database!\n")) } ## create list for plots number.of.plots <- 0 for (i in xvardef("covariates", object)) { number.of.plots <- number.of.plots + 1 } plotList <- vector("list",number.of.plots) plot.num <- 0 # initialize plot number for (i in xvardef("covariates", object)) { xplot <- xpose.plot.bw(xvardef("wres",object), i, xlb = xlb, object, main = NULL, ids=FALSE, binvar = i, funx="abs", pass.plot.list = TRUE, ...) plot.num <- plot.num+1 plotList[[plot.num]] <- xplot } default.plot.title <- paste("|",xlabel(xvardef("wres",object),object), "| vs ", "Covariates", sep="") plotTitle <- xpose.multiple.plot.title(object=object, plot.text = default.plot.title, main=main, ...) obj <- xpose.multiple.plot(plotList,plotTitle,...) return(obj) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.wres.vs.cov.bw.R
# Xpose 4 # An R-based population pharmacokinetic/ # pharmacodynamic model building aid for NONMEM. # Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson. # Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins, # Mats O. Karlsson and E. Niclas Jonsson. # Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and # E. Niclas Jonsson. # This file is a part of Xpose 4. # Xpose 4 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. A copy can be cound in the R installation # directory under \share\licenses. If not, see http://www.gnu.org/licenses/. #' Absolute value of (C)WRES vs. independent variable plot in Xpose4. #' #' This is a plot of the absolute value of the CWRES (default, other residuals #' as an option) vs independent variable, a specific function in Xpose 4. It is #' a wrapper encapsulating arguments to the \code{\link{xpose.plot.default}} #' function. Most of the options take their default values from the xpose.data #' object but may be overridden by supplying them as arguments. #' #' A wide array of extra options controlling xyplots are available. See #' \code{\link{xpose.plot.default}} for details. #' #' @param object An xpose.data object. #' @param idv the independent variable. #' @param wres Which weighted residual to use. \code{"Default"} is the CWRES. #' @param ylb Y-axis label. #' @param smooth Logical value indicating whether an x-y smooth should be #' superimposed. The default is TRUE. #' @param idsdir Direction for displaying point labels. The default is "up", #' since we are displaying absolute values. #' @param type Type of plot. The default is points only ("p"), but lines ("l") #' and both ("b") are also available. #' @param \dots Other arguments passed to \code{link{xpose.plot.default}}. #' @return Returns an xyplot of |CWRES| vs idv (often TIME, defined by #' \code{\link{xvardef}}). #' @author Andrew Hooker #' @seealso \code{\link{xpose.plot.default}}, #' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}}, #' \code{\link{xpose.prefs-class}}, \code{\link{compute.cwres}}, #' \code{\link{xpose.data-class}} %% ~~objects to See Also as #' \code{\link{help}}, ~~~ #' @keywords methods #' @examples #' #' \dontrun{ #' ## We expect to find the required NONMEM run and table files for run #' ## 5 in the current working directory #' xpdb5 <- xpose.data(5) #' } #' #' ## Here we load the example xpose database #' data(simpraz.xpdb) #' xpdb <- simpraz.xpdb #' #' ## A vanilla plot #' absval.wres.vs.idv(xpdb) #' #' ## A conditioning plot #' absval.wres.vs.idv(xpdb, by="HCTZ") #' #' ## Custom heading and axis labels #' absval.wres.vs.idv(xpdb, main="Hello World", ylb="|CWRES|", xlb="IDV") #' #' ## Custom colours and symbols #' absval.wres.vs.idv(xpdb, cex=0.6, pch=3, col=1) #' #' ## using the NPDEs instead of CWRES #' absval.wres.vs.idv(xpdb,wres="NPDE") #' #' ## subsets #' absval.wres.vs.idv(xpdb,subset="TIME<10") #' #' #' @export absval.wres.vs.idv #' @family specific functions "absval.wres.vs.idv" <- function(object, idv="idv", wres="Default", ylb = "Default", smooth = TRUE, idsdir = "up", type = "p", ...) { if(is.null(check.vars(idv,object,silent=FALSE))) { return() } if(!is.na(match(wres,"Default"))) { if(is.null(check.vars("cwres",object,silent=T))) { if(is.null(check.vars("wres",object,silent=F))){ return() }else{ wres="wres" } } else { wres = "cwres" } } else { if(is.null(check.vars(wres,object,silent=FALSE))) { return() } } if(is.null(xvardef(idv,object))){ xvar <- idv }else{ xvar <- xvardef(idv,object) } if(is.null(xvardef(wres,object))){ yvar <- wres }else{ yvar <- xvardef(wres,object) } if(!is.na(match(ylb,"Default"))) { ylb <- paste("|",yvar, "|", sep="") } xplot <- xpose.plot.default(xvar, yvar, object, ylb=ylb, funy="abs", idsdir=idsdir, smooth=smooth, type = type, ...) return(xplot) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.wres.vs.idv.R
# Xpose 4 # An R-based population pharmacokinetic/ # pharmacodynamic model building aid for NONMEM. # Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson. # Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins, # Mats O. Karlsson and E. Niclas Jonsson. # Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and # E. Niclas Jonsson. # This file is a part of Xpose 4. # Xpose 4 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. A copy can be cound in the R installation # directory under \share\licenses. If not, see http://www.gnu.org/licenses/. #' Absolute population weighted residuals vs population predictions for Xpose 4 #' #' This is a plot of absolute population weighted residuals (|WRES|) vs #' population predictions (PRED), a specific function in Xpose 4. It is a #' wrapper encapsulating arguments to the \code{xpose.plot.default} function. #' Most of the options take their default values from xpose.data object but may #' be overridden by supplying them as arguments. #' #' A wide array of extra options controlling xyplots are available. See #' \code{\link{xpose.plot.default}} for details. #' #' @param object An xpose.data object. #' @param ylb A string giving the label for the y-axis. \code{NULL} if none. #' @param idsdir Direction for displaying point labels. The default is "up", #' since we are displaying absolute values. #' @param type Type of plot. The default is points only ("p"), but lines ("l") #' and both ("b") are also available. #' @param smooth Logical value indicating whether an x-y smooth should be #' superimposed. The default is TRUE. #' @param \dots Other arguments passed to \code{link{xpose.plot.default}}. #' @return Returns an xyplot of |WRES| vs PRED. #' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins #' @seealso \code{\link{xpose.plot.default}}, #' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}}, #' \code{\link{xpose.prefs-class}}, \code{\link{xpose.data-class}} #' @keywords methods #' @examples #' #' \dontrun{ #' ## We expect to find the required NONMEM run and table files for run #' ## 5 in the current working directory #' xpdb5 <- xpose.data(5) #' } #' #' ## Here we load the example xpose database #' data(simpraz.xpdb) #' xpdb <- simpraz.xpdb #' #' ## A vanilla plot #' absval.wres.vs.pred(xpdb) #' #' ## A conditioning plot #' absval.wres.vs.pred(xpdb, by="HCTZ") #' #' ## Custom heading and axis labels #' absval.wres.vs.pred(xpdb, main="My conditioning plot", #' ylb="|WRES|", xlb="PRED") #' #' ## Custom colours and symbols #' absval.wres.vs.pred(xpdb, cex=0.6, pch=19, col=1, #' smcol="blue", smlty=2) #' #' @export absval.wres.vs.pred #' @family specific functions "absval.wres.vs.pred" <- function(object, ylb = "|WRES|", idsdir="up", type="p", smooth=TRUE, ...) { if(is.null(check.vars(c("pred","wres"), object,silent=FALSE))) { return() } xplot <- xpose.plot.default(xvardef("pred",object), xvardef("wres",object), object, funy="abs", ylb=ylb, idsdir=idsdir, type=type, smooth=smooth, ...) return(xplot) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.wres.vs.pred.R
# Xpose 4 # An R-based population pharmacokinetic/ # pharmacodynamic model building aid for NONMEM. # Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson. # Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins, # Mats O. Karlsson and E. Niclas Jonsson. # Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and # E. Niclas Jonsson. # This file is a part of Xpose 4. # Xpose 4 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. A copy can be cound in the R installation # directory under \share\licenses. If not, see http://www.gnu.org/licenses/. #' Absolute population weighted residuals vs population predictions, #' conditioned on covariates, for Xpose 4 #' #' This is a plot of absolute population weighted residuals (|WRES|) vs #' population predictions (PRED) conditioned by covariates, a specific function #' in Xpose 4. It is a wrapper encapsulating arguments to the #' \code{xpose.plot.default} function. Most of the options take their default #' values from xpose.data object but may be overridden by supplying them as #' arguments. #' #' Each of the covariates in the Xpose data object, as specified in #' \code{object@Prefs@Xvardef$Covariates}, is evaluated in turn, creating a #' stack of plots. #' #' A wide array of extra options controlling xyplots are available. See #' \code{\link{xpose.plot.default}} for details. #' #' @param object An xpose.data object. #' @param ylb A string giving the label for the y-axis. \code{NULL} if none. #' @param ids Logical. Should id labels on points be shown? #' @param idsdir Direction for displaying point labels. The default is "up", #' since we are displaying absolute values. #' @param type Type of plot. The default is points only ("p"), but lines ("l") #' and both ("b") are also available. #' @param smooth Logical value indicating whether an x-y smooth should be #' superimposed. The default is TRUE. #' @param main The title of the plot. If \code{"Default"} then a default title #' is plotted. Otherwise the value should be a string like \code{"my title"} or #' \code{NULL} for no plot title. #' @param \dots Other arguments passed to \code{link{xpose.plot.default}}. #' @return Returns a stack of xyplots of |WRES| vs PRED, conditioned on #' covariates. #' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins #' @seealso \code{\link{absval.wres.vs.pred}}, #' \code{\link{xpose.plot.default}}, \code{\link{xpose.panel.default}}, #' \code{\link[lattice]{xyplot}}, \code{\link{xpose.prefs-class}}, #' \code{\link{xpose.data-class}} #' @examples #' #' \dontrun{ #' ## We expect to find the required NONMEM run and table files for run #' ## 5 in the current working directory #' xpdb5 <- xpose.data(5) #' #' ## Here we load the example xpose database #' data(simpraz.xpdb) #' xpdb <- simpraz.xpdb #' #' ## A vanilla plot #' absval.wres.vs.pred.by.cov(xpdb) #' #' ## Custom axis labels #' absval.wres.vs.pred.by.cov(xpdb, ylb="|CWRES|", xlb="PRED") #' #' ## Custom colours and symbols, IDs #' absval.wres.vs.pred.by.cov(xpdb, cex=0.6, pch=3, col=1, ids=TRUE) #' } #' #' @export absval.wres.vs.pred.by.cov #' @family specific functions "absval.wres.vs.pred.by.cov" <- function(object, ylb = "|WRES|", type="p", smooth=TRUE, ids = FALSE, idsdir="up", main="Default", ...) { if(is.null(check.vars(c("pred","wres"), object,silent=FALSE))) { return() } if(any(is.null(xvardef("covariates",object)))) { return(cat("There are no covariates defined in the database!\n")) } ## create list for plots number.of.plots <- 0 for (i in xvardef("covariates", object)) { number.of.plots <- number.of.plots + 1 } plotList <- vector("list",number.of.plots) plot.num <- 0 # initialize plot number for (i in xvardef("covariates", object)) { xplot <- xpose.plot.default(xvardef("pred",object), xvardef("wres",object), object, main=NULL, funy="abs", ylb=ylb, type=type, smooth=smooth, by=i, ids = ids, idsdir=idsdir, pass.plot.list = TRUE, ...) plot.num <- plot.num+1 plotList[[plot.num]] <- xplot } default.plot.title <- paste("|",xlabel(xvardef("wres",object),object), "| \nvs. ", xlabel(xvardef("pred",object),object), sep="") plotTitle <- xpose.multiple.plot.title(object=object, plot.text = default.plot.title, main=main, ...) obj <- xpose.multiple.plot(plotList,plotTitle,...) return(obj) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/absval.wres.vs.pred.by.cov.R
#' Column-transformation functions for Xpose 4 #' #' These functions transform existing Xpose 4 data columns, adding new columns. #' #' These functions may be used to create new data columns within the Xpose data #' object by transforming existing ones. #' #' @param object An \code{xpose.data} object. #' @param listall A logical operator specifying whether the items in the #' database should be listed. #' @param classic A logical operator specifying whether the function should #' assume the classic menu system. This is an internal option and need never #' be called from the command line. #' @return An \code{\link{xpose.data}} object (classic == FALSE) or null #' (classic == TRUE). #' @author Niclas Jonsson, Justin Wilkins and Andrew Hooker #' @seealso \code{\link{xpose.data}} #' @examples #' #' \dontrun{ #' ## xpdb5 is an Xpose data object #' ## We expect to find the required NONMEM run and table files for run #' ## 5 in the current working directory #' xpdb5 <- xpose.data(5) #' #' ## Create a column containing the absolute values of data in another #' ## column #' add.absval(xpdb5) #' #' ## Create a categorical data column based on a continuous data column, #' ## and do not list variables #' add.dichot(xpdb5, listall = FALSE) #' #' ## Create a column containing the exponentiated values of data in #' ## another column #' add.exp(xpdb5) #' #' ## Create a column containing log-transformations of data in another #' ## column #' add.log(xpdb5) #' #' ## Create a time-after-dose column #' add.tad(xpdb5) #' } #' #' @family data functions #' @name add_transformed_columns NULL #' @export #' @describeIn add_transformed_columns Create a column containing the absolute values of data #' in another column. "add.absval" <- function(object, listall=TRUE, classic=FALSE ) { if(listall) db.names(object) cat("Please type the names of the items to be converted to\n") cat("absolute values, one per line, and finish with a blank line.\n") items <- scan(what=character()) data <- object@Data sdata <- object@SData nams <- names(data) for(i in items) { if(is.na(match(i, nams))) { cat("No match: ", i, "\n", sep="") next } nam <- paste("abs", i, sep="") #cat(nam) newit <- abs(data[[i]]) if(any((data[[i]]-newit) !=0)) { data[[nam]] <- newit #vname(data[,nam]) <- nam } if(!all(is.null(sdata))){ newits <- abs(sdata[[i]]) if(any((sdata[[i]]-newits) !=0)) { sdata[[nam]] <- newits #vname(data[,nam]) <- nam } } } object@Data <- data object@SData <- sdata for (i in items) { expitem <- paste("abs", i, sep="") object@Prefs@Labels[[expitem]] <- c(paste("abs(", i, ")", sep="")) } if (classic==TRUE) { c1<-call("assign",paste("xpdb", object@Runno, sep = ""),object,envir=.GlobalEnv) eval(c1) #assign(paste("xpdb", object@Runno, sep = ""), object, immediate=T, envir = .GlobalEnv) c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = "")))) eval(c2) #assign(pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = "")))) return(cat("")) } else { return(object) } }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/add.absval.R
#' @describeIn add_transformed_columns Create a categorical data column based on a continuous data column #' @export # @describeIn add.absval Dichotomize continuous variables "add.dichot" <- function(object, listall=TRUE, classic=FALSE ) { if(listall) db.names(object) data <- object@Data sdata <- object@SData nams <- names(data) cat("Please type the name of the item you whish to categorize:\n") ans <- readline() if(is.na(match(ans,nams))) { cat("Couldn't find that data item in the current database.\n") return(cat("")) } if(!is.numeric(data[[ans]])) { cat("The specified data item is not numeric.\n") return(cat("")) } cat("The quartiles of",ans,"are:\n") cat(paste(summary(data[[ans]])[1:3]),"\n\n",sep=" ") cat("Enter the breakpoints to use and finish with a blank line\n") cat("(the quartiles will be used if left empty).\n") br <- scan(what=numeric()) if(length(br) == 0) { cat("No breakpoints were given. Will use default of Q1-3.\n") br <- summary(data[[ans]])[1:3] } br <- c(min(data[[ans]]),br,max(data[[ans]])) br <- unique(br) br <- br[order(br)] nam <- paste("cat", ans, sep="") data[[nam]] <- cut(data[[ans]], breaks=br, include.lowest=T) if (!is.null(sdata)) { sdata[[nam]] <- cut(sdata[[ans]], breaks=br, include.lowest=T) } object@Data <- data object@SData <- sdata #for (i in items) { catitem <- paste("cat", ans, sep="") object@Prefs@Labels[[catitem]] <- c(paste("categorical(", ans, ")", sep="")) #} if (classic==TRUE) { # assign(paste("xpdb", object@Runno, sep = ""), object, immediate=T, envir = .GlobalEnv) # assign(pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = "")))) # return(cat("")) ## to avoid checks on global variable assignment in package building c1<-call("assign",paste("xpdb", object@Runno, sep = ""),object,envir=.GlobalEnv) eval(c1) c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = "")))) eval(c2) return(cat("")) } else { return(object) } }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/add.dichot.R
#' @describeIn add_transformed_columns Create an exponentiated version of an existing variable #' @export "add.exp" <- function(object, listall=TRUE, classic=FALSE ) { if(listall) db.names(object) cat("Please type the names of the items to be exponentiated, one\n") cat("per line, and finish with a blank line.\n") items <- scan(what=character()) data <- object@Data sdata <- object@SData nams <- names(data) for(i in items) { if(is.na(match(i, nams))) { cat("No match: ", i, "\n", sep="") next } nam <- paste("exp", i, sep="") #cat(nam) newit <- exp(data[[i]]) newits <- exp(sdata[[i]]) if(any((data[[i]]-newit) !=0)) { data[[nam]] <- newit #vname(data[,nam]) <- nam } if(any((sdata[[i]]-newits) !=0)) { sdata[[nam]] <- newits #vname(data[,nam]) <- nam } } object@Data <- data object@SData <- sdata for (i in items) { expitem <- paste("exp", i, sep="") object@Prefs@Labels[[expitem]] <- c(paste("exp(", i, ")", sep="")) } if (classic==TRUE) { #assign(paste("xpdb", object@Runno, sep = ""), object, immediate=T, envir = .GlobalEnv) #assign(pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = "")))) #return(cat("")) ## to avoid checks on global variable assignment in package building c1<-call("assign",paste("xpdb", object@Runno, sep = ""),object,envir=.GlobalEnv) eval(c1) c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = "")))) eval(c2) return(cat("")) } else { return(object) } }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/add.exp.R
# Xpose 4 # An R-based population pharmacokinetic/ # pharmacodynamic model building aid for NONMEM. # Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson. # Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins, # Mats O. Karlsson and E. Niclas Jonsson. # Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and # E. Niclas Jonsson. # This file is a part of Xpose 4. # Xpose 4 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. A copy can be cound in the R installation # directory under \share\licenses. If not, see http://www.gnu.org/licenses/. #' Print tables or text in a grid object #' #' These functions take an array of values and labels or an array of text and #' add it to one or many grid viewports in an orderly fashion. #' #' #' @aliases add.grid.table add.grid.text #' @param txt The text or table values to add to the grid object. #' @param col.nams the column names of the table values #' @param ystart The y location to start printing in the grid viewport #' @param xstart The x location to start printing in the grid viewport #' @param start.pt The start point (row) in the table array to start printing #' @param vp The viewport(s) to add the table or text to #' @param vp.num the viewport number in \code{vp} to start printing to #' @param minrow The minimum rows before printing more columns to use in the #' table #' @param cell.padding padding between cells in the table #' @param mult.col.padding padding between multiple columns in the table #' @param col.optimize should we column optimize (\code{TRUE}) or row optimize #' (\code{FALSE}) #' @param equal.widths Should all columns have equal widths #' @param space.before.table Should there be a space before the table #' @param center.table should we center the table in the viewport? #' @param use.rect Should we make rectangles with background color around the #' table entries \code{TRUE} or \code{FALSE} #' @param fill.type Which rectangles should be filled. Allowed values are #' \code{"all"}, \code{"top"}, \code{"side"}, \code{"both"} and \code{NULL}. #' @param fill.col The color of the filled rectangles #' @param cell.lines.lty The line-type for the lines between the cells, using #' the same values as lty. #' @param \dots Other arguments passed to the various functions. #' @return A List is returned with the following components \item{ystart }{new #' starting point for new text} \item{stop.pt }{null if everything gets #' printed} \item{vp.num }{the viewport needed for next text printed} #' \item{xpose.table }{A grob object that can be plotted.} #' @author Andrew Hooker #' @seealso \code{\link{runsum}}, \code{\link[grid]{grid.text}} #' @keywords methods #' @export add.grid.table add.grid.table <- function(txt, # list of character vectors # corresponding to # columns in table # list(parnam, parval) col.nams=NULL, # collumn names c("col1","col2") ystart, # y-coordinate in viewport to start xstart=unit(0,"npc"), # x coordinate in viewport start.pt=1, # point in lists to start vp, # list of viewport names list(vp1,vp2) vp.num=1, # number of viewport to begin with minrow=5, # minimum rows in each column cell.padding=0.5, # padding in each cell of table # in character units mult.col.padding=1, # padding between # new new columns of the table col.optimize=TRUE, # get maximum columns or rows in viewport equal.widths=FALSE, # should all columns have equal widths space.before.table=1, center.table=FALSE, use.rect=FALSE, fill.type=NULL, # all,top,side,both,NULL fill.col="grey", cell.lines.lty=0, ...) { ## to do: ## ## add grid rectangles if asked for ## table title for(k in vp.num:length(vp)){ vp.num = k pushViewport(vp[[k]]) wdth <- rep(0,length(txt)) ncols <- length(txt) npar <- length(txt[[1]]) for (i in 1:ncols){ wdth[i] <- convertWidth(max(unit(rep(1, length(txt[[i]])),"strwidth", data = as.list(txt[[i]])))+unit(cell.padding,"char"), "npc",valueOnly=TRUE) if(!is.null(col.nams)) { tmp <- convertWidth(max(unit(rep(1, length(col.nams[i])),"strwidth", data = as.list(col.nams[i]))) +unit(cell.padding,"char"), "npc",valueOnly=TRUE) if(tmp>wdth[i]) wdth[i]=tmp } } if (equal.widths){ wdth[1:length(wdth)]=max(wdth) } wdth.tot <- sum(wdth) + convertWidth(unit(mult.col.padding,"char"),"npc",valueOnly=TRUE) vp.lines.left <- convertHeight(ystart,"lines",valueOnly=TRUE) vp.width.left <- 1 - convertWidth(xstart,"npc",valueOnly=TRUE) ncol.grps.avail <- floor(vp.width.left/wdth.tot) # a multiple of ncols nrows.avail <- floor(vp.lines.left) xtra.space <- vp.width.left - wdth.tot*ncol.grps.avail upViewport() ## make sure we have space for table if (ncol.grps.avail==0){ warning("fontsize too large for table to print") ret.list <- list(ystart = ystart, # new starting point for new text stop.pt = NULL, vp.num = vp.num # the viewport needed for this to work ) return(ret.list) } if (nrows.avail<2){ space.avail <- TRUE if(!is.null(col.nams)||nrows.avail==0){ space.avail <- FALSE stop.pt <- start.pt } } else { space.avail <- TRUE } ## Decide how many rows in each column of parameters if (col.optimize){ if(npar <= minrow*ncol.grps.avail) { ncol.grps.needed <- ceiling(npar/minrow) if(ncol.grps.needed==1) par.in.col <- npar if(ncol.grps.needed > 1) par.in.col <- minrow } else { par.in.col <- ceiling(npar/ncol.grps.avail) ncol.grps.needed <- ncol.grps.avail } } else { # row optimize ncol.grps.needed <- ceiling(npar/nrows.avail) if(ncol.grps.needed==1) par.in.col <- npar if(ncol.grps.needed > 1) par.in.col <- nrows.avail } ## To make it easier to print the parameters we add empty entries ## to fill all columns max.par <- ncol.grps.needed*par.in.col extra.pars <- max.par-npar tmp.txt <- txt if(extra.pars > 0) { for (i in 1:ncols){ tmp.txt[[i]][(npar+1):max.par] <- "" } } xpose.table <- gTree(name="xpose.table") for( i in 1:ncol.grps.needed) { range.to.print <- (1+(i-1)*par.in.col+(start.pt-1)):(i*par.in.col) ## Print out table wdth.prev.cols <- 0 for (j in 1:ncols){ ystart=ystart xstart=(i-1)*unit(wdth.tot,"npc")+unit(wdth.prev.cols,"npc") if (center.table){ xstart = xstart + unit(xtra.space/2,"npc") + unit((ncol.grps.avail - ncol.grps.needed)*wdth.tot/2,"npc") } col.txt <- tmp.txt[[j]] ## add column names if(!is.null(col.nams)) { if(!all(col.txt[range.to.print]=="")){ col.txt <- c(col.nams[j],col.txt[range.to.print]) } else { col.txt <- c(" ",col.txt[range.to.print]) } } ## add column text if(space.avail) { fill.type.tmp <- fill.type if(!is.null(fill.type)){ if(fill.type=="top") fill.type.tmp <- "firstonly" if(fill.type=="both"){ fill.type.tmp <- "firstonly" if(j==1) fill.type.tmp <- "all" } } txt.marker <- add.grid.text(txt=col.txt, ystart=ystart, xstart=xstart, start.pt=1, vp=list(vp[[k]]), vp.num=1, spaces.before=space.before.table, wdth=wdth[j], fill.type=fill.type.tmp, fill.col=fill.col, cell.lines.lty=cell.lines.lty, xpose.table=xpose.table, use.rect=use.rect, ...) xpose.table <- txt.marker$xpose.table } wdth.prev.cols <- wdth.prev.cols+wdth[j] } } if(space.avail) { ystart <- txt.marker$ystart stop.pt <- txt.marker$stop.pt } if (!is.null(stop.pt)){ start.pt=stop.pt ystart=unit(1,"npc") xstart <- unit(0,"npc") } else{ break } } ret.list <- list(ystart = ystart, # new starting point for new text stop.pt = stop.pt, # null if everything gets printed vp.num = vp.num, # the viewport needed for this to work xpose.table=xpose.table # a grob object ) return(ret.list) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/add.grid.table.R
# Xpose 4 # An R-based population pharmacokinetic/ # pharmacodynamic model building aid for NONMEM. # Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson. # Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins, # Mats O. Karlsson and E. Niclas Jonsson. # Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and # E. Niclas Jonsson. # This file is a part of Xpose 4. # Xpose 4 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. A copy can be cound in the R installation # directory under \share\licenses. If not, see http://www.gnu.org/licenses/. add.grid.text <- function(txt, ystart, # y-coordinate in viewport to start (top) xstart=unit(0,"npc"), # x coordinate in viewport (left) start.pt=1, # point in text to start vp, # list of viewport names list(vp1,vp2) vp.num=1, # number of viewport to begin with spaces.before=NULL, spaces.after=NULL, v.space.before=0, v.space.after=0, use.rect=FALSE, wdth=NULL, #the width of the column of data fill.type=NULL, # all, firstonly, NULL fill.col="grey", cell.lines.lty=0, xpose.table=gTree(), # a grob object ...) { ystart.tmp <- ystart if (!is.null(spaces.before)){ tmp <- rep(" ",spaces.before) txt <- c(tmp,txt) } if (!is.null(spaces.after)){ tmp <- rep(" ",spaces.after) txt <- c(txt,tmp) } for(j in vp.num:length(vp)){ vp.num.final = j pushViewport(vp[[j]]) ## need size of each line and draw a grid around it ## determine line hight of first row and space left #line.ht <- convertHeight(unit(1,"lines"),"npc") #space.left <- convertHeight(ystart - line.ht,"npc",valueOnly=TRUE) ## loop through text stop.pt <- NULL #xpose.cells <- gTree(name="xpose.cells") for (i in start.pt:length(txt)){ new.txt <- txt[i] new.txt.lines <- gregexpr("\n",new.txt) if(all(new.txt.lines[[1]]==-1)) { num.lines=1 } else { num.lines=length(new.txt.lines[[1]])+1 } line.ht <- convertHeight(unit(num.lines,"lines"),"npc") over.space <- convertHeight(unit(v.space.before,"lines"),"npc") under.space <- convertHeight(unit(v.space.after,"lines"),"npc") tot.ht <- line.ht+over.space+under.space space.left <- convertHeight(ystart - tot.ht,"npc",valueOnly=TRUE) if(space.left>=0){ txt.width <- convertWidth(stringWidth(new.txt),"npc",valueOnly=TRUE) while (txt.width >= 1) { new.txt <- substr(new.txt,1,nchar(new.txt)-1) txt.width <- convertWidth(stringWidth(new.txt),"npc",valueOnly=TRUE) } fill.col.tmp=fill.col if(is.null(fill.type)){ fill.col.tmp <- NULL } else { if(fill.type=="firstonly"){ fill.col.tmp <- NULL # fill.list <- c(1:(spaces.before+1)) fill.list <- spaces.before+1 if(any(i==fill.list)) fill.col.tmp <- fill.col } if(fill.type=="all"){ fill.col.tmp <- NULL # fill.list <- c(1:(spaces.before+1)) fill.list <- c(1:spaces.before) if(!any(i==fill.list)) fill.col.tmp <- fill.col } } if(use.rect){ xpose.rect <- grid.rect(x=xstart,y=ystart,width=wdth, height=tot.ht, just=c("left","top"), gp=gpar(fill=fill.col.tmp, lty=cell.lines.lty, ...), ...) xpose.table <- addGrob(gTree=xpose.table, child=xpose.rect) #xpose.line <- grid.lines() #x=c(xstart,wdth),y=ystart,default.units="npc", #just=c("left","top"), #gp=gpar(fill=fill.col.tmp, # lty=cell.lines.lty, # ...), # ...) #xpose.table <- addGrob(gTree=xpose.table, child=xpose.line) } xpose.text <- grid.text(new.txt,x=xstart,y=(ystart-over.space),just=c("left","top"),check.overlap=TRUE,...) xpose.table <- addGrob(gTree=xpose.table, child=xpose.text) ystart <- ystart-tot.ht } else { stop.pt = i break } } upViewport() if (!is.null(stop.pt)){ start.pt=stop.pt #ystart=ystart.tmp ystart=unit(1,"npc") vp.num.final=j+1 } else{ break } } ret.list <- list(ystart = ystart, # new starting point for new text stop.pt = stop.pt, # null if everything gets printed vp.num = vp.num.final, # the viewport needed for this to work xpose.table=xpose.table # the grob object created ) return(ret.list) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/add.grid.text.R
# Xpose 4 # An R-based population pharmacokinetic/ # pharmacodynamic model building aid for NONMEM. # Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson. # Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins, # Mats O. Karlsson and E. Niclas Jonsson. # Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and # E. Niclas Jonsson. # This file is a part of Xpose 4. # Xpose 4 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. A copy can be cound in the R installation # directory under \share\licenses. If not, see http://www.gnu.org/licenses/. #' @describeIn add_transformed_columns Create a log transformation of an existing variable #' @export "add.log" <- function(object, listall=TRUE, classic=FALSE ) { if(listall) db.names(object) cat("Please type the names of the items to be log-transformed, one\n") cat("per line, and finish with a blank line.\n") items <- scan(what=character()) data <- object@Data sdata <- object@SData nams <- names(data) for(i in items) { if(is.na(match(i, nams))) { cat("No match: ", i, "\n", sep="") next } if(any(data[[i]] <=0)) { cat(i,"contains entries which are less than or equal to zero!\n") next } nam <- paste("log", i, sep="") #cat(nam) newit <- log(data[[i]]) newits <- log(sdata[[i]]) if(any((data[[i]]-newit) !=0)) { data[[nam]] <- newit #vname(data[,nam]) <- nam } if(any((sdata[[i]]-newits) !=0)) { sdata[[nam]] <- newits #vname(data[,nam]) <- nam } } object@Data <- data object@SData <- sdata for (i in items) { logitem <- paste("log", i, sep="") object@Prefs@Labels[[logitem]] <- c(paste("log(", i, ")", sep="")) } if (classic==TRUE) { #assign(paste("xpdb", object@Runno, sep = ""), object, immediate=T, envir = .GlobalEnv) #assign(pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = "")))) #return(cat("")) ## to avoid checks on global variable assignment in package building c1<-call("assign",paste("xpdb", object@Runno, sep = ""),object,envir=.GlobalEnv) eval(c1) c2<-call("assign",pos = 1, ".cur.db", eval(as.name(paste("xpdb", object@Runno, sep = "")))) eval(c2) return(cat("")) } else { return(object) } }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/add.log.R
# Xpose 4 # An R-based population pharmacokinetic/ # pharmacodynamic model building aid for NONMEM. # Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson. # Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins, # Mats O. Karlsson and E. Niclas Jonsson. # Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and # E. Niclas Jonsson. # This file is a part of Xpose 4. # Xpose 4 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. A copy can be cound in the R installation # directory under \share\licenses. If not, see http://www.gnu.org/licenses/. #' Additional model comparison plots, for Xpose 4 #' #' This creates a stack of four plots, comparing absolute values of PRED, #' absolute values of IPRED, delta CWRES (or WRES) and delta IWRES estimates #' for the two specified model fits. #' #' Four model comparison plots are displayed in sequence. #' #' Conditional weighted residuals (CWRES) require some extra steps to #' calculate. See \code{\link{compute.cwres}} for details. #' #' A wide array of extra options controlling xyplots are available. See #' \code{\link{xpose.plot.default}} for details. #' #' @param object An xpose.data object. #' @param object.ref An xpose.data object. If not supplied, the user will be #' prompted. #' @param inclZeroWRES Logical value indicating whether rows with WRES=0 is #' included in the plot. The default is TRUE. #' @param onlyfirst Logical value indicating whether only the first row per #' individual is included in the plot. #' @param subset A string giving the subset expression to be applied to the #' data before plotting. See \code{\link{xsubset}}. #' @param main The title of the plot. If \code{"Default"} then a default title #' is plotted. Otherwise the value should be a string like \code{"my title"} or #' \code{NULL} for no plot title. #' @param force.wres Should we use the WRES in the plots instead of CWRES #' (logical \code{TRUE} or \code{FALSE}) #' @param \dots Other arguments passed to \code{link{xpose.plot.default}}. #' @return Returns a stack of plots comprising comparisons of absolute values #' of PRED, absolute values of IPRED, absolute differences in CWRES (or WRES) #' and absolute differences in IWRES for the two specified runs. #' @author E. Niclas Jonsson, Mats Karlsson, Andrew Hooker & Justin Wilkins #' @seealso \code{\link{xpose.plot.default}}, #' \code{\link{xpose.panel.default}}, \code{\link[lattice]{xyplot}}, #' \code{\link{compute.cwres}}, \code{\link{xpose.prefs-class}}, #' \code{\link{xpose.data-class}} #' @keywords methods #' @examples #' #' \dontrun{ #' ## We expect to find the required NONMEM run and table files for runs #' ## 5 and 6 in the current working directory #' xpdb5 <- xpose.data(5) #' xpdb6 <- xpose.data(6) #' #' ## A vanilla plot, without prompts #' add.model.comp(xpdb5, xpdb6, prompt = FALSE) #' #' ## Custom colours and symbols, no user IDs #' add.model.comp(xpdb5, xpdb6, cex=0.6, pch=8, col=1, ids=NULL) #' } #' #' #' @export add.model.comp "add.model.comp" <- function(object, object.ref = NULL, onlyfirst = FALSE, inclZeroWRES = FALSE, subset = xsubset(object), main="Default", force.wres=FALSE, #ref.default = ".ref.db", ...) { if (is.null(object.ref)) { ref.list <- get.refrunno() if(exists(".ref.db")){ object.ref <- eval(parse(text=".ref.db")) } else { return() } if(any(is.null(ref.list))) return() } if(dim(object@Data)[1] != dim(object.ref@Data)[1]) { cat("The current database and the reference database do not have\n") cat("the same number of lines!\n") invisible() return() } if(is.null(check.vars(c("idlab","pred","ipred","iwres","idv"), object,silent=FALSE))) { return() } use.cwres=TRUE if(force.wres){ use.cwres=FALSE if(is.null(check.vars(c("wres"),object,silent=FALSE))) return() } else { if(is.null(check.vars(c("cwres"),object,silent=TRUE))) { use.cwres=FALSE if(is.null(check.vars(c("wres"),object,silent=FALSE))) return() } } object@Data$PRED.REF <- abs(object.ref@Data[,xvardef("pred", object.ref)]) object@Data$IPRED.REF <- abs(object.ref@Data[,xvardef("ipred", object.ref)]) #object@Data$WRES.REF <- abs(object.ref@Data[,xvardef("wres", object.ref)]) object@Data$IWRES.REF <- abs(object.ref@Data[,xvardef("iwres", object.ref)]) #object@Data$dWRES <- abs(object@Data[,xvardef("wres", object)] - object.ref@Data[,xvardef("wres", object.ref)]) object@Data$dIWRES <- abs(object@Data[,xvardef("iwres", object)] - object.ref@Data[,xvardef("iwres", object.ref)]) if(use.cwres){ object@Data$CWRES.REF <- abs(object.ref@Data[,xvardef("cwres", object.ref)]) object@Data$dCWRES <- abs(object@Data[,xvardef("cwres", object)] - object.ref@Data[,xvardef("cwres", object.ref)]) object@Data[,xvardef("cwres", object)] <- abs(object@Data[,xvardef("cwres", object)]) } else { object@Data$WRES.REF <- abs(object.ref@Data[,xvardef("wres", object.ref)]) object@Data$dWRES <- abs(object@Data[,xvardef("wres", object)] - object.ref@Data[,xvardef("wres", object.ref)]) object@Data[,xvardef("wres", object)] <- abs(object@Data[,xvardef("wres", object)]) } object@Data[,xvardef("pred", object)] <- abs(object@Data[,xvardef("pred", object)]) object@Data[,xvardef("ipred", object)] <- abs(object@Data[,xvardef("ipred", object)]) #object@Data[,xvardef("wres", object)] <- abs(object@Data[,xvardef("wres", object)]) object@Data[,xvardef("iwres", object)] <- abs(object@Data[,xvardef("iwres", object)]) ## |PRED| vs |PRED| if(!any(is.null(xvardef("pred", object))) && !any(is.null(xvardef("pred", object.ref)))) { xlb <- paste("|",xlabel(xvardef("pred",object),object), "| (Run ", object@Runno, ")",sep="") ylb <- paste("|",xlabel(xvardef("pred",object.ref),object.ref), "| (Run ", object.ref@Runno, ")",sep="") # main <- paste(ylb, " vs ", xlb, sep="") xplot1 <- xpose.plot.default(xvardef("pred", object), "PRED.REF", object, xlb = xlb, ylb = ylb, main = NULL, abline=c(0,1), onlyfirst = onlyfirst, inclZeroWRES = inclZeroWRES, subset = subset, pass.plot.list = TRUE, ...) } ## |IPRED| vs |IPRED| if(!any(is.null(xvardef("ipred", object))) && !any(is.null(xvardef("ipred", object.ref)))) { xlb <- paste("|",xlabel(xvardef("ipred",object),object), "| (Run ", object@Runno, ")",sep="") ylb <- paste("|",xlabel(xvardef("ipred",object.ref),object.ref), "| (Run ", object.ref@Runno, ")",sep="") # main <- paste(ylb, " vs ", xlb, sep="") xplot2 <- xpose.plot.default(xvardef("ipred", object), "IPRED.REF", object, xlb = xlb, ylb = ylb, main = NULL, abline=c(0,1), onlyfirst = onlyfirst, inclZeroWRES = inclZeroWRES, subset = subset, pass.plot.list = TRUE, ...) } if(use.cwres){ # |dCWRES| vs IDV if(!any(is.null(xvardef("cwres", object))) && !any(is.null(xvardef("cwres", object.ref)))) { xlb <- paste(xlabel(xvardef("idv",object),object),sep="") ylb <- paste("|dCWRES| (Run ", object@Runno, " - Run ",object.ref@Runno,")",sep="") # main <- paste(ylb, " vs ", xlb, sep="") xplot3 <- xpose.plot.default(xvardef("idv", object), "dCWRES", object, xlb = xlb, ylb = ylb, main = NULL, onlyfirst = onlyfirst, inclZeroWRES = inclZeroWRES, subset = subset, pass.plot.list = TRUE, ...) } } else { # |dWRES| vs IDV if(!any(is.null(xvardef("wres", object))) && !any(is.null(xvardef("wres", object.ref)))) { xlb <- paste(xlabel(xvardef("idv",object),object),sep="") ylb <- paste("|dWRES| (Run ", object@Runno, " - Run ",object.ref@Runno,")",sep="") # main <- paste(ylb, " vs ", xlb, sep="") xplot3 <- xpose.plot.default(xvardef("idv", object), "dWRES", object, xlb = xlb, ylb = ylb, main = NULL, onlyfirst = onlyfirst, inclZeroWRES = inclZeroWRES, subset = subset, pass.plot.list = TRUE, ...) } } # |dIWRES| vs IDV if(!any(is.null(xvardef("iwres", object))) && !any(is.null(xvardef("iwres", object.ref)))) { xlb <- paste(xlabel(xvardef("idv",object),object),sep="") ylb <- paste("|diWRES| (Run ", object@Runno, " - Run ",object.ref@Runno,")",sep="") # main <- paste(ylb, " vs ", xlb, sep="") xplot4 <- xpose.plot.default(xvardef("idv", object), "dIWRES", object, xlb = xlb, ylb = ylb, main = NULL, onlyfirst = onlyfirst, inclZeroWRES = inclZeroWRES, subset = subset, pass.plot.list = TRUE, ...) } ## create enpty list for plots num.of.plots <- 4 plotList <- vector("list",num.of.plots) plotList[[1]] <- xplot1 plotList[[2]] <- xplot2 plotList[[3]] <- xplot3 plotList[[4]] <- xplot4 default.plot.title <- "Additional model comparison plots" plotTitle <- xpose.multiple.plot.title(object=object, plot.text = default.plot.title, subset=subset, main=main, ...) obj <- xpose.multiple.plot(plotList,plotTitle,...) return(obj) }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/add.model.comp.R
# Xpose 4 # An R-based population pharmacokinetic/ # pharmacodynamic model building aid for NONMEM. # Copyright (C) 1998-2004 E. Niclas Jonsson and Mats Karlsson. # Copyright (C) 2005-2008 Andrew C. Hooker, Justin J. Wilkins, # Mats O. Karlsson and E. Niclas Jonsson. # Copyright (C) 2009-2010 Andrew C. Hooker, Mats O. Karlsson and # E. Niclas Jonsson. # This file is a part of Xpose 4. # Xpose 4 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. A copy can be cound in the R installation # directory under \share\licenses. If not, see http://www.gnu.org/licenses/. "add.modify.db.items.menu" <- function() { choices <- c("Return to the previous menu ->", "Add a time after dose (TAD) item to the current database", "*Add averaged covariates to the current database", "Add exponentiated values of an item to the current database", "Add the logarithm of an item to the current database", "Add absolute values of an item to the current database", "* Add a random bivariate factor to the current database", "Change covariates categorical <-> continuous ", "Create a categorical item based on a continuous item" ##"Copy data item from another database" ) title=("\nCREATE/MODIFY DATA ITEMS MENU\n \\main\\preferences\\Create/modify items in the current database") pick <- menu(choices,title=title) qx <- 0 switch(pick+1, qx <- 2, qx <- 1, add.tad(eval(parse(text=".cur.db")), classic=T), cat("Not yet implemented!\n"), #cov.ave(), add.exp(eval(parse(text=".cur.db")), classic=T), add.log(eval(parse(text=".cur.db")), classic=T), add.absval(eval(parse(text=".cur.db")), classic=T), #object<-add.absval(object), cat("Not yet implemented!\n"), #add.rand(get("eval(parse(text=".cur.db"))", classic=T), change.cat.cont(eval(parse(text=".cur.db")), classic=T), add.dichot(eval(parse(text=".cur.db")), classic=T) ##copy.item() ) if(qx == 2) { return(invisible(2)) } else { if(qx == 1) { return(invisible(0)) } else { Recall() } } }
/scratch/gouwar.j/cran-all/cranData/xpose4/R/add.modify.db.items.menu.R