- Home
- Doc
- Activities
- Homepage
- Forum
- Github
- SF
- Login

- Edit this page
- View other revisions
- Discuss

# MCX Documentation

  1. Command Line Options
    1.1. Required option
    1.2. MC options
    1.3. GPU options
    1.4. Output options
    1.5. User IO options
    1.6. Debug options
    1.7. Additional options
  2. Input File Format
    2.1. JSON input file format
    2.2. inp input file format
    2.3. JSON shape file format

## 1. Command Line Options

### 1.1. Required option

#### -f / --input

Format
  A string
Default value
  If followed by nothing, reads JSON input from `stdin/pipe`
Restriction
  parameter can not be longer than 1024 characters (including the string ending mark '\0' )
Description

Use -f to specify an input file. Format:

        -f filename.json

or

        -f filename.inp

filename may contain absolute or relative path. If the filename has a '.json' extension, this input file is in the JSON format. If the input file name ends with '.inp', it is in the legacy format. If the file name contains space, one must use quotation marks to quote the full file name. In Windows, the quotation must be double quote (""). In Linux or Mac, either single or double quotation mark works.

If this flag is followed by an inline JSON string, such as `-f '{...}'`, the parameter is parsed as an "inline JSON input file".

If `-f` is followed by nothing, or followed by a dash `-`, mcx reads JSON input from the command line standard input (`stdin`) using the `pipe`. This allows users to call common text processing utilities, such as `sed, awk, perl, jq` to modify JSON input on-the-fly and send the updated JSON input file to mcx. For example

      mcx -Q cube60 --dumpjson | sed -e 's/pencil/cone/g' | mcx -f -

or

      curl -s -X GET https://neurojson.io:7777/mcx/aircube60 | jq '.Forward.Dt = 1e-9' | mcx -f

#### -Q / --bench

Format
  A string
Default value
  If followed by nothing, returns a list of benchmarks
Restriction
  the benchmark name must be one of the supported names
Description

Use `-Q` or `--bench` to list all built-in benchmarks. As of MCX v2025, these benchmarks include

- cube60
- cube60b
- cube60planar
- cubesph60b
- onecube
- twocube
- skinvessel
- sphshells
- spherebox
- colin27

One can execute one of the built-in benchmarks by following the benchmark name, such as

        -Q skinvessel

The default settings in each built-in benchmark can be overwritten by the additional command line flags, such as `-Q cube60 -n 1e8` runs 1e8 photons instead of the default 1e6. Use `-Q name --dumpjson` to export the benchmark as a standalone JSON input file.

#### -N / --net

Format
  A string
Default value
  If followed by nothing, returns a list of benchmarks
Restriction
  the benchmark name must be one of the supported names
Description

Use `-N` or `--net` to browse and run community contributed simulations on https://neurojson.io. The list of supported benchmarks can be found at https://neurojson.org/db/mcx

This feature requires the operating system have `curl` installed. curl is a widely used command line utility, installed by default on Windows 10 or later. On Ubuntu Linux, one can install it using `sudo apt-get install curl`; on MacOS, one can install it using `brew install curl`. Alternatively, one can download installers from curl's website at https://curl.se/download.html

For example, running `-N` without any parameter prints a list of currently available simulations. Running `-N cube60` downloads the JSON file from NeuroJSON.io and run the simulation locally.

### 1.2. MC options

#### -n / --photon

Format
  An integer or floating point number
Default value
  0
Restriction
  the number can not exceed 2^63-1
Description

This flag specifies the total number of photons to be simulated. The format is

        -n N

where N can be either an integer, such as 100000 or a floating point number, such as 1e5. If N is a floating point number, it will be rounded to the largest integer below the current value.

#### -r / --repeat

Format
  A positive or negative integer
Default value
  1
Max Value
  the number can not exceed 2^32-1
Description

Use -r to repeat the simulation so that the total number of photon is multiplied by the repetition count. Format:

        -r N

where N is a positive integer. When use this option, mcx runs 'nphoton*N' photons with nphoton per batch.

If N is a negative integer, this option splits the total simulation into abs(N) number of smaller batches; in each batch, only nphoton/abs(N) number of photons are simulated.

This option is useful when one does not have access to a dedicated GPU, i.e. the GPU is used for both display and computation. In such case, the mcx computation time is limited to only 5 to 10 seconds due to the graphics driver. One can use the -r option to make the execution time per batch under the time limit set by the driver.

#### -b / --reflect

Format
  A boolean, 0 or 1
Default value
  1
Restriction
  must be 0 or 1
Description

Use -b to enable or disable reflections at the boundaries. Format:

        '-b' or '-b 1' to enable (default) or '-b 0' to disable

When enabled, mcx will either reflect or transmit the photon at the boundaries based on the Fresnel's equation.

By default, mcx considers refractive index mismatch at the boundaries.

#### -B / --bc

Format
  a string up to 12 characters
Default value
  '______000000'
Restriction
  the first 6 letters must be one of '_','a','r','c',or 'm', the last 6 letters must be '0' or '1'. can be truncated
Description

The `--bc` option describes per-face boundary condition (BC). The first 6 letters defines the boundary condition for bounding box faces at -x,-y,-z,+x,+y,+z axes; overwrite -b if given.

The first 6 letters can be one of the following:

- '_': undefined, fallback to -b
- 'r': like -b 1, Fresnel reflection BC
- 'a': like -b 0, total absorption BC
- 'm': mirror or total reflection BC
- 'c': cyclic BC, enter from opposite face

if input contains additional 6 letters, the 7th-12th letters can be:

- '0': do not use this face to detect photon, or
- '1': use this face for photon detection (`-d 1`)

the order of the faces for letters 7-12 is the same as the first 6 letters

For example: `--bc ______010` saves photons exiting at plane y=0

#### -u / --unitinmm

Format
  a floating point number
Default value
  1.0
Restriction
  can not be less than or equal to 0
Description

Use -u to set the voxel size in mm. Format:

        -u S

where S is a floating point number, denoting the edge length, in mm, of a voxel in the volume. For example, if the volume used in the simulation is 0.1x0.1x0.1 mm^3, then, one should use `-u 0.1` in the command line.

Only isotropic voxels are currently supported by mcx.

#### -U / --normalize

Format
  A boolean, 0 or 1
Default value
  1
Restriction
  must be 0, 1, or 2
Description

Use -U to enable or disable solution normalization. Format:

        '-U' or '-U 1' to enable (default) or '-U 0' to disable

For fluence, the normalization aims to generate a 'Green's function'. For other qualities, the normalization produces a stable solution by removing the dependency due to total photon numbers, voxel sizes, and time-gate settings. The detailed equations are explained in the MCX paper.

If one sets `-U 2`, the normalization is only applied to the fluence in the interior voxels, and does not apply to the diffuse reflectance (as negative numbers in the raw output volume) along the air voxels right outside of the non-zero voxels.

#### -E / --seed

Format
  An integer or a string
Default value
  1648335518
Restriction
  must be an integer; if is a string, the specified file must exist
Description

Use -E to set the seed of the CPU random number generator (RNG). The CPU RNG in turn initializes the seeds for each GPU thread. Format:

        -E -1    // let MCX to automatically seed the CPU-RNG using system clock
        -E n     // n is a large positive integer, set the CPU-RNG's seed to n
        -E filename.mch // replay detected photons using the seeds saved in the mch file

Setting a fixed RNG seed is expected to create reproducible results on NVIDIA cards if the thread/block size are kept the same.

#### -z / --srcfrom0

Format
  A boolean, 0 or 1
Default value
  0
Restriction
  must be 0 or 1
Description

Use -z to define the coordinate origin mode of the volume. Format:

        -z 0 (default)// assumes the lower-bottom corner of the first voxel as [1 1 1]
        -z or -z 1    // assumes the lower-bottom corner of the first voxel as [0 0 0]

All source and detector positions are referenced from the origin, determined by this flag.

#### -R / --skipradius

depreciated as of v2025. Please do not use. This flag will be re-purposed in future releases.

#### -k / --voidtime

Format
  A boolean, 0 or 1
Default value
  0
Restriction
  must be 0 or 1
Description

Use the -k option to tell MCX whether to count the time-of-flight when a photon is launched outside of the volume. Format:

        -k 1 (default)  // the time-of-flight of the photon starts at the launch time
        -k 0            // the time-of-flight starts when a photon enters the first non-zero voxel.

#### -V / --specular

Format
  A boolean, 0 or 1
Default value
  1
Restriction
  must be 0 or 1
Description

Use -V flag to tell MCX whether to consider the specular reflection at the initial entry of the photon to the domain (entry from a 0-voxel to a non-zero voxel). By default, the initial specular reflection is considered (thus, photon loses a small fraction of energy, but enters the domain). The reflected energy is no longer modeled. Please be aware that the "absorption fraction" number printed at the end of the mcx simulation session should include this energy loss due to specular reflection.

If one sets "-V 0", all launched photon energy preserves after enters the domain.

#### -Y / --replaydet

Format
  A positive integer
Default value
  0
Restriction
  can not be negative
Description

Use the -Y option to specify the ID of the detector for the 'replay' calculations. Format:

        -Y n   // n is a positive integer, denoting the index of the detectors to be replayed
        -Y 0   // all detected photons will be replayed regardless of detector

If -Y is not specified, MCX replays all detected photons; otherwise, MCX only replays the detected photons from the specified detector. See -E for more details.

#### -P / --shapes

Format
  A string
Default value
  None, user must specify
Restriction
  parameter can not be longer than 1024 characters (including the string ending mark '\0' )
Description

Use the -P option to dynamically define heterogeneities from the command line. The `-P` flag is followed by a JSON-formatted string. For example

        -P '{"Shapes":[{"ZLayers":[[1,10,1],[11,30,2],[31,60,3]]}]}'

This defines a 3-layer medium: z slices 1-10 is filled with tissue label 1, z slices 11-30 is filled with label 2, and 31-60 is filled with label 3.

The shape definition always starts an array object named 'Shapes'. Each element in the 'Shapes' object defines a primitive object. The supported primitives include Name/Origin/Grid/Sphere/Box/Subgrid/{XYZ}Layers/{XYZ}Slabs/Cylinder/UpperSpace. Most objects have a sub-field 'Tag', specifying the tissue label (index to the property list). The details of the Shapes objects can be found in this link

#### -j / --json

Format
  A string
Default value
  None, user must specify
Restriction
  no
Description

Use the `-j` option to dynamically define simulation parameters to overwrite/modify the default settings as specified in the .inp/.json file provided after the `-f` flag. The `-j` flag is followed by a JSON-formatted string. The format of the JSON construct is the same as in an MCX JSON input file. For example

        -j '{"Optode":{"Source":{"Type":"fourier","Param1":[40,0,0,2]}}}'

This changes the source type, whatever it was defined in the input file, to "fourier" source, and sets the source parameter 1 to `[40,0,0,2]` while keeping everything else unchanged.

if `-f`, `-j`, `-P` and other parameters (such as `-n, -s ...`) all present in the command line, the priorities are

     all other command line flags > -j > -P > -f

where the settings in `-n/-s/-d/...` overwrite the settings in `-j`, which also overwrites the input file in `-f`

#### -K / --mediabyte

Format
  An integer or a string
Default value
  1
Restriction
  can only be one of the below supported numbers or strings
Description

This flag defines the volumetric input data format. Use either a number or a string from below list

- 1 or `byte`: 0-128 tissue labels
- 2 or `short`: 0-65535 (max to 4000) tissue labels
- 4 or `integer`: integer tissue labels
- 96 or asgn_float: mua/mus/g/n 4xfloat format: `{[f:mua][f:mus][f:g][f:n]}`
- 97 or svmc: split-voxel MC 8-byte format: `{[n.z][n.y][n.x][p.z][p.y][p.x][upper][lower]}`
- 98 or mixlabel: label1+label2+label1_percentage: `{[label1][label2][s:0-32767 label1 percentage]}`
- 99 or labelplus: 32bit composite voxel format: `{[h:mua/mus/g/n][s:(B15-16:0/1/2/3)(label)]}`
- 100 or `muamus_float`: 2x 32bit floats for mua/mus
- 101 or `mua_float`: 1 float per voxel for mua
- 102 or `muamus_half`: 2x 16bit float for mua/mus
- 103 or `asgn_byte`: 4x byte gray-levels for mua/s/g/n
- 104 or `muamus_short`: 2x short gray-levels for mua/s

#### -e / --minenergy

Format
  A floating point number
Default value
  0.0
Restriction
  must be positive or 0.0
Description

Use -e to set the min photon packet weight to trigger Russian Roulette. Format:

        -e f    // where f is a floating point number between 0 and 1.

#### -g / --gategroup

Format
  A positive integer
Default value
  100
Restriction
  can not be negative
Description

Use -g to split a simulation containing many time gates into smaller but multiple sequential simulations. Format:

        -g n    // n is a positive integer

Only use this option when the GPU global memory can not hold the data for all required time gates, which only happens when one trys to simulate a very large domain with very dense time gates (very rare). If one's GPU can only hold the data for n time gates, while one has to simulate a total of N > n time gates, use -g n to split the total simulations into multiple runs: in the first run, MCX will record the results for 1~n time gates, in the second run, MCX will launch a new kernel to simulate photons for 1~2*n time gates, but only records the photon fluence for `n+1 ~ 2*n` time gates and so on. As one can see, this method introduces overhead in the later simulations. Therefore, it is recommended to avoid.

#### -a / --array

Format
  A boolean, 0 or 1
Default value
  0
Restriction
  must be 0 or 1
Description

Use -a to tell mcx if the input volume data is a MATLAB-like data (column-major) or a C-like data (row-major).Format

        -a 0 (default) // the input volume is a MATLAB-array
        -a 1           // the input volume is a C-array

If an MATLAB array is used, the fastest loop index is the left-most index of an array; while for a C array, it is the right-most index.

### 1.3. GPU options

#### -L / --listgpu

Format
  A boolean, 0 or 1
Default value
  0
Restriction
  must be 0 or 1
Description

Use the -L flag to list all available GPUs on your system without running the simulation. For example

    $ ../../bin/mcx -L
    =============================   GPU Information  ================================
    Device 1 of 2:          GeForce RTX 2080
    Compute Capability:     7.5
    Global Memory:          8370061312 B
    Constant Memory:        65536 B
    Shared Memory:          49152 B
    Registers:              65536
    Clock Speed:            1.81 GHz
    Number of SMs:          46
    Number of Cores:        2944
    Auto-thread:            94208
    Auto-block:             64
    =============================   GPU Information  ================================
    Device 2 of 2:          GeForce GTX 1050
    Compute Capability:     6.1
    Global Memory:          3165323264 B
    Constant Memory:        65536 B
    Shared Memory:          49152 B
    Registers:              65536
    Clock Speed:            1.52 GHz
    Number of SMs:          6
    Number of Cores:        768
    Auto-thread:            12288
    Auto-block:             64

