Debian Codegraph @

current/barcode/DemuxData.java

raw symbols SCIP
1 package barcode;
2
3 import java.util.ArrayList;
4 import java.util.Arrays;
5 import java.util.Collection;
6 import java.util.Collections;
7 import java.util.LinkedHashSet;
8
9 import shared.LineParser1;
10 import shared.LineParser2;
11 import shared.Parse;
12 import shared.Tools;
13 import sketch.Sketch;
14 import structures.ByteBuilder;
15
16 public class DemuxData {
17
18 public static void main(String[] args) {
19 DemuxData dd=new DemuxData(10, 10, '+');
20 dd.deltaBarcodes=true;
21 dd.deltaCounts=true;
22 // dd.coding=Sketch.A48;
23
24 dd.expectedList=new LinkedHashSet<String>();
25 dd.codeCounts=new ArrayList<Barcode>();
26
27 dd.expectedList.add("ACGTACGTAC+CGAACGAACG");
28 dd.expectedList.add("GGGGGGGGGG+CGAACGAACG");
29
30 dd.codeCounts.add(new Barcode("ACGTACGTAC+CGAACGAACG", 17));
31 dd.codeCounts.add(new Barcode("ACGTACGTAC+NNNNNNNNNN", 3));
32 dd.codeCounts.add(new Barcode("GGGGGGGGGG+GNNNNNNNNN", 3));
33 dd.codeCounts.add(new Barcode("GGGGGGGGGG+NNNNNNNNNN", 3));
34 dd.codeCounts.add(new Barcode("GGGGGGGGGG+GNNNNNNNNN", 2));
35 dd.codeCounts.add(new Barcode("GGGGGGGGGT+GNNNNNNNNN", 2));
36 dd.codeCounts.add(new Barcode("GGGGGGGGGT+TNNNNNNNNN", 2));
37 dd.codeCounts.add(new Barcode("GGGGGGGGGG+TCGTACGTTT", 1));
38 dd.codeCounts.add(new Barcode("NNNNNNNNNN+NNNNNNNNNN", 1));
39 System.err.println("Expected:\n"+dd.expectedList);
40
41
42 ArrayList<Barcode> list=(ArrayList<Barcode>)(dd.codeCounts);
43
44 System.err.println("Encoding.");
45 ArrayList<byte[]> chunks=dd.encode();
46 System.err.println(new String(chunks.get(0)));
47
48 System.err.println("Decoding.");
49 DemuxData dd2=new DemuxData(chunks);
50 System.err.println("Counts:\n"+dd.codeCounts);
51 System.err.println("Result:\n"+dd2.codeCounts);
52 }
53
54 public DemuxData(int length1_, int length2_, int delimiter_){
55 length1=length1_;
56 length2=length2_;
57 barcodeDelimiter=delimiter_;
58 }
59
60 public DemuxData(ArrayList<byte[]> chunks) {
61 decode(chunks);
62 }
63
64 public ArrayList<byte[]> encode() {
65 ByteBuilder bb=new ByteBuilder();
66
67 ArrayList<byte[]> chunks=new ArrayList<byte[]>(2);
68
69 bb.append("#Flags").nl();
70 bb.append("length1=").append(length1).nl();
71 bb.append("length2=").append(length2).nl();
72 bb.append("barcodedelimiter=").append(barcodeDelimiter).nl();
73 bb.append("coding=").append(coding).nl();
74 bb.append("deltacounts=").append(deltaCounts).nl();
75 bb.append("deltabarcodes=").append(deltaBarcodes).nl();
76
77 bb.append("maxhdist0=").append(maxHDist0).nl();
78 bb.append("minratio0=").append(minRatio0, 6).nl();
79 bb.append("minprob0=").append(minProb0, 6).nl();
80 bb.append("maxhdist1=").append(maxHDist1).nl();
81 bb.append("minratio1=").append(minRatio1, 6).nl();
82 bb.append("minprob1=").append(minProb1, 6).nl();
83 bb.append("addpolya=").append(addPolyA).nl();
84 bb.append("addpolyc=").append(addPolyC).nl();
85 bb.append("addpolyg=").append(addPolyG).nl();
86 bb.append("addpolyt=").append(addPolyT).nl();
87
88
89 bb.nl().append("#Expected\t").append(expectedList.size()).nl();
90 for(String s : expectedList) {
91 bb.append(s).nl();
92 }
93
94 if(ENSURE_SORTED) {
95 Barcode prev=null;
96 boolean sorted=true;
97 for(Barcode bc : codeCounts) {
98 if(prev!=null) {
99 if(bc.compareTo(prev)<0) {
100 sorted=false;
101 break;
102 }
103 }
104 prev=bc;
105 if(!sorted) {
106 ArrayList<Barcode> list=new ArrayList<Barcode>(codeCounts);
107 Collections.sort(list);
108 codeCounts=list;
109 }
110 }
111 }
112
113 long total=0;
114 bb.nl().append("#Counts\t").append(codeCounts.size()).nl();
115 long prevCount=-1;
116 String prevName=null;
117 final byte[] buffer=new byte[64];
118 prevCode1=prevCode2=0;
119 for(Barcode bc : codeCounts) {
120 appendBarcode(bc, bb, prevCount, prevName, buffer);
121 prevCount=bc.count();
122 prevName=bc.name;
123 if(bb.length>=SEND_BUFFER_MAX_BYTES) {
124 total+=bb.length;
125 byte[] chunk=bb.toBytes();
126 chunks.add(chunk);
127 bb.clear();
128 // System.err.println("Created chunk "+toStringChunk(chunk, 50));
129 }
130 }
131 bb.append("#End").nl();
132 if(bb.length>0) {
133 total+=bb.length;
134 byte[] chunk=bb.toBytes();
135 chunks.add(chunk);
136 bb.clear();
137 // System.err.println("Created chunk "+toStringChunk(chunk, 50));
138 }
139
140 System.err.println("Encoded "+total+" bytes as "+chunks.size()+" chunks.");
141 // for(byte[] b : chunks) {
142 // System.err.println(new String(b));
143 // }
144 // assert(false);
145
146 return chunks;
147 }
148
149 private ByteBuilder appendBarcode(Barcode bc, ByteBuilder bb, long prevCount,
150 String prevName, final byte[] buffer) {
151 final long count=bc.count();
152 if(coding==Sketch.RAW) {
153 bb.append(bc.name);
154 }else if(coding==Sketch.HEX) {
155 assert(false) : coding;
156 }else if(coding==Sketch.A48) {
157 final boolean sameCount=(count==prevCount);
158 final long x1=encodeACGTN(bc.name, 0, length1);
159 assert(!deltaBarcodes || !sameCount || x1>=prevCode1) :
160 prevCode1+", "+x1+", "+prevName+", "+bc+", "+deltaBarcodes+", "+count+", "+prevCount;
161 final boolean match1=(x1==prevCode1);
162 if(!SKIP_DUPLICATE || !match1) {
163 final long x=x1;
164 final long code=(deltaBarcodes && sameCount ? x-prevCode1 : x);
165 appendA48(code, bb, buffer);
166 prevCode1=x;
167 }
168 if(length2>0) {
169 final long x2=encodeACGTN(bc.name, length1+1, length1+1+length2);
170 assert(!deltaBarcodes || !sameCount || !match1 || x2>=prevCode2) :
171 "\npc2="+prevCode2+", x2="+x2+", pn="+prevName+", n="+bc.name+", "
172 + "pcount="+prevCount+", count="+bc.count();
173 final boolean match2=(x2==prevCode2);
174 final long code=(deltaBarcodes && sameCount && match1 ? x2-prevCode2 : x2);
175 bb.tab();
176 if(!SKIP_DUPLICATE || !match2) {appendA48(code, bb, buffer);}
177 prevCode2=x2;
178 }
179 }else {
180 assert(false) : coding;
181 }
182 if(count!=prevCount) {
183 bb.tab().append(prevCount<1 || !deltaCounts ? count : prevCount-count);
184 }
185 return bb.nl();
186 }
187
188 public static final long encodeACGTN(String s, int a, int b) {
189 final byte[] table=baseToNumberACGNT;
190 //Starting with 1 would simplify things by encoding the length, at the cost of ~1 bit.
191 long code=0;
192 for(int i=a; i<b; i++) {
193 final char c=s.charAt(i);
194 final int x=table[c];
195 assert(x>=0) : x+", "+c+", "+s+"["+i+"] is not ACGTN";
196 code=code*5+x;
197 assert(code>=0) : s+", "+a+", "+b;
198 }
199 return code;
200 }
201
202 public static final void decodeACGTN(final long code0, final ByteBuilder bb, final int len) {
203 final byte[] table=numberToBaseACGNT;
204 long code=code0;
205 final int from=bb.length();
206 for(int i=0; i<len; i++) {
207 final int x=(int)(code%5);
208 code/=5;
209 final byte c=table[x];
210 bb.append(c);
211 }
212 final int to=bb.length();
213 bb.reverseInPlace(from, to);
214 // assert(false);
215 assert(code<=1) : "Code too big for expected length: len="+
216 len+", code0="+code0+", code="+code+", term="+bb;
217 }
218
219 public static final void appendA48(long value, ByteBuilder bb, byte[] temp){
220 int i=0;
221 while(value!=0){
222 byte b=(byte)(value&0x3F);
223 temp[i]=b;
224 value=value>>6;
225 i++;
226 }
227 if(i==0){
228 bb.append((byte)'0');
229 }else{
230 for(i--;i>=0;i--){
231 bb.append((char)(temp[i]+48));
232 }
233 }
234 }
235
236 public static long parseA48(byte[] line, int from){
237 if(line.length<=from){return 0;}
238 long x=0;
239 for(int i=from; i<line.length; i++){
240 final byte b=line[i];
241 if(b<48) {break;}
242 x<<=6;
243 x|=(((long)b)-48);
244 }
245 return x;
246 }
247
248 private static String toStringChunk(byte[] chunk, int x) {
249 return "'"+new String(chunk, 0, x)+"','"+new String(chunk, chunk.length-x, x)+"'";
250 }
251
252 public void decode(Collection<byte[]> chunks) {
253 System.err.println("Decoding "+chunks.size()+" chunks.");
254 int mode=0;
255 LineParser2 lp=new LineParser2('\n');
256 // expectedList=new ArrayList<Barcode>();
257 // codeCounts=new ArrayList<Barcode>();
258 int numExpected=0, expectedSeen=0;
259 int numCounts=0, countsSeen=0;
260 int chunksSeen=0;
261
262 ByteBuilder bbChunk=new ByteBuilder(), bbBuffer=new ByteBuilder();
263 long prevCount=-1;
264 prevCode1=prevCode2=0;
265 String prevName=null;
266 for(byte[] chunk0 : chunks) {
267 chunksSeen++;
268
269 byte[] chunk=chunk0;
270 if(!bbChunk.endsWith('\n')) {//This block fixes each chunk so they end with a linebreak
271 bbChunk.append(chunk0);
272 int offset=0;
273 while(!bbChunk.endsWith('\n')) {
274 offset++;
275 bbChunk.length--;
276 }
277 chunk=bbChunk.toBytes();
278 bbChunk.clear();
279 for(; offset>0; offset--) {
280 bbChunk.append(chunk0[chunk0.length-offset]);
281 }
282 }
283
284 // System.err.println("Processing chunk "+chunksSeen+": "+new String(chunk, 0, 60)+"..."+
285 // new String(chunk, chunk.length-60, 60));
286 lp.set(chunk);
287
288 //Inverted the above loop for faster processing
289 while(mode<1 && lp.hasMore()) {
290 lp.advance();
291 if(lp.currentFieldLength()>0) {
292 final byte[] line=lp.parseByteArrayFromCurrentField();
293 if(line[0]=='#') {
294 int x=parseMode(line);
295 assert(x>mode);
296 mode=x;
297 assert(mode==FLAGS) : mode+", "+new String(line);
298 }else {assert(false) : new String(line);}
299 }
300 }
301 while(mode==FLAGS && lp.hasMore()) {
302 lp.advance();
303 if(lp.currentFieldLength()>0) {
304 final byte[] line=lp.parseByteArrayFromCurrentField();
305 tabParser.set(line);
306 if(line[0]=='#') {
307 int x=parseMode(line);
308 assert(x>mode);
309 mode=x;
310 assert(mode==EXPECTED) : mode+", "+new String(line);
311 numExpected=tabParser.parseInt(1);
312 expectedList=new LinkedHashSet<String>(numExpected);
313 }else{
314 boolean x=parseFlag(line);
315 }
316 }
317 }
318 while(mode==EXPECTED && lp.hasMore()) {
319 lp.advance();
320 if(lp.currentFieldLength()>0) {
321 final byte[] line=lp.parseByteArrayFromCurrentField();
322 tabParser.set(line);
323 if(line[0]=='#') {
324 int x=parseMode(line);
325 assert(x>mode);
326 mode=x;
327 assert(mode==COUNTS) : mode+", "+new String(line);
328 numCounts=tabParser.parseInt(1);
329 codeCounts=new ArrayList<Barcode>(numCounts);
330 }else{
331 expectedSeen++;
332 Barcode bc=new Barcode(tabParser.parseString(0));
333 expectedList.add(bc.name);
334 if(length1<0) {
335 length1=bc.length1();
336 length2=bc.length2();
337 }
338 }
339 }
340 }
341 while(mode==COUNTS && lp.hasMore()) {
342 lp.advance();
343 if(lp.currentFieldLength()>0) {
344 final byte[] line=lp.parseByteArrayFromCurrentField();
345 if(lp.parseByteFromCurrentField()=='#') {
346 int x=parseMode(line);
347 assert(x>mode);
348 mode=x;
349 assert(mode==END) : mode+", "+new String(line);
350 }else{
351 countsSeen++;
352 // tabParser.set(line);
353 // Barcode bc=new Barcode(tabParser.parseString(0), tabParser.parseLong(1));
354 Barcode bc=parseCountLine(line, prevCount, prevName, bbBuffer);
355 prevCount=bc.count();
356 prevName=bc.name;
357 codeCounts.add(bc);
358 if(length1<0) {
359 length1=bc.length1();
360 length2=bc.length2();
361 }
362 }
363 }
364 }
365 if(mode==END){break;}
366 }
367 assert(countsSeen==numCounts) : countsSeen+", "+numCounts+", "+mode;
368 assert(mode==END) : mode;
369 }
370
371 private Barcode parseCountLine(byte[] line, long prevCount, String prevName, ByteBuilder bb) {
372 bb.clear();
373 tabParser.set(line);
374 int term=0;
375 tabParser.setBounds(term);
376 if(coding==Sketch.A48) {
377 final long x1, x2, x3;
378 x1=(tabParser.currentFieldLength()<1 ? -1 : parseA48(line, tabParser.a()));
379 if(length2>0) {
380 term++;
381 tabParser.setBounds(term);
382 x2=(tabParser.currentFieldLength()<1 ? -1 : parseA48(line, tabParser.a()));
383 }else {x2=-1;}
384 if(tabParser.hasMore()) {
385 term++;
386 x3=tabParser.parseLong(term);
387 }else {x3=-1;}
388
389 final long count=(x3<0 ? prevCount : deltaCounts && prevCount>0 ? prevCount-x3 : x3);
390 assert(count>0 && (count<=prevCount || prevCount<0)) : x3+", "+count+", "+prevCount+"\n"+new String(line);
391 final long code1=(x1<0 ? prevCode1 :
392 deltaBarcodes && count==prevCount ? prevCode1+x1 : x1);
393 final long code2=(x2<0 ? prevCode2 :
394 deltaBarcodes && count==prevCount && code1==prevCode1 ? prevCode2+x2 : x2);
395
396 decodeACGTN(code1, bb, length1);
397 if(length2>0) {
398 if(barcodeDelimiter>0) {bb.append((byte)barcodeDelimiter);}
399 decodeACGTN(code2, bb, length2);
400 }
401 prevCode1=code1;
402 prevCode2=code2;
403 return new Barcode(bb.toString(), count);
404 }else {
405 bb.append(line, tabParser.a(), tabParser.b());
406 }
407 long count=prevCount;
408 if(tabParser.hasMore()) {
409 term++;
410 long x=tabParser.parseLong(term);
411 count=prevCount>0 && deltaCounts ? prevCount-x : x;
412 assert(count>0) : prevCount+", "+x+", "+count;
413 }
414 return new Barcode(bb.toString(), count);
415 }
416
417 public int parseMode(byte[] line) {
418 if(Tools.startsWith(line, "#Flags")) {return FLAGS;}
419 if(Tools.startsWith(line, "#Expected")) {return EXPECTED;}
420 if(Tools.startsWith(line, "#Counts")) {return COUNTS;}
421 if(Tools.startsWith(line, "#End")) {return END;}
422 return -1;
423 }
424
425 public boolean parseFlag(byte[] line) {
426 equalsParser.set(line);
427 String a=equalsParser.parseString(0);
428 String b=equalsParser.terms()>1 ? equalsParser.parseString(1) : null;
429 boolean c=parseFlag(a, b);
430 assert(c) : a+", "+b;
431 return c;
432 }
433
434
435
436
437
438 public boolean parseFlag(String a, String b){
439
440 if(a.equalsIgnoreCase("polya") || a.equalsIgnoreCase("addpolya")){
441 addPolyA=Parse.parseBoolean(b);
442 }else if(a.equalsIgnoreCase("polyc") || a.equalsIgnoreCase("addpolyc")){
443 addPolyC=Parse.parseBoolean(b);
444 }else if(a.equalsIgnoreCase("polyg") || a.equalsIgnoreCase("addpolyg")){
445 addPolyG=Parse.parseBoolean(b);
446 }else if(a.equalsIgnoreCase("polyt") || a.equalsIgnoreCase("addpolyt")){
447 addPolyT=Parse.parseBoolean(b);
448 }
449
450 else if(a.equalsIgnoreCase("coding") || a.equalsIgnoreCase("encoding")){
451 coding=Tools.startsWithDigit(b) ? Integer.parseInt(b) : Tools.indexOf(Sketch.codingArray, b.charAt(0));
452 }else if(a.equalsIgnoreCase("length1") || a.equalsIgnoreCase("len1")){
453 length1=Integer.parseInt(b);
454 }else if(a.equalsIgnoreCase("length2") || a.equalsIgnoreCase("len2")){
455 length2=Integer.parseInt(b);
456 }else if(a.equalsIgnoreCase("delimiter") || a.equalsIgnoreCase("barcodedelimiter")){
457 barcodeDelimiter=Integer.parseInt(b);
458 }else if(a.equalsIgnoreCase("deltacounts")){
459 deltaCounts=Parse.parseBoolean(b);
460 }else if(a.equalsIgnoreCase("deltacodes") || a.equalsIgnoreCase("deltabarcodes")){
461 deltaBarcodes=Parse.parseBoolean(b);
462 }else if(a.equalsIgnoreCase("delta")){
463 deltaBarcodes=deltaCounts=Parse.parseBoolean(b);
464 }
465
466 else if(a.equals("maxhdist0") || a.equals("hdist0")){
467 maxHDist0=Integer.parseInt(b);
468 }else if(a.equals("maxhdist") || a.equals("hdist") || a.equals("maxhdist1") || a.equals("hdist1")){
469 maxHDist1=Integer.parseInt(b);
470 }else if(a.equals("minratio0") || a.equals("ratio0")){
471 minRatio0=(float)Parse.parseDoubleKMG(b);
472 assert(minRatio0>=0) : minRatio0;
473 }else if(a.equals("minratio1") || a.equals("ratio1") || a.equals("ratio") || a.equals("minratio")){
474 minRatio1=(float)Parse.parseDoubleKMG(b);
475 assert(minRatio1>=0) : minRatio1;
476 }else if(a.equals("minprob0")){
477 minProb0=(float)Parse.parseDoubleKMG(b);
478 minProb0=(minProb0>=0 ? minProb0 : (float)Math.pow(10, minProb0));
479 assert(minProb0<=1 && minProb0>=0) : minProb0;
480 }else if(a.equals("minprob1") || a.equals("minprob")){
481 minProb1=(float)Parse.parseDoubleKMG(b);
482 minProb1=(minProb1>=0 ? minProb1 : (float)Math.pow(10, minProb1));
483 assert(minProb1<=1 && minProb1>=0) : minProb1;
484
485 // }else if(a.equals("hybrid") || a.equalsIgnoreCase("hybridhdist")){
486 // hybridHDist=Tools.startsWithDigit(b) ? Integer.parseInt(b) : Parse.parseBoolean(b) ? 1 : -1;
487 // }else if(a.equalsIgnoreCase("hybridClearzone") || a.equals("hybridcz")){
488 // hybridClearzone=Integer.parseInt(b);
489 }else{
490 return false;
491 }
492 return true;
493 }
494
495 public Collection<Barcode> codeCounts;
496 public LinkedHashSet<String> expectedList;
497
498 private long prevCode1=0;
499 private long prevCode2=0;
500
501 public int length1=-1;
502 public int length2=-1;
503 public int barcodeDelimiter='+';
504
505 public int maxHDist0=6;
506 public float minRatio0=20f;
507 public float minProb0=-12;
508
509 public int maxHDist1=6;
510 public float minRatio1=1_000_000f; //Possibly 5k for single-ended (10bp), or based on length
511 public float minProb1=-5.6f;
512
513 public boolean addPolyA=PCRMatrix.addPolyA;
514 public boolean addPolyC=PCRMatrix.addPolyC;
515 public boolean addPolyG=PCRMatrix.addPolyG;
516 public boolean addPolyT=PCRMatrix.addPolyT;
517
518 public int SEND_BUFFER_MAX_BYTES=8000000;
519 public boolean deltaCounts=deltaCountsDefault;
520 public boolean deltaBarcodes=deltaBarcodesDefault;
521
522 public static boolean deltaCountsDefault=true;
523 public static boolean deltaBarcodesDefault=false;
524
525 private LineParser1 equalsParser=new LineParser1('=');
526 private LineParser1 tabParser=new LineParser1('\t');
527
528 public int type=PCRMatrix.PROB_TYPE;
529 public boolean hdistSum=false;
530 public int coding=DEFAULT_CODING;
531
532 public static int DEFAULT_CODING=Sketch.A48;
533 public static boolean ENSURE_SORTED=true;
534 public static boolean SKIP_DUPLICATE=true;
535 private static final int FLAGS=1, EXPECTED=2, COUNTS=3, END=4;
536
537 public static final byte[] numberToBaseACGNT=new byte[] {'A', 'C', 'G', 'N', 'T'};
538 public static final byte[] baseToNumberACGNT=makeBaseToNumberACGNT();
539
540 private static final byte[] makeBaseToNumberACGNT() {
541 byte[] array=new byte[128];
542 Arrays.fill(array, (byte)(-1));
543 array['A']=array['a']=0;
544 array['C']=array['c']=1;
545 array['G']=array['g']=2;
546 array['N']=array['n']=3;
547 array['T']=array['t']=4;
548 array['U']=array['u']=4;
549 return array;
550 }
551
552 }