File: Dictionary.java

package info (click to toggle)
rockhopper 2.0.3%2Bdfsg2-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 33,140 kB
  • sloc: java: 10,831; sh: 31; xml: 29; makefile: 14
file content (430 lines) | stat: -rw-r--r-- 12,536 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/*
 * Copyright 2014 Brian Tjaden
 *
 * This file is part of Rockhopper.
 *
 * Rockhopper is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * Rockhopper is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * (in the file gpl.txt) along with Rockhopper.  
 * If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * A Dictionary instance represents a dictionary of k-mers 
 * found in a set of sequencing reads.
 */

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;

public class Dictionary {

    /********************************************
     **********   Instance Variables   **********
     ********************************************/

    public Table dict;
    private int size;
    private ArrayList<StringBuilder> transcripts = new ArrayList<StringBuilder>();
    private ArrayList<KMer> seeds;
    private int seedIndex;
    public DeNovoIndex bwtIndex;



    /*****************************************
     **********   Class Variables   **********
     *****************************************/

    private static int k;  // Size of k-mer
    private static char[] alphabet_1 = {'A', 'C', 'G', 'T'};
    private static int[] alphabet_2 = new int[128];  // ASCII values



    /**************************************
     **********   Constructors   **********
     **************************************/

    public Dictionary(int k) {
	Dictionary.k = k;
	dict = new Table();
	alphabet_2['A'] = 0;
	alphabet_2['C'] = 1;
	alphabet_2['G'] = 2;
	alphabet_2['T'] = 3;
	alphabet_2['^'] = 4;
	alphabet_2['$'] = 5;
	bwtIndex = new DeNovoIndex(new ArrayList<StringBuilder>());  // Empty transcript index initially
    }



    /*************************************************
     **********   Public Instance Methods   **********
     *************************************************/

    public void add(String read) {
	String read_RC = "";
	if (Assembler.unstranded) read_RC = Assembler.reverseComplement(read);
	for (int i=0; i<read.length()-k+1; i++) {
	    if (!bwtIndex.exactMatch(read, i, i+k)) {  // k-mer not in BWT transcript index
		if (Assembler.unstranded) {  // Strand ambiguous
		    if (!bwtIndex.exactMatch(read_RC, read.length()-i-k, read.length()-i)) {  // revComp of k-mer not in index
			Long k_mer = stringToLong(read, i, i+k);
			Long k_mer_RC = stringToLong(read_RC, read.length()-i-k, read.length()-i);
			dict.add(k_mer, k_mer_RC);
		    }
		} else {  // Strand specific
		    Long k_mer = stringToLong(read, i, i+k);
		    dict.add(k_mer);
		}
	    }
	}
	if (dict.exceedsLoadFactor()) buildTranscriptsAndClearTable();  // Table is full
    }

    /**
     * Returns the number of unique elements in the dictionary.
     */
    public int getSize() {
	return size;
    }

    /**
     * Returns the number of transcripts.
     */
    public int getNumTranscripts() {
	int size = 0;
	for (StringBuilder sb : transcripts) {
	    if (sb.length() >= Assembler.minTranscriptLength) size++;
	}
	return size;
    }

    /**
     * Returns the average transcript length.
     */
    public int getAverageTranscriptLength() {
	long length = 0;
	int count = 0;
	if (transcripts.size() == 0) return 0;
	for (StringBuilder sb : transcripts) {
	    if (sb.length() >= Assembler.minTranscriptLength) {
		length += sb.length();
		count++;
	    }
	}
	if (count == 0) return 0;
	else return (int)(length/count);
    }

    public void initializeReadMapping(boolean stopAfterOneHit) {
	bwtIndex.initializeReadMapping(stopAfterOneHit);
    }

    /**
     * Map the full length read to the index of assembled transcripts.
     */
    public void mapFullLengthRead(String read) {
	bwtIndex.exactMatch_fullRead(read);
    }

    /**
     * Map the full length *paired-end* read to the index of assembled transcripts.
     */
    public void mapFullLengthRead(String read, String read2) {
	bwtIndex.exactMatch_fullRead(read, read2);
    }

