app_noReporteR.R 85.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
# SESYNC Endangered Species Recovery Decision Explorer Tool ----
# 
# Code by C. Ashton Drew, KDV Decision Analysis LLC
# ashton.drew@kdv-decisions.com
# March 2017 - November 2017
# R version 3.3.2 (2016-10-31)

# Libraries, Data, and Source Code ----
#source("dependencies.R")

 library(shiny) #Version 1.0.3
 library(readr) #Version 1.1.1
 library(magrittr) #Version 1.5
 library(plyr) #Version 1.8.4
 library(dplyr) #Version 0.7.1
 library(tidyr) #Version 0.6.3
 library(forcats) #Version 0.2.0
 library(ggplot2) # Version 2.2.1
 library(scales) #Version 0.4.1
 library(DT) #Version 0.2
# library(ReporteRsjars) #Version 0.0.2 # depreciated. Broke ability to download report from shiny. Needs to be updated to "officer"
# library(ReporteRs) #Version 0.8.8


# load tidy PPP data
# These data files are tidy versions of Gwen Iacona's PPP result data
# The script used to prep the data for use here is: script_TidyPPPData.R
datLONG <- read_csv("Data/TidyPPPOutput_LONG.csv", guess_max = 2740) # added guess_max to avoid parsing errors
datWIDE <- read_csv("Data/TidyPPPOutput_WIDE.csv")

## drop the records where benefit is NA. Should have done this before...

datLONG <- datLONG[-which(is.na(datLONG$Benefit)),]
datWIDE <- datWIDE[-which(is.na(datWIDE$Benefit)),]

# Load preprocessed Included/Excluded by Budget data
# budget simulation lists for Budget=seq(200000, 600000000, by=200000)
# as created by script_BudgetSimulationList.R
national_budgetSim <- readRDS("Data/National_budgetSimList.rds")
regional_budgetSim <- readRDS("Data/Regional_budgetSimList.rds")
taxa_budgetSim <- readRDS("Data/Taxa_budgetSimList.rds")
national_reg_budgetSim <- readRDS("Data/National_regional_budgetSimList.rds")
regional_reg_budgetSim <- readRDS("Data/Regional_regional_budgetSimList.rds")
taxa_reg_budgetSim <- readRDS("Data/Taxa_regional_budgetSimList.rds")

# Load Stephanie Avery Gomm's Uncertainty Analysis results
# Table 1 Summary of Number of Species Results
uncNSpp <- read_csv("Data/Updated_TidyUncertaintyTable1.csv")
uncNSpp$Treatment <- fct_relevel(uncNSpp$Treatment, "BSCo", "BS", "BCo", "SCo", "B", "S", "Co")
uncNSpp$Budget <- fct_relevel(uncNSpp$Budget, "$7,500,000", "$15,000,000", "$30,000,000")
# Table 3 Summary of Always-Never Funded
uncInOut <- read_csv("Data/Updated_TidyUncertaintyTable3.csv")
uncInOut$Budget <- fct_relevel(uncInOut$Budget, "$7,500,000", "$15,000,000", "$30,000,000")
uncInOut$Status <- fct_relevel(uncInOut$Status, "never", "sometimes", "always")
uncProbInc <- read_csv("Data/Updated_TidyUncertaintyTable2.csv")

#load custom functions
source("Functions/function_PossibleByBudget.R") # used external to shiny when building rds files
source("Functions/function_IncExcByBudget.R") # used external to shiny when building rds files
source("Functions/function_IncExcBySpecies.R")
source("Functions/function_SummaryIncExc.R")
source("Functions/function_CreateRegionTaxaBarPlots.R")
source("Functions/function_ExtractRegionTaxaBarPlots.R")
source("Functions/function_CreateRegionTaxaBoxPlots.R")
source("Functions/function_ExtractRegionTaxaBoxPlots.R")
source("Functions/function_CreateRegionTaxaBoxPlots_Rescaled.R")

# Static Plots and Values ----

# Cost to complete all plans & recovery all species
MaxCumCost <- max(datWIDE$CumulativeCost)
MaxAnnReqBudget <- max(datWIDE$CumMeanAnnCost)
TotalCosts <- sum(datWIDE$Cost)
TotalNSpp <- sum(datWIDE$SpeciesInPlan)
TotalNPlans <- nrow(datWIDE)
TotalSumBenefit <- sum(datWIDE$Benefit)
TotalSumSuccess <- sum(datWIDE$Success)
TotalSumWeight <- sum(datWIDE$Weight)

# Histogram of Recovery Plan Costs
CostHist <- ggplot(datWIDE[datWIDE$Cost<quantile(datWIDE$Cost, 0.90),], aes(Cost/1000000))+
  geom_histogram(bins=100, fill="blue")+
  scale_x_continuous(labels = scales::dollar)+
  theme_minimal()+
  theme(axis.text=element_text(size=16))+
  xlab("Cost (millions of dollars)") +
  ylab("Count")

# List of all AD summary barplots
SummaryBarPlotList <- CreateRegionTaxaBarPlots(x=datWIDE)
# List of all AD summary boxplots
SummaryBoxPlotList <- CreateRegionTaxaBoxPlots(x=datWIDE)
rescaled_SummaryBoxPlotList <- CreateRegionTaxaBoxPlots_Rescaled(x=datWIDE)

# USER INTERFACE ----

