Unix-like systems and bash

1. Logging on to the Falcon Supercomputer

Prerequisites

You will interact with four main systems:

  • COGS – The account portal where you request and manage your Falcon login (username and password).
  • ColdFront – Normally only PIs need to access ColdFront. The portal where projects, project membership, and compute allocations are managed.
  • Falcon login node – The HPC login server where you log in and run jobs.
    • falcon_username@falconlogin.cf.ac.uk
  • Bangor’s SSH Bastion – The gateway you must connect through before you can reach Falcon.
    • bangor_username@ssh.bangor.ac.uk

Important Note: COGS and ColdFront are reachable directly from the Bangor LAN - e.g. campus managed wired, VPN or via standard Bangor remote access solutions such as the Linux Desktop available through eResearch OnDemand. Also note:

  • your bangor_username for the ssh server and falcon_username are different
  • bangor_username has your normal password with MFA
  • falcon_username password (suggest no special characters) can be set in COGS
# Linux/Mac/WSL
# Open a terminal
ssh you25usr@ssh.bangor.ac.uk
# enter your bangor password and complete MFA

# from bangor ssh server, log into falcon
ssh b.you25usr@falconlogin.cf.ac.uk

# ! advanced option: all-in-one
ssh -J you25usr@ssh.bangor.ac.uk b.you25usr@falconlogin.cf.ac.uk

2. Basic bash commands

Unix-like (linux and Mac) generally use a bash shell (or something like it).

“Bash is a command processor that typically runs in a text window where the user types commands that cause actions. Bash can also read and execute commands from a file, called a shell script. Like most Unix shells, it supports filename globbing (wildcard matching), piping, here documents, command substitution, variables, and control structures for condition-testing and iteration.”

See https://en.wikipedia.org/wiki/Bash_(Unix_shell)

# print working directory
pwd

# make directory
mkdir my_directory

# change directory
cd my_directory

# print working directory
pwd

# print something to screen
echo "hello"

# redirect output to file 
echo "hello" > hello.txt

# list contents of directory
ls

# help menu
ls --help

# view contents of file
cat
less
head

# print something else to file
echo "hello2" > hello.txt
echo "hello" > hello.txt
echo "hello2" >> hello.txt

# count lines and characters
wc -l
wc -c

# search for content in files
grep --help
grep "2" hello.txt

# pipes
grep "2" hello.txt | wc -l

# deleting (CAREFUL!!!)
rm hello.txt

# let's make some more files
yes hello | head -n 100 > my_file1.txt
yes goodbye | head -n 100 > my_file2.txt

# wildcards
cat my_file* > my_combined_file.txt

# a note on file extensions
mv my_combined_file2.txt my_combined_file2.mp3
mv my_combined_file2.txt my_combined_file2

# deleting with wildcards (VERY CAREFUL!!!)
rm my*

# Download file from internet: e.g. NCBI
wget https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/964/194/415/GCF_964194415.1_rVipBer3.hap1.1/GCF_964194415.1_rVipBer3.hap1.1_genomic.fna.gz

# Note file is compressed with gzip compression
# view contents without unzipping
zcat GCF_964194415.1_rVipBer3.hap1.1_genomic.fna.gz | less

# uncompress
gunzip GCF_964194415.1_rVipBer3.hap1.1_genomic.fna.gz
# note you can compress with the command gzip

# log off
exit

3. Your turn :)

  • Count number of scaffolds in the adder genome
  • Print scaffold names to a file
  • Print only scaffold names 10 to 20 to a file
  • Count the number of bases in the first line of DNA sequence (i.e. line 2)
  • Work out the genome size (don’t worry about newline characters in your base counts for now)
  • If you are finished early, you can find a genome of your choice to play around with
  • Or… advanced! look at setting up a jump host for 1-step log on and easier data transfer to your local PC: https://bangoroffice365.sharepoint.com/sites/DigitalServices/SitePages/eResearch_Connecting-to-eResearch-Resources.aspx

