Debian Codegraph @

uk/ac/babraham/FastQC/Modules/KmerContent.java

raw symbols SCIP
1 /**
2 * Copyright Copyright 2010-17 Simon Andrews
3 *
4 * This file is part of FastQC.
5 *
6 * FastQC is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * FastQC is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with FastQC; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20 package uk.ac.babraham.FastQC.Modules;
21
22 import java.awt.BorderLayout;
23 import java.io.IOException;
24 import java.util.Arrays;
25 import java.util.Hashtable;
26 import java.util.Iterator;
27 import java.util.Vector;
28
29 import javax.swing.JLabel;
30 import javax.swing.JPanel;
31 import javax.swing.JScrollPane;
32 import javax.swing.JSplitPane;
33 import javax.swing.JTable;
34 import javax.swing.table.AbstractTableModel;
35 import javax.swing.table.TableModel;
36 import javax.xml.stream.XMLStreamException;
37 import javax.xml.stream.XMLStreamWriter;
38
39 import org.apache.commons.math3.distribution.BinomialDistribution;
40
41
42 import uk.ac.babraham.FastQC.FastQCConfig;
43 import uk.ac.babraham.FastQC.Graphs.BaseGroup;
44 import uk.ac.babraham.FastQC.Graphs.LineGraph;
45 import uk.ac.babraham.FastQC.Report.HTMLReportArchive;
46 import uk.ac.babraham.FastQC.Sequence.Sequence;
47
48 public class KmerContent extends AbstractQCModule {
49
50 private Hashtable<String, Kmer> kmers = new Hashtable<String, Kmer>((int)Math.pow(4, MAX_KMER_SIZE));
51
52 private int longestSequence = 0;
53
54 /* 2D array, first dimension is the position in the sequence, second is Kmer length */
55 private long [][] totalKmerCounts = new long [0][0];
56
57 private long skipCount = 0;
58
59 private static int MIN_KMER_SIZE = 7;
60 private static int MAX_KMER_SIZE = 7;
61
62 public boolean calculated = false;
63
64 // This is the full set of Kmers to be reported
65 private Kmer [] enrichedKmers = null;
66
67 // This is the data for the Kmers which are going to be placed on the graph
68 private double [][] enrichments = null;
69
70 // For the graph we also need to know the scale we need to use on the axes.
71 private double minGraphValue = 0;
72 private double maxGraphValue = 0;
73
74
75 private String [] xCategories = new String[0];
76 private String [] xLabels = new String[0];
77
78 BaseGroup [] groups;
79 public KmerContent () {
80 if (FastQCConfig.getInstance().kmer_size != null) {
81 int kmerSize = FastQCConfig.getInstance().kmer_size;
82 MIN_KMER_SIZE = kmerSize;
83 MAX_KMER_SIZE = kmerSize;
84 }
85 }
86
87 public boolean ignoreFilteredSequences() {
88 return true;
89 }
90
91 public boolean ignoreInReport () {
92 if (ModuleConfig.getParam("kmer", "ignore") > 0) {
93 return true;
94 }
95 return false;
96 }
97
98 public JPanel getResultsPanel() {
99
100 if (!calculated) calculateEnrichment();
101 JPanel returnPanel = new JPanel();
102 returnPanel.setLayout(new BorderLayout());
103 returnPanel.add(new JLabel("Overrepresented Kmers",JLabel.CENTER),BorderLayout.NORTH);
104
105 JSplitPane splitPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
106
107 if (enrichedKmers.length > 0) {
108 TableModel model = new ResultsTable(enrichedKmers);
109 splitPanel.setBottomComponent(new JScrollPane(new JTable(model)));
110 splitPanel.setTopComponent(new LineGraph(enrichments, minGraphValue, maxGraphValue, "Position in read (bp)", xLabels, xCategories, "Log2 Obs/Exp"));
111 returnPanel.add(splitPanel,BorderLayout.CENTER);
112 }
113 else {
114 returnPanel.add(new JLabel("There are no overrepresented Kmers",JLabel.CENTER),BorderLayout.CENTER);
115 }
116
117 return returnPanel;
118 }
119
120 /**
121 * This method simply keeps a count of the number of Kmers of a given size
122 * seen at each position within the run. We can use this later on to calculate
123 * the enrichment of the Kmers we actually count.
124 *
125 * We take in the Kmer sequence even though this isn't used in the total counts
126 * we do this because we don't want to count Kmers with Ns in them, but we do
127 * need to ensure that the data structure is expanded to the right size, and if
128 * we have libraries where later positions are Ns in all sequences then our
129 * data structure ends up too short and we crash.
130 *
131 * @param position Position within the read. 0 indexed
132 * @param kmerLength Actual length of the Kmer analysed
133 */
134 private void addKmerCount (int position,int kmerLength, String kmer) {
135
136
137 if (position >= totalKmerCounts.length) {
138 // We need to expand the array
139 long [][] newCounts = new long[position+1][];
140 for (int i=0;i<totalKmerCounts.length;i++) {
141 newCounts[i] = totalKmerCounts[i];
142 }
143 for (int i=totalKmerCounts.length;i<newCounts.length;i++) {
144 newCounts[i] = new long[MAX_KMER_SIZE];
145 }
146
147 totalKmerCounts = newCounts;
148 }
149
150 if (kmer.indexOf("N") >=0) return;
151
152 ++totalKmerCounts[position][kmerLength-1];
153
154 }
155
156 private synchronized void calculateEnrichment () {
157
158 /*
159 * For each Kmer we work out whether there is a statistically
160 * significant deviation in its coverage at any given position
161 * compared to its average coverage over all positions.
162 */
163
164
165 // We'll be grouping together positions later so make up the groups now
166 groups = BaseGroup.makeBaseGroups((longestSequence-MIN_KMER_SIZE)+1);
167
168 Vector<Kmer>unevenKmers = new Vector<Kmer>();
169
170 Iterator<Kmer> rawKmers = kmers.values().iterator();
171
172 while (rawKmers.hasNext()) {
173 Kmer k = rawKmers.next();
174 char [] chars = k.sequence().toCharArray();
175
176
177 long totalKmerCount = 0;
178
179
180 // This gets us the total number of Kmers of this type in the whole
181 // dataset.
182 for (int i=0;i<totalKmerCounts.length;i++) {
183 totalKmerCount += totalKmerCounts[i][k.sequence().length()-1];
184 }
185
186 // This is the expected proportion of all Kmers which have this
187 // specific Kmer sequence. We no longer make any attempt to judge
188 // overall enrichment or depletion of this sequence since once you
189 // get to longer lengths the distribution isn't flat anyway
190
191 float expectedProportion = k.count/(float)totalKmerCount;
192
193 // We now want to go through each of the positions looking for whether
194 // this Kmer was seen an unexpected number of times compared to what we
195 // expected from the global values
196
197
198 float [] obsExpPositions = new float[groups.length];
199 float [] binomialPValues = new float[groups.length];
200
201 long [] positionCounts = k.getPositions();
202
203 for (int g=0;g<groups.length;g++) {
204 // This is a summation of the number of Kmers of this length which
205 // fall into this base group
206 long totalGroupCount = 0;
207
208 // This is a summation of the number of hit Kmers which fall within
209 // this base group.
210 long totalGroupHits = 0;
211 for (int p=groups[g].lowerCount()-1;p<groups[g].upperCount() && p < positionCounts.length ;p++) {
212 totalGroupCount += totalKmerCounts[p][chars.length-1];
213 totalGroupHits += positionCounts[p];
214 }
215
216 float predicted = expectedProportion * totalGroupCount;
217 // obsExpPositions[g] = (float)(Math.log(totalGroupHits/predicted)/Math.log(2));
218 obsExpPositions[g] = (float)(totalGroupHits/predicted);
219
220 // Now we can run a binomial test to see if there is a significant
221 // deviation from what we expect given the number of observations we've
222 // made
223
224 BinomialDistribution bd = new BinomialDistribution((int)totalGroupCount, expectedProportion);
225 if (totalGroupHits > predicted) {
226 binomialPValues[g] = (float)((1 - bd.cumulativeProbability((int)totalGroupHits)) * Math.pow(4,chars.length));
227 }
228 else {
229 binomialPValues[g] = 1;
230 }
231
232 }
233
234 k.setObsExpPositions(obsExpPositions);
235
236
237 // To keep this we need a p-value below 0.01 and an obs/exp above 5 (actual values are log2 transformed)
238 float lowestPValue = 1;
239 for (int i=0;i<binomialPValues.length;i++) {
240 // if (binomialPValues[i] < 0.01 && obsExpPositions[i] > (Math.log(5)/Math.log(2))) {
241 if (binomialPValues[i] < 0.01 && obsExpPositions[i] > 5) {
242 if (binomialPValues[i]<lowestPValue) {
243 lowestPValue = binomialPValues[i];
244 }
245 }
246 }
247
248 if (lowestPValue < 0.01) {
249 k.setLowestPValue(lowestPValue);
250 unevenKmers.add(k);
251 }
252
253
254 }
255
256 Kmer [] finalKMers = unevenKmers.toArray(new Kmer[0]);
257
258 // We sort by the highest degree of enrichment over the average
259 Arrays.sort(finalKMers);
260
261 // So we don't end up with stupidly long lists of Kmers in the
262 // report we'll only report the top 20
263 if (finalKMers.length > 20) {
264 Kmer [] shortenedKmers = new Kmer [20];
265 for (int i=0;i<shortenedKmers.length;i++) {
266 shortenedKmers[i] = finalKMers[i];
267 }
268
269 finalKMers = shortenedKmers;
270 }
271
272 // Now we take the enrichment positions for the top 6 hits and
273 // record these so we can plot them on a line graph
274 enrichments = new double [Math.min(6, finalKMers.length)][];
275 xLabels = new String[enrichments.length];
276
277 xCategories = new String [groups.length];
278
279 for (int i=0;i<xCategories.length;i++) {
280 xCategories[i] = groups[i].toString();
281 }
282
283 for (int k=0;k<enrichments.length;k++) {
284 enrichments[k] = new double[groups.length];
285
286 float [] obsExpPos = finalKMers[k].getObsExpPositions();
287
288 for (int g=0;g<groups.length;g++) {
289 enrichments[k][g] = obsExpPos[g];
290 if (obsExpPos[g] > maxGraphValue) maxGraphValue = obsExpPos[g];
291 if (obsExpPos[g] < minGraphValue) minGraphValue = obsExpPos[g];
292 }
293
294 xLabels[k] = finalKMers[k].sequence();
295
296 }
297
298 minGraphValue = 0;
299
300 // System.err.println("Max value="+maxGraphValue+" min value="+minGraphValue);
301
302 this.enrichedKmers = finalKMers;
303
304 // Delete the initial data structure so we don't suck up more memory
305 // than we have to.
306 kmers.clear();
307
308 calculated = true;
309 }
310
311
312 public void processSequence(Sequence sequence) {
313 calculated = false;
314
315 /*
316 * The processing done by this module is quite intensive so to speed things
317 * up we don't look at every sequence. Instead we take only 2% of the
318 * submitted sequences and extrapolate from these to the full set in the file.
319 */
320 ++skipCount;
321 if (skipCount % 50 != 0) return;
322
323 /*
324 * This module uses horrible amounts of memory if allowed to store the full
325 * Kmer content for all positions in really long reads (pacbio reads were the
326 * ones which really broke this). We'll therefore limit our read lengths to
327 * 500bp since specific Kmer positions beyond that are not likely to be useful
328 */
329
330 String seq;
331
332 if (sequence.getSequence().length() > 500) {
333 seq = sequence.getSequence().substring(0, 500);
334 }
335 else {
336 seq = sequence.getSequence();
337 }
338
339 if (seq.length() > longestSequence) {
340 longestSequence = seq.length();
341 }
342
343 // Now we go through all of the Kmers to count these
344 for (int kmerSize=MIN_KMER_SIZE;kmerSize<=MAX_KMER_SIZE;kmerSize++) {
345 for (int i=0;i<=seq.length()-kmerSize;i++) {
346
347 String kmer = seq.substring(i, i+kmerSize);
348
349 if (kmer.length() != kmerSize) {
350 throw new IllegalStateException("String length "+kmer.length()+" wasn't the same as the kmer length "+kmerSize);
351 }
352
353 // Add to the counts before skipping Kmers containing Ns (see
354 // explanation in addKmerCount for the reasoning).
355 addKmerCount(i, kmerSize, kmer);
356
357 // Skip Kmers containing N
358 if (kmer.indexOf("N") >=0) continue;
359
360 if (kmers.containsKey(kmer)) {
361 kmers.get(kmer).incrementCount(i);
362 }
363 else {
364 kmers.put(new String(kmer), new Kmer(kmer,i,(seq.length()-kmerSize)+1));
365 }
366
367 }
368 }
369 }
370
371 public void reset () {
372 calculated = false;
373 totalKmerCounts = new long[0][0];
374 longestSequence = 0;
375 skipCount = 0;
376 enrichedKmers = null;
377 kmers.clear();
378 }
379
380 public String description() {
381 return "Identifies short sequences which have uneven representation";
382 }
383
384 public String name() {
385 return "Kmer Content";
386 }
387
388 public boolean raisesError() {
389 if (!calculated) calculateEnrichment();
390
391 // We raise an error if the most enriched kmer is seen more than 100 times
392 // more frequently than we expect.
393
394 if (enrichedKmers.length > 0 && 0-Math.log10(enrichedKmers[0].pValue()) > ModuleConfig.getParam("kmer", "error")) return true;
395 return false;
396 }
397
398 public boolean raisesWarning() {
399 if (!calculated) calculateEnrichment();
400
401 // We raise a warning if there are any enriched kmers
402 if (enrichedKmers.length > 0 && 0-Math.log10(enrichedKmers[0].pValue()) > ModuleConfig.getParam("kmer", "warn")) return true;
403 return false;
404 }
405
406 public void makeReport(HTMLReportArchive report) throws IOException,XMLStreamException {
407 if (!calculated) calculateEnrichment();
408
409 if (enrichedKmers.length > 0) {
410 writeSpecificImage(report, new LineGraph(enrichments, minGraphValue, maxGraphValue, "Position in read (bp)", xLabels, xCategories, "Log2 Obs/Exp"),"kmer_profiles.png", "Kmer graph", Math.max(800, groups.length*15), 600);
411 }
412
413
414 ResultsTable table = new ResultsTable(enrichedKmers);
415
416 XMLStreamWriter xhtml = report.xhtmlStream();
417
418 if (enrichedKmers.length == 0)
419 {
420 xhtml.writeStartElement("p");
421 xhtml.writeCharacters("No overrepresented Kmers");
422 xhtml.writeEndElement();
423 }
424
425 else
426 {
427 super.writeTable(report, table);
428 }
429 }
430
431 private class Kmer implements Comparable<Kmer>{
432
433 private String sequence;
434 private long count = 0;
435 private float lowestPValue = 0;
436 private float [] obsExpPositions = null;
437 private long [] positions = new long[0];
438
439 public Kmer (String sequence, int position, int seqLength) {
440
441 // Do this slightly convoluted dance to try to avoid
442 // keeping the whole original sequence in memory
443 char [] chars = sequence.toCharArray();
444 this.sequence = new String(chars);
445 count = 1;
446 positions = new long[seqLength];
447 ++positions[position];
448 }
449
450 public void incrementCount (int position) {
451 ++count;
452
453 if (position >= positions.length) {
454 long [] newPositions = new long[position+1];
455 for (int i=0;i<positions.length;i++) {
456 newPositions[i] = positions[i];
457 }
458 positions = newPositions;
459 }
460
461 ++positions[position];
462
463 }
464
465 public long [] getPositions () {
466 return positions;
467 }
468
469 public String sequence () {
470 return sequence;
471 }
472
473 public long count () {
474 return count;
475 }
476
477 public void setLowestPValue (float p) {
478 this.lowestPValue = p;
479 }
480
481 public void setObsExpPositions (float [] oePositions) {
482 this.obsExpPositions = oePositions;
483 }
484
485 public float [] getObsExpPositions () {
486 return obsExpPositions;
487 }
488
489 public float pValue () {
490 return lowestPValue;
491 }
492
493 public float maxObsExp () {
494 float max = 0;
495 for (int i=0;i<obsExpPositions.length;i++) {
496 if (obsExpPositions[i]>max) max = obsExpPositions[i];
497 }
498 return max;
499 }
500
501 public int maxPosition () {
502 float max = 0;
503 int position = 0;
504 for (int i=0;i<obsExpPositions.length;i++) {
505 if (obsExpPositions[i]>max) {
506 max = obsExpPositions[i];
507 position = i+1;
508 }
509 }
510
511 if (position == 0) {
512 System.err.println("No value > 0 for "+sequence);
513 position = 1;
514 }
515
516 return position;
517 }
518
519 public int compareTo(Kmer o) {
520 return Float.compare(o.maxObsExp(), maxObsExp());
521 }
522 }
523
524
525 private class ResultsTable extends AbstractTableModel
526 {
527 private static final long serialVersionUID = 1L;
528 private Kmer [] kmers;
529
530 public ResultsTable (Kmer [] kmers) {
531 this.kmers = kmers;
532 }
533
534
535 // Sequence - Count - Obs/Exp
536 public int getColumnCount() {
537 return 5;
538 }
539
540 public int getRowCount() {
541 return kmers.length;
542 }
543
544 public Object getValueAt(int rowIndex, int columnIndex) {
545 switch (columnIndex) {
546 case 0: return kmers[rowIndex].sequence();
547 case 1: return kmers[rowIndex].count()*5;
548 case 2: return kmers[rowIndex].pValue();
549 case 3: return kmers[rowIndex].maxObsExp();
550 case 4: return groups[kmers[rowIndex].maxPosition()-1].toString();
551
552 }
553 return null;
554 }
555
556 public String getColumnName (int columnIndex) {
557 switch (columnIndex) {
558 case 0: return "Sequence";
559 case 1: return "Count";
560 case 2: return "PValue";
561 case 3: return "Obs/Exp Max";
562 case 4: return "Max Obs/Exp Position";
563 }
564 return null;
565 }
566
567 public Class<?> getColumnClass (int columnIndex) {
568 switch (columnIndex) {
569 case 0: return String.class;
570 case 1: return Integer.class;
571 case 2: return Float.class;
572 case 3: return Float.class;
573 case 4: return String.class;
574 }
575 return null;
576
577 }
578 }
579
580 }