Monte Carlo eXtreme (MCX)
Macros | Functions | Variables
mcx_utils.c File Reference

Mie scattering parameters handling for polarized light simulations. More...

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "mcx_utils.h"
#include "mcx_const.h"
#include "mcx_shapes.h"
#include "mcx_core.h"
#include "mcx_bench.h"
#include "mcx_mie.h"
#include "zmat/zmatlib.h"
#include "ubj/ubj.h"
Include dependency graph for mcx_utils.c:

Macros

#define FIND_JSON_KEY(id, idfull, parent, fallback, val)
 
#define FIND_JSON_OBJ(id, idfull, parent)
 
#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), (unsigned char*)(val), (UBJ_TYPE)(JDB_##type), (nlen));}
 
#define ubjw_write_single   ubjw_write_float32
 
#define ubjw_write_double   ubjw_write_float64
 
#define MCX_ASSERT(a)   (!(a) && (mcx_error((a),"input error",__FILE__,__LINE__),1) );
 
#define MIN_HEADER_SIZE   348
 
#define NII_HEADER_SIZE   352
 
#define GL_RGBA32F   0x8814
 

Functions

void mcx_initcfg (Config *cfg)
 Initializing the simulation configuration with default values. More...
 
void mcx_cleargpuinfo (GPUInfo **gpuinfo)
 Reset and clear the GPU information data structure. More...
 
void mcx_clearcfg (Config *cfg)
 Clearing the simulation configuration data structure. More...
 
void mcx_savenii (float *dat, size_t len, char *name, int type32bit, int outputformatid, Config *cfg)
 Save volumetric output (fluence etc) to an Nifty format binary file. More...
 
void mcx_savebnii (float *vol, int ndim, uint *dims, float *voxelsize, char *name, int isfloat, Config *cfg)
 Save volumetric output (fluence etc) to a binary JNIfTI/JSON/JData format file. More...
 
void mcx_savejnii (float *vol, int ndim, uint *dims, float *voxelsize, char *name, int isfloat, Config *cfg)
 Save volumetric output (fluence etc) to a JNIfTI/JSON/JData format file. More...
 
void mcx_savedata (float *dat, size_t len, Config *cfg)
 Save volumetric output (fluence etc) to mc2 format binary file. More...
 
void mcx_savedetphoton (float *ppath, void *seeds, int count, int doappend, Config *cfg)
 Save detected photon data to mch format binary file. More...
 
void mcx_savejdet (float *ppath, void *seeds, uint count, int doappend, Config *cfg)
 Save detected photon data to mch format binary file. More...
 
void mcx_printlog (Config *cfg, char *str)
 Print a message to the console or a log file. More...
 
void mcx_normalize (float field[], float scale, int fieldlen, int option, int pidx, int srcnum)
 Normalize the solution by multiplying a scaling factor. More...
 
void mcx_kahanSum (float *sum, float *kahanc, float input)
 Kahan summation: Add a sequence of finite precision floating point numbers. More...
 
float mcx_updatemua (unsigned int mediaid, Config *cfg)
 Retrieve mua for different cfg.vol formats to convert fluence back to energy in post-processing. More...
 
void mcx_flush (Config *cfg)
 Force flush the command line to print the message. More...
 
void mcx_error (const int id, const char *msg, const char *file, const int linenum)
 Error reporting function. More...
 
int mkpath (char *dir_path, int mode)
 Function to recursively create output folder. More...
 
void mcx_assert (int ret)
 Function to raise a CUDA error. More...
 
void mcx_readconfig (char *fname, Config *cfg)
 Read simulation settings from a configuration file (.inp or .json) More...
 
void mcx_writeconfig (char *fname, Config *cfg)
 Write simulation settings to an inp file. More...
 
void mcx_preprocess (Config *cfg)
 Preprocess user input and prepare the cfg data structure. More...
 
void mcx_prep_polarized (Config *cfg)
 Preprocess media to prepare polarized photon simulation. More...
 
void mcx_prepdomain (char *filename, Config *cfg)
 Preprocess user input and prepare the volumetric domain for simulation. More...
 
void mcx_loadconfig (FILE *in, Config *cfg)
 Load user inputs from a .inp input file. More...
 
int mcx_loadjson (cJSON *root, Config *cfg)
 Load user inputs from a .json input file. More...
 
