Mathematica

The following example can be used as a template for Mathematica jobs:

#!/bin/bash
#SBATCH --job-name=Mathematica
#SBATCH --partition=regular
#SBATCH --nodes=1
#SBATCH --cpus-per-task=1
#SBATCH --time=00:05:00

module purge
module load Mathematica/13.1.0

math -script myscript.m

The math -script command will run all the Mathematica code from myscript.m without starting the graphical interface. The output of the code will be written to the output file of the job (slurm-<jobid>.out).

Your script can contain any Mathematica code, e.g.:

Select[Range[8000],PrimeQ[2^# - 1]&] 

The LaunchKernels function allows you to start multiple Mathematica Kernels (the processes that are actually performing the calculations). By requesting multiple cores on the same node, you can start more than a single kernel. Note that for the best performance, the number of kernels should always equal the number of requested cores. Furthermore, put the LaunchKernels function call somewhere at the top of your script, otherwise Mathematica might have already started too many kernels itself.

Once you have started multiple kernels, you can use built-in functions for parallelizing some of the work, e.g. the Parallelize function:

LaunchKernels[4]
p=Parallelize[Select[Range[8000],PrimeQ[2^# - 1]&]]
Print[p]

In your job script, leave --nodes=1, but set --cpus-per-task=4 in order to get four cores allocated to your job. You can automatically set it in the right way by reading the requested number of cores through an environment variable that is set by the scheduler:

ncores = ToExpression[Environment["SLURM_CPUS_PER_TASK"]]
LaunchKernels[ncores]

For more information about parallelization in Mathematica, see:
https://reference.wolfram.com/language/guide/ParallelComputing.html