【问题标题】:Run R code in parallel in a shell without having R file在没有 R 文件的情况下在 shell 中并行运行 R 代码
【发布时间】:2018-05-06 01:01:51
【问题描述】:

我有以下 .sh 文件,可以使用 sbatch 在集群计算机上运行:

Shell.sh

#!/bin/bash
#
#SBATCH -p smp # partition (queue)
#SBATCH -N 2 # number of nodes
#SBATCH -n 2 # number of cores
#SBATCH --mem 2000 # memory pool for all cores
#SBATCH -t 5-0:00 # time (D-HH:MM)
#SBATCH -o out.out # STDOUT
#SBATCH -e err.err # STDERR

module load R
srun -N1 -n1 R CMD BATCH ./MyFile.R &
srun -N1 -n1 R CMD BATCH ./MyFile2.R &
wait

我的问题是 MyFile.R 和 MyFile2.R 看起来几乎一样:

MyFile.R

source("Experiment.R")
Experiment(args1) # some arguments

MyFile2.R

source("Experiment.R")
Experiment(args2) # some arguments

事实上,我需要为大约 100 个文件执行此操作。由于他们都加载了一些 R 文件,然后使用不同的参数运行实验,我想知道是否可以在不为每次运行创建新文件的情况下执行此操作。我想并行运行所有进程,所以我认为不能只创建一个 R 文件。

我的问题是:是否有某种方法可以直接从 shell 运行该进程,而无需为每次运行创建一个 R 文件?那么我可以做类似的事情吗

srun -N1 -n1 R cmd BATCH 'source("Experiment.R"); Experiment(args1)' &
srun -N1 -n1 R cmd BATCH 'source("Experiment.R"); Experiment(args2)' &
wait

而不是 shell.sh 中的最后三行?

【问题讨论】:

  • 您是否考虑过将您的参数作为脚本的参数传递? tuxette.nathalievilla.org/?p=1696
  • 是的,但是我没有在 Rscript 中找到并行运行这些进程的方法,在这种情况下,这意味着我可以为每个 Rscript 分配一个节点(计算机)和一个核心

标签: r slurm sbatch


【解决方案1】:

您的批处理脚本仍应包含 2 行来启动 2 个不同的 R 进程,但您可以使用相同的文件名在命令行上传递参数:

module load R
srun -N1 -n1 Rscript ./MyFile.R args1_1 args1_2 &
srun -N1 -n1 Rscript ./MyFile.R args2_1 args2_2 &
wait

然后在你的 R 文件中:

source("Experiment.R")
#Get aruments from the command line
argv <- commandArgs(TRUE)

# Check if the command line is not empty and convert values if needed
if (length(argv) > 0){
   nSim <- as.numeric( argv[1] )
   meanVal <- as.numeric( argv[2] ) 
} else {
   nSim=100  # some default values
   meanVal =5
}

Experiment(nSim, meanVal) # some arguments

如果您更喜欢使用R 命令而不是Rscript,那么您的批处理脚本应如下所示:

module load R
srun -N1 -n1 R -q --slave --vanilla --args args1_1 args1_2 < myFile.R &
srun -N1 -n1 R -q --slave --vanilla --args args2_1 args2_2 < myFile.R &
wait

"R -q --slave ... &lt; myFile.R" 部分可能需要(或不需要)引号

【讨论】:

  • 谢谢!这正是我想要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
  • 2011-02-25
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多