void mcx_saveconfig (FILE *out, Config *cfg)
 Save simulation settings to an inp file. More...
 
void mcx_savejdata (char *filename, Config *cfg)
 Save simulation settings to an inp file. More...
 
void mcx_loadvolume (char *filename, Config *cfg, int isbuf)
 Load media index data volume (.bin or .vol) to the memory. More...
 
void mcx_replayinit (Config *cfg, float *detps, int dimdetps[2], int seedbyte)
 Initialize the replay data structure from detected photon data - in embedded mode (MATLAB/Python) More...
 
void mcx_replayprep (int *detid, float *ppath, History *his, Config *cfg)
 Initialize the replay data structure from detected photon data - in standalone mode. More...
 
void mcx_validatecfg (Config *cfg, float *detps, int dimdetps[2], int seedbyte)
 Validate all input fields, and warn incompatible inputs. More...
 
void mcx_loadseedjdat (char *filename, Config *cfg)
 Load previously saved photon seeds from an .jdat file for replay. More...
 
void mcx_loadseedfile (Config *cfg)
 Load previously saved photon seeds from an .mch file for replay. More...
 
void mcx_convertrow2col (unsigned int **vol, uint3 *dim)
 Convert a row-major (C/C++) array to a column-major (MATLAB/FORTRAN) array. More...
 
void mcx_convertrow2col64 (size_t **vol, uint3 *dim)
 Convert a row-major (C/C++) array to a column-major (MATLAB/FORTRAN) array. More...
 
void mcx_convertcol2row (unsigned int **vol, uint3 *dim)
 Convert a column-major (MATLAB/FORTRAN) array to a row-major (C/C++) array. More...
 
void mcx_convertcol2row4d (unsigned int **vol, uint4 *dim)
 Convert a column-major (MATLAB/FORTRAN) array to a row-major (C/C++) array. More...
 
int mcx_svmc_bgvoxel (int vol)
 Check if a voxel contains background medium(0) More...
 
void mcx_maskdet (Config *cfg)
 Pre-label the voxel near a detector for easy photon detection. More...
 
void mcx_dumpmask (Config *cfg)
 Save the pre-masked volume (with detector ID) to an nii file. More...
 
int mcx_jdatadecode (void **vol, int *ndim, uint *dims, int maxdim, char **type, cJSON *obj, Config *cfg)
 Decode an ND array from JSON/JData construct and output to a volumetric array. More...
 
int mcx_jdataencode (void *vol, int ndim, uint *dims, char *type, int byte, int zipid, void *obj, int isubj, Config *cfg)
 Export an ND volumetric image to JSON/JData encoded construct. More...
 
void mcx_progressbar (float percent, Config *cfg)
 Print a progress bar. More...
 
int mcx_readarg (int argc, char *argv[], int id, void *output, const char *type)
 Function to read a single parameter value followed by a command line option. More...
 
int mcx_remap (char *opt)
 Test if a long command line option is supported. More...
 
void mcx_parsecmd (int argc, char *argv[], Config *cfg)
 Main function to read user command line options. More...
 
int mcx_parsedebugopt (char *debugopt, const char *debugflag)
 Parse the debug flag in the letter format. More...
 
int mcx_keylookup (char *origkey, const char *table[])
 Look up a string in a string list and return the index. More...
 
int mcx_lookupindex (char *key, const char *index)
 Look up a single character in a string. More...
 
void mcx_version (Config *cfg)
 Print MCX software version. More...
 
int mcx_isbinstr (const char *str)
 Test if a string contains only '0' and '1'. More...
 
int mcx_run_from_json (char *jsonstr)
 Run MCX simulations from a JSON input in a persistent session. More...
 
void mcx_printheader (Config *cfg)
 Print MCX output header. More...
 
void mcx_usage (Config *cfg, char *exename)
 Print MCX help information. More...
 

Variables

char pathsep = '/'
 
const char shortopt []
 
const char * fullopt []
 
const char outputtype [] = {'x', 'f', 'e', 'j', 'p', 'm', 'r', 'l', '\0'}
 
const char debugflag [] = {'R', 'M', 'P', 'T', '\0'}
 
const char saveflag [] = {'D', 'S', 'P', 'M', 'X', 'V', 'W', 'I', '\0'}
 
