Debian Codegraph @

current/jgi/RepresentativeSet.java

raw symbols SCIP
1 package jgi;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5 import java.util.Arrays;
6 import java.util.Collections;
7 import java.util.HashMap;
8
9 import fileIO.ByteFile;
10 import fileIO.ByteFile1;
11 import fileIO.ByteFile2;
12 import fileIO.ByteStreamWriter;
13 import fileIO.FileFormat;
14 import fileIO.ReadWrite;
15 import shared.KillSwitch;
16 import shared.Parse;
17 import shared.Parser;
18 import shared.PreParser;
19 import shared.Shared;
20 import shared.Timer;
21 import shared.Tools;
22 import stream.ConcurrentGenericReadInputStream;
23 import stream.FastaReadInputStream;
24 import structures.ByteBuilder;
25 import structures.LongHashSet;
26 import tax.TaxFilter;
27
28 /**
29 * From a 3+ column text file of {node 1, node 2, dist, optionally sizeratio and others},
30 * makes a minimal representative set by retaining nodes
31 * such that all original nodes are within a minimum distance
32 * of at least one representative node.
33 * Singleton nodes will only be included if they are
34 * represented by a self-edge.
35 *
36 * @author Brian Bushnell
37 * @date October 26, 2017
38 *
39 */
40 public class RepresentativeSet {
41
42 public static void main(String[] args){
43 Timer t=new Timer();
44 RepresentativeSet x=new RepresentativeSet(args);
45 x.process(t);
46 x.printResults(t);
47
48 //Close the print stream if it was redirected
49 Shared.closeStream(x.outstream);
50 }
51
52 public RepresentativeSet(String[] args){
53
54 {//Preparse block for help, config files, and outstream
55 PreParser pp=new PreParser(args, getClass(), false);
56 args=pp.args;
57 outstream=pp.outstream;
58 }
59
60 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
61 ReadWrite.setZipThreads(Shared.threads());
62 boolean taxFlag=false;
63
64 Parser parser=new Parser();
65 for(int i=0; i<args.length; i++){
66 String arg=args[i];
67 String[] split=arg.split("=");
68 String a=split[0].toLowerCase();
69 String b=split.length>1 ? split[1] : null;
70
71 if(a.equals("invalid")){
72 outInvalid=b;
73 }else if(a.equals("lines")){
74 maxLines=Long.parseLong(b);
75 if(maxLines<0){maxLines=Long.MAX_VALUE;}
76 }else if(a.equals("thresh") || a.equals("threshold") || a.equals("minid") || a.equals("minani") || a.equals("id") || a.equals("ani")){
77 threshold=Float.parseFloat(b);
78 }else if(a.equals("ratio") || a.equals("minratio") || a.equals("sizeratio") || a.equals("sr")){
79 minRatio=Float.parseFloat(b);
80 }
81
82 else if(a.equals("maxsize")){
83 maxSize=Parse.parseKMG(b);
84 }else if(a.equals("minsize")){
85 minSize=Parse.parseKMG(b);
86 }
87 else if(a.equals("maxbases") || a.equals("maxbp")){
88 maxBases=Parse.parseKMG(b);
89 }else if(a.equals("minbases") || a.equals("minbp")){
90 minBases=Parse.parseKMG(b);
91 }
92
93 else if(a.equals("invertratio") || a.equals("ir")){
94 invertRatio=Parse.parseBoolean(b);
95 }else if(a.equals("printsize")){
96 printSize=Parse.parseBoolean(b);
97 }else if(a.equals("printclusters") || a.equals("cluster")){
98 printClusters=Parse.parseBoolean(b);
99 }else if(a.equals("printheader") || a.equals("header")){
100 printHeader=Parse.parseBoolean(b);
101 }
102
103 // else if(a.equals("taxfilter")){
104 // foo=Parse.parseBoolean(b);
105 // }
106
107 else if(a.equals("verbose")){
108 verbose=Parse.parseBoolean(b);
109 ByteFile1.verbose=verbose;
110 ByteFile2.verbose=verbose;
111 stream.FastaReadInputStream.verbose=verbose;
112 ConcurrentGenericReadInputStream.verbose=verbose;
113 stream.FastqReadInputStream.verbose=verbose;
114 ReadWrite.verbose=verbose;
115 }else if(TaxFilter.validArgument(a)){
116 taxFlag=true;
117 }else if(parser.parse(arg, a, b)){
118 //do nothing
119 }else{
120 outstream.println("Unknown parameter "+args[i]);
121 assert(false) : "Unknown parameter "+args[i];
122 // throw new RuntimeException("Unknown parameter "+args[i]);
123 }
124 }
125
126 {//Process parser fields
127 overwrite=parser.overwrite;
128 append=parser.append;
129
130 in1=parser.in1;
131
132 out1=parser.out1;
133 }
134
135 assert(FastaReadInputStream.settingsOK());
136
137 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
138
139 if(!ByteFile.FORCE_MODE_BF2){
140 ByteFile.FORCE_MODE_BF2=false;
141 ByteFile.FORCE_MODE_BF1=true;
142 }
143
144 if(out1!=null && out1.equalsIgnoreCase("null")){out1=null;}
145
146 if(!Tools.testOutputFiles(overwrite, append, false, out1)){
147 outstream.println((out1==null)+", "+out1);
148 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+"\n");
149 }
150
151 ffout1=FileFormat.testOutput(out1, FileFormat.TXT, null, true, overwrite, append, false);
152 ffoutInvalid=FileFormat.testOutput(outInvalid, FileFormat.TXT, null, true, overwrite, append, false);
153 ffin1=FileFormat.testInput(in1, FileFormat.TXT, null, true, true);
154
155 if(taxFlag){
156 filter=TaxFilter.makeFilter(args);
157 if(filter.isEmpty()){filter=null;}
158 }
159 }
160
161 void process(Timer t){
162
163 HashMap<Long, Node> map=load();
164 LongHashSet set=new LongHashSet();
165
166 ByteStreamWriter bsw=null;
167 if(ffout1!=null){
168 bsw=new ByteStreamWriter(ffout1);
169 bsw.start();
170 }
171
172 ArrayList<Node> list=new ArrayList<Node>(map.size());
173 ArrayList<Node> singletons=new ArrayList<Node>(map.size());
174 {//Isolate singletons to accelerate sorting. This is not really necessary.
175 ArrayList<Node> list0=new ArrayList<Node>(map.size());
176 list0.addAll(map.values());
177 for(Node n : list0){
178 sizeProcessed+=n.size;
179 basesProcessed+=n.bases;
180 if(n.edges==null || n.edges.isEmpty()){
181 singletons.add(n);
182 nodesValid++;
183 sizeValid+=n.size;
184 basesValid+=n.bases;
185 n.used=true;
186 }else{
187 list.add(n);
188 }
189 }
190 }
191
192 Collections.sort(list);
193 Collections.reverse(list);
194 // assert(list.size()==0 || list.get(0).sum>=list.get(list.size()-1).sum) : "\n"+list+"\n"; //This is incorrect because the comparator changed
195
196 for(Node n : list){
197 assert(!n.used);
198 boolean ok=true;
199 if(n.edges!=null){
200 for(Edge e : n.edges){
201 if(set.contains(e.b)){
202 ok=false;
203 break;
204 }
205 }
206 }
207 if(ok){
208 set.add(n.id);
209 n.used=true;
210 }
211 }
212
213 ByteStreamWriter bswInvalid=null;
214 if(ffoutInvalid!=null){
215 bswInvalid=new ByteStreamWriter(ffoutInvalid);
216 bswInvalid.start();
217 }
218
219 if(printHeader){
220 StringBuilder header=new StringBuilder();
221 header.append("#Representative");
222 if(printSize){header.append("\tSize");}
223 if(printClusters){header.append("\tNodeCount\tNodes");}
224 if(bsw!=null){bsw.println(header);}
225 if(bswInvalid!=null){bswInvalid.println(header);}
226 }
227
228 for(Node n : list){
229 if(n.used){
230 nodesValid++;
231 sizeValid+=n.size;
232 basesValid+=n.bases;
233 if(bsw!=null){
234 bsw.print(n.id);
235 if(printSize){
236 bsw.print('\t').print(n.size);
237 }
238 if(printClusters){
239 bsw.print('\t').print(n.edges.size());
240 bsw.print('\t').print(n.edges.get(0).b);
241 for(int i=1; i<n.edges.size(); i++){
242 bsw.print(',').print(n.edges.get(i).b);
243 }
244 }
245 bsw.println();
246 }
247 }else{
248 if(bswInvalid!=null){
249 bswInvalid.print(n.id);
250 if(printSize){
251 bswInvalid.print('\t').print(n.size);
252 }
253 if(printClusters){
254 bswInvalid.print('\t').print(n.edges.size());
255 bswInvalid.print('\t').print(n.edges.get(0).b);
256 for(int i=1; i<n.edges.size(); i++){
257 bswInvalid.print(',').print(n.edges.get(i).b);
258 }
259 }
260 bswInvalid.println();
261 }
262 }
263 }
264 for(Node n : singletons){
265 if(bsw!=null){
266 bsw.print(n.id);
267 if(printSize){
268 bsw.print('\t').print(n.size);
269 }
270 if(printClusters && n.edges!=null){
271 bsw.print('\t').print(n.edges.size());
272 bsw.print('\t').print(n.edges.get(0).b);
273 for(int i=1; i<n.edges.size(); i++){
274 bsw.print(',').print(n.edges.get(i).b);
275 }
276 }
277 bsw.println();
278 }
279 }
280
281 if(bsw!=null){errorState|=bsw.poisonAndWait();}
282 if(bswInvalid!=null){errorState|=bswInvalid.poisonAndWait();}
283 }
284
285 private HashMap<Long, Node> load(){
286 ByteFile bf=ByteFile.makeByteFile(ffin1);
287
288 HashMap<Long, Node> map=new HashMap<Long, Node>();
289
290 byte[] line=bf.nextLine();
291 if(line!=null && (Tools.startsWith(line, "Query\t") || line[0]=='#')){
292 line=bf.nextLine();
293 }
294
295 LongHashSet ignored=new LongHashSet();
296
297 while(line!=null){
298 if(line.length>0){
299 if(maxLines>0 && linesProcessed>=maxLines){break;}
300 linesProcessed++;
301 bytesProcessed+=line.length;
302 Edge e=new Edge(line);
303 boolean pass=false;
304 if(e.sizeA<1 || (e.sizeA>=minSize && (maxSize<1 || e.sizeA<=maxSize))){//Size filter
305 if(e.basesA<1 || (e.basesA>=minBases && (maxBases<1 || e.basesA<=maxBases))){//Bases filter
306 pass=true;
307 if(filter==null || (filter.passesFilter((int)e.a) && filter.passesFilter((int)e.b))){//Tax filter
308 if(e.dist>=threshold && e.ratio()>=minRatio){
309 Node n=map.get(e.a);
310 if(n==null){
311 nodesProcessed++;
312 n=new Node(e.a, e.sizeA, e.basesA);
313 map.put(e.a, n);
314 }
315 if(e.a!=e.b){n.add(e);}
316 }
317 }
318 }
319 }
320 if(!pass && !ignored.contains(e.a)){
321 ignored.add(e.a);
322 nodesIgnored++;
323 sizeIgnored+=e.sizeA;
324 basesIgnored+=e.basesA;
325 }
326 }
327 line=bf.nextLine();
328 }
329
330 errorState|=bf.close();
331 return map;
332 }
333
334 private void printResults(Timer t){
335 t.stop();
336
337 long np2=nodesProcessed+nodesIgnored;
338 double rpnano=linesProcessed/(double)(t.elapsed);
339 double npnano=np2/(double)(t.elapsed);
340 double bpnano=bytesProcessed/(double)(t.elapsed);
341
342 String rpstring=(linesProcessed<100000 ? ""+linesProcessed : linesProcessed<100000000 ? (linesProcessed/1000)+"k" : (linesProcessed/1000000)+"m");
343 String npstring=(np2<100000 ? ""+np2 : np2<100000000 ? (np2/1000)+"k" : (np2/1000000)+"m");
344 String bpstring=(bytesProcessed<100000 ? ""+bytesProcessed : bytesProcessed<100000000 ? (bytesProcessed/1000)+"k" : (bytesProcessed/1000000)+"m");
345
346 while(rpstring.length()<8){rpstring=" "+rpstring;}
347 while(npstring.length()<8){npstring=" "+npstring;}
348 while(bpstring.length()<8){bpstring=" "+bpstring;}
349
350 outstream.println("Time: \t"+t);
351 outstream.println("Lines Processed: "+rpstring+" \t"+Tools.format("%.2fk lines/sec", rpnano*1000000));
352 outstream.println("Nodes Processed: "+npstring+" \t"+Tools.format("%.2fk lines/sec", npnano*1000000));
353 outstream.println("Bytes Processed: "+bpstring+" \t"+Tools.format("%.2fm bytes/sec", bpnano*1000));
354
355 outstream.println();
356 outstream.println("Valid Nodes: \t"+nodesValid);
357 outstream.println("Invalid Nodes: \t"+(nodesProcessed-nodesValid));
358 outstream.println("Ignored Nodes: \t"+nodesIgnored);
359 outstream.println();
360 outstream.println("Valid Size: \t"+sizeValid);
361 outstream.println("Invalid Size: \t"+(sizeProcessed-sizeValid));
362 outstream.println("Ignored Size: \t"+sizeIgnored);
363 outstream.println();
364 outstream.println("Valid Bases: \t"+basesValid);
365 outstream.println("Invalid Bases: \t"+(basesProcessed-basesValid));
366 outstream.println("Ignored Bases: \t"+basesIgnored);
367
368 if(errorState){
369 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
370 }
371 }
372
373 /*--------------------------------------------------------------*/
374
375 /*--------------------------------------------------------------*/
376
377
378 private class Node implements Comparable<Node> {
379
380 Node(long id_, long size_, long bases_){
381 id=id_;
382 size=Tools.max(2, size_);
383 bases=Tools.max(2, bases_);
384 // assert(bases>2) : bases+", "+size;
385 }
386
387 void add(Edge e){
388 if(edges==null){edges=new ArrayList<Edge>();}
389 edges.add(e);
390 sum+=e.dist-threshold+0.000001;
391 }
392
393 @Override
394 public int compareTo(Node b) {
395 double ca=sum+0.25*sum*Math.log(size);
396 double cb=b.sum+0.25*b.sum*Math.log(b.size);
397 if(ca>cb){return 1;}
398 if(ca==cb){return 0;}
399 return -1;
400 // if(sum>b.sum){return 1;}
401 // if(sum==b.sum){return 0;}
402 // return -1;
403 }
404
405 @Override
406 public String toString(){
407 StringBuilder sb=new StringBuilder();
408 sb.append("Node ").append(id);
409 sb.append(", size ").append(size);
410 sb.append(", sum ").append(sum);
411 sb.append(", edges: {");
412 char c=0;
413 for(Edge e : edges){
414 if(c>0){sb.append(c);sb.append(' ');}
415 else{c=',';}
416 sb.append(e);
417 }
418 sb.append('}').append('\n');
419 return sb.toString();
420 }
421
422 final long id;
423 final long size;
424 final long bases;
425 ArrayList<Edge> edges;
426 boolean used=false;
427 double sum;
428
429 }
430
431 private class Edge {
432
433 Edge(byte[] line){
434 String[] split=new String(line).split("\t+");
435 try {
436 a=Long.parseLong(split[0]);
437 b=Long.parseLong(split[1]);
438 dist=Float.parseFloat(split[2]);
439 } catch (NumberFormatException e) {
440 System.err.println(new String(line)+"\n"+Arrays.toString(split));
441 e.printStackTrace();
442 KillSwitch.kill();
443 throw new RuntimeException();
444 }
445 long sizeA_=1, sizeB_=1;
446 if(split.length>4){
447 try {
448 sizeA_=Long.parseLong(split[3]);
449 sizeB_=Long.parseLong(split[4]);
450 } catch (NumberFormatException e) {}
451 }
452 sizeA=sizeA_;
453 sizeB=sizeB_;
454 long basesA_=1, basesB_=1;
455 if(split.length>6){
456 try {
457 basesA_=Long.parseLong(split[5]);
458 basesB_=Long.parseLong(split[6]);
459 } catch (NumberFormatException e) {}
460 }
461 basesA=basesA_;
462 basesB=basesB_;
463 // assert(basesA>2) : new String(line);
464 }
465
466 Edge(long a_, long b_, double dist_, long sizeA_, long sizeB_, long basesA_, long basesB_){
467 a=a_;
468 b=b_;
469 dist=dist_;
470 sizeA=sizeA_;
471 sizeB=sizeB_;
472 basesA=basesA_;
473 basesB=basesB_;
474 }
475
476 double ratio(){
477 double ratio=Tools.max(1, sizeA)/(float)Tools.max(1, sizeB);
478 return (invertRatio && ratio>1 ? 1/ratio : ratio);
479 }
480
481 @Override
482 public String toString(){
483 ByteBuilder sb=new ByteBuilder();
484 sb.append('(').append(a).append(',').append(b).append(',').append(dist, 3).append(')');
485 return sb.toString();
486 }
487
488 final long a;
489 final long b;
490 final double dist;
491 final long sizeA;
492 final long sizeB;
493 final long basesA;
494 final long basesB;
495
496 }
497
498 /*--------------------------------------------------------------*/
499
500 private String in1=null;
501 private String out1=null;
502 private String outInvalid=null;
503
504 /*--------------------------------------------------------------*/
505
506 private long nodesProcessed=0;
507 private long nodesValid=0;
508 private long sizeValid=0;
509 private long basesValid=0;
510
511 private long linesProcessed=0;
512 private long bytesProcessed=0;
513 private long sizeProcessed=0;
514 private long basesProcessed=0;
515
516 private long nodesIgnored=0;
517 private long sizeIgnored=0;
518 private long basesIgnored=0;
519
520 private long maxLines=Long.MAX_VALUE;
521
522 private double threshold=0;
523 private double minRatio=0;
524
525 /** Ignore nodes over this estimated size in unique kmers */
526 private long maxSize=-1;
527 /** Ignore nodes under this estimated size in unique kmers */
528 private long minSize=0;
529
530 /** Ignore nodes over this estimated size in total bp */
531 private long maxBases=-1;
532 /** Ignore nodes under this estimated size in total bp */
533 private long minBases=0;
534
535 boolean invertRatio=false;
536 boolean printSize=true;
537 boolean printHeader=true;
538 boolean printClusters=true;
539
540 private TaxFilter filter;
541
542 /*--------------------------------------------------------------*/
543
544 private final FileFormat ffin1;
545 private final FileFormat ffout1;
546 private final FileFormat ffoutInvalid;
547
548 /*--------------------------------------------------------------*/
549
550 private PrintStream outstream=System.err;
551 public static boolean verbose=false;
552 public boolean errorState=false;
553 private boolean overwrite=true;
554 private boolean append=false;
555
556 }