File: AnalyzeGenes.java

package info (click to toggle)
bbmap 39.20%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 26,008 kB
  • sloc: java: 312,743; sh: 18,096; python: 5,247; ansic: 2,074; perl: 96; makefile: 39; xml: 38
file content (404 lines) | stat: -rwxr-xr-x 13,234 bytes parent folder | download | duplicates (2)
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package prok;

import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

import fileIO.ByteFile;
import fileIO.ByteStreamWriter;
import fileIO.FileFormat;
import fileIO.ReadWrite;
import shared.Parse;
import shared.Parser;
import shared.PreParser;
import shared.Shared;
import shared.Timer;
import shared.Tools;
import structures.ByteBuilder;
import structures.IntList;

/**
 * This class is designed to analyze paired prokaryotic fna and gff files
 * to calculate the patterns in coding and noncoding frames, start and stop sites.
 * It outputs a pgm file.
 * @author Brian Bushnell
 * @date Sep 27, 2018
 *
 */
public class AnalyzeGenes {
	
	/*--------------------------------------------------------------*/
	/*----------------        Initialization        ----------------*/
	/*--------------------------------------------------------------*/
	
	/**
	 * Code entrance from the command line.
	 * @param args Command line arguments
	 */
	public static void main(String[] args){
		//Start a timer immediately upon code entrance.
		Timer t=new Timer();
		
		//Create an instance of this class
		AnalyzeGenes x=new AnalyzeGenes(args);
		
		//Run the object
		x.process(t);
		
		//Close the print stream if it was redirected
		Shared.closeStream(x.outstream);
	}
	
	/**
	 * Constructor.
	 * @param args Command line arguments
	 */
	public AnalyzeGenes(String[] args){
		
		{//Preparse block for help, config files, and outstream
			PreParser pp=new PreParser(args, null/*getClass()*/, false);
			args=pp.args;
			outstream=pp.outstream;
		}
		
		//Set shared static variables prior to parsing
		ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
		ReadWrite.setZipThreads(Shared.threads());
		
		{//Parse the arguments
			final Parser parser=parse(args);
			overwrite=parser.overwrite;
			append=parser.append;

			out=parser.out1;
		}
		
		if(alignRibo){
			//Load sequences
			ProkObject.loadConsensusSequenceFromFile(false, false);
		}
		
		fixExtensions(); //Add or remove .gz or .bz2 as needed
		checkFileExistence(); //Ensure files can be read and written
		checkStatics(); //Adjust file-related static fields as needed for this program
		
		//Determine how many threads may be used
		threads=Tools.min(fnaList.size(), Shared.threads(), Tools.max(32, Shared.CALC_LOGICAL_PROCESSORS()/2));
		
		ffout=FileFormat.testOutput(out, FileFormat.PGM, null, true, overwrite, append, false);
	}
	
	/*--------------------------------------------------------------*/
	/*----------------    Initialization Helpers    ----------------*/
	/*--------------------------------------------------------------*/
	
	/** Parse arguments from the command line */
	private Parser parse(String[] args){
		
		Parser parser=new Parser();
		parser.overwrite=overwrite;
		for(int i=0; i<args.length; i++){
			String arg=args[i];
			String[] split=arg.split("=");
			String a=split[0].toLowerCase();
			String b=split.length>1 ? split[1] : null;
			if(b!=null && b.equalsIgnoreCase("null")){b=null;}

//			outstream.println(arg+", "+a+", "+b);
			if(PGMTools.parseStatic(arg, a, b)){
				//do nothing
			}else if(a.equals("in") || a.equals("infna") || a.equals("fnain") || a.equals("fna") || a.equals("ref")){
				assert(b!=null);
				Tools.addFiles(b, fnaList);
			}else if(a.equals("gff") || a.equals("ingff") || a.equals("gffin")){
				assert(b!=null);
				Tools.addFiles(b, gffList);
			}else if(a.equals("verbose")){
				verbose=Parse.parseBoolean(b);
				ReadWrite.verbose=verbose;
			}else if(a.equals("alignribo") || a.equals("align")){
				alignRibo=Parse.parseBoolean(b);
			}else if(a.equals("adjustendpoints")){
				adjustEndpoints=Parse.parseBoolean(b);
			}
			
			else if(ProkObject.parse(arg, a, b)){}
			
			else if(parser.parse(arg, a, b)){
				//do nothing
			}else if(arg.indexOf('=')<0 && new File(arg).exists() && FileFormat.isFastaFile(arg)){
				fnaList.add(arg);
			}else{
				outstream.println("Unknown parameter "+args[i]);
				assert(false) : "Unknown parameter "+args[i];
				//				throw new RuntimeException("Unknown parameter "+args[i]);
			}
		}

		if(gffList.isEmpty()){
			for(String s : fnaList){
				String prefix=ReadWrite.stripExtension(s);
				String gff=prefix+".gff";
				File f=new File(gff);
				if(!f.exists()){
					String gz=gff+".gz";
					f=new File(gz);
					assert(f.exists() && f.canRead()) : "Can't read file "+gff;
					gff=gz;
				}
				gffList.add(gff);
			}
		}
		assert(gffList.size()==fnaList.size()) : "Number of fna and gff files do not match: "+fnaList.size()+", "+gffList.size();
		return parser;
	}
	
