forked from rickardcronholm/SAMC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsamcUtil.py
1567 lines (1358 loc) · 55.5 KB
/
samcUtil.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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# this is a file containing utility scripts for the Skane Automatic Monte Carlo
# Rickard Cronholm, 2013
import re
import math
import os
import random
import dicom
import numpy as np
# config file path goes here
confFile = 'samc.conf'
class struct:
def __init__(self):
pass
def rreplace(s, old, new, occurence):
li = s.rsplit(old, occurence)
return new.join(li)
def typeCast(cv, variables, types):
for i in range(0, len(variables)):
try:
setattr(cv, variables[i], map(types[i], getattr(cv, variables[i])))
except TypeError:
if types[i] == int:
setattr(cv, variables[i], int(getattr(cv, variables[i])))
except ValueError:
pass
return cv
def getPartOfstringFromList(lst, lookFor, delimiter, splitIndx=False, returnType=False):
value = lst[[i for i, s in enumerate(lst) if lookFor in s][0]]
if splitIndx:
value = value.split(delimiter)[splitIndx].strip()
else:
value = value.strip()
if not returnType:
return value
else:
return np.asarray(value).astype(returnType).tolist()
def validateRP(RTP):
(beams, corrBeams) = getBeams(RTP)
# get treatmentMachine hereby assuming that all beams are planned on
# the same linac
treatmentMachine = RTP.BeamSequence[corrBeams[0]].TreatmentMachineName
# get nominal energy and fluence mode
nomEnfluMod = getEnFlu(RTP, corrBeams)
print ' '.join([treatmentMachine, nomEnfluMod[0]])
valid = True
# make sure that there exists a config file for the treatmentMachine
try:
with open(treatmentMachine, 'r') as f:
content = f.readlines()
except IOError:
return False # no config file for treatmentMachine
# only consider unique nomEnfluMods
nomEnfluMod = list(set(nomEnfluMod))
for i in range(0, len(nomEnfluMod)):
# synthesize string
lookFor = ' '.join(['absCalib', nomEnfluMod[i]])
# make sure that absCalib exists for the current nomEnfluMod
if len([i for i, s in enumerate(content) if lookFor in s]) == 0:
return False
return valid
def getConfVars(cv, wtg, content):
for item in wtg: # loop over what to get
for elem in content: # loop over content
if elem.startswith(item): # if found
name = elem.split()[0].split('.')[-1]
val = elem.split()[1]
try:
val = float(val)
except ValueError:
pass
setattr(cv, name, val) # add to confvariables
return cv
def flatten(seq, container=None):
if container is None:
container = []
for s in seq:
if hasattr(s, '__iter__'):
flatten(s, container)
else:
container.append(s)
return container
def writeTimeToFile(fileName, newTime):
f = open(fileName, 'w')
f.write('{0}\n'.format(newTime))
f.close()
def getVariable(confFile, varName):
with open(confFile, 'r') as f:
content = f.readlines()
try:
return content[[i for i, s in enumerate(content)
if s.startswith(varName)][0]].split(' ')[1].rstrip()
except IndexError:
print varName, ' not found in configuration file\n'
return ''
def getID(RTP,timeStamp):
try:
ID = RTP.PatientID
except AttributeError:
ID = int(timeStamp)
return ID
def getName(RTP):
try:
name = RTP.PatientName
except AttributeError:
name = 'N^N'
return " ".join(name.split('^'))
def getBeams(RTP):
numBeams = len(RTP.BeamSequence)
beams = []
corrBeams = []
for i in range(0, numBeams):
if RTP.BeamSequence[i].TreatmentDeliveryType == 'TREATMENT':
beams.append(int(RTP.BeamSequence[i].BeamNumber))
corrBeams.append(i)
return (beams, corrBeams)
def getBeamNames(RTP, corrBeams):
beamNames = []
for i in range(0, len(corrBeams)):
beamNames.append(RTP.BeamSequence[corrBeams[i]].BeamName)
return beamNames
def getMU(RTP, beams):
MUs = []
for i in range(0, len(beams)):
count = 0
while int(RTP.FractionGroupSequence[0].ReferencedBeamSequence[count].ReferencedBeamNumber) != beams[i]:
count += 1
MUs.append(float(RTP.FractionGroupSequence[0].ReferencedBeamSequence[count].BeamMeterset))
return MUs
def getEnFlu(RTP, beams):
nomEnfluMod = []
for i in range(0, len(beams)):
nomE = ''.join([(RTP.BeamSequence[beams[i]].ControlPointSequence[0].NominalBeamEnergy).original_string, 'X'])
fluMod = (RTP.BeamSequence[beams[i]].PrimaryFluenceModeSequence[0].FluenceMode)
nomEnfluMod.append('_'.join([nomE, fluMod]).rstrip())
return nomEnfluMod
def getAngles(RTP,beams):
gantry = []
couch = []
coll = []
for i in range(0,len(beams)):
thisGantry = []
thisCouch = []
thisColl = []
numCtrlPts = int(RTP.BeamSequence[beams[i]].NumberOfControlPoints)
for j in range(0, numCtrlPts):
if j == 0: # then this information is certain to exist
thisGantry.append(float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].GantryAngle))
thisCouch.append(float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].PatientSupportAngle))
thisColl.append(float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].BeamLimitingDeviceAngle))
lastGantry = float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].GantryAngle)
lastCouch = float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].PatientSupportAngle)
lastColl = float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].BeamLimitingDeviceAngle)
else:
try:
thisGantry.append(float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].GantryAngle))
lastGantry = float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].GantryAngle)
except AttributeError:
thisGantry.append(lastGantry)
try:
thisCouch.append(float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].PatientSupportAngle))
lastCouch = float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].PatientSupportAngle)
except AttributeError:
thisCouch.append(lastCouch)
try:
thisColl.append(float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].BeamLimitingDeviceAngle))
lastColl = float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].BeamLimitingDeviceAngle)
except AttributeError:
thisColl.append(lastColl)
gantry.append(thisGantry)
couch.append(thisCouch)
coll.append(thisColl)
return (gantry, couch, coll)
def getMUindx(RTP,beams,MUs):
MUindx = []
for i in range(0, len(beams)):
thisMUindx = []
numCtrlPts = int(RTP.BeamSequence[beams[i]].NumberOfControlPoints)
for j in range(0, numCtrlPts):
if j == 0: # then this information is certain to exist
thisMUindx.append(float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].CumulativeMetersetWeight))
lastMUindx = float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].CumulativeMetersetWeight)
else:
try:
thisMUindx.append(float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].CumulativeMetersetWeight))
lastMUindx = float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].CumulativeMetersetWeight)
except AttributeError:
thisMUindx.append(lastMUindx)
MUindx.append(thisMUindx)
return MUindx
def getMUindxScaled(RTP, beams, MUs):
MUindx = []
for i in range(0, len(beams)):
scale = MUs[i] / math.fsum(MUs)
addThis = 0
if i != 0:
for j in range(0, i):
addThis += MUs[j]
addThis = addThis / math.fsum(MUs)
thisMUindx = []
numCtrlPts = int(RTP.BeamSequence[beams[i]].NumberOfControlPoints)
for j in range(0, numCtrlPts):
if j == 0: # then this information is certain to exist
thisMUindx.append(float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].CumulativeMetersetWeight)*scale + addThis)
lastMUindx = float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].CumulativeMetersetWeight)*scale + addThis
else:
try:
thisMUindx.append(float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].CumulativeMetersetWeight)*scale + addThis)
lastMUindx = float(RTP.BeamSequence[beams[i]].ControlPointSequence[j].CumulativeMetersetWeight)*scale + addThis
except AttributeError:
thisMUindx.append(lastMUindx)
MUindx.append(thisMUindx)
return MUindx
def getISO(RTP, beams):
ISO = []
for i in range(0, len(beams)):
thisISO = []
thisISO = RTP.BeamSequence[beams[i]].ControlPointSequence[0].IsocenterPosition
thisISO = [float(thisISO) / 10 for thisISO in thisISO] # mm to cm
beamISO = []
numCtrlPts = int(RTP.BeamSequence[beams[i]].NumberOfControlPoints)
for j in range(0,numCtrlPts):
beamISO.append(thisISO)
ISO.append(beamISO)
return ISO
def isEDW(RTP, beams):
EDW = []
for i in range(0, len(beams)):
try:
len(RTP.BeamSequence[beams[i]].WedgeSequence)
EDW.append(1)
except AttributeError:
EDW.append(0)
return EDW
def getBLDPos(RTP, beams, limiter):
nLeafPair = 60 # hard coded the number of leaf pairs
parkPos = 20 # hard coded the half field opening for parked MLC
limiterPos = []
for i in range(0, len(beams)):
thisLimPos = []
numCtrlPts = int(RTP.BeamSequence[beams[i]].NumberOfControlPoints)
lastLimPos = []
for j in range(0, numCtrlPts):
try:
len(RTP.BeamSequence[beams[i]].ControlPointSequence[j].BeamLimitingDevicePositionSequence)
doGo = True
except AttributeError:
lastLimPos = leafPos
doGo = False
if doGo:
leafPos = []
# look for the current limiter
iamLimiter = -1
for k in range(0, len(RTP.BeamSequence[beams[i]].ControlPointSequence[j].BeamLimitingDevicePositionSequence)):
for l in range(0, len(limiter)):
if limiter[l] == RTP.BeamSequence[beams[i]].ControlPointSequence[j].BeamLimitingDevicePositionSequence[k].RTBeamLimitingDeviceType:
iamLimiter = k
if iamLimiter < 0 and j == 0:
for n in range(0, nLeafPair):
lastLimPos.append(-parkPos)
for n in range(0, nLeafPair):
lastLimPos.append(parkPos)
if iamLimiter >= 0:
leafPos = RTP.BeamSequence[beams[i]].ControlPointSequence[j].BeamLimitingDevicePositionSequence[iamLimiter][0x300a,0x11c].value
leafPos = [float(leafPos) / 10 for leafPos in leafPos] # mm to cm
lastLimPos = leafPos
else:
leafPos = lastLimPos
thisLimPos.append(leafPos)
limiterPos.append(thisLimPos)
return limiterPos
def machineTypeLookUp(fileName, machineName):
f = open(fileName, "r")
# add a trailing white character
machineName = ' '.join([machineName, ''])
for line in f:
if re.search(machineName, line):
thisLine = line
break
return thisLine[thisLine.find(":",
thisLine.find("TreatmentMachineType")) + 1:len(thisLine) - 1].rstrip()
def keeptrack(timeStamp, patID, patName, planLabel):
fileName = ''.join([timeStamp, '.keepTrack'])
f = open(fileName, 'w')
ktstr = '{tS}\t{pID}\t{pN}\t{plL}\n'.format(tS=timeStamp,
pID=patID, pN=patName, plL=planLabel)
f.write(ktstr)
f.close()
return
def numBeams(timeStamp, numBeams):
fileName = ''.join([timeStamp, '.numBeams'])
f = open(fileName, 'w')
f.write(str(numBeams))
f.close()
return
def beamDir(timeStamp, beamDir, suffix):
fileName = '.'.join([timeStamp, suffix])
f = open(fileName, 'w')
f.write(str(beamDir))
f.close()
return
def absCalib(timeStamp, machineName, eflu, MUs, nFrac, corr):
fileName = ''.join([timeStamp, '.absCalib'])
fout = open(fileName, 'w')
with open(machineName, 'r') as fmachine:
cont = fmachine.readlines()
lookFor = ' '.join(['absCalib', eflu])
try:
absCalib = float(cont[[i for i, s in enumerate(cont)
if s.startswith(lookFor)][0]].split(' ')[-1].rstrip())
except IndexError:
absCalib = 1.0 # set to unity if no matched found
fout.write(str(absCalib * math.fsum(MUs) * nFrac * corr))
fout.close()
return
def BEAMegsinp(timeStamp, templateType, machineType, nomEnfluMod, phspDir, EGS_HOME, ncase):
confFile = 'samc.conf'
# get templateDir
templateDir = getVariable(confFile, 'common.templateDir')
phspInType = getVariable(confFile, 'daemonA.phspInType')
fileNameIn = ''.join([templateDir, templateType,
'_BEAMnrc_template.egsinp'])
fIn = open(fileNameIn, 'r')
if nomEnfluMod == '_BEAMnrc':
fileName = ''.join([timeStamp, '_MLCnrc.egsinp'])
else:
fileName = ''.join([timeStamp, '_BEAMnrc.egsinp'])
fOut = open(fileName, 'w')
# the first line in the template file is the BEAMnrc directory
beamDir = (fIn.readline()).rstrip()
# write title
fOut.write('{0}\n'.format(timeStamp))
# Change the stuff below to simple search replace
while True:
thisLine = fIn.readline()
if not thisLine:
break
if thisLine.find('{phsp}') >= 0:
thisLine = thisLine.format(phsp=''.join([phspDir,
machineType, '_', nomEnfluMod, phspInType]))
if thisLine.find('phspType=') > 0:
phspType = int(thisLine[thisLine.rindex('phspType=') + len('phspType=')])
thisLine = thisLine.format(phspType=phspType)
if thisLine.rstrip() == 'syncjawSequence':
thisLine = ''.join([EGS_HOME, beamDir, os.path.sep,
timeStamp, '_BEAMnrc.jaw\n'])
if thisLine.rstrip() == 'syncmlcSequence':
if nomEnfluMod == '_BEAMnrc':
thisLine = ''.join([EGS_HOME, beamDir, os.path.sep,
timeStamp, '_MLCnrc.mlc\n'])
else:
thisLine = ''.join([EGS_HOME, beamDir, os.path.sep,
timeStamp, '_BEAMnrc.mlc\n'])
if thisLine.startswith('{NCASE}'):
thisLine = thisLine.format(NCASE=ncase,
IXXIN=str(random.randint(1, 31328)),
JXXIN=str(random.randint(1, 30081)))
if thisLine.find('{myPhsp}') >= 0:
thisLine = thisLine.format(myPhsp=''.join([EGS_HOME, machineType,
timeStamp, nomEnfluMod, phspDir]))
fOut.write(thisLine)
fOut.close()
fIn.close()
return (beamDir, phspType)
def DOSXYZegsinp(timeStamp, EGS_HOME, egsPhant, mlcLib, beamDir, phspEnd, VCUinp, ISO, gantry, couch, coll, MUindx, dSource, ncase, PatientPosition):
numCtrlPts = len(flatten(MUindx))
ISO = flatten(ISO)
gantry = flatten(gantry)
couch = flatten(couch)
coll = flatten(coll)
MUindx = flatten(MUindx)
# convert angels in DICOM format to EGSnrc format (in a nasty for loop)
theta = []
phi = []
phiCol = []
for i in range(0, numCtrlPts):
(thisTheta, thisPhi, thisPhiCol) = dcm2dosxyz(gantry[i], couch[i], coll[i], PatientPosition)
theta.append(thisTheta)
phi.append(thisPhi)
phiCol.append(thisPhiCol)
confFile = 'samc.conf'
# get templateDir
templateDir = getVariable(confFile, 'common.templateDir')
if numCtrlPts > 0:
fileNameIn = ''.join([templateDir, 'DOSXYZnrc_template.egsinp'])
fileName = ''.join([timeStamp, '_DOSXYZnrc.egsinp'])
else:
fileNameIn = ''.join([templateDir, mlcLib, '_template.egsinp'])
fileName = ''.join([timeStamp, '_MLC.egsinp'])
fIn = open(fileNameIn, 'r')
fOut = open(fileName, 'w')
# the first line in the template file is the DOSXYZnrc directory
dosDir = (fIn.readline()).rstrip()
# write title
fOut.write('{0}\n'.format(timeStamp))
# Change the stuff below to simple search replace
while True:
loopNow = False
thisLine = fIn.readline()
if not thisLine:
break
if thisLine.find('{myEgsphant}') >= 0:
thisLine = thisLine.format(myEgsphant=''.join([EGS_HOME, dosDir,
os.path.sep, egsPhant]))
if thisLine.find('{myMlcLib}') >= 0:
if VCUinp == '0':
thisLine = thisLine.format(myMlcLib=VCUinp,
myPhsp=''.join([EGS_HOME, beamDir, os.path.sep, timeStamp,
'_BEAMnrc', phspEnd]), myVcuTxt=VCUinp)
elif VCUinp == mlcLib:
thisLine = thisLine.format(myMlcLib=mlcLib,
myPhsp=''.join([EGS_HOME, beamDir, os.path.sep, timeStamp,
'_BEAMnrc', phspEnd]),
myVcuTxt=''.join([timeStamp, '_MLCnrc']))
else:
thisLine = thisLine.format(myMlcLib=mlcLib,
myPhsp=''.join([EGS_HOME, beamDir, os.path.sep, timeStamp,
'_BEAMnrc', phspEnd]),
myVcuTxt=''.join([VCUinp, timeStamp, '_vcu.txt']))
if thisLine.find('{NCASE}') >= 0:
thisLine = thisLine.format(NCASE=ncase,
IXXIN=str(random.randint(1, 31328)),
JXXIN=str(random.randint(1, 30081)))
if thisLine.find('{myNumCtrlPts}') > 0:
thisLine = thisLine.format(myNumCtrlPts=numCtrlPts)
loopNow = True
if thisLine.startswith('{myPhsp}'):
thisLine = thisLine.format(myPhsp=''.join([EGS_HOME, beamDir,
os.path.sep, timeStamp, '_BEAMnrc', phspEnd]))
if thisLine.startswith('{MLCseq}'):
thisLine = thisLine.format(MLCseq=VCUinp)
fOut.write(thisLine)
if loopNow:
# loop over numCtrlPts and write:
# ISO(x), ISO(y), ISO(z), theta, phi, phiCol, dSource, MUindx
for i in range(0, numCtrlPts):
fOut.write('{isox:.4f}, {isoy:.4f}, {isoz:.4f}, {th:.4f}, {ph:.4f}, {phC:.4f}, {dS:.4f}, {MUi:.4f}\n'.format(isox=ISO[3*i], isoy=ISO[3*i+1], isoz=ISO[3*i+2], th=theta[i], ph=phi[i], phC=phiCol[i], dS=dSource, MUi=MUindx[i]))
fOut.close()
fIn.close()
return
def syncjawSeq(timeStamp, xJawPos, yJawPos, MUindx):
# syncjawSeq for Varian TrueBeam and Clinac iX, valid for the BEAMnrc CM SYNCJAWS
numCtrlPts = len(flatten(MUindx))
fileName = ''.join([timeStamp, '_BEAMnrc.jaw'])
f = open(fileName, 'w')
# write title
f.write('{0}\n'.format(timeStamp))
# write numCtrlPts
f.write('{0}\n'.format(str(numCtrlPts)))
for i in range(0, len(MUindx)):
for j in range(0, len(MUindx[i])):
# write MUindx[i][j]
f.write('{0:.4f}\n'.format(MUindx[i][j]))
# calculate BEAMnrc SYNCJAW parameters
thisJawPos = calcSyncjawPos(xJawPos[i][j], yJawPos[i][j])
# write SYNCJAW parameters
f.write('{0:.4f}, {1:.4f}, {2:.4f}, {3:.4f}, {4:.4f}, {5:.4f}, \n{6:.4f}, {7:.4f}, {8:.4f}, {9:.4f}, {10:.4f}, {11:.4f}, \n'.format(thisJawPos[0][0], thisJawPos[0][1], thisJawPos[0][2], thisJawPos[0][3], thisJawPos[0][4], thisJawPos[0][5], thisJawPos[1][0], thisJawPos[1][1], thisJawPos[1][2], thisJawPos[1][3], thisJawPos[1][4], thisJawPos[1][5]))
f.close()
return
def syncmlcSeq(timeStamp, leafPos, MUindx, SCD, SAD, leafRadius, is_static, physicalLeafOffset):
# syncmlcSeq for Varian TrueBeam and Clinac iX, valid for the BEAMnrc CMs SYNCVMLC andde SYNCHDMLC
numCtrlPts = len(flatten(MUindx))
bankA, bankB = calcMLCphysPos(leafPos, SAD, SCD, leafRadius, is_static,
physicalLeafOffset, numCtrlPts)
# reshape MUindx according to numCtrlPts
MUindx = np.asarray(flatten(MUindx)).reshape((1, numCtrlPts)).tolist()
fileName = ''.join([timeStamp, '_MLCnrc.mlc'])
f = open(fileName, 'w')
# write title
f.write('{0}\n'.format(timeStamp))
# write numCtrlPts
f.write('{0}\n'.format(str(numCtrlPts)))
for i in range(0, len(MUindx)):
for j in range(0, len(MUindx[i])):
# write MUindx[i][j]
f.write('{0:.4f}\n'.format(MUindx[i][j]))
for k in range(0, len(bankA[i][j])):
f.write('{0:.4f}, {1:.4f}, 1\n'.format(bankA[i][j][-(k + 1)],
bankB[i][j][-(k + 1)])) # invert leaf order
f.close()
return
def vcuMLC(timeStamp, leafPos, MUindx):
numCtrlPts = len(flatten(MUindx))
numLeafs = len(leafPos[0][0])
fileName = ''.join([timeStamp, '_vcu.mlc'])
f = open(fileName, 'w')
# write title and base information
f.write('File Rev = G\nTreatment = Dynamic Dose\nLast Name = {tS}\nFirst Name = {tS}\nPatient ID = {tS}\nNumber of Fields = {nF}\nNumber of Leaves = {nL}\nTolerance = 0.2000\n\n'.format(tS=timeStamp, nF=str(numCtrlPts), nL=str(numLeafs)))
counter = 0
for i in range(0, len(MUindx)):
for j in range(0, len(MUindx[i])):
# write controlpoint header
f.write('Field = 0-{cnt}\nIndex = {indx:.4f}\nCarriage Group = 1\nOperator = \nCollimator = 0.00\n'.format(cnt=str(counter),indx=MUindx[i][j]))
# write leaf positions, bank A
for k in range(0, numLeafs / 2):
if k < 9:
f.write('Leaf ')
else:
f.write('Leaf ')
f.write('{n}A = {i:6.2f}\n'.format(n=str(k + 1),
i=leafPos[i][j][k + numLeafs / 2]))
# write leaf positions, bank B
for k in range(0, numLeafs / 2):
if k < 9:
f.write('Leaf ')
else:
f.write('Leaf ')
f.write('{n}B = {i:6.2f}\n'.format(n=str(k + 1),
i=-leafPos[i][j][k])) # note sign shift for bank B
# write control point footer
f.write('Note = 0\nShape = 0\nMagnification = 1.0\n\n')
counter += 1
# write checksum
f.write('CRC = 8415') # just use a static checksum
f.close()
return
def calcMLCphysPos(leafPos, SAD, SCD, R, is_static, physicalLeafOffset, numCtrlPts):
SAD = float(SAD)
SCD = float(SCD)
R = float(R)
# get nLeafs per bank
nLeafs = len(leafPos[0][0]) / 2
# convert to np.array
leafPos = flatten(leafPos)
leafPos = np.asarray(leafPos).reshape((1, numCtrlPts, nLeafs * 2))
bankA = leafPos[:, :, 0:nLeafs]
bankB = leafPos[:, :, nLeafs:2 * nLeafs]
# adjust for physical Leaf Offset in non-nice loop fashion
#for n in range(0, bankA.shape[0]):
# for i in range(0, bankA.shape[-2]):
# for j in range(0, bankA.shape[-1]):
# if not is_static[n][i][j] and bankB[n][i][j] - bankA[n][i][j] < physicalLeafOffset:
# midpoint = np.mean([bankB[n][i][j], bankA[n][i][j]])
# bankA[n][i][j] = midpoint - physicalLeafOffset/2.
# bankB[n][i][j] = midpoint + physicalLeafOffset/2.
bankA = computeMLCphysPos(-bankA, SAD, SCD, R) * -1
bankB = computeMLCphysPos(bankB, SAD, SCD, R)
return bankA.tolist(), bankB.tolist()
def computeMLCphysPos(bank, SAD, SCD, R):
# compute theta
theta = np.arctan(bank / SAD)
# comnpute light field/MLC cross point
bank = bank / SAD * (SCD + R * np.sin(theta))
# compute physical position
bank = bank - R + R * np.cos(theta)
return bank
def syncMLC(timeStamp, leafPos, MUindx, MLCtype, MLCeffZ, templateDir, SAD):
numCtrlPts = len(flatten(MUindx))
# numLeafs = len(leafPos[0][0])
fileName = ''.join([timeStamp, '_MLCnrc.mlc'])
f = open(fileName, 'w')
# write title
f.write('{0}\n'.format(timeStamp))
# write numCtrlPts
f.write('{0}\n'.format(str(numCtrlPts)))
for i in range(0, len(MUindx)):
for j in range(0, len(MUindx[i])):
# write MUindx[i][j]
f.write('{0:.4f}\n'.format(MUindx[i][j]))
# calculate BEAMnrc SYNCJAW parameters
bankA, bankB = computePhysMLCpos(leafPos[i][j], MLCtype, MLCeffZ,
templateDir, SAD)
for k in range(0, len(bankA)):
# write leafPosition
f.write('{0:.6f}, {1:.6f}, \n'.format(bankB[k], bankA[k]))
f.close()
return
def vcuTXT(timeStamp, machineType, EGS_HOME, beamDir, VCUinp, phspEnd):
confFile = 'samc.conf'
# get templateDir
templateDir = getVariable(confFile, 'common.templateDir')
fileNameIn = ''.join([templateDir, machineType, '_vcuMLC_template.txt'])
fIn = open(fileNameIn, 'r')
fileName = ''.join([timeStamp, '_vcu.txt'])
fOut = open(fileName, 'w')
# Possibly change below to simple search replace.
# Not sure if I can be bothered though, since vcu mlc is kinda outdated
while True:
thisLine = fIn.readline()
if not thisLine:
break
if thisLine.find('{title}') >= 0:
thisLine = thisLine.format(title=timeStamp)
if thisLine.find('{mlcPosFile}') >= 0:
thisLine = thisLine.format(mlcPosFile=''.join([VCUinp,
timeStamp, '_vcu.mlc']))
if thisLine.find('{phspFile}') >= 0:
thisLine = thisLine.format(phspFile=''.join([EGS_HOME, beamDir,
os.path.sep, timeStamp, phspEnd]))
if thisLine.find('{bin}') >= 0:
thisLine = thisLine.format(bin=''.join([EGS_HOME, 'bin']))
fOut.write(thisLine)
fOut.close()
fIn.close()
return
def calcSyncjawPos(xJawPos, yJawPos):
# define static defaults.
# borrowed (with permission) from T.Popescu and C.Shaw
# Applies to both Varian iX and TB
SAD = 100.0
fieldfocus = 0.0
wjaws = 7.873769
zrady = 27.9389
x1 = xJawPos[0]
x2 = xJawPos[1]
y1 = yJawPos[0]
y2 = yJawPos[1]
htY2 = zrady * SAD / math.sqrt(pow(y2, 2) + pow(SAD, 2))
htY1 = zrady * SAD / math.sqrt(pow(y1, 2) + pow(SAD, 2))
htY = (htY2 + htY1) / 2
hbY2 = htY2 + wjaws * SAD / math.sqrt(pow(y2, 2) + pow(SAD, 2))
hbY1 = htY1 + wjaws * SAD / math.sqrt(pow(y1, 2) + pow(SAD, 2))
hbY = (hbY2 + hbY1) / 2
tfY2 = (-1) * (htY - fieldfocus) * y2 / SAD
tbY2 = (-1) * (hbY - fieldfocus) * y2 / SAD
tfY1 = (htY - fieldfocus) * y1 / SAD
tbY1 = (hbY - fieldfocus) * y1 / SAD
htX2 = 36.82855 - wjaws * 20 / math.sqrt(pow(20.0, 2) + pow(SAD, 2))
htX1 = 36.82855
htX = (htX2 + htX1) / 2
hbX2 = htX + wjaws * SAD / math.sqrt(pow(x2, 2) + pow(SAD, 2))
hbX1 = htX + wjaws * SAD / math.sqrt(pow(x1, 2) + pow(SAD, 2))
hbX = (hbX2 + hbX1) / 2
tfX2 = (htX - fieldfocus) * x2 / SAD
tbX2 = (hbX - fieldfocus) * x2 / SAD
tfX1 = (-1) * (htX - fieldfocus) * x1 / SAD
tbX1 = (-1) * (hbX - fieldfocus) * x1 / SAD
jawParams = []
jawParams.append([htY, hbY, -tfY1, -tbY1, tfY2, tbY2])
jawParams.append([htX, hbX, tfX2, tbX2, -tfX1, -tbX1])
return jawParams
def returnAngle(angle, lowBound, upBound):
while angle < lowBound:
angle += upBound
while angle >= upBound:
angle -= upBound
return angle
def rewriteRP(RP, prefix):
# Need to change
# SOPInstanceUID, RTPlanLabel, RTPlanDescription
# SOPInstanceUID
RP.SOPInstanceUID = dicom.UID.generate_uid()
# RTPlanLabel - just add _suffix
s = '_'.join([prefix, RP.RTPlanLabel])
s = s.split(':')
if len(s[0]) > 13: # Eclipse has a limit of 13 chars
s[0] = s[0][0:13]
s = ':'.join(s)
RP.RTPlanLabel = s
# RTPlanDescription
if prefix == 'gamma':
RP.RTPlanDescription = '3D gamma distribution'
else:
RP.RTPlanDescription = 'Monte Carlo simulation; Not for clinical use'
RP.ApprovalStatus = 'REJECTED'
return RP
def rotateByOrientation(matrix, orientation):
# rotate matrix, depending on PatientOrientation
if orientation == 'FFS':
# flip about x and z
matrix = matrix[::-1, ::, ::-1]
elif orientation == 'HFP':
# flip about y and z
matrix = matrix[::, ::-1, ::-1]
elif orientation == 'FFP':
# flip about x and z
matrix = matrix[::-1, ::, ::-1]
# flip about y and z
matrix = matrix[::, ::-1, ::-1]
elif orientation == 'HFDL':
# transpose
matrix = np.transpose(matrix, (0, 2, 1))
# flip about z
matrix = matrix[::, ::, ::-1]
elif orientation == 'FFDL':
# transpose
matrix = np.transpose(matrix, (0, 2, 1))
# flip about z
matrix = matrix[::, ::, ::-1]
# flip about x and z
matrix = matrix[::-1, ::, ::-1]
elif orientation == 'HFDR':
# transpose
matrix = np.transpose(matrix, (0, 2, 1))
# flip about z
matrix = matrix[::, ::, ::-1]
# flip about y and z
matrix = matrix[::, ::-1, ::-1]
elif orientation == 'FFDR':
# transpose
matrix = np.transpose(matrix, (0, 2, 1))
# flip about z
matrix = matrix[::, ::, ::-1]
# flip about y and z
matrix = matrix[::, ::-1, ::-1]
# flip about x and z
matrix = matrix[::-1, ::, ::-1]
return matrix
def rewriteRD(RD, RefSOPuid, doseDist, timeStamp, PatientPosition):
# Need to change
# SOPInstanceUID, ReferencedSOPInstanceUD, DoseGridScaling, PixelData
# SOPInstanceUID
RD.SOPInstanceUID = dicom.UID.generate_uid()
# ReferencedSOPInstanceUID
RD.ReferencedRTPlanSequence[0].ReferencedSOPInstanceUID = RefSOPuid
# rotate matrix, depending on PatientPosition
doseDist = rotateByOrientation(doseDist, PatientPosition)
'''
if PatientPosition == 'FFS':
# flip about x and z
doseDist = doseDist[::-1,::,::-1]
if PatientPosition == 'HFP':
# flip about y and z
doseDist = doseDist[::,::-1,::-1]
if PatientPosition == 'FFP':
# flip about x and z
doseDist = doseDist[::-1,::,::-1]
# flip about y and z
doseDist = doseDist[::,::-1,::-1]
if PatientPosition == 'HFDL':
# transpose
doseDist = np.transpose(doseDist, (0, 2, 1))
# flip about z
doseDist = doseDist[::,::,::-1]
if PatientPosition == 'FFDL':
# transpose
doseDist = np.transpose(doseDist, (0, 2, 1))
# flip about z
doseDist = doseDist[::,::,::-1]
# flip about x and z
doseDist = doseDist[::-1,::,::-1]
if PatientPosition == 'HFDR':
# transpose
doseDist = np.transpose(doseDist, (0, 2, 1))
# flip about z
doseDist = doseDist[::,::,::-1]
# flip about y and z
doseDist = doseDist[::,::-1,::-1]
if PatientPosition == 'FFDR':
# transpose
doseDist = np.transpose(doseDist, (0, 2, 1))
# flip about z
doseDist = doseDist[::,::,::-1]
# flip about y and z
doseDist = doseDist[::,::-1,::-1]
# flip about x and z
doseDist = doseDist[::-1,::,::-1]
'''
if int(RD.Rows) != int(doseDist.shape[1]) or int(RD.Columns) != int(doseDist.shape[2]) or int(RD.NumberOfFrames) != int(doseDist.shape[0]):
ImagePositionPatient = []
GridFrameOffsetVector = []
Rows = doseDist.shape[1]
Columns = doseDist.shape[2]
nof = doseDist.shape[0]
with open(os.path.join(timeStamp, timeStamp + '.doseGrid')) as f:
lines = f.read().splitlines()
for i in range(0, len(lines)):
data = lines[i].split()
val = str(float(data[0]) * 10) # cm to mm
ImagePositionPatient.append(val)
dist = float(RD.GridFrameOffsetVector[1]) - float(RD.GridFrameOffsetVector[0])
GridFrameOffsetVector.append('0.0')
for i in range(1, int(data[2])):
GridFrameOffsetVector.append(str(float(GridFrameOffsetVector[i - 1]) + dist))
RD.Rows = Rows
RD.Columns = Columns
RD.NumberOfFrames = nof
RD.ImagePositionPatient = ImagePositionPatient
RD.GridFrameOffsetVector = GridFrameOffsetVector
# set DoseGridScaling to 1e-6
RD.DoseGridScaling = str(1e-6)
# convert to uint32 using RD.DoseGridScaling
doseDist[doseDist < 0] = 0 # get rid of negative doses.
doseDist = (doseDist / float(RD.DoseGridScaling)).astype('uint32')
# PixelData
RD.PixelData = doseDist.tostring()
return RD
def addRDs(fileA, fileB):
# read fileA
A = dicom.read_file(fileA)
# read fileB
B = dicom.read_file(fileB)
# add doses, assuming that they have the same grid
totDose = A.pixel_array * float(A.DoseGridScaling) + B.pixel_array * float(B.DoseGridScaling)
# convert to uint32 using RD.DoseGridScaling
totDose = (totDose / float(A.DoseGridScaling)).astype('uint32')
# PixelData
A.PixelData = totDose.tostring()
# save as fileA
A.save_as(fileA)
return
def addTPSRDs(fileA, fileB):
# read files
A, Adose, Ax, Ay, Az = readRD(fileA)
B, Bdose, Bx, By, Bz = readRD(fileB)
# check which of the A and B that is most extreme
if (min(Ax) < min(Bx)):
minX = min(Bx)
else:
minX = min(Ax)
if (max(Ax) > max(Bx)):
maxX = max(Bx)
else:
maxX = max(Ax)
if (min(Ay) < min(By)):
minY = min(By)
else:
minY = min(Ay)
if (max(Ay) > max(By)):
maxY = max(By)
else:
maxY = max(Ay)
if (min(Az) < min(Bz)):
minZ = min(Bz)
else:
minZ = min(Az)
if (max(Az) > max(Bz)):
maxZ = max(Bz)
else:
maxZ = max(Az)
# find start and stop indices
iA = []
iA.append(find_nearest_indx(Ax, minX))
iA.append(find_nearest_indx(Ax, maxX))
jA = []
jA.append(find_nearest_indx(Ay, minY))
jA.append(find_nearest_indx(Ay, maxY))
kA = []
kA.append(find_nearest_indx(Az, minZ))
kA.append(find_nearest_indx(Az, maxZ))
iB = []
iB.append(find_nearest_indx(Bx, minX))
iB.append(find_nearest_indx(Bx, maxX))
jB = []
jB.append(find_nearest_indx(By, minY))
jB.append(find_nearest_indx(By, maxY))
kB = []
kB.append(find_nearest_indx(Bz, minZ))
kB.append(find_nearest_indx(Bz, maxZ))
change = False
if len(Adose) * len(Adose[0]) * len(Adose[0][0]) > len(Bdose) * len(Bdose[0]) * len(Bdose[0][0]):
change = True
# crop dose ndarrays
Adose = Adose[kA[0]:kA[1] + 1, jA[0]:jA[1] + 1, iA[0]:iA[1] + 1]
Bdose = Bdose[kA[0]:kA[1] + 1, jA[0]:jA[1] + 1, iA[0]:iA[1] + 1]
# add doses
totDose = Adose + Bdose
#check which is smaller A or B
if change:
# convert to uint32 using RD.DoseGridScaling
totDose = (totDose / float(B.DoseGridScaling)).astype('uint32')
A = B
else:
# convert to uint32 using RD.DoseGridScaling
totDose = (totDose / float(A.DoseGridScaling)).astype('uint32')
# PixelData
A.PixelData = totDose.tostring()
# save as fileA
A.save_as(fileA)
return
def readRD(fileName):
rd = dicom.read_file(fileName)
dose = rd.pixel_array * rd.DoseGridScaling
rows = rd.Rows
columns = rd.Columns
pixel_spacing = rd.PixelSpacing
image_position = rd.ImagePositionPatient
x = np.arange(columns) * pixel_spacing[0] + image_position[0]
y = np.arange(rows) * pixel_spacing[1] + image_position[1]
z = np.array(rd.GridFrameOffsetVector) + image_position[2]
return rd, dose, x, y, z
def find_nearest_indx(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return idx
def readNlist(fileID, n, a):
thisList = []
thatList = []
while len(thisList) < n: