Macros | Functions | Variables
mmc_utils.c File Reference

MC simulation settings and command line option processing unit. More...

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <time.h>
#include "mmc_utils.h"
#include "mmc_const.h"
#include "mmc_bench.h"
#include "zmat/zmatlib.h"
#include "ubj/ubj.h"
#include "nifti1.h"
Include dependency graph for mmc_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), (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
 
#define MMC_ASSERT(id)   mcx_assert(id,__FILE__,__LINE__)
 
#define MIN_HEADER_SIZE   348
 
#define NII_HEADER_SIZE   352
 
#define GL_RGBA32F   0x8814
 

Functions

void mcx_initcfg (mcconfig *cfg)
 Initializing the simulation configuration with default values. More...
 
void mcx_clearcfg (mcconfig *cfg)
 Clearing the simulation configuration data structure. More...
 
void mcx_cleargpuinfo (GPUInfo **gpuinfo)
 Reset and clear the GPU information data structure. More...
 
void mcx_savenii (OutputType *dat, size_t len, char *name, int type32bit, int outputformatid, mcconfig *cfg)
 Save volumetric output (fluence etc) to an Nifty format binary file. More...
 
void mcx_savebnii (OutputType *vol, int ndim, uint *dims, float *voxelsize, char *name, int isfloat, mcconfig *cfg)
 Save volumetric output (fluence etc) to a binary JNIfTI/JSON/JData format file. More...
 
void mcx_savejnii (OutputType *vol, int ndim, uint *dims, float *voxelsize, char *name, int isfloat, mcconfig *cfg)
 Save volumetric output (fluence etc) to a JNIfTI/JSON/JData format file. More...
 
void mcx_savedata (OutputType *dat, size_t len, mcconfig *cfg, int isref)
 Save volumetric output (fluence etc) to mc2 format binary file. More...
 
void mcx_savejdet (float *ppath, void *seeds, uint count, int doappend, mcconfig *cfg)
 Save detected photon data to mch format binary file. More...
 
void mcx_printlog (mcconfig *cfg, char *str)
 Print a message to the console or a log file. More...
 
void mcx_normalize (float field[], float scale, int fieldlen)
 Normalize the solution by multiplying a scaling factor. More...
 
void mcx_error (const int id, const char *msg, const char *file, const int linenum)
 Error reporting function. More...
 
void mcx_assert (const int ret, const char *file, const int linenum)
 Function to test return value and raise an error. More...
 
void mcx_readconfig (char *fname, mcconfig *cfg)
 Read simulation settings from a configuration file (.inp or .json) More...
 
int mcx_loadfromjson (char *jbuf, mcconfig *cfg)
 Load a .json input file into memory. More...
 
int mcx_loadjson (cJSON *root, mcconfig *cfg)
 Load user inputs from a .json input file. More...
 
void mcx_writeconfig (char *fname, mcconfig *cfg)
 Write simulation settings to an inp file. More...
 
void mcx_loadconfig (FILE *in, mcconfig *cfg)
 Load user inputs from a .inp input file. More...
 
void mcx_saveconfig (FILE *out, mcconfig *cfg)
 Save simulation settings to an inp file. More...
 
void mcx_savejdata (char *filename, mcconfig *cfg)
 Save simulation settings to an inp file. 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_jdatadecode (void **vol, int *ndim, uint *dims, int maxdim, char **type, cJSON *obj, mcconfig *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, mcconfig *cfg)
 Export an ND volumetric image to JSON/JData encoded construct. More...
 
int mcx_parsedebugopt (char *debugopt)
 Parse the debug flag in the letter format. More...
 
void mcx_fflush (FILE *out)
 Flush command line output. More...
 
void mcx_progressbar (float percent)
 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...
 
int mcx_lookupindex (char *key, const char *index)
 Look up a single character in a string. More...
 
int mcx_keylookup (char *key, const char *table[])
 Look up a string in a string list and return the index. More...
 
int mcx_isbinstr (const char *str)
 
void mcx_validatecfg (mcconfig *cfg)
 Validate all input fields, and warn incompatible inputs. More...
 
void mcx_prep (mcconfig *cfg)
 Preprocess configuration and set option dependency. More...
 
void mcx_parsecmd (int argc, char *argv[], mcconfig *cfg)
 Main function to read user command line options. More...
 
void mcx_savedetphoton (float *ppath, void *seeds, int count, int doappend, mcconfig *cfg)
 
void mcx_version (mcconfig *cfg)
 Print MCX software version. More...
 
void mcx_printheader (mcconfig *cfg)
 Print MCX output header. More...
 
void mcx_usage (char *exename, mcconfig *cfg)
 Print MCX help information. More...
 

Variables

const char shortopt []
 
const char * fullopt []
 
char pathsep
 
const char debugflag [] = {'M', 'C', 'B', 'W', 'D', 'I', 'O', 'X', 'A', 'T', 'R', 'P', 'E', '\0'}
 
const char raytracing [] = {'p', 'h', 'b', 's', 'g', '\0'}
 
const char outputtype [] = {'x', 'f', 'e', 'j', 'l', 'p', '\0'}
 
const char * outputformat [] = {"ascii", "bin", "nii", "hdr", "mc2", "tx3", "jnii", "bnii", ""}
 
const char * srctypeid []
 
char flagset [256] = {'\0'}
 
const char * zipformat [] = {"zlib", "gzip", "base64", "lzip", "lzma", "lz4", "lz4hc", ""}
 
const char * computebackend [] = {"sse", "opencl", "cuda", ""}
 

Detailed Description

MC simulation settings and command line option processing unit.

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

◆ MIN_HEADER_SIZE

#define MIN_HEADER_SIZE   348

Analyze header size

◆ MMC_ASSERT

#define MMC_ASSERT (   id)    mcx_assert(id,__FILE__,__LINE__)

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

◆ NII_HEADER_SIZE

#define NII_HEADER_SIZE   352

NIFTI header size

Function Documentation

◆ mcx_assert()

void mcx_assert ( const int  ret,
const char *  file,
const int  linenum 
)

Function to test return value and raise an error.

Parameters
[in]retfunction return value, non-zero means an error
[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_clearcfg()

void mcx_clearcfg ( mcconfig 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_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_fflush()

void mcx_fflush ( FILE *  out)

Flush command line output.

Parameters
[in]outthe stream to be flushed
Here is the call graph for this function:

◆ mcx_initcfg()

void mcx_initcfg ( mcconfig cfg)

Initializing the simulation configuration with default values.

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

◆ mcx_jdatadecode()

int mcx_jdatadecode ( void **  vol,
int *  ndim,
uint *  dims,
int  maxdim,
char **  type,
cJSON *  obj,
mcconfig 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

◆ mcx_jdataencode()

int mcx_jdataencode ( void *  vol,
int  ndim,
uint *  dims,
char *  type,
int  byte,
int  zipid,
void *  obj,
int  isubj,
mcconfig 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_keylookup()

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

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

Parameters
[in]keystring 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,
mcconfig 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

◆ mcx_loadfromjson()

int mcx_loadfromjson ( char *  jbuf,
mcconfig cfg 
)

Load a .json input file into memory.

This function loads a JSON file using cJSON

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

◆ mcx_loadjson()

int mcx_loadjson ( cJSON *  root,
mcconfig 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

◆ 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_normalize()

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

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

◆ mcx_parsecmd()

void mcx_parsecmd ( int  argc,
char *  argv[],
mcconfig 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)

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
Returns
debugflag: the numerical format of the debug flag

◆ mcx_prep()

void mcx_prep ( mcconfig cfg)

Preprocess configuration and set option dependency.

This function preprocess the user input and set dependent flags

Parameters
[in,out]cfgsimulation configuration

◆ mcx_printheader()

void mcx_printheader ( mcconfig cfg)

Print MCX output header.

Parameters
[in]cfgsimulation configuration

◆ mcx_printlog()

void mcx_printlog ( mcconfig 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)

Print a progress bar.

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

Parameters
[in]nthe number of completed photons
[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,
mcconfig 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_savebnii()

void mcx_savebnii ( OutputType *  vol,
int  ndim,
uint *  dims,
float *  voxelsize,
char *  name,
int  isfloat,
mcconfig 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,
mcconfig cfg 
)

Save simulation settings to an inp file.

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

◆ mcx_savedata()

void mcx_savedata ( OutputType *  dat,
size_t  len,
mcconfig cfg,
int  isref 
)

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_savejdata()

void mcx_savejdata ( char *  filename,
mcconfig 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,
mcconfig 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 ( OutputType *  vol,
int  ndim,
uint *  dims,
float *  voxelsize,
char *  name,
int  isfloat,
mcconfig 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 ( OutputType *  dat,
size_t  len,
char *  name,
int  type32bit,
int  outputformatid,
mcconfig 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_usage()

void mcx_usage ( char *  exename,
mcconfig cfg 
)

Print MCX help information.

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

◆ mcx_validatecfg()

void mcx_validatecfg ( mcconfig cfg)

Validate all input fields, and warn incompatible inputs.

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

Parameters
[in,out]cfgthe simulation configuration structure

◆ mcx_version()

void mcx_version ( mcconfig cfg)

Print MCX software version.

Parameters
[in]cfgsimulation configuration

◆ mcx_writeconfig()

void mcx_writeconfig ( char *  fname,
mcconfig 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:

Variable Documentation

◆ computebackend

const char* computebackend[] = {"sse", "opencl", "cuda", ""}

Flag to decide which platform to run mmc

◆ debugflag

const char debugflag[] = {'M', 'C', 'B', 'W', 'D', 'I', 'O', 'X', 'A', 'T', 'R', 'P', 'E', '\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", "--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", ""
}

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

◆ outputformat

const char* outputformat[] = {"ascii", "bin", "nii", "hdr", "mc2", "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)

◆ outputtype

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

Output data types x: fluence rate f: fluence e: energy deposition j: jacobian for mua p: scattering counts for computing Jacobians for mus

◆ pathsep

char pathsep

path separator on Linux/Unix/OSX

◆ raytracing

const char raytracing[] = {'p', 'h', 'b', 's', 'g', '\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

◆ shortopt

const char shortopt[]
Initial value:
= {'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'
}

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

◆ srctypeid

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

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

◆ zipformat

const char* zipformat[] = {"zlib", "gzip", "base64", "lzip", "lzma", "lz4", "lz4hc", ""}

Flag for JData compression methods