    public void assembleTranscripts() {
	size = dict.size();  // Compute size

	// Extend existing transcripts
	for (int i=0; i<transcripts.size(); i++) {
	    extendSeedForward(transcripts.get(i));
	    extendSeedBackward(transcripts.get(i));
	}

	// Create new transcripts
	prepareSeeds();
	Long seed = getSeed();
	while (seed != null) {
	    StringBuilder transcript = new StringBuilder(longToString(seed));
	    dict.remove(seed);  // Remove seed from dict
	    extendSeedForward(transcript);
	    extendSeedBackward(transcript);
	    seed = getSeed();
	    transcripts.add(transcript);
	}
	dict = new Table();
	bwtIndex = new DeNovoIndex(transcripts);
	System.gc();
    }



    /**************************************************
     **********   Private Instance Methods   **********
     **************************************************/

    /**
     * Check if the table is full.
     * If so, assemble transcripts via deBruijn graph and
     * clear the dictionary.
     */
    private synchronized void buildTranscriptsAndClearTable() {
	if (dict.exceedsLoadFactor()) {  // Table is full
	    assembleTranscripts();
	}
    }

    /**
     * Returns the most frequently occurring k-mer subject
     * to the following restrictions:
     *  - The seed is sufficiently expressed, i.e., sufficiently many reads supporting the k-mer
     *  - The information content is at least 1.5
     *  - The k-mer is not palindromic (deleted).
     */
    private Long getSeed() {
	while (seedIndex < seeds.size()) {
	    Long key = seeds.get(seedIndex).key;
	    seedIndex++;
	    if (dict.containsKey(key) && (informationContent(key) >= 1.5)) return key;
	}
	return null;
    }

    /**
     * Since we need to repeatedly determine the best seed in the
     * dictionary (an expensive operation for a hashtable), we 
     * create a sorted vector so that finding the best seed is
     * efficient.
     */
    private void prepareSeeds() {
	seeds = new ArrayList<KMer>();
	for (int i=0; i<dict.capacity; i++) {
	    int value = dict.getValueAtIndex(i);
	    if (value == 0) continue;
	    Long key = dict.getKeyAtIndex(i);
	    if (value >= Assembler.minSeedExpression) seeds.add(new KMer(key, value));
	}
	Collections.sort(seeds, Collections.reverseOrder());
	seedIndex = 0;
    }

    /**
     * Extends transcript 5' to 3'.
     */
    private void extendSeedForward(StringBuilder transcript) {
	boolean done = false;
	while (!done) {
	    int max = Assembler.minExpression-1;
	    int maxIndex = -1;
	    transcript.append('?');
	    for (int i=0; i<alphabet_1.length; i++) {
		transcript.setCharAt(transcript.length()-1, alphabet_1[i]);
		Long k_mer = stringToLong(transcript, transcript.length()-k, transcript.length());
		if (dict.containsKey(k_mer) && (dict.get(k_mer) > max)) {
		    max = dict.get(k_mer);
		    maxIndex = i;
		}
		if (Assembler.unstranded) {  // Strand ambiguous
		    Long k_mer_RC = stringToLong(Assembler.reverseComplement(transcript.substring(transcript.length()-k)), 0, k);
		    if (dict.containsKey(k_mer_RC) && (dict.get(k_mer_RC) > max)) {
			max = dict.get(k_mer_RC);
			maxIndex = i;
		    }
		}
	    }
	    if (maxIndex >= 0) {  // Found an extension
		transcript.setCharAt(transcript.length()-1, alphabet_1[maxIndex]);
		Long key = stringToLong(transcript, transcript.length()-k, transcript.length());
		dict.remove(key);  // Remove k-mer from dict
		if (Assembler.unstranded) {  // Strand ambiguous
		    Long key_RC = stringToLong(Assembler.reverseComplement(transcript.substring(transcript.length()-k)), 0, k);
		    dict.remove(key_RC);  // Remove k-mer from dict
		}
	    } else {  // No extension
		transcript.deleteCharAt(transcript.length()-1);
		done = true;
	    }
	}
    }

