-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpinn2Json.py
696 lines (563 loc) · 26.6 KB
/
pinn2Json.py
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
#!/usr/bin/env python
# coding = utf-8
import json
import re
import sys
import os
from optparse import OptionParser
import numpy as np
from box import Box
# ----------------------------------------- #
"""
Use JSON structured text file readers to parse pinnacle file into a muliple
layered dictionary.
A pinnacle file is similar in structure to a json file although not identical. Script parses thepinnacle file and resolves the syntax differences to make a
valid json specification conforming
string which contains all the data present in the original file.
Issue with new line inside comments field in Patient file.
Issue with plan.defaults file Line :
image_file : ../ImageSet_1
"""
# ----------------------------------------- #
class pinn2Json(object):
def __init__(self):
return
def read(self, pinnFile):
"""
Read the pinnacle file and return as a dictionary or array of dictionaries.
"""
with open(pinnFile, 'r', encoding='ISO-8859-1') as f:
fileTxt = f.read()
fileTxt = self.pinnProcess(fileTxt)
if fileTxt:
fileTxt = self.pinn2Json(fileTxt)
f.close()
# f = open(pinnFile + '.json', 'w')
# f.write(fileTxt)
# f.close()
return Box(json.loads(fileTxt, strict=False))
# return DotMap(json.loads(fileTxt))
else:
print("emptyfile\n")
return None
# return pinnObjDict.pinnObjDict(json.loads(fileTxt),pinnFile)
# ----------------------------------------- #
def reads(self, fileTxt):
"""
Translate the pinnacle file text to a python dictionary object.
"""
fileTxt = self.pinn2Json(fileTxt)
# data = Box(json.loads(fileTxt))
# return data
return Box(json.loads(fileTxt))
# return pinnObjDict.pinnObjDict(json.loads(fileTxt),pinnFile)
# ----------------------------------------- #
def readJson(self, pinnFile):
"""
Read the pinnacle data from a file in JSON format
"""
f = open(pinnFile)
fileTxt = f.read()
f.close()
return Box(json.loads(fileTxt))
# return pinnObjDict.pinnObjDict(json.loads(fileTxt))
# ----------------------------------------- #
def writeJson(self, pinnFile, jsonFile):
"""
Write the pinnacle file to a new file in JSON format
"""
f = open(pinnFile)
fileTxt = self.pinn2Json(f.read())
f.close()
f2 = open(jsonFile, 'w')
f2.write(fileTxt)
f2.close()
# ----------------------------------------- #
def pinnProcess(self, pinnFileText):
"""
before convert, process the raw pinnacle format text
"""
# Remove single line comments
pinnFileText = re.sub('^//.*?\n', '', pinnFileText, re.MULTILINE)
pinnFileText = re.sub('//.*?\n', '\n', pinnFileText)
# Remove block comments
pinnFileText = re.sub(
r'\/\*[^*]*\*+([^/][^*]*\*+)*\/', '', pinnFileText, re.DOTALL)
pinnFileText = re.sub(r'\n\n', '', pinnFileText)
# remove roi_name like : name : 6000 (Trial_1)
pinnFileText = re.sub("\((.*)\)", '', pinnFileText)
# pinnFileText = re.sub("name:\s(\d+)\s\((.*)\)",
# 'name:ring', pinnFileText)
return pinnFileText
def pinn2Json(self, pinnFileText):
"""
Convert pinnacle format text to JSON format text
"""
# Add an enclosing parenthesis for the file
sectionStart, sectionEnd, sectionDepth = self.findSectionBrakes(
pinnFileText)
# if len(sectionStart) == 0 and len(sectionEnd) == 0 and len(sectionDepth) == 0:
# return None
pinnFileText = self.dotHeirarchyToPinnFormat(pinnFileText)
# print(pinnFileText[:150])
# For opening objects add an opening list to contain them:
# E.g. files start with Trial{ ... } followed by another Trial{ ... }
# should start with TrialList{ Trial{...} Trial{...} }
sectionStart, sectionEnd, sectionDepth = self.findSectionBrakes(
pinnFileText)
# Files that contain primary sections need an incasing list for consistancy with the rest of the file.
# E.g. this: becomes:
# roi ={ roiList ={
# ... roi ={
# }; ...
# roi ={ };
# ... roi ={
# }; ...
# };
# };
numPrimaries = 0
sectionName = []
primaryStart = []
primaryEnd = []
for sDepth, sStart, sEnd in zip(sectionDepth, sectionStart, sectionEnd):
if sDepth == 0:
numPrimaries += 1
# sName = re.search('(?<=\n).*(?=\=$)', pinnFileText[:sStart]).group()
sName = re.search(
'^.*(?=\=$)', pinnFileText[:sStart], re.MULTILINE).group()
sectionName.append(sName)
primaryStart.append(sStart)
primaryEnd.append(sEnd)
if numPrimaries > 0:
# Find first repeated primary section
for sName in set(sectionName):
if sectionName.count(sName) > 1:
pStart = primaryStart[sectionName.index(sName)]
pEnd = primaryEnd[len(sectionName) -
sectionName[::-1].index(sName) - 1]
pinnFileText = pinnFileText[:pStart - len(sName) - 1] + sName.strip() + \
"List ={\n" + sName + "=" + pinnFileText[pStart:pEnd] + "\n};\n" + \
pinnFileText[pEnd:]
break
# match1 = re.search("\w*(?= {0,1}={)",pinnFileText)
# objName = pinnFileText[match1.start():match1.end()]
# pinnFileText = pinnFileText[:match1.start()] + objName + "List ={\n" + pinnFileText[match1.start():] + "\n};\n"
# f1 = open('debug01','w')
# f1.write(pinnFileText)
# f1.close()
sectionStart2, sectionEnd2, sectionDepth2 = self.findSectionBrakes(
pinnFileText)
# add by peteryang
# pinnFileText = re.sub(r'#(\d?)\s*(=\{)',r'Number\1 \2',pinnFileText)
# pinnFileText = re.sub('^#0\s*={','Number0 ={',pinnFileText)
# pinnFileText = re.sub('\n#1\s*={','Number1 ={',pinnFileText)
pinnFileText = re.sub('\+*', '', pinnFileText)
# Remove single line comments
pinnFileText = re.sub('^//.*?\n', '', pinnFileText, re.MULTILINE)
pinnFileText = re.sub('//.*?\n', '\n', pinnFileText)
# Remove block comments
pinnFileText = re.sub(
r'\/\*[^*]*\*+([^/][^*]*\*+)*\/', '', pinnFileText, re.DOTALL)
# Protect = sign when inside string quotation by changing to @$, will be changed back later
pinnFileText = re.sub(
r'("[\w \t;,\-\+\.]*)(=)([\w \t;,\-\+\.]*")', r'\1@$\3', pinnFileText)
# f1 = open('debug02','w')
# f1.write(pinnFileText)
# f1.close()
# In some pinnacle files : is used for string equality instead of = "" change for consistency
pinnFileText = re.sub(
r'\n([ \t\w\^\._-]*) *: *([ \t\w\^\.:/_-]*)', r'\n\1 = "\2";', pinnFileText)
# At end of line change ; to , and at start of line add a " to start of key
pinnFileText = re.sub(';\n*\s*(?=[\w#])', ',\n"', pinnFileText)
# f1 = open('debug03','w')
# f1.write(pinnFileText)
# f1.close()
# For lines ending in { make sure following line has a "
pinnFileText = re.sub('{\n\s*(?=[A-Za-z#])', '{\n"', pinnFileText)
# f1 = open('debug04','w')
# f1.write(pinnFileText)
# f1.close()
# If there is a key on the first line then it also needs a "
pinnFileText = re.sub('\A\s*(?=[A-Za-z#])', '"', pinnFileText)
# f1 = open('debug05','w')
# f1.write(pinnFileText)
# f1.close()
# And last line needs the semicolon removed
pinnFileText = re.sub(';\s*\Z', '', pinnFileText)
# Remove semicolon for lines followed by a closing paren
pinnFileText = re.sub(';\n*\s*}', '\n}', pinnFileText)
# Add " to end of key and change key, value separator from = to :
pinnFileText = re.sub('\s*=\s*', '" : ', pinnFileText)
# f1 = open('debug06','w')
# f1.write(pinnFileText)
# f1.close()
# Return the = inside quotation marks
pinnFileText = re.sub('@$', '=', pinnFileText)
# Add an enclosing parenthesis for the file
pinnFileText = "{\n" + pinnFileText + "\n}\n"
# f1 = open('debug07','w')
# f1.write(pinnFileText)
# f1.close()
# modifiying ROI-curveList 2019-04-12
pinnFileText = re.sub('\n\"num_curve\"(.*)\n',
'\n\"num_curve\" : [\n', pinnFileText)
pinnFileText = re.sub('\n\"surface_mesh\"',
'\n],\n\"surface_mesh\"', pinnFileText)
pinnFileText = re.sub('\n\"curve\"\s:\s\{\n', "\n{", pinnFileText)
# Convert plan.roi points into plan.Trial Points[], vertices,triangles,
# pinnFileText = re.sub(
# r'\n\s*"curve" ?: ?{\n', r'\n"curve[]" :{\n', pinnFileText)
pinnFileText = re.sub(
r'\n\s*"points" ?: ?{\n', r'\n"Points[]" :{\n', pinnFileText)
pinnFileText = re.sub(
r'\n\s*"vertices" ?: ?{\n', r'\n"Vertices[]" :{\n', pinnFileText)
pinnFileText = re.sub(
r'\n\s*"triangles" ?: ?{\n', r'\n"Triangles[]" :{\n', pinnFileText)
# Convert N N N lines into [ N, N, N ], lines, where N is a number that might be negative and might have a decimal point.
pinnFileText = re.sub(
r'\n\s*(\-?[0-9]+\.?[0-9]*)\s(\-?[0-9]+\.?[0-9]*)\s(\-?[0-9]+\.?[0-9]*)\s*(?=\n)', r'\n[ \1, \2, \3 ],',
pinnFileText)
# in plan.pinnacle.Machines N,N, -> [N,N]
pinnFileText = re.sub(
r'\n\s*(\-?[0-9]+\.?[0-9]*),(\-?[0-9]+\.?[0-9]*),\s*(?=\n)', r'\n[ \1, \2 ],', pinnFileText)
pinnFileText = re.sub(
r'\n\s*(\-?[0-9]+\.?[0-9]*),(\-?[0-9]+\.?[0-9]*)\s*(?=\n)', r'\n[ \1, \2 ],', pinnFileText)
# [e-01 e-01 e-01]
pinnFileText = re.sub(
r'\n\s*(\-?[0-9]+\.?[0-9]*e-[0-9]*)\s(\-?[0-9]+\.?[0-9]*e-[0-9]*)\s(\-?[0-9]+\.?[0-9]*e-[0-9]*)\s*(?=\n)',
r'\n[ \1, \2, \3 ],', pinnFileText)
# [e-01 y z]
pinnFileText = re.sub(
r'\n\s*(\-?[0-9]+\.?[0-9]*e-[0-9]*)\s(\-?[0-9]+\.?[0-9]*)\s(\-?[0-9]+\.?[0-9]*)\s*(?=\n)',
r'\n[ \1, \2, \3 ],', pinnFileText)
# [x e-01 z]
pinnFileText = re.sub(
r'\n\s*(\-?[0-9]+\.?[0-9]*)\s(\-?[0-9]+\.?[0-9]*e-[0-9]*)\s(\-?[0-9]+\.?[0-9]*)\s*(?=\n)',
r'\n[ \1, \2, \3 ],', pinnFileText)
# [x y e-01]
pinnFileText = re.sub(
r'\n\s*(\-?[0-9]+\.?[0-9]*)\s(\-?[0-9]+\.?[0-9]*)\s(\-?[0-9]+\.?[0-9]*e-[0-9]*)\s*(?=\n)',
r'\n[ \1, \2, \3 ],', pinnFileText)
# f1 = open('debug08','w')
# f1.write(pinnFileText)
# f1.close()
# Convert Points[] : { N,N } arrays to Points : [ N,N ] (match anything except '}')
# pinnFileText = re.sub(
# r'"curve\[\]" ?: ?{\n([^}]*)}', r'"curve" : [\n\1]', pinnFileText)
pinnFileText = re.sub(
r'"Points\[\]" ?: ?{\n([^}]*)}', r'"Points" : [\n\1]', pinnFileText)
pinnFileText = re.sub(
r'"Vertices\[\]" ?: ?{\n([^}]*)}', r'"Vertices" : [\n\1]', pinnFileText)
pinnFileText = re.sub(
r'"Triangles\[\]" ?: ?{\n([^}]*)}', r'"Triangles" : [\n\1]', pinnFileText)
# pinnFileText = re.sub( r'"PhotonEnergyList" ?: ?{\n(^}*)}', r'"PhotonEnergyList" : [\n\1]', pinnFileText)
# pinnFileText = re.sub( r'"ElectronEnergyList" ?: ?{\n(^}*)}', r'"ElectronEnergyList" : [\n\1]', pinnFileText)
# pinnFileText = re.sub( r'"PhotonEnergyList" ?: ?{\n([^}]*)}', r'"PhotonEnergyList" : [{\n\1}]', pinnFileText)
# Convert Points[] : { N,N } arrays to Points : [ N,N ] (match anything except '}')
# pinnFileText = re.sub( r'"Points\[\]" ?: ?{\n([^}]*)}', r'"Points" : [\n\1]', pinnFileText)
# f1 = open('debug09','w')
# f1.write(pinnFileText)
# f1.close()
# Remove " from start of lines in a numeric array
pinnFileText = re.sub(
r'\[\n"([0-9]*\.?[0-9]*,[0-9]*.?[0-9]*,)\n', r'[\n\1\n', pinnFileText)
# remove e-06
# pinnFileText = re.sub(r'e-\d*',r'e',pinnFileText)
# f1 = open('debug10','w')
# f1.write(pinnFileText)
# f1.close()
# Convert = \XDR:0\; to = "XDR:0";
pinnFileText = re.sub(
r': \\XDR:([0-9]*)\\', r': "XDR-\1"', pinnFileText)
# For store objects change syntax slightly : e.g. Float { to : {
pinnFileText = re.sub(' : Float {', ' : {', pinnFileText)
pinnFileText = re.sub(' : SimpleString {', ' : {', pinnFileText)
# f1 = open('debug11','w')
# f1.write(pinnFileText)
# f1.close()
# ----------------------------------------------------------------------------------- #
# Convert ObjectLists from ObjectList = { Object={A}, Object={B} } to ObjectList = [ A, B ]
# Find matching pairs of brackets
sectionStart, sectionEnd, sectionDepth = self.findSectionBrakes(
pinnFileText)
listStarts = []
for listP in re.finditer('List" : {', pinnFileText):
listStarts.append(listP.start())
listStarts = np.array(listStarts)
# Compile a list of pinnacle List arrays such as BeamList, etc.
for ll, listSt in enumerate(listStarts):
# print("List %d at line %d, char %d" % (ll, lineNumber(pinnFileText,listSt), listSt))
# Find the beginning and end of the list section
bracketNum = np.where(sectionStart > listSt)[0][0]
listEnd = sectionEnd[bracketNum]
# Get the name of the pinnacle list type (the part that comes before List)
# E.g. BeamList becomes Beam, TrialList becomes Trial
listMatch = re.search('(?<=\n")[\s\w]*?$', pinnFileText[:listSt])
# print(repr(pinnFileText[listSt-30:listSt]))
if listMatch:
listName = pinnFileText[listMatch.start():listSt]
matchStr = '"' + listName + '" : {'
# Cut out the list portion from the file text
extract = pinnFileText[listSt:listEnd]
# If there are no items in the list then skip it and leave it as it is.
if len(re.findall(matchStr, extract)) == 0 and len(re.findall('"#[0-9]*" : {', extract)) == 0:
continue
nCharsRemoved = len(matchStr) - 1
for mm, matchM in enumerate(re.finditer(matchStr, extract)):
matchPos = matchM.start() + listSt
if mm == 0:
firstMatch = matchPos
listInds = np.where(listStarts > matchPos)[0]
sectionStart[np.where(sectionStart > matchPos)[
0]] -= nCharsRemoved
sectionEnd[np.where(sectionEnd > matchPos)[0]] -= nCharsRemoved
listStarts[listInds] -= nCharsRemoved
extract = re.sub(matchStr, '{', extract)
# Set text to previous portion + extract + subsequent portion
pinnFileText = pinnFileText[:listSt] + 'List" : [' + \
extract[9:-1] + "]," + pinnFileText[listEnd + 1:]
# f1 = open('debug12','w')
# f1.write(pinnFileText)
# f1.close()
# ObjectLists that have elements named #0, #1 etc. must be changed
pinnFileText = re.sub('"#[0-9]*" : {', '{', pinnFileText)
# f1 = open('debug13','w')
# f1.write(pinnFileText)
# f1.close()
# Clean up a bit by removing any commas added where we shouldn't have commas
# Match } or ] following by , some whitespace and then } or ]
# Replace by the first bracket newline second bracket.
# pinnFileText = re.sub(r'([}\]]),\s*([[}\]])', r'\1\n\2', pinnFileText )
pinnFileText = re.sub(r'([}\]]),\s*([}\]])', r'\1\n\2', pinnFileText)
# f1 = open('debug14','w')
# f1.write(pinnFileText)
# f1.close()
return pinnFileText
# ----------------------------------------- #
def dotHeirarchyToPinnFormat(self, fileTxt):
"""
Convert dot object heirarchy to bracket heirarchy
E.g. Convert this syntax:
DoseGrid .VoxelSize .X = 0.4;
DoseGrid .VoxelSize .Y = 0.4;
DoseGrid .Dimension .X = 125;
DoseGrid .Dimension .Y = 112;
to this syntax, which is more consistent with the rest of pinnacle file format
DoseGrid ={
VoxelSize = {
X = 0.4;
Y = 0.4;
};
Dimension = {
X = 125;
Y = 112;
};
};
Assume that sub-objects in dot heirarchy are on subsequent lines.
"""
prevEnd = 0
prevSection = ""
charDelta = 0
nBrktsOpen = 0
nBrktsClose = 0
# Regular expression explained :
# match Something.SomethingElse = SomethingElse;\n
# where Something can have upper or lowercase letters or numbers, spaces, tabs, hyphens or double quotes
# SomethingElse can additionally have dots '.'
# must be preeceded by newline - i.e. rule out comments that start with // or rhs of equals
# Group match into three parts so the Something, SomethingElse and SomethingElse can all
# be used in constructing the replacement string
for m1 in re.finditer(r'(?<=\n)(["A-Za-z0-9 \t_-]*)\.(["A-Za-z0-9 \t_\.-]*)=(["0-9A-Za-z \t_\.-]*;\n)',
fileTxt):
grps = m1.groups()
if m1.lastindex == 3:
if m1.start() > prevEnd or prevSection != grps[0]:
if prevEnd > 0:
txtAdded = "\n};\n"
fileTxt = fileTxt[:prevEnd + charDelta] + \
txtAdded + fileTxt[prevEnd + charDelta:]
charDelta += len(txtAdded)
prevEnd = m1.end()
nBrktsClose += 1
txtAdded = grps[0] + "={\n " + grps[1] + "=" + grps[2]
# ch1 = m1.start()+charDelta
# ch2 = m1.end()+charDelta
# print( str(m1.start()) + "-" + str(m1.end()) + ":" + str(prevEnd) + "***" + \
# repr(fileTxt[ch1-50:ch1]) + "***" + repr(fileTxt[ch1:ch2]) + \
# "***" + repr(txtAdded) + "***" + repr(fileTxt[ch2:ch2+50]) )
fileTxt = fileTxt[:m1.start() + charDelta] + \
txtAdded + fileTxt[m1.end() + charDelta:]
charDelta += len(txtAdded) + m1.start() - m1.end()
prevEnd = m1.end()
prevSection = grps[0]
nBrktsOpen += 1
else:
txtAdded = " " + grps[1] + "=" + grps[2]
# ch1 = m1.start()+charDelta
# ch2 = m1.end()+charDelta
# print( str(m1.start()) + "-" + str(m1.end()) + ":" + str(prevEnd) + "***" + \
# repr(fileTxt[ch1-50:ch1]) + "***" + repr(fileTxt[ch1:ch2]) + \
# "***" + repr(txtAdded) + "***" + repr(fileTxt[ch2:ch2+50]) )
fileTxt = fileTxt[:m1.start() + charDelta] + \
txtAdded + fileTxt[m1.end() + charDelta:]
charDelta += len(txtAdded) + m1.start() - m1.end()
prevEnd = m1.end()
else:
print("We should have 3 matches here but we don't ")
if nBrktsOpen > 0:
txtAdded = "};\n"
fileTxt = fileTxt[:prevEnd + charDelta] + \
txtAdded + fileTxt[prevEnd + charDelta:]
# charDelta += len(txtAdded)
# nBrktsClose += 1
fileTxt = self.dotHeirarchyToPinnFormat(fileTxt)
# print("Sections opened = %d, closed = %d" % (nBrktsOpen,nBrktsClose))
return fileTxt
# ----------------------------------------- #
def findSectionBrakes(self, fileTxt):
"""
Find matching pairs of curley brackets {} and return their position in the string.
"""
opBrkt = []
for result in re.finditer("{", fileTxt):
opBrkt.append(result)
clBrkt = []
for result in re.finditer("}", fileTxt):
clBrkt.append(result)
# depthBrkt = []
# if len(opBrkt) == 0 or len(clBrkt) == 0:
# print("maybe a empty file\n")
# return np.array([]),np.array([]),np.array([])
nBrackets = len(opBrkt)
if len(clBrkt) != nBrackets:
raise Exception("Brackets {} are not balanced in file %d opening and %d closing." % (
len(opBrkt), len(clBrkt)))
# print("Brackets {} %d opening and %d closing." % (len(opBrkt), len(clBrkt)))
sectionStart = []
sectionEnd = []
sectionDepth = []
sectionInd = 0
while len(opBrkt) > 0:
self.findMatchingBrackets(opBrkt, clBrkt, sectionStart,
sectionEnd, sectionDepth, 0)
return np.array(sectionStart), np.array(sectionEnd), np.array(sectionDepth)
# ----------------------------------------- #
def findMatchingBrackets(self, opBrkt, clBrkt, sectionStart, sectionEnd, sectionDepth, curDepth):
"""
Recursive function to find sections delimited by matching pairs of braces.
"""
curOpBrkt = opBrkt.pop(0)
sectionInd = len(sectionStart)
sectionStart.append(curOpBrkt.start())
sectionEnd.append(-1)
sectionDepth.append(-1)
while len(opBrkt) > 0 and clBrkt[0].start() > opBrkt[0].start():
self.findMatchingBrackets(opBrkt, clBrkt, sectionStart,
sectionEnd, sectionDepth, curDepth + 1)
curClBrkt = clBrkt.pop(0)
sectionEnd[sectionInd] = curClBrkt.end()
sectionDepth[sectionInd] = curDepth
# ----------------------------------------- #
def lineNumber(self, text, charNum):
"""
Convert a given character index in a string to a line number by counting the preceeding newlines
"""
ln = 0
for mm in re.finditer("\n", text[:charNum]):
ln += 1
return ln
# ----------------------------------------- #
def test(self):
"""
Run tests.
"""
# Test dotHeirarchyToPinnFormat()
testStr = "PatientRepresentation ={\n" + \
" PatientVolumeName = \"plan\";\n" + \
" CtToDensityName = \"RMH GE 120kV\";\n" + \
" CtToDensityVersion = \"2012-08-14 10:56:29\";\n" + \
" DMTableName = \"Standard Patient\";\n" + \
" DMTableVersion = \"2003-07-17 12:00:00\";\n" + \
" TopZPadding = 0;\n" + \
" BottomZPadding = 0;\n" + \
" HighResZSpacingForVariable = 0.2;\n" + \
" OutsidePatientIsCtNumber = 0;\n" + \
" OutsidePatientAirThreshold = 0.6;\n" + \
" CtToDensityTableAccepted = 1;\n" + \
" CtToDensityTableExtended = 0;\n" + \
"};\n" + \
"DoseGrid .VoxelSize .X = 0.4;\n" + \
"DoseGrid .VoxelSize .Y = 0.4;\n" + \
"DoseGrid .VoxelSize .Z = 0.4;\n" + \
"DoseGrid .Dimension .X = 125;\n" + \
"DoseGrid .Dimension .Y = 112;\n" + \
"DoseGrid .Dimension .Z = 90;\n" + \
"DoseGrid .Origin .X = -24.5082;\n" + \
"DoseGrid .Origin .Y = -19.3726;\n" + \
"DoseGrid .Origin .Z = -18.886;\n" + \
"DoseGrid .DisplayAsSecondary = 0;\n" + \
"DoseGrid .Display2d = 1;\n" + \
"PatientRepresentation ={\n" + \
" PatientVolumeName = \"plan\";\n" + \
" CtToDensityName = \"RMH GE 120kV\";\n" + \
" CtToDensityVersion = \"2012-08-14 10:56:29\";\n" + \
"};\n" + \
"RowLabelList ={\n" + \
" #0 ={\n" + \
" String = \" 1. Y = -19.50 cm\";\n" + \
" };\n" + \
" #1 ={\n" + \
" String = \" 2. Y = -18.50 cm\";\n" + \
" };\n" + \
"};\n" + \
"\n"
# outStr = dotHeirarchyToPinnFormat(testStr)
# print(outStr)
# testFile = '/home/dualta/code/python/Patient_27814/Plan_0/plan.Trial'
# testFile = '/home/dualta/code/python/Patient_27814/Plan_0/plan.roi'
# writeJson(testFile, testFile+'.json')
import os
testPath = '/home/dualta/code/python/Patient_27814/Plan_0/'
for testFile in os.listdir(testPath):
if 'json' in testFile or 'binary' in testFile:
continue
msg = "Trying " + testFile + " : "
try:
self.writeJson(testPath + testFile,
testPath + testFile + '.json')
print(msg + "ok")
except:
print(msg + "PROBLEM")
# ----------------------------------------- #
if __name__ == "__main__":
"""
Main function
"""
# Set up input argument parser
parser = OptionParser("\nProcess a pinnacle object." +
"\n\n%s [options] pinnacle_file" % sys.argv[0])
parser.add_option("-t", "--test", dest="runTest",
action="store_true", default=False,
help="Run test by converting a sample plan.Trial file to JSON file.")
# parser.add_option("-n","--name",dest="annonName",
# type="string", action="store", default="NO^NAME", \
# help="Annonomize images by changing name to annonName.")
workingPath = os.path.join(os.getenv('HOME'), 'PinnWork')
filename = os.path.join(workingPath, 'Mount_0/Patient_28471/ImageSet_0.ImageInfo')
# filename = os.path.join(workingPath, 'test.roi')
pinnObjList = pinn2Json().read(filename)
for scriptObj in pinnObjList:
print(scriptObj)
# (options, args) = parser.parse_args()
#
# if options.runTest:
# test()
# elif len(args) < 1:
# print("No pinnacle file found !!")
# parser.print_help()
# else:
# filename = args[0]
# pinnObjList = read(filename)
#
# for scriptObj in pinnObjList:
# print(scriptObj)