# Define UI for application
ui <- fluidPage(
  tags$head(
    tags$style(
      HTML('#Welcome {color: white; background-color: #3B4C70;}'),
      HTML('#BA_1113 {color: white; background-color: #3B4C70;}'),
      HTML('#NS_BudgetsTargets {color: white; background-color: #3B4C70;}'),
      HTML('#BS_RedScenario {color: white; background-color: darkred;}'),
      HTML('#BS_BlueScenario {color: white; background-color: darkblue;}'),
      HTML('#qChoices {color: white; background-color: #3B4C70;}')
    )
  ),
  tabsetPanel(
    
    ## Welcome ----
    tabPanel("Welcome",
             h1("Recovery Prioritization Explorer"),
             img(src="manyspeciesbanner1.jpg",width = "1300px", height = "100px"),
             hr(),
             wellPanel(id="Welcome",
             tags$i(h4("How many more species could be recovered with a 10% budget increase?")),
             tags$i(h4("What would be the impact on species or regions of budget reductions?")),
             tags$i(h4("How does the allocation of money among regions and taxa affect overall recovery efforts?"))
             ),
             wellPanel(
               tags$div(
                 HTML('<h5>These and other similar questions prompted the development of this decision-support tool by the <a href="http://www.sesync.org/project/ventures/esa-decision-making">SESYNC Endangered Species Act Decision Support Venture</a>, a collaboration of CBO, USFWS, and academic partners.  The tool has two primary purposes:</h5>')
               ),
               h4("1. Communicate Expected Recovery Outcomes of National Budgets"),
               tags$div(
                 HTML('<h5>The USFWS expressed a need to quickly summarize the expected outcomes of alternative budget proposals.  On the <b>National Summary</b> tab, you can explore expected outcomes given a budget target (percent increase or decrease in the annual national recovery budget) or species target (number of species to be set on path to recovery).  You have the option of printing your results as a one-page summary report to support budget negotiations.</h5>')
               ),
               h4("2. Support Discussion of Recovery Priorities and Budget Allocations"),
               tags$div(
                 HTML('<h5>Once a national budget has been set (<b>1113 Budget</b> tab), there are many ways this money could be allocated among Recovery Plans.  The USFWS expressed a need to better understand the expected long-term recovery outcomes of alternative plan prioritization and budget allocation scenarios.  Using information from the <a href="https://www.fws.gov/endangered/species/recovery-plans.html">Recovery Plans</a> and the <a href="http://ecos.fws.gov/ecp0/ore-input/ad-hoc-recovery-actions-public-report-input">Recovery Online Activity Reporting (ROAR) database</a> the tool allows side-by-side comparison of alternative scenarios (<b>Compare Scenarios</b> tab), investigation of uncertainty in model predictions (<b>Uncertainty Simulations</b> tab), and direct access to the underlying data (<b>Data and Definitions</b> tab).  The <b>Action Quadrant</b> tab supplements the discussion of USFWS budgets by illustrating how differences among plans point to opportunities for research, partnership, and outreach.</h5>')
               )
             ),
             hr(),
             img(src="manylogos1.jpg",width = "1300px", height = "100px")
    ),
    
    ## 1113 Allocation ----

    tabPanel("1113 Allocation",
             fluidRow(
               column(4,
                      h2("Total 1113 Budget Allocation"),
                      h5("Enter the expected 1113 budget and then allocate that budget among the five primary recovery activities."),
                      wellPanel(id="BA_1113",
                                h4("Expected 1113 Budget"),
                        numericInput("BA_Total", label="Annual Dollars:",
                                     value=20000000, width=400, step=1000000),
                        hr(),
                        h4("Allocation Summary"),
                        tableOutput("BA_BudgetTable"),
                        h5(span(textOutput("BA_Summary"), style="color:#FFC300")),
                        hr(),
                        h5("Save a brief powerpoint report of these results."),
                        downloadButton("PPT_report", "*.pptx Presentation")
                      )
               ),
               column(8,
                      fluidRow(
                        column(6,
                               wellPanel(
                                 h4("Congressional and Service Required Work"),
                                 numericInput("BA_DWork_Budget",
                                              label="Enter the amount allocated to required work:",
                                              value=2500000, width=400, step=10000)
                               ),
                               wellPanel(
                                 h4("Five Year Reviews"),
                                 numericInput("BA_5Yr_Number",
                                              label="Enter the target number of five-year reviews:",
                                              value=15, width=400, step=1),
                                 numericInput("BA_5Yr_Cost",
                                              label="Enter the estimated average cost per review:",
                                              value=20000, width=400, step=500),
                                 h5(textOutput("BA_5Yr_Budget"))
                               ),
                               wellPanel(
                                 h4("Recovery Planning"),
                                 numericInput("BA_Plan_Number",
                                              label="Enter the target number of plans:",
                                              value=20, width=400, step=1),
                                 numericInput("BA_Plan_Cost",
                                              label="Enter the estimated average cost per plan:",
                                              value=20000, width=400, step=500),
                                 h5(textOutput("BA_Plan_Budget"))
                               )
                        ),
                        column(6,
                               wellPanel(
                                 h4("Down-listing and Delisting"),
                                 numericInput("BA_Downlist_Number",
                                              label="Enter the target number of down-listings:",
                                              value=5, width=400, step=1),
                                 numericInput("BA_Downlist_Cost",
                                              label="Enter the estimated average cost per down-listing:",
                                              value=10000, width=400, step=500),
                                 numericInput("BA_Delist_Number",
                                              label="Enter the target number of delistings:",
                                              value=5, width=400, step=1),
                                 numericInput("BA_Delist_Cost",
                                              label="Enter the estimated average cost per delisting:",
                                              value=10000, width=400, step=500),
                                 h5(textOutput("BA_Downlist_Budget")),
                                 h5(textOutput("BA_Delist_Budget"))
                               ),
                               wellPanel(
                                 h4("Implementation"),
                                 h5(span(textOutput("BA_AvailableForRecovery"), style="color:red")),
                                 numericInput("BA_Action_Percent",
                                              label="Enter the percentage of implementation budget to allocate towards Recovery Actions (versus other implementation activities):",
                                              value=50, width=400, step=1),
                                 h5(textOutput("BA_Action_Budget")),
                                 h5(textOutput("BA_Other_Budget"))
                               )
                        )
                      )
               )
             )
    ),
    
    ## National Summary ----

    tabPanel("National Summary",
             fluidRow(
               column(4,
                      h2("National Summary Report"),
                      tags$ul(
                        tags$li("View expected recovery outcome given budget."),
                        tags$li("Explore impacts of percent change in budget."),
                        tags$li("Identify budget required to achieve target number of species recovered.")
                      ),
                      wellPanel(id="NS_BudgetsTargets",
                        h4("Current Estimated Annual Budget for Recovery Actions"),
                        uiOutput("uiNS_CurrAnnBudget"),
                        span(h5("Default is the value set on the 1113 tab."), style="color:#FFC300"),
                        hr(),
                        h4("Save a brief document report of these results."),
                        downloadButton("DOC_report", "*.docx Document")
                      ),
                      wellPanel(id="NS_BudgetsTargets",
                        h4("Select a tab to set a budget or species target:"),
                        tabsetPanel(id="NS_TargetTabs",
                          tabPanel("Set Budget Target", value="NS_SetBudget",
                                   p(" "),
                                   numericInput("NS_BudgetPercent",
                                                label="What percent change in budget is proposed?",
                                                value=10, width=400, step=5),
                                   h4(span(textOutput("NS_ChangeSummary"), style="color:#FFC300")),
                                   h4("To explore the data behind this conclusion, view the Data & Definitions tab. To compare alternative budgets and prioritization strategies, view the Compare Scenarios tab.")
                                   
                          ),
                          tabPanel("Set Species Target", value="NS_SetSpecies",
                                   p(" "),
                                   numericInput("NS_SpeciesNumber",
                                                label="What target number of species is proposed?",
                                                value=800, width=400),
                                   h4(span(textOutput("NS_TargetSummary"), style="color:#FFC300")),
                                   h4("To explore the data behind this conclusion, view the Data & Definitions tab.  To compare alternative budgets and prioritization strategies, view the Compare Scenarios tab.")
                          )
                        )
                      )
               ),
               column(8,
                      # Budget Target Results
                      fluidRow(
                        column(6,
                               textOutput("test"),
                               h4("Species included (green) and excluded (grey) as budget and number of completed plans increases.", align="center"),
                               plotOutput("NS_IncExc_Budget") ),
                        column(6,
                               p(" "),
                               h4("Cost distribution to complete all actions in a plan (some plans have many species).", align="center"),
                               plotOutput("NS_Cost_Histogram1"),
                               helpText(paste0("Costs range from ", dollar(round(min(datWIDE$Cost),0)), " to ", dollar(round(max(datWIDE$Cost),0)), " in this set of ", nrow(datWIDE), " plans. The figure above shows plans in the lower 90th percentile of costs (plans less than or equal to ", dollar(quantile(datWIDE$Cost, 0.90)),").")))
                      ),
                      hr(),
                      h4("The table below lists the next most cost-efficient plans excluded under the proposed target."),

                      conditionalPanel(condition="input.NS_TargetTabs == 'NS_SetBudget'",
                                       dataTableOutput("NS_ExcludedPlansUnderBudgetTarget")
                      ),
                      conditionalPanel(condition="input.NS_TargetTabs == 'NS_SetSpecies'",
                                       dataTableOutput("NS_ExcludedPlansUnderSpeciesTarget")
                      )  
                      
               )
             )
    ),
    
    ## Data and Definitions ----

    tabPanel("Data & Definitions",
             p(" "),
             h2("Background Data and Definitions"),
             tags$ul(
               tags$li("View overall distribution of opportunity, needs, and costs across regions and taxa."),
               tags$li("View distribution of opportunity, needs, and costs among plans."),
               tags$li("Search for definitions in the project dictionary.")
             ),
             tabsetPanel(
               tabPanel("Summary of Recovery Needs",
                        radioButtons("DA_regiontaxa_barplots", 
                                     label="Show needs summary by region or by taxa?",
                                     choices=c("Region"="Region", "Taxa"="Taxa"),
                                     selected="Region", inline=TRUE),
                        fluidRow(column(4,
                                        plotOutput("DA_NPlans")),
                                 column(4,
                                        plotOutput("DA_NSpp")),
                                 column(4,
                                        plotOutput("DA_TotAnnCosts"))
                        )
               ),
               tabPanel("Summary of Plan Characteristics",
                        fluidRow(
                          column(4,
                                 radioButtons("DA_regiontaxa_boxplots", 
                                              label="Show plan chacteristics by region or by taxa?",
                                              choices=c("Region"="Region", "Taxa"="Taxa"),
                                              selected="Region", inline=TRUE),
                                 p(" "),
                                 h5("On some scales (Cost, Benefit, and Success) there are multiple extreme outliers.  To better view the differences among regions (or taxa), you can adjust the x-axis maximum value."),
                                 radioButtons("DA_rescale_cost", width=500,
                                              label="Would you like to rescale the Cost plot?",
                                              choices=c("Yes, exclude values above the 75th percentile cost."="Yes", "No, show all the data."="No"),
                                              selected="No", inline=FALSE),
                                 radioButtons("DA_rescale_benefit", width=500,
                                              label="Would you like to rescale the Benefit plot?",
                                              choices=c("Yes, exclude values above the 95th percentile benefit."="Yes", "No, show all the data."="No"),
                                              selected="No", inline=FALSE),
                                 radioButtons("DA_rescale_success", width=500,
                                              label="Would you like to rescale the Success plot?",
                                              choices=c("Yes, exclude values above 95th percentile success."="Yes", "No, show all the data."="No"),
                                              selected="No", inline=FALSE)
                          ),
                          column(8,
                                 fluidRow(
                                   column(6,
                                          plotOutput("DA_Cost"),
                                          helpText(paste0("The median cost to complete all actions in a Recovery Plan is ", dollar(round(median(datWIDE$Cost),0)), " (dark red line).")),
                                          plotOutput("DA_Benefit"),
                                          helpText(paste0("The median benefit of completing all actions in a Recovery Plan is ", median(datWIDE$Benefit), "(dark red line)."))),
                                   column(6,
                                          plotOutput("DA_Success"),
                                          helpText(paste0("The median feasibility of success of all actions in a Recovery Plan is ", median(datWIDE$Success), "(light blue line).")),
                                          plotOutput("DA_Weight"),
                                          helpText(paste0("The median taxonomic weight of all actions in a Recovery Plan is ", median(datWIDE$Weight), "(light blue line).")))
                                 )
                          )
                        )
               ),
               tabPanel("Recovery Explorer Input Data",
                        
                      dataTableOutput("DA_RawData")
               ),
               tabPanel("Definitions",
                        
                        wellPanel(
                          h4(strong("Definitions of input variables:")),
                          tags$div(
                            HTML('<h5><li><em>Taxa</em>: The taxa group addressed by the Recovery Plan.</li></h5>'),
                            HTML('<h5><li><em>Lead Region</em>: The USFWS region with primary responsibility for the Recovery Plan.</li></h5>'),
                            HTML('<h5><li><em>Cost</em>: Discounted total estimated cost to complete all actions in the Recovery Plan.</li></h5>'),
                            HTML('<h5><li><em>Benefit</em>: Degree of threat, as indicated by the recovery priority number (RPN) calculations, summed across all species in the plan.</li></h5>'),
                            HTML('<h5><li><em>Success</em>: Feasibility of success, as indicated by the recoverability score in the recovery priority number (RPN) calculations, summed across all species in the plan.</li></h5>'),
                            HTML('<h5><li><em>Weight</em>: Weighting based on the taxonomic rarity component of the recovery priority number (RPN) calculations, summed across all species in the plan.</li></h5>')
                          ),
                          hr(),
                          h4(strong("Definitions of output cost effectiveness scores:")),
                          tags$div(
                            HTML('<h5><li><em>CE</em>: Cost effectiveness given all information on cost, benefit (degree of threat), weightings (taxonomic rarity), and success (feasibility).  Based on completion of all priority level actions (1=Prevent Extinction; 2=Reverse Declines; 3=Recovery to Delisting).</li><h5>'),
                            HTML('<h5><li><em>CE-W</em>: Cost effectiveness given all information EXCLUDING the taxonomic rarity weightings.  Based on completion of all priority level actions.</li><h5>'),
                            HTML('<h5><li><em>CE-S</em>: Cost effectiveness to given all information EXCLUDING the feasibility of success. Based on completion of all priority level actions.</li><h5>'),
                            HTML('<h5><li><em>CE-23</em>: Cost effectiveness given all information, but EXCLUDING Priority 2 and 3 actions and their costs.</li><h5>'),
                            HTML('<h5><li><em>CE-3</em>: Cost effectiveness given all information, but EXCLUDING Priority 3 actions and their costs.</li><h5>'),
                            helpText("N.B.: The cost effectiveness scores are in units of standard deviations.  Positive numbers are the number of standard deviations above the mean; negative numbers are the number of standard deviations below the mean.")
                          )
                        )
               )
             )
    ),
    
    ## Compare Scenarios ----

    tabPanel("Compare Scenarios",
             
             fluidRow(column(4,
                             h2("Compare Scenarios"),
                             tags$ul(
                               tags$li("Compare outcomes of alternative decisions."),
                               tags$li("Explore alternative budgets."),
                               tags$li("Select factors to include or exclude from prioritization."),
                               tags$li("Select whether to apply prioritization at national, regional, or taxa level.")
                             )
             ),
                      column(4,
                             wellPanel(id="BS_RedScenario",
                               h3("Scenario A"),
                               uiOutput("uiBS_A_Budget"),
                               span(h5("Default is the value set on the 1113 tab."), style="color:#FFC300"),
                               # numericInput("BS_A_Budget",
                               #              label="Choose an annual budget",
                               #              value=2000000, step=200000),
                               selectInput("BS_A_CEmethod",
                                           label="Choose which cost effectiveness score to apply",
                                           choices=c("Use all information and complete all actions (CE)"="CE",
                                                     "Ignore feasibility of success (CE-S)"="CEs",
                                                     "Ignore taxanomic weight (CE-W)"="CEw",
                                                     "Complete only Priority 1 actions (CE-23)"="CE1",
                                                     "Complete only Priority 1&2 actions (CE-3)"="CE12")),
                               selectInput("BS_A_SplitLvl",
                                           label="Choose at which level to rank cost effectiveness",
                                           choices=c("National list"="National",
                                                     "Regional lists"="Regional",
                                                     "Taxonomic lists"="Taxa"))
                             )
                      ),
                      column(4,
                             wellPanel(id="BS_BlueScenario",
                               h3("Scenario B"),
                               uiOutput("uiBS_B_Budget"),
                               span(h5("Default is the value set on the 1113 tab."), style="color:#FFC300"),
                               # numericInput("BS_B_Budget",
                               #              label="Choose an annual budget",
                               #              value=200000000, step=1000000),
                               selectInput("BS_B_CEmethod",
                                           label="Choose which cost effectiveness score to apply",
                                           choices=c("Use all information and complete all actions (CE)"="CE",
                                                     "Ignore feasibility of success (CE-S)"="CEs",
                                                     "Ignore taxanomic weight (CE-W)"="CEw",
                                                     "Complete only Priority 1 actions (CE-23)"="CE1",
                                                     "Complete only Priority 1&2 actions (CE-3)"="CE12")),
                               selectInput("BS_B_SplitLvl",
                                           label="Choose at which level to rank cost effectiveness",
                                           choices=c("National list"="National",
                                                     "Regional lists"="Regional",
                                                     "Taxonomic lists"="Taxa"))
                             )
                      )
             ),
             hr(),
             fluidRow(column(4,
                             h4("Number of Plans Included", align="center"),
                             plotOutput("BS_NPlans")),
                      column(4,
                             h4("Number of Species Included", align="center"),
                             plotOutput("BS_NSpecies")),
                      column(4,
                             h4("Total Benefit of Included Plans", align="center"),
                             plotOutput("BS_Benefit"))
             ),
             fluidRow(column(4,
                             h4("Total Feasibility of Success of Included Plans", align="center"),
                             plotOutput("BS_Success")),
                      column(4,
                             h4("Total Taxonomic Weight of Included Plans", align="center"),
                             plotOutput("BS_Weight")),
                      column(4,
                             h4("Total Cost of Included Plans", align="center"),
                             plotOutput("BS_ActualSpend"))
             ),
             fluidRow(column(4,
                             h4("Number of Plans Included by Region", align="center"),
                             plotOutput("BS_RegNPlans")),
                      column(4,
                             h4("Number of Species Included by Region", align="center"),
                             plotOutput("BS_RegNSpecies")),
                      column(4,
                             h4("Total Cost by Region", align="center"),
                             plotOutput("BS_RegCost"))
             ),
             tableOutput("testtable")
             
    ),

    ## Action Quadrant ----

    tabPanel("Action Quadrant",
             h2("Opportunities for Outreach, Research, and Conservation Partnerships"),
             fluidRow(
               column(4,
                      h5("Explore how the distribution of plan costs and expected outcomes present different opportunities."),
                      helpText("The vertical and horizontal thresholds define quadrats (figure below) with different information value. They could define boundaries for action versus inaction, but could also highlight opportunities to pursue distinct actions. For example, low cost projects might offer an opportunity to involve smaller partners. High benefit projects might offer opportunties for synergy with other programs. High success projects might be well-suited to outreach and engagement activities, whereas high cost and low success projects are good candidates for research programmes to increase effectiveness.  Set thresholds and display options below to view graphical and tabular summaries of the Recovery Plans by quadrant"),
                      img(src="ThreshholdKey.png",width = "200px", height = "200px"),
                      wellPanel(id="qChoices",
                        
                        h4("Set thresholds"),
                        numericInput("qCost", paste0("Enter a Cost per Species threshold between ", dollar(round(min(datWIDE$Cost/datWIDE$SpeciesInPlan),0)), " and ", dollar(200000000), ":"), value=1000000),
                        sliderInput("qBslider", "Set the Benefit threshold:", min=min(datWIDE$Benefit), max(datWIDE$Benefit), value=median(datWIDE$Benefit)),
                        sliderInput("qSslider", "Set the Success threshold:", min=min(datWIDE$Success), max(datWIDE$Success), value=median(datWIDE$Success)),
                        sliderInput("qWslider", "Set a Taxonomic Weight threshold:", min=min(datWIDE$Weight), max(datWIDE$Weight), value=median(datWIDE$Weight)),
                        
                        h4("Optional display features"),
                        
                        
                        radioButtons("qRegionTaxa", "Which set of plans would you like to highlight?", 
                                     choices=c("None" = "N", 
                                               "A Specific Taxa"="T", 
                                               "A Specific Region"="R", 
                                               "Plans Included Under Scenario A"="A", 
                                               "Plans Included Under Scenario B"="B"), selected = "N", inline=FALSE),
                        
                        conditionalPanel(condition = "input.qRegionTaxa == 'T'", 
                                         selectInput("qTaxa", "Select one taxa group to display as red triangles:", 
                                                     choices = c("Amphibians"="Amphibians", "Arachnids"="Arachnids", "Birds"="Birds", "Clams"="Clams", "Conifers and Cycads"="Conifers and Cycads", "Crustaceans"="Crustaceans", "Ferns and Allies"="Ferns and Allies", "Fishes"="Fishes", "Flowering Plants"="Flowering Plants", "Insects"="Insects", "Lichens"="Lichens", "Mammals"="Mammals", "Plants"="Plants", "Reptiles"="Reptiles", "Snails"="Snails"), selected = "Insects")
                        ),
                        conditionalPanel(condition = "input.qRegionTaxa == 'R'", 
                                         selectInput("qRegion", "Select one region to display as red triangles:", 
                                                     choices = c("Alaska"="Alaska","Midwest"="Midwest", "Mountain Prairie"="Mountain Prairie", "Northeast"="Northeast", "Pacific"="Pacific", "Pacific Southwest"="Pacific Southwest", "Southeast"="Southeast", "Southwest"="Southwest" ), selected = "Pacific Southwest")
                        )
                      )
               ),
               column(8,
                      tabsetPanel(
                        tabPanel("View Graphs",
                                 plotOutput("quadBENEFIT"),
                                 hr(),
                                 plotOutput("quadSUCCESS"),
                                 hr(),
                                 plotOutput("quadWEIGHT")
                        ),
                        tabPanel("View Table",
                                 dataTableOutput("quadTable")
                        )
                      )
               )
             )              
               
    ),
    
    ## Uncertainty Simulations ----

    tabPanel("Uncertainty Simulations",
             p(" "),
             h2("Sensitivity Analysis of Cost, Benefit, and Success Data"),

            hr(),
             
             fluidRow(
               column(3,
                      h5("Explore and compare how uncertainty about the input data influence the decision tool results. View outcomes as:"),
                      radioButtons("US_Uncertainty_View", 
                                   label="",
                                   choices=c("Number of Species Recovered"="NSpp",
                                             "Portfolio Performance"="Perform",
                                             "Percent Plans Always Included or Excluded"="InOut"),
                                   selected="NSpp", inline=FALSE),
                      conditionalPanel(
                        condition = "input.US_Uncertainty_View=='InOut'",
                        selectInput("US_Level", "Select a level of uncertainty to simulate:",
                                    choices=c("Low"="L", "Moderate"="M", "High"="H"),
                                    selected="H"),
                        selectInput("US_Sim", "Select which variables will be treated as uncertain in the simulation:",
                                    choices=c("Benefit, Success, and Cost"= "BSCo", "Benefit and Success only"="BS", "Benefit and Cost only"="BCo", "Success and Cost only"="SCo", "Benefit only"="B", "Success only"="S", "Cost only"="Co"), selected="BSCo")
                        
                      ),
                      hr(),
                      tabsetPanel(
                        tabPanel("Guide",
                                 conditionalPanel(
                                   condition="input.US_Uncertainty_View=='NSpp'",
                                   tags$div(HTML('<h5><i><font color=\"#FF0000\">If you used these data to predict an outcome from a budget change, how confident could you be in your predctions?</font></i><p><p>Compare graphs across a row to observe the affect of low, moderate, and high uncertainty applied to a set of variables. Compare graphs down a column to observe the affect of applying uncertainty to different combinations of variables. Consider the questions:<p><ul><li>Does the level of uncertainty influence the expectation regarding the how many more (or less) species can be conserved under a budget increase (or decrease)?<p><li>Does the uncertainty in any one variable have a greater influence on the expectations regarding the number of species conserved than other variables?</ul></h5>'))
                                 ),
                                 conditionalPanel(
                                   condition = "input.US_Uncertainty_View=='Perform'",
                                   tags$div(HTML('<h5><i><font color=\"#FF0000\">If you used these data to predict an outcome from a budget change, how confident could you be in your predctions?</font></i><p><p>Compare graphs across a row to observe the affect of low, moderate, and high uncertainty applied to a set of variables. Compare graphs down a column to observe the affect of applying uncertainty to different combinations of variables. Consider the questions:<p><ul><li>Does the level of uncertainty influence the expectation regarding how much value is gained (or lost) from my conservation portfolio under a budget increase (or decrease)?<p><li>Does the uncertainty in any one variable have a much greater influence on my expectations regarding portfolio performance than other variables?</ul></h5>'))
                                 ),
                                 conditionalPanel(
                                   condition = "input.US_Uncertainty_View=='InOut'",
                                   tags$div(HTML('<h5><i><font color=\"#FF0000\">If you must make decisions under uncertainty, can you distinguish safe bets from risky ventures?</font></i><p><p>Consider the questions:<p><ul><li>Which species, despite uncertainty, are always included in (or excluded from) the portfolio?</ul></h5>'))
                                 )
                        ), 
                        tabPanel("Definitions",
                                 tags$div(HTML('<h5>Cost (Co) uncertainty draws values from a normal distribution where the mean is the estimated cost and the standard deviation at each level is:<p><ul><li>HIGH (sd=mean x 0.20)<li>MEDIUM (sd=mean x 0.1)<li>LOW (sd=mean x 0.05)</ul></h5>')),
                                 tags$div(HTML('<h5>Benefit (B) and Success (S) uncertainty draw values from a beta distribution where the variance at each level is:<p><ul><li>HIGH (variance = 0.01)<li>MEDIUM (variance = 0.005)<li>LOW (variance = 0.001)</ul></h5>')),
                                 tags$div(HTML('<h5>Six sets of simulations apply uncertainty to different components of the cost efficiency calculation.  Abbreviations above the graphs indicate which simulation set the data represent:<p><ul><li>Benefit, Success, and Cost (BSCo)<li>Benefit and Success only (BS)<li>Benefit and Cost only (BCo)<li>Success and Cost only (SCo)<li>Benefit only (B)<li> Success only (S)<li>Cost only (Co)</ul></h5>'))
                        )
                      )
                      
               ),
               
               conditionalPanel(
                 condition = "input.US_Uncertainty_View != 'InOut'",
                 
                 column(3,
                        h4("Low Uncertainty", align="center"),
                        conditionalPanel(
                          condition = "input.US_Uncertainty_View == 'NSpp'",
                          plotOutput("US_UncertainNSpp_Low")),
                        conditionalPanel(
                          condition = "input.US_Uncertainty_View == 'Perform'",
                          plotOutput("US_UncertainPerform_Low"))
                 ),
                 column(3,
                        h4("Moderate Uncertainty", align="center"),
                        conditionalPanel(
                          condition = "input.US_Uncertainty_View == 'NSpp'",
                          plotOutput("US_UncertainNSpp_Mod")),
                        conditionalPanel(
                          condition = "input.US_Uncertainty_View == 'Perform'",
                          plotOutput("US_UncertainPerform_Mod"))
                 ),
                 column(3,
                        h4("High Uncertainty", align="center"),
                        conditionalPanel(
                          condition = "input.US_Uncertainty_View == 'NSpp'",
                          plotOutput("US_UncertainNSpp_High")),
                        conditionalPanel(
                          condition = "input.US_Uncertainty_View == 'Perform'",
                          plotOutput("US_UncertainPerform_High"))
                 )
                 
               ),
               
               conditionalPanel(
                 condition = "input.US_Uncertainty_View == 'InOut'",
                 
                 column(9,
                        fluidRow(
                          h3("Probability of Plan Inclusion in Conservation Portfolio", align="center"),
                          plotOutput("US_UncertainInOut")
                        ),
                        fluidRow(
                          hr(),
                          h5("View which plans were always, sometimes, and never included in the portfolio under each of the buget levels for a given uncertainty simulation set."),
                          dataTableOutput("US_InOutProbability")
                        )
                        
                 )
               )
             )
    ),
    
    ## More Info ----

    tabPanel("Notes and Credits",
             h2("Information about this Recovery Explorer Tool"),
             tags$div(
               HTML('<h5>This pilot Recovery Prioritisation decision support tool was built as part of a <a href="http://www.sesync.org/project/ventures/esa-decision-making">SESYNC project</a> examining regional and federal support products for US endangered species, led by <a href="http://gerberlab.faculty.asu.edu/team/leah-gerber/">Leah Gerber</a> (Arizona State University ) and <a href="https://www.usgs.gov/staff-profiles/michael-runge?qt-staff_profile_science_products=0#qt-staff_profile_science_products">Mike Runge</a> (USGS). The Recovery Prioritisation Tool development was coordinated by Richard Maloney (New Zealand Department of Conservation ), the application was built by <a href="http://www.kdv-decisions.com/">Ashton Drew</a> (KDV Decision Analysis), the prioritisation code was written by <a href="http://possinghamlab.org/people-new/all-lab-members/564-gwen-iacona.html">Gwen Iacona</a> (CEED, University of Queensland), the uncertainty analysis was developed by <a href="http://stephanieaverygomm.weebly.com/">Stephanie Avery-Gomm</a> (CEED, University of Queensland ).  We thank the participants of the SESYNC working group for their input and support. Funding for this work was provided by SESYNC, ASU, USGS,  NZ DOC, UQ, and KDV Decision Analysis.</h5>')
             )  
    )
  )
)