    /**
     * Extends transcript 3' to 5'.
     */
    private void extendSeedBackward(StringBuilder transcript) {
	transcript.reverse();
	boolean done = false;
	while (!done) {
	    int max = Assembler.minExpression-1;
	    int maxIndex = -1;
	    transcript.append('?');
	    for (int i=0; i<alphabet_1.length; i++) {
		transcript.setCharAt(transcript.length()-1, alphabet_1[i]);
		Long k_mer = stringToLong_Reverse(transcript, transcript.length()-k, transcript.length());
		if (dict.containsKey(k_mer) && (dict.get(k_mer) > max)) {
		    max = dict.get(k_mer);
		    maxIndex = i;
		}
		if (Assembler.unstranded) {  // Strand ambiguous
		    Long k_mer_RC = stringToLong_Reverse(Assembler.reverseComplement(transcript.substring(transcript.length()-k)), 0, k);
		    if (dict.containsKey(k_mer_RC) && (dict.get(k_mer_RC) > max)) {
			max = dict.get(k_mer_RC);
			maxIndex = i;
		    }
		}
	    }
	    if (maxIndex >= 0) {  // Found an extension
		transcript.setCharAt(transcript.length()-1, alphabet_1[maxIndex]);
		Long key = stringToLong_Reverse(transcript, transcript.length()-k, transcript.length());
		dict.remove(key);  // Remove k-mer from dict
		if (Assembler.unstranded) {  // Strand ambiguous
		    Long key_RC = stringToLong_Reverse(Assembler.reverseComplement(transcript.substring(transcript.length()-k)), 0, k);
		    dict.remove(key_RC);  // Remove k-mer from dict
		}
	    } else {  // No extension
		transcript.deleteCharAt(transcript.length()-1);
		done = true;
	    }
	}
	transcript.reverse();
    }



    /***********************************************
     **********   Private Class Methods   **********
     ***********************************************/

    private static Long stringToLong(String s, int index1, int index2) {
	long num = 0;
	for (int i=index1; i<index2; i++) {
	    num = num << 2;
	    num += charToInt(s.charAt(i));
	}
	return new Long(num);
    }

    private static Long stringToLong(StringBuilder sb, int index1, int index2) {
	long num = 0;
	for (int i=index1; i<index2; i++) {
	    num = num << 2;
	    num += charToInt(sb.charAt(i));
	}
	return new Long(num);
    }

    private static Long stringToLong_Reverse(String s, int index1, int index2) {
	long num = 0;
	for (int i=index2-1; i>=index1; i--) {
	    num = num << 2;
	    num += charToInt(s.charAt(i));
	}
	return new Long(num);
    }

    private static Long stringToLong_Reverse(StringBuilder sb, int index1, int index2) {
	long num = 0;
	for (int i=index2-1; i>=index1; i--) {
	    num = num << 2;
	    num += charToInt(sb.charAt(i));
	}
	return new Long(num);
    }

    private static String longToString(Long key) {
	long num = key.longValue();
	StringBuilder sb = new StringBuilder(k+1);
	for (int i=0; i<k; i++) {
	    sb.append(intToChar((int)num & 3));
	    num = num >>> 2;
	}
	return sb.reverse().toString();
    }

    public static int charToInt(char c) {
	return alphabet_2[c];
    }

    private static char intToChar(int num) {
	return alphabet_1[num];
    }

    private static double informationContent(Long k_mer) {
	double[] counts = new double[4];
	long num = k_mer.longValue();
	for (int i=0; i<k; i++) {
	    counts[((int)num & 3)] += 1.0;
	    num = num >>> 2;
	}

	double sum = 0.0;
	for (int i=0; i<counts.length; i++) sum += counts[i];

	double informationContent = 0.0;
	for (int i=0; i<counts.length; i++) {
	    if (counts[i] > 0.0) {
		double frequency = counts[i] / sum;
		informationContent += frequency * Math.log(frequency) / Math.log(2.0);
	    }
	}
	return 0.0 - informationContent;
    }



    /*************************************
     **********   Main Method   **********
     *************************************/

    public static void main(String[] args) {

	int k = 25;
	Dictionary d = new Dictionary(k);

	String s = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAG";
	System.out.println(s);
	for (int i=0; i<d.dict.capacity; i++) {
	    int value = d.dict.getValueAtIndex(i);
	    if (value == 0) continue;
	    Long key = d.dict.getKeyAtIndex(i);
	    System.out.println(longToString(key) + "\t" + value);
	}
    }

}



/**************************************
 **********   Helper Class   **********
 **************************************/

class KMer implements Comparable<KMer> {

    public Long key;
    public Integer count;

    public KMer(Long key, Integer count) {
	this.key = key;
	this.count = count;
    }

    public int compareTo(KMer k) {
	return count.compareTo(k.count);
    }
}