| 1 |
package org.broadinstitute.dropseqrna.barnyard.digitalallelecounts.sampleassignment; |
| 2 |
|
| 3 |
import java.io.File; |
| 4 |
import java.util.Arrays; |
| 5 |
import java.util.Collection; |
| 6 |
import java.util.HashMap; |
| 7 |
import java.util.HashSet; |
| 8 |
import java.util.Iterator; |
| 9 |
import java.util.Map; |
| 10 |
import java.util.Set; |
| 11 |
import java.util.TreeSet; |
| 12 |
|
| 13 |
import htsjdk.samtools.util.Log; |
| 14 |
import picard.util.TabbedTextFileWithHeaderParser; |
| 15 |
import picard.util.TabbedTextFileWithHeaderParser.Row; |
| 16 |
|
| 17 |
public class CellContaminationParser { |
| 18 |
|
| 19 |
private static final Log log = Log.getInstance(CellContaminationParser.class); |
| 20 |
|
| 21 |
public static Map<String,Double> parseCellContamination (File input, Collection<String> expectedCellBarcodes) { |
| 22 |
double maxError=1; |
| 23 |
TabbedTextFileWithHeaderParser parser = new TabbedTextFileWithHeaderParser(input); |
| 24 |
|
| 25 |
// validate that the expected header lines are contained |
| 26 |
Set<String> expected = new HashSet<String>(Arrays.asList("cell_barcode", "frac_contamination")); |
| 27 |
Set<String> h = parser.getColumnNames(); |
| 28 |
if (!h.containsAll(expected)) { |
| 29 |
parser.close(); |
| 30 |
log.error("Parsing cell contamination map, expected header values" + expected.toString()); |
| 31 |
log.error("File header ", h.toString()); |
| 32 |
throw new IllegalArgumentException("Cell contamination file has the wrong headers!"); |
| 33 |
} |
| 34 |
|
| 35 |
Map<String, Double> result = new HashMap<>(); |
| 36 |
|
| 37 |
Iterator<Row> iter = parser.iterator(); |
| 38 |
|
| 39 |
// parse each line into the map |
| 40 |
while (iter.hasNext()) { |
| 41 |
Row r = iter.next(); |
| 42 |
String cell=r.getField("cell_barcode"); |
| 43 |
Double frac = Double.parseDouble(r.getField("frac_contamination")); |
| 44 |
frac=Double.min(frac, maxError); |
| 45 |
// only add something to the map when we expect / need it to save memory. |
| 46 |
if (expectedCellBarcodes.contains(cell)) |
| 47 |
result.put(cell, frac); |
| 48 |
} |
| 49 |
|
| 50 |
parser.close(); |
| 51 |
|
| 52 |
final TreeSet<String> onlyInBest = new TreeSet<>(expectedCellBarcodes); |
| 53 |
onlyInBest.removeAll(result.keySet()); |
| 54 |
if (onlyInBest.size()>0) { |
| 55 |
log.warn("Not all cells have a defined ambient RNA estimate! These will fall back to the default maximum value if supplied, or no cap if not supplied+" |
| 56 |
+ String.join(", ", onlyInBest)); |
| 57 |
} |
| 58 |
|
| 59 |
return result; |
| 60 |
|
| 61 |
} |
| 62 |
} |