output/script/migration-global.R

library(tidyverse)
library(deSolve)
library(data.table)
library(micro.crm)

#rm(list= ls())
# Augument passed from command line
args = commandArgs(trailingOnly=TRUE)
treatment_name = args[1]

# Make regional species pool
#treatment_name <- "migration-global001"
parameter_load(parameter_text = paste0("parameter_script/", treatment_name, ".txt"))
pool_build(save_data = F)

# Make resource environment
resource <- setNames(c(1, rep(0, P-1)), paste0("R", sprintf("%03d", 1:P)))
assign("Rin", c(Rin1, rep(0, times = P-1)), envir = .GlobalEnv) # Supply for each resource. Set to 0

# Modify the `w` and `stoi` of fermenters
w[1,1:(S_pool/function_group)] <- w_fermenter_P1
stoi[2,1,1:(S_pool/function_group)] <- stoi_fermenter_P1_P2

# Run
result_list <- rep(list(rep(list(NA), replicate)), migration_event+1) # [[1]]: migration 1; [[1]][[2]]: migration1, community2
comm <- rep(list(resource), replicate)
global_pool <- regional_pool

for (i in 1:migration_event) {
  for (r in 1:replicate) {
    # Simulation
    result <- 
      community_generate(pool = global_pool, I = I, threshold = threshold, seed = i*r) %>% # Draw from pool
      community_coalesce(comm[[r]]) %>% # Consumers and resource from previous transfer
      CR_model(time_limit = migration_time_limit, time_step = 1)
    
    # Time
    result$time <- result$time + migration_time_limit*(i-1)
    
    # Save result to the main list
    result_list[[i]][[r]] <- result
    
    cat(paste0(" ", r))
  }
  
  # Take the final time step
  comm <- lapply(result_list[[i]], function(x) {
    temp <- filter(x, time == max(time), value >= threshold) %>% dplyr::select(-time)
    return(setNames(temp$value, temp$variable))
  })
  
  # Make the global pool for this migration
  global_pool <- community_coalesce2(comm)

  # Report progress
  print(paste0("Migration event=", i))
}

# Final time step
print("Final time step")
for (r in 1:replicate) {
  result <- 
    community_generate(pool = global_pool, I = I, threshold = threshold, seed = r*(migration_event+1)) %>% # Draw from pool
    community_coalesce(comm[[r]]) %>% # Consumers and resources from previous transfer
    CR_model(time_limit = time_limit, time_step = 1)
  
  # Time
  result$time <- result$time + migration_time_limit*migration_event
  
  result_list[[migration_event+1]][[r]] <- result
  
  #
  cat(paste0(" ", r))
}


print("Write result")
for (r in 1:replicate) {
  result_r <- rep(list(NA), migration_event+1)
  for (j in 1:(migration_event+1)) result_r[[j]] <- result_list[[j]][[r]]
  
  # Merge all migration events
  result_merged <- rbindlist(result_r)
  
  # Write result file to txt
  parameter_write(result = result_merged, 
                  parameter_list = parameter_list, 
                  file_name = paste0("simulation_result/", treatment_name,"_", sprintf("%03d", r),".txt"))
  
  #
  cat(paste0(" ", r))
}
Chang-Yu-Chang/MigrationCommunity documentation built on Aug. 13, 2019, 9:41 p.m.