4. Bash scripts

  • Bash scripts allow sets of commands to be executed in an automated fashion
  • Files contain bash scripts are given the extension .sh by convention
  • fist line is the bash shebang, it instructs the system to parse the file using bash (as opposed to python, perl, R, etc.)
  • lines starting # are comments
  • commands are executed from top to bottom
#!/bin/bash

# let's make some files
yes hello | head -n 100 > my_file1.txt
yes goodbye | head -n 100 > my_file2.txt

# combine files
cat my_file* > my_combined_file.txt

echo "job finished"

A note on text editors

  • never (ever) use a word processor
  • plain text editor (many available)
  • includes terminal plain text editors
  • be careful windows people :)
  • example: vim
# open file
vim my_script.sh

# enter insert mode
i

# do stuff ######################################

# exit insert mode 
[ESC]

# write changes to file
:w

# quit
:q

Executing bash scripts

sh my_script.sh

5. Your turn :)

  • Generate the bash script described above and execute
  • try modifying the script, for example to delete the intermediary files my_file1.txt and my_file2.txt
  • If you are finished early, think what other functions you could add to your script. For example lines counts reported to the terminal or saved in a file

6. Variables

  • In bash, variables can be used to store data in memory
  • Works exactly like objects in R
  • After they are defined, variables can be recalled using $
  • anything entered after the script call becomes variables $1, $2, $3, etc.
  • Or they can be defined in the script variable=value
#!/bin/bash

# script makes lists of 2 words, which can be entered when the script is called
# $count controls the length of the list
# call the script like:
# sh my_script.sh hello goodbye

# declare variables
count=100

# main script 

# let's make some files
yes $1 | head -n $count > my_file1.txt
yes $2 | head -n $count > my_file2.txt

# combine files
cat my_file* > my_combined_file.txt

echo "job finished"

8. Your turn :)

  • Generate the script shown in part 6. variables
  • execute your script, and try changing the variables. Is behaviour as expected?
  • try modifying your script, for example entering the counts at the command line, or specifying the name of the output file at the command line

7. Loops

  • Loops are quite an advanced feature, but extremely useful
  • different types of loop while, for, if, and many more
  • here we look at a basic while loop with a counter
#!/bin/bash 

x=0

while [ $x -lt 10 ]; do
  echo The counter is $x
  let x=x+1
done

8.for loops

  • for loops are extremely useful for iterating over files in a directory, or over a list of items
  • it’s a way of doing things automatically and sequentially

cat are_these_all_adder_scaffolds.txt

# execute a command for each scaffold in the list
for x in $(cat are_these_all_adder_scaffolds.txt); do
  echo $x
done

# the variable can be any word which could help with clarity
for scaffold in $(cat are_these_all_adder_scaffolds.txt); do
  echo $scaffold
done

# you can do multiple commands in the loop, but you need to use `;` to separate them
for scaffold in $(cat are_these_all_adder_scaffolds.txt); do
  echo $scaffold;
  grep -c "$scaffold" GCF_964194415.1_rVipBer3.hap1.1_genomic.fna
done

# other cool loops: if loops
if grep -c "chromosome: 1" GCF_964194415.1_rVipBer3.hap1.1_genomic.fna; then
  echo "did I find a chromosome?"
fi
  • and they can even be nested!

for scaffold in $(cat are_these_all_adder_scaffolds.txt); do

  if grep "$scaffold" GCF_964194415.1_rVipBer3.hap1.1_genomic.fna; then
    echo "${scaffold} is present :)"
  fi

done

9. your turn :)

  • Generate the script shown in part 7. using a loop. Execute
  • create a file containing all scaffolds in the adder genome (you should already have this, see part 3)
  • create a bash script that automatically goes through all scaffolds in the adder genome file and prints their name to the screen if found
  • use VIM to remove some scaffolds from your scaffold file
  • create a bash script that loops through the scaffold names and prints an informative message (for example: “Scaffoldxxx found”) to the terminal if they are found. How could you detect which scaffolds were not in the scaffold file?
  • bonus round: you can loop through a list of scaffolds, without actually creating a scaffold file first… Can you figure out how?