#### -t / --thread

Format
  An integer
Default value
  2^14=16384
Restriction
  can not be negative
Description

Use -t to specify the number of threads. Format:

        -t N

where `N` is a positive integer. The thread number N must be a multiple of 32 - the size of a warp - on all CUDA devices. If N is not a multiple of `blocksize` specified by `--blocksize` below, mcx will round it to the nearest multiple less than N.

To achieve the best efficiency, it is recommended to launch a large number of threads to maximize the utility of the GPU resources; a thread number larger than 10000 is generally sufficient.

You should not manually specify the thread number using this option when you use the autopilot mode (`-A`).

#### -T / --blocksize

Format
  An integer
Default value
  64
Restriction
  can not be negative, must be multiples of 32
Description

Use -T to specify the size of a block. Format:

        -T N

where N is a positive integer. The block size N is recommended to be a multiple of 32 - the size of a warp - on all CUDA devices. If N is not a multiple of 32, in most cases, this will result in inefficient use of threads (but there are special cases).

Because mcx does not need inter-thread communication, a small block size, such as 32 or 64, is generally recommended.

You should not manually specify the block size using this option when you use the autopilot mode (`-A`), which by default is on.

#### -A / --autopilot

Format
  A boolean, 0 or 1
Default value
  1
Restriction
  must be 0 or 1
Description

Use -A to enable automatic thread/block configuration (i.e. autopilot). Format:

        -A 1

When the autopilot mode is enabled, mcx will compute the 'optimal' thread number and block size using a heuristic algorithm.

#### -G / --gpu

Format
  An integer or a string made of '0's and '1's
Default value
  1
Restriction
  If integer, must be positive (>0); if string, can only have '0's and '1's.
Description

Use -G to specify one or multiple GPUs to run the simulation. Format

        -G 1    // use only the first GPU device (device orders based on 'mcx -L' output)
        -G n    // n is a positive integer, use only the n-th GPU device
        -G 1110 // when -G is followed by a string made of only 0s and 1s, it specifies
                // a mask for active GPUs, for example, 1110 means to use GPU 1-3
                // together while the 4th GPU is not used.

When multiple GPU devices are specified, one need to use the `-W/--workload` flag to optimally partition the total photons to be simulated. By default, photons will be evenly distributed among multiple GPU devices.

#### -W / --workload

Format
  A list of floating point/integer values, separated by commas
Default value
  100
Restriction
  all values must be positive; no space is allowed; length must be equal or longer than number of activated GPUs (i.e. count of all '1's in `-G`)
Description

Use -W to partition the total simulated photon numbers between multiple devices. Format

        -W w1,w2,w3,...  // w_i is a numerical value, corresponding to the relative portions
                         // of the workload of the i-th GPU device. The total load
                         // is proportional to the sum of w_i.

For example, -W 10,20,20 indicates a 1:2:2 workload split between 3 active GPUs.If one needs to simulate 1e6 photons, the 1st GPU will run 2e5 photons, while the 2nd and the 3rd GPUs will run 4e5 photons each.

#### -I / --printgpu

Format
  A boolean, 0 or 1
Default value
  0
Restriction
  must be 0 or 1
Description

The -I option lists all available GPU, same as -L, but it also run the actual simulation.

### 1.4. Output options

#### -s / --session

Format
  A string
Default value
  same as the input file name followed by the -f flag (without the path); it can not contain <>:"/|?*
Restriction
  must be 0 or 1
Description

Use -s to specify a session ID for the simulation. Format:

        -s session_name // session_name is a string, it can not contain <>:"/|?*

If -s is set, the output fluence file (.mc2), detected photon file (.mch) and the log file (.log) will be named as session_name.{mc2,mch,log}. Otherwise, the input file name following the -f option will be used in the place of session_name.

#### -d / --savedet

Format
  A boolean, 0 or 1, or 3
Default value
  1
Restriction
  must be 0 or 1, or 3
Description

Use -d to enable or disable saving the detailed path data for all detected photons. Format:

        '-d' or '-d 1' to enable (default) or
        '-d 0' to disable

When this option is enabled, a binary file, with a suffix of `.mch`, will be produced in additional to the '.mc2' output. The `.mch` file contains the partial path data for all photons enters the apertures of the detectors.

When `-d 3` is used, mcx terminates the simulation as soon as the maximum detected photon buffer (length set by `-H`) is filled.

#### -w / --savedetflag

Format
  A string or an integer
Default value
  `dp` or 5
Restriction
  must be a string or an integer
Description

A case-insensitive string controlling the presence of each detected photon data fields. The presence of a letter denotes that the corresponding detected photon data is saved, otherwise, it is not saved. The below list shows all supported data fields (the data columns of each field is shown in the parentheses)

