wsim_ag_spinup.R 2.5 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
#!/usr/bin/env Rscript

# Copyright (c) 2019 ISciences, LLC.
# All rights reserved.
#
# WSIM is licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License. You may
# obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

wsim.io::logging_init('wsim_ag_spinup')
suppressMessages({
library(dplyr)
library(wsim.agriculture)
library(wsim.io)
})

'
Perform spin-up calculations for agriculture assessment

26
Usage: wsim_ag_spinup --loss_method <method> --output_dir <dir>
27 28

Options:
29 30
--output_dir <dir>      Output directory
--loss_method <method>  Method for combining losses from multiple streses [sum or max]
31 32 33 34
'->usage

main <- function(raw_args) {
  args <- parse_args(usage, raw_args)
35

36 37 38
  rp_onset <- 12
  rp_total <- 80
  rp_power <- 2
39

40
  num_iterations = 10000
41

42 43
  infof("Performing expected loss simulations (N=%d, combining losses using %s)", num_iterations, args$loss_method)
  simulation_results <- simulate_expected_loss(N=num_iterations, combine_with=args$loss_method, rp_onset, rp_total, rp_power)
44

45 46 47
  write_list <- function(dat, fname) {
    write.csv(data.frame(param=names(dat),
                         value=as.character(dat),
48 49 50
                         stringsAsFactors=FALSE),
              fname,
              row.names=FALSE)
51
  }
52

53
  for (m in unique(simulation_results$method)) {
54
    inputs <- simulation_results %>%
55
      filter(method==m) %>%
56 57 58 59 60
      group_by(season_length_months) %>%
      summarize(expected_loss= mean(mean_loss)) %>%
      transmute(season_length = 30.42*season_length_months,
                season_length2 = season_length*season_length,
                expected_loss)
61

62
    fit <- lm(expected_loss ~ season_length + season_length2 + 0, inputs)
63

64
    infof("Writing loss function params for method: %s", m)
65
    write_list(list(
66 67
      mean_loss_fit_a= fit$coefficients[[1]],
      mean_loss_fit_b= fit$coefficients[[2]],
68 69
      loss_initial= rp_onset,
      loss_total= rp_total,
70 71 72
      loss_power= rp_power,
      loss_method= args$loss_method
    ), file.path(args$output_dir, sprintf('loss_params_%s.csv', m)))
73 74 75 76 77 78
  }
}

if (!interactive()) {
  tryCatch(main(commandArgs(trailingOnly=TRUE)), error=wsim.io::die_with_message)
}