# SERVER CODE ----

server <- function(input, output) {
  
  ## 1113 Allocation ---- 

  # Calculate reactive budgets
  
  # Budget fr 5 year reviews
  BA_5Yr <- reactive({
    input$BA_5Yr_Number*input$BA_5Yr_Cost
  })
  # Budget for downlisting
  BA_Downlist <- reactive({
    input$BA_Downlist_Number*input$BA_Downlist_Cost
  })
  # Budget for delisting
  BA_Delist <- reactive({
    input$BA_Delist_Number*input$BA_Delist_Cost
  })
  # Budget for planning
  BA_Plan <- reactive({
    input$BA_Plan_Number*input$BA_Plan_Cost
  })
  # Budget for implementation is what remain after above expenses
  BA_RecoveryImplementation <- reactive({
    spent <- input$BA_DWork_Budget + BA_5Yr() + BA_Downlist() + BA_Delist() + BA_Plan()
    input$BA_Total - spent
  })
  # Budget for Recovery Action portion on implementation
  # This value is used on this tab but also used as default start value for National Summary
  # tab's current budget
  BA_Action <- reactive({
    sum(input$BA_Total-(input$BA_DWork_Budget + BA_5Yr() + BA_Downlist() + BA_Delist() +
                          BA_Plan())) * (input$BA_Action_Percent/100)
  })
  # Budget for all implementation NOT Recovery Actions
  BA_Other <- reactive({
    sum(input$BA_Total-(input$BA_DWork_Budget + BA_5Yr() + BA_Downlist() + BA_Delist() +
                          BA_Plan() + BA_Action()))
  })
  
  # Generate summary table of budget results to show here on tab and to insert into report
  BA_CreateTable <- reactive({
    out <- data.frame(Category=c("Required Work", "Five-Year Reviews", "Down-listing & Delisting", "Recovery Planning", "Implementation"),
                      Budget=c(input$BA_DWork_Budget, BA_5Yr(), BA_Downlist()+BA_Delist(), BA_Plan(),
                               BA_Action()+BA_Other()))
    out$Percent <- out$Budget*100/sum(out$Budget)
    out$Budget <- dollar(out$Budget)
    out
  })
  output$BA_BudgetTable <- renderTable({
    BA_CreateTable()
  }, width=200)
  
  # Generate summary text for tab
  output$BA_Summary <- renderText({
    paste0("The total amount allocated to Recovery Actions, ", dollar(BA_Action()), ", represents ",
           round(BA_Action()*100/input$BA_Total,0), "% of the 1113 budget.")
  })
  output$BA_5Yr_Budget <- renderText({
    paste0("Five-year review total budget: ", dollar(BA_5Yr()))
  })

  # Generate result label text for each budget component wellPanel
  # Downlist result text
  output$BA_Downlist_Budget <- renderText({
    paste0("Down-listing total budget: ", dollar(BA_Downlist()))
  })
  # Delist result text
  output$BA_Delist_Budget <- renderText({
    paste0("Delisting total budget: ", dollar(BA_Delist()))
  })
  # Planning result text
  output$BA_Plan_Budget <- renderText({
    paste0("Recovery planning total budget: ", dollar(BA_Plan()))
  })
  # Total implementation result text
  output$BA_AvailableForRecovery <- renderText({
    paste0("The total amount available for recovery implementation: ", dollar(BA_RecoveryImplementation()))
  })
  # Recovery Actions in implementation text summary
  output$BA_Action_Budget <- renderText({
    paste0("Recovery actions total budget: ", dollar(BA_Action()))
  })
  # All other costs of implementation text summary
  output$BA_Other_Budget <- renderText({
    paste0("Other implementation total budget: ", dollar(BA_Other()))
  })
  
  # National Summary - Reactive Data Elements ---- 

  #Create the Current Budget input with the result from 1113 tab as default value
  output$uiNS_CurrAnnBudget <- renderUI({
    inputBudget <- BA_Action()
    numericInput("NS_CurrAnnBudget",
                 label="",
                 value=inputBudget, width=500, step=200000)
  })

  
  # Given the requested percent budget change, calculate the new required budget
  NS_ReqAnnBudget <- reactive({
    # ToDo: Add an error message for if new budget is outside range of possible budgets given data
    round(input$NS_CurrAnnBudget+(input$NS_CurrAnnBudget*(input$NS_BudgetPercent/100)),0) 
    })
  
  
  #Given CURRENT annual budget gather from the SimList the summary data for CE method
  #This extracts the single line from table for budget <= user input budget value
  NS_TableByCurrAnnBudget <- reactive({
    tmp <- national_budgetSim[["CE"]]
    tmp2 <- tmp[tmp$Budget<=input$NS_CurrAnnBudget,]
    tmp2[nrow(tmp2),] })
  
  #Given new REQUESTED annual budget gather from the SimList the summary data for CE method
  NS_TableByReqAnnBudget <- reactive({
    tmp <- national_budgetSim[["CE"]]
    tmp2 <- tmp[tmp$Budget<=NS_ReqAnnBudget(),]
    tmp2[nrow(tmp2),]  })
  
  
  # Given target number of species, define set of species & necessary costs
  # This is a one step process because "possible/impossible" not relevant when target 
  # by species rather than budget
  NS_TableByReqSpecies <- reactive({
    IncExcBySpecies(datLONG, ReqSpecies = input$NS_SpeciesNumber, SplitLvl="National") })
  
  NS_IncExc_Plot <- reactive({
    validate(
      need(input$NS_CurrAnnBudget >= 0, "Please wait.  Data are processing!")
    )
    dat <- national_budgetSim[["CE"]]
    dat <- dat[dat$Budget<=150000000,]
    dat$Budget <- dat$Budget/1000000
    
    labCurr <- input$NS_CurrAnnBudget/1000000

    out <- ggplot()+
      geom_line(data=dat, aes(Budget, NSppIncluded), col="#1E8449", size=1.5, linetype="solid") +
      geom_line(data=dat, aes(Budget, TotalNSpp-NSppIncluded), col="grey", size=1.5, linetype="solid")+
      geom_vline(xintercept=labCurr, size=1.5, linetype="dotted")+
      geom_text(x=labCurr, y=1200, label="Current \nBudget", hjust=-0.1)+
      scale_x_continuous(labels = scales::dollar)+
      xlim(0,150)+
      theme_minimal()+
      theme(axis.text=element_text(size=16))+
      theme(plot.title = element_text(hjust = 0.5))+
      xlab("Annual Budget (millions) for Recovery Actions")+
      ylab("Number of Species on Path to Recovery")
    if (input$NS_TargetTabs=="NS_SetBudget"){
      out <- out + geom_vline(xintercept=NS_ReqAnnBudget()/1000000, size=1.1, col="blue") +
        geom_text(x=NS_ReqAnnBudget()/1000000, y=1000, label="Proposed \nBudget", hjust=-0.1, col="blue")
          } else {
      out <- out + geom_vline(xintercept=NS_BudgetForReqSpecies()/1000000, size=1.1, col="blue")+
        geom_text(x=NS_BudgetForReqSpecies()/1000000, y=1000, label="Budget to Meet \nSpecies Target", hjust=-0.1, col="blue")
          }
    out
  })
  
  # Given new REQUESTED budget, create a table with the next best plans excluded
  NS_TableExcludedByBudget <- reactive({
    validate(
      need(input$NS_CurrAnnBudget >= 0, "Please wait.  Data are processing!")
    )
    tmp_budget <- NS_ReqAnnBudget()
    datPossible <- PossibleByBudget(datLONG, AnnBudget=tmp_budget)
    datIncExc <- IncExcByBudget(datPossible, AnnBudget=tmp_budget, SplitLvl="National")
    subset <- datIncExc %>%
      dplyr::filter(CEmethod=="CE" & PlanPossible=="Possible" & Status=="Excluded") %>%
      dplyr::select(TID, RegionName, SpeciesInPlan, Cost, Benefit, Success, Weight, ReqBudget)
  })
  
  # Given a species target, calculate the required budget
  NS_BudgetForReqSpecies <- reactive({
    SummaryIncExc(NS_TableByReqSpecies(), CEmethod="CE", summary="annualspend") })
  
  # Given a species target, create a table with the next best plans excluded
  NS_TableExcludedBySpecies <- reactive({
    tmp <- IncExcBySpecies(datLONG, ReqSpecies = input$NS_SpeciesNumber, SplitLvl="National")
    tmp <- tmp[tmp$CEmethod=="CE" & tmp$Status=="Excluded",]
    tmp <- tmp %>%
      dplyr::filter(CEmethod=="CE" & Status=="Excluded") %>%
      dplyr::select(TID, RegionName, SpeciesInPlan, Cost, Benefit, Success, Weight, ReqBudget)
  })
  
  ## National Summary - Budget Subtab ----

  output$NS_Cost_Histogram1 <- renderPlot({CostHist})
  
  output$NS_CurrBudgetText <- renderText({
    paste0("At the current budget level for recovery actions (", dollar(input$NS_CurrAnnBudget), "; black dashed line), you could expect to set up to ", NS_TableByCurrAnnBudget()[4], " species on the path to recovery by implementing ", NS_TableByCurrAnnBudget()[3], " Recovery Plans. This represents ", round(NS_TableByCurrAnnBudget()[4]*100/TotalNSpp,1), "% of total species and ", round(input$NS_CurrAnnBudget*100/MaxAnnReqBudget,1), "% of the estimated annual budget required to achieve full recovery for all species (", TotalNSpp, ") in all Recovery Plans (", TotalNPlans, ") in the database.")
  })
  
  output$NS_ChangeSummary <- renderText({
    
    # Budget change sentence
    PartA <- ifelse(input$NS_BudgetPercent>=0, 
                    paste0("A ", input$NS_BudgetPercent, "% budget increase corresponds to a proposed budget of ", dollar(NS_ReqAnnBudget()), " (blue solid line). "), 
                    paste0("A ", input$NS_BudgetPercent, "% budget decrease corresponds to a proposed budget of ", dollar(NS_ReqAnnBudget()), " (blue solid line). "))
    
    # Species change given budget sentence
    SppChange <- NS_TableByReqAnnBudget()[[4]]-NS_TableByCurrAnnBudget()[[4]]
    
    PartB <- ifelse(SppChange>=0,
                    paste0("At this budget level, you would expect to set ", abs(SppChange), " more species on the path to recovery."),
                    paste0("At this budget level, you would expect to set ", abs(SppChange), " fewer species on the path to recovery."))
    
    # Join sentences.
    paste0(PartA, PartB)
  })
  
  output$NS_IncExc_Budget <- renderPlot({
    NS_IncExc_Plot()
  })
  
  output$NS_ExcludedPlansUnderBudgetTarget <- renderDataTable({
    out <- NS_TableExcludedByBudget()
    ifelse(nrow(out)<10, subset <- out[1:nrow(out),], subset <- out[1:10,])
    subset <- dplyr::arrange(subset, ReqBudget)
    subset$Cost <- dollar(subset$Cost)
    subset$ReqBudget <- dollar(subset$ReqBudget)
    subset
    datatable(subset, rownames=FALSE, colnames=c("Plan ID", "Lead Region", 
                                              "Number Species in Plan", "Total Cost", "Benefit",
                                              "Success", "Weight", "Included when Annual Budget Reaches"))
  })
    
  ## National Summary - Species Subtab ----

  output$NS_TargetSummary <- renderText({
    SppChange <- abs(NS_TableByCurrAnnBudget()[[4]] - input$NS_SpeciesNumber)
    # Add an error message for if new target is outside range of possible targets given data
    PartA <- paste0("To set a total of ", input$NS_SpeciesNumber, " of the most Cost Efficient species onto the path towards recovery, you would need an estimated mean annual Recovery budget of ", dollar(NS_BudgetForReqSpecies()), ".")
  })
  
  output$NS_ExcludedPlansUnderSpeciesTarget <- renderDataTable({
    dat <- NS_TableExcludedBySpecies()
    dat$ReqBudget <- dollar(round(dat$ReqBudget,0))
    dat$Cost <- dollar(round(dat$Cost,0))
    dat$Benefit <- round(dat$Benefit,2)
    dat$Weight <- round(dat$Weight,2)
    dat$Success <- round(dat$Success,2)
    out <- dat[1:10,]
    datatable(out, rownames=FALSE, colnames=c("Plan ID", "Lead Region", 
                                              "Number Species in Plan", "Total Cost", "Benefit",
                                              "Success", "Weight", "Included when Annual Budget Reaches"))
    
  })
  
  ## Data and Assumptions ----

  output$DA_NSpp <- renderPlot({
    ExtractRegionTaxaBarPlots(x=SummaryBarPlotList, summary="NSpp", 
                              by=input$DA_regiontaxa_barplots) })
  
  output$DA_NPlans <- renderPlot({
    ExtractRegionTaxaBarPlots(x=SummaryBarPlotList, summary="NPlans", 
                              by=input$DA_regiontaxa_barplots) })
  
  output$DA_TotAnnCosts <- renderPlot({
    ExtractRegionTaxaBarPlots(x=SummaryBarPlotList, summary="TotAnnCosts", 
                              by=input$DA_regiontaxa_barplots) })
  
  output$DA_Cost <- renderPlot({
    if (input$DA_rescale_cost == "No"){
      ExtractRegionTaxaBoxPlots(x=SummaryBoxPlotList, summary="Cost", 
                                by=input$DA_regiontaxa_boxplots)
    } else {
      ExtractRegionTaxaBoxPlots(x=rescaled_SummaryBoxPlotList, summary="Cost", by=input$DA_regiontaxa_boxplots)
    }
  })
  
  output$DA_Benefit <- renderPlot({
    if (input$DA_rescale_benefit == "No"){
      ExtractRegionTaxaBoxPlots(x=SummaryBoxPlotList, summary="Benefit", 
                                by=input$DA_regiontaxa_boxplots)
    } else {
      ExtractRegionTaxaBoxPlots(x=rescaled_SummaryBoxPlotList, summary="Benefit", by=input$DA_regiontaxa_boxplots)
    }
  })
  
  output$DA_Success <- renderPlot({
    if (input$DA_rescale_success == "No"){
      ExtractRegionTaxaBoxPlots(x=SummaryBoxPlotList, summary="Success", 
                                by=input$DA_regiontaxa_boxplots)
    } else {
      ExtractRegionTaxaBoxPlots(x=rescaled_SummaryBoxPlotList, summary="Success", by=input$DA_regiontaxa_boxplots)
    }
  })
  
  output$DA_Weight <- renderPlot({
    ExtractRegionTaxaBoxPlots(x=SummaryBoxPlotList, summary="Weight", 
                              by=input$DA_regiontaxa_boxplots)})
  
  output$DA_RawData <- renderDataTable({
    out <- datWIDE %>%
      dplyr::mutate(RegionName = plyr::mapvalues(Region, c(1:8), c("Pacific", "Southwest", "Midwest", "Southeast", "Northeast", "Mountain Prairie", "Alaska", "Pacific Southwest"))) %>%
      dplyr::select(TID, RegionName, Cost=Cost, Benefit, Success, Weight,
             crCE, crCEs, crCEw, crCE1, crCE12) %>%
      dplyr::mutate(crCE=round(crCE,2),crCEs=round(crCEs,2), crCEw=round(crCEw,2),
             crCE1=round(crCE1,2),crCE12=round(crCE12,2))
    out$Cost <- dollar(out$Cost)
    datatable(out, rownames=FALSE, colnames=c("Plan ID", "Lead Region", 
                                              "Cost (Dollars)", "Benefit", "Success",
                                              "Weight", "CE",
                                              "CE-W", "CE-S", "CE-23",
                                              "CE-3"))
  })
  
  ## Compare Scenarios ----

  output$uiBS_A_Budget <- renderUI({
    inputBudget <- BA_Action()
    numericInput("BS_A_Budget", label="Choose an annual budget", value=inputBudget, step=200000)
  })
  
  output$uiBS_B_Budget <- renderUI({
    inputBudget <- BA_Action()
    numericInput("BS_B_Budget", label="Choose an annual budget", value=inputBudget, step=200000)
  })
  
  # Generate 
  BS_A_SummaryRow <- reactive({
    # pull out the dataframe containing the relevant series of budget simulation results
    if (input$BS_A_SplitLvl =="National"){
      tmp <- national_budgetSim[[input$BS_A_CEmethod]]
      # get the rows less than requested budget
      tmp2 <- tmp[tmp$Budget<=input$BS_A_Budget,]
      # get the row associated with the highest budget value that is less than or equal to the requested budget
      tmp2[nrow(tmp2),]
    } else {
      if (input$BS_A_SplitLvl =="Regional"){
        tmp <- regional_budgetSim[[input$BS_A_CEmethod]]
        tmp2 <- tmp[tmp$Budget<=input$BS_A_Budget,]
        tmp2[nrow(tmp2),]
      } else {
        tmp <- taxa_budgetSim[[input$BS_A_CEmethod]]
        tmp2 <- tmp[tmp$Budget<=input$BS_A_Budget,]
        tmp2[nrow(tmp2),]
      }
    }
  })
  BS_B_SummaryRow <- reactive({
    if (input$BS_B_SplitLvl =="National"){
      tmp <- national_budgetSim[[input$BS_B_CEmethod]]
      tmp2 <- tmp[tmp$Budget<=input$BS_B_Budget,]
      tmp2[nrow(tmp2),]
    } else {
      if (input$BS_B_SplitLvl =="Regional"){
        tmp <- regional_budgetSim[[input$BS_B_CEmethod]]
        tmp2 <- tmp[tmp$Budget<=input$BS_B_Budget,]
        tmp2[nrow(tmp2),]
      } else {
        tmp <- taxa_budgetSim[[input$BS_B_CEmethod]]
        tmp2 <- tmp[tmp$Budget<=input$BS_B_Budget,]
        tmp2[nrow(tmp2),]
      }
    }
  })
  BS_AB_SummaryDF <- reactive({
    tmp <- rbind(BS_A_SummaryRow(),BS_B_SummaryRow())
    tmp$Scenario <- c("A","B")
    tmp
  })
  
  BS_A_RegionalSummary <- reactive({
    if (input$BS_A_SplitLvl =="National"){
      tmp <- national_reg_budgetSim[[input$BS_A_CEmethod]]
      tmp$RegionName <- as.factor(tmp$RegionName)
      tmp$RegionName <- fct_relevel(tmp$RegionName, "Pacific", "Southwest", "Midwest", "Southeast", "Northeast", "Mountain Prairie", "Alaska", "Pacific Southwest")
      tmp2 <- tmp[tmp$Budget<=input$BS_A_Budget,]
    } else {
      if (input$BS_A_SplitLvl =="Regional"){
        tmp <- regional_reg_budgetSim[[input$BS_A_CEmethod]]
        tmp$RegionName <- as.factor(tmp$RegionName)
        tmp$RegionName <- fct_relevel(tmp$RegionName, "Pacific", "Southwest", "Midwest", "Southeast", "Northeast", "Mountain Prairie", "Alaska", "Pacific Southwest")
        tmp2 <- tmp[tmp$Budget<=input$BS_A_Budget,]
      } else {
        tmp <- taxa_reg_budgetSim[[input$BS_A_CEmethod]]
        tmp$RegionName <- as.factor(tmp$RegionName)
        tmp$RegionName <- fct_relevel(tmp$RegionName, "Pacific", "Southwest", "Midwest", "Southeast", "Northeast", "Mountain Prairie", "Alaska", "Pacific Southwest")
        tmp2 <- tmp[tmp$Budget<=input$BS_A_Budget,]
      }
    }
    tmp2$Scenario <- "A"
    tail(tmp2[order(tmp2$Budget), ], 8)
  })
  BS_B_RegionalSummary <- reactive({
    if (input$BS_B_SplitLvl =="National"){
      tmp <- national_reg_budgetSim[[input$BS_B_CEmethod]]
      tmp$RegionName <- as.factor(tmp$RegionName)
      tmp$RegionName <- fct_relevel(tmp$RegionName, "Pacific", "Southwest", "Midwest", "Southeast", "Northeast", "Mountain Prairie", "Alaska", "Pacific Southwest")
      tmp2 <- tmp[tmp$Budget<=input$BS_B_Budget,]
    } else {
      if (input$BS_B_SplitLvl =="Regional"){
        tmp <- regional_reg_budgetSim[[input$BS_B_CEmethod]]
        tmp$RegionName <- as.factor(tmp$RegionName)
        tmp$RegionName <- fct_relevel(tmp$RegionName, "Pacific", "Southwest", "Midwest", "Southeast", "Northeast", "Mountain Prairie", "Alaska", "Pacific Southwest")
        tmp2 <- tmp[tmp$Budget<=input$BS_B_Budget,]
      } else {
        tmp <- taxa_reg_budgetSim[[input$BS_B_CEmethod]]
        tmp$RegionName <- as.factor(tmp$RegionName)
        tmp$RegionName <- fct_relevel(tmp$RegionName, "Pacific", "Southwest", "Midwest", "Southeast", "Northeast", "Mountain Prairie", "Alaska", "Pacific Southwest")
        tmp2 <- tmp[tmp$Budget<=input$BS_B_Budget,]
      }
    }
    tmp2$Scenario <- "B"
    tail(tmp2[order(tmp2$Budget), ], 8)
  })
  BS_AB_RegionalSummaryDF <- reactive({
    tmp <- rbind(BS_A_RegionalSummary(),BS_B_RegionalSummary())
  })
  
  output$BS_NPlans <- renderPlot({
    validate(
      need(input$BS_A_Budget >= 0, "Please wait.  Data are processing!")
    )
    validate(
      need(input$BS_B_Budget >= 0, "Please wait.  Data are processing!")
    )
    ggplot(BS_AB_SummaryDF(), aes(Scenario, NPlansIncluded/TotalNPlans, fill=Scenario))+
      geom_bar(stat="identity")+
      geom_text(aes(label=NPlansIncluded), vjust=1.5, colour="white", size=5)+
      theme_minimal()+
      theme(axis.text=element_text(size=16))+
      scale_y_continuous(limits=c(0,1), labels = scales::percent)+
      scale_fill_manual(values=c("darkred","darkblue"))+
      guides(fill=FALSE)+
      xlab("")+
      ylab("")
  })
  
  output$BS_NSpecies <- renderPlot({
    validate(
      need(input$BS_A_Budget >= 0, "Please wait.  Data are processing!")
    )
    validate(
      need(input$BS_B_Budget >= 0, "Please wait.  Data are processing!")
    )
    ggplot(BS_AB_SummaryDF(), aes(Scenario, NSppIncluded/TotalNSpp, fill=Scenario))+
      geom_bar(stat="identity")+
      geom_text(aes(label=NSppIncluded), vjust=1.5, colour="white", size=5)+
      theme_minimal()+
      theme(axis.text=element_text(size=16))+
      scale_y_continuous(limits=c(0,1),labels = scales::percent)+
      scale_fill_manual(values=c("darkred","darkblue"))+
      guides(fill=FALSE)+
      xlab("")+
      ylab("")
  })
  
  output$BS_Benefit <- renderPlot({
    validate(
      need(input$BS_A_Budget >= 0, "Please wait.  Data are processing!")
    )
    validate(
      need(input$BS_B_Budget >= 0, "Please wait.  Data are processing!")
    )
    ggplot(BS_AB_SummaryDF(), aes(Scenario, SumBenefit/TotalSumBenefit, fill=Scenario))+
      geom_bar(stat="identity")+
      geom_text(aes(label=round(SumBenefit,0)), vjust=1.5, colour="white", size=5)+
      theme_minimal()+
      theme(axis.text=element_text(size=16))+
      scale_y_continuous(limits=c(0,1), labels = scales::percent)+
      scale_fill_manual(values=c("darkred","darkblue"))+
      guides(fill=FALSE)+
      xlab("")+
      ylab("")
  })
  
  output$BS_Success <- renderPlot({
    validate(
      need(input$BS_A_Budget >= 0, "Please wait.  Data are processing!")
    )
    validate(
      need(input$BS_B_Budget >= 0, "Please wait.  Data are processing!")
    )
    ggplot(BS_AB_SummaryDF(), aes(Scenario, SumSuccess/TotalSumSuccess, fill=Scenario))+
      geom_bar(stat="identity")+
      geom_text(aes(label=round(SumSuccess,0)), vjust=1.5, colour="white", size=5)+
      theme_minimal()+
      theme(axis.text=element_text(size=16))+
      scale_y_continuous(limits=c(0,1), labels = scales::percent)+
      scale_fill_manual(values=c("darkred","darkblue"))+
      guides(fill=FALSE)+
      xlab("")+
      ylab("")
  })
  
  output$BS_Weight <- renderPlot({
    validate(
      need(input$BS_A_Budget >= 0, "Please wait.  Data are processing!")
    )
    validate(
      need(input$BS_B_Budget >= 0, "Please wait.  Data are processing!")
    )
    ggplot(BS_AB_SummaryDF(), aes(Scenario, SumWeight/TotalSumWeight, fill=Scenario))+
      geom_bar(stat="identity")+
      geom_text(aes(label=round(SumWeight,0)), vjust=1.5, colour="white", size=5)+
      theme_minimal()+
      theme(axis.text=element_text(size=16))+
      scale_y_continuous(limits=c(0,1), labels = scales::percent)+
      scale_fill_manual(values=c("darkred","darkblue"))+
      guides(fill=FALSE)+
      xlab("")+
      ylab("")
  })
  
  output$BS_ActualSpend <- renderPlot({
    validate(
      need(input$BS_A_Budget >= 0, "Please wait.  Data are processing!")
    )
    validate(
      need(input$BS_B_Budget >= 0, "Please wait.  Data are processing!")
    )
    ggplot(BS_AB_SummaryDF(), aes(Scenario, TotSpend, fill=Scenario))+
      geom_bar(stat="identity")+
      geom_text(aes(label=round(TotSpend,0)), vjust=1.5, colour="white", size=5)+
      theme_minimal()+
      theme(axis.text=element_text(size=16))+
      scale_fill_manual(values=c("darkred","darkblue"))+
      scale_y_continuous(labels = scales::dollar)+
      guides(fill=FALSE)+
      xlab("")+
      ylab("")
  })
  
  output$BS_RegNPlans <- renderPlot({
    validate(
      need(input$BS_A_Budget >= 0, "Please wait.  Data are processing!")
    )
    validate(
      need(input$BS_B_Budget >= 0, "Please wait.  Data are processing!")
    )
    ggplot(BS_AB_RegionalSummaryDF(), aes(RegionName, NPlanIncluded, group=fct_relevel(Scenario, "B","A"), fill=Scenario))+
      geom_bar(stat="identity", position="dodge")+
      theme_minimal()+
      theme(axis.text=element_text(size=16))+
      scale_fill_manual(values=c("darkred","darkblue"))+
      coord_flip()+
      guides(fill=FALSE)+
      xlab("")+
      ylab("")
  })
  
  output$BS_RegNSpecies <- renderPlot({
    validate(
      need(input$BS_A_Budget >= 0, "Please wait.  Data are processing!")
    )
    validate(
      need(input$BS_B_Budget >= 0, "Please wait.  Data are processing!")
    )
    ggplot(BS_AB_RegionalSummaryDF(), aes(RegionName, NSppIncluded, group=fct_relevel(Scenario, "B","A"), fill=Scenario))+
      geom_bar(stat="identity", position="dodge")+
      theme_minimal()+
      theme(axis.text=element_text(size=16))+
      scale_fill_manual(values=c("darkred","darkblue"))+
      coord_flip()+
      guides(fill=FALSE)+
      xlab("")+
      ylab("")
  })
  
  output$BS_RegCost <- renderPlot({
    validate(
      need(input$BS_A_Budget >= 0, "Please wait.  Data are processing!")
    )
    validate(
      need(input$BS_B_Budget >= 0, "Please wait.  Data are processing!")
    )
    # The fact I need to add a /50 here implies the math in underlying function is off
    # The values are still correct this way because Gwen divided equally across years
    # but should be checked if/when code redeveloped
    ggplot(BS_AB_RegionalSummaryDF(), aes(RegionName, (TotSpend/1000000)/50, group=fct_relevel(Scenario, "B","A"), fill=Scenario))+
      geom_bar(stat="identity", position="dodge")+
      theme_minimal()+
      theme(axis.text=element_text(size=16))+
      scale_fill_manual(values=c("darkred","darkblue"))+
      coord_flip()+
      scale_y_continuous(labels = scales::dollar)+
      guides(fill=FALSE)+
      xlab("")+
      ylab("Millions of Dollars")
  })
  
  ## Action Quadrant ----

  # generate quadrant data subset
  quadINCEXC_A <- reactive({
    tmpA <- datLONG %>%
      dplyr::mutate(PlanPossible = ifelse(MaxYearCost<=input$BS_A_Budget, "Possible", "Impossible"))
    outA <- IncExcByBudget(x=tmpA, AnnBudget=input$BS_A_Budget, SplitLvl = input$BS_A_SplitLvl)
    outA <- outA[outA$CEmethod==input$BS_A_CEmethod,c("TID","Status")]
  })
  
  quadINCEXC_B <- reactive({
    tmpB <- datLONG %>%
      dplyr::mutate(PlanPossible = ifelse(MaxYearCost<=input$BS_B_Budget, "Possible", "Impossible"))
    outB <- IncExcByBudget(x=tmpB, AnnBudget=input$BS_B_Budget, SplitLvl = input$BS_B_SplitLvl)
    outB <- outB[outB$CEmethod==input$BS_B_CEmethod,c("TID","Status")]
  })
  
  quadINCEXC_AB <- reactive({
    outAB <- merge(quadINCEXC_A(), quadINCEXC_B(), by.x="TID", by.y="TID", all=TRUE)
    names(outAB) <- c("TID", "ScenarioA", "ScenarioB")
    outAB
  })
  
  quadDAT <- reactive({
    
    tmp <- datWIDE %>%
      # remove 7 outlier high cost plans
      dplyr::filter(Cost/SpeciesInPlan <= 200000000) %>%
      # select the columns for visualization
      dplyr::select(TID, Cost, SpeciesInPlan, Benefit, Success, Weight, RegionName, Taxa, CE, CEs, CEw, CE1, CE12) %>%
      dplyr::mutate(Highlight = "N", CostPerSpecies = Cost/SpeciesInPlan) %>%
      # Assign all labels as quandrant A to save effort later, then adjust
      dplyr::mutate(CBquad = "A", CSquad = "A", CWquad = "A")
    
    # Adjust letter labels for BENEFIT quadrants
    tmp$CBquad[which(tmp$CostPerSpecies <= input$qCost & tmp$Benefit <= input$qBslider)] <- "B"
    tmp$CBquad[which(tmp$CostPerSpecies > input$qCost & tmp$Benefit <= input$qBslider)] <- "C"
    tmp$CBquad[which(tmp$CostPerSpecies > input$qCost & tmp$Benefit > input$qBslider)] <- "D"
    
    # Ajdust letter labels for SUCCESS quadrants
    tmp$CSquad[which(tmp$CostPerSpecies <= input$qCost & tmp$Success <= input$qSslider)] <- "B"
    tmp$CSquad[which(tmp$CostPerSpecies > input$qCost & tmp$Success <= input$qSslider)] <- "C"
    tmp$CSquad[which(tmp$CostPerSpecies > input$qCost & tmp$Success > input$qSslider)] <- "D"
    
    # Adjust letter labels for WEIGHT quadrants
    tmp$CWquad[which(tmp$CostPerSpecies <= input$qCost & tmp$Weight <= input$qWslider)] <- "B"
    tmp$CWquad[which(tmp$CostPerSpecies > input$qCost & tmp$Weight <= input$qWslider)] <- "C"
    tmp$CWquad[which(tmp$CostPerSpecies > input$qCost & tmp$Weight > input$qWslider)] <- "D"
    
    # Add in the Scenario columns and replace all NAs ("Impossibles") with "Excluded"
    tmp <- merge(tmp, quadINCEXC_AB(), by.x="TID", by.y="TID", all=TRUE)
    tmp$ScenarioA[which(is.na(tmp$ScenarioA))] <- "Excluded"
    tmp$ScenarioB[which(is.na(tmp$ScenarioB))] <- "Excluded"    
    
    # Assign the optional Highlight column based on optional choices
    if (input$qRegionTaxa == "R"){
      tmp <- tmp %>% 
        dplyr::mutate(Highlight = ifelse(RegionName==input$qRegion, "Y", "N"))
    } else {
      if (input$qRegionTaxa == "T"){
        tmp <- tmp %>%
          dplyr::mutate(Highlight = ifelse(Taxa==input$qTaxa, "Y", "N"))
      } else {
        if (input$qRegionTaxa == "A"){
          tmp <- tmp %>%
            dplyr::mutate(Highlight = ifelse(ScenarioA=="Included", "Y", "N"))
        }else{
          if (input$qRegionTaxa == "B"){
            tmp <- tmp %>%
              dplyr::mutate(Highlight = ifelse(ScenarioB=="Included", "Y", "N"))
          }
        }
      }
    }
    tmp
  })
  
  # Set of quadrant plots
  output$quadBENEFIT <- renderPlot({
    validate(
      need(input$BS_A_Budget >= 0, "Vist the Compare Scenarios tab first, then this plot will appear.")
    )
    validate(
      need(input$BS_B_Budget >= 0, "Vist the Compare Scenarios tab first, then this plot will appear.")
    )
    ggplot(quadDAT(), 
           aes(Benefit, Cost/SpeciesInPlan, color=Highlight, shape=Highlight, size=Highlight))+
      geom_hline(yintercept=input$qCost, color="blue")+
      geom_vline(xintercept=input$qBslider, color="red")+
      geom_point(alpha=0.5)+
      scale_color_manual(values=c("black", "red"), guide=FALSE)+
      scale_shape_manual(values=c(19, 17), guide=FALSE)+
      scale_size_manual(values=c(2, 4), guide=FALSE)+
      scale_y_continuous(label=scales::dollar)+
      theme_grey()+
      theme(axis.text=element_text(size=16), title = element_text(size=18))+
      ggtitle("Cost & Benefit")+
      ylab("")+
      xlab("")
  })
  output$quadSUCCESS <- renderPlot({
    validate(
      need(input$BS_A_Budget >= 0, "Vist the Compare Scenarios tab first, then this plot will appear.")
    )
    validate(
      need(input$BS_B_Budget >= 0, "Vist the Compare Scenarios tab first, then this plot will appear.")
    )
    ggplot(quadDAT(), 
           aes(Success, Cost/SpeciesInPlan, color=Highlight, shape=Highlight, size=Highlight))+
      geom_point(alpha=0.5)+
      geom_hline(yintercept=input$qCost, color="blue")+
      geom_vline(xintercept=input$qSslider, color="magenta")+
      scale_color_manual(values=c("black", "red"), guide=FALSE)+
      scale_shape_manual(values=c(19, 17), guide=FALSE)+
      scale_size_manual(values=c(2, 4), guide=FALSE)+
      scale_y_continuous(label=scales::dollar)+
      theme_grey()+
      theme(axis.text=element_text(size=16), title = element_text(size=18))+
      ggtitle("Cost & Success (Feasibility)")+
      ylab("")+
      xlab("")
  })
  output$quadWEIGHT <- renderPlot({
    validate(
      need(input$BS_A_Budget >= 0, "Vist the Compare Scenarios tab first, then this plot will appear.")
    )
    validate(
      need(input$BS_B_Budget >= 0, "Vist the Compare Scenarios tab first, then this plot will appear.")
    )
    ggplot(quadDAT(), 
           aes(Weight, Cost/SpeciesInPlan, color=Highlight, shape=Highlight, size=Highlight))+
      geom_point(alpha=0.5)+
      geom_hline(yintercept=input$qCost, color="blue")+
      geom_vline(xintercept=input$qWslider, color="goldenrod")+
      scale_color_manual(values=c("black", "red"), guide=FALSE)+
      scale_shape_manual(values=c(19, 17), guide=FALSE)+
      scale_size_manual(values=c(2, 4), guide=FALSE)+
      scale_y_continuous(label=scales::dollar)+
      theme_grey()+
      theme(axis.text=element_text(size=16), title = element_text(size=18))+
      ggtitle("Cost & Taxonomic Weight")+
      ylab("")+
      xlab("")
  })
  
  # Set of quadrant tables
  
  output$quadTable <- renderDataTable({
    validate(
      need(input$BS_A_Budget >= 0, "Vist the Compare Scenarios tab first, then this table will appear.")
    )
    validate(
      need(input$BS_B_Budget >= 0, "Vist the Compare Scenarios tab first, then this table will appear.")
    )
    tmp <- quadDAT() %>%
      dplyr::select(TID, RegionName, CBquad, CSquad, CWquad, ScenarioA, ScenarioB)
    datatable(tmp, filter = 'top', rownames=FALSE, 
              colnames=c("Plan ID", "Lead Region", "Cost-Benefit Quad", "Cost-Success Quad", "Cost-Weight Quad", 
                         "Scenario A", "Scenario B"),
              options = list(pageLength = 15))
    
  })
  
  ## Uncertainty Simulations ----

  # Create the Low, Moderate, and High Number Species Plots
  output$US_UncertainNSpp_Low <- renderPlot({
    lowdata <- uncNSpp[uncNSpp$SimCo=="L" & uncNSpp$SimBS=="L",]
    ggplot(lowdata, aes(Budget, MeanFunded, group=Treatment, color=Treatment))+
      geom_point(na.rm = TRUE, position=position_dodge(width=0.2), size=5)+
      geom_line(na.rm = TRUE, position=position_dodge(width=0.2))+
      geom_errorbar(aes(x=Budget,ymax=MeanFunded+(2*SDFunded),ymin=MeanFunded-(2*SDFunded)), 
                    na.rm = TRUE, position=position_dodge(width=0.2), width=0.1)+
      guides(color="none")+
      theme_minimal()+
      theme(axis.text=element_text(size=14))+
      ylab("Mean Number of Species Included in Portfolio")+
      xlab("Mean Annual Budget")+
      facet_wrap(~Treatment, ncol=1)
  }, height = 900, width = 320)
  
  output$US_UncertainNSpp_Mod <- renderPlot({
    moddata <- uncNSpp[uncNSpp$SimCo=="M" & uncNSpp$SimBS=="M",]
    ggplot(moddata, aes(Budget, MeanFunded, group=Treatment, color=Treatment))+
      geom_point(na.rm = TRUE, position=position_dodge(width=0.2), size=5)+
      geom_line(na.rm = TRUE, position=position_dodge(width=0.2))+
      geom_errorbar(aes(x=Budget,ymax=MeanFunded+(2*SDFunded),ymin=MeanFunded-(2*SDFunded)), 
                    na.rm = TRUE, position=position_dodge(width=0.2), width=0.1)+
      guides(color="none")+
      theme_minimal()+
      theme(axis.text=element_text(size=14))+
      ylab("Mean Number of Species Included in Portfolio")+
      xlab("Mean Annual Budget")+
      facet_wrap(~Treatment, ncol=1)
  }, height = 900, width = 320)
  
  output$US_UncertainNSpp_High <- renderPlot({
    highdata <- uncNSpp[uncNSpp$SimCo=="H" & uncNSpp$SimBS=="H",]
    ggplot(highdata, aes(Budget, MeanFunded, group=Treatment, color=Treatment))+
      geom_point(na.rm = TRUE, position=position_dodge(width=0.2), size=5)+
      geom_line(na.rm = TRUE, position=position_dodge(width=0.2))+
      geom_errorbar(aes(x=Budget,ymax=MeanFunded+(2*SDFunded),ymin=MeanFunded-(2*SDFunded)), 
                    na.rm = TRUE, position=position_dodge(width=0.2), width=0.1)+
      guides(color="none")+
      theme_minimal()+
      theme(axis.text=element_text(size=14))+
      ylab("Mean Number of Species Included in Portfolio")+
      xlab("Mean Annual Budget")+
      facet_wrap(~Treatment, ncol=1)
  }, height = 900, width = 320)
  
  # Create the Low, Moderate, and High Performance Plots
  output$US_UncertainPerform_Low <- renderPlot({
    lowdata <- uncNSpp[uncNSpp$SimCo=="L" & uncNSpp$SimBS=="L",]
    ggplot(lowdata, aes(Budget, MeanPerform, group=fct_reorder(Treatment,MeanPerform), color=Treatment))+
      geom_point(na.rm = TRUE, position=position_dodge(width=0.2), size=5)+
      geom_line(na.rm = TRUE, position=position_dodge(width=0.2))+
      geom_errorbar(aes(x=Budget,ymax=MeanPerform+(2*SDPerform),ymin=MeanPerform-(2*SDPerform)), 
                    na.rm = TRUE, position=position_dodge(width=0.2), width=0.1)+
      guides(color="none")+
      #theme_minimal()+
      theme(axis.text=element_text(size=14))+
      ylab("Mean Portfolio Performance Value")+
      xlab("Mean Annual Budget")+
      scale_y_continuous(labels = scales::comma)+
      facet_wrap(~Treatment, ncol=1)
  }, height = 900, width = 320)
  output$US_UncertainPerform_Mod <- renderPlot({
    moddata <- uncNSpp[uncNSpp$SimCo=="M" & uncNSpp$SimBS=="M",]
    ggplot(moddata, aes(Budget, MeanPerform, group=fct_reorder(Treatment,MeanPerform), color=Treatment))+
      geom_point(na.rm = TRUE, position=position_dodge(width=0.2), size=5)+
      geom_line(na.rm = TRUE, position=position_dodge(width=0.2))+
      geom_errorbar(aes(x=Budget,ymax=MeanPerform+(2*SDPerform),ymin=MeanPerform-(2*SDPerform)), na.rm = TRUE, position=position_dodge(width=0.2), width=0.1)+
      guides(color="none")+
      #theme_minimal()+
      theme(axis.text=element_text(size=14))+
      ylab("Mean Portfolio Performance Value")+
      xlab("Mean Annual Budget")+
      scale_y_continuous(labels = scales::comma)+
      facet_wrap(~Treatment, ncol=1)
  }, height = 900, width = 320)
  
  output$US_UncertainPerform_High <- renderPlot({
    highdata <- uncNSpp[uncNSpp$SimCo=="H" & uncNSpp$SimBS=="H",]
    ggplot(highdata, aes(Budget, MeanPerform, group=fct_reorder(Treatment,MeanPerform), color=Treatment))+
      geom_point(na.rm = TRUE, position=position_dodge(width=0.2), size=5)+
      geom_line(na.rm = TRUE, position=position_dodge(width=0.2))+
      geom_errorbar(aes(x=Budget,ymax=MeanPerform+(2*SDPerform),ymin=MeanPerform-(2*SDPerform)), na.rm = TRUE, position=position_dodge(width=0.2), width=0.1)+
      guides(color="none")+
      #theme_minimal()+
      theme(axis.text=element_text(size=14))+
      ylab("Mean Portfolio Performance Value")+
      xlab("Mean Annual Budget")+
      scale_y_continuous(labels = scales::comma)+
      facet_wrap(~Treatment, ncol=1)
  }, height = 900, width = 320)
  
  
  # Create the Low, Moderate, and High InOut Plots
  # These are reactive to choice of Uncertainty Level & Simulation Set
  
  output$US_UncertainInOut <- renderPlot({
      SimDAT <- uncInOut[uncInOut$SimCo==input$US_Level & uncInOut$SimBS==input$US_Level & uncInOut$Treatment==input$US_Sim,]
      ggplot(SimDAT, aes(Budget, PlanCount/545, fill=Status))+
        geom_bar(stat="identity")+
        scale_y_continuous(labels = scales::percent)+
        scale_fill_manual(values=c("orange", "yellow", "deepskyblue"))+
        ylab("Percentage of Plans")+
        theme(axis.text=element_text(size=14))
    })
  
  output$US_InOutProbability <- renderDataTable({
    tmp <- uncProbInc %>%
      dplyr::filter(SimVar==input$US_Sim & SimCo==input$US_Level & SimBS==input$US_Level) %>%
      dplyr::select(TID, RegionName, L, M, H, Cost=Cost, Benefit, Success, Weight) %>%
      dplyr::mutate(Cost=round(Cost,0))
    datatable(tmp, filter =list(position='top', plain=TRUE), rownames=FALSE, 
              colnames=c("Plan ID", "Lead Region", "$7.5m", "$15m", "$30m", "Cost", "Benefit", "Success", "Weight"))%>%
              #options = list(
                #pageLength = 15, 
                #autoWidth=TRUE, 
                #scrollX=T, 
                #scrollY=400,
                #columnDefs = list(list(width = '10%', targets = c(1:9))))  )%>%
    formatStyle("L", backgroundColor = styleInterval(cuts=c(.01,0.99), values=c("orange","yellow","deepskyblue"))) %>%
      formatStyle("M", backgroundColor = styleInterval(cuts=c(.01,0.99), values=c("orange","yellow","deepskyblue"))) %>%
      formatStyle("H", backgroundColor = styleInterval(cuts=c(.01,0.99), values=c("orange","yellow","deepskyblue"))) %>%
      formatCurrency(c("Cost"))
   })

  
  ## Generate PPT Report ----

  output$PPT_report <- downloadHandler(
    filename = function() {
      paste0("RecoveryExplorer_",Sys.Date(),".pptx")
    }, # the document to produce
    content = function(file){
      # Creation of doc, a pptx object
      # use custom template
      doc <- pptx(template = 'www/SESYNC_template.pptx')

      # Add Title Page slide
      doc <- addSlide( doc, slide.layout = 'Title Slide' )
      doc <- addTitle( doc, "Recovery Data Explorer")
      doc <- addSubtitle( doc, paste0("Report Demonstration: ", Sys.Date()))
      
      # Add Intro slide
      doc <- addSlide( doc, slide.layout = 'SESYNC_Intro' )
      
      # Add 1113 Summary Slide
      FT_1113 <- FlexTable(data=BA_CreateTable())
      
      doc <- addSlide( doc, slide.layout = 'Two Content' )
      doc <- addTitle( doc, "1113 Budget Allocation")
      doc <- addParagraph( doc, paste0("The total amount allocated to Recovery Actions, ", dollar(BA_Action()), ", represents ",
                                      round(BA_Action()*100/input$BA_Total,0), "% of the 1113 budget."))
      doc <- addFlexTable( doc, FT_1113)

      # Add Notes & Credits slide
      doc <- addSlide( doc, slide.layout = 'SESYNC_NotesCredits' )

      
      writeDoc( doc, file )
    })
  
  # Generate Word Report ----

  output$DOC_report <- downloadHandler(
    filename = function() {
      paste0("RecoveryExplorer_", Sys.Date(),".docx")
    }, # the document to produce
    content = function(file){
      # Creation of doc object
      doc <- docx(title = "demo")

      # Add Document title
      doc <- addParagraph( doc,
                           paste0("Sample SESYNC Recovery Explorer Report"), stylename = "Titre")

      # Add Document subtitle
      doc <- addParagraph( doc,
                           paste0("https://kdvprivate.shinyapps.io/SESYNC/"), stylename = "Sous-titre")

      # Add Summary paragraph
      doc <- addParagraph( doc,
                           paste0("This report summarizes information from the 1113 Allocation and National Summary tabs of the Recovery Explorer tool.  It summarizes one possible scenario for the dispersement of recovery funds among programs and plans.  The information in this report is for demonstration purposes only.  Both the data and the valuation metrics underlying the work are examples to demonstrate how such a tool can support decisions and both would require further refinement and discussion."), stylename = "Normal")

      # Add a section title
      doc <- addTitle( doc, "1113 Budget Allocation", level=1)

      # Add Summary paragraph
      doc <- addParagraph( doc,
                           paste0("The proposed 1113 budget allocation appears in Table 1.  Given an anticipated recovery budget of ", dollar(input$BA_Total) , ", this scenario allocates ", dollar(BA_RecoveryImplementation()) ," (", round(BA_RecoveryImplementation()*100/input$BA_Total,0), " percent) of that budget towards implemention.  Implementation itself involves multiple tasks and this scenario placed ", dollar(BA_Action()) ," of the implementation dollars (", round(BA_Action()*100/input$BA_Total,0) ," percent of the 1113 budget) directly towards Recovery Actions as outlined in the Recovery Plans and Five Year Reviews."), stylename = "Normal")

      # Add 1113 Budget table
      budgetTable <- FlexTable(data=BA_CreateTable())
      doc <- addFlexTable( doc, budgetTable)

      # Add a section title
      doc <- addTitle( doc, "Anticipated Recovery Outcomes", level=1)

      # Add Summary paragraph
      doc <- addParagraph( doc,
                           paste0("A cost efficient prioritization of Recovery Plans can guide managers towards actions that are most likely to offer the greatest overall benefit for the least cost.  The Recovery Explorer implements a cost efficiency calculation that considers cost, benefit (degree of threat), probability of success (feasibility), and taxonomic weight (uniqueness)."), stylename = "Normal")

      # Add Summary paragraph
      NS_Dat <- NS_TableByCurrAnnBudget()
      doc <- addParagraph( doc,
                           paste0("Given an annual budget of ", dollar(BA_Action()), " allocated towards actions in the most cost efficient recovery plans, you could take action on ", NS_Dat[[3]], " plans (", round(NS_Dat[[3]]*100/TotalNPlans, 0),"% of total) to place up to ", NS_Dat[[4]], " species (", round(NS_Dat[[4]]*100/TotalNSpp, 0),"% of total) onto the path to recovery.  This annual budget represents ", round(input$NS_CurrAnnBudget*100/MaxAnnReqBudget,1), "% of the estimated annual budget required to achieve full recovery for all species in the database."), stylename = "Normal")

      if (requireNamespace("ggplot2", quietly=TRUE)){
        max_xaxis <- (BA_Action()/1000000) +50
        incexcplot <- ggplot(national_budgetSim[["CE"]])+
          geom_line(aes(Budget/1000000, NSppIncluded), col="gold", size=1.5, linetype="solid")+
          geom_line(aes(Budget/1000000, TotalNSpp-NSppIncluded), col="grey", size=1.5, linetype="solid")+
          geom_vline(xintercept=BA_Action()/1000000, size=1.5, linetype="dotted")+
          scale_x_continuous(limits=c(0,max_xaxis), labels = scales::dollar)+
          theme_minimal()+
          theme(axis.text=element_text(size=16))+
          theme(plot.title = element_text(hjust = 0.5))+
          xlab("Annual Budget (millions) for Recovery Actions")+
          ylab("Number of Species on Path to Recovery")
      }

      doc <- addPlot( doc=doc, fun=print, x=incexcplot)

      doc <- addParagraph( doc, value="The number of Recovery Plans included (gold) and excluded (grey) in the conservation portfolio per annual budget.  The 1113 budget for recovery actions is shown as a verticle black dashed line.", stylename="rPlotLegend")

      #
      writeDoc( doc, file)
    }
  )
}

# Run the application 
shinyApp(ui = ui, server = server)