content
stringlengths
0
14.9M
filename
stringlengths
44
136
# Pipeline_function -------------------------------------------------------- #' @title AutoScore STEP (i) for ordinal outcomes: Generate variable ranking #' list by machine learning (AutoScore Module 1) #' @details The first step in the AutoScore framework is variable ranking. We #' use random forest (RF) for multiclass classification to identify the #' top-ranking predictors for subsequent score generation. This step #' corresponds to Module 1 in the AutoScore-Ordinal paper. #' @inheritParams AutoScore_rank #' @inherit AutoScore_rank return #' @examples #' \dontrun{ #' # see AutoScore-Ordinal Guidebook for the whole 5-step workflow #' data("sample_data_ordinal") # Output is named `label` #' ranking <- AutoScore_rank_ordinal(sample_data_ordinal, ntree = 50) #' } #' @references #' \itemize{ #' \item{Breiman, L. (2001), Random Forests, Machine Learning 45(1), 5-32} #' \item{Saffari SE, Ning Y, Feng X, Chakraborty B, Volovici V, Vaughan R, Ong #' ME, Liu N, AutoScore-Ordinal: An interpretable machine learning framework for #' generating scoring models for ordinal outcomes, arXiv:2202.08407} #' } #' @seealso \code{\link{AutoScore_parsimony_Ordinal}}, #' \code{\link{AutoScore_weighting_Ordinal}}, #' \code{\link{AutoScore_fine_tuning_Ordinal}}, #' \code{\link{AutoScore_testing_Ordinal}}. #' @importFrom randomForest randomForest importance #' @export AutoScore_rank_Ordinal <- function(train_set, ntree = 100) { train_set <- AutoScore_impute(train_set) train_set$label <- ordered(train_set$label) # Ordered factor model <- randomForest::randomForest(label ~ ., data = train_set, ntree = ntree, preProcess = "scale") # estimate variable importance importance <- randomForest::importance(model, scale = F) # summarize importance names(importance) <- rownames(importance) importance <- sort(importance, decreasing = T) cat("The ranking based on variable importance was shown below for each variable: \n") print(importance) plot_importance(importance) return(importance) } #' @title AutoScore STEP(ii) for ordinal outcomes: Select the best model with #' parsimony plot (AutoScore Modules 2+3+4) #' @inheritParams AutoScore_parsimony #' @param rank The raking result generated from AutoScore STEP(i) for ordinal #' outcomes (\code{\link{AutoScore_rank_Ordinal}}). #' @param link The link function used to model ordinal outcomes. Default is #' \code{"logit"} for proportional odds model. Other options are #' \code{"cloglog"} (proportional hazards model) and \code{"probit"}. #' @details This is the second step of the general AutoScore workflow for #' ordinal outcomes, to generate the parsimony plot to help select a #' parsimonious model. In this step, it goes through AutoScore Module 2,3 and #' 4 multiple times and to evaluate the performance under different variable #' list. The generated parsimony plot would give researcher an intuitive #' figure to choose the best models. If data size is small (eg, <5000), an #' independent validation set may not be a wise choice. Then, we suggest using #' cross-validation to maximize the utility of data. Set #' \code{cross_validation=TRUE}. #' @return List of mAUC (ie, the average AUC of dichotomous classifications) #' value for different number of variables #' @examples #' \dontrun{ #' # see AutoScore-Ordinal Guidebook for the whole 5-step workflow #' data("sample_data_ordinal") # Output is named `label` #' out_split <- split_data(data = sample_data_ordinal, ratio = c(0.7, 0.1, 0.2)) #' train_set <- out_split$train_set #' validation_set <- out_split$validation_set #' ranking <- AutoScore_rank_Ordinal(train_set, ntree=100) #' mAUC <- AutoScore_parsimony_Ordinal( #' train_set = train_set, validation_set = validation_set, #' rank = ranking, max_score = 100, n_min = 1, n_max = 20, #' categorize = "quantile", quantiles = c(0, 0.05, 0.2, 0.8, 0.95, 1) #' ) #' } #' @references #' \itemize{ #' \item{Saffari SE, Ning Y, Feng X, Chakraborty B, Volovici V, Vaughan R, Ong #' ME, Liu N, AutoScore-Ordinal: An interpretable machine learning framework for #' generating scoring models for ordinal outcomes, arXiv:2202.08407} #' } #' @seealso \code{\link{AutoScore_rank_Ordinal}}, #' \code{\link{AutoScore_weighting_Ordinal}}, #' \code{\link{AutoScore_fine_tuning_Ordinal}}, #' \code{\link{AutoScore_testing_Ordinal}}. #' @export #' @import pROC AutoScore_parsimony_Ordinal <- function(train_set, validation_set, rank, link = "logit", max_score = 100, n_min = 1, n_max = 20, cross_validation = FALSE, fold = 10, categorize = "quantile", quantiles = c(0, 0.05, 0.2, 0.8, 0.95, 1), max_cluster = 5, do_trace = FALSE, auc_lim_min = 0.5, auc_lim_max = "adaptive") { link <- check_link(link = link) if (n_max > length(rank)) { warning("WARNING: the n_max (", n_max, ") is larger the number of all variables (", length(rank), "). We Automatically revise the n_max to ", length(rank)) n_max <- length(rank) } # Cross Validation scenario if (cross_validation == TRUE) { # Divide the data equally into n fold, record its index number index <- list() all <- 1:length(train_set[, 1]) for (i in 1:(fold - 1)) { a <- sample(all, trunc(length(train_set[, 1]) / fold)) index <- append(index, list(a)) all <- all[!(all %in% a)] } index <- c(index, list(all)) # Create a new variable auc_set to store all AUC value during the cross-validation auc_set <- data.frame(rep(0, n_max - n_min + 1)) # for each fold, generate train_set and validation_set for (j in 1:fold) { train_set_tmp <- train_set[-index[[j]], ] validation_set_temp <- train_set[index[[j]], ] # Go through AutoScore-Ordinal Module 2/3/4 in the loop mauc <- unlist(lapply(n_min:n_max, function(i) { variable_list <- names(rank)[1:i] train_set_1 <- train_set_tmp[, c(variable_list, "label")] validation_set_1 <- validation_set_temp[, c(variable_list, "label")] model_auc <- compute_auc_val_ord(train_set_1 = train_set_1, validation_set_1 = validation_set_1, variable_list = variable_list, link = link, categorize = categorize, quantiles = quantiles, max_cluster = max_cluster, max_score = max_score) model_auc })) # plot parsimony plot for each fold names(mauc) <- n_min:n_max # only print and plot when do_trace = TRUE if (do_trace) { print(paste("list of mAUC values for fold",j)) print(data.frame(mAUC = mauc)) plot(mauc, main = paste("Parsimony plot (cross validation) for fold",j), xlab = "Number of Variables", ylab = "Mean Area Under the Curve", col = "#2b8cbe", lwd = 2, type = "o")} # store AUC result from each fold into "auc_set" auc_set <- cbind(auc_set, data.frame(mAUC = mauc)) } # finish loop and then output final results averaged by all folds auc_set$rep.0..n_max...n_min...1. <- NULL auc_set$sum <- rowSums(auc_set) / fold cat("***list of fianl Mean AUC values through cross validation are shown below \n") print(data.frame(auc_set$sum)) plot(plot_auc(AUC = auc_set$sum, variables = names(rank)[n_min:n_max], num = n_min:n_max, auc_lim_min = auc_lim_min, auc_lim_max = auc_lim_max, ylab = "Mean Area Under the Curve", title = paste0("Final Parsimony plot based on ", fold, "-fold Cross Validation"))) return(auc_set) } else {# Go through AutoScore-Ordinal Module 2/3/4 in the loop mauc <- unlist(lapply(n_min:n_max, function(i) { cat("Select", i, "variables: ") variable_list <- names(rank)[1:i] train_set_1 <- train_set[, c(variable_list, "label")] validation_set_1 <- validation_set[, c(variable_list, "label")] model_auc <- compute_auc_val_ord(train_set_1 = train_set_1, validation_set_1 = validation_set_1, variable_list = variable_list, link = link, categorize = categorize, quantiles = quantiles, max_cluster = max_cluster, max_score = max_score) cat("Mean area under the curve:", model_auc, "\n") model_auc })) # output final results and plot parsimony plot plot(plot_auc(AUC = mauc, variables = names(rank)[n_min:n_max], num = n_min:n_max, auc_lim_min = auc_lim_min, auc_lim_max = auc_lim_max, ylab = "Mean Area Under the Curve", title = "Parsimony plot on the validation set")) names(mauc) <- names(rank)[n_min:n_max] mauc } } #' @title AutoScore STEP(iii) for ordinal outcomes: Generate the initial score #' with the final list of variables (Re-run AutoScore Modules 2+3) #' @inheritParams AutoScore_weighting #' @inheritParams AutoScore_parsimony_Ordinal #' @param final_variables A vector containing the list of selected variables, #' selected from Step(ii) \code{\link{AutoScore_parsimony_Ordinal}}. #' @return Generated \code{cut_vec} for downstream fine-tuning process STEP(iv) #' \code{\link{AutoScore_fine_tuning_Ordinal}}. #' @inherit AutoScore_parsimony_Ordinal references #' @param n_boot Number of bootstrap cycles to compute 95\% CI for performance #' metrics. #' @examples #' \dontrun{ #' data("sample_data_ordinal") # Output is named `label` #' out_split <- split_data(data = sample_data_ordinal, ratio = c(0.7, 0.1, 0.2)) #' train_set <- out_split$train_set #' validation_set <- out_split$validation_set #' ranking <- AutoScore_rank_Ordinal(train_set, ntree=100) #' num_var <- 6 #' final_variables <- names(ranking[1:num_var]) #' cut_vec <- AutoScore_weighting_Ordinal( #' train_set = train_set, validation_set = validation_set, #' final_variables = final_variables, max_score = 100, #' categorize = "quantile", quantiles = c(0, 0.05, 0.2, 0.8, 0.95, 1) #' ) #' } #' @seealso \code{\link{AutoScore_rank_Ordinal}}, #' \code{\link{AutoScore_parsimony_Ordinal}}, #' \code{\link{AutoScore_fine_tuning_Ordinal}}, #' \code{\link{AutoScore_testing_Ordinal}}. #' @export #' @import knitr AutoScore_weighting_Ordinal <- function(train_set, validation_set, final_variables, link = "logit", max_score = 100, categorize = "quantile", quantiles = c(0, 0.05, 0.2, 0.8, 0.95, 1), max_cluster = 5, n_boot = 100) { link <- check_link(link = link) # prepare train_set and validation_set cat("****Included Variables: \n") print(data.frame(variable_name = final_variables)) train_set_1 <- train_set[, c(final_variables, "label")] # AutoScore Module 2 : cut numeric and transform categories and generate "cut_vec" cut_vec <- get_cut_vec(df = train_set_1, categorize = categorize, quantiles = quantiles, max_cluster = max_cluster) train_set_2 <- transform_df_fixed(df = train_set_1, cut_vec = cut_vec) # AutoScore Module 3 : Score weighting score_table <- compute_score_table_ord(train_set_2 = train_set_2, max_score = max_score, variable_list = final_variables, link = link) cat("****Initial Scores: \n") print_scoring_table(scoring_table = score_table, final_variable = final_variables) # Intermediate evaluation based on Validation Set validation_set_1 <- validation_set[, c(final_variables, "label")] validation_set_1$total_score <- compute_final_score_ord( data = validation_set_1, final_variables = final_variables, cut_vec = cut_vec, scoring_table = score_table ) cat("***Performance (based on validation set):\n") print_performance_ordinal(label = validation_set_1$label, score = validation_set_1$total_score, n_boot = n_boot, report_cindex = FALSE) cat("***The cutoffs of each variables generated by the AutoScore-Ordinal are saved in cut_vec. You can decide whether to revise or fine-tune them \n") return(cut_vec) } #' @title AutoScore STEP(iv) for ordinal outcomes: Fine-tune the score by #' revising \code{cut_vec} with domain knowledge (AutoScore Module 5) #' @inherit AutoScore_fine_tuning description return examples #' @inherit AutoScore_parsimony_Ordinal references #' @inheritParams AutoScore_fine_tuning_Ordinal #' @inheritParams AutoScore_weighting_Ordinal #' @param cut_vec Generated from STEP(iii) \code{\link{AutoScore_weighting_Ordinal}}. #' @param report_cindex Whether to report generalized c-index for model #' evaluation (Default:FALSE for faster evaluation). #' @seealso \code{\link{AutoScore_rank_Ordinal}}, #' \code{\link{AutoScore_parsimony_Ordinal}}, #' \code{\link{AutoScore_weighting_Ordinal}}, #' \code{\link{AutoScore_testing_Ordinal}}. #' @import pROC #' @import ggplot2 #' @export AutoScore_fine_tuning_Ordinal <- function(train_set, validation_set, final_variables, link = "logit", cut_vec, max_score = 100, n_boot = 100, report_cindex = FALSE) { link <- check_link(link = link) # Prepare train_set and VadalitionSet train_set_1 <- train_set[, c(final_variables, "label")] # AutoScore Module 2 : cut numeric and transfer categories (based on fix "cut_vec" vector) train_set_2 <- transform_df_fixed(df = train_set_1, cut_vec = cut_vec) # AutoScore Module 3 : Score weighting score_table <- compute_score_table_ord(train_set_2 = train_set_2, max_score = max_score, variable_list = final_variables, link = link) cat("***Fine-tuned Scores: \n") print_scoring_table(scoring_table = score_table, final_variable = final_variables) validation_set_1 <- validation_set[, c(final_variables, "label")] validation_set_1$total_score <- compute_final_score_ord( data = validation_set_1, final_variables = final_variables, cut_vec = cut_vec, scoring_table = score_table ) cat("***Performance (based on Validation Set, after fine-tuning):\n") print_performance_ordinal(label = validation_set_1$label, score = validation_set_1$total_score, n_boot = n_boot, report_cindex = report_cindex) # Intermediate evaluation based on Validation Set after fine-tuning return(score_table) } #' @title AutoScore STEP(v) for ordinal outcomes: Evaluate the final score #' (AutoScore Module 6) #' @inherit AutoScore_testing description return examples #' @inherit AutoScore_parsimony_Ordinal references #' @param test_set A processed data.frame that contains data for testing #' purpose. This data.frame should have same format as train_set (same #' variable names and outcomes) #' @param scoring_table The final scoring table after fine-tuning, generated #' from STEP(iv) \code{\link{AutoScore_fine_tuning_Ordinal}}.Please follow the #' guidebook #' @inheritParams AutoScore_fine_tuning_Ordinal #' @param with_label Set to TRUE if there are labels in the test_set and #' performance will be evaluated accordingly (Default:TRUE). #' @seealso \code{\link{AutoScore_rank_Ordinal}}, #' \code{\link{AutoScore_parsimony_Ordinal}}, #' \code{\link{AutoScore_weighting_Ordinal}}, #' \code{\link{AutoScore_fine_tuning_Ordinal}}. #' @export AutoScore_testing_Ordinal <- function(test_set, final_variables, link = "logit", cut_vec, scoring_table, with_label = TRUE, n_boot = 100) { link <- check_link(link = link) # prepare test set: categorization and "assign_score" if (with_label) { test_set_1 <- test_set[, c(final_variables, "label")] } else { test_set_1 <- cbind(test_set[, final_variables], label = NA) } if (with_label) { test_set_1$total_score <- compute_final_score_ord( data = test_set_1, final_variables = final_variables, cut_vec = cut_vec, scoring_table = scoring_table ) cat("***Performance using AutoScore-Ordinal (based on unseen test Set):\n") print_performance_ordinal(label = test_set_1$label, score = test_set_1$total_score, n_boot = n_boot, report_cindex = TRUE) return(data.frame(pred_score = test_set_1$total_score, Label = test_set_1$label)) } else { return(data.frame(pred_score = test_set_1$total_score, Label = NA)) } } # Direct functions -------------------------------------------------------- #' @title AutoScore function for ordinal outcomes: Check whether the input #' dataset fulfil the requirement of the AutoScore #' @inheritParams check_data #' @inherit check_data return #' @examples #' data("sample_data_ordinal") #' check_data_ordinal(sample_data_ordinal) #' @export check_data_ordinal <- function(data) { surv_labels <- c("label_time", "label_status") #1. check label and binary if (is.null(data$label)) { if (any(surv_labels %in% names(data))) { stop(paste0( "ERROR: detected labels for survival data ('", paste(surv_labels, collapse = "', '"), "'). If outcome is survival, please use function 'check_data_survival()' and pipeline functions for survival outcome." )) } stop( "ERROR: for this dataset: These is no dependent variable 'label' to indicate the outcome. Please add one first\n" ) } if (!"factor" %in% class(data$label)) { warning("Please code outcome label variable as a factor\n") } if (length(levels(factor(data$label))) < 3) warning("Expecting 3 or more categories in an ordinal outcome. If 'label' only has 2 categories, please use function 'check_data()' and pipeline functions for binary outcome.") check_predictor(data_predictor = data[, setdiff(names(data), "label")]) } #' @title AutoScore-Ordinal function: Univariable Analysis #' @description Perform univariable analysis and generate the result table with #' odd ratios from proportional odds models. #' @inheritParams compute_uni_variable_table #' @inheritParams extract_or_ci_ord #' @inheritParams AutoScore_parsimony_Ordinal #' @return result of univariate analysis #' @examples #' data("sample_data_ordinal") #' # Using just a few variables to demonstrate usage: #' uni_table<-compute_uni_variable_table_ordinal(sample_data_ordinal[, 1:3]) #' @importFrom ordinal clm #' @export compute_uni_variable_table_ordinal <- function(df, link = "logit", n_digits = 3) { link <- check_link(link = link) x_names <- setdiff(names(df), "label") tb <- do.call("rbind", lapply(x_names, function(x_name) { model <- ordinal::clm(as.formula("label ~ ."), data = df[, c("label", x_name)], link = link, na.action = na.omit) extract_or_ci_ord(model = model, n_digits = n_digits) })) if (link != "logit") names(tb)[1] <- "exp(coefficient)" tb } #' @title AutoScore-Ordinal function: Multivariate Analysis #' @description Generate tables for multivariate analysis #' @inheritParams compute_multi_variable_table #' @inheritParams extract_or_ci_ord #' @inheritParams AutoScore_parsimony_Ordinal #' @return result of the multivariate analysis #' @examples #' data("sample_data_ordinal") #' # Using just a few variables to demonstrate usage: #' multi_table<-compute_multi_variable_table_ordinal(sample_data_ordinal[, 1:3]) #' @importFrom ordinal clm #' @export compute_multi_variable_table_ordinal <- function(df, link = "logit", n_digits = 3) { link <- check_link(link = link) model <- ordinal::clm(as.formula("label ~ ."), data = df, link = link, na.action = na.omit) tb <- extract_or_ci_ord(model = model, n_digits = n_digits) if (link == "logit") names(tb)[1] <- "adjusted_OR" if (link != "logit") names(tb)[1] <- "exp(adjusted_coefficient)" tb } #' @title AutoScore function for ordinal outcomes: Print predictive performance #' @description Print mean area under the curve (mAUC) and generalised c-index #' (if requested) #' @inheritParams print_roc_performance #' @inheritParams AutoScore_fine_tuning_Ordinal #' @seealso \code{\link{AutoScore_testing_Ordinal}} #' @return No return value and the ROC performance will be printed out directly. #' @export print_performance_ordinal <- function(label, score, n_boot = 100, report_cindex = FALSE) { n_boot <- round(n_boot) if (n_boot < 1) n_boot <- 1 if (all(is.na(score))) stop(simpleError("All entries in score are NA.")) i_na <- which(is.na(score)) if (length(i_na) > 0) { warning("NA in the score: ", length(i_na)) label <- label[-i_na] score <- score[-i_na] } perf_list <- evaluate_model_ord(label = label, score = score, n_boot = n_boot, report_cindex = report_cindex) if (n_boot > 1) { cat(sprintf( "mAUC: %.4f \t 95%% CI: %.4f-%.4f (from %d bootstrap samples)\n", perf_list$mauc, min(perf_list$mauc_ci), max(perf_list$mauc_ci), n_boot )) if (report_cindex) { cat(sprintf( "Generalised c-index: %.4f \t 95%% CI: %.4f-%.4f (from %d bootstrap samples)\n", perf_list$cindex, min(perf_list$cindex_ci), max(perf_list$cindex_ci), n_boot )) } } else { message(simpleMessage("To obtain 95% CI of metrics, set n_boot>1.\n")) cat(sprintf("mAUC: %.4f\n", perf_list$mauc)) if (report_cindex) { cat(sprintf("Generalised c-index: %.4f\n", perf_list$cindex)) } } } #' @title AutoScore function: Print conversion table for ordinal outcomes to map score to risk #' @inheritParams AutoScore_testing_Ordinal #' @param pred_score A \code{data.frame} with outcomes and final scores #' generated from \code{\link{AutoScore_fine_tuning_Ordinal}} #' @param score_breaks A vector of score breaks to group scores. The average #' predicted risk will be reported for each score interval in the lookup #' table. Users are advised to first visualise the predicted risk for all #' attainable scores to determine \code{scores} (see #' \code{\link{plot_predicted_risk}}) #' @param max_score Maximum attainable value of final scores. #' @param ... Additional parameters to pass to \code{\link[knitr]{kable}}. #' @seealso \code{\link{AutoScore_testing_Ordinal}} #' @inherit conversion_table return #' @export #' @importFrom tidyr pivot_wider #' @importFrom rlang .data #' @importFrom knitr kable conversion_table_ordinal <- function(pred_score, link = "logit", max_score = 100, score_breaks = seq(from = 5, to = 70, by = 5), ...) { lookup_long <- compute_prob_predicted(pred_score = pred_score, link = link, max_score = max_score, score_breaks = score_breaks) lookup <- pivot_wider(data = lookup_long, id_cols = .data$score, names_from = .data$`Outcome category`, values_from = .data$p_label) names(lookup) <- c("Score", paste("Predicted risk, category", names(lookup)[-1])) knitr::kable(lookup, ...) } # Internal functions ------------------------------------------------------ #' Internal function: Check link function #' @inheritParams AutoScore_parsimony_Ordinal check_link <- function(link) { match.arg(arg = tolower(link), choices = c("logit", "cloglog", "probit")) } #' Extract OR, CI and p-value from a proportional odds model #' @param model An ordinal regression model fitted using \code{\link[ordinal]{clm}}. #' @param n_digits Number of digits to print for OR or exponentiated #' coefficients (Default:3). extract_or_ci_ord <- function(model, n_digits = 3) { s_str <- paste0("%.", n_digits, "f") # Number of threshold parameters, not to include in results: n_theta <- length(model$alpha) summ <- summary(model) df_coef <- as.data.frame(summ$coefficients)[-(1:n_theta), ] conf_int <- confint(model) # Naturally excludes threshold parameters or_ci <- cbind(exp(cbind(OR = df_coef$Estimate, conf_int))) tb <- data.frame( OR = unlist(lapply(1:nrow(or_ci), function(i) { sprintf(paste0(s_str, " (", s_str, " - ", s_str, ")"), or_ci[i, 1], or_ci[i, 2], or_ci[i, 3]) })), `p value` = ifelse(df_coef$`Pr(>|z|)` < 0.001, "<0.001", sprintf("%.3f", df_coef$`Pr(>|z|)`)), check.names = FALSE ) rownames(tb) <- rownames(df_coef) tb } #' @title Internal function: Compute scoring table for ordinal outcomes based on #' training dataset #' @description Compute scoring table based on training dataset #' @inheritParams compute_score_table #' @inheritParams AutoScore_parsimony_Ordinal #' @param train_set_2 Processed training set after variable transformation #' @return A scoring table #' @importFrom ordinal clm #' @importFrom stats as.formula na.omit compute_score_table_ord <- function(train_set_2, max_score, variable_list, link) { link <- check_link(link = link) #AutoScore Module 3 : Score weighting # First-step ordinal regression model <- ordinal::clm(as.formula("label ~ ."), link = link, data = train_set_2) if (anyNA(model$alpha)) { stop(" Error: Ordinal regression produced invalid threshold. Check data.") } coef_vec <- model$beta if (anyNA(coef_vec)) { warning(" WARNING: Ordinal regression output contains NULL, Replace NULL with 1") coef_vec[which(is.na(coef_vec))] <- 1 } train_set_2 <- change_reference(df = train_set_2, coef_vec = coef_vec) # Second-step ordinal regression model <- ordinal::clm(as.formula("label ~ ."), link = link, data = train_set_2) coef_vec <- model$beta if (anyNA(coef_vec)) { warning(" WARNING: Ordinal regression output contains NA, Replace NA with 1") coef_vec[which(is.na(coef_vec))] <- 1 } # rounding for final scoring table "score_table" score_table <- add_baseline(train_set_2, round(coef_vec / min(coef_vec))) if (!is.null(max_score)) { # normalization according to "max_score" and regenerate score_table total_max <- max_score total <- 0 for (i in 1:length(variable_list)) { total <- total + max(score_table[grepl(variable_list[i], names(score_table))]) } score_table <- round(score_table / (total / total_max)) } return(score_table) } #' Internal function: Compute mAUC for ordinal predictions #' @param y An ordered factor representing the ordinal outcome, with length n #' and J categories. #' @param fx Either (i) a numeric vector of predictor (e.g., predicted scores) #' of length n or (ii) a numeric matrix of predicted cumulative probabilities #' with n rows and (J-1) columns. #' @return The mean AUC of J-1 cumulative AUCs (i.e., when evaluating #' the prediction of Y<=j, j=1,...,J-1). #' @import pROC compute_mauc_ord <- function(y, fx) { y <- as.numeric(y) J <- length(unique(y)) if (is.null(dim(fx))) {# fx is a vector of linear predictor auc_df <- do.call("rbind", lapply(1:(J - 1), function(j) { model_roc <- pROC::roc(response = y <= j, predictor = fx, quiet = TRUE) auc_ci_vec <- pROC::ci.auc(model_roc) data.frame(j = j, auc = auc_ci_vec[2], se = (auc_ci_vec[3] - auc_ci_vec[1]) / (1.96 * 2), auc_lower = auc_ci_vec[1], auc_upper = auc_ci_vec[3]) })) } else {# fx is a matrix with J-1 columns fx <- as.matrix(fx) if (nrow(fx) != length(y) | ncol(fx) != J - 1) { stop(simpleError("Wrong dimention for fx.")) } auc_df <- do.call("rbind", lapply(1:(J - 1), function(j) { model_roc <- pROC::roc(response = y <= j, predictor = fx[, j], quiet = TRUE) auc_ci_vec <- pROC::ci.auc(model_roc) data.frame(j = j, auc = auc_ci_vec[2], se = (auc_ci_vec[3] - auc_ci_vec[1]) / (1.96 * 2), auc_lower = auc_ci_vec[1], auc_upper = auc_ci_vec[3]) })) } mean(auc_df$auc) } #' @title Internal function: Compute mean AUC for ordinal outcomes based on #' validation set for plotting parsimony #' @description Compute mean AUC based on validation set for plotting parsimony #' @inheritParams compute_auc_val #' @inheritParams AutoScore_parsimony_Ordinal #' @return A list of mAUC for parsimony plot compute_auc_val_ord <- function(train_set_1, validation_set_1, variable_list, link, categorize, quantiles, max_cluster, max_score) { # AutoScore-Ordinal Module 2 : cut numeric and transfer categories cut_vec <- get_cut_vec(df = train_set_1, categorize = categorize, quantiles = quantiles, max_cluster = max_cluster) train_set_2 <- transform_df_fixed(df = train_set_1, cut_vec = cut_vec) validation_set_2 <- transform_df_fixed(df = validation_set_1, cut_vec = cut_vec) if (sum(is.na(validation_set_2)) > 0) { warning("NA in the validation_set_2: ", sum(is.na(validation_set_2))) } if (sum(is.na(train_set_2)) > 0) { warning("NA in the train_set_2: ", sum(is.na(train_set_2))) } # AutoScore-Ordinal Module 3 : Variable Weighting score_table <- compute_score_table_ord(train_set_2 = train_set_2, variable_list = variable_list, link = link, max_score = max_score) # Using "assign_score" to generate score based on new dataset and Scoring # table "score_table" validation_set_3 <- assign_score(df = validation_set_2, score_table = score_table) if (sum(is.na(validation_set_3)) > 0) { warning("NA in the validation_set_3: ", sum(is.na(validation_set_3))) } validation_set_3$total_score <- rowSums(subset( validation_set_3, select = setdiff(names(validation_set_3), "label") )) compute_mauc_ord(y = validation_set_3$label, fx = validation_set_3$total_score) } #' Internal function: Compute risk scores for ordinal data given variables #' selected, cut-off values and scoring table #' @inheritParams AutoScore_fine_tuning_Ordinal #' @inheritParams AutoScore_testing_Ordinal #' @param data A processed \code{data.frame} that contains data for validation #' or testing purpose. This \code{data.frame} must have variable \code{label} #' and should have same format as \code{train_set} (same variable names and #' outcomes) compute_final_score_ord <- function(data, final_variables, cut_vec, scoring_table) { data_1 <- data[, c(final_variables, "label")] data_2 <- transform_df_fixed(df = data_1, cut_vec = cut_vec) data_3 <- assign_score(df = data_2, score_table = scoring_table) d3 <- data_3[, final_variables] if (length(final_variables) == 1) d3 <- matrix(d3, ncol = 1) data_3$total_score <- as.numeric(apply(d3, 1, sum)) if (anyNA(data_3$total_score)) { warning(simpleWarning("NA in risk score. Check analyses.")) data_3$total_score[which(is.na(data_3$total_score))] <- 0 } data_3$total_score } #' Internal function: Evaluate model performance on ordinal data #' @inheritParams print_performance_ordinal #' @inheritParams compute_final_score_ord #' @inheritParams AutoScore_weighting_Ordinal #' @param report_cindex If generalized c-index should be reported alongside #' mAUC (Default:FALSE). #' @import survival #' @importFrom Hmisc rcorrcens #' @importFrom coxed bca #' @import ggplot2 #' @return Returns a list of the mAUC (mauc) and generalized c-index (cindex, if #' requested for) and their 95% bootstrap CIs (mauc_ci and cindex_ci). evaluate_model_ord <- function(label, score, n_boot, report_cindex = TRUE) { model_auc <- compute_mauc_ord(y = label, fx = score) # Compute bootstrap CI: score_list <- lapply(1:n_boot, function(iter) { rows <- sample(x = 1:length(score), size = length(score), replace = TRUE) data.frame(label = label[rows], score = score[rows]) }) model_auc_boot <- unlist(lapply(score_list, function(score_boot) { compute_mauc_ord(y = score_boot$label, fx = score_boot$score) })) model_auc_ci <- coxed::bca(model_auc_boot, conf.level = 0.95) if (report_cindex) { model_cindex <- Hmisc::rcorrcens( Surv(label, status) ~ pred_score, data = data.frame(pred_score = score, label = as.numeric(label), status = 1) )[, "C"] model_cindex_boot <- unlist(lapply(score_list, function(score_boot) { Hmisc::rcorrcens( Surv(label, status) ~ pred_score, data = data.frame(pred_score = score_boot$score, label = as.numeric(score_boot$label), status = 1) )[, "C"] })) model_cindex_ci <- coxed::bca(model_cindex_boot, conf.level = 0.95) } else { model_cindex <- NULL model_cindex_ci <- NULL } list(mauc = model_auc, mauc_ci = model_auc_ci, cindex = model_cindex, cindex_ci = model_cindex_ci) } #' Internal function: Inverse logit link #' @param x A numeric vector. inv_logit <- function(x) { exp(x) / (1 + exp(x)) } #' Internal function: Inverse cloglog link #' @param x A numeric vector. inv_cloglog <- function(x) { 1 - exp(-exp(x)) } #' Internal function: Inverse probit link #' @param x A numeric vector. #' @importFrom stats pnorm inv_probit <- function(x) { pnorm(x) } #' Internal function: generate probability matrix for ordinal outcomes given #' thresholds, linear predictor and link function #' @inheritParams AutoScore_parsimony_Ordinal #' @param theta numeric vector of thresholds #' @param z numeric vector of linear predictor estimate_p_mat <- function(theta, z, link) { n <- length(z) inv_link <- get(paste0("inv_", link)) cump_mat <- inv_link(matrix(rep(theta, n), nrow = n, byrow = TRUE) - matrix(rep(z, length(theta)), nrow = n, byrow = FALSE)) cump_mat <- cbind(0, cump_mat, 1) t(apply(cump_mat, 1, diff)) } #' Internal function: Group scores based on given score breaks, and use friendly #' names for first and last intervals. #' @inheritParams conversion_table_ordinal #' @param score numeric vector of scores. #' @importFrom car recode group_score <- function(score, max_score, score_breaks) { score_breaks <- sort(score_breaks) len <- length(score_breaks) level_min0 <- paste0("(-Inf,", min(score_breaks), "]") level_min <- paste0("[0,", min(score_breaks), "]") level_max0 <- paste0("(", max(score_breaks), ", Inf]") level_max <- paste0("(", max(score_breaks), ",", max_score, "]") all_scores <- c( level_min, paste0("(", score_breaks[1:(len - 1)], ",", score_breaks[-1], "]"), level_max ) score_group <- cut(score, breaks = c(-Inf, score_breaks, Inf), right = TRUE) factor(car::recode( var = score_group, recodes = paste0("'", level_min0, "'='", level_min, "'; ", "'", level_max0, "'='", level_max, "'") ), levels = all_scores) } #' Internal function: Based on given labels and scores, compute average #' predicted risks in given score intervals. #' @inheritParams conversion_table_ordinal #' @importFrom magrittr %>% #' @importFrom tidyr pivot_wider #' @importFrom ordinal clm #' @importFrom dplyr mutate group_by summarise rename #' @importFrom rlang .data compute_prob_predicted <- function(pred_score, link = "logit", max_score = 100, score_breaks = seq(from = 5, to = 70, by = 5)) { n_labels <- length(unique(pred_score$Label)) link <- check_link(link = link) # Compute theoretical predicted risk clm_model <- ordinal::clm(ordered(Label) ~ pred_score, link = link, data = pred_score) # Evaluate classification performance: score_table <- 0:max_score lookup <- data.frame(score = score_table, estimate_p_mat(theta = clm_model$alpha, z = clm_model$beta * score_table, link = link)) names(lookup)[-1] <- 1:n_labels lookup_long <- tidyr::pivot_longer(data = lookup, cols = -.data$score, names_to = "Label", values_to = "p_label") names(lookup)[-1] <- paste("Predicted risk, category", 1:length(unique(pred_score$Label))) # Group predicted risk accordingly lookup_long %>% mutate(score = group_score(score = .data$score, max_score = max_score, score_breaks = score_breaks)) %>% group_by(.data$Label, .data$score) %>% summarise(p_label = mean(.data$p_label)) %>% rename(`Outcome category` = .data$Label) %>% mutate(`Outcome category` = factor(.data$`Outcome category`)) } #' Internal function: Based on given labels and scores, compute proportion of #' subjects observed in each outcome category in given score intervals. #' @inheritParams conversion_table_ordinal #' @importFrom dplyr mutate group_by summarise rename right_join select n #' @importFrom rlang .data #' @importFrom magrittr %>% compute_prob_observed <- function(pred_score, link = "logit", max_score = 100, score_breaks = seq(from = 5, to = 70, by = 5)) { n_labels <- length(unique(pred_score$Label)) link <- check_link(link = link) obs_risk <- pred_score %>% mutate(score = group_score(score = .data$pred_score, max_score = max_score, score_breaks = score_breaks)) %>% group_by(.data$Label, .data$score) %>% summarise(n_label = n()) %>% group_by(.data$score) %>% mutate(n = sum(.data$n_label), p_label = .data$n_label / .data$n) # Fill up any missing with 0 all_scores <- levels(obs_risk$score) obs_risk_full <- data.frame( Label = ordered(rep(1:length(unique(pred_score$Label)), length(all_scores))), score = factor(rep(all_scores, each = length(unique(pred_score$Label))), levels = all_scores) ) obs_risk %>% right_join(obs_risk_full) %>% mutate(p_label = ifelse(is.na(.data$p_label), 0, .data$p_label)) %>% select(-.data$n_label) %>% rename(`Outcome category` = .data$Label) %>% mutate(`Outcome category` = factor(.data$`Outcome category`, ordered = FALSE)) } # Data -------------------------------------------------------------------- #' Simulated ED data with ordinal outcome #' #' @description Simulated data for 20,000 inpatient visits with demographic #' information, healthcare resource utilisation and associated laboratory #' tests and vital signs measured in the emergency department (ED). Data were #' simulated based on the dataset analysed in the AutoScore-Ordinal paper, and #' only includes a subset of variables (with masked variable names) for the #' purpose of demonstrating the AutoScore framework for ordinal outcomes. #' @inherit AutoScore_parsimony_Ordinal references "sample_data_ordinal" #' Simulated ED data with ordinal outcome (small sample size) #' #' @description 5,000 observations randomly sampled from #' \code{\link{sample_data_ordinal}}. It is used for demonstration only in the #' Guidebook. "sample_data_ordinal_small"
/scratch/gouwar.j/cran-all/cranData/AutoScore/R/AutoScore_Ordinal.R
# Pipeline_function -------------------------------------------------------- #' @title AutoScore STEP (1) for survival outcomes: Generate variable ranking #' List by machine learning (Random Survival Forest) (AutoScore Module 1) #' @details The first step in the AutoScore framework is variable ranking. We #' use Random Survival Forest (RSF) for survival outcome to identify the #' top-ranking predictors for subsequent score generation. This step #' correspond to Module 1 in the AutoScore-Survival paper. #' @inheritParams AutoScore_rank #' @inherit AutoScore_rank return #' @examples #' \dontrun{ #' # see AutoScore-Survival Guidebook for the whole 5-step workflow #' data("sample_data_survival") # Output is named `label_time` and `label_status` #' ranking <- AutoScore_rank_Survival(sample_data_survival, ntree = 50) #' } #' @references #' \itemize{ #' \item{Ishwaran, H., Kogalur, U. B., Blackstone, E. H., & Lauer, M. S. (2008). #' Random survival forests. The annals of applied statistics, 2(3), 841-860.} #' \item{Xie F, Ning Y, Yuan H, et al. AutoScore-Survival: Developing #' interpretable machine learning-based time-to-event scores with right-censored #' survival data. J Biomed Inform. 2022;125:103959. doi:10.1016/j.jbi.2021.103959} #' } #' @seealso \code{\link{AutoScore_parsimony_Survival}}, #' \code{\link{AutoScore_weighting_Survival}}, #' \code{\link{AutoScore_fine_tuning_Survival}}, #' \code{\link{AutoScore_testing_Survival}}. #' @importFrom randomForestSRC rfsrc vimp #' @export AutoScore_rank_Survival <- function(train_set, ntree = 50) { #set.seed(4) train_set <- AutoScore_impute(train_set) model <- rfsrc( Surv(label_time, label_status) ~ ., train_set, nsplit = 10, ntree = ntree, importance = "permute", do.trace = T ) # estimate variable importance importance <- vimp(model) # summarize importance importance_a <- sort(importance$importance, decreasing = T) cat("The ranking based on variable importance was shown below for each variable: \n") print(importance_a) plot_importance(importance_a) return(importance_a) } #' @title AutoScore STEP(ii) for survival outcomes: Select the best model with #' parsimony plot (AutoScore Modules 2+3+4) #' @inheritParams AutoScore_parsimony #' @param rank the raking result generated from AutoScore STEP(i) for survival #' outcomes (\code{\link{AutoScore_rank_Survival}}). #' @details This is the second step of the general AutoScore-Survival workflow for #' ordinal outcomes, to generate the parsimony plot to help select a #' parsimonious model. In this step, it goes through AutoScore-Survival Module 2,3 and #' 4 multiple times and to evaluate the performance under different variable #' list. The generated parsimony plot would give researcher an intuitive #' figure to choose the best models. If data size is small (eg, <5000), an #' independent validation set may not be a wise choice. Then, we suggest using #' cross-validation to maximize the utility of data. Set #' \code{cross_validation=TRUE}. #' @return List of iAUC (ie, the integrated AUC by integral under a time-dependent AUC curve #' for different number of variables #' @examples #' \dontrun{ #' # see AutoScore-Survival Guidebook for the whole 5-step workflow #' data("sample_data_survival") #' out_split <- split_data(data = sample_data_survival, ratio = c(0.7, 0.1, 0.2)) #' train_set <- out_split$train_set #' validation_set <- out_split$validation_set #' ranking <- AutoScore_rank_Survival(train_set, ntree=10) #' iAUC <- AutoScore_parsimony_Survival( #' train_set = train_set, validation_set = validation_set, #' rank = ranking, max_score = 100, n_min = 1, n_max = 20, #' categorize = "quantile", quantiles = c(0, 0.05, 0.2, 0.8, 0.95, 1) #' ) #' } #' @references #' \itemize{ #' \item{Xie F, Ning Y, Yuan H, et al. AutoScore-Survival: Developing #' interpretable machine learning-based time-to-event scores with right-censored #' survival data. J Biomed Inform. 2022;125:103959. doi:10.1016/j.jbi.2021.103959} #' } #' @seealso \code{\link{AutoScore_rank_Survival}}, #' \code{\link{AutoScore_weighting_Survival}}, #' \code{\link{AutoScore_fine_tuning_Survival}}, #' \code{\link{AutoScore_testing_Survival}}. #' @export #' @import pROC AutoScore_parsimony_Survival <- function(train_set, validation_set, rank, max_score = 100, n_min = 1, n_max = 20, cross_validation = FALSE, fold = 10, categorize = "quantile", quantiles = c(0, 0.05, 0.2, 0.8, 0.95, 1), max_cluster = 5, do_trace = FALSE, auc_lim_min = 0.5, auc_lim_max = "adaptive") { if (n_max > length(rank)) { warning( "WARNING: the n_max (", n_max, ") is larger the number of all variables (", length(rank), "). We Automatically revise the n_max to ", length(rank) ) n_max <- length(rank) } # Cross Validation scenario if (cross_validation == TRUE) { # Divide the data equally into n fold, record its index number #set.seed(4) index <- list() all <- 1:length(train_set[, 1]) for (i in 1:(fold - 1)) { a <- sample(all, trunc(length(train_set[, 1]) / fold)) index <- append(index, list(a)) all <- all[!(all %in% a)] } index <- c(index, list(all)) # Create a new variable auc_set to store all AUC value during the cross-validation auc_set <- data.frame(rep(0, n_max - n_min + 1)) # for each fold, generate train_set and validation_set for (j in 1:fold) { validation_set_temp <- train_set[index[[j]],] train_set_tmp <- train_set[-index[[j]],] #variable_list <- names(rank) AUC <- c() # Go through AUtoScore Module 2/3/4 in the loop for (i in n_min:n_max) { variable_list <- names(rank)[1:i] train_set_1 <- train_set_tmp[, c(variable_list, "label_time", "label_status")] validation_set_1 <- validation_set_temp[, c(variable_list, "label_time", "label_status")] model_roc <- compute_auc_val_survival( train_set_1, validation_set_1, variable_list, categorize, quantiles, max_cluster, max_score ) #print(auc(model_roc)) AUC <- c(AUC, model_roc) } # plot parsimony plot for each fold names(AUC) <- n_min:n_max # only print and plot when do_trace = TRUE if (do_trace) { print(paste("list of AUC values for fold", j)) print(data.frame(AUC)) plot( AUC, main = paste("Parsimony plot (cross validation) for fold", j), xlab = "Number of Variables", ylab = "Area Under the Curve", col = "#2b8cbe", lwd = 2, type = "o" ) } # store AUC result from each fold into "auc_set" auc_set <- cbind(auc_set, data.frame(AUC)) } # finish loop and then output final results averaged by all folds auc_set$rep.0..n_max...n_min...1. <- NULL auc_set$sum <- rowSums(auc_set) / fold cat("***list of final mean AUC values through cross-validation are shown below \n") print(data.frame(auc_set$sum)) plot(plot_auc(AUC = auc_set$sum, variables = names(rank)[n_min:n_max], num = n_min:n_max, auc_lim_min = auc_lim_min, auc_lim_max = auc_lim_max, ylab = "Integrated Area Under the Curve", title = paste0("Final Parsimony plot based on ", fold, "-fold Cross Validation"))) return(auc_set) } # if Cross validation is FALSE else{ AUC <- c() # Go through AutoScore Module 2/3/4 in the loop for (i in n_min:n_max) { cat(paste("Select", i, "Variable(s): ")) variable_list <- names(rank)[1:i] train_set_1 <- train_set[, c(variable_list, "label_time", "label_status")] validation_set_1 <- validation_set[, c(variable_list, "label_time", "label_status")] model_roc <- compute_auc_val_survival( train_set_1, validation_set_1, variable_list, categorize, quantiles, max_cluster, max_score ) cat(model_roc,"\n") AUC <- c(AUC, model_roc) } plot(plot_auc(AUC = AUC, variables = names(rank)[n_min:n_max], num = n_min:n_max, auc_lim_min = auc_lim_min, auc_lim_max = auc_lim_max, ylab = "Area Under the Curve", title = "Parsimony plot on the validation set")) names(AUC) <- names(rank)[n_min:n_max] return(AUC) } } #' @title AutoScore STEP(iii) for survival outcomes: Generate the initial score #' with the final list of variables (Re-run AutoScore Modules 2+3) #' @inheritParams AutoScore_weighting #' @inherit AutoScore_weighting return #' @inherit AutoScore_parsimony_Survival references #' @param time_point The time points to be evaluated using time-dependent AUC(t). #' @examples #' \dontrun{ #' data("sample_data_survival") # #' out_split <- split_data(data = sample_data_survival, ratio = c(0.7, 0.1, 0.2)) #' train_set <- out_split$train_set #' validation_set <- out_split$validation_set #' ranking <- AutoScore_rank_Survival(train_set, ntree=5) #' num_var <- 6 #' final_variables <- names(ranking[1:num_var]) #' cut_vec <- AutoScore_weighting_Survival( #' train_set = train_set, validation_set = validation_set, #' final_variables = final_variables, max_score = 100, #' categorize = "quantile", quantiles = c(0, 0.05, 0.2, 0.8, 0.95, 1), #' time_point = c(1,3,7,14,30,60,90) #' ) #' } #' @seealso \code{\link{AutoScore_rank_Survival}}, #' \code{\link{AutoScore_parsimony_Survival}}, #' \code{\link{AutoScore_fine_tuning_Survival}}, #' \code{\link{AutoScore_testing_Survival}}. #' @export #' @import knitr AutoScore_weighting_Survival <- function(train_set, validation_set, final_variables, max_score = 100, categorize = "quantile", max_cluster = 5, quantiles = c(0, 0.05, 0.2, 0.8, 0.95, 1), time_point = c(1,3,7,14,30,60,90)) { # prepare train_set and Validation Set cat("****Included Variables: \n") print(data.frame(variable_name = final_variables)) train_set_1 <- train_set[, c(final_variables, "label_time", "label_status")] validation_set_1 <- validation_set[, c(final_variables, "label_time", "label_status")] # AutoScore Module 2 : cut numeric and transfer categories and generate "cut_vec" cut_vec <- get_cut_vec( train_set_1, categorize = categorize, quantiles = quantiles, max_cluster = max_cluster ) train_set_2 <- transform_df_fixed(train_set_1, cut_vec) validation_set_2 <- transform_df_fixed(validation_set_1, cut_vec) # AutoScore Module 3 : Score weighting score_table <- compute_score_table_survival(train_set_2, max_score, final_variables) cat("****Initial Scores: \n") #print(as.data.frame(score_table)) print_scoring_table(scoring_table = score_table, final_variable = final_variables) # Using "assign_score" to generate score based on new dataset and Scoring table "score_table" validation_set_3 <- assign_score(validation_set_2, score_table) validation_set_3$total_score <- rowSums(subset(validation_set_3, select = names(validation_set_3)[names(validation_set_3) != c("label_status")& names(validation_set_3) != c("label_time")])) y_time <- validation_set_3$label_time y_status <- validation_set_3$label_status # Intermediate evaluation based on Validation Set print_performance_survival(validation_set_3$total_score, validation_set_3, time_point) cat( "***The cutoffs of each variable generated by the AutoScore are saved in cut_vec. You can decide whether to revise or fine-tune them \n" ) #print(cut_vec) return(cut_vec) } #' @title AutoScore STEP(iv) for survival outcomes: Fine-tune the score by #' revising cut_vec with domain knowledge (AutoScore Module 5) #' @inherit AutoScore_fine_tuning description return examples #' @inherit AutoScore_parsimony_Survival references #' @inheritParams AutoScore_fine_tuning #' @inheritParams AutoScore_weighting_Survival #' @param cut_vec Generated from STEP(iii) #' \code{AutoScore_weighting_Survival()}.Please follow the guidebook #' @param time_point The time points to be evaluated using time-dependent AUC(t). #' @seealso \code{\link{AutoScore_rank_Survival}}, #' \code{\link{AutoScore_parsimony_Survival}}, #' \code{\link{AutoScore_weighting_Survival}}, #' \code{\link{AutoScore_testing_Survival}}. #' @import pROC #' @import ggplot2 #' @export AutoScore_fine_tuning_Survival <- function(train_set, validation_set, final_variables, cut_vec, max_score = 100, time_point = c(1,3,7,14,30,60,90)) { # Prepare train_set and Validation Set train_set_1 <- train_set[, c(final_variables, "label_time","label_status")] validation_set_1 <- validation_set[, c(final_variables, "label_time","label_status")] # AutoScore Module 2 : cut numeric and transfer categories (based on fix "cut_vec" vector) train_set_2 <- transform_df_fixed(train_set_1, cut_vec = cut_vec) validation_set_2 <- transform_df_fixed(validation_set_1, cut_vec = cut_vec) # AutoScore Module 3 : Score weighting score_table <- compute_score_table_survival(train_set_2, max_score, final_variables) cat("***Fine-tuned Scores: \n") #print(as.data.frame(score_table)) print_scoring_table(scoring_table = score_table, final_variable = final_variables) # Using "assign_score" to generate score based on new dataset and Scoring table "score_table" validation_set_3 <- assign_score(validation_set_2, score_table) validation_set_3$total_score <- rowSums(subset(validation_set_3, select = names(validation_set_3)[names(validation_set_3) != c("label_status")& names(validation_set_3) != c("label_time")])) ## which name ="label" y_time <- validation_set_3$label_time y_status <- validation_set_3$label_status cat("***Performance (based on validation set, after fine-tuning):\n") print_performance_survival(validation_set_3$total_score, validation_set_3, time_point) return(score_table) } #' @title AutoScore STEP(v) for survival outcomes: Evaluate the final score with #' ROC analysis (AutoScore Module 6) #' @inherit AutoScore_testing description return examples #' @inherit AutoScore_parsimony_Survival references #' @inheritParams AutoScore_testing #' @inheritParams AutoScore_weighting_Survival #' @param cut_vec Generated from STEP(iii) #' \code{AutoScore_weighting_Survival()}.Please follow the guidebook #' @param with_label Set to TRUE if there are labels(`label_time` and `label_status`) in the test_set and #' performance will be evaluated accordingly (Default:TRUE). #' @param time_point The time points to be evaluated using time-dependent AUC(t). #' @seealso \code{\link{AutoScore_rank_Survival}}, #' \code{\link{AutoScore_parsimony_Survival}}, #' \code{\link{AutoScore_weighting_Survival}}, #' \code{\link{AutoScore_fine_tuning_Survival}}. #' @export AutoScore_testing_Survival <- function(test_set, final_variables, cut_vec, scoring_table, threshold = "best", with_label = TRUE, time_point = c(1,3,7,14,30,60,90)) { if (with_label) { # prepare test set: categorization and "assign_score" test_set_1 <- test_set[, c(final_variables, c("label_time","label_status"))] test_set_2 <- transform_df_fixed(test_set_1, cut_vec = cut_vec) test_set_3 <- assign_score(test_set_2, scoring_table) test_set_3$total_score <- rowSums(subset(test_set_3, select = names(test_set_3)[names(test_set_3) != c("label_status")& names(test_set_3) != c("label_time")])) test_set_3$total_score[which(is.na(test_set_3$total_score))] <- 0 # Final evaluation based on testing set cat("***Performance using AutoScore (based on unseen test Set):\n") print_performance_ci_survival(test_set_3$total_score, test_set_3, time_point) #Modelprc <- pr.curve(test_set_3$total_score[which(y_test == 1)],test_set_3$total_score[which(y_test == 0)],curve = TRUE) #values<-coords(model_roc, "best", ret = c("specificity", "sensitivity", "accuracy", "npv", "ppv", "precision"), transpose = TRUE) pred_score <- data.frame(pred_score = test_set_3$total_score, label_time = test_set_3$label_time, label_status = test_set_3$label_status) return(pred_score) } else { test_set_1 <- test_set[, c(final_variables)] test_set_2 <- transform_df_fixed(test_set_1, cut_vec = cut_vec) test_set_3 <- assign_score(test_set_2, scoring_table) test_set_3$total_score <- rowSums(subset(test_set_3, select = names(test_set_3)[names(test_set_3) != c("label_status")& names(test_set_3) != c("label_time")])) test_set_3$total_score[which(is.na(test_set_3$total_score))] <- 0 pred_score <- data.frame(pred_score = test_set_3$total_score, label_time = NA, label_status = NA) return(pred_score) } } # Direct_function --------------------------------------------------------- #' @title AutoScore function for survival data: Check whether the input #' dataset fulfill the requirement of the AutoScore #' @inheritParams check_data #' @inherit check_data return #' @examples #' data("sample_data_survival") #' check_data_survival(sample_data_survival) #' @export check_data_survival <- function(data) { #1. check label and binary if (!all(c("label_time", "label_status") %in% names(data))) stop( "ERROR: for this dataset: These is no dependent variable 'label_time' or 'label_status' to indicate the outcome. Please add one first\n" ) if (length(levels(factor(data$label_status))) != 2) warning("Please keep outcome status variable binary\n") check_predictor(data)} #' @title AutoScore function for survival outcomes: Print predictive performance #' @description Print mean area under the curve (mAUC) and generalised c-index #' (if requested) #' @param score Predicted score #' @param validation_set Dataset for generating performance #' @param time_point The time points to be evaluated using time-dependent AUC(t). #' @seealso \code{\link{AutoScore_testing_Ordinal}} #' @return No return value and the ROC performance will be printed out directly. #' @import survAUC survival #' @export print_performance_survival <- function(score, validation_set, time_point) { cat("Integrated AUC by all time points: " ) iAUC <- eva_performance_iauc(score, validation_set) Surv.rsp.new <- Surv(validation_set$label_time, validation_set$label_status) AUC_c<-concordancefit(Surv.rsp.new, -score) cat("C_index: ", AUC_c$concordance, "\n") #3. D-index #AUC_d<-D.index(x=score, surv.time=validation_set$time,surv.event=validation_set$status) #cat("D_index: ", AUC_d$d.index, "\n") #7. AUC_uno all AUC_uno <- AUC.uno(Surv.rsp.new, Surv.rsp.new, lpnew = score, times = time_point) AUC_t <- data.frame(time_point=time_point, AUC_t=AUC_uno$auc) cat("The AUC(t) are shown as bwlow:\n") print(AUC_t) } #' @title AutoScore function for survival outcomes: Print predictive performance with confidence intervals #' @description Print iAUC, c-index and time-dependent AUC as the predictive performance #' @inheritParams print_performance_survival #' @param n_boot Number of bootstrap cycles to compute 95\% CI for performance #' metrics. #' @seealso \code{\link{AutoScore_testing_Ordinal}} #' @return No return value and the ROC performance will be printed out directly. #' @import survAUC survival #' @export print_performance_ci_survival <- function(score, validation_set, time_point, n_boot = 100) { result_all<-data.frame(matrix(nrow=0,ncol=2+length(time_point))) for(i in 1:n_boot){ len<-length(validation_set[,1]) index<-sample(1:len,len,replace = TRUE) Val_tmp<-validation_set[index,] score_tmp <- score[index] result<-c() iAUC<- eva_performance_iauc(score_tmp, Val_tmp,print = FALSE) result<-c(result,iAUC) Surv.rsp.new <- Surv(Val_tmp$label_time, Val_tmp$label_status) AUC_c<-concordancefit(Surv.rsp.new, -score_tmp) result<-c(result,AUC_c$concordance) #3. D-index #AUC_d<-D.index(x=score, surv.time=validation_set$time,surv.event=validation_set$status) #cat("D_index: ", AUC_d$d.index, "\n") #7. AUC_uno all AUC_uno <- AUC.uno(Surv.rsp.new, Surv.rsp.new, lpnew = score_tmp, times = time_point) AUC_t <- data.frame(time_point=time_point, AUC_t=AUC_uno$auc) result<-c(result,AUC_t$AUC_t) result_all<-rbind(result_all,result)} #colSums(AUC_all_tmp) m<-colMeans(result_all) up<-sapply(result_all,function(x){quantile(x,probs = c(0.975))}) down<-sapply(result_all,function(x){quantile(x,probs = c(0.025))}) result_final<-paste0(round(m,3)," (",round(down,3),"-",round(up,3),")") #names(result_final)<-c("iAUC","C_index",time_point)} cat("Integrated AUC by all time points: " ) cat(result_final[1]) cat("\n") cat("C_index: ", result_final[2], "\n") AUC_t <- data.frame(time_point=time_point, AUC_t=result_final[-c(1,2)]) cat("The AUC(t) are shown as bwlow:\n") print(AUC_t) } #' @title AutoScore function for survival outcomes: Print scoring performance (KM curve) #' @description Print scoring performance (KM curve) for survival outcome #' @param pred_score Generated from STEP(v)\code{AutoScore_testing_Survival()} #' @param score_cut Score cut-offs to be used for the analysis #' @param risk.table Allowed values include: TRUE or FALSE specifying whether #' to show or not the risk table. Default is TRUE. #' @param title Title displayed in the KM curve #' @param legend.title Legend title displayed in the KM curve #' @param xlim limit for x #' @param break.x.by Threshold for analyze sensitivity, #' @param ... additional parameters to pass to #' \code{\link[survminer]{ggsurvplot}} . #' @seealso \code{\link{AutoScore_testing_Survival}} #' @return No return value and the KM performance will be plotted. #' @export #' @importFrom survminer ggsurvplot #' @importFrom survival survfit Surv plot_survival_km <- function(pred_score, score_cut = c(40,50,60),risk.table=TRUE, title=NULL, legend.title="Score", xlim=c(0,90),break.x.by=30, ...){ #library(survival) test_score<-pred_score$pred_score pred_score$test_score_cut<-cut(test_score, breaks = c(min(test_score),score_cut,max(test_score)), right = F, include.lowest = T, dig.lab = 3) sfit <- survfit(Surv(label_time, label_status) ~ test_score_cut, data = pred_score) summary(sfit, times=seq(min(pred_score$label_time),max(pred_score$label_time),1)) #summary(sfit, times=seq(0,365,30)) names(sfit$strata)<-levels(pred_score$test_score_cut) ggsurvplot(sfit, data = pred_score, conf.int=TRUE, pval=TRUE, title=title,risk.table=TRUE, palette = "lancet",legend.title = legend.title, pval.size=-1,ggtheme=theme_bw(),xlim=xlim,break.x.by=break.x.by, ...) } #' @title AutoScore function for survival outcomes: Print conversion table #' @description Print conversion table for survival outcomes #' @param pred_score a data frame with outcomes and final scores generated from \code{\link{AutoScore_testing_Survival}} #' @param score_cut Score cut-offs to be used for generating conversion table #' @param time_point The time points to be evaluated using time-dependent AUC(t). #' @seealso \code{\link{AutoScore_testing_Survival}} #' @return conversion table and the it will also be printed out directly. #' @export conversion_table_survival<- function(pred_score, score_cut = c(40,50,60), time_point = c(7,14,30,60,90)){ test_score<-pred_score$pred_score test_score_cut<-cut(test_score, breaks = c(min(test_score),score_cut,max(test_score)), right = F, include.lowest = T, dig.lab = 3) seed<-rep(1,length(time_point)+2) interval_table_test<-data.frame(seed) for(i in levels(test_score_cut)){ index<-test_score_cut==i r<-c() r<-c(r,length(pred_score$label_time[index])) r<-c(r,convert_percent(length(pred_score$label_time[index])/length(pred_score$label_time))) for(j in time_point) r<-c(r,convert_percent(mean(pred_score$label_time[index]<=j))) interval_table_test<-cbind(interval_table_test,r)} interval_table_test$seed<-NULL row.names(interval_table_test)<-c("Number of patients","Percentage of patients",paste0("t=",time_point)) names(interval_table_test)<- levels(test_score_cut) #ktable(interval_table_test) return(interval_table_test) } #' @title AutoScore function for survival outcomes: Univariate Analysis #' @description Generate tables for Univariate analysis for survival outcomes #' @param df data frame after checking #' @return result of the Univariate analysis for survival outcomes #' @examples #' data("sample_data_survival") #' uni_table<-compute_uni_variable_table_survival(sample_data_survival) #' @import survival #' @export compute_uni_variable_table_survival <- function(df) { uni_table <- data.frame() for (i in names(df)[names(df) != c("label_status")& names(df) != c("label_time")]) { model <- coxph(Surv(label_time, label_status) ~ ., data=subset(df, select = c("label_time","label_status", i))) coef_vec <- coef(model) a <- cbind(exp(cbind(OR = coef(model), confint.default(model))), summary(model)$coef[, "Pr(>|z|)"]) uni_table <- rbind(uni_table, a) } #uni_table <- # uni_table[!grepl("Intercept", row.names(uni_table), ignore.case = T), ] uni_table <- round(uni_table, digits = 3) uni_table$V4[uni_table$V4 < 0.001] <- "<0.001" uni_table$OR <- paste(uni_table$OR, "(", uni_table$`2.5 %`, "-", uni_table$`97.5 %`, ")", sep = "") uni_table$`2.5 %` <- NULL uni_table$`97.5 %` <- NULL names(uni_table)[names(uni_table) == "V4"] <- "p value" return(uni_table) } #' @title AutoScore function for survival outcomes: Multivariate Analysis #' @description Generate tables for multivariate analysis for survival outcomes #' @param df data frame after checking #' @return result of the multivariate analysis for survival outcomes #' @examples #' data("sample_data_survival") #' multi_table<-compute_multi_variable_table_survival(sample_data_survival) #' @import survival #' @export compute_multi_variable_table_survival <- function(df) { model <- coxph(Surv(label_time, label_status) ~ ., data = df) coef_vec <- coef(model) #model1 <- # glm(status ~ ., data = df,family = binomial, # na.action = na.omit) multi_table <- cbind(exp(cbind( adjusted_OR = coef(model), confint.default(model) )), summary(model)$coef[, "Pr(>|z|)"]) #multi_table <- # multi_table[!grepl("Intercept", row.names(multi_table), ignore.case = T), ] multi_table <- round(multi_table, digits = 3) multi_table <- as.data.frame(multi_table) multi_table$V4[multi_table$V4 < 0.001] <- "<0.001" multi_table$adjusted_OR <- paste( multi_table$adjusted_OR, "(", multi_table$`2.5 %`, "-", multi_table$`97.5 %`, ")", sep = "" ) multi_table$`2.5 %` <- NULL multi_table$`97.5 %` <- NULL names(multi_table)[names(multi_table) == "V4"] <- "p value" return(multi_table) } # Internal_function ------------------------------------------------------- ## built-in function for AutoScore below ## Those functions are cited by pipeline functions #' @title Internal function: Compute scoring table for survival outcomes based on training dataset #' @description Compute scoring table for survival outcomes based on training dataset #' @param train_set_2 Processed training set after variable transformation (AutoScore Module 2) #' @param max_score Maximum total score #' @param variable_list List of included variables #' @return A scoring table #' @import survival compute_score_table_survival <- function(train_set_2, max_score, variable_list) { #AutoScore Module 3 : Score weighting # First-step logistic regression model <- coxph(Surv(label_time, label_status) ~ ., data = train_set_2) coef_vec <- coef(model) if (length(which(is.na(coef_vec))) > 0) { warning(" WARNING: GLM output contains NULL, Replace NULL with 1") coef_vec[which(is.na(coef_vec))] <- 1 } train_set_2 <- change_reference(train_set_2, coef_vec) # Second-step logistic regression model <- coxph(Surv(label_time, label_status) ~ ., data = train_set_2) coef_vec <- coef(model) if (length(which(is.na(coef_vec))) > 0) { warning(" WARNING: GLM output contains NULL, Replace NULL with 1") coef_vec[which(is.na(coef_vec))] <- 1 } # rounding for final scoring table "score_table" coef_vec_tmp <- round(coef_vec / min(coef_vec)) score_table <- add_baseline(train_set_2, coef_vec_tmp) # normalization according to "max_score" and regenerate score_table total_max <- max_score total <- 0 for (i in 1:length(variable_list)) total <- total + max(score_table[grepl(variable_list[i], names(score_table))]) score_table <- round(score_table / (total / total_max)) return(score_table) } #' @title Internal function for survival outcomes: Compute AUC based on validation set for plotting parsimony #' @description Compute AUC based on validation set for plotting parsimony (survival outcomes) #' @param train_set_1 Processed training set #' @param validation_set_1 Processed validation set #' @param max_score Maximum total score #' @param variable_list List of included variables #' @param categorize Methods for categorize continuous variables. Options include "quantile" or "kmeans" #' @param quantiles Predefined quantiles to convert continuous variables to categorical ones. Available if \code{categorize = "quantile"}. #' @param max_cluster The max number of cluster (Default: 5). Available if \code{categorize = "kmeans"}. #' @return A List of AUC for parsimony plot compute_auc_val_survival <- function(train_set_1, validation_set_1, variable_list, categorize, quantiles, max_cluster, max_score) { # AutoScore Module 2 : cut numeric and transfer categories cut_vec <- get_cut_vec( train_set_1, categorize = categorize, quantiles = quantiles, max_cluster = max_cluster ) train_set_2 <- transform_df_fixed(train_set_1, cut_vec) validation_set_2 <- transform_df_fixed(validation_set_1, cut_vec) if (sum(is.na(validation_set_2)) > 0) warning("NA in the validation_set_2: ", sum(is.na(validation_set_2))) if (sum(is.na(train_set_2)) > 0) warning("NA in the train_set_2: ", sum(is.na(train_set_2))) # AutoScore Module 3 : Variable Weighting score_table <- compute_score_table_survival(train_set_2, max_score, variable_list) if (sum(is.na(score_table)) > 0) warning("NA in the score_table: ", sum(is.na(score_table))) # Using "assign_score" to generate score based on new dataset and Scoring table "score_table" validation_set_3 <- assign_score(validation_set_2, score_table) if (sum(is.na(validation_set_3)) > 0) warning("NA in the validation_set_3: ", sum(is.na(validation_set_3))) validation_set_3$total_score <- rowSums(subset(validation_set_3, select = names(validation_set_3)[names(validation_set_3) != "label_status" & names(validation_set_3) != "label_time"])) y_time <- validation_set_3$label_time y_status <- validation_set_3$label_status # plot_roc_curve(validation_set_3$total_score,as.numeric(y_validation)-1) # calculate iAUC value for plotting parsimony plot. model_roc <- eva_performance_iauc( validation_set_3$total_score, validation_set_3,print=FALSE) return(model_roc) } #' Internal function survival outcome: Calculate iAUC for validation set #' @inheritParams print_performance_survival #' @param print Whether to print out the final iAUC result #' @import survival #' @import survAUC eva_performance_iauc<-function(score,validation_set,print=TRUE){ AUC<-c() #1. iAUC_uno + Surv.rsp.new <- Surv(validation_set$label_time, validation_set$label_status) #iAUC km_fit_test <- survfit(Surv.rsp.new ~ 1, data = validation_set) km_time<-summary(km_fit_test)$time km_survival<-summary(km_fit_test)$surv km_time<-km_time[-length(km_time)] km_survival<-km_survival[-length(km_survival)] AUC_uno <- AUC.uno(Surv.rsp.new, Surv.rsp.new, lpnew = score, times = km_time) #iAUC<-IntAUC(AUC_uno$auc,AUC_uno$times,km_survival,90,auc.type = "cumulative") km_survival_w<-c(1,km_survival[-length(km_survival)]) km_survival_sum<-sum(km_survival_w-km_survival) weight<-(km_survival_w-km_survival)/km_survival_sum iAUC<-sum(weight*AUC_uno$auc) if(print){cat(iAUC) cat("\n")} return(iAUC) } convert_percent<-function(m){paste(round(100*m, 2), "%", sep="")} # Data -------------------------------------------------------------------- #' 20000 simulated MIMIC sample data with survival outcomes #' @description 20000 simulated samples, with the same distribution #' as the data in the MIMIC-III ICU database. Data were simulated based on the dataset #' analysed in the AutoScore-Survival paper. It is used for demonstration #' only in the Guidebook. Run \code{vignette("Guide_book", package = "AutoScore")} #' to see the guidebook or vignette. #' \itemize{ #' \item{Johnson, A., Pollard, T., Shen, L. et al. MIMIC-III, a freely accessible critical care database. Sci Data 3, 160035 (2016).} #' } "sample_data_survival" #' 1000 simulated MIMIC sample data with survival outcomes #' @description 1000 simulated samples, with the same distribution #' as the data in the MIMIC-III ICU database. Data were simulated based on the dataset #' analysed in the AutoScore-Survival paper. It is used for demonstration #' only in the Guidebook. Run \code{vignette("Guide_book", package = "AutoScore")} #' to see the guidebook or vignette. #' \itemize{ #' \item{Johnson, A., Pollard, T., Shen, L. et al. MIMIC-III, a freely accessible critical care database. Sci Data 3, 160035 (2016).} #' } "sample_data_survival_small"
/scratch/gouwar.j/cran-all/cranData/AutoScore/R/AutoScore_Survival.R
# For plotting predicted risk (binary & ordinal) ----- #' Internal function: Find column indices in design matrix that should be 1 #' @param x_inds A list of column indices corresponding to each final variable. find_one_inds <- function(x_inds) { if (length(x_inds) < 2) stop(simpleError("Should have at least 2 variables")) for (x1 in x_inds[[1]]) { for (x2 in x_inds[[2]]) { paste(x1, x2, sep = ";") } } x_first2 <- unlist(lapply(x_inds[[1]], function(x1) { lapply(x_inds[[2]], function(x2) paste(x1, x2, sep = ";")) })) if (length(x_inds) == 2) { return(x_first2) } else { unlist(find_one_inds(c(list(x_first2), x_inds[-(1:2)]))) } } #' Internal function: Based on \code{find_one_inds}, make a design matrix to #' compute all scores attainable. #' @param one_inds Output from \code{find_one_inds}. make_design_mat <- function(one_inds) { one_inds_num <- do.call("rbind", lapply(one_inds, function(one_ind) { as.integer(unlist(strsplit(x = one_ind, split = ";"))) })) x_mat <- matrix(0, nrow = nrow(one_inds_num), ncol = max(one_inds_num)) for (i in 1:nrow(one_inds_num)) x_mat[i, one_inds_num[i, ]] <- 1 x_mat } #' Internal function: Compute all scores attainable. #' @param final_variables A vector containing the list of selected variables. #' @param scoring_table The final scoring table after fine-tuning. #' @return Returns a numeric vector of all scores attainable. find_possible_scores <- function(final_variables, scoring_table) { x_inds <- list() n_prev <- 0 for (i in seq_along(final_variables)) { score_table_tmp <- scoring_table[grepl(final_variables[i], names(scoring_table))] len <- length(score_table_tmp) x_inds[[i]] <- 1:len + n_prev n_prev <- n_prev + len } one_inds <- find_one_inds(x_inds) x_mat <- make_design_mat(one_inds = one_inds) scores <- x_mat %*% scoring_table sort(unique(scores)) } #' AutoScore function for binary and ordinal outcomes: Plot predicted risk #' @param pred_score Output from \code{\link{AutoScore_testing}} (for binary #' outcomes) or \code{\link{AutoScore_testing_Ordinal}} (for ordinal #' outcomes). #' @param link (For ordinal outcome only) The link function used in ordinal #' regression, which must be the same as the value used to build the risk #' score. Default is \code{"logit"} for proportional odds model. #' @param max_score Maximum total score (Default: 100). #' @param final_variables A vector containing the list of selected variables, #' selected from Step(ii) \code{\link{AutoScore_parsimony}} (for binary #' outcomes) or \code{\link{AutoScore_parsimony_Ordinal}} (for ordinal #' outcomes). #' @param scoring_table The final scoring table after fine-tuning, generated #' from STEP(iv) \code{\link{AutoScore_fine_tuning}} (for binary outcomes) or #' \code{\link{AutoScore_fine_tuning_Ordinal}} (for ordinal outcomes). #' @param point_size Size of points in the plot. Default is 0.5. #' @export #' @importFrom dplyr mutate #' @importFrom tidyr pivot_longer #' @importFrom magrittr %>% #' @import ggplot2 #' @importFrom plotly ggplotly layout subplot #' @importFrom rlang .data plot_predicted_risk <- function(pred_score, link = "logit", max_score = 100, final_variables, scoring_table, point_size = 0.5) { n_class <- length(unique(pred_score$Label)) z <- seq(from = 0, to = max_score, by = 1) if (n_class == 2) { glm_model <- glm(Label ~ pred_score, family = "binomial", data = pred_score) pred_risk <- predict(object = glm_model, newdata = data.frame(pred_score = z), type = "response") pred_risk <- data.frame(outcome = pred_risk) } else { link <- check_link(link = link) # Compute theoretical predicted risk clm_model <- ordinal::clm(ordered(Label) ~ pred_score, link = link, data = pred_score) pred_risk <- estimate_p_mat(theta = clm_model$alpha, z = clm_model$beta * z, link = link) names(pred_risk) <- 1:ncol(pred_risk) } # Proportion of subjects with each score value: p_scores <- table(pred_score$pred_score) / nrow(pred_score) ps <- data.frame(Score = as.numeric(names(p_scores)), Proportion = as.numeric(p_scores)) %>% ggplot(aes_string(x = "Score", y = "Proportion")) + coord_cartesian(xlim = c(0, max_score)) + geom_bar(stat = "identity") + labs(y = "Proportion\nof subjects") + theme_classic() + theme(panel.grid.major = element_line(color = "grey90"), panel.grid.minor = element_line(color = "grey90"), axis.text = element_text(size = 12)) possible_scores <- find_possible_scores(final_variables = final_variables, scoring_table = scoring_table) dat_plot <- data.frame(Score = z, pred_risk, check.names = FALSE) %>% pivot_longer(-.data$Score, names_to = "Outcome category", values_to = "Predicted risk") %>% mutate(add_point = .data$Score %in% possible_scores) p <- dat_plot %>% ggplot(aes_string(x = "Score", y = "`Predicted risk`", color = "`Outcome category`")) + coord_cartesian(ylim = c(0, 1)) + geom_line() + geom_point(data = dat_plot[dat_plot$add_point, ], aes_string(x = "Score", y = "`Predicted risk`"), size = point_size) + labs(title = "Points indicate attainable final scores", x = "Score") + theme_classic() + theme(legend.position = "bottom", panel.grid.major = element_line(color = "grey90"), panel.grid.minor = element_line(color = "grey90"), axis.text = element_text(size = 12)) ps_title <- "Proportion of subjects" if (n_class == 2) p <- p + theme(legend.position = "none") plotly::subplot( plotly::ggplotly(p), plotly::ggplotly(ps), nrows = 2, heights = c(5, 2) / 7, margin = 0.08, shareX = FALSE, shareY = TRUE, titleX = TRUE ) } # For parsimony plot (all outcomes) ----- #' Internal function: Make parsimony plot #' @inheritParams AutoScore_parsimony #' @param AUC A vector of AUC values (or mAUC for ordinal outcomes). #' @param variables A vector of variable names #' @param num A vector of indices for AUC values to plot. Default is to plot all. #' @param ylab Title of y-axis #' @param title Plot title #' @import ggplot2 plot_auc <- function(AUC, variables, num = seq_along(variables), auc_lim_min, auc_lim_max, ylab = "Mean Area Under the Curve", title = "Parsimony plot on the validation set") { if (auc_lim_max == "adaptive") { auc_lim_max <- max(AUC) } dt <- data.frame(AUC = AUC, variables = factor(variables, levels = variables), num = num) p <- ggplot(data = dt, mapping = aes_string(x = "variables", y = "AUC")) + geom_bar(stat = "identity", fill = "steelblue") + coord_cartesian(ylim = c(auc_lim_min, auc_lim_max)) + theme_bw() + labs(x = "", y = ylab, title = title) + theme(legend.position = "none", axis.text = element_text(size = 12), axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) # Add number of variables to bar (resolves previous warning regarding dt$num): if (nrow(dt) >= 100) { p + geom_text(data = dt, aes_string(label = "num"), vjust = 1.5, colour = "white", angle = 90) } else { p + geom_text(data = dt, aes_string(label = "num"), vjust = 1.5, colour = "white") } } # For non-plot tasks (all outcomes) ----- #' @title AutoScore Function: Automatically splitting dataset to train, #' validation and test set, possibly stratified by label #' @param data The dataset to be split #' @param ratio The ratio for dividing dataset into training, validation and #' testing set. (Default: c(0.7, 0.1, 0.2)) #' @param cross_validation If set to \code{TRUE}, cross-validation would be used #' for generating parsimony plot, which is suitable for small-size data. #' Default to \code{FALSE} #' @param strat_by_label If set to \code{TRUE}, data splitting is stratified on #' the outcome variable. Default to \code{FALSE} #' @return Returns a list containing training, validation and testing set #' @examples #' data("sample_data") #' names(sample_data)[names(sample_data) == "Mortality_inpatient"] <- "label" #' set.seed(4) #' #large sample size #' out_split <- split_data(data = sample_data, ratio = c(0.7, 0.1, 0.2)) #' #small sample size #' out_split <- split_data(data = sample_data, ratio = c(0.7, 0, 0.3), #' cross_validation = TRUE) #' #large sample size, stratified #' out_split <- split_data(data = sample_data, ratio = c(0.7, 0.1, 0.2), #' strat_by_label = TRUE) #' @export split_data <- function(data, ratio, cross_validation = FALSE, strat_by_label = FALSE) { data <- as.data.frame(data) ratio <- ratio / sum(ratio) if (!strat_by_label) { n <- nrow(data) test_ratio <- ratio[3] validation_ratio <- ratio[2] test_index <- sample((1:n), test_ratio * n) validate_index <- sample((1:n)[!(1:n) %in% test_index], validation_ratio * n) # non cross validation: default if (cross_validation == FALSE) { train_set <- data[-c(validate_index, test_index), ] test_set <- data[test_index, ] validation_set <- data[validate_index, ] } else {# cross validation: train = validation train_set <- data[-c(test_index),] test_set <- data[test_index,] validation_set <- train_set } } else { index_list <- lapply(levels(data$label), function(j) { n_j <- which(data$label == j) ind_test <- sample(n_j, round(ratio[3] * length(n_j)), replace = FALSE) ind_val <- sample(setdiff(n_j, ind_test), round(ratio[2] * length(n_j)), replace = FALSE) list(test = ind_test, val = ind_val) }) index_test <- unlist(lapply(index_list, function(l) l$test)) index_validation <- unlist(lapply(index_list, function(l) l$val)) # non cross validation: default if (cross_validation == FALSE) { train_set <- data[-unlist(index_list), ] test_set <- data[index_test, ] validation_set <- data[index_validation, ] } else {# cross validation: train = validation train_set <- data[-c(index_test),] test_set <- data[index_test,] validation_set <- train_set } } return(list(train_set = train_set, validation_set = validation_set, test_set = test_set)) } #' @title AutoScore function: Descriptive Analysis #' @description Compute descriptive table (usually Table 1 in the medical #' literature) for the dataset. #' @param df data frame after checking and fulfilling the requirement of AutoScore #' @param ... additional parameters to pass to #' \code{\link[tableone]{print.TableOne}} and \code{\link[knitr]{kable}}. #' @examples #' data("sample_data") #' names(sample_data)[names(sample_data) == "Mortality_inpatient"] <- "label" #' compute_descriptive_table(sample_data) #' # Report median and IQR (instead of default mean and SD) for Age, and add a #' # caption to printed table: #' compute_descriptive_table(sample_data, nonnormal = "Age", #' caption = "Table 1. Patient characteristics") #' @return No return value and the result of the descriptive analysis will be printed out. #' @export #' @import tableone compute_descriptive_table <- function(df, ...) { label_name <- "label" surv_labels <- c("label_time", "label_status") if (all(surv_labels %in% names(df))) label_name <- surv_labels[2] descriptive_table <- CreateTableOne(vars = names(df), strata = label_name, data = df, addOverall = TRUE) kableone(descriptive_table, ...) } #' @title Internal Function: Change Reference category after first-step logistic regression (part of AutoScore Module 3) #' @param df A \code{data.frame} used for logistic regression #' @param coef_vec Generated from logistic regression #' @return Processed \code{data.frame} after changing reference category change_reference <- function(df, coef_vec) { # delete label first df_tmp <- subset(df, select = names(df)[!names(df) %in% c("label", "label_time", "label_status")]) names(coef_vec) <- gsub("[`]", "", names(coef_vec)) # remove the possible "`" in the names # one loops to go through all variable for (i in (1:length(df_tmp))) { var_name <- names(df_tmp)[i] var_levels <- levels(df_tmp[, i]) var_coef_names <- paste0(var_name, var_levels) coef_i <- coef_vec[which(names(coef_vec) %in% var_coef_names)] # if min(coef_tmp)<0, the current lowest one will be used for reference if (min(coef_i) < 0) { ref <- var_levels[which(var_coef_names == names(coef_i)[which.min(coef_i)])] df_tmp[, i] <- relevel(df_tmp[, i], ref = ref) } # char_tmp <- paste("^", names(df_tmp)[i], sep = "") # coef_tmp <- coef_vec[grepl(char_tmp, names(coef_vec))] # coef_tmp <- coef_tmp[!is.na(coef_tmp)] # if min(coef_tmp)<0, the current lowest one will be used for reference # if (min(coef_tmp) < 0) { # ref <- gsub(names(df_tmp)[i], "", names(coef_tmp)[which.min(coef_tmp)]) # df_tmp[, i] <- relevel(df_tmp[, i], ref = ref) # } } # add label again if(!is.null(df$label)) df_tmp$label <- df$label else{ df_tmp$label_time <- df$label_time df_tmp$label_status <- df$label_status} return(df_tmp) } #' @title Internal Function: Add baselines after second-step logistic regression (part of AutoScore Module 3) #' @param df A \code{data.frame} used for logistic regression #' @param coef_vec Generated from logistic regression #' @return Processed \code{vector} for generating the scoring table add_baseline <- function(df, coef_vec) { names(coef_vec) <- gsub("[`]", "", names(coef_vec)) # remove the possible "`" in the names df <- subset(df, select = names(df)[!names(df) %in% c("label", "label_time", "label_status")]) coef_names_all <- unlist(lapply(names(df), function(var_name) { paste0(var_name, levels(df[, var_name])) })) coef_vec_all <- numeric(length(coef_names_all)) names(coef_vec_all) <- coef_names_all # Remove items in coef_vec that are not meant to be in coef_vec_all # (i.e., the intercept) coef_vec_core <- coef_vec[which(names(coef_vec) %in% names(coef_vec_all))] i_coef <- match(x = names(coef_vec_core), table = names(coef_vec_all)) coef_vec_all[i_coef] <- coef_vec_core coef_vec_all } #' @title Internal Function: Automatically assign scores to each subjects given new data set and scoring table (Used for intermediate and final evaluation) #' @param df A \code{data.frame} used for testing, where variables keep before categorization #' @param score_table A \code{vector} containing the scoring table #' @return Processed \code{data.frame} with assigned scores for each variables assign_score <- function(df, score_table) { for (i in setdiff(names(df), c("label", "label_time", "label_status"))) { score_table_tmp <- score_table[grepl(i, names(score_table))] df[, i] <- as.character(df[, i]) for (j in 1:length(names(score_table_tmp))) { df[, i][df[, i] %in% gsub(i, "", names(score_table_tmp)[j])] <- score_table_tmp[j] } df[, i] <- as.numeric(df[, i]) } return(df) } getmode <- function(vect) { uniqvect <- unique(vect) freq <- tabulate(match(vect, uniqvect)) mode_tmp <- uniqvect[which.max(freq)] if (is.na(mode_tmp)){ mode_tmp <- uniqvect[order(freq, decreasing=T)[2]] } return(mode_tmp) } #' @title AutoScore function for datasets with binary outcomes: Check whether the input dataset fulfill the requirement of the AutoScore #' @param data The data to be checked #' @examples #' data("sample_data") #' names(sample_data)[names(sample_data) == "Mortality_inpatient"] <- "label" #' check_data(sample_data) #' @return No return value, the result of the checking will be printed out. #' @export check_data <- function(data) { #1. check label and binary if (!"label" %in% names(data)) stop( "ERROR: for this dataset: These is no dependent variable 'label' to indicate the outcome. Please add one first\n" ) if (length(levels(factor(data$label))) != 2) warning("Please keep outcome label variable binary\n") check_predictor(data)} #' Internal function: Check predictors #' @param data_predictor Predictors to be checked #' @return No return value, the result of the checking will be printed out. check_predictor <- function(data_predictor) { data <- data_predictor data <- as.data.frame(data, check.names = FALSE) symbol_vec <- c(",", "\\[", "]", "\\(", ")") any_error <- FALSE # Check for error ---- # 1. Checking variable names name_has_symbol <- lapply(names(data), function(x_name) { unlist(lapply(symbol_vec, function(s) grepl(pattern = s, x = x_name))) }) if (any(unlist(name_has_symbol))) { any_error <- TRUE message(simpleMessage( "WARNING: Special character detected in variable names -----\n" )) for (i in seq_along(names(data))) { has_symb <- name_has_symbol[[i]] if (any(has_symb)) { message(simpleMessage(sprintf( " * Variable name '%s' has symbols '%s'.\n", names(data)[i], paste(symbol_vec[which(has_symb)], collapse = "','") ))) } } message(simpleMessage("SUGGESTED ACTION: For each variable name above, consider relpacing special characters by '_'.\n")) } # Check for duplicated/nested name name_dup <- lapply(names(data), function(i) { # If any variable name has opening bracket but no closing bracket, cannot # search for it. Manually handle these if (grepl(pattern = "\\(", x = i) && !grepl(pattern = ")", x = i)) { i <- paste(unlist(strsplit(x = i, split = "\\(")), collapse = "\\(") } if (grepl(pattern = "\\[", x = i) && !grepl(pattern = "]", x = i)) { i <- paste(unlist(strsplit(x = i, split = "\\[")), collapse = "\\[") } if (sum(grepl(i, names(data))) > 1) { a <- names(data)[grepl(i, names(data))] a[a != i] } }) n_name_dup <- unlist(lapply(name_dup, length)) if (sum(n_name_dup) > 0) { i_dup <- which(n_name_dup > 0) message(simpleMessage(sprintf( "\nWARNING: Duplicated/nested variable names detected: -----\n" ))) for (i in i_dup) { message(simpleMessage(sprintf( " * Variable name '%s' duplicated/nested in variables: '%s'.\n", names(data)[i], paste(name_dup[[i]], collapse = "','") ))) } message(simpleMessage("SUGGESTED ACTION: For each variable above, please rename them using 'names(*your_data*)' before using the AutoScore. Consider appending '_1', '_2', etc, to variable names.\n")) } # 2. Check levels for factors i_factors <- which(unlist(lapply(data, is.factor))) if (length(i_factors) > 0) { data_f <- data[, i_factors] if (length(i_factors) == 1) { data_f <- data.frame(data_f) names(data_f) <- names(data)[i_factors] } nlevels_gt_10 <- unlist(lapply(data_f, nlevels)) > 10 if (any(nlevels_gt_10)) { any_error <- TRUE message(simpleMessage(sprintf( "\nWARNING: Too many categories (>10) in variables: '%s' -----\n", paste(names(i_factors[which(nlevels_gt_10)]), collapse = "','") ))) } level_has_symbol <- unlist(lapply(data_f, function(x) { any(grepl(pattern = ",", x = levels(x))) })) if (any(level_has_symbol)) { any_error <- TRUE message(simpleMessage(sprintf( "\nWARNING: Special character ',' detected in categorical variables: '%s'. -----\nSUGGESTED ACTION: For each variable above, use 'levels(*your_variable*)' to change the name of the levels before using the AutoScore. Consider replacing ',' with '_'.\n", paste(names(data[i_factors[which(level_has_symbol)]])) ))) } } # 3. Check if any variable is character instead of factor i_character <- which(unlist(lapply(data, function(x_i) { (!is.factor(x_i) && !is.numeric(x_i) && !is.integer(x_i) && !is.logical(x_i)) }))) if (length(i_character) > 0) { any_error <- TRUE message(simpleMessage(sprintf( "\nWARNING: Variables coded as character instead of factor: '%s' -----\nSUGGESTED ACTION: Convert each variable above to factor (using 'data$xxx <- as.factor(data$xxx))') or numeric (using 'data$xxx <- as.numeric(data$xxx))') as appropriate before using AutoScore.\n", paste(names(i_character), collapse = "','") ))) } # If no error, print message if (!any_error) { message(simpleMessage("Data type check passed. \n")) } else { message(simpleMessage("\n!!IMPORTANT: Please check data again for other potential issues after handling all issues reported above.\n")) } # Check for missing ---- missing_rate <- colSums(is.na(data)) if (sum(missing_rate) == 0) { message(simpleMessage("No NA in data. \n")) } else { n_missing <- missing_rate[which(missing_rate > 0)] tb_missing <- data.frame( `Variable name` = names(n_missing), `No. missing` = n_missing, `%missing` = round(n_missing / nrow(data) * 100, 2), check.names = FALSE ) message(simpleMessage("\nWARNING: NA detected in data: -----\n")) print(tb_missing) message(simpleMessage("SUGGESTED ACTION:\n * Consider imputation and supply AutoScore with complete data.\n")) message(simpleMessage(paste0( " * Alternatively, AutoScore can handle missing values as a separate 'Unknown' category, IF:\n", " - you believe the missingness in your dataset is informative, AND\n", " - missing is prevalent enough that you prefer to preserve them as NA rather than removing or doing imputation, AND\n", " - missing is not too prevalent, which may make results unstable.\n" ))) } } #' Internal function: induce informative missing in a single variable #' @param x Variable to induce missing in. #' @inheritParams induce_informative_missing induce_median_missing <- function(x, prop_missing) { if (anyNA(x)) stop(simpleError("x already has missing.")) x_mdn <- median(x) sqr_diff <- (x - x_mdn) ^ 2 # Probability of missing is based on square difference from median: smaller # difference means higher probability # Handle 0 difference: p <- 1 / sqr_diff p <- ifelse(sqr_diff == 0, min(p), p) i_na <- sample(x = 1:length(x), size = round(prop_missing * length(x)), replace = FALSE, prob = p) x[i_na] <- NA x } # For missing-realted issues ----- #' Internal function: induce informative missing to sample data in the package #' to demonstrate how AutoScore handles missing as a separate category #' @details Assume subjects with normal values (i.e., values close to the #' median) are more likely to not have measurements. #' @param df A data.frame of sample data. #' @param vars_to_induce Names of variables to induce informative missing in. #' Default is c("Lab_A", "Vital_A"). #' @param prop_missing Proportion of missing to induce for each #' \code{vars_to_induce}. Can be a single value for a common proportion for #' all variables (default is 0.4), or a vector with same length as #' \code{vars_to_induce}. #' @return Returns \code{df} with selected columns modified to have missing. induce_informative_missing <- function(df, vars_to_induce = c("Lab_A", "Vital_A"), prop_missing = 0.4) { # Only work on variable names that can be found in df: vars_not_in <- vars_to_induce[which(!vars_to_induce %in% names(df))] if (length(vars_not_in) > 0) { warning(simpleWarning(paste( "The following variables are not in df and are ignored:", toString(vars_not_in) ))) } vars_to_induce <- setdiff(vars_to_induce, vars_not_in) prop_missing <- unlist(as.numeric(prop_missing)) if (length(prop_missing) == 1) { prop_missing <- rep(prop_missing, length = length(vars_to_induce)) } if (length(prop_missing) != length(vars_to_induce)) { stop(simpleError(paste( "prop_missing should be either a single value or a vector of length", length(vars_to_induce) ))) } names(prop_missing) <- vars_to_induce # Induce missing to each variable: for (var in vars_to_induce) { df[, var] <- induce_median_missing(x = df[, var], prop_missing = prop_missing[var]) } df } AutoScore_impute <- function(train_set, validation_set = NULL){ n_train <- nrow(train_set) df <- rbind(train_set, validation_set) for (i in 1:ncol(df)){ # print(names(df)[i]) if (names(df)[i] == "label" & sum(is.na(df[, i])) > 0){ stop("There are missing values in the outcome: label! Please fix it and try again") } if (names(df)[i] == "label_time" & sum(is.na(df[, i])) > 0){ stop("There are missing values in the outcome: label_time!Please fix it and try again") } if (names(df)[i] == "label_status" & sum(is.na(df[, i])) > 0){ stop("There are missing values in the outcome:lable_status!Please fix it and try again") } var = df[1:n_train, i] if (is.factor(df[, i]) & sum(is.na(df[, i])) > 0){ df[is.na(df[, i]), i] <- getmode(var) } else if (is.numeric(var) & sum(is.na(var)) > 0) { df[is.na(df[, i]), i] <- median(var, na.rm=T) } } if (is.null(validation_set)){ return(df) } else { train_set <- df[1:n_train, ] validation_set <- df[(n_train+1):nrow(df), ] return(list("train" = train_set, "validation" = validation_set)) } } #' @title Internal function: Calculate cut_vec from the training set (AutoScore Module 2) #' @param df training set to be used for calculate the cut vector #' @param categorize Methods for categorize continuous variables. Options include "quantile" or "kmeans" (Default: "quantile"). #' @param quantiles Predefined quantiles to convert continuous variables to categorical ones. (Default: c(0, 0.05, 0.2, 0.8, 0.95, 1)) Available if \code{categorize = "quantile"}. #' @param max_cluster The max number of cluster (Default: 5). Available if \code{categorize = "kmeans"}. #' @return cut_vec for \code{transform_df_fixed} get_cut_vec <- function(df, quantiles = c(0, 0.05, 0.2, 0.8, 0.95, 1), #by default max_cluster = 5, categorize = "quantile") { # Generate cut_vec for downstream usage cut_vec <- list() for (i in setdiff(names(df), c("label", "label_time", "label_status"))) { # for factor variable if (is.factor(df[, i])) { if (length(levels(df[, i])) < 10) #(next)() else stop("ERROR: The number of categories should be less than 10") (next)() else warning("WARNING: The number of categories should be less than 10", i) } ## mode 1 - quantiles if (categorize == "quantile") { # options(scipen = 20) #print("in quantile") cut_off_tmp <- quantile(df[, i], quantiles, na.rm=T) cut_off_tmp <- unique(cut_off_tmp) cut_off <- signif(cut_off_tmp, 3) # remain 3 digits #print(cut_off) ## mode 2 k-means clustering } else if (categorize == "k_means") { #print("using k-means") clusters <- kmeans(na.omit(df[, i]), max_cluster) cut_off_tmp <- c() for (j in unique(clusters$cluster)) { #print(min(df[,i][clusters$cluster==j])) #print(length(df[,i][clusters$cluster==j])) cut_off_tmp <- append(cut_off_tmp, min(df[, i][clusters$cluster == j], na.rm=T)) #print(cut_off_tmp) } cut_off_tmp <- append(cut_off_tmp, max(df[, i], na.rm=T)) cut_off_tmp <- sort(cut_off_tmp) #print(names(df)[i]) #assert (length(cut_off_tmp) == 6) cut_off_tmp <- unique(cut_off_tmp) cut_off <- signif(cut_off_tmp, 3) cut_off <- unique(cut_off) #print (cut_off) } else { stop('ERROR: please specify correct method for categorizing: "quantile" or "k_means".') } l <- list(cut_off) names(l)[1] <- i cut_vec <- append(cut_vec, l) #print("****************************cut_vec*************************") #print(cut_vec) } ## delete min and max for each cut-off (min and max will be captured in the new dataset) if (length(cut_vec) != 0) { ## in case all the variables are categorical for (i in 1:length(cut_vec)) { if (length(cut_vec[[i]]) <= 2) cut_vec[[i]] <- c("let_binary") else cut_vec[[i]] <- cut_vec[[i]][2:(length(cut_vec[[i]]) - 1)] } } return(cut_vec) } #' @title Internal function: Categorizing continuous variables based on cut_vec (AutoScore Module 2) #' @param df dataset(training, validation or testing) to be processed #' @param cut_vec fixed cut vector #' @return Processed \code{data.frame} after categorizing based on fixed cut_vec #' @export transform_df_fixed <- function(df, cut_vec) { j <- 1 # for loop going through all variables for (i in setdiff(names(df), c("label", "label_time", "label_status"))) { if (is.factor(df[, i])) { df[, i] <- factor(car::recode(var = df[, i], recodes = "NA = 'Unknown'")) if (length(levels(df[, i])) < 10) (next)() else stop("ERROR: The number of categories should be less than 9") } ## make conresponding cutvec for validation_set: cut_vec_new #df<-validation_set_1 #df<-train_set_1 vec <- df[, i] cut_vec_new <- cut_vec[[j]] if (cut_vec_new[1] == "let_binary") { vec[vec != getmode(vec)] <- paste0("not_", getmode(vec)) vec <- as.factor(vec) df[, i] <- vec } else{ if (min(vec, na.rm=T) < cut_vec[[j]][1]) cut_vec_new <- c(floor(min(df[, i], na.rm=T)) - 100, cut_vec_new) if (max(vec, na.rm=T) >= cut_vec[[j]][length(cut_vec[[j]])]) cut_vec_new <- c(cut_vec_new, ceiling(max(df[, i], na.rm=T) + 100)) cut_vec_new_tmp <- signif(cut_vec_new, 3) cut_vec_new_tmp <- unique(cut_vec_new_tmp) ###revised update## df_i_tmp <- cut( df[, i], breaks = cut_vec_new_tmp, right = F, include.lowest = F, dig.lab = 3 ) # xmin<-as.character(min(cut_vec_new_tmp)) xmax<-as.character(max(cut_vec_new_tmp)) ## delete min and max for the Interval after discretion: validation_set if (min(vec, na.rm=T) < cut_vec[[j]][1]) levels(df_i_tmp)[1] <- gsub(".*,", "(,", levels(df_i_tmp)[1]) if (max(vec, na.rm=T) >= cut_vec[[j]][length(cut_vec[[j]])]) levels(df_i_tmp)[length(levels(df_i_tmp))] <- gsub(",.*", ",)", levels(df_i_tmp)[length(levels(df_i_tmp))]) df[, i] <- as.factor(ifelse(is.na(df[, i]), "*Unknown", as.character(df_i_tmp))) } j <- j + 1 } return(df) } #' @title AutoScore Function: Print scoring tables for visualization #' @param scoring_table Raw scoring table generated by AutoScore step(iv) \code{\link{AutoScore_fine_tuning}} #' @param final_variable Final included variables #' @return Data frame of formatted scoring table #' @seealso \code{\link{AutoScore_fine_tuning}}, \code{\link{AutoScore_weighting}} #' @export #' @importFrom knitr kable print_scoring_table <- function(scoring_table, final_variable) { #library(knitr) table_tmp <- data.frame() var_name <- names(scoring_table) var_name_tmp<-gsub("\\(.*","",var_name) var_name_tmp<-gsub("\\[.*","",var_name_tmp) var_name_tmp<-gsub("\\*.*","",var_name_tmp) # for "Unknown" category for (i in 1:length(final_variable)) { var_tmp <- final_variable[i] # num <- grepl(var_tmp, var_name) # rank_indicator[which(rank_indicator=="")]<-max(as.numeric(rank_indicator[-which(rank_indicator=="")]))+1 { num <- grep(var_tmp, var_name_tmp) if (sum(grepl(",", var_name[num])) == 0) { # for categorical variable table_1 <- data.frame(name = var_name[num], value = unname(scoring_table[num])) table_1$rank_indicator <- c(seq(1:nrow(table_1))) interval <- c(gsub( pattern = var_tmp, replacement = "", table_1$name )) table_1$interval <- interval table_2 <- table_1[order(table_1$interval),] table_2$variable <- c(var_tmp, rep("", (nrow(table_2) - 1))) table_3 <- rbind(table_2, rep("", ncol(table_2))) table_tmp <- rbind(table_tmp, table_3) } else { num <- grep(paste("^",var_tmp,"$", sep=""), var_name_tmp) table_1 <- data.frame(name = var_name[num], value = unname(scoring_table[num])) rank_indicator <- gsub(".*,", "", table_1$name) rank_indicator <- gsub(")", "", rank_indicator) rank_indicator <- gsub(".*\\*", "", rank_indicator) # for "Unknown" category rank_indicator[which(rank_indicator == "")] <- max(as.numeric(rank_indicator[-which(rank_indicator %in% c("", "Unknown"))])) + 1 # rank_indicator <- as.numeric(rank_indicator) table_1$rank_indicator <- rank_indicator if ("Unknown" %in% rank_indicator){ table_unknown <- table_1[rank_indicator == "Unknown", ] table_unknown$interval <- "Unknown" table_1 <- table_1[rank_indicator != "Unknown", ] table_1$rank_indicator <- as.numeric(table_1$rank_indicator) } else { table_unknown <- data.frame() table_1$rank_indicator <- as.numeric(table_1$rank_indicator) } table_2 <- table_1[order(table_1$rank_indicator),] { if (length(rank_indicator[rank_indicator != "Unknown"]) == 2) { # table_1$rank_indicator <- rank_indicator # table_2 <- table_1[order(table_1$rank_indicator),] interval <- c(paste0("<", table_2$rank_indicator[1])) interval <- c(interval, paste0(">=", table_2$rank_indicator[length(rank_indicator) - 1])) # table_2$interval <- interval # table_2 <- rbind(table_2, table_unknown) # table_2$variable <- c(var_tmp, rep("", (nrow( # table_2 # ) - 1))) # table_3 <- rbind(table_2, rep("", ncol(table_2))) # table_tmp <- rbind(table_tmp, table_3) } else{ interval <- c(paste0("<", table_2$rank_indicator[1])) for (j in 1:(length(table_2$rank_indicator) - 2)) { interval <- c( interval, paste0( "[", table_2$rank_indicator[j], ",", table_2$rank_indicator[j + 1], ")" ) ) } interval <- c(interval, paste0(">=", table_2$rank_indicator[length(rank_indicator) - 1])) } table_2$interval <- interval table_2 <- rbind(table_2, table_unknown) table_2$variable <- c(var_tmp, rep("", (nrow( table_2 ) - 1))) table_3 <- rbind(table_2, rep("", ncol(table_2))) table_tmp <- rbind(table_tmp, table_3) } } } } table_tmp <- table_tmp[1:(nrow(table_tmp) - 1),] table_final <- data.frame( variable = table_tmp$variable, interval = table_tmp$interval, point = table_tmp$value ) table_kable_format <- kable(table_final, align = "llc", caption = "AutoScore-created scoring model", format = "rst") print(table_kable_format) invisible(table_final) } #' @title Internal Function: Print plotted variable importance #' @param ranking vector output generated by functions: AutoScore_rank, AutoScore_rank_Survival or AutoScore_rank_Ordinal #' @seealso \code{\link{AutoScore_rank}}, \code{\link{AutoScore_rank_Survival}}, \code{\link{AutoScore_rank_Ordinal}} #' @export #' @import ggplot2 plot_importance <- function(ranking){ df = data.frame(Imp = ranking, Index = factor(names(ranking), levels = rev(names(ranking)))) p <- ggplot(data = df, mapping = aes_string(y = "Index", x = "Imp")) + geom_bar(stat = "identity", fill = "deepskyblue") + scale_y_discrete(expand = expansion(mult = 0, add = 1)) + labs(x = "Importance", y = "", title = "Importance Ranking") + theme(plot.title = element_text(hjust = 0.5, vjust = 0.3), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"), axis.text = element_text(size = 13.5), axis.text.x = element_text(angle = 0, vjust = 0, hjust = 0)) if(nrow(df) > 25){ p <- p + theme(axis.text.y = element_text(size = 13.5 - 1.5 * (floor(nrow(df)/21))-1)) } print(p) }
/scratch/gouwar.j/cran-all/cranData/AutoScore/R/common.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( echo = TRUE, collapse = TRUE, comment = "#>", cache = FALSE ) options(rmarkdown.html_vignette.check_title = FALSE)
/scratch/gouwar.j/cran-all/cranData/AutoScore/inst/doc/brief_intro.R
--- title: "AutoScore: An Interpretable Machine Learning-Based Automatic Clinical Score Generator" output: rmarkdown::html_vignette: toc: yes vignette: > %\VignetteIndexEntry{Brief Introduction} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( echo = TRUE, collapse = TRUE, comment = "#>", cache = FALSE ) options(rmarkdown.html_vignette.check_title = FALSE) ``` # AutoScore Introduction AutoScore is a novel machine learning framework to automate the development of interpretable clinical scoring models. AutoScore consists of six modules: 1) variable ranking with machine learning, 2) variable transformation, 3) score derivation, 4) model selection, 5) domain knowledge-based score fine-tuning, and 6) performance evaluation. The original AutoScore structure is elaborated in [this article](http://dx.doi.org/10.2196/21798) and its flowchart is shown in the following figure. AutoScore was originally designed for binary outcomes and later extended to [survival outcomes](http://dx.doi.org/10.1016/j.jbi.2021.103959) and [ordinal outcomes](https://doi.org/10.48550/arxiv.2202.08407). AutoScore could seamlessly generate risk scores using a parsimonious set of variables for different types of clinical outcomes, which can be easily implemented and validated in clinical practice. Moreover, it enables users to build transparent and interpretable clinical scores quickly in a straightforward manner. **Please go to our [bookdown page](https://nliulab.github.io/AutoScore/) for a full tutorial on AutoScore usage.** ## Usage The five pipeline functions constitute the 5-step AutoScore-based process for generating point-based clinical scores for binary, survival and ordinal outcomes. This 5-step process gives users the flexibility of customization (e.g., determining the final list of variables according to the parsimony plot, and fine-tuning the cutoffs in variable transformation): - STEP(i): `AutoScore_rank()`or `AutoScore_rank_Survival()` or `AutoScore_rank_Ordinal()` - Rank variables with machine learning (AutoScore Module 1) - STEP(ii): `AutoScore_parsimony()` or `AutoScore_parsimony_Survival()` or `AutoScore_parsimony_Ordinal()` - Select the best model with parsimony plot (AutoScore Modules 2+3+4) - STEP(iii): `AutoScore_weighting()` or `AutoScore_weighting_Survival()` or `AutoScore_weighting_Ordinal()` - Generate the initial score with the final list of variables (Re-run AutoScore Modules 2+3) - STEP(iv): `AutoScore_fine_tuning()` or `AutoScore_fine_tuning_Survival()` or `AutoScore_fine_tuning_Ordinal()` - Fine-tune the score by revising `cut_vec` with domain knowledge (AutoScore Module 5) - STEP(v): `AutoScore_testing()` or `AutoScore_testing_Survival()` or `AutoScore_testing_Ordinal()` - Evaluate the final score with ROC analysis (AutoScore Module 6) We also include several optional functions in the package, which could help with data analysis and result reporting. Please go to our [bookdown page](https://nliulab.github.io/AutoScore/) for a full tutorial on AutoScore usage. ## Citation ### Core paper * Xie F, Chakraborty B, Ong MEH, Goldstein BA, Liu N. [AutoScore: A machine learning-based automatic clinical score generator and its application to mortality prediction using electronic health records](http://dx.doi.org/10.2196/21798). JMIR Medical Informatics 2020; 8(10): e21798. ### Method extensions * Xie F, Ning Y, Yuan H, Goldstein BA, Ong MEH, Liu N, Chakraborty B. [AutoScore-Survival: Developing interpretable machine learning-based time-to-event scores with right-censored survival data](http://dx.doi.org/10.1016/j.jbi.2021.103959). Journal of Biomedical Informatics 2022; 125: 103959. * Saffari SE, Ning Y, Xie F, Chakraborty B, Volovici V, Vaughan R, Ong MEH, Liu N, [AutoScore-Ordinal: An interpretable machine learning framework for generating scoring models for ordinal outcomes](https://doi.org/10.48550/arxiv.2202.08407), arXiv:2202.08407. * Ning Y, Li S, Ong ME, Xie F, Chakraborty B, Ting DS, Liu N. [A novel interpretable machine learning system to generate clinical risk scores: An application for predicting early mortality or unplanned readmission in a retrospective cohort study](https://doi.org/10.1371/journal.pdig.0000062). PLOS Digit Health 2022; 1(6): e0000062. ## Contact - Feng Xie (Email: <[email protected]>) - Yilin Ning (Email: <[email protected]>) - Nan Liu (Email: <[email protected]>) # AutoScore package installation Install from GitHub or CRAN: ``` r # From Github install.packages("devtools") library(devtools) install_github(repo = "nliulab/AutoScore", build_vignettes = TRUE) # From CRAN (recommended) install.packages("AutoScore") ``` [devtools]: https://github.com/hadley/devtools Load AutoScore package: ``` r library(AutoScore) ``` Please go to our [bookdown page](https://nliulab.github.io/AutoScore/) for a full tutorial on AutoScore usage.
/scratch/gouwar.j/cran-all/cranData/AutoScore/inst/doc/brief_intro.Rmd
--- title: "AutoScore: An Interpretable Machine Learning-Based Automatic Clinical Score Generator" output: rmarkdown::html_vignette: toc: yes vignette: > %\VignetteIndexEntry{Brief Introduction} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( echo = TRUE, collapse = TRUE, comment = "#>", cache = FALSE ) options(rmarkdown.html_vignette.check_title = FALSE) ``` # AutoScore Introduction AutoScore is a novel machine learning framework to automate the development of interpretable clinical scoring models. AutoScore consists of six modules: 1) variable ranking with machine learning, 2) variable transformation, 3) score derivation, 4) model selection, 5) domain knowledge-based score fine-tuning, and 6) performance evaluation. The original AutoScore structure is elaborated in [this article](http://dx.doi.org/10.2196/21798) and its flowchart is shown in the following figure. AutoScore was originally designed for binary outcomes and later extended to [survival outcomes](http://dx.doi.org/10.1016/j.jbi.2021.103959) and [ordinal outcomes](https://doi.org/10.48550/arxiv.2202.08407). AutoScore could seamlessly generate risk scores using a parsimonious set of variables for different types of clinical outcomes, which can be easily implemented and validated in clinical practice. Moreover, it enables users to build transparent and interpretable clinical scores quickly in a straightforward manner. **Please go to our [bookdown page](https://nliulab.github.io/AutoScore/) for a full tutorial on AutoScore usage.** ## Usage The five pipeline functions constitute the 5-step AutoScore-based process for generating point-based clinical scores for binary, survival and ordinal outcomes. This 5-step process gives users the flexibility of customization (e.g., determining the final list of variables according to the parsimony plot, and fine-tuning the cutoffs in variable transformation): - STEP(i): `AutoScore_rank()`or `AutoScore_rank_Survival()` or `AutoScore_rank_Ordinal()` - Rank variables with machine learning (AutoScore Module 1) - STEP(ii): `AutoScore_parsimony()` or `AutoScore_parsimony_Survival()` or `AutoScore_parsimony_Ordinal()` - Select the best model with parsimony plot (AutoScore Modules 2+3+4) - STEP(iii): `AutoScore_weighting()` or `AutoScore_weighting_Survival()` or `AutoScore_weighting_Ordinal()` - Generate the initial score with the final list of variables (Re-run AutoScore Modules 2+3) - STEP(iv): `AutoScore_fine_tuning()` or `AutoScore_fine_tuning_Survival()` or `AutoScore_fine_tuning_Ordinal()` - Fine-tune the score by revising `cut_vec` with domain knowledge (AutoScore Module 5) - STEP(v): `AutoScore_testing()` or `AutoScore_testing_Survival()` or `AutoScore_testing_Ordinal()` - Evaluate the final score with ROC analysis (AutoScore Module 6) We also include several optional functions in the package, which could help with data analysis and result reporting. Please go to our [bookdown page](https://nliulab.github.io/AutoScore/) for a full tutorial on AutoScore usage. ## Citation ### Core paper * Xie F, Chakraborty B, Ong MEH, Goldstein BA, Liu N. [AutoScore: A machine learning-based automatic clinical score generator and its application to mortality prediction using electronic health records](http://dx.doi.org/10.2196/21798). JMIR Medical Informatics 2020; 8(10): e21798. ### Method extensions * Xie F, Ning Y, Yuan H, Goldstein BA, Ong MEH, Liu N, Chakraborty B. [AutoScore-Survival: Developing interpretable machine learning-based time-to-event scores with right-censored survival data](http://dx.doi.org/10.1016/j.jbi.2021.103959). Journal of Biomedical Informatics 2022; 125: 103959. * Saffari SE, Ning Y, Xie F, Chakraborty B, Volovici V, Vaughan R, Ong MEH, Liu N, [AutoScore-Ordinal: An interpretable machine learning framework for generating scoring models for ordinal outcomes](https://doi.org/10.48550/arxiv.2202.08407), arXiv:2202.08407. * Ning Y, Li S, Ong ME, Xie F, Chakraborty B, Ting DS, Liu N. [A novel interpretable machine learning system to generate clinical risk scores: An application for predicting early mortality or unplanned readmission in a retrospective cohort study](https://doi.org/10.1371/journal.pdig.0000062). PLOS Digit Health 2022; 1(6): e0000062. ## Contact - Feng Xie (Email: <[email protected]>) - Yilin Ning (Email: <[email protected]>) - Nan Liu (Email: <[email protected]>) # AutoScore package installation Install from GitHub or CRAN: ``` r # From Github install.packages("devtools") library(devtools) install_github(repo = "nliulab/AutoScore", build_vignettes = TRUE) # From CRAN (recommended) install.packages("AutoScore") ``` [devtools]: https://github.com/hadley/devtools Load AutoScore package: ``` r library(AutoScore) ``` Please go to our [bookdown page](https://nliulab.github.io/AutoScore/) for a full tutorial on AutoScore usage.
/scratch/gouwar.j/cran-all/cranData/AutoScore/vignettes/brief_intro.Rmd
#' @title Automated Backward Stepwise GLM #' #' @description Takes in a dataframe and the dependent variable (in quotes) as arguments, splits the data into testing and training, #' and uses automated backward stepwise selection to build a series of multiple regression models on the training data. #' Each model is then evaluated on the test data and model evaluation metrics are computed for each model. These metrics #' are provided as plots. Additionally, the model metrics are ranked and average rank is taken. The model with the best #' average ranking among the metrics is displayed (along with its formula). By default, metrics are all given the same #' relative importance (i.e., weights) when calculating average model metric rank, but if the user desires to give more #' weight to one or more metrics than the others they can specify these weights as arguments (default for weights is 1). #' As of v 0.2.0, only the family = gauissian(link = 'identity') argument is provided within the glm function. #' @param data A dataframe with one column as the dependent variable and the others as independent variables #' @param dv The column name of the (continuous) dependent variable (must be in quotes, i.e., 'Dependent_Variable') #' @param aic_wt Weight given to the rank value of the AIC of the model fitted on the training data (used when calculating mean model performance, default = 1) #' @param r_wt Weight given to the rank value of the Pearson Correlation between the predicted and actual values on the test data (used when calculating mean model performance, default = 1) #' @param mae_wt Weight given to the rank value of Mean Absolute Error on the test data (used when calculating mean model performance, default = 1) #' @param r_squ_wt Weight given to the rank value of R-Squared on the test data (used when calculating mean model performance, default = 1) #' @param train_prop Proportion of the data used for the training data set #' @param random_seed Random seed to use when splitting into training and testing data #' #' @return This function returns a plot for each metric by model and the best overall model with the formula used when fitting that model #' #' @examples #' dt <- mtcars #' stepwise_model <- backwd_stepwise_glm(data = dt, #' dv = 'mpg', #' aic_wt = 1, #' r_wt = 0.8, #' mae_wt = 1, #' r_squ_wt = 0.8, #' train_prop = 0.6, #' random_seed = 5) #' stepwise_model #' @export # dv argument must be a string (i.e., it must have quotes) backwd_stepwise_glm = function(data, dv, aic_wt=1, r_wt=1, mae_wt=1, r_squ_wt=1, train_prop = 0.7, random_seed = 7){ # save data as dt dt = data # rename the given dv to 'DV' in dt names(dt)[names(dt) == dv] = 'DV' # Split into testing/training nrows = nrow(dt) train_size = floor(train_prop*nrows) set.seed(random_seed) train_idx = sample(nrows, train_size, replace = F) dt_train = dt[train_idx, ] dt_test = dt[-train_idx, ] # instantiate an empty vector to store model formulas model_formulas_vector = vector() # Instantiate an empty vector of AIC for which to append AIC values model_AIC_vector = vector() # instantiate empty vector to store predictions predictions_vector = vector() # instantiate an empty vector to store residuals residuals_vector = vector() # Instantiate an empty vector of pearson correlations between predicted and actual for which to append pearson r values model_r_vector = vector() # Instantiate an empty vector of R-squared for which to append R-Squared values model_R_Squared_vector = vector() # Instantiate an empty vector of MAE for which to append MAE values model_MAE_vector = vector() # store the first formula with every variable except the DV as a predictor formula = as.formula('DV ~ .') # instantiate a counter count = 0 for (i in 1:(length(names(dt_test))-2)) { # -2 because we don't want a simple linear regression at the end # add 1 to the counter count = count + 1 # fit model model = glm(formula, data = dt_train, family = gaussian(link = 'identity')) # save the model formula to a vector model_formula = model$formula # add model_formula to model_formulas_vector model_formulas_vector = c(model_formulas_vector, model_formula) # get aic model_aic = model$aic # append this to the vector model_first_aic model_AIC_vector = c(model_AIC_vector, model_aic) # get predictions predictions = predict(model, dt_test) # append to predictions_vector predictions_vector = c(predictions_vector, predictions) # get the pearson correlation between predictions and actual values correlation = cor(predictions, dt_test$DV) # append correlation to model_r_vector model_r_vector = c(model_r_vector, correlation) # get the r-squared value r_squared = 1 - (sum((dt_test$DV-predictions)^2)/sum((dt_test$DV-mean(dt_test$DV))^2)) # append to model_R_Squared_vector model_R_Squared_vector = c(model_R_Squared_vector, r_squared) # get residuals resids = dt_test$DV - predictions # append to residuals_vector residuals_vector = c(residuals_vector, resids) # get the absolute values of residuals abs_residuals = abs(resids) # get mean of the absolute values of residuals (MAE) MAE = mean(abs_residuals) # Append to the model_MAE_vector model_MAE_vector = c(model_MAE_vector, MAE) # Get variable importance #library(caret) var_imp = as.data.frame(varImp(model)) # Turn into a data frame imp = data.frame(overall = var_imp$Overall, names = rownames(var_imp)) # Order it by importance imp_ordered = imp[order(imp$overall, decreasing = TRUE),] # Get only names from this vector with the last name removed names_vector = as.vector(imp_ordered[1:nrow(imp_ordered)-1,2]) # remove quotes and add plus sig for formula names_no_quotes = noquote(paste(names_vector, collapse='+')) # save the new formula formula = as.formula(paste(paste('DV ~'), names_no_quotes)) } # Print a message if the loop was completed successfuly if (count == length(dt_test) - 2) { print(noquote(paste("Success: There were", count, 'models build and there were', length(dt_test) - 1, 'independent variables in the origninal model'))) } else print(noquote('Failure: There was an error, review code')) # rank the values in each of the vectors (1=worst, largest number = best) # AIC: Lower is better model_AIC_vector_rank = rank(model_AIC_vector) * aic_wt # Pearson r: Higher is better model_r_vector_rank = rank(-model_r_vector) * r_wt # R-Squared: Higher is better model_R_Squared_vector_rank = rank(-model_R_Squared_vector) * r_squ_wt # MAE: Lower is better model_MAE_vector_rank = rank(model_MAE_vector) * mae_wt # create a data frame with these ranked vectors dt_rank = data.frame(model_AIC_vector_rank, model_r_vector_rank, model_R_Squared_vector_rank, model_MAE_vector_rank) # get an average ranking for each model dt_rank$Avg_Rank = rowMeans(dt_rank, na.rm = FALSE, dims = 1) # which row (i.e., model has lowest ranking) best_model = which.min(dt_rank$Avg_Rank) # insert plots # AIC plot # get the index of the minimum AIC value to programmatically plot it best_model_AIC = which.min(model_AIC_vector) # find the value of the lowest AIC lowest_aic = min(model_AIC_vector) # round this value rounded_lowest_aic = round(lowest_aic, 3) # Plot the AIC (y) by model number (x) ymin = min(model_AIC_vector, na.rm = TRUE) ymax = max(model_AIC_vector, na.rm = TRUE) plot(model_AIC_vector, type="o", col="blue", ylim=c(ymin, ymax), ylab='Model AIC', xlab='Model Number', main= print(paste('Model', best_model_AIC, 'has the lowest AIC:', rounded_lowest_aic))) # Pearson correlation # get the index of the minimum AIC value to programmatically plot it best_model_r = which.max(model_r_vector) # find the value of the highest r highest_r = max(model_r_vector) # round this value rounded_highest_r = round(highest_r, 4) # Plot the r (y) by model number (x) ymin = min(model_r_vector, na.rm = TRUE) ymax = max(model_r_vector, na.rm = TRUE) plot(model_r_vector, type="o", col="blue", ylim=c(ymin, ymax), ylab='Model r', xlab='Model Number', main= print(paste('Model', best_model_r, 'has the highest r:', rounded_highest_r))) # MAE # get the index of the minimum MAE value to programmatically plot it best_model_MAE = which.min(model_MAE_vector) # find the value of the minimum MAE lowest_MAE = min(model_MAE_vector) # round this value rounded_lowest_MAE = round(lowest_MAE, 4) # Plot the MAE (y) by model number (x) ymin = min(model_MAE_vector, na.rm = TRUE) ymax = max(model_MAE_vector, na.rm = TRUE) plot(model_MAE_vector, type="o", col="blue", ylim=c(ymin, ymax), ylab='Model MAE', xlab='Model Number', main= print(paste('Model', best_model_MAE, 'has the lowest MAE:', rounded_lowest_MAE))) # R squared # get the index of the maximum r squared value to programmatically plot it best_model_R_squared = which.max(model_R_Squared_vector) # find the value of the maximum R-squared highest_r_squared = max(model_R_Squared_vector) # round this value rounded_highest_r_squared = round(highest_r_squared, 4) # Plot the R-Squared (y) by model number (x) ymin = min(model_R_Squared_vector, na.rm = TRUE) ymax = max(model_R_Squared_vector, na.rm = TRUE) plot(model_R_Squared_vector, type="o", col="blue", ylim=c(ymin, ymax), ylab='Model R-Squared', xlab='Model Number', main= print(paste('Model', best_model_R_squared, 'has the highest R-Squared:', rounded_highest_r_squared))) # create vector from Avg_Rank Avg_Rank_vector = as.vector(dt_rank$Avg_Rank) # Plot mean rank of each model ymin = min(Avg_Rank_vector, na.rm = TRUE) ymax = max(Avg_Rank_vector, na.rm = TRUE) plot(Avg_Rank_vector, type="o", col="blue", ylim=c(ymin, ymax), ylab='Avg. Weighted Rank', xlab='Model Number', main = print(paste('Model', best_model, 'has the lowest weighted average rank (lower is better)\n amongst model evaluation metrics'))) # Build the model with the best score and return it, so the user can call summary model = glm(paste(model_formulas_vector[best_model]), data = dt_train, family = gaussian(link = 'identity')) return(model) }
/scratch/gouwar.j/cran-all/cranData/AutoStepwiseGLM/R/BckwdStepwise.R
#' @title Automated Forward Stepwise GLM #' #' @description Takes in a dataframe and the dependent variable (in quotes) as arguments, splits the data into testing and training, #' and uses automated forward stepwise selection to build a series of multiple regression models on the training data. #' Each model is then evaluated on the test data and model evaluation metrics are computed for each model. These metrics #' are provided as plots. Additionally, the model metrics are ranked and average rank is taken. The model with the lowest #' average ranking among the metrics is displayed (along with its formula). By default, metrics are all given the same #' relative importance (i.e., weights) when calculating average model metric rank, but if the user desires to give more #' weight to one or more metrics than the others they can specify these weights as arguments (default for weights is 1). #' As of v 0.2.0, only the family = gauissian(link = 'identity') argument is provided within the glm function. #' @param data A dataframe with one column as the dependent variable and the others as independent variables #' @param dv The column name of the (continuous) dependent variable (must be in quotes, i.e., 'Dependent_Variable') #' @param aic_wt Weight given to the rank value of the AIC of the model fitted on the training data (used when calculating mean model performance, default = 1) #' @param r_wt Weight given to the rank value of the Pearson Correlation between the predicted and actual values on the test data (used when calculating mean model performance, default = 1) #' @param mae_wt Weight given to the rank value of Mean Absolute Error on the test data (used when calculating mean model performance, default = 1) #' @param r_squ_wt Weight given to the rank value of R-Squared on the test data (used when calculating mean model performance, default = 1) #' @param train_prop Proportion of the data used for the training data set #' @param random_seed Random seed to use when splitting into training and testing data #' #' @return This function returns a plot for each metric by model and the best overall model with the formula used when fitting that model #' #' @examples #' dt <- mtcars #' stepwise_model <- fwd_stepwise_glm(data = dt, #' dv = 'mpg', #' aic_wt = 1, #' r_wt = 0.8, #' mae_wt = 1, #' r_squ_wt = 0.8, #' train_prop = 0.6, #' random_seed = 5) #' stepwise_model #' @export # dv argument must be a string (i.e., it must have quotes) fwd_stepwise_glm = function(data, dv, aic_wt=1, r_wt=1, mae_wt=1, r_squ_wt=1, train_prop = 0.7, random_seed = 7){ # save data as dt dt = data # rename the given dv to 'DV' in dt names(dt)[names(dt) == dv] = 'DV' # Split into testing/training nrows = nrow(dt) train_size = floor(train_prop*nrows) set.seed(random_seed) train_idx = sample(nrows, train_size, replace = F) dt_train = dt[train_idx, ] dt_test = dt[-train_idx, ] # instantiate an empty vector to store model formulas model_formulas_vector = vector() # Instantiate an empty vector of AIC for which to append AIC values model_AIC_vector = vector() # instantiate empty vector to store predictions predictions_vector = vector() # instantiate an empty vector to store residuals residuals_vector = vector() # Instantiate an empty vector of pearson correlations between predicted and actual for which to append pearson r values model_r_vector = vector() # Instantiate an empty vector of R-squared for which to append R-Squared values model_R_Squared_vector = vector() # Instantiate an empty vector of MAE for which to append MAE values model_MAE_vector = vector() # Program formulas formula1 = as.formula('DV ~ .') formula2 = 'DV ~' # instantiate a counter count = 0 for (i in 1:(length(names(dt_test))-1)) { # -1 because we have a dv in our dt # add 1 to the counter count = count +1 # Fit model from formula to get variable importance for next model model1 = glm(formula1, data = dt_train, family = gaussian(link = 'identity')) # Get most important variable #library(caret) var_imp = as.data.frame(varImp(model1)) # Turn into a data frame imp = data.frame(overall = var_imp$Overall, names = rownames(var_imp)) # Order it by importance imp_ordered = imp[order(imp$overall, decreasing = TRUE),] # Get the top name from this list var = imp_ordered[1,2] # Create a new formula that adds the most important var to the existing formula #library(formula.tools) formula2str = as.character(formula2) formula2 = as.formula(paste(formula2str, '+', var)) # Fit new model with this variable (FOR EVALUATED MODEL) model2 = glm(formula2, data = dt_train, family = gaussian(link = 'identity')) # save the model formula to a vector model_formula = model2$formula # add model_formula to model_formulas_vector model_formulas_vector = c(model_formulas_vector, model_formula) # get aic model_aic = model2$aic # append this to the vector model_first_aic model_AIC_vector = c(model_AIC_vector, model_aic) # get predictions predictions = predict(model2, dt_test) # append to predictions_vector predictions_vector = c(predictions_vector, predictions) # get the pearson correlation between predictions and actual values correlation = cor(predictions, dt_test$DV) # append correlation to model_r_vector model_r_vector = c(model_r_vector, correlation) # get the r-squared value r_squared = 1 - (sum((dt_test$DV-predictions)^2)/sum((dt_test$DV-mean(dt_test$DV))^2)) # append to model_R_Squared_vector model_R_Squared_vector = c(model_R_Squared_vector, r_squared) # get residuals resids = dt_test$DV - predictions # append to residuals_vector residuals_vector = c(residuals_vector, resids) # get the absolute values of residuals abs_residuals = abs(resids) # get mean of the absolute values of residuals (MAE) MAE = mean(abs_residuals) # Append to the model_MAE_vector model_MAE_vector = c(model_MAE_vector, MAE) # Build new model with the variables except the first one to get next most important var # Save the names of the variables vars = paste(imp_ordered[2:nrow(imp_ordered), 2], collapse = "+") formula1 = as.formula(paste('DV ~', vars)) } # Print a message if the loop was completed successfuly if (count == length(dt_test) - 1) { print(noquote(paste("Success: There were", count, 'models build and there were', length(dt_test) - 1, 'independent variables in the origninal model'))) } else print(noquote('Failure: There was an error, review code')) # rank the values in each of the vectors (1=worst, largest number = best) # AIC: Lower is better model_AIC_vector_rank = rank(model_AIC_vector) * aic_wt # Pearson r: Higher is better model_r_vector_rank = rank(-model_r_vector) * r_wt # R-Squared: Higher is better model_R_Squared_vector_rank = rank(-model_R_Squared_vector) * r_squ_wt # MAE: Lower is better model_MAE_vector_rank = rank(model_MAE_vector) * mae_wt # create a data frame with these ranked vectors dt_rank = data.frame(model_AIC_vector_rank, model_r_vector_rank, model_R_Squared_vector_rank, model_MAE_vector_rank) # get an average ranking for each model dt_rank$Avg_Rank = rowMeans(dt_rank, na.rm = FALSE, dims = 1) # which row (i.e., model has lowest ranking) best_model = which.min(dt_rank$Avg_Rank) # insert plots # AIC plot # get the index of the minimum AIC value to programmatically plot it best_model_AIC = which.min(model_AIC_vector) # find the value of the lowest AIC lowest_aic = min(model_AIC_vector) # round this value rounded_lowest_aic = round(lowest_aic, 3) # Plot the AIC (y) by model number (x) ymin = min(model_AIC_vector, na.rm = TRUE) ymax = max(model_AIC_vector, na.rm = TRUE) plot(model_AIC_vector, type="o", col="blue", ylim=c(ymin, ymax), ylab='Model AIC', xlab='Model Number', main= print(paste('Model', best_model_AIC, 'has the lowest AIC:', rounded_lowest_aic))) # Pearson correlation # get the index of the minimum AIC value to programmatically plot it best_model_r = which.max(model_r_vector) # find the value of the highest r highest_r = max(model_r_vector) # round this value rounded_highest_r = round(highest_r, 4) # Plot the r (y) by model number (x) ymin = min(model_r_vector, na.rm = TRUE) ymax = max(model_r_vector, na.rm = TRUE) plot(model_r_vector, type="o", col="blue", ylim=c(ymin, ymax), ylab='Model r', xlab='Model Number', main= print(paste('Model', best_model_r, 'has the highest r:', rounded_highest_r))) # MAE # get the index of the minimum MAE value to programmatically plot it best_model_MAE = which.min(model_MAE_vector) # find the value of the minimum MAE lowest_MAE = min(model_MAE_vector) # round this value rounded_lowest_MAE = round(lowest_MAE, 4) # Plot the MAE (y) by model number (x) ymin = min(model_MAE_vector, na.rm = TRUE) ymax = max(model_MAE_vector, na.rm = TRUE) plot(model_MAE_vector, type="o", col="blue", ylim=c(ymin, ymax), ylab='Model MAE', xlab='Model Number', main= print(paste('Model', best_model_MAE, 'has the lowest MAE:', rounded_lowest_MAE))) # R squared # get the index of the maximum r squared value to programmatically plot it best_model_R_squared = which.max(model_R_Squared_vector) # find the value of the maximum R-squared highest_r_squared = max(model_R_Squared_vector) # round this value rounded_highest_r_squared = round(highest_r_squared, 4) # Plot the R-Squared (y) by model number (x) ymin = min(model_R_Squared_vector, na.rm = TRUE) ymax = max(model_R_Squared_vector, na.rm = TRUE) plot(model_R_Squared_vector, type="o", col="blue", ylim=c(ymin, ymax), ylab='Model R-Squared', xlab='Model Number', main= print(paste('Model', best_model_R_squared, 'has the highest R-Squared:', rounded_highest_r_squared))) # create vector from Avg_Rank Avg_Rank_vector = as.vector(dt_rank$Avg_Rank) # Plot mean rank of each model ymin = min(Avg_Rank_vector, na.rm = TRUE) ymax = max(Avg_Rank_vector, na.rm = TRUE) plot(Avg_Rank_vector, type="o", col="blue", ylim=c(ymin, ymax), ylab='Avg. Weighted Rank', xlab='Model Number', main = print(paste('Model', best_model, 'has the lowest weighted average rank (lower is better)\n amongst model evaluation metrics'))) # Build the model with the best score and return it, so the user can call summary model = glm(paste(model_formulas_vector[best_model]), data = dt_train, family = gaussian(link = 'identity')) return(model) }
/scratch/gouwar.j/cran-all/cranData/AutoStepwiseGLM/R/FwdStepwise.R
#' @importFrom stats pnorm #' @importFrom stats sd #' @export ADStatQF <- function(x) { #The function is used to calculate the Anderson Darling Test Statistics of Standard Normal Distribution #vectors tested need lengths greater than 7 n = length(x) if (n < 7) { warning('Sample Size must be greater than 7.') } else { test1 = sort(x) f = pnorm(test1, mean = mean(test1), sd = sd(test1)) i = 1:n S = sum(((2*i)-1) / n * (log(f)+log(1-f[n+1-i]))) ADval = -n-S return(ADval) } }
/scratch/gouwar.j/cran-all/cranData/AutoTransQF/R/ADStatQF.R
#' A Novel Automatic Shifted Log Transformation #' #' The R package AutoTransQF based on Feng et al.(2016) introduces a novel parametrization of log transformation and a shift parameter to automate the transformation process. Please read Feng et al. (2016) <doi: 10.1002/sta4.104> for more details of the method. #' #' @docType package #' #' @author Yue Hu [aut, cre], Hyeon Lee [aut], J. S. Marron [aut] #' #' @name AutoTransQF-package NULL
/scratch/gouwar.j/cran-all/cranData/AutoTransQF/R/AutoTransQF-package.R
#' @importFrom moments skewness #' @importFrom matlab2r num2str #' @importFrom stats sd #' @importFrom stats IQR #' @docType methods #' @export AutoTransQF <- function(mdata, paramstruct = list(istat, iscreenwrite, FeatureNames)) { mdata = as.matrix(mdata) row_num = NROW(mdata) col_num = NCOL(mdata) transformed_data = matrix(NA, nrow = row_num, ncol = col_num) transformation = list() istat = 1 iscreenwrite = 0 FeatureNames = c() beta = -1 alpha = -1 all_alpha = c() all_beta = c() for (i in 1:row_num) { feature = paste("Feature",i, sep = '') FeatureNames = append(FeatureNames, feature) } if(length(paramstruct) == 0){ istat = istat iscreenwrite = iscreenwrite FeatureNames = FeatureNames} if(length(paramstruct)!=0){ if (!is.null(paramstruct$istat) && !is.null(paramstruct$iscreenwrite) && !is.null(paramstruct$FeatureNames)) { istat = paramstruct$istat iscreenwrite = paramstruct$iscreenwrite FeatureNames = paramstruct$FeatureNames } else if (is.null(paramstruct$istat) && !is.null(paramstruct$iscreenwrite) && !is.null(paramstruct$FeatureNames)) { iscreenwrite = paramstruct$iscreenwrite FeatureNames = paramstruct$FeatureNames } else if (!is.null(paramstruct$istat) && is.null(paramstruct$iscreenwrite) && !is.null(paramstruct$FeatureNames)) { istat = paramstruct$istat FeatureNames = paramstruct$FeatureNames } else if (!is.null(paramstruct$istat) && !is.null(paramstruct$iscreenwrite) && is.null(paramstruct$FeatureNames)) { istat = paramstruct$istat iscreenwrite = paramstruct$iscreenwrite } else if (is.null(paramstruct$istat) && is.null(paramstruct$iscreenwrite) && !is.null(paramstruct$FeatureNames)) { FeatureNames = paramstruct$FeatureNames } else if (is.null(paramstruct$istat) && !is.null(paramstruct$iscreenwrite) && is.null(paramstruct$FeatureNames)) { iscreenwrite = paramstruct$iscreenwrite } else if (!is.null(paramstruct$istat) && is.null(paramstruct$iscreenwrite) && is.null(paramstruct$FeatureNames)) { istat = paramstruct$istat } if (row_num != length(FeatureNames)){ message("\n") warning('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!', '\n', '!!!!!!!!!! Warning: Number of Feature Names!!!!!!!!!!!!!!!!', '\n', '!!!!!!!!!! Unmatched with Number of Features!!!!!!!!!!!!!!!', '\n', '!!!!!!!!!! Use Default Set for Feature Names!!!!!!!!!!!!!!!', '\n', '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!', '\n') FeatureNames = c() for (i in 1:row_num){ feature = paste('Feature', i, sep = '') FeatureNames = append(FeatureNames, feature) } } } for(i in 1:row_num){ vari = mdata[i,] if (sum(is.na(vari)!= 0)) { message("\n") warning('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!', '\n', '!!!!!!!!!!!!!! Warning from AutoTransQF.R: !!!!!!!!!!!!', '\n', '!!!!!!!!!!', FeatureNames[i], ' Contains Missing Value!!!!!!', '\n', '!!!!! Returning Orignial Data !!!!!!!!!!!!!!', '\n', '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!','\n') final_vari = vari text_k = "return original vector" transformed_data[i,] = final_vari transformation_info = paste(FeatureNames[i], ": ", text_k, sep = '') transformation = append(transformation, transformation_info) all_beta = append(all_beta, beta) all_alpha = append(all_alpha, alpha) } else if(abs(sd(vari)) < 1e-6 | (is.na(sd(vari)) == TRUE)){ message("\n") warning('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!IIIIIIIIIIIIIIIII!!!!!!!!!!', '\n', '!!! Warning from AutoTransQF.R: !!!', '\n', '!!! Standard deviation = 0 !!!', '\n', '!!! Returning all zeros !!!', '\n', '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!IIIIIIIIIIIIIIIII!!!!!!!!!!', '\n') final_vari = matrix(0, nrow = row_num, ncol = col_num) text_k = 'Return zero vector' transformed_data[i,] = final_vari[i,] transformation_info = paste('Feature', i, ': ', text_k, sep = '') transformation = append(transformation, transformation_info) all_beta = append(all_beta, beta) all_alpha = append(all_alpha, alpha) } else if(length(unique(vari)) <= 2){ message("\n") warning(' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!', '\n', '!!!!!!!!!!!!!! Warning from AutoTransQF.R: !!!!!!!!!!!', '\n', '!!!!!!!!!!!!!!! Binary Variable !!!!!!!!!!!', '\n', '!!!!!!!!!!!!!!! Return original values !!!!!!!!!!!', '\n', '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!') final_vari = vari text_k = 'No Transformation' transformed_data[i,] = final_vari transformation_info = paste('Feature', i, ': ', text_k, sep = '') transformation = append(transformation, transformation_info) all_beta = append(all_beta, beta) all_alpha = append(all_alpha, alpha) } else { if (skewness(c(t(vari))) > 0){ arrayindx = seq(0, 9, 0.01) } else { arrayindx = -seq(0, 9, 0.01) } func = function(paraindex) { autotransfuncQF(vari, istat, paraindex) } evals = list() for (k in arrayindx) { final_vari = func(k) if(istat == 1) { eval = ADStatQF(final_vari) }else { eval = skewness(final_vari) } evals = append(evals, eval) } iqrange_vari = IQR(vari, type = 2) if(iqrange_vari == 0) { range_vari = range(vari) }else{ range_vari = iqrange_vari } index = which.min(unlist(evals)) beta = sign(arrayindx[index]) * (exp(abs(arrayindx[index])) - 1) alpha = abs(1/beta) * range_vari final_vari = autotransfuncQF(vari, istat, arrayindx[index]) value = evals[index] text_k = paste('Transformation Parameter Beta = ', beta, sep = '') transformed_data[i,] = final_vari transformation_info = paste('Feature', i, ': ', text_k, sep = '') transformation = append(transformation, transformation_info) all_beta = append(all_beta, beta) all_alpha = append(all_alpha, alpha) } if (iscreenwrite == 1) { message("\n") if(istat == 1) { message('************ Transformation of ', FeatureNames[i],' **********','\n', 'Transformation Criterion: Minimize Log ', '(Anderson_Darling Test Statistic) (Standard Normal)', '\n') } else if(istat == 2) { message('************ Transformation of ', FeatureNames[i],' **********','\n', 'Transformation Criterion: Minimize Skewness', '\n') } message('Log A-D Stat Before Transformation:', num2str(log(ADStatQF(vari))),'\n', 'Skewness Before Transformation: ', num2str(skewness(vari)),'\n', 'Selected Transformation: ', text_k,'\n', 'Selected Transformation: Transformation Parameter alpha = ', alpha, '\n', 'Skewness After Transformation: ', num2str(skewness(final_vari)),'\n', 'Log A-D Stat After Transformation: ', num2str(log(ADStatQF(final_vari))),'\n', '*****************************************************','\n') } } return_value = list(data = transformed_data, beta = all_beta, alpha = all_alpha) return(return_value) }
/scratch/gouwar.j/cran-all/cranData/AutoTransQF/R/AutoTransQF.R
#' @importFrom VGAM qgumbel #' @importFrom stats IQR #' @importFrom stats median #' @importFrom stats sd #' @export autotransfuncQF <- function(vari, istat, paraindex) { #The function is used for transformation of each individual variable #The variable paraindex is used to calculate transformation parameter beta i = paraindex row_num = dim(matrix(vari, nrow = 1))[1] col_num = dim(matrix(vari, nrow = 1))[2] beta = sign(i)*(exp(abs(i))-1) alpha = abs(1/beta) #get the interquartile range of the values in the data vector iqrange_vari = IQR(vari, type = 2) #use the interquartile range as the data range if not zero #otherwise use the full data range if(iqrange_vari == 0) { range_vari = range(vari) }else{ range_vari = iqrange_vari } #transform based on the sign of the beta if (beta == 0) { vark1 = vari }else if (beta > 0) { vark1 = log(vari-min(vari)+alpha*range_vari) }else { vark1 = -log(max(vari)-vari+alpha*range_vari) } #standardize transformed data vector mabd = mean(abs(vark1 - median(vark1))) mabd = mabd* sqrt(pi / 2) if (mabd == 0) { final_vari = matrix(0, row_num, col_num) }else { vark1 = (vark1 - median(vark1)) / mabd # winsorise transformed data vector p95 = -qgumbel(0.05) ak = (2*log(row_num*col_num))^(-0.5) bk = (2*log(row_num*col_num) - log(log(row_num*col_num)) - log(4*pi))^0.5 TH = p95 * ak + bk vark1[vark1 > TH] = rep(TH, sum(vark1 > TH)) vark1[vark1 < -TH] = rep(-TH, sum(vark1 < -TH)) #re-standardize by substract the mean and divide by standard deviation final_vari = (vark1 - mean(vark1)) / sd(vark1) } #calculate evaluation stat #both AD statistics and skewness test how far away data is from normality if(istat == 1) { eval = ADStatQF(final_vari) }else { eval = skewness(final_vari) } return(final_vari) }
/scratch/gouwar.j/cran-all/cranData/AutoTransQF/R/autotransfuncQF.R
#' MelanomaFeatures from Miedema et al. (2012) #' #' The dataset from Miedema et al. (2012) is built based on 49 hematoxylin and eosin stained slides of distinctive melanocytic lesions. #' #' @format #' A data frame with 10152 observations on 49 variables where columns serve as data objects and rows serve as features. All 49 features are numeric variables including \code{Area}, \code{Hu.1}, \code{Hu.2 }etc. #' #' @source Miedema, Jayson, et al. (2012). Image and statistical analysis of melanocytic histology. Histopathology, 61(3), pp.436-444. doi: 10.1111/j.1365-2559.2012.04229.x "Melanoma"
/scratch/gouwar.j/cran-all/cranData/AutoTransQF/R/data.R
# This package calculates weather indices from weather variables for using as input for further analysis. AutoWeatherIndices<-function(x,nw) { imd<-as.matrix(x[,-1]) yld<-as.numeric(unlist(x[,1])) no_of_weeks<-nw no_of_w_variables<-round(ncol(imd)/no_of_weeks) no_of_years<-as.numeric(nrow(imd)) wmatrix<- list() j<-1 k<-no_of_weeks for (i in 1:no_of_w_variables) { wmatrix[[i]] <- imd[,j:k] j=j+no_of_weeks k=k+no_of_weeks } t<-1:no_of_years;t dt<-stats::lm(yld~t) adjustedyield<-dt$residuals cor_wv<-matrix(nrow=no_of_weeks,ncol=no_of_w_variables,byrow = TRUE) varZ1<-matrix(nrow=no_of_years,ncol=no_of_w_variables) varZ0<-matrix(nrow=no_of_years,ncol=no_of_w_variables) k<-no_of_weeks i<-1 for (j in 1:no_of_w_variables) { for(i in i:k) { cor_wv[i]<-stats::cor(adjustedyield,imd[,i]) } i=i+1 k=k+no_of_weeks varZ1[,j]<-(rowSums(wmatrix[[j]]%*%as.vector(cor_wv[,j]))) varZ0[,j]<-(rowSums(wmatrix[[j]])) } ##To find the product of the weather variable wpmatrix<-list() m<-1 for (p in 1:no_of_w_variables) { for (q in p+1:no_of_w_variables) { if(q<=no_of_w_variables) { wpmatrix[[m]]<-wmatrix[[p]]*wmatrix[[q]] m=m+1 } } } #computing the correlation matrix combi<-(gtools::combinations(no_of_w_variables,2)) tol_combi<-2*nrow(combi) corp_wv<-matrix(nrow=no_of_weeks,ncol=nrow(combi),byrow = TRUE) varZ11<-matrix(nrow=no_of_years,ncol=nrow(combi)) varZ10<-matrix(nrow=no_of_years,ncol=nrow(combi)) k<-no_of_weeks i<-1 l<-1 for (j in 1:nrow(combi)) { b=1 for(i in i:k) { corp_wv[i]<-stats::cor(adjustedyield,wpmatrix[[j]][,b]) b=b+1 } i=i+1 k=k+no_of_weeks varZ11[,j]<-(rowSums(wpmatrix[[j]]%*%as.vector(corp_wv[,j]))) varZ10[,j]<-(rowSums(wpmatrix[[j]])) } w_indices<-cbind(varZ0,varZ1,varZ10,varZ11) correlation_mat_wv<-cor_wv correlation_mat_wvp<-corp_wv return_list<-list(w_indices,correlation_mat_wv,correlation_mat_wvp) return(return_list) }
/scratch/gouwar.j/cran-all/cranData/AutoWeatherIndices/R/AutoWeatherIndices.R
###############################data download############################### ####download length length_data=function(){ #protein[9] is the type of protein's name, you can use " Gene names", "Protein names" or "KB" to choice the protein which you want to see. protein=read.table("Protein.txt", sep="\t",stringsAsFactors=F) type=protein[9] if(type=="Gene names"){ name.t="gene%3A" } if(type=="Protein names"){ name.t="name%3A" } if(type=="KB"){ name.t="" } name.x=protein[2] url_1="http://www.uniprot.org/uniprot/?query=" url_2="+human&sort=score" url_3=paste(url_1,name.t,name.x,url_2,sep="") doc_1<- htmlParse(url_3) KB<-xpathSApply(doc_1,"//html/body/main/div/div/div[position()=2]/form/table/tbody/tr[position()=1]/td[position()=2]/a/text() ",xmlValue) if(is.null(KB)) {KB[1] <- protein[2] } name=KB[1] url_p="http://www.uniprot.org/uniprot/" url_s="#showFeatures" url_w=paste(url_p,name,url_s,sep="") url= url_w doc <- htmlParse(url) position_l <- xpathSApply(doc,"//table[@id= 'peptides_section']/tr/td/a[@class='position tooltipped']",xmlValue) #position_l s_l <- c() for(i in 1:length(position_l)){ s_l[i] <- gsub(pattern="\\D",replacement="x",position_l[i])} s_l <- strsplit(s_l,"xxx") d2_l <- laply(s_l,function(x)x[2]) #d2 r1_l <-0 r2_l <- d2_l dfrm_l <- data.frame(r1_l,r2_l) write.table(dfrm_l,file="Length.txt",sep="\t",quote =FALSE,row.names = F,col.names = F) } ####download domain domain_data=function(){ protein=read.table("Protein.txt", sep="\t",stringsAsFactors=F) type=protein[9] if(type=="Gene names"){ name.t="gene%3A" } if(type=="Protein names"){ name.t="name%3A" } if(type=="KB"){ name.t="" } name.x=protein[2] url_1="http://www.uniprot.org/uniprot/?query=" url_2="+human&sort=score" url_3=paste(url_1,name.t,name.x,url_2,sep="") doc_1<- htmlParse(url_3) KB<-xpathSApply(doc_1,"//html/body/main/div/div/div[position()=2]/form/table/tbody/tr[position()=1]/td[position()=2]/a/text() ",xmlValue) if(is.null(KB)) {KB[1] <- protein[2] } name=KB[1] url_p="http://www.uniprot.org/uniprot/" url_s="#showFeatures" url_w=paste(url_p,name,url_s,sep="") url= url_w doc<- htmlParse(url) position_d = xpathSApply(doc,"//table[@id= 'domainsAnno_section']/tr/td/a[@class='position tooltipped']",xmlValue) name_d = xpathSApply(doc,"//table[@id= 'domainsAnno_section']/tr/td/span[@property='text']",xmlValue) #position_d #name_d s_d=c() for(i in 1:length(position_d)){ s_d[i] <- gsub(pattern="\\D",replacement="x",position_d[i])} s_d <- strsplit(s_d,"xxx") d1_d <- laply(s_d,function(x)x[1]) d2_d <- laply(s_d,function(x)x[2]) #d1_d #d2_d r1_d = d1_d r2_d = d2_d r3_d = name_d dfrm_d = data.frame(r1_d,r2_d,r3_d) write.table(dfrm_d,file="Domain.txt",sep="\t",quote =FALSE,row.names = F,col.names = F) } ####download site site_data=function(){ protein=read.table("Protein.txt", sep="\t",stringsAsFactors=F) type=protein[9] if(type=="Gene names"){ name.t="gene%3A" } if(type=="Protein names"){ name.t="name%3A" } if(type=="KB"){ name.t="" } name.x=protein[2] url_1="http://www.uniprot.org/uniprot/?query=" url_2="+human&sort=score" url_3=paste(url_1,name.t,name.x,url_2,sep="") doc_1<- htmlParse(url_3) KB<-xpathSApply(doc_1,"//html/body/main/div/div/div[position()=2]/form/table/tbody/tr[position()=1]/td[position()=2]/a/text() ",xmlValue) if(is.null(KB)) {KB[1] <- protein[2] } name=KB[1] url_p="http://www.uniprot.org/uniprot/" url_s="#showFeatures" url_w=paste(url_p,name,url_s,sep="") url= url_w doc<- htmlParse(url) #p=xpathSApply(doc,"//table[@id= 'sitesAnno_section']/tr/td/a/text()",xmlValue) position_s = xpathSApply(doc,"//table[@id= 'sitesAnno_section']/tr/td/a[@class='position tooltipped']",xmlValue) name_s = xpathSApply(doc,"//table[@id= 'sitesAnno_section']/tr/td/span[@property='text']",xmlValue) #position_site #name_site s_s <- c() for(i in 1:length(position_s)){ s_s[i] <- gsub(pattern="\\D",replacement="x",position_s[i])} s_s <- strsplit(s_s,"xxx") d1_s <- laply(s_s,function(x)x[1]) d2_s <- laply(s_s,function(x)x[2]) #d1_s #d2_s r1_site=d1_s r2_site=name_s dfrm_site = data.frame(r1_site,r2_site) write.table(dfrm_site,file="Site.txt",sep="\t",quote =FALSE,row.names = F,col.names = F) } ###############################plot protein############################### Autoplotprotein=function(){ protein=read.table("Protein.txt", sep="\t",stringsAsFactors=F) domain=read.table("Domain.txt", sep="\t",stringsAsFactors=F) length=read.table("Length.txt", sep="\t",stringsAsFactors=F) site=read.table("Site.txt", sep="\t",stringsAsFactors=F) muta=read.table("Mutagenesis.txt", sep="\t",stringsAsFactors=F) option=read.table("Option.txt", sep="\t",stringsAsFactors=F) zoomin=read.table("ZoomIn.txt", sep="\t",stringsAsFactors=F) size<-c(10.5,7.27) high<-c(1,-1) sizen=size[1] highn=high[1] if(option[2,2]=="no") { sizen=size[2] highn=high[2]} path=protein[1] pdf(as.character(path), height=sizen[1], width=11) layout(matrix(c(1,2),nrow=1), widths=c(1,3)) #par(oma=c(4, 0, 4, 0), mar=c(5, 0, 4, 0) + 0.4) par(oma=c(3, 0, 2, 0), mar=c(4, 0, 2, 0) + 0.4) nameOfYourQuery = option[2,1] additionalOptions = option[2,2] showReferenceSequence = option[2,3] showConservationScore = option[2,4] showGridlinesAtTicks = option[2,5] conservation = option[2,6] zoomIn = zoomin[2,1] zoomStart = zoomin[2,2] zoomEnd = zoomin[2,3] tickSize = as.numeric(zoomin[2,4]) #stable legend ##important plot((-30:-15), rep(-1, 16), col="white", type="l", ann=FALSE, bty="n", xaxt="n", yaxt="n", xlim=c(-160, -15), ylim=c(highn[1],-5.5)) #conservation text if(additionalOptions == "yes"){ if(conservation == "yes"){ lines((-30:-15), rep(0, 16), col="purple3") lines((-30:-15), rep(-0.5, 16), col="purple3") lines((-30:-15), rep(-1, 16), col="purple3") text(-100, -0.5, "Conservation", col="purple3", cex=0.9, font=2) text(-45,-1, "1", col="purple3", cex=0.9) text(-45,-0.5, "0.5", col="purple3", cex=0.9) text(-45,0, "0", col="purple3", cex=0.9) } } #showReferenceSequence text if(additionalOptions == "yes"){ if(showReferenceSequence == "yes"){ #reference text text(-100,-4.9,"Reference", col="black", cex=0.9, font=2) } } #showConservationScore text if(additionalOptions == "yes"){ if(showConservationScore == "yes"){ #score text text(-100,0.5,"Score", col="purple3", cex=0.9, font=2) } } #query text text(-100,-2.95,nameOfYourQuery, col="blue", cex=0.9, font=2) #main plot Protein=function(start=1,end,height=-0.3,color='green',face='stereoscopic'){ x=0 kong1=(round(log(start,10))+1)*start/50 kong2=(round(log(end,10))+1)*end/50 if(round(log(end,10))+1<=5){ kong2=(round(log(end,10))+1)*end/50 } else{ kong2=5*end/50 } h1=-2.8 h2=-3.1 #boxplot(x,xlim=c(start-kong1,end+kong2),ylim=c(-50,50),axes=FALSE,border=FALSE) boxplot((1:as.numeric(end)),rep(h1,as.numeric(end)),xlab="Amino Acid Position", ylab="",xlim=c(0,as.numeric(end)), ylim=c(highn[1],-5.5),axes=FALSE) #boxplot((1:as.numeric(end)),rep(h1,as.numeric(end)),xlab="Amino Acid Position", ylab="",xlim=c(300,400), ylim=c(1,-5.5),axes=FALSE) if(face=='stereoscopic'){ cylindrect(start,h1,end,h2,col=color,gradient="y") } else{ rect(start,h1,end,h2,col=color) } text(0,h1-height/2,start,adj=1) text(end-17,h1-height/2,end,adj=0) } ZoomIn=function(start=1,end,height=-0.3,color='green',face='stereoscopic',zoomstart,zoomend){ x=0 kong1=(round(log(start,10))+1)*start/50 kong2=(round(log(end,10))+1)*end/50 if(round(log(end,10))+1<=5){ kong2=(round(log(end,10))+1)*end/50 } else{ kong2=5*end/50 } h1=-2.8 h2=-3.1 #boxplot(x,xlim=c(start-kong1,end+kong2),ylim=c(-50,50),axes=FALSE,border=FALSE) boxplot((as.numeric(zoomstart):as.numeric(zoomend)),rep(h1,as.numeric(zoomend)),xlab="Amino Acid Position", ylab="",xlim=c(as.numeric(zoomstart),as.numeric(zoomend)), ylim=c(highn[1],-5.5),axes=FALSE) #boxplot((1:as.numeric(end)),rep(h1,as.numeric(end)),xlab="Amino Acid Position", ylab="",xlim=c(300,400), ylim=c(1,-5.5),axes=FALSE) if(face=='stereoscopic'){ cylindrect(start,h1,end,h2,col=color,gradient="y") } else{ rect(start,h1,end,h2,col=color) } #text(start,height/2,start,adj=1) #text(end,height/2,end,adj=0) text(start,h1+height/2,start,adj=1) text(end,h1+height/2,end,adj=0) } #zoomin if(zoomIn == "yes"){ #zoomin ZoomIn(start=as.numeric(length[1]),end=as.numeric(length[2]),height=as.numeric(protein[4]),color=as.character(protein[5]),face=protein[6],zoomstart = zoomin[2,2],zoomend = zoomin[2,3])#,options=option[2,2],zoomin=zoomin[2,1])start=as.numeric(protein[2]),end=as.numeric(protein[3]) }else{ Protein(start=as.numeric(length[1]),end=as.numeric(length[2]),height=as.numeric(protein[4]),color=as.character(protein[5]),face=protein[6])#,options=option[2,2],zoomin=zoomin[2,1])start=as.numeric(protein[2]),end=as.numeric(protein[3]) } #legend legend("topleft", legend=c("mutation","Protein Domain"), pch=c(19,15),col=c("lightseagreen", "deeppink"),box.col="white", bg="white", pt.cex=1.5,text.width=1) #scale ticks=seq(0,as.numeric(length[2]), by=tickSize) axis(side = 1, at = ticks, las=3) #showGridlinesAtTicks if(additionalOptions == "yes"){ if(showGridlinesAtTicks == "yes"){ #grid len=array(rep(1:as.numeric(length[2]))) #for(i in 1:as.numeric(len)){ for(i in 1:length(len)){ abline(v=ticks[i], lty=3, lwd=0.5, col="lightgray") } } } } ###############################conservation analysis############################### conservation=function(){ protein=read.table("Protein.txt", sep="\t",stringsAsFactors=F) domain=read.table("Domain.txt", sep="\t",stringsAsFactors=F) length=read.table("Length.txt", sep="\t",stringsAsFactors=F) site=read.table("Site.txt", sep="\t",stringsAsFactors=F) muta=read.table("Mutagenesis.txt", sep="\t",stringsAsFactors=F) option=read.table("Option.txt", sep="\t",stringsAsFactors=F) zoomin=read.table("ZoomIn.txt", sep="\t",stringsAsFactors=F) nameOfYourQuery = option[2,1] additionalOptions = option[2,2] showReferenceSequence = option[2,3] showConservationScore = option[2,4] showGridlinesAtTicks = option[2,5] conservation = option[2,6] zoomIn = zoomin[2,1] zoomStart = zoomin[2,2] zoomEnd = zoomin[2,3] tickSize = as.numeric(zoomin[2,4]) referenceSequencePositionInFile = option[2,7] option=read.table("Option.txt", sep="\t",stringsAsFactors=F) a <- read.fasta(file = "alignmentFile.fasta") seq <- list() for(i in 1:length(a)){ #length(a)=7 seq[[i]] <- a[[i]][1:length(a[[i]])] #length(a[[1]])=485 } numberOfSeq <- length(seq) #length(seq)=7 mat <- matrix(0, nrow=length(a), ncol=length(a[[1]])) for(i in 1:length(seq)){ mat[i,] <- seq[[i]] } df <- as.data.frame(mat) tdf <- t(df) referenceSequencePositionInFile = option[2,7] referenceSeq <- tdf[which(tdf[,as.numeric(referenceSequencePositionInFile)] != "-"),] referenceSeq <- as.data.frame(referenceSeq) leng<-length(a[[1]]) write.table(referenceSeq, file="alignment_table", sep="\t", quote=F, row.names=F, col.names=F) counter <- rep(0, nrow(referenceSeq)) a <- read.table("alignment_table", sep="\t") a <- data.frame(lapply(a, as.character), stringsAsFactors=FALSE) for(i in 1:nrow(a)){ #nrow(a)=463 a[i,"consensus"] <- paste(as.character(a[i,]), collapse="") } countBases <- function(string){ table(strsplit(string, "")[[1]]) } c <- as.character(a[,"consensus"]) tab <- list() for(i in 1:length(c)){ tab[[i]] <- countBases(c[i]) } score <- rep(0, nrow(a)) for(i in 1:length(tab)){ for(j in 1:length(tab[[i]])){ if((names(tab[[i]][j])) == a[i,][as.numeric(referenceSequencePositionInFile)]) score[i] <- tab[[i]][j] } } scorePlot <- -(((score/numberOfSeq))) a <- read.fasta(file = "alignmentFile.fasta") #Sequence of Interest seqForPlot <- a[[as.numeric(referenceSequencePositionInFile)]][which(a[[as.numeric(referenceSequencePositionInFile)]] != "-")] #conservation if(additionalOptions == "yes"){ if(conservation == "yes"){ lines(scorePlot, col="purple3") } } #ReferenceSequence if(additionalOptions == "yes"){ if(showReferenceSequence == "yes"){ #specify if you want a reference track rect(0, -4.75, length(scorePlot), -5.05, col="white", border=NA) if(leng[1]<500){ for(i in 1:length(seqForPlot)){ text(i,-4.9, toupper(seqForPlot[i]), font=2, cex=1) } } else{ text(0,-4.9," OverLengthCannotBeDisplayed!",font=2,cex=1) } } } #showConservationScore if(additionalOptions == "yes"){ if(showConservationScore == "yes"){ #specify if you want score rect(0, 0.3, length(scorePlot), 0.7, col="white", border=NA) for(i in 1:length(seqForPlot)){ text(i,0.5, toupper(abs(round(scorePlot[i],1))), font=2, cex=0.8, srt=90, col="purple3") } } } } ###############################plot site############################### plotsite=function(){ protein=read.table("Protein.txt", sep="\t",stringsAsFactors=F) domain=read.table("Domain.txt", sep="\t",stringsAsFactors=F) length=read.table("Length.txt", sep="\t",stringsAsFactors=F) site=read.table("Site.txt", sep="\t",stringsAsFactors=F) muta=read.table("Mutagenesis.txt", sep="\t",stringsAsFactors=F) option=read.table("Option.txt", sep="\t",stringsAsFactors=F) zoomin=read.table("ZoomIn.txt", sep="\t",stringsAsFactors=F) ####Site Site=function(position,position2,name,height=-0.3,x_y,up_down){ #plot site , adjust the marked line length #position is the location of site #position2 is the location of marked character #name is the name of site #height is the heigth of the proteic main body #up_down : the marked line is up or down h1=-0.1 h2=-0.2 h=-0.4 hh1=-2.8 if(up_down=="up"){ if(position==position2){ segments(position,hh1+height,position,hh1+height+h) } else{ segments(position,hh1+height,position,hh1+height+h1) segments(position2,hh1+height+h-h2,position2,hh1+height+h) segments(position,hh1+height+h1,position2,hh1+height+h-h2) } #if (x_y==FALSE){ #par(srt=90) text(position2,hh1+height+h-0.02,name,srt=90,adj=c(0,0.5),cex=0.8) } else{ if(position==position2){ segments(position,hh1,position,hh1-h) } else{ segments(position,hh1,position,hh1-h1) segments(position2,hh1-h+h2,position2,hh1-h) segments(position,hh1-h1,position2,hh1-h+h2) } text(position2,hh1-h+0.02,name,srt=270,adj=c(0,0.5),cex=0.8) } } ####Change_x Change_x=function(site_pos,site_name,protein_width){ #Implement site marking line space position distribution, so that they don't overlap. #site_pos is the location of the x coordinate #site_name is the name of the marked character #protein_width is the length of the protein dec=1.4*protein_width/100 position2=1:length(site_pos) position2[1]=site_pos[1] if(length(site_pos)>1){ for(i in 2:length(site_pos)){ if (site_pos[i]-site_pos[i-1]<=dec){ if(site_pos[i]!=site_pos[i-1]){ position2[i] =position2[i-1]+dec } else{ position2[i]=position2[i-1] } } else{ position2[i] = site_pos[i] } } } return(position2) } #Plot site if(!is.na(site[1,1])){ position2=Change_x(site[,1],site[,2],as.numeric(length[2])) for(i in 1: nrow(site)){ Site(position=as.numeric(site[i,1]),position2=position2[i],name=as.character(site[i,2]),height=as.numeric(protein[4]),x_y=FALSE,up_down="up") } } } ###############################plot domain############################### plotdomain=function(){ protein=read.table("Protein.txt", sep="\t",stringsAsFactors=F) domain=read.table("Domain.txt", sep="\t",stringsAsFactors=F) length=read.table("Length.txt", sep="\t",stringsAsFactors=F) site=read.table("Site.txt", sep="\t",stringsAsFactors=F) muta=read.table("Mutagenesis.txt", sep="\t",stringsAsFactors=F) option=read.table("Option.txt", sep="\t",stringsAsFactors=F) zoomin=read.table("ZoomIn.txt", sep="\t",stringsAsFactors=F) ####Domain Domain = function(start,end,name,height=-0.3,color='orange',face='stereoscopic',protein_width,x_y){ h1=-2.8 h2=-3.1 dec=2*nchar(name)*protein_width/100 if(face=='stereoscopic'){ cylindrect(start,h1,end,h2,col=color,gradient="y") } else{ rect(start,h1,end,h2,col=color) } if(end-start>=dec){ par(srt=0) text((end+start)/2,h1+height/2,name,cex=0.7) isContain=TRUE } else{ isContain=FALSE } isContain } #####Domain_w Domain_w=function(domain_pos,domain_name,protein_width){ dec=1.4*protein_width/100 #dec=3 protein_width=100 position2=1:length(domain_pos) position2[1]=domain_pos[1] if(length(domain_pos)>1){ for(i in 2:length(domain_pos)){ if (domain_pos[i]-domain_pos[i-1]<=dec){ if(domain_pos[i]!=domain_pos[i-1]){ position2[i] =position2[i-1]+dec } else{ position2[i]=position2[i-1] } } else{ position2[i] = domain_pos[i] } } } return(position2) } ####Domain_h Domain_h=function(position,position2,name,height=-0.3,x_y,up_down){ h1=-0.1 h2=-0.2 h=-0.4 hh1=-2.8 if(up_down=="up"){ if(position==position2){ segments(position,hh1+height,position,hh1+height+h) } else{ segments(position,hh1+height,position,hh1+height+h1) segments(position2,hh1+height+h-h2,position2,hh1+height+h) segments(position,hh1+height+h1,position2,hh1+height+h-h2) } #if (x_y==FALSE){ #par(srt=90) text(position2,hh1+height+h-0.02,name,srt=90,adj=c(0,0.5),cex=0.8) } else{ if(position==position2){ segments(position,hh1,position,hh1-h) } else{ segments(position,hh1,position,hh1-h1) segments(position2,hh1-h+h2,position2,hh1-h) segments(position,hh1-h1,position2,hh1-h+h2) } text(position2,hh1-h+0.02,name,srt=270,adj=c(0,0.5),cex=0.8) } } #Plot domaain #if(domain[1,1]!="null"){ if(!is.na(domain[1,1])){ domainn=domain count=0 for(i in 1: nrow(domainn)){ isContain=Domain(start=as.numeric(domainn[i,1]),end=as.numeric(domainn[i,2]),name=as.character(domainn[i,3]),height=as.numeric(protein[4]),color=i+1,face=protein[6],protein_width=as.numeric(length[2]),x_y=flag) #color=as.character(domainn[i,4])# if (isContain==TRUE){ domain=domain[-i+count,] count=count+1 } } domain2=(domain[,1]+domain[,2])/2 if (length(domain2)!=0){ flag=TRUE if(flag==TRUE){ position3=Domain_w(domain2,domain[,3],as.numeric(length[2])) } for(i in 1: nrow(domain)){ position1=(as.numeric(domain[i,1])+as.numeric(domain[i,2]))/2 Domain_h(position=position1,position2=position3[i],name=as.character(domain[i,3]),height=as.numeric(protein[4]),x_y=flag,up_down="down") } } } } ###############################plot mutagensis############################### plotmutagensis=function(){ protein=read.table("Protein.txt", sep="\t",stringsAsFactors=F) domain=read.table("Domain.txt", sep="\t",stringsAsFactors=F) length=read.table("Length.txt", sep="\t",stringsAsFactors=F) site=read.table("Site.txt", sep="\t",stringsAsFactors=F) muta=read.table("Mutagenesis.txt", sep="\t",stringsAsFactors=F) option=read.table("Option.txt", sep="\t",stringsAsFactors=F) zoomin=read.table("ZoomIn.txt", sep="\t",stringsAsFactors=F) ####Mutagenesis Mutagenesis=function(position,position2,color,height2,height,up_down,start,end,pc,cex1){ h1=-0.1 h2=-1.4 h=-1.6 hh1=-2.8 if(up_down=="up"){ if(position==position2){ segments(position,hh1+height,position,hh1+height+h) } else{ segments(position,hh1+height,position,hh1+height+h1) segments(position2,hh1+height+h-h2,position2,hh1+height+h) segments(position,hh1+height+h1,position2,hh1+height+h-h2) } } x = 0 kong1=(round(log(start,10))+1)*start/50 kong2=(round(log(end,10))+1)*end/50 if(round(log(end,10))+1<=5){ kong2=(round(log(end,10))+1)*end/50 } else{ kong2=5*end/50 } #boxplot((as.numeric(start):as.numeric(end)),rep(hh1, as.numeric(end)),xlim=c(0,463),ylim=c(1,-5.5),axes=FALSE,add=TRUE,border=FALSE) boxplot(x,xlim=c(start-kong1,end+kong2),ylim=c(1,-5.5),axes=FALSE,add=TRUE,border=FALSE) points(position2,height2,pch=pc,col=color,cex=cex1) } ####Change_h Change_h=function(muta_pos,muta_name,protein_h){ d=0.1 d1=0.26 hh1=-2.8 height2=1:length(muta_pos) height2[1]=hh1+protein_h-d1 position_h= muta_pos position_h[1]=muta_pos[1] if(length(muta_pos)>1){ for(i in 2:length(muta_pos)){ if(muta_pos[i]== position_h[i-1]){ height2[i]=height2[i-1]-d } else{ height2[i]=hh1+protein_h-d1 } } } height2 } ####Change_m Change_m=function(muta,protein_width){ dec=1.4*protein_width/100 position3=1:length(muta) position3[1]=muta[1] if(length(muta)>1){ for(i in 2:length(muta)){ if (muta[i]-muta[i-1]<=dec){ if(muta[i]!=muta[i-1]){ position3[i] =position3[i-1]+dec } else{ position3[i]=position3[i-1] } } else{ position3[i] = muta[i] } } } position3 } #Plot mutations #if(muta[1,1]!="null"){ if(!is.na(muta[1,1])){ position3=Change_m(muta[,1],as.numeric(length[2])) height2=Change_h(muta[,1],muta[,2],as.numeric(protein[4])) for(i in 1: nrow(muta)){ Mutagenesis(position=as.numeric(muta[i,1]),position2=position3[i],color=as.character(muta[i,2]),height2=height2[i],height=as.numeric(protein[4]),up_down="up",start=as.numeric(length[1]),end=as.numeric(length[2]),pc=as.numeric(protein[7]),cex1=as.numeric(protein[8])) } } } data=function(){ protein=read.table("Protein.txt", sep="\t",stringsAsFactors=F) domain=read.table("Domain.txt", sep="\t",stringsAsFactors=F) length=read.table("Length.txt", sep="\t",stringsAsFactors=F) site=read.table("Site.txt", sep="\t",stringsAsFactors=F) muta=read.table("Mutagenesis.txt", sep="\t",stringsAsFactors=F) option=read.table("Option.txt", sep="\t",stringsAsFactors=F) zoomin=read.table("ZoomIn.txt", sep="\t",stringsAsFactors=F) c <- merge(muta,domain,all=T,sort = FALSE) c <- merge(c,option,all=T,sort = FALSE) c <- merge(c,zoomin,all=T,sort = FALSE) c <- merge(c,protein,all=T,sort = FALSE) c <- merge(c,length,all=T,sort = FALSE) c <- merge(c,site,all=T,sort = FALSE) write.table(c,file="data.txt",sep="\t",quote =FALSE,row.names = F,col.names = F) }
/scratch/gouwar.j/cran-all/cranData/Autoplotprotein/R/Autoplotprotein.R
#' Performs minimum distance estimation in autoregressive model #'@param X : vector of n observed value #'@param AR_Order : oder of the autoregressive model #'@return returns minimum distance estimators of the parameter in the autoregressive model #'@examples #'X <- rnorm(10, mean=0, sd=1) #'AR_Order <- 2 #'rhohat<-ARMDE(X,AR_Order) #'@references #'[1] Koul, H. L (1985). Minimum distance estimation in linear regression with unknown error distributions. Statist. Probab. Lett., 3 1-8. #'@references #'[2] Koul, H. L (1986). Minimum distance estimation and goodness-of-fit tests in first-order autoregression. Ann. Statist., 14 1194-1213. #'@references #'[3] Koul, H. L (2002). Weighted empirical process in nonlinear dynamic models. Springer, Berlin, Vol. 166 #'@importFrom "stats" "optim" #'@importFrom "utils" "read.csv" #'@export #'@seealso LRMDE ARMDE <- function(X, AR_Order){ nLength <- length(X) if(nLength<=AR_Order){ message("Length of vector X should be greater than AR_Order.") stop } Xres <- rep(0, times=(nLength-AR_Order)) tempvec <- rep(0, times= AR_Order*(nLength-AR_Order) ) Xexp <- matrix( tempvec, nrow = (nLength-AR_Order), ncol = AR_Order) for (i in 1:(nLength-AR_Order) ) { Xres[i] <- X[nLength - (i-1)] for (j in 1:AR_Order){ Xexp[i,j] <- X[nLength-(i+j-1) ] } } tempdet = det( t(Xexp) %*% Xexp ) if ( tempdet < 0.01 ){ rho0 <- 0.5*rep(1, times = AR_Order) }else{ rho0 <- solve(t(Xexp)%*%Xexp)%*% (t(Xexp)%*%Xres) } Tmin <- optim(rho0, TLoss(X, AR_Order)) return(Tmin$par) } TLoss <- function(X, AR_Order){ filepath <- paste(system.file(package = "AutoregressionMDE"),"/LegendreTable.csv", sep="") tbl <- read.csv(filepath, header = FALSE) x <- tbl[,1] w <- tbl[,2] nNode <- length(x) Dual <- function(t){ fval <- 0 for (i in 1:nNode){ for(k in 1:AR_Order){ fval <- fval + ( Uk_yt(k, x[i], t, X, AR_Order) )^2 * w[i] } } return(fval) } return(Dual) } Uk_yt <- function(k, y, t, X, AR_Order){ nLength <- length(X) fval <- 0 for(i in 1:nLength){ if(i-k<=0){ Xik <- 0 }else{ Xik <- X[i-k] } tXi1 <- 0 for(j in 1:AR_Order){ if(i-j<=0){ Xij <- 0 }else{ Xij <- X[i-j] } tXi1 <- tXi1 + t[j]*Xij; } fval <- fval + Xik*( (X[i]-tXi1<=y ) - ( -X[i] + tXi1 < y ) ) } fval <- fval/sqrt(nLength) return(fval) }
/scratch/gouwar.j/cran-all/cranData/AutoregressionMDE/R/ARMDE.R
if (getRversion()>="2.15.1") utils::globalVariables(c("mala","edgar","drugbank")) #' Get disease-related genes from eDGAR #' #' #' @param disease Name of the disease, character #' #' @return a vector containing genesymbol related to the disease #' @export #' #' @examples #' result = edgar_disease_gene("diabetes") edgar_disease_gene = function(disease){ grep(toupper(disease),edgar$Disease,value = FALSE) -> grep_temp gene = as.vector(edgar$Gene[grep_temp]) return(gene) } #' Get disease-related genes from DrugBank. #' #' @param search Name of the disease, character #' #' @return The genes related to the disease, list #' @export #' #' @examples #' result = drugbank_disease_gene("diabetes") drugbank_disease_gene = function(search){ grep(toupper(search),drugbank$disease,value = FALSE) -> grep_temp gene = as.vector(drugbank$gene[grep_temp]) return(gene) } #' Get disease-related genes from MalaCards #' #' @param disease Name of the disease #' #' @return The genes related to the disease, character vector #' @export #' #' @examples #' result = malacards_disease_gene("diabetes") malacards_disease_gene = function(disease){ grep(toupper(disease),mala$disease,value = FALSE) -> grep_temp gene = as.vector(mala$gene[grep_temp]) return(gene) } #' Get disease-related genes from eDGAR, DrugBank and MalaCards #' #' @param search Name of the disease #' #' @return #' result$edgar: Containing Disease Name, OMIM ID and Genesymbol (Data comes from the eDGAR) #' result$malacards: Containing genes related to the disease (Data comes from the MalaCards) #' result$drugbank: Containing genes related to the disease (Data comes from the DrugBank) #' @export #' #' @examples #' result = AutoSeed("diabetes") AutoSeed = function(search){ output = c() edgar_disease_gene(search)->output$edgar malacards_disease_gene(search)->output$malacards drugbank_disease_gene(search)->output$drugbank return(output) }
/scratch/gouwar.j/cran-all/cranData/Autoseed/R/AutoSeed.r
# Script containing the functions to calculate the moment of inertia and CG # of different anatomical components # ------------------------------------------------------------------------------ #------------------------- Mass properties - Bone ------------------------------ # ------------------------------------------------------------------------------ #' Bone mass properties #' #' Calculate the moment of inertia of a bone modeled as a hollow cylinder #' with two solid end caps #' #' @param m Mass of bone (kg) #' @param l Length of bone (kg) #' @param r_out Outer radius of bone (m) #' @param r_in Inner radius of bone (m) #' @param rho Density of the bone (kg/m^3) #' @param start a 1x3 vector (x,y,z) representing the 3D point where bone starts. #' Points from the VRP to the bone start. Frame of reference: VRP | Origin: VRP #' @param end a 1x3 vector (x,y,z) representing the 3D point where bone ends. #' Points from the VRP to the bone start. Frame of reference: VRP | Origin: VRP #' #' @return This function returns a list that includes: #' \itemize{ #' \item{I}{a 3x3 matrix representing the moment of inertia tensor of a bone #' modeled as a hollow cylinder with two solid end caps} #' \item{CG}{a 1x3 vector representing the center of gravity position of a bone #' modeled as a hollow cylinder with two solid end caps} #' \item{m}{a double that returns the input bone mass} #' } #' #' @section Warning: #' Parallel axis theorem does not apply between two arbitrary points. #' One point must be the object's center of gravity. #' #' @inherit combine_inertialprop examples #' #' @export #' massprop_bones <- function(m,l,r_out,r_in,rho,start,end){ # ---------------------------- Define geometry ------------------------------- vol = m/rho # total volume of the bone material # calculate how thick the cap needs to be to match volumes: # vol_true = m/rho and vol2 = geometric r_cap = r_out t_cap = 0.5*((-(l*(r_out^2-r_in^2))/(r_in^2))+(vol/(pi*r_in^2))) m_cap = rho*pi*t_cap*r_cap^2 # cylinder geometry m_cyl = m - (2*m_cap) l_cyl = l - (2*t_cap) # --------------------------- Adjust axis ------------------------------------- z_axis = end-start; # Frame of reference: VRP | Origin: VRP temp_vec = c(1,1,1) # arbitrary vector as long as it's not the z-axis x_axis = pracma::cross(z_axis,temp_vec/norm(temp_vec, type = "2")) # doesn't matter where the x axis points as long as: # 1. we know what it is # 2. it's orthogonal to z # calculate the rotation matrix between VRP frame of reference and the object VRP2object = calc_rot(z_axis,x_axis) # Frame of reference: VRP | Origin: VRP # ----------------------- Calculate moment of inertia ----------------------------- I_cyl = calc_inertia_cylhollow(r_out, r_in, l_cyl, m_cyl) # Frame of reference: Bone | Origin: Bone CG I_cap = calc_inertia_cylsolid(r_cap, t_cap, m_cap) # Frame of reference: Bone | Origin: Bone CG # want to move origin from CG to VRP but need to know where the bone is relative to the VRP origin off = VRP2object%*%start # Frame of reference: Bone | Origin: VRP # determine the offset vector for each component with # Frame of reference: Bone | Origin: VRP # the hollow cylinder is displaced halfway along the bone (in z-axis) I_cyl_off = c(0,0,0.5*l) + off # Cap 1 edge centered on the beginning of the bone I_cap1_off = c(0,0,0.5*t_cap) + off # Cap 2 edge centered on the end of the bone I_cap2_off = c(0,0,(l - (0.5*t_cap)))+ off # need to adjust the moment of inertia tensor # Frame of reference: Bone | Origin: VRP I_cyl_vrp = parallelaxis(I_cyl,-I_cyl_off,m_cyl,"CG") I_cap1_vrp = parallelaxis(I_cap,-I_cap1_off,m_cap,"CG") I_cap2_vrp = parallelaxis(I_cap,-I_cap2_off,m_cap,"CG") I_boneaxis = I_cyl_vrp + I_cap1_vrp + I_cap2_vrp # Frame of reference: Bone | Origin: VRP mass_prop = list() # pre-define # Adjust frame to VRP axes mass_prop$I = t(VRP2object) %*% I_boneaxis %*% VRP2object # Frame of reference: VRP | Origin: VRP mass_prop$CG = t(VRP2object) %*% I_cyl_off # Frame of reference: VRP | Origin: VRP mass_prop$m = m return(mass_prop) } # ------------------------------------------------------------------------------ # -------------------------- Mass properties - Muscle -------------------------- # ------------------------------------------------------------------------------ #' Muscle mass properties #' #' Calculate the moment of inertia of a muscle modeled as a solid cylinder #' distributed along the bone length #' #' @param m Mass of muscle (kg). #' @param rho Density of muscle (kg/m^3). #' @param l Length of the muscle group (m). #' @param start a 1x3 vector (x,y,z) representing the 3D point where bone starts. #' Frame of reference: VRP | Origin: VRP. #' @param end a 1x3 vector (x,y,z) representing the 3D point where bone ends. #' Frame of reference: VRP | Origin: VRP. #' #' @author Christina Harvey #' #' @return This function returns a list that includes: #' \itemize{ #' \item{I}{a 3x3 matrix representing the moment of inertia tensor of a muscle #' modeled as a solid cylinder distributed along the bone length.} #' \item{CG}{a 1x3 vector representing the center of gravity position of a muscle #' modeled as a solid cylinder distributed along the bone length.} #' \item{m}{a double that returns the input muscle mass.} #' } #' #' @section Warning: #' Parallel axis theorem does not apply between two arbitrary points. One point #' must be the object's center of gravity. #' #' @inherit combine_inertialprop examples #' #' @export massprop_muscles <- function(m,rho,l,start,end){ r = sqrt(m/(rho*pi*l)) # determine the pseudo radius of the muscles # ------------------------------- Adjust axis -------------------------------- z_axis = end-start temp_vec = c(1,1,1) # arbitrary vector as long as it's not the z-axis x_axis = pracma::cross(z_axis,temp_vec/norm(temp_vec, type = "2")) # doesn't matter where the x axis points as long as: #1. we know what it is #2. it's orthogonal to z # calculate the rotation matrix between VRP frame of reference and the object VRP2object = calc_rot(z_axis,x_axis) # -------------------------- Moment of inertia ------------------------------- I_m = calc_inertia_cylsolid(r, l, m) # Frame of reference: Muscle | Origin: Muscle CG # want to move origin from CG to VRP but need to know where the # bone is relative to the VRP origin off = VRP2object %*% start # Frame of reference: Muscle | Origin: VRP # determine the offset vector for each component CG_m_off = c(0,0,0.5*l)+ off # Frame of reference: Muscle | Origin: VRP # need to adjust the moment of inertia tensor I_m_vrp = parallelaxis(I_m,-CG_m_off,m,"CG") # Frame of reference: Muscle | Origin: VRP mass_prop = list() # pre-define # Adjust frame to VRP axes mass_prop$I = t(VRP2object) %*% I_m_vrp %*% VRP2object # Frame of reference: VRP | Origin: VRP mass_prop$CG = t(VRP2object) %*% CG_m_off # Frame of reference: VRP | Origin: VRP mass_prop$m = m return(mass_prop) } # ------------------------------------------------------------------------------ # ------------------- Mass properties - Skin/Tertiaries ------------------------ # ------------------------------------------------------------------------------ #' Calculates the mass properties of skin or tertiaries #' #' Calculate the moment of inertia of skin or tertiaries modeled as a #' flat triangular plate #' #' @param m Mass of skin (kg) #' @param rho Density of skin (kg/m^3) #' @param pts a 3x3 matrix that represent three points that define the #' vertices of the triangle. Frame of reference: VRP | Origin: VRP #' Must be numbered in a counterclockwise direction for positive area, #' otherwise signs will be reversed. #' each point should be a different of the matrix as follows: #' \itemize{ #' \item{pt1x, pt1y, pt1z} #' \item{pt2x, pt1y, pt2z} #' \item{pt3x, pt3y, pt3z} #' } #' #' @author Christina Harvey #' #' @return This function returns a list that includes: #' point mass #' \itemize{ #' \item{I}{a 3x3 matrix representing the moment of inertia tensor of skin #' modeled as a flat triangular plate} #' \item{CG}{a 1x3 vector representing the center of gravity position of skin #' modeled as a flat triangular plate} #' \item{m}{a double that returns the input skin mass} #' } #' #' #' @section Warning: #' Parallel axis theorem does not apply between two arbitrary points. #' One point must be the object's center of gravity. #' #' Caution: The skin frame of reference assumes that the z axis is normal #' to the incoming points. #' #' @inherit combine_inertialprop examples #' #' @export massprop_skin <- function(m,rho,pts){ # ------------------ Determine the geometry of the skin ---------------------- temp_cross = pracma::cross((pts[3,]-pts[1,]),(pts[3,]-pts[2,])) A = 0.5*norm(temp_cross, type = "2"); v = m/rho t = v/A; # ------------------------------- Adjust axis -------------------------------- # normal to the incoming points z_axis = temp_cross # vector points towards the second input point along the bone edge x_axis = pts[3,]-pts[1,] # calculate the rotation matrix between VRP frame of reference and the object VRP2object = calc_rot(z_axis,x_axis) # Adjust the input pts frame to skin axes adj_pts = pts # define the new matrix for (i in 1:3){ adj_pts[i,] = VRP2object%*%pts[i,] # Frame of reference: Skin | Origin: VRP } # ---------------------------- Moment of inertia ------------------------------ I_s = calc_inertia_platetri(adj_pts, A, rho, t, "I") # Frame of reference: Skin | Origin: Skin CG CG_s = calc_inertia_platetri(adj_pts, A, rho, t, "CG") # Frame of reference: Skin | Origin: VRP # need to adjust the moment of inertia tensor I_s_vrp = parallelaxis(I_s,-CG_s,m,"CG") # Frame of reference: Skin | Origin: VRP mass_prop = list() # pre-define # Adjust frames to VRP mass_prop$I = t(VRP2object) %*% I_s_vrp %*% VRP2object # Frame of reference: VRP | Origin: VRP mass_prop$CG = t(VRP2object) %*% CG_s # Frame of reference: VRP | Origin: VRP mass_prop$m = m return(mass_prop) } # ------------------------------------------------------------------------------ #-- ----------------------- Mass properties - point mass ----------------------- # ------------------------------------------------------------------------------ #' Point-mass mass properties #' #' Calculate the moment of inertia of any point mass #' #' @param m Mass of point mass (kg) #' @param pt a 1x3 vector (x,y,z) representing the location of the point mass. #' Frame of reference: VRP | Origin: VRP #' #' @author Christina Harvey #' #' @return This function returns a list that includes: #' \itemize{ #' \item{I}{a 3x3 matrix representing the moment of inertia tensor #' of a point mass} #' \item{CG}{a 1x3 vector representing the center of gravity position #' of a point mass} #' \item{m}{a double that returns the input mass} #' } #' #' @section Warning: #' Parallel axis theorem does not apply between two arbitrary points. #' One point must be the object's center of gravity. #' #' @inherit combine_inertialprop examples #' #' @export massprop_pm <- function(m,pt){ emtpy_I = matrix(0, nrow = 3, ncol = 3) # 0 tensor for point mass about it's #own CG mass_prop = list() # pre-define # Adjust frames to VRP mass_prop$I = parallelaxis(emtpy_I,-pt,m,"CG") # Frame of reference: VRP | Origin: VRP mass_prop$CG = pt # Frame of reference: VRP | Origin: VRP mass_prop$m = m return(mass_prop) } # ------------------------------------------------------------------------------ # ----------------------- Mass properties - Feathers --------------------------- # ------------------------------------------------------------------------------ #' Feather mass properties #' #' Calculate the moment of inertia of the feathers within the #' feather frame of reference. #' #' @param m_f Mass of the entire feather (kg) #' @param l_c Length of the calamus; start of vane to end of calamus(m) #' @param l_r_cor Length of rachis; tip to start of vane (m) #' @param w_cal Width (diameter) of the cortex part of the calamus (m) #' @param r_b Radius of feather barbs (m) #' @param d_b Distance between barbs (m) #' @param rho_cor Density of the cortex (kg/m^3) #' @param rho_med Density of the medullary (kg/m^3) #' @param w_vp Width of proximal (closest to body) vane (m) #' @param w_vd Width of distal (closest to wing tip) vane (m) #' @param angle Angle between calamus and the vane taken the supplement angle #' to the interior angle. Negative indicates the feather tip is rotated #' proximally relative to the start of the feather vane. #' #' @author Christina Harvey #' #' @section Warning: #' Parallel axis theorem does not apply between two arbitrary points. #' One point must be the object's center of gravity. #' #' CAUTION: While computing the variable components of the feather the x axis #' is the normal of the feather. #' #' @return a list that includes: #' \itemize{ #' \item{I}{a 3x3 matrix representing the moment of inertia tensor of a #' simplified feather with the origin at the feather calamus end and within #' the feather frame of reference} #' \item{CG}{a 1x3 vector representing the center of gravity position of a #' simplified feather with the origin at the feather calamus end and within #' the feather frame of reference} #' \item{m}{a double that returns the feather mass} #' } #' #' @inherit combine_inertialprop examples #' #' @export massprop_feathers <- function(m_f,l_c,l_r_cor,w_cal,r_b,d_b,rho_cor, rho_med,w_vp,w_vd,angle){ # ------------------ Determine the geometry of feathers ----------------------- r_cor = 0.5*w_cal # radius of the cortex part of the calamus # mass of each component of the feather m_vp = rho_cor*(l_r_cor/(d_b+(2*r_b)))*w_vp*pi*r_b^2 # mass of the proximal vane m_vd = rho_cor*(l_r_cor/(d_b+(2*r_b)))*w_vd*pi*r_b^2 # mass of the distal vane m_rc = m_f - m_vp - m_vd # mass of the rachis and calamus #assumes that the interior medullary pyramid has the same height as the cortex exterior r_med = sqrt((m_rc - rho_cor * r_cor ^ 2 * ((pi * l_c) + (4 / 3) * l_r_cor)) / ((4 / 3) * l_r_cor * (rho_med - rho_cor) - l_c * pi * rho_cor)) l_r_med = l_r_cor # ------ Calculate the mass of each component ----- # mass of the cortex part of the calamus m_c = rho_cor*(pi*l_c)*(r_cor^2-r_med^2) # mass of the cortex part of the rachis m_r_cor = (4/3)*rho_cor*(l_r_cor*r_cor^2 - l_r_med*r_med^2) # mass of the medullary part of the rachis m_r_med = (4/3)*rho_med*(r_med^2)*l_r_med # mass as if entire rachis was solid cortex mass_outer = (4/3)*rho_cor*r_cor^2*l_r_cor # mass as if hollow part of rachis was solid cortex mass_inner = (4/3)*rho_cor*r_med^2*l_r_med if (r_med > r_cor | m_rc < 0){ browser() warning("Incorrect feather medullary radius. Larger than the exterior radius.") } # --------------------------- Moment of inertia ----------------------------------- # 1. For each component compute their inertia about their center of mass # in the centroidal axes # 2. Rotate the axes to be in the feather rachis axis (Vanes only) # 3. Parallel axis to the start of feather vane (Vanes only) # 4. Sum the vanes and rachis components # 5. Rotate the axes to be in the feather calamus axis (Rachis and Vanes only) # 6. Parallel axis to the start of feather # 7. Sum all feather components # 8. Rotate axes so that the feather tip will fall on the z-axis # 9. Parallel axes to VRP axes # 10. Rotate axes to the VRP # ------- Calamus ------- # 1. Moment of inertia tensors in the calamus I_cCG = calc_inertia_cylhollow(r_cor, r_med, l_c, m_c) # Frame of reference: Feather Calamus | Origin: Calamus CG # 6. Adjust so that the origin is at the start of the feather - READY TO BE SUMMED WITH OTHER COMPONENTS CG_c1 = c(0,0,0.5*l_c) # Frame of reference: Feather Calamus | Origin: Start of Feather I_c1 = parallelaxis(I_cCG,-CG_c1,m_c, "CG") # Frame of reference: Feather Calamus | Origin: Start of Feather # ------- Rachis ------- # - Medullary - solid square pyramid # Moment of inertia tensor - inner rachis medullary component # CAUTION: this is about the center of base I_r_med_base = calc_inertia_pyrasolid(2*r_med, l_r_med, m_r_med) # Frame of reference: Feather Rachis | Origin: Start of the vane (center) # - Cortex - hollow square pyramid # Moment of inertia tensor - as if solid inner and outer cortex components # CAUTION: this is about the center of base I_r_out_cor = calc_inertia_pyrasolid(2*r_cor, l_r_cor, mass_outer) # Frame of reference: Feather Rachis | Origin: Start of the vane I_r_in_cor = calc_inertia_pyrasolid(2*r_med, l_r_med, mass_inner) # Frame of reference: Feather Rachis | Origin: Start of the vane I_r_cor_base = I_r_out_cor - I_r_in_cor # hollow square pyramid # Frame of reference: Feather Rachis | Origin: Start of the vane CG_pyrasquare = c(0,0,0.25) # multiply by length CG_r_out_cor = CG_pyrasquare*l_r_cor # Frame of reference: Feather Rachis | Origin: Start of the vane CG_r_in_cor = CG_pyrasquare*l_r_med # Frame of reference: Feather Rachis | Origin: Start of the vane # Calculate the CG of hollow cortex pyramid CG_r_cor1 = (mass_outer*CG_r_out_cor - mass_inner*CG_r_in_cor)/m_r_cor # Frame of reference: Feather Rachis | Origin: Start of the vane # Calculate the CG of solid medullary pyramid CG_r_med1 = CG_pyrasquare*l_r_med # Frame of reference: Feather Rachis | Origin: Start of the vane # Calculate the CG of the entire rachis CG_r1 = ((CG_r_cor1*m_r_cor)+(CG_r_med1*m_r_med))/(m_r_cor+m_r_med)# Frame of reference: Feather Rachis | Origin: Start of the vane # ------------------- # ------- Vane ------- # 1. Moment of inertia for each vane about their centroidal axes I_vd1 = calc_inertia_platerect(w_vd, l_r_cor, m_vd) # Frame of reference: Feather Distal Vane | Origin: Distal Vane CG CG_vd1 = c(0,-0.5*w_vd,0.5*l_r_cor) # Frame of reference: Feather Distal Vane | Origin: Start of the vane (distal edge) I_vp1 = calc_inertia_platerect(w_vp, l_r_cor, m_vp) # Frame of reference: Feather Proximal Vane | Origin: Proximal Vane CG CG_vp1 = c(0,0.5*w_vp,0.5*l_r_cor) # Frame of reference: Feather Proximal Vane | Origin: Start of the vane (proximal edge) # 2. Rotate positive angle is a ccw rotation about x (normal to the feather plane) ** all angles should be negative for bird feathers rot_vd = rotx(-pracma::atand(r_cor/l_r_cor)) rot_vp = rotx(pracma::atand(r_cor/l_r_cor)) I_vd2 = rot_vd %*% I_vd1 %*% t(rot_vd) # Frame of reference: Feather Rachis | Origin: Distal Vane CG I_vp2 = rot_vp %*% I_vp1 %*% t(rot_vp) # Frame of reference: Feather Rachis | Origin: Proximal Vane CG CG_vd2 = rot_vd %*% CG_vd1 # Frame of reference: Feather Rachis | Origin: Start of the vane (distal edge) CG_vp2 = rot_vp %*% CG_vp1 # Frame of reference: Feather Rachis | Origin: Start of the vane (proximal edge) # 3. adjust I and CG to the start of the vane CG_vd3 = CG_vd2 - c(0,r_cor,0) # Frame of reference: Feather Rachis | Origin: Start of the vane CG_vp3 = CG_vp2 + c(0,r_cor,0) # Frame of reference: Feather Rachis | Origin: Start of the vane I_vd3 = parallelaxis(I_vd2,-CG_vd3,m_vd, "CG") # Frame of reference: Feather Rachis | Origin: Start of the vane I_vp3 = parallelaxis(I_vp2,-CG_vp3,m_vp, "CG") # Frame of reference: Feather Rachis | Origin: Start of the vane # ----------- Rotate all Rachis and Vane components relative to the calamus ----------------- # 4. sum the rachis and vane components that are in Frame of reference: Feather Rachis | Origin: Start of the vane m_r = m_r_cor+m_r_med+m_vd+m_vp I_vr1 = I_vp3 + I_vd3 + I_r_med_base + I_r_cor_base CG_vr1 = ((CG_r_cor1 * m_r_cor) + (CG_r_med1 * m_r_med) + (CG_vd3 * m_vd) + (CG_vp3 * m_vp)) / (m_r) # Frame of reference: Feather Rachis | Origin: Start of the vane # 5. Rotate the frame of reference from the rachis to the calamus I_vr2 = rotx(angle) %*% I_vr1 %*% t(rotx(angle)) # Frame of reference: Feather Calamus | Origin: Start of the vane CG_vr2 = rotx(angle) %*% CG_vr1 # Frame of reference: Feather Calamus | Origin: Start of the vane # 6. Adjust the origin first to the CG of the entire rachis and then to the start of the feather I_vrCG = parallelaxis(I_vr2,CG_vr2,m_r,"A") # Frame of reference: Feather Calamus | Origin: Rachis & Vane CG CG_vr3 = CG_vr2 + c(0,0,l_c) # Frame of reference: Feather Calamus | Origin: Start of Feather I_vr3 = parallelaxis(I_vrCG,-CG_vr3,m_r,"CG") # Frame of reference: Feather Calamus | Origin: Start of Feather # 7. Sum all feather components - must be in Frame of reference: Feather Calamus | Origin: Start of Feather ----------------- I_1 = I_c1 + I_vr3 CG_1 = ((CG_c1*m_c)+(CG_vr3*m_r))/m_f # 8. Rotate the axes about the x-axis with the origin at the start of the feather so that the length of the calamus is no longer directly along the z-axis. full_rot = rotx(pracma::atand(l_r_cor * abs(pracma::sind(angle)) / (l_c + l_r_cor * abs( pracma::cosd(angle) )))) I_2 = full_rot %*% I_1 %*% t(full_rot) # Frame of reference: Feather start to tip | Origin: Start of Feather CG_2 = full_rot %*% CG_1 # Frame of reference: Feather start to tip | Origin: Start of Feather I_fCG = parallelaxis(I_2,CG_2,m_f,"A") # Frame of reference: Feather start to tip | Origin: Feather CG #Ensures that the final frame of reference z-axis points from the start of the feather to the feather tip and the x axis points upwards (dorsally) normal from the feather surface mass_prop = list() # pre-define mass_prop$I = I_fCG mass_prop$CG = CG_2 mass_prop$m = m_f return(mass_prop) } # ------------------------------------------------------------------------------ # ---------------- Mass properties - Feathers (Transform) ---------------------- # ------------------------------------------------------------------------------ #' Transform feather specific inertial properties to current position #' #' @param m_f a scalar representing the mass of the feather (kg) #' @param I_fCG a 3x3 matrix representing the moment of inertia tensor with the #' origin at the feather calamus end and within the feather frame of reference #' @param CG_start a 1x3 vector representing the center of gravity of the #' feather with the origin at the feather calamus end and within the feather #' frame of reference #' @param start a 1x3 vector representing the location of the feather calamus #' end with the origin at the VRP and within the full bird frame of reference #' @param end a 1x3 vector representing the location of the feather #' tip with the origin at the VRP and within the full bird frame of reference #' @param normal a 1x3 vector representing the normal to the plane of the #' feather vanes within the full bird frame of reference #' #' @return a list that includes: #' \itemize{ #' \item{I}{a 3x3 matrix representing the moment of inertia tensor of a #' simplified feather with the origin at the VRP and within the full bird #' frame of reference} #' \item{CG}{a 1x3 vector representing the center of gravity position of a #' simplified feather with the origin at the VRP and within the full bird #' frame of reference} #' \item{m}{a double that returns the feather mass} #' } #' #' @inherit combine_inertialprop examples #' #' @export structural2VRP_feat <- function(m_f, I_fCG, CG_start, start, end, normal){ # ------------------------------- Adjust axis ------------------------------------- # first find the frame where z points towards the tip then rotate to frame where z axis points straight along the calamus z_axis = end - start # Frame of reference: VRP | Origin: VRP x_axis = normal # Frame of reference: VRP | Origin: VRP # calculate the rotation matrix between VRP frame of reference and the feather start to tip VRP2object = calc_rot(z_axis,x_axis) # To properly use parallel axis first, return the origin to the center of gravity of the full feather # 9. Need to return origin to VRP before rotating to the final axis system off = VRP2object %*% start # Frame of reference: Feather start to tip | Origin: VRP CG_3 = CG_start + off # Frame of reference: Feather start to tip | Origin: VRP I_3 = parallelaxis(I_fCG,-CG_3,m_f,"CG") # Frame of reference: Feather start to tip | Origin: VRP # 10. Rotate the FOR to the VRP axes mass_prop = list() # pre-define mass_prop$I = t(VRP2object) %*% I_3 %*% VRP2object # Frame of reference: VRP | Origin: VRP mass_prop$CG = t(VRP2object) %*% CG_3 # Frame of reference: VRP | Origin: VRP mass_prop$m = m_f return(mass_prop) } # ------------------------------------------------------------------------------ #-------------------------- Feather Orientation -------------------------------- # ------------------------------------------------------------------------------ #' Determine the feather orientation #' #' Code that returns the orientation of each primary and secondary feather on the wing. #' #' @param no_pri a scalar representing the amount of primary feathers. #' @param no_sec a scalar representing the amount of secondary feathers. #' @param Pt1 a 1x3 vector (x,y,z) representing the point on the #' shoulder joint (m). #' @param Pt2 a 1x3 vector (x,y,z) representing the point on the #' elbow joint (m). #' @param Pt3 a 1x3 vector (x,y,z) representing the point on the #' wrist joint (m). #' @param Pt4 a 1x3 vector (x,y,z) representing the point on the #' end of carpometacarpus (m). #' @param Pt8 a 1x3 vector (x,y,z) representing the point on tip #' of most distal primary (m). #' @param Pt9 a 1x3 vector (x,y,z) representing the point on the tip #' of the last primary to model as if it is on the end of the carpometacarpus (m). #' @param Pt10 1x3 vector (x,y,z) representing the point on tip #' of last primary to model as if it was distributed along the carpometacarpus (m). #' Usually the first secondary feather tip. #' @param Pt11 1x3 vector (x,y,z) representing the point on #' tip of most proximal secondary feather (m). #' @param Pt12 1x3 vector (x,y,z) representing the point on #' exterior shoulder position (wing root leading edge) (m). #' #' @author Christina Harvey #' #' @return a list called "feather". This contains three matrices. #' 1. "loc_start" a matrix defining the 3D point where each feather starts. #' Rows are the different feathers and columns are x, y, z coordinates #' respectively. #' 2. "loc_end" a matrix defining the 3D point where each feather end. #' Rows are the different feathers and columns are x, y, z coordinates #' respectively. #' 3. "normal" a matrix that gives the vector that defines the normal to #' each feather plane. Rows are the different feathers and columns are x, y, z #' vector directions respectively. #' #' @inherit combine_inertialprop examples #' #' @export orient_feather <- function(no_pri,no_sec,Pt1,Pt2,Pt3,Pt4,Pt8,Pt9,Pt10,Pt11,Pt12){ # pre-define variables count = 1 feather = list() feather$loc_start = matrix(0, nrow = (no_pri+no_sec), ncol = 3) feather$loc_end = matrix(0, nrow = (no_pri+no_sec), ncol = 3) feather$normal = matrix(0, nrow = (no_pri+no_sec), ncol = 3) k = 1 # --- Primaries --- # Calculate the start and end of the primaries for(i in 1:no_pri){ if (i < (no_pri-2)) { # Note: We don't want last primary to be exact same spot as S1 or P7 to be # at same spot as P8 this requires that we skip the first and last # position # -- Start -- # Primaries less than P7 distribute linearly along the carpometacarpus # needs to be 1/8 so that P7 is not right on Pt4 feather$loc_start[count,] = Pt3 + (1/8)*(i)*(Pt4-Pt3) # -- End -- # Distributes linearly between P7 and S1 # needs to be 1/7 so that at i = 7 the end = pt9 feather$loc_end[count,] = Pt10 + (1/7)*(i)*(Pt9-Pt10) } else { # -- Start -- # Any primary past P7 starts on the end of the carpometacarpus feather$loc_start[count,] = Pt4; # -- End -- # Distributes linearly feather$loc_end[count,] = Pt9 + (1/(no_pri-7))*(k)*(Pt8-Pt9); k = k + 1 } count = count + 1 } # --- Secondaries --- # Calculate the start and end of the secondaries given the orientation # it is possible that the secondary moves into a positive area if(Pt11[2]<0){ # vector between S1 and the wing root trailing edge sec_vec = Pt11-Pt10; # proportion along the vector where it intersects y = Pt12y t = (Pt12[2]-Pt10[2])/sec_vec[2]; # Point along the vector at Pt12Y sec_end = c((t*sec_vec[1]+Pt10[1]), Pt12[2], (t*sec_vec[3]+Pt10[3])); }else{ sec_end = Pt11 } for(i in 1:no_sec){ # -- Start -- #equally space the start of the secondaries along the forearm ulna/radius feather$loc_start[count,] = Pt3 + (1/(no_sec-1))*(i-1)*(Pt2-Pt3); # -- End -- feather$loc_end[count,] = Pt10 + (1/(no_sec-1))*(i-1)*(sec_end-Pt10); count = count + 1 } # --- Calculate normal for the feather ---- for(i in 1:(no_pri+no_sec)){ if(i <= no_pri){ # primaries on the carpometacarpus plane feather$normal[i,] = pracma::cross((Pt3-Pt4),(feather$loc_end[i,]-Pt4)) } else { # secondaries on the ulna/radius plane feather$normal[i,] = pracma::cross((Pt2-Pt3),(feather$loc_end[i,]-Pt3)) } } return(feather) } # ------------------------------------------------------------------------------ # -------------------------- Mass properties - Neck ---------------------------- # ------------------------------------------------------------------------------ #' Neck mass properties #' #' Calculate the moment of inertia of a neck modeled as a solid cylinder #' #' @param m Mass of muscle (kg). #' @param r Radius of the neck (m). #' @param l Length of the stretched neck (m). #' @param start a 1x3 vector (x,y,z) representing the 3D point where neck starts. Frame of reference: VRP | Origin: VRP. #' @param end a 1x3 vector (x,y,z) representing the 3D point where neck ends. Frame of reference: VRP | Origin: VRP. #' #' @author Christina Harvey #' #' @return This function returns a list that includes: #' \itemize{ #' \item{I}{a 3x3 matrix representing the moment of inertia tensor of a neck modeled as a solid cylinder.} #' \item{CG}{a 1x3 vector representing the center of gravity position of a neck modeled as a solid cylinder.} #'\item{m}{a double that returns the neck mass.} #' } #' #' @section Warning: #' Parallel axis theorem does not apply between two arbitrary points. One point must be the object's center of gravity. #' #' @export massprop_neck <- function(m,r,l,start,end){ # ------------------------------- Adjust axis -------------------------------- z_axis = end-start temp_vec = c(0,-1,0) # In this case this is not arbitrary and defines the y axis x_axis = pracma::cross(z_axis,temp_vec/norm(temp_vec, type = "2")) VRP2object = calc_rot(z_axis,x_axis) # -------------------------- Moment of inertia -------------------------------- I_n = calc_inertia_cylsolid(r, l, m) # Frame of reference: Neck | Origin: Neck CG # want to move origin from CG to VRP but need to know # where the bone is relative to the VRP origin off = VRP2object %*% start # Frame of reference: Neck | Origin: VRP # determine the offset vector for each component I_n_off = c(0,0,0.5*l)+ off # Frame of reference: Neck | Origin: VRP # need to adjust the moment of inertia tensor I_n_vrp = parallelaxis(I_n,-I_n_off,m,"CG") # Frame of reference: Neck | Origin: VRP mass_prop = list() # pre-define # Adjust frame to VRP axes mass_prop$I = t(VRP2object) %*% I_n_vrp %*% VRP2object # Frame of reference: VRP | Origin: VRP mass_prop$CG = 0.5*(start + end) # Frame of reference: VRP | Origin: VRP mass_prop$m = m return(mass_prop) } # ------------------------------------------------------------------------------ # --------------------------- Mass properties - Head --------------------------- # ------------------------------------------------------------------------------ #' Head mass properties #' #' Calculate the moment of inertia of a head modeled as a solid cone #' #' @param m Mass of head (kg) #' @param r Maximum head radius (m) #' @param l Maximum head length (m) #' @param start a 1x3 vector (x,y,z) representing the 3D point where head starts. #' Frame of reference: VRP | Origin: VRP #' @param end a 1x3 vector (x,y,z) representing the 3D point where head ends. #' Frame of reference: VRP | Origin: VRP #' #' @author Christina Harvey #' #' @return This function returns a list that includes: #' \itemize{ #' \item{I}{a 3x3 matrix representing the moment of inertia tensor of a head #' modeled as a solid cone} #' \item{CG}{a 1x3 vector representing the center of gravity position of a head #' modeled as a solid cone} #'\item{m}{a double that returns the head mass} #' } #' #' @section Warning: #' Parallel axis theorem does not apply between two arbitrary points. #' One point must be the object's center of gravity. #' #' @export massprop_head <- function(m,r,l,start,end){ # ------------------------------- Adjust axis -------------------------------- z_axis = end-start # In this case this is not arbitrary and defines the y axis temp_vec = c(0,-1,0) x_axis = pracma::cross(z_axis,temp_vec/norm(temp_vec, type = "2")) VRP2object = calc_rot(z_axis,x_axis) # -------------------------- Moment of inertia ------------------------------- I_h = calc_inertia_conesolid(r, l, m) # Frame of reference: Head | Origin: Head CG # want to move origin from CG to VRP but need to know # where the bone is relative to the VRP origin off = VRP2object %*% start # Frame of reference: Head | Origin: VRP # determine the offset vector for each component CG_1 = c(0,0,0.25*l)+ off # Frame of reference: Head | Origin: VRP # need to adjust the moment of inertia tensor I_h_vrp = parallelaxis(I_h,-CG_1,m,"CG") # Frame of reference: Head | Origin: VRP mass_prop = list() # pre-define # Adjust frame to VRP axes mass_prop$I = t(VRP2object) %*% I_h_vrp %*% VRP2object # Frame of reference: VRP | Origin: VRP mass_prop$CG = t(VRP2object) %*% CG_1 # Frame of reference: VRP | Origin: VRP mass_prop$m = m return(mass_prop) } # ------------------------------------------------------------------------------ # --------------------------- Mass properties of Tail -------------------------- # ------------------------------------------------------------------------------ #' Head mass properties #' #' Calculate the moment of inertia of a tail modeled as a solid cone #' #' @param m Mass of muscle (kg) #' @param l Length of the tail (m) #' @param w Width of the tail (m) #' @param start a 1x3 vector (x,y,z) representing the 3D point where head starts. #' Frame of reference: VRP | Origin: VRP #' @param end a 1x3 vector (x,y,z) representing the 3D point where head ends. #' Frame of reference: VRP | Origin: VRP #' #' @author Christina Harvey #' #' @return This function returns a list that includes: #' \itemize{ #' \item{I}{a 3x3 matrix representing the moment of inertia tensor of a head #' modeled as a solid cone} #' \item{CG}{a 1x3 vector representing the center of gravity position of a head #' modeled as a solid cone} #'\item{m}{a double that returns the head mass} #' } #' #' @section Warning: #' Parallel axis theorem does not apply between two arbitrary points. #' One point must be the object's center of gravity. #' #' @inherit combine_inertialprop examples #' #' @export massprop_tail <- function(m,l,w,start,end){ # ------------------------------- Adjust axis -------------------------------- z_axis = end-start # must be this value to ensure that the x axis in the tail FOR is the VRP z axis temp_vec = c(0,-1,0) x_axis = pracma::cross(z_axis,temp_vec/norm(temp_vec, type = "2")) VRP2object = calc_rot(z_axis,x_axis) # -------------------------- Moment of inertia ------------------------------- # calculate the tail offset off = VRP2object %*% start # Frame of reference: Tail | Origin: VRP I_t1 = calc_inertia_platerect(w, l, m) # Frame of reference: Tail | Origin: Tail CG CG_t = off + c(0,0,0.5*l) # Frame of reference: Tail | Origin: VRP I_t2 = parallelaxis(I_t1,-CG_t,m,"CG") # Frame of reference: Tail | Origin: VRP mass_prop = list() # pre-define # Adjust frame to VRP axes mass_prop$I = t(VRP2object) %*% I_t2 %*% VRP2object # Frame of reference: VRP | Origin: VRP mass_prop$CG = t(VRP2object) %*% CG_t # Frame of reference: VRP | Origin: VRP mass_prop$m = m return(mass_prop) } # ------------------------------------------------------------------------------ # --------------------------- Mass properties of Torso ------------------------- # ------------------------------------------------------------------------------ #' Torso and leg mass properties #' #' Calculate the moment of inertia of a head modeled as a solid cone #' #' @param m_true Mass of the torso and legs - no tail (kg) #' @param m_legs Mass of the legs only (kg) #' @param w_max Maximum width of the body (m) #' @param h_max Maximum height of the body (m) #' @param l_bmax x location of the maximum width of the body (m) #' @param w_leg width of the body at leg insertion (m) #' @param l_leg x location of the leg insertion point (m) #' @param l_tot length of body from clavicle to beginning of the tail (m) #' @param CG_true_x x location of the CG for the torso and legs, #' origin is at the VRP, measured positive if aft of the VRP (m) #' @param CG_true_z z location of the CG for the torso and legs, #' origin is at the VRP (m) #' @param start a 1x3 vector (x,y,z) representing the 3D point where torso starts. #' Frame of reference: VRP | Origin: VRP #' @param end a 1x3 vector (x,y,z) representing the 3D point where tail ends. #' Frame of reference: VRP | Origin: VRP #' #' @author Christina Harvey #' #' @return This function returns a list that includes: #' \itemize{ #' \item{I}{a 3x3 matrix representing the moment of inertia tensor of the #' torso and leg composite body} #' \item{CG}{a 1x3 vector representing the center of gravity position of the #' torso and leg composite body} #' \item{m}{a double that returns the mass of the torso and leg composite body} #' } #' #' @section Warning: #' Parallel axis theorem does not apply between two arbitrary points. #' One point must be the object's center of gravity. #' #' @inherit combine_inertialprop examples #' #' @export massprop_torso <- function(m_true, m_legs, w_max, h_max, l_bmax, w_leg, l_leg,l_tot, CG_true_x, CG_true_z, start, end){ # ----------------------------- Adjust axis ---------------------------------- z_axis = end-start # In this case this is not arbitrary and defines the y axis temp_vec = c(0,-1,0) # z points along the VRP positive z axis x_axis = pracma::cross(z_axis,temp_vec/norm(temp_vec, type = "2")) VRP2object = calc_rot(z_axis,x_axis) # -------------------------- Moment of inertia ------------------------------- # pre-define info about the partial elliptic cone h_leg = w_leg*h_max/w_max l_par = l_leg-l_bmax l_full = (l_par/(w_max-w_leg))*w_max # based on equivalent triangle l_end = l_tot - l_leg # ------------------------- Legs - point mass -------------------------------- # placed at the bottom of the bird body CG_leg_right = c(0.5*h_leg, 0.5*w_leg, l_leg) # Frame of reference: Torso | Origin: VRP CG_leg_left = c(0.5*h_leg,-0.5*w_leg, l_leg) # Frame of reference: Torso | Origin: VRP leg_right = massprop_pm(0.5*m_legs, CG_leg_right) # Frame of reference: Torso | Origin: VRP leg_left = massprop_pm(0.5*m_legs, CG_leg_left) # Frame of reference: Torso | Origin: VRP # adjust torso mass and CG to remove the effects of the legs m_body = (m_true-m_legs) # Caution CG_body_z refers to the full bird FOR but in this formulation the # torso FOR causes z to be torso x and x to be the torso -z # CG_body_x comes in positive even though it is a negative x from the BRP CG_body_z = (CG_true_z * m_true - CG_leg_left[1] * 0.5 * m_legs - CG_leg_right[1] * 0.5 * m_legs) / m_body # Yes this is supposed to in index 3 - in the torso FOR CG_body_x = (CG_true_x * m_true - CG_leg_left[3] * 0.5 * m_legs - CG_leg_right[3] * 0.5 * m_legs) / m_body # -------------- Calculate the body volume to have an estimate for the density -------------- # - 1. volume and CGx of the hemiellipsoid - v_ell = (1/6)*(pi*w_max*h_max*l_bmax) CG_ell = (5/8)*l_bmax # Frame of reference: Torso | Origin: VRP # - 2. volume of the partial elliptical cone - # volume as if the interior cone went to full length v_full = (1/12)*pi*w_max*h_max*l_full #volume of the ghost part of the cone v_cut = (1/12)*pi*w_leg*h_leg*(l_full-l_par) v_par = v_full-v_cut CG_full = l_bmax + 0.25*l_full # Frame of reference: Torso | Origin: VRP CG_cut = l_leg + 0.25*(l_full-l_par) # Frame of reference: Torso | Origin: VRP CG_par = (1/v_par)*(v_full*CG_full - v_cut*CG_cut) # Frame of reference: Torso | Origin: VRP # ------ Option 1: Elliptical cylinder back and constant density --------- v_end_1 = (1/4)*(pi*w_leg*h_leg*l_end) CG_end_1 = l_leg+0.5*l_end # Frame of reference: Torso | Origin: VRP rho_avg_1 = m_body/(v_ell + v_par + v_end_1) est_CGx_1 = rho_avg_1*(v_ell*CG_ell + v_par*CG_par + v_end_1*CG_end_1)/m_body # if the error is larger than +- 5% of the torso length if(abs(est_CGx_1-CG_body_x) > 0.05*l_tot){ # ------ Option 2: Elliptical cone back and constant density --------- v_end_2 = (1/12)*(pi*w_leg*h_leg*l_end) CG_end_2 = l_leg+0.25*l_end # Frame of reference: Torso | Origin: VRP rho_avg_2 = m_body/(v_ell + v_par + v_end_2) est_CGx_2 = rho_avg_2*(v_ell*CG_ell + v_par*CG_par + v_end_2*CG_end_2)/m_body # if the error is larger than +- 5% of the torso length if(abs(est_CGx_2-CG_body_x) > 0.05*l_tot){ # ------ Option 3: Elliptical cylinder back and variable density --------- est_CGx_3 = CG_body_x A = matrix(c(v_par,v_par*CG_par,v_end_1,v_end_1*CG_end_1),2,2) test = pracma::lsqnonlin(density_optimizer, rho_avg_2, options=list(tolx=1e-12, tolg=1e-12), m_body,A,v_ell,est_CGx_3,CG_ell,rho_avg_2) rho_ell = abs(test$x[1]) + 200 b = c((m_body-(rho_ell*v_ell)), ((m_body*est_CGx_3)-(rho_ell*v_ell*CG_ell))) output = solve(A,b) rho_par = output[1] rho_back = output[2] if(rho_par < 0 | rho_back < 0){ # ------ Option 3.5: Elliptical cylinder back and variable density ----- # also allows CG to shift to a max position est_CGx_3 = CG_body_x + 0.05*l_tot A = matrix(c(v_par,v_par*CG_par,v_end_1,v_end_1*CG_end_1),2,2) test = pracma::lsqnonlin(density_optimizer, rho_avg_2, options=list(tolx=1e-12, tolg=1e-12), m_body,A,v_ell,est_CGx_3,CG_ell,rho_avg_2) rho_ell = abs(test$x[1]) + 200 b = c((m_body-(rho_ell*v_ell)), ((m_body*est_CGx_3)-(rho_ell*v_ell*CG_ell))) output = solve(A,b) rho_par = output[1] rho_back = output[2] } option = 3 v_end = (1/4)*(pi*w_leg*h_leg*l_end) CG_end = l_leg+0.5*l_end # Frame of reference: Torso | Origin: VRP }else{ option = 2 v_end = (1/12)*(pi*w_leg*h_leg*l_end) CG_end = l_leg+0.25*l_end # Frame of reference: Torso | Origin: VRP rho_ell = rho_avg_2 rho_par = rho_avg_2 rho_back = rho_avg_2 } }else{ option = 1 v_end = (1/4)*(pi*w_leg*h_leg*l_end) CG_end = l_leg+0.5*l_end # Frame of reference: Torso | Origin: VRP rho_ell = rho_avg_1 rho_par = rho_avg_1 rho_back = rho_avg_1 } # ----------- Estimate the density in each section of the body ------------- # calculate the mass of each section m_ell = rho_ell*v_ell # hemi-ellipsoid m_par = rho_par*v_par # mid section partial cone m_end = rho_back*v_end # end section cone ## ------ Sanity checks --------- # Check that no components have negative mass if(m_ell < 0 | m_par < 0 | m_end < 0){ stop("Error: The mass of one or more of the torso sections is negative.") } # Check that the mass matches the expected value if(abs(m_end+m_par+m_ell-m_body)>0.001){ warning("The mass of the predicted body shape does not match the expected value") } ## ------------------------ FRONT TORSO SECTION ------------------------------ # --------------------------- Hemiellipsoid ---------------------------------- # MOI about the base I_ell1 = calc_inertia_ellipse(h_max/2, w_max/2, l_bmax, m_ell) # Frame of reference: Torso | Origin: Hemiellipsoid base # Define center of gravity wrt to I origin CG_ell1 = c(0,0,-(3/8)*l_bmax) # Frame of reference: Torso | Origin: Hemiellipsoid base # Adjust the moment of inertia to be about the center of gravity of the hemiellipsoid I_ellCG = parallelaxis(I_ell1,CG_ell1,m_ell,"A") # Frame of reference: Torso | Origin: Hemiellipsoid CG # Define center of gravity wrt to VRP origin # NOTE: we need to offset the body from the x axis to ensure that the VRP z-location of the CG is correct in the Torso frame of ref this is the positive x direction CG_ell2 = c(CG_body_z,0,(5/8)*l_bmax) # Frame of reference: Torso | Origin: VRP # Adjust the MOI to be about the VRP I_ell_vrp = parallelaxis(I_ellCG,-CG_ell2,m_ell,"CG") # Frame of reference: Torso | Origin: VRP ## ------------------ MID TORSO SECTION -------------------- # ---------------- Partial elliptic cone ------------------- # CG as if the interior cone went to full length CG_full = c(0,0,0.25*l_full) # Frame of reference: Torso | Origin: Hemiellipsoid base # CG of the ghost part of the cone CG_cut = c(0,0,l_par+0.25*(l_full-l_par)) # Frame of reference: Torso | Origin: Hemiellipsoid base # CG of the partial cone CG_par1 = (1/v_par)*(v_full*CG_full - v_cut*CG_cut) # Frame of reference: Torso | Origin: Hemiellipsoid base m_cut = rho_par*v_cut m_full = rho_par*v_full # MOI of the full cone about the wide base I_full = calc_inertia_ellcone(0.5*h_max, 0.5*w_max, l_full, m_full) # Frame of reference: Torso | Origin: Hemiellipsoid base I_cut = calc_inertia_ellcone(0.5*h_leg, 0.5*w_leg, (l_full-l_par), m_cut) # Frame of reference: Torso | Origin: Leg insertion cut base # move the origin to the cut cone CG I_cut2 = parallelaxis(I_cut,-c(0,0,0.25*(l_full - l_par)),m_cut,"A") # Frame of reference: Torso | Origin: Cut cone CG I_cut3 = parallelaxis(I_cut2,CG_cut,m_cut,"CG") # Frame of reference: Torso | Origin: Hemiellipsoid base #remove the ghost part of the cone I_par1 = I_full - I_cut3 # Frame of reference: Torso | Origin: Hemiellipsoid base # Adjust the moment of inertia to be about the center of gravity of the partial cone I_parCG = parallelaxis(I_par1,CG_par1,m_par,"A") # Frame of reference: Torso | Origin: Partial Cone CG # Define CG wrt to VRP origin # NOTE: we need to offset the body from the x axis to ensure that the VRP z-location of the CG is correct in the Torso frame of ref this is the positive x direction CG_par2 = CG_par1 + c(CG_body_z,0,l_bmax) # Frame of reference: Torso | Origin: VRP # Adjust the MOI to be about the VRP I_par_vrp = parallelaxis(I_parCG,-CG_par2,m_par,"CG") # Frame of reference: Torso | Origin: VRP ## ------------------ BACK TORSO SECTION -------------------- if(option == 2){ # -------------- Option 2: Full elliptic cone ------------------- # CG of the end cone CG_end1 = c(0,0,0.25*l_end) # Frame of reference: Torso | Origin: Base of the end cone # MOI of the end cone about the wide base I_end1 = calc_inertia_ellcone(h_leg*0.5, w_leg*0.5, l_end, m_end) # Frame of reference: Torso | Origin: Base of the end cone # Adjust the moment of inertia to be about the center of gravity of the partial cone I_endCG = parallelaxis(I_end1,CG_end1,m_end,"A") # Frame of reference: Torso | Origin: End Cone CG # Define CG wrt to VRP origin # NOTE: we need to offset the body from the x axis to ensure that the VRP z-location of the CG is correct in the Torso frame of ref this is the positive x direction CG_end2 = CG_end1 + c(CG_body_z,0,l_leg) # Frame of reference: Torso | Origin: VRP # Adjust the MOI to be about the VRP I_end_vrp = parallelaxis(I_endCG,-CG_end2,m_end,"CG") # Frame of reference: Torso | Origin: VRP } if(option == 1 | option == 3){ # -------------- Option 1 or 3: Elliptic cylinder ------------------- # Define CG wrt to VRP origin # NOTE: we need to offset the body from the x axis to ensure that the VRP z-location of the CG is correct in the Torso frame of ref this is the positive x direction CG_end2 = c(0,0,0.5*l_end) + c(CG_body_z,0,l_leg) # Frame of reference: Torso | Origin: VRP # MOI of the end cylinder about its CG I_endCG = calc_inertia_ellcyl(h_leg*0.5, w_leg*0.5, l_end, m_end) # Frame of reference: Torso | Origin: End Cyl CG # Adjust the MOI to be about the VRP I_end_vrp = parallelaxis(I_endCG,-CG_end2,m_end,"CG") # Frame of reference: Torso | Origin: VRP } ## ------------- COMBINE ALL TORSO SECTIONS ---------------- # -------------- Sum data and adjust axes ------------------- I_torso_vrp = I_ell_vrp + I_par_vrp + I_end_vrp + leg_right$I + leg_left$I CG_torso_vrp = (1/m_true)*(m_ell*CG_ell2 + m_par*CG_par2 + m_end*CG_end2 + 0.5*m_legs*CG_leg_left + 0.5*m_legs*CG_leg_right) # we need to offset the body from the x axis to ensure that the VRP z-location of the CG is correct in the Torso frame of ref this is the positive x direction mass_prop = list() # pre-define # Adjust frame to VRP axes mass_prop$I = t(VRP2object) %*% I_torso_vrp %*% VRP2object # Frame of reference: VRP | Origin: VRP mass_prop$CG = t(VRP2object) %*% CG_torso_vrp # Frame of reference: VRP | Origin: VRP mass_prop$m = m_true # Check that the CG matches the expected value if(abs(abs(mass_prop$CG[1])-CG_true_x)>0.05*l_tot){ warning("The center of gravity the predicted body shape does not match the expected value.") } return(mass_prop) } # --------------------------------------------------------------------------------------- ##### -------------------- Body component density optimizer ----------------------- ##### # --------------------------------------------------------------------------------------- #' Optimize torso section densities #' #' Function that is used within an optimization routine to select the #' appropriate torso section density #' #' @param x a scalar guess at the density of the torso hemi-ellipsoid section (kg/m^3) #' @param m_body a scalar representing the mass of the full torso #' @param A a 2x2 matrix representing the mass and volume calculations of the #' final two torso section #' @param v_ell a scalar representing the volume of the hemi-ellipsoid #' @param CG_body_x a scalar representing the position of the center of gravity #' of the full torso along the x axis with the origin at the VRP #' @param CG_ell a scalar representing the position of the center of gravity #' of the hemi-ellipsoid section along the x axis with the origin at the VRP #' @param rho_avg average density of the full torso #' #' @return the squared error between the three section densities and the #' average torso density #' #' @inherit combine_inertialprop examples #' #' @export density_optimizer <- function(x,m_body,A,v_ell,CG_body_x,CG_ell,rho_avg){ # ensures that the density is always positive & greater than medullary density rho = abs(x[1]) + 200 b = c((m_body-(rho*v_ell)), ((m_body*CG_body_x)-(rho*v_ell*CG_ell))) output = solve(A,b) err = ((rho-rho_avg)^2 + (output[1]-rho_avg)^2 + (output[2]-rho_avg)^2) if(output[1] < 0 | output[2] < 0 | rho < 0){ err = err + rho_avg } return(err) }
/scratch/gouwar.j/cran-all/cranData/AvInertia/R/anatomicalmassprop.R
#' The identified peripheral and joint 3D positions. #' #' A dataset containing the identified peripheral and joint 3D positions for a #' pigeon BirdID = 20_0300, TestID = 20_03004, FrameID = 317 #' #' @format A matrix with 10 rows and 3 columns. Columns represent x, y, and z coordinate respectively: #' \describe{ #' \item{pt1x, pt1y, pt1z}{Point on the shoulder joint (m).} #' \item{pt2x, pt1y, pt2z}{Point on the elbow joint (m).} #' \item{pt3x, pt3y, pt3z}{Point on the wrist joint (m).} #' \item{pt4x, pt4y, pt4z}{Point on the end of carpometacarpus (m).} #' \item{pt6x, pt6y, pt6z}{Point on the leading edge of the wing in front of the #' wrist joint (m).} #' \item{pt8x, pt8y, pt8z}{Point on tip of most distal primary (m).} #' \item{pt9x, pt9y, pt9z}{Point on the tip of the last primary to model as if #' it is on the end of the carpometacarpus (m).} #' \item{pt10x, pt10y, pt10z}{Point on tip of last primary to model as if #' it was distributed along the carpometacarpus (m).} #' \item{pt11x, pt11y, pt11z}{Point on tip of most proximal feather (m).} #' \item{pt12x, pt12y, pt12z}{Point on exterior shoulder position #' (wing root leading edge) (m).} #' } #' "clean_pts" #' Identification variables for current configuration #' #' A dataset containing the identification data for a #' pigeon BirdID = 20_0300, TestID = 20_03004, FrameID = 317 #' #' @format A dataframe with 1 row and 4 required variables: #' \describe{ #' \item{species}{Species ID code as a string} #' \item{BirdID}{Bird ID code as a string} #' \item{TestID}{Test ID code as a string} #' \item{frameID}{Video frame ID code as a string} #' } #' "dat_id_curr" #' Bird specific morphology dataset #' #' A dataset containing the bird specific morphology data for a #' pigeon BirdID = 20_0300, TestID = 20_03004, FrameID = 317 #' #' @format A dataframe with 1 row and 125 variables. #' Only 29 required for proper operation: #' \describe{ #' \item{total_bird_mass}{Mass of full bird for the current wing (kg)} #' \item{wing_mass}{Mass of one wing, should be the current wing (kg)} #' \item{barb_radius}{Radius of feather barb for current species (m)} #' \item{barb_distance}{Distance between feather barbs for current species (m)} #' \item{brachial_muscle_mass}{Mass of all muscles in the brachial region #' of the wing (kg)} #' \item{antebrachial_muscle_mass}{Mass of all muscles in the antebrachial region #' of the wing (kg)} #' \item{manus_muscle_mass}{Mass of all muscles in the manus region #' of the wing (kg)} #' \item{all_skin_coverts_mass}{Mass of all skin and covert feathers (kg).} #' \item{tertiary_mass}{Mass of tertiary feathers (kg).} #' \item{extend_neck}{Logical input defining whether the neck should be #' modeled as extended or not} #' \item{head_length}{Length of the head from base to tip (m)} #' \item{head_mass}{Mass of the head (kg)} #' \item{head_height}{Height of the head at the base (m)} #' \item{neck_mass}{Mass of the neck (kg)} #' \item{neck_width}{OPTIONAL: Average width of the stretched neck (m)} #' \item{neck_length}{OPTIONAL: Length of the stretched neck (m)} #' \item{torsotail_length}{Length from the beginning of the torso to the tip of the tail (m)} #' \item{torsotail_mass}{Mass of the torso and tail (kg)} #' \item{tail_length}{Length of the tail (m)} #' \item{tail_mass}{Mass of the tail (kg)} #' \item{tail_width}{Average width of the furled tail (m)} #' \item{right_leg_mass}{Mass of the right leg (kg)} #' \item{left_leg_mass}{Mass of the left leg (kg)} #' \item{body_width_max}{Maximum width of the torso (m)} #' \item{body_width_at_leg_insert}{Width of the body at the point #' where the legs are inserted (m).} #' \item{x_loc_of_body_max}{x coordinate from the VRP in the #' full bird frame of reference of the maximum body width (m).} #' \item{x_loc_leg_insertion}{x coordinate from the VRP in the #' full bird frame of reference of the leg insertion location (m).} #' \item{x_loc_TorsotailCoG}{x coordinate from the VRP in the #' full bird frame of reference of the center of gravity of the torso and tail (m).} #' \item{z_loc_TorsotailCoG}{x coordinate from the VRP in the #' full bird frame of reference of the the center of gravity of the torso and tail (m).} #' } #' "dat_bird_curr" #' Wing bone specific morphology dataset #' #' A dataset containing the wing bone specific data for a #' pigeon BirdID = 20_0300, TestID = 20_03004, FrameID = 317 #' #' @format A dataframe with 6 rows and 5 variables: #' \describe{ #' \item{bone}{Bone ID code. Must include: #' "Humerus","Ulna","Radius","Carpometacarpus","Ulnare" and "Radiale".} #' \item{bone_mass}{Mass of bone in the same row as the appropriate #' bone ID code (kg)} #' \item{bone_len}{Length of bone in the same row as the appropriate #' bone ID code (m)} #' \item{bone_out_rad}{Outer radius of bone in the same row as the appropriate #' bone ID code (m)} #' \item{bone_in_rad}{Inner radius of bone in the same row as the appropriate #' bone ID code (m)} #' } #' "dat_bone_curr" #' Flight feather specific morphology dataset #' #' A dataset containing the wing bone specific data for a #' pigeon BirdID = 20_0300, TestID = 20_03004, FrameID = 317 #' #' @format A dataframe with 20 rows and 15 variables. #' Only 8 variables required for proper functioning: #' \describe{ #' \item{feather}{Feather ID code. Must be in standard format i.e. #' 1st primary is "P1", third secondary is "S3", etc. #' Alula feathers should be grouped and named "alula".} #' \item{m_f}{Mass of feather in the same row as the #' appropriate feather ID code (kg)} #' \item{l_cal}{Length of calamus in the same row as the #' appropriate feather ID code (m)} #' \item{l_vane}{Length of rachis/vane in the same row as the #' appropriate feather ID code (m)} #' \item{w_cal}{Width (diameter) of calamus in the same row as the #' appropriate feather ID code (m)} #' \item{w_vp}{Width of proximal vane (average value) in the same row as the #' appropriate feather ID code (m)} #' \item{w_vd}{Width of distal vane (average value) in the same row as the #' appropriate feather ID code (m)} #' \item{vane_angle}{Interior angle between the rachis and calamus (degrees)} #' } #' "dat_feat_curr" #' Material properties. #' #' A dataset containing the material properties for a #' pigeon BirdID = 20_0300, TestID = 20_03004, FrameID = 317. #' #' @format A dataframe with 20 rows and 15 variables. #' Only 8 variables required for proper functioning: #' \describe{ #' \item{material}{Material information. Must include the following: #' "Bone","Skin","Muscle","Cortex", "Medullary"} #' \item{density}{Density of each material (kg/m^3)} #' } #' "dat_mat"
/scratch/gouwar.j/cran-all/cranData/AvInertia/R/data.R
# ------------------------------------------------------------------------------ # ------------------------- Moment of inertia tensors Properties -------------- # ------------------------------------------------------------------------------ # ---------------------- Mass Properties - Solid cylinder ---------------------- #' Moment of inertia tensor of a solid cylinder #' #' Reference: https://apps.dtic.mil/sti/pdfs/AD0274936.pdf #' #' @param r radius of the cylinder (m) #' @param h height of the cylinder (m) #' @param m mass of the cylinder (kg) #' #' @author Christina Harvey #' #' @return a 3x3 matrix representing the moment of inertia tensor of #' a solid cylinder about its center of gravity with z oriented #' through it's major axis #' #' @inherit combine_inertialprop examples #' #' @export #' calc_inertia_cylsolid <- function(r, h, m){ I = matrix(0, nrow = 3, ncol = 3) I[1,1] = (1/12)*(3*r^2+h^2) # Ixx I[2,2] = (1/12)*(3*r^2+h^2) # Iyy I[3,3] = (0.5)*(r^2) # Izz I = m*I return(I) } # ------------------------------------------------------------------------------ # ---------------------- Mass Properties - Hollow cylinder --------------------- # ------------------------------------------------------------------------------ #' Moment of inertia tensor of a hollow cylinder #' #' Reference:https://apps.dtic.mil/sti/pdfs/AD0274936.pdf #' #' @param r_out outer radius of the cylinder (m) #' @param r_in inner radius of the cylinder (m) #' @param h height of the cylinder (m) #' @param m mass of the cylinder (kg) #' #' @author Christina Harvey #' #' @return a 3x3 matrix representing the moment of inertia tensor of a hollow #' cylinder about its center of gravity with z oriented through it's major axis #' #' @inherit combine_inertialprop examples #' #' @export #' calc_inertia_cylhollow <- function(r_out, r_in, h, m){ temp_r = r_out^2 + r_in^2 I = matrix(0, nrow = 3, ncol = 3) I[1,1] = (1/12)*(3*temp_r+h^2) # Ixx I[2,2] = (1/12)*(3*temp_r+h^2) # Iyy I[3,3] = (0.5)*(temp_r) # Izz I = m*I return(I) } # ------------------------------------------------------------------------------ # -------------------- Mass Properties - Solid Ellipse ----------------------- # ------------------------------------------------------------------------------ #' Moment of inertia tensor of solid ellipse CG or a half ellipse centered on #' the base #' #' Reference:https://apps.dtic.mil/sti/pdfs/AD0274936.pdf #' #' @param a half the height along the x direction (m) #' @param b half the width along the y direction (m) #' @param c half the length along the z direction (m) #' @param m mass of the ellipse (kg) #' #' @author Christina Harvey #' #' @return a 3x3 matrix representing the moment of inertia tensor of a solid #' ellipse about its center of gravity with the major axes aligned. #' #' @section #' CAUTION: Origin is at the center of gravity for a full ellipse or at the #' center of the base if modeling a half ellipse. #' #' @inherit combine_inertialprop examples #' #' @export #' calc_inertia_ellipse <- function(a, b, c, m){ I = matrix(0, nrow = 3, ncol = 3) I[1,1] = (b^2 + c^2) # Ixx I[2,2] = (a^2 + c^2) # Iyy I[3,3] = (a^2 + b^2) # Izz I = (1/5)*m*I return(I) } # ------------------------------------------------------------------------------ # -------------------- Mass Properties - Solid Circular Cone ----------------- # ------------------------------------------------------------------------------ #' Moment of inertia tensor of a solid circular cone pyramid #' #' All outputs are based on an origin at the centered point on the base #' Reference: https://apps.dtic.mil/sti/pdfs/AD0274936.pdf #' #' @param r radius of the cone base (m) #' @param h height of the cone (m) #' @param m mass of the cone (kg) #' #' @author Christina Harvey #' #' @return a 3x3 matrix representing the moment of inertia tensor of a solid #' circular cone about #' its center of gravity with z oriented through it's major axis. #' #' @section #' CAUTION: Origin of the output tensor is NOT at the center of gravity but #' at the center of the base. #' #' @inherit combine_inertialprop examples #' #' @export #' calc_inertia_conesolid <- function(r, h, m){ I = matrix(0, nrow = 3, ncol = 3) I[1,1] = (1.5*r^2+h^2) # Ixx I[2,2] = (1.5*r^2+h^2) # Iyy I[3,3] = 3*(r^2) # Izz I = (1/10)*m*I return(I) } # ------------------------------------------------------------------------------ # -------------------- Mass Properties - Solid Elliptical Cone ---------------- # ------------------------------------------------------------------------------ #' Moment of inertia tensor of a solid elliptical cone - end of purple notebook #' derivation verified in green #' #' @param A half height of the wide base (m) #' @param B half width of the wide base (m) #' @param l length of the cone (m) #' @param m mass of the cone (kg) #' #' @author Christina Harvey #' #' @return a 3x3 matrix representing the moment of inertia tensor of a solid #' elliptical cone about the center of the wider base with z oriented #' towards the end. #' #' @section #' CAUTION: Origin of the output tensor is NOT at the center of gravity #' but at the center of the base. #' #' @inherit combine_inertialprop examples #' #' @export #' calc_inertia_ellcone <- function(A, B, l, m){ I = matrix(0, nrow = 3, ncol = 3) tmpx2 = (3/20)*A^2 tmpy2 = (3/20)*B^2 tmpz2 = (1/10)*l^2 I[1,1] = tmpy2 + tmpz2 # Ixx I[2,2] = tmpx2 + tmpz2 # Iyy I[3,3] = tmpx2 + tmpy2 # Izz I = m*I return(I) } # ------------------------------------------------------------------------------ # -------------------- Mass Properties - Solid Elliptical Cylinder ------------ # ------------------------------------------------------------------------------ #' Moment of inertia tensor of a solid elliptical cylinder #' Reference: https://apps.dtic.mil/sti/pdfs/AD0274936.pdf #' #' @param a half height of the base - oriented along the x axis in torso FOR #' (z axis in full bird FOR) (m) #' @param b half width of the base - oriented along the y axis in torso FOR #' (y axis in full bird FOR) (m) #' @param l length of the cylinder - oriented along the z axis in torso FOR #' (x axis in full bird FOR) (m) #' @param m mass of the cylinder (kg) #' #' @author Christina Harvey #' #' @return a 3x3 matrix representing the moment of inertia tensor of a solid #' elliptical cylinder about it's center of gravity #' #' @inherit combine_inertialprop examples #' #' @export #' calc_inertia_ellcyl <- function(a, b, l, m){ I = matrix(0, nrow = 3, ncol = 3) I[1,1] = (1/4)*b^2 + (1/12)*l^2 # Ixx I[2,2] = (1/4)*a^2 + (1/12)*l^2 # Iyy I[3,3] = (1/4)*(a^2+b^2) # Izz I = m*I return(I) } # ------------------------------------------------------------------------------ # -------------------- Mass Properties - Solid Square Pyramid ----------------- # ------------------------------------------------------------------------------ #' Moment of inertia tensor of a solid square pyramid #' Reference: https://apps.dtic.mil/sti/pdfs/AD0274936.pdf #' All outputs are based on an origin at the centered point on the base #' #' @param w entire width of one side of the pyramid base (m) #' @param h entire height of the pyramid (m) #' @param m mass of the pyramid (kg) #' #' @author Christina Harvey #' #' @return a 3x3 matrix representing the moment of inertia tensor of a solid #' square pyramid about its center of gravity with z oriented through it's #' major axis. #' #' @section #' CAUTION: Origin is NOT at the center of gravity but at the center of the base. #' #' @inherit combine_inertialprop examples #' #' @export #' calc_inertia_pyrasolid <- function(w, h, m){ I = matrix(0, nrow = 3, ncol = 3) I[1,1] = (w^2+2*h^2) # Ixx I[2,2] = (w^2+2*h^2) # Iyy I[3,3] = 2*(w^2) # Izz I = (1/20)*m*I return(I) } # ------------------------------------------------------------------------------ # -------------------- Mass Properties - Flat Rectangular Plate --------------- # ------------------------------------------------------------------------------ #' Moment of inertia tensor of a flat rectangular plate - assumes thickness is #' approximately zero #' Reference: https://apps.dtic.mil/sti/pdfs/AD0274936.pdf #' @param w full width of one side of the plate - short edge (m) #' @param h height of the plate - long edge (m) #' @param m mass of the plate (kg) #' #' @author Christina Harvey #' #' @return a 3x3 matrix representing the moment of inertia tensor of a flat #' plate about its center of gravity with z oriented parallel with it's long #' edge (h) and y along its short edge (w) #' #' @inherit combine_inertialprop examples #' #' @export #' calc_inertia_platerect <- function(w, h, m){ I = matrix(0, nrow = 3, ncol = 3) I[1,1] = (w^2+h^2) # Ixx I[2,2] = (h^2) # Iyy I[3,3] = (w^2) # Izz I = (1/12)*m*I return(I) } # ------------------------------------------------------------------------------ # -------------------- Mass Properties - Flat Triangular Plate ---------------- # ------------------------------------------------------------------------------ #' Moment of inertia tensor of a flat triangular plate #' #' Reference: https://apps.dtic.mil/dtic/tr/fulltext/u2/a183444.pdf #' page 4 equations 2.16-2.20 #' #' @param pts a matrix of the three 3D points that define a point on #' the triangular plate. #' Frame of reference: Muscle | Origin: VRP #' each point should be a different row as follows: #' pt1x, pt1y, pt1z #' pt2x, pt1y, pt2z #' pt3x, pt3y, pt3z #' #' @param A area of the triangular plate (m) #' @param rho density of the material (kg/m^3) #' @param t thickness of the plate (m) #' @param desired_prop a string containing either "I" or "CG" depending on the #' desired output #' #' @author Christina Harvey #' #' @return a 3x3 matrix representing the moment of inertia tensor of a flat #' triangular plate about #' its center of gravity. Z axis defined as the normal to the input points. #' #' @section Warning: #' The input points should be defined in a counterclockwise direction around the #' plate in the triangular plate frame of reference #' i.e. all z components should be equal #' #' @inherit combine_inertialprop examples #' #' @export #' calc_inertia_platetri <- function(pts, A, rho, t, desired_prop){ # need to add the first point to allow circular calculation pts = rbind(pts,pts[1,]) # ------------ Center of Gravity Calculation ----------------- # Returns the centroid times the area. Ref: page 2 x1 = 0 y1 = 0 for (i in 1:3){ x1 = x1 + (1/(6*A))*(((pts[i,1]*pts[i+1,2])- (pts[i+1,1]*pts[i,2]))*(pts[i,1]+ pts[i+1,1])); # eqn 2.16 y1 = y1 + (1/(6*A))*(((pts[i,1]*pts[i+1,2])- (pts[i+1,1]*pts[i,2]))*(pts[i,2]+ pts[i+1,2])); # eqn 2.17 } # Frame of reference: Incoming points | Origin: Incoming points CG = c(x1, y1, pts[1,3]); # ------------ Moment of Inertia Calculation ----------------- # Returns the second moment of area if(desired_prop == "I"){ # adjust the incoming points to be so that the origin of the pts is # on the plate's center of gravity adj_pts = pts # define the new matrix for (i in 1:4){ adj_pts[i,] = pts[i,] - CG } # calculate the moment of inertia of the plate x2 = 0; y2 = 0; Ixy = 0; for (i in 1:3){ temp = ((adj_pts[i,1]*adj_pts[i+1,2])-(adj_pts[i+1,1]*adj_pts[i,2])) x2 = x2 + (temp*(adj_pts[i,1]^2+ (adj_pts[i,1]*adj_pts[i+1,1])+ adj_pts[i+1,1]^2)); # eqn 2.18 y2 = y2 + (temp*(adj_pts[i,2]^2+ (adj_pts[i,2]*adj_pts[i+1,2])+ adj_pts[i+1,2]^2)); # eqn 2.20 Ixy = Ixy + (0.5)*(temp*((2*adj_pts[i,1]*adj_pts[i,2]) + adj_pts[i,1]*adj_pts[i+1,2] + adj_pts[i,2]*adj_pts[i+1,1] + (2*adj_pts[i+1,1]*adj_pts[i+1,2]))); # eqn 2.19 } I = matrix(0, nrow = 3, ncol = 3) # define matrix I[1,1] = y2 # Ixx - (y^2)dA I[2,2] = x2 # Iyy - (x^2)dA I[3,3] = (x2+y2) # Izz - (x^2 + y^2)dA I[1,2] = -Ixy # Ixy - (xy)dA I[2,1] = -Ixy # Iyx - (xy)dA I = (1/12)*rho*t*I return(I) } if(desired_prop == "CG"){ return(CG) } } # ------------------------------------------------------------------------------ # ------------------- Mass Properties - Flight Feather ------------------------- # ------------------------------------------------------------------------------ #' Compute the inertia of the individual feathers #' #' @param dat_mat Dataframe related to the current species input as a #' dataframe with the following structure: #' \itemize{ #' \item{material}{Material information. Must include the following: #' "Cortex", "Medullary"} #' \item{density}{Density of each material (kg/m^3)} #' } #' @param dat_feat_curr Dataframe related to the current bird wing feathers #' input as a dataframe with the following structure: #' \itemize{ #' \item{feather}{Feather ID code. Must be in standard format i.e. #' 1st primary is "P1", third secondary is "S3", etc. #' Alula feathers should be grouped and named "alula".} #' \item{m_f}{Mass of feather in the same row as the #' appropriate feather ID code (kg)} #' \item{l_cal}{Length of calamus in the same row as the #' appropriate feather ID code (m)} #' \item{l_vane}{Length of rachis/vane in the same row as the #' appropriate feather ID code (m)} #' \item{w_cal}{Width (diameter) of calamus in the same row as the #' appropriate feather ID code (m)} #' \item{w_vp}{Width of proximal vane (average value) in the same row as the #' appropriate feather ID code (m)} #' \item{w_vd}{Width of distal vane (average value) in the same row as the #' appropriate feather ID code (m)} #' \item{vane_angle}{Interior angle between the rachis and calamus (degrees)} #' } #' NOTE: Alula feathers will be treated as point mass so only the mass of the #' feathers is required. Other columns can be left blank. #' @param dat_bird_curr Dataframe related to the current bird wing that must #' include the following columns: #' \itemize{ #' \item{barb_radius}{Radius of feather barb for current species (m)} #' \item{barb_distance}{Distance between feather barbs for current species (m)} #' } #' #' @return A list with one entry per flight feather. Each primary feather includes the following variables: #' \itemize{ #' \item{I_pri}{a 3x3 matrix representing the moment of inertia about each feather calamus tip (kg-m^2).} #' \item{CG_pri}{a 1x3 vector (x,y,z) representing the center of gravity of the primary feather (m).} #' \item{m_pri}{a double representing the mass of the primary feather (kg).} #' } #' Each secondary feather includes the following variables: #' \itemize{ #' \item{I_sec}{a 3x3 matrix representing the moment of inertia about each feather calamus tip (kg-m^2).} #' \item{CG_sec}{a 1x3 vector (x,y,z) representing the center of gravity of the primary feather (m).} #' \item{m_sec}{a double representing the mass of the primary feather (kg).} #' } #' #' @inherit combine_inertialprop examples #' #' @export #' compute_feat_inertia <- function(dat_mat, dat_feat_curr, dat_bird_curr){ # Set feather to NULL to avoid having to define as a global variable as # CRAN can't see a binding for feather within the dataframe dat_feat_curr feather=NULL # density information rho_cor = dat_mat$density[which(dat_mat$material == "Cortex")] rho_med = dat_mat$density[which(dat_mat$material == "Medullary")] # separate out primaries and secondaries primaries = dat_feat_curr[grep("P",dat_feat_curr$feather),] secondaries = dat_feat_curr[grep("S",dat_feat_curr$feather),] no_sec = length(secondaries$feather) no_pri = length(primaries$feather) #pre-define storage matrices res_pri = list() res_pri$I_pri = array(dim = c(3,3,no_pri)) res_pri$CG_pri = array(dim = c(no_pri,3)) res_pri$m_pri = array(dim = c(no_pri)) res_sec = list() res_sec$I_sec = array(dim = c(3,3,no_sec)) res_sec$CG_sec = array(dim = c(no_sec,3)) res_sec$m_sec = array(dim = c(no_sec)) # --------------------------- Primaries -------------------------------------- # P1 -> P10 for (i in 1:no_pri){ feather_name = paste("P",i,sep = "") # subset data to be for this specific feather pri_info = subset(dat_feat_curr,feather == feather_name) # Calculate MOI and CG tmp = massprop_feathers(pri_info$m_f, pri_info$l_cal, pri_info$l_vane, pri_info$w_cal, dat_bird_curr$barb_radius, dat_bird_curr$barb_distance, rho_cor,rho_med, pri_info$w_vp, pri_info$w_vd, pri_info$vane_angle) # Save MOI, CG and CG*mass res_pri$I_pri[,,i] = tmp$I res_pri$CG_pri[i,] = tmp$CG res_pri$m_pri[i] = tmp$m } # -----------------------------------Secondaries ---------------------------- # S1 -> last secondary for (i in 1:no_sec){ feather_name = paste("S",i,sep = "") # subset data to be for this specific feather sec_info = subset(dat_feat_curr,feather == feather_name) # Calculate MOI and CG tmp = massprop_feathers(sec_info$m_f, sec_info$l_cal, sec_info$l_vane, sec_info$w_cal, dat_bird_curr$barb_radius, dat_bird_curr$barb_distance, rho_cor,rho_med, sec_info$w_vp, sec_info$w_vd, sec_info$vane_angle) # Save MOI, CG and CG*mass res_sec$I_sec[,,i] = tmp$I res_sec$CG_sec[i,] = tmp$CG res_sec$m_sec[i] = tmp$m } return(c(res_pri,res_sec)) }
/scratch/gouwar.j/cran-all/cranData/AvInertia/R/inertiafunctions.R
# Script containing the overarching function that calculates the moment of # inertia and CG for an entire bird # ------------------------------------------------------------------------------ # ------------------ Mass Properties - Combine all body components ------------- # ------------------------------------------------------------------------------ #' Combine body and wing inertial components. #' #' @description Combines data exported from massprop_restbody #' and massprop_birdwing. #' #' @param curr_torsotail_data {Output dataframe from massprop_restbody.} #' @param left_wing_data {Output dataframe from massprop_birdwing.} #' @param right_wing_data {Output dataframe from massprop_birdwing.} #' @param dat_id_curr Dataframe related to the current bird wing ID #' info that must include the following columns: #' \itemize{ #' \item{species}{Species ID code as a string.} #' \item{BirdID}{Bird ID code as a string.} #' \item{TestID}{Test ID code as a string.} #' \item{frameID}{Video frame ID code as a string.} #' } #' @param dat_bird_curr Dataframe related to the current bird wing that must #' include the following columns: #' \itemize{ #' \item{total_bird_mass}{Mass of full bird for the current wing (kg).} #' } #' @param symmetric {Logical indicating if the input wings are symmetric or not. #' If True than left_wing_data = right_wing_data.} #' #' @return a dataframe containing all of the inertial properties for each wing #' component and the full bird about it's center of gravity and the vehicle #' reference point (VRP) #' #' @examples #' # refer to the vignette #' library(AvInertia) #' #' # load data #' data(dat_id_curr, package = "AvInertia") #' data(dat_bird_curr, package = "AvInertia") #' data(dat_feat_curr, package = "AvInertia") #' data(dat_bone_curr, package = "AvInertia") #' data(dat_mat, package = "AvInertia") #' data(clean_pts, package = "AvInertia") #' #' # 1. Determine the center of gravity of the bird's torso (including the legs) #' dat_torsotail_out = massprop_restbody(dat_id_curr, dat_bird_curr) #' # 2. Calculate the inertia of the flight feathers about the tip of the calamus #' feather_inertia <- compute_feat_inertia(dat_mat, dat_feat_curr, dat_bird_curr) #' # 3. Determine the center of gravity of one of the bird's wings #' dat_wing_out = massprop_birdwing(dat_id_curr, dat_bird_curr, #' dat_bone_curr, dat_feat_curr, dat_mat, clean_pts, #' feather_inertia, plot_var = 0) #' # Visualize the center of gravity of each wing component in the x and y axis #' dat_wing_out = massprop_birdwing(dat_id_curr, dat_bird_curr, #' dat_bone_curr, dat_feat_curr, dat_mat, clean_pts, #' feather_inertia, plot_var = "yx") #' # or the y and z axis #' dat_wing_out = massprop_birdwing(dat_id_curr, dat_bird_curr, #' dat_bone_curr, dat_feat_curr, dat_mat, clean_pts, #' feather_inertia, plot_var = "yz") #' # 4. Combine all data and obtain the center of gravity, moment of inertia #' # and principal axes of the bird #' curr_full_bird = combine_inertialprop(dat_torsotail_out,dat_wing_out, #' dat_wing_out, dat_id_curr, dat_bird_curr, symmetric=TRUE) #' #' @export combine_inertialprop <- function(curr_torsotail_data,left_wing_data, right_wing_data, dat_id_curr, dat_bird_curr, symmetric){ # --------------------- Initialize variables ----------------------- # pre-define storage matrices mass_properties = as.data.frame(matrix(0, nrow = 0, ncol = 7)) # overall data colnames(mass_properties) = c("species","BirdID","TestID","FrameID", "component","object","value") # Compute the full bird results fullbird = list() fullbird$I = matrix(0, nrow = 3, ncol = 3) fullbird$CG = matrix(0, nrow = 3, ncol = 1) # Set variables to NULL to avoid having to define as a global variable as # CRAN can't see a binding for feather within the dataframe dat_feat_curr component=NULL object=NULL # --------------------- Combine results ----------------------- # --- Mass --- fullbird$m = sum(subset(curr_torsotail_data, object == "m")$value, subset(left_wing_data, object == "m" & component == "wing")$value, subset(right_wing_data, object == "m" & component == "wing")$value) # --- Moment of Inertia tensor --- **Origin is about the VRP** # Diagonal elements fullbird$I[1,1] = sum(subset(curr_torsotail_data, object == "Ixx")$value) + subset(left_wing_data, object == "Ixx" & component == "wing")$value + subset(right_wing_data, object == "Ixx" & component == "wing")$value fullbird$I[2,2] = sum(subset(curr_torsotail_data, object == "Iyy")$value) + subset(left_wing_data, object == "Iyy" & component == "wing")$value + subset(right_wing_data, object == "Iyy" & component == "wing")$value fullbird$I[3,3] = sum(subset(curr_torsotail_data, object == "Izz")$value) + subset(left_wing_data, object == "Izz" & component == "wing")$value + subset(right_wing_data, object == "Izz" & component == "wing")$value # ------ Off-diagonal elements ---- # only compute xz because the symmetry of the wing will cancel out xy and yz fullbird$I[1,3] = sum(subset(curr_torsotail_data, object == "Ixz")$value) + subset(left_wing_data, object == "Ixz" & component == "wing")$value + subset(right_wing_data, object == "Ixz" & component == "wing")$value fullbird$I[3,1] = fullbird$I[1,3] # --- Center of gravity vector --- # include neck contribution if it was calculated seperate from the head if (length(subset(curr_torsotail_data, object == "m" & component == "neck")$value) == 0) { fullbird$CG[1] = ( subset(curr_torsotail_data, object == "CGx" & component == "head")$value * subset(curr_torsotail_data, object == "m" & component == "head")$value + subset(curr_torsotail_data, object == "CGx" & component == "torso")$value * subset(curr_torsotail_data, object == "m" & component == "torso")$value + subset(curr_torsotail_data, object == "CGx" & component == "tail")$value * subset(curr_torsotail_data, object == "m" & component == "tail")$value + subset(left_wing_data, object == "CGx" & component == "wing")$value * subset(left_wing_data, object == "m" & component == "wing")$value + subset(right_wing_data, object == "CGx" & component == "wing")$value * subset(right_wing_data, object == "m" & component == "wing")$value ) / fullbird$m fullbird$CG[3] = ( subset(curr_torsotail_data, object == "CGz" & component == "head")$value * subset(curr_torsotail_data, object == "m" & component == "head")$value + subset(curr_torsotail_data, object == "CGz" & component == "torso")$value * subset(curr_torsotail_data, object == "m" & component == "torso")$value + subset(curr_torsotail_data, object == "CGz" & component == "tail")$value * subset(curr_torsotail_data, object == "m" & component == "tail")$value + subset(left_wing_data, object == "CGz" & component == "wing")$value * subset(left_wing_data, object == "m" & component == "wing")$value + subset(right_wing_data, object == "CGz" & component == "wing")$value * subset(right_wing_data, object == "m" & component == "wing")$value ) / fullbird$m } else { fullbird$CG[1] = ( subset(curr_torsotail_data, object == "CGx" & component == "head")$value * subset(curr_torsotail_data, object == "m" & component == "head")$value + subset(curr_torsotail_data, object == "CGx" & component == "neck")$value * subset(curr_torsotail_data, object == "m" & component == "neck")$value + subset(curr_torsotail_data, object == "CGx" & component == "torso")$value * subset(curr_torsotail_data, object == "m" & component == "torso")$value + subset(curr_torsotail_data, object == "CGx" & component == "tail")$value * subset(curr_torsotail_data, object == "m" & component == "tail")$value + subset(left_wing_data, object == "CGx" & component == "wing")$value * subset(left_wing_data, object == "m" & component == "wing")$value + subset(right_wing_data, object == "CGx" & component == "wing")$value * subset(right_wing_data, object == "m" & component == "wing")$value ) / fullbird$m fullbird$CG[3] = ( subset(curr_torsotail_data, object == "CGz" & component == "head")$value * subset(curr_torsotail_data, object == "m" & component == "head")$value + subset(curr_torsotail_data, object == "CGz" & component == "neck")$value * subset(curr_torsotail_data, object == "m" & component == "neck")$value + subset(curr_torsotail_data, object == "CGz" & component == "torso")$value * subset(curr_torsotail_data, object == "m" & component == "torso")$value + subset(curr_torsotail_data, object == "CGz" & component == "tail")$value * subset(curr_torsotail_data, object == "m" & component == "tail")$value + subset(left_wing_data, object == "CGz" & component == "wing")$value * subset(left_wing_data, object == "m" & component == "wing")$value + subset(right_wing_data, object == "CGz" & component == "wing")$value * subset(right_wing_data, object == "m" & component == "wing")$value ) / fullbird$m } if (!symmetric){ fullbird$I[2,3] = sum(subset(curr_torsotail_data, object == "Iyz")$value) + subset(left_wing_data, object == "Iyz" & component == "wing")$value + subset(right_wing_data, object == "Iyz" & component == "wing")$value fullbird$I[3,2] = fullbird$I[2,3] fullbird$I[1,2] = sum(subset(curr_torsotail_data, object == "Ixy")$value) + subset(left_wing_data, object == "Ixy" & component == "wing")$value + subset(right_wing_data, object == "Ixy" & component == "wing")$value fullbird$I[2,1] = fullbird$I[1,2] if (length(subset(curr_torsotail_data, object == "m" & component == "neck")$value) == 0) { fullbird$CG[2] = ( subset(curr_torsotail_data, object == "CGy" & component == "head")$value * subset(curr_torsotail_data, object == "m" & component == "head")$value + subset(curr_torsotail_data, object == "CGy" & component == "torso")$value * subset(curr_torsotail_data, object == "m" & component == "torso")$value + subset(curr_torsotail_data, object == "CGy" & component == "tail")$value * subset(curr_torsotail_data, object == "m" & component == "tail")$value + subset(left_wing_data, object == "CGy" & component == "wing")$value * subset(left_wing_data, object == "m" & component == "wing")$value + subset(right_wing_data, object == "CGy" & component == "wing")$value * subset(right_wing_data, object == "m" & component == "wing")$value ) / fullbird$m } else{ fullbird$CG[2] = ( subset(curr_torsotail_data, object == "CGy" & component == "head")$value * subset(curr_torsotail_data, object == "m" & component == "head")$value + subset(curr_torsotail_data, object == "CGy" & component == "neck")$value * subset(curr_torsotail_data, object == "m" & component == "neck")$value + subset(curr_torsotail_data, object == "CGy" & component == "torso")$value * subset(curr_torsotail_data, object == "m" & component == "torso")$value + subset(curr_torsotail_data, object == "CGy" & component == "tail")$value * subset(curr_torsotail_data, object == "m" & component == "tail")$value + subset(left_wing_data, object == "CGy" & component == "wing")$value * subset(left_wing_data, object == "m" & component == "wing")$value + subset(right_wing_data, object == "CGy" & component == "wing")$value * subset(right_wing_data, object == "m" & component == "wing")$value ) / fullbird$m } } # Save the error between the measured bird mass and the final output mass err_mass = fullbird$m - dat_bird_curr$total_bird_mass dat_err = data.frame(species = dat_id_curr$species, BirdID = dat_id_curr$BirdID, TestID = dat_id_curr$TestID, FrameID = dat_id_curr$FrameID, component = "full", object = "m_err", value = err_mass) # ------------------------- Save the full data ----------------------------- # origin about the VRP curr_full_bird_vrp = store_data(dat_id_curr,fullbird, mass_properties,"full_VRP") # ---------- Adjust the final moment of inertia tensor to be about the CG ---- fullbird$I = parallelaxis(fullbird$I,-fullbird$CG,fullbird$m,"A") # store data so far curr_full_bird = store_data(dat_id_curr,fullbird, mass_properties,"full") # calculate the principal axes pri_axes = eigen(fullbird$I) # --- saves the principal axes ----- pri_axes = eigen(fullbird$I) new_row1 = data.frame(species = curr_full_bird$species[1], BirdID = curr_full_bird$BirdID[1], TestID = curr_full_bird$TestID[1], FrameID = curr_full_bird$FrameID[1], component = "full", object = "maj_axis_x", value = pri_axes$vectors[1,1]) new_row2 = data.frame(species = curr_full_bird$species[1], BirdID = curr_full_bird$BirdID[1], TestID = curr_full_bird$TestID[1], FrameID = curr_full_bird$FrameID[1], component = "full", object = "maj_axis_y", value = pri_axes$vectors[2,1]) new_row3 = data.frame(species = curr_full_bird$species[1], BirdID = curr_full_bird$BirdID[1], TestID = curr_full_bird$TestID[1], FrameID = curr_full_bird$FrameID[1], component = "full", object = "maj_axis_z", value = pri_axes$vectors[3,1]) new_row4 = data.frame(species = curr_full_bird$species[1], BirdID = curr_full_bird$BirdID[1], TestID = curr_full_bird$TestID[1], FrameID = curr_full_bird$FrameID[1], component = "full", object = "int_axis_x", value = pri_axes$vectors[1,2]) new_row5 = data.frame(species = curr_full_bird$species[1], BirdID = curr_full_bird$BirdID[1], TestID = curr_full_bird$TestID[1], FrameID = curr_full_bird$FrameID[1], component = "full", object = "int_axis_y", value = pri_axes$vectors[2,2]) new_row6 = data.frame(species = curr_full_bird$species[1], BirdID = curr_full_bird$BirdID[1], TestID = curr_full_bird$TestID[1], FrameID = curr_full_bird$FrameID[1], component = "full", object = "int_axis_z", value = pri_axes$vectors[3,2]) new_row7 = data.frame(species = curr_full_bird$species[1], BirdID = curr_full_bird$BirdID[1], TestID = curr_full_bird$TestID[1], FrameID = curr_full_bird$FrameID[1], component = "full", object = "min_axis_x", value = pri_axes$vectors[1,3]) new_row8 = data.frame(species = curr_full_bird$species[1], BirdID = curr_full_bird$BirdID[1], TestID = curr_full_bird$TestID[1], FrameID = curr_full_bird$FrameID[1], component = "full", object = "min_axis_y", value = pri_axes$vectors[2,3]) new_row9 = data.frame(species = curr_full_bird$species[1], BirdID = curr_full_bird$BirdID[1], TestID = curr_full_bird$TestID[1], FrameID = curr_full_bird$FrameID[1], component = "full", object = "min_axis_z", value = pri_axes$vectors[3,3]) new_row10 = data.frame(species = curr_full_bird$species[1], BirdID = curr_full_bird$BirdID[1], TestID = curr_full_bird$TestID[1], FrameID = curr_full_bird$FrameID[1], component = "full", object = "max_eign", value = pri_axes$values[1]) new_row11 = data.frame(species = curr_full_bird$species[1], BirdID = curr_full_bird$BirdID[1], TestID = curr_full_bird$TestID[1], FrameID = curr_full_bird$FrameID[1], component = "full", object = "int_eign", value = pri_axes$values[2]) new_row12 = data.frame(species = curr_full_bird$species[1], BirdID = curr_full_bird$BirdID[1], TestID = curr_full_bird$TestID[1], FrameID = curr_full_bird$FrameID[1], component = "full", object = "min_eign", value = pri_axes$values[3]) curr_full_bird = rbind(curr_full_bird,curr_full_bird_vrp[1:6,],dat_err, new_row1,new_row2,new_row3,new_row4,new_row5, new_row6,new_row7,new_row8,new_row9,new_row10, new_row11,new_row12) return(curr_full_bird) } # -------------------- Mass Properties - Body less wings ----------------------- #' Calculate the center of gravity and moment of inertia for the head, neck, #' torso and tail. #' #' Function that reads in anatomical data and returns the moment of inertia #' tensor and center of gravity for the head, neck, tail and torso. #' #' @param dat_wingID_curr Dataframe related to the current bird wing ID #' info that must include the following columns: #' \itemize{ #' \item{species}{Species ID code as a string.} #' \item{BirdID}{Bird ID code as a string.} #' \item{TestID}{Test ID code as a string.} #' \item{frameID}{Video frame ID code as a string.} #' } #' #' @param dat_bird_curr Dataframe related to the current bird wing that must #' include the following columns: #' \itemize{ #' \item{extend_neck}{Logical input defining whether the neck should be #' modeled as extended or not.} #' \item{head_length}{Length of the head from base to tip (m).} #' \item{head_mass}{Mass of the head (kg).} #' \item{head_height}{Height of the head at the base (m).} #' \item{neck_mass}{Mass of the neck (kg).} #' \item{neck_width}{OPTIONAL - Average width of the stretched neck (m).} #' \item{neck_length}{OPTIONAL - Length of the stretched neck (m).} #' \item{torsotail_length}{Length from the beginning of the torso to the tip of the tail (m).} #' \item{torsotail_mass}{Mass of the torso and tail (kg).} #' \item{tail_length}{Length of the tail (m).} #' \item{tail_mass}{Mass of the tail (kg).} #' \item{tail_width}{Average width of the furled tail (m).} #' \item{right_leg_mass}{Mass of the right leg (kg).} #' \item{left_leg_mass}{Mass of the left leg (kg).} #' \item{body_width_max}{Maximum width of the torso (m).} #' \item{body_width_at_leg_insert}{Width of the body at the point #' where the legs are inserted (m).} #' \item{x_loc_of_body_max}{x coordinate from the VRP in the #' full bird frame of reference of the maximum body width (m).} #' \item{x_loc_leg_insertion}{x coordinate from the VRP in the #' full bird frame of reference of the leg insertion location (m).} #' \item{x_loc_TorsotailCoG}{x coordinate from the VRP in the #' full bird frame of reference of the center of gravity of the torso and tail (m).} #' \item{z_loc_TorsotailCoG}{x coordinate from the VRP in the #' full bird frame of reference of the the center of gravity of the torso and tail (m).} #' } #' #' @return Function returns a dataframe that includes the moment of inertia and #' center of gravity of head, neck, torso and tail. #' #' @inherit combine_inertialprop examples #' #' @export #' massprop_restbody <- function(dat_wingID_curr, dat_bird_curr){ # --------------------- Initialize variables ----------------------- # pre-define storage matrices mass_properties = as.data.frame(matrix(0, nrow = 0, ncol = 7)) # overall data colnames(mass_properties) = c("species","BirdID","TestID","FrameID", "component","object","value") # ------------------------------------------------------------- # ----------------- Head and neck data ------------------------ # ------------------------------------------------------------- neck_start = c(0,0,0) if (dat_bird_curr$extend_neck){ neck_end = c(dat_bird_curr$neck_length,0,0) head_end = neck_end + c(dat_bird_curr$head_length,0,0) # Calculate the effects of the head head = massprop_head(dat_bird_curr$head_mass, 0.5*dat_bird_curr$head_height, dat_bird_curr$head_length,neck_end,head_end) # Calculate the effects of the neck neck = massprop_neck(dat_bird_curr$neck_mass, 0.5*dat_bird_curr$neck_width, dat_bird_curr$neck_length,neck_start,neck_end) } else{ head_end = c(dat_bird_curr$head_length,0,0) # Calculate the effects of the head + neck head = massprop_head((dat_bird_curr$head_mass+dat_bird_curr$neck_mass), 0.5*dat_bird_curr$head_height, dat_bird_curr$head_length,neck_start,head_end) } # ------------------------------------------------------------- # ------------------- Torso and tail data ------------------------- # ------------------------------------------------------------- tail_start = c(-(dat_bird_curr$torsotail_length-dat_bird_curr$tail_length),0,0) tail_end = c(-dat_bird_curr$torsotail_length,0,0) m_legs = dat_bird_curr$right_leg_mass + dat_bird_curr$left_leg_mass tail = massprop_tail(dat_bird_curr$tail_mass, dat_bird_curr$tail_length, dat_bird_curr$tail_width,tail_start,tail_end) if(abs(tail$CG[1]) > abs(tail_end[1]) | abs(tail$CG[1]) < abs(tail_start[1])){ warning("Tail CG is incorrect") } # adjust the COG from the torso tail to be torso only m_torso = dat_bird_curr$torsotail_mass - dat_bird_curr$tail_mass l_torso = dat_bird_curr$torsotail_length - dat_bird_curr$tail_length CG_x_torso = ((dat_bird_curr$torsotail_mass*dat_bird_curr$x_loc_TorsotailCoG) - (dat_bird_curr$tail_mass*tail$CG[1]))/m_torso CG_z_torso = ((dat_bird_curr$torsotail_mass*dat_bird_curr$z_loc_TorsotailCoG) - (dat_bird_curr$tail_mass*tail$CG[3]))/m_torso # CAUTION: INGOING CG_x must be positive as it calculates a total distance # along the known axis torso = massprop_torso(m_torso, m_legs, dat_bird_curr$body_width_max, dat_bird_curr$body_height_max, dat_bird_curr$x_loc_of_body_max, dat_bird_curr$body_width_at_leg_insert, dat_bird_curr$x_loc_leg_insertion, l_torso, abs(CG_x_torso), CG_z_torso, neck_start, tail_start) # ---------------------------------------------------- # ----------------- Save Data ------------------------ # ---------------------------------------------------- # ---- Head ---- mass_properties = store_data(dat_wingID_curr,head,mass_properties,"head") # ---- Neck ---- if (dat_bird_curr$extend_neck){ mass_properties = store_data(dat_wingID_curr,neck,mass_properties,"neck") } # ---- Torso/Legs ---- mass_properties = store_data(dat_wingID_curr,torso,mass_properties,"torso") # ---- Tail ---- mass_properties = store_data(dat_wingID_curr,tail,mass_properties,"tail") return(mass_properties) } # ----------------- Mass Properties - Halfspan bird wing ---------------------- #' Calculate the center of gravity and moment of inertia for a #' halfspan wing. #' #' Function that reads in anatomical data and returns the moment of inertia #' tensor and center of gravity of a wing one side of the bird. #' #' @param dat_wingID_curr Dataframe related to the current bird wing ID info #' that must include the following columns: #' \itemize{ #' \item{species}{Species ID code as a string.} #' \item{BirdID}{Bird ID code as a string.} #' \item{TestID}{Test ID code as a string.} #' \item{frameID}{Video frame ID code as a string.} #' } #' #' @param dat_bird_curr Dataframe related to the current bird wing that must #' include the following columns: #' \itemize{ #' \item{total_bird_mass}{Mass of full bird for the current wing (kg).} #' \item{wing_mass}{Mass of one wing, should be the current wing (kg).} #' \item{barb_radius}{Radius of feather barb for current species (m).} #' \item{barb_distance}{Distance between feather barbs for current species (m).} #' \item{brachial_muscle_mass}{Mass of all muscles in the brachial region #' of the wing (kg).} #' \item{antebrachial_muscle_mass}{Mass of all muscles in the antebrachial region #' of the wing (kg).} #' \item{manus_muscle_mass}{Mass of all muscles in the manus region #' of the wing (kg).} #' \item{all_skin_coverts_mass}{Mass of all skin and covert feathers (kg).} #' \item{tertiary_mass}{Mass of tertiary feathers (kg).} #' } #' #' @param dat_bone_curr Dataframe (6 row x 5 column) related to the current bird #' wing bones that must include the following columns: #' \itemize{ #' \item{bone}{Bone ID code. Must include: #' "Humerus","Ulna","Radius","Carpometacarpus","Ulnare" and "Radiale".} #' \item{bone_mass}{Mass of bone in the same row as the appropriate #' bone ID code (kg).} #' \item{bone_len}{Length of bone in the same row as the appropriate #' bone ID code (m).} #' \item{bone_out_rad}{Outer radius of bone in the same row as the appropriate #' bone ID code (m).} #' \item{bone_in_rad}{Inner radius of bone in the same row as the appropriate #' bone ID code (m).} #' } #' #' @param dat_feat_curr Dataframe related to the current bird wing feathers #' input as a dataframe with the following structure: #' \itemize{ #' \item{feather}{Feather ID code. Must be in standard format i.e. #' 1st primary is "P1", third secondary is "S3", etc. #' Alula feathers should be grouped and named "alula".} #' \item{m_f}{Mass of feather in the same row as the #' appropriate feather ID code (kg).} #' \item{l_cal}{Length of calamus in the same row as the #' appropriate feather ID code (m).} #' \item{l_vane}{Length of rachis/vane in the same row as the #' appropriate feather ID code (m).} #' \item{w_cal}{Width (diameter) of calamus in the same row as the #' appropriate feather ID code (m).} #' \item{w_vp}{Width of proximal vane (average value) in the same row as the #' appropriate feather ID code (m).} #' \item{w_vd}{Width of distal vane (average value) in the same row as the #' appropriate feather ID code (m).} #' \item{vane_angle}{Interior angle between the rachis and calamus (degrees).} #' } #' NOTE: Alula feathers will be treated as point mass so only the mass of the #' feathers is required. Other columns can be left blank. #' #' @param dat_mat_curr Dataframe related to the current species input as a #' dataframe with the following structure: #' \itemize{ #' \item{material}{Material information. Must include the following: #' "Bone","Skin","Muscle","Cortex", "Medullary"} #' \item{density}{Density of each material (kg/m^3).} #' } #' #' @param clean_pts A data frame of the key positions of the bird as follows: #' \itemize{ #' \item{pt1x, pt1y, pt1z}{Point on the shoulder joint (m).} #' \item{pt2x, pt1y, pt2z}{Point on the elbow joint (m).} #' \item{pt3x, pt3y, pt3z}{Point on the wrist joint (m).} #' \item{pt4x, pt4y, pt4z}{Point on the end of carpometacarpus (m).} #' \item{pt6x, pt6y, pt6z}{Point on the leading edge of the wing in front of the #' wrist joint (m).} #' \item{pt8x, pt8y, pt8z}{Point on tip of most distal primary (m).} #' \item{pt9x, pt9y, pt9z}{Point on the tip of the last primary to model as if #' it is on the end of the carpometacarpus (m).} #' \item{pt10x, pt10y, pt10z}{Point on tip of last primary to model as if #' it was distributed along the carpometacarpus (m).} #' \item{pt11x, pt11y, pt11z}{Point on tip of most proximal feather (m).} #' \item{pt12x, pt12y, pt12z}{Point on exterior shoulder position #' (wing root leading edge) (m).} #' } #' #' @param feather_inertia A list with one entry per flight feather. Each primary feather includes the following variables: #' \itemize{ #' \item{I_pri}{a 3x3 matrix representing the moment of inertia about each feather calamus tip (kg-m^2).} #' \item{CG_pri}{a 1x3 vector (x,y,z) representing the center of gravity of the primary feather (m).} #' \item{m_pri}{a double representing the mass of the primary feather (kg).} #' } #' Each secondary feather includes the following variables: #' \itemize{ #' \item{I_sec}{a 3x3 matrix representing the moment of inertia about each feather calamus tip (kg-m^2).} #' \item{CG_sec}{a 1x3 vector (x,y,z) representing the center of gravity of the primary feather (m).} #' \item{m_sec}{a double representing the mass of the primary feather (kg).} #' } #' #' @param plot_var A string that defines the x-axis and y-axis of the output plot. #' Can either equal "yx" or "yz". #' #' @section CAUTION: #' All points must all have the vehicle reference point (VRP) as their #' origin and the vehicle major axes as their frame of reference. This #' is normally selected so that the VRP is in line with the body center #' of gravity. Ensure the axes used represent a right-handed axis system. #' #' @author Christina Harvey #' #' @return Function returns a dataframe that includes the moment of inertia and #' center of gravity of one wing about the VRP in the VRP frame and that of each #' major anatomical group i.e. skin, feathers, bones, muscles. #' #' @inherit combine_inertialprop examples #' #' @export #' massprop_birdwing <- function(dat_wingID_curr, dat_bird_curr, dat_bone_curr, dat_feat_curr, dat_mat_curr, clean_pts, feather_inertia, plot_var){ # --------------------- Initialize variables ----------------------- mass_properties = as.data.frame(matrix(0, nrow = 0, ncol = 7)) # overall data column_names = c("species","BirdID","TestID","FrameID", "component","object","value") colnames(mass_properties) = column_names # Set variables to NULL to avoid having to define as a global variable as # CRAN can't see a binding for feather within the dataframe dat_feat_curr feather=NULL bone=NULL mass_properties_bone = mass_properties # specific bone data mass_properties_muscle = mass_properties # specific muscle data mass_properties_skin = mass_properties # specific skin data mass_properties_feathers = mass_properties # individual feather mass data # define incoming points Pt1 = clean_pts[1,] # shoulder Pt2 = clean_pts[2,] # elbow Pt3 = clean_pts[3,] # wrist Pt4 = clean_pts[4,] # end of carpometacarpus (cmc) Pt6 = clean_pts[5,] # leading edge in front of wrist Pt8 = clean_pts[6,] # tip of most distal primary Pt9 = clean_pts[7,] # tip of last primary as if on the end of the cmc Pt10 = clean_pts[8,] # tip of S1 Pt11 = clean_pts[9,] # tip of last secondary feather at wing root Pt12 = clean_pts[10,] # leading edge of wing root # -------------------------------------------------- # --------------- Bone Data ------------------------ # -------------------------------------------------- rho_bone = dat_mat_curr$density[which(dat_mat_curr$material == "Bone")] dat_bone_hum = subset(dat_bone_curr, bone == "Humerus") dat_bone_uln = subset(dat_bone_curr, bone == "Ulna") dat_bone_rad = subset(dat_bone_curr, bone == "Radius") dat_bone_car = subset(dat_bone_curr, bone == "Carpometacarpus") hum = massprop_bones(dat_bone_hum$bone_mass,dat_bone_hum$bone_len, dat_bone_hum$bone_out_rad,dat_bone_hum$bone_in_rad, rho_bone, Pt1, Pt2) ulna = massprop_bones(dat_bone_uln$bone_mass,dat_bone_uln$bone_len, dat_bone_uln$bone_out_rad,dat_bone_uln$bone_in_rad, rho_bone, Pt2, Pt3) radius = massprop_bones(dat_bone_rad$bone_mass,dat_bone_rad$bone_len, dat_bone_rad$bone_out_rad,dat_bone_rad$bone_in_rad, rho_bone, Pt2, Pt3) car = massprop_bones(dat_bone_car$bone_mass,dat_bone_car$bone_len, dat_bone_car$bone_out_rad,dat_bone_car$bone_in_rad, rho_bone, Pt3, Pt4) wristbone = massprop_pm((subset(dat_bone_curr, bone == "Ulnare")$bone_mass + subset(dat_bone_curr, bone == "Radiale")$bone_mass), Pt3) # --- All Bones --- prop_bone = list() # simply addition as long as about the same origin in the same frame of # reference #(Frame of reference: VRP | Origin: VRP) prop_bone$I = hum$I + ulna$I + radius$I + car$I + wristbone$I # weighted average of the individual center of mass #(Frame of reference: VRP | Origin: VRP) prop_bone$CG = ( dat_bone_hum$bone_mass * hum$CG + dat_bone_uln$bone_mass * ulna$CG + dat_bone_rad$bone_mass * radius$CG + dat_bone_car$bone_mass * car$CG + ( subset(dat_bone_curr, bone == "Ulnare")$bone_mass + subset(dat_bone_curr, bone == "Radiale")$bone_mass ) * wristbone$CG ) / sum(dat_bone_curr$bone_mass) prop_bone$m = sum(dat_bone_curr$bone_mass) # ---------------------------------------------------- # --------------- Muscle Data ------------------------ # ---------------------------------------------------- rho_muscle = dat_mat_curr$density[which(dat_mat_curr$material == "Muscle")] mass_muscles = c() mass_muscles[1] = dat_bird_curr$brachial_muscle_mass mass_muscles[2] = dat_bird_curr$antebrachial_muscle_mass mass_muscles[3] = dat_bird_curr$manus_muscle_mass brach = massprop_muscles(mass_muscles[1],rho_muscle,dat_bone_hum$bone_len, Pt1,Pt2) abrach = massprop_muscles(mass_muscles[2],rho_muscle,dat_bone_uln$bone_len, Pt2,Pt3) manus = massprop_muscles(mass_muscles[3],rho_muscle,dat_bone_car$bone_len, Pt3,Pt4) # --- All Muscles --- prop_muscles = list() # simply addition as long as about same origin in the same frame of reference # (Frame of reference: VRP | Origin: VRP) prop_muscles$I = brach$I + abrach$I + manus$I # weighted average of the individual center of mass # (Frame of reference: VRP | Origin: VRP) prop_muscles$CG = (mass_muscles[1]*brach$CG + mass_muscles[2]*abrach$CG + mass_muscles[3]*manus$CG)/sum(mass_muscles) prop_muscles$m = sum(mass_muscles) # ------------------------------------------------------- # ----------------- Feather Data ------------------------ # ------------------------------------------------------- # density information rho_cor = dat_mat_curr$density[which(dat_mat_curr$material == "Cortex")] rho_med = dat_mat_curr$density[which(dat_mat_curr$material == "Medullary")] # separate out primaries and secondaries primaries = dat_feat_curr[grep("P",dat_feat_curr$feather),] secondaries = dat_feat_curr[grep("S",dat_feat_curr$feather),] no_sec = length(secondaries$feather) no_pri = length(primaries$feather) #pre-define storage matrices res_pri = list() res_pri$I = array(dim = c(3,3,no_pri)) res_pri$CG = array(dim = c(no_pri,3)) res_pri$CGm = array(dim = c(no_pri,3)) res_pri$m = array(dim = c(no_pri)) res_sec = list() res_sec$I = array(dim = c(3,3,no_sec)) res_sec$CG = array(dim = c(no_sec,3)) res_sec$CGm = array(dim = c(no_sec,3)) res_sec$m = array(dim = c(no_sec)) # determine the orientation and normal of each feather feather_info = orient_feather(no_pri,no_sec,Pt1,Pt2,Pt3,Pt4, Pt8,Pt9,Pt10,Pt11,Pt12) # --------------------------- Primaries -------------------------------------- # P1 -> P10 for (i in 1:no_pri){ # Adjust MOI and CG to the current orientation tmp = structural2VRP_feat(feather_inertia$m_pri[i], feather_inertia$I_pri[,,i], feather_inertia$CG_pri[i,], feather_info$loc_start[i,], feather_info$loc_end[i,], feather_info$normal[i,]) # Save MOI, CG and CG*mass res_pri$I[,,i] = tmp$I res_pri$CG[i,] = tmp$CG res_pri$CGm[i,] = tmp$CG*tmp$m res_pri$m[i] = tmp$m } # --------------------------Secondaries ------------------------------------- # S1 -> last secondary for (i in 1:no_sec){ # Adjust MOI and CG to the current orientation tmp = structural2VRP_feat(feather_inertia$m_sec[i], feather_inertia$I_sec[,,i], feather_inertia$CG_sec[i,], feather_info$loc_start[i+no_pri,], feather_info$loc_end[i+no_pri,], feather_info$normal[i+no_pri,]) # Save MOI, CG and CG*mass res_sec$I[,,i] = tmp$I res_sec$CG[i,] = tmp$CG res_sec$CGm[i,] = tmp$CG*tmp$m res_sec$m[i] = tmp$m } # -------------------------------- Alula ------------------------------------- m_alula = subset(dat_feat_curr,feather == "alula")$m_f alula = massprop_pm(m_alula, Pt6) # ------------------------------ Tertiaries ---------------------------------- # position where the teritaries likely encounter the body edge_tert = c(Pt11[1],min(Pt12[2],Pt11[2]),Pt12[3]) prop_tertiary1 = massprop_skin(0.5*dat_bird_curr$tertiary_mass, rho_cor,rbind(Pt12,edge_tert,Pt2)) prop_tertiary2 = massprop_skin(0.5*dat_bird_curr$tertiary_mass, rho_cor,rbind(Pt11,Pt2,edge_tert)) # --- All Feathers --- prop_feathers = list() I_feathers_pri = rbind(rowSums(res_pri$I[,1,]), rowSums(res_pri$I[,2,]), rowSums(res_pri$I[,3,])) I_feathers_sec = rbind(rowSums(res_sec$I[,1,]), rowSums(res_sec$I[,2,]), rowSums(res_sec$I[,3,])) prop_feathers$I = I_feathers_pri + I_feathers_sec + alula$I + prop_tertiary1$I + prop_tertiary2$I prop_feathers$m = sum(dat_feat_curr$m_f) + dat_bird_curr$tertiary_mass prop_feathers$CG = ( colSums(res_pri$CGm) + colSums(res_sec$CGm) + alula$CG * m_alula + prop_tertiary1$CG * 0.5 * dat_bird_curr$tertiary_mass + prop_tertiary2$CG * 0.5 * dat_bird_curr$tertiary_mass ) / prop_feathers$m # --------------------------------------------------------- # --------------- Skin/Covert Data ------------------------ # --------------------------------------------------------- rho_skin = dat_mat_curr$density[which(dat_mat_curr$material == "Skin")] mass_skin = dat_bird_curr$wing_mass - prop_feathers$m - prop_bone$m - prop_muscles$m prop_skin = massprop_skin(mass_skin,rho_skin,rbind(Pt12,Pt6,Pt2)) # ---------------------------------------------------- # ----------------- Save Data ------------------------ # ---------------------------------------------------- # add data to bone specific data frame mass_properties_bone = store_data(dat_wingID_curr,hum, mass_properties_bone,"humerus") mass_properties_bone = store_data(dat_wingID_curr,ulna, mass_properties_bone,"ulna") mass_properties_bone = store_data(dat_wingID_curr,radius, mass_properties_bone,"radius") mass_properties_bone = store_data(dat_wingID_curr,car, mass_properties_bone,"carpo") mass_properties_bone = store_data(dat_wingID_curr,wristbone, mass_properties_bone,"wristbones") # add data to muscle specific data frame mass_properties_muscle = store_data(dat_wingID_curr,brach, mass_properties_muscle,"brach") mass_properties_muscle = store_data(dat_wingID_curr,abrach, mass_properties_muscle,"abrach") mass_properties_muscle = store_data(dat_wingID_curr,manus, mass_properties_muscle,"manus") # add data to skin specific data frame mass_properties_skin = store_data(dat_wingID_curr,prop_skin, mass_properties_skin,"skin_prop") # add data to feather specific data frame # --- Primaries --- for (i in 1:no_pri){ feather_name = paste("P",i,sep = "") curr_res_pri = list() curr_res_pri$I = res_pri$I[,,i] curr_res_pri$CG = res_pri$CG[i,] curr_res_pri$m = res_pri$m[i] mass_properties_feathers = store_data(dat_wingID_curr,curr_res_pri, mass_properties_feathers,feather_name) } # --- Secondaries --- for (i in 1:no_sec){ feather_name = paste("S",i,sep = "") curr_res_sec = list() curr_res_sec$I = res_sec$I[,,i] curr_res_sec$CG = res_sec$CG[i,] curr_res_sec$m = res_sec$m[i] mass_properties_feathers = store_data(dat_wingID_curr,curr_res_sec, mass_properties_feathers,feather_name) } # save all combined data groups to the master list mass_properties = store_data(dat_wingID_curr,prop_bone, mass_properties,"bones") mass_properties = store_data(dat_wingID_curr,prop_muscles, mass_properties,"muscles") mass_properties = store_data(dat_wingID_curr,prop_skin, mass_properties,"skin") mass_properties = store_data(dat_wingID_curr,prop_feathers, mass_properties,"feathers") # save all wing data prop_wing = list() prop_wing$I = prop_bone$I + prop_muscles$I + prop_skin$I + prop_feathers$I prop_wing$m = prop_bone$m + prop_muscles$m + prop_skin$m + prop_feathers$m prop_wing$CG = (prop_bone$CG*prop_bone$m + prop_muscles$CG*prop_muscles$m + prop_skin$CG*prop_skin$m + prop_feathers$CG*prop_feathers$m)/prop_wing$m mass_properties = store_data(dat_wingID_curr,prop_wing,mass_properties,"wing") # Plot to verify correct outputs if (plot_var != 0){ CGplot = plot_CGloc(clean_pts,mass_properties,mass_properties_skin, mass_properties_bone,mass_properties_feathers, mass_properties_muscle, prop_tertiary1, prop_tertiary2, plot_var) } return(mass_properties) } # -------------------- Store Data ------------------------------- #' Store data from the inertia calculations in long format #' #' Function to store moment of inertia tensor and center of gravity vector #' components in long format #' #' @param dat_wingID_curr Dataframe related to the current bird wing ID #' info that must include the following columns: #' \itemize{ #' \item{species}{Species ID code as a string} #' \item{BirdID}{Bird ID code as a string} #' \item{TestID}{Test ID code as a string} #' \item{frameID}{Video frame ID code as a string} #' } #' #' @param dat_mass Dataframe containing the new MOI and CG data to add #' to mass_properties as new rows. Must include: #' \itemize{ #' \item{I}{Moment of inertia tensor (kg-m^2)} #' \item{CG}{Center of gravity with three location components (m)} #' } #' #' @param mass_properties Dataframe containing any previously saved data. #' Must have the following columns: "species","BirdID","TestID","FrameID", #' "prop_type","component","value". #' #' @param name Name of the component for which the moment of inertia and #' center of gravity were computed. #' #' @return This function returns mass_properties as an updated dataframe #' with a new row corresponding to the dat_mass information #' #' @inherit combine_inertialprop examples #' #' @export store_data <- function(dat_wingID_curr,dat_mass,mass_properties,name){ prop_type_list = c("Ixx","Iyy","Izz","Ixy","Iyz","Ixz","CGx","CGy","CGz") prop_type_ind = cbind(c(1,2,3,1,2,1),c(1,2,3,2,3,3)) species = dat_wingID_curr$species BirdID = dat_wingID_curr$BirdID testID = dat_wingID_curr$TestID frameID = dat_wingID_curr$FrameID # Moment of inertia tensor for (i in 1:6){ # saves the name and value of the tensor component new_row = data.frame(species = species, BirdID = BirdID, TestID = testID, FrameID = frameID, component = name, object = prop_type_list[i], value = dat_mass$I[prop_type_ind[i,1], prop_type_ind[i,2]]) mass_properties = rbind(mass_properties,new_row) } # Center of gravity for (i in 1:3){ # saves the name and value of the CG component new_row = data.frame(species = species,BirdID = BirdID, TestID = testID, FrameID = frameID, component = name, object = prop_type_list[6+i], value = dat_mass$CG[i]) mass_properties = rbind(mass_properties,new_row) } # Mass # saves the name and value of the mass new_row = data.frame(species = species, BirdID = BirdID, TestID = testID, FrameID = frameID, component = name, object = "m", value = dat_mass$m) mass_properties = rbind(mass_properties,new_row) return(mass_properties) }
/scratch/gouwar.j/cran-all/cranData/AvInertia/R/mainrunfunctions.R
# Script containing all basic mathematical functions # ------------------------------------------------------------------------------ # ---------------------- Kronecker-delta function ------------------------------ # ------------------------------------------------------------------------------ #' Kroneckerdelta function #' #' @param i a scalar index (usually row of a matrix) #' @param j a scalar index (usually column of a matrix) #' #' @author Christina Harvey #' #' @return a scalar value. Returns 1 if i and j are equal otherwise returns 0 #' #' @examples #' #' library(AvInertia) #' #' # should return 1 #' kronecker_delta(1,1) #' #' # should return 0 #' kronecker_delta(0,1) #' #' @export #' kronecker_delta <- function(i,j){ if (i == j) { return(1) } else { return(0) } } # ------------------------------------------------------------------------------ # ---------------------- Rotation about the x axis ----------------------------- # ------------------------------------------------------------------------------ #' A 3x3 rotation matrix allowing rotation about the x-axis. #' Constructed using a cosine rotation matrix where the rotation angle in #' degrees is measured counterclockwise allowing positive rotation under #' the right hand rule. #' #' @param angle a scalar representing the angle to rotate (degrees) #' #' @author Christina Harvey #' #' @return a 3x3 matrix representing the rotation about the x-axis by the #' given angle #' #' @examples #' #' library(AvInertia) #' angle = 90 #' # should return matrix [[1,0,0];[0,0,1];[0,1,0]] #' rotx(angle) #' #' @export #' rotx <- function(angle){ R = matrix(0, nrow = 3, ncol = 3) R[1,1] = 1 R[2,2] = pracma::cosd(angle) R[3,3] = pracma::cosd(angle) R[3,2] = pracma::sind(angle) R[2,3] = -pracma::sind(angle) return(R) } # ------------------------------------------------------------------------------ # ------------------------ Calculate a unit vector ----------------------------- # ------------------------------------------------------------------------------ #' Determine the unit vector of any input vector #' #' @param vector any vector or array with only one dimension #' #' @author Christina Harvey #' #' @return the unit vector in the size of the input vector #' #' @examples #' #' library(AvInertia) #' #' #any random input vector #' vector = c(1,2,3) #' output_vec = calc_univec(vector) #' #' # if unit vector the magnitude should = 1 #' pracma::Norm(output_vec) #' #' @export calc_univec <- function(vector){ unit_vector = vector/pracma::Norm(vector) return(unit_vector) } # ------------------------------------------------------------------------------ # ---------------------- Calculate a rotation matrices ------------------------- # ------------------------------------------------------------------------------ #' A 3x3 rotation matrix constructed by projecting the new axes onto the #' original system. Likely results in rotation about all axes. #' #' @param z_vector a 1x3 vector representing the direction for the desired z #' axis of the new frame of reference. Frame of reference: VRP #' @param x_vector a 1x3 vector representing the direction for the desired x #' axis of the new frame of reference. Frame of reference: VRP #' #' @author Christina Harvey #' #' @return a 3x3 matrix representing the rotation matrix that transforms between #' VRP frame and object frame #' #' @examples #' library(AvInertia) #' z_vector = c(0,0,1) #' x_vector = c(-1,0,0) #' #' # should return matrix [[-1,0,0];[0,-1,0];[0,0,1]] #' calc_rot(z_vector, x_vector) #' #' @export #' calc_rot <- function(z_vector, x_vector){ #CAUTION: incoming vectors must be in the structural frame at the VRP # x and z vectors must already be orthogonal axes # ensure vectors are in unit form unit_z_vector = calc_univec(z_vector) unit_x_vector = calc_univec(x_vector) # cross z with x to get the right-handed axis - verified y_vector = pracma::cross(unit_z_vector,unit_x_vector) # ensure vectors are in unit form unit_y_vector = calc_univec(y_vector) # rotation matrix representing the rotated basis VRP2object = rbind(unit_x_vector,unit_y_vector,unit_z_vector) # strip row names rownames(VRP2object)<-NULL return(VRP2object) } # ------------------------------------------------------------------------------ # ------------------------- Parallel axis theorem ----------------------------- # ------------------------------------------------------------------------------ #' Parallel axis theory #' #' Reads in an initial tensor and an offset to compute the transformed tensor. #' Will be in the same frame of reference as the input tensor. #' #' @param I a 3x3 matrix representing the moment of inertia tensor about the #' center of gravity of the object (kg-m^2). #' @param offset_vec a 1x3 vector representing the distance (x,y,z) between #' the objects CG and the arbitrary pt A (m). #' Vector should always point from the CG to the arbitrary point A. #' @param m Mass of the object (kg). #' @param cg_a If input I is about the CG enter "CG" or if I is about an #' arbitrary axis enter "A". #' #' @author Christina Harvey #' #' @return a 3x3 matrix representing the transformed moment of inertia tensor #' after a solid body translation defined by the offset vector. #' #' @inherit combine_inertialprop examples #' @export #' parallelaxis <- function(I, offset_vec, m, cg_a){ # CAUTION: the parallel axis theorem only works if the I_CG is given about # the object's centroidal axis I_new = matrix(0, nrow = 3, ncol = 3) # predefine matrix if(cg_a == "CG"){ sign = 1 } if(cg_a == "A"){ sign = -1 } for (i in 1:3){ for (j in 1:3){ I_new[i,j] = I[i,j] + sign*m*((kronecker_delta(i,j)*pracma::dot(offset_vec,offset_vec)) - (offset_vec[i]*offset_vec[j])) } } return(I_new) }
/scratch/gouwar.j/cran-all/cranData/AvInertia/R/mathematicalfunctions.R
# This script contains all applicable plotting functions #' Plot the center of gravity of each component #' #' @param clean_pts Dataframe of the key positions of the bird as follows: #' \itemize{ #' \item{pt1x, pt1y, pt1z}{Point on the shoulder joint} #' \item{pt2x, pt1y, pt2z}{Point on the elbow joint} #' \item{pt3x, pt3y, pt3z}{Point on the wrist joint} #' \item{pt4x, pt4y, pt4z}{Point on the end of carpometacarpus} #' \item{pt6x, pt6y, pt6z}{Point on the leading edge of the wing in front of the #' wrist joint} #' \item{pt8x, pt8y, pt8z}{Point on tip of most distal primary} #' \item{pt9x, pt9y, pt9z}{Point that defines the end of carpometacarpus} #' \item{pt10x, pt10y, pt10z}{Point on tip of last primary to model as if on the #' end of the carpometacarpus} #' \item{pt11x, pt11y, pt11z}{Point on tip of most proximal feather #' (wing root trailing edge)} #' \item{pt12x, pt12y, pt12z}{Point on exterior shoulder position #' (wing root leading edge)} #' } #' @param mass_properties Dataframe containing the center of gravity and #' moment of inertia components of the full wing. #' @param mass_properties_skin Dataframe containing the center of gravity and #' moment of inertia components of the skin. #' Formatted with the following columns: "species","BirdID","TestID","FrameID", #' "prop_type","component","value". #' @param mass_properties_bone Dataframe containing the center of gravity and #' moment of inertia components of the wing bones. #' Formatted with the following columns: "species","BirdID","TestID","FrameID", #' "prop_type","component","value". #' @param mass_properties_feathers Dataframe containing the center of gravity and #' moment of inertia components of the feathers. #' Formatted with the following columns: "species","BirdID","TestID","FrameID", #' "prop_type","component","value". #' @param mass_properties_muscle Dataframe containing the center of gravity and #' moment of inertia components of the muscles #' Formatted with the following columns: "species","BirdID","TestID","FrameID", #' "prop_type","component","value". #' @param prop_tertiary1 Dataframe containing the center of gravity and #' moment of inertia components of the first tertiary group. #' Formatted with the following columns: "species","BirdID","TestID","FrameID", #' "prop_type","component","value". #' @param prop_tertiary2 Dataframe containing the center of gravity and #' moment of inertia components of the second tertiary group. #' Formatted with the following columns: "species","BirdID","TestID","FrameID", #' "prop_type","component","value". #' @param plot_var Character of either "yx" or "yz". #' Defines the output axes of the plot. #' #' @return A plot of the request axes #' #' @inherit combine_inertialprop examples #' #' @export #' plot_CGloc <- function(clean_pts, mass_properties, mass_properties_skin, mass_properties_bone, mass_properties_feathers, mass_properties_muscle, prop_tertiary1, prop_tertiary2, plot_var) { # Set variables to NULL to avoid having to define as a global variable as # CRAN can't see a binding for feather within the dataframe dat_feat_curr component=NULL object=NULL primaries = mass_properties_feathers[grep("P", mass_properties_feathers$component), ] secondaries = mass_properties_feathers[grep("S", mass_properties_feathers$component), ] #--- Predefine the main theme ---- th <- ggplot2::theme_classic() + ggplot2::theme( # Text axis.title = ggplot2::element_text(size = 10), axis.text = ggplot2::element_text(size = 10, colour = "black"), axis.text.x.top = ggplot2::element_text(margin = ggplot2::margin(t = 0, r = 0, b = 0, l = 0), vjust = 3.5), axis.text.y = ggplot2::element_text(margin = ggplot2::margin(r = 10)), # Axis line axis.line = ggplot2::element_blank(), axis.ticks.length = ggplot2::unit(-5, "pt"), # Legend legend.position = 'none', # Background transparency # Background of panel panel.background = ggplot2::element_rect(fill = "transparent"), # Background behind actual data points plot.background = ggplot2::element_rect(fill = "transparent", color = NA) ) CGplot_x <- ggplot2::ggplot() + # Add in data ggplot2::geom_point( ggplot2::aes(x = prop_tertiary1$CG[2], y = prop_tertiary1$CG[1]), col = "black", fill = "#BEA4BD", pch = 21 ) + ggplot2::geom_point( ggplot2::aes(x = prop_tertiary2$CG[2], y = prop_tertiary2$CG[1]), col = "black", fill = "#BEA4BD", pch = 21 ) + ggplot2::geom_point( ggplot2::aes( x = subset(mass_properties_skin, object == "CGy")$value, y = subset(mass_properties_skin, object == "CGx")$value ), col = "black", fill = "#BEA4BD", pch = 21 ) + ggplot2::geom_point( ggplot2::aes( x = subset(mass_properties_bone, object == "CGy")$value, y = subset(mass_properties_bone, object == "CGx")$value ), col = "black", fill = "#FAC5C6", pch = 21 ) + ggplot2::geom_point( ggplot2::aes( x = subset(primaries, object == "CGy")$value, y = subset(primaries, object == "CGx")$value ), col = "black", fill = "#A0B3DC", pch = 21 ) + ggplot2::geom_point( ggplot2::aes( x = subset(secondaries, object == "CGy")$value, y = subset(secondaries, object == "CGx")$value ), col = "black", fill = "#9AD09B", pch = 21 ) + ggplot2::geom_point( ggplot2::aes( x = subset(mass_properties_muscle, object == "CGy")$value, y = subset(mass_properties_muscle, object == "CGx")$value ), col = "black", fill = "#FAC5C6", pch = 21 ) + ggplot2::geom_point(ggplot2::aes( x = subset(mass_properties, component == "wing" & object == "CGy")$value, y = subset(mass_properties, component == "wing" & object == "CGx")$value ), col = "black", size = 3) + ggplot2::geom_point( ggplot2::aes(x = clean_pts[1:4, 2], y = clean_pts[1:4, 1]), col = "black", fill = "white", pch = 22 ) + ggplot2::geom_point(ggplot2::aes(x = clean_pts[5:10, 2], y = clean_pts[5:10, 1]), col = "gray50", pch = 15) + ggplot2::geom_point(ggplot2::aes(x = clean_pts[5:10, 2], y = clean_pts[5:10, 1]), col = "black", pch = 0) + # Theme th + # Axis control ggplot2::scale_y_continuous(name = "x (m)", limits = c(-0.4, 0.01)) + ggplot2::scale_x_continuous(name = "y (m)", limits = c(0, 0.6), position = "top") + ggthemes::geom_rangeframe() + ggplot2::coord_fixed() + ggplot2::annotate( geom = "segment", x = log(0), xend = log(0), y = -0.4, yend = 0 ) + ggplot2::annotate( geom = "segment", x = 0, xend = 0.6, y = -log(0), yend = -log(0) ) if (plot_var == "yx") { plot(CGplot_x) } CGplot_z <- ggplot2::ggplot() + # Add in data ggplot2::geom_point( ggplot2::aes(x = prop_tertiary1$CG[2], y = -prop_tertiary1$CG[3]), col = "black", fill = "#BEA4BD", pch = 21 ) + ggplot2::geom_point( ggplot2::aes(x = prop_tertiary2$CG[2], y = -prop_tertiary2$CG[3]), col = "black", fill = "#BEA4BD", pch = 21 ) + ggplot2::geom_point( ggplot2::aes( x = subset(mass_properties_skin, object == "CGy")$value, y = -subset(mass_properties_skin, object == "CGz")$value ), col = "black", fill = "#BEA4BD", pch = 21 ) + ggplot2::geom_point( ggplot2::aes( x = subset(mass_properties_bone, object == "CGy")$value, y = -subset(mass_properties_bone, object == "CGz")$value ), col = "black", fill = "#FAC5C6", pch = 21 ) + ggplot2::geom_point( ggplot2::aes( x = subset(primaries, object == "CGy")$value, y = -subset(primaries, object == "CGz")$value ), col = "black", fill = "#A0B3DC", pch = 21 ) + ggplot2::geom_point( ggplot2::aes( x = subset(secondaries, object == "CGy")$value, y = -subset(secondaries, object == "CGz")$value ), col = "black", fill = "#9AD09B", pch = 21 ) + ggplot2::geom_point( ggplot2::aes( x = subset(mass_properties_muscle, object == "CGy")$value, y = -subset(mass_properties_muscle, object == "CGz")$value ), col = "black", fill = "#FAC5C6", pch = 21 ) + ggplot2::geom_point( ggplot2::aes( x = subset(mass_properties, component == "wing" & object == "CGy")$value, y = -subset(mass_properties, component == "wing" & object == "CGz")$value ), col = "black", size = 3 ) + ggplot2::geom_point( ggplot2::aes(x = clean_pts[1:4, 2], y = -clean_pts[1:4, 3]), col = "black", fill = "white", pch = 22 ) + ggplot2::geom_point(ggplot2::aes(x = clean_pts[5:10, 2], y = -clean_pts[5:10, 3]), col = "gray50", pch = 15) + ggplot2::geom_point(ggplot2::aes(x = clean_pts[5:10, 2], y = -clean_pts[5:10, 3]), col = "black", pch = 0) + # Theme th + # Axis control ggplot2::scale_y_continuous(name = "z (m)", limits = c(-0.2, 0.2)) + ggplot2::scale_x_continuous( name = "y (m)", limits = c(0, 0.6), position = "top" ) + ggthemes::geom_rangeframe() + ggplot2::coord_fixed() + ggplot2::annotate( geom = "segment", x = log(0), xend = log(0), y = -0.2, yend = 0.2 ) + ggplot2::annotate( geom = "segment", x = 0, xend = 0.6, y = -log(0), yend = -log(0) ) if (plot_var == "yz") { plot(CGplot_z) } return(CGplot_x) }
/scratch/gouwar.j/cran-all/cranData/AvInertia/R/plottingfunctions.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- library(AvInertia) ## ----load_data---------------------------------------------------------------- data(dat_id_curr, package = "AvInertia") data(dat_bird_curr, package = "AvInertia") data(dat_feat_curr, package = "AvInertia") data(dat_bone_curr, package = "AvInertia") data(dat_mat, package = "AvInertia") data(clean_pts, package = "AvInertia") ## ----calc_torso--------------------------------------------------------------- dat_torsotail_out = massprop_restbody(dat_id_curr, dat_bird_curr) ## ----calc_feat---------------------------------------------------------------- feather_inertia <- compute_feat_inertia(dat_mat, dat_feat_curr, dat_bird_curr) ## ----calc_wing_noplot--------------------------------------------------------- dat_wing_out = massprop_birdwing(dat_id_curr, dat_bird_curr, dat_bone_curr, dat_feat_curr, dat_mat, clean_pts, feather_inertia, plot_var = 0) ## ----calc_wing_plotxy, fig.width = 4------------------------------------------ dat_wing_out = massprop_birdwing(dat_id_curr, dat_bird_curr, dat_bone_curr, dat_feat_curr, dat_mat, clean_pts, feather_inertia, plot_var = "yx") ## ----calc_wing_plotyz, fig.width = 4------------------------------------------ dat_wing_out = massprop_birdwing(dat_id_curr, dat_bird_curr, dat_bone_curr, dat_feat_curr, dat_mat, clean_pts, feather_inertia, plot_var = "yz") ## ----combine_prop------------------------------------------------------------- curr_full_bird = combine_inertialprop(dat_torsotail_out,dat_wing_out,dat_wing_out, dat_id_curr, dat_bird_curr, symmetric=TRUE)
/scratch/gouwar.j/cran-all/cranData/AvInertia/inst/doc/how-to-analyze-data.R
--- title: "How to analyze data in AvInertia" author: "Christina Harvey" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{How to analyze data in AvInertia} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` # Determine the inertial characteristics of a flying bird. This package was developed to determine the center of gravity and moment of inertia for a bird in a general flight configuration. This code assumes that birds are a composite structure of simple geometric shapes. For details on the specific assumptions please refer to: ```{r setup} library(AvInertia) ``` Generally, you should already have all of the necessary measurements loaded into R in the form of a database. We have included the data set from our paper. The bird properties are reported in the metric system and all measurements have been taken with the origin placed at the bird (vehicle) reference point (VRP). ```{r load_data} data(dat_id_curr, package = "AvInertia") data(dat_bird_curr, package = "AvInertia") data(dat_feat_curr, package = "AvInertia") data(dat_bone_curr, package = "AvInertia") data(dat_mat, package = "AvInertia") data(clean_pts, package = "AvInertia") ``` ## 1. Determine the center of gravity of the bird's torso (including the legs) ```{r calc_torso} dat_torsotail_out = massprop_restbody(dat_id_curr, dat_bird_curr) ``` ## 2. Calculate the inertia of the flight feathers about the tip of the calamus ```{r calc_feat} feather_inertia <- compute_feat_inertia(dat_mat, dat_feat_curr, dat_bird_curr) ``` ## 3. Determine the center of gravity of one of the bird's wings ```{r calc_wing_noplot} dat_wing_out = massprop_birdwing(dat_id_curr, dat_bird_curr, dat_bone_curr, dat_feat_curr, dat_mat, clean_pts, feather_inertia, plot_var = 0) ``` Visualize the center of gravity of each wing component in the x and y axis ```{r calc_wing_plotxy, fig.width = 4} dat_wing_out = massprop_birdwing(dat_id_curr, dat_bird_curr, dat_bone_curr, dat_feat_curr, dat_mat, clean_pts, feather_inertia, plot_var = "yx") ``` or the y and z axis ```{r calc_wing_plotyz, fig.width = 4} dat_wing_out = massprop_birdwing(dat_id_curr, dat_bird_curr, dat_bone_curr, dat_feat_curr, dat_mat, clean_pts, feather_inertia, plot_var = "yz") ``` ## 4. If computing for asymmetric case, input a different set of clean points (clean_pts) Note: that in this case the wing should still be input as it it is on the right-hand side of the bird. The following code will adjust. ## 5. Combine all data and obtain the center of gravity, moment of inertia and principal axes of the bird ```{r combine_prop} curr_full_bird = combine_inertialprop(dat_torsotail_out,dat_wing_out,dat_wing_out, dat_id_curr, dat_bird_curr, symmetric=TRUE) ``` This will return a long format data frame with all the individual components I about the VRP and both the full bird I about the VRP and about the full center of gravity.
/scratch/gouwar.j/cran-all/cranData/AvInertia/inst/doc/how-to-analyze-data.Rmd
--- title: "How to analyze data in AvInertia" author: "Christina Harvey" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{How to analyze data in AvInertia} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` # Determine the inertial characteristics of a flying bird. This package was developed to determine the center of gravity and moment of inertia for a bird in a general flight configuration. This code assumes that birds are a composite structure of simple geometric shapes. For details on the specific assumptions please refer to: ```{r setup} library(AvInertia) ``` Generally, you should already have all of the necessary measurements loaded into R in the form of a database. We have included the data set from our paper. The bird properties are reported in the metric system and all measurements have been taken with the origin placed at the bird (vehicle) reference point (VRP). ```{r load_data} data(dat_id_curr, package = "AvInertia") data(dat_bird_curr, package = "AvInertia") data(dat_feat_curr, package = "AvInertia") data(dat_bone_curr, package = "AvInertia") data(dat_mat, package = "AvInertia") data(clean_pts, package = "AvInertia") ``` ## 1. Determine the center of gravity of the bird's torso (including the legs) ```{r calc_torso} dat_torsotail_out = massprop_restbody(dat_id_curr, dat_bird_curr) ``` ## 2. Calculate the inertia of the flight feathers about the tip of the calamus ```{r calc_feat} feather_inertia <- compute_feat_inertia(dat_mat, dat_feat_curr, dat_bird_curr) ``` ## 3. Determine the center of gravity of one of the bird's wings ```{r calc_wing_noplot} dat_wing_out = massprop_birdwing(dat_id_curr, dat_bird_curr, dat_bone_curr, dat_feat_curr, dat_mat, clean_pts, feather_inertia, plot_var = 0) ``` Visualize the center of gravity of each wing component in the x and y axis ```{r calc_wing_plotxy, fig.width = 4} dat_wing_out = massprop_birdwing(dat_id_curr, dat_bird_curr, dat_bone_curr, dat_feat_curr, dat_mat, clean_pts, feather_inertia, plot_var = "yx") ``` or the y and z axis ```{r calc_wing_plotyz, fig.width = 4} dat_wing_out = massprop_birdwing(dat_id_curr, dat_bird_curr, dat_bone_curr, dat_feat_curr, dat_mat, clean_pts, feather_inertia, plot_var = "yz") ``` ## 4. If computing for asymmetric case, input a different set of clean points (clean_pts) Note: that in this case the wing should still be input as it it is on the right-hand side of the bird. The following code will adjust. ## 5. Combine all data and obtain the center of gravity, moment of inertia and principal axes of the bird ```{r combine_prop} curr_full_bird = combine_inertialprop(dat_torsotail_out,dat_wing_out,dat_wing_out, dat_id_curr, dat_bird_curr, symmetric=TRUE) ``` This will return a long format data frame with all the individual components I about the VRP and both the full bird I about the VRP and about the full center of gravity.
/scratch/gouwar.j/cran-all/cranData/AvInertia/vignettes/how-to-analyze-data.Rmd
#' Check if string matches pattern for an instrumentation key. #' @param x A string containing nothing else but an instrumentation key. #' @return Logical value. #' @export is_instrumentation_key <- function(x) { grepl('[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{8}', x) }
/scratch/gouwar.j/cran-all/cranData/AzureAppInsights/R/0aux.R
#' Azure Application Insights for web pages #' #' Add Azure Application Insights tracking to a Shiny App. #' \emph{Requires an active Azure subscription and Application Insights instrumentation key!} #' Based on \url{https://docs.microsoft.com/en-us/azure/azure-monitor/app/javascript} / #' \url{https://github.com/microsoft/ApplicationInsights-JS}. #' #' Documentation in this page will be limited, as most is explained on the main page. #' #' Supports so far only #' \code{pageViews} (automatically sent), #' \code{autoTrackPageVisitTime} (when configured with \code{\link{config}}), #' \code{customEvents} (see \code{\link{trackEvent}}). #' #' #' #' @author Stefan McKinnon Edwards <smhe@@kamstrup.dk> #' "_PACKAGE"
/scratch/gouwar.j/cran-all/cranData/AzureAppInsights/R/AzureAppInsights-package.R
#' Configure Azure Application Insights #' #' Ensures an instrumentationKey/connectionString and appId is provided. #' #' See https://docs.microsoft.com/en-us/azure/azure-monitor/app/javascript#configuration #' for explanation of options. #' #' If jsonlite is playing tricks on the arguments given, wrap the value with \code{I}. #' E.g. if you want to force an atomic vector of length 1 to be parsed as an array, use #' \code{I(3.14)}. #' #' @param instrumentationKey,connectionString Credentials for sending to Application Insights. #' \code{connectionString} is preferred for newer accounts and must contain both \code{InstrumentationKey} and \code{IngestionEndpoint}. #' @param appId String for identifying your app, if you use same Application Insights for multiple apps. #' @param autoTrackPageVisitTime Submits how long time a user spent on the *previous* page (see website for more information). #' @param ... Additional options, as given in \url{https://docs.microsoft.com/en-us/azure/azure-monitor/app/javascript#configuration}. #' No checks performed here. #' @return List. #' @export config <- function(appId, instrumentationKey, connectionString, autoTrackPageVisitTime=TRUE, ...) { if (!rlang::is_missing(instrumentationKey)) { assertthat::assert_that(assertthat::is.string(instrumentationKey), is_instrumentation_key(instrumentationKey)) cfg <- list(instrumentationKey = instrumentationKey, ...) } else if (!rlang::is_missing(connectionString)) { assertthat::assert_that( grepl('InstrumentationKey=', connectionString, ignore.case=TRUE), grepl('IngestionEndpoint=', connectionString, ignore.case=TRUE) ) cfg <- list(connectionString=connectionString, ...) } else { stop("An instrumentation key or connection string must be provided!") } assertthat::assert_that(rlang::is_string(appId)) cfg$appId = appId assertthat::assert_that(rlang::is_logical(autoTrackPageVisitTime, n=1)) cfg$autoTrackPageVisitTime <- autoTrackPageVisitTime cfg }
/scratch/gouwar.j/cran-all/cranData/AzureAppInsights/R/cfg.R
#' Demonstration of Application Insights #' #' Launches a simple demonstration of using Application Insights for Shiny apps. #' Requires that you have a Microsoft Azure Application Insights resource to #' send to; demonstration will still work -- your metrics will just be sent to oblivion. #' #' It may take some minutes before the values sent to Application Insights are #' visible in the logs on portal.azure.com. #' #' If neither \code{connectionString} nor \code{instrumentationKey} is provided, #' a connection string is found in the environment variable \code{AAI_CONNSTR}. #' #' @param connectionString,instrumentationKey Credentials for sending to Application Insights. #' See arguments for \code{\link{config}}. #' @param debug Logical, see \code{\link{startAzureAppInsights}}. #' @param appId A id for this particular application. #' @param launch.browser Logical, see \code{\link[shiny]{runApp}}. #' #' @examples #' connstr <- paste0( #' 'InstrumentationKey=00000000-0000-0000-0000-000000000000;', #' 'IngestionEndpoint=https://northeurope-0.in.applicationinsights.azure.com/;', #' 'LiveEndpoint=https://northeurope.livediagnostics.monitor.azure.com/') #' \dontrun{ #' demo(connstr) #' } #' @export demo <- function(connectionString, debug = TRUE, appId = "Test AzureAppInsights", launch.browser=FALSE, instrumentationKey) { if (rlang::is_missing(connectionString) && rlang::is_missing(instrumentationKey)) { connectionString <- Sys.getenv('AAI_CONNSTR') } cfg <- config(appId = appId, connectionString = rlang::maybe_missing(connectionString), instrumentationKey = rlang::maybe_missing(instrumentationKey), autoTrackPageVisitTime = TRUE) ui <- fluidPage( includeAzureAppInsights(), tags$button("Click me!", onClick=HTML("appInsights.trackEvent( {name: 'garble', properties: {moobs: 15, bacon: true}});" ) ), actionButton("button","Click me too!"), actionButton("metric", "Track metrics! (Check R console for values)") ) server <- function(input, output, session) { startAzureAppInsights(session, cfg, extras=list(started=lubridate::now()), cookie.user = TRUE, include.ip = TRUE ) observe({ trackEvent(session, "click", list("clicks"=input$button)) }) observeEvent(input$metric, { metrics <- stats::runif(5) print('metric summaries:') res <- trackMetric(session, 'metric', metrics) print(res) }) } shiny::runApp(list(ui=ui, server=server), launch.browser = launch.browser) }
/scratch/gouwar.j/cran-all/cranData/AzureAppInsights/R/demo.R
#' Include and run Azure Application Insights for web pages #' #' Include the JS snippet in your \code{ui}-function with \code{includeAzureAppInsights} #' and start the tracking with \code{startAzureAppInsights} in your \code{server}-function. #' #' @references #' https://docs.microsoft.com/en-us/azure/azure-monitor/app/javascript #' and #' https://github.com/microsoft/ApplicationInsights-JS #' and #' https://learn.microsoft.com/en-us/azure/azure-monitor/app/ip-collection?tabs=net #' #' @section Tracking users' ip-address: #' Generally, Azure's Application Insight does not collect the users' ip-address, #' due to it being somewhat sensitive data (\href{https://learn.microsoft.com/en-us/azure/azure-monitor/app/ip-collection?tabs=net}{link}). #' #' \code{\link{startAzureAppInsights}} however has the argument `include.ip` which, #' when set to \code{TRUE}, will add the entry \code{ip} to all trackings. #' The tracked ip-address is taken from \code{session$request$REMOTE_ADDR}, #' which is an un-documented feature and may or may not be the users ip-address. #' #' #' @rdname azureinsights #' @param session The \code{session} object passed to function given to \code{shinyServer}. #' @param cfg List-object from \code{\link{config}}. #' @param instance.name Global JavaScript Instance name defaults to "appInsights" when not supplied. \emph{NOT} the app's name. Used for accessing the instance from other JavaScript routines. #' @param ld Defines the load delay (in ms) before attempting to load the sdk. -1 = block page load and add to head. (default) = 0ms load after timeout, #' @param useXhr Logical, use XHR instead of fetch to report failures (if available). #' @param crossOrigin When supplied this will add the provided value as the cross origin attribute on the script tag. #' @param onInit Once the application insights instance has loaded and initialized this callback function will be called with 1 argument -- the sdk instance #' @param heartbeat Integer, how often should the heartbeat beat -- or set to \code{FALSE} to disable. #' @param extras (Named) list of values to add to any tracking. #' @param include.ip Logical, adds \code{ip} to all tracking's \code{customDimension}. See note. #' @param cookie.user Logical, when \code{TRUE} sets a cookie with a random string and submits this #' along with any tracking with the key \code{userid}. #' @param debug Logical, JS loader uses \code{console.log}. #' @return Methods sends data to client's browser; returns the sent list, invisibly. #' @include 0aux.R #' @include cfg.R #' @export startAzureAppInsights <- function(session, cfg, instance.name = 'appInsights', ld = 0, useXhr = TRUE, crossOrigin = "anonymous", onInit = NULL, heartbeat=300000, extras=list(), include.ip=FALSE, cookie.user=FALSE, debug = FALSE) { assertthat::assert_that(assertthat::is.string(instance.name)) assertthat::assert_that(assertthat::is.count(ld) || ld == 0 || ld == -1) assertthat::assert_that(rlang::is_logical(useXhr, 1)) assertthat::assert_that(assertthat::is.string(crossOrigin)) assertthat::assert_that(is.numeric(heartbeat) || heartbeat == FALSE, length(heartbeat) == 1) assertthat::assert_that(is.null(extras) || is.list(extras)) assertthat::assert_that(rlang::is_logical(include.ip, 1), rlang::is_logical(cookie.user, 1)) assertthat::assert_that(rlang::is_logical(debug, 1)) if (rlang::is_list(cfg)) { assertthat::assert_that(length(cfg) > 0) assertthat::assert_that(!is.null(cfg$instrumentationKey) || !is.null(cfg$connectionString), !is.null(cfg$appId)) cfg <- jsonlite::toJSON(cfg, auto_unbox = TRUE, null = 'null') } assertthat::assert_that(inherits(cfg, 'json')) if (is.null(extras)) extras <- list() ## ip: if (include.ip) { ip <- session$request$REMOTE_ADDR extras$ip <- ip } msg <- list( src = "https://js.monitor.azure.com/scripts/b/ai.2.min.js", # The SDK URL Source name = instance.name, # Global SDK Instance name defaults to "appInsights" when not supplied ld = ld, # Defines the load delay (in ms) before attempting to load the sdk. -1 = block page load and add to head. (default) = 0ms load after timeout, useXhr = useXhr, # Use XHR instead of fetch to report failures (if available), crossOrigin = crossOrigin, # When supplied this will add the provided value as the cross origin attribute on the script tag onInit = onInit, # Once the application insights instance has loaded and initialized this callback function will be called with 1 argument -- the sdk instance (DO NOT ADD anything to the sdk.queue -- As they won't get called) config = cfg, options = list( heartbeat = as.integer(heartbeat), cookie_user = cookie.user, extras = extras, debug = debug ) ) session$sendCustomMessage('azure_insights_run', msg) invisible(msg) } #' @param version Version of the Application Insights JavaScript SDK to load. #' @rdname azureinsights #' @import shiny #' @export includeAzureAppInsights <- function(version = c('2.8.14','2.7.0')) { version = match.arg(version) addResourcePath('azureinsights', system.file('www', package = 'AzureAppInsights', mustWork = TRUE)) singleton( tags$head( tags$script(src = paste0('azureinsights/ApplicationInsights-JS/ai.',version,'.min.js')), tags$script(src = 'azureinsights/azure_insights_loader_v2.js') ) ) }
/scratch/gouwar.j/cran-all/cranData/AzureAppInsights/R/include_snippet.R
#' @include include_snippet.R #' @include cfg.R NULL check_name <- function(name) { assertthat::assert_that(rlang::is_string(name)) } check_properties <- function(properties) { if (rlang::is_missing(properties) || is.null(properties)) properties <- list() assertthat::assert_that(is.list(properties)) if (length(properties) > 0) assertthat::assert_that(!is.null(names(properties)), all(names(properties) != "")) return(properties) } #' Sends an event or set of metrics to Application Insights #' #' Use \code{trackEvent} for tracking a single event together with any extra properties. #' @param session The \code{session} object passed to function given to \code{shinyServer}. #' @param name Name of the event. #' @param properties List of properties to track. \code{appId} and any extras given in #' \code{\link{startAzureAppInsights}} is automatically inserted. #' @return Method sends data to client's browser; returns the sent list, invisibly. #' #' @export #' @rdname tracking trackEvent <- function(session, name, properties) { check_name(name) properties <- check_properties(rlang::maybe_missing(properties)) msg <- jsonlite::toJSON(list(name=name, properties=properties), auto_unbox = TRUE, null='null') session$sendCustomMessage('azure_track_event', msg) invisible(msg) } #' Track Metric #' #' Use \code{trackMetric} to track a summary of some measured metrics. #' #' @section Tracking Metrics: #' Individual measured values are not sent to Application Insights. Instead, #' summaries of the values (mean, range, average, standard deviation) are sent. #' \emph{Note:} Standard deviation doesn't quite work yet. #' #' Before calculating summaries, non-finite values are removed (see \code{\link[base]{is.finite}}). #' If there are no values in \code{metrics}, nothing is sent. #' # @inheritParams trackEvent session name properties #' @param metrics Numeric vector of values to calculate summary on. Non-finite values are removed. #' #' @rdname tracking #' @export trackMetric <- function(session, name, metrics, properties) { assertthat::assert_that(rlang::is_string(name)) if (rlang::is_missing(properties) || is.null(properties)) properties <- list() assertthat::assert_that(is.list(properties)) if (length(properties) > 0) assertthat::assert_that(!is.null(names(properties)), all(names(properties) != "")) assertthat::assert_that(is.numeric(metrics)) metrics <- metrics[is.finite(metrics)] if (length(metrics) == 0) return(invisible(NULL)) m <- c( average=mean(metrics), range=range(metrics), count=length(metrics), stdDev=if (length(metrics) < 2) 0.0 else stats::sd(metrics) ) msg <- jsonlite::toJSON(list(name=name, metrics=as.list(m), properties=properties), auto_unbox = TRUE, null='null') session$sendCustomMessage('azure_track_metric', msg) invisible(msg) }
/scratch/gouwar.j/cran-all/cranData/AzureAppInsights/R/tracking.R
utils::globalVariables(c("self", "private")) .onLoad <- function(libname, pkgname) { make_AzureR_dir() options(azure_imds_version="2018-02-01") invisible(NULL) } # create a directory for saving creds -- ask first, to satisfy CRAN requirements make_AzureR_dir <- function() { AzureR_dir <- AzureR_dir() if(!dir.exists(AzureR_dir) && interactive()) { ok <- get_confirmation(paste0( "The AzureR packages can save your authentication credentials in the directory:\n\n", AzureR_dir, "\n\n", "This saves you having to re-authenticate with Azure in future sessions. Create this directory?")) if(!ok) return(invisible(NULL)) dir.create(AzureR_dir, recursive=TRUE) } } #' Data directory for AzureR packages #' #' @details #' AzureAuth can save your authentication credentials in a user-specific directory, using the rappdirs package. On recent Windows versions, this will usually be in the location `C:\\Users\\(username)\\AppData\\Local\\AzureR`. On Unix/Linux, it will be in `~/.local/share/AzureR`, and on MacOS, it will be in `~/Library/Application Support/AzureR`.Alternatively, you can specify the location of the directory in the environment variable `R_AZURE_DATA_DIR`. AzureAuth does not modify R's working directory, which significantly lessens the risk of accidentally introducing cached tokens into source control. #' #' On package startup, if this directory does not exist, AzureAuth will prompt you for permission to create it. It's recommended that you allow the directory to be created, as otherwise you will have to reauthenticate with Azure every time. Note that many cloud engineering tools, including the [Azure CLI](https://docs.microsoft.com/en-us/cli/azure/?view=azure-cli-latest), save authentication credentials in this way. The prompt only appears in an interactive session (in the sense that `interactive()` returns TRUE); if AzureAuth is loaded in a batch script, the directory is not created if it doesn't already exist. #' #' `create_AzureR_dir` is a utility function to create the caching directory manually. This can be useful not just for non-interactive sessions, but also Jupyter and R notebooks, which are not _technically_ interactive in that `interactive()` returns FALSE. #' #' The caching directory is also used by other AzureR packages, notably AzureRMR (for storing Resource Manager logins) and AzureGraph (for Microsoft Graph logins). You should not save your own files in it; instead, treat it as something internal to the AzureR packages. #' #' @return #' A string containing the data directory. #' #' @seealso #' [get_azure_token] #' #' [rappdirs::user_data_dir] #' #' @rdname AzureR_dir #' @export AzureR_dir <- function() { userdir <- Sys.getenv("R_AZURE_DATA_DIR") if(userdir != "") return(userdir) rappdirs::user_data_dir(appname="AzureR", appauthor="", roaming=FALSE) } #' @rdname AzureR_dir #' @export create_AzureR_dir <- function() { azdir <- AzureR_dir() if(!dir.exists(azdir)) dir.create(azdir, recursive=TRUE) }
/scratch/gouwar.j/cran-all/cranData/AzureAuth/R/AzureAuth.R
#' Azure OAuth authentication #' #' Azure OAuth 2.0 token classes, with an interface based on the [Token2.0 class][httr::Token2.0] in httr. Rather than calling the initialization methods directly, tokens should be created via [get_azure_token()]. #' #' @docType class #' @section Methods: #' - `refresh`: Refreshes the token. For expired tokens without an associated refresh token, refreshing really means requesting a new token. #' - `validate`: Checks if the token has not yet expired. Note that a token may be invalid for reasons other than having expired, eg if it is revoked on the server. #' - `hash`: Computes an MD5 hash on the input fields of the object. Used internally for identification purposes when caching. #' - `cache`: Stores the token on disk for use in future sessions. #' #' @seealso #' [get_azure_token], [httr::Token] #' #' @format An R6 object representing an Azure Active Directory token and its associated credentials. `AzureToken` is the base class, and the others inherit from it. #' @export AzureToken <- R6::R6Class("AzureToken", public=list( version=NULL, resource=NULL, scope=NULL, aad_host=NULL, tenant=NULL, auth_type=NULL, client=NULL, token_args=list(), authorize_args=list(), credentials=NULL, # returned token details from host initialize=function(resource, tenant, app, password=NULL, username=NULL, certificate=NULL, aad_host="https://login.microsoftonline.com/", version=1, authorize_args=list(), token_args=list(), use_cache=NULL, auth_info=NULL) { if(is.null(private$initfunc)) stop("Do not call this constructor directly; use get_azure_token() instead") self$version <- normalize_aad_version(version) if(self$version == 1) { if(length(resource) != 1) stop("Resource for Azure Active Directory v1.0 token must be a single string", call.=FALSE) self$resource <- resource } else self$scope <- sapply(resource, verify_v2_scope, USE.NAMES=FALSE) # default behaviour: disable cache if running in shiny if(is.null(use_cache)) use_cache <- !in_shiny() self$aad_host <- aad_host self$tenant <- normalize_tenant(tenant) self$token_args <- token_args private$use_cache <- use_cache # use_cache = NA means return dummy object: initialize fields, but don't contact AAD if(is.na(use_cache)) return() if(use_cache) private$load_cached_credentials() # time of initial request for token: in case we need to set expiry time manually request_time <- Sys.time() if(is.null(self$credentials)) { res <- private$initfunc(auth_info) self$credentials <- process_aad_response(res) } private$set_expiry_time(request_time) if(private$use_cache) self$cache() }, cache=function() { if(dir.exists(AzureR_dir())) { filename <- file.path(AzureR_dir(), self$hash()) saveRDS(self, filename, version=2) } invisible(NULL) }, hash=function() { token_hash_internal(self$version, self$aad_host, self$tenant, self$auth_type, self$client, self$resource, self$scope, self$authorize_args, self$token_args) }, validate=function() { if(is.null(self$credentials$expires_on) || is.na(self$credentials$expires_on)) return(TRUE) expdate <- as.POSIXct(as.numeric(self$credentials$expires_on), origin="1970-01-01") curdate <- Sys.time() curdate < expdate }, can_refresh=function() { TRUE }, refresh=function() { request_time <- Sys.time() res <- if(!is.null(self$credentials$refresh_token)) { body <- list(grant_type="refresh_token", client_id=self$client$client_id, client_secret=self$client$client_secret, resource=self$resource, scope=paste_v2_scopes(self$scope), client_assertion=self$client$client_assertion, client_assertion_type=self$client$client_assertion_type, refresh_token=self$credentials$refresh_token ) uri <- private$aad_uri("token") httr::POST(uri, body=body, encode="form") } else private$initfunc() # reauthenticate if no refresh token (cannot reuse any supplied creds) creds <- try(process_aad_response(res)) if(inherits(creds, "try-error")) { delete_azure_token(hash=self$hash(), confirm=FALSE) stop("Unable to refresh token", call.=FALSE) } self$credentials <- creds private$set_expiry_time(request_time) if(private$use_cache) self$cache() invisible(self) }, print=function() { cat(format_auth_header(self)) invisible(self) } ), private=list( use_cache=NULL, load_cached_credentials=function() { tokenfile <- file.path(AzureR_dir(), self$hash()) if(!file.exists(tokenfile)) return(NULL) message("Loading cached token") token <- readRDS(tokenfile) if(!is_azure_token(token)) { file.remove(tokenfile) stop("Invalid or corrupted cached token", call.=FALSE) } self$credentials <- token$credentials if(!self$validate()) self$refresh() }, set_expiry_time=function(request_time) { # v2.0 endpoint doesn't provide an expires_on field, set it here if(is.null(self$credentials$expires_on)) { expiry <- try(decode_jwt(self$credentials$access_token)$payload$exp, silent=TRUE) if(inherits(expiry, "try-error")) expiry <- try(decode_jwt(self$credentials$id_token)$payload$exp, silent=TRUE) if(inherits(expiry, "try-error")) expiry <- NA expires_in <- if(!is.null(self$credentials$expires_in)) as.numeric(self$credentials$expires_in) else NA request_time <- floor(as.numeric(request_time)) expires_on <- request_time + expires_in self$credentials$expires_on <- if(is.na(expiry) && is.na(expires_on)) { warning("Could not set expiry time, using default validity period of 1 hour") as.character(as.numeric(request_time + 3600)) } else as.character(as.numeric(min(expiry, expires_on, na.rm=TRUE))) } }, aad_uri=function(type, ...) { aad_uri(self$aad_host, self$tenant, self$version, type, list(...)) }, build_access_body=function(body=self$client) { stopifnot(is.list(self$token_args)) # fill in cert assertion details body$client_assertion <- build_assertion(body$client_assertion, self$tenant, body$client_id, self$aad_host, self$version) c(body, self$token_args, if(self$version == 1) list(resource=self$resource) else list(scope=paste_v2_scopes(self$scope)) ) } ))
/scratch/gouwar.j/cran-all/cranData/AzureAuth/R/AzureToken.R
#' Create a client assertion for certificate authentication #' #' @param certificate An Azure Key Vault certificate object, or the name of a PEM or PFX file containing _both_ a private key and a public certificate. #' @param duration The requested validity period of the token, in seconds. The default is 1 hour. #' @param signature_size The size of the SHA2 signature. #' @param ... Other named arguments which will be treated as custom claims. #' #' @details #' Use this function to customise a client assertion for authenticating with a certificate. #' #' @return #' An object of S3 class `cert_assertion`, which is a list representing the assertion. #' #' @seealso #' [get_azure_token] #' #' @examples #' \dontrun{ #' #' cert_assertion("mycert.pem", duration=2*3600) #' cert_assertion("mycert.pem", custom_data="some text") #' #' # using a cert stored in Azure Key Vault #' cert <- AzureKeyVault::key_vault("myvault")$certificates$get("mycert") #' cert_assertion(cert, duration=2*3600) #' #' } #' @export cert_assertion <- function(certificate, duration=3600, signature_size=256, ...) { structure(list(cert=certificate, duration=duration, size=signature_size, claims=list(...)), class="cert_assertion") } build_assertion <- function(assertion, ...) { UseMethod("build_assertion") } build_assertion.stored_cert <- function(assertion, ...) { build_assertion(cert_assertion(assertion), ...) } build_assertion.character <- function(assertion, ...) { pair <- read_cert_pair(assertion) build_assertion(cert_assertion(pair), ...) } build_assertion.cert_assertion <- function(assertion, tenant, app, aad_host, version) { url <- httr::parse_url(aad_host) if(url$path == "") { url$path <- if(version == 1) file.path(tenant, "oauth2/token") else file.path(tenant, "oauth2/v2.0/token") } claim <- jose::jwt_claim(iss=app, sub=app, aud=httr::build_url(url), exp=as.numeric(Sys.time() + assertion$duration)) if(!is_empty(assertion$claims)) claim <- utils::modifyList(claim, assertion$claims) sign_assertion(assertion$cert, claim, assertion$size) } build_assertion.default <- function(assertion, ...) { if(is.null(assertion)) assertion else stop("Invalid certificate assertion", call.=FALSE) } sign_assertion <- function(certificate, claim, size) { UseMethod("sign_assertion") } sign_assertion.stored_cert <- function(certificate, claim, size) { kty <- certificate$policy$key_props$kty # key type determines signing alg alg <- if(kty == "RSA") paste0("RS", size) else paste0("ES", size) header <- list(alg=alg, x5t=certificate$x5t, kid=certificate$x5t, typ="JWT") token_conts <- paste(token_encode(header), token_encode(claim), sep=".") paste(token_conts, certificate$sign(openssl::sha2(charToRaw(token_conts), size=size), alg), sep=".") } sign_assertion.openssl_cert_pair <- function(certificate, claim, size) { alg <- if(inherits(certificate$key, "rsa")) paste0("RS", size) else if(inherits(certificate$key, "ecdsa")) paste0("EC", size) else stop("Unsupported key type", call.=FALSE) x5t <- jose::base64url_encode(openssl::sha1(certificate$cert)) header <- list(x5t=x5t, kid=x5t) jose::jwt_encode_sig(claim, certificate$key, size=size, header=header) } sign_assertion.character <- function(certificate, claim, size) { pair <- read_cert_pair(certificate) sign_assertion(pair, claim, size) } read_cert_pair <- function(file) { ext <- tolower(tools::file_ext(file)) if(ext == "pem") { pem <- openssl::read_pem(file) obj <- list( key=openssl::read_key(pem[["PRIVATE KEY"]]), cert=openssl::read_cert(pem[["CERTIFICATE"]]) ) } else if(ext %in% c("p12", "pfx")) { pfx <- openssl::read_p12(file) obj <- list(key=pfx$key, cert=pfx$cert) } else stop("Unsupported file extension: ", ext, call.=FALSE) structure(obj, class="openssl_cert_pair") } token_encode <- function(x) { jose::base64url_encode(jsonlite::toJSON(x, auto_unbox=TRUE)) }
/scratch/gouwar.j/cran-all/cranData/AzureAuth/R/cert_creds.R
#' @rdname AzureToken #' @export AzureTokenAuthCode <- R6::R6Class("AzureTokenAuthCode", inherit=AzureToken, public=list( initialize=function(common_args, authorize_args, auth_code) { self$auth_type <- "authorization_code" self$authorize_args <- authorize_args with(common_args, private$set_request_credentials(app, password, username)) do.call(super$initialize, c(common_args, list(auth_info=auth_code))) # notify user if no refresh token if(!is.null(self$credentials) && is.null(self$credentials$refresh_token)) norenew_alert(self$version) } ), private=list( initfunc=function(code=NULL) { stopifnot(is.list(self$token_args)) stopifnot(is.list(self$authorize_args)) opts <- utils::modifyList(list( resource=if(self$version == 1) self$resource else self$scope, tenant=self$tenant, app=self$client$client_id, username=self$client$login_hint, aad_host=self$aad_host, version=self$version ), self$authorize_args) auth_uri <- do.call(build_authorization_uri, opts) redirect <- httr::parse_url(auth_uri)$query$redirect_uri if(is.null(code)) { if(!requireNamespace("httpuv", quietly=TRUE)) stop("httpuv package must be installed to use authorization_code method", call.=FALSE) code <- listen_for_authcode(auth_uri, redirect) } # contact token endpoint for token access_uri <- private$aad_uri("token") body <- c(self$client, code=code, redirect_uri=redirect, self$token_args) httr::POST(access_uri, body=body, encode="form") }, set_request_credentials=function(app, password, username) { object <- list(client_id=app, grant_type="authorization_code") if(!is.null(username)) object$login_hint <- username if(!is.null(password)) object$client_secret <- password self$client <- object } )) #' @rdname AzureToken #' @export AzureTokenDeviceCode <- R6::R6Class("AzureTokenDeviceCode", inherit=AzureToken, public=list( initialize=function(common_args, device_creds) { self$auth_type <- "device_code" with(common_args, private$set_request_credentials(app)) do.call(super$initialize, c(common_args, list(auth_info=device_creds))) # notify user if no refresh token if(!is.null(self$credentials) && is.null(self$credentials$refresh_token)) norenew_alert(self$version) } ), private=list( initfunc=function(creds=NULL) { if(is.null(creds)) { creds <- get_device_creds( if(self$version == 1) self$resource else self$scope, tenant=self$tenant, app=self$client$client_id, aad_host=self$aad_host, version=self$version ) cat(creds$message, "\n") } # poll token endpoint for token access_uri <- private$aad_uri("token") body <- c(self$client, code=creds$device_code) poll_for_token(access_uri, body, creds$interval, creds$expires_in) }, set_request_credentials=function(app) { self$client <- list(client_id=app, grant_type="device_code") } )) #' @rdname AzureToken #' @export AzureTokenClientCreds <- R6::R6Class("AzureTokenClientCreds", inherit=AzureToken, public=list( initialize=function(common_args) { self$auth_type <- "client_credentials" with(common_args, private$set_request_credentials(app, password, certificate)) do.call(super$initialize, common_args) } ), private=list( initfunc=function(init_args) { # contact token endpoint directly with client credentials uri <- private$aad_uri("token") body <- private$build_access_body() httr::POST(uri, body=body, encode="form") }, set_request_credentials=function(app, password, certificate) { object <- list(client_id=app, grant_type="client_credentials") if(!is.null(password)) object$client_secret <- password else if(!is.null(certificate)) { object$client_assertion_type <- "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" object$client_assertion <- certificate # not actual assertion: will be replaced later } else stop("Must provide either a client secret or certificate for client_credentials grant", call.=FALSE) self$client <- object } )) #' @rdname AzureToken #' @export AzureTokenOnBehalfOf <- R6::R6Class("AzureTokenOnBehalfOf", inherit=AzureToken, public=list( initialize=function(common_args, on_behalf_of) { self$auth_type <- "on_behalf_of" with(common_args, private$set_request_credentials(app, password, certificate, on_behalf_of)) do.call(super$initialize, common_args) } ), private=list( initfunc=function(init_args) { # contact token endpoint directly with client credentials uri <- private$aad_uri("token") body <- private$build_access_body() httr::POST(uri, body=body, encode="form") }, set_request_credentials=function(app, password, certificate, on_behalf_of) { if(is_empty(on_behalf_of)) stop("Must provide an Azure token for on_behalf_of grant", call.=FALSE) object <- list(client_id=app, grant_type="urn:ietf:params:oauth:grant-type:jwt-bearer") if(!is.null(password)) object$client_secret <- password else if(!is.null(certificate)) { object$client_assertion_type <- "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" object$client_assertion <- certificate # not actual assertion: will be replaced later } else stop("Must provide either a client secret or certificate for on_behalf_of grant", call.=FALSE) object$requested_token_use <- "on_behalf_of" object$assertion <- extract_jwt(on_behalf_of) self$client <- object } )) #' @rdname AzureToken #' @export AzureTokenResOwner <- R6::R6Class("AzureTokenResOwner", inherit=AzureToken, public=list( initialize=function(common_args) { self$auth_type <- "resource_owner" with(common_args, private$set_request_credentials(app, password, username)) do.call(super$initialize, common_args) } ), private=list( initfunc=function(init_args) { # contact token endpoint directly with resource owner username/password uri <- private$aad_uri("token") body <- private$build_access_body() httr::POST(uri, body=body, encode="form") }, set_request_credentials=function(app, password, username) { object <- list(client_id=app, grant_type="password") if(is.null(username) && is.null(password)) stop("Must provide a username and password for resource_owner grant", call.=FALSE) object$username <- username object$password <- password self$client <- object } )) #' @rdname AzureToken #' @export AzureTokenManaged <- R6::R6Class("AzureTokenManaged", inherit=AzureToken, public=list( initialize=function(resource, aad_host, token_args, use_cache) { self$auth_type <- "managed" super$initialize(resource, tenant="common", aad_host=aad_host, token_args=token_args, use_cache=use_cache) } ), private=list( initfunc=function(init_args) { stopifnot(is.list(self$token_args)) uri <- private$aad_uri("token") query <- utils::modifyList(self$token_args, list(`api-version`=getOption("azure_imds_version"), resource=self$resource)) secret <- Sys.getenv("MSI_SECRET") headers <- if(secret != "") httr::add_headers(secret=secret) else httr::add_headers(metadata="true") httr::GET(uri, headers, query=query) } )) norenew_alert <- function(version) { if(version == 1) message("Server did not provide a refresh token: please reauthenticate to refresh.") else message("Server did not provide a refresh token: you will have to reauthenticate to refresh.\n", "Add the 'offline_access' scope to obtain a refresh token.") }
/scratch/gouwar.j/cran-all/cranData/AzureAuth/R/classes.R
#' Standalone OAuth authorization functions #' #' @param resource,tenant,app,aad_host,version See the corresponding arguments for [get_azure_token]. #' @param username For `build_authorization_uri`, an optional login hint to be sent to the authorization endpoint. #' @param ... Named arguments that will be added to the authorization URI as query parameters. #' #' @details #' These functions are mainly for use in embedded scenarios, such as within a Shiny web app. In this case, the interactive authentication flows (authorization code and device code) need to be split up so that the authorization step is handled separately from the token acquisition step. You should not need to use these functions inside a regular R session, or when executing an R batch script. #' #' @return #' For `build_authorization_uri`, the authorization URI as a string. This can be set as a redirect from within a Shiny app's UI component. #' #' For `get_device_creds`, a list containing the following components: #' - `user_code`: A short string to be shown to the user #' - `device_code`: A long string to verify the session with the AAD server #' - `verification_uri`: The URI the user should browse to in order to login #' - `expires_in`: The duration in seconds for which the user and device codes are valid #' - `interval`: The interval between polling requests to the AAD token endpoint #' - `message`: A string with login instructions for the user #' #' @examples #' build_authorization_uri("https://myresource", "mytenant", "app_id", #' redirect_uri="http://localhost:8100") #' #' \dontrun{ #' #' ## obtaining an authorization code separately to acquiring the token #' # first, get the authorization URI #' auth_uri <- build_authorization_uri("https://management.azure.com/", "mytenant", "app_id") #' # browsing to the URI will log you in and redirect to another URI containing the auth code #' browseURL(auth_uri) #' # use the code to acquire the token #' get_azure_token("https://management.azure.com/", "mytenant", "app_id", #' auth_code="code-from-redirect") #' #' #' ## obtaining device credentials separately to acquiring the token #' # first, contact the authorization endpoint to get the user and device codes #' creds <- get_device_creds("https://management.azure.com/", "mytenant", "app_id") #' # print the login instructions #' creds$message #' # use the creds to acquire the token #' get_azure_token("https://management.azure.com/", "mytenant", "app_id", #' auth_type="device_code", device_creds=creds) #' #' } #' @rdname authorization #' @export build_authorization_uri <- function(resource, tenant, app, username=NULL, ..., aad_host="https://login.microsoftonline.com/", version=1) { version <- normalize_aad_version(version) default_opts <- list( client_id=app, response_type="code", redirect_uri="http://localhost:1410/", login_hint=username, state=paste0(sample(letters, 20, TRUE), collapse="") # random nonce ) default_opts <- if(version == 1) c(default_opts, resource=resource) else c(default_opts, scope=paste_v2_scopes(resource)) opts <- utils::modifyList(default_opts, list(...)) aad_uri(aad_host, normalize_tenant(tenant), version, "authorize", opts) } #' @rdname authorization #' @export get_device_creds <- function(resource, tenant, app, aad_host="https://login.microsoftonline.com/", version=1) { version <- normalize_aad_version(version) uri <- aad_uri(aad_host, normalize_tenant(tenant), version, "devicecode") body <- if(version == 1) list(resource=resource) else list(scope=paste_v2_scopes(resource)) body <- c(body, client_id=app) res <- httr::POST(uri, body=body, encode="form") process_aad_response(res) }
/scratch/gouwar.j/cran-all/cranData/AzureAuth/R/flow_init.R
#' Format an AzureToken object #' #' @param token An Azure OAuth token. #' #' @rdname format #' @export format_auth_header <- function(token) { stopifnot(is_azure_token(token)) expiry <- as.POSIXct(as.numeric(token$credentials$expires_on), origin="1970-01-01") obtained <- expiry - as.numeric(token$credentials$expires_in) if(is_azure_v1_token(token)) { version <- "v1.0" res <- paste("resource", token$resource) } else { version <- "v2.0" res <- paste("scope", paste_v2_scopes(token$scope)) } tenant <- token$tenant if(tenant == "common") { token_obj <- try(decode_jwt(token), silent=TRUE) if(inherits(token_obj, "try-error")) { token_obj <- try(decode_jwt(token, "id"), silent=TRUE) if(inherits(token_obj, "try-error")) tenant <- "NA" else tenant <- paste0(tenant, " / ", token_obj$payload$tid) } else tenant <- paste0(tenant, " / ", token_obj$payload$tid) } paste0("Azure Active Directory ", version, " token for ", res, "\n", " Tenant: ", tenant, "\n", " App ID: ", token$client$client_id, "\n", " Authentication method: ", token$auth_type, "\n", " Token valid from: ", format(obtained, usetz=TRUE), " to: ", format(expiry, usetz=TRUE), "\n", " MD5 hash of inputs: ", token$hash(), "\n") }
/scratch/gouwar.j/cran-all/cranData/AzureAuth/R/format.R
listen_for_authcode <- function(remote_url, local_url) { local_url <- httr::parse_url(local_url) localhost <- if(local_url$hostname == "localhost") "127.0.0.1" else local_url$hostname localport <- local_url$port # based on httr::oauth_listener info <- NULL listen <- function(env) { query <- env$QUERY_STRING info <<- if(is.character(query) && nchar(query) > 0) httr::parse_url(query)$query else list() if(is_empty(info$code)) list(status=404L, headers=list(`Content-Type`="text/plain"), body="Not found") else list(status=200L, headers=list(`Content-Type`="text/plain"), body="Authenticated with Azure Active Directory. Please close this page and return to R.") } server <- httpuv::startServer(as.character(localhost), as.integer(localport), list(call=listen)) on.exit(httpuv::stopServer(server)) message("Waiting for authentication in browser...\nPress Esc/Ctrl + C to abort") httr::BROWSE(remote_url) while(is.null(info)) { httpuv::service() Sys.sleep(0.001) } httpuv::service() if(is_empty(info$code)) { msg <- gsub("\\+", " ", utils::URLdecode(info$error_description)) stop("Authentication failed. Message:\n", msg, call.=FALSE) } message("Authentication complete.") info$code } poll_for_token <- function(url, body, interval, period) { interval <- as.numeric(interval) ntries <- as.numeric(period) %/% interval body$grant_type <- "urn:ietf:params:oauth:grant-type:device_code" message("Waiting for device code in browser...\nPress Esc/Ctrl + C to abort") for(i in seq_len(ntries)) { Sys.sleep(interval) res <- httr::POST(url, body=body, encode="form") status <- httr::status_code(res) cont <- httr::content(res) if(status == 400 && cont$error == "authorization_pending") { # do nothing } else if(status >= 300) process_aad_response(res) # fail here on error else break } if(status >= 300) stop("Authentication failed.", call.=FALSE) message("Authentication complete.") res }
/scratch/gouwar.j/cran-all/cranData/AzureAuth/R/initfuncs.R
#' Get raw access token (which is a JWT object) #' #' @param token A token object. This can be an object of class `AzureToken`, of class `httr::Token`, or a character string containing the encoded token. #' @param type For the `AzureToken` and `httr::Token` methods, the token to decode/retrieve: either the access token or ID token. #' @param ... Other arguments passed to methods. #' #' @details #' An OAuth token is a _JSON Web Token_, which is a set of base64URL-encoded JSON objects containing the token credentials along with an optional (opaque) verification signature. `decode_jwt` decodes the credentials into an R object so they can be viewed. `extract_jwt` extracts the credentials from an R object of class `AzureToken` or `httr::Token`. #' #' Note that `decode_jwt` does not touch the token signature or attempt to verify the credentials. You should not rely on the decoded information without verifying it independently. Passing the token itself to Azure is safe, as Azure will carry out its own verification procedure. #' #' @return #' For `extract_jwt`, the character string containing the encoded token, suitable for including in a HTTP query. For `decode_jwt`, a list containing up to 3 components: `header`, `payload` and `signature`. #' #' @seealso #' [jwt.io](https://jwt.io), the main JWT informational site #' #' [jwt.ms](https://jwt.ms), Microsoft site to decode and explain JWTs #' #' [JWT Wikipedia entry](https://en.wikipedia.org/wiki/JSON_Web_Token) #' @rdname jwt #' @export decode_jwt <- function(token, ...) { UseMethod("decode_jwt") } #' @rdname jwt #' @export decode_jwt.AzureToken <- function(token, type=c("access", "id"), ...) { type <- paste0(match.arg(type), "_token") if(is.null(token$credentials[[type]])) stop(type, " not found", call.=FALSE) decode_jwt(token$credentials[[type]]) } #' @rdname jwt #' @export decode_jwt.Token <- function(token, type=c("access", "id"), ...) { type <- paste0(match.arg(type), "_token") if(is.null(token$credentials[[type]])) stop(type, " not found", call.=FALSE) decode_jwt(token$credentials[[type]]) } #' @rdname jwt #' @export decode_jwt.character <- function(token, ...) { token <- as.list(strsplit(token, "\\.")[[1]]) token[1:2] <- lapply(token[1:2], function(x) jsonlite::fromJSON(rawToChar(jose::base64url_decode(x)))) names(token)[1:2] <- c("header", "payload") if(length(token) > 2) names(token)[3] <- "signature" token } #' @rdname jwt #' @export extract_jwt <- function(token, ...) { UseMethod("extract_jwt") } #' @rdname jwt #' @export extract_jwt.AzureToken <- function(token, type=c("access", "id"), ...) { type <- match.arg(type) token$credentials[[paste0(type, "_token")]] } #' @rdname jwt #' @export extract_jwt.Token <- function(token, type=c("access", "id"), ...) { type <- match.arg(type) token$credentials[[paste0(type, "_token")]] } #' @rdname jwt #' @export extract_jwt.character <- function(token, ...) { token }
/scratch/gouwar.j/cran-all/cranData/AzureAuth/R/jwt.R
#' @rdname get_azure_token #' @export get_managed_token <- function(resource, token_args=list(), use_cache=NULL) { aad_host <- Sys.getenv("MSI_ENDPOINT", "http://169.254.169.254/metadata/identity/oauth2") AzureTokenManaged$new(resource, aad_host, token_args=token_args, use_cache=use_cache) }
/scratch/gouwar.j/cran-all/cranData/AzureAuth/R/managed_token.R
#' Normalize GUID and tenant values #' #' These functions are used by `get_azure_token` to recognise and properly format tenant and app IDs. `is_guid` can also be used generically for identifying GUIDs/UUIDs in any context. #' #' @param tenant For `normalize_tenant`, a string containing an Azure Active Directory tenant. This can be a name ("myaadtenant"), a fully qualified domain name ("myaadtenant.onmicrosoft.com" or "mycompanyname.com"), or a valid GUID. #' @param x For `is_guid`, a character string; for `normalize_guid`, a string containing a _validly formatted_ GUID. #' #' @details #' A tenant can be identified either by a GUID, or its name, or a fully-qualified domain name (FQDN). The rules for normalizing a tenant are: #' 1. If `tenant` is recognised as a valid GUID, return its canonically formatted value #' 2. Otherwise, if it is a FQDN, return it #' 3. Otherwise, if it is one of the generic tenants "common", "organizations" or "consumers", return it #' 4. Otherwise, append ".onmicrosoft.com" to it #' #' These functions are vectorised. See the link below for the GUID formats they accept. #' #' @return #' For `is_guid`, a logical vector indicating which values of `x` are validly formatted GUIDs. #' #' For `normalize_guid`, a vector of GUIDs in canonical format. If any values of `x` are not recognised as GUIDs, it throws an error. #' #' For `normalize_tenant`, the normalized tenant IDs or names. #' #' @seealso #' [get_azure_token] #' #' [Parsing rules for GUIDs in .NET](https://docs.microsoft.com/en-us/dotnet/api/system.guid.parse). `is_guid` and `normalize_guid` recognise the "N", "D", "B" and "P" formats. #' #' @examples #' #' is_guid("72f988bf-86f1-41af-91ab-2d7cd011db47") # TRUE #' is_guid("{72f988bf-86f1-41af-91ab-2d7cd011db47}") # TRUE #' is_guid("72f988bf-86f1-41af-91ab-2d7cd011db47}") # FALSE (unmatched brace) #' is_guid("microsoft") # FALSE #' #' # all of these return the same value #' normalize_guid("72f988bf-86f1-41af-91ab-2d7cd011db47") #' normalize_guid("{72f988bf-86f1-41af-91ab-2d7cd011db47}") #' normalize_guid("(72f988bf-86f1-41af-91ab-2d7cd011db47)") #' normalize_guid("72f988bf86f141af91ab2d7cd011db47") #' #' normalize_tenant("microsoft") # returns 'microsoft.onmicrosoft.com' #' normalize_tenant("microsoft.com") # returns 'microsoft.com' #' normalize_tenant("72f988bf-86f1-41af-91ab-2d7cd011db47") # returns the GUID #' #' # vector arguments are accepted #' ids <- c("72f988bf-86f1-41af-91ab-2d7cd011db47", "72f988bf86f141af91ab2d7cd011db47") #' is_guid(ids) #' normalize_guid(ids) #' normalize_tenant(c("microsoft", ids)) #' #' @export #' @rdname guid normalize_tenant <- function(tenant) { if(!is.character(tenant)) stop("Tenant must be a character string", call.=FALSE) tenant <- tolower(tenant) # check if supplied a guid; if not, check if a fqdn; # if not, check if 'common', 'organizations' or 'consumers'; if not, append '.onmicrosoft.com' guid <- is_guid(tenant) tenant[guid] <- normalize_guid(tenant[guid]) name <- !guid & !(tenant %in% c("common", "organizations", "consumers")) & !grepl(".", tenant, fixed=TRUE) tenant[name] <- paste0(tenant[name], ".onmicrosoft.com") tenant } #' @export #' @rdname guid normalize_guid <- function(x) { if(!all(is_guid(x))) stop("Not a GUID", call.=FALSE) x <- sub("^[({]?([-0-9a-f]+)[})]$", "\\1", x) x <- gsub("-", "", x) return(paste( substr(x, 1, 8), substr(x, 9, 12), substr(x, 13, 16), substr(x, 17, 20), substr(x, 21, 32), sep="-")) } #' @export #' @rdname guid is_guid <- function(x) { if(!is.character(x)) return(FALSE) x <- tolower(x) grepl("^[0-9a-f]{32}$", x) | grepl("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", x) | grepl("^\\{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}}$", x) | grepl("^\\([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\)$", x) } normalize_aad_version <- function(v) { if(v == "v1.0") v <- 1 else if(v == "v2.0") v <- 2 if(!(is.numeric(v) && v %in% c(1, 2))) stop("Invalid AAD version") v }
/scratch/gouwar.j/cran-all/cranData/AzureAuth/R/normalize.R
#' Manage Azure Active Directory OAuth 2.0 tokens #' #' Use these functions to authenticate with Azure Active Directory (AAD). #' #' @param resource For AAD v1.0, the URL of your resource host, or a GUID. For AAD v2.0, a character vector of scopes, each consisting of a URL or GUID along with a path designating the access scope. See 'Details' below. #' @param tenant Your tenant. This can be a name ("myaadtenant"), a fully qualified domain name ("myaadtenant.onmicrosoft.com" or "mycompanyname.com"), or a GUID. It can also be one of the generic tenants "common", "organizations" or "consumers"; see 'Generic tenants' below. #' @param app The client/app ID to use to authenticate with. #' @param password For most authentication flows, this is the password for the _app_ where needed, also known as the client secret. For the resource owner grant, this is your personal account password. See 'Details' below. #' @param username Your AAD username, if using the resource owner grant. See 'Details' below. #' @param certificate A file containing the certificate for authenticating with (including the private key), an Azure Key Vault certificate object, or a call to the `cert_assertion` function to build a client assertion with a certificate. See 'Certificate authentication' below. #' @param auth_type The authentication type. See 'Details' below. #' @param aad_host URL for your AAD host. For the public Azure cloud, this is `https://login.microsoftonline.com/`. Change this if you are using a government or private cloud. Can also be a full URL, eg `https://mydomain.b2clogin.com/mydomain/other/path/names/oauth2` (this is relevant mainly for Azure B2C logins). #' @param version The AAD version, either 1 or 2. Authenticating with a personal account as opposed to a work or school account requires AAD 2.0. The default is AAD 1.0 for compatibility reasons, but you should use AAD 2.0 if possible. #' @param authorize_args An optional list of further parameters for the AAD authorization endpoint. These will be included in the request URI as query parameters. Only used if `auth_type="authorization_code"`. #' @param token_args An optional list of further parameters for the token endpoint. These will be included in the body of the request for `get_azure_token`, or as URI query parameters for `get_managed_token`. #' @param use_cache If TRUE and cached credentials exist, use them instead of obtaining a new token. The default value of NULL means to use the cache only if AzureAuth is not running inside a Shiny app. #' @param on_behalf_of For the on-behalf-of authentication type, a token. This should be either an AzureToken object, or a string containing the JWT-encoded token itself. #' @param auth_code For the `authorization_code` flow, the code. Only used if `auth_type == "authorization_code"`. #' @param device_creds For the `device_code` flow, the device credentials used to verify the session between the client and the server. Only used if `auth_type == "device_code"`. #' #' @details #' `get_azure_token` does much the same thing as [httr::oauth2.0_token()], but customised for Azure. It obtains an OAuth token, first by checking if a cached value exists on disk, and if not, acquiring it from the AAD server. `load_azure_token` loads a token given its hash, `delete_azure_token` deletes a cached token given either the credentials or the hash, and `list_azure_tokens` lists currently cached tokens. #' #' `get_managed_token` is a specialised function to acquire tokens for a _managed identity_. This is an Azure service, such as a VM or container, that has been assigned its own identity and can be granted access permissions like a regular user. The advantage of managed identities over the other authentication methods (see below) is that you don't have to store a secret password, which improves security. Note that `get_managed_token` can only be used from within the managed identity itself. #' #' By default `get_managed_token` retrieves a token using the system-assigned identity for the resource. To obtain a token with a user-assigned identity, pass either the client, object or Azure resource ID in the `token_args` argument. See the examples below. #' #' The `resource` arg should be a single URL or GUID for AAD v1.0. For AAD v2.0, it should be a vector of _scopes_, where each scope consists of a URL or GUID along with a path that designates the type of access requested. If a v2.0 scope doesn't have a path, `get_azure_token` will append the `/.default` path with a warning. A special scope is `offline_access`, which requests a refresh token from AAD along with the access token: without this scope, you will have to reauthenticate if you want to refresh the token. #' #' The `auth_code` and `device_creds` arguments are intended for use in embedded scenarios, eg when AzureAuth is loaded from within a Shiny web app. They enable the flow authorization step to be separated from the token acquisition step, which is necessary within an app; you can generally ignore these arguments when using AzureAuth interactively or as part of an R script. See the help for [build_authorization_uri] for examples on their use. #' #' `token_hash` computes the MD5 hash of its arguments. This is used by AzureAuth to identify tokens for caching purposes. Note that tokens are only cached if you allowed AzureAuth to create a data directory at package startup. #' #' One particular use of the `authorize_args` argument is to specify a different redirect URI to the default; see the examples below. #' #' @section Authentication methods: #' 1. Using the **authorization_code** method is a multi-step process. First, `get_azure_token` opens a login window in your browser, where you can enter your AAD credentials. In the background, it loads the [httpuv](https://github.com/rstudio/httpuv) package to listen on a local port. Once you have logged in, the AAD server redirects your browser to a local URL that contains an authorization code. `get_azure_token` retrieves this authorization code and sends it to the AAD access endpoint, which returns the OAuth token. #' #' 2. The **device_code** method is similar in concept to authorization_code, but is meant for situations where you are unable to browse the Internet -- for example if you don't have a browser installed or your computer has input constraints. First, `get_azure_token` contacts the AAD devicecode endpoint, which responds with a login URL and an access code. You then visit the URL and enter the code, possibly using a different computer. Meanwhile, `get_azure_token` polls the AAD access endpoint for a token, which is provided once you have entered the code. #' #' 3. The **client_credentials** method is much simpler than the above methods, requiring only one step. `get_azure_token` contacts the access endpoint, passing it either the app secret or the certificate assertion (which you supply in the `password` or `certificate` argument respectively). Once the credentials are verified, the endpoint returns the token. This is the method typically used by service accounts. #' #' 4. The **resource_owner** method also requires only one step. In this method, `get_azure_token` passes your (personal) username and password to the AAD access endpoint, which validates your credentials and returns the token. #' #' 5. The **on_behalf_of** method is used to authenticate with an Azure resource by passing a token obtained beforehand. It is mostly used by intermediate apps to authenticate for users. In particular, you can use this method to obtain tokens for multiple resources, while only requiring the user to authenticate once: see the examples below. #' #' If the authentication method is not specified, it is chosen based on the presence or absence of the other arguments, and whether httpuv is installed. #' #' The httpuv package must be installed to use the authorization_code method, as this requires a web server to listen on the (local) redirect URI. See [httr::oauth2.0_token] for more information; note that Azure does not support the `use_oob` feature of the httr OAuth 2.0 token class. #' #' Similarly, since the authorization_code method opens a browser to load the AAD authorization page, your machine must have an Internet browser installed that can be run from inside R. In particular, if you are using a Linux [Data Science Virtual Machine](https://azure.microsoft.com/en-us/services/virtual-machines/data-science-virtual-machines/) in Azure, you may run into difficulties; use one of the other methods instead. #' #' @section Certificate authentication: #' OAuth tokens can be authenticated via an SSL/TLS certificate, which is considered more secure than a client secret. To do this, use the `certificate` argument, which can contain any of the following: #' - The name of a PEM or PFX file, containing _both_ the private key and the public certificate. #' - A certificate object from the AzureKeyVault package, representing a cert stored in the Key Vault service. #' - A call to the `cert_assertion()` function to customise details of the requested token, eg the duration, expiry date, custom claims, etc. See the examples below. #' #' @section Generic tenants: #' #' There are 3 generic values that can be used as tenants when authenticating: #' #' | Tenant | Description | #' | ------ | ----------- | #' | `common` | Allows users with both personal Microsoft accounts and work/school accounts from Azure AD to sign into the application. | #' | `organizations` | Allows only users with work/school accounts from Azure AD to sign into the application. | #' | `consumers` | Allows only users with personal Microsoft accounts (MSA) to sign into the application. | #' #' @section Authentication vs authorization: #' Azure Active Directory can be used for two purposes: _authentication_ (verifying that a user is who they claim they are) and _authorization_ (granting a user permission to access a resource). In AAD, a successful authorization process concludes with the granting of an OAuth 2.0 access token, as discussed above. Authentication uses the same process but concludes by granting an ID token, as defined in the OpenID Connect protocol. #' #' `get_azure_token` can be used to obtain ID tokens along with regular OAuth access tokens, when using an interactive flow (authorization_code or device_code). The behaviour depends on the AAD version: #' #' When retrieving ID tokens, the behaviour depends on the AAD version: #' - AAD v1.0 will return an ID token as well as the access token by default; you don't have to do anything extra. However, AAD v1.0 will not _refresh_ the ID token when it expires; you must reauthenticate to get a new one. To ensure you don't pull the cached version of the credentials, specify `use_cache=FALSE` in the calls to `get_azure_token`. #' - Unlike AAD v1.0, AAD v2.0 does not return an ID token by default. To get a token, include `openid` as a scope. On the other hand it _does_ refresh the ID token, so bypassing the cache is not needed. It's recommended to use AAD v2.0 if you only want an ID token. #' #' If you _only_ want to do authentication and not authorization (for example if your app does not use any Azure resources), specify the `resource` argument as follows: #' - For AAD v1.0, use a blank resource (`resource=""`). #' - For AAD v2.0, use `resource="openid"` without any other elements. Optionally you can add `"offline_access"` as a 2nd element if you want a refresh token as well. #' #' See also the examples below. #' #' @section Caching: #' AzureAuth caches tokens based on all the inputs to `get_azure_token` as listed above. Tokens are cached in a custom, user-specific directory, created with the rappdirs package. On recent Windows versions, this will usually be in the location `C:\\Users\\(username)\\AppData\\Local\\AzureR`. On Linux, it will be in `~/.config/AzureR`, and on MacOS, it will be in `~/Library/Application Support/AzureR`. Alternatively, you can specify the location of the directory in the environment variable `R_AZURE_DATA_DIR`. Note that a single directory is used for all tokens, and the working directory is not touched (which significantly lessens the risk of accidentally introducing cached tokens into source control). #' #' To list all cached tokens on disk, use `list_azure_tokens`. This returns a list of token objects, named according to their MD5 hashes. #' #' To delete a cached token, use `delete_azure_token`. This takes the same inputs as `get_azure_token`, or you can specify the MD5 hash directly in the `hash` argument. #' #' To delete all files in the caching directory, use `clean_token_directory`. #' #' @section Refreshing: #' A token object can be refreshed by calling its `refresh()` method. If the token's credentials contain a refresh token, this is used; otherwise a new access token is obtained by reauthenticating. #' #' Note that in AAD, a refresh token can be used to obtain an access token for any resource or scope that you have permissions for. Thus, for example, you could use a refresh token issued on a request for Azure Resource Manager (`https://management.azure.com/`) to obtain a new access token for Microsoft Graph (`https://graph.microsoft.com/`). #' #' To obtain an access token for a new resource, change the object's `resource` (for an AAD v1.0 token) or `scope` field (for an AAD v2.0 token) before calling `refresh()`. If you _also_ want to retain the token for the old resource, you should call the `clone()` method first to create a copy. See the examples below. #' #' @section Value: #' For `get_azure_token`, an object inheriting from `AzureToken`. The specific class depends on the authentication flow: `AzureTokenAuthCode`, `AzureTokenDeviceCode`, `AzureTokenClientCreds`, `AzureTokenOnBehalfOf`, `AzureTokenResOwner`. For `get_managed_token`, a similar object of class `AzureTokenManaged`. #' #' For `list_azure_tokens`, a list of such objects retrieved from disk. #' #' The actual credentials that are returned from the authorization endpoint can be found in the `credentials` field, the same as with a `httr::Token` object. The access token (if present) will be `credentials$access_token`, and the ID token (if present) will be `credentials$id_token`. Use these if you are manually constructing a HTTP request and need to insert an "Authorization" header, for example. #' #' @seealso #' [AzureToken], [httr::oauth2.0_token], [httr::Token], [cert_assertion], #' [build_authorization_uri], [get_device_creds] #' #' [Azure Active Directory for developers](https://docs.microsoft.com/en-us/azure/active-directory/develop/), #' [Managed identities overview](https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview) #' [Device code flow on OAuth.com](https://www.oauth.com/oauth2-servers/device-flow/token-request/), #' [OAuth 2.0 RFC](https://tools.ietf.org/html/rfc6749) for the gory details on how OAuth works #' #' @examples #' \dontrun{ #' #' # authenticate with Azure Resource Manager: #' # no user credentials are supplied, so this will use the authorization_code #' # method if httpuv is installed, and device_code if not #' get_azure_token("https://management.azure.com/", tenant="mytenant", app="app_id") #' #' # you can force a specific authentication method with the auth_type argument #' get_azure_token("https://management.azure.com/", tenant="mytenant", app="app_id", #' auth_type="device_code") #' #' # to default to the client_credentials method, supply the app secret as the password #' get_azure_token("https://management.azure.com/", tenant="mytenant", app="app_id", #' password="app_secret") #' #' # authenticate to your resource with the resource_owner method: provide your username and password #' get_azure_token("https://myresource/", tenant="mytenant", app="app_id", #' username="user", password="abcdefg") #' #' # obtaining multiple tokens: authenticate (interactively) once... #' tok0 <- get_azure_token("serviceapp_id", tenant="mytenant", app="clientapp_id", #' auth_type="authorization_code") #' # ...then get tokens for each resource (Resource Manager and MS Graph) with on_behalf_of #' tok1 <- get_azure_token("https://management.azure.com/", tenant="mytenant", app="serviceapp_id", #' password="serviceapp_secret", on_behalf_of=tok0) #' tok2 <- get_azure_token("https://graph.microsoft.com/", tenant="mytenant", app="serviceapp_id", #' password="serviceapp_secret", on_behalf_of=tok0) #' #' #' # authorization_code flow with app registered in AAD as a web rather than a native client: #' # supply the client secret in the password arg #' get_azure_token("https://management.azure.com/", "mytenant", "app_id", #' password="app_secret", auth_type="authorization_code") #' #' #' # use a different redirect URI to the default localhost:1410 #' get_azure_token("https://management.azure.com/", tenant="mytenant", app="app_id", #' authorize_args=list(redirect_uri="http://localhost:8000")) #' #' #' # request an AAD v1.0 token for Resource Manager (the default) #' token1 <- get_azure_token("https://management.azure.com/", "mytenant", "app_id") #' #' # same request to AAD v2.0, along with a refresh token #' token2 <- get_azure_token(c("https://management.azure.com/.default", "offline_access"), #' "mytenant", "app_id", version=2) #' #' # requesting multiple scopes (Microsoft Graph) with AAD 2.0 #' get_azure_token(c("https://graph.microsoft.com/User.Read.All", #' "https://graph.microsoft.com/User.ReadWrite.All", #' "https://graph.microsoft.com/Directory.ReadWrite.All", #' "offline_access"), #' "mytenant", "app_id", version=2) #' #' #' # list saved tokens #' list_azure_tokens() #' #' # delete a saved token from disk #' delete_azure_token(resource="https://myresource/", tenant="mytenant", app="app_id", #' username="user", password="abcdefg") #' #' # delete a saved token by specifying its MD5 hash #' delete_azure_token(hash="7ea491716e5b10a77a673106f3f53bfd") #' #' #' # authenticating for B2C logins (custom AAD host) #' get_azure_token("https://mydomain.com", "mytenant", "app_id", "password", #' aad_host="https://mytenant.b2clogin.com/tfp/mytenant.onmicrosoft.com/custom/oauth2") #' #' #' # authenticating with a certificate #' get_azure_token("https://management.azure.com/", "mytenant", "app_id", #' certificate="mycert.pem") #' #' # authenticating with a certificate stored in Azure Key Vault #' cert <- AzureKeyVault::key_vault("myvault")$certificates$get("mycert") #' get_azure_token("https://management.azure.com/", "mytenant", "app_id", #' certificate=cert) #' #' # get a token valid for 2 hours (default is 1 hour) #' get_azure_token("https://management.azure.com/", "mytenant", "app_id", #' certificate=cert_assertion("mycert.pem", duration=2*3600)) #' #' #' # ID token with AAD v1.0 #' # if you only want an ID token, set the resource to blank ("") #' tok <- get_azure_token("", "mytenant", "app_id", use_cache=FALSE) #' extract_jwt(tok, "id") #' #' # ID token with AAD v2.0 (recommended) #' tok2 <- get_azure_token(c("openid", "offline_access"), "mytenant", "app_id", version=2) #' extract_jwt(tok2, "id") #' #' #' # get a token from within a managed identity (VM, container or service) #' get_managed_token("https://management.azure.com/") #' #' # get a token from a managed identity, with a user-defined identity: #' # specify one of the identity's object_id, client_id and mi_res_id (Azure resource ID) #' # you can get these values via the Azure Portal or Azure CLI #' get_managed_token("https://management.azure.com/", token_args=list( #' mi_res_id="/subscriptions/zzzz-zzzz/resourceGroups/resgroupname/..." #' )) #' #' # use a refresh token from one resource to get an access token for another resource #' tok <- get_azure_token("https://myresource", "mytenant", "app_id") #' tok2 <- tok$clone() #' tok2$resource <- "https://anotherresource" #' tok2$refresh() #' #' # same for AAD v2.0 #' tok <- get_azure_token(c("https://myresource/.default", "offline_access"), #' "mytenant", "app_id", version=2) #' tok2 <- tok$clone() #' tok2$scope <- c("https://anotherresource/.default", "offline_access") #' tok2$refresh() #' #' #' # manually adding auth header for a HTTP request #' tok <- get_azure_token("https://myresource", "mytenant", "app_id") #' header <- httr::add_headers(Authorization=paste("Bearer", tok$credentials$access_token)) #' httr::GET("https://myresource/path/for/call", header, ...) #' #' } #' @export get_azure_token <- function(resource, tenant, app, password=NULL, username=NULL, certificate=NULL, auth_type=NULL, aad_host="https://login.microsoftonline.com/", version=1, authorize_args=list(), token_args=list(), use_cache=NULL, on_behalf_of=NULL, auth_code=NULL, device_creds=NULL) { auth_type <- select_auth_type(password, username, certificate, auth_type, on_behalf_of) common_args <- list( resource=resource, tenant=tenant, app=app, password=password, username=username, certificate=certificate, aad_host=aad_host, version=version, token_args=token_args, use_cache=use_cache ) switch(auth_type, authorization_code= AzureTokenAuthCode$new(common_args, authorize_args, auth_code), device_code= AzureTokenDeviceCode$new(common_args, device_creds), client_credentials= AzureTokenClientCreds$new(common_args), on_behalf_of= AzureTokenOnBehalfOf$new(common_args, on_behalf_of), resource_owner= AzureTokenResOwner$new(common_args), stop("Unknown authentication method ", auth_type, call.=FALSE)) } #' @param hash The MD5 hash of this token, computed from the above inputs. Used by `load_azure_token` and `delete_azure_token` to identify a cached token to load and delete, respectively. #' @param confirm For `delete_azure_token`, whether to prompt for confirmation before deleting a token. #' @rdname get_azure_token #' @export delete_azure_token <- function(resource, tenant, app, password=NULL, username=NULL, certificate=NULL, auth_type=NULL, aad_host="https://login.microsoftonline.com/", version=1, authorize_args=list(), token_args=list(), on_behalf_of=NULL, hash=NULL, confirm=TRUE) { if(!dir.exists(AzureR_dir())) return(invisible(NULL)) if(is.null(hash)) hash <- token_hash(resource, tenant, app, password, username, certificate, auth_type, aad_host, version, authorize_args, token_args, on_behalf_of) if(confirm && interactive() && !get_confirmation("Do you really want to delete this Azure Active Directory token?", FALSE)) return(invisible(NULL)) file.remove(file.path(AzureR_dir(), hash)) invisible(NULL) } #' @rdname get_azure_token #' @export load_azure_token <- function(hash) { readRDS(file.path(AzureR_dir(), hash)) } #' @rdname get_azure_token #' @export clean_token_directory <- function(confirm=TRUE) { if(!dir.exists(AzureR_dir())) return(invisible(NULL)) if(confirm && interactive() && !get_confirmation("Do you really want to remove all files in the AzureR token directory?", FALSE)) return(invisible(NULL)) toks <- dir(AzureR_dir(), full.names=TRUE) file.remove(toks) invisible(NULL) } #' @rdname get_azure_token #' @export list_azure_tokens <- function() { tokens <- dir(AzureR_dir(), pattern="[0-9a-f]{32}", full.names=TRUE) lst <- lapply(tokens, function(fname) { x <- try(readRDS(fname), silent=TRUE) if(is_azure_token(x)) x else NULL }) names(lst) <- basename(tokens) lst[!sapply(lst, is.null)] } #' @rdname get_azure_token #' @export token_hash <- function(resource, tenant, app, password=NULL, username=NULL, certificate=NULL, auth_type=NULL, aad_host="https://login.microsoftonline.com/", version=1, authorize_args=list(), token_args=list(), on_behalf_of=NULL) { # create dummy object object <- get_azure_token( resource=resource, tenant=tenant, app=app, password=password, username=username, certificate=certificate, auth_type=auth_type, aad_host=aad_host, version=version, authorize_args=authorize_args, token_args=token_args, on_behalf_of=on_behalf_of, use_cache=NA ) object$hash() } token_hash_internal <- function(...) { msg <- serialize(list(...), NULL, version=2) paste(openssl::md5(msg[-(1:14)]), collapse="") } # handle different behaviour of file_path on Windows/Linux wrt trailing / construct_path <- function(...) { sub("/$", "", file.path(..., fsep="/")) } is_empty <- function(x) { is.null(x) || length(x) == 0 } #' @param object For `is_azure_token`, `is_azure_v1_token` and `is_azure_v2_token`, an R object. #' @rdname get_azure_token #' @export is_azure_token <- function(object) { R6::is.R6(object) && inherits(object, "AzureToken") } #' @rdname get_azure_token #' @export is_azure_v1_token <- function(object) { is_azure_token(object) && object$version == 1 } #' @rdname get_azure_token #' @export is_azure_v2_token <- function(object) { is_azure_token(object) && object$version == 2 }
/scratch/gouwar.j/cran-all/cranData/AzureAuth/R/token.R
select_auth_type <- function(password, username, certificate, auth_type, on_behalf_of) { if(!is.null(auth_type)) { if(!auth_type %in% c("authorization_code", "device_code", "client_credentials", "resource_owner", "on_behalf_of", "managed")) stop("Invalid authentication method") return(auth_type) } got_pwd <- !is.null(password) got_user <- !is.null(username) got_cert <- !is.null(certificate) got_httpuv <- system.file(package="httpuv") != "" auth_type <- if(got_pwd && got_user && !got_cert) "resource_owner" else if(!got_pwd && !got_user && !got_cert) { if(!got_httpuv) { message("httpuv not installed, defaulting to device code authentication") "device_code" } else "authorization_code" } else if(!got_pwd && !got_cert && got_user && got_httpuv) "authorization_code" else if((got_pwd && !got_user) || got_cert) { if(is_empty(on_behalf_of)) "client_credentials" else "on_behalf_of" } else stop("Can't select authentication method", call.=FALSE) message("Using ", auth_type, " flow") auth_type } process_aad_response <- function(res) { status <- httr::status_code(res) if(status >= 300) { cont <- httr::content(res) msg <- if(is.character(cont)) cont else if(is.list(cont) && is.character(cont$error_description)) cont$error_description else "" msg <- paste0("obtain Azure Active Directory token. Message:\n", sub("\\.$", "", msg)) list(token=httr::stop_for_status(status, msg)) } else httr::content(res) } # need to capture bad scopes before requesting auth code # v2.0 endpoint will show error page rather than redirecting, causing get_azure_token to wait forever verify_v2_scope <- function(scope) { # some OpenID scopes get a pass openid_scopes <- c("openid", "email", "profile", "offline_access") if(scope %in% openid_scopes) return(scope) # but not all bad_scopes <- c("address", "phone") if(scope %in% bad_scopes) stop("Unsupported OpenID scope: ", scope, call.=FALSE) # is it a URI or GUID? valid_uri <- !is.null(httr::parse_url(scope)$scheme) valid_guid <- is_guid(sub("/.*$", "", scope)) if(!valid_uri && !valid_guid) stop("Invalid scope (must be a URI or GUID): ", scope, call.=FALSE) # if a URI or GUID, check that there is a valid scope in the path if(valid_uri) { uri <- httr::parse_url(scope) if(uri$path == "") { warning("No path supplied for scope ", scope, "; setting to /.default", call.=FALSE) uri$path <- ".default" scope <- httr::build_url(uri) } } else { path <- sub("^[^/]+/?", "", scope) if(path == "") { warning("No path supplied for scope ", scope, "; setting to /.default", call.=FALSE) scope <- sub("//", "/", paste0(scope, "/.default")) } } scope } aad_uri <- function(aad_host, tenant, version, type, query=list()) { uri <- httr::parse_url(aad_host) uri$query <- query uri$path <- if(nchar(uri$path) == 0) { if(version == 1) file.path(tenant, "oauth2", type) else file.path(tenant, "oauth2/v2.0", type) } else file.path(uri$path, type) httr::build_url(uri) } paste_v2_scopes <- function(scope) { paste(scope, collapse=" ") } # display confirmation prompt, return TRUE/FALSE (no NA) get_confirmation <- function(msg, default=TRUE) { ok <- if(getRversion() < numeric_version("3.5.0")) { msg <- paste(msg, if(default) "(Yes/no/cancel) " else "(yes/No/cancel) ") yn <- readline(msg) if(nchar(yn) == 0) default else tolower(substr(yn, 1, 1)) == "y" } else utils::askYesNo(msg, default) isTRUE(ok) } in_shiny <- function() { ("shiny" %in% loadedNamespaces()) && shiny::isRunning() }
/scratch/gouwar.j/cran-all/cranData/AzureAuth/R/utils.R
--- title: "Common authentication scenarios" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Authentication scenarios} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- The interaction between app registration configuration and requesting a token can be confusing. This vignette outlines some common authentication scenarios that R users might encounter. For each scenario, we briefly describe the necessary settings for your app registration in Azure, and how to request a token using AzureAuth. The [Azure Active Directory documentation](https://docs.microsoft.com/en-au/azure/active-directory/develop/v2-overview) is the authoritative reference. ## Interactive authentication on a local machine This is the simplest scenario: you're using R on your local desktop or laptop, and you want to authenticate to Azure with your user credentials. The authentication flow to use in this case is **authorization_code**. This requires that you have a browser installed on your machine, and it can be called from within R (as is usually the case). You'll also need to have the [httpuv](https://cran.r-project.org/package=httpuv) package: this will be installed if you're a Shiny developer, but otherwise you might have to install it manually. The code to run in your R session is ```r library(AzureAuth) # for an AADv1 token tok <- get_azure_token("https://resource", tenant="yourtenant", app="yourappid") # for an AADv2 token tok <- get_azure_token("https://resource/scope", tenant="yourtenant", app="yourappid", version=2) ``` where `resource[/scope]` is the Azure resource/scope you want a token for, `yourtenant` is your Azure tenant name or GUID, and `yourappid` is your app registration ID. Note that you do _not_ specify your username or password in the `get_azure_token` call. On the server side, the app registration you use should have a **mobile & desktop redirect** of `http://localhost:1410`. See the crop below of the authentication pane for the app in the Azure portal. ![](images/authcode.png) ## Interactive authentication in a remote session This is the scenario where you are using R in a remote terminal session of some kind: RStudio Server, Azure Databricks, or a Linux VM over ssh. Here, you still want to authenticate with your user credentials, but a browser may not be available to use the regular AAD authentication process. The authentication flow to use is **device_code**. This requires that you have a browser available elsewhere (for example, on the local machine from which you're logged in to your remote session). The code to run in your R session is ```r tok <- get_azure_token("resource", tenant="yourtenant", app="yourappid", auth_type="device_code") ``` As before, you do _not_ include your username or password in the `get_azure_token` call. On the server side, the app registration should have the **"Allow public client flows"** setting enabled. ![](images/devicecode.png) It's possible, and indeed desirable, to combine this with the previous redirect URI in the one app registration. This way, you can use the same app ID to authenticate both locally and in a remote terminal. ## Interactive authentication in a webapp This is the scenario where you want to authenticate as part of a webapp, such as a Shiny app. For this scenario, your app registration should have a **webapp redirect** that has the same URL as your app, eg `https://youraccount.shinyapps.io/yourapp` for an app hosted in shinyapps.io. The difference between a mobile & desktop and a webapp redirect is that you supply a **client secret** when authenticating with the latter, but not the former. The client secret is like a password, and helps prevent third parties from hijacking your app registration. The authentication flow to use is **authorization_code**, the same as for a local machine. The Shiny R code that is required is described in more detail in the 'Authenticating from Shiny' vignette, but essentially, the authentication is split into 2 parts: the authorization step in the UI, and then the token acquisition step on the server. ```r tenant <- "yourtenant" app <- "yourappid" redirect <- "https://yourwebsite.example.com/" # authorization: part of UI.r auth_uri <- build_authorization_uri("https://resource", tenant, app, redirect_uri=redirect) redir_js <- sprintf("location.replace(\"%s\");", auth_uri) tags$script(HTML(redir_js)) # token acquisition: part of server.R tok <- get_azure_token("https://resource", tenant, app, password="client_secret", auth_type="authorization_code", authorize_args=list(redirect_uri=redirect), use_cache=FALSE, auth_code=opts$code) ``` Note that the `password` argument holds the client secret for the app registration, _not_ a user password. See the crop below of the certificates & secrets pane for the app registration. ![](images/clientcred.png) Be aware that the client secret is automatically generated by the server and cannot be modified. You can only see it at the time of generation, so make sure you note down its value. ## Non-interactive authentication This is the scenario where you want to authenticate to Azure without a user account present, for example in a deployment pipeline. The authentication flow to use is **client_credentials**. The code to run looks like ```r tok <- get_azure_token("resource", tenant="yourtenant", app="yourccappid", password="client_secret") ``` Here, `yourccappid` is the app ID to use for your pipeline; you should not use the same app registration for this purpose as for interactive logins. The `password` argument is the **client secret** for your app registration, and not a user password. The client secret is set in the same way as for the interactive webapp scenario, above. As an alternative to a client secret, it's possible to authenticate using a TLS certificate (public key). This is considered more secure, but is also more complicated to setup. For more information, see the AAD docs linked previously. ## More information The following pages at the AAD documentation will be helpful if you're new to creating app registrations: - [A step-by-step guide](https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app) to registering an app in the Azure portal. - [How to set permissions for an app](https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-configure-app-access-web-apis). For interactive authentication (authenticating as a user), you want _delegated_ permissions. For non-interactive authentication (authenticating as the application), you want _application_ permissions. - [Restricting your app to a set of users](https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-restrict-your-app-to-a-set-of-users)---if you don't want your app to be accessible to every user in your organisation. Only applies to webapps, not native (desktop & mobile) apps.
/scratch/gouwar.j/cran-all/cranData/AzureAuth/inst/doc/scenarios.Rmd
--- title: "Authenticating from Shiny" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Shiny} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- Because a Shiny app has separate UI and server components, the interactive authentication flows require some changes. In particular, the authorization step (logging in to Azure) has to be conducted separately from the token acquisition step. AzureAuth provides the `build_authorization_uri` function to facilitate this separation. You call this function to obtain a URI that you browse to in order to login to Azure. Once you have logged in, Azure will return an authorization code as part of a redirect. Here is a skeleton Shiny app that demonstrates its use. The UI calls `build_authorization_uri`, and then redirects your browser to that location. When you have logged in, the server captures the authorization code and calls `get_azure_token` to obtain the token. Once the token is obtained, `shinyjs` is used to return the URL back to its original state. ```r library(AzureAuth) library(shiny) library(shinyjs) tenant <- "your-tenant-here" app <- "your-app-id-here" # the Azure resource permissions needed # if your app doesn't use any Azure resources (you only want to do authentication), # set the resource to "openid" only resource <- c("https://management.azure.com/.default", "openid") # set this to the site URL of your app once it is deployed # this must also be the redirect for your registered app in Azure Active Directory redirect <- "http://localhost:8100" port <- httr::parse_url(redirect)$port options(shiny.port=if(is.null(port)) 80 else as.numeric(port)) # replace this with your app's regular UI ui <- fluidPage( useShinyjs(), verbatimTextOutput("token") ) ui_func <- function(req) { opts <- parseQueryString(req$QUERY_STRING) if(is.null(opts$code)) { auth_uri <- build_authorization_uri(resource, tenant, app, redirect_uri=redirect, version=2) redir_js <- sprintf("location.replace(\"%s\");", auth_uri) tags$script(HTML(redir_js)) } else ui } # code for cleaning url after authentication clean_url_js <- sprintf( " $(document).ready(function(event) { const nextURL = '%s'; const nextTitle = 'My new page title'; const nextState = { additionalInformation: 'Updated the URL with JS' }; // This will create a new entry in the browser's history, without reloading window.history.pushState(nextState, nextTitle, nextURL); }); ", redirect ) server <- function(input, output, session) { shinyjs::runjs(clean_url_js) opts <- parseQueryString(isolate(session$clientData$url_search)) if(is.null(opts$code)) return() # this assumes your app has a 'public client/native' redirect: # if it is a 'web' redirect, include the client secret as the password argument token <- get_azure_token(resource, tenant, app, auth_type="authorization_code", authorize_args=list(redirect_uri=redirect), version=2, use_cache=FALSE, auth_code=opts$code) output$token <- renderPrint(token) } shinyApp(ui_func, server) ``` Note that this process is only necessary within a web app, and only when using an interactive authentication flow. In a normal R session, or when using the client credentials or resource owner grant flows, you can simply call `get_azure_token` directly.
/scratch/gouwar.j/cran-all/cranData/AzureAuth/inst/doc/shiny.Rmd
--- title: "Acquire an OAuth token" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Acquire an OAuth token} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- This is a short introduction to authenticating with Azure Active Directory (AAD) with AzureAuth. ## The `get_azure_token` function The main function in AzureAuth is `get_azure_token`, which obtains an OAuth token from AAD: ```r library(AzureAuth) token <- get_azure_token(resource="myresource", tenant="mytenant", app="app_id", password="mypassword", username="username", certificate="encoded_cert", version=1, ...) ``` The function has the following arguments: - `resource`: The resource or scope for which you want a token. For AAD v1.0, this should be a single URL (eg "[https://example.com](https://example.com)") or a GUID. For AAD v2.0, this should be a vector of scopes (see below). - `tenant`: The AAD tenant. - `app`: The app ID or service principal ID to authenticate with. - `username`, `password`, `certificate`: Your authentication credentials. - `auth_type`: The OAuth authentication method to use. See the next section. - `version`: The version of AAD for which you want a token, either 1 or 2. The default is version 1. Note that the _OAuth scheme_ is always 2.0. Scopes in AAD v2.0 consist of a URL or a GUID, along with a path that designates the scope. If a scope doesn't have a path, `get_azure_token` will append the `/.default` path with a warning. A special scope is `offline_access`, which requests a refresh token from AAD along with the access token: without this, you will have to reauthenticate if you want to refresh the token. ```r # request an AAD v1.0 token for Resource Manager token1 <- get_azure_token("https://management.azure.com/", "mytenant", "app_id") # same request to AAD v2.0, along with a refresh token token2 <- get_azure_token(c("https://management.azure.com/.default", "offline_access"), "mytenant", "app_id", version=2) # requesting multiple scopes in AAD v2.0 (Microsoft Graph) scopes <- c("https://graph.microsoft.com/User.Read", "https://graph.microsoft.com/Files.Read", "https://graph.microsoft.com/Mail.Read", "offline_access") token3 <- get_azure_token(scopes, "mytenant", "app_id", version=2) ``` ## Authentication methods AzureAuth supports the following methods for authenticating with AAD: **authorization_code**, **device_code**, **client_credentials**, **resource_owner** and **on_behalf_of**. 1. Using the **authorization_code** method is a multi-step process. First, `get_azure_token` opens a login window in your browser, where you can enter your AAD credentials. In the background, it loads the [httpuv](https://github.com/rstudio/httpuv) package to listen on a local port. Once you have logged in, the AAD server redirects your browser to a local URL that contains an authorization code. `get_azure_token` retrieves this authorization code and sends it to the AAD access endpoint, which returns the OAuth token.</p> The httpuv package must be installed to use this method, as it requires a web server to listen on the (local) redirect URI. Since it opens a browser to load the AAD authorization page, your machine must also have an Internet browser installed that can be run from inside R. In particular, if you are using a Linux [Data Science Virtual Machine](https://azure.microsoft.com/en-us/services/virtual-machines/data-science-virtual-machines/) in Azure, you may run into difficulties; use one of the other methods instead. ```r # obtain a token using authorization_code # no user credentials needed get_azure_token("myresource", "mytenant", "app_id", auth_type="authorization_code") ``` 2. The **device_code** method is similar in concept to authorization_code, but is meant for situations where you are unable to browse the Internet -- for example if you don't have a browser installed or your computer has input constraints. First, `get_azure_token` contacts the AAD devicecode endpoint, which responds with a login URL and an access code. You then visit the URL and enter the code, possibly using a different computer. Meanwhile, `get_azure_token` polls the AAD access endpoint for a token, which is provided once you have entered the code. ```r # obtain a token using device_code # no user credentials needed get_azure_token("myresource", "mytenant", "app_id", auth_type="device_code") ``` 3. The **client_credentials** method is much simpler than the above methods, requiring only one step. `get_azure_token` contacts the access endpoint, passing it the credentials. This can be either a client secret or a certificate, which you supply in the `password` or `certificate` argument respectively. Once the credentials are verified, the endpoint returns the token. This is the method typically used by service accounts. ```r # obtain a token using client_credentials # supply credentials in password arg get_azure_token("myresource", "mytenant", "app_id", password="client_secret", auth_type="client_credentials") # can also supply a client certificate as a PEM/PFX file... get_azure_token("myresource", "mytenant", "app_id", certificate="mycert.pem", auth_type="client_credentials") # ... or as an object in Azure Key Vault cert <- AzureKeyVault::key_vault("myvault")$certificates$get("mycert") get_azure_token("myresource", "mytenant", "app_id", certificate=cert, auth_type="client_credentials") ``` 4. The **resource_owner** method also requires only one step. In this method, `get_azure_token` passes your (personal) username and password to the AAD access endpoint, which validates your credentials and returns the token. ```r # obtain a token using resource_owner # supply credentials in username and password args get_azure_token("myresource", "mytenant", "app_id", username="myusername", password="mypassword", auth_type="resource_owner") ``` 5. The **on_behalf_of** method is used to authenticate with an Azure resource by passing a token obtained beforehand. It is mostly used by intermediate apps to authenticate for users. In particular, you can use this method to obtain tokens for multiple resources, while only requiring the user to authenticate once. ```r # obtaining multiple tokens: authenticate (interactively) once... tok0 <- get_azure_token("serviceapp_id", "mytenant", "clientapp_id", auth_type="authorization_code") # ...then get tokens for each resource with on_behalf_of tok1 <- get_azure_token("resource1", "mytenant," "serviceapp_id", password="serviceapp_secret", auth_type="on_behalf_of", on_behalf_of=tok0) tok2 <- get_azure_token("resource2", "mytenant," "serviceapp_id", password="serviceapp_secret", auth_type="on_behalf_of", on_behalf_of=tok0) ``` If you don't specify the method, `get_azure_token` makes a best guess based on the presence or absence of the other authentication arguments, and whether httpuv is installed. ```r # this will default to authorization_code if httpuv is installed, and device_code if not get_azure_token("myresource", "mytenant", "app_id") # this will use client_credentials method get_azure_token("myresource", "mytenant", "app_id", password="client_secret") # this will use on_behalf_of method get_azure_token("myresource", "mytenant", "app_id", password="client_secret", on_behalf_of=token) ``` ### Managed identities AzureAuth provides `get_managed_token` to obtain tokens from within a managed identity. This is a VM, service or container in Azure that can authenticate as itself, which removes the need to save secret passwords or certificates. ```r # run this from within an Azure VM or container for which an identity has been setup get_managed_token("myresource") ``` ### Inside a web app Using the interactive flows (authorization_code and device_code) from within a Shiny app requires separating the authorization (logging in to Azure) step from the token acquisition step. For this purpose, AzureAuth provides the `build_authorization_uri` and `get_device_creds` functions. You can use these from within your app to carry out the authorization, and then pass the resulting credentials to `get_azure_token` itself. See the "Authenticating from Shiny" vignette for an example app. ## Authentication vs authorization: Azure Active Directory can be used for two purposes: _authentication_ (verifying that a user is who they claim they are) and _authorization_ (granting a user permission to access a resource). In AAD, a successful authorization process concludes with the granting of an OAuth 2.0 access token, as discussed above. Authentication uses the same process but concludes by granting an ID token, as defined in the OpenID Connect protocol. You can use `get_azure_token` to obtain ID tokens, in addition to access tokens. With AAD v1.0, using an interactive authentication flow (authorization_code or device_code) will return an ID token by default -- you don't have to do anything extra. However, AAD v1.0 will _not_ refresh the ID token when it expires (only the access token). Because of this, specify `use_cache=FALSE` to avoid picking up cached token credentials which may have been refreshed previously. AAD v2.0 does not return an ID token by default, but you can get one by specifying `openid` as a scope. Again, this applies only to interactive authentication. If you only want an ID token, it's recommended to use AAD v2.0. ```r # ID token with AAD v1.0 # if you only want an ID token, set the resource to blank ("") tok <- get_azure_token("", "mytenant", "app_id") extract_token(tok, "id") # ID token with AAD v2.0 tok2 <- get_azure_token(c("openid", "offline_access"), "mytenant", "app_id", version=2) extract_token(tok2, "id") ``` ## Caching AzureAuth caches tokens based on all the inputs to `get_azure_token`, as listed above. It defines its own directory for cached tokens, using the rappdirs package. On recent Windows versions, this will usually be in the location `C:\Users\(username)\AppData\Local\AzureR`. On Linux, it will be in `~/.local/share/AzureR`, and on MacOS, it will be in `~/Library/Application Support/AzureR`. Note that a single directory is used for all tokens, and the working directory is not touched (which significantly lessens the risk of accidentally introducing cached tokens into source control). For reasons of CRAN policy, the first time that AzureAuth is loaded, it will prompt you for permission to create this directory. Unless you have a specific reason otherwise, it's recommended that you allow the directory to be created. Note that most other cloud engineering tools save credentials in this way, including Docker, Kubernetes, and the Azure CLI itself. The prompt only appears in an interactive session; if AzureAuth is loaded in a batch script, the directory is not created if it doesn't already exist. To list all cached tokens on disk, use `list_azure_tokens`. This returns a list of token objects, named according to their MD5 hashes. To load a token from the cache using its MD5 hash, use `load_azure_token`. To delete a cached token, use `delete_azure_token`. This takes the same inputs as `get_azure_token`, or you can supply an MD5 hash via the `hash` argument. To delete _all_ cached tokens, use `clean_token_directory`. ```r # list all tokens list_azure_tokens() # <... list of token objects ...> # delete a token delete_azure_token("myresource", "mytenant", "app_id", password="client_credentials", auth_type="client_credentials") ``` If you want to bypass the cache, specify `use_cache=FALSE` in the call to `get_azure_token`. This will always obtain a new token from AAD, and also prevent it being saved to the cache. ```r get_azure_token("myresource", "mytenant", "app_id", use_cache=FALSE) ``` ## Refreshing A token object can be refreshed by calling its `refresh()` method. If the token's credentials contain a refresh token, this is used; otherwise a new access token is obtained by reauthenticating. In most situations you don't need to worry about this, as the AzureR packages will check if the credentials have expired and automatically refresh them for you. One scenario where you might want to refresh manually is using a token for one resource to obtain a token for another resource. Note that in AAD, a refresh token can be used to obtain an access token for any resource or scope that you have permissions for. Thus, for example, you could use a refresh token issued on a request for `https://management.azure.com` to obtain a new access token for `https://graph.microsoft.com` (assuming you've been granted permission). To obtain an access token for a new resource, change the object's `resource` (for an AAD v1.0 token) or `scope` field (for an AAD v2.0 token) before calling `refresh()`. If you _also_ want to retain the token for the old resource, you should call the `clone()` method first to create a copy. ```r # use a refresh token from one resource to get an access token for another resource tok <- get_azure_token("https://myresource", "mytenant", "app_id") tok2 <- tok$clone() tok2$resource <- "https://anotherresource" tok2$refresh() # same for AAD v2.0 tok <- get_azure_token(c("https://myresource/.default", "offline_access"), "mytenant", "app_id", version=2) tok2 <- tok$clone() tok2$scope <- c("https://anotherresource/.default", "offline_access") tok2$refresh() ``` ## More information For the details on Azure Active Directory, consult the [Microsoft documentation](https://docs.microsoft.com/en-us/azure/active-directory/develop/).
/scratch/gouwar.j/cran-all/cranData/AzureAuth/inst/doc/token.Rmd
--- title: "Common authentication scenarios" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Authentication scenarios} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- The interaction between app registration configuration and requesting a token can be confusing. This vignette outlines some common authentication scenarios that R users might encounter. For each scenario, we briefly describe the necessary settings for your app registration in Azure, and how to request a token using AzureAuth. The [Azure Active Directory documentation](https://docs.microsoft.com/en-au/azure/active-directory/develop/v2-overview) is the authoritative reference. ## Interactive authentication on a local machine This is the simplest scenario: you're using R on your local desktop or laptop, and you want to authenticate to Azure with your user credentials. The authentication flow to use in this case is **authorization_code**. This requires that you have a browser installed on your machine, and it can be called from within R (as is usually the case). You'll also need to have the [httpuv](https://cran.r-project.org/package=httpuv) package: this will be installed if you're a Shiny developer, but otherwise you might have to install it manually. The code to run in your R session is ```r library(AzureAuth) # for an AADv1 token tok <- get_azure_token("https://resource", tenant="yourtenant", app="yourappid") # for an AADv2 token tok <- get_azure_token("https://resource/scope", tenant="yourtenant", app="yourappid", version=2) ``` where `resource[/scope]` is the Azure resource/scope you want a token for, `yourtenant` is your Azure tenant name or GUID, and `yourappid` is your app registration ID. Note that you do _not_ specify your username or password in the `get_azure_token` call. On the server side, the app registration you use should have a **mobile & desktop redirect** of `http://localhost:1410`. See the crop below of the authentication pane for the app in the Azure portal. ![](images/authcode.png) ## Interactive authentication in a remote session This is the scenario where you are using R in a remote terminal session of some kind: RStudio Server, Azure Databricks, or a Linux VM over ssh. Here, you still want to authenticate with your user credentials, but a browser may not be available to use the regular AAD authentication process. The authentication flow to use is **device_code**. This requires that you have a browser available elsewhere (for example, on the local machine from which you're logged in to your remote session). The code to run in your R session is ```r tok <- get_azure_token("resource", tenant="yourtenant", app="yourappid", auth_type="device_code") ``` As before, you do _not_ include your username or password in the `get_azure_token` call. On the server side, the app registration should have the **"Allow public client flows"** setting enabled. ![](images/devicecode.png) It's possible, and indeed desirable, to combine this with the previous redirect URI in the one app registration. This way, you can use the same app ID to authenticate both locally and in a remote terminal. ## Interactive authentication in a webapp This is the scenario where you want to authenticate as part of a webapp, such as a Shiny app. For this scenario, your app registration should have a **webapp redirect** that has the same URL as your app, eg `https://youraccount.shinyapps.io/yourapp` for an app hosted in shinyapps.io. The difference between a mobile & desktop and a webapp redirect is that you supply a **client secret** when authenticating with the latter, but not the former. The client secret is like a password, and helps prevent third parties from hijacking your app registration. The authentication flow to use is **authorization_code**, the same as for a local machine. The Shiny R code that is required is described in more detail in the 'Authenticating from Shiny' vignette, but essentially, the authentication is split into 2 parts: the authorization step in the UI, and then the token acquisition step on the server. ```r tenant <- "yourtenant" app <- "yourappid" redirect <- "https://yourwebsite.example.com/" # authorization: part of UI.r auth_uri <- build_authorization_uri("https://resource", tenant, app, redirect_uri=redirect) redir_js <- sprintf("location.replace(\"%s\");", auth_uri) tags$script(HTML(redir_js)) # token acquisition: part of server.R tok <- get_azure_token("https://resource", tenant, app, password="client_secret", auth_type="authorization_code", authorize_args=list(redirect_uri=redirect), use_cache=FALSE, auth_code=opts$code) ``` Note that the `password` argument holds the client secret for the app registration, _not_ a user password. See the crop below of the certificates & secrets pane for the app registration. ![](images/clientcred.png) Be aware that the client secret is automatically generated by the server and cannot be modified. You can only see it at the time of generation, so make sure you note down its value. ## Non-interactive authentication This is the scenario where you want to authenticate to Azure without a user account present, for example in a deployment pipeline. The authentication flow to use is **client_credentials**. The code to run looks like ```r tok <- get_azure_token("resource", tenant="yourtenant", app="yourccappid", password="client_secret") ``` Here, `yourccappid` is the app ID to use for your pipeline; you should not use the same app registration for this purpose as for interactive logins. The `password` argument is the **client secret** for your app registration, and not a user password. The client secret is set in the same way as for the interactive webapp scenario, above. As an alternative to a client secret, it's possible to authenticate using a TLS certificate (public key). This is considered more secure, but is also more complicated to setup. For more information, see the AAD docs linked previously. ## More information The following pages at the AAD documentation will be helpful if you're new to creating app registrations: - [A step-by-step guide](https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app) to registering an app in the Azure portal. - [How to set permissions for an app](https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-configure-app-access-web-apis). For interactive authentication (authenticating as a user), you want _delegated_ permissions. For non-interactive authentication (authenticating as the application), you want _application_ permissions. - [Restricting your app to a set of users](https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-restrict-your-app-to-a-set-of-users)---if you don't want your app to be accessible to every user in your organisation. Only applies to webapps, not native (desktop & mobile) apps.
/scratch/gouwar.j/cran-all/cranData/AzureAuth/vignettes/scenarios.Rmd
--- title: "Authenticating from Shiny" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Shiny} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- Because a Shiny app has separate UI and server components, the interactive authentication flows require some changes. In particular, the authorization step (logging in to Azure) has to be conducted separately from the token acquisition step. AzureAuth provides the `build_authorization_uri` function to facilitate this separation. You call this function to obtain a URI that you browse to in order to login to Azure. Once you have logged in, Azure will return an authorization code as part of a redirect. Here is a skeleton Shiny app that demonstrates its use. The UI calls `build_authorization_uri`, and then redirects your browser to that location. When you have logged in, the server captures the authorization code and calls `get_azure_token` to obtain the token. Once the token is obtained, `shinyjs` is used to return the URL back to its original state. ```r library(AzureAuth) library(shiny) library(shinyjs) tenant <- "your-tenant-here" app <- "your-app-id-here" # the Azure resource permissions needed # if your app doesn't use any Azure resources (you only want to do authentication), # set the resource to "openid" only resource <- c("https://management.azure.com/.default", "openid") # set this to the site URL of your app once it is deployed # this must also be the redirect for your registered app in Azure Active Directory redirect <- "http://localhost:8100" port <- httr::parse_url(redirect)$port options(shiny.port=if(is.null(port)) 80 else as.numeric(port)) # replace this with your app's regular UI ui <- fluidPage( useShinyjs(), verbatimTextOutput("token") ) ui_func <- function(req) { opts <- parseQueryString(req$QUERY_STRING) if(is.null(opts$code)) { auth_uri <- build_authorization_uri(resource, tenant, app, redirect_uri=redirect, version=2) redir_js <- sprintf("location.replace(\"%s\");", auth_uri) tags$script(HTML(redir_js)) } else ui } # code for cleaning url after authentication clean_url_js <- sprintf( " $(document).ready(function(event) { const nextURL = '%s'; const nextTitle = 'My new page title'; const nextState = { additionalInformation: 'Updated the URL with JS' }; // This will create a new entry in the browser's history, without reloading window.history.pushState(nextState, nextTitle, nextURL); }); ", redirect ) server <- function(input, output, session) { shinyjs::runjs(clean_url_js) opts <- parseQueryString(isolate(session$clientData$url_search)) if(is.null(opts$code)) return() # this assumes your app has a 'public client/native' redirect: # if it is a 'web' redirect, include the client secret as the password argument token <- get_azure_token(resource, tenant, app, auth_type="authorization_code", authorize_args=list(redirect_uri=redirect), version=2, use_cache=FALSE, auth_code=opts$code) output$token <- renderPrint(token) } shinyApp(ui_func, server) ``` Note that this process is only necessary within a web app, and only when using an interactive authentication flow. In a normal R session, or when using the client credentials or resource owner grant flows, you can simply call `get_azure_token` directly.
/scratch/gouwar.j/cran-all/cranData/AzureAuth/vignettes/shiny.Rmd
--- title: "Acquire an OAuth token" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Acquire an OAuth token} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- This is a short introduction to authenticating with Azure Active Directory (AAD) with AzureAuth. ## The `get_azure_token` function The main function in AzureAuth is `get_azure_token`, which obtains an OAuth token from AAD: ```r library(AzureAuth) token <- get_azure_token(resource="myresource", tenant="mytenant", app="app_id", password="mypassword", username="username", certificate="encoded_cert", version=1, ...) ``` The function has the following arguments: - `resource`: The resource or scope for which you want a token. For AAD v1.0, this should be a single URL (eg "[https://example.com](https://example.com)") or a GUID. For AAD v2.0, this should be a vector of scopes (see below). - `tenant`: The AAD tenant. - `app`: The app ID or service principal ID to authenticate with. - `username`, `password`, `certificate`: Your authentication credentials. - `auth_type`: The OAuth authentication method to use. See the next section. - `version`: The version of AAD for which you want a token, either 1 or 2. The default is version 1. Note that the _OAuth scheme_ is always 2.0. Scopes in AAD v2.0 consist of a URL or a GUID, along with a path that designates the scope. If a scope doesn't have a path, `get_azure_token` will append the `/.default` path with a warning. A special scope is `offline_access`, which requests a refresh token from AAD along with the access token: without this, you will have to reauthenticate if you want to refresh the token. ```r # request an AAD v1.0 token for Resource Manager token1 <- get_azure_token("https://management.azure.com/", "mytenant", "app_id") # same request to AAD v2.0, along with a refresh token token2 <- get_azure_token(c("https://management.azure.com/.default", "offline_access"), "mytenant", "app_id", version=2) # requesting multiple scopes in AAD v2.0 (Microsoft Graph) scopes <- c("https://graph.microsoft.com/User.Read", "https://graph.microsoft.com/Files.Read", "https://graph.microsoft.com/Mail.Read", "offline_access") token3 <- get_azure_token(scopes, "mytenant", "app_id", version=2) ``` ## Authentication methods AzureAuth supports the following methods for authenticating with AAD: **authorization_code**, **device_code**, **client_credentials**, **resource_owner** and **on_behalf_of**. 1. Using the **authorization_code** method is a multi-step process. First, `get_azure_token` opens a login window in your browser, where you can enter your AAD credentials. In the background, it loads the [httpuv](https://github.com/rstudio/httpuv) package to listen on a local port. Once you have logged in, the AAD server redirects your browser to a local URL that contains an authorization code. `get_azure_token` retrieves this authorization code and sends it to the AAD access endpoint, which returns the OAuth token.</p> The httpuv package must be installed to use this method, as it requires a web server to listen on the (local) redirect URI. Since it opens a browser to load the AAD authorization page, your machine must also have an Internet browser installed that can be run from inside R. In particular, if you are using a Linux [Data Science Virtual Machine](https://azure.microsoft.com/en-us/services/virtual-machines/data-science-virtual-machines/) in Azure, you may run into difficulties; use one of the other methods instead. ```r # obtain a token using authorization_code # no user credentials needed get_azure_token("myresource", "mytenant", "app_id", auth_type="authorization_code") ``` 2. The **device_code** method is similar in concept to authorization_code, but is meant for situations where you are unable to browse the Internet -- for example if you don't have a browser installed or your computer has input constraints. First, `get_azure_token` contacts the AAD devicecode endpoint, which responds with a login URL and an access code. You then visit the URL and enter the code, possibly using a different computer. Meanwhile, `get_azure_token` polls the AAD access endpoint for a token, which is provided once you have entered the code. ```r # obtain a token using device_code # no user credentials needed get_azure_token("myresource", "mytenant", "app_id", auth_type="device_code") ``` 3. The **client_credentials** method is much simpler than the above methods, requiring only one step. `get_azure_token` contacts the access endpoint, passing it the credentials. This can be either a client secret or a certificate, which you supply in the `password` or `certificate` argument respectively. Once the credentials are verified, the endpoint returns the token. This is the method typically used by service accounts. ```r # obtain a token using client_credentials # supply credentials in password arg get_azure_token("myresource", "mytenant", "app_id", password="client_secret", auth_type="client_credentials") # can also supply a client certificate as a PEM/PFX file... get_azure_token("myresource", "mytenant", "app_id", certificate="mycert.pem", auth_type="client_credentials") # ... or as an object in Azure Key Vault cert <- AzureKeyVault::key_vault("myvault")$certificates$get("mycert") get_azure_token("myresource", "mytenant", "app_id", certificate=cert, auth_type="client_credentials") ``` 4. The **resource_owner** method also requires only one step. In this method, `get_azure_token` passes your (personal) username and password to the AAD access endpoint, which validates your credentials and returns the token. ```r # obtain a token using resource_owner # supply credentials in username and password args get_azure_token("myresource", "mytenant", "app_id", username="myusername", password="mypassword", auth_type="resource_owner") ``` 5. The **on_behalf_of** method is used to authenticate with an Azure resource by passing a token obtained beforehand. It is mostly used by intermediate apps to authenticate for users. In particular, you can use this method to obtain tokens for multiple resources, while only requiring the user to authenticate once. ```r # obtaining multiple tokens: authenticate (interactively) once... tok0 <- get_azure_token("serviceapp_id", "mytenant", "clientapp_id", auth_type="authorization_code") # ...then get tokens for each resource with on_behalf_of tok1 <- get_azure_token("resource1", "mytenant," "serviceapp_id", password="serviceapp_secret", auth_type="on_behalf_of", on_behalf_of=tok0) tok2 <- get_azure_token("resource2", "mytenant," "serviceapp_id", password="serviceapp_secret", auth_type="on_behalf_of", on_behalf_of=tok0) ``` If you don't specify the method, `get_azure_token` makes a best guess based on the presence or absence of the other authentication arguments, and whether httpuv is installed. ```r # this will default to authorization_code if httpuv is installed, and device_code if not get_azure_token("myresource", "mytenant", "app_id") # this will use client_credentials method get_azure_token("myresource", "mytenant", "app_id", password="client_secret") # this will use on_behalf_of method get_azure_token("myresource", "mytenant", "app_id", password="client_secret", on_behalf_of=token) ``` ### Managed identities AzureAuth provides `get_managed_token` to obtain tokens from within a managed identity. This is a VM, service or container in Azure that can authenticate as itself, which removes the need to save secret passwords or certificates. ```r # run this from within an Azure VM or container for which an identity has been setup get_managed_token("myresource") ``` ### Inside a web app Using the interactive flows (authorization_code and device_code) from within a Shiny app requires separating the authorization (logging in to Azure) step from the token acquisition step. For this purpose, AzureAuth provides the `build_authorization_uri` and `get_device_creds` functions. You can use these from within your app to carry out the authorization, and then pass the resulting credentials to `get_azure_token` itself. See the "Authenticating from Shiny" vignette for an example app. ## Authentication vs authorization: Azure Active Directory can be used for two purposes: _authentication_ (verifying that a user is who they claim they are) and _authorization_ (granting a user permission to access a resource). In AAD, a successful authorization process concludes with the granting of an OAuth 2.0 access token, as discussed above. Authentication uses the same process but concludes by granting an ID token, as defined in the OpenID Connect protocol. You can use `get_azure_token` to obtain ID tokens, in addition to access tokens. With AAD v1.0, using an interactive authentication flow (authorization_code or device_code) will return an ID token by default -- you don't have to do anything extra. However, AAD v1.0 will _not_ refresh the ID token when it expires (only the access token). Because of this, specify `use_cache=FALSE` to avoid picking up cached token credentials which may have been refreshed previously. AAD v2.0 does not return an ID token by default, but you can get one by specifying `openid` as a scope. Again, this applies only to interactive authentication. If you only want an ID token, it's recommended to use AAD v2.0. ```r # ID token with AAD v1.0 # if you only want an ID token, set the resource to blank ("") tok <- get_azure_token("", "mytenant", "app_id") extract_token(tok, "id") # ID token with AAD v2.0 tok2 <- get_azure_token(c("openid", "offline_access"), "mytenant", "app_id", version=2) extract_token(tok2, "id") ``` ## Caching AzureAuth caches tokens based on all the inputs to `get_azure_token`, as listed above. It defines its own directory for cached tokens, using the rappdirs package. On recent Windows versions, this will usually be in the location `C:\Users\(username)\AppData\Local\AzureR`. On Linux, it will be in `~/.local/share/AzureR`, and on MacOS, it will be in `~/Library/Application Support/AzureR`. Note that a single directory is used for all tokens, and the working directory is not touched (which significantly lessens the risk of accidentally introducing cached tokens into source control). For reasons of CRAN policy, the first time that AzureAuth is loaded, it will prompt you for permission to create this directory. Unless you have a specific reason otherwise, it's recommended that you allow the directory to be created. Note that most other cloud engineering tools save credentials in this way, including Docker, Kubernetes, and the Azure CLI itself. The prompt only appears in an interactive session; if AzureAuth is loaded in a batch script, the directory is not created if it doesn't already exist. To list all cached tokens on disk, use `list_azure_tokens`. This returns a list of token objects, named according to their MD5 hashes. To load a token from the cache using its MD5 hash, use `load_azure_token`. To delete a cached token, use `delete_azure_token`. This takes the same inputs as `get_azure_token`, or you can supply an MD5 hash via the `hash` argument. To delete _all_ cached tokens, use `clean_token_directory`. ```r # list all tokens list_azure_tokens() # <... list of token objects ...> # delete a token delete_azure_token("myresource", "mytenant", "app_id", password="client_credentials", auth_type="client_credentials") ``` If you want to bypass the cache, specify `use_cache=FALSE` in the call to `get_azure_token`. This will always obtain a new token from AAD, and also prevent it being saved to the cache. ```r get_azure_token("myresource", "mytenant", "app_id", use_cache=FALSE) ``` ## Refreshing A token object can be refreshed by calling its `refresh()` method. If the token's credentials contain a refresh token, this is used; otherwise a new access token is obtained by reauthenticating. In most situations you don't need to worry about this, as the AzureR packages will check if the credentials have expired and automatically refresh them for you. One scenario where you might want to refresh manually is using a token for one resource to obtain a token for another resource. Note that in AAD, a refresh token can be used to obtain an access token for any resource or scope that you have permissions for. Thus, for example, you could use a refresh token issued on a request for `https://management.azure.com` to obtain a new access token for `https://graph.microsoft.com` (assuming you've been granted permission). To obtain an access token for a new resource, change the object's `resource` (for an AAD v1.0 token) or `scope` field (for an AAD v2.0 token) before calling `refresh()`. If you _also_ want to retain the token for the old resource, you should call the `clone()` method first to create a copy. ```r # use a refresh token from one resource to get an access token for another resource tok <- get_azure_token("https://myresource", "mytenant", "app_id") tok2 <- tok$clone() tok2$resource <- "https://anotherresource" tok2$refresh() # same for AAD v2.0 tok <- get_azure_token(c("https://myresource/.default", "offline_access"), "mytenant", "app_id", version=2) tok2 <- tok$clone() tok2$scope <- c("https://anotherresource/.default", "offline_access") tok2$refresh() ``` ## More information For the details on Azure Active Directory, consult the [Microsoft documentation](https://docs.microsoft.com/en-us/azure/active-directory/develop/).
/scratch/gouwar.j/cran-all/cranData/AzureAuth/vignettes/token.Rmd
#' @import AzureRMR NULL globalVariables(c("self", "private")) .onLoad <- function(libname, pkgname) { add_methods() } #' Create, retrieve or delete an Azure Cognitive Service #' #' Methods for the [AzureRMR::az_resource_group] class. #' #' @rdname create_cognitive_service #' @name create_cognitive_service #' @aliases create_cognitive_service get_cognitive_service delete_cognitive_service #' @section Usage: #' ``` #' create_cognitive_service(name, service_type, service_tier, location = self$location, #' subdomain = name, properties = list(), ...) #' get_cognitive_service(name) #' delete_cognitive_service(name, confirm = TRUE, wait = FALSE) #' ``` #' @section Arguments: #' - `name`: The name for the cognitive service resource. #' - `service_type`: The type of service (or "kind") to create. See 'Details' below. #' - `service_tier`: The pricing tier (SKU) for the service. #' - `location`: The Azure location in which to create the service. Defaults to the resource group's location. #' - `subdomain`: The subdomain name to assign to the service; defaults to the resource name. Set this to NULL if you don't want to assign the service a subdomain of its own. #' - `properties`: For `create_cognitive_service`, an optional named list of other properties for the service. #' - `confirm`: For `delete_cognitive_service`, whether to prompt for confirmation before deleting the resource. #' - `wait`: For `delete_cognitive_service`, whether to wait until the deletion is complete before returning. #' #' @section Details: #' These are methods to create, get or delete a cognitive service resource within a resource group. #' #' For `create_cognitive_service`, the type of service created can be one of the following: #' - `CognitiveServices`: multiple service types #' - `ComputerVision`: generic computer vision service #' - `Face`: face recognition #' - `LUIS`: language understanding #' - `CustomVision.Training`: Training endpoint for a custom vision service #' - `CustomVision.Prediction`: Prediction endpoint for a custom vision service #' - `ContentModerator`: Content moderation (text and images) #' - `Text`: text analytics #' - `TextTranslate`: text translation #' #' The possible tiers depend on the type of service created. Consult the Azure Cognitive Service documentation for more information. Usually there will be at least one free tier available. #' #' @section Value: #' For `create_cognitive_service` and `get_cognitive_service`, an object of class `az_cognitive_service`. #' #' @seealso #' [cognitive_endpoint], [call_cognitive_endpoint] #' #' [Azure Cognitive Services documentation](https://docs.microsoft.com/en-us/azure/cognitive-services/), #' [REST API reference](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/) #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("sub_id")$ #' get_resource_group("rgname") #' #' rg$create_cognitive_service("myvisionservice", #' service_type="ComputerVision", service_tier="F0") #' #' rg$create_cognitive_service("mylangservice", #' service_type="LUIS", service_tier="F0") #' #' rg$get_cognitive_service("myvisionservice") #' #' rg$delete_cognitive_service("myvisionservice") #' #'} NULL add_methods <- function() { az_resource_group$set("public", "create_cognitive_service", overwrite=TRUE, function(name, service_type, service_tier, location=self$location, subdomain=name, properties=list(), ...) { if(!is.null(subdomain)) properties <- utils::modifyList(properties, list(customSubDomainName=subdomain)) # resource deployment fails if properties is {} if(is_empty(properties)) properties <- NULL AzureCognitive::az_cognitive_service$new(self$token, self$subscription, self$name, type="Microsoft.CognitiveServices/accounts", name=name, location=location, kind=service_type, sku=list(name=service_tier), properties=properties, ...) }) az_resource_group$set("public", "get_cognitive_service", overwrite=TRUE, function(name) { AzureCognitive::az_cognitive_service$new(self$token, self$subscription, self$name, type="Microsoft.CognitiveServices/accounts", name=name) }) az_resource_group$set("public", "delete_cognitive_service", overwrite=TRUE, function(name, confirm=TRUE, wait=FALSE) { AzureCognitive::az_cognitive_service$new(self$token, self$subscription, self$name, type="Microsoft.CognitiveServices/accounts", name=name, deployed_properties=list(NULL))$delete(confirm=confirm, wait=wait) }) }
/scratch/gouwar.j/cran-all/cranData/AzureCognitive/R/AzureCognitive.R
#' Azure Cognitive Service resource class #' #' Class representing a cognitive service resource, exposing methods for working with it. #' #' @docType class #' @section Methods: #' The following methods are available, in addition to those provided by the [AzureRMR::az_resource] class: #' - `list_keys()`: Return the access keys for this service. #' - `get_endpoint()`: Return the service endpoint, along with an access key. See 'Endpoints' below. #' - `regen_key(key)`: Regenerates (creates a new value for) an access key. The argument `key` can be 1 or 2. #' - `list_service_tiers()`: List the service pricing tiers (SKUs) available for this service. #' #' @section Initialization: #' Initializing a new object of this class can either retrieve an existing service, or create a new service on the host. Generally, the best way to initialize an object is via the `get_cognitive_service` and `create_cognitive_service` methods of the [az_resource_group] class, which handle the details automatically. #' #' @section Endpoints: #' The client-side interaction with a cognitive service is via an _endpoint_. Endpoint interaction in AzureCognitive is implemented using S3 classes. You can create a new endpoint object via the `get_endpoint()` method, or with the standalone `cognitive_endpoint()` function. If you use the latter, you will also have to supply any necessary authentication credentials, eg a subscription key or token. #' #' @seealso #' [cognitive_endpoint], [create_cognitive_service], [get_cognitive_service] #' @examples #' \dontrun{ #' #' # recommended way of creating a new resource: via resource group method #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("sub_id")$ #' get_resource_group("rgname") #' cogsvc <- rg$create_cognitive_service("myvisionservice", #' service_type="ComputerVision", service_tier="F0") #' #' cogsvc$list_service_tiers() #' cogsvc$list_keys() #' cogsvc$regen_key() #' cogsvc$get_endpoint() #' #' } #' @export az_cognitive_service <- R6::R6Class("az_cognitive_service", inherit=AzureRMR::az_resource, public=list( list_keys=function() { unlist(private$res_op("listKeys", http_verb="POST")) }, regen_key=function(key=1) { body <- list(keyName=paste0("Key", key)) unlist(private$res_op("regenerateKey", body=body, http_verb="POST")) }, list_service_tiers=function() { private$res_op("skus")$value }, get_endpoint=function(key=self$list_keys()[1]) { cognitive_endpoint(self$properties$endpoint, self$kind, key=key) } ))
/scratch/gouwar.j/cran-all/cranData/AzureCognitive/R/az_cogsvc.R
#' Object representing an Azure Cognitive Service endpoint #' #' @param url The URL of the endpoint. #' @param service_type What type (or kind) of service the endpoint provides. See below for the services that AzureCognitive currently recognises. #' @param key The subscription key (single- or multi-service) to use to authenticate with the endpoint. #' @param aad_token An Azure Active Directory (AAD) OAuth token, as an alternative to a key for the services that allow AAD authentication. #' @param cognitive_token A Cognitive Service token, as another alternative to a key for the services that accept it. #' @param auth_header The name of the HTTP request header for authentication. Only used if a subscription key is supplied. #' @details #' Currently, `cognitive_endpoint` recognises the following service types: #' - `CognitiveServices`: multiple service types #' - `ComputerVision`: generic computer vision service #' - `Face`: face recognition #' - `LUIS`: language understanding #' - `CustomVision.Training`: Training endpoint for a custom vision service #' - `CustomVision.Prediction`: Prediction endpoint for a custom vision service #' - `ContentModerator`: Content moderation (text and images) #' - `Text`: text analytics #' - `TextTranslate`: text translation #' #' @return #' An object inheriting from class `cognitive_endpoint`, that can be used to communicate with the REST endpoint. The subclass of the object indicates the type of service provided. #' #' @seealso #' [call_cognitive_endpoint], [create_cognitive_service], [get_cognitive_service] #' @examples #' \dontrun{ #' #' cognitive_endpoint("https://myvisionservice.api.cognitive.azure.com", #' service_type="Computervision", key="key") #' #' cognitive_endpoint("https://mylangservice.api.cognitive.azure.com", #' service_type="LUIS", key="key") #' #' # authenticating with AAD #' token <- AzureAuth::get_azure_token("https://cognitiveservices.azure.com", #' tenant="mytenant", app="app_id", password="password") #' cognitive_endpoint("https://myvisionservice.api.cognitive.azure.com", #' service_type="Computervision", aad_token=token) #' #' } #' @export cognitive_endpoint <- function(url, service_type, key=NULL, aad_token=NULL, cognitive_token=NULL, auth_header="ocp-apim-subscription-key") { service_type <- normalize_cognitive_type(service_type) url <- httr::parse_url(url) url$path <- get_api_path(service_type) object <- list( url=url, key=unname(key), aad_token=aad_token, cognitive_token=cognitive_token, auth_header=auth_header ) class(object) <- c(paste0(service_type, "_endpoint"), "cognitive_endpoint") object } #' @export print.cognitive_endpoint <- function(x, ...) { cat("Azure Cognitive Service endpoint\n") cat("Service type:", class(x)[1], "\n") cat("Endpoint URL:", httr::build_url(x$url), "\n") invisible(x) } #' Call a Cognitive Service REST endpoint #' #' @param endpoint An object of class `cognitive_endpoint`. #' @param operation The operation to perform. #' @param options Any query parameters that the operation takes. #' @param headers Any optional HTTP headers to include in the REST call. Note that `call_cognitive_endpoint` will handle authentication details automatically, so don't include them here. #' @param body The body of the HTTP request for the REST call. #' @param encode The encoding (really content-type) for the body. See the `encode` argument for [`httr::POST`]. The default value of NULL will use `raw` encoding if the body is a raw vector, and `json` encoding for anything else. #' @param http_verb The HTTP verb for the REST call. #' @param http_status_handler How to handle a failed REST call. `stop`, `warn` and `message` will call the corresponding `*_for_status` handler in the httr package; `pass` will return the raw response object unchanged. The last one is mostly intended for debugging purposes. #' @param ... Further arguments passed to lower-level functions. For the default method, these are passed to [`httr::content`]; in particular, you can convert a structured JSON response into a data frame by specifying `simplifyDataFrame=TRUE`. #' @details #' This function does the low-level work of constructing a HTTP request and then calling the REST endpoint. It is meant to be used by other packages that provide higher-level views of the service functionality. #' #' @return #' For a successful REST call, the contents of the response. This will usually be a list, obtained by translating the raw JSON body into R. If the call returns a non-success HTTP status code, based on the `http_status_handler` argument. #' #' @seealso #' [cognitive_endpoint], [create_cognitive_service], [get_cognitive_service] #' @examples #' \dontrun{ #' #' endp <- cognitive_endpoint("https://myvisionservice.api.cognitive.azure.com", #' service_type="Computervision", key="key") #' #' # analyze an online image #' img_link <- "https://news.microsoft.com/uploads/2014/09/billg1_print.jpg" #' call_cognitive_endpoint(endp, #' operation="analyze", #' body=list(url=img_link), #' options=list(details="celebrities"), #' http_verb="POST") #' #' # analyze an image on the local machine #' img_raw <- readBin("image.jpg", "raw", file.info("image.jpg")$size) #' call_cognitive_endpoint(endp, #' operation="analyze", #' body=img_raw, #' encode="raw", #' http_verb="POST") #' #' } #' @export call_cognitive_endpoint <- function(endpoint, ...) { UseMethod("call_cognitive_endpoint") } #' @rdname call_cognitive_endpoint #' @export call_cognitive_endpoint.cognitive_endpoint <- function(endpoint, operation, options=list(), headers=list(), body=NULL, encode=NULL, ..., http_verb=c("GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"), http_status_handler=c("stop", "warn", "message", "pass")) { url <- endpoint$url url$path <- file.path(url$path, operation) url$query <- options if(is.null(encode)) # auto-detect from body { if(is.raw(body)) { encode <- "raw" headers$`content-type` <- "application/octet-stream" } else if(!is.null(body)) { body <- jsonlite::toJSON(body, auto_unbox=TRUE, digits=22, null="null") encode <- "raw" headers$`content-type` <- "application/json" } } else if(encode == "json") { # manually convert to json to avoid issues with nulls body <- jsonlite::toJSON(body, auto_unbox=TRUE, digits=22, null="null") encode <- "raw" headers$`content-type` <- "application/json" } else if(encode == "raw" && is.null(headers$`content-type`)) headers$`content-type` <- "application/octet-stream" headers <- add_cognitive_auth(endpoint, headers) verb <- match.arg(http_verb) res <- httr::VERB(verb, url, headers, body=body, encode=encode) process_cognitive_response(res, match.arg(http_status_handler), ...) } add_cognitive_auth <- function(endpoint, headers, auth_header) { if(!is.null(endpoint$key)) headers[[endpoint$auth_header]] <- unname(endpoint$key) else if(!is.null(endpoint$aad_token)) { token <- endpoint$aad_token if(inherits(token, c("AzureToken", "Token")) && !token$validate()) token$refresh() headers[["Authorization"]] <- paste("Bearer", AzureAuth::extract_jwt(token)) } else if(!is_empty(endpoint$cognitive_token)) headers[["Authorization"]] <- paste("Bearer", endpoint$cognitive_token) else stop("No supported authentication method found", call.=FALSE) do.call(httr::add_headers, headers) } process_cognitive_response <- function(response, handler, ...) { if(handler != "pass") { handler <- get(paste0(handler, "_for_status"), getNamespace("httr")) handler(response, paste0("complete Cognitive Services operation. Message:\n", sub("\\.$", "", cognitive_error_message(httr::content(response))))) # only return parsed content if json if(is_json_content(httr::headers(response))) httr::content(response, ...) else response$content } else response } cognitive_error_message <- function(cont) { if(is.raw(cont)) cont <- jsonlite::fromJSON(rawToChar(cont)) else if(is.character(cont)) cont <- jsonlite::fromJSON(cont) msg <- if(is.list(cont)) { if(is.character(cont$message)) cont$message else if(is.list(cont$error) && is.character(cont$error$message)) cont$error$message else "" } else "" paste0(strwrap(msg), collapse="\n") } get_api_path <- function(type) { switch(type, computervision="vision/v2.0", face="face/v1.0", luis="luis/v2.0", customvision=, customvision_training=, customvision_prediction="customvision/v3.0", contentmoderator="contentmoderator/moderate/v1.0", text="text/analytics/v2.0", cognitiveservices=, texttranslation="", stop("Unknown cognitive service", call.=FALSE) ) } normalize_cognitive_type <- function(type) { tolower(gsub("[. ]", "_", type)) } is_json_content <- function(headers) { cont_type <- which(tolower(names(headers)) == "content-type") !is_empty(cont_type) && grepl("json", tolower(headers[[cont_type]])) }
/scratch/gouwar.j/cran-all/cranData/AzureCognitive/R/endpoint.R
#' Obtain authentication token for a cognitive service #' #' @param key The subscription key for the service. #' @param region The Azure region where the service is located. #' @param token_url Optionally, the URL for the token endpoint. #' @export get_cognitive_token <- function(key, region="global", token_url=NULL) { if(is.null(token_url)) { token_url <- if(region != "global") sprintf("https://%s.api.cognitive.microsoft.com/sts/v1.0/issueToken", normalize_region(region)) else "https://api.cognitive.microsoft.com/sts/v1.0/issueToken" } hdrs <- httr::add_headers(`Ocp-Apim-Subscription-Key`=unname(key)) res <- httr::POST(token_url, encode="form", hdrs) rawToChar(process_cognitive_response(res, "stop")) } normalize_region <- function(region) { tolower(gsub(" ", "", region)) }
/scratch/gouwar.j/cran-all/cranData/AzureCognitive/R/get_cognitive_token.R
--- title: "Introduction to AzureCognitive" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- AzureCognitive is a package for working with [Azure Cognitive Services](https://azure.microsoft.com/en-us/services/cognitive-services/). Both a Resource Manager interface and a client interface to the Cognitive Services REST API are provided. The aim is to provide a foundation that can be built on by other packages that will support specific services (Computer Vision, LUIS, etc). ## Resource Manager interface AzureCognitive extends the class framework provided by [AzureRMR](https://github.com/Azure/AzureRMR) to support Cognitive Services. You can create, retrieve, update, and delete cognitive service resources by calling the corresponding methods for a resource group. ```r az <- AzureRMR::get_azure_login() sub <- az$get_subscription("sub_id") rg <- sub$get_resource_group("rgname") # create a new Computer Vision service rg$create_cognitive_service("myvisionservice", service_type="ComputerVision", service_tier="S1") # retrieve it cogsvc <- rg$get_cognitive_service("myvisionservice") # list subscription keys cogsvc$list_keys() ``` ## Client interface AzureCognitive implements basic functionality for communicating with the Cognitive Services REST API. The main functions are `cognitive_endpoint`, which creates an object representing the endpoint, and `call_cognitive_endpoint` to perform the REST calls. ```r # getting the endpoint from the resource object endp <- cogsvc$get_endpoint() # or standalone (must provide subscription key or other means of authentication) endp <- cognitive_endpoint("https://myvisionservice.cognitiveservices.azure.com/", service_type="ComputerVision", key="key") # analyze an image img_link <- "https://news.microsoft.com/uploads/2014/09/billg1_print.jpg" call_cognitive_endpoint(endp, operation="analyze", body=list(url=img_link), options=list(details="celebrities"), http_verb="POST") ``` The latter call produces output like that below (truncated for brevity). ``` $categories $categories[[1]] $categories[[1]]$name [1] "people_" $categories[[1]]$score [1] 0.953125 $categories[[1]]$detail $categories[[1]]$detail$celebrities $categories[[1]]$detail$celebrities[[1]] $categories[[1]]$detail$celebrities[[1]]$name [1] "Bill Gates" $categories[[1]]$detail$celebrities[[1]]$confidence [1] 0.9999552 ```
/scratch/gouwar.j/cran-all/cranData/AzureCognitive/inst/doc/intro.Rmd
--- title: "Introduction to AzureCognitive" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- AzureCognitive is a package for working with [Azure Cognitive Services](https://azure.microsoft.com/en-us/services/cognitive-services/). Both a Resource Manager interface and a client interface to the Cognitive Services REST API are provided. The aim is to provide a foundation that can be built on by other packages that will support specific services (Computer Vision, LUIS, etc). ## Resource Manager interface AzureCognitive extends the class framework provided by [AzureRMR](https://github.com/Azure/AzureRMR) to support Cognitive Services. You can create, retrieve, update, and delete cognitive service resources by calling the corresponding methods for a resource group. ```r az <- AzureRMR::get_azure_login() sub <- az$get_subscription("sub_id") rg <- sub$get_resource_group("rgname") # create a new Computer Vision service rg$create_cognitive_service("myvisionservice", service_type="ComputerVision", service_tier="S1") # retrieve it cogsvc <- rg$get_cognitive_service("myvisionservice") # list subscription keys cogsvc$list_keys() ``` ## Client interface AzureCognitive implements basic functionality for communicating with the Cognitive Services REST API. The main functions are `cognitive_endpoint`, which creates an object representing the endpoint, and `call_cognitive_endpoint` to perform the REST calls. ```r # getting the endpoint from the resource object endp <- cogsvc$get_endpoint() # or standalone (must provide subscription key or other means of authentication) endp <- cognitive_endpoint("https://myvisionservice.cognitiveservices.azure.com/", service_type="ComputerVision", key="key") # analyze an image img_link <- "https://news.microsoft.com/uploads/2014/09/billg1_print.jpg" call_cognitive_endpoint(endp, operation="analyze", body=list(url=img_link), options=list(details="celebrities"), http_verb="POST") ``` The latter call produces output like that below (truncated for brevity). ``` $categories $categories[[1]] $categories[[1]]$name [1] "people_" $categories[[1]]$score [1] 0.953125 $categories[[1]]$detail $categories[[1]]$detail$celebrities $categories[[1]]$detail$celebrities[[1]] $categories[[1]]$detail$celebrities[[1]]$name [1] "Bill Gates" $categories[[1]]$detail$celebrities[[1]]$confidence [1] 0.9999552 ```
/scratch/gouwar.j/cran-all/cranData/AzureCognitive/vignettes/intro.Rmd
#' @import AzureRMR #' @importFrom utils tail NULL .AzureContainers <- new.env() .az_cli_app_id <- "04b07795-8ddb-461a-bbee-02f9e1bf7b46" globalVariables("self", "AzureContainers") .onLoad <- function(libname, pkgname) { # find docker, kubectl and helm binaries .AzureContainers$docker <- Sys.which("docker") .AzureContainers$dockercompose <- Sys.which("docker-compose") .AzureContainers$kubectl <- Sys.which("kubectl") .AzureContainers$helm <- Sys.which("helm") ## add methods to AzureRMR resource group and subscription classes add_acr_methods() add_aks_methods() add_aci_methods() add_vmsize_methods() } .onAttach <- function(libname, pkgname) { if(.AzureContainers$docker != "") packageStartupMessage("Using docker binary ", .AzureContainers$docker) if(.AzureContainers$dockercompose != "") packageStartupMessage("Using docker-compose binary ", .AzureContainers$dockercompose) if(.AzureContainers$kubectl != "") packageStartupMessage("Using kubectl binary ", .AzureContainers$kubectl) if(.AzureContainers$helm != "") packageStartupMessage("Using helm binary ", .AzureContainers$helm) if(.AzureContainers$docker == "") packageStartupMessage("NOTE: docker binary not found") if(.AzureContainers$dockercompose == "") packageStartupMessage("NOTE: docker-compose binary not found") if(.AzureContainers$kubectl == "") packageStartupMessage("NOTE: kubectl binary not found") if(.AzureContainers$helm == "") packageStartupMessage("NOTE: helm binary not found") invisible(NULL) }
/scratch/gouwar.j/cran-all/cranData/AzureContainers/R/AzureContainers.R
#' Create Azure Container Instance (ACI) #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname create_aci #' @name create_aci #' @aliases create_aci #' @section Usage: #' ``` #' create_aci(name, location = self$location, #' container = name, image, #' registry_creds = list(), #' cores = 1, memory = 8, #' os = c("Linux", "Windows"), #' command = list(), env_vars = list(), #' ports = aci_ports(), dns_name = name, public_ip = TRUE, #' restart = c("Always", "OnFailure", "Never"), managed_identity = TRUE, #' ...) #' ``` #' @section Arguments: #' - `name`: The name of the ACI service. #' - `location`: The location/region in which to create the ACI service. Defaults to this resource group's location. #' - `container`: The name of the running container. #' - `image`: The name of the image to run. #' - `registry_creds`: Docker registry authentication credentials, if the image is stored in a private registry. See 'Details'. #' - `cores`: The number of CPU cores for the instance. #' - `memory`: The memory size in GB for the instance. #' - `os`: The operating system to run in the instance. #' - `command`: A list of commands to run in the instance. This is similar to the `--entrypoint` commandline argument to `docker run`; see [here](https://docs.microsoft.com/en-us/azure/container-instances/container-instances-start-command) for some examples. #' - `env_vars`: A list of name-value pairs to set as environment variables in the instance. #' - `secure_env_vars`: A list of name-value pairs to set as _secure_ environment variables in the instance. The values of these variables are not visible in the container's properties, eg when viewed in the Azure portal or via the CLI. #' - `ports`: The network ports to open. By default, opens ports 80 and 443. See 'Details'. #' - `dns_name`: The domain name prefix for the instance. Only takes effect if `public_ip=TRUE`. #' - `public_ip`: Whether the instance should be publicly accessible. #' - `restart`: Whether to restart the instance should an event occur. #' - `managed_identity`: Whether to assign the container instance a managed identity. #' - `...`: Other named arguments to pass to the [az_resource] initialization function. #' #' @section Details: #' An ACI resource is a running container hosted in Azure. See the [documentation for the resource](https://docs.microsoft.com/en-us/azure/container-instances/) for more information. Currently ACI only supports a single image in an instance. #' #' To supply the registry authentication credentials, the `registry_creds` argument should contain either an [ACR][acr] object, a [docker_registry] object, or the result of a call to the [aci_creds] function. #' #' The ports to open should be obtained by calling the [aci_ports] function. This takes a vector of port numbers as well as the protocol (TCP or UDP) for each port. #' #' @section Value: #' An object of class `az_container_instance` representing the instance. #' #' @seealso #' [get_aci], [delete_aci], [list_acis] #' #' [az_container_instance] #' #' [ACI documentation](https://docs.microsoft.com/en-us/azure/container-instances/) and #' [API reference](https://docs.microsoft.com/en-us/rest/api/container-instances/) #' #' [Docker commandline reference](https://docs.docker.com/engine/reference/commandline/cli/) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' # get the ACR resource that contains the image #' myacr <- rg$get_acr("myregistry", as_admin=TRUE) #' #' rg$create_aci("mycontainer", #' image="myregistry.azurecr.io/myimage:latest", #' registry_creds=myacr) #' #' } NULL #' Get Azure Container Instance (ACI) #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname get_aci #' @name get_aci #' @aliases get_aci list_acis #' #' @section Usage: #' ``` #' get_aci(name) #' list_acis() #' ``` #' @section Arguments: #' - `name`: For `get_aci()`, the name of the container instance resource. #' #' @section Details: #' The `AzureRMR::az_resource_group` class has both `get_aci()` and `list_acis()` methods, while the `AzureRMR::az_subscription` class only has the latter. #' #' @section Value: #' For `get_aci()`, an object of class `az_container_instance` representing the instance resource. #' #' For `list_acis()`, a list of such objects. #' #' @seealso #' [create_aci], [delete_aci] #' #' [az_container_instance] #' #' [ACI documentation](https://docs.microsoft.com/en-us/azure/container-instances/) and #' [API reference](https://docs.microsoft.com/en-us/rest/api/container-instances/) #' #' [Docker commandline reference](https://docs.docker.com/engine/reference/commandline/cli/) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' rg$get_aci("mycontainer") #' #' } NULL #' Delete an Azure Container Instance (ACI) #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname delete_aci #' @name delete_aci #' @aliases delete_aci #' #' @section Usage: #' ``` #' delete_aci(name, confirm=TRUE, wait=FALSE) #' ``` #' @section Arguments: #' - `name`: The name of the container instance. #' - `confirm`: Whether to ask for confirmation before deleting. #' - `wait`: Whether to wait until the deletion is complete. #' #' @section Value: #' NULL on successful deletion. #' #' @seealso #' [create_aci], [get_aci] #' #' [az_container_instance] #' #' [ACI documentation](https://docs.microsoft.com/en-us/azure/container-instances/) and #' [API reference](https://docs.microsoft.com/en-us/rest/api/container-instances/) #' #' [Docker commandline reference](https://docs.docker.com/engine/reference/commandline/cli/) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' rg$delete_aci("mycontainer") #' #' } NULL add_aci_methods <- function() { az_resource_group$set("public", "create_aci", overwrite=TRUE, function(name, location=self$location, container=name, image, registry_creds=list(), cores=1, memory=8, os=c("Linux", "Windows"), command=list(), env_vars=list(), secure_env_vars=list(), ports=aci_ports(), dns_name=name, public_ip=TRUE, restart=c("Always", "OnFailure", "Never"), managed_identity=TRUE, ..., wait=TRUE) { as_name_value_pairs <- function(vars, securevars) { c( lapply(seq_along(vars), function(i) list(name=names(vars)[i], value=vars[[i]])), lapply(seq_along(securevars), function(i) list(name=names(securevars)[i], secureValue=securevars[[i]])) ) } containers <- list( name=container, properties=list( image=image, command=I(command), environmentVariables=as_name_value_pairs(env_vars, secure_env_vars), resources=list(requests=list(cpu=cores, memoryInGB=memory)), ports=ports ) ) props <- list( containers=list(containers), restartPolicy=match.arg(restart), osType=match.arg(os) ) if(!is_empty(registry_creds)) props$imageRegistryCredentials <- get_aci_credentials_list(registry_creds) if(public_ip) props$ipAddress <- list(type="public", dnsNameLabel=dns_name, ports=ports) identity <- if(managed_identity) list(type="systemAssigned") else NULL AzureContainers::aci$new(self$token, self$subscription, self$name, type="Microsoft.containerInstance/containerGroups", name=name, location=location, properties=props, identity=identity, ..., wait=wait) }) az_resource_group$set("public", "get_aci", overwrite=TRUE, function(name) { AzureContainers::aci$new(self$token, self$subscription, self$name, type="Microsoft.containerInstance/containerGroups", name=name) }) az_resource_group$set("public", "delete_aci", overwrite=TRUE, function(name, confirm=TRUE, wait=FALSE) { self$get_aci(name)$delete(confirm=confirm, wait=wait) }) az_resource_group$set("public", "list_acis", overwrite=TRUE, function() { provider <- "Microsoft.ContainerInstance" path <- "containerGroups" api_version <- az_subscription$ new(self$token, self$subscription)$ get_provider_api_version(provider, path) op <- file.path("resourceGroups", self$name, "providers", provider, path) cont <- call_azure_rm(self$token, self$subscription, op, api_version=api_version) lst <- lapply(cont$value, function(parms) AzureContainers::aci$new(self$token, self$subscription, deployed_properties=parms)) # keep going until paging is complete while(!is_empty(cont$nextLink)) { cont <- call_azure_url(self$token, cont$nextLink) lst <- lapply(cont$value, function(parms) AzureContainers::aci$new(self$token, self$subscription, deployed_properties=parms)) } named_list(lst) }) az_subscription$set("public", "list_acis", overwrite=TRUE, function() { provider <- "Microsoft.ContainerInstance" path <- "containerGroups" api_version <- self$get_provider_api_version(provider, path) op <- file.path("providers", provider, path) cont <- call_azure_rm(self$token, self$id, op, api_version=api_version) lst <- lapply(cont$value, function(parms) AzureContainers::aci$new(self$token, self$id, deployed_properties=parms)) # keep going until paging is complete while(!is_empty(cont$nextLink)) { cont <- call_azure_url(self$token, cont$nextLink) lst <- lapply(cont$value, function(parms) AzureContainers::aci$new(self$token, self$id, deployed_properties=parms)) } named_list(lst) }) }
/scratch/gouwar.j/cran-all/cranData/AzureContainers/R/add_aci_methods.R
#' Create Azure Container Registry (ACR) #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname create_acr #' @name create_acr #' @aliases create_acr #' @section Usage: #' ``` #' create_acr(name, location = self$location, #' admin_user_enabled = TRUE, sku = "Standard", ...) #' ``` #' @section Arguments: #' - `name`: The name of the container registry. #' - `location`: The location/region in which to create the container registry. Defaults to this resource group's location. #' - `admin_user_enabled`: Whether to enable the Admin user. Currently this must be `TRUE` for ACI to pull from the registry. #' - `sku`: Either "Basic", "Standard" (the default) or "Premium". #' - `wait`: Whether to wait until the ACR resource provisioning is complete. #' - `...`: Other named arguments to pass to the [az_resource] initialization function. #' #' @section Details: #' An ACR resource is a Docker registry hosted in Azure. See the [documentation for the resource](https://docs.microsoft.com/en-us/azure/container-registry/) for more information. To work with the registry (transfer images, retag images, etc) see the [documentation for the registry endpoint][docker_registry]. #' #' @section Value: #' An object of class `az_container_registry` representing the registry resource. #' #' @seealso #' [get_acr], [delete_acr], [list_acrs] #' #' [az_container_registry] #' #' [docker_registry] for the registry endpoint #' #' [ACR documentation](https://docs.microsoft.com/en-us/azure/container-registry/) and #' [API reference](https://docs.microsoft.com/en-us/rest/api/containerregistry/registries) #' #' [Docker registry API](https://docs.docker.com/registry/spec/api/) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' rg$create_acr("myregistry") #' #' } NULL #' Get Azure Container Registry (ACR) #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname get_acr #' @name get_acr #' @aliases get_acr list_acrs #' #' @section Usage: #' ``` #' get_acr(name) #' list_acrs() #' ``` #' @section Arguments: #' - `name`: For `get_acr()`, the name of the container registry resource. #' #' @section Details: #' The `AzureRMR::az_resource_group` class has both `get_acr()` and `list_acrs()` methods, while the `AzureRMR::az_subscription` class only has the latter. #' #' @section Value: #' For `get_acr()`, an object of class `az_container_registry` representing the registry resource. #' #' For `list_acrs()`, a list of such objects. #' #' @seealso #' [create_acr], [delete_acr] #' #' [az_container_registry] #' #' [docker_registry] for the registry endpoint #' #' [ACR documentation](https://docs.microsoft.com/en-us/azure/container-registry/) and #' [API reference](https://docs.microsoft.com/en-us/rest/api/containerregistry/registries) #' #' [Docker registry API](https://docs.docker.com/registry/spec/api/) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' rg$get_acr("myregistry") #' #' } NULL #' Delete an Azure Container Registry (ACR) #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname delete_acr #' @name delete_acr #' @aliases delete_acr #' #' @section Usage: #' ``` #' delete_acr(name, confirm=TRUE, wait=FALSE) #' ``` #' @section Arguments: #' - `name`: The name of the container registry. #' - `confirm`: Whether to ask for confirmation before deleting. #' - `wait`: Whether to wait until the deletion is complete. #' #' @section Value: #' NULL on successful deletion. #' #' @seealso #' [create_acr], [get_acr] #' #' [az_container_registry] #' #' [docker_registry] for the registry endpoint #' #' [ACR documentation](https://docs.microsoft.com/en-us/azure/container-registry/) and #' [API reference](https://docs.microsoft.com/en-us/rest/api/containerregistry/registries) #' #' [Docker registry API](https://docs.docker.com/registry/spec/api/) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' rg$delete_acr("myregistry") #' #' } NULL add_acr_methods <- function() { az_resource_group$set("public", "create_acr", overwrite=TRUE, function(name, location=self$location, admin_user_enabled=TRUE, sku="Standard", ..., wait=TRUE) { AzureContainers::acr$new(self$token, self$subscription, self$name, type="Microsoft.containerRegistry/registries", name=name, location=location, properties=list(adminUserEnabled=admin_user_enabled), sku=list(name=sku, tier=sku), ..., wait=wait) }) az_resource_group$set("public", "get_acr", overwrite=TRUE, function(name) { AzureContainers::acr$new(self$token, self$subscription, self$name, type="Microsoft.containerRegistry/registries", name=name) }) az_resource_group$set("public", "delete_acr", overwrite=TRUE, function(name, confirm=TRUE, wait=FALSE) { self$get_acr(name)$delete(confirm=confirm, wait=wait) }) az_resource_group$set("public", "list_acrs", overwrite=TRUE, function() { provider <- "Microsoft.ContainerRegistry" path <- "registries" api_version <- az_subscription$ new(self$token, self$subscription)$ get_provider_api_version(provider, path) op <- file.path("resourceGroups", self$name, "providers", provider, path) cont <- call_azure_rm(self$token, self$subscription, op, api_version=api_version) lst <- lapply(cont$value, function(parms) AzureContainers::acr$new(self$token, self$subscription, deployed_properties=parms)) # keep going until paging is complete while(!is_empty(cont$nextLink)) { cont <- call_azure_url(self$token, cont$nextLink) lst <- lapply(cont$value, function(parms) AzureContainers::acr$new(self$token, self$subscription, deployed_properties=parms)) } named_list(lst) }) az_subscription$set("public", "list_acrs", overwrite=TRUE, function() { provider <- "Microsoft.ContainerRegistry" path <- "registries" api_version <- self$get_provider_api_version(provider, path) op <- file.path("providers", provider, path) cont <- call_azure_rm(self$token, self$id, op, api_version=api_version) lst <- lapply(cont$value, function(parms) AzureContainers::acr$new(self$token, self$id, deployed_properties=parms)) # keep going until paging is complete while(!is_empty(cont$nextLink)) { cont <- call_azure_url(self$token, cont$nextLink) lst <- lapply(cont$value, function(parms) AzureContainers::acr$new(self$token, self$id, deployed_properties=parms)) } named_list(lst) }) }
/scratch/gouwar.j/cran-all/cranData/AzureContainers/R/add_acr_methods.R
#' Create Azure Kubernetes Service (AKS) #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname create_aks #' @name create_aks #' @aliases create_aks #' @section Usage: #' ``` #' create_aks(name, location = self$location, #' dns_prefix = name, kubernetes_version = NULL, #' enable_rbac = FALSE, agent_pools = agent_pool("pool1", 3), #' login_user = "", login_passkey = "", #' cluster_service_principal = NULL, managed_identity = TRUE, #' private_cluster = FALSE, #' properties = list(), ..., wait = TRUE) #' ``` #' @section Arguments: #' - `name`: The name of the Kubernetes service. #' - `location`: The location/region in which to create the service. Defaults to this resource group's location. #' - `dns_prefix`: The domain name prefix to use for the cluster endpoint. The actual domain name will start with this argument, followed by a string of pseudorandom characters. #' - `kubernetes_version`: The Kubernetes version to use. If not specified, uses the most recent version of Kubernetes available. #' - `enable_rbac`: Whether to enable Kubernetes role-based access controls (which is distinct from Azure AD RBAC). #' - `agent_pools`: The pool specification(s) for the cluster. See 'Details'. #' - `login_user,login_passkey`: Optionally, a login username and public key (on Linux). Specify these if you want to be able to ssh into the cluster nodes. #' - `cluster_service_principal`: The service principal that AKS will use to manage the cluster resources. This should be a list, with the first component being the client ID and the second the client secret. If not supplied, a new service principal will be created (requires an interactive session). Ignored if `managed_identity=TRUE`, which is the default. #' - `managed_identity`: Whether the cluster should have a managed identity assigned to it. If `FALSE`, a service principal will be used to manage the cluster's resources; see 'Details' below. #' - `private_cluster`: Whether this cluster is private (not visible from the public Internet). A private cluster is accessible only to hosts on its virtual network. #' - `properties`: A named list of further Kubernetes-specific properties to pass to the initialization function. #' - `wait`: Whether to wait until the AKS resource provisioning is complete. Note that provisioning a Kubernetes cluster can take several minutes. #' - `...`: Other named arguments to pass to the initialization function. #' #' @section Details: #' An AKS resource is a Kubernetes cluster hosted in Azure. See the [documentation for the resource][aks] for more information. To work with the cluster (deploy images, define and start services, etc) see the [documentation for the cluster endpoint][kubernetes_cluster]. #' #' The nodes for an AKS cluster are organised into _agent pools_, also known as _node pools_, which are homogenous groups of virtual machines. To specify the details for a single agent pool, use the `agent_pool` function, which returns an S3 object of that class. To specify the details for multiple pools, you can supply a list of such objects, or a single call to the `aks_pools` function; see the examples below. Note that `aks_pools` is older, and does not support all the possible parameters for an agent pool. #' #' Of the agent pools in a cluster, at least one must be a _system pool_, which is used to host critical system pods such as CoreDNS and tunnelfront. If you specify more than one pool, the first pool will be treated as the system pool. Note that there are certain [extra requirements](https://docs.microsoft.com/en-us/azure/aks/use-system-pools) for the system pool. #' #' An AKS cluster requires an identity to manage the low-level resources it uses, such as virtual machines and networks. The default and recommended method is to use a _managed identity_, in which all the details of this process are handled by AKS. In AzureContainers version 1.2.1 and older, a _service principal_ was used instead, which is an older and less automated method. By setting `managed_identity=FALSE`, you can continue using a service principal instead of a managed identity. #' #' One thing to be aware of with service principals is that they have a secret password that will expire eventually. By default, the password for a newly-created service principal will expire after one year. You should run the `update_service_password` method of the AKS object to reset/update the password before it expires. #' #' @section Value: #' An object of class `az_kubernetes_service` representing the service. #' #' @seealso #' [get_aks], [delete_aks], [list_aks], [agent_pool], [aks_pools] #' #' [az_kubernetes_service] #' #' [kubernetes_cluster] for the cluster endpoint #' #' [AKS documentation](https://docs.microsoft.com/en-us/azure/aks/) and #' [API reference](https://docs.microsoft.com/en-us/rest/api/aks/) #' #' [Kubernetes reference](https://kubernetes.io/docs/reference/) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' rg$create_aks("mycluster", agent_pools=agent_pool("pool1", 5)) #' #' # GPU-enabled cluster #' rg$create_aks("mygpucluster", agent_pools=agent_pool("pool1", 5, size="Standard_NC6s_v3")) #' #' # multiple agent pools #' rg$create_aks("mycluster", agent_pools=list( #' agent_pool("pool1", 2), #' agent_pool("pool2", 3, size="Standard_NC6s_v3") #' )) #' #' # deprecated alternative for multiple pools #' rg$create_aks("mycluster", #' agent_pools=aks_pools(c("pool1", "pool2"), c(2, 3), c("Standard_DS2_v2", "Standard_NC6s_v3"))) #' #' } NULL #' Get Azure Kubernetes Service (AKS) #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname get_aks #' @name get_aks #' @aliases get_aks list_aks #' #' @section Usage: #' ``` #' get_aks(name) #' list_aks() #' ``` #' @section Arguments: #' - `name`: For `get_aks()`, the name of the Kubernetes service. #' #' @section Details: #' The `AzureRMR::az_resource_group` class has both `get_aks()` and `list_aks()` methods, while the `AzureRMR::az_subscription` class only has the latter. #' #' @section Value: #' For `get_aks()`, an object of class `az_kubernetes_service` representing the service. #' #' For `list_aks()`, a list of such objects. #' #' @seealso #' [create_aks], [delete_aks] #' #' [az_kubernetes_service] #' #' [kubernetes_cluster] for the cluster endpoint #' #' [AKS documentation](https://docs.microsoft.com/en-us/azure/aks/) and #' [API reference](https://docs.microsoft.com/en-us/rest/api/aks/) #' #' [Kubernetes reference](https://kubernetes.io/docs/reference/) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' rg$get_aks("mycluster") #' #' } NULL #' Delete an Azure Kubernetes Service (AKS) #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname delete_aks #' @name delete_aks #' @aliases delete_aks #' #' @section Usage: #' ``` #' delete_aks(name, confirm=TRUE, wait=FALSE) #' ``` #' @section Arguments: #' - `name`: The name of the Kubernetes service. #' - `confirm`: Whether to ask for confirmation before deleting. #' - `wait`: Whether to wait until the deletion is complete. #' #' @section Value: #' NULL on successful deletion. #' #' @seealso #' [create_aks], [get_aks] #' #' [az_kubernetes_service] #' #' [kubernetes_cluster] for the cluster endpoint #' #' [AKS documentation](https://docs.microsoft.com/en-us/azure/aks/) and #' [API reference](https://docs.microsoft.com/en-us/rest/api/aks/) #' #' [Kubernetes reference](https://kubernetes.io/docs/reference/) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' rg$delete_aks("mycluster") #' #' } NULL #' List available Kubernetes versions #' #' Method for the [AzureRMR::az_subscription] and [AzureRMR::az_resource_group] classes. #' #' @rdname list_kubernetes_versions #' @name list_kubernetes_versions #' @aliases list_kubernetes_versions #' #' @section Usage: #' ``` #' ## R6 method for class 'az_subscription' #' list_kubernetes_versions(location) #' #' ## R6 method for class 'az_resource_group' #' list_kubernetes_versions() #' ``` #' @section Arguments: #' - `location`: For the az_subscription class method, the location for which to obtain available Kubernetes versions. #' #' @section Value: #' A vector of strings, which are the Kubernetes versions that can be used when creating a cluster. #' @seealso #' [create_aks] #' #' [Kubernetes reference](https://kubernetes.io/docs/reference/) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' rg$list_kubernetes_versions() #' #' } NULL add_aks_methods <- function() { az_resource_group$set("public", "create_aks", overwrite=TRUE, function(name, location=self$location, dns_prefix=name, kubernetes_version=NULL, login_user="", login_passkey="", enable_rbac=FALSE, agent_pools=agent_pool("pool1", 3), cluster_service_principal=NULL, managed_identity=TRUE, private_cluster=FALSE, properties=list(), ..., wait=TRUE) { if(is_empty(kubernetes_version)) kubernetes_version <- tail(self$list_kubernetes_versions(), 1) # figure out how to handle managing resources: either identity, or SP if(managed_identity) { identity <- list(type="systemAssigned") sp_profile <- NULL } else { identity <- NULL # hide from CRAN check find_app_creds <- get("find_app_creds", getNamespace("AzureContainers")) cluster_service_principal <- find_app_creds(cluster_service_principal, name, location, self$token) if(is.null(cluster_service_principal[[2]])) stop("Must provide a service principal with a secret password", call.=FALSE) sp_profile <- list( clientId=cluster_service_principal[[1]], secret=cluster_service_principal[[2]] ) } if(inherits(agent_pools, "agent_pool")) agent_pools <- list(unclass(agent_pools)) else if(is.list(agent_pools) && all(sapply(agent_pools, inherits, "agent_pool"))) agent_pools <- lapply(agent_pools, unclass) # 1st agent pool is system agent_pools[[1]]$mode <- "System" props <- list( kubernetesVersion=kubernetes_version, dnsPrefix=dns_prefix, agentPoolProfiles=agent_pools, enableRBAC=enable_rbac ) if(private_cluster) { props$apiServerAccessProfile <- list(enablePrivateCluster=private_cluster) props$networkProfile <- list(loadBalancerSku="standard") } if(!is.null(sp_profile)) props$servicePrincipalProfile <- sp_profile if(login_user != "" && login_passkey != "") props$linuxProfile <- list( adminUsername=login_user, ssh=list(publicKeys=list(list(Keydata=login_passkey))) ) props <- utils::modifyList(props, properties) # if service principal was created here, must try repeatedly until it shows up in ARM for(i in 1:20) { res <- tryCatch(AzureContainers::aks$new(self$token, self$subscription, self$name, type="Microsoft.ContainerService/managedClusters", name=name, location=location, properties=props, identity=identity, ..., wait=wait), error=function(e) e) if(!(inherits(res, "error") && grepl("Service principal|ServicePrincipal", res$message))) break Sys.sleep(5) } if(inherits(res, "error")) { # fix printed output from httr errors class(res) <- c("simpleError", "error", "condition") stop(res) } res }) az_resource_group$set("public", "get_aks", overwrite=TRUE, function(name) { AzureContainers::aks$new(self$token, self$subscription, self$name, type="Microsoft.ContainerService/managedClusters", name=name) }) az_resource_group$set("public", "delete_aks", overwrite=TRUE, function(name, confirm=TRUE, wait=FALSE) { self$get_aks(name)$delete(confirm=confirm, wait=wait) }) az_resource_group$set("public", "list_aks", overwrite=TRUE, function() { provider <- "Microsoft.ContainerService" path <- "managedClusters" api_version <- az_subscription$ new(self$token, self$subscription)$ get_provider_api_version(provider, path) op <- file.path("resourceGroups", self$name, "providers", provider, path) cont <- call_azure_rm(self$token, self$subscription, op, api_version=api_version) lst <- lapply(cont$value, function(parms) AzureContainers::aks$new(self$token, self$subscription, deployed_properties=parms)) # keep going until paging is complete while(!is_empty(cont$nextLink)) { cont <- call_azure_url(self$token, cont$nextLink) lst <- lapply(cont$value, function(parms) AzureContainers::aks$new(self$token, self$subscription, deployed_properties=parms)) } named_list(lst) }) az_resource_group$set("public", "list_kubernetes_versions", overwrite=TRUE, function() { az_subscription$ new(self$token, self$subscription)$ list_kubernetes_versions(self$location) }) az_subscription$set("public", "list_aks", overwrite=TRUE, function() { provider <- "Microsoft.ContainerService" path <- "managedClusters" api_version <- self$get_provider_api_version(provider, path) op <- file.path("providers", provider, path) cont <- call_azure_rm(self$token, self$id, op, api_version=api_version) lst <- lapply(cont$value, function(parms) AzureContainers::aks$new(self$token, self$id, deployed_properties=parms)) # keep going until paging is complete while(!is_empty(cont$nextLink)) { cont <- call_azure_url(self$token, cont$nextLink) lst <- lapply(cont$value, function(parms) AzureContainers::aks$new(self$token, self$id, deployed_properties=parms)) } named_list(lst) }) az_subscription$set("public", "list_kubernetes_versions", overwrite=TRUE, function(location) { api_version <- self$get_provider_api_version("Microsoft.ContainerService", "locations/orchestrators") op <- file.path("providers/Microsoft.ContainerService/locations", location, "orchestrators") res <- call_azure_rm(self$token, self$id, op, options=list(`resource-type`="managedClusters"), api_version=api_version) sapply(res$properties$orchestrators, `[[`, "orchestratorVersion") }) } find_app_creds <- function(credlist, name, location, token) { creds <- if(is.null(credlist)) { gr <- graph_login(token$tenant) message("Creating cluster service principal") appname <- paste("RAKSapp", name, location, sep="-") app <- gr$create_app(appname) message("Waiting for Resource Manager to sync with Graph") list(app$properties$appId, app$password) } else if(inherits(credlist, "az_app")) list(credlist$properties$appId, credlist$password) else if(length(credlist) == 2) list(credlist[[1]], credlist[[2]]) if(is_empty(creds) || length(creds) < 2 || is_empty(creds[[2]])) stop("Invalid service principal credentials: must supply app ID and password") creds }
/scratch/gouwar.j/cran-all/cranData/AzureContainers/R/add_aks_methods.R
#' List available VM sizes #' #' Method for the [AzureRMR::az_subscription] and [AzureRMR::az_resource_group] classes. #' #' @section Usage: #' ``` #' ## R6 method for class 'az_subscription' #' list_vm_sizes(location, name_only = FALSE) #' #' ## R6 method for class 'az_resource_group' #' list_vm_sizes(name_only = FALSE) #' ``` #' @section Arguments: #' - `location`: For the subscription class method, the location/region for which to obtain available VM sizes. #' - `name_only`: Whether to return only a vector of names, or all information on each VM size. #' #' @section Value: #' If `name_only` is TRUE, a character vector of names. If FALSE, a data frame containing the following information for each VM size: the name, number of cores, OS disk size, resource disk size, memory, and maximum data disks. #' #' @examples #' \dontrun{ #' #' sub <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id") #' #' sub$list_vm_sizes("australiaeast") #' #' # same output as above #' rg <- sub$create_resource_group("rgname", location="australiaeast") #' rg$list_vm_sizes() #' #' } #' @rdname list_vm_sizes #' @aliases list_vm_sizes #' @name list_vm_sizes NULL # extend subscription methods add_vmsize_methods <- function() { az_subscription$set("public", "list_vm_sizes", overwrite=TRUE, function(location, name_only=FALSE) { provider <- "Microsoft.Compute" path <- "locations" api_version <- self$get_provider_api_version(provider, path) op <- file.path("providers", provider, path, location, "vmSizes") res <- call_azure_rm(self$token, self$id, op, api_version=api_version) if(!name_only) do.call(rbind, lapply(res$value, data.frame, stringsAsFactors=FALSE)) else sapply(res$value, `[[`, "name") }) az_resource_group$set("public", "list_vm_sizes", overwrite=TRUE, function(name_only=FALSE) { az_subscription$ new(self$token, self$subscription)$ list_vm_sizes(self$location, name_only=name_only) }) }
/scratch/gouwar.j/cran-all/cranData/AzureContainers/R/add_vmsize_methods.R
# stub class, may be expanded later az_agent_pool <- R6::R6Class("az_agent_pool", inherit=AzureRMR::az_resource)
/scratch/gouwar.j/cran-all/cranData/AzureContainers/R/az_agent_pool.R
#' Azure Container Instance class #' #' Class representing an Azure Container Instance (ACI) resource. #' #' @docType class #' @section Methods: #' The following methods are available, in addition to those provided by the [AzureRMR::az_resource] class: #' - `new(...)`: Initialize a new ACI object. #' - `restart()`, `start()`: Start a stopped container. These methods are synonyms for each other. #' - `stop()`: Stop a container. #' #' @section Details: #' Initializing a new object of this class can either retrieve an existing ACI resource, or create a new resource on the host. Generally, the best way to initialize an object is via the `get_aci`, `create_aci` or `list_acis` methods of the [az_resource_group] class, which handle the details automatically. #' #' @seealso #' [acr], [aks] #' #' [ACI documentation](https://docs.microsoft.com/en-us/azure/container-instances/) and #' [API reference](https://docs.microsoft.com/en-us/rest/api/container-instances/) #' #' [Docker commandline reference](https://docs.docker.com/engine/reference/commandline/cli/) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' myaci <- rg$get_aci("mycontainer") #' #' myaci$stop() #' myaci$restart() #' #' } #' @aliases az_container_instance #' @export aci <- R6::R6Class("az_container_instance", inherit=AzureRMR::az_resource, public=list( restart=function() { private$res_op("restart", http_verb="POST") }, start=function() { private$res_op("start", http_verb="POST") }, stop=function() { private$res_op("stop", http_verb="POST") } )) #' Utilities for specifying ACI configuration information #' #' @param port,protocol For `aci_ports`, vectors of the port numbers and protocols to open for the instance. #' @param server,username,password For `aci_creds`, the authentication details for a Docker registry. See [docker_registry]. #' @param lst for `get_aci_credentials_list`, a list of objects. #' #' @details #' These are helper functions to be used in specifying the configuration for a container instance. Only `aci_ports` and `aci_creds` are meant to be called by the user; `get_aci_credentials_list` is exported to workaround namespacing issues on startup. #' #' @seealso [create_aci], [aci], [docker_registry] #' @rdname aci_utils #' @export aci_ports <- function(port=c(80L, 443L), protocol="TCP") { df <- data.frame(port=as.integer(port), protocol=protocol, stringsAsFactors=FALSE) lapply(seq_len(nrow(df)), function(i) unclass(df[i, ])) } #' @rdname aci_utils #' @export aci_creds <- function(server, username=NULL, password=NULL) { if(is.null(username)) stop("No container registry identity supplied", call.=FALSE) obj <- list(server=server, username=username, password=password) class(obj) <- "aci_creds" obj } #' @rdname aci_utils #' @export get_aci_credentials_list <- function(lst) { # try to ensure we actually have a list of registries as input if(is_acr(lst) || is_docker_registry(lst) || inherits(lst, "aci_creds") || !is.list(lst)) lst <- list(lst) lapply(lst, function(x) extract_creds(x)) } extract_creds <- function(obj, ...) { UseMethod("extract_creds") } extract_creds.az_container_registry <- function(obj, ...) { extract_creds(obj$get_docker_registry()) } extract_creds.DockerRegistry <- function(obj, ...) { if(is.null(obj$username) || is.null(obj$password)) stop("Docker registry object does not contain a username/password", call.=FALSE) list(server=obj$server$hostname, username=obj$username, password=obj$password) } extract_creds.aci_creds <- function(obj, ...) { unclass(obj) }
/scratch/gouwar.j/cran-all/cranData/AzureContainers/R/az_container_instance.R
#' Azure Container Registry class #' #' Class representing an Azure Container Registry (ACR) resource. For working with the registry endpoint itself, including uploading and downloading images etc, see [docker_registry]. #' #' @docType class #' @section Methods: #' The following methods are available, in addition to those provided by the [AzureRMR::az_resource] class: #' - `new(...)`: Initialize a new ACR object. See 'Details'. #' - `add_role_assignment(principal, role, scope=NULL, ...)`: Adds a role for the specified principal. This is an override mainly to handle AKS objects, so that the Kubernetes cluster can be granted access to the registry. You can use the `...` arguments to supply authentication details for AzureGraph, which is used to retrieve the cluster service principal. #' - `list_credentials`: Return the username and passwords for this registry. Only valid if the Admin user for the registry has been enabled. #' - `list_policies`: Return the policies for this registry. #' - `list_usages`: Return the usage for this registry. #' - `get_docker_registry(username, password)`: Return an object representing the Docker registry endpoint. #' #' @section Details: #' Initializing a new object of this class can either retrieve an existing registry resource, or create a new registry on the host. Generally, the best way to initialize an object is via the `get_acr`, `create_acr` or `list_acrs` methods of the [az_resource_group] class, which handle the details automatically. #' #' Note that this class is separate from the Docker registry itself. This class exposes methods for working with the Azure resource: listing credentials, updating resource tags, updating and deleting the resource, and so on. #' #' For working with the registry, including uploading and downloading images, updating tags, deleting layers and images etc, use the endpoint object generated with `get_docker_registry`. This method takes two optional arguments: #' #' - `username`: The username that Docker will use to authenticate with the registry. #' - `password`: The password that Docker will use to authenticate with the registry. #' #' By default, these arguments will be retrieved from the ACR resource. They will only exist if the resource was created with `admin_user_enabled=TRUE`. Currently AzureContainers does not support authentication methods other than a username/password combination. #' #' @seealso #' [create_acr], [get_acr], [delete_acr], [list_acrs] #' #' [docker_registry] for interacting with the Docker registry endpoint #' #' [Azure Container Registry](https://docs.microsoft.com/en-us/azure/container-registry/) and #' [API reference](https://docs.microsoft.com/en-us/rest/api/containerregistry/registries) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' myacr <- rg$get_acr("myregistry") #' #' myacr$list_credentials() #' myacr$list_policies() #' #' # see who has push and pull access #' myacr$list_role_assignments() #' #' # grant a Kubernetes cluster pull access #' myaks <- rg$get_aks("myaks") #' myacr$add_role_assignment(myaks, "Acrpull") #' #' # get the registry endpoint (for interactive use) #' myacr$get_docker_registry() #' #' # get the registry endpoint (admin user account) #' myacr$get_docker_registry(as_admin=TRUE) #' #' } #' @aliases az_container_registry #' @export acr <- R6::R6Class("az_container_registry", inherit=AzureRMR::az_resource, public=list( add_role_assignment=function(principal, role, scope=NULL, ...) { if(is_aks(principal)) { clientid <- principal$properties$servicePrincipalProfile$clientId if(clientid == "msi") { ident <- principal$properties$identityProfile principal <- ident[[1]]$objectId } else { tenant <- self$token$tenant principal <- graph_login(tenant, ...)$get_app(clientid) } } super$add_role_assignment(principal, role, scope) }, list_credentials=function() { if(!self$properties$adminUserEnabled) stop("Admin user account is disabled", call.=FALSE) creds <- private$res_op("listCredentials", http_verb="POST") pwds <- sapply(creds$passwords, `[[`, "value") names(pwds) <- sapply(creds$passwords, `[[`, "name") list(username=creds$username, passwords=pwds) }, list_policies=function() { private$res_op("listPolicies") }, list_usages=function() { use <- private$res_op("listUsages")$value do.call(rbind, lapply(use, as.data.frame)) }, get_docker_registry=function(..., as_admin=FALSE, token=self$token) { server <- paste0("https://", self$properties$loginServer) if(as_admin) { creds <- self$list_credentials() docker_registry(server, username=creds$username, password=creds$passwords[1], app=NULL) } else docker_registry(server, ..., token=token) } ))
/scratch/gouwar.j/cran-all/cranData/AzureContainers/R/az_container_registry.R
#' Azure Kubernetes Service class #' #' Class representing an Azure Kubernetes Service (AKS) resource. For working with the cluster endpoint itself, including deploying images, creating services etc, see [kubernetes_cluster]. #' #' @docType class #' @section Methods: #' The following methods are available, in addition to those provided by the [AzureRMR::az_resource] class: #' - `new(...)`: Initialize a new AKS object. #' - `get_cluster(config, role)`: Return an object representing the Docker registry endpoint. #' - `get_agent_pool(pollname)`: Returns an object of class `az_agent_pool` representing an agent pool. This class inherits from [AzureRMR::az_resource]; it currently has no extra methods, but these may be added in the future. #' - `list_agent_pools()`: Returns a list of agent pool objects. #' - `create_agent_pool(poolname, ..., wait=FALSE)`: Creates a new agent pool. See the [agent_pool] function for further arguments to this method. #' - `delete_agent_pool(poolname, confirm=TRUE. wait=FALSE)`: Deletes an agent pool. #' - `list_cluster_resources()`: Returns a list of all the Azure resources managed by the cluster. #' - `update_aad_password(name=NULL, duration=NULL, ...)`: Update the password for Azure Active Directory integration, returning the new password invisibly. See 'Updating credentials' below. #' - `update_service_password(name=NULL, duration=NULL, ...)`: Update the password for the service principal used to manage the cluster resources, returning the new password invisibly. See 'Updating credentials' below. #' #' @section Details: #' Initializing a new object of this class can either retrieve an existing AKS resource, or create a new resource on the host. Generally, the best way to initialize an object is via the `get_aks`, `create_aks` or `list_aks` methods of the [az_resource_group] class, which handle the details automatically. #' #' Note that this class is separate from the Kubernetes cluster itself. This class exposes methods for working with the Azure resource: updating resource tags, updating and deleting the resource (including updating the Kubernetes version), and so on. #' #' For working with the cluster, including deploying images, services, etc use the object generated with the `get_cluster` method. This method takes two optional arguments: #' #' - `config`: The file in which to store the cluster configuration details. By default, this will be located in the AzureR configuration directory if it exists (see [AzureAuth::AzureR_dir]); otherwise, in the R temporary directory. To use the Kubernetes default `~/.kube/config` file, set this argument to NULL. Any existing file in the given location will be overwritten. #' - `role`: This can be `"User"` (the default) or `"Admin"`. #' #' @section Updating credentials: #' An AKS resource can have up to three service principals associated with it. Two of these are for Azure Active Directory (AAD) integration. The third is used to manage the subsidiary resources (VMs, networks, disks, etc) used by the cluster, if it doesn't have a service identity. #' #' Any service principals used by the AKS resource will have secret passwords, which have to be refreshed as they expire. The `update_aad_password()` and `update_service_password()` methods let you refresh the passwords for the cluster's service principals. Their arguments are: #' #' - `name`: An optional friendly name for the password. #' - `duration`: The duration for which the new password is valid. Defaults to 2 years. #' - `...`: Other arguments passed to `AzureGraph::create_graph_login`. Note that these are used to authenticate with Microsoft Graph, which does the actual work of updating the service principals, not to the cluster itself. #' #' @seealso #' [create_aks], [get_aks], [delete_aks], [list_aks], [AzureAuth::AzureR_dir], [AzureGraph::create_graph_login] #' #' [kubernetes_cluster] for interacting with the cluster endpoint #' #' [AKS documentation](https://docs.microsoft.com/en-us/azure/aks/) and #' [API reference](https://docs.microsoft.com/en-us/rest/api/aks/) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' myaks <- rg$get_aks("mycluster") #' #' # sync with Azure: AKS resource creation can take a long time, use this to track status #' myaks$sync_fields() #' #' # get the cluster endpoint #' kubclus <- myaks$get_cluster() #' #' # list of agent pools #' myaks$list_agent_pools() #' #' # create a new agent pool, then delete it #' pool <- myaks$create_agent_pool("pool2", 3, size="Standard_DS3_v2") #' pool$delete() #' #' # refresh the service principal password (mostly for legacy clusters without a managed identity) #' myaks$update_service_password() #' #' # refresh the service principal password, using custom credentials to authenticate with MS Graph #' # arguments here are for Graph, not AKS! #' myaks$update_service_password(app="app_id", password="app_password") #' #' } #' @aliases az_kubernetes_service #' @export aks <- R6::R6Class("az_kubernetes_service", inherit=AzureRMR::az_resource, public=list( get_cluster=function(config=kubeconfig_file(), role=c("User", "Admin")) { kubeconfig_file <- function() { az_dir <- AzureR_dir() if(!dir.exists(az_dir)) az_dir <- tempdir() file.path(az_dir, paste0("kubeconfig_", self$name)) } role <- match.arg(role) profile <- private$res_op(paste0("listCluster", role, "Credential"), http_verb="POST")$kubeconfigs profile <- rawToChar(openssl::base64_decode(profile[[1]]$value)) # provide ability to save to default .kube/config by passing a NULL if(is.null(config)) { win <- .Platform$OS.type == "windows" config <- if(win) file.path(Sys.getenv("HOMEPATH"), ".kube/config") else file.path(Sys.getenv("HOME"), ".kube/config") } if(file.exists(config)) message("Overwriting existing cluster information in ", config) else { config_dir <- dirname(config) if(!dir.exists(config_dir)) dir.create(config_dir, recursive=TRUE) message("Storing cluster information in ", config) } writeLines(profile, config) kubernetes_cluster(config=config) }, get_agent_pool=function(poolname) { az_agent_pool$new(self$token, self$subscription, resource_group=self$resource_group, type="Microsoft.ContainerService/managedClusters", name=file.path(self$name, "agentPools", poolname), api_version=self$get_api_version()) }, create_agent_pool=function(poolname, ..., wait=FALSE) { pool <- agent_pool(name=poolname, ...) az_agent_pool$new(self$token, self$subscription, resource_group=self$resource_group, type="Microsoft.ContainerService/managedClusters", name=file.path(self$name, "agentPools", poolname), properties=pool[-1], api_version=self$get_api_version(), wait=wait) }, delete_agent_pool=function(poolname, confirm=TRUE, wait=FALSE) { az_agent_pool$new(self$token, self$subscription, resource_group=self$resource_group, type="Microsoft.ContainerService/managedClusters", name=file.path(self$name, "agentPools", poolname), deployed_properties=list(NULL), api_version=self$get_api_version())$ delete(confirm=confirm, wait=wait) }, list_agent_pools=function() { cont <- self$do_operation("agentPools") api_version <- self$get_api_version() lapply(get_paged_list(cont, self$token), function(parms) az_agent_pool$new(self$token, self$subscription, deployed_properties=parms, api_version=api_version)) }, list_cluster_resources=function() { clusrgname <- self$properties$nodeResourceGroup clusrg <- az_resource_group$new(self$token, self$subscription, clusrgname) clusrg$list_resources() }, update_aad_password=function(name=NULL, duration=NULL, ...) { prof <- self$properties$aadProfile if(is.null(prof)) stop("No Azure Active Directory profile associated with this cluster", call.=FALSE) app <- graph_login(self$token$tenant, ...)$get_app(prof$serverAppID) app$add_password(name, duration) prof$serverAppSecret <- app$password self$do_operation(body=list(properties=list(aadProfile=prof)), encode="json", http_verb="PATCH") self$sync_fields() invisible(prof$serverAppSecret) }, update_service_password=function(name=NULL, duration=NULL, ...) { prof <- self$properties$servicePrincipalProfile if(prof$clientId == "msi") stop("Cluster uses service identity for managing resources", call.=FALSE) app <- graph_login(self$token$tenant, ...)$get_app(prof$clientId) app$add_password(name, duration) prof$secret <- app$password self$do_operation(body=list(properties=list(servicePrincipalProfile=prof)), encode="json", http_verb="PATCH") self$sync_fields() invisible(prof$secret) } )) #' Utility function for specifying Kubernetes agent pools #' #' @param name The name(s) of the pool(s). #' @param count The number of nodes per pool. #' @param size The VM type (size) to use for the pool. To see a list of available VM sizes, use the [list_vm_sizes] method for the resource group or subscription classes. #' @param os The operating system to use for the pool. Can be "Linux" or "Windows". #' @param disksize The OS disk size in gigabytes for each node in the pool. A value of 0 means to use the default disk size for the VM type. #' @param use_scaleset Whether to use a VM scaleset instead of individual VMs for this pool. A scaleset offers greater flexibility than individual VMs, and is the recommended method of creating an agent pool. #' @param low_priority If this pool uses a scaleset, whether it should be made up of spot (low-priority) VMs. A spot VM pool is cheaper, but is subject to being evicted to make room for other, higher-priority workloads. Ignored if `use_scaleset=FALSE`. #' @param autoscale_nodes The cluster autoscaling parameters for the pool. To enable autoscaling, set this to a vector of 2 numbers giving the minimum and maximum size of the agent pool. Ignored if `use_scaleset=FALSE`. #' @param ... Other named arguments, to be used as parameters for the agent pool. #' #' @details #' `agent_pool` is a convenience function to simplify the task of specifying the agent pool for a Kubernetes cluster. #' #' @return #' An object of class `agent_pool`, suitable for passing to the `create_aks` constructor method. #' #' @seealso #' [create_aks], [list_vm_sizes] #' #' [Agent pool parameters on Microsoft Docs](https://docs.microsoft.com/en-us/rest/api/aks/managedclusters/createorupdate#managedclusteragentpoolprofile) #' #' @examples #' # pool of 5 Linux GPU-enabled VMs #' agent_pool("pool1", 5, size="Standard_NC6s_v3") #' #' # pool of 3 Windows Server VMs, 500GB disk size each #' agent_pool("pool1", 3, os="Windows", disksize=500) #' #' # enable cluster autoscaling, with a minimum of 1 and maximum of 10 nodes #' agent_pool("pool1", 5, autoscale_nodes=c(1, 10)) #' #' # use individual VMs rather than scaleset #' agent_pool("vmpool1", 3, use_scaleset=FALSE) #' #' @export agent_pool <- function(name, count, size="Standard_DS2_v2", os="Linux", disksize=0, use_scaleset=TRUE, low_priority=FALSE, autoscale_nodes=FALSE, ...) { parms <- list( name=name, count=as.integer(count), vmSize=size, osType=os, osDiskSizeGB=disksize, type=if(use_scaleset) "VirtualMachineScaleSets" else "AvailabilitySet" ) if(use_scaleset) { if(is.numeric(autoscale_nodes) && length(autoscale_nodes) == 2) { parms$enableAutoScaling <- TRUE parms$minCount <- min(autoscale_nodes) parms$maxCount <- max(autoscale_nodes) } if(low_priority) parms$scaleSetPriority <- "spot" } extras <- list(...) if(!is_empty(extras)) parms <- utils::modifyList(parms, extras) structure(parms, class="agent_pool") } #' Vectorised utility function for specifying Kubernetes agent pools #' #' @param name The name(s) of the pool(s). #' @param count The number of nodes per pool. #' @param size The VM type (size) to use for the pool. To see a list of available VM sizes, use the [list_vm_sizes] method for the resource group or subscription classes. #' @param os The operating system to use for the pool. Can be "Linux" or "Windows". #' #' @details #' This is a convenience function to simplify the task of specifying the agent pool for a Kubernetes cluster. You can specify multiple pools by providing vectors as input arguments; any scalar inputs will be replicated to match. #' #' `aks_pools` is deprecated; please use [agent_pool] going forward. #' #' @return #' A list of lists, suitable for passing to the `create_aks` constructor method. #' #' @seealso #' [list_vm_sizes], [agent_pool] #' #' @examples #' # 1 pool of 5 Linux VMs #' aks_pools("pool1", 5) #' #' # 1 pool of 3 Windows Server VMs #' aks_pools("pool1", 3, os="Windows") #' #' # 2 pools with different VM sizes per pool #' aks_pools(c("pool1", "pool2"), count=c(3, 3), size=c("Standard_DS2_v2", "Standard_DS3_v2")) #' #' @export aks_pools <- function(name, count, size="Standard_DS2_v2", os="Linux") { count <- as.integer(count) pool_df <- data.frame(name=name, count=count, vmSize=size, osType=os, stringsAsFactors=FALSE) pool_df$name <- make.unique(pool_df$name, sep="") lapply(seq_len(nrow(pool_df)), function(i) unclass(pool_df[i, ])) }
/scratch/gouwar.j/cran-all/cranData/AzureContainers/R/az_kubernetes_service.R
#' Docker registry class #' #' Class representing a [Docker registry](https://docs.docker.com/registry/). Note that this class can be used to interface with any Docker registry that supports the HTTP V2 API, not just those created via the Azure Container Registry service. Use the [docker_registry] function to instantiate new objects of this class. #' #' @docType class #' @section Methods: #' The following methods are available, in addition to those provided by the [AzureRMR::az_resource] class: #' - `login(...)`: Do a local login to the registry via `docker login`; necessary if you want to push and pull images. By default, instantiating a new object of this class will also log you in. See 'Details' below. #' - `push(src_image, dest_image, ...)`: Push an image to the registry, using `docker tag` and `docker push`. #' - `pull(image, ...)`: Pull an image from the registry, using `docker pull`. #' - `get_image_manifest(image, tag="latest")`: Gets the manifest for an image. #' - `get_image_digest(image, tag="latest")`: Gets the digest (SHA hash) for an image. #' - `delete_image(image, digest, confirm=TRUE)`: Deletes an image from the registry. #' - `list_repositories()`: Lists the repositories (images) in the registry. #' #' @section Details: #' The arguments to the `login()` method are: #' - `tenant`: The Azure Active Directory (AAD) tenant for the registry. #' - `username`: The username that Docker will use to authenticate with the registry. This can be either the admin username, if the registry was created with an admin account, or the ID of a registered app that has access to the registry. #' - `password`: The password that Docker will use to authenticate with the registry. #' - `app`: The app ID to use to authenticate with the registry. Set this to NULL to authenticate with a username and password, rather than via AAD. #' - `...`: Further arguments passed to [AzureAuth::get_azure_token]. #' - `token`: An Azure token object. If supplied, all authentication details will be inferred from this. #' #' The `login()`, `push()` and `pull()` methods for this class call the `docker` commandline tool under the hood. This allows all the features supported by Docker to be available immediately, with a minimum of effort. Any calls to the `docker` tool will also contain the full commandline as the `cmdline` attribute of the (invisible) returned value; this allows scripts to be developed that can be run outside R. #' #' @seealso #' [acr], [docker_registry], [call_docker] #' #' [Docker commandline reference](https://docs.docker.com/engine/reference/commandline/cli/) #' #' [Docker registry API](https://docs.docker.com/registry/spec/api/) #' #' @examples #' \dontrun{ #' #' reg <- docker_registry("myregistry") #' #' reg$list_repositories() #' #' # create an image from a Dockerfile in the current directory #' call_docker(c("build", "-t", "myimage", ".")) #' #' # push the image #' reg$push("myimage") #' #' reg$get_image_manifest("myimage") #' reg$get_image_digest("myimage") #' #' } #' @export DockerRegistry <- R6::R6Class("DockerRegistry", public=list( server=NULL, username=NULL, password=NULL, aad_token=NULL, initialize=function(server, ..., login=TRUE) { self$server <- httr::parse_url(server) if(login) self$login(...) }, login=function(tenant="common", username=NULL, password=NULL, app=.az_cli_app_id, ..., token=NULL) { # ways to login: # via creds inferred from AAD token # if app == NULL, with admin account if(is.null(app)) { if(is.null(username) || is.null(password)) stop("Must supply username and password for admin login", call.=FALSE) self$username <- username self$password <- password } else { # default is to reuse token from any existing AzureRMR login if(is.null(token)) token <- AzureAuth::get_azure_token("https://management.azure.com/", tenant=tenant, app=app, password=password, username=username, ...) self$aad_token <- token username <- "00000000-0000-0000-0000-000000000000" password <- private$get_creds_from_aad() } # special-casing Docker Hub cmd <- if(self$server$hostname == "hub.docker.com") paste("login --password-stdin --username", username) else paste("login --password-stdin --username", username, self$server$hostname) pwd_file <- tempfile() on.exit(unlink(pwd_file)) writeLines(password, pwd_file) call_docker(cmd, stdin=pwd_file) invisible(NULL) }, push=function(src_image, dest_image, ...) { out1 <- if(missing(dest_image)) { dest_image <- private$paste_server(src_image) call_docker(sprintf("tag %s %s", src_image, dest_image), ...) } else { dest_image <- private$paste_server(dest_image) call_docker(sprintf("tag %s %s", src_image, dest_image), ...) } out2 <- call_docker(sprintf("push %s", dest_image), ...) invisible(list(out1, out2)) }, pull=function(image, ...) { image <- private$paste_server(image) call_docker(sprintf("pull %s", image), ...) }, get_image_manifest=function(image, tag="latest") { if(grepl(":", image)) { tag <- sub("^[^:]+:", "", image) image <- sub(":.+$", "", image) } op <- file.path(image, "manifests", tag) perms <- paste("repository", image, "pull", sep=":") cont <- self$call_registry(op, permissions=perms) # registry API doesn't set content-type correctly, need to process further jsonlite::fromJSON(rawToChar(cont), simplifyVector=FALSE) }, get_image_digest=function(image, tag="latest") { if(grepl(":", image)) { tag <- sub("^[^:]+:", "", image) image <- sub(":.+$", "", image) } op <- file.path(image, "manifests", tag) perms <- paste("repository", image, "pull", sep=":") cont <- self$call_registry(op, http_verb="HEAD", permissions=perms, http_status_handler="pass") httr::stop_for_status(cont) httr::headers(cont)$`docker-content-digest` }, delete_image=function(image, confirm=TRUE) { if(confirm && interactive()) { yn <- readline(paste0("Do you really want to delete the image '", image, "'? (y/N) ")) if(tolower(substr(yn, 1, 1)) != "y") return(invisible(NULL)) } # get the digest for this image digest <- self$get_image_digest(image) if(is_empty(digest)) stop("Unable to find digest info for image", call.=FALSE) op <- file.path(image, "manifests", digest) perms <- paste("repository", image, "delete", sep=":") res <- self$call_registry(op, http_verb="DELETE", permissions=perms) invisible(res) }, list_repositories=function() { res <- self$call_registry("_catalog", permissions="registry:catalog:*") unlist(res$repositories) }, call_registry=function(op, ..., encode="form", http_verb=c("GET", "DELETE", "PUT", "POST", "HEAD", "PATCH"), http_status_handler=c("stop", "warn", "message", "pass"), permissions="") { auth <- if(is.null(self$aad_token)) { userpass <- openssl::base64_encode(paste(self$username, self$password, sep=":")) paste("Basic", userpass) } else { creds <- private$get_creds_from_aad() access_token <- private$get_access_token(creds, permissions) paste("Bearer", access_token) } headers <- httr::add_headers( Accept="application/vnd.docker.distribution.manifest.v2+json", Authorization=auth ) uri <- self$server uri$path <- paste0("/v2/", op) res <- httr::VERB(match.arg(http_verb), uri, headers, ..., encode=encode) process_registry_response(res, match.arg(http_status_handler)) }, print=function(...) { cat("Docker registry '", self$server$hostname, "'\n", sep="") cat("<Authentication>\n") if(is.null(self$aad_token)) { cat(" Username:", self$username, "\n") cat(" Password: <hidden>\n") } else cat(" Via Azure Active Directory\n") cat("---\n") cat(format_public_methods(self)) invisible(self) } ), private=list( paste_server=function(image) { # special-casing Docker Hub server <- if(self$server$hostname == "hub.docker.com") self$username else self$server$hostname server <- paste0(server, "/") has_server <- substr(image, 1, nchar(server)) == server if(!has_server) paste0(server, image) else image }, get_creds_from_aad=function() { if(!self$aad_token$validate()) self$aad_token$refresh() uri <- self$server uri$path <- "oauth2/exchange" tenant <- if(self$aad_token$tenant == "common") AzureAuth::decode_jwt(self$aad_token$credentials$access_token)$payload$tid else self$aad_token$tenant res <- httr::POST(uri, body=list( grant_type="access_token", service=uri$hostname, tenant=tenant, access_token=self$aad_token$credentials$access_token ), encode="form" ) httr::stop_for_status(res) httr::content(res)$refresh_token }, get_access_token=function(creds, permissions) { uri <- self$server uri$path <- "oauth2/token" res <- httr::POST(uri, body=list( grant_type="refresh_token", service=uri$hostname, scope=permissions, refresh_token=creds ), encode="form" ) httr::stop_for_status(res) httr::content(res)$access_token } )) #' Create a new Docker registry object #' #' @param server The registry server. This can be a URL ("https://myregistry.azurecr.io") or a domain name label ("myregistry"); if the latter, the value of the `domain` argument is appended to obtain the full hostname. #' @param tenant,username,password,app,... Authentication arguments to [AzureAuth::get_azure_token]. See 'Details' below. #' @param domain The default domain for the registry server. #' @param token An OAuth token, of class [AzureAuth::AzureToken]. If supplied, the authentication details for the registry will be inferred from this. #' @param login Whether to perform a local login (requires that you have Docker installed). This is necessary if you want to push or pull images. #' #' @details #' There are two ways to authenticate with an Azure Docker registry: via Azure Active Directory (AAD), or with a username and password. The latter is simpler, while the former is more complex but also more flexible and secure. #' #' The default method of authenticating is via AAD. Without any arguments, `docker_registry` will authenticate using the AAD credentials of the currently logged-in user. You can change this by supplying the appropriate arguments to `docker_registry`, which will be passed to `AzureAuth::get_azure_token`; alternatively, you can provide an existing token object. #' #' To authenticate via the admin user account, set `app=NULL` and supply the admin username and password in the corresponding arguments. Note that for this to work, the registry must have been created with the admin account enabled. #' #' Authenticating with a service principal can be done either indirectly via AAD, or via a username and password. See the examples below. The latter method is recommended, as it is both faster and allows easier interoperability with AKS and ACI. #' #' @return #' An R6 object of class `DockerRegistry`. #' #' @seealso #' [DockerRegistry] for methods available for interacting with the registry, [call_docker] #' #' [kubernetes_cluster] for the corresponding function to create a Kubernetes cluster object #' #' @examples #' \dontrun{ #' #' # connect to the Docker registry 'myregistry.azurecr.io', authenticating as the current user #' docker_registry("myregistry") #' #' # same, but providing a full URL #' docker_registry("https://myregistry.azurecr.io") #' #' # authenticating via the admin account #' docker_registry("myregistry", username="admin", password="password", app=NULL) #' #' # authenticating with a service principal, method 1: recommended #' docker_registry("myregistry", username="app_id", password="client_creds", app=NULL) #' #' # authenticating with a service principal, method 2 #' docker_registry("myregistry", app="app_id", password="client_creds") #' #' # authenticating from a managed service identity (MSI) #' token <- AzureAuth::get_managed_token("https://management.azure.com/") #' docker_registry("myregistry", token=token) #' #' # you can also interact with a registry outside Azure #' # note that some registry methods, and AAD authentication, may not work in this case #' docker_registry("https://hub.docker.com", username="mydockerid", password="password", app=NULL) #' #' } #' @export docker_registry <- function(server, tenant="common", username=NULL, password=NULL, app=.az_cli_app_id, ..., domain="azurecr.io", token=NULL, login=TRUE) { if(!is_url(server)) server <- sprintf("https://%s.%s", server, domain) DockerRegistry$new(server, tenant=tenant, username=username, password=password, app=app, ..., token=token, login=login) } process_registry_response <- function(response, handler) { if(handler != "pass") { handler <- get(paste0(handler, "_for_status"), getNamespace("httr")) handler(response) cont <- httr::content(response) if(is.null(cont)) cont <- list() attr(cont, "status") <- httr::status_code(response) cont } else response }
/scratch/gouwar.j/cran-all/cranData/AzureContainers/R/docker_registry.R
#' Call the docker commandline tool #' #' @param cmd The docker command. This should be a _vector_ of individual docker arguments, but can also be a single commandline string. See below. #' @param echo Whether to echo the output of the command to the console. #' @param ... Other arguments to pass to [processx::run]. #' #' @details #' This function calls the `docker` binary, which must be located in your search path. AzureContainers will search for the binary at package startup, and print a warning if it is not found. #' #' The docker command should be specified as a vector of the individual arguments, which is what `processx::run` expects. If a single string is passed, for convenience and back-compatibility reasons `call_docker` will split it into arguments for you. This is prone to error, for example if you are working with pathnames that contain spaces, so it's strongly recommended to pass a vector of arguments as a general practice. #' #' @return #' A list with the following components: #' - `status`: The exit status of the docker tool. If this is `NA`, then the process was killed and had no exit status. #' - `stdout`: The standard output of the command, in a character scalar. #' - `stderr`: The standard error of the command, in a character scalar. #' - `timeout`: Whether the process was killed because of a timeout. #' - `cmdline`: The command line. #' #' The first four components are from `processx::run`; AzureContainers adds the last to make it easier to construct scripts that can be run outside R. #' #' @seealso #' [processx::run], [call_docker_compose], [call_kubectl] for the equivalent interface to the `kubectl` Kubernetes tool #' #' [docker_registry] #' #' [Docker command line reference](https://docs.docker.com/engine/reference/commandline/cli/) #' #' @examples #' \dontrun{ #' #' # without any args, prints the docker help screen #' call_docker() #' #' # build an image: recommended usage #' call_docker(c("build", "-t", "myimage", ".")) #' #' # alternative usage, will be split into individual arguments #' call_docker("build -t myimage .") #' #' # list running containers #' call_docker(c("container", "ls")) #' #' # prune unused containers and images #' call_docker(c("container", "prune", "-f")) #' call_docker(c("image", "prune", "-f")) #' #' } #' @export call_docker <- function(cmd="", ..., echo=getOption("azure_containers_tool_echo", TRUE)) { if(.AzureContainers$docker == "") stop("docker binary not found", call.=FALSE) if(length(cmd) == 1 && grepl(" ", cmd, fixed=TRUE)) cmd <- strsplit(cmd, "\\s+")[[1]] win <- .Platform$OS.type == "windows" if(!win) { dockercmd <- "sudo" realcmd <- c(.AzureContainers$docker, cmd) } else { dockercmd <- .AzureContainers$docker realcmd <- cmd } echo <- as.logical(echo) val <- processx::run(dockercmd, realcmd, ..., echo=echo) val$cmdline <- paste("docker", paste(realcmd, collapse=" ")) invisible(val) } #' Call the docker-compose commandline tool #' #' @param cmd The docker-compose command line to execute. This should be a _vector_ of individual docker-compose arguments, but can also be a single commandline string. See below. #' @param echo Whether to echo the output of the command to the console. #' @param ... Other arguments to pass to [processx::run]. #' #' @details #' This function calls the `docker-compose` binary, which must be located in your search path. AzureContainers will search for the binary at package startup, and print a warning if it is not found. #' #' The docker-compose command should be specified as a vector of the individual arguments, which is what `processx::run` expects. If a single string is passed, for convenience and back-compatibility reasons `call_docker_compose` will split it into arguments for you. This is prone to error, for example if you are working with pathnames that contain spaces, so it's strongly recommended to pass a vector of arguments as a general practice. #' #' @return #' A list with the following components: #' - `status`: The exit status of the docker-compose tool. If this is `NA`, then the process was killed and had no exit status. #' - `stdout`: The standard output of the command, in a character scalar. #' - `stderr`: The standard error of the command, in a character scalar. #' - `timeout`: Whether the process was killed because of a timeout. #' - `cmdline`: The command line. #' #' The first four components are from `processx::run`; AzureContainers adds the last to make it easier to construct scripts that can be run outside R. #' #' @seealso #' [processx::run], [call_docker], [call_kubectl] for the equivalent interface to the `kubectl` Kubernetes tool #' #' [docker_registry] #' #' [Docker-compose command line reference](https://docs.docker.com/compose/) #' @export call_docker_compose <- function(cmd="", ..., echo=getOption("azure_containers_tool_echo", TRUE)) { if(.AzureContainers$dockercompose == "") stop("docker-compose binary not found", call.=FALSE) if(length(cmd) == 1 && grepl(" ", cmd, fixed=TRUE)) cmd <- strsplit(cmd, "\\s+")[[1]] win <- .Platform$OS.type == "windows" if(!win) { dcmpcmd <- "sudo" realcmd <- c(.AzureContainers$dockercompose, cmd) } else { dcmpcmd <- .AzureContainers$dockercompose realcmd <- cmd } echo <- as.logical(echo) val <- processx::run(dcmpcmd, realcmd, ..., echo=echo) val$cmdline <- paste("docker-compose", paste(realcmd, collapse=" ")) invisible(val) } #' Call the Kubernetes commandline tool, kubectl #' #' @param cmd The kubectl command line to execute. This should be a _vector_ of individual kubectl arguments, but can also be a single commandline string. See below. #' @param echo Whether to echo the output of the command to the console. #' @param config The pathname of the cluster config file, if required. #' @param ... Other arguments to pass to [processx::run]. #' #' @details #' This function calls the `kubectl` binary, which must be located in your search path. AzureContainers will search for the binary at package startup, and print a warning if it is not found. #' #' The kubectl command should be specified as a vector of the individual arguments, which is what `processx::run` expects. If a single string is passed, for convenience and back-compatibility reasons `call_docker_compose` will split it into arguments for you. This is prone to error, for example if you are working with pathnames that contain spaces, so it's strongly recommended to pass a vector of arguments as a general practice. #' #' @return #' A list with the following components: #' - `status`: The exit status of the kubectl tool. If this is `NA`, then the process was killed and had no exit status. #' - `stdout`: The standard output of the command, in a character scalar. #' - `stderr`: The standard error of the command, in a character scalar. #' - `timeout`: Whether the process was killed because of a timeout. #' - `cmdline`: The command line. #' #' The first four components are from `processx::run`; AzureContainers adds the last to make it easier to construct scripts that can be run outside R. #' #' @seealso #' [processx::run], [call_docker], [call_helm] #' #' [kubernetes_cluster] #' #' [Kubectl command line reference](https://kubernetes.io/docs/reference/kubectl/overview/) #' #' @examples #' \dontrun{ #' #' # without any args, prints the kubectl help screen #' call_kubectl() #' #' # append "--help" to get help for a command #' call_kubectl(c("create", "--help")) #' #' # deploy a service from a yaml file #' call_kubectl(c("create", "-f", "deployment.yaml")) #' #' # get deployment and service status #' call_kubectl(c("get", "deployment")) #' call_kubectl(c("get", "service")) #' #' } #' @export call_kubectl <- function(cmd="", config=NULL, ..., echo=getOption("azure_containers_tool_echo", TRUE)) { if(.AzureContainers$kubectl == "") stop("kubectl binary not found", call.=FALSE) if(!is.null(config)) config <- paste0("--kubeconfig=", config) if(length(cmd) == 1 && grepl(" ", cmd, fixed=TRUE)) cmd <- strsplit(cmd, "\\s+")[[1]] echo <- as.logical(echo) val <- processx::run(.AzureContainers$kubectl, c(cmd, config), ..., echo=echo) val$cmdline <- paste("kubectl", paste(cmd, collapse=" "), config) invisible(val) } #' Call the Helm commandline tool #' #' @param cmd The Helm command line to execute. This should be a _vector_ of individual helm arguments, but can also be a single commandline string. See below. #' @param echo Whether to echo the output of the command to the console. #' @param config The pathname of the cluster config file, if required. #' @param ... Other arguments to pass to [processx::run]. #' #' @details #' This function calls the `helm` binary, which must be located in your search path. AzureContainers will search for the binary at package startup, and print a warning if it is not found. #' #' The helm command should be specified as a vector of the individual arguments, which is what `processx::run` expects. If a single string is passed, for convenience and back-compatibility reasons `call_docker_compose` will split it into arguments for you. This is prone to error, for example if you are working with pathnames that contain spaces, so it's strongly recommended to pass a vector of arguments as a general practice. #' #' @return #' A list with the following components: #' - `status`: The exit status of the helm tool. If this is `NA`, then the process was killed and had no exit status. #' - `stdout`: The standard output of the command, in a character scalar. #' - `stderr`: The standard error of the command, in a character scalar. #' - `timeout`: Whether the process was killed because of a timeout. #' - `cmdline`: The command line. #' #' The first four components are from `processx::run`; AzureContainers adds the last to make it easier to construct scripts that can be run outside R. #' #' @seealso #' [processx::run], [call_docker], [call_kubectl] #' #' [kubernetes_cluster] #' #' [Kubectl command line reference](https://kubernetes.io/docs/reference/kubectl/overview/) #' #' @export call_helm <- function(cmd="", config=NULL, ..., echo=getOption("azure_containers_tool_echo", TRUE)) { if(.AzureContainers$helm == "") stop("helm binary not found", call.=FALSE) if(!is.null(config)) config <- paste0("--kubeconfig=", config) if(length(cmd) == 1 && grepl(" ", cmd, fixed=TRUE)) cmd <- strsplit(cmd, "\\s+")[[1]] echo <- as.logical(echo) val <- processx::run(.AzureContainers$helm, c(cmd, config), ..., echo=echo) val$cmdline <- paste("helm", paste(cmd, collapse=" "), config) invisible(val) }
/scratch/gouwar.j/cran-all/cranData/AzureContainers/R/ext_tools.R
graph_login <- function(tenant, ...) { gr <- try(AzureGraph::get_graph_login(tenant=tenant), silent=TRUE) if(inherits(gr, "try-error")) gr <- AzureGraph::create_graph_login(tenant=tenant, ...) gr }
/scratch/gouwar.j/cran-all/cranData/AzureContainers/R/graph_login.R
#' Utility functions to test whether an object is of the given class. #' #' @param object An R object #' #' @details #' These functions are simple wrappers around `R6::is.R6` and `inherits`. #' #' @return #' TRUE or FALSE depending on whether the object is an R6 object of the specified class. #' @rdname is #' @export is_acr <- function(object) { R6::is.R6(object) && inherits(object, "az_container_registry") } #' @rdname is #' @export is_aks <- function(object) { R6::is.R6(object) && inherits(object, "az_kubernetes_service") } #' @rdname is #' @export is_aci <- function(object) { R6::is.R6(object) && inherits(object, "az_container_instance") } #' @rdname is #' @export is_docker_registry <- function(object) { R6::is.R6(object) && inherits(object, "DockerRegistry") } #' @rdname is #' @export is_kubernetes_cluster <- function(object) { R6::is.R6(object) && inherits(object, "KubernetesCluster") }
/scratch/gouwar.j/cran-all/cranData/AzureContainers/R/is.R
#' Kubernetes cluster class #' #' Class representing a [Kubernetes](https://kubernetes.io/docs/home/) cluster. Note that this class can be used to interface with any Docker registry that supports the HTTP V2 API, not just those created via the Azure Container Registry service. Use the [kubernetes_cluster] function to instantiate new objects of this class. #' #' @docType class #' @section Methods: #' The following methods are available, in addition to those provided by the [AzureRMR::az_resource] class: #' - `new(...)`: Initialize a new registry object. See 'Initialization' below. #' - `create_registry_secret(registry, secret_name, email)`: Provide authentication secret for a Docker registry. See 'Secrets' below. #' - `delete_registry_secret(secret_name)`: Delete a registry authentication secret. #' - `create(file, ...)`: Creates a deployment or service from a file, using `kubectl create -f`. #' - `get(type, ...)`: Get information about resources, using `kubectl get`. #' - `run(name, image, ...)`: Run an image using `kubectl run --image`. #' - `expose(name, type, file, ...)`: Expose a service using `kubectl expose`. If the `file` argument is provided, read service information from there. #' - `delete(type, name, file, ...)`: Delete a resource (deployment or service) using `kubectl delete`. If the `file` argument is provided, read resource information from there. #' - `apply(file, ...)`: Apply a configuration file, using `kubectl apply -f`. #' - `show_dashboard(port, ...)`: Display the cluster dashboard. By default, use local port 30000. #' - `kubectl(cmd, ...)`: Run an arbitrary `kubectl` command on this cluster. Called by the other methods above. #' - `helm(cmd, ...)`: Run a `helm` command on this cluster. #' #' @section Initialization: #' The `new()` method takes one argument: `config`, the name of the file containing the configuration details for the cluster. This should be a YAML or JSON file in the standard Kubernetes configuration format. Set this to NULL to use the default `~/.kube/config` file. #' #' @section Secrets: #' The recommended way to allow a cluster to authenticate with a Docker registry is to give its service principal the appropriate role-based access. However, you can also authenticate with a username and password. To do this, call the `create_registry_secret` method with the following arguments: #' - `registry`: An object of class either [acr] representing an Azure Container Registry service, or [DockerRegistry] representing the registry itself. #' - `secret_name`: The name to give the secret. Defaults to the name of the registry server. #' - `email`: The email address for the Docker registry. #' #' @section Kubectl and helm: #' The methods for this class call the `kubectl` and `helm` commandline tools, passing the `--config` option to specify the configuration information for the cluster. This allows all the features supported by Kubernetes to be available immediately and with a minimum of effort, although it does require that the tools be installed. The returned object from a call to `kubectl` or `helm` will contain the following components: #' - `status`: The exit status. If this is `NA`, then the process was killed and had no exit status. #' - `stdout`: The standard output of the command, in a character scalar. #' - `stderr`: The standard error of the command, in a character scalar. #' - `timeout`: Whether the process was killed because of a timeout. #' - `cmdline`: The command line. #' #' The first four components are from `processx::run`; AzureContainers adds the last to make it easier to construct scripts that can be run outside R. #' #' @seealso #' [aks], [call_kubectl], [call_helm] #' #' [Kubectl commandline reference](https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' # get the cluster endpoint #' kubclus <- rg$get_aks("mycluster")$get_cluster() #' #' # get registry authentication secret #' kubclus$create_registry_secret(rg$get_acr("myregistry")) #' #' # deploy a service #' kubclus$create("deployment.yaml") #' #' # deploy a service from an Internet URL #' kubclus$create("https://example.com/deployment.yaml") #' #' # can also supply the deployment parameters inline #' kubclus$create(" #' apiVersion: extensions/v1beta1 #' kind: Deployment #' metadata: #' name: model1 #' spec: #' replicas: 1 #' template: #' metadata: #' labels: #' app: model1 #' spec: #' containers: #' - name: model1 #' image: myregistry.azurecr.io/model1 #' ports: #' - containerPort: 8000 #' imagePullSecrets: #' - name: myregistry.azurecr.io #' --- #' apiVersion: v1 #' kind: Service #' metadata: #' name: model1-svc #' spec: #' selector: #' app: model1 #' type: LoadBalancer #' ports: #' - protocol: TCP #' port: 8000") #' #' # track status #' kubclus$get("deployment") #' kubclus$get("service") #' #' } #' @export KubernetesCluster <- R6::R6Class("KubernetesCluster", public=list( initialize=function(config=NULL) { private$config <- config }, create_registry_secret=function(registry, secret_name=registry$server$hostname, email, ...) { if(is_acr(registry)) registry <- registry$get_docker_registry(as_admin=TRUE) if(!is_docker_registry(registry)) stop("Must supply a Docker registry object", call.=FALSE) if(is.null(registry$username) || is.null(registry$password)) stop("Docker registry object does not contain a username/password", call.=FALSE) cmd <- paste0("create secret docker-registry ", secret_name, " --docker-server=", registry$server$hostname, " --docker-username=", registry$username, " --docker-password=", registry$password, " --docker-email=", email) self$kubectl(cmd, ...) }, delete_registry_secret=function(secret_name, ...) { cmd <- paste0("delete secret ", secret_name) self$kubectl(cmd, ...) }, run=function(name, image, options="", ...) { cmd <- paste0("run ", name, " --image ", image, " ", options) self$kubectl(cmd, ...) }, expose=function(name, type=c("pod", "service", "replicationcontroller", "deployment", "replicaset"), file=NULL, options="", ...) { if(is.null(file)) { type <- match.arg(type) cmd <- paste0("expose ", type, " ", name, " ", options) } else { cmd <- paste0("expose -f ", make_file(file, ".yaml"), " ", options) } self$kubectl(cmd, ...) }, create=function(file, options="", ...) { cmd <- paste0("create -f ", make_file(file, ".yaml"), " ", options) self$kubectl(cmd, ...) }, apply=function(file, options="", ...) { cmd <- paste0("apply -f ", make_file(file, ".yaml"), " ", options) self$kubectl(cmd, ...) }, delete=function(type, name, file=NULL, options="", ...) { if(is.null(file)) { cmd <- paste0("delete ", type, " ", name, " ", options) } else { cmd <- paste0("delete -f ", make_file(file, ".yaml"), " ", options) } self$kubectl(cmd, ...) }, get=function(type, options="", ...) { cmd <- paste0("get ", type, " ", options) self$kubectl(cmd, ...) }, show_dashboard=function(port=30000, options="", ...) { cmd <- paste0("proxy --port=", port, " ", options) config <- if(!is.null(private$config)) paste0("--kubeconfig=", private$config) else NULL processx::process$new(.AzureContainers$kubectl, c(strsplit(cmd, " ", fixed=TRUE)[[1]], config), ...) url <- paste0("http://localhost:", port, "/api/v1/namespaces/kube-system/services/kubernetes-dashboard/proxy/#!/overview") message("If the dashboard does not appear, enter the URL '", url, "' in your browser") browseURL(url) }, kubectl=function(cmd="", ...) { call_kubectl(cmd, config=private$config, ...) }, helm=function(cmd="", ...) { call_helm(cmd, config=private$config, ...) } ), private=list( config=NULL )) #' Create a new Kubernetes cluster object #' #' @param config The name of the file containing the configuration details for the cluster. This should be a YAML or JSON file in the standard Kubernetes configuration format. Set this to NULL to use the default `~/.kube/config` file. #' @details #' Use this function to instantiate a new object of the `KubernetesCluster` class, for interacting with a Kubernetes cluster. #' @return #' An R6 object of class `KubernetesCluster`. #' #' @seealso #' [KubernetesCluster] for methods for working with the cluster, [call_kubectl], [call_helm] #' #' [docker_registry] for the corresponding function to create a Docker registry object #' #' @examples #' \dontrun{ #' #' kubernetes_cluster() #' kubernetes_cluster("myconfig.yaml") #' #' } #' @export kubernetes_cluster <- function(config=NULL) { KubernetesCluster$new(config) } # generate a file from a character vector to be passed to kubectl make_file <- function(file, ext="") { if(length(file) == 1 && (file.exists(file) || is_url(file))) return(file) out <- tempfile(fileext=ext) writeLines(file, out) out }
/scratch/gouwar.j/cran-all/cranData/AzureContainers/R/kubernetes_cluster.R
--- title: "Deploying a prediction service with Plumber" Author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Plumber model deployment} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- This document shows how you can deploy a fitted model as a web service using ACR, ACI and AKS. The framework used is [Plumber](https://www.rplumber.io), a package to expose your R code as a service via a REST API. ## Fit the model We'll fit a simple model for illustrative purposes, using the Boston housing dataset which ships with R (in the MASS package). To make the deployment process more interesting, the model we fit will be a random forest, using the randomForest package. ```r data(Boston, package="MASS") library(randomForest) # train a model for median house price as a function of the other variables bos_rf <- randomForest(medv ~ ., data=Boston, ntree=100) # save the model saveRDS(bos_rf, "bos_rf.rds") ``` ## Scoring script for plumber Now that we have the model, we also need a script to obtain predicted values from it given a set of inputs: ```r # save as bos_rf_score.R bos_rf <- readRDS("bos_rf.rds") library(randomForest) #* @param df data frame of variables #* @post /score function(req, df) { df <- as.data.frame(df) predict(bos_rf, df) } ``` This is fairly straightforward, but the comments may require some explanation. They are plumber annotations that tell it to call the function if the server receives a HTTP POST request with the path `/score`, and query parameter `df`. The value of the `df` parameter is then converted to a data frame, and passed to the randomForest `predict` method. ## Create a Dockerfile Let's package up the model and the scoring script into a Docker image. A Dockerfile to do this would look like the following. This uses the base image supplied by Plumber (`trestletech/plumber`), installs randomForest, and then adds the model and the above scoring script. Finally, it runs the code that will start the server and listen on port 8000. ```dockerfile # example Dockerfile to expose a plumber service FROM trestletech/plumber # install the randomForest package RUN R -e 'install.packages(c("randomForest"))' # copy model and scoring script RUN mkdir /data COPY bos_rf.rds /data COPY bos_rf_score.R /data WORKDIR /data # plumb and run server EXPOSE 8000 ENTRYPOINT ["R", "-e", \ "pr <- plumber::plumb('/data/bos_rf_score.R'); pr$run(host='0.0.0.0', port=8000)"] ``` ## Build and upload the image The code to store our image on Azure Container Registry is as follows. If you are running this code, you should substitute the values of `tenant`, `app` and/or `secret` from your Azure service principal. Similarly, if you are using the public Azure cloud, note that all ACR instances share a common DNS namespace, as do all ACI and AKS instances. For more information on how to create a service principal, see the [AzureRMR readme](https://github.com/cloudyr/AzureRMR). ```r library(AzureContainers) # create a resource group for our deployments deployresgrp <- AzureRMR::get_azure_login()$ get_subscription("sub_id")$ create_resource_group("deployresgrp", location="australiaeast") # create container registry deployreg_svc <- deployresgrp$create_acr("deployreg") # build image 'bos_rf' call_docker("build -t bos_rf .") # upload the image to Azure deployreg <- deployreg_svc$get_docker_registry(as_admin=TRUE) deployreg$push("bos_rf") ``` If you run this code, you should see a lot of output indicating that R is downloading, compiling and installing randomForest, and finally that the image is being pushed to Azure. (You will see this output even if your machine already has the randomForest package installed. This is because the package is being installed to the R session _inside the container_, which is distinct from the one running the code shown here.) All Docker calls in AzureContainers, like the one to build the image, return the actual docker commandline as the `cmdline` attribute of the (invisible) returned value. In this case, the commandline is `docker build -t bos_rf .` Similarly, the `push()` method actually involves two Docker calls, one to retag the image, and the second to do the actual pushing; the returned value in this case will be a 2-component list with the command lines being `docker tag bos_rf deployreg.azurecr.io/bos_rf` and `docker push deployreg.azurecr.io/bos_rf`. ## Deploy to an Azure Container Instance The simplest way to deploy a service is via a Container Instance. The following code creates a single running container which contains our model, listening on port 8000. ```r # create an instance with 2 cores and 8GB memory, and deploy our image deployaci <- deployresgrp$create_aci("deployaci", image="deployreg.azurecr.io/bos_rf", registry_creds=deployreg, cores=2, memory=8, ports=aci_ports(8000)) ``` Once the instance is running, let's call the prediction API with some sample data. By default, AzureContainers will assign the container a domain name with prefix taken from the instance name. The port is 8000 as specified in the Dockerfile, and the URI path is `/score` indicating we want to call the scoring function defined earlier. The data to be scored---the first 10 rows of the Boston dataset---is passed in the _body_ of the request as a named list, encoded as JSON. A feature of Plumber is that, when the body of the request is in this format, it will extract the elements of the list and pass them to the scoring function as named arguments. This makes it easy to pass around relatively large amounts of data, eg if the data is wide, or for scoring multiple rows at a time. For more information on how to create and interact with Plumber APIs, consult the [Plumber documentation](https://www.rplumber.io/docs/). ```r response <- httr::POST("http://deployaci.australiaeast.azurecontainer.io:8000/score", body=list(df=MASS::Boston[1:10,]), encode="json") httr::content(response, simplifyVector=TRUE) #> [1] 25.9269 22.0636 34.1876 33.7737 34.8081 27.6394 21.8007 22.3577 16.7812 18.9785 ``` ## Deploy to a Kubernetes cluster Deploying a service to a container instance is simple, but lacks many features that are important in a production setting. A better alternative for production purposes is to deploy to a Kubernetes cluster. Such a cluster can be created using Azure Kubernetes Service (AKS). ```r # create a Kubernetes cluster with 2 nodes, running Linux (the default) deployclus_svc <- deployresgrp$create_aks("deployclus", agent_pools=agent_pool("pool1", 2)) ``` Unlike an ACI resource, creating a Kubernetes cluster can take several minutes. By default, the `create_aks()` method will wait until the cluster provisioning is complete before it returns. Having created the cluster, we can deploy our model and create a service. We'll use a YAML configuration file to specify the details for the deployment and service API. The image to be deployed is the same as before. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: bos-rf spec: selector: matchLabels: app: bos-rf replicas: 1 template: metadata: labels: app: bos-rf spec: containers: - name: bos-rf image: deployreg.azurecr.io/bos_rf ports: - containerPort: 8000 resources: requests: cpu: 250m limits: cpu: 500m imagePullSecrets: - name: deployreg.azurecr.io --- apiVersion: v1 kind: Service metadata: name: bos-rf-svc spec: selector: app: bos-rf type: LoadBalancer ports: - protocol: TCP port: 8000 ``` The following code will obtain the cluster endpoint from the AKS resource and then deploy the image and service to the cluster. The configuration details for the `deployclus` cluster are stored in a file located in the R temporary directory; all of the cluster's methods will use this file. Unless told otherwise, AzureContainers does not touch your default Kubernetes configuration (`~/kube/config`). ```r # grant the cluster pull access to the registry deployreg_svc$add_role_assignment(deployclus_svc, "Acrpull") # get the cluster endpoint deployclus <- deployclus_svc$get_cluster() # create and start the service deployclus$create("bos_rf.yaml") ``` To check on the progress of the deployment, run the `get()` methods specifying the type and name of the resource to get information on. As with Docker, these correspond to calls to the `kubectl` commandline tool, and again, the actual commandline is stored as the `cmdline` attribute of the returned value. ```r deployclus$get("deployment bos-rf") #> Kubernetes operation: get deployment bos-rf --kubeconfig=".../kubeconfigxxxx" #> NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE #> bos-rf 1 1 1 1 5m svc <- read.table(text=deployclus$get("service bos-rf-svc")$stdout, header=TRUE) #> Kubernetes operation: get service bos-rf-svc --kubeconfig=".../kubeconfigxxxx" #> NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE #> bos-rf-svc LoadBalancer 10.0.8.189 52.187.249.58 8000:32276/TCP 5m ``` Once the service is up and running, as indicated by the presence of an external IP in the service details, let's test it with a HTTP request. The response should be the same as it was with the container instance. Notice how we extract the IP address from the service details above. ```r response <- httr::POST(paste0("http://", svc$EXTERNAL.IP[1], ":8000/score"), body=list(df=MASS::Boston[1:10, ]), encode="json") httr::content(response, simplifyVector=TRUE) #> [1] 25.9269 22.0636 34.1876 33.7737 34.8081 27.6394 21.8007 22.3577 16.7812 18.9785 ``` Finally, once we are done, we can tear down the service and deployment. Depending on the version of Kubernetes the cluster is running, deleting the service may take a few minutes. ```r deployclus$delete("service", "bos-rf-svc") deployclus$delete("deployment", "bos-rf") ``` And if required, we can also delete all the resources created here, by simply deleting the resource group (AzureContainers will prompt you for confirmation): ```r deployresgrp$delete() ``` ### Security note One important thing to note about the above example is that it is **insecure**. The Plumber service is exposed over HTTP, and there is no authentication layer: anyone on the Internet can contact the service and interact with it. Therefore, it's highly recommended that you should provide at least some level of authentication, as well as restricting the service to HTTPS only (this will require deploying an ingress controller to the Kubernetes cluster). You can also create the AKS resource as a private cluster; however, be aware that if you do this, you can only interact with the cluster endpoint from a host which is on the cluster's own subnet. ## See also Plumber is a relatively simple framework for creating and deploying services. As an alternative, the [RestRserve](https://restrserve.org) package is a more comprehensive framework, built on top of functionality provided by Rserve. It includes features such as automatic parallelisation, support for HTTPS, and support for basic and bearer authentication schemes. See the vignette "Deploying an ACI service with HTTPS and authentication" for more information.
/scratch/gouwar.j/cran-all/cranData/AzureContainers/inst/doc/vig01_plumber_deploy.Rmd
--- title: "Deploying an ACI service with HTTPS and authentication" Author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{RestRserve model deployment to ACI} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- This document shows how you can deploy a fitted model as a web service to an Azure Container Instance, using the [RestRserve](https://restrserve.org) package. RestRserve has a number of features that can make it more suitable than Plumber for building robust, production-ready services. These include: - Automatic parallelisation, based on the Rserve backend - Support for HTTPS - Support for basic and bearer HTTP authentication schemes In particular, we'll show how to implement the latter two features in this vignette. ## Deployment artifacts ### Model object For illustrative purposes, we'll reuse the random forest model and resource group from the Plumber deployment vignette. The code to fit the model is reproduced below for convenience. ```r data(Boston, package="MASS") library(randomForest) # train a model for median house price as a function of the other variables bos_rf <- randomForest(medv ~ ., data=Boston, ntree=100) # save the model saveRDS(bos_rf, "bos_rf.rds") ``` Basic authentication requires that we provide a list of usernames and passwords that grant access to the service. In a production setting, you would typically query a database, directory service or other backing store to authenticate users. To keep this example simple, we'll just create a flat file in the standard [Apache `.htpasswd` format](https://en.wikipedia.org/wiki/.htpasswd). In this format, the passwords are encrypted using a variety of algorithms, as a security measure; we'll use the bcrypt algorithm since an R implementation is available in the package of that name. ```r library(bcrypt) user_list <- list( c("user1", "password1"), c("user2", "password2") ) user_str <- sapply(user_list, function(x) paste(x[1], hashpw(x[2]), sep=":")) writeLines(user_str, ".htpasswd") ``` ### TLS certificate/private key To enable HTTPS, we need to provide a TLS certificate and private key. Again, in a production setting, the cert will typically be provided to you; for this vignette, we'll generate a self-signed cert instead. If you are running Linux or MacOS and have openssl installed, you can use that to generate the cert. Here, since we're already using Azure, we'll leverage the Azure Key Vault service to do it in a platform-independent manner. ```r library(AzureRMR) library(AzureContainers) library(AzureKeyVault) deployresgrp <- AzureRMR::get_azure_login()$ get_subscription("sub_id")$ get_resource_group("deployresgrp") # create the key vault vault_res <- deployresgrp$create_key_vault("mykeyvault") # get the vault endpoint kv <- vault_res$get_endpoint() # generate the certificate: use the DNS name of the ACI container endpoint kv$certificates$create( "deployrrsaci", "CN=deployrrsaci", x509=cert_x509_properties(dns_names=c("deployrrsaci.australiaeast.azurecontainer.io")) ) secret <- kv$secrets$get("deployrrsaci") key <- sub("-----BEGIN CERTIFICATE-----.*$", "", secret$value) cer <- sub("^.*-----END PRIVATE KEY-----\n", "", secret$value) writeLines(key, "cert.key") writeLines(cer, "cert.cer") ``` ### App Unlike Plumber, in RestRserve you define your service in R code, as a web app. An app is an object of R6 class `Application`: it contains various middleware and backend objects, and exposes the endpoint paths for your service. The overall server backend is of R6 class `BackendRserve`, and has responsibility for running and managing the app. The script below defines an app that exposes the scoring function on the `/score` path. Save this as `app.R`: ```r library(RestRserve) library(randomForest) bos_rf <- readRDS("bos_rf.rds") users <- local({ usr <- read.table(".htpasswd", sep=":", stringsAsFactors=FALSE) structure(usr[[2]], names=usr[[1]]) }) # scoring function: calls predict() on the provided dataset # - input is a jsonified data frame, in the body of a POST request # - output is the predicted values score <- function(request, response) { df <- jsonlite::fromJSON(rawToChar(request$body), simplifyDataFrame=TRUE) sc <- predict(bos_rf, df) response$set_body(jsonlite::toJSON(sc, auto_unbox=TRUE)) response$set_content_type("application/json") } # basic authentication against provided username/password values # use try() construct to ensure robustness against malicious input authenticate <- function(user, password) { res <- FALSE try({ res <- bcrypt::checkpw(password, users[[user]]) }, silent=TRUE) res } # chain of objects for app auth_backend <- AuthBackendBasic$new(FUN=authenticate) auth_mw <- AuthMiddleware$new(auth_backend=auth_backend, routes="/score") app <- Application$new(middleware=list(auth_mw)) app$add_post(path="/score", FUN=score) backend <- BackendRserve$new(app) ``` ### Dockerfile Here is the dockerfile for the image. Save this as `RestRserve-aci.dockerfile`: ```dockerfile FROM rexyai/restrserve # install required packages RUN Rscript -e "install.packages(c('randomForest', 'bcrypt'), repos='https://cloud.r-project.org')" # copy model object, cert files, user file and app script RUN mkdir /data COPY bos_rf.rds /data COPY .htpasswd /data COPY cert.cer /data COPY cert.key /data COPY app.R /data WORKDIR /data EXPOSE 8080 CMD ["Rscript", "-e", "source('app.R'); backend$start(app, http_port=-1, https.port=8080, tls.key=normalizePath('cert.key'), tls.cert=normalizePath('cert.cer'))"] ``` ## Create the container We now build the image and upload it to an Azure Container Registry. This assumes a fresh start; if you have created an ACR in this resource group already, you can reuse that instead by calling `get_acr` instead of `create_acr`. ```r call_docker("build -t rrs-aci -f RestRserve-aci.dockerfile .") deployreg_svc <- deployresgrp$create_acr("deployreg") deployreg <- deployreg_svc$get_docker_registry(as_admin=TRUE) deployreg$push("rrs-aci") ``` We can now deploy the image to ACI and obtain predicted values from the RestRserve app. Because we used a self-signed certificate in this example, we need to turn off the SSL verification check that curl performs by default. There may also be a short delay from when the container is started, to when the app is ready to accept requests. ```r # ensure the name of the resource matches the one on the cert we obtained above deployresgrp$create_aci("deployrrsaci", image="deployreg.azurecr.io/bos-rrs-https", registry_creds=deployreg, cores=2, memory=8, ports=aci_ports(8080)) Sys.sleep(30) # tell curl not to verify the cert unverified_handle <- function() { structure(list( handle=curl::handle_setopt(curl::new_handle(), ssl_verifypeer=FALSE), url="https://deployrrsaci.australiaeast.azurecontainer.io"), class="handle") } # send the username and password as part of the request response <- httr::POST("https://deployrrsaci.australiaeast.azurecontainer.io:8080/score", httr::authenticate("user1", "password1"), body=MASS::Boston[1:10, ], encode="json", handle=unverified_handle()) httr::content(response, simplifyVector=TRUE) #> [1] 25.9269 22.0636 34.1876 33.7737 34.8081 27.6394 21.8007 22.3577 16.7812 18.9785 ```
/scratch/gouwar.j/cran-all/cranData/AzureContainers/inst/doc/vig02_restrserve_deploy_aci.Rmd
--- title: "Securing an AKS deployment with Traefik" Author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Securing an AKS deployment with Traefik} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- The vignette "Deploying a prediction service with Plumber" showed you how to deploy a simple prediction service to a Kubernetes cluster in Azure. That deployment had a number of drawbacks: chiefly, it was open to the public, and used HTTP and thus was vulnerable to man-in-the-middle (MITM) attacks. Here, we'll show how to address these issues with basic authentication and HTTPS. To run the code in this vignette, you'll need the helm binary installed on your machine in addition to docker and kubectl. ## Model object and image We'll reuse the image from the Plumber vignette. The code and artifacts to build this image are reproduced below for convenience. Save the model object: ```r data(Boston, package="MASS") library(randomForest) # train a model for median house price as a function of the other variables bos_rf <- randomForest(medv ~ ., data=Boston, ntree=100) # save the model saveRDS(bos_rf, "bos_rf.rds") ``` Scoring script: ```r bos_rf <- readRDS("bos_rf.rds") library(randomForest) #* @param df data frame of variables #* @post /score function(req, df) { df <- as.data.frame(df) predict(bos_rf, df) } ``` Dockerfile: ```dockerfile FROM trestletech/plumber # install the randomForest package RUN R -e 'install.packages(c("randomForest"))' # copy model and scoring script RUN mkdir /data COPY bos_rf.rds /data COPY bos_rf_score.R /data WORKDIR /data # plumb and run server EXPOSE 8000 ENTRYPOINT ["R", "-e", \ "pr <- plumber::plumb('/data/bos_rf_score.R'); pr$run(host='0.0.0.0', port=8000)"] ``` Build and upload the image to ACR: ```r library(AzureContainers) # create a resource group for our deployments deployresgrp <- AzureRMR::get_azure_login()$ get_subscription("sub_id")$ create_resource_group("deployresgrp", location="australiaeast") # create container registry deployreg_svc <- deployresgrp$create_acr("deployreg") # build image 'bos_rf' call_docker("build -t bos_rf .") # upload the image to Azure deployreg <- deployreg_svc$get_docker_registry() deployreg$push("bos_rf") ``` ## Deploy to AKS Create a new AKS resource for this deployment: ```r # create a Kubernetes cluster deployclus_svc <- deployresgrp$create_aks("secureclus", agent_pools=agent_pool("pool1", 2)) # grant the cluster pull access to the registry deployreg_svc$add_role_assignment(deployclus_svc, "Acrpull") ``` ### Install traefik The middleware we'll use to enable HTTPS and authentication is [Traefik](https://traefik.io/traefik/). This features built-in integration with Let's Encrypt, which is a popular source for TLS certificates (necessary for HTTPS). An alternative to Traefik is [Nginx](https://www.nginx.com/). Deploying traefik and enabling HTTPS involves the following steps, on top of deploying the model service itself: - Install traefik - Assign a domain name to the cluster's public IP address - Deploy the ingress route The following yaml contains the configuration parameters for traefik. Insert your email address where indicated (it will be used to obtain a certificate from Let's Encrypt), and save this as `traefik_values.yaml`. ```yaml # traefik_values.yaml fullnameOverride: traefik replicas: 1 resources: limits: cpu: 500m memory: 500Mi requests: cpu: 100m memory: 200Mi externalTrafficPolicy: Local kubernetes: ingressClass: traefik ingressEndpoint: useDefaultPublishedService: true dashboard: enabled: false debug: enabled: false accessLogs: enabled: true fields: defaultMode: keep headers: defaultMode: keep names: Authorization: redact rbac: enabled: true acme: enabled: true email: "[email protected]" # insert your email address here staging: false challengeType: tls-alpn-01 ssl: enabled: true enforced: true permanentRedirect: true tlsMinVersion: VersionTLS12 cipherSuites: - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 - TLS_RSA_WITH_AES_128_GCM_SHA256 - TLS_RSA_WITH_AES_256_GCM_SHA384 - TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 ``` We can now install traefik: ```r # get the cluster endpoint deployclus <- deployclus_svc$get_cluster() deployclus$helm("repo add stable https://kubernetes-charts.storage.googleapis.com/") deployclus$helm("repo update") deployclus$helm("install traefik-ingress stable/traefik --namespace kube-system --values traefik_values.yaml") ``` ### Assign domain name Installing an ingress controller will create a public IP resource, which is the visible address for the cluster. It takes a minute or two for this resource to be created; once it appears, we assign a domain name to it. ```r for(i in 1:100) { res <- read.table(text=deployclus$get("service", "--all-namespaces")$stdout, header=TRUE, stringsAsFactors=FALSE) ip <- res$EXTERNAL.IP[res$NAME == "traefik"] if(ip != "<pending>") break Sys.sleep(10) } if(ip == "<pending>") stop("Ingress public IP not assigned") cluster_resources <- deployclus_svc$list_cluster_resources() found <- FALSE for(res in cluster_resources) { if(res$type != "Microsoft.Network/publicIPAddresses") next res$sync_fields() if(res$properties$ipAddress == ip) { found <- TRUE break } } if(!found) stop("Ingress public IP resource not found") # assign domain name to IP address res$do_operation( body=list( location=ip$location, properties=list( dnsSettings=list(domainNameLabel="secureclus"), publicIPAllocationMethod=ip$properties$publicIPAllocationMethod ) ), http_verb="PUT" ) ``` ### Generate an auth file We'll use Traefik to handle authentication details. While some packages like RestRserve can also authenticate users, a key benefit of assigning this to the ingress controller is that it frees our container to focus purely on the task of returning predicted values. For example, if we want to switch to a different kind of model, we can do so without having to copy over any authentication code. Using basic auth with Traefik requires an authentication file, in [Apache `.htpasswd` format](https://en.wikipedia.org/wiki/.htpasswd). Here is R code to create such a file. This is essentially the same code that is used in the "Deploying an ACI service with HTTPS and authentication" vignette. ```r library(bcrypt) user_list <- list( c("user1", "password1") ) user_str <- sapply(user_list, function(x) paste(x[1], hashpw(x[2]), sep=":")) writeLines(user_str, "auth") ``` ### Deploy the service The yaml for the deployment and service is the same as in the original Plumber vignette. The main difference is that we now create a separate `bos-rf` namespace for our objects, which is the recommended practice: it allows us to manage the service independently of any others that may exist on the cluster. Save the following as `secure_deploy.yaml`: ```yaml # deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: bos-rf namespace: bos-rf spec: selector: matchLabels: app: bos-rf replicas: 1 template: metadata: labels: app: bos-rf spec: containers: - name: bos-rf image: deployreg.azurecr.io/bos_rf # insert URI for your container registry/image ports: - containerPort: 8000 resources: requests: cpu: 250m limits: cpu: 500m --- apiVersion: v1 kind: Service metadata: name: bos-rf-svc namespace: bos-rf spec: selector: app: bos-rf ports: - protocol: TCP port: 8000 ``` The yaml to create the ingress route is below. Save this as `secure_ingress.yaml`. ```yaml # ingress.yaml apiVersion: extensions/v1beta1 kind: Ingress metadata: name: bos-rf-ingress namespace: bos-rf annotations: kubernetes.io/ingress.class: traefik ingress.kubernetes.io/auth-type: basic ingress.kubernetes.io/auth-secret: bos-rf-secret spec: rules: - host: secureclus.australiaeast.cloudapp.azure.com http: paths: - path: / backend: serviceName: bos-rf-svc servicePort: 8000 ``` We can now create the deployment, service, and ingress route: ```r deployclus$kubectl("create namespace bos-rf") deployclus$kubectl("create secret generic bos-rf-secret --from-file=auth --namespace bos-rf") deployclus$create("secure_deploy.yaml") deployclus$apply("secure_ingress.yaml") ``` ## Call the service Once the deployment is complete, we can obtain predicted values from it. Notice that we use the default HTTPS port for the request (port 443). While port 8000 is nominally exposed by the service, this is visible only within the cluster; it is connected to the external port 443 by Traefik. ```r response <- httr::POST("https://secureclus.australiaeast.cloudapp.azure.com/score", httr::authenticate("user1", "password1"), body=list(df=MASS::Boston[1:10,]), encode="json") httr::content(response, simplifyVector=TRUE) #> [1] 25.9269 22.0636 34.1876 33.7737 34.8081 27.6394 21.8007 22.3577 16.7812 18.9785 ``` ## Further comments In this vignette, we've secured the predictive service with a single username and password. While we could add more users to the authentication file, a more flexible and scalable solution is to use a frontend service, such as [Azure API Management](https://azure.microsoft.com/services/api-management/), or a directory service like [Azure Active Directory](https://azure.microsoft.com/services/active-directory/). The specifics will typically be determined by your organisation's IT infrastructure, and are beyond the scope of this vignette.
/scratch/gouwar.j/cran-all/cranData/AzureContainers/inst/doc/vig03_securing_aks_traefik.Rmd
--- title: "RBAC examples" Author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{RBAC examples} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- Working with role-based access control (RBAC) can be tricky, especially when containers are involved. This vignette provides example code snippets to handle some common use cases. ## Authenticating with a service principal from ACI to ACR This covers the scenario where you want to deploy an image to a container instance using a service principal, rather than the registry's admin credentials. ```r library(AzureGraph) az <- AzureRMR::get_azure_login() gr <- AzureGraph::get_graph_login() # create the registry rg <- az$ get_subscription("sub_id")$ get_resource_group("rgname") acr <- rg$create_acr("myacr") # create an app and give it pull access to the registry app <- gr$create_app("mycontainerapp") acr$add_role_assignment(app, "Acrpull") # build and push an image call_docker("build -t myimage .") reg <- acr$get_docker_registry() reg$push("myimage") # create an ACI credentials object containing the app ID and password creds <- aci_creds("myacr.azurecr.io", username=app$properties$appId, password=app$password) # create the instance, passing it the credentials object rg$create_aci("myinstance", image="myacr.azurecr.io/myimage", registry_creds=creds) ``` ## Authenticating with a service principal from AKS to ACR The corresponding scenario for a Kubernetes cluster is much simpler: we simply call the `add_role_assignment` method for the ACR object, passing it the AKS object. We'll reuse the registry from the above example. ```r # create the AKS resource aks <- rg$create_aks("myaks", agent_pools=aks_pools("pool1", 2), enable_rbac=TRUE) # give the cluster pull access to the registry reg$add_role_assignment(aks, "Acrpull") ``` After giving the cluster the necessary permissions, you can then deploy images from the registry as normal. ## Creating an AKS resource and reusing an existing service principal This scenario is most relevant when creating an AKS resource in an automated environment, ie without a logged-in user's credentials. Currently, creating an AKS resource also involves creating an associated service principal, for the cluster to manage its sub-resources. In turn, creating this service principal will attempt to get the credentials for the logged-in user, which fails if there is no user present. To avoid this, you can create an app ahead of time and pass it to `create_aks`: ```r # login to ARM and MS Graph with client credentials flow # your app must have the right permissions to work with ARM and Graph az <- AzureRMR::create_azure_login("mytenant", app="app_id", password="clientsecret") gr <- AzureGraph::create_graph_login("mytenant", app="app_id", password="clientsecret") app <- gr$create_app("myaksapp") az$get_subscription("sub_id")$ get_resource_group("rgname")$ create_aks("myaks", cluster_service_principal=app, agent_pools=aks_pools("pool1", 2, "Standard_DS2_v2", "Linux")) ``` ## Integrating AKS with Azure Active Directory Integrating AKS and AAD requires creating two registered apps, the client and server, and giving them permissions to talk to each other. Most of the work here is actually done using the AzureGraph package; once the apps are correctly configured, we then pass them to the `create_aks` method. You'll need to be an administrator for your AAD tenant to carry out these steps. ```r # create the server app srvapp <- gr$create_app("akssrvapp") # save the app ID and password srvapp_id <- srvapp$properties$appId srvapp_pwd <- srvapp$password # update group membership claims srvapp$update(groupMembershipClaims="all") # update API permissions (Directory.Read.All scope & role, User.Read.All scope) srvapp$update(requiredResourceAccess=list( list( resourceAppId="00000003-0000-0000-c000-000000000000", resourceAccess=list( list(id="06da0dbc-49e2-44d2-8312-53f166ab848a", type="Scope"), list(id="e1fe6dd8-ba31-4d61-89e7-88639da4683d", type="Scope"), list(id="7ab1d382-f21e-4acd-a863-ba3e13f7da61", type="Role") ) ) )) # add OAuth permissions API srvapp_api <- srvapp$properties$api srvapp_newapi_id <- uuid::UUIDgenerate() srvapp_api$oauth2PermissionScopes <- list( list( adminConsentDescription="AKS", adminConsentDisplayName="AKS", id=srvapp_newapi_id, isEnabled=TRUE, type="User", userConsentDescription="AKS", userConsentDisplayName="AKS", value="AKS" ) ) srvapp$update(api=srvapp_api, identifierUris=I(sprintf("api://%s", srvapp_id))) # create the client app cliapp <- gr$create_app("akscliapp", isFallbackPublicClient=TRUE, publicClient=list(redirectUris=list("https://akscliapp")) ) cliapp_id <- cliapp$properties$appId # tell the server app to trust the client srvapp_api <- srvapp$properties$api srvapp_api$preAuthorizedApplications <- list( list( appId=cliapp_id, permissionIds=list(srvapp_newapi_id) ) ) srvapp$update(api=srvapp_api) ``` Once the apps have been configured, we still have to grant admin consent. This is best done in the Azure Portal: - Click on "Azure Active Directory" in the list of items on the left - In the AAD blade, click on "App registrations" - Find the app that you created, and click on it. - Click on "API permissions". - Click on the "Grant admin consent" button at the bottom of the pane. ![](perms2.png "permissions") Having created and configured the apps, we can then create the cluster resource. ```r rg$create_aks("akswithaad", agent_pools=aks_pools("pool1", 2), properties=list( aadProfile=list( clientAppID=cliapp_id, serverAppID=srvapp_id, serverAppSecret=srvapp_pwd ) ), enable_rbac=TRUE ) ``` For more information, see the following Microsoft Docs pages: - [Enable Azure Active Directory integration](https://docs.microsoft.com/en-us/azure/aks/azure-ad-integration) - [Use Kubernetes RBAC with Azure AD integration](https://docs.microsoft.com/en-us/azure/aks/azure-ad-rbac)
/scratch/gouwar.j/cran-all/cranData/AzureContainers/inst/doc/vig04_rbac.Rmd
--- title: "Deploying a prediction service with Plumber" Author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Plumber model deployment} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- This document shows how you can deploy a fitted model as a web service using ACR, ACI and AKS. The framework used is [Plumber](https://www.rplumber.io), a package to expose your R code as a service via a REST API. ## Fit the model We'll fit a simple model for illustrative purposes, using the Boston housing dataset which ships with R (in the MASS package). To make the deployment process more interesting, the model we fit will be a random forest, using the randomForest package. ```r data(Boston, package="MASS") library(randomForest) # train a model for median house price as a function of the other variables bos_rf <- randomForest(medv ~ ., data=Boston, ntree=100) # save the model saveRDS(bos_rf, "bos_rf.rds") ``` ## Scoring script for plumber Now that we have the model, we also need a script to obtain predicted values from it given a set of inputs: ```r # save as bos_rf_score.R bos_rf <- readRDS("bos_rf.rds") library(randomForest) #* @param df data frame of variables #* @post /score function(req, df) { df <- as.data.frame(df) predict(bos_rf, df) } ``` This is fairly straightforward, but the comments may require some explanation. They are plumber annotations that tell it to call the function if the server receives a HTTP POST request with the path `/score`, and query parameter `df`. The value of the `df` parameter is then converted to a data frame, and passed to the randomForest `predict` method. ## Create a Dockerfile Let's package up the model and the scoring script into a Docker image. A Dockerfile to do this would look like the following. This uses the base image supplied by Plumber (`trestletech/plumber`), installs randomForest, and then adds the model and the above scoring script. Finally, it runs the code that will start the server and listen on port 8000. ```dockerfile # example Dockerfile to expose a plumber service FROM trestletech/plumber # install the randomForest package RUN R -e 'install.packages(c("randomForest"))' # copy model and scoring script RUN mkdir /data COPY bos_rf.rds /data COPY bos_rf_score.R /data WORKDIR /data # plumb and run server EXPOSE 8000 ENTRYPOINT ["R", "-e", \ "pr <- plumber::plumb('/data/bos_rf_score.R'); pr$run(host='0.0.0.0', port=8000)"] ``` ## Build and upload the image The code to store our image on Azure Container Registry is as follows. If you are running this code, you should substitute the values of `tenant`, `app` and/or `secret` from your Azure service principal. Similarly, if you are using the public Azure cloud, note that all ACR instances share a common DNS namespace, as do all ACI and AKS instances. For more information on how to create a service principal, see the [AzureRMR readme](https://github.com/cloudyr/AzureRMR). ```r library(AzureContainers) # create a resource group for our deployments deployresgrp <- AzureRMR::get_azure_login()$ get_subscription("sub_id")$ create_resource_group("deployresgrp", location="australiaeast") # create container registry deployreg_svc <- deployresgrp$create_acr("deployreg") # build image 'bos_rf' call_docker("build -t bos_rf .") # upload the image to Azure deployreg <- deployreg_svc$get_docker_registry(as_admin=TRUE) deployreg$push("bos_rf") ``` If you run this code, you should see a lot of output indicating that R is downloading, compiling and installing randomForest, and finally that the image is being pushed to Azure. (You will see this output even if your machine already has the randomForest package installed. This is because the package is being installed to the R session _inside the container_, which is distinct from the one running the code shown here.) All Docker calls in AzureContainers, like the one to build the image, return the actual docker commandline as the `cmdline` attribute of the (invisible) returned value. In this case, the commandline is `docker build -t bos_rf .` Similarly, the `push()` method actually involves two Docker calls, one to retag the image, and the second to do the actual pushing; the returned value in this case will be a 2-component list with the command lines being `docker tag bos_rf deployreg.azurecr.io/bos_rf` and `docker push deployreg.azurecr.io/bos_rf`. ## Deploy to an Azure Container Instance The simplest way to deploy a service is via a Container Instance. The following code creates a single running container which contains our model, listening on port 8000. ```r # create an instance with 2 cores and 8GB memory, and deploy our image deployaci <- deployresgrp$create_aci("deployaci", image="deployreg.azurecr.io/bos_rf", registry_creds=deployreg, cores=2, memory=8, ports=aci_ports(8000)) ``` Once the instance is running, let's call the prediction API with some sample data. By default, AzureContainers will assign the container a domain name with prefix taken from the instance name. The port is 8000 as specified in the Dockerfile, and the URI path is `/score` indicating we want to call the scoring function defined earlier. The data to be scored---the first 10 rows of the Boston dataset---is passed in the _body_ of the request as a named list, encoded as JSON. A feature of Plumber is that, when the body of the request is in this format, it will extract the elements of the list and pass them to the scoring function as named arguments. This makes it easy to pass around relatively large amounts of data, eg if the data is wide, or for scoring multiple rows at a time. For more information on how to create and interact with Plumber APIs, consult the [Plumber documentation](https://www.rplumber.io/docs/). ```r response <- httr::POST("http://deployaci.australiaeast.azurecontainer.io:8000/score", body=list(df=MASS::Boston[1:10,]), encode="json") httr::content(response, simplifyVector=TRUE) #> [1] 25.9269 22.0636 34.1876 33.7737 34.8081 27.6394 21.8007 22.3577 16.7812 18.9785 ``` ## Deploy to a Kubernetes cluster Deploying a service to a container instance is simple, but lacks many features that are important in a production setting. A better alternative for production purposes is to deploy to a Kubernetes cluster. Such a cluster can be created using Azure Kubernetes Service (AKS). ```r # create a Kubernetes cluster with 2 nodes, running Linux (the default) deployclus_svc <- deployresgrp$create_aks("deployclus", agent_pools=agent_pool("pool1", 2)) ``` Unlike an ACI resource, creating a Kubernetes cluster can take several minutes. By default, the `create_aks()` method will wait until the cluster provisioning is complete before it returns. Having created the cluster, we can deploy our model and create a service. We'll use a YAML configuration file to specify the details for the deployment and service API. The image to be deployed is the same as before. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: bos-rf spec: selector: matchLabels: app: bos-rf replicas: 1 template: metadata: labels: app: bos-rf spec: containers: - name: bos-rf image: deployreg.azurecr.io/bos_rf ports: - containerPort: 8000 resources: requests: cpu: 250m limits: cpu: 500m imagePullSecrets: - name: deployreg.azurecr.io --- apiVersion: v1 kind: Service metadata: name: bos-rf-svc spec: selector: app: bos-rf type: LoadBalancer ports: - protocol: TCP port: 8000 ``` The following code will obtain the cluster endpoint from the AKS resource and then deploy the image and service to the cluster. The configuration details for the `deployclus` cluster are stored in a file located in the R temporary directory; all of the cluster's methods will use this file. Unless told otherwise, AzureContainers does not touch your default Kubernetes configuration (`~/kube/config`). ```r # grant the cluster pull access to the registry deployreg_svc$add_role_assignment(deployclus_svc, "Acrpull") # get the cluster endpoint deployclus <- deployclus_svc$get_cluster() # create and start the service deployclus$create("bos_rf.yaml") ``` To check on the progress of the deployment, run the `get()` methods specifying the type and name of the resource to get information on. As with Docker, these correspond to calls to the `kubectl` commandline tool, and again, the actual commandline is stored as the `cmdline` attribute of the returned value. ```r deployclus$get("deployment bos-rf") #> Kubernetes operation: get deployment bos-rf --kubeconfig=".../kubeconfigxxxx" #> NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE #> bos-rf 1 1 1 1 5m svc <- read.table(text=deployclus$get("service bos-rf-svc")$stdout, header=TRUE) #> Kubernetes operation: get service bos-rf-svc --kubeconfig=".../kubeconfigxxxx" #> NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE #> bos-rf-svc LoadBalancer 10.0.8.189 52.187.249.58 8000:32276/TCP 5m ``` Once the service is up and running, as indicated by the presence of an external IP in the service details, let's test it with a HTTP request. The response should be the same as it was with the container instance. Notice how we extract the IP address from the service details above. ```r response <- httr::POST(paste0("http://", svc$EXTERNAL.IP[1], ":8000/score"), body=list(df=MASS::Boston[1:10, ]), encode="json") httr::content(response, simplifyVector=TRUE) #> [1] 25.9269 22.0636 34.1876 33.7737 34.8081 27.6394 21.8007 22.3577 16.7812 18.9785 ``` Finally, once we are done, we can tear down the service and deployment. Depending on the version of Kubernetes the cluster is running, deleting the service may take a few minutes. ```r deployclus$delete("service", "bos-rf-svc") deployclus$delete("deployment", "bos-rf") ``` And if required, we can also delete all the resources created here, by simply deleting the resource group (AzureContainers will prompt you for confirmation): ```r deployresgrp$delete() ``` ### Security note One important thing to note about the above example is that it is **insecure**. The Plumber service is exposed over HTTP, and there is no authentication layer: anyone on the Internet can contact the service and interact with it. Therefore, it's highly recommended that you should provide at least some level of authentication, as well as restricting the service to HTTPS only (this will require deploying an ingress controller to the Kubernetes cluster). You can also create the AKS resource as a private cluster; however, be aware that if you do this, you can only interact with the cluster endpoint from a host which is on the cluster's own subnet. ## See also Plumber is a relatively simple framework for creating and deploying services. As an alternative, the [RestRserve](https://restrserve.org) package is a more comprehensive framework, built on top of functionality provided by Rserve. It includes features such as automatic parallelisation, support for HTTPS, and support for basic and bearer authentication schemes. See the vignette "Deploying an ACI service with HTTPS and authentication" for more information.
/scratch/gouwar.j/cran-all/cranData/AzureContainers/vignettes/vig01_plumber_deploy.Rmd
--- title: "Deploying an ACI service with HTTPS and authentication" Author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{RestRserve model deployment to ACI} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- This document shows how you can deploy a fitted model as a web service to an Azure Container Instance, using the [RestRserve](https://restrserve.org) package. RestRserve has a number of features that can make it more suitable than Plumber for building robust, production-ready services. These include: - Automatic parallelisation, based on the Rserve backend - Support for HTTPS - Support for basic and bearer HTTP authentication schemes In particular, we'll show how to implement the latter two features in this vignette. ## Deployment artifacts ### Model object For illustrative purposes, we'll reuse the random forest model and resource group from the Plumber deployment vignette. The code to fit the model is reproduced below for convenience. ```r data(Boston, package="MASS") library(randomForest) # train a model for median house price as a function of the other variables bos_rf <- randomForest(medv ~ ., data=Boston, ntree=100) # save the model saveRDS(bos_rf, "bos_rf.rds") ``` Basic authentication requires that we provide a list of usernames and passwords that grant access to the service. In a production setting, you would typically query a database, directory service or other backing store to authenticate users. To keep this example simple, we'll just create a flat file in the standard [Apache `.htpasswd` format](https://en.wikipedia.org/wiki/.htpasswd). In this format, the passwords are encrypted using a variety of algorithms, as a security measure; we'll use the bcrypt algorithm since an R implementation is available in the package of that name. ```r library(bcrypt) user_list <- list( c("user1", "password1"), c("user2", "password2") ) user_str <- sapply(user_list, function(x) paste(x[1], hashpw(x[2]), sep=":")) writeLines(user_str, ".htpasswd") ``` ### TLS certificate/private key To enable HTTPS, we need to provide a TLS certificate and private key. Again, in a production setting, the cert will typically be provided to you; for this vignette, we'll generate a self-signed cert instead. If you are running Linux or MacOS and have openssl installed, you can use that to generate the cert. Here, since we're already using Azure, we'll leverage the Azure Key Vault service to do it in a platform-independent manner. ```r library(AzureRMR) library(AzureContainers) library(AzureKeyVault) deployresgrp <- AzureRMR::get_azure_login()$ get_subscription("sub_id")$ get_resource_group("deployresgrp") # create the key vault vault_res <- deployresgrp$create_key_vault("mykeyvault") # get the vault endpoint kv <- vault_res$get_endpoint() # generate the certificate: use the DNS name of the ACI container endpoint kv$certificates$create( "deployrrsaci", "CN=deployrrsaci", x509=cert_x509_properties(dns_names=c("deployrrsaci.australiaeast.azurecontainer.io")) ) secret <- kv$secrets$get("deployrrsaci") key <- sub("-----BEGIN CERTIFICATE-----.*$", "", secret$value) cer <- sub("^.*-----END PRIVATE KEY-----\n", "", secret$value) writeLines(key, "cert.key") writeLines(cer, "cert.cer") ``` ### App Unlike Plumber, in RestRserve you define your service in R code, as a web app. An app is an object of R6 class `Application`: it contains various middleware and backend objects, and exposes the endpoint paths for your service. The overall server backend is of R6 class `BackendRserve`, and has responsibility for running and managing the app. The script below defines an app that exposes the scoring function on the `/score` path. Save this as `app.R`: ```r library(RestRserve) library(randomForest) bos_rf <- readRDS("bos_rf.rds") users <- local({ usr <- read.table(".htpasswd", sep=":", stringsAsFactors=FALSE) structure(usr[[2]], names=usr[[1]]) }) # scoring function: calls predict() on the provided dataset # - input is a jsonified data frame, in the body of a POST request # - output is the predicted values score <- function(request, response) { df <- jsonlite::fromJSON(rawToChar(request$body), simplifyDataFrame=TRUE) sc <- predict(bos_rf, df) response$set_body(jsonlite::toJSON(sc, auto_unbox=TRUE)) response$set_content_type("application/json") } # basic authentication against provided username/password values # use try() construct to ensure robustness against malicious input authenticate <- function(user, password) { res <- FALSE try({ res <- bcrypt::checkpw(password, users[[user]]) }, silent=TRUE) res } # chain of objects for app auth_backend <- AuthBackendBasic$new(FUN=authenticate) auth_mw <- AuthMiddleware$new(auth_backend=auth_backend, routes="/score") app <- Application$new(middleware=list(auth_mw)) app$add_post(path="/score", FUN=score) backend <- BackendRserve$new(app) ``` ### Dockerfile Here is the dockerfile for the image. Save this as `RestRserve-aci.dockerfile`: ```dockerfile FROM rexyai/restrserve # install required packages RUN Rscript -e "install.packages(c('randomForest', 'bcrypt'), repos='https://cloud.r-project.org')" # copy model object, cert files, user file and app script RUN mkdir /data COPY bos_rf.rds /data COPY .htpasswd /data COPY cert.cer /data COPY cert.key /data COPY app.R /data WORKDIR /data EXPOSE 8080 CMD ["Rscript", "-e", "source('app.R'); backend$start(app, http_port=-1, https.port=8080, tls.key=normalizePath('cert.key'), tls.cert=normalizePath('cert.cer'))"] ``` ## Create the container We now build the image and upload it to an Azure Container Registry. This assumes a fresh start; if you have created an ACR in this resource group already, you can reuse that instead by calling `get_acr` instead of `create_acr`. ```r call_docker("build -t rrs-aci -f RestRserve-aci.dockerfile .") deployreg_svc <- deployresgrp$create_acr("deployreg") deployreg <- deployreg_svc$get_docker_registry(as_admin=TRUE) deployreg$push("rrs-aci") ``` We can now deploy the image to ACI and obtain predicted values from the RestRserve app. Because we used a self-signed certificate in this example, we need to turn off the SSL verification check that curl performs by default. There may also be a short delay from when the container is started, to when the app is ready to accept requests. ```r # ensure the name of the resource matches the one on the cert we obtained above deployresgrp$create_aci("deployrrsaci", image="deployreg.azurecr.io/bos-rrs-https", registry_creds=deployreg, cores=2, memory=8, ports=aci_ports(8080)) Sys.sleep(30) # tell curl not to verify the cert unverified_handle <- function() { structure(list( handle=curl::handle_setopt(curl::new_handle(), ssl_verifypeer=FALSE), url="https://deployrrsaci.australiaeast.azurecontainer.io"), class="handle") } # send the username and password as part of the request response <- httr::POST("https://deployrrsaci.australiaeast.azurecontainer.io:8080/score", httr::authenticate("user1", "password1"), body=MASS::Boston[1:10, ], encode="json", handle=unverified_handle()) httr::content(response, simplifyVector=TRUE) #> [1] 25.9269 22.0636 34.1876 33.7737 34.8081 27.6394 21.8007 22.3577 16.7812 18.9785 ```
/scratch/gouwar.j/cran-all/cranData/AzureContainers/vignettes/vig02_restrserve_deploy_aci.Rmd
--- title: "Securing an AKS deployment with Traefik" Author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Securing an AKS deployment with Traefik} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- The vignette "Deploying a prediction service with Plumber" showed you how to deploy a simple prediction service to a Kubernetes cluster in Azure. That deployment had a number of drawbacks: chiefly, it was open to the public, and used HTTP and thus was vulnerable to man-in-the-middle (MITM) attacks. Here, we'll show how to address these issues with basic authentication and HTTPS. To run the code in this vignette, you'll need the helm binary installed on your machine in addition to docker and kubectl. ## Model object and image We'll reuse the image from the Plumber vignette. The code and artifacts to build this image are reproduced below for convenience. Save the model object: ```r data(Boston, package="MASS") library(randomForest) # train a model for median house price as a function of the other variables bos_rf <- randomForest(medv ~ ., data=Boston, ntree=100) # save the model saveRDS(bos_rf, "bos_rf.rds") ``` Scoring script: ```r bos_rf <- readRDS("bos_rf.rds") library(randomForest) #* @param df data frame of variables #* @post /score function(req, df) { df <- as.data.frame(df) predict(bos_rf, df) } ``` Dockerfile: ```dockerfile FROM trestletech/plumber # install the randomForest package RUN R -e 'install.packages(c("randomForest"))' # copy model and scoring script RUN mkdir /data COPY bos_rf.rds /data COPY bos_rf_score.R /data WORKDIR /data # plumb and run server EXPOSE 8000 ENTRYPOINT ["R", "-e", \ "pr <- plumber::plumb('/data/bos_rf_score.R'); pr$run(host='0.0.0.0', port=8000)"] ``` Build and upload the image to ACR: ```r library(AzureContainers) # create a resource group for our deployments deployresgrp <- AzureRMR::get_azure_login()$ get_subscription("sub_id")$ create_resource_group("deployresgrp", location="australiaeast") # create container registry deployreg_svc <- deployresgrp$create_acr("deployreg") # build image 'bos_rf' call_docker("build -t bos_rf .") # upload the image to Azure deployreg <- deployreg_svc$get_docker_registry() deployreg$push("bos_rf") ``` ## Deploy to AKS Create a new AKS resource for this deployment: ```r # create a Kubernetes cluster deployclus_svc <- deployresgrp$create_aks("secureclus", agent_pools=agent_pool("pool1", 2)) # grant the cluster pull access to the registry deployreg_svc$add_role_assignment(deployclus_svc, "Acrpull") ``` ### Install traefik The middleware we'll use to enable HTTPS and authentication is [Traefik](https://traefik.io/traefik/). This features built-in integration with Let's Encrypt, which is a popular source for TLS certificates (necessary for HTTPS). An alternative to Traefik is [Nginx](https://www.nginx.com/). Deploying traefik and enabling HTTPS involves the following steps, on top of deploying the model service itself: - Install traefik - Assign a domain name to the cluster's public IP address - Deploy the ingress route The following yaml contains the configuration parameters for traefik. Insert your email address where indicated (it will be used to obtain a certificate from Let's Encrypt), and save this as `traefik_values.yaml`. ```yaml # traefik_values.yaml fullnameOverride: traefik replicas: 1 resources: limits: cpu: 500m memory: 500Mi requests: cpu: 100m memory: 200Mi externalTrafficPolicy: Local kubernetes: ingressClass: traefik ingressEndpoint: useDefaultPublishedService: true dashboard: enabled: false debug: enabled: false accessLogs: enabled: true fields: defaultMode: keep headers: defaultMode: keep names: Authorization: redact rbac: enabled: true acme: enabled: true email: "[email protected]" # insert your email address here staging: false challengeType: tls-alpn-01 ssl: enabled: true enforced: true permanentRedirect: true tlsMinVersion: VersionTLS12 cipherSuites: - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 - TLS_RSA_WITH_AES_128_GCM_SHA256 - TLS_RSA_WITH_AES_256_GCM_SHA384 - TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 ``` We can now install traefik: ```r # get the cluster endpoint deployclus <- deployclus_svc$get_cluster() deployclus$helm("repo add stable https://kubernetes-charts.storage.googleapis.com/") deployclus$helm("repo update") deployclus$helm("install traefik-ingress stable/traefik --namespace kube-system --values traefik_values.yaml") ``` ### Assign domain name Installing an ingress controller will create a public IP resource, which is the visible address for the cluster. It takes a minute or two for this resource to be created; once it appears, we assign a domain name to it. ```r for(i in 1:100) { res <- read.table(text=deployclus$get("service", "--all-namespaces")$stdout, header=TRUE, stringsAsFactors=FALSE) ip <- res$EXTERNAL.IP[res$NAME == "traefik"] if(ip != "<pending>") break Sys.sleep(10) } if(ip == "<pending>") stop("Ingress public IP not assigned") cluster_resources <- deployclus_svc$list_cluster_resources() found <- FALSE for(res in cluster_resources) { if(res$type != "Microsoft.Network/publicIPAddresses") next res$sync_fields() if(res$properties$ipAddress == ip) { found <- TRUE break } } if(!found) stop("Ingress public IP resource not found") # assign domain name to IP address res$do_operation( body=list( location=ip$location, properties=list( dnsSettings=list(domainNameLabel="secureclus"), publicIPAllocationMethod=ip$properties$publicIPAllocationMethod ) ), http_verb="PUT" ) ``` ### Generate an auth file We'll use Traefik to handle authentication details. While some packages like RestRserve can also authenticate users, a key benefit of assigning this to the ingress controller is that it frees our container to focus purely on the task of returning predicted values. For example, if we want to switch to a different kind of model, we can do so without having to copy over any authentication code. Using basic auth with Traefik requires an authentication file, in [Apache `.htpasswd` format](https://en.wikipedia.org/wiki/.htpasswd). Here is R code to create such a file. This is essentially the same code that is used in the "Deploying an ACI service with HTTPS and authentication" vignette. ```r library(bcrypt) user_list <- list( c("user1", "password1") ) user_str <- sapply(user_list, function(x) paste(x[1], hashpw(x[2]), sep=":")) writeLines(user_str, "auth") ``` ### Deploy the service The yaml for the deployment and service is the same as in the original Plumber vignette. The main difference is that we now create a separate `bos-rf` namespace for our objects, which is the recommended practice: it allows us to manage the service independently of any others that may exist on the cluster. Save the following as `secure_deploy.yaml`: ```yaml # deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: bos-rf namespace: bos-rf spec: selector: matchLabels: app: bos-rf replicas: 1 template: metadata: labels: app: bos-rf spec: containers: - name: bos-rf image: deployreg.azurecr.io/bos_rf # insert URI for your container registry/image ports: - containerPort: 8000 resources: requests: cpu: 250m limits: cpu: 500m --- apiVersion: v1 kind: Service metadata: name: bos-rf-svc namespace: bos-rf spec: selector: app: bos-rf ports: - protocol: TCP port: 8000 ``` The yaml to create the ingress route is below. Save this as `secure_ingress.yaml`. ```yaml # ingress.yaml apiVersion: extensions/v1beta1 kind: Ingress metadata: name: bos-rf-ingress namespace: bos-rf annotations: kubernetes.io/ingress.class: traefik ingress.kubernetes.io/auth-type: basic ingress.kubernetes.io/auth-secret: bos-rf-secret spec: rules: - host: secureclus.australiaeast.cloudapp.azure.com http: paths: - path: / backend: serviceName: bos-rf-svc servicePort: 8000 ``` We can now create the deployment, service, and ingress route: ```r deployclus$kubectl("create namespace bos-rf") deployclus$kubectl("create secret generic bos-rf-secret --from-file=auth --namespace bos-rf") deployclus$create("secure_deploy.yaml") deployclus$apply("secure_ingress.yaml") ``` ## Call the service Once the deployment is complete, we can obtain predicted values from it. Notice that we use the default HTTPS port for the request (port 443). While port 8000 is nominally exposed by the service, this is visible only within the cluster; it is connected to the external port 443 by Traefik. ```r response <- httr::POST("https://secureclus.australiaeast.cloudapp.azure.com/score", httr::authenticate("user1", "password1"), body=list(df=MASS::Boston[1:10,]), encode="json") httr::content(response, simplifyVector=TRUE) #> [1] 25.9269 22.0636 34.1876 33.7737 34.8081 27.6394 21.8007 22.3577 16.7812 18.9785 ``` ## Further comments In this vignette, we've secured the predictive service with a single username and password. While we could add more users to the authentication file, a more flexible and scalable solution is to use a frontend service, such as [Azure API Management](https://azure.microsoft.com/services/api-management/), or a directory service like [Azure Active Directory](https://azure.microsoft.com/services/active-directory/). The specifics will typically be determined by your organisation's IT infrastructure, and are beyond the scope of this vignette.
/scratch/gouwar.j/cran-all/cranData/AzureContainers/vignettes/vig03_securing_aks_traefik.Rmd
--- title: "RBAC examples" Author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{RBAC examples} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- Working with role-based access control (RBAC) can be tricky, especially when containers are involved. This vignette provides example code snippets to handle some common use cases. ## Authenticating with a service principal from ACI to ACR This covers the scenario where you want to deploy an image to a container instance using a service principal, rather than the registry's admin credentials. ```r library(AzureGraph) az <- AzureRMR::get_azure_login() gr <- AzureGraph::get_graph_login() # create the registry rg <- az$ get_subscription("sub_id")$ get_resource_group("rgname") acr <- rg$create_acr("myacr") # create an app and give it pull access to the registry app <- gr$create_app("mycontainerapp") acr$add_role_assignment(app, "Acrpull") # build and push an image call_docker("build -t myimage .") reg <- acr$get_docker_registry() reg$push("myimage") # create an ACI credentials object containing the app ID and password creds <- aci_creds("myacr.azurecr.io", username=app$properties$appId, password=app$password) # create the instance, passing it the credentials object rg$create_aci("myinstance", image="myacr.azurecr.io/myimage", registry_creds=creds) ``` ## Authenticating with a service principal from AKS to ACR The corresponding scenario for a Kubernetes cluster is much simpler: we simply call the `add_role_assignment` method for the ACR object, passing it the AKS object. We'll reuse the registry from the above example. ```r # create the AKS resource aks <- rg$create_aks("myaks", agent_pools=aks_pools("pool1", 2), enable_rbac=TRUE) # give the cluster pull access to the registry reg$add_role_assignment(aks, "Acrpull") ``` After giving the cluster the necessary permissions, you can then deploy images from the registry as normal. ## Creating an AKS resource and reusing an existing service principal This scenario is most relevant when creating an AKS resource in an automated environment, ie without a logged-in user's credentials. Currently, creating an AKS resource also involves creating an associated service principal, for the cluster to manage its sub-resources. In turn, creating this service principal will attempt to get the credentials for the logged-in user, which fails if there is no user present. To avoid this, you can create an app ahead of time and pass it to `create_aks`: ```r # login to ARM and MS Graph with client credentials flow # your app must have the right permissions to work with ARM and Graph az <- AzureRMR::create_azure_login("mytenant", app="app_id", password="clientsecret") gr <- AzureGraph::create_graph_login("mytenant", app="app_id", password="clientsecret") app <- gr$create_app("myaksapp") az$get_subscription("sub_id")$ get_resource_group("rgname")$ create_aks("myaks", cluster_service_principal=app, agent_pools=aks_pools("pool1", 2, "Standard_DS2_v2", "Linux")) ``` ## Integrating AKS with Azure Active Directory Integrating AKS and AAD requires creating two registered apps, the client and server, and giving them permissions to talk to each other. Most of the work here is actually done using the AzureGraph package; once the apps are correctly configured, we then pass them to the `create_aks` method. You'll need to be an administrator for your AAD tenant to carry out these steps. ```r # create the server app srvapp <- gr$create_app("akssrvapp") # save the app ID and password srvapp_id <- srvapp$properties$appId srvapp_pwd <- srvapp$password # update group membership claims srvapp$update(groupMembershipClaims="all") # update API permissions (Directory.Read.All scope & role, User.Read.All scope) srvapp$update(requiredResourceAccess=list( list( resourceAppId="00000003-0000-0000-c000-000000000000", resourceAccess=list( list(id="06da0dbc-49e2-44d2-8312-53f166ab848a", type="Scope"), list(id="e1fe6dd8-ba31-4d61-89e7-88639da4683d", type="Scope"), list(id="7ab1d382-f21e-4acd-a863-ba3e13f7da61", type="Role") ) ) )) # add OAuth permissions API srvapp_api <- srvapp$properties$api srvapp_newapi_id <- uuid::UUIDgenerate() srvapp_api$oauth2PermissionScopes <- list( list( adminConsentDescription="AKS", adminConsentDisplayName="AKS", id=srvapp_newapi_id, isEnabled=TRUE, type="User", userConsentDescription="AKS", userConsentDisplayName="AKS", value="AKS" ) ) srvapp$update(api=srvapp_api, identifierUris=I(sprintf("api://%s", srvapp_id))) # create the client app cliapp <- gr$create_app("akscliapp", isFallbackPublicClient=TRUE, publicClient=list(redirectUris=list("https://akscliapp")) ) cliapp_id <- cliapp$properties$appId # tell the server app to trust the client srvapp_api <- srvapp$properties$api srvapp_api$preAuthorizedApplications <- list( list( appId=cliapp_id, permissionIds=list(srvapp_newapi_id) ) ) srvapp$update(api=srvapp_api) ``` Once the apps have been configured, we still have to grant admin consent. This is best done in the Azure Portal: - Click on "Azure Active Directory" in the list of items on the left - In the AAD blade, click on "App registrations" - Find the app that you created, and click on it. - Click on "API permissions". - Click on the "Grant admin consent" button at the bottom of the pane. ![](perms2.png "permissions") Having created and configured the apps, we can then create the cluster resource. ```r rg$create_aks("akswithaad", agent_pools=aks_pools("pool1", 2), properties=list( aadProfile=list( clientAppID=cliapp_id, serverAppID=srvapp_id, serverAppSecret=srvapp_pwd ) ), enable_rbac=TRUE ) ``` For more information, see the following Microsoft Docs pages: - [Enable Azure Active Directory integration](https://docs.microsoft.com/en-us/azure/aks/azure-ad-integration) - [Use Kubernetes RBAC with Azure AD integration](https://docs.microsoft.com/en-us/azure/aks/azure-ad-rbac)
/scratch/gouwar.j/cran-all/cranData/AzureContainers/vignettes/vig04_rbac.Rmd
#' @import AzureRMR NULL utils::globalVariables(c("self", "private")) .onLoad <- function(libname, pkgname) { options(azure_cosmosdb_api_version="2018-12-31") add_methods() } delete_confirmed <- function(confirm, name, type) { if(!interactive() || !confirm) return(TRUE) msg <- sprintf("Are you sure you really want to delete the %s '%s'?", type, name) ok <- if(getRversion() < numeric_version("3.5.0")) { msg <- paste(msg, "(yes/No/cancel) ") yn <- readline(msg) if (nchar(yn) == 0) FALSE else tolower(substr(yn, 1, 1)) == "y" } else utils::askYesNo(msg, FALSE) isTRUE(ok) }
/scratch/gouwar.j/cran-all/cranData/AzureCosmosR/R/AzureCosmosR.R
# documentation separate from implementation because roxygen can't handle adding methods to another package's R6 classes #' Create Azure Cosmos DB account #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname create_cosmosdb_account #' @name create_cosmosdb_account #' @aliases create_cosmosdb_account #' @section Usage: #' ``` #' create_cosmosdb_account( #' name, #' location = self$location, #' interface = c("sql", "cassandra", "mongo", "table", "graph"), #' serverless = FALSE, #' free_tier = FALSE, #' properties = list(), #' ... #' ) #' ``` #' @section Arguments: #' - `name`: The name of the Cosmos DB account. #' - `location`: The location/region in which to create the account. Defaults to the resource group's location. #' - `interface`: The default API by which to access data in the account. #' - `serverless`: Whether this account should use provisioned throughput or a serverless mode. In the latter, you are charged solely on the basis of the traffic generated by your database operations. Serverless mode is best suited for small-to-medium workloads with light and intermittent traffic that is hard to forecast; it is currently (January 2021) in preview. #' - `free_tier`: Whether this account should be in the free tier, in which a certain amount of database operations are provided free of charge. You can have one free tier account per subscription. #' - `properties`: Additional properties to set for the account. #' - `wait`: Whether to wait until the Cosmos DB account provisioning is complete. #' - `...`: Optional arguments to pass to `az_cosmosdb$new()`. #' @section Details: #' This method creates a new Azure Cosmos DB account in the given resource group. Azure Cosmos DB is a globally distributed multi-model database that supports the document, graph, and key-value data models. #' #' The ARM resource object provides methods for working in the management plane. For working in the data plane, AzureCosmosR provides a client framework that interfaces with the core (SQL) API. Other packages provide functionality for other APIs, such as AzureTableStor for table storage and mongolite for MongoDB. #' @section Value: #' An object of class `az_cosmosdb` representing the Cosmos DB account. #' @seealso #' [get_cosmosdb_account], [delete_cosmosdb_account] #' #' For the SQL API client framework: [cosmos_endpoint], [cosmos_database], [cosmos_container], [query_documents] #' #' For the table storage API: [AzureTableStor::table_endpoint] #' #' For the MongoDB API: [cosmos_mongo_endpoint], [mongolite::mongo] NULL #' Get Azure Cosmos DB account #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname get_cosmosdb_account #' @name get_cosmosdb_account #' @aliases get_cosmosdb_account list_cosmosdb_accounts #' @section Usage: #' ``` #' get_cosmosdb_account(name) #' list_cosmosdb_accounts() #' ``` #' @section Arguments: #' - `name`: The name of the Cosmos DB account. #' @section Details: #' `get_cosmosdb_account` retrieves the details for an existing Azure Cosmos DB account. `list_cosmosdb_accounts` retrieves all the Cosmos DB accounts within the resource group. #' @section Value: #' For `get_cosmosdb_account`, an object of class `az_cosmosdb` representing the Cosmos DB account. For `list_cosmosdb_accounts`, a list of such objects. #' @seealso #' [create_cosmosdb_account], [delete_cosmosdb_account] #' #' For the SQL API client framework: [cosmos_endpoint], [cosmos_database], [cosmos_container], [query_documents] #' #' For the table storage API: [AzureTableStor::table_endpoint] #' #' For the MongoDB API: [cosmos_mongo_endpoint], [mongolite::mongo] NULL #' Delete Azure Cosmos DB account #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname delete_cosmosdb_account #' @name delete_cosmosdb_account #' @aliases delete_cosmosdb_account #' @section Usage: #' ``` #' delete_cosmosdb_account(name, confirm = TRUE, wait = FALSE) #' ``` #' @section Arguments: #' - `name`: The name of the Cosmos DB account. #' - `confirm`: Whether to ask for confirmation before deleting. #' - `wait`: Whether to wait until the deletion has completed before returning. #' @section Details: #' This method deletes an existing Azure Cosmos DB account. #' @seealso #' [create_cosmosdb_account], [get_cosmosdb_account] #' #' For the SQL API client framework: [cosmos_endpoint], [cosmos_database], [cosmos_container], [query_documents] #' #' For the table storage API: [AzureTableStor::table_endpoint] #' #' For the MongoDB API: [cosmos_mongo_endpoint], [mongolite::mongo] NULL add_methods <- function() { az_resource_group$set("public", "create_cosmosdb_account", overwrite=TRUE, function(name, location=self$location, interface=c("sql", "cassandra", "mongo", "table", "graph"), serverless=FALSE, free_tier=FALSE, properties=list(), wait=TRUE, ...) { interface <- match.arg(interface) kind <- if(interface == "mongo") "MongoDB" else "GlobalDocumentDB" capabilities <- if(interface == "cassandra") list(list(name="EnableCassandra")) else if(interface == "mongo") list( list(name="EnableMongo"), list(name="DisableRateLimitingResponses") ) else if(interface == "table") list(list(name="EnableTable")) else if(interface == "graph") list(list(name="EnableGremlin")) else list() if(serverless) capabilities <- c(capabilities, list(list(name="EnableServerless"))) properties <- utils::modifyList(properties, list( databaseAccountOfferType="standard", enableFreeTier=free_tier, capabilities=capabilities, locations=list( list( id=paste0(name, "-", location), failoverPriority=0, locationName=location ) ) )) AzureCosmosR::az_cosmosdb$new(self$token, self$subscription, self$name, type="Microsoft.documentDB/databaseAccounts", name=name, location=location, kind=kind, properties=properties, wait=wait, ...) }) az_resource_group$set("public", "get_cosmosdb_account", overwrite=TRUE, function(name) { AzureCosmosR::az_cosmosdb$new(self$token, self$subscription, self$name, type="Microsoft.documentDB/databaseAccounts", name=name) }) az_resource_group$set("public", "list_cosmosdb_accounts", overwrite=TRUE, function() { provider <- "Microsoft.documentDB" path <- "databaseAccounts" api_version <- az_subscription$ new(self$token, self$subscription)$ get_provider_api_version(provider, path) op <- file.path("resourceGroups", self$name, "providers", provider, path) cont <- call_azure_rm(self$token, self$subscription, op, api_version=api_version) lst <- lapply(cont$value, function(parms) AzureCosmosR::az_cosmosdb$new(self$token, self$subscription, deployed_properties=parms)) # keep going until paging is complete while(!is_empty(cont$nextLink)) { cont <- call_azure_url(self$token, cont$nextLink) lst <- lapply(cont$value, function(parms) AzureCosmosR::az_cosmosdb$new(self$token, self$subscription, deployed_properties=parms)) } named_list(lst) }) az_resource_group$set("public", "delete_cosmosdb_account", overwrite=TRUE, function(name, confirm=TRUE, wait=FALSE) { self$get_cosmosdb_account(name)$delete(confirm=confirm, wait=wait) }) }
/scratch/gouwar.j/cran-all/cranData/AzureCosmosR/R/add_methods.R
#' Azure Cosmos DB account class #' #' Class representing an Azure Cosmos DB account. For working with the data inside the account, see [cosmos_endpoint] and [cosmos_database]. #' #' @docType class #' @section Methods: #' The following methods are available, in addition to those provided by the [AzureRMR::az_resource] class: #' - `list_keys(read_only=FALSE`): Return the access keys for this account. #' - `regen_key(kind)`: Regenerate (change) an access key. `kind` should be one of "primary", "secondary", "primaryReadonly" or "secondaryReadonly". #' - `get_endpoint(interface, ...)`: Return a default endpoint object for interacting with the data. See 'Endpoints' below. #' - `get_sql_endpoint(key, key_type)`: Return an object representing the core (SQL) endpoint of the account. #' - `get_table_endpoint(key)`: Return an object representing the table storage endpoint of the account. #' - `get_mongo_endpoint(collection, key, mongo_options)`: Return an object representing the MongoDB enpoint of the account. #' #' @section Details: #' Initializing a new object of this class can either retrieve an existing Cosmos DB resource, or create a new resource on the host. Generally, the best way to initialize an object is via the `get_cosmosdb_account` or `create_cosmosdb_account` methods of the [AzureRMR::az_resource_group] class, which handle the details automatically. #' #' @section Endpoints: #' Azure Cosmos DB provides multiple APIs for accessing the data stored within the account. You choose at account creation the API that you want to use: core (SQL), table storage, Mongo DB, Apache Cassandra, or Gremlin. The following methods allow you to create an endpoint object corresponding to these APIs. #' #' - `get_endpoint(interface=NULL, ...)`: Return an endpoint object for interacting with the data. The default `interface=NULL` will choose the interface that you selected at account creation. Otherwise, set `interface` to one of "sql", "table", "mongo", "cassandra" or "gremlin" to create an endpoint object for that API. It's an error to select an interface that the Cosmos DB account doesn't actually provide. #' - `get_sql_endpoint(key, key_type=c("master", "resource"))`: Return an endpoint object for the core (SQL) API, of class [cosmos_endpoint]. A master key provides full access to all the data in the account; a resource key provides access only to a chosen subset of the data. #' - `get_table_endpoint(key)`: Return an endpoint object for the table storage API, of class [AzureTableStor::table_endpoint]. #' - `get_mongo_endpoint(key, mongo_options)`: Return an endpoint object for the MongoDB API, of class [cosmos_mongo_endpoint]. `mongo_options` should be an optional named list of parameters to set in the connection string. #' #' Note that AzureCosmosR provides a client framework only for the SQL API. To use the table storage API, you will also need the AzureTableStor package, and to use the MongoDB API, you will need the mongolite package. Currently, the Cassandra and Gremlin APIs are not supported. #' #' As an alternative to AzureCosmosR, you can also use the ODBC protocol to interface with the SQL API. By installing a suitable ODBC driver, you can then talk to Cosmos DB in a manner similar to other SQL databases. An advantage of the ODBC interface is that it fully supports cross-partition queries, unlike the REST API. A disadvantage is that it does not support nested document fields; functions like `array_contains()` cannot be used, and attempts to reference arrays and objects may return incorrect results. #' #' @seealso #' [get_cosmosdb_account], [create_cosmosdb_account], [delete_cosmosdb_account] #' #' [cosmos_endpoint], [cosmos_database], [cosmos_container], [query_documents], [cosmos_mongo_endpoint], [AzureTableStor::table_endpoint], [mongolite::mongo] #' @export az_cosmosdb <- R6::R6Class("az_cosmosdb", inherit=az_resource, public=list( list_keys=function(read_only=FALSE) { op <- if(read_only) "readonlykeys" else "listkeys" unlist(self$do_operation(op, http_verb="POST")) }, regen_key=function(kind=c("primary", "secondary", "primaryReadonly", "secondaryReadonly")) { kind <- match.arg(kind) self$do_operation("regenerateKey", body=list(keyKind=kind), http_verb="POST") invisible(self) }, get_endpoint=function(interface=NULL, ...) { if(is.null(interface)) interface <- tolower(self$properties$EnabledApiTypes) if(grepl("table", interface)) self$get_table_endpoint(...) else if(grepl("mongo", interface)) self$get_mongo_endpoint(...) else if(grepl("cassandra", interface)) self$get_cassandra_endpoint(...) else if(grepl("gremlin", interface)) self$get_graph_endpoint(...) else self$get_sql_endpoint(...) }, get_sql_endpoint=function(key=self$list_keys()[[1]], key_type=c("master", "resource")) { private$assert_has_sql() key_type <- match.arg(key_type) cosmos_endpoint(self$properties$documentEndpoint, key=key, key_type=key_type) }, get_table_endpoint=function(key=self$list_keys()[[1]]) { private$assert_has_table() if(!requireNamespace("AzureTableStor")) stop("AzureTableStor package must be installed to use the table endpoint", call.=FALSE) AzureTableStor::table_endpoint(self$properties$tableEndpoint, key=key) }, get_mongo_endpoint=function(key=self$list_keys()[[1]], mongo_options=list()) { private$assert_has_mongo() assert_mongolite_installed() cosmos_mongo_endpoint(self$properties$mongoEndpoint, key, mongo_options) }, get_cassandra_endpoint=function(...) { stop("Cassandra endpoint is not yet implemented", call.=FALSE) }, get_graph_endpoint=function(...) { stop("Graph (Gremlin) endpoint is not yet implemented", call.=FALSE) } ), private=list( assert_has_sql=function() { if(is.null(self$properties$documentEndpoint)) stop("Not a SQL-enabled Cosmos DB account", call.=FALSE) }, assert_has_cassandra=function() { if(is.null(self$properties$cassandraEndpoint)) stop("Not a Cassandra-enabled Cosmos DB account", call.=FALSE) }, assert_has_mongo=function() { if(is.null(self$properties$mongoEndpoint)) stop("Not a MongoDB-enabled Cosmos DB account", call.=FALSE) }, assert_has_table=function() { if(is.null(self$properties$tableEndpoint)) stop("Not a table storage-enabled Cosmos DB account", call.=FALSE) }, assert_has_graph=function() { if(is.null(self$properties$gremlinEndpoint)) stop("Not a Gremlin-enabled Cosmos DB account", call.=FALSE) } ))
/scratch/gouwar.j/cran-all/cranData/AzureCosmosR/R/az_cosmosdb.R
#' Import a set of documents to an Azure Cosmos DB container #' #' @param container A Cosmos DB container object, as obtained by `get_cosmos_container` or `create_cosmos_container`. #' @param data The data to import. Can be a data frame, or a string containing JSON text. #' @param init_chunksize The number of rows to import per chunk. `bulk_import` can adjust this number dynamically based on observed performance. #' @param verbose Whether to print updates to the console as the import progresses. #' @param procname The stored procedure name to use for the server-side import code. Change this if, for some reason, the default name is taken. #' @param ... Optional arguments passed to lower-level functions. #' @details #' This is a convenience function to import a dataset into a container. It works by creating a stored procedure and then calling it in a loop, passing the to-be-imported data in chunks. The dataset must include a column for the container's partition key or an error will result. #' #' Note that this function is not meant for production use. In particular, if the import fails midway through, it will not clean up after itself: you should call `bulk_delete` to remove the remnants of a failed import. #' @return #' A list containing the number of rows imported, for each value of the partition key. #' @seealso #' [bulk_delete], [cosmos_container] #' @examples #' \dontrun{ #' #' endp <- cosmos_endpoint("https://myaccount.documents.azure.com:443/", key="mykey") #' db <- get_cosmos_database(endp, "mydatabase") #' cont <- create_cosmos_container(db, "mycontainer", partition_key="sex") #' #' # importing the Star Wars data from dplyr #' # notice that rows with sex=NA are not imported #' bulk_import(cont, dplyr::starwars) #' #' # importing from a JSON file #' writeLines(jsonlite::toJSON(dplyr::starwars), "starwars.json") #' bulk_import(cont, "starwars.json") #' #' } #' @rdname bulk_import #' @export bulk_import <- function(container, ...) { UseMethod("bulk_import") } #' @rdname bulk_import #' @export bulk_import.cosmos_container <- function(container, data, init_chunksize=1000, verbose=TRUE, procname="_AzureCosmosR_bulkImport", ...) { # create the stored procedure if necessary res <- tryCatch(create_stored_procedure(container, procname, readLines(system.file("srcjs/bulkUpload.js", package="AzureCosmosR"))), error=function(e) e) if(inherits(res, "error")) if(!(is.character(res$message) && grepl("HTTP 409", res$message))) # proc already existing is ok stop(res) if(is.character(data) && jsonlite::validate(data)) data <- jsonlite::fromJSON(data, simplifyDataFrame=FALSE) key <- get_partition_key(container) res <- if(is.null(key)) import_by_key(container, NULL, data, procname, init_chunksize, ...) else { if(is.null(data[[key]])) stop("Data does not contain partition key", call.=FALSE) lapply(split(data, data[[key]]), function(partdata) import_by_key(container, partdata[[key]][1], partdata, procname, init_chunksize, verbose=verbose, ...)) } invisible(res) } import_by_key <- function(container, key, data, procname, init_chunksize, headers=list(), verbose=TRUE, ...) { rows_imported <- 0 this_import <- 0 this_chunksize <- avg_chunksize <- init_chunksize nrows <- nrow(data) n <- 0 if(!is.null(key)) headers$`x-ms-documentdb-partitionkey` <- jsonlite::toJSON(key) while(rows_imported < nrows) { n <- n + 1 this_chunk <- seq(rows_imported + 1, min(nrows, rows_imported + this_chunksize)) this_import <- exec_stored_procedure(container, procname, list(data[this_chunk, ]), headers=headers, ...) rows_imported <- rows_imported + this_import avg_chunksize <- (avg_chunksize * (n-1))/n + this_chunksize/n if(verbose) message("Rows imported: ", rows_imported, " this chunk: ", length(this_chunk), " average chunksize: ", avg_chunksize) # adjust chunksize based on observed import performance per chunk this_chunksize <- if(this_import < this_chunksize) (this_chunksize + this_import)/2 else init_chunksize } rows_imported } #' Delete a set of documents from an Azure Cosmos DB container #' #' @param container A Cosmos DB container object, as obtained by `get_cosmos_container` or `create_cosmos_container`. #' @param query A query specifying which documents to delete. #' @param partition_key Optionally, limit the deletion only to documents with this key value. #' @param procname The stored procedure name to use for the server-side import code. Change this if, for some reason, the default name is taken. #' @param headers,... Optional arguments passed to lower-level functions. #' @details #' This is a convenience function to delete multiple documents from a container. It works by creating a stored procedure and then calling it with the supplied query as a parameter. This function is not meant for production use. #' @return #' The number of rows deleted. #' @seealso #' [bulk_import], [cosmos_container] #' @examples #' \dontrun{ #' #' endp <- cosmos_endpoint("https://myaccount.documents.azure.com:443/", key="mykey") #' db <- get_cosmos_database(endp, "mydatabase") #' cont <- create_cosmos_container(db, "mycontainer", partition_key="sex") #' #' # importing the Star Wars data from dplyr #' bulk_import(cont, dplyr::starwars) #' #' # deleting a subset of documents #' bulk_delete(cont, "select * from mycontainer c where c.gender = 'masculine'") #' #' # deleting documents for a specific partition key value #' bulk_delete(cont, "select * from mycontainer", partition_key="male") #' #' # deleting all documents #' bulk_delete(cont, "select * from mycontainer") #' #' } #' @rdname bulk_delete #' @export bulk_delete <- function(container, ...) { UseMethod("bulk_delete") } #' @rdname bulk_delete #' @export bulk_delete.cosmos_container <- function(container, query, partition_key, procname="_AzureCosmosR_bulkDelete", headers=list(), ...) { # create the stored procedure if necessary res <- tryCatch(create_stored_procedure(container, procname, readLines(system.file("srcjs/bulkDelete.js", package="AzureCosmosR"))), error=function(e) e) if(inherits(res, "error")) if(!(is.character(res$message) && grepl("HTTP 409", res$message))) # proc already existing is ok stop(res) if(!is.null(partition_key)) headers$`x-ms-documentdb-partitionkey` <- jsonlite::toJSON(partition_key) if(length(query) > 1) query <- paste0(query, collapse="\n") deleted <- 0 repeat { res <- exec_stored_procedure.cosmos_container(container, procname, list(query), headers=headers, ...) deleted <- deleted + res$deleted if(!res$continuation) break } invisible(deleted) }
/scratch/gouwar.j/cran-all/cranData/AzureCosmosR/R/bulk.R
#' Methods for working with Azure Cosmos DB containers #' #' @param object A Cosmos DB database object, as obtained from `get_cosmos_database` or `create_cosmos_database`, or for `delete_cosmos_container.cosmos_container`, the container object. #' @param database For `get_cosmos_container.cosmos_endpoint`, the name of the database that includes the container. #' @param container The name of the container. #' @param partition_key For `create_cosmos_container`, the name of the partition key. #' @param partition_version For `create_cosmos_container`, the partition version. Can be either 1 or 2. Version 2 supports large partition key values (longer than 100 bytes) but requires API version `2018-12-31` or later. Use version 1 if the container needs to be accessible to older Cosmos DB SDKs. #' @param autoscale_maxRUs,manual_RUs For `create_cosmos_container`, optional parameters for the maximum request units (RUs) allowed. See the Cosmos DB documentation for more details. #' @param confirm For `delete_cosmos_container`, whether to ask for confirmation before deleting. #' @param headers,... Optional arguments passed to lower-level functions. #' @details #' These are methods for working with Cosmos DB containers using the core (SQL) API. A container is analogous to a table in SQL, or a collection in MongoDB. #' #' `get_cosmos_container`, `create_cosmos_container`, `delete_cosmos_container` and `list_cosmos_containers` provide basic container management functionality. #' #' `get_partition_key` returns the name of the partition key column in the container, and `list_partition_key_values` returns all the distinct values for this column. These are useful when working with queries that have to be mapped across partitions. #' @return #' For `get_cosmos_container` and `create_cosmos_container`, an object of class `cosmos_container. For `list_cosmos_container`, a list of such objects. #' @seealso #' [cosmos_container], [query_documents], [bulk_import], [bulk_delete] #' @examples #' \dontrun{ #' #' endp <- cosmos_endpoint("https://myaccount.documents.azure.com:443/", key="mykey") #' db <- get_cosmos_database(endp, "mydatabase") #' #' create_cosmos_container(db, "mycontainer", partition_key="sex") #' #' list_cosmos_containers(db) #' #' cont <- get_cosmos_container(db, "mycontainer") #' #' delete_cosmos_container(cont) #' #' } #' @aliases cosmos_container #' @rdname cosmos_container #' @export get_cosmos_container <- function(object, ...) { UseMethod("get_cosmos_container") } #' @rdname cosmos_container #' @export get_cosmos_container.cosmos_database <- function(object, container, ...) { path <- file.path("colls", container) res <- do_cosmos_op(object, path, "colls", path, ...) obj <- process_cosmos_response(res) obj$database <- object class(obj) <- "cosmos_container" obj } #' @rdname cosmos_container #' @export get_cosmos_container.cosmos_endpoint <- function(object, database, container, ...) { path <- file.path("dbs", database, "colls", container) res <- do_cosmos_op(object, path, "colls", path, ...) obj <- process_cosmos_response(res) obj$database <- structure(list(endpoint=object, id=database), class="cosmos_database") class(obj) <- "cosmos_container" obj } #' @rdname cosmos_container #' @export create_cosmos_container <- function(object, ...) { UseMethod("create_cosmos_container") } #' @rdname cosmos_container #' @export create_cosmos_container.cosmos_database <- function(object, container, partition_key, partition_version=2, autoscale_maxRUs=NULL, manual_RUs=NULL, headers=list(), ...) { if(!is.null(manual_RUs)) headers$`x-ms-offer-throughput` <- manual_RUs if(!is.null(autoscale_maxRUs)) headers$`x-ms-cosmos-offer-autopilot-settings` <- jsonlite::toJSON(autoscale_maxRUs) body <- list( id=container, partitionKey=list( paths=list(paste0("/", partition_key)), kind="Hash", version=partition_version ) ) res <- do_cosmos_op(object, "colls", "colls", "", headers=headers, body=body, encode="json", http_verb="POST", ...) obj <- process_cosmos_response(res) obj$database <- object class(obj) <- "cosmos_container" obj } #' @rdname cosmos_container #' @export delete_cosmos_container <- function(object, ...) { UseMethod("delete_cosmos_container") } #' @rdname cosmos_container #' @export delete_cosmos_container.cosmos_database <- function(object, container, confirm=TRUE, ...) { if(!delete_confirmed(confirm, container, "container")) return(invisible(NULL)) path <- file.path("colls", container) res <- do_cosmos_op(object, path, "colls", path, http_verb="DELETE", ...) invisible(process_cosmos_response(res)) } #' @rdname cosmos_container #' @export delete_cosmos_container.cosmos_container <- function(object, ...) { delete_cosmos_container(object$database, object$id, ...) } #' @rdname cosmos_container #' @export list_cosmos_containers <- function(object, ...) { UseMethod("list_cosmos_containers") } #' @rdname cosmos_container #' @export list_cosmos_containers.cosmos_database <- function(object, ...) { res <- do_cosmos_op(object, "colls", "colls", "", ...) named_list(lapply(process_cosmos_response(res)$DocumentCollections, function(obj) { obj$database <- object structure(obj, class="cosmos_container") }), "id") } #' @export print.cosmos_container <- function(x, ...) { cat("Cosmos DB SQL container '", x$id, "'\n", sep="") path <- x$database$endpoint$host path$path <- file.path("dbs", x$database$id, "colls", x$id) cat("Path:", httr::build_url(path), "\n") invisible(x) }
/scratch/gouwar.j/cran-all/cranData/AzureCosmosR/R/container.R
#' Methods for working with Azure Cosmos DB databases #' #' @param object A Cosmos DB endpoint object as obtained from `cosmos_endpoint`, or for `delete_cosmos_database.cosmos_database`, the database object. #' @param database The name of the Cosmos DB database. #' @param autoscale_maxRUs,manual_RUs For `create_cosmos_database`, optional parameters for the maximum request units (RUs) allowed. See the Cosmos DB documentation for more details. #' @param confirm For `delete_cosmos_database`, whether to ask for confirmation before deleting. #' @param headers,... Optional arguments passed to lower-level functions. #' @details #' These are methods for managing Cosmos DB databases using the core (SQL) API. #' @return #' `get_cosmos_database` and `create_cosmos_database` return an object of class `cosmos_database`. `list_cosmos_databases` returns a list of such objects. #' @examples #' \dontrun{ #' #' endp <- cosmos_endpoint("https://myaccount.documents.azure.com:443/", key="mykey") #' #' create_cosmos_database(endp, "mydatabase") #' #' list_cosmos_databases(endp) #' #' db <- get_cosmos_database(endp, "mydatabase") #' #' delete_cosmos_database(db) #' #' } #' @aliases cosmos_database #' @rdname cosmos_database #' @export get_cosmos_database <- function(object, ...) { UseMethod("get_cosmos_database") } #' @rdname cosmos_database #' @export get_cosmos_database.cosmos_endpoint <- function(object, database, ...) { path <- file.path("dbs", database) res <- do_cosmos_op(object, path, "dbs", path, ...) obj <- process_cosmos_response(res) class(obj) <- "cosmos_database" obj$endpoint <- object obj } #' @rdname cosmos_database #' @export create_cosmos_database <- function(object, ...) { UseMethod("create_cosmos_database") } #' @rdname cosmos_database #' @export create_cosmos_database.cosmos_endpoint <- function(object, database, autoscale_maxRUs=NULL, manual_RUs=NULL, headers=list(), ...) { if(!is.null(manual_RUs)) headers$`x-ms-offer-throughput` <- manual_RUs if(!is.null(autoscale_maxRUs)) headers$`x-ms-cosmos-offer-autopilot-settings` <- jsonlite::toJSON(autoscale_maxRUs) body <- list(id=database) res <- do_cosmos_op(object, "dbs", "dbs", "", headers=headers, body=body, encode="json", http_verb="POST", ...) obj <- process_cosmos_response(res) class(obj) <- "cosmos_database" obj$endpoint <- object obj } #' @rdname cosmos_database #' @export delete_cosmos_database <- function(object, ...) { UseMethod("delete_cosmos_database") } #' @rdname cosmos_database #' @export delete_cosmos_database.cosmos_endpoint <- function(object, database, confirm=TRUE, ...) { if(!delete_confirmed(confirm, database, "database")) return(invisible(NULL)) path <- file.path("dbs", database) res <- do_cosmos_op(object, path, "dbs", path, http_verb="DELETE", ...) invisible(process_cosmos_response(res)) } #' @rdname cosmos_database #' @export delete_cosmos_database.cosmos_database <- function(object, ...) { delete_cosmos_database(object$endpoint, object$id, ...) } #' @rdname cosmos_database #' @export list_cosmos_databases <- function(object, ...) { UseMethod("list_cosmos_databases") } #' @rdname cosmos_database #' @export list_cosmos_databases.cosmos_endpoint <- function(object, ...) { res <- do_cosmos_op(object, "dbs", "dbs", "", ...) named_list(lapply(process_cosmos_response(res)$Databases, function(obj) { obj$endpoint <- object structure(obj, class="cosmos_database") }), "id") } #' @export print.cosmos_database <- function(x, ...) { cat("Cosmos DB SQL database '", x$id, "'\n", sep="") path <- x$endpoint$host path$path <- x$id cat("Path:", httr::build_url(path)) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/AzureCosmosR/R/database.R
#' Carry out a Cosmos DB operation #' #' @param object A Cosmos DB endpoint, database, container or document object. #' @param path The (partial) URL path for the operation. #' @param resource_type The type of resource. For most purposes, the default value should suffice. #' @param resource_link The resource link for authorization. For most purposes, the default value should suffice. #' @param headers Any optional HTTP headers to include in the API call. #' @param ... Arguments passed to lower-level functions. #' @details #' `do_cosmos_op` provides a higher-level interface to the Cosmos DB REST API than `call_cosmos_endpoint`. In particular, it sets the `resource_type` and `resource_link` arguments to sensible defaults, and fills in the beginning of the URL path for the REST call. #' @return #' The result of `call_cosmos_endpoint`: either a httr response object, or a list of such objects. Call `process_cosmos_response` to extract the result of the call. #' @examples #' \dontrun{ #' #' endp <- cosmos_endpoint("https://myaccount.documents.azure.com:443/", key="mykey") #' #' db <- get_cosmos_database(endp, "mydatabase") #' do_cosmos_op(db) %>% #' process_cosmos_response() #' #' cont <- get_cosmos_container(db, "mycontainer") #' do_cosmos_op(cont) %>% #' process_cosmos_response() #' #' } #' @rdname do_cosmos_op #' @export do_cosmos_op <- function(object, ...) { UseMethod("do_cosmos_op") } #' @rdname do_cosmos_op #' @export do_cosmos_op.cosmos_endpoint <- function(object, ...) { call_cosmos_endpoint(object, ...) } #' @rdname do_cosmos_op #' @export do_cosmos_op.cosmos_database <- function(object, path="", resource_type="dbs", resource_link="", ...) { full_path <- full_reslink <- file.path("dbs", object$id) if(nchar(path) > 0) full_path <- file.path(full_path, path) if(nchar(resource_link) > 0) full_reslink <- file.path(full_reslink, resource_link) call_cosmos_endpoint(object$endpoint, full_path, resource_type, full_reslink, ...) } #' @rdname do_cosmos_op #' @export do_cosmos_op.cosmos_container <- function(object, path="", resource_type="colls", resource_link="", ...) { full_path <- full_reslink <- file.path("dbs", object$database$id, "colls", object$id) if(nchar(path) > 0) full_path <- file.path(full_path, path) if(nchar(resource_link) > 0) full_reslink <- file.path(full_reslink, resource_link) call_cosmos_endpoint(object$database$endpoint, full_path, resource_type, full_reslink, ...) } #' @rdname do_cosmos_op #' @export do_cosmos_op.cosmos_document <- function(object, path="", resource_type="docs", resource_link="", headers=list(), ...) { full_path <- full_reslink <- file.path("dbs", object$container$database$id, "colls", object$container$id, "docs", object$data$id) if(nchar(path) > 0) full_path <- file.path(full_path, path) if(nchar(resource_link) > 0) full_reslink <- file.path(full_reslink, resource_link) partition_key <- sub("^/", "", object$container$partitionKey$paths) headers$`x-ms-documentdb-partitionkey` <- jsonlite::toJSON(object$data[[partition_key]]) call_cosmos_endpoint(object$container$database$endpoint, full_path, resource_type, full_reslink, headers=headers, ...) }
/scratch/gouwar.j/cran-all/cranData/AzureCosmosR/R/do_cosmos_op.R
#' Methods for working with Azure Cosmos DB documents #' #' @param object A Cosmos DB container object, as obtained by `get_cosmos_container` or `create_cosmos_container`. #' @param id The document ID. #' @param partition_key For `get_document` and `delete_document`, the value of the partition key for the desired document. For `list_documents`, restrict the returned list only to documents with this key value. #' @param data For `create_document`, the document data. This can be either a string containing JSON text, or a (possibly nested) list containing the parsed JSON. #' @param metadata For `get_document` and `list_documents`, whether to include Cosmos DB document metadata in the result. #' @param as_data_frame For `list_documents`, whether to return a data frame or a list of Cosmos DB document objects. Note that the default value is FALSE, unlike [query_documents]. #' @param confirm For `delete_cosmos_container`, whether to ask for confirmation before deleting. #' @param headers,... Optional arguments passed to lower-level functions. #' @details #' These are low-level functions for working with individual documents in a Cosmos DB container. In most cases you will want to use [query_documents] to issue queries against the container, or [bulk_import] and [bulk_delete] to create and delete documents. #' @return #' `get_document` and `create_document` return an object of S3 class `cosmos_document`. The actual document contents can be found in the `data` component of this object. #' #' `list_documents` returns a list of `cosmos_document` objects if `as_data_frame` is FALSE, and a data frame otherwise. #' @seealso #' [query_documents], [bulk_import], [bulk_delete], [cosmos_container] #' @examples #' \dontrun{ #' #' endp <- cosmos_endpoint("https://myaccount.documents.azure.com:443/", key="mykey") #' db <- get_cosmos_database(endp, "mydatabase") #' #' cont <- get_cosmos_container(db, "mycontainer") #' #' # a list of document objects #' list_documents(cont) #' #' # a data frame #' list_documents(cont, as_data_frame=TRUE) #' #' # a single document #' doc <- get_document(cont, "mydocumentid") #' doc$data #' #' delete_document(doc) #' #' } #' @aliases cosmos_document #' @rdname cosmos_document #' @export get_document <- function(object, ...) { UseMethod("get_document") } #' @export get_document.cosmos_container <- function(object, id, partition_key, metadata=TRUE, headers=list(), ...) { headers <- utils::modifyList(headers, list(`Content-Type`="application/query+json")) headers$`x-ms-documentdb-partitionkey` <- jsonlite::toJSON(partition_key) res <- do_cosmos_op(object, file.path("docs", id), "docs", file.path("docs", id), headers=headers, ...) doc <- process_cosmos_response(res, simplify=FALSE) if(!metadata) doc[c("id", "_rid", "_self", "_etag", "_attachments", "_ts")] <- NULL as_document(doc, object) } #' @rdname cosmos_document #' @export create_document <- function(object, ...) { UseMethod("create_document") } #' @rdname cosmos_document #' @export create_document.cosmos_container <- function(object, data, headers=list(), ...) { if(is.character(data) && jsonlite::validate(data)) data <- jsonlite::fromJSON(data) # assume only 1 partition key at most if(!is.null(object$partitionKey)) { partition_key <- sub("^/", "", object$partitionKey$paths) if(is.null(data[[partition_key]])) stop("Partition key not found in document data", call.=FALSE) headers$`x-ms-documentdb-partitionkey` <- jsonlite::toJSON(data[[partition_key]]) } if(is.null(data$id)) data$id <- uuid::UUIDgenerate() data <- jsonlite::toJSON(data, auto_unbox=TRUE, null="null") res <- do_cosmos_op(object, "docs", "docs", "", headers=headers, body=data, http_verb="POST", ...) doc <- process_cosmos_response(res) invisible(as_document(doc, object)) } #' @rdname cosmos_document #' @export list_documents <- function(object, ...) { UseMethod("list_documents") } #' @rdname cosmos_document #' @export list_documents.cosmos_container <- function(object, partition_key=NULL, as_data_frame=FALSE, metadata=TRUE, headers=list(), ...) { headers <- utils::modifyList(headers, list(`Content-Type`="application/query+json")) if(!is.null(partition_key)) headers$`x-ms-documentdb-partitionkey` <- jsonlite::toJSON(partition_key) res <- do_cosmos_op(object, "docs", "docs", headers=headers, ...) get_docs(res, as_data_frame, metadata, object) } #' @rdname cosmos_document #' @export delete_document <- function(object, ...) { UseMethod("delete_document") } #' @rdname cosmos_document #' @export delete_document.cosmos_container <- function(object, id, partition_key, headers=list(), confirm=TRUE, ...) { if(!delete_confirmed(confirm, id, "document")) return(invisible(NULL)) path <- file.path("docs", id) headers$`x-ms-documentdb-partitionkey` <- jsonlite::toJSON(partition_key) res <- do_cosmos_op(object, path, "docs", path, headers=headers, http_verb="DELETE", ...) invisible(process_cosmos_response(res)) } #' @rdname cosmos_document #' @export delete_document.cosmos_document <- function(object, ...) { partition_key <- sub("^/", "", object$container$partitionKey$paths) delete_document(object$container, object$data$id, object$data[[partition_key]], ...) } #' @export print.cosmos_document <- function(x, ...) { cat("Cosmos DB document '", x$data$id, "'\n", sep="") invisible(x) } as_document <- function(document, container) { structure(list(container=container, data=document), class="cosmos_document") }
/scratch/gouwar.j/cran-all/cranData/AzureCosmosR/R/document.R
#' Client endpoint for Azure Cosmos DB core API #' #' @param host For `cosmos_endpoint`, the host URL for the endpoint. Typically of the form `https://{account-name}.documents.azure.com:443/` (note the port number). #' @param key For `cosmos_endpoint`, a string containing the password for the endpoint. This can be either a master key or a resource token. #' @param key_type For `cosmos_endpoint`, the type of the key, either "master" or "resource". #' @param api_version For `cosmos_endpoint`, the API version to use. #' @param endpoint For `call_cosmos_endpoint`, a Cosmos DB endpoint object, as returned by `cosmos_endpoint`. #' @param path For `call_cosmos_endpoint`, the path in the URL for the endpoint call. #' @param resource_type For `call_cosmos_endpoint`, the type of resource: for example, "dbs" for a database, "colls" for a collection (container), "docs" for a document, etc. #' @param resource_link For `call_cosmos_endpoint`, a string to pass to the API for authorization purposes. See the Cosmos DB API documentation for more information. #' @param options For `call_cosmos_endpoint`, query options to include in the request URL. #' @param headers For `call_cosmos_endpoint`, any HTTP headers to include in the request. You don't need to include authorization headers as `call_cosmos_endpoint` will take care of the details. #' @param body For `call_cosmos_endpoint`, the body of the request if any. #' @param encode For `call_cosmos_endpoint`, the encoding (really content-type) of the request body. The Cosmos DB REST API uses JSON, so there should rarely be a need to change this argument. #' @param do_continuations For `call_cosmos_endpoint`, whether to automatically handle paged responses. If FALSE, only the initial response is returned. #' @param http_verb For `call_cosmos_endpoint`, the HTTP verb for the request. One of "GET", "POST", "PUT", "PATCH", "HEAD" or "DELETE". #' @param num_retries For `call_cosmos_endpoint`, how many times to retry a failed request. Useful for dealing with rate limiting issues. #' @param response For `process_cosmos_response`, the returned object from a `call_cosmos_endpoint` call. This will be either a single httr request object, or a list of such objects. #' @param http_status_handler For `process_cosmos_response`, the R handler for the HTTP status code of the response. "stop", "warn" or "message" will call the corresponding handlers in httr, while "pass" ignores the status code. The latter is primarily useful for debugging purposes. #' @param return_headers For `process_cosmos_response`, whether to return the headers from the response object(s), as opposed to the body. Defaults to TRUE if the original endpoint call was a HEAD request, and FALSE otherwise. #' @param simplify For `process_cosmos_response`, whether to convert arrays of objects into data frames via the `simplifyDataFrame` argument to [jsonlite::fromJSON]. #' @param ... Arguments passed to lower-level functions. #' @details #' These functions are the basis of the SQL API client framework provided by AzureCosmosR. The `cosmos_endpoint` function returns a client object, which can then be passed to other functions for querying databases and containers. The `call_cosmos_endpoint` function sends calls to the REST endpoint, the results of which are then processed by `process_cosmos_response`. #' #' In most cases, you should not have to use `call_cosmos_endpoint` directly. Instead, use `do_cosmos_op` which provides a slightly higher-level interface to the API, by providing sensible defaults for the `resource_type` and`resource_link` arguments and partially filling in the request path. #' #' As an alternative to AzureCosmosR, you can also use the ODBC protocol to interface with the SQL API. By installing a suitable ODBC driver, you can then talk to Cosmos DB in a manner similar to other SQL databases. An advantage of the ODBC interface is that it fully supports cross-partition queries, unlike the REST API. A disadvantage is that it does not support nested document fields; functions like `array_contains()` cannot be used, and attempts to reference arrays and objects may return incorrect results. #' #' Note that AzureCosmosR is a framework for communicating directly with the _core_ Cosmos DB client API, also known as the "SQL" API. Cosmos DB provides other APIs as options when creating an account, such as Cassandra, MongoDB, table storage and Gremlin. These APIs are not supported by AzureCosmosR, but you can use other R packages for working with them. For example, you can use AzureTableStor to work with the table storage API, or mongolite to work with the MongoDB API. #' @return #' For `cosmos_endpoint`, an object of S3 class `cosmos_endpoint`. #' #' For `call_cosmos_endpoint`, either a httr response object, or a list of such responses (if a paged query, and `do_continuations` is TRUE). #' #' For `process_cosmos_response` and a single response object, the content of the response. This can be either the parsed response body (if `return_headers` is FALSE) or the headers (if `return_headers` is TRUE). #' #' For `process_cosmos_response` and a list of response objects, a list containing the individual contents of each response. #' @seealso #' [do_cosmos_op], [cosmos_database], [cosmos_container], [az_cosmosdb] #' #' [httr::VERB], which is what carries out the low-level work of sending the HTTP request. #' @examples #' \dontrun{ #' #' endp <- cosmos_endpoint("https://myaccount.documents.azure.com:443/", key="mykey") #' #' # properties for the Cosmos DB account #' call_cosmos_endpoint(endp, "", "", "") %>% #' process_cosmos_response() #' #' } #' @rdname cosmos_endpoint #' @export cosmos_endpoint <- function(host, key, key_type=c("master", "resource"), api_version=getOption("azure_cosmosdb_api_version")) { obj <- list( host=httr::parse_url(host), key=list(value=unname(key), type=match.arg(key_type)), api_version=api_version ) class(obj) <- "cosmos_endpoint" obj } #' @export print.cosmos_endpoint <- function(x, ...) { cat("Cosmos DB SQL endpoint\n") cat("Host:", httr::build_url(x$host), "\n") invisible(x) } #' @rdname cosmos_endpoint #' @export call_cosmos_endpoint <- function(endpoint, path, resource_type, resource_link, options=list(), headers=list(), body=NULL, encode="json", do_continuations=TRUE, http_verb=c("GET", "DELETE", "PUT", "POST", "PATCH", "HEAD"), num_retries=10, ...) { http_verb <- match.arg(http_verb) headers$`x-ms-version` <- endpoint$api_version url <- endpoint$host url$path <- gsub("/{2,}", "/", utils::URLencode(enc2utf8(path))) if(!is_empty(options)) url$query <- options # repeat until no more continuations reslst <- list() repeat { response <- do_request(url, endpoint$key, resource_type, resource_link, headers, body, http_verb=http_verb, num_retries=num_retries, ...) if(inherits(response, "error")) stop(response) reslst <- c(reslst, list(response)) response_headers <- httr::headers(response) if(do_continuations && !is.null(response_headers$`x-ms-continuation`)) headers$`x-ms-continuation` <- response_headers$`x-ms-continuation` else { if(!is.null(response_headers$`x-ms-continuation`)) attr(reslst[[1]], "x-ms-continuation" <- response_headers$`x-ms-continuation`) break } } if(length(reslst) == 1) reslst[[1]] else reslst } do_request <- function(url, key, resource_type, resource_link, headers=list(), body=NULL, encode="json", http_verb=c("GET", "DELETE", "PUT", "POST", "PATCH", "HEAD"), num_retries=10, ...) { http_verb <- match.arg(http_verb) for(r in seq_len(num_retries)) { now <- httr::http_date(Sys.time()) headers$`x-ms-date` <- now headers$Authorization <- sign_cosmos_request( key, http_verb, resource_type, resource_link, now ) response <- tryCatch(httr::VERB(http_verb, url, do.call(httr::add_headers, headers), body=body, encode=encode, ...), error=function(e) e) if(!retry_transfer(response)) # retry on curl errors (except host not found) and http 429 responses break delay <- if(inherits(response, "response")) { delay <- httr::headers(response)$`x-ms-retry-after-ms` if(!is.null(delay)) as.numeric(delay)/1000 else 1 } else 1 Sys.sleep(delay) } if(inherits(response, "error")) stop(response) response } retry_transfer <- function(response) { UseMethod("retry_transfer") } retry_transfer.error <- function(response) { grepl("curl", deparse(response$call[[1]]), fixed=TRUE) && !grepl("Could not resolve host", response$message, fixed=TRUE) } retry_transfer.response <- function(response) { httr::status_code(response) == 429 } #' @rdname cosmos_endpoint #' @export process_cosmos_response <- function(response, ...) { UseMethod("process_cosmos_response") } #' @rdname cosmos_endpoint #' @export process_cosmos_response.response <- function(response, http_status_handler=c("stop", "warn", "message", "pass"), return_headers=NULL, simplify=FALSE, ...) { http_status_handler <- match.arg(http_status_handler) if(http_status_handler == "pass") return(response) handler <- get(paste0(http_status_handler, "_for_status"), getNamespace("httr")) handler(response, cosmos_error_message(response)) if(is.null(return_headers)) return_headers <- response$request$method == "HEAD" if(return_headers) unclass(httr::headers(response)) else httr::content(response, simplifyVector=TRUE, simplifyDataFrame=simplify) } #' @rdname cosmos_endpoint #' @export process_cosmos_response.list <- function(response, http_status_handler=c("stop", "warn", "message", "pass"), return_headers=NULL, simplify=FALSE, ...) { if(!inherits(response[[1]], "response")) stop("Expecting a list of response objects", call.=FALSE) http_status_handler <- match.arg(http_status_handler) if(http_status_handler == "pass") return(response) lapply(response, process_cosmos_response, http_status_handler=http_status_handler, return_headers=return_headers, simplify=simplify) } cosmos_error_message <- function(response) { paste0("complete Cosmos DB operation. Message:\n", sub("\\.$", "", httr::content(response)$message)) }
/scratch/gouwar.j/cran-all/cranData/AzureCosmosR/R/endpoint.R
#' MongoDB endpoint for Azure Cosmos DB #' #' @param host For `cosmos_mongo_endpoint`, the URL of the Cosmos DB MongoDB endpoint. Usually of the form "https://{account-name}.mongo.cosmos.azure.com:443/". #' @param key For `cosmos_mongo_endpoint`, a string containing the access key (password) for the endpoint. Can be either a read-write or read-only key. #' @param mongo_options For `cosmos_mongo_endpoint`, a named list containing any additional parameters for the MongoDB connection string. #' @param connection_string Alternatively, the full connection string for the MongoDB endpoint. If this is supplied, all other arguments to `cosmos_mongo_endpoint` are ignored. Note that if you already have the full connection string, you most likely do not need AzureCosmosR and can call `mongolite::mongo` directly. #' @param endpoint For `cosmos_mongo_connection`, a MongoDB endpoint object as obtained from `cosmos_mongo_endpoint`. #' @param collection,database For `cosmos_mongo_connection`, the collection and database to connect to. #' @param ... Optional arguments passed to lower-level functions. #' @details #' These functions act as a bridge between the Azure resource and the functionality provided by the mongolite package. #' @return #' For `cosmos_mongo_endpoint`, an object of S3 class `cosmos_mongo_endpoint`. #' #' For `cosmos_mongo_connection`, an object of class `mongolite::mongo` which can then be used to interact with the given collection. #' @seealso #' [az_cosmosdb], [mongolite::mongo] #' #' For the SQL API client framework: [cosmos_endpoint], [cosmos_database], [cosmos_container], [query_documents] #' @examples #' \dontrun{ #' #' mendp <- cosmos_mongo_endpoint("https://mymongoacct.mongo.cosmos.azure.com:443", #' key="mykey") #' #' cosmos_mongo_connection(mendp, "mycollection", "mydatabase") #' #' } #' @rdname cosmos_mongo #' @export cosmos_mongo_endpoint <- function(host, key, mongo_options=list(), connection_string=NULL) { assert_mongolite_installed() if(is.null(connection_string)) { url <- httr::parse_url(host) url$port <- 10255 url$scheme <- "mongodb" url$username <- regmatches(url$hostname, regexpr("^[^.]+", url$hostname)) url$password <- key url$query <- utils::modifyList( list( ssl=TRUE, replicaSet="globaldb", retrywrites=FALSE, maxIdleTimeMS=120000 ), mongo_options ) } else url <- httr::parse_url(connection_string) structure(list(host=url, key=key), class="cosmos_mongo_endpoint") } #' @export print.cosmos_mongo_endpoint <- function(x, ...) { cat("Cosmos DB MongoDB endpoint\n") orig_host <- x$host orig_host$username <- orig_host$password <- NULL orig_host$query <- list() cat("Host:", httr::build_url(orig_host), "\n") invisible(x) } #' @rdname cosmos_mongo #' @export cosmos_mongo_connection <- function(endpoint, ...) { assert_mongolite_installed() UseMethod("cosmos_mongo_connection") } #' @rdname cosmos_mongo #' @export cosmos_mongo_connection.cosmos_mongo_endpoint <- function(endpoint, collection, database, ...) { mongolite::mongo(collection=collection, db=database, url=httr::build_url(endpoint$host), ...) } assert_mongolite_installed <- function() { if(!requireNamespace("mongolite")) stop("mongolite package must be installed to use the MongoDB endpoint", call.=FALSE) }
/scratch/gouwar.j/cran-all/cranData/AzureCosmosR/R/mongo_endpoint.R
#' Container partition key information #' #' @param container An object of class `cosmos_container`. #' @details #' These are functions to facilitate working with a Cosmos DB container, which often requires knowledge of its partition key. #' @return #' For `get_partition_key`, the name of the partition key column as a string. #' #' For `list_partition_key_values`, a character vector of all the values of the partition key. #' #' For `list_partition_key_ranges`, a character vector of the IDs of the partition key ranges. #' @rdname partition_key #' @export get_partition_key <- function(container) { key <- container$partitionKey$paths if(is.character(key)) sub("^/", "", key) else NULL } #' @rdname partition_key #' @export list_partition_key_values <- function(container) { key <- get_partition_key(container)[1] qry <- sprintf("select distinct value %s.%s from %s", container$id, key, container$id) lst <- suppressMessages(query_documents(container, qry, by_pkrange=TRUE)) unique(unlist(lst)) } #' @rdname partition_key #' @export list_partition_key_ranges <- function(container) { res <- do_cosmos_op(container, "pkranges", "pkranges", "", headers=list(`x-ms-documentdb-query-enablecrosspartition`=TRUE)) lst <- process_cosmos_response(res) sapply(lst$PartitionKeyRanges, `[[`, "id") }
/scratch/gouwar.j/cran-all/cranData/AzureCosmosR/R/partition_key.R
#' Query an Azure Cosmos DB container #' #' @param container A Cosmos DB container object, as obtained by `get_cosmos_container` or `create_cosmos_container`. #' @param query A string containing the query text. #' @param parameters A named list of parameters to pass to a parameterised query, if required. #' @param cross_partition,partition_key,by_pkrange Arguments that control how to handle cross-partition queries. See 'Details' below. #' @param as_data_frame Whether to return the query result as a data frame, or a list of Cosmos DB document objects. #' @param metadata Whether to include Cosmos DB document metadata in the query result. #' @param headers,... Optional arguments passed to lower-level functions. #' @details #' This is the primary function for querying the contents of a Cosmos DB container (table). The `query` argument should contain the text of a SQL query, optionally parameterised. if the query contains parameters, pass them in the `parameters` argument as a named list. #' #' Cosmos DB is a partitioned key-value store under the hood, with documents stored in separate physical databases according to their value of the partition key. The Cosmos DB REST API has limited support for cross-partition queries: basic SELECTs should work, but aggregates and more complex queries may require some hand-hacking. #' #' The default `cross_partition=TRUE` runs the query for all partition key values and then attempts to stitch the results together. To run the query for only one key value, set `cross_partition=FALSE` and `partition_key` to the desired value. You can obtain all the values of the key with the [list_partition_key_values] function. #' #' The `by_pkrange` argument allows running the query separately across all _partition key ranges_. Each partition key range corresponds to a separate physical partition, and contains the documents for one or more key values. You can set this to TRUE to run a query that fails when run across partitions; the returned object will be a list containing the individual query results from each pkrange. #' #' As an alternative to AzureCosmosR, you can also use the ODBC protocol to interface with the SQL API. By installing a suitable ODBC driver, you can then talk to Cosmos DB in a manner similar to other SQL databases. An advantage of the ODBC interface is that it fully supports cross-partition queries, unlike the REST API. A disadvantage is that it does not support nested document fields; functions like `array_contains()` cannot be used, and attempts to reference arrays and objects may return incorrect results. #' @return #' `query_documents` returns the results of the query. Most of the time this will be a data frame, or list of data frames if `by_pkrange=TRUE`. #' @seealso #' [cosmos_container], [cosmos_document], [list_partition_key_values], [list_partition_key_ranges] #' @examples #' \dontrun{ #' #' endp <- cosmos_endpoint("https://myaccount.documents.azure.com:443/", key="mykey") #' #' # importing the Star Wars data from dplyr #' cont <- endp %>% #' get_cosmos_database(endp, "mydatabase") %>% #' create_cosmos_container(db, "mycontainer", partition_key="sex") #' #' bulk_import(cont, dplyr::starwars) #' #' query_documents(cont, "select * from mycontainer") #' #' # removing the Cosmos DB metadata cruft #' query_documents(cont, "select * from mycontainer", metadata=FALSE) #' #' # a simple filter #' query_documents(cont, "select * from mycontainer c where c.gender = 'masculine'") #' #' # run query for one partition key -- zero rows returned #' query_documents(cont, "select * from mycontainer c where c.gender = 'masculine'", #' partition_key="female") #' #' # aggregates will fail -- API does not fully support cross-partition queries #' try(query_documents(cont, "select avg(c.height) avgheight from mycontainer c")) #' # Error in process_cosmos_response.response(response, simplify = as_data_frame) : #' # Bad Request (HTTP 400). Failed to complete Cosmos DB operation. Message: #' # ... #' #' # run query separately by pkrange and combine the results manually #' query_documents( #' cont, #' "select avg(c.height) avgheight, count(1) n from mycontainer c", #' by_pkrange=TRUE #' ) #' #' } #' @export query_documents <- function(container, ...) { UseMethod("query_documents") } #' @rdname query_documents #' @export query_documents.cosmos_container <- function(container, query, parameters=list(), cross_partition=TRUE, partition_key=NULL, by_pkrange=FALSE, as_data_frame=TRUE, metadata=TRUE, headers=list(), ...) { headers <- utils::modifyList(headers, list(`Content-Type`="application/query+json")) if(cross_partition) headers$`x-ms-documentdb-query-enablecrosspartition` <- TRUE if(!is.null(partition_key)) headers$`x-ms-documentdb-partitionkey` <- jsonlite::toJSON(partition_key) if(length(query) > 1) query <- paste0(query, collapse="\n") body <- list(query=query, parameters=make_parameter_list(parameters)) res <- do_cosmos_op(container, "docs", "docs", headers=headers, body=body, encode="json", http_verb="POST", ...) # sending query to individual partitions (low-level API) if(by_pkrange) { message("Running query on individual pkrange") # if(query_needs_rewrite(res)) # { # message("Also rewriting query for individual pkranges") # body$query <- rewrite_query(res) # } part_ids <- list_partition_key_ranges(container) lapply(part_ids, function(id) { headers$`x-ms-documentdb-partitionkeyrangeid` <- id res_part <- do_cosmos_op(container, "docs", "docs", headers=headers, body=body, encode="json", http_verb="POST", ...) get_docs(res_part, as_data_frame, metadata, container) }) } else get_docs(res, as_data_frame, metadata, container) } make_parameter_list <- function(parlist) { parnames <- names(parlist) noatsign <- substr(parnames, 1, 1) != "@" parnames[noatsign] <- paste0("@", parnames[noatsign]) Map(function(n, v) c(name=n, value=v), parnames, parlist, USE.NAMES=FALSE) } get_docs <- function(response, as_data_frame, metadata, container) { docs <- process_cosmos_response(response, simplify=as_data_frame) if(as_data_frame) { docs <- if(inherits(response, "response")) docs$Documents else do.call(vctrs::vec_rbind, lapply(docs, `[[`, "Documents")) if(is_empty(docs)) return(data.frame()) if(!metadata && is.data.frame(docs)) # a query can return scalars rather than documents docs[c("id", "_rid", "_self", "_etag", "_attachments", "_ts")] <- NULL return(docs) } else { docs <- if(inherits(response, "response")) docs$Documents else unlist(lapply(docs, `[[`, "Documents"), recursive=FALSE, use.names=FALSE) return(lapply(docs, as_document, container=container)) } } # bad_query_with_valid_syntax <- function(response) # { # if(!inherits(response, "response") || httr::status_code(response) != 400) # return(FALSE) # cont <- httr::content(response) # is.character(cont$message) && !grepl("Syntax error", cont$message, fixed=TRUE) # } # query_needs_rewrite <- function(response) # { # cont <- httr::content(response) # if(is.null(cont$additionalErrorInfo)) # return(FALSE) # qry <- try(jsonlite::fromJSON(cont$additionalErrorInfo)$queryInfo$rewrittenQuery, silent=TRUE) # if(inherits(qry, "try-error")) # return(FALSE) # is.character(qry) && nchar(qry) > 0 # } # rewrite_query <- function(response) # { # cont <- httr::content(response) # jsonlite::fromJSON(cont$additionalErrorInfo)$queryInfo$rewrittenQuery # }
/scratch/gouwar.j/cran-all/cranData/AzureCosmosR/R/query.R
sign_sha256 <- function(string, key) { openssl::base64_encode(openssl::sha256(charToRaw(string), openssl::base64_decode(key))) } sign_cosmos_request <- function(key, verb, resource_type, resource_link, date) { if(key$type == "resource") return(curl::curl_escape(key$value)) if(inherits(date, "POSIXt")) date <- httr::http_date(date) string_to_sign <- paste( tolower(verb), tolower(resource_type), resource_link, tolower(date), "", "", sep="\n" ) sig <- sign_sha256(string_to_sign, key$value) curl::curl_escape(sprintf("type=%s&ver=1.0&sig=%s", key$type, sig)) }
/scratch/gouwar.j/cran-all/cranData/AzureCosmosR/R/sign_request.R
#' Methods for working with Azure Cosmos DB stored procedures #' #' @param object A Cosmos DB container object, as obtained by `get_cosmos_container` or `create_cosmos_container`, or for `delete_stored_procedure.cosmos_stored_procedure`, the stored procedure object. #' @param procname The name of the stored procedure. #' @param body For `create_stored_procedure` and `replace_stored_procedure`, the body of the stored procedure. This can be either a character string containing the source code, or the name of a source file. #' @param parameters For `exec_stored_procedure`, a list of parameters to pass to the procedure. #' @param confirm For `delete_stored_procedure`, whether to ask for confirmation before deleting. #' @param ... Optional arguments passed to lower-level functions. #' @details #' These are methods for working with stored procedures in Azure Cosmos DB using the core (SQL) API. In the Cosmos DB model, stored procedures are written in JavaScript and associated with a container. #' #' @return #' For `get_stored_procedure` and `create_stored_procedure`, an object of class `cosmos_stored_procedure`. For `list_stored_procedures`, a list of such objects. #' @seealso #' [cosmos_container], [get_udf] #' @examples #' \dontrun{ #' #' endp <- cosmos_endpoint("https://myaccount.documents.azure.com:443/", key="mykey") #' db <- get_cosmos_database(endp, "mydatabase") #' cont <- create_cosmos_container(db, "mycontainer", partition_key="sex") #' #' # a simple stored procedure #' src <- 'function helloworld() { #' var context = getContext(); #' var response = context.getResponse(); #' response.setBody("Hello, World"); #' }' #' create_stored_procedure(cont, "helloworld", src) #' sproc <- get_stored_procedure(cont, "helloworld") #' exec_stored_procedure(sproc) #' #' # more complex example: uploading data #' sproc2 <- create_stored_procedure(cont, "myBulkUpload", #' body=system.file("srcjs/bulkUpload.js", package="AzureCosmosR")) #' #' list_stored_procedures(cont) #' #' sw_male <- dplyr::filter(dplyr::starwars, sex == "male") #' exec_stored_procedure(sproc2, parameters=list(sw_male)) #' #' delete_stored_procedure(sproc) #' delete_stored_procedure(sproc2) #' #' } #' @aliases cosmos_stored_procedure #' @rdname cosmos_stored_procedure #' @export get_stored_procedure <- function(object, ...) { UseMethod("get_stored_procedure") } #' @rdname cosmos_stored_procedure #' @export get_stored_procedure.cosmos_container <- function(object, procname, ...) { path <- file.path("sprocs", procname) res <- do_cosmos_op(object, path, "sprocs", path, ...) sproc <- process_cosmos_response(res) as_stored_procedure(sproc, object) } #' @rdname cosmos_stored_procedure #' @export list_stored_procedures <- function(object, ...) { UseMethod("list_stored_procedures") } #' @export list_stored_procedures.cosmos_container <- function(object, ...) { res <- do_cosmos_op(object, "sprocs", "sprocs", "", ...) atts <- if(inherits(res, "response")) process_cosmos_response(res)$StoredProcedures else unlist(lapply(process_cosmos_response(res), `[[`, "StoredProcedures"), recursive=FALSE) lapply(atts, as_stored_procedure, container=object) } #' @rdname cosmos_stored_procedure #' @export create_stored_procedure <- function(object, ...) { UseMethod("create_stored_procedure") } #' @rdname cosmos_stored_procedure #' @export create_stored_procedure.cosmos_container <- function(object, procname, body, ...) { if(is.character(body) && length(body) == 1 && file.exists(body)) body <- readLines(body) body <- list(id=procname, body=paste0(body, collapse="\n")) res <- do_cosmos_op(object, "sprocs", "sprocs", "", body=body, encode="json", http_verb="POST", ...) sproc <- process_cosmos_response(res) invisible(as_stored_procedure(sproc, object)) } #' @rdname cosmos_stored_procedure #' @export exec_stored_procedure <- function(object, ...) { UseMethod("exec_stored_procedure") } #' @rdname cosmos_stored_procedure #' @export exec_stored_procedure.cosmos_container <- function(object, procname, parameters=list(), ...) { path <- file.path("sprocs", procname) res <- do_cosmos_op(object, path, "sprocs", path, body=parameters, encode="json", http_verb="POST", ...) process_cosmos_response(res) } #' @rdname cosmos_stored_procedure #' @export exec_stored_procedure.cosmos_stored_procedure <- function(object, ...) { exec_stored_procedure(object$container, object$id, ...) } #' @rdname cosmos_stored_procedure #' @export replace_stored_procedure <- function(object, ...) { UseMethod("replace_stored_procedure") } #' @rdname cosmos_stored_procedure #' @export replace_stored_procedure.cosmos_container <- function(object, procname, body, ...) { body <- list(id=procname, body=body) path <- file.path("sprocs", procname) res <- do_cosmos_op(object, path, "sprocs", path, body=body, encode="json", http_verb="PUT", ...) sproc <- process_cosmos_response(res) invisible(as_stored_procedure(sproc, object)) } #' @rdname cosmos_stored_procedure #' @export replace_stored_procedure.cosmos_stored_procedure <- function(object, body, ...) { replace_stored_procedure.cosmos_container(object$container, object$id, body, ...) } #' @rdname cosmos_stored_procedure #' @export delete_stored_procedure <- function(object, ...) { UseMethod("delete_stored_procedure") } #' @rdname cosmos_stored_procedure #' @export delete_stored_procedure.cosmos_container <- function(object, procname, confirm=TRUE, ...) { if(!delete_confirmed(confirm, procname, "stored procedure")) return(invisible(NULL)) path <- file.path("sprocs", procname) res <- do_cosmos_op(object, path, "sprocs", path, http_verb="DELETE", ...) invisible(process_cosmos_response(res)) } #' @rdname cosmos_stored_procedure #' @export delete_stored_procedure.cosmos_stored_procedure <- function(object, ...) { delete_stored_procedure(object$container, object$id, ...) } #' @export print.cosmos_stored_procedure <- function(x, ...) { cat("Cosmos DB SQL stored procedure '", x$id, "'\n", sep="") invisible(x) } as_stored_procedure <- function(sproc, container) { sproc$container <- container structure(sproc, class="cosmos_stored_procedure") }
/scratch/gouwar.j/cran-all/cranData/AzureCosmosR/R/sproc.R
#' Methods for working with Azure Cosmos DB user-defined functions #' #' @param object A Cosmos DB container object, as obtained by `get_cosmos_container` or `create_cosmos_container`, or for `delete_udf.cosmos_udf`, the function object. #' @param funcname The name of the user-defined function. #' @param body For `create_udf` and `replace_udf`, the body of the function. This can be either a character string containing the source code, or the name of a source file. #' @param confirm For `delete_udf`, whether to ask for confirmation before deleting. #' @param ... Optional arguments passed to lower-level functions. #' @details #' These are methods for working with user-defined functions (UDFs) in Azure Cosmos DB using the core (SQL) API. In the Cosmos DB model, UDFs are written in JavaScript and associated with a container. #' #' @return #' For `get_udf` and `create_udf`, an object of class `cosmos_udf`. For `list_udfs`, a list of such objects. #' @seealso #' [cosmos_container], [get_stored_procedure] #' @examples #' \dontrun{ #' #' endp <- cosmos_endpoint("https://myaccount.documents.azure.com:443/", key="mykey") #' db <- get_cosmos_database(endp, "mydatabase") #' #' # importing the Star Wars data from dplyr #' cont <- endp %>% #' get_cosmos_database(endp, "mydatabase") %>% #' create_cosmos_container(db, "mycontainer", partition_key="sex") #' #' create_udf(cont, "times2", "function(x) { return 2*x; }") #' #' list_udfs(cont) #' #' # UDFs in queries are prefixed with the 'udf.' identifier #' query_documents(cont, "select udf.times2(c.height) t2 from cont c") #' #' delete_udf(cont, "times2") #' #' } #' @rdname cosmos_udf #' @export get_udf <- function(object, ...) { UseMethod("get_udf") } #' @rdname cosmos_udf #' @export get_udf.cosmos_container <- function(object, funcname, ...) { path <- file.path("udfs", funcname) res <- do_cosmos_op(object, path, "udfs", path, ...) udf <- process_cosmos_response(res) as_udf(udf, object) } #' @rdname cosmos_udf #' @export list_udfs <- function(object, ...) { UseMethod("list_udfs") } #' @export list_udfs.cosmos_container <- function(object, ...) { res <- do_cosmos_op(object, "udfs", "udfs", "", ...) atts <- if(inherits(res, "response")) process_cosmos_response(res)$UserDefinedFunctions else unlist(lapply(process_cosmos_response(res), `[[`, "UserDefinedFunctions"), recursive=FALSE) lapply(atts, as_udf, container=object) } #' @rdname cosmos_udf #' @export create_udf <- function(object, ...) { UseMethod("create_udf") } #' @rdname cosmos_udf #' @export create_udf.cosmos_container <- function(object, funcname, body, ...) { if(is.character(body) && length(body) == 1 && file.exists(body)) body <- readLines(body) body <- list(id=funcname, body=paste0(body, collapse="\n")) res <- do_cosmos_op(object, "udfs", "udfs", "", body=body, encode="json", http_verb="POST", ...) udf <- process_cosmos_response(res) invisible(as_udf(udf, object)) } #' @rdname cosmos_udf #' @export replace_udf <- function(object, ...) { UseMethod("replace_udf") } #' @rdname cosmos_udf #' @export replace_udf.cosmos_container <- function(object, funcname, body, ...) { body <- list(id=funcname, body=body) path <- file.path("udfs", funcname) res <- do_cosmos_op(object, path, "udfs", path, body=body, encode="json", http_verb="PUT", ...) udf <- process_cosmos_response(res) invisible(as_udf(udf, object)) } #' @rdname cosmos_udf #' @export replace_udf.cosmos_udf <- function(object, body, ...) { replace_udf.cosmos_container(object$container, object$id, body, ...) } #' @rdname cosmos_udf #' @export delete_udf <- function(object, ...) { UseMethod("delete_udf") } #' @rdname cosmos_udf #' @export delete_udf.cosmos_container <- function(object, funcname, confirm=TRUE, ...) { if(!delete_confirmed(confirm, funcname, "stored procedure")) return(invisible(NULL)) path <- file.path("udfs", funcname) res <- do_cosmos_op(object, path, "udfs", path, http_verb="DELETE", ...) invisible(process_cosmos_response(res)) } #' @rdname cosmos_udf #' @export delete_udf.cosmos_udf <- function(object, ...) { delete_udf(object$container, object$id, ...) } #' @export print.cosmos_udf <- function(x, ...) { cat("Cosmos DB SQL user defined function '", x$id, "'\n", sep="") invisible(x) } as_udf <- function(udf, container) { udf$container <- container structure(udf, class="cosmos_udf") }
/scratch/gouwar.j/cran-all/cranData/AzureCosmosR/R/udf.R
--- title: "AzureCosmosR: Interface to Azure Cosmos DB" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{AzureCosmosR} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- # AzureCosmosR An interface to [Azure Cosmos DB](https://azure.microsoft.com/en-us/services/cosmos-db/), a NoSQL database service from Microsoft. > Azure Cosmos DB is a fully managed NoSQL database for modern app development. Single-digit millisecond response times, and automatic and instant scalability, guarantee speed at any scale. Business continuity is assured with SLA-backed availability and enterprise-grade security. App development is faster and more productive thanks to turnkey multi region data distribution anywhere in the world, open source APIs and SDKs for popular languages. As a fully managed service, Azure Cosmos DB takes database administration off your hands with automatic management, updates and patching. It also handles capacity management with cost-effective serverless and automatic scaling options that respond to application needs to match capacity with demand. On the Resource Manager side, AzureCosmosR extends the [AzureRMR](https://cran.r-project.org/package=AzureRMR) class framework to allow creating and managing Cosmos DB accounts. On the client side, it provides a comprehensive interface to the Cosmos DB SQL/core API as well as bridges to the MongoDB and table storage APIs. ## SQL interface AzureCosmosR provides a suite of methods to work with databases, containers (tables) and documents (rows) using the SQL API. ```r library(dplyr) library(AzureCosmosR) endp <- cosmos_endpoint("https://myaccount.documents.azure.com:443/", key="mykey") list_cosmos_databases(endp) db <- get_cosmos_database(endp, "mydatabase") # create a new container and upload the Star Wars dataset from dplyr cont <- create_cosmos_container(db, "mycontainer", partition_key="sex") bulk_import(cont, starwars) query_documents(cont, "select * from mycontainer") # remove document metadata cruft query_documents(cont, "select * from mycontainer", metadata=FALSE) # an array select: all characters who appear in ANH query_documents(cont, "select c.name from mycontainer c where array_contains(c.films, 'A New Hope')") ``` You can easily create and execute stored procedures and user-defined functions: ```r proc <- create_stored_procedure( cont, "helloworld", 'function () { var context = getContext(); var response = context.getResponse(); response.setBody("Hello, World"); }' ) exec_stored_procedure(proc) create_udf(cont, "times2", "function(x) { return 2*x; }") query_documents(cont, "select udf.times2(c.height) from cont c") ``` Aggregates take some extra work, as the Cosmos DB REST API only has limited support for cross-partition queries. Set `by_pkrange=TRUE` in the `query_documents` call, which will run the query on each partition key range (pkrange) and return a list of data frames. You can then process the list to obtain an overall result. ```r # average height by sex, by pkrange df_lst <- query_documents(cont, "select c.gender, count(1) n, avg(c.height) height from mycontainer c group by c.gender", by_pkrange=TRUE ) # combine pkrange results df_lst %>% bind_rows(.id="pkrange") %>% group_by(gender) %>% summarise(height=weighted.mean(height, n)) ``` Full support for cross-partition queries, including aggregates, may come in a future version of AzureCosmosR. ## Other client interfaces ### MongoDB You can query data in a MongoDB-enabled Cosmos DB instance using the mongolite package. AzureCosmosR provides a simple bridge to facilitate this. ```r endp <- cosmos_mongo_endpoint("https://myaccount.mongo.cosmos.azure.com:443/", key="mykey") # a mongolite::mongo object conn <- cosmos_mongo_connection(endp, "mycollection", "mydatabase") conn$find("{}") ``` For more information on working with MongoDB, see the [mongolite](https://jeroen.github.io/mongolite/) documentation. ### Table storage You can work with data in a table storage-enabled Cosmos DB instance using the AzureTableStor package. ```r endp <- AzureTableStor::table_endpoint("https://myaccount.table.cosmos.azure.com:443/", key="mykey") tab <- AzureTableStor::storage_table(endp, "mytable") AzureTableStor::list_table_entities(tab, filter="firstname eq 'Satya'") ``` ### ODBC (SQL interface) As an alternative to AzureCosmosR, you can also use the ODBC protocol to interface with the SQL API. By installing a suitable ODBC driver, you can then talk to Cosmos DB in a manner similar to other SQL databases. An advantage of the ODBC interface is that it fully supports cross-partition queries, unlike the REST API. A disadvantage is that it does not support nested document fields; functions like `array_contains()` cannot be used, and attempts to reference arrays and objects may return incorrect results. ```r conn <- DBI::dbConnect( odbc::odbc(), driver="Microsoft Azure DocumentDB ODBC Driver", host="https://myaccount.documents.azure.com:443/", authenticationkey="mykey", RESTAPIversion="2018-12-31" # for large partition key support ) DBI::dbListTables(conn) DBI::dbGetQuery(conn, "select * from mycontainer where gender = 'masculine'") ``` ## Azure Resource Manager interface On the ARM side, AzureCosmosR extends the AzureRMR class framework with a new `az_cosmosdb` class representing a Cosmos DB account resource, and methods for the `az_resource_group` resource group class. ```r rg <- AzureRMR::get_azure_login()$ get_subscription("sub_id")$ get_resource_group("rgname") rg$create_cosmosdb_account("mycosmosdb", interface="sql", free_tier=TRUE) rg$list_cosmosdb_accounts() cosmos <- rg$get_cosmosdb_account("mycosmosdb") # access keys (passwords) for this account cosmos$list_keys() # get an endpoint object -- detects which API this account uses endp <- cosmos$get_endpoint() # API-specific endpoints cosmos$get_sql_endpoint() cosmos$get_mongo_endpoint() cosmos$get_table_endpoint() ``` ## Further information - [An introduction to Azure Cosmos DB](https://www.sqlservercentral.com/articles/an-introduction-to-azure-cosmos-db) - [Azure Cosmos DB documentation](https://docs.microsoft.com/en-us/azure/cosmos-db/) - [REST API reference](https://docs.microsoft.com/en-us/rest/api/cosmos-db/)
/scratch/gouwar.j/cran-all/cranData/AzureCosmosR/inst/doc/AzureCosmosR.Rmd
--- title: "AzureCosmosR: Interface to Azure Cosmos DB" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{AzureCosmosR} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- # AzureCosmosR An interface to [Azure Cosmos DB](https://azure.microsoft.com/en-us/services/cosmos-db/), a NoSQL database service from Microsoft. > Azure Cosmos DB is a fully managed NoSQL database for modern app development. Single-digit millisecond response times, and automatic and instant scalability, guarantee speed at any scale. Business continuity is assured with SLA-backed availability and enterprise-grade security. App development is faster and more productive thanks to turnkey multi region data distribution anywhere in the world, open source APIs and SDKs for popular languages. As a fully managed service, Azure Cosmos DB takes database administration off your hands with automatic management, updates and patching. It also handles capacity management with cost-effective serverless and automatic scaling options that respond to application needs to match capacity with demand. On the Resource Manager side, AzureCosmosR extends the [AzureRMR](https://cran.r-project.org/package=AzureRMR) class framework to allow creating and managing Cosmos DB accounts. On the client side, it provides a comprehensive interface to the Cosmos DB SQL/core API as well as bridges to the MongoDB and table storage APIs. ## SQL interface AzureCosmosR provides a suite of methods to work with databases, containers (tables) and documents (rows) using the SQL API. ```r library(dplyr) library(AzureCosmosR) endp <- cosmos_endpoint("https://myaccount.documents.azure.com:443/", key="mykey") list_cosmos_databases(endp) db <- get_cosmos_database(endp, "mydatabase") # create a new container and upload the Star Wars dataset from dplyr cont <- create_cosmos_container(db, "mycontainer", partition_key="sex") bulk_import(cont, starwars) query_documents(cont, "select * from mycontainer") # remove document metadata cruft query_documents(cont, "select * from mycontainer", metadata=FALSE) # an array select: all characters who appear in ANH query_documents(cont, "select c.name from mycontainer c where array_contains(c.films, 'A New Hope')") ``` You can easily create and execute stored procedures and user-defined functions: ```r proc <- create_stored_procedure( cont, "helloworld", 'function () { var context = getContext(); var response = context.getResponse(); response.setBody("Hello, World"); }' ) exec_stored_procedure(proc) create_udf(cont, "times2", "function(x) { return 2*x; }") query_documents(cont, "select udf.times2(c.height) from cont c") ``` Aggregates take some extra work, as the Cosmos DB REST API only has limited support for cross-partition queries. Set `by_pkrange=TRUE` in the `query_documents` call, which will run the query on each partition key range (pkrange) and return a list of data frames. You can then process the list to obtain an overall result. ```r # average height by sex, by pkrange df_lst <- query_documents(cont, "select c.gender, count(1) n, avg(c.height) height from mycontainer c group by c.gender", by_pkrange=TRUE ) # combine pkrange results df_lst %>% bind_rows(.id="pkrange") %>% group_by(gender) %>% summarise(height=weighted.mean(height, n)) ``` Full support for cross-partition queries, including aggregates, may come in a future version of AzureCosmosR. ## Other client interfaces ### MongoDB You can query data in a MongoDB-enabled Cosmos DB instance using the mongolite package. AzureCosmosR provides a simple bridge to facilitate this. ```r endp <- cosmos_mongo_endpoint("https://myaccount.mongo.cosmos.azure.com:443/", key="mykey") # a mongolite::mongo object conn <- cosmos_mongo_connection(endp, "mycollection", "mydatabase") conn$find("{}") ``` For more information on working with MongoDB, see the [mongolite](https://jeroen.github.io/mongolite/) documentation. ### Table storage You can work with data in a table storage-enabled Cosmos DB instance using the AzureTableStor package. ```r endp <- AzureTableStor::table_endpoint("https://myaccount.table.cosmos.azure.com:443/", key="mykey") tab <- AzureTableStor::storage_table(endp, "mytable") AzureTableStor::list_table_entities(tab, filter="firstname eq 'Satya'") ``` ### ODBC (SQL interface) As an alternative to AzureCosmosR, you can also use the ODBC protocol to interface with the SQL API. By installing a suitable ODBC driver, you can then talk to Cosmos DB in a manner similar to other SQL databases. An advantage of the ODBC interface is that it fully supports cross-partition queries, unlike the REST API. A disadvantage is that it does not support nested document fields; functions like `array_contains()` cannot be used, and attempts to reference arrays and objects may return incorrect results. ```r conn <- DBI::dbConnect( odbc::odbc(), driver="Microsoft Azure DocumentDB ODBC Driver", host="https://myaccount.documents.azure.com:443/", authenticationkey="mykey", RESTAPIversion="2018-12-31" # for large partition key support ) DBI::dbListTables(conn) DBI::dbGetQuery(conn, "select * from mycontainer where gender = 'masculine'") ``` ## Azure Resource Manager interface On the ARM side, AzureCosmosR extends the AzureRMR class framework with a new `az_cosmosdb` class representing a Cosmos DB account resource, and methods for the `az_resource_group` resource group class. ```r rg <- AzureRMR::get_azure_login()$ get_subscription("sub_id")$ get_resource_group("rgname") rg$create_cosmosdb_account("mycosmosdb", interface="sql", free_tier=TRUE) rg$list_cosmosdb_accounts() cosmos <- rg$get_cosmosdb_account("mycosmosdb") # access keys (passwords) for this account cosmos$list_keys() # get an endpoint object -- detects which API this account uses endp <- cosmos$get_endpoint() # API-specific endpoints cosmos$get_sql_endpoint() cosmos$get_mongo_endpoint() cosmos$get_table_endpoint() ``` ## Further information - [An introduction to Azure Cosmos DB](https://www.sqlservercentral.com/articles/an-introduction-to-azure-cosmos-db) - [Azure Cosmos DB documentation](https://docs.microsoft.com/en-us/azure/cosmos-db/) - [REST API reference](https://docs.microsoft.com/en-us/rest/api/cosmos-db/)
/scratch/gouwar.j/cran-all/cranData/AzureCosmosR/vignettes/AzureCosmosR.Rmd
#' @import AzureAuth #' @importFrom utils modifyList NULL utils::globalVariables(c("self", "private")) .onLoad <- function(libname, pkgname) { options(azure_graph_api_version="v1.0") invisible(NULL) } # default authentication app ID: leverage the az CLI .az_cli_app_id <- "04b07795-8ddb-461a-bbee-02f9e1bf7b46" # authentication app ID for personal accounts .azurer_graph_app_id <- "5bb21e8a-06bf-4ac4-b613-110ac0e582c1"
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/AzureGraph.R
#' Registered app in Azure Active Directory #' #' Base class representing an AAD app. #' #' @docType class #' @section Fields: #' - `token`: The token used to authenticate with the Graph host. #' - `tenant`: The Azure Active Directory tenant for this app. #' - `type`: always "application" for an app object. #' - `properties`: The app properties. #' - `password`: The app password. Note that the Graph API does not return previously-generated passwords. This field will only be populated for an app object created with `ms_graph$create_app()`, or after a call to the `add_password()` method below. #' @section Methods: #' - `new(...)`: Initialize a new app object. Do not call this directly; see 'Initialization' below. #' - `delete(confirm=TRUE)`: Delete an app. By default, ask for confirmation first. #' - `update(...)`: Update the app data in Azure Active Directory. For what properties can be updated, consult the REST API documentation link below. #' - `do_operation(...)`: Carry out an arbitrary operation on the app. #' - `sync_fields()`: Synchronise the R object with the app data in Azure Active Directory. #' - `list_owners(type=c("user", "group", "application", "servicePrincipal"), filter=NULL, n=Inf)`: Return a list of all owners of this app. Specify the `type` argument to limit the result to specific object type(s). #' - `create_service_principal(...)`: Create a service principal for this app, by default in the current tenant. #' - `get_service_principal()`: Get the service principal for this app. #' - `delete_service_principal(confirm=TRUE)`: Delete the service principal for this app. By default, ask for confirmation first. #' - `add_password(password_name=NULL, password_duration=NULL)`: Adds a strong password. `password_duration` is the length of time in years that the password remains valid, with default duration 2 years. Returns the ID of the generated password. #' - `remove_password(password_id, confirm=TRUE)`: Removes the password with the given ID. By default, ask for confirmation first. #' - `add_certificate(certificate)`: Adds a certificate for authentication. This can be specified as the name of a .pfx or .pem file, an `openssl::cert` object, an `AzureKeyVault::stored_cert` object, or a raw or character vector. #' - `remove_certificate(certificate_id, confirm=TRUE`): Removes the certificate with the given ID. By default, ask for confirmation first. #' #' @section Initialization: #' Creating new objects of this class should be done via the `create_app` and `get_app` methods of the [ms_graph] class. Calling the `new()` method for this class only constructs the R object; it does not call the Microsoft Graph API to create the actual app. #' #' [Microsoft Graph overview](https://learn.microsoft.com/en-us/graph/overview), #' [REST API reference](https://learn.microsoft.com/en-us/graph/api/overview?view=graph-rest-beta) #' #' @section List methods: #' All `list_*` methods have `filter` and `n` arguments to limit the number of results. The former should be an [OData expression](https://learn.microsoft.com/en-us/graph/query-parameters#filter-parameter) as a string to filter the result set on. The latter should be a number setting the maximum number of (filtered) results to return. The default values are `filter=NULL` and `n=Inf`. If `n=NULL`, the `ms_graph_pager` iterator object is returned instead to allow manual iteration over the results. #' #' Support in the underlying Graph API for OData queries is patchy. Not all endpoints that return lists of objects support filtering, and if they do, they may not allow all of the defined operators. If your filtering expression results in an error, you can carry out the operation without filtering and then filter the results on the client side. #' @seealso #' [ms_graph], [az_service_principal], [az_user], [az_group], [az_object] #' #' @examples #' \dontrun{ #' #' gr <- get_graph_login() #' app <- gr$create_app("MyNewApp") #' #' # password resetting: remove the old password, add a new one #' pwd_id <- app$properties$passwordCredentials[[1]]$keyId #' app$add_password() #' app$remove_password(pwd_id) #' #' # set a redirect URI #' app$update(publicClient=list(redirectUris=I("http://localhost:1410"))) #' #' # add API permission (access Azure Storage as user) #' app$update(requiredResourceAccess=list( #' list( #' resourceAppId="e406a681-f3d4-42a8-90b6-c2b029497af1", #' resourceAccess=list( #' list( #' id="03e0da56-190b-40ad-a80c-ea378c433f7f", #' type="Scope" #' ) #' ) #' ) #' )) #' #' # add a certificate from a .pem file #' app$add_certificate("cert.pem") #' #' # can also read the file into an openssl object, and then add the cert #' cert <- openssl::read_cert("cert.pem") #' app$add_certificate(cert) #' #' # add a certificate stored in Azure Key Vault #' vault <- AzureKeyVault::key_vault("mytenant") #' cert2 <- vault$certificates$get("certname") #' app$add_certificate(cert2) #' #' # change the app name #' app$update(displayName="MyRenamedApp") #' #' } #' @format An R6 object of class `az_app`, inheriting from `az_object`. #' @export az_app <- R6::R6Class("az_app", inherit=az_object, public=list( password=NULL, initialize=function(token, tenant=NULL, properties=NULL, password=NULL) { self$type <- "application" private$api_type <- "applications" self$password <- password super$initialize(token, tenant, properties) }, add_password=function(password_name=NULL, password_duration=NULL) { creds <- list() if(!is.null(password_name)) creds$displayName <- password_name if(!is.null(password_duration)) { now <- as.POSIXlt(Sys.time()) now$year <- now$year + password_duration creds$endDateTime <- format(as.POSIXct(now), "%Y-%m-%dT%H:%M:%SZ", tz="GMT") } properties <- if(!is_empty(creds)) list(passwordCredential=creds) else NULL res <- self$do_operation("addPassword", body=properties, http_verb="POST") self$properties <- self$do_operation() self$password <- res$secretText invisible(res$keyId) }, remove_password=function(password_id, confirm=TRUE) { if(confirm && interactive()) { msg <- sprintf("Do you really want to remove the password '%s'?", password_id) if(!get_confirmation(msg, FALSE)) return(invisible(NULL)) } self$do_operation("removePassword", body=list(keyId=password_id), http_verb="POST") self$sync_fields() invisible(NULL) }, add_certificate=function(certificate) { key <- read_cert(certificate) creds <- c(self$properties$keyCredentials, list(list( key=key, type="AsymmetricX509Cert", usage="verify" ))) self$update(keyCredentials=creds) }, remove_certificate=function(certificate_id, confirm=TRUE) { if(confirm && interactive()) { msg <- sprintf("Do you really want to remove the certificate '%s'?", certificate_id) if(!get_confirmation(msg, FALSE)) return(invisible(NULL)) } creds <- self$properties$keyCredentials idx <- vapply(creds, function(keycred) keycred$keyId == certificate_id, logical(1)) if(!any(idx)) stop("Certificate not found", call.=FALSE) self$update(keyCredentials=creds[-idx]) }, list_owners=function(type=c("user", "group", "application", "servicePrincipal"), filter=NULL, n=Inf) { opts <- list(`$filter`=filter, `$count`=if(!is.null(filter)) "true") hdrs <- if(!is.null(filter)) httr::add_headers(consistencyLevel="eventual") pager <- self$get_list_pager(self$do_operation("owners", options=opts, hdrs, type_filter=type)) extract_list_values(pager, n) }, create_service_principal=function(...) { properties <- modifyList(list(...), list(appId=self$properties$appId)) az_service_principal$new( self$token, self$tenant, call_graph_endpoint(self$token, "servicePrincipals", body=properties, encode="json", http_verb="POST") ) }, get_service_principal=function() { op <- sprintf("servicePrincipals?$filter=appId+eq+'%s'", self$properties$appId) az_service_principal$new( self$token, self$tenant, call_graph_endpoint(self$token, op)$value[[1]] ) }, delete_service_principal=function(confirm=TRUE) { self$get_service_principal()$delete(confirm=confirm) }, print=function(...) { cat("<Graph registered app '", self$properties$displayName, "'>\n", sep="") cat(" app id:", self$properties$appId, "\n") cat(" directory id:", self$properties$id, "\n") cat(" domain:", self$properties$publisherDomain, "\n") cat("---\n") cat(format_public_methods(self)) invisible(self) } ))
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/az_app.r
#' Device in Azure Active Directory #' #' Class representing a registered device. #' #' @docType class #' @section Fields: #' - `token`: The token used to authenticate with the Graph host. #' - `tenant`: The Azure Active Directory tenant for this group. #' - `type`: always "device" for a device object. #' - `properties`: The device properties. #' @section Methods: #' - `new(...)`: Initialize a new device object. Do not call this directly; see 'Initialization' below. #' - `delete(confirm=TRUE)`: Delete a device. By default, ask for confirmation first. #' - `update(...)`: Update the device information in Azure Active Directory. #' - `do_operation(...)`: Carry out an arbitrary operation on the device. #' - `sync_fields()`: Synchronise the R object with the app data in Azure Active Directory. #' #' @section Initialization: #' Create objects of this class via the `list_registered_devices()` and `list_owned_devices()` methods of the `az_user` class. #' #' @seealso #' [ms_graph], [az_user], [az_object] #' #' [Microsoft Graph overview](https://learn.microsoft.com/en-us/graph/overview), #' [REST API reference](https://learn.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0) #' #' @format An R6 object of class `az_device`, inheriting from `az_object`. #' @export az_device <- R6::R6Class("az_device", inherit=az_object, public=list( initialize=function(token, tenant=NULL, properties=NULL) { self$type <- "device" super$initialize(token, tenant, properties) }, print=function(...) { cat("<Graph device '", self$properties$displayName, "'>\n", sep="") cat(" directory id:", self$properties$id, "\n") cat(" device id:", self$properties$deviceId, "\n") invisible(self) } ))
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/az_device.R
#' Directory role #' #' Class representing a role in Azure Active Directory. #' #' @docType class #' @section Fields: #' - `token`: The token used to authenticate with the Graph host. #' - `tenant`: The Azure Active Directory tenant for this role. #' - `type`: always "directory role" for a directory role object. #' - `properties`: The item properties. #' @section Methods: #' - `new(...)`: Initialize a new object. Do not call this directly; see 'Initialization' below. #' - `delete(confirm=TRUE)`: Delete this item. By default, ask for confirmation first. #' - `update(...)`: Update the item's properties in Microsoft Graph. #' - `do_operation(...)`: Carry out an arbitrary operation on the item. #' - `sync_fields()`: Synchronise the R object with the item metadata in Microsoft Graph. #' - `list_members(filter=NULL, n=Inf)`: Return a list of all members of this group. #' #' @section Initialization: #' Currently support for directory roles is limited. Objects of this class should not be initialized directly. #' #' @section List methods: #' All `list_*` methods have `filter` and `n` arguments to limit the number of results. The former should be an [OData expression](https://learn.microsoft.com/en-us/graph/query-parameters#filter-parameter) as a string to filter the result set on. The latter should be a number setting the maximum number of (filtered) results to return. The default values are `filter=NULL` and `n=Inf`. If `n=NULL`, the `ms_graph_pager` iterator object is returned instead to allow manual iteration over the results. #' #' Support in the underlying Graph API for OData queries is patchy. Not all endpoints that return lists of objects support filtering, and if they do, they may not allow all of the defined operators. If your filtering expression results in an error, you can carry out the operation without filtering and then filter the results on the client side. #' @seealso #' [ms_graph], [az_user] #' #' [Microsoft Graph overview](https://learn.microsoft.com/en-us/graph/overview), #' [REST API reference](https://learn.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0) #' #' @format An R6 object of class `az_directory_role`, inheriting from `az_object`. #' @export az_directory_role <- R6::R6Class("az_directory_role", inherit=az_object, public=list( initialize=function(token, tenant=NULL, properties=NULL) { self$type <- "directory role" private$api_type <- "directoryRoles" super$initialize(token, tenant, properties) }, list_members=function(filter=NULL, n=Inf) { opts <- list(`$filter`=filter, `$count`=if(!is.null(filter)) "true") hdrs <- if(!is.null(filter)) httr::add_headers(consistencyLevel="eventual") pager <- self$get_list_pager(self$do_operation("members", options=opts, hdrs)) extract_list_values(pager, n) }, print=function(...) { cat("<Azure Active Directory role '", self$properties$displayName, "'>\n", sep="") cat(" directory id:", self$properties$id, "\n") cat(" description:", self$properties$description, "\n") cat("---\n") cat(format_public_methods(self)) invisible(self) } ))
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/az_dir_role.R
#' Group in Azure Active Directory #' #' Class representing an AAD group. #' #' @docType class #' @section Fields: #' - `token`: The token used to authenticate with the Graph host. #' - `tenant`: The Azure Active Directory tenant for this group. #' - `type`: always "group" for a group object. #' - `properties`: The group properties. #' @section Methods: #' - `new(...)`: Initialize a new group object. Do not call this directly; see 'Initialization' below. #' - `delete(confirm=TRUE)`: Delete a group. By default, ask for confirmation first. #' - `update(...)`: Update the group information in Azure Active Directory. #' - `do_operation(...)`: Carry out an arbitrary operation on the group. #' - `sync_fields()`: Synchronise the R object with the app data in Azure Active Directory. #' - `list_members(type=c("user", "group", "application", "servicePrincipal"), filter=NULL, n=Inf)`: Return a list of all members of this group. Specify the `type` argument to limit the result to specific object type(s). #' - `list_owners(type=c("user", "group", "application", "servicePrincipal"), filter=NULL, n=Inf)`: Return a list of all owners of this group. Specify the `type` argument to limit the result to specific object type(s). #' #' @section Initialization: #' Creating new objects of this class should be done via the `create_group` and `get_group` methods of the [ms_graph] and [az_app] classes. Calling the `new()` method for this class only constructs the R object; it does not call the Microsoft Graph API to create the actual group. #' #' @section List methods: #' All `list_*` methods have `filter` and `n` arguments to limit the number of results. The former should be an [OData expression](https://learn.microsoft.com/en-us/graph/query-parameters#filter-parameter) as a string to filter the result set on. The latter should be a number setting the maximum number of (filtered) results to return. The default values are `filter=NULL` and `n=Inf`. If `n=NULL`, the `ms_graph_pager` iterator object is returned instead to allow manual iteration over the results. #' #' Support in the underlying Graph API for OData queries is patchy. Not all endpoints that return lists of objects support filtering, and if they do, they may not allow all of the defined operators. If your filtering expression results in an error, you can carry out the operation without filtering and then filter the results on the client side. #' @seealso #' [ms_graph], [az_app], [az_user], [az_object] #' #' [Microsoft Graph overview](https://learn.microsoft.com/en-us/graph/overview), #' [REST API reference](https://learn.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0) #' #' @examples #' \dontrun{ #' #' gr <- get_graph_login() #' usr <- gr$get_user("[email protected]") #' #' grps <- usr$list_group_memberships() #' grp <- gr$get_group(grps[1]) #' #' grp$list_members() #' grp$list_owners() #' #' # capping the number of results #' grp$list_members(n=10) #' #' # get the pager object for a listing method #' pager <- grp$list_members(n=NULL) #' pager$value #' #' } #' @format An R6 object of class `az_group`, inheriting from `az_object`. #' @export az_group <- R6::R6Class("az_group", inherit=az_object, public=list( initialize=function(token, tenant=NULL, properties=NULL) { self$type <- "group" private$api_type <- "groups" super$initialize(token, tenant, properties) }, list_members=function(type=c("user", "group", "application", "servicePrincipal"), filter=NULL, n=Inf) { opts <- list(`$filter`=filter, `$count`=if(!is.null(filter)) "true") hdrs <- if(!is.null(filter)) httr::add_headers(consistencyLevel="eventual") pager <- self$get_list_pager(self$do_operation("members", options=opts, hdrs), type_filter=type) extract_list_values(pager, n) }, list_owners=function(type=c("user", "group", "application", "servicePrincipal"), filter=NULL, n=Inf) { opts <- list(`$filter`=filter, `$count`=if(!is.null(filter)) "true") hdrs <- if(!is.null(filter)) httr::add_headers(consistencyLevel="eventual") pager <- self$get_list_pager(self$do_operation("owners", options=opts, hdrs), type_filter=type) extract_list_values(pager, n) }, print=function(...) { group_type <- if("Unified" %in% self$properties$groupTypes) "Microsoft 365" else if(!self$properties$mailEnabled) "Security" else if(self$properties$securityEnabled) "Mail-enabled security" else "Distribution" cat("<", group_type, " group '", self$properties$displayName, "'>\n", sep="") cat(" directory id:", self$properties$id, "\n") cat(" description:", self$properties$description, "\n") cat("---\n") cat(format_public_methods(self)) invisible(self) } ))
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/az_group.R