const char * outputformat [] = {"mc2", "nii", "hdr", "ubj", "tx3", "jnii", "bnii", ""}
 
const char boundarycond [] = {'_', 'r', 'a', 'm', 'c', '\0'}
 
const char boundarydetflag [] = {'0', '1', '\0'}
 
const char * srctypeid []
 
const unsigned int mediaformatid [] = {1, 2, 4, 97, 98, 99, 100, 101, 102, 103, 104, 0}
 
const char * mediaformat []
 
char flagset [256] = {'\0'}
 
const char * zipformat [] = {"zlib", "gzip", "base64", "lzip", "lzma", "lz4", "lz4hc", ""}
 

Detailed Description

Mie scattering parameters handling for polarized light simulations.

Simulation configuration and command line option handling.

Macro Definition Documentation

◆ FIND_JSON_KEY

#define FIND_JSON_KEY (   id,
  idfull,
  parent,
  fallback,
  val 
)
Value:
((tmp=cJSON_GetObjectItem(parent,id))==0 ? \
((tmp=cJSON_GetObjectItem(root,idfull))==0 ? fallback : tmp->val) \
: tmp->val)

Macro to load JSON keys

◆ FIND_JSON_OBJ

#define FIND_JSON_OBJ (   id,
  idfull,
  parent 
)
Value:
((tmp=cJSON_GetObjectItem(parent,id))==0 ? \
((tmp=cJSON_GetObjectItem(root,idfull))==0 ? NULL : tmp) \
: tmp)

Macro to load JSON object

◆ MCX_ASSERT

#define MCX_ASSERT (   a)    (!(a) && (mcx_error((a),"input error",__FILE__,__LINE__),1) );

Macro to include unit name and line number in the error message

◆ MIN_HEADER_SIZE

#define MIN_HEADER_SIZE   348

Analyze header size

◆ NII_HEADER_SIZE

#define NII_HEADER_SIZE   352

NIFTI header size

Function Documentation

◆ mcx_assert()

void mcx_assert ( int  ret)

Function to raise a CUDA error.

Parameters
[in]retCUDA function return value, non-zero means an error

◆ mcx_clearcfg()

void mcx_clearcfg ( Config cfg)

Clearing the simulation configuration data structure.

Destructor of the simulation configuration, delete all dynamically allocated members

Here is the call graph for this function:

◆ mcx_cleargpuinfo()

void mcx_cleargpuinfo ( GPUInfo **  gpuinfo)

Reset and clear the GPU information data structure.

Clearing the GPU information data structure

◆ mcx_convertcol2row()

void mcx_convertcol2row ( unsigned int **  vol,
uint3 dim 
)

Convert a column-major (MATLAB/FORTRAN) array to a row-major (C/C++) array.

Parameters
[in,out]vola 3D array (wrapped in 1D) to be converted
[in]dimthe dimensions of the 3D array

◆ mcx_convertcol2row4d()

void mcx_convertcol2row4d ( unsigned int **  vol,
uint4 dim 
)

Convert a column-major (MATLAB/FORTRAN) array to a row-major (C/C++) array.

Parameters
[in,out]vola 3D array (wrapped in 1D) to be converted
[in]dimthe dimensions of the 3D array

◆ mcx_convertrow2col()

void mcx_convertrow2col ( unsigned int **  vol,
uint3 dim 
)

Convert a row-major (C/C++) array to a column-major (MATLAB/FORTRAN) array.

Parameters
[in,out]vola 3D array (wrapped in 1D) to be converted
[in]dimthe dimensions of the 3D array

◆ mcx_convertrow2col64()

void mcx_convertrow2col64 ( size_t **  vol,
uint3 dim 
)

Convert a row-major (C/C++) array to a column-major (MATLAB/FORTRAN) array.

Parameters
[in,out]vola 3D array (wrapped in 1D) to be converted
[in]dimthe dimensions of the 3D array

◆ mcx_dumpmask()

void mcx_dumpmask ( Config cfg)

Save the pre-masked volume (with detector ID) to an nii file.

To test the results, you should use -M to dump the det-mask, load it in matlab, and plot the interface containing the detector with pcolor() (has the matching index), and then draw a circle with the radius and center set in the input file. the pixels should completely cover the circle.

Parameters
[in]cfgsimulation configuration

◆ mcx_error()

