Debian Codegraph @

current/sketch/SketchIndex.java

raw symbols SCIP
1 package sketch;
2
3 import java.util.ArrayList;
4 import java.util.concurrent.atomic.AtomicInteger;
5 import java.util.concurrent.atomic.AtomicLong;
6
7 import kmer.AbstractKmerTable;
8 import kmer.HashBuffer;
9 import kmer.KmerTableSet;
10 import shared.Shared;
11 import shared.Timer;
12 import shared.Tools;
13 import structures.AbstractBitSet;
14 import structures.IntHashMap;
15 import structures.IntHashSetList;
16 import structures.IntList;
17
18 public class SketchIndex extends SketchObject {
19
20 public SketchIndex(ArrayList<Sketch> refs){
21 refSketches=refs;
22 tables=new KmerTableSet(new String[] {"ways="+WAYS, "tabletype="+AbstractKmerTable.ARRAYHF, "prealloc="+(prealloc>0 ? ""+prealloc : "f")},
23 20+(defaultParams.trackCounts() ? 4 : 0)+18);//An extra 18 bytes per kmer because a lot of them occur multiple times
24 tables.allocateTables();
25 tableArray=tables.tables();
26 }
27
28 public void load(){
29 spawnIndexThreads();
30 if(useWhitelist){
31 assert(!Whitelist.exists());
32 Whitelist.initialize(tableArray);
33 }
34 }
35
36 /** Spawn index threads */
37 private void spawnIndexThreads(){
38
39 //Do anything necessary prior to processing
40
41 //Determine how many threads may be used
42 final int threads=Shared.threads();
43 ArrayList<IndexThread> alht=new ArrayList<IndexThread>(threads);
44 AtomicInteger ai=new AtomicInteger(0);
45 AtomicLong totalKeys=new AtomicLong(0);
46 AtomicLong uniqueKeys=new AtomicLong(0);
47 for(int i=0; i<threads; i++){
48 alht.add(new IndexThread(ai, totalKeys, uniqueKeys));
49 }
50
51 //Start the threads
52 for(IndexThread pt : alht){
53 pt.start();
54 }
55
56 //Wait for completion of all threads
57 boolean success=true;
58 long codesProcessed=0;
59 for(IndexThread pt : alht){
60
61 //Wait until this thread has terminated
62 while(pt.getState()!=Thread.State.TERMINATED){
63 try {
64 //Attempt a join operation
65 pt.join();
66 synchronized(pt){
67 codesProcessed+=pt.codesProcessedT;
68 }
69 } catch (InterruptedException e) {
70 //Potentially handle this, if it is expected to occur
71 e.printStackTrace();
72 }
73 }
74 success&=pt.success;
75 }
76
77 //Track whether any threads failed
78 if(!success){errorState=true;}
79
80 System.err.println("Indexed "+uniqueKeys+" unique and "+totalKeys+" total hashcodes."); //For some reason codesProcessed is nondeterministic.
81
82 //Do anything necessary after processing
83 // System.gc();
84 }
85
86 /*--------------------------------------------------------------*/
87
88 public SketchResults getSketches(Sketch a, DisplayParams params){
89 if(useIntMap){
90 return getSketchesMap(a, params);
91 }else{
92 return getSketchesList(a, params);
93 }
94 }
95
96 /** Return true if added. */
97 private boolean addToTaxSet(int sketchID, IntHashSetList taxSet, int taxLevelExtended){
98 Sketch sk=refSketches.get(sketchID);
99 int taxID=sk.taxID;
100 if(taxID<0 || taxID>=minFakeID){return false;}
101 taxID=taxtree.getIdAtLevelExtended(taxID, taxLevelExtended);
102 return taxSet.add(taxID);
103 }
104
105 public SketchResults getSketchesList(final Sketch a, DisplayParams params){
106 final int minHits=params.minHits, contamLevel=params.contamLevel();
107 final boolean countContamHits=params.needContamCounts();//, metaFilter=params.hasMetaFilters(), taxFilter=params.hasTaxFilters();
108 final Timer t=(printTime ? new Timer() : null);
109
110 final int[] singleton=new int[1];
111 final IntList idList=new IntList(Tools.min(targetSketchSize, indexLimit, 1000));
112 AbstractBitSet abs=a.indexBitSet();
113 assert((abs==null)!=countContamHits);
114
115 final IntHashSetList taxSet;
116 final int[][] taxHits;
117 if(contamLevel>=0){
118 taxSet=new IntHashSetList(31);
119 taxHits=new int[a.length()][];
120 assert(taxtree!=null) : "A TaxTree is required for this operation.";
121 }else{
122 taxSet=null;
123 taxHits=null;
124 }
125
126 for(int i=0; i<a.keys.length; i++){
127 long key=a.keys[i];
128 AbstractKmerTable set=tableArray[(int)(key%WAYS)];
129 // System.err.println(set.getValue(key));
130 final int[] ids=set.getValues(key, singleton);
131 // System.err.println(Arrays.toString(ids));
132 if(ids!=null && ids[0]>=0){
133 int incr=0;
134 for(int id : ids){
135 if(id>=0){
136 final int trueID=id-1;//Minimum id is 1, indicating sketch 0.
137 idList.add(trueID);//Minimum id is 1, indicating sketch 0.
138 incr++;
139 if(taxSet!=null){addToTaxSet(trueID, taxSet, contamLevel);}
140 }
141 }
142 if(countContamHits && incr>0){abs.increment(i, incr);}
143 if(taxSet!=null && taxSet.size()>0){
144 taxHits[i]=taxSet.toArray();
145 taxSet.clear();
146 }
147 }
148
149 }
150
151 // assert(abs!=null);
152 // assert(false) : abs.cardinality();
153
154 if(printTime){
155 t.stop("\nTime for searching index: \t");
156 t.start();
157 }
158
159 // System.err.println("idList.size:"+idList.size);
160 if(idList.size<minHits){return new SketchResults(a);}//null breaks some things
161 idList.sort();
162
163 if(printTime){
164 t.stop("Time for sorting "+idList.size()+" hits:\t");
165 t.start();
166 }
167
168 ArrayList<Sketch> list=new ArrayList<Sketch>(Tools.min(8, idList.size));
169
170 int last=-1;
171 int hits=0;
172 for(int i=0; i<idList.size; i++){
173 int id=idList.get(i);
174 if(id==last){
175 // System.err.println("A: "+last+", "+id+", "+count+", "+minHits);
176 hits++;
177 }else{
178 // System.err.println("B: "+last+", "+id+", "+count+", "+minHits);
179 if(last>-1 && (hits>=minHits)){
180 final Sketch ref=refSketches.get(last);
181 list.add(ref);
182 }
183 last=id;
184 hits=0;
185 }
186 }
187 if(last>-1 && (hits>=minHits)){
188 final Sketch ref=refSketches.get(last);
189 // if((!metaFilter || ref.passesMeta(params)) && (!taxFilter || params.passesFilter(ref))){list.add(ref);}
190 list.add(ref);
191 }
192 if(printTime){
193 t.stop("Time for fetching sketches: \t");
194 }
195 return list.isEmpty() ? new SketchResults(a) : new SketchResults(a, list, taxHits);
196 }
197
198 // static ThreadLocal<IntHashMap> intMapHolder=new ThreadLocal<IntHashMap>();
199
200 public final int[] getSketchIdsMap(long key, int[] singleton){
201 AbstractKmerTable set=tableArray[(int)(key%WAYS)];
202 final int[] ids=set.getValues(key, singleton);
203 return ids;
204 }
205
206 public SketchResults getSketchesMap(final Sketch a, DisplayParams params){
207 final int minHits=params.minHits, contamLevel=params.contamLevel();
208 final boolean countContamHits=params.needContamCounts();//, metaFilter=params.hasMetaFilters(), taxFilter=params.hasTaxFilters();
209 final Timer t=(printTime ? new Timer() : null);
210 final int[] singleton=new int[1];
211
212 final IntHashMap idMap=new IntHashMap(Tools.min(targetSketchSize, indexLimit, intMapSize), 0.7f);
213
214 AbstractBitSet abs=a.indexBitSet();
215 assert((abs==null)!=countContamHits);
216
217 final IntHashSetList taxSet;
218 final int[][] taxHits;
219 if(contamLevel>=0){
220 taxSet=new IntHashSetList(31);
221 taxHits=new int[a.length()][];
222 assert(taxtree!=null) : "A TaxTree is required for this operation.";
223 }else{
224 taxSet=null;
225 taxHits=null;
226 }
227 // assert(false) : (taxHits==null)+", "+contamLevel;
228
229 if(printTime){
230 t.stop("\nTime for allocation: \t");
231 t.start();
232 }
233
234 int[] refHitCounts;
235 if(params.printRefHits){
236 refHitCounts=new int[a.keys.length];
237 a.setRefHitCounts(refHitCounts);
238 }else{refHitCounts=null;}
239
240 for(int i=0; i<a.keys.length; i++){
241 long key=a.keys[i];
242 final int[] ids=getSketchIdsMap(key, singleton);
243
244 if(ids!=null && ids[0]>=0){
245 int incr=0;
246 for(int id : ids){
247 if(id>=0){
248 final int trueID=id-1;//Minimum id is 1, indicating sketch 0.
249 idMap.increment(trueID);
250 if(!allToAll || compareSelf){incr++;}
251 if(taxSet!=null){addToTaxSet(trueID, taxSet, contamLevel);}
252 if(refHitCounts!=null && trueID!=a.sketchID){refHitCounts[i]++;}
253 }
254 }
255 if(countContamHits && incr>0){abs.increment(i, incr);}
256 if(taxSet!=null && taxSet.size()>0){
257 taxHits[i]=taxSet.toArray();
258 taxSet.clear();
259 }
260 }
261 }
262
263 if(printTime){
264 t.stop("Time for searching index: \t");
265 System.err.println("Size: \t"+idMap.size());
266 t.start();
267 }
268
269 // System.err.println("idList.size:"+idList.size);
270 final int size=idMap.size();
271 if(size==0){return new SketchResults(a);}//null breaks some things
272
273 ArrayList<Sketch> list=new ArrayList<Sketch>(Tools.min(8, size));
274
275 final int[] keys=idMap.keys();
276 final int[] values=idMap.values();
277
278 for(int i=0; i<keys.length; i++){
279 int value=values[i];
280 if(value>=minHits){
281 int id=keys[i];
282 final Sketch ref=refSketches.get(id);
283 // if((!metaFilter || ref.passesMeta(params)) && (!taxFilter || params.passesFilter(ref))){list.add(ref);}
284 list.add(ref);
285 }
286 }
287 if(printTime){
288 t.stop("Time for fetching sketches: \t");
289 }
290 return list.isEmpty() ? new SketchResults(a) : new SketchResults(a, list, taxHits);
291 }
292
293 /*--------------------------------------------------------------*/
294
295 public class IndexThread extends Thread {
296
297 public IndexThread(AtomicInteger nextIndex_, AtomicLong keyCount_, AtomicLong uniqueKeyCount_){
298 buffer=new HashBuffer(tableArray, 1000, 31, true, false);
299 nextIndex=nextIndex_;
300 keyCount=keyCount_;
301 uniqueKeyCount=uniqueKeyCount_;
302 }
303
304 @Override
305 public void run(){
306 // System.err.println("Thread running.");
307 int id=nextIndex.getAndIncrement();
308 final int numSketches=refSketches.size();
309 final int limit0=Tools.min((AUTOSIZE || AUTOSIZE_LINEAR ? Integer.MAX_VALUE : targetSketchSize), indexLimit);
310 // System.err.println("numSketches="+numSketches);
311 while(id<numSketches){
312 final Sketch sk=refSketches.get(id);
313 final long[] array=sk.keys;
314 final int limit=Tools.min(array.length, limit0);
315 // System.err.println("limit="+limit);
316 for(int i=0; i<limit; i++){
317 long key=array[i];
318 buffer.set(key, id+1);//Must be greater than zero
319 codesProcessedT++;
320 }
321 id=nextIndex.getAndIncrement();
322 }
323 long temp=buffer.flush();
324
325 synchronized(this){
326 codesProcessedT+=0;
327 success=true;
328 keyCount.getAndAdd(codesProcessedT);
329 uniqueKeyCount.getAndAdd(buffer.uniqueAdded);
330 // if(codesProcessedT>0){System.err.println(codesProcessedT);}
331 }
332 }
333
334 AtomicInteger nextIndex;
335 AtomicLong keyCount;
336 AtomicLong uniqueKeyCount;
337 long codesProcessedT=0;
338 HashBuffer buffer;
339 boolean success=false;
340
341 }
342
343 /*--------------------------------------------------------------*/
344
345 public final KmerTableSet tables;
346 public final AbstractKmerTable[] tableArray;
347 public final ArrayList<Sketch> refSketches;
348
349 public boolean errorState=false;
350
351 private static final boolean printTime=false;
352 public static boolean useIntMap=true;
353 // public static boolean useIntMapBinary=false;
354 public static int intMapSize=1000;
355 public static int indexLimit=Integer.MAX_VALUE;
356 public static final int WAYS=31;
357
358 }