Debian Codegraph @

current/barcode/PCRMatrix.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.HashMap;
8 import java.util.LinkedHashSet;
9 import java.util.Map.Entry;
10 import java.util.concurrent.locks.ReadWriteLock;
11 import java.util.concurrent.locks.ReentrantReadWriteLock;
12
13 import barcode.stub.PCRMatrixProb;
14 import barcode.stub.PCRMatrixProbAbstract;
15 import barcode.stub.PCRMatrixTile;
16 import dna.AminoAcid;
17 import fileIO.ByteStreamWriter;
18 import shared.KillSwitch;
19 import shared.Parse;
20 import shared.Tools;
21 import sketch.Sketch;
22 import structures.ByteBuilder;
23 import structures.IntList;
24
25 /**
26 * Tracks data about bar code mismatches by position.
27 * Used for demultiplexing.
28 *
29 * @author Brian Bushnell
30 * @date March 7, 2024
31 *
32 */
33 public abstract class PCRMatrix {
34
35 /*--------------------------------------------------------------*/
36 /*---------------- Constructor ----------------*/
37 /*--------------------------------------------------------------*/
38
39 protected PCRMatrix(int length1_, int length2_, int delimiter_, boolean hdistSum_) {
40 writelock();
41 if(!valid()) {
42 KillSwitch.killTraceless("This software does not have a valid license.");
43 }
44 length1=length1_;
45 length2=length2_;
46 delimiter=delimiter_;
47 hdistSum=hdistSum_ || length2<1;
48
49 length=length1+length2+(delimiter>0 ? 1 : 0);
50 delimiterPos=(delimiter>0 ? length1 : -1);
51 start2=(length2>0 ? length1+(delimiter>0 ? 1 : 0) : -1);
52 letters=length1+length2;
53
54 assert(length>0) : length+", "+length1+", "+length2+", "+delimiter;
55 assert(length1>0) : length+", "+length1+", "+length2+", "+delimiter;
56 assert(delimiter==0 || length2>0) : length+", "+length1+", "+length2+", "+delimiter;
57
58 counts=new long[length][5][5];
59 writeunlock();
60 }
61
62 public static PCRMatrix create(int length1_, int length2_, int delimiter_) {
63 return create(matrixType0, length1_, length2_, delimiter_, hdistSum0);
64 }
65
66 public static PCRMatrix create(int type, int length1_, int length2_, int delimiter_, boolean hdistSum_) {
67 if(type==HDIST_TYPE) {
68 return new PCRMatrixHDist(length1_, length2_, delimiter_, hdistSum_);
69 }else if(type==PROB_TYPE) {
70 return new PCRMatrixProb(length1_, length2_, delimiter_, hdistSum_);
71 }else if(type==TILE_TYPE) {
72 return new PCRMatrixTile(length1_, length2_, delimiter_, hdistSum_);
73 }else if(type==HDIST_OLD_TYPE) {
74 // return new PCRMatrixHDist_old(length1_, length2_, delimiter_, hdistSum_);
75 }else if(type==PROB_OLD_TYPE) {
76 // return new PCRMatrixProb_old(length1_, length2_, delimiter_, hdistSum_);
77 }
78 throw new RuntimeException("Unknown PCRMatrix type "+type);
79 }
80
81 /*--------------------------------------------------------------*/
82 /*---------------- Parsing ----------------*/
83 /*--------------------------------------------------------------*/
84
85 public static boolean parseStatic(String arg, String a, String b){
86
87 if(a.equals("localcounts")){
88 localCounts=Parse.parseBoolean(b);
89 }else if(a.equalsIgnoreCase("coding")){
90 if(Tools.startsWithDigit(b)) {
91 DemuxData.DEFAULT_CODING=Integer.parseInt(b);
92 }else if("raw".equalsIgnoreCase(b)) {
93 DemuxData.DEFAULT_CODING=Sketch.RAW;
94 }else if("a48".equalsIgnoreCase(b)) {
95 DemuxData.DEFAULT_CODING=Sketch.A48;
96 }else {
97 assert(false) : "Unknown coding format: "+b;
98 }
99 }else if(a.equalsIgnoreCase("raw")){
100 DemuxData.DEFAULT_CODING=Sketch.RAW;
101 }else if(a.equalsIgnoreCase("a48")){
102 DemuxData.DEFAULT_CODING=Sketch.A48;
103 }else if(a.equals("writesent")){
104 if(b==null || b.equalsIgnoreCase("t") || b.equalsIgnoreCase("true")) {
105 DemuxClient.writeSent="sent.txt";
106 }else if(b.equalsIgnoreCase("f") || b.equalsIgnoreCase("false")) {
107 DemuxClient.writeSent=null;
108 }else {
109 DemuxClient.writeSent=b;
110 }
111 }else if(a.equals("deltacounts")){
112 DemuxData.deltaCountsDefault=Parse.parseBoolean(b);
113 }else if(a.equals("deltacodes") || a.equals("deltabarcodes")){
114 DemuxData.deltaBarcodesDefault=Parse.parseBoolean(b);
115 }else if(a.equalsIgnoreCase("delta")){
116 DemuxData.deltaBarcodesDefault=DemuxData.deltaCountsDefault=Parse.parseBoolean(b);
117 }
118
119
120 else if(a.equalsIgnoreCase("polya") || a.equalsIgnoreCase("addpolya")){
121 addPolyA=Parse.parseBoolean(b);
122 }else if(a.equalsIgnoreCase("polyc") || a.equalsIgnoreCase("addpolyc")){
123 addPolyC=Parse.parseBoolean(b);
124 }else if(a.equalsIgnoreCase("polyg") || a.equalsIgnoreCase("addpolyg")){
125 addPolyG=Parse.parseBoolean(b);
126 }else if(a.equalsIgnoreCase("polyt") || a.equalsIgnoreCase("addpolyt")){
127 addPolyT=Parse.parseBoolean(b);
128 }else if(a.equals("hdistsum") || a.equals("pairhdist") || a.equals("hdistpair") || a.equals("sumhdist")){
129 hdistSum0=Parse.parseBoolean(b);
130 }else if(a.equals("matrixtype") || a.equals("type") || a.equals("mode") || a.equals("pcrmatrixtype")){
131 if("hdist".equals(b)) {matrixType0=HDIST_TYPE;}
132 else if("prob".equals(b) || "probability".equals(b)) {matrixType0=PROB_TYPE;}
133 else if("tile".equals(b) || "bytile".equals(b)) {matrixType0=TILE_TYPE;}
134 else {matrixType0=Integer.parseInt(b);}
135 }else if(a.equals("probability")){
136 matrixType0=(Parse.parseBoolean(b) ? PROB_TYPE : (matrixType0==PROB_TYPE ? HDIST_TYPE : matrixType0));
137 }else if(a.equals("bytile") || a.equals("tile")){
138 matrixType0=(Parse.parseBoolean(b) ? TILE_TYPE : (matrixType0==TILE_TYPE ? PROB_TYPE : matrixType0));
139 }else if(a.equalsIgnoreCase("matrixThreads")){
140 matrixThreads=Integer.parseInt(b);
141 }else if(a.equalsIgnoreCase("devmode")){
142 devMode=Parse.parseBoolean(b);
143 }else if(a.equalsIgnoreCase("ensuresorted")){
144 DemuxData.ENSURE_SORTED=Parse.parseBoolean(b);
145 }else if(PCRMatrixHDist.parseStatic(arg, a, b) ||
146 PCRMatrixProbAbstract.parseStatic(arg, a, b)){
147 //In case of shared flags with different defaults
148 PCRMatrixHDist.parseStatic(arg, a, b);
149 PCRMatrixProbAbstract.parseStatic(arg, a, b);
150 }else{
151 return false;
152 }
153 return true;
154 }
155
156 public abstract boolean parse(String arg, String a, String b);
157
158 public static void postParseStatic(){
159 PCRMatrixHDist.postParseStatic();
160 PCRMatrixProbAbstract.postParseStatic();
161 if(matrixType0==TILE_TYPE) {byTile=true;}
162 else {
163 assert(byTile==false);
164 byTile=false;
165 }
166 }
167
168 /*--------------------------------------------------------------*/
169 /*---------------- File I/O ----------------*/
170 /*--------------------------------------------------------------*/
171
172 public static class MapLine implements Comparable<MapLine> {
173
174 public MapLine(String observed_, String assigned_, long count_, float prob_){
175 observed=observed_;
176 assigned=assigned_;
177 count=count_;
178 hdist=Barcode.hdist(observed, assigned);
179 prob=prob_;
180 }
181
182 @Override
183 public int compareTo(MapLine b) {
184 int x=assigned.compareTo(b.assigned);
185 if(x!=0) {return x;}
186 if(count!=b.count) {return count>b.count ? -1 : 1;}
187 if(hdist!=b.hdist) {return hdist-b.hdist;}
188 return observed.compareTo(b.observed);
189 }
190
191 public ByteBuilder toBytes() {
192 ByteBuilder bb=new ByteBuilder();
193 bb.append(observed).tab().append(assigned);
194 bb.tab().append(count).tab().append(hdist);
195 // if(prob>=0) {bb.tab().append(prob, 5);}
196 return bb;
197 }
198
199 @Override
200 public String toString() {
201 return toBytes().toString();
202 }
203
204 final String observed;
205 final String assigned;
206 final long count;
207 final int hdist;
208 float prob=-1;
209 }
210
211 public final void printAssignmentMap(HashMap<String, String> assignmentMap,
212 String mapOut, Collection<Barcode> counts, boolean overwrite, boolean append) {
213 readlock();
214 HashMap<String, Barcode> countMap=Barcode.barcodesToMap(counts);
215 printAssignmentMap(assignmentMap, mapOut, countMap, overwrite, append);
216 readunlock();
217 }
218
219 public void printAssignmentMap(HashMap<String, String> assignmentMap,
220 String mapOut, HashMap<String, Barcode> counts, boolean overwrite, boolean append) {
221 readlock();
222 ArrayList<MapLine> lines=new ArrayList<MapLine>();
223 for(Entry<String, String> e : assignmentMap.entrySet()) {
224 String a=e.getKey(), b=e.getValue();
225 Barcode v=(counts==null ? null : counts.get(a));
226 lines.add(new MapLine(a, b, v==null ? 0 : v.count(), -1));
227 }
228 Collections.sort(lines);
229 printAssignmentMap(lines, mapOut, overwrite, append);
230 readunlock();
231 }
232
233 public static final void printAssignmentMapStatic(HashMap<String, String> assignmentMap,
234 String mapOut, Collection<Barcode> counts, boolean overwrite, boolean append) {
235 HashMap<String, Barcode> countMap=Barcode.barcodesToMap(counts);
236 printAssignmentMapStatic(assignmentMap, mapOut, countMap, overwrite, append);
237 }
238
239 public static void printAssignmentMapStatic(HashMap<String, String> assignmentMap,
240 String mapOut, HashMap<String, Barcode> counts, boolean overwrite, boolean append) {
241 ArrayList<MapLine> lines=new ArrayList<MapLine>();
242 for(Entry<String, String> e : assignmentMap.entrySet()) {
243 String a=e.getKey(), b=e.getValue();
244 Barcode v=(counts==null ? null : counts.get(a));
245 lines.add(new MapLine(a, b, v==null ? 0 : v.count(), -1));
246 }
247 Collections.sort(lines);
248 printAssignmentMap(lines, mapOut, overwrite, append);
249 }
250
251 public static final void printAssignmentMap(ArrayList<MapLine> lines, String mapOut,
252 boolean overwrite, boolean append) {
253 ByteStreamWriter bsw=new ByteStreamWriter(mapOut, overwrite, append, true);
254 bsw.start();
255 for(MapLine line : lines) {bsw.println(line.toBytes());}
256 bsw.poisonAndWait();
257 }
258
259 /*--------------------------------------------------------------*/
260 /*---------------- HDist ----------------*/
261 /*--------------------------------------------------------------*/
262
263 protected static final void fillHDistList(byte[] q, byte[][] list, IntList hdList){
264 hdList.clear();
265 for(byte[] r : list) {
266 hdList.add(hdist(q, r));
267 }
268 }
269
270 public static final int hdist(byte[] q, byte[] r) {return Barcode.hdist(q, r);}
271
272 public final int hdist(int d1, int d2) {return hdistSum ? d1+d2 : Tools.max(d1, d2);}
273
274 public final int hdist(Barcode q, String r) {
275 return hdist(q.name, r);
276 }
277
278 public final int hdist(String q, String r) {
279 return hdistSum ? Barcode.hdist(q, r) : Tools.max(Barcode.hdistL(q, r), Barcode.hdistR(q, r));
280 }
281
282 public static final long encodeHDist(long idx, long hdist, long hdist2) {
283 return idx|(hdist<<32)|(hdist2<<48);
284 }
285
286 protected final ArrayList<Barcode> highpass(Collection<Barcode> codeCounts, long minCount) {
287 if(minCount<=1) {
288 return codeCounts instanceof ArrayList ? (ArrayList<Barcode>)codeCounts
289 : new ArrayList<Barcode>(codeCounts);
290 }
291 ArrayList<Barcode> list=new ArrayList<Barcode>(256);
292 for(Barcode b : codeCounts) {
293 if(b.count()>=minCount) {list.add(b);}
294 }
295 return list;
296 }
297
298 /*--------------------------------------------------------------*/
299 /*---------------- HDist ----------------*/
300 /*--------------------------------------------------------------*/
301
302 protected final Barcode findClosestHDist(String s, int maxHDist, int clearzone) {
303 return length2<1 ? findClosestSingleHDist(s, maxHDist, clearzone) :
304 findClosestDualHDist(s, maxHDist, clearzone);
305 }
306
307 protected final Barcode findClosestSingleHDist(String q, int maxHDist, int clearzone) {
308 assert(q.length()==length1) : q+", "+length1+", "+length2;
309 final byte[] left=q.getBytes();
310 long packed=findClosestHDist(left, leftBytes, maxHDist, clearzone);
311 int idx=(int)(packed&0xFFFFFFFFL);
312 int hdist=(int)((packed>>32)&0xFFFFL);
313 int hdist2=(int)((packed>>48)&0xFFFFL);
314 // System.err.println("q="+q+/*", packed="+packed+*/", idx="+idx+", hd="+hdist+", hd2="+hdist2);
315 assert(idx<leftCodes.length);
316 assert(idx<0 || hdist+clearzone<=hdist2);
317 assert(idx<0 || hdist<=maxHDist) : idx+", "+hdist+", "+maxHDist;
318 return idx<0 ? null : leftCodes[idx];
319 }
320
321 protected final Barcode findClosestDualHDist(String q, int maxHDist, int clearzone) {
322 //if(verbose) {System.err.println("Looking for "+q);}
323 byte[] left=new byte[length1];
324 byte[] right=new byte[length2];
325 for(int i=0; i<length1; i++) {left[i]=(byte) q.charAt(i);}
326 for(int i=length2-1, j=q.length()-1; i>=0; i--, j--) {
327 right[i]=(byte) q.charAt(j);
328 }
329 final long lpacked=findClosestHDist(left, leftBytes, maxHDist, clearzone);
330 final long rpacked=findClosestHDist(right, rightBytes, maxHDist, clearzone);
331
332 final int lidx=(int)(lpacked&0xFFFFFFFFL);
333 final int lhdist=(int)((lpacked>>32)&0xFFFFL);
334 final int lhdist2=(int)((lpacked>>48)&0xFFFFL);
335 final int lmargin=lhdist2-lhdist;
336 assert(lidx<leftCodes.length);
337 assert(lidx<0 || lmargin>=clearzone);
338 assert(lidx<0 || lhdist<=maxHDist) : lidx+", "+lhdist+", "+lhdist2+", "+lmargin+", "+maxHDist;
339
340 final int ridx=(int)(rpacked&0xFFFFFFFFL);
341 final int rhdist=(int)((rpacked>>32)&0xFFFFL);
342 final int rhdist2=(int)((rpacked>>48)&0xFFFFL);
343 final int rmargin=rhdist2-rhdist;
344 assert(ridx<rightCodes.length);
345 assert(ridx<0 || rmargin>=clearzone) : ridx+", "+rhdist+", "+rhdist2+", "+rmargin;
346 assert(ridx<0 || rhdist<=maxHDist) : ridx+", "+rhdist+", "+rhdist2+", "+rmargin;
347
348 if(lidx<0 || ridx<0) {return null;}
349
350 if(hdistSum) {
351 // int idx=lidx*rightBytes.length+ridx;
352 // Barcode bc=allCodes[idx];
353 int hdist=lhdist+rhdist;
354 int hdist2=lhdist2+rhdist2;
355 int margin=hdist2-hdist;
356 // System.err.println("\n"+q+"\n"+bc+"\ntrue="+bc.hdist(q)+", max="+maxHDist+", margin="+margin+", h="+hdist+", h2="+hdist2+"\n");
357 // System.err.println((hdist>maxHDist)+" "+(margin>=clearzone)+" "+clearzone);
358 if(hdist>maxHDist || margin<clearzone) {return null;}
359 // System.err.println("PASS");
360 }
361
362 int idx=lidx*rightBytes.length+ridx;
363 Barcode bc=allCodes[idx];
364 //if(verbose) {System.err.println(q+" -> "+bc.name+" ("+bc.expected+")");}
365 if(bc.expected==1) {assert(expectedMap.containsKey(bc.name)) : "\n"+expectedMap;}
366 else {assert(!expectedMap.containsKey(bc.name));}
367 // assert(!hdistSum || bc.hdist(q)<=maxHDist) : "\n"+q+"\n"+bc+"\n"+bc.hdist(q)+", "+maxHDist+"\n";
368 assert(hdist(bc.name, q)<=maxHDist) : "\n"+q+"\n"+bc+"\n"+hdist(bc.name, q)+", "+maxHDist+"\n";
369 return bc;
370 }
371
372 protected final long findClosestHDist(byte[] q, byte[][] list, int maxHDist, int clearzone) {
373 assert(!expectedList.isEmpty());
374 int best=-1, best2=-1;
375
376 int hdist=Tools.min(q.length, letters);
377 int hdist2=hdist;
378
379 for(int i=0; i<list.length; i++) {
380 byte[] ref=list[i];
381 final int d=hdist(q, ref);
382 if(d<hdist2) {
383 best2=i;
384 hdist2=d;
385 if(d<hdist) {
386 best2=best;
387 hdist2=hdist;
388 best=i;
389 hdist=d;
390 }
391 if(hdist2<clearzone) {return -1;}
392 }
393 }
394 //if(verbose) {System.err.println("best="+best+", hdist="+hdist+", hdist2="+hdist2);}
395 if(best<0 || hdist>maxHDist) {return -1;}
396 if(hdist+clearzone>hdist2) {return -1;}
397 //if(verbose) {System.err.println("q="+new String(q)+" -> best="+new String(list[best]));}
398 return encodeHDist(best, hdist, hdist2);
399 }
400
401 /*--------------------------------------------------------------*/
402 /*---------------- Various ----------------*/
403 /*--------------------------------------------------------------*/
404
405 public abstract Barcode findClosest(String s);
406
407 public abstract void refine(Collection<Barcode> codeCounts, long minCount);
408
409 public abstract HashMap<String, String> makeAssignmentMap(Collection<Barcode> codeCounts, long minCount);
410
411 public abstract void populateCounts(ArrayList<Barcode> list, long minCount);
412
413 public abstract void makeProbs();
414
415 public abstract void initializeData();
416
417 protected abstract boolean valid();// {return true;}
418
419 /*--------------------------------------------------------------*/
420 /*---------------- Populating ----------------*/
421 /*--------------------------------------------------------------*/
422
423 @SuppressWarnings("unchecked")
424 public final void populateExpected(Collection<String> expected) {
425 writelock();
426 assert(expectedList==null);
427
428 expectedList=new ArrayList<Barcode>(expected.size());
429 expectedMap=new HashMap<String, Barcode>(expectedList.size()*2);
430 for(String s : expected) {
431 assert(s.length()==counts.length) : "Expected barcode lengths do not match actual barcode lengths."
432 +"\n"+s+", "+s.length()+", "+counts.length+", "+expected.size();
433 // assert(!expectedMap.containsKey(s)) : "Duplicate key: "+s;
434 if(!expectedMap.containsKey(s)) {
435 Barcode bc=new Barcode(s);
436 expectedList.add(bc);
437 expectedMap.put(s, bc);
438 }
439 }
440 // System.err.println("size="+expectedList.size());
441 writeunlock();
442 }
443 public final void populateExpectedFromBarcodes(Collection<Barcode> expected) {
444 writelock();
445 assert(expectedList==null);
446 assert(expected!=null && expected.size()>0) : expected;
447 expectedList=new ArrayList<Barcode>(expected.size());
448 expectedMap=new HashMap<String, Barcode>(expectedList.size()*2);
449 for(Barcode bc0 : expected) {
450 String s=bc0.name;
451 Barcode bc=new Barcode(s);
452 assert(s.length()==counts.length);
453 // assert(!expectedMap.containsKey(s)) : "Duplicate key: "+s;
454 if(!expectedMap.containsKey(s)) {
455 expectedList.add(bc);
456 expectedMap.put(s, bc);
457 }
458 }
459 // System.err.println("size="+expectedList.size());
460 writeunlock();
461 }
462
463 public abstract void populateUnexpected();
464
465 public final void populateSplitCodes() {
466 DemuxData dd=new DemuxData(length1, length2, delimiter);
467 populateSplitCodes(dd);
468 }
469
470 public final void populateSplitCodes(DemuxData dd) {
471 writelock();
472 assert(leftBytes==null) : "Already populated.";
473 LinkedHashSet<String> set1=new LinkedHashSet<String>();
474 LinkedHashSet<String> set2=new LinkedHashSet<String>();
475 @SuppressWarnings("unchecked")
476 LinkedHashSet<String>[] sets=new LinkedHashSet[] {set1, set2};
477 for(Barcode b : expectedList) {
478 String code1=b.name.substring(0, length1);
479 set1.add(code1);
480 if(length2>0) {
481 String code2=b.name.substring(start2);
482 assert(code2.length()==length2);
483 set2.add(code2);
484 }
485 }
486
487 if(dd.addPolyA && length1>0) {set1.add(poly('A', length1));}
488 if(dd.addPolyC && length1>0) {set1.add(poly('C', length1));}
489 if(dd.addPolyG && length1>0) {set1.add(poly('G', length1));}
490 if(dd.addPolyT && length1>0) {set1.add(poly('T', length1));}
491
492 if(dd.addPolyA && length2>0) {set2.add(poly('A', length2));}
493 if(dd.addPolyC && length2>0) {set2.add(poly('C', length2));}
494 if(dd.addPolyG && length2>0) {set2.add(poly('G', length2));}
495 if(dd.addPolyT && length2>0) {set2.add(poly('T', length2));}
496
497 final int size1=set1.size();
498 final int size2=set2.size();
499 leftBytes=new byte[size1][length1];
500 rightBytes=new byte[size2][length2];
501 splitBytes=new byte[][][] {leftBytes, rightBytes};
502
503 leftCodes=new Barcode[size1];
504 rightCodes=new Barcode[size2];
505 allCodes=new Barcode[size1*size2];
506 allCodesMap=new HashMap<String, Barcode>((size1*size2*3)/2);
507
508 for(int i=0; i<sets.length; i++){
509 LinkedHashSet<String> set=sets[i];
510 int j=0;
511 for(String s : set) {
512 Tools.copy(s, splitBytes[i][j]);
513 j++;
514 }
515 }
516
517 ByteBuilder bb=new ByteBuilder();
518 if(length2>0) {//dual
519 for(int i=0; i<leftBytes.length; i++) {
520 bb.clear().append(leftBytes[i]);
521 if(delimiter>0) {bb.append((byte)delimiter);}
522 int len=bb.length();
523 leftCodes[i]=new Barcode(new String(leftBytes[i]));
524 for(int j=0; j<rightBytes.length; j++) {
525 bb.setLength(len);
526 bb.append(rightBytes[j]);
527 String s=bb.toString();
528 Barcode bc=expectedMap.get(s);
529 if(bc==null) {
530 bc=new Barcode(s, 0, 0);
531 }else {
532 assert(bc.expected==1);
533 }
534 int idx=i*size2+j;
535 assert(allCodes[idx]==null);
536 allCodes[idx]=bc;
537 allCodesMap.put(s, bc);
538 rightCodes[j]=new Barcode(new String(rightBytes[j]));
539 }
540 }
541 }else {//single
542 // assert(leftCodes.length==expectedList.size()) : leftCodes.length+", "+expectedList.size()+
543 // "\n"+expectedList+"\n"+Arrays.toString(leftCodes);
544 assert(leftCodes.length==leftBytes.length) : leftCodes.length+", "+expectedList.size()+
545 "\n"+expectedList+"\n"+Arrays.toString(leftCodes);
546
547 for(int i=0; i<leftBytes.length; i++) {
548 String s=new String(leftBytes[i]);
549 Barcode bc=expectedMap.get(s);
550 if(bc==null) {
551 bc=new Barcode(s, 0, 0);
552 }else {
553 assert(bc.expected==1);
554 }
555 leftCodes[i]=bc;
556 allCodesMap.put(bc.name, bc);
557 }
558 allCodes=leftCodes;
559 }
560 writeunlock();
561 }
562
563 public void clearCounts() {
564 writelock();
565 Tools.fill(counts, 0);
566 totalCounted=totalAssigned=totalAssignedToExpected=0;
567 for(Barcode bc : expectedList) {bc.setCount(0);}
568 writeunlock();
569 }
570
571 public final float assignedFraction() {
572 return (totalAssigned/(1.0f*totalCounted));
573 }
574
575 public final float expectedFraction() {
576 return (totalAssignedToExpected/(1.0f*totalCounted));
577 }
578
579 public final float chimericFraction() {
580 return ((totalAssigned-totalAssignedToExpected)/(1.0f*totalCounted));
581 }
582
583 public final void add(Barcode query, Barcode ref) {add(query.name, ref, query.count());}
584 public final void add(String query, Barcode ref, long count) {add(query, ref, count, 0);}
585 public final void add(String query, Barcode ref, long count, int pos) {
586 assert(ref==null || ref.length()==counts.length || matrixType0>=5);
587 for(int i=0; i<query.length(); i++, pos++) {
588 final int q=query.charAt(i), r=(ref==null ? 'N' : ref.charAt(i));
589 final byte xq=baseToNumber[q], xr=baseToNumber[r];
590 counts[pos][xq][xr]+=count;
591 }
592 totalCounted+=count;
593 if(ref!=null) {
594 ref.incrementSync(count);
595 totalAssigned+=count;
596 totalAssignedToExpected+=ref.expected*count;
597 }
598 }
599
600 public ByteBuilder toBytes(ByteBuilder bb) {
601 return toBytes(counts, bb);
602 }
603
604 public ByteBuilder toAccuracy(ByteBuilder bb, boolean excludeUnknown) {
605 return toAccuracy(counts, bb, excludeUnknown);
606 }
607
608 public boolean byTile() {return false;}
609 public abstract ByteBuilder toBytesProb(ByteBuilder bb);
610
611 final public void add(PCRMatrix p) {//Unused?
612 p.readlock();
613 writelock();
614 Tools.add(counts, p.counts);
615 totalCounted+=p.totalCounted;
616 totalAssigned+=p.totalAssigned;
617 totalAssignedToExpected+=p.totalAssignedToExpected;
618 writeunlock();
619 p.readunlock();
620 }
621
622 protected final Barcode getBarcode(String s) {return expectedMap.get(s);}
623
624 /*--------------------------------------------------------------*/
625 /*---------------- Static Methods ----------------*/
626 /*--------------------------------------------------------------*/
627
628 public static final ByteBuilder toBytes(long[][][] counts, ByteBuilder bb) {
629 if(bb==null) {bb=new ByteBuilder();}
630 bb.append("#pos\tcall\tA\tC\tG\tT\tN\tSum\n");
631 for(int pos=0; pos<counts.length; pos++) {
632 for(int xq=0; xq<5; xq++) {
633 final byte q=numberToBase[xq];
634 bb.append(pos).tab().append(q);
635 long sum=0;
636 for(int xr=0; xr<5; xr++) {
637 // final byte r=numberToBase[xr];
638 final long count=counts[pos][xq][xr];
639 sum+=count;
640 bb.tab().append(count);
641 }
642 bb.tab().append(sum).nl();
643 }
644 }
645 return bb;
646 }
647
648 public static final ByteBuilder toAccuracy(long[][][] counts, ByteBuilder bb, boolean excludeUnknown) {
649 if(bb==null) {bb=new ByteBuilder();}
650
651 bb.append("#pos\tA_call\tC_call\tG_call\tT_call\tA_ref\tC_ref\tG_ref\tT_ref\n");
652 for(int pos=0; pos<counts.length; pos++) {
653 long[] refCount=new long[5];
654 long[] callCount=new long[5];
655 long[] unknown=new long[5];
656 long[] callCorrect=new long[5];
657 long[] refCorrect=new long[5];
658 long sum=0;
659 for(int xc=0; xc<5; xc++) {
660 for(int xr=0; xr<5; xr++) {
661 final long count=counts[pos][xc][xr];
662 refCount[xr]+=count;
663 callCount[xc]+=count;
664 sum+=count;
665 if(xc==xr) {
666 refCorrect[xr]+=count;
667 callCorrect[xc]+=count;
668 }
669 if(xr==4) {unknown[xc]=count;}
670 }
671 }
672 if(sum>refCount[4]) {
673 bb.append(pos);
674 for(int i=0; i<4; i++) {
675 long count=callCount[i], correct=callCorrect[i];
676 if(excludeUnknown) {count-=unknown[i];}
677 double accuracy=(count<1 ? 1 : correct/(double)count);
678 bb.tab().append(accuracy, 4);
679 // assert(false) : "\ncount="+count+", correct="+correct
680 // +", cc4="+callCount[4]+", acc="+accuracy
681 // +"\ncounts="+Arrays.toString(callCount)
682 // +"\ncorrects="+Arrays.toString(callCorrect);
683 }
684 for(int i=0; i<4; i++) {
685 long count=refCount[i], correct=refCorrect[i];
686 double accuracy=(count<1 ? 1 : correct/(double)count);
687 bb.tab().append(accuracy, 4);
688 }
689 bb.nl();
690 }
691 }
692 return bb;
693 }
694
695 private static String poly(char c, int len) {
696 ByteBuilder bb=new ByteBuilder(len);
697 for(int i=0; i<len; i++) {bb.append(c);}
698 return bb.toString();
699 }
700
701 protected final void writelock() {rwlock.writeLock().lock();}
702 protected final void writeunlock() {rwlock.writeLock().unlock();}
703 protected final void readlock() {rwlock.readLock().lock();}
704 protected final void readunlock() {rwlock.readLock().unlock();}
705
706 /*--------------------------------------------------------------*/
707 /*---------------- Fields ----------------*/
708 /*--------------------------------------------------------------*/
709
710 public final ReadWriteLock rwlock() {return rwlock;}
711 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
712
713 protected final int length;
714 protected final int length1;
715 protected final int length2;
716 protected final int delimiter;
717 protected final int delimiterPos;
718 protected final int start2;
719 protected final int letters;
720 protected final boolean hdistSum;
721
722 /** [position][Call: A,C,G,T,N][Ref: A,C,G,T,N,Sum] */
723 protected final long[][][] counts;
724 protected long totalCounted;
725 protected long totalAssigned;
726 protected long totalAssignedToExpected;
727
728 protected ArrayList<Barcode> expectedList;
729 protected HashMap<String, Barcode> expectedMap;
730
731 protected byte[][] leftBytes;
732 protected byte[][] rightBytes;
733 protected byte[][][] splitBytes;
734
735 protected Barcode[] leftCodes;
736 protected Barcode[] rightCodes;
737 protected Barcode[] allCodes;
738 protected HashMap<String, Barcode> allCodesMap;
739
740 public boolean verbose=true;
741 public static boolean verbose2=false;
742 public boolean errorState=false;
743
744 /*--------------------------------------------------------------*/
745 /*---------------- Static Fields ----------------*/
746 /*--------------------------------------------------------------*/
747
748 public static boolean errorStateS=false;
749
750 protected static boolean addPolyA=false;
751 protected static boolean addPolyC=false;
752 protected static boolean addPolyG=false;
753 protected static boolean addPolyT=false;
754
755 //This is just a maximum; will not go over Shared.threads()
756 protected static int matrixThreads=64;
757
758 protected static boolean localCounts=true;
759 public static boolean byTile=false;
760 protected static boolean devMode=false;
761
762 protected static boolean hdistSum0=false;
763 public static final int HDIST_TYPE=0, PROB_TYPE=1, TILE_TYPE=2,
764 HDIST_OLD_TYPE=7, PROB_OLD_TYPE=8;
765 protected static int matrixType0=HDIST_TYPE;
766
767 protected static final byte[] baseToNumber=AminoAcid.baseToNumber4;
768 protected static final byte[] numberToBase=AminoAcid.numberToBase;
769
770 }