In this tutorial, you will run an R script. This script generates simulated data points with random noise, fits a cubic smoothing spline to the data, and plots the data points, original model, and smoothing spline.
See folder 10-R-pass-in-env-var from examples for reference.
# fitspline.R
# Set the initial seed for the random number generator.
set.seed(sample(1:1000, 1))
# Create n = 100 random data points.
# x is n equally spaced values from 0 to 1.
n <- 100
x <- (1:n)/n
# The model in this simulation (no random error)
mval <- ((exp(x/3) - 2 * exp(-7 * x) + sin(9 * x)) + 1)/3
# Generate n independent normal random variates with mean 0
# and variance derived from the task id
tid <- as.integer(Sys.getenv("SLURM_ARRAY_TASK_ID"))
v <- tid/100
noise <- rnorm(n, 0, v)
# Simulated observed values (model value + noise)
y <- mval + noise
# Alternatively, you can read data from a file:
# dat <- read.table("dataset.dat", header = TRUE)
# attach(dat)
# Fit a cubic smoothing spline to the data
# Use GCV score and all basis functions
fit <- smooth.spline(x, y, cv = FALSE, all.knots = TRUE)
# Create a graph that shows the data, the smoothing spline,
# and the original model
r <- paste("result_", tid, ".ps", sep = "")
postscript(r, height = 8, width = 10, horizo = FALSE)
# Plot data points
plot(x, y, xlab = "x", ylab = "y", cex = 0.5)
# Plot original model values without noise
lines(x, mval, lty = 2)
# Plot smooth spline fit
lines(fit$x, fit$y)
# Save the graph to a PS file
graphics.off()
# To view with Ghostscript, at the
# command line type: gs result_X.ps
# where X is the corresponding task id
#!/bin/bash
#
# [ fitspline.sbatch ]
# This script runs an R program that fits a smoothing spline to simulated data.
# It is an array job: each task uses its array task ID (5, 10 or 15) to set the
# amount of noise in the data, and writes its results to fitspline.<taskID>.Rout
# and result_<taskID>.ps.
#
# Submit it with:
# sbatch fitspline.sbatch
#SBATCH --job-name=fitspline
#SBATCH --array=5-15:5 # task IDs 5, 10 and 15
#SBATCH --mem=512m
#SBATCH --time=00:10:00
#SBATCH --output=fitspline-%A-%a.out # %A = array job ID; %a = array task ID
#SBATCH --mail-type=END,FAIL
#SBATCH --mail-user=netID@stern.nyu.edu
module purge
module load R/4.6.1
R CMD BATCH --no-save --no-restore fitspline.R fitspline.$SLURM_ARRAY_TASK_ID.Rout
To run the SLURM script, execute this command:
sbatch --array=5-15:5 fitspline.sbatch