APSIM 模型运行和结果分析:利用 R 语言模拟土壤参数对作物生长的影响

本文介绍使用 R 语言和 APSIM 模型模拟土壤参数对作物生长的影响。代码展示了读取土壤参数文件、设置模型参数、运行 APSIM 模型以及整合模拟结果的完整流程,并提供结果保存和文件组织的方案。

1. 读取土壤信息文件

首先,需要将土壤信息存储在一个数据框中。

soil_df <- read.csv('E:/weidan/SOIL.csv')

2. 安装和加载 APSIM 包,设置模型运行参数

安装并加载 APSIM 包,并设置模型运行参数。

#install.packages('APSIM')
library(APSIM)

apsim <- readLines('E:/weidan/region1wheat/quyu1xiaomai.apsim', warn = FALSE)

# 模型运行参数
sim_parameters <- list(
  simulation_name = 'my_simulation',
  override_met = TRUE, # 是否使用默认气象数据
  datapath = '.', # 数据文件夹路径
  soilpath = '.', # 土壤文件夹路径
  version = '7413.3', # APSIM 版本号
  start_date = as.Date('1990-01-01'),
  end_date = as.Date('2000-12-31'),
  run_type = 'auto', # 运行类型(auto或batch)
  num_workers = 1 # 并行运行的进程数
)

3. 设置土壤参数,运行 APSIM 模型,并保存结果

针对每个站点和深度,设置土壤参数,运行 APSIM 模型,并将结果保存为 CSV 文件。

for (i in 1:nrow(soil_df)) {
  site <- soil_df$site[i]
  lat <- soil_df$lat[i]
  lon <- soil_df$lon[i]
  
  for (depth in c(5, 15, 30, 60, 100, 200)) {
    # 设置土壤参数
    soil_parameters <- list(
      Site = site,
      Latitude = lat,
      Longitude = lon,
      Depth = depth,
      LL15 = soil_df$LL15[i],
      DUL = soil_df$DUL[i],
      SAT = soil_df$SAT[i],
      BD = soil_df$BD[i]
    )
    
    # 运行 APSIM 模型
    #output <- run_APSIM(sim_parameters, soil_parameters)
    system(paste(apsim_exe, file_apsim),wait = TRUE,ignore.stdout=TRUE,show.output.on.console=FALSE)
    # 将结果保存为 CSV 文件
    
    # 需要定义一个新的 apsim 文件!
    file_apsim <- paste0('E:/weidan/region1wheat/SHIYONG.apsim') 
    
    writeLines(apsim, file_apsim)
    
    system(paste(apsim_exe, file_apsim),wait = TRUE,ignore.stdout=TRUE,show.output.on.console=FALSE)
    
    file.copy('E:/weidan/region1wheat/SHIYONG.out',paste0('E:/weidan/region1wheat/SHIYONG/',df$name[i],'.out'))
   
    
    print(i)
  }
}
output_list <- list()
for (i in 1:nrow(soil_df)) {
  site <- soil_df$site[i]
  
  for (depth in c(5, 15, 30, 60, 100, 200)) {
    file <- paste0('E:/weidan/region1wheat/SHIYONG/', site, '_', depth, '.out')
    output <- read_APSIM_output(file)
    output$site <- site
    output$depth <- depth
    output_list[[length(output_list) + 1]] <- output
  }
}
output_df <- rbindlist(output_list, fill = TRUE)
write.csv(output_df, 'E:/weidan/shiyongresult.csv', row.names = FALSE)

4. 结果分析

这段代码保存的是 SOIL.csv 中每个经纬度和深度的模拟结果。每次模拟的 OUT 文件会被新的模拟替代,因此需要将模拟结果保存到不同的文件中。这段代码使用 file.copy() 函数将每次模拟的 OUT 文件复制到以站点名为文件夹名的文件夹中。具体来说,这段代码会在当前工作目录下创建一个名为 SHIYONG 的文件夹,然后将每个站点和深度的模拟结果保存为 SHIYONG/站点名.out 的文件名格式。最后,将所有模拟结果合并为一个数据框,并保存为 shiyongresult.csv 文件。

5. 总结

本文介绍了使用 R 语言和 APSIM 模型模拟土壤参数对作物生长的影响。通过读取土壤信息文件、设置模型参数、运行 APSIM 模型以及整合模拟结果,我们可以得到不同土壤条件下作物生长的模拟结果。最后,我们可以根据结果进行进一步的分析和研究。

APSIM 模型运行和结果分析:利用 R 语言模拟土壤参数对作物生长的影响

原文地址: https://www.cveoy.top/t/topic/nCiL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录