Prerequisites
You will interact with four main systems:
falcon_username@falconlogin.cf.ac.ukbangor_username@ssh.bangor.ac.ukImportant 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:
# 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
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
.sh
by conventionbash (as opposed to
python, perl, R, etc.)# are comments#!/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"
vim# open file
vim my_script.sh
# enter insert mode
i
# do stuff ######################################
# exit insert mode
[ESC]
# write changes to file
:w
# quit
:q
sh my_script.sh
bash script described above and
executebash, variables can be used to store data in
memoryR$$1, $2, $3, etc.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"
while, for,
if, and many more#!/bin/bash
x=0
while [ $x -lt 10 ]; do
echo The counter is $x
let x=x+1
done
for loopsfor loops are extremely useful for iterating over files
in a directory, or over a list of items
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
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
VIM to remove some scaffolds from your scaffold
filemarkdown and Rmarkdown in
RstudioAt 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)
## 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
R code chunk# ```{r, echo=TRUE, eval=TRUE}
# here is some R code that is executed
1+1
# ```
bash code chunk (not exectuted)# ```bash
echo "hello"
# ```
# 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 ~
# 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 .
# 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/
# 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
# 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
slurm
job scriptslurm 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
home:
my_slurm_scripts and output_logsslurm script in
./my_slurm_scripts./output_logsNext
slurm script.slurm script in
./my_slurm_scriptshome directory./output_logsOur shared project directory is /scratch/SCWF00251/
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
angsdWe 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
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
PCangsdWe 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
ngsDistWe 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
STRUCTURE-type analysis using
ngsAdmixWe 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
Rmarkdown notebookR commandsDownload 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
download the following 3 files to your working directory (use right-click “Save link as…”):
Download adder_distribution.shx
Download adder_distribution.shp
# 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)
plot() functionRmarkdown 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.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
# 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
)
# 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)
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)
angsd
output file or the ones providedRmarkdownOur 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
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
Rmarkdown notebookYou can use your own angsd output files or the ones here:
my_het <- read.table("./assets/data/adder01_het.window.sfs")
plot(1:length(my_het$V2), my_het$V2, pch = 20, cex=0.7)
my_div <- read.table("./assets/data/ang.50kb.thetas.txt")
plot(my_div$V3, my_div$V5, pch = 20, cex=0.7)
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.
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
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
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
iqtreemodule 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
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
angsd: 4 CPUs, 8Gb RAM, 10 minsExcel:
R and add to
your Rmarkdown notebook