void mcx_error ( const int  id,
const char *  msg,
const char *  file,
const int  linenum 
)

Error reporting function.

Parameters
[in]ida single integer for the types of the error
[in]msgthe error message string
[in]filethe unit file name where this error is raised
[in]linenumthe line number in the file where this error is raised
Here is the call graph for this function:

◆ mcx_flush()

void mcx_flush ( Config cfg)

Force flush the command line to print the message.

Parameters
[in]cfgsimulation configuration
Here is the call graph for this function:

◆ mcx_initcfg()

void mcx_initcfg ( Config cfg)

Initializing the simulation configuration with default values.

Constructor of the simulation configuration, initializing all field to default values

expect 1-byte per medium index, use –mediabyte to set to 2 or 4

in theory, mcx can use min block size 32 because no communication between threads, but 64 seems to work the best

launch many threads to saturate the device to maximize throughput

default is Matlab array

output detected photon data by default, use -d 0 to disable

use pencil beam as default source type

default RNG seed, a big integer, with a hidden meaning :)

This format is only supported by C99

by default, honor anisotropy for all scattering, use –gscatter to reduce it

use the first GPU device by default

◆ mcx_isbinstr()

int mcx_isbinstr ( const char *  str)

Test if a string contains only '0' and '1'.

Parameters
[in]strstring to be tested

◆ mcx_jdatadecode()

int mcx_jdatadecode ( void **  vol,
int *  ndim,
uint dims,
int  maxdim,
char **  type,
cJSON *  obj,
Config cfg 
)

Decode an ND array from JSON/JData construct and output to a volumetric array.

The JData specification defines a portable way to encode and share volumetric ND arrays and other complex data structures, such as trees, graphs and tables. This function is capable of importing any ND numerical arrays in the JData construct in to a generic array, permitting data decompression and base64 decoding.

Parameters
[in]vola pointer that points to the ND array buffer
[in]ndimthe number of dimensions
[in]dimsan integer pointer that points to the dimensional vector
[in]typea string of JData data types, such as "uint8" "float32", "int32" etc
[in]bytenumber of byte per voxel
[in]zipidzip method: 0:zlib,1:gzip,2:base64,3:lzma,4:lzip,5:lz4,6:lz4hc
[in]obja pre-created cJSON object to store the output JData fields
Here is the call graph for this function:

◆ mcx_jdataencode()

int mcx_jdataencode ( void *  vol,
int  ndim,
uint dims,
char *  type,
int  byte,
int  zipid,
void *  obj,
int  isubj,
Config cfg 
)

Export an ND volumetric image to JSON/JData encoded construct.

The JData specification defines a portable way to encode and share volumetric ND arrays and other complex data structures, such as trees, graphs and tables. This function is capable of exporting any ND numerical arrays into a JData construct, permitting data compression and base64 encoding.

Parameters
[in]vola pointer that points to the ND array buffer
[in]ndimthe number of dimensions
[in]dimsan integer pointer that points to the dimensional vector
[in]typea string of JData data types, such as "uint8" "float32", "int32" etc
[in]bytenumber of byte per voxel
[in]zipidzip method: 0:zlib,1:gzip,2:base64,3:lzma,4:lzip,5:lz4,6:lz4hc
[in]obja pre-created cJSON object to store the output JData fields

◆ mcx_kahanSum()

void mcx_kahanSum ( float *  sum,
float *  kahanc,
float  input 
)

Kahan summation: Add a sequence of finite precision floating point numbers.

Source: https://en.wikipedia.org/wiki/Kahan_summation_algorithm

Parameters
[in,out]sumsum of the squence before and after adding the next element
[in,out]kahanca running compensation for lost low-order bits
[in]inputthe next element of the sequence

◆ mcx_keylookup()

int mcx_keylookup ( char *  origkey,
const char *  table[] 
)

Look up a string in a string list and return the index.

Parameters
[in]origkeystring to be looked up
[out]tablethe dictionary where the string is searched
Returns
if found, return the index of the string in the dictionary, otherwise -1.

◆ mcx_loadconfig()

void mcx_loadconfig ( FILE *  in,
Config cfg 
)

Load user inputs from a .inp input file.

This function loads user input from a simple text input format in a .inp extension

Parameters
[in]infile handle to the .inp file
[in]cfgsimulation configuration
Here is the call graph for this function:

◆ mcx_loadjson()

