/
TDFWriter.java
368 lines (294 loc) · 11.6 KB
/
TDFWriter.java
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
/*
* The MIT License (MIT)
*
* Copyright (c) 2007-2015 Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.tdf;
import org.broad.igv.logging.*;
import org.broad.igv.exceptions.DataLoadException;
import org.broad.igv.track.TrackType;
import org.broad.igv.track.WindowFunction;
import org.broad.igv.util.CompressionUtils;
import java.io.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Assumptions
* <p/>
* Little endian is used throughout
* Strings are null terminated ascii (single byte)
*
* @author jrobinso
*/
public class TDFWriter {
static private Logger log = LogManager.getLogger(TDFWriter.class);
static private int version = 4;
static final String ROOT_GROUP = "/";
public static final String CHROMOSOMES = "chromosomes";
OutputStream fos = null;
long bytesWritten = 0;
File file;
Map<String, TDFGroup> groupCache = new LinkedHashMap();
Map<String, TDFDataset> datasetCache = new LinkedHashMap();
Map<String, IndexEntry> datasetIndex = new LinkedHashMap();
Map<String, IndexEntry> groupIndex = new LinkedHashMap();
long indexPositionPosition;
boolean compressed;
private final CompressionUtils compressionUtils;
public TDFWriter(File f,
String genomeId,
TrackType trackType,
String trackLine, String[] trackNames,
Collection<WindowFunction> windowFunctions,
boolean compressed) {
if (f.getName().endsWith(".tdf")) {
this.file = f;
} else {
this.file = new File(f.getAbsolutePath() + ".tdf");
}
this.compressed = compressed;
try {
// OutputStream os;
// if(file != null){
// os = new FileOutputStream(file);
// }else{
// //TODO be able to write TDF to output stream. Would need to buffer because
// //index position is at the beginning.
// os = System.out;
// }
fos = new BufferedOutputStream(new FileOutputStream(file));
writeHeader(genomeId, trackType, trackLine, trackNames, windowFunctions);
TDFGroup rootGroup = new TDFGroup("/");
groupCache.put(rootGroup.getName(), rootGroup);
} catch (IOException ex) {
log.error("Error opening output stream to file: " + file, ex);
throw new DataLoadException("Error creating file", "" + file);
}
compressionUtils = new CompressionUtils();
}
private void writeHeader(String genomeId,
TrackType trackType,
String trackLine, String[] trackNames,
Collection<WindowFunction> windowFunctions) throws IOException {
// Magic number -- 4 bytes
byte[] magicNumber = new byte[]{'T', 'D', 'F', '4'};
BufferedByteWriter buffer = new BufferedByteWriter(24);
buffer.put(magicNumber);
buffer.putInt(version);
// Reserve space for the master index pointer and byte count.
// The actual values will be written at the end
indexPositionPosition = buffer.bytesWritten();
buffer.putLong(0l);
buffer.putInt(0);
write(buffer.getBytes());
buffer = new BufferedByteWriter(24);
// Window function definition
buffer.putInt(windowFunctions.size());
for (WindowFunction wf : windowFunctions) {
buffer.putNullTerminatedString(wf.toString());
}
// Track type
buffer.putNullTerminatedString(trackType.toString());
// Reserved space for the track line
byte[] trackLineBuffer = bufferString(trackLine, 1024);
buffer.put(trackLineBuffer);
// Track names
buffer.putInt(trackNames.length);
for (String nm : trackNames) {
buffer.putNullTerminatedString(nm);
}
// Fields below added in version 3
// Genome id
buffer.putNullTerminatedString(genomeId);
// Flags
int flags = 0;
if (compressed) {
flags |= TDFReader.GZIP_FLAG;
} else {
flags &= ~TDFReader.GZIP_FLAG;
}
buffer.putInt(flags);
byte[] bytes = buffer.getBytes();
writeInt(bytes.length);
write(buffer.getBytes());
}
/**
* Write out the group and dataset index and close the underlying file.
*/
public void closeFile() {
try {
writeDatasets();
writeGroups();
long indexPosition = bytesWritten;
writeIndex();
int nbytes = (int) (bytesWritten - indexPosition);
fos.close();
writeIndexPosition(indexPosition, nbytes);
} catch (IOException ex) {
log.error("Error closing file", ex);
}
}
private void writeIndexPosition(long indexPosition, int nbytes) {
try {
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.getChannel().position(indexPositionPosition);
// Write as little endian
BufferedByteWriter buffer = new BufferedByteWriter();
buffer.putLong(indexPosition);
buffer.putInt(nbytes);
raf.write(buffer.getBytes());
raf.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public TDFGroup getGroup(String name) {
return groupCache.get(name);
}
public TDFGroup getRootGroup() {
if (!groupCache.containsKey("/")) {
groupCache.put("/", new TDFGroup("/"));
}
return groupCache.get("/");
}
public TDFGroup createGroup(String name) {
if (groupCache.containsKey(name)) {
throw new RuntimeException("Group: " + name + " already exists");
}
TDFGroup group = new TDFGroup(name);
groupCache.put(name, group);
return group;
}
public TDFDataset createDataset(String name, TDFDataset.DataType dataType,
int tileWidth, int nTiles) {
if (datasetCache.containsKey(name)) {
throw new RuntimeException("Dataset: " + name + " already exists");
}
TDFDataset ds = new TDFDataset(name, dataType, tileWidth, nTiles);
datasetCache.put(name, ds);
return ds;
}
// Note this will only work for "fixed step" format. Others need location arrays
// Tile layout
public void writeTile(String dsId, int tileNumber, TDFTile tile) throws IOException {
TDFDataset dataset = datasetCache.get(dsId);
if (dataset == null) {
throw new java.lang.NoSuchFieldError("Dataset: " + dsId + " doese not exist. " +
"Call createDataset first");
}
long pos = bytesWritten;
if (tileNumber < dataset.tilePositions.length) {
dataset.tilePositions[tileNumber] = pos;
// Write the tile contents to a byte buffer first, so we can optionally gzip it
BufferedByteWriter buffer = new BufferedByteWriter();
tile.writeTo(buffer);
byte[] bytes = buffer.getBytes();
if (compressed) {
bytes = compressionUtils.compress(bytes);
}
write(bytes);
int nBytes = bytes.length;
dataset.tileSizes[tileNumber] = nBytes;
} else {
// The occasional tile number == tile array size is expected, but tile
// numbers larger than that are not
if (tileNumber > dataset.tilePositions.length) {
System.out.println("Unexpected tile number: " + tileNumber + " (max of " + dataset.tilePositions.length + " expected).");
}
}
}
private void writeGroups() throws IOException {
for (TDFGroup group : groupCache.values()) {
long position = bytesWritten;
BufferedByteWriter buffer = new BufferedByteWriter();
group.write(buffer);
write(buffer.getBytes());
int nBytes = (int) (bytesWritten - position);
groupIndex.put(group.getName(), new IndexEntry(position, nBytes));
}
}
private void writeDatasets() throws IOException {
for (TDFDataset dataset : datasetCache.values()) {
long position = bytesWritten;
BufferedByteWriter buffer = new BufferedByteWriter();
dataset.write(buffer);
write(buffer.getBytes());
int nBytes = (int) (bytesWritten - position);
datasetIndex.put(dataset.getName(), new IndexEntry(position, nBytes));
}
}
private void writeIndex() throws IOException {
BufferedByteWriter buffer = new BufferedByteWriter();
// Now write out dataset index
buffer.putInt(datasetIndex.size());
for (Map.Entry<String, IndexEntry> entry : datasetIndex.entrySet()) {
buffer.putNullTerminatedString(entry.getKey());
buffer.putLong(entry.getValue().position);
buffer.putInt(entry.getValue().nBytes);
}
// group index
// log.warn("Group idx: " + groupIndex.size());
buffer.putInt(groupIndex.size());
for (Map.Entry<String, IndexEntry> entry : groupIndex.entrySet()) {
buffer.putNullTerminatedString(entry.getKey());
buffer.putLong(entry.getValue().position);
buffer.putInt(entry.getValue().nBytes);
}
byte[] bytes = buffer.getBytes();
write(bytes);
}
private byte[] bufferString(String str, int bufferSize) throws IOException {
byte[] buffer = new byte[bufferSize];
Arrays.fill(buffer, (byte) ' ');
buffer[bufferSize - 1] = 0;
if (str != null) {
int len = Math.min(bufferSize, str.length());
System.arraycopy(str.getBytes(), 0, buffer, 0, len);
}
return buffer;
}
private void writeInt(int v) throws IOException {
fos.write((v >>> 0) & 0xFF);
fos.write((v >>> 8) & 0xFF);
fos.write((v >>> 16) & 0xFF);
fos.write((v >>> 24) & 0xFF);
bytesWritten += 4;
}
private void write(byte[] bytes) throws IOException {
fos.write(bytes);
bytesWritten += bytes.length;
}
class IndexEntry {
long position;
int nBytes;
public IndexEntry(long position, int nBytes) {
this.position = position;
this.nBytes = nBytes;
}
}
}