- 1 D output detector ID (1)
- 2 S output partial scat. even counts (#media)
- 4 P output partial path-lengths (#media)
- 8 M output momentum transfer (#media)
- 16 X output exit position (3)
- 32 V output exit direction (3)
- 64 W output initial weight (1)

For example, `-w dspmxvw` asks mcx to save all supported field. If a domain contains 2 tissue types (#media=2), this results in a 2D floating point array made of 14 columns and #detected photon rows.

#### -x / --saveexit

Format
  A boolean, 0 or 1
Default value
  0
Restriction
  must be 0 or 1
Description

1 to save photon exit positions and directions setting `-x` to 1 also implies setting '-d' to 1 This is the same as appending letters 'xv' with `-w/--savedetflag`.

#### -X / --saveref

Format
  A boolean, 0 or 1
Default value
  0
Restriction
  must be 0 or 1
Description

Setting this flag to 1 to save diffuse reflectance at the air-voxels (0-valued) immediately outside of the domain; if a domain is filled entirely by non-zero voxels, one must preprocess the volume to pad 0s at the facets where diffuse reflectance is desired before using `-X`.

#### -q / --saveseed

Format
  A boolean, 0 or 1
Default value
  0
Restriction
  must be 0 or 1
Description

1 to save photon RNG seed for replay; 0 not save

#### -M / --dumpmask

Format
  A boolean, 0 or 1
Default value
  0
Restriction
  must be 0 or 1
Description

Use `-M` to dump the modified volume data for debugging purposes. The dumped volume is saved in a binary file with `Nx x Ny x Nz` bytes, each byte contains the tissue label as the input volume, and the highest bit of each byte denotes whether the voxel is next to a detector. If `-F jnii` or '-F nii' is used, the output file will be a JSON/JData or NIfTI file, respectively.

#### -m / --momentum

Format
  A boolean, 0 or 1
Default value
  0
Restriction
  must be 0 or 1
Description

Use `-m` to save the momentum transfer for all detected photons. This is the same as appending letter 'm' with `-w/--savedetflag`. One can use this output for diffuse correlation spectroscopy (DCS) simulations. This information is stored in the `.mch` file. One can load the data using `loadmch.m` and process the saved data using the `mcxdcsg1.m` script, both matlab scripts can be found under `mcx/utils`.

#### -H / --maxdetphoton

Format
  An integer
Default value
  1000000
Restriction
  can not be negative
Description

Use -H to specify the maximum number of detected photons. Format:

        -H n    // n is a positive integer, signifying mcx to allocate a buffer to hold n detected photons

By default, mcx can save up to 1e6 detected photons. If the detected photons exceed this limit, mcx will show a warning. Users may use the -H option to rerun the simulation and use the number in the warning to reallocate the buffer.

#### -S / --save2pt

Format
  A boolean, 0 or 1
Default value
  1
Restriction
  must be 0 or 1
Description

Use `-S` to enable or disable saving volumetric fluence distributions (or the requested output specified by the `-X` flag).

#### -O / --outputtype

Format
  A single character (case insensitive)
Default value
  'X'
Restriction
  must be one of `X,F,E,J,P,M,R,L`, case insensitive
Description

Use -O to specify the type of data to be saved in the volumetric output. The supported formats include

     'X' - output time-resolved fluence rate (1/mm^2), i.e. TPSF
     'F' - output time-resolved fluence rate integrated in each time-gate,
     'E' - energy deposit at each voxel (normalized or unnormalized, depends on -u)
     'J' - Jacobian (replay mode),
     'P' - scattering event counts at each voxel (replay mode only)
     'M' - partial momentum transfer
     'R' - RF/FD replay
     'L' - weighted accumulated pathlength in each voxel

#### -F / --outputformat

Format
  A string
Default value
  'jnii'
Restriction
  must be one of 'mc2', 'jnii', 'bnii', 'nii','hdr','ubj', case insensitive
Description

Use -F to specify the volumetric data output format:

        mc2 - MCX mc2 format (binary 32bit float) (default)
        nii - Nifti format (fluence after taking log10())
        jnii - JNIfTI format (http://openjdata.org)
        bnii - Binary JNIfTI (http://openjdata.org)
        hdr - Analyze 7.5 hdr/img format
        tx3 - GL texture data for rendering (GL_RGBA32F)

the bnii/jnii formats support compression (-Z) and generate small files load jnii (JSON) and bnii (UBJSON) files using below lightweight libraries in MATLAB or Python:

- MATLAB/Octave: JNIfTI toolbox https://github.com/fangq/jnifti
- MATLAB/Octave: JSONLab toolbox https://github.com/fangq/jsonlab
- Python: PyJData: https://pypi.org/project/jdata
- JavaScript: JSData: https://github.com/fangq/jsdata

#### -Z / --zip

Format
  a number (0-6) or a string
Default value
  0 or 'zlib'
Restriction
  must be 0-6 or one of 'zlib', 'gzip','base64','lzip','lzma','lz4' or 'lz4hc', case insensitive
Description

Set compression method if `-F jnii` or `--dumpjson` is used (when saving data to JSON/JNIfTI format)

- 0 zlib: zip format (moderate compression,fast)
- 1 gzip: gzip format (compatible with *.gz)
- 2 base64: base64 encoding with no compression
- 3 lzip: lzip format (high compression,very slow)
- 4 lzma: lzma format (high compression,very slow)
- 5 lz4: LZ4 format (low compression,extrem. fast)
- 6 lz4hc: LZ4HC format (moderate compression,fast)

#### --dumpjson

Format
  a number (1-3), empty, '-' or a file name
Default value
  '-'
Restriction
  must be empty or a number 1,2,3 or a file name
Description

Export all settings, including volume data using JSON/JData (http://openjdata.org) format for easy sharing; can be reused using `-f`

- if followed by nothing or '-', mcx will print the JSON to the console;
- write to a file if file name is specified;
- by default, prints settings after pre-processing;
- `--dumpjson 2` prints configurations before validation
- `--dumpjson 3` prints configurations after validation

### 1.5. User IO options

#### -h / --help

Format
  no follow-up parameter needed
Default value
Restriction
  None
Description

Use the `-h` flag to print the built-in help of all supported command line flags

#### -v / --version

Format
  no follow-up parameter needed
Default value
Restriction
  None
Description

Use the `-v` flag to print the version of MCX

#### -l / --log

Format
  An integer
Default value
  -1
Restriction
  0, 1
Description

Use the `-l` flag to save the MCX's command line output into a log file. Format

        '-l' or '-l 1' to enable (default) or
        '-l 0' to print the log to the command line, disable printing the mcx banner

The output file name is 'session_name.log' where 'session_name' is the string specified by the -s flag. If -l is used, no message will be printed in the command line.

#### -i / --interactive

Format
  A boolean, 0 or 1
Default value
  0
Restriction
  must be 0 or 1
Description

Use -i when one wants to type in the domain settings in an item-by-item prompt mode. The -i option can not be used together with -f. When -i is used, one can use the redirect operator to include an input file, i.e.

        mcx -i < input.inp
        mcx -f input.json

can produce the same answer.

### 1.6. Debug options

#### -D / --debug

Format
  An integer or a string
Default value
  0
Restriction
  If integer, must be positive; if string, must be made of any combinations of 'R','M','P' (case insensitive).
Description

Use -D to print debug information (you can use an integer or a string by combining the following flags)

      1 R  debug RNG
      2 M  store photon trajectory info (saved in a .mct file, can be loaded with loadmch.m)
      4 P  print progress bar

combine multiple items by using a string, or add selected numbers together

### 1.7. Additional options

#### --gscatter

Format
  An integer
Default value
  1e9
Restriction
  can not be negative
Description

after a photon completes the specified number of scattering events, mcx then ignores anisotropy g and only performs isotropic scattering using mus' = mus*(1-g) for speed. Setting `--gscatter` to 0 to completely ignore g in all scattering events (and use mus' instead of mus).

#### --maxvoidstep

Format
  An integer
Default value
  1000
Restriction
  can not be negative
Description

maximum distance (in voxel unit) of a photon that can travel before entering the domain, if launched outside (i.e. a widefield source)

#### --maxjumpdebug

Format
  An integer
Default value
  10000000
Restriction
  can not be negative
Description

when trajectory is requested (i.e. -D M), use this parameter to set the maximum positions stored (default: 1e7)

## 2. Input File Format

### 2.1. JSON input file format

Starting from version 0.7.9, MCX accepts a JSON-formatted input file in addition to the conventional tMCimg-like input format. JSON (JavaScript Object Notation) is a portable, human-readable and "fat-free" text format to represent complex and hierarchical data. Using the JSON format makes a input file self-explanatory, extensible and easy-to-interface with other applications (like MATLAB).

A sample JSON input file can be found under the examples/quicktest folder. The same file, qtest.json, is also shown below:

     {
        "Help": {
          "[en]": {
            "Domain::VolumeFile": "file full path to the volume description file, can be a binary or JSON file",
            "Domain::Dim": "dimension of the data array stored in the volume file",
            "Domain::OriginType": "similar to --srcfrom0, 1 if the origin is [0 0 0], 0 if it is [1.0,1.0,1.0]",
    	"Domain::LengthUnit": "define the voxel length in mm, similar to --unitinmm",
            "Domain::Media": "the first medium is always assigned to voxels with a value of 0 or outside of
                             the volume, the second row is for medium type 1, and so on. mua and mus must
                             be in 1/mm unit",
            "Session::Photons": "if -n is not specified in the command line, this defines the total photon number",
            "Session::ID": "if -s is not specified in the command line, this defines the output file name stub",
            "Forward::T0": "the start time of the simulation, in seconds",
            "Forward::T1": "the end time of the simulation, in seconds",
            "Forward::Dt": "the width of each time window, in seconds",
            "Optode::Source::Pos": "the grid position of the source, can be non-integers, in grid unit",
            "Optode::Detector::Pos": "the grid position of a detector, can be non-integers, in grid unit",
            "Optode::Source::Dir": "the unitary directional vector of the photon at launch",
            "Optode::Source::Type": "source types, must be one of the following:
                       pencil,isotropic,cone,gaussian,planar,pattern,fourier,arcsine,disk,fourierx,fourierx2d",
            "Optode::Source::Param1": "source parameters, 4 floating-point numbers",
            "Optode::Source::Param2": "additional source parameters, 4 floating-point numbers"
          }
        },
        "Domain": {
    	"VolumeFile": "semi60x60x60.bin",
            "Dim":    [60,60,60],
            "OriginType": 1,
    	"LengthUnit": 1,
            "Media": [
                 {"mua": 0.00, "mus": 0.0, "g": 1.00, "n": 1.0},
                 {"mua": 0.005,"mus": 1.0, "g": 0.01, "n": 1.0}
            ]
        },
        "Session": {
    	"Photons":  1000000,
    	"RNGSeed":  29012392,
    	"ID":       "qtest"
        },
        "Forward": {
    	"T0": 0.0e+00,
    	"T1": 5.0e-09,
    	"Dt": 5.0e-09
        },
        "Optode": {
    	"Source": {
    	    "Pos": [29.0, 29.0, 0.0],
    	    "Dir": [0.0, 0.0, 1.0],
    	    "Type": "pencil",
    	    "Param1": [0.0, 0.0, 0.0, 0.0],
    	    "Param2": [0.0, 0.0, 0.0, 0.0]
    	},
    	"Detector": [
    	    {
    		"Pos": [29.0,  19.0,  0.0],
    		"R": 1.0
    	    },
                {
                    "Pos": [29.0,  39.0,  0.0],
                    "R": 1.0
                },
                {
                    "Pos": [19.0,  29.0,  0.0],
                    "R": 1.0
                },
                {
                    "Pos": [39.0,  29.0,  0.0],
                    "R": 1.0
                }
    	]
        }
     }

A JSON input file requiers several root objects, namely "Domain", "Session", "Forward" and "Optode". Other root sections, like "Help", will be ignored. Each object is a data structure providing information indicated by its name. Each object can contain various sub-fields. The orders of the fields in the same level are flexible. For each field, you can always find the equivalent fields in the *.inp input files. For example, The "VolumeFile" field under the "Domain" object is the same as Line#6 in qtest.inp; the "RNGSeed" under "Session" is the same as Line#2; the "Optode.Source.Pos" is the same as the triplet in Line#3; the "Forward.T0" is the same as the first number in Line#5, etc.

An MCX JSON input file must be a valid JSON text file. You can validate your input file by running a JSON validator, for example http://jsonlint.com/ You should always use "" to quote a "name" and separate parallel items by ",".

MCX accepts an alternative form of JSON input, but using it is not recommended. In the alternative format, you can use

     "rootobj_name.field_name": value

to represent any parameter directly in the root level. For example

     {
        "Domain.VolumeFile": "semi60x60x60.json",
        "Session.Photons": 10000000,
        ...
     }

You can even mix the alternative format with the standard format. If any input parameter has values in both formats in a single input file, the standard-formatted value has higher priority.

To invoke the JSON-formatted input file in your simulations, you can use the "-f" command line option with MCX, just like using an .inp file. For example:

      mcx -A -n 20 -f onecube.json -s onecubejson

The input file must have a ".json" suffix in order for MCX to recognize. If the input information is set in both command line, and input file, the command line value has higher priority (this is the same for .inp input files). For example, when using "-n 20", the value set in "Session"/"Photons" is overwritten to 20; when using "-s onecubejson", the "Session"/"ID" value is modified. If your JSON input file is invalid, MCX will quit and point out where the format is incorrect.

### 2.2. inp input file format

Historically, MCX supports an extended version of the input file format used by tMCimg. The difference is that MCX allows comments in the input file. A typical MCX input file looks like this:

    1000000              # total photon, use -n to overwrite in the command line
    29012392             # RNG seed, negative to generate
    30.0 30.0 0.0 1      # source position (in grid unit), the last num (optional) sets srcfrom0 (-z)
    0 0 1                # initial directional vector
    0.e+00 1.e-09 1.e-10 # time-gates(s): start, end, step
    semi60x60x60.bin     # volume ('unsigned char' binary format)
    1 60 1 60            # x voxel size in mm (isotropic only), dim, start/end indices
    1 60 1 60            # y voxel size, must be same as x, dim, start/end indices
    1 60 1 60            # y voxel size, must be same as x, dim, start/end indices
    1                    # num of media
    1.010101 0.01 0.005 1.37  # scat. mus (1/mm), g, mua (1/mm), n
    4       1.0          # detector number and default radius (in grid unit)
    30.0  20.0  0.0  2.0 # detector 1 position (real numbers in grid unit) and individual radius (optional)
    30.0  40.0  0.0      # ..., if individual radius is ignored, MCX will use the default radius
    20.0  30.0  0.0      #
    40.0  30.0  0.0      #
    pencil               # source type (optional)
    0 0 0 0              # parameters (4 floats) for the selected source
    0 0 0 0              # additional source parameters

Note that the scattering coefficient mus=musp/(1-g).

### 2.3. JSON shape file format

Starting from v0.7.9, MCX can also use a shape description file in the place of the volume file. Using a shape-description file can save you from making a binary .bin volume. A shape file uses more descriptive syntax and can be easily understood and shared with others.

Samples on how to use the shape files are included under the example/shapetest folder.

The sample shape file, shapes.json, is shown below:

     {
      "MCX_Shape_Command_Help":{
         "Shapes::Common Rules": "Shapes is an array object. The Tag field sets the voxel value for each
             region; if Tag is missing, use 0. Tag must be smaller than the maximum media number in the
             input file.Most parameters are in floating-point (FP). If a parameter is a coordinate, it
             assumes the origin is defined at the lowest corner of the first voxel, unless user overwrite
             with an Origin object. The default origin of all shapes is initialized by user's --srcfrom0
             setting: if srcfrom0=1, the lowest corner of the 1st voxel is [0,0,0]; otherwise, it is [1,1,1]",
         "Shapes::Name": "Just for documentation purposes, not parsed in MCX",
         "Shapes::Origin": "A floating-point (FP) triplet, set coordinate origin for the subsequent objects",
         "Shapes::Grid": "Recreate the background grid with the given dimension (Size) and fill-value (Tag)",
         "Shapes::Sphere": "A 3D sphere, centered at C0 with radius R, both have FP values",
         "Shapes::Box": "A 3D box, with lower corner O and edge length Size, both have FP values",
         "Shapes::SubGrid": "A sub-section of the grid, integer O- and Size-triplet, inclusive of both ends",
         "Shapes::XLayers/YLayers/ZLayers": "Layered structures, defined by an array of integer triples:
              [start,end,tag]. Ends are inclusive in MATLAB array indices. XLayers are perpendicular to x-axis, and so on",
         "Shapes::XSlabs/YSlabs/ZSlabs": "Slab structures, consisted of a list of FP pairs [start,end]
              both ends are inclusive in MATLAB array indices, all XSlabs are perpendicular to x-axis, and so on",
         "Shapes::Cylinder": "A finite cylinder, defined by the two ends, C0 and C1, along the axis and a radius R",
         "Shapes::UpperSpace": "A semi-space defined by inequality A*x+B*y+C*z>D, Coef is required, but not Equ"
      },
      "Shapes": [
         {"Name":     "Test"},
         {"Origin":   [0,0,0]},
         {"Grid":     {"Tag":1, "Size":[40,60,50]}},
         {"Sphere":   {"Tag":2, "O":[30,30,30],"R":20}},
         {"Box":      {"Tag":0, "O":[10,10,10],"Size":[10,10,10]}},
         {"Subgrid":  {"Tag":1, "O":[13,13,13],"Size":[5,5,5]}},
         {"UpperSpace":{"Tag":3,"Coef":[1,-1,0,0],"Equ":"A*x+B*y+C*z>D"}},
         {"XSlabs":   {"Tag":4, "Bound":[[5,15],[35,40]]}},
         {"Cylinder": {"Tag":2, "C0": [0.0,0.0,0.0], "C1": [15.0,8.0,10.0], "R": 4.0}},
         {"ZLayers":  [[1,10,1],[11,30,2],[31,50,3]]}
      ]
     }

A shape file must contain a "Shapes" object in the root level. Other root-level fields are ignored. The "Shapes" object is a JSON array, with each element representing a 3D object or setting. The object-class commands include "Grid", "Sphere", "Box" etc. Each of these object include a number of sub-fields to specify the parameters of the object. For example, the "Sphere" object has 3 subfields, "O", "R" and "Tag". Field "O" has a value of 1x3 array, representing the center of the sphere; "R" is a scalar for the radius; "Tag" is the voxel values. The most useful command is "[XYZ]Layers". It contains a series of integer triplets, specifying the starting index, ending index and voxel value of a layered structure. If multiple objects are included, the subsequent objects always overwrite the overlapping regions covered by the previous objects.

There are a few ways for you to use shape description records in your MCX simulations. You can save it to a JSON shape file, and put the file name in Line#6 of yoru .inp file, or set as the value for Domain.VolumeFile field in a .json input file. In these cases, a shape file must have a suffix of .json.

You can also merge the Shapes section with a .json input file by simply appending the Shapes section to the root-level object. You can find an example, jsonshape_allinone.json, under examples/shapetest. In this case, you no longer need to define the "VolumeFile" field in the input.

Another way to use Shapes is to specify it using the -P (or --shapes) command line flag. For example:

     mcx -f input.json -P '{"Shapes":[{"ZLayers":[[1,10,1],[11,30,2],[31,60,3]]}]}'

This will first initialize a volume based on the settings in the input .json file, and then rasterize new objects to the domain and overwrite regions that are overlapping.

For both JSON-formatted input and shape files, you can use the JSONlab toolbox [4] to load and process in MATLAB.

Powered by Habitat