markdown and Rmarkdown in Rstudio

At this stage, you may be taking notes on commands and results in some way. We suggest markdown is the best option for this. It is a simple text format that allows you to combine text, code and results in a single document, and knit to html to view in an internet browser.

Rmarkdown is an one implementation of markdown for use within Rstudio. An Rmarkdown document is written in markdown and contains chunks of embedded R code, which can be executed and results knitted to the html.

# this is an example yaml header that goes at the top of the document
---
title: "R markdown example"
author: "Axel Barlow"
date: "2023-10-31"
output:
  html_document:
    keep_md: true
---

The setup chunk is a special code chunk that is executed at the start of the document. It is used to set options for the document and load libraries.

knitr::opts_chunk$set(echo = TRUE)

1. Basic text formatting


## Header 1

### Header 2

#### Header 3

You can just write stuff like this

- list1
- list2
  - sublist 1
  - sublist 2

1. Numbered list1
2. Numbered list2

**here is bold**

*here is italic*

`this is inline code`  

## Tables

Subject|Emotion|Object
--|--|--
I|hate|Powerpoint
I|love|Rmarkdown

2. R code chunk

# ```{r, echo=TRUE, eval=TRUE}
# here is some R code that is executed
1+1
# ```

3. bash code chunk (not exectuted)

# ```bash
echo "hello"
# ```

4. Your turn :)

  • Set up an Rmarkdown document and save some of your notes and bash commands/scripts in it
  • This will become you personal notebook for the bootcamp, and you can add to it as we go along

Supercomputing Wales and slurm

1. Filesystem

# print working directory
pwd

# list contents of working directory
ls

# move up one level in hierarchy
cd ..

# print working directory
pwd

# list contents of working directory
ls

# move to root directory 
cd /

# list contents of working directory
ls

# Go home
cd ~

2. Copying files

# copying files
cp <source> <destination_file>
cp sheep.txt bla/sheep_in_bla.txt

# on falcon: make a small file
echo "scp'ing is awesome!" > copy.txt

# check the small file
cat copy.txt

# open a new terminal from your local PC & log into the ssh jump host
ssh you25usr@ssh.bangor.ac.uk

# copy the file from falcon to bangor ssh server
scp b.you25usr@falconlogin.cf.ac.uk:/shared/home1/b.jhp24gpg/b.you25usr/copy.txt .

# log out of bangor ssh server
exit

# copy the file from bangor ssh server to your local PC
scp you25usr@ssh.bangor.ac.uk:/home/people/you25usr/copy.txt .

# for WSL users: if you move the file to your Windows filesystem, you can edit in Notepad etc
# your windows filesystem can be found in the WSL in the following path:
/mnt/c/Users/your_windows_username/


# !Advanced! all-in-one
scp -o ProxyJump=you25usr@ssh.bangor.ac.uk b.you25usr@falconlogin.cf.ac.uk:/shared/home1/b.jhp24gpg/b.you25usr/copy.txt .

Paths of glory game :)

# start in your home
cd

# Copy the contents of this file:
/scratch/SCWF00251/oooooo/its/such/a/long/filepatch/paths_of_glory.txt

# To a file named with your name, here:
/scratch/SCWF00251/and/did/he/use/caPITAls/what/a/masochist/

3. Modules

# module searching
module avail
module avail angsd
module spider angsd

# module load
angsd
module load angsd/0.940-GCC-12.3.0
angsd

# module unload
module purge
angsd

4. Slurm

# You are currently using the log in node. 
# Do not run resource-intensive jobs on the log in node!

# use slurm to open an active bash shell on a compute node
srun --nodes=1 --ntasks=4 --mem=4G --time=0-00:20 --pty /bin/bash

# the queue
squeue
squeue -u username

# do something resource intensive
module load pigz
pigz -p 4 GCF_964194415.1_rVipBer3.hap1.1_genomic.fna

# exit
exit

# check efficiency
seff jobid

5. Slurm scripts

  • Running a live terminal is not very convenient
  • We need a way of submitting jobs to the queue: slurm job script
  • It’s just a bash script, with additional options passed to slurm using #SBATCH
