-
Notifications
You must be signed in to change notification settings - Fork 30
/
mmc_utils.c
3167 lines (2565 loc) · 107 KB
/
mmc_utils.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
/***************************************************************************//**
** \mainpage Mesh-based Monte Carlo (MMC) - a 3D photon simulator
**
** \author Qianqian Fang <q.fang at neu.edu>
** \copyright Qianqian Fang, 2010-2023
**
** \section sref Reference:
** \li \c (\b Fang2010) Qianqian Fang, <a href="http://www.opticsinfobase.org/abstract.cfm?uri=boe-1-1-165">
** "Mesh-based Monte Carlo Method Using Fast Ray-Tracing
** in Plucker Coordinates,"</a> Biomed. Opt. Express, 1(1) 165-175 (2010).
** \li \c (\b Fang2012) Qianqian Fang and David R. Kaeli,
** <a href="https://www.osapublishing.org/boe/abstract.cfm?uri=boe-3-12-3223">
** "Accelerating mesh-based Monte Carlo method on modern CPU architectures,"</a>
** Biomed. Opt. Express 3(12), 3223-3230 (2012)
** \li \c (\b Yao2016) Ruoyang Yao, Xavier Intes, and Qianqian Fang,
** <a href="https://www.osapublishing.org/boe/abstract.cfm?uri=boe-7-1-171">
** "Generalized mesh-based Monte Carlo for wide-field illumination and detection
** via mesh retessellation,"</a> Biomed. Optics Express, 7(1), 171-184 (2016)
** \li \c (\b Fang2019) Qianqian Fang and Shijie Yan,
** <a href="http://dx.doi.org/10.1117/1.JBO.24.11.115002">
** "Graphics processing unit-accelerated mesh-based Monte Carlo photon transport
** simulations,"</a> J. of Biomedical Optics, 24(11), 115002 (2019)
** \li \c (\b Yuan2021) Yaoshen Yuan, Shijie Yan, and Qianqian Fang,
** <a href="https://www.osapublishing.org/boe/fulltext.cfm?uri=boe-12-1-147">
** "Light transport modeling in highly complex tissues using the implicit
** mesh-based Monte Carlo algorithm,"</a> Biomed. Optics Express, 12(1) 147-161 (2021)
**
** \section slicense License
** GPL v3, see LICENSE.txt for details
*******************************************************************************/
/***************************************************************************//**
\file mmc_utils.c
\brief MC simulation settings and command line option processing unit
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <time.h>
#ifdef _POSIX_SOURCE
#include <sys/ioctl.h>
#endif
#include "mmc_utils.h"
#include "mmc_const.h"
#include "mmc_bench.h"
#include "zmat/zmatlib.h"
#include "ubj/ubj.h"
#if defined(_WIN32) && defined(USE_OS_TIMER) && !defined(MCX_CONTAINER)
#include "mmc_tictoc.h"
#endif
#ifdef MCX_EMBED_CL
#include "mmc_core.clh"
#endif
#include "nifti1.h"
/**
* Macro to load JSON keys
*/
#define FIND_JSON_KEY(id,idfull,parent,fallback,val) \
((tmp=cJSON_GetObjectItem(parent,id))==0 ? \
((tmp=cJSON_GetObjectItem(root,idfull))==0 ? fallback : tmp->val) \
: tmp->val)
/**
* Macro to load JSON object
*/
#define FIND_JSON_OBJ(id,idfull,parent) \
((tmp=cJSON_GetObjectItem(parent,id))==0 ? \
((tmp=cJSON_GetObjectItem(root,idfull))==0 ? NULL : tmp) \
: tmp)
#define UBJ_WRITE_KEY(ctx, key, type, val) {ubjw_write_key( (ctx), (key)); ubjw_write_##type((ctx), (val));}
#define UBJ_WRITE_ARRAY(ctx, type, nlen, val) {ubjw_write_buffer( (ctx), (uint8_t*)(val), JDB_##type, (nlen));}
#define ubjw_write_single ubjw_write_float32
#define ubjw_write_double ubjw_write_float64
#define ubjw_write_uint16 ubjw_write_int16
#define ubjw_write_uint32 ubjw_write_int32
#define ubjw_write_uint64 ubjw_write_int64
/**
* Macro to include unit name and line number in the error message
*/
#define MMC_ASSERT(id) mcx_assert(id,__FILE__,__LINE__)
#define MIN_HEADER_SIZE 348 /**< Analyze header size */
#define NII_HEADER_SIZE 352 /**< NIFTI header size */
#define GL_RGBA32F 0x8814
/**
* Short command line options
* If a short command line option is '-' that means it only has long/verbose option.
* Array terminates with '\0'.
*/
const char shortopt[] = {'h', 'E', 'f', 'n', 'A', 't', 'T', 's', 'a', 'g', 'b', 'D', 'G',
'd', 'r', 'S', 'e', 'U', 'R', 'l', 'L', 'I', '-', 'u', 'C', 'M',
'i', 'V', 'O', '-', 'F', 'q', 'x', 'P', 'k', 'v', 'm', '-', '-',
'J', 'o', 'H', '-', 'W', 'X', '-', 'c', '-', '-', 'Z', '\0'
};
/**
* Long command line options
* The length of this array must match the length of shortopt[], terminates with ""
*/
const char* fullopt[] = {"--help", "--seed", "--input", "--photon", "--autopilot",
"--thread", "--blocksize", "--session", "--array",
"--gategroup", "--reflect", "--debug", "--gpu", "--savedet",
"--repeat", "--save2pt", "--minenergy",
"--normalize", "--skipradius", "--log", "--listgpu",
"--printgpu", "--root", "--unitinmm", "--basisorder",
"--method", "--interactive", "--specular", "--outputtype",
"--momentum", "--outputformat", "--saveseed", "--saveexit",
"--replaydet", "--voidtime", "--version", "--mc", "--atomic",
"--debugphoton", "--compileropt", "--optlevel", "--maxdetphoton",
"--buffer", "--workload", "--saveref", "--gridsize", "--compute",
"--bench", "--dumpjson", "--zip", ""
};
extern char pathsep;
/**
* Debug flags
* R: debug random number generator
* M: record photon movement and trajectory
* P: show progress bar
*/
const char debugflag[] = {'M', 'C', 'B', 'W', 'D', 'I', 'O', 'X', 'A', 'T', 'R', 'P', 'E', '\0'};
/**
* Selecting mesh-based ray-tracing algorithm:
* p: Plucker-based ray-tracer, see Fang2010
* h: Havel-based SSE4 ray-tracer, see Fang2012
* b: Badouel ray-tracing algorithm, see Fang2011
* s: branch-less Badouel SSE4 ray-tracer, see Fang2011
* g: grid-output using dual-mesh MMC
*/
const char raytracing[] = {'p', 'h', 'b', 's', 'g', '\0'};
/**
* Output data types
* x: fluence rate
* f: fluence
* e: energy deposition
* j: jacobian for mua
* p: scattering counts for computing Jacobians for mus
*/
const char outputtype[] = {'x', 'f', 'e', 'j', 'l', 'p', '\0'};
/**
* Output file format
* mc2: binary mc2 format to store fluence volume data
* nii: output fluence in nii format
* hdr: output volume in Analyze hdr/img format
* ubj: output volume in unversal binary json format (not implemented)
*/
const char* outputformat[] = {"ascii", "bin", "nii", "hdr", "mc2", "tx3", "jnii", "bnii", ""};
/**
* Source type specifier
* User can specify the source type using a string
*/
const char* srctypeid[] = {"pencil", "isotropic", "cone", "gaussian", "planar",
"pattern", "fourier", "arcsine", "disk", "fourierx", "fourierx2d", "zgaussian", "line", "slit", ""
};
/**
* Flag to decide if parameter has been initialized over command line
*/
char flagset[256] = {'\0'};
/**
* Flag for JData compression methods
*/
const char* zipformat[] = {"zlib", "gzip", "base64", "lzip", "lzma", "lz4", "lz4hc", ""};
/**
* Flag to decide which platform to run mmc
*/
const char* computebackend[] = {"sse", "opencl", "cuda", ""};
/**
* @brief Initializing the simulation configuration with default values
*
* Constructor of the simulation configuration, initializing all field to default values
*/
void mcx_initcfg(mcconfig* cfg) {
cfg->medianum = 0;
cfg->srcnum = 1;
cfg->detnum = 0;
cfg->e0 = 0;
cfg->dim.x = 0;
cfg->dim.y = 0;
cfg->dim.z = 0;
cfg->steps.x = 1.f;
cfg->steps.y = 1.f;
cfg->steps.z = 1.f;
cfg->nblocksize = 64;
cfg->nphoton = 0;
cfg->nthread = 1024 * 8;
cfg->seed = 0x623F9A9E;
cfg->isrowmajor = 0; /* not needed */
cfg->maxgate = 1;
cfg->implicit = 0;
cfg->isreflect = 1;
cfg->isref3 = 1;
cfg->isnormalized = 1;
cfg->issavedet = 0;
cfg->respin = 1;
cfg->issave2pt = 1;
cfg->isgpuinfo = 0;
cfg->basisorder = 1;
cfg->compute = cbOpenCL;
cfg->isdumpjson = 0;
cfg->zipid = zmZlib;
memset(cfg->jsonfile, 0, MAX_PATH_LENGTH);
cfg->shapedata = NULL;
#if defined(USE_OPENCL) || defined(USE_CUDA)
cfg->method = rtBLBadouelGrid;
#else
#ifndef MMC_USE_SSE
cfg->method = rtPlucker;
#else
cfg->method = rtHavel;
#endif
#endif
cfg->prop = NULL;
cfg->detpos = NULL;
cfg->vol = NULL;
cfg->session[0] = '\0';
cfg->meshtag[0] = '\0';
cfg->minenergy = 1e-6f;
cfg->flog = stdout;
cfg->sradius = 0.f;
cfg->rootpath[0] = '\0';
cfg->seedfile[0] = '\0';
cfg->debuglevel = 0;
cfg->minstep = 1.f;
cfg->roulettesize = 10.f;
cfg->nout = 1.f;
cfg->unitinmm = 1.f;
cfg->srctype = 0;
cfg->isspecular = 0;
cfg->issaveref = 0;
cfg->outputtype = otFlux;
cfg->outputformat = ofASCII;
cfg->ismomentum = 0;
cfg->issaveseed = 0;
cfg->issaveexit = 0;
cfg->photonseed = NULL;
cfg->replaydet = 0;
cfg->replayweight = NULL;
cfg->replaytime = NULL;
cfg->isextdet = 0;
cfg->srcdir.w = 0.f;
cfg->isatomic = 1;
cfg->debugphoton = -1;
cfg->savedetflag = 0x47;
cfg->mediabyte = 1;
cfg->tstart = 0.f;
cfg->tstep = 0.f;
cfg->tend = 0.f;
cfg->mcmethod = mmMCX;
memset(&(cfg->his), 0, sizeof(history));
cfg->his.version = 1;
cfg->his.unitinmm = 1.f;
cfg->his.normalizer = 1.f;
cfg->his.respin = 1;
cfg->his.srcnum = cfg->srcnum;
cfg->his.savedetflag = 0;
memcpy(cfg->his.magic, "MCXH", 4);
memset(&(cfg->srcpos), 0, sizeof(float3));
memset(&(cfg->srcdir), 0, sizeof(float3));
memset(&(cfg->bary0), 0, sizeof(float4));
memset(&(cfg->srcparam1), 0, sizeof(float4));
memset(&(cfg->srcparam2), 0, sizeof(float4));
cfg->srcpattern = NULL;
cfg->voidtime = 1;
memset(cfg->checkpt, 0, sizeof(unsigned int)*MAX_CHECKPOINT);
memset(&(cfg->detparam1), 0, sizeof(float4));
memset(&(cfg->detparam2), 0, sizeof(float4));
cfg->detpattern = NULL;
cfg->optlevel = 3;
memset(cfg->deviceid, 0, MAX_DEVICE);
memset(cfg->workload, 0, MAX_DEVICE * sizeof(float));
cfg->deviceid[0] = '1'; /*use the first GPU device by default*/
memset(cfg->compileropt, 0, MAX_PATH_LENGTH);
memset(cfg->kernelfile, 0, MAX_SESSION_LENGTH);
cfg->maxdetphoton = 1000000;
cfg->exportfield = NULL;
cfg->exportdetected = NULL;
cfg->exportseed = NULL;
cfg->detectedcount = 0;
cfg->energytot = 0.f;
cfg->energyabs = 0.f;
cfg->energyesc = 0.f;
cfg->runtime = 0;
cfg->autopilot = 1;
cfg->nbuffer = 0;
cfg->gpuid = 0;
#ifdef MCX_EMBED_CL
cfg->clsource = (char*)mmc_core_cl;
#else
cfg->clsource = NULL;
#endif
#ifdef MCX_CONTAINER
cfg->parentid = mpMATLAB;
#else
cfg->parentid = mpStandalone;
#endif
}
/**
* @brief Clearing the simulation configuration data structure
*
* Destructor of the simulation configuration, delete all dynamically allocated members
*/
void mcx_clearcfg(mcconfig* cfg) {
if (cfg->medianum) {
free(cfg->prop);
}
if (cfg->detnum) {
free(cfg->detpos);
}
if (cfg->vol) {
free(cfg->vol);
}
if (cfg->srcpattern) {
free(cfg->srcpattern);
}
if (cfg->detpattern) {
free(cfg->detpattern);
}
if (cfg->photonseed) {
free(cfg->photonseed);
}
if (cfg->replayweight) {
free(cfg->replayweight);
}
if (cfg->replaytime) {
free(cfg->replaytime);
}
if (cfg->exportseed) {
free(cfg->exportseed);
}
if (cfg->exportdetected) {
free(cfg->exportdetected);
}
if (cfg->flog && cfg->flog != stdout && cfg->flog != stderr) {
fclose(cfg->flog);
}
if (cfg->shapedata) {
free(cfg->shapedata);
}
#ifndef MCX_EMBED_CL
if (cfg->clsource && cfg->clsource != (char*)mmc_core_cl) {
free(cfg->clsource);
}
#endif
mcx_initcfg(cfg);
}
/**
* @brief Reset and clear the GPU information data structure
*
* Clearing the GPU information data structure
*/
void mcx_cleargpuinfo(GPUInfo** gpuinfo) {
if (*gpuinfo) {
free(*gpuinfo);
*gpuinfo = NULL;
}
}
#ifndef MCX_CONTAINER
/**
* @brief Save volumetric output (fluence etc) to an Nifty format binary file
*
* @param[in] dat: volumetric data to be saved
* @param[in] len: total byte length of the data to be saved
* @param[in] name: output file name (will append '.nii')
* @param[in] type32bit: type of the data, only support 32bit per record
* @param[in] outputformatid: decide if save as nii or analyze format
* @param[in] cfg: simulation configuration
*/
void mcx_savenii(OutputType* dat, size_t len, char* name, int type32bit, int outputformatid, mcconfig* cfg) {
FILE* fp;
char fname[MAX_PATH_LENGTH] = {'\0'};
nifti_1_header hdr;
nifti1_extender pad = {{0, 0, 0, 0}};
OutputType* logval = dat;
size_t i;
memset((void*)&hdr, 0, sizeof(hdr));
hdr.sizeof_hdr = MIN_HEADER_SIZE;
hdr.dim[0] = 4;
hdr.dim[1] = cfg->dim.x;
hdr.dim[2] = cfg->dim.y;
hdr.dim[3] = cfg->dim.z;
hdr.dim[4] = len / (cfg->dim.x * cfg->dim.y * cfg->dim.z);
hdr.datatype = type32bit;
hdr.bitpix = (type32bit == NIFTI_TYPE_FLOAT64) ? 64 : 32;
hdr.pixdim[1] = cfg->steps.x;
hdr.pixdim[2] = cfg->steps.y;
hdr.pixdim[3] = cfg->steps.z;
hdr.intent_code = NIFTI_INTENT_NONE;
if (type32bit == NIFTI_TYPE_FLOAT32 || type32bit == NIFTI_TYPE_FLOAT64) {
hdr.pixdim[4] = cfg->tstep * 1e6f;
} else {
short* mask = (short*)logval;
for (i = 0; i < len; i++) {
mask[(i << 1)] = (((unsigned int*)dat)[i] & MED_MASK);
mask[(i << 1) + 1] = (((unsigned int*)dat)[i] & DET_MASK) >> 31;
}
hdr.datatype = NIFTI_TYPE_UINT16;
hdr.bitpix = 16;
hdr.dim[1] = 2;
hdr.dim[2] = cfg->dim.x;
hdr.dim[3] = cfg->dim.y;
hdr.dim[4] = cfg->dim.z;
hdr.pixdim[4] = cfg->unitinmm;
hdr.pixdim[1] = 1.f;
}
if (outputformatid == ofNifti) {
strncpy(hdr.magic, "n+1\0", 4);
hdr.vox_offset = (float) NII_HEADER_SIZE;
} else {
strncpy(hdr.magic, "ni1\0", 4);
hdr.vox_offset = (float)0;
}
hdr.scl_slope = 0.f;
hdr.xyzt_units = NIFTI_UNITS_MM | NIFTI_UNITS_USEC;
sprintf(fname, "%s.%s", name, outputformat[outputformatid]);
if (( fp = fopen(fname, "wb")) == NULL) {
mcx_error(-9, "Error opening header file for write", __FILE__, __LINE__);
}
if (fwrite(&hdr, MIN_HEADER_SIZE, 1, fp) != 1) {
mcx_error(-9, "Error writing header file", __FILE__, __LINE__);
}
if (outputformatid == ofNifti) {
if (fwrite(&pad, 4, 1, fp) != 1) {
mcx_error(-9, "Error writing header file extension pad", __FILE__, __LINE__);
}
if (fwrite(logval, (size_t)(hdr.bitpix >> 3), hdr.dim[1]*hdr.dim[2]*hdr.dim[3]*hdr.dim[4], fp) !=
hdr.dim[1]*hdr.dim[2]*hdr.dim[3]*hdr.dim[4]) {
mcx_error(-9, "Error writing data to file", __FILE__, __LINE__);
}
fclose(fp);
} else if (outputformatid == ofAnalyze) {
fclose(fp); /* close .hdr file */
sprintf(fname, "%s.img", name);
fp = fopen(fname, "wb");
if (fp == NULL) {
mcx_error(-9, "Error opening img file for write", __FILE__, __LINE__);
}
if (fwrite(logval, (size_t)(hdr.bitpix >> 3), hdr.dim[1]*hdr.dim[2]*hdr.dim[3]*hdr.dim[4], fp) !=
hdr.dim[1]*hdr.dim[2]*hdr.dim[3]*hdr.dim[4]) {
mcx_error(-9, "Error writing img file", __FILE__, __LINE__);
}
fclose(fp);
} else {
mcx_error(-9, "Output format is not supported", __FILE__, __LINE__);
}
}
/**
* @brief Save volumetric output (fluence etc) to a binary JNIfTI/JSON/JData format file
*
* @param[in] dat: volumetric data to be saved
* @param[in] len: total byte length of the data to be saved
* @param[in] name: output file name (will append '.nii')
* @param[in] type32bit: type of the data, only support 32bit per record
* @param[in] outputformatid: decide if save as nii or analyze format
* @param[in] cfg: simulation configuration
*/
void mcx_savebnii(OutputType* vol, int ndim, uint* dims, float* voxelsize, char* name, int isfloat, mcconfig* cfg) {
FILE* fp;
char fname[MAX_FULL_PATH] = {'\0'};
int affine[] = {0, 0, 1, 0, 0, 0};
size_t datalen = sizeof(int), outputlen = 0;
int i;
ubjw_context_t* root = NULL;
uchar* jsonstr = NULL;
for (i = 0; i < ndim; i++) {
datalen *= dims[i];
}
jsonstr = malloc(datalen << 1);
root = ubjw_open_memory(jsonstr, jsonstr + (datalen << 1));
ubjw_begin_object(root, UBJ_MIXED, 0);
/* the "_DataInfo_" section */
ubjw_write_key(root, "_DataInfo_");
ubjw_begin_object(root, UBJ_MIXED, 0);
UBJ_WRITE_KEY(root, "JNIFTIVersion", string, "0.5");
UBJ_WRITE_KEY(root, "Comment", string, "Created by MCX (http://mcx.space)");
UBJ_WRITE_KEY(root, "AnnotationFormat", string, "https://neurojson.org/jnifti/draft1");
UBJ_WRITE_KEY(root, "SerialFormat", string, "https://neurojson.org/bjdata/draft2");
ubjw_write_key(root, "Parser");
ubjw_begin_object(root, UBJ_MIXED, 0);
ubjw_write_key(root, "Python");
ubjw_begin_array(root, UBJ_STRING, 2);
ubjw_write_string(root, "https://pypi.org/project/jdata");
ubjw_write_string(root, "https://pypi.org/project/bjdata");
ubjw_end(root);
ubjw_write_key(root, "MATLAB");
ubjw_begin_array(root, UBJ_STRING, 2);
ubjw_write_string(root, "https://github.com/NeuroJSON/jnifty");
ubjw_write_string(root, "https://github.com/NeuroJSON/jsonlab");
ubjw_end(root);
ubjw_write_key(root, "JavaScript");
ubjw_begin_array(root, UBJ_STRING, 2);
ubjw_write_string(root, "https://www.npmjs.com/package/jda");
ubjw_write_string(root, "https://www.npmjs.com/package/bjd");
ubjw_end(root);
UBJ_WRITE_KEY(root, "CPP", string, "https://github.com/NeuroJSON/json");
UBJ_WRITE_KEY(root, "C", string, "https://github.com/NeuroJSON/ubj");
ubjw_end(root);
ubjw_end(root);
/* the "NIFTIHeader" section */
ubjw_write_key(root, "NIFTIHeader");
ubjw_begin_object(root, UBJ_MIXED, 0);
UBJ_WRITE_KEY(root, "NIIHeaderSize", uint16, 348);
ubjw_write_key(root, "Dim");
UBJ_WRITE_ARRAY(root, uint32, ndim, dims);
UBJ_WRITE_KEY(root, "Param1", uint8, 0);
UBJ_WRITE_KEY(root, "Param2", uint8, 0);
UBJ_WRITE_KEY(root, "Param3", uint8, 0);
UBJ_WRITE_KEY(root, "Intent", uint8, 0);
UBJ_WRITE_KEY(root, "DataType", string, ((isfloat ? "single" : "uint32")));
UBJ_WRITE_KEY(root, "BitDepth", uint8, 32);
UBJ_WRITE_KEY(root, "FirstSliceID", uint8, 0);
ubjw_write_key(root, "VoxelSize");
UBJ_WRITE_ARRAY(root, single, ndim, voxelsize);
ubjw_write_key(root, "Orientation");
ubjw_begin_object(root, UBJ_MIXED, 3);
UBJ_WRITE_KEY(root, "x", char, 'r');
UBJ_WRITE_KEY(root, "y", char, 'a');
UBJ_WRITE_KEY(root, "z", char, 's');
ubjw_end(root);
UBJ_WRITE_KEY(root, "ScaleSlope", uint8, 1);
UBJ_WRITE_KEY(root, "ScaleOffset", uint8, 1);
UBJ_WRITE_KEY(root, "LastSliceID", uint32, cfg->maxgate);
UBJ_WRITE_KEY(root, "SliceType", uint8, 1);
ubjw_write_key(root, "Unit");
ubjw_begin_object(root, UBJ_MIXED, 2);
UBJ_WRITE_KEY(root, "L", string, "mm");
UBJ_WRITE_KEY(root, "T", string, "s");
ubjw_end(root);
UBJ_WRITE_KEY(root, "MaxIntensity", uint32, 1);
UBJ_WRITE_KEY(root, "MinIntensity", uint32, 0);
UBJ_WRITE_KEY(root, "SliceTime", uint8, 0);
UBJ_WRITE_KEY(root, "TimeOffset", uint8, 0);
if (cfg->outputtype >= 0) {
const char* typestr[] = {"MMC volumetric output: Fluence rate (W/mm^2)", "MMC volumetric output: Fluence (J/mm^2)",
"MMC volumetric output: Energy density (J/mm^3)", "MMC volumetric output: Jacobian for mua (J/mm)", "MMC volumetric output: Scattering count",
"MMC volumetric output: Partial momentum transfer"
};
UBJ_WRITE_KEY(root, "Description", string, typestr[(int)cfg->outputtype]);
} else {
UBJ_WRITE_KEY(root, "Description", string, "MMC volumetric output");
}
UBJ_WRITE_KEY(root, "AuxFile", string, "");
UBJ_WRITE_KEY(root, "QForm", uint8, 0);
UBJ_WRITE_KEY(root, "SForm", uint8, 1);
ubjw_write_key(root, "Quatern");
ubjw_begin_object(root, UBJ_MIXED, 3);
UBJ_WRITE_KEY(root, "b", uint8, 0);
UBJ_WRITE_KEY(root, "c", uint8, 0);
UBJ_WRITE_KEY(root, "d", uint8, 0);
ubjw_end(root);
ubjw_write_key(root, "QuaternOffset");
ubjw_begin_object(root, UBJ_MIXED, 3);
UBJ_WRITE_KEY(root, "x", uint8, 0);
UBJ_WRITE_KEY(root, "y", uint8, 0);
UBJ_WRITE_KEY(root, "z", uint8, 0);
ubjw_end(root);
ubjw_write_key(root, "Affine");
ubjw_begin_array(root, UBJ_MIXED, 0);
UBJ_WRITE_ARRAY(root, int32, 4, affine + 2);
UBJ_WRITE_ARRAY(root, int32, 4, affine + 1);
UBJ_WRITE_ARRAY(root, int32, 4, affine);
ubjw_end(root);
UBJ_WRITE_KEY(root, "Name", string, cfg->session);
UBJ_WRITE_KEY(root, "NIIFormat", string, "JNIfTI v0.4");
ubjw_end(root);
ubjw_write_key(root, "NIFTIData");
/* the "NIFTIData" section stores volumetric data */
ubjw_begin_object(root, UBJ_MIXED, 0);
if (mcx_jdataencode(vol, ndim, dims, (isfloat ? "single" : "uint32"), 4, cfg->zipid, root, 1, cfg)) {
MMC_ERROR(-1, "error when converting to JSON");
}
ubjw_end(root);
ubjw_end(root);
/* now save JSON to file */
outputlen = ubjw_close_context(root);
if (jsonstr == NULL) {
MMC_ERROR(-1, "error when converting to JSON");
}
sprintf(fname, "%s.bnii", name);
fp = fopen(fname, "wb");
if (fp == NULL) {
MMC_ERROR(-1, "error opening file to write");
}
fwrite(jsonstr, outputlen, 1, fp);
fclose(fp);
if (jsonstr) {
free(jsonstr);
}
}
/**
* @brief Save volumetric output (fluence etc) to a JNIfTI/JSON/JData format file
*
* @param[in] dat: volumetric data to be saved
* @param[in] len: total byte length of the data to be saved
* @param[in] name: output file name (will append '.nii')
* @param[in] type32bit: type of the data, only support 32bit per record
* @param[in] outputformatid: decide if save as nii or analyze format
* @param[in] cfg: simulation configuration
*/
void mcx_savejnii(OutputType* vol, int ndim, uint* dims, float* voxelsize, char* name, int isfloat, mcconfig* cfg) {
FILE* fp;
char fname[MAX_FULL_PATH] = {'\0'};
int affine[] = {0, 0, 1, 0, 0, 0};
const char* libpy[] = {"https://pypi.org/project/jdata", "https://pypi.org/project/bjdata"};
const char* libmat[] = {"https://github.com/NeuroJSON/jnifty", "https://github.com/NeuroJSON/jsonlab"};
const char* libjs[] = {"https://www.npmjs.com/package/jda", "https://www.npmjs.com/package/bjd"};
const char* libc[] = {"https://github.com/DaveGamble/cJSON", "https://github.com/NeuroJSON/ubj"};
cJSON* root = NULL, *hdr = NULL, *dat = NULL, *sub = NULL, *info = NULL, *parser = NULL;
char* jsonstr = NULL;
root = cJSON_CreateObject();
/* the "_DataInfo_" section */
cJSON_AddItemToObject(root, "_DataInfo_", info = cJSON_CreateObject());
cJSON_AddStringToObject(info, "JNIFTIVersion", "0.5");
cJSON_AddStringToObject(info, "Comment", "Created by MCX (http://mcx.space)");
cJSON_AddStringToObject(info, "AnnotationFormat", "https://neurojson.org/jnifti/draft1");
cJSON_AddStringToObject(info, "SerialFormat", "https://json.org");
cJSON_AddItemToObject(info, "Parser", parser = cJSON_CreateObject());
cJSON_AddItemToObject(parser, "Python", cJSON_CreateStringArray(libpy, 2));
cJSON_AddItemToObject(parser, "MATLAB", cJSON_CreateStringArray(libmat, 2));
cJSON_AddItemToObject(parser, "JavaScript", cJSON_CreateStringArray(libjs, 2));
cJSON_AddStringToObject(parser, "CPP", "https://github.com/NeuroJSON/json");
cJSON_AddItemToObject(parser, "C", cJSON_CreateStringArray(libc, 2));
/* the "NIFTIHeader" section */
cJSON_AddItemToObject(root, "NIFTIHeader", hdr = cJSON_CreateObject());
cJSON_AddNumberToObject(hdr, "NIIHeaderSize", 348);
cJSON_AddItemToObject(hdr, "Dim", cJSON_CreateIntArray((int*)dims, ndim));
cJSON_AddNumberToObject(hdr, "Param1", 0);
cJSON_AddNumberToObject(hdr, "Param2", 0);
cJSON_AddNumberToObject(hdr, "Param3", 0);
cJSON_AddNumberToObject(hdr, "Intent", 0);
cJSON_AddStringToObject(hdr, "DataType", (isfloat ? "single" : "uint32"));
cJSON_AddNumberToObject(hdr, "BitDepth", 32);
cJSON_AddNumberToObject(hdr, "FirstSliceID", 0);
cJSON_AddItemToObject(hdr, "VoxelSize", cJSON_CreateFloatArray(voxelsize, ndim));
cJSON_AddItemToObject(hdr, "Orientation", sub = cJSON_CreateObject());
cJSON_AddStringToObject(sub, "x", "r");
cJSON_AddStringToObject(sub, "y", "a");
cJSON_AddStringToObject(sub, "z", "s");
cJSON_AddNumberToObject(hdr, "ScaleSlope", 1);
cJSON_AddNumberToObject(hdr, "ScaleOffset", 0);
cJSON_AddNumberToObject(hdr, "LastSliceID", cfg->maxgate);
cJSON_AddNumberToObject(hdr, "SliceType", 1);
cJSON_AddItemToObject(hdr, "Unit", sub = cJSON_CreateObject());
cJSON_AddStringToObject(sub, "L", "mm");
cJSON_AddStringToObject(sub, "T", "s");
cJSON_AddNumberToObject(hdr, "MaxIntensity", 1);
cJSON_AddNumberToObject(hdr, "MinIntensity", 0);
cJSON_AddNumberToObject(hdr, "SliceTime", 0);
cJSON_AddNumberToObject(hdr, "TimeOffset", 0);
if (cfg->outputtype >= 0) {
const char* typestr[] = {"MMC volumetric output: Fluence rate (W/mm^2)", "MMC volumetric output: Fluence (J/mm^2)",
"MMC volumetric output: Energy density (J/mm^3)", "MMC volumetric output: Jacobian for mua (J/mm)", "MMC volumetric output: Scattering count",
"MMC volumetric output: Partial momentum transfer"
};
cJSON_AddStringToObject(hdr, "Description", typestr[(int)cfg->outputtype]);
} else {
cJSON_AddStringToObject(hdr, "Description", "MMC volumetric output");
}
cJSON_AddStringToObject(hdr, "AuxFile", "");
cJSON_AddNumberToObject(hdr, "QForm", 0);
cJSON_AddNumberToObject(hdr, "SForm", 1);
cJSON_AddItemToObject(hdr, "Quatern", sub = cJSON_CreateObject());
cJSON_AddNumberToObject(sub, "b", 0);
cJSON_AddNumberToObject(sub, "c", 0);
cJSON_AddNumberToObject(sub, "d", 0);
cJSON_AddItemToObject(hdr, "QuaternOffset", sub = cJSON_CreateObject());
cJSON_AddNumberToObject(sub, "x", 0);
cJSON_AddNumberToObject(sub, "y", 0);
cJSON_AddNumberToObject(sub, "z", 0);
cJSON_AddItemToObject(hdr, "Affine", sub = cJSON_CreateArray());
cJSON_AddItemToArray(sub, cJSON_CreateIntArray(affine + 2, 4));
cJSON_AddItemToArray(sub, cJSON_CreateIntArray(affine + 1, 4));
cJSON_AddItemToArray(sub, cJSON_CreateIntArray(affine, 4));
cJSON_AddStringToObject(hdr, "Name", cfg->session);
cJSON_AddStringToObject(hdr, "NIIFormat", "JNIfTI v0.4");
/* the "NIFTIData" section stores volumetric data */
cJSON_AddItemToObject(root, "NIFTIData", dat = cJSON_CreateObject());
if (mcx_jdataencode(vol, ndim, dims, (isfloat ? "single" : "uint32"), 4, cfg->zipid, dat, 0, cfg)) {
MMC_ERROR(-1, "error when converting to JSON");
}
/* now save JSON to file */
jsonstr = cJSON_Print(root);
if (jsonstr == NULL) {
MMC_ERROR(-1, "error when converting to JSON");
}
sprintf(fname, "%s.jnii", name);
fp = fopen(fname, "wb");
if (fp == NULL) {
MMC_ERROR(-1, "error opening file to write");
}
fwrite(jsonstr, strlen(jsonstr), 1, fp);
fclose(fp);
if (jsonstr) {
free(jsonstr);
}
if (root) {
cJSON_Delete(root);
}
}
/**
* @brief Save volumetric output (fluence etc) to mc2 format binary file
*
* @param[in] dat: volumetric data to be saved
* @param[in] len: total byte length of the data to be saved
* @param[in] cfg: simulation configuration
*/
void mcx_savedata(OutputType* dat, size_t len, mcconfig* cfg, int isref) {
FILE* fp;
char name[MAX_FULL_PATH];
char fname[MAX_FULL_PATH + 20];
unsigned int glformat = GL_RGBA32F;
if (cfg->rootpath[0])
#ifdef WIN32
sprintf(name, "%s\\%s", cfg->rootpath, cfg->session);
#else
sprintf(name, "%s/%s", cfg->rootpath, cfg->session);
#endif
else {
sprintf(name, "%s", cfg->session);
}
if (!isref && (cfg->outputformat == ofNifti || cfg->outputformat == ofAnalyze)) {
mcx_savenii(dat, len, name, NIFTI_TYPE_FLOAT64, cfg->outputformat, cfg);
return;
} else if (cfg->outputformat == ofJNifti || cfg->outputformat == ofBJNifti) {
int d1 = (cfg->maxgate == 1);
if (cfg->seed == SEED_FROM_FILE && cfg->replaydet == -1 && (cfg->detnum > 1 || cfg->srcnum > 1)) {
uint dims[5] = {cfg->detnum* cfg->srcnum, cfg->maxgate, cfg->dim.z, cfg->dim.y, cfg->dim.x};
float voxelsize[] = {1, cfg->tstep, cfg->steps.z, cfg->steps.y, cfg->steps.x};
if (cfg->outputformat == ofJNifti) {
mcx_savejnii(dat, 5, dims, voxelsize, name, 1, cfg);
} else {
mcx_savebnii(dat, 5, dims, voxelsize, name, 1, cfg);
}
} else {
uint dims[] = {cfg->dim.x, cfg->dim.y, cfg->dim.z, cfg->maxgate};
float voxelsize[] = {cfg->steps.x, cfg->steps.y, cfg->steps.z, cfg->tstep};
size_t datalen = cfg->dim.x * cfg->dim.y * cfg->dim.z * cfg->maxgate;
uint* buf = (uint*)malloc(datalen * sizeof(float));
memcpy(buf, dat, datalen * sizeof(float));
if (d1) {
mcx_convertcol2row(&buf, (uint3*)dims);
} else {
mcx_convertcol2row4d(&buf, (uint4*)dims);
}
if (cfg->outputformat == ofJNifti) {
mcx_savejnii((OutputType*)buf, 4 - d1, dims, voxelsize, name, 1, cfg);
} else {
mcx_savebnii((OutputType*)buf, 4 - d1, dims, voxelsize, name, 1, cfg);
}
free(buf);
}
return;
}
sprintf(fname, "%s%s.%s", name, (isref ? "_dref" : ""), (isref ? "bin" : outputformat[(int)cfg->outputformat]));
fp = fopen(fname, "wb");
if (fp == NULL) {
mcx_error(-2, "can not save data to disk", __FILE__, __LINE__);
}
if (!isref && cfg->outputformat == ofTX3) {
fwrite(&glformat, sizeof(unsigned int), 1, fp);
fwrite(&(cfg->dim.x), sizeof(int), 3, fp);
}
fwrite(dat, sizeof(OutputType), len, fp);
fclose(fp);
}
/**
* @brief Save detected photon data to mch format binary file
*
* @param[in] ppath: buffer pointing to the detected photon data (partial path etc)
* @param[in] seeds: buffer pointing to the detected photon seed data
* @param[in] count: number of detected photons
* @param[in] doappend: flag if the new data is appended or write from the begining
* @param[in] cfg: simulation configuration
*/
void mcx_savejdet(float* ppath, void* seeds, uint count, int doappend, mcconfig* cfg) {
FILE* fp;
char fhistory[MAX_FULL_PATH], filetag;
cJSON* root = NULL, *obj = NULL, *hdr = NULL, *dat = NULL, *sub = NULL;
char* jsonstr = NULL;
int col = 0, i, j, id;
root = cJSON_CreateObject();
/* the "NIFTIHeader" section */
cJSON_AddItemToObject(root, "MCXData", obj = cJSON_CreateObject());
cJSON_AddItemToObject(obj, "Info", hdr = cJSON_CreateObject());
cJSON_AddNumberToObject(hdr, "Version", cfg->his.version);
cJSON_AddNumberToObject(hdr, "MediaNum", cfg->his.maxmedia);
cJSON_AddNumberToObject(hdr, "DetNum", cfg->his.detnum);
cJSON_AddNumberToObject(hdr, "ColumnNum", cfg->his.colcount);
cJSON_AddNumberToObject(hdr, "TotalPhoton", cfg->his.totalphoton);
cJSON_AddNumberToObject(hdr, "DetectedPhoton", count);
cJSON_AddNumberToObject(hdr, "SavedPhoton", cfg->his.savedphoton);
cJSON_AddNumberToObject(hdr, "LengthUnit", cfg->his.unitinmm);
cJSON_AddNumberToObject(hdr, "SeedByte", cfg->his.seedbyte);
cJSON_AddNumberToObject(hdr, "Normalizer", cfg->his.normalizer);
cJSON_AddNumberToObject(hdr, "Repeat", cfg->his.respin);
cJSON_AddNumberToObject(hdr, "SrcNum", cfg->his.srcnum);
cJSON_AddNumberToObject(hdr, "SaveDetFlag", cfg->his.savedetflag);
cJSON_AddItemToObject(hdr, "Media", sub = cJSON_CreateArray());
for (i = 0; i < cfg->medianum; i++) {
cJSON_AddItemToArray(sub, dat = cJSON_CreateObject());
cJSON_AddNumberToObject(dat, "mua", cfg->prop[i].mua / cfg->unitinmm);
cJSON_AddNumberToObject(dat, "mus", cfg->prop[i].mus / cfg->unitinmm);
cJSON_AddNumberToObject(dat, "g", cfg->prop[i].g);
cJSON_AddNumberToObject(dat, "n", cfg->prop[i].n);
}
if (cfg->his.detected == 0 && cfg->his.savedphoton) {
char colnum[] = {1, 3, 1};
char* dtype[] = {"uint32", "single", "single"};
char* dname[] = {"photonid", "p", "w0"};
cJSON_AddItemToObject(obj, "Trajectory", dat = cJSON_CreateObject());
for (id = 0; id < sizeof(colnum); id++) {
uint dims[2] = {count, colnum[id]};
float* buf = (float*)calloc(dims[0] * dims[1], sizeof(float));
for (i = 0; i < dims[0]; i++)
for (j = 0; j < dims[1]; j++) {
buf[i * dims[1] + j] = ppath[i * cfg->his.colcount + col + j];
}
cJSON_AddItemToObject(dat, dname[id], sub = cJSON_CreateObject());
if (mcx_jdataencode(buf, 2, dims, dtype[id], 4, cfg->zipid, sub, 0, cfg)) {
MMC_ERROR(-1, "error when converting to JSON");
}
free(buf);
col += dims[1];
}
} else {
char colnum[] = {1, cfg->his.maxmedia, cfg->his.maxmedia, cfg->his.maxmedia, 3, 3, 1};
char* dtype[] = {"uint32", "uint32", "single", "single", "single", "single", "single"};
char* dname[] = {"detid", "nscat", "ppath", "mom", "p", "v", "w0"};
cJSON_AddItemToObject(obj, "PhotonData", dat = cJSON_CreateObject());
for (id = 0; id < sizeof(colnum); id++) {
if ((cfg->savedetflag >> id) & 0x1) {
uint dims[2] = {count, colnum[id]};
void* val = NULL;
float* fbuf = NULL;
uint* ibuf = NULL;
if (!strcmp(dtype[id], "uint32")) {
ibuf = (uint*)calloc(dims[0] * dims[1], sizeof(uint));
for (i = 0; i < dims[0]; i++)
for (j = 0; j < dims[1]; j++) {
ibuf[i * dims[1] + j] = ppath[i * cfg->his.colcount + col + j];
}
val = (void*)ibuf;
} else {
fbuf = (float*)calloc(dims[0] * dims[1], sizeof(float));
for (i = 0; i < dims[0]; i++)