int mcx_loadjson ( cJSON *  root,
Config cfg 
)

Load user inputs from a .json input file.

This function loads user input from a JSON format in a .json extension

Parameters
[out]rootjson data structure pointer
[in]cfgsimulation configuration
Here is the call graph for this function:

◆ mcx_loadseedfile()

void mcx_loadseedfile ( Config cfg)

Load previously saved photon seeds from an .mch file for replay.

Parameters
[in,out]cfgsimulation configuration

◆ mcx_loadseedjdat()

void mcx_loadseedjdat ( char *  filename,
Config cfg 
)

Load previously saved photon seeds from an .jdat file for replay.

Parameters
[in]filenamethe name/path of the .jdat file produced from the baseline simulation
[in,out]cfgsimulation configuration
Here is the call graph for this function:

◆ mcx_loadvolume()

void mcx_loadvolume ( char *  filename,
Config cfg,
int  isbuf 
)

Load media index data volume (.bin or .vol) to the memory.

Parameters
[in]filenamefile name to the binary volume data (support 1,2 and 4 bytes per voxel)
[in]cfgsimulation configuration

float to half conversion https://stackoverflow.com/questions/3026441/float32-to-float16/5587983#5587983 https://gamedev.stackexchange.com/a/17410 (for denorms)

Here is the call graph for this function:

◆ mcx_lookupindex()

int mcx_lookupindex ( char *  key,
const char *  index 
)

Look up a single character in a string.

Parameters
[in]keycharacter to be looked up
[out]indexthe dictionary string where the char is searched
Returns
if found, return 0; otherwise, return 1

◆ mcx_maskdet()

void mcx_maskdet ( Config cfg)

Pre-label the voxel near a detector for easy photon detection.

This function preprocess the volume and detector data and add the detector ID to the upper 16bits of the voxel that the detector encompasses. If two detectors cover the same voxel, the later one will overwrite the ID of the 1st one. In MCX kernel, the detector coverage is tested for all detectors despite the label written (only used as a binary mask)

Parameters
[in]cfgsimulation configuration

The goal here is to find a set of voxels for each detector so that the intersection between a sphere of R=cfg->detradius,c0=cfg->detpos[d] and the object surface (or bounding box) is fully covered.

Here is the call graph for this function:

◆ mcx_normalize()

void mcx_normalize ( float  field[],
float  scale,
int  fieldlen,
int  option,
int  pidx,
int  srcnum 
)

Normalize the solution by multiplying a scaling factor.

Parameters
[in,out]fieldvolumetric data before normalization
[in]scalethe scaling factor (or normalization factor) to be applied
[in]fieldlenthe length (floating point) of elements in the volume
[in]optionif set to 2, only normalize positive values (negative values for diffuse reflectance calculations)

◆ mcx_parsecmd()

void mcx_parsecmd ( int  argc,
char *  argv[],
Config cfg 
)

Main function to read user command line options.

This function process user command line inputs and parse all short and long options.

Parameters
[in]argcthe number of total command line parameters
[in]argvthe pointer to all command line options
[in]cfgsimulation configuration
Here is the call graph for this function:

◆ mcx_parsedebugopt()

int mcx_parsedebugopt ( char *  debugopt,
const char *  debugflag 
)

Parse the debug flag in the letter format.

The debug flag following the -D can be either a string format, or numerical format. This function converts the string debug flags into number format

Parameters
[in]debugoptstring following the -D parameter
[out]debugflagthe numerical format of the debug flag

◆ mcx_prep_polarized()

void mcx_prep_polarized ( Config cfg)

Preprocess media to prepare polarized photon simulation.

This function precompute the scattering coefficent and smatrix for different sphere-medium combinations.

Parameters
[in]cfgsimulation configuration
Here is the call graph for this function:

◆ mcx_prepdomain()

void mcx_prepdomain ( char *  filename,
Config cfg 
)

Preprocess user input and prepare the volumetric domain for simulation.

This function preprocess the user input and prepare the domain for the simulation. It loads the media index array from file, add detector masks for easy detection, and check inconsistency between the user specified inputs.

Parameters
[in]filenamethe name of the output file
[in]cfgsimulation configuration
Here is the call graph for this function:

◆ mcx_preprocess()

void mcx_preprocess ( Config cfg)

Preprocess user input and prepare the cfg data structure.