#!/bin/bash --login
###
#job name
#SBATCH --job-name=example
#job stdout file
#SBATCH --output=/path/to/dir/example%J
#job stderr file
#SBATCH --error=/path/to/dir/example_err%J
#maximum job time in D-HH:MM
#SBATCH --time=0-00:01
#number of nodes
#SBATCH --nodes=1
#number of parallel processes (tasks)
#SBATCH --ntasks=1
#memory in Gb 
#SBATCH --mem=1G
#specify project
#SBATCH --account SCWF00251_j_paijmans_246

echo hello > hello.txt
# submit to queue
sbatch job_script.sh

5. Your turn :)

  • make 2 new directories in your home: my_slurm_scripts and output_logs
  • make a copy of the slurm script in ./my_slurm_scripts
  • Direct stdout and error messages to ./output_logs
  • Specify 1 node, 4 cpus, 8Gb RAM, 1 hour
  • Submit job to queue

Next

  • You are going to implement the method you developed to print scaffold names to a file from the adder genome in part 3. as a slurm script.
  • Make a slurm script in ./my_slurm_scripts
  • You should work on the compressed file located in your home directory
  • use pigz to decompress the genome file and then re-compress after doing the computation
  • Direct stdout and error messages to ./output_logs
  • Specify 1 node, 8 cpus, 16Gb RAM, 1 hour
  • Submit job to queue

Population genomics: genotype likelihoods and population structure

Our shared project directory is /scratch/SCWF00251/

1. Tour and BEARCAVE

# enter project directory
cd /scratch/SCWF00251/

# view directories
ll

# bams
cd BEARCAVE2/mappedrVipBer3_chr6/
ll

# ref genome
ll ../refgenomes/rVipBer3_chr6/

# look at coverage
module load SAMtools
samtools tview adder0X_XXX_chr6.bam ../refgenomes/rVipBer3_chr6/rVipBer3_chr6.fa
samtools coverage adder0X_XXX_chr6.bam | head -2

2. Compute genotype likelihoods in angsd

We will compute genotype likelihoods using angsd. This requires a list of bamfiles (with full paths) to analyse. For example:

