Debian Codegraph @

current/tax/AnalyzeAccession.java

raw symbols SCIP
1 package tax;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.Arrays;
7 import java.util.Collections;
8 import java.util.HashMap;
9 import java.util.Map.Entry;
10 import java.util.concurrent.locks.ReadWriteLock;
11 import java.util.concurrent.locks.ReentrantReadWriteLock;
12
13 import fileIO.ByteFile;
14 import fileIO.ByteFile1;
15 import fileIO.ByteFile2;
16 import fileIO.ByteStreamWriter;
17 import fileIO.FileFormat;
18 import fileIO.ReadWrite;
19 import fileIO.TextFile;
20 import shared.Parse;
21 import shared.Parser;
22 import shared.PreParser;
23 import shared.Shared;
24 import shared.Timer;
25 import shared.Tools;
26 import stream.ConcurrentGenericReadInputStream;
27 import stream.FastaReadInputStream;
28 import structures.ByteBuilder;
29 import structures.ListNum;
30 import structures.StringNum;
31 import template.Accumulator;
32 import template.ThreadWaiter;
33
34 /**
35 * Counts patterns in Accessions.
36 * Handles hashing for Accession to TaxID lookups.
37 * @author Brian Bushnell
38 * @date May 9, 2018
39 *
40 */
41 public class AnalyzeAccession implements Accumulator<AnalyzeAccession.ProcessThread> {
42
43 public static void main(String[] args){
44 //Start a timer immediately upon code entrance.
45 Timer t=new Timer();
46
47 //Create an instance of this class
48 AnalyzeAccession x=new AnalyzeAccession(args);
49
50 //Run the object
51 x.process(t);
52
53 //Close the print stream if it was redirected
54 Shared.closeStream(x.outstream);
55 }
56
57 public AnalyzeAccession(String[] args){
58
59 {//Preparse block for help, config files, and outstream
60 PreParser pp=new PreParser(args, getClass(), false);
61 args=pp.args;
62 outstream=pp.outstream;
63 }
64
65 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
66 ReadWrite.setZipThreads(Shared.threads());
67
68 Parser parser=new Parser();
69 for(int i=0; i<args.length; i++){
70 String arg=args[i];
71 String[] split=arg.split("=");
72 String a=split[0].toLowerCase();
73 String b=split.length>1 ? split[1] : null;
74
75 if(a.equals("verbose")){
76 verbose=Parse.parseBoolean(b);
77 ByteFile1.verbose=verbose;
78 ByteFile2.verbose=verbose;
79 stream.FastaReadInputStream.verbose=verbose;
80 ConcurrentGenericReadInputStream.verbose=verbose;
81 stream.FastqReadInputStream.verbose=verbose;
82 ReadWrite.verbose=verbose;
83 }else if(a.equals("in")){
84 if(b==null){in.clear();}
85 else{
86 String[] split2=b.split(",");
87 for(String s2 : split2){
88 in.add(s2);
89 }
90 }
91 }else if(a.equals("perfile")){
92 perFile=Parse.parseBoolean(b);
93 }else if(b==null && new File(arg).exists()){
94 in.add(arg);
95 }else if(parser.parse(arg, a, b)){
96 //do nothing
97 }else{
98 outstream.println("Unknown parameter "+args[i]);
99 assert(false) : "Unknown parameter "+args[i];
100 // throw new RuntimeException("Unknown parameter "+args[i]);
101 }
102 }
103
104 {//Process parser fields
105 overwrite=parser.overwrite;
106 append=parser.append;
107
108 out=parser.out1;
109 }
110
111 assert(FastaReadInputStream.settingsOK());
112
113 if(in==null){throw new RuntimeException("Error - at least one input file is required.");}
114
115 // if(!ByteFile.FORCE_MODE_BF2){
116 // ByteFile.FORCE_MODE_BF2=false;
117 // ByteFile.FORCE_MODE_BF1=true;
118 // }
119
120 if(out!=null && out.equalsIgnoreCase("null")){out=null;}
121
122 if(!Tools.testOutputFiles(overwrite, append, false, out)){
123 outstream.println((out==null)+", "+out);
124 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out+"\n");
125 }
126
127 ffout=FileFormat.testOutput(out, FileFormat.TXT, null, true, overwrite, append, false);
128 ffina=new FileFormat[in.size()];
129 for(int i=0; i<in.size(); i++){
130 ffina[i]=FileFormat.testInput(in.get(i), FileFormat.TXT, null, true, false);
131 }
132 }
133
134 void process(Timer t){
135
136 if(perFile) {
137 process_perFile();
138 }else{
139 for(FileFormat ffin : ffina){
140 process_inner(ffin);
141 }
142 }
143
144 if(ffout!=null){
145 ByteStreamWriter bsw=new ByteStreamWriter(ffout);
146 bsw.println("#Pattern\tCount\tCombos\tBits");
147 ArrayList<StringNum> list=new ArrayList<StringNum>();
148 list.addAll(countMap.values());
149 Collections.sort(list);
150 Collections.reverse(list);
151 for(StringNum sn : list){
152 double combos=1;
153 for(int i=0; i<sn.s.length(); i++){
154 char c=sn.s.charAt(i);
155 if(c=='D'){combos*=10;}
156 else if(c=='L'){combos*=26;}
157 }
158 bsw.print(sn.toString().getBytes());
159 bsw.println("\t"+(long)combos+"\t"+Tools.format("%.2f", Tools.log2(combos)));
160 }
161 bsw.start();
162 errorState|=bsw.poisonAndWait();
163 }
164
165 t.stop();
166
167 outstream.println(Tools.timeLinesBytesProcessed(t, linesProcessed, bytesProcessed, 8));
168
169 outstream.println();
170 outstream.println("Valid Lines: \t"+linesOut);
171 outstream.println("Invalid Lines: \t"+(linesProcessed-linesOut));
172
173 if(errorState){
174 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
175 }
176 }
177
178 void process_inner(FileFormat ffin){
179
180 ByteFile bf=ByteFile.makeByteFile(ffin);
181
182 final int threads=Tools.min(8, Shared.threads());
183 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
184 for(int i=0; i<threads; i++){alpt.add(new ProcessThread(bf));}
185 boolean success=ThreadWaiter.startAndWait(alpt, this);
186 errorState|=!success;
187 }
188
189
190 void process_perFile(){
191 ArrayList<ArrayList<ProcessThread>> perFileList=new ArrayList<ArrayList<ProcessThread>>(ffina.length);
192 for(FileFormat ffin : ffina) {
193 ByteFile bf=ByteFile.makeByteFile(ffin);
194
195 final int threads=Tools.min(16, Shared.threads());
196 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
197 for(int i=0; i<threads; i++){alpt.add(new ProcessThread(bf));}
198 perFileList.add(alpt);
199 ThreadWaiter.startThreads(alpt);
200 }
201 for(ArrayList<ProcessThread> alpt : perFileList){
202 boolean success=ThreadWaiter.waitForThreadsToFinish(alpt, this);
203 errorState|=!success;
204 }
205 }
206
207 /*--------------------------------------------------------------*/
208
209 static class ProcessThread extends Thread {
210
211 ProcessThread(ByteFile bf_){
212 bf=bf_;
213 }
214
215 @Override
216 public void run() {
217 final StringBuilder buffer=new StringBuilder(128);
218 for(ListNum<byte[]> lines=bf.nextList(); lines!=null; lines=bf.nextList()){
219 assert(lines.size()>0);
220 if(lines.id==0){
221 //This one is not really important; the header could be missing.
222 assert(Tools.startsWith(lines.get(0), "accession")) : bf.name()+"[0]: "+new String(lines.get(0));
223 }else{
224 assert(!Tools.startsWith(lines.get(0), "accession")) : bf.name()+"["+lines.id+"]: "+new String(lines.get(0));
225 }
226 for(byte[] line : lines){
227 if(line.length>0){
228 linesProcessedT++;
229 bytesProcessedT+=(line.length+1);
230
231 boolean valid=lines.id>0 || !(Tools.startsWith(line, "accession")); //Skips test for most lines
232
233 if(valid){
234 linesOutT++;
235 increment(line, buffer);
236 }
237 }
238 }
239 }
240 }
241
242 void increment(byte[] line, StringBuilder buffer){
243 buffer.setLength(0);
244 for(int i=0; i<line.length; i++){
245 final byte b=line[i];
246 if(b==' ' || b=='\t' || b=='.' || b==':'){break;}
247 final char b2=(char)remap[b];
248 assert(b2!='?' || b=='+') : "unprocessed symbol in "+new String(line)+"\n"+"'"+(char)b+"'";
249 buffer.append(b2);
250 }
251 String key=buffer.toString();
252 StringNum value=countMapT.get(key);
253 if(value!=null){value.increment();}
254 else{countMapT.put(key, new StringNum(key, 1));}
255 }
256
257 private HashMap<String, StringNum> countMapT=new HashMap<String, StringNum>();
258 private final ByteFile bf;
259 long linesProcessedT=0;
260 long linesOutT=0;
261 long bytesProcessedT=0;
262
263 }
264
265 /*--------------------------------------------------------------*/
266
267 @Override
268 public void accumulate(ProcessThread t) {
269 linesProcessed+=t.linesProcessedT;
270 linesOut+=t.linesOutT;
271 bytesProcessed+=t.bytesProcessedT;
272 for(Entry<String, StringNum> e : t.countMapT.entrySet()){
273 StringNum value=e.getValue();
274 final String key=e.getKey();
275 StringNum old=countMap.get(key);
276 if(old==null){countMap.put(key, value);}
277 else{old.add(value);}
278 }
279 }
280
281 @Override
282 public boolean success() {
283 return !errorState;
284 }
285
286 /*--------------------------------------------------------------*/
287
288 public static long combos(String s){
289 double combos=1;
290 for(int i=0; i<s.length(); i++){
291 char c=s.charAt(i);
292 if(c=='D'){combos*=10;}
293 else if(c=='L'){combos*=26;}
294 }
295 return (combos>=Long.MAX_VALUE ? Long.MAX_VALUE : (long)Math.ceil(combos));
296 }
297
298 public static long combos(byte[] s){
299 double combos=1;
300 for(int i=0; i<s.length; i++){
301 byte c=s[i];
302 if(c=='D'){combos*=10;}
303 else if(c=='L'){combos*=26;}
304 }
305 return (combos>=Long.MAX_VALUE ? -1 : (long)Math.ceil(combos));
306 }
307
308 /*--------------------------------------------------------------*/
309
310 public static HashMap<String, Integer> loadCodeMap(String fname){
311 assert(codeMap==null);
312 TextFile tf=new TextFile(fname);
313 ArrayList<String> list=new ArrayList<String>();
314 for(String line=tf.nextLine(); line!=null; line=tf.nextLine()){
315 if(!line.startsWith("#")){
316 String[] split=line.split("\t");
317 list.add(split[0]);
318 }
319 }
320 HashMap<String, Integer> map=new HashMap<String, Integer>(list.size()*3);
321 codeBits=(int)Math.ceil(Tools.log2(list.size()));
322 final int patternBits=63-codeBits;
323 final long maxCombos=((1L<<(patternBits-1))-1);
324 for(int i=0; i<list.size(); i++){
325 String s=list.get(i);
326 longestPattern=Tools.max(longestPattern, s.length());
327 long combos=combos(s);
328 if(combos<0 || combos>=maxCombos){map.put(s, -1);}
329 else{map.put(s, i);}
330 }
331 codeMap=map;
332 return map;
333 }
334
335 public static long digitize(String s){
336 String pattern=remap(s);
337 Integer code=codeMap.get(pattern);
338 if(code==null){return -2;}
339 if(code.intValue()<0){return -1;}
340
341 long number=0;
342 for(int i=0; i<pattern.length(); i++){
343 char c=s.charAt(i);
344 char p=pattern.charAt(i);
345 if(p=='-' || p=='?'){
346 //do nothing
347 }else if(p=='D'){
348 number=(number*10)+(c-'0');
349 }else if(p=='L'){
350 number=(number*26)+(Tools.toUpperCase(c)-'A');
351 }else{
352 assert(false) : s;
353 }
354 }
355 number=(number<<codeBits)+code;
356 return number;
357 }
358
359 public static long digitize(byte[] s){
360 String pattern=remap(s);
361 Integer code=codeMap.get(pattern);
362 if(code==null){return -2;}
363 if(code.intValue()<0){return -1;}
364
365 long number=0;
366 for(int i=0; i<pattern.length(); i++){
367 byte c=s[i];
368 char p=pattern.charAt(i);
369 if(p=='-' || p=='?'){
370 //do nothing
371 }else if(p=='D'){
372 number=(number*10)+(c-'0');
373 }else if(p=='L'){
374 number=(number*26)+(Tools.toUpperCase(c)-'A');
375 }else{
376 assert(false) : new String(s);
377 }
378 }
379 number=(number<<codeBits)+code;
380 return number;
381 }
382
383 public static String remap(String s){
384 if(s==null || s.length()<1){return "";}
385 ByteBuilder buffer=new ByteBuilder(s.length());
386 for(int i=0; i<s.length(); i++){
387 final char b=s.charAt(i);
388 if(b==' ' || b=='\t' || b=='.' || b==':'){break;}
389 buffer.append((char)remap[b]);
390 }
391 return buffer.toString();
392 }
393
394 public static String remap(byte[] s){
395 ByteBuilder buffer=new ByteBuilder(s.length);
396 for(int i=0; i<s.length; i++){
397 final byte b=s[i];
398 if(b==' ' || b=='\t' || b=='.' || b==':'){break;}
399 buffer.append((char)remap[b]);
400 }
401 return buffer.toString();
402 }
403
404 /*--------------------------------------------------------------*/
405
406 private ArrayList<String> in=new ArrayList<String>();
407 private String out=null;
408 private boolean perFile=true;
409
410 /*--------------------------------------------------------------*/
411
412 private HashMap<String, StringNum> countMap=new HashMap<String, StringNum>();
413 public static HashMap<String, Integer> codeMap;
414 private static int codeBits=-1;
415 private static int longestPattern=-1;
416
417 private long linesProcessed=0;
418 private long linesOut=0;
419 private long bytesProcessed=0;
420 private long bytesOut=0;
421
422 /*--------------------------------------------------------------*/
423
424 private final FileFormat[] ffina;
425 private final FileFormat ffout;
426
427 @Override
428 public final ReadWriteLock rwlock() {return rwlock;}
429 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
430
431 private static final byte[] remap=makeRemap();
432
433 private static byte[] makeRemap(){
434 byte[] array=new byte[128];
435 Arrays.fill(array, (byte)'?');
436 for(int i='A'; i<='Z'; i++){array[i]='L';}
437 for(int i='a'; i<='z'; i++){array[i]='L';}
438 for(int i='0'; i<='9'; i++){array[i]='D';}
439 array['_']=array['-']='-';
440 return array;
441 }
442
443 /*--------------------------------------------------------------*/
444
445 private PrintStream outstream=System.err;
446 public static boolean verbose=false;
447 public boolean errorState=false;
448 private boolean overwrite=true;
449 private boolean append=false;
450
451 }