keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
2D
rpestourie/fdfd_local_field
examples/consolidate_dataset.jl
.jl
769
27
using DelimitedFiles function consolidate_dataset(substring, dir_name) """ this function goes through all the files in dir_names and consolidates the dataset for the files containing substring """ datafull = [] for file in cd(readdir, dir_name) if occursin(substring, file) if datafull == [] datafull = copy(readdlm(dir_name*"/"*file, ',')) else cur_data = readdlm(dir_name*"/"*file, ',') datafull = vcat(datafull, cur_data) end end end return datafull end dir_name = "./examples/data" substring = "imag_gd" datafull = consolidate_dataset(substring, dir_name) writedlm(dir_name*"/consolidated_data_$(substring[1:4]).csv", datafull, ',')
Julia
2D
rpestourie/fdfd_local_field
examples/growing_dataset.jl
.jl
825
26
using DelimitedFiles function generate_datasets(namedir, application_name, nbpoints) """ This function takes the full dataset and sets the first nbpoints points in a test set, then creates an ever growing train dataset by increments of nboints""" fulldataset = readdlm("examples/data/consolidated_data_$application_name.csv", ',') nb_train = size(fulldataset)[1] testdataset = fulldataset[1:nbpoints,:] writedlm(namedir*"test_dataset_$application_name.csv", testdataset, ',') i = 2 while nbpoints * i <= nb_train writedlm(namedir*"train_dataset_$(application_name)_$(i-1).csv", fulldataset[nbpoints+1:i*nbpoints,:], ',') i+=1 end end application_name = "real" namedir = "examples/data/" nbpoints = 10000 generate_datasets(namedir, application_name, nbpoints)
Julia
2D
mitenjain/nanopore
__init__.py
.py
0
0
null
Python
2D
mitenjain/nanopore
nanopore/pipeline.sh
.sh
715
10
#!/bin/bash #Cleanup the old files rm -rf ${2} ${3} #Set the python path to just these local directories export PYTHONPATH=:./:./submodules:${PYTHONPATH} #Preferentially put the local binaries at the front of the path export PATH=:./submodules/sonLib/bin:./submodules/cactus/bin:./submodules/jobTree/bin:./submodules/bwa/:./submodules/lastz/src/:./submodules/last/src/:./submodules/last/scripts/:./submodules/fastqc/:./submodules/qualimap:./submodules/blasrbinary/:./submodules/samtools-0.1.19:./submodules/samtools-0.1.19/bcftools:./submodules/consensus/:${PATH} python ./nanopore/pipeline.py ${1} --jobTree ${2} --logInfo --maxThreads=${4} --batchSystem=${5} --defaultMemory=${6} --logLevel INFO --stats &> ${3}
Shell
2D
mitenjain/nanopore
nanopore/__init__.py
.py
0
0
null
Python
2D
mitenjain/nanopore
nanopore/pipeline.py
.py
12,152
216
import os from optparse import OptionParser from jobTree.scriptTree.target import Target from jobTree.scriptTree.stack import Stack from jobTree.src.bioio import getLogLevelString, isNewer, logger, setLoggingFromOptions from nanopore.analyses.abstractAnalysis import AbstractAnalysis from nanopore.analyses.mutate_reference import mutateReferenceSequences from nanopore.analyses.utils import makeFastaSequenceNamesUnique, makeFastqSequenceNamesUnique #The following specify which mappers and analyses get run from nanopore.mappers.lastz import Lastz, LastzChain, LastzRealign, LastzRealignEm, LastzRealignTrainedModel from nanopore.mappers.lastzParams import LastzParams, LastzParamsChain, LastzParamsRealign, LastzParamsRealignEm, LastzParamsRealignTrainedModel from nanopore.mappers.bwa import Bwa, BwaChain, BwaRealign, BwaRealignEm, BwaRealignTrainedModel from nanopore.mappers.bwa_params import BwaParams, BwaParamsChain, BwaParamsRealign, BwaParamsRealignEm, BwaParamsRealignTrainedModel from nanopore.mappers.last import Last, LastChain, LastRealign, LastRealignEm, LastRealignTrainedModel from nanopore.mappers.blasr import Blasr, BlasrChain, BlasrRealign, BlasrRealignEm, BlasrRealignTrainedModel from nanopore.mappers.blasr_params import BlasrParams, BlasrParamsChain, BlasrParamsRealign, BlasrParamsRealignEm, BlasrParamsRealignTrainedModel, BlasrParamsRealignTrainedModel20, BlasrParamsRealignTrainedModel40 from nanopore.mappers.last_params import LastParams, LastParamsChain, LastParamsRealign, LastParamsRealignEm, LastParamsRealignTrainedModel, LastParamsRealignTrainedModel20, LastParamsRealignTrainedModel40 from nanopore.mappers.combinedMapper import CombinedMapper, CombinedMapperChain, CombinedMapperRealign, CombinedMapperRealignEm, CombinedMapperRealignTrainedModel from nanopore.analyses.substitutions import Substitutions from nanopore.analyses.coverage import LocalCoverage, GlobalCoverage from nanopore.analyses.kmerAnalysis import KmerAnalysis from nanopore.analyses.indelKmerAnalysis import IndelKmerAnalysis from nanopore.analyses.indels import Indels from nanopore.analyses.fastqc import FastQC from nanopore.analyses.qualimap import QualiMap from nanopore.analyses.alignmentUncertainty import AlignmentUncertainty from nanopore.analyses.read_sampler import SampleReads from nanopore.analyses.consensus import Consensus from nanopore.analyses.channelMappability import ChannelMappability from nanopore.analyses.hmm import Hmm from nanopore.analyses.marginAlignSnpCaller import MarginAlignSnpCaller from nanopore.metaAnalyses.unmappedKmerAnalysis import UnmappedKmerAnalysis from nanopore.metaAnalyses.unmappedLengthDistributionAnalysis import UnmappedLengthDistributionAnalysis from nanopore.metaAnalyses.comparePerReadMappabilityByMapper import ComparePerReadMappabilityByMapper from nanopore.metaAnalyses.coverageSummary import CoverageSummary from nanopore.metaAnalyses.customTrackAssemblyHub import CustomTrackAssemblyHub from nanopore.metaAnalyses.marginAlignMetaAnalysis import MarginAlignMetaAnalysis from nanopore.metaAnalyses.coverageDepth import CoverageDepth from nanopore.metaAnalyses.hmmMetaAnalysis import HmmMetaAnalysis mappers = [ #Bwa, BwaChain, #BwaParams, BwaParamsChain, BwaParamsRealign, BwaParamsRealignEm, #BwaParamsRealignTrainedModel, #Blasr, BlasrChain, #BlasrParams, BlasrParamsChain, BlasrParamsRealign, BlasrParamsRealignEm, #BlasrParamsRealignTrainedModel, #Last, LastChain, #LastParams, LastParamsChain, LastParamsRealign, LastParamsRealignEm, #LastParamsRealignTrainedModel, #Lastz, LastzChain, #LastzParams, LastzParamsChain, LastzParamsRealign, LastzParamsRealignEm ] #, #LastzParamsRealignTrainedModel, #CombinedMapper, #CombinedMapperChain ] #CombinedMapperRealign ] #CombinedMapperRealignEm, #CombinedMapperRealignTrainedModel ] analyses = [ Hmm, GlobalCoverage, LocalCoverage, Substitutions, Indels, AlignmentUncertainty, ChannelMappability, KmerAnalysis, IndelKmerAnalysis ] #, FastQC, QualiMap, Consensus] metaAnalyses = [ UnmappedKmerAnalysis, CoverageSummary, UnmappedLengthDistributionAnalysis, ComparePerReadMappabilityByMapper, HmmMetaAnalysis ]# CustomTrackAssemblyHub ] #mappers = [ LastParamsRealignEm ] #analyses = [ GlobalCoverage, Indels ] #metaAnalyses = [] ####Enable these to do variant calling #analyses = [ MarginAlignSnpCaller, AlignmentUncertainty ] #metaAnalyses = [ MarginAlignMetaAnalysis ] #mappers = [ LastParamsChain, LastParamsRealignTrainedModel, # LastParamsRealignTrainedModel20, LastParamsRealignTrainedModel40, # BlasrParamsChain, BlasrParamsRealignTrainedModel, # BlasrParamsRealignTrainedModel20, BlasrParamsRealignTrainedModel40, ] #The following runs the mapping and analysis for every combination of readFastqFile, referenceFastaFile and mapper def setupExperiments(target, readFastqFiles, referenceFastaFiles, mappers, analysers, metaAnalyses, outputDir): experiments = [] for readType, readTypeFastaFiles in readFastqFiles: outputBase = os.path.join(outputDir, "analysis_" + readType) if not os.path.exists(outputBase): os.mkdir(outputBase) for readFastqFile in readTypeFastaFiles: for referenceFastaFile in referenceFastaFiles: for mapper in mappers: experimentDir = os.path.join(outputBase, "experiment_%s_%s_%s" % \ (os.path.split(readFastqFile)[-1], os.path.split(referenceFastaFile)[-1], mapper.__name__)) experiment = (readFastqFile, readType, referenceFastaFile, mapper, analyses, experimentDir) target.addChildTarget(Target.makeTargetFn(mapThenAnalyse, args=experiment)) experiments.append(experiment) target.setFollowOnTargetFn(runMetaAnalyses, args=(metaAnalyses, outputDir, experiments)) def mapThenAnalyse(target, readFastqFile, readType, referenceFastaFile, mapper, analyses, experimentDir): if not os.path.exists(experimentDir): os.mkdir(experimentDir) target.logToMaster("Creating experiment dir: %s" % experimentDir) else: target.logToMaster("Experiment dir already exists: %s" % experimentDir) samFile = os.path.join(experimentDir, "mapping.sam") hmmFileToTrain = os.path.join(experimentDir, "hmm.txt") remapped = False if not os.path.exists(samFile): target.logToMaster("Starting mapper %s for reference file %s and read file %s" % (mapper.__name__, referenceFastaFile, readFastqFile)) target.addChildTarget(mapper(readFastqFile, readType, referenceFastaFile, samFile, hmmFileToTrain)) remapped = True else: target.logToMaster("Mapper %s for reference file %s and read file %s is already complete" % (mapper.__name__, referenceFastaFile, readFastqFile)) target.setFollowOnTarget(Target.makeTargetFn(runAnalyses, args=(readFastqFile, readType, referenceFastaFile, samFile, analyses, experimentDir, remapped, mapper))) def runAnalyses(target, readFastqFile, readType, referenceFastaFile, samFile, analyses, experimentDir, remapped, mapper): for analysis in analyses: analysisDir = os.path.join(experimentDir, "analysis_" + analysis.__name__) #if not os.path.exists(analysisDir) or isNewer(readFastqFile, analysisDir) or isNewer(referenceFastaFile, analysisDir): if not os.path.exists(analysisDir): os.mkdir(analysisDir) if remapped or not AbstractAnalysis.isFinished(analysisDir): target.logToMaster("Starting analysis %s for reference file %s and read file %s analyzed with mapper %s" % (analysis.__name__, referenceFastaFile, readFastqFile, mapper.__name__)) AbstractAnalysis.reset(analysisDir) target.addChildTarget(analysis(readFastqFile, readType, referenceFastaFile, samFile, analysisDir)) else: target.logToMaster("Analysis %s for reference file %s and read file %s is already complete" % (analysis.__name__, referenceFastaFile, readFastqFile)) def runMetaAnalyses(target, metaAnalyses, outputDir, experiments): for metaAnalysis in metaAnalyses: metaAnalysisDir = os.path.join(outputDir, "metaAnalysis_" + metaAnalysis.__name__) if not os.path.exists(metaAnalysisDir): os.mkdir(metaAnalysisDir) target.addChildTarget(metaAnalysis(metaAnalysisDir, experiments)) def main(): #Parse the inputs args/options parser = OptionParser(usage="usage: workingDir [options]", version="%prog 0.1") Stack.addJobTreeOptions(parser) options, args = parser.parse_args() setLoggingFromOptions(options) if len(args) != 1: raise RuntimeError("Expected one argument, got %s arguments: %s" % (len(args), " ".join(args))) workingDir = args[0] # call read sampler script; samples 75, 50, and 25% reads #SampleReads(workingDir) #Create (if necessary) the output dir outputDir = os.path.join(workingDir, "output") if not os.path.exists(outputDir): logger.info("Creating output dir: %s" % outputDir) os.mkdir(outputDir) else: logger.info("Root output dir already exists: %s" % outputDir) #Assign/process (uniquify the names of) the input read fastq files processedFastqFiles = os.path.join(outputDir, "processedReadFastqFiles") if not os.path.exists(processedFastqFiles): os.mkdir(processedFastqFiles) fastqParentDir = os.path.join(workingDir, "readFastqFiles") readFastqFiles = list() for fastqSubDir in filter(os.path.isdir, [os.path.join(fastqParentDir, x) for x in os.listdir(fastqParentDir)]): readType = os.path.basename(fastqSubDir) if not os.path.exists(os.path.join(processedFastqFiles, os.path.basename(fastqSubDir))): os.mkdir(os.path.join(processedFastqFiles, readType)) readFastqFiles.append([readType, [ makeFastqSequenceNamesUnique(os.path.join(workingDir, "readFastqFiles", readType, i), os.path.join(processedFastqFiles, readType, i)) for i in os.listdir(os.path.join(workingDir, "readFastqFiles", readType)) if (".fq" in i and i[-3:] == '.fq') or (".fastq" in i and i[-6:] == '.fastq') ]]) #Assign/process (uniquify the names of) the input reference fasta files processedFastaFiles = os.path.join(outputDir, "processedReferenceFastaFiles") if not os.path.exists(processedFastaFiles): os.mkdir(processedFastaFiles) referenceFastaFiles = [ makeFastaSequenceNamesUnique(os.path.join(workingDir, "referenceFastaFiles", i), os.path.join(processedFastaFiles, i)) for i in os.listdir(os.path.join(workingDir, "referenceFastaFiles")) if (".fa" in i and i[-3:] == '.fa') or (".fasta" in i and i[-6:] == '.fasta') ] # call reference mutator script; introduces 1%, and 5% mutations (No nucleotide bias used for now) #referenceFastaFiles = mutateReferenceSequences(referenceFastaFiles) #Log the inputs logger.info("Using the following working directory: %s" % workingDir) logger.info("Using the following output directory: %s" % outputDir) for readType, readTypeFastqFiles in readFastqFiles: logger.info("Got the follow read type: %s" % readType) for readFastqFile in readTypeFastqFiles: logger.info("Got the following read fastq file: %s" % readFastqFile) for referenceFastaFile in referenceFastaFiles: logger.info("Got the following reference fasta files: %s" % referenceFastaFile) #This line invokes jobTree i = Stack(Target.makeTargetFn(setupExperiments, args=(readFastqFiles, referenceFastaFiles, mappers, analyses, metaAnalyses, outputDir))).startJobTree(options) if i != 0: raise RuntimeError("Got failed jobs") if __name__ == '__main__': from nanopore.pipeline import * main()
Python
2D
mitenjain/nanopore
nanopore/metaAnalyses/ROC_marginAlign.R
.R
2,119
46
#!/usr/bin/env Rscript args <- commandArgs(trailingOnly = T) library(lattice) cols <- max(count.fields(args[1], sep="\t")) data <- read.table(args[1], fill=T, sep="\t", col.names=paste("V",seq_len(cols))) #find # of algorithms, coverages and proportions heldout used algorithms <- length(unique(data[,2])) coverage <- length(unique(data[,4])) heldout <- length(unique(data[,3])) #set it to 4 plots per page because we are assuming 4 heldouts #if there are not 4 heldouts then this won't work properly #loop over every algorithm block, which is heldout*coverage*2 #this corresponds to each row of plots for (i in seq(1, algorithms*heldout*coverage*2, heldout*coverage*2)) { #open a pdf for each algorithm, put into the folder for this readtype/mapper combination pdf(paste(args[2], data[,2][i], args[3], sep="")) par(mfrow=c(2,2)) #loop over every fpr/tpr block, which happens every coverage*2 #this corresponds to one plot in a row for (j in seq(i, i+heldout*coverage*2-heldout-coverage, coverage*2)) { #pull out these fprs and tprs (which alternate down the whole file) fprs <- data[seq(j, j+coverage*2-1, 2),] tprs <- data[seq(j+1, j+coverage*2, 2),] #find the coverages for this plot *should always be the same* coverages <- tprs[,4] #find this trials algorithm *should be the same for each row* algorithm <- tprs[,2][1] #find the proportion heldout for this plot, turn into a text percentage held_out <- paste(formatC(100*round(tprs[,3][1],6), format="f", digits=2), "%", sep="") #remove the non-data columns in preparation for plotting tprs <- tprs[,-(1:4)] fprs <- fprs[,-(1:4)] #plot and draw legend matplot(t(fprs), t(tprs), type="l", col=rev(c(1:length(coverages))), lty=1, lwd=1.1, main=paste("ProportionHeldOut: ", held_out, sep=""), cex.main=0.8, cex.axis=0.7, xlab="Recall", ylab="Precision", xlim=c(0.85,1), ylim=c(0.85,1)) legend("bottomleft", legend=coverages, col=rev(c(1:length(coverages))), cex=0.8, pch="-", title="Coverage") } dev.off() }
R
2D
mitenjain/nanopore
nanopore/metaAnalyses/hmmMetaAnalysis.py
.py
6,877
107
import os from nanopore.metaAnalyses.abstractMetaAnalysis import AbstractMetaAnalysis import xml.etree.cElementTree as ET from jobTree.src.bioio import * import itertools import numpy as np class HmmMetaAnalysis(AbstractMetaAnalysis): def run(self): #Call base method to do some logging AbstractMetaAnalysis.run(self) bases = "ACGT" readTypes = set([ readType for readFastqFile, readType in self.readFastqFiles ]) for readType in readTypes: #This is the info we collate transitions = {} insertEmissions = { "A":[], 'C':[], 'G':[], 'T':[] } deleteEmissions = { "A":[], 'C':[], 'G':[], 'T':[] } substitutionEmissions = dict(zip(itertools.product(bases, bases), map(lambda i : [], range(len(bases)**2)))) for referenceFastaFile in self.referenceFastaFiles: for readFastqFile, readFileReadType in self.readFastqFiles: if readFileReadType == readType: for mapper in self.mappers: analyses, resultsDir = self.experimentHash[((readFastqFile, readType), referenceFastaFile, mapper)] if os.path.exists(os.path.join(resultsDir, "hmm.txt.xml")): hmmsNode = ET.parse(os.path.join(resultsDir, "hmm.txt.xml")).getroot() #Aggregate transition expectations for transition in hmmsNode.findall("transition"): if float(transition.attrib["avg"]) > 0.0: key= (transition.attrib["from"], transition.attrib["to"]) if key not in transitions: transitions[key] = [] transitions[key].append((float(transition.attrib["avg"]), float(transition.attrib["std"]))) #Aggregate substitution expectations #Plot match emission data insertEmissions2 = dict(zip(bases, [0.0]*len(bases))) deleteEmissions2 = dict(zip(bases, [0.0]*len(bases))) for emission in hmmsNode.findall("emission"): if emission.attrib["state"] == '0': substitutionEmissions[(emission.attrib["x"], emission.attrib["y"])].append((float(emission.attrib["avg"]), float(emission.attrib["std"]))) elif emission.attrib["state"] == '1': deleteEmissions2[emission.attrib["x"]] += float(emission.attrib["avg"]) elif emission.attrib["state"] == '2': insertEmissions2[emission.attrib["y"]] += float(emission.attrib["avg"]) for base in bases: insertEmissions[base].append(insertEmissions2[base]) deleteEmissions[base].append(deleteEmissions2[base]) #Write out a dot file representing the avg HMM transitions with std errors #Plot graphviz version of nanopore hmm, showing transitions and variances. fH = open(os.path.join(self.outputDir, "hmm_%s.dot" % readType), 'w') setupGraphFile(fH) #Make states addNodeToGraph("n0n", fH, "match") addNodeToGraph("n1n", fH, "short delete") addNodeToGraph("n2n", fH, "short insert") addNodeToGraph("n3n", fH, "long insert") addNodeToGraph("n4n", fH, "long delete") #Make edges with labelled transition probs. for fromState, toState in transitions: t = transitions[(fromState, toState)] addEdgeToGraph("n%sn" % fromState, "n%sn" % toState, fH, dir="arrow", style='""', label="%.3f,%.3f" % (np.average(map(lambda x : x[0], t)), np.std(map(lambda x : x[0], t)))) #Finish up finishGraphFile(fH) fH.close() #Write out a matrix representing the substitutions with std errors, normalised by reference base matchEmissionsFile = os.path.join(self.outputDir, "matchEmissionsNormalisedByReference_%s.tsv" % readType) outf = open(matchEmissionsFile, "w") bases = "ACGT" outf.write("\t".join(bases) + "\n") for base in bases: d = sum(map(lambda x : np.average(substitutionEmissions[(base, x)][0]), bases)) outf.write("\t".join([ base ] + map(lambda x : str(np.average(substitutionEmissions[(base, x)][0])/d), bases)) + "\n") outf.close() system("Rscript nanopore/analyses/substitution_plot.R %s %s %s" % (matchEmissionsFile, os.path.join(self.outputDir, "substitutionPlotNormalisedByReference_%s.pdf" % readType), "Avg. of ML substitution rates given the reference base")) #Write out the substitution errors. #Write out a matrix representing the substitutions with std errors, normalised by reference base matchEmissionsFile = os.path.join(self.outputDir, "matchEmissionsUnnormalised_%s.tsv" % readType) outf = open(matchEmissionsFile, "w") bases = "ACGT" outf.write("\t".join(bases) + "\n") for base in bases: outf.write("\t".join([ base ] + map(lambda x : str(np.average(substitutionEmissions[(base, x)][0])), bases)) + "\n") outf.close() system("Rscript nanopore/analyses/substitution_plot.R %s %s %s" % (matchEmissionsFile, os.path.join(self.outputDir, "substitutionPlotUnnormalised_%s.pdf" % readType), "Avg. ML substitution estimates")) #Write out a matrix representing the substitutions with std errors, normalised by reference base matchEmissionsFile = os.path.join(self.outputDir, "matchEmissionsUnnormalisedStdErrors_%s.tsv" % readType) outf = open(matchEmissionsFile, "w") bases = "ACGT" outf.write("\t".join(bases) + "\n") for base in bases: outf.write("\t".join([ base ] + map(lambda x : str(np.average(substitutionEmissions[(base, x)][1])), bases)) + "\n") outf.close() system("Rscript nanopore/analyses/substitution_plot.R %s %s %s" % (matchEmissionsFile, os.path.join(self.outputDir, "substitutionPlotUnnormalisedStdErrors_%s.pdf" % readType), "Avg. ML substitution estimates"))
Python
2D
mitenjain/nanopore
nanopore/metaAnalyses/unmapped_mapped_distributions.R
.R
1,871
35
#!/usr/bin/env Rscript # args <- commandArgs(trailingOnly = T) unmapped <- read.table(args[1]) mapped <- read.table(args[2]) analysis <- args[4] if (length(unmapped[,1]) >= 1 && length(mapped[,1]) >= 1) { pdf(args[3]) b <- max(c(unmapped[,1], mapped[,1])) m <- hist(mapped[,1], breaks = seq(1,b+100,100), plot=F) u <- hist(unmapped[,1], breaks = seq(1,b+100,100), plot=F) combined <- c(mapped[,1], unmapped[,1]) combined <- combined[!is.na(combined)] combined.sort <- combined[order(combined)] xmax <- combined.sort[round(0.98*length(combined.sort))] ymax <- max(m$counts, u$counts) plot(m, col=rgb(1,0,0,0.5), xlim=c(0,xmax), ylim=c(0,ymax), main="Mapped and Unmapped Read Length Distributions", xlab="Read Length") plot(u, col=rgb(0,0,1,0.5), add=T, xlim=c(0,xmax), ylim=c(0,ymax), main="", xlab="", ylab="") legend("top", pch=15, legend=c(paste("Mapped n =", dim(mapped)[1]), paste("Unmapped n =", dim(unmapped)[1])), col=c(rgb(1,0,0),rgb(0,0,1))) #stacked histogram without removing outliers ymax <- max(u$counts, m$counts) xmax <- combined.sort[length(combined.sort)] plot(m, col=rgb(1,0,0,0.5), xlim=c(0,xmax), ylim=c(0,ymax), main="Mapped and Unmapped Read Length Distributions", xlab="Read Length") plot(u, col=rgb(0,0,1,0.5), add=T, xlim=c(0,xmax), ylim=c(0,ymax), main="", xlab="", ylab="") legend("topright", pch=15, legend=c(paste("Mapped n =", dim(mapped)[1]), paste("Unmapped n =", dim(unmapped)[1])), col=c(rgb(1,0,0),rgb(0,0,1))) lengths <- c(length(unmapped[,1]), length(mapped[,1])) q <- barplot(lengths, names.arg=c("Unmapped","Mapped"), col=c("red","blue"), main=paste(analysis, " # Of Mapped and Unmapped Reads")) text(y=lengths+0.015*sum(lengths), x=q, labels=paste(formatC(round(100*lengths/sum(lengths),3), format="f", digits=2), "%"), xpd=T) dev.off() }
R
2D
mitenjain/nanopore
nanopore/metaAnalyses/unmappedLengthDistributionAnalysis.py
.py
2,509
31
from nanopore.metaAnalyses.abstractUnmappedAnalysis import AbstractUnmappedMetaAnalysis import os, sys from jobTree.src.bioio import system class UnmappedLengthDistributionAnalysis(AbstractUnmappedMetaAnalysis): """runs length distribution analysis on all mapped/unmapped per read Type as well as per reference""" def run(self): for readType in self.readTypes: unmapped = open(os.path.join(self.outputDir, readType + "_unmapped.txt"), "w") mapped = open(os.path.join(self.outputDir, readType + "_mapped.txt"), "w") for read in self.reads: if read.is_mapped is True and read.readType == readType: mapped.write("{}\n".format(len(read.seq))) elif read.readType == readType: unmapped.write("{}\n".format(len(read.seq))) unmapped.close(); mapped.close() if os.path.getsize(os.path.join(self.outputDir, readType + "_unmapped.txt")) > 0 and os.path.getsize(os.path.join(self.outputDir, readType + "_mapped.txt")) > 0: system("Rscript nanopore/metaAnalyses/unmapped_mapped_distributions.R {} {} {} {}".format(os.path.join(self.outputDir, readType + "_unmapped.txt"), os.path.join(self.outputDir, readType + "_mapped.txt"), os.path.join(self.outputDir, readType + "_length_distribution.pdf"), readType)) for reference in self.referenceFastaFiles: unmapped = open(os.path.join(self.outputDir, os.path.basename(reference) + "_unmapped.txt"), "w") mapped = open(os.path.join(self.outputDir, os.path.basename(reference) + "_mapped.txt"), "w") for read in self.reads: if read.is_mapped is True: mapped.write("{}\n".format(len(read.seq))) else: unmapped.write("{}\n".format(len(read.seq))) unmapped.close(); mapped.close() if os.path.getsize(os.path.join(self.outputDir, os.path.basename(reference) + "_unmapped.txt")) > 0 and os.path.getsize(os.path.join(self.outputDir, os.path.basename(reference) + "_mapped.txt")) > 0: system("Rscript nanopore/metaAnalyses/unmapped_mapped_distributions.R {} {} {} {}".format(os.path.join(self.outputDir, os.path.basename(reference) + "_unmapped.txt"), os.path.join(self.outputDir, os.path.basename(reference) + "_mapped.txt"), os.path.join(self.outputDir, os.path.basename(reference) + "_length_distribution.pdf"), os.path.basename(reference)))
Python
2D
mitenjain/nanopore
nanopore/metaAnalyses/comparePerReadMappabilityByMapper.py
.py
1,652
26
from nanopore.metaAnalyses.abstractUnmappedAnalysis import AbstractUnmappedMetaAnalysis import os, sys import xml.etree.cElementTree as ET from jobTree.src.bioio import system import re from collections import OrderedDict as od class ComparePerReadMappabilityByMapper(AbstractUnmappedMetaAnalysis): """Finds which base mappers mapped which reads""" def run(self): for readType in self.readTypes: sortedBaseMappers = [x for x in sorted(self.baseMappers) if x != "Combined"] outf = open(os.path.join(self.outputDir, readType + "_perReadMappability.tsv"), "w") outf.write("Read\tReadFastqFile\t"); outf.write("\t".join(sortedBaseMappers)); outf.write("\n") for read in self.reads: if read.readType == readType: tmp = od([[x, 0] for x in sortedBaseMappers]) if read.is_mapped is True: for mapper, reference in read.get_map_ref_pair(): baseMapper = re.findall("[A-Z][a-z]*", mapper)[0] #hacky way to avoid including 'combined' analysis if baseMapper != "Combined" and tmp[baseMapper] == 0: tmp[baseMapper] = 1 outf.write("\t".join([read.name, os.path.basename(read.readFastqFile)] + map(str, tmp.values()))); outf.write("\n") outf.close() system("Rscript nanopore/metaAnalyses/vennDiagram.R {} {}".format(os.path.join(self.outputDir, readType + "_perReadMappability.tsv"), os.path.join(self.outputDir, readType + "_perReadMappabilityVennDiagram.pdf")))
Python
2D
mitenjain/nanopore
nanopore/metaAnalyses/coverageSummaryPlots.R
.R
4,603
91
#!/usr/bin/env Rscript args <- commandArgs(trailingOnly = T) summary <- read.csv(args[1], header=T, row.names=1) name <- args[2] summary <- summary[order(rownames(summary)),] if (dim(summary)[1] >= 1) { num <- 1 names <- vector() for (i in 1:length(rownames(summary))){ tmp <- as.numeric(strsplit(rownames(summary)[i], "[.]")[[1]][2]) n <- as.character(strsplit(rownames(summary)[i], "[.]")[[1]][1]) if (! is.na(tmp)) { num <- max(tmp, num) } else { names <- c(names, n) } } colmap <- vector() for (i in 1:8){ colmap <- c(colmap, rep(i, times=num)) } pchmap <- rep(15:(15+num-1), times=ceiling(length(summary)/num)) pdf(args[3]) ################################################ ####Looking at insertion/deletion/match rates ################################################ plot(summary$AvgInsertionsPerReadBase, summary$AvgDeletionsPerReadBase, xlab="Avg. Insertions Per Aligned Read Base", ylab="Avg. Deletions Per Aligned Read Base", main=name, col=colmap, pch=pchmap, xlim=c(0,0.2), ylim=c(0,0.2), cex.main=0.9) legend("topright", cex=0.75, legend=names, pch="*", col=1:8, pt.cex=1.2) #scatterplot of Avg identity coverage vs Avg # of indels per base plot(100 * summary$AvgIdentity, summary$AvgDeletionsPerReadBase + summary$AvgInsertionsPerReadBase, ylab="Avg. Indels Per Aligned Read Base", xlab="Avg. Match Identity", main=name, col=colmap, pch=pchmap, xlim=c(0,100), cex.main=0.9) legend("topleft", cex=0.75, legend=names, pch="*", col=1:8) q <- barplot(height=summary$AvgInsertionsPerReadBase, xaxt="n", col=colmap, main=paste(name,"Avg. Insertions Per Aligned Base",sep="\n"), ylab="Avg. Insertions Per Aligned Base", cex.main=0.9) text(cex=0.8, x=q, y=-0.01, rownames(summary), xpd=T, srt=90) q <- barplot(height=summary$AvgDeletionsPerReadBase, xaxt="n", col=colmap, main=paste(name,"Avg. Deletions Per Aligned Base",sep="\n"), ylab="Avg. Deletions Per Aligned Base", cex.main=0.9) text(cex=0.8, x=q, y=-0.01, rownames(summary), xpd=T, srt=90) q <- barplot(height=summary$AvgIdentity, xaxt="n", col=colmap, main=paste(name,"Identity of Aligned Bases",sep="\n"), ylab="Proportion of matched aligned bases.", cex.main=0.9) text(cex=0.8, x=q, y=-0.01, rownames(summary), xpd=T, srt=90) ################################################ ####Looking at identity - demonstrating chaining and EM are useful improvements ################################################ q <- barplot(height=summary$AvgIdentity, xaxt="n", col=colmap, main=paste(name,"Identity (inc. gaps)",sep="\n"), ylab="Identity (inc. gaps)", cex.main=0.9) text(cex=0.8, x=q, y=-0.01, rownames(summary), xpd=T, srt=90) #scatterplot of Avg read coverage vs Avg match identity plot(100 * summary$AvgReadCoverage, 100 * summary$AvgIdentity, ylab="Avg. Match Identity", xlab="Avg. Read Coverage", main=name, col=colmap, pch=pchmap, xlim=c(0,100), ylim=c(0,100), cex.main=0.9) legend("topleft", cex=0.75, legend=names, pch="*", col=1:8) ################################################ ####Looking at unmapped reads - demonstrating last is doing a great job ################################################ #barplot of unmapped read counts per mapper q <- barplot(height=summary$NumberOfMappedReads/summary$NumberOfReads, xaxt="n", col=colmap, main=paste(name,"Prop. Mapped Reads",sep="\n"), ylab="Prop. Reads Mapped", cex.main=0.9) text(cex=0.8, x=q, y=-0.01, rownames(summary), xpd=T, srt=90) ################################################ ####Combining mapped reads + identity to get measure of pipeline productivity. ################################################ #scatterplot of Avg. identity vs Proportion reads mapped. plot(100 * summary$AvgIdentity, 100 * summary$NumberOfMappedReads/summary$NumberOfReads, xlab="Avg. Identity", ylab="Prop. Reads Mapped", main=name, col=colmap, pch=20, xlim=c(0,100), ylim=c(0,100), cex.main=0.9) text(100 * summary$AvgIdentity, 100 * summary$NumberOfMappedReads/summary$NumberOfReads, cex=0.65, pos=2, labels=rownames(summary)) q <- barplot(height=(summary$NumberOfMappedReads/summary$NumberOfReads*summary$AvgIdentity), xaxt="n", col=colmap, main=paste(name,"Prop. Of Sequenced Bases Aligned with Identity",sep="\n"), ylab="Prop. Of Sequenced Bases Aligned with Identity", cex.main=0.9) text(cex=0.8, x=q, y=-0.01, rownames(summary), xpd=T, srt=90) dev.off() }
R
2D
mitenjain/nanopore
nanopore/metaAnalyses/mappable_kmer_analysis.R
.R
1,528
48
#!/usr/bin/env Rscript args <- commandArgs(trailingOnly = T) data <- read.table(args[1], row.names=1, header=T) outf <- args[2] outsig <- args[3] outplot <- args[4] library(stats) library(lattice) num_trials <- 1000 trial_size <- 5000 trial_fn <- function(d, t) { matrix(table(factor(sample(1024, t, prob=d, replace=T), levels=1:1024)))[,1] } if (sum(data$mappableFraction) != 0 & sum(data$unmappableFraction) != 0) { mappable <- replicate(num_trials, trial_fn(d=data$mappableFraction, t=trial_size)) unmappable <- replicate(num_trials, trial_fn(d=data$unmappableFraction, t=trial_size)) p_values <- rep(0, 1024) for (i in 1:1024) { p_values[i] <- ks.test(mappable[i,], unmappable[i,])$p.value } adjusted_p_value <- p.adjust(p_values, method="bonferroni") #combine original data frame with two new vectors finished <- cbind(data, p_values, adjusted_p_value) #write full dataset write.table(finished, outf) #find significant hits significant <- finished[finished$adjusted_p_value <= 0.05,] pdf(outplot) xyplot(finished$adjusted_p_value~finished$logFoldChange, xlab="Log Fold Change", ylab="Adjusted P Value", main="Unmappable vs. Mappable Volcano Plot") dev.off() #sort the significant hits by fold change ordered <- significant[order(significant$logFoldChange),] #report the top 20 and bottom 20 significant hits top <- head(ordered, n=20L) bot <- apply(tail(ordered, n=20L), 2, rev) write.table(rbind(top,bot), outsig) }
R
2D
mitenjain/nanopore
nanopore/metaAnalyses/coverageSummary.py
.py
6,668
125
from nanopore.metaAnalyses.abstractMetaAnalysis import AbstractMetaAnalysis import os, sys import xml.etree.cElementTree as ET from jobTree.src.bioio import system import re from itertools import product, izip from collections import Counter class Entry(object): def __init__(self, readType, readFastqFile, referenceFastaFile, mapper, XML): self.readType = readType self.readFastqFile = os.path.basename(readFastqFile) self.referenceFastaFile = os.path.basename(referenceFastaFile) self.mapper = mapper.__name__ self.base_mapper = re.findall("[A-Z][a-z]*", mapper.__name__)[0] self.XML = XML class CoverageSummary(AbstractMetaAnalysis): """Calculates meta-coverage across all the samples. Includes analysis per mapper, per readType+mapper, per reference, and combined """ def build_db(self): """ Builds db of coverage results """ db = list() for readFastqFile, readType in self.readFastqFiles: for referenceFastaFile in self.referenceFastaFiles: for mapper in self.mappers: analyses, resultsDir = self.experimentHash[(readFastqFile, readType), referenceFastaFile, mapper] if os.path.exists(os.path.join(resultsDir, "analysis_GlobalCoverage", "coverage_bestPerRead.xml")): globalCoverageXML = ET.parse(os.path.join(resultsDir, "analysis_GlobalCoverage", "coverage_bestPerRead.xml")).getroot() db.append(Entry(readType, readFastqFile, referenceFastaFile, mapper, globalCoverageXML)) return db def by_mapper_readtype_reference(self): entry_map = {x : list() for x in product(self.baseMappers, self.readTypes, [os.path.basename(x) for x in self.referenceFastaFiles])} for entry in self.db: entry_map[(entry.base_mapper, entry.readType, entry.referenceFastaFile)].append(entry) for (base_mapper, readType, referenceFastaFile), entries in entry_map.iteritems(): name = "_".join([base_mapper, readType, referenceFastaFile]) self.write_file_analyze(entries, name) def by_mapper_readfile(self): entry_map = {x: list() for x in product(self.baseMappers, [os.path.basename(x[0]) for x in self.readFastqFiles])} for entry in self.db: entry_map[(entry.base_mapper, entry.readFastqFile)].append(entry) for (base_mapper, readFastqFile), entries in entry_map.iteritems(): name = "_".join([base_mapper, readFastqFile]) self.write_file_analyze(entries, name) def by_reference(self): entry_map = {os.path.basename(x): list() for x in self.referenceFastaFiles} for entry in self.db: entry_map[entry.referenceFastaFile].append(entry) for referenceFastaFile, entries in entry_map.iteritems(): self.write_file_analyze(entries, referenceFastaFile, multiple_read_types=True) def write_file_analyze(self, entries, name, multiple_read_types=False): path = os.path.join(self.outputDir, name + ".csv") outf = open(path, "w") outf.write(",".join(["Name", "Mapper", "ReadType", "ReadFile", "ReferenceFile", "AvgReadCoverage", "AvgReferenceCoverage", "AvgIdentity", "AvgMismatchesPerReadBase", "AvgDeletionsPerReadBase", "AvgInsertionsPerReadBase", "NumberOfMappedReads", "NumberOfUnmappedReads", "NumberOfReads"])); outf.write("\n") entries = sorted(entries, key = lambda x: (x.mapper, x.readType, x.readFastqFile)) names = self.resolve_duplicate_rownames(entries, multiple_read_types) for entry, n in izip(entries, names): outf.write(",".join([n, entry.mapper, entry.readType, entry.readFastqFile, entry.referenceFastaFile, entry.XML.attrib["avgreadCoverage"], entry.XML.attrib["avgreferenceCoverage"], entry.XML.attrib["avgidentity"], entry.XML.attrib["avgmismatchesPerReadBase"], entry.XML.attrib["avgdeletionsPerReadBase"], entry.XML.attrib["avginsertionsPerReadBase"], entry.XML.attrib["numberOfMappedReads"], entry.XML.attrib["numberOfUnmappedReads"], entry.XML.attrib["numberOfReads"]]) + "\n") outf.close() path2 = os.path.join(self.outputDir, name + "_distribution.csv") outf = open(path2, "w") for entry, n in izip(entries, names): outf.write(",".join([n] + entry.XML.attrib["distributionidentity"].split())); outf.write("\n") outf.close() system("Rscript nanopore/metaAnalyses/coverageSummaryPlots.R {} {} {}".format(path, name, os.path.join(self.outputDir, name + "_summary_plots.pdf"))) system("Rscript nanopore/metaAnalyses/coveragePlots.R {} {} {}".format(path2, name, os.path.join(self.outputDir, name + "_distribution.pdf"))) def resolve_duplicate_rownames(self, entries, multiple_read_types=False): #this is really ugly if multiple_read_types is True: last_mapper = entries[0].mapper + "_" + entries[0].readType else: last_mapper = entries[0].mapper count = 0; start = True names = list() for entry in entries: if multiple_read_types is True and entry.mapper + "_" + entry.readType == last_mapper: count += 1 last_mapper = entry.mapper + "_" + entry.readType if start is not True: names.append(entry.mapper + "_" + entry.readType + "." + str(count)) else: names.append(entry.mapper + "_" + entry.readType) start = False elif multiple_read_types is True: last_mapper = entry.mapper + "_" + entry.readType names.append(entry.mapper + "_" + entry.readType) count = 1 elif multiple_read_types is False and entry.mapper == last_mapper: count += 1 last_mapper = entry.mapper if start is not True: names.append(entry.mapper + "." + str(count)) else: names.append(entry.mapper) start = False else: last_mapper = entry.mapper names.append(entry.mapper) count = 1 return names def run(self): self.db = self.build_db() self.by_mapper_readtype_reference() self.by_mapper_readfile() self.by_reference()
Python
2D
mitenjain/nanopore
nanopore/metaAnalyses/__init__.py
.py
0
0
null
Python
2D
mitenjain/nanopore
nanopore/metaAnalyses/abstractUnmappedAnalysis.py
.py
2,488
52
from nanopore.metaAnalyses.abstractMetaAnalysis import AbstractMetaAnalysis import os, sys import xml.etree.cElementTree as ET from jobTree.src.bioio import system, fastqRead from nanopore.analyses.utils import samIterator import pysam class Read(): """stores a individual read and everything about it""" def __init__(self, name, seq, readType, readFastqFile, mapRefPairs): self.seq = seq self.name = name self.readType = readType self.readFastqFile = readFastqFile self.mapRefPairs = mapRefPairs if mapRefPairs is not None: self.is_mapped = True self.mappers, self.references = set(mapRefPairs[0]), set(mapRefPairs[1]) else: self.is_mapped = False self.mappers, self.references = None, None def get_map_ref_pair(self): if self.mapRefPairs is not None: for mapper, reference in zip(self.mapRefPairs[0], self.mapRefPairs[1]): yield (mapper, reference) class AbstractUnmappedMetaAnalysis(AbstractMetaAnalysis): """Builds a database of reads and the information gathered about them during analysis""" def __init__(self, outputDir, experiments): AbstractMetaAnalysis.__init__(self, outputDir, experiments) allReads = {(name, readFastqFile, readType, seq) for readFastqFile, readType, referenceFastaFile, mapper, analyses, resultsDir \ in self.experiments for name, seq, qual in fastqRead(readFastqFile)} mappedReads = dict() for readFastqFile, readType, referenceFastaFile, mapper, analyses, resultsDir in self.experiments: for record in samIterator(pysam.Samfile(os.path.join(resultsDir, "mapping.sam"))): if not record.is_unmapped: if (record.qname, readFastqFile) not in mappedReads: mappedReads[(record.qname, readFastqFile)] = set() mappedReads[(record.qname, readFastqFile)].add((mapper.__name__, referenceFastaFile)) self.reads = list() for name, readFastqFile, readType, seq in allReads: if (name, readFastqFile) in mappedReads: mappers, referenceFastaFiles = map(tuple, zip(*mappedReads[(name, readFastqFile)])) self.reads.append(Read(name, seq, readType, readFastqFile, (mappers, referenceFastaFiles))) else: self.reads.append(Read(name, seq, readType, readFastqFile, None))
Python
2D
mitenjain/nanopore
nanopore/metaAnalyses/abstractMetaAnalysis.py
.py
1,355
32
from jobTree.scriptTree.target import Target import re class AbstractMetaAnalysis(Target): """Base class to for meta-analysis targets. Inherit this class to create a meta-analysis. """ def __init__(self, outputDir, experiments): Target.__init__(self) self.experiments = experiments self.outputDir = outputDir #Quadruples of (readFastqFile, readType, referenceFastaFile, mapper) to pairs of (analyses, resultsDir) self.experimentHash = {} #Mappers self.mappers = set() #Read file readType double self.readFastqFiles = set() #Reference files self.referenceFastaFiles = set() #readTypes self.readTypes = set() #base mappers (lastz, last, bwa, blasr) self.baseMappers = set() #Store all this stuff for readFastqFile, readType, referenceFastaFile, mapper, analyses, resultsDir in self.experiments: self.experimentHash[((readFastqFile, readType), referenceFastaFile, mapper)] = (analyses, resultsDir) self.mappers.add(mapper) self.readFastqFiles.add((readFastqFile, readType)) self.referenceFastaFiles.add(referenceFastaFile) self.readTypes.add(readType) self.baseMappers.add(re.findall("[A-Z][a-z]*", mapper.__name__)[0])
Python
2D
mitenjain/nanopore
nanopore/metaAnalyses/marginAlignMetaAnalysis.py
.py
9,458
135
from nanopore.metaAnalyses.abstractMetaAnalysis import AbstractMetaAnalysis import os, sys import xml.etree.cElementTree as ET from jobTree.src.bioio import system, fastqRead, fastaRead from nanopore.analyses.utils import samIterator from itertools import product import numpy class MarginAlignMetaAnalysis(AbstractMetaAnalysis): def run(self): readTypes = set([ readType for readFastqFile, readType in self.readFastqFiles ]) coverageLevels = set() hash = {} variantCallingAlgorithms = set() proportionsHeldOut = set() for referenceFastaFile in self.referenceFastaFiles: for readType in readTypes: for readFastqFile, readFileReadType in self.readFastqFiles: if readFileReadType == readType: for mapper in self.mappers: analyses, resultsDir = self.experimentHash[((readFastqFile, readType), referenceFastaFile, mapper)] try: node = ET.parse(os.path.join(resultsDir, "analysis_MarginAlignSnpCaller", "marginaliseConsensus.xml")).getroot() except: self.logToMaster("Parsing the file following failed: %s" % os.path.join(resultsDir, "analysis_MarginAlignSnpCaller", "marginaliseConsensus.xml")) continue for c in node: coverage = int(c.attrib["coverage"]) if coverage == 10: continue #Remove the dead coverage plot if coverage > 1000: coverage = "ALL" coverageLevels.add(coverage) proportionHeldOut = float(c.attrib["totalHeldOut"]) / (float(c.attrib["totalHeldOut"]) + float(c.attrib["totalNonHeldOut"])) if proportionHeldOut == 0: continue if proportionHeldOut < 0.04: proportionHeldOut = 0.01 elif proportionHeldOut < 0.09: proportionHeldOut = 0.05 elif proportionHeldOut < 0.18: proportionHeldOut = 0.1 else: proportionHeldOut = 0.2 key = (readType, mapper.__name__, c.tag, proportionHeldOut, referenceFastaFile) variantCallingAlgorithms.add(c.tag) proportionsHeldOut.add(proportionHeldOut) if key not in hash: hash[key] = {} if coverage not in hash[key]: hash[key][coverage] = [] hash[key][coverage].append(c) fH = open(os.path.join(self.outputDir, "marginAlignAll.txt"), 'w') fH.write("\t".join(["readType", "mapper", "caller", "%heldOut", "coverage", "fScoreMin", "fScoreMedian", "fScoreMax", "recallMin", "recallMedian", "recallMax", "precisionMin", "precisionMedian", "precisionMax", "%notCalledMin", "%notCalledMedian", "%notCalledMax", "actualCoverageMin", "actualCoverageMedian", "actualCoverageMax"]) + "\n") fH2 = open(os.path.join(self.outputDir, "marginAlignSquares.txt"), 'w') coverageLevels = list(coverageLevels) coverageLevels.sort() fH2.write("\t".join(["readType", "mapper", "caller", "%heldOut", "\t".join([ ("min_recall_coverage_%s\t" % coverage) + ("avg_recall_coverage_%s\t" % coverage) + ("max_recall_coverage_%s" % coverage) for coverage in coverageLevels]), "\t".join([ ("min_precision_coverage_%s\t" % coverage) + ("avg_precision_coverage_%s\t" % coverage) + ("max_precision_coverage_%s" % coverage) for coverage in coverageLevels]), "\t".join([ ("min_fscore_coverage_%s\t" % coverage) + ("avg_fscore_coverage_%s\t" % coverage) + ("max_fscore_coverage_%s" % coverage) for coverage in coverageLevels]), "\n" ])) keys = hash.keys() keys.sort() rocCurvesHash = {} for readType, mapper, algorithm, proportionHeldOut, referenceFastaFile in keys: nodes = hash[(readType, mapper, algorithm, proportionHeldOut, referenceFastaFile)] recall = lambda c : float(c.attrib["recall"]) #float(c.attrib["totalTruePositives"])/float(c.attrib["totalHeldOut"]) if float(c.attrib["totalHeldOut"]) != 0 else 0 precision = lambda c : float(c.attrib["precision"]) # float(c.attrib["totalTruePositives"])/(float(c.attrib["totalTruePositives"]) + float(c.attrib["totalFalsePositives"])) if float(c.attrib["totalTruePositives"]) + float(c.attrib["totalFalsePositives"]) != 0 else 0 fScore = lambda c : 2 * precision(c) * recall(c) / (precision(c) + recall(c)) if precision(c) + recall(c) > 0 else 0 notCalled = lambda c : float(c.attrib["totalNoCalls"]) / (float(c.attrib["totalHeldOut"]) + float(c.attrib["totalNonHeldOut"])) actualCoverage = lambda c : float(c.attrib["actualCoverage"]) for coverage in coverageLevels: def r(f): i = map(f, nodes[coverage]) return "\t".join(map(str, (min(i), numpy.median(i), max(i)))) fH.write("\t".join([readType, mapper, algorithm, str(proportionHeldOut), str(coverage), r(fScore), r(recall), r(precision), r(notCalled), r(actualCoverage)]) + "\n") fH2.write("\t".join([readType, mapper, algorithm, str(proportionHeldOut)]) + "\t") f2 = lambda f, end : fH2.write("\t".join(map(lambda coverage : str(min(map(f, nodes[coverage]))) + "\t" + str(numpy.average(map(f, nodes[coverage]))) + "\t" + str(max(map(f, nodes[coverage]))), coverageLevels)) + end) f2(recall, "\t") f2(precision, "\t") f2(fScore, "\n") #Make ROC curves for coverage in coverageLevels: #Get the median true positive / median false positives recallByProbability = map(lambda c : map(float, c.attrib["recallByProbability"].split()), nodes[coverage]) precisionByProbability = map(lambda c : map(float, c.attrib["precisionByProbability"].split()), nodes[coverage]) def merge(curves, fn): return map(lambda i : fn(map(lambda curve : curve[i], curves)), range(len(curves[0]))) avgRecallByProbability = merge(recallByProbability, numpy.average) avgPrecisionByProbability = merge(precisionByProbability, numpy.average) while len(avgRecallByProbability) > 0 and avgRecallByProbability[-1] == 0.0: avgRecallByProbability = avgRecallByProbability[:-1] avgPrecisionByProbability = avgPrecisionByProbability[:-1] rocCurvesHash[(readType, mapper, algorithm, proportionHeldOut, coverage)] = (avgPrecisionByProbability, avgRecallByProbability) ####Ian todo ### #Place to create ROC / precision/recall plots variantCallingAlgorithms = list(variantCallingAlgorithms) variantCallingAlgorithms.sort() proportionsHeldOut = list(proportionsHeldOut) proportionsHeldOut.sort() for readType, mapper in product(readTypes, self.mappers): outf = open(os.path.join(self.outputDir, readType + "_" + mapper.__name__ + ".tsv"), "w") #Make grid plot for each combination of readType/mapper #Grid dimensions would be variant calling algorithms x proportion held out #On each plot we should show the roc curve (use falsePositiveRatesByProbability vs. truePositiveRatesByProbability) for the different coverages. for algorithm in variantCallingAlgorithms: for proportionHeldOut in proportionsHeldOut: for coverage in coverageLevels: avgPrecisionByProbability, avgRecallByProbability = rocCurvesHash[(readType, mapper.__name__, algorithm, proportionHeldOut, coverage)] outf.write("FPR\t{0}\t{1}\t{2}\t{3}\nTPR\t{0}\t{1}\t{2}\t{4}\n".format(str(algorithm), str(proportionHeldOut), str(coverage), "\t".join(map(str,avgPrecisionByProbability)), "\t".join(map(str,avgRecallByProbability)))) outf.close() if not os.path.exists(os.path.join(self.outputDir, readType + "_" + mapper.__name__)): os.mkdir(os.path.join(self.outputDir, readType + "_" + mapper.__name__)) system("Rscript nanopore/metaAnalyses/ROC_marginAlign.R {} {} {}".format(os.path.join(self.outputDir, readType + "_" + mapper.__name__ + ".tsv"), os.path.join(self.outputDir, readType + "_" + mapper.__name__) + "/", "_ROC_curves.pdf"))
Python
2D
mitenjain/nanopore
nanopore/metaAnalyses/coverageDepth.py
.py
3,529
99
from nanopore.metaAnalyses.abstractMetaAnalysis import AbstractMetaAnalysis from sonLib.bioio import system import os, sys, glob, subprocess, numpy from nanopore.analyses.utils import samToBamFile import pysam class Fastaseq(): """ fasta reader """ def __init__(self): self.id = None self.seq = '' self.length = '' @staticmethod def readline(linein): seqobj = Fastaseq() for line in linein: if len(line)==0: print >> sys.stderr, 'empty line' continue if line.startswith('>'): if seqobj.id is None: seqobj.id = line.rstrip() continue else: yield seqobj seqobj = Fastaseq() seqobj.id = line.rstrip() else: seqobj.seq += line.rstrip('\n\r').upper() yield seqobj class CoverageDepth(AbstractMetaAnalysis): """ Uses samtools depth to obtain and plot coverage depth per base across reference """ def __init__(self, outputDir, experiments): AbstractMetaAnalysis.__init__(self, outputDir, experiments) parentFolder = self.outputDir + "/" experiments = [] for readFastqFile, readType, referenceFastaFile, mapper, analyses, resultsDir in self.experiments: experiment = resultsDir.split("/")[-1] experiments.append(experiment) # Check and create bam, sorted bam, and indexed bam files bamFile = os.path.join(resultsDir, "mapping.bam") sortedbamFile = os.path.join(resultsDir, "mapping.sorted") depthFile = os.path.join(self.outputDir, experiment + "_Depth.txt") if not os.path.isfile(sortedbamFile): try: samToBamFile(os.path.join(resultsDir, "mapping.sam"), bamFile) pysam.sort(bamFile, sortedbamFile) pysam.index(sortedbamFile + ".bam") except: continue else: continue # if sorted bam file present then compute coverage and plot if os.path.isfile(sortedbamFile + ".bam"): try: system("samtools depth %s > %s" % (sortedbamFile + ".bam", depthFile)) covStats = parentFolder + experiment + "_Stats.out" fastaFile = open(referenceFastaFile, "r") depth_file = open(depthFile, "r") ref_seq = None for seq in Fastaseq.readline(fastaFile): ref_seq = seq.seq fastaFile.close() # macro numbers for coverage all_cov = map(int, subprocess.check_output('''awk '{split($0, a, "\t"); print a[3]}' %s''' % (depthFile), shell=True).strip().split("\n")) mean_cov = numpy.mean(all_cov) sd_cov = numpy.std(all_cov) #Threshold is 2X SD, for 95% sd_threshold = 2 * sd_cov cov_stats = open(covStats, "w") cov_stats.write("Position\tCoverage (mu=" + str(mean_cov) + "X, sd=" + str(sd_cov) + "X)\tKmer\n") prev_pos_cov = 0 # Counter for previous position coverage for line in depth_file: line = line.strip().split("\t") if int(line[2]) - prev_pos_cov >= sd_threshold: if int(line[1]) >= 5: cov_stats.write(str(line[1]) + "\t" + str(line[2]) + "\t" + str(ref_seq[(int(line[1])) - 5: int(line[1])]) + "\n") else: cov_stats.write(str(line[1]) + "\t" + str(line[2]) + "\t" + str(ref_seq[0: int(line[1])]) + "\n") prev_pos_cov = int(line[2]) # Reassign depth_file.close() cov_stats.close() system("Rscript nanopore/metaAnalyses/coverageDepth_plot.R {} {} {} {}".format(depthFile, os.path.join(self.outputDir, experiment + "_Coverage_Distribution.pdf"), os.path.join(self.outputDir, experiment + "_Coverage_Depth.pdf"), os.path.join(self.outputDir, experiment + "_Coverage_Outliers.tsv"))) except: continue
Python
2D
mitenjain/nanopore
nanopore/metaAnalyses/customTrackAssemblyHub.py
.py
4,927
132
from nanopore.metaAnalyses.abstractMetaAnalysis import AbstractMetaAnalysis from sonLib.bioio import system import os, sys, glob from nanopore.analyses.utils import samToBamFile import pysam class Fastaseq(): """ fasta reader """ def __init__(self): self.id = None self.seq = '' self.length = '' @staticmethod def readline(linein): seqobj = Fastaseq() for line in linein: if len(line)==0: print >> sys.stderr, 'empty line' continue if line.startswith('>'): if seqobj.id is None: seqobj.id = line.rstrip() continue else: yield seqobj seqobj = Fastaseq() seqobj.id = line.rstrip() else: seqobj.seq += line.rstrip('\n\r').upper() yield seqobj class CustomTrackAssemblyHub(AbstractMetaAnalysis): """moves mapping.sorted.bam and mapping.sorted.bam.bai files to a folder and creates trackDb.txt""" def __init__(self, outputDir, experiments): AbstractMetaAnalysis.__init__(self, outputDir, experiments) parentFolder = self.outputDir + "/" experiments = [] for readFastqFile, readType, referenceFastaFile, mapper, analyses, resultsDir in self.experiments: experiment = resultsDir.split("/")[-1] experiments.append(experiment) hubFastaDir = experiment.split(".fastq")[-1].split(".fa")[0][1:] outFolderReferenceFiles = parentFolder + hubFastaDir + "/" outFolderBamFiles = outFolderReferenceFiles + "bamFiles/" # Create hierarchical reference and bamfile folders if not os.path.exists(outFolderReferenceFiles): os.mkdir(outFolderReferenceFiles) if not os.path.exists(outFolderBamFiles): os.mkdir(outFolderBamFiles) # Check and create bam, sorted bam, and indexed bam files bamFile = os.path.join(resultsDir, "mapping.bam") sortedbamFile = os.path.join(resultsDir, "mapping.sorted") if not os.path.isfile(os.path.join(resultsDir, "mapping.bam")): try: samToBamFile(os.path.join(resultsDir, "mapping.sam"), bamFile) pysam.sort(bamFile, sortedbamFile) pysam.index(sortedbamFile + ".bam") except: continue # Copy files try: system("cp %s %s" % (os.path.join(resultsDir, "mapping.sorted.bam"), outFolderBamFiles + experiment + ".sorted.bam")) system("cp %s %s" % (os.path.join(resultsDir, "mapping.sorted.bam.bai"), outFolderBamFiles + experiment + ".sorted.bam.bai")) except: continue genomes = open(parentFolder + "genomes.txt", "a") for referenceFastaFile in self.referenceFastaFiles: if referenceFastaFile.endswith(".fa") or referenceFastaFile.endswith(".fasta"): header = referenceFastaFile.split("/")[-1].split(".fa")[0] system("cp %s %s" % (referenceFastaFile, parentFolder + header + "/")) # Create 2bit referenceFastaFile oldreferenceFastaFile = referenceFastaFile.split("/")[-1] newreferenceFastaFile = parentFolder + header + "/" + oldreferenceFastaFile ref2bit = newreferenceFastaFile.split(".fa")[0] + ".2bit" system("/cluster/bin/x86_64/faToTwoBit %s %s" % (newreferenceFastaFile, ref2bit)) # Get reference length for coordinates fastaFile = open(referenceFastaFile, "r") for seq in Fastaseq.readline(fastaFile): id = seq.id.split(" ")[0].replace(">", "") coord = len(seq.seq) fastaFile.close() # Fasta referenceFastaFile name without .fasta genomes.write("genome " + header + "\n") genomes.write("trackDb " + header + "/trackDb.txt\n") genomes.write("groups groups.txt\n") genomes.write("description " + header + "\n") genomes.write("twoBitPath " + header + "/" + header + ".2bit\n") genomes.write("organism " + header + "\n") genomes.write("defaultPos " + id + ":1-" + str(coord) + "\n") genomes.write("\n") track_label = 1 for experiment in experiments: hubFastaDir = experiment.split(".fastq")[-1].split(".fa")[0][1:] tracks = open(parentFolder + hubFastaDir + "/trackDb.txt", "a") label = experiment.split(".fastq")[0].split("_")[-1] readType = experiment.split(".fastq")[0].split("_")[-1] tracks.write("track " + str(track_label) + "_\n") tracks.write("longLabel " + experiment + "\n") shortLabel = experiment.strip().split("_")[-1] tracks.write("shortLabel " + readType + "_" + shortLabel + "\n") tracks.write("priority 10\n") tracks.write("visibility pack\n") tracks.write("colorByStrand 150,100,30 230,170,40\n") tracks.write("color 150,100,30\n") tracks.write("altColor 230,170,40\n") tracks.write("bigDataUrl bamFiles/" + experiment + ".sorted.bam\n") tracks.write("type bam\n") tracks.write("group " + readType + "\n") tracks.write("html assembly\n\n") track_label += 1 tracks.close() genomes.close() groups = open(parentFolder + "groups.txt", "a") groups.write("name readType\n") groups.write("label readType\n") groups.write("priority 1\n") groups.write("defaultIsClosed 0\n\n") groups.close()
Python
2D
mitenjain/nanopore
nanopore/metaAnalyses/vennDiagram.R
.R
11,873
286
#!/usr/bin/env Rscript # args <- commandArgs(trailingOnly = T) data <- read.table(args[1], header = T) library(methods) ############################################################################## #### R script to #### Produce Venn Diagrams with 1 to 5 groups #### an extension on the code from the limma package #### #### Written By: Matt Settles #### Postdoctoral Research Associate #### Washington State University #### ############################################################################## #### #### Change Log: #### Feb 8, 2008: #### formalized code #### Dec 23, 2008: #### added mixed type to vennCounts ############################################################################## #### #### Usage: #### source("http://bioinfo-mite.crb.wsu.edu/Rcode/Venn.R") #### can change colors now on 4 way plot ############################################################################## #################################### ## Function ellipse ## Add an elipse to the current plot "ellipse" <- function (center, radius, rotate, segments = 360, add = FALSE, xlab = "", ylab = "", las = par("las"), col = palette()[2], lwd = 2, lty = 1, ...) { # x' = x cosø + y sinø # y' = y cosø - x sinø if (!(is.vector(center) && 2 == length(center))) stop("center must be a vector of length 2") if (!(is.vector(radius) && 2 == length(radius))) stop("radius must be a vector of length 2") angles <- (0:segments) * 2 * pi/segments rotate <- rotate*pi/180 ellipse <- cbind(radius[1] * cos(angles), radius[2] * sin(angles)) if(rotate != 0) ellipse <- cbind( ellipse[,1]*cos(rotate) + ellipse[,2]*sin(rotate), ellipse[,2]*cos(rotate) - ellipse[,1]*sin(rotate) ) ellipse <- cbind(center[1]+ellipse[,1], center[2]+ellipse[,2]) if (add) lines(ellipse, col = col, lwd = lwd, lty = lty, ...) else plot(ellipse, type = "l", xlim = c(-4, 4), ylim = c(-4, 4), xlab = "", ylab = "", axes = FALSE, col = col, lwd = lwd, lty = lty, ...) } ################################### ## Function vennCounts ## Produce venn table object "vennCounts" <- function (x, include = "both") { x <- as.matrix(x) include <- match.arg(include, c("both", "up", "down","mixed")) x <- sign(switch(include, both = abs(x), up = x > 0, down = x < 0, mixed = x)) nprobes <- nrow(x) ncontrasts <- ncol(x) names <- colnames(x) if (is.null(names)) names <- paste("Group", 1:ncontrasts) noutcomes <- 2^ncontrasts if ( include == "mixed" ) noutcomes <- 3^ncontrasts outcomes <- matrix(0, noutcomes, ncontrasts) colnames(outcomes) <- names for (j in 1:ncontrasts) { if( include == "mixed"){ outcomes[, j] <- rep(-1:1, times = 3^(j - 1), each = 3^(ncontrasts - j)) } else { outcomes[, j] <- rep(0:1, times = 2^(j - 1), each = 2^(ncontrasts - j)) } } xlist <- list() for (i in 1:ncontrasts) { if( include == "mixed"){ xlist[[i]] <- factor(x[, ncontrasts - i + 1], levels = c(-1,0, 1)) } else { xlist[[i]] <- factor(x[, ncontrasts - i + 1], levels = c(0, 1)) } } counts <- as.vector(table(xlist)) structure(cbind(outcomes, Counts = counts), class = "vennCounts") } "vennDiagram" <- function (object, include = "both", names, mar = rep(1, 4), cex = 1.5, lwd = 2, circle.col, counts.col, show.include, ...) { if (!is(object, "vennCounts")) { if (length(include) > 2) stop("Cannot plot Venn diagram for more than 2 sets of counts") if (length(include) == 2) object.2 <- vennCounts(object, include = include[2]) object <- vennCounts(object, include = include[1]) } else if (length(include == 2)) include <- include[1] nsets <- ncol(object) - 1 if (nsets > 4) stop("Can't plot Venn diagram for more than 4 sets") if (missing(names)) names <- colnames(object)[1:nsets] counts <- object[, "Counts"] if (length(include) == 2) if (length(include) == 2 && nsets < 4) counts.2 <- object.2[, "Counts"] #Setup colors if (missing(circle.col) & nsets == 4) circle.col <- c("red","blue","orange","green") else circle.col <- par("col") if (length(circle.col) < nsets) circle.col <- rep(circle.col, length.out = nsets) if (missing(counts.col) & nsets == 4) counts.col <- c("red","blue","orange","green") else counts.col <- par("col") if (length(counts.col) < length(include) & nsets < 4) counts.col <- rep(counts.col, length.out = length(include)) else if (length(counts.col) < nsets) counts.col <- rep(counts.col, length.out = nsets) if (missing(show.include)) show.include <- as.logical(length(include) - 1) xcentres <- list(0, c(-1, 1), c(-1, 1, 0), c(-0.2,0.2,-1.05,1.05))[[nsets]] ycentres <- list(0, c(0, 0), c(1/sqrt(3), 1/sqrt(3), -2/sqrt(3)),c(.20,.20,-0.35,-0.35))[[nsets]] centers <- cbind(xcentres,ycentres) r1 <- c(1.5, 1.5, 1.5, 1.5)[nsets] r2 <- c(1.5, 1.5, 1.5, 2.7)[nsets] radius <- c(r1,r2) rotate <- list(0, c(0,0), c(0,0,0), c(-45,45,-45,45))[[nsets]] xtext <- list(-1.2, c(-1.2, 1.2), c(-1.2, 1.2, 0),c(-3.2,3.2,-3.2,3.2))[[nsets]] ytext <- list(1.8, c(1.8, 1.8), c(2.4, 2.4, -3),c(3.2,3.2,-3.2,-3.2))[[nsets]] old.par <- par(mar = mar) on.exit(par(old.par)) plot(x = 0, y = 0, type = "n", xlim = c(-4.0, 4.0), ylim = c(-4.0, 4.0), xlab = "", ylab = "", axes = FALSE, ...) for (circle in 1:nsets) { ellipse(centers[circle,],radius,rotate[circle],add=TRUE, , lwd = lwd, col = circle.col[circle]) text(xtext[circle], ytext[circle], names[circle], #pos=ifelse(circle != as.integer(circle/2)*2,4,2), offset = 0.5, col = circle.col[circle], cex = cex) } # rect(-3.5, -3.5, 3.5, 3.5) switch(nsets, { #rect(-3, -2.5, 3, 2.5) printing <- function(counts, cex, adj, col, leg) { col <- col[1] text(2.3, -2.1, counts[1], cex = cex, col = col, adj = adj) text(0, 0, counts[2], cex = cex, col = col, adj = adj) if (show.include) text(-2.3, -2.1, leg, cex = cex, col = col, adj = adj) } }, { #rect(-3, -2.5, 3, 2.5) printing <- function(counts, cex, adj, col, leg) { col <- col[1] text(2.3, -2.1, counts[1], cex = cex, col = col, adj = adj) text(1.5, 0.1, counts[2], cex = cex, col = col, adj = adj) text(-1.5, 0.1, counts[3], cex = cex, col = col, adj = adj) text(0, 0.1, counts[4], cex = cex, col = col, adj = adj) if (show.include) text(-2.3, -2.1, leg, cex = cex, col = col, adj = adj) } }, { #rect(-3, -3.5, 3, 3.3) printing <- function(counts, cex, adj, col, leg) { col <- col[1] text(2.5, -3, counts[1], cex = cex, col = col, adj = adj) text(0, -1.7, counts[2], cex = cex, col = col, adj = adj) text(1.5, 1, counts[3], cex = cex, col = col, adj = adj) text(0.75, -0.35, counts[4], cex = cex, col = col, adj = adj) text(-1.5, 1, counts[5], cex = cex, col = col, adj = adj) text(-0.75, -0.35, counts[6], cex = cex, col = col, adj = adj) text(0, 0.9, counts[7], cex = cex, col = col, adj = adj) text(0, 0, counts[8], cex = cex, col = col, adj = adj) if (show.include) text(-2.5, -3, leg, cex = cex, col = col, adj = adj) } }, { #rect(-3.5, -3.5, 3.5, 3.5) printing <- function(counts, cex, adj, col, leg) { text(0, -3, counts[1], cex = cex, col = "black", adj = adj) text(2.5, 0, counts[2], cex = cex, col = col[4], adj = adj) lines(c(2.25,2.75),c(-0.2,-0.2),col=col[4]) text(-2.5, 0, counts[3], cex = cex, col = col[3], adj = adj) lines(c(-2.75,-2.25),c(-0.2,-0.2),col=col[3]) text(0, -2.0, counts[4], cex = cex, col = "black", adj = adj) lines(c(-0.25,0.25),c(-2.2,-2.2),col=col[3]) lines(c(-0.25,0.25),c(-2.25,-2.25),col=col[4]) text(1.3, 2.1, counts[5], cex = cex, col = col[2], adj = adj) lines(c(1.05,1.55),c(1.9,1.9),col=col[2]) text(1.7, 1.2, counts[6], cex = cex, col = "black", adj = adj) lines(c(1.45,1.95),c(1.0,1.0),col=col[2]) lines(c(1.45,1.95),c(0.95,0.95),col=col[4]) text(-1.6, -1.1, counts[7], cex = cex, col = "black", adj = adj) lines(c(-1.85,-1.35),c(-1.3,-1.3),col=col[2]) lines(c(-1.85,-1.35),c(-1.35,-1.35),col=col[3]) text(-0.8, -1.55, counts[8], cex = cex, col = "black", adj = adj) lines(c(-0.55,-1.05),c(-1.75,-1.75),col=col[2]) lines(c(-0.55,-1.05),c(-1.8,-1.8),col=col[3]) lines(c(-0.55,-1.05),c(-1.85,-1.85),col=col[4]) text(-1.3, 2.1, counts[9], cex = cex, col = col[1], adj = adj) lines(c(-1.55,-1.05),c(1.9,1.9),col=col[1]) text(1.6, -1.1, counts[10], cex = cex, col = "black", adj = adj) lines(c(1.85,1.35),c(-1.3,-1.3),col=col[1]) lines(c(1.85,1.35),c(-1.35,-1.35),col=col[4]) text(-1.7, 1.2, counts[11], cex = cex, col = "black", adj = adj) lines(c(-1.45,-1.95),c(1.0,1.0),col=col[1]) lines(c(-1.45,-1.95),c(0.95,0.95),col=col[3]) text(0.8, -1.55, counts[12], cex = cex, col = "black", adj = adj) lines(c(0.55,1.05),c(-1.75,-1.75),col=col[1]) lines(c(0.55,1.05),c(-1.8,-1.8),col=col[3]) lines(c(0.55,1.05),c(-1.85,-1.85),col=col[4]) text(0, 1.6, counts[13], cex = cex, col = "black", adj = adj) lines(c(-0.25,0.25),c(1.4,1.4),col=col[1]) lines(c(-0.25,0.25),c(1.35,1.35),col=col[2]) text(0.9, 0.5, counts[14], cex = cex, col = "black", adj = adj) lines(c(1.15,0.65),c(0.3,0.3),col=col[1]) lines(c(1.15,0.65),c(0.25,0.25),col=col[2]) lines(c(1.15,0.65),c(0.2,0.2),col=col[4]) text(-0.9, 0.5, counts[15], cex = cex, col = "black", adj = adj) lines(c(-1.15,-0.65),c(0.3,0.3),col=col[1]) lines(c(-1.15,-0.65),c(0.25,0.25),col=col[2]) lines(c(-1.15,-0.65),c(0.2,0.2),col=col[3]) text(0, -0.5, counts[16], cex = cex, col = "black", adj = adj) lines(c(-0.25,0.25),c(-0.7,-0.7),col=col[1]) lines(c(-0.25,0.25),c(-0.75,-0.75),col=col[2]) lines(c(-0.25,0.25),c(-0.8,-0.8),col=col[3]) lines(c(-0.25,0.25),c(-0.85,-0.85),col=col[4]) } } ) adj <- c(0.5, 0.5) if (length(include) == 2 & nsets < 4) adj <- c(0.5, 0) printing(counts, cex, adj, counts.col, include[1]) if (length(include) == 2 & nsets < 4) printing(counts.2, cex, c(0.5, 1), counts.col[2], include[2]) invisible() } if (dim(data)[2] > 0) { pdf(args[2]) x <- vennCounts(data[,3:dim(data)[2]]) vennDiagram(x) x[,dim(x)[2]] <- round(100 * x[,dim(x)[2]] / sum(x[,dim(x)[2]]), 2) vennDiagram(x) dev.off() }
R
2D
mitenjain/nanopore
nanopore/metaAnalyses/unmappedKmerAnalysis.py
.py
2,617
52
from nanopore.metaAnalyses.abstractUnmappedAnalysis import AbstractUnmappedMetaAnalysis import os, sys from jobTree.src.bioio import system import itertools from collections import Counter from math import log class UnmappedKmerAnalysis(AbstractUnmappedMetaAnalysis): """Calculates kmer statistics for all reads (in all samples) not mapped by any mapper """ def countKmers(self, seq): kmers = Counter() for i in xrange(self.kmerSize, len(seq)): if "N" not in seq[ i - self.kmerSize : i ]: kmers[ seq[ i - self.kmerSize : i ] ] += 1 return kmers def run(self, kmerSize=5): self.kmerSize = kmerSize for readType in self.readTypes: mappedKmers, unmappedKmers = Counter(), Counter() for read in self.reads: if read.readType == readType and read.is_mapped: mappedKmers += self.countKmers(read.seq) elif read.readType == readType: unmappedKmers += self.countKmers(read.seq) mappedSize, unmappedSize = sum(mappedKmers.values()), sum(unmappedKmers.values()) outf = open(os.path.join(self.getLocalTempDir(), readType + "_kmer_counts.txt"), "w") outf.write("kmer\tmappableCount\tmappableFraction\tunmappableCount\tunmappableFraction\tlogFoldChange\n") for kmer in itertools.product("ATGC",repeat=5): kmer = "".join(kmer) if mappedSize > 0: mappedFraction = 1.0 * mappedKmers[kmer] / mappedSize else: mappedFraction = 0 if unmappedSize > 0: unmappedFraction = 1.0 * unmappedKmers[kmer] / unmappedSize else: unmappedFraction = 0 if unmappedFraction == 0: foldChange = "-Inf" elif mappedFraction == 0: foldChange = "Inf" else: foldChange = -log(mappedFraction / unmappedFraction) outf.write("\t".join(map(str,[kmer, mappedKmers[kmer], mappedFraction, unmappedKmers[kmer], unmappedFraction, foldChange]))+"\n") outf.close() system("Rscript nanopore/metaAnalyses/mappable_kmer_analysis.R {} {} {} {}".format(os.path.join(self.getLocalTempDir(), readType + "_kmer_counts.txt"), os.path.join(self.outputDir, readType + "_unmapped_kmer_counts.txt"), os.path.join(self.outputDir, readType + "_unmapped_top_bot_sigkmer_counts.txt"), os.path.join(self.outputDir, readType + "_volcano_plot.pdf")))
Python
2D
mitenjain/nanopore
nanopore/metaAnalyses/coveragePlots.R
.R
4,741
115
#!/usr/bin/env Rscript args <- commandArgs(trailingOnly = T) if (file.info(args[1])$size != 0) { cols <- max(count.fields(args[1], sep=",")) dist <- read.table(args[1], fill=T, sep=",", row.names=1, col.names=paste("V",seq_len(cols))) dist <- dist[order(rownames(dist)),] } if (! is.null(dim(dist)) && dim(dist)[2] > 2 && dim(dist)[1] > 1) { tmp <- dist dist <- vector() #throw out rows with single-value columns for (i in 1:length(rownames(tmp))) { r <- tmp[i,] if (length(r[!is.na(r)]) > 1) { dist <- rbind(dist, r) } } pdf(args[3]) hists <- list() xmax <- 0 ymax <- 0 b <- 0 for (i in 1:length(rownames(dist))){ b <- max(b, nclass.FD(dist[i,][!is.na(dist[i,])])) } for (i in 1:length(rownames(dist))){ hists[[i]] <- hist(dist[i,][!is.na(dist[i,])], plot=F, breaks=b) xmax <- max(xmax, hists[[i]]$mids) ymax <- max(ymax, hists[[i]]$counts) } colmap <- expand.grid(1:8, 15:(15+ceiling(length(hists)/8))) #whatever plot(1, xlim=c(0,xmax), ylim=c(0,ymax), main=paste(args[2],"Identity by Mapper", sep="\n"), xlab="Identity", type="n", ylab="Frequency") q <- vector() for (i in 1:length(hists)) { x <- hists[[i]] points(x$mids, x$counts, col=colmap[i,1], pch=colmap[i,2], cex=0.4) lines(x$mids, x$counts, col=colmap[i,1], pch=colmap[i,2]) q[i] <- paste(formatC(round(100*mean(dist[i,][!is.na(dist[i,])]),1),format="f",digits=1), sep= "") } col <- rep(c(rep(1:8, length.out=length(hists)),rep("NA",times=length(hists))), times=ceiling(length(hists)/8)) legend(x="top", col=col, pch=colmap[,2], legend=cbind(rownames(dist),q), ncol=2, title="\t\tAverage % Identity", cex=0.55,bty="n") #hacky way to determine the number of replicates seen num <- 1 for (i in 1:length(rownames(dist))){ tmp <- as.numeric(strsplit(rownames(dist)[i], "[.]")[[1]][2]) if (! is.na(tmp)) { num <- max(tmp, num) } } if (num > 1) { #this plot plots the replicates as the same color with different pch and one (average) line #build a new color map where we have one color for every aligner group colmap <- vector() for (i in 1:8){ colmap <- c(colmap, rep(i, times=num)) } pchmap <- rep(15:(15+num-1), times=ceiling(length(hists)/num)) plot(1, xlim=c(0,xmax), ylim=c(0,ymax), main=paste(args[2],"Identity by Mapper", sep="\n"), xlab="Identity", type="n", ylab="Frequency") if (length(hists) > num){ for (i in seq(num, length(hists), num)) { for (j in 0:(num-1)) { x <- hists[[i-j]] points(x$mids, x$counts, col=colmap[i-j], pch=pchmap[i-j], cex=0.4) lines(x$mids, x$counts, col=colmap[i-j]) } } avgs <- vector() names <- vector() for (i in seq(num, length(hists), num)){ tmp <- mean(c(dist[i,][!is.na(dist[i,])], dist[i-1,][!is.na(dist[i-1,])], dist[i-2,][!is.na(dist[i-2,])])) tmp <- paste(formatC(round(100*tmp,1),format="f",digits=1), sep= "") avgs <- c(avgs, tmp) names <- c(names, rownames(dist)[i-2]) } coltmp <- rep(c(1:length(names), rep("NA", times=length(names))), times=10) legend("top", col=coltmp, pch=pchmap, cex=0.55, legend=cbind(names, avgs), ncol=2, title="\t\tAverage % Identity", bty="n") #now we plot them added together hists2 <- list() xmax2 <- 0 ymax2 <- 0 for (i in seq(1, length(rownames(dist)), num)){ t <- ceiling(i/num) tmp <- vector() for (j in 0:(num-1)) { tmp <- c(tmp, dist[i+j,][!is.na(dist[i+j,])]) } hists2[[t]] <- hist(tmp, plot=F, breaks=b) xmax2 <- max(xmax2, hists2[[t]]$mids) ymax2 <- max(ymax2, hists2[[t]]$counts) } plot(1, xlim=c(0,xmax2), ylim=c(0,ymax2), main=paste(args[2],"Identity by Mapper", sep="\n"), xlab="Identity", type="n", ylab="Frequency") for (i in 1:length(hists2)) { x <- hists2[[i]] points(x$mids, x$counts, col=i, cex=0.4, pch=16) lines(x$mids, x$counts, col=i) } legend("top", col=1:8, pch=c(rep("-", times=length(hists2)), rep(NA, times=length(hists2))), cex=0.55, legend=cbind(names, avgs), ncol=2, title="\t\tAverage % Identity", bty="n") } } dev.off() }
R
2D
mitenjain/nanopore
nanopore/metaAnalyses/coverageDepth_plot.R
.R
1,274
41
#!/usr/bin/env Rscript args <- commandArgs(trailingOnly = T) library(lattice) inFile <- args[1] pdf(args[2]) library(boot) depthFile = read.delim(inFile, sep="\t", header=F) obs_cov <- unlist(depthFile[3]) avg <- mean(unlist(depthFile[3])) dev <- sd(unlist(depthFile[3])) samples <- length(obs_cov) outlier_pos <- boxplot.stats(c(unlist(obs_cov, dpois(obs_cov, avg))))$out outliers <- length(outlier_pos) proportion <- round((outliers / length(unlist(depthFile[3]))) * 100, 2) xmax <- max(obs_cov) + 1000 par(mfrow <- c(1,1)) hist(obs_cov, freq=F, main=paste("Coverage distribution\n Number of under-represented sites = ", outliers, "(", proportion, "%)"), xlab="Coverage", ylab="Density", xlim=c(0, xmax), col = "green", breaks="FD") library(MASS) d <- fitdistr(obs_cov, "Weibull") lines(1:max(obs_cov) + 1000,dweibull(1:max(obs_cov) + 1000,shape=d$estimate[1],scale=d$estimate[2]), col="red") legend("topleft",legend=c("Expected","Observed"),col=c("red","green"),pch="-") dev.off() pdf(args[3]) par(mfrow <- c(1,1)) plot(spline(unlist(depthFile[2]), obs_cov/max(obs_cov)), main="Coverage across reference", xlab="Position across reference", ylab="Normalized Coverage", type = "l", col = "red") dev.off() write(paste(names(outlier_pos), outlier_pos), args[4])
R
2D
mitenjain/nanopore
nanopore/mappers/combinedMapper.py
.py
2,410
58
from nanopore.mappers.abstractMapper import AbstractMapper from nanopore.mappers.last_params import LastParams from nanopore.mappers.lastzParams import LastzParams from nanopore.mappers.bwa_params import BwaParams from nanopore.mappers.blasr_params import BlasrParams import pysam import os from nanopore.analyses.utils import combineSamFiles class CombinedMapper(AbstractMapper): def run(self): #Make child mapping job for each mapper mappers=[ LastParams, LastzParams, BwaParams, BlasrParams] tempSamFiles = [] tempHmmFiles = [] for mapper in mappers: tempSamFiles.append(os.path.join(self.getGlobalTempDir(), "mapping_%s.sam" % mapper.__name__)) tempHmmFiles.append(os.path.join(self.getGlobalTempDir(), "mapping_%s.hmm" % mapper.__name__)) self.addChildTarget(mapper(self.readFastqFile, self.readType, self.referenceFastaFile, tempSamFiles[-1], tempHmmFiles[-1])) #Now make a follow on to cat together the different alignments self.setFollowOnFn(combineSamFiles, args=(tempSamFiles[0], tempSamFiles[1:], self.outputSamFile)) class CombinedMapperChain2(AbstractMapper): def run(self): self.chainSamFile() class CombinedMapperChain(AbstractMapper): def run(self, followOnMapper=CombinedMapperChain2): self.addChildTarget(CombinedMapper(self.readFastqFile, self.readType, self.referenceFastaFile, self.outputSamFile, self.emptyHmmFile)) self.setFollowOnTarget(followOnMapper(self.readFastqFile, self.readType, self.referenceFastaFile, self.outputSamFile, self.emptyHmmFile)) class CombinedMapperRealign2(AbstractMapper): def run(self): self.realignSamFile() class CombinedMapperRealign(CombinedMapperChain): def run(self): CombinedMapperChain.run(self, followOnMapper=CombinedMapperRealign2) class CombinedMapperRealignEm2(AbstractMapper): def run(self): self.realignSamFile(doEm=True) class CombinedMapperRealignEm(CombinedMapperChain): def run(self): CombinedMapperChain.run(self, followOnMapper=CombinedMapperRealignEm2) class CombinedMapperRealignTrainedModel2(AbstractMapper): def run(self): self.realignSamFile(useTrainedModel=True) class CombinedMapperRealignTrainedModel(CombinedMapperChain): def run(self): CombinedMapperChain.run(self, followOnMapper=CombinedMapperRealignTrainedModel2)
Python
2D
mitenjain/nanopore
nanopore/mappers/blasr_params.py
.py
1,283
40
from nanopore.mappers.blasr import Blasr from sonLib.bioio import system import os class BlasrParams(Blasr): def run(self): Blasr.run(self, args="-sdpTupleSize 8 -bestn 1 -m 0") #system("blasr %s %s -sdpTupleSize 8 -bestn 1 -clipping hard -nproc 8 -sam -out %s -m 0" % (self.readFastqFile, self.referenceFastaFile, self.outputSamFile)) class BlasrParamsChain(BlasrParams): def run(self): BlasrParams.run(self) self.chainSamFile() class BlasrParamsRealign(BlasrParams): def run(self): BlasrParams.run(self) self.realignSamFile() class BlasrParamsRealignEm(BlasrParams): def run(self): BlasrParams.run(self) self.realignSamFile(doEm=True) class BlasrParamsRealignTrainedModel(BlasrParams): def run(self): BlasrParams.run(self) self.realignSamFile(useTrainedModel=True) class BlasrParamsRealignTrainedModel20(BlasrParams): def run(self): BlasrParams.run(self) self.realignSamFile(useTrainedModel=True, trainedModelFile="blasr_hmm_20.txt") class BlasrParamsRealignTrainedModel40(BlasrParams): def run(self): BlasrParams.run(self) self.realignSamFile(useTrainedModel=True, trainedModelFile="blasr_hmm_40.txt")
Python
2D
mitenjain/nanopore
nanopore/mappers/bwa.py
.py
974
30
from nanopore.mappers.abstractMapper import AbstractMapper from sonLib.bioio import system import os class Bwa(AbstractMapper): def run(self, args=""): localReferenceFastaFile = os.path.join(self.getLocalTempDir(), "ref.fa") #Because BWA builds these crufty index files, copy to a temporary directory system("cp %s %s" % (self.referenceFastaFile, localReferenceFastaFile)) system("bwa index %s" % localReferenceFastaFile) system("bwa mem %s %s %s > %s" % (args, localReferenceFastaFile, self.readFastqFile, self.outputSamFile)) class BwaChain(Bwa): def run(self): Bwa.run(self) self.chainSamFile() class BwaRealign(Bwa): def run(self): Bwa.run(self) self.realignSamFile() class BwaRealignEm(Bwa): def run(self): Bwa.run(self) self.realignSamFile() class BwaRealignTrainedModel(Bwa): def run(self): Bwa.run(self) self.realignSamFile(useTrainedModel=True)
Python
2D
mitenjain/nanopore
nanopore/mappers/__init__.py
.py
0
0
null
Python
2D
mitenjain/nanopore
nanopore/mappers/lastzParams.py
.py
1,004
32
from nanopore.mappers.lastz import Lastz import pysam import os from nanopore.analyses.utils import pathToBaseNanoporeDir class LastzParams(Lastz): def run(self): #scoreFile = os.path.join(pathToBaseNanoporeDir(), "nanopore", "mappers", "last_em_575_M13_2D_scores.txt") #Lastz.run(self, args="--hspthresh=1200 --gappedthresh=1500 --seed=match12 --scores=%s" % scoreFile) Lastz.run(self, args="--hspthresh=1800 --gap=100,100") class LastzParamsChain(LastzParams): def run(self): LastzParams.run(self) self.chainSamFile() class LastzParamsRealign(LastzParams): def run(self): LastzParams.run(self) self.realignSamFile() class LastzParamsRealignEm(LastzParams): def run(self): LastzParams.run(self) self.realignSamFile(doEm=True) class LastzParamsRealignTrainedModel(LastzParams): def run(self): LastzParams.run(self) self.realignSamFile(useTrainedModel=True)
Python
2D
mitenjain/nanopore
nanopore/mappers/blasr.py
.py
1,615
44
from nanopore.mappers.abstractMapper import AbstractMapper from nanopore.analyses.utils import getFastqDictionary from sonLib.bioio import system import os import pysam class Blasr(AbstractMapper): def run(self, args=""): tempSamFile = os.path.join(self.getLocalTempDir(), "temp.sam") system("blasr %s %s -sam -clipping hard %s > %s" % (self.readFastqFile, self.referenceFastaFile, args, tempSamFile)) #Blasr seems to corrupt the names of read sequences, so lets correct them. sam = pysam.Samfile(tempSamFile, "r" ) outputSam = pysam.Samfile(self.outputSamFile, "wh", template=sam) readSequences = getFastqDictionary(self.readFastqFile) #Hash of names to sequences for aR in sam: #Iterate on the sam lines and put into buckets by read if aR.qname not in readSequences: newName = '/'.join(aR.qname.split('/')[:-1]) if newName not in readSequences: raise RuntimeError("Tried to deduce correct read name: %s, %s" % (newName, readSequences.keys())) aR.qname = newName outputSam.write(aR) outputSam.close() class BlasrChain(Blasr): def run(self): Blasr.run(self) self.chainSamFile() class BlasrRealign(Blasr): def run(self): Blasr.run(self) self.realignSamFile() class BlasrRealignEm(Blasr): def run(self): Blasr.run(self) self.realignSamFile(doEm=True) class BlasrRealignTrainedModel(Blasr): def run(self): Blasr.run(self) self.realignSamFile(useTrainedModel=True)
Python
2D
mitenjain/nanopore
nanopore/mappers/last_params.py
.py
1,208
40
from nanopore.mappers.abstractMapper import AbstractMapper from nanopore.mappers.last import Last from sonLib.bioio import system, fastaRead, fastqRead, fastaWrite import os class LastParams(Last): def run(self): Last.run(self, params="-s 2 -T 0 -Q 0 -a 1") class LastParamsChain(LastParams): def run(self): LastParams.run(self) self.chainSamFile() class LastParamsRealign(LastParams): def run(self): LastParams.run(self) self.realignSamFile() class LastParamsRealignEm(LastParams): def run(self): LastParams.run(self) self.realignSamFile(doEm=True, gapGamma=0.5, matchGamma=0.0) class LastParamsRealignTrainedModel(LastParams): def run(self): LastParams.run(self) self.realignSamFile(useTrainedModel=True) class LastParamsRealignTrainedModel20(LastParams): def run(self): LastParams.run(self) self.realignSamFile(useTrainedModel=True, trainedModelFile="blasr_hmm_20.txt") class LastParamsRealignTrainedModel40(LastParams): def run(self): LastParams.run(self) self.realignSamFile(useTrainedModel=True, trainedModelFile="blasr_hmm_40.txt")
Python
2D
mitenjain/nanopore
nanopore/mappers/lastz.py
.py
1,384
41
from nanopore.mappers.abstractMapper import AbstractMapper from sonLib.bioio import system, fastaRead from nanopore.analyses.utils import normaliseQualValues import pysam import os class Lastz(AbstractMapper): def run(self, args=""): tempFastqFile = os.path.join(self.getLocalTempDir(), "temp.fastq") normaliseQualValues(self.readFastqFile, tempFastqFile) system("lastz %s[multiple] %s %s --format=sam > %s" % (self.referenceFastaFile, tempFastqFile, args, self.outputSamFile)) try: pysam.Samfile(self.outputSamFile, "r" ).close() except ValueError: #Hack to make lastz work, creating SQ lines when no alignments are found fH = open(self.outputSamFile, 'a') for name, seq in fastaRead(open(self.referenceFastaFile, 'r')): fH.write("@SQ\tSN:%s\tLN:%s\n" % (name.split()[0], len(seq))) fH.close() class LastzChain(Lastz): def run(self): Lastz.run(self) self.chainSamFile() class LastzRealign(Lastz): def run(self): Lastz.run(self) self.realignSamFile() class LastzRealignEm(Lastz): def run(self): Lastz.run(self) self.realignSamFile(doEm=True) class LastzRealignTrainedModel(Lastz): def run(self): Lastz.run(self) self.realignSamFile(useTrainedModel=True)
Python
2D
mitenjain/nanopore
nanopore/mappers/last.py
.py
1,928
46
from nanopore.mappers.abstractMapper import AbstractMapper from sonLib.bioio import system, fastaRead, fastqRead, fastaWrite import os class Last(AbstractMapper): def run(self, params=""): localReferenceFastaFile = os.path.join(self.getLocalTempDir(), "ref.fa") #Because we don't want to have any crufty files created in the local temp dir. indexFile = os.path.join(self.getLocalTempDir(), "my-index") #Index file mafFile = os.path.join(self.getLocalTempDir(), "out.maf") #MAF file #Hack to make last work, creating SQ line fH = open(self.outputSamFile, 'w') for name, seq in fastaRead(open(self.referenceFastaFile, 'r')): fH.write("@SQ\tSN:%s\tLN:%s\n" % (name.split()[0], len(seq))) fH.close() #Make fasta file, as last fastq seems broken localReadFile = os.path.join(self.getLocalTempDir(), "reads.fa") #Index file fH = open(localReadFile, 'w') for name, seq, quals in fastqRead(self.readFastqFile): fastaWrite(fH, name, seq) fH.close() system("cp %s %s" % (self.referenceFastaFile, localReferenceFastaFile)) #Copy across the ref file system("lastdb %s %s" % (indexFile, localReferenceFastaFile)) #Build the index system("lastal %s %s %s > %s" % (params, indexFile, localReadFile, mafFile)) #Build the alignment system("maf-convert.py sam %s >> %s" % (mafFile, self.outputSamFile)) #Now convert sam file class LastChain(Last): def run(self): Last.run(self) self.chainSamFile() class LastRealign(Last): def run(self): Last.run(self) self.realignSamFile() class LastRealignEm(Last): def run(self): Last.run(self) self.realignSamFile(doEm=True) class LastRealignTrainedModel(Last): def run(self): Last.run(self) self.realignSamFile(useTrainedModel=True)
Python
2D
mitenjain/nanopore
nanopore/mappers/bwa_params.py
.py
667
27
from nanopore.mappers.bwa import Bwa from sonLib.bioio import system import os class BwaParams(Bwa): def run(self): Bwa.run(self, args="-x pacbio") class BwaParamsChain(BwaParams): def run(self): BwaParams.run(self) self.chainSamFile() class BwaParamsRealign(BwaParams): def run(self): BwaParams.run(self) self.realignSamFile() class BwaParamsRealignEm(BwaParams): def run(self): BwaParams.run(self) self.realignSamFile(doEm=True) class BwaParamsRealignTrainedModel(BwaParams): def run(self): BwaParams.run(self) self.realignSamFile(useTrainedModel=True)
Python
2D
mitenjain/nanopore
nanopore/mappers/abstractMapper.py
.py
2,064
40
from jobTree.scriptTree.target import Target from nanopore.analyses.utils import chainSamFile, realignSamFileTargetFn import os from sonLib.bioio import system from nanopore.analyses.utils import AlignedPair, getFastaDictionary, getFastqDictionary, getExonerateCigarFormatString, samIterator, pathToBaseNanoporeDir class AbstractMapper(Target): """Base class for mappers. Inherit this class to create a mapper """ def __init__(self, readFastqFile, readType, referenceFastaFile, outputSamFile, emptyHmmFile=None): Target.__init__(self) self.readFastqFile = readFastqFile self.referenceFastaFile = referenceFastaFile self.outputSamFile = outputSamFile self.readType = readType self.emptyHmmFile=emptyHmmFile def chainSamFile(self): """Converts the sam file so that there is at most one global alignment of each read """ tempSamFile = os.path.join(self.getLocalTempDir(), "temp.sam") system("cp %s %s" % (self.outputSamFile, tempSamFile)) chainSamFile(tempSamFile, self.outputSamFile, self.readFastqFile, self.referenceFastaFile) def realignSamFile(self, gapGamma=0.5, matchGamma=0.0, doEm=False, useTrainedModel=False, trainedModelFile="blasr_hmm_0.txt"): """Chains and then realigns the resulting global alignments. """ tempSamFile = os.path.join(self.getGlobalTempDir(), "temp.sam") if useTrainedModel and doEm: raise RuntimeError("Attempting to train stock model") system("cp %s %s" % (self.outputSamFile, tempSamFile)) if doEm: hmmFile = self.emptyHmmFile elif useTrainedModel: hmmFile = os.path.join(pathToBaseNanoporeDir(), "nanopore", "mappers", trainedModelFile) else: hmmFile = None self.addChildTargetFn(realignSamFileTargetFn, args=(tempSamFile, self.outputSamFile, self.readFastqFile, self.referenceFastaFile, gapGamma, matchGamma, hmmFile, doEm))
Python
2D
mitenjain/nanopore
nanopore/analyses/qualimap.py
.py
903
21
from nanopore.analyses.abstractAnalysis import AbstractAnalysis from sonLib.bioio import system from nanopore.analyses.utils import samToBamFile, samIterator import os import pysam class QualiMap(AbstractAnalysis): def run(self): AbstractAnalysis.run(self) #Call base method to do some logging emptyQual = False for entry in samIterator(pysam.Samfile(self.samFile, "r")): if entry.qual is None: emptyQual = True if emptyQual is False: localBamFile = os.path.join(self.getLocalTempDir(), "mapping.bam") localSortedBamFile = os.path.join(self.getLocalTempDir(), "mapping.sorted") samToBamFile(self.samFile, localBamFile) pysam.sort(localBamFile, localSortedBamFile) system("qualimap bamqc -bam %s -outdir %s" % (localSortedBamFile + ".bam", self.outputDir)) self.finish()
Python
2D
mitenjain/nanopore
nanopore/analyses/substitutions.py
.py
4,018
82
from nanopore.analyses.abstractAnalysis import AbstractAnalysis from nanopore.analyses.utils import AlignedPair, getFastaDictionary, getFastqDictionary, samIterator import os import pysam import xml.etree.cElementTree as ET from jobTree.src.bioio import reverseComplement, prettyXml, system from itertools import product class SubstitutionMatrix(): """Represents a nucleotide substitution matrix. Also allows for recording matches against Ns. """ def __init__(self): self.matrix = [0.0]*25 #Includes alignments between wildcard characters. def addAlignedPair(self, refBase, readBase): self.matrix[self._index(refBase) * 5 + self._index(readBase)] += 1 def getCount(self, refBase, readBase): return self.matrix[self._index(refBase) * 5 + self._index(readBase)] def getFreqs(self, refBase, bases): """ Get list of relative frequencies for a refBase against all bases (passed as string) """ freqs = list() for b in bases: freqs.append(self.getCount(refBase, b)) if sum(freqs) == 0: return [ 0.0 ] * len(freqs) return [x / sum(freqs) for x in freqs] def getXML(self): def _identity(matches, mismatches): if matches + mismatches == 0: return "NaN" return matches/(mismatches+matches) matches = sum([ self.getCount(base, base) for base in "ACTG" ]) mismatches = sum([ sum([ self.getCount(refBase, readBase) for readBase in "ACTG" if readBase != refBase ]) for refBase in "ACTG" ]) node = ET.Element("substitutions", { "matches":str(matches), "mismatches":str(mismatches), "identity":str(_identity(matches, mismatches)) }) overallMatches = 0 overallMismatches = 0 for refBase in "ACGTN": matches = self.getCount(refBase, refBase) mismatches = sum([ self.getCount(refBase, readBase) for readBase in "ACTG" if readBase != refBase ]) baseNode = ET.SubElement(node, refBase, { "matches":str(matches), "mismatches":str(mismatches), "identity":str(_identity(matches, mismatches)) }) for readBase in "ACGTN": ET.SubElement(baseNode, readBase, { "count":str(self.getCount(refBase, readBase)) }) return node @staticmethod def _index(base): base = base.upper() if base not in "ACGT": return 4 return { 'A':0, 'C':1, 'G':2, 'T':3 }[base] class Substitutions(AbstractAnalysis): """Calculates stats on substitutions """ def run(self, kmer=5): AbstractAnalysis.run(self) #Call base method to do some logging refSequences = getFastaDictionary(self.referenceFastaFile) #Hash of names to sequences readSequences = getFastqDictionary(self.readFastqFile) #Hash of names to sequences sM = SubstitutionMatrix() #The thing to store the counts in sam = pysam.Samfile(self.samFile, "r" ) for aR in samIterator(sam): #Iterate on the sam lines for aP in AlignedPair.iterator(aR, refSequences[sam.getrname(aR.rname)], readSequences[aR.qname]): #Walk through the matches mismatches: sM.addAlignedPair(aP.getRefBase(), aP.getReadBase()) sam.close() #Write out the substitution info open(os.path.join(self.outputDir, "substitutions.xml"), 'w').write(prettyXml(sM.getXML())) bases = "ACGT" outf = open(os.path.join(self.outputDir, "subst.tsv"), "w") outf.write("A\tC\tG\tT\n") for x in bases: freqs = sM.getFreqs(x, bases) outf.write("{}\t{}\n".format(x, "\t".join(map(str,freqs)), "\n")) outf.close() analysis = self.outputDir.split("/")[-2].split("_")[-1] + "_Substitution_Levels" system("Rscript nanopore/analyses/substitution_plot.R {} {} {}".format(os.path.join(self.outputDir, "subst.tsv"), os.path.join(self.outputDir, "substitution_plot.pdf"), analysis)) self.finish()
Python
2D
mitenjain/nanopore
nanopore/analyses/coverage_plot.R
.R
5,998
108
#!/usr/bin/env Rscript args <- commandArgs(trailingOnly = T) #thanks SO: http://stackoverflow.com/questions/6602881/text-file-to-list-in-r raw <- strsplit(readLines(args[1]), "[[:space:]]+") data <- lapply(raw, tail, n = -1) names(data) <- lapply(raw, head, n = 1) data <- lapply(data, as.numeric) library(lattice) for (i in 1:length(data)) { if ( sum(data[[i]], na.rm=T) == 0 ) { quit() } } if ( length(data$MappedReadLengths) > 1 && length(data$UnmappedReadLengths) > 1) { #open a pdf pdf(args[2]) par(mfrow=c(2,2)) #plot the mapped/unmapped read lengths #future - stack them; remove very long unmapped reads? lengths <- c(data$MappedReadLengths, data$UnmappedReadLengths) lengths.sort <- lengths[order(lengths)] #remove the 5% longest reads so they don't skew the graph xmax <- lengths.sort[round(0.95*length(lengths.sort))] b <- max(nclass.FD(data$MappedReadLengths), nclass.FD(data$UnmappedReadLengths)) m <- hist(data$MappedReadLengths, breaks = b, plot=F) u <- hist(data$UnmappedReadLengths, breaks = b, plot=F) plot(m, main=paste("Mapped Read Length Distribution\nn = ", length(data$MappedReadLengths), sep=" "), xlab="Read Length", xlim=c(0,xmax), cex.main=0.8) plot(u, main=paste("Unmapped Read Length Distribution\nn = ", length(data$UnmappedReadLengths), sep=" "), xlab="Read Length", xlim=c(0,xmax), cex.main=0.8) #plot read coverage distribution hist(data$ReadCoverage, breaks="FD", main="Read Coverage Distribution", xlab="Read Coverage", cex.main=0.8) hist(data$ReadIdentity, breaks="FD", main="Read Identity Distribution", xlab="Read Identity", cex.main=0.8) #put new plots on next page par(mfrow=c(1,1)) #stacked histogram of mapped/unmapped length distribution ymax <- max(u$counts, m$counts) plot(m, col=rgb(1,0,0,0.5), xlim=c(0,xmax), ylim=c(0,ymax), main="Mapped and Unmapped Read Length Distributions", xlab="Read Length") plot(u, col=rgb(0,0,1,0.5), add=T, xlim=c(0,xmax), ylim=c(0,ymax), main="", xlab="", ylab="") legend("topleft", pch=15, legend=c(paste("Mapped n =", length(data$MappedReadLengths)), paste("Unmapped n =", length(data$UnmappedReadLengths))), col=c(rgb(1,0,0),rgb(0,0,1))) p1 <- xyplot(data$ReadIdentity~data$MappedReadLengths, main=list("Read Identity vs.\nRead Length", cex=0.95), xlab="Read Length", ylab="Read Identity", grid=T, panel=panel.smoothScatter) p2 <- xyplot((data$InsertionsPerBase+data$DeletionsPerBase)~data$MappedReadLengths, main=list("Indels Per Aligned Base vs.\nRead Length", cex=0.95), xlab="Read Length", ylab="Indels Per Base", grid=T, panel=panel.smoothScatter) p3 <- xyplot(data$MismatchesPerReadBase~data$MappedReadLengths, main=list("Mismatches Per Aligned Base vs.\nRead Length", cex=0.95), ylab="Mismatches Per Aligned Base", xlab="Read Length", grid=T, panel=panel.smoothScatter) #print the graphs print(p1, position=c(0, 0.5, 0.5, 1), more=T) print(p2, position=c(0.5, 0.5, 1, 1), more=T) print(p3, position=c(0, 0, 0.5, 0.5)) #now time to do more graphs #filter out any read identities that are outside of 3 sd's from mean for fit lines #but still plot the points m <- mean(data$ReadIdentity) s <- sd(data$ReadIdentity) inliers <- which(data$ReadIdentity >= m - 3 * s & data$ReadIdentity <= m + 3 * s) p1 <- xyplot(data$MismatchesPerReadBase~(data$InsertionsPerBase+data$DeletionsPerBase), main=list("Mismatches Per Aligned Base vs.\nIndels Per Aligned Base", cex=0.95), xlab="Indels Per Aligned Base", ylab="Mismatches Per Aligned Base", grid=T, panel=function(...){ panel.smoothScatter(...) panel.lmline(..., lwd=1.2) }, key=simpleKey(paste("R^2 =", as.character(round(summary.lm( lm(data$MismatchesPerReadBase~(data$InsertionsPerBase+data$DeletionsPerBase)))$adj.r.squared,3)), sep=" "), points=F, corner=c(0,1), cex=0.9)) p2 <- xyplot((data$InsertionsPerBase+data$DeletionsPerBase)~data$ReadIdentity, main=list("Indels Per Aligned Base vs.\nRead Identity", cex=0.95), xlab="Read Identity", ylab="Indels Per Base", grid=T, panel=function(...){ panel.smoothScatter(...) panel.abline(lwd=1.2, lm((data$InsertionsPerBase+data$DeletionsPerBase)[inliers]~data$ReadIdentity[inliers])) }, key=simpleKey(paste("R^2 =", as.character(round(summary.lm( lm((data$InsertionsPerBase+data$DeletionsPerBase)~data$ReadIdentity))$adj.r.squared,3)), sep=" "), points=F, corner=c(1,1), cex=0.9)) p3 <- xyplot(data$MismatchesPerReadBase~data$ReadIdentity, main=list("Mismatches Per Aligned Base vs.\nRead Identity",cex=0.95), ylab="Mismatches Per Aligned Base", xlab="Read Identity", grid=T, panel=function(...){ panel.smoothScatter(...) panel.abline(lwd=1.2, lm(data$MismatchesPerReadBase[data$ReadIdentity>0.6]~data$ReadIdentity[data$ReadIdentity>0.6])) }, key=simpleKey(paste("R^2 =", as.character(round(summary.lm( lm((data$InsertionsPerBase+data$DeletionsPerBase)~data$ReadIdentity))$adj.r.squared,3)), sep=" "), points=F, corner=c(0,0), cex=0.9)) p4 <- xyplot(data$InsertionsPerBase~data$DeletionsPerBase, main=list("Insertions Per Aligned Base vs.\nDeletions Per Aligned Base",cex=0.95), xlab="Deletions Per Aligned Base", ylab="Insertions Per Aligned Base", grid=T, panel=function(...){ panel.smoothScatter(...) panel.lmline(..., lwd=1.2) }, key=simpleKey(paste("R^2 =", as.character(round(summary.lm( lm(data$InsertionsPerBase~data$DeletionsPerBase))$adj.r.squared,3)), sep=" "), points=F, corner=c(0,1), cex=0.9)) #print the graphs print(p1, position=c(0, 0.5, 0.5, 1), more=T) print(p2, position=c(0.5, 0.5, 1, 1), more=T) print(p3, position=c(0, 0, 0.5, 0.5), more=T) print(p4, position=c(0.5, 0, 1, 0.5)) dev.off() }
R
2D
mitenjain/nanopore
nanopore/analyses/mutate_reference.py
.py
2,066
38
import os, sys, random from sonLib.bioio import fastaRead, fastaWrite ''' Inserts SNPs and 20% of SNPs as InDels Outputs Two files for every file - reference.fasta 1. mutated reference - reference_X_percent_SNPs_Y_percent_InDels.fasta 2. mutation index for true and mutated reference - reference_X_percent_SNPs_Y_percent_InDels_Index.txt ''' def mutateSequence(sequence, snpRate): #Does not preserve softmasking return "".join(map(lambda x : x.upper() if random.random() >= snpRate else random.choice(list(set(("A", 'C', 'G', 'T')) - set(x.upper()))), sequence)) def mutateReferenceSequences(referenceFastaFiles): updatedReferenceFastaFiles = referenceFastaFiles[:] for referenceFastaFile in referenceFastaFiles: if not "percent" in referenceFastaFile: mutation_rates = [0.01, 0.05, 0.10, 0.20] for mutation_rate in mutation_rates: indel_rate = 0.0 * mutation_rate # indel rate = 20% of Substitution rate i = mutation_rate * 100 j = indel_rate * 100 newReferenceFastaFile = referenceFastaFile.split(".fa")[0] + "_" + str(i) + "_percent_SNPs_" + str(j) + "_percent_InDels.fasta" mutationIndexFile = referenceFastaFile.split(".fa")[0] + "_" + str(i) + "_percent_SNPs_" + str(j) + "_percent_InDels.fasta_Index.txt" updatedReferenceFastaFiles.append(newReferenceFastaFile) if not os.path.exists(newReferenceFastaFile): fH = open(newReferenceFastaFile, 'w') fH2 = open(mutationIndexFile, 'w') for header, seq in fastaRead(referenceFastaFile): header = header.split()[0] mutatedSeq = mutateSequence(seq, mutation_rate) fastaWrite(fH, header, mutatedSeq) fastaWrite(fH2, header, seq) fastaWrite(fH2, header + "_mutated", mutatedSeq) fH.close() fH2.close() return updatedReferenceFastaFiles
Python
2D
mitenjain/nanopore
nanopore/analyses/consensus.py
.py
2,943
75
from nanopore.analyses.abstractAnalysis import AbstractAnalysis from sonLib.bioio import system from nanopore.analyses.utils import samToBamFile import os import pysam def formatConsensusFastq(inputConsensusFastq, outputConsensusFastq): infile = open(inputConsensusFastq, "r") outfile = open(outputConsensusFastq, "w") fasta_id = None fasta_seq = {} qual_id = {} qual_scr = {} flag = None for line in infile: if not line == "": if line.startswith("@") and not flag == "qual": fasta_id = line.strip() flag = "seq" fasta_seq[fasta_id] = [] continue elif line.startswith("+"): qual_id[fasta_id] = line.strip() flag = "qual" qual_scr[fasta_id] = [] continue if flag == "seq": fasta_seq[fasta_id].append(line.upper().strip()) elif flag == "qual": qual_scr[fasta_id].append(line.strip()) else: #print >> sys.stderr, "Warning: End of Sequence" break for fasta_id in fasta_seq.keys(): #if len(fasta_seq[fasta_id]) > 0: outfile.write(fasta_id) outfile.write("\n") outfile.write("".join(fasta_seq[fasta_id])) outfile.write("\n") outfile.write(qual_id[fasta_id]) outfile.write("\n") outfile.write("".join(qual_scr[fasta_id])) outfile.write("\n") infile.close() outfile.close() class Consensus(AbstractAnalysis): def run(self): AbstractAnalysis.run(self) #Call base method to do some logging localBamFile = os.path.join(self.getLocalTempDir(), "mapping.bam") localSortedBamFile = os.path.join(self.getLocalTempDir(), "mapping.sorted") samToBamFile(self.samFile, localBamFile) pysam.sort(localBamFile, localSortedBamFile) pysam.index(localSortedBamFile + ".bam") pysam.faidx(self.referenceFastaFile) file_header = self.readFastqFile.split(".fastq")[0].split("/")[-1] + "_" + self.referenceFastaFile.split(".fa")[0].split("/")[-1] consensus_vcf = os.path.join(self.outputDir, file_header + "_Consensus.vcf") consensus_fastq = os.path.join(self.outputDir, file_header + "_Consensus.fastq") system("samtools mpileup -Q 0 -uf %s %s | bcftools view -cg - > %s" \ % (self.referenceFastaFile, localSortedBamFile + ".bam", consensus_vcf)) system("vcfutils.pl vcf2fq %s > %s" % (consensus_vcf, consensus_fastq)) system("rm -rf %s" % (self.referenceFastaFile + ".fai")) formatted_consensus_fastq = os.path.join(self.getLocalTempDir(), "Consensus.fastq") formatConsensusFastq(consensus_fastq, formatted_consensus_fastq) system("mv %s %s" % (formatted_consensus_fastq, consensus_fastq)) self.finish()
Python
2D
mitenjain/nanopore
nanopore/analyses/__init__.py
.py
0
0
null
Python
2D
mitenjain/nanopore
nanopore/analyses/hmm.py
.py
4,792
88
import os from nanopore.analyses.abstractAnalysis import AbstractAnalysis from nanopore.analyses.utils import AlignedPair, getFastaDictionary, getFastqDictionary, samIterator import xml.etree.cElementTree as ET from jobTree.src.bioio import * class Hmm(AbstractAnalysis): """Calculates stats on indels. """ def run(self): #Call base method to do some logging AbstractAnalysis.run(self) #Hmm file hmmFile = os.path.join(os.path.split(self.samFile)[0], "hmm.txt.xml") if os.path.exists(hmmFile): #Load the hmm hmmsNode = ET.parse(hmmFile).getroot() #Plot graphviz version of nanopore hmm, showing transitions and variances. fH = open(os.path.join(self.outputDir, "hmm.dot"), 'w') setupGraphFile(fH) #Make states addNodeToGraph("n0n", fH, "match") addNodeToGraph("n1n", fH, "short delete") addNodeToGraph("n2n", fH, "short insert") addNodeToGraph("n3n", fH, "long insert") addNodeToGraph("n4n", fH, "long delete") #Make edges with labelled transition probs. for transition in hmmsNode.findall("transition"): if float(transition.attrib["avg"]) > 0.0: addEdgeToGraph("n%sn" % transition.attrib["from"], "n%sn" % transition.attrib["to"], fH, dir="arrow", style='""', label="%.3f,%.3f" % (float(transition.attrib["avg"]), float(transition.attrib["std"]))) #Finish up finishGraphFile(fH) fH.close() #Plot match emission data emissions = dict([ ((emission.attrib["x"], emission.attrib["y"]), emission.attrib["avg"]) \ for emission in hmmsNode.findall("emission") if emission.attrib["state"] == '0' ]) matchEmissionsFile = os.path.join(self.outputDir, "matchEmissions.tsv") outf = open(matchEmissionsFile, "w") bases = "ACGT" outf.write("\t".join(bases) + "\n") for base in bases: outf.write("\t".join([ base] + map(lambda x : emissions[(base, x)], bases)) + "\n") outf.close() system("Rscript nanopore/analyses/substitution_plot.R %s %s %s" % (matchEmissionsFile, os.path.join(self.outputDir, "substitution_plot.pdf"), "Per-Base Substitutions after HMM")) #Plot indel info #Get the sequences to contrast the neutral model. refSequences = getFastaDictionary(self.referenceFastaFile) #Hash of names to sequences readSequences = getFastqDictionary(self.readFastqFile) #Hash of names to sequences #Need to do plot of insert and deletion gap emissions #Plot of insert and deletion gap emissions insertEmissions = { "A":0.0, 'C':0.0, 'G':0.0, 'T':0.0 } deleteEmissions = { "A":0.0, 'C':0.0, 'G':0.0, 'T':0.0 } for emission in hmmsNode.findall("emission"): if emission.attrib["state"] == '2': insertEmissions[emission.attrib["x"]] += float(emission.attrib["avg"]) elif emission.attrib["state"] == '1': deleteEmissions[emission.attrib["y"]] += float(emission.attrib["avg"]) #PLot insert and delete emissions indelEmissionsFile = os.path.join(self.outputDir, "indelEmissions.tsv") outf = open(indelEmissionsFile, "w") outf.write("\t".join(bases) + "\n") outf.write("\t".join(map(lambda x : str(insertEmissions[x]), bases)) + "\n") outf.write("\t".join(map(lambda x : str(deleteEmissions[x]), bases)) + "\n") outf.close() ###Here's where we do the plot.. system("Rscript nanopore/analyses/emissions_plot.R {} {}".format(indelEmissionsFile, os.path.join(self.outputDir, "indelEmissions_plot.pdf"))) #Plot convergence of likelihoods outf = open(os.path.join(self.outputDir, "runninglikelihoods.tsv"), "w") for hmmNode in hmmsNode.findall("hmm"): #This is a loop over trials runningLikelihoods = map(float, hmmNode.attrib["runningLikelihoods"].split()) #This is a list of floats ordered from the first iteration to last. outf.write("\t".join(map(str, runningLikelihoods))); outf.write("\n") outf.close() system("Rscript nanopore/analyses/running_likelihood.R {} {}".format(os.path.join(self.outputDir, "runninglikelihoods.tsv"), os.path.join(self.outputDir, "running_likelihood.pdf"))) self.finish() #Indicates the batch is done
Python
2D
mitenjain/nanopore
nanopore/analyses/read_sampler.py
.py
1,961
41
import pysam import os, sys, glob, random # using generator and yield function to read 4 lines at a time def getStanza (infile): while True: fasta_id = infile.readline().strip() fasta_seq = infile.readline().strip() qual_id = infile.readline().strip() qual_scr = infile.readline().strip() if fasta_id != '': yield [fasta_id, fasta_seq, qual_id, qual_scr] else: # print >> sys.stderr, "Warning: End of Sequence" break def SampleReads(workingDir): for readType in glob.glob(os.path.join(workingDir + "readFastqFiles", "*")): for readFastqFile in glob.glob(os.path.join(readType, "*")): if (not "percent" in readFastqFile and not "Consensus" in readFastqFile) and (".fq" in readFastqFile or ".fastq" in readFastqFile): for i in range(90, 0, -10): newReadFastqFile = readFastqFile.split(".fastq")[0] + "_" + str(i) + "_percent.fastq" if not os.path.exists(newReadFastqFile): index = 0 readFastq = open(readFastqFile, "r") output = len(readFastq.readlines()) readFastq.close() # number of sequences total_seqs = output / 4 num_seq = total_seqs * i / 100 indexes = sorted(random.sample(range(total_seqs), num_seq)) readFastq = open(readFastqFile, "r") newreadFastq = open(newReadFastqFile, "w") for stanza in getStanza(readFastq): if index in indexes: newreadFastq.write("\n".join(stanza)) newreadFastq.write("\n") index += 1 readFastq.close() newreadFastq.close()
Python
2D
mitenjain/nanopore
nanopore/analyses/marginAlignSnpCaller.py
.py
20,859
310
from nanopore.analyses.abstractAnalysis import AbstractAnalysis from nanopore.analyses.utils import AlignedPair, getFastaDictionary, getFastqDictionary, getExonerateCigarFormatString, samIterator, pathToBaseNanoporeDir import os import pysam import numpy import math import random import xml.etree.cElementTree as ET from jobTree.src.bioio import reverseComplement, prettyXml, system, fastaWrite, cigarRead, PairwiseAlignment, cigarReadFromString from itertools import product from cactus.bar.cactus_expectationMaximisation import Hmm bases = "ACGT" def getProb(subMatrix, start, end): return subMatrix[(start, end)] def calcBasePosteriorProbs(baseObservations, refBase, evolutionarySubstitionMatrix, errorSubstutionMatrix): logBaseProbs = map(lambda missingBase : math.log(getProb(evolutionarySubstitionMatrix, refBase, missingBase)) + reduce(lambda x, y : x + y, map(lambda observedBase : math.log(getProb(errorSubstutionMatrix, missingBase, observedBase))*baseObservations[observedBase], bases)), bases) totalLogProb = reduce(lambda x, y : x + math.log(1 + math.exp(y-x)), logBaseProbs) return dict(zip(bases, map(lambda logProb : math.exp(logProb - totalLogProb), logBaseProbs))) def loadHmmErrorSubstitutionMatrix(hmmFile): hmm = Hmm.loadHmm(hmmFile) m = hmm.emissions[:len(bases)**2] m = map(lambda i : m[i] / sum(m[4*(i/4):4*(1 + i/4)]), range(len(m))) #Normalise m return dict(zip(product(bases, bases), m)) def getNullSubstitutionMatrix(): return dict(zip(product(bases, bases), [1.0]*len(bases)**2)) def getJukesCantorTypeSubstitutionMatrix(): return dict(zip(product(bases, bases), map(lambda x : 0.8 if x[0] == x[1] else (0.2/3), product(bases, bases)))) class MarginAlignSnpCaller(AbstractAnalysis): """Calculates stats on snp calling. """ def run(self): AbstractAnalysis.run(self) #Call base method to do some logging refSequences = getFastaDictionary(self.referenceFastaFile) #Hash of names to sequences readSequences = getFastqDictionary(self.readFastqFile) #Hash of names to sequences node = ET.Element("marginAlignComparison") for hmmType in ("cactus", "trained_0", "trained_20", "trained_40"): for coverage in (1000000, 120, 60, 30, 10): for replicate in xrange(3 if coverage < 1000000 else 1): #Do replicates, unless coverage is all sam = pysam.Samfile(self.samFile, "r" ) #Trained hmm file to use.q hmmFile0 = os.path.join(pathToBaseNanoporeDir(), "nanopore", "mappers", "blasr_hmm_0.txt") hmmFile20 = os.path.join(pathToBaseNanoporeDir(), "nanopore", "mappers", "blasr_hmm_20.txt") hmmFile40 = os.path.join(pathToBaseNanoporeDir(), "nanopore", "mappers", "blasr_hmm_40.txt") #Get substitution matrices nullSubstitionMatrix = getNullSubstitutionMatrix() flatSubstitutionMatrix = getJukesCantorTypeSubstitutionMatrix() hmmErrorSubstitutionMatrix = loadHmmErrorSubstitutionMatrix(hmmFile20) #Load the held out snps snpSet = {} referenceAlignmentFile = self.referenceFastaFile + "_Index.txt" if os.path.exists(referenceAlignmentFile): seqsAndMutatedSeqs = getFastaDictionary(referenceAlignmentFile) count = 0 for name in seqsAndMutatedSeqs: if name in refSequences: count += 1 trueSeq = seqsAndMutatedSeqs[name] mutatedSeq = seqsAndMutatedSeqs[name + "_mutated"] assert mutatedSeq == refSequences[name] for i in xrange(len(trueSeq)): if trueSeq[i] != mutatedSeq[i]: snpSet[(name, i)] = trueSeq[i] else: assert name.split("_")[-1] == "mutated" assert count == len(refSequences.keys()) #The data we collect expectationsOfBasesAtEachPosition = {} frequenciesOfAlignedBasesAtEachPosition = {} totalSampledReads = 0 totalAlignedPairs = 0 totalReadLength = 0 totalReferenceLength = sum(map(len, refSequences.values())) #Get a randomised ordering for the reads reads = [ aR for aR in samIterator(sam) ] random.shuffle(reads) for aR in reads: #Iterate on the sam lines if totalReadLength/totalReferenceLength >= coverage: #Stop when coverage exceeds the quota break totalReadLength += len(readSequences[aR.qname]) totalSampledReads += 1 #Temporary files tempCigarFile = os.path.join(self.getLocalTempDir(), "rescoredCigar.cig") tempRefFile = os.path.join(self.getLocalTempDir(), "ref.fa") tempReadFile = os.path.join(self.getLocalTempDir(), "read.fa") tempPosteriorProbsFile = os.path.join(self.getLocalTempDir(), "probs.tsv") #Ref name refSeqName = sam.getrname(aR.rname) #Sequences refSeq = refSequences[sam.getrname(aR.rname)] #Walk through the aligned pairs to collate the bases of aligned positions for aP in AlignedPair.iterator(aR, refSeq, readSequences[aR.qname]): totalAlignedPairs += 1 #Record an aligned pair key = (refSeqName, aP.refPos) if key not in frequenciesOfAlignedBasesAtEachPosition: frequenciesOfAlignedBasesAtEachPosition[key] = dict(zip(bases, [0.0]*len(bases))) readBase = aP.getReadBase() #readSeq[aP.readPos].upper() #Use the absolute read, ins if readBase in bases: frequenciesOfAlignedBasesAtEachPosition[key][readBase] += 1 #Write the temporary files. readSeq = aR.query #This excludes bases that were soft-clipped and is always of positive strand coordinates fastaWrite(tempRefFile, refSeqName, refSeq) fastaWrite(tempReadFile, aR.qname, readSeq) #Exonerate format Cigar string, which is in readSeq coordinates (positive strand). assert aR.pos == 0 assert aR.qstart == 0 assert aR.qend == len(readSeq) assert aR.aend == len(refSeq) cigarString = getExonerateCigarFormatString(aR, sam) #Call to cactus_realign if hmmType == "trained_0": system("echo %s | cactus_realign %s %s --diagonalExpansion=10 --splitMatrixBiggerThanThis=100 --outputAllPosteriorProbs=%s --loadHmm=%s > %s" % \ (cigarString, tempRefFile, tempReadFile, tempPosteriorProbsFile, hmmFile0, tempCigarFile)) elif hmmType == "trained_20": system("echo %s | cactus_realign %s %s --diagonalExpansion=10 --splitMatrixBiggerThanThis=100 --outputAllPosteriorProbs=%s --loadHmm=%s > %s" % \ (cigarString, tempRefFile, tempReadFile, tempPosteriorProbsFile, hmmFile20, tempCigarFile)) elif hmmType == "trained_40": system("echo %s | cactus_realign %s %s --diagonalExpansion=10 --splitMatrixBiggerThanThis=100 --outputAllPosteriorProbs=%s --loadHmm=%s > %s" % \ (cigarString, tempRefFile, tempReadFile, tempPosteriorProbsFile, hmmFile40, tempCigarFile)) else: system("echo %s | cactus_realign %s %s --diagonalExpansion=10 --splitMatrixBiggerThanThis=100 --outputAllPosteriorProbs=%s > %s" % \ (cigarString, tempRefFile, tempReadFile, tempPosteriorProbsFile, tempCigarFile)) #Now collate the reference position expectations for refPosition, readPosition, posteriorProb in map(lambda x : map(float, x.split()), open(tempPosteriorProbsFile, 'r')): key = (refSeqName, int(refPosition)) if key not in expectationsOfBasesAtEachPosition: expectationsOfBasesAtEachPosition[key] = dict(zip(bases, [0.0]*len(bases))) readBase = readSeq[int(readPosition)].upper() if readBase in bases: expectationsOfBasesAtEachPosition[key][readBase] += posteriorProb #Collate aligned positions from cigars sam.close() totalHeldOut = len(snpSet) totalNotHeldOut = totalReferenceLength - totalHeldOut class SnpCalls: def __init__(self): self.falsePositives = [] self.truePositives = [] self.falseNegatives = [] self.notCalled = 0 @staticmethod def bucket(calls): calls = calls[:] calls.sort() buckets = [0.0]*101 for prob in calls: #Discretize buckets[int(round(prob*100))] += 1 for i in xrange(len(buckets)-2, -1, -1): #Make cumulative buckets[i] += buckets[i+1] return buckets def getPrecisionByProbability(self): tPs = self.bucket(map(lambda x : x[0], self.truePositives)) fPs = self.bucket(map(lambda x : x[0], self.falsePositives)) return map(lambda i : float(tPs[i]) / (tPs[i] + fPs[i]) if tPs[i] + fPs[i] != 0 else 0, xrange(len(tPs))) def getRecallByProbability(self): return map(lambda i : i/totalHeldOut if totalHeldOut != 0 else 0, self.bucket(map(lambda x : x[0], self.truePositives))) def getTruePositiveLocations(self): return map(lambda x : x[1], self.truePositives) def getFalsePositiveLocations(self): return map(lambda x : x[1], self.falsePositives) def getFalseNegativeLocations(self): return map(lambda x : x[0], self.falseNegatives) #The different call sets marginAlignMaxExpectedSnpCalls = SnpCalls() marginAlignMaxLikelihoodSnpCalls = SnpCalls() maxFrequencySnpCalls = SnpCalls() maximumLikelihoodSnpCalls = SnpCalls() #Now calculate the calls for refSeqName in refSequences: refSeq = refSequences[refSeqName] for refPosition in xrange(len(refSeq)): mutatedRefBase = refSeq[refPosition].upper() trueRefBase = (mutatedRefBase if not (refSeqName, refPosition) in snpSet else snpSet[(refSeqName, refPosition)]).upper() key = (refSeqName, refPosition) #Get base calls for errorSubstitutionMatrix, evolutionarySubstitutionMatrix, baseExpectations, snpCalls in \ ((flatSubstitutionMatrix, nullSubstitionMatrix, expectationsOfBasesAtEachPosition, marginAlignMaxExpectedSnpCalls), (hmmErrorSubstitutionMatrix, nullSubstitionMatrix, expectationsOfBasesAtEachPosition, marginAlignMaxLikelihoodSnpCalls), (flatSubstitutionMatrix, nullSubstitionMatrix, frequenciesOfAlignedBasesAtEachPosition, maxFrequencySnpCalls), (hmmErrorSubstitutionMatrix, nullSubstitionMatrix, frequenciesOfAlignedBasesAtEachPosition, maximumLikelihoodSnpCalls)): if key in baseExpectations: #Get posterior likelihoods expectations = baseExpectations[key] totalExpectation = sum(expectations.values()) if totalExpectation > 0.0: #expectationCallingThreshold: posteriorProbs = calcBasePosteriorProbs(dict(zip(bases, map(lambda x : float(expectations[x])/totalExpectation, bases))), mutatedRefBase, evolutionarySubstitutionMatrix, errorSubstitutionMatrix) probs = [ posteriorProbs[base] for base in "ACGT" ] #posteriorProbs.pop(mutatedRefBase) #Remove the ref base. #maxPosteriorProb = max(posteriorProbs.values()) #chosenBase = random.choice([ base for base in posteriorProbs if posteriorProbs[base] == maxPosteriorProb ]).upper() #Very naive way to call the base for chosenBase in "ACGT": if chosenBase != mutatedRefBase: maxPosteriorProb = posteriorProbs[chosenBase] if trueRefBase != mutatedRefBase and trueRefBase == chosenBase: snpCalls.truePositives.append((maxPosteriorProb, refPosition)) #True positive else: snpCalls.falsePositives.append((maxPosteriorProb, refPosition)) #False positive """ snpCalls.falseNegatives.append((refPosition, trueRefBase, mutatedRefBase, probs)) #False negative if trueRefBase != mutatedRefBase: if trueRefBase == chosenBase: snpCalls.truePositives.append((maxPosteriorProb, refPosition)) #True positive else: snpCalls.falseNegatives.append((refPosition, trueRefBase, mutatedRefBase, probs)) #False negative else: snpCalls.falsePositives.append((maxPosteriorProb, refPosition)) #False positive """ else: snpCalls.notCalled += 1 #Now find max-fscore point for snpCalls, tagName in ((marginAlignMaxExpectedSnpCalls, "marginAlignMaxExpectedSnpCalls"), (marginAlignMaxLikelihoodSnpCalls, "marginAlignMaxLikelihoodSnpCalls"), (maxFrequencySnpCalls, "maxFrequencySnpCalls"), (maximumLikelihoodSnpCalls, "maximumLikelihoodSnpCalls")): recall = snpCalls.getRecallByProbability() precision = snpCalls.getPrecisionByProbability() assert len(recall) == len(precision) fScore, pIndex = max(map(lambda i : (2 * recall[i] * precision[i] / (recall[i] + precision[i]) if recall[i] + precision[i] > 0 else 0.0, i), range(len(recall)))) truePositives = snpCalls.getRecallByProbability()[pIndex] falsePositives = snpCalls.getPrecisionByProbability()[pIndex] optimumProbThreshold = float(pIndex)/100.0 #Write out the substitution info node2 = ET.SubElement(node, tagName + "_" + hmmType, { "coverage":str(coverage), "actualCoverage":str(float(totalAlignedPairs)/totalReferenceLength), "totalAlignedPairs":str(totalAlignedPairs), "totalReferenceLength":str(totalReferenceLength), "replicate":str(replicate), "totalReads":str(len(reads)), "avgSampledReadLength":str(float(totalReadLength)/totalSampledReads), "totalSampledReads":str(totalSampledReads), "totalHeldOut":str(totalHeldOut), "totalNonHeldOut":str(totalNotHeldOut), "recall":str(recall[pIndex]), "precision":str(precision[pIndex]), "fScore":str(fScore), "optimumProbThreshold":str(optimumProbThreshold), "totalNoCalls":str(snpCalls.notCalled), "recallByProbability":" ".join(map(str, snpCalls.getRecallByProbability())), "precisionByProbability":" ".join(map(str, snpCalls.getPrecisionByProbability())) }) #"falsePositiveLocations":" ".join(map(str, snpCalls.getFalsePositiveLocations())), #"falseNegativeLocations":" ".join(map(str, snpCalls.getFalseNegativeLocations())), #"truePositiveLocations":" ".join(map(str, snpCalls.getTruePositiveLocations())) }) for refPosition, trueRefBase, mutatedRefBase, posteriorProbs in snpCalls.falseNegatives: ET.SubElement(node2, "falseNegative_%s_%s" % (trueRefBase, mutatedRefBase), { "posteriorProbs":" ".join(map(str, posteriorProbs))}) for falseNegativeBase in bases: for mutatedBase in bases: posteriorProbsArray = [ posteriorProbs for refPosition, trueRefBase, mutatedRefBase, posteriorProbs in snpCalls.falseNegatives if (trueRefBase.upper() == falseNegativeBase.upper() and mutatedBase.upper() == mutatedRefBase.upper() ) ] if len(posteriorProbsArray) > 0: summedProbs = reduce(lambda x, y : map(lambda i : x[i] + y[i], xrange(len(x))), posteriorProbsArray) summedProbs = map(lambda x : float(x)/sum(summedProbs), summedProbs) ET.SubElement(node2, "combinedFalseNegative_%s_%s" % (falseNegativeBase, mutatedBase), { "posteriorProbs":" ".join(map(str, summedProbs))}) open(os.path.join(self.outputDir, "marginaliseConsensus.xml"), "w").write(prettyXml(node)) #Indicate everything is all done self.finish()
Python
2D
mitenjain/nanopore
nanopore/analyses/indelKmerAnalysis.py
.py
3,300
70
from nanopore.analyses.abstractAnalysis import AbstractAnalysis from jobTree.src.bioio import fastqRead, fastaRead, system from nanopore.analyses.utils import samIterator, getFastaDictionary, UniqueList import pysam, os, itertools from collections import Counter from math import log class IndelKmerAnalysis(AbstractAnalysis): """Runs kmer analysis""" def indelKmerFinder(self, aligned): r = UniqueList(); s = self.kmerSize+1 for i in xrange(len(aligned)): r.add(aligned[i]) if r[0] == None or (len(r) == s and r[self.kmerSize] == None) or (None not in r and len(r) == s): r.remove(last=False) elif None in r and len(r) == s: yield (r[0],r[self.kmerSize]) r.remove(last=False) def countIndelKmers(self): sam = pysam.Samfile(self.samFile) refKmers, readKmers = Counter(), Counter() refDict = getFastaDictionary(self.referenceFastaFile) for x in refDict: refDict[x] = tuple(refDict[x]) for record in samIterator(sam): refSeq = refDict[sam.getrname(record.rname)] readSeq = tuple(record.query) readAligned, refAligned = zip(*record.aligned_pairs) for start, end in self.indelKmerFinder(readAligned): s = readSeq[start:end+1] readKmers[s] += 1 refKmers[s[::-1]] += 1 for start, end in self.indelKmerFinder(refAligned): s = refSeq[start:end+1] refKmers[s] += 1 refKmers[s[::-1]] += 1 return (refKmers, readKmers) def analyzeCounts(self, refKmers, readKmers, name): refSize, readSize = sum(refKmers.values()), sum(readKmers.values()) outf = open(os.path.join(self.outputDir, name + "kmer_counts.txt"), "w") outf.write("kmer\trefCount\trefFraction\treadCount\treadFraction\tlogFoldChange\n") if refSize > 0 and readSize > 0: for kmer in itertools.product("ATGC", repeat=5): refFraction, readFraction = 1.0 * refKmers[kmer] / refSize, 1.0 * readKmers[kmer] / readSize if refFraction == 0: foldChange = "-Inf" elif readFraction == 0: foldChange = "Inf" else: foldChange = -log(readFraction / refFraction) outf.write("\t".join(map(str,["".join(kmer), refKmers[kmer], refFraction, readKmers[kmer], readFraction, foldChange]))+"\n") outf.close() system("Rscript nanopore/analyses/kmer_analysis.R {} {} {} {} {}".format(os.path.join(self.outputDir, name + "kmer_counts.txt"), os.path.join(self.outputDir, name + "pval_kmer_counts.txt"), os.path.join(self.outputDir, name + "top_bot_sigkmer_counts.txt"), os.path.join(self.outputDir, name + "volcano_plot.pdf"), "Indel_Kmer")) def run(self, kmerSize=5): AbstractAnalysis.run(self) self.kmerSize = kmerSize #analyze kmers around the boundaries of indels indelRefKmers, indelReadKmers = self.countIndelKmers() if len(indelRefKmers) > 0 and len(indelReadKmers) > 0: self.analyzeCounts(indelRefKmers, indelReadKmers, "indel_bases_") self.finish()
Python
2D
mitenjain/nanopore
nanopore/analyses/channel_plots.R
.R
7,317
159
#!/usr/bin/env Rscript args <- commandArgs(trailingOnly = T) data <- read.table(args[1], row.names=1, header=T) library(lattice) #below is hard coded positions on the nanopore labels <- c(125, 126, 127, 128, 253, 254, 255, 256, 381, 382, 383, 384, 509, 510, 511, 512, 121, 122, 123, 124, 249, 250, 251, 252, 377, 378, 379, 380, 505, 506, 507, 508, 117, 118, 119, 120, 245, 246, 247, 248, 373, 374, 375, 376, 501, 502, 503, 504, 113, 114, 115, 116, 241, 242, 243, 244, 369, 370, 371, 372, 497, 498, 499, 500, 109, 110, 111, 112, 237, 238, 239, 240, 365, 366, 367, 368, 493, 494, 495, 496, 105, 106, 107, 108, 233, 234, 235, 236, 361, 362, 363, 364, 489, 490, 491, 492, 101, 102, 103, 104, 229, 230, 231, 232, 357, 358, 359, 360, 485, 486, 487, 488, 97, 98, 99, 100, 225, 226, 227, 228, 353, 354, 355, 356, 481, 482, 483, 484, 93, 94, 95, 96, 221, 222, 223, 224, 349, 350, 351, 352, 477, 478, 479, 480, 89, 90, 91, 92, 217, 218, 219, 220, 345, 346, 347, 348, 473, 474, 475, 476, 85, 86, 87, 88, 213, 214, 215, 216, 341, 342, 343, 344, 469, 470, 471, 472, 81, 82, 83, 84, 209, 210, 211, 212, 337, 338, 339, 340, 465, 466, 467, 468, 77, 78, 79, 80, 205, 206, 207, 208, 333, 334, 335, 336, 461, 462, 463, 464, 73, 74, 75, 76, 201, 202, 203, 204, 329, 330, 331, 332, 457, 458, 459, 460, 69, 70, 71, 72, 197, 198, 199, 200, 325, 326, 327, 328, 453, 454, 455, 456, 65, 66, 67, 68, 193, 194, 195, 196, 321, 322, 323, 324, 449, 450, 451, 452, 61, 62, 63, 64, 189, 190, 191, 192, 317, 318, 319, 320, 445, 446, 447, 448, 57, 58, 59, 60, 185, 186, 187, 188, 313, 314, 315, 316, 441, 442, 443, 444, 53, 54, 55, 56, 181, 182, 183, 184, 309, 310, 311, 312, 437, 438, 439, 440, 49, 50, 51, 52, 177, 178, 179, 180, 305, 306, 307, 308, 433, 434, 435, 436, 45, 46, 47, 48, 173, 174, 175, 176, 301, 302, 303, 304, 429, 430, 431, 432, 41, 42, 43, 44, 169, 170, 171, 172, 297, 298, 299, 300, 425, 426, 427, 428, 37, 38, 39, 40, 165, 166, 167, 168, 293, 294, 295, 296, 421, 422, 423, 424, 33, 34, 35, 36, 161, 162, 163, 164, 289, 290, 291, 292, 417, 418, 419, 420, 29, 30, 31, 32, 157, 158, 159, 160, 285, 286, 287, 288, 413, 414, 415, 416, 25, 26, 27, 28, 153, 154, 155, 156, 281, 282, 283, 284, 409, 410, 411, 412, 21, 22, 23, 24, 149, 150, 151, 152, 277, 278, 279, 280, 405, 406, 407, 408, 17, 18, 19, 20, 145, 146, 147, 148, 273, 274, 275, 276, 401, 402, 403, 404, 13, 14, 15, 16, 141, 142, 143, 144, 269, 270, 271, 272, 397, 398, 399, 400, 9, 10, 11, 12, 137, 138, 139, 140, 265, 266, 267, 268, 393, 394, 395, 396, 5, 6, 7, 8, 133, 134, 135, 136, 261, 262, 263, 264, 389, 390, 391, 392, 1, 2, 3, 4, 129, 130, 131, 132, 257, 258, 259, 260, 385, 386, 387, 388) g <- function(p, x) {p*(1-p)^(x-1)} #geometric parameterized to start at 1 if (dim(data)[1] > 1) { sorted <- data[order(data$ReadCount, decreasing=T),] sorted <- t(sorted[sorted$ReadCount > 0,]) png(args[3], height=3000, width=3000, type="cairo") q<- barplot(sorted, main=paste("Sorted Channel Mappability", paste("# Reporting = ", length(sorted[1,]), "/512", sep=""), sep=" "), xlab="Channel", ylab="Read Counts", legend.text=T, xaxt="n", col=c("blue","red"), args.legend=c(cex=4), cex.names=3, cex.main=5) text(cex=0.5, x=q-.25, y=-1.25, colnames(sorted), xpd=T, srt=65) #geometric fit - tried it, was not a good fit #phat <- 1/mean(data$ReadCount) #curve(length(data$ReadCount) * g(phat, x), add=T, col="blue", lwd=3) #phat <- 1/mean(data$MappableReadCount) #curve(length(data$MappableReadCount) * g(phat, x), add=T, col="red", lwd=3) dev.off() pdf(args[2]) sorted.percent <- sorted["MappableReadCount",]/sorted["ReadCount",] sorted.percent <- sorted.percent[order(sorted.percent, decreasing=T)] sorted.percent <- sorted.percent[sorted.percent > 0] sorted.percent <- sorted.percent[!is.na(sorted.percent)] q<- barplot(sorted.percent, main="Sorted Channel Percent Mappability", xlab="Channel", ylab="Read Counts", xaxt="n") text(cex=0.27, x=q-.25,y=-0.005, names(sorted.percent), xpd=T, srt=45) #do linear regression reg <- lm(sorted["MappableReadCount",]~sorted["ReadCount",]) #plot scatterplot plot(sorted["MappableReadCount",]~sorted["ReadCount",], pch=20, col="blue", xlab="Total Read Count", ylab="Mappable Read Count", main="Mappable vs Total Reads\nReporting Channels Only") #add regression line abline(reg) #add R2 legend("topleft",legend=c(paste("R^2 = ", round(summary.lm(reg)$adj.r.squared,4)))) barplot(t(data)[2,]/(t(data)[1,]+t(data)[2,])*100, main="% Mappable Reads Per Channel", xlab="Channel", ylab="% Mappable") par(mfrow=(c(1,2))) barplot(t(data)[1,], main="Total Read Counts", xlab="Channel", ylab="Read Counts") barplot(t(data)[2,], main="Mappable Read Counts", xlab="Channel", ylab="Read Counts") dev.off() png(args[4], height=1000, width=1000, type="cairo") is.nan.data.frame <- function(x){ do.call(cbind, lapply(x, is.nan))} #need to find % mapped, but then replace the NaNs with 0s mapped <- data$MappableReadCount/data$ReadCount mapped[is.nan(mapped)] <- 0 positions <- labels for (i in 1:length(positions) ) { positions[match(c(i), positions)] <- mapped[i] } positions <- matrix(positions, nrow=16) rotate <- function(x) t(apply(x, 2, rev)) p <- levelplot(rotate(positions), main ="MinION Channel Percent Read Mappability Layout", col.regions=colorRampPalette(c("white","red"))(256)) print(p) dev.off() png(args[5], height=1000, width=1000, type="cairo") #do it again except with total # of reads reads <- data$ReadCount reads[is.nan(reads)] <- 0 positions <- labels for (i in 1:length(positions) ) { positions[match(c(i), positions)] <- reads[i] } positions <- matrix(positions, nrow=16) rotate <- function(x) t(apply(x, 2, rev)) p <- levelplot(rotate(positions), main ="MinION Channel Number of Reads", col.regions=colorRampPalette(c("white","red"))(256)) print(p) #plot that checks for independence of read amount by position xvals <- vector() yvals <- vector() #grid of (y) positions around <- expand.grid(c(-1,0,1),c(-1,0,1)) #remove the one position where x = y = 0 around <- around[-5,] for (y in 1:16) { for (x in 1:32) { for (z in 1:8){ yoffset <- around[z,1] xoffset <- around[z,2] #ensure we are not on the edge of the grid if ( ! x + xoffset < 1 && ! y + yoffset < 1 && ! x + xoffset > 32 && ! y + yoffset > 16){ xvals <- c(xvals, positions[y,x]) yvals <- c(yvals, positions[y+yoffset,x+xoffset]) } } } } p <- xyplot(yvals~xvals, xlab="# Of Reads", ylab="# Of Reads In Adjacent Channels", main="Comparing The Number of Reads In Individual Channels\nTo All Adjacent Channels",panel=panel.smoothScatter) print(p) dev.off() }
R
2D
mitenjain/nanopore
nanopore/analyses/match_hist.R
.R
273
15
#!/usr/bin/env Rscript args <- commandArgs(trailingOnly = T) data <- read.table(args[1], sep="\t") if ( dim(data)[1] > 0 & sum(data, na.rm=T) > 0 ) { pdf(args[2]) hist(t(data), main = "Average Posterior Match Probability", xlab="Probability") dev.off() }
R
2D
mitenjain/nanopore
nanopore/analyses/fastqc.py
.py
272
9
from nanopore.analyses.abstractAnalysis import AbstractAnalysis from sonLib.bioio import system import os class FastQC(AbstractAnalysis): def run(self): AbstractAnalysis.run(self) system("fastqc %s --outdir=%s" % (self.readFastqFile, self.outputDir))
Python
2D
mitenjain/nanopore
nanopore/analyses/kmer_analysis.R
.R
1,978
53
#!/usr/bin/env Rscript args <- commandArgs(trailingOnly = T) data <- read.table(args[1], row.names=1, header=T) if (sum(data$refCount) > 1000 && sum(data$readCount) > 10000 ){ outf <- args[2] outsig <- args[3] outplot <- args[4] library(stats) library(lattice) num_trials <- 1000 trial_size <- 5000 #builds a table of samples from a kmer count distribution #samples the probability distribution d t times trial_fn <- function(d, t) { matrix(table(factor(sample(1024, t, prob=d, replace=T), levels=1:1024)))[,1] } #do num_trials trials of sampling from the refFraction distribution ref <- replicate(num_trials, trial_fn(d=data$refFraction, t=trial_size)) #do num_trials trials of sampling from the readFraction distribution read <- replicate(num_trials, trial_fn(d=data$readFraction, t=trial_size)) #initialize a p_value vector p_values <- rep(0, 1024) #loop over each kmer and do a Kolmogorov-Smirnov test comparing the two distributions for (i in 1:1024) { p_values[i] <- ks.test(ref[i,], read[i,])$p.value } #Bonferroni correction for multiple hypotheses adjusted_p_value <- p.adjust(p_values, method="bonferroni") #combine original data frame with two new vectors finished <- cbind(data, p_values, adjusted_p_value) #write full dataset write.table(finished, outf) #find significant hits significant <- finished[finished$adjusted_p_value <= 0.05,] #plot volcano plot pdf(outplot) xyplot(finished$adjusted_p_value~finished$logFoldChange, xlab="Log Fold Change", ylab="Adjusted P Value", main=paste(args[5], "Volcano Plot", sep=" ")) dev.off() #sort the significant hits by fold change ordered <- significant[order(significant$logFoldChange),] #report the top 20 and bottom 20 significant hits top <- head(ordered, n=20L) bot <- apply(tail(ordered, n=20L), 2, rev) write.table(rbind(top,bot), outsig) }
R
2D
mitenjain/nanopore
nanopore/analyses/coverage.py
.py
9,851
167
from nanopore.analyses.abstractAnalysis import AbstractAnalysis from nanopore.analyses.utils import AlignedPair, getFastaDictionary, getFastqDictionary, samIterator import os import numpy import pysam import xml.etree.cElementTree as ET from jobTree.src.bioio import reverseComplement, fastaRead, fastqRead, prettyXml, system from itertools import chain class ReadAlignmentCoverageCounter: """Counts coverage from a pairwise alignment. Global alignment means the entire reference and read sequences (trailing indels). """ def __init__(self, readSeqName, readSeq, refSeqName, refSeq, alignedRead, globalAlignment=False): self.matches = 0 self.mismatches = 0 self.ns = 0 self.totalReadInsertionLength = 0 self.totalReadInsertions = 0 self.totalReadDeletionLength = 0 self.totalReadDeletions = 0 self.readSeqName = readSeqName self.readSeq = readSeq self.refSeqName = refSeqName self.refSeq = refSeq self.globalAlignment = globalAlignment #Now process the read alignment totalReadInsertionLength, totalReadDeletionLength = 0, 0 aP = None for aP in AlignedPair.iterator(alignedRead, self.refSeq, self.readSeq): if aP.isMatch(): self.matches += 1 elif aP.isMismatch(): self.mismatches += 1 else: self.ns += 1 if aP.getPrecedingReadInsertionLength(self.globalAlignment) > 0: self.totalReadInsertions += 1 totalReadInsertionLength += aP.getPrecedingReadInsertionLength(self.globalAlignment) if aP.getPrecedingReadDeletionLength(self.globalAlignment) > 0: self.totalReadDeletions += 1 totalReadDeletionLength += aP.getPrecedingReadDeletionLength(self.globalAlignment) if self.globalAlignment and aP != None: #If global alignment account for any trailing indels assert len(self.refSeq) - aP.refPos - 1 >= 0 if len(self.refSeq) - aP.refPos - 1 > 0: self.totalReadDeletions += 1 self.totalReadDeletionLength += len(self.refSeq) - aP.refPos - 1 if alignedRead.is_reverse: aP.readPos >= 0 if aP.readPos > 0: self.totalReadInsertions += 1 totalReadInsertionLength += aP.readPos else: assert len(self.readSeq) - aP.readPos - 1 >= 0 if len(self.readSeq) - aP.readPos - 1 > 0: self.totalReadInsertions += 1 totalReadInsertionLength += len(self.readSeq) - aP.readPos - 1 assert totalReadInsertionLength <= len(self.readSeq) assert totalReadDeletionLength <= len(self.refSeq) self.totalReadInsertionLength += totalReadInsertionLength self.totalReadDeletionLength += totalReadDeletionLength def readCoverage(self): return AbstractAnalysis.formatRatio(self.matches + self.mismatches, self.matches + self.mismatches + self.totalReadInsertionLength) def referenceCoverage(self): return AbstractAnalysis.formatRatio(self.matches + self.mismatches, self.matches + self.mismatches + self.totalReadDeletionLength) def identity(self): return AbstractAnalysis.formatRatio(self.matches, self.matches + self.mismatches + self.totalReadInsertionLength) def mismatchesPerReadBase(self): return AbstractAnalysis.formatRatio(self.mismatches, self.matches + self.mismatches) def deletionsPerReadBase(self): return AbstractAnalysis.formatRatio(self.totalReadDeletions, self.matches + self.mismatches) def insertionsPerReadBase(self): return AbstractAnalysis.formatRatio(self.totalReadInsertions, self.matches + self.mismatches) def readLength(self): return len(self.readSeq) def getXML(self): return ET.Element("readAlignmentCoverage", { "refSeqName":self.refSeqName, "readSeqName":self.readSeqName, "readLength":str(self.readLength()), "readCoverage":str(self.readCoverage()), "referenceCoverage":str(self.referenceCoverage()), "identity":str(self.identity()), "mismatchesPerReadBase":str(self.mismatchesPerReadBase()), "insertionsPerReadBase":str(self.insertionsPerReadBase()), "deletionsPerReadBase":str(self.deletionsPerReadBase()) }) def getAggregateCoverageStats(readAlignmentCoverages, tagName, refSequences, readSequences, readsToReadAlignmentCoverages, typeof): """Calculates aggregate stats across a set of read alignments, plots distributions. """ if typeof == "coverage_all": mappedReadLengths = [ [len(readSequences[i])] * len(readsToReadAlignmentCoverages[i]) for i in readSequences.keys() if i in readsToReadAlignmentCoverages ] mappedReadLengths = list(chain(*mappedReadLengths)) else: mappedReadLengths = [ len(readSequences[i]) for i in readSequences.keys() if i in readsToReadAlignmentCoverages ] unmappedReadLengths = [ len(readSequences[i]) for i in readSequences.keys() if i not in readsToReadAlignmentCoverages ] def stats(fnStringName): l = map(lambda x : getattr(x, fnStringName)(), readAlignmentCoverages) l2 = l[:] l2.sort() return l2[0], numpy.average(l2), numpy.median(l2), l2[-1], " ".join(map(str, l)) attribs = { "numberOfReadAlignments":str(len(readAlignmentCoverages)), "numberOfReads":str(len(readSequences)), "numberOfReferenceSequences":str(len(refSequences)), "numberOfMappedReads":str(len(mappedReadLengths)), "mappedReadLengths":" ".join(map(str, mappedReadLengths)), "numberOfUnmappedReads":str(len(unmappedReadLengths)), "unmappedReadLengths":" ".join(map(str, unmappedReadLengths)), } for fnStringName in "readCoverage", "referenceCoverage", "identity", "mismatchesPerReadBase", "deletionsPerReadBase", "insertionsPerReadBase", "readLength": for attribName, value in zip([ "min" + fnStringName, "avg" + fnStringName, "median" + fnStringName, "max" + fnStringName, "distribution" + fnStringName ], list(stats(fnStringName))): attribs[attribName] = str(value) parentNode = ET.Element(tagName, attribs) for readAlignmentCoverage in readAlignmentCoverages: parentNode.append(readAlignmentCoverage.getXML()) return parentNode class LocalCoverage(AbstractAnalysis): """Calculates coverage, treating alignments as local alignments. """ def run(self, globalAlignment=False): AbstractAnalysis.run(self) #Call base method to do some logging refSequences = getFastaDictionary(self.referenceFastaFile) #Hash of names to sequences readSequences = getFastqDictionary(self.readFastqFile) #Hash of names to sequences sam = pysam.Samfile(self.samFile, "r" ) readsToReadCoverages = {} for aR in samIterator(sam): #Iterate on the sam lines refSeq = refSequences[sam.getrname(aR.rname)] readSeq = readSequences[aR.qname] readAlignmentCoverageCounter = ReadAlignmentCoverageCounter(aR.qname, readSeq, sam.getrname(aR.rname), refSeq, aR, globalAlignment) if aR.qname not in readsToReadCoverages: readsToReadCoverages[aR.qname] = [] readsToReadCoverages[aR.qname].append(readAlignmentCoverageCounter) sam.close() #Write out the coverage info for differing subsets of the read alignments if len(readsToReadCoverages.values()) > 0: for readCoverages, outputName in [ (reduce(lambda x, y : x + y, readsToReadCoverages.values()), "coverage_all"), (map(lambda x : max(x, key=lambda y : y.readCoverage()), readsToReadCoverages.values()), "coverage_bestPerRead") ]: parentNode = getAggregateCoverageStats(readCoverages, outputName, refSequences, readSequences, readsToReadCoverages, outputName) open(os.path.join(self.outputDir, outputName + ".xml"), 'w').write(prettyXml(parentNode)) #this is a ugly file format with each line being a different data type - column length is variable outf = open(os.path.join(self.outputDir, outputName + ".txt"), "w") outf.write("MappedReadLengths " + parentNode.get("mappedReadLengths") + "\n") outf.write("UnmappedReadLengths " + parentNode.get("unmappedReadLengths") + "\n") outf.write("ReadCoverage " + parentNode.get("distributionreadCoverage") + "\n") outf.write("MismatchesPerReadBase " + parentNode.get("distributionmismatchesPerReadBase") + "\n") outf.write("ReadIdentity " + parentNode.get("distributionidentity") + "\n") outf.write("InsertionsPerBase " + parentNode.get("distributioninsertionsPerReadBase") + "\n") outf.write("DeletionsPerBase " + parentNode.get("distributiondeletionsPerReadBase") + "\n") outf.close() system("Rscript nanopore/analyses/coverage_plot.R {} {}".format(os.path.join(self.outputDir, outputName + ".txt"), os.path.join(self.outputDir, outputName + ".pdf"))) self.finish() class GlobalCoverage(LocalCoverage): def run(self): """Calculates coverage, treating alignments as global alignments. """ LocalCoverage.run(self, globalAlignment=True)
Python
2D
mitenjain/nanopore
nanopore/analyses/emissions_plot.R
.R
746
33
#!/usr/bin/env Rscript args <- commandArgs(trailingOnly = T) library(lattice) f <- args[1] out <- args[2] myPanel <- function(x, y, z, ...) { panel.levelplot(x, y, z, ...) panel.text(x, y, round(z,3)) } d <- read.table(f, header = T) if ( dim(d)[1] > 0 && sum(d) > 0) { pdf(out) p <- levelplot(t(as.matrix(d[1,])), ylab="Emission Probability", xlab="Nucleotide", main="Insertion Emission Probabilities", panel = myPanel, col.regions=colorRampPalette(c("white","red"))(256)) print(p) p2 <- levelplot(t(as.matrix(d[2,])), ylab="Emission Probability", xlab="Nucleotide", main="Deletion Emission Probabilities", panel = myPanel, col.regions=colorRampPalette(c("white","red"))(256)) print(p2) dev.off() }
R
2D
mitenjain/nanopore
nanopore/analyses/indelPlots.R
.R
2,415
44
#!/usr/bin/env Rscript args <- commandArgs(trailingOnly = T) indels <- read.table(args[1], fill=T, sep="\t", header=T, na.strings="None", comment.char="") g <- function(p, x) {p*(1-p)^(x-1)} #geometric parameterized to start at 1 if (dim(indels)[1] > 2) { pdf(args[2]) par(mfrow=c(2,1)) if ( ! is.null(indels$readInsertionLengths) && ! is.null(indels$readDeletionLengths) && length(indels$readInsertionLengths[!is.na(indels$readInsertionLengths)]) > 1 && length(indels$readDeletionLengths[!is.na(indels$readDeletionLengths)]) ) { insertionLengths <- indels$readInsertionLengths[!is.na(indels$readInsertionLengths)] deletionLengths <- indels$readDeletionLengths[!is.na(indels$readDeletionLengths)] hist(insertionLengths, main="Read Insertion\nLength Distribution",xlab="Insertion Length", breaks="FD", xlim=c(1,10)) phat <- 1 / mean(insertionLengths) curve(length(insertionLengths)*g(phat, x), xlim=c(1,10), add=T) hist(deletionLengths, main="Read Deletion\nLength Distribution",xlab="Deletion Length", breaks="FD", xlim=c(1,10)) phat <- 1 / mean(deletionLengths) curve(length(deletionLengths)*g(phat, x), xlim=c(1,10), add=T) } plot(x=as.numeric(indels$ReadSequenceLengths),y=as.numeric(indels$NumberReadInsertions), main="Insertions vs. Read Length", xlab="Read Length", ylab="Read Insertions", pch=19, col="blue") plot(x=as.numeric(indels$ReadSequenceLengths),y=as.numeric(indels$NumberReadDeletions), main="Deletions vs. Read Length", xlab="Read Length", ylab="Read Deletions", pch=19, col="blue") if (! "NaN" %in% indels$MedianReadInsertionLengths && ! "NaN" %in% indels$MedianReadDeletionLengths) { if (! length(indels$MedianReadDeletionLengths[!is.na(indels$MedianReadDeletionLengths)]) > 1 && ! length(indels$MedianReadInsertionLengths[!is.na(indels$MedianReadInsertionLengths)]) > 1 ) { barplot( c(indels$MedianReadDeletionLengths[!is.na(indels$MedianReadDeletionLengths)], indels$MedianReadInsertionLengths[!is.na(indels$MedianReadInsertionLengths)]), main="Median Insertion Lengths", names.arg=c("Deletions", "Insertions")) } else { plot(density(as.numeric(indels$MedianReadInsertionLengths), na.rm=T), main="Distribution of Median Insertion Lengths", xlab="Median Insertion Lengths") plot(density(as.numeric(indels$MedianReadDeletionLengths), na.rm=T), main="Distribution of Median Deletion Lengths", xlab="Median Deletion Lengths") } } dev.off() }
R
2D
mitenjain/nanopore
nanopore/analyses/utils.py
.py
28,935
631
import pysam, sys, os, collections from jobTree.src.bioio import reverseComplement, fastaRead, fastqRead, cigarReadFromString, PairwiseAlignment, system, fastaWrite, fastqWrite, cigarRead, logger, nameValue, absSymPath from cactus.bar import cactus_expectationMaximisation from cactus.bar.cactus_expectationMaximisation import Hmm, SYMBOL_NUMBER import numpy as np class UniqueList(collections.MutableSet): def __init__(self, iterable=None): self.end = end = [] end += [None, end, end] # sentinel node for doubly linked list self.map = {} # key --> [key, prev, next] if iterable is not None: self |= iterable def __len__(self): return len(self.map) def __contains__(self, key): return key in self.map def add(self, key): if key not in self.map: end = self.end curr = end[1] curr[2] = end[1] = self.map[key] = [key, curr, end] def discard(self, key): if key in self.map: key, prev, next = self.map.pop(key) prev[2] = next next[1] = prev def __iter__(self): end = self.end curr = end[2] while curr is not end: yield curr[0] curr = curr[2] def __reversed__(self): end = self.end curr = end[1] while curr is not end: yield curr[0] curr = curr[1] def pop(self, last=True): if not self: raise KeyError('set is empty') key = self.end[1][0] if last else self.end[2][0] self.discard(key) return key def remove(self, last=True): if not self: raise KeyError('set is empty') key = self.end[1][0] if last else self.end[2][0] self.discard(key) def __getitem__(self, index): if not self: raise KeyError('set is empty') elif index >= len(self.map): raise IndexError('UniqueList index out of range') elif index < 0: raise IndexError('UniqueList cannot handle negative indices because Ian is lazy') end = self.end if index == len(self.map) - 1: #fast way to get last element return end[1][0] curr = end[2] for i in xrange(index): curr = curr[2] return curr[0] def __repr__(self): if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, list(self)) def __eq__(self, other): if isinstance(other, UniqueList): return len(self) == len(other) and list(self) == list(other) return set(self) == set(other) def pathToBaseNanoporeDir(): import nanopore i = absSymPath(nanopore.__file__) return os.path.split(os.path.split(i)[0])[0] class AlignedPair: """Represents an aligned pair of positions. """ def __init__(self, refPos, refSeq, readPos, isReversed, readSeq, pPair): assert refPos >= 0 and refPos < len(refSeq) self.refPos = refPos self.refSeq = refSeq assert readPos >= 0 and readPos < len(readSeq) self.readPos = readPos self.isReversed = isReversed self.readSeq = readSeq self.pPair = pPair #Pointer to the previous aligned pair def isMatch(self): return self.getRefBase().upper() == self.getReadBase().upper() and self.getRefBase().upper() in "ACTG" def isMismatch(self): return self.getRefBase().upper() != self.getReadBase().upper() and self.getRefBase().upper() in "ACTG" and self.getReadBase().upper() in "ACTG" def getRefBase(self): return self.refSeq[self.refPos] def getReadBase(self): if self.isReversed: return reverseComplement(self.readSeq[self.readPos]) return self.readSeq[self.readPos] def getSignedReadPos(self): if self.isReversed: return -self.readPos return self.readPos def getPrecedingReadInsertionLength(self, globalAlignment=False): if self.pPair == None: if globalAlignment: if self.isReversed: assert len(self.readSeq) - self.readPos - 1 >= 0 return len(self.readSeq) - self.readPos - 1 return self.readPos return 0 return self._indelLength(self.readPos, self.pPair.readPos) def getPrecedingReadDeletionLength(self, globalAlignment=False): if self.pPair == None: if globalAlignment: return self.refPos return 0 return self._indelLength(self.refPos, self.pPair.refPos) @staticmethod def _indelLength(pos, pPos): length = abs(pPos - pos) - 1 assert length >= 0 return length @staticmethod def iterator(alignedRead, refSeq, readSeq): """Generates aligned pairs from a pysam.AlignedRead object. """ readOffset = getAbsoluteReadOffset(alignedRead, refSeq, readSeq) pPair = None assert len(alignedRead.seq) <= len(readSeq) for readPos, refPos in alignedRead.aligned_pairs: #Iterate over the block if readPos != None and refPos != None: assert refPos >= alignedRead.pos and refPos < alignedRead.aend if refPos >= len(refSeq): #This is masking an (apparently minor?) one off error in the BWA sam files? logger.critical("Detected an aligned reference position out of bounds! Reference length: %s, reference coordinate: %s" % (len(refSeq), refPos)) continue aP = AlignedPair(refPos, refSeq, abs(readOffset + readPos), alignedRead.is_reverse, readSeq, pPair) if aP.getReadBase().upper() != alignedRead.query[readPos].upper(): logger.critical("Detected a discrepancy between the absolute read sequence and the aligned read sequence. Bases: %s %s, read-position: %s, is reversed: %s, absolute read offset: %s, length absolute read sequence %s, length aligned read sequence %s, length aligned read sequence plus soft clipping %s, read name: %s, cigar string %s" % (aP.getReadBase().upper(), alignedRead.query[readPos].upper(), readPos, alignedRead.is_reverse, readOffset, len(readSeq), len(alignedRead.query), len(alignedRead.seq), alignedRead.qname, alignedRead.cigarstring)) assert aP.getReadBase().upper() == alignedRead.query[readPos].upper() pPair = aP yield aP def getAbsoluteReadOffset(alignedRead, refSeq, readSeq): """Gets the absolute starting coordinate of the first non-clipped position in the read. """ if alignedRead.cigar[0][0] == 5: #Translate the read position to the original coordinates by removing hard clipping readOffset = alignedRead.cigar[0][1] else: readOffset = 0 if alignedRead.is_reverse: #SEQ is reverse complemented readOffset = -(len(readSeq) - 1 - readOffset) readOffset += alignedRead.qstart #This removes any soft-clipping return readOffset def getExonerateCigarFormatString(alignedRead, sam): """Gets a complete exonerate like cigar-string describing the sam line """ for op, length in alignedRead.cigar: assert op in (0, 1, 2, 4, 5) translation = { 0:"M", 1:"I", 2:"D" } cigarString = " ".join([ "%s %i" % (translation[op], length) for op, length in alignedRead.cigar if op in translation ]) completeCigarString = "cigar: %s %i %i + %s %i %i + 1 %s" % ( alignedRead.qname, 0, alignedRead.qend - alignedRead.qstart, sam.getrname(alignedRead.rname), alignedRead.pos, alignedRead.aend, cigarString) pA = cigarReadFromString(completeCigarString) #This checks it's an okay cigar assert sum([ op.length for op in pA.operationList if op.type == PairwiseAlignment.PAIRWISE_MATCH ]) == len([ readPos for readPos, refPos in alignedRead.aligned_pairs if readPos != None and refPos != None ]) return completeCigarString """ def getGlobalAlignmentExonerateCigarFormatString(alignedRead, sam, refSeq, readSeq): #Gets a complete exonerate like cigar-string describing the sam line, but is global alignment (not in soft-clipped coordinates). ops = [] matchLength = 0 for aP in AlignedPair.iterator(alignedRead, refSeq, readSeq): deleteLength = aP.getPrecedingReadDeletionLength(globalAlignment=True) insertLength = aP.getPrecedingReadInsertionLength(globalAlignment=True) if (deleteLength > 0 or insertLength > 0) and matchLength > 0: ops.append(("M", matchLength)) matchLength = 1 if deleteLength > 0: ops.append(("D", deleteLength)) if insertLength > 0: ops.append(("I", insertLength)) else: matchLength += 1 if matchLength > 0: ops.append(("M", matchLength)) cumulativeRefLength = sum(map(lambda x : 0 if x[0] == 'I' else x[1], ops)) cumulativeReadLength = sum(map(lambda x : 0 if x[0] == 'D' else x[1], ops)) assert cumulativeRefLength <= len(refSeq) assert cumulativeReadLength <= len(readSeq) if cumulativeRefLength < len(refSeq): ops.append("D", len(refSeq) - cumulativeRefLength) if cumulativeReadLength < len(readSeq): ops.append("I", len(readSeq) - cumulativeReadLength) assert sum(map(lambda x : 0 if x[0] == 'I' else x[1], ops)) == len(refSeq) assert sum(map(lambda x : 0 if x[0] == 'D' else x[1], ops)) == len(readSeq) readCoordinates = ("%i 0 -" if alignedRead.is_reverse else "0 %i +") % len(readSeq) completeCigarString = "cigar: %s %s %s %i %i + 1 %s" % (alignedRead.qname, readCoordinates, sam.getrname(alignedRead.rname), 0, len(refSeq), " ".join(map(lambda x : "%s %i" % (x[0], x[1]), ops))) pA = cigarReadFromString(completeCigarString) #This checks it's an okay formatted cigar assert sum([ op.length for op in pA.operationList if op.type == PairwiseAlignment.PAIRWISE_MATCH ]) == len([ readPos for readPos, refPos in alignedRead.aligned_pairs if readPos != None and refPos != None ]) return completeCigarString """ def samToBamFile(samInputFile, bamOutputFile): """Converts a sam file to a bam file (sorted) """ samfile = pysam.Samfile(samInputFile, "r" ) bamfile = pysam.Samfile(bamOutputFile, "wb", template=samfile) for line in samfile: bamfile.write(line) samfile.close() bamfile.close() def getFastaDictionary(fastaFile): """Returns a dictionary of the first words of fasta headers to their corresponding fasta sequence """ names = map(lambda x : x[0].split()[0], fastaRead(open(fastaFile, 'r'))) assert len(names) == len(set(names)) #Check all the names are unique return dict(map(lambda x : (x[0].split()[0], x[1]), fastaRead(open(fastaFile, 'r')))) #Hash of names to sequences def getFastqDictionary(fastqFile): """Returns a dictionary of the first words of fastq headers to their corresponding fastq sequence """ names = map(lambda x : x[0].split()[0], fastqRead(open(fastqFile, 'r'))) assert len(names) == len(set(names)) #Check all the names are unique return dict(map(lambda x : (x[0].split()[0], x[1]), fastqRead(open(fastqFile, 'r')))) #Hash of names to sequences def makeFastaSequenceNamesUnique(inputFastaFile, outputFastaFile): """Makes a fasta file with unique names """ names = set() fileHandle = open(outputFastaFile, 'w') for name, seq in fastaRead(open(inputFastaFile, 'r')): while name in names: logger.critical("Got a duplicate fasta sequence name: %s" % name) name += "i" names.add(name) fastaWrite(fileHandle, name, seq) fileHandle.close() return outputFastaFile def makeFastqSequenceNamesUnique(inputFastqFile, outputFastqFile): """Makes a fastq file with unique names """ names = set() fileHandle = open(outputFastqFile, 'w') for name, seq, quals in fastqRead(open(inputFastqFile, 'r')): name = name.split()[0] #Get rid of any white space while name in names: logger.critical("Got a duplicate fastq sequence name: %s" % name) name += "i" names.add(name) fastqWrite(fileHandle, name, seq, quals) fileHandle.close() return outputFastqFile def normaliseQualValues(inputFastqFile, outputFastqFile): """Makes a fastq with valid qual values """ fileHandle = open(outputFastqFile, 'w') for name, seq, quals in fastqRead(open(inputFastqFile, 'r')): if quals == None: quals = [33] * len(seq) fastqWrite(fileHandle, name, seq, quals) fileHandle.close() return outputFastqFile def samIterator(sam): """Creates an iterator over the aligned reads in a sam file, filtering out any reads that have no reference alignment. """ for aR in sam: if aR.rname != -1: yield aR def mergeChainedAlignedReads(chainedAlignedReads, refSequence, readSequence): """Makes a global aligment for the given chained reads. From doc on building pysam line a = pysam.AlignedRead() a.qname = "read_28833_29006_6945" a.seq="AGCTTAGCTAGCTACCTATATCTTGGTCTTGGCCG" a.flag = 99 a.rname = 0 a.pos = 32 a.mapq = 20 a.cigar = ( (0,10), (2,1), (0,25) ) a.mrnm = 0 a.mpos=199 a.isize=167 a.qual="<<<<<<<<<<<<<<<<<<<<<:<9/,&,22;;<<<" a.tags = ( ("NM", 1), ("RG", "L1") ) """ cAR = pysam.AlignedRead() aR = chainedAlignedReads[0] cAR.qname = aR.qname #Parameters we don't and therefore set properly #cAR.flag = aR.flag #cAR.mapq = aR.mapq #cAR.mrnm = 0 #cAR.mpos=0 #cAR.isize=0 #cAR.qual = "<" * len(readSequence) #cAR.tags = aR.tags cAR.rnext = -1 cAR.pos = 0 cAR.is_reverse = aR.is_reverse if cAR.is_reverse: cAR.seq = reverseComplement(readSequence) else: cAR.seq = readSequence cAR.rname = aR.rname cigarList = [] pPos = 0 if cAR.is_reverse: #Iterate from the other end of the sequence pQPos = -(len(readSequence)-1) else: pQPos = 0 for aR in chainedAlignedReads: assert cAR.is_reverse == aR.is_reverse #Add a deletion representing the preceding unaligned reference positions assert aR.pos >= pPos if aR.pos > pPos: cigarList.append((2, aR.pos - pPos)) pPos = aR.pos #Add an insertion representing the preceding unaligned read positions qPos = getAbsoluteReadOffset(aR, refSequence, readSequence) assert qPos >= pQPos if qPos > pQPos: cigarList.append((1, qPos - pQPos)) pQPos = qPos #Add the operations of the cigar, filtering hard and soft clipping for op, length in aR.cigar: assert op in (0, 1, 2, 4, 5) if op in (0, 1, 2): cigarList.append((op, length)) if op in (0, 2): #Is match or deletion pPos += length if op in (0, 1): #Is match or insertion pQPos += length #Now add any trailing deletions/insertions assert pPos <= len(refSequence) if pPos < len(refSequence): cigarList.append((2, len(refSequence) - pPos)) if cAR.is_reverse: assert pQPos <= 1 if pQPos < 1: cigarList.append((1, -pQPos + 1)) else: assert pQPos <= len(readSequence) if pQPos < len(readSequence): cigarList.append((1, len(readSequence) - pQPos)) #Check coordinates #print cAR.is_reverse, sum([ length for op, length in cigarList if op in (0, 2)]), len(refSequence), sum([ length for op, length in cigarList if op in (0, 1)]), len(readSequence), cAR.qname assert sum([ length for op, length in cigarList if op in (0, 2)]) == len(refSequence) assert sum([ length for op, length in cigarList if op in (0, 1)]) == len(readSequence) cAR.cigar = tuple(cigarList) return cAR def chainFn(alignedReads, refSeq, readSeq, scoreFn=lambda alignedRead, refSeq, readSeq : len(list(AlignedPair.iterator(alignedRead, refSeq, readSeq))), maxGap=200): """Gets the highest scoring chain of alignments on either the forward or reverse strand. Score is (by default) number of aligned positions. """ def getStartAndEndCoordinates(alignedRead): """Gets the start and end coordinates in both the reference and query """ alignedPairs = list(AlignedPair.iterator(alignedRead, refSeq, readSeq)) return alignedPairs[0].refPos, alignedPairs[0].getSignedReadPos(), alignedPairs[-1].refPos, alignedPairs[-1].getSignedReadPos() alignedReadToScores = dict([ (aR, scoreFn(aR, refSeq, readSeq)) for aR in alignedReads]) alignedReadToCoordinates = dict([ (aR, getStartAndEndCoordinates(aR)) for aR in alignedReads]) alignedReadPointers = {} #Currently uses sloppy quadratic algorithm to find highest chain alignedReads = sorted(alignedReads, key=lambda aR : alignedReadToCoordinates[aR][0]) #Sort by reference coordinate for i in xrange(len(alignedReads)): aR = alignedReads[i] rStart, qStart, rEnd, qEnd = alignedReadToCoordinates[aR] score = alignedReadToScores[aR] for j in xrange(i): #Look at earlier alignments in list aR2 = alignedReads[j] rStart2, qStart2, rEnd2, qEnd2 = alignedReadToCoordinates[aR2] assert rStart2 <= rStart if rStart > rEnd2 and qStart > qEnd2 and aR.is_reverse == aR2.is_reverse and \ rStart - rEnd2 + qStart - qEnd2 <= maxGap and \ score + alignedReadToScores[aR2] > alignedReadToScores[aR]: #Conditions for a chain alignedReadToScores[aR] = score + alignedReadToScores[aR2] alignedReadPointers[aR] = aR2 #Now find highest scoring alignment aR = sorted(alignedReads, key=lambda aR : alignedReadToScores[aR])[-1] #Construct chain of alignedReads chain = [ aR ] while aR in alignedReadPointers: aR = alignedReadPointers[aR] chain.append(aR) chain.reverse() return chain def combineSamFiles(baseSamFile, extraSamFiles, outputSamFile): """Combines the lines from multiple sam files into one sam file """ sam = pysam.Samfile(baseSamFile, "r" ) outputSam = pysam.Samfile(outputSamFile, "wh", template=sam) sam.close() for samFile in [ baseSamFile ] + extraSamFiles: sam = pysam.Samfile(samFile, "r" ) for line in sam: outputSam.write(line) sam.close() outputSam.close() def chainSamFile(samFile, outputSamFile, readFastqFile, referenceFastaFile, chainFn=chainFn): """Chains together the reads in the SAM file so that each read is covered by a single maximal alignment """ sam = pysam.Samfile(samFile, "r" ) refSequences = getFastaDictionary(referenceFastaFile) #Hash of names to sequences readSequences = getFastqDictionary(readFastqFile) #Hash of names to sequences readsToAlignedReads = {} for aR in samIterator(sam): #Iterate on the sam lines and put into buckets by read if aR.qname not in readSequences: raise RuntimeError("Aligned read name: %s not in read sequences names: %s" % (aR.qname, readSequences.keys())) key = (aR.qname,aR.rname) if key not in readsToAlignedReads: readsToAlignedReads[key] = [] readsToAlignedReads[key].append(aR) #Now write out the sam file outputSam = pysam.Samfile(outputSamFile, "wh", template=sam) #Chain together the reads chainedAlignedReads = [] for readName, refID in readsToAlignedReads.keys(): alignedReads = readsToAlignedReads[(readName, refID)] refSeq = refSequences[sam.getrname(refID)] readSeq = readSequences[readName] chainedAlignedReads.append(mergeChainedAlignedReads(chainFn(alignedReads, refSeq, readSeq), refSeq, readSeq)) chainedAlignedReads.sort() #Sort by reference coordinate for cAR in chainedAlignedReads: outputSam.write(cAR) sam.close() outputSam.close() def learnModelFromSamFileTargetFn(target, samFile, readFastqFile, referenceFastaFile, outputModel): """Does expectation maximisation on sam file to learn the hmm for the sam file. """ #Convert the read file to fasta refSequences = getFastaDictionary(referenceFastaFile) #Hash of names to sequences readSequences = getFastqDictionary(readFastqFile) #Hash of names to sequences reads = os.path.join(target.getGlobalTempDir(), "temp.fa") fH = open(reads, 'w') for name in readSequences.keys(): seq = readSequences[name] fastaWrite(fH, name, seq) fastaWrite(fH, name + "_reverse", reverseComplement(seq)) fH.close() #Get cigars file cigars = os.path.join(target.getGlobalTempDir(), "temp.cigar") fH = open(cigars, 'w') sam = pysam.Samfile(samFile, "r" ) for aR in sam: #Iterate on the sam lines realigning them in parallel #Because these are global alignments with reverse complement coordinates reversed the following should all be true assert aR.pos == 0 assert aR.qstart == 0 assert aR.qend == len(readSequences[aR.qname]) #aR.query) assert aR.aend == len(refSequences[sam.getrname(aR.rname)]) assert len(aR.query) == len(readSequences[aR.qname]) if aR.is_reverse: #Deal with reverse complements assert aR.query.upper() == reverseComplement(readSequences[aR.qname]).upper() aR.qname += "_reverse" else: assert aR.query.upper() == readSequences[aR.qname].upper() fH.write(getExonerateCigarFormatString(aR, sam) + "\n") #Exonerate format Cigar string, using global coordinates #fH.write(getGlobalAlignmentExonerateCigarFormatString(aR, sam, refSequences[sam.getrname(aR.rname)], readSequences[aR.qname]) + "\n") fH.close() #Run cactus_expectationMaximisation options = cactus_expectationMaximisation.Options() options.modelType="fiveStateAsymmetric" #"threeStateAsymmetric" options.optionsToRealign="--diagonalExpansion=10 --splitMatrixBiggerThanThis=300" options.randomStart = True options.trials = 3 options.outputTrialHmms = True options.iterations = 100 options.maxAlignmentLengthPerJob=700000 options.maxAlignmentLengthToSample = 50000000 options.outputXMLModelFile = outputModel + ".xml" #options.updateTheBand = True #options.useDefaultModelAsStart = True #options.setJukesCantorStartingEmissions=0.3 options.trainEmissions=True #options.tieEmissions = True unnormalisedOutputModel = outputModel + "_unnormalised" #Do training if necessary if not os.path.exists(unnormalisedOutputModel): target.addChildTargetFn(cactus_expectationMaximisation.expectationMaximisationTrials, args=(" ".join([reads, referenceFastaFile ]), cigars, unnormalisedOutputModel, options)) #Now set up normalisation target.setFollowOnTargetFn(learnModelFromSamFileTargetFn2, args=(unnormalisedOutputModel, outputModel)) def learnModelFromSamFileTargetFn2(target, unnormalisedOutputModel, outputModel): hmm = Hmm.loadHmm(unnormalisedOutputModel) setHmmIndelEmissionsToBeFlat(hmm) #Normalise background emission frequencies, if requested to GC% given normaliseHmmByReferenceGCContent(hmm, 0.5) hmm.write(outputModel) def realignSamFileTargetFn(target, samFile, outputSamFile, readFastqFile, referenceFastaFile, gapGamma, matchGamma, hmmFile=None, trainHmmFile=False, chainFn=chainFn): """Chains and then realigns the resulting global alignments, using jobTree to do it in parallel on a cluster. Optionally runs expectation maximisation. """ #Chain the sam file tempSamFile = os.path.join(target.getGlobalTempDir(), "temp.sam") chainSamFile(samFile, tempSamFile, readFastqFile, referenceFastaFile, chainFn) #If we do expectation maximisation we split here: if hmmFile != None and trainHmmFile: target.addChildTargetFn(learnModelFromSamFileTargetFn, args=(tempSamFile, readFastqFile, referenceFastaFile, hmmFile)) else: assert not trainHmmFile target.setFollowOnTargetFn(realignSamFile2TargetFn, args=(tempSamFile, outputSamFile, readFastqFile, referenceFastaFile, hmmFile, gapGamma, matchGamma)) def realignSamFile2TargetFn(target, samFile, outputSamFile, readFastqFile, referenceFastaFile, hmmFile, gapGamma, matchGamma): #Load reference sequences refSequences = getFastaDictionary(referenceFastaFile) #Hash of names to sequences readSequences = getFastqDictionary(readFastqFile) #Hash of names to sequences #Read through the SAM file sam = pysam.Samfile(samFile, "r" ) tempCigarFiles = [] for aR, index in zip(samIterator(sam), xrange(sys.maxint)): #Iterate on the sam lines realigning them in parallel #Temporary cigar file tempCigarFiles.append(os.path.join(target.getGlobalTempDir(), "rescoredCigar_%i.cig" % index)) #Add a child target to do the alignment target.addChildTargetFn(realignCigarTargetFn, args=(getExonerateCigarFormatString(aR, sam), sam.getrname(aR.rname), refSequences[sam.getrname(aR.rname)], aR.qname, aR.query, tempCigarFiles[-1], hmmFile, gapGamma, matchGamma)) target.setFollowOnTargetFn(realignSamFile3TargetFn, args=(samFile, outputSamFile, tempCigarFiles)) #Finish up sam.close() def realignCigarTargetFn(target, exonerateCigarString, referenceSequenceName, referenceSequence, querySequenceName, querySequence, outputCigarFile, hmmFile, gapGamma, matchGamma): #Temporary files tempRefFile = os.path.join(target.getGlobalTempDir(), "ref.fa") tempReadFile = os.path.join(target.getGlobalTempDir(), "read.fa") #Write the temporary files. fastaWrite(tempRefFile, referenceSequenceName, referenceSequence) fastaWrite(tempReadFile, querySequenceName, querySequence) #Call to cactus_realign loadHmm = nameValue("loadHmm", hmmFile) system("echo %s | cactus_realign %s %s --diagonalExpansion=10 --splitMatrixBiggerThanThis=3000 %s --gapGamma=%s --matchGamma=%s > %s" % (exonerateCigarString, tempRefFile, tempReadFile, loadHmm, gapGamma, matchGamma, outputCigarFile)) assert len([ pA for pA in cigarRead(open(outputCigarFile)) ]) > 0 assert len([ pA for pA in cigarRead(open(outputCigarFile)) ]) == 1 def realignSamFile3TargetFn(target, samFile, outputSamFile, tempCigarFiles): #Setup input and output sam files sam = pysam.Samfile(samFile, "r" ) #Replace the cigar lines with the realigned cigar lines outputSam = pysam.Samfile(outputSamFile, "wh", template=sam) for aR, tempCigarFile in zip(samIterator(sam), tempCigarFiles): #Iterate on the sam lines realigning them in parallel #Load the cigar pA = [ i for i in cigarRead(open(tempCigarFile)) ][0] #Convert to sam line aR.cigar = tuple([ (op.type, op.length) for op in pA.operationList ]) #Write out outputSam.write(aR) #Finish up sam.close() outputSam.close() toMatrix = lambda e : map(lambda i : e[SYMBOL_NUMBER*i:SYMBOL_NUMBER*(i+1)], xrange(SYMBOL_NUMBER)) fromMatrix = lambda e : reduce(lambda x, y : list(x) + list(y), e) def normaliseHmmByReferenceGCContent(hmm, gcContent): #Normalise background emission frequencies, if requested to GC% given for state in range(hmm.stateNumber): if state not in (2, 4): #Don't normalise GC content of insert states (as they don't have any ref bases!) n = toMatrix(hmm.emissions[(SYMBOL_NUMBER**2) * state:(SYMBOL_NUMBER**2) * (state+1)]) hmm.emissions[(SYMBOL_NUMBER**2) * state:(SYMBOL_NUMBER**2) * (state+1)] = fromMatrix(map(lambda i : map(lambda j : (n[i][j]/sum(n[i])) * (gcContent/2.0 if i in [1, 2] else (1.0-gcContent)/2.0), range(SYMBOL_NUMBER)), range(SYMBOL_NUMBER))) #Normalise def modifyHmmEmissionsByExpectedVariationRate(hmm, substitutionRate): #Normalise background emission frequencies, if requested to GC% given n = toMatrix(map(lambda i : (1.0-substitutionRate) if i % SYMBOL_NUMBER == i / SYMBOL_NUMBER else substitutionRate/(SYMBOL_NUMBER-1), xrange(SYMBOL_NUMBER**2))) hmm.emissions[:SYMBOL_NUMBER**2] = fromMatrix(np.dot(toMatrix(hmm.emissions[:SYMBOL_NUMBER**2]), n)) def setHmmIndelEmissionsToBeFlat(hmm): #Set indel emissions to all be flat for state in range(1, hmm.stateNumber): hmm.emissions[(SYMBOL_NUMBER**2) * state:(SYMBOL_NUMBER**2) * (state+1)] = [1.0/(SYMBOL_NUMBER**2)]*SYMBOL_NUMBER**2
Python
2D
mitenjain/nanopore
nanopore/analyses/kmerAnalysis.py
.py
2,599
59
from nanopore.analyses.abstractAnalysis import AbstractAnalysis from jobTree.src.bioio import fastqRead, fastaRead, system, reverseComplement from nanopore.analyses.utils import samIterator import pysam, os, itertools from collections import Counter from math import log class KmerAnalysis(AbstractAnalysis): """Runs kmer analysis""" def countKmers(self): refKmers, readKmers = Counter(), Counter() for name, seq in fastaRead(self.referenceFastaFile): for i in xrange(self.kmerSize, len(seq)): s = seq[ i - self.kmerSize : i ] if "N" not in s: refKmers[s] += 1 refKmers[reverseComplement(s)] += 1 for name, seq, qual in fastqRead(self.readFastqFile): for i in xrange(self.kmerSize, len(seq)): s = seq[ i - self.kmerSize : i ] if "N" not in s: readKmers[s] += 1 readKmers[reverseComplement(s)] += 1 return (refKmers, readKmers) def analyzeCounts(self, refKmers, readKmers, name): refSize, readSize = sum(refKmers.values()), sum(readKmers.values()) outf = open(os.path.join(self.outputDir, name + "kmer_counts.txt"), "w") outf.write("kmer\trefCount\trefFraction\treadCount\treadFraction\tlogFoldChange\n") for kmer in itertools.product("ATGC", repeat=5): kmer = "".join(kmer) refFraction, readFraction = 1.0 * refKmers[kmer] / refSize, 1.0 * readKmers[kmer] / readSize if refFraction == 0: foldChange = "-Inf" elif readFraction == 0: foldChange = "Inf" else: foldChange = -log(readFraction / refFraction) outf.write("\t".join(map(str,[kmer, refKmers[kmer], refFraction, readKmers[kmer], readFraction, foldChange]))+"\n") outf.close() system("Rscript nanopore/analyses/kmer_analysis.R {} {} {} {} {}".format(os.path.join(self.outputDir, name + "kmer_counts.txt"), os.path.join(self.outputDir, name + "pval_kmer_counts.txt"), os.path.join(self.outputDir, name + "top_bot_sigkmer_counts.txt"), os.path.join(self.outputDir, name + "volcano_plot.pdf"), "Kmer")) def run(self, kmerSize=5): AbstractAnalysis.run(self) self.kmerSize = kmerSize #analyze kmers across both files refKmers, readKmers = self.countKmers() if len(refKmers) > 0 and len(readKmers) > 0: self.analyzeCounts(refKmers, readKmers, "all_bases_") self.finish()
Python
2D
mitenjain/nanopore
nanopore/analyses/channelMappability.py
.py
1,887
31
from nanopore.analyses.abstractAnalysis import AbstractAnalysis from nanopore.analyses.utils import getFastqDictionary, samIterator import os import pysam import xml.etree.cElementTree as ET from jobTree.src.bioio import reverseComplement, prettyXml, system from collections import Counter import re class ChannelMappability(AbstractAnalysis): """Calculates nanopore channel specific mappability """ def run(self): AbstractAnalysis.run(self) readSequences = getFastqDictionary(self.readFastqFile) nr = re.compile(r"channel_[0-9]+_read_[0-9]+") per_channel_read_counts = Counter([int(x.split("_")[1]) for x in readSequences.iterkeys() if re.match(nr, x)]) sam = pysam.Samfile(self.samFile, "r") mapped_read_counts = Counter([int(aR.qname.split("_")[1]) for aR in samIterator(sam) if re.match(nr, aR.qname) and aR.is_unmapped is False]) if len(mapped_read_counts) > 0 and len(per_channel_read_counts) > 0: outf = open(os.path.join(self.outputDir, "channel_mappability.tsv"), "w") outf.write("Channel\tReadCount\tMappableReadCount\n") max_channel = max(513, max(per_channel_read_counts.keys())) #in case there are more than 512 in the future for channel in xrange(1, max_channel): outf.write("\t".join(map(str, [channel, per_channel_read_counts[channel], mapped_read_counts[channel]]))) outf.write("\n") outf.close() system("Rscript nanopore/analyses/channel_plots.R {} {} {} {} {}".format(os.path.join(self.outputDir, "channel_mappability.tsv"), os.path.join(self.outputDir, "channel_mappability.pdf"), os.path.join(self.outputDir, "channel_mappability_sorted.png"), os.path.join(self.outputDir, "mappability_levelplot.png"), os.path.join(self.outputDir, "mappability_leveplot_percent.png"))) self.finish()
Python
2D
mitenjain/nanopore
nanopore/analyses/alignmentUncertainty.py
.py
4,503
73
from nanopore.analyses.abstractAnalysis import AbstractAnalysis from nanopore.analyses.utils import AlignedPair, getFastaDictionary, getFastqDictionary, getExonerateCigarFormatString, samIterator, pathToBaseNanoporeDir import os import pysam import numpy import xml.etree.cElementTree as ET from jobTree.src.bioio import reverseComplement, prettyXml, system, fastaWrite, cigarRead, PairwiseAlignment, cigarReadFromString class AlignmentUncertainty(AbstractAnalysis): """Calculates stats on indels. """ def run(self): AbstractAnalysis.run(self) #Call base method to do some logging refSequences = getFastaDictionary(self.referenceFastaFile) #Hash of names to sequences readSequences = getFastqDictionary(self.readFastqFile) #Hash of names to sequences sam = pysam.Samfile(self.samFile, "r" ) #The data we collect avgPosteriorMatchProbabilityInCigar = [] alignedPairsInCigar = [] posteriorMatchProbabilities = [] for aR in samIterator(sam): #Iterate on the sam lines #Exonerate format Cigar string cigarString = getExonerateCigarFormatString(aR, sam) #Temporary files tempCigarFile = os.path.join(self.getLocalTempDir(), "rescoredCigar.cig") tempRefFile = os.path.join(self.getLocalTempDir(), "ref.fa") tempReadFile = os.path.join(self.getLocalTempDir(), "read.fa") tempPosteriorProbsFile = os.path.join(self.getLocalTempDir(), "probs.tsv") #Write the temporary files. fastaWrite(tempRefFile, sam.getrname(aR.rname), refSequences[sam.getrname(aR.rname)]) fastaWrite(tempReadFile, aR.qname, aR.query) #Trained hmm file to use. hmmFile = os.path.join(pathToBaseNanoporeDir(), "nanopore", "mappers", "blasr_hmm_0.txt") #Call to cactus_realign system("echo %s | cactus_realign %s %s --rescoreByPosteriorProbIgnoringGaps --rescoreOriginalAlignment --diagonalExpansion=10 --splitMatrixBiggerThanThis=100 --outputPosteriorProbs=%s --loadHmm=%s > %s" % \ (cigarString, tempRefFile, tempReadFile, tempPosteriorProbsFile, hmmFile, tempCigarFile)) #Load the cigar and get the posterior prob assert len([ pA for pA in cigarRead(open(tempCigarFile)) ]) > 0 assert len([ pA for pA in cigarRead(open(tempCigarFile)) ]) == 1 pA = [ i for i in cigarRead(open(tempCigarFile)) ][0] avgPosteriorMatchProbabilityInCigar.append(pA.score) #Calculate the number of aligned pairs in the cigar alignedPairsInCigar.append(sum([ op.length for op in pA.operationList if op.type == PairwiseAlignment.PAIRWISE_MATCH ])) assert alignedPairsInCigar[-1] == len([ readPos for readPos, refPos in aR.aligned_pairs if readPos != None and refPos != None ]) #Get the posterior probs #posteriorMatchProbabilities += [ float(line.split()[2]) for line in open(tempPosteriorProbsFile) ] sam.close() #Write out the substitution info node = ET.Element("alignmentUncertainty", { "averagePosteriorMatchProbabilityPerRead":str(self.formatRatio(sum(avgPosteriorMatchProbabilityInCigar), len(avgPosteriorMatchProbabilityInCigar))), "averagePosteriorMatchProbability":str(self.formatRatio(float(sum([ avgMatchProb*alignedPairs for avgMatchProb, alignedPairs in zip(avgPosteriorMatchProbabilityInCigar, alignedPairsInCigar) ])),sum(alignedPairsInCigar))), "averagePosteriorMatchProbabilitesPerRead":",".join([ str(i) for i in avgPosteriorMatchProbabilityInCigar ]), "alignedPairsInCigar":",".join([ str(i) for i in alignedPairsInCigar ]) }) open(os.path.join(self.outputDir, "alignmentUncertainty.xml"), "w").write(prettyXml(node)) if len(avgPosteriorMatchProbabilityInCigar) > 0: outf = open(os.path.join(self.getLocalTempDir(), "tmp_uncertainty"), "w") outf.write("\t".join([ str(i) for i in avgPosteriorMatchProbabilityInCigar ])); outf.write("\n") outf.close() system("Rscript nanopore/analyses/match_hist.R {} {}".format(os.path.join(self.getLocalTempDir(), "tmp_uncertainty"), os.path.join(self.outputDir, "posterior_prob_hist.pdf"))) #Indicate everything is all done self.finish()
Python
2D
mitenjain/nanopore
nanopore/analyses/abstractAnalysis.py
.py
1,550
42
from jobTree.scriptTree.target import Target from sonLib.bioio import logger import os class AbstractAnalysis(Target): """Base class to for analysis targets. Inherit this class to create an analysis. """ def __init__(self, readFastqFile, readType, referenceFastaFile, samFile, outputDir): Target.__init__(self) self.readFastqFile = readFastqFile self.referenceFastaFile = referenceFastaFile self.samFile = samFile self.outputDir = outputDir self.readType = readType print(str(self.samFile)) def run(self): """Base method that does some logging """ logger.info("This analysis target has read fastq file: %s, reference fasta file: %s, sam file: %s and will output to the directory: %s" % \ (self.readFastqFile, self.referenceFastaFile, self.samFile, self.outputDir)) def finish(self): """Method called when a analysis has finished successfully to indicate that it should not be repeated. """ open(os.path.join(self.outputDir, "DONE"), 'w').close() @staticmethod def reset(outputDir): if AbstractAnalysis.isFinished(outputDir): os.remove(os.path.join(outputDir, "DONE")) @staticmethod def isFinished(outputDir): return os.path.exists(os.path.join(outputDir, "DONE")) @staticmethod def formatRatio(numerator, denominator): if denominator == 0: return float("nan") return float(numerator)/denominator
Python
2D
mitenjain/nanopore
nanopore/analyses/substitution_plot.R
.R
557
31
#!/usr/bin/env Rscript args <- commandArgs(trailingOnly = T) library(lattice) f <- args[1] out <- args[2] inf <- args[3] myPanel <- function(x, y, z, ...) { panel.levelplot(x, y, z, ...) panel.text(x, y, paste(100 * round(exp(-z),4), "%", sep="")) } d <- read.table(f, header = T, row.names = 1) if ( dim(d)[1] > 0 && sum(d) > 0) { pdf(out) p <- levelplot(as.matrix(-log(d)), main=inf, xlab="Reference bases", ylab="Read bases", panel = myPanel, col.regions=colorRampPalette(c("white","red"))(256)) print(p) dev.off() }
R
2D
mitenjain/nanopore
nanopore/analyses/indels.py
.py
6,347
111
from nanopore.analyses.abstractAnalysis import AbstractAnalysis from nanopore.analyses.utils import AlignedPair, getFastaDictionary, getFastqDictionary, samIterator import os import pysam import numpy import xml.etree.cElementTree as ET from jobTree.src.bioio import reverseComplement, prettyXml, system class IndelCounter(): def __init__(self, refSeqName, refSeq, readSeqName, readSeq, alignedRead): self.readInsertionLengths = [] self.readDeletionLengths = [] self.blockLengths = [] self.readSeqName = readSeqName self.readSeq = readSeq self.refSeqName = refSeqName self.refSeq = refSeq #Now add the aligned read blockLength = 0 for aP in AlignedPair.iterator(alignedRead, self.refSeq, self.readSeq): if aP.getPrecedingReadInsertionLength() > 0: self.readInsertionLengths.append(aP.getPrecedingReadInsertionLength()) if aP.getPrecedingReadDeletionLength() > 0: self.readDeletionLengths.append(aP.getPrecedingReadDeletionLength()) if aP.getPrecedingReadInsertionLength() > 0 or aP.getPrecedingReadDeletionLength() > 0: assert blockLength > 0 self.blockLengths.append(blockLength) blockLength = 1 else: blockLength += 1 def getXML(self): return ET.Element("indels", { "refSeqName":self.refSeqName, "refSeqLength":str(len(self.refSeq)), "readSeqName":self.readSeqName, "readSeqLength":str(len(self.readSeq)), "numberReadInsertions":str(len(self.readInsertionLengths)), "numberReadDeletions":str(len(self.readDeletionLengths)), "avgReadInsertionLength":str(numpy.average(self.readInsertionLengths)), "avgReadDeletionLength":str(numpy.average(self.readDeletionLengths)), "medianReadInsertionLength":str(numpy.median(self.readInsertionLengths)), "medianReadDeletionLength":str(numpy.median(self.readDeletionLengths)), "readInsertionLengths":" ".join([ str(i) for i in self.readInsertionLengths ]), "readDeletionLengths":" ".join([ str(i) for i in self.readDeletionLengths ]) }) def getAggregateIndelStats(indelCounters): """Calculates aggregate stats across a set of read alignments. """ readInsertionLengths = reduce(lambda x, y : x + y, map(lambda ic : ic.readInsertionLengths, indelCounters)) readDeletionLengths = reduce(lambda x, y : x + y, map(lambda ic : ic.readDeletionLengths, indelCounters)) attribs = { "numberOfReadAlignments":str(len(indelCounters)), "readInsertionLengths":" ".join(map(str, readInsertionLengths)), "readDeletionLengths":" ".join(map(str, readDeletionLengths)) } readSequenceLengths = map(lambda ic : len(ic.readSeq), indelCounters) numberReadInsertions = map(lambda ic : len(ic.readInsertionLengths), indelCounters) numberReadDeletions = map(lambda ic : len(ic.readDeletionLengths), indelCounters) medianReadInsertionLengths = map(lambda ic : numpy.median(ic.readInsertionLengths), indelCounters) medianReadDeletionLengths = map(lambda ic : numpy.median(ic.readDeletionLengths), indelCounters) def stats(distribution): distribution = distribution[:] distribution.sort() return distribution[0], numpy.average(distribution), numpy.median(distribution), distribution[-1], " ".join(map(str, distribution)) for name, distribution in [("ReadSequenceLengths", readSequenceLengths), ("NumberReadInsertions", numberReadInsertions), ("NumberReadDeletions", numberReadDeletions), ("MedianReadInsertionLengths", medianReadInsertionLengths), ("MedianReadDeletionLengths", medianReadDeletionLengths) ]: for attribName, value in zip([ "min" + name, "avg" + name, "median" + name, "max" + name, "distribution" + name ], list(stats(distribution))): attribs[name] = str(value) parentNode = ET.Element("indels", attribs) for indelCounter in indelCounters: parentNode.append(indelCounter.getXML()) return parentNode class Indels(AbstractAnalysis): """Calculates stats on indels. """ def run(self): AbstractAnalysis.run(self) #Call base method to do some logging refSequences = getFastaDictionary(self.referenceFastaFile) #Hash of names to sequences readSequences = getFastqDictionary(self.readFastqFile) #Hash of names to sequences sam = pysam.Samfile(self.samFile, "r" ) indelCounters = map(lambda aR : IndelCounter(sam.getrname(aR.rname), refSequences[sam.getrname(aR.rname)], aR.qname, readSequences[aR.qname], aR), samIterator(sam)) #Iterate on the sam lines sam.close() #Write out the substitution info if len(indelCounters) > 0: indelXML = getAggregateIndelStats(indelCounters) open(os.path.join(self.outputDir, "indels.xml"), "w").write(prettyXml(indelXML)) tmp = open(os.path.join(self.outputDir, "indels.tsv"), "w") #build list of data as vectors data_list = [] var = ["readInsertionLengths", "readDeletionLengths", "ReadSequenceLengths", "NumberReadInsertions", "NumberReadDeletions", "MedianReadInsertionLengths", "MedianReadDeletionLengths"] for x in var: data_list.append([x] + indelXML.attrib[x].split()) #transpose this list so R doesn't take hours to load it using magic data_list = map(None, *data_list) for line in data_list: tmp.write("\t".join(map(str,line))); tmp.write("\n") tmp.close() system("Rscript nanopore/analyses/indelPlots.R {} {}".format(os.path.join(self.outputDir, "indels.tsv"), os.path.join(self.outputDir, "indel_plots.pdf"))) self.finish() #Indicates the batch is done
Python
2D
mitenjain/nanopore
nanopore/analyses/running_likelihood.R
.R
992
35
#!/usr/bin/env Rscript args <- commandArgs(trailingOnly = T) f <- args[1] out <- args[2] tryCatch({ dist <- read.table(f) if (dim(dist)[1] > 1) { m <- max(dist) pdf(out) r <- topo.colors(length(rownames(dist))) n <- 0 plot(x=seq(1,dim(dist)[2]),y=as.vector(dist[1,]/m), type="n", main="Convergence of Likelihoods", xlab="Trials", ylab="Running Log Likelihoods Ratio") for (i in 1:length(rownames(dist))) { n <- n + 1 lines(x=seq(1,dim(dist)[2]),y=as.vector(dist[i,]/m), col =r[n]) } n <- 0 plot(x=seq(1,dim(dist)[2]),y=log(as.vector(dist[1,]/m)), type="n", main="Convergence of Likelihoods", xlab="Trials", ylab="Running Log-Log Likelihoods Ratio", ylim=c(0,0.01)) for (i in 1:length(rownames(dist))) { n <- n + 1 lines(x=seq(1,dim(dist)[2]),y=log(as.vector(dist[i,]/m)), col =r[n]) } dev.off() } }, error = function(err) { })
R
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_import.c
.c
16,461
490
#include <zlib.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #ifdef _WIN32 #include <fcntl.h> #endif #include "kstring.h" #include "bam.h" #include "sam_header.h" #include "kseq.h" #include "khash.h" KSTREAM_INIT(gzFile, gzread, 16384) KHASH_MAP_INIT_STR(ref, uint64_t) void bam_init_header_hash(bam_header_t *header); void bam_destroy_header_hash(bam_header_t *header); int32_t bam_get_tid(const bam_header_t *header, const char *seq_name); unsigned char bam_nt16_table[256] = { 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 1, 2, 4, 8, 15,15,15,15, 15,15,15,15, 15, 0 /*=*/,15,15, 15, 1,14, 2, 13,15,15, 4, 11,15,15,12, 15, 3,15,15, 15,15, 5, 6, 8,15, 7, 9, 15,10,15,15, 15,15,15,15, 15, 1,14, 2, 13,15,15, 4, 11,15,15,12, 15, 3,15,15, 15,15, 5, 6, 8,15, 7, 9, 15,10,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15 }; unsigned short bam_char2flag_table[256] = { 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,BAM_FREAD1,BAM_FREAD2,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, BAM_FPROPER_PAIR,0,BAM_FMREVERSE,0, 0,BAM_FMUNMAP,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, BAM_FDUP,0,BAM_FQCFAIL,0, 0,0,0,0, 0,0,0,0, BAM_FPAIRED,0,BAM_FREVERSE,BAM_FSECONDARY, 0,BAM_FUNMAP,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 }; char *bam_nt16_rev_table = "=ACMGRSVTWYHKDBN"; struct __tamFile_t { gzFile fp; kstream_t *ks; kstring_t *str; uint64_t n_lines; int is_first; }; char **__bam_get_lines(const char *fn, int *_n) // for bam_plcmd.c only { char **list = 0, *s; int n = 0, dret, m = 0; gzFile fp = (strcmp(fn, "-") == 0)? gzdopen(fileno(stdin), "r") : gzopen(fn, "r"); kstream_t *ks; kstring_t *str; str = (kstring_t*)calloc(1, sizeof(kstring_t)); ks = ks_init(fp); while (ks_getuntil(ks, '\n', str, &dret) > 0) { if (n == m) { m = m? m << 1 : 16; list = (char**)realloc(list, m * sizeof(char*)); } if (str->s[str->l-1] == '\r') str->s[--str->l] = '\0'; s = list[n++] = (char*)calloc(str->l + 1, 1); strcpy(s, str->s); } ks_destroy(ks); gzclose(fp); free(str->s); free(str); *_n = n; return list; } static bam_header_t *hash2header(const kh_ref_t *hash) { bam_header_t *header; khiter_t k; header = bam_header_init(); header->n_targets = kh_size(hash); header->target_name = (char**)calloc(kh_size(hash), sizeof(char*)); header->target_len = (uint32_t*)calloc(kh_size(hash), 4); for (k = kh_begin(hash); k != kh_end(hash); ++k) { if (kh_exist(hash, k)) { int i = (int)kh_value(hash, k); header->target_name[i] = (char*)kh_key(hash, k); header->target_len[i] = kh_value(hash, k)>>32; } } bam_init_header_hash(header); return header; } bam_header_t *sam_header_read2(const char *fn) { bam_header_t *header; int c, dret, ret, error = 0; gzFile fp; kstream_t *ks; kstring_t *str; kh_ref_t *hash; khiter_t k; if (fn == 0) return 0; fp = (strcmp(fn, "-") == 0)? gzdopen(fileno(stdin), "r") : gzopen(fn, "r"); if (fp == 0) return 0; hash = kh_init(ref); ks = ks_init(fp); str = (kstring_t*)calloc(1, sizeof(kstring_t)); while (ks_getuntil(ks, 0, str, &dret) > 0) { char *s = strdup(str->s); int len, i; i = kh_size(hash); ks_getuntil(ks, 0, str, &dret); len = atoi(str->s); k = kh_put(ref, hash, s, &ret); if (ret == 0) { fprintf(stderr, "[sam_header_read2] duplicated sequence name: %s\n", s); error = 1; } kh_value(hash, k) = (uint64_t)len<<32 | i; if (dret != '\n') while ((c = ks_getc(ks)) != '\n' && c != -1); } ks_destroy(ks); gzclose(fp); free(str->s); free(str); fprintf(stderr, "[sam_header_read2] %d sequences loaded.\n", kh_size(hash)); if (error) return 0; header = hash2header(hash); kh_destroy(ref, hash); return header; } static inline uint8_t *alloc_data(bam1_t *b, int size) { if (b->m_data < size) { b->m_data = size; kroundup32(b->m_data); b->data = (uint8_t*)realloc(b->data, b->m_data); } return b->data; } static inline void parse_error(int64_t n_lines, const char * __restrict msg) { fprintf(stderr, "Parse error at line %lld: %s\n", (long long)n_lines, msg); abort(); } static inline void append_text(bam_header_t *header, kstring_t *str) { size_t x = header->l_text, y = header->l_text + str->l + 2; // 2 = 1 byte dret + 1 byte null kroundup32(x); kroundup32(y); if (x < y) { header->n_text = y; header->text = (char*)realloc(header->text, y); if ( !header->text ) { fprintf(stderr,"realloc failed to alloc %ld bytes\n", y); abort(); } } // Sanity check if ( header->l_text+str->l+1 >= header->n_text ) { fprintf(stderr,"append_text FIXME: %ld>=%ld, x=%ld,y=%ld\n", header->l_text+str->l+1,(long)header->n_text,x,y); abort(); } strncpy(header->text + header->l_text, str->s, str->l+1); // we cannot use strcpy() here. header->l_text += str->l + 1; header->text[header->l_text] = 0; } int sam_header_parse(bam_header_t *h) { char **tmp; int i; free(h->target_len); free(h->target_name); h->n_targets = 0; h->target_len = 0; h->target_name = 0; if (h->l_text < 3) return 0; if (h->dict == 0) h->dict = sam_header_parse2(h->text); tmp = sam_header2list(h->dict, "SQ", "SN", &h->n_targets); if (h->n_targets == 0) return 0; h->target_name = calloc(h->n_targets, sizeof(void*)); for (i = 0; i < h->n_targets; ++i) h->target_name[i] = strdup(tmp[i]); free(tmp); tmp = sam_header2list(h->dict, "SQ", "LN", &h->n_targets); h->target_len = calloc(h->n_targets, 4); for (i = 0; i < h->n_targets; ++i) h->target_len[i] = atoi(tmp[i]); free(tmp); return h->n_targets; } bam_header_t *sam_header_read(tamFile fp) { int ret, dret; bam_header_t *header = bam_header_init(); kstring_t *str = fp->str; while ((ret = ks_getuntil(fp->ks, KS_SEP_TAB, str, &dret)) >= 0 && str->s[0] == '@') { // skip header str->s[str->l] = dret; // note that str->s is NOT null terminated!! append_text(header, str); if (dret != '\n') { ret = ks_getuntil(fp->ks, '\n', str, &dret); str->s[str->l] = '\n'; // NOT null terminated!! append_text(header, str); } ++fp->n_lines; } sam_header_parse(header); bam_init_header_hash(header); fp->is_first = 1; return header; } int sam_read1(tamFile fp, bam_header_t *header, bam1_t *b) { int ret, doff, doff0, dret, z = 0; bam1_core_t *c = &b->core; kstring_t *str = fp->str; kstream_t *ks = fp->ks; if (fp->is_first) { fp->is_first = 0; ret = str->l; } else { do { // special consideration for empty lines ret = ks_getuntil(fp->ks, KS_SEP_TAB, str, &dret); if (ret >= 0) z += str->l + 1; } while (ret == 0); } if (ret < 0) return -1; ++fp->n_lines; doff = 0; { // name c->l_qname = strlen(str->s) + 1; memcpy(alloc_data(b, doff + c->l_qname) + doff, str->s, c->l_qname); doff += c->l_qname; } { // flag long flag; char *s; ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1; flag = strtol((char*)str->s, &s, 0); if (*s) { // not the end of the string flag = 0; for (s = str->s; *s; ++s) flag |= bam_char2flag_table[(int)*s]; } c->flag = flag; } { // tid, pos, qual ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1; c->tid = bam_get_tid(header, str->s); if (c->tid < 0 && strcmp(str->s, "*")) { if (header->n_targets == 0) { fprintf(stderr, "[sam_read1] missing header? Abort!\n"); exit(1); } else fprintf(stderr, "[sam_read1] reference '%s' is recognized as '*'.\n", str->s); } ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1; c->pos = isdigit(str->s[0])? atoi(str->s) - 1 : -1; ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1; c->qual = isdigit(str->s[0])? atoi(str->s) : 0; if (ret < 0) return -2; } { // cigar char *s, *t; int i, op; long x; c->n_cigar = 0; if (ks_getuntil(ks, KS_SEP_TAB, str, &dret) < 0) return -3; z += str->l + 1; if (str->s[0] != '*') { uint32_t *cigar; for (s = str->s; *s; ++s) { if ((isalpha(*s)) || (*s=='=')) ++c->n_cigar; else if (!isdigit(*s)) parse_error(fp->n_lines, "invalid CIGAR character"); } b->data = alloc_data(b, doff + c->n_cigar * 4); cigar = bam1_cigar(b); for (i = 0, s = str->s; i != c->n_cigar; ++i) { x = strtol(s, &t, 10); op = toupper(*t); if (op == 'M') op = BAM_CMATCH; else if (op == 'I') op = BAM_CINS; else if (op == 'D') op = BAM_CDEL; else if (op == 'N') op = BAM_CREF_SKIP; else if (op == 'S') op = BAM_CSOFT_CLIP; else if (op == 'H') op = BAM_CHARD_CLIP; else if (op == 'P') op = BAM_CPAD; else if (op == '=') op = BAM_CEQUAL; else if (op == 'X') op = BAM_CDIFF; else if (op == 'B') op = BAM_CBACK; else parse_error(fp->n_lines, "invalid CIGAR operation"); s = t + 1; cigar[i] = bam_cigar_gen(x, op); } if (*s) parse_error(fp->n_lines, "unmatched CIGAR operation"); c->bin = bam_reg2bin(c->pos, bam_calend(c, cigar)); doff += c->n_cigar * 4; } else { if (!(c->flag&BAM_FUNMAP)) { fprintf(stderr, "Parse warning at line %lld: mapped sequence without CIGAR\n", (long long)fp->n_lines); c->flag |= BAM_FUNMAP; } c->bin = bam_reg2bin(c->pos, c->pos + 1); } } { // mtid, mpos, isize ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1; c->mtid = strcmp(str->s, "=")? bam_get_tid(header, str->s) : c->tid; ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1; c->mpos = isdigit(str->s[0])? atoi(str->s) - 1 : -1; ret = ks_getuntil(ks, KS_SEP_TAB, str, &dret); z += str->l + 1; c->isize = (str->s[0] == '-' || isdigit(str->s[0]))? atoi(str->s) : 0; if (ret < 0) return -4; } { // seq and qual int i; uint8_t *p = 0; if (ks_getuntil(ks, KS_SEP_TAB, str, &dret) < 0) return -5; // seq z += str->l + 1; if (strcmp(str->s, "*")) { c->l_qseq = strlen(str->s); if (c->n_cigar && c->l_qseq != (int32_t)bam_cigar2qlen(c, bam1_cigar(b))) { fprintf(stderr, "Line %ld, sequence length %i vs %i from CIGAR\n", (long)fp->n_lines, c->l_qseq, (int32_t)bam_cigar2qlen(c, bam1_cigar(b))); parse_error(fp->n_lines, "CIGAR and sequence length are inconsistent"); } p = (uint8_t*)alloc_data(b, doff + c->l_qseq + (c->l_qseq+1)/2) + doff; memset(p, 0, (c->l_qseq+1)/2); for (i = 0; i < c->l_qseq; ++i) p[i/2] |= bam_nt16_table[(int)str->s[i]] << 4*(1-i%2); } else c->l_qseq = 0; if (ks_getuntil(ks, KS_SEP_TAB, str, &dret) < 0) return -6; // qual z += str->l + 1; if (strcmp(str->s, "*") && c->l_qseq != strlen(str->s)) parse_error(fp->n_lines, "sequence and quality are inconsistent"); p += (c->l_qseq+1)/2; if (strcmp(str->s, "*") == 0) for (i = 0; i < c->l_qseq; ++i) p[i] = 0xff; else for (i = 0; i < c->l_qseq; ++i) p[i] = str->s[i] - 33; doff += c->l_qseq + (c->l_qseq+1)/2; } doff0 = doff; if (dret != '\n' && dret != '\r') { // aux while (ks_getuntil(ks, KS_SEP_TAB, str, &dret) >= 0) { uint8_t *s, type, key[2]; z += str->l + 1; if (str->l < 6 || str->s[2] != ':' || str->s[4] != ':') parse_error(fp->n_lines, "missing colon in auxiliary data"); key[0] = str->s[0]; key[1] = str->s[1]; type = str->s[3]; s = alloc_data(b, doff + 3) + doff; s[0] = key[0]; s[1] = key[1]; s += 2; doff += 2; if (type == 'A' || type == 'a' || type == 'c' || type == 'C') { // c and C for backward compatibility s = alloc_data(b, doff + 2) + doff; *s++ = 'A'; *s = str->s[5]; doff += 2; } else if (type == 'I' || type == 'i') { long long x; s = alloc_data(b, doff + 5) + doff; x = (long long)atoll(str->s + 5); if (x < 0) { if (x >= -127) { *s++ = 'c'; *(int8_t*)s = (int8_t)x; s += 1; doff += 2; } else if (x >= -32767) { *s++ = 's'; *(int16_t*)s = (int16_t)x; s += 2; doff += 3; } else { *s++ = 'i'; *(int32_t*)s = (int32_t)x; s += 4; doff += 5; if (x < -2147483648ll) fprintf(stderr, "Parse warning at line %lld: integer %lld is out of range.", (long long)fp->n_lines, x); } } else { if (x <= 255) { *s++ = 'C'; *s++ = (uint8_t)x; doff += 2; } else if (x <= 65535) { *s++ = 'S'; *(uint16_t*)s = (uint16_t)x; s += 2; doff += 3; } else { *s++ = 'I'; *(uint32_t*)s = (uint32_t)x; s += 4; doff += 5; if (x > 4294967295ll) fprintf(stderr, "Parse warning at line %lld: integer %lld is out of range.", (long long)fp->n_lines, x); } } } else if (type == 'f') { s = alloc_data(b, doff + 5) + doff; *s++ = 'f'; *(float*)s = (float)atof(str->s + 5); s += 4; doff += 5; } else if (type == 'd') { s = alloc_data(b, doff + 9) + doff; *s++ = 'd'; *(float*)s = (float)atof(str->s + 9); s += 8; doff += 9; } else if (type == 'Z' || type == 'H') { int size = 1 + (str->l - 5) + 1; if (type == 'H') { // check whether the hex string is valid int i; if ((str->l - 5) % 2 == 1) parse_error(fp->n_lines, "length of the hex string not even"); for (i = 0; i < str->l - 5; ++i) { int c = toupper(str->s[5 + i]); if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'))) parse_error(fp->n_lines, "invalid hex character"); } } s = alloc_data(b, doff + size) + doff; *s++ = type; memcpy(s, str->s + 5, str->l - 5); s[str->l - 5] = 0; doff += size; } else if (type == 'B') { int32_t n = 0, Bsize, k = 0, size; char *p; if (str->l < 8) parse_error(fp->n_lines, "too few values in aux type B"); Bsize = bam_aux_type2size(str->s[5]); // the size of each element for (p = (char*)str->s + 6; *p; ++p) // count the number of elements in the array if (*p == ',') ++n; p = str->s + 7; // now p points to the first number in the array size = 6 + Bsize * n; // total number of bytes allocated to this tag s = alloc_data(b, doff + 6 * Bsize * n) + doff; // allocate memory *s++ = 'B'; *s++ = str->s[5]; memcpy(s, &n, 4); s += 4; // write the number of elements if (str->s[5] == 'c') while (p < str->s + str->l) ((int8_t*)s)[k++] = (int8_t)strtol(p, &p, 0), ++p; else if (str->s[5] == 'C') while (p < str->s + str->l) ((uint8_t*)s)[k++] = (uint8_t)strtol(p, &p, 0), ++p; else if (str->s[5] == 's') while (p < str->s + str->l) ((int16_t*)s)[k++] = (int16_t)strtol(p, &p, 0), ++p; // FIXME: avoid unaligned memory else if (str->s[5] == 'S') while (p < str->s + str->l) ((uint16_t*)s)[k++] = (uint16_t)strtol(p, &p, 0), ++p; else if (str->s[5] == 'i') while (p < str->s + str->l) ((int32_t*)s)[k++] = (int32_t)strtol(p, &p, 0), ++p; else if (str->s[5] == 'I') while (p < str->s + str->l) ((uint32_t*)s)[k++] = (uint32_t)strtol(p, &p, 0), ++p; else if (str->s[5] == 'f') while (p < str->s + str->l) ((float*)s)[k++] = (float)strtod(p, &p), ++p; else parse_error(fp->n_lines, "unrecognized array type"); s += Bsize * n; doff += size; } else parse_error(fp->n_lines, "unrecognized type"); if (dret == '\n' || dret == '\r') break; } } b->l_aux = doff - doff0; b->data_len = doff; if (bam_no_B) bam_remove_B(b); return z; } tamFile sam_open(const char *fn) { tamFile fp; gzFile gzfp = (strcmp(fn, "-") == 0)? gzdopen(fileno(stdin), "rb") : gzopen(fn, "rb"); if (gzfp == 0) return 0; fp = (tamFile)calloc(1, sizeof(struct __tamFile_t)); fp->str = (kstring_t*)calloc(1, sizeof(kstring_t)); fp->fp = gzfp; fp->ks = ks_init(fp->fp); return fp; } void sam_close(tamFile fp) { if (fp) { ks_destroy(fp->ks); gzclose(fp->fp); free(fp->str->s); free(fp->str); free(fp); } }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/sample.c
.c
2,984
108
#include <stdlib.h> #include <string.h> #include "sample.h" #include "khash.h" KHASH_MAP_INIT_STR(sm, int) bam_sample_t *bam_smpl_init(void) { bam_sample_t *s; s = calloc(1, sizeof(bam_sample_t)); s->rg2smid = kh_init(sm); s->sm2id = kh_init(sm); return s; } void bam_smpl_destroy(bam_sample_t *sm) { int i; khint_t k; khash_t(sm) *rg2smid = (khash_t(sm)*)sm->rg2smid; if (sm == 0) return; for (i = 0; i < sm->n; ++i) free(sm->smpl[i]); free(sm->smpl); for (k = kh_begin(rg2smid); k != kh_end(rg2smid); ++k) if (kh_exist(rg2smid, k)) free((char*)kh_key(rg2smid, k)); kh_destroy(sm, sm->rg2smid); kh_destroy(sm, sm->sm2id); free(sm); } static void add_pair(bam_sample_t *sm, khash_t(sm) *sm2id, const char *key, const char *val) { khint_t k_rg, k_sm; int ret; khash_t(sm) *rg2smid = (khash_t(sm)*)sm->rg2smid; k_rg = kh_get(sm, rg2smid, key); if (k_rg != kh_end(rg2smid)) return; // duplicated @RG-ID k_rg = kh_put(sm, rg2smid, strdup(key), &ret); k_sm = kh_get(sm, sm2id, val); if (k_sm == kh_end(sm2id)) { // absent if (sm->n == sm->m) { sm->m = sm->m? sm->m<<1 : 1; sm->smpl = realloc(sm->smpl, sizeof(void*) * sm->m); } sm->smpl[sm->n] = strdup(val); k_sm = kh_put(sm, sm2id, sm->smpl[sm->n], &ret); kh_val(sm2id, k_sm) = sm->n++; } kh_val(rg2smid, k_rg) = kh_val(sm2id, k_sm); } int bam_smpl_add(bam_sample_t *sm, const char *fn, const char *txt) { const char *p = txt, *q, *r; kstring_t buf, first_sm; int n = 0; khash_t(sm) *sm2id = (khash_t(sm)*)sm->sm2id; if (txt == 0) { add_pair(sm, sm2id, fn, fn); return 0; } memset(&buf, 0, sizeof(kstring_t)); memset(&first_sm, 0, sizeof(kstring_t)); while ((q = strstr(p, "@RG")) != 0) { p = q + 3; r = q = 0; if ((q = strstr(p, "\tID:")) != 0) q += 4; if ((r = strstr(p, "\tSM:")) != 0) r += 4; if (r && q) { char *u, *v; int oq, or; for (u = (char*)q; *u && *u != '\t' && *u != '\n'; ++u); for (v = (char*)r; *v && *v != '\t' && *v != '\n'; ++v); oq = *u; or = *v; *u = *v = '\0'; buf.l = 0; kputs(fn, &buf); kputc('/', &buf); kputs(q, &buf); add_pair(sm, sm2id, buf.s, r); if ( !first_sm.s ) kputs(r,&first_sm); *u = oq; *v = or; } else break; p = q > r? q : r; ++n; } if (n == 0) add_pair(sm, sm2id, fn, fn); // If there is only one RG tag present in the header and reads are not annotated, don't refuse to work but // use the tag instead. else if ( n==1 && first_sm.s ) add_pair(sm,sm2id,fn,first_sm.s); if ( first_sm.s ) free(first_sm.s); // add_pair(sm, sm2id, fn, fn); free(buf.s); return 0; } int bam_smpl_rg2smid(const bam_sample_t *sm, const char *fn, const char *rg, kstring_t *str) { khint_t k; khash_t(sm) *rg2smid = (khash_t(sm)*)sm->rg2smid; if (rg) { str->l = 0; kputs(fn, str); kputc('/', str); kputs(rg, str); k = kh_get(sm, rg2smid, str->s); } else k = kh_get(sm, rg2smid, fn); return k == kh_end(rg2smid)? -1 : kh_val(rg2smid, k); }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_plcmd.c
.c
22,175
607
#include <math.h> #include <stdio.h> #include <unistd.h> #include <ctype.h> #include <string.h> #include <errno.h> #include <sys/stat.h> #include <getopt.h> #include "sam.h" #include "faidx.h" #include "kstring.h" #include "sam_header.h" static inline int printw(int c, FILE *fp) { char buf[16]; int l, x; if (c == 0) return fputc('0', fp); for (l = 0, x = c < 0? -c : c; x > 0; x /= 10) buf[l++] = x%10 + '0'; if (c < 0) buf[l++] = '-'; buf[l] = 0; for (x = 0; x < l/2; ++x) { int y = buf[x]; buf[x] = buf[l-1-x]; buf[l-1-x] = y; } fputs(buf, fp); return 0; } static inline void pileup_seq(const bam_pileup1_t *p, int pos, int ref_len, const char *ref) { int j; if (p->is_head) { putchar('^'); putchar(p->b->core.qual > 93? 126 : p->b->core.qual + 33); } if (!p->is_del) { int c = bam_nt16_rev_table[bam1_seqi(bam1_seq(p->b), p->qpos)]; if (ref) { int rb = pos < ref_len? ref[pos] : 'N'; if (c == '=' || bam_nt16_table[c] == bam_nt16_table[rb]) c = bam1_strand(p->b)? ',' : '.'; else c = bam1_strand(p->b)? tolower(c) : toupper(c); } else { if (c == '=') c = bam1_strand(p->b)? ',' : '.'; else c = bam1_strand(p->b)? tolower(c) : toupper(c); } putchar(c); } else putchar(p->is_refskip? (bam1_strand(p->b)? '<' : '>') : '*'); if (p->indel > 0) { putchar('+'); printw(p->indel, stdout); for (j = 1; j <= p->indel; ++j) { int c = bam_nt16_rev_table[bam1_seqi(bam1_seq(p->b), p->qpos + j)]; putchar(bam1_strand(p->b)? tolower(c) : toupper(c)); } } else if (p->indel < 0) { printw(p->indel, stdout); for (j = 1; j <= -p->indel; ++j) { int c = (ref && (int)pos+j < ref_len)? ref[pos+j] : 'N'; putchar(bam1_strand(p->b)? tolower(c) : toupper(c)); } } if (p->is_tail) putchar('$'); } #include <assert.h> #include "bam2bcf.h" #include "sample.h" #define MPLP_GLF 0x10 #define MPLP_NO_COMP 0x20 #define MPLP_NO_ORPHAN 0x40 #define MPLP_REALN 0x80 #define MPLP_NO_INDEL 0x400 #define MPLP_REDO_BAQ 0x800 #define MPLP_ILLUMINA13 0x1000 #define MPLP_IGNORE_RG 0x2000 #define MPLP_PRINT_POS 0x4000 #define MPLP_PRINT_MAPQ 0x8000 #define MPLP_PER_SAMPLE 0x10000 void *bed_read(const char *fn); void bed_destroy(void *_h); int bed_overlap(const void *_h, const char *chr, int beg, int end); typedef struct { int max_mq, min_mq, flag, min_baseQ, capQ_thres, max_depth, max_indel_depth, fmt_flag; int rflag_require, rflag_filter; int openQ, extQ, tandemQ, min_support; // for indels double min_frac; // for indels char *reg, *pl_list, *fai_fname; faidx_t *fai; void *bed, *rghash; } mplp_conf_t; typedef struct { bamFile fp; bam_iter_t iter; bam_header_t *h; int ref_id; char *ref; const mplp_conf_t *conf; } mplp_aux_t; typedef struct { int n; int *n_plp, *m_plp; bam_pileup1_t **plp; } mplp_pileup_t; static int mplp_func(void *data, bam1_t *b) { extern int bam_realn(bam1_t *b, const char *ref); extern int bam_prob_realn_core(bam1_t *b, const char *ref, int); extern int bam_cap_mapQ(bam1_t *b, char *ref, int thres); mplp_aux_t *ma = (mplp_aux_t*)data; int ret, skip = 0; do { int has_ref; ret = ma->iter? bam_iter_read(ma->fp, ma->iter, b) : bam_read1(ma->fp, b); if (ret < 0) break; if (b->core.tid < 0 || (b->core.flag&BAM_FUNMAP)) { // exclude unmapped reads skip = 1; continue; } if (ma->conf->rflag_require && !(ma->conf->rflag_require&b->core.flag)) { skip = 1; continue; } if (ma->conf->rflag_filter && ma->conf->rflag_filter&b->core.flag) { skip = 1; continue; } if (ma->conf->bed) { // test overlap skip = !bed_overlap(ma->conf->bed, ma->h->target_name[b->core.tid], b->core.pos, bam_calend(&b->core, bam1_cigar(b))); if (skip) continue; } if (ma->conf->rghash) { // exclude read groups uint8_t *rg = bam_aux_get(b, "RG"); skip = (rg && bcf_str2id(ma->conf->rghash, (const char*)(rg+1)) >= 0); if (skip) continue; } if (ma->conf->flag & MPLP_ILLUMINA13) { int i; uint8_t *qual = bam1_qual(b); for (i = 0; i < b->core.l_qseq; ++i) qual[i] = qual[i] > 31? qual[i] - 31 : 0; } has_ref = (ma->ref && ma->ref_id == b->core.tid)? 1 : 0; skip = 0; if (has_ref && (ma->conf->flag&MPLP_REALN)) bam_prob_realn_core(b, ma->ref, (ma->conf->flag & MPLP_REDO_BAQ)? 7 : 3); if (has_ref && ma->conf->capQ_thres > 10) { int q = bam_cap_mapQ(b, ma->ref, ma->conf->capQ_thres); if (q < 0) skip = 1; else if (b->core.qual > q) b->core.qual = q; } else if (b->core.qual < ma->conf->min_mq) skip = 1; else if ((ma->conf->flag&MPLP_NO_ORPHAN) && (b->core.flag&1) && !(b->core.flag&2)) skip = 1; } while (skip); return ret; } static void group_smpl(mplp_pileup_t *m, bam_sample_t *sm, kstring_t *buf, int n, char *const*fn, int *n_plp, const bam_pileup1_t **plp, int ignore_rg) { int i, j; memset(m->n_plp, 0, m->n * sizeof(int)); for (i = 0; i < n; ++i) { for (j = 0; j < n_plp[i]; ++j) { const bam_pileup1_t *p = plp[i] + j; uint8_t *q; int id = -1; q = ignore_rg? 0 : bam_aux_get(p->b, "RG"); if (q) id = bam_smpl_rg2smid(sm, fn[i], (char*)q+1, buf); if (id < 0) id = bam_smpl_rg2smid(sm, fn[i], 0, buf); if (id < 0 || id >= m->n) { assert(q); // otherwise a bug fprintf(stderr, "[%s] Read group %s used in file %s but absent from the header or an alignment missing read group.\n", __func__, (char*)q+1, fn[i]); exit(1); } if (m->n_plp[id] == m->m_plp[id]) { m->m_plp[id] = m->m_plp[id]? m->m_plp[id]<<1 : 8; m->plp[id] = realloc(m->plp[id], sizeof(bam_pileup1_t) * m->m_plp[id]); } m->plp[id][m->n_plp[id]++] = *p; } } } static int mpileup(mplp_conf_t *conf, int n, char **fn) { extern void *bcf_call_add_rg(void *rghash, const char *hdtext, const char *list); extern void bcf_call_del_rghash(void *rghash); mplp_aux_t **data; int i, tid, pos, *n_plp, tid0 = -1, beg0 = 0, end0 = 1u<<29, ref_len, ref_tid = -1, max_depth, max_indel_depth; const bam_pileup1_t **plp; bam_mplp_t iter; bam_header_t *h = 0; char *ref; void *rghash = 0; bcf_callaux_t *bca = 0; bcf_callret1_t *bcr = 0; bcf_call_t bc; bcf_t *bp = 0; bcf_hdr_t *bh = 0; bam_sample_t *sm = 0; kstring_t buf; mplp_pileup_t gplp; memset(&gplp, 0, sizeof(mplp_pileup_t)); memset(&buf, 0, sizeof(kstring_t)); memset(&bc, 0, sizeof(bcf_call_t)); data = calloc(n, sizeof(void*)); plp = calloc(n, sizeof(void*)); n_plp = calloc(n, sizeof(int*)); sm = bam_smpl_init(); // read the header and initialize data for (i = 0; i < n; ++i) { bam_header_t *h_tmp; data[i] = calloc(1, sizeof(mplp_aux_t)); data[i]->fp = strcmp(fn[i], "-") == 0? bam_dopen(fileno(stdin), "r") : bam_open(fn[i], "r"); if ( !data[i]->fp ) { fprintf(stderr, "[%s] failed to open %s: %s\n", __func__, fn[i], strerror(errno)); exit(1); } data[i]->conf = conf; h_tmp = bam_header_read(data[i]->fp); if ( !h_tmp ) { fprintf(stderr,"[%s] fail to read the header of %s\n", __func__, fn[i]); exit(1); } data[i]->h = i? h : h_tmp; // for i==0, "h" has not been set yet bam_smpl_add(sm, fn[i], (conf->flag&MPLP_IGNORE_RG)? 0 : h_tmp->text); rghash = bcf_call_add_rg(rghash, h_tmp->text, conf->pl_list); if (conf->reg) { int beg, end; bam_index_t *idx; idx = bam_index_load(fn[i]); if (idx == 0) { fprintf(stderr, "[%s] fail to load index for %s\n", __func__, fn[i]); exit(1); } if (bam_parse_region(h_tmp, conf->reg, &tid, &beg, &end) < 0) { fprintf(stderr, "[%s] malformatted region or wrong seqname for %s\n", __func__, fn[i]); exit(1); } if (i == 0) tid0 = tid, beg0 = beg, end0 = end; data[i]->iter = bam_iter_query(idx, tid, beg, end); bam_index_destroy(idx); } if (i == 0) h = h_tmp; else { // FIXME: to check consistency bam_header_destroy(h_tmp); } } gplp.n = sm->n; gplp.n_plp = calloc(sm->n, sizeof(int)); gplp.m_plp = calloc(sm->n, sizeof(int)); gplp.plp = calloc(sm->n, sizeof(void*)); fprintf(stderr, "[%s] %d samples in %d input files\n", __func__, sm->n, n); // write the VCF header if (conf->flag & MPLP_GLF) { kstring_t s; bh = calloc(1, sizeof(bcf_hdr_t)); s.l = s.m = 0; s.s = 0; bp = bcf_open("-", (conf->flag&MPLP_NO_COMP)? "wu" : "w"); for (i = 0; i < h->n_targets; ++i) { kputs(h->target_name[i], &s); kputc('\0', &s); } bh->l_nm = s.l; bh->name = malloc(s.l); memcpy(bh->name, s.s, s.l); s.l = 0; for (i = 0; i < sm->n; ++i) { kputs(sm->smpl[i], &s); kputc('\0', &s); } bh->l_smpl = s.l; bh->sname = malloc(s.l); memcpy(bh->sname, s.s, s.l); s.l = 0; ksprintf(&s, "##samtoolsVersion=%s\n", BAM_VERSION); if (conf->fai_fname) ksprintf(&s, "##reference=file://%s\n", conf->fai_fname); h->dict = sam_header_parse2(h->text); int nseq; const char *tags[] = {"SN","LN","UR","M5",NULL}; char **tbl = sam_header2tbl_n(h->dict, "SQ", tags, &nseq); for (i=0; i<nseq; i++) { ksprintf(&s, "##contig=<ID=%s", tbl[4*i]); if ( tbl[4*i+1] ) ksprintf(&s, ",length=%s", tbl[4*i+1]); if ( tbl[4*i+2] ) ksprintf(&s, ",URL=%s", tbl[4*i+2]); if ( tbl[4*i+3] ) ksprintf(&s, ",md5=%s", tbl[4*i+3]); kputs(">\n", &s); } if (tbl) free(tbl); bh->txt = s.s; bh->l_txt = 1 + s.l; bcf_hdr_sync(bh); bcf_hdr_write(bp, bh); bca = bcf_call_init(-1., conf->min_baseQ); bcr = calloc(sm->n, sizeof(bcf_callret1_t)); bca->rghash = rghash; bca->openQ = conf->openQ, bca->extQ = conf->extQ, bca->tandemQ = conf->tandemQ; bca->min_frac = conf->min_frac; bca->min_support = conf->min_support; bca->per_sample_flt = conf->flag & MPLP_PER_SAMPLE; } if (tid0 >= 0 && conf->fai) { // region is set ref = faidx_fetch_seq(conf->fai, h->target_name[tid0], 0, 0x7fffffff, &ref_len); ref_tid = tid0; for (i = 0; i < n; ++i) data[i]->ref = ref, data[i]->ref_id = tid0; } else ref_tid = -1, ref = 0; iter = bam_mplp_init(n, mplp_func, (void**)data); max_depth = conf->max_depth; if (max_depth * sm->n > 1<<20) fprintf(stderr, "(%s) Max depth is above 1M. Potential memory hog!\n", __func__); if (max_depth * sm->n < 8000) { max_depth = 8000 / sm->n; fprintf(stderr, "<%s> Set max per-file depth to %d\n", __func__, max_depth); } max_indel_depth = conf->max_indel_depth * sm->n; bam_mplp_set_maxcnt(iter, max_depth); while (bam_mplp_auto(iter, &tid, &pos, n_plp, plp) > 0) { if (conf->reg && (pos < beg0 || pos >= end0)) continue; // out of the region requested if (conf->bed && tid >= 0 && !bed_overlap(conf->bed, h->target_name[tid], pos, pos+1)) continue; if (tid != ref_tid) { free(ref); ref = 0; if (conf->fai) ref = faidx_fetch_seq(conf->fai, h->target_name[tid], 0, 0x7fffffff, &ref_len); for (i = 0; i < n; ++i) data[i]->ref = ref, data[i]->ref_id = tid; ref_tid = tid; } if (conf->flag & MPLP_GLF) { int total_depth, _ref0, ref16; bcf1_t *b = calloc(1, sizeof(bcf1_t)); for (i = total_depth = 0; i < n; ++i) total_depth += n_plp[i]; group_smpl(&gplp, sm, &buf, n, fn, n_plp, plp, conf->flag & MPLP_IGNORE_RG); _ref0 = (ref && pos < ref_len)? ref[pos] : 'N'; ref16 = bam_nt16_table[_ref0]; for (i = 0; i < gplp.n; ++i) bcf_call_glfgen(gplp.n_plp[i], gplp.plp[i], ref16, bca, bcr + i); bcf_call_combine(gplp.n, bcr, bca, ref16, &bc); bcf_call2bcf(tid, pos, &bc, b, bcr, conf->fmt_flag, 0, 0); bcf_write(bp, bh, b); bcf_destroy(b); // call indels if (!(conf->flag&MPLP_NO_INDEL) && total_depth < max_indel_depth && bcf_call_gap_prep(gplp.n, gplp.n_plp, gplp.plp, pos, bca, ref, rghash) >= 0) { for (i = 0; i < gplp.n; ++i) bcf_call_glfgen(gplp.n_plp[i], gplp.plp[i], -1, bca, bcr + i); if (bcf_call_combine(gplp.n, bcr, bca, -1, &bc) >= 0) { b = calloc(1, sizeof(bcf1_t)); bcf_call2bcf(tid, pos, &bc, b, bcr, conf->fmt_flag, bca, ref); bcf_write(bp, bh, b); bcf_destroy(b); } } } else { printf("%s\t%d\t%c", h->target_name[tid], pos + 1, (ref && pos < ref_len)? ref[pos] : 'N'); for (i = 0; i < n; ++i) { int j, cnt; for (j = cnt = 0; j < n_plp[i]; ++j) { const bam_pileup1_t *p = plp[i] + j; if (bam1_qual(p->b)[p->qpos] >= conf->min_baseQ) ++cnt; } printf("\t%d\t", cnt); if (n_plp[i] == 0) { printf("*\t*"); // FIXME: printf() is very slow... if (conf->flag & MPLP_PRINT_POS) printf("\t*"); } else { for (j = 0; j < n_plp[i]; ++j) { const bam_pileup1_t *p = plp[i] + j; if (bam1_qual(p->b)[p->qpos] >= conf->min_baseQ) pileup_seq(plp[i] + j, pos, ref_len, ref); } putchar('\t'); for (j = 0; j < n_plp[i]; ++j) { const bam_pileup1_t *p = plp[i] + j; int c = bam1_qual(p->b)[p->qpos]; if (c >= conf->min_baseQ) { c = c + 33 < 126? c + 33 : 126; putchar(c); } } if (conf->flag & MPLP_PRINT_MAPQ) { putchar('\t'); for (j = 0; j < n_plp[i]; ++j) { int c = plp[i][j].b->core.qual + 33; if (c > 126) c = 126; putchar(c); } } if (conf->flag & MPLP_PRINT_POS) { putchar('\t'); for (j = 0; j < n_plp[i]; ++j) { if (j > 0) putchar(','); printf("%d", plp[i][j].qpos + 1); // FIXME: printf() is very slow... } } } } putchar('\n'); } } bcf_close(bp); bam_smpl_destroy(sm); free(buf.s); for (i = 0; i < gplp.n; ++i) free(gplp.plp[i]); free(gplp.plp); free(gplp.n_plp); free(gplp.m_plp); bcf_call_del_rghash(rghash); bcf_hdr_destroy(bh); bcf_call_destroy(bca); free(bc.PL); free(bcr); bam_mplp_destroy(iter); bam_header_destroy(h); for (i = 0; i < n; ++i) { bam_close(data[i]->fp); if (data[i]->iter) bam_iter_destroy(data[i]->iter); free(data[i]); } free(data); free(plp); free(ref); free(n_plp); return 0; } #define MAX_PATH_LEN 1024 int read_file_list(const char *file_list,int *n,char **argv[]) { char buf[MAX_PATH_LEN]; int len, nfiles = 0; char **files = NULL; struct stat sb; *n = 0; *argv = NULL; FILE *fh = fopen(file_list,"r"); if ( !fh ) { fprintf(stderr,"%s: %s\n", file_list,strerror(errno)); return 1; } files = calloc(nfiles,sizeof(char*)); nfiles = 0; while ( fgets(buf,MAX_PATH_LEN,fh) ) { // allow empty lines and trailing spaces len = strlen(buf); while ( len>0 && isspace(buf[len-1]) ) len--; if ( !len ) continue; // check sanity of the file list buf[len] = 0; if (stat(buf, &sb) != 0) { // no such file, check if it is safe to print its name int i, safe_to_print = 1; for (i=0; i<len; i++) if (!isprint(buf[i])) { safe_to_print = 0; break; } if ( safe_to_print ) fprintf(stderr,"The file list \"%s\" appears broken, could not locate: %s\n", file_list,buf); else fprintf(stderr,"Does the file \"%s\" really contain a list of files and do all exist?\n", file_list); return 1; } nfiles++; files = realloc(files,nfiles*sizeof(char*)); files[nfiles-1] = strdup(buf); } fclose(fh); if ( !nfiles ) { fprintf(stderr,"No files read from %s\n", file_list); return 1; } *argv = files; *n = nfiles; return 0; } #undef MAX_PATH_LEN int bam_mpileup(int argc, char *argv[]) { int c; const char *file_list = NULL; char **fn = NULL; int nfiles = 0, use_orphan = 0; mplp_conf_t mplp; memset(&mplp, 0, sizeof(mplp_conf_t)); mplp.max_mq = 60; mplp.min_baseQ = 13; mplp.capQ_thres = 0; mplp.max_depth = 250; mplp.max_indel_depth = 250; mplp.openQ = 40; mplp.extQ = 20; mplp.tandemQ = 100; mplp.min_frac = 0.002; mplp.min_support = 1; mplp.flag = MPLP_NO_ORPHAN | MPLP_REALN; static struct option lopts[] = { {"rf",1,0,1}, // require flag {"ff",1,0,2}, // filter flag {0,0,0,0} }; while ((c = getopt_long(argc, argv, "Agf:r:l:M:q:Q:uaRC:BDSd:L:b:P:po:e:h:Im:F:EG:6OsV1:2:",lopts,NULL)) >= 0) { switch (c) { case 1 : mplp.rflag_require = strtol(optarg,0,0); break; case 2 : mplp.rflag_filter = strtol(optarg,0,0); break; case 'f': mplp.fai = fai_load(optarg); if (mplp.fai == 0) return 1; mplp.fai_fname = optarg; break; case 'd': mplp.max_depth = atoi(optarg); break; case 'r': mplp.reg = strdup(optarg); break; case 'l': mplp.bed = bed_read(optarg); break; case 'P': mplp.pl_list = strdup(optarg); break; case 'p': mplp.flag |= MPLP_PER_SAMPLE; break; case 'g': mplp.flag |= MPLP_GLF; break; case 'u': mplp.flag |= MPLP_NO_COMP | MPLP_GLF; break; case 'a': mplp.flag |= MPLP_NO_ORPHAN | MPLP_REALN; break; case 'B': mplp.flag &= ~MPLP_REALN; break; case 'D': mplp.fmt_flag |= B2B_FMT_DP; break; case 'S': mplp.fmt_flag |= B2B_FMT_SP; break; case 'V': mplp.fmt_flag |= B2B_FMT_DV; break; case 'I': mplp.flag |= MPLP_NO_INDEL; break; case 'E': mplp.flag |= MPLP_REDO_BAQ; break; case '6': mplp.flag |= MPLP_ILLUMINA13; break; case 'R': mplp.flag |= MPLP_IGNORE_RG; break; case 's': mplp.flag |= MPLP_PRINT_MAPQ; break; case 'O': mplp.flag |= MPLP_PRINT_POS; break; case 'C': mplp.capQ_thres = atoi(optarg); break; case 'M': mplp.max_mq = atoi(optarg); break; case 'q': mplp.min_mq = atoi(optarg); break; case 'Q': mplp.min_baseQ = atoi(optarg); break; case 'b': file_list = optarg; break; case 'o': mplp.openQ = atoi(optarg); break; case 'e': mplp.extQ = atoi(optarg); break; case 'h': mplp.tandemQ = atoi(optarg); break; case 'A': use_orphan = 1; break; case 'F': mplp.min_frac = atof(optarg); break; case 'm': mplp.min_support = atoi(optarg); break; case 'L': mplp.max_indel_depth = atoi(optarg); break; case 'G': { FILE *fp_rg; char buf[1024]; mplp.rghash = bcf_str2id_init(); if ((fp_rg = fopen(optarg, "r")) == 0) fprintf(stderr, "(%s) Fail to open file %s. Continue anyway.\n", __func__, optarg); while (!feof(fp_rg) && fscanf(fp_rg, "%s", buf) > 0) // this is not a good style, but forgive me... bcf_str2id_add(mplp.rghash, strdup(buf)); fclose(fp_rg); } break; } } if (use_orphan) mplp.flag &= ~MPLP_NO_ORPHAN; if (argc == 1) { fprintf(stderr, "\n"); fprintf(stderr, "Usage: samtools mpileup [options] in1.bam [in2.bam [...]]\n\n"); fprintf(stderr, "Input options:\n\n"); fprintf(stderr, " -6 assume the quality is in the Illumina-1.3+ encoding\n"); fprintf(stderr, " -A count anomalous read pairs\n"); fprintf(stderr, " -B disable BAQ computation\n"); fprintf(stderr, " -b FILE list of input BAM filenames, one per line [null]\n"); fprintf(stderr, " -C INT parameter for adjusting mapQ; 0 to disable [0]\n"); fprintf(stderr, " -d INT max per-BAM depth to avoid excessive memory usage [%d]\n", mplp.max_depth); fprintf(stderr, " -E recalculate extended BAQ on the fly thus ignoring existing BQs\n"); fprintf(stderr, " -f FILE faidx indexed reference sequence file [null]\n"); fprintf(stderr, " -G FILE exclude read groups listed in FILE [null]\n"); fprintf(stderr, " -l FILE list of positions (chr pos) or regions (BED) [null]\n"); fprintf(stderr, " -M INT cap mapping quality at INT [%d]\n", mplp.max_mq); fprintf(stderr, " -r STR region in which pileup is generated [null]\n"); fprintf(stderr, " -R ignore RG tags\n"); fprintf(stderr, " -q INT skip alignments with mapQ smaller than INT [%d]\n", mplp.min_mq); fprintf(stderr, " -Q INT skip bases with baseQ/BAQ smaller than INT [%d]\n", mplp.min_baseQ); fprintf(stderr, " --rf INT required flags: skip reads with mask bits unset []\n"); fprintf(stderr, " --ff INT filter flags: skip reads with mask bits set []\n"); fprintf(stderr, "\nOutput options:\n\n"); fprintf(stderr, " -D output per-sample DP in BCF (require -g/-u)\n"); fprintf(stderr, " -g generate BCF output (genotype likelihoods)\n"); fprintf(stderr, " -O output base positions on reads (disabled by -g/-u)\n"); fprintf(stderr, " -s output mapping quality (disabled by -g/-u)\n"); fprintf(stderr, " -S output per-sample strand bias P-value in BCF (require -g/-u)\n"); fprintf(stderr, " -u generate uncompress BCF output\n"); fprintf(stderr, "\nSNP/INDEL genotype likelihoods options (effective with `-g' or `-u'):\n\n"); fprintf(stderr, " -e INT Phred-scaled gap extension seq error probability [%d]\n", mplp.extQ); fprintf(stderr, " -F FLOAT minimum fraction of gapped reads for candidates [%g]\n", mplp.min_frac); fprintf(stderr, " -h INT coefficient for homopolymer errors [%d]\n", mplp.tandemQ); fprintf(stderr, " -I do not perform indel calling\n"); fprintf(stderr, " -L INT max per-sample depth for INDEL calling [%d]\n", mplp.max_indel_depth); fprintf(stderr, " -m INT minimum gapped reads for indel candidates [%d]\n", mplp.min_support); fprintf(stderr, " -o INT Phred-scaled gap open sequencing error probability [%d]\n", mplp.openQ); fprintf(stderr, " -p apply -m and -F per-sample to increase sensitivity\n"); fprintf(stderr, " -P STR comma separated list of platforms for indels [all]\n"); fprintf(stderr, "\n"); fprintf(stderr, "Notes: Assuming diploid individuals.\n\n"); return 1; } bam_no_B = 1; if (file_list) { if ( read_file_list(file_list,&nfiles,&fn) ) return 1; mpileup(&mplp,nfiles,fn); for (c=0; c<nfiles; c++) free(fn[c]); free(fn); } else mpileup(&mplp, argc - optind, argv + optind); if (mplp.rghash) bcf_str2id_thorough_destroy(mplp.rghash); free(mplp.reg); free(mplp.pl_list); if (mplp.fai) fai_destroy(mplp.fai); if (mplp.bed) bed_destroy(mplp.bed); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/knetfile.h
.h
1,611
76
#ifndef KNETFILE_H #define KNETFILE_H #include <stdint.h> #include <fcntl.h> #ifndef _WIN32 #define netread(fd, ptr, len) read(fd, ptr, len) #define netwrite(fd, ptr, len) write(fd, ptr, len) #define netclose(fd) close(fd) #else #include <winsock2.h> #define netread(fd, ptr, len) recv(fd, ptr, len, 0) #define netwrite(fd, ptr, len) send(fd, ptr, len, 0) #define netclose(fd) closesocket(fd) #endif // FIXME: currently I/O is unbuffered #define KNF_TYPE_LOCAL 1 #define KNF_TYPE_FTP 2 #define KNF_TYPE_HTTP 3 typedef struct knetFile_s { int type, fd; int64_t offset; char *host, *port; // the following are for FTP only int ctrl_fd, pasv_ip[4], pasv_port, max_response, no_reconnect, is_ready; char *response, *retr, *size_cmd; int64_t seek_offset; // for lazy seek int64_t file_size; // the following are for HTTP only char *path, *http_host; } knetFile; #define knet_tell(fp) ((fp)->offset) #define knet_fileno(fp) ((fp)->fd) #ifdef __cplusplus extern "C" { #endif #ifdef _WIN32 int knet_win32_init(); void knet_win32_destroy(); #endif knetFile *knet_open(const char *fn, const char *mode); /* This only works with local files. */ knetFile *knet_dopen(int fd, const char *mode); /* If ->is_ready==0, this routine updates ->fd; otherwise, it simply reads from ->fd. */ off_t knet_read(knetFile *fp, void *buf, off_t len); /* This routine only sets ->offset and ->is_ready=0. It does not communicate with the FTP server. */ off_t knet_seek(knetFile *fp, int64_t off, int whence); int knet_close(knetFile *fp); #ifdef __cplusplus } #endif #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_pileup.c
.c
12,954
438
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <assert.h> #include "sam.h" typedef struct { int k, x, y, end; } cstate_t; static cstate_t g_cstate_null = { -1, 0, 0, 0 }; typedef struct __linkbuf_t { bam1_t b; uint32_t beg, end; cstate_t s; struct __linkbuf_t *next; } lbnode_t; /* --- BEGIN: Memory pool */ typedef struct { int cnt, n, max; lbnode_t **buf; } mempool_t; static mempool_t *mp_init() { mempool_t *mp; mp = (mempool_t*)calloc(1, sizeof(mempool_t)); return mp; } static void mp_destroy(mempool_t *mp) { int k; for (k = 0; k < mp->n; ++k) { free(mp->buf[k]->b.data); free(mp->buf[k]); } free(mp->buf); free(mp); } static inline lbnode_t *mp_alloc(mempool_t *mp) { ++mp->cnt; if (mp->n == 0) return (lbnode_t*)calloc(1, sizeof(lbnode_t)); else return mp->buf[--mp->n]; } static inline void mp_free(mempool_t *mp, lbnode_t *p) { --mp->cnt; p->next = 0; // clear lbnode_t::next here if (mp->n == mp->max) { mp->max = mp->max? mp->max<<1 : 256; mp->buf = (lbnode_t**)realloc(mp->buf, sizeof(lbnode_t*) * mp->max); } mp->buf[mp->n++] = p; } /* --- END: Memory pool */ /* --- BEGIN: Auxiliary functions */ /* s->k: the index of the CIGAR operator that has just been processed. s->x: the reference coordinate of the start of s->k s->y: the query coordiante of the start of s->k */ static inline int resolve_cigar2(bam_pileup1_t *p, uint32_t pos, cstate_t *s) { #define _cop(c) ((c)&BAM_CIGAR_MASK) #define _cln(c) ((c)>>BAM_CIGAR_SHIFT) bam1_t *b = p->b; bam1_core_t *c = &b->core; uint32_t *cigar = bam1_cigar(b); int k, is_head = 0; // determine the current CIGAR operation // fprintf(stderr, "%s\tpos=%d\tend=%d\t(%d,%d,%d)\n", bam1_qname(b), pos, s->end, s->k, s->x, s->y); if (s->k == -1) { // never processed is_head = 1; if (c->n_cigar == 1) { // just one operation, save a loop if (_cop(cigar[0]) == BAM_CMATCH || _cop(cigar[0]) == BAM_CEQUAL || _cop(cigar[0]) == BAM_CDIFF) s->k = 0, s->x = c->pos, s->y = 0; } else { // find the first match or deletion for (k = 0, s->x = c->pos, s->y = 0; k < c->n_cigar; ++k) { int op = _cop(cigar[k]); int l = _cln(cigar[k]); if (op == BAM_CMATCH || op == BAM_CDEL || op == BAM_CEQUAL || op == BAM_CDIFF) break; else if (op == BAM_CREF_SKIP) s->x += l; else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) s->y += l; } assert(k < c->n_cigar); s->k = k; } } else { // the read has been processed before int op, l = _cln(cigar[s->k]); if (pos - s->x >= l) { // jump to the next operation assert(s->k < c->n_cigar); // otherwise a bug: this function should not be called in this case op = _cop(cigar[s->k+1]); if (op == BAM_CMATCH || op == BAM_CDEL || op == BAM_CREF_SKIP || op == BAM_CEQUAL || op == BAM_CDIFF) { // jump to the next without a loop if (_cop(cigar[s->k]) == BAM_CMATCH|| _cop(cigar[s->k]) == BAM_CEQUAL || _cop(cigar[s->k]) == BAM_CDIFF) s->y += l; s->x += l; ++s->k; } else { // find the next M/D/N/=/X if (_cop(cigar[s->k]) == BAM_CMATCH|| _cop(cigar[s->k]) == BAM_CEQUAL || _cop(cigar[s->k]) == BAM_CDIFF) s->y += l; s->x += l; for (k = s->k + 1; k < c->n_cigar; ++k) { op = _cop(cigar[k]), l = _cln(cigar[k]); if (op == BAM_CMATCH || op == BAM_CDEL || op == BAM_CREF_SKIP || op == BAM_CEQUAL || op == BAM_CDIFF) break; else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) s->y += l; } s->k = k; } assert(s->k < c->n_cigar); // otherwise a bug } // else, do nothing } { // collect pileup information int op, l; op = _cop(cigar[s->k]); l = _cln(cigar[s->k]); p->is_del = p->indel = p->is_refskip = 0; if (s->x + l - 1 == pos && s->k + 1 < c->n_cigar) { // peek the next operation int op2 = _cop(cigar[s->k+1]); int l2 = _cln(cigar[s->k+1]); if (op2 == BAM_CDEL) p->indel = -(int)l2; else if (op2 == BAM_CINS) p->indel = l2; else if (op2 == BAM_CPAD && s->k + 2 < c->n_cigar) { // no working for adjacent padding int l3 = 0; for (k = s->k + 2; k < c->n_cigar; ++k) { op2 = _cop(cigar[k]); l2 = _cln(cigar[k]); if (op2 == BAM_CINS) l3 += l2; else if (op2 == BAM_CDEL || op2 == BAM_CMATCH || op2 == BAM_CREF_SKIP || op2 == BAM_CEQUAL || op2 == BAM_CDIFF) break; } if (l3 > 0) p->indel = l3; } } if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) { p->qpos = s->y + (pos - s->x); } else if (op == BAM_CDEL || op == BAM_CREF_SKIP) { p->is_del = 1; p->qpos = s->y; // FIXME: distinguish D and N!!!!! p->is_refskip = (op == BAM_CREF_SKIP); } // cannot be other operations; otherwise a bug p->is_head = (pos == c->pos); p->is_tail = (pos == s->end); } return 1; } /* --- END: Auxiliary functions */ /******************* * pileup iterator * *******************/ struct __bam_plp_t { mempool_t *mp; lbnode_t *head, *tail, *dummy; int32_t tid, pos, max_tid, max_pos; int is_eof, flag_mask, max_plp, error, maxcnt; bam_pileup1_t *plp; // for the "auto" interface only bam1_t *b; bam_plp_auto_f func; void *data; }; bam_plp_t bam_plp_init(bam_plp_auto_f func, void *data) { bam_plp_t iter; iter = calloc(1, sizeof(struct __bam_plp_t)); iter->mp = mp_init(); iter->head = iter->tail = mp_alloc(iter->mp); iter->dummy = mp_alloc(iter->mp); iter->max_tid = iter->max_pos = -1; iter->flag_mask = BAM_DEF_MASK; iter->maxcnt = 8000; if (func) { iter->func = func; iter->data = data; iter->b = bam_init1(); } return iter; } void bam_plp_destroy(bam_plp_t iter) { mp_free(iter->mp, iter->dummy); mp_free(iter->mp, iter->head); if (iter->mp->cnt != 0) fprintf(stderr, "[bam_plp_destroy] memory leak: %d. Continue anyway.\n", iter->mp->cnt); mp_destroy(iter->mp); if (iter->b) bam_destroy1(iter->b); free(iter->plp); free(iter); } const bam_pileup1_t *bam_plp_next(bam_plp_t iter, int *_tid, int *_pos, int *_n_plp) { if (iter->error) { *_n_plp = -1; return 0; } *_n_plp = 0; if (iter->is_eof && iter->head->next == 0) return 0; while (iter->is_eof || iter->max_tid > iter->tid || (iter->max_tid == iter->tid && iter->max_pos > iter->pos)) { int n_plp = 0; lbnode_t *p, *q; // write iter->plp at iter->pos iter->dummy->next = iter->head; for (p = iter->head, q = iter->dummy; p->next; q = p, p = p->next) { if (p->b.core.tid < iter->tid || (p->b.core.tid == iter->tid && p->end <= iter->pos)) { // then remove q->next = p->next; mp_free(iter->mp, p); p = q; } else if (p->b.core.tid == iter->tid && p->beg <= iter->pos) { // here: p->end > pos; then add to pileup if (n_plp == iter->max_plp) { // then double the capacity iter->max_plp = iter->max_plp? iter->max_plp<<1 : 256; iter->plp = (bam_pileup1_t*)realloc(iter->plp, sizeof(bam_pileup1_t) * iter->max_plp); } iter->plp[n_plp].b = &p->b; if (resolve_cigar2(iter->plp + n_plp, iter->pos, &p->s)) ++n_plp; // actually always true... } } iter->head = iter->dummy->next; // dummy->next may be changed *_n_plp = n_plp; *_tid = iter->tid; *_pos = iter->pos; // update iter->tid and iter->pos if (iter->head->next) { if (iter->tid > iter->head->b.core.tid) { fprintf(stderr, "[%s] unsorted input. Pileup aborts.\n", __func__); iter->error = 1; *_n_plp = -1; return 0; } } if (iter->tid < iter->head->b.core.tid) { // come to a new reference sequence iter->tid = iter->head->b.core.tid; iter->pos = iter->head->beg; // jump to the next reference } else if (iter->pos < iter->head->beg) { // here: tid == head->b.core.tid iter->pos = iter->head->beg; // jump to the next position } else ++iter->pos; // scan contiguously // return if (n_plp) return iter->plp; if (iter->is_eof && iter->head->next == 0) break; } return 0; } int bam_plp_push(bam_plp_t iter, const bam1_t *b) { if (iter->error) return -1; if (b) { if (b->core.tid < 0) return 0; if (b->core.flag & iter->flag_mask) return 0; if (iter->tid == b->core.tid && iter->pos == b->core.pos && iter->mp->cnt > iter->maxcnt) return 0; bam_copy1(&iter->tail->b, b); iter->tail->beg = b->core.pos; iter->tail->end = bam_calend(&b->core, bam1_cigar(b)); iter->tail->s = g_cstate_null; iter->tail->s.end = iter->tail->end - 1; // initialize cstate_t if (b->core.tid < iter->max_tid) { fprintf(stderr, "[bam_pileup_core] the input is not sorted (chromosomes out of order)\n"); iter->error = 1; return -1; } if ((b->core.tid == iter->max_tid) && (iter->tail->beg < iter->max_pos)) { fprintf(stderr, "[bam_pileup_core] the input is not sorted (reads out of order)\n"); iter->error = 1; return -1; } iter->max_tid = b->core.tid; iter->max_pos = iter->tail->beg; if (iter->tail->end > iter->pos || iter->tail->b.core.tid > iter->tid) { iter->tail->next = mp_alloc(iter->mp); iter->tail = iter->tail->next; } } else iter->is_eof = 1; return 0; } const bam_pileup1_t *bam_plp_auto(bam_plp_t iter, int *_tid, int *_pos, int *_n_plp) { const bam_pileup1_t *plp; if (iter->func == 0 || iter->error) { *_n_plp = -1; return 0; } if ((plp = bam_plp_next(iter, _tid, _pos, _n_plp)) != 0) return plp; else { // no pileup line can be obtained; read alignments *_n_plp = 0; if (iter->is_eof) return 0; while (iter->func(iter->data, iter->b) >= 0) { if (bam_plp_push(iter, iter->b) < 0) { *_n_plp = -1; return 0; } if ((plp = bam_plp_next(iter, _tid, _pos, _n_plp)) != 0) return plp; // otherwise no pileup line can be returned; read the next alignment. } bam_plp_push(iter, 0); if ((plp = bam_plp_next(iter, _tid, _pos, _n_plp)) != 0) return plp; return 0; } } void bam_plp_reset(bam_plp_t iter) { lbnode_t *p, *q; iter->max_tid = iter->max_pos = -1; iter->tid = iter->pos = 0; iter->is_eof = 0; for (p = iter->head; p->next;) { q = p->next; mp_free(iter->mp, p); p = q; } iter->head = iter->tail; } void bam_plp_set_mask(bam_plp_t iter, int mask) { iter->flag_mask = mask < 0? BAM_DEF_MASK : (BAM_FUNMAP | mask); } void bam_plp_set_maxcnt(bam_plp_t iter, int maxcnt) { iter->maxcnt = maxcnt; } /***************** * callback APIs * *****************/ int bam_pileup_file(bamFile fp, int mask, bam_pileup_f func, void *func_data) { bam_plbuf_t *buf; int ret; bam1_t *b; b = bam_init1(); buf = bam_plbuf_init(func, func_data); bam_plbuf_set_mask(buf, mask); while ((ret = bam_read1(fp, b)) >= 0) bam_plbuf_push(b, buf); bam_plbuf_push(0, buf); bam_plbuf_destroy(buf); bam_destroy1(b); return 0; } void bam_plbuf_set_mask(bam_plbuf_t *buf, int mask) { bam_plp_set_mask(buf->iter, mask); } void bam_plbuf_reset(bam_plbuf_t *buf) { bam_plp_reset(buf->iter); } bam_plbuf_t *bam_plbuf_init(bam_pileup_f func, void *data) { bam_plbuf_t *buf; buf = calloc(1, sizeof(bam_plbuf_t)); buf->iter = bam_plp_init(0, 0); buf->func = func; buf->data = data; return buf; } void bam_plbuf_destroy(bam_plbuf_t *buf) { bam_plp_destroy(buf->iter); free(buf); } int bam_plbuf_push(const bam1_t *b, bam_plbuf_t *buf) { int ret, n_plp, tid, pos; const bam_pileup1_t *plp; ret = bam_plp_push(buf->iter, b); if (ret < 0) return ret; while ((plp = bam_plp_next(buf->iter, &tid, &pos, &n_plp)) != 0) buf->func(tid, pos, n_plp, plp, buf->data); return 0; } /*********** * mpileup * ***********/ struct __bam_mplp_t { int n; uint64_t min, *pos; bam_plp_t *iter; int *n_plp; const bam_pileup1_t **plp; }; bam_mplp_t bam_mplp_init(int n, bam_plp_auto_f func, void **data) { int i; bam_mplp_t iter; iter = calloc(1, sizeof(struct __bam_mplp_t)); iter->pos = calloc(n, 8); iter->n_plp = calloc(n, sizeof(int)); iter->plp = calloc(n, sizeof(void*)); iter->iter = calloc(n, sizeof(void*)); iter->n = n; iter->min = (uint64_t)-1; for (i = 0; i < n; ++i) { iter->iter[i] = bam_plp_init(func, data[i]); iter->pos[i] = iter->min; } return iter; } void bam_mplp_set_maxcnt(bam_mplp_t iter, int maxcnt) { int i; for (i = 0; i < iter->n; ++i) iter->iter[i]->maxcnt = maxcnt; } void bam_mplp_destroy(bam_mplp_t iter) { int i; for (i = 0; i < iter->n; ++i) bam_plp_destroy(iter->iter[i]); free(iter->iter); free(iter->pos); free(iter->n_plp); free(iter->plp); free(iter); } int bam_mplp_auto(bam_mplp_t iter, int *_tid, int *_pos, int *n_plp, const bam_pileup1_t **plp) { int i, ret = 0; uint64_t new_min = (uint64_t)-1; for (i = 0; i < iter->n; ++i) { if (iter->pos[i] == iter->min) { int tid, pos; iter->plp[i] = bam_plp_auto(iter->iter[i], &tid, &pos, &iter->n_plp[i]); iter->pos[i] = (uint64_t)tid<<32 | pos; } if (iter->plp[i] && iter->pos[i] < new_min) new_min = iter->pos[i]; } iter->min = new_min; if (new_min == (uint64_t)-1) return 0; *_tid = new_min>>32; *_pos = (uint32_t)new_min; for (i = 0; i < iter->n; ++i) { if (iter->pos[i] == iter->min) { // FIXME: valgrind reports "uninitialised value(s) at this line" n_plp[i] = iter->n_plp[i], plp[i] = iter->plp[i]; ++ret; } else n_plp[i] = 0, plp[i] = 0; } return ret; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam2bcf.c
.c
14,804
468
#include <math.h> #include <stdint.h> #include <assert.h> #include "bam.h" #include "kstring.h" #include "bam2bcf.h" #include "errmod.h" #include "bcftools/bcf.h" extern void ks_introsort_uint32_t(size_t n, uint32_t a[]); #define CALL_ETA 0.03f #define CALL_MAX 256 #define CALL_DEFTHETA 0.83f #define DEF_MAPQ 20 #define CAP_DIST 25 bcf_callaux_t *bcf_call_init(double theta, int min_baseQ) { bcf_callaux_t *bca; if (theta <= 0.) theta = CALL_DEFTHETA; bca = calloc(1, sizeof(bcf_callaux_t)); bca->capQ = 60; bca->openQ = 40; bca->extQ = 20; bca->tandemQ = 100; bca->min_baseQ = min_baseQ; bca->e = errmod_init(1. - theta); bca->min_frac = 0.002; bca->min_support = 1; bca->per_sample_flt = 0; bca->npos = 100; bca->ref_pos = calloc(bca->npos, sizeof(int)); bca->alt_pos = calloc(bca->npos, sizeof(int)); return bca; } static int get_position(const bam_pileup1_t *p, int *len) { int icig, n_tot_bases = 0, iread = 0, edist = p->qpos + 1; for (icig=0; icig<p->b->core.n_cigar; icig++) { // Conversion from uint32_t to MIDNSHP // 0123456 // MIDNSHP int cig = bam1_cigar(p->b)[icig] & BAM_CIGAR_MASK; int ncig = bam1_cigar(p->b)[icig] >> BAM_CIGAR_SHIFT; if ( cig==0 ) { n_tot_bases += ncig; iread += ncig; } else if ( cig==1 ) { n_tot_bases += ncig; iread += ncig; } else if ( cig==4 ) { iread += ncig; if ( iread<=p->qpos ) edist -= ncig; } } *len = n_tot_bases; return edist; } void bcf_call_destroy(bcf_callaux_t *bca) { if (bca == 0) return; errmod_destroy(bca->e); if (bca->npos) { free(bca->ref_pos); free(bca->alt_pos); bca->npos = 0; } free(bca->bases); free(bca->inscns); free(bca); } /* ref_base is the 4-bit representation of the reference base. It is * negative if we are looking at an indel. */ int bcf_call_glfgen(int _n, const bam_pileup1_t *pl, int ref_base, bcf_callaux_t *bca, bcf_callret1_t *r) { int i, n, ref4, is_indel, ori_depth = 0; memset(r, 0, sizeof(bcf_callret1_t)); if (ref_base >= 0) { ref4 = bam_nt16_nt4_table[ref_base]; is_indel = 0; } else ref4 = 4, is_indel = 1; if (_n == 0) return -1; // enlarge the bases array if necessary if (bca->max_bases < _n) { bca->max_bases = _n; kroundup32(bca->max_bases); bca->bases = (uint16_t*)realloc(bca->bases, 2 * bca->max_bases); } // fill the bases array for (i = n = r->n_supp = 0; i < _n; ++i) { const bam_pileup1_t *p = pl + i; int q, b, mapQ, baseQ, is_diff, min_dist, seqQ; // set base if (p->is_del || p->is_refskip || (p->b->core.flag&BAM_FUNMAP)) continue; ++ori_depth; baseQ = q = is_indel? p->aux&0xff : (int)bam1_qual(p->b)[p->qpos]; // base/indel quality seqQ = is_indel? (p->aux>>8&0xff) : 99; if (q < bca->min_baseQ) continue; if (q > seqQ) q = seqQ; mapQ = p->b->core.qual < 255? p->b->core.qual : DEF_MAPQ; // special case for mapQ==255 mapQ = mapQ < bca->capQ? mapQ : bca->capQ; if (q > mapQ) q = mapQ; if (q > 63) q = 63; if (q < 4) q = 4; if (!is_indel) { b = bam1_seqi(bam1_seq(p->b), p->qpos); // base b = bam_nt16_nt4_table[b? b : ref_base]; // b is the 2-bit base is_diff = (ref4 < 4 && b == ref4)? 0 : 1; } else { b = p->aux>>16&0x3f; is_diff = (b != 0); } if (is_diff) ++r->n_supp; bca->bases[n++] = q<<5 | (int)bam1_strand(p->b)<<4 | b; // collect annotations if (b < 4) r->qsum[b] += q; ++r->anno[0<<2|is_diff<<1|bam1_strand(p->b)]; min_dist = p->b->core.l_qseq - 1 - p->qpos; if (min_dist > p->qpos) min_dist = p->qpos; if (min_dist > CAP_DIST) min_dist = CAP_DIST; r->anno[1<<2|is_diff<<1|0] += baseQ; r->anno[1<<2|is_diff<<1|1] += baseQ * baseQ; r->anno[2<<2|is_diff<<1|0] += mapQ; r->anno[2<<2|is_diff<<1|1] += mapQ * mapQ; r->anno[3<<2|is_diff<<1|0] += min_dist; r->anno[3<<2|is_diff<<1|1] += min_dist * min_dist; // collect read positions for ReadPosBias int len, pos = get_position(p, &len); int epos = (double)pos/(len+1) * bca->npos; if ( bam1_seqi(bam1_seq(p->b),p->qpos) == ref_base ) bca->ref_pos[epos]++; else bca->alt_pos[epos]++; } r->depth = n; r->ori_depth = ori_depth; // glfgen errmod_cal(bca->e, n, 5, bca->bases, r->p); return r->depth; } double mann_whitney_1947(int n, int m, int U) { if (U<0) return 0; if (n==0||m==0) return U==0 ? 1 : 0; return (double)n/(n+m)*mann_whitney_1947(n-1,m,U-m) + (double)m/(n+m)*mann_whitney_1947(n,m-1,U); } void calc_ReadPosBias(bcf_callaux_t *bca, bcf_call_t *call) { int i, nref = 0, nalt = 0; unsigned long int U = 0; for (i=0; i<bca->npos; i++) { nref += bca->ref_pos[i]; nalt += bca->alt_pos[i]; U += nref*bca->alt_pos[i]; bca->ref_pos[i] = 0; bca->alt_pos[i] = 0; } #if 0 //todo double var = 0, avg = (double)(nref+nalt)/bca->npos; for (i=0; i<bca->npos; i++) { double ediff = bca->ref_pos[i] + bca->alt_pos[i] - avg; var += ediff*ediff; bca->ref_pos[i] = 0; bca->alt_pos[i] = 0; } call->read_pos.avg = avg; call->read_pos.var = sqrt(var/bca->npos); call->read_pos.dp = nref+nalt; #endif if ( !nref || !nalt ) { call->read_pos_bias = -1; return; } if ( nref>=8 || nalt>=8 ) { // normal approximation double mean = ((double)nref*nalt+1.0)/2.0; double var2 = (double)nref*nalt*(nref+nalt+1.0)/12.0; double z = (U-mean)/sqrt(var2); call->read_pos_bias = z; //fprintf(stderr,"nref=%d nalt=%d U=%ld mean=%e var=%e zval=%e\n", nref,nalt,U,mean,sqrt(var2),call->read_pos_bias); } else { double p = mann_whitney_1947(nalt,nref,U); // biased form claimed by GATK to behave better empirically // double var2 = (1.0+1.0/(nref+nalt+1.0))*(double)nref*nalt*(nref+nalt+1.0)/12.0; double var2 = (double)nref*nalt*(nref+nalt+1.0)/12.0; double z; if ( p >= 1./sqrt(var2*2*M_PI) ) z = 0; // equal to mean else { if ( U >= nref*nalt/2. ) z = sqrt(-2*log(sqrt(var2*2*M_PI)*p)); else z = -sqrt(-2*log(sqrt(var2*2*M_PI)*p)); } call->read_pos_bias = z; //fprintf(stderr,"nref=%d nalt=%d U=%ld p=%e var2=%e zval=%e\n", nref,nalt,U, p,var2,call->read_pos_bias); } } float mean_diff_to_prob(float mdiff, int dp, int readlen) { if ( dp==2 ) { if ( mdiff==0 ) return (2.0*readlen + 4.0*(readlen-1.0))/((float)readlen*readlen); else return 8.0*(readlen - 4.0*mdiff)/((float)readlen*readlen); } // This is crude empirical approximation and is not very accurate for // shorter read lengths (<100bp). There certainly is a room for // improvement. const float mv[24][2] = { {0,0}, {0,0}, {0,0}, { 9.108, 4.934}, { 9.999, 3.991}, {10.273, 3.485}, {10.579, 3.160}, {10.828, 2.889}, {11.014, 2.703}, {11.028, 2.546}, {11.244, 2.391}, {11.231, 2.320}, {11.323, 2.138}, {11.403, 2.123}, {11.394, 1.994}, {11.451, 1.928}, {11.445, 1.862}, {11.516, 1.815}, {11.560, 1.761}, {11.544, 1.728}, {11.605, 1.674}, {11.592, 1.652}, {11.674, 1.613}, {11.641, 1.570} }; float m, v; if ( dp>=24 ) { m = readlen/8.; if (dp>100) dp = 100; v = 1.476/(0.182*pow(dp,0.514)); v = v*(readlen/100.); } else { m = mv[dp][0]; v = mv[dp][1]; m = m*readlen/100.; v = v*readlen/100.; v *= 1.2; // allow more variability } return 1.0/(v*sqrt(2*M_PI)) * exp(-0.5*((mdiff-m)/v)*((mdiff-m)/v)); } void calc_vdb(bcf_callaux_t *bca, bcf_call_t *call) { int i, dp = 0; float mean_pos = 0, mean_diff = 0; for (i=0; i<bca->npos; i++) { if ( !bca->alt_pos[i] ) continue; dp += bca->alt_pos[i]; int j = i<bca->npos/2 ? i : bca->npos - i; mean_pos += bca->alt_pos[i]*j; } if ( dp<2 ) { call->vdb = -1; return; } mean_pos /= dp; for (i=0; i<bca->npos; i++) { if ( !bca->alt_pos[i] ) continue; int j = i<bca->npos/2 ? i : bca->npos - i; mean_diff += bca->alt_pos[i] * fabs(j - mean_pos); } mean_diff /= dp; call->vdb = mean_diff_to_prob(mean_diff, dp, bca->npos); } /** * bcf_call_combine() - sets the PL array and VDB, RPB annotations, finds the top two alleles * @n: number of samples * @calls: each sample's calls * @bca: auxiliary data structure for holding temporary values * @ref_base: the reference base * @call: filled with the annotations */ int bcf_call_combine(int n, const bcf_callret1_t *calls, bcf_callaux_t *bca, int ref_base /*4-bit*/, bcf_call_t *call) { int ref4, i, j, qsum[4]; int64_t tmp; if (ref_base >= 0) { call->ori_ref = ref4 = bam_nt16_nt4_table[ref_base]; if (ref4 > 4) ref4 = 4; } else call->ori_ref = -1, ref4 = 0; // calculate qsum memset(qsum, 0, 4 * sizeof(int)); for (i = 0; i < n; ++i) for (j = 0; j < 4; ++j) qsum[j] += calls[i].qsum[j]; int qsum_tot=0; for (j=0; j<4; j++) { qsum_tot += qsum[j]; call->qsum[j] = 0; } for (j = 0; j < 4; ++j) qsum[j] = qsum[j] << 2 | j; // find the top 2 alleles for (i = 1; i < 4; ++i) // insertion sort for (j = i; j > 0 && qsum[j] < qsum[j-1]; --j) tmp = qsum[j], qsum[j] = qsum[j-1], qsum[j-1] = tmp; // set the reference allele and alternative allele(s) for (i = 0; i < 5; ++i) call->a[i] = -1; call->unseen = -1; call->a[0] = ref4; for (i = 3, j = 1; i >= 0; --i) { if ((qsum[i]&3) != ref4) { if (qsum[i]>>2 != 0) { if ( j<4 ) call->qsum[j] = (float)(qsum[i]>>2)/qsum_tot; // ref N can make j>=4 call->a[j++] = qsum[i]&3; } else break; } else call->qsum[0] = (float)(qsum[i]>>2)/qsum_tot; } if (ref_base >= 0) { // for SNPs, find the "unseen" base if (((ref4 < 4 && j < 4) || (ref4 == 4 && j < 5)) && i >= 0) call->unseen = j, call->a[j++] = qsum[i]&3; call->n_alleles = j; } else { call->n_alleles = j; if (call->n_alleles == 1) return -1; // no reliable supporting read. stop doing anything } // set the PL array if (call->n < n) { call->n = n; call->PL = realloc(call->PL, 15 * n); } { int x, g[15], z; double sum_min = 0.; x = call->n_alleles * (call->n_alleles + 1) / 2; // get the possible genotypes for (i = z = 0; i < call->n_alleles; ++i) for (j = 0; j <= i; ++j) g[z++] = call->a[j] * 5 + call->a[i]; for (i = 0; i < n; ++i) { uint8_t *PL = call->PL + x * i; const bcf_callret1_t *r = calls + i; float min = 1e37; for (j = 0; j < x; ++j) if (min > r->p[g[j]]) min = r->p[g[j]]; sum_min += min; for (j = 0; j < x; ++j) { int y; y = (int)(r->p[g[j]] - min + .499); if (y > 255) y = 255; PL[j] = y; } } // if (ref_base < 0) fprintf(stderr, "%d,%d,%f,%d\n", call->n_alleles, x, sum_min, call->unseen); call->shift = (int)(sum_min + .499); } // combine annotations memset(call->anno, 0, 16 * sizeof(int)); for (i = call->depth = call->ori_depth = 0, tmp = 0; i < n; ++i) { call->depth += calls[i].depth; call->ori_depth += calls[i].ori_depth; for (j = 0; j < 16; ++j) call->anno[j] += calls[i].anno[j]; } calc_vdb(bca, call); calc_ReadPosBias(bca, call); return 0; } int bcf_call2bcf(int tid, int pos, bcf_call_t *bc, bcf1_t *b, bcf_callret1_t *bcr, int fmt_flag, const bcf_callaux_t *bca, const char *ref) { extern double kt_fisher_exact(int n11, int n12, int n21, int n22, double *_left, double *_right, double *two); kstring_t s; int i, j; b->n_smpl = bc->n; b->tid = tid; b->pos = pos; b->qual = 0; s.s = b->str; s.m = b->m_str; s.l = 0; kputc('\0', &s); if (bc->ori_ref < 0) { // an indel // write REF kputc(ref[pos], &s); for (j = 0; j < bca->indelreg; ++j) kputc(ref[pos+1+j], &s); kputc('\0', &s); // write ALT kputc(ref[pos], &s); for (i = 1; i < 4; ++i) { if (bc->a[i] < 0) break; if (i > 1) { kputc(',', &s); kputc(ref[pos], &s); } if (bca->indel_types[bc->a[i]] < 0) { // deletion for (j = -bca->indel_types[bc->a[i]]; j < bca->indelreg; ++j) kputc(ref[pos+1+j], &s); } else { // insertion; cannot be a reference unless a bug char *inscns = &bca->inscns[bc->a[i] * bca->maxins]; for (j = 0; j < bca->indel_types[bc->a[i]]; ++j) kputc("ACGTN"[(int)inscns[j]], &s); for (j = 0; j < bca->indelreg; ++j) kputc(ref[pos+1+j], &s); } } kputc('\0', &s); } else { // a SNP kputc("ACGTN"[bc->ori_ref], &s); kputc('\0', &s); for (i = 1; i < 5; ++i) { if (bc->a[i] < 0) break; if (i > 1) kputc(',', &s); kputc(bc->unseen == i? 'X' : "ACGT"[bc->a[i]], &s); } kputc('\0', &s); } kputc('\0', &s); // INFO if (bc->ori_ref < 0) ksprintf(&s,"INDEL;IS=%d,%f;", bca->max_support, bca->max_frac); kputs("DP=", &s); kputw(bc->ori_depth, &s); kputs(";I16=", &s); for (i = 0; i < 16; ++i) { if (i) kputc(',', &s); kputw(bc->anno[i], &s); } //ksprintf(&s,";RPS=%d,%f,%f", bc->read_pos.dp,bc->read_pos.avg,bc->read_pos.var); ksprintf(&s,";QS=%f,%f,%f,%f", bc->qsum[0],bc->qsum[1],bc->qsum[2],bc->qsum[3]); if (bc->vdb != -1) ksprintf(&s, ";VDB=%e", bc->vdb); if (bc->read_pos_bias != -1 ) ksprintf(&s, ";RPB=%e", bc->read_pos_bias); kputc('\0', &s); // FMT kputs("PL", &s); if (bcr && fmt_flag) { if (fmt_flag & B2B_FMT_DP) kputs(":DP", &s); if (fmt_flag & B2B_FMT_DV) kputs(":DV", &s); if (fmt_flag & B2B_FMT_SP) kputs(":SP", &s); } kputc('\0', &s); b->m_str = s.m; b->str = s.s; b->l_str = s.l; bcf_sync(b); memcpy(b->gi[0].data, bc->PL, b->gi[0].len * bc->n); if (bcr && fmt_flag) { uint16_t *dp = (fmt_flag & B2B_FMT_DP)? b->gi[1].data : 0; uint16_t *dv = (fmt_flag & B2B_FMT_DV)? b->gi[1 + ((fmt_flag & B2B_FMT_DP) != 0)].data : 0; int32_t *sp = (fmt_flag & B2B_FMT_SP)? b->gi[1 + ((fmt_flag & B2B_FMT_DP) != 0) + ((fmt_flag & B2B_FMT_DV) != 0)].data : 0; for (i = 0; i < bc->n; ++i) { bcf_callret1_t *p = bcr + i; if (dp) dp[i] = p->depth < 0xffff? p->depth : 0xffff; if (dv) dv[i] = p->n_supp < 0xffff? p->n_supp : 0xffff; if (sp) { if (p->anno[0] + p->anno[1] < 2 || p->anno[2] + p->anno[3] < 2 || p->anno[0] + p->anno[2] < 2 || p->anno[1] + p->anno[3] < 2) { sp[i] = 0; } else { double left, right, two; int x; kt_fisher_exact(p->anno[0], p->anno[1], p->anno[2], p->anno[3], &left, &right, &two); x = (int)(-4.343 * log(two) + .499); if (x > 255) x = 255; sp[i] = x; } } } } return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam2bcf_indel.c
.c
18,351
499
#include <assert.h> #include <ctype.h> #include <string.h> #include "bam.h" #include "bam2bcf.h" #include "kaln.h" #include "kprobaln.h" #include "khash.h" KHASH_SET_INIT_STR(rg) #include "ksort.h" KSORT_INIT_GENERIC(uint32_t) #define MINUS_CONST 0x10000000 #define INDEL_WINDOW_SIZE 50 void *bcf_call_add_rg(void *_hash, const char *hdtext, const char *list) { const char *s, *p, *q, *r, *t; khash_t(rg) *hash; if (list == 0 || hdtext == 0) return _hash; if (_hash == 0) _hash = kh_init(rg); hash = (khash_t(rg)*)_hash; if ((s = strstr(hdtext, "@RG\t")) == 0) return hash; do { t = strstr(s + 4, "@RG\t"); // the next @RG if ((p = strstr(s, "\tID:")) != 0) p += 4; if ((q = strstr(s, "\tPL:")) != 0) q += 4; if (p && q && (t == 0 || (p < t && q < t))) { // ID and PL are both present int lp, lq; char *x; for (r = p; *r && *r != '\t' && *r != '\n'; ++r); lp = r - p; for (r = q; *r && *r != '\t' && *r != '\n'; ++r); lq = r - q; x = calloc((lp > lq? lp : lq) + 1, 1); for (r = q; *r && *r != '\t' && *r != '\n'; ++r) x[r-q] = *r; if (strstr(list, x)) { // insert ID to the hash table khint_t k; int ret; for (r = p; *r && *r != '\t' && *r != '\n'; ++r) x[r-p] = *r; x[r-p] = 0; k = kh_get(rg, hash, x); if (k == kh_end(hash)) k = kh_put(rg, hash, x, &ret); else free(x); } else free(x); } s = t; } while (s); return hash; } void bcf_call_del_rghash(void *_hash) { khint_t k; khash_t(rg) *hash = (khash_t(rg)*)_hash; if (hash == 0) return; for (k = kh_begin(hash); k < kh_end(hash); ++k) if (kh_exist(hash, k)) free((char*)kh_key(hash, k)); kh_destroy(rg, hash); } static int tpos2qpos(const bam1_core_t *c, const uint32_t *cigar, int32_t tpos, int is_left, int32_t *_tpos) { int k, x = c->pos, y = 0, last_y = 0; *_tpos = c->pos; for (k = 0; k < c->n_cigar; ++k) { int op = cigar[k] & BAM_CIGAR_MASK; int l = cigar[k] >> BAM_CIGAR_SHIFT; if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) { if (c->pos > tpos) return y; if (x + l > tpos) { *_tpos = tpos; return y + (tpos - x); } x += l; y += l; last_y = y; } else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) y += l; else if (op == BAM_CDEL || op == BAM_CREF_SKIP) { if (x + l > tpos) { *_tpos = is_left? x : x + l; return y; } x += l; } } *_tpos = x; return last_y; } // FIXME: check if the inserted sequence is consistent with the homopolymer run // l is the relative gap length and l_run is the length of the homopolymer on the reference static inline int est_seqQ(const bcf_callaux_t *bca, int l, int l_run) { int q, qh; q = bca->openQ + bca->extQ * (abs(l) - 1); qh = l_run >= 3? (int)(bca->tandemQ * (double)abs(l) / l_run + .499) : 1000; return q < qh? q : qh; } static inline int est_indelreg(int pos, const char *ref, int l, char *ins4) { int i, j, max = 0, max_i = pos, score = 0; l = abs(l); for (i = pos + 1, j = 0; ref[i]; ++i, ++j) { if (ins4) score += (toupper(ref[i]) != "ACGTN"[(int)ins4[j%l]])? -10 : 1; else score += (toupper(ref[i]) != toupper(ref[pos+1+j%l]))? -10 : 1; if (score < 0) break; if (max < score) max = score, max_i = i; } return max_i - pos; } /* * @n: number of samples */ int bcf_call_gap_prep(int n, int *n_plp, bam_pileup1_t **plp, int pos, bcf_callaux_t *bca, const char *ref, const void *rghash) { int i, s, j, k, t, n_types, *types, max_rd_len, left, right, max_ins, *score1, *score2, max_ref2; int N, K, l_run, ref_type, n_alt; char *inscns = 0, *ref2, *query, **ref_sample; khash_t(rg) *hash = (khash_t(rg)*)rghash; if (ref == 0 || bca == 0) return -1; // mark filtered reads if (rghash) { N = 0; for (s = N = 0; s < n; ++s) { for (i = 0; i < n_plp[s]; ++i) { bam_pileup1_t *p = plp[s] + i; const uint8_t *rg = bam_aux_get(p->b, "RG"); p->aux = 1; // filtered by default if (rg) { khint_t k = kh_get(rg, hash, (const char*)(rg + 1)); if (k != kh_end(hash)) p->aux = 0, ++N; // not filtered } } } if (N == 0) return -1; // no reads left } // determine if there is a gap for (s = N = 0; s < n; ++s) { for (i = 0; i < n_plp[s]; ++i) if (plp[s][i].indel != 0) break; if (i < n_plp[s]) break; } if (s == n) return -1; // there is no indel at this position. for (s = N = 0; s < n; ++s) N += n_plp[s]; // N is the total number of reads { // find out how many types of indels are present bca->max_support = bca->max_frac = 0; int m, n_alt = 0, n_tot = 0, indel_support_ok = 0; uint32_t *aux; aux = calloc(N + 1, 4); m = max_rd_len = 0; aux[m++] = MINUS_CONST; // zero indel is always a type for (s = 0; s < n; ++s) { int na = 0, nt = 0; for (i = 0; i < n_plp[s]; ++i) { const bam_pileup1_t *p = plp[s] + i; if (rghash == 0 || p->aux == 0) { ++nt; if (p->indel != 0) { ++na; aux[m++] = MINUS_CONST + p->indel; } } j = bam_cigar2qlen(&p->b->core, bam1_cigar(p->b)); if (j > max_rd_len) max_rd_len = j; } float frac = (float)na/nt; if ( !indel_support_ok && na >= bca->min_support && frac >= bca->min_frac ) indel_support_ok = 1; if ( na > bca->max_support && frac > 0 ) bca->max_support = na, bca->max_frac = frac; n_alt += na; n_tot += nt; } // To prevent long stretches of N's to be mistaken for indels (sometimes thousands of bases), // check the number of N's in the sequence and skip places where half or more reference bases are Ns. int nN=0; for (i=pos; i-pos<max_rd_len && ref[i]; i++) if ( ref[i]=='N' ) nN++; if ( nN*2>i ) { free(aux); return -1; } ks_introsort(uint32_t, m, aux); // squeeze out identical types for (i = 1, n_types = 1; i < m; ++i) if (aux[i] != aux[i-1]) ++n_types; // Taking totals makes it hard to call rare indels if ( !bca->per_sample_flt ) indel_support_ok = ( (float)n_alt / n_tot < bca->min_frac || n_alt < bca->min_support ) ? 0 : 1; if ( n_types == 1 || !indel_support_ok ) { // then skip free(aux); return -1; } if (n_types >= 64) { free(aux); if (bam_verbose >= 2) fprintf(stderr, "[%s] excessive INDEL alleles at position %d. Skip the position.\n", __func__, pos + 1); return -1; } types = (int*)calloc(n_types, sizeof(int)); t = 0; types[t++] = aux[0] - MINUS_CONST; for (i = 1; i < m; ++i) if (aux[i] != aux[i-1]) types[t++] = aux[i] - MINUS_CONST; free(aux); for (t = 0; t < n_types; ++t) if (types[t] == 0) break; ref_type = t; // the index of the reference type (0) } { // calculate left and right boundary left = pos > INDEL_WINDOW_SIZE? pos - INDEL_WINDOW_SIZE : 0; right = pos + INDEL_WINDOW_SIZE; if (types[0] < 0) right -= types[0]; // in case the alignments stand out the reference for (i = pos; i < right; ++i) if (ref[i] == 0) break; right = i; } /* The following block fixes a long-existing flaw in the INDEL * calling model: the interference of nearby SNPs. However, it also * reduces the power because sometimes, substitutions caused by * indels are not distinguishable from true mutations. Multiple * sequence realignment helps to increase the power. * * Masks mismatches present in at least 70% of the reads with 'N'. */ { // construct per-sample consensus int L = right - left + 1, max_i, max2_i; uint32_t *cns, max, max2; char *ref0, *r; ref_sample = calloc(n, sizeof(void*)); cns = calloc(L, 4); ref0 = calloc(L, 1); for (i = 0; i < right - left; ++i) ref0[i] = bam_nt16_table[(int)ref[i+left]]; for (s = 0; s < n; ++s) { r = ref_sample[s] = calloc(L, 1); memset(cns, 0, sizeof(int) * L); // collect ref and non-ref counts for (i = 0; i < n_plp[s]; ++i) { bam_pileup1_t *p = plp[s] + i; bam1_t *b = p->b; uint32_t *cigar = bam1_cigar(b); uint8_t *seq = bam1_seq(b); int x = b->core.pos, y = 0; for (k = 0; k < b->core.n_cigar; ++k) { int op = cigar[k]&0xf; int j, l = cigar[k]>>4; if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) { for (j = 0; j < l; ++j) if (x + j >= left && x + j < right) cns[x+j-left] += (bam1_seqi(seq, y+j) == ref0[x+j-left])? 1 : 0x10000; x += l; y += l; } else if (op == BAM_CDEL || op == BAM_CREF_SKIP) x += l; else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) y += l; } } // determine the consensus for (i = 0; i < right - left; ++i) r[i] = ref0[i]; max = max2 = 0; max_i = max2_i = -1; for (i = 0; i < right - left; ++i) { if (cns[i]>>16 >= max>>16) max2 = max, max2_i = max_i, max = cns[i], max_i = i; else if (cns[i]>>16 >= max2>>16) max2 = cns[i], max2_i = i; } if ((double)(max&0xffff) / ((max&0xffff) + (max>>16)) >= 0.7) max_i = -1; if ((double)(max2&0xffff) / ((max2&0xffff) + (max2>>16)) >= 0.7) max2_i = -1; if (max_i >= 0) r[max_i] = 15; if (max2_i >= 0) r[max2_i] = 15; //for (i = 0; i < right - left; ++i) fputc("=ACMGRSVTWYHKDBN"[(int)r[i]], stderr); fputc('\n', stderr); } free(ref0); free(cns); } { // the length of the homopolymer run around the current position int c = bam_nt16_table[(int)ref[pos + 1]]; if (c == 15) l_run = 1; else { for (i = pos + 2; ref[i]; ++i) if (bam_nt16_table[(int)ref[i]] != c) break; l_run = i; for (i = pos; i >= 0; --i) if (bam_nt16_table[(int)ref[i]] != c) break; l_run -= i + 1; } } // construct the consensus sequence max_ins = types[n_types - 1]; // max_ins is at least 0 if (max_ins > 0) { int *inscns_aux = calloc(5 * n_types * max_ins, sizeof(int)); // count the number of occurrences of each base at each position for each type of insertion for (t = 0; t < n_types; ++t) { if (types[t] > 0) { for (s = 0; s < n; ++s) { for (i = 0; i < n_plp[s]; ++i) { bam_pileup1_t *p = plp[s] + i; if (p->indel == types[t]) { uint8_t *seq = bam1_seq(p->b); for (k = 1; k <= p->indel; ++k) { int c = bam_nt16_nt4_table[bam1_seqi(seq, p->qpos + k)]; assert(c<5); ++inscns_aux[(t*max_ins+(k-1))*5 + c]; } } } } } } // use the majority rule to construct the consensus inscns = calloc(n_types * max_ins, 1); for (t = 0; t < n_types; ++t) { for (j = 0; j < types[t]; ++j) { int max = 0, max_k = -1, *ia = &inscns_aux[(t*max_ins+j)*5]; for (k = 0; k < 5; ++k) if (ia[k] > max) max = ia[k], max_k = k; inscns[t*max_ins + j] = max? max_k : 4; if ( max_k==4 ) { types[t] = 0; break; } // discard insertions which contain N's } } free(inscns_aux); } // compute the likelihood given each type of indel for each read max_ref2 = right - left + 2 + 2 * (max_ins > -types[0]? max_ins : -types[0]); ref2 = calloc(max_ref2, 1); query = calloc(right - left + max_rd_len + max_ins + 2, 1); score1 = calloc(N * n_types, sizeof(int)); score2 = calloc(N * n_types, sizeof(int)); bca->indelreg = 0; for (t = 0; t < n_types; ++t) { int l, ir; kpa_par_t apf1 = { 1e-4, 1e-2, 10 }, apf2 = { 1e-6, 1e-3, 10 }; apf1.bw = apf2.bw = abs(types[t]) + 3; // compute indelreg if (types[t] == 0) ir = 0; else if (types[t] > 0) ir = est_indelreg(pos, ref, types[t], &inscns[t*max_ins]); else ir = est_indelreg(pos, ref, -types[t], 0); if (ir > bca->indelreg) bca->indelreg = ir; // fprintf(stderr, "%d, %d, %d\n", pos, types[t], ir); // realignment for (s = K = 0; s < n; ++s) { // write ref2 for (k = 0, j = left; j <= pos; ++j) ref2[k++] = bam_nt16_nt4_table[(int)ref_sample[s][j-left]]; if (types[t] <= 0) j += -types[t]; else for (l = 0; l < types[t]; ++l) ref2[k++] = inscns[t*max_ins + l]; for (; j < right && ref[j]; ++j) ref2[k++] = bam_nt16_nt4_table[(int)ref_sample[s][j-left]]; for (; k < max_ref2; ++k) ref2[k] = 4; if (j < right) right = j; // align each read to ref2 for (i = 0; i < n_plp[s]; ++i, ++K) { bam_pileup1_t *p = plp[s] + i; int qbeg, qend, tbeg, tend, sc, kk; uint8_t *seq = bam1_seq(p->b); uint32_t *cigar = bam1_cigar(p->b); if (p->b->core.flag&4) continue; // unmapped reads // FIXME: the following loop should be better moved outside; nonetheless, realignment should be much slower anyway. for (kk = 0; kk < p->b->core.n_cigar; ++kk) if ((cigar[kk]&BAM_CIGAR_MASK) == BAM_CREF_SKIP) break; if (kk < p->b->core.n_cigar) continue; // FIXME: the following skips soft clips, but using them may be more sensitive. // determine the start and end of sequences for alignment qbeg = tpos2qpos(&p->b->core, bam1_cigar(p->b), left, 0, &tbeg); qend = tpos2qpos(&p->b->core, bam1_cigar(p->b), right, 1, &tend); if (types[t] < 0) { int l = -types[t]; tbeg = tbeg - l > left? tbeg - l : left; } // write the query sequence for (l = qbeg; l < qend; ++l) query[l - qbeg] = bam_nt16_nt4_table[bam1_seqi(seq, l)]; { // do realignment; this is the bottleneck const uint8_t *qual = bam1_qual(p->b), *bq; uint8_t *qq; qq = calloc(qend - qbeg, 1); bq = (uint8_t*)bam_aux_get(p->b, "ZQ"); if (bq) ++bq; // skip type for (l = qbeg; l < qend; ++l) { qq[l - qbeg] = bq? qual[l] + (bq[l] - 64) : qual[l]; if (qq[l - qbeg] > 30) qq[l - qbeg] = 30; if (qq[l - qbeg] < 7) qq[l - qbeg] = 7; } sc = kpa_glocal((uint8_t*)ref2 + tbeg - left, tend - tbeg + abs(types[t]), (uint8_t*)query, qend - qbeg, qq, &apf1, 0, 0); l = (int)(100. * sc / (qend - qbeg) + .499); // used for adjusting indelQ below if (l > 255) l = 255; score1[K*n_types + t] = score2[K*n_types + t] = sc<<8 | l; if (sc > 5) { sc = kpa_glocal((uint8_t*)ref2 + tbeg - left, tend - tbeg + abs(types[t]), (uint8_t*)query, qend - qbeg, qq, &apf2, 0, 0); l = (int)(100. * sc / (qend - qbeg) + .499); if (l > 255) l = 255; score2[K*n_types + t] = sc<<8 | l; } free(qq); } /* for (l = 0; l < tend - tbeg + abs(types[t]); ++l) fputc("ACGTN"[(int)ref2[tbeg-left+l]], stderr); fputc('\n', stderr); for (l = 0; l < qend - qbeg; ++l) fputc("ACGTN"[(int)query[l]], stderr); fputc('\n', stderr); fprintf(stderr, "pos=%d type=%d read=%d:%d name=%s qbeg=%d tbeg=%d score=%d\n", pos, types[t], s, i, bam1_qname(p->b), qbeg, tbeg, sc); */ } } } free(ref2); free(query); { // compute indelQ int *sc, tmp, *sumq; sc = alloca(n_types * sizeof(int)); sumq = alloca(n_types * sizeof(int)); memset(sumq, 0, sizeof(int) * n_types); for (s = K = 0; s < n; ++s) { for (i = 0; i < n_plp[s]; ++i, ++K) { bam_pileup1_t *p = plp[s] + i; int *sct = &score1[K*n_types], indelQ1, indelQ2, seqQ, indelQ; for (t = 0; t < n_types; ++t) sc[t] = sct[t]<<6 | t; for (t = 1; t < n_types; ++t) // insertion sort for (j = t; j > 0 && sc[j] < sc[j-1]; --j) tmp = sc[j], sc[j] = sc[j-1], sc[j-1] = tmp; /* errmod_cal() assumes that if the call is wrong, the * likelihoods of other events are equal. This is about * right for substitutions, but is not desired for * indels. To reuse errmod_cal(), I have to make * compromise for multi-allelic indels. */ if ((sc[0]&0x3f) == ref_type) { indelQ1 = (sc[1]>>14) - (sc[0]>>14); seqQ = est_seqQ(bca, types[sc[1]&0x3f], l_run); } else { for (t = 0; t < n_types; ++t) // look for the reference type if ((sc[t]&0x3f) == ref_type) break; indelQ1 = (sc[t]>>14) - (sc[0]>>14); seqQ = est_seqQ(bca, types[sc[0]&0x3f], l_run); } tmp = sc[0]>>6 & 0xff; indelQ1 = tmp > 111? 0 : (int)((1. - tmp/111.) * indelQ1 + .499); // reduce indelQ sct = &score2[K*n_types]; for (t = 0; t < n_types; ++t) sc[t] = sct[t]<<6 | t; for (t = 1; t < n_types; ++t) // insertion sort for (j = t; j > 0 && sc[j] < sc[j-1]; --j) tmp = sc[j], sc[j] = sc[j-1], sc[j-1] = tmp; if ((sc[0]&0x3f) == ref_type) { indelQ2 = (sc[1]>>14) - (sc[0]>>14); } else { for (t = 0; t < n_types; ++t) // look for the reference type if ((sc[t]&0x3f) == ref_type) break; indelQ2 = (sc[t]>>14) - (sc[0]>>14); } tmp = sc[0]>>6 & 0xff; indelQ2 = tmp > 111? 0 : (int)((1. - tmp/111.) * indelQ2 + .499); // pick the smaller between indelQ1 and indelQ2 indelQ = indelQ1 < indelQ2? indelQ1 : indelQ2; if (indelQ > 255) indelQ = 255; if (seqQ > 255) seqQ = 255; p->aux = (sc[0]&0x3f)<<16 | seqQ<<8 | indelQ; // use 22 bits in total sumq[sc[0]&0x3f] += indelQ < seqQ? indelQ : seqQ; // fprintf(stderr, "pos=%d read=%d:%d name=%s call=%d indelQ=%d seqQ=%d\n", pos, s, i, bam1_qname(p->b), types[sc[0]&0x3f], indelQ, seqQ); } } // determine bca->indel_types[] and bca->inscns bca->maxins = max_ins; bca->inscns = realloc(bca->inscns, bca->maxins * 4); for (t = 0; t < n_types; ++t) sumq[t] = sumq[t]<<6 | t; for (t = 1; t < n_types; ++t) // insertion sort for (j = t; j > 0 && sumq[j] > sumq[j-1]; --j) tmp = sumq[j], sumq[j] = sumq[j-1], sumq[j-1] = tmp; for (t = 0; t < n_types; ++t) // look for the reference type if ((sumq[t]&0x3f) == ref_type) break; if (t) { // then move the reference type to the first tmp = sumq[t]; for (; t > 0; --t) sumq[t] = sumq[t-1]; sumq[0] = tmp; } for (t = 0; t < 4; ++t) bca->indel_types[t] = B2B_INDEL_NULL; for (t = 0; t < 4 && t < n_types; ++t) { bca->indel_types[t] = types[sumq[t]&0x3f]; memcpy(&bca->inscns[t * bca->maxins], &inscns[(sumq[t]&0x3f) * max_ins], bca->maxins); } // update p->aux for (s = n_alt = 0; s < n; ++s) { for (i = 0; i < n_plp[s]; ++i) { bam_pileup1_t *p = plp[s] + i; int x = types[p->aux>>16&0x3f]; for (j = 0; j < 4; ++j) if (x == bca->indel_types[j]) break; p->aux = j<<16 | (j == 4? 0 : (p->aux&0xffff)); if ((p->aux>>16&0x3f) > 0) ++n_alt; // fprintf(stderr, "X pos=%d read=%d:%d name=%s call=%d type=%d q=%d seqQ=%d\n", pos, s, i, bam1_qname(p->b), p->aux>>16&63, bca->indel_types[p->aux>>16&63], p->aux&0xff, p->aux>>8&0xff); } } } free(score1); free(score2); // free for (i = 0; i < n; ++i) free(ref_sample[i]); free(ref_sample); free(types); free(inscns); return n_alt > 0? 0 : -1; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_tview_curses.c
.c
7,879
298
#undef _HAVE_CURSES #if _CURSES_LIB == 0 #elif _CURSES_LIB == 1 #include <curses.h> #ifndef NCURSES_VERSION #warning "_CURSES_LIB=1 but NCURSES_VERSION not defined; tview is NOT compiled" #else #define _HAVE_CURSES #endif #elif _CURSES_LIB == 2 #include <xcurses.h> #define _HAVE_CURSES #else #warning "_CURSES_LIB is not 0, 1 or 2; tview is NOT compiled" #endif #include "bam_tview.h" #ifdef _HAVE_CURSES typedef struct CursesTview { tview_t view; WINDOW *wgoto, *whelp; } curses_tview_t; #define FROM_TV(ptr) ((curses_tview_t*)ptr) static void curses_destroy(tview_t* base) { curses_tview_t* tv=(curses_tview_t*)base; delwin(tv->wgoto); delwin(tv->whelp); endwin(); base_tv_destroy(base); free(tv); } /* void (*my_mvprintw)(struct AbstractTview* ,int,int,const char*,...); void (*my_)(struct AbstractTview*,int,int,int); void (*my_attron)(struct AbstractTview*,int); void (*my_attroff)(struct AbstractTview*,int); void (*my_clear)(struct AbstractTview*); int (*my_colorpair)(struct AbstractTview*,int); */ static void curses_mvprintw(struct AbstractTview* tv,int y ,int x,const char* fmt,...) { unsigned int size=tv->mcol+2; char* str=malloc(size); if(str==0) exit(EXIT_FAILURE); va_list argptr; va_start(argptr, fmt); vsnprintf(str,size, fmt, argptr); va_end(argptr); mvprintw(y,x,str); free(str); } static void curses_mvaddch(struct AbstractTview* tv,int y,int x,int ch) { mvaddch(y,x,ch); } static void curses_attron(struct AbstractTview* tv,int flag) { attron(flag); } static void curses_attroff(struct AbstractTview* tv,int flag) { attroff(flag); } static void curses_clear(struct AbstractTview* tv) { clear(); } static int curses_colorpair(struct AbstractTview* tv,int flag) { return COLOR_PAIR(flag); } static int curses_drawaln(struct AbstractTview* tv, int tid, int pos) { return base_draw_aln(tv, tid, pos); } static void tv_win_goto(curses_tview_t *tv, int *tid, int *pos) { char str[256], *p; int i, l = 0; tview_t *base=(tview_t*)tv; wborder(tv->wgoto, '|', '|', '-', '-', '+', '+', '+', '+'); mvwprintw(tv->wgoto, 1, 2, "Goto: "); for (;;) { int c = wgetch(tv->wgoto); wrefresh(tv->wgoto); if (c == KEY_BACKSPACE || c == '\010' || c == '\177') { if(l > 0) --l; } else if (c == KEY_ENTER || c == '\012' || c == '\015') { int _tid = -1, _beg, _end; if (str[0] == '=') { _beg = strtol(str+1, &p, 10) - 1; if (_beg > 0) { *pos = _beg; return; } } else { bam_parse_region(base->header, str, &_tid, &_beg, &_end); if (_tid >= 0) { *tid = _tid; *pos = _beg; return; } } } else if (isgraph(c)) { if (l < TV_MAX_GOTO) str[l++] = c; } else if (c == '\027') l = 0; else if (c == '\033') return; str[l] = '\0'; for (i = 0; i < TV_MAX_GOTO; ++i) mvwaddch(tv->wgoto, 1, 8 + i, ' '); mvwprintw(tv->wgoto, 1, 8, "%s", str); } } static void tv_win_help(curses_tview_t *tv) { int r = 1; tview_t* base=(tview_t*)base; WINDOW *win = tv->whelp; wborder(win, '|', '|', '-', '-', '+', '+', '+', '+'); mvwprintw(win, r++, 2, " -=- Help -=- "); r++; mvwprintw(win, r++, 2, "? This window"); mvwprintw(win, r++, 2, "Arrows Small scroll movement"); mvwprintw(win, r++, 2, "h,j,k,l Small scroll movement"); mvwprintw(win, r++, 2, "H,J,K,L Large scroll movement"); mvwprintw(win, r++, 2, "ctrl-H Scroll 1k left"); mvwprintw(win, r++, 2, "ctrl-L Scroll 1k right"); mvwprintw(win, r++, 2, "space Scroll one screen"); mvwprintw(win, r++, 2, "backspace Scroll back one screen"); mvwprintw(win, r++, 2, "g Go to specific location"); mvwprintw(win, r++, 2, "m Color for mapping qual"); mvwprintw(win, r++, 2, "n Color for nucleotide"); mvwprintw(win, r++, 2, "b Color for base quality"); mvwprintw(win, r++, 2, "c Color for cs color"); mvwprintw(win, r++, 2, "z Color for cs qual"); mvwprintw(win, r++, 2, ". Toggle on/off dot view"); mvwprintw(win, r++, 2, "s Toggle on/off ref skip"); mvwprintw(win, r++, 2, "r Toggle on/off rd name"); mvwprintw(win, r++, 2, "N Turn on nt view"); mvwprintw(win, r++, 2, "C Turn on cs view"); mvwprintw(win, r++, 2, "i Toggle on/off ins"); mvwprintw(win, r++, 2, "q Exit"); r++; mvwprintw(win, r++, 2, "Underline: Secondary or orphan"); mvwprintw(win, r++, 2, "Blue: 0-9 Green: 10-19"); mvwprintw(win, r++, 2, "Yellow: 20-29 White: >=30"); wrefresh(win); wgetch(win); } static int curses_underline(tview_t* tv) { return A_UNDERLINE; } static int curses_loop(tview_t* tv) { int tid, pos; curses_tview_t *CTV=(curses_tview_t *)tv; tid = tv->curr_tid; pos = tv->left_pos; while (1) { int c = getch(); switch (c) { case '?': tv_win_help(CTV); break; case '\033': case 'q': goto end_loop; case '/': case 'g': tv_win_goto(CTV, &tid, &pos); break; case 'm': tv->color_for = TV_COLOR_MAPQ; break; case 'b': tv->color_for = TV_COLOR_BASEQ; break; case 'n': tv->color_for = TV_COLOR_NUCL; break; case 'c': tv->color_for = TV_COLOR_COL; break; case 'z': tv->color_for = TV_COLOR_COLQ; break; case 's': tv->no_skip = !tv->no_skip; break; case 'r': tv->show_name = !tv->show_name; break; case KEY_LEFT: case 'h': --pos; break; case KEY_RIGHT: case 'l': ++pos; break; case KEY_SLEFT: case 'H': pos -= 20; break; case KEY_SRIGHT: case 'L': pos += 20; break; case '.': tv->is_dot = !tv->is_dot; break; case 'N': tv->base_for = TV_BASE_NUCL; break; case 'C': tv->base_for = TV_BASE_COLOR_SPACE; break; case 'i': tv->ins = !tv->ins; break; case '\010': pos -= 1000; break; case '\014': pos += 1000; break; case ' ': pos += tv->mcol; break; case KEY_UP: case 'j': --tv->row_shift; break; case KEY_DOWN: case 'k': ++tv->row_shift; break; case KEY_BACKSPACE: case '\177': pos -= tv->mcol; break; case KEY_RESIZE: getmaxyx(stdscr, tv->mrow, tv->mcol); break; default: continue; } if (pos < 0) pos = 0; if (tv->row_shift < 0) tv->row_shift = 0; tv->my_drawaln(tv, tid, pos); } end_loop: return 0; } tview_t* curses_tv_init(const char *fn, const char *fn_fa, const char *samples) { curses_tview_t *tv = (curses_tview_t*)calloc(1, sizeof(curses_tview_t)); tview_t* base=(tview_t*)tv; if(tv==0) { fprintf(stderr,"Calloc failed\n"); return 0; } base_tv_init(base,fn,fn_fa,samples); /* initialize callbacks */ #define SET_CALLBACK(fun) base->my_##fun=curses_##fun; SET_CALLBACK(destroy); SET_CALLBACK(mvprintw); SET_CALLBACK(mvaddch); SET_CALLBACK(attron); SET_CALLBACK(attroff); SET_CALLBACK(clear); SET_CALLBACK(colorpair); SET_CALLBACK(drawaln); SET_CALLBACK(loop); SET_CALLBACK(underline); #undef SET_CALLBACK initscr(); keypad(stdscr, TRUE); clear(); noecho(); cbreak(); getmaxyx(stdscr, base->mrow, base->mcol); tv->wgoto = newwin(3, TV_MAX_GOTO + 10, 10, 5); tv->whelp = newwin(29, 40, 5, 5); start_color(); init_pair(1, COLOR_BLUE, COLOR_BLACK); init_pair(2, COLOR_GREEN, COLOR_BLACK); init_pair(3, COLOR_YELLOW, COLOR_BLACK); init_pair(4, COLOR_WHITE, COLOR_BLACK); init_pair(5, COLOR_GREEN, COLOR_BLACK); init_pair(6, COLOR_CYAN, COLOR_BLACK); init_pair(7, COLOR_YELLOW, COLOR_BLACK); init_pair(8, COLOR_RED, COLOR_BLACK); init_pair(9, COLOR_BLUE, COLOR_BLACK); return base; } #else // #ifdef _HAVE_CURSES #include <stdio.h> #warning "No curses library is available; tview with curses is disabled." extern tview_t* text_tv_init(const char *fn, const char *fn_fa, const char *samples); tview_t* curses_tv_init(const char *fn, const char *fn_fa, const char *samples) { return text_tv_init(fn,fn_fa,samples); } #endif // #ifdef _HAVE_CURSES
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_rmdup.c
.c
5,631
207
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <zlib.h> #include <unistd.h> #include "sam.h" typedef bam1_t *bam1_p; #include "khash.h" KHASH_SET_INIT_STR(name) KHASH_MAP_INIT_INT64(pos, bam1_p) #define BUFFER_SIZE 0x40000 typedef struct { uint64_t n_checked, n_removed; khash_t(pos) *best_hash; } lib_aux_t; KHASH_MAP_INIT_STR(lib, lib_aux_t) typedef struct { int n, max; bam1_t **a; } tmp_stack_t; static inline void stack_insert(tmp_stack_t *stack, bam1_t *b) { if (stack->n == stack->max) { stack->max = stack->max? stack->max<<1 : 0x10000; stack->a = (bam1_t**)realloc(stack->a, sizeof(bam1_t*) * stack->max); } stack->a[stack->n++] = b; } static inline void dump_best(tmp_stack_t *stack, samfile_t *out) { int i; for (i = 0; i != stack->n; ++i) { samwrite(out, stack->a[i]); bam_destroy1(stack->a[i]); } stack->n = 0; } static void clear_del_set(khash_t(name) *del_set) { khint_t k; for (k = kh_begin(del_set); k < kh_end(del_set); ++k) if (kh_exist(del_set, k)) free((char*)kh_key(del_set, k)); kh_clear(name, del_set); } static lib_aux_t *get_aux(khash_t(lib) *aux, const char *lib) { khint_t k = kh_get(lib, aux, lib); if (k == kh_end(aux)) { int ret; char *p = strdup(lib); lib_aux_t *q; k = kh_put(lib, aux, p, &ret); q = &kh_val(aux, k); q->n_checked = q->n_removed = 0; q->best_hash = kh_init(pos); return q; } else return &kh_val(aux, k); } static void clear_best(khash_t(lib) *aux, int max) { khint_t k; for (k = kh_begin(aux); k != kh_end(aux); ++k) { if (kh_exist(aux, k)) { lib_aux_t *q = &kh_val(aux, k); if (kh_size(q->best_hash) >= max) kh_clear(pos, q->best_hash); } } } static inline int sum_qual(const bam1_t *b) { int i, q; uint8_t *qual = bam1_qual(b); for (i = q = 0; i < b->core.l_qseq; ++i) q += qual[i]; return q; } void bam_rmdup_core(samfile_t *in, samfile_t *out) { bam1_t *b; int last_tid = -1, last_pos = -1; tmp_stack_t stack; khint_t k; khash_t(lib) *aux; khash_t(name) *del_set; aux = kh_init(lib); del_set = kh_init(name); b = bam_init1(); memset(&stack, 0, sizeof(tmp_stack_t)); kh_resize(name, del_set, 4 * BUFFER_SIZE); while (samread(in, b) >= 0) { bam1_core_t *c = &b->core; if (c->tid != last_tid || last_pos != c->pos) { dump_best(&stack, out); // write the result clear_best(aux, BUFFER_SIZE); if (c->tid != last_tid) { clear_best(aux, 0); if (kh_size(del_set)) { // check fprintf(stderr, "[bam_rmdup_core] %llu unmatched pairs\n", (long long)kh_size(del_set)); clear_del_set(del_set); } if ((int)c->tid == -1) { // append unmapped reads samwrite(out, b); while (samread(in, b) >= 0) samwrite(out, b); break; } last_tid = c->tid; fprintf(stderr, "[bam_rmdup_core] processing reference %s...\n", in->header->target_name[c->tid]); } } if (!(c->flag&BAM_FPAIRED) || (c->flag&(BAM_FUNMAP|BAM_FMUNMAP)) || (c->mtid >= 0 && c->tid != c->mtid)) { samwrite(out, b); } else if (c->isize > 0) { // paired, head uint64_t key = (uint64_t)c->pos<<32 | c->isize; const char *lib; lib_aux_t *q; int ret; lib = bam_get_library(in->header, b); q = lib? get_aux(aux, lib) : get_aux(aux, "\t"); ++q->n_checked; k = kh_put(pos, q->best_hash, key, &ret); if (ret == 0) { // found in best_hash bam1_t *p = kh_val(q->best_hash, k); ++q->n_removed; if (sum_qual(p) < sum_qual(b)) { // the current alignment is better; this can be accelerated in principle kh_put(name, del_set, strdup(bam1_qname(p)), &ret); // p will be removed bam_copy1(p, b); // replaced as b } else kh_put(name, del_set, strdup(bam1_qname(b)), &ret); // b will be removed if (ret == 0) fprintf(stderr, "[bam_rmdup_core] inconsistent BAM file for pair '%s'. Continue anyway.\n", bam1_qname(b)); } else { // not found in best_hash kh_val(q->best_hash, k) = bam_dup1(b); stack_insert(&stack, kh_val(q->best_hash, k)); } } else { // paired, tail k = kh_get(name, del_set, bam1_qname(b)); if (k != kh_end(del_set)) { free((char*)kh_key(del_set, k)); kh_del(name, del_set, k); } else samwrite(out, b); } last_pos = c->pos; } for (k = kh_begin(aux); k != kh_end(aux); ++k) { if (kh_exist(aux, k)) { lib_aux_t *q = &kh_val(aux, k); dump_best(&stack, out); fprintf(stderr, "[bam_rmdup_core] %lld / %lld = %.4lf in library '%s'\n", (long long)q->n_removed, (long long)q->n_checked, (double)q->n_removed/q->n_checked, kh_key(aux, k)); kh_destroy(pos, q->best_hash); free((char*)kh_key(aux, k)); } } kh_destroy(lib, aux); clear_del_set(del_set); kh_destroy(name, del_set); free(stack.a); bam_destroy1(b); } void bam_rmdupse_core(samfile_t *in, samfile_t *out, int force_se); int bam_rmdup(int argc, char *argv[]) { int c, is_se = 0, force_se = 0; samfile_t *in, *out; while ((c = getopt(argc, argv, "sS")) >= 0) { switch (c) { case 's': is_se = 1; break; case 'S': force_se = is_se = 1; break; } } if (optind + 2 > argc) { fprintf(stderr, "\n"); fprintf(stderr, "Usage: samtools rmdup [-sS] <input.srt.bam> <output.bam>\n\n"); fprintf(stderr, "Option: -s rmdup for SE reads\n"); fprintf(stderr, " -S treat PE reads as SE in rmdup (force -s)\n\n"); return 1; } in = samopen(argv[optind], "rb", 0); out = samopen(argv[optind+1], "wb", in->header); if (in == 0 || out == 0) { fprintf(stderr, "[bam_rmdup] fail to read/write input files\n"); return 1; } if (is_se) bam_rmdupse_core(in, out, force_se); else bam_rmdup_core(in, out); samclose(in); samclose(out); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_reheader.c
.c
1,506
63
#include <stdio.h> #include <stdlib.h> #include "knetfile.h" #include "bgzf.h" #include "bam.h" #define BUF_SIZE 0x10000 int bam_reheader(BGZF *in, const bam_header_t *h, int fd) { BGZF *fp; bam_header_t *old; int len; uint8_t *buf; if (in->is_write) return -1; buf = malloc(BUF_SIZE); old = bam_header_read(in); fp = bgzf_fdopen(fd, "w"); bam_header_write(fp, h); if (in->block_offset < in->block_length) { bgzf_write(fp, in->uncompressed_block + in->block_offset, in->block_length - in->block_offset); bgzf_flush(fp); } #ifdef _USE_KNETFILE while ((len = knet_read(in->fp, buf, BUF_SIZE)) > 0) fwrite(buf, 1, len, fp->fp); #else while (!feof(in->file) && (len = fread(buf, 1, BUF_SIZE, in->file)) > 0) fwrite(buf, 1, len, fp->file); #endif free(buf); fp->block_offset = in->block_offset = 0; bgzf_close(fp); return 0; } int main_reheader(int argc, char *argv[]) { bam_header_t *h; BGZF *in; if (argc != 3) { fprintf(stderr, "Usage: samtools reheader <in.header.sam> <in.bam>\n"); return 1; } { // read the header tamFile fph = sam_open(argv[1]); if (fph == 0) { fprintf(stderr, "[%s] fail to read the header from %s.\n", __func__, argv[1]); return 1; } h = sam_header_read(fph); sam_close(fph); } in = strcmp(argv[2], "-")? bam_open(argv[2], "r") : bam_dopen(fileno(stdin), "r"); if (in == 0) { fprintf(stderr, "[%s] fail to open file %s.\n", __func__, argv[2]); return 1; } bam_reheader(in, h, fileno(stdout)); bgzf_close(in); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/faidx.h
.h
3,188
104
/* The MIT License Copyright (c) 2008 Genome Research Ltd (GRL). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Contact: Heng Li <lh3@sanger.ac.uk> */ #ifndef FAIDX_H #define FAIDX_H /*! @header Index FASTA files and extract subsequence. @copyright The Wellcome Trust Sanger Institute. */ struct __faidx_t; typedef struct __faidx_t faidx_t; #ifdef __cplusplus extern "C" { #endif /*! @abstract Build index for a FASTA or razip compressed FASTA file. @param fn FASTA file name @return 0 on success; or -1 on failure @discussion File "fn.fai" will be generated. */ int fai_build(const char *fn); /*! @abstract Distroy a faidx_t struct. @param fai Pointer to the struct to be destroyed */ void fai_destroy(faidx_t *fai); /*! @abstract Load index from "fn.fai". @param fn File name of the FASTA file */ faidx_t *fai_load(const char *fn); /*! @abstract Fetch the sequence in a region. @param fai Pointer to the faidx_t struct @param reg Region in the format "chr2:20,000-30,000" @param len Length of the region @return Pointer to the sequence; null on failure @discussion The returned sequence is allocated by malloc family and should be destroyed by end users by calling free() on it. */ char *fai_fetch(const faidx_t *fai, const char *reg, int *len); /*! @abstract Fetch the number of sequences. @param fai Pointer to the faidx_t struct @return The number of sequences */ int faidx_fetch_nseq(const faidx_t *fai); /*! @abstract Fetch the sequence in a region. @param fai Pointer to the faidx_t struct @param c_name Region name @param p_beg_i Beginning position number (zero-based) @param p_end_i End position number (zero-based) @param len Length of the region @return Pointer to the sequence; null on failure @discussion The returned sequence is allocated by malloc family and should be destroyed by end users by calling free() on it. */ char *faidx_fetch_seq(const faidx_t *fai, char *c_name, int p_beg_i, int p_end_i, int *len); #ifdef __cplusplus } #endif #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/sample.h
.h
396
18
#ifndef BAM_SAMPLE_H #define BAM_SAMPLE_H #include "kstring.h" typedef struct { int n, m; char **smpl; void *rg2smid, *sm2id; } bam_sample_t; bam_sample_t *bam_smpl_init(void); int bam_smpl_add(bam_sample_t *sm, const char *abs, const char *txt); int bam_smpl_rg2smid(const bam_sample_t *sm, const char *fn, const char *rg, kstring_t *str); void bam_smpl_destroy(bam_sample_t *sm); #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_lpileup.c
.c
4,976
199
#include <stdlib.h> #include <stdio.h> #include <assert.h> #include "bam.h" #include "ksort.h" #define TV_GAP 2 typedef struct __freenode_t { uint32_t level:28, cnt:4; struct __freenode_t *next; } freenode_t, *freenode_p; #define freenode_lt(a,b) ((a)->cnt < (b)->cnt || ((a)->cnt == (b)->cnt && (a)->level < (b)->level)) KSORT_INIT(node, freenode_p, freenode_lt) /* Memory pool, similar to the one in bam_pileup.c */ typedef struct { int cnt, n, max; freenode_t **buf; } mempool_t; static mempool_t *mp_init() { return (mempool_t*)calloc(1, sizeof(mempool_t)); } static void mp_destroy(mempool_t *mp) { int k; for (k = 0; k < mp->n; ++k) free(mp->buf[k]); free(mp->buf); free(mp); } static inline freenode_t *mp_alloc(mempool_t *mp) { ++mp->cnt; if (mp->n == 0) return (freenode_t*)calloc(1, sizeof(freenode_t)); else return mp->buf[--mp->n]; } static inline void mp_free(mempool_t *mp, freenode_t *p) { --mp->cnt; p->next = 0; p->cnt = TV_GAP; if (mp->n == mp->max) { mp->max = mp->max? mp->max<<1 : 256; mp->buf = (freenode_t**)realloc(mp->buf, sizeof(freenode_t*) * mp->max); } mp->buf[mp->n++] = p; } /* core part */ struct __bam_lplbuf_t { int max, n_cur, n_pre; int max_level, *cur_level, *pre_level; mempool_t *mp; freenode_t **aux, *head, *tail; int n_nodes, m_aux; bam_pileup_f func; void *user_data; bam_plbuf_t *plbuf; }; void bam_lplbuf_reset(bam_lplbuf_t *buf) { freenode_t *p, *q; bam_plbuf_reset(buf->plbuf); for (p = buf->head; p->next;) { q = p->next; mp_free(buf->mp, p); p = q; } buf->head = buf->tail; buf->max_level = 0; buf->n_cur = buf->n_pre = 0; buf->n_nodes = 0; } static int tview_func(uint32_t tid, uint32_t pos, int n, const bam_pileup1_t *pl, void *data) { bam_lplbuf_t *tv = (bam_lplbuf_t*)data; freenode_t *p; int i, l, max_level; // allocate memory if necessary if (tv->max < n) { // enlarge tv->max = n; kroundup32(tv->max); tv->cur_level = (int*)realloc(tv->cur_level, sizeof(int) * tv->max); tv->pre_level = (int*)realloc(tv->pre_level, sizeof(int) * tv->max); } tv->n_cur = n; // update cnt for (p = tv->head; p->next; p = p->next) if (p->cnt > 0) --p->cnt; // calculate cur_level[] max_level = 0; for (i = l = 0; i < n; ++i) { const bam_pileup1_t *p = pl + i; if (p->is_head) { if (tv->head->next && tv->head->cnt == 0) { // then take a free slot freenode_t *p = tv->head->next; tv->cur_level[i] = tv->head->level; mp_free(tv->mp, tv->head); tv->head = p; --tv->n_nodes; } else tv->cur_level[i] = ++tv->max_level; } else { tv->cur_level[i] = tv->pre_level[l++]; if (p->is_tail) { // then return a free slot tv->tail->level = tv->cur_level[i]; tv->tail->next = mp_alloc(tv->mp); tv->tail = tv->tail->next; ++tv->n_nodes; } } if (tv->cur_level[i] > max_level) max_level = tv->cur_level[i]; ((bam_pileup1_t*)p)->level = tv->cur_level[i]; } assert(l == tv->n_pre); tv->func(tid, pos, n, pl, tv->user_data); // sort the linked list if (tv->n_nodes) { freenode_t *q; if (tv->n_nodes + 1 > tv->m_aux) { // enlarge tv->m_aux = tv->n_nodes + 1; kroundup32(tv->m_aux); tv->aux = (freenode_t**)realloc(tv->aux, sizeof(void*) * tv->m_aux); } for (p = tv->head, i = l = 0; p->next;) { if (p->level > max_level) { // then discard this entry q = p->next; mp_free(tv->mp, p); p = q; } else { tv->aux[i++] = p; p = p->next; } } tv->aux[i] = tv->tail; // add a proper tail for the loop below tv->n_nodes = i; if (tv->n_nodes) { ks_introsort(node, tv->n_nodes, tv->aux); for (i = 0; i < tv->n_nodes; ++i) tv->aux[i]->next = tv->aux[i+1]; tv->head = tv->aux[0]; } else tv->head = tv->tail; } // clean up tv->max_level = max_level; memcpy(tv->pre_level, tv->cur_level, tv->n_cur * 4); // squeeze out terminated levels for (i = l = 0; i < n; ++i) { const bam_pileup1_t *p = pl + i; if (!p->is_tail) tv->pre_level[l++] = tv->pre_level[i]; } tv->n_pre = l; /* fprintf(stderr, "%d\t", pos+1); for (i = 0; i < n; ++i) { const bam_pileup1_t *p = pl + i; if (p->is_head) fprintf(stderr, "^"); if (p->is_tail) fprintf(stderr, "$"); fprintf(stderr, "%d,", p->level); } fprintf(stderr, "\n"); */ return 0; } bam_lplbuf_t *bam_lplbuf_init(bam_pileup_f func, void *data) { bam_lplbuf_t *tv; tv = (bam_lplbuf_t*)calloc(1, sizeof(bam_lplbuf_t)); tv->mp = mp_init(); tv->head = tv->tail = mp_alloc(tv->mp); tv->func = func; tv->user_data = data; tv->plbuf = bam_plbuf_init(tview_func, tv); return (bam_lplbuf_t*)tv; } void bam_lplbuf_destroy(bam_lplbuf_t *tv) { freenode_t *p, *q; free(tv->cur_level); free(tv->pre_level); bam_plbuf_destroy(tv->plbuf); free(tv->aux); for (p = tv->head; p->next;) { q = p->next; mp_free(tv->mp, p); p = q; } mp_free(tv->mp, p); assert(tv->mp->cnt == 0); mp_destroy(tv->mp); free(tv); } int bam_lplbuf_push(const bam1_t *b, bam_lplbuf_t *tv) { return bam_plbuf_push(b, tv->plbuf); }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_cat.c
.c
5,803
186
/* bam_cat -- efficiently concatenates bam files bam_cat can be used to concatenate BAM files. Under special circumstances, it can be used as an alternative to 'samtools merge' to concatenate multiple sorted files into a single sorted file. For this to work each file must be sorted, and the sorted files must be given as command line arguments in order such that the final read in file i is less than or equal to the first read in file i+1. This code is derived from the bam_reheader function in samtools 0.1.8 and modified to perform concatenation by Chris Saunders on behalf of Illumina. ########## License: The MIT License Original SAMtools work copyright (c) 2008-2009 Genome Research Ltd. Modified SAMtools work copyright (c) 2010 Illumina, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* makefile: """ CC=gcc CFLAGS+=-g -Wall -O2 -D_FILE_OFFSET_BITS=64 -D_USE_KNETFILE -I$(SAMTOOLS_DIR) LDFLAGS+=-L$(SAMTOOLS_DIR) LDLIBS+=-lbam -lz all:bam_cat """ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "knetfile.h" #include "bgzf.h" #include "bam.h" #define BUF_SIZE 0x10000 #define GZIPID1 31 #define GZIPID2 139 #define BGZF_EMPTY_BLOCK_SIZE 28 int bam_cat(int nfn, char * const *fn, const bam_header_t *h, const char* outbam) { BGZF *fp; FILE* fp_file; uint8_t *buf; uint8_t ebuf[BGZF_EMPTY_BLOCK_SIZE]; const int es=BGZF_EMPTY_BLOCK_SIZE; int i; fp = strcmp(outbam, "-")? bgzf_open(outbam, "w") : bgzf_fdopen(fileno(stdout), "w"); if (fp == 0) { fprintf(stderr, "[%s] ERROR: fail to open output file '%s'.\n", __func__, outbam); return 1; } if (h) bam_header_write(fp, h); buf = (uint8_t*) malloc(BUF_SIZE); for(i = 0; i < nfn; ++i){ BGZF *in; bam_header_t *old; int len,j; in = strcmp(fn[i], "-")? bam_open(fn[i], "r") : bam_dopen(fileno(stdin), "r"); if (in == 0) { fprintf(stderr, "[%s] ERROR: fail to open file '%s'.\n", __func__, fn[i]); return -1; } if (in->is_write) return -1; old = bam_header_read(in); if (h == 0 && i == 0) bam_header_write(fp, old); if (in->block_offset < in->block_length) { bgzf_write(fp, in->uncompressed_block + in->block_offset, in->block_length - in->block_offset); bgzf_flush(fp); } j=0; #ifdef _USE_KNETFILE fp_file = fp->fp; while ((len = knet_read(in->fp, buf, BUF_SIZE)) > 0) { #else fp_file = fp->fp; while (!feof(in->file) && (len = fread(buf, 1, BUF_SIZE, in->file)) > 0) { #endif if(len<es){ int diff=es-len; if(j==0) { fprintf(stderr, "[%s] ERROR: truncated file?: '%s'.\n", __func__, fn[i]); return -1; } fwrite(ebuf, 1, len, fp_file); memcpy(ebuf,ebuf+len,diff); memcpy(ebuf+diff,buf,len); } else { if(j!=0) fwrite(ebuf, 1, es, fp_file); len-= es; memcpy(ebuf,buf+len,es); fwrite(buf, 1, len, fp_file); } j=1; } /* check final gzip block */ { const uint8_t gzip1=ebuf[0]; const uint8_t gzip2=ebuf[1]; const uint32_t isize=*((uint32_t*)(ebuf+es-4)); if(((gzip1!=GZIPID1) || (gzip2!=GZIPID2)) || (isize!=0)) { fprintf(stderr, "[%s] WARNING: Unexpected block structure in file '%s'.", __func__, fn[i]); fprintf(stderr, " Possible output corruption.\n"); fwrite(ebuf, 1, es, fp_file); } } bam_header_destroy(old); bgzf_close(in); } free(buf); bgzf_close(fp); return 0; } int main_cat(int argc, char *argv[]) { bam_header_t *h = 0; char *outfn = 0; int c, ret; while ((c = getopt(argc, argv, "h:o:")) >= 0) { switch (c) { case 'h': { tamFile fph = sam_open(optarg); if (fph == 0) { fprintf(stderr, "[%s] ERROR: fail to read the header from '%s'.\n", __func__, argv[1]); return 1; } h = sam_header_read(fph); sam_close(fph); break; } case 'o': outfn = strdup(optarg); break; } } if (argc - optind < 2) { fprintf(stderr, "Usage: samtools cat [-h header.sam] [-o out.bam] <in1.bam> <in2.bam> [...]\n"); return 1; } ret = bam_cat(argc - optind, argv + optind, h, outfn? outfn : "-"); free(outfn); return ret; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/khash.h
.h
17,815
529
/* The MIT License Copyright (c) 2008, 2009, 2011 by Attractive Chaos <attractor@live.co.uk> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* An example: #include "khash.h" KHASH_MAP_INIT_INT(32, char) int main() { int ret, is_missing; khiter_t k; khash_t(32) *h = kh_init(32); k = kh_put(32, h, 5, &ret); if (!ret) kh_del(32, h, k); kh_value(h, k) = 10; k = kh_get(32, h, 10); is_missing = (k == kh_end(h)); k = kh_get(32, h, 5); kh_del(32, h, k); for (k = kh_begin(h); k != kh_end(h); ++k) if (kh_exist(h, k)) kh_value(h, k) = 1; kh_destroy(32, h); return 0; } */ /* 2011-02-14 (0.2.5): * Allow to declare global functions. 2009-09-26 (0.2.4): * Improve portability 2008-09-19 (0.2.3): * Corrected the example * Improved interfaces 2008-09-11 (0.2.2): * Improved speed a little in kh_put() 2008-09-10 (0.2.1): * Added kh_clear() * Fixed a compiling error 2008-09-02 (0.2.0): * Changed to token concatenation which increases flexibility. 2008-08-31 (0.1.2): * Fixed a bug in kh_get(), which has not been tested previously. 2008-08-31 (0.1.1): * Added destructor */ #ifndef __AC_KHASH_H #define __AC_KHASH_H /*! @header Generic hash table library. @copyright Heng Li */ #define AC_VERSION_KHASH_H "0.2.5" #include <stdlib.h> #include <string.h> #include <limits.h> /* compipler specific configuration */ #if UINT_MAX == 0xffffffffu typedef unsigned int khint32_t; #elif ULONG_MAX == 0xffffffffu typedef unsigned long khint32_t; #endif #if ULONG_MAX == ULLONG_MAX typedef unsigned long khint64_t; #else typedef unsigned long long khint64_t; #endif #ifdef _MSC_VER #define inline __inline #endif typedef khint32_t khint_t; typedef khint_t khiter_t; #define __ac_HASH_PRIME_SIZE 32 static const khint32_t __ac_prime_list[__ac_HASH_PRIME_SIZE] = { 0ul, 3ul, 11ul, 23ul, 53ul, 97ul, 193ul, 389ul, 769ul, 1543ul, 3079ul, 6151ul, 12289ul, 24593ul, 49157ul, 98317ul, 196613ul, 393241ul, 786433ul, 1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul, 50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul, 1610612741ul, 3221225473ul, 4294967291ul }; #define __ac_isempty(flag, i) ((flag[i>>4]>>((i&0xfU)<<1))&2) #define __ac_isdel(flag, i) ((flag[i>>4]>>((i&0xfU)<<1))&1) #define __ac_iseither(flag, i) ((flag[i>>4]>>((i&0xfU)<<1))&3) #define __ac_set_isdel_false(flag, i) (flag[i>>4]&=~(1ul<<((i&0xfU)<<1))) #define __ac_set_isempty_false(flag, i) (flag[i>>4]&=~(2ul<<((i&0xfU)<<1))) #define __ac_set_isboth_false(flag, i) (flag[i>>4]&=~(3ul<<((i&0xfU)<<1))) #define __ac_set_isdel_true(flag, i) (flag[i>>4]|=1ul<<((i&0xfU)<<1)) static const double __ac_HASH_UPPER = 0.77; #define KHASH_DECLARE(name, khkey_t, khval_t) \ typedef struct { \ khint_t n_buckets, size, n_occupied, upper_bound; \ khint32_t *flags; \ khkey_t *keys; \ khval_t *vals; \ } kh_##name##_t; \ extern kh_##name##_t *kh_init_##name(); \ extern void kh_destroy_##name(kh_##name##_t *h); \ extern void kh_clear_##name(kh_##name##_t *h); \ extern khint_t kh_get_##name(const kh_##name##_t *h, khkey_t key); \ extern void kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets); \ extern khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret); \ extern void kh_del_##name(kh_##name##_t *h, khint_t x); #define KHASH_INIT2(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \ typedef struct { \ khint_t n_buckets, size, n_occupied, upper_bound; \ khint32_t *flags; \ khkey_t *keys; \ khval_t *vals; \ } kh_##name##_t; \ SCOPE kh_##name##_t *kh_init_##name() { \ return (kh_##name##_t*)calloc(1, sizeof(kh_##name##_t)); \ } \ SCOPE void kh_destroy_##name(kh_##name##_t *h) \ { \ if (h) { \ free(h->keys); free(h->flags); \ free(h->vals); \ free(h); \ } \ } \ SCOPE void kh_clear_##name(kh_##name##_t *h) \ { \ if (h && h->flags) { \ memset(h->flags, 0xaa, ((h->n_buckets>>4) + 1) * sizeof(khint32_t)); \ h->size = h->n_occupied = 0; \ } \ } \ SCOPE khint_t kh_get_##name(const kh_##name##_t *h, khkey_t key) \ { \ if (h->n_buckets) { \ khint_t inc, k, i, last; \ k = __hash_func(key); i = k % h->n_buckets; \ inc = 1 + k % (h->n_buckets - 1); last = i; \ while (!__ac_isempty(h->flags, i) && (__ac_isdel(h->flags, i) || !__hash_equal(h->keys[i], key))) { \ if (i + inc >= h->n_buckets) i = i + inc - h->n_buckets; \ else i += inc; \ if (i == last) return h->n_buckets; \ } \ return __ac_iseither(h->flags, i)? h->n_buckets : i; \ } else return 0; \ } \ SCOPE void kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets) \ { \ khint32_t *new_flags = 0; \ khint_t j = 1; \ { \ khint_t t = __ac_HASH_PRIME_SIZE - 1; \ while (__ac_prime_list[t] > new_n_buckets) --t; \ new_n_buckets = __ac_prime_list[t+1]; \ if (h->size >= (khint_t)(new_n_buckets * __ac_HASH_UPPER + 0.5)) j = 0; \ else { \ new_flags = (khint32_t*)malloc(((new_n_buckets>>4) + 1) * sizeof(khint32_t)); \ memset(new_flags, 0xaa, ((new_n_buckets>>4) + 1) * sizeof(khint32_t)); \ if (h->n_buckets < new_n_buckets) { \ h->keys = (khkey_t*)realloc(h->keys, new_n_buckets * sizeof(khkey_t)); \ if (kh_is_map) \ h->vals = (khval_t*)realloc(h->vals, new_n_buckets * sizeof(khval_t)); \ } \ } \ } \ if (j) { \ for (j = 0; j != h->n_buckets; ++j) { \ if (__ac_iseither(h->flags, j) == 0) { \ khkey_t key = h->keys[j]; \ khval_t val; \ if (kh_is_map) val = h->vals[j]; \ __ac_set_isdel_true(h->flags, j); \ while (1) { \ khint_t inc, k, i; \ k = __hash_func(key); \ i = k % new_n_buckets; \ inc = 1 + k % (new_n_buckets - 1); \ while (!__ac_isempty(new_flags, i)) { \ if (i + inc >= new_n_buckets) i = i + inc - new_n_buckets; \ else i += inc; \ } \ __ac_set_isempty_false(new_flags, i); \ if (i < h->n_buckets && __ac_iseither(h->flags, i) == 0) { \ { khkey_t tmp = h->keys[i]; h->keys[i] = key; key = tmp; } \ if (kh_is_map) { khval_t tmp = h->vals[i]; h->vals[i] = val; val = tmp; } \ __ac_set_isdel_true(h->flags, i); \ } else { \ h->keys[i] = key; \ if (kh_is_map) h->vals[i] = val; \ break; \ } \ } \ } \ } \ if (h->n_buckets > new_n_buckets) { \ h->keys = (khkey_t*)realloc(h->keys, new_n_buckets * sizeof(khkey_t)); \ if (kh_is_map) \ h->vals = (khval_t*)realloc(h->vals, new_n_buckets * sizeof(khval_t)); \ } \ free(h->flags); \ h->flags = new_flags; \ h->n_buckets = new_n_buckets; \ h->n_occupied = h->size; \ h->upper_bound = (khint_t)(h->n_buckets * __ac_HASH_UPPER + 0.5); \ } \ } \ SCOPE khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret) \ { \ khint_t x; \ if (h->n_occupied >= h->upper_bound) { \ if (h->n_buckets > (h->size<<1)) kh_resize_##name(h, h->n_buckets - 1); \ else kh_resize_##name(h, h->n_buckets + 1); \ } \ { \ khint_t inc, k, i, site, last; \ x = site = h->n_buckets; k = __hash_func(key); i = k % h->n_buckets; \ if (__ac_isempty(h->flags, i)) x = i; \ else { \ inc = 1 + k % (h->n_buckets - 1); last = i; \ while (!__ac_isempty(h->flags, i) && (__ac_isdel(h->flags, i) || !__hash_equal(h->keys[i], key))) { \ if (__ac_isdel(h->flags, i)) site = i; \ if (i + inc >= h->n_buckets) i = i + inc - h->n_buckets; \ else i += inc; \ if (i == last) { x = site; break; } \ } \ if (x == h->n_buckets) { \ if (__ac_isempty(h->flags, i) && site != h->n_buckets) x = site; \ else x = i; \ } \ } \ } \ if (__ac_isempty(h->flags, x)) { \ h->keys[x] = key; \ __ac_set_isboth_false(h->flags, x); \ ++h->size; ++h->n_occupied; \ *ret = 1; \ } else if (__ac_isdel(h->flags, x)) { \ h->keys[x] = key; \ __ac_set_isboth_false(h->flags, x); \ ++h->size; \ *ret = 2; \ } else *ret = 0; \ return x; \ } \ SCOPE void kh_del_##name(kh_##name##_t *h, khint_t x) \ { \ if (x != h->n_buckets && !__ac_iseither(h->flags, x)) { \ __ac_set_isdel_true(h->flags, x); \ --h->size; \ } \ } #define KHASH_INIT(name, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \ KHASH_INIT2(name, static inline, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) /* --- BEGIN OF HASH FUNCTIONS --- */ /*! @function @abstract Integer hash function @param key The integer [khint32_t] @return The hash value [khint_t] */ #define kh_int_hash_func(key) (khint32_t)(key) /*! @function @abstract Integer comparison function */ #define kh_int_hash_equal(a, b) ((a) == (b)) /*! @function @abstract 64-bit integer hash function @param key The integer [khint64_t] @return The hash value [khint_t] */ #define kh_int64_hash_func(key) (khint32_t)((key)>>33^(key)^(key)<<11) /*! @function @abstract 64-bit integer comparison function */ #define kh_int64_hash_equal(a, b) ((a) == (b)) /*! @function @abstract const char* hash function @param s Pointer to a null terminated string @return The hash value */ static inline khint_t __ac_X31_hash_string(const char *s) { khint_t h = *s; if (h) for (++s ; *s; ++s) h = (h << 5) - h + *s; return h; } /*! @function @abstract Another interface to const char* hash function @param key Pointer to a null terminated string [const char*] @return The hash value [khint_t] */ #define kh_str_hash_func(key) __ac_X31_hash_string(key) /*! @function @abstract Const char* comparison function */ #define kh_str_hash_equal(a, b) (strcmp(a, b) == 0) /* --- END OF HASH FUNCTIONS --- */ /* Other necessary macros... */ /*! @abstract Type of the hash table. @param name Name of the hash table [symbol] */ #define khash_t(name) kh_##name##_t /*! @function @abstract Initiate a hash table. @param name Name of the hash table [symbol] @return Pointer to the hash table [khash_t(name)*] */ #define kh_init(name) kh_init_##name() /*! @function @abstract Destroy a hash table. @param name Name of the hash table [symbol] @param h Pointer to the hash table [khash_t(name)*] */ #define kh_destroy(name, h) kh_destroy_##name(h) /*! @function @abstract Reset a hash table without deallocating memory. @param name Name of the hash table [symbol] @param h Pointer to the hash table [khash_t(name)*] */ #define kh_clear(name, h) kh_clear_##name(h) /*! @function @abstract Resize a hash table. @param name Name of the hash table [symbol] @param h Pointer to the hash table [khash_t(name)*] @param s New size [khint_t] */ #define kh_resize(name, h, s) kh_resize_##name(h, s) /*! @function @abstract Insert a key to the hash table. @param name Name of the hash table [symbol] @param h Pointer to the hash table [khash_t(name)*] @param k Key [type of keys] @param r Extra return code: 0 if the key is present in the hash table; 1 if the bucket is empty (never used); 2 if the element in the bucket has been deleted [int*] @return Iterator to the inserted element [khint_t] */ #define kh_put(name, h, k, r) kh_put_##name(h, k, r) /*! @function @abstract Retrieve a key from the hash table. @param name Name of the hash table [symbol] @param h Pointer to the hash table [khash_t(name)*] @param k Key [type of keys] @return Iterator to the found element, or kh_end(h) is the element is absent [khint_t] */ #define kh_get(name, h, k) kh_get_##name(h, k) /*! @function @abstract Remove a key from the hash table. @param name Name of the hash table [symbol] @param h Pointer to the hash table [khash_t(name)*] @param k Iterator to the element to be deleted [khint_t] */ #define kh_del(name, h, k) kh_del_##name(h, k) /*! @function @abstract Test whether a bucket contains data. @param h Pointer to the hash table [khash_t(name)*] @param x Iterator to the bucket [khint_t] @return 1 if containing data; 0 otherwise [int] */ #define kh_exist(h, x) (!__ac_iseither((h)->flags, (x))) /*! @function @abstract Get key given an iterator @param h Pointer to the hash table [khash_t(name)*] @param x Iterator to the bucket [khint_t] @return Key [type of keys] */ #define kh_key(h, x) ((h)->keys[x]) /*! @function @abstract Get value given an iterator @param h Pointer to the hash table [khash_t(name)*] @param x Iterator to the bucket [khint_t] @return Value [type of values] @discussion For hash sets, calling this results in segfault. */ #define kh_val(h, x) ((h)->vals[x]) /*! @function @abstract Alias of kh_val() */ #define kh_value(h, x) ((h)->vals[x]) /*! @function @abstract Get the start iterator @param h Pointer to the hash table [khash_t(name)*] @return The start iterator [khint_t] */ #define kh_begin(h) (khint_t)(0) /*! @function @abstract Get the end iterator @param h Pointer to the hash table [khash_t(name)*] @return The end iterator [khint_t] */ #define kh_end(h) ((h)->n_buckets) /*! @function @abstract Get the number of elements in the hash table @param h Pointer to the hash table [khash_t(name)*] @return Number of elements in the hash table [khint_t] */ #define kh_size(h) ((h)->size) /*! @function @abstract Get the number of buckets in the hash table @param h Pointer to the hash table [khash_t(name)*] @return Number of buckets in the hash table [khint_t] */ #define kh_n_buckets(h) ((h)->n_buckets) /* More conenient interfaces */ /*! @function @abstract Instantiate a hash set containing integer keys @param name Name of the hash table [symbol] */ #define KHASH_SET_INIT_INT(name) \ KHASH_INIT(name, khint32_t, char, 0, kh_int_hash_func, kh_int_hash_equal) /*! @function @abstract Instantiate a hash map containing integer keys @param name Name of the hash table [symbol] @param khval_t Type of values [type] */ #define KHASH_MAP_INIT_INT(name, khval_t) \ KHASH_INIT(name, khint32_t, khval_t, 1, kh_int_hash_func, kh_int_hash_equal) /*! @function @abstract Instantiate a hash map containing 64-bit integer keys @param name Name of the hash table [symbol] */ #define KHASH_SET_INIT_INT64(name) \ KHASH_INIT(name, khint64_t, char, 0, kh_int64_hash_func, kh_int64_hash_equal) /*! @function @abstract Instantiate a hash map containing 64-bit integer keys @param name Name of the hash table [symbol] @param khval_t Type of values [type] */ #define KHASH_MAP_INIT_INT64(name, khval_t) \ KHASH_INIT(name, khint64_t, khval_t, 1, kh_int64_hash_func, kh_int64_hash_equal) typedef const char *kh_cstr_t; /*! @function @abstract Instantiate a hash map containing const char* keys @param name Name of the hash table [symbol] */ #define KHASH_SET_INIT_STR(name) \ KHASH_INIT(name, kh_cstr_t, char, 0, kh_str_hash_func, kh_str_hash_equal) /*! @function @abstract Instantiate a hash map containing const char* keys @param name Name of the hash table [symbol] @param khval_t Type of values [type] */ #define KHASH_MAP_INIT_STR(name, khval_t) \ KHASH_INIT(name, kh_cstr_t, khval_t, 1, kh_str_hash_func, kh_str_hash_equal) #endif /* __AC_KHASH_H */
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam2bcf.h
.h
1,889
68
#ifndef BAM2BCF_H #define BAM2BCF_H #include <stdint.h> #include "errmod.h" #include "bcftools/bcf.h" #define B2B_INDEL_NULL 10000 #define B2B_FMT_DP 0x1 #define B2B_FMT_SP 0x2 #define B2B_FMT_DV 0x4 typedef struct __bcf_callaux_t { int capQ, min_baseQ; int openQ, extQ, tandemQ; // for indels int min_support, max_support; // for collecting indel candidates double min_frac, max_frac; // for collecting indel candidates int per_sample_flt; // indel filtering strategy int *ref_pos, *alt_pos, npos; // for ReadPosBias // for internal uses int max_bases; int indel_types[4]; int maxins, indelreg; int read_len; char *inscns; uint16_t *bases; errmod_t *e; void *rghash; } bcf_callaux_t; typedef struct { int depth, n_supp, ori_depth, qsum[4]; unsigned int anno[16]; float p[25]; } bcf_callret1_t; typedef struct { int a[5]; // alleles: ref, alt, alt2, alt3 float qsum[4]; int n, n_alleles, shift, ori_ref, unseen; int n_supp; // number of supporting non-reference reads unsigned int anno[16], depth, ori_depth; uint8_t *PL; float vdb; // variant distance bias float read_pos_bias; struct { float avg, var; int dp; } read_pos; } bcf_call_t; #ifdef __cplusplus extern "C" { #endif bcf_callaux_t *bcf_call_init(double theta, int min_baseQ); void bcf_call_destroy(bcf_callaux_t *bca); int bcf_call_glfgen(int _n, const bam_pileup1_t *pl, int ref_base, bcf_callaux_t *bca, bcf_callret1_t *r); int bcf_call_combine(int n, const bcf_callret1_t *calls, bcf_callaux_t *bca, int ref_base /*4-bit*/, bcf_call_t *call); int bcf_call2bcf(int tid, int pos, bcf_call_t *bc, bcf1_t *b, bcf_callret1_t *bcr, int fmt_flag, const bcf_callaux_t *bca, const char *ref); int bcf_call_gap_prep(int n, int *n_plp, bam_pileup1_t **plp, int pos, bcf_callaux_t *bca, const char *ref, const void *rghash); #ifdef __cplusplus } #endif #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/kprobaln.h
.h
1,568
50
/* The MIT License Copyright (c) 2003-2006, 2008, 2009 by Heng Li <lh3@live.co.uk> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef LH3_KPROBALN_H_ #define LH3_KPROBALN_H_ #include <stdint.h> typedef struct { float d, e; int bw; } kpa_par_t; #ifdef __cplusplus extern "C" { #endif int kpa_glocal(const uint8_t *_ref, int l_ref, const uint8_t *_query, int l_query, const uint8_t *iqual, const kpa_par_t *c, int *state, uint8_t *q); #ifdef __cplusplus } #endif extern kpa_par_t kpa_par_def, kpa_par_alt; #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/errmod.h
.h
442
25
#ifndef ERRMOD_H #define ERRMOD_H #include <stdint.h> struct __errmod_coef_t; typedef struct { double depcorr; struct __errmod_coef_t *coef; } errmod_t; errmod_t *errmod_init(float depcorr); void errmod_destroy(errmod_t *em); /* n: number of bases m: maximum base bases[i]: qual:6, strand:1, base:4 q[i*m+j]: phred-scaled likelihood of (i,j) */ int errmod_cal(const errmod_t *em, int n, int m, uint16_t *bases, float *q); #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_tview.h
.h
1,880
76
#ifndef BAM_TVIEW_H #define BAM_TVIEW_H #include <ctype.h> #include <assert.h> #include <string.h> #include <math.h> #include <unistd.h> #include <stdarg.h> #include "bam.h" #include "faidx.h" #include "bam2bcf.h" #include "sam_header.h" #include "khash.h" KHASH_MAP_INIT_STR(kh_rg, const char *) typedef struct AbstractTview { int mrow, mcol; bam_index_t *idx; bam_lplbuf_t *lplbuf; bam_header_t *header; bamFile fp; int curr_tid, left_pos; faidx_t *fai; bcf_callaux_t *bca; int ccol, last_pos, row_shift, base_for, color_for, is_dot, l_ref, ins, no_skip, show_name; char *ref; khash_t(kh_rg) *rg_hash; /* callbacks */ void (*my_destroy)(struct AbstractTview* ); void (*my_mvprintw)(struct AbstractTview* ,int,int,const char*,...); void (*my_mvaddch)(struct AbstractTview*,int,int,int); void (*my_attron)(struct AbstractTview*,int); void (*my_attroff)(struct AbstractTview*,int); void (*my_clear)(struct AbstractTview*); int (*my_colorpair)(struct AbstractTview*,int); int (*my_drawaln)(struct AbstractTview*,int,int); int (*my_loop)(struct AbstractTview*); int (*my_underline)(struct AbstractTview*); } tview_t; char bam_aux_getCEi(bam1_t *b, int i); char bam_aux_getCSi(bam1_t *b, int i); char bam_aux_getCQi(bam1_t *b, int i); #define TV_MIN_ALNROW 2 #define TV_MAX_GOTO 40 #define TV_LOW_MAPQ 10 #define TV_COLOR_MAPQ 0 #define TV_COLOR_BASEQ 1 #define TV_COLOR_NUCL 2 #define TV_COLOR_COL 3 #define TV_COLOR_COLQ 4 #define TV_BASE_NUCL 0 #define TV_BASE_COLOR_SPACE 1 int tv_pl_func(uint32_t tid, uint32_t pos, int n, const bam_pileup1_t *pl, void *data); int base_tv_init(tview_t*,const char *fn, const char *fn_fa, const char *samples); void base_tv_destroy(tview_t*); int base_draw_aln(tview_t *tv, int tid, int pos); typedef struct Tixel { int ch; int attributes; }tixel_t; #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/razip.c
.c
4,110
142
#include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include "razf.h" #define WINDOW_SIZE 4096 static int razf_main_usage() { printf("\n"); printf("Usage: razip [options] [file] ...\n\n"); printf("Options: -c write on standard output, keep original files unchanged\n"); printf(" -d decompress\n"); printf(" -l list compressed file contents\n"); printf(" -b INT decompress at INT position in the uncompressed file\n"); printf(" -s INT decompress INT bytes in the uncompressed file\n"); printf(" -h give this help\n"); printf("\n"); return 0; } static int write_open(const char *fn, int is_forced) { int fd = -1; char c; if (!is_forced) { if ((fd = open(fn, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0666)) < 0 && errno == EEXIST) { printf("razip: %s already exists; do you wish to overwrite (y or n)? ", fn); scanf("%c", &c); if (c != 'Y' && c != 'y') { printf("razip: not overwritten\n"); exit(1); } } } if (fd < 0) { if ((fd = open(fn, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0) { fprintf(stderr, "razip: %s: Fail to write\n", fn); exit(1); } } return fd; } int main(int argc, char **argv) { int c, compress, pstdout, is_forced; RAZF *rz; void *buffer; long start, end, size; compress = 1; pstdout = 0; start = 0; size = -1; end = -1; is_forced = 0; while((c = getopt(argc, argv, "cdlhfb:s:")) >= 0){ switch(c){ case 'h': return razf_main_usage(); case 'd': compress = 0; break; case 'c': pstdout = 1; break; case 'l': compress = 2; break; case 'b': start = atol(optarg); break; case 's': size = atol(optarg); break; case 'f': is_forced = 1; break; } } if (size >= 0) end = start + size; if(end >= 0 && end < start){ fprintf(stderr, " -- Illegal region: [%ld, %ld] --\n", start, end); return 1; } if(compress == 1){ int f_src, f_dst = -1; if(argc > optind){ if((f_src = open(argv[optind], O_RDONLY)) < 0){ fprintf(stderr, " -- Cannot open file: %s --\n", argv[optind]); return 1; } if(pstdout){ f_dst = fileno(stdout); } else { char *name = malloc(sizeof(strlen(argv[optind]) + 5)); strcpy(name, argv[optind]); strcat(name, ".rz"); f_dst = write_open(name, is_forced); if (f_dst < 0) return 1; free(name); } } else if(pstdout){ f_src = fileno(stdin); f_dst = fileno(stdout); } else return razf_main_usage(); rz = razf_dopen(f_dst, "w"); buffer = malloc(WINDOW_SIZE); while((c = read(f_src, buffer, WINDOW_SIZE)) > 0) razf_write(rz, buffer, c); razf_close(rz); // f_dst will be closed here if (argc > optind && !pstdout) unlink(argv[optind]); free(buffer); close(f_src); return 0; } else { if(argc <= optind) return razf_main_usage(); if(compress == 2){ rz = razf_open(argv[optind], "r"); if(rz->file_type == FILE_TYPE_RZ) { printf("%20s%20s%7s %s\n", "compressed", "uncompressed", "ratio", "name"); printf("%20lld%20lld%6.1f%% %s\n", (long long)rz->end, (long long)rz->src_end, rz->end * 100.0f / rz->src_end, argv[optind]); } else fprintf(stdout, "%s is not a regular rz file\n", argv[optind]); } else { int f_dst; if (argc > optind && !pstdout) { char *name; if (strstr(argv[optind], ".rz") - argv[optind] != strlen(argv[optind]) - 3) { printf("razip: %s: unknown suffix -- ignored\n", argv[optind]); return 1; } name = strdup(argv[optind]); name[strlen(name) - 3] = '\0'; f_dst = write_open(name, is_forced); free(name); } else f_dst = fileno(stdout); rz = razf_open(argv[optind], "r"); buffer = malloc(WINDOW_SIZE); razf_seek(rz, start, SEEK_SET); while(1){ if(end < 0) c = razf_read(rz, buffer, WINDOW_SIZE); else c = razf_read(rz, buffer, (end - start > WINDOW_SIZE)? WINDOW_SIZE:(end - start)); if(c <= 0) break; start += c; write(f_dst, buffer, c); if(end >= 0 && start >= end) break; } free(buffer); if (!pstdout) unlink(argv[optind]); } razf_close(rz); return 0; } }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam.h
.h
25,785
794
/* The MIT License Copyright (c) 2008-2010 Genome Research Ltd (GRL). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Contact: Heng Li <lh3@sanger.ac.uk> */ #ifndef BAM_BAM_H #define BAM_BAM_H /*! @header BAM library provides I/O and various operations on manipulating files in the BAM (Binary Alignment/Mapping) or SAM (Sequence Alignment/Map) format. It now supports importing from or exporting to SAM, sorting, merging, generating pileup, and quickly retrieval of reads overlapped with a specified region. @copyright Genome Research Ltd. */ #define BAM_VERSION "0.1.19-44428cd" #include <stdint.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #ifndef BAM_LITE #define BAM_VIRTUAL_OFFSET16 #include "bgzf.h" /*! @abstract BAM file handler */ typedef BGZF *bamFile; #define bam_open(fn, mode) bgzf_open(fn, mode) #define bam_dopen(fd, mode) bgzf_fdopen(fd, mode) #define bam_close(fp) bgzf_close(fp) #define bam_read(fp, buf, size) bgzf_read(fp, buf, size) #define bam_write(fp, buf, size) bgzf_write(fp, buf, size) #define bam_tell(fp) bgzf_tell(fp) #define bam_seek(fp, pos, dir) bgzf_seek(fp, pos, dir) #else #define BAM_TRUE_OFFSET #include <zlib.h> typedef gzFile bamFile; #define bam_open(fn, mode) gzopen(fn, mode) #define bam_dopen(fd, mode) gzdopen(fd, mode) #define bam_close(fp) gzclose(fp) #define bam_read(fp, buf, size) gzread(fp, buf, size) /* no bam_write/bam_tell/bam_seek() here */ #endif /*! @typedef @abstract Structure for the alignment header. @field n_targets number of reference sequences @field target_name names of the reference sequences @field target_len lengths of the referene sequences @field dict header dictionary @field hash hash table for fast name lookup @field rg2lib hash table for @RG-ID -> LB lookup @field l_text length of the plain text in the header @field text plain text @discussion Field hash points to null by default. It is a private member. */ typedef struct { int32_t n_targets; char **target_name; uint32_t *target_len; void *dict, *hash, *rg2lib; uint32_t l_text, n_text; char *text; } bam_header_t; /*! @abstract the read is paired in sequencing, no matter whether it is mapped in a pair */ #define BAM_FPAIRED 1 /*! @abstract the read is mapped in a proper pair */ #define BAM_FPROPER_PAIR 2 /*! @abstract the read itself is unmapped; conflictive with BAM_FPROPER_PAIR */ #define BAM_FUNMAP 4 /*! @abstract the mate is unmapped */ #define BAM_FMUNMAP 8 /*! @abstract the read is mapped to the reverse strand */ #define BAM_FREVERSE 16 /*! @abstract the mate is mapped to the reverse strand */ #define BAM_FMREVERSE 32 /*! @abstract this is read1 */ #define BAM_FREAD1 64 /*! @abstract this is read2 */ #define BAM_FREAD2 128 /*! @abstract not primary alignment */ #define BAM_FSECONDARY 256 /*! @abstract QC failure */ #define BAM_FQCFAIL 512 /*! @abstract optical or PCR duplicate */ #define BAM_FDUP 1024 #define BAM_OFDEC 0 #define BAM_OFHEX 1 #define BAM_OFSTR 2 /*! @abstract defautl mask for pileup */ #define BAM_DEF_MASK (BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP) #define BAM_CORE_SIZE sizeof(bam1_core_t) /** * Describing how CIGAR operation/length is packed in a 32-bit integer. */ #define BAM_CIGAR_SHIFT 4 #define BAM_CIGAR_MASK ((1 << BAM_CIGAR_SHIFT) - 1) /* CIGAR operations. */ /*! @abstract CIGAR: M = match or mismatch*/ #define BAM_CMATCH 0 /*! @abstract CIGAR: I = insertion to the reference */ #define BAM_CINS 1 /*! @abstract CIGAR: D = deletion from the reference */ #define BAM_CDEL 2 /*! @abstract CIGAR: N = skip on the reference (e.g. spliced alignment) */ #define BAM_CREF_SKIP 3 /*! @abstract CIGAR: S = clip on the read with clipped sequence present in qseq */ #define BAM_CSOFT_CLIP 4 /*! @abstract CIGAR: H = clip on the read with clipped sequence trimmed off */ #define BAM_CHARD_CLIP 5 /*! @abstract CIGAR: P = padding */ #define BAM_CPAD 6 /*! @abstract CIGAR: equals = match */ #define BAM_CEQUAL 7 /*! @abstract CIGAR: X = mismatch */ #define BAM_CDIFF 8 #define BAM_CBACK 9 #define BAM_CIGAR_STR "MIDNSHP=XB" #define BAM_CIGAR_TYPE 0x3C1A7 #define bam_cigar_op(c) ((c)&BAM_CIGAR_MASK) #define bam_cigar_oplen(c) ((c)>>BAM_CIGAR_SHIFT) #define bam_cigar_opchr(c) (BAM_CIGAR_STR[bam_cigar_op(c)]) #define bam_cigar_gen(l, o) ((l)<<BAM_CIGAR_SHIFT|(o)) #define bam_cigar_type(o) (BAM_CIGAR_TYPE>>((o)<<1)&3) // bit 1: consume query; bit 2: consume reference /*! @typedef @abstract Structure for core alignment information. @field tid chromosome ID, defined by bam_header_t @field pos 0-based leftmost coordinate @field bin bin calculated by bam_reg2bin() @field qual mapping quality @field l_qname length of the query name @field flag bitwise flag @field n_cigar number of CIGAR operations @field l_qseq length of the query sequence (read) */ typedef struct { int32_t tid; int32_t pos; uint32_t bin:16, qual:8, l_qname:8; uint32_t flag:16, n_cigar:16; int32_t l_qseq; int32_t mtid; int32_t mpos; int32_t isize; } bam1_core_t; /*! @typedef @abstract Structure for one alignment. @field core core information about the alignment @field l_aux length of auxiliary data @field data_len current length of bam1_t::data @field m_data maximum length of bam1_t::data @field data all variable-length data, concatenated; structure: qname-cigar-seq-qual-aux @discussion Notes: 1. qname is zero tailing and core.l_qname includes the tailing '\0'. 2. l_qseq is calculated from the total length of an alignment block on reading or from CIGAR. 3. cigar data is encoded 4 bytes per CIGAR operation. 4. seq is nybble-encoded according to bam_nt16_table. */ typedef struct { bam1_core_t core; int l_aux, data_len, m_data; uint8_t *data; } bam1_t; typedef struct __bam_iter_t *bam_iter_t; #define bam1_strand(b) (((b)->core.flag&BAM_FREVERSE) != 0) #define bam1_mstrand(b) (((b)->core.flag&BAM_FMREVERSE) != 0) /*! @function @abstract Get the CIGAR array @param b pointer to an alignment @return pointer to the CIGAR array @discussion In the CIGAR array, each element is a 32-bit integer. The lower 4 bits gives a CIGAR operation and the higher 28 bits keep the length of a CIGAR. */ #define bam1_cigar(b) ((uint32_t*)((b)->data + (b)->core.l_qname)) /*! @function @abstract Get the name of the query @param b pointer to an alignment @return pointer to the name string, null terminated */ #define bam1_qname(b) ((char*)((b)->data)) /*! @function @abstract Get query sequence @param b pointer to an alignment @return pointer to sequence @discussion Each base is encoded in 4 bits: 1 for A, 2 for C, 4 for G, 8 for T and 15 for N. Two bases are packed in one byte with the base at the higher 4 bits having smaller coordinate on the read. It is recommended to use bam1_seqi() macro to get the base. */ #define bam1_seq(b) ((b)->data + (b)->core.n_cigar*4 + (b)->core.l_qname) /*! @function @abstract Get query quality @param b pointer to an alignment @return pointer to quality string */ #define bam1_qual(b) ((b)->data + (b)->core.n_cigar*4 + (b)->core.l_qname + (((b)->core.l_qseq + 1)>>1)) /*! @function @abstract Get a base on read @param s Query sequence returned by bam1_seq() @param i The i-th position, 0-based @return 4-bit integer representing the base. */ //#define bam1_seqi(s, i) ((s)[(i)/2] >> 4*(1-(i)%2) & 0xf) #define bam1_seqi(s, i) ((s)[(i)>>1] >> ((~(i)&1)<<2) & 0xf) #define bam1_seq_seti(s, i, c) ( (s)[(i)>>1] = ((s)[(i)>>1] & 0xf<<(((i)&1)<<2)) | (c)<<((~(i)&1)<<2) ) /*! @function @abstract Get query sequence and quality @param b pointer to an alignment @return pointer to the concatenated auxiliary data */ #define bam1_aux(b) ((b)->data + (b)->core.n_cigar*4 + (b)->core.l_qname + (b)->core.l_qseq + ((b)->core.l_qseq + 1)/2) #ifndef kroundup32 /*! @function @abstract Round an integer to the next closest power-2 integer. @param x integer to be rounded (in place) @discussion x will be modified. */ #define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x)) #endif /*! @abstract Whether the machine is big-endian; modified only in bam_header_init(). */ extern int bam_is_be; /*! @abstract Verbose level between 0 and 3; 0 is supposed to disable all debugging information, though this may not have been implemented. */ extern int bam_verbose; extern int bam_no_B; /*! @abstract Table for converting a nucleotide character to the 4-bit encoding. */ extern unsigned char bam_nt16_table[256]; /*! @abstract Table for converting a 4-bit encoded nucleotide to a letter. */ extern char *bam_nt16_rev_table; extern char bam_nt16_nt4_table[]; #ifdef __cplusplus extern "C" { #endif /********************* * Low-level SAM I/O * *********************/ /*! @abstract TAM file handler */ typedef struct __tamFile_t *tamFile; /*! @abstract Open a SAM file for reading, either uncompressed or compressed by gzip/zlib. @param fn SAM file name @return SAM file handler */ tamFile sam_open(const char *fn); /*! @abstract Close a SAM file handler @param fp SAM file handler */ void sam_close(tamFile fp); /*! @abstract Read one alignment from a SAM file handler @param fp SAM file handler @param header header information (ordered names of chromosomes) @param b read alignment; all members in b will be updated @return 0 if successful; otherwise negative */ int sam_read1(tamFile fp, bam_header_t *header, bam1_t *b); /*! @abstract Read header information from a TAB-delimited list file. @param fn_list file name for the list @return a pointer to the header structure @discussion Each line in this file consists of chromosome name and the length of chromosome. */ bam_header_t *sam_header_read2(const char *fn_list); /*! @abstract Read header from a SAM file (if present) @param fp SAM file handler @return pointer to header struct; 0 if no @SQ lines available */ bam_header_t *sam_header_read(tamFile fp); /*! @abstract Parse @SQ lines a update a header struct @param h pointer to the header struct to be updated @return number of target sequences @discussion bam_header_t::{n_targets,target_len,target_name} will be destroyed in the first place. */ int sam_header_parse(bam_header_t *h); int32_t bam_get_tid(const bam_header_t *header, const char *seq_name); /*! @abstract Parse @RG lines a update a header struct @param h pointer to the header struct to be updated @return number of @RG lines @discussion bam_header_t::rg2lib will be destroyed in the first place. */ int sam_header_parse_rg(bam_header_t *h); #define sam_write1(header, b) bam_view1(header, b) /******************************** * APIs for string dictionaries * ********************************/ int bam_strmap_put(void *strmap, const char *rg, const char *lib); const char *bam_strmap_get(const void *strmap, const char *rg); void *bam_strmap_dup(const void*); void *bam_strmap_init(); void bam_strmap_destroy(void *strmap); /********************* * Low-level BAM I/O * *********************/ /*! @abstract Initialize a header structure. @return the pointer to the header structure @discussion This function also modifies the global variable bam_is_be. */ bam_header_t *bam_header_init(); /*! @abstract Destroy a header structure. @param header pointer to the header */ void bam_header_destroy(bam_header_t *header); /*! @abstract Read a header structure from BAM. @param fp BAM file handler, opened by bam_open() @return pointer to the header structure @discussion The file position indicator must be placed at the beginning of the file. Upon success, the position indicator will be set at the start of the first alignment. */ bam_header_t *bam_header_read(bamFile fp); /*! @abstract Write a header structure to BAM. @param fp BAM file handler @param header pointer to the header structure @return always 0 currently */ int bam_header_write(bamFile fp, const bam_header_t *header); /*! @abstract Read an alignment from BAM. @param fp BAM file handler @param b read alignment; all members are updated. @return number of bytes read from the file @discussion The file position indicator must be placed right before an alignment. Upon success, this function will set the position indicator to the start of the next alignment. This function is not affected by the machine endianness. */ int bam_read1(bamFile fp, bam1_t *b); int bam_remove_B(bam1_t *b); /*! @abstract Write an alignment to BAM. @param fp BAM file handler @param c pointer to the bam1_core_t structure @param data_len total length of variable size data related to the alignment @param data pointer to the concatenated data @return number of bytes written to the file @discussion This function is not affected by the machine endianness. */ int bam_write1_core(bamFile fp, const bam1_core_t *c, int data_len, uint8_t *data); /*! @abstract Write an alignment to BAM. @param fp BAM file handler @param b alignment to write @return number of bytes written to the file @abstract It is equivalent to: bam_write1_core(fp, &b->core, b->data_len, b->data) */ int bam_write1(bamFile fp, const bam1_t *b); /*! @function @abstract Initiate a pointer to bam1_t struct */ #define bam_init1() ((bam1_t*)calloc(1, sizeof(bam1_t))) /*! @function @abstract Free the memory allocated for an alignment. @param b pointer to an alignment */ #define bam_destroy1(b) do { \ if (b) { free((b)->data); free(b); } \ } while (0) /*! @abstract Format a BAM record in the SAM format @param header pointer to the header structure @param b alignment to print @return a pointer to the SAM string */ char *bam_format1(const bam_header_t *header, const bam1_t *b); char *bam_format1_core(const bam_header_t *header, const bam1_t *b, int of); /*! @abstract Check whether a BAM record is plausibly valid @param header associated header structure, or NULL if unavailable @param b alignment to validate @return 0 if the alignment is invalid; non-zero otherwise @discussion Simple consistency check of some of the fields of the alignment record. If the header is provided, several additional checks are made. Not all fields are checked, so a non-zero result is not a guarantee that the record is valid. However it is usually good enough to detect when bam_seek() has been called with a virtual file offset that is not the offset of an alignment record. */ int bam_validate1(const bam_header_t *header, const bam1_t *b); const char *bam_get_library(bam_header_t *header, const bam1_t *b); /*************** * pileup APIs * ***************/ /*! @typedef @abstract Structure for one alignment covering the pileup position. @field b pointer to the alignment @field qpos position of the read base at the pileup site, 0-based @field indel indel length; 0 for no indel, positive for ins and negative for del @field is_del 1 iff the base on the padded read is a deletion @field level the level of the read in the "viewer" mode @discussion See also bam_plbuf_push() and bam_lplbuf_push(). The difference between the two functions is that the former does not set bam_pileup1_t::level, while the later does. Level helps the implementation of alignment viewers, but calculating this has some overhead. */ typedef struct { bam1_t *b; int32_t qpos; int indel, level; uint32_t is_del:1, is_head:1, is_tail:1, is_refskip:1, aux:28; } bam_pileup1_t; typedef int (*bam_plp_auto_f)(void *data, bam1_t *b); struct __bam_plp_t; typedef struct __bam_plp_t *bam_plp_t; bam_plp_t bam_plp_init(bam_plp_auto_f func, void *data); int bam_plp_push(bam_plp_t iter, const bam1_t *b); const bam_pileup1_t *bam_plp_next(bam_plp_t iter, int *_tid, int *_pos, int *_n_plp); const bam_pileup1_t *bam_plp_auto(bam_plp_t iter, int *_tid, int *_pos, int *_n_plp); void bam_plp_set_mask(bam_plp_t iter, int mask); void bam_plp_set_maxcnt(bam_plp_t iter, int maxcnt); void bam_plp_reset(bam_plp_t iter); void bam_plp_destroy(bam_plp_t iter); struct __bam_mplp_t; typedef struct __bam_mplp_t *bam_mplp_t; bam_mplp_t bam_mplp_init(int n, bam_plp_auto_f func, void **data); void bam_mplp_destroy(bam_mplp_t iter); void bam_mplp_set_maxcnt(bam_mplp_t iter, int maxcnt); int bam_mplp_auto(bam_mplp_t iter, int *_tid, int *_pos, int *n_plp, const bam_pileup1_t **plp); /*! @typedef @abstract Type of function to be called by bam_plbuf_push(). @param tid chromosome ID as is defined in the header @param pos start coordinate of the alignment, 0-based @param n number of elements in pl array @param pl array of alignments @param data user provided data @discussion See also bam_plbuf_push(), bam_plbuf_init() and bam_pileup1_t. */ typedef int (*bam_pileup_f)(uint32_t tid, uint32_t pos, int n, const bam_pileup1_t *pl, void *data); typedef struct { bam_plp_t iter; bam_pileup_f func; void *data; } bam_plbuf_t; void bam_plbuf_set_mask(bam_plbuf_t *buf, int mask); void bam_plbuf_reset(bam_plbuf_t *buf); bam_plbuf_t *bam_plbuf_init(bam_pileup_f func, void *data); void bam_plbuf_destroy(bam_plbuf_t *buf); int bam_plbuf_push(const bam1_t *b, bam_plbuf_t *buf); int bam_pileup_file(bamFile fp, int mask, bam_pileup_f func, void *func_data); struct __bam_lplbuf_t; typedef struct __bam_lplbuf_t bam_lplbuf_t; void bam_lplbuf_reset(bam_lplbuf_t *buf); /*! @abstract bam_plbuf_init() equivalent with level calculated. */ bam_lplbuf_t *bam_lplbuf_init(bam_pileup_f func, void *data); /*! @abstract bam_plbuf_destroy() equivalent with level calculated. */ void bam_lplbuf_destroy(bam_lplbuf_t *tv); /*! @abstract bam_plbuf_push() equivalent with level calculated. */ int bam_lplbuf_push(const bam1_t *b, bam_lplbuf_t *buf); /********************* * BAM indexing APIs * *********************/ struct __bam_index_t; typedef struct __bam_index_t bam_index_t; /*! @abstract Build index for a BAM file. @discussion Index file "fn.bai" will be created. @param fn name of the BAM file @return always 0 currently */ int bam_index_build(const char *fn); /*! @abstract Load index from file "fn.bai". @param fn name of the BAM file (NOT the index file) @return pointer to the index structure */ bam_index_t *bam_index_load(const char *fn); /*! @abstract Destroy an index structure. @param idx pointer to the index structure */ void bam_index_destroy(bam_index_t *idx); /*! @typedef @abstract Type of function to be called by bam_fetch(). @param b the alignment @param data user provided data */ typedef int (*bam_fetch_f)(const bam1_t *b, void *data); /*! @abstract Retrieve the alignments that are overlapped with the specified region. @discussion A user defined function will be called for each retrieved alignment ordered by its start position. @param fp BAM file handler @param idx pointer to the alignment index @param tid chromosome ID as is defined in the header @param beg start coordinate, 0-based @param end end coordinate, 0-based @param data user provided data (will be transferred to func) @param func user defined function */ int bam_fetch(bamFile fp, const bam_index_t *idx, int tid, int beg, int end, void *data, bam_fetch_f func); bam_iter_t bam_iter_query(const bam_index_t *idx, int tid, int beg, int end); int bam_iter_read(bamFile fp, bam_iter_t iter, bam1_t *b); void bam_iter_destroy(bam_iter_t iter); /*! @abstract Parse a region in the format: "chr2:100,000-200,000". @discussion bam_header_t::hash will be initialized if empty. @param header pointer to the header structure @param str string to be parsed @param ref_id the returned chromosome ID @param begin the returned start coordinate @param end the returned end coordinate @return 0 on success; -1 on failure */ int bam_parse_region(bam_header_t *header, const char *str, int *ref_id, int *begin, int *end); /************************** * APIs for optional tags * **************************/ /*! @abstract Retrieve data of a tag @param b pointer to an alignment struct @param tag two-character tag to be retrieved @return pointer to the type and data. The first character is the type that can be 'iIsScCdfAZH'. @discussion Use bam_aux2?() series to convert the returned data to the corresponding type. */ uint8_t *bam_aux_get(const bam1_t *b, const char tag[2]); int32_t bam_aux2i(const uint8_t *s); float bam_aux2f(const uint8_t *s); double bam_aux2d(const uint8_t *s); char bam_aux2A(const uint8_t *s); char *bam_aux2Z(const uint8_t *s); int bam_aux_del(bam1_t *b, uint8_t *s); void bam_aux_append(bam1_t *b, const char tag[2], char type, int len, uint8_t *data); uint8_t *bam_aux_get_core(bam1_t *b, const char tag[2]); // an alias of bam_aux_get() /***************** * Miscellaneous * *****************/ /*! @abstract Calculate the rightmost coordinate of an alignment on the reference genome. @param c pointer to the bam1_core_t structure @param cigar the corresponding CIGAR array (from bam1_t::cigar) @return the rightmost coordinate, 0-based */ uint32_t bam_calend(const bam1_core_t *c, const uint32_t *cigar); /*! @abstract Calculate the length of the query sequence from CIGAR. @param c pointer to the bam1_core_t structure @param cigar the corresponding CIGAR array (from bam1_t::cigar) @return length of the query sequence */ int32_t bam_cigar2qlen(const bam1_core_t *c, const uint32_t *cigar); #ifdef __cplusplus } #endif /*! @abstract Calculate the minimum bin that contains a region [beg,end). @param beg start of the region, 0-based @param end end of the region, 0-based @return bin */ static inline int bam_reg2bin(uint32_t beg, uint32_t end) { --end; if (beg>>14 == end>>14) return 4681 + (beg>>14); if (beg>>17 == end>>17) return 585 + (beg>>17); if (beg>>20 == end>>20) return 73 + (beg>>20); if (beg>>23 == end>>23) return 9 + (beg>>23); if (beg>>26 == end>>26) return 1 + (beg>>26); return 0; } /*! @abstract Copy an alignment @param bdst destination alignment struct @param bsrc source alignment struct @return pointer to the destination alignment struct */ static inline bam1_t *bam_copy1(bam1_t *bdst, const bam1_t *bsrc) { uint8_t *data = bdst->data; int m_data = bdst->m_data; // backup data and m_data if (m_data < bsrc->data_len) { // double the capacity m_data = bsrc->data_len; kroundup32(m_data); data = (uint8_t*)realloc(data, m_data); } memcpy(data, bsrc->data, bsrc->data_len); // copy var-len data *bdst = *bsrc; // copy the rest // restore the backup bdst->m_data = m_data; bdst->data = data; return bdst; } /*! @abstract Duplicate an alignment @param src source alignment struct @return pointer to the destination alignment struct */ static inline bam1_t *bam_dup1(const bam1_t *src) { bam1_t *b; b = bam_init1(); *b = *src; b->m_data = b->data_len; b->data = (uint8_t*)calloc(b->data_len, 1); memcpy(b->data, src->data, b->data_len); return b; } static inline int bam_aux_type2size(int x) { if (x == 'C' || x == 'c' || x == 'A') return 1; else if (x == 'S' || x == 's') return 2; else if (x == 'I' || x == 'i' || x == 'f' || x == 'F') return 4; else return 0; } /********************************* *** Compatibility with htslib *** *********************************/ typedef bam_header_t bam_hdr_t; #define bam_get_qname(b) bam1_qname(b) #define bam_get_cigar(b) bam1_cigar(b) #define bam_hdr_read(fp) bam_header_read(fp) #define bam_hdr_write(fp, h) bam_header_write(fp, h) #define bam_hdr_destroy(fp) bam_header_destroy(fp) #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_mate.c
.c
4,553
129
#include <stdlib.h> #include <string.h> #include <unistd.h> #include "kstring.h" #include "bam.h" void bam_template_cigar(bam1_t *b1, bam1_t *b2, kstring_t *str) { bam1_t *swap; int i, end; uint32_t *cigar; str->l = 0; if (b1->core.tid != b2->core.tid || b1->core.tid < 0) return; // coordinateless or not on the same chr; skip if (b1->core.pos > b2->core.pos) swap = b1, b1 = b2, b2 = swap; // make sure b1 has a smaller coordinate kputc((b1->core.flag & BAM_FREAD1)? '1' : '2', str); // segment index kputc((b1->core.flag & BAM_FREVERSE)? 'R' : 'F', str); // strand for (i = 0, cigar = bam1_cigar(b1); i < b1->core.n_cigar; ++i) { kputw(bam_cigar_oplen(cigar[i]), str); kputc(bam_cigar_opchr(cigar[i]), str); } end = bam_calend(&b1->core, cigar); kputw(b2->core.pos - end, str); kputc('T', str); kputc((b2->core.flag & BAM_FREAD1)? '1' : '2', str); // segment index kputc((b2->core.flag & BAM_FREVERSE)? 'R' : 'F', str); // strand for (i = 0, cigar = bam1_cigar(b2); i < b2->core.n_cigar; ++i) { kputw(bam_cigar_oplen(cigar[i]), str); kputc(bam_cigar_opchr(cigar[i]), str); } bam_aux_append(b1, "CT", 'Z', str->l+1, (uint8_t*)str->s); } // currently, this function ONLY works if each read has one hit void bam_mating_core(bamFile in, bamFile out, int remove_reads) { bam_header_t *header; bam1_t *b[2]; int curr, has_prev, pre_end = 0, cur_end; kstring_t str; str.l = str.m = 0; str.s = 0; header = bam_header_read(in); bam_header_write(out, header); b[0] = bam_init1(); b[1] = bam_init1(); curr = 0; has_prev = 0; while (bam_read1(in, b[curr]) >= 0) { bam1_t *cur = b[curr], *pre = b[1-curr]; if (cur->core.tid < 0) { if ( !remove_reads ) bam_write1(out, cur); continue; } cur_end = bam_calend(&cur->core, bam1_cigar(cur)); if (cur_end > (int)header->target_len[cur->core.tid]) cur->core.flag |= BAM_FUNMAP; if (cur->core.flag & BAM_FSECONDARY) { if ( !remove_reads ) bam_write1(out, cur); continue; // skip secondary alignments } if (has_prev) { if (strcmp(bam1_qname(cur), bam1_qname(pre)) == 0) { // identical pair name cur->core.mtid = pre->core.tid; cur->core.mpos = pre->core.pos; pre->core.mtid = cur->core.tid; pre->core.mpos = cur->core.pos; if (pre->core.tid == cur->core.tid && !(cur->core.flag&(BAM_FUNMAP|BAM_FMUNMAP)) && !(pre->core.flag&(BAM_FUNMAP|BAM_FMUNMAP))) // set TLEN/ISIZE { uint32_t cur5, pre5; cur5 = (cur->core.flag&BAM_FREVERSE)? cur_end : cur->core.pos; pre5 = (pre->core.flag&BAM_FREVERSE)? pre_end : pre->core.pos; cur->core.isize = pre5 - cur5; pre->core.isize = cur5 - pre5; } else cur->core.isize = pre->core.isize = 0; if (pre->core.flag&BAM_FREVERSE) cur->core.flag |= BAM_FMREVERSE; else cur->core.flag &= ~BAM_FMREVERSE; if (cur->core.flag&BAM_FREVERSE) pre->core.flag |= BAM_FMREVERSE; else pre->core.flag &= ~BAM_FMREVERSE; if (cur->core.flag & BAM_FUNMAP) { pre->core.flag |= BAM_FMUNMAP; pre->core.flag &= ~BAM_FPROPER_PAIR; } if (pre->core.flag & BAM_FUNMAP) { cur->core.flag |= BAM_FMUNMAP; cur->core.flag &= ~BAM_FPROPER_PAIR; } bam_template_cigar(pre, cur, &str); bam_write1(out, pre); bam_write1(out, cur); has_prev = 0; } else { // unpaired or singleton pre->core.mtid = -1; pre->core.mpos = -1; pre->core.isize = 0; if (pre->core.flag & BAM_FPAIRED) { pre->core.flag |= BAM_FMUNMAP; pre->core.flag &= ~BAM_FMREVERSE & ~BAM_FPROPER_PAIR; } bam_write1(out, pre); } } else has_prev = 1; curr = 1 - curr; pre_end = cur_end; } if (has_prev) bam_write1(out, b[1-curr]); bam_header_destroy(header); bam_destroy1(b[0]); bam_destroy1(b[1]); free(str.s); } void usage() { fprintf(stderr,"Usage: samtools fixmate <in.nameSrt.bam> <out.nameSrt.bam>\n"); fprintf(stderr,"Options:\n"); fprintf(stderr," -r remove unmapped reads and secondary alignments\n"); exit(1); } int bam_mating(int argc, char *argv[]) { bamFile in, out; int c, remove_reads=0; while ((c = getopt(argc, argv, "r")) >= 0) { switch (c) { case 'r': remove_reads=1; break; } } if (optind+1 >= argc) usage(); in = (strcmp(argv[optind], "-") == 0)? bam_dopen(fileno(stdin), "r") : bam_open(argv[optind], "r"); out = (strcmp(argv[optind+1], "-") == 0)? bam_dopen(fileno(stdout), "w") : bam_open(argv[optind+1], "w"); bam_mating_core(in, out, remove_reads); bam_close(in); bam_close(out); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/razf.c
.c
24,343
854
/* * RAZF : Random Access compressed(Z) File * Version: 1.0 * Release Date: 2008-10-27 * * Copyright 2008, Jue Ruan <ruanjue@gmail.com>, Heng Li <lh3@sanger.ac.uk> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _NO_RAZF #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "razf.h" #if ZLIB_VERNUM < 0x1221 struct _gz_header_s { int text; uLong time; int xflags; int os; Bytef *extra; uInt extra_len; uInt extra_max; Bytef *name; uInt name_max; Bytef *comment; uInt comm_max; int hcrc; int done; }; #warning "zlib < 1.2.2.1; RAZF writing is disabled." #endif #define DEF_MEM_LEVEL 8 static inline uint32_t byte_swap_4(uint32_t v){ v = ((v & 0x0000FFFFU) << 16) | (v >> 16); return ((v & 0x00FF00FFU) << 8) | ((v & 0xFF00FF00U) >> 8); } static inline uint64_t byte_swap_8(uint64_t v){ v = ((v & 0x00000000FFFFFFFFLLU) << 32) | (v >> 32); v = ((v & 0x0000FFFF0000FFFFLLU) << 16) | ((v & 0xFFFF0000FFFF0000LLU) >> 16); return ((v & 0x00FF00FF00FF00FFLLU) << 8) | ((v & 0xFF00FF00FF00FF00LLU) >> 8); } static inline int is_big_endian(){ int x = 0x01; char *c = (char*)&x; return (c[0] != 0x01); } #ifndef _RZ_READONLY static void add_zindex(RAZF *rz, int64_t in, int64_t out){ if(rz->index->size == rz->index->cap){ rz->index->cap = rz->index->cap * 1.5 + 2; rz->index->cell_offsets = realloc(rz->index->cell_offsets, sizeof(int) * rz->index->cap); rz->index->bin_offsets = realloc(rz->index->bin_offsets, sizeof(int64_t) * (rz->index->cap/RZ_BIN_SIZE + 1)); } if(rz->index->size % RZ_BIN_SIZE == 0) rz->index->bin_offsets[rz->index->size / RZ_BIN_SIZE] = out; rz->index->cell_offsets[rz->index->size] = out - rz->index->bin_offsets[rz->index->size / RZ_BIN_SIZE]; rz->index->size ++; } static void save_zindex(RAZF *rz, int fd){ int32_t i, v32; int is_be; is_be = is_big_endian(); if(is_be) write(fd, &rz->index->size, sizeof(int)); else { v32 = byte_swap_4((uint32_t)rz->index->size); write(fd, &v32, sizeof(uint32_t)); } v32 = rz->index->size / RZ_BIN_SIZE + 1; if(!is_be){ for(i=0;i<v32;i++) rz->index->bin_offsets[i] = byte_swap_8((uint64_t)rz->index->bin_offsets[i]); for(i=0;i<rz->index->size;i++) rz->index->cell_offsets[i] = byte_swap_4((uint32_t)rz->index->cell_offsets[i]); } write(fd, rz->index->bin_offsets, sizeof(int64_t) * v32); write(fd, rz->index->cell_offsets, sizeof(int32_t) * rz->index->size); } #endif #ifdef _USE_KNETFILE static void load_zindex(RAZF *rz, knetFile *fp){ #else static void load_zindex(RAZF *rz, int fd){ #endif int32_t i, v32; int is_be; if(!rz->load_index) return; if(rz->index == NULL) rz->index = malloc(sizeof(ZBlockIndex)); is_be = is_big_endian(); #ifdef _USE_KNETFILE knet_read(fp, &rz->index->size, sizeof(int)); #else read(fd, &rz->index->size, sizeof(int)); #endif if(!is_be) rz->index->size = byte_swap_4((uint32_t)rz->index->size); rz->index->cap = rz->index->size; v32 = rz->index->size / RZ_BIN_SIZE + 1; rz->index->bin_offsets = malloc(sizeof(int64_t) * v32); #ifdef _USE_KNETFILE knet_read(fp, rz->index->bin_offsets, sizeof(int64_t) * v32); #else read(fd, rz->index->bin_offsets, sizeof(int64_t) * v32); #endif rz->index->cell_offsets = malloc(sizeof(int) * rz->index->size); #ifdef _USE_KNETFILE knet_read(fp, rz->index->cell_offsets, sizeof(int) * rz->index->size); #else read(fd, rz->index->cell_offsets, sizeof(int) * rz->index->size); #endif if(!is_be){ for(i=0;i<v32;i++) rz->index->bin_offsets[i] = byte_swap_8((uint64_t)rz->index->bin_offsets[i]); for(i=0;i<rz->index->size;i++) rz->index->cell_offsets[i] = byte_swap_4((uint32_t)rz->index->cell_offsets[i]); } } #ifdef _RZ_READONLY static RAZF* razf_open_w(int fd) { fprintf(stderr, "[razf_open_w] Writing is not available with zlib ver < 1.2.2.1\n"); return 0; } #else static RAZF* razf_open_w(int fd){ RAZF *rz; #ifdef _WIN32 setmode(fd, O_BINARY); #endif rz = calloc(1, sizeof(RAZF)); rz->mode = 'w'; #ifdef _USE_KNETFILE rz->x.fpw = fd; #else rz->filedes = fd; #endif rz->stream = calloc(sizeof(z_stream), 1); rz->inbuf = malloc(RZ_BUFFER_SIZE); rz->outbuf = malloc(RZ_BUFFER_SIZE); rz->index = calloc(sizeof(ZBlockIndex), 1); deflateInit2(rz->stream, RZ_COMPRESS_LEVEL, Z_DEFLATED, WINDOW_BITS + 16, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); rz->stream->avail_out = RZ_BUFFER_SIZE; rz->stream->next_out = rz->outbuf; rz->header = calloc(sizeof(gz_header), 1); rz->header->os = 0x03; //Unix rz->header->text = 0; rz->header->time = 0; rz->header->extra = malloc(7); strncpy((char*)rz->header->extra, "RAZF", 4); rz->header->extra[4] = 1; // obsolete field // block size = RZ_BLOCK_SIZE, Big-Endian rz->header->extra[5] = RZ_BLOCK_SIZE >> 8; rz->header->extra[6] = RZ_BLOCK_SIZE & 0xFF; rz->header->extra_len = 7; rz->header->name = rz->header->comment = 0; rz->header->hcrc = 0; deflateSetHeader(rz->stream, rz->header); rz->block_pos = rz->block_off = 0; return rz; } static void _razf_write(RAZF* rz, const void *data, int size){ int tout; rz->stream->avail_in = size; rz->stream->next_in = (void*)data; while(1){ tout = rz->stream->avail_out; deflate(rz->stream, Z_NO_FLUSH); rz->out += tout - rz->stream->avail_out; if(rz->stream->avail_out) break; #ifdef _USE_KNETFILE write(rz->x.fpw, rz->outbuf, RZ_BUFFER_SIZE - rz->stream->avail_out); #else write(rz->filedes, rz->outbuf, RZ_BUFFER_SIZE - rz->stream->avail_out); #endif rz->stream->avail_out = RZ_BUFFER_SIZE; rz->stream->next_out = rz->outbuf; if(rz->stream->avail_in == 0) break; }; rz->in += size - rz->stream->avail_in; rz->block_off += size - rz->stream->avail_in; } static void razf_flush(RAZF *rz){ uint32_t tout; if(rz->buf_len){ _razf_write(rz, rz->inbuf, rz->buf_len); rz->buf_off = rz->buf_len = 0; } if(rz->stream->avail_out){ #ifdef _USE_KNETFILE write(rz->x.fpw, rz->outbuf, RZ_BUFFER_SIZE - rz->stream->avail_out); #else write(rz->filedes, rz->outbuf, RZ_BUFFER_SIZE - rz->stream->avail_out); #endif rz->stream->avail_out = RZ_BUFFER_SIZE; rz->stream->next_out = rz->outbuf; } while(1){ tout = rz->stream->avail_out; deflate(rz->stream, Z_FULL_FLUSH); rz->out += tout - rz->stream->avail_out; if(rz->stream->avail_out == 0){ #ifdef _USE_KNETFILE write(rz->x.fpw, rz->outbuf, RZ_BUFFER_SIZE - rz->stream->avail_out); #else write(rz->filedes, rz->outbuf, RZ_BUFFER_SIZE - rz->stream->avail_out); #endif rz->stream->avail_out = RZ_BUFFER_SIZE; rz->stream->next_out = rz->outbuf; } else break; } rz->block_pos = rz->out; rz->block_off = 0; } static void razf_end_flush(RAZF *rz){ uint32_t tout; if(rz->buf_len){ _razf_write(rz, rz->inbuf, rz->buf_len); rz->buf_off = rz->buf_len = 0; } while(1){ tout = rz->stream->avail_out; deflate(rz->stream, Z_FINISH); rz->out += tout - rz->stream->avail_out; if(rz->stream->avail_out < RZ_BUFFER_SIZE){ #ifdef _USE_KNETFILE write(rz->x.fpw, rz->outbuf, RZ_BUFFER_SIZE - rz->stream->avail_out); #else write(rz->filedes, rz->outbuf, RZ_BUFFER_SIZE - rz->stream->avail_out); #endif rz->stream->avail_out = RZ_BUFFER_SIZE; rz->stream->next_out = rz->outbuf; } else break; } } static void _razf_buffered_write(RAZF *rz, const void *data, int size){ int i, n; while(1){ if(rz->buf_len == RZ_BUFFER_SIZE){ _razf_write(rz, rz->inbuf, rz->buf_len); rz->buf_len = 0; } if(size + rz->buf_len < RZ_BUFFER_SIZE){ for(i=0;i<size;i++) ((char*)rz->inbuf + rz->buf_len)[i] = ((char*)data)[i]; rz->buf_len += size; return; } else { n = RZ_BUFFER_SIZE - rz->buf_len; for(i=0;i<n;i++) ((char*)rz->inbuf + rz->buf_len)[i] = ((char*)data)[i]; size -= n; data += n; rz->buf_len += n; } } } int razf_write(RAZF* rz, const void *data, int size){ int ori_size, n; int64_t next_block; ori_size = size; next_block = ((rz->in / RZ_BLOCK_SIZE) + 1) * RZ_BLOCK_SIZE; while(rz->in + rz->buf_len + size >= next_block){ n = next_block - rz->in - rz->buf_len; _razf_buffered_write(rz, data, n); data += n; size -= n; razf_flush(rz); add_zindex(rz, rz->in, rz->out); next_block = ((rz->in / RZ_BLOCK_SIZE) + 1) * RZ_BLOCK_SIZE; } _razf_buffered_write(rz, data, size); return ori_size; } #endif /* gzip flag byte */ #define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */ #define HEAD_CRC 0x02 /* bit 1 set: header CRC present */ #define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ #define ORIG_NAME 0x08 /* bit 3 set: original file name present */ #define COMMENT 0x10 /* bit 4 set: file comment present */ #define RESERVED 0xE0 /* bits 5..7: reserved */ static int _read_gz_header(unsigned char *data, int size, int *extra_off, int *extra_len){ int method, flags, n, len; if(size < 2) return 0; if(data[0] != 0x1f || data[1] != 0x8b) return 0; if(size < 4) return 0; method = data[2]; flags = data[3]; if(method != Z_DEFLATED || (flags & RESERVED)) return 0; n = 4 + 6; // Skip 6 bytes *extra_off = n + 2; *extra_len = 0; if(flags & EXTRA_FIELD){ if(size < n + 2) return 0; len = ((int)data[n + 1] << 8) | data[n]; n += 2; *extra_off = n; while(len){ if(n >= size) return 0; n ++; len --; } *extra_len = n - (*extra_off); } if(flags & ORIG_NAME) while(n < size && data[n++]); if(flags & COMMENT) while(n < size && data[n++]); if(flags & HEAD_CRC){ if(n + 2 > size) return 0; n += 2; } return n; } #ifdef _USE_KNETFILE static RAZF* razf_open_r(knetFile *fp, int _load_index){ #else static RAZF* razf_open_r(int fd, int _load_index){ #endif RAZF *rz; int ext_off, ext_len; int n, is_be, ret; int64_t end; unsigned char c[] = "RAZF"; rz = calloc(1, sizeof(RAZF)); rz->mode = 'r'; #ifdef _USE_KNETFILE rz->x.fpr = fp; #else #ifdef _WIN32 setmode(fd, O_BINARY); #endif rz->filedes = fd; #endif rz->stream = calloc(sizeof(z_stream), 1); rz->inbuf = malloc(RZ_BUFFER_SIZE); rz->outbuf = malloc(RZ_BUFFER_SIZE); rz->end = rz->src_end = 0x7FFFFFFFFFFFFFFFLL; #ifdef _USE_KNETFILE n = knet_read(rz->x.fpr, rz->inbuf, RZ_BUFFER_SIZE); #else n = read(rz->filedes, rz->inbuf, RZ_BUFFER_SIZE); #endif ret = _read_gz_header(rz->inbuf, n, &ext_off, &ext_len); if(ret == 0){ PLAIN_FILE: rz->in = n; rz->file_type = FILE_TYPE_PLAIN; memcpy(rz->outbuf, rz->inbuf, n); rz->buf_len = n; free(rz->stream); rz->stream = NULL; return rz; } rz->header_size = ret; ret = inflateInit2(rz->stream, -WINDOW_BITS); if(ret != Z_OK){ inflateEnd(rz->stream); goto PLAIN_FILE;} rz->stream->avail_in = n - rz->header_size; rz->stream->next_in = rz->inbuf + rz->header_size; rz->stream->avail_out = RZ_BUFFER_SIZE; rz->stream->next_out = rz->outbuf; rz->file_type = FILE_TYPE_GZ; rz->in = rz->header_size; rz->block_pos = rz->header_size; rz->next_block_pos = rz->header_size; rz->block_off = 0; if(ext_len < 7 || memcmp(rz->inbuf + ext_off, c, 4) != 0) return rz; if(((((unsigned char*)rz->inbuf)[ext_off + 5] << 8) | ((unsigned char*)rz->inbuf)[ext_off + 6]) != RZ_BLOCK_SIZE){ fprintf(stderr, " -- WARNING: RZ_BLOCK_SIZE is not %d, treat source as gz file. in %s -- %s:%d --\n", RZ_BLOCK_SIZE, __FUNCTION__, __FILE__, __LINE__); return rz; } rz->load_index = _load_index; rz->file_type = FILE_TYPE_RZ; #ifdef _USE_KNETFILE if(knet_seek(fp, -16, SEEK_END) == -1){ #else if(lseek(fd, -16, SEEK_END) == -1){ #endif UNSEEKABLE: rz->seekable = 0; rz->index = NULL; rz->src_end = rz->end = 0x7FFFFFFFFFFFFFFFLL; } else { is_be = is_big_endian(); rz->seekable = 1; #ifdef _USE_KNETFILE knet_read(fp, &end, sizeof(int64_t)); #else read(fd, &end, sizeof(int64_t)); #endif if(!is_be) rz->src_end = (int64_t)byte_swap_8((uint64_t)end); else rz->src_end = end; #ifdef _USE_KNETFILE knet_read(fp, &end, sizeof(int64_t)); #else read(fd, &end, sizeof(int64_t)); #endif if(!is_be) rz->end = (int64_t)byte_swap_8((uint64_t)end); else rz->end = end; if(n > rz->end){ rz->stream->avail_in -= n - rz->end; n = rz->end; } if(rz->end > rz->src_end){ #ifdef _USE_KNETFILE knet_seek(fp, rz->in, SEEK_SET); #else lseek(fd, rz->in, SEEK_SET); #endif goto UNSEEKABLE; } #ifdef _USE_KNETFILE knet_seek(fp, rz->end, SEEK_SET); if(knet_tell(fp) != rz->end){ knet_seek(fp, rz->in, SEEK_SET); #else if(lseek(fd, rz->end, SEEK_SET) != rz->end){ lseek(fd, rz->in, SEEK_SET); #endif goto UNSEEKABLE; } #ifdef _USE_KNETFILE load_zindex(rz, fp); knet_seek(fp, n, SEEK_SET); #else load_zindex(rz, fd); lseek(fd, n, SEEK_SET); #endif } return rz; } #ifdef _USE_KNETFILE RAZF* razf_dopen(int fd, const char *mode){ if (strstr(mode, "r")) fprintf(stderr,"[razf_dopen] implement me\n"); else if(strstr(mode, "w")) return razf_open_w(fd); return NULL; } RAZF* razf_dopen2(int fd, const char *mode) { fprintf(stderr,"[razf_dopen2] implement me\n"); return NULL; } #else RAZF* razf_dopen(int fd, const char *mode){ if(strstr(mode, "r")) return razf_open_r(fd, 1); else if(strstr(mode, "w")) return razf_open_w(fd); else return NULL; } RAZF* razf_dopen2(int fd, const char *mode) { if(strstr(mode, "r")) return razf_open_r(fd, 0); else if(strstr(mode, "w")) return razf_open_w(fd); else return NULL; } #endif static inline RAZF* _razf_open(const char *filename, const char *mode, int _load_index){ int fd; RAZF *rz; if(strstr(mode, "r")){ #ifdef _USE_KNETFILE knetFile *fd = knet_open(filename, "r"); if (fd == 0) { fprintf(stderr, "[_razf_open] fail to open %s\n", filename); return NULL; } #else #ifdef _WIN32 fd = open(filename, O_RDONLY | O_BINARY); #else fd = open(filename, O_RDONLY); #endif #endif if(fd < 0) return NULL; rz = razf_open_r(fd, _load_index); } else if(strstr(mode, "w")){ #ifdef _WIN32 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666); #else fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666); #endif if(fd < 0) return NULL; rz = razf_open_w(fd); } else return NULL; return rz; } RAZF* razf_open(const char *filename, const char *mode){ return _razf_open(filename, mode, 1); } RAZF* razf_open2(const char *filename, const char *mode){ return _razf_open(filename, mode, 0); } int razf_get_data_size(RAZF *rz, int64_t *u_size, int64_t *c_size){ int64_t n; if(rz->mode != 'r' && rz->mode != 'R') return 0; switch(rz->file_type){ case FILE_TYPE_PLAIN: if(rz->end == 0x7fffffffffffffffLL){ #ifdef _USE_KNETFILE if(knet_seek(rz->x.fpr, 0, SEEK_CUR) == -1) return 0; n = knet_tell(rz->x.fpr); knet_seek(rz->x.fpr, 0, SEEK_END); rz->end = knet_tell(rz->x.fpr); knet_seek(rz->x.fpr, n, SEEK_SET); #else if((n = lseek(rz->filedes, 0, SEEK_CUR)) == -1) return 0; rz->end = lseek(rz->filedes, 0, SEEK_END); lseek(rz->filedes, n, SEEK_SET); #endif } *u_size = *c_size = rz->end; return 1; case FILE_TYPE_GZ: return 0; case FILE_TYPE_RZ: if(rz->src_end == rz->end) return 0; *u_size = rz->src_end; *c_size = rz->end; return 1; default: return 0; } } static int _razf_read(RAZF* rz, void *data, int size){ int ret, tin; if(rz->z_eof || rz->z_err) return 0; if (rz->file_type == FILE_TYPE_PLAIN) { #ifdef _USE_KNETFILE ret = knet_read(rz->x.fpr, data, size); #else ret = read(rz->filedes, data, size); #endif if (ret == 0) rz->z_eof = 1; return ret; } rz->stream->avail_out = size; rz->stream->next_out = data; while(rz->stream->avail_out){ if(rz->stream->avail_in == 0){ if(rz->in >= rz->end){ rz->z_eof = 1; break; } if(rz->end - rz->in < RZ_BUFFER_SIZE){ #ifdef _USE_KNETFILE rz->stream->avail_in = knet_read(rz->x.fpr, rz->inbuf, rz->end -rz->in); #else rz->stream->avail_in = read(rz->filedes, rz->inbuf, rz->end -rz->in); #endif } else { #ifdef _USE_KNETFILE rz->stream->avail_in = knet_read(rz->x.fpr, rz->inbuf, RZ_BUFFER_SIZE); #else rz->stream->avail_in = read(rz->filedes, rz->inbuf, RZ_BUFFER_SIZE); #endif } if(rz->stream->avail_in == 0){ rz->z_eof = 1; break; } rz->stream->next_in = rz->inbuf; } tin = rz->stream->avail_in; ret = inflate(rz->stream, Z_BLOCK); rz->in += tin - rz->stream->avail_in; if(ret == Z_NEED_DICT || ret == Z_MEM_ERROR || ret == Z_DATA_ERROR){ fprintf(stderr, "[_razf_read] inflate error: %d %s (at %s:%d)\n", ret, rz->stream->msg ? rz->stream->msg : "", __FILE__, __LINE__); rz->z_err = 1; break; } if(ret == Z_STREAM_END){ rz->z_eof = 1; break; } if ((rz->stream->data_type&128) && !(rz->stream->data_type&64)){ rz->buf_flush = 1; rz->next_block_pos = rz->in; break; } } return size - rz->stream->avail_out; } int razf_read(RAZF *rz, void *data, int size){ int ori_size, i; ori_size = size; while(size > 0){ if(rz->buf_len){ if(size < rz->buf_len){ for(i=0;i<size;i++) ((char*)data)[i] = ((char*)rz->outbuf + rz->buf_off)[i]; rz->buf_off += size; rz->buf_len -= size; data += size; rz->block_off += size; size = 0; break; } else { for(i=0;i<rz->buf_len;i++) ((char*)data)[i] = ((char*)rz->outbuf + rz->buf_off)[i]; data += rz->buf_len; size -= rz->buf_len; rz->block_off += rz->buf_len; rz->buf_off = 0; rz->buf_len = 0; if(rz->buf_flush){ rz->block_pos = rz->next_block_pos; rz->block_off = 0; rz->buf_flush = 0; } } } else if(rz->buf_flush){ rz->block_pos = rz->next_block_pos; rz->block_off = 0; rz->buf_flush = 0; } if(rz->buf_flush) continue; rz->buf_len = _razf_read(rz, rz->outbuf, RZ_BUFFER_SIZE); if(rz->z_eof && rz->buf_len == 0) break; } rz->out += ori_size - size; return ori_size - size; } int razf_skip(RAZF* rz, int size){ int ori_size; ori_size = size; while(size > 0){ if(rz->buf_len){ if(size < rz->buf_len){ rz->buf_off += size; rz->buf_len -= size; rz->block_off += size; size = 0; break; } else { size -= rz->buf_len; rz->buf_off = 0; rz->buf_len = 0; rz->block_off += rz->buf_len; if(rz->buf_flush){ rz->block_pos = rz->next_block_pos; rz->block_off = 0; rz->buf_flush = 0; } } } else if(rz->buf_flush){ rz->block_pos = rz->next_block_pos; rz->block_off = 0; rz->buf_flush = 0; } if(rz->buf_flush) continue; rz->buf_len = _razf_read(rz, rz->outbuf, RZ_BUFFER_SIZE); if(rz->z_eof || rz->z_err) break; } rz->out += ori_size - size; return ori_size - size; } static void _razf_reset_read(RAZF *rz, int64_t in, int64_t out){ #ifdef _USE_KNETFILE knet_seek(rz->x.fpr, in, SEEK_SET); #else lseek(rz->filedes, in, SEEK_SET); #endif rz->in = in; rz->out = out; rz->block_pos = in; rz->next_block_pos = in; rz->block_off = 0; rz->buf_flush = 0; rz->z_eof = rz->z_err = 0; inflateReset(rz->stream); rz->stream->avail_in = 0; rz->buf_off = rz->buf_len = 0; } int64_t razf_jump(RAZF *rz, int64_t block_start, int block_offset){ int64_t pos; rz->z_eof = 0; if(rz->file_type == FILE_TYPE_PLAIN){ rz->buf_off = rz->buf_len = 0; pos = block_start + block_offset; #ifdef _USE_KNETFILE knet_seek(rz->x.fpr, pos, SEEK_SET); pos = knet_tell(rz->x.fpr); #else pos = lseek(rz->filedes, pos, SEEK_SET); #endif rz->out = rz->in = pos; return pos; } if(block_start == rz->block_pos && block_offset >= rz->block_off) { block_offset -= rz->block_off; goto SKIP; // Needn't reset inflate } if(block_start == 0) block_start = rz->header_size; // Automaticly revist wrong block_start _razf_reset_read(rz, block_start, 0); SKIP: if(block_offset) razf_skip(rz, block_offset); return rz->block_off; } int64_t razf_seek(RAZF* rz, int64_t pos, int where){ int64_t idx; int64_t seek_pos, new_out; rz->z_eof = 0; if (where == SEEK_CUR) pos += rz->out; else if (where == SEEK_END) pos += rz->src_end; if(rz->file_type == FILE_TYPE_PLAIN){ #ifdef _USE_KNETFILE knet_seek(rz->x.fpr, pos, SEEK_SET); seek_pos = knet_tell(rz->x.fpr); #else seek_pos = lseek(rz->filedes, pos, SEEK_SET); #endif rz->buf_off = rz->buf_len = 0; rz->out = rz->in = seek_pos; return seek_pos; } else if(rz->file_type == FILE_TYPE_GZ){ if(pos >= rz->out) goto SKIP; return rz->out; } if(pos == rz->out) return pos; if(pos > rz->src_end) return rz->out; if(!rz->seekable || !rz->load_index){ if(pos >= rz->out) goto SKIP; } idx = pos / RZ_BLOCK_SIZE - 1; seek_pos = (idx < 0)? rz->header_size:(rz->index->cell_offsets[idx] + rz->index->bin_offsets[idx / RZ_BIN_SIZE]); new_out = (idx + 1) * RZ_BLOCK_SIZE; if(pos > rz->out && new_out <= rz->out) goto SKIP; _razf_reset_read(rz, seek_pos, new_out); SKIP: razf_skip(rz, (int)(pos - rz->out)); return rz->out; } uint64_t razf_tell2(RAZF *rz) { /* if (rz->load_index) { int64_t idx, seek_pos; idx = rz->out / RZ_BLOCK_SIZE - 1; seek_pos = (idx < 0)? rz->header_size:(rz->index->cell_offsets[idx] + rz->index->bin_offsets[idx / RZ_BIN_SIZE]); if (seek_pos != rz->block_pos || rz->out%RZ_BLOCK_SIZE != rz->block_off) fprintf(stderr, "[razf_tell2] inconsistent block offset: (%lld, %lld) != (%lld, %lld)\n", (long long)seek_pos, (long long)rz->out%RZ_BLOCK_SIZE, (long long)rz->block_pos, (long long) rz->block_off); } */ return (uint64_t)rz->block_pos<<16 | (rz->block_off&0xffff); } int64_t razf_seek2(RAZF *rz, uint64_t voffset, int where) { if (where != SEEK_SET) return -1; return razf_jump(rz, voffset>>16, voffset&0xffff); } void razf_close(RAZF *rz){ if(rz->mode == 'w'){ #ifndef _RZ_READONLY razf_end_flush(rz); deflateEnd(rz->stream); #ifdef _USE_KNETFILE save_zindex(rz, rz->x.fpw); if(is_big_endian()){ write(rz->x.fpw, &rz->in, sizeof(int64_t)); write(rz->x.fpw, &rz->out, sizeof(int64_t)); } else { uint64_t v64 = byte_swap_8((uint64_t)rz->in); write(rz->x.fpw, &v64, sizeof(int64_t)); v64 = byte_swap_8((uint64_t)rz->out); write(rz->x.fpw, &v64, sizeof(int64_t)); } #else save_zindex(rz, rz->filedes); if(is_big_endian()){ write(rz->filedes, &rz->in, sizeof(int64_t)); write(rz->filedes, &rz->out, sizeof(int64_t)); } else { uint64_t v64 = byte_swap_8((uint64_t)rz->in); write(rz->filedes, &v64, sizeof(int64_t)); v64 = byte_swap_8((uint64_t)rz->out); write(rz->filedes, &v64, sizeof(int64_t)); } #endif #endif } else if(rz->mode == 'r'){ if(rz->stream) inflateEnd(rz->stream); } if(rz->inbuf) free(rz->inbuf); if(rz->outbuf) free(rz->outbuf); if(rz->header){ free(rz->header->extra); free(rz->header->name); free(rz->header->comment); free(rz->header); } if(rz->index){ free(rz->index->bin_offsets); free(rz->index->cell_offsets); free(rz->index); } free(rz->stream); #ifdef _USE_KNETFILE if (rz->mode == 'r') knet_close(rz->x.fpr); if (rz->mode == 'w') close(rz->x.fpw); #else close(rz->filedes); #endif free(rz); } #endif
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_endian.h
.h
1,064
43
#ifndef BAM_ENDIAN_H #define BAM_ENDIAN_H #include <stdint.h> static inline int bam_is_big_endian() { long one= 1; return !(*((char *)(&one))); } static inline uint16_t bam_swap_endian_2(uint16_t v) { return (uint16_t)(((v & 0x00FF00FFU) << 8) | ((v & 0xFF00FF00U) >> 8)); } static inline void *bam_swap_endian_2p(void *x) { *(uint16_t*)x = bam_swap_endian_2(*(uint16_t*)x); return x; } static inline uint32_t bam_swap_endian_4(uint32_t v) { v = ((v & 0x0000FFFFU) << 16) | (v >> 16); return ((v & 0x00FF00FFU) << 8) | ((v & 0xFF00FF00U) >> 8); } static inline void *bam_swap_endian_4p(void *x) { *(uint32_t*)x = bam_swap_endian_4(*(uint32_t*)x); return x; } static inline uint64_t bam_swap_endian_8(uint64_t v) { v = ((v & 0x00000000FFFFFFFFLLU) << 32) | (v >> 32); v = ((v & 0x0000FFFF0000FFFFLLU) << 16) | ((v & 0xFFFF0000FFFF0000LLU) >> 16); return ((v & 0x00FF00FF00FF00FFLLU) << 8) | ((v & 0xFF00FF00FF00FF00LLU) >> 8); } static inline void *bam_swap_endian_8p(void *x) { *(uint64_t*)x = bam_swap_endian_8(*(uint64_t*)x); return x; } #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/sam.c
.c
6,051
187
#include <string.h> #include <unistd.h> #include "faidx.h" #include "sam.h" #define TYPE_BAM 1 #define TYPE_READ 2 bam_header_t *bam_header_dup(const bam_header_t *h0) { bam_header_t *h; int i; h = bam_header_init(); *h = *h0; h->hash = h->dict = h->rg2lib = 0; h->text = (char*)calloc(h->l_text + 1, 1); memcpy(h->text, h0->text, h->l_text); h->target_len = (uint32_t*)calloc(h->n_targets, 4); h->target_name = (char**)calloc(h->n_targets, sizeof(void*)); for (i = 0; i < h->n_targets; ++i) { h->target_len[i] = h0->target_len[i]; h->target_name[i] = strdup(h0->target_name[i]); } return h; } static void append_header_text(bam_header_t *header, char* text, int len) { int x = header->l_text + 1; int y = header->l_text + len + 1; // 1 byte null if (text == 0) return; kroundup32(x); kroundup32(y); if (x < y) header->text = (char*)realloc(header->text, y); strncpy(header->text + header->l_text, text, len); // we cannot use strcpy() here. header->l_text += len; header->text[header->l_text] = 0; } int samthreads(samfile_t *fp, int n_threads, int n_sub_blks) { if (!(fp->type&1) || (fp->type&2)) return -1; bgzf_mt(fp->x.bam, n_threads, n_sub_blks); return 0; } samfile_t *samopen(const char *fn, const char *mode, const void *aux) { samfile_t *fp; fp = (samfile_t*)calloc(1, sizeof(samfile_t)); if (strchr(mode, 'r')) { // read fp->type |= TYPE_READ; if (strchr(mode, 'b')) { // binary fp->type |= TYPE_BAM; fp->x.bam = strcmp(fn, "-")? bam_open(fn, "r") : bam_dopen(fileno(stdin), "r"); if (fp->x.bam == 0) goto open_err_ret; fp->header = bam_header_read(fp->x.bam); } else { // text fp->x.tamr = sam_open(fn); if (fp->x.tamr == 0) goto open_err_ret; fp->header = sam_header_read(fp->x.tamr); if (fp->header->n_targets == 0) { // no @SQ fields if (aux) { // check if aux is present bam_header_t *textheader = fp->header; fp->header = sam_header_read2((const char*)aux); if (fp->header == 0) goto open_err_ret; append_header_text(fp->header, textheader->text, textheader->l_text); bam_header_destroy(textheader); } if (fp->header->n_targets == 0 && bam_verbose >= 1) fprintf(stderr, "[samopen] no @SQ lines in the header.\n"); } else if (bam_verbose >= 2) fprintf(stderr, "[samopen] SAM header is present: %d sequences.\n", fp->header->n_targets); } } else if (strchr(mode, 'w')) { // write fp->header = bam_header_dup((const bam_header_t*)aux); if (strchr(mode, 'b')) { // binary char bmode[3]; int i, compress_level = -1; for (i = 0; mode[i]; ++i) if (mode[i] >= '0' && mode[i] <= '9') break; if (mode[i]) compress_level = mode[i] - '0'; if (strchr(mode, 'u')) compress_level = 0; bmode[0] = 'w'; bmode[1] = compress_level < 0? 0 : compress_level + '0'; bmode[2] = 0; fp->type |= TYPE_BAM; fp->x.bam = strcmp(fn, "-")? bam_open(fn, bmode) : bam_dopen(fileno(stdout), bmode); if (fp->x.bam == 0) goto open_err_ret; bam_header_write(fp->x.bam, fp->header); } else { // text // open file fp->x.tamw = strcmp(fn, "-")? fopen(fn, "w") : stdout; if (fp->x.tamw == 0) goto open_err_ret; if (strchr(mode, 'X')) fp->type |= BAM_OFSTR<<2; else if (strchr(mode, 'x')) fp->type |= BAM_OFHEX<<2; else fp->type |= BAM_OFDEC<<2; // write header if (strchr(mode, 'h')) { int i; bam_header_t *alt; // parse the header text alt = bam_header_init(); alt->l_text = fp->header->l_text; alt->text = fp->header->text; sam_header_parse(alt); alt->l_text = 0; alt->text = 0; // check if there are @SQ lines in the header fwrite(fp->header->text, 1, fp->header->l_text, fp->x.tamw); // FIXME: better to skip the trailing NULL if (alt->n_targets) { // then write the header text without dumping ->target_{name,len} if (alt->n_targets != fp->header->n_targets && bam_verbose >= 1) fprintf(stderr, "[samopen] inconsistent number of target sequences. Output the text header.\n"); } else { // then dump ->target_{name,len} for (i = 0; i < fp->header->n_targets; ++i) fprintf(fp->x.tamw, "@SQ\tSN:%s\tLN:%d\n", fp->header->target_name[i], fp->header->target_len[i]); } bam_header_destroy(alt); } } } return fp; open_err_ret: free(fp); return 0; } void samclose(samfile_t *fp) { if (fp == 0) return; if (fp->header) bam_header_destroy(fp->header); if (fp->type & TYPE_BAM) bam_close(fp->x.bam); else if (fp->type & TYPE_READ) sam_close(fp->x.tamr); else fclose(fp->x.tamw); free(fp); } int samread(samfile_t *fp, bam1_t *b) { if (fp == 0 || !(fp->type & TYPE_READ)) return -1; // not open for reading if (fp->type & TYPE_BAM) return bam_read1(fp->x.bam, b); else return sam_read1(fp->x.tamr, fp->header, b); } int samwrite(samfile_t *fp, const bam1_t *b) { if (fp == 0 || (fp->type & TYPE_READ)) return -1; // not open for writing if (fp->type & TYPE_BAM) return bam_write1(fp->x.bam, b); else { char *s = bam_format1_core(fp->header, b, fp->type>>2&3); int l = strlen(s); fputs(s, fp->x.tamw); fputc('\n', fp->x.tamw); free(s); return l + 1; } } int sampileup(samfile_t *fp, int mask, bam_pileup_f func, void *func_data) { bam_plbuf_t *buf; int ret; bam1_t *b; b = bam_init1(); buf = bam_plbuf_init(func, func_data); bam_plbuf_set_mask(buf, mask); while ((ret = samread(fp, b)) >= 0) bam_plbuf_push(b, buf); bam_plbuf_push(0, buf); bam_plbuf_destroy(buf); bam_destroy1(b); return 0; } char *samfaipath(const char *fn_ref) { char *fn_list = 0; if (fn_ref == 0) return 0; fn_list = calloc(strlen(fn_ref) + 5, 1); strcat(strcpy(fn_list, fn_ref), ".fai"); if (access(fn_list, R_OK) == -1) { // fn_list is unreadable if (access(fn_ref, R_OK) == -1) { fprintf(stderr, "[samfaipath] fail to read file %s.\n", fn_ref); } else { if (bam_verbose >= 3) fprintf(stderr, "[samfaipath] build FASTA index...\n"); if (fai_build(fn_ref) == -1) { fprintf(stderr, "[samfaipath] fail to build FASTA index.\n"); free(fn_list); fn_list = 0; } } } return fn_list; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam2depth.c
.c
5,844
144
/* This program demonstrates how to generate pileup from multiple BAMs * simutaneously, to achieve random access and to use the BED interface. * To compile this program separately, you may: * * gcc -g -O2 -Wall -o bam2depth -D_MAIN_BAM2DEPTH bam2depth.c -L. -lbam -lz */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include "bam.h" typedef struct { // auxiliary data structure bamFile fp; // the file handler bam_iter_t iter; // NULL if a region not specified int min_mapQ, min_len; // mapQ filter; length filter } aux_t; void *bed_read(const char *fn); // read a BED or position list file void bed_destroy(void *_h); // destroy the BED data structure int bed_overlap(const void *_h, const char *chr, int beg, int end); // test if chr:beg-end overlaps // This function reads a BAM alignment from one BAM file. static int read_bam(void *data, bam1_t *b) // read level filters better go here to avoid pileup { aux_t *aux = (aux_t*)data; // data in fact is a pointer to an auxiliary structure int ret = aux->iter? bam_iter_read(aux->fp, aux->iter, b) : bam_read1(aux->fp, b); if (!(b->core.flag&BAM_FUNMAP)) { if ((int)b->core.qual < aux->min_mapQ) b->core.flag |= BAM_FUNMAP; else if (aux->min_len && bam_cigar2qlen(&b->core, bam1_cigar(b)) < aux->min_len) b->core.flag |= BAM_FUNMAP; } return ret; } int read_file_list(const char *file_list,int *n,char **argv[]); #ifdef _MAIN_BAM2DEPTH int main(int argc, char *argv[]) #else int main_depth(int argc, char *argv[]) #endif { int i, n, tid, beg, end, pos, *n_plp, baseQ = 0, mapQ = 0, min_len = 0, nfiles; const bam_pileup1_t **plp; char *reg = 0; // specified region void *bed = 0; // BED data structure char *file_list = NULL, **fn = NULL; bam_header_t *h = 0; // BAM header of the 1st input aux_t **data; bam_mplp_t mplp; // parse the command line while ((n = getopt(argc, argv, "r:b:q:Q:l:f:")) >= 0) { switch (n) { case 'l': min_len = atoi(optarg); break; // minimum query length case 'r': reg = strdup(optarg); break; // parsing a region requires a BAM header case 'b': bed = bed_read(optarg); break; // BED or position list file can be parsed now case 'q': baseQ = atoi(optarg); break; // base quality threshold case 'Q': mapQ = atoi(optarg); break; // mapping quality threshold case 'f': file_list = optarg; break; } } if (optind == argc && !file_list) { fprintf(stderr, "\n"); fprintf(stderr, "Usage: samtools depth [options] in1.bam [in2.bam [...]]\n"); fprintf(stderr, "Options:\n"); fprintf(stderr, " -b <bed> list of positions or regions\n"); fprintf(stderr, " -f <list> list of input BAM filenames, one per line [null]\n"); fprintf(stderr, " -l <int> minQLen\n"); fprintf(stderr, " -q <int> base quality threshold\n"); fprintf(stderr, " -Q <int> mapping quality threshold\n"); fprintf(stderr, " -r <chr:from-to> region\n"); fprintf(stderr, "\n"); return 1; } // initialize the auxiliary data structures if (file_list) { if ( read_file_list(file_list,&nfiles,&fn) ) return 1; n = nfiles; argv = fn; optind = 0; } else n = argc - optind; // the number of BAMs on the command line data = calloc(n, sizeof(void*)); // data[i] for the i-th input beg = 0; end = 1<<30; tid = -1; // set the default region for (i = 0; i < n; ++i) { bam_header_t *htmp; data[i] = calloc(1, sizeof(aux_t)); data[i]->fp = bam_open(argv[optind+i], "r"); // open BAM data[i]->min_mapQ = mapQ; // set the mapQ filter data[i]->min_len = min_len; // set the qlen filter htmp = bam_header_read(data[i]->fp); // read the BAM header if (i == 0) { h = htmp; // keep the header of the 1st BAM if (reg) bam_parse_region(h, reg, &tid, &beg, &end); // also parse the region } else bam_header_destroy(htmp); // if not the 1st BAM, trash the header if (tid >= 0) { // if a region is specified and parsed successfully bam_index_t *idx = bam_index_load(argv[optind+i]); // load the index data[i]->iter = bam_iter_query(idx, tid, beg, end); // set the iterator bam_index_destroy(idx); // the index is not needed any more; phase out of the memory } } // the core multi-pileup loop mplp = bam_mplp_init(n, read_bam, (void**)data); // initialization n_plp = calloc(n, sizeof(int)); // n_plp[i] is the number of covering reads from the i-th BAM plp = calloc(n, sizeof(void*)); // plp[i] points to the array of covering reads (internal in mplp) while (bam_mplp_auto(mplp, &tid, &pos, n_plp, plp) > 0) { // come to the next covered position if (pos < beg || pos >= end) continue; // out of range; skip if (bed && bed_overlap(bed, h->target_name[tid], pos, pos + 1) == 0) continue; // not in BED; skip fputs(h->target_name[tid], stdout); printf("\t%d", pos+1); // a customized printf() would be faster for (i = 0; i < n; ++i) { // base level filters have to go here int j, m = 0; for (j = 0; j < n_plp[i]; ++j) { const bam_pileup1_t *p = plp[i] + j; // DON'T modfity plp[][] unless you really know if (p->is_del || p->is_refskip) ++m; // having dels or refskips at tid:pos else if (bam1_qual(p->b)[p->qpos] < baseQ) ++m; // low base quality } printf("\t%d", n_plp[i] - m); // this the depth to output } putchar('\n'); } free(n_plp); free(plp); bam_mplp_destroy(mplp); bam_header_destroy(h); for (i = 0; i < n; ++i) { bam_close(data[i]->fp); if (data[i]->iter) bam_iter_destroy(data[i]->iter); free(data[i]); } free(data); free(reg); if (bed) bed_destroy(bed); if ( file_list ) { for (i=0; i<n; i++) free(fn[i]); free(fn); } return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bamtk.c
.c
5,403
120
#include <stdio.h> #include <unistd.h> #include <assert.h> #include <fcntl.h> #include "bam.h" #ifdef _USE_KNETFILE #include "knetfile.h" #endif int bam_taf2baf(int argc, char *argv[]); int bam_mpileup(int argc, char *argv[]); int bam_merge(int argc, char *argv[]); int bam_index(int argc, char *argv[]); int bam_sort(int argc, char *argv[]); int bam_tview_main(int argc, char *argv[]); int bam_mating(int argc, char *argv[]); int bam_rmdup(int argc, char *argv[]); int bam_flagstat(int argc, char *argv[]); int bam_fillmd(int argc, char *argv[]); int bam_idxstats(int argc, char *argv[]); int main_samview(int argc, char *argv[]); int main_import(int argc, char *argv[]); int main_reheader(int argc, char *argv[]); int main_cut_target(int argc, char *argv[]); int main_phase(int argc, char *argv[]); int main_cat(int argc, char *argv[]); int main_depth(int argc, char *argv[]); int main_bam2fq(int argc, char *argv[]); int main_pad2unpad(int argc, char *argv[]); int main_bedcov(int argc, char *argv[]); int main_bamshuf(int argc, char *argv[]); int faidx_main(int argc, char *argv[]); static int usage() { fprintf(stderr, "\n"); fprintf(stderr, "Program: samtools (Tools for alignments in the SAM format)\n"); fprintf(stderr, "Version: %s\n\n", BAM_VERSION); fprintf(stderr, "Usage: samtools <command> [options]\n\n"); fprintf(stderr, "Command: view SAM<->BAM conversion\n"); fprintf(stderr, " sort sort alignment file\n"); fprintf(stderr, " mpileup multi-way pileup\n"); fprintf(stderr, " depth compute the depth\n"); fprintf(stderr, " faidx index/extract FASTA\n"); #if _CURSES_LIB != 0 fprintf(stderr, " tview text alignment viewer\n"); #endif fprintf(stderr, " index index alignment\n"); fprintf(stderr, " idxstats BAM index stats (r595 or later)\n"); fprintf(stderr, " fixmate fix mate information\n"); fprintf(stderr, " flagstat simple stats\n"); fprintf(stderr, " calmd recalculate MD/NM tags and '=' bases\n"); fprintf(stderr, " merge merge sorted alignments\n"); fprintf(stderr, " rmdup remove PCR duplicates\n"); fprintf(stderr, " reheader replace BAM header\n"); fprintf(stderr, " cat concatenate BAMs\n"); fprintf(stderr, " bedcov read depth per BED region\n"); fprintf(stderr, " targetcut cut fosmid regions (for fosmid pool only)\n"); fprintf(stderr, " phase phase heterozygotes\n"); fprintf(stderr, " bamshuf shuffle and group alignments by name\n"); // fprintf(stderr, " depad convert padded BAM to unpadded BAM\n"); // not stable fprintf(stderr, "\n"); #ifdef _WIN32 fprintf(stderr, "\ Note: The Windows version of SAMtools is mainly designed for read-only\n\ operations, such as viewing the alignments and generating the pileup.\n\ Binary files generated by the Windows version may be buggy.\n\n"); #endif return 1; } int main(int argc, char *argv[]) { #ifdef _WIN32 setmode(fileno(stdout), O_BINARY); setmode(fileno(stdin), O_BINARY); #ifdef _USE_KNETFILE knet_win32_init(); #endif #endif if (argc < 2) return usage(); if (strcmp(argv[1], "view") == 0) return main_samview(argc-1, argv+1); else if (strcmp(argv[1], "import") == 0) return main_import(argc-1, argv+1); else if (strcmp(argv[1], "mpileup") == 0) return bam_mpileup(argc-1, argv+1); else if (strcmp(argv[1], "merge") == 0) return bam_merge(argc-1, argv+1); else if (strcmp(argv[1], "sort") == 0) return bam_sort(argc-1, argv+1); else if (strcmp(argv[1], "index") == 0) return bam_index(argc-1, argv+1); else if (strcmp(argv[1], "idxstats") == 0) return bam_idxstats(argc-1, argv+1); else if (strcmp(argv[1], "faidx") == 0) return faidx_main(argc-1, argv+1); else if (strcmp(argv[1], "fixmate") == 0) return bam_mating(argc-1, argv+1); else if (strcmp(argv[1], "rmdup") == 0) return bam_rmdup(argc-1, argv+1); else if (strcmp(argv[1], "flagstat") == 0) return bam_flagstat(argc-1, argv+1); else if (strcmp(argv[1], "calmd") == 0) return bam_fillmd(argc-1, argv+1); else if (strcmp(argv[1], "fillmd") == 0) return bam_fillmd(argc-1, argv+1); else if (strcmp(argv[1], "reheader") == 0) return main_reheader(argc-1, argv+1); else if (strcmp(argv[1], "cat") == 0) return main_cat(argc-1, argv+1); else if (strcmp(argv[1], "targetcut") == 0) return main_cut_target(argc-1, argv+1); else if (strcmp(argv[1], "phase") == 0) return main_phase(argc-1, argv+1); else if (strcmp(argv[1], "depth") == 0) return main_depth(argc-1, argv+1); else if (strcmp(argv[1], "bam2fq") == 0) return main_bam2fq(argc-1, argv+1); else if (strcmp(argv[1], "pad2unpad") == 0) return main_pad2unpad(argc-1, argv+1); else if (strcmp(argv[1], "depad") == 0) return main_pad2unpad(argc-1, argv+1); else if (strcmp(argv[1], "bedcov") == 0) return main_bedcov(argc-1, argv+1); else if (strcmp(argv[1], "bamshuf") == 0) return main_bamshuf(argc-1, argv+1); else if (strcmp(argv[1], "pileup") == 0) { fprintf(stderr, "[main] The `pileup' command has been removed. Please use `mpileup' instead.\n"); return 1; } #if _CURSES_LIB != 0 else if (strcmp(argv[1], "tview") == 0) return bam_tview_main(argc-1, argv+1); #endif else { fprintf(stderr, "[main] unrecognized command '%s'\n", argv[1]); return 1; } return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/errmod.c
.c
3,485
131
#include <math.h> #include "errmod.h" #include "ksort.h" KSORT_INIT_GENERIC(uint16_t) typedef struct __errmod_coef_t { double *fk, *beta, *lhet; } errmod_coef_t; typedef struct { double fsum[16], bsum[16]; uint32_t c[16]; } call_aux_t; static errmod_coef_t *cal_coef(double depcorr, double eta) { int k, n, q; long double sum, sum1; double *lC; errmod_coef_t *ec; ec = calloc(1, sizeof(errmod_coef_t)); // initialize ->fk ec->fk = (double*)calloc(256, sizeof(double)); ec->fk[0] = 1.0; for (n = 1; n != 256; ++n) ec->fk[n] = pow(1. - depcorr, n) * (1.0 - eta) + eta; // initialize ->coef ec->beta = (double*)calloc(256 * 256 * 64, sizeof(double)); lC = (double*)calloc(256 * 256, sizeof(double)); for (n = 1; n != 256; ++n) { double lgn = lgamma(n+1); for (k = 1; k <= n; ++k) lC[n<<8|k] = lgn - lgamma(k+1) - lgamma(n-k+1); } for (q = 1; q != 64; ++q) { double e = pow(10.0, -q/10.0); double le = log(e); double le1 = log(1.0 - e); for (n = 1; n <= 255; ++n) { double *beta = ec->beta + (q<<16|n<<8); sum1 = sum = 0.0; for (k = n; k >= 0; --k, sum1 = sum) { sum = sum1 + expl(lC[n<<8|k] + k*le + (n-k)*le1); beta[k] = -10. / M_LN10 * logl(sum1 / sum); } } } // initialize ->lhet ec->lhet = (double*)calloc(256 * 256, sizeof(double)); for (n = 0; n < 256; ++n) for (k = 0; k < 256; ++k) ec->lhet[n<<8|k] = lC[n<<8|k] - M_LN2 * n; free(lC); return ec; } errmod_t *errmod_init(float depcorr) { errmod_t *em; em = (errmod_t*)calloc(1, sizeof(errmod_t)); em->depcorr = depcorr; em->coef = cal_coef(depcorr, 0.03); return em; } void errmod_destroy(errmod_t *em) { if (em == 0) return; free(em->coef->lhet); free(em->coef->fk); free(em->coef->beta); free(em->coef); free(em); } // qual:6, strand:1, base:4 int errmod_cal(const errmod_t *em, int n, int m, uint16_t *bases, float *q) { call_aux_t aux; int i, j, k, w[32]; if (m > m) return -1; memset(q, 0, m * m * sizeof(float)); if (n == 0) return 0; // calculate aux.esum and aux.fsum if (n > 255) { // then sample 255 bases ks_shuffle(uint16_t, n, bases); n = 255; } ks_introsort(uint16_t, n, bases); memset(w, 0, 32 * sizeof(int)); memset(&aux, 0, sizeof(call_aux_t)); for (j = n - 1; j >= 0; --j) { // calculate esum and fsum uint16_t b = bases[j]; int q = b>>5 < 4? 4 : b>>5; if (q > 63) q = 63; k = b&0x1f; aux.fsum[k&0xf] += em->coef->fk[w[k]]; aux.bsum[k&0xf] += em->coef->fk[w[k]] * em->coef->beta[q<<16|n<<8|aux.c[k&0xf]]; ++aux.c[k&0xf]; ++w[k]; } // generate likelihood for (j = 0; j != m; ++j) { float tmp1, tmp3; int tmp2, bar_e; // homozygous for (k = 0, tmp1 = tmp3 = 0.0, tmp2 = 0; k != m; ++k) { if (k == j) continue; tmp1 += aux.bsum[k]; tmp2 += aux.c[k]; tmp3 += aux.fsum[k]; } if (tmp2) { bar_e = (int)(tmp1 / tmp3 + 0.499); if (bar_e > 63) bar_e = 63; q[j*m+j] = tmp1; } // heterozygous for (k = j + 1; k < m; ++k) { int cjk = aux.c[j] + aux.c[k]; for (i = 0, tmp2 = 0, tmp1 = tmp3 = 0.0; i < m; ++i) { if (i == j || i == k) continue; tmp1 += aux.bsum[i]; tmp2 += aux.c[i]; tmp3 += aux.fsum[i]; } if (tmp2) { bar_e = (int)(tmp1 / tmp3 + 0.499); if (bar_e > 63) bar_e = 63; q[j*m+k] = q[k*m+j] = -4.343 * em->coef->lhet[cjk<<8|aux.c[k]] + tmp1; } else q[j*m+k] = q[k*m+j] = -4.343 * em->coef->lhet[cjk<<8|aux.c[k]]; // all the bases are either j or k } for (k = 0; k != m; ++k) if (q[j*m+k] < 0.0) q[j*m+k] = 0.0; } return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bamshuf.c
.c
3,603
142
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "sam.h" #include "ksort.h" #define DEF_CLEVEL 1 static inline unsigned hash_Wang(unsigned key) { key += ~(key << 15); key ^= (key >> 10); key += (key << 3); key ^= (key >> 6); key += ~(key << 11); key ^= (key >> 16); return key; } static inline unsigned hash_X31_Wang(const char *s) { unsigned h = *s; if (h) { for (++s ; *s; ++s) h = (h << 5) - h + *s; return hash_Wang(h); } else return 0; } typedef struct { unsigned key; bam1_t *b; } elem_t; static inline int elem_lt(elem_t x, elem_t y) { if (x.key < y.key) return 1; if (x.key == y.key) { int t; t = strcmp(bam_get_qname(x.b), bam_get_qname(y.b)); if (t < 0) return 1; return (t == 0 && ((x.b->core.flag>>6&3) < (y.b->core.flag>>6&3))); } else return 0; } KSORT_INIT(bamshuf, elem_t, elem_lt) static void bamshuf(const char *fn, int n_files, const char *pre, int clevel, int is_stdout) { BGZF *fp, *fpw, **fpt; char **fnt, modew[8]; bam1_t *b; int i, l; bam_hdr_t *h; int64_t *cnt; // split fp = strcmp(fn, "-")? bgzf_open(fn, "r") : bgzf_dopen(fileno(stdin), "r"); assert(fp); h = bam_hdr_read(fp); fnt = (char**)calloc(n_files, sizeof(void*)); fpt = (BGZF**)calloc(n_files, sizeof(void*)); cnt = (int64_t*)calloc(n_files, 8); l = strlen(pre); for (i = 0; i < n_files; ++i) { fnt[i] = (char*)calloc(l + 10, 1); sprintf(fnt[i], "%s.%.4d.bam", pre, i); fpt[i] = bgzf_open(fnt[i], "w1"); bam_hdr_write(fpt[i], h); } b = bam_init1(); while (bam_read1(fp, b) >= 0) { uint32_t x; x = hash_X31_Wang(bam_get_qname(b)) % n_files; bam_write1(fpt[x], b); ++cnt[x]; } bam_destroy1(b); for (i = 0; i < n_files; ++i) bgzf_close(fpt[i]); free(fpt); bgzf_close(fp); // merge sprintf(modew, "w%d", (clevel >= 0 && clevel <= 9)? clevel : DEF_CLEVEL); if (!is_stdout) { // output to a file char *fnw = (char*)calloc(l + 5, 1); sprintf(fnw, "%s.bam", pre); fpw = bgzf_open(fnw, modew); free(fnw); } else fpw = bgzf_dopen(fileno(stdout), modew); // output to stdout bam_hdr_write(fpw, h); bam_hdr_destroy(h); for (i = 0; i < n_files; ++i) { int64_t j, c = cnt[i]; elem_t *a; fp = bgzf_open(fnt[i], "r"); bam_hdr_destroy(bam_hdr_read(fp)); a = (elem_t*)calloc(c, sizeof(elem_t)); for (j = 0; j < c; ++j) { a[j].b = bam_init1(); assert(bam_read1(fp, a[j].b) >= 0); a[j].key = hash_X31_Wang(bam_get_qname(a[j].b)); } bgzf_close(fp); unlink(fnt[i]); free(fnt[i]); ks_introsort(bamshuf, c, a); for (j = 0; j < c; ++j) { bam_write1(fpw, a[j].b); bam_destroy1(a[j].b); } free(a); } bgzf_close(fpw); free(fnt); free(cnt); } int main_bamshuf(int argc, char *argv[]) { int c, n_files = 64, clevel = DEF_CLEVEL, is_stdout = 0, is_un = 0; while ((c = getopt(argc, argv, "n:l:uO")) >= 0) { switch (c) { case 'n': n_files = atoi(optarg); break; case 'l': clevel = atoi(optarg); break; case 'u': is_un = 1; break; case 'O': is_stdout = 1; break; } } if (is_un) clevel = 0; if (optind + 2 > argc) { fprintf(stderr, "\nUsage: bamshuf [-Ou] [-n nFiles] [-c cLevel] <in.bam> <out.prefix>\n\n"); fprintf(stderr, "Options: -O output to stdout\n"); fprintf(stderr, " -u uncompressed BAM output\n"); fprintf(stderr, " -l INT compression level [%d]\n", DEF_CLEVEL); fprintf(stderr, " -n INT number of temporary files [%d]\n", n_files); fprintf(stderr, "\n"); return 1; } bamshuf(argv[optind], n_files, argv[optind+1], clevel, is_stdout); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/knetfile.c
.c
18,332
633
/* The MIT License Copyright (c) 2008 by Genome Research Ltd (GRL). 2010 by Attractive Chaos <attractor@live.co.uk> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Probably I will not do socket programming in the next few years and therefore I decide to heavily annotate this file, for Linux and Windows as well. -ac */ #include <time.h> #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #ifndef _WIN32 #include <netdb.h> #include <arpa/inet.h> #include <sys/socket.h> #endif #include "knetfile.h" /* In winsock.h, the type of a socket is SOCKET, which is: "typedef * u_int SOCKET". An invalid SOCKET is: "(SOCKET)(~0)", or signed * integer -1. In knetfile.c, I use "int" for socket type * throughout. This should be improved to avoid confusion. * * In Linux/Mac, recv() and read() do almost the same thing. You can see * in the header file that netread() is simply an alias of read(). In * Windows, however, they are different and using recv() is mandatory. */ /* This function tests if the file handler is ready for reading (or * writing if is_read==0). */ static int socket_wait(int fd, int is_read) { fd_set fds, *fdr = 0, *fdw = 0; struct timeval tv; int ret; tv.tv_sec = 5; tv.tv_usec = 0; // 5 seconds time out FD_ZERO(&fds); FD_SET(fd, &fds); if (is_read) fdr = &fds; else fdw = &fds; ret = select(fd+1, fdr, fdw, 0, &tv); #ifndef _WIN32 if (ret == -1) perror("select"); #else if (ret == 0) fprintf(stderr, "select time-out\n"); else if (ret == SOCKET_ERROR) fprintf(stderr, "select: %d\n", WSAGetLastError()); #endif return ret; } #ifndef _WIN32 /* This function does not work with Windows due to the lack of * getaddrinfo() in winsock. It is addapted from an example in "Beej's * Guide to Network Programming" (http://beej.us/guide/bgnet/). */ static int socket_connect(const char *host, const char *port) { #define __err_connect(func) do { perror(func); freeaddrinfo(res); return -1; } while (0) int on = 1, fd; struct linger lng = { 0, 0 }; struct addrinfo hints, *res = 0; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; /* In Unix/Mac, getaddrinfo() is the most convenient way to get * server information. */ if (getaddrinfo(host, port, &hints, &res) != 0) __err_connect("getaddrinfo"); if ((fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) __err_connect("socket"); /* The following two setsockopt() are used by ftplib * (http://nbpfaus.net/~pfau/ftplib/). I am not sure if they * necessary. */ if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) __err_connect("setsockopt"); if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &lng, sizeof(lng)) == -1) __err_connect("setsockopt"); if (connect(fd, res->ai_addr, res->ai_addrlen) != 0) __err_connect("connect"); freeaddrinfo(res); return fd; } #else /* MinGW's printf has problem with "%lld" */ char *int64tostr(char *buf, int64_t x) { int cnt; int i = 0; do { buf[i++] = '0' + x % 10; x /= 10; } while (x); buf[i] = 0; for (cnt = i, i = 0; i < cnt/2; ++i) { int c = buf[i]; buf[i] = buf[cnt-i-1]; buf[cnt-i-1] = c; } return buf; } int64_t strtoint64(const char *buf) { int64_t x; for (x = 0; *buf != '\0'; ++buf) x = x * 10 + ((int64_t) *buf - 48); return x; } /* In windows, the first thing is to establish the TCP connection. */ int knet_win32_init() { WSADATA wsaData; return WSAStartup(MAKEWORD(2, 2), &wsaData); } void knet_win32_destroy() { WSACleanup(); } /* A slightly modfied version of the following function also works on * Mac (and presummably Linux). However, this function is not stable on * my Mac. It sometimes works fine but sometimes does not. Therefore for * non-Windows OS, I do not use this one. */ static SOCKET socket_connect(const char *host, const char *port) { #define __err_connect(func) \ do { \ fprintf(stderr, "%s: %d\n", func, WSAGetLastError()); \ return -1; \ } while (0) int on = 1; SOCKET fd; struct linger lng = { 0, 0 }; struct sockaddr_in server; struct hostent *hp = 0; // open socket if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) __err_connect("socket"); if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on)) == -1) __err_connect("setsockopt"); if (setsockopt(fd, SOL_SOCKET, SO_LINGER, (char*)&lng, sizeof(lng)) == -1) __err_connect("setsockopt"); // get host info if (isalpha(host[0])) hp = gethostbyname(host); else { struct in_addr addr; addr.s_addr = inet_addr(host); hp = gethostbyaddr((char*)&addr, 4, AF_INET); } if (hp == 0) __err_connect("gethost"); // connect server.sin_addr.s_addr = *((unsigned long*)hp->h_addr); server.sin_family= AF_INET; server.sin_port = htons(atoi(port)); if (connect(fd, (struct sockaddr*)&server, sizeof(server)) != 0) __err_connect("connect"); // freehostent(hp); // strangely in MSDN, hp is NOT freed (memory leak?!) return fd; } #endif static off_t my_netread(int fd, void *buf, off_t len) { off_t rest = len, curr, l = 0; /* recv() and read() may not read the required length of data with * one call. They have to be called repeatedly. */ while (rest) { if (socket_wait(fd, 1) <= 0) break; // socket is not ready for reading curr = netread(fd, buf + l, rest); /* According to the glibc manual, section 13.2, a zero returned * value indicates end-of-file (EOF), which should mean that * read() will not return zero if EOF has not been met but data * are not immediately available. */ if (curr == 0) break; l += curr; rest -= curr; } return l; } /************************* * FTP specific routines * *************************/ static int kftp_get_response(knetFile *ftp) { #ifndef _WIN32 unsigned char c; #else char c; #endif int n = 0; char *p; if (socket_wait(ftp->ctrl_fd, 1) <= 0) return 0; while (netread(ftp->ctrl_fd, &c, 1)) { // FIXME: this is *VERY BAD* for unbuffered I/O //fputc(c, stderr); if (n >= ftp->max_response) { ftp->max_response = ftp->max_response? ftp->max_response<<1 : 256; ftp->response = realloc(ftp->response, ftp->max_response); } ftp->response[n++] = c; if (c == '\n') { if (n >= 4 && isdigit(ftp->response[0]) && isdigit(ftp->response[1]) && isdigit(ftp->response[2]) && ftp->response[3] != '-') break; n = 0; continue; } } if (n < 2) return -1; ftp->response[n-2] = 0; return strtol(ftp->response, &p, 0); } static int kftp_send_cmd(knetFile *ftp, const char *cmd, int is_get) { if (socket_wait(ftp->ctrl_fd, 0) <= 0) return -1; // socket is not ready for writing netwrite(ftp->ctrl_fd, cmd, strlen(cmd)); return is_get? kftp_get_response(ftp) : 0; } static int kftp_pasv_prep(knetFile *ftp) { char *p; int v[6]; kftp_send_cmd(ftp, "PASV\r\n", 1); for (p = ftp->response; *p && *p != '('; ++p); if (*p != '(') return -1; ++p; sscanf(p, "%d,%d,%d,%d,%d,%d", &v[0], &v[1], &v[2], &v[3], &v[4], &v[5]); memcpy(ftp->pasv_ip, v, 4 * sizeof(int)); ftp->pasv_port = (v[4]<<8&0xff00) + v[5]; return 0; } static int kftp_pasv_connect(knetFile *ftp) { char host[80], port[10]; if (ftp->pasv_port == 0) { fprintf(stderr, "[kftp_pasv_connect] kftp_pasv_prep() is not called before hand.\n"); return -1; } sprintf(host, "%d.%d.%d.%d", ftp->pasv_ip[0], ftp->pasv_ip[1], ftp->pasv_ip[2], ftp->pasv_ip[3]); sprintf(port, "%d", ftp->pasv_port); ftp->fd = socket_connect(host, port); if (ftp->fd == -1) return -1; return 0; } int kftp_connect(knetFile *ftp) { ftp->ctrl_fd = socket_connect(ftp->host, ftp->port); if (ftp->ctrl_fd == -1) return -1; kftp_get_response(ftp); kftp_send_cmd(ftp, "USER anonymous\r\n", 1); kftp_send_cmd(ftp, "PASS kftp@\r\n", 1); kftp_send_cmd(ftp, "TYPE I\r\n", 1); return 0; } int kftp_reconnect(knetFile *ftp) { if (ftp->ctrl_fd != -1) { netclose(ftp->ctrl_fd); ftp->ctrl_fd = -1; } netclose(ftp->fd); ftp->fd = -1; return kftp_connect(ftp); } // initialize ->type, ->host, ->retr and ->size knetFile *kftp_parse_url(const char *fn, const char *mode) { knetFile *fp; char *p; int l; if (strstr(fn, "ftp://") != fn) return 0; for (p = (char*)fn + 6; *p && *p != '/'; ++p); if (*p != '/') return 0; l = p - fn - 6; fp = calloc(1, sizeof(knetFile)); fp->type = KNF_TYPE_FTP; fp->fd = -1; /* the Linux/Mac version of socket_connect() also recognizes a port * like "ftp", but the Windows version does not. */ fp->port = strdup("21"); fp->host = calloc(l + 1, 1); if (strchr(mode, 'c')) fp->no_reconnect = 1; strncpy(fp->host, fn + 6, l); fp->retr = calloc(strlen(p) + 8, 1); sprintf(fp->retr, "RETR %s\r\n", p); fp->size_cmd = calloc(strlen(p) + 8, 1); sprintf(fp->size_cmd, "SIZE %s\r\n", p); fp->seek_offset = 0; return fp; } // place ->fd at offset off int kftp_connect_file(knetFile *fp) { int ret; long long file_size; if (fp->fd != -1) { netclose(fp->fd); if (fp->no_reconnect) kftp_get_response(fp); } kftp_pasv_prep(fp); kftp_send_cmd(fp, fp->size_cmd, 1); #ifndef _WIN32 if ( sscanf(fp->response,"%*d %lld", &file_size) != 1 ) { fprintf(stderr,"[kftp_connect_file] %s\n", fp->response); return -1; } #else const char *p = fp->response; while (*p != ' ') ++p; while (*p < '0' || *p > '9') ++p; file_size = strtoint64(p); #endif fp->file_size = file_size; if (fp->offset>=0) { char tmp[32]; #ifndef _WIN32 sprintf(tmp, "REST %lld\r\n", (long long)fp->offset); #else strcpy(tmp, "REST "); int64tostr(tmp + 5, fp->offset); strcat(tmp, "\r\n"); #endif kftp_send_cmd(fp, tmp, 1); } kftp_send_cmd(fp, fp->retr, 0); kftp_pasv_connect(fp); ret = kftp_get_response(fp); if (ret != 150) { fprintf(stderr, "[kftp_connect_file] %s\n", fp->response); netclose(fp->fd); fp->fd = -1; return -1; } fp->is_ready = 1; return 0; } /************************** * HTTP specific routines * **************************/ knetFile *khttp_parse_url(const char *fn, const char *mode) { knetFile *fp; char *p, *proxy, *q; int l; if (strstr(fn, "http://") != fn) return 0; // set ->http_host for (p = (char*)fn + 7; *p && *p != '/'; ++p); l = p - fn - 7; fp = calloc(1, sizeof(knetFile)); fp->http_host = calloc(l + 1, 1); strncpy(fp->http_host, fn + 7, l); fp->http_host[l] = 0; for (q = fp->http_host; *q && *q != ':'; ++q); if (*q == ':') *q++ = 0; // get http_proxy proxy = getenv("http_proxy"); // set ->host, ->port and ->path if (proxy == 0) { fp->host = strdup(fp->http_host); // when there is no proxy, server name is identical to http_host name. fp->port = strdup(*q? q : "80"); fp->path = strdup(*p? p : "/"); } else { fp->host = (strstr(proxy, "http://") == proxy)? strdup(proxy + 7) : strdup(proxy); for (q = fp->host; *q && *q != ':'; ++q); if (*q == ':') *q++ = 0; fp->port = strdup(*q? q : "80"); fp->path = strdup(fn); } fp->type = KNF_TYPE_HTTP; fp->ctrl_fd = fp->fd = -1; fp->seek_offset = 0; return fp; } int khttp_connect_file(knetFile *fp) { int ret, l = 0; char *buf, *p; if (fp->fd != -1) netclose(fp->fd); fp->fd = socket_connect(fp->host, fp->port); buf = calloc(0x10000, 1); // FIXME: I am lazy... But in principle, 64KB should be large enough. l += sprintf(buf + l, "GET %s HTTP/1.0\r\nHost: %s\r\n", fp->path, fp->http_host); l += sprintf(buf + l, "Range: bytes=%lld-\r\n", (long long)fp->offset); l += sprintf(buf + l, "\r\n"); netwrite(fp->fd, buf, l); l = 0; while (netread(fp->fd, buf + l, 1)) { // read HTTP header; FIXME: bad efficiency if (buf[l] == '\n' && l >= 3) if (strncmp(buf + l - 3, "\r\n\r\n", 4) == 0) break; ++l; } buf[l] = 0; if (l < 14) { // prematured header netclose(fp->fd); fp->fd = -1; return -1; } ret = strtol(buf + 8, &p, 0); // HTTP return code if (ret == 200 && fp->offset>0) { // 200 (complete result); then skip beginning of the file off_t rest = fp->offset; while (rest) { off_t l = rest < 0x10000? rest : 0x10000; rest -= my_netread(fp->fd, buf, l); } } else if (ret != 206 && ret != 200) { free(buf); fprintf(stderr, "[khttp_connect_file] fail to open file (HTTP code: %d).\n", ret); netclose(fp->fd); fp->fd = -1; return -1; } free(buf); fp->is_ready = 1; return 0; } /******************** * Generic routines * ********************/ knetFile *knet_open(const char *fn, const char *mode) { knetFile *fp = 0; if (mode[0] != 'r') { fprintf(stderr, "[kftp_open] only mode \"r\" is supported.\n"); return 0; } if (strstr(fn, "ftp://") == fn) { fp = kftp_parse_url(fn, mode); if (fp == 0) return 0; if (kftp_connect(fp) == -1) { knet_close(fp); return 0; } kftp_connect_file(fp); } else if (strstr(fn, "http://") == fn) { fp = khttp_parse_url(fn, mode); if (fp == 0) return 0; khttp_connect_file(fp); } else { // local file #ifdef _WIN32 /* In windows, O_BINARY is necessary. In Linux/Mac, O_BINARY may * be undefined on some systems, although it is defined on my * Mac and the Linux I have tested on. */ int fd = open(fn, O_RDONLY | O_BINARY); #else int fd = open(fn, O_RDONLY); #endif if (fd == -1) { perror("open"); return 0; } fp = (knetFile*)calloc(1, sizeof(knetFile)); fp->type = KNF_TYPE_LOCAL; fp->fd = fd; fp->ctrl_fd = -1; } if (fp && fp->fd == -1) { knet_close(fp); return 0; } return fp; } knetFile *knet_dopen(int fd, const char *mode) { knetFile *fp = (knetFile*)calloc(1, sizeof(knetFile)); fp->type = KNF_TYPE_LOCAL; fp->fd = fd; return fp; } off_t knet_read(knetFile *fp, void *buf, off_t len) { off_t l = 0; if (fp->fd == -1) return 0; if (fp->type == KNF_TYPE_FTP) { if (fp->is_ready == 0) { if (!fp->no_reconnect) kftp_reconnect(fp); kftp_connect_file(fp); } } else if (fp->type == KNF_TYPE_HTTP) { if (fp->is_ready == 0) khttp_connect_file(fp); } if (fp->type == KNF_TYPE_LOCAL) { // on Windows, the following block is necessary; not on UNIX off_t rest = len, curr; while (rest) { do { curr = read(fp->fd, buf + l, rest); } while (curr < 0 && EINTR == errno); if (curr < 0) return -1; if (curr == 0) break; l += curr; rest -= curr; } } else l = my_netread(fp->fd, buf, len); fp->offset += l; return l; } off_t knet_seek(knetFile *fp, int64_t off, int whence) { if (whence == SEEK_SET && off == fp->offset) return 0; if (fp->type == KNF_TYPE_LOCAL) { /* Be aware that lseek() returns the offset after seeking, * while fseek() returns zero on success. */ off_t offset = lseek(fp->fd, off, whence); if (offset == -1) { // Be silent, it is OK for knet_seek to fail when the file is streamed // fprintf(stderr,"[knet_seek] %s\n", strerror(errno)); return -1; } fp->offset = offset; return 0; } else if (fp->type == KNF_TYPE_FTP) { if (whence==SEEK_CUR) fp->offset += off; else if (whence==SEEK_SET) fp->offset = off; else if ( whence==SEEK_END) fp->offset = fp->file_size+off; fp->is_ready = 0; return 0; } else if (fp->type == KNF_TYPE_HTTP) { if (whence == SEEK_END) { // FIXME: can we allow SEEK_END in future? fprintf(stderr, "[knet_seek] SEEK_END is not supported for HTTP. Offset is unchanged.\n"); errno = ESPIPE; return -1; } if (whence==SEEK_CUR) fp->offset += off; else if (whence==SEEK_SET) fp->offset = off; fp->is_ready = 0; return 0; } errno = EINVAL; fprintf(stderr,"[knet_seek] %s\n", strerror(errno)); return -1; } int knet_close(knetFile *fp) { if (fp == 0) return 0; if (fp->ctrl_fd != -1) netclose(fp->ctrl_fd); // FTP specific if (fp->fd != -1) { /* On Linux/Mac, netclose() is an alias of close(), but on * Windows, it is an alias of closesocket(). */ if (fp->type == KNF_TYPE_LOCAL) close(fp->fd); else netclose(fp->fd); } free(fp->host); free(fp->port); free(fp->response); free(fp->retr); // FTP specific free(fp->path); free(fp->http_host); // HTTP specific free(fp); return 0; } #ifdef KNETFILE_MAIN int main(void) { char *buf; knetFile *fp; int type = 4, l; #ifdef _WIN32 knet_win32_init(); #endif buf = calloc(0x100000, 1); if (type == 0) { fp = knet_open("knetfile.c", "r"); knet_seek(fp, 1000, SEEK_SET); } else if (type == 1) { // NCBI FTP, large file fp = knet_open("ftp://ftp.ncbi.nih.gov/1000genomes/ftp/data/NA12878/alignment/NA12878.chrom6.SLX.SRP000032.2009_06.bam", "r"); knet_seek(fp, 2500000000ll, SEEK_SET); l = knet_read(fp, buf, 255); } else if (type == 2) { fp = knet_open("ftp://ftp.sanger.ac.uk/pub4/treefam/tmp/index.shtml", "r"); knet_seek(fp, 1000, SEEK_SET); } else if (type == 3) { fp = knet_open("http://www.sanger.ac.uk/Users/lh3/index.shtml", "r"); knet_seek(fp, 1000, SEEK_SET); } else if (type == 4) { fp = knet_open("http://www.sanger.ac.uk/Users/lh3/ex1.bam", "r"); knet_read(fp, buf, 10000); knet_seek(fp, 20000, SEEK_SET); knet_seek(fp, 10000, SEEK_SET); l = knet_read(fp, buf+10000, 10000000) + 10000; } if (type != 4 && type != 1) { knet_read(fp, buf, 255); buf[255] = 0; printf("%s\n", buf); } else write(fileno(stdout), buf, l); knet_close(fp); free(buf); return 0; } #endif
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/razf.h
.h
4,137
135
/*- * RAZF : Random Access compressed(Z) File * Version: 1.0 * Release Date: 2008-10-27 * * Copyright 2008, Jue Ruan <ruanjue@gmail.com>, Heng Li <lh3@sanger.ac.uk> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef __RAZF_RJ_H #define __RAZF_RJ_H #include <stdint.h> #include <stdio.h> #include "zlib.h" #ifdef _USE_KNETFILE #include "knetfile.h" #endif #if ZLIB_VERNUM < 0x1221 #define _RZ_READONLY struct _gz_header_s; typedef struct _gz_header_s _gz_header; #define gz_header _gz_header #endif #define WINDOW_BITS 15 #ifndef RZ_BLOCK_SIZE #define RZ_BLOCK_SIZE (1<<WINDOW_BITS) #endif #ifndef RZ_BUFFER_SIZE #define RZ_BUFFER_SIZE 4096 #endif #ifndef RZ_COMPRESS_LEVEL #define RZ_COMPRESS_LEVEL 6 #endif #define RZ_BIN_SIZE ((1LLU << 32) / RZ_BLOCK_SIZE) typedef struct { uint32_t *cell_offsets; // i int64_t *bin_offsets; // i / BIN_SIZE int size; int cap; } ZBlockIndex; /* When storing index, output bytes in Big-Endian everywhere */ #define FILE_TYPE_RZ 1 #define FILE_TYPE_PLAIN 2 #define FILE_TYPE_GZ 3 typedef struct RandomAccessZFile { char mode; /* 'w' : write mode; 'r' : read mode */ int file_type; /* plain file or rz file, razf_read support plain file as input too, in this case, razf_read work as buffered fread */ #ifdef _USE_KNETFILE union { knetFile *fpr; int fpw; } x; #else int filedes; /* the file descriptor */ #endif z_stream *stream; ZBlockIndex *index; int64_t in, out, end, src_end; /* in: n bytes total in; out: n bytes total out; */ /* end: the end of all data blocks, while the start of index; src_end: the true end position in uncompressed file */ int buf_flush; // buffer should be flush, suspend inflate util buffer is empty int64_t block_pos, block_off, next_block_pos; /* block_pos: the start postiion of current block in compressed file */ /* block_off: tell how many bytes have been read from current block */ void *inbuf, *outbuf; int header_size; gz_header *header; /* header is used to transfer inflate_state->mode from HEAD to TYPE after call inflateReset */ int buf_off, buf_len; int z_err, z_eof; int seekable; /* Indice where the source is seekable */ int load_index; /* set has_index to 0 in mode 'w', then index will be discarded */ } RAZF; #ifdef __cplusplus extern "C" { #endif RAZF* razf_dopen(int data_fd, const char *mode); RAZF *razf_open(const char *fn, const char *mode); int razf_write(RAZF* rz, const void *data, int size); int razf_read(RAZF* rz, void *data, int size); int64_t razf_seek(RAZF* rz, int64_t pos, int where); void razf_close(RAZF* rz); #define razf_tell(rz) ((rz)->out) RAZF* razf_open2(const char *filename, const char *mode); RAZF* razf_dopen2(int fd, const char *mode); uint64_t razf_tell2(RAZF *rz); int64_t razf_seek2(RAZF *rz, uint64_t voffset, int where); #ifdef __cplusplus } #endif #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_md.c
.c
12,942
390
#include <unistd.h> #include <assert.h> #include <string.h> #include <ctype.h> #include <math.h> #include "faidx.h" #include "sam.h" #include "kstring.h" #include "kaln.h" #include "kprobaln.h" #define USE_EQUAL 1 #define DROP_TAG 2 #define BIN_QUAL 4 #define UPDATE_NM 8 #define UPDATE_MD 16 #define HASH_QNM 32 char bam_nt16_nt4_table[] = { 4, 0, 1, 4, 2, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4 }; int bam_aux_drop_other(bam1_t *b, uint8_t *s); void bam_fillmd1_core(bam1_t *b, char *ref, int flag, int max_nm) { uint8_t *seq = bam1_seq(b); uint32_t *cigar = bam1_cigar(b); bam1_core_t *c = &b->core; int i, x, y, u = 0; kstring_t *str; int32_t old_nm_i = -1, nm = 0; str = (kstring_t*)calloc(1, sizeof(kstring_t)); for (i = y = 0, x = c->pos; i < c->n_cigar; ++i) { int j, l = cigar[i]>>4, op = cigar[i]&0xf; if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) { for (j = 0; j < l; ++j) { int z = y + j; int c1 = bam1_seqi(seq, z), c2 = bam_nt16_table[(int)ref[x+j]]; if (ref[x+j] == 0) break; // out of boundary if ((c1 == c2 && c1 != 15 && c2 != 15) || c1 == 0) { // a match if (flag&USE_EQUAL) seq[z/2] &= (z&1)? 0xf0 : 0x0f; ++u; } else { kputw(u, str); kputc(ref[x+j], str); u = 0; ++nm; } } if (j < l) break; x += l; y += l; } else if (op == BAM_CDEL) { kputw(u, str); kputc('^', str); for (j = 0; j < l; ++j) { if (ref[x+j] == 0) break; kputc(ref[x+j], str); } u = 0; if (j < l) break; x += l; nm += l; } else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) { y += l; if (op == BAM_CINS) nm += l; } else if (op == BAM_CREF_SKIP) { x += l; } } kputw(u, str); // apply max_nm if (max_nm > 0 && nm >= max_nm) { for (i = y = 0, x = c->pos; i < c->n_cigar; ++i) { int j, l = cigar[i]>>4, op = cigar[i]&0xf; if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) { for (j = 0; j < l; ++j) { int z = y + j; int c1 = bam1_seqi(seq, z), c2 = bam_nt16_table[(int)ref[x+j]]; if (ref[x+j] == 0) break; // out of boundary if ((c1 == c2 && c1 != 15 && c2 != 15) || c1 == 0) { // a match seq[z/2] |= (z&1)? 0x0f : 0xf0; bam1_qual(b)[z] = 0; } } if (j < l) break; x += l; y += l; } else if (op == BAM_CDEL || op == BAM_CREF_SKIP) x += l; else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) y += l; } } // update NM if (flag & UPDATE_NM) { uint8_t *old_nm = bam_aux_get(b, "NM"); if (c->flag & BAM_FUNMAP) return; if (old_nm) old_nm_i = bam_aux2i(old_nm); if (!old_nm) bam_aux_append(b, "NM", 'i', 4, (uint8_t*)&nm); else if (nm != old_nm_i) { fprintf(stderr, "[bam_fillmd1] different NM for read '%s': %d -> %d\n", bam1_qname(b), old_nm_i, nm); bam_aux_del(b, old_nm); bam_aux_append(b, "NM", 'i', 4, (uint8_t*)&nm); } } // update MD if (flag & UPDATE_MD) { uint8_t *old_md = bam_aux_get(b, "MD"); if (c->flag & BAM_FUNMAP) return; if (!old_md) bam_aux_append(b, "MD", 'Z', str->l + 1, (uint8_t*)str->s); else { int is_diff = 0; if (strlen((char*)old_md+1) == str->l) { for (i = 0; i < str->l; ++i) if (toupper(old_md[i+1]) != toupper(str->s[i])) break; if (i < str->l) is_diff = 1; } else is_diff = 1; if (is_diff) { fprintf(stderr, "[bam_fillmd1] different MD for read '%s': '%s' -> '%s'\n", bam1_qname(b), old_md+1, str->s); bam_aux_del(b, old_md); bam_aux_append(b, "MD", 'Z', str->l + 1, (uint8_t*)str->s); } } } // drop all tags but RG if (flag&DROP_TAG) { uint8_t *q = bam_aux_get(b, "RG"); bam_aux_drop_other(b, q); } // reduce the resolution of base quality if (flag&BIN_QUAL) { uint8_t *qual = bam1_qual(b); for (i = 0; i < b->core.l_qseq; ++i) if (qual[i] >= 3) qual[i] = qual[i]/10*10 + 7; } free(str->s); free(str); } void bam_fillmd1(bam1_t *b, char *ref, int flag) { bam_fillmd1_core(b, ref, flag, 0); } int bam_cap_mapQ(bam1_t *b, char *ref, int thres) { uint8_t *seq = bam1_seq(b), *qual = bam1_qual(b); uint32_t *cigar = bam1_cigar(b); bam1_core_t *c = &b->core; int i, x, y, mm, q, len, clip_l, clip_q; double t; if (thres < 0) thres = 40; // set the default mm = q = len = clip_l = clip_q = 0; for (i = y = 0, x = c->pos; i < c->n_cigar; ++i) { int j, l = cigar[i]>>4, op = cigar[i]&0xf; if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) { for (j = 0; j < l; ++j) { int z = y + j; int c1 = bam1_seqi(seq, z), c2 = bam_nt16_table[(int)ref[x+j]]; if (ref[x+j] == 0) break; // out of boundary if (c2 != 15 && c1 != 15 && qual[z] >= 13) { // not ambiguous ++len; if (c1 && c1 != c2 && qual[z] >= 13) { // mismatch ++mm; q += qual[z] > 33? 33 : qual[z]; } } } if (j < l) break; x += l; y += l; len += l; } else if (op == BAM_CDEL) { for (j = 0; j < l; ++j) if (ref[x+j] == 0) break; if (j < l) break; x += l; } else if (op == BAM_CSOFT_CLIP) { for (j = 0; j < l; ++j) clip_q += qual[y+j]; clip_l += l; y += l; } else if (op == BAM_CHARD_CLIP) { clip_q += 13 * l; clip_l += l; } else if (op == BAM_CINS) y += l; else if (op == BAM_CREF_SKIP) x += l; } for (i = 0, t = 1; i < mm; ++i) t *= (double)len / (i+1); t = q - 4.343 * log(t) + clip_q / 5.; if (t > thres) return -1; if (t < 0) t = 0; t = sqrt((thres - t) / thres) * thres; // fprintf(stderr, "%s %lf %d\n", bam1_qname(b), t, q); return (int)(t + .499); } int bam_prob_realn_core(bam1_t *b, const char *ref, int flag) { int k, i, bw, x, y, yb, ye, xb, xe, apply_baq = flag&1, extend_baq = flag>>1&1, redo_baq = flag&4; uint32_t *cigar = bam1_cigar(b); bam1_core_t *c = &b->core; kpa_par_t conf = kpa_par_def; uint8_t *bq = 0, *zq = 0, *qual = bam1_qual(b); if ((c->flag & BAM_FUNMAP) || b->core.l_qseq == 0) return -1; // do nothing // test if BQ or ZQ is present if ((bq = bam_aux_get(b, "BQ")) != 0) ++bq; if ((zq = bam_aux_get(b, "ZQ")) != 0 && *zq == 'Z') ++zq; if (bq && redo_baq) { bam_aux_del(b, bq-1); bq = 0; } if (bq && zq) { // remove the ZQ tag bam_aux_del(b, zq-1); zq = 0; } if (bq || zq) { if ((apply_baq && zq) || (!apply_baq && bq)) return -3; // in both cases, do nothing if (bq && apply_baq) { // then convert BQ to ZQ for (i = 0; i < c->l_qseq; ++i) qual[i] = qual[i] + 64 < bq[i]? 0 : qual[i] - ((int)bq[i] - 64); *(bq - 3) = 'Z'; } else if (zq && !apply_baq) { // then convert ZQ to BQ for (i = 0; i < c->l_qseq; ++i) qual[i] += (int)zq[i] - 64; *(zq - 3) = 'B'; } return 0; } // find the start and end of the alignment x = c->pos, y = 0, yb = ye = xb = xe = -1; for (k = 0; k < c->n_cigar; ++k) { int op, l; op = cigar[k]&0xf; l = cigar[k]>>4; if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) { if (yb < 0) yb = y; if (xb < 0) xb = x; ye = y + l; xe = x + l; x += l; y += l; } else if (op == BAM_CSOFT_CLIP || op == BAM_CINS) y += l; else if (op == BAM_CDEL) x += l; else if (op == BAM_CREF_SKIP) return -1; // do nothing if there is a reference skip } // set bandwidth and the start and the end bw = 7; if (abs((xe - xb) - (ye - yb)) > bw) bw = abs((xe - xb) - (ye - yb)) + 3; conf.bw = bw; xb -= yb + bw/2; if (xb < 0) xb = 0; xe += c->l_qseq - ye + bw/2; if (xe - xb - c->l_qseq > bw) xb += (xe - xb - c->l_qseq - bw) / 2, xe -= (xe - xb - c->l_qseq - bw) / 2; { // glocal uint8_t *s, *r, *q, *seq = bam1_seq(b), *bq; int *state; bq = calloc(c->l_qseq + 1, 1); memcpy(bq, qual, c->l_qseq); s = calloc(c->l_qseq, 1); for (i = 0; i < c->l_qseq; ++i) s[i] = bam_nt16_nt4_table[bam1_seqi(seq, i)]; r = calloc(xe - xb, 1); for (i = xb; i < xe; ++i) { if (ref[i] == 0) { xe = i; break; } r[i-xb] = bam_nt16_nt4_table[bam_nt16_table[(int)ref[i]]]; } state = calloc(c->l_qseq, sizeof(int)); q = calloc(c->l_qseq, 1); kpa_glocal(r, xe-xb, s, c->l_qseq, qual, &conf, state, q); if (!extend_baq) { // in this block, bq[] is capped by base quality qual[] for (k = 0, x = c->pos, y = 0; k < c->n_cigar; ++k) { int op = cigar[k]&0xf, l = cigar[k]>>4; if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) { for (i = y; i < y + l; ++i) { if ((state[i]&3) != 0 || state[i]>>2 != x - xb + (i - y)) bq[i] = 0; else bq[i] = bq[i] < q[i]? bq[i] : q[i]; } x += l; y += l; } else if (op == BAM_CSOFT_CLIP || op == BAM_CINS) y += l; else if (op == BAM_CDEL) x += l; } for (i = 0; i < c->l_qseq; ++i) bq[i] = qual[i] - bq[i] + 64; // finalize BQ } else { // in this block, bq[] is BAQ that can be larger than qual[] (different from the above!) uint8_t *left, *rght; left = calloc(c->l_qseq, 1); rght = calloc(c->l_qseq, 1); for (k = 0, x = c->pos, y = 0; k < c->n_cigar; ++k) { int op = cigar[k]&0xf, l = cigar[k]>>4; if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) { for (i = y; i < y + l; ++i) bq[i] = ((state[i]&3) != 0 || state[i]>>2 != x - xb + (i - y))? 0 : q[i]; for (left[y] = bq[y], i = y + 1; i < y + l; ++i) left[i] = bq[i] > left[i-1]? bq[i] : left[i-1]; for (rght[y+l-1] = bq[y+l-1], i = y + l - 2; i >= y; --i) rght[i] = bq[i] > rght[i+1]? bq[i] : rght[i+1]; for (i = y; i < y + l; ++i) bq[i] = left[i] < rght[i]? left[i] : rght[i]; x += l; y += l; } else if (op == BAM_CSOFT_CLIP || op == BAM_CINS) y += l; else if (op == BAM_CDEL) x += l; } for (i = 0; i < c->l_qseq; ++i) bq[i] = 64 + (qual[i] <= bq[i]? 0 : qual[i] - bq[i]); // finalize BQ free(left); free(rght); } if (apply_baq) { for (i = 0; i < c->l_qseq; ++i) qual[i] -= bq[i] - 64; // modify qual bam_aux_append(b, "ZQ", 'Z', c->l_qseq + 1, bq); } else bam_aux_append(b, "BQ", 'Z', c->l_qseq + 1, bq); free(bq); free(s); free(r); free(q); free(state); } return 0; } int bam_prob_realn(bam1_t *b, const char *ref) { return bam_prob_realn_core(b, ref, 1); } int bam_fillmd(int argc, char *argv[]) { int c, flt_flag, tid = -2, ret, len, is_bam_out, is_sam_in, is_uncompressed, max_nm, is_realn, capQ, baq_flag; samfile_t *fp, *fpout = 0; faidx_t *fai; char *ref = 0, mode_w[8], mode_r[8]; bam1_t *b; flt_flag = UPDATE_NM | UPDATE_MD; is_bam_out = is_sam_in = is_uncompressed = is_realn = max_nm = capQ = baq_flag = 0; mode_w[0] = mode_r[0] = 0; strcpy(mode_r, "r"); strcpy(mode_w, "w"); while ((c = getopt(argc, argv, "EqreuNhbSC:n:Ad")) >= 0) { switch (c) { case 'r': is_realn = 1; break; case 'e': flt_flag |= USE_EQUAL; break; case 'd': flt_flag |= DROP_TAG; break; case 'q': flt_flag |= BIN_QUAL; break; case 'h': flt_flag |= HASH_QNM; break; case 'N': flt_flag &= ~(UPDATE_MD|UPDATE_NM); break; case 'b': is_bam_out = 1; break; case 'u': is_uncompressed = is_bam_out = 1; break; case 'S': is_sam_in = 1; break; case 'n': max_nm = atoi(optarg); break; case 'C': capQ = atoi(optarg); break; case 'A': baq_flag |= 1; break; case 'E': baq_flag |= 2; break; default: fprintf(stderr, "[bam_fillmd] unrecognized option '-%c'\n", c); return 1; } } if (!is_sam_in) strcat(mode_r, "b"); if (is_bam_out) strcat(mode_w, "b"); else strcat(mode_w, "h"); if (is_uncompressed) strcat(mode_w, "u"); if (optind + 1 >= argc) { fprintf(stderr, "\n"); fprintf(stderr, "Usage: samtools fillmd [-eubrS] <aln.bam> <ref.fasta>\n\n"); fprintf(stderr, "Options: -e change identical bases to '='\n"); fprintf(stderr, " -u uncompressed BAM output (for piping)\n"); fprintf(stderr, " -b compressed BAM output\n"); fprintf(stderr, " -S the input is SAM with header\n"); fprintf(stderr, " -A modify the quality string\n"); fprintf(stderr, " -r compute the BQ tag (without -A) or cap baseQ by BAQ (with -A)\n"); fprintf(stderr, " -E extended BAQ for better sensitivity but lower specificity\n\n"); return 1; } fp = samopen(argv[optind], mode_r, 0); if (fp == 0) return 1; if (is_sam_in && (fp->header == 0 || fp->header->n_targets == 0)) { fprintf(stderr, "[bam_fillmd] input SAM does not have header. Abort!\n"); return 1; } fpout = samopen("-", mode_w, fp->header); fai = fai_load(argv[optind+1]); b = bam_init1(); while ((ret = samread(fp, b)) >= 0) { if (b->core.tid >= 0) { if (tid != b->core.tid) { free(ref); ref = fai_fetch(fai, fp->header->target_name[b->core.tid], &len); tid = b->core.tid; if (ref == 0) fprintf(stderr, "[bam_fillmd] fail to find sequence '%s' in the reference.\n", fp->header->target_name[tid]); } if (is_realn) bam_prob_realn_core(b, ref, baq_flag); if (capQ > 10) { int q = bam_cap_mapQ(b, ref, capQ); if (b->core.qual > q) b->core.qual = q; } if (ref) bam_fillmd1_core(b, ref, flt_flag, max_nm); } samwrite(fpout, b); } bam_destroy1(b); free(ref); fai_destroy(fai); samclose(fp); samclose(fpout); return 0; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/faidx.c
.c
10,934
438
#include <ctype.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include "faidx.h" #include "khash.h" typedef struct { int32_t line_len, line_blen; int64_t len; uint64_t offset; } faidx1_t; KHASH_MAP_INIT_STR(s, faidx1_t) #ifndef _NO_RAZF #include "razf.h" #else #ifdef _WIN32 #define ftello(fp) ftell(fp) #define fseeko(fp, offset, whence) fseek(fp, offset, whence) #else extern off_t ftello(FILE *stream); extern int fseeko(FILE *stream, off_t offset, int whence); #endif #define RAZF FILE #define razf_read(fp, buf, size) fread(buf, 1, size, fp) #define razf_open(fn, mode) fopen(fn, mode) #define razf_close(fp) fclose(fp) #define razf_seek(fp, offset, whence) fseeko(fp, offset, whence) #define razf_tell(fp) ftello(fp) #endif #ifdef _USE_KNETFILE #include "knetfile.h" #endif struct __faidx_t { RAZF *rz; int n, m; char **name; khash_t(s) *hash; }; #ifndef kroundup32 #define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x)) #endif static inline void fai_insert_index(faidx_t *idx, const char *name, int len, int line_len, int line_blen, uint64_t offset) { khint_t k; int ret; faidx1_t t; if (idx->n == idx->m) { idx->m = idx->m? idx->m<<1 : 16; idx->name = (char**)realloc(idx->name, sizeof(void*) * idx->m); } idx->name[idx->n] = strdup(name); k = kh_put(s, idx->hash, idx->name[idx->n], &ret); t.len = len; t.line_len = line_len; t.line_blen = line_blen; t.offset = offset; kh_value(idx->hash, k) = t; ++idx->n; } faidx_t *fai_build_core(RAZF *rz) { char c, *name; int l_name, m_name, ret; int line_len, line_blen, state; int l1, l2; faidx_t *idx; uint64_t offset; int64_t len; idx = (faidx_t*)calloc(1, sizeof(faidx_t)); idx->hash = kh_init(s); name = 0; l_name = m_name = 0; len = line_len = line_blen = -1; state = 0; l1 = l2 = -1; offset = 0; while (razf_read(rz, &c, 1)) { if (c == '\n') { // an empty line if (state == 1) { offset = razf_tell(rz); continue; } else if ((state == 0 && len < 0) || state == 2) continue; } if (c == '>') { // fasta header if (len >= 0) fai_insert_index(idx, name, len, line_len, line_blen, offset); l_name = 0; while ((ret = razf_read(rz, &c, 1)) != 0 && !isspace(c)) { if (m_name < l_name + 2) { m_name = l_name + 2; kroundup32(m_name); name = (char*)realloc(name, m_name); } name[l_name++] = c; } name[l_name] = '\0'; if (ret == 0) { fprintf(stderr, "[fai_build_core] the last entry has no sequence\n"); free(name); fai_destroy(idx); return 0; } if (c != '\n') while (razf_read(rz, &c, 1) && c != '\n'); state = 1; len = 0; offset = razf_tell(rz); } else { if (state == 3) { fprintf(stderr, "[fai_build_core] inlined empty line is not allowed in sequence '%s'.\n", name); free(name); fai_destroy(idx); return 0; } if (state == 2) state = 3; l1 = l2 = 0; do { ++l1; if (isgraph(c)) ++l2; } while ((ret = razf_read(rz, &c, 1)) && c != '\n'); if (state == 3 && l2) { fprintf(stderr, "[fai_build_core] different line length in sequence '%s'.\n", name); free(name); fai_destroy(idx); return 0; } ++l1; len += l2; if (state == 1) line_len = l1, line_blen = l2, state = 0; else if (state == 0) { if (l1 != line_len || l2 != line_blen) state = 2; } } } fai_insert_index(idx, name, len, line_len, line_blen, offset); free(name); return idx; } void fai_save(const faidx_t *fai, FILE *fp) { khint_t k; int i; for (i = 0; i < fai->n; ++i) { faidx1_t x; k = kh_get(s, fai->hash, fai->name[i]); x = kh_value(fai->hash, k); #ifdef _WIN32 fprintf(fp, "%s\t%d\t%ld\t%d\t%d\n", fai->name[i], (int)x.len, (long)x.offset, (int)x.line_blen, (int)x.line_len); #else fprintf(fp, "%s\t%d\t%lld\t%d\t%d\n", fai->name[i], (int)x.len, (long long)x.offset, (int)x.line_blen, (int)x.line_len); #endif } } faidx_t *fai_read(FILE *fp) { faidx_t *fai; char *buf, *p; int len, line_len, line_blen; #ifdef _WIN32 long offset; #else long long offset; #endif fai = (faidx_t*)calloc(1, sizeof(faidx_t)); fai->hash = kh_init(s); buf = (char*)calloc(0x10000, 1); while (!feof(fp) && fgets(buf, 0x10000, fp)) { for (p = buf; *p && isgraph(*p); ++p); *p = 0; ++p; #ifdef _WIN32 sscanf(p, "%d%ld%d%d", &len, &offset, &line_blen, &line_len); #else sscanf(p, "%d%lld%d%d", &len, &offset, &line_blen, &line_len); #endif fai_insert_index(fai, buf, len, line_len, line_blen, offset); } free(buf); return fai; } void fai_destroy(faidx_t *fai) { int i; for (i = 0; i < fai->n; ++i) free(fai->name[i]); free(fai->name); kh_destroy(s, fai->hash); if (fai->rz) razf_close(fai->rz); free(fai); } int fai_build(const char *fn) { char *str; RAZF *rz; FILE *fp; faidx_t *fai; str = (char*)calloc(strlen(fn) + 5, 1); sprintf(str, "%s.fai", fn); rz = razf_open(fn, "r"); if (rz == 0) { fprintf(stderr, "[fai_build] fail to open the FASTA file %s\n",fn); free(str); return -1; } fai = fai_build_core(rz); razf_close(rz); fp = fopen(str, "wb"); if (fp == 0) { fprintf(stderr, "[fai_build] fail to write FASTA index %s\n",str); fai_destroy(fai); free(str); return -1; } fai_save(fai, fp); fclose(fp); free(str); fai_destroy(fai); return 0; } #ifdef _USE_KNETFILE FILE *download_and_open(const char *fn) { const int buf_size = 1 * 1024 * 1024; uint8_t *buf; FILE *fp; knetFile *fp_remote; const char *url = fn; const char *p; int l = strlen(fn); for (p = fn + l - 1; p >= fn; --p) if (*p == '/') break; fn = p + 1; // First try to open a local copy fp = fopen(fn, "r"); if (fp) return fp; // If failed, download from remote and open fp_remote = knet_open(url, "rb"); if (fp_remote == 0) { fprintf(stderr, "[download_from_remote] fail to open remote file %s\n",url); return NULL; } if ((fp = fopen(fn, "wb")) == 0) { fprintf(stderr, "[download_from_remote] fail to create file in the working directory %s\n",fn); knet_close(fp_remote); return NULL; } buf = (uint8_t*)calloc(buf_size, 1); while ((l = knet_read(fp_remote, buf, buf_size)) != 0) fwrite(buf, 1, l, fp); free(buf); fclose(fp); knet_close(fp_remote); return fopen(fn, "r"); } #endif faidx_t *fai_load(const char *fn) { char *str; FILE *fp; faidx_t *fai; str = (char*)calloc(strlen(fn) + 5, 1); sprintf(str, "%s.fai", fn); #ifdef _USE_KNETFILE if (strstr(fn, "ftp://") == fn || strstr(fn, "http://") == fn) { fp = download_and_open(str); if ( !fp ) { fprintf(stderr, "[fai_load] failed to open remote FASTA index %s\n", str); free(str); return 0; } } else #endif fp = fopen(str, "rb"); if (fp == 0) { fprintf(stderr, "[fai_load] build FASTA index.\n"); fai_build(fn); fp = fopen(str, "rb"); if (fp == 0) { fprintf(stderr, "[fai_load] fail to open FASTA index.\n"); free(str); return 0; } } fai = fai_read(fp); fclose(fp); fai->rz = razf_open(fn, "rb"); free(str); if (fai->rz == 0) { fprintf(stderr, "[fai_load] fail to open FASTA file.\n"); return 0; } return fai; } char *fai_fetch(const faidx_t *fai, const char *str, int *len) { char *s, c; int i, l, k, name_end; khiter_t iter; faidx1_t val; khash_t(s) *h; int beg, end; beg = end = -1; h = fai->hash; name_end = l = strlen(str); s = (char*)malloc(l+1); // remove space for (i = k = 0; i < l; ++i) if (!isspace(str[i])) s[k++] = str[i]; s[k] = 0; l = k; // determine the sequence name for (i = l - 1; i >= 0; --i) if (s[i] == ':') break; // look for colon from the end if (i >= 0) name_end = i; if (name_end < l) { // check if this is really the end int n_hyphen = 0; for (i = name_end + 1; i < l; ++i) { if (s[i] == '-') ++n_hyphen; else if (!isdigit(s[i]) && s[i] != ',') break; } if (i < l || n_hyphen > 1) name_end = l; // malformated region string; then take str as the name s[name_end] = 0; iter = kh_get(s, h, s); if (iter == kh_end(h)) { // cannot find the sequence name iter = kh_get(s, h, str); // try str as the name if (iter == kh_end(h)) { *len = 0; free(s); return 0; } else s[name_end] = ':', name_end = l; } } else iter = kh_get(s, h, str); if(iter == kh_end(h)) { fprintf(stderr, "[fai_fetch] Warning - Reference %s not found in FASTA file, returning empty sequence\n", str); free(s); return 0; }; val = kh_value(h, iter); // parse the interval if (name_end < l) { for (i = k = name_end + 1; i < l; ++i) if (s[i] != ',') s[k++] = s[i]; s[k] = 0; beg = atoi(s + name_end + 1); for (i = name_end + 1; i != k; ++i) if (s[i] == '-') break; end = i < k? atoi(s + i + 1) : val.len; if (beg > 0) --beg; } else beg = 0, end = val.len; if (beg >= val.len) beg = val.len; if (end >= val.len) end = val.len; if (beg > end) beg = end; free(s); // now retrieve the sequence l = 0; s = (char*)malloc(end - beg + 2); razf_seek(fai->rz, val.offset + beg / val.line_blen * val.line_len + beg % val.line_blen, SEEK_SET); while (razf_read(fai->rz, &c, 1) == 1 && l < end - beg && !fai->rz->z_err) if (isgraph(c)) s[l++] = c; s[l] = '\0'; *len = l; return s; } int faidx_main(int argc, char *argv[]) { if (argc == 1) { fprintf(stderr, "Usage: faidx <in.fasta> [<reg> [...]]\n"); return 1; } else { if (argc == 2) fai_build(argv[1]); else { int i, j, k, l; char *s; faidx_t *fai; fai = fai_load(argv[1]); if (fai == 0) return 1; for (i = 2; i != argc; ++i) { printf(">%s\n", argv[i]); s = fai_fetch(fai, argv[i], &l); for (j = 0; j < l; j += 60) { for (k = 0; k < 60 && k < l - j; ++k) putchar(s[j + k]); putchar('\n'); } free(s); } fai_destroy(fai); } } return 0; } int faidx_fetch_nseq(const faidx_t *fai) { return fai->n; } char *faidx_fetch_seq(const faidx_t *fai, char *c_name, int p_beg_i, int p_end_i, int *len) { int l; char c; khiter_t iter; faidx1_t val; char *seq=NULL; // Adjust position iter = kh_get(s, fai->hash, c_name); if(iter == kh_end(fai->hash)) return 0; val = kh_value(fai->hash, iter); if(p_end_i < p_beg_i) p_beg_i = p_end_i; if(p_beg_i < 0) p_beg_i = 0; else if(val.len <= p_beg_i) p_beg_i = val.len - 1; if(p_end_i < 0) p_end_i = 0; else if(val.len <= p_end_i) p_end_i = val.len - 1; // Now retrieve the sequence l = 0; seq = (char*)malloc(p_end_i - p_beg_i + 2); razf_seek(fai->rz, val.offset + p_beg_i / val.line_blen * val.line_len + p_beg_i % val.line_blen, SEEK_SET); while (razf_read(fai->rz, &c, 1) == 1 && l < p_end_i - p_beg_i + 1) if (isgraph(c)) seq[l++] = c; seq[l] = '\0'; *len = l; return seq; } #ifdef FAIDX_MAIN int main(int argc, char *argv[]) { return faidx_main(argc, argv); } #endif
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/kaln.h
.h
2,072
68
/* The MIT License Copyright (c) 2003-2006, 2008, 2009 by Heng Li <lh3@live.co.uk> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef LH3_KALN_H_ #define LH3_KALN_H_ #include <stdint.h> #define MINOR_INF -1073741823 typedef struct { int gap_open; int gap_ext; int gap_end_open; int gap_end_ext; int *matrix; int row; int band_width; } ka_param_t; typedef struct { int iio, iie, ido, ide; int eio, eie, edo, ede; int *matrix; int row; int band_width; } ka_param2_t; #ifdef __cplusplus extern "C" { #endif uint32_t *ka_global_core(uint8_t *seq1, int len1, uint8_t *seq2, int len2, const ka_param_t *ap, int *_score, int *n_cigar); int ka_global_score(const uint8_t *_seq1, int len1, const uint8_t *_seq2, int len2, const ka_param2_t *ap); #ifdef __cplusplus } #endif extern ka_param_t ka_param_blast; /* = { 5, 2, 5, 2, aln_sm_blast, 5, 50 }; */ extern ka_param_t ka_param_qual; // only use this for global alignment!!! extern ka_param2_t ka_param2_qual; // only use this for global alignment!!! #endif
Unknown
2D
mitenjain/nanopore
submodules/samtools-0.1.19/padding.c
.c
17,140
480
#include <string.h> #include <assert.h> #include <unistd.h> #include "kstring.h" #include "sam_header.h" #include "sam.h" #include "bam.h" #include "faidx.h" bam_header_t *bam_header_dup(const bam_header_t *h0); /*in sam.c*/ static void replace_cigar(bam1_t *b, int n, uint32_t *cigar) { if (n != b->core.n_cigar) { int o = b->core.l_qname + b->core.n_cigar * 4; if (b->data_len + (n - b->core.n_cigar) * 4 > b->m_data) { b->m_data = b->data_len + (n - b->core.n_cigar) * 4; kroundup32(b->m_data); b->data = (uint8_t*)realloc(b->data, b->m_data); } memmove(b->data + b->core.l_qname + n * 4, b->data + o, b->data_len - o); memcpy(b->data + b->core.l_qname, cigar, n * 4); b->data_len += (n - b->core.n_cigar) * 4; b->core.n_cigar = n; } else memcpy(b->data + b->core.l_qname, cigar, n * 4); } #define write_cigar(_c, _n, _m, _v) do { \ if (_n == _m) { \ _m = _m? _m<<1 : 4; \ _c = (uint32_t*)realloc(_c, _m * 4); \ } \ _c[_n++] = (_v); \ } while (0) static void unpad_seq(bam1_t *b, kstring_t *s) { int k, j, i; int length; uint32_t *cigar = bam1_cigar(b); uint8_t *seq = bam1_seq(b); // b->core.l_qseq gives length of the SEQ entry (including soft clips, S) // We need the padded length after alignment from the CIGAR (excluding // soft clips S, but including pads from CIGAR D operations) length = 0; for (k = 0; k < b->core.n_cigar; ++k) { int op, ol; op= bam_cigar_op(cigar[k]); ol = bam_cigar_oplen(cigar[k]); if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF || op == BAM_CDEL) length += ol; } ks_resize(s, length); for (k = 0, s->l = 0, j = 0; k < b->core.n_cigar; ++k) { int op, ol; op = bam_cigar_op(cigar[k]); ol = bam_cigar_oplen(cigar[k]); if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) { for (i = 0; i < ol; ++i, ++j) s->s[s->l++] = bam1_seqi(seq, j); } else if (op == BAM_CSOFT_CLIP) { j += ol; } else if (op == BAM_CHARD_CLIP) { /* do nothing */ } else if (op == BAM_CDEL) { for (i = 0; i < ol; ++i) s->s[s->l++] = 0; } else { fprintf(stderr, "[depad] ERROR: Didn't expect CIGAR op %c in read %s\n", BAM_CIGAR_STR[op], bam1_qname(b)); assert(-1); } } assert(length == s->l); } int load_unpadded_ref(faidx_t *fai, char *ref_name, int ref_len, kstring_t *seq) { char base; char *fai_ref = 0; int fai_ref_len = 0, k; fai_ref = fai_fetch(fai, ref_name, &fai_ref_len); if (fai_ref_len != ref_len) { fprintf(stderr, "[depad] ERROR: FASTA sequence %s length %i, expected %i\n", ref_name, fai_ref_len, ref_len); free(fai_ref); return -1; } ks_resize(seq, ref_len); seq->l = 0; for (k = 0; k < ref_len; ++k) { base = fai_ref[k]; if (base == '-' || base == '*') { // Map gaps to null to match unpad_seq function seq->s[seq->l++] = 0; } else { int i = bam_nt16_table[(int)base]; if (i == 0 || i==16) { // Equals maps to 0, anything unexpected to 16 fprintf(stderr, "[depad] ERROR: Invalid character %c (ASCII %i) in FASTA sequence %s\n", base, (int)base, ref_name); free(fai_ref); return -1; } seq->s[seq->l++] = i; } } assert(ref_len == seq->l); free(fai_ref); return 0; } int get_unpadded_len(faidx_t *fai, char *ref_name, int padded_len) { char base; char *fai_ref = 0; int fai_ref_len = 0, k; int bases=0, gaps=0; fai_ref = fai_fetch(fai, ref_name, &fai_ref_len); if (fai_ref_len != padded_len) { fprintf(stderr, "[depad] ERROR: FASTA sequence '%s' length %i, expected %i\n", ref_name, fai_ref_len, padded_len); free(fai_ref); return -1; } for (k = 0; k < padded_len; ++k) { //fprintf(stderr, "[depad] checking base %i of %i or %i\n", k+1, ref_len, strlen(fai_ref)); base = fai_ref[k]; if (base == '-' || base == '*') { gaps += 1; } else { int i = bam_nt16_table[(int)base]; if (i == 0 || i==16) { // Equals maps to 0, anything unexpected to 16 fprintf(stderr, "[depad] ERROR: Invalid character %c (ASCII %i) in FASTA sequence '%s'\n", base, (int)base, ref_name); free(fai_ref); return -1; } bases += 1; } } free(fai_ref); assert (padded_len == bases + gaps); return bases; } inline int * update_posmap(int *posmap, kstring_t ref) { int i, k; posmap = realloc(posmap, ref.m * sizeof(int)); for (i = k = 0; i < ref.l; ++i) { posmap[i] = k; if (ref.s[i]) ++k; } return posmap; } int bam_pad2unpad(samfile_t *in, samfile_t *out, faidx_t *fai) { bam_header_t *h = 0; bam1_t *b = 0; kstring_t r, q; int r_tid = -1; uint32_t *cigar2 = 0; int ret = 0, n2 = 0, m2 = 0, *posmap = 0; b = bam_init1(); r.l = r.m = q.l = q.m = 0; r.s = q.s = 0; int read_ret; h = in->header; while ((read_ret = samread(in, b)) >= 0) { // read one alignment from `in' uint32_t *cigar = bam1_cigar(b); n2 = 0; if (b->core.pos == 0 && b->core.tid >= 0 && strcmp(bam1_qname(b), h->target_name[b->core.tid]) == 0) { // fprintf(stderr, "[depad] Found embedded reference '%s'\n", bam1_qname(b)); r_tid = b->core.tid; unpad_seq(b, &r); if (h->target_len[r_tid] != r.l) { fprintf(stderr, "[depad] ERROR: (Padded) length of '%s' is %d in BAM header, but %ld in embedded reference\n", bam1_qname(b), h->target_len[r_tid], r.l); return -1; } if (fai) { // Check the embedded reference matches the FASTA file if (load_unpadded_ref(fai, h->target_name[b->core.tid], h->target_len[b->core.tid], &q)) { fprintf(stderr, "[depad] ERROR: Failed to load embedded reference '%s' from FASTA\n", h->target_name[b->core.tid]); return -1; } assert(r.l == q.l); int i; for (i = 0; i < r.l; ++i) { if (r.s[i] != q.s[i]) { // Show gaps as ASCII 45 fprintf(stderr, "[depad] ERROR: Embedded sequence and reference FASTA don't match for %s base %i, '%c' vs '%c'\n", h->target_name[b->core.tid], i+1, r.s[i] ? bam_nt16_rev_table[(int)r.s[i]] : 45, q.s[i] ? bam_nt16_rev_table[(int)q.s[i]] : 45); return -1; } } } write_cigar(cigar2, n2, m2, bam_cigar_gen(b->core.l_qseq, BAM_CMATCH)); replace_cigar(b, n2, cigar2); posmap = update_posmap(posmap, r); } else if (b->core.n_cigar > 0) { int i, k, op; if (b->core.tid < 0) { fprintf(stderr, "[depad] ERROR: Read '%s' has CIGAR but no RNAME\n", bam1_qname(b)); return -1; } else if (b->core.tid == r_tid) { ; // good case, reference available //fprintf(stderr, "[depad] Have ref '%s' for read '%s'\n", h->target_name[b->core.tid], bam1_qname(b)); } else if (fai) { if (load_unpadded_ref(fai, h->target_name[b->core.tid], h->target_len[b->core.tid], &r)) { fprintf(stderr, "[depad] ERROR: Failed to load '%s' from reference FASTA\n", h->target_name[b->core.tid]); return -1; } posmap = update_posmap(posmap, r); r_tid = b->core.tid; // fprintf(stderr, "[depad] Loaded %s from FASTA file\n", h->target_name[b->core.tid]); } else { fprintf(stderr, "[depad] ERROR: Missing %s embedded reference sequence (and no FASTA file)\n", h->target_name[b->core.tid]); return -1; } unpad_seq(b, &q); if (bam_cigar_op(cigar[0]) == BAM_CSOFT_CLIP) { write_cigar(cigar2, n2, m2, cigar[0]); } else if (bam_cigar_op(cigar[0]) == BAM_CHARD_CLIP) { write_cigar(cigar2, n2, m2, cigar[0]); if (b->core.n_cigar > 2 && bam_cigar_op(cigar[1]) == BAM_CSOFT_CLIP) { write_cigar(cigar2, n2, m2, cigar[1]); } } /* Determine CIGAR operator for each base in the aligned read */ for (i = 0, k = b->core.pos; i < q.l; ++i, ++k) q.s[i] = q.s[i]? (r.s[k]? BAM_CMATCH : BAM_CINS) : (r.s[k]? BAM_CDEL : BAM_CPAD); /* Include any pads if starts with an insert */ if (q.s[0] == BAM_CINS) { for (k = 0; k+1 < b->core.pos && !r.s[b->core.pos - k - 1]; ++k); if (k) write_cigar(cigar2, n2, m2, bam_cigar_gen(k, BAM_CPAD)); } /* Count consecutive CIGAR operators to turn into a CIGAR string */ for (i = k = 1, op = q.s[0]; i < q.l; ++i) { if (op != q.s[i]) { write_cigar(cigar2, n2, m2, bam_cigar_gen(k, op)); op = q.s[i]; k = 1; } else ++k; } write_cigar(cigar2, n2, m2, bam_cigar_gen(k, op)); if (bam_cigar_op(cigar[b->core.n_cigar-1]) == BAM_CSOFT_CLIP) { write_cigar(cigar2, n2, m2, cigar[b->core.n_cigar-1]); } else if (bam_cigar_op(cigar[b->core.n_cigar-1]) == BAM_CHARD_CLIP) { if (b->core.n_cigar > 2 && bam_cigar_op(cigar[b->core.n_cigar-2]) == BAM_CSOFT_CLIP) { write_cigar(cigar2, n2, m2, cigar[b->core.n_cigar-2]); } write_cigar(cigar2, n2, m2, cigar[b->core.n_cigar-1]); } /* Remove redundant P operators between M/X/=/D operators, e.g. 5M2P10M -> 15M */ int pre_op, post_op; for (i = 2; i < n2; ++i) if (bam_cigar_op(cigar2[i-1]) == BAM_CPAD) { pre_op = bam_cigar_op(cigar2[i-2]); post_op = bam_cigar_op(cigar2[i]); /* Note don't need to check for X/= as code above will use M only */ if ((pre_op == BAM_CMATCH || pre_op == BAM_CDEL) && (post_op == BAM_CMATCH || post_op == BAM_CDEL)) { /* This is a redundant P operator */ cigar2[i-1] = 0; // i.e. 0M /* If had same operator either side, combine them in post_op */ if (pre_op == post_op) { /* If CIGAR M, could treat as simple integers since BAM_CMATCH is zero*/ cigar2[i] = bam_cigar_gen(bam_cigar_oplen(cigar2[i-2]) + bam_cigar_oplen(cigar2[i]), post_op); cigar2[i-2] = 0; // i.e. 0M } } } /* Remove the zero'd operators (0M) */ for (i = k = 0; i < n2; ++i) if (cigar2[i]) cigar2[k++] = cigar2[i]; n2 = k; replace_cigar(b, n2, cigar2); b->core.pos = posmap[b->core.pos]; if (b->core.mtid < 0 || b->core.mpos < 0) { /* Nice case, no mate to worry about*/ // fprintf(stderr, "[depad] Read '%s' mate not mapped\n", bam1_qname(b)); /* TODO - Warning if FLAG says mate should be mapped? */ /* Clean up funny input where mate position is given but mate reference is missing: */ b->core.mtid = -1; b->core.mpos = -1; } else if (b->core.mtid == b->core.tid) { /* Nice case, same reference */ // fprintf(stderr, "[depad] Read '%s' mate mapped to same ref\n", bam1_qname(b)); b->core.mpos = posmap[b->core.mpos]; } else { /* Nasty case, Must load alternative posmap */ // fprintf(stderr, "[depad] Loading reference '%s' temporarily\n", h->target_name[b->core.mtid]); if (!fai) { fprintf(stderr, "[depad] ERROR: Needed reference %s sequence for mate (and no FASTA file)\n", h->target_name[b->core.mtid]); return -1; } /* Temporarily load the other reference sequence */ if (load_unpadded_ref(fai, h->target_name[b->core.mtid], h->target_len[b->core.mtid], &r)) { fprintf(stderr, "[depad] ERROR: Failed to load '%s' from reference FASTA\n", h->target_name[b->core.mtid]); return -1; } posmap = update_posmap(posmap, r); b->core.mpos = posmap[b->core.mpos]; /* Restore the reference and posmap*/ if (load_unpadded_ref(fai, h->target_name[b->core.tid], h->target_len[b->core.tid], &r)) { fprintf(stderr, "[depad] ERROR: Failed to load '%s' from reference FASTA\n", h->target_name[b->core.tid]); return -1; } posmap = update_posmap(posmap, r); } } samwrite(out, b); } if (read_ret < -1) { fprintf(stderr, "[depad] truncated file.\n"); ret = 1; } free(r.s); free(q.s); free(posmap); bam_destroy1(b); return ret; } bam_header_t * fix_header(bam_header_t *old, faidx_t *fai) { int i = 0, unpadded_len = 0; bam_header_t *header = 0 ; header = bam_header_dup(old); for (i = 0; i < old->n_targets; ++i) { unpadded_len = get_unpadded_len(fai, old->target_name[i], old->target_len[i]); if (unpadded_len < 0) { fprintf(stderr, "[depad] ERROR getting unpadded length of '%s', padded length %i\n", old->target_name[i], old->target_len[i]); } else { header->target_len[i] = unpadded_len; //fprintf(stderr, "[depad] Recalculating '%s' length %i -> %i\n", old->target_name[i], old->target_len[i], header->target_len[i]); } } /* Duplicating the header allocated new buffer for header string */ /* After modifying the @SQ lines it will only get smaller, since */ /* the LN entries will be the same or shorter, and we'll remove */ /* any MD entries (MD5 checksums). */ assert(strlen(old->text) == strlen(header->text)); assert (0==strcmp(old->text, header->text)); const char *text; text = old->text; header->text[0] = '\0'; /* Resuse the allocated buffer */ char * newtext = header->text; char * end=NULL; while (text[0]=='@') { end = strchr(text, '\n'); assert(end != 0); if (text[1]=='S' && text[2]=='Q' && text[3]=='\t') { /* TODO - edit the @SQ line here to remove MD and fix LN. */ /* For now just remove the @SQ line, and samtools will */ /* automatically generate a minimal replacement with LN. */ /* However, that discards any other tags like AS, SP, UR. */ //fprintf(stderr, "[depad] Removing @SQ line\n"); } else { /* Copy this line to the new header */ strncat(newtext, text, end - text + 1); } text = end + 1; } assert (text[0]=='\0'); /* Check we didn't overflow the buffer */ assert (strlen(header->text) <= strlen(old->text)); if (strlen(header->text) < header->l_text) { //fprintf(stderr, "[depad] Reallocating header buffer\n"); assert (newtext == header->text); newtext = malloc(strlen(header->text) + 1); strcpy(newtext, header->text); free(header->text); header->text = newtext; header->l_text = strlen(newtext); } //fprintf(stderr, "[depad] Here is the new header (pending @SQ lines),\n\n%s\n(end)\n", header->text); return header; } static int usage(int is_long_help); int main_pad2unpad(int argc, char *argv[]) { samfile_t *in = 0, *out = 0; bam_header_t *h = 0; faidx_t *fai = 0; int c, is_bamin = 1, compress_level = -1, is_bamout = 1, is_long_help = 0; char in_mode[5], out_mode[5], *fn_out = 0, *fn_list = 0, *fn_ref = 0; int ret=0; /* parse command-line options */ strcpy(in_mode, "r"); strcpy(out_mode, "w"); while ((c = getopt(argc, argv, "Sso:u1T:?")) >= 0) { switch (c) { case 'S': is_bamin = 0; break; case 's': assert(compress_level == -1); is_bamout = 0; break; case 'o': fn_out = strdup(optarg); break; case 'u': assert(is_bamout == 1); compress_level = 0; break; case '1': assert(is_bamout == 1); compress_level = 1; break; case 'T': fn_ref = strdup(optarg); break; case '?': is_long_help = 1; break; default: return usage(is_long_help); } } if (argc == optind) return usage(is_long_help); if (is_bamin) strcat(in_mode, "b"); if (is_bamout) strcat(out_mode, "b"); strcat(out_mode, "h"); if (compress_level >= 0) { char tmp[2]; tmp[0] = compress_level + '0'; tmp[1] = '\0'; strcat(out_mode, tmp); } // Load FASTA reference (also needed for SAM -> BAM if missing header) if (fn_ref) { fn_list = samfaipath(fn_ref); fai = fai_load(fn_ref); } // open file handlers if ((in = samopen(argv[optind], in_mode, fn_list)) == 0) { fprintf(stderr, "[depad] failed to open \"%s\" for reading.\n", argv[optind]); ret = 1; goto depad_end; } if (in->header == 0) { fprintf(stderr, "[depad] failed to read the header from \"%s\".\n", argv[optind]); ret = 1; goto depad_end; } if (in->header->text == 0 || in->header->l_text == 0) { fprintf(stderr, "[depad] Warning - failed to read any header text from \"%s\".\n", argv[optind]); assert (0 == in->header->l_text); assert (0 == in->header->text); } if (fn_ref) { h = fix_header(in->header, fai); } else { fprintf(stderr, "[depad] Warning - reference lengths will not be corrected without FASTA reference\n"); h = in->header; } if ((out = samopen(fn_out? fn_out : "-", out_mode, h)) == 0) { fprintf(stderr, "[depad] failed to open \"%s\" for writing.\n", fn_out? fn_out : "standard output"); ret = 1; goto depad_end; } // Do the depad ret = bam_pad2unpad(in, out, fai); depad_end: // close files, free and return if (fai) fai_destroy(fai); if (h != in->header) bam_header_destroy(h); samclose(in); samclose(out); free(fn_list); free(fn_out); return ret; } static int usage(int is_long_help) { fprintf(stderr, "\n"); fprintf(stderr, "Usage: samtools depad <in.bam>\n\n"); fprintf(stderr, "Options: -s output is SAM (default is BAM)\n"); fprintf(stderr, " -S input is SAM (default is BAM)\n"); fprintf(stderr, " -u uncompressed BAM output (can't use with -s)\n"); fprintf(stderr, " -1 fast compression BAM output (can't use with -s)\n"); fprintf(stderr, " -T FILE reference sequence file [null]\n"); fprintf(stderr, " -o FILE output file name [stdout]\n"); fprintf(stderr, " -? longer help\n"); fprintf(stderr, "\n"); if (is_long_help) fprintf(stderr, "Notes:\n\ \n\ 1. Requires embedded reference sequences (before the reads for that reference),\n\ with the future aim to also support a FASTA padded reference sequence file.\n\ \n\ 2. The input padded alignment read's CIGAR strings must not use P or I operators.\n\ \n"); return 1; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bedidx.c
.c
3,882
163
#include <stdlib.h> #include <stdint.h> #include <string.h> #include <stdio.h> #include <zlib.h> #ifdef _WIN32 #define drand48() ((double)rand() / RAND_MAX) #endif #include "ksort.h" KSORT_INIT_GENERIC(uint64_t) #include "kseq.h" KSTREAM_INIT(gzFile, gzread, 8192) typedef struct { int n, m; uint64_t *a; int *idx; } bed_reglist_t; #include "khash.h" KHASH_MAP_INIT_STR(reg, bed_reglist_t) #define LIDX_SHIFT 13 typedef kh_reg_t reghash_t; int *bed_index_core(int n, uint64_t *a, int *n_idx) { int i, j, m, *idx; m = *n_idx = 0; idx = 0; for (i = 0; i < n; ++i) { int beg, end; beg = a[i]>>32 >> LIDX_SHIFT; end = ((uint32_t)a[i]) >> LIDX_SHIFT; if (m < end + 1) { int oldm = m; m = end + 1; kroundup32(m); idx = realloc(idx, m * sizeof(int)); for (j = oldm; j < m; ++j) idx[j] = -1; } if (beg == end) { if (idx[beg] < 0) idx[beg] = i; } else { for (j = beg; j <= end; ++j) if (idx[j] < 0) idx[j] = i; } *n_idx = end + 1; } return idx; } void bed_index(void *_h) { reghash_t *h = (reghash_t*)_h; khint_t k; for (k = 0; k < kh_end(h); ++k) { if (kh_exist(h, k)) { bed_reglist_t *p = &kh_val(h, k); if (p->idx) free(p->idx); ks_introsort(uint64_t, p->n, p->a); p->idx = bed_index_core(p->n, p->a, &p->m); } } } int bed_overlap_core(const bed_reglist_t *p, int beg, int end) { int i, min_off; if (p->n == 0) return 0; min_off = (beg>>LIDX_SHIFT >= p->n)? p->idx[p->n-1] : p->idx[beg>>LIDX_SHIFT]; if (min_off < 0) { // TODO: this block can be improved, but speed should not matter too much here int n = beg>>LIDX_SHIFT; if (n > p->n) n = p->n; for (i = n - 1; i >= 0; --i) if (p->idx[i] >= 0) break; min_off = i >= 0? p->idx[i] : 0; } for (i = min_off; i < p->n; ++i) { if ((int)(p->a[i]>>32) >= end) break; // out of range; no need to proceed if ((int32_t)p->a[i] > beg && (int32_t)(p->a[i]>>32) < end) return 1; // find the overlap; return } return 0; } int bed_overlap(const void *_h, const char *chr, int beg, int end) { const reghash_t *h = (const reghash_t*)_h; khint_t k; if (!h) return 0; k = kh_get(reg, h, chr); if (k == kh_end(h)) return 0; return bed_overlap_core(&kh_val(h, k), beg, end); } void *bed_read(const char *fn) { reghash_t *h = kh_init(reg); gzFile fp; kstream_t *ks; int dret; kstring_t *str; // read the list fp = strcmp(fn, "-")? gzopen(fn, "r") : gzdopen(fileno(stdin), "r"); if (fp == 0) return 0; str = calloc(1, sizeof(kstring_t)); ks = ks_init(fp); while (ks_getuntil(ks, 0, str, &dret) >= 0) { // read the chr name int beg = -1, end = -1; bed_reglist_t *p; khint_t k = kh_get(reg, h, str->s); if (k == kh_end(h)) { // absent from the hash table int ret; char *s = strdup(str->s); k = kh_put(reg, h, s, &ret); memset(&kh_val(h, k), 0, sizeof(bed_reglist_t)); } p = &kh_val(h, k); if (dret != '\n') { // if the lines has other characters if (ks_getuntil(ks, 0, str, &dret) > 0 && isdigit(str->s[0])) { beg = atoi(str->s); // begin if (dret != '\n') { if (ks_getuntil(ks, 0, str, &dret) > 0 && isdigit(str->s[0])) { end = atoi(str->s); // end if (end < beg) end = -1; } } } } if (dret != '\n') while ((dret = ks_getc(ks)) > 0 && dret != '\n'); // skip the rest of the line if (end < 0 && beg > 0) end = beg, beg = beg - 1; // if there is only one column if (beg >= 0 && end > beg) { if (p->n == p->m) { p->m = p->m? p->m<<1 : 4; p->a = realloc(p->a, p->m * 8); } p->a[p->n++] = (uint64_t)beg<<32 | end; } } ks_destroy(ks); gzclose(fp); free(str->s); free(str); bed_index(h); return h; } void bed_destroy(void *_h) { reghash_t *h = (reghash_t*)_h; khint_t k; for (k = 0; k < kh_end(h); ++k) { if (kh_exist(h, k)) { free(kh_val(h, k).a); free(kh_val(h, k).idx); free((char*)kh_key(h, k)); } } kh_destroy(reg, h); }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/sam_header.c
.c
21,248
811
#include "sam_header.h" #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <stdarg.h> #include "khash.h" KHASH_MAP_INIT_STR(str, const char *) struct _HeaderList { struct _HeaderList *last; // Hack: Used and maintained only by list_append_to_end. Maintained in the root node only. struct _HeaderList *next; void *data; }; typedef struct _HeaderList list_t; typedef list_t HeaderDict; typedef struct { char key[2]; char *value; } HeaderTag; typedef struct { char type[2]; list_t *tags; } HeaderLine; const char *o_hd_tags[] = {"SO","GO",NULL}; const char *r_hd_tags[] = {"VN",NULL}; const char *o_sq_tags[] = {"AS","M5","UR","SP",NULL}; const char *r_sq_tags[] = {"SN","LN",NULL}; const char *u_sq_tags[] = {"SN",NULL}; const char *o_rg_tags[] = {"CN","DS","DT","FO","KS","LB","PG","PI","PL","PU","SM",NULL}; const char *r_rg_tags[] = {"ID",NULL}; const char *u_rg_tags[] = {"ID",NULL}; const char *o_pg_tags[] = {"VN","CL",NULL}; const char *r_pg_tags[] = {"ID",NULL}; const char *types[] = {"HD","SQ","RG","PG","CO",NULL}; const char **optional_tags[] = {o_hd_tags,o_sq_tags,o_rg_tags,o_pg_tags,NULL,NULL}; const char **required_tags[] = {r_hd_tags,r_sq_tags,r_rg_tags,r_pg_tags,NULL,NULL}; const char **unique_tags[] = {NULL, u_sq_tags,u_rg_tags,NULL,NULL,NULL}; static void debug(const char *format, ...) { va_list ap; va_start(ap, format); vfprintf(stderr, format, ap); va_end(ap); } #if 0 // Replaced by list_append_to_end static list_t *list_prepend(list_t *root, void *data) { list_t *l = malloc(sizeof(list_t)); l->next = root; l->data = data; return l; } #endif // Relies on the root->last being correct. Do not use with the other list_* // routines unless they are fixed to modify root->last as well. static list_t *list_append_to_end(list_t *root, void *data) { list_t *l = malloc(sizeof(list_t)); l->last = l; l->next = NULL; l->data = data; if ( !root ) return l; root->last->next = l; root->last = l; return root; } static list_t *list_append(list_t *root, void *data) { list_t *l = root; while (l && l->next) l = l->next; if ( l ) { l->next = malloc(sizeof(list_t)); l = l->next; } else { l = malloc(sizeof(list_t)); root = l; } l->data = data; l->next = NULL; return root; } static void list_free(list_t *root) { list_t *l = root; while (root) { l = root; root = root->next; free(l); } } // Look for a tag "XY" in a predefined const char *[] array. static int tag_exists(const char *tag, const char **tags) { int itag=0; if ( !tags ) return -1; while ( tags[itag] ) { if ( tags[itag][0]==tag[0] && tags[itag][1]==tag[1] ) return itag; itag++; } return -1; } // Mimics the behaviour of getline, except it returns pointer to the next chunk of the text // or NULL if everything has been read. The lineptr should be freed by the caller. The // newline character is stripped. static const char *nextline(char **lineptr, size_t *n, const char *text) { int len; const char *to = text; if ( !*to ) return NULL; while ( *to && *to!='\n' && *to!='\r' ) to++; len = to - text + 1; if ( *to ) { // Advance the pointer for the next call if ( *to=='\n' ) to++; else if ( *to=='\r' && *(to+1)=='\n' ) to+=2; } if ( !len ) return to; if ( !*lineptr ) { *lineptr = malloc(len); *n = len; } else if ( *n<len ) { *lineptr = realloc(*lineptr, len); *n = len; } if ( !*lineptr ) { debug("[nextline] Insufficient memory!\n"); return 0; } memcpy(*lineptr,text,len); (*lineptr)[len-1] = 0; return to; } // name points to "XY", value_from points to the first character of the value string and // value_to points to the last character of the value string. static HeaderTag *new_tag(const char *name, const char *value_from, const char *value_to) { HeaderTag *tag = malloc(sizeof(HeaderTag)); int len = value_to-value_from+1; tag->key[0] = name[0]; tag->key[1] = name[1]; tag->value = malloc(len+1); memcpy(tag->value,value_from,len+1); tag->value[len] = 0; return tag; } static HeaderTag *header_line_has_tag(HeaderLine *hline, const char *key) { list_t *tags = hline->tags; while (tags) { HeaderTag *tag = tags->data; if ( tag->key[0]==key[0] && tag->key[1]==key[1] ) return tag; tags = tags->next; } return NULL; } // Return codes: // 0 .. different types or unique tags differ or conflicting tags, cannot be merged // 1 .. all tags identical -> no need to merge, drop one // 2 .. the unique tags match and there are some conflicting tags (same tag, different value) -> error, cannot be merged nor duplicated // 3 .. there are some missing complementary tags and no unique conflict -> can be merged into a single line static int sam_header_compare_lines(HeaderLine *hline1, HeaderLine *hline2) { HeaderTag *t1, *t2; if ( hline1->type[0]!=hline2->type[0] || hline1->type[1]!=hline2->type[1] ) return 0; int itype = tag_exists(hline1->type,types); if ( itype==-1 ) { debug("[sam_header_compare_lines] Unknown type [%c%c]\n", hline1->type[0],hline1->type[1]); return -1; // FIXME (lh3): error; I do not know how this will be handled in Petr's code } if ( unique_tags[itype] ) { t1 = header_line_has_tag(hline1,unique_tags[itype][0]); t2 = header_line_has_tag(hline2,unique_tags[itype][0]); if ( !t1 || !t2 ) // this should never happen, the unique tags are required return 2; if ( strcmp(t1->value,t2->value) ) return 0; // the unique tags differ, cannot be merged } if ( !required_tags[itype] && !optional_tags[itype] ) { t1 = hline1->tags->data; t2 = hline2->tags->data; if ( !strcmp(t1->value,t2->value) ) return 1; // identical comments return 0; } int missing=0, itag=0; while ( required_tags[itype] && required_tags[itype][itag] ) { t1 = header_line_has_tag(hline1,required_tags[itype][itag]); t2 = header_line_has_tag(hline2,required_tags[itype][itag]); if ( !t1 && !t2 ) return 2; // this should never happen else if ( !t1 || !t2 ) missing = 1; // there is some tag missing in one of the hlines else if ( strcmp(t1->value,t2->value) ) { if ( unique_tags[itype] ) return 2; // the lines have a matching unique tag but have a conflicting tag return 0; // the lines contain conflicting tags, cannot be merged } itag++; } itag = 0; while ( optional_tags[itype] && optional_tags[itype][itag] ) { t1 = header_line_has_tag(hline1,optional_tags[itype][itag]); t2 = header_line_has_tag(hline2,optional_tags[itype][itag]); if ( !t1 && !t2 ) { itag++; continue; } if ( !t1 || !t2 ) missing = 1; // there is some tag missing in one of the hlines else if ( strcmp(t1->value,t2->value) ) { if ( unique_tags[itype] ) return 2; // the lines have a matching unique tag but have a conflicting tag return 0; // the lines contain conflicting tags, cannot be merged } itag++; } if ( missing ) return 3; // there are some missing complementary tags with no conflicts, can be merged return 1; } static HeaderLine *sam_header_line_clone(const HeaderLine *hline) { list_t *tags; HeaderLine *out = malloc(sizeof(HeaderLine)); out->type[0] = hline->type[0]; out->type[1] = hline->type[1]; out->tags = NULL; tags = hline->tags; while (tags) { HeaderTag *old = tags->data; HeaderTag *new = malloc(sizeof(HeaderTag)); new->key[0] = old->key[0]; new->key[1] = old->key[1]; new->value = strdup(old->value); out->tags = list_append(out->tags, new); tags = tags->next; } return out; } static int sam_header_line_merge_with(HeaderLine *out_hline, const HeaderLine *tmpl_hline) { list_t *tmpl_tags; if ( out_hline->type[0]!=tmpl_hline->type[0] || out_hline->type[1]!=tmpl_hline->type[1] ) return 0; tmpl_tags = tmpl_hline->tags; while (tmpl_tags) { HeaderTag *tmpl_tag = tmpl_tags->data; HeaderTag *out_tag = header_line_has_tag(out_hline, tmpl_tag->key); if ( !out_tag ) { HeaderTag *tag = malloc(sizeof(HeaderTag)); tag->key[0] = tmpl_tag->key[0]; tag->key[1] = tmpl_tag->key[1]; tag->value = strdup(tmpl_tag->value); out_hline->tags = list_append(out_hline->tags,tag); } tmpl_tags = tmpl_tags->next; } return 1; } static HeaderLine *sam_header_line_parse(const char *headerLine) { HeaderLine *hline; HeaderTag *tag; const char *from, *to; from = headerLine; if ( *from != '@' ) { debug("[sam_header_line_parse] expected '@', got [%s]\n", headerLine); return 0; } to = ++from; while (*to && *to!='\t') to++; if ( to-from != 2 ) { debug("[sam_header_line_parse] expected '@XY', got [%s]\nHint: The header tags must be tab-separated.\n", headerLine); return 0; } hline = malloc(sizeof(HeaderLine)); hline->type[0] = from[0]; hline->type[1] = from[1]; hline->tags = NULL; int itype = tag_exists(hline->type, types); from = to; while (*to && *to=='\t') to++; if ( to-from != 1 ) { debug("[sam_header_line_parse] multiple tabs on line [%s] (%d)\n", headerLine,(int)(to-from)); free(hline); return 0; } from = to; while (*from) { while (*to && *to!='\t') to++; if ( !required_tags[itype] && !optional_tags[itype] ) { // CO is a special case, it can contain anything, including tabs if ( *to ) { to++; continue; } tag = new_tag(" ",from,to-1); } else tag = new_tag(from,from+3,to-1); if ( header_line_has_tag(hline,tag->key) ) debug("The tag '%c%c' present (at least) twice on line [%s]\n", tag->key[0],tag->key[1], headerLine); hline->tags = list_append(hline->tags, tag); from = to; while (*to && *to=='\t') to++; if ( *to && to-from != 1 ) { debug("[sam_header_line_parse] multiple tabs on line [%s] (%d)\n", headerLine,(int)(to-from)); return 0; } from = to; } return hline; } // Must be of an existing type, all tags must be recognised and all required tags must be present static int sam_header_line_validate(HeaderLine *hline) { list_t *tags; HeaderTag *tag; int itype, itag; // Is the type correct? itype = tag_exists(hline->type, types); if ( itype==-1 ) { debug("The type [%c%c] not recognised.\n", hline->type[0],hline->type[1]); return 0; } // Has all required tags? itag = 0; while ( required_tags[itype] && required_tags[itype][itag] ) { if ( !header_line_has_tag(hline,required_tags[itype][itag]) ) { debug("The tag [%c%c] required for [%c%c] not present.\n", required_tags[itype][itag][0],required_tags[itype][itag][1], hline->type[0],hline->type[1]); return 0; } itag++; } // Are all tags recognised? tags = hline->tags; while ( tags ) { tag = tags->data; if ( !tag_exists(tag->key,required_tags[itype]) && !tag_exists(tag->key,optional_tags[itype]) ) { // Lower case tags are user-defined values. if( !(islower(tag->key[0]) || islower(tag->key[1])) ) { // Neither is lower case, but tag was not recognized. debug("Unknown tag [%c%c] for [%c%c].\n", tag->key[0],tag->key[1], hline->type[0],hline->type[1]); // return 0; // Even unknown tags are allowed - for forward compatibility with new attributes } // else - allow user defined tag } tags = tags->next; } return 1; } static void print_header_line(FILE *fp, HeaderLine *hline) { list_t *tags = hline->tags; HeaderTag *tag; fprintf(fp, "@%c%c", hline->type[0],hline->type[1]); while (tags) { tag = tags->data; fprintf(fp, "\t"); if ( tag->key[0]!=' ' || tag->key[1]!=' ' ) fprintf(fp, "%c%c:", tag->key[0],tag->key[1]); fprintf(fp, "%s", tag->value); tags = tags->next; } fprintf(fp,"\n"); } static void sam_header_line_free(HeaderLine *hline) { list_t *tags = hline->tags; while (tags) { HeaderTag *tag = tags->data; free(tag->value); free(tag); tags = tags->next; } list_free(hline->tags); free(hline); } void sam_header_free(void *_header) { HeaderDict *header = (HeaderDict*)_header; list_t *hlines = header; while (hlines) { sam_header_line_free(hlines->data); hlines = hlines->next; } list_free(header); } HeaderDict *sam_header_clone(const HeaderDict *dict) { HeaderDict *out = NULL; while (dict) { HeaderLine *hline = dict->data; out = list_append(out, sam_header_line_clone(hline)); dict = dict->next; } return out; } // Returns a newly allocated string char *sam_header_write(const void *_header) { const HeaderDict *header = (const HeaderDict*)_header; char *out = NULL; int len=0, nout=0; const list_t *hlines; // Calculate the length of the string to allocate hlines = header; while (hlines) { len += 4; // @XY and \n HeaderLine *hline = hlines->data; list_t *tags = hline->tags; while (tags) { HeaderTag *tag = tags->data; len += strlen(tag->value) + 1; // \t if ( tag->key[0]!=' ' || tag->key[1]!=' ' ) len += strlen(tag->value) + 3; // XY: tags = tags->next; } hlines = hlines->next; } nout = 0; out = malloc(len+1); hlines = header; while (hlines) { HeaderLine *hline = hlines->data; nout += sprintf(out+nout,"@%c%c",hline->type[0],hline->type[1]); list_t *tags = hline->tags; while (tags) { HeaderTag *tag = tags->data; nout += sprintf(out+nout,"\t"); if ( tag->key[0]!=' ' || tag->key[1]!=' ' ) nout += sprintf(out+nout,"%c%c:", tag->key[0],tag->key[1]); nout += sprintf(out+nout,"%s", tag->value); tags = tags->next; } hlines = hlines->next; nout += sprintf(out+nout,"\n"); } out[len] = 0; return out; } void *sam_header_parse2(const char *headerText) { list_t *hlines = NULL; HeaderLine *hline; const char *text; char *buf=NULL; size_t nbuf = 0; int tovalidate = 0; if ( !headerText ) return 0; text = headerText; while ( (text=nextline(&buf, &nbuf, text)) ) { hline = sam_header_line_parse(buf); if ( hline && (!tovalidate || sam_header_line_validate(hline)) ) // With too many (~250,000) reference sequences the header parsing was too slow with list_append. hlines = list_append_to_end(hlines, hline); else { if (hline) sam_header_line_free(hline); sam_header_free(hlines); if ( buf ) free(buf); return NULL; } } if ( buf ) free(buf); return hlines; } void *sam_header2tbl(const void *_dict, char type[2], char key_tag[2], char value_tag[2]) { const HeaderDict *dict = (const HeaderDict*)_dict; const list_t *l = dict; khash_t(str) *tbl = kh_init(str); khiter_t k; int ret; if (_dict == 0) return tbl; // return an empty (not null) hash table while (l) { HeaderLine *hline = l->data; if ( hline->type[0]!=type[0] || hline->type[1]!=type[1] ) { l = l->next; continue; } HeaderTag *key, *value; key = header_line_has_tag(hline,key_tag); value = header_line_has_tag(hline,value_tag); if ( !key || !value ) { l = l->next; continue; } k = kh_get(str, tbl, key->value); if ( k != kh_end(tbl) ) debug("[sam_header_lookup_table] They key %s not unique.\n", key->value); k = kh_put(str, tbl, key->value, &ret); kh_value(tbl, k) = value->value; l = l->next; } return tbl; } char **sam_header2list(const void *_dict, char type[2], char key_tag[2], int *_n) { const HeaderDict *dict = (const HeaderDict*)_dict; const list_t *l = dict; int max, n; char **ret; ret = 0; *_n = max = n = 0; while (l) { HeaderLine *hline = l->data; if ( hline->type[0]!=type[0] || hline->type[1]!=type[1] ) { l = l->next; continue; } HeaderTag *key; key = header_line_has_tag(hline,key_tag); if ( !key ) { l = l->next; continue; } if (n == max) { max = max? max<<1 : 4; ret = realloc(ret, max * sizeof(void*)); } ret[n++] = key->value; l = l->next; } *_n = n; return ret; } void *sam_header2key_val(void *iter, const char type[2], const char key_tag[2], const char value_tag[2], const char **_key, const char **_value) { list_t *l = iter; if ( !l ) return NULL; while (l) { HeaderLine *hline = l->data; if ( hline->type[0]!=type[0] || hline->type[1]!=type[1] ) { l = l->next; continue; } HeaderTag *key, *value; key = header_line_has_tag(hline,key_tag); value = header_line_has_tag(hline,value_tag); if ( !key && !value ) { l = l->next; continue; } *_key = key->value; *_value = value->value; return l->next; } return l; } const char *sam_tbl_get(void *h, const char *key) { khash_t(str) *tbl = (khash_t(str)*)h; khint_t k; k = kh_get(str, tbl, key); return k == kh_end(tbl)? 0 : kh_val(tbl, k); } int sam_tbl_size(void *h) { khash_t(str) *tbl = (khash_t(str)*)h; return h? kh_size(tbl) : 0; } void sam_tbl_destroy(void *h) { khash_t(str) *tbl = (khash_t(str)*)h; kh_destroy(str, tbl); } void *sam_header_merge(int n, const void **_dicts) { const HeaderDict **dicts = (const HeaderDict**)_dicts; HeaderDict *out_dict; int idict, status; if ( n<2 ) return NULL; out_dict = sam_header_clone(dicts[0]); for (idict=1; idict<n; idict++) { const list_t *tmpl_hlines = dicts[idict]; while ( tmpl_hlines ) { list_t *out_hlines = out_dict; int inserted = 0; while ( out_hlines ) { status = sam_header_compare_lines(tmpl_hlines->data, out_hlines->data); if ( status==0 ) { out_hlines = out_hlines->next; continue; } if ( status==2 ) { print_header_line(stderr,tmpl_hlines->data); print_header_line(stderr,out_hlines->data); debug("Conflicting lines, cannot merge the headers.\n"); return 0; } if ( status==3 ) sam_header_line_merge_with(out_hlines->data, tmpl_hlines->data); inserted = 1; break; } if ( !inserted ) out_dict = list_append(out_dict, sam_header_line_clone(tmpl_hlines->data)); tmpl_hlines = tmpl_hlines->next; } } return out_dict; } char **sam_header2tbl_n(const void *dict, const char type[2], const char *tags[], int *n) { int nout = 0; char **out = NULL; *n = 0; list_t *l = (list_t *)dict; if ( !l ) return NULL; int i, ntags = 0; while ( tags[ntags] ) ntags++; while (l) { HeaderLine *hline = l->data; if ( hline->type[0]!=type[0] || hline->type[1]!=type[1] ) { l = l->next; continue; } out = (char**) realloc(out, sizeof(char*)*(nout+1)*ntags); for (i=0; i<ntags; i++) { HeaderTag *key = header_line_has_tag(hline, tags[i]); if ( !key ) { out[nout*ntags+i] = NULL; continue; } out[nout*ntags+i] = key->value; } nout++; l = l->next; } *n = nout; return out; }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bgzip.c
.c
5,903
207
/* The MIT License Copyright (c) 2008 Broad Institute / Massachusetts Institute of Technology Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <sys/select.h> #include <sys/stat.h> #include "bgzf.h" static const int WINDOW_SIZE = 64 * 1024; static int bgzip_main_usage() { fprintf(stderr, "\n"); fprintf(stderr, "Usage: bgzip [options] [file] ...\n\n"); fprintf(stderr, "Options: -c write on standard output, keep original files unchanged\n"); fprintf(stderr, " -d decompress\n"); fprintf(stderr, " -f overwrite files without asking\n"); fprintf(stderr, " -b INT decompress at virtual file pointer INT\n"); fprintf(stderr, " -s INT decompress INT bytes in the uncompressed file\n"); fprintf(stderr, " -h give this help\n"); fprintf(stderr, "\n"); return 1; } static int write_open(const char *fn, int is_forced) { int fd = -1; char c; if (!is_forced) { if ((fd = open(fn, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0666)) < 0 && errno == EEXIST) { fprintf(stderr, "[bgzip] %s already exists; do you wish to overwrite (y or n)? ", fn); scanf("%c", &c); if (c != 'Y' && c != 'y') { fprintf(stderr, "[bgzip] not overwritten\n"); exit(1); } } } if (fd < 0) { if ((fd = open(fn, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0) { fprintf(stderr, "[bgzip] %s: Fail to write\n", fn); exit(1); } } return fd; } static void fail(BGZF* fp) { fprintf(stderr, "Error: %s\n", fp->error); exit(1); } int main(int argc, char **argv) { int c, compress, pstdout, is_forced; BGZF *fp; void *buffer; long start, end, size; compress = 1; pstdout = 0; start = 0; size = -1; end = -1; is_forced = 0; while((c = getopt(argc, argv, "cdhfb:s:")) >= 0){ switch(c){ case 'h': return bgzip_main_usage(); case 'd': compress = 0; break; case 'c': pstdout = 1; break; case 'b': start = atol(optarg); break; case 's': size = atol(optarg); break; case 'f': is_forced = 1; break; } } if (size >= 0) end = start + size; if (end >= 0 && end < start) { fprintf(stderr, "[bgzip] Illegal region: [%ld, %ld]\n", start, end); return 1; } if (compress == 1) { struct stat sbuf; int f_src = fileno(stdin); int f_dst = fileno(stdout); if ( argc>optind ) { if ( stat(argv[optind],&sbuf)<0 ) { fprintf(stderr, "[bgzip] %s: %s\n", strerror(errno), argv[optind]); return 1; } if ((f_src = open(argv[optind], O_RDONLY)) < 0) { fprintf(stderr, "[bgzip] %s: %s\n", strerror(errno), argv[optind]); return 1; } if (pstdout) f_dst = fileno(stdout); else { char *name = malloc(strlen(argv[optind]) + 5); strcpy(name, argv[optind]); strcat(name, ".gz"); f_dst = write_open(name, is_forced); if (f_dst < 0) return 1; free(name); } } else if (!pstdout && isatty(fileno((FILE *)stdout)) ) return bgzip_main_usage(); fp = bgzf_fdopen(f_dst, "w"); buffer = malloc(WINDOW_SIZE); while ((c = read(f_src, buffer, WINDOW_SIZE)) > 0) if (bgzf_write(fp, buffer, c) < 0) fail(fp); // f_dst will be closed here if (bgzf_close(fp) < 0) fail(fp); if (argc > optind && !pstdout) unlink(argv[optind]); free(buffer); close(f_src); return 0; } else { struct stat sbuf; int f_dst; if ( argc>optind ) { if ( stat(argv[optind],&sbuf)<0 ) { fprintf(stderr, "[bgzip] %s: %s\n", strerror(errno), argv[optind]); return 1; } char *name; int len = strlen(argv[optind]); if ( strcmp(argv[optind]+len-3,".gz") ) { fprintf(stderr, "[bgzip] %s: unknown suffix -- ignored\n", argv[optind]); return 1; } fp = bgzf_open(argv[optind], "r"); if (fp == NULL) { fprintf(stderr, "[bgzip] Could not open file: %s\n", argv[optind]); return 1; } if (pstdout) { f_dst = fileno(stdout); } else { name = strdup(argv[optind]); name[strlen(name) - 3] = '\0'; f_dst = write_open(name, is_forced); free(name); } } else if (!pstdout && isatty(fileno((FILE *)stdin)) ) return bgzip_main_usage(); else { f_dst = fileno(stdout); fp = bgzf_fdopen(fileno(stdin), "r"); if (fp == NULL) { fprintf(stderr, "[bgzip] Could not read from stdin: %s\n", strerror(errno)); return 1; } } buffer = malloc(WINDOW_SIZE); if (bgzf_seek(fp, start, SEEK_SET) < 0) fail(fp); while (1) { if (end < 0) c = bgzf_read(fp, buffer, WINDOW_SIZE); else c = bgzf_read(fp, buffer, (end - start > WINDOW_SIZE)? WINDOW_SIZE:(end - start)); if (c == 0) break; if (c < 0) fail(fp); start += c; write(f_dst, buffer, c); if (end >= 0 && start >= end) break; } free(buffer); if (bgzf_close(fp) < 0) fail(fp); if (!pstdout) unlink(argv[optind]); return 0; } }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_rmdupse.c
.c
4,127
160
#include <math.h> #include "sam.h" #include "khash.h" #include "klist.h" #define QUEUE_CLEAR_SIZE 0x100000 #define MAX_POS 0x7fffffff typedef struct { int endpos; uint32_t score:31, discarded:1; bam1_t *b; } elem_t, *elem_p; #define __free_elem(p) bam_destroy1((p)->data.b) KLIST_INIT(q, elem_t, __free_elem) typedef klist_t(q) queue_t; KHASH_MAP_INIT_INT(best, elem_p) typedef khash_t(best) besthash_t; typedef struct { uint64_t n_checked, n_removed; besthash_t *left, *rght; } lib_aux_t; KHASH_MAP_INIT_STR(lib, lib_aux_t) static lib_aux_t *get_aux(khash_t(lib) *aux, const char *lib) { khint_t k = kh_get(lib, aux, lib); if (k == kh_end(aux)) { int ret; char *p = strdup(lib); lib_aux_t *q; k = kh_put(lib, aux, p, &ret); q = &kh_val(aux, k); q->left = kh_init(best); q->rght = kh_init(best); q->n_checked = q->n_removed = 0; return q; } else return &kh_val(aux, k); } static inline int sum_qual(const bam1_t *b) { int i, q; uint8_t *qual = bam1_qual(b); for (i = q = 0; i < b->core.l_qseq; ++i) q += qual[i]; return q; } static inline elem_t *push_queue(queue_t *queue, const bam1_t *b, int endpos, int score) { elem_t *p = kl_pushp(q, queue); p->discarded = 0; p->endpos = endpos; p->score = score; if (p->b == 0) p->b = bam_init1(); bam_copy1(p->b, b); return p; } static void clear_besthash(besthash_t *h, int32_t pos) { khint_t k; for (k = kh_begin(h); k != kh_end(h); ++k) if (kh_exist(h, k) && kh_val(h, k)->endpos <= pos) kh_del(best, h, k); } static void dump_alignment(samfile_t *out, queue_t *queue, int32_t pos, khash_t(lib) *h) { if (queue->size > QUEUE_CLEAR_SIZE || pos == MAX_POS) { khint_t k; while (1) { elem_t *q; if (queue->head == queue->tail) break; q = &kl_val(queue->head); if (q->discarded) { q->b->data_len = 0; kl_shift(q, queue, 0); continue; } if ((q->b->core.flag&BAM_FREVERSE) && q->endpos > pos) break; samwrite(out, q->b); q->b->data_len = 0; kl_shift(q, queue, 0); } for (k = kh_begin(h); k != kh_end(h); ++k) { if (kh_exist(h, k)) { clear_besthash(kh_val(h, k).left, pos); clear_besthash(kh_val(h, k).rght, pos); } } } } void bam_rmdupse_core(samfile_t *in, samfile_t *out, int force_se) { bam1_t *b; queue_t *queue; khint_t k; int last_tid = -2; khash_t(lib) *aux; aux = kh_init(lib); b = bam_init1(); queue = kl_init(q); while (samread(in, b) >= 0) { bam1_core_t *c = &b->core; int endpos = bam_calend(c, bam1_cigar(b)); int score = sum_qual(b); if (last_tid != c->tid) { if (last_tid >= 0) dump_alignment(out, queue, MAX_POS, aux); last_tid = c->tid; } else dump_alignment(out, queue, c->pos, aux); if ((c->flag&BAM_FUNMAP) || ((c->flag&BAM_FPAIRED) && !force_se)) { push_queue(queue, b, endpos, score); } else { const char *lib; lib_aux_t *q; besthash_t *h; uint32_t key; int ret; lib = bam_get_library(in->header, b); q = lib? get_aux(aux, lib) : get_aux(aux, "\t"); ++q->n_checked; h = (c->flag&BAM_FREVERSE)? q->rght : q->left; key = (c->flag&BAM_FREVERSE)? endpos : c->pos; k = kh_put(best, h, key, &ret); if (ret == 0) { // in the hash table elem_t *p = kh_val(h, k); ++q->n_removed; if (p->score < score) { if (c->flag&BAM_FREVERSE) { // mark "discarded" and push the queue p->discarded = 1; kh_val(h, k) = push_queue(queue, b, endpos, score); } else { // replace p->score = score; p->endpos = endpos; bam_copy1(p->b, b); } } // otherwise, discard the alignment } else kh_val(h, k) = push_queue(queue, b, endpos, score); } } dump_alignment(out, queue, MAX_POS, aux); for (k = kh_begin(aux); k != kh_end(aux); ++k) { if (kh_exist(aux, k)) { lib_aux_t *q = &kh_val(aux, k); fprintf(stderr, "[bam_rmdupse_core] %lld / %lld = %.4lf in library '%s'\n", (long long)q->n_removed, (long long)q->n_checked, (double)q->n_removed/q->n_checked, kh_key(aux, k)); kh_destroy(best, q->left); kh_destroy(best, q->rght); free((char*)kh_key(aux, k)); } } kh_destroy(lib, aux); bam_destroy1(b); kl_destroy(q, queue); }
C
2D
mitenjain/nanopore
submodules/samtools-0.1.19/bam_sort.c
.c
18,685
572
#include <stdlib.h> #include <ctype.h> #include <assert.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include "bam.h" #include "ksort.h" static int g_is_by_qname = 0; static int strnum_cmp(const char *_a, const char *_b) { const unsigned char *a = (const unsigned char*)_a, *b = (const unsigned char*)_b; const unsigned char *pa = a, *pb = b; while (*pa && *pb) { if (isdigit(*pa) && isdigit(*pb)) { while (*pa == '0') ++pa; while (*pb == '0') ++pb; while (isdigit(*pa) && isdigit(*pb) && *pa == *pb) ++pa, ++pb; if (isdigit(*pa) && isdigit(*pb)) { int i = 0; while (isdigit(pa[i]) && isdigit(pb[i])) ++i; return isdigit(pa[i])? 1 : isdigit(pb[i])? -1 : (int)*pa - (int)*pb; } else if (isdigit(*pa)) return 1; else if (isdigit(*pb)) return -1; else if (pa - a != pb - b) return pa - a < pb - b? 1 : -1; } else { if (*pa != *pb) return (int)*pa - (int)*pb; ++pa; ++pb; } } return *pa? 1 : *pb? -1 : 0; } #define HEAP_EMPTY 0xffffffffffffffffull typedef struct { int i; uint64_t pos, idx; bam1_t *b; } heap1_t; #define __pos_cmp(a, b) ((a).pos > (b).pos || ((a).pos == (b).pos && ((a).i > (b).i || ((a).i == (b).i && (a).idx > (b).idx)))) static inline int heap_lt(const heap1_t a, const heap1_t b) { if (g_is_by_qname) { int t; if (a.b == 0 || b.b == 0) return a.b == 0? 1 : 0; t = strnum_cmp(bam1_qname(a.b), bam1_qname(b.b)); return (t > 0 || (t == 0 && (a.b->core.flag&0xc0) > (b.b->core.flag&0xc0))); } else return __pos_cmp(a, b); } KSORT_INIT(heap, heap1_t, heap_lt) static void swap_header_targets(bam_header_t *h1, bam_header_t *h2) { bam_header_t t; t.n_targets = h1->n_targets, h1->n_targets = h2->n_targets, h2->n_targets = t.n_targets; t.target_name = h1->target_name, h1->target_name = h2->target_name, h2->target_name = t.target_name; t.target_len = h1->target_len, h1->target_len = h2->target_len, h2->target_len = t.target_len; } static void swap_header_text(bam_header_t *h1, bam_header_t *h2) { int tempi; char *temps; tempi = h1->l_text, h1->l_text = h2->l_text, h2->l_text = tempi; temps = h1->text, h1->text = h2->text, h2->text = temps; } #define MERGE_RG 1 #define MERGE_UNCOMP 2 #define MERGE_LEVEL1 4 #define MERGE_FORCE 8 /*! @abstract Merge multiple sorted BAM. @param is_by_qname whether to sort by query name @param out output BAM file name @param headers name of SAM file from which to copy '@' header lines, or NULL to copy them from the first file to be merged @param n number of files to be merged @param fn names of files to be merged @discussion Padding information may NOT correctly maintained. This function is NOT thread safe. */ int bam_merge_core2(int by_qname, const char *out, const char *headers, int n, char * const *fn, int flag, const char *reg, int n_threads, int level) { bamFile fpout, *fp; heap1_t *heap; bam_header_t *hout = 0; bam_header_t *hheaders = NULL; int i, j, *RG_len = 0; uint64_t idx = 0; char **RG = 0, mode[8]; bam_iter_t *iter = 0; if (headers) { tamFile fpheaders = sam_open(headers); if (fpheaders == 0) { const char *message = strerror(errno); fprintf(stderr, "[bam_merge_core] cannot open '%s': %s\n", headers, message); return -1; } hheaders = sam_header_read(fpheaders); sam_close(fpheaders); } g_is_by_qname = by_qname; fp = (bamFile*)calloc(n, sizeof(bamFile)); heap = (heap1_t*)calloc(n, sizeof(heap1_t)); iter = (bam_iter_t*)calloc(n, sizeof(bam_iter_t)); // prepare RG tag if (flag & MERGE_RG) { RG = (char**)calloc(n, sizeof(void*)); RG_len = (int*)calloc(n, sizeof(int)); for (i = 0; i != n; ++i) { int l = strlen(fn[i]); const char *s = fn[i]; if (l > 4 && strcmp(s + l - 4, ".bam") == 0) l -= 4; for (j = l - 1; j >= 0; --j) if (s[j] == '/') break; ++j; l -= j; RG[i] = calloc(l + 1, 1); RG_len[i] = l; strncpy(RG[i], s + j, l); } } // read the first for (i = 0; i != n; ++i) { bam_header_t *hin; fp[i] = bam_open(fn[i], "r"); if (fp[i] == 0) { int j; fprintf(stderr, "[bam_merge_core] fail to open file %s\n", fn[i]); for (j = 0; j < i; ++j) bam_close(fp[j]); free(fp); free(heap); // FIXME: possible memory leak return -1; } hin = bam_header_read(fp[i]); if (i == 0) { // the first BAM hout = hin; } else { // validate multiple baf int min_n_targets = hout->n_targets; if (hin->n_targets < min_n_targets) min_n_targets = hin->n_targets; for (j = 0; j < min_n_targets; ++j) if (strcmp(hout->target_name[j], hin->target_name[j]) != 0) { fprintf(stderr, "[bam_merge_core] different target sequence name: '%s' != '%s' in file '%s'\n", hout->target_name[j], hin->target_name[j], fn[i]); return -1; } // If this input file has additional target reference sequences, // add them to the headers to be output if (hin->n_targets > hout->n_targets) { swap_header_targets(hout, hin); // FIXME Possibly we should also create @SQ text headers // for the newly added reference sequences } bam_header_destroy(hin); } } if (hheaders) { // If the text headers to be swapped in include any @SQ headers, // check that they are consistent with the existing binary list // of reference information. if (hheaders->n_targets > 0) { if (hout->n_targets != hheaders->n_targets) { fprintf(stderr, "[bam_merge_core] number of @SQ headers in '%s' differs from number of target sequences\n", headers); if (!reg) return -1; } for (j = 0; j < hout->n_targets; ++j) if (strcmp(hout->target_name[j], hheaders->target_name[j]) != 0) { fprintf(stderr, "[bam_merge_core] @SQ header '%s' in '%s' differs from target sequence\n", hheaders->target_name[j], headers); if (!reg) return -1; } } swap_header_text(hout, hheaders); bam_header_destroy(hheaders); } if (reg) { int tid, beg, end; if (bam_parse_region(hout, reg, &tid, &beg, &end) < 0) { fprintf(stderr, "[%s] Malformated region string or undefined reference name\n", __func__); return -1; } for (i = 0; i < n; ++i) { bam_index_t *idx; idx = bam_index_load(fn[i]); iter[i] = bam_iter_query(idx, tid, beg, end); bam_index_destroy(idx); } } for (i = 0; i < n; ++i) { heap1_t *h = heap + i; h->i = i; h->b = (bam1_t*)calloc(1, sizeof(bam1_t)); if (bam_iter_read(fp[i], iter[i], h->b) >= 0) { h->pos = ((uint64_t)h->b->core.tid<<32) | (uint32_t)((int32_t)h->b->core.pos+1)<<1 | bam1_strand(h->b); h->idx = idx++; } else h->pos = HEAP_EMPTY; } if (flag & MERGE_UNCOMP) level = 0; else if (flag & MERGE_LEVEL1) level = 1; strcpy(mode, "w"); if (level >= 0) sprintf(mode + 1, "%d", level < 9? level : 9); if ((fpout = strcmp(out, "-")? bam_open(out, "w") : bam_dopen(fileno(stdout), "w")) == 0) { fprintf(stderr, "[%s] fail to create the output file.\n", __func__); return -1; } bam_header_write(fpout, hout); bam_header_destroy(hout); if (!(flag & MERGE_UNCOMP)) bgzf_mt(fpout, n_threads, 256); ks_heapmake(heap, n, heap); while (heap->pos != HEAP_EMPTY) { bam1_t *b = heap->b; if (flag & MERGE_RG) { uint8_t *rg = bam_aux_get(b, "RG"); if (rg) bam_aux_del(b, rg); bam_aux_append(b, "RG", 'Z', RG_len[heap->i] + 1, (uint8_t*)RG[heap->i]); } bam_write1_core(fpout, &b->core, b->data_len, b->data); if ((j = bam_iter_read(fp[heap->i], iter[heap->i], b)) >= 0) { heap->pos = ((uint64_t)b->core.tid<<32) | (uint32_t)((int)b->core.pos+1)<<1 | bam1_strand(b); heap->idx = idx++; } else if (j == -1) { heap->pos = HEAP_EMPTY; free(heap->b->data); free(heap->b); heap->b = 0; } else fprintf(stderr, "[bam_merge_core] '%s' is truncated. Continue anyway.\n", fn[heap->i]); ks_heapadjust(heap, 0, n, heap); } if (flag & MERGE_RG) { for (i = 0; i != n; ++i) free(RG[i]); free(RG); free(RG_len); } for (i = 0; i != n; ++i) { bam_iter_destroy(iter[i]); bam_close(fp[i]); } bam_close(fpout); free(fp); free(heap); free(iter); return 0; } int bam_merge_core(int by_qname, const char *out, const char *headers, int n, char * const *fn, int flag, const char *reg) { return bam_merge_core2(by_qname, out, headers, n, fn, flag, reg, 0, -1); } int bam_merge(int argc, char *argv[]) { int c, is_by_qname = 0, flag = 0, ret = 0, n_threads = 0, level = -1; char *fn_headers = NULL, *reg = 0; while ((c = getopt(argc, argv, "h:nru1R:f@:l:")) >= 0) { switch (c) { case 'r': flag |= MERGE_RG; break; case 'f': flag |= MERGE_FORCE; break; case 'h': fn_headers = strdup(optarg); break; case 'n': is_by_qname = 1; break; case '1': flag |= MERGE_LEVEL1; break; case 'u': flag |= MERGE_UNCOMP; break; case 'R': reg = strdup(optarg); break; case 'l': level = atoi(optarg); break; case '@': n_threads = atoi(optarg); break; } } if (optind + 2 >= argc) { fprintf(stderr, "\n"); fprintf(stderr, "Usage: samtools merge [-nr] [-h inh.sam] <out.bam> <in1.bam> <in2.bam> [...]\n\n"); fprintf(stderr, "Options: -n sort by read names\n"); fprintf(stderr, " -r attach RG tag (inferred from file names)\n"); fprintf(stderr, " -u uncompressed BAM output\n"); fprintf(stderr, " -f overwrite the output BAM if exist\n"); fprintf(stderr, " -1 compress level 1\n"); fprintf(stderr, " -l INT compression level, from 0 to 9 [-1]\n"); fprintf(stderr, " -@ INT number of BAM compression threads [0]\n"); fprintf(stderr, " -R STR merge file in the specified region STR [all]\n"); fprintf(stderr, " -h FILE copy the header in FILE to <out.bam> [in1.bam]\n\n"); fprintf(stderr, "Note: Samtools' merge does not reconstruct the @RG dictionary in the header. Users\n"); fprintf(stderr, " must provide the correct header with -h, or uses Picard which properly maintains\n"); fprintf(stderr, " the header dictionary in merging.\n\n"); return 1; } if (!(flag & MERGE_FORCE) && strcmp(argv[optind], "-")) { FILE *fp = fopen(argv[optind], "rb"); if (fp != NULL) { fclose(fp); fprintf(stderr, "[%s] File '%s' exists. Please apply '-f' to overwrite. Abort.\n", __func__, argv[optind]); return 1; } } if (bam_merge_core2(is_by_qname, argv[optind], fn_headers, argc - optind - 1, argv + optind + 1, flag, reg, n_threads, level) < 0) ret = 1; free(reg); free(fn_headers); return ret; } /*************** * BAM sorting * ***************/ #include <pthread.h> typedef bam1_t *bam1_p; static int change_SO(bam_header_t *h, const char *so) { char *p, *q, *beg = 0, *end = 0, *newtext; if (h->l_text > 3) { if (strncmp(h->text, "@HD", 3) == 0) { if ((p = strchr(h->text, '\n')) == 0) return -1; *p = '\0'; if ((q = strstr(h->text, "\tSO:")) != 0) { *p = '\n'; // change back if (strncmp(q + 4, so, p - q - 4) != 0) { beg = q; for (q += 4; *q != '\n' && *q != '\t'; ++q); end = q; } else return 0; // no need to change } else beg = end = p, *p = '\n'; } } if (beg == 0) { // no @HD h->l_text += strlen(so) + 15; newtext = malloc(h->l_text + 1); sprintf(newtext, "@HD\tVN:1.3\tSO:%s\n", so); strcat(newtext, h->text); } else { // has @HD but different or no SO h->l_text = (beg - h->text) + (4 + strlen(so)) + (h->text + h->l_text - end); newtext = malloc(h->l_text + 1); strncpy(newtext, h->text, beg - h->text); sprintf(newtext + (beg - h->text), "\tSO:%s", so); strcat(newtext, end); } free(h->text); h->text = newtext; return 0; } static inline int bam1_lt(const bam1_p a, const bam1_p b) { if (g_is_by_qname) { int t = strnum_cmp(bam1_qname(a), bam1_qname(b)); return (t < 0 || (t == 0 && (a->core.flag&0xc0) < (b->core.flag&0xc0))); } else return (((uint64_t)a->core.tid<<32|(a->core.pos+1)<<1|bam1_strand(a)) < ((uint64_t)b->core.tid<<32|(b->core.pos+1)<<1|bam1_strand(b))); } KSORT_INIT(sort, bam1_p, bam1_lt) typedef struct { size_t buf_len; const char *prefix; bam1_p *buf; const bam_header_t *h; int index; } worker_t; static void write_buffer(const char *fn, const char *mode, size_t l, bam1_p *buf, const bam_header_t *h, int n_threads) { size_t i; bamFile fp; fp = strcmp(fn, "-")? bam_open(fn, mode) : bam_dopen(fileno(stdout), mode); if (fp == 0) return; bam_header_write(fp, h); if (n_threads > 1) bgzf_mt(fp, n_threads, 256); for (i = 0; i < l; ++i) bam_write1_core(fp, &buf[i]->core, buf[i]->data_len, buf[i]->data); bam_close(fp); } static void *worker(void *data) { worker_t *w = (worker_t*)data; char *name; ks_mergesort(sort, w->buf_len, w->buf, 0); name = (char*)calloc(strlen(w->prefix) + 20, 1); sprintf(name, "%s.%.4d.bam", w->prefix, w->index); write_buffer(name, "w1", w->buf_len, w->buf, w->h, 0); free(name); return 0; } static int sort_blocks(int n_files, size_t k, bam1_p *buf, const char *prefix, const bam_header_t *h, int n_threads) { int i; size_t rest; bam1_p *b; pthread_t *tid; pthread_attr_t attr; worker_t *w; if (n_threads < 1) n_threads = 1; if (k < n_threads * 64) n_threads = 1; // use a single thread if we only sort a small batch of records pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); w = calloc(n_threads, sizeof(worker_t)); tid = calloc(n_threads, sizeof(pthread_t)); b = buf; rest = k; for (i = 0; i < n_threads; ++i) { w[i].buf_len = rest / (n_threads - i); w[i].buf = b; w[i].prefix = prefix; w[i].h = h; w[i].index = n_files + i; b += w[i].buf_len; rest -= w[i].buf_len; pthread_create(&tid[i], &attr, worker, &w[i]); } for (i = 0; i < n_threads; ++i) pthread_join(tid[i], 0); free(tid); free(w); return n_files + n_threads; } /*! @abstract Sort an unsorted BAM file based on the chromosome order and the leftmost position of an alignment @param is_by_qname whether to sort by query name @param fn name of the file to be sorted @param prefix prefix of the output and the temporary files; upon sucessess, prefix.bam will be written. @param max_mem approxiate maximum memory (very inaccurate) @param full_path the given output path is the full path and not just the prefix @discussion It may create multiple temporary subalignment files and then merge them by calling bam_merge_core(). This function is NOT thread safe. */ void bam_sort_core_ext(int is_by_qname, const char *fn, const char *prefix, size_t _max_mem, int is_stdout, int n_threads, int level, int full_path) { int ret, i, n_files = 0; size_t mem, max_k, k, max_mem; bam_header_t *header; bamFile fp; bam1_t *b, **buf; char *fnout = 0; char const *suffix = ".bam"; if (full_path) suffix += 4; if (n_threads < 2) n_threads = 1; g_is_by_qname = is_by_qname; max_k = k = 0; mem = 0; max_mem = _max_mem * n_threads; buf = 0; fp = strcmp(fn, "-")? bam_open(fn, "r") : bam_dopen(fileno(stdin), "r"); if (fp == 0) { fprintf(stderr, "[bam_sort_core] fail to open file %s\n", fn); return; } header = bam_header_read(fp); if (is_by_qname) change_SO(header, "queryname"); else change_SO(header, "coordinate"); // write sub files for (;;) { if (k == max_k) { size_t old_max = max_k; max_k = max_k? max_k<<1 : 0x10000; buf = realloc(buf, max_k * sizeof(void*)); memset(buf + old_max, 0, sizeof(void*) * (max_k - old_max)); } if (buf[k] == 0) buf[k] = (bam1_t*)calloc(1, sizeof(bam1_t)); b = buf[k]; if ((ret = bam_read1(fp, b)) < 0) break; if (b->data_len < b->m_data>>2) { // shrink b->m_data = b->data_len; kroundup32(b->m_data); b->data = realloc(b->data, b->m_data); } mem += sizeof(bam1_t) + b->m_data + sizeof(void*) + sizeof(void*); // two sizeof(void*) for the data allocated to pointer arrays ++k; if (mem >= max_mem) { n_files = sort_blocks(n_files, k, buf, prefix, header, n_threads); mem = k = 0; } } if (ret != -1) fprintf(stderr, "[bam_sort_core] truncated file. Continue anyway.\n"); // output file name fnout = calloc(strlen(prefix) + 20, 1); if (is_stdout) sprintf(fnout, "-"); else sprintf(fnout, "%s%s", prefix, suffix); // write the final output if (n_files == 0) { // a single block char mode[8]; strcpy(mode, "w"); if (level >= 0) sprintf(mode + 1, "%d", level < 9? level : 9); ks_mergesort(sort, k, buf, 0); write_buffer(fnout, mode, k, buf, header, n_threads); } else { // then merge char **fns; n_files = sort_blocks(n_files, k, buf, prefix, header, n_threads); fprintf(stderr, "[bam_sort_core] merging from %d files...\n", n_files); fns = (char**)calloc(n_files, sizeof(char*)); for (i = 0; i < n_files; ++i) { fns[i] = (char*)calloc(strlen(prefix) + 20, 1); sprintf(fns[i], "%s.%.4d%s", prefix, i, suffix); } bam_merge_core2(is_by_qname, fnout, 0, n_files, fns, 0, 0, n_threads, level); for (i = 0; i < n_files; ++i) { unlink(fns[i]); free(fns[i]); } free(fns); } free(fnout); // free for (k = 0; k < max_k; ++k) { if (!buf[k]) continue; free(buf[k]->data); free(buf[k]); } free(buf); bam_header_destroy(header); bam_close(fp); } void bam_sort_core(int is_by_qname, const char *fn, const char *prefix, size_t max_mem) { bam_sort_core_ext(is_by_qname, fn, prefix, max_mem, 0, 0, -1, 0); } int bam_sort(int argc, char *argv[]) { size_t max_mem = 768<<20; // 512MB int c, is_by_qname = 0, is_stdout = 0, n_threads = 0, level = -1, full_path = 0; while ((c = getopt(argc, argv, "fnom:@:l:")) >= 0) { switch (c) { case 'f': full_path = 1; break; case 'o': is_stdout = 1; break; case 'n': is_by_qname = 1; break; case 'm': { char *q; max_mem = strtol(optarg, &q, 0); if (*q == 'k' || *q == 'K') max_mem <<= 10; else if (*q == 'm' || *q == 'M') max_mem <<= 20; else if (*q == 'g' || *q == 'G') max_mem <<= 30; break; } case '@': n_threads = atoi(optarg); break; case 'l': level = atoi(optarg); break; } } if (optind + 2 > argc) { fprintf(stderr, "\n"); fprintf(stderr, "Usage: samtools sort [options] <in.bam> <out.prefix>\n\n"); fprintf(stderr, "Options: -n sort by read name\n"); fprintf(stderr, " -f use <out.prefix> as full file name instead of prefix\n"); fprintf(stderr, " -o final output to stdout\n"); fprintf(stderr, " -l INT compression level, from 0 to 9 [-1]\n"); fprintf(stderr, " -@ INT number of sorting and compression threads [1]\n"); fprintf(stderr, " -m INT max memory per thread; suffix K/M/G recognized [768M]\n"); fprintf(stderr, "\n"); return 1; } bam_sort_core_ext(is_by_qname, argv[optind], argv[optind+1], max_mem, is_stdout, n_threads, level, full_path); return 0; }
C