-
Notifications
You must be signed in to change notification settings - Fork 176
/
matRad_TopasMCEngine.m
2402 lines (2050 loc) · 128 KB
/
matRad_TopasMCEngine.m
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
classdef matRad_TopasMCEngine < DoseEngines.matRad_MonteCarloEngineAbstract
% matRad_TopasMCEngine
% Implementation of the TOPAS interface for Monte Carlo dose
% calculation
%
% References
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright 2023 the matRad development team.
%
% This file is part of the matRad project. It is subject to the license
% terms in the LICENSE file found in the top-level directory of this
% distribution and at https://github.com/e0404/matRad/LICENSE.md. No part
% of the matRad project, including this file, may be copied, modified,
% propagated, or distributed except according to the terms contained in the
% LICENSE file.
%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
properties (Constant)
possibleRadiationModes = {'photons','protons','helium','carbon'};
name = 'TOPAS';
shortName = 'TOPAS';
end
properties
calcLET = false;
calcBioDose = false;
prescribedDose = [];
topasExecCommand; %Defaults will be set during construction according to TOPAS installation instructions and used system
parallelRuns = false; %Starts runs in parallel
externalCalculation = false; %Generates folder for external TOPAS calculation (e.g. on a server)
workingDir; %working directory for the simulation
engine = 'TOPAS'; %parameter for continuity
label = 'matRad_plan';
%Simulation parameters
numThreads = 0; %number of used threads, 0 = max number of threads (= num cores)
numOfRuns = 1; %Default number of runs / batches
modeHistories = 'num'; %'frac';
fracHistories = 1e-4; %Fraction of histories to compute
numParticlesPerHistory = 1e6;
verbosity = struct( 'timefeatures',0,...
'cputime',true,...
'run',0,...
'event',0,...
'tracking',0,...
'material',0,...
'maxinterruptedhistories',1000,...
'maxDetailedErrorReports',0);
minRelWeight = .00001; %Threshold for discarding beamlets. 0 means all weights are being considered, can otherwise be assigned to min(w)
useOrigBaseData = false; % base data of the original matRad plan will be used?
beamProfile = 'biGaussian'; %'biGaussian' (emittance); 'simple'
useEnergySpectrum = false;
%Not yet implemented
%beamletMode = false; %In beamlet mode simulation will be performed for a dose influence matrix (i.e., each beamlet simulates numHistories beamlets)
pencilBeamScanning = true; %This should be always true except when using photons (enables deflection)
%Image
materialConverter = struct('mode','HUToWaterSchneider',... %'RSP','HUToWaterSchneider';
'densityCorrection','Schneider_TOPAS',... %'rspHLUT','Schneider_TOPAS','Schneider_matRad'
'addSection','none',... %'none','lung'
'addTitanium',false,... %'false','true' (can only be used with advanced HUsections)
'HUSection','advanced',... %'default','advanced'
'HUToMaterial','default',... %'default',','advanced','MCsquare'
'loadConverterFromFile',false); % set true if you want to use your own SchneiderConverter written in "TOPAS_SchneiderConverter"
arrayOrdering = 'F'; %'C';
rsp_basematerial = 'Water';
%Scoring
scorer = struct('volume',false,...
'doseToMedium',true,...
'doseToWater',false,...
'surfaceTrackCount',false,...
'calcDij',false,...
'RBE',false,...
'RBE_model',{{'default'}},... % default is MCN for protons and LEM1 for ions
'defaultModelProtons',{{'MCN'}},...
'defaultModelCarbon',{{'LEM'}},...
'LET',false,...
'sharedSubscorers',true,...
'outputType','binary',... %'csv'; 'binary';%
... % This variable is only used for physicalDose, since for now it adds unnecessary computation time
'reportQuantity',{{'Sum','Standard_Deviation'}}); % 'reportQuantity',{{'Sum'}});
scorerRBEmodelOrderForEvaluation = {'MCN','WED','LEM','libamtrack'};
bioParameters = struct( 'PrescribedDose',2,...
'AlphaX',0.1,...
'BetaX',0.05,...
'SimultaneousExposure','"True"');
%Physics
electronProductionCut = 0.5; %in mm
radiationMode;
modules_protons = {'g4em-standard_opt4','g4h-phy_QGSP_BIC_HP','g4decay','g4h-elastic_HP','g4stopping','g4ion-QMD','g4radioactivedecay'};
modules_GenericIon = {'g4em-standard_opt4','g4h-phy_QGSP_BIC_HP','g4decay','g4h-elastic_HP','g4stopping','g4ion-QMD','g4radioactivedecay'};
modules_photons = {'g4em-standard_opt4','g4h-phy_QGSP_BIC_HP','g4decay'};
%Geometry / World
worldMaterial = 'G4_AIR';
%filenames
converterFolder = 'materialConverter';
scorerFolder = 'scorer';
outfilenames = struct( 'patientParam','matRad_cube.txt',...
'patientCube','matRad_cube.dat');
infilenames = struct( 'geometry','world/TOPAS_matRad_geometry.txt.in',...
... % BeamSetup files
'beam_virtualGaussian','beamSetup/TOPAS_beamSetup_virtualGaussian.txt.in',...
'beam_phasespace','beamSetup/TOPAS_beamSetup_phasespace.txt.in',...
'beam_uniform','beamSetup/TOPAS_beamSetup_uniform.txt.in',...
'beam_mlc','beamSetup/TOPAS_beamSetup_mlc.txt.in',...
'beam_biGaussian','beamSetup/TOPAS_beamSetup_biGaussian.txt.in',...
'beam_generic','beamSetup/TOPAS_beamSetup_generic.txt.in',...
... % Schneier Converter
... % Defined Materials
'matConv_Schneider_definedMaterials',struct('default','definedMaterials/default.txt.in',...
'MCsquare','definedMaterials/MCsquare.txt.in',...
'advanced','definedMaterials/advanced.txt.in'),...
... % Density Correction
'matConv_Schneider_densityCorr_Schneider_matRad','densityCorrection/Schneider_matRad.dat',...
'matConv_Schneider_densityCorr_Schneider_TOPAS','densityCorrection/Schneider_TOPAS.dat',...
... % load from file
'matConv_Schneider_loadFromFile','TOPAS_SchneiderConverter.txt.in',...
... % Scorer
'Scorer_surfaceTrackCount','TOPAS_scorer_surfaceIC.txt.in',...
'Scorer_doseToMedium','TOPAS_scorer_doseToMedium.txt.in',...
'Scorer_LET','TOPAS_subscorer_LET.txt.in',...
'Scorer_doseToWater','TOPAS_scorer_doseToWater.txt.in',...
'Scorer_RBE_libamtrack','TOPAS_scorer_doseRBE_libamtrack.txt.in',...
'Scorer_RBE_LEM1','TOPAS_scorer_doseRBE_LEM1.txt.in',...
'Scorer_RBE_WED','TOPAS_scorer_doseRBE_Wedenberg.txt.in',...
'Scorer_RBE_MCN','TOPAS_scorer_doseRBE_McNamara.txt.in', ...
... %PhaseSpace Source
'phaseSpaceSourcePhotons' ,'VarianClinaciX_6MV_20x20_aboveMLC_w2' );
end
properties (SetAccess = protected, GetAccess = private)
topasFolder;
MCparam; %Struct with parameters of last simulation to be saved to file
ctR; %resmpaled CT
end
methods
function obj = matRad_TopasMCEngine(pln)
if nargin < 1
pln = [];
end
% call superclass constructor
obj = obj@DoseEngines.matRad_MonteCarloEngineAbstract(pln);
end
function setDefaults(this)
this.setDefaults@DoseEngines.matRad_MonteCarloEngineAbstract();
matRad_cfg = MatRad_Config.instance(); %Instance of matRad configuration class
% Default execution paths are set here
this.topasFolder = [matRad_cfg.matRadRoot filesep 'TOPAS'];
this.workingDir = [this.topasFolder filesep 'MCrun' filesep];
%Let's set some default commands taken from topas installation
%instructions for mac & debain/ubuntu
if ispc %We assume topas is installed in wsl (since no windows version)
this.topasExecCommand = 'wsl export TOPAS_G4_DATA_DIR=~/G4Data; ~/topas/bin/topas';
elseif ismac
this.topasExecCommand = 'export TOPAS_G4_DATA_DIR=/Applications/G4Data; export QT_QPA_PLATFORM_PLUGIN_PATH=/Applications/topas/Frameworks; /Applications/topas/bin/topas';
elseif isunix
this.topasExecCommand = 'export TOPAS_G4_DATA_DIR=~/G4Data; ~/topas/bin/topas';
else
this.topasExecCommand = '';
end
end
function writeAllFiles(obj,ct,cst,stf,machine,w)
% constructor to write all TOPAS fils for local or external simulation
%
% call
% topasConfig.writeAllFiles(ct,pln,stf,machine,w)
%
% input
% ct: Path to folder where TOPAS files are in (as string)
% pln: matRad plan struct
% stf: matRad steering struct
% machine: machine to be used for calculation
% w: (optional) weights in case of calcDoseDirect
matRad_cfg = MatRad_Config.instance(); %Instance of matRad configuration class
% prepare biological parameters
if ~isempty(obj.prescribedDose)
obj.bioParameters.PrescribedDose = obj.prescribedDose;
end
if isempty(obj.radiationMode)
obj.radiationMode = machine.meta.radiationMode;
end
% Set correct RBE scorer parameters
if obj.scorer.RBE
obj.scorer.doseToMedium = true;
if any(cellfun(@(teststr) ~isempty(strfind(lower(teststr),'default')), obj.scorer.RBE_model))
switch obj.radiationMode
case 'protons'
obj.scorer.RBE_model = obj.scorer.defaultModelProtons;
case {'carbon','helium'}
obj.scorer.RBE_model = obj.scorer.defaultModelCarbon;
otherwise
matRad_cfg.dispError(['No RBE model implemented for ',obj.radiationMode]);
end
end
% Get alpha beta parameters from bioParam struct
for i = 1:length(obj.bioParameters.AvailableAlphaXBetaX)
if ~isempty(strfind(lower(obj.bioParameters.AvailableAlphaXBetaX{i,2}),'default'))
break
end
end
obj.bioParameters.AlphaX = obj.bioParameters.AvailableAlphaXBetaX{5,1}(1);
obj.bioParameters.BetaX = obj.bioParameters.AvailableAlphaXBetaX{5,1}(2);
end
if obj.scorer.LET
obj.scorer.doseToMedium = true;
end
% create TOPAS working directory if not set
if ~exist(obj.workingDir,'dir')
mkdir(obj.workingDir);
matRad_cfg.dispInfo('Created TOPAS working directory %s\n',obj.workingDir);
end
% Write CT, patient parameters and Schneider converter
matRad_cfg.dispInfo('Writing parameter files to %s\n',obj.workingDir);
obj.writePatient(ct);
% Generate uniform weights in case of dij calculation (for later optimization)
if ~exist('w','var')
numBixels = sum([stf(:).totalNumOfBixels]);
w = ones(numBixels,1);
end
% Set MCparam structure with important simulation parameters that is needed for later readOut and
% postprocessing
obj.MCparam = struct();
obj.MCparam.tallies = {};
obj.MCparam.nbRuns = obj.numOfRuns;
obj.MCparam.simLabel = obj.label;
obj.MCparam.scoreReportQuantity = obj.scorer.reportQuantity;
obj.MCparam.workingDir = obj.workingDir;
obj.MCparam.weights = w;
obj.MCparam.ctGrid = ct.ctGrid;
if isfield(ct,'originalGrid')
obj.MCparam.originalGrid = ct.originalGrid;
end
obj.MCparam.cubeDim = ct.cubeDim;
obj.MCparam.ctResolution = ct.resolution;
obj.MCparam.numOfCtScen = ct.numOfCtScen;
% Save used RBE models
if obj.scorer.RBE
obj.MCparam.RBE_models = obj.scorer.RBE_model;
[obj.MCparam.ax,obj.MCparam.bx] = matRad_getPhotonLQMParameters(cst,prod(ct.cubeDim),obj.MCparam.numOfCtScen);
obj.MCparam.abx(obj.MCparam.bx>0) = obj.MCparam.ax(obj.MCparam.bx>0)./obj.MCparam.bx(obj.MCparam.bx>0);
end
% fill in bixels, rays and beams in case of dij calculation or external calculation
if obj.scorer.calcDij
counter = 1;
for f = 1:length(stf)
for r = 1:stf(f).numOfRays
for b = 1:stf(f).numOfBixelsPerRay(r)
obj.MCparam.bixelNum(counter) = b;
obj.MCparam.rayNum(counter) = r;
obj.MCparam.beamNum(counter) = f;
counter = counter + 1;
end
end
end
else
% In case of calcDoseDirect, you only need beamNum
obj.MCparam.bixelNum = 1;
obj.MCparam.rayNum = 1;
obj.MCparam.beamNum = 1:length(stf);
end
obj.MCparam.numOfRaysPerBeam = [stf(:).numOfRays];
% Generate baseData using the MCemittanceBaseData constructor
% Write TOPAS beam properties
if ~strcmp(machine.meta.radiationMode,'photons')
topasBaseData = matRad_MCemittanceBaseData(machine,stf);
else
topasBaseData = [];
end
obj.writeStfFields(ct,stf,w,topasBaseData);
% Save simulation parameters to folder
obj.writeMCparam();
% Console message
matRad_cfg.dispInfo('Successfully written TOPAS setup files!\n')
end
function dij = readFiles(obj,folder)
% function to read out TOPAS data
%
% call
% topasCube = topasConfig.readFiles(folder,dij)
% topasCube = obj.readFiles(folder,dij)
%
% input
% folder: Path to folder where TOPAS files are in (as string)
% dij: dij struct (this part needs update)
%
% output
% topasCube: struct with all read out subfields
% Load in saved MC parameters
if isfile([folder filesep 'MCparam.mat'])
obj.MCparam = load([folder filesep 'MCparam.mat'],'MCparam');
obj.MCparam = obj.MCparam.MCparam;
end
% Read out all TOPAS fields
topasCubes = obj.readTopasCubes(folder);
% Set 0 for empty or NaN fields
topasCubes = obj.markFieldsAsEmpty(topasCubes);
%% Fill Dij analogously to matRad
% Prepare empty Dij with empty sparse matrices for fields in topasCubes
dij = obj.prepareDij(topasCubes);
% Fill empty Dij with fields from topasCubes
dij = obj.fillDij(topasCubes,dij);
end
function resultGUI = getResultGUI(obj,dij)
if obj.scorer.calcDij
resultGUI = matRad_calcCubes(ones(dij.totalNumOfBixels,1),dij,1);
else
resultGUI = matRad_calcCubes(ones(dij.numOfBeams,1),dij,1);
end
% Export RBE model if filled
if isfield(resultGUI,'RBE_model') && ~isempty(resultGUI.RBE_model)
resultGUI.RBE_model = dij.RBE_model;
end
% Export histories to resultGUI
if isfield(dij,'nbHistoriesTotal')
resultGUI.nbHistoriesTotal = dij.nbHistoriesTotal;
resultGUI.nbParticlesTotal = dij.nbParticlesTotal;
end
% stuff for 4D
% if this.multScen.totNumScen ~= 1
% resultGUI.accPhysicalDose = zeros(size(resultGUI.phaseDose{1}));
% for i = 1:this.multScen.totNumScen
% resultGUI.accPhysicalDose = resultGUI.accPhysicalDose + resultGUI.phaseDose{i};
% end
% end
end
function resultGUI = readExternal(obj,folder)
% function to read out complete TOPAS simulation from single folder
%
% call
% topasCube = topasConfig.readExternal(folder)
% topasCube = obj.readExternal(folder)
%
% input
% folder: Path to folder where TOPAS files are in (as string)
%
% output
% topasCube: struct with all read out subfields
%
% EXAMPLE calls:
% topasCube = topasConfig.readExternal('pathToFolder')
% read in TOPAS files in dij
dij = obj.readFiles(folder);
% Postprocessing
resultGUI = obj.getResultGUI(dij);
end
end
methods (Access = protected)
function dij = calcDose(this,ct,cst,stf)
% Instance of MatRad_Config class
matRad_cfg = MatRad_Config.instance();
% Set parameters for full Dij calculation
if ~this.calcDoseDirect
this.scorer.calcDij = true;
this.numOfRuns = 1;
end
% set nested folder structure if external calculation is turned on (this will put new simulations in subfolders)
if this.externalCalculation
this.workingDir = [this.topasFolder filesep 'MCrun' filesep];
this.workingDir = [this.workingDir stf(1).radiationMode,'_',stf(1).machine,'_',datestr(now, 'dd-mm-yy')];
end
%% Initialize dose grid and dij
% load calcDoseInit as usual
dij = this.initDoseCalc(ct,cst,stf);
%% sending data to topas
if isfield(this.machine.meta,'SCD')
for i = 1:size(stf,2)
stf(i).SCD = this.machine.meta.SCD;
end
end
% Collect given weights
if this.calcDoseDirect
% w = zeros(sum([stf(:).totalNumOfBixels]),ctR.numOfCtScen);
w = zeros(sum([stf(:).totalNumOfBixels]),1);
counter = 1;
for i = 1:length(stf)
for j = 1:stf(i).numOfRays
rayBix = stf(i).numOfBixelsPerRay(j);
if isfield(stf(1).ray, 'shapes')
w(counter:counter+rayBix-1) = [stf(i).ray.shapes.weight];
else
w(counter:counter+rayBix-1,:) = stf(i).ray(j).weight;
end
counter = counter + rayBix;
end
end
end
for i = 1:numel(stf)
if strcmp(stf(i).radiationMode,'photons')
stf(i).ray.energy = stf(i).ray.energy.*ones(size(w));
end
end
% Get photon parameters for RBExD calculation
if this.calcBioDose
this.scorer.RBE = true;
[dij.ax,dij.bx] = matRad_getPhotonLQMParameters(cst,dij.doseGrid.numOfVoxels,1,VdoseGrid);
dij.abx(dij.bx>0) = dij.ax(dij.bx>0)./dij.bx(dij.bx>0);
end
% save current directory to revert back to later
currDir = cd;
for shiftScen = 1:this.multScen.totNumShiftScen
%Find first instance of the shift to select the shift values
ixShiftScen = find(this.multScen.linearMask(:,2) == shiftScen,1);
% manipulate isocenter
for k = 1:numel(stf)
stf(k).isoCenter = stf(k).isoCenter + this.multScen.isoShift(ixShiftScen,:);
end
% Delete previous topas files so there is no mix-up
files = dir([this.workingDir,'*']);
files = {files(~[files.isdir]).name};
fclose('all');
for i = 1:length(files)
delete([this.workingDir,files{i}])
end
% Run simulations for each scenario
for ctScen = 1:this.multScen.numOfCtScen
for rangeShiftScen = 1:this.multScen.totNumRangeScen
if this.multScen.scenMask(ctScen,shiftScen,rangeShiftScen)
% Save ctScen and rangeShiftScen for file constructor
if ct.numOfCtScen > 1
this.ctR.currCtScen = ctScen;
this.ctR.currRangeShiftScen = rangeShiftScen;
end
% actually write TOPAS files
if this.calcDoseDirect
this.writeAllFiles(this.ctR,cst,stf,this.machine,w);
else
this.writeAllFiles(this.ctR,cst,stf,this.machine);
end
end
end
end
% change director back to original directory
cd(this.workingDir);
% Skip local calculation and data readout with this parameter. All necessary parameters to read the data back in
% later are stored in the MCparam file that is stored in the folder. The folder is generated in the working
% directory and the matRad_plan*.txt file can be manually called with TOPAS.
if this.externalCalculation
matRad_cfg.dispInfo(['TOPAS simulation skipped for external calculation\nFiles have been written to: "',replace(this.workingDir,'\','\\'),'"']);
else
for ctScen = 1:ct.numOfCtScen
for beamIx = 1:numel(stf)
for runIx = 1:this.numOfRuns
if ct.numOfCtScen > 1
fname = sprintf('%s_field%d_ct%d_run%d',this.label,beamIx,ctScen,runIx);
else
fname = sprintf('%s_field%d_run%d',this.label,beamIx,runIx);
end
if isprop(this,'verbosity') && strcmp(this.verbosity,'full')
topasCall = sprintf('%s %s.txt',this.topasExecCommand,fname);
else
topasCall = sprintf('%s %s.txt > %s.out > %s.log',this.topasExecCommand,fname,fname,fname);
end
% initiate parallel runs and delete previous files
if this.parallelRuns
finishedFiles{runIx} = sprintf('%s.finished',fname);
topasCall = [topasCall '; touch ' finishedFiles{runIx} ' &'];
end
% Actual simulation happening here
matRad_cfg.dispInfo('Calling TOPAS: %s\n',topasCall);
[status,cmdout] = system(topasCall,'-echo');
% Process TOPAS output and potential errors
cout = splitlines(string(cmdout));
if status == 0
matRad_cfg.dispInfo('TOPAS simulation completed succesfully\n');
else
if status == 139
matRad_cfg.dispError('TOPAS segmentation fault: might be caused from an outdated TOPAS version or Linux distribution');
else
matRad_cfg.dispError('TOPAS simulation exited with error code %d\n "%s"',status,cout(2:end-1));
end
end
end
% wait for parallel runs to finish and process
if this.parallelRuns
runsFinished = false;
pause('on');
while ~runsFinished
pause(1);
fin = cellfun(@(f) exist(f,'file'),finishedFiles);
runsFinished = all(fin);
end
% Delete marker files
delete(finishedFiles{:});
end
end
end
end
% revert back to original directory
cd(currDir);
% manipulate isocenter back
for k = 1:length(stf)
stf(k).isoCenter = stf(k).isoCenter - this.multScen.isoShift(ixShiftScen,:);
end
end
%% Simulation(s) finished - read out volume scorers from topas simulation
% Skip readout if external files were generated
if ~this.externalCalculation
dij = this.readFiles(this.workingDir);
% Order fields for easier comparison between different dijs
dij = orderfields(dij);
else
dij = [];
end
end
function dij = initDoseCalc(this,ct,cst,stf)
dij = this.initDoseCalc@DoseEngines.matRad_MonteCarloEngineAbstract(ct,cst,stf);
matRad_cfg = MatRad_Config.instance();
% % for TOPAS we explicitly downsample the ct to the dose grid (might not be necessary in future versions with separated grids)
% Check if CT has already been resampled
matRad_cfg.dispInfo('Resampling cst... ');
if ~isfield(ct,'resampled')
% Allpcate resampled cubes
cubeHUresampled = cell(1,ct.numOfCtScen);
cubeResampled = cell(1,ct.numOfCtScen);
% Perform resampling to dose grid
for s = 1:ct.numOfCtScen
cubeHUresampled{s} = matRad_interp3(dij.ctGrid.x, dij.ctGrid.y', dij.ctGrid.z,ct.cubeHU{s}, ...
dij.doseGrid.x,dij.doseGrid.y',dij.doseGrid.z,'linear');
cubeResampled{s} = matRad_interp3(dij.ctGrid.x, dij.ctGrid.y', dij.ctGrid.z,ct.cube{s}, ...
dij.doseGrid.x,dij.doseGrid.y',dij.doseGrid.z,'linear');
end
% Allocate temporary resampled CT
this.ctR = ct;
this.ctR.cube = cell(1);
this.ctR.cubeHU = cell(1);
% Set CT resolution to doseGrid resolution
this.ctR.resolution = dij.doseGrid.resolution;
this.ctR.cubeDim = dij.doseGrid.dimensions;
this.ctR.x = dij.doseGrid.x;
this.ctR.y = dij.doseGrid.y;
this.ctR.z = dij.doseGrid.z;
% Write resampled cubes
this.ctR.cubeHU = cubeHUresampled;
this.ctR.cube = cubeResampled;
% Set flag for complete resampling
this.ctR.resampled = 1;
this.ctR.ctGrid = dij.doseGrid;
% Save original grid
this.ctR.originalGrid = dij.ctGrid;
matRad_cfg.dispInfo('done!\n');
else
this.ctR = ct;
matRad_cfg.dispInfo('already resampled. Skipping! \n');
end
% overwrite CT grid in dij in case of modulation.
if isfield(this.ctR,'ctGrid')
dij.ctGrid = this.ctR.ctGrid;
end
end
end
methods (Access = private)
function topasCubes = markFieldsAsEmpty(obj,topasCubes)
matRad_cfg = MatRad_Config.instance(); %Instance of matRad configuration class
% Check if all fields in topasCubes are filled or overwrite with 0 if not.
fields = fieldnames(topasCubes);
for field = 1:length(fields)
if all(isnan(topasCubes.(fields{field}){1}(:)) | topasCubes.(fields{field}){1}(:)==0)
matRad_cfg.dispWarning(['Field ' fields{field} ' in topasCubes resulted in all zeros and NaN.'])
topasCubes.(fields{field}) = 0;
end
end
end
function topasCube = readTopasCubes(obj,folder)
% function to read out TOPAS data
%
% call
% topasCube = topasConfig.readTopasCubes(folder,dij)
% topasCube = obj.readTopasCubes(folder,dij)
%
% input
% folder: Path to folder where TOPAS files are in (as string)
% dij: dij struct (this part needs update)
%
% output
% topasCube: struct with all read out subfields
matRad_cfg = MatRad_Config.instance(); %Instance of matRad configuration class
% obj.MCparam.scoreReportQuantity = 'Sum';
% Process reportQuantities (for example 'Sum' or 'Standard_Deviation'read
if iscell(obj.MCparam.scoreReportQuantity)
obj.MCparam.numOfReportQuantities = length(obj.MCparam.scoreReportQuantity);
else
obj.MCparam.numOfReportQuantities = 1;
obj.MCparam.scoreReportQuantity = {obj.MCparam.scoreReportQuantity};
end
% Normalize with histories and particles/weight
correctionFactor = obj.numParticlesPerHistory / double(obj.MCparam.nbHistoriesTotal);
% Get all saved quantities
% Make sure that the filename always ends on 'run1_tally'
switch obj.MCparam.outputType
case 'csv'
searchstr = 'score_matRad_plan_field1_run1_*.csv';
files = dir([folder filesep searchstr]);
%obj.MCparam.tallies = cellfun(@(x) extractBetween(x,'run1_','.csv') ,{files(:).name}); %Not Octave compatible
nameBegin = strfind(searchstr,'*');
obj.MCparam.tallies = cellfun(@(s) s(nameBegin:end-4),{files(:).name},'UniformOutput',false);
case 'binary'
searchstr = 'score_matRad_plan_field1_run1_*.bin';
files = dir([folder filesep searchstr]);
%obj.MCparam.tallies = cellfun(@(x) extractBetween(x,'run1_','.bin') ,{files(:).name}); %Not Octave compatible
nameBegin = strfind(searchstr,'*');
obj.MCparam.tallies = cellfun(@(s) s(nameBegin:end-4),{files(:).name},'UniformOutput',false);
end
obj.MCparam.tallies = unique(obj.MCparam.tallies);
talliesCut = replace(obj.MCparam.tallies,'-','_');
% Load data for each tally individually
for t = 1:length(obj.MCparam.tallies)
tnameFile = obj.MCparam.tallies{t};
tname = talliesCut{t};
% Loop over all beams/fields and ctScenarios
for f = 1:obj.MCparam.nbFields
for ctScen = 1:obj.MCparam.numOfCtScen
% Loop over all batches/runs
for k = 1:obj.MCparam.nbRuns
% Get file name of current field, run and tally (and ct, if applicable)
if obj.MCparam.numOfCtScen > 1
genFileName = sprintf('score_%s_field%d_ct%d_run%d_%s',obj.MCparam.simLabel,f,ctScen,k,tnameFile);
else
genFileName = sprintf('score_%s_field%d_run%d_%s',obj.MCparam.simLabel,f,k,tnameFile);
end
switch obj.MCparam.outputType
case 'csv'
% Generate csv file path to load
genFullFile = fullfile(folder,[genFileName '.csv']);
case 'binary'
% Generate bin file path to load
genFullFile = fullfile(folder,[genFileName '.bin']);
otherwise
matRad_cfg.dispError('Not implemented!');
end
% Read data from scored TOPAS files
dataRead = obj.readBinCsvData(genFullFile);
for i = 1:numel(dataRead)
data.(obj.MCparam.scoreReportQuantity{i}){k} = dataRead{i};
end
% for example the standard deviation is not calculated for alpha/beta so a loop through all
% reportQuantities does not work here
currNumOfQuantities = numel(dataRead);
end
% Set dimensions of output cube
cubeDim = size(dataRead{1});
% add STD quadratically
for i = 1:currNumOfQuantities
if ~isempty(strfind(lower(obj.MCparam.scoreReportQuantity{i}),'standard_deviation'))
topasSum.(obj.MCparam.scoreReportQuantity{i}) = sqrt(double(obj.MCparam.nbHistoriesTotal)) * sqrt(sum(cat(4,data.(obj.MCparam.scoreReportQuantity{i}){:}).^2,4));
else
topasSum.(obj.MCparam.scoreReportQuantity{i}) = sum(cat(4,data.(obj.MCparam.scoreReportQuantity{i}){:}),4);
end
end
if ~isempty(strfind(lower(tnameFile),'dose'))
if obj.MCparam.nbRuns > 1
% Calculate Standard Deviation from batches
topasMeanDiff = zeros(cubeDim(1),cubeDim(2),cubeDim(3));
for k = 1:obj.MCparam.nbRuns
topasMeanDiff = topasMeanDiff + (data.Sum{k} - topasSum.Sum / obj.MCparam.nbRuns).^2;
end
% variance of the mean
topasVarMean = topasMeanDiff./(obj.MCparam.nbRuns - 1)./obj.MCparam.nbRuns;
% std of the MEAN!
topasStdMean = sqrt(topasVarMean);
% std of the SUM
topasStdSum = topasStdMean * correctionFactor * obj.MCparam.nbRuns;
% Save std to topasCube
topasCube.([tname '_batchStd_beam' num2str(f)]){ctScen} = topasStdSum;
end
for i = 1:currNumOfQuantities
topasSum.(obj.MCparam.scoreReportQuantity{i}) = correctionFactor .* topasSum.(obj.MCparam.scoreReportQuantity{i});
end
elseif any(cellfun(@(teststr) ~isempty(strfind(tname,teststr)), {'alpha','beta','RBE','LET'}))
for i = 1:currNumOfQuantities
topasSum.(obj.MCparam.scoreReportQuantity{i}) = topasSum.(obj.MCparam.scoreReportQuantity{i}) ./ obj.MCparam.nbRuns;
end
end
% Tally per field
if isfield(topasSum,'Sum')
topasCube.([tname '_beam' num2str(f)]){ctScen} = topasSum.Sum;
end
if isfield(topasSum,'Standard_Deviation')
topasCube.([tname '_std_beam' num2str(f)]){ctScen} = topasSum.Standard_Deviation;
end
end
end
end
end
function dataOut = readBinCsvData(~,genFullFile)
matRad_cfg = MatRad_Config.instance(); %Instance of matRad configuration class
if ~isempty(strfind(lower(genFullFile),'.csv'))
% Read csv header file to get cubeDim and number of scorers automatically
fid = fopen(genFullFile);
header = textscan(fid,'%[^,],%[^,],%[^,]',1);
fclose(fid);
% Split header in rows
header = strsplit(strrep(header{1}{1},' ',''),'#');
elseif ~isempty(strfind(lower(genFullFile),'.bin'))
% Isolate filename without ending
[folder, filename] = fileparts(genFullFile);
strippedFileName = [folder filesep filename];
% Read binheader file to get cubeDim and number of scorers automatically
fID = fopen([strippedFileName '.binheader']);
header = textscan(fID,'%c');
fclose(fID);
% Split header in rows
header = strsplit(header{1}','#')';
else
% Error if neither csv nor bin
matRad_cfg.dispError('Not implemented!');
end
% Find rows where number of bins are stored
xLine = find(cellfun(@(x) ~isempty(x), strfind(header,'Xin')));
cubeDim(2) = str2double(header{xLine}(4:strfind(header{xLine},'binsof')-1));
cubeDim(1) = str2double(header{xLine+1}(4:strfind(header{xLine+1},'binsof')-1));
cubeDim(3) = str2double(header{xLine+2}(4:strfind(header{xLine+2},'binsof')-1));
if ~isempty(strfind(lower(genFullFile),'.csv'))
% Read out bin data
dataOut = matRad_readCsvData(genFullFile,cubeDim);
elseif ~isempty(strfind(lower(genFullFile),'.bin'))
% Read out bin data
dataOut = matRad_readBinData(genFullFile,cubeDim);
end
end
function dij = prepareDij(obj,topasCubes)
% Load ctScen variable
numOfScenarios = obj.MCparam.numOfCtScen;
% Set flag for RBE and LET
if any(cellfun(@(teststr) ~isempty(strfind(lower(teststr),'alpha')), fieldnames(topasCubes)))
obj.scorer.RBE = true;
end
if any(cellfun(@(teststr) ~isempty(strfind(teststr,'LET')), fieldnames(topasCubes)))
obj.scorer.LET = true;
end
% Create empty dij
dij.numOfScenarios = numOfScenarios;
dij.numOfBeams = max(obj.MCparam.beamNum);
dij.numOfRaysPerBeam = obj.MCparam.numOfRaysPerBeam;
dij.totalNumOfRays = sum(dij.numOfRaysPerBeam);
dij.totalNumOfBixels = length(obj.MCparam.bixelNum);
dij.bixelNum = obj.MCparam.bixelNum';
dij.rayNum = obj.MCparam.rayNum';
dij.beamNum = obj.MCparam.beamNum';
% Write dij grids
dij.doseGrid = obj.MCparam.ctGrid;
dij.ctGrid = obj.MCparam.originalGrid;
% Save RBE models in dij for postprocessing in calcCubes
if obj.scorer.RBE
dij.RBE_models = obj.MCparam.RBE_models;
dij.ax = obj.MCparam.ax;
dij.bx = obj.MCparam.bx;
dij.abx = obj.MCparam.abx;
end
% Get basic tallies from topasCubes for sparse matrix allocation
beamNames = strsplit(sprintf('_beam%i,',1:dij.numOfBeams),',');
if obj.scorer.calcDij
rayNames = strsplit(sprintf('_ray%i,',unique(dij.rayNum)),',');
bixelNames = strsplit(sprintf('_bixel%i,',unique(dij.bixelNum)),',');
topasCubesTallies = unique(erase(fieldnames(topasCubes),rayNames));
topasCubesTallies = unique(erase(topasCubesTallies,bixelNames));
topasCubesTallies = unique(erase(topasCubesTallies,beamNames));
else
topasCubesTallies = unique(erase(fieldnames(topasCubes),beamNames));
end
% Get default tallies from dose
dijTallies = topasCubesTallies(cellfun(@(teststr) ~isempty(strfind(lower(teststr),'dose')), topasCubesTallies));
% Handle LET tally
if obj.scorer.LET
dijTallies{end+1} = 'mLETDose';
% dijTallies{end+1} = 'LET';
end
% Get unique tallies for RBE models
if obj.scorer.RBE
for r = 1:length(obj.MCparam.RBE_models)
dijTallies{end+1} = ['mAlphaDose_' obj.MCparam.RBE_models{r}];
dijTallies{end+1} = ['mSqrtBetaDose_' obj.MCparam.RBE_models{r}];
% dijTallies{end+1} = 'alpha';
% dijTallies{end+1} = 'beta';
end
end
% Create empty sparse matrices
% Note that for MonteCarlo, there are no individual bixels, but only 2 beams
for t = 1:length(dijTallies)
for ctScen = 1:dij.numOfScenarios
if obj.scorer.calcDij
dij.(dijTallies{t}){ctScen,1} = spalloc(obj.MCparam.ctGrid.numOfVoxels,dij.totalNumOfBixels,1);
else
dij.(dijTallies{t}){ctScen,1} = spalloc(obj.MCparam.ctGrid.numOfVoxels,dij.numOfBeams,1);
end
end
end
end
function dij = fillDij(obj,topasCubes,dij)
%TODO: Insert documentation
matRad_cfg = MatRad_Config.instance(); %Instance of matRad configuration class
% Load weights from parameter variable
w = obj.MCparam.weights;
% Get basic tallies from topasCubes for sparse matrix allocation
beamNames = strsplit(sprintf('_beam%i,',1:dij.numOfBeams),',');
if obj.scorer.calcDij
rayNames = strsplit(sprintf('_ray%i,',unique(dij.rayNum)),',');
bixelNames = strsplit(sprintf('_bixel%i,',unique(dij.bixelNum)),',');
topasCubesTallies = unique(erase(fieldnames(topasCubes),rayNames));
topasCubesTallies = unique(erase(topasCubesTallies,bixelNames));
topasCubesTallies = unique(erase(topasCubesTallies,beamNames));
else
topasCubesTallies = unique(erase(fieldnames(topasCubes),beamNames));
end
% Allocate possible scored quantities
processedQuantities = {'','_std','_batchStd'};
topasCubesTallies = unique(erase(topasCubesTallies,processedQuantities(2:end)));
% Loop through 4D scenarios
for ctScen = 1:dij.numOfScenarios
% Process physicalDose
% this is done separately since it's needed for processing the other dose fields
if obj.scorer.calcDij
for d = 1:dij.totalNumOfBixels
physDoseFields = strfind(lower(topasCubesTallies),'physicaldose');
physDoseFields = not(cellfun('isempty',physDoseFields));
for j = find(physDoseFields)'
% loop through possible quantities
for p = 1:length(processedQuantities)
% Check if current quantity is available and write to dij
if isfield(topasCubes,[topasCubesTallies{j} '_ray' num2str(dij.rayNum(d)) '_bixel' num2str(dij.bixelNum(d)) processedQuantities{p} '_beam' num2str(dij.beamNum(d))]) ...
&& iscell(topasCubes.([topasCubesTallies{j} '_ray' num2str(dij.rayNum(d)) '_bixel' num2str(dij.bixelNum(d)) processedQuantities{p} '_beam' num2str(dij.beamNum(d))]))
dij.([topasCubesTallies{j} processedQuantities{p}]){ctScen,1}(:,d) = sum(w)*reshape(topasCubes.([topasCubesTallies{j} '_ray' num2str(dij.rayNum(d)) '_bixel' num2str(dij.bixelNum(d)) processedQuantities{p} '_beam' num2str(dij.beamNum(d))]){ctScen},[],1);
end
end
end
end
else
for d = 1:dij.numOfBeams
physDoseFields = strfind(lower(topasCubesTallies),'physicaldose');
physDoseFields = not(cellfun('isempty',physDoseFields));
for j = find(physDoseFields)'
for p = 1:length(processedQuantities)
% Check if current quantity is available and write to dij
if isfield(topasCubes,[topasCubesTallies{j} processedQuantities{p} '_beam' num2str(d)]) && iscell(topasCubes.([topasCubesTallies{j} processedQuantities{p} '_beam' num2str(d)]))
dij.([topasCubesTallies{j} processedQuantities{p}]){ctScen}(:,d) = sum(w)*reshape(topasCubes.([topasCubesTallies{j} processedQuantities{p} '_beam',num2str(d)]){ctScen},[],1);
end
end
end
end
end
% Remove processed physDoseFields from total tallies
topasCubesTallies = topasCubesTallies(~physDoseFields);
% Process other fields
if obj.scorer.calcDij
for d = 1:dij.totalNumOfBixels
for j = 1:numel(topasCubesTallies)
% Handle dose to water
if ~isempty(strfind(lower(topasCubesTallies{j}),'dose'))
% loop through possible quantities
for p = 1:length(processedQuantities)