{"id":17744091,"url":"https://github.com/fangq/mcx","last_synced_at":"2025-05-15T15:05:07.831Z","repository":{"id":26354388,"uuid":"29803383","full_name":"fangq/mcx","owner":"fangq","description":"Monte Carlo eXtreme (MCX) - GPU-accelerated photon transport simulator","archived":false,"fork":false,"pushed_at":"2025-03-14T15:39:35.000Z","size":25822,"stargazers_count":138,"open_issues_count":4,"forks_count":81,"subscribers_count":24,"default_branch":"master","last_synced_at":"2025-04-02T02:31:27.689Z","etag":null,"topics":["3d","c","cuda","matlab","monte-carlo","optical-imaging","pascal","photon-transport","physics-simulation","ray-tracing","volumetric-rendering","voxel-based"],"latest_commit_sha":null,"homepage":"http://mcx.space","language":"Pascal","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fangq.png","metadata":{"files":{"readme":"README.md","changelog":"ChangeLog.txt","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":"AUTHORS.txt","dei":null,"publiccode":null,"codemeta":null}},"created_at":"2015-01-25T05:02:33.000Z","updated_at":"2025-03-14T15:39:39.000Z","dependencies_parsed_at":"2023-11-17T05:44:48.129Z","dependency_job_id":"1e5f833d-6bf1-4100-9b43-5feb28d61810","html_url":"https://github.com/fangq/mcx","commit_stats":{"total_commits":1950,"total_committers":17,"mean_commits":"114.70588235294117","dds":0.1446153846153846,"last_synced_commit":"4b7020ddccfe59b21a7eb7713391c031259c1748"},"previous_names":[],"tags_count":18,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fangq%2Fmcx","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fangq%2Fmcx/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fangq%2Fmcx/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fangq%2Fmcx/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fangq","download_url":"https://codeload.github.com/fangq/mcx/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247730068,"owners_count":20986404,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["3d","c","cuda","matlab","monte-carlo","optical-imaging","pascal","photon-transport","physics-simulation","ray-tracing","volumetric-rendering","voxel-based"],"created_at":"2024-10-26T06:41:56.029Z","updated_at":"2025-04-07T21:11:52.605Z","avatar_url":"https://github.com/fangq.png","language":"Pascal","readme":"\nMonte Carlo eXtreme (MCX) - CUDA Edition\n=========================\n\n-   Author: Qianqian Fang (q.fang at neu.edu)\n-   License: GNU General Public License version 3 (GPLv3)\n-   Version: 2.8 (v2025.6.pre, Kilo-Kelvin)\n-   Website: \u003chttps://mcx.space\u003e\n-   Download: \u003chttps://mcx.space/wiki/?Get\u003e\n\n![Mex and Binaries](https://github.com/fangq/mcx/actions/workflows/build_all.yml/badge.svg)\\\n![Linux Python Module](https://github.com/fangq/mcx/actions/workflows/build_linux_manywheel.yml/badge.svg)\\\n![MacOS Python Module](https://github.com/fangq/mcx/actions/workflows/build_macos_wheel.yml/badge.svg)\\\n![Windows Python Module](https://github.com/fangq/mcx/actions/workflows/build_windows_wheel.yml/badge.svg)\n\nTable of Content:\n\n  * [What's New](#whats-new)\n  * [Introduction](#introduction)\n  * [Requirement and Installation](#requirement-and-installation)\n  * [Running Simulations](#running-simulations)\n  * [Using JSON-formatted input files](#using-json-formatted-input-files)\n  * [Using JSON-formatted shape description files](#using-json-formatted-shape-description-files)\n  * [Output data formats](#output-data-formats)\n    + [Volumetric output](#volumetric-output)\n    + [Detected photon data](#detected-photon-data)\n    + [Photon trajectory data](#photon-trajectory-data)\n  * [Using MCXLAB in MATLAB and Octave](#using-mcxlab-in-matlab-and-octave)\n  * [Using MCX Studio GUI](#using-mcx-studio-gui)\n  * [Interpreting the Output](#interpreting-the-output)\n    + [Output files](#output-files)\n    + [Console print messages](#console-print-messages)\n  * [Best practices guide](#best-practices-guide)\n    + [Use dedicated GPUs](#use-dedicated-gpus)\n    + [Launch as many threads as possible](#launch-as-many-threads-as-possible)\n  * [Acknowledgement](#acknowledgement)\n    + [cJSON library by Dave Gamble](#cjson-library-by-dave-gamble)\n    + [myslicer toolbox by Anders Brun](#myslicer-toolbox-by-anders-brun)\n    + [Texture3D Sample Project by Jürgen Abel](#texture3d-sample-project-by-jürgen-abel)\n  * [Reference](#reference)\n\nWhat's New\n-------------\n\nMCX v2025 is a maintenance release with multiple bug fixes and minor new features. It is highly\nrecommended to upgrade for all users.\n\nNotable major bug fixes include\n- a high priority bug #222, introduced in 198cd34, was fixed. this bug affects all simulations\n  since v2023. Particularly, when a photon has a long pathlength, with weight drops to numerical 0,\n  its pathlength data is carried in the immediately launched new photon, causing skews in the\n  detected photon pathlength distributions\n- further updates to the handling of low absorption medium (#164), previously affect not-so-low mua values\n- a bug fix related to multi-source simulation to properly return the source ID (#217)\n- fix angleinvcdf and invcdf in pmcx that was previously not enabled (#233)\n- fix svmc flipped normal direction only in mcxlab for Octave (#221)\n- fix continuous media nan handling (#224, #225)\n- fix the bug that prevents the use of photon-sharing with pattern3d source\n- correctly store detector ID and initial launch pixel index in pattern3d photon-sharing simulations\n- for all brain related simulations, we have updated the CSF mua value of 0.004/mm that was\n  previously used in Custo et al. 2006 paper to 0.0004/mm, matching its upstream reference Strangman et al. 2003.\n  However, we want to highlight that both literature may not provide the best mua value for CSF - as such low\n  mua/mus CSF properties are mostly for CSF in the inner part of the brain, but not representiative to those in\n  the subarachnoid space. A few literature have shown that CSF in the subarachnoid space may have a higher\n  mus' value, in the range between 0.16/mm to 0.32/mm, as shown in Okada et al. 2003\n\n1. [Okada_2003]\nE. Okada and D. T. Delpy, \"Near-infrared light propagation in an adult head model. I. Modeling of low-level scattering in the cerebrospinal fluid layer,\" Applied Optics 42, 2906–2914 (2003)\n2. [Custo_2006]\nA. Custo, W. M. Wells III., A. H. Barnett, et al., \"Effective scattering coefficient of the cerebral spinal fluid in adult head models for diffuse optical imaging,\" Applied Optics 45, 4747 (2006)\n3. [Strangman_2003]\nG. Strangman, M. A. Franceschini, and D. A. Boas, \"Factors affecting the accuracy of near-infrared spectroscopy concentration calculations for focal changes in oxygenation parameters,\" NeuroImage 18, 865–879 (2003)\n\n\nIn addition, in this release, we also added the following key new features\n\n- the new `-N/--net` command line flag allows one to browse and run growing number of community-contributed\n  simulations hosted on https://neurojson.io (one can browse the list at https://neurojson.org/db/mcx)\n- mcx can read JSON input file from `stdin` (standard input) using pipe, allow one to use advanced text processing utilities in the shell,\n  such as `sed, perl, jq` to modify JSON inputs at runtime. For example `mcx -N cube60 --dumpjson | jq '.Forward.Dt=1e-10' | mcx -f`\n- a new shortcut option `-Q` for `--bench` to conveniently browse and run built-in benchmarks\n- a new demo script `demo_mcxlab_replay_traj.m` to show how to use replay to produce trajectories between source/detector\n- mcxlab and pmcx cam set `cfg.flog=1` or 0 to disable printing of mcx banner\n- setting a negative detector radius creates excluded detection areas, making it possible to create ring-shaped detectors\n\nThe detailed updates can be found in the below change log\n\n* 2025-01-22 [24b445e] [bug] fix incorrect per-voxel pathlength when mua-\u003e0, #164\n* 2025-01-21 [1f536ba] [bug] fix windows -N error\n* 2025-01-21 [aeca212] [cmake] update cmake to add -N support\n* 2025-01-21 [134ab82] [ci] fix windows msvc compilation error\n* 2025-01-21 [12071fd] [feat] add -N/--net to download simulations from NeuroJSON.io, add -Q\n* 2025-01-10 [cf10d5f] [pmcx] Parse issavedet field of the cfg dict as an int instead of a bool.\n* 2025-01-03 [8f433e9] [feat] allow plotting logical arrays in mcxplotvol\n* 2024-12-15 [eafea84] [feat] polish and miss_hit format of `demo_mcxlab_replay_traj.m`\n* 2024-12-15 [82e100b] [feat] add missing demo_mcxlab_replay_traj.m script\n* 2024-12-11 [22bf12a] [bug] fix mcxlab castlist\n* 2024-12-04 [86dcba9] [bug] force most scalar inputs to be double to avoid incorrect typecasting\n* 2024-11-25 [4b7020d] [ci] upgrade pmcx macos build to macos-13\n* 2024-11-25 [51e9970] [bug] fix mcx crash when replay is requested without seed file\n* 2024-11-22 [e8907db] [ci] include vcomp140.dll in windows binary\n* 2024-11-22 [2902119] [ci] further test vcomp140\n* 2024-11-22 [c3d413d] [ci] find vcomp140.dll\n* 2024-11-21 [4f1335c] [ci] print vcomp1xx.dll path\n* 2024-11-21 [d033755] [bug] apply patch in #235 to pmcx, bump pmcx to v0.3.6\n* 2024-11-21 [744c088] [bug] correctly return integer based w0 and detid in pattern3d\n* 2024-11-21 [dcf11c4] [bug] enable photon sharing for pattern3d source\n* 2024-11-18 [bd62362] [bug] fix mcxlab crash with \u003e2^31-1 voxels, fix #235, revert #164\n* 2024-11-13 [188338b] [feat] negative detector radius captures but does not save photons\n* 2024-11-12 [dfc704f] [ci] reduce macos binary size using strip\n* 2024-11-12 [7d33c14] [ci] disable octave download on macos\n* 2024-11-12 [43e7416] [ci] download octave app with -L\n* 2024-11-12 [c978a3e] [ci] use octave app on macos\n* 2024-11-12 [30cc3cb] [ci] upload macos mcx package\n* 2024-11-12 [24d1257] [ci] downgrade download-artifact as it does not support multiple jobs\n* 2024-11-10 [f17dcc6] [bug] fix mcxlab crash when using issave2pt=0 with photonsharing\n* 2024-11-09 [8c69db3] [ci] update setup.py for pmcx\n* 2024-11-09 [fd83829] [ci] disable CMAKE_RANLIB\n* 2024-11-09 [dbada19] [ci] debug ranlib\n* 2024-11-09 [208c31d] [ci] use verbose option to debug macos build flags\n* 2024-11-09 [4e0c672] [bug] fix maskdet 1cube test\n* 2024-11-08 [ee5be15] [feat] make onecube benchmark maskdet work, fix --dumpmask\n* 2024-11-08 [f2d3bc4] [feat] support 1x1x1 volume, add onecube/twocube benchmarks, det not working\n* 2024-11-06 [eaafb0b] [feat] disabling issaveref if issave2pt is false\n* 2024-10-09 [0411ec6] Fix data ordering in traj.iquv\n* 2024-09-25 [8c0cfec] [pmcx] bump up pmcx version to 0.3.5 after fixing #233\n* 2024-09-25 [58dec12] [bug] angleinvcdf and invcdf are not read in full in pmcx, fix #233\n* 2024-09-14 [7b8ecb6] [ci] restore macos-12\n* 2024-09-13 [6fbf3db] [bug] fix the potential typo in Custo et al for CSF mua, fix #232\n* 2024-09-03 [c9456a7] [ci] fix action alert related to download-artifact\n* 2024-08-22 [70f95ba] [pmcx] fix CI error for pmcx\n* 2024-08-22 [82fb8f1] [feat] allow mcxlab and pmcx to use cfg.flog to control log printing\n* 2024-08-18 [17e347c] [bug] fix lzma memory leakage, NeuroJSON/zmat#11, lloyd/easylzma#4\n* 2024-08-06 [5cc92ab] [bug] avoid using the same RNG seed when -E -1 on multiple GPUs\n* 2024-08-06 [3c480b6] [doc] clarify the default RNG seed (1648335518) in html doc\n* 2024-07-22 [d8959eb] [ci] update macos-11 to 12 as 11 no longer works\n* 2024-07-14 [b17cb1a] [bug] mcxplotshapes patch by ChenJY-L to plot Box, close #227\n* 2024-07-14 [78716e4] [bug] avoid overwriting mua/mus when one is nan, fix #224, fix #225\n* 2024-07-04 [80b5794] [bug] read g and n when mua or mus=nan in asgn_float, close #225, close #224\n* 2024-06-22 [f959c71] [bug] store reflection position in trajectory\n* 2024-06-19 [4ff5b60] [bug] print large photon numbers without overflow\n* 2024-06-11 [d66a0a3] [test] sync test script between mcx and mcxcl after fangq/mcxcl#57\n* 2024-06-11 [1e7d0f1] [bug] reset replay.tof when tof exceeds tend, like fangq/mcxcl#57\n* 2024-06-07 [026eebf] [bug] ensure to clear shared mem buffer regardless of weight, #222\n* 2024-06-06 [b41c915] [bug] fix skewed nscat distribution, fix #222\n* 2024-06-05 [654dff1] [bug] fix outputtype error in json2mcx, reformat with miss_hit\n* 2024-06-05 [25b0268] [feat] export iquv in trajectory data when cfg.istrajstokes=1\n* 2024-05-18 [0a76d17] [bug] fix mcxsvmc flipped normal direction in octave, fix #221\n* 2024-05-18 [2f42524] [ci] downgrade matlab from v2024a to v2022a\n* 2024-05-14 [56aa355] [doc] update jsonlan and neurojson toolbox download links\n* 2024-04-25 [ea67ea9] [bug] avoid double-base64-encoding when -Z 2 is used, fix #219\n* 2024-03-28 [3b7e11c] [doc] fix incorrect default value for gscatter\n* 2024-03-25 [b4706ae] [release] update winget mcxstudio package\n* 2024-03-18 [2953735] [doc] add documentation on the srcid output in detp and traj\n* 2024-03-18 [94961f3] [bug] return source ID in multi-source simulation, fix #217\n* 2024-03-17 [3c3d755] [release] post v2024.2 release action, close #216\n* 2024-03-17 [7902a4e] [mcxcloud] update docker image to v2024.2\n* 2024-03-15 [08bfe11] [feat] support `_ArrayData_` in Shapes volume input\n\n\nIntroduction\n---------------\n\nMonte Carlo eXtreme (MCX) is a fast physically-accurate photon simulation \nsoftware for 3D heterogeneous complex media. By taking advantage of \nthe massively parallel threads and extremely low memory latency in a \nmodern graphics processing unit (GPU), this program is able to perform Monte \nCarlo (MC) simulations at a blazing speed, typically hundreds to\na thousand times faster than a single-threaded CPU-based MC implementation.\n\nMCX is written in C and NVIDIA CUDA. It only be executed on NVIDIA GPUs.\nIf you want to run hardware-accelerated MCX simulations on AMD/Intel GPUs\nor CPUs, please download MCX-CL (MCX for OpenCL), which is written in OpenCL.\nMCX and MCX-CL are highly compatible.\n\nDue to the nature of the underlying MC algorithms, MCX and MCX-CL are\nray-tracing/ray-casting software under-the-hood. Compared to commonly\nseen ray-tracing libraries used in computer graphics or gaming\nengines, MCX-CL and MCX have many unique characteristics. The most\nimportant difference is that MCX/MCX-CL are rigorously based on physical\nlaws. They are numerical solvers to the underlying radiative transfer equation\n(RTE) and their solutions have been validated across many publications\nusing optical instruments and experimental measurements. In comparison,\nmost graphics-oriented ray-tracers have to make many approximations in\norder to achieve fast rendering, enable to provide quantitatively accurate\nlight simulation results. Because of this, MCX/MCX-CL have been extensively\nused by biophotonics research communities to obtain reference solutions and\nguide the development of novel medical imaging systems or clinical\napplications. Additionally, MCX/MCX-CL are volumetric ray-tracers; they\ntraverse photon-rays throughout complex 3-D domains and computes physically\nmeaningful quantities such as spatially resolved fluence, flux, diffuse\nreflectance/transmittance, energy deposition, partial pathlengths,\namong many others. In contrast, most graphics ray-tracing engines\nonly trace the RGB color of a ray and render it on a flat 2-D screen.\nIn other words, MCX/MCX-CL gives physically accurate 3-D light distributions\nwhile graphics ray-tracers focus on 2-D rendering of a scene at the camera.\nNonetheless, they share many similarities, such as ray-marching computation,\nGPU acceleration, scattering/absorption handling etc.\n\nThe algorithm of this software is detailed in the References \n[Fang2009,Yu2018,Yan2020]. A short summary of the main features includes:\n\n-   3D heterogeneous media represented by voxelated array\n-   support complex sources including wide-field and pattern illuminations\n-   boundary reflection support\n-   time-resolved photon transport simulations\n-   saving photon partial path lengths and trajectories\n-   optimized random number generators\n-   build-in flux/fluence normalization to output Green's functions\n-   user adjustable voxel resolution\n-   improved accuracy with atomic operations\n-   cross-platform graphical user interface\n-   native Matlab/Octave support for high usability\n-   flexible JSON interface for future extensions\n-   multi-GPU support\n-   advanced features: photon-replay, photon-sharing, and more\n\nThis software can be used on Windows, Linux and Mac OS. MCX is written in C/CUDA\nand requires NVIDIA GPUs (support for AMD/Intel CPUs/GPUs via ROCm is still\nunder development). A more portable OpenCL implementation of MCX, i.e. MCXCL, \nwas announced on July, 2012 and supports almost all NVIDIA/AMD/Intel CPU and GPU \nmodels. If your hardware does not support CUDA, please download MCXCL from the \nbelow URL:\n\nhttps://mcx.space/wiki/index.cgi?Learn#mcxcl\n\n\nRequirement and Installation\n-------------------------------\n\nPlease read this section carefully. The majority of failures using MCX were \nfound related to incorrect installation of NVIDIA GPU driver.\n\nPlease browse \u003chttps://mcx.space/#documentation\u003e for step-by-step instructions.\n\nFor MCX-CUDA, the requirements for using this software include\n\n-   a CUDA capable NVIDIA graphics card\n-   pre-installed NVIDIA graphics driver\n\nYou must make sure that your NVIDIA graphics driver was installed properly.\nA list of CUDA capable cards can be found at [2]. The oldest \nGPU architecture that MCX source code can be compiled is Fermi (`sm_20`).\nUsing the latest NVIDIA card is expected to produce the best\nspeed. The officially released binaries (including mex files and `pmcx` modules)\ncan run on NVIDIA GPUs as old as Kepler (GTX-730, `sm_35`). All MCX binaries\ncan run directly on future generations of NVIDIA GPUs without needing to\nbe recompiled, therefore forward-compatible.\n\nIn the below webpage, we summarized the speed differences\nbetween different generations of NVIDIA GPUs\n\nhttps://mcx.space/gpubench/\n\nFor simulations with large volumes, sufficient graphics memory is also required \nto perform the simulation. The minimum amount of graphics memory required for a \nMC simulation is Nx\\*Ny\\*Nz bytes for the input tissue data plus \nNx\\*Ny\\*Nz\\*Ng\\*4\\*2 bytes for the output flux/fluence data - where Nx,Ny,Nz are \nthe dimensions of the tissue volume, Ng is the number of concurrent time gates, \n4 is the size of a single-precision floating-point number, 2 is for the extra memory\nneeded to ensure output accuracy (https://github.com/fangq/mcx/issues/41). MCX does not require \ndouble-precision support in your hardware.\n\nMCX stores optical properties and detector positions in the constant memory.\nUsually, NVIDIA GPUs provides about 64 kB constant memory. As a result, we can only\nthe total number of optical properties plus the number of detectors can not\nexceed 4000 (4000 * 4 * 4 = 64 k).\n\nIn addition, MCX stores detected photon data inside the shared memory, which also ranges\nbetween 42 kB to 100 kB per stream processor across different GPU generations. \nIf your domain contains many medium types, it is possible that the allocation of\nthe shared memory can exceed the limit. You will also receive an \"out of memory\" error.\n\nTo install MCX, you need to download the binary executable compiled for your \ncomputer architecture (32 or 64bit) and platform, extract the package and run \nthe executable under the `{mcx root}/bin` directory.\n\nFor Windows users, you must make sure you have installed the appropriate NVIDIA \ndriver for your GPU. You should also configure your OS to run CUDA simulations. \nThis requires you to open the mcx/setup/win64 folder using your file explorer, \nright-click on the `apply_timeout_registry_fix.bat` file and select \n**“Run as administrator”**. After confirmation, you should see a windows \ncommand window with message\n\n      Patching your registry\n      Done\n      Press any key to continue ...\n\nYou MUST REBOOT your Windows computer to make this setting effective. The above \npatch modifies your driver settings so that you can run MCX simulations for \nlonger than a few seconds. Otherwise, when running MCX for over a few seconds, \nyou will get a CUDA error: “unspecified error”.\n\nPlease see the below link for details\n\nhttps://mcx.space/wiki/index.cgi?Doc/FAQ#I_am_getting_a_kernel_launch_timed_out_error_what_is_that\n\nIf you use Linux, you may enable Intel integrated GPU (iGPU) for display while\nleaving your NVIDIA GPU dedicated for computing using `nvidia-prime`, see\n\nhttps://forums.developer.nvidia.com/t/solved-run-cuda-on-dedicated-nvidia-gpu-while-connecting-monitors-to-intel-hd-graphics-is-this-possible/47690/6\n\nor choose one of the 4 other approaches in this blog post\n\nhttps://nvidia.custhelp.com/app/answers/detail/a_id/3029/~/using-cuda-and-x\n\nWe noticed that running Ubuntu Linux 22.04 with a 6.5 kernel on a laptop with \na hybrid GPU with an Intel iGPU and an NVIDIA GPU, you must configure the\nlaptop to use the NVIDIA GPU as the primary GPU by choosing \"NVIDIA (Performance Mode)\"\nin the PRIME Profiles section of **NVIDIA X Server Settings**. You can also run \n\n```\nsudo prime-select nvidia\n```\n\nto achieve the same goal. Otherwise, the simulation may hang your system\nafter running for a few seconds. A hybrid GPU laptop combing an NVIDIA GPU \nwith an AMD iGPU does not seem to have this issue if using Linux.\n\nIn addition, NVIDIA drirver (520 or newer) has a known glitch running on Linux kernel\n6.x (such as those in Ubuntu 22.04). See\n\nhttps://forums.developer.nvidia.com/t/dev-nvidia-uvm-io-error-on-ubuntu-22-04-520-to-535-driver-versions/262153\n\nWhen the laptop is in the \"performance\" mode and wakes up from suspension, MCX or any\nCUDA program fails to run with an error\n\n\n```\nMCX ERROR(-999):unknown error in unit mcx_core.cu:2523\n```\n\nThis is because the kernel module `nvida-uvm` fails to be reloaded after suspension.\nIf you had an open MATLAB session, you must close MATLAB first, and\nrun the below commands (if MATLAB is open, you will see `rmmod: ERROR: Module nvidia_uvm is in use`)\n\n```\nsudo rmmod /dev/nvidia-uvm\nsudo modprobe nvidia-uvm\n```\n\nafter the above command, MCX should be able to run again.\n\nNew generations of Mac computers no longer support NVIDIA or AMD GPUs. you will\nhave to use the OpenCL version of MCX, MCX-CL by downloading it from\n\nhttps://mcx.space/wiki/?Learn#mcxcl\n\n\nRunning Simulations\n----------------------\n\nTo run a simulation, the minimum input is a configuration (text) file, and, if\nthe input file does not contain built-in domain shape descriptions, an external\nvolume file (a binary file with a specified voxel format via `-K/--mediabyte`). \nTyping `mcx` without any parameters prints the help information and a list of \nsupported parameters, as shown below:\n\n```\n###############################################################################\n#                      Monte Carlo eXtreme (MCX) -- CUDA                      #\n#          Copyright (c) 2009-2025 Qianqian Fang \u003cq.fang at neu.edu\u003e          #\n#                https://mcx.space/  \u0026  https://neurojson.io                  #\n#                                                                             #\n# Computational Optics \u0026 Translational Imaging (COTI) Lab- http://fanglab.org #\n#   Department of Bioengineering, Northeastern University, Boston, MA, USA    #\n###############################################################################\n#    The MCX Project is funded by the NIH/NIGMS under grant R01-GM114365      #\n###############################################################################\n#  Open-source codes and reusable scientific data are essential for research, #\n# MCX proudly developed human-readable JSON-based data formats for easy reuse.#\n#                                                                             #\n#Please visit our free scientific data sharing portal at https://neurojson.io #\n# and consider sharing your public datasets in standardized JSON/JData format #\n###############################################################################\n$Rev::9c446e $ v2025 $Date::2025-01-23 17:18:06 -05$ by $Author::Qianqian Fang$\n###############################################################################\n\nusage: mcx \u003cparam1\u003e \u003cparam2\u003e ...\nwhere possible parameters include (the first value in [*|*] is the default)\n\n== Required option ==\n -f config     (--input)       read an input file in the .json format,if config\n                               string starts with '{',it is parsed as an inline\n                               JSON input file; if -f is followed by nothing or\n                               a single '-', it reads input from stdin via pipe\n      or\n -Q/--bench [cube60, skinvessel,...] run a buint-in benchmark specified by name\n                               run -Q without parameter to get a list\n -N benchmark  (--net)         get benchmark from NeuroJSON.io, -N only to list\n                               benchmark can be dataset URL,or dbname/benchname\n                               requires 'curl', install from https://curl.se/\n\n== MC options ==\n -n [0|int]    (--photon)      total photon number (exponential form accepted)\n                               max accepted value:9.2234e+18 on 64bit systems\n -r [1|+/-int] (--repeat)      if positive, repeat by r times,total= #photon*r\n                               if negative, divide #photon into r subsets\n -b [1|0]      (--reflect)     1 to reflect photons at ext. boundary;0 to exit\n -B '______'   (--bc)          per-face boundary condition (BC), 6 letters for\n    /case insensitive/         bounding box faces at -x,-y,-z,+x,+y,+z axes;\n                               overwrite -b if given. \n                               each letter can be one of the following:\n                               '_': undefined, fallback to -b\n                               'r': like -b 1, Fresnel reflection BC\n                               'a': like -b 0, total absorption BC\n                               'm': mirror or total reflection BC\n                               'c': cyclic BC, enter from opposite face\n\n                               if input contains additional 6 letters,\n                               the 7th-12th letters can be:\n                               '0': do not use this face to detect photon, or\n                               '1': use this face for photon detection (-d 1)\n                               the order of the faces for letters 7-12 is \n                               the same as the first 6 letters\n                               eg: --bc ______010 saves photons exiting at y=0\n -u [1.|float] (--unitinmm)    defines the length unit for the grid edge\n -U [1|0]      (--normalize)   1 to normalize flux to unitary; 0 save raw\n -E [1648335518|int|mch](--seed) set rand-number-generator seed, -1 to generate\n                               if an mch file is followed, MCX \"replays\" \n                               the detected photon; the replay mode can be used\n                               to calculate the mua/mus Jacobian matrices\n -z [0|1]      (--srcfrom0)    1 volume origin is [0 0 0]; 0: origin at [1 1 1]\n -k [1|0]      (--voidtime)    when src is outside, 1 enables timer inside void\n -Y [0|int]    (--replaydet)   replay only the detected photons from a given \n                               detector (det ID starts from 1), used with -E \n                               if 0, replay all detectors and sum all Jacobians\n                               if -1, replay all detectors and save separately\n -V [0|1]      (--specular)    1 source located in the background,0 inside mesh\n -e [0.|float] (--minenergy)   minimum energy level to trigger Russian roulette\n -g [1|int]    (--gategroup)   number of maximum time gates per run\n\n== GPU options ==\n -L            (--listgpu)     print GPU information only\n -t [16384|int](--thread)      total thread number\n -T [64|int]   (--blocksize)   thread number per block\n -A [1|int]    (--autopilot)   1 let mcx decide thread/block size, 0 use -T/-t\n -G [0|int]    (--gpu)         specify which GPU to use, list GPU by -L; 0 auto\n      or\n -G '1101'     (--gpu)         using multiple devices (1 enable, 0 disable)\n -W '50,30,20' (--workload)    workload for active devices; normalized by sum\n -I            (--printgpu)    print GPU information and run program\n --atomic [1|0]                1: use atomic operations to avoid thread racing\n                               0: do not use atomic operation (not recommended)\n\n== Input options ==\n -P '{...}'    (--shapes)      a JSON string for additional shapes in the grid.\n                               only the root object named 'Shapes' is parsed \n                               and added to the existing domain defined via -f \n                               or --bench\n -j '{...}'    (--json)        a JSON string for modifying all input settings.\n                               this input can be used to modify all existing \n                               settings defined by -f or --bench\n -K [1|int|str](--mediabyte)   volume data format, use either a number or a str\n       voxel binary data layouts are shown in {...}, where [] for byte,[i:]\n       for 4-byte integer, [s:] for 2-byte short, [h:] for 2-byte half float,\n       [f:] for 4-byte float; on Little-Endian systems, least-sig. bit on left\n                               1 or byte: 0-128 tissue labels\n                               2 or short: 0-65535 (max to 4000) tissue labels\n                               4 or integer: integer tissue labels \n                              96 or asgn_float: mua/mus/g/n 4xfloat format\n                                {[f:mua][f:mus][f:g][f:n]}\n                              97 or svmc: split-voxel MC 8-byte format\n                                {[n.z][n.y][n.x][p.z][p.y][p.x][upper][lower]}\n                              98 or mixlabel: label1+label2+label1_percentage\n                                {[label1][label2][s:0-32767 label1 percentage]}\n                              99 or labelplus: 32bit composite voxel format\n                                {[h:mua/mus/g/n][s:(B15-16:0/1/2/3)(label)]}\n                             100 or muamus_float: 2x 32bit floats for mua/mus\n                                {[f:mua][f:mus]}; g/n from medium type 1\n                             101 or mua_float: 1 float per voxel for mua\n                                {[f:mua]}; mus/g/n from medium type 1\n                             102 or muamus_half: 2x 16bit float for mua/mus\n                                {[h:mua][h:mus]}; g/n from medium type 1\n                             103 or asgn_byte: 4x byte gray-levels for mua/s/g/n\n                                {[mua][mus][g][n]}; 0-255 mixing prop types 1\u00262\n                             104 or muamus_short: 2x short gray-levels for mua/s\n                                {[s:mua][s:mus]}; 0-65535 mixing prop types 1\u00262\n       when formats 99 or 102 is used, the mua/mus values in the input volume\n       binary data must be pre-scaled by voxel size (unitinmm) if it is not 1.\n       pre-scaling is not needed when using these 2 formats in mcxlab/pmcx\n -a [0|1]      (--array)       1 for C array (row-major); 0 for Matlab array\n\n== Output options ==\n -s sessionid  (--session)     a string to label all output file names\n -O [X|XFEJPMRL](--outputtype) X - output flux, F - fluence, E - energy deposit\n    /case insensitive/         J - Jacobian (replay mode),   P - scattering, \n                               event counts at each voxel (replay mode only)\n                               M - momentum transfer; R - RF/FD Jacobian\n                               L - total pathlength\n -d [1|0-3]    (--savedet)     1 to save photon info at detectors; 0 not save\n                               2 reserved, 3 terminate simulation when detected\n                               photon buffer is filled\n -w [DP|DSPMXVW](--savedetflag)a string controlling detected photon data fields\n    /case insensitive/         1 D  output detector ID (1)\n                               2 S  output partial scat. even counts (#media)\n                               4 P  output partial path-lengths (#media)\n                               8 M  output momentum transfer (#media)\n                              16 X  output exit position (3)\n                              32 V  output exit direction (3)\n                              64 W  output initial weight (1)\n      combine multiple items by using a string, or add selected numbers together\n      by default, mcx only saves detector ID and partial-path data\n -x [0|1]      (--saveexit)    1 to save photon exit positions and directions\n                               setting -x to 1 also implies setting '-d' to 1.\n                               same as adding 'XV' to -w.\n -X [0|1]      (--saveref)     1 to save diffuse reflectance at the air-voxels\n                               right outside of the domain; if non-zero voxels\n                               appear at the boundary, pad 0s before using -X\n -m [0|1]      (--momentum)    1 to save photon momentum transfer,0 not to save.\n                               same as adding 'M' to the -w flag\n -q [0|1]      (--saveseed)    1 to save photon RNG seed for replay; 0 not save\n -M [0|1]      (--dumpmask)    1 to dump detector volume masks; 0 do not save\n -H [1000000] (--maxdetphoton) max number of detected photons\n -S [1|0]      (--save2pt)     1 to save the flux field; 0 do not save\n -F [jnii|...](--outputformat) fluence data output format:\n                               mc2 - MCX mc2 format (binary 32bit float)\n                               jnii - JNIfTI format (https://neurojson.org)\n                               bnii - Binary JNIfTI (https://neurojson.org)\n                               nii - NIfTI format\n                               hdr - Analyze 7.5 hdr/img format\n                               tx3 - GL texture data for rendering (GL_RGBA32F)\n    the bnii/jnii formats support compression (-Z) and generate small files\n    load jnii (JSON) and bnii (UBJSON) files using below lightweight libs:\n      MATLAB/Octave: JNIfTI toolbox   https://neurojson.org/download/jnifty\n      MATLAB/Octave: JSONLab toolbox  https://neurojson.org/download/jsonlab\n      Python:        PyJData:         https://neurojson.org/download/pyjdata\n      JavaScript:    JSData:          https://neurojson.org/download/jsdata\n -Z [zlib|...] (--zip)         set compression method if -F jnii or --dumpjson\n                               is used (when saving data to JSON/JNIfTI format)\n                               0 zlib: zip format (moderate compression,fast) \n                               1 gzip: gzip format (compatible with *.gz)\n                               2 base64: base64 encoding with no compression\n                               3 lzip: lzip format (high compression,very slow)\n                               4 lzma: lzma format (high compression,very slow)\n                               5 lz4: LZ4 format (low compression,extrem. fast)\n                               6 lz4hc: LZ4HC format (moderate compression,fast)\n --dumpjson [-,0,1,'file.json']  export all settings, including volume data using\n                               JSON/JData (https://neurojson.org) format for\n                               easy sharing; can be reused using -f\n                               if followed by nothing or '-', mcx will print\n                               the JSON to the console; write to a file if file\n                               name is specified; by default, prints settings\n                               after pre-processing; '--dumpjson 2' prints \n                               raw inputs before pre-processing\n\n== User IO options ==\n -h            (--help)        print this message\n -v            (--version)     print MCX revision number\n -l            (--log)         print messages to a log file instead\n -i            (--interactive) interactive mode\n\n== Debug options ==\n -D [0|int]    (--debug)       print debug information (you can use an integer\n  or                           or a string by combining the following flags)\n -D [''|RMPT]                  1 R  debug RNG\n    /case insensitive/         2 M  store photon trajectory info\n                               4 P  print progress bar\n                               8 T  save trajectory data only, disable flux/detp\n      combine multiple items by using a string, or add selected numbers together\n\n== Additional options ==\n --root         [''|string]    full path to the folder storing the input files\n --gscatter     [1e9|int]      after a photon completes the specified number of\n                               scattering events, mcx then ignores anisotropy g\n                               and only performs isotropic scattering for speed\n --srcid  [0|-1,0,1,2,..]      -1 simulate multi-source separately;0 all sources\n                               together; a positive integer runs a single source\n --internalsrc  [0|1]          set to 1 to skip entry search to speedup launch\n --trajstokes   [0|1]          set to 1 to save Stokes IQUV in trajectory data\n --maxvoidstep  [1000|int]     maximum distance (in voxel unit) of a photon that\n                               can travel before entering the domain, if \n                               launched outside (i.e. a widefield source)\n --maxjumpdebug [10000000|int] when trajectory is requested (i.e. -D M),\n                               use this parameter to set the maximum positions\n                               stored (default: 1e7)\n\n== Example ==\nexample: (list built-in benchmarks: -Q/--bench)\n       mcx -Q\nor (list supported GPUs on the system: -L/--listgpu)\n       mcx -L\nor (use multiple devices - 1st,2nd and 4th GPUs - together with equal load)\n       mcx -Q cube60b -n 1e7 -G 1101 -W 10,10,10\nor (use inline domain definition)\n       mcx -f input.json -P '{\"Shapes\":[{\"ZLayers\":[[1,10,1],[11,30,2],[31,60,3]]}]}'\nor (use inline json setting modifier)\n       mcx -f input.json -j '{\"Optode\":{\"Source\":{\"Type\":\"isotropic\"}}}'\nor (dump simulation in a single json file)\n       mcx -Q cube60planar --dumpjson\nor (use -N/--net to browse community-contributed mcx simulations at https://neurojson.io)\n       mcx -N\nor (run user-shared mcx simulations, see full list at https://neurojson.org/db/mcx)\n       mcx -N aircube60\nor (use -f - to read piped input file modified by shell text processing utilities)\n       mcx -Q cube60 --dumpjson | sed -e 's/pencil/cone/g' | mcx -f -\nor (download/modify simulations from NeuroJSON.io and run with mcx -f)\n       curl -s -X GET https://neurojson.io:7777/mcx/aircube60 | jq '.Forward.Dt = 1e-9' | mcx -f\n```\n\nTo further illustrate the command line options, below one can find a sample command\n```\nmcx -A 0 -t 16384 -T 64 -n 1e7 -G 1 -f input.json -r 2 -s test -g 10 -d 1 -w dpx -b 1\n```\nthe command above asks mcx to manually (`-A 0`) set GPU threads, and launch 16384 \nGPU threads (`-t`) with every 64 threads a block (`-T`); a total of 1e7 photons (`-n`)\nare simulated by the first GPU (`-G 1`) and repeat twice (`-r`) - i.e. total 2e7 photons;\nthe media/source configuration will be read from a JSON file named `input.json` \n(`-f`) and the output will be labeled with the session id “test” (`-s`); the \nsimulation will run 10 concurrent time gates (`-g`) if the GPU memory can not \nsimulate all desired time gates at once. Photons passing through the defined \ndetector positions are saved for later rescaling (`-d`); refractive index \nmismatch is considered at media boundaries (`-b`).\n\nHistorically, MCX supports an extended version of the input file format (.inp)\nused by tMCimg. However, we are phasing out the .inp support and strongly \nencourage users to adopt JSON formatted (.json) input files. Many of the \nadvanced MCX options are only supported in the JSON input format.\n\nA legacy .inp MCX input file looks like this:\n\n```\n1000000              # total photon, use -n to overwrite in the command line\n29012392             # RNG seed, negative to generate, use -E to overwrite\n30.0 30.0 0.0 1      # source position (in grid unit), the last num (optional) sets --srcfrom0 (-z)\n0 0 1 0              # initial directional vector, 4th number is the focal-length, 0 for collimated beam, nan for isotropic\n0.e+00 1.e-09 1.e-10 # time-gates(s): start, end, step\nsemi60x60x60.bin     # volume ('unsigned char' binary format, or specified by -K/--mediabyte)\n1 60 1 60            # x voxel size in mm (isotropic only), dim, start/end indices\n1 60 1 60            # y voxel size, must be same as x, dim, start/end indices \n1 60 1 60            # y voxel size, must be same as x, dim, start/end indices\n1                    # num of media\n1.010101 0.01 0.005 1.37  # scat. mus (1/mm), g, mua (1/mm), n\n4       1.0          # detector number and default radius (in grid unit)\n30.0  20.0  0.0  2.0 # detector 1 position (real numbers in grid unit) and individual radius (optional)\n30.0  40.0  0.0      # ..., if individual radius is ignored, MCX will use the default radius\n20.0  30.0  0.0      #\n40.0  30.0  0.0      # \npencil               # source type (optional)\n0 0 0 0              # parameters (4 floats) for the selected source\n0 0 0 0              # additional source parameters\n```\n\nNote that the scattering coefficient mus=musp/(1-g).\n\nThe volume file (`semi60x60x60.bin` in the above example), can be read in two \nways by MCX: row-major[3] or column-major depending on the value of the user \nparameter `-a`. If the volume file was saved using matlab or fortran, the \nbyte order is column-major, and you should use `-a 0` or leave it out of \nthe command line. If it was saved using the `fwrite()` in C, the order is \nrow-major, and you can either use `-a 1`.\n\nYou may replace the binary volume file by a JSON-formatted shape file. Please \nrefer to Section V for details.\n\nThe time gate parameter is specified by three numbers: start time, end time and \ntime step size (in seconds). In the above example, the configuration specifies \na total time window of [0 1] ns, with a 0.1 ns resolution. That means the \ntotal number of time gates is 10.\n\nMCX provides an advanced option, -g, to run simulations when the GPU memory is \nlimited. It specifies how many time gates to simulate concurrently. Users may \nwant to limit that number to less than the total number specified in the input \nfile - and by default it runs one gate at a time in a single simulation. But if \nthere's enough memory based on the memory requirement in Section II, you can \nsimulate all 10 time gates (from the above example) concurrently by using \n`-g 10` in which case you have to make sure the video card has at least \n60\\*60\\*60\\*10\\*5=10MB of free memory. If you do not include the `-g`, MCX will \nassume you want to simulate just 1 time gate at a time.. If you specify a \ntime-gate number greater than the total number in the input file, (e.g, \n`-g 20`) MCX will stop when the 10 time-gates are completed. If you use the \nautopilot mode (`-A`), then the time-gates are automatically estimated for you.\n\n\nUsing JSON-formatted input files\n-----------------------------------\n\nStarting from version 0.7.9, MCX accepts a JSON-formatted input file in \naddition to the conventional tMCimg-like input format. JSON (JavaScript Object \nNotation) is a portable, human-readable and “fat-free” text format to \nrepresent complex and hierarchical data. Using the JSON format makes a input \nfile self-explanatory, extensible and easy-to-interface with other applications \n(like MATLAB).\n\nA sample JSON input file can be found under the examples/quicktest folder. The \nsame file, `qtest.json`, is also shown below:\n```\n{\n    \"Help\": {\n      \"[en]\": {\n        \"Domain::VolumeFile\": \"file full path to the volume description file, can be a binary or JSON file\",\n        \"Domain::Dim\": \"dimension of the data array stored in the volume file\",\n        \"Domain::OriginType\": \"similar to --srcfrom0, 1 if the origin is [0 0 0], 0 if it is [1.0,1.0,1.0]\",\n\t\"Domain::LengthUnit\": \"define the voxel length in mm, similar to --unitinmm\",\n        \"Domain::Media\": \"the first medium is always assigned to voxels with a value of 0 or outside of\n                         the volume, the second row is for medium type 1, and so on. mua and mus must \n                         be in 1/mm unit\",\n        \"Session::Photons\": \"if -n is not specified in the command line, this defines the total photon number\",\n        \"Session::ID\": \"if -s is not specified in the command line, this defines the output file name stub\",\n        \"Forward::T0\": \"the start time of the simulation, in seconds\",\n        \"Forward::T1\": \"the end time of the simulation, in seconds\",\n        \"Forward::Dt\": \"the width of each time window, in seconds\",\n        \"Optode::Source::Pos\": \"the grid position of the source, can be non-integers, in grid unit\",\n        \"Optode::Detector::Pos\": \"the grid position of a detector, can be non-integers, in grid unit\",\n        \"Optode::Source::Dir\": \"the unitary directional vector of the photon at launch\",\n        \"Optode::Source::Type\": \"source types, must be one of the following: \n                   pencil,isotropic,cone,gaussian,planar,pattern,fourier,arcsine,disk,fourierx,fourierx2d,\n\t\t   zgaussian,line,slit,pencilarray,pattern3d\",\n        \"Optode::Source::Param1\": \"source parameters, 4 floating-point numbers\",\n        \"Optode::Source::Param2\": \"additional source parameters, 4 floating-point numbers\"\n      }\n    },\n    \"Domain\": {\n\t\"VolumeFile\": \"semi60x60x60.bin\",\n        \"Dim\":    [60,60,60],\n        \"OriginType\": 1,\n\t\"LengthUnit\": 1,\n        \"Media\": [\n             {\"mua\": 0.00, \"mus\": 0.0, \"g\": 1.00, \"n\": 1.0},\n             {\"mua\": 0.005,\"mus\": 1.0, \"g\": 0.01, \"n\": 1.0}\n        ]\n    },\n    \"Session\": {\n\t\"Photons\":  1000000,\n\t\"RNGSeed\":  29012392,\n\t\"ID\":       \"qtest\"\n    },\n    \"Forward\": {\n\t\"T0\": 0.0e+00,\n\t\"T1\": 5.0e-09,\n\t\"Dt\": 5.0e-09\n    },\n    \"Optode\": {\n\t\"Source\": {\n\t    \"Pos\": [29.0, 29.0, 0.0],\n\t    \"Dir\": [0.0, 0.0, 1.0],\n\t    \"Type\": \"pencil\",\n\t    \"Param1\": [0.0, 0.0, 0.0, 0.0],\n\t    \"Param2\": [0.0, 0.0, 0.0, 0.0]\n\t},\n\t\"Detector\": [\n\t    {\n\t\t\"Pos\": [29.0,  19.0,  0.0],\n\t\t\"R\": 1.0\n\t    },\n            {\n                \"Pos\": [29.0,  39.0,  0.0],\n                \"R\": 1.0\n            },\n            {\n                \"Pos\": [19.0,  29.0,  0.0],\n                \"R\": 1.0\n            },\n            {\n                \"Pos\": [39.0,  29.0,  0.0],\n                \"R\": 1.0\n            }\n\t]\n    }\n}\n```\n\nA JSON input file requiers several root objects, namely `Domain`, \n`Session`, `Forward` and `Optode`. Other root sections, like \n`Help`, will be ignored. Each object is a data structure providing \ninformation indicated by its name. Each object can contain various sub-fields. \nThe orders of the fields in the same level are flexible. For each field, you \ncan always find the equivalent fields in the `*.inp` input files. For example, \nThe `VolumeFile` field under the `Domain` object is the same as Line\\#6 \nin `qtest.inp`; the `RNGSeed` under `Session` is the same as Line\\#2; the \n`Optode.Source.Pos` is the same as the triplet in Line\\#3; the \n`Forward.T0` is the same as the first number in Line\\#5, etc.\n\nAn MCX JSON input file must be a valid JSON text file. You can validate your \ninput file by running a JSON validator, for example \u003chttp://jsonlint.com/\u003e You \nshould always use \"\" to quote a “name” and separate parallel items by \n“,”.\n\nMCX accepts an alternative form of JSON input, but using it is not recommended. \nIn the alternative format, you can use “`rootobj_name.field_name`”`: value` \nto represent any parameter directly in the root level. For example\n\n    {\n        \"Domain.VolumeFile\": \"semi60x60x60.json\",\n        \"Session.Photons\": 10000000,\n        ...\n    }\n\nYou can even mix the alternative format with the standard format. If any input \nparameter has values in both formats in a single input file, the \nstandard-formatted value has higher priority.\n\nTo invoke the JSON-formatted input file in your simulations, you can use the \n`-f` command line option with MCX, just like using an `.inp` file. For \nexample:\n\n      mcx -A 1 -n 20 -f onecube.json -s onecubejson\n\nThe input file must have a `.json` suffix in order for MCX to recognize. If \nthe input information is set in both command line, and input file, the command \nline value has higher priority (this is the same for `.inp` input files). For \nexample, when using `-n 20`, the value set in `Session`/`Photons`\nis overwritten to 20; when using `-s onecubejson`, the \n`Session`/`ID` value is modified. If your JSON input file is invalid, \nMCX will quit and point out where the format is incorrect.\n\n\nUsing JSON-formatted shape description files\n-----------------------------------------------\n\nStarting from v0.7.9, MCX can also use a shape description file in the place of \nthe volume file. Using a shape-description file can save you from making a \nbinary `.bin` volume. A shape file uses more descriptive syntax and can be easily \nunderstood and shared with others.\n\nSamples on how to use the shape files are included under the example/shapetest \nfolder.\n\nThe sample shape file, `shapes.json`, is shown below:\n```\n{\n  \"MCX_Shape_Command_Help\":{\n     \"Shapes::Common Rules\": \"Shapes is an array object. The Tag field sets the voxel value for each\n         region; if Tag is missing, use 0. Tag must be smaller than the maximum media number in the\n         input file.Most parameters are in floating-point (FP). If a parameter is a coordinate, it\n         assumes the origin is defined at the lowest corner of the first voxel, unless user overwrite\n         with an Origin object. The default origin of all shapes is initialized by user's --srcfrom0\n         setting: if srcfrom0=1, the lowest corner of the 1st voxel is [0,0,0]; otherwise, it is [1,1,1]\",\n     \"Shapes::Name\": \"Just for documentation purposes, not parsed in MCX\",\n     \"Shapes::Origin\": \"A floating-point (FP) triplet, set coordinate origin for the subsequent objects\",\n     \"Shapes::Grid\": \"Recreate the background grid with the given dimension (Size) and fill-value (Tag)\",\n     \"Shapes::Sphere\": \"A 3D sphere, centered at C0 with radius R, both have FP values\",\n     \"Shapes::Box\": \"A 3D box, with lower corner O and edge length Size, both have FP values\",\n     \"Shapes::SubGrid\": \"A sub-section of the grid, integer O- and Size-triplet, inclusive of both ends\",\n     \"Shapes::XLayers/YLayers/ZLayers\": \"Layered structures, defined by an array of integer triples:\n          [start,end,tag]. Ends are inclusive in MATLAB array indices. XLayers are perpendicular to x-axis, and so on\",\n     \"Shapes::XSlabs/YSlabs/ZSlabs\": \"Slab structures, consisted of a list of FP pairs [start,end]\n          both ends are inclusive in MATLAB array indices, all XSlabs are perpendicular to x-axis, and so on\",\n     \"Shapes::Cylinder\": \"A finite cylinder, defined by the two ends, C0 and C1, along the axis and a radius R\",\n     \"Shapes::UpperSpace\": \"A semi-space defined by inequality A*x+B*y+C*z\u003eD, Coef is required, but not Equ\"\n  },\n  \"Shapes\": [\n     {\"Name\":     \"Test\"},\n     {\"Origin\":   [0,0,0]},\n     {\"Grid\":     {\"Tag\":1, \"Size\":[40,60,50]}},\n     {\"Sphere\":   {\"Tag\":2, \"O\":[30,30,30],\"R\":20}},\n     {\"Box\":      {\"Tag\":0, \"O\":[10,10,10],\"Size\":[10,10,10]}},\n     {\"Subgrid\":  {\"Tag\":1, \"O\":[13,13,13],\"Size\":[5,5,5]}},\n     {\"UpperSpace\":{\"Tag\":3,\"Coef\":[1,-1,0,0],\"Equ\":\"A*x+B*y+C*z\u003eD\"}},\n     {\"XSlabs\":   {\"Tag\":4, \"Bound\":[[5,15],[35,40]]}},\n     {\"Cylinder\": {\"Tag\":2, \"C0\": [0.0,0.0,0.0], \"C1\": [15.0,8.0,10.0], \"R\": 4.0}},\n     {\"ZLayers\":  [[1,10,1],[11,30,2],[31,50,3]]}\n  ]\n }\n```\nA shape file must contain a `Shapes` object in the root level. Other \nroot-level fields are ignored. The `Shapes` object is a JSON array, with \neach element representing a 3D object or setting. The object-class commands \ninclude `Grid`, `Sphere`, `Box` etc. Each of these object include a \nnumber of sub-fields to specify the parameters of the object. For example, the \n`Sphere` object has 3 subfields, `O`, `R` and `Tag`. Field \n`O` has a value of 1x3 array, representing the center of the sphere; \n`R` is a scalar for the radius; `Tag` is the voxel values. The most \nuseful command is `[XYZ]Layers`. It contains a series of integer \ntriplets, specifying the starting index, ending index and voxel value of a \nlayered structure. If multiple objects are included, the subsequent objects \nalways overwrite the overlapping regions covered by the previous objects.\n\nThere are a few ways for you to use shape description records in your MCX \nsimulations. You can save it to a JSON shape file, and put the file name in \nLine\\#6 of your `.inp` file, or set as the value for Domain.VolumeFile field in a \n`.json` input file. In these cases, a shape file must have a suffix of `.json`.\n\nYou can also merge the Shapes section with a `.json` input file by simply \nappending the Shapes section to the root-level object. You can find an example, \n`jsonshape_allinone.json`, under examples/shapetest. In this case, you no longer \nneed to define the `VolumeFile` field in the input.\n\nAnother way to use Shapes is to specify it using the `-P` (or `--shapes`) command \nline flag. For example:\n```\n     mcx -f input.json -P '{\"Shapes\":[{\"ZLayers\":[[1,10,1],[11,30,2],[31,60,3]]}]}'\n```\nThis will first initialize a volume based on the settings in the input `.json` \nfile, and then rasterize new objects to the domain and overwrite regions that \nare overlapping.\n\nFor both JSON-formatted input and shape files, you can use the JSONlab toolbox \n[4] to load and process in MATLAB.\n\n\nOutput data formats\n------------------------------------\n\nMCX may produces several output files depending user's simulation settings.\nOverall, MCX produces two types of outputs, 1) data accummulated within the \n3D volume of the domain (volumetric output), and 2) data stored for each detected\nphoton (detected photon data).\n\n### Volumetric output\n\nBy default, MCX stores a 4D array denoting the fluence-rate at each voxel in \nthe volume, with a dimension of Nx*Ny*Nz*Ng, where Nx/Ny/Nz are the voxel dimension\nof the domain, and Ng is the total number of time gates. The output data are\nstored in the format of single-precision floating point numbers. One may choose\nto output different physical quantities by setting the `-O` option. When the\nflag `-X/--saveref` is used, the output volume may contain the total diffuse\nreflectance only along the background-voxels adjacent to non-zero voxels. \nA negative sign is added for the diffuse reflectance raw output to distinguish\nit from the fuence data in the interior voxels.\n\nWhen photon-sharing (simultaneous simulations of multiple patterns) or photon-replay\n(the Jacobian of all source/detector pairs) is used, the output array may be extended\nto a 5D array, with the left-most/fastest index being the number of patterns Ns (in the\ncase of photon-sharing) or src/det pairs (in replay), denoted as Ns.\n\nSeveral data formats can be used to store the 3D/4D/5D volumetric output. \n\n#### mc2 files\n\nStarting in MCX v2023, `.mc2` files are no longer the default output format for\nMCX binary. Instead, JSON based JNIfTI (`.jnii`) files are used.\n\nThe `.mc2` format is simply a binary dump of the entire volumetric data output,\nconsisted of the voxel values (single-precision floating-point) of all voxels and\ntime gates. The file contains a continuous buffer of a single-precision (4-byte) \n5D array of dimension Ns\\*Nx\\*Ny\\*Nz\\*Ng, with the fastest index being the left-most \ndimension (i.e. column-major, similar to MATLAB/FORTRAN).\n\nTo load the mc2 file, one should call `loadmc2.m` and must provide explicitly\nthe dimensions of the data. This is because mc2 file does not contain the data\ndimension information.\n\nSaving to .mc2 volumetric file is depreciated as we are transitioning towards\nJNIfTI/JData formatted outputs (.jnii). \n\n#### nii files\n\nThe NIfTI-1 (.nii) format is widely used in neuroimaging and MRI community to\nstore and exchange ND numerical arrays. It contains a 352 byte header, followed\nby the raw binary stream of the output data. In the header, the data dimension\ninformation as well as other metadata is stored. \n\nA .nii output file can be generated by using `-F nii` in the command line.\n\nThe .nii file is widely supported among data processing platforms, including\nMATLAB and Python. For example\n- niftiread.m/niftiwrite in MATLAB Image Processing Toolbox\n- JNIfTI toolbox by Qianqian Fang (https://github.com/NeuroJSON/jnifti/tree/master/lib/matlab)\n- PyNIfTI for Python http://niftilib.sourceforge.net/pynifti/intro.html\n\n#### jnii files\n\nStarting in MCX v2023, JSON based JNIfTI (`.jnii`) files are used as the default\nvolumetric data output format.\n\nThe JNIfTI format represents the next-generation scientific data storage \nand exchange standard and is part of the US NIH-funded NeuroJSON initiative (https://neurojson.org)\nled by the MCX author Dr. Qianqian Fang. The NeuroJSON project aims at developing\neasy-to-parse, human-readable and easy-to-reuse data storage formats based on\nthe ubiquitously supported JSON/binary JSON formats and portable JData data annotation\nkeywords. In short, .jnii file is simply a JSON file with capability of storing \nbinary strongly-typed data with internal compression and built in metadata.\n\nThe format standard (Draft 1) of the JNIfTI file can be found at\n\nhttps://github.com/NeuroJSON/jnifti\n\nA .jnii output file can be generated by using `-F jnii` in the command line.\n\nThe .jnii file can be potentially read in nearly all programming languages \nbecause it is 100% comaptible to the JSON format. However, to properly decode\nthe ND array with built-in compression, one should call JData compatible\nlibraries, which can be found at https://neurojson.org/#software\n\nSpecifically, to parse/save .jnii files in MATLAB, you should use\n- JSONLab for MATLAB (https://neurojson.org/download/jsonlab) or install `octave-jsonlab` on Fedora/Debian/Ubuntu\n- `jsonencode/jsondecode` in MATLAB + `jdataencode/jdatadecode` from JSONLab (https://neurojson.org/download/jsonlab)\n\nTo parse/save .jnii files in Python, you should use\n- PyJData module (https://neurojson.org/download/pyjdata) or install `python3-jdata` on Debian/Ubuntu\n\nIn Python, the volumetric data is loaded as a `dict` object where `data['NIFTIData']` \nis a NumPy `ndarray` object storing the volumetric data.\n\n\n#### bnii files\n\nThe binary JNIfTI file is also part of the JNIfTI specification and the NeuroJSON\nproject. In comparison to text-based JSON format, .bnii files can be much smaller\nand faster to parse. The .bnii format is also defined in the BJData specification\n\nhttps://github.com/NeuroJSON/bjdata\n\nand is the binary interface to .jnii. A .bnii output file can be generated by \nusing `-F bnii` in the command line.\n\nThe .bnii file can be potentially read in nearly all programming languages \nbecause it was based on UBJSON (Universal Binary JSON). However, to properly decode\nthe ND array with built-in compression, one should call JData compatible\nlibraries, which can be found at https://neurojson.org/#software\n\nSpecifically, to parse/save .jnii files in MATLAB, you should use one of\n- JSONLab for MATLAB (https://neurojson.org/download/jsonlab) or install `octave-jsonlab` on Fedora/Debian/Ubuntu\n- `jsonencode/jsondecode` in MATLAB + `jdataencode/jdatadecode` from JSONLab (https://neurojson.org/download/jsonlab)\n\nTo parse/save .jnii files in Python, you should use\n- PyJData module (https://neurojson.org/download/pyjdata) or install `python3-jdata` on Debian/Ubuntu\n\nIn Python, the volumetric data is loaded as a `dict` object where `data['NIFTIData']` \nis a NumPy `ndarray` object storing the volumetric data.\n\n### Detected photon data\n\nIf one defines detectors, MCX is able to store a variety of photon data when a photon\nis captured by these detectors. One can selectively store various supported data fields,\nincluding partial pathlengths, exit position and direction, by using the `-w/--savedetflag`\nflag. The storage of detected photon information is enabled by default, and can be\ndisabled using the `-d` flag.\n\nThe detected photon data are stored in a separate file from the volumetric output.\nThe supported data file formats are explained below.\n\n#### mch files\n\nThe .mch file, or MC history file, is stored by default, but we strongly encourage users\nto adpot the newly implemented JSON/.jdat format for easy data sharing. \n\nThe .mch file contains a 256 byte binary header, followed by a 2-D numerical array\nof dimensions `#savedphoton * #colcount` as recorded in the header.\n```\ntypedef struct MCXHistoryHeader{\n\tchar magic[4];                 // magic bits= 'M','C','X','H'\n\tunsigned int  version;         // version of the mch file format \n\tunsigned int  maxmedia;        // number of media in the simulation \n\tunsigned int  detnum;          // number of detectors in the simulation \n\tunsigned int  colcount;        // how many output files per detected photon \n\tunsigned int  totalphoton;     // how many total photon simulated \n\tunsigned int  detected;        // how many photons are detected (not necessarily all saved) \n\tunsigned int  savedphoton;     // how many detected photons are saved in this file \n\tfloat unitinmm;                // what is the voxel size of the simulation\n\tunsigned int  seedbyte;        // how many bytes per RNG seed\n\tfloat normalizer;              // what is the normalization factor\n\tint respin;                    // if positive, repeat count so total photon=totalphoton*respin; if negative, total number is processed in respin subset \n\tunsigned int  srcnum;          // number of sources for simultaneous pattern sources \n\tunsigned int  savedetflag;     // number of sources for simultaneous pattern sources \n    unsigned int  totalsource;     // total source number when multiple sources are defined\n\tint reserved[1];               // reserved fields for future extension \n} History;\n```\nWhen the `-q` flag is set to 1, the detected photon initial seeds are also stored\nfollowing the detected photon data, consisting of a 2-D byte array of `#savedphoton * #seedbyte`.\n\nTo load the mch file, one should call `loadmch.m` in MATLAB/Octave.\n\nSaving to .mch history file is depreciated as we are transitioning towards\nJSON/JData formatted outputs (`.jdat`).\n\n#### jdat files\n\nWhen `-F jnii` is specified, instead of saving the detected photon into the legacy .mch format,\na .jdat file is written, which is a pure JSON file. This file contains a hierachical data\nrecord of the following JSON structure\n````\n{\n   \"MCXData\":{\n       \"Info\":{\n           \"Version\":\n           \"MediaNum\":\n           \"DetNum\":\n           ...\n           \"Media\":{\n               ...\n           }\n       },\n       \"PhotonData\":{\n           \"detid\":\n           \"nscat\":\n           \"ppath\":\n           \"mom\":\n           \"p\":\n           \"v\":\n           \"w0\":\n       },\n       \"Trajectory\":{\n           \"photonid\":\n           \"p\":\n           \"w0\":\n       },\n       \"Seed\":[\n           ...\n       ]\n   }\n}\n````\nwhere \"Info\" is required, and other subfields are optional depends on users' input.\nEach subfield in this file may contain JData 1-D or 2-D array constructs to allow \nstoring binary and compressed data.\n\nAlthough .jdat and .jnii have different suffix, they are both JSON/JData files and\ncan be opened/written by the same JData compatible libraries mentioned above, i.e.\n\nFor MATLAB\n- JSONLab for MATLAB (https://neurojson.org/download/jsonlab) or install `octave-jsonlab` on Fedora/Debian/Ubuntu\n- `jsonencode/jsondecode` in MATLAB + `jdataencode/jdatadecode` from JSONLab (https://neurojson.org/download/jsonlab)\n\nFor Python\n- PyJData module (https://neurojson.org/download/pyjdata) or install `python3-jdata` on Debian/Ubuntu\n\nIn Python, the volumetric data is loaded as a `dict` object where `data['MCXData']['PhotonData']` \nstores the photon data, `data['MCXData']['Trajectory']` stores the trajectory data etc.\n\n\n### Photon trajectory data\n\nFor debugging and plotting purposes, MCX can output photon trajectories, as polylines,\nwhen `-D M` flag is attached, or mcxlab is asked for the 5th output. Such information\ncan be stored in one of the following formats.\n\n#### mct files\n\nBy default, MCX stores the photon trajectory data in to a .mct file MC trajectory, which\nuses the same binary format as .mch but renamed as .mct. This file can be loaded to\nMATLAB using the same `loadmch.m` function. \n\nUsing .mct file is depreciated and users are encouraged to migrate to .jdat file\nas described below.\n\n#### jdat files\n\nWhen `-F jnii` is used, MCX merges the trajectory data with the detected photon and\nseed data and saved as a JSON-compatible .jdat file. The overall structure of the\n.jdat file as well as the relevant parsers can be found in the above section.\n\n\nUsing MCXLAB in MATLAB and Octave\n------------------------------------\n\nMCXLAB is the native MEX version of MCX for MATLAB and GNU Octave. It includes \nthe entire MCX code in a MEX function which can be called directly inside \nMATLAB or Octave. The input and output files in MCX are replaced by convenient \nin-memory struct variables in MCXLAB, thus, making it much easier to use and \ninteract. MATLAB/Octave also provides convenient plotting and data analysis \nfunctions. With MCXLAB, your analysis can be streamlined and simplified without \ninvolving disk files.\n\nPlease read the `mcxlab/README.txt` file for more details on how to install and \nuse MCXLAB.\n\nPlease also browse this interactive [Jupyter Notebook based MCXLAB tutorial](https://colab.research.google.com/github/fangq/mcx/blob/master/mcxlab/tutorials/mcxlab_getting_started.ipynb)\nto see a suite of examples showing the key functionalities of MCXLAB (using GNU Octave).\n\n\nUsing PMCX in Python\n------------------------------------\n\nPMCX is the native binary binding of MCX for Python 3.6 or newer. Similar to\nMCXLAB, PMCX can run GPU-based simulations inside Python environment with\nefficient in-memory inputs and outputs. \n\nPlease read the `pmcx/README.txt` file for more details on how to install and \nuse PMCX.\n\nPlease also browse this interactive [Jupyter Notebook based PMCX tutorial](https://colab.research.google.com/github/fangq/mcx/blob/master/pmcx/tutorials/pmcx_getting_started.ipynb)\nto see a suite of examples showing the key functionalities of PMCX.\n\n\nUsing MCX Studio GUI\n-----------------------\n\nMCX Studio is a graphics user interface (GUI) for MCX. It gives users a \nstraightforward way to set the command line options and simulation parameters. \nIt also allows users to create different simulation tasks and organize them \ninto a project and save for later use. MCX Studio can be run on many platforms \nsuch as Windows, GNU Linux and Mac OS.\n\nTo use MCX Studio, it is suggested to put the mcxstudio binary in the same \ndirectory as the mcx command; alternatively, you can also add the path to mcx \ncommand to your PATH environment variable.\n\nOnce launched, MCX Studio will automatically check if mcx binary is in the \nsearch path, if so, the “GPU” button in the toolbar will be enabled. It is \nsuggested to click on this button once, and see if you can see a list of GPUs \nand their parameters printed in the output field at the bottom part of the \nwindow. If you are able to see this information, your system is ready to run \nMCX simulations. If you get error messages or not able to see any usable GPU, \nplease check the following:\n\n-   are you running MCX Studio/MCX on a computer with a supported card?\n-   have you installed the CUDA/NVIDIA drivers correctly?\n-   did you put mcx in the same folder as mcxstudio or add its path to PATH?\n\nIf your system has been properly configured, you can now add new simulations by \nclicking the “New” button. MCX Studio will ask you to give a session ID \nstring for this new simulation. Then you are allowed to adjust the parameters \nbased on your needs. Once you finish the adjustment, you should click the \n“Verify” button to see if there are missing settings. If everything looks \nfine, the “Run” button will be activated. Click on it once will start your \nsimulation. If you want to abort the current simulation, you can click the \n“Stop” button.\n\nYou can create multiple tasks with MCX Studio by hitting the “New” button \nagain. The information for all session configurations can be saved as a project \nfile (with .mcxp extension) by clicking the “Save” button. You can load a \npreviously saved project file back to MCX Studio by clicking the “Load” \nbutton.\n\n\nInterpreting the Output\n--------------------------\n\nMCX output consists of two parts, the flux volume file and messages printed on \nthe screen.\n\n### Output files\n\nAn mc2 file contains the fluence-rate distribution from the simulation in the \ngiven medium. By default, this fluence-rate is a normalized solution (as \nopposed to the raw probability) therefore, one can compare this directly to the \nanalytical solutions (i.e. Green's function). The order of storage in the mc2 \nfiles is the same as the input file: i.e., if the input is row-major, the \noutput is row-major, and so on. The dimensions of the file are Nx, Ny, Nz, and \nNg where Ng is the total number of time gates.\n\nBy default, MCX produces the **Green's function** of the **fluence rate** for \nthe given domain and source. Sometime it is also known as the time-domain \n“two-point” function. If you run MCX with the following command\n\n      mcx -f input.inp -s output ....\n\nthe fluence-rate data will be saved in a file named “output.dat” under the \ncurrent folder. If you run MCX without `-s output`, the output file will be \nnamed as `input.inp.dat`.\n\nTo understand this further, you need to know that a **fluence-rate (Phi(r,t))** \nis measured by number of particles passing through an infinitesimal spherical \nsurface per **unit time** at **a given location** regardless of directions. The \nunit of the MCX output is “W/mm\u003csup\u003e2\u003c/sup\u003e = J/(mm\u003csup\u003e2\u003c/sup\u003es)”, if it is \ninterpreted as the “energy fluence-rate” [6], or \n“1/(mm\u003csup\u003e2\u003c/sup\u003es)”, if the output is interpreted as the “particle \nfluence-rate” [6].\n\nThe Green's function of the fluence-rate means that it is produced by a \n**unitary source**. In simple terms, this represents the fraction of \nparticles/energy that arrives a location per second under **the radiation of 1 \nunit (packet or J) of particle or energy at time t=0**. The Green's function is \ncalculated by a process referred to as the “normalization” in the MCX code \nand is detailed in the MCX paper [6] (MCX and MMC outputs share the same \nmeanings).\n\nPlease be aware that the output flux is calculated at each time-window defined \nin the input file. For example, if you type\n\n     0.e+00 5.e-09 1e-10  # time-gates(s): start, end, step\n\nin the 5th row in the input file, MCX will produce 50 fluence-rate snapshots, \ncorresponding to the time-windows at [0 0.1] ns, [0.1 0.2]ns ... and \n[4.9,5.0] ns. To convert the fluence rate to the fluence for each \ntime-window, you just need to multiply each solution by the width of the \nwindow, 0.1 ns in this case. To convert the time-dependent fluence-rate to \ncontinuous-wave (CW) fluence (fluence in short), you need to integrate the \nfluence-rate along the time dimension. Assuming the fluence-rate after 5 ns is \nnegligible, then the CW fluence is simply `sum(flux_i*0.1 ns, i=1,50)`. You can \nread `mcx/examples/validation/plotsimudata.m` and \n`mcx/examples/sphbox/plotresults.m` for examples to compare an MCX output with \nthe analytical fluence-rate/fluence solutions.\n\nOne can load an `.mc2` output file into Matlab or Octave using the loadmc2 \nfunction in the `{mcx root}/utils` folder.\n\nTo get a continuous-wave solution, run a simulation with a sufficiently long \ntime window, and sum the flux along the time dimension, for example\n\n       mcx=loadmc2('output.mc2',[60 60 60 10],'float');\n       cw_mcx=sum(mcx,4);\n\nNote that for time-resolved simulations, the corresponding solution in the \nresults approximates the flux at the center point of each time window. For \nexample, if the simulation time window setting is \n`[t0,t0+dt,t0+2dt,t0+3dt...,t1]`, the time points for the snapshots stored in \nthe solution file is located at `[t0+dt/2, t0+3*dt/2, t0+5*dt/2, ... ,t1-dt/2]`\n\nA more detailed interpretation of the output data can be found at \nhttp://mcx.sf.net/cgi-bin/index.cgi?MMC/Doc/FAQ#How_do_I_interpret_MMC_s_output_data\n\nMCX can also output “current density” (J(r,t), unit W/m^2, same as \nPhi(r,t)) - referring to the expected number of photons or Joule of energy \nflowing through a unit area pointing towards a particular direction per unit \ntime. The current density can be calculated at the boundary of the domain by \ntwo means:\n\n1.  using the detected photon partial path output (i.e. the second output of \n  mcxlab.m),\n  one can compute the total energy E received by a detector, then one can divide \n  E by the area/aperture of the detector to obtain the J(r) at a detector (E \n  should be calculated as a function of t by using the time-of-fly of detected \n  photons, the E(t)/A gives J(r,t); if you integrate all time gates, the total \n  E/A gives the current I(r), instead of the current density).\n2.  use `-X 1` or `--saveref/cfg.issaveref` option in mcx to enable the\n  diffuse reflectance recordings on the boundary. the diffuse reflectance is \n  represented by the current density J(r) flowing outward from the domain.\n\nThe current density has, as mentioned, the same unit as fluence rate, but the \ndifference is that `J(r,t)` is a vector, and Phi(r,t) is a scalar. Both measuring \nthe energy flow across a small area (the are has direction in the case of J) \nper unit time.\n\nYou can find more rigorous definitions of these quantities in Lihong Wang's \nBiomedical Optics book, Chapter 5.\n\n### Console print messages\n\nTiming information is printed on the screen (stdout). The clock starts (at time \nT0) right before the initialization data is copied from CPU to GPU. For each \nsimulation, the elapsed time from T0 is printed (in ms). Also the accumulated \nelapsed time is printed for all memory transaction from GPU to CPU.\n\nWhen a user specifies `-D P` in the command line, or set \n`cfg.debuglevel='P'`, MCX or MCXLAB prints a progress bar showing the percentage \nof completition.\n\n\n\nBest practices guide\n-----------------------\n\nTo maximize MCX's performance on your hardware, you should follow the best \npractices guide listed below:\n\n### Use a middle-range or enthusiastic-grade GPU, use multiple of them if possible\n\nMCX is highly scalable, providing linear-speedup as long as you provide the\nGPU cores it can use. As a result, the better the GPU you use, the higher the speed\nyou can get. An enthusiastic-grade GPU, such as RTX 4070Ti (~$700), can be 12x\nfaster than an low-end laptop RTX 4050 GPU even within the same generation.\n\nMCX can readily take advantage of multiple GPUs if you have it installed. The\nMCX simulation speed scales nearly linearly as the number of GPUs increases.\nSo, to maximize MCX performance, get at least a middle-level or high-end consumer\ngrade GPU; if you need more speed, throw in more GPUs will cut down the runtime.\n\n### Launch as many threads as possible\n\nIt has been shown that MCX's speed is related to the thread number (-t). \nGenerally, the more threads, the better speed, until all GPU resources are \nfully occupied. For higher-end GPUs, a thread number over 10,000 is \nrecommended. Please use the autopilot mode, `-A`, to let MCX determine the \n“optimal” thread number when you are not sure what to use.\n\n\n\nAcknowledgement\n------------------\n\nMCX contains modified versions of the below source codes from other \nopen-source projects (with a compatible license).\n\n### cJSON library by Dave Gamble\n\n- Files: src/cJSON folder\n- Copyright (c) 2009 Dave Gamble\n- URL: https://github.com/DaveGamble/cJSON\n- License: MIT License, https://github.com/DaveGamble/cJSON/blob/master/LICENSE\n\n### GLScene library for Lazarus by GLScene developers\n\n- Files: mcxstudio/glscene/*\n- Copyright (c) GLScene developers\n- URL: http://glscene.org, https://sourceforge.net/p/glscene/code/HEAD/tree/branches/GLSceneLCL/\n- License: Mozilla Public License 2.0 (MPL-2), https://sourceforge.net/p/glscene/code/HEAD/tree/trunk/LICENSE\n- Comment: \n  A subset of the GLSceneLCL branch is included as part of the MCX source code tree\n  to allow compilation of the MCX Studio binary on various platforms without\n  needing to install the full package.\n\n### Texture3D sample project by Jürgen Abel\n\n- Files: mcx/src/mcxstudio/mcxview.pas\n- Copyright (c) 2003 Jürgen Abel\n- License: Mozilla Public License 2.0 (MPL-2), https://sourceforge.net/p/glscene/code/HEAD/tree/trunk/LICENSE\n- Comment: \n  The MCX volume renderer (mcxviewer) was adapted based on the Texture3D Example \n  provided by the GLScene Project (http://glscene.org). The original author of \n  this example is Jürgen Abel. \n\n### Synapse communication library for Lazarus\n\n- Files: mcxstudio/synapse/*\n- Copyright (c) 1999-2017, Lukas Gebauer\n- URL: http://www.ararat.cz/synapse/\n- License: MIT License or LGPL version 2 or later or GPL version 2 or later\n- Comment:\n  A subset of the Synapse units is included as part of the MCX source code tree\n  to allow compilation of the MCX Studio binary on various platforms without\n  needing to install the full package.\n\n### ZMat data compression unit\n\n- Files: src/zmat/*\n- Copyright: 2019-2023 Qianqian Fang\n- URL: https://github.com/fangq/zmat\n- License: GPL version 3 or later, https://github.com/fangq/zmat/blob/master/LICENSE.txt\n\n### LZ4 data compression library\n\n- Files: src/zmat/lz4/*\n- Copyright: 2011-2020, Yann Collet\n- URL: https://github.com/lz4/lz4\n- License: BSD-2-clause, https://github.com/lz4/lz4/blob/dev/lib/LICENSE\n\n### LZMA/Easylzma data compression library\n\n- Files: src/zmat/easylzma/*\n- Copyright: 2009, Lloyd Hilaiel, 2008, Igor Pavlov\n- License: public-domain\n- Comment:\n All the cruft you find here is public domain.  You don't have to\n credit anyone to use this code, but my personal request is that you mention\n Igor Pavlov for his hard, high quality work.\n\n### myslicer toolbox by Anders Brun\n\n- Files: utils/{islicer.m, slice3i.m, image3i.m}\n- Copyright (c) 2009 Anders Brun, anders@cb.uu.se\n- URL: https://www.mathworks.com/matlabcentral/fileexchange/25923-myslicer-make-mouse-interactive-slices-of-a-3-d-volume\n- License: BSD-3-clause License, https://www.mathworks.com/matlabcentral/fileexchange/25923-myslicer-make-mouse-interactive-slices-of-a-3-d-volume#license_modal\n\n### MCX Filter submodule\n\n- Files: filter/*\n- Copyright (c) 2018 Yaoshen Yuan, 2018 Qianqian Fang\n- URL: https://github.com/fangq/GPU-ANLM/\n- License: MIT License, https://github.com/fangq/GPU-ANLM/blob/master/LICENSE.txt\n\n### pymcx Python module\n\n- Files: pymcx/*\n- Copyright (c) 2020  Maxime Baillot \u003cmaxime.baillot.1 at ulaval.ca\u003e\n- URL: https://github.com/fangq/GPU-ANLM/\n- License: GPL version 3 or later, https://github.com/4D42/pymcx/blob/master/LICENSE.txt\n\n### Pybind11\n- Files: src/pybind11/*\n- Copyright (c) 2016 Wenzel Jakob \u003cwenzel.jakob@epfl.ch\u003e\n- URL: https://github.com/pybind/pybind11/\n- License: BSD-style license, https://github.com/pybind/pybind11/blob/master/LICENSE\n\nReference\n------------\n\n- [Fang2009] Qianqian Fang and David A. Boas, \"Monte Carlo Simulation of \n  Photon Migration in 3D Turbid Media Accelerated by Graphics Processing Units,\" \n  Optics Express, vol. 17, issue 22, pp. 20178-20190 (2009).\n\n- [Yu2018] Leiming Yu, Fanny Nina-Paravecino, David Kaeli, Qianqian Fang, \n  “Scalable and massively parallel Monte Carlo photon transport simulations \n  for heterogeneous computing platforms,” J. Biomed. Opt. 23(1), 010504 (2018).\n\n- [Yan2020] Shijie Yan and Qianqian Fang* (2020), \"Hybrid mesh and voxel \n  based Monte Carlo algorithm for accurate and efficient photon transport \n  modeling in complex bio-tissues,\" Biomed. Opt. Express, 11(11) pp. 6262-6270.\n  https://www.osapublishing.org/boe/abstract.cfm?uri=boe-11-11-6262\n\nIf you use MCX in your research, the author of this software would like you to \ncite the above papers in your related publications.\n\nLinks:\n\n- [1] http://developer.nvidia.com/cuda-downloads\n- [2] http://www.nvidia.com/object/cuda_gpus.html\n- [3] http://en.wikipedia.org/wiki/Row-major_order\n- [4] https://neurojson.org/jsonlab\n- [5] http://science.jrank.org/pages/60024/particle-fluence.html\n- [6] http://www.opticsinfobase.org/oe/abstract.cfm?uri=oe-17-22-20178\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffangq%2Fmcx","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffangq%2Fmcx","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffangq%2Fmcx/lists"}