From 86bbcde9feb3a7a2a8f31071be0800ec4990a0ed Mon Sep 17 00:00:00 2001
From: thierrychambert <thierry.chambert@gmail.com>
Date: Thu, 24 Jun 2021 09:01:35 +0200
Subject: [PATCH] Made Model 3 (with DD) simulations faster by changing the
 calibrate_params function (based on optim) by an analytical approximation
 (using match_lam_delta function).

Tests reveals that the approx is largely good enough. Makes no differences in the results.
---
 R/models.R     |  8 +++++---
 junk.R         | 35 +++++++++++++++++++++++++++--------
 run_analysis.R |  2 +-
 3 files changed, 33 insertions(+), 12 deletions(-)

diff --git a/R/models.R b/R/models.R
index 7fa630d..b0fcf3b 100644
--- a/R/models.R
+++ b/R/models.R
@@ -125,11 +125,13 @@ M3_WithDD_noDemoStoch <- function(N1, s, f, h, DD_params = NULL){
 
   # Apply density dependence effect
   lam_Nt <- 1 + rMAX*(1-(sum(N1)/K)^theta)
-  lam_Nt
 
   # Calibrate vital rates to match lam_Nt
-  inits <- init_calib(s = s, f = f, lam0 = lam_Nt)
-  vr_Nt <- calibrate_params(inits = inits, f = f, s = s, lam0 = lam_Nt)
+  A <- build_Leslie(s = s, f = f)
+  diff_rel_lam <- (lam_Nt - lambda(A))/lambda(A)
+  d <- match_lam_delta(diff_rel_lam = diff_rel_lam, s=s, f=f)
+  vr_Nt <- c(s,f) + d
+
   s_Nt <- head(vr_Nt, length(s))
   f_Nt <- tail(vr_Nt, length(f))
 
diff --git a/junk.R b/junk.R
index 9541fca..ff3f67d 100644
--- a/junk.R
+++ b/junk.R
@@ -10,32 +10,51 @@ h <- 0.05
 
 
 
-A <- build_Leslie(s = s, f = f)
-lambda(A)
-lam_N
+
+
 
 rMAX = 0.15
 K = sum(N1)*5
 theta = 1
 
 # Apply density dependence effect
+N1 = K
 lam_Nt <- 1 + rMAX*(1-(sum(N1)/K)^theta)
 lam_Nt
 
+
 # Calibrate vital rates to match lam_Nt
-inits <- init_calib(s = s, f = f, lam0 = lam_Nt)
-vr_Nt <- calibrate_params(inits = inits, f = f, s = s, lam0 = lam_Nt)
+A <- build_Leslie(s = s, f = f)
+diff_rel_lam <- (lam_Nt - lambda(A))/lambda(A)
+d <- match_lam_delta(diff_rel_lam = diff_rel_lam, s=s, f=f)
+vr_Nt <- c(s,f) + d
+
 s_Nt <- head(vr_Nt, length(s))
 f_Nt <- tail(vr_Nt, length(f))
 
-s ; s_Nt
-f ; f_Nt
-
 A_Nt <- build_Leslie(s = s_Nt, f = f_Nt)
 lambda(A_Nt)
 
 
 
+
+
+
+
+
+
+
+
+
+
+
+
+
+# Calibrate vital rates to match lam_Nt
+inits <- init_calib(s = s, f = f, lam0 = lam_Nt)
+vr_Nt <- calibrate_params(inits = inits, f = f, s = s, lam0 = lam_Nt)
+
+
 s = s_calibrated
 f = f_calibrated
 
diff --git a/run_analysis.R b/run_analysis.R
index 9e3a0d7..21c6a00 100644
--- a/run_analysis.R
+++ b/run_analysis.R
@@ -51,7 +51,7 @@ run0 <- run_simul(nsim, cumuated_impacts,
                   model_demo, time_horzion, coeff_var_environ, fatal_constant)
 
 
-
+# saved time (ratio): 493/12
 # save(run0, file = "./data/run0.rda")
 names(run0)
 
-- 
GitLab