This function preprocess the user input and prepare the domain for the simulation. It loads the media index array from file, add detector masks for easy detection, and check inconsistency between the user specified inputs.

Parameters
[in]cfgsimulation configuration
Here is the call graph for this function:

◆ mcx_printheader()

void mcx_printheader ( Config cfg)

Print MCX output header.

Parameters
[in]cfgsimulation configuration

◆ mcx_printlog()

void mcx_printlog ( Config cfg,
char *  str 
)

Print a message to the console or a log file.

Parameters
[in]cfgsimulation configuration
[in]stra string to be printed

◆ mcx_progressbar()

void mcx_progressbar ( float  percent,
Config cfg 
)

Print a progress bar.

When -D P is specified, this function prints and update a progress bar.

Parameters
[in]percentthe percentage value from 1 to 100
[in]cfgsimulation configuration

◆ mcx_readarg()

int mcx_readarg ( int  argc,
char *  argv[],
int  id,
void *  output,
const char *  type 
)

Function to read a single parameter value followed by a command line option.

This function reads different types of parameter values following a command line option.

Parameters
[in]argcthe number of total command line parameters
[in]argvthe pointer to all command line options
[in]idwhich parameter to be parsed
[out]outputthe pointer to which the parsed value to be written
[in]typethe type of data support char, int, float, string, bytenumlist, floatlist

◆ mcx_readconfig()

void mcx_readconfig ( char *  fname,
Config cfg 
)

Read simulation settings from a configuration file (.inp or .json)

Parameters
[in]fnamethe name of the input file (.inp or .json)
[in]cfgsimulation configuration
Here is the call graph for this function:

◆ mcx_remap()

int mcx_remap ( char *  opt)

Test if a long command line option is supported.

This function returns 1 if a long option is found, and 0 otherwise

Parameters
[in]optthe long command line option string

◆ mcx_replayinit()

void mcx_replayinit ( Config cfg,
float *  detps,
int  dimdetps[2],
int  seedbyte 
)

Initialize the replay data structure from detected photon data - in embedded mode (MATLAB/Python)

Parameters
[in,out]cfgsimulation configuration
[in]detpsdetected photon data
[in]dimdetpsthe dimension vector of the detected photon data
[in]seedbytethe number of bytes per RNG seed

◆ mcx_replayprep()

void mcx_replayprep ( int *  detid,
float *  ppath,
History his,
Config cfg 
)

Initialize the replay data structure from detected photon data - in standalone mode.

Parameters
[in,out]cfgsimulation configuration
[in]detpsdetected photon data
[in]dimdetpsthe dimension vector of the detected photon data
[in]seedbytethe number of bytes per RNG seed

◆ mcx_run_from_json()

int mcx_run_from_json ( char *  jsonstr)

Run MCX simulations from a JSON input in a persistent session.

Parameters
[in]jsonstra string in the JSON format, the content of the .json input file

mcxconfig: structure to store all simulation parameters

gpuinfo: structure to store GPU information

activedev: count of total active GPUs to be used

Here is the call graph for this function:

◆ mcx_savebnii()

void mcx_savebnii ( float *  vol,
int  ndim,
uint dims,
float *  voxelsize,
char *  name,
int  isfloat,
Config cfg 
)

Save volumetric output (fluence etc) to a binary JNIfTI/JSON/JData format file.

Parameters
[in]datvolumetric data to be saved
[in]lentotal byte length of the data to be saved
[in]nameoutput file name (will append '.nii')
[in]type32bittype of the data, only support 32bit per record
[in]outputformatiddecide if save as nii or analyze format
[in]cfgsimulation configuration

◆ mcx_saveconfig()

void mcx_saveconfig ( FILE *  out,
Config cfg 
)

Save simulation settings to an inp file.

Parameters
[in]outhandle to the output file
[in]cfgsimulation configuration

◆ mcx_savedata()

void mcx_savedata ( float *  dat,
size_t  len,
Config cfg 
)

Save volumetric output (fluence etc) to mc2 format binary file.

Parameters
[in]datvolumetric data to be saved
[in]lentotal byte length of the data to be saved
[in]cfgsimulation configuration

◆ mcx_savedetphoton()

void mcx_savedetphoton ( float *  ppath,
void *  seeds,
int  count,
int  doappend,
Config cfg 
)

