-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmrmlToJson.js
312 lines (266 loc) · 10.4 KB
/
mrmlToJson.js
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
//external module
var fs = require('fs');
var uuid = require ('uuid');
var chalk = require('chalk');
var hashGenerator = require('sha.js');
var sha256 = hashGenerator('sha256');
var sha512 = hashGenerator('sha512');
var multihash = require('multihashes');
var canonicalJSON = require('canonical-json');
//define hash function
function getHash (obj) {
var hexValue = sha256.update(canonicalJSON(obj), 'utf8').digest('hex');
var buf = new Buffer(hexValue, 'hex');
var encoded = multihash.encode(buf, 'sha2-256');
return multihash.toB58String(encoded);
}
//defining chalk style
var errorLog = chalk.red.bold;
var successLog = chalk.green;
var warningLog = chalk.yellow;
//global vars
var extractedHierarchy,
buildHierarchy,
writeJSONFile,
JSONResult = [],
initialDate = Date.now(),
defaultLabelMap = "",
labelMapExceptions = [];
//parameters
var config = require('../configMrmlToJson.js');
var mrmlFileLocation = config.mrmlFileLocation;
var colorTableFileLocation = config.colorTableFileLocation;
var vtkFilesDirectory = config.vtkFilesDirectory;
var jsonResultFileName = config.jsonResultFileName;
//------------------------------------------------- DEFINING HEADER -------------------------------------------------//
var header = config.header;
header['@id'] = uuid.v4();
JSONResult.push(header);
//------------------------------------------------ DEFINING BASE URL ------------------------------------------------//
if (config.baseURL) {
var baseURL = {
'@id' : uuid.v4(),
'@type' : "BaseURL",
url : config.baseURL
};
JSONResult.push(baseURL);
}
//--------------------------------------- BUILD HIERARCHY FROM THE MRML FILE ----------------------------------------//
(function launchPythonScript() {
require('child_process').exec(
'python mrml-extract-hierarchy.py '+mrmlFileLocation+' '+colorTableFileLocation,
function () {
fs.readFile('extractedHierarchy.json', function (err, data) {
if (err) {
console.log(errorLog('Error while opening extracted hierarchy :'),err);
}
else {
extractedHierarchy = JSON.parse(data);
addNRRDFiles();
buildHierarchy();
}
});
}
);
})();
function addNRRDFiles () {
var backgroundImagesNames = config.backgroundImages,
labelMapNames = config.labelMapFiles,
name,
object,
i,
backgroundIds = [];
function getNRRDDatasource (source) {
var val = { "@id" : uuid.v4(), "@type" : "DataSource", "mimeType": "application/x-nrrd", "source" : source};
if (config.filesDisplayName && config.filesDisplayName[source]) {
val.displayName = config.filesDisplayName[source];
}
if (baseURL) {
val.baseURL = baseURL['@id'];
}
return val;
}
if (Array.isArray(backgroundImagesNames)) {
for (i = 0; i < backgroundImagesNames.length; i++) {
name = backgroundImagesNames[i];
object = getNRRDDatasource(name);
backgroundIds.push(object["@id"]);
JSONResult.push(object);
}
header.backgroundImage = backgroundIds;
}
else {
object = getNRRDDatasource(backgroundImagesNames);
header.backgroundImage = object["@id"];
JSONResult.push(object);
}
if (Array.isArray(labelMapNames)) {
for (i = 0; i < labelMapNames.length; i++) {
name = labelMapNames[i].name;
object = getNRRDDatasource(name);
if (Array.isArray(labelMapNames[i].includes)) {
for (var j = 0; j < labelMapNames[i].includes; j++) {
labelMapExceptions[labelMapNames[i].includes[j]] = object;
}
}
else if (labelMapNames[i].includes === '*' && !defaultLabelMap) {
defaultLabelMap = object;
}
JSONResult.push(object);
}
}
else {
//only one label map
object = getNRRDDatasource(labelMapNames);
defaultLabelMap = object;
JSONResult.push(object);
}
}
function getLabelFromModelName (modelName) {
var reg = /Model_(\d+)/;
var result = modelName.match(reg);
return result && Number(result[1]);
}
function buildHierarchy () {
if (extractedHierarchy) {
for (var label in extractedHierarchy.nodes) {
if (label in extractedHierarchy.Hierarchies.__default__) {
//then its a group
var group = {
"@id" : uuid.v4(),
"@type" : "Group",
"annotation" : {
name : extractedHierarchy.nodes[label].name
},
member : extractedHierarchy.Hierarchies.__default__[label].children //store the reference of the hierarchy node to retrieve uuid once every group is created
};
if (extractedHierarchy.Hierarchies.__default__.__root__.children.indexOf(label) > -1) {
//group is at the root so we add it to the list of root groups in the header
header.root.push(group['@id']);
}
extractedHierarchy.nodes[label].uuid = group['@id'];
JSONResult.push(group);
}
else {
//it has to be a structure
var dataSource = {
"@id" : uuid.v4(),
"@type" : "DataSource",
"mimeType": "application/octet-stream",
"source": vtkFilesDirectory+extractedHierarchy.nodes[label].modelFile
};
if (baseURL) {
dataSource.baseURL = baseURL['@id'];
}
var dataKey = getLabelFromModelName(extractedHierarchy.nodes[label].modelFile);
var labelMapDatasource = labelMapExceptions[dataKey] || defaultLabelMap;
var labelMapSelector = {
"@type" : ["Selector", "LabelMapSelector"],
dataKey : dataKey,
dataSource : labelMapDatasource['@id'],
authoritative : true
};
var structure = {
"@id" : uuid.v4(),
"@type" : "Structure",
"annotation" : {
name : extractedHierarchy.nodes[label].name
},
"sourceSelector" : [{
"@type" : ["Selector", "GeometrySelector"],
dataSource : dataSource['@id']
}, labelMapSelector],
"renderOption" : {
color : extractedHierarchy.nodes[label].color
}
};
extractedHierarchy.nodes[label].uuid = structure['@id'];
JSONResult.push(dataSource);
JSONResult.push(structure);
}
}
//at this point, every object is created, we just need to retrieve uuid of the members of the groups
var _getNodeUuid = memberLabel => extractedHierarchy.nodes[memberLabel].uuid;
for (var i = 0; i<JSONResult.length; i++) {
var item = JSONResult[i];
if (item['@type']==='Group') {
item.member = item.member.map(_getNodeUuid);
}
}
buildHierarchy.done = true;
writeJSONFile();
}
}
//---------------------------------------------- GENERATE HASH VERSION ----------------------------------------------//
function generateHashVersion () {
var JSONHash = JSON.parse(JSON.stringify(JSONResult));
var uuids = {};
var hashed = {};
var i;
for (i = 0; i < JSONHash.length; i++) {
uuids[JSONHash[i]['@id']] = JSONHash[i];
}
function hashify (obj, returnString) {
if (hashed[obj['@id']]) {
return obj['@id'];
}
for (var key in obj) {
if (typeof obj[key] === 'string' && uuids[obj[key]] && key !== '@id') {
obj[key] = hashify(uuids[obj[key]], true);
}
else if (Array.isArray(obj[key])) {
for (var i = 0; i < obj[key].length; i++) {
if (typeof obj[key][i] === 'string' && uuids[obj[key][i]]) {
obj[key][i] = hashify(uuids[obj[key][i]], true);
}
else if (typeof obj[key][i] === 'object') {
obj[key][i] = hashify(obj[key][i], false);
}
}
}
else if (typeof obj[key] === 'object') {
obj[key] = hashify(obj[key], false);
}
}
if (returnString) {
delete obj["@id"];
var hash = getHash(obj);
obj["@id"] = hash;
hashed[hash] = true;
return hash;
}
return obj;
}
JSONHash[0]['@id'] = hashify(JSONHash[0], true);
return JSONHash;
}
//------------------------------------------------ WRITING JSON FILE ------------------------------------------------//
function writeJSONFile () {
if (buildHierarchy.done) {
fs.writeFile(jsonResultFileName, JSON.stringify(JSONResult, null, 4), function(err) {
if(err) {
return console.log(errorLog('Error while writing atlas structure : '), err);
}
console.log(successLog("The JSON file was saved!"));
console.log('done in '+(Date.now()-initialDate)+'ms');
});
var JSONLD = {
"@context" : config['@context'],
"@graph" : JSONResult
};
fs.writeFile(config.jsonLDResultFileName, JSON.stringify(JSONLD, null, 4), function(err) {
if(err) {
return console.log(errorLog('Error while writing atlas structure LD : '), err);
}
console.log(successLog("The JSON LD file was saved!"));
console.log('done in '+(Date.now()-initialDate)+'ms');
});
fs.writeFile(config.jsonHashResultFileName, JSON.stringify(generateHashVersion(), null, 4), function(err) {
if(err) {
return console.log(errorLog('Error while writing atlas structure hash version : '), err);
}
console.log(successLog("The JSON hash file was saved!"));
console.log('done in '+(Date.now()-initialDate)+'ms');
});
}
}