# angsd requires a list of bam files in a text file
ls -1 /scratch/SCWF00251/BEARCAVE2/mappedrVipBer3_chr6/*bam > bamlist_all.txt

For angsd documentation see: https://github.com/angsd/angsd

# load angsd module
module purge
module load angsd/0.940-GCC-12.3.0

# angsd command
#-b = specify bamlist
#-GL = specify genotype likelihood model
#-doMajorMinor = identify major/minor allele using genotype likelihoods
#-doGlf = output genotype likelihoods in beagle format
#-doMaf = calculate minor allele frequency
#-SNP_pval = p-value for SNP calling
#-minMapQ = minimum mapping quality
#-minQ = minimum base quality
#-minMaf = minimum minor allele frequency
#-minInd = minimum number of individuals with data
#-setMinDepthInd = minimum depth per individual
#-doCounts = count number of sampled alleles (required for -seMinDepthInd)
#-out = output file prefix
#-nThreads = number of threads to use

# this calculates the genotype likelihoods for all samples in the bamlist and outputs as a beagle file
angsd -b bamlist_all.txt -GL 1 -doMajorMinor 1 -doGlf 2 -doMaf 1 -SNP_pval 1e-6 -minMapQ 30 -minQ 30 -minMaf 0.1 -minInd 50 -setMinDepthInd 4 -doCounts 1 -out all_gl -nThreads 6

3. Your turn

  • Make a separate slurm job script (somewhere in your home directory) for the above analysis
  • make bamlist in the same directory
  • direct stdout and errors to your chosen location in your home directory
  • adjust SBATCH to appropriate paths and filenames
  • Use 16Gb RAM, 6 CPUs, and run for 40 mins
  • Check results
  • Document your code in your Rmarkdown notebook
# look at beagle file
zcat all_gl.beagle.gz | less 

# uncompress mafs for later use and look
gunzip all_gl.mafs.gz
less all_gl.mafs

4. Allele covariance matrix using PCangsd

We will use the beagle file generated by angsd to compute an allele covariance matrix using PCangsd. This is a fast and efficient way to compute PCA from genotype likelihoods.

See: https://github.com/rosemeis/pcangsd

module purge
module load PCAngsd/1.36.4-gfbf-2025a

#--beagle = specify beagle file
#--eig = number of eigenvectors to compute
#--threads = number of threads to use
#--out = output file prefix

# run PCangsd
pcangsd --beagle all_gl.beagle.gz --eig 2 --threads 4 --out all_gl_pcangsd

5. Genetic distance matrix using ngsDist

We will use the beagle file generated by angsd to compute a genetic distance matrix using ngsDist. This is a fast and efficient way to compute genetic distances from genotype likelihoods.

See: https://github.com/fgvieira/ngsDist

module purge
module load ngsDist/1.0.10-foss-2025a

#--geno all_gl.beagle.gz = specify beagle file
#--probs = input is genotype likelihoods
#--n_ind = number of individuals
#--n_sites = number of sites [note you need to find this out!]
#--posH = specify mafs file [H indicates header]
#--out = output file prefix
#--n_threads = number of threads to use

# run ngsDist
ngsDist --geno all_gl.beagle.gz --probs --n_ind 50 --n_sites XXXXX --posH all_gl.mafs --out all_gl_dist.mat --n_threads 4

6. STRUCTURE-type analysis using ngsAdmix

We will use the beagle file generated by angsd to compute a STRUCTURE analysis using ngsAdmix. This is a fast and efficient way to assign individuals to K populations and to compute admixture proportions from genotype likelihoods.

See: https://github.com/aalbrechtsen/NGSadmix

module purge
module load angsd/0.940-GCC-12.3.0

#-likes = specify beagle file
#-K = number of populations
#-P = number of threads to use
#-outfiles = output file prefix

# run ngsAdmix, included in angsd module
NGSadmix -likes all_gl.beagle.gz -K 5 -P 4 -outfiles all_gl_admix_k5

7. Your turn :)

  • Make separate slurm job scripts somewhere in your home directory for the PCangsd, NGSdist and NGSadmix analyses above
  • direct stdout and errors to your chosen location in your home directory
  • adjust SBATCH to appropriate paths and filenames
  • Specify 1 node, 4 CPUS, 8Gb RAM, and run for 10 mins
  • Check results
  • Document your code in your Rmarkdown notebook

Intro to basic R commands

Download the adder_measurements_2026.txt file to your working directory (use right-click “Save link as…”):

Download adder_measurements_2026.txt

# R is just a big calculator
1+1

# make an object
my_sum <- 1+1

# vectors
my_vec <- c(1,2,3,4)

# functions
length(my_vec)

# plotting
my_vec2 <- c(1,2,3,4) # geenrate data
plot(my_vec, my_vec2)
plot(c(1,2,3,4), c(4,3,2,1))

# sample from a normal distribution
rnorm(500, 10, 1)

# histogram
hist(rnorm(500, 10, 1))

# read in data as a dataframe
my_adder <- read.table("adder_measurements_2026.txt", header=TRUE)

# isolate svl data
my_adder$svl

# and we can make this into a self-contained script too...
# ...and also run this on the SCW

Your turn

  • Draw a histogram of adder tail length
  • Draw a scatterplot of svl vs tail length
  • Calculate means and standard deviations for each variable
  • If you have finished early, try out ways to make your plots more attractive

Pretty maps

download the following 3 files to your working directory (use right-click “Save link as…”):

Download adder_distribution.shx

Download adder_distribution.shp

Download adder_info_2026.txt


# read in the data

# read in the data
adders <- read.table("adder_info_2026.txt", header=T, sep=',')

# load libraries
library(maps)

# plot simple map
map("world",
    xlim=c(-12, 32),
    ylim=c(49, 71))


# add samples
points(adders$lon,adders$lat)

Wouldn’t it be nice to add an adder distribution to this?

# load libraries
library(sf)

# add IUCN distribution as SHP file on the map
iucn <- st_read("adder_distribution.shx")
plot(st_geometry(iucn), add=TRUE, border=NA, col="slategrey")

# add samples
points(adders$lon,adders$lat)

your turn

  • crop the map to the region of interest using xlim and ylim in the plot() function
  • colour the points by locality (adders$col)
  • create your own colours that are colourblind friendly without changing the input file
  • change the symbols / sizes
  • Create a Rmarkdown document that contains all your code and outputs to create a summary document of this whole analysis we’ve just done: create plots of measurements, calculating means, standard deviations of measurements, generate maps.

Population structure analyses

You can use your own angsd output files or the ones here:

Download covariance matrix all_gl_pcangsd.cov

Download distance matrix all_gl_dist.mat

Download NGSAdmix output all_gl_admix_k5.qopt

1. PCA

# read in covariance matrix
my_cov <- as.matrix(read.table("./assets/data/all_gl_pcangsd.cov"))

# read in adder info
adders <- read.table("./assets/data/adder_info_2026.txt", header=T, sep=',')

# do PCA
my_pca <- eigen(my_cov)
# the output is a list with two parts:
# $values = vector of eigen values 
# $vectors = matrix of eigen vectors

# look at eigen values
my_pca$values
##  [1] 9.3088562 6.8410582 4.1681294 3.3248946 1.8921952 1.8682885 1.7580818
##  [8] 1.7188633 1.4938344 1.3692458 1.2956920 1.2126838 1.1383479 1.1155928
## [15] 1.0417361 1.0178383 0.9373068 0.9194945 0.8878075 0.8768859 0.8519084
## [22] 0.8166972 0.7978276 0.7645141 0.7179618 0.7171298 0.6884394 0.6689225
## [29] 0.6378859 0.6257676 0.6132691 0.6056818 0.5952524 0.5828674 0.5316044
## [36] 0.5101660 0.4928826 0.4793737 0.4448026 0.4434346 0.4346284 0.4276047
## [43] 0.4079586 0.3675224 0.3516974 0.3282824 0.3221235 0.2917445 0.2156902
## [50] 0.0218801
# plot
# colours are just a vector of colours, one for each sample, in order of bamlist
plot(my_pca$vectors[,1], my_pca$vectors[,2],
     pch=21, bg=adders$col
)

2. NJ tree

# we use the ape library
# note for markdown libraries are normally loaded in the setup chunk
library(ape)

# read in matrix
my_mat <- as.matrix(read.table("./assets/data/all_gl_dist.mat", skip=2, row.names=1))

# compute tree
my_tree <- nj(my_mat)

par(mar=(c(1,5,1,1)), xpd=TRUE) # set margins to 1 on all sides

# plot
my_root <- root(my_tree, node=60)
my_root$tip.label <- adders$loc
plot(my_root, label.offset = 0.01)
tiplabels(pch=21, bg=adders$col, cex=0.8)
add.scale.bar(x=0., y=0., lwd=2, cex=1)

3. NGSadmix

# read in admixture proportions
my_ngs <- as.matrix(read.table("./assets/data/all_gl_admix_k5.qopt"))

# plot
barplot(t(my_ngs), col=c("yellow", "blue", "green", "grey", "red"), names.arg=adders$name, las=2, cex.names=0.6)

Your turn :)

Population genomics: genetic diversity

1. Heterozygosity

Our estimate of heterozygosity is the SFS for a single individual in sliding windows across chromosome 6. This requires a single bam file (with full path) to analyse and an outgroup, for which we will used the related species Vipera ursinii. angsd is used to first calculate GLs and allele frequencies. realSFS which is included in angsd is then used to compute the SFS.

# set files as variables
input='/scratch/SCWF00251/BEARCAVE2/mappedrVipBer3_chr6/adderXX_YYY_chr6.bam'
output='adderXX_het'
# We need to specify the ancestral allele, use fasta generated from Vipera ursinii outgroup
urs='/scratch/SCWF00251/BEARCAVE2/outgroups/ursinii01_rom_chr6.fa'

# depth variables
min=4

# estimate genotype likelihoods
# -i = input file
# -doSaf = per-site allele frequencies
# -GL = genotype likelihood model
# -P = number threads
# -anc = outgroup, to identify ancestral allele
# -minQ,-minMapQ = min base and map quality
# -setMinDepthInd = min depth filter
angsd -i $input -doSaf 1 -GL 1 -P 4 -anc $urs -out $output -minMapQ 30 -minQ 30 -setMinDepthInd $min -doCounts 1

# calculate sfs
# -nSites = sliding window size
# -P = no threads
realSFS $output.saf.idx -nSites 50000 -P 4 > $output.window.sfs

2. Population genetic diversity

We require a list of bamfiles (with full paths) from a single population to analyse. For example:

# angsd requires a list of bam files from one population in a text file
ls -1 /scratch/SCWF00251/BEARCAVE2/mappedrVipBer3_chr6/*bam | grep ang > bamlist_ang.txt

Next we will compute various population genetic diversity metrics in sliding windows across chromosome 6. We first compute GLs and allele frequencies in angsd, then use realSFS for the SFS, and finally thetastat for the diversity metrics in a sliding window.

# set files as variables
# We need to specify the ancestral allele, use fasta generated from Vipera ursinii outgroup
urs='/scratch/SCWF00251/BEARCAVE2/outgroups/ursinii01_rom_chr6.fa'
outpop='ang'

# depth variables
min=4

# estimate genotype likelihoods
# -b = input bam list
# -doSaf = per-site allele frequencies
# -GL = genotype likelihood model
# -P = number threads
# -anc = outgroup, to identify ancestral allele
# -minQ,-minMapQ = min base and map quality
# -setMinDepthInd = min depth filter
# -minInd = minimum number of individuals with data
angsd -b bamlist_ang.txt -doSaf 1 -doMaf 1 -GL 1 -P 4 -doMajorMinor 1 -anc $urs -out $outpop -minMapQ 30 -minQ 30 -setMinDepthInd 4 -minInd 7 -doCounts 1

#get 1d sfs for population
realSFS $outpop.saf.idx -P 4 > $outpop.sfs

#combine saf and sfs to generate per site theta values
realSFS saf2theta $outpop.saf.idx -sfs $outpop.sfs -outname $outpop

#make slidingwindow files from it
thetaStat do_stat $outpop.thetas.idx -win 50000 -step 50000 -outnames $output.50kb.thetas.txt

3. Your turn :)

  • Make separate slurm job scripts somewhere in your home directory for the heterozygosity and population diversity analyses above
  • direct stdout and errors to your chosen location in your home directory
  • adjust SBATCH to appropriate paths and filenames
  • Specify 1 node, 4 CPUS, 8Gb RAM, and run for 10 mins for heterozygosity
  • Specify 1 node, 4 CPUS, 16Gb RAM, and run for 20 mins for population diversity
  • Check results
  • Document your code in your Rmarkdown notebook
  • ADVANCED: make a script that computes heterozygosity for all adders using a loop
  • ADVANCED: compute population diversity metrics for the other 4 populations

5. Heterozygosity plot

my_het <- read.table("./assets/data/adder01_het.window.sfs")

plot(1:length(my_het$V2), my_het$V2, pch = 20, cex=0.7)

6. Population diversity plot

my_div <- read.table("./assets/data/ang.50kb.thetas.txt")

plot(my_div$V3, my_div$V5, pch = 20, cex=0.7)

7. Your turn :)

  • Plot the Manhattan plots above
  • Improve the plots, for example:
    • Add sensible x axis and y axis scales and labels
    • Add a horizontal line showing the mean heterozygosity or nucleotide diversity
  • What other plots would be appropriate? Generate them and add to your Rmarkdown notebook. You could also add results for other individuals or populations for comparison.

Phylogenomics

We will change datasets for phylogenomics. We have datasets from 7 species of European viper mapped to chromosome 6. The mapping reference is Macrovipera schweizeri, which is an outgroup. This avoids any issues with mapping reference bias.

Bam files are located in /scratch/SCWF00251/BEARCAVE2/mappedrMacScw_chr6/.

ls -1 *bam

ammodytes_chr6.bam
aspis_chr6.bam
berus_UK_chr6.bam
latastei_chr6.bam
seoani_chr6.bam
ursinii_chr6.bam

The reference genome is: /scratch/SCWF00251/BEARCAVE2/refgenomes/rMacScw_chr6/rMacScw1_chr6.fa.

1. Consensus fasta

We use angsd to generate a consensus fasta using the -doFasta command

#-doFasta 2 = generate consensus fasta using the most frequent base
#-minQ -minMapQ = minimum base and map quality
#-setMinDepthInd = minimum depth
#-basesPerLine = number of bases per line in output fasta, set to > chromosome size [believe me you will thank me for this later]
angsd -doFasta 2 -doCounts 1 -minQ 30 -minMapQ 30 -setMinDepthInd 3 -basesPerLine 100000000 -i /scratch/SCWF00251/BEARCAVE2/mappedrMacScw_chr6/ammodytes_chr6.bam -out ammodytes_chr6

2. Your turn :)

  • generate a script to call consensus fasta for all 6 bam files. You could consider using a loop for this

PROBLEM! Look at the fasta files you just generated. They all have the same header line. This means we won’t be able to tell which species is which in the final tree

  • Johanna live coding hackathon

Once you have an alignment, we can strip out invariant sites and sites with missing data using snp-sites.

module load snp-sites/2.5.1-GCCcore-12.3.0

# run snp-sites
# -c = remove sites with missing data
snp-sites -c alignment_file.fa > alignment_chr6.fa

3. Maximum likelihood analysis using iqtree

module purge
module load IQ-TREE/3.0.1-gompi-2024a

# run iqtree
# -s = input alignment
# -o = outgroup
# -T = number of threads
# -B = number of bootstrap replicates
# -m GTR+ASC = GTR model of sequence evolution for ascertained SNPs
# --redo = overwrite existing output files
iqtree3 -s alignment_chr6.fa -o macrovipera_chr6 -T 4 -B 1000 -m GTR+G+ASC --redo

4. Your turn :)

  • generate the ML tree in iqtree, log in node should be fine
  • look at the output files, visualise the tree file (*.treefile) in FigTree

Download alignment_chr6.fa.treefile

5. D statistics

We need a bamlist of the 6 Vipera species to compute D statistics. We use the reference genome file for the outgroup Macrovipera schweizeri.

# -doAbbababa 1 = compute D statistics using single read sampling
# -minQ -minMapQ = minimum base and map quality
# -b = input bam list
# -anc = outgroup reference genome
# -out = output file prefix
angsd -doAbbababa 1 -doCounts 1 -minQ 30 -minMapQ 30 -b bamlist_phylo -anc /scratch/SCWF00251/BEARCAVE2/refgenomes/rMacScw1_chr6/rMacScw1_chr6.fa -out vipera_dstat -nThreads 4

We then carry out the jackknife analysis in R

# create a file containing the list of individuals in the order they appear in the bamlist_phylo file
ammodytes_chr6
aspis_chr6
berus_UK_chr6
latastei_chr6
seoani_chr6
ursinii_chr6

# run jackknife with the jackKnife.R script (comes with angsd)
Rscript jackKnife.R file=vipera_dstat.abbababa indNames=indnames_dstat outfile=vipera_dstat_jackknife

Your turn :)

  • run the D statistic and jackknife analysis above
  • Set up a slurm for angsd: 4 CPUs, 8Gb RAM, 10 mins
  • jackknife can be run on the log in node
  • open the output in Excel:
    • delete all comparisons that are incongruent with the species tree
    • identify potential admixture events
  • think about how you could visualise the results in a more informative way than a table. Try to plot in R and add to your Rmarkdown notebook

Download vipera_dstat_jackknife.txt