Save detected photon data to mch format binary file.

Parameters
[in]ppathbuffer pointing to the detected photon data (partial path etc)
[in]seedsbuffer pointing to the detected photon seed data
[in]countnumber of detected photons
[in]doappendflag if the new data is appended or write from the begining
[in]cfgsimulation configuration

◆ mcx_savejdata()

void mcx_savejdata ( char *  filename,
Config cfg 
)

Save simulation settings to an inp file.

Parameters
[in]outhandle to the output file
[in]cfgsimulation configuration

◆ mcx_savejdet()

void mcx_savejdet ( float *  ppath,
void *  seeds,
uint  count,
int  doappend,
Config cfg 
)

Save detected photon data to mch format binary file.

Parameters
[in]ppathbuffer pointing to the detected photon data (partial path etc)
[in]seedsbuffer pointing to the detected photon seed data
[in]countnumber of detected photons
[in]doappendflag if the new data is appended or write from the begining
[in]cfgsimulation configuration
Here is the call graph for this function:

◆ mcx_savejnii()

void mcx_savejnii ( float *  vol,
int  ndim,
uint dims,
float *  voxelsize,
char *  name,
int  isfloat,
Config cfg 
)

Save volumetric output (fluence etc) to a JNIfTI/JSON/JData format file.

Parameters
[in]datvolumetric data to be saved
[in]lentotal byte length of the data to be saved
[in]nameoutput file name (will append '.nii')
[in]type32bittype of the data, only support 32bit per record
[in]outputformatiddecide if save as nii or analyze format
[in]cfgsimulation configuration
Here is the call graph for this function:

◆ mcx_savenii()

void mcx_savenii ( float *  dat,
size_t  len,
char *  name,
int  type32bit,
int  outputformatid,
Config cfg 
)

Save volumetric output (fluence etc) to an Nifty format binary file.

Parameters
[in]datvolumetric data to be saved
[in]lentotal byte length of the data to be saved
[in]nameoutput file name (will append '.nii')
[in]type32bittype of the data, only support 32bit per record
[in]outputformatiddecide if save as nii or analyze format
[in]cfgsimulation configuration

◆ mcx_svmc_bgvoxel()

int mcx_svmc_bgvoxel ( int  vol)

Check if a voxel contains background medium(0)

This function check if a voxel contains background medium, under SVMC mode

Parameters
[in]volhigh 32 bit of the input volume under SVMC mdoe

◆ mcx_updatemua()

float mcx_updatemua ( unsigned int  mediaid,
Config cfg 
)

Retrieve mua for different cfg.vol formats to convert fluence back to energy in post-processing.

Parameters
[out]outputmedium absorption coefficient for the current voxel
[in]mediaidmedium index of the current voxel
[in]cfgsimulation configuration

◆ mcx_usage()

void mcx_usage ( Config cfg,
char *  exename 
)

Print MCX help information.

Parameters
[in]cfgsimulation configuration structure
[in]exenamepath and name of the mcx executable
Here is the call graph for this function:

◆ mcx_validatecfg()

void mcx_validatecfg ( Config cfg,
float *  detps,
int  dimdetps[2],
int  seedbyte 
)

Validate all input fields, and warn incompatible inputs.

Perform self-checking and raise exceptions or warnings when input error is detected

Parameters
[in,out]cfgsimulation configuration
[in]detpsdetected photon data
[in]dimdetpsthe dimension vector of the detected photon data
[in]seedbytethe number of bytes per RNG seed

◆ mcx_version()

void mcx_version ( Config cfg)

Print MCX software version.

Parameters
[in]cfgsimulation configuration

◆ mcx_writeconfig()

void mcx_writeconfig ( char *  fname,
Config cfg 
)

Write simulation settings to an inp file.

Parameters
[in]fnamethe name of the output file
[in]cfgsimulation configuration
Here is the call graph for this function:

◆ mkpath()

int mkpath ( char *  dir_path,
int  mode 
)

Function to recursively create output folder.

Source: https://stackoverflow.com/questions/2336242/recursive-mkdir-system-call-on-unix

Parameters
[in]dir_pathfolder name to be created
[in]modemode of the created folder

Variable Documentation

◆ boundarycond

const char boundarycond[] = {'_', 'r', 'a', 'm', 'c', '\0'}

