├── .gitignore ├── examples ├── README.md ├── test.md5 └── test.sh ├── Makefile ├── scripts ├── plot2dSFS.R ├── plot2DSFS.R ├── README.md ├── samplingNCD.R ├── plotPCA.R ├── samplingSFS.R ├── plotFST.R ├── sampling2DSFS.R ├── getDxy.pl ├── calcDxy.R └── plotSS.R ├── ngs2dSFS.hpp ├── ngsStat.cpp ├── ngsCovar.hpp ├── ngs2dSFS.cpp ├── ngsStat.hpp ├── ngsFST.cpp ├── ngsFST.hpp ├── README.md ├── ngsCovar.cpp ├── shared.hpp └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | ngsFST 2 | ngsCovar 3 | ngs2dSFS 4 | ngsStat 5 | *.o 6 | examples/testA* 7 | examples/test.log 8 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | 2 | A tutorial on using ngsTools from BAM files can be found [here](https://github.com/mfumagalli/ngsTools/blob/master/TUTORIAL.md)). 3 | In most cases, it will contain all the information you need. 4 | The examples previously reported here are now deprecated. 5 | 6 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CXX ?= g++ 2 | 3 | TOOLS = ngs2dSFS ngsCovar ngsFST ngsStat 4 | 5 | CXXFLAGS := -O3 -Wall $(CXXFLAGS) 6 | LDLIBS = -lm 7 | 8 | all: $(TOOLS) 9 | 10 | $(TOOLS): %: %.cpp %.hpp shared.hpp 11 | $(CXX) $(CXXFLAGS) $(CPPFLAGS) $@.cpp $(LDFLAGS) $(LDLIBS) -o $@ 12 | 13 | test: 14 | @cd examples/; bash test.sh 2> test.log; cd ../ 15 | 16 | clean: 17 | @rm -rf $(TOOLS) *.o examples/testA* 18 | 19 | .PHONY: all clean test 20 | -------------------------------------------------------------------------------- /scripts/plot2dSFS.R: -------------------------------------------------------------------------------- 1 | 2 | # Usage: Rscript infile.spec outfile.eps pop1 pop2 3 | 4 | # Read parameters 5 | args <- commandArgs(trailingOnly = TRUE); 6 | infile <- args[1]; 7 | outfile <- args[2]; 8 | pop1 <- args[3]; 9 | pop2 <- args[4]; 10 | rm(args); 11 | 12 | # Read input file 13 | values <- as.matrix(read.table(infile, stringsAsFact=F)); 14 | n1=nrow(values)-1; 15 | n2=ncol(values)-1; 16 | 17 | # Plot 18 | pdf(outfile); 19 | image(x=seq(0,n1), y=seq(0,n2), z=-log10(values), xlab=pop1, ylab=pop2, main="Joint SFS") 20 | dev.off(); 21 | 22 | -------------------------------------------------------------------------------- /ngs2dSFS.hpp: -------------------------------------------------------------------------------- 1 | #include "shared.hpp" 2 | 3 | // comput 2d-sfs, adding each site the joint max post prob of allele frequencies 4 | void sumSpectrum(matrix &spec, matrix &m1, matrix &m2, int maxlike) { 5 | int nsites = 0; 6 | nsites = m1.x; 7 | if (maxlike==1) { // get the max like joint alle freq 8 | for (int s=0; s0 & aaf0.5)] <- 1 - aaf[which(aaf>0.5)] 50 | 51 | # NCD1 52 | ind1 <- snps 53 | ncd1 <- sqrt(mean((aaf[ind1]-tf)^2)) 54 | 55 | # NCD2 56 | ind2 <- sort(unique(snps,fd)) 57 | ncd2 <- sqrt(mean((aaf[ind2]-tf)^2)) 58 | 59 | cat(length(ind1),"\t",ncd1,"\t",length(ind2),"\t",ncd2,"\n") 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /examples/test.md5: -------------------------------------------------------------------------------- 1 | 6415c5c0ecd371f03423adcd2bf8af70 testA1.geno.gz 2 | e73e77e1f31e60a24efa10ae7d9150ca testA1.mafs.gz 3 | 18b55459de315b1b3360c3c531510869 testA1.rf.saf 4 | c9bd6b093e88ca1d3e058a6066a46f5d testA1.rf.saf.idx 5 | 2ef0db351e1c2ab28ea069af4e1c8ed3 testA1.rf.saf.pos.gz 6 | 217dbd841793795b532a0cf179f6782d testA1.saf 7 | c9bd6b093e88ca1d3e058a6066a46f5d testA1.saf.idx 8 | d803500150a8be988e35f0d9d72b2406 testA1.saf.ml 9 | 2ef0db351e1c2ab28ea069af4e1c8ed3 testA1.saf.pos.gz 10 | 7bd842ca6ccba9454bdd3d1230bb7c45 testA2.geno.gz 11 | 40532e12753061f2bccc829e0e8ae817 testA2.mafs.gz 12 | 36003ad1694b3deae82dd91a700b098a testA2.rf.saf 13 | 296e9560401bba06e57b66b8fced07f9 testA2.rf.saf.idx 14 | 2ef0db351e1c2ab28ea069af4e1c8ed3 testA2.rf.saf.pos.gz 15 | 382b583a4714ae321c41ed13cc443ae0 testA2.saf 16 | 296e9560401bba06e57b66b8fced07f9 testA2.saf.idx 17 | 9607f2ec5f82a4bf7ac1485617bfbdb2 testA2.saf.ml 18 | 2ef0db351e1c2ab28ea069af4e1c8ed3 testA2.saf.pos.gz 19 | ffff04476222b0fceb669a2f850f305b testA.covar1 20 | 517f8fc6fe8677389922930434995119 testA.covar2 21 | a98275d44976dfab3a1943d479229ded testA.covar3 22 | fe9a2245b034734dc9b3afa7f10e4369 testA.fst1 23 | e2e42e6c7de7f9d315eea7aed7f9b1bd testA.fst2 24 | efed98d852aef895699922b227abff03 testA.fst3 25 | 9a46a6e8cce8b241fe51a5f5c21b34ee testA.geno 26 | ea9aa8882271823dbe31f8947a3bf142 testA.joint.spec 27 | 4ad56bafab229c3e69bcff5c3d969119 testA.mafs.gz 28 | 325d650261660adff0c759d870d2eed8 testA.rf.saf 29 | 2f015df7d60fc930b55270407bb82924 testA.rf.saf.idx 30 | 2ef0db351e1c2ab28ea069af4e1c8ed3 testA.rf.saf.pos.gz 31 | 5799f1e3162c5c2f9e8680cf205f4953 testA.saf.gz 32 | 2f015df7d60fc930b55270407bb82924 testA.saf.idx 33 | 2f1a8eec14104cce565f056b8514e380 testA.saf.ml 34 | 2ef0db351e1c2ab28ea069af4e1c8ed3 testA.saf.pos.gz 35 | 9a15a4e873895e5ad53f7a4e144dc09f testA.stat 36 | -------------------------------------------------------------------------------- /scripts/plotPCA.R: -------------------------------------------------------------------------------- 1 | # Usage: Rscript -i infile.covar -c component1-component2 -a annotation.file -o outfile.eps 2 | 3 | library(optparse) 4 | library(ggplot2) 5 | 6 | option_list <- list(make_option(c('-i','--in_file'), action='store', type='character', default=NULL, help='Input file (output from ngsCovar)'), 7 | make_option(c('-c','--comp'), action='store', type='character', default=1-2, help='Components to plot'), 8 | make_option(c('-a','--annot_file'), action='store', type='character', default=NULL, help='Annotation file with individual classification (2 column TSV with ID and ANNOTATION)'), 9 | make_option(c('-o','--out_file'), action='store', type='character', default=NULL, help='Output file') 10 | ) 11 | opt <- parse_args(OptionParser(option_list = option_list)) 12 | 13 | # Annotation file is in plink cluster format 14 | 15 | ################################################################################# 16 | 17 | # Read input file 18 | covar <- read.table(opt$in_file, stringsAsFact=FALSE); 19 | 20 | # Read annot file 21 | annot <- read.table(opt$annot_file, sep="\t", header=TRUE); # note that plink cluster files are usually tab-separated instead 22 | 23 | # Parse components to analyze 24 | comp <- as.numeric(strsplit(opt$comp, "-", fixed=TRUE)[[1]]) 25 | 26 | # Eigenvalues 27 | eig <- eigen(covar, symm=TRUE); 28 | eig$val <- eig$val/sum(eig$val); 29 | cat(signif(eig$val, digits=3)*100,"\n"); 30 | 31 | # Plot 32 | PC <- as.data.frame(eig$vectors) 33 | colnames(PC) <- gsub("V", "PC", colnames(PC)) 34 | PC$Pop <- factor(annot$CLUSTER) 35 | 36 | title <- paste("PC",comp[1]," (",signif(eig$val[comp[1]], digits=3)*100,"%)"," / PC",comp[2]," (",signif(eig$val[comp[2]], digits=3)*100,"%)",sep="",collapse="") 37 | 38 | x_axis = paste("PC",comp[1],sep="") 39 | y_axis = paste("PC",comp[2],sep="") 40 | 41 | ggplot() + geom_point(data=PC, aes_string(x=x_axis, y=y_axis, color="Pop")) + ggtitle(title) 42 | ggsave(opt$out_file) 43 | unlink("Rplots.pdf", force=TRUE) 44 | 45 | -------------------------------------------------------------------------------- /scripts/samplingSFS.R: -------------------------------------------------------------------------------- 1 | 2 | args <- commandArgs(T) 3 | 4 | if (length(args)==0) { 5 | stop("No arguments given.\nAim: Estimate the SFS by sampling from .saf files. Fold it at the end if requested.\nUsage: Rscript fastSFS.R input.saf.idx.gz nr_chroms fold_it? plot.pdf\nInfo: Final sfs is in stdout and fold_it? is boolean (0 or 1) and nr_chroms is the number of chromosomes. This program take unfolded .saf.idx.gz data.\n") 6 | } 7 | 8 | fin <- args[1] # saf.idx file, this must be unfolded 9 | nchroms <- as.numeric(args[2]) # how many chroms 10 | tofold <- as.numeric(args[3]) # fold it at the end? 11 | fout <- args[4] # plot in pdf 12 | rm(args) 13 | 14 | # output is in stdout 15 | 16 | saf <- rep(0, nchroms+1) 17 | 18 | con <- file(fin, "r") 19 | 20 | while (TRUE) { 21 | line <- readLines(con, n=1) 22 | if (length(line)==0) { 23 | break 24 | } 25 | probs <- exp(as.numeric(strsplit(line, split="\t")[[1]][c(-1,-2)])) 26 | probs <- probs/sum(probs) # perhaps not necessary 27 | if (length(probs)==length(saf)) { 28 | sampled <- sample(x=seq(1,length(probs)), size=1, prob=probs) 29 | saf[sampled] <- saf[sampled]+1 30 | } else { 31 | break("Error! Quit!") 32 | } 33 | } 34 | 35 | close(con) 36 | 37 | fold <- function(spec) { 38 | nt <- length(spec) 39 | ns <- (length(spec)-1)/2 40 | ff <- rep(NA, ns+1) 41 | for (i in 1:(length(ff))) { 42 | ff[i] <- spec[i]+spec[nt-i+1] 43 | } 44 | ff[length(ff)] <- spec[length(ff)] 45 | #print(sum(spec)==sum(ff)) 46 | ff 47 | } 48 | 49 | # fold the final sfs if required 50 | sfs <- saf 51 | if (tofold) sfs <- fold(saf) 52 | 53 | pdf(file=fout) 54 | 55 | if (tofold) { 56 | pvar <- sfs[1]/sum(sfs) 57 | barplot(sfs[-1], names.arg=1:(length(sfs)-1), sub=paste("variability: ", pvar)) 58 | } else { 59 | pvar <- (sfs[1]+sfs[length(sfs)])/sum(sfs) 60 | barplot(sfs[2:(length(sfs)-1)], names.arg=1:(length(sfs)-2), sub=paste("variability: ", pvar)) 61 | } 62 | 63 | invisible(dev.off()) 64 | 65 | cat(sfs,"\n") 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /scripts/plotFST.R: -------------------------------------------------------------------------------- 1 | 2 | # Usage: Rscript -i infile.fst -o outfile.eps -w win -s step 3 | 4 | library(optparse) 5 | library(ggplot2) 6 | 7 | option_list <- list(make_option(c('-i','--in_file'), action='store', type='character', default=NULL, help='Input file'), 8 | make_option(c('-p','--pos_file'), action='store', type='character', default=NULL, help='Input position file'), 9 | make_option(c('-w','--window'), action='store', type='character', default=1, help='Window length'), 10 | make_option(c('-s','--step'), action='store', type='character', default=1, help='Step size'), 11 | make_option(c('-t','--th'), action='store', type='character', default=0, help='Minimu probability of being variable'), 12 | make_option(c('-o','--out_file'), action='store', type='character', default=NULL, help='Output file') 13 | ) 14 | opt <- parse_args(OptionParser(option_list = option_list)) 15 | 16 | # Read input file 17 | values <- read.table(opt$in_file, stringsAsFact=F); 18 | ind <- which(values[,5]>=as.numeric(opt$th)) 19 | pos <- as.numeric(readLines(opt$pos_file)) 20 | if (length(pos)!=nrow(values)) stop("Dimensions of fst values and positions must match. Terminate.\n"); 21 | values <- values[ind,] 22 | pos <- pos[ind] 23 | cat("After removing sites, now there are",nrow(values),"sites going from",min(pos),"to",max(pos),"\n") 24 | cat("Overall FST:",sum(values[,1])/sum(values[,2]),"\n"); 25 | 26 | # Windows 27 | len=max(pos) 28 | win=as.numeric(opt$window); 29 | step=as.numeric(opt$step); 30 | start=seq(min(pos), len, step); 31 | end=start+win-1; 32 | wpos=round(start+(win/2)); # position of the window in the plot (center) 33 | fst=c(); 34 | for (i in 1:length(start)) { 35 | ipos=which(pos>=start[i] & pos<=end[i]) 36 | fst[i]=sum(values[ipos,1])/sum(values[ipos,2]); 37 | } 38 | 39 | # Data 40 | df=data.frame(cbind(Pop=rep(1,length(wpos)), Pos=wpos, Value=fst)); 41 | df[,2:3]=sapply(df[,2:3], as.character) 42 | df[,2:3]=sapply(df[,2:3], as.numeric) 43 | write.table(df, file=paste(opt$out_file,".txt",sep="",collapse=""), sep="\t", quote=F, row.names=F, col.names=F) 44 | 45 | # Plot 46 | title = expression(F[ST]); 47 | ggplot(data=df, aes(x=Pos, y=Value)) + geom_line() + ggtitle(title); 48 | ggsave(paste(opt$out_file,".eps",sep="",collapse="")) 49 | unlink("Rplots.pdf", force=TRUE) 50 | 51 | 52 | -------------------------------------------------------------------------------- /scripts/sampling2DSFS.R: -------------------------------------------------------------------------------- 1 | 2 | print(date()) 3 | 4 | args <- commandArgs(T) 5 | 6 | if (length(args)==0) { 7 | stop("No arguments given. 8 | Aim: Estimate the 2DSFS by sampling from .saf files. 9 | Usage: Rscript fast2DSFS.R input1.saf.idx.gz input1.saf.idx.gz nr_chroms1 nr_chroms2 prob_sampling_site 10 | Info: Final sfs is in last argument, nr_chroms is the number of chromosomes, prob_sampling_site is the chance of sampling the current site for the estimation. This program take unfolded .saf.idx.gz data.\n") 11 | } 12 | 13 | fin1 <- args[1] # saf.idx file, this must be unfolded 14 | fin2 <- args[2] 15 | nchroms1 <- as.numeric(args[3]) # how many chroms 16 | nchroms2 <- as.numeric(args[4]) 17 | psam <- as.numeric(args[5]) 18 | fout <- args[6] 19 | rm(args) 20 | 21 | nl <- 1000000 22 | 23 | selpaste <- function(arr) { 24 | paste(arr[1:2], sep="", collapse=":") 25 | } 26 | 27 | expsam <- function(arr) { 28 | probs <- exp(as.numeric(arr[c(-1,-2)])) 29 | sample(x=seq(1,length(probs)), size=1, prob=probs) 30 | } 31 | 32 | # first file 33 | pos <- saf <- c() 34 | 35 | cat("Reading first file...\n") 36 | con <- file(fin1, "r") 37 | while (TRUE) { 38 | mline <- readLines(con, n=nl) 39 | if (length(mline)==0) { 40 | break 41 | } 42 | ss <- strsplit(mline, split="\t") 43 | pos <- c(pos, sapply(ss, selpaste)) 44 | saf <- c(saf, sapply(ss, expsam)) 45 | cat(pos[length(pos)],"\t") 46 | } 47 | close(con) 48 | 49 | sfs <- matrix(0, nrow=(nchroms1+1), ncol=(nchroms2+1)) 50 | 51 | # second file 52 | cat("\nReading second file...\n") 53 | con <- file(fin2, "r") 54 | while (TRUE) { 55 | mline <- readLines(con, n=nl) 56 | if (length(mline)==0) { 57 | break 58 | } 59 | ss <- strsplit(mline, split="\t") 60 | pos2 <- sapply(ss, selpaste) 61 | 62 | ind <- match(pos2, pos) 63 | 64 | take <- (!is.na(ind))*(sample(c(0,1),length(pos2),T,c(1-psam,psam))) 65 | 66 | saf2 <- sapply(ss, expsam)[which(take==1)] 67 | 68 | saf1 <- saf[ind[which(take==1)]] 69 | 70 | for (j in 1:length(saf1)) sfs[saf1[j], saf2[j]] <- sfs[saf1[j], saf2[j]] + 1 71 | 72 | cat(pos2[length(pos2)], "\t") 73 | 74 | } 75 | close(con) 76 | 77 | final <- array(t(sfs)) 78 | 79 | cat("\nTotal sites:", sum(final)) 80 | cat("\nProportion (on pop1):", sum(final)/length(pos)) 81 | 82 | cat("\nNon-normalised SFS:\n") 83 | cat(final) 84 | 85 | final <- final/sum(final) 86 | cat("\nNormalised SFS:\n") 87 | cat(final) 88 | 89 | cat(final, file=fout) 90 | 91 | cat("\n") 92 | print(date()) 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /scripts/getDxy.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | #use strict; 4 | use warnings; 5 | use Getopt::Long; 6 | 7 | my $pop1maf; 8 | my $pop2maf; 9 | my $minInd; 10 | 11 | &GetOptions( 'pop1maf=s' => \$pop1maf, 12 | 'pop2maf=s' => \$pop2maf, 13 | 'minInd=i' => \$minInd, 14 | ); 15 | 16 | my $usage = <<_EOUSAGE_; 17 | ######################################################################################### 18 | #this script updates 19 | # getDxy.pl --pop1maf --pop2maf --nInd 20 | # Required: 21 | # --pop1maf a text maf file output from ANGSD with apporpriate filtering for Population 1 22 | # --pop2maf a text maf file output from ANGSD with apporpriate filtering for Population 2 23 | # --minInd minimum number of individuals required per population 24 | # 25 | #This script assumes equal and corresponding lines in the two maf files. User needs to filter for variable sites using the SNP pval before running this script. 26 | # 27 | # 28 | #Following columns need to be present: 29 | # 30 | #chromo position major minor ref knownEM unknownEM nInd 31 | # 32 | # 33 | #Dxy is reported only for the sites included in the MAF file. While calculating the value per window, the correct number of sites has to be used. 34 | # 35 | #Example command to run the script 36 | #perl getDxy.pl --pop1maf pop1.pop1_pop2.genotypes.mafs.txt --pop2maf pop2.pop1_pop2.genotypes.mafs.txt --minInd 5 37 | ########################################################################################### 38 | _EOUSAGE_ 39 | 40 | ; 41 | 42 | if (! defined $pop1maf) {print $usage;exit;} 43 | if (! defined $pop2maf) {print $usage;exit;} 44 | if (! defined $minInd) {print $usage;exit;} 45 | 46 | open POP1MAF, $pop1maf or die $!; 47 | open POP2MAF, $pop2maf or die $!; 48 | 49 | my $line1; 50 | my $line2; 51 | 52 | my $dxy=0; 53 | #read in the header and do nothing 54 | my $header1=;my $header2=; 55 | 56 | print "chromo\tposition\tDxy\n"; 57 | 58 | while($line1=){ 59 | #read in maf from pop1 60 | chomp $line1;my @parts=split('\t',$line1); 61 | 62 | #read in maf from pop2 63 | $line2=;chomp $line2;my @parts2=split('\t',$line2); 64 | 65 | if(($parts[7]>=$minInd)&&($parts2[7]>=$minInd)){#use only sites that are covered by at least $minInd individuals in each population, in v2 updated the position of the nIND column in MAF file 66 | 67 | #if($parts3[4]>0.99999999){#use only sites with pvar >0.99999999, same as criteria used for fst 68 | 69 | if(($parts[2]=~/$parts2[2]/)&&($parts[3]=~/$parts2[3]/)){#check if the major and minor allele are matching 70 | 71 | $dxy=$parts[5]*(1-$parts2[5])+($parts2[5]*(1-$parts[5])); # 72 | 73 | print "$parts[0]\t$parts[1]\t$dxy\n"; # print scaffold, position and per site dxy 74 | 75 | } 76 | 77 | if(($parts[2]=~/$parts2[3]/)&&($parts[3]=~/$parts2[2]/)){#check if the major and minor allele are NOT matching 78 | 79 | $dxy=($parts[5]*$parts2[5])+((1-$parts2[5])*(1-$parts[5])); 80 | 81 | print "$parts[0]\t$parts[1]\t$dxy\n";# print scaffold, position and per site dxy 82 | 83 | } 84 | }} 85 | close POP1MAF; 86 | close POP2MAF; 87 | -------------------------------------------------------------------------------- /scripts/calcDxy.R: -------------------------------------------------------------------------------- 1 | ######################################### 2 | # # 3 | # Calculates Dxy from mafs files # 4 | # # 5 | # Author: Joshua Penalba # 6 | # Date: 22 Oct 2016 # 7 | # # 8 | ######################################### 9 | 10 | 11 | # NOTES 12 | # * Prior to calculating Dxy the following steps are recommended: 13 | # 1. Run ANGSD with all populations with a -SNP_pval and -skipTriallelic flags. 14 | # 2. Rerun ANGSD per population 15 | # Use the -sites flag with a file corresponding to the recovered SNPs. 16 | # This will guarantee that sites with an allele fixed in one population is still included. 17 | # Remove the -SNP_pval flag. 18 | # IMPORTANT: Include an outgroup reference to polarize alleles. 19 | # 3. Gunzip the resulting mafs files. 20 | # 21 | # * Make sure the totLen only includes the chromosomes being analyzed. 22 | # * minInd flag not added, assuming already considered in the ANGSD run. 23 | # * Test for matching major and minor alleles not included as it would filter out sequencing errors. 24 | # This has been accounted for in the allele frequency calculations. 25 | # This filter may give an underestimate of dxy. 26 | # * Per site Dxy of ~0 could be common if the alternate alleles are present in a population other than the two being included in the calculation. 27 | 28 | 29 | ### Creating an argument parser 30 | library("optparse") 31 | 32 | option_list = list( 33 | make_option(c("-p","--popA"), type="character",default=NULL,help="path to unzipped mafs file for pop 1",metavar="character"), 34 | make_option(c("-q","--popB"), type="character",default=NULL,help="path to unzipped mafs file for pop 2",metavar="character"), 35 | make_option(c("-t","--totLen"), type="numeric",default=NULL,help="total sequence length for global per site Dxy estimate [optional]",metavar="numeric") 36 | ) 37 | opt_parser = OptionParser(option_list=option_list) 38 | opt = parse_args(opt_parser) 39 | 40 | ### Troubleshooting input 41 | if(is.null(opt$popA) | is.null(opt$popB)){ 42 | print_help(opt_parser) 43 | stop("One or more of the mafs paths are missing", call.=FALSE) 44 | } 45 | 46 | if(grepl('.gz$',opt$popA) | grepl('.gz$',opt$popB)){ 47 | print_help(opt_parser) 48 | stop("One or more of the mafs is gzipped.", call.=FALSE) 49 | } 50 | 51 | if(is.null(opt$totLen)){ 52 | print("Total length not supplied. The output will not be a per site estimate.") 53 | } 54 | 55 | ### Reading data in 56 | allfreqA <- read.table(opt$popA,sep='\t',row.names=NULL, header=T) 57 | allfreqB <- read.table(opt$popB,sep='\t',row.names=NULL, header=T) 58 | 59 | ### Manipulating the table and print dxy table 60 | allfreq <- merge(allfreqA, allfreqB, by=c("chromo","position")) 61 | allfreq <- allfreq[order(allfreq$chromo, allfreq$position),] 62 | # -> Actual dxy calculation 63 | allfreq <- transform(allfreq, dxy=(knownEM.x*(1-knownEM.y))+(knownEM.y*(1-knownEM.x))) 64 | write.table(allfreq[,c("chromo","position","dxy")], file="Dxy_persite.txt",quote=FALSE, row.names=FALSE, sep='\t') 65 | print('Created Dxy_persite.txt') 66 | 67 | ### Print global dxy 68 | print(paste0('Global dxy is: ',sum(allfreq$dxy))) 69 | if(!is.null(opt$totLen)){ 70 | print(paste0('Global per site Dxy is: ',sum(allfreq$dxy)/opt$totLen)) 71 | } 72 | 73 | 74 | -------------------------------------------------------------------------------- /examples/test.sh: -------------------------------------------------------------------------------- 1 | SCRIPTS=../scripts 2 | SIM_DATA=../../ngsSim/examples 3 | ANGSD=../../angsd 4 | 5 | 6 | 7 | ##### Clean-up 8 | rm -f testA* 9 | touch -d 'next minute' $SIM_DATA/testAF.ANC.fas.fai 10 | 11 | 12 | ##### Genotypes' and sample allele frequencies' posterior probabilities 13 | $ANGSD/angsd -glf $SIM_DATA/testA.glf.gz -fai $SIM_DATA/testAF.ANC.fas.fai -nInd 24 -doMajorMinor 1 -doMaf 1 -doPost 1 -doGeno 32 -doSaf 1 -anc $SIM_DATA/testAF.ANC.fas -out testA 14 | $ANGSD/misc/realSFS testA.saf.idx -seed 12345 > testA.saf.ml 15 | $ANGSD/angsd -glf $SIM_DATA/testA.glf.gz -fai $SIM_DATA/testAF.ANC.fas.fai -nInd 24 -doSaf 1 -anc $SIM_DATA/testAF.ANC.fas -pest testA.saf.ml -out testA.rf 16 | 17 | # Estimated and true pooled site frequency spectrum 18 | #Rscript --vanilla --slave -e 'barplot(rbind(as.numeric(scan("../../ngsSim/examples/testA.frq", what="char")), exp(as.numeric(scan("testA.saf.ml", what="char")))), beside=T, legend=c("True","Estimated"))' 19 | 20 | 21 | 22 | 23 | 24 | ##### PCA 25 | # Get covariance matrix 26 | gunzip -f testA.geno.gz testA.rf.saf.gz 27 | ../ngsCovar -probfile testA.geno -outfile testA.covar1 -nind 24 -nsites 10000 -call 0 -sfsfile testA.rf.saf -norm 0 28 | ../ngsCovar -probfile testA.geno -outfile testA.covar2 -nind 24 -nsites 10000 -call 0 -minmaf 0.05 29 | ../ngsCovar -probfile testA.geno -outfile testA.covar3 -nind 24 -nsites 10000 -call 1 -minmaf 0.05 30 | 31 | # Plot results 32 | #Rscript --vanilla --slave -e 'write.table(cbind(seq(1,24),rep(1,24),c(rep("A",10),rep("B",8),rep("C",6))), row.names=F, sep="\t", col.names=c("FID","IID","CLUSTER"), file="testA.clst", quote=F)' 33 | #Rscript --vanilla --slave $SCRIPTS/plotPCA.R -i testA.covar1 -c 1-2 -a testA.clst -o testA.pca.SAF.pdf 34 | #Rscript --vanilla --slave $SCRIPTS/plotPCA.R -i testA.covar2 -c 1-2 -a testA.clst -o testA.pca.MAF.pdf 35 | #Rscript --vanilla --slave $SCRIPTS/plotPCA.R -i testA.covar3 -c 1-2 -a testA.clst -o testA.pca.MAFcall.pdf 36 | 37 | 38 | 39 | 40 | 41 | ##### Statistics 42 | # Pop 1 43 | $ANGSD/angsd -glf $SIM_DATA/testA1.glf.gz -fai $SIM_DATA/testAF.ANC.fas.fai -nInd 10 -doMajorMinor 1 -doMaf 1 -doPost 1 -doGeno 32 -doSaf 1 -anc $SIM_DATA/testAF.ANC.fas -out testA1 44 | $ANGSD/misc/realSFS testA1.saf.idx -seed 12345 > testA1.saf.ml 45 | $ANGSD/angsd -glf $SIM_DATA/testA1.glf.gz -fai $SIM_DATA/testAF.ANC.fas.fai -nInd 10 -doSaf 1 -anc $SIM_DATA/testAF.ANC.fas -pest testA1.saf.ml -out testA1.rf 46 | # Pop 2 47 | $ANGSD/angsd -glf $SIM_DATA/testA2.glf.gz -fai $SIM_DATA/testAF.ANC.fas.fai -nInd 8 -doMajorMinor 1 -doMaf 1 -doPost 1 -doGeno 32 -doSaf 1 -anc $SIM_DATA/testAF.ANC.fas -out testA2 48 | $ANGSD/misc/realSFS testA2.saf.idx -seed 12345 > testA2.saf.ml 49 | $ANGSD/angsd -glf $SIM_DATA/testA2.glf.gz -fai $SIM_DATA/testAF.ANC.fas.fai -nInd 8 -doSaf 1 -anc $SIM_DATA/testAF.ANC.fas -pest testA2.saf.ml -out testA2.rf 50 | 51 | # Get stats 52 | gunzip -f testA1.rf.saf.gz testA2.rf.saf.gz 53 | ../ngsStat -npop 2 -postfiles testA1.rf.saf testA2.rf.saf -nsites 10000 -iswin 1 -nind 10 8 -outfile testA.stat -block_size 100 54 | 55 | # Plot results 56 | #Rscript --vanilla --slave $SCRIPTS/plotSS.R -i testA.stat -o testA.stat.pdf -n pop1-pop2 57 | #Rscript --vanilla --slave $SCRIPTS/plotSS.R -i testA.stat -o testA.stat.pop1.pdf -n pop1 58 | 59 | 60 | 61 | 62 | 63 | ##### Fst 64 | # 2D-SFS 65 | ../ngs2dSFS -postfiles testA1.rf.saf testA2.rf.saf -outfile testA.joint.spec -relative 1 -nind 10 8 -nsites 10000 -maxlike 1 66 | #Rscript --vanilla --slave $SCRIPTS/plot2dSFS.R testA.joint.spec testA.joint.spec.pdf pop1 pop2 67 | 68 | # Estimate Fst 69 | gunzip -f testA1.saf.gz testA2.saf.gz 70 | ../ngsFST -postfiles testA1.saf testA2.saf -priorfile testA.joint.spec -nind 10 8 -nsites 10000 -outfile testA.fst1 71 | ../ngsFST -postfiles testA1.saf testA2.saf -priorfiles testA1.saf.ml testA2.saf.ml -nind 10 8 -nsites 10000 -outfile testA.fst2 72 | ../ngsFST -postfiles testA1.rf.saf testA2.rf.saf -nind 10 8 -nsites 10000 -outfile testA.fst3 73 | 74 | # Plot 75 | #Rscript --vanilla --slave $SCRIPTS/plotFST.R -i testA.fst -o testA.fst.pdf -w 100 -s 50 76 | 77 | 78 | 79 | 80 | 81 | ##### Check MD5 82 | rm -f *.arg 83 | TMP=`mktemp --suffix .ngsPopGen` 84 | md5sum testA* | sort -k 2,2 > $TMP 85 | if diff $TMP test.md5 > /dev/null 86 | then 87 | echo "ngsPopGen: All tests OK!" 88 | else 89 | echo "ngsPopGen: test(s) failed!" 90 | fi 91 | -------------------------------------------------------------------------------- /ngsStat.cpp: -------------------------------------------------------------------------------- 1 | 2 | // this program receives as input the .sfs files from realSFS and sfstools and outputs several statistics for each window: expected number of segregating sites, expected average heterozygosity, expected number of fixed differendes (if 2 pops are provided) 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "ngsStat.hpp" 11 | 12 | // to compile: g++ -Wall -O0 -g ngsStat.cpp -o ngsStat 13 | 14 | int main (int argc, char *argv[]) { 15 | 16 | if (argc==1) { 17 | info(); 18 | return 0; 19 | } 20 | 21 | /// DECLARE AND INITIALIZE VARIABLES 22 | 23 | char *sfsfile1=NULL; // posterior probabilities or sample allele frequency likelihoods 24 | char *sfsfile2=NULL; 25 | 26 | FILE *outpost; 27 | char *outfile=NULL; 28 | char *foutpost=NULL; 29 | 30 | int argPos = 1, increment = 0, npop = 1, nind1 = 0, nind2 = 0, nsites = 0, verbose = 0, block_size = 20000, firstbase=1, iswin = 0; 31 | 32 | // if iswin==1 then block_size is the window size and print the valeus for each window 33 | // if iswin==0 then block_size is just for efficiency and print values for each site 34 | 35 | /// READ AND ASSIGN INPUT PARAMETERS 36 | 37 | while (argPosDumping file: %s\n", foutpost); 83 | outpost = getFILE(foutpost, "w"); 84 | 85 | /// GET POSITIONS OF BLOCKS 86 | // if block_size longer than nsites 87 | if (block_size>(nsites-firstbase+1)) block_size=(nsites-firstbase+1); 88 | if (block_size==0) block_size=nsites-firstbase+1; 89 | 90 | array start; array end; 91 | start=getStart(nsites, firstbase, block_size); 92 | end=getEnd(nsites, firstbase, block_size); 93 | int nwin= (nsites-firstbase+1)/block_size; 94 | if ( ( (nsites-firstbase+1) % block_size)>0) nwin=nwin+1; 95 | if (verbose==1) fprintf(stderr, "\nLen %d and win %d and rest is %d", (nsites-firstbase+1), block_size, ( (nsites-firstbase+1) % block_size)); 96 | 97 | if (verbose==1) fprintf(stderr, "\nNum of win %d and win[0] is %d %d\n", nwin, start.data[0], end.data[0]); 98 | 99 | /// ITERATE OVER EACH BLOCK 100 | for (int n=0; n post1; 106 | matrix post2; 107 | post1 = readFileSub(sfsfile1, nind1, start.data[n], end.data[n]); 108 | if (npop==2) { 109 | post2 = readFileSub(sfsfile2, nind2, start.data[n], end.data[n]); 110 | } 111 | 112 | // NORM from LOG 113 | normSFS(post1, true); 114 | if(npop==2) normSFS(post2, true); 115 | 116 | if (npop==1) computeStats(post1, verbose, outpost, iswin, start.data[n]); 117 | if (npop==2) computeStats2Pops(post1, verbose, outpost, iswin, start.data[n], post2); 118 | 119 | cleanup(post1); 120 | if (npop==2) cleanup(post2); 121 | 122 | } // end for n 123 | 124 | delete [] start.data; 125 | delete [] end.data; 126 | 127 | fclose(outpost); 128 | free(foutpost); 129 | 130 | return 0; 131 | 132 | 133 | } // end main 134 | -------------------------------------------------------------------------------- /ngsCovar.hpp: -------------------------------------------------------------------------------- 1 | 2 | #include "shared.hpp" 3 | 4 | // print help 5 | void info() { 6 | fprintf(stdout, "\nInput:\n-probfile: file with genotype posterior probabilities [required]\n-outfile: name of output file [required], currently it is a text file, tab separated with n*n cells\n-sfsfile: file with SFS posterior probabilities [required if you want to weight each site by its probability of being variable]\n-nind: nr of individuals [required]\n-nsites: nr of sites [required]\n-norm: if 0 no normalization, if 1 matrix is normalized by (p(1-p)) as in Patterson et al 2006, if 2 normalization is 2p(1-p) [0]\n-verbose: level of verbosity [0]\n-block_size: how many sites per block when reading the input file [0]\n-call: whether calling genotypes (1) or not (0) [0]\n-offset: starting position of subset analysis [1]\n-minmaf: filter out sites with estimated MAF less than minmaf or greater than 1-minmaf [0] (this filtering will be ignored when using the weighting approach\n-genoquality: text file with nsites lines; each line has a 0 and 1; if 0 the program will ignore this site [NULL]\n\n"); 7 | } 8 | 9 | // compute estimated allele frequencies from genotype posterior probabilities 10 | array getAlleFreq (matrix &m) { 11 | // m is dimensions: nsites * (nind*3) 12 | int nsites = m.x; 13 | int nind = m.y/3; 14 | double somma; 15 | double *tmp = new double[nsites]; 16 | for (int i=0; i ret; 24 | ret.x = nsites; 25 | ret.data = tmp; 26 | return ret; 27 | } 28 | 29 | // get the covariance for a pair of individual; output is the effective number of sites (expected or passed the filter) 30 | double calcCovarUp (matrix &m, array a, matrix &covar, double minmaf, array good, int start, int norm) { 31 | int nsites = m.x; 32 | int nind = m.y/3; 33 | if (nsites != a.x) { 34 | fprintf(stderr, "\n prob file and alle freq dimensions disagree. Terminate."); 35 | exit(-1); 36 | } 37 | double eff_nsites=0.0; 38 | for (int s=0; sminmaf) & (a.data[s]<(1-minmaf))) { 40 | eff_nsites=eff_nsites+1.0; 41 | } 42 | } 43 | double somma = 0.0, subsomma = 0.0; 44 | double **data = new double*[nind]; 45 | for (int i=0; iminmaf) & (a.data[s]<(1-minmaf))) { 52 | for (int C1=0; C1<3; C1++) { 53 | for (int C2=0; C2<3; C2++) { 54 | subsomma = subsomma + (C1-(2*a.data[s]))*(C2-(2*a.data[s]))*m.data[s][(i*3)+C1]*m.data[s][(j*3)+C2]; 55 | } 56 | } 57 | subsomma = subsomma * good.data[start+s]; 58 | if (norm==1) subsomma = subsomma / ((a.data[s]*(1-a.data[s]))); 59 | if (norm==2) subsomma = subsomma / (2*(a.data[s]*(1-a.data[s]))); 60 | } 61 | if (isnan(subsomma)==0) somma = somma + subsomma; 62 | } 63 | tmp[j] = somma; 64 | } 65 | data[i] = tmp; 66 | } 67 | fprintf(stderr, "Message (not error/warning): for this window nsites is %d and effective is %f\n", nsites, eff_nsites); 68 | matrix ret; 69 | ret.x = nind; 70 | ret.y = nind; 71 | ret.data = data; 72 | for (int i=0;i &m, array a, matrix &covar, array pvar, array good, int start, int norm) { 85 | int nsites = m.x; 86 | int nind = m.y/3; 87 | if (nsites != a.x) { 88 | fprintf(stderr, "\n prob file and alle freq dimensions disagree. Terminate."); 89 | exit(-1); 90 | } 91 | double somma = 0.0, subsomma = 0.0; 92 | double **data = new double*[nind]; 93 | for (int i=0; i ret; 114 | ret.x = nind; 115 | ret.y = nind; 116 | ret.data = data; 117 | for (int i=0;i //for stderr,stdout 5 | #include //for atoi 6 | #include //for getting file attributes 7 | #include //for str operations 8 | #include 9 | #include // for exponential and log 10 | #include "ngs2dSFS.hpp" // include templates, functions 11 | 12 | // input is the output of sfstools 13 | 14 | // to compile: g++ -Wall -O0 -g ngs2dSFS.cpp -o ngs2dSFS 15 | 16 | int main (int argc, char *argv[]) { 17 | 18 | if (argc==1) { 19 | fprintf(stdout, "\nInput:\n-postfiles: file with sample allele frequency posterior probabilities for each population\n-outfile: name of output file\n-nind: number of individuals per population\n -nsites: number of sites, or upper limit in case of analyzing a subset\n-block_size: memory efficiency, number of sites for each chunk\n-offset: lower limit in case of analyzing a subset\n-maxlike: if 1 compute the most likely joint allele frequency and sum across sites, if 0 it computes the sum of the products of likelihoods\n-relative: boolean, if 1 number are relative frequencies from 0 to 1 which sum up 1; if 0 numbers are absolute counts of sites having a specific joint allele frequency\n-offset: lower limit of sites in case you want to analyze a subset\n\n"); 20 | return 0; 21 | } 22 | 23 | /// DECLARE AND INITIALIZE VARIABLES 24 | 25 | char *sfsfile1=NULL; 26 | char *sfsfile2=NULL; 27 | 28 | FILE *outpost; 29 | char *outfile=NULL; 30 | char *foutpost=NULL; 31 | 32 | int argPos = 1; 33 | int increment = 0; 34 | int nind1 = 0, nind2 = 0, nsites = 0; 35 | int block_size = 10000; 36 | int firstbase = 1; 37 | int relative = 1; 38 | int maxlike=1; 39 | 40 | // READ AND ASSIGN INPUT PARAMETERS 41 | 42 | while (argPos spec; 86 | spec.x=(2*nind1)+1; 87 | spec.y=(2*nind2)+1; 88 | 89 | double **data = new double*[spec.x]; 90 | for (int i=0; i(nsites-firstbase+1)) block_size=(nsites-firstbase+1); 105 | if (block_size==0) block_size=nsites-firstbase+1; 106 | array start; array end; 107 | start=getStart(nsites, firstbase, block_size); 108 | end=getEnd(nsites, firstbase, block_size); 109 | int nwin= (nsites-firstbase+1)/block_size; 110 | if ( ( (nsites-firstbase+1) % block_size)!=0) nwin++; 111 | 112 | matrix post1; 113 | matrix post2; 114 | 115 | // for each block 116 | for (int n=0; n=start[i] & pos<=end[i]) 94 | sub[i,]=apply(MAR=2, X=values[ipos,3:(ncol(values))], FUN=sum, na.rm=T) 95 | } 96 | 97 | values=sub 98 | pos=wpos 99 | 100 | # Plot 101 | 102 | if (npop==2) { 103 | title <- ""; 104 | 105 | # Data 106 | df = data.frame(cbind( Pop=c(rep(pops[1],length(pos)),rep(pops[2],length(pos))), Pos=pos, Segr.sites=c(values[,1], values[,3]), Exp.heterozygosity=c(values[,2],values[,4]), Fixed.differences=(rep(values[,5],2)), Dxy=(rep(values[,6],2)), Pops=c(rep(paste(pops[1],"\n",pops[2]),length(pos)*2)) ) ); 107 | df[,2:5] = sapply(df[,2:5], as.character) 108 | df[,2:5] = sapply(df[,2:5], as.numeric) 109 | 110 | p1 = ggplot(data=df, aes(x=Pos, y=Segr.sites, color=Pop)) + geom_line() + ggtitle(title) 111 | p2 = ggplot(data=df, aes(x=Pos, y=Exp.heterozygosity, color=Pop)) + geom_line() + ggtitle(title) 112 | p3 = ggplot(data=df, aes(x=Pos, y=Fixed.differences, color=Pops)) + geom_line() + ggtitle(title) 113 | p4 = ggplot(data=df, aes(x=Pos, y=Dxy, color=Pops)) + geom_line() + ggtitle(title) 114 | 115 | pdf(paste(opt$out_file,".eps",sep="",collapse="")); 116 | multiplot(p1, p2, p3, p4, ncol=2) 117 | null <- dev.off(); 118 | 119 | df=df[,2:6] 120 | 121 | } 122 | 123 | if (npop==1) { 124 | df = data.frame(cbind( Pop=rep(pops[1],length(pos)), Pos=pos, Segr.sites=values[,1], Exp.heterozygosity=values[,2])); 125 | df[,2:4] = sapply(df[,2:4], as.character) 126 | df[,2:4] = sapply(df[,2:4], as.numeric) 127 | 128 | title <- ""; 129 | 130 | p1 = ggplot(data=df, aes(x=Pos, y=Segr.sites, color=Pop)) + geom_line() + ggtitle(title) 131 | p2 = ggplot(data=df, aes(x=Pos, y=Exp.heterozygosity, color=Pop)) + geom_line() + ggtitle(title) 132 | 133 | pdf(paste(opt$out_file,".eps",sep="",collapse="")); 134 | multiplot(p1, p2, ncol=1) 135 | null <- dev.off(); 136 | 137 | df=df[,2:4] 138 | } 139 | 140 | write.table(df, file=paste(opt$out_file,".txt",sep="",collapse=""), sep="\t", quote=F, row.names=F, col.names=T) 141 | 142 | -------------------------------------------------------------------------------- /ngsStat.hpp: -------------------------------------------------------------------------------- 1 | #include "shared.hpp" 2 | 3 | // print help 4 | void info() { 5 | fprintf(stdout, "\nInput:\n-npop: how many pops (1 or 2)\n-postfiles: .sfs files with posterior probabilities of sample allele frequencies for each population (with or without running sfstools)\n-outfile: name of the output file\n-nind: number of individuals for each population\n-nsites: total number of sites; in case you want to analyze a subset of sites this is the upper limit\n-verbose: level of verbosity, if 0 suppress all messages\n-block_size: to be memory efficient, set this number as the number of sites you want to analyze at each chunk\n-firstbase: in case you want to analyze a subset of your sites this is the lower limit\n-iswin: if 1 then print the value computed for each non-overlapping window defined by block_size\n\n"); 6 | } 7 | 8 | 9 | // compute summary stats for each block in case of 1 pop and print the results 10 | void computeStats(matrix &post1, int verbose, FILE *outpost, int iswin, int start) { 11 | 12 | int nind = (post1.y-1)/2; // sample size 13 | int nsites = post1.x; 14 | 15 | // init 16 | array segsites; 17 | segsites.x=nsites; 18 | double *tmp1 = new double [nsites]; 19 | for (int i=0; i hetero; 25 | hetero.x=nsites; 26 | double *tmp2 = new double [nsites]; 27 | for (int i=0; i &post1, int verbose, FILE *outpost, int iswin, int start, matrix &post2) { 71 | // sample sizes 72 | int nind1 = (post1.y-1)/2; 73 | int nind2 = (post2.y-1)/2; 74 | int nsites=post1.x; 75 | 76 | // init 77 | array segsites1; 78 | segsites1.x=nsites; 79 | array hetero1; 80 | hetero1.x=nsites; 81 | array segsites2; 82 | segsites2.x=nsites; 83 | array hetero2; 84 | hetero2.x=nsites; 85 | array fixed; 86 | fixed.x=nsites; 87 | array dxy; 88 | dxy.x=nsites; 89 | 90 | double *tmp1= new double [nsites]; 91 | for (int i=0; i 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include "ngsFST.hpp" 14 | 15 | // to compile: g++ ngsFST.cpp -Wall -o bin/ngsFST -lm -lz -O0 -g 16 | 17 | int main (int argc, char *argv[]) { 18 | 19 | if (argc==1) { 20 | info(); 21 | return 0; 22 | } 23 | 24 | /// DECLARE AND INITIALIZE VARIABLES 25 | 26 | char *sfsfile1=NULL; // posterior probabilities or sample allele frequency likelihoods 27 | char *sfsfile2=NULL; 28 | char *priorfile1=NULL; // marginal priors 29 | char *priorfile2=NULL; 30 | char *priorfile12=NULL; // joint prior, it is 2D-SFS 31 | 32 | FILE *outpost; 33 | char *outfile=NULL; 34 | char *foutpost=NULL; 35 | 36 | int argPos = 1, increment = 0, nind = 0, nind1 = 0, nind2 = 0, nsites = 0, verbose = 0, nsums = 1, block_size = 20000, firstbase=1; 37 | 38 | /// READ AND ASSIGN INPUT PARAMETERS 39 | 40 | while (argPosDumping file: %s\n", foutpost); 93 | outpost = getFILE(foutpost, "w"); 94 | 95 | // print input arguments 96 | if(verbose==1) fprintf(stderr,"\t->Using some of these args: -nind %d -nind1 %d -nind2 %d -nsites %d -postfiles %s %s -priorfiles %s %s -priorfile %s -outfile %s -verbose %d -firstbase %d -block_size %d\n", nind, nind1, nind2, nsites, sfsfile1, sfsfile2, priorfile1, priorfile2, priorfile12, foutpost, verbose, firstbase, block_size); 97 | 98 | // READ PRIORS (if provided) 99 | // marginal spectra 100 | array prior1; 101 | array prior2; 102 | if (priorfile1 != NULL) { 103 | if (verbose==1) fprintf(stderr, "\nReading priors..."); 104 | prior1 = readArray(priorfile1, nind1); 105 | prior2 = readArray(priorfile2, nind2); 106 | } 107 | // 2D-SFS 108 | matrix prior12; 109 | if ((priorfile12==NULL)==0) { 110 | if (verbose==1) fprintf(stderr, "\nReading 2D prior..."); 111 | prior12 = readPrior12(priorfile12, nind1*2+1, nind2*2+1); 112 | if (verbose==2) { 113 | fprintf(stderr, "\nPrior 2d:\n"); 114 | writematrix(prior12, stderr); 115 | } 116 | //// the difference with this prior is that I don't add the prior, but I add the prior directly at computeFST step 117 | } 118 | 119 | /// GET POSITIONS OF BLOCKS 120 | if (block_size>(nsites-firstbase+1)) block_size=(nsites-firstbase+1); 121 | if (block_size==0) block_size=nsites-firstbase+1; 122 | array start; array end; 123 | start=getStart(nsites, firstbase, block_size); 124 | end=getEnd(nsites, firstbase, block_size); 125 | int nwin= (nsites-firstbase+1)/block_size; 126 | if ( ( (nsites-firstbase+1) % block_size)!=0) nwin++; 127 | 128 | if (verbose==1) fprintf(stderr, "\n num win %d win0 is %d %d\n", nwin, start.data[0], end.data[0]); 129 | 130 | /// ITERATE OVER EACH BLOCK 131 | for (int n=0; n post1; 137 | matrix post2; 138 | post1 = readFileSub(sfsfile1, nind1, start.data[n], end.data[n]); 139 | post2 = readFileSub(sfsfile2, nind2, start.data[n], end.data[n]); 140 | 141 | // print first post probs 142 | if (verbose==1) { 143 | fprintf(stderr, "initial post probs 1: %f %f %f\n", post1.data[0][0], post1.data[0][1], post1.data[0][nind1]); 144 | fprintf(stderr, "initial post probs 2: %f %f %f\n", post2.data[0][0], post2.data[0][1], post2.data[0][nind2]); 145 | } 146 | 147 | // NORM from LOG 148 | normSFS(post1, 1); 149 | normSFS(post2, 1); 150 | 151 | if (verbose==1) { 152 | fprintf(stderr, "mid post probs 1: %f %f %f\n", post1.data[0][0], post1.data[0][1], post1.data[0][nind1]); 153 | fprintf(stderr, "mid post probs 2: %f %f %f\n", post2.data[0][0], post2.data[0][1], post2.data[0][nind2]); 154 | } 155 | 156 | // ADD PRIOR is marginal priors 157 | if (priorfile1!=NULL) { 158 | addPrior(post1, prior1); 159 | addPrior(post2, prior2); 160 | normSFS(post1, 0); 161 | normSFS(post2, 0); 162 | } 163 | 164 | // print first post probs 165 | if (verbose==1) { 166 | fprintf(stderr, "final post probs 1: %f %f %f\n", post1.data[0][0], post1.data[0][1], post1.data[0][nind1]); 167 | fprintf(stderr, "final post probs 2: %f %f %f\n", post2.data[0][0], post2.data[0][1], post2.data[0][nind2]); 168 | } 169 | 170 | // CALCULATE FST 171 | if (verbose==1) fprintf(stderr,"Computing FST.\n"); 172 | if (priorfile12==NULL) { 173 | computeVarRey(post1, post2, verbose, outpost, nsums); 174 | } else { 175 | if (verbose==1) fprintf(stderr,"Using 2D-SFS as prior.\n"); 176 | computeVarRey12(post1, post2, verbose, outpost, nsums, prior12); 177 | } 178 | 179 | cleanup(post1); 180 | cleanup(post2); 181 | 182 | } // end blocks iterations 183 | 184 | delete [] start.data; 185 | delete [] end.data; 186 | 187 | if (priorfile12!=NULL) cleanup(prior12); 188 | 189 | if (priorfile1!=NULL) delete [] prior1.data; 190 | if (priorfile2!=NULL) delete [] prior2.data; 191 | 192 | fclose(outpost); 193 | free(foutpost); 194 | 195 | return 0; 196 | 197 | } // end main 198 | 199 | 200 | 201 | 202 | 203 | -------------------------------------------------------------------------------- /ngsFST.hpp: -------------------------------------------------------------------------------- 1 | 2 | #include "shared.hpp" 3 | 4 | // print help 5 | void info() { 6 | fprintf(stdout, "\nInput:\n-postfiles: .sfs files with posterior probabilities of sample allele frequencies for each population [required]\n-priorfile: 2D-SFS to be used as a prior; you can use ngs2DSFS with parameter -relative set to 1 [NULL]\n-priorfiles: marginal spectra to be used as a prior; you can use optimSFS in ANGSD [NULL]\n-outfile: name of the output file [required]\n-nind: number of individuals for each population [required]\n-nsites: total number of sites; in case you want to analyze a subset of sites this is the upper limit [required]\n-verbose: level of verbosity [0]\n-block_size: to be memory efficient, set this number as the number of sites you want to analyze at each chunk [0]\n-firstbase: in case you want to analyze a subset of your sites this is the lower limit [1]\n\n"); 7 | } 8 | 9 | /// 10 | 11 | // compute a and ab (using short-cut formulas) given allele frequencies and sample sizes 12 | array calcAB(int s1, int s2, int n1, int n2, int debug) { 13 | if (debug) fprintf(stderr, "\nInside calcAB"); 14 | double alfa1 = 0.0, alfa2 = 0.0, p1 = 0.0, p2 = 0.0, a = 0.0, ab = 0.0; 15 | array res; res.x = 2; 16 | double *values= new double [2]; 17 | if (debug) fprintf(stderr, "%f\t%f\t%f\t%f\t%f\t%f\n", alfa1, alfa2, p1,p2,a,ab); 18 | p1 = static_cast(s1) / (2*n1); 19 | p2 = static_cast(s2) / (2*n2); 20 | if (debug) fprintf(stderr, "%f\t%f\n", p1, p2); 21 | alfa1 = 2*p1*(1-p1); 22 | alfa2 = 2*p2*(1-p2); 23 | if (debug) fprintf(stderr, "%f\t%f\n", alfa1, alfa2); 24 | a = ((p1-p2)*(p1-p2)) - (((n1+n2) * (n1 * alfa1 + n2 * alfa2)) / (4*n1*n2*(n1+n2-1))); 25 | ab = ((p1-p2)*(p1-p2)) + ( ( (4*n1*n2 - n1 - n2) * (n1 * alfa1 + n2 * alfa2) ) / ((4*n1*n2)*(n1+n2-1)) ); 26 | values[0]=a; 27 | values[1]=ab; 28 | if (debug) fprintf(stderr, "%f\t%f\n", a, ab); 29 | res.data = values; 30 | return res; 31 | } 32 | 33 | // compute a and ab estimate for all possible combinations of sample size, then weight by their prob, but no correction from a first guess of fst 34 | void computeVarRey(matrix &m1, matrix &m2, int verbose, FILE *fname, int nsums) { 35 | // m1 and m2 are post probs 36 | /// DEFINITION (DECLARATION AND INITIALIZATION) 37 | if (verbose==2) fprintf(stderr, "\nInside computeVarRey"); 38 | int n1 = 0, n2 = 0; // sample sizes 39 | int nsites = 0; // nsites 40 | // estimates nsites and pop sizes from matrices 41 | n1 = (m1.y-1)/2; // nind1 42 | n2 = (m2.y-1)/2; // nind2 43 | nsites = m1.x; // nsites from file 44 | double VAR = 0.0, COVAR = 0.0, FACT = 0.0; 45 | matrix A; 46 | matrix AB; 47 | array temp; 48 | for (int s=0; s (q) ) *m1.data[s][i]*m2.data[s][j]; 88 | COVAR = COVAR + pow((AB.data[i][j]-EAB)*(A.data[i][j]-EA), static_cast (q) ) *m1.data[s][i]*m2.data[s][j]; 89 | } // end for in j 90 | } // end for in i 91 | FACT = FACT + pow( (-1.0), static_cast (q)) *( (EA*VAR + COVAR) / pow(EAB, static_cast (q+1))); 92 | if ((verbose==4) & (s==0)) fprintf(stderr, "\n q %d v %f c %f f %f",q,VAR,COVAR,FACT); 93 | } // end for in nsums 94 | // print results 95 | fprintf(fname, "%f\t%f\t%f\t%f\t%f\n", EA, EAB, FACT, (EA/EAB)+FACT, pvar); 96 | cleanup(A); 97 | cleanup(AB); 98 | } // end for s in nsites 99 | } // end 100 | 101 | 102 | // compute a and ab estimate for all possible combinations of sample size, then weight by their prob12 computed from post1, pos12 and prior12 (normalize it) 103 | void computeVarRey12(matrix &m1, matrix &m2, int verbose, FILE *fname, int nsums, matrix &p12) { 104 | 105 | int n1 = 0, n2 = 0; // sample sizes 106 | int nsites = 0; // nsites 107 | 108 | // estimates nsites and pop sizes from matrices 109 | n1 = (m1.y-1)/2; // nind1 110 | n2 = (m2.y-1)/2; // nind2 111 | nsites = m1.x; // nsites from file 112 | 113 | double VAR = 0.0, COVAR = 0.0, FACT = 0.0, pvar = 0.0; 114 | 115 | for (int s=0; s m12; 119 | m12.x=m1.y; 120 | m12.y=m2.y; 121 | double **ddata = new double*[m12.x]; 122 | for(int i=0;i A; 157 | matrix AB; 158 | 159 | A.x=AB.x=(n1*2)+1; 160 | A.y=AB.y=(n2*2)+1; 161 | 162 | // FIRST CYCLE: get expected A and AB and retain matrices of A and AB 163 | double **dataA = new double*[(n1*2)+1]; 164 | double **dataAB = new double*[(n1*2)+1]; 165 | 166 | // get also the probability of site being variable 167 | pvar = 1 - m12.data[0][0] - m12.data[2*n1][2*n2]; 168 | 169 | if (verbose==2) fprintf(stderr, "\t first cycle"); 170 | 171 | double EA = 0.0, EAB = 0.0; 172 | 173 | for (int i=0; i<(2*n1+1); i++) { 174 | 175 | if (verbose==2) fprintf(stderr, "\ti%d",i); 176 | 177 | double *bufA = new double[(n2*2)+1]; 178 | double *bufAB = new double[(n2*2)+1]; 179 | 180 | for (int j=0; j<(2*n2+1); j++) { 181 | 182 | array temp; 183 | temp = calcAB(i, j, n1, n2, 0); 184 | bufA[j]=temp.data[0]; 185 | bufAB[j]=temp.data[1]; 186 | 187 | EA = EA + temp.data[0]*m12.data[i][j]; 188 | EAB = EAB + temp.data[1]*m12.data[i][j]; 189 | 190 | delete [] temp.data; 191 | 192 | } // end for in j 193 | 194 | dataA[i]=bufA; 195 | dataAB[i]=bufAB; 196 | 197 | } // end for in i 198 | 199 | A.data=dataA; 200 | AB.data=dataAB; 201 | 202 | if (EA<0.0) EA=0.0; // protect against -0.000 cases 203 | // SECOND CYCLE: get VAR and COVAR, and then the correcting FACTor, according to number of sums to retain 204 | VAR = 0.0, COVAR = 0.0, FACT = 0.0; 205 | 206 | if ((verbose==4) & (s==0)) fprintf(stderr, "\t second cycle %d", nsums); 207 | 208 | for (int q=1; q<=nsums; q++) { 209 | 210 | VAR = 0.0; COVAR = 0.0; 211 | for (int i=0; i<(2*n1+1); i++) { 212 | for (int j=0; j<(2*n2+1); j++) { 213 | 214 | VAR = VAR + pow((AB.data[i][j]-EAB), static_cast (q) )*m12.data[i][j]; 215 | 216 | COVAR = COVAR + pow((AB.data[i][j]-EAB)*(A.data[i][j]-EA), static_cast (q) ) *m12.data[i][j]; 217 | 218 | } // end for in j 219 | } // end for in i 220 | 221 | FACT = FACT + pow( (-1.0), static_cast (q)) *( (EA*VAR + COVAR) / pow(EAB, static_cast (q+1))); 222 | 223 | if ((verbose==4) & (s==0)) fprintf(stderr, "\n q %d v %f c %f f %f",q,VAR,COVAR,FACT); 224 | 225 | } // end for in nsums 226 | 227 | // print results 228 | fprintf(fname, "%f\t%f\t%f\t%f\t%f\n", EA, EAB, FACT, (EA/EAB)+FACT, pvar); 229 | 230 | cleanup(A); 231 | cleanup(AB); 232 | cleanup(m12); 233 | 234 | } // end for s in nsites 235 | 236 | 237 | 238 | } // end 239 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # ngsPopGen 3 | 4 | Several tools to perform population genetic analyses from NGS data: 5 | * ` ngsFst` - Quantificate population genetic differentiation 6 | * ` ngsCovar` - Population structure via PCA (principal components analysis) 7 | * ` ngs2dSFS` - Estimate 2D-SFS from posterior probabilities of sample allele frequencies 8 | * ` ngsStat` - Estimates number of segregating sites, expected average heterozygosity, and number of fixed differences and Dxy (if 2 populations provided). 9 | 10 | IMPORTANT NOTE i): 11 | 12 | In all analises involving 2 populations, input data must refer to the exact same sites. If they differ (e.g. because of different filtering), you must first get the overlapping subset of sites for both populations. 13 | To achieve this, you can follow instructions given in the tutorial ([here](https://github.com/mfumagalli/ngsTools/blob/master/TUTORIAL.md)). 14 | 15 | IMPORTANT NOTE ii): 16 | 17 | The use of folded data (spectrum or sample allele frequencies probabilities) is no longer supported. 18 | In case you do not have a reliable ancestral information, please use your reference sequence to polarise your data and follow all the steps as documented here. However, do not attempt to make any inference based on the resulting unfolded reference/non-reference based - site frequency spectrum. 19 | 20 | IMPORTANT NOTE iii): 21 | 22 | It may be practical to perform a non-stringent SNP calling before running the following analyses, in order to reduce the computational time and data dimensions. 23 | Moreover, this will reduce noise due to monomorphic sites, especially when the species' polymorphic rate is very low. 24 | 25 | 26 | ### Installation 27 | 28 | To install the entire package just download the source code: 29 | 30 | % git clone https://github.com/mfumagalli/ngsPopGen.git 31 | 32 | and run: 33 | 34 | % cd ngsPopGen 35 | % make 36 | 37 | To run the tests (only if installed through [ngsTools](https://github.com/mfumagalli/ngsTools)): 38 | 39 | % make test 40 | 41 | Executables are built into the main directory. If you wish to clean all binaries and intermediate files: 42 | 43 | % make clean 44 | 45 | However, we recommend to download and install the whole [ngsTools](https://github.com/mfumagalli/ngsTools) package. 46 | 47 | 48 | --- 49 | 50 | ## ngsFST 51 | 52 | Program to estimate FST from NGS data. It computes expected genetic variance components and estimate per-site FST from those using methods-of-moments estimator. See Fumagalli et al. Genetics 2013 for more details. 53 | In input it receives sample allele frequencies likelihoods for each population and a 2D-SFS as a prior. 54 | 55 | The output is a tab-separated text file. Each row represents a site. Columns are ordered as: A, AB, f, FST, Pvar; where A is the expectation of genetic variance between populations, AB is the expectation of the total genetic variance, f is the correcting factor for the ratio of expectations, FST is the per-site FST value, Pvar is the probability for the site of being variable. 56 | 57 | ### Usage 58 | #### Examples: 59 | 60 | * using a 2D-SFS as a prior, estimated using ngs2dSFS: 61 | 62 | # 63 | 64 | % ./ngsFST -postfiles pop1.saf pop2.saf -priorfile spectrum2D.txt -nind 20 20 -nsites 100000 -outfile pops.fst -verbose 0 65 | 66 | #### Parameters: 67 | * `-postfiles FILE_1 FILE_2`: files with sample allele frequencies likelihoods for each population 68 | * `-priorfile FILE`: 2D-SFS to be used as a prior; you can use ngs2dSfs with parameter -relative set to 1 69 | * `-nind INT`: number of individuals for each population 70 | * `-nsites INT`: total number of sites; in case of a site subset this is the upper limit 71 | * `-firstbase INT`: in case of a site subset, this is the lower limit 72 | * `-outfile FILE`: name of the output file 73 | * `-block_size INT`: number of sites in each chunk (for memory reasons, increase it if you can use more RAM) 74 | * `-verbose INT`: level of verbosity 75 | 76 | --- 77 | 78 | ## ngsCovar 79 | 80 | Program to compute the expected correlation matrix between individuals from genotype posterior probabilities. It receives as input genotype posterior probabilities. It can receive in input also posterior probabilities of sample allele frequencies for computing the probability of each site to be variant. 81 | 82 | ### Usage 83 | 84 | #### Examples: 85 | 86 | * not calling genotypes but with SNP calling (preferred way under most circumstances): 87 | 88 | # 89 | 90 | % ./ngsCovar -probfile pop.geno -outfile pop.covar -nind 40 -nsites 100000 -block_size 20000 -call 0 -minmaf 0.05 91 | 92 | * not calling genotypes and no SNP calling (weighting by each site's probability of being variable; recommended if depth is extremely low): 93 | 94 | # 95 | 96 | % gunzip -f pop.saf.gz 97 | % ./ngsCovar -probfile pop.geno -outfile pop.covar -nind 40 -nsites 100000 -block_size 20000 -call 0 -norm 0 -sfsfile pop.saf 98 | 99 | * calling genotypes (this is kept for compatibility but should not be used unless you have high-depth data, > 20X): 100 | 101 | # 102 | 103 | % ./ngsCovar -probfile pop.geno -outfile pop.covar -nind 40 -nsites 100000 -block_size 20000 -call 1 104 | 105 | 106 | #### Parameters: 107 | * `-probfile FILE`: file with genotype posterior probabilities 108 | * `-sfsfile FILE`: file with per site allele frequency posterior probabilities 109 | * `-nind INT`: number of individuals 110 | * `-nsites INT`: total number of sites; in case of a site subset this is the upper limit 111 | * `-offset INT`: in case of a site subset, this is the lower limit 112 | * `-genoquality FILE`: text file with 'nsites' lines stating whether to use (1) or ignore (0) the site 113 | * `-norm INT`: normalization procedure; either "0" for no normalization (recommended if no SNP calling was performed), "1" for normalization by `p(1-p)` (Patterson et al, 2006) or "2" for normalization by `2p(1-p)` 114 | * `-minmaf FLOAT`: ignore sites below this threshold of minor allele frequency 115 | * `-call`: call genotypes based on the maximum posterior probability 116 | * `-outfile FILE`: name of output file 117 | * `-block_size INT`: number of sites in each chunk (for memory reasons) 118 | * `-verbose INT`: level of verbosity 119 | 120 | --- 121 | 122 | ## ngs2dSFS 123 | 124 | Program to estimate 2D-SFS from posterior probabilities of sample allele frequencies. Output file reports the occurrence of sites at distinct joint allele frequencies. This spectrum is a (2N1+1)x(2N2+2) matrix with N1 and N2 number of individuals at the two populations. Please note that cells are zero-based ordered. As an example, value reported in the cell [4,3] represents the frequency of sites with allele frequency 3 and 2 at population 1 and 2 respectively. 125 | 126 | #### Example: 127 | 128 | % ./ngs2dSFS -postfiles pop1.saf pop2.saf -outfile spectrum.txt -relative 1 -nind 20 20 -nsites 100000 129 | 130 | #### Parameters: 131 | * `-postfiles FILE`: file with sample allele frequency posterior probabilities (or likelihoods) for each population 132 | * `-nind INT`: number of individuals 133 | * `-nsites INT`: total number of sites; in case of a site subset this is the upper limit 134 | * `-offset INT`: in case of a site subset, this is the lower limit 135 | * `-outfile FILE`: name of output file 136 | * `-maxlike INT`: how to compute the MLE; either, "1" (preferred) to sum across sites' joint allele frequency, or "0" to sum of the products of likelihoods 137 | * `-relative INT`: whether input are absolute counts of sites with a specific joint allele frequency (0) or relative frequencies (1) 138 | * `-block_size INT`: number of sites for each chunk (for memory efficiency only) 139 | 140 | ANGSD can compute a ML estimate of the 2D-SFS which should be preferred when many sites are available. However, ANGSD output file should be transformed (from log to un-log and from space-separated to tab-separated) before being used in ngsFST. 141 | 142 | 143 | --- 144 | 145 | ## ngsStat 146 | 147 | Program to compute estimates of the number of segregating sites, the expected average heterozygosity, and the number of fixed differences (if 2 populations data is provided). It receives as input sample allele frequency posterior probabilities (from ANGSD) from 1 or 2 populations. Output is a text file with columns: start, end, segregating sites (pop 1), heterozygosity (pop 1), segregating sites (pop 2), heterozygosity (pop 2), fixed differences, dxy. 148 | 149 | #### Example: 150 | 151 | * 2 populations, sliding windows of 100 sites (latter recommended only if no missing data is present, however in most cases you will have some missing sites so this command should not be used): 152 | 153 | # 154 | 155 | ./ngsStat -npop 2 -postfiles pop1.saf pop2.saf -nsites 1000 -iswin 1 -nind 10 10 -outfile pops.stat -verbose 0 -block_size 100 156 | 157 | * 1 populations, sliding windows of 100 sites (latter recommended only if no missing data is present, so again in many cases this should not be used): 158 | 159 | # 160 | 161 | ./ngsStat -npop 1 -postfiles pop1.saf -nsites 1000 -iswin 1 -nind 10 -outfile pops.stat -block_size 100 162 | 163 | * 1 population, values estimated at each site (recommended in case of missing data, and then the computation of values in sliding windows will be performed using the R script provided): 164 | 165 | # 166 | 167 | ./ngsStat -npop 1 -postfiles pop1.saf -nsites 1000 -iswin 0 -nind 10 -outfile pops.stat 168 | 169 | #### Parameters: 170 | * `-npop INT`: number of populations (should be the first one to be specified) 171 | * `-postfiles`: file with sample allele frequency posterior probabilities for each population 172 | * `-nind INT`: number of individuals 173 | * `-nsites INT`: total number of sites; in case of a site subset this is the upper limit 174 | * `-firstbase INT`: in case of a site subset, this is the lower limit 175 | * `-iswin INT`: if set to 1, chuncks are considered non-overlapping sliding-windows 176 | * `-outfile FILE`: name of output file 177 | * `-block_size INT`: number of sites in each chunk (for memory reasons) 178 | * `-verbose INT`: level of verbosity 179 | 180 | 181 | Further examples can be found in the [Tutorial](https://github.com/mfumagalli/ngsTools/blob/master/TUTORIAL.md). 182 | 183 | -------------------------------------------------------------------------------- /ngsCovar.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include "ngsCovar.hpp" 8 | 9 | // to compile: g++ -Wall -O0 -g ngsCovar.cpp -o ngsCovar 10 | 11 | // implement offset 12 | 13 | int main (int argc, char *argv[]) { 14 | 15 | // CALL HELP FUNCTION 16 | if (argc==1) { 17 | info(); 18 | return 0; // terminate 19 | } 20 | 21 | // DECLARE 22 | 23 | // possible inputs 24 | char *estfile=NULL; // estimated genotypes with probs (from angsd -doGeno 64) 25 | char *sfsfile=NULL; // sfs probs (-realSFS 1 + optimSFS = sfstools) 26 | char *genoquality=NULL; // list of boolean, whether to keep or not each site 27 | 28 | FILE *outest; 29 | char *outfiles=NULL; 30 | char *foutest=NULL; 31 | 32 | int argPos = 1, increment = 0, nind = 0, nsites = 0, debug = 0, block_size = 20000, call=0, offset=1, maxgeno=0, norm=0; 33 | double esites = 0.0, minmaf = 0.0; 34 | 35 | /// READ AND ASSIGN INPUT PARAMETERS 36 | 37 | while (argPosUsing args: -nind %d -nsites %d -probfile %s -sfsfile %s -outfile %s -verbose %d -minmaf %f -block_size %d -call %d -offset %d\n", nind, nsites, estfile, sfsfile, foutest, debug, minmaf, block_size, call, offset); 74 | 75 | // check if there is the input file 76 | if (estfile == NULL) { 77 | fprintf(stderr,"\nMust supply -probfile.\n"); 78 | info(); 79 | return 0; 80 | } 81 | 82 | // check if there is the sfs file 83 | if ((sfsfile != NULL) & (minmaf>0)) { 84 | fprintf(stderr,"\n-sfsfile and -minmaf are in conflict! If use use -sfsfile to weight each file there is no need (theoretically) to filter out sites with low maf. In this case -minmaf won't be applied and the program terminates here.\n"); 85 | info(); 86 | return 0; 87 | } 88 | 89 | // check if there is the output file 90 | if (outfiles == NULL) { 91 | fprintf(stderr,"\nMust supply -outfile.\n"); 92 | info(); 93 | return 0; 94 | } 95 | 96 | // if block_size longer than nsites 97 | if (block_size>(nsites-offset+1)) block_size=(nsites-offset+1); 98 | if (block_size==0) block_size=nsites-offset+1; 99 | 100 | // When reading from stdin, reading in blocks is not supported 101 | if ( (strcmp(estfile,"-")==0 || (sfsfile!=NULL && strcmp(sfsfile,"-")==0)) && block_size != nsites ) { 102 | fprintf(stderr,"\nInput in blocks is not supported when using piped input (either -postfile or -sfsfile).\n"); 103 | exit(-1); 104 | } 105 | 106 | // prepare output files 107 | foutest = append(outfiles, ""); 108 | 109 | 110 | // BLOCKS 111 | /// GET POSITIONS OF BLOCKS 112 | array start; array end; 113 | start=getStart(nsites, offset, block_size); 114 | end=getEnd(nsites, offset, block_size); 115 | int maxlen=end.data[0]-start.data[0]+1; // len for each win, it will never be greater than this 116 | double temp_sum=0.0; // check at each iteration not NA, for debug 117 | int nwin= (nsites-offset+1)/block_size; 118 | if ( ( (nsites-offset+1) % block_size)!=0) nwin++; 119 | 120 | // prepare out 121 | if (debug) fprintf(stderr,"\t->Dumping file: %s\n", foutest); 122 | outest = getFILE(foutest, "w"); 123 | 124 | // initialize covariance matrix 125 | matrix covar; 126 | double **cdata = new double*[nind]; 127 | for(int i=0;i pvar; 142 | double *temp2 = new double [maxlen]; // init to the size of the largest window 143 | for (int i=0; i good; 150 | if (genoquality!=NULL) { 151 | good = readGenoQuality(genoquality, nsites); 152 | } else { 153 | good.x=nsites; 154 | int *good_tmp = new int [nsites]; 155 | for (int i=0; i sfs; 163 | matrix esti; 164 | array pp; 165 | 166 | if (debug) fprintf(stderr, "\nBlock %d out of %d from %d to %d\n", n, (nwin-1), start.data[n], end.data[n]); 167 | 168 | // compute esti 169 | if (debug==1) fprintf(stderr, "\nGetting esti..."); 170 | esti = readEstiSub(estfile, nind, start.data[n], end.data[n]); 171 | if (debug==2) writematrix(esti, stderr); 172 | if (debug==1) fprintf(stderr, ": %d %d , %f %f", esti.x, esti.y, esti.data[0][0], esti.data[1][1]); 173 | 174 | // IF CALL GENOTYPES, set max prob to 1 175 | if (call) { 176 | 177 | if (debug==1) fprintf(stderr, "\nCalling genotypes..."); 178 | for (int i=0; i //for str operations 4 | #include 5 | 6 | // a general matrix style structure 7 | template 8 | struct matrix{ 9 | int x; 10 | int y; 11 | T** data; 12 | }; 13 | 14 | // a general array style structure 15 | template 16 | struct array{ 17 | int x; 18 | T* data; 19 | }; 20 | 21 | template 22 | T *collapse(std::vector &v){ 23 | T *tmp = new T[v.size()]; 24 | for(int i=0;i 31 | void cleanup(matrix &m){//using a reference to avoid copying the data 32 | for(int i=0;i getStart(int nsites, int firstbase, int block_size) { 40 | // note that firstbase and nsites are 1-based 41 | int len = nsites-firstbase+1; 42 | int nwin = len/block_size; 43 | if ( (len % block_size)!=0) nwin=nwin+1; 44 | 45 | array start; 46 | start.x=nwin; 47 | 48 | int *tStart= new int [nwin]; 49 | for (int i=0; i1) { 55 | for (int i=0; i getEnd(int nsites, int firstbase, int block_size) { 64 | // note that firstbase and nsites are 1-based 65 | int len = nsites-firstbase+1; 66 | 67 | int nwin = len/block_size; 68 | if ( (len % block_size)!=0) nwin=nwin+1; 69 | 70 | array end; 71 | end.x=nwin; 72 | 73 | int *tEnd= new int [nwin]; 74 | for (int i=0; i0) { 81 | for (int i=0; i File exists: %s exiting...\n",fname); 121 | exit(0); 122 | } 123 | 124 | if(strcmp(fname, "-") == 0){ 125 | if(writeFile) 126 | fp = stdout; 127 | else 128 | fp = stdin; 129 | } else { 130 | if(NULL==(fp=fopen(fname,mode))){ 131 | fprintf(stderr,"\t->Error opening FILE handle for file:%s exiting\n",fname); 132 | exit(0); 133 | } 134 | } 135 | 136 | if(isatty(fileno(fp))) { 137 | fprintf(stderr, "Your stdin/stdout is not a pipe, this might not be what you want!\n"); 138 | exit(0); 139 | } 140 | 141 | return fp; 142 | } 143 | 144 | // read a file of prior into an array 145 | array readArray(const char *fname, int nInd) { 146 | FILE *fp = getFILE(fname,"r"); 147 | size_t filesize =fsize(fname); 148 | if(filesize==0){ 149 | fprintf(stderr,"file:%s looks empty\n",fname); 150 | exit(0); 151 | } 152 | int len = 2*nInd+1; 153 | char *buf = new char[filesize]; 154 | double *tmp = new double[len]; 155 | fread(buf,sizeof(char),filesize,fp); 156 | tmp[0] = atof(strtok(buf,"\t \n")); 157 | for(int i=1;i<(len);i++) 158 | tmp[i] = atof(strtok(NULL,"\t \n")); 159 | fclose(fp); 160 | delete [] buf; 161 | array ret; 162 | ret.x = len; 163 | ret.data = tmp; 164 | return ret; 165 | } 166 | 167 | // read 2d sfs 168 | matrix readPrior12(const char *fname, int nrow, int ncol) { 169 | FILE *fp = getFILE(fname,"r"); 170 | size_t filesize =fsize(fname); 171 | if(filesize==0){ 172 | fprintf(stderr,"file:%s looks empty\n",fname); 173 | exit(0); 174 | } 175 | double *tmp = new double[nrow*ncol]; 176 | char *buf = new char[filesize]; 177 | fread(buf,sizeof(char),filesize,fp); 178 | tmp[0] = atof(strtok(buf,"\t \n")); 179 | for(int i=1;i<(nrow*ncol);i++) 180 | tmp[i] = atof(strtok(NULL,"\t \n")); 181 | fclose(fp); 182 | delete [] buf; 183 | array allvalues; 184 | allvalues.x = nrow*ncol; 185 | allvalues.data = tmp; 186 | int index=0; 187 | double **data = new double*[nrow]; 188 | for(int i=0;i ret; 197 | ret.x=nrow; 198 | ret.y=ncol; 199 | ret.data=data; 200 | delete [] allvalues.data; 201 | return ret; 202 | } 203 | 204 | 205 | // read a file of posterior probabilities into a matrix but only for a specific subsets of positions (0-based notation) 206 | matrix readFileSub(char *fname, int nInd, int start, int end) { 207 | FILE *fp = getFILE(fname,"r"); 208 | size_t filesize =fsize(fname); 209 | int n_categ = 2*nInd+1; 210 | 211 | if( strcmp(fname,"-")!=0 ) { 212 | if( filesize % (n_categ*sizeof(float)) != 2*sizeof(float) ) { 213 | fprintf(stderr,"\n\t-> Possible error reading SFS, binary file might be broken...\n"); 214 | exit(-1); 215 | } 216 | } 217 | 218 | int nsites = end-start+1; 219 | double **data = new double*[nsites]; 220 | float float_tmp = 0; 221 | 222 | // Locate data to read 223 | fseek(fp, (2+n_categ*start)*sizeof(float), SEEK_SET); 224 | 225 | // Read data 226 | for(int i=0; i ret; 237 | ret.x = nsites; 238 | ret.y = n_categ; 239 | ret.data = data; 240 | return ret; 241 | } 242 | 243 | // read genotype posterior probabilities from angsd (-dogeno 64), but only for a specific subsets of positions (0-based notation) 244 | matrix readEstiSub(char *fname, int nInd, int start, int end) { 245 | FILE *fp = getFILE(fname,"rb"); 246 | size_t filesize =fsize(fname); 247 | if( strcmp(fname,"-")!=0 && (filesize %(sizeof(double)*3*nInd)) ) { 248 | fprintf(stderr,"\n\t-> Possible error read GENO, binary file might be broken...\n"); 249 | exit(-1); 250 | } 251 | int nsites = end-start+1; 252 | double **data = new double*[nsites]; 253 | fseek(fp, sizeof(double)*(3*nInd)*start, SEEK_SET); 254 | for(int i=0; i ret; 261 | ret.x = nsites; 262 | ret.y = 3*nInd; 263 | ret.data = data; 264 | return ret; 265 | } 266 | 267 | // read genotype quality (boolean), analysis only on sites to be kept (1) and discard the rest (0) 268 | array readGenoQuality(const char *fname, int nsites) { 269 | // nsites is how many sites you want 270 | FILE *fp = getFILE(fname,"r"); 271 | size_t filesize =fsize(fname); 272 | if( strcmp(fname,"-")!=0 && filesize==0){ 273 | fprintf(stderr,"file:%s looks empty\n",fname); 274 | exit(0); 275 | } 276 | int *tmp = new int[nsites]; 277 | char *buf = new char[filesize]; 278 | fread(buf,sizeof(char),filesize,fp); 279 | tmp[0] = atoi(strtok(buf,"\t \n")); 280 | for(int i=1;i<(nsites);i++) 281 | tmp[i] = atoi(strtok(NULL,"\t \n")); 282 | fclose(fp); 283 | array allvalues; 284 | allvalues.x = nsites; 285 | allvalues.data = tmp; 286 | return allvalues; 287 | } 288 | 289 | // return max value position of a row from a matrix of geno likes or post probs for a specific individual 290 | int maxposarr(matrix &m, int row, int start, int end) { 291 | double val = m.data[row][start]; 292 | 293 | for (int i = start; i < end; i++) { 294 | if (m.data[row][i] > val) { 295 | start = i; 296 | val = m.data[row][i]; 297 | } 298 | } 299 | 300 | return start; 301 | } 302 | 303 | // normalize SFS and exp it if log 304 | void normSFS(matrix &sfs, bool islog) { 305 | int nsites = sfs.x; 306 | int ncol = sfs.y; 307 | double somma = 0.0; 308 | for (int j=0; j &sfs, array pvar) { 332 | for (int i=0; i &m,FILE *fp) { 338 | for(int i=0;i &m,FILE *fp) { 345 | for(int i=0;i &m,FILE *fp) { 352 | for(int i=0;i &m,FILE *fp) { 361 | for(int i=0;i &sfs, array prior) { 370 | int nsites = sfs.x; 371 | int ncol = sfs.y; 372 | for (int j=0; j 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------