Debian Codegraph @

current/barcode/AnalyzeBarcodes.java

raw symbols SCIP
1 package barcode;
2
3 import java.io.PrintStream;
4 import java.util.Collections;
5
6 import fileIO.ByteFile;
7 import fileIO.ByteFile1;
8 import fileIO.ByteFile2;
9 import fileIO.ByteStreamWriter;
10 import fileIO.FileFormat;
11 import fileIO.ReadWrite;
12 import shared.Parse;
13 import shared.Parser;
14 import shared.PreParser;
15 import shared.Shared;
16 import shared.Timer;
17 import shared.Tools;
18 import structures.ByteBuilder;
19
20 /**
21 * Analyzes paired barcode counts.
22 * This is the output file from CountBarcodes2.
23 * Example: TODO
24 *
25 * @author Brian Bushnell
26 * @date July 19, 2023
27 *
28 */
29 public class AnalyzeBarcodes {
30
31 /*--------------------------------------------------------------*/
32 /*---------------- Initialization ----------------*/
33 /*--------------------------------------------------------------*/
34
35 /**
36 * Code entrance from the command line.
37 * @param args Command line arguments
38 */
39 public static void main(String[] args){
40 //Start a timer immediately upon code entrance.
41 Timer t=new Timer();
42
43 //Create an instance of this class
44 AnalyzeBarcodes x=new AnalyzeBarcodes(args);
45
46 //Run the object
47 x.process(t);
48
49 //Close the print stream if it was redirected
50 Shared.closeStream(x.outstream);
51 }
52
53 /**
54 * Constructor.
55 * @param args Command line arguments
56 */
57 public AnalyzeBarcodes(String[] args){
58
59 {//Preparse block for help, config files, and outstream
60 PreParser pp=new PreParser(args, /*getClass()*/null, false);
61 args=pp.args;
62 outstream=pp.outstream;
63 }
64
65 //Set shared static variables prior to parsing
66 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
67 ReadWrite.setZipThreads(Shared.threads());
68
69 {//Parse the arguments
70 final Parser parser=parse(args);
71 overwrite=parser.overwrite;
72 append=parser.append;
73
74 in1=parser.in1;
75 }
76
77 validateParams();
78 fixExtensions(); //Add or remove .gz or .bz2 as needed
79 checkFileExistence(); //Ensure files can be read and written
80 checkStatics(); //Adjust file-related static fields as needed for this program
81
82 ffin1=FileFormat.testInput(in1, FileFormat.TXT, null, true, true);
83 }
84
85 /*--------------------------------------------------------------*/
86 /*---------------- Initialization Helpers ----------------*/
87 /*--------------------------------------------------------------*/
88
89 /** Parse arguments from the command line */
90 private Parser parse(String[] args){
91
92 //Create a parser object
93 Parser parser=new Parser();
94
95 //Set any necessary Parser defaults here
96 //parser.foo=bar;
97 // parser.out1="stdout";
98
99 //Parse each argument
100 for(int i=0; i<args.length; i++){
101 String arg=args[i];
102
103 //Break arguments into their constituent parts, in the form of "a=b"
104 String[] split=arg.split("=");
105 String a=split[0].toLowerCase();
106 String b=split.length>1 ? split[1] : null;
107 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
108
109 if(a.equals("lines")){
110 maxLines=Long.parseLong(b);
111 if(maxLines<0){maxLines=Long.MAX_VALUE;}
112 }else if(a.equals("verbose")){
113 verbose=Parse.parseBoolean(b);
114 ByteFile1.verbose=verbose;
115 ByteFile2.verbose=verbose;
116 ReadWrite.verbose=verbose;
117 }else if(a.equals("expected") || a.equals("expectedbarcodes")){
118 if(Tools.isNumeric(b)) {
119 expectedBarcodeCount=Integer.parseInt(b);
120 }else {
121 expectedBarcodeFile=b;
122 }
123 }else if(a.equals("outleft") || a.equals("left") || a.equals("leftstats")){
124 outLeft=b;
125 }else if(a.equals("outright") || a.equals("right") || a.equals("rightstats")){
126 outRight=b;
127 }else if(a.equals("outpair") || a.equals("pair") || a.equals("pairstats")){
128 outPair=b;
129 }else if(a.equals("parse_flag_goes_here")){
130 long fake_variable=Parse.parseKMG(b);
131 //Set a variable here
132 }else if(parser.parse(arg, a, b)){
133 //do nothing
134 }else{
135 outstream.println("Unknown parameter "+args[i]);
136 assert(false) : "Unknown parameter "+args[i];
137 throw new RuntimeException("Unknown parameter "+args[i]);
138 }
139 }
140
141 return parser;
142 }
143
144 /** Add or remove .gz or .bz2 as needed */
145 private void fixExtensions(){
146 in1=Tools.fixExtension(in1);
147 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
148 }
149
150 /** Ensure files can be read and written */
151 private void checkFileExistence(){
152 //Ensure output files can be written
153 if(!Tools.testOutputFiles(overwrite, append, false, outLeft, outRight, outPair)){
154 // outstream.println((out1==null)+", "+out1);
155 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to some output files.\n");
156 }
157
158 //Ensure input files can be read
159 if(!Tools.testInputFiles(false, true, in1, expectedBarcodeFile)){
160 throw new RuntimeException("\nCan't read some input files.\n");
161 }
162
163 //Ensure that no file was specified multiple times
164 if(!Tools.testForDuplicateFiles(true, in1, expectedBarcodeFile, outLeft, outRight, outPair)){
165 throw new RuntimeException("\nSome file names were specified multiple times.\n");
166 }
167 }
168
169 /** Adjust file-related static fields as needed for this program */
170 private static void checkStatics(){
171 //Adjust the number of threads for input file reading
172 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
173 ByteFile.FORCE_MODE_BF2=true;
174 }
175
176 // if(!ByteFile.FORCE_MODE_BF2){
177 // ByteFile.FORCE_MODE_BF2=false;
178 // ByteFile.FORCE_MODE_BF1=true;
179 // }
180 }
181
182 /** Ensure parameter ranges are within bounds and required parameters are set */
183 private boolean validateParams(){
184 // assert(minfoo>0 && minfoo<=maxfoo) : minfoo+", "+maxfoo;
185 assert(in1!=null && expectedBarcodeFile!=null) : "Barcode stats and expected barcodes must be specified.";
186 return true;
187 }
188
189 /*--------------------------------------------------------------*/
190 /*---------------- Outer Methods ----------------*/
191 /*--------------------------------------------------------------*/
192
193 /** Create streams and process all data */
194 void process(Timer t){
195
196 bs=BarcodeStats.loadStatic(in1, expectedBarcodeFile, expectedBarcodeCount);
197 linesProcessed+=bs.linesProcessed;
198 bytesProcessed+=bs.bytesProcessed;
199 bs.leftStats=bs.makeLeft();
200 bs.rightStats=bs.makeRight();
201 bs.calcStats();
202 bs.leftStats.calcStats();
203 bs.rightStats.calcStats();
204
205 // float errorFraction1=bs.leftStats.errorFraction();
206 float badPairFraction=bs.badPairFraction;
207
208 // HashMap<String, Barcode> leftBadPairs
209
210 if(outLeft!=null){
211 ByteStreamWriter bsw=makeBSW(outLeft);
212 printMismatchVsTotal(bs.leftStats, bsw);
213 if(bsw!=null){errorState|=bsw.poisonAndWait();}
214 }
215
216 if(outRight!=null){
217 ByteStreamWriter bsw=makeBSW(outRight);
218 printMismatchVsTotal(bs.rightStats, bsw);
219 if(bsw!=null){errorState|=bsw.poisonAndWait();}
220 }
221
222 if(outPair!=null){
223 ByteStreamWriter bsw=makeBSW(outPair);
224 printActualVsExpected(bs, bsw);
225 if(bsw!=null){errorState|=bsw.poisonAndWait();}
226 }
227
228 t.stop();
229
230 outstream.println(Tools.timeLinesBytesProcessed(t, linesProcessed, bytesProcessed, 8));
231
232 outstream.println();
233 outstream.println("Lines Out: \t"+linesOut);
234 outstream.println("Bytes Out: \t"+bytesOut);
235
236 //Throw an exception of there was an error in a thread
237 if(errorState){
238 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
239 }
240 }
241
242 /*--------------------------------------------------------------*/
243 /*---------------- Inner Methods ----------------*/
244 /*--------------------------------------------------------------*/
245
246 void printMismatchVsTotal(BarcodeStats bs, ByteStreamWriter bsw) {
247 ByteBuilder bb=new ByteBuilder();
248 bb.append("#Name\tTotal\tBadPair\n");
249 linesOut++;
250 // ArrayList<Barcode> list=new ArrayList<Barcode>(bs.expectedCodeList.size());
251 for(Barcode e : bs.expectedCodeList) {
252 Barcode bTotal=bs.codeMap.get(e.name);
253 if(bTotal!=null) {e.setCount(bTotal.count());}
254 }
255 Collections.sort(bs.expectedCodeList);
256 for(Barcode e : bs.expectedCodeList) {
257 Barcode bTotal=bs.codeMap.get(e.name);
258 Barcode bBad=bs.badPairMap.get(e.name);
259 bb.append(e.name).tab().append((bTotal==null ? 0 : bTotal.count())).tab().append(bBad==null ? 0 : bBad.count()).nl();
260 bsw.print(bb);
261 bytesOut+=bb.length();
262 bb.clear();
263 }
264 }
265
266 void printActualVsExpected(BarcodeStats bs, ByteStreamWriter bsw) {
267 ByteBuilder bb=new ByteBuilder();
268 bb.append("#Name\tExpectedCount\tActualCount\n");
269 linesOut++;
270 String dString=(bs.delimiter<1 ? "" : Character.toString((char)bs.delimiter));
271 final double badRate=bs.badPairFraction;
272 final double validLeft=bs.leftStats.expectedCodes;
273 final double validRight=bs.rightStats.expectedCodes;
274
275 //For two barcodes, a.count*b.count*badMult will give the expect number of bad pairs
276 final double badMult=bs.validArray[0]/(validLeft*validRight);
277
278 for(Barcode ebLeft : bs.leftStats.expectedCodeList) {
279 final double leftCount;
280 {
281 Barcode bLeft=bs.leftStats.codeMap.get(ebLeft.name);
282 leftCount=(bLeft==null ? 0 : bLeft.count());
283 }
284 for(Barcode ebRight : bs.rightStats.expectedCodeList) {
285 final double rightCount;
286 {
287 Barcode bRight=bs.rightStats.codeMap.get(ebRight.name);
288 rightCount=(bRight==null ? 0 : bRight.count());
289 }
290 String pair=ebLeft.name+dString+ebRight.name;
291 if(!bs.expectedCodeMap.containsKey(pair)) {
292 Barcode bPair=bs.codeMap.get(pair);
293 final double pairCount=(bPair==null ? 0 : bPair.count());
294 final double expectedCount=leftCount*rightCount*badMult;
295
296 bb.append(pair).tab().append(expectedCount,2).tab().append(pairCount,0).nl();
297 bsw.print(bb);
298 bytesOut+=bb.length();
299 linesOut++;
300 bb.clear();
301 }
302 }
303 }
304 }
305
306 private ByteStreamWriter makeBSW(String fname){
307 FileFormat ff=FileFormat.testOutput(fname, FileFormat.TXT, null, true, overwrite, append, false);
308 return makeBSW(ff);
309 }
310
311 private static ByteStreamWriter makeBSW(FileFormat ff){
312 if(ff==null){return null;}
313 ByteStreamWriter bsw=new ByteStreamWriter(ff);
314 bsw.start();
315 return bsw;
316 }
317
318 /*--------------------------------------------------------------*/
319 /*---------------- Fields ----------------*/
320 /*--------------------------------------------------------------*/
321
322 /** Primary input file path */
323 private String in1=null;
324
325 private String expectedBarcodeFile=null;
326 private int expectedBarcodeCount=-1;
327
328 /** Primary output file path */
329 private String outLeft="leftStats.txt";
330 private String outRight="rightStats.txt";
331 private String outPair="pairStats.txt";
332
333 private BarcodeStats bs;
334
335 /*--------------------------------------------------------------*/
336
337 private long linesProcessed=0;
338 private long bytesProcessed=0;
339 private long linesOut=0;
340 private long bytesOut=0;
341
342 private long maxLines=Long.MAX_VALUE;
343
344 /*--------------------------------------------------------------*/
345 /*---------------- Final Fields ----------------*/
346 /*--------------------------------------------------------------*/
347
348 /** Input File */
349 private final FileFormat ffin1;
350
351 /*--------------------------------------------------------------*/
352 /*---------------- Common Fields ----------------*/
353 /*--------------------------------------------------------------*/
354
355 /** Print status messages to this output stream */
356 private PrintStream outstream=System.err;
357 /** Print verbose messages */
358 public static boolean verbose=false;
359 /** True if an error was encountered */
360 public boolean errorState=false;
361 /** Overwrite existing output files */
362 private boolean overwrite=true;
363 /** Append to existing output files */
364 private boolean append=false;
365
366 }