	/** Add or remove .gz or .bz2 as needed */
	private void fixExtensions(){
		fnaList=Tools.fixExtension(fnaList);
		gffList=Tools.fixExtension(gffList);
		if(fnaList.isEmpty()){throw new RuntimeException("Error - at least one input file is required.");}
	}
	
	/** Ensure files can be read and written */
	private void checkFileExistence(){
		//Ensure output files can be written
		if(!Tools.testOutputFiles(overwrite, append, false, out)){
			outstream.println((out==null)+", "+out);
			throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output file "+out+"\n");
		}
		
		//Ensure input files can be read
		ArrayList<String> foo=new ArrayList<String>();
		foo.addAll(fnaList);
		foo.addAll(gffList);
		if(!Tools.testInputFiles(false, true, foo.toArray(new String[0]))){
			throw new RuntimeException("\nCan't read some input files.\n");  
		}
		
		//Ensure that no file was specified multiple times
		foo.add(out);
		if(!Tools.testForDuplicateFiles(true, foo.toArray(new String[0]))){
			throw new RuntimeException("\nSome file names were specified multiple times.\n");
		}
	}
	
	/** Adjust file-related static fields as needed for this program */
	private static void checkStatics(){
		//Adjust the number of threads for input file reading
		if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
			ByteFile.FORCE_MODE_BF2=true;
		}
	}
	
	/*--------------------------------------------------------------*/
	/*----------------         Outer Methods        ----------------*/
	/*--------------------------------------------------------------*/
	
	void process(Timer t){
		
		final GeneModel pgm;
		if(Shared.threads()<2 || fnaList.size()<2){
			pgm=makeModelST();
		}else{
			pgm=spawnThreads();
		}
		
		ByteStreamWriter bsw=ByteStreamWriter.makeBSW(ffout);
		
		ByteBuilder bb=new ByteBuilder();
		pgm.appendTo(bb);
		bytesOut+=bb.length;
		
		if(bsw!=null){
			bsw.addJob(bb);
			errorState|=bsw.poisonAndWait();
		}
		
		t.stop();
		
		outstream.println(timeReadsBasesGenesProcessed(t, pgm.readsProcessed, pgm.basesProcessed, pgm.genesProcessed, pgm.filesProcessed, 8));
		
		outstream.println();
		outstream.println(typesProcessed(pgm, 12));
		
		//outstream.println("Bytes Out:         \t"+bytesOut);
		
		if(errorState){
			throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
		}
	}
	
	private static String timeReadsBasesGenesProcessed(Timer t, long readsProcessed, long basesProcessed, long genesProcessed, long filesProcessed, int pad){
		return ("Time:                         \t"+t+"\n"+readsBasesGenesProcessed(t.elapsed, readsProcessed, basesProcessed, genesProcessed, filesProcessed, pad));
	}
	
	private static String readsBasesGenesProcessed(long elapsed, long reads, long bases, long genes, long files, int pad){
		double rpnano=reads/(double)elapsed;
		double bpnano=bases/(double)elapsed;
		double gpnano=genes/(double)elapsed;
		double fpnano=files/(double)elapsed;

		String rstring=Tools.padKMB(reads, pad);
		String bstring=Tools.padKMB(bases, pad);
		String gstring=Tools.padKMB(genes, pad);
		String fstring=Tools.padKMB(files, pad);
		ByteBuilder sb=new ByteBuilder();
		sb.append("Files Processed:    ").append(fstring).append(Tools.format(" \t%.2f  files/sec", fpnano*1000000000)).append('\n');
		sb.append("Sequences Processed:").append(rstring).append(Tools.format(" \t%.2fk seqs/sec", rpnano*1000000)).append('\n');
		sb.append("Genes Processed:    ").append(gstring).append(Tools.format(" \t%.2fk genes/sec", gpnano*1000000)).append('\n');
		sb.append("Bases Processed:    ").append(bstring).append(Tools.format(" \t%.2fm bases/sec", bpnano*1000));
		return sb.toString();
	}
	
	private static String typesProcessed(GeneModel pgm, int pad){
		
		ByteBuilder sb=new ByteBuilder();
		sb.append("CDS:   "+Tools.padLeft(pgm.statsCDS.lengthCount, pad)).nl();
		sb.append("tRNA:  "+Tools.padLeft(pgm.statstRNA.lengthCount, pad)).nl();
		sb.append("16S:   "+Tools.padLeft(pgm.stats16S.lengthCount, pad)).nl();
		sb.append("23S:   "+Tools.padLeft(pgm.stats23S.lengthCount, pad)).nl();
		sb.append("5S:    "+Tools.padLeft(pgm.stats5S.lengthCount, pad)).nl();
		sb.append("18S:   "+Tools.padLeft(pgm.stats18S.lengthCount, pad));
		return sb.toString();
	}
	
	/*--------------------------------------------------------------*/
	/*----------------         Inner Methods        ----------------*/
	/*--------------------------------------------------------------*/
	
	//TODO: Process each file in a thread.
	private GeneModel makeModelST(){
		GeneModel pgmSum=new GeneModel(true);
		
		for(int i=0; i<fnaList.size(); i++){
			String fna=fnaList.get(i);
			String gff=gffList.get(i);
			pgmSum.process(fna, gff);
		}
		return pgmSum;
	}
	
	/*--------------------------------------------------------------*/
	/*----------------       Thread Management      ----------------*/
	/*--------------------------------------------------------------*/
	
	/** Spawn process threads */
	private GeneModel spawnThreads(){
		
		//Do anything necessary prior to processing
		
		final AtomicInteger aint=new AtomicInteger(0);
		
		//Fill a list with FileThreads
		ArrayList<FileThread> alpt=new ArrayList<FileThread>(threads);
		for(int i=0; i<threads; i++){
			alpt.add(new FileThread(aint));
		}
		
		//Start the threads
		for(FileThread pt : alpt){
			pt.start();
		}
		
		//Wait for threads to finish
		GeneModel pgm=waitForThreads(alpt);
		
		//Do anything necessary after processing
		return pgm;
	}
	
	private GeneModel waitForThreads(ArrayList<FileThread> alpt){
		
		GeneModel pgm=new GeneModel(false);
		
		//Wait for completion of all threads
		boolean success=true;
		for(FileThread pt : alpt){
			
			//Wait until this thread has terminated
			while(pt.getState()!=Thread.State.TERMINATED){
				try {
					//Attempt a join operation
					pt.join();
				} catch (InterruptedException e) {
					//Potentially handle this, if it is expected to occur
					e.printStackTrace();
				}
			}
			
			//Accumulate per-thread statistics
			pgm.add(pt.pgm);
			
			success&=pt.success;
			errorState|=pt.errorStateT;
		}
		
		//Track whether any threads failed
		if(!success){errorState=true;}
		return pgm;
	}
	
	/*--------------------------------------------------------------*/
	/*----------------         Inner Classes        ----------------*/
	/*--------------------------------------------------------------*/
	
	private class FileThread extends Thread {
		
		FileThread(AtomicInteger fnum_){
			fnum=fnum_;
			pgm=new GeneModel(true);
		}
		
		@Override
		public void run(){
			for(int i=fnum.getAndIncrement(); i<fnaList.size(); i=fnum.getAndIncrement()){
				String fna=fnaList.get(i);
				String gff=gffList.get(i);
				errorStateT=pgm.process(fna, gff)|errorState;
//				System.err.println("Processed "+fna+" in "+this.toString());
			}
			success=true;
		}
		
		private final AtomicInteger fnum;
		private final GeneModel pgm;
		boolean errorStateT=false;
		boolean success=false;
	}
	
	/*--------------------------------------------------------------*/
	/*----------------            Fields            ----------------*/
	/*--------------------------------------------------------------*/

	private ArrayList<String> fnaList=new ArrayList<String>();
	private ArrayList<String> gffList=new ArrayList<String>();
	private IntList taxList=new IntList();
	private String out=null;
	
	/*--------------------------------------------------------------*/
	
	private long bytesOut=0;
	static boolean alignRibo=true;
	static boolean adjustEndpoints=true;
	
	/*--------------------------------------------------------------*/
	/*----------------         Final Fields         ----------------*/
	/*--------------------------------------------------------------*/
	
	private final FileFormat ffout;
	private final int threads;
	
	/*--------------------------------------------------------------*/
	/*----------------        Common Fields         ----------------*/
	/*--------------------------------------------------------------*/
	
	private PrintStream outstream=System.err;
	public static boolean verbose=false;
	public boolean errorState=false;
	private boolean overwrite=true;
	private boolean append=false;
	
}