Debian Codegraph @

current/jgi/PickSubset.java

raw symbols SCIP
1 package jgi;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5 import java.util.Collections;
6 import java.util.HashMap;
7 import java.util.Map.Entry;
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.LineParser1;
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 structures.ByteBuilder;
23
24 /**
25 * Select a maximally diverse subset from an all-to-all ANI comparison,
26 * by removing a node with the highest pairwise ANI until the
27 * desired number of nodes remain, or the desired ANI threshold
28 * is reached.
29 * Unlike RepresentativeSet, it does not use taxonomy or centroids.
30 * @author Brian Bushnell
31 * @date July 30, 2024
32 *
33 */
34 public class PickSubset {
35
36 /*--------------------------------------------------------------*/
37 /*---------------- Initialization ----------------*/
38 /*--------------------------------------------------------------*/
39
40 /**
41 * Code entrance from the command line.
42 * @param args Command line arguments
43 */
44 public static void main(String[] args){
45 //Start a timer immediately upon code entrance.
46 Timer t=new Timer();
47
48 //Create an instance of this class
49 PickSubset x=new PickSubset(args);
50
51 //Run the object
52 x.process(t);
53
54 //Close the print stream if it was redirected
55 Shared.closeStream(x.outstream);
56 }
57
58 /**
59 * Constructor.
60 * @param args Command line arguments
61 */
62 public PickSubset(String[] args){
63
64 {//Preparse block for help, config files, and outstream
65 PreParser pp=new PreParser(args, /*getClass()*/null, false);
66 args=pp.args;
67 outstream=pp.outstream;
68 }
69
70 //Set shared static variables prior to parsing
71 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
72 ReadWrite.setZipThreads(Shared.threads());
73
74 {//Parse the arguments
75 final Parser parser=parse(args);
76 overwrite=parser.overwrite;
77 append=parser.append;
78
79 in1=parser.in1;
80
81 out1=parser.out1;
82 }
83
84 validateParams();
85 fixExtensions(); //Add or remove .gz or .bz2 as needed
86 checkFileExistence(); //Ensure files can be read and written
87 checkStatics(); //Adjust file-related static fields as needed for this program
88
89 ffout1=FileFormat.testOutput(out1, FileFormat.TXT, null, true, overwrite, append, false);
90 ffoutInvalid=FileFormat.testOutput(outInvalid, FileFormat.TXT, null, true, overwrite, append, false);
91 ffin1=FileFormat.testInput(in1, FileFormat.TXT, null, true, true);
92 }
93
94 /*--------------------------------------------------------------*/
95 /*---------------- Initialization Helpers ----------------*/
96 /*--------------------------------------------------------------*/
97
98 /** Parse arguments from the command line */
99 private Parser parse(String[] args){
100
101 //Create a parser object
102 Parser parser=new Parser();
103
104 //Set any necessary Parser defaults here
105 //parser.foo=bar;
106 // parser.out1="stdout";
107
108 //Parse each argument
109 for(int i=0; i<args.length; i++){
110 String arg=args[i];
111
112 //Break arguments into their constituent parts, in the form of "a=b"
113 String[] split=arg.split("=");
114 String a=split[0].toLowerCase();
115 String b=split.length>1 ? split[1] : null;
116 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
117
118 if(a.equals("invalid") || a.equals("outu")){
119 outInvalid=b;
120 }else if(a.equals("nodes") || a.equals("files") || a.equals("genomes")){
121 desiredNodes=Integer.parseInt(b);
122 }else if(a.equalsIgnoreCase("ani") || a.equalsIgnoreCase("maxani")){
123 desiredANI=Float.parseFloat(b);
124 }else if(a.equals("lines")){
125 maxLines=Long.parseLong(b);
126 if(maxLines<0){maxLines=Long.MAX_VALUE;}
127 }else if(a.equals("verbose")){
128 verbose=Parse.parseBoolean(b);
129 ByteFile1.verbose=verbose;
130 ByteFile2.verbose=verbose;
131 ReadWrite.verbose=verbose;
132 }else if(a.equals("parse_flag_goes_here")){
133 long fake_variable=Parse.parseKMG(b);
134 //Set a variable here
135 }else if(parser.parse(arg, a, b)){
136 //do nothing
137 }else{
138 outstream.println("Unknown parameter "+args[i]);
139 assert(false) : "Unknown parameter "+args[i];
140 throw new RuntimeException("Unknown parameter "+args[i]);
141 }
142 }
143
144 return parser;
145 }
146
147 /** Add or remove .gz or .bz2 as needed */
148 private void fixExtensions(){
149 in1=Tools.fixExtension(in1);
150 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
151 }
152
153 /** Ensure files can be read and written */
154 private void checkFileExistence(){
155 //Ensure output files can be written
156 if(!Tools.testOutputFiles(overwrite, append, false, out1)){
157 outstream.println((out1==null)+", "+out1);
158 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output file "+out1+"\n");
159 }
160
161 //Ensure input files can be read
162 if(!Tools.testInputFiles(false, true, in1)){
163 throw new RuntimeException("\nCan't read some input files.\n");
164 }
165
166 //Ensure that no file was specified multiple times
167 if(!Tools.testForDuplicateFiles(true, in1, out1)){
168 throw new RuntimeException("\nSome file names were specified multiple times.\n");
169 }
170 }
171
172 /** Adjust file-related static fields as needed for this program */
173 private static void checkStatics(){
174 //Adjust the number of threads for input file reading
175 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
176 ByteFile.FORCE_MODE_BF2=true;
177 }
178
179 // if(!ByteFile.FORCE_MODE_BF2){
180 // ByteFile.FORCE_MODE_BF2=false;
181 // ByteFile.FORCE_MODE_BF1=true;
182 // }
183 }
184
185 /** Ensure parameter ranges are within bounds and required parameters are set */
186 private boolean validateParams(){
187 // assert(minfoo>0 && minfoo<=maxfoo) : minfoo+", "+maxfoo;
188 assert(desiredANI>0 || desiredNodes>0) : "Desired ANI or genomes must be greater than 0.";
189 return true;
190 }
191
192 /*--------------------------------------------------------------*/
193 /*---------------- Outer Methods ----------------*/
194 /*--------------------------------------------------------------*/
195
196 /** Create streams and process all data */
197 void process(Timer t){
198
199 ByteFile bf=ByteFile.makeByteFile(ffin1);
200 ByteStreamWriter bsw=makeBSW(ffout1);
201 ByteStreamWriter bswInvalid=makeBSW(ffoutInvalid);
202
203 // assert(false) : "Header goes here.";
204 if(bsw!=null){
205 // assert(false) : "Header goes here.";
206 }
207
208 ArrayList<Edge> edges=readFile(bf);
209 ArrayList<Node> chosen=pickNodes(edges, desiredNodes);
210 if(bsw!=null) {
211 for(Node n : chosen) {
212 bsw.println(n.name);
213 }
214 }
215 if(bswInvalid!=null) {
216 for(Entry<String, Node> e : nodeMap.entrySet()) {
217 Node n=e.getValue();
218 if(!n.valid) {
219 bswInvalid.println(n.name);
220 }
221 }
222 }
223
224 float maxANI=0;
225 for(Node n : chosen) {
226 for(Edge e : n.edges) {
227 Node r=nodeMap.get(e.ref);
228 if(r.valid) {
229 maxANI=Tools.max(maxANI, e.ani);
230 }
231 }
232 }
233
234 errorState|=bf.close();
235 if(bsw!=null){errorState|=bsw.poisonAndWait();}
236 if(bswInvalid!=null){errorState|=bswInvalid.poisonAndWait();}
237
238 t.stop();
239
240 outstream.println(Tools.timeLinesBytesProcessed(t, linesProcessed, bytesProcessed, 8));
241
242 outstream.println();
243 outstream.println("Nodes In: \t"+nodeMap.size());
244 outstream.println("Nodes Out: \t"+chosen.size());
245 outstream.println("Maximum ANI: \t"+maxANI);
246
247 //Throw an exception of there was an error in a thread
248 if(errorState){
249 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
250 }
251 }
252
253 /*--------------------------------------------------------------*/
254 /*---------------- Inner Methods ----------------*/
255 /*--------------------------------------------------------------*/
256
257 private ArrayList<Edge> readFile(ByteFile bf){
258 byte[] line=bf.nextLine();
259 ByteBuilder bb=new ByteBuilder();
260
261 ArrayList<Edge> edges=new ArrayList<Edge>();
262 while(line!=null){
263 if(line.length>0){
264 if(maxLines>0 && linesProcessed>=maxLines){break;}
265 linesProcessed++;
266 bytesProcessed+=(line.length+1);
267
268 if(line[0]!='#'){
269 Edge e=new Edge(line);
270 Node query=nodeMap.get(e.query);
271 if(query==null) {
272 query=new Node(line);
273 nodeMap.put(e.query, query);
274 }
275 if(!e.query.equals(e.ref)) {//if not a self edge
276 query.edges.add(e);
277 edges.add(e);
278 }
279 }
280 }
281 line=bf.nextLine();
282 }
283 return edges;
284 }
285
286 ArrayList<Node> pickNodes(ArrayList<Edge> list, int desiredNodes){
287 int remaining=nodeMap.size();
288 for(Node n : nodeMap.values()) {n.calcSum();}
289 Collections.sort(list);
290 Collections.reverse(list);
291 for(Edge e : list) {
292 if(remaining<=desiredNodes || e.ani<=desiredANI) {break;}
293 if(e.valid) {
294 Node q=nodeMap.get(e.query);
295 Node r=nodeMap.get(e.ref);
296 if(q.valid && r.valid) {
297 if(q.compareTo(r)>=0) {
298 q.setInvalid();
299 }else {
300 r.setInvalid();
301 }
302 remaining--;
303 }
304 e.valid=false;
305 }
306 }
307 ArrayList<Node> chosen=new ArrayList<Node>(remaining);
308 for(Node n : nodeMap.values()) {
309 if(n.valid) {chosen.add(n);}
310 }
311 return chosen;
312 }
313
314 private static ByteStreamWriter makeBSW(FileFormat ff){
315 if(ff==null){return null;}
316 ByteStreamWriter bsw=new ByteStreamWriter(ff);
317 bsw.start();
318 return bsw;
319 }
320
321 private HashMap<String, Node> nodeMap=new HashMap<String, Node>();
322
323 /*--------------------------------------------------------------*/
324
325 private class Node implements Comparable<Node> {
326
327 Node(byte[] line){
328 lp.set(line);
329 name=lp.parseString(0);
330 size=lp.parseLong(3);
331 bases=lp.parseLong(5);
332 }
333
334 float calcSum() {
335 sum=0;
336 for(Edge e : edges) {
337 sum+=e.kid;
338 sum+=e.ani*0.0001;//In case kid is absent
339 }
340 return sum;
341 }
342
343 void setInvalid() {
344 assert(valid);
345 valid=false;
346 for(Edge e : edges) {e.valid=false;}
347 }
348
349 @Override
350 public int compareTo(Node o) {
351 if(sum!=o.sum) {return sum>o.sum ? 1 : -1;}
352 return name.compareTo(o.name);
353 }
354
355
356 final String name;
357 long size;
358 long bases;
359 float sum;
360 boolean valid=true;
361 ArrayList<Edge> edges=new ArrayList<Edge>();
362 }
363
364 // #Query Ref ANI QSize RefSize QBases RBases QTaxID RTaxID KID WKID SSU
365 // a.fa b.fa 80.980 11178684 8473676 12055201 8514625 -1 -1 0.237 0.313 94.233
366
367 private class Edge implements Comparable<Edge> {
368
369 Edge(byte[] line){
370 lp.set(line);
371 query=lp.parseString(0);
372 ref=lp.parseString(1);
373 ani=lp.parseFloat(2);
374 kid=(lp.terms()>9) ? lp.parseFloat(9) : 0;
375 if(lp.terms()<11 || lp.termEquals('.', 11)) {
376 ssu=0;
377 }else {
378 ssu=lp.parseFloat(11);
379 }
380 }
381
382 @Override
383 public int compareTo(Edge o) {
384 if(ani!=o.ani) {return ani>o.ani ? 1 : -1;}
385 if(kid!=o.kid) {return kid>o.kid ? 1 : -1;}
386 int x=query.compareTo(o.query);
387 if(x!=0) {return x;}
388 return ref.compareTo(o.ref);
389 }
390
391 final String query;
392 final String ref;
393 float ani;
394 float kid;
395 float ssu;
396 boolean valid=true;
397 }
398
399 private LineParser1 lp=new LineParser1('\t');
400
401 /*--------------------------------------------------------------*/
402 /*---------------- Fields ----------------*/
403 /*--------------------------------------------------------------*/
404
405 /** Primary input file path */
406 private String in1=null;
407
408 /** Primary output file path */
409 private String out1=null;
410
411 /** Junk output file path */
412 private String outInvalid=null;
413
414 private int desiredNodes=0;
415 private float desiredANI=0;
416
417 /*--------------------------------------------------------------*/
418
419 private long edgesProcessed=0;
420 private long nodesProcessed=0;
421 private long edgesOut=0;
422 private long nodesOut=0;
423
424 private long linesProcessed=0;
425 private long linesOut=0;
426 private long bytesProcessed=0;
427 private long bytesOut=0;
428
429 private long maxLines=Long.MAX_VALUE;
430
431 /*--------------------------------------------------------------*/
432 /*---------------- Final Fields ----------------*/
433 /*--------------------------------------------------------------*/
434
435 /** Input File */
436 private final FileFormat ffin1;
437 /** Output File */
438 private final FileFormat ffout1;
439 /** Optional Output File for Junk */
440 private final FileFormat ffoutInvalid;
441
442 /*--------------------------------------------------------------*/
443 /*---------------- Common Fields ----------------*/
444 /*--------------------------------------------------------------*/
445
446 /** Print status messages to this output stream */
447 private PrintStream outstream=System.err;
448 /** Print verbose messages */
449 public static boolean verbose=false;
450 /** True if an error was encountered */
451 public boolean errorState=false;
452 /** Overwrite existing output files */
453 private boolean overwrite=true;
454 /** Append to existing output files */
455 private boolean append=false;
456
457 }