Boundary condition (BC) types _: no condition (fallback to isreflect) r: Fresnel boundary a: total absorption BC m: total reflection (mirror) BC c: cylic BC

◆ boundarydetflag

const char boundarydetflag[] = {'0', '1', '\0'}

Boundary detection flags 0: do not detect photon 1: detect photon at that boundary

◆ debugflag

const char debugflag[] = {'R', 'M', 'P', 'T', '\0'}

Debug flags R: debug random number generator M: record photon movement and trajectory P: show progress bar

◆ flagset

char flagset[256] = {'\0'}

Flag to decide if parameter has been initialized over command line

◆ fullopt

const char* fullopt[]
Initial value:
= {"--help", "--interactive", "--input", "--photon",
"--thread", "--blocksize", "--session", "--array",
"--gategroup", "--reflect", "--reflectin", "--srcfrom0",
"--unitinmm", "--maxdetphoton", "--shapes", "--savedet",
"--repeat", "--save2pt", "--printlen", "--minenergy",
"--normalize", "--skipradius", "--log", "--listgpu", "--faststep",
"--printgpu", "--root", "--gpu", "--dumpmask", "--autopilot",
"--seed", "--version", "--debug", "--voidtime", "--saveseed",
"--replaydet", "--outputtype", "--outputformat", "--maxjumpdebug",
"--maxvoidstep", "--saveexit", "--saveref", "--gscatter", "--mediabyte",
"--momentum", "--specular", "--bc", "--workload", "--savedetflag",
"--internalsrc", "--bench", "--dumpjson", "--zip", "--json", "--atomic", ""
}

Long command line options The length of this array must match the length of shortopt[], terminates with ""

◆ mediaformat

const char* mediaformat[]
Initial value:
= {"byte", "short", "integer", "svmc", "mixlabel", "labelplus",
"muamus_float", "mua_float", "muamus_half", "asgn_byte", "muamus_short", ""
}

◆ mediaformatid

const unsigned int mediaformatid[] = {1, 2, 4, 97, 98, 99, 100, 101, 102, 103, 104, 0}

Media byte format User can specify the source type using a string

◆ outputformat

const char* outputformat[] = {"mc2", "nii", "hdr", "ubj", "tx3", "jnii", "bnii", ""}

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) tx3: a simple 3D texture format jnii: NeuroJSON JNIfTI format (JSON compatible) bnii: NeuroJSON binary JNIfTI format (binary JSON format BJData compatible)

◆ outputtype

const char outputtype[] = {'x', 'f', 'e', 'j', 'p', 'm', 'r', 'l', '\0'}

Output data types x: fluence rate f: fluence e: energy deposition j: jacobian for mua p: scattering counts for computing Jacobians for mus m: momentum transfer in replay r: frequency domain/RF mua Jacobian by replay l: total path lengths in each voxel

◆ saveflag

const char saveflag[] = {'D', 'S', 'P', 'M', 'X', 'V', 'W', 'I', '\0'}

Recorded fields for detected photons D: detector ID (starting from 1) [1] S: partial scattering event count [#media] P: partial path lengths [#media] M: momentum transfer [#media] X: exit position [3] V: exit direction vector [3] W: initial weight [1]

◆ shortopt

const char shortopt[]
Initial value:
= {'h', 'i', 'f', 'n', 't', 'T', 's', 'a', 'g', 'b', '-', 'z', 'u', 'H', 'P',
'd', 'r', 'S', 'p', 'e', 'U', 'R', 'l', 'L', '-', 'I', '-', 'G', 'M', 'A', 'E', 'v', 'D',
'k', 'q', 'Y', 'O', 'F', '-', '-', 'x', 'X', '-', 'K', 'm', 'V', 'B', 'W', 'w', '-',
'-', '-', 'Z', 'j', '-', '\0'
}

Short command line options If a short command line option is '-' that means it only has long/verbose option. Array terminates with '\0'. Currently un-used options: cCJNoQy0-9

◆ srctypeid

const char* srctypeid[]
Initial value:
= {"pencil", "isotropic", "cone", "gaussian", "planar",
"pattern", "fourier", "arcsine", "disk", "fourierx", "fourierx2d", "zgaussian",
"line", "slit", "pencilarray", "pattern3d", "hyperboloid", "ring", ""
}

Source type specifier User can specify the source type using a string