code
stringlengths
1
13.8M
estimate_ss_cor <- function(ref_pcs, ref_genotypes, link_function) { X_mat <- as.matrix(cbind(1, ref_pcs)) W_mat <- diag(x=1, nrow=nrow(ref_pcs), ncol=nrow(ref_pcs)) P_mat <- W_mat - X_mat %*% solve(t(X_mat) %*% X_mat) %*% t(X_mat) est_cor <- matrix(data=NA, nrow=ncol(ref_genotypes), ncol=ncol(ref_genotypes)) denominators <- rep(NA, ncol(ref_genotypes)) for (i in 1:ncol(ref_genotypes)) { temp_G <- ref_genotypes[,i] denominators[i] <- sqrt(t(temp_G) %*% P_mat %*% temp_G) } for (temp_row in 2:ncol(ref_genotypes)) { for (temp_col in 1:(temp_row-1)) { est_cor[temp_row, temp_col] <- t(ref_genotypes[,temp_row]) %*% P_mat %*% ref_genotypes[,temp_col] / (denominators[temp_row] * denominators[temp_col]) est_cor[temp_col, temp_row] <- est_cor[temp_row, temp_col] } } return (est_cor) }
NULL .networkfirewall$associate_firewall_policy_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(UpdateToken = structure(logical(0), tags = list(type = "string")), FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallName = structure(logical(0), tags = list(type = "string")), FirewallPolicyArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$associate_firewall_policy_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallName = structure(logical(0), tags = list(type = "string")), FirewallPolicyArn = structure(logical(0), tags = list(type = "string")), UpdateToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$associate_subnets_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(UpdateToken = structure(logical(0), tags = list(type = "string")), FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallName = structure(logical(0), tags = list(type = "string")), SubnetMappings = structure(list(structure(list(SubnetId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$associate_subnets_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallName = structure(logical(0), tags = list(type = "string")), SubnetMappings = structure(list(structure(list(SubnetId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), UpdateToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$create_firewall_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(FirewallName = structure(logical(0), tags = list(type = "string")), FirewallPolicyArn = structure(logical(0), tags = list(type = "string")), VpcId = structure(logical(0), tags = list(type = "string")), SubnetMappings = structure(list(structure(list(SubnetId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), DeleteProtection = structure(logical(0), tags = list(type = "boolean")), SubnetChangeProtection = structure(logical(0), tags = list(type = "boolean")), FirewallPolicyChangeProtection = structure(logical(0), tags = list(type = "boolean")), Description = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$create_firewall_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Firewall = structure(list(FirewallName = structure(logical(0), tags = list(type = "string")), FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallPolicyArn = structure(logical(0), tags = list(type = "string")), VpcId = structure(logical(0), tags = list(type = "string")), SubnetMappings = structure(list(structure(list(SubnetId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), DeleteProtection = structure(logical(0), tags = list(type = "boolean")), SubnetChangeProtection = structure(logical(0), tags = list(type = "boolean")), FirewallPolicyChangeProtection = structure(logical(0), tags = list(type = "boolean")), Description = structure(logical(0), tags = list(type = "string")), FirewallId = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")), FirewallStatus = structure(list(Status = structure(logical(0), tags = list(type = "string")), ConfigurationSyncStateSummary = structure(logical(0), tags = list(type = "string")), SyncStates = structure(list(structure(list(Attachment = structure(list(SubnetId = structure(logical(0), tags = list(type = "string")), EndpointId = structure(logical(0), tags = list(type = "string")), Status = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")), Config = structure(list(structure(list(SyncStatus = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$create_firewall_policy_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(FirewallPolicyName = structure(logical(0), tags = list(type = "string")), FirewallPolicy = structure(list(StatelessRuleGroupReferences = structure(list(structure(list(ResourceArn = structure(logical(0), tags = list(type = "string")), Priority = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure"))), tags = list(type = "list")), StatelessDefaultActions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), StatelessFragmentDefaultActions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), StatelessCustomActions = structure(list(structure(list(ActionName = structure(logical(0), tags = list(type = "string")), ActionDefinition = structure(list(PublishMetricAction = structure(list(Dimensions = structure(list(structure(list(Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure"))), tags = list(type = "structure"))), tags = list(type = "list")), StatefulRuleGroupReferences = structure(list(structure(list(ResourceArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")), Description = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), DryRun = structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$create_firewall_policy_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(UpdateToken = structure(logical(0), tags = list(type = "string")), FirewallPolicyResponse = structure(list(FirewallPolicyName = structure(logical(0), tags = list(type = "string")), FirewallPolicyArn = structure(logical(0), tags = list(type = "string")), FirewallPolicyId = structure(logical(0), tags = list(type = "string")), Description = structure(logical(0), tags = list(type = "string")), FirewallPolicyStatus = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$create_rule_group_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(RuleGroupName = structure(logical(0), tags = list(type = "string")), RuleGroup = structure(list(RuleVariables = structure(list(IPSets = structure(list(structure(list(Definition = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "map")), PortSets = structure(list(structure(list(Definition = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "map"))), tags = list(type = "structure")), RulesSource = structure(list(RulesString = structure(logical(0), tags = list(type = "string")), RulesSourceList = structure(list(Targets = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), TargetTypes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), GeneratedRulesType = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")), StatefulRules = structure(list(structure(list(Action = structure(logical(0), tags = list(type = "string")), Header = structure(list(Protocol = structure(logical(0), tags = list(type = "string")), Source = structure(logical(0), tags = list(type = "string")), SourcePort = structure(logical(0), tags = list(type = "string")), Direction = structure(logical(0), tags = list(type = "string")), Destination = structure(logical(0), tags = list(type = "string")), DestinationPort = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")), RuleOptions = structure(list(structure(list(Keyword = structure(logical(0), tags = list(type = "string")), Settings = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "list")), StatelessRulesAndCustomActions = structure(list(StatelessRules = structure(list(structure(list(RuleDefinition = structure(list(MatchAttributes = structure(list(Sources = structure(list(structure(list(AddressDefinition = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), Destinations = structure(list(structure(list(AddressDefinition = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), SourcePorts = structure(list(structure(list(FromPort = structure(logical(0), tags = list(type = "integer")), ToPort = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure"))), tags = list(type = "list")), DestinationPorts = structure(list(structure(list(FromPort = structure(logical(0), tags = list(type = "integer")), ToPort = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure"))), tags = list(type = "list")), Protocols = structure(list(structure(logical(0), tags = list(type = "integer"))), tags = list(type = "list")), TCPFlags = structure(list(structure(list(Flags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), Masks = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")), Actions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure")), Priority = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure"))), tags = list(type = "list")), CustomActions = structure(list(structure(list(ActionName = structure(logical(0), tags = list(type = "string")), ActionDefinition = structure(list(PublishMetricAction = structure(list(Dimensions = structure(list(structure(list(Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure"))), tags = list(type = "structure")), Rules = structure(logical(0), tags = list(type = "string")), Type = structure(logical(0), tags = list(type = "string")), Description = structure(logical(0), tags = list(type = "string")), Capacity = structure(logical(0), tags = list(type = "integer")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), DryRun = structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$create_rule_group_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(UpdateToken = structure(logical(0), tags = list(type = "string")), RuleGroupResponse = structure(list(RuleGroupArn = structure(logical(0), tags = list(type = "string")), RuleGroupName = structure(logical(0), tags = list(type = "string")), RuleGroupId = structure(logical(0), tags = list(type = "string")), Description = structure(logical(0), tags = list(type = "string")), Type = structure(logical(0), tags = list(type = "string")), Capacity = structure(logical(0), tags = list(type = "integer")), RuleGroupStatus = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$delete_firewall_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(FirewallName = structure(logical(0), tags = list(type = "string")), FirewallArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$delete_firewall_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Firewall = structure(list(FirewallName = structure(logical(0), tags = list(type = "string")), FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallPolicyArn = structure(logical(0), tags = list(type = "string")), VpcId = structure(logical(0), tags = list(type = "string")), SubnetMappings = structure(list(structure(list(SubnetId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), DeleteProtection = structure(logical(0), tags = list(type = "boolean")), SubnetChangeProtection = structure(logical(0), tags = list(type = "boolean")), FirewallPolicyChangeProtection = structure(logical(0), tags = list(type = "boolean")), Description = structure(logical(0), tags = list(type = "string")), FirewallId = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")), FirewallStatus = structure(list(Status = structure(logical(0), tags = list(type = "string")), ConfigurationSyncStateSummary = structure(logical(0), tags = list(type = "string")), SyncStates = structure(list(structure(list(Attachment = structure(list(SubnetId = structure(logical(0), tags = list(type = "string")), EndpointId = structure(logical(0), tags = list(type = "string")), Status = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")), Config = structure(list(structure(list(SyncStatus = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$delete_firewall_policy_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(FirewallPolicyName = structure(logical(0), tags = list(type = "string")), FirewallPolicyArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$delete_firewall_policy_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(FirewallPolicyResponse = structure(list(FirewallPolicyName = structure(logical(0), tags = list(type = "string")), FirewallPolicyArn = structure(logical(0), tags = list(type = "string")), FirewallPolicyId = structure(logical(0), tags = list(type = "string")), Description = structure(logical(0), tags = list(type = "string")), FirewallPolicyStatus = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$delete_resource_policy_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$delete_resource_policy_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$delete_rule_group_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(RuleGroupName = structure(logical(0), tags = list(type = "string")), RuleGroupArn = structure(logical(0), tags = list(type = "string")), Type = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$delete_rule_group_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(RuleGroupResponse = structure(list(RuleGroupArn = structure(logical(0), tags = list(type = "string")), RuleGroupName = structure(logical(0), tags = list(type = "string")), RuleGroupId = structure(logical(0), tags = list(type = "string")), Description = structure(logical(0), tags = list(type = "string")), Type = structure(logical(0), tags = list(type = "string")), Capacity = structure(logical(0), tags = list(type = "integer")), RuleGroupStatus = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$describe_firewall_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(FirewallName = structure(logical(0), tags = list(type = "string")), FirewallArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$describe_firewall_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(UpdateToken = structure(logical(0), tags = list(type = "string")), Firewall = structure(list(FirewallName = structure(logical(0), tags = list(type = "string")), FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallPolicyArn = structure(logical(0), tags = list(type = "string")), VpcId = structure(logical(0), tags = list(type = "string")), SubnetMappings = structure(list(structure(list(SubnetId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), DeleteProtection = structure(logical(0), tags = list(type = "boolean")), SubnetChangeProtection = structure(logical(0), tags = list(type = "boolean")), FirewallPolicyChangeProtection = structure(logical(0), tags = list(type = "boolean")), Description = structure(logical(0), tags = list(type = "string")), FirewallId = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")), FirewallStatus = structure(list(Status = structure(logical(0), tags = list(type = "string")), ConfigurationSyncStateSummary = structure(logical(0), tags = list(type = "string")), SyncStates = structure(list(structure(list(Attachment = structure(list(SubnetId = structure(logical(0), tags = list(type = "string")), EndpointId = structure(logical(0), tags = list(type = "string")), Status = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")), Config = structure(list(structure(list(SyncStatus = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$describe_firewall_policy_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(FirewallPolicyName = structure(logical(0), tags = list(type = "string")), FirewallPolicyArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$describe_firewall_policy_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(UpdateToken = structure(logical(0), tags = list(type = "string")), FirewallPolicyResponse = structure(list(FirewallPolicyName = structure(logical(0), tags = list(type = "string")), FirewallPolicyArn = structure(logical(0), tags = list(type = "string")), FirewallPolicyId = structure(logical(0), tags = list(type = "string")), Description = structure(logical(0), tags = list(type = "string")), FirewallPolicyStatus = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")), FirewallPolicy = structure(list(StatelessRuleGroupReferences = structure(list(structure(list(ResourceArn = structure(logical(0), tags = list(type = "string")), Priority = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure"))), tags = list(type = "list")), StatelessDefaultActions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), StatelessFragmentDefaultActions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), StatelessCustomActions = structure(list(structure(list(ActionName = structure(logical(0), tags = list(type = "string")), ActionDefinition = structure(list(PublishMetricAction = structure(list(Dimensions = structure(list(structure(list(Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure"))), tags = list(type = "structure"))), tags = list(type = "list")), StatefulRuleGroupReferences = structure(list(structure(list(ResourceArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$describe_logging_configuration_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallName = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$describe_logging_configuration_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(FirewallArn = structure(logical(0), tags = list(type = "string")), LoggingConfiguration = structure(list(LogDestinationConfigs = structure(list(structure(list(LogType = structure(logical(0), tags = list(type = "string")), LogDestinationType = structure(logical(0), tags = list(type = "string")), LogDestination = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$describe_resource_policy_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$describe_resource_policy_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Policy = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$describe_rule_group_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(RuleGroupName = structure(logical(0), tags = list(type = "string")), RuleGroupArn = structure(logical(0), tags = list(type = "string")), Type = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$describe_rule_group_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(UpdateToken = structure(logical(0), tags = list(type = "string")), RuleGroup = structure(list(RuleVariables = structure(list(IPSets = structure(list(structure(list(Definition = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "map")), PortSets = structure(list(structure(list(Definition = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "map"))), tags = list(type = "structure")), RulesSource = structure(list(RulesString = structure(logical(0), tags = list(type = "string")), RulesSourceList = structure(list(Targets = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), TargetTypes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), GeneratedRulesType = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")), StatefulRules = structure(list(structure(list(Action = structure(logical(0), tags = list(type = "string")), Header = structure(list(Protocol = structure(logical(0), tags = list(type = "string")), Source = structure(logical(0), tags = list(type = "string")), SourcePort = structure(logical(0), tags = list(type = "string")), Direction = structure(logical(0), tags = list(type = "string")), Destination = structure(logical(0), tags = list(type = "string")), DestinationPort = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")), RuleOptions = structure(list(structure(list(Keyword = structure(logical(0), tags = list(type = "string")), Settings = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "list")), StatelessRulesAndCustomActions = structure(list(StatelessRules = structure(list(structure(list(RuleDefinition = structure(list(MatchAttributes = structure(list(Sources = structure(list(structure(list(AddressDefinition = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), Destinations = structure(list(structure(list(AddressDefinition = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), SourcePorts = structure(list(structure(list(FromPort = structure(logical(0), tags = list(type = "integer")), ToPort = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure"))), tags = list(type = "list")), DestinationPorts = structure(list(structure(list(FromPort = structure(logical(0), tags = list(type = "integer")), ToPort = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure"))), tags = list(type = "list")), Protocols = structure(list(structure(logical(0), tags = list(type = "integer"))), tags = list(type = "list")), TCPFlags = structure(list(structure(list(Flags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), Masks = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")), Actions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure")), Priority = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure"))), tags = list(type = "list")), CustomActions = structure(list(structure(list(ActionName = structure(logical(0), tags = list(type = "string")), ActionDefinition = structure(list(PublishMetricAction = structure(list(Dimensions = structure(list(structure(list(Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure"))), tags = list(type = "structure")), RuleGroupResponse = structure(list(RuleGroupArn = structure(logical(0), tags = list(type = "string")), RuleGroupName = structure(logical(0), tags = list(type = "string")), RuleGroupId = structure(logical(0), tags = list(type = "string")), Description = structure(logical(0), tags = list(type = "string")), Type = structure(logical(0), tags = list(type = "string")), Capacity = structure(logical(0), tags = list(type = "integer")), RuleGroupStatus = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$disassociate_subnets_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(UpdateToken = structure(logical(0), tags = list(type = "string")), FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallName = structure(logical(0), tags = list(type = "string")), SubnetIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$disassociate_subnets_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallName = structure(logical(0), tags = list(type = "string")), SubnetMappings = structure(list(structure(list(SubnetId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), UpdateToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$list_firewall_policies_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), MaxResults = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$list_firewall_policies_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), FirewallPolicies = structure(list(structure(list(Name = structure(logical(0), tags = list(type = "string")), Arn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$list_firewalls_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), VpcIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), MaxResults = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$list_firewalls_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), Firewalls = structure(list(structure(list(FirewallName = structure(logical(0), tags = list(type = "string")), FirewallArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$list_rule_groups_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), MaxResults = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$list_rule_groups_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), RuleGroups = structure(list(structure(list(Name = structure(logical(0), tags = list(type = "string")), Arn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$list_tags_for_resource_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), MaxResults = structure(logical(0), tags = list(type = "integer")), ResourceArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$list_tags_for_resource_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$put_resource_policy_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string")), Policy = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$put_resource_policy_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$tag_resource_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$tag_resource_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$untag_resource_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string")), TagKeys = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$untag_resource_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$update_firewall_delete_protection_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(UpdateToken = structure(logical(0), tags = list(type = "string")), FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallName = structure(logical(0), tags = list(type = "string")), DeleteProtection = structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$update_firewall_delete_protection_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallName = structure(logical(0), tags = list(type = "string")), DeleteProtection = structure(logical(0), tags = list(type = "boolean")), UpdateToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$update_firewall_description_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(UpdateToken = structure(logical(0), tags = list(type = "string")), FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallName = structure(logical(0), tags = list(type = "string")), Description = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$update_firewall_description_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallName = structure(logical(0), tags = list(type = "string")), Description = structure(logical(0), tags = list(type = "string")), UpdateToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$update_firewall_policy_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(UpdateToken = structure(logical(0), tags = list(type = "string")), FirewallPolicyArn = structure(logical(0), tags = list(type = "string")), FirewallPolicyName = structure(logical(0), tags = list(type = "string")), FirewallPolicy = structure(list(StatelessRuleGroupReferences = structure(list(structure(list(ResourceArn = structure(logical(0), tags = list(type = "string")), Priority = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure"))), tags = list(type = "list")), StatelessDefaultActions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), StatelessFragmentDefaultActions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), StatelessCustomActions = structure(list(structure(list(ActionName = structure(logical(0), tags = list(type = "string")), ActionDefinition = structure(list(PublishMetricAction = structure(list(Dimensions = structure(list(structure(list(Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure"))), tags = list(type = "structure"))), tags = list(type = "list")), StatefulRuleGroupReferences = structure(list(structure(list(ResourceArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")), Description = structure(logical(0), tags = list(type = "string")), DryRun = structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$update_firewall_policy_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(UpdateToken = structure(logical(0), tags = list(type = "string")), FirewallPolicyResponse = structure(list(FirewallPolicyName = structure(logical(0), tags = list(type = "string")), FirewallPolicyArn = structure(logical(0), tags = list(type = "string")), FirewallPolicyId = structure(logical(0), tags = list(type = "string")), Description = structure(logical(0), tags = list(type = "string")), FirewallPolicyStatus = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$update_firewall_policy_change_protection_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(UpdateToken = structure(logical(0), tags = list(type = "string")), FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallName = structure(logical(0), tags = list(type = "string")), FirewallPolicyChangeProtection = structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$update_firewall_policy_change_protection_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(UpdateToken = structure(logical(0), tags = list(type = "string")), FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallName = structure(logical(0), tags = list(type = "string")), FirewallPolicyChangeProtection = structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$update_logging_configuration_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallName = structure(logical(0), tags = list(type = "string")), LoggingConfiguration = structure(list(LogDestinationConfigs = structure(list(structure(list(LogType = structure(logical(0), tags = list(type = "string")), LogDestinationType = structure(logical(0), tags = list(type = "string")), LogDestination = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$update_logging_configuration_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallName = structure(logical(0), tags = list(type = "string")), LoggingConfiguration = structure(list(LogDestinationConfigs = structure(list(structure(list(LogType = structure(logical(0), tags = list(type = "string")), LogDestinationType = structure(logical(0), tags = list(type = "string")), LogDestination = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$update_rule_group_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(UpdateToken = structure(logical(0), tags = list(type = "string")), RuleGroupArn = structure(logical(0), tags = list(type = "string")), RuleGroupName = structure(logical(0), tags = list(type = "string")), RuleGroup = structure(list(RuleVariables = structure(list(IPSets = structure(list(structure(list(Definition = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "map")), PortSets = structure(list(structure(list(Definition = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "map"))), tags = list(type = "structure")), RulesSource = structure(list(RulesString = structure(logical(0), tags = list(type = "string")), RulesSourceList = structure(list(Targets = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), TargetTypes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), GeneratedRulesType = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")), StatefulRules = structure(list(structure(list(Action = structure(logical(0), tags = list(type = "string")), Header = structure(list(Protocol = structure(logical(0), tags = list(type = "string")), Source = structure(logical(0), tags = list(type = "string")), SourcePort = structure(logical(0), tags = list(type = "string")), Direction = structure(logical(0), tags = list(type = "string")), Destination = structure(logical(0), tags = list(type = "string")), DestinationPort = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")), RuleOptions = structure(list(structure(list(Keyword = structure(logical(0), tags = list(type = "string")), Settings = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "list")), StatelessRulesAndCustomActions = structure(list(StatelessRules = structure(list(structure(list(RuleDefinition = structure(list(MatchAttributes = structure(list(Sources = structure(list(structure(list(AddressDefinition = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), Destinations = structure(list(structure(list(AddressDefinition = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), SourcePorts = structure(list(structure(list(FromPort = structure(logical(0), tags = list(type = "integer")), ToPort = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure"))), tags = list(type = "list")), DestinationPorts = structure(list(structure(list(FromPort = structure(logical(0), tags = list(type = "integer")), ToPort = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure"))), tags = list(type = "list")), Protocols = structure(list(structure(logical(0), tags = list(type = "integer"))), tags = list(type = "list")), TCPFlags = structure(list(structure(list(Flags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), Masks = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")), Actions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure")), Priority = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure"))), tags = list(type = "list")), CustomActions = structure(list(structure(list(ActionName = structure(logical(0), tags = list(type = "string")), ActionDefinition = structure(list(PublishMetricAction = structure(list(Dimensions = structure(list(structure(list(Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure"))), tags = list(type = "structure")), Rules = structure(logical(0), tags = list(type = "string")), Type = structure(logical(0), tags = list(type = "string")), Description = structure(logical(0), tags = list(type = "string")), DryRun = structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$update_rule_group_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(UpdateToken = structure(logical(0), tags = list(type = "string")), RuleGroupResponse = structure(list(RuleGroupArn = structure(logical(0), tags = list(type = "string")), RuleGroupName = structure(logical(0), tags = list(type = "string")), RuleGroupId = structure(logical(0), tags = list(type = "string")), Description = structure(logical(0), tags = list(type = "string")), Type = structure(logical(0), tags = list(type = "string")), Capacity = structure(logical(0), tags = list(type = "integer")), RuleGroupStatus = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$update_subnet_change_protection_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(UpdateToken = structure(logical(0), tags = list(type = "string")), FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallName = structure(logical(0), tags = list(type = "string")), SubnetChangeProtection = structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "structure")) return(populate(args, shape)) } .networkfirewall$update_subnet_change_protection_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(UpdateToken = structure(logical(0), tags = list(type = "string")), FirewallArn = structure(logical(0), tags = list(type = "string")), FirewallName = structure(logical(0), tags = list(type = "string")), SubnetChangeProtection = structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "structure")) return(populate(args, shape)) }
check_param_list <- function(pm, type = "string", check_paths = FALSE, correct = TRUE) { . <- valid_s2tiles <- reference_path <- NULL if (is(pm, "character")) { if (file.exists(pm)) { pm <- jsonlite::fromJSON(pm) } else { print_message( type = "error", "The file ",pm," does not exist." ) } } else if (!is(pm, "list")) { print_message( type = "error", "\"",deparse(substitute(pm)),"\"", "must be a list or a path of a JSON parameter file." ) } if (length(nn(pm$list_prods)) == 0) {pm$list_prods <- NA} if (length(nn(pm$list_rgb)) == 0) {pm$list_rgb <- NA} if (length(nn(pm$list_indices)) == 0) {pm$list_indices <- NA} pm_def <- formals(sen2r::sen2r) pm_def <- sapply(pm_def[!names(pm_def) %in% c("param_list","gui","use_python","tmpdir","rmtmp")], eval) for (sel_par in names(pm_def)) { if (length(nn(pm[[sel_par]])) == 0) { print_message( type = if (type == "error") {"warning"} else {type}, paste0("Parameter \"",sel_par,"\" was not specified; ", "setting it to the default ('",pm_def[[sel_par]],"').") ) pm[[sel_par]] <- pm_def[[sel_par]] } } pm_length1 <- c( "preprocess", "online", "order_lta", "downloader", "overwrite_safe", "rm_safe", "step_atmcorr", "sen2cor_use_dem", "max_cloud_safe", "timeperiod", "extent_name", "index_source", "mask_type", "max_mask", "mask_smooth", "mask_buffer", "clip_on_extent", "extent_as_mask", "reference_path", "res_s2", "unit", "proj", "resampling", "resampling_scl", "outformat", "rgb_outformat", "index_datatype", "compression", "rgb_compression", "overwrite", "path_l1c", "path_l2a", "path_tiles", "path_merged", "path_out", "path_rgb", "path_indices", "path_subdirs", "thumbnails", "parallel", "processing_order" ) for (sel_par in pm_length1) { if (length(nn(pm[[sel_par]])) > 1) { print_message( type = type, paste0("Parameter \"",sel_par,"\" must be of length 1; ", "only the first element ('",pm[[sel_par]][1],"') is used.") ) pm[[sel_par]] <- pm[[sel_par]][1] } } pm_logical <- c( "preprocess", "online", "overwrite_safe", "clip_on_extent", "extent_as_mask", "path_subdirs", "thumbnails", "overwrite" ) for (sel_par in pm_logical) { if (any(!is(pm[[sel_par]], "logical"), !pm[[sel_par]] %in% c(TRUE,FALSE))) { print_message( type = type, paste0("Parameter \"",sel_par,"\" must be TRUE or FALSE; ", "setting it to the default (",pm_def[[sel_par]],").") ) pm[[sel_par]] <- pm_def[[sel_par]] } } if (all(!pm$sel_sensor %in% c("s2a", "s2b"))) { print_message( type = type, "Parameter \"sel_sensor\" must be 's2a', 's2b' or both (setting to the default)." ) pm$sel_sensor <- pm_def$sel_sensor } if (all(!pm$server %in% c("scihub", "gcloud"))) { print_message( type = type, "Parameter \"server\" must be 'scihub', 'gcloud' or both (setting to the default)." ) pm$server <- pm_def$server } if (!pm$downloader %in% c("builtin", "aria2")) { print_message( type = type, "Parameter \"downloader\" must be 'builtin' or 'aria2' (setting to the default)." ) pm$downloader <- pm_def$downloader } if (pm$rm_safe == TRUE) { pm$rm_safe <- "yes" } else if (pm$rm_safe == FALSE) { pm$rm_safe <- "no" } else if (!pm$rm_safe %in% c("yes", "all", "no", "l1c")) { print_message( type = type, "Parameter \"rm_safe\" must be one among 'yes' (or 'all'), ", "'no' and 'l1c' (setting to the default)." ) pm$rm_safe <- pm_def$rm_safe } if (!is(pm$max_cloud_safe, "numeric")) { if (is.na(suppressWarnings(as.numeric(as.character(pm$max_cloud_safe))))) { print_message( type = type, "Parameter \"max_cloud_safe\" must be numeric (setting it to the default)." ) pm$max_cloud_safe <- pm_def$max_cloud_safe } else { pm$max_cloud_safe <- as.numeric(as.character(pm$max_cloud_safe)) } } if (pm$max_cloud_safe < 0) { print_message( type = if (type == "error") {"warning"} else {type}, "Minimum allowed cloud cover value is 0; ", "setting parameter \"max_cloud_safe\" to 0." ) pm$max_cloud_safe <- 0 } else if (pm$max_cloud_safe > 100) { print_message( type = if (type == "error") {"warning"} else {type}, "Maximum allowed cloud cover value is 100; ", "setting parameter \"max_cloud_safe\" to 100." ) pm$max_cloud_safe <- 0 } if (!anyNA(pm$timewindow)) { if (length(pm$timewindow)==1) { if (is(pm$timewindow, "numeric") | is(pm$timewindow, "difftime")) { pm$timewindow <- c(Sys.Date() - pm$timewindow, Sys.Date()) } else { pm$timewindow <- rep(pm$timewindow, 2) } } else if (length(pm$timewindow)>2) { print_message( type = type, "Parameter 'timewindow' must be of length 1 or 2." ) } if (is(pm$timewindow, "character")) { tryCatch(pm$timewindow <- as.Date(pm$timewindow), error = print) } else if (is(pm$timewindow, "POSIXt")) { pm$timewindow <- as.Date(pm$timewindow) } if (!is(pm$timewindow, "Date")) { print_message( type = type, "Parameter 'timewindow' must be a Date object." ) } } else if (pm$online == TRUE) { pm$timewindow <- c(Sys.Date() - 90, Sys.Date()) } if (!pm$timeperiod %in% c("full", "seasonal")) { print_message( type = type, "Parameter \"timeperiod\" must be one among 'full' and 'seasonal' (setting to the default)." ) pm$timeperiod <- pm_def$timeperiod } if (inherits(pm$extent, "character") | inherits(pm$extent, "geojson")) { tryCatch( pm$extent <- st_read(pm$extent, quiet=TRUE), error = function(e) { print_message( type = type, "Extent can not be read from the specified file or string." ) } ) } else if (inherits(pm$extent, "Spatial")) { pm$extent <- st_as_sf(pm$extent) } if (inherits(pm$extent, c("sfc", "sf"))) { if (any(!st_is_valid(pm$extent))) { pm$extent <- st_make_valid(pm$extent) } } pm$s2tiles_selected <- toupper(pm$s2tiles_selected) invalid_s2tiles <- pm$s2tiles_selected[ !is.na(pm$s2tiles_selected) & !grepl("^[0-9]{2}[A-Z]{3}$", pm$s2tiles_selected) ] if (length(nn(invalid_s2tiles)) > 0) { print_message( type = type, "Values '", paste(invalid_s2tiles, collapse = "', '"), "' are not valid tiles ID and will be removed." ) valid_s2orbits <- pm$s2tiles_selected[!pm$s2tiles_selected %in% invalid_s2orbits] pm$s2tiles_selected <- if (length(nn(valid_s2tiles)) == 0) {NA} else {valid_s2tiles} } if (all( pm$online, all(is.na(pm$extent)) || length(nn(pm$extent))==0, all(is.na(pm$s2tiles_selected)) || length(nn(pm$s2tiles_selected))==0 )) { print_message( type = type, "In online mode, at least one parameter among 'extent' and ", "'s2tiles_selected' must be provided." ) } if (is(pm$s2orbits_selected, "numeric")) { pm$s2orbits_selected <- str_pad2(pm$s2orbits_selected, 3, "left", "0") } invalid_s2orbits <- pm$s2orbits_selected[ !is.na(pm$s2orbits_selected) & (is.na(suppressWarnings(as.numeric(pm$s2orbits_selected))) | as.numeric(pm$s2orbits_selected) < 0 | as.numeric(pm$s2orbits_selected) > 143) ] if (length(nn(invalid_s2orbits)) > 0) { print_message( type = type, "Values '", paste(invalid_s2orbits, collapse = "', '"), "' are not valid orbit ID and will be removed." ) valid_s2orbits <- pm$s2orbits_selected[!pm$s2orbits_selected %in% invalid_s2orbits] pm$s2orbits_selected <- if (length(nn(valid_s2orbits)) == 0) {NA} else {valid_s2orbits} } invalid_prods <- pm$list_prods[ !is.na(pm$list_prods) & !pm$list_prods %in% c("BOA","TOA","SCL","TCI","WVP","AOT","CLD","SNW") ] if (length(nn(invalid_prods)) > 0) { print_message( type = type, "Values '", paste(invalid_prods, collapse = "', '"), "' are not valid products and will be removed." ) } pm$list_prods <- pm$list_prods[!is.na(pm$list_prods) & !pm$list_prods %in% invalid_prods] if (length(nn(pm$list_prods)) == 0) {pm$list_prods <- NA} invalid_indices <- pm$list_indices[!is.na(pm$list_indices) & !pm$list_indices %in% list_indices(all=TRUE)$name] if (length(nn(invalid_indices)) > 0) { print_message( type = type, "Values '", paste(invalid_indices, collapse = "', '"), "' are not valid index names and will be removed." ) } pm$list_indices <- pm$list_indices[!is.na(pm$list_indices) & !pm$list_indices %in% invalid_indices] if (length(nn(pm$list_indices)) == 0) {pm$list_indices <- NA} invalid_rgb <- pm$list_rgb[!is.na(pm$list_rgb) & !grepl("^RGB[0-9a-f]{3}[BT]$", pm$list_rgb)] if (length(nn(invalid_rgb)) > 0) { print_message( type = type, "Values '", paste(invalid_rgb, collapse = "', '"), "' are not valid RGB names and will be removed." ) } pm$list_rgb <- pm$list_rgb[!is.na(pm$list_rgb) & !pm$list_rgb %in% invalid_rgb] if (length(nn(pm$list_rgb))>0) { rgb_bands <- lapply( strsplit(gsub("^RGB([0-9a-f]{3})([BT])$","\\1",pm$list_rgb),""), function(x) {strtoi(paste0("0x",x))} ) rgb_sources <- gsub("^RGB([0-9a-f]{3})([BT])$","\\2OA",pm$list_rgb) rgb_list <- foreach(i = seq_along(pm$list_rgb), .combine=c) %do% { if (any( rgb_bands[[i]]<1 | rgb_bands[[i]]>12 | rgb_bands[[i]]==10 & rgb_sources[i]=="BOA" )) { print_message( type = type, "RGB ",pm$list_rgb[i]," can not be computed (bands out of range)." ) character(0) } else { pm$list_rgb[i] } } pm$list_rgb <- rgb_list } else {pm$list_rgb <- NA} if (all(is.array(pm$rgb_ranges), length(dim(pm$rgb_ranges)) > 2)) { pm$rgb_ranges <- split(pm$rgb_ranges, nrow(pm$rgb_ranges)) } if (is.matrix(pm$rgb_ranges)) { pm$rgb_ranges <- list(pm$rgb_ranges) } if (all(is.na(pm$list_rgb), length(nn(pm$rgb_ranges))==0)) { pm$rgb_ranges <- NA } if (!all(is.na(pm$rgb_ranges)) & length(pm$rgb_ranges) != length(pm$list_rgb)) { print_message( type = type, "\"rgb_ranges\" and \"list_rgb\" must be of the same length." ) pm$rgb_ranges <- pm$list_rgb <- NA } if (!pm$index_source %in% c("BOA", "TOA")) { print_message( type = type, "Parameter \"index_source\" must be one among 'BOA' and 'TOA' (setting to the default)." ) pm$index_source <- pm_def$index_source } if (!pm$mask_type %in% c(NA, "nodata", "cloud_high_proba", "cloud_medium_proba", "cloud_low_proba", "cloud_and_shadow", "clear_sky", "land") & !grepl("^scl_[\\_0-9]+$", pm$mask_type) ) { print_message( type = type, "Parameter \"mask_type\" is not accepted (setting to the default)." ) pm$mask_type <- pm_def$mask_type } if ( !is.na(pm$mask_type) & all(is.na(nn(pm$list_indices))) & all(is.na(nn(pm$list_prods[pm$list_prods!="SCL"]))) ) { pm$mask_type <- NA pm$max_mask <- 100 } if (!is(pm$max_mask, "numeric")) { if (is.na(suppressWarnings(as.numeric(as.character(pm$max_mask))))) { print_message( type = type, "Parameter \"max_mask\" must be numeric (setting it to the default)." ) pm$max_mask <- pm_def$max_mask } else { pm$max_mask <- as.numeric(as.character(pm$max_mask)) } } if (pm$max_mask < 0) { print_message( type = if (type == "error") {"warning"} else {type}, "Minimum allowed cloud cover value is 0; ", "setting parameter \"max_mask\" to 0." ) pm$max_mask <- 0 } else if (pm$max_mask > 100) { print_message( type = if (type == "error") {"warning"} else {type}, "Maximum allowed cloud cover value is 100; ", "setting parameter \"max_mask\" to 100." ) pm$max_mask <- 0 } if (all(pm$max_mask < 100, is.na(pm$mask_type))) { print_message( type = if (type == "error") {"warning"} else {type}, "\"max_mask\" was set to ",pm$max_mask,", but no masks were defined: ", "set argument \"mask_type\" properly in order to use a cloud mask." ) } if (!is(pm$mask_smooth, "numeric")) { if (is.na(suppressWarnings(as.numeric(as.character(pm$mask_smooth))))) { print_message( type = type, "Parameter \"mask_smooth\" must be numeric (setting it to the default)." ) pm$mask_smooth <- pm_def$mask_smooth } else { pm$mask_smooth <- as.numeric(as.character(pm$mask_smooth)) } } if (pm$mask_smooth < 0) { print_message( type = type, "Parameter \"mask_smooth\" must be positive (setting it to the default)." ) pm$mask_smooth <- pm_def$mask_smooth } if (!is(pm$mask_buffer, "numeric")) { if (is.na(suppressWarnings(as.numeric(as.character(pm$mask_buffer))))) { print_message( type = type, "Parameter \"mask_buffer\" must be numeric (setting it to the default)." ) pm$mask_buffer <- pm_def$mask_buffer } else { pm$mask_buffer <- as.numeric(as.character(pm$mask_buffer)) } } if (is.na(pm$extent_name) || length(nn(pm$extent_name))==0 || pm$extent_name=="") { print_message( type = type, "The extent name (parameter \"extent_name\" ) can not be empty." ) } if (grepl("[ \\.\\_]", pm$extent_name)) { print_message( type = type, "The extent name (parameter \"extent_name\" ) can not contain ", "spaces, points nor underscores." ) } if (grepl("^[0-9]{2}[A-Z]{3}$", pm$extent_name)) { print_message( type = type, "The extent name (parameter \"extent_name\" ) can not cannot be ", "a five-length string with the same structure of a tile ID", "(two numeric and three uppercase character values)." ) } if (all(!is.na(pm$reference_path), pm$reference_path != "")) { if(!file.exists(pm$reference_path)) { print_message( type = type, "File \"",pm$reference_path,"\" does not exist ", "(replacing parameter \"",reference_path,"\" with default value)." ) pm$reference_path <- pm_def$reference_path } } if (all(!is.na(pm$res), !is(pm$res, "numeric"))) { if (anyNA(suppressWarnings(as.numeric(as.character(pm$res))))) { print_message( type = type, "Parameter \"res\" must be numeric (setting it to the default)." ) pm$res <- pm_def$res } else { pm$res <- as.numeric(as.character(pm$res)) } } if (!anyNA(pm$res) & any(pm$res <= 0)) { print_message( type = type, "Output custom resolution (parameter \"res\" ) must be positive." ) } if (length(pm$res) == 1) { pm$res <- rep(pm$res, 2) } if ((!anyNA(pm$res) & !is.null(pm$res)) & (!anyNA(pm$res_s2) & !is.null(pm$res_s2))) { print_message( type = if (type == "error") {"warning"} else {type}, "Both native and custom resolution were provided; ", "only custom one (\"res\") will be used." ) pm$res_s2 <- NA } if (!anyNA(pm$res_s2) & any(!pm$res_s2 %in% c("10m", "20m", "60m"))) { print_message( type = type, "Output native resolution (parameter \"res_s2\" ) is invalid ", "(accepted values are '10m', '20m' and '60m'); setting it to default." ) if (!any(!pm$res_s2 %in% c("10m","20m","60m"))) { pm$res_s2 <- pm_def$res_s2 } } if (any(!pm$res_s2 %in% c("10m","20m","60m"))) { pm$res_s2 <- if (as.integer(mean(pm$res)) >= 60) {"60m"} else if (as.integer(mean(pm$res)) >= 20) {"20m"} else {"10m"} } if (pm$unit != "Meter") { print_message( type = if (type == "error") {"warning"} else {type}, "Only \"unit\" == 'meter' is accepted." ) pm$unit <- "Meter" } if (inherits(try(st_crs2(pm$proj), silent = TRUE), "try-error")) { print_message( type = type, "Output projection (parameter \"proj\" ) is not recognised; ", "setting it to default." ) pm$proj <- pm_def$proj } if (!pm$resampling %in% c("near", "mode", "bilinear", "cubic", "cubicspline", "lanczos", "average", "mode")) { print_message( type = type, "Parameter \"resampling\" is not accepted (setting to the default)." ) pm$resampling <- pm_def$resampling } if (!pm$resampling_scl %in% c("near", "mode")) { print_message( type = type, "Parameter \"resampling_scl\" is not accepted (setting to the default)." ) pm$resampling_scl <- pm_def$resampling_scl } gdal_formats <- fromJSON( system.file("extdata/settings/gdal_formats.json",package="sen2r") )$drivers if (!pm$outformat %in% c(gdal_formats$name, "BigTIFF")) { print_message( type = type, "Parameter \"outformat\" is not accepted (setting to the default)." ) pm$outformat <- pm_def$outformat } if (anyNA(pm$rgb_outformat)) {pm$rgb_outformat <- pm$outformat} if (!pm$rgb_outformat %in% gdal_formats$name) { print_message( type = type, "Parameter \"rgb_outformat\" is not accepted (setting to the default)." ) pm$rgb_outformat <- pm_def$rgb_outformat } if (!pm$index_datatype %in% c("Byte", "UInt16", "Int16", "UInt32", "Int32", "Float32", "Float64")) { print_message( type = type, "Parameter \"index_datatype\" is not accepted (setting to the default)." ) pm$index_datatype <- pm_def$index_datatype } if (!as.character(pm$compression) %in% c(NA, "NONE", "LZW", "DEFLATE", "PACKBITS", "JPEG", 1:100)) { print_message( type = type, "Parameter \"compression\" is not accepted (setting to the default)." ) pm$compression <- pm_def$compression } if (anyNA(pm$rgb_compression)) {pm$rgb_compression <- pm$compression} if (!as.character(pm$rgb_compression) %in% c(NA, "NONE", "LZW", "DEFLATE", "PACKBITS", "JPEG", 1:100)) { print_message( type = type, "Parameter \"rgb_compression\" is not accepted (setting to the default)." ) pm$rgb_compression <- pm_def$rgb_compression } l1c_prods <- c("TOA") l2a_prods <- c("BOA","SCL","TCI") if (pm$preprocess==TRUE) { list_prods <- if (!is.na(pm$mask_type)) { unique(c(pm$list_prods, "SCL")) } else { pm$list_prods } if (any(!is.na(pm$list_rgb))) { list_prods <- unique(c( list_prods, paste0(unique(substr(pm$list_rgb,7,7)),"OA") )) } if (any(!is.na(pm$list_indices))) { list_prods <- unique(c(list_prods, pm$index_source)) } list_prods <- list_prods[!is.na(list_prods)] pm$s2_levels <- if (length(list_prods) > 0) { c( if (any(list_prods %in% l1c_prods)) {"l1c"}, if (any(list_prods %in% l2a_prods)) {"l2a"} ) } else { pm_def$s2_levels } } if (all(!pm$s2_levels %in% c("l1c", "l2a"))) { print_message( type = type, "Parameter \"s2_levels\" must be 'l1c', 'l2a' or both (setting to the default)." ) pm$s2_levels <- pm_def$s2_levels } if (pm$step_atmcorr == "no") { print_message( type = if (type == "error") {"warning"} else {type}, "Value \"no\" for parameter \"step_atmcorr\" is deprecated ", "(\"l2a\" will be used)." ) pm$step_atmcorr <- "l2a" } else if (!pm$step_atmcorr %in% c("auto", "scihub", "l2a")) { print_message( type = type, "Parameter \"step_atmcorr\" must be one among 'auto', 'scihub' and 'l2a' ", "(setting to the default)." ) pm$step_atmcorr <- pm_def$step_atmcorr } if (!is(pm$sen2cor_use_dem, "logical")) { print_message( type = type, paste0("Parameter sen2cor_use_dem must be TRUE or FALSE; ", "setting it to the default (NA).") ) pm$sen2cor_use_dem <- NA } if (all(!is.na(pm$path_l1c), pm$path_l1c != "")) { if(!dir.exists(pm$path_l1c)) { if(!dir.exists(dirname(pm$path_l1c))) { print_message( type = type, "Directory \"",dirname(pm$path_l1c),"\" does not exist ", "(it must be created before continuing)." ) } } } else if (all("l1c" %in% pm$s2_levels, check_paths)) { print_message( type = type, "Parameter \"path_l1c\" was not specified; ", "please provide the path of an existing directory." ) } if (all(!is.na(pm$path_l2a), pm$path_l2a != "")) { if(!dir.exists(pm$path_l2a)) { if(!dir.exists(dirname(pm$path_l2a))) { print_message( type = type, "Directory \"",dirname(pm$path_l2a),"\" does not exist ", "(it must be created before continuing)." ) } } } else if (all("l2a" %in% pm$s2_levels, check_paths)) { print_message( type = type, "Parameter \"path_l2a\" was not specified; ", "please provide the path of an existing directory." ) } if (all(!is.na(pm$path_tiles), pm$path_tiles != "", pm$preprocess == TRUE)) { if(!dir.exists(pm$path_tiles)) { if(!dir.exists(dirname(pm$path_tiles))) { print_message( type = type, "Directory \"",dirname(pm$path_tiles),"\" does not exist ", "(it must be created before continuing)." ) } } } if (all(!is.na(pm$path_merged), pm$path_merged != "", pm$preprocess == TRUE)) { if(!dir.exists(pm$path_merged)) { if(!dir.exists(dirname(pm$path_merged))) { print_message( type = type, "Directory \"",dirname(pm$path_merged),"\" does not exist ", "(it must be created before continuing)." ) } } } if (pm$preprocess == TRUE) { if (sum(!is.na(pm$list_rgb))==0) { pm$path_rgb <- NA } else if (is.na(pm$path_rgb) | pm$path_rgb=="") { pm$path_rgb <- pm$path_out } if (all(!is.na(pm$path_rgb), pm$path_rgb != "")) { if(!dir.exists(pm$path_rgb)) { if(!dir.exists(dirname(pm$path_rgb))) { print_message( type = type, "Directory \"",dirname(pm$path_rgb),"\" does not exist ", "(it must be created before continuing)." ) } } } else if (all(length(nn(pm$list_rgb[!is.na(pm$list_rgb)])) > 0, check_paths)) { print_message( type = type, "Neither parameter \"path_rgb\" nor \"path_out\" were specified; ", "please provide the path of an existing directory for at least one of the two." ) } } if (pm$preprocess == TRUE) { if (sum(!is.na(pm$list_indices))==0) { pm$path_indices <- NA } else if (is.na(pm$path_indices) | pm$path_indices=="") { pm$path_indices <- pm$path_out } if (all(!is.na(pm$path_indices), pm$path_indices != "")) { if(!dir.exists(pm$path_indices)) { if(!dir.exists(dirname(pm$path_indices))) { print_message( type = type, "Directory \"",dirname(pm$path_indices),"\" does not exist ", "(it must be created before continuing)." ) } } } else if (all(length(nn(pm$list_indices[!is.na(pm$list_indices)])) > 0, check_paths)) { print_message( type = type, "Neither parameter \"path_indices\" nor \"path_out\" were specified; ", "please provide the path of an existing directory for at least one of the two." ) } } if (pm$preprocess == TRUE) { if (sum(!is.na(nn(pm$list_prods)))==0) { pm$path_out <- NA } if (all(!is.na(pm$path_out), pm$path_out != "")) { if(!dir.exists(pm$path_out)) { if(!dir.exists(dirname(pm$path_out))) { print_message( type = type, "Directory \"",dirname(pm$path_out),"\" does not exist ", "(it must be created before continuing)." ) } } } else if (all(length(nn(pm$list_prods[!is.na(pm$list_prods)])) > 0, check_paths)) { print_message( type = type, "Parameter \"path_out\" was not specified; ", "please provide the path of an existing directory." ) } } if (length(pm$log) > 2) { print_message( type = type, paste0("Parameter \"log\" must be of length 1 or 2; ", "only the first two elements are used.") ) pm$log <- pm$log[1:2] } for (i in 1:2) { if (all(!is.na(pm$log[i]), pm$log[i] != "")) { if(!dir.exists(dirname(pm$log[i]))) { print_message( type = type, "Directory \"",dirname(pm$log[i]),"\" does not exist ", "(it must be created before continuing)." ) } } } if (all( !is(pm$parallel, "logical"), !pm$parallel %in% c(TRUE,FALSE), !is(pm$parallel, "numeric"), pm$parallel > 0 )) { print_message( type = type, "Parameter \"",sel_par,"\" must be TRUE or FALSE, ", "or a positive integer value; ", "setting it to the default (",pm_def$parallel,")." ) pm$parallel <- pm_def$parallel } if (all( is(pm$parallel, "numeric"), !is(pm$parallel, "integer") )) { pm$parallel <- floor(pm$parallel) } if (length(nn(pm$processing_order) > 0)) { if (pm$preprocess == FALSE) { pm$processing_order <- "by_step" } } if (!as.character(pm$processing_order) %in% c("by_step", "mixed", "by_date", "by_groups", 1:4)) { print_message( type = type, "Parameter \"processing_order\" must be one among 'by_step', 'mixed' and ", "'by_date', 'by_groups' (setting to the default)." ) pm$processing_order <- pm_def$processing_order } if (correct==TRUE) { return(pm) } else { return(invisible(NULL)) } }
categorical_pal <- function(n) { stopifnot(n > 0) x <- c(" " if (n > length(x)) warning("Cannot make ", n, " categorical colors") n <- min(n, length(x)) x[seq_len(n)] } sequential_pal <- function(n) { stopifnot(n >= 0) x <- list( " c(" c(" c(" c(" c(" c(" " c(" " c(" " ) if (n > length(x)) warning("Cannot make ", n, " sequential colors") n <- min(n, length(x)) if (n == 0) character() else x[[n]] } diverging_pal <- function(n) { stopifnot(n > 0) x <- list( " c(" c(" c(" c(" c(" c(" " c(" " c(" " c(" " c(" " ) if (n > length(x)) warning("Cannot make ", n, " divergent colors") n <- min(n, length(x)) if (n == 0) character() else x[[n]] } r_pal <- function(n) { x <- palette() if (n > length(x)) warning("Cannot make ", n, " divergent colors") n <- min(n, length(x)) if (n == 0) character() else x[[n]] }
insertPmet <- function(vals, nc2, var2, dim2, units2 = NA, conv = NULL, missval = -6999, verbose = FALSE, ...) { vals[vals == -6999 | vals == -9999] <- NA if (!is.null(conv)) { vals <- lapply(vals, conv) } var <- ncdf4::ncvar_def(name = var2, units = units2, dim = dim2, missval = missval, verbose = verbose) nc2 <- ncdf4::ncvar_add(nc = nc2, v = var, verbose = verbose) ncdf4::ncvar_put(nc = nc2, varid = var2, vals = vals) } met2CF.PalEONregional <- function(in.path, in.prefix, outfolder, start_date, end_date, overwrite = FALSE, verbose = FALSE, ...) { start_year <- lubridate::year(start_date) end_year <- lubridate::year(end_date) if (!file.exists(outfolder)) { dir.create(outfolder) } by.folder <- list.dirs(in.path, recursive = FALSE, full.names = FALSE) if (length(by.folder) == 0) { PEcAn.logger::logger.severe("met2CF.PalEON, could not detect input folders", in.path) } rows <- end_year - start_year + 1 results <- data.frame(file = character(rows), host = character(rows), mimetype = character(rows), formatname = character(rows), startdate = character(rows), enddate = character(rows), dbfile.name = in.prefix, stringsAsFactors = FALSE) for (year in start_year:end_year) { my.prefix <- in.prefix if (nchar(my.prefix) > 0) { my.prefix <- paste0(my.prefix, ".") } new.file <- file.path(outfolder, sprintf("%s%04d.nc", my.prefix, year)) row <- year - start_year + 1 results$file[row] <- new.file results$host[row] <- PEcAn.remote::fqdn() results$startdate[row] <- paste0(year, "-01-01 00:00:00") results$enddate[row] <- paste0(year, "-12-31 23:59:59") results$mimetype[row] <- "application/x-netcdf" results$formatname[row] <- "CF" if (file.exists(new.file) && !overwrite) { PEcAn.logger::logger.debug("File '", new.file, "' already exists, skipping to next file.") next } met <- list() for (i in seq_along(by.folder)) { met[[i]] <- NA } names(met) <- by.folder met[["time"]] <- NA for (v in by.folder) { fnames <- dir(file.path(in.path, v), full.names = TRUE) for (m in 1:12) { stub <- paste0(year, "_", formatC(m, width = 2, format = "d", flag = "0")) sel <- grep(stub, fnames) if (length(sel) == 0) { PEcAn.logger::logger.severe("missing file", v, stub) } old.file <- fnames[sel] nc1 <- ncdf4::nc_open(old.file, write = FALSE) if (length(met[[v]]) <= 1) { met[[v]] <- aperm(ncdf4::ncvar_get(nc = nc1, varid = v),c(2,1,3)) } else { tmp <- aperm(ncdf4::ncvar_get(nc = nc1, varid = v),c(2,1,3)) met[[v]] <- abind::abind(met[[v]], tmp) } if (v == by.folder[1]) { if (length(met[["time"]]) <= 1) { met[["time"]] <- nc1$dim[["time"]]$vals } else { tmp <- nc1$dim[["time"]]$vals met[["time"]] <- abind::abind(met[["time"]], tmp) } } ncdf4::nc_close(nc1) } } nc1 <- ncdf4::nc_open(old.file) tdim <- nc1$dim[["time"]] met[["time"]] <- udunits2::ud.convert(met[["time"]],"days","seconds") tdim$units <- paste0("seconds since ",year,"-01-01 00:00:00") tdim$vals <- met[["time"]] tdim$len <- length(tdim$vals) lat <- ncdf4::ncdim_def(name = "latitude", units = "degrees", vals = nc1$dim[["lat"]]$vals, create_dimvar = TRUE) lon <- ncdf4::ncdim_def(name = "longitude", units = "degrees", vals = nc1$dim[["lon"]]$vals, create_dimvar = TRUE) time <- ncdf4::ncdim_def(name = "time", units = tdim$units, vals = tdim$vals, create_dimvar = TRUE, unlim = TRUE) dim <- list(lat, lon, time) cp.global.atts <- ncdf4::ncatt_get(nc = nc1, varid = 0) ncdf4::nc_close(nc1) print(year) var <- ncdf4::ncvar_def(name = "air_temperature", units = "K", dim = dim, missval = as.numeric(-9999)) nc2 <- ncdf4::nc_create(filename = new.file, vars = var, verbose = verbose) ncdf4::ncvar_put(nc = nc2, varid = "air_temperature", vals = met[["tair"]]) insertPmet(met[["psurf"]], nc2 = nc2, var2 = "air_pressure", units2 = "Pa", dim2 = dim, verbose = verbose) insertPmet(met[["qair"]], nc2 = nc2, var2 = "specific_humidity", units2 = "kg/kg", dim2 = dim, verbose = verbose) insertPmet(met[["swdown"]], nc2 = nc2, var2 = "surface_downwelling_shortwave_flux_in_air", units2 = "W m-2", dim2 = dim, verbose = verbose) insertPmet(met[["lwdown"]], nc2 = nc2, var2 = "surface_downwelling_longwave_flux_in_air", units2 = "W m-2", dim2 = dim, verbose = verbose) insertPmet(met[["wind"]], nc2 = nc2, var2 = "wind_speed", units2 = "m s-1", dim2 = dim, verbose = verbose) insertPmet(met[["precipf"]], nc2 = nc2, var2 = "precipitation_flux", units2 = "kg/m^2/s", dim2 = dim, verbose = verbose) for (j in seq_along(cp.global.atts)) { ncdf4::ncatt_put(nc = nc2, varid = 0, attname = names(cp.global.atts)[j], attval = cp.global.atts[[j]]) } ncdf4::nc_close(nc2) } return(invisible(results)) } met2CF.PalEON <- function(in.path, in.prefix, outfolder, start_date, end_date, lat, lon, overwrite = FALSE, verbose = FALSE, ...) { start_year <- lubridate::year(start_date) end_year <- lubridate::year(end_date) if (!file.exists(outfolder)) { dir.create(outfolder) } by.folder <- list.dirs(in.path, recursive = FALSE, full.names = FALSE) if (length(by.folder) == 0) { PEcAn.logger::logger.severe("met2CF.PalEON, could not detect input folders", in.path) } rows <- end_year - start_year + 1 results <- data.frame(file = character(rows), host = character(rows), mimetype = character(rows), formatname = character(rows), startdate = character(rows), enddate = character(rows), dbfile.name = in.prefix, stringsAsFactors = FALSE) for (year in start_year:end_year) { my.prefix <- in.prefix if (nchar(my.prefix) > 0) { my.prefix <- paste0(my.prefix, ".") } new.file <- file.path(outfolder, sprintf("%s%04d.nc", my.prefix, year)) row <- year - start_year + 1 results$file[row] <- new.file results$host[row] <- PEcAn.remote::fqdn() results$startdate[row] <- paste0(year, "-01-01 00:00:00") results$enddate[row] <- paste0(year, "-12-31 23:59:59") results$mimetype[row] <- "application/x-netcdf" results$formatname[row] <- "CF" if (file.exists(new.file) && !overwrite) { PEcAn.logger::logger.debug("File '", new.file, "' already exists, skipping to next file.") next } met <- list() for (i in seq_along(by.folder)) { met[[i]] <- NA } names(met) <- by.folder met[["time"]] <- NA if(FALSE){ for (v in by.folder) { fnames <- dir(file.path(in.path, v), full.names = TRUE) for (m in 1:12) { stub <- paste0(formatC(m, width = 2, format = "d", flag = "0"), ".", formatC(year,width = 4,format = 'd',flag = '0')) sel <- grep(stub, fnames) if (length(sel) == 0) { PEcAn.logger::logger.severe("missing file", v, stub) } old.file <- fnames[sel] nc1 <- ncdf4::nc_open(old.file, write = FALSE) if (length(met[[v]]) <= 1) { met[[v]] <- ncdf4::ncvar_get(nc = nc1, varid = v) } else { tmp <- ncdf4::ncvar_get(nc = nc1, varid = v) met[[v]] <- abind::abind(met[[v]], tmp) } if (v == by.folder[1]) { if (length(met[["time"]]) <= 1) { met[["time"]] <- nc1$dim[["time"]]$vals } else { tmp <- nc1$dim[["time"]]$vals met[["time"]] <- abind::abind(met[["time"]], tmp) } } ncdf4::nc_close(nc1) } } } fnames <- dir(file.path(in.path, by.folder[1]), full.names = TRUE) stub <- paste0(formatC(1, width = 2, format = "d", flag = "0"), ".", formatC(year,width = 4,format = 'd',flag = '0')) sel <- grep(stub, fnames) if (length(sel) == 0) { PEcAn.logger::logger.severe("missing file", by.folder[1], stub) } old.file <- fnames[sel] var.ids <- c('air_temperature','precipitation_flux', 'surface_downwelling_shortwave_flux_in_air', 'surface_downwelling_longwave_flux_in_air', 'air_pressure','specific_humidity', 'wind_speed') for(v in var.ids){ met[[v]] <- ncdf4::ncvar_get(nc = nc1, varid = v) } nc1 <- ncdf4::nc_open(old.file) tdim <- nc1$dim[["time"]] met[["time"]] <- met[["time"]] + (850 - 1700) tdim$units <- "days since 1700-01-01 00:00:00" tdim$vals <- met[["time"]] tdim$len <- length(tdim$vals) latlon <- lat latlon[2] <- lon lat <- ncdf4::ncdim_def(name = "latitude", units = "", vals = 1:1, create_dimvar = FALSE) lon <- ncdf4::ncdim_def(name = "longitude", units = "", vals = 1:1, create_dimvar = FALSE) time <- ncdf4::ncdim_def(name = "time", units = tdim$units, vals = tdim$vals, create_dimvar = TRUE, unlim = TRUE) dim <- list(lat, lon, time) cp.global.atts <- ncdf4::ncatt_get(nc = nc1, varid = 0) ncdf4::nc_close(nc1) print(c(latlon, year)) var <- ncdf4::ncvar_def(name = "latitude", units = "degree_north", dim = (list(lat, lon, time)), missval = as.numeric(-9999)) nc2 <- ncdf4::nc_create(filename = new.file, vars = var, verbose = verbose) ncdf4::ncvar_put(nc = nc2, varid = "latitude", vals = rep(latlon[1], tdim$len)) var <- ncdf4::ncvar_def(name = "longitude", units = "degree_east", dim = (list(lat, lon, time)), missval = as.numeric(-9999)) nc2 <- ncdf4::ncvar_add(nc = nc2, v = var, verbose = verbose) ncdf4::ncvar_put(nc = nc2, varid = "longitude", vals = rep(latlon[2], tdim$len)) insertPmet(met[["air_temperature"]], nc2 = nc2, var2 = "air_temperature", units2 = "K", dim2 = dim, verbose = verbose) insertPmet(met[["air_pressure"]], nc2 = nc2, var2 = "air_pressure", units2 = "Pa", dim2 = dim, verbose = verbose) insertPmet(met[["specific_humidity"]], nc2 = nc2, var2 = "specific_humidity", units2 = "kg/kg", dim2 = dim, verbose = verbose) insertPmet(met[["surface_downwelling_shortwave_flux_in_air"]], nc2 = nc2, var2 = "surface_downwelling_shortwave_flux_in_air", units2 = "W m-2", dim2 = dim, verbose = verbose) insertPmet(met[["surface_downwelling_longwave_flux_in_air"]], nc2 = nc2, var2 = "surface_downwelling_longwave_flux_in_air", units2 = "W m-2", dim2 = dim, verbose = verbose) insertPmet(met[["wind_speed"]], nc2 = nc2, var2 = "wind_speed", units2 = "m s-1", dim2 = dim, verbose = verbose) insertPmet(met[["precipitation_flux"]], nc2 = nc2, var2 = "precipitation_flux", units2 = "kg/m^2/s", dim2 = dim, verbose = verbose) for (j in seq_along(cp.global.atts)) { ncdf4::ncatt_put(nc = nc2, varid = 0, attname = names(cp.global.atts)[j], attval = cp.global.atts[[j]]) } ncdf4::nc_close(nc2) } return(invisible(results)) } met2CF.ALMA <- function(in.path, in.prefix, outfolder, start_date, end_date, overwrite = FALSE, verbose = FALSE) { start_year <- lubridate::year(start_date) end_year <- lubridate::year(end_date) if (!file.exists(outfolder)) { dir.create(outfolder) } by.file <- dir(in.path, pattern = ".nc") if (length(by.file) == 0) { by.file <- FALSE by.folder <- list.dirs(in.path, recursive = FALSE, full.names = FALSE) if (length(by.folder) == 0) { PEcAn.logger::logger.severe("met2CF.ALMA, could not detect input file or folders", in.path) } } else { by.file <- TRUE } rows <- end_year - start_year + 1 results <- data.frame(file = character(rows), host = character(rows), mimetype = character(rows), formatname = character(rows), startdate = character(rows), enddate = character(rows), dbfile.name = in.prefix, stringsAsFactors = FALSE) for (year in start_year:end_year) { new.file <- file.path(outfolder, paste(in.prefix, year, "nc", sep = ".")) row <- year - start_year + 1 results$file[row] <- new.file results$host[row] <- PEcAn.remote::fqdn() results$startdate[row] <- paste0(year, "-01-01 00:00:00") results$enddate[row] <- paste0(year, "-12-31 23:59:59") results$mimetype[row] <- "application/x-netcdf" results$formatname[row] <- "CF" if (file.exists(new.file) && !overwrite) { PEcAn.logger::logger.debug("File '", new.file, "' already exists, skipping to next file.") next } if (by.file) { old.file <- file.path(in.path, paste(in.prefix, year, "nc", sep = ".")) nc1 <- ncdf4::nc_open(old.file, write = TRUE) tdim <- nc1$dim[["DTIME"]] ncdf4::nc_close(nc1) } else { met <- list() for (i in seq_along(by.folder)) { met[[i]] <- NA } names(met) <- by.folder met[["time"]] <- NA for (v in by.folder) { fnames <- dir(file.path(in.path, v), full.names = TRUE) for (m in 1:12) { sel <- grep(paste0(year, "_", formatC(m, width = 2, format = "d", flag = "0")), fnames) old.file <- fnames[sel] nc1 <- ncdf4::nc_open(old.file, write = FALSE) if (length(met[[v]]) <= 1) { met[[v]] <- ncdf4::ncvar_get(nc = nc1, varid = v) } else { tmp <- ncdf4::ncvar_get(nc = nc1, varid = v) met[[v]] <- abind::abind(met[[v]], tmp) } if (v == by.folder[1]) { if (length(met[["time"]]) <= 1) { met[["time"]] <- nc1$dim[["time"]]$vals } else { tmp <- nc1$dim[["time"]]$vals met[["time"]] <- abind::abind(met[["time"]], tmp) } } ncdf4::nc_close(nc1) } } } nc1 <- ncdf4::nc_open(old.file) tdim <- nc1$dim[["time"]] latlon <- nc1$dim$lat$vals latlon[2] <- nc1$dim$lon$vals lat <- ncdf4::ncdim_def(name = "latitude", units = "", vals = 1:1, create_dimvar = FALSE) lon <- ncdf4::ncdim_def(name = "longitude", units = "", vals = 1:1, create_dimvar = FALSE) time <- ncdf4::ncdim_def(name = "time", units = tdim$units, vals = met[["time"]], create_dimvar = TRUE, unlim = TRUE) dim <- list(lat, lon, time) print(latlon) var <- ncdf4::ncvar_def(name = "latitude", units = "degree_north", dim = (list(lat, lon, time)), missval = as.numeric(-9999)) nc2 <- ncdf4::nc_create(filename = new.file, vars = var, verbose = verbose) ncdf4::ncvar_put(nc = nc2, varid = "latitude", vals = rep(latlon[1], tdim$len)) var <- ncdf4::ncvar_def(name = "longitude", units = "degree_east", dim = (list(lat, lon, time)), missval = as.numeric(-9999)) nc2 <- ncdf4::ncvar_add(nc = nc2, v = var, verbose = verbose) ncdf4::ncvar_put(nc = nc2, varid = "longitude", vals = rep(latlon[2], tdim$len)) copyvals(nc1 = nc1, var1 = "TA", nc2 = nc2, var2 = "air_temperature", units2 = "K", dim2 = dim, conv = function(x) { udunits2::ud.convert(x, "degC", "K") }, verbose = verbose) copyvals(nc1 = nc1, var1 = "PRESS", nc2 = nc2, var2 = "air_pressure", units2 = "Pa", dim2 = dim, conv = function(x) { udunits2::ud.convert(x, 'kPa', 'Pa') }, verbose = verbose) copyvals(nc1 = nc1, var1 = "CO2", nc2 = nc2, var2 = "mole_fraction_of_carbon_dioxide_in_air", units2 = "mole/mole", dim2 = dim, conv = function(x) { udunits2::ud.convert(x, "mol/mol", "ppm") }, verbose = verbose) copyvals(nc1 = nc1, var1 = "TS1", nc2 = nc2, var2 = "soil_temperature", units2 = "K", dim2 = dim, conv = function(x) { udunits2::ud.convert(x, "degC", "K") }, verbose = verbose) copyvals(nc1 = nc1, var1 = "RH", nc2 = nc2, var2 = "relative_humidity", dim2 = dim, verbose = verbose) rh <- ncdf4::ncvar_get(nc = nc1, varid = "RH") rh[rh == -6999 | rh == -9999] <- NA rh <- rh/100 ta <- ncdf4::ncvar_get(nc = nc1, varid = "TA") ta[ta == -6999 | ta == -9999] <- NA ta <- udunits2::ud.convert(ta, "degC", "K") sh <- rh2qair(rh = rh, T = ta) var <- ncdf4::ncvar_def(name = "specific_humidity", units = "kg/kg", dim = dim, missval = -6999, verbose = verbose) nc2 <- ncdf4::ncvar_add(nc = nc2, v = var, verbose = verbose) ncdf4::ncvar_put(nc = nc2, varid = "specific_humidity", vals = sh) copyvals(nc1 = nc1, var1 = "VPD", nc2 = nc2, var2 = "water_vapor_saturation_deficit", units2 = "mol m-2 s-1", dim2 = dim, conv = function(x) { ifelse(x < 0, NA, x * 1000) }, verbose = verbose) copyvals(nc1 = nc1, var1 = "Rg", nc2 = nc2, var2 = "surface_downwelling_shortwave_flux_in_air", dim2 = dim, verbose = verbose) copyvals(nc1 = nc1, var1 = "Rgl", nc2 = nc2, var2 = "surface_downwelling_longwave_flux_in_air", dim2 = dim, verbose = verbose) copyvals(nc1 = nc1, var1 = "PAR", nc2 = nc2, var2 = "surface_downwelling_photosynthetic_photon_flux_in_air", units2 = "mol m-2 s-1", dim2 = dim, conv = function(x) { udunits2::ud.convert(x, "umol m-2 s-1", "mol m-2 s-1") }, verbose = verbose) copyvals(nc1 = nc1, var1 = "WD", nc2 = nc2, var2 = "wind_direction", dim2 = dim, verbose = verbose) copyvals(nc1 = nc1, var1 = "WS", nc2 = nc2, var2 = "wind_speed", dim2 = dim, verbose = verbose) t <- tdim$vals min <- 0.02083 / 30 timestep <- round(x = mean(diff(t)) / min, digits = 1) copyvals(nc1 = nc1, var1 = "PREC", nc2 = nc2, var2 = "precipitation_flux", units2 = "kg/m^2/s", dim2 = dim, conv = function(x) { x / timestep / 60 }, verbose = verbose) wd <- ncdf4::ncvar_get(nc = nc1, varid = "WD") wd[wd == -6999 | wd == -9999] <- NA ws <- ncdf4::ncvar_get(nc = nc1, varid = "WS") ws[ws == -6999 | ws == -9999] <- NA ew <- ws * cos(wd * (pi / 180)) nw <- ws * sin(wd * (pi / 180)) max <- ncdf4::ncatt_get(nc = nc1, varid = "WS", "valid_max")$value var <- ncdf4::ncvar_def(name = "eastward_wind", units = "m/s", dim = dim, missval = -6999, verbose = verbose) nc2 <- ncdf4::ncvar_add(nc = nc2, v = var, verbose = verbose) ncdf4::ncvar_put(nc = nc2, varid = "eastward_wind", vals = ew) ncdf4::ncatt_put(nc = nc2, varid = "eastward_wind", attname = "valid_min", attval = -max) ncdf4::ncatt_put(nc = nc2, varid = "eastward_wind", attname = "valid_max", attval = max) var <- ncdf4::ncvar_def(name = "northward_wind", units = "m/s", dim = dim, missval = -6999, verbose = verbose) nc2 <- ncdf4::ncvar_add(nc = nc2, v = var, verbose = verbose) ncdf4::ncvar_put(nc = nc2, varid = "northward_wind", vals = nw) ncdf4::ncatt_put(nc = nc2, varid = "northward_wind", attname = "valid_min", attval = -max) ncdf4::ncatt_put(nc = nc2, varid = "northward_wind", attname = "valid_max", attval = max) cp.global.atts <- ncdf4::ncatt_get(nc = nc1, varid = 0) for (j in seq_along(cp.global.atts)) { ncdf4::ncatt_put(nc = nc2, varid = 0, attname = names(cp.global.atts)[j], attval = cp.global.atts[[j]]) } ncdf4::nc_close(nc1) ncdf4::nc_close(nc2) } return(invisible(results)) }
LD.thin <- function(x, threshold, max.dist = 250e3, beg = 1, end = ncol(x), which.snps, dist.unit = c("bases", "indices", "cM"), extract = TRUE, keep = c("left", "right", "random")) { if(missing(which.snps)) which.snps <- rep(TRUE, end-beg+1) if(!is.logical(which.snps) | length(which.snps) != end-beg+1) stop("which.snps must be a Logical vector of length end - beg + 1") if(is.null(x@mu) | is.null(x@sigma)) stop("LD.thin needs mu and sigma to be set for LD computation (use set.stats)") which.snps <- which.snps & (x@snps$callrate > 0) & (x@snps$maf > 0) dist.unit <- match.arg(dist.unit) if(dist.unit == "bases") { pos = as.integer(x@snps$pos) } else if(dist.unit == "indices") { pos = seq_len(ncol(x)) } else { if(max.dist > 100) warning("max.dist value seems very high for dist.unit = \"cM\"") pos = as.integer( x@snps$dist * 1e4 ) max.dist = as.integer(max.dist*1e4) } if( all(x@snps$pos == x@snps$pos[1]) ) stop("Position of SNPs must be available") keep <- match.arg(keep) if(keep == "left") { w <- .Call("gg_ld_thin_left", x@bed, x@mu, x@sigma, threshold, pos, as.integer(x@snps$chr), as.integer(max.dist), as.integer(beg)-1L, as.integer(end)-1L, which.snps) } else if (keep == "right"){ w <- .Call("gg_ld_thin_right", x@bed, x@mu, x@sigma, threshold, pos, as.integer(x@snps$chr), as.integer(max.dist), as.integer(beg)-1L, as.integer(end)-1L, which.snps) } else { w <- .Call("gg_ld_thin_random", x@bed, x@mu, x@sigma, threshold, pos, as.integer(x@snps$chr), as.integer(max.dist), as.integer(beg)-1L, as.integer(end)-1L, which.snps) } if(!extract) return(w) x[ , seq(beg,end)[w] ] }
meucci.ranking <- function(R, p, order){ R = coredata(R) J = nrow( R ) N = ncol( R ) k = length( order ) Aeq = matrix(rep(1, J), ncol=J) beq = matrix(1, 1) V = R[ , order[1:(k-1)] ] - R[ , order[2:k] ] A = t( V ) b = matrix(rep(0, nrow(A)), ncol=1) p_ = EntropyProg( p , A , b , Aeq , beq )$p_ out <- meucci.moments(R, p_) return( out ) }
print.bammdata = function(x, ...) { print.phylo(as.phylo.bammdata(x)); nsamples <- length(x$eventData); cat(paste("\nPosterior samples:", nsamples,"\n\n")); cat("List elements:\n"); cat("\t",names(x)[1:10]); cat("\t",names(x)[11:length(x)]); cat('\n'); }
library(readr) library(dplyr) library(stringr) library(usethis) mig_recodes <- read_csv( "data-raw/mig-flow-recode.csv", col_types = cols( characteristic = col_character(), code = col_double(), desc = col_character(), ordered = col_logical() ) ) %>% mutate(code = as.character(code)) %>% mutate(code = str_pad(code, 2, pad = "0")) use_data(mig_recodes, overwrite = TRUE)
context("fctr.labelled") no_lab = rep(1:2,3) vec_with_lab = no_lab var_lab(vec_with_lab) = "Fruits" val_lab(vec_with_lab) = c(Apple=1,Bananas=2) expect_identical(fctr(unlab(vec_with_lab)),factor(no_lab)) expect_identical(fctr(unvr(vec_with_lab)),factor(no_lab,levels = 1:2,labels= c("Apple","Bananas"))) expect_identical(fctr(unvr(vec_with_lab)),fctr(vec_with_lab, prepend_var_lab = FALSE)) a = letters[1:3] var_lab(a) = "letters" expect_identical(fctr(a), factor(unlab(a),levels = c("a", "b", "c"),labels= c("letters|a", "letters|b", "letters|c"))) a = letters[1:3] var_lab(a) = "letters" expect_identical(fctr(unvr(a)), factor(unlab(a))) expect_identical(fctr(vec_with_lab), factor(no_lab,levels = 1:2,labels= c("Fruits|Apple","Fruits|Bananas"))) expect_identical(fctr(vec_with_lab, ordered = TRUE), factor(no_lab,levels = 1:2,labels= c("Fruits|Apple","Fruits|Bananas"), ordered = TRUE)) expect_identical(fctr(no_lab,levels = 1:2,labels= c("Fruits|Apple","Fruits|Bananas"), ordered = TRUE), factor(no_lab,levels = 1:2,labels= c("Fruits|Apple","Fruits|Bananas"), ordered = TRUE)) expect_identical(fctr(unvl(vec_with_lab)),factor(no_lab,levels = 1:2,labels= c("Fruits|1","Fruits|2"))) vec_with_lab2 = add_val_lab(vec_with_lab, c("Ananas" = 42)) expect_identical(fctr(vec_with_lab2), factor(no_lab,levels = c(1:2, 42), labels= c("Fruits|Apple","Fruits|Bananas","Fruits|Ananas"))) expect_identical(fctr(vec_with_lab2, drop_unused_labels = TRUE), factor(no_lab,levels = c(1:2), labels= c("Fruits|Apple","Fruits|Bananas"))) a = factor(c("a", "b", "c"), levels = rev(c("a", "b", "c", "d", "e"))) expect_identical(fctr(a, drop_unused_labels = TRUE), factor(a)) expect_identical(fctr(a, drop_unused_labels = FALSE), a) var_lab(a) = "My 'a' with labels" expect_identical(fctr(a, drop_unused_labels = FALSE, prepend_var_lab = FALSE), unvr(a)) b = a levels(b) = paste0(var_lab(b),"|", levels(b)) expect_identical(fctr(a, drop_unused_labels = FALSE, prepend_var_lab = TRUE), unvr(b)) expect_identical(fctr(a, drop_unused_labels = TRUE, prepend_var_lab = FALSE), factor(a)) test_ds = data.frame(total = 1, s2b = sample(2:3,100,replace = TRUE)) test_ds = unlab(test_ds) val_lab(test_ds$s2b) = c('18 - 26' = 2, '27 - 35' = 3) expect_identical(levels(fctr(test_ds$s2b)), names(val_lab(test_ds$s2b))) context("fctr.labelled - some values without labels") no_lab = c(no_lab,5:6) vec_with_lab = c(vec_with_lab,5:6) expect_identical(fctr(unlab(vec_with_lab)), factor(no_lab)) expect_identical(fctr(unvr(vec_with_lab)), factor(no_lab,levels = c(1:2,5:6),labels= c("Apple","Bananas","5","6"))) expect_identical(fctr(vec_with_lab), factor(no_lab,levels = c(1:2,5:6),labels= c("Fruits|Apple","Fruits|Bananas","Fruits|5","Fruits|6"))) expect_identical(fctr(unvl(vec_with_lab)), factor(no_lab,levels = c(1:2,5:6),labels= c("Fruits|1","Fruits|2","Fruits|5","Fruits|6"))) context( "fctr - errors and warnings") a = 1 class(a) = "labelled" attr(a, "labels") = c(a = 1, b = 1) expect_error(fctr(a)) attr(a, "labels") = c(a = 1, a = 2) expect_identical(suppressWarnings(fctr(a)), factor(1, levels = 1:2, labels = c("a","a|"))) attr(a, "labels") = c(a = 1, a = 2, a = 3) expect_identical(suppressWarnings(fctr(a)), factor(1, levels = 1:3, labels = c("a","a|","a||"))) a = 1:3 val_lab(a) = c("1" = 3) suppressWarnings(expect_identical(fctr(a), factor(c("1", "2", "1|"), levels = c("1", "2", "1|"))))
inlf <- function(x, table) { if(inherits(x, "lfactor")) { m1 <- match(x=as.character(x), table=as.character(table), nomatch=0, incomparables=NULL) m2 <- match(x=as.character(switchllevels(x)), table=as.character(table), nomatch=0, incomparables=NULL) } else { m1 <- match(x=as.character(x), table=as.character(table), nomatch=0, incomparables=NULL) m2 <- match(x=as.character(x), table=as.character(switchllevels(table)), nomatch=0, incomparables=NULL) } ((m1 > 0) | (m2 > 0)) } methods::setGeneric("%in%") methods::setMethod("%in%", methods::signature(x="lfactor"), inlf) methods::setMethod("%in%", methods::signature(table="lfactor"), inlf) methods::setMethod("%in%", methods::signature(x="lfactor", table="lfactor"), inlf)
dist_betw_matrices <- function(x,y, distance=c("rmsd", "mad", "propdiff"), align_cols=TRUE, cores=1) { distance <- match.arg(distance) if(!is.matrix(x)) x <- as.matrix(x) if(!is.matrix(y)) y <- as.matrix(y) if(align_cols) { aligned <- align_matrix_cols(x, y) x <- aligned$x y <- aligned$y if(ncol(x) < 2) { stop("In trying to align columns, we omitted all but 1 column") } } if(ncol(x) != ncol(y)) stop("x and y should have the same number of columns") x <- t(x) y <- t(y) cores <- setup_cluster(cores) if(distance=="rmsd") { func <- rmsd_betw_matrices } else if(distance=="mad") { func <- mad_betw_matrices } else { func <- propdiff_betw_matrices } if(n_cores(cores)==1) { result <- func(x, y) } else { func_by_xcol <- function(i) func(x[,i,drop=FALSE], y) result <- cluster_lapply(cores, 1:ncol(x), func_by_xcol) result <- matrix(unlist(result), ncol=ncol(y), byrow=TRUE) } dimnames(result) <- list(colnames(x), colnames(y)) result }
getQuantile <- function(Ftheta, mu, sigma, dist, par.location = 0, par.scale = 1, par.shape = 1, dist.par = NULL) { switch(dist, Uniform = { a <- 0 b <- 1 if(!is.null(dist.par)){ a <- dist.par[1] b <- dist.par[2] } EX <- (a+b)/2 VarX <- (b-a)^2/12 q <- qunif(Ftheta,min=a,max=b) }, Normal = { a <- par.location b <- par.scale if(!is.null(dist.par)){ a <- dist.par[1] b <- dist.par[2] } EX <- a VarX <- b^2 q <- qnorm(Ftheta, mean = a, sd = b) }, Normal2 = { a <- par.location b <- par.scale if(!is.null(dist.par)){ a <- dist.par[1] b <- dist.par[2] } EX <- a^2 + b^2 VarX <- 4 * a^2 * b^2 + 2 * b^4 q <- qchisq(Ftheta, 1) }, DoubleExp = { a <- par.location b <- par.scale if(!is.null(dist.par)){ a <- dist.par[1] b <- dist.par[2] } EX <- a VarX <- 2 * b^2 q <- a + (-1)^(Ftheta > 0.5) * b * log(2*(1-Ftheta + (-1+2*Ftheta)*(Ftheta<=0.5))) }, DoubleExp2 = { a <- par.location b <- par.scale if(!is.null(dist.par)){ a <- dist.par[1] b <- dist.par[2] } EX <- 2 * b^2 + a^2 EY3 <- 6 * b^3 + 6 * a * b^2 + 5 * a^3 EY4 <- 24 * b^4 + 4 * a * EY3 - 6 * a^2 * (2 * b^2 + a^2) + 5 * a^4 VarX <- EY4 - EX^2 stop("Result not available for this distribution.") }, LogNormal = { a <- par.location b <- par.scale if(!is.null(dist.par)){ a <- dist.par[1] b <- dist.par[2] } EX <- exp(a + b^2 / 2) VarX <- exp(2 * (a + b^2)) - exp(2 * a + b^2) q <- qlnorm(Ftheta) }, Gamma = { k <- par.scale o <- par.shape if(!is.null(dist.par)){ k <- dist.par[1] o <- dist.par[2] } EX <- k * o VarX <- o * k^2 q <- qgamma(Ftheta, shape = o, scale = k) }, Weibull = { k <- par.shape l <- par.scale if(!is.null(dist.par)){ k <- dist.par[1] l <- dist.par[2] } EX <- l * gamma(1 + 1 / k) VarX <- l^2 * (gamma(1 + 2 / k) - (gamma(1 + 1 / k))^2) q <- qweibull(Ftheta,shape = k, scale = l) }, t = { v <- par.shape if(!is.null(dist.par)){ v <- dist.par[1] } EX <- 0 VarX <- v/(v-2) q <- qt(Ftheta, v) }, { a <- par.location b <- par.scale if(!is.null(dist.par)){ a <- dist.par[1] b <- dist.par[2] } EX <- a VarX <- b^2 q <- qnorm(Ftheta, mean = a, sd = b) } ) theta <- (q - EX)/sqrt(VarX) * (sigma) + mu return(theta) }
context("Test API response columns are renamed correctly") unnamed_data <- read.table(system.file("extdata", "example_api_data_unnamed.txt", package = "scrobbler"), header = TRUE) test_renamed_data <- rename_api_response(unnamed_data) verified_renamed_data <- read.table(system.file("extdata", "example_api_data_renamed.txt", package = "scrobbler"), header = TRUE) test_that("Rename API table is successful", { expect_equal(test_renamed_data, verified_renamed_data) })
rasterise_grob <- function(grob, vp = NULL) { dim_inch <- dev.size("in") dim_pix <- dev.size("px") res <- dim_pix[1] / dim_inch[1] vp_size <- deviceDim(unit(1, 'npc'), unit(1, 'npc')) vp_loc <- deviceLoc(unit(0, 'npc'), unit(0, 'npc')) raster_loc <- unit.c(-1 * vp_loc$x, -1 * vp_loc$y) if (is.null(vp) && is_reference_grob(grob)) { return(list( raster = get_layer(grob$id), location = raster_loc, dimension = unit(dim_inch, 'inch') )) } if (is.null(vp)) vp <- viewport() vp_parent <- viewport(vp_loc$x, vp_loc$y, vp_size$w, vp_size$h, just = c('left', 'bottom'), clip = 'off') cur <- dev.cur() cap <- agg_capture( width = dim_inch[1], height = dim_inch[2], units = 'in', background = NA, res = res, scaling = getOption("ggfx.scaling", 1) ) on.exit({ dev.off() dev.set(cur) }, add = TRUE) pushViewport(vp) pushViewport(vp_parent) grid.draw(grob) list( raster = cap(native = TRUE), location = raster_loc, dimension = unit(dim_inch, 'inch') ) } groberize_raster <- function(raster, loc, dim, id, include) { if (!is.null(id)) { store_raster(raster, id) } if (!include) { return(nullGrob()) } rasterGrob(raster, x = loc[1], y = loc[2], width = dim[1], height = dim[2], just = c('left', 'bottom')) } NULL
.snormFit <- function(x, mean = 0, sd = 1, xi = 1.5, scale = NA, doplot = TRUE, add = FALSE, span = "auto", trace = TRUE, title = NULL, description = NULL, ...) { dist = dsnorm model = "SNORM Parameter Estimation" scale = "not used" x = x.orig = as.vector(x) obj = function(x, y = x, trace) { f = try(-sum(log(dist(y, x[1], x[2], x[3]))), silent = TRUE) if (is.na(f) | class(f) == "try-error") return(1e9) if (trace) { cat("\n Objective Function Value: ", -f) cat("\n Parameter Estimates: ", x, "\n") } f } r = nlminb( start = c(mean = 0, sd = 1, xi = 1.5), objective = obj, lower = c(-Inf, 0, 0), upper = c( Inf, Inf, Inf), y = x, trace = trace) names(r$par) <- c("mean", "sd", "xi") if (is.null(title)) title = model if (is.null(description)) description = description() fit = list(estimate = r$par, minimum = -r$objective, code = r$convergence) if (doplot) { x = as.vector(x.orig) if (span == "auto") span = seq(min(x), max(x), length = 501) z = density(x, n = 100, ...) x = z$x[z$y > 0] y = z$y[z$y > 0] y.points = dist(span, r$par[1], r$par[2], r$par[3]) ylim = log(c(min(y.points), max(y.points))) if (add) { lines(x = span, y = log(y.points), col = "steelblue") } else { plot(x, log(y), xlim = c(span[1], span[length(span)]), ylim = ylim, type = "p", xlab = "x", ylab = "log f(x)", ...) title(main = model) lines(x = span, y = log(y.points), col = "steelblue") } } new("fDISTFIT", call = match.call(), model = model, data = as.data.frame(x.orig), fit = fit, title = title, description = description() ) } snormFit <- function(x, ...) { start = c(mean = mean(x), sd = sqrt(var(x)), xi = 1) loglik = function(x, y = x){ f = -sum(log(dsnorm(y, x[1], x[2], x[3]))) f } fit = nlminb( start = start, objective = loglik, lower = c(-Inf, 0, 0), upper = c( Inf, Inf, Inf), y = x, ...) names(fit$par) = c("mean", "sd", "xi") fit }
setMethod( f = "show", signature = signature( object = "SamplingPattern" ), definition = function(object) { sampleSize <- getSampleSize(object) cat("Object of class", dQuote(class(object)), "\n") cat("sample size:", sampleSize, "\n") } )
ll_flexrsurv_alpha0alpha_bh<-function(alpha0alpha, beta0, beta, gamma0, Y, X0, X, Z, expected_rate, weights=NULL, step, Nstep, intTD=intTD_NC, intweightsfunc=intweights_CAV_SIM, nT0basis, Spline_t0=BSplineBasis(knots=NULL, degree=3, keep.duplicates=TRUE), Intercept_t0=TRUE, ialpha0, nX0, nX, ialpha, nTbasis, Spline_t =BSplineBasis(knots=NULL, degree=3, keep.duplicates=TRUE), Intercept_t_NPH=rep(TRUE, nX), debug=FALSE, ...){ if(is.null(Z)){ nZ <- 0 } else { nZ <- Z@nZ } if(Intercept_t0){ tmpgamma0 <- gamma0 } else { tmpgamma0 <- c(0, gamma0) } YT0Gamma0 <- predictSpline(Spline_t0*tmpgamma0, Y[,1], intercept=Intercept_t0) if( nX0){ PHterm <-exp(X0 %*% alpha0alpha[ialpha0]) } else PHterm <- 1 if(nZ) { Zalphabeta <- Z@DM %*%( diag(alpha0alpha[ialpha]) %*% Z@signature %*% t(ExpandAllCoefBasis(beta, ncol=nZ, value=1)) ) if(nX) { Zalphabeta <- Zalphabeta + X %*% t(ExpandCoefBasis(beta0, ncol=nX, splinebasis=Spline_t, expand=!Intercept_t_NPH, value=0)) } } else { if(nX) { Zalphabeta <- X %*% t(ExpandCoefBasis(beta0, ncol=nX, splinebasis=Spline_t, expand=!Intercept_t_NPH, value=0)) } else { Zalphabeta <- NULL } } if(nX + nZ) { NPHterm <- intTD(rateTD_bh_alphabeta, intTo=Y[,1], intToStatus=Y[,2], step, Nstep, intweightsfunc=intweightsfunc, gamma0=gamma0, Zalphabeta=Zalphabeta, Spline_t0=Spline_t0*tmpgamma0, Intercept_t0=Intercept_t0, Spline_t = Spline_t, Intercept_t=TRUE) } else { NPHterm <- predict(integrate(Spline_t0*tmpgamma0), Y[,1], intercep=Intercept_t0) } YT0 <- evaluate(Spline_t0, Y[,1], intercept=Intercept_t0) if(nX + nZ){ YT <- evaluate(Spline_t, Y[,1], intercept=TRUE) eventterm <- ifelse(Y[,2] , log( PHterm * (YT0Gamma0) * exp(apply(YT * Zalphabeta, 1, sum)) + expected_rate ), 0) } else { eventterm <- ifelse(Y[,2] , log( PHterm * (YT0Gamma0) + expected_rate ), 0) } if (!is.null(weights)) { ret <- crossprod(eventterm - PHterm * NPHterm , weights) } else { ret <- sum( eventterm - PHterm * NPHterm ) } ret }
context("taxa functions") test_that("Test read.names",{ names<-c( "1\t|\tall\t|\t\t|\tsynonym\t|", "1\t|\troot\t|\t\t|\tscientific name\t|", "2\t|\tBacteria\t|\tBacteria <prokaryotes>\t|\tscientific name\t|", "2\t|\tMonera\t|\tMonera <Bacteria>\t|\tin-part\t|", "2\t|\tProcaryotae\t|\tProcaryotae <Bacteria>\t|\tin-part\t|" ) out<-data.table::data.table('id'=1:2,'name'=c('root','Bacteria'),key='id') data.table::setindex(out,'name') expect_warning(expect_equal(read.names(textConnection(names)),out)) out<-data.table::data.table('id'=rep(1:2,2:3),'name'=c('all','root','Bacteria','Monera','Procaryotae'),key='id') data.table::setindex(out,'name') expect_warning(expect_equal(read.names(textConnection(names),FALSE),out)) expect_warning(read.names(textConnection(names)),'SQLite') }) test_that("Test read.nodes",{ nodes<-c( "1\t|\t1\t|\tno rank\t|\t\t|\t8\t|\t0\t|\t1\t|\t0\t|\t0\t|\t0\t|\t0\t|\t0\t|\t\t|", "2\t|\t131567\t|\tsuperkingdom\t|\t\t|\t0\t|\t0\t|\t11\t|\t0\t|\t0\t|\t0\t|\t0\t|\t0\t|\t\t|", "6\t|\t335928\t|\tgenus\t|\t\t|\t0\t|\t1\t|\t11\t|\t1\t|\t0\t|\t1\t|\t0\t|\t0\t|\t\t|", "7\t|\t6\t|\tspecies\t|\tAC\t|\t0\t|\t1\t|\t11\t|\t1\t|\t0\t|\t1\t|\t1\t|\t0\t|\t\t|", "9\t|\t32199\t|\tspecies\t|\tBA\t|\t0\t|\t1\t|\t11\t|\t1\t|\t0\t|\t1\t|\t1\t|\t0\t|\t\t|" ) out<-data.table::data.table('id'=c(1:2,6:7,9),'rank'=c('no rank','superkingdom','genus','species','species'),'parent'=c(1,131567,335928,6,32199),key='id') expect_warning(expect_equal(read.nodes(textConnection(nodes)),out)) expect_warning(read.nodes(textConnection(nodes)),'SQLite') }) test_that("Test read.names.sql",{ names<-c( "1\t|\tall\t|\t\t|\tsynonym\t|", "1\t|\troot\t|\t\t|\tscientific name\t|", "2\t|\tBacteria\t|\tBacteria <prokaryotes>\t|\tscientific name\t|", "2\t|\tMonera\t|\tMonera <Bacteria>\t|\tin-part\t|", "2\t|\tProcaryotae\t|\tProcaryotae <Bacteria>\t|\tin-part\t|" ) tmp<-tempfile() out<-data.frame('id'=1:2,'name'=c('root','Bacteria'),scientific=c(1,1),stringsAsFactors=FALSE) out2<-data.frame('id'=rep(1:2,2:3),'name'=c('all','root','Bacteria','Monera','Procaryotae'),'scientific'=c(0,1,1,0,0),stringsAsFactors=FALSE) expect_warning(expect_error(read.names.sql('____NOT_A_REAL____.FILE'),'cannot open'),'cannot open') expect_equal(read.names.sql(textConnection(names),tmp),tmp) expect_true(file.exists(tmp)) expect_message(read.names.sql(textConnection(names),tmp),'contains') expect_error(db <- RSQLite::dbConnect(RSQLite::SQLite(), dbname=tmp),NA) expect_equal(RSQLite::dbGetQuery(db,"SELECT * FROM names WHERE scientific"),out) expect_equal(RSQLite::dbGetQuery(db,"SELECT * FROM names"),out2) RSQLite::dbDisconnect(db) expect_equal(read.names.sql(textConnection(names[-length(names)]),tmp,overwrite=TRUE),tmp) expect_error(db <- RSQLite::dbConnect(RSQLite::SQLite(), dbname=tmp),NA) expect_equal(RSQLite::dbGetQuery(db,"SELECT * FROM names"),out2[-length(names),]) RSQLite::dbDisconnect(db) }) test_that("Test read.nodes.sql",{ nodes<-c( "1\t|\t1\t|\tno rank\t|\t\t|\t8\t|\t0\t|\t1\t|\t0\t|\t0\t|\t0\t|\t0\t|\t0\t|\t\t|", "2\t|\t131567\t|\tsuperkingdom\t|\t\t|\t0\t|\t0\t|\t11\t|\t0\t|\t0\t|\t0\t|\t0\t|\t0\t|\t\t|", "6\t|\t335928\t|\tgenus\t|\t\t|\t0\t|\t1\t|\t11\t|\t1\t|\t0\t|\t1\t|\t0\t|\t0\t|\t\t|", "7\t|\t6\t|\tspecies\t|\tAC\t|\t0\t|\t1\t|\t11\t|\t1\t|\t0\t|\t1\t|\t1\t|\t0\t|\t\t|", "9\t|\t32199\t|\tspecies\t|\tBA\t|\t0\t|\t1\t|\t11\t|\t1\t|\t0\t|\t1\t|\t1\t|\t0\t|\t\t|" ) tmp<-tempfile() out<-data.frame('id'=c(1:2,6:7,9),'rank'=c('no rank','superkingdom','genus','species','species'),'parent'=c(1,131567,335928,6,32199),stringsAsFactors=FALSE) expect_equal(read.nodes.sql(textConnection(nodes),tmp),tmp) expect_true(file.exists(tmp)) expect_message(read.nodes.sql(textConnection(nodes),tmp),'contains') expect_equal(read.nodes.sql(textConnection(nodes),tmp),tmp) expect_error(db <- RSQLite::dbConnect(RSQLite::SQLite(), dbname=tmp),NA) expect_equal(RSQLite::dbGetQuery(db,"SELECT * FROM nodes"),out) RSQLite::dbDisconnect(db) expect_equal(read.nodes.sql(textConnection(nodes[-length(nodes)]),tmp,overwrite=TRUE),tmp) expect_error(db <- RSQLite::dbConnect(RSQLite::SQLite(), dbname=tmp),NA) expect_equal(RSQLite::dbGetQuery(db,"SELECT * FROM nodes"),out[-length(nodes),]) RSQLite::dbDisconnect(db) }) test_that("Test lastNotNa",{ expect_equal(lastNotNa(1:100),100) expect_equal(lastNotNa(c(1:100,rep(NA,50))),100) expect_equal(lastNotNa(c(rep(NA,50),1:100,rep(NA,50))),100) expect_equal(lastNotNa(rep(NA,100),'z'),'z') expect_equal(lastNotNa(rep(NA,100),-999),-999) expect_equal(lastNotNa(rep(NA,100),NA),NA) expect_equal(lastNotNa(c(),999),999) }) test_that("Test streamingRead",{ expect_equal(streamingRead(textConnection(letters),2,paste,collapse=''),unname(as.list(tapply(letters,rep(1:13,each=2),function(x)paste(x,collapse=''))))) expect_output(streamingRead(textConnection(letters),2,vocal=TRUE),'.............') temp<-tempfile() writeLines(letters,temp) expect_equal(streamingRead(temp,2,paste,collapse=''),unname(as.list(tapply(letters,rep(1:13,each=2),function(x)paste(x,collapse=''))))) expect_equal(streamingRead(temp,100,paste,collapse=''),list(paste(letters,collapse=''))) expect_equal(streamingRead(temp,0),list()) expect_output(streamingRead(temp,2,vocal=TRUE),'.............') gz<-gzfile(temp,'w') writeLines(letters,gz) close(gz) expect_equal(streamingRead(temp,2,paste,collapse=''),unname(as.list(tapply(letters,rep(1:13,each=2),function(x)paste(x,collapse=''))))) expect_output(streamingRead(temp,2,vocal=TRUE),'.............') handle<-file(temp) expect_equal(streamingRead(handle,2,paste,collapse=''),unname(as.list(tapply(letters,rep(1:13,each=2),function(x)paste(x,collapse=''))))) handle<-file(temp,'w') expect_error(streamingRead(handle,2,paste,collapse=''),'read.*connection') }) test_that("Test trimTaxa",{ expect_error(taxonomizr:::trimTaxa('NotARealFile','test'),'file') expect_error(.C('taxaTrim',c('NotARealFile','test'),PACKAGE='taxonomizr'),'file') tmp<-tempfile() out<-c( 'head\t1\t2\t3', 'a\t2\t3\t4', 'b\t3\t4\t5', 'c\t4\t5\t6' ) writeLines(out,tmp) tmp2<-tempfile() dir.create(tmp2) expect_error(.C('taxaTrim',c(tmp,tmp2),PACKAGE='taxonomizr'),'file') tmp2<-tempfile() expect_error(taxonomizr:::trimTaxa(tmp,tmp2),NA) expect_equal(readLines(tmp2),c('2\t3','3\t4','4\t5')) writeLines(c(out,'1\t2\t3\t4\t5'),tmp) expect_error(taxonomizr:::trimTaxa(tmp,tmp2),"line") file.remove(tmp2);tmp2<-tempfile() gzHandle<-gzfile(tmp) writeLines(out,gzHandle) close(gzHandle) expect_error(taxonomizr:::trimTaxa(tmp,tmp2),NA) expect_equal(readLines(tmp2),c('2\t3','3\t4','4\t5')) file.remove(tmp2);tmp2<-tempfile() expect_error(taxonomizr:::trimTaxa(tmp,tmp2,2),NA) expect_equal(readLines(tmp2),c('2','3','4')) file.remove(tmp2);tmp2<-tempfile() expect_error(taxonomizr:::trimTaxa(tmp,tmp2,c(2,4)),NA) expect_equal(readLines(tmp2),c('2\t4','3\t5','4\t6')) expect_error(taxonomizr:::trimTaxa(tmp,tmp2,c(2,4)),NA) expect_equal(readLines(tmp2),rep(c('2\t4','3\t5','4\t6'),2)) with_mock(`R.utils::gunzip`=function(...){},expect_error(taxonomizr:::trimTaxa(tmp,tmp2),'unzip')) }) test_that("Test read.accession2taxid",{ taxa<-c( "accession\taccession.version\ttaxid\tgi", "Z17427\tZ17427.1\t3702\t16569", "Z17428\tZ17428.1\t3702\t16570", "Z17429\tZ17429.1\t3702\t16571", "Z17430\tZ17430.1\t3702\t16572" ) outFile<-tempfile() outFile2<-tempfile() inFile<-tempfile() writeLines(taxa,inFile) file.create(outFile) expect_error(read.accession2taxid(inFile,outFile),NA) file.remove(outFile) expect_error(read.accession2taxid(inFile,outFile),NA) expect_message(read.accession2taxid(inFile,outFile),'contains') expect_error(read.accession2taxid(inFile,outFile,overwrite=TRUE),NA) db<-RSQLite::dbConnect(RSQLite::SQLite(),dbname=outFile) result<-data.frame('base'=c('Z17427','Z17428','Z17429','Z17430'),'accession'=c('Z17427.1','Z17428.1','Z17429.1','Z17430.1'),taxa=3702,stringsAsFactors=FALSE) expect_true(file.exists(outFile)) expect_equal(RSQLite::dbGetQuery(db,'SELECT * FROM accessionTaxa'),result) file.remove(outFile) expect_error(read.accession2taxid(inFile,outFile,extraSqlCommand='pragma temp_store = 2;'),NA) file.remove(outFile) expect_error(read.accession2taxid(inFile,outFile,indexTaxa=TRUE),NA) expect_equal(RSQLite::dbGetQuery(db,'SELECT * FROM accessionTaxa'),result) RSQLite::dbDisconnect(db) file.remove(outFile) if(.Platform$OS.type == "unix"){ expect_error(read.accession2taxid(inFile,outFile,extraSqlCommand='DROP TABLE NOTEXISTXYZ;'),'NOTEXISTXYZ') expect_true(file.exists(outFile)) } }) test_that("Test getTaxonomy and getRawTaxonomy",{ namesText<-c( "1\t|\tall\t|\t\t|\tsynonym\t|", "1\t|\troot\t|\t\t|\tscientific name\t|", "2\t|\tBacteria\t|\tBacteria <prokaryotes>\t|\tscientific name\t|", "2\t|\tMonera\t|\tMonera <Bacteria>\t|\tin-part\t|", "2\t|\tProcaryotae\t|\tProcaryotae <Bacteria>\t|\tin-part\t|", "9606\t|\tHomo sapiens\t|\t\t|\tscientific name", "9605\t|\tHomo\t|\t\t|\tscientific name", "207598\t|\tHomininae\t|\t\t|\tscientific name", "9604\t|\tHominidae\t|\t\t|\tscientific name", "314295\t|\tHominoidea\t|\t\t|\tscientific name", "9526\t|\tCatarrhini\t|\t\t|\tscientific name", "314293\t|\tSimiiformes\t|\t\t|\tscientific name", "376913\t|\tHaplorrhini\t|\t\t|\tscientific name", "9443\t|\tPrimates\t|\t\t|\tscientific name", "314146\t|\tEuarchontoglires\t|\t\t|\tscientific name", "1437010\t|\tBoreoeutheria\t|\t\t|\tscientific name", "9347\t|\tEutheria\t|\t\t|\tscientific name", "32525\t|\tTheria\t|\t\t|\tscientific name", "40674\t|\tMammalia\t|\t\t|\tscientific name", "32524\t|\tAmniota\t|\t\t|\tscientific name", "32523\t|\tTetrapoda\t|\t\t|\tscientific name", "1338369\t|\tDipnotetrapodomorpha\t|\t\t|\tscientific name", "8287\t|\tSarcopterygii\t|\t\t|\tscientific name", "117571\t|\tEuteleostomi\t|\t\t|\tscientific name", "117570\t|\tTeleostomi\t|\t\t|\tscientific name", "7776\t|\tGnathostomata\t|\t\t|\tscientific name", "7742\t|\tVertebrata\t|\t\t|\tscientific name", "89593\t|\tCraniata\t|\t\t|\tscientific name", "7711\t|\tChordata\t|\t\t|\tscientific name", "33511\t|\tDeuterostomia\t|\t\t|\tscientific name", "33213\t|\tBilateria\t|\t\t|\tscientific name", "6072\t|\tEumetazoa\t|\t\t|\tscientific name", "33208\t|\tMetazoa\t|\t\t|\tscientific name", "33154\t|\tOpisthokonta\t|\t\t|\tscientific name", "2759\t|\tEukaryota\t|\t\t|\tscientific name", "131567\t|\tcellular organisms\t|\t\t|\tscientific name" ) nodesText<-c( "1\t|\t1\t|\tno rank\t|\t\t|\t8\t|\t0\t|\t1\t|\t0\t|\t0\t|\t0\t|\t0\t|\t0\t|\t\t|", "2\t|\t131567\t|\tsuperkingdom\t|\t\t|\t0\t|\t0\t|\t11\t|\t0\t|\t0\t|\t0\t|\t0\t|\t0\t|\t\t|", "6\t|\t335928\t|\tgenus\t|\t\t|\t0\t|\t1\t|\t11\t|\t1\t|\t0\t|\t1\t|\t0\t|\t0\t|\t\t|", "7\t|\t6\t|\tspecies\t|\tAC\t|\t0\t|\t1\t|\t11\t|\t1\t|\t0\t|\t1\t|\t1\t|\t0\t|\t\t|", "9\t|\t32199\t|\tspecies\t|\tBA\t|\t0\t|\t1\t|\t11\t|\t1\t|\t0\t|\t1\t|\t1\t|\t0\t|\t\t|", "9606\t|\t9605\t|\tspecies", "9605\t|\t207598\t|\tgenus", "207598\t|\t9604\t|\tsubfamily", "9604\t|\t314295\t|\tfamily", "314295\t|\t9526\t|\tsuperfamily", "9526\t|\t314293\t|\tparvorder", "314293\t|\t376913\t|\tinfraorder", "376913\t|\t9443\t|\tsuborder", "9443\t|\t314146\t|\torder", "314146\t|\t1437010\t|\tsuperorder", "1437010\t|\t9347\t|\tno rank", "9347\t|\t32525\t|\tno rank", "32525\t|\t40674\t|\tno rank", "40674\t|\t32524\t|\tclass", "32524\t|\t32523\t|\tno rank", "32523\t|\t1338369\t|\tno rank", "1338369\t|\t8287\t|\tno rank", "8287\t|\t117571\t|\tno rank", "117571\t|\t117570\t|\tno rank", "117570\t|\t7776\t|\tno rank", "7776\t|\t7742\t|\tno rank", "7742\t|\t89593\t|\tno rank", "89593\t|\t7711\t|\tsubphylum", "7711\t|\t33511\t|\tphylum", "33511\t|\t33213\t|\tno rank", "33213\t|\t6072\t|\tno rank", "6072\t|\t33208\t|\tno rank", "33208\t|\t33154\t|\tkingdom", "33154\t|\t2759\t|\tno rank", "2759\t|\t131567\t|\tsuperkingdom", "131567\t|\t1\t|\tno rank" ) tmp<-tempfile() read.names.sql(textConnection(namesText),tmp) read.nodes.sql(textConnection(nodesText),tmp) desiredTaxa<-c('superkingdom','phylum','class','order','family','genus','species') out<-matrix(c( "Eukaryota","Chordata","Mammalia","Primates","Hominidae","Homo","Homo sapiens", "Eukaryota","Chordata","Mammalia","Primates","Hominidae","Homo",NA ),byrow=TRUE,dimnames=list(c('9606','9605'),desiredTaxa),nrow=2) expect_equal(getTaxonomy(c(9606,9605),tmp,desiredTaxa=desiredTaxa),out) expect_equal(getTaxonomy(c(9605,9606,9605),tmp,desiredTaxa=desiredTaxa),out[c(2,1,2),]) expect_equal(getTaxonomy(c(9605,9606,9605),tmp,desiredTaxa=desiredTaxa[3:1]),out[c(2,1,2),3:1]) expect_equal(getTaxonomy(9606,tmp,desiredTaxa='NOTREAL'),matrix(as.character(NA),dimnames=list(9606,'NOTREAL'))) expect_equal(getTaxonomy(9999999,tmp,desiredTaxa='class'),matrix(as.character(NA),dimnames=list(9999999,'class'))) expect_equal(getTaxonomy(c(9999999,9606),tmp,desiredTaxa='class'),matrix(c(NA,'Mammalia'),dimnames=list(c('9999999',' 9606'),'class'),nrow=2)) expect_equal(getTaxonomy(c(),tmp,desiredTaxa=desiredTaxa),NULL) desiredRaw<-list(`9606` = c(species = "Homo sapiens", genus = "Homo", subfamily = "Homininae", family = "Hominidae", superfamily = "Hominoidea", parvorder = "Catarrhini", infraorder = "Simiiformes", suborder = "Haplorrhini", order = "Primates", superorder = "Euarchontoglires", `no rank` = "Boreoeutheria", `no rank.1` = "Eutheria", `no rank.2` = "Theria", class = "Mammalia", `no rank.3` = "Amniota", `no rank.4` = "Tetrapoda", `no rank.5` = "Dipnotetrapodomorpha", `no rank.6` = "Sarcopterygii", `no rank.7` = "Euteleostomi", `no rank.8` = "Teleostomi", `no rank.9` = "Gnathostomata", `no rank.10` = "Vertebrata", subphylum = "Craniata", phylum = "Chordata", `no rank.11` = "Deuterostomia", `no rank.12` = "Bilateria", `no rank.13` = "Eumetazoa", kingdom = "Metazoa", `no rank.14` = "Opisthokonta", superkingdom = "Eukaryota", `no rank.15` = "cellular organisms"), `9605` = c(genus = "Homo", subfamily = "Homininae", family = "Hominidae", superfamily = "Hominoidea", parvorder = "Catarrhini", infraorder = "Simiiformes", suborder = "Haplorrhini", order = "Primates", superorder = "Euarchontoglires", `no rank` = "Boreoeutheria", `no rank.1` = "Eutheria", `no rank.2` = "Theria", class = "Mammalia", `no rank.3` = "Amniota", `no rank.4` = "Tetrapoda", `no rank.5` = "Dipnotetrapodomorpha", `no rank.6` = "Sarcopterygii", `no rank.7` = "Euteleostomi", `no rank.8` = "Teleostomi", `no rank.9` = "Gnathostomata", `no rank.10` = "Vertebrata", subphylum = "Craniata", phylum = "Chordata", `no rank.11` = "Deuterostomia", `no rank.12` = "Bilateria", `no rank.13` = "Eumetazoa", kingdom = "Metazoa", `no rank.14` = "Opisthokonta", superkingdom = "Eukaryota", `no rank.15` = "cellular organisms")) expect_equal(getRawTaxonomy(c(9606,9605),tmp),desiredRaw) expect_equal(getRawTaxonomy(c(9606,9605,9605,9606),tmp),desiredRaw[c(1:2,2:1)]) expect_equal(getRawTaxonomy(c(),tmp),NULL) expect_equal(getRawTaxonomy(c(1),tmp),list('1'=NULL)) expect_equal(getRawTaxonomy(c(1,0),tmp),list('1'=NULL,'0'=structure(as.character(NA),.Names=NA))) expect_equal(getRawTaxonomy(c(NA),tmp),list('NA'=NULL)) expect_equal(getRawTaxonomy(c(NA,NA),tmp),list('NA'=NULL,'NA'=NULL)) expect_equal(getRawTaxonomy(c(NA,9606),tmp),c(list(' NA'=NULL),desiredRaw[1])) naDf<-out naDf[,]<-NA rownames(naDf)<-c('NA','NA') expect_equal(getTaxonomy(c(NA,NA),tmp),naDf) suppressWarnings(expect_equal(getTaxonomy(c(NA,9605,NA,'9604,9605'),tmp),rbind(' NA'=naDf[1,],'9605'=out[2,],' NA'=naDf[1,],' NA'=naDf[1,]))) expect_equal(getTaxonomy('9605',tmp),getTaxonomy(9605,tmp)) expect_warning(getTaxonomy('9605,123',tmp),'coercion') expect_warning(getRawTaxonomy('9605,123',tmp),'coercion') cycle<-c( "9606\t|\t9605\t|\tno rank\t|\t\t|\t8\t|\t0\t|\t1\t|\t0\t|\t0\t|\t0\t|\t0\t|\t0\t|\t\t|", "9605\t|\t9606\t|\tsuperkingdom\t|\t\t|\t0\t|\t0\t|\t11\t|\t0\t|\t0\t|\t0\t|\t0\t|\t0\t|\t\t|" ) tmp2<-tempfile() read.names.sql(textConnection(namesText),tmp2) read.nodes.sql(textConnection(cycle),tmp2) expect_error(getTaxonomy(9606,tmp2),'cycle') expect_error(getRawTaxonomy(9606,tmp2),'cycle') }) test_that("Test getTaxonomy and getRawTaxonomy with duplicated taxa ranks",{ namesText<-c( "1\t|\tall\t|\t\t|\tsynonym\t|", "1\t|\troot\t|\t\t|\tscientific name\t|", "2\t|\tBacteria\t|\tBacteria <prokaryotes>\t|\tscientific name\t|", "2\t|\tMonera\t|\tMonera <Bacteria>\t|\tin-part\t|", "2\t|\tProcaryotae\t|\tProcaryotae <Bacteria>\t|\tin-part\t|", "3\t|\tClade A\t|\t\t|\tscientific name\t|", "4\t|\tClade B\t|\t\t|\tscientific name\t|", "5\t|\tClade C\t|\t\t|\tscientific name\t|", "6\t|\tClade D\t|\t\t|\tscientific name\t|", "7\t|\tClade E\t|\t\t|\tscientific name\t|" ) nodesText<-c( "1\t|\t1\t|\tno rank\t|\t\t|\t8\t|\t0\t|\t1\t|\t0\t|\t0\t|\t0\t|\t0\t|\t0\t|\t\t|", "2\t|\t1\t|\tsuperkingdom\t|\t\t|\t0\t|\t0\t|\t11\t|\t0\t|\t0\t|\t0\t|\t0\t|\t0\t|\t\t|", "3\t|\t2\t|\tclade", "4\t|\t3\t|\tclade", "5\t|\t4\t|\tclade", "6\t|\t5\t|\tclade", "7\t|\t6\t|\tclade" ) tmp<-tempfile() read.names.sql(textConnection(namesText),tmp) read.nodes.sql(textConnection(nodesText),tmp) desiredTaxa<-c('superkingdom','clade') out<-matrix(c( "Bacteria","Clade A", "Bacteria","Clade A" ),byrow=TRUE,dimnames=list(c('7','6'),desiredTaxa),nrow=2) expect_equal(getTaxonomy(c(7,6),tmp,desiredTaxa=desiredTaxa),out) expect_equal(getRawTaxonomy(c(7,6,3),tmp),list('7'=c('clade'='Clade E','clade.1'='Clade D','clade.2'='Clade C','clade.3'='Clade B','clade.4'='Clade A','superkingdom'='Bacteria'),'6'=c('clade'='Clade D','clade.1'='Clade C','clade.2'='Clade B','clade.3'='Clade A','superkingdom'='Bacteria'),'3'=c('clade'='Clade A','superkingdom'='Bacteria'))) expect_equal(getRawTaxonomy(c(7),tmp),list('7'=c('clade'='Clade E','clade.1'='Clade D','clade.2'='Clade C','clade.3'='Clade B','clade.4'='Clade A','superkingdom'='Bacteria'))) }) test_that("Test getTaxonomy with deprecated data.tables",{ namesText<-c( "1\t|\tall\t|\t\t|\tsynonym\t|", "1\t|\troot\t|\t\t|\tscientific name\t|", "2\t|\tBacteria\t|\tBacteria <prokaryotes>\t|\tscientific name\t|", "2\t|\tMonera\t|\tMonera <Bacteria>\t|\tin-part\t|", "2\t|\tProcaryotae\t|\tProcaryotae <Bacteria>\t|\tin-part\t|", "9606\t|\tHomo sapiens\t|\t\t|\tscientific name", "9605\t|\tHomo\t|\t\t|\tscientific name", "207598\t|\tHomininae\t|\t\t|\tscientific name", "9604\t|\tHominidae\t|\t\t|\tscientific name", "314295\t|\tHominoidea\t|\t\t|\tscientific name", "9526\t|\tCatarrhini\t|\t\t|\tscientific name", "314293\t|\tSimiiformes\t|\t\t|\tscientific name", "376913\t|\tHaplorrhini\t|\t\t|\tscientific name", "9443\t|\tPrimates\t|\t\t|\tscientific name", "314146\t|\tEuarchontoglires\t|\t\t|\tscientific name", "1437010\t|\tBoreoeutheria\t|\t\t|\tscientific name", "9347\t|\tEutheria\t|\t\t|\tscientific name", "32525\t|\tTheria\t|\t\t|\tscientific name", "40674\t|\tMammalia\t|\t\t|\tscientific name", "32524\t|\tAmniota\t|\t\t|\tscientific name", "32523\t|\tTetrapoda\t|\t\t|\tscientific name", "1338369\t|\tDipnotetrapodomorpha\t|\t\t|\tscientific name", "8287\t|\tSarcopterygii\t|\t\t|\tscientific name", "117571\t|\tEuteleostomi\t|\t\t|\tscientific name", "117570\t|\tTeleostomi\t|\t\t|\tscientific name", "7776\t|\tGnathostomata\t|\t\t|\tscientific name", "7742\t|\tVertebrata\t|\t\t|\tscientific name", "89593\t|\tCraniata\t|\t\t|\tscientific name", "7711\t|\tChordata\t|\t\t|\tscientific name", "33511\t|\tDeuterostomia\t|\t\t|\tscientific name", "33213\t|\tBilateria\t|\t\t|\tscientific name", "6072\t|\tEumetazoa\t|\t\t|\tscientific name", "33208\t|\tMetazoa\t|\t\t|\tscientific name", "33154\t|\tOpisthokonta\t|\t\t|\tscientific name", "2759\t|\tEukaryota\t|\t\t|\tscientific name", "131567\t|\tcellular organisms\t|\t\t|\tscientific name" ) taxaNames<-expect_warning(read.names(textConnection(namesText))) nodesText<-c( "1\t|\t1\t|\tno rank\t|\t\t|\t8\t|\t0\t|\t1\t|\t0\t|\t0\t|\t0\t|\t0\t|\t0\t|\t\t|", "2\t|\t131567\t|\tsuperkingdom\t|\t\t|\t0\t|\t0\t|\t11\t|\t0\t|\t0\t|\t0\t|\t0\t|\t0\t|\t\t|", "6\t|\t335928\t|\tgenus\t|\t\t|\t0\t|\t1\t|\t11\t|\t1\t|\t0\t|\t1\t|\t0\t|\t0\t|\t\t|", "7\t|\t6\t|\tspecies\t|\tAC\t|\t0\t|\t1\t|\t11\t|\t1\t|\t0\t|\t1\t|\t1\t|\t0\t|\t\t|", "9\t|\t32199\t|\tspecies\t|\tBA\t|\t0\t|\t1\t|\t11\t|\t1\t|\t0\t|\t1\t|\t1\t|\t0\t|\t\t|", "9606\t|\t9605\t|\tspecies", "9605\t|\t207598\t|\tgenus", "207598\t|\t9604\t|\tsubfamily", "9604\t|\t314295\t|\tfamily", "314295\t|\t9526\t|\tsuperfamily", "9526\t|\t314293\t|\tparvorder", "314293\t|\t376913\t|\tinfraorder", "376913\t|\t9443\t|\tsuborder", "9443\t|\t314146\t|\torder", "314146\t|\t1437010\t|\tsuperorder", "1437010\t|\t9347\t|\tno rank", "9347\t|\t32525\t|\tno rank", "32525\t|\t40674\t|\tno rank", "40674\t|\t32524\t|\tclass", "32524\t|\t32523\t|\tno rank", "32523\t|\t1338369\t|\tno rank", "1338369\t|\t8287\t|\tno rank", "8287\t|\t117571\t|\tno rank", "117571\t|\t117570\t|\tno rank", "117570\t|\t7776\t|\tno rank", "7776\t|\t7742\t|\tno rank", "7742\t|\t89593\t|\tno rank", "89593\t|\t7711\t|\tsubphylum", "7711\t|\t33511\t|\tphylum", "33511\t|\t33213\t|\tno rank", "33213\t|\t6072\t|\tno rank", "6072\t|\t33208\t|\tno rank", "33208\t|\t33154\t|\tkingdom", "33154\t|\t2759\t|\tno rank", "2759\t|\t131567\t|\tsuperkingdom", "131567\t|\t1\t|\tno rank" ) taxaNodes<-expect_warning(read.nodes(textConnection(nodesText))) desiredTaxa<-c('superkingdom','phylum','class','order','family','genus','species') out<-matrix(c( "Eukaryota","Chordata","Mammalia","Primates","Hominidae","Homo","Homo sapiens", "Eukaryota","Chordata","Mammalia","Primates","Hominidae","Homo",NA ),byrow=TRUE,dimnames=list(c('9606','9605'),desiredTaxa),nrow=2) expect_warning(expect_equal(getTaxonomy(c(9606,9605),taxaNodes,taxaNames,mc.cores=1,desiredTaxa=desiredTaxa),out)) expect_warning(expect_equal(getTaxonomy(c(9605,9606,9605),taxaNodes,taxaNames,mc.cores=1,desiredTaxa=desiredTaxa),out[c(2,1,2),])) expect_warning(expect_equal(getTaxonomy(c(9605,9606,9605),taxaNodes,taxaNames,mc.cores=1,desiredTaxa=desiredTaxa[3:1]),out[c(2,1,2),3:1])) expect_warning(expect_output(getTaxonomy(9606,taxaNodes,taxaNames,mc.cores=1,debug=TRUE),'\\\\t')) expect_warning(expect_equal(getTaxonomy(9606,taxaNodes,taxaNames,mc.cores=1,desiredTaxa='NOTREAL'),matrix(as.character(NA),dimnames=list(9606,'NOTREAL')))) expect_warning(expect_equal(getTaxonomy(9999999,taxaNodes,taxaNames,mc.cores=1,desiredTaxa='class'),matrix(as.character(NA),dimnames=list(9999999,'class')))) if(.Platform$OS.type == "unix")expect_warning(expect_equal(getTaxonomy(c(9605,9606,9605),taxaNodes,taxaNames,mc.cores=2,desiredTaxa=desiredTaxa),out[c(2,1,2),])) expect_warning(expect_equal(getTaxonomy(c(),taxaNodes,taxaNames,mc.cores=1,desiredTaxa=desiredTaxa),NULL)) naDf<-out naDf[,]<-NA rownames(naDf)<-c('NA','NA') expect_warning(expect_equal(getTaxonomy(c(NA,NA),taxaNodes,taxaNames),naDf)) expect_warning(expect_equal(getTaxonomy(c(NA,9605,NA,'9604,9605'),taxaNodes,taxaNames),rbind(' NA'=naDf[1,],'9605'=out[2,],' NA'=naDf[1,],' NA'=naDf[1,]))) expect_warning(expect_equal(getTaxonomy('9605',taxaNodes,taxaNames),getTaxonomy(9605,taxaNodes,taxaNames))) expect_warning(getTaxonomy('9605,123',taxaNodes,taxaNames),'coercion') expect_warning(getTaxonomy(9999999,taxaNodes,taxaNames),'SQLite') }) test_that("Test getTaxonomy2",{ namesText<-c( "1\t|\tall\t|\t\t|\tsynonym\t|", "1\t|\troot\t|\t\t|\tscientific name\t|", "2\t|\tBacteria\t|\tBacteria <prokaryotes>\t|\tscientific name\t|", "2\t|\tMonera\t|\tMonera <Bacteria>\t|\tin-part\t|", "2\t|\tProcaryotae\t|\tProcaryotae <Bacteria>\t|\tin-part\t|", "9606\t|\tHomo sapiens\t|\t\t|\tscientific name", "9605\t|\tHomo\t|\t\t|\tscientific name", "207598\t|\tHomininae\t|\t\t|\tscientific name", "9604\t|\tHominidae\t|\t\t|\tscientific name", "314295\t|\tHominoidea\t|\t\t|\tscientific name", "9526\t|\tCatarrhini\t|\t\t|\tscientific name", "314293\t|\tSimiiformes\t|\t\t|\tscientific name", "376913\t|\tHaplorrhini\t|\t\t|\tscientific name", "9443\t|\tPrimates\t|\t\t|\tscientific name", "314146\t|\tEuarchontoglires\t|\t\t|\tscientific name", "1437010\t|\tBoreoeutheria\t|\t\t|\tscientific name", "9347\t|\tEutheria\t|\t\t|\tscientific name", "32525\t|\tTheria\t|\t\t|\tscientific name", "40674\t|\tMammalia\t|\t\t|\tscientific name", "32524\t|\tAmniota\t|\t\t|\tscientific name", "32523\t|\tTetrapoda\t|\t\t|\tscientific name", "1338369\t|\tDipnotetrapodomorpha\t|\t\t|\tscientific name", "8287\t|\tSarcopterygii\t|\t\t|\tscientific name", "117571\t|\tEuteleostomi\t|\t\t|\tscientific name", "117570\t|\tTeleostomi\t|\t\t|\tscientific name", "7776\t|\tGnathostomata\t|\t\t|\tscientific name", "7742\t|\tVertebrata\t|\t\t|\tscientific name", "89593\t|\tCraniata\t|\t\t|\tscientific name", "7711\t|\tChordata\t|\t\t|\tscientific name", "33511\t|\tDeuterostomia\t|\t\t|\tscientific name", "33213\t|\tBilateria\t|\t\t|\tscientific name", "6072\t|\tEumetazoa\t|\t\t|\tscientific name", "33208\t|\tMetazoa\t|\t\t|\tscientific name", "33154\t|\tOpisthokonta\t|\t\t|\tscientific name", "2759\t|\tEukaryota\t|\t\t|\tscientific name", "131567\t|\tcellular organisms\t|\t\t|\tscientific name" ) taxaNames<-expect_warning(read.names(textConnection(namesText))) nodesText<-c( "1\t|\t1\t|\tno rank\t|\t\t|\t8\t|\t0\t|\t1\t|\t0\t|\t0\t|\t0\t|\t0\t|\t0\t|\t\t|", "2\t|\t131567\t|\tsuperkingdom\t|\t\t|\t0\t|\t0\t|\t11\t|\t0\t|\t0\t|\t0\t|\t0\t|\t0\t|\t\t|", "6\t|\t335928\t|\tgenus\t|\t\t|\t0\t|\t1\t|\t11\t|\t1\t|\t0\t|\t1\t|\t0\t|\t0\t|\t\t|", "7\t|\t6\t|\tspecies\t|\tAC\t|\t0\t|\t1\t|\t11\t|\t1\t|\t0\t|\t1\t|\t1\t|\t0\t|\t\t|", "9\t|\t32199\t|\tspecies\t|\tBA\t|\t0\t|\t1\t|\t11\t|\t1\t|\t0\t|\t1\t|\t1\t|\t0\t|\t\t|", "9606\t|\t9605\t|\tspecies", "9605\t|\t207598\t|\tgenus", "207598\t|\t9604\t|\tsubfamily", "9604\t|\t314295\t|\tfamily", "314295\t|\t9526\t|\tsuperfamily", "9526\t|\t314293\t|\tparvorder", "314293\t|\t376913\t|\tinfraorder", "376913\t|\t9443\t|\tsuborder", "9443\t|\t314146\t|\torder", "314146\t|\t1437010\t|\tsuperorder", "1437010\t|\t9347\t|\tno rank", "9347\t|\t32525\t|\tno rank", "32525\t|\t40674\t|\tno rank", "40674\t|\t32524\t|\tclass", "32524\t|\t32523\t|\tno rank", "32523\t|\t1338369\t|\tno rank", "1338369\t|\t8287\t|\tno rank", "8287\t|\t117571\t|\tno rank", "117571\t|\t117570\t|\tno rank", "117570\t|\t7776\t|\tno rank", "7776\t|\t7742\t|\tno rank", "7742\t|\t89593\t|\tno rank", "89593\t|\t7711\t|\tsubphylum", "7711\t|\t33511\t|\tphylum", "33511\t|\t33213\t|\tno rank", "33213\t|\t6072\t|\tno rank", "6072\t|\t33208\t|\tno rank", "33208\t|\t33154\t|\tkingdom", "33154\t|\t2759\t|\tno rank", "2759\t|\t131567\t|\tsuperkingdom", "131567\t|\t1\t|\tno rank" ) taxaNodes<-expect_warning(read.nodes(textConnection(nodesText))) desiredTaxa<-c('superkingdom','phylum','class','order','family','genus','species') out<-matrix(c( "Eukaryota","Chordata","Mammalia","Primates","Hominidae","Homo","Homo sapiens", "Eukaryota","Chordata","Mammalia","Primates","Hominidae","Homo",NA ),byrow=TRUE,dimnames=list(c('9606','9605'),desiredTaxa),nrow=2) expect_warning(expect_equal(getTaxonomy2(c(9606,9605),taxaNodes,taxaNames,mc.cores=1,desiredTaxa=desiredTaxa),out)) expect_warning(expect_equal(getTaxonomy2(c(9605,9606,9605),taxaNodes,taxaNames,mc.cores=1,desiredTaxa=desiredTaxa),out[c(2,1,2),])) expect_warning(expect_equal(getTaxonomy2(c(9605,9606,9605),taxaNodes,taxaNames,mc.cores=1,desiredTaxa=desiredTaxa[3:1]),out[c(2,1,2),3:1])) expect_warning(expect_output(getTaxonomy2(9606,taxaNodes,taxaNames,mc.cores=1,debug=TRUE),'\\\\t')) expect_warning(expect_equal(getTaxonomy2(9606,taxaNodes,taxaNames,mc.cores=1,desiredTaxa='NOTREAL'),matrix(as.character(NA),dimnames=list(9606,'NOTREAL')))) expect_warning(expect_equal(getTaxonomy2(9999999,taxaNodes,taxaNames,mc.cores=1,desiredTaxa='class'),matrix(as.character(NA),dimnames=list(9999999,'class')))) if(.Platform$OS.type == "unix")expect_warning(expect_equal(getTaxonomy2(c(9605,9606,9605),taxaNodes,taxaNames,mc.cores=2,desiredTaxa=desiredTaxa),out[c(2,1,2),])) expect_warning(expect_equal(getTaxonomy2(c(),taxaNodes,taxaNames,mc.cores=1,desiredTaxa=desiredTaxa),NULL)) naDf<-out naDf[,]<-NA rownames(naDf)<-c('NA','NA') expect_warning(expect_equal(getTaxonomy2(c(NA,NA),taxaNodes,taxaNames),naDf)) expect_warning(expect_equal(getTaxonomy2(c(NA,9605,NA,'9604,9605'),taxaNodes,taxaNames),rbind(' NA'=naDf[1,],'9605'=out[2,],' NA'=naDf[1,],' NA'=naDf[1,]))) expect_warning(expect_equal(getTaxonomy2('9605',taxaNodes,taxaNames),getTaxonomy2(9605,taxaNodes,taxaNames))) expect_warning(getTaxonomy2('9605,123',taxaNodes,taxaNames),'coercion') }) test_that("Test getParentNodes",{ nodesText<-c( "1\t|\t1\t|\tno rank\t|\t\t|\t8\t|\t0\t|\t1\t|\t0\t|\t0\t|\t0\t|\t0\t|\t0\t|\t\t|", "2\t|\t131567\t|\tsuperkingdom\t|\t\t|\t0\t|\t0\t|\t11\t|\t0\t|\t0\t|\t0\t|\t0\t|\t0\t|\t\t|", "6\t|\t335928\t|\tgenus\t|\t\t|\t0\t|\t1\t|\t11\t|\t1\t|\t0\t|\t1\t|\t0\t|\t0\t|\t\t|", "7\t|\t6\t|\tspecies\t|\tAC\t|\t0\t|\t1\t|\t11\t|\t1\t|\t0\t|\t1\t|\t1\t|\t0\t|\t\t|", "9\t|\t32199\t|\tspecies\t|\tBA\t|\t0\t|\t1\t|\t11\t|\t1\t|\t0\t|\t1\t|\t1\t|\t0\t|\t\t|", "9606\t|\t9605\t|\tspecies", "9605\t|\t207598\t|\tgenus", "207598\t|\t9604\t|\tsubfamily", "9604\t|\t314295\t|\tfamily", "314295\t|\t9526\t|\tsuperfamily", "9526\t|\t314293\t|\tparvorder", "314293\t|\t376913\t|\tinfraorder", "376913\t|\t9443\t|\tsuborder", "9443\t|\t314146\t|\torder", "314146\t|\t1437010\t|\tsuperorder", "1437010\t|\t9347\t|\tno rank", "9347\t|\t32525\t|\tno rank", "32525\t|\t40674\t|\tno rank", "40674\t|\t32524\t|\tclass", "32524\t|\t32523\t|\tno rank", "32523\t|\t1338369\t|\tno rank", "1338369\t|\t8287\t|\tno rank", "8287\t|\t117571\t|\tno rank", "117571\t|\t117570\t|\tno rank", "117570\t|\t7776\t|\tno rank", "7776\t|\t7742\t|\tno rank", "7742\t|\t89593\t|\tno rank", "89593\t|\t7711\t|\tsubphylum", "7711\t|\t33511\t|\tphylum", "33511\t|\t33213\t|\tno rank", "33213\t|\t6072\t|\tno rank", "6072\t|\t33208\t|\tno rank", "33208\t|\t33154\t|\tkingdom", "33154\t|\t2759\t|\tno rank", "2759\t|\t131567\t|\tsuperkingdom", "131567\t|\t1\t|\tno rank" ) namesText<-c( "1\t|\tall\t|\t\t|\tsynonym\t|", "1\t|\troot\t|\t\t|\tscientific name\t|", "2\t|\tBacteria\t|\tBacteria <prokaryotes>\t|\tscientific name\t|", "2\t|\tMonera\t|\tMonera <Bacteria>\t|\tin-part\t|", "2\t|\tProcaryotae\t|\tProcaryotae <Bacteria>\t|\tin-part\t|", "9606\t|\tMan\t|\t\t|\tsynonym","9606\t|\thuman\t|\t\t|\tsynonym", "9606\t|\tHomo sapiens\t|\t\t|\tscientific name", "9605\t|\tHomo\t|\t\t|\tscientific name", "207598\t|\tHomininae\t|\t\t|\tscientific name", "9604\t|\tHominidae\t|\t\t|\tscientific name", "314295\t|\tHominoidea\t|\t\t|\tscientific name", "9526\t|\tCatarrhini\t|\t\t|\tscientific name", "314293\t|\tSimiiformes\t|\t\t|\tscientific name", "376913\t|\tHaplorrhini\t|\t\t|\tscientific name", "9443\t|\tPrimates\t|\t\t|\tscientific name", "314146\t|\tEuarchontoglires\t|\t\t|\tscientific name", "1437010\t|\tBoreoeutheria\t|\t\t|\tscientific name", "9347\t|\tEutheria\t|\t\t|\tscientific name", "32525\t|\tTheria\t|\t\t|\tscientific name", "40674\t|\tMammalia\t|\t\t|\tscientific name", "32524\t|\tAmniota\t|\t\t|\tscientific name", "32523\t|\tTetrapoda\t|\t\t|\tscientific name", "1338369\t|\tDipnotetrapodomorpha\t|\t\t|\tscientific name", "8287\t|\tSarcopterygii\t|\t\t|\tscientific name", "117571\t|\tEuteleostomi\t|\t\t|\tscientific name", "117570\t|\tTeleostomi\t|\t\t|\tscientific name", "7776\t|\tGnathostomata\t|\t\t|\tscientific name", "7742\t|\tVertebrata\t|\t\t|\tscientific name", "89593\t|\tCraniata\t|\t\t|\tscientific name", "7711\t|\tChordata\t|\t\t|\tscientific name", "33511\t|\tDeuterostomia\t|\t\t|\tscientific name", "33213\t|\tBilateria\t|\t\t|\tscientific name", "6072\t|\tEumetazoa\t|\t\t|\tscientific name", "33208\t|\tMetazoa\t|\t\t|\tscientific name", "33154\t|\tOpisthokonta\t|\t\t|\tscientific name", "2759\t|\tEukaryota\t|\t\t|\tscientific name", "131567\t|\tcellular organisms\t|\t\t|\tscientific name" ) tmp<-tempfile() read.nodes.sql(textConnection(nodesText),tmp) read.names.sql(textConnection(namesText),tmp) expect_equal(taxonomizr:::getParentNodes(c(9606,9605),tmp),data.frame('name'=c('Homo sapiens','Homo'),'parent'=c(9605,207598),'rank'=c('species','genus'),stringsAsFactors=FALSE)) expect_equal(taxonomizr:::getParentNodes(c('a'=9606,'b'=9605),tmp),data.frame('name'=c('Homo sapiens','Homo'),'parent'=c(9605,207598),'rank'=c('species','genus'),stringsAsFactors=FALSE)) expect_equal(taxonomizr:::getParentNodes(c(NA,9606,9999999,9606),tmp),data.frame('name'=c(NA,'Homo sapiens',NA,'Homo sapiens'),'parent'=c(NA,9605,NA,9605),'rank'=c(NA,'species',NA,'species'),stringsAsFactors=FALSE)) with_mock(`RSQLite::dbGetQuery`=function(...){data.frame('id'=c(9999))},expect_error(taxonomizr:::getParentNodes(c(9606,9605),tmp),'finding')) with_mock(`RSQLite::dbGetQuery`=function(...){data.frame('id'=c(9605,9606))},expect_error(taxonomizr:::getParentNodes(c(9606,9605),tmp),'finding')) }) test_that("Test checkDownloadMd5",{ tmp<-tempfile() tmp2<-tempfile() writeLines('THISISSOMEDATA',tmp) writeLines('THISISSOMEOTHERDATA',tmp2) md5<-tools::md5sum(tmp) expect_true(checkDownloadMd5(sprintf('file://%s',tmp),tmp2)) expect_error(checkDownloadMd5(sprintf('file://%s',tmp),tmp2,TRUE),'md5') writeLines(sprintf('%s EXTRASTUFF',md5),sprintf('%s.md5',tmp)) expect_false(checkDownloadMd5(sprintf('file://%s',tmp),tmp2)) file.copy(tmp,tmp2,TRUE) expect_true(checkDownloadMd5(sprintf('file://%s',tmp),tmp2)) writeLines(sprintf('SOMEOTHERMD5 EXTRASTUFF',md5),sprintf('%s.md5',tmp)) expect_false(checkDownloadMd5(sprintf('file://%s',tmp),tmp2)) }) test_that("Test accessionToTaxa",{ taxa<-c( "accession\taccession.version\ttaxid\tgi", "Z17427\tZ17427.1\t3702\t16569", "Z17428\tZ17428.1\t3702\t16570", "Z17429\tZ17429.1\t3702\t16571", "Z17430\tZ17430.1\t3702\t16572", "X62402\tX62402.1\t9606\t30394" ) inFile<-tempfile() sqlFile<-tempfile() expect_error(accessionToTaxa("Z17430.1",notARealVariable),"found") expect_error(accessionToTaxa("Z17430.1",sqlFile),"exist") expect_error(accessionToTaxa(c(),notARealVariable),"found") expect_error(accessionToTaxa(c(),sqlFile),"exist") writeLines(taxa,inFile) read.accession2taxid(inFile,sqlFile) expect_equal(accessionToTaxa(c("Z17430.1","Z17429.1","X62402.1"),sqlFile),c(3702,3702,9606)) expect_equal(accessionToTaxa(c('A'="Z17430.1",'B'="Z17429.1",'C'="X62402.1"),sqlFile),c(3702,3702,9606)) expect_equal(accessionToTaxa(c(),sqlFile),c()) expect_equal(accessionToTaxa(c("Z17430.1","NOTREAL","X62402.1","Z17429.1","X62402.1"),sqlFile),c(3702,NA,9606,3702,9606)) expect_error(accessionToTaxa("Z17430.1","NOTREAL"),"exist") expect_equal(accessionToTaxa(c(),sqlFile),c()) expect_equal(accessionToTaxa(c("Z17430.1","Z17429.1","X62402.1"),sqlFile,'base'),as.integer(c(NA,NA,NA))) expect_equal(accessionToTaxa(c("Z17430","NOTREAL","X62402","Z17429","X62402"),sqlFile,'base'),c(3702,NA,9606,3702,9606)) expect_equal(accessionToTaxa(c("Z17430","NOTREAL","X62402","Z17429","X62402"),sqlFile,'version'),as.integer(c(NA,NA,NA,NA,NA))) with_mock(`RSQLite::dbGetQuery`=function(...){data.frame('accession'=c(9605,9606))},expect_error(accessionToTaxa(c("Z17430.1","X62402.1"),sqlFile),'mismatch')) with_mock(`RSQLite::dbGetQuery`=function(...){data.frame('accession'=c("X62402.1","Z17430.1"))},expect_error(accessionToTaxa(c("Z17430.1","X62402.1"),sqlFile),'mismatch')) with_mock(`RSQLite::dbGetQuery`=function(...){data.frame('accession'=c("NOTREAL","NOTREAL2","NOTREAL3"))},expect_error(accessionToTaxa(c("Z17430.1","X62402.1"),sqlFile),'mismatch')) }) test_that("Test condenseTaxa",{ taxas<-matrix(c( 'a','b','c','e', 'a','b','d','e' ),nrow=2,byrow=TRUE) expect_equal(condenseTaxa(taxas),matrix(c('a','b',NA,NA),nrow=1,dimnames=list('1',c('V1','V2','V3','V4')))) expect_equal(condenseTaxa(taxas[c(1,1,1),]),matrix(c('a','b','c','e'),nrow=1,dimnames=list('1',c('V1','V2','V3','V4')))) expect_equal(condenseTaxa(taxas[1,,drop=FALSE]),matrix(c('a','b','c','e'),nrow=1,dimnames=list('1',c('V1','V2','V3','V4')))) expect_equal(condenseTaxa(taxas[,1,drop=FALSE]),matrix(c('a'),nrow=1,dimnames=list('1',c('V1')))) expect_equal(condenseTaxa(taxas[1,1,drop=FALSE]),matrix(c('a'),nrow=1,dimnames=list('1',c('V1')))) expect_equal(condenseTaxa(taxas[c(1,1,1,2),]),matrix(c('a','b',NA,NA),nrow=1,dimnames=list('1',c('V1','V2','V3','V4')))) expect_equal(condenseTaxa(taxas[,3,drop=FALSE]),matrix(c(as.character(NA)),nrow=1,dimnames=list('1',c('V1')))) expect_equal(condenseTaxa(taxas[,3,drop=FALSE],1:2),matrix(c('c','d'),nrow=2,dimnames=list(c('1','2'),c('V1')))) expect_equal(condenseTaxa(taxas[0,]),NULL) expect_equal(condenseTaxa(taxas[c(1:2,1),],c(1,1,2)),matrix(c('a','a','b','b',NA,'c',NA,'e'),nrow=2,dimnames=list(c('1','2'),c('V1','V2','V3','V4')))) expect_equal(condenseTaxa(taxas[c(1:2,rep(1,10)),],c(1,1,rep(2,10))),matrix(c('a','a','b','b',NA,'c',NA,'e'),nrow=2,dimnames=list(c('1','2'),c('V1','V2','V3','V4')))) taxas<-matrix(c( 'a','b',NA,'e', 'a','b','d','e' ),nrow=2,byrow=TRUE,dimnames=list(NULL,c('a','b','c','d'))) expect_equal(condenseTaxa(taxas),matrix(c('a','b',NA,NA),nrow=1,dimnames=list('1',c('a','b','c','d')))) expect_equal(condenseTaxa(taxas[1,,drop=FALSE]),matrix(c('a','b',NA,'e'),nrow=1,dimnames=list('1',c('a','b','c','d')))) expect_equal(condenseTaxa(taxas[c(1,1,1),,drop=FALSE]),matrix(c('a','b',NA,'e'),nrow=1,dimnames=list('1',c('a','b','c','d')))) out<-matrix(c('a','b',NA,NA),byrow=TRUE,nrow=10,ncol=4,dimnames=list(as.character(1:10),c('a','b','c','d'))) expect_equal(condenseTaxa(taxas[rep(1:2,each=10),,drop=FALSE],rep(1:10,2)),out) rownames(out)<-letters[1:10] expect_equal(condenseTaxa(taxas[rep(1:2,each=10),,drop=FALSE],rep(letters[1:10],2)),out) }) test_that("Test getNamesAndNodes",{ tmp<-tempfile() dir.create(tmp) testFile<-system.file('testdata/fakeNamesNodes.tar.gz',package='taxonomizr') if(.Platform$OS.type == "windows"){ R.utils::gunzip(testFile,remove=FALSE,skip=TRUE) testFile<-system.file('testdata/fakeNamesNodes.tar',package='taxonomizr') } fakeFile<-sprintf('file://%s',testFile) expect_error(getNamesAndNodes(tmp,fakeFile),NA) expect_equal(sort(list.files(tmp,'^(names|nodes).dmp$')),c('names.dmp','nodes.dmp')) expect_message(getNamesAndNodes(tmp,fakeFile),'exist') expect_equal(getNamesAndNodes(tmp,fakeFile),file.path(tmp,c('names.dmp','nodes.dmp'))) expect_error(getNamesAndNodes(tmp,fakeFile,'NOTREAL.FILE'),'finding|incomplete') tmp<-tempfile() with_mock(`file.copy`=function(...)TRUE,expect_error(getNamesAndNodes(tmp,fakeFile),'copying')) if(.Platform$OS.type == "windows")file.remove('fakeNamesNodes.tar') tmp<-tempfile() dir.create(tmp) newFake<-file.path(tmp,'fake') download.file(fakeFile,newFake,mode='wb') fakeMd5<-tools::md5sum(newFake) writeLines(sprintf('%s EXTRATEXT',fakeMd5),sprintf('%s.md5',newFake)) expect_error(getNamesAndNodes(tmp,sprintf('file://%s',newFake)),NA) tmp<-tempfile() dir.create(tmp) writeLines('NOTREALHASH EXTRATEXT',sprintf('%s.md5',newFake)) expect_error(getNamesAndNodes(tmp,sprintf('file://%s',newFake)),'match') }) test_that("Test getAccession2taxid",{ tmp<-tempfile() dir.create(tmp) types<-c('XxXx','XyXyX') targets<-sprintf('nucl_%s.accession2taxid.gz',types) sapply(targets,function(xx)writeLines('TEST',file.path(tmp,xx),sep='')) tmp2<-tempfile() dir.create(tmp2) expect_error(getAccession2taxid(tmp2,baseUrl=sprintf('file://%s',tmp),types=c('nucl_XxXx','nucl_XyXyX')),NA) expect_equal(sort(list.files(tmp2,'accession2taxid.gz$')),sort(targets)) expect_message(getAccession2taxid(tmp2,baseUrl=sprintf('file://%s',tmp),types=c('nucl_XxXx','nucl_XyXyX')),'exist') file.remove(list.files(tmp2,'^nucl_.*.gz$',full.names=TRUE)) writeLines('NOTREALHASH EXTRATEXT',sprintf('%s.md5',file.path(tmp,targets[1]))) expect_error(getAccession2taxid(tmp2,baseUrl=sprintf('file://%s',tmp),types=c('nucl_XxXx','nucl_XyXyX')),'match') fakeMd5<-tools::md5sum(file.path(tmp,targets[1])) file.remove(list.files(tmp2,'^nucl_.*.gz$',full.names=TRUE)) writeLines(sprintf('%s EXTRATEXT',fakeMd5),sprintf('%s.md5',file.path(tmp,targets[1]))) expect_error(getAccession2taxid(tmp2,baseUrl=sprintf('file://%s',tmp),types=c('nucl_XxXx','nucl_XyXyX')),NA) fakeMd5<-tools::md5sum(file.path(tmp,targets[2])) file.remove(list.files(tmp2,'^nucl_.*.gz$',full.names=TRUE)) writeLines('NOTREALHASH EXTRATEXT',sprintf('%s.md5',file.path(tmp,targets[2]))) expect_error(getAccession2taxid(tmp2,baseUrl=sprintf('file://%s',tmp),types=c('nucl_XxXx','nucl_XyXyX')),'match') file.remove(list.files(tmp2,'^nucl_.*.gz$',full.names=TRUE)) writeLines(sprintf('%s EXTRATEXT',fakeMd5),sprintf('%s.md5',file.path(tmp,targets[2]))) expect_error(getAccession2taxid(tmp2,baseUrl=sprintf('file://%s',tmp),types=c('nucl_XxXx','nucl_XyXyX')),NA) }) test_that("Test getId with deprecated data.table",{ namesText<-c( "1\t|\troot\t|\t\t|\tscientific name\t|", "4\t|\tMulti\t|\tBacteria <prokaryotes>\t|\tscientific name\t|", "3\t|\tMulti\t|\tBacteria <prokaryotes>\t|\tscientific name\t|", "2\t|\tBacteria\t|\tBacteria <prokaryotes>\t|\tscientific name\t|" ) expect_warning(names<-read.names(textConnection(namesText))) expect_warning(expect_equal(getId('Bacteria',names),'2')) expect_warning(expect_equal(getId(c('Bacteria','root','Bacteria','NOTREAL'),names),c('2','1','2',NA))) expect_warning(expect_equal(getId('Not a real name',names),as.character(NA))) expect_warning(expect_equal(getId('Multi',names),'3,4')) expect_warning(getId('Multi',names),'Multiple') expect_warning(getId('Bacteria',names),'SQLite') }) test_that("Test getId2",{ namesText<-c( "1\t|\troot\t|\t\t|\tscientific name\t|", "4\t|\tMulti1\t|\tBacteria <prokaryotes>\t|\tscientific name\t|", "3\t|\tMulti1\t|\tBacteria <prokaryotes>\t|\tscientific name\t|", "2\t|\tBacteria\t|\tBacteria <prokaryotes>\t|\tscientific name\t|", "5\t|\tMulti2\t|\tBacteria <prokaryotes>\t|\tscientific name\t|", "6\t|\tMulti2\t|\tBacteria <prokaryotes>\t|\tscientific name\t|" ) expect_warning(names<-read.names(textConnection(namesText))) expect_warning(expect_equal(getId2('Bacteria',names),'2')) expect_warning(expect_equal(getId2(c('Bacteria','root','Bacteria','NOTREAL'),names),c('2','1','2',NA))) expect_warning(expect_equal(getId2('Not a real name',names),as.character(NA))) expect_warning(expect_equal(getId2(c('Bacteria','Multi1','NOTREAL'),names),c('2','3,4',NA))) expect_warning(getId2(c('Multi1','Bacteria','Multi2'),names),'Multiple.*Multi1, Multi2') expect_warning(getId2('Bacteria',names),'SQLite') }) test_that("Test getId",{ namesText<-c( "1\t|\troot\t|\t\t|\tscientific name\t|", "4\t|\tMulti1\t|\tBacteria <prokaryotes>\t|\tscientific name\t|", "3\t|\tMulti1\t|\tBacteria <prokaryotes>\t|\tscientific name\t|", "2\t|\tBacteria\t|\tBacteria <prokaryotes>\t|\tscientific name\t|", "5\t|\tMulti2\t|\tBacteria <prokaryotes>\t|\tscientific name\t|", "6\t|\tMulti2\t|\tBacteria <prokaryotes>\t|\tscientific name\t|" ) tmp<-tempfile() read.names.sql(textConnection(namesText),tmp) expect_equal(getId('Bacteria',tmp),'2') expect_equal(getId(c('Bacteria','root','Bacteria','NOTREAL'),tmp),c('2','1','2',NA)) expect_equal(getId('Not a real name',tmp),as.character(NA)) suppressWarnings(expect_equal(getId(c('Bacteria','Multi1','NOTREAL'),tmp),c('2','3,4',NA))) expect_warning(getId(c('Multi1','Bacteria','Multi2'),tmp),'Multiple.*Multi1, Multi2') }) test_that("Test getAccessions",{ taxa<-c( "accession\taccession.version\ttaxid\tgi", "Z17427\tZ17427.1\t3702\t16569", "Z17428\tZ17428.1\t3702\t16570", "Z17429\tZ17429.1\t3702\t16571", "Z17430\tZ17430.1\t3702\t16572", "X62402\tX62402.1\t9606\t30394" ) inFile<-tempfile() sqlFile<-tempfile() expect_error(getAccessions("Z17430.1",notARealVariable),"found") expect_error(getAccessions("Z17430.1",sqlFile),"exist") expect_error(getAccessions(c(),notARealVariable),"found") expect_error(getAccessions(c(),sqlFile),"exist") writeLines(taxa,inFile) read.accession2taxid(inFile,sqlFile) expect_equal(getAccessions(3702,sqlFile),data.frame('taxa'=3702,'accession'=c("Z17427.1","Z17428.1","Z17429.1","Z17430.1"),stringsAsFactors=FALSE)) expect_equal(getAccessions(c(3702,9606),sqlFile),data.frame('taxa'=rep(c(3702,9606),c(4,1)),'accession'=c("Z17427.1","Z17428.1","Z17429.1","Z17430.1","X62402.1"),stringsAsFactors=FALSE)) expect_equal(getAccessions(c(3702,9606),sqlFile,'base'),data.frame('taxa'=rep(c(3702,9606),c(4,1)),'accession'=c("Z17427","Z17428","Z17429","Z17430","X62402"),stringsAsFactors=FALSE)) expect_equal(getAccessions(c(3702,9999),sqlFile),data.frame('taxa'=rep(c(3702,9999),c(4,1)),'accession'=c("Z17427.1","Z17428.1","Z17429.1","Z17430.1",NA),stringsAsFactors=FALSE)) expect_equal(getAccessions(c(3702,9999,'NOTREAL'),sqlFile),data.frame('taxa'=rep(c(3702,9999,'NOTREAL'),c(4,1,1)),'accession'=c("Z17427.1","Z17428.1","Z17429.1","Z17430.1",NA,NA),stringsAsFactors=FALSE)) expect_equal(getAccessions(c(3702,9999,'NOTREAL'),sqlFile,'base'),data.frame('taxa'=rep(c(3702,9999,'NOTREAL'),c(4,1,1)),'accession'=c("Z17427","Z17428","Z17429","Z17430",NA,NA),stringsAsFactors=FALSE)) expect_equal(getAccessions(c(3702,9999,'NOTREAL'),sqlFile,'version'),data.frame('taxa'=rep(c(3702,9999,'NOTREAL'),c(4,1,1)),'accession'=c("Z17427.1","Z17428.1","Z17429.1","Z17430.1",NA,NA),stringsAsFactors=FALSE)) expect_equal(getAccessions(c(3702,9606),sqlFile,limit=3),data.frame('taxa'=rep(c(3702,9606),c(3,0)),'accession'=c("Z17427.1","Z17428.1","Z17429.1"),stringsAsFactors=FALSE)) expect_equal(getAccessions(c(),sqlFile),NULL) }) test_that("Test prepareDatabase",{ tmp<-tempfile() tmpDir<-tempfile() dir.create(tmpDir) types<-c('XxXx','XyXyX') taxa<-list(c( "accession\taccession.version\ttaxid\tgi", "Z17427\tZ17427.1\t3702\t16569", "Z17428\tZ17428.1\t3702\t16570" ),c( "accession\taccession.version\ttaxid\tgi", "Z17429\tZ17429.1\t3702\t16571", "Z17430\tZ17430.1\t3702\t16572" )) targets<-sprintf('nucl_%s.accession2taxid.gz',types) mapply(function(xx,yy)writeLines(xx,file.path(tmpDir,yy)),taxa,targets) testFile<-system.file('testdata/fakeNamesNodes.tar.gz',package='taxonomizr') if(.Platform$OS.type == "windows"){ R.utils::gunzip(testFile,remove=FALSE,skip=TRUE) testFile<-system.file('testdata/fakeNamesNodes.tar',package='taxonomizr') } fakeFile<-sprintf('file://%s',testFile) expect_error(prepareDatabase(tmp,tmpDir,url=fakeFile,baseUrl=sprintf('file://%s',tmpDir),types=c('nucl_XxXx','nucl_XyXyX')),NA) db<-RSQLite::dbConnect(RSQLite::SQLite(),tmp) expect_equal(sort(RSQLite::dbListTables(db)),c('accessionTaxa','names','nodes')) expect_equal(colnames(RSQLite::dbGetQuery(db,'SELECT * FROM names LIMIT 1')),c('id','name','scientific')) expect_equal(colnames(RSQLite::dbGetQuery(db,'SELECT * FROM nodes LIMIT 1')),c('id','rank','parent')) expect_equal(colnames(RSQLite::dbGetQuery(db,'SELECT * FROM accessionTaxa LIMIT 1')),c('base','accession','taxa')) expect_message(prepareDatabase(tmp,tmpDir,url=fakeFile,baseUrl=sprintf('file://%s',tmpDir),types=c('nucl_XxXx','nucl_XyXyX')),'exists') expect_message(prepareDatabase(tmp,tmpDir,url='file://NOTAREALFILE',baseUrl='ALSONOTAREALFILE',types=c('NOTREAL','NOTREAL2')),'exists') tmpDir2<-tempfile() expect_error(prepareDatabase(tmp,tmpDir2,url=fakeFile,baseUrl=sprintf('file://%s',tmpDir),types=c('nucl_XxXx','nucl_XyXyX')),NA) RSQLite::dbDisconnect(db) if(.Platform$OS.type == "windows")file.remove('fakeNamesNodes.tar') }) test_that("Test makeNewick",{ expect_equal(makeNewick(matrix('A')),'(A)') expect_equal(makeNewick(matrix('')),'()') expect_equal(makeNewick(matrix(NA),naSub='Missing'),'(Missing)') expect_equal(makeNewick(matrix(LETTERS[1:6],nrow=1)),'((((((F)E)D)C)B)A)') expect_equal(makeNewick(matrix(LETTERS[1:6],ncol=1)),'(A,B,C,D,E,F)') expect_equal(makeNewick(rbind(LETTERS[1:6],LETTERS[1:6])),'((((((F)E)D)C)B)A)') expect_equal(makeNewick(rbind(LETTERS[1:6],LETTERS[1:6],LETTERS[1:6])),'((((((F)E)D)C)B)A)') expect_equal(makeNewick(rbind(LETTERS[1:6],LETTERS[1:6],LETTERS[7:12])),'((((((F)E)D)C)B)A,(((((L)K)J)I)H)G)') expect_equal(makeNewick(matrix(c('A','B','D','A','C','D'),nrow=2,byrow=TRUE)),'(((D)B,(D)C)A)') expect_equal(makeNewick(matrix(c('A',NA,'D','A','C','D'),nrow=2,byrow=TRUE),naSub='_'),'(((D)_,(D)C)A)') expect_equal(makeNewick(matrix(c('A',NA,'D','A',NA,'D'),nrow=2,byrow=TRUE),naSub='_'),'(((D)_)A)') expect_equal(makeNewick(matrix(c('A','B',NA,'A','C',NA),nrow=2,byrow=TRUE),naSub='xx'),'(((xx)B,(xx)C)A)') expect_equal(makeNewick(matrix(c('Abc','B','D','Abc','C','D'),nrow=2,byrow=TRUE)),'(((D)B,(D)C)Abc)') expect_equal(makeNewick(matrix(c('Abc','B','Abc','D','C','D'),nrow=3,byrow=TRUE)),'((B,D)Abc,(D)C)') expect_equal(makeNewick(matrix(c('Abc','D','Abc','B','C','D'),nrow=3,byrow=TRUE)),'((D,B)Abc,(D)C)') })
idle_time <- function(eventlog, level, append, append_column, units, ...) { UseMethod("idle_time") } idle_time.eventlog <- function(eventlog, level = c("log","case","trace","resource"), append = FALSE, append_column = NULL, units = c("days","hours","mins","secs","weeks"), sort = TRUE, ...) { level <- match.arg(level) level <- deprecated_level(level, ...) units <- match.arg(units) if(is.null(append_column)) { append_column <- case_when(level == "case" ~ "idle_time", level == "resource" ~ "idle_time", T ~ "NA") } FUN <- switch(level, log = idle_time_log, case = idle_time_case, trace = idle_time_trace, resource = idle_time_resource) output <- FUN(eventlog = eventlog, units = units) if(sort && level %in% c("case","resource")) { output %>% arrange(-idle_time) -> output } return_metric(eventlog, output, level, append, append_column, "idle_time", 1, empty_label = T) -> t attr(t, "units") <- units t } idle_time.grouped_eventlog <- function(eventlog, level = c("log","case","trace","resource"), append = FALSE, append_column = NULL, units = c("days","hours","mins","secs","weeks"), sort = TRUE, ...) { level <- match.arg(level) level <- deprecated_level(level, ...) units <- match.arg(units) if(is.null(append_column)) { append_column <- case_when(level == "case" ~ "idle_time", level == "resource" ~ "idle_time", T ~ "NA") } FUN <- switch(level, log = idle_time_log, case = idle_time_case, trace = idle_time_trace, resource = idle_time_resource) if(level != "log") { grouped_metric(eventlog, FUN, units) -> output } else { grouped_metric_raw_log(eventlog, FUN, units) -> output } if(sort && level %in% c("case","resource")) { output %>% arrange(-idle_time) -> output } return_metric(eventlog, output, level, append, append_column, "idle_time", 1, empty_label = T) -> t attr(t, "units") <- units t }
expected <- eval(parse(text="c(\"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"0\", NA, \"0\", \"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"1\", \"0\", \"1\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", NA, \"0\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"1\", \"0\", \"0\", \"0\", NA, \"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"0\", \"1\", NA, \"0\", \"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"0\", \"0\", \"0\")")); test(id=0, code={ argv <- eval(parse(text="list(structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, NA, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, NA, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, NA, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, NA, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c(\"0\", \"1\"), class = \"factor\"))")); do.call(`as.character`, argv); }, o=expected);
multiLine_plot <- function (bpstart=0, bpend=1000000000, dList, title=NULL, showmaxlr=3, kcut=NULL, pl='linear' ,ylim=c(-0.5,10),color=c('violet','green','red','blue'),markSNP=NULL,round=2,legend_cex=1) { summaryStats=do.call(rbind,dList[,'SummaryStats']) if (is.null(kcut)){ kcut=dList[,'k_cutoff'][[1]] } kcutCol=which(dList[,'k_cutoff'][[1]]==min(kcut)) dframe_inRange=summaryStats[summaryStats$bp>=bpstart&summaryStats$bp<=bpend,] if (pl=='logit'){ ylim=c(0,10); ylab='Odds Ratio';threshold=1 } else { ylab='Beta';threshold=0 } plot(0,0,main=title,xlab='Location (bp)',ylab=ylab, xlim=range(dframe_inRange$bp),ylim=ylim) abline(h=threshold) skipCol=which(names(dframe_inRange)=='lo_1')-1 for (i in 1:length(kcut)){ signColor=color[length(kcut)-i+1] boundCol=(length(kcut)-i+1)*2+skipCol+c(-1,0) lineColor=c('grey',signColor)[as.numeric(dframe_inRange[,(2*kcutCol-1+skipCol)]>threshold | dframe_inRange[,(2*kcutCol+skipCol)]<threshold)+1] segments(dframe_inRange$bp,dframe_inRange[,boundCol[1]],dframe_inRange$bp,dframe_inRange[,boundCol[2]],col=lineColor) } signAtKcutoff = dframe_inRange[dframe_inRange[,(2*kcutCol-1+skipCol)]>threshold | dframe_inRange[,(2*kcutCol+skipCol)]<threshold,] signAtKcutoff=signAtKcutoff[order(signAtKcutoff$maxlr,decreasing = T),] points(signAtKcutoff$bp,signAtKcutoff$mle,pch='-') num_of_hits = nrow(signAtKcutoff) if (num_of_hits>0 & is.null(markSNP)){ text(signAtKcutoff$bp,signAtKcutoff[,ncol(signAtKcutoff)],signAtKcutoff$SNP,srt=90,pos=4,offset=0.3,cex=0.75) } else if (!is.null(markSNP)) { snpIndex=which(dframe_inRange$SNP %in% markSNP) text(dframe_inRange$bp[snpIndex],dframe_inRange[snpIndex,ncol(dframe_inRange)],dframe_inRange$SNP[snpIndex],srt=90,pos=4,offset=0.3,cex=0.75) } legend_txt=c(paste0('> 1/',kcut[1],' LI'),paste0('1/',kcut,' LI')) if (num_of_hits > 0 & showmaxlr > 0) { if (num_of_hits < showmaxlr) { showmaxlr = num_of_hits } legend.txt2='' for (i in 1:showmaxlr) { hit = paste ("max LR =", round(signAtKcutoff$maxlr[i],round), "at", signAtKcutoff$snp[i], "(", signAtKcutoff$bp[i] ,")") legend.txt2 = c(legend.txt2, hit) } legend("topright",8,legend.txt2,col=par("col"),lty=0,bty="n",cex=legend_cex) } legend("topleft",legend_txt,col=c("grey",color),lty=c(1.5),bty="n",cex=legend_cex) }
context("nn-linear") test_that("nn_linear", { linear <- nn_linear(10, 1) x <- torch_randn(10, 10) y <- linear(x) expect_tensor(y) expect_length(as_array(y), 10) }) test_that("initialization is identical to pytorch", { torch_manual_seed(1) expect_equal( nn_linear(1,1)$weight$item(), 0.5152631998062134 ) })
modelOptimise <- function (model, options, ...) { funcName <- paste(model$type, "Optimise", sep="") if ( exists(funcName, mode="function") ) { func <- get(funcName, mode="function") model <- func(model, options, ...) } else { if ( "optimiser" %in% names(options) ) { funcName <- paste(options$optimiser, "optim", sep="") } else { funcName <- "CGoptim" } optFunc <- get(funcName, mode="function") params <- modelExtractParam(model) newParams <- optFunc(params, modelObjective, modelGradient, options, model) model <- modelExpandParam(model, newParams$xmin) model$llscore <- newParams$objective } return (model) }
data("Reit98") KL <<- Reit98 nVar <<- 9 dMax <<- 2 yDeb <<- etat0 <- c(3.105053, 3.335297, -2.367497, 3.276356, 0.2985118, -2.195064, -35.06073, -20.59253, -18.33939) intgrMthod <<- "rk4" nIterMin <<- 1 tEnd <<- 0.5 timeStep <<- 0.001 printIter <<- 10 lastIter <<- 50
context("criteria") testCriterionL2loss <- function(testset, estset) { sum((testset - mean(estset))^2) } testCriterionL1loss <- function(testset, estset) { sum(abs(testset - mean(estset))) } testCriterionMod <- function(testset, estset) { length(testset) / (length(testset) - 1) * sum((testset[-length(testset)] - mean(estset))^2) } test_that("criterionL2loss is working", { testtestset <- rnorm(43) testestset <- rnorm(34) expect_equal(criterionL2loss(testset = testtestset, estset = testestset), testCriterionL2loss(testset = testtestset, estset = testestset)) expect_equal(criterionL2loss(testset = testtestset, estset = testestset, value = NULL), testCriterionL2loss(testset = testtestset, estset = testestset)) expect_equal(criterionL2loss(testset = testtestset, estset = testestset, test = "s"), testCriterionL2loss(testset = testtestset, estset = testestset)) expect_identical(criterionL2loss(testset = rep(1, 10), estset = 0), 10) expect_identical(criterionL2loss(testset = 1:10, estset = 1:10), sum((1:10 - 5.5)^2)) expect_identical(criterionL2loss(testset = rep(1, 10), estset = rnorm(10), value = 0), 10) expect_identical(criterionL2loss(testset = 1:10, estset = rnorm(10), value = 12.37), sum((1:10 - 12.37)^2)) }) test_that("criterionL1loss is working", { testtestset <- rnorm(43) testestset <- rnorm(34) expect_equal(criterionL1loss(testset = testtestset, estset = testestset), testCriterionL1loss(testset = testtestset, estset = testestset)) expect_equal(criterionL1loss(testset = testtestset, estset = testestset, value = NULL), testCriterionL1loss(testset = testtestset, estset = testestset)) expect_equal(criterionL1loss(testset = testtestset, estset = testestset, test = "s"), testCriterionL1loss(testset = testtestset, estset = testestset)) expect_identical(criterionL1loss(testset = rep(1, 10), estset = 0), 10) expect_identical(criterionL1loss(testset = 1:10, estset = 1:10), sum(abs(1:10 - 5.5))) expect_identical(criterionL1loss(testset = rep(1, 10), estset = rnorm(10), value = 0), 10) expect_identical(criterionL1loss(testset = 1:10, estset = rnorm(10), value = 12.37), sum(abs(1:10 - 12.37))) }) test_that("criterionMod is working", { testtestset <- rnorm(43) testestset <- rnorm(34) expect_identical(criterionMod(testset = testtestset, estset = testestset), testCriterionMod(testset = testtestset, estset = testestset)) expect_identical(criterionMod(testset = 1, estset = 10), NaN) expect_equal(criterionMod(testset = testtestset, estset = testestset, value = NULL), testCriterionMod(testset = testtestset, estset = testestset)) expect_equal(criterionMod(testset = testtestset, estset = testestset, test = "s"), testCriterionMod(testset = testtestset, estset = testestset)) expect_identical(criterionMod(testset = rep(1, 10), estset = 0), 10) expect_identical(criterionMod(testset = 1:10, estset = 1:10), sum(10 / 9 * (1:9 - 5.5)^2)) expect_identical(criterionMod(testset = rep(1, 10), estset = rnorm(10), value = 0), 10) expect_identical(criterionMod(testset = 1:10, estset = rnorm(10), value = 12.37), sum(10 / 9 * (1:9 - 12.37)^2)) })
rsf.main <- function(X, ntree = 1000, method = "mdms", splitrule = "logrank", importance = "random", B = 1000, ci = 90, parallel = FALSE, conf = NULL, verbose = TRUE, seed = NULL) { if (!parallel) { if (is.null(seed)) { digits <- getOption("digits") seed <- runif(n=B, min=1, max=2) * 10^(digits-2) } else { seed <- (0:(B-1)) + seed } rsf.obj <- rsf.main.signif(X=X, ntree=ntree, method=method, splitrule=splitrule, importance=importance, B=B, verbose=verbose, seed=seed) rsf.obs.boot <- rsf.obj$boot.obs rsf.noise.boot <- rsf.obj$boot.noise } else { if (conf$type == "SOCKET") { cl <- parallel::makeCluster(spec=conf$spec, type="PSOCK", homogeneous=conf$homo, outfile=conf$outfile, verbose=conf$verbose) cpus <- length(conf$spec) } else if (conf$type == "MPI") { cl <- parallel::makeCluster(spec=conf$spec, type="MPI", homogeneous=conf$homo, outfile=conf$outfile, verbose=conf$verbose) cpus <- conf$spec } else { stop("Unrecognized cluster type\n") } parallel::clusterSetRNGStream(cl=cl, iseed=seed) parallel::clusterEvalQ(cl=cl, expr=library("randomForestSRC")) parallel::clusterEvalQ(cl=cl, expr=library("survival")) parallel::clusterExport(cl=cl, varlist=c("rsf.main.signif"), envir=.GlobalEnv) rsf.cl <- parallel::clusterCall(cl=cl, fun=rsf.main.signif, X=X, ntree=ntree, method=method, splitrule=splitrule, importance=importance, B=ceiling(B/cpus), verbose=verbose, seed=NULL) parallel::stopCluster(cl) rsf.obs.boot <- matrix(data=NA, nrow=0, ncol=ncol(rsf.cl[[1]]$boot.obs)) rsf.noise.boot <- matrix(data=NA, nrow=0, ncol=ncol(rsf.cl[[1]]$boot.noise)) for (b in 1:cpus) { rsf.obs.boot <- rbind(rsf.obs.boot, rsf.cl[[b]]$boot.obs) rsf.noise.boot <- rbind(rsf.noise.boot, rsf.cl[[b]]$boot.noise) } } theta <- (100-ci)/200 ranks.obs.mean <- apply(X=rsf.obs.boot, MARGIN=2, FUN=mean) ranks.noise.mean <- apply(X=rsf.noise.boot, MARGIN=2, FUN=mean) ranks.obs.se <- apply(X=rsf.obs.boot, MARGIN=2, FUN=sd) ranks.noise.se <- apply(X=rsf.noise.boot, MARGIN=2, FUN=sd) ranks.obs.bpci <- apply(X=rsf.obs.boot, MARGIN=2, FUN=function(x) quantile(x=x, probs=c(theta, 1-theta))) ranks.noise.bpci <- apply(X=rsf.noise.boot, MARGIN=2, FUN=function(x) quantile(x=x, probs=c(theta, 1-theta))) names(ranks.noise.mean) <- gsub(pattern=".noise", replacement="", x=names(ranks.noise.mean), ignore.case=F, fixed=F) w <- pmatch(x=names(ranks.obs.mean), table=names(ranks.noise.mean)) ranks.noise.mean <- ranks.noise.mean[w] ranks.noise.se <- ranks.noise.se[w] ranks.noise.bpci <- ranks.noise.bpci[,w] if (method == "mdms") { mat.ranks <- data.frame("obs.mean"=ranks.obs.mean, "obs.se"=ranks.obs.se, "obs.LBCI"=ranks.obs.bpci[1,], "obs.UBCI"=ranks.obs.bpci[2,], "noise.mean"=ranks.noise.mean, "noise.se"=ranks.noise.se, "noise.LBCI"=ranks.noise.bpci[1,], "noise.UBCI"=ranks.noise.bpci[2,], "signif.1SE"=(ranks.obs.mean + ranks.obs.se < ranks.noise.mean), "signif.CI"=(ranks.obs.bpci[2,] < ranks.noise.bpci[1,])) ord <- order(mat.ranks[,"obs.mean"], decreasing=F) } else { stop("Unmatched method \n") } mat.ranks <- mat.ranks[ord,] return(mat.ranks) } rsf.int <- function(X, ntree = 1000, method = "imdms", splitrule = "logrank", importance = "random", B = 1000, ci = 90, parallel = FALSE, conf = NULL, verbose = TRUE, seed = NULL) { p <- ncol(X) - 2 if (!parallel) { if (is.null(seed)) { digits <- getOption("digits") seed <- runif(n=B, min=1, max=2) * 10^(digits-2) } else { seed <- (0:(B-1)) + seed } rsf.obj <- rsf.int.signif(X=X, ntree=ntree, method=method, splitrule=splitrule, importance=importance, B=B, verbose=verbose, seed=seed) rsf.obs.boot <- rsf.obj$boot.obs rsf.noise.boot <- rsf.obj$boot.noise } else { if (conf$type == "SOCKET") { cl <- parallel::makeCluster(spec=conf$spec, type="PSOCK", homogeneous=conf$homo, outfile=conf$outfile, verbose=conf$verbose) cpus <- length(conf$spec) } else if (conf$type == "MPI") { cl <- parallel::makeCluster(spec=conf$spec, type="MPI", homogeneous=conf$homo, outfile=conf$outfile, verbose=conf$verbose) cpus <- conf$spec } else { stop("Unrecognized cluster type\n") } parallel::clusterSetRNGStream(cl=cl, iseed=seed) parallel::clusterEvalQ(cl=cl, expr=library("randomForestSRC")) parallel::clusterEvalQ(cl=cl, expr=library("survival")) parallel::clusterExport(cl=cl, varlist=c("rsf.int.signif"), envir=.GlobalEnv) rsf.cl <- parallel::clusterCall(cl=cl, fun=rsf.int.signif, X=X, ntree=ntree, method=method, splitrule=splitrule, importance=importance, B=ceiling(B/cpus), verbose=verbose, seed=NULL) parallel::stopCluster(cl) if (method == "imdms") { rsf.obs.boot <- array(data=NA, dim=c(dim(rsf.cl[[1]]$boot.obs)[1], dim(rsf.cl[[1]]$boot.obs)[2], 0)) rsf.noise.boot <- array(data=NA, dim=c(dim(rsf.cl[[1]]$boot.noise)[1], dim(rsf.cl[[1]]$boot.noise)[2], 0)) for (b in 1:cpus) { rsf.obs.boot <- abind::abind(rsf.obs.boot, rsf.cl[[b]]$boot.obs) rsf.noise.boot <- abind::abind(rsf.noise.boot, rsf.cl[[b]]$boot.noise) } } else { stop("Unmatched method \n") } } theta <- (100-ci)/200 if (method == "imdms") { int.obs.mean <- apply(X=rsf.obs.boot, MARGIN=1:2, FUN=mean) int.noise.mean <- apply(X=rsf.noise.boot, MARGIN=1:2, FUN=mean) int.obs.se <- apply(X=rsf.obs.boot, MARGIN=1:2, FUN=sd) int.noise.se <- apply(X=rsf.noise.boot, MARGIN=1:2, FUN=sd) int.obs.bpci <- apply(X=rsf.obs.boot, MARGIN=1:2, FUN=function(x) quantile(x=x, probs=c(theta, 1-theta))) int.noise.bpci <- apply(X=rsf.noise.boot, MARGIN=1:2, FUN=function(x) quantile(x=x, probs=c(theta, 1-theta))) int.obs.bpci <- aperm(a=int.obs.bpci, perm=c(2,3,1)) int.noise.bpci <- aperm(a=int.noise.bpci, perm=c(2,3,1)) vo.mean <- numeric(choose(n=p, k=2)) vn.mean <- numeric(choose(n=p, k=2)) vo.se <- numeric(choose(n=p, k=2)) vn.se <- numeric(choose(n=p, k=2)) mo.bpci <- matrix(data=NA, nrow=4, ncol=choose(n=p, k=2)) mn.bpci <- matrix(data=NA, nrow=4, ncol=choose(n=p, k=2)) k <- 1 for (i in 2:p) { for (j in 1:(i-1)) { vmean <- c(int.obs.mean[i,j], int.obs.mean[j,i]) vse <- c(int.obs.se[i,j], int.obs.se[j,i]) mbpci <- cbind(int.obs.bpci[i,j,], int.obs.bpci[j,i,]) vo.mean[k] <- vmean[which.min(vmean)] vo.se[k] <- vse[which.min(vmean)] mo.bpci[,k] <- mbpci[,which.min(vmean)] names(vo.mean)[k] <- paste(colnames(int.obs.mean)[j], rownames(int.obs.mean)[i], sep=":") vmean <- c(int.noise.mean[i,j], int.noise.mean[j,i]) vse <- c(int.noise.se[i,j], int.noise.se[j,i]) mbpci <- cbind(int.noise.bpci[i,j,], int.noise.bpci[j,i,]) vn.mean[k] <- vmean[which.min(vmean)] vn.se[k] <- vse[which.min(vmean)] mn.bpci[,k] <- mbpci[,which.min(vmean)] names(vn.mean)[k] <- paste(colnames(int.noise.mean)[j], rownames(int.noise.mean)[i], sep=":") k <- k+1 } } mat.int <- data.frame("obs.mean"=vo.mean, "obs.se"=vo.se, "obs.LBCI"=mo.bpci[1,], "obs.UBCI"=mo.bpci[2,], "noise.mean"=vn.mean, "noise.se"=vn.se, "noise.LBCI"=mn.bpci[1,], "noise.UBCI"=mn.bpci[2,], "signif.1SE"=(vo.mean + vo.se < vn.mean), "signif.CI"=(mo.bpci[2,] < mn.bpci[1,])) ord <- order(mat.int[,"obs.mean"], decreasing=F) } else { stop("Unmatched method \n") } mat.int <- mat.int[ord,] return(mat.int) } cph.main <- function (X, main.term) { p <- ncol(X) - 2 fmla.main <- as.formula(paste("survival::Surv(time=", colnames(X)[1], ", event=", colnames(X)[2], ", type=\"right\") ~ .", sep="")) P.cph.main <- numeric(p) names(P.cph.main) <- main.term for (j in 1:p) { Z <- X[,c(colnames(X)[1], colnames(X)[2], main.term[j])] coxfit <- tryCatch({survival::coxph(fmla.main, data=Z, model=T, x=T, y=T)}, error=function(w){NULL}, warning=function(w){NULL}) if (is.null(coxfit)) { P.cph.main[j] <- NA } else { P.cph.main[j] <- summary(coxfit)$coefficients[1,"Pr(>|z|)",drop=T] } } P.cph.bh.main <- P.cph.main nna <- !is.na(P.cph.main) P.cph.bh.main[nna] <- p.adjust(p=P.cph.main[nna], method="BH") P.cph.bh.main[!nna] <- NA return(list("raw"=P.cph.main, "fdr"=P.cph.bh.main)) } cph.int <- function (X, int.term) { p <- ncol(X) - 2 int.term.list <- strsplit(x=int.term, split=":") fmla.int <- as.formula(paste("survival::Surv(time=", colnames(X)[1], ", event=", colnames(X)[2], ", type=\"right\") ~ . + (.)^2", sep="")) P.cph.int <- numeric(p*(p-1)/2) names(P.cph.int) <- int.term for (j in 1:(p*(p-1)/2)) { Z <- X[,c(colnames(X)[1], colnames(X)[2], int.term.list[[j]])] coxfit <- tryCatch({survival::coxph(fmla.int, data=Z, model=T, x=T, y=T)}, error=function(w){NULL}, warning=function(w){NULL}) if (is.null(coxfit)) { P.cph.int[j] <- NA } else { P.cph.int[j] <- summary(coxfit)$coefficients[3,"Pr(>|z|)",drop=T] } } P.cph.bh.int <- P.cph.int nna <- !is.na(P.cph.int) P.cph.bh.int[nna] <- p.adjust(p=P.cph.int[nna], method="BH") P.cph.bh.int[!nna] <- NA return(list("raw"=P.cph.int, "fdr"=P.cph.bh.int)) } IRSF.news <- function(...) { newsfile <- file.path(system.file(package="IRSF"), "NEWS") file.show(newsfile) }
bayesCaret <- list( type = c("Classification", "Regression"), library = c(), parameters = data.frame( parameter = c( "shiftAmount", "retainMinValues", "doEcdf", "online", "mode", "numBuckets", "sampleFromAllBuckets", "regressor" ), class = c( "numeric", "integer", "boolean", "integer", "character", "integer", "boolean", "function" ), label = c( "shiftAmount", "retainMinValues", "doEcdf", "online", "mode", "numBuckets", "sampleFromAllBuckets", "regressor" ) ), prob = NULL ) bayesCaret$grid <- function(x = NULL, y = NULL, len = NULL, search = "grid") { if (missing(y)) { warning("y is missing; assuming you want to do regression then?") } isClassification <- (is.character(y) || is.factor(y)) numTrain <- NULL cOnline <- c(0) if (!missing(x)) { numTrain <- if (is.data.frame(x)) nrow(x) else length(x) cOnline <- c(cOnline, round(1.2 * numTrain)) } else if (!missing(y)) { numTrain <- if (is.data.frame(y)) nrow(y) else length(y) cOnline <- c(cOnline, round(1.2 * numTrain)) } modes <- c("full", "simple") if (isClassification) { modes <- c(modes, "naive") } gridList <- list( shiftAmount = c(0, 0.1), doEcdf = c(TRUE, FALSE), online = sort(c(cOnline, .Machine$integer.max)), mode = modes, regressor = NA ) rmv <- NULL rmvMin <- if (isClassification) 1 else 2 if (!is.null(numTrain)) { rmv <- c(max(rmvMin, ceiling(numTrain * 0.01)), max(rmvMin, ceiling(numTrain * 0.05))) } if (isClassification) { rmv <- c(rmv, 0, 1, 2, 11) gridList[["numBuckets"]] <- NA gridList[["sampleFromAllBuckets"]] <- FALSE } else { rmv <- c(rmv, 2, 11) gridList[["numBuckets"]] <- c(5, 10, NA) gridList[["sampleFromAllBuckets"]] <- c(TRUE, FALSE) } gridList[["retainMinValues"]] <- sort(unique(rmv)) return(expand.grid(gridList)) } bayesCaret$fit <- function(x, y, wts, param, lev, last, weights, classProbs, ...) { args <- list(...) m <- args[["messages"]] w <- args[["warnings"]] p <- args[["parallel"]] if (!is.null(m)) { mmb::setMessages(is.logical(m) && m) } if (!is.null(w)) { mmb::setWarnings(is.logical(w) && w) } theData <- data.frame(x) theData$y <- y return(list( train = theData, labelCol = "y", param = param, parallel = if (is.logical(p)) p else !foreach::getDoParRegistered() )) } bayesCaret$predict <- function(modelFit, newdata, submodels) { classify <- modelFit$problemType == "Classification" theFunc <- if (classify) mmb::bayesProbabilityAssign else mmb::bayesRegressAssign default_classification <- list( shiftAmount = 0.1, retainMinValues = 1, doEcdf = FALSE, online = 0, simple = FALSE, naive = FALSE ) default_regression <- list( shiftAmount = 0.1, retainMinValues = 2, doEcdf = FALSE, online = 0, simple = FALSE, numBuckets = ceiling(log2(nrow(modelFit$train))), sampleFromAllBuckets = TRUE, regressor = NA ) dfParams <- if (classify) default_classification else default_regression dfTune <- modelFit$tuneValue dfTune$simple <- dfTune$mode == "simple" dfTune$naive <- dfTune$mode == "naive" dfTune$mode <- NULL for (n in names(dfParams)) { if (n %in% colnames(dfTune)) { dfParams[[n]] <- dfTune[[n]] } } dfParams[["dfTrain"]] <- modelFit$train dfParams[["dfValid"]] <- data.frame(newdata) dfParams[["targetCol"]] <- modelFit$labelCol dfParams[["useParallel"]] <- modelFit$parallel return(do.call(theFunc, dfParams)) }
heart <- structure(list(id = 1:103, status = c(0, 0, 1, 1, 0, 0, 2, 0, 0, 2, 1, 0, 2, 2, 0, 2, 0, 1, 0, 2, 2, 2, 2, 2, 0, -1, 0, 1, 0, 2, 0, 2, 0, 0, 0, 2, 2, 1, 0, 0, 0, 0, 0, 0, 1, 2, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 2, 0, 2, 0, 0, 0, 1, 2, 0, 1, 2, 0, 2, 0, 0, 2, 1, 0, 0, 0, 0, 2, 0, 0, -1, 1, 2, 0, 0, 2, 0, 2, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, -1, -1, 0), ftime = c(NA, NA, 15, 3, NA, NA, 624, NA, NA, 46, 127, NA, 64, 1350, NA, 280, NA, 23, NA, 10, 1024, 39, 730, 136, 1775, NA, NA, 1, NA, 836, NA, 60, 1536, 1549, NA, 54, 47, 0, 51, 1367, 1264, NA, NA, NA, 44, 994, 51, NA, 1106, 897, 253, NA, 147, NA, 51, 875, NA, 322, 838, 65, NA, NA, 815, 551, 66, NA, 228, 65, 660, 25, 589, 592, 63, 12, NA, 499, NA, 305, 29, 456, 439, NA, 48, 297, NA, 389, 50, 339, 68, 26, NA, 30, 237, 161, 14, 167, 110, 13, NA, 1, NA, NA, NA), age = c(NA, NA, 19832, 14741, NA, NA, 18630, NA, NA, 15535, 17550, NA, 19949, 19764, NA, 18088, NA, 20783, NA, 20208, 15838, 15638, 21317, 19002, 12159, NA, NA, 19802, NA, 16419, NA, 23541, 17912, 14834, NA, 17915, 22481, 15151, 18453, 17748, 16604, NA, NA, NA, 13216, 17756, 17223, NA, 13423, 16842, 17831, NA, 17332, NA, 19168, 14217, NA, 17558, 15192, 17919, NA, NA, 11955, 17862, 18746, NA, 7197, 16526, 17537, 19363, 17346, 9765, 20601, 10657, NA, 19069, NA, 17998, 19710, 16989, 19324, NA, 19502, 15639, NA, 17875, 16953, 19886, 18783, 19164, NA, 16739, 17468, 16016, 14714, 9746, 8646, 10552, NA, 12843, NA, NA, NA), mismat = c(NA, NA, 1.11, 1.66, NA, NA, 1.32, NA, NA, 0.61, 0.36, NA, 1.89, 0.87, NA, 1.12, NA, 2.05, NA, 2.76, 1.13, 1.38, 0.96, 1.62, 1.06, NA, NA, 0.47, NA, 1.58, NA, 0.69, 0.91, 0.38, NA, 2.09, 0.87, 0.87, NA, 0.75, 0.98, NA, NA, NA, 0, 0.81, 1.38, NA, 1.35, NA, 1.08, NA, NA, NA, 1.51, 0.98, NA, 1.82, 0.19, 0.66, NA, NA, 1.93, 0.12, 1.12, NA, 1.02, 1.68, 1.2, 1.68, 0.97, 1.46, 2.16, 0.61, NA, 1.7, NA, 0.81, 1.08, 1.41, 1.94, NA, 3.05, 0.6, NA, 1.44, 2.25, 0.68, 1.33, 0.82, NA, 0.16, 0.33, 1.2, NA, 0.46, 1.78, 0.77, NA, 0.67, NA, NA, NA)), .Names = c("id", "status", "ftime", "age", "mismat"), class = "data.frame", row.names = c(NA, -103)) heart2 <- na.omit(heart) heart2 <- transform(heart2,age.std=scale(age),mismat.std=scale(mismat)) require(moc) pgompertz <- function(x,la,ka) {1-exp(-la*(exp(ka*x)-1)/ka)} dgompertz <- function(x,la,ka) {(exp(-la * (exp(ka * x) - 1)/ka) * la * exp(ka * x) )} qgompertz <- function(prob,la,ka) {log(1-ka*log(1-prob)/la)/ka} gompertz.mean <- function(la,ka) integrate(function(x) x*dgompertz(x,la,ka),0,Inf)$value Gompertz.Surv <- function(x,la,ka,cens) { (x[,2]==0)*(1-pgompertz(x[,1],la[,1],ka[,1]))*cens[,2]+ (x[,2]<0)*pgompertz(x[,1],la[,1],ka[,1])*cens[,2]+ (x[,2]>0)*dgompertz(x[,1],la[,1],ka[,1])*cens[,2] } la.heart <- list(G1=function(p) {cbind(exp(p[1]+p[2]*heart2$age.std),0)}, G2=function(p) {cbind(exp(p[3]+p[4]*heart2$age.std),0)}) attr(la.heart,"parameters") <- c("lambda_1","age_1","lambda_2","age_2") ka.heart <- list(G1=function(p) {cbind(p[1],0)}, G2=function(p) {cbind(p[2],0)}) attr(ka.heart,"parameters") <- c("kappa_1","kappa_2") cens.heart <- list(G1=function(p) {cbind(0,c(1,1,0)[heart2$status+1])}, G2=function(p) {cbind(0,c(1,0,1)[heart2$status+1])}) mix.heart <- function(p) {t(apply(cbind(p[1]+p[2]*heart2$mismat.std+p[3]*heart2$age.std),1,inv.glogit))} attr(mix.heart,"parameters") <- c("Cons","mismatch","age") heart.expected2 <- list( G1=function(p) {cbind(qgompertz(0.5,la.heart[[1]](p[1:4])[,1], ka.heart[[1]](p[5:6])[,1]),1)}, G2=function(p) {cbind(qgompertz(0.5,la.heart[[2]](p[1:4])[,1], ka.heart[[2]](p[5:6])[,1]),2)} ) heart.moc <- moc(heart2[,c("ftime","status")],density=Gompertz.Surv,joint=TRUE,groups=2, gmu=la.heart,gshape=ka.heart,gextra=cens.heart,gmixture=mix.heart, pgmu=c(-6,1,-4,0.3),pgshape=c(-0.0015,-0.0055),pgmix=c(1.4,0.4,0.2), gradtol=1e-6,iterlim=200) heart.moc cens.heart2 <- list(G1=function(p) {p1 <- inv.glogit(p[1]); cbind(0,c(1,p1)[heart2$status+1])}, G2=function(p) {p2 <- inv.glogit(p[2]); cbind(0,c(1,p2)[heart2$status+1])}) attr(cens.surv2,"parameters") <- c("OR_1","OR_2") heart.moc2 <- moc(heart2[,c("ftime","status")],density=Gompertz.Surv,joint=TRUE,groups=2, gmu=la.heart,gshape=ka.heart,gextra=cens.heart2,gmixture=mix.heart, pgmu=heart.moc$coef[1:4],pgshape=heart.moc$coef[5:6],pgmix=heart.moc$coef[7:9],pgextra=c(0,0), gradtol=1e-5,iterlim=200) heart.moc2 Weibull.Surv <- function(x,la,ka,cens) { (x[,2]==0)*(1-pweibull(x[,1],shape=la[,1],scale=ka[,1]))*cens[,2]+ (x[,2]<0)*pweibull(x[,1],shape=la[,1],scale=ka[,1])*cens[,2]+ (x[,2]>0)*dweibull(x[,1],shape=la[,1],scale=ka[,1])*cens[,2] } weibull.mean <- function(a,b) {b*gamma(1+1/a)} ka.wb.heart <- list(G1=function(p) {cbind(exp(p[1]+p[2]*heart2$age.std),0)}, G2=function(p) {cbind(exp(p[3]+p[4]*heart2$age.std),0)}) attr(ka.wb.heart,"parameters") <- c("log.beta_1","age_1","log.beta_2","age_2") la.wb.heart <- list(G1=function(p) {cbind(exp(p[1]),0)}, G2=function(p) {cbind(exp(p[2]),0)}) attr(la.wb.heart,"parameters") <- c("log.alpha_1","log.alpha_2") expected.wb.heart <- list( G1=function(p) {cbind(weibull.mean(la.wb.heart[[1]](p[1:2])[,1], ka.wb.heart[[1]](p[3:6])[,1]), heart2$status)}, G2=function(p) {cbind(weibull.mean(la.wb.heart[[2]](p[1:2])[,1], ka.wb.heart[[2]](p[3:6])[,1]), heart2$status)} ) heart2.tmp <- heart2 heart2.tmp$ftime[which(heart2.tmp$ftime==0)] <- 0.1 heart.moc.wb <- moc(heart2.tmp[,c("ftime","status")],density=Weibull.Surv,joint=TRUE,groups=2, gmu=la.wb.heart,gshape=ka.wb.heart,gextra=cens.heart2,gmixture=mix.heart, expected=expected.wb.heart,pgmu=c(-1,1),pgshape=c(6,0,8,0),pgmix=c(0,0,0),pgextra=c(0,0), gradtol=1e-6,iterlim=200) heart.moc.wb
linfinity_depth <- function(dt){ if (is.data.frame(dt)) { dt <- as.matrix(dt) } if (!is.array(dt) || !is.numeric(dt)) stop("Argument \"dt\" must be a numeric matrix or dataframe.") if (any(!is.finite(dt))) { stop("Missing or infinite values are not allowed in argument \"dt\"") } distances <- as.matrix(dist(dt, method = "maximum", diag = T, upper = T)) unname(1/(1+colMeans(distances))) }
call_sig_reg <- function(res, nr, threshold = 3.5, win = 10) { if(class(res)!="sharpr2") { stop('The first argument must be an object obtained from sharpr2.') } re <- res$score[[nr]] sig_reg <- which(re$est_a - threshold*sqrt(re$var_nb) > 0) sig_reg_l <- length(sig_reg) if(sig_reg_l>1) { keep <- rep(TRUE, sig_reg_l) p <- 1 count <- 1 for(cum in 2:sig_reg_l) { if(sig_reg[cum]==(sig_reg[cum-1]+1)) { count <- count + 1 if(cum==sig_reg_l) { if(count<=win) { keep[p:cum] <- FALSE } } }else{ if(count<=win) { keep[p:(cum-1)] <- FALSE } count <- 1 p <- cum } } sig_reg <- sig_reg[keep] if(length(sig_reg)<=win) { sig_reg <- NA } }else{ sig_reg <- NA } motif <- NA if(!is.na(sig_reg[1])) { max_mean <- c() for(bp in 1:length(sig_reg)) { max_mean <- c(max_mean,mean(re$est_a[max(1,sig_reg[bp]-10):min(sig_reg[bp]+10,length(re$est_a)),1])) } max_bp <- which(max_mean==max(max_mean)) max_bp <- max_bp[ceiling(length(max_bp)/2)] o_start <- as.numeric(strsplit(as.character(res$region[[nr]]),'-')[[1]][1]) motif <- c(o_start + sig_reg[max_bp] - 1 -10, o_start + sig_reg[max_bp] -1 +10) sig_reg <- sig_reg + o_start - 1 } res <- list(sig_reg=sig_reg, motif=motif) return(res) }
test_that("normal deviance equals MSE", { y <- c(0, 2) pred <- c(1, 1) expect_equal(mse(y, pred), deviance_normal(y, pred)) }) test_that("Poisson deviance only accepts positive predictions", { y <- 0:3 pred <- y + 0.1 pred_bad <- y expect_silent(deviance_poisson(y, pred)) expect_error(deviance_poisson(y, pred_bad)) }) test_that("Poisson deviance only accepts non-negative actual values", { y <- 0:3 pred <- y + 0.1 y_bad <- y - 0.01 expect_silent(deviance_poisson(y, pred)) expect_error(deviance_poisson(y_bad, pred)) }) test_that("Gamma deviance only accepts positive predictions", { y <- 1:4 pred <- y + 0.1 pred_bad <- y - 1 expect_silent(deviance_gamma(y, pred)) expect_error(deviance_gamma(y, pred_bad)) }) test_that("Gamma deviance only accepts positive actual values", { y <- 1:4 pred <- y + 0.1 y_bad <- y - 1 expect_silent(deviance_gamma(y, pred)) expect_error(deviance_gamma(y_bad, pred)) }) test_that("Poisson deviance is 0 if actual = predicted", { y <- 1:2 pred <- y expect_equal(deviance_poisson(y, pred), 0) }) test_that("Poisson deviance is 2 * pred for actual 0", { y <- 0 pred <- 0.5 expect_equal(deviance_poisson(y, pred), 2 * pred) }) test_that("Gamma deviance is 0 if actual = predicted", { y <- 1:2 pred <- y expect_equal(deviance_gamma(y, pred), 0) }) test_that("Gamma deviance is 2 * (1 - log(2)) if predicted = actual / 2", { y <- 2 pred <- y / 2 expect_equal(deviance_gamma(y, pred), 2 * (1 - log(2))) }) test_that("normal deviance is Tweedie 0", { y <- 1:3 pred <- y + 0.1 w <- 1:3 expect_equal(deviance_normal(y, pred, w), deviance_tweedie(y, pred, w, tweedie_p = 0)) }) test_that("Poisson deviance is Tweedie 1", { y <- 1:3 pred <- y + 0.1 w <- 1:3 expect_equal(deviance_poisson(y, pred, w), deviance_tweedie(y, pred, w, tweedie_p = 1)) }) test_that("Gamma deviance is Tweedie 2", { y <- 1:3 pred <- y + 0.1 w <- 1:3 expect_equal(deviance_gamma(y, pred, w), deviance_tweedie(y, pred, w, tweedie_p = 2)) }) test_that("Tweedie deviance 0.5 gives error", { y <- 1:3 pred <- y + 0.1 w <- 1:3 expect_error(deviance_tweedie(y, pred, w, tweedie_p = 0.5)) }) test_that("deviance with weight 1 gives same as unweighted", { y <- c(0.1, 0.2, 1, 2) pred <- y + 0.1 w <- rep(1, length(y)) expect_equal(deviance_poisson(y, pred, w), deviance_poisson(y, pred)) expect_equal(deviance_gamma(y, pred, w), deviance_gamma(y, pred)) expect_equal(deviance_normal(y, pred, w), deviance_normal(y, pred)) expect_equal(deviance_tweedie(y, pred, w, tweedie_p = 1.5), deviance_tweedie(y, pred, tweedie_p = 1.5)) }) test_that("deviance with weight 2 gives same as weight 1", { y <- c(0.1, 0.2, 1, 2) pred <- y + 0.1 w1 <- rep(1, length(y)) w2 <- rep(2, length(y)) expect_equal(deviance_poisson(y, pred, w1), deviance_poisson(y, pred, w2)) expect_equal(deviance_gamma(y, pred, w1), deviance_gamma(y, pred, w2)) expect_equal(deviance_normal(y, pred, w1), deviance_normal(y, pred, w2)) expect_equal(deviance_tweedie(y, pred, w = w1, tweedie_p = 1.5), deviance_tweedie(y, pred, w = w2, tweedie_p = 1.5)) }) test_that("deviance with varying weights is different from unweighted", { y <- c(0.1, 0.2, 1, 2) pred <- y + 0.1 w <- 1:4 expect_false(deviance_poisson(y, pred, w) == deviance_poisson(y, pred)) expect_false(deviance_gamma(y, pred, w) == deviance_gamma(y, pred)) expect_false(deviance_normal(y, pred, w) == deviance_normal(y, pred)) expect_false(deviance_tweedie(y, pred, w, tweedie_p = 1.5) == deviance_tweedie(y, pred, tweedie_p = 1.5)) })
Rowz2Keep<-function(Ldat, EQ, G1, RESMAX) { keep1 = !is.na(G1$TT) if(all(RESMAX>0)) { residp = Ldat$sec - EQ$t - G1$TT aresidp = abs(residp) okayP = Ldat$phase=="P" & aresidp<RESMAX[1] okayS = Ldat$phase=="S" & aresidp<RESMAX[2] keep = keep1 & (okayP | okayS ) keepind=which(keep) if(length( keepind )<4) { k1 = order(aresidp, decreasing = TRUE) keepind = k1[1:4] } } else { keepind=which(keep1) } return(keepind) }
as_prediction.PredictionDataSurv = function(x, check = TRUE, ...) { invoke(PredictionSurv$new, check = check, .args = x) } check_prediction_data.PredictionDataSurv = function(pdata) { n = length(assert_row_ids(pdata$row_id)) assert_surv(pdata$truth, "Surv", len = n, any.missing = TRUE, null.ok = TRUE) assert_numeric(pdata$crank, len = n, any.missing = FALSE, null.ok = FALSE) assert_numeric(pdata$response, len = n, any.missing = FALSE, null.ok = TRUE) assert_numeric(pdata$lp, len = n, any.missing = FALSE, null.ok = TRUE) if (inherits(pdata$distr, "VectorDistribution")) { assert(nrow(pdata$distr$modelTable) == n) } else { assert_matrix(pdata$distr, nrows = n, any.missing = FALSE, null.ok = TRUE) } pdata } is_missing_prediction_data.PredictionDataSurv = function(pdata) { miss = logical(length(pdata$row_id)) if (!is.null(pdata$crank)) { miss = is.na(pdata$crank) } if (!is.null(pdata$lp)) { miss = miss | is.na(pdata$lp) } if (!is.null(pdata$response)) { miss = miss | is.na(pdata$response) } pdata$row_ids[miss] } c.PredictionDataSurv = function(..., keep_duplicates = TRUE) { dots = list(...) assert_list(dots, "PredictionDataSurv") assert_flag(keep_duplicates) if (length(dots) == 1L) { return(dots[[1L]]) } predict_types = names(mlr_reflections$learner_predict_types$surv) predict_types = map(dots, function(x) intersect(names(x), predict_types)) if (!every(predict_types[-1L], setequal, y = predict_types[[1L]])) { stopf("Cannot combine predictions: Different predict types") } predict_types = predict_types[[1L]] row_ids = do.call(c, map(dots, "row_ids")) ii = if (keep_duplicates) seq_along(row_ids) else which(!duplicated(row_ids, fromLast = TRUE)) elems = c("truth", intersect(c("crank", "lp", "response"), predict_types)) result = named_list(elems) result$row_ids = row_ids[ii] for (elem in elems) { result[[elem]] = do.call(c, map(dots, elem))[ii] } if ("distr" %in% predict_types) { if (inherits(dots[[1]]$distr, "VectorDistribution")) { result$distr = do.call(c, map(dots, "distr")) } else { result$distr = tryCatch( do.call(rbind, map(dots, "distr")), error = function(e) { do.call(c, map(dots, function(x) { as.Distribution(1 - x$distr, "cdf", decorators = c("CoreStatistics", "ExoticStatistics")) })) } ) } } set_class(result, "PredictionDataSurv") } filter_prediction_data.PredictionDataSurv = function(pdata, row_ids) { keep = pdata$row_ids %in% row_ids pdata$row_ids = pdata$row_ids[keep] pdata$truth = pdata$truth[keep] if (!is.null(pdata$crank)) { pdata$crank = pdata$crank[keep] } if (!is.null(pdata$lp)) { pdata$lp = pdata$lp[keep] } if (!is.null(pdata$distr)) { pdata$distr = pdata$distr[keep,, drop = FALSE] } pdata }
apply_thr <- function (r, thr) { stopifnot(class(r) == "RasterLayer" ) if (any(class(thr) == "numeric", class(thr) == "integer")) { stopifnot(length(thr) == 1) tmp <- values(r) if (thr < min(tmp, na.rm = TRUE)) stop("\"thr\" should be greater than or equal to minimum layer value") if (thr >= max(tmp, na.rm = TRUE)) stop("\"thr\" should be lower than maximum layer value") } else { if (class(thr) != "RasterLayer") stop(paste("\"thr\" class should be \"numeric\",", "\"integer\", or \"RasterLayer\"")) } r > thr }
sigmoid.x <- function(x, y0, y1, xmid, r) y0 + (y1 - y0)/(1 + exp(r * (xmid - x))) sigmoid2.x <- function(x, y0, y1, xmid, r) y0 + (y1 - y0)/(1 + exp(4 * r * (xmid - x) / (y1 - y0))) constant.x <- function(x, c) rep(c, length(x)) noroptimal.x <- function(x, y0, y1, xmid, s2) y0 + (y1-y0)*exp(-(x - xmid)^2/(2 * s2)) make.linear.x <- function(x0, x1) { if ( is.null(x1) ) { function(x, c, m) { x1 <- length(x) - x0 + 1 x[seq_len(x0)] <- x[x0] x[x1:length(x)] <- x[x1] ans <- m * x + c ans[ans < 0] <- 0 ans } } else { function(x, c, m) { x[x < x0] <- x0 x[x > x1] <- x1 ans <- m * x + c ans[ans < 0] <- 0 ans } } } stepf.x <- function(x, y0, y1, xmid) ifelse(x < xmid, y0, y1) normalise <- function(x) x / sum(x) starting.point.quasse <- function(tree, states, states.sd=NULL) { p.bd <- starting.point.bd(tree) lik.bm <- make.bm(tree, states, states.sd, control=list(method="pruning", backend="C")) c(p.bd, diffusion=as.numeric(stats::coef(find.mle(lik.bm, .1)))) } load.wisdom <- function(file="wisdom") { w <- paste(readLines(file), collapse="\n") .Call(r_set_wisdom, w) } save.wisdom <- function(file="wisdom") { w <- .Call(r_get_wisdom) write(w, file) } check.f.quasse <- function(f) { args <- names(formals(f)) if ( args[1] != "x" ) stop("First argument of speciation/extinction function must be x") length(args) - 1 } check.states.quasse <- function(tree, states, states.sd) { states <- check.states(tree, states, as.integer=FALSE) if ( length(states.sd) == 1 ) states.sd <- structure(rep(states.sd, length(states)), names=names(states)) else states.sd <- check.states(tree, states.sd, as.integer=FALSE) list(states=states, states.sd=states.sd) } check.control.quasse <- function(control, tree, states) { tree.length <- max(branching.times(tree)) xr <- diff(range(states)) xr.mult <- if ( "xr.mult" %in% names(control) ) control$xr.mult else 5 defaults <- list(tc=tree.length/10, dt.max=tree.length/1000, nx=1024, dx=xr * xr.mult / 1024, r=4, xmid=mean(range(states)), w=5, method="fftC", tips.combined=FALSE, flags=FFTW.MEASURE, atol=1e-6, rtol=1e-6, eps=1e-6, verbose=FALSE) nx.changed <- "nx" %in% names(control) dx.changed <- "dx" %in% names(control) control <- if ( is.null(control) ) defaults else modifyList(defaults, control) if ( dx.changed && !nx.changed ) control$nx <- 2^ceiling(log2(xr * xr.mult / control$dx)) else if ( nx.changed && !dx.changed ) control$dx <- xr * xr.mult / control$nx method <- match.arg(control$method, c("fftC", "fftR", "mol")) if ( control$tips.combined && method != "fftC" ) stop("'tips.combined' can only be used with method 'fftC'") if ( control$tc <= 0 || control$tc >= tree.length ) stop(sprintf("tc must lie in (0, %2.2f)", tree.length)) if ( log2(control$nx) %% 1 != 0 ) stop("nx must be a power of two") if ( log2(control$r) %% 1 != 0 ) stop("r must be a power of two") rr <- with(control, xmid + c(-1,1) * dx * nx / 2) rmin <- min(c(1, -1) * (mean(range(states)) - rr) / (xr / 2)) if ( rmin - xr.mult < -1e-5 ) warning("Range does not look wide enough - be careful!") else if ( rmin < 2 ) stop("Range is not wide enough") ctrl.int <- c("nx", "flags", "verbose") ctrl.num <- c("tc", "dt.max", "r", "xmid", "w", "atol", "rtol") control[ctrl.int] <- sapply(control[ctrl.int], as.integer) control[ctrl.num] <- sapply(control[ctrl.num], as.numeric) control } expand.pars.quasse <- function(lambda, mu, args, ext, pars) { pars.use <- vector("list", 2) for ( i in c(1,2) ) { x <- list() pars.use[[i]] <- list(x=ext$x[[i]], lambda=do.call(lambda, c(ext$x[i], pars[args$lambda])), mu=do.call(mu, c(ext$x[i], pars[args$mu])), drift=pars[args$drift], diffusion=pars[args$diffusion], padding=ext$padding[i,], ndat=ext$ndat[i], nx=ext$nx[i]) } names(pars.use) <- c("hi", "lo") pars.use$tr <- ext$tr pars.use } make.pars.quasse <- function(cache) { args <- cache$args function(pars) { names(pars) <- NULL drift <- pars[args$drift] diffusion <- pars[args$diffusion] ext <- quasse.extent(cache$control, drift, diffusion) pars <- expand.pars.quasse(cache$lambda, cache$mu, args, ext, pars) check.pars.quasse(pars$hi$lambda, pars$hi$mu, drift, diffusion) pars } } quasse.extent <- function(control, drift, diffusion) { nx <- control$nx dx <- control$dx dt <- control$dt.max xmid <- control$xmid r <- control$r w <- control$w if ( control$method == "mol" ) { ndat <- nx*c(r, 1) padding <- NULL } else { mean <- drift * dt sd <- sqrt(diffusion * dt) nkl <- max(ceiling(-(mean - w * sd)/dx)) * c(r, 1) nkr <- max(ceiling( (mean + w * sd)/dx)) * c(r, 1) ndat <- nx*c(r, 1) - (nkl + 1 + nkr) padding <- cbind(nkl, nkr) storage.mode(padding) <- "integer" } x0.2 <- xmid - dx*ceiling((ndat[2] - 1)/2) x0.1 <- x0.2 - dx*(1 - 1/r) x <- list(seq(x0.1, length.out=ndat[1], by=dx/r), seq(x0.2, length.out=ndat[2], by=dx)) tr <- seq(r, length.out=ndat[2], by=r) list(x=x, padding=padding, ndat=ndat, tr=tr, nx=c(nx*r, nx)) } combine.branches.quasse <- function(f.hi, f.lo, control) { nx <- control$nx dx <- control$dx tc <- control$tc r <- control$r eps <- log(control$eps) dt.max <- control$dt.max careful <- function(f, y, len, pars, t0, dt.max) { ans <- f(y, len, pars, t0) if ( ans[[1]] > eps ) { ans } else { if ( control$method == "fftC" || control$method == "fftR" ) dt.max <- dt.max / 2 len2 <- len/2 ans1 <- Recall(f, y, len2, pars, t0, dt.max) ans2 <- Recall(f, ans1[[2]], len2, pars, t0 + len2, dt.max) ans2[[1]][[1]] <- ans1[[1]][[1]] + ans2[[1]][[1]] ans2 } } function(y, len, pars, t0, idx) { if ( t0 < tc ) { dx0 <- dx / r nx0 <- nx * r } else { dx0 <- dx nx0 <- nx } if ( any(y < -1e-8) ) stop("Actual negative D value detected -- calculation failure") y[y < 0] <- 0 y <- matrix(y, nx0, 2) q0 <- sum(y[,2]) * dx0 if ( q0 <= 0 ) stop("No positive D values") y[,2] <- y[,2] / q0 lq0 <- log(q0) if ( t0 >= tc ) { ans <- careful(f.lo, y, len, pars$lo, t0, dt.max) } else if ( t0 + len < tc ) { ans <- careful(f.hi, y, len, pars$hi, t0, dt.max) } else { len.hi <- tc - t0 ans.hi <- careful(f.hi, y, len.hi, pars$hi, t0, dt.max) y.lo <- ans.hi[[2]][pars$tr,] lq0 <- lq0 + ans.hi[[1]] if ( nrow(y.lo) < nx ) y.lo <- rbind(y.lo, matrix(0, nx - length(pars$tr), 2)) ans <- careful(f.lo, y.lo, len - len.hi, pars$lo, tc, dt.max) } c(ans[[1]] + lq0, ans[[2]]) } }
config <- local({ conflist <- list() confpaths <- character() load <- function(filepath){ message("Loading config from ", filepath) confpaths <<- c(confpaths, filepath) newconf <- as.list(fromJSON(filepath)); for(i in seq_along(newconf)){ val <- newconf[[i]] name <- names(newconf[i]) conflist[[name]] <<- if(length(val)) val else NA } } function(x){ value = conflist[[x]]; if(is.null(value)){ stop("System error! No config set for: ", x); } return(value); } }) create_user_config <- function(){ configfile <- get_user_conf() if(file.exists(configfile)){ if(!validate(readLines(configfile))){ stop("Config contains invalid JSON: ", configfile) } } else { defaultconf <- system.file("config/defaults.conf", package = packagename); confdir <- dirname(configfile) dir.create(confdir, showWarnings = FALSE, recursive = TRUE) if(file.exists(confdir)){ if(file.copy(defaultconf, configfile)){ message("Creating new user config file: ", configfile); } else { stop(jsonlite::toJSON(names(Sys.getenv()))) warning("Failed to create new config file: ", configfile, ". Using default config.") } } } } get_user_conf <- function(){ if(is_rapache() || is_admin()){ return("/etc/opencpu/server.conf") } else { file.path(getlocaldir('config'), "user.conf") } }
SSD <- function(level){ x <- NULL if(level==1){ x1 <- github.cssegisanddata.covid19(country = "South Sudan") x2 <- ourworldindata.org(id = "SSD") x <- full_join(x1, x2, by = "date") } return(x) }
`.f3` <- function(a1,a2,a3){ exp(complex_gamma(a1,log=TRUE) - complex_gamma(a2,log=TRUE) - complex_gamma(a3,log=TRUE)) } `.f4` <- function(a1,a2,a3,a4){ exp(complex_gamma(a1,log=TRUE) + complex_gamma(a2,log=TRUE) - complex_gamma(a3,log=TRUE) - complex_gamma(a4,log=TRUE)) } "f15.1.1" <- function(A, B, C, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} genhypergeo(U=c(A,B), L=C, z=z, tol=tol, maxiter=maxiter) } "f15.3.1" <- function(A,B,C,z,h=0){ if(!is.null(getOption("showHGcalls"))){print(match.call())} mult <- .f3(C,B,C-B) f <- function(t){t^(B-1)*(1-t)^(C-B-1)*(1-t*z)^(-A)} if(length(h)==1){ if(h==0){ return(mult * myintegrate(f,lower=0,upper=1)) } else { if(is.double(h)){ h <- 0.5 + h*1i } } } return(mult * integrate.segments(f,c(0,h,1),close=FALSE)) } "f15.3.3" <- function(A,B,C,z,tol=0,maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} (1-z)^(C-A-B)*genhypergeo(U=c(C-A,C-B),L=C,z=z,tol=tol,maxiter=maxiter) } "f15.3.4" <- function(A,B,C,z,tol=0,maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} (1-z)^(-A)*genhypergeo(U=c(A,C-B),L=C,z=z/(z-1),tol=tol,maxiter=maxiter) } "f15.3.5" <- function(A,B,C,z,tol=0,maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} (1-z)^(-B)*genhypergeo(U=c(B,C-A),L=C,z=z/(z-1),tol=tol,maxiter=maxiter) } "i15.3.6" <- function(A,B,C){ if(!is.null(getOption("showHGcalls"))){print(match.call())} c( ifelse(is.nonpos(C-A) | is.nonpos(C-B), 0, .f4(C, C-A-B, C-A,C-B)), ifelse(is.nonpos(A ) | is.nonpos(B ), 0, .f4(C, A+B-C, A , B )) ) } "j15.3.6" <- function(A,B,C){ if(!is.null(getOption("showHGcalls"))){print(match.call())} is.nonpos(c( C , C-A-B , C , A+B-C )) } "f15.3.6" <- function(A,B,C,z,tol=0,maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} if(length(z)==0){ return(z) } jj <- i15.3.6(A,B,C) jj[1] * genhypergeo(U=c( A, B),L=A+B-C+1,z=1-z,tol=tol,maxiter=maxiter) + jj[2] * genhypergeo(U=c(C-A,C-B),L=C-A-B+1,z=1-z,tol=tol,maxiter=maxiter) * (1-z)^(C-A-B) } "i15.3.7" <- function(A,B,C){ if(!is.null(getOption("showHGcalls"))){print(match.call())} c( ifelse(is.nonpos(B) | is.nonpos(C-A), 0, .f4(C,B-A,B,C-A)), ifelse(is.nonpos(A) | is.nonpos(C-B), 0, .f4(C,A-B,A,C-B)) ) } "j15.3.7" <- function(A,B,C){ if(!is.null(getOption("showHGcalls"))){print(match.call())} is.nonpos(c( C , B-A, C , A-B )) } "f15.3.7" <- function(A,B,C,z,tol=0,maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} if(length(z)==0){ return(z) } jj <- i15.3.7(A,B,C) jj[1] * (-z)^(-A) * genhypergeo(U=c(A,1-C+A),L=1-B+A,z=1/z,tol=tol,maxiter=maxiter) + jj[2] * (-z)^(-B) * genhypergeo(U=c(B,1-C+B),L=1-A+B,z=1/z,tol=tol,maxiter=maxiter) } "i15.3.8" <- function(A,B,C){ if(!is.null(getOption("showHGcalls"))){print(match.call())} c( ifelse(is.nonpos(B) | is.nonpos(C-A), 0, .f4(C,B-A,B,C-A)), ifelse(is.nonpos(A) | is.nonpos(C-B), 0, .f4(C,A-B,A,C-B)) ) } "j15.3.8" <- function(A,B,C){ if(!is.null(getOption("showHGcalls"))){print(match.call())} is.nonpos(c( C , B-A , C , A-B )) } "f15.3.8" <- function(A,B,C,z,tol=0,maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} if(length(z)==0){ return(z) } jj <- i15.3.8(A,B,C) return( jj[1] * (1-z)^(-A) * genhypergeo(U=c(A,C-B),L=A-B+1,z=1/(1-z),tol=tol,maxiter=maxiter) + jj[2] * (1-z)^(-B) * genhypergeo(U=c(B,C-A),L=B-A+1,z=1/(1-z),tol=tol,maxiter=maxiter) ) } "i15.3.9" <- function(A,B,C){ if(!is.null(getOption("showHGcalls"))){print(match.call())} return(c( ifelse(is.nonpos(C-A)|is.nonpos(C-B), 0, .f4(C,C-A-B,C-A,C-B)), ifelse(is.nonpos( A)|is.nonpos(B) , 0, .f4(C,A+B-C,A, B)) )) } "j15.3.9" <- function(A,B,C){ if(!is.null(getOption("showHGcalls"))){print(match.call())} is.nonpos(c( C , C-A-B , C , A+B-C )) } "f15.3.9" <- function(A,B,C,z,tol=0,maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} if(length(z)==0){ return(z) } jj <- i15.3.9(A,B,C) jj[1] * z^( -A)*genhypergeo(U=c(A,A-C+1),L=A+B-C+1,z=1-1/z,tol=tol,maxiter=maxiter) + jj[2] * (1-z)^(C-A-B)*z^(A-C)*genhypergeo(U=c(C-A,1-A),L=C-A-B+1,z=1-1/z,tol=tol,maxiter=maxiter) } "isgood" <- function(x,tol){ all(abs(x[!is.na(x)]) <= tol)} "genhypergeo" <- function (U, L, z, tol = 0, maxiter=2000, check_mod=TRUE, polynomial=FALSE, debug=FALSE, series=TRUE) { if(series){ return(genhypergeo_series(U, L, z, tol = tol, maxiter=maxiter, check_mod=check_mod, polynomial=polynomial, debug=debug)) } else { return(genhypergeo_contfrac(U, L, z, maxiter=maxiter)) } } "genhypergeo_series" <- function (U, L, z, tol = 0, maxiter=2000, check_mod=TRUE, polynomial=FALSE, debug=FALSE) { if(!is.null(getOption("showHGcalls"))){print(match.call())} if(debug){ stopifnot(length(z)==1) out <- NULL } if(check_mod){ lU <- length(U) lL <- length(L) if(lU > lL+1){ greater <- Mod(z)>0 } else if(lU > lL) { greater <- Mod(z)>1 } else { greater <- Mod(z)<0 } if(all(greater)){ return(z*NA) } else { z[greater] <- NA } } fac <- 1 temp <- fac if(debug){out <- temp} if(maxiter==0){ return(z*0+fac) } for (n in seq_len(maxiter)) { fac <- fac * (prod(U)/prod(L)) * (z/n) series <- temp + fac if(debug){out <- c(out,fac)} if (isgood(series-temp,tol)){ if(debug){ return(list(series,out)) } else { return(series) } } temp <- series U <- U + 1 L <- L + 1 } if(debug){ return(list(series,out)) } if(polynomial){ return(series) } else { warning("series not converged") return(z*NA) } } "hypergeo_taylor" <- function(A, B, C, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} genhypergeo(U=c(A,B), L=C, z=z, tol=tol, maxiter=maxiter, check_mod=FALSE, polynomial=TRUE) } "is.near_integer" <- function(i , tol=getOption("tolerance")){ if(is.null(tol)){ tol <- 1e-11 } abs(i-round(Re(i))) <= tol } "is.nonpos" <- function(i){ is.near_integer(i) & (Re(i) < 0.5) } "is.zero" <- function(i){ is.near_integer(i) & (abs(i) < 0.5) } "hypergeo_A_nonpos_int" <- function(A, B, C, z, tol=0){ if(!is.null(getOption("showHGcalls"))){print(match.call())} stopifnot(is.nonpos(A)) if(( is.near_integer(C) ) & is.near_integer(C) & (abs(C-A) < 0.5) ){ warning("this case is not uniquely defined: proceed, assuming both A and C approach the same nonpositive integer at the same speed [that is, (a)_n cancels (c)_n for all 'n']") return(genhypergeo(U=B,L=NULL,z,tol=tol,check_mod = FALSE)) } else { return(hypergeo_taylor(A,B,C,z,tol=tol,maxiter = -A)) } } "hypergeo_AorB_nonpos_int" <- function(A, B, C, z, tol=0){ if(!is.null(getOption("showHGcalls"))){print(match.call())} stopifnot(is.nonpos(A) | is.nonpos(B)) if(is.nonpos(A) & is.nonpos(B)){ if(A>B){ return(hypergeo_A_nonpos_int(A,B,C,z,tol=tol)) } else { return(hypergeo_A_nonpos_int(B,A,C,z,tol=tol)) } } if(is.nonpos(A)){ return(hypergeo_A_nonpos_int(A,B,C,z,tol=tol)) } else { return(hypergeo_A_nonpos_int(B,A,C,z,tol=tol)) } } ".process_args" <- function(...){ a <- list(...) attr <- attributes(a[[which.max(unlist(lapply(a,length)))]]) a <- lapply(a,as.vector) out <- do.call("cbind",a) return(list(out=out, attr = attr)) } "crit" <- function(...){ c( 1/2 + 1i*sqrt(3)/2, 1/2 - 1i*sqrt(3)/2 ) } "hypergeo" <- function(A, B, C, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} if(length(A)>1 | length(B)>1 | length(C)>1){ jj <- .process_args(A,B,C,z) f <- function(x){hypergeo(A=Re(x[1]), B=Re(x[2]),C=Re(x[3]),z=x[4],tol=tol,maxiter=maxiter)} out <- apply(jj$out , 1, f) attributes(out) <- jj$attr return(out) } jj <- crit() c1 <- jj[1] c2 <- jj[2] close_to_crit <- (abs(z-c1) < 0.1) | (abs(z-c2) < 0.1) out <- z*NA if(any( close_to_crit)){out[ close_to_crit] <- hypergeo_gosper (A,B,C,z[ close_to_crit], tol=tol, maxiter=maxiter)} if(any(!close_to_crit)){out[!close_to_crit] <- hypergeo_powerseries (A,B,C,z[!close_to_crit], tol=tol, maxiter=maxiter)} do_with_cf <- !is.na(z) & is.na(out) if(any(do_with_cf)){ out[do_with_cf] <- hypergeo_contfrac(A=A, B=B, C=C, z=z[do_with_cf], maxiter=maxiter) } do_with_integration <- !is.na(z) & is.na(out) if(any(do_with_integration)){ g <- function(z){f15.3.1(A=A, B=B, C=C, z=z)} out[do_with_integration] <- sapply(z[do_with_integration] , g) } return(out) } "hypergeo_powerseries" <- function(A, B, C, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} z <- z+0i if(is.zero(A) | is.zero(B)){ if(is.zero(C)){ return(z*NA) } else { return(z*0+1) } } if(is.zero(C)){ return(z*Inf) } if(is.zero(A-C)){ return( (1-z)^(-B) ) } else if (is.zero(B-C)){ return( (1-z)^(-A) ) } if(is.nonpos(A) | is.nonpos(B)){ return(hypergeo_AorB_nonpos_int(A,B,C,z,tol=tol)) } if(is.nonpos(C)){ return(z*NA) } if(Re(A) > Re(B)){ swap <- A A <- B B <- swap } m <- C-A n <- B-A if(is.near_integer(m)){ if(m <= 0){ return( (1-z)^(C-A-B)*Recall(C-A,C-B,C,z=z,tol=tol,maxiter=maxiter) ) } else { if(is.near_integer(n)){ return(hypergeo_cover3(A,n,m,z,tol=tol,maxiter=maxiter)) } } } m <- -(A+B-C) if(is.near_integer(m)){ return(hypergeo_cover1(A,B,m,z,tol=tol,maxiter=maxiter)) } m <- B-A if(is.near_integer(m)){ return(hypergeo_cover2(A,C,m,z,tol=tol,maxiter=maxiter)) } return(hypergeo_general(A,B,C,z,tol=tol,maxiter=maxiter)) } "hypergeo_general" <- function(A, B, C, z, tol=0, maxiter=2000, give=FALSE){ if(!is.null(getOption("showHGcalls"))){print(match.call())} attr <- attributes(z) z <- as.vector(as.complex(z)) things <- thingfun(z) choice <- apply(things,1,which.min) if(!is.null(getOption("showHGcalls"))){ print("choice: ") print(choice) } u15.1.1 <- choice==1 u15.3.4 <- choice==2 u15.3.6 <- choice==3 u15.3.7 <- choice==4 u15.3.8 <- choice==5 u15.3.9 <- choice==6 out <- z*NA if(any(u15.1.1)){ out[u15.1.1] <- f15.1.1(A=A,B=B,C=C, z[u15.1.1], tol=tol,maxiter=maxiter) } if(any(u15.3.4)){ out[u15.3.4] <- f15.3.4(A=A,B=B,C=C, z[u15.3.4], tol=tol,maxiter=maxiter) } if(any(u15.3.6)){ out[u15.3.6] <- f15.3.6(A=A,B=B,C=C, z[u15.3.6], tol=tol,maxiter=maxiter) } if(any(u15.3.7)){ out[u15.3.7] <- f15.3.7(A=A,B=B,C=C, z[u15.3.7], tol=tol,maxiter=maxiter) } if(any(u15.3.8)){ out[u15.3.8] <- f15.3.8(A=A,B=B,C=C, z[u15.3.8], tol=tol,maxiter=maxiter) } if(any(u15.3.9)){ out[u15.3.9] <- f15.3.9(A=A,B=B,C=C, z[u15.3.9], tol=tol,maxiter=maxiter) } attributes(out) <- attr if(give){ return(list(choice,out)) } else { return(out) } } "thingfun" <- function(z,complex=FALSE){ things <- cbind("z" = z, "z/(z-1)" = z/(z-1), "1-z" = 1-z, "1/z" = 1/z, "1/(1-z)" = 1/(1-z), "1-1/z" = 1-1/z ) if(complex){return(things)} things <- Mod(things) if(any(apply(things,1,min, na.rm=TRUE)>1)){ stop("odd: none of the transformations take the argument inside the unit disk. Contact the package maintainer") } return(things) } "hypergeo_cover1" <- function(A, B, m, z, tol=0, maxiter=2000, method="a", give=FALSE){ if(!is.null(getOption("showHGcalls"))){print(match.call())} stopifnot(is.near_integer(m)) C <- A+B+m attr <- attributes(z) z <- as.vector(as.complex(z)) things <- thingfun(z) if(any(j15.3.7(A,B,C))){ things[,4] <- Inf } if(any(j15.3.8(A,B,C))){ things[,5] <- Inf } if(any(j15.3.9(A,B,C))){ things[,6] <- Inf } choice <- apply(things,1,which.min) u15.1.1 <- choice==1 u15.3.4 <- choice==2 u15.3.x <- choice==3 u15.3.7 <- choice==4 u15.3.8 <- choice==5 u15.3.9 <- choice==6 out <- z*NA if(any(u15.1.1)){ out[u15.1.1] <- f15.1.1 (A=A,B=B,C=C, z[u15.1.1], tol=tol,maxiter=maxiter) } if(any(u15.3.4)){ out[u15.3.4] <- f15.3.4 (A=A,B=B,C=C, z[u15.3.4], tol=tol,maxiter=maxiter) } if(any(u15.3.x)){ out[u15.3.x] <- f15.3.10_11_12(A=A,B=B,m=m, z[u15.3.x], tol=tol,maxiter=maxiter, method=method) } if(any(u15.3.7)){ out[u15.3.7] <- f15.3.7 (A=A,B=B,C=C, z[u15.3.7], tol=tol,maxiter=maxiter) } if(any(u15.3.8)){ out[u15.3.8] <- f15.3.8 (A=A,B=B,C=C, z[u15.3.8], tol=tol,maxiter=maxiter) } if(any(u15.3.9)){ out[u15.3.9] <- f15.3.9 (A=A,B=B,C=C, z[u15.3.9], tol=tol,maxiter=maxiter) } attributes(out) <- attr if(give){ return(list(choice,out)) } else { return(out) } } "hypergeo_cover2" <- function(A, C, m, z, tol=0, maxiter=2000, method="a", give=FALSE){ if(!is.null(getOption("showHGcalls"))){print(match.call())} stopifnot(is.near_integer(m)) B <- A+m attr <- attributes(z) z <- as.vector(as.complex(z)) things <- thingfun(z) if(any(j15.3.6(A,B,C))){ things[,3] <- Inf } if(any(j15.3.8(A,B,C))){ things[,5] <- Inf } if(any(j15.3.9(A,B,C))){ things[,6] <- Inf } choice <- apply(things,1,which.min) u15.1.1 <- choice==1 u15.3.4 <- choice==2 u15.3.6 <- choice==3 u15.3.x <- choice==4 u15.3.8 <- choice==5 u15.3.9 <- choice==6 out <- z*NA if(any(u15.1.1)){ out[u15.1.1] <- f15.1.1 (A=A,B=B,C=C, z[u15.1.1], tol=tol,maxiter=maxiter) } if(any(u15.3.4)){ out[u15.3.4] <- f15.3.4 (A=A,B=B,C=C, z[u15.3.4], tol=tol,maxiter=maxiter) } if(any(u15.3.6)){ out[u15.3.6] <- f15.3.6 (A=A,B=B,C=C, z[u15.3.6], tol=tol,maxiter=maxiter) } if(any(u15.3.x)){ out[u15.3.x] <- f15.3.13_14(A=A,C=C,m=m, z[u15.3.x], tol=tol,maxiter=maxiter, method=method) } if(any(u15.3.8)){ out[u15.3.8] <- f15.3.8 (A=A,B=B,C=C, z[u15.3.8], tol=tol,maxiter=maxiter) } if(any(u15.3.9)){ out[u15.3.9] <- f15.3.9 (A=A,B=B,C=C, z[u15.3.9], tol=tol,maxiter=maxiter) } attributes(out) <- attr if(give){ return(list(choice,out)) } else { return(out) } } "hypergeo_cover3" <- function(A, n, m, z, tol=0, maxiter=2000, method="a", give=FALSE){ if(!is.null(getOption("showHGcalls"))){print(match.call())} stopifnot(is.near_integer(n)) stopifnot(is.near_integer(m)) attr <- attributes(z) z <- as.vector(as.complex(z)) things <- Mod(cbind( "z" = z, "1/z" = 1/z ) ) if(any(apply(things,1,min,na.rm=TRUE)>1)){ stop("odd: none of the transformations take the argument inside the unit disk. Contact the package maintainer") } choice <- apply(things,1,which.min) u15.1.1 <- choice==1 u07.23.06.0026.01 <- (choice==2) & (m > n) u07.23.06.0031.01 <- (choice==2) & (m <= n) out <- z*NA if(any(u15.1.1)){ out[u15.1.1] <- f15.1.1(A=A,B=A+n,C=A+m, z[u15.1.1], tol=tol,maxiter=maxiter) } if(any(u07.23.06.0026.01)){ out[u07.23.06.0026.01] <- w07.23.06.0026.01(A=A,n,m, z[u07.23.06.0026.01], tol=tol, maxiter=maxiter, method=method) } if(any(u07.23.06.0031.01)){ out[u07.23.06.0031.01] <- w07.23.06.0031.01(A=A,n,m, z[u07.23.06.0031.01], tol=tol, maxiter=maxiter) } attributes(out) <- attr if(give){ return(list(choice,out)) } else { return(out) } } "f15.3.10_a" <- function(A, B, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} U <- c(A,B) z[Mod(1-z) >= 1] <- NA fac <- 1 l1mz <- log(1+0i-z) temp <- 2*psigamma(0+1)-psigamma(A+0)-psigamma(B+0)-l1mz for(n in seq_len(maxiter)){ fac <- fac * prod(U) * ((1-z)/n^2) series <- temp + fac * (2*psigamma(n+1)- psigamma(A+n) - psigamma(B+n) - l1mz) if(isgood(series-temp,tol)){ return(series/beta(A,B)) } temp <- series U <- U+1 } warning("series not converged") return(z*NA) } "f15.3.10_b" <- function(A, B, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} U <- c(A,B) z[Mod(1-z) >= 1] <- NA fac <- 1 pn <- psigamma(1) pa <- psigamma(A) pb <- psigamma(B) l1mz <- log(1+0i-z) temp <- 2*pn-pa-pb-l1mz for(n in seq_len(maxiter)){ fac <- fac * prod(U) * ((1-z)/n^2) pn <- pn + 1/n pa <- pa + 1/(A+n-1) pb <- pb + 1/(B+n-1) series <- temp + fac * (2*pn - pa - pb - l1mz) if(isgood(series-temp,tol)){ return(series/beta(A,B)) } temp <- series U <- U+1 } warning("series not converged") return(z*NA) } "f15.3.10" <- function(A, B, z, tol=0, maxiter=2000, method="a"){ if(!is.null(getOption("showHGcalls"))){print(match.call())} switch(method, a = f15.3.10_a(A,B,z,tol=tol,maxiter=2000), b = f15.3.10_b(A,B,z,tol=tol,maxiter=2000), stop("method must be either 'a' or 'b'") ) } "f15.3.11_bit1" <- function(A, B, m, z, tol=0){ if(!is.null(getOption("showHGcalls"))){print(match.call())} stopifnot(is.near_integer(m)) stopifnot(m>0) m <- round(m) U <- c(A,B) L <- 1-m mult <- .f4(m,A+B+m,A+m,B+m) series <- z*0+1 z[Mod(1-z)>1] <- NA fac <- 1 temp <- fac for (n in seq_len(m-1)) { fac <- fac * (prod(U)/prod(L)) * (1-z)/n series <- temp + fac if (isgood(series-temp,tol)){ return(series * mult) } temp <- series U <- U + 1 L <- L + 1 } return(series*mult) } "f15.3.11_bit2_a" <- function(A, B, m, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} stopifnot(is.near_integer(m)) stopifnot(m>0) U <- c(A+m , B+m) z[Mod(1-z) >= 1] <- NA fac <- 1/factorial(m) l1mz <- log(1+0i-z) temp <- (l1mz-psigamma(0+1)-psigamma(0+m+1) + psigamma(A+0+m) + psigamma(B+0+m) ) * fac for(n in seq_len(maxiter)){ fac <- fac * prod(U) * (1-z)/(n*(n+m)) series <- temp + fac * (l1mz - psigamma(n+1) - psigamma(n+m+1) + psigamma(A+n+m) + psigamma(B+n+m)) if(isgood(series-temp,tol)){ return((z-1)^m * .f3(A+B+m,A,B) * series) } temp <- series U <- U+1 } warning("series not converged") return(z*NA) } "f15.3.11_bit2_b" <- function(A, B, m, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} stopifnot(is.near_integer(m)) stopifnot(m>0) U <- c(A+m , B+m) z[Mod(1-z) >= 1] <- NA fac <- 1/factorial(m) pn <- psigamma( 1) pm <- psigamma(m+1) pa <- psigamma(m+A) pb <- psigamma(m+B) l1mz <- log(1+0i-z) temp <- (l1mz - pn - pm + pa + pb ) * fac for(n in seq_len(maxiter)){ fac <- fac * prod(U) * (1-z)/(n*(n+m)) pn <- pn + 1/n pm <- pm + 1/(n+m) pa <- pa + 1/(A+n+m-1) pb <- pb + 1/(B+n+m-1) series <- temp + fac * (l1mz - pn - pm + pa + pb) if(isgood(series-temp,tol)){ return((z-1)^m * .f3(A+B+m,A,B) * series) } temp <- series U <- U+1 } warning("series not converged") return(z*NA) } "f15.3.11" <- function(A,B,m,z,tol=0, maxiter=2000,method="a"){ if(!is.null(getOption("showHGcalls"))){print(match.call())} switch(method, a = f15.3.11_bit1(A,B,m,z,tol=tol) - f15.3.11_bit2_a(A,B,m,z,tol=tol, maxiter=maxiter), b = f15.3.11_bit1(A,B,m,z,tol=tol) - f15.3.11_bit2_a(A,B,m,z,tol=tol, maxiter=maxiter), stop("method must be either 'a' or 'b'") ) } "f15.3.12_bit1" <- function(A, B, m, z, tol=0){ if(!is.null(getOption("showHGcalls"))){print(match.call())} m <- round(m) U <- c(A-m,B-m) L <- 1-m mult <- .f4(m,A+B-m,A,B) / (1-z)^m z[Mod(1-z)>1] <- NA fac <- 1 temp <- fac series <- z*0+1 for (n in seq_len(m-1)) { fac <- fac * (prod(U)/prod(L)) * (1-z)/n series <- temp + fac if (isgood(series-temp,tol)){ return(series * mult) } temp <- series U <- U + 1 L <- L + 1 } return(series*mult) } "f15.3.12_bit2_a" <- function(A, B, m, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} m <- round(m) if(is.nonpos(A-m)|is.nonpos(B-m)){return(z*0)} mult <- (-1)^m * .f3(A+B-m,A-m,B-m) U <- c(A , B) z[Mod(1-z) >= 1] <- NA fac <- 1/factorial(m) l1mz <- log(1+0i-z) temp <- (l1mz-psigamma(1)-psigamma(m+1) + psigamma(A) + psigamma(B) ) * fac for(n in seq_len(maxiter)){ fac <- fac * prod(U) * (1-z)/(n*(n+m)) series <- temp + fac * (l1mz - psigamma(n+1) - psigamma(n+m+1) + psigamma(A+n) + psigamma(B+n)) if(isgood(series-temp,tol)){ return(mult * series) } temp <- series U <- U+1 } warning("series not converged") return(z*NA) } "f15.3.12_bit2_b" <- function(A, B, m, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} m <- round(m) if(is.nonpos(A-m)|is.nonpos(B-m)){return(z*0)} mult <- (-1)^m * .f3(A+B-m,A-m,B-m) U <- c(A , B) z[Mod(1-z) >= 1] <- NA fac <- 1/factorial(m) pn <- psigamma(1) pm <- psigamma(m+1) pa <- psigamma(A) pb <- psigamma(B) l1mz <- log(1+0i-z) temp <- (l1mz-pn - pm + pa + pb ) * fac for(n in seq_len(maxiter)){ fac <- fac * prod(U) * (1-z)/(n*(n+m)) pn <- pn + 1/n pm <- pm + 1/(n+m) pa <- pa + 1/(A+n-1) pb <- pb + 1/(B+n-1) series <- temp + fac * (l1mz - pn - pm + pa + pb) if(isgood(series-temp,tol)){ return(mult * series) } temp <- series U <- U+1 } warning("series not converged") return(z*NA) } "f15.3.12" <- function(A, B, m, z, tol=0, maxiter=2000, method = "a"){ if(!is.null(getOption("showHGcalls"))){print(match.call())} switch(method, a = f15.3.12_bit1(A,B,m,z,tol=tol) - f15.3.12_bit2_a(A,B,m,z,tol=tol, maxiter=maxiter), b = f15.3.12_bit1(A,B,m,z,tol=tol) - f15.3.12_bit2_b(A,B,m,z,tol=tol, maxiter=maxiter), stop("method must be one of 'a' or 'b'") ) } "f15.3.13" <- function(A, C, z, tol=0, maxiter=2000, method = "a"){ if(!is.null(getOption("showHGcalls"))){print(match.call())} switch(method, a = f15.3.13_a(A,C,z,tol=tol,maxiter=maxiter), b = f15.3.13_b(A,C,z,tol=tol,maxiter=maxiter) ) } "f15.3.13_a" <- function(A, C, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} U <- c(A,1-C+A) z[Mod(z) < 1] <- NA fac <- 1 pn <- psigamma(1) pa <- psigamma(A) pc <- psigamma(C-A) lmz <- log(0i-z) temp <- lmz + 2*psigamma(1) - psigamma(A) - psigamma(C-A) for(n in seq_len(maxiter)){ fac <- fac * prod(U) / (z*n^2) series <- temp + fac * (lmz + 2*psigamma(n+1) - psigamma(A+n) - psigamma(C-A-n)) if(isgood(series-temp,tol)){ return(series * .f3(C,A,C-A) * (0i-z)^(-A)) } temp <- series U <- U+1 } warning("series not converged") return(z*NA) } "f15.3.13_b" <- function(A, C, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} U <- c(A,1-C+A) z[Mod(z) < 1] <- NA fac <- 1 pn <- psigamma(1) pa <- psigamma(A) pc <- psigamma(C-A) lmz <- log(0i-z) temp <- lmz + 2*pn - pa - pc for(n in seq_len(maxiter)){ fac <- fac * prod(U) / (z*n^2) pn <- pn + 1/n pa <- pa + 1/(A+n-1) pc <- pc - 1/(C-A-n) series <- temp + fac * (lmz + 2*pn - pa - pc) if(isgood(series-temp,tol)){ return(series * .f3(C,A,C-A) * (0i-z)^(-A)) } temp <- series U <- U+1 } warning("series not converged") return(z*NA) } "f15.3.14_bit1_a" <- function(A, C, m, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} m <- round(m) U <- c(A+m, 1-C+A+m) z[Mod(z) < 1] <- NA fac <- exp( +complex_gamma(A+m,log=TRUE) -complex_gamma(A,log=TRUE) +complex_gamma(1-C+A+m,log=TRUE) -complex_gamma(1-C+A,log=TRUE) -complex_factorial(m,log=TRUE) ) lmz <- log(0i-z) temp <- (lmz + psigamma(1+m) + psigamma(1) - psigamma(A+m) - psigamma(C-A-m)) * fac for(n in seq_len(maxiter)){ fac <- fac * prod(U) / (z*n*(n+m)) series <- temp + fac * (lmz + psigamma(1+m+n) + psigamma(1+n) - psigamma(A+m+n) - psigamma(C-A-m-n)) if(isgood(series-temp,tol)){ return( (0i-z)^(-A-m) * .f3(C,A+m,C-A) * series) } temp <- series U <- U+1 } warning("series not converged") return(z*NA) } "f15.3.14_bit1_b" <- function(A, C, m, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} m <- round(m) U <- c(A+m, 1-C+A+m) z[Mod(z) < 1] <- NA fac <- exp( +complex_gamma(A+m,log=TRUE) -complex_gamma(A,log=TRUE) +complex_gamma(1-C+A+m,log=TRUE) -complex_gamma(1-C+A) -complex_factorial(m,log=TRUE) ) pm <- psigamma(m+1) pn <- psigamma(1) pa <- psigamma(m+A) pc <- psigamma(C-A-m) lmz <- log(0i-z) temp <- (lmz + pm + pn - pa - pc) * fac for(n in seq_len(maxiter)){ fac <- fac * prod(U) / (z*n*(n+m)) pm <- pm + 1/(n+m) pn <- pn + 1/n pa <- pa + 1/(m+A+n-1) pc <- pc - 1/(C-A-m-n) series <- temp + fac * (lmz + pm + pn - pa - pc) if(isgood(series-temp,tol)){ return( (0i-z)^(-A-m) * .f3(C,A+m,C-A) * series) } temp <- series U <- U+1 } warning("series not converged") return(z*NA) } "f15.3.14_bit2" <- function(A, C, m, z, tol=0){ if(!is.null(getOption("showHGcalls"))){print(match.call())} m <- round(m) stopifnot(m>0) stopifnot(is.near_integer(m)) U <- c(A) mult <- (0i-z)^(-A) * .f3(C,A+m,1) z[Mod(z)<1] <- NA fac <- 1 temp <- gamma(m)/gamma(C-A) series <- z*0+temp for (n in seq_len(m-1)) { fac <- fac * prod(U) / (z*n) series <- temp + fac * .f3(m-n,C-A-n,1) if (isgood(series-temp,tol)){ return(series * mult) } temp <- series U <- U + 1 } return(series*mult) } "f15.3.14" <- function(A, C, m, z, tol=0, maxiter=2000, method="a"){ if(!is.null(getOption("showHGcalls"))){print(match.call())} a1 <- f15.3.14_bit1_a(A,C,m,z,tol=tol,maxiter=maxiter) a2 <- f15.3.14_bit2(A,C,m,z,tol=tol) switch(method, a=f15.3.14_bit1_a(A,C,m,z,tol=tol,maxiter=maxiter) + f15.3.14_bit2(A,C,m,z,tol=tol), b=f15.3.14_bit1_b(A,C,m,z,tol=tol,maxiter=maxiter) + f15.3.14_bit2(A,C,m,z,tol=tol), stop("method must be one of 'a' or 'b'") ) } "f15.3.10_11_12" <- function(A,B,m,z,tol=0,maxiter=2000,method="a"){ if(!is.null(getOption("showHGcalls"))){print(match.call())} stopifnot(is.near_integer(m)) m <- round(m) if(is.zero(m)){ return(f15.3.10(A,B, z,tol=tol,maxiter=maxiter,method=method)) } else if (m>0){ return(f15.3.11(A,B, m,z,tol=tol,maxiter=maxiter,method=method)) } else if (m<0){ return(f15.3.12(A,B,-m,z,tol=tol,maxiter=maxiter,method=method)) } else { stop("this cannot happen") } } "f15.3.13_14" <- function(A, C, m, z, tol=0, maxiter=2000, method="a"){ if(!is.null(getOption("showHGcalls"))){print(match.call())} stopifnot(is.near_integer(m)) m <- round(m) if(is.zero(m)){ return(f15.3.13(A ,C ,z,tol=tol,maxiter=maxiter,method=method)) } else if (m>0){ return(f15.3.14(A ,C, m,z,tol=tol,maxiter=maxiter,method=method)) } else if (m<0){ return(f15.3.14(A+m,C,-m,z,tol=tol,maxiter=maxiter,method=method)) } else { stop("this cannot happen") } } "w07.23.06.0029.01" <- function(A, n, m, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} ((-1)^m*gamma(A-m)*factorial(m+n)*(0i-z)^(-A-n)/(gamma(A)*factorial(n)))* hypergeo(A+n , m+n+1, n+1, 1/z,tol=tol,maxiter=maxiter) } "w07.23.06.0031.01_bit1" <- function(A, n, m, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} stopifnot(is.near_integer(m)) stopifnot(m>0) U <- c(A,1-m) L <- 1-n mult <- .f4(A+m,n,m,A+n) * (0i-z)^(-A) series <- z*0+1 z[Mod(z) < 1] <- NA fac <- 1 temp <- fac for (k in seq_len(m-1)) { fac <- fac * (prod(U)/prod(L)) / (k*z) series <- temp + fac if (isgood(series-temp,tol)){ return(series * mult) } temp <- series U <- U + 1 L <- L + 1 } return(series*mult) } "w07.23.06.0031.01_bit2" <- function(A, n, m, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} (-1)^m*(0i-z)^(-A-n) * .f4(A+m,n-m+1,A,n+1)* hypergeo(A+n , 1-m+n , n+1 , 1/z , tol=tol , maxiter=maxiter) } "w07.23.06.0031.01" <- function(A, n, m, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} stopifnot(m <= n) w07.23.06.0031.01_bit1(A, n, m, z, tol=tol, maxiter=maxiter) + w07.23.06.0031.01_bit2(A, n, m, z, tol=tol, maxiter=maxiter) } "w07.23.06.0026.01" <- function(A, n, m, z, tol=0, maxiter=2000, method="a"){ if(!is.null(getOption("showHGcalls"))){print(match.call())} stopifnot(m >= n) stopifnot(m >= 0) stopifnot(n >= 0) stopifnot(is.near_integer(n)) stopifnot(is.near_integer(m)) m <- round(m) n <- round(n) z <- z+0i bit1 <- w07.23.06.0026.01_bit1(A, n, m, z, tol=tol) bit2 <- w07.23.06.0026.01_bit2(A, n, m, z, tol=tol, maxiter=maxiter) bit3 <- switch(method, a = w07.23.06.0026.01_bit3_a(A, n, m, z, tol=tol), b = w07.23.06.0026.01_bit3_b(A, n, m, z, tol=tol), c = w07.23.06.0026.01_bit3_c(A, n, m, z, tol=tol), stop("method must be 'a' or 'b' or 'c'") ) return(bit1 + bit2 + bit3) } "w07.23.06.0026.01_bit1" <- function(A, n, m, z, tol=0){ if(!is.null(getOption("showHGcalls"))){print(match.call())} if(length(z)==0){return(z)} if(is.zero(n)){ return(0) } mult <- (0i-z)^(-A) * .f4(n,A+m,m,A+n) U <- c(A,1-m) L <- 1-n series <- z*0+1 z[Mod(z) < 1] <- NA fac <- 1 temp <- fac for (k in seq_len(n-1)) { fac <- fac * (prod(U)/prod(L)) /(z*k) series <- temp + fac if (isgood(series-temp,tol)){ return(series * mult) } temp <- series U <- U + 1 L <- L + 1 } return(series*mult) } "w07.23.06.0026.01_bit2" <- function(A, n, m, z, tol=0, maxiter = 2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} mult <- (-1)^n * (-z)^(-A-m) * .f3(A+m,A,A+n) * .f3(A+m,m+1,m-n+1) return(mult * genhypergeo(U=c(1,1,A+m),L=c(m+1,m-n+1), z=1/z, tol=tol, maxiter=maxiter)) } "w07.23.06.0026.01_bit3_a" <- function(A, n, m, z, tol=0){ if(!is.null(getOption("showHGcalls"))){print(match.call())} U <- c(A+n , 1-m+n) mult <- (-1)^n * .f3(A+m,A,m-n) * (-z)^(-A-n) fac <- 1/factorial(n) lmz <- log(0i-z) temp <- (lmz - psigamma(m-n-0) +psigamma(0+1) + psigamma(0+n+1) - psigamma(A+0+n)) * fac series <- temp for(k in seq_len(m-n-1)){ fac <- fac * prod(U) / (z * k * (k+n)) series <- temp + fac * (lmz - psigamma(m-n-k) + psigamma(k+1) + psigamma(k+n+1) - psigamma(A+k+n)) if(isgood(series-temp,tol)){ return(series*mult) } temp <- series U <- U+1 } return(series*mult) } "w07.23.06.0026.01_bit3_b" <- function(A, n, m, z, tol=0){ if(!is.null(getOption("showHGcalls"))){print(match.call())} U <- c(A+n , 1-m+n) mult <- (-1)^n*.f3(A+m,A,m-n) * (-z)^(-A-n) fac <- 1/factorial(n) lmz <- log(0i-z) p1 <- psigamma(m-n) p2 <- psigamma(1) p3 <- psigamma(n+1) p4 <- psigamma(A+n) temp <- (lmz - p1 + p2 + p3 - p4) * fac series <- temp for(k in seq_len(m-n-1)){ fac <- fac * prod(U) / (z * k * (k+n) ) p1 <- p1 - 1/(m-n-k) p2 <- p2 + 1/k p3 <- p3 + 1/(k+n) p4 <- p4 + 1/(A+k+n-1) series <- temp + fac * (lmz - p1 + p2 + p3 - p4) if(isgood(series-temp,tol)){ return(series*mult) } temp <- series U <- U+1 } return(series*mult) } "w07.23.06.0026.01_bit3_c" <- function(A, n, m, z, tol=0){ if(!is.null(getOption("showHGcalls"))){print(match.call())} poch <- function(x,j){ prod(x + (seq_len(j)-1)) } mult <- ((-1)^n*.f3(A+m,A,m-n))*(-z)^(-A-n) out <- 0 for(k in 0:(m-n-1)){ out <- out + ( (poch(A+n,k) * poch(1-m+n,k))/(factorial(k)*factorial(k+n)) ) * (log(-z) - psigamma(m-n-k)+psigamma(k+1)+psigamma(k+n+1)-psigamma(A+k+n))*z^(-k) } return(out * mult) } "genhypergeo_contfrac_single" <- function(U, L, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} f <- function(k){prod(U+k)/prod(k+c(1,L))} alpha <- z*sapply(seq_len(maxiter), f) 1+z*prod(U)/(prod(L)*(1+GCF(a = -alpha , b = 1+alpha, tol=tol))) } "genhypergeo_contfrac" <- function(U, L, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} attr <- attributes(z) f <- function(z){genhypergeo_contfrac_single(U, L, z=z, tol=tol, maxiter=maxiter)} out <- sapply(z,f) attributes(out) <- attr return(out) } "hypergeo_contfrac" <- function(A, B, C, z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} attr <- attributes(z) f <- function(z){genhypergeo_contfrac_single(U=c(A, B), L=C, z=z, tol=tol, maxiter=maxiter)} out <- sapply(z,f) attributes(out) <- attr return(out) } "hypergeo_residue_general" <- function(A, B, C, z, r, O=z, tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} stopifnot(length(z)==1) residue(f=function(z){hypergeo(A,B,C,z,tol=tol,maxiter=maxiter)}, z0=z, r=0.15, O=O) } "hypergeo_residue_close_to_crit_single" <- function(A, B, C, z, strategy='A', tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} jj <- crit() c1 <- jj[1] c2 <- jj[2] if( (abs(z-c1) <= 0.1) & (abs(z-c2) <= 0.1) ) {stop("this cannot happen")} stopifnot( (abs(z-c1) <= 0.1) | (abs(z-c2) <= 0.1) ) if(abs(z-c1) <= 0.1){ crit <- c1 } else { crit <- c2 } O <- switch( strategy, A = crit, B = z, stop('strategy must be A or B') ) hypergeo_residue_general(A=A,B=B,C=C, z=z, r=0.15, O=O, tol=tol, maxiter=maxiter) } "hypergeo_residue_close_to_crit_multiple" <- function(A, B, C, z, strategy='A', tol=0, maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} sapply(z, function(z){ hypergeo_residue_close_to_crit_single(A,B,C,z,strategy=strategy,tol=tol,maxiter=maxiter) } ) } "lpham" <- function(x,n){lgamma(x+n)-lgamma(x)} "buhring_eqn11" <- function(n,S,A,B,C,z0=1/2){ stopifnot(length(z0)==1) if(length(n)>1) {return(sapply(n,function(nn){buhring_eqn11(n=nn,S,A,B,C,z0=z0)}))} return( exp( +lpham(S,n) +lpham(1+S-C,n) -lpham(1+2*S-A-B,n) -lfactorial(n) ) * hypergeo(-n, A+B-2*S-n, C-S-n, z=z0) ) } "buhring_eqn12" <- function(n,S,A,B,C,z0=1/2){ stopifnot(length(z0)==1) if(length(n)>1) {return(sapply(n,function(nn){buhring_eqn12(n=nn,S,A,B,C,z0=z0)}))} return( (-1)^n* exp( +lpham(S,n) +lpham(S+C-A-B,n) -lpham(1+2*S-A-B,n) -lfactorial(n) ) * hypergeo(-n,A+B-2*S-n, 1+A+B-S-C-n, z=1-z0) ) } "buhring_eqn5_factors" <- function(A,B,C,z,z0=1/2){ c( exp( +complex_gamma(C,log=TRUE) +complex_gamma(B-A,log=TRUE) -complex_gamma(B,log=TRUE) -complex_gamma(C-A,log=TRUE) -A*log(z0-z) ), exp( +complex_gamma(C,log=TRUE) +complex_gamma(A-B,log=TRUE) -complex_gamma(A,log=TRUE) -complex_gamma(C-B,log=TRUE) -B*log(z0-z) ) ) } "buhring_eqn5_series" <- function(S,A,B,C,z,z0=1/2,use11=FALSE,tol=0,maxiter=2000){ if(!is.null(getOption("showHGcalls"))){print(match.call())} if(length(z)==0){return(z)} if(use11){ f <- buhring_eqn11 } else { f <- buhring_eqn12 } temp <- 1 n <- 1 while(n < maxiter){ out <- temp + f(n,S=S,A=A,B=B,C=C,z0=z0)/(z-z0)^n if(isgood(out-temp,tol)){return(out)} temp <- out n <- n+1 } warning("series not converged") return(out) } "hypergeo_buhring" <- function(A,B,C,z,z0=1/2,tol=0,maxiter=2000,use11=TRUE){ jj <- buhring_eqn5_factors(A,B,C,z,z0) return( jj[1]*buhring_eqn5_series(S=A,A,B,C,z,z0=1/2,use11=use11,tol=tol,maxiter=maxiter)+ jj[2]*buhring_eqn5_series(S=B,A,B,C,z,z0=1/2,use11=use11,tol=tol,maxiter=maxiter) ) } "shanks" <- function(Last,This,Next){ if(identical(Next,This)){return(Next)} num <- Next*Last - This^2 den <- Next-2*This+Last if(den==0){ return(Next) } else { return(num/den) } } "genhypergeo_shanks" <- function (U, L, z, maxiter=20){ if(!is.null(getOption("showHGcalls"))){print(match.call())} fac <- 1 temp <- fac if(maxiter==0){ return(z*0+fac) } Last <- 0 This <- 1 Next <- 2 Shanks <- shanks(Last,This,Next) for (n in seq_len(maxiter)) { fac.old <- fac fac <- fac * (prod(U)/prod(L)) * (z/n) fac.new <- fac series <- temp + fac Last <- This This <- Next Next <- series Shanks.old <- Shanks Shanks <- shanks(Last,This,Next) temp <- series U <- U + 1 L <- L + 1 } return(series) } "hypergeo_shanks" <- function (A, B, C, z, maxiter = 20){ genhypergeo_shanks(U=c(A,B), L=C, z=z,maxiter=maxiter) } "hypergeo_gosper" <- function(A, B, C, z, tol=0, maxiter=2000){ d <- 0 e <- 1 f <- 0 for(k in 0:maxiter){ dnew <- (k+A)*(k+B)*z*(e-(k+C-B-A)*d*z/(1-z)) /(4*(k+1)*(k+C/2)*(k+(C+1)/2)) enew <- (k+A)*(k+B)*z*(A*B*d*z/(1-z) + (k+C)*e)/(4*(k+1)*(k+C/2)*(k+(C+1)/2)) fnew <- f-d*(k*((C-B-A)*z+k*(z-2)-C)-A*B*z) /(2* (k+C/2)*(1-z) )+e if(isgood(f-fnew,tol)){return(f)} d <- dnew e <- enew f <- fnew } warning("not converged") return(f) }
download_US_WLEF <- function(start_date, end_date) { base_url <- "http://co2.aos.wisc.edu/data/cheas/wlef/flux/prelim/" start_year <- lubridate::year(start_date) end_year <- lubridate::year(end_date) raw.data <- start_year:end_year %>% purrr::map_df(function(syear) { influx <- tryCatch( read.table( paste0(base_url, syear, "/flux_", syear, ".txt"), sep = "", header = TRUE ) %>% apply(2, trimws) %>% apply(2, as.character) %>% data.frame(stringsAsFactors = F), error = function(e) { NULL }, warning = function(e) { NULL } ) }) %>% mutate_all(funs(as.numeric)) raw.data$date <-as.POSIXct(paste0(raw.data$Year,"/",raw.data$MO,"/",raw.data$DD," ", raw.data$HH), format="%Y/%m/%d %H", tz="UTC") raw.data <- raw.data %>% dplyr::select(date, NEE_122, LE_122) %>% filter(date >= start_date & date <=end_date) %>% na_if( -999) %>% mutate(NEE_122 = PEcAn.utils::misc.convert(NEE_122, "umol C m-2 s-1", "kg C m-2 s-1")) colnames(raw.data) <- c("Time", "NEE", "LE") return(raw.data) }
"allCategory"
pda.fd <- function(xfdlist, bwtlist=NULL, awtlist=NULL, ufdlist=NULL, nfine=501) { if (inherits(xfdlist, "fd")) xfdlist = list(xfdlist) if (!inherits(xfdlist, "list")) stop( "XFDLIST is neither a list or a FD object") nvar <- length(xfdlist) if (nvar == 1) { difeorder <- length(bwtlist) difeordp1 <- difeorder + 1 xfdobj <- xfdlist[[1]] xbasis <- xfdobj$basis xcoef <- xfdobj$coefs xrange <- xbasis$rangeval if (is.null(ufdlist) | is.null(awtlist)) { nforce <- 0 } else { if (inherits(ufdlist[[1]], "list")) { nforce <- length(ufdlist[[1]]) temp <- vector("list", nforce) for (iu in 1:nforce) temp[[iu]] <- ufdlist[[1]][[iu]] ufdlist <- temp } else { nforce <- length(ufdlist) } if (inherits(awtlist[[1]], "list")) { if (length(awtlist[[1]]) != nforce) stop("The length of AWTLIST is incorrect.") temp <- vector("list", nforce) for (iu in 1:nforce) temp[[iu]] <- awtlist[[1]][[iu]] awtlist <- temp } else { if (length(awtlist) != nforce) stop("The length of AWTLIST is incorrect.") } } if (difeorder == 0 && nforce == 0) stop("There are no coefficient functions to estimate.") ncurve <- dim(xcoef)[2] nbasmax <- xbasis$nbasis if (nforce > 0) { errorwrd <- FALSE for (iu in 1:nforce) { if (!inherits(ufdlist[[iu]], "fd")) { print(paste("UFDLIST[[",iu, "]] is not a functional data object.",sep="")) errorwrd <- TRUE } else { ufdi <- ufdlist[[iu]] urange <- ufdi$basis$rangeval if (any(urange != xrange)) { print(paste( "XRANGE and URANGE are not identical for UFDLIST[[", iu,"]].",sep="")) errorwrd <- TRUE } } afdPari <- awtlist[[iu]] afdi <- afdPari$fd if (!inherits(afdi, "fd")) { print(paste( "AFDI is not a functional data object for AWTLIST[[", iu,"]].",sep="")) errorwrd <- TRUE } else { basisi <- afdi$basis if (any(basisi$rangeval != urange)) { print(paste("Ranges are incompatible for AWTLIST[[", iu,"]].",sep="")) errorwrd <- TRUE } nbasmax <- max(c(nbasmax,basisi$nbasis)) } } if (errorwrd) stop("") } if (inherits(bwtlist[[1]],"list")) { temp <- vector("list",difeorder) for (j in 1:nvar) { if (inherits(bwtlist[[1]][[j]], "list")) { bwtlist[[1]][[j]] <- bwtlist[[1]][[j]][[1]] } temp[[j]] <- bwtlist[[1]][[j]] } bwtlist <- temp } errorwrd <- FALSE for (j in 1:difeorder) { if (!is.null(bwtlist[[j]])) { bfdParj <- bwtlist[[j]] if (!inherits(bfdParj,"fdPar")) { print(paste( "BWTLIST[[",j,"]] is not a functional parameter object.",sep="")) errorwrd <- TRUE } else { bfdj <- bfdParj$fd if (!inherits(bfdj, "fd")) { print(paste( "BFDJ in BWTLIST[[",j,"]] is not a functional data object.", sep="")) errorwrd <- TRUE } else { basisj <- bfdj$basis if (any(basisj$rangeval != xrange)) print(paste( "Ranges are incompatible for BWTLIST[[",j,"]].",sep="")) } } nbasmax <- max(c(nbasmax,basisj$nbasis)) } } if (errorwrd) stop("") if (nfine < 5*nbasmax) nfine <- 5*nbasmax deltax <- (xrange[2]-xrange[1])/(nfine-1) tx <- seq(xrange[1],xrange[2],deltax) yarray <- array(0,c(nfine,ncurve,difeordp1)) for (j in 1:difeordp1) yarray[,,j] <- eval.fd(tx, xfdobj, j-1) if (nforce > 0) { uarray <- array(0,c(nfine,ncurve,nforce)) for (iu in 1:nforce) uarray[,,iu] <- eval.fd(tx, ufdlist[[iu]]) } yprod <- array(0,c(nfine,difeordp1,difeordp1)) for (j1 in 1:difeordp1) for (j2 in 1:j1) { if (ncurve == 1) yprodval <- yarray[,1,j1]*yarray[,1,j2] else yprodval <- apply(yarray[,,j1]*yarray[,,j2],1,mean) yprod[,j1,j2] <- yprodval yprod[,j2,j1] <- yprodval } if (nforce > 0) { yuprod <- array(0,c(nfine, nforce, difeordp1)) for (iu in 1:nforce) { for (j1 in 1:difeordp1) { if (ncurve == 1) { yuprodval <- yarray[,1,j1]*uarray[,1,iu] } else { yuprodval <- apply(yarray[,,j1]*uarray[,,iu],1,mean) } yuprod[,iu,j1] <- yuprodval } } } if (nforce > 0) { uprod <- array(0,c(nfine, nforce, nforce)) for (iu in 1:nforce) for (ju in 1:iu) { if (ncurve == 1) uprodval <- uarray[,1,iu]*uarray[,1,ju] else uprodval <- apply(uarray[,,iu]*uarray[,,ju],1,mean) uprod[,iu,ju] <- uprodval uprod[,ju,iu] <- uprodval } } onesn <- rep(1,nfine) if (nforce > 0) { aarray <- matrix(0,nfine,nforce) } else { aarray <- NULL } barray <- matrix(0,nfine,difeorder) neqns <- 0 if (nforce > 0) { for (iu in 1:nforce) { if (!is.null(awtlist[[iu]])) { afdPari <- awtlist[[iu]] if (afdPari$estimate) neqns <- neqns + afdPari$fd$basis$nbasis } } } for (j1 in 1:difeorder) { if (!is.null(bwtlist[[j1]])) { bfdParj <- bwtlist[[j1]] if (bfdParj$estimate) neqns <- neqns + bfdParj$fd$basis$nbasis } } if (neqns < 1) stop( "Number of equations to solve is not positive.") cmat <- matrix(0,neqns, neqns) dmat <- matrix(0,neqns, 1) if (nforce > 0) { for (iu in 1:nforce) { if (!is.null(awtlist[[iu]])) { afdPari <- awtlist[[iu]] aarray[,iu] <- eval.fd(tx, afdPari$fd) } } } for (j1 in 1:difeorder) { if (!is.null(bwtlist[[j1]])) { bfdParj <- bwtlist[[j1]] bvecj <- eval.fd(tx, bfdParj$fd) barray[,j1] <- bvecj } } mi12 <- 0 if (nforce > 0) { for (iu1 in 1:nforce) { if (!is.null(awtlist[[iu1]])) { afdPari1 <- awtlist[[iu1]] if (afdPari1$estimate) { abasisi1 <- afdPari1$fd$basis abasismati1 <- getbasismatrix(tx, abasisi1) mi11 <- mi12 + 1 mi12 <- mi12 + abasisi1$nbasis indexi1 <- mi11:mi12 weighti1 <- -yuprod[,iu1,difeordp1] dmat[indexi1] <- trapzmat(abasismati1,onesn,deltax,weighti1) for (j1 in 1:difeorder) { bfdParij <- bwtlist[[j1]] if (!bfdParij$estimate) { weightij <- -yuprod[,iu1,j1] dmat[indexi1] <- dmat[indexi1] + trapzmat(abasismati1, barray[,j1], deltax, weightij) } } mi22 <- 0 for (iu2 in 1:nforce) { if (!is.null(awtlist[[iu2]])) { afdPari2 <- awtlist[[iu2]] if (afdPari2$estimate) { abasisi2 <- afdPari2$fd$basis abasismati2 <- getbasismatrix(tx, abasisi2) weighti2 <- uprod[,iu1,iu2] Cprod <- trapzmat(abasismati1, abasismati2, deltax, weighti2) mi21 <- mi22 + 1 mi22 <- mi22 + abasisi2$nbasis indexi2 <- mi21:mi22 cmat[indexi1,indexi2] <- Cprod } } } mij22 <- mi22 for (j2 in 1:difeorder) { if (!is.null(bwtlist[[j2]])) { bfdParj2 <- bwtlist[[j2]] if (bfdParj2$estimate) { bbasisij2 <- bfdParj2$fd$basis bbasismatij2 <- getbasismatrix(tx, bbasisij2) weightij12 <- -yuprod[,iu1,j2] Cprod <- trapzmat(abasismati1,bbasismatij2, deltax,weightij12) mij21 <- mij22 + 1 mij22 <- mij22 + bbasisij2$nbasis indexij2 <- mij21:mij22 cmat[indexi1,indexij2] <- Cprod } } } lambdai1 <- afdPari1$lambda if (lambdai1 > 0) { Lfdobj <- afdPari1$Lfd penmat <- lambdai1*eval.penalty(abasisi1, Lfdobj) cmat[indexi1,indexi1] <- cmat[indexi1,indexi1] + penmat } } } } } mij12 <- mi12 for (j1 in 1:difeorder) { if (!is.null(bwtlist[[j1]])) { bfdParj1 <- bwtlist[[j1]] if (bfdParj1$estimate) { bbasisij1 <- bfdParj1$fd$basis bbasismatij1 <- getbasismatrix(tx,bbasisij1) mij11 <- mij12 + 1 mij12 <- mij12 + bbasisij1$nbasis indexij1 <- mij11:mij12 weightij1 <- yprod[,j1,difeordp1] dmat[indexij1] <- trapzmat(bbasismatij1,onesn,deltax,weightij1) if (nforce > 0) { for (iu in 1:nforce) { if (!is.null(awtlist[[iu]])) { afdPari <- awtlist[[iu]] if (!afdPari$estimate) { weightijk <- -yuprod[,iu,j1] dmat[indexij1] <- dmat[indexij1] + trapzmat(bbasisij1, aarray[,iu],deltax, weightijk) } } } } } } mi22 <- 0 if (nforce > 0) { for (iu2 in 1:nforce) { if (!is.null(awtlist[[iu2]])) { afdPari2 <- awtlist[[iu2]] if (afdPari2$estimate) { abasisi2 <- afdPari2$fd$basis abasismati2 <- getbasismatrix(tx, abasisi2) weighti2 <- -yuprod[,iu2,j1] Cprod <- trapzmat(bbasismatij1,abasismati2,deltax,weighti2) mi21 <- mi22 + 1 mi22 <- mi22 + abasisi2$nbasis indexi2 <- mi21:mi22 cmat[indexij1,indexi2] <- Cprod } } } } mij22 <- mi22 for (j2 in 1:difeorder) { if (!is.null(bwtlist[[j2]])) { bfdParj2 <- bwtlist[[j2]] bbasisij2 <- bfdParj2$fd$basis if (bfdParj2$estimate) { bbasismatij2 <- getbasismatrix(tx, bbasisij2) weightij22 <- yprod[,j1,j2] Cprod <- trapzmat(bbasismatij1,bbasismatij2,deltax,weightij22) mij21 <- mij22 + 1 mij22 <- mij22 + bbasisij2$nbasis indexij2 <- mij21:mij22 cmat[indexij1,indexij2] <- Cprod } } } lambdaj1 <- bfdParj1$lambda if (lambdaj1 > 0) { Lfdobj <- bfdParj1$Lfd penmat <- lambdaj1*eval.penalty(bbasisij1, Lfdobj) cmat[indexij1,indexij1] <- cmat[indexij1,indexij1] + penmat } } dvec <- -symsolve(cmat,dmat) mi2 <- 0 if (nforce > 0) { for (iu in 1:nforce) { if (!is.null(awtlist[[iu]])) { afdPari <- awtlist[[iu]] if (afdPari$estimate) { mi1 <- mi2 + 1 mi2 <- mi2 + afdPari$fd$basis$nbasis indexi <- mi1:mi2 afdPari$fd$coefs <- as.matrix(dvec[indexi]) awtlist[[iu]] <- afdPari } } } } mij2 <- mi2 for (j in 1:difeorder) { if (!is.null(bwtlist[[j]])) { bfdParj <- bwtlist[[j]] if (bfdParj$estimate) { mij1 <- mij2 + 1 mij2 <- mij2 + bfdParj$fd$basis$nbasis indexij <- mij1:mij2 bfdParj$fd$coefs <- as.matrix(dvec[indexij]) bwtlist[[j]] <- bfdParj } } } resmat <- eval.fd(tx, xfdobj, difeorder) if (nforce > 0) { onesncurve <- rep(1,ncurve) for (iu in 1:nforce) { if (!is.null(awtlist[[iu]])) { afdPari <- awtlist[[iu]] aveci <- as.vector(eval.fd(tx, afdPari$fd)) umati <- eval.fd(tx, ufdlist[[iu]]) aumati <- outer(aveci,onesncurve)*umati resmat <- resmat - aumati } } } for (j in 1:difeorder) { if (!is.null(bwtlist[[j]])) { bfdParj <- bwtlist[[j]] bmatij <- as.vector(eval.fd(tx, bfdParj$fd)) xmatij <- eval.fd(tx, xfdobj, j-1) resmat <- resmat + bmatij*xmatij } } resbasis <- xbasis resfd <- smooth.basis(tx, resmat, resbasis)$fd resfdnames <- xfdobj$fdnames resfdnames[[2]] <- "Residual function" resfdnames[[3]] <- "Residual function value" resfd$fdnames <- resfdnames resfdlist <- list(resfd) } else { if (is.null(ufdlist) || is.null(awtlist)) { awtlist <- NULL } else { if (length(ufdlist) != nvar) stop(paste("The length of UFDLIST", " does not match that of XFDLIST.")) errorwrd = FALSE for (j in 1:nvar) { if (!is.null(ufdlist[[j]])) { nforce <- length(ufdlist[[j]]) if (length(awtlist[[j]]) != nforce) { print(paste("The length of AWTLIST[[",j, "]] is incorrect.",sep="")) errorwrd = TRUE } } } if (errorwrd) stop("") } if (length(bwtlist) != nvar) stop("Length of BWTLIST is incorrect.") errorwrd = FALSE for (ivar in 1:nvar) { if (length(bwtlist[[ivar]]) != nvar) { print(paste("The length of BWTLIST[[",ivar, "]] is incorrect.",sep="")) errorwrd = TRUE } } if (errorwrd) stop("") xfd1 <- xfdlist[[1]] xcoef1 <- xfd1$coefs xbasis1 <- xfd1$basis xrange1 <- xbasis1$rangeval ncurve <- dim(xcoef1)[2] resfdnames <- xfd1$fdnames errorwrd = FALSE for (ivar in 1:nvar) { xfdi <- xfdlist[[ivar]] xcoefi <- xfdi$coefs xbasisi <- xfdi$basis xrangei <- xbasisi$rangeval ncurvei <- dim(xcoefi)[2] if (!inherits(xfdi, "fd")) { print(paste("XFDLIST[[",ivar, "]] is not a functional data object.",sep="")) errorwrd = TRUE } else { if (any(xrangei != xrange1)) { print("Ranges are incompatible for XFDLIST.") errorwrd = TRUE } if (ncurvei != ncurve) { print("Number of curves is incompatible for XFDLIST.") errorwrd = TRUE } } } if (errorwrd) stop("") nbasmax <- xbasis1$nbasis if (!(is.null(ufdlist) || is.null(awtlist))) { urange <- ufdlist[[1]]$basis$rangeval errorwrd <- FALSE for (ivar in 1:nvar) { if (!is.null(ufdlist[[ivar]])) { for (iu in 1:length(ufdlist[[ivar]])) { ufdiviu <- ufdlist[[ivar]][[iu]] if (!inherits(ufdiviu, "fd")) { print(paste("UFDLIST[[",ivar,",",iu, "]] is not a functional data object.", sep="")) errorwrd <- TRUE } if (any(ufdiviu$basis$rangeval != urange)) { print("Ranges are incompatible for UFDLIST.") errorwrd <- TRUE } awtfdPari <- awtlist[[ivar]][[iu]] if (!inherits(awtfdPari, "fdPar")) { print(paste("AWTFDPAR[[",ivar,"]][[",iu, "]] is not a functional parameter object.",sep="")) errorwrd <- TRUE } afdi <- awtfdPari$fd basisi <- afdi$basis if (any(basisi$rangeval != urange)) { print("Ranges are incompatible for AWTLIST.") errorwrd <- TRUE } nbasmax <- max(c(nbasmax,basisi$nbasis)) } if (errorwrd) stop("") } } } errorwrd <- FALSE for (ivar1 in 1:nvar) { for (ivar2 in 1:nvar) { difeorder <- length(bwtlist[[ivar1]][[ivar2]]) for (j in 1:difeorder) { if (!is.null(bwtlist[[ivar1]][[ivar2]][[j]])) { bfdPari1i2j <- bwtlist[[ivar1]][[ivar2]][[j]] if (!inherits(bfdPari1i2j, "fdPar")) { print(paste("BWTLIST[[",ivar1, ",",ivar2, ",",j, "]] is not a functional parameter object.",sep="")) errorwrd = TRUE } basisi1i2j <- bfdPari1i2j$fd$basis if (any(basisi1i2j$rangeval != xrange1)) { print(paste("Ranges are incompatible for BWTLIST[[", ivar1,"]][[",ivar2,"]][[", j,"]]",sep="")) errorwrd <- TRUE } nbasmax <- max(c(nbasmax,basisi1i2j$nbasis)) } } } } if (errorwrd) stop("") if (nfine < 5*nbasmax) nfine <- 5*nbasmax deltax <- (xrange1[2]-xrange1[1])/(nfine-1) tx <- seq(xrange1[1],xrange1[2],deltax) yarray <- vector("list", 0) for (ivar in 1:nvar) { difeorder <- length(bwtlist[[ivar]][[ivar]]) difeordp1 <- difeorder + 1 yarray[[ivar]] <- array(0,c(nfine,ncurve,difeordp1)) for (j in 1:difeordp1){ yj <- eval.fd(tx, xfdlist[[ivar]], j-1) yarray[[ivar]][,,j] <- as.matrix(yj) } } if (!is.null(ufdlist)) { uarray <- vector("list", nvar) for (ivar in 1:nvar) { if (is.null(ufdlist[[ivar]])) { uarray[[ivar]] <- NULL } else { nforce <- length(ufdlist[[ivar]]) uarray[[ivar]] <- vector("list", nforce) for (iu in 1:nforce) uarray[[ivar]][[iu]] <- matrix(0,nfine,ncurve) } } for (ivar in 1:nvar) { if (!is.null(ufdlist[[ivar]])) { nforce <- length(ufdlist[[ivar]]) for (iu in 1:nforce) uarray[[ivar]][[iu]] <- eval.fd(tx, ufdlist[[ivar]][[iu]]) } } } yprod <- vector("list", nvar) for (i1 in 1:nvar) yprod[[i1]] <- vector("list", nvar) for (i1 in 1:nvar) { difeord1p1 <- length(bwtlist[[i1]][[i1]]) + 1 for (i2 in 1:nvar) { difeord2p1 <- length(bwtlist[[i2]][[i2]]) + 1 yprod[[i1]][[i2]] <- array(0,c(nfine,difeord2p1,difeord2p1)) } } for (i1 in 1:nvar) { difeord1p1 <- length(bwtlist[[i1]][[i1]]) + 1 for (j1 in 1:difeordp1) { for (i2 in 1:nvar) { difeord2p1 <- length(bwtlist[[i2]][[i2]]) + 1 for (j2 in 1:difeord2p1) { if (ncurve == 1) { yprodval <- yarray[[i1]][,1,j1]*yarray[[i2]][,1,j2] } else { yprodval <- apply(yarray[[i1]][,,j1]*yarray[[i2]][,,j2],1,mean) } yprod[[i1]][[i2]][,j1,j2] <- yprodval } } } } if (!is.null(ufdlist)) { yuprod <- vector("list", nvar) for (i1 in 1:nvar) { if (!is.null(ufdlist[[i1]])) { nforce <- length(ufdlist[[i1]]) if (nforce > 0) { yuprod[[i1]] <- vector("list", nforce) for (iu in 1:nforce) { difeordp1 <- length(bwtlist[[i1]][[i1]]) + 1 yuprod[[i1]][[iu]] <- matrix(0,nfine,difeordp1) } } } } onesncurve <- rep(1,ncurve) for (i1 in 1:nvar) { if (!is.null(ufdlist[[i1]])) { nforce <- length(ufdlist[[i1]]) if (nforce > 0) { difeordp1 <- length(bwtlist[[i1]][[i1]]) + 1 for (iu in 1:nforce) { for (j1 in 1:difeordp1) { if (ncurve == 1) { yuprodval <- yarray[[i1]][,1,j1]*uarray[[i1]][[iu]] } else { yuprodval <- apply(yarray[[i1]][,,j1]* outer(uarray[[i1]][[iu]],onesncurve),1,mean) } yuprod[[i1]][[iu]][,j1] <- yuprodval } } } } } } if (!is.null(ufdlist)) { uprod <- vector("list", nvar) for (ivar in 1:nvar) { nforce <- length(ufdlist[[ivar]]) if (nforce > 0) { uprod[[ivar]] <- array(0,c(nfine, nforce, nforce)) for (iu in 1:nforce) for (ju in 1:iu) { uprodval <- uarray[[ivar]][[iu]]*uarray[[ivar]][[ju]] uprod[[ivar]][,iu,ju] <- uprodval uprod[[ivar]][,ju,iu] <- uprodval } } } } onesn <- rep(1,nfine) for (ivar in 1:nvar) { neqns <- 0 if (is.null(ufdlist) || is.null(ufdlist[[ivar]])) nforce <- 0 else nforce <- length(ufdlist[[ivar]]) if (nforce > 0) { for (iu in 1:nforce) { afdPari <- awtlist[[ivar]][[iu]] if (afdPari$estimate) { nbasisiu <- afdPari$fd$basis$nbasis neqns <- neqns + nbasisiu } } } for (i2 in 1:nvar) { difeorder <- length(bwtlist[[ivar]][[i2]]) for (j2 in 1:difeorder) { if (!is.null(bwtlist[[ivar]][[i2]][[j2]])) { bfdParij <- bwtlist[[ivar]][[i2]][[j2]] nbasisi2j2 = bfdParij$fd$basis$nbasis if (bfdParij$estimate) neqns <- neqns + nbasisi2j2 } } } if (neqns < 1) stop("Number of equations to solve is not positive.") cmat <- matrix(0,neqns, neqns) dmat <- matrix(0,neqns, 1) if (nforce > 0) { aarray <- matrix(0,nfine,nforce) for (iu in 1:nforce) { if (!is.null(awtlist[[ivar]][[iu]])) { afdPari <- awtlist[[ivar]][[iu]] aarray[,iu] <- eval.fd(tx, afdPari$fd) } } } barray <- vector("list", nvar) for (i in 1:nvar) { difeorder <- length(bwtlist[[ivar]][[i]]) barray[[i]] <- matrix(0,nfine,difeorder) for (j in 1:difeorder) { if (!is.null(bwtlist[[ivar]][[i]][[j]])) { bfdParij <- bwtlist[[ivar]][[i]][[j]] barray[[i]][,j] <- as.matrix(eval.fd(tx, bfdParij$fd)) } } } mi12 <- 0 if (nforce > 0) { for (iu1 in 1:nforce) { if (!is.null(awtlist[[ivar]][[iu1]])) { afdPari1 <- awtlist[[ivar]][[iu1]] if (afdPari1$estimate) { abasisi1 <- afdPari1$fd$basis abasismati1 <- getbasismatrix(tx, abasisi1) mi11 <- mi12 + 1 mi12 <- mi12 + abasisi1$nbasis indexi1 <- mi11:mi12 weighti1 <- -yuprod[[ivar]][[iu1]][,difeordp1] dmat[indexi1] <- trapzmat(abasismati1,onesn,deltax,weighti1) for (i in 1:nvar) { difeorder <- length(bwtlist[[ivar]][[i]]) for (j in 1:difeorder) { bfdParij <- bwtlist[[ivar]][[i]][[j]] if (!is.null(bwtlist[[ivar]][[i]][[j]])) { if (!bfdParij$estimate) { weightij <- -yuprod[[ivar]][[iu1]][,j] dmat[indexi1] <- dmat[indexi1] + trapzmat(abasismati1, barray[[ivar]][,j], deltax, weightij) } } } } mi22 <- 0 for (iu2 in 1:nforce) { if (!is.null(awtlist[[ivar]][[iu2]])) { afdPari2 <- awtlist[[ivar]][[iu2]] if (afdPari2$estimate) { abasisi2 <- afdPari2$fd$basis abasismati2 <- getbasismatrix(tx, abasisi2) weighti2 <- uprod[[ivar]][,iu1,iu2] Cprod <- trapzmat(abasismati1, abasismati2, deltax, weighti2) mi21 <- mi22 + 1 mi22 <- mi22 + abasisi2$nbasis indexi2 <- mi21:mi22 cmat[indexi1,indexi2] <- Cprod } } } mij22 <- mi22 for (i2 in 1:nvar) { if (!is.null(bwtlist[[ivar]][[i2]])) { difeorder <- length(bwtlist[[ivar]][[i2]]) for (j2 in 1:difeorder) { bfdParij2 <- bwtlist[[ivar]][[i2]][[j2]] if (bfdParij2$estimate) { bbasisij2 <- bfdParij2$fd$basis bbasismatij2 <- getbasismatrix(tx, bbasisij2) weightij12 <- -yuprod[[i2]][[iu1]][,j2] Cprod <- trapzmat(abasismati1,bbasismatij2, deltax,weightij12) mij21 <- mij22 + 1 mij22 <- mij22 + bbasisij2$nbasis indexij2 <- mij21:mij22 cmat[indexi1,indexij2] <- Cprod } } } } lambdai1 <- afdPari1$lambda if (lambdai1 > 0) { Lfdobj <- afdPari1$Lfd penmat <- lambdai1*eval.penalty(abasisi1,Lfdobj) cmat[indexi1,indexi1] <- cmat[indexi1,indexi1] + penmat } } } } } mij12 <- mi12 for (i1 in 1:nvar) { difeorder1 <- length(bwtlist[[ivar]][[i1]]) difeordp1 <- difeorder1 + 1 for (j1 in 1:difeorder1) { if (!is.null(bwtlist[[ivar]][[i1]][[j1]])) { bfdParij1 <- bwtlist[[ivar]][[i1]][[j1]] if (bfdParij1$estimate) { bbasisij1 <- bfdParij1$fd$basis bbasismatij1 <- getbasismatrix(tx, bbasisij1) mij11 <- mij12 + 1 mij12 <- mij12 + bbasisij1$nbasis indexij1 <- mij11:mij12 weightij1 <- yprod[[i1]][[ivar]][,j1,difeordp1] trapzij1 <- trapzmat(bbasismatij1,onesn,deltax,weightij1) dmat[indexij1] <- trapzij1 if (nforce > 0) { for (iu in 1:nforce) { if (!is.null(awtlist[[ivar]][[iu]])) { afdPari <- awtlist[[ivar]][[iu]] if (!afdPari$estimate) { weightijk <- yprod[,ivar,iu,j1] trapzijk <-trapzmat(bbasismatij1,aarray[,iu], deltax,weightijk) dmat[indexij1] <- dmat[indexij1] + trapzijk } } } } mi22 <- 0 if (nforce > 0) { for (iu2 in 1:nforce) { if (!is.null(awtlist[[ivar]][[iu2]])) { afdPari2 <- awtlist[[ivar]][[iu2]] if (afdPari2$estimate) { abasisi2 <- afdPari2$fd$basis abasismati2 <- getbasismatrix(tx, abasisi2) weighti2 <- -yuprod[[i1]][[iu2]][,j1] mi21 <- mi22 + 1 mi22 <- mi22 + abasisi2$nbasis indexi2 <- mi21:mi22 Cprod <- trapzmat(bbasismatij1,abasismati2,deltax,weighti2) cmat[indexij1,indexi2] <- cmat[indexij1,indexi2] + Cprod } } } } mij22 <- mi22 for (i2 in 1:nvar) { difeorder2 <- length(bwtlist[[ivar]][[i2]]) for (j2 in 1:difeorder2) { if (!is.null(bwtlist[[ivar]][[i2]][[j2]])) { bfdParij2 <- bwtlist[[ivar]][[i2]][[j2]] bbasisij2 <- bfdParij2$fd$basis bbasismatij2 <- getbasismatrix(tx, bbasisij2) weightij22 <- yprod[[i1]][[i2]][,j1,j2] Cprod <- trapzmat(bbasismatij1,bbasismatij2,deltax,weightij22) if (bfdParij2$estimate) { mij21 <- mij22 + 1 mij22 <- mij22 + bbasisij2$nbasis indexij2 <- mij21:mij22 cmat[indexij1,indexij2] <- cmat[indexij1,indexij2] + Cprod } } } } lambdaij1 <- bfdParij1$lambda if (lambdaij1 > 0) { Lfdobj <- bfdParij1$Lfd penmat <- lambdaij1*eval.penalty(bbasisij1,Lfdobj) cmat[indexij1,indexij1] <- cmat[indexij1,indexij1] + penmat } } } } } dvec <- -solve(cmat,dmat) mi2 <- 0 if (nforce > 0) { for (iu in 1:nforce) { if (!is.null(awtlist[[ivar]][[iu]])) { afdPari <- awtlist[[ivar]][[iu]] if (afdPari$estimate) { mi1 <- mi2 + 1 mi2 <- mi2 + afdPari$fd$basis$nbasis indexi <- mi1:mi2 afdPari$fd$coefs <- as.matrix(dvec[indexi]) awtlist[[ivar]][[iu]] <- afdPari } } } } mij2 <- mi2 for (i1 in 1:nvar) { difeorder <- length(bwtlist[[ivar]][[i1]]) for (j1 in 1:difeorder) { if (!is.null(bwtlist[[ivar]][[i1]][[j1]])) { bfdParij <- bwtlist[[ivar]][[i1]][[j1]] if (bfdParij$estimate) { mij1 <- mij2 + 1 mij2 <- mij2 + bfdParij$fd$basis$nbasis indexij <- mij1:mij2 bfdParij$fd$coefs <- as.matrix(dvec[indexij]) bwtlist[[ivar]][[i1]][[j1]] <- bfdParij } } } } } resfdlist <- vector("list", nvar) for (ivar in 1:nvar) { difeorder <- length(bwtlist[[ivar]][[ivar]]) xfdi <- xfdlist[[ivar]] resbasis <- xfdi$basis resmat <- eval.fd(tx, xfdi, difeorder) onesncurve <- rep(1,ncurve) if (!is.null(ufdlist)) { nforce <- length(ufdlist[[ivar]]) if (nforce > 0) { for (iu in 1:nforce) { if (!is.null(awtlist[[ivar]][[iu]])) { afdPari <- awtlist[[ivar]][[iu]] amati <- as.vector(eval.fd(tx, afdPari$fd)) umati <- eval.fd(tx, ufdlist[[ivar]][[iu]]) if (ncurve == 1) aumati <- amati*umati else aumati <- outer(amati,onesncurve)*umati resmat <- resmat - aumati } } } } for (i1 in 1:nvar) { difeorder <- length(bwtlist[[ivar]][[i1]]) for (j1 in 1:difeorder) { if (!is.null(bwtlist[[ivar]][[i1]][[j1]])) { bfdParij <- bwtlist[[ivar]][[i1]][[j1]] bfdij <- bfdParij$fd bvecij <- as.vector(eval.fd(tx, bfdij)) if (ncurve == 1) { bmatij <- bvecij } else { bmatij <- outer(bvecij,onesncurve) } xmatij <- eval.fd(tx, xfdlist[[i1]], j1-1) resmat <- resmat + bmatij*xmatij } } } resfdi <- smooth.basis(tx, resmat, resbasis)$fd resfdnames <- xfdi$fdnames resfdnames[[2]] <- "Residual function" resfdnames[[3]] <- "Residual function value" resfdlist[[ivar]] <- resfdi } } pdaList <- list(bwtlist=bwtlist, resfdlist=resfdlist, awtlist=awtlist) class(pdaList) <- 'pda.fd' pdaList }
norm <- function(x, type = c("O", "I", "F", "M", "2")) { if(identical("2", type)) { if(anyNA(x)) return(NA_real_) svd(x, nu = 0L, nv = 0L)$d[1L] } else .Internal(La_dlange(x, type)) } kappa <- function(z, ...) UseMethod("kappa") rcond <- function(x, norm = c("O","I","1"), triangular = FALSE, ...) { norm <- match.arg(norm) stopifnot(is.matrix(x)) if({d <- dim(x); d[1L] != d[2L]}) return(rcond(qr.R(qr(if(d[1L] < d[2L]) t(x) else x)), norm=norm, ...)) if(is.complex(x)) { if(triangular) .Internal(La_ztrcon(x, norm)) else .Internal(La_zgecon(x, norm)) } else { if(triangular) .Internal(La_dtrcon(x, norm)) else .Internal(La_dgecon(x, norm)) } } kappa.default <- function(z, exact = FALSE, norm = NULL, method = c("qr", "direct"), ...) { method <- match.arg(method) z <- as.matrix(z) norm <- if(!is.null(norm)) match.arg(norm, c("2", "1","O", "I")) else "2" if(exact && norm == "2") { s <- svd(z, nu = 0, nv = 0)$d max(s)/min(s[s > 0]) } else { if(exact) warning(gettextf("norm '%s' currently always uses exact = FALSE", norm)) d <- dim(z) if(method == "qr" || d[1L] != d[2L]) kappa.qr(qr(if(d[1L] < d[2L]) t(z) else z), exact = FALSE, norm = norm, ...) else .kappa_tri(z, exact = FALSE, norm = norm, ...) } } kappa.lm <- function(z, ...) kappa.qr(z$qr, ...) kappa.qr <- function(z, ...) { qr <- z$qr R <- qr[1L:min(dim(qr)), , drop = FALSE] R[lower.tri(R)] <- 0 .kappa_tri(R, ...) } .kappa_tri <- function(z, exact = FALSE, LINPACK = TRUE, norm=NULL, ...) { if(exact) { stopifnot(is.null(norm) || identical("2", norm)) kappa.default(z, exact = TRUE) } else { p <- as.integer(nrow(z)) if(is.na(p)) stop("invalid nrow(x)") if(p != ncol(z)) stop("triangular matrix should be square") if(is.null(norm)) norm <- "1" if(is.complex(z)) 1/.Internal(La_ztrcon(z, norm)) else if(LINPACK) { if(norm == "I") z <- t(z) storage.mode(z) <- "double" 1 / .Fortran(.F_dtrco, z, p, p, k = double(1), double(p), 1L)$k } else 1/.Internal(La_dtrcon(z, norm)) } }
solve.quadratic <- function (a, b, c, nan.upper=NA, nan.lower=NA) { d <- b * b - 4 * a * c data.frame(lower = ifelse(d < 0, rep(nan.upper, length(d)), (-b - sqrt(d)) / (2*a)), upper = ifelse(d < 0, rep(nan.lower, length(d)), (-b + sqrt(d)) / (2*a))) }
rxodeTest( { context("Test large model compiles") mod <- RxODE(" if (Heart_failure_link == 1) { R_art0 = (R_art0_initial-R_art0_initial*heart_failure_resistance_aorta_scale)/exp(sim_time/(24*5))+R_art0_initial*heart_failure_resistance_aorta_scale; R_per0 = (R_per0_initial-R_per0_initial*heart_failure_resistance_prepheral_scale)/exp(sim_time/(24*5))+R_per0_initial*heart_failure_resistance_prepheral_scale; R_al0 = R_al0_scale*R_per0; R_cap0= R_cap0_scale*R_per0; R_vn0 = R_vn0_scale*R_per0; R_ven0 = (R_ven0_initial-R_ven0_initial*heart_failure_resistance_venous_scale)/exp(sim_time/(24*5))+R_ven0_initial*heart_failure_resistance_venous_scale; R_art_pulm = (R_art_pulm_initial-R_art_pulm_initial*heart_failure_resistance_R_art_pulm_scale)/exp(sim_time/(24*5))+R_art_pulm_initial*heart_failure_resistance_R_art_pulm_scale; R_ven_pulm = (R_ven_pulm_initial-R_ven_pulm_initial*heart_failure_resistance_R_ven_pulm_scale)/exp(sim_time/(24*5))+R_ven_pulm_initial*heart_failure_resistance_R_ven_pulm_scale; C_art = (C_art_initial-C_art_initial*heart_failure_compliance_aorta_scale)/exp(sim_time/(24*5))+C_art_initial*heart_failure_compliance_aorta_scale; C_ven0 = (C_ven0_initial-C_ven0_initial*heart_failure_compliance_venous_scale)/exp(sim_time/(24*5))+C_ven0_initial*heart_failure_compliance_venous_scale; C_pulm_ven = (C_pulm_ven_initial-C_pulm_ven_initial*heart_failure_compliance_pulm_ven_scale)/exp(sim_time/(24*5))+C_pulm_ven_initial*heart_failure_compliance_pulm_ven_scale; C_pulm_art = (C_pulm_art_initial-C_pulm_art_initial*heart_failure_compliance_pulm_art_scale)/exp(sim_time/(24*5))+C_pulm_art_initial*heart_failure_compliance_pulm_art_scale; cf = (cf_initial-cf_initial*cf_scale)/exp(sim_time/(24))+cf_initial*cf_scale; contractility = (contractility_initial-contractility_initial*contractility_HF_scale)/exp(sim_time/(24))+contractility_initial*contractility_HF_scale; Sodium_protein_filtration_rate_Kf = (Sodium_protein_filtration_rate_Kf_nom-Sodium_protein_filtration_rate_Kf_nom*kf_scale)/exp(sim_time/(24))+Sodium_protein_filtration_rate_Kf_nom*kf_scale; vascular_responsiveness_scale = (vascular_responsiveness_scale_nom-vascular_responsiveness_scale_nom*vascular_responsiveness_scale_nom_scale)/exp(sim_time/(24))+vascular_responsiveness_scale_nom*vascular_responsiveness_scale_nom_scale; } else { R_art0 = R_art0_initial ; R_per0 = R_per0_initial ; R_al0 = R_al0_scale*R_per0; R_cap0= R_cap0_scale*R_per0; R_vn0 = R_vn0_scale*R_per0; R_ven0 = R_ven0_initial ; R_art_pulm = R_art_pulm_initial; R_ven_pulm = R_ven_pulm_initial; C_art = C_art_initial ; C_ven0 = C_ven0_initial ; C_pulm_ven = C_pulm_ven_initial; C_pulm_art = C_pulm_art_initial; cf = cf_initial; contractility = contractility_initial; Sodium_protein_filtration_rate_Kf = Sodium_protein_filtration_rate_Kf_nom; vascular_responsiveness_scale = vascular_responsiveness_scale_nom; } CO_nom = CO_nom_initial; plasma_protein_concentration =plasma_protein_amount / (blood_volume_L * L_dL); ISF_protein_concentration = ISF_protein_amount / (interstitial_fluid_volume * L_dL); if(test_ISF_pressure==1){ ISF_pressure = -0.000000002316554*interstitial_fluid_volume^6 + 0.000000910096686*interstitial_fluid_volume^5 - 0.000141950241878*interstitial_fluid_volume^4 + 0.011247538513374*interstitial_fluid_volume^3 - 0.471694546620885*interstitial_fluid_volume^2 + 9.92251133652023*interstitial_fluid_volume - 81.2426416630404+5.09732; }else{ ISF_pressure=ISF_pressure_initial; } if (Heart_failure_link == 0 & cardiac_reserve == 0 ) { tissue_autoregulation_signal = max(0.1,1+tissue_autoreg_scale*(Kp_CO*(CO_delayed - CO_nom*CO_species_scale)+Ki_CO*CO_error)); peripheral_resistance_multiplier = disease_effect_on_TPR_peripheral_resistance * B2sna_effect_on_TPR*A1sna_effect_on_TPR*tissue_autoregulation_signal; peripheral_resistance_multiplier_adjusted = max(dilation_scale,time_TPR_scale*(1+vascular_responsiveness_scale*(peripheral_resistance_multiplier-1))); heart_rate = HR_heart_rate * BB_HR_effect ; } else if (Heart_failure_link == 0 & cardiac_reserve == 1){ tissue_autoregulation_signal = max(0.1,1+tissue_autoreg_scale*(Kp_CO*(CO_delayed - CO_nom*CO_species_scale)+Ki_CO*CO_error)); HR_autoregulation_signal = 1+tissue_autoreg_scale*(HRP_CO*(CO_delayed - CO_nom*CO_species_scale)+HRI_CO*CO_error); heart_rate_multiplier_adjusted = time_HR_scale*(1-HR_autoregulation_signal); Heart_rate_increasing_ratio = min(Mag_HR_changing_ratio,(Heart_rate_increasing_ratio + heart_rate_multiplier_adjusted)); heart_rate = (HR_heart_rate * BB_HR_effect*(1+Heart_rate_increasing_ratio)); peripheral_resistance_multiplier = disease_effect_on_TPR_peripheral_resistance * B2sna_effect_on_TPR*A1sna_effect_on_TPR*tissue_autoregulation_signal; peripheral_resistance_multiplier_adjusted = max(dilation_scale,time_TPR_scale*(1+vascular_responsiveness_scale*(peripheral_resistance_multiplier-1))); } else if (Heart_failure_link == 1 & cardiac_reserve == 0){ tissue_autoregulation_signal = max(0.1,1+tissue_autoreg_scale*(Kp_HF_CO*(CO_delayed - CO_nom*CO_species_scale)+Ki_HF_CO*CO_error)); HR_autoregulation_signal = 1+tissue_autoreg_scale*(HRP_HF_CO*(CO_delayed - CO_nom*CO_species_scale)+HRI_HF_CO*CO_error); peripheral_resistance_multiplier = disease_effect_on_TPR_peripheral_resistance * B2sna_effect_on_TPR*A1sna_effect_on_TPR*tissue_autoregulation_signal; peripheral_resistance_multiplier_adjusted =max(dilation_HF_Chronic_scale,(1+vascular_responsiveness_scale*(peripheral_resistance_multiplier-1))); heart_rate_multiplier_adjusted = (1-HR_autoregulation_signal); Heart_rate_increasing_ratio = min(Mag_HR_HF_Chronic_ratio,(Heart_rate_increasing_ratio + heart_rate_multiplier_adjusted)); heart_rate = (HR_heart_rate * BB_HR_effect*(1+Heart_rate_increasing_ratio)); } else if (Heart_failure_link == 1& cardiac_reserve == 1){ tissue_autoregulation_signal = max(0.1,1+tissue_autoreg_scale*(Kp_HF_CO*(CO_delayed - CO_nom*CO_species_scale)+Ki_HF_CO*CO_error)); HR_autoregulation_signal = 1+tissue_autoreg_scale*(HRP_HF_CO*(CO_delayed - CO_nom*CO_species_scale)+HRI_HF_CO*CO_error); peripheral_resistance_multiplier = disease_effect_on_TPR_peripheral_resistance * B2sna_effect_on_TPR*A1sna_effect_on_TPR*tissue_autoregulation_signal; peripheral_resistance_multiplier_adjusted =max(dilation_HF_Acute_scale,(1+vascular_responsiveness_scale*(peripheral_resistance_multiplier-1))); heart_rate_multiplier_adjusted = (1-HR_autoregulation_signal); Heart_rate_increasing_ratio = min(Mag_HR_HF_Acute_ratio,(Heart_rate_increasing_ratio + heart_rate_multiplier_adjusted)); heart_rate = (HR_heart_rate * BB_HR_effect*(1+Heart_rate_increasing_ratio)); } peripheral_resistance =TPR_scale_peripheral_resistance * R_al0*peripheral_resistance_multiplier_adjusted; arterial_dis_resistance=peripheral_resistance; capillary_resistance=R_cap0; venules_resistance=R_vn0; beat_duration = min_sec / heart_rate ; beat_time = sim_time/beat_duration - floor(sim_time/beat_duration); periods = floor(sim_time/beat_duration); blood_volume = blood_volume_L/1000; time_step = 0.01; sna_effect_on_contractility=1; sna_effect_on_HR = 1; AngII_effect_on_venous_compliance=1; SNA_effect_on_venous_compliance=1; B2sna_effect_on_TPR = 1; A1sna_effect_on_TPR = 1; Ang_II_effect_on_systemic_resistance =1; aldo_effect_on_systemic_resistances = 1; CCB_effect_on_systemic_arterial_resistance = 1; glu_eff_1 = 0; angII_eff_1 = 0; aldo_eff_1 = 0; beta_blocker_effect_on_contractility = BB_contractility_effect; BP_effect_on_compliance=1; LV_volume_mL = LV_volume * m3_mL; arterial_volume_mL = arterial_volume * m3_mL; arterial_dis_circulation_volume_mL =arterial_dis_circulation_volume *m3_mL; capillary_circulation_volume_mL =capillary_circulation_volume *m3_mL; venules_circulation_volume_mL =venules_circulation_volume *m3_mL; RV_volume_mL = RV_volume * m3_mL; pulmonary_arterial_volume_mL = pulmonary_arterial_volume * m3_mL; venous_volume_mL = venous_volume * m3_mL; total_blood_volume_mL = LV_volume_mL + arterial_volume_mL + arterial_dis_circulation_volume_mL+capillary_circulation_volume_mL+venules_circulation_volume_mL + RV_volume_mL + pulmonary_arterial_volume_mL + pulmonary_venous_volume * m3_mL + venous_volume_mL; baseline_total_myocyte_volume = V_w_0 - Baseline_Interstitial_Fibrosis - Baseline_Replacement_Fibrosis - Baseline_Interstitial_Tissue; baseline_single_myocyte_volume = baseline_total_myocyte_volume/Baseline_Myocyte_Number; baseline_myocyte_diameter = 2*sqrt(baseline_single_myocyte_volume/(Pi*Baseline_Myocyte_Length)); myocyte_length = Baseline_Myocyte_Length + change_in_myocyte_length; myocyte_diameter = baseline_myocyte_diameter + change_in_myocyte_diameter; single_myocyte_volume = myocyte_length * Pi * (myocyte_diameter ^ 2) / 4; number_of_live_myocytes = Baseline_Myocyte_Number; total_myocyte_volume = single_myocyte_volume * number_of_live_myocytes; total_nonmyocyte_volume = Baseline_Interstitial_Fibrosis + Baseline_Interstitial_Tissue + Baseline_Replacement_Fibrosis; LV_wall_volume = total_myocyte_volume + total_nonmyocyte_volume; level_of_hypertrophy = LV_wall_volume / (baseline_total_myocyte_volume + total_nonmyocyte_volume); outward_growth = LV_cavity_volume / LV_V0_baseline; pct_change_in_myocyte_diameter = change_in_myocyte_diameter / baseline_myocyte_diameter * 100; pct_change_in_myocyte_length = change_in_myocyte_length / Baseline_Myocyte_Length * 100; LV_cavity_volume = LV_V0_baseline * (1 + myo_L_scale * change_in_myocyte_length / Baseline_Myocyte_Length) ^ 3 * (1 - myo_D_scale * change_in_myocyte_diameter / baseline_myocyte_diameter) ^ 2; LV_fiber_stretch =((LV_volume + (LV_wall_volume/3)) / (LV_cavity_volume + (LV_wall_volume / 3)))^0.3333333; LV_sarcomere_length = ls_0_passive_LV_sarcomere_length * LV_fiber_stretch; LV_sarcomere_contraction_velocity = (LV_sarcomere_length - LV_sarcomere_length_delayed) / time_step; contraction_velocity_effect_in_LV = (1 - LV_sarcomere_contraction_velocity / v0_LV_contraction_velocity_effect_in_LV) / (1 + Cv_contraction_velocity_effect_in_LV * LV_sarcomere_contraction_velocity / v0_LV_contraction_velocity_effect_in_LV); if (LV_sarcomere_length > ls_a0) { sarcomere_length_effect_in_LV = ((LV_sarcomere_length - ls_a0) / (ls_ar_sarcomere_length_effect_in_LV - ls_a0)); } else { sarcomere_length_effect_in_LV = 0; } chamber_radius = ((LV_cavity_volume * 3 / 4 / Pi) ^ 0.3333333) * m_mm ; chamber_diameter = 2 * chamber_radius; outer_radius = (((LV_cavity_volume + LV_wall_volume) * 3 / 4 / Pi) ^ 0.3333333) * m_mm ; h_wall = outer_radius - chamber_radius; h_over_r = h_wall / chamber_radius; EDV_chamber_radius = ((LV_EDV* 3 / 4 / Pi) ^ 0.33333333) * m_mm; EDV_chamber_diameter = 2*EDV_chamber_radius; EDV_outer_radius = (((LV_EDV + LV_wall_volume) * 3 / 4 / Pi) ^ 0.3333333) * m_mm ; EDV_h_wall = EDV_outer_radius - EDV_chamber_radius; EDV_h_over_r = EDV_h_wall / EDV_chamber_radius; LV_mass = 1000000*LV_wall_volume*1.05 ; RV_twitch_duration = RV_systolic_time_fraction * beat_duration; t_d = tau_d_LV_twitch_shape; t_r = tau_r_LV_twitch_shape; t_twitch = t_r + t_d; if (beat_time <= t_r) { sin_signal=(sin(Pi*beat_time/t_twitch))^n_r_LV_twitch_shape; }else { sin_signal=(sin(Pi*beat_time/t_twitch))^n_r_LV_twitch_shape; } LV_twitch_shape = sin_signal; if (beat_time < 0) { LV_twitch_shape = 0; } if (beat_time > t_twitch) { LV_twitch_shape=0; } RV_twitch_shape = (sin(Pi * beat_time / RV_twitch_duration)) ^ 2; if (beat_time < 0) { RV_twitch_shape=0; } if (beat_time > RV_twitch_duration) { RV_twitch_shape = 0; } LV_active_stress = contractility_scale_LV_active_stress * contractility * sigma_ar * sarcomere_length_effect_in_LV * LV_twitch_shape * contraction_velocity_effect_in_LV * beta_blocker_effect_on_contractility *sna_effect_on_contractility; hypertrophy_effect_on_Cf = hypertrophy_Cf_slope*(level_of_hypertrophy - 1); C_f = cf*(1+hypertrophy_effect_on_Cf); stretch_zero_S = stretch_min_LV_passive_stress_along_fiber - stretch_scale_LV_passive_stress_along_fiber; if (LV_fiber_stretch >= stretch_zero_S) { LV_passive_stress_along_fiber = s_f0 * (exp(C_f * (LV_fiber_stretch - stretch_zero_S)) - 1); } else { LV_passive_stress_along_fiber = 0; } LV_radial_stretch = 1/ (LV_fiber_stretch * LV_fiber_stretch); if (LV_radial_stretch >= 1) { LV_passive_radial_stress = s_r0 * (exp(c_r_LV * (LV_radial_stretch - 1)) - 1); } else { LV_passive_radial_stress = 0; } LV_total_stress = LV_active_stress + LV_passive_stress_along_fiber - 2 * LV_passive_radial_stress; if (LV_volume > LV_V0_min) { rel_volume_LV = 1+LV_wall_volume/LV_volume; } else { rel_volume_LV = 1+LV_wall_volume/LV_V0_min; } LV_pressure = LV_total_stress * log(rel_volume_LV)/ 3; arterial_dis_pressure = P_al0 + (arterial_dis_circulation_volume-V_al0)/C_al; capillary_pressure = P_cap0 + (capillary_circulation_volume-V_cap0)/C_cap; venules_pressure = P_vn0 + (venules_circulation_volume-V_vn0)/C_vn; venous_compliance=C_ven0*AngII_effect_on_venous_compliance*SNA_effect_on_venous_compliance; venous_pressure = P_ven0 + (venous_volume - V_ven0) / venous_compliance; RV_Cavity_Volume = RV_V0; RV_wall_volume = V_w_0_RV; RV_fiber_stretch = ((RV_volume + V_w_0_RV/3) / (RV_Cavity_Volume + RV_wall_volume/3))^(0.333); RV_sarcomere_length = ls_a0_RV * RV_fiber_stretch; if (RV_sarcomere_length > ls_a0_RV) { sarcomere_length_effect_in_RV = (RV_sarcomere_length - ls_a0_RV) / (0.000002 - ls_a0_RV); } else { sarcomere_length_effect_in_RV = 0; } RV_sarcomere_contraction_velocity = (RV_sarcomere_length - RV_sarcomere_length_delayed) / time_step; contraction_velocity_effect_in_RV = (1 - RV_sarcomere_contraction_velocity / v0_RV_contraction_velocity_effect_in_RV) / (1 + 0 * RV_sarcomere_contraction_velocity / v0_RV_contraction_velocity_effect_in_RV); RV_active_stress_multiplier = contractility_RV*sna_effect_on_contractility; RV_active_stress = contractility_RV * sigma_ar_RV * sarcomere_length_effect_in_RV * RV_twitch_shape * contraction_velocity_effect_in_RV*sna_effect_on_contractility; RV_radial_stretch = 1/ (RV_fiber_stretch * RV_fiber_stretch); if (RV_radial_stretch >= 1) { RV_passive_radial_stress = s_r0_RV * (exp(c_r_RV * (RV_radial_stretch - 1)) - 1); } else { RV_passive_radial_stress = 0; } if (RV_fiber_stretch >= 1) { RV_passive_stress_along_fiber = s_f0_RV * (exp(cf_RV * (RV_fiber_stretch - 1)) - 1); } else { RV_passive_stress_along_fiber = 0; } RV_total_stress = RV_active_stress + RV_passive_stress_along_fiber - 2 * RV_passive_radial_stress; if (RV_volume > RV_V0_min) { rel_volume = (1 + RV_wall_volume / RV_volume); } else { rel_volume = (1 + RV_wall_volume / RV_V0_min); } RV_pressure = RV_total_stress * log(rel_volume) / 3; venous_flow = (venules_pressure - venous_pressure) / (R_ven0); if (heart_renal_link == 1) { venous_volume_target = blood_volume - LV_volume - arterial_volume - arterial_dis_circulation_volume-capillary_circulation_volume-venules_circulation_volume - RV_volume - pulmonary_arterial_volume - pulmonary_venous_volume; } else { venous_volume_target = venous_volume; } tricuspid_valve_flow_rate = max((venous_pressure - RV_pressure) / R_r_atrium,min_flux); pulmonary_arterial_pressure = ( pulmonary_arterial_volume - V_pulm_art0 )/C_pulm_art + P_art0; pulmonary_venous_pressure = P_ven0 + (pulmonary_venous_volume - V_pulm_ven0 )/C_pulm_ven; pulmonary_arterial_blood_flow = (pulmonary_arterial_pressure - pulmonary_venous_pressure )/ R_ven_pulm ; dP = RV_pressure - pulmonary_arterial_pressure; Zn = L_pulm + time_step * R_art_pulm; pulmonary_blood_flow = (pulmonary_blood_flow_delayed * L_pulm + dP * time_step) / Zn; pulmonary_valve_flow_rate = max(pulmonary_blood_flow,min_flux); if (pulmonary_venous_pressure > LV_pressure) { mitral_valve_flow_rate = max ( (pulmonary_venous_pressure - LV_pressure)/R_left_atrium , min_flux ) ; } else { if (LV_pressure - pulmonary_venous_pressure < mitral_regurgitation_pressure_diff) { mitral_valve_flow_rate = min_flux; } else { mitral_valve_flow_rate = (pulmonary_venous_pressure - LV_pressure)/R_left_atrium; } } pulmonary_valve_flow_rate = max(pulmonary_blood_flow,min_flux); Stiffness0=1/C_art; arterial_stiffness = Stiffness0*(1+ (MAP_delayed - nominal_map_setpoint)*Stiffness_BP_slope); arterial_compliance = 1/arterial_stiffness; arterial_pressure = (arterial_volume - V_art0) / arterial_compliance + P_art0 ; systemic_blood_flow = (arterial_pressure - arterial_dis_pressure) / arterial_dis_resistance; arterial_dis_blood_flow = (arterial_dis_pressure-capillary_pressure)/capillary_resistance; capillary_blood_flow = (capillary_pressure-venules_pressure)/venules_resistance; venules_blood_flow = (venules_pressure-venous_pressure)/R_ven0; dP_1 = LV_pressure - arterial_pressure; Zn_1 = L_art + R_art0 * time_step; aortic_blood_flow = (aortic_blood_flow_delayed * L_art*L_scale + dP_1 * time_step) / Zn_1; aortic_valve_flow_rate = max(aortic_blood_flow,min_flux); BNP = exp(BNP_factor*((LV_EDS+1736)/5.094)+3.14); NTP = exp((log(BNP)+1.4919)/1.0694); if (heart_renal_link == 1) { Pra = 0.2787*exp(CO_delayed*0.2281); Canp = max(0,7.427 - 6.554 / ( 1 + exp( Pra - 3.762) ) + deltaCanp); lambdaANP = -0.1*Canp+1.1199; } else { lambdaANP = 1; } if (beat_time >= (1 - .01/beat_duration) && beat_time < 1) { LV_pressure_diastolic_max = LV_pressure; LV_stress_diastolic_max = LV_passive_stress_along_fiber; LV_volume_maximum = LV_volume; } else { LV_pressure_diastolic_max = LV_EDP; LV_stress_diastolic_max = LV_EDS; LV_volume_maximum = LV_EDV; } LV_EDP_old = LV_pressure_diastolic_max; LV_EDS_old = LV_stress_diastolic_max; LV_EDV_old = LV_volume_maximum; if (arterial_pressure_delayed < arterial_pressure_bigger_delay) { systemic_pressure_minimum_1 = arterial_pressure_delayed; } else { systemic_pressure_minimum_1 = diastolic_pressure; } if (arterial_pressure_delayed < arterial_pressure) { systemic_pressure_minimum = systemic_pressure_minimum_1; } else { systemic_pressure_minimum = diastolic_pressure; } if (arterial_pressure_delayed > arterial_pressure_bigger_delay) { systemic_pressure_maximum_1 = arterial_pressure_delayed; } else { systemic_pressure_maximum_1 = systolic_pressure; } if (arterial_pressure_delayed > arterial_pressure) { systemic_pressure_maximum= systemic_pressure_maximum_1; } else { systemic_pressure_maximum= systolic_pressure; } systolic_pressure_old = systemic_pressure_maximum; diastolic_pressure_old = systemic_pressure_minimum; if (beat_time >= (t_r*0.8) && beat_time < (t_r*0.85)) { LV_peak_stress = LV_active_stress; } else { LV_peak_stress = LV_active_stress_peak; } if (LV_active_stress > 1) { LV_active_stress_peak_old = LV_peak_stress; } else { LV_active_stress_peak_old = LV_active_stress_peak; } if (venous_pressure_delayed < venous_pressure_bigger_delay) { venous_pressure_minimum_1 = venous_pressure_delayed; } else { venous_pressure_minimum_1 = venous_diastolic_pressure; } if (venous_pressure_delayed < venous_pressure) { venous_pressure_minimum = venous_pressure_minimum_1; } else { venous_pressure_minimum = venous_diastolic_pressure; } if (venous_pressure_delayed > venous_pressure_bigger_delay) { venous_pressure_maximum_1 = venous_pressure_delayed; } else { venous_pressure_maximum_1 = venous_systolic_pressure; } if (venous_pressure_delayed > venous_pressure) { venous_pressure_maximum= venous_pressure_maximum_1; } else { venous_pressure_maximum= venous_systolic_pressure; } venous_systolic_pressure_old = venous_pressure_maximum; venous_diastolic_pressure_old = venous_pressure_minimum; if (capillary_pressure_delayed < capillary_pressure_bigger_delay) { capillary_pressure_minimum_1 = capillary_pressure_delayed; } else { capillary_pressure_minimum_1 = capillary_diastolic_pressure; } if (capillary_pressure_delayed < capillary_pressure) { capillary_pressure_minimum = capillary_pressure_minimum_1; } else { capillary_pressure_minimum = capillary_diastolic_pressure; } if (capillary_pressure_delayed > capillary_pressure_bigger_delay) { capillary_pressure_maximum_1 = capillary_pressure_delayed; } else { capillary_pressure_maximum_1 = capillary_systolic_pressure; } if (capillary_pressure_delayed > capillary_pressure) { capillary_pressure_maximum= capillary_pressure_maximum_1; } else { capillary_pressure_maximum= capillary_systolic_pressure; } capillary_systolic_pressure_old = capillary_pressure_maximum; capillary_diastolic_pressure_old = capillary_pressure_minimum; mean_capillary_pressure = (capillary_systolic_pressure/3+capillary_diastolic_pressure*2/3)*Pa_mmHg; if (heart_renal_link == 1) { mean_arterial_pressure_MAP = (systolic_pressure/3+diastolic_pressure*2/3)*Pa_mmHg; mean_venous_pressure = (venous_systolic_pressure+venous_diastolic_pressure*2)/3*Pa_mmHg; } else { mean_arterial_pressure_MAP = nominal_map_setpoint; mean_venous_pressure = P_venous; } if (LV_active_stress_peak > LV_active_stress_threshhold) { kD_hypertrophy = (kD_HYPERTROPHY*C_renal_CV_timescale) * max(0, ((max_myocyte_diameter_increase) - change_in_myocyte_diameter)/(max_myocyte_diameter_increase)); } else { kD_hypertrophy = (kD_HYPERTROPHY*C_renal_CV_timescale); } if (LV_EDS > LV_passive_stress_along_fiber_threshhold) { kL_hypertrophy = (kL_HYPERTROPHY*C_renal_CV_timescale) * max(0, ((max_myocyte_length_increase) - change_in_myocyte_length)/(max_myocyte_length_increase)); } else { kL_hypertrophy = 0; } LVID=((6*LV_EDV)/3.14159)^(1/3); number_of_functional_glomeruli = baseline_nephrons*(1 - 0.3*disease_effects_decreasing_Kf); number_of_functional_tubules = baseline_nephrons*(1-disease_effect_on_nephrons); AT1_preaff_int = 1 - AT1_preaff_scale/2; AT1_effect_on_preaff = AT1_preaff_int + AT1_preaff_scale/(1+exp(-(AT1_bound_AngII - nominal_equilibrium_AT1_bound_AngII)/AT1_preaff_slope)); AT1_aff_int = 1 - AT1_aff_scale/2; AT1_effect_on_aff = AT1_aff_int + AT1_aff_scale/(1+exp(-(AT1_bound_AngII - nominal_equilibrium_AT1_bound_AngII)/AT1_aff_slope)); AT1_eff_int = 1 - AT1_eff_scale/2; AT1_effect_on_eff = AT1_eff_int + AT1_eff_scale/(1+exp(-(AT1_bound_AngII - nominal_equilibrium_AT1_bound_AngII)/AT1_eff_slope)); rsna_preaff_int = 1 - rsna_preaff_scale/2; rsna_effect_on_preaff = rsna_preaff_int + rsna_preaff_scale/(1+exp(-(renal_sympathetic_nerve_activity - nom_rsna)/rsna_preaff_slope)); if(renal_blood_flow_L_min_delayed < 1 & interstitial_fluid_volume < 15){ IF_Venous_RIHP_Effect_int = 1- IF_Venous_RIHP_Effect_scale/2; IF_Venous_RIHP_Effect =(IF_Venous_RIHP_Effect_int+IF_Venous_RIHP_Effect_scale/(1+exp(-(renal_blood_flow_L_min_delayed-nom_renal_blood_flow_L_min)/IF_Venous_RIHP_Effect_slope))); }else{ IF_Venous_RIHP_Effect=1; } preaff_arteriole_signal_multiplier = AT1_effect_on_preaff*rsna_effect_on_preaff*preafferent_pressure_autoreg_signal*CCB_effect_on_preafferent_resistance; preaff_arteriole_adjusted_signal_multiplier = (1/(1+exp(preaff_signal_nonlin_scale*(1-preaff_arteriole_signal_multiplier)))+0.5); preafferent_arteriole_resistance = IF_Venous_RIHP_Effect*nom_preafferent_arteriole_resistance*preaff_arteriole_adjusted_signal_multiplier; afferent_arteriole_signal_multiplier = tubulo_glomerular_feedback_effect * AT1_effect_on_aff *glomerular_pressure_autoreg_signal*CCB_effect_on_afferent_resistance; afferent_arteriole_adjusted_signal_multiplier = (1/(1+exp(afferent_signal_nonlin_scale*(1-afferent_arteriole_signal_multiplier)))+0.5); afferent_arteriole_resistance = IF_Venous_RIHP_Effect*nom_afferent_arteriole_resistance*afferent_arteriole_adjusted_signal_multiplier*(1-ANP_effect_on_Arterial_Resistance); efferent_arteriole_signal_multiplier = AT1_effect_on_eff * CCB_effect_on_efferent_resistance; efferent_arteriole_adjusted_signal_multiplier = 1/(1+exp(efferent_signal_nonlin_scale*(1-efferent_arteriole_signal_multiplier)))+0.5; efferent_arteriole_resistance = IF_Venous_RIHP_Effect*nom_efferent_arteriole_resistance*efferent_arteriole_adjusted_signal_multiplier; RBF_autoreg_int = 1-RBF_autoreg_scale/2; peritubular_autoreg_signal = RBF_autoreg_int + RBF_autoreg_scale/(1+exp((nom_renal_blood_flow_L_min - renal_blood_flow_L_min_delayed)/RBF_autoreg_steepness)); autoregulated_peritubular_resistance = peritubular_autoreg_signal*nom_peritubular_resistance; renal_vascular_resistance = (preafferent_arteriole_resistance + (afferent_arteriole_resistance + efferent_arteriole_resistance) / number_of_functional_glomeruli + autoregulated_peritubular_resistance); renal_blood_flow_L_min = ((mean_arterial_pressure_MAP - P_venous) / renal_vascular_resistance); renal_blood_flow_ml_hr = renal_blood_flow_L_min * 1000 * 60; preafferent_pressure = mean_arterial_pressure_MAP - renal_blood_flow_L_min*preafferent_arteriole_resistance; glomerular_pressure = (mean_arterial_pressure_MAP - renal_blood_flow_L_min * (preafferent_arteriole_resistance + afferent_arteriole_resistance / number_of_functional_glomeruli)); postglomerular_pressure = (mean_arterial_pressure_MAP - renal_blood_flow_L_min * (preafferent_arteriole_resistance + (afferent_arteriole_resistance+efferent_arteriole_resistance) / number_of_functional_glomeruli)); preaff_autoreg_int = 1 - preaff_autoreg_scale/2; preafferent_pressure_autoreg_function = preaff_autoreg_int+preaff_autoreg_scale/(1+exp((nom_preafferent_pressure - preafferent_pressure)/myogenic_steepness)); gp_autoreg_int = 1 - gp_autoreg_scale/2; glomerular_pressure_autoreg_function = gp_autoreg_int+gp_autoreg_scale/(1+exp((nom_glomerular_pressure - glomerular_pressure)/myogenic_steepness)); GP_effect_increasing_Kf = (maximal_glom_surface_area_increase - disease_effects_increasing_Kf) * max(glomerular_pressure/(nom_glomerular_pressure+2) - 1,0) / (T_glomerular_pressure_increases_Kf/C_renal_CV_timescale); glomerular_hydrostatic_conductance_Kf = nom_Kf*(1+disease_effects_increasing_Kf)*(1-disease_effects_decreasing_Kf); net_filtration_pressure = glomerular_pressure - oncotic_pressure_difference - P_bowmans; if (net_filtration_pressure <= 0) { SNGFR_nL_min = 0.001; } else { SNGFR_nL_min = glomerular_hydrostatic_conductance_Kf * (glomerular_pressure - oncotic_pressure_difference - P_bowmans); } GFR = (SNGFR_nL_min / 1000 / 1000000 * number_of_functional_tubules); GFR_ml_min = GFR * 1000; filtration_fraction = GFR/renal_blood_flow_L_min; serum_creatinine_concentration = serum_creatinine/blood_volume_L; creatinine_clearance_rate = GFR_ml_min * dl_ml * serum_creatinine_concentration; GPdiff = max(0, glomerular_pressure - (nom_GP_seiving_damage)); GP_effect_on_Seiving = Emax_seiving * GPdiff ^ Gamma_seiving / (GPdiff ^ Gamma_seiving + Km_seiving ^ Gamma_seiving); nom_glomerular_albumin_sieving_coefficient = seiving_inf/(1-(1-seiving_inf)*exp(-c_albumin*SNGFR_nL_min)); glomerular_albumin_sieving_coefficient = nom_glomerular_albumin_sieving_coefficient*(1 + GP_effect_on_Seiving); SN_albumin_filtration_rate = plasma_albumin_concentration*SNGFR_nL_min*1e-6*glomerular_albumin_sieving_coefficient; SN_albumin_excretion_rate = max(0, SN_albumin_filtration_rate - SN_albumin_reabsorptive_capacity)+nom_albumin_excretion_rate; albumin_excretion_rate = SN_albumin_excretion_rate*number_of_functional_tubules; Oncotic_pressure_in = 1.629*plasma_protein_concentration+0.2935*(plasma_protein_concentration^2); SNRBF_nl_min = 1e6*1000*renal_blood_flow_L_min/number_of_functional_glomeruli; plasma_protein_concentration_out = (SNRBF_nl_min*plasma_protein_concentration-SN_albumin_filtration_rate)/(SNRBF_nl_min-SNGFR_nL_min); Oncotic_pressure_out = 1.629*plasma_protein_concentration_out+0.2935*(plasma_protein_concentration_out^2); oncotic_pressure_avg = (Oncotic_pressure_in+Oncotic_pressure_out)/2; Na_concentration = sodium_amount / blood_volume_L; IF_Na_concentration = IF_sodium_amount/interstitial_fluid_volume; sodium_storate_rate = Q_Na_store*((max_stored_sodium - stored_sodium)/max_stored_sodium)*(IF_Na_concentration - ref_Na_concentration); Na_water_controller = Na_controller_gain*(Kp_VP*(Na_concentration - ref_Na_concentration)+Ki_VP*Na_concentration_error); normalized_vasopressin_concentration = 1 + Na_water_controller; vasopressin_concentration = nominal_vasopressin_conc * normalized_vasopressin_concentration; water_intake_vasopressin_int = 1-water_intake_vasopressin_scale/2; water_intake = water_intake_species_scale*(nom_water_intake/60/24)*(water_intake_vasopressin_int + water_intake_vasopressin_scale/(1+exp((normalized_vasopressin_concentration_delayed-1)/water_intake_vasopressin_slope))); daily_water_intake = (water_intake * 24 * 60); L_pt_s1 = L_pt_s1_nom*(1+tubular_length_increase); L_pt_s2 = L_pt_s2_nom*(1+tubular_length_increase); L_pt_s3 = L_pt_s3_nom*(1+tubular_length_increase); Dc_pt = Dc_pt_nom*(1+tubular_diameter_increase); L_pt = L_pt_s1+L_pt_s2 + L_pt_s3; SN_filtered_Na_load = (SNGFR_nL_min / 1000 / 1000000)*Na_concentration; filtered_Na_load = SN_filtered_Na_load*number_of_functional_tubules; pressure_natriuresis_f_int = 1- pressure_natriuresis_f_scale/2; pressure_natriuresis_p_int = 1- pressure_natriuresis_p_scale/2; pressure_natriuresis_signal_f = ((pressure_natriuresis_f_int+pressure_natriuresis_f_scale/(1+exp(-(renal_blood_flow_L_min_delayed-nom_renal_blood_flow_L_min)/pressure_natriuresis_f_slope)))); pressure_natriuresis_signal_p =(pressure_natriuresis_p_int+pressure_natriuresis_p_scale/(1+exp(-(RIHP_delayed-RIHP0)/pressure_natriuresis_p_slope))); pressure_natriuresis_IF_int = 1- pressure_natriuresis_IF_scale/2; pessure_natriuresis_signal_IF = ((pressure_natriuresis_IF_int+pressure_natriuresis_IF_scale/(1+exp(-(Net_oncotic_pressure_diff-Nom_Net_oncotic_pressure_diff)/pressure_natriuresis_IF_slope)))); pressure_natriuresis_signal = pressure_natriuresis_signal_f*pressure_natriuresis_signal_p*pessure_natriuresis_signal_IF; pressure_natriuresis_PT_int = 1 - pressure_natriuresis_PT_scale/2; pressure_natriuresis_PT_effect = max(0.001,pressure_natriuresis_PT_int + pressure_natriuresis_PT_scale / (1 + exp(pressure_natriuresis_signal-1))); pressure_natriuresis_LoH_int = 1 - pressure_natriuresis_LoH_scale/2; pressure_natriuresis_LoH_effect = max(0.001,pressure_natriuresis_LoH_int + pressure_natriuresis_LoH_scale / (1 + exp((postglomerular_pressure_delayed - RIHP0) / pressure_natriuresis_LoH_slope))); pressure_natriuresis_DCT_magnitude = max(0,pressure_natriuresis_DCT_scale ); pressure_natriuresis_DCT_int = 1 - pressure_natriuresis_DCT_magnitude/2; pressure_natriuresis_DCT_effect = max(0.001,pressure_natriuresis_DCT_int + pressure_natriuresis_DCT_magnitude/ (1 + exp((postglomerular_pressure_delayed - RIHP0) / pressure_natriuresis_DCT_slope))); pressure_natriuresis_CD_magnitude = max(0,pressure_natriuresis_CD_scale *(1+disease_effects_decreasing_CD_PN)); pressure_natriuresis_CD_int = 1 - pressure_natriuresis_CD_magnitude/2; pressure_natriuresis_CD_effect = max(0.001,pressure_natriuresis_CD_int + pressure_natriuresis_CD_magnitude/ (1 + exp(pressure_natriuresis_signal-1))); AT1_PT_int = 1 - AT1_PT_scale/2; AT1_effect_on_PT = AT1_PT_int + AT1_PT_scale/(1+exp(-(AT1_bound_AngII - nominal_equilibrium_AT1_bound_AngII)/AT1_PT_slope)); rsna_PT_int = 1 - rsna_PT_scale/2; rsna_effect_on_PT = 1; rsna_CD_int = 1 - rsna_CD_scale/2; rsna_effect_on_CD= rsna_CD_int + rsna_CD_scale/(1+exp((1 - renal_sympathetic_nerve_activity)/rsna_CD_slope)); aldosterone_concentration = normalized_aldosterone_level* nominal_aldosterone_concentration; Aldo_MR_normalised_effect = normalized_aldosterone_level*(1 - pct_target_inhibition_MRA); aldo_DCT_int = 1 - aldo_DCT_scale/2; aldo_effect_on_DCT = aldo_DCT_int + aldo_DCT_scale/(1+exp((1 - Aldo_MR_normalised_effect)/aldo_DCT_slope)); aldo_CD_int = 1 - aldo_CD_scale/2; aldo_effect_on_CD= aldo_CD_int + aldo_CD_scale/(1+exp((1 - Aldo_MR_normalised_effect)/aldo_CD_slope)); NHE3inhib = Anhe3*RUGE_delayed; pt_multiplier = AT1_effect_on_PT * rsna_effect_on_PT *pressure_natriuresis_PT_effect*(1-NHE3inhib); e_pt_sodreab = min(1,nominal_pt_na_reabsorption_nonSGLT * pt_multiplier); e_dct_sodreab = min(1,nominal_dt_na_reabsorption * aldo_effect_on_DCT*pressure_natriuresis_DCT_effect ); cd_multiplier = aldo_effect_on_CD*rsna_effect_on_CD*pressure_natriuresis_CD_effect; cd_scale = max_cd_reabs_rate/nominal_cd_na_reabsorption-1; e_cd_sodreab = min(0.9999,nominal_cd_na_reabsorption*cd_multiplier*lambdaANP); glucose_reabs_per_unit_length_s1 = nom_glucose_reabs_per_unit_length_s1*diabetic_adaptation*SGLT2_inhibition_delayed*(1+RTg_compensation); glucose_reabs_per_unit_length_s2 = nom_glucose_reabs_per_unit_length_s2*diabetic_adaptation*SGLT2_inhibition_delayed*(1+RTg_compensation); glucose_reabs_per_unit_length_s3 = nom_glucose_reabs_per_unit_length_s3*diabetic_adaptation*(1+RTg_compensation)*SGLT1_inhibition; SN_filtered_glucose_load = glucose_concentration*SNGFR_nL_min / 1000 / 1000000; glucose_pt_out_s1 = max(0,SN_filtered_glucose_load-glucose_reabs_per_unit_length_s1*L_pt_s1); glucose_pt_out_s2 = max(0,glucose_pt_out_s1-glucose_reabs_per_unit_length_s2*L_pt_s2); glucose_pt_out_s3 = max(0,glucose_pt_out_s2-glucose_reabs_per_unit_length_s3*L_pt_s3); RUGE = glucose_pt_out_s3*number_of_functional_tubules*180; excess_glucose_increasing_RTg = (maximal_RTg_increase - RTg_compensation) * max(RUGE,0) / (T_glucose_RTg/C_renal_CV_timescale); osmotic_natriuresis_effect_pt = 1-min(1,RUGE *glucose_natriuresis_effect_pt); osmotic_natriuresis_effect_cd = 1-min(1,RUGE *glucose_natriuresis_effect_cd); osmotic_diuresis_effect_pt = 1-min(1,RUGE *glucose_diuresis_effect_pt); osmotic_diuresis_effect_cd = 1-min(1,RUGE *glucose_diuresis_effect_cd); SN_filtered_Na_load = (SNGFR_nL_min / 1000 / 1000000)*Na_concentration; SGTL2_Na_reabs_mmol_s1 = SN_filtered_glucose_load-glucose_pt_out_s1; SGTL2_Na_reabs_mmol_s2 = glucose_pt_out_s1-glucose_pt_out_s2; SGTL1_Na_reabs_mmol = 2*(glucose_pt_out_s2-glucose_pt_out_s3); total_SGLT_Na_reabs = SGTL2_Na_reabs_mmol_s1+SGTL2_Na_reabs_mmol_s2+SGTL1_Na_reabs_mmol; Na_reabs_per_unit_length = -log(1-e_pt_sodreab)/(L_pt_s1+L_pt_s2+L_pt_s3); Na_pt_s1_reabs = min(max_s1_Na_reabs, SN_filtered_Na_load*(1-exp(-Na_reabs_per_unit_length*L_pt_s1))); Na_pt_out_s1 = SN_filtered_Na_load - Na_pt_s1_reabs - SGTL2_Na_reabs_mmol_s1 ; Na_pt_s2_reabs = min(max_s2_Na_reabs, Na_pt_out_s1*(1-exp(-Na_reabs_per_unit_length*L_pt_s2))); Na_pt_out_s2 = Na_pt_out_s1 - Na_pt_s2_reabs - SGTL2_Na_reabs_mmol_s2; Na_pt_s3_reabs = min(max_s3_Na_reabs, Na_pt_out_s2*(1-exp(-Na_reabs_per_unit_length*L_pt_s3))); Na_pt_out_s3 = Na_pt_out_s2 - Na_pt_s3_reabs - SGTL1_Na_reabs_mmol; PT_Na_reabs_fraction = 1-Na_pt_out_s3/SN_filtered_Na_load; SN_filtered_urea_load = (SNGFR_nL_min / 1000 / 1000000)*plasma_urea; urea_out_s1 = SN_filtered_urea_load - urea_permeability_PT*(SN_filtered_urea_load/(0.5*((SNGFR_nL_min / 1000 / 1000000)+water_out_s1_delayed))-plasma_urea)*water_out_s1_delayed; urea_out_s2 = urea_out_s1 - urea_permeability_PT*(urea_out_s1/(0.5*(water_out_s1_delayed+water_out_s2_delayed))-plasma_urea)*water_out_s2_delayed; urea_out_s3 = urea_out_s2 - urea_permeability_PT*(urea_out_s2/(0.5*(water_out_s2_delayed+water_out_s3_delayed))-plasma_urea)*water_out_s3_delayed; urea_reabsorption_fraction = 1-urea_out_s3/SN_filtered_urea_load; osmoles_out_s1 = 2*Na_pt_out_s1 + glucose_pt_out_s1 + urea_out_s1; water_out_s1 = (((SNGFR_nL_min / 1000 / 1000000)/(2*SN_filtered_Na_load+SN_filtered_glucose_load+ SN_filtered_urea_load)))*osmoles_out_s1; osmoles_out_s2 = 2*Na_pt_out_s2 + glucose_pt_out_s2 + urea_out_s2; water_out_s2 = (water_out_s1/osmoles_out_s1)*osmoles_out_s2; osmoles_out_s3 = 2*Na_pt_out_s3 + glucose_pt_out_s3 + urea_out_s3; water_out_s3 = (water_out_s2/osmoles_out_s2)*osmoles_out_s3; PT_water_reabs_fraction = 1-water_out_s3/(SNGFR_nL_min / 1000 / 1000000); Na_concentration_out_s1 = Na_pt_out_s1/water_out_s1; Na_concentration_out_s2 = Na_pt_out_s2/water_out_s2; Na_concentration_out_s3 = Na_pt_out_s3/water_out_s3; glucose_concentration_out_s1 = glucose_pt_out_s1/water_out_s1; glucose_concentration_out_s2 = glucose_pt_out_s2/water_out_s2; glucose_concentration_out_s3 = glucose_pt_out_s3/water_out_s3; urea_concentration_out_s1 = urea_out_s1/water_out_s1; urea_concentration_out_s2 = urea_out_s2/water_out_s2; urea_concentration_out_s3 = urea_out_s3/water_out_s3; osmolality_out_s1 = osmoles_out_s1/water_out_s1; osmolality_out_s2 = osmoles_out_s2/water_out_s2; osmolality_out_s3 = osmoles_out_s3/water_out_s3; PT_Na_outflow = Na_pt_out_s3*number_of_functional_tubules; PT_Na_reab_perUnitSA = SN_filtered_Na_load*e_pt_sodreab/(3.14*Dc_pt*(L_pt_s1+L_pt_s2+L_pt_s3)); normalized_PT_reabsorption_density = PT_Na_reab_perUnitSA/PT_Na_reab_perUnitSA_0; PT_Na_reabs_effect_increasing_tubular_length = 0; PT_Na_reabs_effect_increasing_tubular_diameter = 0; water_in_DescLoH = water_out_s3; Na_in_DescLoH = Na_pt_out_s3; urea_in_DescLoH = urea_out_s3; glucose_in_DescLoH = glucose_pt_out_s3; osmoles_in_DescLoH = osmoles_out_s3; Na_concentration_in_DescLoH = Na_concentration_out_s3; Urea_concentration_in_DescLoH = urea_concentration_out_s3; glucose_concentration_in_DescLoH = glucose_concentration_out_s3; osmolality_in_DescLoH = osmoles_out_s3/water_out_s3; Na_out_DescLoH = Na_in_DescLoH; urea_out_DescLoH = urea_in_DescLoH; glucose_out_DescLoH = glucose_in_DescLoH; osmoles_out_DescLoH = osmoles_in_DescLoH; deltaLoH_NaFlow = min(max_deltaLoH_reabs,LoH_flow_dependence*(Na_out_DescLoH-nom_Na_in_AscLoH)); AscLoH_Reab_Rate =(2*nominal_loh_na_reabsorption*(nom_Na_in_AscLoH+deltaLoH_NaFlow)*loop_diuretic_effect)/L_lh_des; effective_AscLoH_Reab_Rate =AscLoH_Reab_Rate*pressure_natriuresis_LoH_effect; osmolality_out_DescLoH = osmolality_in_DescLoH*exp(min(effective_AscLoH_Reab_Rate*L_lh_des,2*Na_in_DescLoH)/(water_in_DescLoH*osmolality_in_DescLoH)); water_out_DescLoH = water_in_DescLoH*osmolality_in_DescLoH/osmolality_out_DescLoH; Na_concentration_out_DescLoH = Na_out_DescLoH/water_out_DescLoH; glucose_concentration_out_DescLoH = glucose_out_DescLoH/water_out_DescLoH; urea_concentration_out_DescLoH = urea_out_DescLoH/water_out_DescLoH; Na_in_AscLoH = Na_out_DescLoH; urea_in_AscLoH_before_secretion = urea_out_DescLoH; glucose_in_AscLoH = glucose_out_DescLoH; osmoles_in_AscLoH_before_secretion = osmoles_out_DescLoH; water_in_AscLoH = water_out_DescLoH; Na_concentration_in_AscLoH = Na_concentration_out_DescLoH; urea_in_AscLoH = urea_in_AscLoH_before_secretion + reabsorbed_urea_cd_delayed; urea_concentration_in_AscLoH = urea_in_AscLoH/water_out_DescLoH; osmoles_in_AscLoH = osmoles_in_AscLoH_before_secretion + reabsorbed_urea_cd_delayed; osmolality_in_AscLoH = osmoles_in_AscLoH/water_in_AscLoH; osmolality_out_AscLoH = osmolality_in_AscLoH - min(L_lh_des*effective_AscLoH_Reab_Rate, 2*Na_in_DescLoH)*(exp(min(L_lh_des*effective_AscLoH_Reab_Rate, 2*Na_in_DescLoH)/(water_in_DescLoH*osmolality_in_DescLoH))/water_in_DescLoH); osmoles_reabsorbed_AscLoH = (osmolality_in_AscLoH - osmolality_out_AscLoH)*water_in_AscLoH; Na_reabsorbed_AscLoH = osmoles_reabsorbed_AscLoH/2; Na_out_AscLoH = max(0,Na_in_AscLoH - Na_reabsorbed_AscLoH); urea_out_AscLoH = urea_in_AscLoH; glucose_out_AscLoH = glucose_in_AscLoH; water_out_AscLoH = water_in_AscLoH; osmoles_out_AscLoH = osmolality_out_AscLoH*water_out_AscLoH; Na_concentration_out_AscLoH = Na_out_AscLoH/water_out_AscLoH; glucose_concentration_out_AscLoH = glucose_out_AscLoH/water_out_AscLoH; urea_concentration_out_AscLoH = urea_out_AscLoH/water_out_AscLoH; LoH_reabs_fraction = 1-Na_out_AscLoH/Na_in_AscLoH; SN_macula_densa_Na_flow = Na_out_AscLoH; MD_Na_concentration = Na_concentration_out_AscLoH; TGF0_tubulo_glomerular_feedback = 1 - S_tubulo_glomerular_feedback/2; tubulo_glomerular_feedback_signal = (TGF0_tubulo_glomerular_feedback + S_tubulo_glomerular_feedback / (1 + exp((MD_Na_concentration_setpoint - MD_Na_concentration)/ F_md_scale_tubulo_glomerular_feedback))); water_in_DCT = water_out_AscLoH; Na_in_DCT = Na_out_AscLoH; urea_in_DCT = urea_out_AscLoH; glucose_in_DCT = glucose_out_AscLoH; osmoles_in_DCT = osmoles_out_AscLoH; Na_concentration_in_DCT = Na_concentration_out_AscLoH; urea_concentration_in_DCT = urea_concentration_out_AscLoH; glucose_concentration_in_DCT = glucose_concentration_out_AscLoH; osmolality_in_DCT = osmolality_out_AscLoH; urea_out_DCT = urea_in_DCT; glucose_out_DCT = glucose_in_DCT; water_out_DCT = water_in_DCT; urea_concentration_out_DCT = urea_out_DCT/water_out_DCT; glucose_concentration_out_DCT = glucose_out_DCT/water_out_DCT; R_dct = -log(1-e_dct_sodreab)/L_dct; Na_out_DCT = Na_in_DCT*exp(-R_dct*L_dct); Na_concentration_out_DCT = Na_out_DCT/water_out_DCT; osmolality_out_DCT = 2*Na_concentration_out_DCT + glucose_concentration_out_DescLoH + urea_concentration_in_AscLoH; osmoles_out_DCT = osmolality_out_DCT*water_out_DCT; DCT_Na_reabs_fraction = 1-Na_out_DCT/Na_in_DCT; Na_reabsorbed_DCT = Na_in_DCT - Na_out_DCT; water_in_CD = water_out_DCT; Na_in_CD = Na_out_DCT; urea_in_CD = urea_out_DCT; glucose_in_CD = glucose_out_DCT; osmoles_in_CD = osmoles_out_DCT; osmolality_in_CD = osmoles_in_CD/water_in_CD; Na_concentration_in_CD = Na_concentration_out_DCT; urea_concentration_in_CD = urea_concentration_out_DCT; glucose_concentration_in_CD = glucose_concentration_out_DCT; osmotic_diuresis_effect_cd = 1-min(1,RUGE *glucose_diuresis_effect_cd); e_cd_sodreab_adj = e_cd_sodreab*osmotic_natriuresis_effect_cd; R_cd = -log(1-e_cd_sodreab_adj)/L_cd; Na_reabsorbed_CD = min(Na_in_CD*(1-exp(-R_cd*L_cd)),CD_Na_reabs_threshold); Na_out_CD = Na_in_CD-Na_reabsorbed_CD; CD_Na_reabs_fraction = 1-Na_out_CD/Na_in_CD; Na_reabsorbed_CT=Na_in_CD-Na_out_CD; ADH_water_permeability_old = min(0.99999,max(0,nom_ADH_water_permeability*normalized_vasopressin_concentration)); ADH_water_permeability = normalized_vasopressin_concentration/(0.15+normalized_vasopressin_concentration); osmoles_out_CD = osmoles_in_CD-2*(Na_in_CD - Na_out_CD); osmolality_out_CD_before_osmotic_reabsorption = osmoles_out_CD/water_in_CD; water_reabsorbed_CD = ADH_water_permeability*osmotic_diuresis_effect_cd*water_in_CD*(1-osmolality_out_CD_before_osmotic_reabsorption/osmolality_out_DescLoH); water_out_CD = water_in_CD-water_reabsorbed_CD; Na_concentration_out_CD = Na_out_CD/water_out_CD; osmolality_out_CD_after_osmotic_reabsorption = osmoles_out_CD/water_out_CD; glucose_concentration_after_urea_reabsorption = glucose_in_CD/water_out_CD; urine_flow_rate = water_out_CD*number_of_functional_tubules; daily_urine_flow = (urine_flow_rate * 60 * 24); Na_excretion_via_urine = Na_out_CD*number_of_functional_tubules; Na_balance = Na_intake_rate - Na_excretion_via_urine; water_balance = daily_water_intake - daily_urine_flow; total_NA_reabsorbed = (total_SGLT_Na_reabs +Na_reabsorbed_AscLoH +Na_reabsorbed_DCT +Na_reabsorbed_CT )*number_of_functional_tubules; Na_concentration_average_PT = (Na_concentration_out_s1 + Na_concentration_out_s2+Na_concentration_out_s3)/3; Na_concentration_average_DescLoH = 0.5*(Na_concentration_in_DescLoH + Na_concentration_out_DescLoH); Na_concentration_average_AscLoH = 0.5*(Na_concentration_in_AscLoH + Na_concentration_out_AscLoH ); Na_concentration_average_DCT = 0.5*(Na_concentration_in_DCT + Na_concentration_out_DCT); Na_concentration_average_CD = 0.5*(Na_concentration_in_CD + Na_concentration_out_CD); Na_concentration_average_tubule = 0.2*(Na_concentration_average_PT+Na_concentration_average_DescLoH+Na_concentration_average_AscLoH+Na_concentration_average_DCT+Na_concentration_average_CD); Oncotic_pressure_tubule = Na_concentration_average_tubule*19.3*2; Na_amount_in_renal_interstitium = total_NA_reabsorbed; Na_concentration_renal_interstitium = Na_amount_in_renal_interstitium/(0.03831672); Oncotic_pressure_renal_interstitium = Na_concentration_renal_interstitium*19.3*2; Net_oncotic_pressure = Oncotic_pressure_tubule-Oncotic_pressure_renal_interstitium; FENA = Na_excretion_via_urine/filtered_Na_load; PT_fractional_glucose_reabs = (SN_filtered_glucose_load - glucose_pt_out_s3)/SN_filtered_glucose_load; PT_fractional_Na_reabs = (SN_filtered_Na_load - Na_pt_out_s3)/SN_filtered_Na_load; PT_fractional_urea_reabs = ( SN_filtered_urea_load - urea_out_s3)/SN_filtered_urea_load; PT_fractional_water_reabs = ((SNGFR_nL_min / 1000 / 1000000) - water_out_s3)/(SNGFR_nL_min / 1000 / 1000000); LoH_fractional_Na_reabs = (Na_in_DescLoH - Na_out_AscLoH)/Na_in_DescLoH; LoH_fractional_urea_reabs = (urea_in_DescLoH-urea_out_AscLoH)/urea_in_DescLoH; LoH_fractional_water_reabs = (water_in_DescLoH - water_out_AscLoH)/water_in_DescLoH; DCT_fractional_Na_reabs = (Na_in_DCT - Na_out_DCT)/Na_in_DCT; CD_fractional_Na_reabs = (Na_in_CD - Na_out_CD)/Na_in_CD; CD_OM_fractional_water_reabs = (water_in_CD - water_out_CD)/water_in_CD; Oncotic_pressure_peritubular_in = Oncotic_pressure_out; plasma_protein_concentration_peritubular_out = (SNRBF_nl_min)*plasma_protein_concentration/(SNRBF_nl_min-urine_flow_rate*1e6*1000/number_of_functional_glomeruli); Oncotic_pressure_peritubular_out = 1.629*plasma_protein_concentration_peritubular_out+0.2935*(plasma_protein_concentration_peritubular_out^2); oncotic_pressure_peritubular_avg = (Oncotic_pressure_peritubular_in+Oncotic_pressure_peritubular_out)/2; Na_concentration_peritubular_cap = (sodium_amount-filtered_Na_load)/blood_volume_L; oncotic_pressure_peritubular_cap_Na = 0; oncotic_pressure_peritubular = oncotic_pressure_peritubular_avg+oncotic_pressure_peritubular_cap_Na; tubular_reabsorption = GFR_ml_min/1000 - urine_flow_rate; Volume = interstitial_fluid_volume; volume_RIHP_int = 1- volume_RIHP_scale/2; IF_effect_RIHP = (volume_RIHP_int+volume_RIHP_scale/(1+exp(-(Volume-IF_nom)/volume_RIHP_slope))); oncotic_int = 1-IF_Interonvotic_Effect_scale/2; IF_effect_oncotic = (oncotic_int+IF_Interonvotic_Effect_scale/(1+exp((Volume-IF_nom)/IF_Interonvotic_Effect_slope))); Renal_plasma_amount= 2.5 * RISF_nom*0.01; RISF_plasma_protein_concentration = Renal_plasma_amount / (RISF*10); interstitial_oncotic_pressure = 1.629*RISF_plasma_protein_concentration+0.2935*(RISF_plasma_protein_concentration^2); RIHP = RISF/C_RISF; capillary_filtration = nom_peritubular_cap_Kf*(RIHP - postglomerular_pressure - (interstitial_oncotic_pressure -oncotic_pressure_peritubular)); mmHg_Nperm2_conv = 133.32; Pc_pt_s1 = Pc_pt_s1_mmHg*mmHg_Nperm2_conv; Pc_pt_s2 = Pc_pt_s2_mmHg*mmHg_Nperm2_conv; Pc_pt_s3 = Pc_pt_s3_mmHg*mmHg_Nperm2_conv; Pc_lh_des = Pc_lh_des_mmHg*mmHg_Nperm2_conv; Pc_lh_asc = Pc_lh_asc_mmHg*mmHg_Nperm2_conv; Pc_dt = Pc_dt_mmHg*mmHg_Nperm2_conv; Pc_cd = Pc_cd_mmHg*mmHg_Nperm2_conv; P_interstitial = (RIHP)*mmHg_Nperm2_conv; pi=3.14; B1 = (4*tubular_compliance+1)*128*gamma/pi; mean_cd_water_flow = (water_in_CD-water_out_CD)/2; B2_cd = (Pc_cd^(4*tubular_compliance))/(Dc_cd^4); P_in_cd = (0^(4*tubular_compliance+1)+B1*B2_cd*(mean_cd_water_flow/1e3)*L_cd)^(1/(4*tubular_compliance+1)); P_in_cd_mmHg = (P_in_cd+P_interstitial)/mmHg_Nperm2_conv; B2_dt = (Pc_dt^(4*tubular_compliance))/(Dc_dt^4); P_in_dt = (P_in_cd^(4*tubular_compliance+1)+B1*B2_dt*(water_in_DCT/1e3)*L_dct)^(1/(4*tubular_compliance+1)); P_in_dt_mmHg = (P_in_dt+P_interstitial)/mmHg_Nperm2_conv; B2_lh_asc = (Pc_lh_asc^(4*tubular_compliance))/(Dc_lh^4); P_in_lh_asc = (P_in_dt^(4*tubular_compliance+1)+B1*B2_lh_asc*(water_in_AscLoH/1e3)*L_lh_asc)^(1/(4*tubular_compliance+1)); P_in_lh_asc_mmHg = (P_in_lh_asc+P_interstitial)/mmHg_Nperm2_conv; A_lh_des = effective_AscLoH_Reab_Rate/(water_in_DescLoH*osmolality_in_DescLoH); B2_lh_des = (Pc_lh_des^(4*tubular_compliance))*(water_in_DescLoH/1e3)/((Dc_lh^4)*A_lh_des); P_in_lh_des = (P_in_lh_asc^(4*tubular_compliance+1)+B1*B2_lh_des*(1-exp(-A_lh_des*L_lh_des)))^(1/(4*tubular_compliance+1)); P_in_lh_des_mmHg = (P_in_lh_des+P_interstitial)/mmHg_Nperm2_conv; Rurea = (SN_filtered_urea_load - urea_out_s3)/(L_pt_s1+L_pt_s2+L_pt_s3); urea_in_s2 = SN_filtered_urea_load - Rurea*L_pt_s1; urea_in_s3 = SN_filtered_urea_load - Rurea*(L_pt_s1+L_pt_s2); A_na = Na_reabs_per_unit_length; flow_integral_s3 = 2*(Na_pt_out_s2/A_na)*(1-exp(-A_na*L_pt_s3)) - (3/2)*glucose_pt_out_s2*L_pt_s3^2 + urea_in_s3*L_pt_s3 - (1/2)*Rurea*(L_pt_s3^2); flow_integral_s2 = 2*(Na_pt_out_s1/A_na)*(1-exp(-A_na*L_pt_s2)) - (1/2)*glucose_pt_out_s1*L_pt_s2^2 + urea_in_s2*L_pt_s2 - (1/2)*Rurea*(L_pt_s2^2); flow_integral_s1 = 2*(SN_filtered_Na_load/A_na)*(1-exp(-A_na*L_pt_s1)) - (1/2)*SN_filtered_glucose_load*L_pt_s1^2 + SN_filtered_urea_load*L_pt_s1 - (1/2)*Rurea*(L_pt_s1^2); B2_pt_s3 = (Pc_pt_s3^(4*tubular_compliance))/(Dc_pt^4); B3_pt_s3 = (water_out_s2/1e3)/osmoles_out_s2; P_in_pt_s3= (P_in_lh_des^(4*tubular_compliance+1)+B1*B2_pt_s3*B3_pt_s3*flow_integral_s3)^(1/(4*tubular_compliance+1)); P_in_pt_s3_mmHg = (P_in_pt_s3+P_interstitial)/mmHg_Nperm2_conv; B2_pt_s2 = (Pc_pt_s3^(4*tubular_compliance))/(Dc_pt^4); B3_pt_s2 = (water_out_s1/1e3)/osmoles_out_s1; P_in_pt_s2= (P_in_pt_s3^(4*tubular_compliance+1)+B1*B2_pt_s2*B3_pt_s2*flow_integral_s2)^(1/(4*tubular_compliance+1)); P_in_pt_s2_mmHg = (P_in_pt_s2+P_interstitial)/mmHg_Nperm2_conv; B2_pt_s1 = (Pc_pt_s1^(4*tubular_compliance))/(Dc_pt^4); B3_pt_s1 = (SNGFR_nL_min / 1e12)/(2*SN_filtered_Na_load+SN_filtered_glucose_load+ SN_filtered_urea_load); P_in_pt_s1= (P_in_pt_s2^(4*tubular_compliance+1)+B1*B2_pt_s1*B3_pt_s1*flow_integral_s1)^(1/(4*tubular_compliance+1)); P_in_pt_s1_mmHg = (P_in_pt_s1+P_interstitial)/mmHg_Nperm2_conv; AT1_aldo_int = 1 - AT1_aldo_slope*nominal_equilibrium_AT1_bound_AngII; AngII_effect_on_aldo = AT1_aldo_int + AT1_aldo_slope*AT1_bound_AngII; N_als = (K_Na_ratio_effect_on_aldo * AngII_effect_on_aldo ); rsna_renin_intercept = 1-rsna_renin_slope; rnsa_effect_on_renin_secretion = rsna_renin_slope * renal_sympathetic_nerve_activity + rsna_renin_intercept; md_effect_on_renin_secretion = md_renin_A*exp(-md_renin_tau*(SN_macula_densa_Na_flow_delayed*baseline_nephrons - nom_LoH_Na_outflow)); AT1_bound_AngII_effect_on_PRA = (10 ^ (AT1_PRC_slope * log10(AT1_bound_AngII / nominal_equilibrium_AT1_bound_AngII) + AT1_PRC_yint)); aldo_renin_intercept = 1-aldo_renin_slope; aldo_effect_on_renin_secretion = aldo_renin_intercept + aldo_renin_slope*Aldo_MR_normalised_effect; plasma_renin_activity = concentration_to_renin_activity_conversion_plasma* plasma_renin_concentration*(1-pct_target_inhibition_DRI); renin_secretion_rate = (log(2)/renin_half_life)*nominal_equilibrium_PRC*AT1_bound_AngII_effect_on_PRA*md_effect_on_renin_secretion*HCTZ_effect_on_renin_secretion*aldo_effect_on_renin_secretion*BB_renin_secretion_effect; renin_degradation_rate = log(2)/renin_half_life; AngI_degradation_rate = log(2)/AngI_half_life; AngII_degradation_rate = log(2)/AngII_half_life; AT1_bound_AngII_degradation_rate = log(2)/AT1_bound_AngII_half_life; AT2_bound_AngII_degradation_rate = log(2)/AT2_bound_AngII_half_life; ACE_activity = nominal_ACE_activity*(1 - pct_target_inhibition_ACEi); chymase_activity = nominal_chymase_activity; AT1_receptor_binding_rate = nominal_AT1_receptor_binding_rate*(1 - pct_target_inhibition_ARB); AT2_receptor_binding_rate = nominal_AT2_receptor_binding_rate; Blood_volume_protein_osmotic_pressure = 1.629*plasma_protein_concentration + 0.2935*plasma_protein_concentration^2; ISF_protein_osmotic_pressure = 1.629*ISF_protein_concentration + 0.2935*ISF_protein_concentration^2; Blood_volume_osmotic_pressure = Blood_volume_protein_osmotic_pressure+ Na_concentration*19.3*2; ISF_osmotic_pressire = IF_Na_concentration*19.3*2 + ISF_protein_osmotic_pressure; Protein_sodium_filtration_pressure_grad = (mean_capillary_pressure - ISF_pressure - Blood_volume_osmotic_pressure + ISF_osmotic_pressire); Kidney_disconnect_heart = Q_water*(Na_concentration - IF_Na_concentration); Kidney_connect_heart = -Sodium_protein_filtration_rate_Kf*(Protein_sodium_filtration_pressure_grad)*0.001; if (heart_renal_link == 1) { Fluid_exchanging_function=Kidney_connect_heart; } else{ Fluid_exchanging_function=Kidney_connect_heart; } peripheral_volume_change=arterial_dis_circulation_volume+capillary_circulation_volume+venules_circulation_volume; d/dt(venous_volume) = venous_flow + C_renal_CV_timescale*(venous_volume_target - venous_volume) - tricuspid_valve_flow_rate ; d/dt(LV_volume) = mitral_valve_flow_rate - aortic_valve_flow_rate; d/dt(arterial_volume) = (aortic_valve_flow_rate) - (systemic_blood_flow); d/dt(RV_volume) = (tricuspid_valve_flow_rate) - (pulmonary_valve_flow_rate); d/dt(pulmonary_arterial_volume) = pulmonary_valve_flow_rate - pulmonary_arterial_blood_flow; d/dt(arterial_dis_circulation_volume)=systemic_blood_flow - capillary_blood_flow; d/dt(capillary_circulation_volume)=arterial_dis_blood_flow-venules_blood_flow; d/dt(venules_circulation_volume)=capillary_blood_flow-venous_flow; d/dt(pulmonary_venous_volume) = pulmonary_arterial_blood_flow - mitral_valve_flow_rate; d/dt(aortic_blood_flow_delayed) = C_cycle2 * (aortic_blood_flow - aortic_blood_flow_delayed); d/dt(pulmonary_blood_flow_delayed) = C_cycle2 * (pulmonary_blood_flow - pulmonary_blood_flow_delayed); d/dt(change_in_myocyte_length) = kL_hypertrophy * (LV_EDS / LV_passive_stress_along_fiber_threshhold - 1); d/dt(change_in_myocyte_diameter) = kD_hypertrophy * (LV_active_stress_peak / LV_active_stress_threshhold - 1); d/dt(LV_active_stress_peak) = C_cycle3 *(LV_active_stress_peak_old - LV_active_stress_peak); d/dt(sim_time)=1; d/dt(LV_sarcomere_length_delayed) = C_cycle* (LV_sarcomere_length - LV_sarcomere_length_delayed); d/dt(RV_sarcomere_length_delayed) = C_cycle* (RV_sarcomere_length - RV_sarcomere_length_delayed); d/dt(LV_EDV) = C_cycle2 * (LV_EDV_old - LV_EDV); d/dt(LV_EDP) = C_cycle2 *(LV_EDP_old - LV_EDP); d/dt(LV_EDS) = C_cycle2 *(LV_EDS_old - LV_EDS); d/dt(arterial_pressure_delayed) = C_cycle2 * (arterial_pressure - arterial_pressure_delayed); d/dt(arterial_pressure_bigger_delay) = C_cycle2 * (arterial_pressure_delayed - arterial_pressure_bigger_delay); d/dt(systolic_pressure) = C_cycle2 * (systolic_pressure_old - systolic_pressure); d/dt(diastolic_pressure) = C_cycle2 * (diastolic_pressure_old - diastolic_pressure); d/dt(venous_pressure_delayed)=C_cycle2*(venous_pressure-venous_pressure_delayed); d/dt(venous_pressure_bigger_delay)=C_cycle2*(venous_pressure_delayed-venous_pressure_bigger_delay); d/dt(venous_systolic_pressure)=C_cycle2*(venous_systolic_pressure_old-venous_systolic_pressure); d/dt(venous_diastolic_pressure)=C_cycle2*(venous_diastolic_pressure_old-venous_diastolic_pressure); d/dt(mean_venous_pressure_delayed) = 1*(mean_venous_pressure - mean_venous_pressure_delayed); d/dt(capillary_pressure_delayed)=C_cycle2*(capillary_pressure-capillary_pressure_delayed); d/dt(capillary_pressure_bigger_delay)=C_cycle2*(capillary_pressure_delayed-capillary_pressure_bigger_delay); d/dt(capillary_systolic_pressure)=C_cycle2*(capillary_systolic_pressure_old-capillary_systolic_pressure); d/dt(capillary_diastolic_pressure)=C_cycle2*(capillary_diastolic_pressure_old-capillary_diastolic_pressure); d/dt(mean_capillary_pressure_delayed) = 1*(mean_capillary_pressure - mean_capillary_pressure_delayed); d/dt(CO) = C_co*(aortic_valve_flow_rate*60/L_m3 - CO); d/dt(CO_delayed) = C_co_delay*(CO - CO_delayed); d/dt(AngI) = plasma_renin_activity - (AngI) * (chymase_activity + ACE_activity) - (AngI) * AngI_degradation_rate; d/dt(AngII) = AngI * (chymase_activity + ACE_activity) - AngII * AngII_degradation_rate - AngII*AT1_receptor_binding_rate - AngII* (AT2_receptor_binding_rate); d/dt(AT1_bound_AngII) = AngII * (AT1_receptor_binding_rate) - AT1_bound_AngII_degradation_rate*AT1_bound_AngII; d/dt(AT2_bound_AngII) = AngII * (AT2_receptor_binding_rate) - AT2_bound_AngII_degradation_rate*AT2_bound_AngII; d/dt(plasma_renin_concentration) = renin_secretion_rate - plasma_renin_concentration * renin_degradation_rate; d/dt(blood_volume_L) = C_renal_CV_timescale *(water_intake- urine_flow_rate+Fluid_exchanging_function); d/dt(interstitial_fluid_volume) = -C_renal_CV_timescale *Fluid_exchanging_function; d/dt(sodium_amount) = C_renal_CV_timescale * (Na_intake_rate - Na_excretion_via_urine + Q_Na*(IF_Na_concentration - Na_concentration)); d/dt(IF_sodium_amount) = C_renal_CV_timescale *(Q_Na*(Na_concentration - IF_Na_concentration) - sodium_storate_rate); d/dt(stored_sodium) = C_renal_CV_timescale *sodium_storate_rate; d/dt(tubulo_glomerular_feedback_effect) = C_renal_CV_timescale *(tubulo_glomerular_feedback_signal-tubulo_glomerular_feedback_effect); d/dt(normalized_aldosterone_level) = C_renal_CV_timescale *C_aldo_secretion * (N_als-normalized_aldosterone_level); d/dt(preafferent_pressure_autoreg_signal) = C_renal_CV_timescale *100*(preafferent_pressure_autoreg_function - preafferent_pressure_autoreg_signal); d/dt(glomerular_pressure_autoreg_signal) = 0; d/dt(CO_error) = C_renal_CV_timescale*C_co_error*(CO_delayed-CO_nom); d/dt(Na_concentration_error) = C_renal_CV_timescale *C_Na_error*(Na_concentration - ref_Na_concentration); d/dt(normalized_vasopressin_concentration_delayed)= C_renal_CV_timescale *C_vasopressin_delay*(normalized_vasopressin_concentration - normalized_vasopressin_concentration_delayed); d/dt(F0_TGF) = C_renal_CV_timescale *C_tgf_reset*(SN_macula_densa_Na_flow*baseline_nephrons - F0_TGF); d/dt(P_bowmans) = C_renal_CV_timescale *100*(P_in_pt_s1_mmHg - P_bowmans); d/dt(oncotic_pressure_difference) = 100*(oncotic_pressure_avg - oncotic_pressure_difference); d/dt(renal_blood_flow_L_min_delayed)=C_renal_CV_timescale*C_rbf*(renal_blood_flow_L_min - renal_blood_flow_L_min_delayed); d/dt(SN_macula_densa_Na_flow_delayed) = C_renal_CV_timescale * C_md_flow*( SN_macula_densa_Na_flow - SN_macula_densa_Na_flow_delayed); d/dt(rsna_delayed) = C_renal_CV_timescale *C_rsna*(renal_sympathetic_nerve_activity - rsna_delayed); d/dt(disease_effects_increasing_Kf) = GP_effect_increasing_Kf; d/dt(disease_effects_decreasing_CD_PN) = CD_PN_loss_rate; d/dt(tubular_length_increase) = PT_Na_reabs_effect_increasing_tubular_length; d/dt(tubular_diameter_increase) = PT_Na_reabs_effect_increasing_tubular_diameter; d/dt(water_out_s1_delayed) = C_renal_CV_timescale * C_pt_water*(water_out_s1 - water_out_s1_delayed); d/dt(water_out_s2_delayed) = C_renal_CV_timescale * C_pt_water*(water_out_s2 - water_out_s2_delayed); d/dt(water_out_s3_delayed) = C_renal_CV_timescale * C_pt_water*(water_out_s3 - water_out_s3_delayed); d/dt(reabsorbed_urea_cd_delayed) = 0; d/dt(UGE) = C_renal_CV_timescale * RUGE; d/dt(serum_creatinine) = C_renal_CV_timescale*(creatinine_synthesis_rate - creatinine_clearance_rate); d/dt(cumNaExcretion) = C_renal_CV_timescale*Na_excretion_via_urine; d/dt(cumWaterExcretion) = C_renal_CV_timescale*urine_flow_rate; d/dt(cumCreatinineExcretion) = C_renal_CV_timescale*creatinine_clearance_rate; d/dt(RTg_compensation) = C_renal_CV_timescale*excess_glucose_increasing_RTg; d/dt(SGLT2_inhibition_delayed) = C_renal_CV_timescale*C_sglt2_delay*(SGLT2_inhibition - SGLT2_inhibition_delayed); d/dt(RUGE_delayed) = C_renal_CV_timescale*C_ruge*(RUGE - RUGE_delayed); d/dt(postglomerular_pressure_delayed) = C_renal_CV_timescale*C_postglomerular_pressure*(postglomerular_pressure - postglomerular_pressure_delayed); d/dt(postglomerular_pressure_error) = C_renal_CV_timescale*(postglomerular_pressure - RIHP0); d/dt(renal_flow_rate_error) = C_renal_CV_timescale*(renal_blood_flow_L_min - nom_renal_blood_flow_L_min); d/dt(MAP_delayed) = C_renal_CV_timescale*C_cycle2*(mean_arterial_pressure_MAP - MAP_delayed); d/dt(RIHP_delayed)=C_renal_CV_timescale*C_cycle2*(RIHP - RIHP_delayed); d/dt(Net_oncotic_pressure_diff) = C_renal_CV_timescale*C_cycle2*(Net_oncotic_pressure - Net_oncotic_pressure_diff); d/dt(RISF) = tubular_reabsorption - capillary_filtration; ") test_that("large models compile", { expect_true(inherits(mod, "RxODE")) }) }, test = "lvl2" )
context(".generate_partitions") test_that("num_tfs_sampler works as expected", { num_tfs <- 90 num_modules <- 8 samples <- map( seq_len(5000), ~ .generate_partitions(num_tfs, num_modules, min_elements_per_group = 1) ) expect_true(all(map_int(samples, length) == num_modules)) expect_true(all(map_int(samples, sum) == num_tfs)) expect_true(all(map_int(samples, min) >= 1)) avg <- Reduce("+", samples) / length(samples) exp <- num_tfs / num_modules expect_equal(mean(avg), exp, tolerance = 0.1) }) test_that("num_tfs_sampler works as expected", { num_tfs <- 200 num_modules <- 13 samples <- map( seq_len(1000), ~ .generate_partitions(num_tfs, num_modules, min_elements_per_group = 1) ) expect_true(all(map_int(samples, length) == num_modules)) expect_true(all(map_int(samples, sum) == num_tfs)) expect_true(all(map_int(samples, min) >= 1)) avg <- Reduce("+", samples) / length(samples) exp <- num_tfs / num_modules expect_equal(mean(avg), exp, tolerance = 0.1) }) test_that("num_tfs_sampler works as expected", { num_tfs <- 1000 num_modules <- 8 samples <- map( seq_len(1000), ~ .generate_partitions(num_tfs, num_modules, min_elements_per_group = 1) ) expect_true(all(map_int(samples, length) == num_modules)) expect_true(all(map_int(samples, sum) == num_tfs)) expect_true(all(map_int(samples, min) >= 1)) avg <- Reduce("+", samples) / length(samples) exp <- num_tfs / num_modules expect_equal(mean(avg), exp, tolerance = 0.1) }) test_that("num_tfs_sampler works as expected", { expect_equal(.generate_partitions(50, 10, 5), rep(5, 10)) })
xgx_breaks_time <- function(data_range, units_plot, number_breaks = 5) { data_min <- min(data_range) data_max <- max(data_range) data_span <- data_max - data_min number_breaks <- 5 preferred_increment_default <- c(1, 5, 2, 4, 3, 1) weights_default <- c(0.25, 0.2, 0.5, 0.05) weights_simple <- c(1, 0.2, 0.5, 0.05) if (units_plot %in% c("h", "m") && data_span >= 48) { preferred_increment <- c(24, 12, 6, 3) weights <- weights_simple } else if (units_plot %in% c("h", "m") && data_span >= 24) { preferred_increment <- c(3, 12, 6, 2) weights <- weights_simple } else if (units_plot %in% c("h", "m") && data_span < 24) { preferred_increment <- c(6, 3, 2, 1) weights <- weights_simple } else if (units_plot == "d" && data_span >= 12) { preferred_increment <- c(7, 14, 28) weights <- weights_simple } else { preferred_increment <- preferred_increment_default weights <- weights_default } breaks <- labeling::extended(data_min, data_max, m = number_breaks, Q = preferred_increment, w = weights) return(breaks) }
praise <- function() { plain <- c( "You rock!", "You are a coding rockstar!", "Keep up the good work.", "Woot!", "Way to go!", "Nice code.", praise::praise("Your tests are ${adjective}!"), praise::praise("${EXCLAMATION} - ${adjective} code.") ) utf8 <- c( "\U0001f600", "\U0001f973", "\U0001f638", paste0(strrep("\U0001f389\U0001f38a", 5), "\U0001f389"), "\U0001f485 Your tests are beautiful \U0001f485", "\U0001f947 Your tests deserve a gold medal \U0001f947", "\U0001f308 Your tests are over the rainbow \U0001f308", "\U0001f9ff Your tests look perfect \U0001f9ff", "\U0001f3af Your tests hit the mark \U0001f3af", "\U0001f41d Your tests are the bees knees \U0001f41d", "\U0001f4a3 Your tests are da bomb \U0001f4a3", "\U0001f525 Your tests are lit \U0001f525" ) x <- if (cli::is_utf8_output()) c(plain, utf8) else plain sample(x, 1) } praise_emoji <- function() { if (!cli::is_utf8_output()) { return("") } emoji <- c( "\U0001f600", "\U0001f973", "\U0001f638", "\U0001f308", "\U0001f947", "\U0001f389", "\U0001f38a" ) sample(emoji, 1) } encourage <- function() { x <- c( "Keep trying!", "Don't worry, you'll get it.", "No one is perfect!", "No one gets it right on their first try", "Frustration is a natural part of programming :)", "I believe in you!" ) sample(x, 1) }
source("test.prolog.R") options(warn=1) library(earth) cat("loading parsnip libraries\n") library(tidymodels) library(timetk) library(lubridate) cat("loaded parsnip libraries\n") cat("parsnip version:", as.character(packageVersion("parsnip")[[1]]), "\n") vdata <- data.frame( resp = 1:23, bool = c(F, F, F, F, F, T, T, T, T, T, T, T, T, F, F, T, T, T, T, T, T, T, T), ord = ordered(c("ORD1", "ORD1", "ORD1", "ORD1", "ORD1", "ORD1", "ORD1", "ORD3", "ORD1", "ORD2", "ORD2", "ORD2", "ORD2", "ORD2", "ORD2", "ORD2", "ORD3", "ORD3", "ORD3", "ORD2", "ORD2", "ORD2", "ORD2"), levels=c("ORD1", "ORD3", "ORD2")), fac = as.factor(c("FAC1", "FAC1", "FAC1", "FAC2", "FAC2", "FAC2", "FAC3", "FAC1", "FAC1", "FAC1", "FAC2", "FAC2", "FAC2", "FAC2", "FAC2", "FAC2", "FAC3", "FAC3", "FAC3", "FAC1", "FAC3", "FAC3", "FAC3")), str = c("STR1", "STR1", "STR1", "STR1", "STR1", "STR1", "STR2", "STR2", "STR2", "STR3", "STR3", "STR2", "STR3", "STR2", "STR3", "STR2", "STR3", "STR3", "STR3", "STR3", "STR3", "STR3", "STR3"), num = c(1, 9, 2, 3, 14, 5, 6, 4, 5, 6.5, 3, 6, 5, 3, 4, 5, 6, 4, 5, 16.5, 3, 16, 15), sqrt_num = sqrt( c(1, 9, 2, 3, 14, 5, 6, 4, 5, 6.5, 3, 6, 5, 3, 4, 5, 6, 4, 5, 16.5, 3, 16, 15)), int = c(1L, 1L, 3L, 3L, 4L, 4L, 3L, 5L, 3L, 6L, 7L, 8L, 10L, 13L, 14L, 3L, 13L, 5L, 13L, 16L, 17L, 18L, 11L), date = as.Date( c("2018-08-01", "2018-08-02", "2018-08-03", "2018-08-04", "2018-08-05", "2018-08-06", "2018-08-07", "2018-08-08", "2018-08-08", "2018-08-10", "2018-08-10", "2018-08-11", "2018-08-11", "2018-08-11", "2018-08-12", "2018-08-13", "2018-08-10", "2018-08-15", "2018-08-17", "2018-08-04", "2018-08-19", "2018-08-03", "2018-08-18")), date_num = as.numeric(as.Date( c("2018-08-01", "2018-08-02", "2018-08-03", "2018-08-04", "2018-08-05", "2018-08-06", "2018-08-07", "2018-08-08", "2018-08-08", "2018-08-10", "2018-08-10", "2018-08-11", "2018-08-11", "2018-08-11", "2018-08-12", "2018-08-13", "2018-08-10", "2018-08-15", "2018-08-17", "2018-08-04", "2018-08-19", "2018-08-03", "2018-08-18")))) set.seed(2020) splits <- initial_time_split(vdata, prop=.9) lm1 <- lm(resp~num+fac:int+date+ord+str, data=training(splits)) cat("lm1:\n") print(summary(lm1)) set.seed(2020) lmpar <- linear_reg(mode = "regression") %>% set_engine("lm") %>% fit(resp~num+fac:int+date+ord+str, data = training(splits)) stopifnot(identical(lm1$coeff, lmpar$fit$coeff)) predict.lm1 <- predict(lm1, testing(splits)) predict.lmpar <- lmpar %>% predict(testing(splits)) stopifnot(all(predict.lm1 == predict.lmpar)) par(mfrow = c(3, 3), mar = c(3, 3, 3, 1), mgp = c(1.5, 0.5, 0)) plotmo(lm1, do.par=2, SHOWCALL=TRUE) plotres(lm1, which=c(3,1), do.par=FALSE) plotmo(lmpar, do.par=2, SHOWCALL=TRUE) plotres(lmpar, which=c(3,1), do.par=FALSE) plotmo(lmpar$fit, do.par=2, SHOWCALL=TRUE) plotres(lmpar$fit, which=c(3,1), do.par=FALSE) par(org.par) lmpar.sqrtnum <- linear_reg(mode = "regression") %>% set_engine("lm") %>% fit(resp~sqrt(num), data = training(splits)) expect.err(try(plotmo(lmpar.sqrtnum)), "cannot get the original model predictors") earth1 <- earth(resp~sqrt(num)+int+ord:bool+fac+str+date, degree=2, data=training(splits), pmethod="none") cat("earth1:\n") print(summary(earth1)) set.seed(2020) earthpar <- mars(mode = "regression", prune_method="none", prod_degree=2) %>% set_engine("earth") %>% fit(resp~sqrt(num)+int+ord:bool+fac+str+date, data = training(splits)) cat("earthpar:\n") print(earthpar) cat("summary(earthpar$fit)\n") print(summary(earthpar$fit)) stopifnot(identical(earth1$coeff, earthpar$fit$coeff)) predict.earth1 <- predict(earth1, testing(splits)) predict.earthpar <- earthpar %>% predict(testing(splits)) stopifnot(all(predict.earth1 == predict.earthpar)) par(mfrow = c(3, 3), mar = c(3, 3, 3, 1), mgp = c(1.5, 0.5, 0)) plotmo(earth1, do.par=2, pt.col=3, SHOWCALL=TRUE) set.seed(2020) plotres(earth1, which=c(1,3), do.par=FALSE, pt.col=3, legend.pos="topleft") par(org.par) par(mfrow = c(3, 3), mar = c(3, 3, 3, 1), mgp = c(1.5, 0.5, 0)) plotmo(earthpar, do.par=2, pt.col=3, SHOWCALL=TRUE) set.seed(2020) plotres(earthpar, which=c(1,3), do.par=FALSE, pt.col=3, legend.pos="topleft") par(org.par) par(mfrow = c(3, 3), mar = c(3, 3, 3, 1), mgp = c(1.5, 0.5, 0)) plotmo(earthpar$fit, do.par=2, pt.col=3, SHOWCALL=TRUE) set.seed(2020) plotres(earthpar$fit, which=c(1,3), do.par=FALSE, pt.col=3, legend.pos="topleft") par(org.par) library(rpart) library(rpart.plot) rpart1 <- rpart(resp~num+fac+int+date+ord+str, data=training(splits), control=rpart.control(minsplit=1, cp=.0001)) cat("\nrpart.rules(rpart1)\n") print(rpart.rules(rpart1)) set.seed(2020) rpartpar <- decision_tree(mode = "regression", min_n=1, cost_complexity=.0001) %>% set_engine("rpart", model=TRUE) %>% fit(resp~num+fac+int+date+ord+str, data = training(splits)) cat("\nrpart.rules(rpartpar$fit)\n") print(rpart.rules(rpartpar$fit)) predict.rpart1 <- predict(rpart1, testing(splits)) predict.rpartpar <- rpartpar %>% predict(testing(splits)) stopifnot(all(predict.rpart1 == predict.rpartpar)) par(mfrow = c(3, 3), mar = c(3, 3, 3, 1), mgp = c(1.5, 0.5, 0)) plotmo(rpart1, do.par=2, SHOWCALL=TRUE, trace=0) plotres(rpart1, which=c(3,1), do.par=FALSE) plotmo(rpartpar, do.par=2, SHOWCALL=TRUE, trace=0) plotres(rpartpar, which=c(3,1), do.par=FALSE) plotmo(rpartpar$fit, do.par=2, SHOWCALL=TRUE) plotres(rpartpar$fit, which=c(3,1), do.par=FALSE) par(org.par) rpartpar.nosavemodel <- decision_tree(mode = "regression", min_n=1, cost_complexity=.0001) %>% set_engine("rpart") %>% fit(resp~num+fac+int+date+str, data = training(splits)) cat("\nrpart.rules(rpartpar.nosavemodel$fit)\n") options(warn=2) expect.err(try(rpart.rules(rpartpar.nosavemodel$fit)), "Cannot retrieve the data used to build the model") options(warn=1) expect.err(try(plotmo(rpartpar.nosavemodel)), "Cannot plot parsnip rpart model: need model=TRUE in call to rpart") rpart.sqrtnum <- decision_tree(mode = "regression", min_n=1, cost_complexity=.0001) %>% set_engine("rpart", model=TRUE) %>% fit(resp~sqrt(num)+fac+int+date+ord+str, data = training(splits)) cat("\nrpart.rules(rpart.sqrtnum$fit)\n") print(rpart.rules(rpart.sqrtnum$fit)) expect.err(try(plotmo(rpart.sqrtnum)), "cannot get the original model predictors") cat("===m750a first example===\n") set.seed(2020) m750a <- m4_monthly %>% filter(id == "M750") %>% select(-id) print(m750a) set.seed(2020) splits_a <- initial_time_split(m750a, prop = 0.9) earth_m750a <- earth(log(value) ~ as.numeric(date) + month(date, label = TRUE), data = training(splits_a), degree=2) print(summary(earth_m750a)) set.seed(2020) model_m750a <- mars(mode = "regression", prod_degree=2) %>% set_engine("earth") %>% fit(log(value) ~ as.numeric(date) + month(date, label = TRUE), data = training(splits_a)) print(summary(model_m750a$fit)) stopifnot(identical(earth_m750a$coeff, model_m750a$fit$coeff)) predict_earth_m750a <- predict(earth_m750a, newdata=testing(splits_a)[1:3,]) predict_m750a <- model_m750a %>% predict(testing(splits_a)[1:3,]) stopifnot(max(c(9.238049628, 9.240535151, 9.232361834) - predict_m750a) < 1e-8) stopifnot(max(predict_earth_m750a - predict_m750a) < 1e-20) par(mfrow = c(2, 2), mar = c(3, 3, 3, 1), mgp = c(1.5, 0.5, 0)) set.seed(2020) plotmo(model_m750a, trace=2, do.par=FALSE, pt.col="green", main="model_m750a", SHOWCALL=TRUE) set.seed(2020) plotmo(model_m750a$fit, trace=1, do.par=FALSE, pt.col="green", main="model_m750a$fit", SHOWCALL=TRUE) set.seed(2020) plotmo(earth_m750a, trace=1, do.par=FALSE, pt.col="green", main="earth_m750a", SHOWCALL=TRUE) par(org.par) cat("===m750a second example===\n") set.seed(2020) m750b <- m4_monthly %>% filter(id == "M750") %>% select(-id) %>% rename(date2 = date) print(m750b) set.seed(2020) splits_b <- initial_time_split(m750b, prop = 0.9) set.seed(2020) model_m750b <- mars(mode = "regression") %>% set_engine("earth") %>% fit(log(value) ~ as.numeric(date2) + month(date2, label = TRUE), data = training(splits_b)) future_data <- m750b %>% future_frame(date2, .length_out = "3 years") print(future_data) stopifnot(class(future_data[,1,drop=TRUE]) == "Date") predict_m750a <- model_m750b %>% predict(new_data = future_data) par(mfrow = c(2, 2), mar = c(3, 3, 3, 1), mgp = c(1.5, 0.5, 0)) set.seed(2020) plotmo(model_m750b, trace=2, do.par=FALSE, pt.col="green", main="model_m750b", SHOWCALL=TRUE) set.seed(2020) plotmo(model_m750b$fit, trace=1, do.par=FALSE, pt.col="green", main="model_m750b$fit", SHOWCALL=TRUE) par(org.par) data(etitanic) etit <- etitanic etit$survived <- factor(ifelse(etitanic$survived == 1, "yes", "no"), levels = c("yes", "no")) etit$notsurvived <- factor(ifelse(etitanic$survived == 0, "notsurvived", "survived"), levels = c("notsurvived", "survived")) set.seed(2020) earth_tworesp <- earth(survived + notsurvived ~ ., data=etit, degree=2) print(summary(earth_tworesp)) source("test.epilog.R")
pcarec <- function(siginput,inputwt, beemap, orientmap, noct, nvoice, compr, maxchnlng=as.numeric(dim(beemap)[1])+10,minnbnodes = 2, w0 = 2*pi, nbchain=100,bstep = 1,ptile =.01,para=5,plot=2,check=FALSE) { tmp <- pcafamily(beemap,orientmap,maxchnlng=maxchnlng,bstep=bstep,nbchain=nbchain,ptile=ptile) chain <- tmp$chain nbchain <- tmp$nbchain ordered <- tmp$ordered sigsize <- length(siginput) rec <- numeric(sigsize) plnb <- 0 if(plot != FALSE){ par(mfrow=c(2,1)) plot.ts(siginput) title("Original signal") image(tmp$ordered) title("Chained Ridges") } sol <- matrix(0,nbchain,sigsize) totnbnodes <- 0 idx <- numeric(nbchain) p <- 0 if(check==TRUE) { inputskel <- matrix(0+0i,nbchain,sigsize) solskel <- matrix(0+0i, nbchain, sigsize) } for (j in 1:nbchain){ sol[j,] <- 0 nbnode <- chain[j,1] bnode <- numeric(nbnode) anode <- numeric(nbnode) for(k in 1:nbnode) { anode[k] <- chain[j,2*k] bnode[k] <- chain[j,2*k+1] } cat("Chain number",j,"\n") tmp2 <- pcaregrec(siginput[min(bnode):max(bnode)], inputwt[min(bnode):max(bnode),], anode,bnode,compr,noct,nvoice, w0 = w0, para = para,minnbnodes = minnbnodes, check=check); if(is.list(tmp2)==TRUE) { totnbnodes <- totnbnodes + tmp2$nbnodes if((sigsize-min(bnode)) > (length(tmp2$sol)-tmp2$bstart)){ np <- length(tmp2$sol) - tmp2$bstart sol[j,min(bnode):(np+min(bnode))]<-tmp2$sol[tmp2$bstart:length(tmp2$sol)] } else { np <- sigsize - min(bnode) sol[j,min(bnode):sigsize]<-tmp2$sol[tmp2$bstart:(np+tmp2$bstart)] } if(min(bnode) < tmp2$bstart) { np <- min(bnode)-1 sol[j,1:min(bnode)]<-tmp2$sol[(tmp2$bstart-np):(tmp2$bstart)] } else { np <- tmp2$bstart-1 sol[j,(min(bnode)-np):min(bnode)]<-tmp2$sol[1:(tmp2$bstart)] } if(check==TRUE) { bridge <- tmp2$bnode aridge <- tmp2$anode wtsol <- cwt(sol[j,],noct,nvoice) for(k in 1:length(bridge)) solskel[j,k] <- wtsol[bridge[k],aridge[k]] for(k in 1:length(bridge)) inputskel[j,k] <- inputwt[bridge[k],aridge[k]] } rec <- rec+sol[j,] } plnb <- plnb + 1 p <- p + 1 idx[p] <- j } if(plot == 1){ par(mfrow=c(2,1)) par(cex=1.1) plot.ts(siginput) title("Original signal") plot.ts(Re(rec)) title("Reconstructed signal") } else if (plot == 2){ par(mfrow=c(plnb+2,1)) par(mar=c(2,4,4,4)) par(cex=1.1) par(err=-1) plot.ts(siginput) title("Original signal") for (j in 1:p) plot.ts(sol[idx[j],]); plot.ts(Re(rec)) title("Reconstructed signal") } cat("Total number of ridge samples used: ",totnbnodes,"\n") par(mfrow=c(1,1)) if(check==TRUE) list(rec=rec,ordered=ordered,chain=chain, comp=tmp,inputskel=inputskel,solskel=solskel,lam=tmp2$lam) else list(rec=rec, ordered=ordered,chain=chain,comp=tmp) } PcaRidgeSampling <- function(anode, bnode, compr) { nbnode <- length(anode) compr <- as.integer(compr) if(compr < 1) compr <- 1 k <- 1 count <- 1 while(k < nbnode) { anode[count] <- anode[k] bnode[count] <- bnode[k] k <- k + compr count <- count + 1 } anode[count] <- anode[nbnode] bnode[count] <- bnode[nbnode] aridge <- numeric(count) bridge <- numeric(count) aridge <- anode[1:count] bridge <- bnode[1:count] list(anode = aridge, bnode = bridge, nbnodes = count) } pcaregrec <- function(siginput,cwtinput,anode,bnode,compr,noct,nvoice, w0 = 2*pi, plot = FALSE, para = 5, minnbnodes = 2, check=FALSE) { tmp <- PcaRidgeSampling(anode, bnode, compr) bnode <- tmp$bnode anode <- tmp$anode nbnodes <- tmp$nbnodes cat("Sampled nodes (b,a): \n") for(j in 1:nbnodes) cat("(",bnode[j],anode[j],")") cat("\n") if(nbnodes < minnbnodes){ cat(" Chain too small\n") NULL } else { a.min <- 2 * 2^(min(anode)/nvoice) a.max <- 2 * 2^(max(anode)/nvoice) b.min <- min(bnode) b.max <- max(bnode) b.max <- (b.max-b.min+1) + round(para * a.max) b.min <- (b.min-b.min+1) - round(para * a.max) bnode <- bnode-min(bnode)+2-b.min b.inc <- 1 np <- as.integer((b.max - b.min)/b.inc) +1 cat("(size:",np,",",nbnodes,"sampled nodes):\n") Q2 <- 0 one <- numeric(np) one[] <- 1 Qinv <- 1/one tmp2 <- pcaridrec(cwtinput,bnode,anode,noct,nvoice, Qinv,np,w0=w0,check=check) if(plot == TRUE){ par(mfrow=c(2,1)) plot.ts(Re(siginput)) title("Original signal") plot.ts(Re(tmp2$sol)) title("Reconstructed signal") } lam <- tmp2$lam list(sol = tmp2$sol,A = tmp2$A, lam = tmp2$lam, dualwave = tmp2$dualwave, morvelets = tmp2$morvelets,pQ2 = Q2, nbnodes=nbnodes, bstart=2-b.min, anode=tmp$anode,bnode=tmp$bnode) } } pcaridrec <- function(cwtinput,bnode,anode,noct,nvoice,Qinv,np, w0 = 2*pi, check = FALSE) { N <- length(bnode) aridge <- anode bridge <- bnode morvelets <- pcamorwave(bridge,aridge,nvoice,np,N) cat("morvelets; ") sk <- pcazeroskeleton(cwtinput,Qinv,morvelets,bridge,aridge,N) cat("skeleton.\n") solskel <- 0 inputskel <- 0 list(sol=sk$sol,A=sk$A,lam=sk$lam,dualwave=sk$dualwave,morvelets=morvelets, solskel=solskel,inputskel = inputskel) } pcazeroskeleton <- function(cwtinput,Qinv,morvelets,bridge,aridge,N) { tmp1 <- dim(morvelets)[1] constraints2 <- dim(morvelets)[2] dualwave <- matrix(0,tmp1,constraints2) for (j in 1:tmp1) { dualwave[j,] <- morvelets[j,]*Qinv[j] } A <- t(morvelets) %*% dualwave rskel <- numeric(2*N) if(is.vector(cwtinput) == TRUE) { for(j in 1:N) { rskel[j] <- Re(cwtinput[aridge[j]]) rskel[N+j] <- -Im(cwtinput[aridge[j]]) } } else { for(j in 1:N) { rskel[j] <- Re(cwtinput[bridge[j]-bridge[1]+1,aridge[j]]) rskel[N+j] <- -Im(cwtinput[bridge[j]-bridge[1]+1,aridge[j]]) } } B <- SVD(A) d <- B$d Invd <- numeric(length(d)) for(j in 1:(2*N)) if(d[j] < 1.0e-6) Invd[j] <- 0 else Invd[j] <- 1/d[j] lam <- B$v %*% diag(Invd) %*% t(B$u) %*% rskel sol <- dualwave%*%lam list(lam=lam,sol=sol,dualwave=dualwave,A=A) } pcamorwave <- function(bridge, aridge, nvoice, np, N, w0 = 2*pi) { morvelets <- matrix(0,np,2*N) aridge <- 2 * 2^((aridge - 1)/nvoice) tmp <- vecmorlet(np,N,bridge,aridge,w0 = w0) dim(tmp) <- c(np,N) morvelets[,1:N] <- Re(tmp[,1:N]) morvelets[,(N+1):(2*N)] <- Im(tmp[,1:N]) morvelets }
siarplotdatawrapper <- function(siardata, siarversion = 0, grp = NULL, panel = NULL, isos = c(1, 2),leg2 = NULL,legloc='topleft') { if (!is.null(panel) & is.null(grp)) { warning(cat("WARNING. grp set to ALL and panel set to a value.\n Overriding your panel selection and setting to panel=NULL.\n In order to plot all groups on seperate panels please call\n grp=1:siardata$numgroups and panel=1 or panel=c(r,c)\n to specify number of rows and columns")) panel <- NULL } if (all(isos == 0)) { isox <- 1 isoy <- 2 } else { isox <- isos[1] isoy <- isos[2] } a <- 1 if (siardata$numgroups == 1) { a <- 0 } if (!is.null(panel)) { if (prod(panel) < length(grp)) { panel <- c(ceiling(sqrt(length(grp)))) panel <- c(max(panel, 1), max(ceiling(length(grp)/panel), 1)) } split.screen(panel) } else { } er <- (siardata$sources[, (2 * isox) + 1]^2 + siardata$corrections[, (2 * isox) + 1]^2)^0.5 xmins <- min(c(siardata$sources[, 2 * isox] + siardata$corrections[, 2 * isox] - 3 * er, siardata$targets[, isox + a])) xmaxs <- max(c(siardata$sources[, 2 * isox] + siardata$corrections[, 2 * isox] + 3 * er, siardata$targets[, isox + a])) er <- (siardata$sources[, (2 * isoy) + 1]^2 + siardata$corrections[, (2 * isoy) + 1]^2)^0.5 ymins <- min(c(siardata$sources[, 2 * isoy] + siardata$corrections[, 2 * isoy] - 3 * er, siardata$targets[, isoy + a])) ymaxs <- max(c(siardata$sources[, 2 * isoy] + siardata$corrections[, 2 * isoy] + 3 * er, siardata$targets[, isoy + a])) if (is.null(panel)) { plot(1, 1, type = "n", xlim = c(xmins, xmaxs), ylim = c(ymins, ymaxs), main = siardata$TITLE, xlab = colnames(siardata$targets)[isox + a], ylab = colnames(siardata$targets)[isoy + a]) } for (k in 1:length(grp)) { if (!is.null(panel)) { screen(k) plot(1, 1, type = "n", xlim = c(xmins, xmaxs), ylim = c(ymins, ymaxs), main = paste("Group", grp[k]), xlab = colnames(siardata$targets)[isox + a], ylab = colnames(siardata$targets)[isoy + a]) } if (!is.null(grp)) { siarplottarget(siardata, isox, isoy, a, grps = grp[k]) } else { siarplottarget(siardata, isox, isoy, a, grps = grp) } for (i in 1:nrow(siardata$sources)) { dx <- siardata$sources[i, 2 * isox] + siardata$corrections[i, 2 * isox] dex <- 2 * (siardata$sources[i, (2 * isox) + 1]^2 + siardata$corrections[i, (2 * isox) + 1]^2)^0.5 dy <- siardata$sources[i, 2 * isoy] + siardata$corrections[i, 2 * isoy] dey <- 2 * (siardata$sources[i, (2 * isoy) + 1]^2 + siardata$corrections[i, (2 * isoy) + 1]^2)^0.5 siaraddcross(x = dx, ex = dex, y = dy, ey = dey, upch = 15, clr = i) } } if (!is.null(panel)) { close.screen(all.screens = TRUE) } if (siarversion > 0) { mtext(paste("siar v", siarversion), side = 1, line = 4, adj = 1, cex = 0.6) } if (siardata$numgroups == 0) { grp <- 1 } if (is.null(grp)) { grp <- 1 } pchseq <- c(1:2, 4:20) if (leg2 == 1) { datalabs <- NULL if (siardata$numgroups == 1) { datalabs <- "data" } else { for (k in 1:length(grp)) { datalabs <- c(datalabs, as.character(paste("Group", grp[k]))) } } legend(legloc, legend = c(as.character(siardata$sources[, 1]), datalabs), lty = c(rep(1, nrow(siardata$sources)), rep(-1, length(grp))), pch = c(rep(15, nrow(siardata$sources)), pchseq[grp]), col = c(seq(1, nrow(siardata$sources)), rep("grey50", length(grp))), bty = "n") } if (leg2 == 2) { datalabs <- NULL if (siardata$numgroups == 1) { datalabs <- "data" } else { for (k in 1:length(grp)) { datalabs <- c(datalabs, as.character(paste("Group", grp[k]))) } } plot(0, 0, "n", xaxt = "n", yaxt = "n", bty = "n") legend(0, 0, legend = c(as.character(siardata$sources[, 1]), datalabs), lty = c(rep(1, nrow(siardata$sources)), rep(-1, length(grp))), pch = c(rep(15, nrow(siardata$sources)), pchseq[grp]), col = c(seq(1, nrow(siardata$sources)), rep("grey50", length(grp))), bty = "n") } }
`recodeSNPs` <- function(mat,first.ref=FALSE,geno=1:3,snp.in.col=FALSE){ if(!is.data.frame(mat) & !is.matrix(mat)) stop("mat must be either a matrix or a data frame.") mat<-as.matrix(mat) if(length(geno)!=3) stop("geno must have length 3.") if(snp.in.col) mat<-t(mat) mat[mat=="NN"]<-NA mat.hete<-checkATCG(mat,first.ref=first.ref) ids.nohete<-rowSums(mat.hete)==0 if(any(!ids.nohete)){ cn<-strsplit(colnames(mat.hete),"") FUN<-if(first.ref) recodeFirst else recodeCount for(i in 1:length(cn)){ ids<-mat.hete[,i]>0 mat[ids,]<-FUN(mat[ids,,drop=FALSE],cn[[i]],geno=geno) } } if(any(ids.nohete)) mat[ids.nohete,]<-recodeNoHete(mat[ids.nohete,, drop=FALSE],geno=geno) if(is.numeric(geno)) mode(mat)<-"numeric" if(snp.in.col) mat<-t(mat) mat }
context("test-impute-median") vec <- rnorm(10) vec[sample(1:10, 3)] <- NA median_val <- median(vec, na.rm = TRUE) vec2 <- vec vec2[is.na(vec)] <- median_val aq_shadow <- nabular(airquality) test_that("impute_median works", { expect_equal(impute_median(vec), vec2) }) test_that("impute_median and scoped variants fail when given wrong input", { expect_error(impute_median_if(numeric(0))) expect_error(impute_median_at(numeric(0))) expect_error(impute_median_all(numeric(0))) expect_error(impute_median_if(NULL)) expect_error(impute_median_at(NULL)) expect_error(impute_mean_all(NULL)) }) test_that("impute_median_if works", { expect_false(impute_median_if(airquality, is.numeric) %>% all_na()) }) test_that("impute_median_if works with shadow", { expect_false(impute_median_if(aq_shadow, is.numeric) %>% all_na()) }) test_that("impute_median_if retains proper shadow values", { expect_equal(unbind_data(impute_median_if(aq_shadow, is.numeric)), unbind_data(aq_shadow)) }) test_that("impute_median_if retains proper shadow values", { expect_equal(unbind_data(impute_median_if(aq_shadow, is.numeric)), unbind_data(aq_shadow)) }) test_that("impute_median_at works", { expect_equal(impute_median_at(airquality, vars(Ozone)) %>% miss_var_which(), "Solar.R") }) test_that("impute_median_at works with shadow", { expect_equal(impute_median_at(aq_shadow, vars(Ozone)) %>% miss_var_which(), "Solar.R") }) test_that("impute_median_at retains proper shadow values", { expect_equal(unbind_data(impute_median_at(aq_shadow, vars(Ozone))), unbind_data(aq_shadow)) }) test_that("impute_median_at retains proper shadow values", { expect_equal(unbind_data(impute_median_at(aq_shadow, vars(Ozone))), unbind_data(aq_shadow)) }) test_that("impute_median_all works", { expect_false(impute_median_all(airquality) %>% all_na()) }) test_that("impute_median_all works with shadow", { expect_false(impute_median_all(aq_shadow) %>% all_na()) }) test_that("impute_median_all retains proper shadow values", { skip_on_cran() expect_equal(unbind_data(impute_median_all(aq_shadow)), unbind_data(aq_shadow)) }) test_that("impute_median_all retains proper shadow values", { skip_on_cran() expect_equal(unbind_data(impute_median_all(aq_shadow)), unbind_data(aq_shadow)) }) test_that("impute_median_all works with shadow", { expect_false(impute_median_all(aq_shadow) %>% all_na()) }) test_that("impute_median_all retains proper shadow values", { skip_on_cran() expect_equal(unbind_data(impute_median_all(aq_shadow)), unbind_data(aq_shadow)) }) test_that("impute_median_all retains proper shadow values", { skip_on_cran() expect_equal(unbind_data(impute_median_all(aq_shadow)), unbind_data(aq_shadow)) })
assert_is_bsd <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_bsd, severity = severity) } assert_is_linux <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_linux, severity = severity) } assert_is_mac <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_mac, severity = severity) } assert_is_osx <- assert_is_mac assert_is_osx_cheetah <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_osx_cheetah, severity = severity) } assert_is_osx_puma <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_osx_puma, severity = severity) } assert_is_osx_jaguar <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_osx_jaguar, severity = severity) } assert_is_osx_panther <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_osx_panther, severity = severity) } assert_is_osx_tiger <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_osx_tiger, severity = severity) } assert_is_osx_leopard <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_osx_leopard, severity = severity) } assert_is_osx_snow_leopard <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_osx_snow_leopard, severity = severity) } assert_is_osx_lion <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_osx_lion, severity = severity) } assert_is_osx_mountain_lion <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_osx_mountain_lion, severity = severity) } assert_is_osx_mavericks <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_osx_mavericks, severity = severity) } assert_is_osx_yosemite <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_osx_yosemite, severity = severity) } assert_is_osx_el_capitan <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_osx_el_capitan, severity = severity) } assert_is_macos_sierra <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_macos_sierra, severity = severity) } assert_is_macos_high_sierra <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_macos_high_sierra, severity = severity) } assert_is_macos_mojave <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_macos_mojave, severity = severity) } assert_is_macos_catalina <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_macos_catalina, severity = severity) } assert_is_macos_big_sur <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_macos_big_sur, severity = severity) } assert_is_solaris <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_solaris, severity = severity) } assert_is_unix <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_unix, severity = severity) } assert_is_windows <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_windows, severity = severity) } assert_is_windows_vista <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_windows_vista, severity = severity) } assert_is_windows_7 <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_windows_7, severity = severity) } assert_is_windows_8 <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_windows_8, severity = severity) } assert_is_windows_8.1 <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_windows_8.1, severity = severity) } assert_is_windows_10 <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_windows_10, severity = severity) } assert_is_windows_server_2008 <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_windows_server_2008, severity = severity) } assert_is_windows_server_2008_r2 <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_windows_server_2008_r2, severity = severity) } assert_is_windows_server_2012 <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_windows_server_2012, severity = severity) } assert_is_windows_server_2012_r2 <- function(severity = getOption("assertive.severity", "stop")) { assert_engine(is_windows_server_2012_r2, severity = severity) }
userInfoUi <- function(id) { ns <- NS(id) tagAppendAttributes( shinydashboardPlus::userOutput(ns("user")), style = "margin-left: 100px; border:none;" ) } userInfo <- function(input, output, session, diseases, sliderDisease, help) { output$user <- shinydashboardPlus::renderUser({ ns <- session$ns req(!is.null(diseases$php1()) | !is.null(diseases$hypopara()) | !is.null(diseases$hypoD3())) shinydashboardPlus::dashboardUser( name = "Rat State", image = if (diseases$php1() | diseases$hypopara() | diseases$hypoD3()) { generate_userFields(diseases, sliderDisease)$image } else { "images_patient_info/happy.png" }, title = if (diseases$php1() | diseases$hypopara() | diseases$hypoD3()) { generate_userFields(diseases, sliderDisease)$description } else { "healthy" }, subtitle = if (diseases$php1()) { "Rat has primary-hyperparathyroidism" } else if (diseases$hypopara()) { "Rat suffers from hypoparathyroidism" } else if (diseases$hypoD3()) { "Rat has vitamin D3 defficiency" } else { "nothing to declare!" }, if (diseases$php1() | diseases$hypopara() | diseases$hypoD3()) { shinydashboardPlus::dashboardUserItem(width = 6, generate_userFields(diseases, sliderDisease)$stat1) } else { shinydashboardPlus::dashboardUserItem( width = 6, HTML(paste("<p style=\"text-align:center;line-height:2.0\">", "<font face =\"TimesNewRoman\" size=\"+1\">[<em><b>Ca<sup>2+</sup></b></em>]<sub><em><b>p</b></em></sub></font>","<br>", "1.21 mM","<br>", "(1.1-1.4 mM)")) ) }, if (diseases$php1() | diseases$hypopara() | diseases$hypoD3()) { shinydashboardPlus::dashboardUserItem(width = 6, generate_userFields(diseases, sliderDisease)$stat2) } else { shinydashboardPlus::dashboardUserItem( width = 6, HTML(paste("<p style=\"text-align:center;line-height:2.0\">", "<font face =\"TimesNewRoman\" size=\"+1\">[<em><b>P<sub>i</sub></b></em>]<sub><em><b>p</b></em></sub></font>","<br>", "2.96 mM","<br>", "(2.1-3.4 mM)")) ) }, if (diseases$php1() | diseases$hypopara() | diseases$hypoD3()) { shinydashboardPlus::dashboardUserItem(width = 12, generate_userFields(diseases, sliderDisease)$stat3) } else { shinydashboardPlus::dashboardUserItem( width = 12, HTML(paste("<br>", "<p style=\"text-align:center;line-height:2.0\">", "<font face =\"TimesNewRoman\" size=\"+1\">[<em><b>PTH</b></em>]<sub><em><b>p</b></em></sub></font>","<br>", "6.87 pM","<br>", "(3-16 pM)")) ) }, br() ) }) }
test_that("doy_decimal.Date", { expect_identical(dtt_doy_decimal(NA_Date_[-1]), numeric(0)) expect_identical(dtt_doy_decimal(NA_Date_), NA_real_) expect_identical( dtt_doy_decimal(as.Date(c("2001-01-01", "2001-12-31", NA))), c(1, 365, NA) ) }) test_that("doy_decimal.POSIXct", { expect_identical(dtt_doy_decimal(NA_POSIXct_[-1]), numeric(0)) expect_identical(dtt_doy_decimal(NA_POSIXct_), NA_real_) expect_equal( dtt_doy_decimal(as.POSIXct(c("2001-01-01", "2001-12-31", NA))), c(1, 365, NA) ) expect_equal( dtt_doy_decimal(as.POSIXct(c("2001-01-01 00:00:01", "2001-12-31 23:59:59", NA))), c(1.00001157407407, 365.999988425926, NA) ) })
sample.cluster = function( pop = ceiling(10 * runif(10, 0.2, 1)), size = 3, p.col = c('blue', 'red'), p.cex = c(1, 3), ... ) { if (size > length(pop)) stop('sample size must be smaller than the number of clusters') ncol = max(pop) nrow = length(pop) nmax = ani.options('nmax') for (i in 1:nmax) { dev.hold() plot(1, axes = FALSE, ann = FALSE, type = 'n', xlim = c(0.5, ncol + 0.5), ylim = c(0.5, nrow + 0.5), xaxs = 'i', yaxs = 'i', xlab = '', ylab = '') rect(rep(0.5, nrow), seq(0.5, nrow, 1), rep(ncol + 0.5, nrow), seq(1.5, nrow + 1, 1), lwd = 1, ...) idx = sample(nrow, size) for (j in 1:nrow) { points(1:pop[j], rep(j, pop[j]), col = p.col[1], cex = p.cex[1], pch = 19) if (j %in% idx) points(1:pop[j], rep(j, pop[j]), col = p.col[2], cex = p.cex[2]) } ani.pause() } invisible(NULL) }
rename_gcdg_gsed <- function(x, copy = TRUE) { aqi <- function(x) { domo <- gsub("a|[0-9]", "", x) domn <- NA domn <- ifelse(domo == "com", "cm", domn) domn <- ifelse(domo == "f", "fm", domn) domn <- ifelse(domo == "pbs", "px", domn) domn <- ifelse(domo == "g", "gm", domn) domn <- ifelse(domo == "ps", "sl", domn) nr <- gsub("[a-z]", "", x) nr <- str_pad(nr, 3, pad = "0") rep <- "c" instr <- "aqi" cbind(as.character(x), paste(instr, domn, rep, nr, sep = "")) } bar <- function(x) { domn <- "xx" nr <- gsub("[a-z]", "", x) nr <- str_pad(nr, 3, pad = "0") repi <- gsub("bm|[0-9]", "", x) rep <- "x" rep <- ifelse(grepl("a", repi), "d", rep) rep <- ifelse(grepl("b", repi), "c", rep) instr <- "bar" cbind(as.character(x), paste(instr, domn, rep, nr, sep = "")) } bat <- function(x) { domo <- substr(x, 4, 4) domn <- rep("", length(x)) domn <- ifelse(domo == "c", "cg", domn) domn <- ifelse(domo == "1", "cm", domn) domn <- ifelse(domo == "a", "ad", domn) domn <- ifelse(domo == "m", "mo", domn) domn <- ifelse(domo == "s", "sl", domn) nr <- str_pad(unlist(lapply(strsplit(x, "_z"), `[[`, 2)), 3, pad = "0" ) rep <- "d" instr <- "bat" cbind(as.character(x), paste(instr, domn, rep, nr, sep = "")) } by1 <- function(x) { domo <- gsub("b|[0-9]", "", x) domn <- NA domn <- ifelse(domo == "m", "md", domn) domn <- ifelse(domo == "p", "pd", domn) nr <- gsub("b1p|b1m", "", x) nr <- str_pad(nr, 3, pad = "0") rep <- "d" instr <- "by1" cbind(as.character(x), paste(instr, domn, rep, nr, sep = "")) } by2 <- function(x) { domo <- gsub("b|[0-9]", "", x) domn <- NA domn <- ifelse(domo == "m", "md", domn) domn <- ifelse(domo == "p" | domo == "g", "pd", domn) nr <- gsub("b2p|b2m|b2g", "", x) nr <- str_pad(nr, 3, pad = "0") rep <- "d" instr <- "by2" cbind(as.character(x), paste(instr, domn, rep, nr, sep = "")) } by3 <- function(x) { domo <- gsub("b|[0-9]", "", x) domn <- NA domn <- ifelse(domo == "c", "cg", domn) domn <- ifelse(domo == "f", "fm", domn) domn <- ifelse(domo == "e", "ex", domn) domn <- ifelse(domo == "r", "re", domn) domn <- ifelse(domo == "g", "gm", domn) nr <- gsub("b3|[a-z]", "", x) nr <- str_pad(nr, 3, pad = "0") rep <- "d" instr <- "by3" cbind(as.character(x), paste(instr, domn, rep, nr, sep = "")) } ddi <- function(x) { fm <- c( 1, 7, 8, 9, 13, 14, 19, 20, 21, 27, 32, 33, 38, 39, 44, 45, 51, 52, 53, 54 ) cm <- c( 2, 6, 10, 25, 31, 30, 37, 40, 47, 55, 56, 16, 36, 41, 48 ) gm <- c( 3, 4, 11, 15, 5, 12, 18, 17, 14, 22, 23, 24, 26, 28, 29, 34, 35, 42, 50, 43, 49, 57, 46 ) domn <- rep("xx", length(x)) nr <- gsub("n|v", "", x) domn <- ifelse(grepl("n", x) & nr %in% fm, "fm", domn) domn <- ifelse(grepl("n", x) & nr %in% cm, "cm", domn) domn <- ifelse(grepl("n", x) & nr %in% gm, "gm", domn) domn <- ifelse(grepl("v", x) & nr < 30, "fm", domn) domn <- ifelse(grepl("v", x) & nr > 30 & nr < 52, "cm", domn) domn <- ifelse(grepl("v", x) & nr > 66, "gm", domn) nr <- ifelse(grepl("n1", x), 1, nr) nr <- ifelse(grepl("n2", x), 29, nr) nr <- ifelse(grepl("n3", x), 52, nr) nr <- ifelse(grepl("n4", x), 53, nr) nr <- ifelse(grepl("n5", x), 56, nr) nr <- ifelse(grepl("n6", x), 30, nr) nr <- ifelse(grepl("n7", x), 2, nr) nr <- ifelse(grepl("n8", x), 3, nr) nr <- ifelse(grepl("n9", x), 4, nr) nr <- ifelse(grepl("n10", x), 31, nr) nr <- ifelse(grepl("n11", x), 54, nr) nr <- ifelse(grepl("n12", x), 57, nr) nr <- ifelse(grepl("n13", x), 5, nr) nr <- ifelse(grepl("n14", x), 6, nr) nr <- ifelse(grepl("n15", x), 55, nr) nr <- ifelse(grepl("n16", x), 116, nr) nr <- ifelse(grepl("n17", x), 59, nr) nr <- ifelse(grepl("n18", x), 58, nr) nr <- ifelse(grepl("n19", x), 7, nr) nr <- ifelse(grepl("n20", x), 8, nr) nr <- ifelse(grepl("n21", x), 9, nr) nr <- ifelse(grepl("n22", x), 60, nr) nr <- ifelse(grepl("n23", x), 61, nr) nr <- ifelse(grepl("n24", x), 62, nr) nr <- ifelse(grepl("n25", x), 33, nr) nr <- ifelse(grepl("n26", x), 63, nr) nr <- ifelse(grepl("n27", x), 10, nr) nr <- ifelse(grepl("n28", x), 64, nr) nr <- ifelse(grepl("n29", x), 65, nr) nr <- ifelse(grepl("n30", x), 36, nr) nr <- ifelse(grepl("n31", x), 34, nr) nr <- ifelse(grepl("n32", x), 11, nr) nr <- ifelse(grepl("n33", x), 12, nr) nr <- ifelse(grepl("n34", x), 66, nr) nr <- ifelse(grepl("n35", x), 67, nr) nr <- ifelse(grepl("n36", x), 136, nr) nr <- ifelse(grepl("n37", x), 37, nr) nr <- ifelse(grepl("n38", x), 13, nr) nr <- ifelse(grepl("n39", x), 14, nr) nr <- ifelse(grepl("n40", x), 39, nr) nr <- ifelse(grepl("n41", x), 141, nr) nr <- ifelse(grepl("n42", x), 68, nr) nr <- ifelse(grepl("n43", x), 69, nr) nr <- ifelse(grepl("n44", x), 15, nr) nr <- ifelse(grepl("n45", x), 16, nr) nr <- ifelse(grepl("n46", x), 146, nr) nr <- ifelse(grepl("n47", x), 41, nr) nr <- ifelse(grepl("n48", x), 148, nr) nr <- ifelse(grepl("n49", x), 70, nr) nr <- ifelse(grepl("n50", x), 168, nr) nr <- ifelse(grepl("n51", x), 17, nr) nr <- ifelse(grepl("n52", x), 18, nr) nr <- ifelse(grepl("n53", x), 19, nr) nr <- ifelse(grepl("n54", x), 154, nr) nr <- ifelse(grepl("n55", x), 43, nr) nr <- ifelse(grepl("n56", x), 44, nr) nr <- ifelse(grepl("n57", x), 71, nr) nr <- ifelse(grepl("v20", x), 20, nr) nr <- ifelse(grepl("v21", x), 21, nr) nr <- ifelse(grepl("v22", x), 22, nr) nr <- ifelse(grepl("v23", x), 23, nr) nr <- ifelse(grepl("v24", x), 24, nr) nr <- ifelse(grepl("v25", x), 25, nr) nr <- ifelse(grepl("v26", x), 27, nr) nr <- ifelse(grepl("v27", x), 26, nr) nr <- ifelse(grepl("v31", x), 32, nr) nr <- ifelse(grepl("v32", x), 132, nr) nr <- ifelse(grepl("v35", x), 35, nr) nr <- ifelse(grepl("v38", x), 38, nr) nr <- ifelse(grepl("v40", x), 40, nr) nr <- ifelse(grepl("v42", x), 42, nr) nr <- ifelse(grepl("v45", x), 45, nr) nr <- ifelse(grepl("v46", x), 46, nr) nr <- ifelse(grepl("v47", x), 47, nr) nr <- ifelse(grepl("v48", x), 48, nr) nr <- ifelse(grepl("v49", x), 49, nr) nr <- ifelse(grepl("v50", x), 50, nr) nr <- ifelse(grepl("v72", x), 72, nr) nr <- ifelse(grepl("v73", x), 268, nr) nr <- ifelse(grepl("v74", x), 73, nr) nr <- ifelse(grepl("v75", x), 74, nr) mitem <- c( 4, 9, 12, 29:38, 60, 64, 65, 66, 67, 14, 16, 19, 25, 39:43, 45:48, 50, 51, 73 ) rep <- ifelse(nr %in% mitem, "m", "d") nr <- str_pad(nr, 3, pad = "0") instr <- "ddi" cbind(as.character(x), paste(instr, domn, rep, nr, sep = "")) } den <- function(x) { domo <- gsub("d|[0-9]", "", x) domn <- NA domn <- ifelse(domo == "l", "lg", domn) domn <- ifelse(domo == "f", "fm", domn) domn <- ifelse(domo == "g", "gm", domn) domn <- ifelse(domo == "p", "sl", domn) nr <- gsub("[a-z]", "", x) nr <- str_pad(nr, 3, pad = "0") rep <- "d" instr <- "den" cbind(as.character(x), paste(instr, domn, rep, nr, sep = "")) } gri <- function(x) { domo <- gsub("g|[0-9]|_", "", x) domn <- NA domn <- ifelse(domo == "c", "cg", domn) domn <- ifelse(domo == "e", "eh", domn) domn <- ifelse(domo == "h", "hs", domn) domn <- ifelse(domo == "p", "re", domn) domn <- ifelse(domo == "", "gm", domn) nr <- gsub("g|[a-z]", "", x) nr <- ifelse(nchar(nr) > 3, gsub("_", "", nr), nr) nr <- gsub("_", "0", nr) nr <- str_pad(nr, 3, pad = "0") rep <- "d" instr <- "gri" cbind(as.character(x), paste(instr, domn, rep, nr, sep = "")) } mac <- function(x) { domn <- "gm" nr <- gsub("mg", "", x) nr <- str_pad(nr, 3, pad = "0") nr <- ifelse(nr == "04a", "041", nr) nr <- ifelse(nr == "04b", "042", nr) rep <- "d" instr <- "mac" cbind(as.character(x), paste(instr, domn, rep, nr, sep = "")) } mds <- function(x) { domn <- "gm" nr <- gsub("mil", "", x) nr <- str_pad(nr, 3, pad = "0") rep <- "d" instr <- "mds" cbind(as.character(x), paste(instr, domn, rep, nr, sep = "")) } mul <- function(x) { domo <- substr(x, 4, 4) domn <- NA domn <- ifelse(domo == "v", "cg", domn) domn <- ifelse(domo == "f", "fm", domn) domn <- ifelse(domo == "r", "re", domn) domn <- ifelse(domo == "g", "gm", domn) domn <- ifelse(domo == "e", "ex", domn) domn <- ifelse(domo == "s", "se", domn) nr <- gsub("[a-z]", "", x) tr <- substr(x, nchar(x), nchar(x)) ad <- rep("0", length(x)) ad <- ifelse(tr == "a", "0", ad) ad <- ifelse(tr == "b", "1", ad) ad <- ifelse(tr == "c", "2", ad) ad <- ifelse(tr == "d", "3", ad) ad <- ifelse(tr == "e", "4", ad) ad <- ifelse(tr == "f", "5", ad) nr <- paste0(nr, ad) nr <- str_pad(nr, 3, pad = "0") rep <- "d" instr <- "mul" cbind(as.character(x), paste(instr, domn, rep, nr, sep = "")) } peg <- function(x) { domn <- "fm" nr <- gsub("peg", "", x) nr <- str_pad(nr, 3, pad = "0") rep <- "d" instr <- "peg" cbind(as.character(x), paste(instr, domn, rep, nr, sep = "")) } sgr <- function(x) { domo <- gsub("sag|[0-9]", "", x) domn <- NA domn <- ifelse(domo == "c", "cg", domn) domn <- ifelse(domo == "e", "eh", domn) domn <- ifelse(domo == "h" | domo == "hs", "hs", domn) domn <- ifelse(domo == "p", "fm", domn) domn <- ifelse(domo == "l", "gm", domn) domn <- ifelse(domo == "ps" | domo == "s", "re", domn) nr <- gsub("[a-z]", "", x) nr <- str_pad(nr, 3, pad = "0") rep <- "d" instr <- "sgr" cbind(as.character(x), paste(instr, domn, rep, nr, sep = "")) } sbi <- function(x) { domo <- gsub("sb|[0-9]", "", x) domn <- NA domn <- ifelse(domo == "w", "wm", domn) domn <- ifelse(domo == "v", "vs", domn) domn <- ifelse(domo == "f", "fr", domn) domn <- ifelse(domo == "s", "sl", domn) nr <- gsub("[a-z]", "", x) nr <- ifelse(nchar(nr) == 1, paste0(nr, "0"), nr) nr <- str_pad(nr, 3, pad = "0") rep <- "d" instr <- "sbi" cbind(as.character(x), paste(instr, domn, rep, nr, sep = "")) } tep <- function(x) { nr <- gsub("j|b|c|__[0-9]", "", x) domn <- NA domn <- ifelse(nr <= 16, "co", domn) domn <- ifelse(nr > 16 & nr <= 40, "lg", domn) domn <- ifelse(nr > 40, "mo", domn) nr <- gsub("[a-z]|__", "", x) nr <- str_pad(nr, 3, pad = "0") rep <- "d" instr <- "tep" cbind(as.character(x), paste(instr, domn, rep, nr, sep = "")) } vin <- function(x) { nr <- gsub("sa2v", "", x) domn <- "xx" nr <- ifelse(grepl("playswith", x), "31", nr) nr <- ifelse(grepl("crayondraw", x), "32", nr) nr <- ifelse(grepl("avoidda", x), "33", nr) nr <- ifelse(grepl("buttons", x), "34", nr) nr <- ifelse(grepl("compete", x), "35", nr) nr <- ifelse(grepl("downstar", x), "36", nr) nr <- ifelse(grepl("dryhand", x), "37", nr) nr <- ifelse(grepl("eatfood", x), "38", nr) nr <- ifelse(grepl("getwater", x), "39", nr) nr <- ifelse(grepl("helpshou", x), "40", nr) nr <- ifelse(grepl("narrates", x), "41", nr) nr <- ifelse(grepl("onjacket", x), "42", nr) nr <- ifelse(grepl("performs", x), "43", nr) nr <- ifelse(grepl("scissors", x), "44", nr) nr <- ifelse(grepl("selftoil", x), "45", nr) nr <- ifelse(grepl("takeoff", x), "46", nr) nr <- ifelse(grepl("washface", x), "47", nr) nr <- ifelse(grepl("washhands", x), "48", nr) nr <- ifelse(grepl("playself", x), "49", nr) nr <- ifelse(grepl("ytoilet", x), "50", nr) nr <- ifelse(grepl("dressself", x), "51", nr) nr <- str_pad(nr, 3, pad = "0") rep <- "c" instr <- "vin" cbind(as.character(x), paste(instr, domn, rep, nr, sep = "")) } convert <- function(x, y, n, pat, func) { idx <- substr(x, 1, n) %in% pat if (!any(idx)) { return(y) } y[idx] <- func(x[idx])[, 2] y } y <- x if (!copy) y <- rep("", length(y)) y <- convert(x, y, 2, c("ac", "af", "ap", "ag"), aqi) y <- convert(x, y, 2, c("bm"), bar) y <- convert(x, y, 3, c("bat"), bat) y <- convert(x, y, 2, c("b1"), by1) y <- convert(x, y, 2, c("b2"), by2) y <- convert(x, y, 2, c("b3"), by3) y <- convert(x, y, 1, c("n", "v"), ddi) y <- convert(x, y, 1, c("d"), den) y <- convert(x, y, 1, c("g"), gri) y <- convert(x, y, 2, c("mg"), mac) y <- convert(x, y, 3, c("mil"), mds) y <- convert(x, y, 3, c("mul"), mul) y <- convert(x, y, 3, c("peg"), peg) y <- convert(x, y, 3, c("sag"), sgr) y <- convert(x, y, 2, c("sb"), sbi) y <- convert(x, y, 1, c("j"), tep) y <- convert(x, y, 4, c("sa2v", "savi", "savn"), vin) y }
evap_est <- function(ts, eMin=0, eMax=0){ if(!(eMin < eMax)){ stop("eMin should be less then eMax") } dt <- diff(as.numeric(ts)) if(!all(dt[]==dt[1])){ stop("Irregularly spaced time series supplied") }else{ dt <- dt[1] } if(dt > 24*60*60){ stop("Time step can be no mroe then a day") } yday <- 0:365 fact <- 1+sin(2*pi*yday/365-pi/2) daily_pet <- eMin + 0.5*(eMax-eMin)*fact dawn <- (10 - 2.5*fact)*60*60 dayLength <- (6 + 4*fact) * 60*60 sts <- ts-dt dts <- as.POSIXct(3600*24*floor(as.numeric(ts)/(3600*24)),origin="1970-01-01",tz='GMT') dsts <- as.POSIXct(3600*24*floor(as.numeric(sts)/(3600*24)),origin="1970-01-01",tz='GMT') pet <- rep(0,length(ts)) tmp <- dsts idx <- tmp<dts while( any(idx) ){ pet[idx] <- pet[idx] + daily_pet[ as.POSIXlt(tmp[idx])$yday + 1] tmp <- tmp + 24*60*60 idx <- tmp<dts } sc <- as.numeric(sts) - as.numeric(dsts) frc <- (sc - dawn[ as.POSIXlt(sts)$yday +1 ])/ dayLength[ as.POSIXlt(sts)$yday +1] frc <- pmin(1,pmax(0,frc)) pet <- pet - daily_pet[ as.POSIXlt(sts)$yday + 1]*0.5*(1-cos(frc*pi)) sc <- as.numeric(ts) - as.numeric(dts) frc <- (sc - dawn[ as.POSIXlt(ts)$yday +1 ])/ dayLength[ as.POSIXlt(ts)$yday +1] frc <- pmin(1,pmax(0,frc)) pet <- pet + daily_pet[ as.POSIXlt(ts)$yday + 1]*0.5*(1-cos(frc*pi)) return(xts::xts(pet,order.by=ts)) }
iso_save <- function(iso_files, filepath, quiet = default(quiet)) { if(!iso_is_object(iso_files)) stop("can only export iso files or lists of iso files", call. = FALSE) filepath <- get_rds_export_filepath(iso_files, filepath) if (!quiet) { sprintf("Info: exporting data from %d iso_files into R Data Storage '%s'", length(iso_as_file_list(iso_files)), str_replace(filepath, "^\\.(/|\\\\)", "")) %>% message() } saveRDS(iso_files, file = filepath) return(invisible(iso_files)) } get_rds_export_filepath <- function(iso_files, filepath) { if (iso_is_continuous_flow(iso_files)) ext <- ".cf.rds" else if (iso_is_dual_inlet(iso_files)) ext <- ".di.rds" else if (iso_is_scan(iso_files)) ext <- ".scan.rds" else stop("R data storage export of this type of iso_files not supported", call. = FALSE) return(get_export_filepath(filepath, ext)) }
simulateGen <- function(ped, AF=c(), mut.rate=0) { colnames(ped) = c("ID","SIRE","DAM") if(length(AF)==0) { AF = runif(ncol(M), min=0.01, max=0.99) } else { stopifnot(min(AF)>=0.01) stopifnot(max(AF)<=0.99) } if(!identical(mut.rate, 0)) { stopifnot(length(AF)==length(mut.rate)) stopifnot(min(mut.rate)>=0) if(length(mut.rate[mut.rate > 10^-6])) { warning("Found ", length(mut.rate[mut.rate > 10^-6]), " markers with mutation rate > 10^-6") warning("Maximum mutation rate = ", max(mut.rate)) } } else { message("No mutation was simulated.") } tmp = c() SNPs = 1:length(AF) for(j in SNPs) tmp = c(tmp, sample(0:2, 1, prob=c((1-AF[j])^2, 2*(1-AF[j])*AF[j], AF[j]^2))) M = matrix(tmp, nrow=1) for(i in 2:nrow(ped)) { s = ped$SIRE[i] d = ped$DAM[i] tmp = c() if(s==0 & d==0) { for(j in SNPs) tmp = c(tmp, sample(0:2, 1, prob=c((1-AF[j])^2, 2*(1-AF[j])*AF[j], AF[j]^2))) } else if(s>0 & d==0) { for(j in SNPs) tmp = c(tmp, sample(0:1, 1, prob=c(1-AF[j], AF[j]))) tmp = tmp+makegamete(M[s,]) } else if(s==0 & d>0) { for(j in SNPs) tmp = c(tmp, sample(0:1, 1, prob=c(1-AF[j], AF[j]))) tmp = tmp+makegamete(M[d,]) } else { tmp = makegamete(M[s,])+makegamete(M[d,]) } if(!identical(mut.rate, 0)) tmp = mutate(tmp, mut.rate) M = rbind(M, tmp) rownames(M) = NULL } return(M) }
htmlUl <- function(children=NULL, id=NULL, n_clicks=NULL, n_clicks_timestamp=NULL, key=NULL, role=NULL, accessKey=NULL, className=NULL, contentEditable=NULL, contextMenu=NULL, dir=NULL, draggable=NULL, hidden=NULL, lang=NULL, spellCheck=NULL, style=NULL, tabIndex=NULL, title=NULL, loading_state=NULL, ...) { wildcard_names = names(dash_assert_valid_wildcards(attrib = list('data', 'aria'), ...)) props <- list(children=children, id=id, n_clicks=n_clicks, n_clicks_timestamp=n_clicks_timestamp, key=key, role=role, accessKey=accessKey, className=className, contentEditable=contentEditable, contextMenu=contextMenu, dir=dir, draggable=draggable, hidden=hidden, lang=lang, spellCheck=spellCheck, style=style, tabIndex=tabIndex, title=title, loading_state=loading_state, ...) if (length(props) > 0) { props <- props[!vapply(props, is.null, logical(1))] } component <- list( props = props, type = 'Ul', namespace = 'dash_html_components', propNames = c('children', 'id', 'n_clicks', 'n_clicks_timestamp', 'key', 'role', 'accessKey', 'className', 'contentEditable', 'contextMenu', 'dir', 'draggable', 'hidden', 'lang', 'spellCheck', 'style', 'tabIndex', 'title', 'loading_state', wildcard_names), package = 'dashHtmlComponents' ) structure(component, class = c('dash_component', 'list')) }
simulateTarget<-function( optimArgs=NULL, simVar=NULL, modelTag=NULL, modelInfo=NULL, attSel=NULL, attPrim=NULL, attInfo=NULL, attInd=NULL, datInd=NULL, initCalibPars=NULL, targetLoc=NULL, attObs=NULL, parLoc=NULL, parSim=NULL, setSeed=1234, file=NULL ){ nMod=length(modelTag) out=list() parV=NULL objScore=NULL if(!is.null(optimArgs$suggestions)){ parSugg=rbind(parSim,optimArgs$suggestions) if(dim(parSugg)[1] > optimArgs$popSize){ parSugg=parSugg[(1:optimArgs$popSize),] } }else{ parSugg=NULL } attSim=list() targetSim=list() for(mod in 1:nMod){ randomVector <- runif(n=datInd[[modelTag[mod]]]$ndays) switch(simVar[mod], "P" = {wdStatus=NULL}, "Temp" = {if(modelInfo[[modelTag[mod]]]$WDcondition==TRUE){ wdStatus=out[["P"]]$sim }else{ wdStatus=NULL } }, {wdStatus=NULL} ) write_model_env(envir = foreSIGHT_modelEnv, modelInfo = modelInfo[[modelTag[mod]]], modelTag = modelTag[mod], datInd = datInd[[modelTag[mod]]] ) if(length(which(modelInfo[[modelTag[mod]]]$minBound==modelInfo[[modelTag[mod]]]$maxBound))==length(modelInfo[[modelTag[mod]]]$minBound)){ progress(p(" Working on variable ",simVar[mod]),file) progress(p(" Parameters specified by user, no optimisation ..."),file) out[[simVar[mod]]]=switch_simulator(type=modelInfo[[modelTag[mod]]]$simVar, parS=modelInfo[[modelTag[mod]]]$minBound, modelEnv = foreSIGHT_modelEnv, randomVector = randomVector, wdSeries=wdStatus, resid_ts=NULL, seed=setSeed) }else{ progress(p(" Working on variable ",simVar[mod]),file) progress(p(" Commencing optimisation..."),file) if(!is.null(parSugg)){ parSel=parSugg[,(parLoc[[mod]][1]:parLoc[[mod]][2])] }else{ parSel=NULL } optTest=gaWrapper(gaArgs=optimArgs, modelEnv = foreSIGHT_modelEnv, modelInfo=modelInfo[[modelTag[mod]]], attSel=attSel[attInd[[mod]]], attPrim=attPrim, attInfo=attInfo[[modelTag[mod]]], datInd=datInd[[modelTag[mod]]], randomVector = randomVector, parSuggest=parSel, target=targetLoc[attInd[[mod]]], attObs=attObs[attInd[[mod]]], lambda.mult=optimArgs$lambda.mult, simSeed=setSeed, wdSeries=wdStatus, resid_ts=NULL) progress(p(" Best fitness: ",signif(optTest$fitness,digits=5), ". Optimisation stopped at iter ",optTest$opt@iter),file) out[[simVar[mod]]]=switch_simulator(type=modelInfo[[modelTag[mod]]]$simVar, parS=optTest$par, modelEnv = foreSIGHT_modelEnv, randomVector = randomVector, wdSeries=wdStatus, resid_ts=NULL, seed=optTest$seed) } sim.att=attribute.calculator(attSel=attSel[attInd[[mod]]],data=out[[simVar[mod]]]$sim,datInd=datInd[[modelTag[mod]]],attribute.funcs=attribute.funcs) attSim[[mod]]=sim.att simPt=unlist(Map(function(type, val,baseVal) simPt.converter.func(type,val,baseVal), attInfo$targetType[attInd[[mod]]], as.vector(sim.att),as.vector(attObs[attInd[[mod]]])),use.names = FALSE) names(simPt)=attSel[attInd[[mod]]] targetSim[[mod]]=simPt score=objFuncMC(attSel= attSel[attInd[[mod]]], attPrim=attPrim, attInfo=attInfo[[modelTag[mod]]], simPt=simPt, target=targetLoc[attInd[[mod]]], penalty.func=penaltyFunc_basic, lambda=optimArgs$lambda.mult) progress(paste0(" Variable ",simVar[mod]," final sim series fitness: ",signif(score,4)),file) parV=c(parV,optTest$par) objScore=c(objScore,score) } out$attSim=unlist(attSim)[attSel] progress(paste(" Attributes Simulated - ",paste(attSel,": ",signif(out$attSim,digits=4),collapse = ", ",sep=""),sep=''),file) out$targetSim=unlist(targetSim)[attSel] progress(paste(" Target Simulated - ",paste(attSel,": ",signif(out$targetSim,digits=4),collapse = ", ",sep=''),sep=""),file) out$parS=parV out$score=objScore return(out) }
calculate.overlap.and.pvalue = function(list1, list2, total.size, lower.tail = TRUE, adjust = FALSE) { actual.overlap <- length(intersect(list1, list2)); expected.overlap <- as.numeric(length(list1)) * length(list2) / total.size; adjust.value <- 0; if (adjust & !lower.tail) { adjust.value <- 1; warning('Calculating P[X >= x]'); } overlap.pvalue <- phyper( q = actual.overlap - adjust.value, m = length(list1), n = total.size - length(list1), k = length(list2), lower.tail = lower.tail ); return( c(actual.overlap, expected.overlap, overlap.pvalue) ); }
context("Parse git repo") test_that("pull request and latest release, via spec and URL", { expect_equal( parse_git_repo("r-lib/remotes github_pull("7") ) expect_equal( parse_git_repo("https://github.com/r-lib/remotes/pull/7")$ref, github_pull("7") ) expect_equal( parse_git_repo("r-lib/remotes@*release")$ref, github_release() ) expect_equal( parse_git_repo("https://github.com/r-lib/remotes/releases/latest")$ref, github_release() ) }) test_that("parse_repo_spec trailing slash, issue expect_equal( parse_repo_spec("foo/bar/baz/"), parse_repo_spec("foo/bar/baz") ) }) test_that("parse_github_url() accepts all forms of URL (github.com and GHE)", { expect_identical( parse_github_url("https://github.com/r-lib/remotes.git"), list(username = "r-lib", repo = "remotes", ref = "", pull = "", release = "") ) expect_identical( parse_github_url("https://github.ubc.ca/user/repo.git"), list(username = "user", repo = "repo", ref = "", pull = "", release = "") ) expect_identical( parse_github_url("[email protected]:r-lib/remotes.git"), list(username = "r-lib", repo = "remotes", ref = "", pull = "", release = "") ) expect_identical( parse_github_url("[email protected]:user/repo.git"), list(username = "user", repo = "repo", ref = "", pull = "", release = "") ) expect_identical( parse_github_url("https://github.com/r-lib/remotes"), list(username = "r-lib", repo = "remotes", ref = "", pull = "", release = "") ) expect_identical( parse_github_url("https://github.ubc.ca/user/repo"), list(username = "user", repo = "repo", ref = "", pull = "", release = "") ) expect_identical( parse_github_url("https://github.com/r-lib/remotes/tree/i-am-a-branch"), list(username = "r-lib", repo = "remotes", ref = "i-am-a-branch", pull = "", release = "") ) expect_identical( parse_github_url("https://github.com/r-lib/remotes/commit/1234567"), list(username = "r-lib", repo = "remotes", ref = "1234567", pull = "", release = "") ) expect_identical( parse_github_url("https://github.com/r-lib/remotes/pull/108"), list(username = "r-lib", repo = "remotes", ref = "", pull = "108", release = "") ) expect_identical( parse_github_url("https://github.com/r-lib/remotes/releases/tag/1.0.0"), list(username = "r-lib", repo = "remotes", ref = "1.0.0", pull = "", release = "") ) expect_identical( parse_github_url("https://github.com/r-lib/remotes/releases/latest"), list(username = "r-lib", repo = "remotes", ref = "", pull = "", release = "*release") ) }) test_that("parse_repo_spec catches invalid spec", { expect_error( parse_repo_spec("/$&@R64&3"), "Invalid git repo specification" ) }) test_that("parse_repo_spec, github", { cases <- list( list("user/repo"), list("pkg=user/repo", package = "pkg"), list("pkg=user/repo", package = "pkg"), list("user/repo/subdir", subdir = "subdir"), list("user/repo@badcafe", ref = "badcafe"), list("user/repo list("user/repo@*release", ref = github_release()), list("pkg=user/repo/subdir", package = "pkg", subdir = "subdir"), list("pkg=user/repo@badcafe", package = "pkg", ref = "badcafe"), list("pkg=user/repo list("pkg=user/repo@*release", package = "pkg", ref = github_release()), list("[email protected]:user/repo.git"), list("[email protected]:user/repo.git"), list("https://github.com/user/repo"), list("https://github.ubc.ca/user/repo"), list("https://github.com/user/repo/tree/i-am-a-branch", ref = "i-am-a-branch"), list("https://github.com/user/repo/commit/1234567", ref = "1234567"), list("https://github.com/user/repo/pull/108", ref = github_pull("108")), list("https://github.com/user/repo/releases/tag/1.0.0", ref = "1.0.0"), list("https://github.com/user/repo/releases/latest", ref = github_release()), list("https://github.com/user/repo/releases/latest", ref = github_release()), list("https://github.com/foo/bar", username = "foo", repo = "bar"), list("[email protected]:foo/bar.git", username = "foo", repo = "bar"), list("[email protected]:foo-bar/baz-qux.git", username = "foo-bar", repo = "baz-qux") ) for (case in cases) { expect_equal_named_lists( p <- parse_git_repo(case[[1]]), utils::modifyList( list(username = "user", repo = "repo"), case[-1] ) ) } }) test_that("parse_git_repo errors on invalid GitHub input", { expect_error(parse_git_repo("https://github.com/r-lib"), "Invalid GitHub URL") })
bayessurvreg1.priorInit <- function(prior, init, Yinit, Xinit, n, nX, nrandom, ncluster, indb, randomInt, toler.chol){ if(length(prior) == 0) inprior <- "arnost" else inprior <- names(prior) if(length(init) == 0) ininit <- "arnost" else ininit <- names(init) prior.pari <- numeric(3) names(prior.pari) <- c("kmax", "k.prior", "Eb0.depend.mix") tmp <- match("kmax", inprior, nomatch=NA) if(is.na(tmp)) prior$kmax <- 5 tmp <- match("k.prior", inprior, nomatch=NA) if(is.na(tmp)) prior$k.prior <- "poisson" tmp <- match("Eb0.depend.mix", inprior, nomatch=NA) if(is.na(tmp)) prior$Eb0.depend.mix <- FALSE tmp <- match("poisson.k", inprior, nomatch=NA) if(is.na(tmp)) prior$poisson.k <- 3 prior.pari["k.prior"] <- pmatch(prior$k.prior, c("poisson", "uniform", "fixed"), nomatch = -1) - 1 if (prior.pari["k.prior"] < 0) stop("Prior for k (number of mixture components) must be either poisson, uniform or fixed.") prior.pari["kmax"] <- prior$kmax prior.pari["Eb0.depend.mix"] <- 1*(prior$Eb0.depend.mix) prior.pard <- numeric(2*prior.pari["kmax"] + 7) names(prior.pard) <- c(paste("pi.split", 1:prior.pari["kmax"], sep = ""), paste("pi.birth", 1:prior.pari["kmax"], sep = ""), "lambda", "delta", "xi", "kappa", "zeta", "g", "h") prior.pard["lambda"] <- prior$poisson.k init.error <- "Something is wrong with your initials." fit.init <- survreg(Yinit ~ Xinit - 1, dist = "lognormal") tmp <- match("iter", ininit, nomatch=NA) if(is.na(tmp)) init$iter <- 0 if (is.na(init$iter)) init$iter <- 0 init$iter <- init$iter[1] tmp <- match("mixture", ininit, nomatch=NA) if(is.na(tmp)){ if (prior.pari["k.prior"] == 2) stop("init$mixture must be given when prior$k.prior is 'fixed'.") init$mixture <- numeric(1 + 3*prior$kmax) init$mixture[1] <- 1 init$mixture[2] <- 1.0 init$mixture[2 + prior$kmax] <- fit.init$coefficients[1] init$mixture[2 + 2*prior$kmax] <- fit.init$scale^2 } else{ if (length(init$mixture) != 1 + 3*prior$kmax) stop("Incorrect init$mixture parameter supplied.") if (is.na(init$mixture[1])) stop("Incorrect init$mixture parameter supplied.") wi <- init$mixture[2:(1 + init$mixture[1])] mui <-init$mixture[(2 + prior$kmax):(1 + prior$kmax + init$mixture[1])] sig2i <- init$mixture[(2 + 2*prior$kmax):(1 + 2*prior$kmax + init$mixture[1])] if (sum(is.na(wi)) | sum(is.na(mui)) | sum(is.na(sig2i))) stop("Incorrect init$mixture parameter supplied.") if (sum(wi < 0)) stop("Incorrect init$mixture parameter supplied.") if (sum(sig2i <= 0)) stop("Incorrect init$mixture parameter supplied.") wi <- wi/sum(wi) ordermu <- order(mui) k.temp <- init$mixture[1] init$mixture <- numeric(1 + 3*prior$kmax) wi <- wi[ordermu] mui <- mui[ordermu] sig2i <- sig2i[ordermu] init$mixture[1] <- k.temp init$mixture[2:(1 + init$mixture[1])] <- wi init$mixture[(2 + prior$kmax):(1 + prior$kmax + init$mixture[1])] <- mui init$mixture[(2 + 2*prior$kmax):(1 + 2*prior$kmax + init$mixture[1])] <- sig2i } if (!nX){ init$beta <- 0 ininit <- names(init) } else{ tmp <- match("beta", ininit, nomatch=NA) if(is.na(tmp)){ init$beta <- fit.init$coefficients[-1] } else{ if (length(init$beta) < nX) stop("Incorrect init$beta parameter supplied.") init$beta <- init$beta[1:nX] } if (sum(is.na(init$beta))) stop("Incorrect init$beta parameter supplied.") } if (!nrandom) init$b <- 0 else{ tmp <- match("b", ininit, nomatch=NA) if(is.na(tmp)){ bb <- fit.init$coefficients[-1][indb > 0] if (randomInt) bb <- c(0, bb) init$b <- rep(bb, ncluster) } else{ if (length(init$b) == 0){ bb <- fit.init$coefficients[-1][indb > 0] if (randomInt) bb <- c(0, bb) init$b <- rep(bb, ncluster) } else{ if (length(init$b) < nrandom*ncluster) stop("Incorrect init$b parameter supplied.") init$b <- init$b[1:(nrandom*ncluster)] } } if (sum(is.na(init$b))) stop("Incorrect init$b parameter supplied.") } tmp <- match("y", ininit, nomatch=NA) if(is.na(tmp)){ init$y <- as.numeric(log(Yinit[,1])) } else{ if (length(init$y) < n) stop("Incorrect init$y parameter supplied.") init$y <- init$y[1:n] } if (sum(is.na(init$y))) stop("Incorrect init$y parameter supplied.") tmp <- match("r", ininit, nomatch=NA) if(is.na(tmp)){ init$r <- numeric(n) + 1 } else{ if (length(init$r) < n) stop("Incorrect init$r parameter supplied.") init$r <- init$r[1:n] } if (sum(is.na(init$r)) | sum(init$r <= 0) | sum(init$r > init$mixture[1])) stop("Incorrect init$r parameter supplied.") if (!nrandom){ init$D <- 0 ininit <- names(init) } else{ tmp <- match("D", ininit, nomatch=NA) if(is.na(tmp)){ init$D <- diag(nrandom)[lower.tri(diag(nrandom), diag = TRUE)] } else{ if (length(init$D) < 0.5*nrandom*(1+nrandom)) stop("Incorrect init$D parameter supplied.") init$D <- init$D[1:(0.5*nrandom*(1+nrandom))] } if (sum(is.na(init$D))) stop("Incorrect init$D parameter supplied.") } tmp <- match("otherp", ininit, nomatch=NA) if(is.na(tmp)){ init$otherp <- 1 } else{ init$otherp <- init$otherp[1] } if (sum(is.na(init$otherp))) stop("Incorrect init$otherp parameter supplied.") tmp <- match("u", ininit, nomatch=NA) if(is.na(tmp)){ init$u <- c(runif(1), 0, 0, runif(3*(prior$kmax - 1))) } else{ if (length(init$u) < 3*prior$kmax) stop("Incorrect init$u parameter supplied.") init$u <- init$u[1:(3*prior$kmax)] } if (sum(is.na(init$u))) stop("Incorrect init$u parameter supplied.") if (sum(init$u < 0 | init$u > 1)) stop("Incorrect init$u parameter supplied.") tmp <- match("dirichlet.w", inprior, nomatch=NA) if(is.na(tmp)) prior$dirichlet.w <- 1 if (prior$dirichlet.w < 1) stop ("prior$dirichlet.w must be at least 1.") prior.pard["delta"] <- prior$dirichlet.w tmp <- match("mean.mu", inprior, nomatch=NA) if(is.na(tmp)) prior$mean.mu <- init$mixture[2 + prior.pari["kmax"]] tmp <- match("var.mu", inprior, nomatch=NA) if(is.na(tmp)) prior$var.mu <- 2*init$mixture[2 + 2*prior.pari["kmax"]] if (prior$var.mu <= 0) stop("prior$var.mu must be positive.") prior.pard["xi"] <- prior$mean.mu prior.pard["kappa"] <- prior$var.mu tmp <- match("shape.invsig2", inprior, nomatch=NA) if(is.na(tmp)) prior$shape.invsig2 <- 1.5 tmp <- match("shape.hyper.invsig2", inprior, nomatch=NA) if(is.na(tmp)) prior$shape.hyper.invsig2 <- 0.8 tmp <- match("rate.hyper.invsig2", inprior, nomatch=NA) if(is.na(tmp)) prior$rate.hyper.invsig2 <- prior$var.mu if (prior$shape.invsig2 <= 0) stop("prior$shape.invsig2 must be positive.") if (prior$shape.hyper.invsig2 <= 0) stop("prior$shape.hyper.invsig2 must be positive.") if (prior$rate.hyper.invsig2 <= 0) stop("prior$rate.hyper.invsig2 must be positive.") prior.pard["zeta"] <- prior$shape.invsig2 prior.pard["g"] <- prior$shape.hyper.invsig2 prior.pard["h"] <- prior$rate.hyper.invsig2 k.is.fixed <- (prior.pari["k.prior"] == 2) tmp <- match("pi.split", inprior, nomatch=NA) tmp <- match("pi.birth", inprior, nomatch=NA) if (k.is.fixed){ prior$pi.split <- 0 prior$pi.birth <- 0 } else{ if(is.na(tmp)) prior$pi.split <- c(1, rep(0.5, prior.pari["kmax"]-2), 0) if(is.na(tmp)) prior$pi.birth <- c(1, rep(0.5, prior.pari["kmax"]-2), 0) if (prior$pi.split[1] != 1) stop("prior$pi.split[1] must be equal to 1.") if (prior$pi.birth[1] != 1) stop("prior$pi.birth[1] must be equal to 1.") if (prior$pi.split[prior.pari["kmax"]] != 0) stop("prior$pi.split[kmax] must be equal to 0.") if (prior$pi.birth[prior.pari["kmax"]] != 0) stop("prior$pi.birth[kmax] must be equal to 0.") if (length(prior$pi.split) != prior.pari["kmax"]) stop("Incorrect length of a vector prior$pi.split.") if (length(prior$pi.birth) != prior.pari["kmax"]) stop("Incorrect length of a vector prior$pi.birth.") } prior.pard[paste("pi.split", 1:prior.pari["kmax"], sep = "")] <- prior$pi.split prior.pard[paste("pi.birth", 1:prior.pari["kmax"], sep = "")] <- prior$pi.birth priordi <- list(integer = prior.pari, double = prior.pard) attr(priordi, "init") <- init attr(priordi, "prior") <- prior return(priordi) }
context("Testing CEEMDAN") set.seed(1) test_that("bogus arguments throw error",{ expect_error(ceemdan("abc")) expect_error(ceemdan(1:3, noise_strength = -1, threads = 1)) expect_error(ceemdan(1:3, num_siftings = 0, S_number = 0, threads = 1)) expect_error(ceemdan(1:3, num_imfs = -1, threads = 1)) expect_error(ceemdan(1:3, num_siftings = -3, threads = 1)) expect_error(ceemdan(1:3, ensemble_size = 0, threads = 1)) expect_error(ceemdan(1:3, num_imfs = "lots", threads = 1)) }) test_that("series full of zeroes should produce only zeroes",{ x <- numeric(64) imfs <- ceemdan(x, ensemble_size = 10, threads = 1) expect_true(all(imfs == 0)) }) test_that("residual is close to the disturbed signal",{ n <- 100 x <- seq(1, 10, length.out = n) ^ 2 + rnorm(n, sd = 0.5) imfs <- ceemdan(x, threads = 1) residual <- imfs[, 6] expect_equal(residual[11:90], x[11:90], tol = 0.1) }) test_that("different seeds give different results",{ x <- rnorm(64) expect_false(isTRUE(all.equal(ceemdan(x, rng_seed = 1, threads = 1), ceemdan(x, rng_seed = 2, threads = 1)))) }) test_that("identical seeds give equal results",{ x <- rnorm(64) expect_equal(ceemdan(x, rng_seed = 1, threads = 1), ceemdan(x, rng_seed = 1, threads = 1)) }) test_that("subsets of IMFs are identical for different num_imfs",{ x <- rnorm(64) imfs3 <- ceemdan(x, num_imfs = 3, rng_seed = 1, threads = 1) imfs4 <- ceemdan(x, num_imfs = 4, rng_seed = 1, threads = 1) expect_equal(imfs3[, 1:2], imfs4[, 1:2]) }) test_that("num_imfs = 1 returns residual which equals data",{ x <- rnorm(64) imfs <- ceemdan(x, num_imfs = 1, threads = 1) expect_identical(c(imfs), x) }) test_that("sum of imfs equals to original series",{ x <- rnorm(64) expect_equal(rowSums(ceemdan(x, threads = 1)), x) })
pkgInfo <- function(pkg, leaveRemains = FALSE) { package <- unzipPackage(pkg) bp <- basename(package) dn <- dirname(package) if(!leaveRemains) on.exit(unlink(dn, recursive = TRUE)) pd <- utils::packageDescription(bp, dn, c('Version', 'Imports', 'Suggests', 'Collate')) vn <- pd$Version imp <- gsub('\n', ' ', pd$Imports) if(!is.na(imp)) { toload <- sub(' .*', '', strsplit(imp, ",[ ]?")[[1]]) srchpth <- basename(searchpaths()) toload <- setdiff(toload, srchpth) for(i in seq_along(toload)) { suppressMessages(didload <- require(toload[i], character.only = TRUE)) if(!didload) { warning(sprintf('imported package failed to load: %s', toload[i])) } } tounload <- setdiff(basename(searchpaths()), srchpth) on.exit({ for(i in seq_along(tounload)) { detach(paste0('package:', tounload[i]), character.only = TRUE) } }, add = TRUE) } sug <- gsub('\n', ' ', pd$Suggests) coll <- pd$Collate dat <- utils::data(package = bp, lib.loc = dn) dsn <- unname(dat[['results']][,'Item']) if(length(dsn)) { e <- new.env() ddf <- data.frame(data = dsn, nrow = NA, ncol = NA) for(i in seq_along(dsn)) { do.call(utils::data, list(dsn[i], package = bp, lib.loc = dn, envir = e)) dimval <- dim(e[[dsn[i]]]) if(is.null(dimval)) { ddf[i,3] <- length(e[[dsn[i]]]) } else if(length(dimval) == 2) { ddf[i,2:3] <- dimval } else { ddf[i,2:3] <- c(dimval[1], paste(dimval[-1], collapse = 'x')) } } rm(e) } else { ddf <- data.frame(data = NA, nrow = NA, ncol = NA)[FALSE,] } code_files <- tools::list_files_with_type(file.path(package, 'R'), "code", full.names = TRUE) if(!is.na(coll)) { coll_order <- strsplit(coll, "[[:space:]]")[[1]] coll_order <- file.path(package, 'R', gsub("'", '', coll_order)) code_files <- c(coll_order, setdiff(code_files, coll_order)) } e <- sourcerer(code_files) le <- ls(envir = e) obj <- vapply(le, function(z) is.function(e[[z]]), logical(1)) fun <- names(obj[obj]) var <- names(obj[!obj]) arg <- lapply(fun, function(z) names(formals(e[[z]]))) names(arg) <- fun nsf <- parseNamespaceFile(bp, dn) exp_list <- nsf[grep('export', names(nsf))] patterns <- grep('Patterns', names(exp_list)) pat_list <- unname(unlist(exp_list[patterns])) exp <- unname(unlist(exp_list[-patterns])) if(nrow(nsf$S3methods)) { s3_fun <- paste(nsf$S3methods[,1], nsf$S3methods[,2], sep = '.') exp <- c(exp, s3_fun) } if(length(pat_list)) { pat_fun <- fun[unlist(lapply(pat_list, grep, fun))] exp <- c(exp, pat_fun) } exp <- sort(unique(exp)) imp_list <- nsf[grep('import', names(nsf))] all_imp <- lapply(imp_list, function(i) vapply(i, paste, character(1), collapse = '::')) imp_fun <- unique(unname(unlist(all_imp))) imp_fun <- imp_fun[order(grepl(':', imp_fun), imp_fun)] doc_files <- tools::list_files_with_type(file.path(package, 'man'), "docs", full.names = TRUE) docmac <- tools::loadPkgRdMacros(package) doctxt <- lapply(doc_files, function(d) { rd <- tools::parse_Rd(d, macros = docmac) paste(paste(utils::capture.output(tools::Rd2txt(rd, options = list(underline_titles = FALSE))), collapse = '\n'), '\n') }) names(doctxt) <- sub('.Rd', '', basename(doc_files)) x <- list( Package = bp, Version = vn, Imports = imp, Suggests = sug, ImportedFunctions = imp_fun, ExportedFunctions = exp, AllFunctions = fun, FormalArgs = arg, Data = ddf, documentation = doctxt ) class(x) <- 'pkgInfo' x }
secder <- function(A, k, l) { n <- dim(A)[1] svec <- matrix(0, nrow = n^2, ncol = n) scalesens <- matrix(0, nrow = n^2, ncol = n - 1) d2 <- matrix(0, nrow = n, ncol = n) ev <- eigen(A) L <- ev$values o <- order(Mod(L)) W <- ev$vectors V <- solve(Conj(W)) V <- t(Conj(V)) o <- order(Mod(L)) V <- V[, rev(o)] for (i in 1:n) { senmat <- Conj(V[, i]) %*% t(W[, i]) svec[, i] <- matrix(senmat, nrow = n^2, ncol = 1) } s1 <- svec[, 1] for (m in 2:n) { scalesens[, m - 1] <- svec[, m] / (L[1] - L[m]) } vecsum <- t(apply(scalesens, 1, sum)) for (i in 1:n) { for (j in 1:n) { x1 <- (l - 1) * n + 1 + (i - 1) x2 <- (j - 1) * n + 1 + (k - 1) d2[i, j] <- s1[x1] * vecsum[x2] + s1[x2] * vecsum[x1] } } d2 <- Re(d2) d2[A == 0] <- 0 return(d2) }
iccplot <- function(object,...)UseMethod("iccplot")
knotsFromProfileEdges <- function(lrthreshold) { profedges <- NULL profileEdges <- blackbox.getOption("profileEdges") if(! is.null(nrow(profileEdges))) { liks <- apply(profileEdges, 1, purefn, testhull=F) profedges <- profileEdges[which(liks>lrthreshold), , drop=FALSE] if(nrow(profedges)>0) { profedges <- q2d(redundant(d2q(cbind(0, 1, profedges)), representation="V")$output[, -c(1:2), drop=FALSE]) colnames(profedges) <- colnames(profileEdges) } } return(profedges) }
source("ESEUR_config.r") plot_layout(2, 1) pal_col=rainbow(2) c_lines=read.csv(paste0(ESEUR_dir, "sourcecode/c_linelen.csv.xz"), as.is=TRUE) h_lines=read.csv(paste0(ESEUR_dir, "sourcecode/h_linelen.csv.xz"), as.is=TRUE) plot(c_lines$length, c_lines$occurrences, log="y", col=pal_col[1], xaxs="i", yaxs="i", xlim=c(0, 250), xlab="Characters on line", ylab="Lines\n") points(h_lines$length, h_lines$occurrences, col=pal_col[2]) legend(x="topright", legend=c(".c files", ".h files"), bty="n", fill=pal_col, cex=1.2) c_toks=read.csv(paste0(ESEUR_dir, "sourcecode/c_linetok.csv.xz"), as.is=TRUE) h_toks=read.csv(paste0(ESEUR_dir, "sourcecode/h_linetok.csv.xz"), as.is=TRUE) plot(c_toks$tokens, c_toks$occurrences, log="y", col=pal_col[1], xaxs="i", yaxs="i", xlim=c(0, 100), xlab="Tokens on line", ylab="Lines") points(h_toks$tokens, h_toks$occurrences, col=pal_col[2]) legend(x="topright", legend=c(".c files", ".h files"), bty="n", fill=pal_col, cex=1.2)
test_that("zero length inputs return correct clases", { expect_s3_class(ident(), "ident") }) test_that("ident quotes", { con <- simulate_dbi() x1 <- ident("x") expect_equal(escape(x1, con = con), sql('`x`')) expect_equal(as.sql(x1), x1) })
diag2silhouette <- function(homology, dimension=1, p=2, nseq=100){ if (!inherits(homology,"homology")){ stop("* diag2silhouette : input 'homology' is not a valid homology object. Please use an output from 'diagRips' or other construction algorithms.") } dimension = round(dimension) if (!(dimension %in% homology$Dimension)){ stop("* diag2silhouette : input 'dimension' does not have corresponding information in the given 'homology'.") } idin = which(homology$Dimension==dimension) dat.dim = round(homology$Dimension[idin]) dat.birth = homology$Birth[idin] dat.death = homology$Death[idin] myp = max(1, as.double(p)) myt = seq(from=0, to=max(dat.death), length.out=max(10, round(nseq))) out.numerator = rep(0,length(myt)) out.denominator = 0 for (i in 1:length(dat.birth)){ bj = dat.birth[i] dj = dat.death[i] weightj = (base::abs(bj-dj)^myp) out.denominator = out.denominator + weightj out.numerator = out.numerator + (weightj*base::pmax(base::pmin(myt-bj, dj-myt), rep(0,length(myt)))) } lbdfun = as.vector((out.numerator/out.denominator)) res = list(lambda=lbdfun, tseq=myt, dimension=dimension) class(res) = "silhouette" return(res) }
context("fread_bib") test_that("fread_bib output", { bibDT <- fread_bib("./fread-bib/1.bib") expect_equal(bibDT[1][["key"]], "AG-2016-Super-splitting-laws-FAQ") expect_equal(bibDT[field == "year"][["value"]], "2016") bibDT_w_braces <- fread_bib("./fread-bib/1.bib", strip.braces = FALSE) expect_equal(bibDT_w_braces[line_no == "2"][["field"]], "author") expect_equal(bibDT_w_braces[line_no == "2"][["value"]], "{{Attorney-General's Department}}") }) test_that(".bib_expected", { tempf <- tempfile() file.create(tempf) expect_warning(fread_bib(tempf), regexp = "File extension is not '.bib'.", fixed = TRUE) expect_message(fread_bib(tempf, .bib_expected = FALSE), regexp = "Returning empty") tempf <- tempfile(fileext = ".bib") file.create(tempf) expect_warning(fread_bib(tempf, .bib_expected = FALSE), regexp = "File extension is not '.bib'.", fixed = TRUE) expect_message(fread_bib(tempf, .bib_expected = TRUE), regexp = "Returning empty") })
print.ddf<-function(x, ...){ cat("\nDistance sampling analysis object\n") print(summary(x)) invisible() }
context("plotFingerPrint") if (!exists("Example_DETha98")) load("data/Example_DETha98.RData") EddyData.F <- Example_DETha98 EddyDataWithPosix.F <- suppressMessages(fConvertTimeToPosix( EddyData.F, 'YDH', Year = 'Year', Day = 'DoY', Hour = 'Hour')) EddyData99.F <- EddyData.F EddyData99.F$Year <- 1999 EddyDataWithPosix2yr.F <- suppressMessages(fConvertTimeToPosix(rbind( EddyData.F, EddyData99.F), 'YDH', Year = 'Year', Day = 'DoY', Hour = 'Hour')) rm( EddyData99.F ) EddyProc.C <- sEddyProc$new('DE-Tha', EddyDataWithPosix.F, c('NEE','Rg', 'Tair', 'VPD')) data <- cbind( EddyProc.C$sDATA, EddyProc.C$sTEMP) dts <- EddyProc.C$sINFO$DTS test_that("plotting NEE with class method",{ EddyProc.C$sPlotFingerprintY("NEE", Year = 1998) }) test_that("plotting NEE with different range",{ EddyProc.C$sPlotFingerprintY( "NEE", Year = 1998, valueLimits = quantile(EddyProc.C$sDATA$NEE, prob = c( 0.05, 0.99), na.rm = TRUE)) }) test_that("plotting legend only",{ EddyProc.C$sPlotFingerprintY("NEE", Year = 1998, onlyLegend = TRUE) }) test_that("plotting NEE",{ sEddyProc_sPlotFingerprintY("NEE", Year = 1998, data = data, dts = dts) }) test_that("plotting NEE with Inf-values",{ data2 <- data data2$NEE[5:10][is.finite(data2$NEE[5:10])] <- Inf sEddyProc_sPlotFingerprintY("NEE", Year = 1998, data = data2, dts = dts) }) test_that("plotting NEE to pdf",{ skip_on_cran() EddyProc.C$sPlotFingerprint("NEE", Dir = tempdir()) }) test_that("plot diurnal cycle of NEE to pdf",{ skip_on_cran() EddyProc.C$sPlotDiurnalCycle("NEE", Dir = tempdir()) }) test_that("sPlotHHFluxes",{ skip_on_cran() EddyProc.C$sPlotHHFluxes("NEE", Dir = tempdir()) }) test_that("sPlotDailySums",{ skip_on_cran() EddyProc.C$sPlotDailySums("NEE", Dir = tempdir()) })
fdm <- function(formula, data, id = NULL, wave = NULL, use.wave = FALSE, min.waves = 1, variance = c("toeplitz-1", "constrained", "unconstrained"), error.type = c("CR2", "CR1S"), ...) { if (!requireNamespace("nlme")) need_package("nlme") if (!requireNamespace("clubSandwich")) need_package("clubSandwich") the_call <- match.call() the_env <- parent.frame() formula <- Formula::Formula(formula) prepped <- diff_data(formula = formula, data = data, id = id, wave = wave, min.waves = min.waves, weights = NULL, use.wave = use.wave, escape = TRUE) e <- prepped$e pf <- prepped$pf data <- e$data wave <- prepped$wave id <- prepped$id dv <- prepped$dv fin_formula <- as.formula(e$fin_formula) if (!is.null(pf$constants)) { constants <- paste(pf$constants, collapse = " - ") up_form <- as.formula(paste(". ~ . -", constants)) fin_formula <- update(fin_formula, up_form) } if (variance[1] == "unconstrained") { cor_form <- as.formula(paste("~ 1 |", id)) var_form <- as.formula(paste("~ 1 |", wave)) corr <- nlme::corSymm(form = cor_form) weights <- nlme::varIdent(form = var_form) } else if (variance[1] == "constrained") { cor_form <- as.formula(paste(" ~ 1 |", id)) corr <- nlme::corARMA(value = -.9999, form = cor_form, p = 0, q = 1, fixed = TRUE) weights <- NULL } else if (variance[1] == "toeplitz-1") { cor_form <- as.formula(paste(" ~ 1 |", id)) corr <- nlme::corARMA(form = cor_form, p = 0, q = 1) weights <- NULL } gls_mod <- nlme::gls(fin_formula, data = as.data.frame(data), na.action = na.omit, correlation = corr, weights = weights) gls_mod$call$model <- substitute(fin_formula) the_vcov <- vcov_CR(gls_mod, cluster = data[[id]], type = error.type[1], data = data) coef_table <- clubSandwich::coef_test(gls_mod, vcov = the_vcov, test = "naive-t", cluster = data[[id]]) coef_table <- as.data.frame(coef_table[c("beta","SE","tstat","p_t")]) if ("tstat" %nin% names(coef_table)) { names(coef_table) <- c("estimate", "std.error", "p.value") coef_table["statistic"] <- coef_table$estimate / coef_table$std.error } else { names(coef_table) <- c("estimate", "std.error", "statistic", "p.value") coef_table["term"] <- rownames(coef_table) } mod_info <- list(dv = dv, min.wave = prepped$minwave, max.wave = prepped$maxwave, num_distinct = prepped$num_distinct, AIC = AIC(gls_mod), BIC = BIC(gls_mod), variance = variance[1], errors = error.type[1]) gls_mod$mod_info <- mod_info gls_mod$coef_table <- coef_table colnames(the_vcov) <- rownames(coef_table) rownames(the_vcov) <- rownames(coef_table) gls_mod$vcov <- the_vcov class(gls_mod) <- c("fdm", "gls") gls_mod } summary.fdm <- function(object, ...) { dots <- list(...) if ("digits" %in% names(dots)) { digits <- dots$digits } else { digits <- getOption("jtools-digits", 2) } x <- object mod_fit <- paste0(bold("MODEL FIT:\n"), italic("AIC = "), round(x$mod_info$AIC, digits), italic(", BIC = "), round(x$mod_info$BIC, digits), "\n") if (x$mod_info$variance == "toeplitz-1") { corstruct <- object$modelStruct$corStruct class(corstruct) <- "corARMA" theta <- coef(corstruct, unconstrained = FALSE) variance <- paste0(italic("Variance structure: "), x$mod_info$variance, " (theta = ", round(theta, digits), ")") } else { variance <- paste0(italic("Variance structure: "), x$mod_info$variance) } mod_info <- paste0(bold("MODEL INFO:\n"), italic("Entities: "), x$mod_info$num_distinct, "\n", italic("Time periods: "), paste0(x$mod_info$min.wave, "-", x$mod_info$max.wave), "\n", italic("Dependent variable: "), x$mod_info$dv, "\n", variance ) mod_info_list <- list(N = x$mod_info$num_distinct, min_wave = x$mod_info$min.wave, max_wave = x$mod_info$max.wave, variance = x$mod_info$variance, AIC = x$mod_info$AIC, BIC = x$mod_info$BIC) coef_table <- x$coef_table names(coef_table) <- sapply(names(coef_table), function(x) {switch(x, "estimate" = "Est.", "std.error" = "S.E.", "p.value" = "p", "statistic" = "t val.", x )}) rownames(coef_table) <- coef_table$term coef_table <- coef_table[c("Est.", "S.E.", "t val.", "p")] out <- list(mod_info = mod_info, coef_table = coef_table, digits = digits, mod_fit = mod_fit, errors = x$mod_info$errors, mod_info_list = mod_info_list) class(out) <- "summary.fdm" out } print.summary.fdm <- function(x, ...) { cat(x$mod_info, "\n\n") cat(x$mod_fit, "\n") cat(italic("Standard errors:"), x$errors, "\n") print(md_table(x$coef_table, digits = x$digits, sig.digits = FALSE, format = getOption("panelr.table.format", "multiline"))) } make_diff_data <- function(formula, data, id = NULL, wave = NULL, use.wave = FALSE, min.waves = 1, weights = NULL, offset = NULL, asym = FALSE, cumulative = FALSE, escape.names = FALSE, ...) { the_call <- match.call() the_env <- parent.frame() formula <- Formula::Formula(formula) prepped <- diff_data(formula = formula, data = data, id = id, wave = wave, min.waves = min.waves, weights = !! enquo(weights), offset = !! enquo(offset), use.wave = use.wave, ignore.lhs = cumulative, asym = asym, escape = escape.names) prepped$e$data } diff_data <- function(formula, data, id = NULL, wave = NULL, min.waves = 2, weights = NULL, offset = NULL, use.wave = FALSE, asym = FALSE, ignore.lhs = FALSE, escape = TRUE, ...) { if ("panel_data" %in% class(data)) { id <- attr(data, "id") wave <- attr(data, "wave") } if ("data.frame" %nin% class(data)) { stop("data argument must be a data frame.") } data <- panel_data(data, id = !! sym(id), wave = !! sym(wave)) orig_data <- data weights <- eval_tidy(enquo(weights), data) if (!is.null(weights)) {data[".weights"] <- weights} offset <- eval_tidy(enquo(offset), data) if (!is.null(offset)) {data[".offset"] <- offset} dv <- as.character((attr(formula, "lhs"))) pf <- wb_formula_parser(formula, dv, data) wave_terms <- if (!is.numeric(data[[wave]])) expand_labels(data, wave) else { wave } if (any(wave_terms %in% pf$varying)) { pf$varying <- pf$varying %not% wave_terms use.wave <- TRUE } mf_form <- paste(" ~ ", paste(pf$allvars, collapse = " + "), collapse = "" ) mf_form <- formula_ticks(mf_form, names(pf$data)) if (!is.null(weights)) { mf_form <- paste(mf_form, "+", ".weights") } data <- model_frame(update(as.formula(mf_form), as.formula(paste("~ . -", id, "-", wave))), data = pf$data) pf$varying <- un_bt(pf$varying) e <- diff_model(pf, dv, data, use.wave, asym, ignore.lhs, escape) e$data <- complete_cases(e$data, min.waves = min.waves) num_distinct <- length(unique(e$data[[id]])) maxwave <- max(e$data[[wave]]) minwave <- min(e$data[[wave]]) if (use.wave == TRUE & !is.numeric(e$data[[wave]])) { e$data[[wave]] <- droplevels(e$data[[wave]]) contrasts(e$data[[wave]]) <- contr.treatment(levels(e$data[[wave]])) } if (!is.null(weights)) { weights <- e$data$.weights } if (!is.null(offset)) { offset <- e$data$.offset } list(e = e, num_distinct = num_distinct, maxwave = maxwave, minwave = minwave, weights = weights, pf = pf, id = id, wave = wave, dv = dv, orig_data = orig_data, mf_form = mf_form) } diff_model <- function(pf, dv, data, use.wave = FALSE, asym = FALSE, ignore.lhs = FALSE, escape = TRUE) { wave <- get_wave(data) id <- get_id(data) vars <- pf$varying if (ignore.lhs == FALSE) vars <- c(dv, vars) for (var in vars %not% wave) { lag_var <- paste0(bt(var), " - lag(`", var, "`)") data <- mutate(data, !! var := !! parse_expr(lag_var) ) } asym_list <- list() if (asym == TRUE) { for (var in c(pf$varying) %not% wave) { plus_var <- if (escape) paste0("plus__", var) else paste0("+", var) minus_var <- if (escape) paste0("minus__", var) else paste0("-", var) plus_expr <- paste0(bt(var), "* (", bt(var), "> 0)") neg_expr <- paste0("-", bt(var), "* (", bt(var), "< 0)") data <- mutate(data, !! plus_var := !! parse_expr(plus_expr), !! minus_var := !! parse_expr(neg_expr) ) asym_list[[var]] <- c(plus_var, minus_var) } } if (asym == FALSE) { the_terms <- make_names(un_bt(c(pf$varying, pf$wint_labs, pf$cint_labs)), int = TRUE) the_terms <- str_replace_all(the_terms, "_by_", "\\*") names(data) <- make_names(names(data)) if (!is.null(c(pf$wint_labs, pf$cint_labs))) { ints <- asym_ints(data = data, pf = pf, asym_list = list()) data <- ints$data names(data) <- make_names(un_bt(names(data)), int = TRUE) the_terms <- c(the_terms, ints$new_terms) } } else { the_terms <- unlist(asym_list) varyings <- are_varying(data) which_not_varying <- the_terms %just% un_bt(names(varyings %just% FALSE)) if (length(which_not_varying) > 0) { for (var in which_not_varying) { plus <- if (escape) "plus__" else "^\\+" minus <- if (escape) "minus__" else "^\\-" if (stringr::str_detect(var, paste0("^", plus))) { bare_var <- stringr::str_extract(var, paste0("(?<=(", plus, ")).*")) msg_wrap(bare_var, " does not increase over time so +", bare_var, " is not included in the model.") } else if (stringr::str_detect(var, paste0("^", minus))) { bare_var <- stringr::str_extract(var, paste0("(?<=(", minus, ")).*")) msg_wrap(bare_var, " does not decrease over time so -", bare_var, " is not included in the model.") } } } the_terms <- the_terms %not% un_bt(names(varyings %just% FALSE)) asym_list <- lapply(asym_list, function(x) { x %not% un_bt(names(varyings %just% FALSE)) }) lengths <- sapply(asym_list, length) == 2 asym_list <- asym_list[lengths] if (escape) { asym_list <- lapply(asym_list, make_names) names(asym_list) <- make_names(names(asym_list)) the_terms <- make_names(the_terms) names(data) <- make_names(names(data)) } else { the_terms <- bt(the_terms) } if (!is.null(c(pf$wint_labs, pf$cint_labs))) { ints <- asym_ints(data = data, pf = pf, asym_list = asym_list, escape = escape) data <- ints$data if (escape) { names(data) <- make_names(names(data)) } the_terms <- c(the_terms, ints$new_terms) } } if (asym == TRUE & ignore.lhs == TRUE) { for (var in c(pf$varying) %not% wave) { plus_var <- if (escape) paste0("plus__", var) else paste0("+", var) minus_var <- if (escape) paste0("minus__", var) else paste0("-", var) set_zero_plus <- paste0("case_when(", wave, " == ", get_periods(data)[1], " ~ 0, TRUE ~", bt(plus_var), ")") set_zero_neg <- paste0("case_when(", wave, " == ", get_periods(data)[1], " ~ 0, TRUE ~", bt(minus_var), ")") plus_expr <- paste0("cumsum(", bt(plus_var), ")") neg_expr <- paste0("cumsum(", bt(minus_var), ")") data <- mutate(data, !! plus_var := !! parse_expr(set_zero_plus), !! minus_var := !! parse_expr(set_zero_neg), !! plus_var := !! parse_expr(plus_expr), !! minus_var := !! parse_expr(neg_expr) ) } } fin_formula <- paste(bt(dv), "~", paste(the_terms, collapse = " + ")) if (use.wave == TRUE) fin_formula <- paste(fin_formula, "+", wave) out <- list(data = data, fin_formula = fin_formula, asym_list = asym_list) return(out) } asym_ints <- function(data, pf, asym_list, escape = TRUE) { all_ints <- c(pf$wint_labs, pf$cint_labs) all_terms <- NULL for (int in all_ints) { name_make <- if (escape) make_names else function(x) return(x) splits <- as.list(name_make(un_bt(str_split(int, "\\*")[[1]]))) names(splits) <- splits for (spl in names(splits)) { if (un_bt(spl) %in% names(asym_list)) { splits[[spl]] <- asym_list[[un_bt(spl)]] } } term_grid <- expand.grid(splits) term_grid <- as.data.frame(lapply(term_grid, bt)) new_terms <- rep(NA, nrow(term_grid)) for (r in 1:nrow(term_grid)) { new_terms[r] <- paste0(unlist(term_grid[r, , drop = TRUE]), collapse = "*") } all_terms <- c(all_terms, new_terms) } list(data = data, new_terms = all_terms) } coef.fdm <- function(object, ...) { out <- object$coef_table$estimate names(out) <- rownames(object$coef_table) out } vcov.fdm <- function(object, ...) { object$vcov } confint.fdm <- function(object, parm, level = .95, ...) { confint.wbgee(object, parm = parm, level = level, ...) } tidy.fdm <- function(x, conf.int = FALSE, conf.level = .95, ...) { if (!requireNamespace("generics")) { stop_wrap("You must have the generics package to use tidy methods.") } params <- x$coef_table if (conf.int == TRUE) { ints <- as.data.frame(confint(x, level = conf.level)) names(ints) <- c("conf.low", "conf.high") ints$term <- stringr::str_remove_all(rownames(ints), "`") params <- dplyr::left_join(params, ints, by = "term") } return(tibble::as_tibble( params %just% c("term", "estimate", "statistic", "std.error", "conf.low", "conf.high", "p.value", "group") )) } glance.fdm <- function(x, ...) { sum <- summary(x) mod_info_list <- sum$mod_info_list mod_info_list[sapply(mod_info_list, is.null)] <- NA return(tibble::as_tibble(mod_info_list)) }
x <- 1:3 expect_equal( case_when( x <= 1 ~ 1, x <= 2 ~ 2, x <= 3 ~ 3 ), c(1, 2, 3), info = "case_when() matches values in order" ) x <- 1:3 expect_equal( case_when( x <= 1 ~ 1, x <= 2 ~ 2 ), c(1, 2, NA), info = "case_when() unmatched gets missing value" ) x <- c(1:3, NA) expect_equal( case_when( x <= 1 ~ 1, x <= 2 ~ 2, is.na(x) ~ 0 ), c(1, 2, NA, 0), info = "case_when() missing values can be replaced" ) expect_equal( case_when( c(TRUE, FALSE, NA) ~ 1:3, TRUE ~ 4L ), c(1L, 4L, 4L), info = "case_when() NA conditions" ) expect_equal( case_when( TRUE ~ 1:3, FALSE ~ 4:6 ), 1:3, info = "case_when() atomic conditions 1" ) expect_equal( case_when( NA ~ 1:3, TRUE ~ 4:6 ), 4:6, info = "case_when() atomic conditions 2" ) expect_equal( case_when( TRUE ~ integer(), FALSE ~ integer() ), integer(), info = "case_when() zero-length conditions and values 1" ) expect_equal( case_when( logical() ~ 1, logical() ~ 2 ), numeric(), info = "case_when() zero-length conditions and values 2" ) res <- data.frame(a = 1:3) %>% mutate(b = (function(x) case_when(x < 2 ~ TRUE, TRUE ~ FALSE))(a)) %>% pull() expect_equal(res, c(TRUE, FALSE, FALSE), info = "case_when() can be used in anonymous functions") res <- mtcars %>% mutate(efficient = case_when(mpg > 25 ~ TRUE, TRUE ~ FALSE)) %>% pull() expect_equal( res, c( FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE ), info = "case_when() can be used inside mutate()" ) expect_error( case_when(c(TRUE, FALSE) ~ 1:3, c(FALSE, TRUE) ~ 1:2), info = "case_when() must return the correct amount of RHS values." ) expect_error( case_when(50 ~ 1:3), info = "case_when() must return a logical vector." ) expect_error( case_when(paste(50)), info = "case_when() requires formula inputs." ) expect_error( case_when(), info = "No cases provided." )
is.multi_transiogram <- function(object) { if(!is(object, "multi_transiogram")) return(FALSE) if(!prod(c("lags", "type", "Tmat") %in% names(object))) return(FALSE) if(length(names(object)) != 3) return(FALSE) if(!is.array(object$Tmat)) return(FALSE) if(!is.numeric(object$lags)) return(FALSE) if(!is.character(object$type)) return(FALSE) if(object$type != "Empirical" && object$type != "Theoretical") return(FALSE) return(TRUE) }
Reformat23 <- function (x) { if (length(dim(x)) != 2) stop("x must be 2d") if (class(x) == "data.frame") x = data.matrix(x) nind = nrow(x) nc = ncol(x) nloc = nc/2 y = tapply(as.vector(x), rep(1:nloc, each = 2 * nind), function(x) as.numeric(as.factor(x))) ym = matrix(unlist(y), nind) nal = as.vector(sapply(y, max, na.rm = TRUE)) nalM = max(nal) g = array(dim = c(nind, nloc, nalM), 0) c1 = as.vector(row(ym)) c2 = ceiling(as.vector(col(ym))/2) c3 = as.vector(ym) qq = table(nloc * nind * (c3 - 1) + nind * (c2 - 1) + c1) g[as.numeric(names(qq))] = qq return(g) }
nd.dsd <- function(A, out.dist=TRUE, type=c("Lap","SLap","NLap","Adj")){ if ((!is.list(A))||(length(A)<=1)){ stop("* nd.csd : input 'A' should be a list of length larger than 1.") } type = match.arg(type) listA = list_transform(A, NIflag="not") N = length(listA) M = nrow(listA[[1]]) if (missing(type)){ type = "Adj" } else { type = match.arg(type) } mat_eigs = array(0,c(N,(M-1))) mat_dist = array(0,c(N,N)) for (i in 1:N){ tgt = listA[[i]] if (all(type=="Adj")){ X = as.matrix(tgt) } else if (all(type=="Lap")){ X = as.matrix(laplacian_unnormalized(tgt)) } else if (all(type=="NLap")){ X = as.matrix(laplacian_normalized(tgt)) } else if (all(type=="SLap")){ X = as.matrix(laplacian_signless(tgt)) } mat_eigs[i,] = as.vector(RSpectra::eigs(X,(M-1))$values) } for (i in 1:(N-1)){ spect1 = mat_eigs[i,] for (j in (i+1):N){ spect2 = mat_eigs[j,] solution = sqrt(sum((spect1-spect2)^2)) mat_dist[i,j] = solution mat_dist[j,i] = solution } } if (out.dist){ mat_dist = as.dist(mat_dist) } result = list() result$D= mat_dist result$spectra = mat_eigs return(result) }
structure(list(url = "https://api.twitter.com/2/tweets?tweet.fields=attachments%2Cauthor_id%2Cconversation_id%2Ccreated_at%2Centities%2Cgeo%2Cid%2Cin_reply_to_user_id%2Clang%2Cpublic_metrics%2Cpossibly_sensitive%2Creferenced_tweets%2Csource%2Ctext%2Cwithheld&user.fields=created_at%2Cdescription%2Centities%2Cid%2Clocation%2Cname%2Cpinned_tweet_id%2Cprofile_image_url%2Cprotected%2Cpublic_metrics%2Curl%2Cusername%2Cverified%2Cwithheld&expansions=author_id%2Centities.mentions.username%2Cgeo.place_id%2Cin_reply_to_user_id%2Creferenced_tweets.id%2Creferenced_tweets.id.author_id&place.fields=contained_within%2Ccountry%2Ccountry_code%2Cfull_name%2Cgeo%2Cid%2Cname%2Cplace_type&ids=1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%2C10%2C11%2C12%2C13%2C14%2C15%2C16%2C1266853931247906816%2C1266853419291234312%2C1266852781526302722%2C1266852099163291650", status_code = 200L, headers = structure(list(date = "Sun, 19 Dec 2021 20:45:28 UTC", server = "tsa_o", `api-version` = "2.32", `content-type` = "application/json; charset=utf-8", `cache-control` = "no-cache, no-store, max-age=0", `content-length` = "4210", `x-access-level` = "read", `x-frame-options` = "SAMEORIGIN", `content-encoding` = "gzip", `x-xss-protection` = "0", `x-rate-limit-limit` = "300", `x-rate-limit-reset` = "1639947531", `content-disposition` = "attachment; filename=json.json", `x-content-type-options` = "nosniff", `x-rate-limit-remaining` = "280", `strict-transport-security` = "max-age=631138519", `x-response-time` = "277", `x-connection-hash` = "7d54fc61481fbbf761f96e7412fcce2a506bf85407f0f6725ae81f8d24a33064"), class = c("insensitive", "list")), all_headers = list(list(status = 200L, version = "HTTP/2", headers = structure(list(date = "Sun, 19 Dec 2021 20:45:28 UTC", server = "tsa_o", `api-version` = "2.32", `content-type` = "application/json; charset=utf-8", `cache-control` = "no-cache, no-store, max-age=0", `content-length` = "4210", `x-access-level` = "read", `x-frame-options` = "SAMEORIGIN", `content-encoding` = "gzip", `x-xss-protection` = "0", `x-rate-limit-limit` = "300", `x-rate-limit-reset` = "1639947531", `content-disposition` = "attachment; filename=json.json", `x-content-type-options` = "nosniff", `x-rate-limit-remaining` = "280", `strict-transport-security` = "max-age=631138519", `x-response-time` = "277", `x-connection-hash` = "7d54fc61481fbbf761f96e7412fcce2a506bf85407f0f6725ae81f8d24a33064"), class = c("insensitive", "list")))), cookies = structure(list(domain = c(".twitter.com", ".twitter.com", ".twitter.com", ".twitter.com"), flag = c(TRUE, TRUE, TRUE, TRUE), path = c("/", "/", "/", "/"), secure = c(TRUE, TRUE, TRUE, TRUE), expiration = structure(c(1702744284, 1702744284, 1702744284, 1702744284), class = c("POSIXct", "POSIXt")), name = c("guest_id_marketing", "guest_id_ads", "personalization_id", "guest_id"), value = c("REDACTED", "REDACTED", "REDACTED", "REDACTED")), row.names = c(NA, -4L), class = "data.frame"), content = charToRaw("{\"data\":[{\"in_reply_to_user_id\":\"107357635\",\"created_at\":\"2020-05-30T22:08:08.000Z\",\"possibly_sensitive\":false,\"author_id\":\"126978307\",\"referenced_tweets\":[{\"type\":\"replied_to\",\"id\":\"1266831085582913538\"}],\"entities\":{\"hashtags\":[{\"start\":152,\"end\":169,\"tag\":\"FridaysForFuture\"}],\"mentions\":[{\"start\":0,\"end\":15,\"username\":\"Bastian_Atzger\",\"id\":\"107357635\"},{\"start\":16,\"end\":27,\"username\":\"LudgerWess\",\"id\":\"989716693\"}]},\"conversation_id\":\"1266677828801695744\",\"public_metrics\":{\"retweet_count\":0,\"reply_count\":1,\"like_count\":0,\"quote_count\":0},\"source\":\"Twitter Web App\",\"id\":\"1266853931247906816\",\"text\":\"@Bastian_Atzger @LudgerWess Wer nicht darauf angewiesen ist, Hetze zu betreiben, hätte vielleicht erkannt, daß diese Ausschnitte aus Plakaten weder von date = structure(1639946728, class = c("POSIXct", "POSIXt" ), tzone = "GMT"), times = c(redirect = 0, namelookup = 3.1e-05, connect = 3.2e-05, pretransfer = 0.00012, starttransfer = 0.294459, total = 0.294668)), class = "response")
theme_ipsum_es <- function( base_family="EconSansCndReg", base_size = 11.5, plot_title_family="EconSansCndBol", plot_title_size = 18, plot_title_face="bold", plot_title_margin = 10, subtitle_family=if (.Platform$OS.type == "windows") "EconSansCndLig" else "EconSansCndLig", subtitle_size = 13, subtitle_face = "plain", subtitle_margin = 15, strip_text_family = base_family, strip_text_size = 12, strip_text_face = "plain", caption_family=if (.Platform$OS.type == "windows") "EconSansCndLig" else "EconSansCndLig", caption_size = 9, caption_face = "plain", caption_margin = 10, axis_text_size = base_size, axis_title_family = base_family, axis_title_size = 9, axis_title_face = "plain", axis_title_just = "rt", plot_margin = margin(30, 30, 30, 30), panel_spacing = grid::unit(2, "lines"), grid_col = " axis_col = " ret <- ggplot2::theme_minimal(base_family = base_family, base_size = base_size) ret <- ret + theme(legend.background = element_blank()) ret <- ret + theme(legend.key = element_blank()) ret <- ret + theme(plot.margin = plot_margin) ret <- ret + theme(panel.spacing = panel_spacing) if (inherits(grid, "character") | grid == TRUE) { ret <- ret + theme(panel.grid = element_line(color = grid_col, size = 0.2)) ret <- ret + theme(panel.grid.major = element_line(color = grid_col, size = 0.2)) ret <- ret + theme(panel.grid.minor = element_line(color = grid_col, size = 0.15)) if (inherits(grid, "character")) { if (regexpr("X", grid)[1] < 0) ret <- ret + theme(panel.grid.major.x = element_blank()) if (regexpr("Y", grid)[1] < 0) ret <- ret + theme(panel.grid.major.y = element_blank()) if (regexpr("x", grid)[1] < 0) ret <- ret + theme(panel.grid.minor.x = element_blank()) if (regexpr("y", grid)[1] < 0) ret <- ret + theme(panel.grid.minor.y = element_blank()) } } else { ret <- ret + theme(panel.grid = element_blank()) ret <- ret + theme(panel.grid.major = element_blank()) ret <- ret + theme(panel.grid.major.x = element_blank()) ret <- ret + theme(panel.grid.major.y = element_blank()) ret <- ret + theme(panel.grid.minor = element_blank()) ret <- ret + theme(panel.grid.minor.x = element_blank()) ret <- ret + theme(panel.grid.minor.y = element_blank()) } if (inherits(axis, "character") | axis == TRUE) { ret <- ret + theme(axis.line = element_line(color = axis_col, size = 0.15)) if (inherits(axis, "character")) { axis <- tolower(axis) if (regexpr("x", axis)[1] < 0) { ret <- ret + theme(axis.line.x = element_blank()) } else { ret <- ret + theme(axis.line.x = element_line(color = axis_col, size = 0.15)) } if (regexpr("y", axis)[1] < 0) { ret <- ret + theme(axis.line.y = element_blank()) } else { ret <- ret + theme(axis.line.y = element_line(color = axis_col, size = 0.15)) } } else { ret <- ret + theme(axis.line.x = element_line(color = axis_col, size = 0.15)) ret <- ret + theme(axis.line.y = element_line(color = axis_col, size = 0.15)) } } else { ret <- ret + theme(axis.line = element_blank()) } if (!ticks) { ret <- ret + theme(axis.ticks = element_blank()) ret <- ret + theme(axis.ticks.x = element_blank()) ret <- ret + theme(axis.ticks.y = element_blank()) } else { ret <- ret + theme(axis.ticks = element_line(size = 0.15)) ret <- ret + theme(axis.ticks.x = element_line(size = 0.15)) ret <- ret + theme(axis.ticks.y = element_line(size = 0.15)) ret <- ret + theme(axis.ticks.length = grid::unit(5, "pt")) } xj <- switch(tolower(substr(axis_title_just, 1, 1)), b = 0, l = 0, m = 0.5, c = 0.5, r = 1, t = 1) yj <- switch(tolower(substr(axis_title_just, 2, 2)), b = 0, l = 0, m = 0.5, c = 0.5, r = 1, t = 1) ret <- ret + theme(axis.text = element_text(size = axis_text_size, margin = margin(t = 0, r = 0))) ret <- ret + theme(axis.text.x = element_text(size = axis_text_size, margin = margin(t = 0))) ret <- ret + theme(axis.text.y = element_text(size = axis_text_size, margin = margin(r = 0))) ret <- ret + theme(axis.title = element_text(size = axis_title_size, family = axis_title_family)) ret <- ret + theme(axis.title.x = element_text( hjust = xj, size = axis_title_size, family = axis_title_family, face = axis_title_face )) ret <- ret + theme(axis.title.y = element_text( hjust = yj, size = axis_title_size, family = axis_title_family, face = axis_title_face )) ret <- ret + theme(axis.title.y.right = element_text( hjust = yj, size = axis_title_size, angle = 90, family = axis_title_family, face = axis_title_face )) ret <- ret + theme(strip.text = element_text( hjust = 0, size = strip_text_size, face = strip_text_face, family = strip_text_family )) ret <- ret + theme(plot.title = element_text( hjust = 0, size = plot_title_size, margin = margin(b = plot_title_margin), family = plot_title_family, face = plot_title_face )) ret <- ret + theme(plot.subtitle = element_text( hjust = 0, size = subtitle_size, margin = margin(b = subtitle_margin), family = subtitle_family, face = subtitle_face )) ret <- ret + theme(plot.caption = element_text( hjust = 1, size = caption_size, margin = margin(t = caption_margin), family = caption_family, face = caption_face )) ret } import_econ_sans <- function() { es_font_dir <- system.file("fonts", "econ-sans", package="hrbrthemes") } font_es <- "EconSansCndReg" font_es_bold <- "EconSansCndBol" font_es_light <- "EconSansCndLig"
NULL scale_color_tq <- function(..., theme = "light") { pal <- switch(theme, "light" = unname(palette_light()) %>% rep(100), "dark" = unname(palette_dark()) %>% rep(100), "green" = unname(palette_green() %>% rep(100)) ) scale_color_manual(values = pal) } scale_colour_tq <- scale_color_tq scale_fill_tq <- function(..., theme = "light") { pal <- switch(theme, "light" = unname(palette_light()) %>% rep(100), "dark" = unname(palette_dark()) %>% rep(100), "green" = unname(palette_green()) %>% rep(100) ) scale_fill_manual(values = pal) } NULL palette_light <- function() { c( blue = " red = " green = " yellow = " steel_blue = " navy_blue = " light_green = " pink = " light_orange = " orange = " light_purple = " purple = " ) %>% toupper() } palette_dark <- function() { c( blue = " red = " green = " yellow = " steel_blue = " navy_blue = " light_green = " pink = " light_orange = " lime_green = " light_purple = " purple = " ) %>% toupper() } palette_green <- function() { c( blue = " red = " yellow = " steel_blue = " navy_blue = " creme = " pink = " light_orange = " lime_green = " light_purple = " purple = " brown = " ) %>% toupper() }
library(knotR) filename <- "7_5.svg" a <- reader(filename) Mver <- matrix( c(13,02, 12,03, 01,14, 11,04, 19,15, 18,16, 05,10, 09,06, 08,07 ), byrow=TRUE,ncol=2) ou75 <- matrix(c( 01,12, 14,02, 04,15, 11,05, 06,10, 17,07, 09,18 ),byrow=TRUE,ncol=2) sym75 <- symmetry_object(a, Mver=Mver, xver=17) jj <- knotoptim(filename, symobj = sym75, ou = ou75, prob = 0, iterlim=100, print.level=2 ) write_svg(jj,filename,safe=FALSE) dput(jj,file=sub('.svg','.S',filename))
source("ESEUR_config.r") library("plyr") plot_a_fit=function(subj) { w_mod=glm(log(FP) ~ log(CFP), data=subj) pred=predict(w_mod, newdata=data.frame(CFP=CFP_seq)) lines(CFP_seq, exp(pred), col=subj$col) } plot_fit=function(who) { d_ply(who, .(col), plot_a_fit) } plot_points=function(who) { points(who$CFP, who$FP, col=who$col) } bench=read.csv(paste0(ESEUR_dir, "statistics/BTH2011Padmanabhuni.csv.xz"), as.is=TRUE) no_students=subset(bench, Dataset != "Cuadtado_jj07" & Dataset != "Cuadtado_jj06") no_Cuadtado=subset(no_students, Dataset != "Cuadtado_2007") conv_mod=glm(FP ~ (who_FP+CFP)^2+kind+Dataset, data=no_students) conv_pmod=glm(FP ~ (who_FP+who_CFP+log(CFP))^2-who_FP:who_CFP+kind, family=poisson, data=no_students) conv_mod=glm(log(FP) ~ (who_FP+log(CFP))^2+kind, data=no_students) conv_cmod=glm(log(CFP) ~ (who_FP+log(FP))^2+kind, data=no_students) summary(conv_pmod) summary(conv_mod) summary(conv_cmod) CFP_seq=seq(20, 2000, by=5) pal_col=rainbow(4) D_names=unique(no_students$Dataset) D_cols=rainbow(length(D_names)) no_students$col=mapvalues(no_students$Dataset, D_names, D_cols) ind=subset(no_students, who_CFP == "ind") aca=subset(no_students, who_CFP != "ind") plot_layout(1, 2) plot(1, type="n", log="xy", xlim=range(no_students$CFP), ylim=range(no_students$FP), xlab="COSMIC", ylab="FPA\n") plot_points(ind) plot_points(aca) legend(x="topleft", legend=D_names, bty="n", fill=D_cols, cex=1.2) plot(1, type="n", log="xy", xlim=range(no_students$CFP), ylim=range(no_students$FP), xlab="COSMIC", ylab="FPA\n") plot_fit(ind) plot_fit(aca) library("simex") no_students=subset(no_students, !is.na(kind)) no_students$l_CFP=log(no_students$CFP) no_students$l_FP=log(no_students$FP) conv_cmod=glm(l_CFP ~ (who_FP+l_FP)^2+kind, data=no_students) conv_simex=simex(conv_cmod, SIMEXvariable="l_FP", measurement.error=no_students$l_FP/30, asymptotic=FALSE) summary(conv_simex)
cc_inference <- function(mod,B=100, alpha_max=.5,numb_cc=NULL,resamp_type="sign-flip",light=FALSE){ mod$call$cc_inference=match.call() n=nrow(mod$data$X) resamp_type=match.arg(resamp_type,c("sign-flip","permutation")) if(is.null(numb_cc)) numb_cc=length(mod$cor) if(!light) { mod=.cc_inference_orthogonal(mod,B, alpha_max,numb_cc,resamp_type) } else if(light) { mod=.cc_inference_residuals(mod,B, alpha_max,numb_cc,resamp_type) } return(mod) } .cc_inference_orthogonal <- function(mod,B, alpha_max,numb_cc,resamp_type){ resid_matrix <- function(Zy) residualizing_matrix(Zy)$Q if(resamp_type=="sign-flip"){ .permute <- function(X,Qx,nred){ t(Qx*(1-2*rbinom(nred,1,.5))) %*%X } } else if(resamp_type=="permutation"){ .permute <- function(X,Qx,nred){ t(Qx[sample(nred),]) %*%X } } perm_and_cc=function(X,Y,Qx,Qy,nredx,nredy){ ccp=.cc_core(.permute(X,Qx,nredx), .permute(Y,Qy,nredy),numb_cc = 0) ccp$cor[1] } if(is.null(mod$data$Zx)) { Qx=diag(nrow(mod$data$X)) X=mod$data$X } else{ Qx=resid_matrix(mod$data$Zx) X=Qx%*%mod$data$X } if(is.null(mod$data$Zy)) { Qy=diag(nrow(mod$data$Y)) Y=mod$data$Y } else{ Qy=resid_matrix(mod$data$Zy) Y=Qy%*%mod$data$Y } nredx=nrow(Qx) nredy=nrow(Qy) mod$p_values=rep(1,length(mod$cor)) attr(mod$p_values,which = "B")=B n_nuisx=min(0,ncol(mod$data$Zx)) n_nuisy=min(0,ncol(mod$data$Zy)) Zx=cbind(mod$data$Zx,mod$scores$xscores[,1:numb_cc]) Zy=cbind(mod$data$Zy,mod$scores$yscores[,1:numb_cc]) for(i in 1:numb_cc){ mod$p_values[i]=(sum(replicate(B,perm_and_cc(X,Y,Qx,Qy,nredx,nredy))>=mod$cor[i])+1)/(B+1) if(mod$p_values[i]>= alpha_max) return(mod) Qx=resid_matrix(Zx[,1:n_nuisx+i]) Qy=resid_matrix(Zy[,1:n_nuisy+i]) X=Qx%*%mod$data$X Y=Qy%*%mod$data$Y } return(mod) } .cc_inference_residuals <- function(mod,B, alpha_max,numb_cc,resamp_type){ n=nrow(mod$data$X) if(resamp_type=="sign-flip"){ .permute <- function(X,n){ (1-2*rbinom(n,1,.5))*X } } else if(resamp_type=="permutation"){ .permute <- function(X,n){ X[sample(n),] } } perm_and_cc=function(X,Y,n){ ccp=.cc_core(.permute(X,n), Y,numb_cc = 0) ccp$cor[1] } if(is.null(mod$data$Zx)) { X=mod$data$X } else{ X=residualize(mod$data$X,mod$data$Zx) } if(is.null(mod$data$Zy)) { Y=mod$data$Y } else{ Y=residualize(mod$data$Y,mod$data$Zy) } mod$p_values=rep(1,length(mod$cor)) attr(mod$p_values,which = "B")=B n_nuisx=min(0,ncol(mod$data$Zx)) n_nuisy=min(0,ncol(mod$data$Zy)) Zx=cbind(mod$data$Zx,mod$scores$xscores[,1:numb_cc]) Zy=cbind(mod$data$Zy,mod$scores$yscores[,1:numb_cc]) for(i in 1:numb_cc){ mod$p_values[i]=(sum(replicate(B,perm_and_cc(X,Y,n))>=mod$cor[i])+1)/(B+1) if((mod$p_values[i]>= alpha_max) | (i== numb_cc)) return(mod) X=residualize(mod$data$X,Zx) Y=residualize(mod$data$Y,Zy) } return(mod) }
mzagglom<-function( MSlist, dmzgap=10, ppm=TRUE, drtgap=500, minpeak=4, maxint=1E7, progbar=FALSE ){ if(!length(MSlist)==8){stop("This is not an MSlist object")} if(!MSlist[[1]][[1]]){stop("MSlist empty or invalid. Use readMSdata to upload raw .mzML data first.")} if(!is.loaded("agglom")){stop(".Call to agglom failed; aborted.")} if(!is.loaded("indexed")){stop(".Call to indexed failed; aborted.")} if(!is.numeric(dmzgap)){stop("dmass must be numeric; aborted.")} if(!is.numeric(drtgap)){stop("dret must be numeric; aborted.")} if(!is.logical(ppm)){stop("ppm must be logical; aborted.")} MSlist[[5]]<-0; MSlist[[6]]<-0; MSlist[[7]]<-0; MSlist[[8]]<-0; MSlist[[4]][[2]][,5]<-rep(0,length(MSlist[[4]][[2]][,4])); MSlist[[4]][[2]][,6]<-rep(0,length(MSlist[[4]][[2]][,4])); MSlist[[4]][[2]][,7]<-rep(0,length(MSlist[[4]][[2]][,4])); if(ppm){ppm2<-1}else{ppm2<-0}; MSlist[[4]][[2]]<-MSlist[[4]][[2]][order(MSlist[[4]][[2]][,1],decreasing=FALSE),] if(progbar==TRUE){prog<-winProgressBar("Agglomerate...",min=0,max=3); setWinProgressBar(prog, 0, title = "Agglomerate...", label = NULL);} part <- .Call("agglom", as.numeric(MSlist[[4]][[2]][,1]), as.numeric(MSlist[[4]][[2]][,3]), as.integer(ppm2), as.numeric(dmzgap), as.numeric(drtgap), PACKAGE="enviPick" ) if(progbar==TRUE){setWinProgressBar(prog, 1, title = "Agglomerate...", label = NULL)} MSlist[[4]][[2]]<-MSlist[[4]][[2]][order(part,decreasing=FALSE),] part<-part[order(part,decreasing=FALSE)] maxit<-max(part) index <- .Call("indexed", as.integer(part), as.numeric(MSlist[[4]][[2]][,2]), as.integer(minpeak), as.numeric(maxint), as.integer(maxit), PACKAGE="enviPick" ) index<-index[index[,2]!=0,,drop=FALSE] colnames(index)<-c("start_ID","end_ID","number_peaks") MSlist[[5]]<-index partID<-.Call("partID", as.integer(index), as.integer(length(MSlist[[4]][[2]][,5])), PACKAGE="enviPick" ) MSlist[[4]][[2]][,5]<-partID if(progbar==TRUE){setWinProgressBar(prog, 2, title = "Agglomerate...", label = NULL)} MSlist[[3]][[1]]<-length(MSlist[[4]][[2]][,1]); MSlist[[3]][[2]]<-length(index[,3]); MSlist[[3]][[3]]<-sum(index[,3]); MSlist[[2]][[2]][1]<-as.character(dmzgap) MSlist[[2]][[2]][2]<-as.character(ppm) MSlist[[2]][[2]][3]<-as.character(drtgap) MSlist[[2]][[2]][4]<-as.character(minpeak) MSlist[[2]][[2]][5]<-as.character(maxint) MSlist[[1]][[2]]<-TRUE; MSlist[[1]][[3]]<-FALSE; MSlist[[1]][[4]]<-FALSE; MSlist[[1]][[5]]<-FALSE; if(progbar==TRUE){close(prog);} return(MSlist) }
Sim.Data.MTS <- function(N.Total=2000, N.Trial=50, R.Trial.Target=.8, R.Indiv.Target=.8, Fixed.Effects=c(0, 0, 0, 0), D.aa=10, D.bb=10, Seed=sample(1:1000, size=1), Model=c("Full")) { if ((Model==c("Full") | Model==c("Reduced") | Model==c("SemiReduced"))==FALSE) {stop ("The specification of the Model=c(\"...\") argument of the call is incorrect. Use either Model=c(\"Full\"), Model=c(\"Reduced\"), or Model=c(\"SemiReduced\").")} N.patients <- N.Total/N.Trial if ((N.patients%%1==0)==FALSE) { cat("\nNOTE: The number of patients per trial requested in the function call equals ", N.patients, " (=N.Total/N.Trial), which is not a whole number. ", sep="") cat("\nThe number of patients per trial was rounded to ") N.patients <- rounded <- ceiling(N.patients) N.Total.old <- N.Total N.Total <- rounded * N.Trial cat(rounded, " to generate the dataset. Data.Observed.MTS thus contains a total of ", N.Total, " patients \nrather than the requested ", N.Total.old, " in the function call.", sep="") } R2.trial.target <- R.Trial.Target**2 if (Model==c("Full")|Model==c("SemiReduced")){ Dmat <- diag(4) Dmat[3,3] <- D.aa Dmat[4,4] <- D.bb Dmat[3,4] <- Dmat[4,3] <- sqrt(R2.trial.target * (Dmat[3,3] * Dmat[4,4])) set.seed(Seed) ran.eff <- MASS::mvrnorm(N.Trial, rep(0,4), Dmat) Smat <- diag(2) Smat[1,2] <- Smat[2,1] <- R.Indiv.Target set.seed(Seed) errors <- MASS::mvrnorm(N.Total, rep(0,2), Smat) Z <- Trial_ID <- Surr <- True <- NULL for (i in 1: N.Trial){ Z_temp <- sample(x=rep(c(-1, 1), each=(ceiling(N.patients/2))), N.patients, replace=FALSE) Trial_ID_temp <- rep(i, N.patients) Z <- append(x=Z, values=Z_temp) Trial_ID <- append(Trial_ID, Trial_ID_temp) } supp <- data.frame(cbind(Z, Trial_ID)) for (i in 1: N.Total){ Surr_temp <- (Fixed.Effects[1]) + ran.eff[supp$Trial_ID[i],1] + (((Fixed.Effects[3]) + ran.eff[supp$Trial_ID[i],3])*Z[i]) + errors[i,1] True_temp <- (Fixed.Effects[2]) + ran.eff[supp$Trial_ID[i],2] + (((Fixed.Effects[4]) + ran.eff[supp$Trial_ID[i],4])*Z[i]) + errors[i,2] Surr <- append(x=Surr, values=Surr_temp) True <- append(x=True, values=True_temp) } } if (Model==c("Reduced")){ Dmat <- diag(2) Dmat[1,1] <- D.aa Dmat[2,2] <- D.bb Dmat[1,2] <- Dmat[2,1] <- sqrt(R2.trial.target * (Dmat[1,1] * Dmat[2,2])) set.seed(Seed) ran.eff <- MASS::mvrnorm(N.Trial, rep(0,2), Dmat) Smat <- diag(2) Smat[1,2] <- Smat[2,1] <- R.Indiv.Target set.seed(Seed) errors <- MASS::mvrnorm(N.Total, rep(0,2), Smat) Z <- Trial_ID <- Surr <- True <- NULL for (i in 1: N.Trial){ Z_temp <- sample(x=rep(c(-1, 1), each=(ceiling(N.patients/2))), N.patients, replace=FALSE) Trial_ID_temp <- rep(i, N.patients) Z <- append(x=Z, values=Z_temp) Trial_ID <- append(Trial_ID, Trial_ID_temp) } supp <- data.frame(cbind(Z, Trial_ID), stringsAsFactors = TRUE) for (i in 1: N.Total){ Surr_temp <- (((Fixed.Effects[1]) + ran.eff[supp$Trial_ID[i],1])*Z[i]) + errors[i,1] True_temp <- (((Fixed.Effects[2]) + ran.eff[supp$Trial_ID[i],2])*Z[i]) + errors[i,2] Surr <- append(x=Surr, values=Surr_temp) True <- append(x=True, values=True_temp) } } Pat_ID <- 1:N.Total Data.Observed.MTS <- cbind(supp, Surr, True, Pat_ID) names(Data.Observed.MTS) <- c("Treat", "Trial.ID", "Surr", "True", "Pat.ID") Data.Observed.MTS <<- Data.Observed.MTS fit <- list(Data.Observed.MTS=Data.Observed.MTS) }
context("corner-cases") test_that("corner-cases are handled as expected", { expect_warning(withr::with_output_sink(tempfile(), { cov <- file_coverage("corner-cases.R", "corner-cases-test.R") })) expect_equal(as.data.frame(cov), readRDS("corner-cases.Rds")) })
findseeds_inwards_updating <- function(nng) { seeds <- NULL assigned <- rep(FALSE, ncol(nng)) tobechecked <- 1:ncol(nng) while (length(tobechecked) > 0) { i <- tobechecked[order(rowSums(nng[tobechecked, intersect(which(!assigned), tobechecked), drop = FALSE]))[1]] tobechecked <- setdiff(tobechecked, i) if (any(nng[, i]) && !any(assigned[nng[, i]])) { seeds <- c(seeds, i) tobechecked <- setdiff(tobechecked, which(nng[, i])) assigned[nng[, i]] <- TRUE } } seeds } findseeds_exclusion_updating <- function(nng) { seeds <- NULL exclusion_graph <- ((nng + t(nng) + t(nng) %*% nng) > 0) exclusion_graph[!apply(nng, 2, any), ] <- FALSE exclud_count <- colSums(exclusion_graph) tobechecked <- which(apply(nng, 2, any)) while (length(tobechecked) > 0) { i <- tobechecked[order(exclud_count[tobechecked])[1]] tobechecked <- setdiff(tobechecked, i) seeds <- c(seeds, i) to_exclude <- intersect(which(exclusion_graph[, i]), tobechecked) tobechecked <- setdiff(tobechecked, to_exclude) for (e in to_exclude) { for (nne in intersect(which(exclusion_graph[, e]), tobechecked)) { exclud_count[nne] <- exclud_count[nne] - 1 } } } seeds }
connection <- function() { auth <- list(host = Sys.getenv("ES_HOST"), port = Sys.getenv("ES_PORT"), path = Sys.getenv("ES_PATH"), transport = Sys.getenv("ES_TRANSPORT"), user = Sys.getenv("ES_USER")) if (is.null(auth$port) || nchar(auth$port) == 0) { baseurl <- sprintf("%s://%s", auth$transport, auth$host) } else { baseurl <- sprintf("%s://%s:%s", auth$transport, auth$host, auth$port) } if (!is.null(auth$path)) { baseurl <- file.path(baseurl, auth$path) } structure(list( transport = auth$transport, host = auth$host, port = auth$port, path = auth$path, user = auth$user, pwd = "<secret>", headers = es_env$headers, errors = Sys.getenv("ELASTIC_RCLIENT_ERRORS")), class = 'es_conn') } print.es_conn <- function(x, ...){ fun <- function(x) ifelse(is.null(x) || nchar(x) == 0, 'NULL', x) cat(paste('transport: ', fun(x$transport)), "\n") cat(paste('host: ', fun(x$host)), "\n") cat(paste('port: ', fun(x$port)), "\n") cat(paste('path: ', fun(x$path)), "\n") cat(paste('username: ', fun(x$user)), "\n") cat(paste('password: ', fun(x$pwd)), "\n") cat(paste('errors: ', fun(x$errors)), "\n") cat(paste('headers (names): ', ph(x$headers)), "\n") } es_auth <- function(es_host = NULL, es_port = NULL, es_path = NULL, es_transport_schema = NULL, es_user = NULL, es_pwd = NULL, force = FALSE, es_base = NULL) { calls <- names(sapply(match.call(), deparse))[-1] calls_vec <- "es_base" %in% calls if (any(calls_vec)) { stop("The parameter es_base has been deprecated, use es_host", call. = FALSE) } host <- ifnull(es_host, 'ES_HOST') port <- if (is.null(es_port)) "" else es_port path <- ifnull(es_path, 'ES_PATH') transport <- ifnull(es_transport_schema, 'ES_TRANSPORT_SCHEMA') user <- ifnull(es_user, 'ES_USER') pwd <- ifnull(es_pwd, 'ES_PWD') if (identical(host, "") || force) { if (!interactive()) { stop("Please set env var ES_HOST for your host url for your Elasticsearch server", call. = FALSE) } message("Couldn't find env var ES_HOST See ?es_auth for more details.") message("Please enter your Elasticsearch host url and press enter:") host <- readline(": ") if (identical(host, "")) { stop("Elasticsearch host url entry failed", call. = FALSE) } message("Updating ES_HOST env var\n") Sys.setenv(ES_HOST = host) } else { host <- host } Sys.setenv(ES_HOST = host) Sys.setenv(ES_TRANSPORT = transport) Sys.setenv(ES_PORT = port) Sys.setenv(ES_PATH = path) Sys.setenv(ES_USER = user) Sys.setenv(ES_PWD = pwd) list(host = host, port = port, path = path, transport = transport) } ifnull <- function(x, y){ if (is.null(x)) Sys.getenv(y) else x } es_get_auth <- function(){ transport <- Sys.getenv("ES_TRANSPORT") host <- Sys.getenv("ES_HOST") port <- Sys.getenv("ES_PORT") path <- Sys.getenv("ES_PATH") if (is.null(host)) stop("Please run connect()", call. = FALSE) list(transport = transport, host = host, port = port, path = path) } es_get_user_pwd <- function(){ user <- Sys.getenv("ES_USER") pwd <- Sys.getenv("ES_PWD") list(user = user, pwd = pwd) } make_url <- function(x) { url <- sprintf("%s://%s", x$transport, x$host) url <- if (is.null(x$port) || nchar(x$port) == 0) { url } else { paste(url, ":", x$port, sep = "") } if (!is.null(x$path) && nchar(x$path) > 0) { url <- file.path(url, x$path) } url } as_headers <- function(x) { UseMethod("as_headers") } as_headers.default <- function(x) NULL as_headers.request <- function(x) x as_headers.list <- function(x) { do.call(add_headers, x) } ph <- function(x) { if (is.null(x)) { 'NULL' } else { str <- paste0(names(x$headers), collapse = ", ") if (nchar(str) > 30) paste0(substring(str, 1, 30), " ...") else str } } es_env <- new.env()
Ice2 %>% filter(time == 1930, phase == "b") %>% group_by(location, treatment, phase) %>% summarise(mean(temp))
NAME <- "diffDeparse" source(file.path('_helper', 'init.R')) all.equal(as.character(diffDeparse(letters, LETTERS)), rdsf(100)) all.equal( as.character( diffDeparse(letters, LETTERS, extra=list(width.cutoff=20)) ), rdsf(200) )
collapse_ranges <- function(df, groups = NULL, start_var = NULL, end_var = NULL, startAttr = NULL, endAttr = NULL, dimension = "date", max_gap = 0L, fmt = "%Y-%m-%d", tz = "UTC", origin = "1970-01-01") { df_collapsed <- copy(df) if (!any(class(df) %in% "data.table")) setDT(df_collapsed) if (!is.null(startAttr) | !is.null(endAttr)) for (j in c(startAttr, endAttr)) set(df_collapsed, j = j, value = as.character(df_collapsed[[j]])) if (dimension == "date") { if (class(df_collapsed[[start_var]]) != 'Date' | class(df_collapsed[[end_var]]) != 'Date') { for (j in c(start_var, end_var)) set(df_collapsed, j = j, value = as.Date(as.character(df_collapsed[[j]]), format = fmt)) } setorderv(df_collapsed, c(groups, start_var)) if (!is.null(groups)) { if (!is.null(startAttr) & !is.null(endAttr)) { df_collapsed <- df_collapsed[, updateAndSubset(get(start_var), get(end_var), max_gap = max_gap, startObjects = mget(startAttr), endObjects = mget(endAttr) ), by = mget(groups)] setnames(df_collapsed, 1:ncol(df_collapsed), c(groups, start_var, end_var, startAttr, endAttr)) } else if (!is.null(startAttr) & is.null(endAttr)) { df_collapsed <- df_collapsed[, updateAndSubset(get(start_var), get(end_var), max_gap = max_gap, startObjects = mget(startAttr), endObjects = NULL ), by = mget(groups)] setnames(df_collapsed, 1:ncol(df_collapsed), c(groups, start_var, end_var, startAttr)) } else if (is.null(startAttr) & !is.null(endAttr)) { df_collapsed <- df_collapsed[, updateAndSubset(get(start_var), get(end_var), max_gap = max_gap, startObjects = NULL, endObjects = mget(endAttr) ), by = mget(groups)] setnames(df_collapsed, 1:ncol(df_collapsed), c(groups, start_var, end_var, endAttr)) } else { df_collapsed <- df_collapsed[, updateAndSubset(get(start_var), get(end_var), max_gap = max_gap, startObjects = NULL, endObjects = NULL ), by = mget(groups)] setnames(df_collapsed, 1:ncol(df_collapsed), c(groups, start_var, end_var)) } } else { if (!is.null(startAttr) & !is.null(endAttr)) { df_collapsed <- df_collapsed[, updateAndSubset(get(start_var), get(end_var), max_gap = max_gap, startObjects = mget(startAttr), endObjects = mget(endAttr) )] setnames(df_collapsed, 1:ncol(df_collapsed), c(groups, start_var, end_var, startAttr, endAttr)) } else if (!is.null(startAttr) & is.null(endAttr)) { df_collapsed <- df_collapsed[, updateAndSubset(get(start_var), get(end_var), max_gap = max_gap, startObjects = mget(startAttr), endObjects = NULL )] setnames(df_collapsed, 1:ncol(df_collapsed), c(groups, start_var, end_var, startAttr)) } else if (is.null(startAttr) & !is.null(endAttr)) { df_collapsed <- df_collapsed[, updateAndSubset(get(start_var), get(end_var), max_gap = max_gap, startObjects = NULL, endObjects = mget(endAttr) )] setnames(df_collapsed, 1:ncol(df_collapsed), c(groups, start_var, end_var, endAttr)) } else { df_collapsed <- df_collapsed[, updateAndSubset(get(start_var), get(end_var), max_gap = max_gap, startObjects = NULL, endObjects = NULL )] setnames(df_collapsed, 1:ncol(df_collapsed), c(groups, start_var, end_var)) } } } else if (dimension == "timestamp") { if (!any(class(df_collapsed[[start_var]]) %in% c('POSIXct', 'POSIXlt')) | !any(class(df_collapsed[[end_var]]) %in% c('POSIXct', 'POSIXlt'))) { if (fmt == "%Y-%m-%d") { warning("Dimension 'timestamp' selected but format unchanged. Will try to convert to '%Y-%m-%d %H:%M:%OS' ..") fmt <- "%Y-%m-%d %H:%M:%OS" } for (j in c(start_var, end_var)) set(df_collapsed, j = j, value = as.POSIXct(as.character(df_collapsed[[j]]), format = fmt, tz = tz)) } setorderv(df_collapsed, c(groups, start_var)) if (!is.null(groups)) { if (!is.null(startAttr) & !is.null(endAttr)) { df_collapsed <- df_collapsed[, updateAndSubsetTime(get(start_var), get(end_var), max_gap = max_gap, startObjects = mget(startAttr), endObjects = mget(endAttr) ), by = mget(groups)] setnames(df_collapsed, 1:ncol(df_collapsed), c(groups, start_var, end_var, startAttr, endAttr)) } else if (!is.null(startAttr) & is.null(endAttr)) { df_collapsed <- df_collapsed[, updateAndSubsetTime(get(start_var), get(end_var), max_gap = max_gap, startObjects = mget(startAttr), endObjects = NULL ), by = mget(groups)] setnames(df_collapsed, 1:ncol(df_collapsed), c(groups, start_var, end_var, startAttr)) } else if (is.null(startAttr) & !is.null(endAttr)) { df_collapsed <- df_collapsed[, updateAndSubsetTime(get(start_var), get(end_var), max_gap = max_gap, startObjects = NULL, endObjects = mget(endAttr) ), by = mget(groups)] setnames(df_collapsed, 1:ncol(df_collapsed), c(groups, start_var, end_var, endAttr)) } else { df_collapsed <- df_collapsed[, updateAndSubsetTime(get(start_var), get(end_var), max_gap = max_gap, startObjects = NULL, endObjects = NULL ), by = mget(groups)] setnames(df_collapsed, 1:ncol(df_collapsed), c(groups, start_var, end_var)) } } else { if (!is.null(startAttr) & !is.null(endAttr)) { df_collapsed <- df_collapsed[, updateAndSubsetTime(get(start_var), get(end_var), max_gap = max_gap, startObjects = mget(startAttr), endObjects = mget(endAttr) )] setnames(df_collapsed, 1:ncol(df_collapsed), c(start_var, end_var, startAttr, endAttr)) } else if (!is.null(startAttr) & is.null(endAttr)) { df_collapsed <- df_collapsed[, updateAndSubsetTime(get(start_var), get(end_var), max_gap = max_gap, startObjects = mget(startAttr), endObjects = NULL )] setnames(df_collapsed, 1:ncol(df_collapsed), c(start_var, end_var, startAttr)) } else if (is.null(startAttr) & !is.null(endAttr)) { df_collapsed <- df_collapsed[, updateAndSubsetTime(get(start_var), get(end_var), max_gap = max_gap, startObjects = NULL, endObjects = mget(endAttr) )] setnames(df_collapsed, 1:ncol(df_collapsed), c(start_var, end_var, endAttr)) } else { df_collapsed <- df_collapsed[, updateAndSubsetTime(get(start_var), get(end_var), max_gap = max_gap, startObjects = NULL, endObjects = NULL )] setnames(df_collapsed, 1:ncol(df_collapsed), c(start_var, end_var)) } } } else { stop("The dimension argument has to be either 'date' or 'timestamp'.") } if (!any(class(df) %in% "data.table")) { return(setDF(df_collapsed)) } else { return(df_collapsed) } }
writeAncestors<-function(tree,Anc=NULL,file="",digits=6,format=c("phylip","nexus"),...){ format=format[1] if(hasArg(CI)) CI<-list(...)$CI else CI<-TRUE if(is.null(Anc)){ if(hasArg(x)){ x<-list(...)$x if(inherits(tree,"multiPhylo")){ if(is.list(x)) Anc<-mapply(fastAnc,tree,x,MoreArgs=list(CI=CI),SIMPLIFY=FALSE) else Anc<-lapply(tree,fastAnc,x=x,CI=CI) } else if(inherits(tree,"phylo")){ if(is.list(x)){ Anc<-lapply(x,fastAnc,tree=tree,CI=CI) tree<-repPhylo(tree,length(x)) class(tree)<-"multiPhylo" } else Anc<-fastAnc(tree,x,CI=CI) } } else stop("must have argument 'Anc' or 'x'") } if(format=="phylip"){ if(class(tree)=="multiPhylo") XX<-mapply(writeAnc,tree,Anc,MoreArgs=list(digits=digits)) else if(class(tree)=="phylo") XX<-writeAnc(tree,Anc,digits) else stop("tree should be an object of class 'phylo' or 'multiPhylo'") write(XX,file) invisible(XX) } else if(format=="nexus"){ writeNex(tree,Anc,file,digits) } } writeNex<-function(tree,Anc,file="",digits){ if(inherits(tree,"multiPhylo")) N<-length(tree) else { N<-1 tree<-list(tree) Anc<-list(Anc) } n<-length(tree[[1]]$tip.label) write(" write(paste("[R-package PHYTOOLS, ",date(),"]\n",sep=""),file,append=TRUE) write("BEGIN TAXA;",file,append=TRUE) write(paste("\tDIMENSIONS NTAX = ",n,";",sep=""),file,append=TRUE) write("\tTAXLABELS",file,append=TRUE) trans<-tree[[1]]$tip.label; trans<-sort(trans) for(i in 1:n) write(paste("\t\t",trans[i],sep=""),file,append=TRUE) write("\t;",file,append=TRUE) write("END;",file,append=TRUE) write("BEGIN TREES;\n\tTRANSLATE",file,append=TRUE) for(i in 1:(n-1)) write(paste("\t\t",i,"\t",trans[i],",",sep=""),file,append=TRUE) write(paste("\t\t",i+1,"\t",trans[i+1],sep=""),file,append=TRUE) write("\t;",file,append=TRUE) for(i in 1:N){ tree[[i]]$tip.label<-sapply(tree[[i]]$tip.label,function(x) which(x==trans)) write(paste("\tTREE * UNTITLED = [&R] ",writeAnc(tree[[i]],Anc[[i]],digits),sep=""),file,append=TRUE) } write("END;",file,append=TRUE) } writeAnc<-function(tree,Anc,digits){ tree<-reorder.phylo(tree,"cladewise") n<-length(tree$tip.label) if(!is.list(Anc)) Anc<-list(ace=Anc) Anc$ace<-Anc$ace[order(names(Anc$ace))] Anc$ace<-round(Anc$ace,digits) if(!is.null(Anc$CI95)){ Anc$CI95<-round(Anc$CI95,digits) tree$node.label<-paste("[&CI={",Anc$CI95[,1],",",Anc$CI95[,2],"},ancstate={",Anc$ace,"}]",sep="") } else { Anc$CI95<-Anc$CI95[names(Anc$ace),] tree$node.label<-paste("[&ancstate={",Anc$ace,"}]",sep="") } tree$edge.length<-round(tree$edge.length,digits) string<-vector(); string[1]<-"("; j<-2 for(i in 1:nrow(tree$edge)){ if(tree$edge[i,2]<=n){ string[j]<-tree$tip.label[tree$edge[i,2]]; j<-j+1 if(!is.null(tree$edge.length)){ string[j]<-paste(c(":",tree$edge.length[i]),collapse="") j<-j+1 } v<-which(tree$edge[,1]==tree$edge[i,1]); k<-i while(length(v)>0&&k==v[length(v)]){ string[j]<-")"; j<-j+1 string[j]<-tree$node.label[tree$edge[k,1]-n]; j<-j+1 w<-which(tree$edge[,2]==tree$edge[k,1]) if(!is.null(tree$edge.length)){ string[j]<-paste(c(":",tree$edge.length[w]),collapse="") j<-j+1 } v<-which(tree$edge[,1]==tree$edge[w,1]); k<-w } string[j]<-","; j<-j+1 } else if(tree$edge[i,2]>=n){ string[j]<-"("; j<-j+1 } } if(is.null(tree$edge.length)) string<-c(string[1:(length(string)-1)],";") else string<-c(string[1:(length(string)-2)],";") string<-paste(string,collapse="") return(string) }
est.analysis = function(Omega.hat.list, Omega.true.list, offdiag=TRUE){ if ( !is.list(Omega.hat.list)){ stop('argument Omega.hat.list should be a list') } else if (!is.list(Omega.true.list)) { stop('argument Omega.true.list should be a list') } else if (any(!sapply(Omega.hat.list,is.matrix))) { stop('argument Omega.hat.list should be a list of precision matrices') } else if (any(!sapply(Omega.true.list,is.matrix))) { stop('argument Omega.true.list should be a list of precision matrices') } else if ( length(Omega.hat.list)!=length(Omega.true.list) ) { stop('arguments Omega.hat.list and Omega.true.list should share the same length') } else if ( any(!(sapply(Omega.hat.list,dim)[1,]==sapply(Omega.true.list,dim)[1,]))) { stop('dimension of elements in argument Omega.hat.list should match argument Omega.true.list') } else if ( !is.logical(offdiag)) { stop('argument offdiag should be a logical TRUE or FALSE ') } K = dim(as.array(Omega.hat.list)) error.f = rep(0,K) error.max = rep(0,K) tpr = rep(0,K) tnr = rep(0,K) if (offdiag==FALSE) { for(i in 1:K){ error.f[i] = norm(Omega.hat.list[[i]] - Omega.true.list[[i]], type="F") error.max[i] = norm(Omega.hat.list[[i]] - Omega.true.list[[i]], type="M") tpr[i] = length(intersect(which(Omega.hat.list[[i]] !=0 ), which(Omega.true.list[[i]] !=0))) / length(which(Omega.true.list[[i]] !=0)) tnr[i] = length(intersect(which(Omega.hat.list[[i]] ==0 ), which(Omega.true.list[[i]] ==0))) / length(which(Omega.true.list[[i]] ==0)) } KOmega.true=1;KOmega.hat=1 for (k in 1:K){ KOmega.true=kronecker(KOmega.true, Omega.true.list[[k]]) KOmega.hat=kronecker(KOmega.hat, Omega.hat.list[[k]]) } error.kro = norm(KOmega.hat - KOmega.true,type="F") tpr.kro = length(intersect(which(KOmega.hat !=0 ), which(KOmega.true !=0))) / length(which(KOmega.true !=0)) tnr.kro = length(intersect(which(KOmega.hat ==0 ), which(KOmega.true ==0))) / length(which(KOmega.true ==0)) } else { Omega.hat.list.off=Omega.hat.list Omega.true.list.off=Omega.true.list for(i in 1:K){ diag(Omega.hat.list.off[[i]])=0 diag(Omega.true.list.off[[i]])=0 error.f[i] = norm(Omega.hat.list.off[[i]] - Omega.true.list.off[[i]], type="F") error.max[i] = norm(Omega.hat.list.off[[i]] - Omega.true.list.off[[i]], type="M") diag(Omega.hat.list.off[[i]])=NA diag(Omega.true.list.off[[i]])=NA tpr[i] = length(intersect(which(Omega.hat.list.off[[i]] !=0 ), which(Omega.true.list.off[[i]] !=0))) / length(which(Omega.true.list.off[[i]] !=0)) tnr[i] = length(intersect(which(Omega.hat.list.off[[i]] ==0 ), which(Omega.true.list.off[[i]] ==0))) / length(which(Omega.true.list.off[[i]] ==0)) } KOmega.true=1;KOmega.hat=1 for (k in 1:K){ KOmega.true=kronecker(KOmega.true, Omega.true.list[[k]]) KOmega.hat=kronecker(KOmega.hat, Omega.hat.list[[k]]) } diag(KOmega.hat)=0 diag(KOmega.true)=0 error.kro = norm(KOmega.hat - KOmega.true,type="F") diag(KOmega.hat)=NA diag(KOmega.true)=NA tpr.kro = length(intersect(which(KOmega.hat !=0 ), which(KOmega.true !=0))) / length(which(KOmega.true !=0)) tnr.kro = length(intersect(which(KOmega.hat ==0 ), which(KOmega.true ==0))) / length(which(KOmega.true ==0)) } Out = list() Out$error.kro = error.kro Out$tpr.kro = tpr.kro Out$tnr.kro = tnr.kro Out$av.error.f = mean(error.f) Out$av.error.max = mean(error.max) Out$av.tpr = mean(tpr) Out$av.tnr = mean(tnr) Out$error.f = error.f Out$error.max = error.max Out$tpr = tpr Out$tnr = tnr return(Out) }
library(forecastML) library(dplyr) test_that("create_skeleton correctly preserves lagged_df objects", { data("data_seatbelts", package = "forecastML") data_lagged <- create_lagged_df(data_seatbelts, "train", "direct", horizons = 1:2, lookback = 1:3) data_skeleton <- create_skeleton(data_lagged) data_lagged_attr <- attributes(data_lagged) data_skeleton_attr <- attributes(data_skeleton)[!names(attributes(data_skeleton)) %in% "skeleton"] testthat::expect_identical(data_lagged_attr, data_skeleton_attr) })
ssc_type <- c("Mean" = "mean", "Proportion" = "proportion") ssc_alternative <- c("Two sided" = "two.sided", "Group 1 less than Group 2" = "less", "Group 1 greater than Group 2" = "greater") ssc_args <- as.list(formals(sample_size_comp)) ssc_inputs <- reactive({ for (i in names(ssc_args)) ssc_args[[i]] <- input[[paste0("ssc_", i)]] ssc_args }) output$ui_sample_size_comp <- renderUI({ tagList( wellPanel( radioButtons( inputId = "ssc_type", label = NULL, choices = ssc_type, selected = state_init("ssc_type", "mean"), inline = TRUE ), numericInput( "ssc_n1", "Sample size (n1):", min = 1, value = state_init("ssc_n1", NA), step = 1 ), numericInput( "ssc_n2", "Sample size (n2):", min = 1, value = state_init("ssc_n2", NA), step = 1 ), conditionalPanel( condition = "input.ssc_type == 'mean'", numericInput( "ssc_delta", "Delta:", value = state_init("ssc_delta", 2), step = 1 ), numericInput( "ssc_sd", "Standard deviation:", min = 0, value = state_init("ssc_sd", 10), step = 1 ) ), conditionalPanel( condition = "input.ssc_type != 'mean'", numericInput( "ssc_p1", "Proportion 1 (p1):", min = 0, max = 1, value = state_init("ssc_p1", .1), step = .05 ), numericInput( "ssc_p2", "Proportion 2 (p2):", min = 0, max = 1, value = state_init("ssc_p2", .15), step = .05 ) ), numericInput( "ssc_conf_lev", "Confidence level:", min = 0, max = 1, value = state_init("ssc_conf_lev", 0.95), step = .05 ), numericInput( "ssc_power", "Power:", min = 0, max = 1, value = state_init("ssc_power", 0.8), step = .05 ), selectInput( inputId = "ssc_alternative", label = "Alternative hypothesis:", choices = ssc_alternative, selected = state_single("ssc_alternative", ssc_alternative, "two.sided") ), checkboxInput("ssc_show_plot", "Show plot" , state_init("ssc_show_plot", FALSE)) ), help_and_report( modal_title = "Sample size (compare)", fun_name = "sample_size_comp", help_file = inclRmd(file.path(getOption("radiant.path.design"), "app/tools/help/sample_size_comp.Rmd")) ) ) }) ssc_plot_width <- function() 650 ssc_plot_height <- function() 650 output$sample_size_comp <- renderUI({ register_print_output("summary_sample_size_comp", ".summary_sample_size_comp") register_plot_output( "plot_sample_size_comp", ".plot_sample_size_comp", width_fun = "ssc_plot_width", height_fun = "ssc_plot_height" ) ssc_output_panels <- tagList( tabPanel("Summary", verbatimTextOutput("summary_sample_size_comp")), tabPanel( "Plot", conditionalPanel( "input.ssc_show_plot == true", download_link("dlp_ssc"), plotOutput("plot_sample_size_comp", height = "100%") ) ) ) stat_tab_panel( menu = "Design > Sample", tool = "Sample size (compare)", data = NULL, tool_ui = "ui_sample_size_comp", output_panels = ssc_output_panels ) }) .sample_size_comp <- reactive({ do.call(sample_size_comp, ssc_inputs()) }) .summary_sample_size_comp <- reactive({ if (is.null(input$ssc_type)) return(invisible()) summary(.sample_size_comp()) }) .plot_sample_size_comp <- reactive({ req(input$ssc_show_plot == TRUE) plot(.sample_size_comp()) }) observeEvent(input$sample_size_comp_report, { ssc <- ssc_inputs() if (input$ssc_type == "mean") { ssc$p1 <- ssc$p2 <- NULL } else { ssc$delta <- ssc$sd <- NULL } inp_out <- list("", "") outputs <- "summary" figs <- FALSE if (isTRUE(input$ssc_show_plot)) { inp_out[[2]] <- list(custom = FALSE) outputs <- c("summary", "plot") figs <- TRUE } update_report( inp_main = clean_args(ssc, ssc_args), fun_name = "sample_size_comp", inp_out = inp_out, outputs = outputs, figs = figs, fig.width = ssc_plot_width(), fig.height = ssc_plot_height() ) }) download_handler( id = "dlp_ssc", fun = download_handler_plot, fn = function() paste0("sample_size_comp_", input$ssc_type), type = "png", caption = "Save sample size comparison plot", plot = .plot_sample_size_comp, width = ssc_plot_width, height = ssc_plot_height )