-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMain.java
188 lines (142 loc) · 10 KB
/
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package nhs.genetics.cardiff;
import htsjdk.samtools.*;
import nhs.genetics.cardiff.framework.*;
import org.apache.commons.cli.*;
import org.biojava.nbio.core.exceptions.CompoundNotFoundException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Program for realigning soft clipped amplicon reads (post merging and whole genome alignment)
*
* @author Matt Lyon
* @version 1.0
* @since 2016-10-11
*/
public class Main {
private static final Logger log = Logger.getLogger(Main.class.getName());
private static final String program = "AmpliconRealigner";
private static final String version = "1.1.1";
public static void main(String[] args) {
CommandLineParser commandLineParser = new DefaultParser();
CommandLine commandLine = null;
HelpFormatter formatter = new HelpFormatter();
Options options = new Options();
options.addOption("I", "Input", true, "Path to input BAM file");
options.addOption("T", "Targets", true, "Path to BED file");
options.addOption("O", "Output", true, "Path to output BAM file");
options.addOption("R", "Reference", true, "Path to FASTA file");
options.addOption("S", "MinScore", true, "Minimum alignment score [50]");
options.addOption("P", "PrimerSimilarity", true, "Primer similarity [0.8]");
options.addOption("Go", "GapOpen", true, "Read alignment gap open penalty [-14]");
options.addOption("Ge", "GapExtend", true, "Read alignment gap extend penalty [-4]");
try {
commandLine = commandLineParser.parse(options, args);
if (!commandLine.hasOption("I") || !commandLine.hasOption("T") || ! commandLine.hasOption("O") || ! commandLine.hasOption("R")){
throw new NullPointerException("Incorrect arguments");
}
} catch (ParseException | NullPointerException e){
formatter.printHelp(program + " " + version, options);
log.log(Level.SEVERE, e.getMessage());
System.exit(-1);
}
File inputSamOrBamFile = new File(commandLine.getOptionValue("I"));
File outputSamOrBamFile = new File(commandLine.getOptionValue("O"));
File bedFile = new File(commandLine.getOptionValue("T"));
File referenceFasta = new File(commandLine.getOptionValue("R"));
File referenceFastaFai = new File(commandLine.getOptionValue("R") + ".fai");
ArrayList<GenomicLocation> genomicLocations = null;
int minScore = commandLine.hasOption("S") ? Integer.parseInt(commandLine.getOptionValue("S")) : 50;
int gapOpenPenalty = commandLine.hasOption("Go") ? Integer.parseInt(commandLine.getOptionValue("Go")) : -14;
int gapExtendPenalty = commandLine.hasOption("Ge") ? Integer.parseInt(commandLine.getOptionValue("Ge")) : -4;
double primerSimilarity = commandLine.hasOption("P") ? Double.parseDouble(commandLine.getOptionValue("P")) : 0.8;
log.log(Level.INFO, "Running with settings: minScore=" + minScore + " gapOpenPenalty=" + gapOpenPenalty + " gapExtendPenalty=" + gapExtendPenalty + " primerSimilarity=" + primerSimilarity);
log.log(Level.INFO, "Reading BED file: " + bedFile + " ...");
try {
genomicLocations = BEDFile.getBedFeatures(bedFile);
} catch (IOException e){
log.log(Level.SEVERE, "Could not read BED file: " + e.getMessage());
System.exit(-1);
}
log.log(Level.INFO, "Reading BAM file: " + inputSamOrBamFile + " ...");
try (SamReader samReader = SamReaderFactory.makeDefault().open(inputSamOrBamFile)){
SAMFileHeader samFileHeader = samReader.getFileHeader();
samFileHeader.setSortOrder(SAMFileHeader.SortOrder.unsorted);
SAMProgramRecord samProgramRecord = samFileHeader.createProgramRecord();
samProgramRecord.setCommandLine(String.join(" ", args));
samProgramRecord.setProgramName(program);
samProgramRecord.setProgramVersion(version);
log.log(Level.INFO, "Processing reads, writing to " + outputSamOrBamFile.getName() + " ...");
try (SAMFileWriter samFileWriter = new SAMFileWriterFactory().makeSAMOrBAMWriter(samFileHeader, true, outputSamOrBamFile)){
//loop over BED records
for (GenomicLocation genomicLocation : genomicLocations){
log.log(Level.FINE, "Inspecting region: " + genomicLocation + " ...");
//get reference sequence
ReferenceSequence referenceSequence = new ReferenceSequence(new GenomicLocation(genomicLocation.getContig(), genomicLocation.getStartPosition(), genomicLocation.getEndPosition()), referenceFasta, referenceFastaFai);
referenceSequence.populateReferenceSequence();
//get primer sequences
String upstreamPrimerSequence = referenceSequence.getReferenceSequence().substring(0, genomicLocation.getUpstreamPrimerLength());
String downstreamPrimerSequence = referenceSequence.getReferenceSequence().substring(referenceSequence.getReferenceSequence().length() - genomicLocation.getDownstreamPrimerLength());
log.log(Level.FINE, "Reference sequence: " + referenceSequence.getReferenceSequence());
log.log(Level.FINE, "Upstream primer: " + upstreamPrimerSequence);
log.log(Level.FINE, "Downstream primer: " + downstreamPrimerSequence);
//query alignments
SAMRecordIterator samRecordIterator = samReader.queryOverlapping(genomicLocation.getContig(), genomicLocation.getStartPosition(), genomicLocation.getEndPosition());
samRecordIterator.stream()
.filter(samRecord -> !samRecord.getReadUnmappedFlag())
.filter(samRecord -> !samRecord.getNotPrimaryAlignmentFlag())
.filter(samRecord -> !samRecord.getSupplementaryAlignmentFlag())
.filter(samRecord -> {
//calculate hamming distances
int upstreamPrimerHammingDist = Hamming.getHammingDistance(samRecord.getReadString().substring(0, upstreamPrimerSequence.length()), upstreamPrimerSequence);
int downstreamPrimerHammingDist = Hamming.getHammingDistance(samRecord.getReadString().substring(samRecord.getReadLength() - downstreamPrimerSequence.length()), downstreamPrimerSequence);
double upstreamPrimerSimilarity = (double) (upstreamPrimerSequence.length() - upstreamPrimerHammingDist) / upstreamPrimerSequence.length();
double downstreamPrimerSimilarity = (double) (downstreamPrimerSequence.length() - downstreamPrimerHammingDist) / downstreamPrimerSequence.length();
if (upstreamPrimerSimilarity > primerSimilarity && downstreamPrimerSimilarity > primerSimilarity){
return true;
}
return false;
})
.forEach(samRecord -> {
if (samRecord.getCigar().getFirstCigarElement().getOperator().equals(CigarOperator.SOFT_CLIP) ||
samRecord.getCigar().getLastCigarElement().getOperator().equals(CigarOperator.SOFT_CLIP)){
try {
PairwiseAligner pairwiseAligner = new PairwiseAligner(referenceSequence.getReferenceSequence(), samRecord.getReadString());
pairwiseAligner.needlemanWunschAlignment(gapOpenPenalty, gapExtendPenalty);
if (pairwiseAligner.getScore() > minScore){
//adjust alignment
String readGroup = samRecord.getStringAttribute("RG");
samRecord.clearAttributes();
samRecord.setAttribute("RG", readGroup);
samRecord.setAttribute("AS", (int) Math.round(pairwiseAligner.getScore()));
samRecord.setAttribute("CO", genomicLocation.getName());
samRecord.setAttribute("XC", samRecord.getCigarString());
samRecord.setCigar(pairwiseAligner.getCigar());
samRecord.setAlignmentStart(genomicLocation.getStartPosition());
samFileWriter.addAlignment(samRecord);
}
} catch (CompoundNotFoundException e){
log.log(Level.SEVERE, "Could not perform pairwise alignment: " + e.getMessage());
System.exit(-1);
}
} else {
String readGroup = samRecord.getStringAttribute("RG");
int alignmentScore = samRecord.getIntegerAttribute("AS");
samRecord.clearAttributes();
samRecord.setAttribute("RG", readGroup);
samRecord.setAttribute("AS", alignmentScore);
samRecord.setAttribute("CO", genomicLocation.getName());
samFileWriter.addAlignment(samRecord);
}
});
samRecordIterator.close();
}
}
} catch (IOException e){
log.log(Level.SEVERE, "Could not read BAM file: " + e.getMessage());
System.exit(-1);
}
}
}