forked from edoerner/ompMC
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.c
5610 lines (4666 loc) · 186 KB
/
main.c
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
/******************************************************************************
ompMC - An hybrid parallel implementation for Monte Carlo particle transport
simulations
Copyright (C) 2018 Edgardo Doerner ([email protected])
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
/******************************************************************************/
/* Parsing program options with getopt long
http://www.gnu.org/software/libc/manual/html_node/Getopt.html#Getopt */
#include <getopt.h>
/* Flag set by ‘--verbose’. */
static int verbose_flag;
/******************************************************************************/
/******************************************************************************/
/* A simple C/C++ class to parse input files and return requested
key value -- https://github.com/bmaynard/iniReader */
#include <string.h>
#include <ctype.h>
/* Parse a configuration file */
void parseInputFile(char *file_name);
/* Copy the value of the selected input item to the char pointer */
int getInputValue(char *dest, char *key);
/* Returns nonzero if line is a string containing only whitespace or is empty */
int lineBlack(char *line);
/* Remove white spaces from string str_untrimmed and saves the results in
str_trimmed. Useful for string input values, such as file names */
void removeSpaces(char* str_trimmed,
const char* str_untrimmed);
struct inputItems {
char key[60];
char value[60];
};
struct inputItems input_items[80]; // i.e. support 80 key,value pairs
int input_idx = 0; // number of key,value pairs
/******************************************************************************/
/******************************************************************************/
/* Geometry definition */
#define MXMED 9 // maximum number of media supported
struct Geom {
int nmed; // number of media in phantom file
char med_names[MXMED][60]; // media names (as found in .pegs4dat file)
int *med_indices; // index of the media in each voxel
double *med_densities; // density of the medium in each voxel
int isize; // number of voxels on each direction
int jsize;
int ksize;
double *xbounds; // boundaries of voxels on each direction
double *ybounds;
double *zbounds;
};
struct Geom geometry;
void initPhantom(void);
void cleanPhantom(void);
/******************************************************************************/
/* Source definition */
#define MXEBIN 200 // number of energy bins of spectrum
#define INVDIM 1000 // number of bins in inverse CDF
struct Source {
int nmed; // number of media in phantom file
int spectrum; // 0 : monoenergetic, 1 : spectrum
int charge; // 0 : photons, -1 : electron, +1 : positron
/* For monoenergetic source */
double energy;
/* For spectrum */
double deltak; // number of elements in inverse CDF
double *cdfinv1; // energy value of bin
double *cdfinv2; // prob. that particle has energy xi
/* Source shape information */
double ssd; // distance of point source to phantom surface
double xinl, xinu; // lower and upper x-bounds of the field on
// phantom surface
double yinl, yinu; // lower and upper y-bounds of the field on
// phantom surface
double xsize, ysize; // x- and y-width of collimated field
int ixinl, ixinu; // lower and upper x-bounds indices of the
// field on phantom surface
int iyinl, iyinu; // lower and upper y-bounds indices of the
// field on phantom surface
};
struct Source source;
void initSource(void);
void cleanSource(void);
/******************************************************************************/
/* Score definition */
struct Score {
double ensrc; // total energy from source
double *endep; // 3D dep. energy matrix per batch
/* The following variables are needed for statistical analysis. Their
values are accumulated across the simulation */
double *accum_endep; // 3D deposited energy matrix
double *accum_endep2; // 3D square deposited energy
};
struct Score score;
void initScore(void);
void cleanScore(void);
void ausgab(double edep);
void accumEndep(void);
void outputResults(char *output_file, int iout, int nhist, int nbatch);
/******************************************************************************/
/* Stack definition */
#define MXSTACK 40 // maximum number of particles on stack
struct Stack {
int np; // stack pointer
int *iq; // particle charge
int *ir; // current region
double *e; // total particle energy
double *x; // particle coordinates
double *y;
double *z;
double *u; // particle direction cosines
double *v;
double *w;
double *dnear; // perpendicular distance to nearest boundary
double *wt; // particle weight
};
struct Stack stack;
void initStack(void);
void initHistory(void);
void cleanStack(void);
/******************************************************************************/
/* Region-by-region data definition */
#define VACUUM -1
struct Region {
int *med;
double *rhof;
double *pcut;
double *ecut;
};
struct Region region;
void initRegions(void);
void cleanRegions(void);
/******************************************************************************/
/* Random number generator definition */
#define NRANDOM 128
struct Random {
int crndm;
int cdrndm;
int cmrndm;
int ixx;
int jxx;
int rng_seed;
int *urndm;
int *rng_array;
double twom24;
};
struct Random rng;
void initRandom(void);
void getRandom(void);
double setRandom(void);
void cleanRandom(void);
/******************************************************************************/
/* Electromagnetic shower simulation */
struct Uphi {
/* This structure holds data saved between uphi() calls */
double A, B, C;
double cosphi, sinphi;
};
void shower(void);
void transferProperties(int npnew, int npold);
void uphi21(struct Uphi *uphi, double costhe, double sinthe);
void uphi32(struct Uphi *uphi, double costhe, double sinthe);
/******************************************************************************/
/* Media definition */
#define RM 0.5109989461 // MeV * c^(-2)
#define MXELEMENT 50 // maximum number of elements in a medium
#define MXEKE 500
struct Element {
/* Attributes of an element in a medium */
char symbol[3];
double z;
double wa;
double pz;
double rhoz;
};
struct Pegs {
/* Data extracted from pegs file */
char names[MXMED][60]; // media names (as found in .pegs4dat file)
int ne[MXMED]; // number of elements in medium
int iunrst[MXMED]; // flag for type of stopping power
int epstfl[MXMED]; // flag for ICRU37 collision stopping powers
int iaprim[MXMED]; // flag for ICRU37 radiative stopping powers
int msge[MXMED];
int mge[MXMED];
int mseke[MXMED];
int meke[MXMED];
int mleke[MXMED];
int mcmfp[MXMED];
int mrange[MXMED];
double rho[MXMED]; // mass density of medium
double rlc[MXMED]; // radiation length for the medium (in cm)
double ae[MXMED], ap[MXMED]; // electron and photon creation threshold E
double ue[MXMED], up[MXMED]; // upper electron and photon energy
double te[MXMED];
double thmoll[MXMED];
double delcm[MXMED];
struct Element elements[MXMED][MXELEMENT]; // element properties
};
struct Pegs pegs_data;
void initMediaData(void);
int readPegsFile(int *media_found);
/******************************************************************************/
/* Photon data definition */
#define MXGE 2000 // gamma mapped energy intervals
struct Photon {
double *ge0, *ge1;
double *gmfp0, *gmfp1;
double *gbr10, *gbr11;
double *gbr20, *gbr21;
double *cohe0, *cohe1;
};
struct Photon photon_data;
void initPhotonData(void);
void readXsecData(char *file, int *ndat,
double **xsec_data0,
double **xsec_data1);
void heap_sort(int n, double *values, int *indices);
double *get_data(int flag, int ne, int *ndat,
double **data0, double **data1,
double *z_sorted, double *pz_sorted,
double ge0, double ge1);
double kn_sigma0(double e);
void cleanPhoton(void);
void listPhoton(void);
/******************************************************************************/
/* Rayleigh data definition */
#define MXRAYFF 100 // Rayleigh atomic form factor
#define RAYCDFSIZE 100 // CDF from Rayleigh from factors squared
#define HC_INVERSE 80.65506856998
#define TWICE_HC2 0.000307444456
struct Rayleigh {
double *xgrid;
double *fcum;
double *b_array;
double *c_array;
double *pe_array;
double *pmax0;
double *pmax1;
int *i_array;
};
struct Rayleigh rayleigh_data;
void initRayleighData(void);
void readFfData(double *xval, double **aff);
void cleanRayleigh(void);
void listRayleigh(void);
/******************************************************************************/
/* Pair data definition */
#define FSC 0.00729735255664 // fine structure constant
struct Pair {
double *dl1;
double *dl2;
double *dl3;
double *dl4;
double *dl5;
double *dl6;
double *bpar0;
double *bpar1;
double *delcm;
double *zbrang;
};
struct Pair pair_data;
void initPairData(void);
double fcoulc(double zi);
double xsif(double zi, double fc);
void cleanPair(void);
void listPair(void);
/******************************************************************************/
/* Photon transport process */
#define SGMFP 1E-05 // smallest gamma mean free path
void photon(void);
void rayleigh(int imed, double eig, double gle, int lgle);
double setPairRejectionFunction(int imed, double xi, double esedei,
double eseder, double tteig);
void pair(int imed);
void compton(void);
void photo(void);
/******************************************************************************/
/* Electron data definition */
#define XIMAX 0.5
#define ESTEPE 0.25
struct Electron {
double *esig0;
double *esig1;
double *psig0;
double *psig1;
double *ededx0;
double *ededx1;
double *pdedx0;
double *pdedx1;
double *ebr10;
double *ebr11;
double *pbr10;
double *pbr11;
double *pbr20;
double *pbr21;
double *tmxs0;
double *tmxs1;
double *blcce0;
double *blcce1;
double *etae_ms0;
double *etae_ms1;
double *etap_ms0;
double *etap_ms1;
double *q1ce_ms0;
double *q1ce_ms1;
double *q1cp_ms0;
double *q1cp_ms1;
double *q2ce_ms0;
double *q2ce_ms1;
double *q2cp_ms0;
double *q2cp_ms1;
double *range_ep;
double *e_array;
double *eke0;
double *eke1;
int *sig_ismonotone;
double *esig_e;
double *psig_e;
double *xcc;
double *blcc;
double *expeke1;
};
struct Electron electron_data;
/* Screened Rutherford MS data */
#define MXL_MS 63
#define MXQ_MS 7
#define MXU_MS 31
#define LAMBMIN_MS 1.0
#define LAMBMAX_MS 1.0E5
#define QMIN_MS 1.0E-3
#define QMAX_MS 0.5
struct Mscat {
double *ums_array;
double *fms_array;
double *wms_array;
int *ims_array;
double dllambi;
double dqmsi;
};
struct Mscat mscat_data;
/* Spin data */
#define MXE_SPIN 15
#define MXE_SPIN1 2*MXE_SPIN+1
#define MXQ_SPIN 15
#define MXU_SPIN 31
struct Spin {
double b2spin_min;
double dbeta2i;
double espml;
double dleneri;
double dqq1i;
double *spin_rej;
};
struct Spin spin_data;
void initMscatData(void);
void cleanElectron(void);
void listElectron(void);
void readRutherfordMscat(int nmed);
void cleanMscat(void);
void listMscat(void);
void initSpinData(int nmed);
void cleanSpin(void);
void listSpin(void);
void setSpline(double *x, double *f, double *a, double *b, double *c,
double *d,int n);
double spline(double s, double *x, double *a, double *b, double *c,
double *d, int n);
/******************************************************************************/
/* Electron interaction processes */
void electron(void);
/******************************************************************************/
/* Auxiliary functions during simulation */
int pwlfInterval(int idx, double lvar, double *coef1, double *coef0);
double pwlfEval(int idx, double lvar, double *coef1, double *coef0);
/******************************************************************************/
/* Geometry functions */
void howfar(int *idisc, int *irnew, double *ustep);
double hownear(void);
/******************************************************************************/
/* ompMC main function */
int main (int argc, char **argv) {
/* Execution time measurement */
clock_t tbegin, tend;
tbegin = clock();
/* Parsing program options */
int c;
char *input_file = NULL;
char *output_file = NULL;
while (1) {
static struct option long_options[] =
{
/* These options set a flag. */
{"verbose", no_argument, &verbose_flag, 1},
{"brief", no_argument, &verbose_flag, 0},
/* These options don’t set a flag.
We distinguish them by their indices. */
{"input", required_argument, 0, 'i'},
{"output", required_argument, 0, 'o'},
{0, 0, 0, 0}
};
/* getopt_long stores the option index here. */
int option_index = 0;
c = getopt_long(argc, argv, "i:o:",
long_options, &option_index);
/* Detect the end of the options. */
if (c == -1)
break;
switch (c) {
case 0:
/* If this option set a flag, do nothing else now. */
if (long_options[option_index].flag != 0)
break;
printf ("option %s", long_options[option_index].name);
if (optarg)
printf (" with arg %s", optarg);
printf ("\n");
break;
case 'i':
input_file = malloc(strlen(optarg) + 1);
strcpy(input_file, optarg);
printf ("option -i with value `%s'\n", input_file);
break;
case 'o':
output_file = malloc(strlen(optarg) + 1);
strcpy(output_file, optarg);
printf ("option -o with value `%s'\n", output_file);
break;
case '?':
/* getopt_long already printed an error message. */
break;
default:
exit(EXIT_FAILURE);
}
}
/* Instead of reporting ‘--verbose’
and ‘--brief’ as they are encountered,
we report the final status resulting from them. */
if (verbose_flag)
puts ("verbose flag is set");
/* Print any remaining command line arguments (not options). */
if (optind < argc)
{
printf ("non-option ARGV-elements: ");
while (optind < argc)
printf ("%s ", argv[optind++]);
putchar ('\n');
}
/* Parse input file and print key,value pairs (test) */
parseInputFile(input_file);
/* Read geometry information from phantom file and initialize geometry */
initPhantom();
/* With number of media and media names initialize the medium data */
initMediaData();
/* Initialize radiation source */
initSource();
/* Initialize data on a region-by-region basis */
initRegions();
/* Preparation of scoring struct */
initScore();
/* Initialize random number generator */
initRandom();
/* Initialize particle stack */
initStack();
/* In verbose mode, list interaction data to output folder */
if (verbose_flag) {
listRayleigh();
listPair();
listPhoton();
listElectron();
listMscat();
listSpin();
}
/* Shower call */
/* Get number of histories and statistical batches */
char buffer[128];
if (getInputValue(buffer, "ncase") != 1) {
printf("Can not find 'ncase' key on input file.\n");
exit(EXIT_FAILURE);
}
int nhist = atoi(buffer);
if (getInputValue(buffer, "nbatch") != 1) {
printf("Can not find 'nbatch' key on input file.\n");
exit(EXIT_FAILURE);
}
int nbatch = atoi(buffer);
if (nhist/nbatch == 0) {
nhist = nbatch;
}
int nperbatch = nhist/nbatch;
nhist = nperbatch*nbatch;
int gridsize = geometry.isize*geometry.jsize*geometry.ksize;
printf("Total number of particle histories: %d\n", nhist);
printf("Number of statistical batches: %d\n", nbatch);
printf("Histories per batch: %d\n", nperbatch);
/* Execution time up to this point */
printf("Execution time up to this point : %8.5f seconds\n",
(double)(clock() - tbegin)/CLOCKS_PER_SEC);
for (int ibatch=0; ibatch<nbatch; ibatch++) {
if (ibatch == 0) {
/* Print header for information during simulation */
printf("%-10s\t%-15s\t%-10s\n", "Batch #", "Elapsed time",
"RNG state");
printf("%-10d\t%-15.5f\t%-5d%-5d\n", ibatch,
(double)(clock() - tbegin)/CLOCKS_PER_SEC, rng.ixx, rng.jxx);
}
else {
/* Print state of current batch */
printf("%-10d\t%-15.5f\t%-5d%-5d\n", ibatch,
(double)(clock() - tbegin)/CLOCKS_PER_SEC, rng.ixx, rng.jxx);
}
for (int ihist=0; ihist<nperbatch; ihist++) {
/* Initialize particle history */
initHistory();
/* Start electromagnetic shower simulation */
shower();
}
/* Accumulate results of current batch for statistical analysis */
accumEndep();
}
/* Print some output and execution time up to this point */
printf("Simulation finished\n");
printf("Execution time up to this point : %8.5f seconds\n",
(double)(clock() - tbegin)/CLOCKS_PER_SEC);
/* Analysis and output of results */
if (verbose_flag) {
/* Sum energy deposition in the phantom */
double etot = 0.0;
for (int irl=1; irl<gridsize+1; irl++) {
etot += score.accum_endep[irl];
}
printf("Fraction of incident energy deposited in the phantom: %5.4f\n",
etot/score.ensrc);
}
int iout = 1; /* i.e. deposit mean dose per particle fluence */
outputResults(output_file, iout, nhist, nbatch);
/* Cleaning */
cleanPhantom();
cleanPhoton();
cleanRayleigh();
cleanPair();
cleanElectron();
cleanMscat();
cleanSpin();
cleanRegions();
cleanRandom();
cleanScore();
cleanStack();
/* Get total execution time */
tend = clock();
printf("Total execution time : %8.5f seconds\n",
(double)(tend - tbegin)/CLOCKS_PER_SEC);
exit (EXIT_SUCCESS);
}
void parseInputFile(char *input_file) {
char buf[120]; // support lines up to 120 characters
/* Make space for the new string */
char *extension = ".inp";
char* file_name = malloc(strlen(input_file) + strlen(extension) + 1);
strcpy(file_name, input_file);
strcat(file_name, extension); /* add the extension */
FILE *fp;
if ((fp = fopen(file_name, "r")) == NULL) {
printf("Unable to open file: %s\n", file_name);
exit(EXIT_FAILURE);
}
while (fgets(buf, sizeof(buf), fp) != NULL) {
/* Jumps lines labeled with #, together with only white
spaced or empty ones. */
if (strstr(buf, "#") || lineBlack(buf)) {
continue;
}
strcpy(input_items[input_idx].key, strtok(buf, "=\r\n"));
strcpy(input_items[input_idx].value, strtok(NULL, "\r\n"));
input_idx++;
}
input_idx--;
fclose(fp);
if(verbose_flag) {
for (int i = 0; i<input_idx; i++) {
printf("key = %s, value = %s\n", input_items[i].key,
input_items[i].value);
}
}
return;
}
int getInputValue(char *dest, char *key) {
/* Check to see if anything got parsed */
if (input_idx == 0) {
return 0;
}
for (int i = 0; i <= input_idx; i++) {
if (strstr(input_items[i].key, key)) {
strcpy(dest, input_items[i].value);
return 1;
}
}
return 0;
}
int lineBlack(char *line) {
char * ch;
int is_blank = 1;
/* Iterate through each character. */
for (ch = line; *ch != '\0'; ++ch) {
if (!isspace(*ch)) {
/* Found a non-whitespace character. */
is_blank = 0;
break;
}
}
return is_blank;
}
void removeSpaces(char* str_trimmed,
const char* str_untrimmed) {
while (*str_untrimmed != '\0') {
if(!isspace(*str_untrimmed)) {
*str_trimmed = *str_untrimmed;
str_trimmed++;
}
str_untrimmed++;
}
*str_trimmed = '\0';
return;
}
void initPhantom() {
/* Get phantom file path from input data */
char phantom_file[128];
char buffer[128];
if (getInputValue(buffer, "phantom file") != 1) {
printf("Can not find 'phantom file' key on input file.\n");
exit(EXIT_FAILURE);
}
removeSpaces(phantom_file, buffer);
/* Open .egsphant file */
FILE *fp;
if ((fp = fopen(phantom_file, "r")) == NULL) {
printf("Unable to open file: %s\n", phantom_file);
exit(EXIT_FAILURE);
}
printf("Path to phantom file : %s\n", phantom_file);
/* Get number of media in the phantom */
fgets(buffer, sizeof(buffer), fp);
geometry.nmed = atoi(buffer);
/* Get media names on phantom file */
for (int i=0; i<geometry.nmed; i++) {
fgets(buffer, sizeof(buffer), fp);
removeSpaces(geometry.med_names[i], buffer);
}
/* Skip next line, it contains dummy input */
fgets(buffer, sizeof(buffer), fp);
/* Read voxel numbers on each direction */
fgets(buffer, sizeof(buffer), fp);
sscanf(buffer, "%d %d %d", &geometry.isize,
&geometry.jsize, &geometry.ksize);
/* Read voxel boundaries on each direction */
geometry.xbounds = malloc((geometry.isize + 1)*sizeof(double));
geometry.ybounds = malloc((geometry.jsize + 1)*sizeof(double));
geometry.zbounds = malloc((geometry.ksize + 1)*sizeof(double));
for (int i=0; i<=geometry.isize; i++) {
fscanf(fp, "%lf", &geometry.xbounds[i]);
}
for (int i=0; i<=geometry.jsize; i++) {
fscanf(fp, "%lf", &geometry.ybounds[i]);
}
for (int i=0; i<=geometry.ksize; i++) {
fscanf(fp, "%lf", &geometry.zbounds[i]);
}
/* Skip the rest of the last line read before */
fgets(buffer, sizeof(buffer), fp);
/* Read media indices */
int irl = 0; // region index
char idx;
geometry.med_indices =
malloc(geometry.isize*geometry.jsize*geometry.ksize*sizeof(int));
for (int k=0; k<geometry.ksize; k++) {
for (int j=0; j<geometry.jsize; j++) {
for (int i=0; i<geometry.isize; i++) {
irl = i + j*geometry.isize + k*geometry.jsize*geometry.isize;
idx = fgetc(fp);
/* Convert digit stored as char to int */
geometry.med_indices[irl] = idx - '0';
}
/* Jump to next line */
fgets(buffer, sizeof(buffer), fp);
}
/* Skip blank line */
fgets(buffer, sizeof(buffer), fp);
}
/* Read media densities */
geometry.med_densities =
malloc(geometry.isize*geometry.jsize*geometry.ksize*sizeof(double));
for (int k=0; k<geometry.ksize; k++) {
for (int j=0; j<geometry.jsize; j++) {
for (int i=0; i<geometry.isize; i++) {
irl = i + j*geometry.isize + k*geometry.jsize*geometry.isize;
fscanf(fp, "%lf", &geometry.med_densities[irl]);
}
}
/* Skip blank line */
fgets(buffer, sizeof(buffer), fp);
}
/* Summary with geometry information */
printf("Number of media in phantom : %d\n", geometry.nmed);
printf("Media names: ");
for (int i=0; i<geometry.nmed; i++) {
printf("%s, ", geometry.med_names[i]);
}
printf("\n");
printf("Number of voxels on each direction (X,Y,Z) : (%d, %d, %d)\n",
geometry.isize, geometry.jsize, geometry.ksize);
printf("Minimum and maximum boundaries on each direction : \n");
printf("\tX (cm) : %lf, %lf\n",
geometry.xbounds[0], geometry.xbounds[geometry.isize]);
printf("\tY (cm) : %lf, %lf\n",
geometry.ybounds[0], geometry.ybounds[geometry.jsize]);
printf("\tZ (cm) : %lf, %lf\n",
geometry.zbounds[0], geometry.zbounds[geometry.ksize]);
/* Close phantom file */
fclose(fp);
return;
}
void cleanPhantom() {
free(geometry.xbounds);
free(geometry.ybounds);
free(geometry.zbounds);
free(geometry.med_indices);
free(geometry.med_densities);
return;
}
void initSource() {
/* Get spectrum file path from input data */
char spectrum_file[128];
char buffer[128];
source.spectrum = 1; /* energy spectrum as default case */
/* First check of spectrum file was given as an input */
if (getInputValue(buffer, "spectrum file") != 1) {
printf("Can not find 'spectrum file' key on input file.\n");
printf("Switch to monoenergetic case.\n");
source.spectrum = 0; /* monoenergetic source */
}
if (source.spectrum) {
removeSpaces(spectrum_file, buffer);
/* Open .source file */
FILE *fp;
if ((fp = fopen(spectrum_file, "r")) == NULL) {
printf("Unable to open file: %s\n", spectrum_file);
exit(EXIT_FAILURE);
}
printf("Path to spectrum file : %s\n", spectrum_file);
/* Read spectrum file title */
fgets(buffer, sizeof(buffer), fp);
printf("Spectrum file title: %s", buffer);
/* Read number of bins and spectrum type */
double enmin; /* lower energy of first bin */
int nensrc; /* number of energy bins in spectrum histogram */
int imode; /* 0 : histogram counts/bin, 1 : counts/MeV*/
fgets(buffer, sizeof(buffer), fp);
sscanf(buffer, "%d %lf %d", &nensrc, &enmin, &imode);
if (nensrc > MXEBIN) {
printf("Number of energy bins = %d is greater than max allowed = "
"%d. Increase MXEBIN macro!\n", nensrc, MXEBIN);
exit(EXIT_FAILURE);
}
/* upper energy of bin i in MeV */
double *ensrcd = malloc(nensrc*sizeof(double));
/* prob. of finding a particle in bin i */
double *srcpdf = malloc(nensrc*sizeof(double));
/* Read spectrum information */
for (int i=0; i<nensrc; i++) {
fgets(buffer, sizeof(buffer), fp);
sscanf(buffer, "%lf %lf", &ensrcd[i], &srcpdf[i]);
}
printf("Have read %d input energy bins from spectrum file.\n", nensrc);
if (imode == 0) {
printf("Counts/bin assumed.\n");
}
else if (imode == 1) {
printf("Counts/MeV assumed.\n");
srcpdf[0] *= (ensrcd[0] - enmin);
for(int i=1; i<nensrc; i++) {
srcpdf[i] *= (ensrcd[i] - ensrcd[i - 1]);
}
}
else {
printf("Invalid mode number in spectrum file.");