├── .git_filters ├── rcs-keywords.clean └── rcs-keywords.smudge ├── .gitattributes ├── .travis.yml ├── AUTHORS.txt ├── ChangeLog.txt ├── LICENSE.txt ├── README.md ├── README.txt ├── TODO.txt ├── deploy └── buildmcxcl.sh ├── doc ├── Download.txt ├── INSTALL.txt ├── MCXCL_Workflow.pdf ├── gendoc.sh ├── mcx_command_option_cheatsheet.xlsx └── mcxcl_benchmark.png ├── example ├── README.txt ├── benchmark │ ├── benchmark1.json │ ├── benchmark3.json │ ├── cubic60.json │ ├── run_benchmark1.bat │ ├── run_benchmark1.sh │ ├── run_benchmark2.bat │ ├── run_benchmark2.sh │ ├── run_benchmark2a.sh │ ├── run_benchmark3.bat │ └── run_benchmark3.sh ├── colin27 │ ├── README.txt │ ├── dump_json.bat │ ├── dump_json.sh │ ├── dump_volume.bat │ ├── dump_volume.sh │ ├── run_atlas.bat │ └── run_atlas.sh ├── digimouse │ ├── README.txt │ ├── digimouse.json │ ├── dump_volume.bat │ ├── dump_volume.sh │ ├── run_atlas.bat │ └── run_atlas.sh ├── mcxcl_demo.mcxp ├── quicktest │ ├── README.txt │ ├── cubic60.json │ ├── listgpu.bat │ ├── listgpu.sh │ ├── qtest.inp │ ├── qtest.json │ ├── run_qtest.bat │ ├── run_qtest.sh │ └── run_qtest_silent.sh ├── skinvessel │ ├── README.txt │ ├── disable_hyper.sh │ ├── enable_hyper.sh │ ├── mcxyz_bench.json │ ├── run_mcxyz_bench.bat │ ├── run_mcxyz_bench.sh │ └── skinvessel.json ├── usc19-5 │ ├── README.txt │ ├── USC_19-5_atlas.json │ ├── dump_volume.bat │ ├── dump_volume.sh │ ├── run_atlas.bat │ └── run_atlas.sh └── validation │ ├── README.txt │ ├── cubic60.json │ ├── plotsimudata.m │ ├── run_validation.bat │ ├── run_validation.sh │ ├── run_validation_b.bat │ ├── run_validation_b.sh │ ├── validation.inp │ ├── validation_b.inp │ ├── validation_dark.inp │ └── validation_dark_b.inp ├── gitlog.sh ├── mcxlabcl ├── INSTALL.txt ├── LICENSE.txt ├── README.txt ├── examples │ ├── colin27_v3.mat │ ├── demo_4layer_head.m │ ├── demo_colin27_atlas.m │ ├── demo_continuous_mua_mus.m │ ├── demo_digimouse_sfdi.m │ ├── demo_focus_mirror_bc.m │ ├── demo_fullhead_atlas.m │ ├── demo_infinite_slab_cyclic_bc.m │ ├── demo_lambertian_exit_angle.m │ ├── demo_mcxlab_2d.m │ ├── demo_mcxlab_basic.m │ ├── demo_mcxlab_replay.m │ ├── demo_mcxlab_srctype.m │ ├── demo_mcxlabcl_basic.m │ ├── demo_mcxyz_skinvessel.m │ ├── demo_photon_sharing.m │ ├── demo_qtest_subpixel.m │ ├── demo_replay_timedomain.m │ ├── demo_replay_vs_pmc_timedomain.m │ ├── demo_sphere_cube_subpixel.m │ ├── demo_test_csf.m │ ├── demo_validation_heterogeneous.m │ ├── demo_validation_homogeneous.m │ ├── digimouse.mat │ ├── fullhead_atlas.mat │ ├── mcx_gpu_benchmarks.m │ ├── mcx_gpu_contest.m │ └── mcxyz_skinvessel.mat ├── json2mcx.m ├── mcx2json.m ├── mcxdetphoton.m └── mcxlabcl.m ├── setup └── win64 │ ├── apply_timeout_registry_fix.bat │ └── launch_timeout_registry_fix.reg ├── speedcontest └── mcxcontest ├── src ├── Makefile ├── buildmcxcl.m ├── cjson │ ├── README │ ├── cJSON.c │ └── cJSON.h ├── mcextreme.h ├── mcx_bench.h ├── mcx_const.h ├── mcx_core.cl ├── mcx_host.cpp ├── mcx_host.hpp ├── mcx_shapes.c ├── mcx_shapes.h ├── mcx_test_nextafter.cl ├── mcx_utils.c ├── mcx_utils.h ├── mcxcl.c ├── mcxlabcl.cpp ├── mexopts_msys2_gcc.xml ├── mingw64 │ └── include │ │ ├── CL │ │ ├── cl.h │ │ ├── cl_d3d10.h │ │ ├── cl_d3d11.h │ │ ├── cl_dx9_media_sharing.h │ │ ├── cl_dx9_media_sharing_intel.h │ │ ├── cl_egl.h │ │ ├── cl_ext.h │ │ ├── cl_ext_intel.h │ │ ├── cl_gl.h │ │ ├── cl_gl_ext.h │ │ ├── cl_platform.h │ │ ├── cl_va_api_media_sharing_intel.h │ │ └── opencl.h │ │ ├── _ansi.h │ │ ├── features.h │ │ ├── ieee754.h │ │ └── sys │ │ ├── ioctl.h │ │ └── termios.h ├── nifti1.h ├── tictoc.c ├── tictoc.h ├── ubj │ ├── LICENSE │ ├── Makefile │ ├── README.md │ ├── ubj.h │ ├── ubj_internal.h │ ├── ubjr.c │ ├── ubjrw.c │ └── ubjw.c ├── vector_types.h └── zmat │ ├── Makefile │ ├── easylzma │ ├── Makefile │ ├── README │ ├── common_internal.c │ ├── common_internal.h │ ├── compress.c │ ├── decompress.c │ ├── easylzma │ │ ├── common.h │ │ ├── compress.h │ │ └── decompress.h │ ├── lzip_header.c │ ├── lzip_header.h │ ├── lzma_header.c │ ├── lzma_header.h │ └── pavlov │ │ ├── 7zBuf.c │ │ ├── 7zBuf.h │ │ ├── 7zBuf2.c │ │ ├── 7zCrc.c │ │ ├── 7zCrc.h │ │ ├── 7zFile.c │ │ ├── 7zFile.h │ │ ├── 7zStream.c │ │ ├── 7zVersion.h │ │ ├── Alloc.c │ │ ├── Alloc.h │ │ ├── Bcj2.c │ │ ├── Bcj2.h │ │ ├── Bra.c │ │ ├── Bra.h │ │ ├── Bra86.c │ │ ├── BraIA64.c │ │ ├── CpuArch.h │ │ ├── LzFind.c │ │ ├── LzFind.h │ │ ├── LzHash.h │ │ ├── LzmaDec.c │ │ ├── LzmaDec.h │ │ ├── LzmaEnc.c │ │ ├── LzmaEnc.h │ │ ├── LzmaLib.c │ │ ├── LzmaLib.h │ │ └── Types.h │ ├── lz4 │ ├── lz4.c │ ├── lz4.h │ ├── lz4hc.c │ └── lz4hc.h │ ├── zmat.cpp │ ├── zmatlib.c │ └── zmatlib.h ├── test └── testmcx.sh └── utils ├── cwdiffusion.m ├── getdistance.m ├── hobbysplines.m ├── image3i.m ├── islicer.m ├── loadmc2.m ├── loadmch.m ├── mcxdcsg1.m ├── mcxdettime.m ├── mcxdettpsf.m ├── mcxdetweight.m ├── mcxfluence2energy.m ├── mcxloadfile.m ├── mcxloadnii.m ├── mcxmeanpath.m ├── mcxmeanscat.m ├── mcxplotphotons.m ├── mcxplotvol.m ├── normalizemcx.m ├── python └── __init__.py ├── serialcorr.m ├── slice3i.m ├── stacked_bar3.m └── tddiffusion.m /.git_filters/rcs-keywords.clean: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl -p 2 | # 3 | # @brief Git filter to implement rcs keyword expansion as seen in cvs and svn. 4 | # @author Martin Turon 5 | # 6 | # Copyright (c) 2009-2011 Turon Technologies, Inc. All rights reserved. 7 | 8 | s/(\$Id)((::)*)([^\$]*)\$/TR($1,$4,$2)/eo; 9 | s/(\$Date)((::)*)([^\$]*)\$/TR($1,$4,$2)/eo; 10 | s/(\$Author)((::)*)([^\$]*)\$/TR($1,$4,$2)/eo; 11 | s/(\$Source)((::)*)([^\$]*)\$/TR($1,$4,$2)/eo; 12 | s/(\$File)((::)*)([^\$]*)\$/TR($1,$4,$2)/eo; 13 | s/(\$Rev)((::)*)([^\$]*)\$/TR($1,$4,$2)/eo; 14 | s/(\$Revision)((::)*)([^\$]*)\$/TR($1,$4,$2)/eo; 15 | 16 | sub TR{ 17 | my ($pre,$from,$fix)=@_; 18 | return $pre.$fix.(" " x length($from)).'$'; 19 | } 20 | -------------------------------------------------------------------------------- /.git_filters/rcs-keywords.smudge: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | # 3 | # @brief Git filter to implement rcs keyword expansion as seen in cvs and svn. 4 | # @author Martin Turon 5 | # 6 | # Usage: 7 | # .git_filter/rcs-keywords.smudge file_path < file_contents 8 | # 9 | # To add keyword expansion: 10 | # /.gitattributes - *.c filter=rcs-keywords 11 | # /.git_filters/rcs-keywords.smudge - copy this file to project 12 | # /.git_filters/rcs-keywords.clean - copy companion to project 13 | # ~/.gitconfig - add [filter] lines below 14 | # 15 | # [filter "rcs-keywords"] 16 | # clean = .git_filters/rcs-keywords.clean 17 | # smudge = .git_filters/rcs-keywords.smudge %f 18 | # 19 | # Copyright (c) 2009-2011 Turon Technologies, Inc. All rights reserved. 20 | 21 | $path = shift; 22 | $path =~ /.*\/(.*)/; 23 | $filename = $1; 24 | 25 | if (0 == length($filename)) { 26 | $filename = $path; 27 | } 28 | 29 | # Need to grab filename and to use git log for this to be accurate. 30 | $rev = `git log --date=iso -- | head -n 3`; 31 | $rev =~ /^Author:\s*(.*)\s*$/m; 32 | $author = $1; 33 | $author =~ /\s*(.*)\s*<.*/; 34 | $name = $1; 35 | $rev =~ /^Date:\s*(.*)\s*$/m; 36 | $date = $1; 37 | $rev =~ /^commit (.*)$/m; 38 | $ident = $1; 39 | $shortident = substr($ident,0, 6); 40 | 41 | while () { 42 | s/\$Date(((::)*)[^\$]*)\$/TR("\$Date",$1,$date,$2,"\$")/eo; 43 | s/\$Author(((::)*)[^\$]*)\$/TR("\$Author",$1,$author,$2,"\$")/eo; 44 | s/\$Id(((::)*)[^\$]*)\$/TR("\$Id",$1,"$filename | $date | $name",$2,"\$")/eo; 45 | s/\$File(((::)*)[^\$]*)\$/TR("\$File",$1,$filename,$2,"\$")/eo; 46 | s/\$Source(((::)*)[^\$]*)\$/TR("\$Source",$1,$path,$2,"\$")/eo; 47 | s/\$Rev(((::)*)[^\$]*)\$/TR("\$Rev",$1,$shortident,$2,"\$")/eo; 48 | s/\$Revision(((::)*)[^\$]*)\$/TR("\$Revision",$1,$ident,$2,"\$")/eo; 49 | } continue { 50 | print or die "-p destination: $!\n"; 51 | } 52 | 53 | sub TR{ 54 | my ($pre,$from,$to,$fix,$post)=@_; 55 | return $pre.$to.$post if($fix eq ''); 56 | 57 | $pre.=$fix; 58 | if(length($from) 10 | 11 | MCX-CL Website : http://mcx.space/mcxcl 12 | MCX Wiki: http://mcx.space/wiki 13 | Source Code: http://github.com/fangq/mcxcl -------------------------------------------------------------------------------- /TODO.txt: -------------------------------------------------------------------------------- 1 | = MCX TODO list = 2 | 3 | == Short term projects == 4 | 5 | == Long term projects == 6 | 7 | == Completed == 8 | 9 | [done] *. fluorescent material support via pattern3d source [2009/09/30, FangQ] 10 | [done] *. results does not repeat with identical random number seed, need to check [2009/04/07, FangQ] 11 | [done] *. normalizing the solution with -U option. [2009/04/07, FangQ] 12 | [done] *. hardware/driver check and inform users for actions [2009/04/30, FangQ] 13 | [done] *. code cleaning [2009/09/24, FangQ] 14 | [done] *. compile on windows [2009/09/30, FangQ] 15 | [done] *. crate a GUI for MCX [2009/09/30, FangQ] 16 | [done] *. save photon history info at detector sites [2009/04/30, FangQ] (experimental) 17 | [done] *. multiple-GPU support [2009/09/30, FangQ] 18 | [done] * port momentum transfer for DCS from mcx to mcxcl [2019/3/2, FangQ] 19 | [done] *port photon replay from mcx to mcxcl [2019/3/2, FangQ] 20 | [done] *port photon sharing from mcx to mcxcl [2019/3/2, FangQ] 21 | [done] *port trajectory data output from mcx to mcxcl [2019/3/2, FangQ] 22 | [done] *port new detected photon output data format from mcx to mcxcl [2019/3/2, FangQ] 23 | -------------------------------------------------------------------------------- /doc/MCXCL_Workflow.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jishanshaikh4/mcxcl/4c1830589e2e4615782e036c994a7e4688357b15/doc/MCXCL_Workflow.pdf -------------------------------------------------------------------------------- /doc/gendoc.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # commands to update the document pages from homepage 4 | 5 | ROOTURL="http://mcx.space/wiki/index.cgi?embed=1&keywords" 6 | 7 | lynx -dump "$ROOTURL=MCXCL" > Download.txt 8 | lynx -dump "$ROOTURL=Workshop/MCX18Preparation/MethodA" > INSTALL.txt 9 | 10 | wget http://mcx.space/wiki/upload/mcxcl_benchmark_0118.png -Omcxcl_benchmark.png 11 | 12 | -------------------------------------------------------------------------------- /doc/mcx_command_option_cheatsheet.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jishanshaikh4/mcxcl/4c1830589e2e4615782e036c994a7e4688357b15/doc/mcx_command_option_cheatsheet.xlsx -------------------------------------------------------------------------------- /doc/mcxcl_benchmark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jishanshaikh4/mcxcl/4c1830589e2e4615782e036c994a7e4688357b15/doc/mcxcl_benchmark.png -------------------------------------------------------------------------------- /example/README.txt: -------------------------------------------------------------------------------- 1 | = README for examples = 2 | 3 | In this folder, you will find a number of examples 4 | to validate, test, or demonstrate the functionalities 5 | of MCXCL. 6 | 7 | Please read the README.txt file for each sub-folder 8 | to understand the purpose, procedures to run and 9 | the interpretation of the results. 10 | -------------------------------------------------------------------------------- /example/benchmark/benchmark1.json: -------------------------------------------------------------------------------- 1 | { 2 | "Help": { 3 | "[en]": { 4 | "Domain::VolumeFile": "file full path to the volume file, file mst be in the uchar binary format", 5 | "Domain::Dim": "dimension of the data array stored in the volume file", 6 | "Domain::OriginType": "similar to --srcfrom0, 1 if the origin is [0 0 0], 0 if it is [1.0,1.0,1.0]", 7 | "Domain::Step": "do not change this, should be always be 1", 8 | "Domain::CacheBoxP0": "for cachebox mcx with -R negative_num, this specifies a 3D index for 9 | a corner of the cache region, in grid unit", 10 | "Domain::CacheBoxP1": "the other corner, the starting value of the indices is 1", 11 | "Domain::Media": "the first medium is always assigned to voxels with a value of 0 or outside of 12 | the volume, the second row is for medium type 1, and so on. mua and mus must 13 | be in 1/mm unit", 14 | "Session::Photons": "if -n is not specified in the command line, this defines the total photon number", 15 | "Session::ID": "if -s is not specified in the command line, this defines the output file name stub", 16 | "Forward::T0": "the start time of the simulation, in seconds", 17 | "Forward::T1": "the end time of the simulation, in seconds", 18 | "Forward::Dt": "the width of each time window, in seconds", 19 | "Optode::Source::Pos": "the grid position of the source, can be non-integers, in grid unit", 20 | "Optode::Detector::Pos": "the grid position of a detector, can be non-integers, in grid unit", 21 | "Optode::Source::Dir": "the unitary directional vector of the photon at launch", 22 | "Optode::Source::Type": "source types, must be one of the following: 23 | pencil,isotropic,cone,gaussian,planar,pattern,fourier,arcsine,disk", 24 | "Optode::Source::Param1": "source parameters, 4 floating-point numbers", 25 | "Optode::Source::Param2": "additional source parameters, 4 floating-point numbers" 26 | } 27 | }, 28 | "Domain": { 29 | "VolumeFile": "cubic60.json", 30 | "Dim": [60,60,60], 31 | "OriginType": 1, 32 | "Media": [ 33 | {"mua": 0.00, "mus": 0.0, "g": 1.00, "n": 1.0}, 34 | {"mua": 0.005,"mus": 1.0, "g": 0.01, "n": 1.37}, 35 | {"mua": 0.002,"mus": 5.0, "g": 0.90, "n": 1.0} 36 | ] 37 | }, 38 | "Session": { 39 | "Photons": 1e8, 40 | "RNGSeed": 29012392, 41 | "ID": "benchmark1" 42 | }, 43 | "Forward": { 44 | "T0": 0.0e+00, 45 | "T1": 5.0e-09, 46 | "Dt": 5.0e-09 47 | }, 48 | "Optode": { 49 | "Source": { 50 | "Type":"pencil", 51 | "Pos": [29.0, 29.0, 0.0], 52 | "Dir": [0.0, 0.0, 1.0] 53 | }, 54 | "Detector": [ 55 | { 56 | "Pos": [29.0, 19.0, 0.0], 57 | "R": 1.0 58 | }, 59 | { 60 | "Pos": [29.0, 39.0, 0.0], 61 | "R": 1.0 62 | }, 63 | { 64 | "Pos": [19.0, 29.0, 0.0], 65 | "R": 1.0 66 | }, 67 | { 68 | "Pos": [39.0, 29.0, 0.0], 69 | "R": 1.0 70 | } 71 | ] 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /example/benchmark/benchmark3.json: -------------------------------------------------------------------------------- 1 | { 2 | "Help": { 3 | "[en]": { 4 | "Domain::VolumeFile": "file full path to the volume file, file mst be in the uchar binary format", 5 | "Domain::Dim": "dimension of the data array stored in the volume file", 6 | "Domain::OriginType": "similar to --srcfrom0, 1 if the origin is [0 0 0], 0 if it is [1.0,1.0,1.0]", 7 | "Domain::Step": "do not change this, should be always be 1", 8 | "Domain::CacheBoxP0": "for cachebox mcx with -R negative_num, this specifies a 3D index for 9 | a corner of the cache region, in grid unit", 10 | "Domain::CacheBoxP1": "the other corner, the starting value of the indices is 1", 11 | "Domain::Media": "the first medium is always assigned to voxels with a value of 0 or outside of 12 | the volume, the second row is for medium type 1, and so on. mua and mus must 13 | be in 1/mm unit", 14 | "Session::Photons": "if -n is not specified in the command line, this defines the total photon number", 15 | "Session::ID": "if -s is not specified in the command line, this defines the output file name stub", 16 | "Forward::T0": "the start time of the simulation, in seconds", 17 | "Forward::T1": "the end time of the simulation, in seconds", 18 | "Forward::Dt": "the width of each time window, in seconds", 19 | "Optode::Source::Pos": "the grid position of the source, can be non-integers, in grid unit", 20 | "Optode::Detector::Pos": "the grid position of a detector, can be non-integers, in grid unit", 21 | "Optode::Source::Dir": "the unitary directional vector of the photon at launch", 22 | "Optode::Source::Type": "source types, must be one of the following: 23 | pencil,isotropic,cone,gaussian,planar,pattern,fourier,arcsine,disk", 24 | "Optode::Source::Param1": "source parameters, 4 floating-point numbers", 25 | "Optode::Source::Param2": "additional source parameters, 4 floating-point numbers" 26 | } 27 | }, 28 | "Domain": { 29 | "VolumeFile": "cubic60.json", 30 | "Dim": [60,60,60], 31 | "OriginType": 1, 32 | "Media": [ 33 | {"mua": 0.00, "mus": 0.0, "g": 1.00, "n": 1.0}, 34 | {"mua": 0.005,"mus": 1.0, "g": 0.01, "n": 1.37}, 35 | {"mua": 0.002,"mus": 5.0, "g": 0.90, "n": 1.0} 36 | ] 37 | }, 38 | "Session": { 39 | "Photons": 1e8, 40 | "RNGSeed": 29012392, 41 | "ID": "benchmark1" 42 | }, 43 | "Forward": { 44 | "T0": 0.0e+00, 45 | "T1": 5.0e-09, 46 | "Dt": 5.0e-09 47 | }, 48 | "Optode": { 49 | "Source": { 50 | "Type":"planar", 51 | "Pos": [10.0, 10.0, -10.0], 52 | "Dir": [0.0, 0.0, 1.0], 53 | "Param1": [40.0, 0.0, 0.0, 0.0], 54 | "Param2": [0.0, 40.0, 0.0, 0.0] 55 | }, 56 | "Detector": [ 57 | { 58 | "Pos": [29.0, 19.0, 0.0], 59 | "R": 1.0 60 | }, 61 | { 62 | "Pos": [29.0, 39.0, 0.0], 63 | "R": 1.0 64 | }, 65 | { 66 | "Pos": [19.0, 29.0, 0.0], 67 | "R": 1.0 68 | }, 69 | { 70 | "Pos": [39.0, 29.0, 0.0], 71 | "R": 1.0 72 | } 73 | ] 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /example/benchmark/cubic60.json: -------------------------------------------------------------------------------- 1 | { 2 | "Shapes": [ 3 | {"Name": "cubic60"}, 4 | {"Origin": [0,0,0]}, 5 | {"Grid": {"Tag":1, "Size":[60,60,60]}} 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /example/benchmark/run_benchmark1.bat: -------------------------------------------------------------------------------- 1 | ..\..\bin\mcxcl.exe -A -f benchmark1.json -b 0 %* 2 | -------------------------------------------------------------------------------- /example/benchmark/run_benchmark1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ../../bin/mcxcl -A -f benchmark1.json -b 0 "$@" 4 | -------------------------------------------------------------------------------- /example/benchmark/run_benchmark2.bat: -------------------------------------------------------------------------------- 1 | ..\..\bin\mcxcl.exe -A -f benchmark1.json -b 1 -P '{"Shapes":[{"Sphere": {"Tag":2, "O":[30,30,30],"R":15}}]}' -s benchmark2 %* 2 | -------------------------------------------------------------------------------- /example/benchmark/run_benchmark2.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ../../bin/mcxcl -A -f benchmark1.json -b 1 -P '{"Shapes":[{"Sphere": {"Tag":2, "O":[30,30,30],"R":15}}]}' -s benchmark2 "$@" 4 | -------------------------------------------------------------------------------- /example/benchmark/run_benchmark2a.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ../../bin/mcxcl -A -f benchmark1.json -b 1 -P '{"Shapes":[{"Sphere": {"Tag":2, "O":[30,30,30],"R":15}}]}' -s benchmark2 --atomic 1 "$@" 4 | -------------------------------------------------------------------------------- /example/benchmark/run_benchmark3.bat: -------------------------------------------------------------------------------- 1 | ..\..\bin\mcxcl.exe -A -f benchmark3.json -b 1 -s benchmark3 %* 2 | -------------------------------------------------------------------------------- /example/benchmark/run_benchmark3.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ../../bin/mcxcl -A -f benchmark3.json -b 1 -s benchmark3 "$@" 4 | -------------------------------------------------------------------------------- /example/colin27/README.txt: -------------------------------------------------------------------------------- 1 | == Colin27 Brain Atlas Photon Simulations == 2 | 3 | In this example, we demonstrate light transport simulation in a full-head 4 | atlas template (Colin27). There are 7 tissue types: 5 | 6 | 0: background (air) 7 | 1: scalp 8 | 2: skull 9 | 3: CSF 10 | 4: gray matter 11 | 5: white matter 12 | 6: air cavities in the brain 13 | 14 | 15 | This demo is identical to the MCX simulation used for Fig.6 in 16 | the original MCX paper [Fang2009]. 17 | 18 | This example is a built-in dataset in MCX. Run "mcx --bench" to show 19 | the full list of built-in examples. 20 | 21 | The JSON files (.json, .jnii) utlizes the JData specifiation (https://github.com/fangq/jdata) 22 | to include binary data with compression support. Please download JSONLab from 23 | 24 | https://github.com/fangq/jsonlab 25 | 26 | to open these files in MATLAB and GNU Octave, or PyJData from 27 | 28 | https://github.com/fangq/pyjdata 29 | 30 | to open such in Python. 31 | 32 | 33 | [Fang2009] Qianqian Fang and David A. Boas, "Monte Carlo simulation 34 | of photon migration in 3D turbid media accelerated by graphics processing 35 | units," Opt. Express 17, 20178-20190 (2009) 36 | 37 | -------------------------------------------------------------------------------- /example/colin27/dump_json.bat: -------------------------------------------------------------------------------- 1 | ::#!/bin/sh 2 | ..\..\bin\mcxcl.exe --bench colin27 --dumpjson > colin27.json %* 3 | -------------------------------------------------------------------------------- /example/colin27/dump_json.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | ../../bin/mcxcl --bench colin27 --dumpjson > colin27.json $@ 3 | -------------------------------------------------------------------------------- /example/colin27/dump_volume.bat: -------------------------------------------------------------------------------- 1 | ::#!/bin/sh 2 | ..\..\bin\mcxcl.exe --bench colin27 --dumpmask -F jnii %* 3 | -------------------------------------------------------------------------------- /example/colin27/dump_volume.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | ../../bin/mcxcl --bench colin27 --dumpmask -F jnii $@ 3 | -------------------------------------------------------------------------------- /example/colin27/run_atlas.bat: -------------------------------------------------------------------------------- 1 | ::#!/bin/sh 2 | ..\..\bin\mcxcl.exe -A -n 1e8 --bench colin27 -D P -F nii %* 3 | -------------------------------------------------------------------------------- /example/colin27/run_atlas.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | ../../bin/mcxcl --bench colin27 -n 1e8 -D P -F jnii $@ 3 | -------------------------------------------------------------------------------- /example/digimouse/README.txt: -------------------------------------------------------------------------------- 1 | == Digimouse Atlas Photon Simulation == 2 | 3 | In this example, we demonstrate light transport simulation in a mouse 4 | atlas template (Digimouse). There are 21 tissue types in the atlas. The volume 5 | is made of 190 x 496 x 104 0.8 mm^3 isotropic voxels. See [Fang2012]. 6 | 7 | To run this example, please call 8 | 9 | ./run_atlas.sh 10 | 11 | or 12 | 13 | ./run_atlas.sh -n 1e6 14 | 15 | to specify a different photon number 16 | 17 | 18 | The JSON files (.json, .jnii) utlizes the JData specifiation (https://github.com/fangq/jdata) 19 | to include binary data with compression support. Please download JSONLab from 20 | 21 | https://github.com/fangq/jsonlab 22 | 23 | to open these files in MATLAB and GNU Octave, or PyJData from 24 | 25 | https://github.com/fangq/pyjdata 26 | 27 | to open such in Python. 28 | 29 | 30 | === Reference === 31 | 32 | [Fang2012] Fang Q and Kaeli D, "Accelerating mesh-based Monte Carlo method 33 | on modern CPU architectures," Biomed. Opt. Express, 3(12), 3223-3230, 2012 34 | 35 | -------------------------------------------------------------------------------- /example/digimouse/dump_volume.bat: -------------------------------------------------------------------------------- 1 | ::#!/bin/sh 2 | ..\..\bin\mcxcl.exe -f digimouse.json --dumpmask -F jnii %* 3 | -------------------------------------------------------------------------------- /example/digimouse/dump_volume.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | ../../bin/mcxcl -f digimouse.json --dumpmask -F jnii 3 | -------------------------------------------------------------------------------- /example/digimouse/run_atlas.bat: -------------------------------------------------------------------------------- 1 | ::#!/bin/sh 2 | ..\..\bin\mcxcl.exe -A -n 1e8 -f digimouse.json -D P %* 3 | -------------------------------------------------------------------------------- /example/digimouse/run_atlas.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | ../../bin/mcxcl -A -n 1e8 -f digimouse.json -F jnii -D P $@ 3 | -------------------------------------------------------------------------------- /example/quicktest/README.txt: -------------------------------------------------------------------------------- 1 | = README for the quicktest example = 2 | 3 | As the name indicates, this example runs a short simulation 4 | for the purpose of testing the command line options build 5 | with MCX. 6 | 7 | To run this example, you need to first compile mcx binary. 8 | Then you can choose to run the following shell scripts: 9 | 10 | listgpu.sh 11 | A script to call mcx to print the GPU information 12 | only. Run this script and find out how many GPUs you 13 | have in your graphics card and the related parameters 14 | (memory, cores etc) 15 | 16 | run_qtest.sh 17 | This will run MCX for a simple homogeneous medium as 18 | the example used in the Fang2009 paper. It will launch 19 | only 0.3 million photons and take roughly half a second. 20 | 21 | run_qtest_silent.sh 22 | This script does the same thing as run_qtest.sh, 23 | except it let mcx to print messages to a log file 24 | rather than printing on the screen (so called silent mode) 25 | 26 | 27 | [Fang2009] Qianqian Fang and David A. Boas, "Monte Carlo 28 | Simulation of Photon Migration in 3D Turbid Media Accelerated 29 | by Graphics Processing Units," Opt. Express, 30 | vol. 17, issue 22, pp. 20178-20190 (2009) 31 | -------------------------------------------------------------------------------- /example/quicktest/cubic60.json: -------------------------------------------------------------------------------- 1 | { 2 | "Shapes": [ 3 | {"Name": "cube60"}, 4 | {"Origin": [0,0,0]}, 5 | {"Grid": {"Tag":1, "Size":[60,60,60]}} 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /example/quicktest/listgpu.bat: -------------------------------------------------------------------------------- 1 | ..\..\bin\mcxcl.exe -L 2 | -------------------------------------------------------------------------------- /example/quicktest/listgpu.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | ../../bin/mcxcl -L 3 | -------------------------------------------------------------------------------- /example/quicktest/qtest.inp: -------------------------------------------------------------------------------- 1 | 1000000 # total photon (not used) 2 | 29012392 # RNG seed, negative to generate 3 | 30.0 30.0 1.0 # source position (mm) 4 | 0 0 1 # initial directional vector 5 | 0.e+00 5.e-09 5.e-9 # time-gates(s): start, end, step 6 | cubic60.json # volume ('uchar' format) 7 | 1 60 10 50 # x: voxel size, dim, start/end indices 8 | 1 60 10 50 # y: voxel size, dim, start/end indices 9 | 1 60 1 20 # z: voxel size, dim, start/end indices 10 | 1 # num of media 11 | 1 0.01 0.005 1.0 # scat(1/mm), g, mua (1/mm), n 12 | 4 1 # detector number and radius (mm) 13 | 30.0 20.0 1.0 # detector 1 position (mm) 14 | 30.0 40.0 1.0 # ... 15 | 20.0 30.0 1.0 16 | 40.0 30.0 1.0 17 | -------------------------------------------------------------------------------- /example/quicktest/qtest.json: -------------------------------------------------------------------------------- 1 | { 2 | "Help": { 3 | "[en]": { 4 | "Domain::VolumeFile": "file full path to the volume file, file mst be in the uchar binary format", 5 | "Domain::Dim": "dimension of the data array stored in the volume file", 6 | "Domain::OriginType": "similar to --srcfrom0, 1 if the origin is [0 0 0], 0 if it is [1.0,1.0,1.0]", 7 | "Domain::Step": "do not change this, should be always be 1", 8 | "Domain::CacheBoxP0": "for cachebox mcx with -R negative_num, this specifies a 3D index for 9 | a corner of the cache region, in grid unit", 10 | "Domain::CacheBoxP1": "the other corner, the starting value of the indices is 1", 11 | "Domain::Media": "the first medium is always assigned to voxels with a value of 0 or outside of 12 | the volume, the second row is for medium type 1, and so on. mua and mus must 13 | be in 1/mm unit", 14 | "Session::Photons": "if -n is not specified in the command line, this defines the total photon number", 15 | "Session::ID": "if -s is not specified in the command line, this defines the output file name stub", 16 | "Forward::T0": "the start time of the simulation, in seconds", 17 | "Forward::T1": "the end time of the simulation, in seconds", 18 | "Forward::Dt": "the width of each time window, in seconds", 19 | "Optode::Source::Pos": "the grid position of the source, can be non-integers, in grid unit", 20 | "Optode::Detector::Pos": "the grid position of a detector, can be non-integers, in grid unit" 21 | } 22 | }, 23 | "Domain": { 24 | "VolumeFile": "cubic60.json", 25 | "Dim": [60,60,60], 26 | "OriginType": 1, 27 | "Step": [1.0,1.0,1.0], 28 | "CacheBoxP0": [24,24,1], 29 | "CacheBoxP1": [34,34,10], 30 | "Media": [ 31 | {"mua": 0.00, "mus": 0.0, "g": 1.00, "n": 1.0}, 32 | {"mua": 0.005,"mus": 1.0, "g": 0.01, "n": 1.0} 33 | ] 34 | }, 35 | "Session": { 36 | "Photons": 1000000, 37 | "RNGSeed": 29012392, 38 | "ID": "qtest" 39 | }, 40 | "Forward": { 41 | "T0": 0.0e+00, 42 | "T1": 5.0e-09, 43 | "Dt": 5.0e-09 44 | }, 45 | "Optode": { 46 | "Source": { 47 | "Pos": [29.0, 29.0, 0.0], 48 | "Dir": [0.0, 0.0, 1.0] 49 | }, 50 | "Detector": [ 51 | { 52 | "Pos": [29.0, 19.0, 0.0], 53 | "R": 1.0 54 | }, 55 | { 56 | "Pos": [29.0, 39.0, 0.0], 57 | "R": 1.0 58 | }, 59 | { 60 | "Pos": [19.0, 29.0, 0.0], 61 | "R": 1.0 62 | }, 63 | { 64 | "Pos": [39.0, 29.0, 0.0], 65 | "R": 1.0 66 | } 67 | ] 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /example/quicktest/run_qtest.bat: -------------------------------------------------------------------------------- 1 | ..\..\bin\mcxcl.exe -A -g 10 -n 1e7 -f qtest.inp -s qtest -r 1 -a 0 -b 0 -G 1 -D P %* 2 | 3 | -------------------------------------------------------------------------------- /example/quicktest/run_qtest.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ../../bin/mcxcl -A -n 1e7 -f qtest.inp "$@" 4 | 5 | -------------------------------------------------------------------------------- /example/quicktest/run_qtest_silent.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ../../bin/mcxcl -A -n 1e7 -f qtest.inp -l "$@" 4 | 5 | -------------------------------------------------------------------------------- /example/skinvessel/README.txt: -------------------------------------------------------------------------------- 1 | == The skin-vessel benchmark from mcxyz by Dr. Jacques == 2 | 3 | In this example, we compare between MCX and mcxyz written by Dr. Steve Jacques. 4 | The same benchmark can be found at https://omlc.org/software/mc/mcxyz/index.html 5 | 6 | By default, this simulation outputs fluence rate. To change the output to energy 7 | deposition, please run the script using 8 | 9 | ./run_mcxyz_bench.sh -O E 10 | 11 | To plot the mcx solutions and compare with those from mcxyz, please use the 12 | matlab script demo_mcxyz_skinvessel.m as part of mcxlab, see 13 | 14 | https://github.com/fangq/mcx/blob/master/mcxlab/examples/demo_mcxyz_skinvessel.m 15 | -------------------------------------------------------------------------------- /example/skinvessel/disable_hyper.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | for i in {1..11}; do 3 | echo "Disabling logical HT core $i." 4 | echo 0 > /sys/devices/system/cpu/cpu${i}/online; 5 | done 6 | -------------------------------------------------------------------------------- /example/skinvessel/enable_hyper.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | for i in {1..11}; do 3 | echo "Enabling logical HT core $i." 4 | echo 1 > /sys/devices/system/cpu/cpu${i}/online; 5 | done 6 | -------------------------------------------------------------------------------- /example/skinvessel/mcxyz_bench.json: -------------------------------------------------------------------------------- 1 | { 2 | "Session": { 3 | "ID": "skinvessel", 4 | "DoMismatch": 1, 5 | "DoAutoThread": 1, 6 | "Photons": 10000000 7 | }, 8 | "Forward": { 9 | "T0": 0, 10 | "T1": 5e-08, 11 | "Dt": 5e-08 12 | }, 13 | "Optode": { 14 | "Source": { 15 | "Pos": [100, 100, 20], 16 | "Dir": [0,0,1], 17 | "Param1": [60,0,0,0], 18 | "Type": "disk" 19 | } 20 | }, 21 | "Domain": { 22 | "OriginType": 1, 23 | "LengthUnit": 0.005, 24 | "Media": [ 25 | { 26 | "mua": 1e-05, 27 | "mus": 0, 28 | "g": 1, 29 | "n": 1.37 30 | }, 31 | { 32 | "mua": 3.564e-05, 33 | "mus": 1, 34 | "g": 1, 35 | "n": 1.37 36 | }, 37 | { 38 | "mua": 23.05426549, 39 | "mus": 9.398496241, 40 | "g": 0.9, 41 | "n": 1.37 42 | }, 43 | { 44 | "mua": 0.04584957865, 45 | "mus": 35.65405549, 46 | "g": 0.9, 47 | "n": 1.37 48 | }, 49 | { 50 | "mua": 1.657237447, 51 | "mus": 37.59398496, 52 | "g": 0.9, 53 | "n": 1.37 54 | } 55 | ], 56 | "Dim": [200,200,200], 57 | "VolumeFile": "skinvessel.json" 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /example/skinvessel/run_mcxyz_bench.bat: -------------------------------------------------------------------------------- 1 | ::#!/bin/sh 2 | 3 | ..\..\bin\mcxcl.exe --bench skinvessel -e 0.01 -d 0 -D P -F bnii %* 4 | -------------------------------------------------------------------------------- /example/skinvessel/run_mcxyz_bench.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ../../bin/mcxcl --bench skinvessel -n 1e7 -e 0.01 -d 0 -F bnii "$@" 4 | -------------------------------------------------------------------------------- /example/skinvessel/skinvessel.json: -------------------------------------------------------------------------------- 1 | { 2 | "Shapes": [ 3 | {"ZLayers":[[1,20,1],[21,32,4],[33,200,3]]}, 4 | {"Cylinder": {"Tag":2, "C0": [0,100.5,100.5], "C1": [200,100.5,100.5], "R": 20}} 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /example/usc19-5/README.txt: -------------------------------------------------------------------------------- 1 | == USC 19-5 Brain Atlas Photon Simulations == 2 | 3 | In this example, we demonstrate light transport simulation in a full-head 4 | atlas template(USC 19.5 year group [Sanchez2012]). 5 | 6 | This demo is identical to the MCX simulation used for Fig.9(a) in 7 | TranYan2019. 8 | 9 | The JSON files (.json, .jnii) utlizes the JData specifiation (https://github.com/fangq/jdata) 10 | to include binary data with compression support. Please download JSONLab from 11 | 12 | https://github.com/fangq/jsonlab 13 | 14 | to open these files in MATLAB and GNU Octave, or PyJData from 15 | 16 | https://github.com/fangq/pyjdata 17 | 18 | to open such in Python. 19 | 20 | 21 | [Sanchez2012] C.E.Sanchez J.E.Richards and C.R.Almli, "Age-Specific MRI Templates 22 | for Pediatric Neuroimaging," Developmental Neuropsychology 37, 379-399 (2012). 23 | 24 | [TranYan2019] A.P.Tran, S.Yan and Q.Fang, "Improving model-based functional near-infrared 25 | spectroscopy analysis using mesh-based anatomical and light-transport models". 26 | 27 | -------------------------------------------------------------------------------- /example/usc19-5/dump_volume.bat: -------------------------------------------------------------------------------- 1 | ::#!/bin/sh 2 | ..\..\bin\mcxcl.exe -f USC_19-5_atlas.json --dumpmask -F jnii %* 3 | -------------------------------------------------------------------------------- /example/usc19-5/dump_volume.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | ../../bin/mcxcl -f USC_19-5_atlas.json --dumpmask -F jnii $@ 3 | -------------------------------------------------------------------------------- /example/usc19-5/run_atlas.bat: -------------------------------------------------------------------------------- 1 | ::#!/bin/sh 2 | ..\..\bin\mcxcl.exe -A -n 1e8 -f USC_19-5_atlas.json -D P %* 3 | -------------------------------------------------------------------------------- /example/usc19-5/run_atlas.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | ../../bin/mcxcl -A -n 1e8 -f USC_19-5_atlas.json -D P -F jnii $@ 3 | -------------------------------------------------------------------------------- /example/validation/README.txt: -------------------------------------------------------------------------------- 1 | = README for the validation example = 2 | 3 | In this example, we validate MCX code with a homogeneous 4 | medium defined by a 60x60x60 uniform grid. The medium has 5 | mua=0.005/mm, musp=1/mm, anisotropy g=0.01 and refraction 6 | index n=1 (without reflection) or n=1.37 (with reflection). 7 | 8 | The detailed report can be found in the paper Fang2009 9 | Section 3.2 and Fig. 5. 10 | 11 | To run this example, you need to first compile the mcx 12 | binary, and then run the run_validation.sh and 13 | run_validation_b.sh scripts to run simulations for 14 | n=1 and n=1.37, respectively. Then you need to start 15 | GNU Octave or Matlab, and run plotsimudata.m script 16 | to reproduce Fig. 5 in Fang2009. 17 | 18 | 19 | [Fang2009] Qianqian Fang and David A. Boas, "Monte Carlo 20 | Simulation of Photon Migration in 3D Turbid Media Accelerated 21 | by Graphics Processing Units," Opt. Express, 22 | vol. 17, issue 22, pp. 20178-20190 (2009) 23 | -------------------------------------------------------------------------------- /example/validation/cubic60.json: -------------------------------------------------------------------------------- 1 | { 2 | "Shapes": [ 3 | {"Name": "cubic60"}, 4 | {"Origin": [0,0,0]}, 5 | {"Grid": {"Tag":1, "Size":[60,60,60]}} 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /example/validation/plotsimudata.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % matlab script to produce the validation plots (Fig. 4) 3 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 4 | 5 | if(exist('loadmc2')~=2) 6 | error('you need to first add path to ''/utils'' in order to run this script'); 7 | end 8 | 9 | c0=299792458000; 10 | srcpos=[30 30 1]; 11 | detpos=[30 15 10]; 12 | twin=[5e-11:1e-10:5e-9]; 13 | 14 | %---------------------------------------------------------------- 15 | % Plot time-domain comparison at a given position 16 | %---------------------------------------------------------------- 17 | 18 | figure; 19 | hold on; 20 | 21 | mcx=loadmc2('semi_infinite.mc2',[60 60 60 50]); 22 | semilogy((1:50)/10,tddiffusion(0.005, 1, c0, 0, srcpos, detpos,twin),'r'); 23 | semilogy((1:50)/10,squeeze(mcx(30,14,9,:)),'o'); 24 | 25 | mcxb=loadmc2('semi_infinite_b.mc2',[60 60 60 50]); 26 | semilogy((1:50)/10,tddiffusion(0.005, 1, c0/1.37, 0.493, srcpos, detpos,twin),'r--'); 27 | semilogy((1:50)/10,squeeze(mcxb(30,14,9,:)),'+'); 28 | 29 | set(gca,'ylim',[1 10^8.5]); 30 | 31 | legend('Diffusion (no reflection)','MCX (no reflection)','Diffusion (with reflection)','MCX (with reflection)'); 32 | legend boxoff; 33 | set(gca,'yscale','log'); 34 | set(gca,'fontsize',18); 35 | xlabel('time (ns)') 36 | ylabel('Fluence in 1/(m^2s)') 37 | box on; 38 | saveas(gcf,'td_validate.fig') 39 | print -depsc2 td_validate.eps 40 | 41 | %---------------------------------------------------------------- 42 | % Plot CW comparison along a line 43 | %---------------------------------------------------------------- 44 | 45 | figure; 46 | hold on; 47 | 48 | cwmcx=sum(mcx,4); 49 | srcpos=[0 0 0]; 50 | detpos=[0.5+(0:29)', 0.5*ones(30,1),0.5*ones(30,1)]; 51 | phicw=cwdiffusion(0.005, 1, 0, srcpos, detpos); 52 | phimcx=cwmcx(30,:,1); 53 | 54 | cwmcxb=sum(mcxb,4); 55 | phicwb=cwdiffusion(0.005, 1, 0.493, srcpos, detpos); 56 | phimcxb=(cwmcxb(30,:,1)); 57 | h=semilogy(1:30, phicw, 'r-', 1:30, phimcx(30:59)*1e-10, 'o', 1:30, phicwb, 'r--', 1:30, phimcxb(30:59)*1e-10, 'b+'); 58 | box on; 59 | set(gca,'yscale','log') 60 | 61 | legend('Diffusion (no reflection)','MCX (no reflection)','Diffusion (with reflection)','MCX(with reflection)'); 62 | legend boxoff; 63 | set(gca,'fontsize',18); 64 | xlabel('x (mm)') 65 | ylabel('Fluence in 1/(m^2s)') 66 | saveas(gcf,'td_validate_cw.fig') 67 | print -depsc2 td_validate_cw.eps 68 | 69 | %---------------------------------------------------------------- 70 | % Plot CW comparison at a cross-section 71 | %---------------------------------------------------------------- 72 | 73 | figure 74 | hold on; 75 | 76 | clines = -1.5:-0.5:-4; 77 | srcpos=[29.5 29.5 0.5]; 78 | [xi,yi]=meshgrid(0.5:59.5,0.5:59.5); 79 | detpos=[xi(:) 30*ones(size(xi(:))) yi(:)]; 80 | phicw=reshape(cwdiffusion(0.005, 1.0, 0, srcpos, detpos),size(xi)); 81 | 82 | [c h2]=contour(xi,yi, log10(max(squeeze(phicw),1e-8)), clines, 'k-' ); 83 | [c h1]=contour(log10(max(squeeze(cwmcx(:,30,:)*1e-10)',1e-8)), clines, 'k:' ); 84 | legend('Diffusion','MCX') 85 | legend boxoff; 86 | box on; 87 | set(gca,'fontsize',18); 88 | xlabel('x (mm)') 89 | ylabel('z (mm)') 90 | saveas(gcf,'td_validate_cw_2d.fig') 91 | print -depsc2 td_validate_cw_2d.eps 92 | 93 | %---------------------------------------------------------------- 94 | % Plot time-domain comparison at a cross-section 95 | %---------------------------------------------------------------- 96 | 97 | c0=299792458000; 98 | twin=5e-11:1e-10:5e-9; 99 | mua=0.005; 100 | musp=1; 101 | Reff=0; 102 | 103 | srcpos=[29.5 29.5 0]; 104 | [xi,yi]=meshgrid(0.5:59.5,0.5:59.5); 105 | 106 | detpos=[xi(:) 29.5*ones(size(xi(:))) yi(:)]; 107 | for i=1:length(twin) 108 | phitd(:,:,i)=reshape(tddiffusion(mua,musp,c0,Reff,srcpos,detpos,twin(i)),size(xi)); 109 | end 110 | 111 | figure; 112 | hold on 113 | 114 | for i=1:5:21 115 | halfmax=max(max(phitd(:,:,i)))/2; 116 | [c h2]=contour(xi, yi,max(squeeze(phitd(:,:,i)),1e-12),[halfmax halfmax], 'k-'); 117 | halfmax=max(max(mcx(:,30,:,i)))/2; 118 | [c h2]=contour(max(squeeze(mcx(:,30,:,i))',1e-12),[halfmax halfmax], 'k:'); 119 | end 120 | legend('Diffusion','MCX') 121 | legend boxoff; 122 | box on; 123 | set(gca,'fontsize',18); 124 | xlabel('x (mm)') 125 | ylabel('z (mm)') 126 | saveas(gcf,'td_validate_2d.fig') 127 | 128 | print -depsc2 td_validate_2d.eps 129 | 130 | -------------------------------------------------------------------------------- /example/validation/run_validation.bat: -------------------------------------------------------------------------------- 1 | ::#!/bin/sh 2 | ..\..\bin\mcxcl.exe -A -n 1e7 -f validation.inp -s semi_infinite -a 0 -b 0 -d 0 %* 3 | -------------------------------------------------------------------------------- /example/validation/run_validation.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | time ../../bin/mcxcl -A -n 1e7 -f validation.inp -s semi_infinite -a 0 -b 0 -d 0 $@ 3 | -------------------------------------------------------------------------------- /example/validation/run_validation_b.bat: -------------------------------------------------------------------------------- 1 | ::#!/bin/sh 2 | ..\..\bin\mcxcl.exe -A 1 -f validation_b.inp -s semi_infinite_b -a 0 -b 1 -U 1 %* 3 | -------------------------------------------------------------------------------- /example/validation/run_validation_b.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | time ../../bin/mcxcl -A 1 -f validation_b.inp -s semi_infinite_b -a 0 -b 1 -U 1 $@ 3 | -------------------------------------------------------------------------------- /example/validation/validation.inp: -------------------------------------------------------------------------------- 1 | 1000000 # total photon (not used) 2 | 1655742 # RNG seed, negative to generate 3 | 30.0 30.0 1.0 # source position (mm) 4 | 0 0 1 # initial directional vector 5 | 0.e+00 5.e-09 1.e-10 # time-gates(s): start, end, step 6 | cubic60.json # volume ('uchar' format) 7 | 1 60 1 60 # x: voxel size, dim, start/end indices 8 | 1 60 1 60 # y: voxel size, dim, start/end indices 9 | 1 60 1 60 # z: voxel size, dim, start/end indices 10 | 1 # num of media 11 | 1.0101010101 0.01 0.005 1.0 # scat(1/mm), g, mua (1/mm), n 12 | 4 1 # detector number and radius (mm) 13 | 30.0 20.0 1.0 # detector 1 position (mm) 14 | 30.0 40.0 1.0 # ... 15 | 20.0 30.0 1.0 16 | 40.0 30.0 1.0 17 | -------------------------------------------------------------------------------- /example/validation/validation_b.inp: -------------------------------------------------------------------------------- 1 | 1000000 # total photon (not used) 2 | 1655742 # RNG seed, negative to generate 3 | 30.0 30.0 1.0 # source position (mm) 4 | 0 0 1 # initial directional vector 5 | 0.e+00 5.e-09 1.e-10 # time-gates(s): start, end, step 6 | cubic60.json # volume ('uchar' format) 7 | 1 60 1 60 # x: voxel size, dim, start/end indices 8 | 1 60 1 60 # y: voxel size, dim, start/end indices 9 | 1 60 1 60 # z: voxel size, dim, start/end indices 10 | 1 # num of media 11 | 1.0101010101 0.01 0.005 1.37 # scat(1/mm), g, mua (1/mm), n 12 | 4 1 # detector number and radius (mm) 13 | 30.0 20.0 1.0 # detector 1 position (mm) 14 | 30.0 40.0 1.0 # ... 15 | 20.0 30.0 1.0 16 | 40.0 30.0 1.0 17 | -------------------------------------------------------------------------------- /example/validation/validation_dark.inp: -------------------------------------------------------------------------------- 1 | 1000000 # total photon (not used) 2 | 1655742 # RNG seed, negative to generate 3 | 30.0 30.0 1.0 # source position (mm) 4 | 0 0 1 # initial directional vector 5 | 0.e+00 5.e-09 1.e-10 # time-gates(s): start, end, step 6 | cubic60.json # volume ('uchar' format) 7 | 1 60 1 60 # x: voxel size, dim, start/end indices 8 | 1 60 1 60 # y: voxel size, dim, start/end indices 9 | 1 60 1 60 # z: voxel size, dim, start/end indices 10 | 1 # num of media 11 | 1.0101010101 0.01 0.01 1.0 # scat(1/mm), g, mua (1/mm), n 12 | 4 1 # detector number and radius (mm) 13 | 30.0 20.0 1.0 # detector 1 position (mm) 14 | 30.0 40.0 1.0 # ... 15 | 20.0 30.0 1.0 16 | 40.0 30.0 1.0 17 | -------------------------------------------------------------------------------- /example/validation/validation_dark_b.inp: -------------------------------------------------------------------------------- 1 | 1000000 # total photon (not used) 2 | 1655742 # RNG seed, negative to generate 3 | 30.0 30.0 1.0 # source position (mm) 4 | 0 0 1 # initial directional vector 5 | 0.e+00 5.e-09 1.e-10 # time-gates(s): start, end, step 6 | cubic60.json # volume ('uchar' format) 7 | 1 60 1 60 # x: voxel size, dim, start/end indices 8 | 1 60 1 60 # y: voxel size, dim, start/end indices 9 | 1 60 1 60 # z: voxel size, dim, start/end indices 10 | 1 # num of media 11 | 1.0101010101 0.01 0.01 1.37 # scat(1/mm), g, mua (1/mm), n 12 | 4 1 # detector number and radius (mm) 13 | 30.0 20.0 1.0 # detector 1 position (mm) 14 | 30.0 40.0 1.0 # ... 15 | 20.0 30.0 1.0 16 | 40.0 30.0 1.0 17 | -------------------------------------------------------------------------------- /gitlog.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | git log --pretty=" %ad [%h] %s" --date=short --since="2014-09-23" 4 | -------------------------------------------------------------------------------- /mcxlabcl/INSTALL.txt: -------------------------------------------------------------------------------- 1 | = Additional Installation Notes = 2 | 3 | One can manually install mcxlabcl by simply unzip the mcxlabcl zip file and use command 4 | `addpath('/path/to/mcxlabcl/')` to install it for Octave/MATLAB. 5 | 6 | Alternatively, for Windows, if you run the Windows all-in-one installer, the mcxlabcl 7 | toolbox, along with other toolboxes are automatically added to your MATLAB path, 8 | and can be used immediately. 9 | 10 | If you use Linux, you can also install these packages via the official software 11 | repositories 12 | 13 | === For Ubuntu/Debian users === 14 | 15 | Please add the fangq/ppa repository (https://launchpad.net/~fangq/+archive/ubuntu/ppa) 16 | to your system via 17 | 18 | sudo add-apt-repository ppa:fangq/ppa 19 | sudo apt-get update 20 | sudo apt-get install octave-mcxlabcl matlab-mcxlabcl 21 | 22 | When opening Octave, one must run 23 | pkg load mcxlabcl 24 | 25 | to load mcxlabcl toolbox if installed via the official octave-mcxlabcl package. 26 | 27 | === For Fedora users === 28 | 29 | The official octave-mcxlabcl package supported on Fedora since F24 can be installed by 30 | 31 | sudo dnf install octave-mcxlab 32 | -------------------------------------------------------------------------------- /mcxlabcl/examples/colin27_v3.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jishanshaikh4/mcxcl/4c1830589e2e4615782e036c994a7e4688357b15/mcxlabcl/examples/colin27_v3.mat -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_4layer_head.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % MCXLAB - Monte Carlo eXtreme for MATLAB/Octave by Qianqina Fang 3 | % 4 | % In this example, we simulate a 4-layer brain model using MCXLAB. 5 | % We will investigate the differences between the solutions with and 6 | % witout boundary reflections (both external and internal) and show 7 | % you how to display and analyze the resulting data. 8 | % 9 | % This file is part of Monte Carlo eXtreme (MCX) URL:http://mcx.sf.net 10 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 11 | clear cfg; 12 | 13 | %% preparing the input data 14 | % set seed to make the simulation repeatible 15 | cfg.seed=hex2dec('623F9A9E'); 16 | 17 | cfg.nphoton=5e7; 18 | 19 | % define a 4 layer structure 20 | cfg.vol=ones(100,100,50); 21 | cfg.vol(:,:,21:25)=2; 22 | cfg.vol(:,:,26:35)=3; 23 | cfg.vol(:,:,36:end)=4; 24 | cfg.vol=uint8(cfg.vol); 25 | 26 | % define the source position 27 | cfg.srcpos=[50,50,0]+1; 28 | cfg.srcdir=[0 0 1]; 29 | 30 | % use the brain optical properties defined at 31 | % http://mcx.sourceforge.net/cgi-bin/index.cgi?MMC/CollinsAtlasMesh 32 | % format: [mua(1/mm) mus(1/mm) g n] 33 | 34 | cfg.prop=[0 0 1 1 % medium 0: the environment 35 | 0.019 7.8 0.89 1.37 % medium 1: skin & skull 36 | 0.004 0.009 0.89 1.37 % medium 2: CSF 37 | 0.02 9.0 0.89 1.37 % medium 3: gray matter 38 | 0.08 40.9 0.84 1.37]; % medium 4: white matter 39 | 40 | % time-domain simulation parameters 41 | cfg.tstart=0; 42 | cfg.tend=5e-9; 43 | cfg.tstep=5e-10; 44 | 45 | % GPU thread configuration 46 | cfg.autopilot=1; 47 | cfg.gpuid=1; 48 | 49 | %% running simulation without boundary reflection 50 | fprintf('running simulation ... this takes about 35 seconds on a GTX 470\n'); 51 | cfg.isreflect=0; % disable reflection at exterior boundary 52 | tic; 53 | f1=mcxlabcl(cfg); 54 | toc; 55 | 56 | %% running simulation with boundary reflection enabled 57 | fprintf('running simulation ... this takes about 50 seconds on a GTX 470\n'); 58 | cfg.isreflect=1; % enable reflection at exterior boundary 59 | cfg.isrefint=1; % enable reflection at interior boundary too 60 | cfg.issavedet=1; % enable recording partial pathlength of detected photons 61 | cfg.detpos=[31 51 1 2]; 62 | tic; 63 | [f2,det2]=mcxlabcl(cfg); 64 | toc; 65 | 66 | %% plot the results 67 | figure 68 | subplot(221); 69 | contourf(log10(squeeze(sum(f1.data(:,51,:,:),4))'),1:0.5:8); 70 | hold on 71 | plot([0 100],[21 21],'--',[0 100],[26 26],'--',[0 100],[36 36],'--'); 72 | title('flux with no reflection'); 73 | set(gca,'clim',[1 8]); 74 | 75 | subplot(222); 76 | contourf(log10(squeeze(sum(f2.data(:,51,:,:),4))'),1:0.5:8); 77 | hold on 78 | plot([0 100],[21 21],'--',[0 100],[26 26],'--',[0 100],[36 36],'--'); 79 | title('flux with reflection at boundaries'); 80 | set(gca,'clim',[1 8]); 81 | 82 | subplot(223); 83 | hold on; 84 | xi=1e9*((cfg.tstart:cfg.tstep:cfg.tend-cfg.tstep)+0.5*cfg.tstep); 85 | for i=31:49 86 | semilogy(xi,squeeze(f2.data(51,i,1,:)),'color',[1-(i-25)/25 1-(i-25)/25 1]); 87 | end 88 | xlabel('time (ns)') 89 | ylabel('flux (1/mm^2/s)') 90 | set(gca,'yscale','log'); 91 | title('time point spread functions (TPSF)'); 92 | 93 | subplot(224); 94 | hold on; 95 | [hs1,c1]=hist(det2.ppath(find(det2.ppath(:,1)),1),200); 96 | [hs2,c2]=hist(det2.ppath(find(det2.ppath(:,2)),2),200); 97 | [hs3,c3]=hist(det2.ppath(find(det2.ppath(:,3)),3),200); 98 | [hs4,c4]=hist(det2.ppath(find(det2.ppath(:,4)),4),200); 99 | bar(c1,hs1,'edgecolor','none','facecolor','r'); 100 | bar(c2,hs2,'edgecolor','none','facecolor','b'); 101 | bar(c3,hs3,'edgecolor','none','facecolor','g'); 102 | bar(c4,hs4,'edgecolor','none','facecolor','k'); 103 | legend('tissue 1','tissue 2','tissue 3','tissue 4'); 104 | xlabel('partial pathlength (mm)'); 105 | title(sprintf('detected %d photons',size(det2.ppath,1))); 106 | -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_colin27_atlas.m: -------------------------------------------------------------------------------- 1 | % == Colin27 Brain Atlas Photon Simulations == 2 | % 3 | % In this example, we demonstrate light transport simulation in a full-head 4 | % atlas template (Colin27). There are 7 tissue types: 5 | % 6 | % 0: background (air) 7 | % 1: scalp 8 | % 2: skull 9 | % 3: CSF 10 | % 4: gray matter 11 | % 5: white matter 12 | % 6: air cavities in the brain 13 | % 14 | % To run the simulation, you must first unzip the domain binary file using 15 | % unlzma on Linux or 7-zip on Windows. For example, on Linux: 16 | % 17 | % unlzma colin27_v3.bin.lzma 18 | % 19 | % This demo is identical to the MCX simulation used for Fig.6 in 20 | % the original MCX paper [Fang2009]. 21 | % 22 | % 23 | % [Fang2009] Qianqian Fang and David A. Boas, "Monte Carlo simulation 24 | % of photon migration in 3D turbid media accelerated by graphics processing 25 | % units," Opt. Express 17, 20178-20190 (2009) 26 | 27 | clear cfg 28 | 29 | load colin27_v3.mat 30 | cfg.vol=colin27; 31 | 32 | cfg.tstart=0; 33 | cfg.tend=5e-09; 34 | cfg.tstep=2e-10; 35 | 36 | cfg.srcpos=[75 67.38 167.5]; 37 | cfg.srcdir=[0.1636 0.4569 -0.8743]; 38 | cfg.srcdir=cfg.srcdir/norm(cfg.srcdir); 39 | 40 | cfg.detpos=[ 75.0000 77.1900 170.3000 3.0000 41 | 75.0000 89.0000 171.6000 3.0000 42 | 75.0000 97.6700 172.4000 3.0000 43 | 75.0000 102.4000 172.0000 3.0000]; 44 | 45 | cfg.issrcfrom0=1; 46 | 47 | cfg.prop=[ 0 0 1.0000 1.0000 % background/air 48 | 0.0190 7.8182 0.8900 1.3700 % scalp 49 | 0.0190 7.8182 0.8900 1.3700 % skull 50 | 0.0040 0.0090 0.8900 1.3700 % csf 51 | 0.0200 9.0000 0.8900 1.3700 % gray matters 52 | 0.0800 40.9000 0.8400 1.3700 % white matters 53 | 0 0 1.0000 1.0000]; % air pockets 54 | 55 | cfg.seed=29012392; 56 | cfg.nphoton=10000000; 57 | cfg.issaveexit=1; 58 | 59 | [flue,detps]=mcxlab(cfg); 60 | mcxplotvol(log10(flue.data)); 61 | figure; 62 | plotmesh(detps.p,'r.') -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_continuous_mua_mus.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % MCXLAB - Monte Carlo eXtreme for MATLAB/Octave by Qianqina Fang 3 | % 4 | % In this example, we show how to define continuously varying media 5 | % (i.e. media optical properties vary from voxel to voxel) 6 | % 7 | % This file is part of Monte Carlo eXtreme (MCX) URL:http://mcx.sf.net 8 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 9 | 10 | clear cfg cfgs 11 | cfg.nphoton=1e8; 12 | cfg.vol=uint8(ones(60,60,60)); 13 | cfg.srcpos=[30 30 1]; 14 | cfg.srcdir=[0 0 1]; 15 | cfg.gpuid=1; 16 | % cfg.gpuid='11'; % use two GPUs together 17 | cfg.autopilot=1; 18 | cfg.prop=[0 0 1 1;0.005 1 0 1.37]; 19 | cfg.tstart=0; 20 | cfg.tend=5e-9; 21 | cfg.tstep=5e-9; 22 | % calculate the flux distribution with the given config 23 | 24 | %% Approach #1: a 1 x Nx x Ny x Nz floating-point array defines mua(x,y,z) 25 | %define continuously varying media - use a 4D array - 1st dimension defines 26 | %the optical property components of each spatial position 27 | 28 | mua1=0.003; 29 | mua2=0.1; 30 | mua=single(reshape(repmat([mua1:(mua2-mua1)/(60-1):mua2]',60,60),60,60,60)); 31 | cfg.vol=permute(mua, [4,1,2,3]); % make 1st dimension the property dimension 32 | 33 | flux=mcxlabcl(cfg); 34 | 35 | mcxplotvol(squeeze(cfg.vol)) 36 | title('continuously varying absorption coeff \mu_a (1/mm)') 37 | view([-25.5,21.2]); 38 | 39 | mcxplotvol(log10(flux.data)) 40 | colormap(jet); 41 | title('fluence in continuously varying media (1/mm^2)') 42 | view([-25.5,21.2]); 43 | 44 | 45 | %% Approach #2: a 2 x Nx x Ny x Nz float32 array defines [mua,mus] per voxel 46 | 47 | mus1=1.0; 48 | mus2=5.0; 49 | mus=single(reshape(repmat([mus1:(mus2-mus1)/(60-1):mus2]',60,60),60,60,60)); 50 | cfg.vol=reshape([mua(:)'; mus(:)'],[2 60 60 60]); 51 | 52 | flux=mcxlabcl(cfg); 53 | 54 | mcxplotvol(squeeze(cfg.vol(2,:,:,:))) 55 | title('continuously varying scattering coeff \mu_s (1/mm)') 56 | view([-25.5,21.2]); 57 | 58 | mcxplotvol(log10(flux.data)) 59 | colormap(jet); 60 | title('fluence in continuously varying media (1/mm^2)') 61 | view([-25.5,21.2]); 62 | -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_digimouse_sfdi.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % MCXLAB - Monte Carlo eXtreme for MATLAB/Octave by Qianqina Fang 3 | % 4 | % In this example, we demonstrate light transport simulation in a digital 5 | % mouse atlas - Digimouse 6 | % 7 | % This demo is similar to the MCX simulation used for Fig. 2 in 8 | % [Fang2012], except this uses a voxelated model instead of a mesh. 9 | % 10 | % 11 | % [Fang2012] Qianqian Fang and David R. Kaeli, "Accelerating mesh-based 12 | % Monte Carlo method on modern CPU architectures ," Biomed. Opt. Express 13 | % 3(12), 3223-3230 (2012) 14 | % 15 | % This file is part of Monte Carlo eXtreme (MCX) URL:http://mcx.sf.net 16 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 17 | 18 | clear cfg; 19 | 20 | load digimouse.mat 21 | cfg.vol=digimouse; 22 | 23 | cfg.prop=[1 0.0191 6.6 0.9 1.37 24 | 2 0.0136 8.6 0.9 1.37 25 | 3 0.0026 0.01 0.9 1.37 26 | 4 0.0186 11.1 0.9 1.37 27 | 5 0.0186 11.1 0.9 1.37 28 | 6 0.0186 11.1 0.9 1.37 29 | 7 0.0186 11.1 0.9 1.37 30 | 8 0.0186 11.1 0.9 1.37 31 | 9 0.0240 8.9 0.9 1.37 32 | 10 0.0026 0.01 0.9 1.37 33 | 11 0.0240 8.9 0.9 1.37 34 | 12 0.0240 8.9 0.9 1.37 35 | 13 0.0240 8.9 0.9 1.37 36 | 14 0.0240 8.9 0.9 1.37 37 | 15 0.0240 8.9 0.9 1.37 38 | 16 0.072 5.6 0.9 1.37 39 | 17 0.072 5.6 0.9 1.37 40 | 18 0.072 5.6 0.9 1.37 41 | 19 0.050 5.4 0.9 1.37 42 | 20 0.024 8.9 0.9 1.37 43 | 21 0.076 10.9 0.9 1.37]; 44 | 45 | cfg.prop(:,1)=[]; 46 | cfg.prop(2:end+1,:)=cfg.prop; 47 | cfg.prop(1,:)=[0 0 1 1]; 48 | 49 | cfg.srctype='fourier'; 50 | cfg.srcpos=[50.0 200.0 100.0]; 51 | cfg.srcparam1=[100.0 0.0 0.0 2]; 52 | cfg.srcparam2=[0 100.0 0.0 0]; 53 | cfg.srcdir=[0 0 -1]; 54 | cfg.issrcfrom0=1; 55 | 56 | cfg.tstart=0; 57 | cfg.tend=5e-9; 58 | cfg.tstep=5e-9; 59 | cfg.nphoton=1e8; 60 | cfg.autopilot=1; 61 | cfg.gpuid=1; 62 | cfg.unitinmm=0.4*2; 63 | cfg.debuglevel='P'; 64 | 65 | flux=mcxlabcl(cfg); 66 | fcw=flux.data; 67 | mcxplotvol(log10(fcw)); 68 | 69 | %mcx2json(cfg,'digimouse.json'); -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_focus_mirror_bc.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % MCXLAB - Monte Carlo eXtreme for MATLAB/Octave by Qianqina Fang 3 | % 4 | % In this demo script, we verify the following two bugs are fixed 5 | % 6 | % https://github.com/fangq/mcx/issues/103 (to handle focal point) 7 | % https://github.com/fangq/mcx/issues/104 (to handle mirror bc) 8 | % 9 | % This file is part of Monte Carlo eXtreme (MCX) URL:http://mcx.sf.net 10 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 11 | 12 | clear cfg 13 | cfg.nphoton=1e7; 14 | cfg.vol=uint8(ones(60,60,60)); 15 | cfg.srctype='pattern'; 16 | cfg.srcpos=[-40,-40, 0]; 17 | cfg.srcparam1=[80 0 0 100]; 18 | cfg.srcparam2=[0 80 0 100]; 19 | cfg.srcdir=[0 0 1 30]; 20 | cfg.issrcfrom0=1; 21 | cfg.srcpattern=zeros(100,100); 22 | cfg.srcpattern(51:end,51:end)=1; 23 | cfg.gpuid=1; 24 | cfg.autopilot=1; 25 | cfg.prop=[0 0 1 1;0.005 0.1 0 1]; 26 | cfg.tstart=0; 27 | cfg.tend=5e-9; 28 | cfg.tstep=5e-09; 29 | cfg.bc='mm____'; 30 | 31 | flux=mcxlab(cfg); 32 | 33 | mcxplotvol(log10(double(flux.data))) 34 | -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_fullhead_atlas.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % MCXLAB - Monte Carlo eXtreme for MATLAB/Octave by Qianqina Fang 3 | % 4 | % In this example, we demonstrate light transport simulation in a full-head 5 | % atlas template(USC 19.5 year group[Sanchez2012]). 6 | % 7 | % This demo is identical to the MCX simulation used for Fig.9(a) in 8 | % TranYan2019(submitted). 9 | % 10 | % [Sanchez2012] C.E.Sanchez J.E.Richards and C.R.Almli, “Age-Specific MRI Templates 11 | % for Pediatric Neuroimaging,” Developmental Neuropsychology 37, 379–399 (2012). 12 | % 13 | % [TranYan2019] A.P.Tran, S.Yan and Q.Fang, "Improving model-based fNIRS 14 | % analysis using mesh-based anatomical and light-transport models". 15 | % 16 | % This file is part of Monte Carlo eXtreme (MCX) URL:http://mcx.sf.net 17 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 18 | 19 | clc 20 | clear 21 | load('fullhead_atlas.mat'); 22 | %% prepare cfg for MCX simulation 23 | clear cfg 24 | cfg.nphoton=1e8; 25 | cfg.outputtype='fluence'; 26 | 27 | % tissue labels:0-ambient air,1-scalp,2-skull,3-csf,4-gray matter,5-white matter,6-air cavities 28 | cfg.vol=USC_atlas; 29 | cfg.prop=[0,0,1,1;0.019 7.8 0.89 1.37;0.02 9.0 0.89 1.37;0.004 0.009 0.89 1.37;0.019 7.8 0.89 1.37;0.08 40.9 0.84 1.37;0,0,1,1]; 30 | 31 | % light source 32 | cfg.srcnum=1; 33 | cfg.srcpos=[133.5370,90.1988,200.0700]; %pencil beam source placed at EEG 10-5 landmark:"C4h" 34 | cfg.srctype='pencil'; 35 | cfg.srcdir=[-0.5086,-0.1822,-0.8415]; %inward-pointing source 36 | cfg.issrcfrom0=1; 37 | 38 | % time windows 39 | cfg.tstart=0; 40 | cfg.tend=5e-9; 41 | cfg.tstep=5e-10; 42 | 43 | % other simulation parameters 44 | cfg.isspecular=0; 45 | cfg.isreflect=1; 46 | cfg.autopilot=1; 47 | cfg.gpuid=1; 48 | 49 | %% run MCX simulation 50 | [flux]=mcxlabcl(cfg); 51 | 52 | %% post-simulation data processing and visualization 53 | % convert time-resolved fluence to CW fluence 54 | CWfluence=sum(flux.data,4); 55 | 56 | % coronal plane selected for fluence plot 57 | y_plane=90.5; 58 | [xx,zz]=meshgrid(1:size(cfg.vol,1),1:size(cfg.vol,3)); 59 | 60 | % plot CW fluence distribution using contour lines 61 | figure; 62 | clines=-20:0.5:0; 63 | contourf(xx,zz,log10(abs(squeeze(CWfluence(:,ceil(y_plane),:))')),clines,'linestyle','--','color',[0.9100 0.4100 0.1700],'linewidth',1.5,'DisplayName','MCX'); 64 | hold on;axis equal; 65 | colorbar('EastOutside'); 66 | 67 | % plot tissue boundary contour, source, legend, etc. 68 | contour(squeeze(cfg.vol(:,ceil(y_plane),:))','k--','linewidth',1.25,'HandleVisibility','off'); 69 | plot(cfg.srcpos(1,1),cfg.srcpos(1,3),'o','MarkerEdgeColor','r','MarkerFaceColor','r','MarkerSize',10,'DisplayName','source'); 70 | lg=legend('Location','northeast'); 71 | set(lg,'color','[0.85 0.85 0.85]'); 72 | set(lg,'box','on'); 73 | set(gca,'ylim', [160 225]);ylabel('z [mm]'); 74 | set(gca,'xlim', [10 165]);xlabel('x [mm]'); 75 | set(gca,'clim',[-12 0]); 76 | set(gca,'fontsize',18); 77 | set(gca, 'FontName', 'Times New Roman'); 78 | -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_infinite_slab_cyclic_bc.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % MCXLAB - Monte Carlo eXtreme for MATLAB/Octave by Qianqina Fang 3 | % 4 | % In this example, we show how to simulate an infinite slab using cyclic 5 | % boundary condition 6 | % 7 | % This file is part of Monte Carlo eXtreme (MCX) URL:http://mcx.sf.net 8 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 9 | 10 | clear cfg; 11 | cfg.nphoton=1e8; 12 | cfg.issrcfrom0=1; 13 | cfg.vol=uint8(ones(60,60,20)); 14 | cfg.srcdir=[0 0 1]; 15 | cfg.gpuid=1; 16 | cfg.autopilot=1; 17 | cfg.prop=[0 0 1 1;0.005 2 0.8 1.37]; 18 | cfg.tstart=0; 19 | cfg.seed=99999; 20 | 21 | % a uniform planar source outside the volume 22 | cfg.srctype='planar'; 23 | cfg.srcpos=[0 0 0]; 24 | cfg.srcparam1=[60 0 0 0]; 25 | cfg.srcparam2=[0 60 0 0]; 26 | cfg.tend=5e-9; 27 | cfg.tstep=5e-9; 28 | cfg.bc='ccrccr'; 29 | flux=mcxlabcl(cfg); 30 | 31 | fcw=flux.data*cfg.tstep; 32 | subplot(121); 33 | imagesc(log10(abs(squeeze(fcw(:,30,:))))) 34 | axis equal; colorbar 35 | set(gca,'xlim',[0 size(cfg.vol,3)]); 36 | title('a uniform planar source incident along an infinite slab'); 37 | 38 | subplot(122); 39 | semilogy(squeeze(mean(mean(fcw,2),1))) 40 | title('averaged light attenuation profile'); 41 | ylabel('averaged CW fluence 1/mm^2') 42 | xlabel('depth (mm)') 43 | -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_lambertian_exit_angle.m: -------------------------------------------------------------------------------- 1 | %========================================================================== 2 | % Script to verify Lambertian photon exiting angular profile 3 | % 4 | % Author: Qianqian Fang 5 | % Initial version: May 5, 2018 6 | %========================================================================== 7 | 8 | clear cfg 9 | cfg.nphoton=1e8; 10 | cfg.vol=uint8(ones(60,60,60)); 11 | cfg.srcpos=[20, 30, 0]; 12 | cfg.srcdir=[0 0 1]; 13 | 14 | cfg.maxdetphoton=1500000; 15 | cfg.gpuid=1; 16 | cfg.autopilot=1; 17 | 18 | cfg.prop=[0 0 1 1;0.005 1 0 1.37]; 19 | 20 | cfg.tstart=0; 21 | cfg.tend=5e-9; 22 | cfg.tstep=5e-9; 23 | 24 | cfg.issrcfrom0=1; 25 | cfg.isreflect=1; 26 | cfg.issaveexit=1; 27 | 28 | cfg.detpos = [25 30 0 2]; 29 | 30 | %cfg.prop=[0 0 1 1;0.005 0.01 0 1.37]; %try this low-scattering case 31 | 32 | % calculate the flux distribution with the given config 33 | [flux1,detp1] = mcxlabcl(cfg); 34 | 35 | % it took me a while to figure out, but the key is to divide the area :) 36 | 37 | el=asin(detp1.v(:,3)); % elevation angle of v, el=0 parallel to surface, el=pi/2 at normal dir 38 | 39 | edges=linspace(min(el),max(el),100); % angle bins for hisotogram 40 | 41 | [ct, bin]=histc(el,edges); % count of photons per angle bin 42 | 43 | R=cfg.detpos(1,4); % radius of the det 44 | hedges=abs(R*sin(edges)); % height of each spherical segment for each bin 45 | zonearea=2*pi*R*(diff(hedges)); % area of each spherical segment 46 | 47 | detweight=mmcdetweight(detp1, cfg.prop); % get detected photon weight 48 | angularweight=accumarray(bin,detweight); % sum total weight per zone 49 | 50 | angularflux=angularweight(1:end-1)'./zonearea; % calculate flux per angle 51 | 52 | polar((edges(1:end-1)+edges(2:end))*0.5, angularflux); % plot flux vs angle 53 | hold on; 54 | polar(pi-(edges(1:end-1)+edges(2:end))*0.5, angularflux); % mirror to form a circle -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_mcxlab_2d.m: -------------------------------------------------------------------------------- 1 | %========================================================================== 2 | % A sample 2D MCX simulation 3 | % 4 | % Author: Qianqian Fang 5 | %========================================================================== 6 | 7 | % you must define a 3D array with one singleton dimension (with length 1). 8 | % unfortunately if you define z as singleton, matlab will make the array 2D 9 | % instead of 3D, so we have to purmute it to make the 1st dimension 10 | % singleton. 11 | 12 | cfg.nphoton=1e6; 13 | 14 | cfg.vol=permute(uint8(ones(100,100)), [3,1,2]); % from 2d to 3d 15 | cfg.vol(1,30:70, 10:50)=2; 16 | cfg.issrcfrom0=1; 17 | cfg.srctype='pencil'; 18 | 19 | cfg.srcpos=[0,50,0]; % src position must be located in the 2D plane 20 | cfg.srcdir=[0 0 1]; % src dir must align in the plan (y-z in this case) 21 | 22 | cfg.gpuid=1; 23 | cfg.autopilot=1; 24 | cfg.gscatter=100; 25 | 26 | myprop=[0.02 0.1 0.9 1.37; 0.02 10 0.9 1.37*5]; 27 | 28 | cfg.prop=[0 0 1 1; myprop]; 29 | cfg.tstart=0; 30 | cfg.tend=1e-8; 31 | cfg.tstep=1e-8; 32 | flux=mcxlabcl(cfg); 33 | 34 | cw=squeeze(sum(flux.data,4)); 35 | figure; 36 | imagesc(log10(abs(cw))) -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_mcxlab_basic.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % MCXLAB - Monte Carlo eXtreme for MATLAB/Octave by Qianqina Fang 3 | % 4 | % In this example, we show the most basic usage of MCXLAB. 5 | % 6 | % This file is part of Monte Carlo eXtreme (MCX) URL:http://mcx.sf.net 7 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 8 | 9 | clear cfg cfgs 10 | cfg.nphoton=1e7; 11 | cfg.vol=uint8(ones(60,60,60)); 12 | cfg.srcpos=[30 30 1]; 13 | cfg.srcdir=[0 0 1]; 14 | cfg.gpuid=1; 15 | % cfg.gpuid='11'; % use two GPUs together 16 | cfg.autopilot=1; 17 | cfg.prop=[0 0 1 1;0.005 1 0 1.37]; 18 | cfg.tstart=0; 19 | cfg.tend=5e-9; 20 | cfg.tstep=1e-10; 21 | 22 | % calculate the flux distribution with the given config 23 | flux=mcxlabcl(cfg); 24 | 25 | 26 | cfgs(1)=cfg; 27 | cfgs(2)=cfg; 28 | cfgs(1).isreflect=0; 29 | cfgs(2).isreflect=1; 30 | cfgs(2).detpos=[30 20 1 1;30 40 1 1;20 30 1 1;40 30 1 1]; 31 | % calculate the flux and partial path lengths for the two configurations 32 | [fluxs,detps]=mcxlabcl(cfgs); 33 | 34 | imagesc(squeeze(log(fluxs(1).data(:,30,:,1)))-squeeze(log(fluxs(2).data(:,30,:,1)))); 35 | -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_mcxlab_replay.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % MCXLAB - Monte Carlo eXtreme for MATLAB/Octave by Qianqina Fang 3 | % 4 | % In this example, we show the most basic usage of MCXLAB. 5 | % 6 | % This file is part of Monte Carlo eXtreme (MCX) URL:http://mcx.sf.net 7 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 8 | 9 | clear cfg cfgs 10 | cfg.nphoton=1e8; 11 | cfg.vol=uint8(ones(60,60,60)); 12 | cfg.srcpos=[30 30 0]; 13 | cfg.srcdir=[0 0 1]; 14 | cfg.gpuid=1; 15 | % cfg.gpuid='11'; % use two GPUs together 16 | cfg.autopilot=1; 17 | cfg.issrcfrom0=1; 18 | cfg.prop=[0 0 1 1;0.005 1 0 1.37]; 19 | cfg.tstart=0; 20 | cfg.tend=5e-9; 21 | cfg.tstep=5e-10; 22 | % calculate the flux distribution with the given config 23 | cfg.detpos=[15 30 0 2]; 24 | %cfg.savedetflag='dsp'; 25 | [flux, detp, vol, seeds]=mcxlab(cfg); 26 | 27 | newcfg=cfg; 28 | newcfg.seed=seeds.data; 29 | newcfg.outputtype='jacobian'; 30 | newcfg.detphotons=detp.data; 31 | [flux2, detp2, vol2, seeds2]=mcxlab(newcfg); 32 | jac=sum(flux2.data,4); 33 | imagesc(log10(abs(squeeze(jac(:,30,:))))) 34 | -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_mcxlabcl_basic.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % MCXLAB-CL - Monte Carlo eXtreme for MATLAB/Octave by Qianqina Fang 3 | % 4 | % In this example, we show the most basic usage of MCXLAB. 5 | % 6 | % This file is part of Monte Carlo eXtreme (MCX) URL:http://mcx.sf.net 7 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 8 | 9 | clear cfg cfgs 10 | cfg.nphoton=1e7; 11 | cfg.vol=uint8(ones(60,60,60)); 12 | cfg.srcpos=[30 30 1]; 13 | cfg.srcdir=[0 0 1]; 14 | cfg.gpuid=1; 15 | % cfg.gpuid='11'; % use two GPUs together 16 | cfg.autopilot=1; 17 | cfg.prop=[0 0 1 1;0.005 1 0 1.37]; 18 | cfg.tstart=0; 19 | cfg.tend=5e-9; 20 | cfg.tstep=1e-10; 21 | % calculate the flux distribution with the given config 22 | flux=mcxlabcl(cfg); 23 | 24 | 25 | cfgs(1)=cfg; 26 | cfgs(2)=cfg; 27 | cfgs(1).isreflect=0; 28 | cfgs(2).isreflect=1; 29 | cfgs(2).detpos=[30 20 1 1;30 40 1 1;20 30 1 1;40 30 1 1]; 30 | % calculate the flux and partial path lengths for the two configurations 31 | [fluxs,detps]=mcxlabcl(cfgs); 32 | 33 | imagesc(squeeze(log(fluxs(1).data(:,30,:,1)))-squeeze(log(fluxs(2).data(:,30,:,1)))); 34 | -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_mcxyz_skinvessel.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % mcxyz skinvessel benchmark 3 | % 4 | % must change mcxyz maketissue.m boundaryflag variable from 2 to 1 to get 5 | % comparable absorption fraction (40%), otherwise, mcxyz obtains slightly 6 | % higher absorption (~42%) with boundaryflag=2 7 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 8 | 9 | clear cfg flux 10 | 11 | %load mcxyz_skinvessel.mat 12 | 13 | cfg.vol=zeros(200,200,200); 14 | cfg.shapes=['{"Shapes":[{"ZLayers":[[1,20,1],[21,32,4],[33,200,3]]},' ... 15 | '{"Cylinder": {"Tag":2, "C0": [0,100.5,100.5], "C1": [200,100.5,100.5], "R": 20}}]}']; 16 | cfg.unitinmm=0.005; 17 | cfg.prop=[0.0000 0.0 1.0000 1 18 | 3.5640e-05 1.0000 1.0000 1.3700 19 | 23.0543 9.3985 0.9000 1.3700 20 | 0.0458 35.6541 0.9000 1.3700 21 | 1.6572 37.5940 0.9000 1.3700]; 22 | 23 | cfg.nphoton=1e8; 24 | cfg.issrcfrom0=1; 25 | cfg.srcpos=[100 100 20]; 26 | cfg.tstart=0; 27 | cfg.tend=5e-8; 28 | cfg.tstep=5e-8; 29 | cfg.srcdir=[0 0 1]; 30 | cfg.srctype='disk'; 31 | cfg.srcparam1=[0.3/cfg.unitinmm 0 0 0]; 32 | cfg.isreflect=0; 33 | cfg.autopilot=1; 34 | cfg.gpuid=1; 35 | cfg.debuglevel='P'; 36 | 37 | %cfg.outputtype='energy'; 38 | cfg.outputtype='flux'; 39 | flux=mcxlabcl(cfg); 40 | 41 | % convert mcx solution to mcxyz's output 42 | % 'energy': mcx outputs normalized energy deposition, must convert 43 | % it to normalized energy density (1/cm^3) as in mcxyz 44 | % 'flux': cfg.tstep is used in mcx's fluence normalization, must 45 | % undo 100 converts 1/mm^2 from mcx output to 1/cm^2 as in mcxyz 46 | if(strcmp(cfg.outputtype,'energy')) 47 | mcxdata=flux.data/((cfg.unitinmm/10)^3); 48 | else 49 | mcxdata=flux.data*100; 50 | end 51 | 52 | if(strcmp(cfg.outputtype,'flux')) 53 | mcxdata=mcxdata*cfg.tstep; 54 | end 55 | 56 | figure; 57 | dim=size(cfg.vol); 58 | yi=((1:dim(2))-floor(dim(2)/2))*cfg.unitinmm; 59 | zi=(1:dim(3))*cfg.unitinmm; 60 | 61 | imagesc(yi,zi,log10(abs(squeeze(mcxdata(100,:,:))))') 62 | axis equal; 63 | colormap(jet); 64 | colorbar 65 | if(strcmp(cfg.outputtype,'energy')) 66 | set(gca,'clim',[-2.4429 4.7581]) 67 | else 68 | set(gca,'clim',[0.5 2.8]) 69 | end 70 | -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_photon_sharing.m: -------------------------------------------------------------------------------- 1 | clear cfg; 2 | 3 | mcximg=[0 1 1 0 0 0 0 0 1 1 0 4 | 0 0 0 1 1 0 1 1 0 0 0 5 | 0 0 0 0 0 1 0 0 0 0 0 6 | 0 0 0 1 1 0 1 1 0 0 0 7 | 0 1 1 0 0 0 0 0 1 1 0 8 | 0 0 0 0 0 0 0 0 0 0 0 9 | 0 0 1 0 0 0 0 0 1 0 0 10 | 0 1 0 0 0 0 0 0 0 1 0 11 | 0 1 0 0 0 0 0 0 0 1 0 12 | 0 1 0 0 0 0 0 0 0 1 0 13 | 0 0 1 1 1 1 1 1 1 0 0 14 | 0 0 0 0 0 0 0 0 0 0 0 15 | 0 1 1 1 1 1 1 1 1 1 0 16 | 0 0 0 1 0 0 0 0 0 0 0 17 | 0 0 0 0 1 1 0 0 0 0 0 18 | 0 0 0 1 0 0 0 0 0 0 0 19 | 0 1 1 1 1 1 1 1 1 1 0 20 | 0 0 0 0 0 0 0 0 0 0 0]; 21 | 22 | cfg.nphoton=1e7; 23 | cfg.vol=uint8(ones(60,60,60)); 24 | cfg.vol(:,:,1)=0; 25 | cfg.issaveref=1; 26 | cfg.srctype='pattern'; 27 | cfg.srcpattern=permute(reshape(mcximg,[6,3,size(mcximg,2)]),[2 1 3]); 28 | cfg.srcnum=3; 29 | cfg.srcpos=[0 0 0]; 30 | cfg.issrcfrom0=1; 31 | cfg.srcdir=[0 0 1]; 32 | cfg.srcparam1=[60 0 0 size(cfg.srcpattern,2)]; 33 | cfg.srcparam2=[0 60 0 size(cfg.srcpattern,3)]; 34 | cfg.tstart=0; 35 | cfg.tend=5e-9; 36 | cfg.tstep=5e-9; 37 | cfg.voidtime=0; 38 | cfg.gpuid=1; 39 | cfg.autopilot=1; 40 | cfg.prop=[0 0 1 1;0.005 1 0.8 1.37]; 41 | cfg.seed=99999; 42 | 43 | % when photon sharing is used, the detpt.w0 output of detected photon stores the 44 | % 1-D index of the pixel within a 2D pattern (col-major, starting from 0) 45 | % where the photon was initially launched. using detpt.w0, one can look up 46 | % the initial launch weight of each photon in all patterns 47 | 48 | cfg.detpos=[25 30 0 2]; 49 | cfg.savedetflag='dpw'; 50 | 51 | [flux, detpt]=mcxlabcl(cfg); 52 | 53 | fcw=flux.data*cfg.tstep; 54 | for i=1:3 55 | subplot(1,3,i); 56 | hs=slice(log10(abs(double(fcw(:,:,:,i)))),1,1,2); 57 | view([1 1 1]) 58 | set(hs,'linestyle','none'); 59 | axis equal; colorbar 60 | title(sprintf('pattern #%d',i)); 61 | end 62 | figure; 63 | fcw=flux.dref*cfg.tstep; 64 | for i=1:3 65 | subplot(1,3,i); 66 | hs=slice(log10(abs(double(fcw(:,:,:,i)))),1,1,1); 67 | view([1 1 1]) 68 | set(hs,'linestyle','none'); 69 | axis equal; colorbar 70 | title(sprintf('pattern #%d',i)); 71 | end 72 | 73 | figure; 74 | hist(double(detpt.w0)) 75 | xlabel('1D pixel index of the launch position'); 76 | -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_qtest_subpixel.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % MCXLAB - Monte Carlo eXtreme for MATLAB/Octave by Qianqina Fang 3 | % 4 | % In this example, we test the sub-millimeter voxel feature using 5 | % the settings in examples/quicktest (i.e. comparing run_qtest.sh and 6 | % run_grid2x.sh) 7 | % 8 | % This file is part of Monte Carlo eXtreme (MCX) URL:http://mcx.sf.net 9 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 10 | 11 | cfg.nphoton=1e7; 12 | cfg.vol=uint8(ones(60,60,60)); 13 | cfg.srcpos=[30 30 1]; 14 | cfg.srcdir=[0 0 1]; 15 | cfg.gpuid=1; 16 | cfg.autopilot=1; 17 | cfg.prop=[0 0 1 1;0.005 1 0 1.0]; 18 | cfg.tstart=0; 19 | cfg.tend=5e-9; 20 | cfg.tstep=5e-9; 21 | % calculate the flux distribution with the given config 22 | [f1,det1]=mcxlabcl(cfg); 23 | 24 | cfg.vol=uint8(ones(120,120,120)); 25 | cfg.srcpos=[60 60 1]; 26 | cfg.unitinmm=0.5; 27 | cfg.nphoton=8e7; % you need to simulate 8x photons to get the same noise 28 | 29 | [f2,det2]=mcxlabcl(cfg); 30 | 31 | figure; 32 | subplot(121); 33 | imagesc(squeeze(log(f1(1).data(:,30,:,1)))); 34 | colorbar;axis equal;axis off; 35 | cl=get(gca,'clim'); 36 | subplot(122); 37 | imagesc(squeeze(log(f2(1).data(:,60,:,1)))); 38 | colorbar;axis equal;axis off; 39 | set(gca,'clim',cl); 40 | -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_replay_timedomain.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % MCXLAB - Monte Carlo eXtreme for MATLAB/Octave by Qianqina Fang 3 | % 4 | % In this example, we show how to use replay to obtain time-resolved 5 | % Jacobians - setting cfg.replaydet to -1 to replay all detectors 6 | % 7 | % This file is part of Monte Carlo eXtreme (MCX) URL:http://mcx.sf.net 8 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 9 | 10 | clear cfg cfgs 11 | cfg.nphoton=1e8; 12 | cfg.vol=uint8(ones(60,60,20)); 13 | cfg.srcpos=[30 30 0]; 14 | cfg.srcdir=[0 0 1]; 15 | cfg.gpuid=1; 16 | % cfg.gpuid='11'; % use two GPUs together 17 | cfg.autopilot=1; 18 | cfg.issrcfrom0=1; 19 | cfg.prop=[0 0 1 1;0.005 1 0 1.37]; 20 | cfg.tstart=0; 21 | cfg.tend=5e-9; 22 | cfg.tstep=2e-10; 23 | % calculate the flux distribution with the given config 24 | cfg.detpos=[30 30 20 2; 30 40 20 2; 30 50 20 2]; 25 | [flux, detp, vol, seeds]=mcxlabcl(cfg); 26 | 27 | %cfg.replaydet=0; % replay all det and sum all 28 | %cfg.replaydet=2; % replay only the 2nd detector 29 | %cfg.replaydet=3; % replay only the 3rd detector 30 | cfg.replaydet=-1; % replay all det and save all 31 | 32 | newcfg=cfg; 33 | newcfg.seed=seeds.data; 34 | newcfg.outputtype='jacobian'; 35 | newcfg.detphotons=detp.data; 36 | [flux2, detp2, vol2, seeds2]=mcxlabcl(newcfg); 37 | for i=1:size(flux2.data,4) 38 | imagesc(log10(abs(squeeze(flux2.data(30,:,:,i))))) 39 | title(sprintf('%d',i)); 40 | waitforbuttonpress; 41 | end 42 | jac=sum(flux2.data,4); 43 | for i=1:size(jac,ndims(jac)) 44 | subplot(1,size(jac,ndims(jac)),i); 45 | imagesc(log10(abs(squeeze(jac(30,:,:,i))))) 46 | end 47 | -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_replay_vs_pmc_timedomain.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % MCXLAB - Monte Carlo eXtreme for MATLAB/Octave by Qianqina Fang 3 | % 4 | % In this example, we compare perturbation MC and replay in predicting 5 | % time-resolved measurement change with respect to mua change in a layer 6 | % 7 | % This file is part of Monte Carlo eXtreme (MCX) URL:http://mcx.sf.net 8 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 9 | 10 | clear cfg 11 | cfg.nphoton=2e8; 12 | cfg.vol=uint8(ones(60,60,30)); 13 | cfg.vol(:,:,15:end)=2; 14 | cfg.srcpos=[30 30 0]; 15 | cfg.srcdir=[0 0 1]; 16 | cfg.gpuid=1; 17 | % cfg.gpuid='11'; % use two GPUs together 18 | cfg.autopilot=1; 19 | cfg.issrcfrom0=1; 20 | cfg.prop=[0 0 1 1;0.005 1 0 1.37; 0.01 1 0 1.37]; 21 | cfg.tstart=0; 22 | cfg.tend=5e-9; 23 | cfg.tstep=2e-10; 24 | cfg.detpos=[15 30 0 2]; 25 | [flux, detp, vol, seeds]=mcxlabcl(cfg); 26 | 27 | %% replay to get time-domain J_mua 28 | 29 | newcfg=cfg; 30 | newcfg.seed=seeds.data; 31 | newcfg.outputtype='jacobian'; 32 | newcfg.detphotons=detp.data; 33 | [flux2, detp2, vol2, seeds2]=mcxlabcl(newcfg); 34 | jac=flux2.data; 35 | 36 | %% predict time-domain measurement change using pMC and partial-path 37 | 38 | dmua=0.0001; 39 | w1=mcxdetweight(detp,cfg.prop); 40 | dprop=cfg.prop; 41 | dprop(3,1)=dprop(3,1)+dmua; 42 | w2=mcxdetweight(detp,dprop); 43 | dw=w2-w1; 44 | tof=mcxdettime(detp,cfg.prop); 45 | [counts, idx]=histc(tof,0:cfg.tstep:cfg.tend); 46 | 47 | %% predict time-domain measurement change using TD Jacobian and compare 48 | 49 | dphi=zeros(size(jac,4),1); % change of measurements using replay Jacobian 50 | dphi2=zeros(size(jac,4),1); % change of measurements from pMC 51 | 52 | for i=1:size(jac,4) 53 | dmeas=jac(:,:,15:end,i)*dmua; 54 | dphi(i)=-sum(dmeas(:)); 55 | dphi2(i)=sum(dw(idx==i))/sum(w1); 56 | end 57 | 58 | plot(1:size(jac,4), dphi, 'r-+',1:size(jac,4), dphi2, 'g-+'); 59 | legend('use replay Jacobian','use pMC') 60 | xlabel('time gates') 61 | ylabel('measurement change') -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_sphere_cube_subpixel.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % MCXLAB - Monte Carlo eXtreme for MATLAB/Octave by Qianqina Fang 3 | % 4 | % In this example, we demonstrate how to use sub-pixel resolution 5 | % to represent the problem domain. The domain is consisted of a 6 | % 6x6x6 cm box with a 2cm diameter sphere embedded at the center. 7 | % 8 | % This file is part of Monte Carlo eXtreme (MCX) URL:http://mcx.sf.net 9 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 10 | 11 | clear cfg; 12 | 13 | % set seed to make the simulation repeatible 14 | cfg.seed=hex2dec('623F9A9E'); 15 | 16 | cfg.nphoton=1e7; 17 | 18 | % define a 1cm radius sphere within a 6x6x6 cm box 19 | dim=60; 20 | [xi,yi,zi]=meshgrid(1:dim,1:dim,1:dim); 21 | dist=(xi-30).^2+(yi-30).^2+(zi-30).^2; 22 | cfg.vol=ones(size(xi)); 23 | cfg.vol(dist<100)=2; 24 | cfg.vol=uint8(cfg.vol); 25 | 26 | % define the source position 27 | cfg.srcpos=[30,30,0]+1; 28 | cfg.srcdir=[0 0 1]; 29 | 30 | % format: [mua(1/mm) mus(1/mm) g n] 31 | cfg.prop=[0 0 1 1 % medium 0: the environment 32 | 0.002 1.0 0.01 1.37 % medium 1: cube 33 | 0.050 0.5 0.01 1.37]; % medium 2: spherical inclusion 34 | 35 | % time-domain simulation parameters 36 | cfg.tstart=0; 37 | cfg.tend=5e-9; 38 | cfg.tstep=5e-10; 39 | 40 | % GPU thread configuration 41 | cfg.autopilot=1; 42 | cfg.gpuid=1; 43 | 44 | cfg.isreflect=1; % enable reflection at exterior boundary 45 | cfg.isrefint=1; % enable reflection at interior boundary too 46 | 47 | fprintf('running simulation ... this takes about 3 seconds on a GTX 470\n'); 48 | tic; 49 | f1=mcxlabcl(cfg); 50 | toc; 51 | 52 | % define a 1cm radius sphere within a 6x6x6 cm box with a 0.5mm resolution 53 | dim=120; 54 | [xi,yi,zi]=meshgrid(1:dim,1:dim,1:dim); 55 | dist=(xi-60).^2+(yi-60).^2+(zi-60).^2; 56 | cfg.vol=ones(size(xi)); 57 | cfg.vol(dist<400)=2; 58 | cfg.srcpos=[60,60,0]+1; 59 | cfg.vol=uint8(cfg.vol); 60 | 61 | cfg.unitinmm=0.5; % define the pixel size in terms of mm 62 | cfg.nphoton=8e7; % you need to simulate 8x photons to get the same noise 63 | 64 | fprintf('running simulation ... this takes about 40 seconds on a GTX 470\n'); 65 | tic; 66 | [f2,det2]=mcxlabcl(cfg); 67 | toc; 68 | 69 | % plot the results 70 | figure 71 | subplot(121); 72 | if(exist('OCTAVE_VERSION')~=0) 73 | imagesc(log10(squeeze(sum(f1.data(:,30,:,:),4))')); 74 | else 75 | contourf(log10(squeeze(sum(f1.data(:,30,:,:),4))'),1:0.5:8); 76 | end 77 | axis equal; 78 | colorbar('SouthOutside'); 79 | title('simulation with 1x1x1 mm resolution'); 80 | 81 | subplot(122); 82 | if(exist('OCTAVE_VERSION')~=0) 83 | imagesc(log10(squeeze(sum(f2.data(:,60,:,:),4))')); 84 | else 85 | contourf(log10(squeeze(sum(f2.data(:,60,:,:),4))'),1:0.5:8); 86 | end 87 | axis equal; 88 | colorbar('SouthOutside'); 89 | title('simulation with 0.5x0.5x0.5 mm resolution'); 90 | -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_test_csf.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % Error evaluation when assuming musp(CSF) with 1/average(thickness) 3 | % from Custo Applied Optics 2006 4 | % 5 | % This file is part of Monte Carlo eXtreme (MCX) URL:http://mcx.sf.net 6 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 7 | clear cfg; 8 | 9 | %% preparing the input data 10 | % set seed to make the simulation repeatible 11 | cfg.seed=hex2dec('623F9A9E'); 12 | 13 | cfg.nphoton=2e8; 14 | 15 | % define a 4 layer structure 16 | cfg.vol=ones(100,100,50); 17 | cfg.vol(:,:,11:16)=2; 18 | cfg.vol(:,:,17:18)=3; 19 | cfg.vol(:,:,19:end)=4; 20 | cfg.vol=uint8(cfg.vol); 21 | 22 | % define the source position 23 | cfg.srcpos=[50,50,0]+1; 24 | cfg.srcdir=[0 0 1]; 25 | 26 | % use the brain optical properties defined at 27 | % http://mcx.sourceforge.net/cgi-bin/index.cgi?MMC/CollinsAtlasMesh 28 | % format: [mua(1/mm) mus(1/mm) g n] 29 | 30 | cfg.prop=[0 0 1 1 % medium 0: the environment 31 | 0.019 7.8 0.89 1.37 % medium 1: scalp 32 | 0.019 7.8 0.89 1.37 % medium 2: skull 33 | 0.004 0.009 0.89 1.37 % medium 3: CSF 34 | 0.02 9.0 0.89 1.37 % medium 4: gray matter 35 | 0.08 40.9 0.84 1.37]; % medium 5: white matter (not used) 36 | 37 | % time-domain simulation parameters 38 | cfg.tstart=0; 39 | cfg.tend=5e-9; 40 | cfg.tstep=5e-9; 41 | 42 | cfg.gscatter=50; % make scattering faster, with some approximations 43 | 44 | % GPU thread configuration 45 | cfg.autopilot=1; 46 | cfg.gpuid=1; 47 | 48 | cfg.isreflect=1; % enable reflection at exterior boundary 49 | 50 | % use literature CSF optical properties 51 | tic; 52 | f1=mcxlabcl(cfg); 53 | toc; 54 | 55 | % use approximated CSF mus', from Custo Applied Optics 2006 56 | %cfg.prop(4,:)=cfg.prop(3,:); % make csf the same as the scalp 57 | cfg.prop(4,2)=1/2; 58 | cfg.prop(4,3)=0; 59 | tic; 60 | f2=mcxlabcl(cfg); 61 | toc; 62 | 63 | % 64 | % cfg.prop(4,:)=cfg.prop(3,:); % make csf the same as the scalp 65 | % tic; 66 | % f3=mcxlabcl(cfg); 67 | % toc; 68 | 69 | dd=f1.data./f2.data; 70 | 71 | figure 72 | 73 | subplot(131) 74 | imagesc(log10(abs(squeeze(f1.data(:,51,:))))); 75 | axis equal; 76 | colorbar; 77 | title('with csf'); 78 | hold on; 79 | plot([10 10],[1 101],'--',[16 16],[1 101],'--',[18 18],[1 101],'--'); 80 | 81 | 82 | subplot(132) 83 | imagesc(log10(abs(squeeze(f2.data(:,51,:))))); 84 | axis equal; 85 | colorbar; 86 | title('csf mus''=1/thickness'); 87 | hold on; 88 | plot([10 10],[1 101],'--',[16 16],[1 101],'--',[18 18],[1 101],'--'); 89 | 90 | subplot(133) 91 | imagesc(log10(abs(squeeze(dd(:,51,:))))); 92 | axis equal; 93 | colorbar; 94 | title('difference log10(with/without)'); 95 | hold on; 96 | plot([10 10],[1 101],'--',[16 16],[1 101],'--',[18 18],[1 101],'--'); -------------------------------------------------------------------------------- /mcxlabcl/examples/demo_validation_heterogeneous.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % MCXLAB - Monte Carlo eXtreme for MATLAB/Octave by Qianqina Fang 3 | % 4 | % In this example, we validate the MCXLAB solver with a heterogeneous 5 | % domain and the analytical solution of the diffusion model. We also 6 | % demonstrate how to use sub-pixel resolution to refine the representation 7 | % of heterogeneities. The domain is consisted of a 6x6x6 cm box with a 8 | % 2cm diameter sphere embedded at the center. 9 | %. 10 | % This test is identical to that used for Fig. 3 in Fang2010. 11 | % 12 | % [Fang2010] Fang Q, "Mesh-based Monte Carlo method using fast ray-tracing 13 | % in Plücker coordinates," Biomed. Opt. Express 1, 165-175 (2010) 14 | % 15 | % This file is part of Monte Carlo eXtreme (MCX) URL:http://mcx.sf.net 16 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 17 | 18 | if(exist('sphdiffusionslab','file')~=2) 19 | error(sprintf('Script "sphdiffusionslab.m" was not found.\nThis demo requires you to add the "mmc/matlab" directory first.')); 20 | end 21 | 22 | clear cfg ana; 23 | 24 | %% preparing the input data 25 | % structure for sphere-diffusion toolbox for the analytical solution 26 | ana.v=299792458000; % mm/s 27 | ana.a=10; % radius, mm 28 | ana.omua=0.002; % outside mua 1/mm 29 | ana.omusp=1.0; % outside mus' 1/mm 30 | ana.imua=0.05; 31 | ana.imusp=0.5; 32 | ana.src=[30,pi,0]; 33 | ana.maxl=20; 34 | ana.omega=0; 35 | 36 | clines=-1:0.25:8; 37 | 38 | % set seed to make the simulation repeatible 39 | cfg.seed=hex2dec('623F9A9E'); 40 | 41 | cfg.nphoton=3e7; 42 | 43 | % define a 1cm radius sphere within a 6x6x6 cm box 44 | dim=60; 45 | [xi,yi,zi]=meshgrid(1:dim,1:dim,1:dim); 46 | dist=(xi-30.5).^2+(yi-30.5).^2+(zi-30.5).^2; 47 | cfg.vol=ones(size(xi)); 48 | cfg.vol(dist15) & za(:)>-10)=nan; 101 | phi_ana((xa(:)<-12 | xa(:)>12) & za(:)>0)=nan; 102 | 103 | %% plotting the results 104 | figure 105 | subplot(121); 106 | contourf(log10(squeeze(sum(f1.data(:,30,:,:),4))'),clines); 107 | hold on; 108 | c=contourc(squeeze(double(cfg.vol(:,30,:))),1); 109 | contour(xa+30.5,za+31,log10(abs(phi_ana/cfg.tstep)),clines,'color',[0.7 0.7 0.7],'linewidth',2); 110 | plot(c(1,2:end),c(2,2:end),'b--') 111 | axis equal; 112 | 113 | colorbar('NorthOutside'); 114 | title('simulation with 1x1x1 mm resolution'); 115 | 116 | subplot(122); 117 | [xx,yy]=meshgrid(0.5:0.5:dim/2,0.5:0.5:dim/2); 118 | contourf(xx,yy,log10(squeeze(sum(f2.data(:,60,:,:),4))'),clines); 119 | hold on; 120 | contour(xa+30,za+30.5,log10(abs(phi_ana/cfg2x.tstep)),clines,'color',[0.7 0.7 0.7],'linewidth',2); 121 | c=contourc(squeeze(double(cfg2x.vol(:,60,:))),1); 122 | plot(c(1,2:end)/2,c(2,2:end)/2,'b--') 123 | axis equal; 124 | colorbar('NorthOutside'); 125 | title('simulation with 0.5x0.5x0.5 mm resolution'); 126 | -------------------------------------------------------------------------------- /mcxlabcl/examples/digimouse.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jishanshaikh4/mcxcl/4c1830589e2e4615782e036c994a7e4688357b15/mcxlabcl/examples/digimouse.mat -------------------------------------------------------------------------------- /mcxlabcl/examples/fullhead_atlas.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jishanshaikh4/mcxcl/4c1830589e2e4615782e036c994a7e4688357b15/mcxlabcl/examples/fullhead_atlas.mat -------------------------------------------------------------------------------- /mcxlabcl/examples/mcx_gpu_benchmarks.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % MCXLAB - Monte Carlo eXtreme for MATLAB/Octave by Qianqina Fang 3 | % 4 | % Speed benchmarks for MCXLAB (equivalent to the examples in mcx/examples/benchmark) 5 | % 6 | % This file is part of Monte Carlo eXtreme (MCX) URL:http://mcx.sf.net 7 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 8 | 9 | clear cfg 10 | 11 | gpuinfo=mcxlabcl('gpuinfo'); 12 | 13 | cfg.gpuid=1; % gpuid can be an integer 1-N to specify the n-th GPU 14 | % or it can be a string containing only '0's and '1's. 15 | % exp: if gpuid='1010', it means the 1st and 3rd GPU are both used. 16 | 17 | %cfg.gpuid='111'; % on wazu, GPU#1,2,3 are 980Ti, 590 Core1 and Core 2 18 | %cfg.workload=[90,10,10]; % workload distribution between the 3 GPUs 19 | 20 | gpuid=cfg.gpuid; 21 | 22 | if(ischar(gpuid) && regexp(gpuid,'^[01]+$')) 23 | gpuid=char(gpuid)-'0'; 24 | lastdev=find(gpuid,1,'last'); 25 | if(lastdev>length(gpuinfo)) 26 | error('you specified a non-existant GPU'); 27 | end 28 | gpuid=gpuid(1:lastdev); 29 | elseif(isnumeric(gpuid) && gpuid>0) 30 | gpuid=[zeros(1,gpuid-1) 1]; 31 | else 32 | error('the specified GPU id is invalid'); 33 | end 34 | 35 | dates=datestr(now,'yyyy-mm-dd HH:MM:SS'); 36 | mcxbenchmark=struct('date',dates,'gpu',gpuinfo(gpuid==1)); 37 | 38 | try 39 | hbar=waitbar(0,'Running benchmarks #1'); 40 | catch 41 | hbar=[]; 42 | end 43 | count=0; 44 | 45 | cfg.nphoton=1e8; 46 | cfg.vol=uint8(ones(60,60,60)); 47 | cfg.srcpos=[29 29 0]; 48 | cfg.srcdir=[0 0 1]; 49 | cfg.issrcfrom0=1; 50 | cfg.autopilot=1; 51 | cfg.prop=[0 0 1 1;0.005 1 0.01 1.37;0.002 5.0 0.9, 1.0]; 52 | cfg.tstart=0; 53 | cfg.tend=5e-9; 54 | cfg.tstep=5e-9; 55 | cfg.seed=29012392; 56 | cfg.detpos=[29 19 0 1;29 39 0 1;19 29 0 1;39 29 0 1]; 57 | cfg.isreflect=0; 58 | % calculate the flux distribution with the given config 59 | 60 | speed=zeros(3); 61 | 62 | for i=1:size(speed,1) 63 | [flux, detps]=mcxlabcl(cfg); 64 | if(abs(flux.stat.energyabs/flux.stat.energytot-0.1769)>0.005 || ... 65 | abs(flux.stat.energytot-flux.stat.nphoton)>10) 66 | flux.stat 67 | error('output absorption fraction is incorrect'); 68 | end 69 | count=count+1; 70 | if(~isempty(hbar)) 71 | waitbar(count/9,hbar,'Running benchmarks #1'); 72 | end 73 | speed(i,1)=flux.stat.nphoton/flux.stat.runtime; 74 | end 75 | mcxbenchmark.benchmark1.stat=flux.stat; 76 | 77 | if(~isempty(hbar)) 78 | waitbar(count/9,hbar,'Running benchmarks #2'); 79 | end 80 | 81 | cfg.shapes='{"Shapes":[{"Sphere":{"Tag":2, "O":[30,30,30],"R":15}}]}'; 82 | cfg.isreflect=1; 83 | 84 | for i=1:size(speed,1) 85 | [flux, detps]=mcxlabcl(cfg); 86 | if(abs(flux.stat.energyabs/flux.stat.energytot-0.2701)>0.005|| ... 87 | abs(flux.stat.energytot-flux.stat.nphoton)>10) 88 | flux.stat 89 | error('output absorption fraction is incorrect'); 90 | end 91 | count=count+1; 92 | if(~isempty(hbar)) 93 | waitbar(count/9,hbar,'Running benchmarks #2'); 94 | end 95 | speed(i,2)=flux.stat.nphoton/flux.stat.runtime; 96 | end 97 | mcxbenchmark.benchmark2.stat=flux.stat; 98 | 99 | if(~isempty(hbar)) 100 | waitbar(count/9,hbar,'Running benchmarks #3'); 101 | end 102 | 103 | cfg=rmfield(cfg,'shapes'); 104 | cfg.srctype='planar'; 105 | cfg.srcparam1=[40 0 0 0]; 106 | cfg.srcparam2=[0 40 0 0]; 107 | cfg.srcpos=[10 10 -10]; 108 | 109 | for i=1:size(speed,1) 110 | [flux, detps]=mcxlabcl(cfg); 111 | if(abs(flux.stat.energyabs/flux.stat.energytot-0.2551)>0.005) 112 | flux.stat 113 | error('output absorption fraction is incorrect'); 114 | end 115 | count=count+1; 116 | if(~isempty(hbar)) 117 | waitbar(count/9,hbar,'Running benchmarks #3'); 118 | end 119 | speed(i,3)=flux.stat.nphoton/flux.stat.runtime; 120 | end 121 | mcxbenchmark.benchmark3.stat=flux.stat; 122 | 123 | speed=mean(speed); 124 | 125 | for i=1:length(speed) 126 | mcxbenchmark.(sprintf('benchmark%d',i)).speed=speed(i); 127 | end 128 | 129 | mcxbenchmark.speedsum=sum(speed); 130 | 131 | if(~isempty(hbar)) 132 | delete(hbar); 133 | end 134 | -------------------------------------------------------------------------------- /mcxlabcl/examples/mcx_gpu_contest.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % MCXLAB - Monte Carlo eXtreme for MATLAB/Octave by Qianqina Fang 3 | % 4 | % MCX GPU Contest 5 | % 6 | % This file is part of Monte Carlo eXtreme (MCX) URL:http://mcx.space 7 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 8 | 9 | %% ask user's basic information 10 | 11 | if(exist('savejson','file')~=2) 12 | error('this example requires savejson.m. please download it from https://github.com/fangq/jsonlab'); 13 | end 14 | 15 | prompt = {sprintf(['Please answer all below questions. Your public name can be your ' ... 16 | 'name or Internet name. Please also give your computer a name to ' ... 17 | 'distinguish your submission from different machines.\n\n' ... 18 | 'Your full name: (will not publish)']),'Email: (will not publish)',... 19 | 'Your public name:','Institution:','Machine name:','Comment: (optional)'}; 20 | dlg_title = 'MCX GPU Contest Submission'; 21 | num_lines = 1; 22 | defaultans = {'','','','','',''}; 23 | 24 | if(exist('contest_info.mat','file')) 25 | load contest_info.mat; 26 | end 27 | 28 | mcxuser = inputdlg(prompt,dlg_title,num_lines,defaultans); 29 | 30 | if(isempty(mcxuser)) 31 | return; 32 | end 33 | 34 | while(isempty(mcxuser{1}) || isempty(mcxuser{2}) || isempty(mcxuser{3}) || isempty(mcxuser{4}) || isempty(mcxuser{5})) 35 | hw=errordlg('missing required information'); 36 | uiwait(hw); 37 | mcxuser = inputdlg(prompt,dlg_title,num_lines,mcxuser); 38 | if(isempty(mcxuser)) 39 | error('user aborted submission.'); 40 | end 41 | end 42 | 43 | defaultans=mcxuser; 44 | save contest_info.mat defaultans; % save the filled data to be load in the future to save time 45 | 46 | %% run the built-in benchmarks 47 | 48 | choice = questdlg('Do you want to run the speed benchmarks? this may take a few minutes','Start Test','Yes','No','Yes'); 49 | if(isempty(choice) || strcmp(choice,'No')) 50 | return; 51 | end 52 | 53 | mcx_gpu_benchmarks 54 | 55 | %% generate benchmark report 56 | 57 | mcxbenchmark.version=1; 58 | mcxbenchmark.mcxversion='$Date:: $'; 59 | mcxbenchmark.userinfo=struct('name',mcxuser{1},'email',mcxuser{2},'nickname',mcxuser{3},... 60 | 'institution',mcxuser{4},'machine',mcxuser{5},'comment',mcxuser{6}); 61 | 62 | savejson(mcxbenchmark) 63 | 64 | choice = questdlg(sprintf('Your benchmark score is %.0f. Press Yes to submit; No to cancel',mcxbenchmark.speedsum),... 65 | 'Submission Confirmation','Yes','No','Yes'); 66 | if(isempty(choice) || strcmp(choice,'No')) 67 | return; 68 | end 69 | 70 | %% submit the benchmark report to the web portal 71 | 72 | gpustr=sprintf('%s/' ,mcxbenchmark.gpu(:).name); 73 | gpustr=regexprep(gpustr,'GeForce\s*',''); 74 | machinestr=sprintf('%s:/%s',mcxbenchmark.userinfo.machine,gpustr); 75 | 76 | submitstr={'name',urlencode(mcxbenchmark.userinfo.nickname), 'time',sprintf('%ld',round(8.64e4 * (now - datenum('1970', 'yyyy')))),... 77 | 'ver',urlencode(mcxbenchmark.mcxversion(8:end-1)), 'b1', sprintf('%.2f',speed(1)), 'b2', sprintf('%.2f',speed(2)), ... 78 | 'b3', sprintf('%.2f',speed(3)), 'score', sprintf('%.2f',mcxbenchmark.speedsum), ... 79 | 'computer',urlencode(machinestr), 'report',urlencode(savejson(mcxbenchmark))}; 80 | 81 | [s, status]=urlread('http://mcx.space/gpubench/gpucontest.cgi','post',submitstr); 82 | pause(2); 83 | 84 | if(isempty(s)) 85 | error('submission failed'); 86 | elseif(strcmp(s,sprintf('SUCCESS\n'))) 87 | hs=msgbox({'Submission is successful.','Please browse http://mcx.space/gpubench/ to see results.'},'Success','modal'); 88 | uiwait(hs); 89 | end 90 | -------------------------------------------------------------------------------- /mcxlabcl/examples/mcxyz_skinvessel.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jishanshaikh4/mcxcl/4c1830589e2e4615782e036c994a7e4688357b15/mcxlabcl/examples/mcxyz_skinvessel.mat -------------------------------------------------------------------------------- /mcxlabcl/mcxdetphoton.m: -------------------------------------------------------------------------------- 1 | function newdetp=mcxdetphoton(detp,medianum, savedetflag, issaveref, srcnum) 2 | 3 | c0=1; 4 | len=1; 5 | if(regexp(savedetflag,'[dD]')) 6 | if(nargin>3 && issaveref>1) 7 | newdetp.w0=detp(1,:)'; 8 | else 9 | newdetp.detid=int32(detp(1,:))'; 10 | end 11 | c0=2; 12 | end 13 | len=medianum; 14 | if(regexp(savedetflag,'[sS]')) 15 | newdetp.nscat=int32(detp(c0:(c0+len-1),:))'; % 1st medianum block is num of scattering 16 | c0=c0+len; 17 | end 18 | if(regexp(savedetflag,'[pP]')) 19 | newdetp.ppath=detp(c0:(c0+len-1),:)';% 2nd medianum block is partial path 20 | c0=c0+len; 21 | end 22 | if(regexp(savedetflag,'[mM]')) 23 | newdetp.mom=detp(c0:(c0+len-1),:)'; % 3rd medianum block is the momentum transfer 24 | c0=c0+len; 25 | end 26 | len=3; 27 | if(regexp(savedetflag,'[xX]')) 28 | newdetp.p=detp(c0:(c0+len-1),:)'; %columns 7-5 from the right store the exit positions 29 | c0=c0+len; 30 | end 31 | if(regexp(savedetflag,'[vV]')) 32 | newdetp.v=detp(c0:(c0+len-1),:)'; %columns 4-2 from the right store the exit dirs 33 | c0=c0+len; 34 | end 35 | if(regexp(savedetflag,'[wW]')) 36 | len=1; 37 | newdetp.w0=detp(c0:(c0+len-1),:)'; % last column is the initial packet weight 38 | if(nargin>4 && srcnum>1) 39 | newdetp.w0=typecast(newdetp.w0,'uint32'); 40 | end 41 | c0=c0+len; 42 | end -------------------------------------------------------------------------------- /setup/win64/apply_timeout_registry_fix.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | echo Patching your registry ... 3 | regedit /s launch_timeout_registry_fix.reg 4 | echo Done 5 | 6 | echo "You must reboot the computer for the setting to be affective" 7 | 8 | set /p option=press y to reboot: 9 | 10 | if %option%==y shutdown /r 11 | 12 | echo "Please remember to reboot the machine to run mcx" 13 | 14 | pause 15 | -------------------------------------------------------------------------------- /setup/win64/launch_timeout_registry_fix.reg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jishanshaikh4/mcxcl/4c1830589e2e4615782e036c994a7e4688357b15/setup/win64/launch_timeout_registry_fix.reg -------------------------------------------------------------------------------- /src/mcextreme.h: -------------------------------------------------------------------------------- 1 | #ifndef _MCEXTREME_AUTO_GENERATED_H_ 2 | #define _MCEXTREME_AUTO_GENERATED_H_ 3 | 4 | /**************************************************************************** 5 | 6 | Copyright (c) 2003, Stanford University 7 | All rights reserved. 8 | 9 | Copyright (c) 2008, Advanced Micro Devices, Inc. 10 | All rights reserved. 11 | 12 | 13 | The BRCC portion of BrookGPU is derived from the cTool project 14 | (http://ctool.sourceforge.net) and distributed under the GNU Public License. 15 | 16 | Additionally, see LICENSE.ctool for information on redistributing the 17 | contents of this directory. 18 | 19 | ****************************************************************************/ 20 | 21 | #include "brook/Stream.h" 22 | #include "brook/KernelInterface.h" 23 | 24 | //! Kernel declarations 25 | class __mcx_main_loop 26 | { 27 | public: 28 | void operator()(const int totalmove, const ::brook::Stream< uchar >& media, const ::brook::Stream< float >& field, const ::brook::Stream< float3 >& gproperty, const float3 vsize, const float minstep, const float lmax, const float gg, const float gg2, const float ggx2, const float one_add_gg2, const float one_sub_gg2, const float one_sub_gg, const float4 p0, const float4 c0, const float3 maxidx, const uint3 cp0, const uint3 cp1, const float4 cachebox, const uchar doreflect, const ::brook::Stream< float3 >& seed, const ::brook::Stream< float4 >& pos, const ::brook::Stream< float4 >& dir, const ::brook::Stream< float3 >& len, const ::brook::Stream< float3 >& n_seed, const ::brook::Stream< float4 >& n_pos, const ::brook::Stream< float4 >& n_dir, const ::brook::Stream< float3 >& n_len); 29 | EXTENDCLASS(); 30 | }; 31 | extern __THREAD__ __mcx_main_loop mcx_main_loop; 32 | 33 | #endif // _MCEXTREME_AUTO_GENERATED_H_ 34 | 35 | -------------------------------------------------------------------------------- /src/mcx_shapes.h: -------------------------------------------------------------------------------- 1 | #ifndef _MCEXTREME_RASTERIZER_H 2 | #define _MCEXTREME_RASTERIZER_H 3 | 4 | #include "vector_types.h" 5 | 6 | #ifdef __cplusplus 7 | extern "C" { 8 | #endif 9 | 10 | #define MAX_SHAPE_ERR 256 11 | 12 | typedef struct GridSpace{ 13 | unsigned int **vol; 14 | uint4 *dim; 15 | float3 orig; 16 | int rowmajor; 17 | } Grid3D; 18 | 19 | int mcx_load_jsonshapes(Grid3D *g, char *fname); 20 | int mcx_parse_jsonshapes(cJSON *root, Grid3D *g); 21 | int mcx_parse_shapestring(Grid3D *g, char *shapedata); 22 | int mcx_raster_origin(cJSON *obj, Grid3D *g); 23 | int mcx_raster_sphere(cJSON *obj, Grid3D *g); 24 | int mcx_raster_subgrid(cJSON *obj, Grid3D *g); 25 | int mcx_raster_box(cJSON *obj, Grid3D *g); 26 | int mcx_raster_cylinder(cJSON *obj, Grid3D *g); 27 | int mcx_raster_slabs(cJSON *obj, Grid3D *g); 28 | int mcx_raster_layers(cJSON *obj, Grid3D *g); 29 | int mcx_raster_upperspace(cJSON *obj, Grid3D *g); 30 | int mcx_raster_grid(cJSON *obj, Grid3D *g); 31 | int mcx_find_shapeid(char *shapename); 32 | char *mcx_last_shapeerror(); 33 | 34 | #ifdef __cplusplus 35 | } 36 | #endif 37 | 38 | #endif 39 | -------------------------------------------------------------------------------- /src/mcx_test_nextafter.cl: -------------------------------------------------------------------------------- 1 | /***************************************************************************//** 2 | ** \mainpage Monte Carlo eXtreme - GPU accelerated Monte Carlo Photon Migration \ 3 | ** -- OpenCL edition 4 | ** \author Qianqian Fang 5 | ** \copyright Qianqian Fang, 2009-2018 6 | ** 7 | ** \section sref Reference: 8 | ** \li \c (\b Yu2018) Leiming Yu, Fanny Nina-Paravecino, David Kaeli, and Qianqian Fang, 9 | ** "Scalable and massively parallel Monte Carlo photon transport simulations 10 | ** for heterogeneous computing platforms," J. Biomed. Optics, 23(1), 010504 (2018) 11 | ** 12 | ** \section slicense License 13 | ** GPL v3, see LICENSE.txt for details 14 | *******************************************************************************/ 15 | 16 | #ifdef USE_HALF 17 | #pragma OPENCL EXTENSION cl_khr_fp16 : enable 18 | #endif 19 | typedef struct KernelParams { 20 | float4 ps,c0; 21 | float4 maxidx; 22 | uint4 dimlen,cp0,cp1; 23 | uint2 cachebox; 24 | float minstep; 25 | float twin0,twin1,tmax; 26 | float oneoverc0; 27 | uint isrowmajor,save2pt,doreflect,dorefint,savedet; 28 | float Rtstep; 29 | float minenergy; 30 | float skipradius2; 31 | float minaccumtime; 32 | uint maxdetphoton; 33 | uint maxmedia; 34 | uint detnum; 35 | uint idx1dorig; 36 | uint mediaidorig; 37 | uint blockphoton; 38 | uint blockextra; 39 | } MCXParam __attribute__ ((aligned (32))); 40 | 41 | float mcx_nextafter1(float a, int dir){ 42 | union{ 43 | float f; 44 | uint i; 45 | } num; 46 | num.f=a+1000.f; 47 | num.i+=dir ^ (num.i & 0x80000000U); 48 | return num.f-1000.f; 49 | } 50 | 51 | float mcx_nextafter2(float a, int dir){ 52 | union{ 53 | float f; 54 | uint i; 55 | } num; 56 | num.f=a; 57 | ((num.i & 0x7FFFFFFFU)==0) ? num.i=((dir & 0x80000000U) | 1) : ((num.i & 0x80000000U) ? (num.i-=dir) : (num.i+=dir) ); 58 | return num.f; 59 | } 60 | 61 | #ifdef USE_HALF 62 | half mcx_nextafter2_half(const half a, short dir){ 63 | union{ 64 | half f; 65 | short i; 66 | } num; 67 | num.f=a; 68 | ((num.i & 0x7FFFU)==0) ? num.i =(((dir & 0x8000U) ) | 1) : ((num.i & 0x8000U) ? (num.i-=dir) : (num.i+=dir) ); 69 | return num.f; 70 | } 71 | #endif 72 | 73 | void test_nextafter(float v){ 74 | printf("input: %e\n",v); 75 | printf("lib v+1.f: %e\tv-1.f: %e\tv+0: %e\n", nextafter(v,v+1.f),nextafter(v,v-1.f),nextafter(v,v+0.f)); 76 | printf("my1 v+1.f: %e\tv-1.f: %e\tv+0: %e\n", mcx_nextafter1(v,1),mcx_nextafter1(v,-1),mcx_nextafter1(v,0)); 77 | printf("my2 v+1.f: %e\tv-1.f: %e\tv+0: %e\n", mcx_nextafter2(v,1),mcx_nextafter2(v,-1),mcx_nextafter2(v,0)); 78 | #ifdef USE_HALF 79 | printf("m2h v+1.f: %e\tv-1.f: %e\tv+0: %e\n", convert_float(mcx_nextafter2_half(convert_half(v),1)), 80 | convert_float(mcx_nextafter2_half(convert_half(v),-1)), 81 | convert_float(mcx_nextafter2_half(convert_half(v),0))); 82 | #endif 83 | } 84 | 85 | 86 | __kernel void mcx_main_loop(const int nphoton, const int ophoton,__global const uint *media, 87 | __global float *field, __global float *genergy, __global uint *n_seed, 88 | __global float *n_det,__constant float4 *gproperty, 89 | __constant float4 *gdetpos, __global uint *stopsign,__global uint *detectedphoton, 90 | __local float *sharedmem, __constant MCXParam *gcfg){ 91 | 92 | int idx= get_global_id(0); 93 | 94 | if(idx==0){ 95 | test_nextafter(15.2f); 96 | test_nextafter(1.f); 97 | test_nextafter(1.2f); 98 | test_nextafter(0.2f); 99 | test_nextafter(0.f); 100 | test_nextafter(-0.f); 101 | test_nextafter(-0.1f); 102 | test_nextafter(-2.2f); 103 | test_nextafter(-100.f); 104 | } 105 | } -------------------------------------------------------------------------------- /src/mcxcl.c: -------------------------------------------------------------------------------- 1 | /***************************************************************************//** 2 | ** \mainpage Monte Carlo eXtreme - GPU accelerated Monte Carlo Photon Migration \ 3 | ** -- OpenCL edition 4 | ** \author Qianqian Fang 5 | ** \copyright Qianqian Fang, 2009-2018 6 | ** 7 | ** \section sref Reference: 8 | ** \li \c (\b Yu2018) Leiming Yu, Fanny Nina-Paravecino, David Kaeli, and Qianqian Fang, 9 | ** "Scalable and massively parallel Monte Carlo photon transport 10 | ** simulations for heterogeneous computing platforms," J. Biomed. Optics, 11 | ** 23(1), 010504 (2018) 12 | ** 13 | ** \section slicense License 14 | ** GPL v3, see LICENSE.txt for details 15 | *******************************************************************************/ 16 | 17 | #include 18 | #include "tictoc.h" 19 | #include "mcx_utils.h" 20 | #include "mcx_host.hpp" 21 | 22 | 23 | int main (int argc, char *argv[]) { 24 | Config mcxconfig; 25 | float *fluence=NULL,totalenergy=0.f; 26 | 27 | mcx_initcfg(&mcxconfig); 28 | 29 | // parse command line options to initialize the configurations 30 | mcx_parsecmd(argc,argv,&mcxconfig); 31 | 32 | mcx_createfluence(&fluence,&mcxconfig); 33 | 34 | // this launches the MC simulation 35 | mcx_run_simulation(&mcxconfig,fluence,&totalenergy); 36 | 37 | // clean up the allocated memory in the config 38 | mcx_clearfluence(&fluence); 39 | mcx_clearcfg(&mcxconfig); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /src/mingw64/include/CL/cl_gl_ext.h: -------------------------------------------------------------------------------- 1 | /********************************************************************************** 2 | * Copyright (c) 2008-2015 The Khronos Group Inc. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and/or associated documentation files (the 6 | * "Materials"), to deal in the Materials without restriction, including 7 | * without limitation the rights to use, copy, modify, merge, publish, 8 | * distribute, sublicense, and/or sell copies of the Materials, and to 9 | * permit persons to whom the Materials are furnished to do so, subject to 10 | * the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included 13 | * in all copies or substantial portions of the Materials. 14 | * 15 | * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS 16 | * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS 17 | * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT 18 | * https://www.khronos.org/registry/ 19 | * 20 | * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 21 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 22 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 23 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 24 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 25 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 26 | * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. 27 | **********************************************************************************/ 28 | 29 | /* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ 30 | 31 | /* cl_gl_ext.h contains vendor (non-KHR) OpenCL extensions which have */ 32 | /* OpenGL dependencies. */ 33 | 34 | #ifndef __OPENCL_CL_GL_EXT_H 35 | #define __OPENCL_CL_GL_EXT_H 36 | 37 | #ifdef __cplusplus 38 | extern "C" { 39 | #endif 40 | 41 | #ifdef __APPLE__ 42 | #include 43 | #else 44 | #include 45 | #endif 46 | 47 | /* 48 | * For each extension, follow this template 49 | * cl_VEN_extname extension */ 50 | /* #define cl_VEN_extname 1 51 | * ... define new types, if any 52 | * ... define new tokens, if any 53 | * ... define new APIs, if any 54 | * 55 | * If you need GLtypes here, mirror them with a cl_GLtype, rather than including a GL header 56 | * This allows us to avoid having to decide whether to include GL headers or GLES here. 57 | */ 58 | 59 | /* 60 | * cl_khr_gl_event extension 61 | * See section 9.9 in the OpenCL 1.1 spec for more information 62 | */ 63 | #define CL_COMMAND_GL_FENCE_SYNC_OBJECT_KHR 0x200D 64 | 65 | extern CL_API_ENTRY cl_event CL_API_CALL 66 | clCreateEventFromGLsyncKHR(cl_context /* context */, 67 | cl_GLsync /* cl_GLsync */, 68 | cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1; 69 | 70 | #ifdef __cplusplus 71 | } 72 | #endif 73 | 74 | #endif /* __OPENCL_CL_GL_EXT_H */ 75 | -------------------------------------------------------------------------------- /src/mingw64/include/CL/opencl.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2008-2015 The Khronos Group Inc. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and/or associated documentation files (the 6 | * "Materials"), to deal in the Materials without restriction, including 7 | * without limitation the rights to use, copy, modify, merge, publish, 8 | * distribute, sublicense, and/or sell copies of the Materials, and to 9 | * permit persons to whom the Materials are furnished to do so, subject to 10 | * the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included 13 | * in all copies or substantial portions of the Materials. 14 | * 15 | * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS 16 | * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS 17 | * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT 18 | * https://www.khronos.org/registry/ 19 | * 20 | * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 21 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 22 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 23 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 24 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 25 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 26 | * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. 27 | ******************************************************************************/ 28 | 29 | /* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ 30 | 31 | #ifndef __OPENCL_H 32 | #define __OPENCL_H 33 | 34 | #ifdef __cplusplus 35 | extern "C" { 36 | #endif 37 | 38 | #ifdef __APPLE__ 39 | 40 | #include 41 | #include 42 | #include 43 | #include 44 | 45 | #else 46 | 47 | #include 48 | #include 49 | #include 50 | #include 51 | 52 | #endif 53 | 54 | #ifdef __cplusplus 55 | } 56 | #endif 57 | 58 | #endif /* __OPENCL_H */ 59 | 60 | -------------------------------------------------------------------------------- /src/mingw64/include/_ansi.h: -------------------------------------------------------------------------------- 1 | /* Provide support for both ANSI and non-ANSI environments. */ 2 | 3 | /* To get a strict ANSI C environment, define macro __STRICT_ANSI__. This will 4 | "comment out" the non-ANSI parts of the ANSI header files (non-ANSI header 5 | files aren't affected). */ 6 | 7 | #ifndef _ANSIDECL_H_ 8 | #define _ANSIDECL_H_ 9 | 10 | #include 11 | #include 12 | 13 | /* ISO C++. */ 14 | 15 | #ifdef __cplusplus 16 | #if !(defined(_BEGIN_STD_C) && defined(_END_STD_C)) 17 | #ifdef _HAVE_STD_CXX 18 | #define _BEGIN_STD_C namespace std { extern "C" { 19 | #define _END_STD_C } } 20 | #else 21 | #define _BEGIN_STD_C extern "C" { 22 | #define _END_STD_C } 23 | #endif 24 | #if __GNUC_PREREQ (3, 3) 25 | #define _NOTHROW __attribute__ ((__nothrow__)) 26 | #else 27 | #define _NOTHROW throw() 28 | #endif 29 | #endif 30 | #else 31 | #define _BEGIN_STD_C 32 | #define _END_STD_C 33 | #define _NOTHROW 34 | #endif 35 | 36 | #ifndef _LONG_DOUBLE 37 | #define _LONG_DOUBLE long double 38 | #endif 39 | 40 | /* Support gcc's __attribute__ facility. */ 41 | 42 | #ifdef __GNUC__ 43 | #define _ATTRIBUTE(attrs) __attribute__ (attrs) 44 | #else 45 | #define _ATTRIBUTE(attrs) 46 | #endif 47 | 48 | /* The traditional meaning of 'extern inline' for GCC is not 49 | to emit the function body unless the address is explicitly 50 | taken. However this behaviour is changing to match the C99 51 | standard, which uses 'extern inline' to indicate that the 52 | function body *must* be emitted. Likewise, a function declared 53 | without either 'extern' or 'static' defaults to extern linkage 54 | (C99 6.2.2p5), and the compiler may choose whether to use the 55 | inline version or call the extern linkage version (6.7.4p6). 56 | If we are using GCC, but do not have the new behaviour, we need 57 | to use extern inline; if we are using a new GCC with the 58 | C99-compatible behaviour, or a non-GCC compiler (which we will 59 | have to hope is C99, since there is no other way to achieve the 60 | effect of omitting the function if it isn't referenced) we use 61 | 'static inline', which c99 defines to mean more-or-less the same 62 | as the Gnu C 'extern inline'. */ 63 | #if defined(__GNUC__) && !defined(__GNUC_STDC_INLINE__) 64 | /* We're using GCC, but without the new C99-compatible behaviour. */ 65 | #define _ELIDABLE_INLINE extern __inline__ _ATTRIBUTE ((__always_inline__)) 66 | #else 67 | /* We're using GCC in C99 mode, or an unknown compiler which 68 | we just have to hope obeys the C99 semantics of inline. */ 69 | #define _ELIDABLE_INLINE static __inline__ 70 | #endif 71 | 72 | #if __GNUC_PREREQ (3, 1) 73 | #define _NOINLINE __attribute__ ((__noinline__)) 74 | #define _NOINLINE_STATIC _NOINLINE static 75 | #else 76 | /* On non-GNU compilers and GCC prior to version 3.1 the compiler can't be 77 | trusted not to inline if it is static. */ 78 | #define _NOINLINE 79 | #define _NOINLINE_STATIC 80 | #endif 81 | 82 | #endif /* _ANSIDECL_H_ */ 83 | -------------------------------------------------------------------------------- /src/mingw64/include/features.h: -------------------------------------------------------------------------------- 1 | /* features.h 2 | 3 | This file is part of Cygwin. 4 | 5 | This software is a copyrighted work licensed under the terms of the 6 | Cygwin license. Please consult the file "CYGWIN_LICENSE" for 7 | details. */ 8 | 9 | #ifndef _FEATURES_H 10 | #define _FEATURES_H 11 | 12 | #include 13 | #include 14 | 15 | /* Various options should be defined here, but the framework to do this 16 | is not laid down so far. Especially notable are the following defines, 17 | which can be used by the application to switch on or off various 18 | datatypes and function prototypes: 19 | 20 | _BSD_SOURCE to include pure BSD functions which are not defined 21 | under POSIX. 22 | 23 | _POSIX_SOURCE if the application requests a POSIX compatible system. 24 | 25 | _XOPEN_SOURCE if X/Open functions and datatypes are requested. This 26 | option includes _POSIX_SOURCE. 27 | 28 | _GNU_SOURCE to turn on GNU extensions which might collide with defines 29 | used in application or library headers. This option 30 | includes _BSD_SOURCE, _XOPEN_SOURCE and _POSIX_SOURCE. 31 | */ 32 | 33 | #endif /* _FEATURES_H */ 34 | -------------------------------------------------------------------------------- /src/mingw64/include/sys/ioctl.h: -------------------------------------------------------------------------------- 1 | /* sys/ioctl.h 2 | 3 | This file is part of Cygwin. 4 | 5 | This software is a copyrighted work licensed under the terms of the 6 | Cygwin license. Please consult the file "CYGWIN_LICENSE" for 7 | details. */ 8 | 9 | /* sys/ioctl.h */ 10 | 11 | #ifndef _SYS_IOCTL_H 12 | #define _SYS_IOCTL_H 13 | 14 | #include 15 | #include 16 | 17 | __BEGIN_DECLS 18 | 19 | /* /dev/windows ioctls */ 20 | 21 | #define WINDOWS_POST 0 /* Set write() behavior to PostMessage() */ 22 | #define WINDOWS_SEND 1 /* Set write() behavior to SendMessage() */ 23 | #define WINDOWS_HWND 2 /* Set hWnd for read() calls */ 24 | 25 | /* Some standard linux defines */ 26 | 27 | #define _IOC_NRBITS 8 28 | #define _IOC_TYPEBITS 8 29 | #define _IOC_SIZEBITS 14 30 | #define _IOC_DIRBITS 2 31 | 32 | #define _IOC_NRMASK ((1 << _IOC_NRBITS)-1) 33 | #define _IOC_TYPEMASK ((1 << _IOC_TYPEBITS)-1) 34 | #define _IOC_SIZEMASK ((1 << _IOC_SIZEBITS)-1) 35 | #define _IOC_DIRMASK ((1 << _IOC_DIRBITS)-1) 36 | 37 | #define _IOC_NRSHIFT 0 38 | #define _IOC_TYPESHIFT (_IOC_NRSHIFT+_IOC_NRBITS) 39 | #define _IOC_SIZESHIFT (_IOC_TYPESHIFT+_IOC_TYPEBITS) 40 | #define _IOC_DIRSHIFT (_IOC_SIZESHIFT+_IOC_SIZEBITS) 41 | 42 | #define _IOC_NONE 0U 43 | #define _IOC_WRITE 1U 44 | #define _IOC_READ 2U 45 | 46 | #define _IOC(dir,type,nr,size) \ 47 | (((dir) << _IOC_DIRSHIFT) | \ 48 | + ((type) << _IOC_TYPESHIFT) | \ 49 | + ((nr) << _IOC_NRSHIFT) | \ 50 | + ((size) << _IOC_SIZESHIFT)) 51 | 52 | #define _LINUX_IO(type,nr) _IOC(_IOC_NONE,(type),(nr),0) 53 | #define _LINUX_IOR(type,nr,size) _IOC(_IOC_READ,(type),(nr),sizeof(size)) 54 | #define _LINUX_IOW(type,nr,size) _IOC(_IOC_WRITE,(type),(nr),sizeof(size)) 55 | #define _LINUX_IOWR(type,nr,size) _IOC(_IOC_READ|_IOC_WRITE,(type),(nr),sizeof(size)) 56 | 57 | #ifdef __USE_LINUX_IOCTL_DEFS 58 | # define _IO _LINUX_IO 59 | # define _IOR _LINUX_IOR 60 | # define _IOW _LINUX_IOW 61 | # define _IOWR _LINUX_IOWR 62 | #endif /*__USE_LINUX_IOCTL_DEFS */ 63 | 64 | int __cdecl ioctl (int __fd, int __cmd, ...); 65 | 66 | __END_DECLS 67 | #endif 68 | -------------------------------------------------------------------------------- /src/tictoc.h: -------------------------------------------------------------------------------- 1 | #ifndef GETTIMEOFDAY_H 2 | #define GETTIMEOFDAY_H 3 | 4 | #ifdef __cplusplus 5 | extern "C" { 6 | #endif 7 | 8 | unsigned int StartTimer (); 9 | unsigned int GetTimeMillis (); 10 | void sleep_ms(int milliseconds); 11 | 12 | #ifdef __cplusplus 13 | } 14 | #endif 15 | 16 | #endif /* GETTIMEOFDAY_H */ 17 | 18 | -------------------------------------------------------------------------------- /src/ubj/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Steven Braeger 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /src/ubj/README.md: -------------------------------------------------------------------------------- 1 | ubj 2 | === 3 | 4 | UBJSON C/C++ libraries 5 | 6 | This library implements the current draft (draft 12) of the UBJSON specification in ANSI C. 7 | 8 | There are three components, each of which may be compiled and used seperately from each-other. 9 | 10 | The reader component (ubjr.c) the writer component (ubjw.c) and the transcoder (ubjrw.c). 11 | 12 | The API is defined in ubj.h 13 | -------------------------------------------------------------------------------- /src/vector_types.h: -------------------------------------------------------------------------------- 1 | /***************************************************************************//** 2 | \file vector_types.h 3 | 4 | \brief Definitions of the basic short vector data structures 5 | *******************************************************************************/ 6 | 7 | #ifndef _MMC_VECTOR_H 8 | #define _MMC_VECTOR_H 9 | 10 | #ifdef _MSC_VER 11 | #define PRE_ALIGN(x) __declspec(align(x)) 12 | #define POST_ALIGN(x) 13 | #else 14 | #define PRE_ALIGN(x) 15 | #define POST_ALIGN(x) __attribute__ ((aligned(x))) 16 | #endif 17 | 18 | /** 19 | \struct MMC_float4 vector_types.h 20 | \brief floating-point quadraplet {x,y,z,w} 21 | 22 | the data structure is 16byte aligned to facilitate SSE operations 23 | */ 24 | 25 | typedef struct PRE_ALIGN(16) MMC_float4{ 26 | float x,y,z,w; 27 | } float4 POST_ALIGN(16); 28 | 29 | /** 30 | \struct MMC_float3 vector_types.h 31 | \brief floating-point triplet {x,y,z} 32 | 33 | if SSE is enabled, float3 is identical to float4 34 | */ 35 | 36 | #if defined(MMC_USE_SSE) || defined(USE_OPENCL) 37 | typedef struct MMC_float4 float3; 38 | #else 39 | typedef struct MMC_float3{ 40 | float x,y,z; 41 | } float3; 42 | #endif 43 | 44 | /** 45 | \struct MMC_int2 vector_types.h 46 | \brief integer pair {ix,iy} 47 | */ 48 | 49 | typedef struct MMC_int2{ 50 | int x,y; 51 | } int2; 52 | 53 | /** 54 | \struct MMC_int3 vector_types.h 55 | \brief integer triplet {ix,iy,iz} 56 | */ 57 | 58 | typedef struct MMC_int3{ 59 | int x,y,z; 60 | } int3; 61 | 62 | /** 63 | \struct MMC_int4 vector_types.h 64 | \brief unsigned integer quadraplet {ix,iy,iz,iw} 65 | */ 66 | typedef struct PRE_ALIGN(16) MMC_int4{ 67 | int x,y,z,w; 68 | } int4 POST_ALIGN(16); 69 | 70 | /** 71 | \struct MMC_uint3 vector_types.h 72 | \brief unsigned integer triplet {ix,iy,iz} 73 | */ 74 | typedef struct MMC_uint3{ 75 | unsigned int x,y,z; 76 | } uint3; 77 | 78 | /** 79 | \struct MMC_uint3 vector_types.h 80 | \brief unsigned integer triplet {ix,iy,iz} 81 | */ 82 | typedef struct PRE_ALIGN(16) MMC_uint4{ 83 | unsigned int x,y,z,w; 84 | } uint4 POST_ALIGN(16); 85 | 86 | /** 87 | \struct MMC_uint2 vector_types.h 88 | \brief unsigned integer pair {ix,iy} 89 | */ 90 | 91 | typedef struct MMC_uint2{ 92 | unsigned int x,y; 93 | } uint2; 94 | 95 | 96 | typedef unsigned int uint; 97 | 98 | #endif 99 | -------------------------------------------------------------------------------- /src/zmat/Makefile: -------------------------------------------------------------------------------- 1 | ################################################################# 2 | # Makefile for ZMAT 3 | # Qianqian Fang 4 | # 2019/04/30 5 | ################################################################# 6 | 7 | BACKEND ?= 8 | 9 | ROOTDIR ?= .. 10 | ZMATDIR ?= $(ROOTDIR) 11 | MCXSRC :=$(ZMATDIR)/src 12 | 13 | MKDIR := mkdir 14 | 15 | MEX=mex 16 | AR=$(CC) 17 | ECHO := echo 18 | 19 | BINARY:=zipmat 20 | OUTPUT_DIR=$(ZMATDIR) 21 | 22 | DOXY := doxygen 23 | DOCDIR := $(ZMATDIR)/doc 24 | DOXYCFG=zmat.cfg 25 | 26 | INCLUDEDIRS=-Ieasylzma -Ieasylzma/pavlov -Ilz4 27 | 28 | CUOMPLINK= 29 | 30 | ARCH = $(shell uname -m) 31 | PLATFORM = $(shell uname -s) 32 | 33 | DLLFLAG=-fPIC 34 | OMP=-fopenmp 35 | 36 | CPPOPT=-g -Wall -O3 37 | CCFLAGS=$(CPPOPT) 38 | 39 | OUTPUTFLAG:=-o 40 | OBJSUFFIX=.o 41 | EXESUFFIX= 42 | 43 | FILES=zmatlib lz4/lz4 lz4/lz4hc easylzma/compress easylzma/decompress \ 44 | easylzma/lzma_header easylzma/lzip_header easylzma/common_internal \ 45 | easylzma/pavlov/LzmaEnc easylzma/pavlov/LzmaDec easylzma/pavlov/LzmaLib \ 46 | easylzma/pavlov/LzFind easylzma/pavlov/Bra easylzma/pavlov/BraIA64 \ 47 | easylzma/pavlov/Alloc easylzma/pavlov/7zCrc 48 | 49 | ifeq ($(findstring CYGWIN,$(PLATFORM)), CYGWIN) 50 | #CUOMPLINK=-Xcompiler 51 | ifeq ($(findstring x86_64,$(ARCH)), x86_64) 52 | LINKOPT=-L"$(CUDA_PATH)/lib/x64" $(CUDART) 53 | else 54 | LINKOPT=-L"$(CUDA_PATH)/lib/Win32" $(CUDART) 55 | endif 56 | INCLUDEDIRS +=-I"$(CUDA_PATH)/lib/include" 57 | CPPOPT =-c -DWIN32 -g -Wall -O3 -fPIC 58 | OBJSUFFIX=.obj 59 | EXESUFFIX= 60 | DLLFLAG= 61 | OMP=-fopenmp 62 | MEX=cmd /c mex 63 | #CPPOPT+=-Xcompiler $(OMP) 64 | else ifeq ($(findstring Darwin,$(PLATFORM)), Darwin) 65 | OUTPUTFLAG= 66 | CPPOPT+= 67 | else 68 | CPPOPT+= 69 | CUCCOPT+=-Xcompiler $(OMP) 70 | ifeq ($(findstring x86_64,$(ARCH)), x86_64) 71 | CPPOPT += 72 | CUCCOPT +=-m64 73 | ifeq "$(wildcard /usr/local/cuda/lib64)" "/usr/local/cuda/lib64" 74 | ifeq ($(BACKEND),cuda) 75 | LINKOPT=-L/usr/local/cuda/lib64 $(CUDART) -lm -lstdc++ 76 | else ifeq ($(BACKEND),cudastatic) 77 | LINKOPT=-L/usr/local/cuda/lib64 $(CUDART) -lm -static-libgcc -static-libstdc++ 78 | endif 79 | endif 80 | endif 81 | endif 82 | 83 | ifeq ($(MAKECMDGOALS),lib) 84 | AR :=ar 85 | ARFLAGS :=cr 86 | BINARY :=libzmat.a 87 | AROUTPUT := 88 | LINKOPT :=#easylzma/src/CMakeFiles/easylzma_s.dir/*.o easylzma/src/CMakeFiles/easylzma_s.dir/pavlov/*.o 89 | endif 90 | 91 | dll: CPPOPT +=$(DLLFLAG) 92 | dll: AR :=gcc 93 | dll: ARFLAGS :=-shared -Wl,-soname,$(BINARY).1 94 | dll: LINKOPT :=easylzma/src/CMakeFiles/easylzma.dir/*.o easylzma/src/CMakeFiles/easylzma.dir/pavlov/*.o 95 | dll: AROUTPUT :=-o 96 | 97 | oct mex: CPPOPT+= $(DLLFLAG) 98 | oct: OUTPUT_DIR=.. 99 | oct: AR= CXXFLAGS='-O3' LFLAGS='$(-lz)' LDFLAGS='$(LFLAGS)' mkoctfile zmat.cpp 100 | oct: BINARY=zmat.mex 101 | oct: ARFLAGS := 102 | oct: LINKOPT+=--mex $(INCLUDEDIRS) 103 | oct: CXX=mkoctfile 104 | 105 | mex: CXX=$(MEX) 106 | mex: OUTPUTFLAG:=-output 107 | mex: AR=$(MEX) zmat.cpp $(INCLUDEDIRS) 108 | mex: LINKOPT+= -cxx CXXLIBS='$$CXXLIBS -lz' -outdir $(ZMATDIR) 109 | mex: ARFLAGS := 110 | mex: OUTPUT_DIR=.. 111 | 112 | all: mex 113 | 114 | TARGETSUFFIX:=$(suffix $(BINARY)) 115 | 116 | ifeq ($(TARGETSUFFIX),.so) 117 | CCFLAGS+= $(DLLFLAG) 118 | ARFLAGS+= -shared -Wl,-soname,$(BINARY).1 119 | endif 120 | 121 | doc: makedocdir 122 | $(DOXY) $(DOXYCFG) 123 | 124 | OBJS := $(addsuffix $(OBJSUFFIX), $(FILES)) 125 | 126 | all dll lib mex oct: $(OUTPUT_DIR)/$(BINARY) 127 | 128 | makedirs: 129 | @if test ! -d $(OUTPUT_DIR); then $(MKDIR) $(OUTPUT_DIR); fi 130 | 131 | makedocdir: 132 | @if test ! -d $(DOCDIR); then $(MKDIR) $(DOCDIR); fi 133 | 134 | $(OUTPUT_DIR)/$(BINARY): makedirs $(OBJS) 135 | $(OUTPUT_DIR)/$(BINARY): $(OBJS) 136 | @$(ECHO) Building $@ 137 | $(AR) $(ARFLAGS) $(OUTPUTFLAG) $@ $(OBJS) $(LINKOPT) $(USERLINKOPT) 138 | 139 | %$(OBJSUFFIX): %.cpp 140 | $(CXX) $(INCLUDEDIRS) $(CPPOPT) -c -o $@ $< 141 | 142 | %$(OBJSUFFIX): %.c 143 | @$(ECHO) Building $@ 144 | $(CC) $(INCLUDEDIRS) $(CPPOPT) -c -o $@ $< 145 | 146 | %$(OBJSUFFIX): %.cu 147 | @$(ECHO) Building $@ 148 | $(CUDACC) -c $(CUCCOPT) -o $@ $< 149 | 150 | clean: 151 | -rm -f $(OBJS) $(OUTPUT_DIR)/$(BINARY)$(EXESUFFIX) 152 | 153 | .PHONY: all mex oct lib 154 | 155 | .DEFAULT_GOAL := all 156 | 157 | -------------------------------------------------------------------------------- /src/zmat/easylzma/README: -------------------------------------------------------------------------------- 1 | pavlov/ - contains original lzma compress/decompress source from Igor Pavlov 2 | easylzma/ - contains the public api of this library 3 | ./ - contains the implementation of this wrapper library 4 | -------------------------------------------------------------------------------- /src/zmat/easylzma/common_internal.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Written in 2009 by Lloyd Hilaiel 3 | * 4 | * License 5 | * 6 | * All the cruft you find here is public domain. You don't have to credit 7 | * anyone to use this code, but my personal request is that you mention 8 | * Igor Pavlov for his hard, high quality work. 9 | */ 10 | 11 | #include "common_internal.h" 12 | 13 | static void *elzmaAlloc(void *p, size_t size) { 14 | struct elzma_alloc_struct * as = (struct elzma_alloc_struct *) p; 15 | if (as->clientMallocFunc) { 16 | return as->clientMallocFunc(as->clientMallocContext, size); 17 | } 18 | return malloc(size); 19 | } 20 | 21 | static void elzmaFree(void *p, void *address) { 22 | struct elzma_alloc_struct * as = (struct elzma_alloc_struct *) p; 23 | if (as->clientFreeFunc) { 24 | as->clientFreeFunc(as->clientMallocContext, address); 25 | } else { 26 | free(address); 27 | } 28 | } 29 | 30 | void 31 | init_alloc_struct(struct elzma_alloc_struct * as, 32 | elzma_malloc clientMallocFunc, 33 | void * clientMallocContext, 34 | elzma_free clientFreeFunc, 35 | void * clientFreeContext) 36 | { 37 | as->Alloc = elzmaAlloc; 38 | as->Free = elzmaFree; 39 | as->clientMallocFunc = clientMallocFunc; 40 | as->clientMallocContext = clientMallocContext; 41 | as->clientFreeFunc = clientFreeFunc; 42 | as->clientFreeContext = clientFreeContext; 43 | } 44 | -------------------------------------------------------------------------------- /src/zmat/easylzma/common_internal.h: -------------------------------------------------------------------------------- 1 | #ifndef __ELZMA_COMMON_INTERNAL_H__ 2 | #define __ELZMA_COMMON_INTERNAL_H__ 3 | 4 | #include "easylzma/common.h" 5 | 6 | /** a structure which may be cast and passed into Igor's allocate 7 | * routines */ 8 | struct elzma_alloc_struct { 9 | void *(*Alloc)(void *p, size_t size); 10 | void (*Free)(void *p, void *address); /* address can be 0 */ 11 | 12 | elzma_malloc clientMallocFunc; 13 | void * clientMallocContext; 14 | 15 | elzma_free clientFreeFunc; 16 | void * clientFreeContext; 17 | }; 18 | 19 | /* initialize an allocation structure, may be called safely multiple 20 | * times */ 21 | void init_alloc_struct(struct elzma_alloc_struct * allocStruct, 22 | elzma_malloc clientMallocFunc, 23 | void * clientMallocContext, 24 | elzma_free clientFreeFunc, 25 | void * clientFreeContext); 26 | 27 | /** superset representation of a compressed file header */ 28 | struct elzma_file_header { 29 | unsigned char pb; 30 | unsigned char lp; 31 | unsigned char lc; 32 | unsigned char isStreamed; 33 | long long unsigned int uncompressedSize; 34 | unsigned int dictSize; 35 | }; 36 | 37 | /** superset representation of a compressed file footer */ 38 | struct elzma_file_footer { 39 | unsigned int crc32; 40 | long long unsigned int uncompressedSize; 41 | }; 42 | 43 | /** a structure which encapsulates information about the particular 44 | * file header and footer in use (lzip vs lzma vs (eventually) xz. 45 | * The intention of this structure is to simplify compression and 46 | * decompression logic by abstracting the file format details a bit. */ 47 | struct elzma_format_handler 48 | { 49 | unsigned int header_size; 50 | void (*init_header)(struct elzma_file_header * hdr); 51 | int (*parse_header)(const unsigned char * hdrBuf, 52 | struct elzma_file_header * hdr); 53 | int (*serialize_header)(unsigned char * hdrBuf, 54 | const struct elzma_file_header * hdr); 55 | 56 | unsigned int footer_size; 57 | int (*serialize_footer)(struct elzma_file_footer * ftr, 58 | unsigned char * ftrBuf); 59 | int (*parse_footer)(const unsigned char * ftrBuf, 60 | struct elzma_file_footer * ftr); 61 | }; 62 | 63 | #endif 64 | -------------------------------------------------------------------------------- /src/zmat/easylzma/easylzma/compress.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Written in 2009 by Lloyd Hilaiel 3 | * 4 | * License 5 | * 6 | * All the cruft you find here is public domain. You don't have to credit 7 | * anyone to use this code, but my personal request is that you mention 8 | * Igor Pavlov for his hard, high quality work. 9 | * 10 | * easylzma/compress.h - the API for LZMA compression using easylzma 11 | */ 12 | 13 | #ifndef __EASYLZMACOMPRESS_H__ 14 | #define __EASYLZMACOMPRESS_H__ 15 | 16 | #include "easylzma/common.h" 17 | #include 18 | 19 | #ifdef __cplusplus 20 | extern "C" { 21 | #endif 22 | 23 | /** suggested default values */ 24 | #define ELZMA_LC_DEFAULT 3 25 | #define ELZMA_LP_DEFAULT 0 26 | #define ELZMA_PB_DEFAULT 2 27 | #define ELZMA_DICT_SIZE_DEFAULT_MAX (1 << 24) 28 | 29 | /** an opaque handle to an lzma compressor */ 30 | typedef struct _elzma_compress_handle * elzma_compress_handle; 31 | 32 | /** 33 | * Allocate a handle to an LZMA compressor object. 34 | */ 35 | elzma_compress_handle EASYLZMA_API elzma_compress_alloc(); 36 | 37 | /** 38 | * set allocation routines (optional, if not called malloc & free will 39 | * be used) 40 | */ 41 | void EASYLZMA_API elzma_compress_set_allocation_callbacks( 42 | elzma_compress_handle hand, 43 | elzma_malloc mallocFunc, void * mallocFuncContext, 44 | elzma_free freeFunc, void * freeFuncContext); 45 | 46 | /** 47 | * Free all data associated with an LZMA compressor object. 48 | */ 49 | void EASYLZMA_API elzma_compress_free(elzma_compress_handle * hand); 50 | 51 | /** 52 | * Set configuration paramters for a compression run. If not called, 53 | * reasonable defaults will be used. 54 | */ 55 | int EASYLZMA_API elzma_compress_config(elzma_compress_handle hand, 56 | unsigned char lc, 57 | unsigned char lp, 58 | unsigned char pb, 59 | unsigned char level, 60 | unsigned int dictionarySize, 61 | elzma_file_format format, 62 | unsigned long long uncompressedSize); 63 | 64 | /** 65 | * Run compression 66 | */ 67 | int EASYLZMA_API elzma_compress_run( 68 | elzma_compress_handle hand, 69 | elzma_read_callback inputStream, void * inputContext, 70 | elzma_write_callback outputStream, void * outputContext, 71 | elzma_progress_callback progressCallback, void * progressContext); 72 | 73 | 74 | /** 75 | * a heuristic utility routine to guess a dictionary size that gets near 76 | * optimal compression while reducing memory usage. 77 | * accepts a size in bytes, returns a proposed dictionary size 78 | */ 79 | unsigned int EASYLZMA_API elzma_get_dict_size(unsigned long long size); 80 | 81 | #ifdef __cplusplus 82 | }; 83 | #endif 84 | 85 | #endif 86 | -------------------------------------------------------------------------------- /src/zmat/easylzma/easylzma/decompress.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Written in 2009 by Lloyd Hilaiel 3 | * 4 | * License 5 | * 6 | * All the cruft you find here is public domain. You don't have to credit 7 | * anyone to use this code, but my personal request is that you mention 8 | * Igor Pavlov for his hard, high quality work. 9 | * 10 | * easylzma/decompress.h - The API for LZMA decompression using easylzma 11 | */ 12 | 13 | #ifndef __EASYLZMADECOMPRESS_H__ 14 | #define __EASYLZMADECOMPRESS_H__ 15 | 16 | #include "easylzma/common.h" 17 | 18 | #ifdef __cplusplus 19 | extern "C" { 20 | #endif 21 | 22 | /** an opaque handle to an lzma decompressor */ 23 | typedef struct _elzma_decompress_handle * elzma_decompress_handle; 24 | 25 | /** 26 | * Allocate a handle to an LZMA decompressor object. 27 | */ 28 | elzma_decompress_handle EASYLZMA_API elzma_decompress_alloc(); 29 | 30 | /** 31 | * set allocation routines (optional, if not called malloc & free will 32 | * be used) 33 | */ 34 | void EASYLZMA_API elzma_decompress_set_allocation_callbacks( 35 | elzma_decompress_handle hand, 36 | elzma_malloc mallocFunc, void * mallocFuncContext, 37 | elzma_free freeFunc, void * freeFuncContext); 38 | 39 | /** 40 | * Free all data associated with an LZMA decompressor object. 41 | */ 42 | void EASYLZMA_API elzma_decompress_free(elzma_decompress_handle * hand); 43 | 44 | /** 45 | * Perform decompression 46 | * 47 | * XXX: should the library automatically detect format by reading stream? 48 | * currently it's based on data external to stream (such as extension 49 | * or convention) 50 | */ 51 | int EASYLZMA_API elzma_decompress_run( 52 | elzma_decompress_handle hand, 53 | elzma_read_callback inputStream, void * inputContext, 54 | elzma_write_callback outputStream, void * outputContext, 55 | elzma_file_format format); 56 | 57 | 58 | #ifdef __cplusplus 59 | }; 60 | #endif 61 | 62 | #endif 63 | -------------------------------------------------------------------------------- /src/zmat/easylzma/lzip_header.c: -------------------------------------------------------------------------------- 1 | #include "lzip_header.h" 2 | 3 | #include 4 | 5 | #define ELZMA_LZIP_HEADER_SIZE 6 6 | #define ELZMA_LZIP_FOOTER_SIZE 12 7 | 8 | static 9 | void initLzipHeader(struct elzma_file_header * hdr) 10 | { 11 | memset((void *) hdr, 0, sizeof(struct elzma_file_header)); 12 | } 13 | 14 | static 15 | int parseLzipHeader(const unsigned char * hdrBuf, 16 | struct elzma_file_header * hdr) 17 | { 18 | if (0 != strncmp("LZIP", (char *) hdrBuf, 4)) return 1; 19 | /* XXX: ignore version for now */ 20 | hdr->pb = 2; 21 | hdr->lp = 0; 22 | hdr->lc = 3; 23 | /* unknown at this point */ 24 | hdr->isStreamed = 1; 25 | hdr->uncompressedSize = 0; 26 | hdr->dictSize = 1 << (hdrBuf[5] & 0x1F); 27 | return 0; 28 | } 29 | 30 | static int 31 | serializeLzipHeader(unsigned char * hdrBuf, 32 | const struct elzma_file_header * hdr) 33 | { 34 | hdrBuf[0] = 'L'; 35 | hdrBuf[1] = 'Z'; 36 | hdrBuf[2] = 'I'; 37 | hdrBuf[3] = 'P'; 38 | hdrBuf[4] = 0; 39 | { 40 | int r = 0; 41 | while ((hdr->dictSize >> r) != 0) r++; 42 | hdrBuf[5] = (unsigned char) (r-1) & 0x1F; 43 | } 44 | return 0; 45 | } 46 | 47 | static int 48 | serializeLzipFooter(struct elzma_file_footer * ftr, 49 | unsigned char * ftrBuf) 50 | { 51 | unsigned int i = 0; 52 | 53 | /* first crc32 */ 54 | for (i = 0; i < 4; i++) { 55 | *(ftrBuf++) = (unsigned char) (ftr->crc32 >> (i * 8)); 56 | } 57 | 58 | /* next data size */ 59 | for (i = 0; i < 8; i++) { 60 | *(ftrBuf++) = (unsigned char) (ftr->uncompressedSize >> (i * 8)); 61 | } 62 | 63 | /* write version 0 files, omit member length for now*/ 64 | 65 | return 0; 66 | } 67 | 68 | static int 69 | parseLzipFooter(const unsigned char * ftrBuf, 70 | struct elzma_file_footer * ftr) 71 | { 72 | unsigned int i = 0; 73 | ftr->crc32 = 0; 74 | ftr->uncompressedSize = 0; 75 | 76 | /* first crc32 */ 77 | for (i = 0; i < 4; i++) 78 | { 79 | ftr->crc32 += ((unsigned int) *(ftrBuf++) << (i * 8)); 80 | } 81 | 82 | /* next data size */ 83 | for (i = 0; i < 8; i++) { 84 | ftr->uncompressedSize += 85 | (unsigned long long) *(ftrBuf++) << (i * 8); 86 | } 87 | /* read version 0 files, omit member length for now*/ 88 | 89 | return 0; 90 | } 91 | 92 | void 93 | initializeLZIPFormatHandler(struct elzma_format_handler * hand) 94 | { 95 | hand->header_size = ELZMA_LZIP_HEADER_SIZE; 96 | hand->init_header = initLzipHeader; 97 | hand->parse_header = parseLzipHeader; 98 | hand->serialize_header = serializeLzipHeader; 99 | hand->footer_size = ELZMA_LZIP_FOOTER_SIZE; 100 | hand->serialize_footer = serializeLzipFooter; 101 | hand->parse_footer = parseLzipFooter; 102 | } 103 | 104 | -------------------------------------------------------------------------------- /src/zmat/easylzma/lzip_header.h: -------------------------------------------------------------------------------- 1 | #ifndef __EASYLZMA_LZIP_HEADER__ 2 | #define __EASYLZMA_LZIP_HEADER__ 3 | 4 | #include "common_internal.h" 5 | 6 | /* lzip file format documented here: 7 | * http://download.savannah.gnu.org/releases-noredirect/lzip/manual/ */ 8 | 9 | void initializeLZIPFormatHandler(struct elzma_format_handler * hand); 10 | 11 | #endif 12 | -------------------------------------------------------------------------------- /src/zmat/easylzma/lzma_header.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Written in 2009 by Lloyd Hilaiel 3 | * 4 | * License 5 | * 6 | * All the cruft you find here is public domain. You don't have to credit 7 | * anyone to use this code, but my personal request is that you mention 8 | * Igor Pavlov for his hard, high quality work. 9 | */ 10 | 11 | /* XXX: clean this up, it's mostly lifted from pavel */ 12 | 13 | #include "lzma_header.h" 14 | 15 | #include 16 | #include 17 | 18 | #define ELZMA_LZMA_HEADER_SIZE 13 19 | #define ELZMA_LZMA_PROPSBUF_SIZE 5 20 | 21 | /**************** 22 | Header parsing 23 | ****************/ 24 | 25 | #ifndef UINT64_MAX 26 | #define UINT64_MAX ((unsigned long long) -1) 27 | #endif 28 | 29 | /* Parse the properties byte */ 30 | static char 31 | lzmadec_header_properties ( 32 | unsigned char *pb, unsigned char *lp, unsigned char *lc, const unsigned char c) 33 | { 34 | /* pb, lp and lc are encoded into a single byte. */ 35 | if (c > (9 * 5 * 5)) 36 | return -1; 37 | *pb = c / (9 * 5); /* 0 <= pb <= 4 */ 38 | *lp = (c % (9 * 5)) / 9; /* 0 <= lp <= 4 */ 39 | *lc = c % 9; /* 0 <= lc <= 8 */ 40 | 41 | assert (*pb < 5 && *lp < 5 && *lc < 9); 42 | return 0; 43 | } 44 | 45 | /* Parse the dictionary size (4 bytes, little endian) */ 46 | static char 47 | lzmadec_header_dictionary (unsigned int *size, const unsigned char *buffer) 48 | { 49 | unsigned int i; 50 | *size = 0; 51 | for (i = 0; i < 4; i++) 52 | *size += (unsigned int)(*buffer++) << (i * 8); 53 | /* The dictionary size is limited to 256 MiB (checked from 54 | * LZMA SDK 4.30) */ 55 | if (*size > (1 << 28)) 56 | return -1; 57 | return 0; 58 | } 59 | 60 | /* Parse the uncompressed size field (8 bytes, little endian) */ 61 | static void 62 | lzmadec_header_uncompressed (unsigned long long *size, 63 | unsigned char *is_streamed, 64 | const unsigned char *buffer) 65 | { 66 | unsigned int i; 67 | 68 | /* Streamed files have all 64 bits set in the size field. 69 | * We don't know the uncompressed size beforehand. */ 70 | *is_streamed = 1; /* Assume streamed. */ 71 | *size = 0; 72 | for (i = 0; i < 8; i++) { 73 | *size += (unsigned long long)buffer[i] << (i * 8); 74 | if (buffer[i] != 255) 75 | *is_streamed = 0; 76 | } 77 | assert ((*is_streamed == 1 && *size == UINT64_MAX) 78 | || (*is_streamed == 0 && *size < UINT64_MAX)); 79 | } 80 | 81 | static void 82 | initLzmaHeader(struct elzma_file_header * hdr) 83 | { 84 | memset((void *) hdr, 0, sizeof(struct elzma_file_header)); 85 | } 86 | 87 | static int 88 | parseLzmaHeader(const unsigned char * hdrBuf, 89 | struct elzma_file_header * hdr) 90 | { 91 | if (lzmadec_header_properties(&(hdr->pb), &(hdr->lp), &(hdr->lc), 92 | *hdrBuf) || 93 | lzmadec_header_dictionary(&(hdr->dictSize), hdrBuf + 1)) 94 | { 95 | return 1; 96 | } 97 | lzmadec_header_uncompressed(&(hdr->uncompressedSize), 98 | &(hdr->isStreamed), 99 | hdrBuf + 5); 100 | 101 | return 0; 102 | } 103 | 104 | static int 105 | serializeLzmaHeader(unsigned char * hdrBuf, 106 | const struct elzma_file_header * hdr) 107 | { 108 | unsigned int i; 109 | 110 | memset((void *) hdrBuf, 0, ELZMA_LZMA_HEADER_SIZE); 111 | 112 | /* encode lc, pb, and lp */ 113 | *hdrBuf++ = hdr->lc + (hdr->pb * 45) + (hdr->lp * 45 * 9); 114 | 115 | /* encode dictionary size */ 116 | for (i = 0; i < 4; i++) { 117 | *(hdrBuf++) = (unsigned char) (hdr->dictSize >> (i * 8)); 118 | } 119 | 120 | /* encode uncompressed size */ 121 | for (i = 0; i < 8; i++) { 122 | if (hdr->isStreamed) { 123 | *(hdrBuf++) = 0xff; 124 | } else { 125 | *(hdrBuf++) = (unsigned char) (hdr->uncompressedSize >> (i * 8)); 126 | } 127 | } 128 | 129 | return 0; 130 | } 131 | 132 | void 133 | initializeLZMAFormatHandler(struct elzma_format_handler * hand) 134 | { 135 | hand->header_size = ELZMA_LZMA_HEADER_SIZE; 136 | hand->init_header = initLzmaHeader; 137 | hand->parse_header = parseLzmaHeader; 138 | hand->serialize_header = serializeLzmaHeader; 139 | hand->footer_size = 0; 140 | hand->serialize_footer = NULL; 141 | } 142 | -------------------------------------------------------------------------------- /src/zmat/easylzma/lzma_header.h: -------------------------------------------------------------------------------- 1 | #ifndef __EASYLZMA_LZMA_HEADER__ 2 | #define __EASYLZMA_LZMA_HEADER__ 3 | 4 | #include "common_internal.h" 5 | 6 | /* LZMA-Alone header format gleaned from reading Igor's code */ 7 | 8 | void initializeLZMAFormatHandler(struct elzma_format_handler * hand); 9 | 10 | #endif 11 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/7zBuf.c: -------------------------------------------------------------------------------- 1 | /* 7zBuf.c -- Byte Buffer 2 | 2008-03-28 3 | Igor Pavlov 4 | Public domain */ 5 | 6 | #include "7zBuf.h" 7 | 8 | void Buf_Init(CBuf *p) 9 | { 10 | p->data = 0; 11 | p->size = 0; 12 | } 13 | 14 | int Buf_Create(CBuf *p, size_t size, ISzAlloc *alloc) 15 | { 16 | p->size = 0; 17 | if (size == 0) 18 | { 19 | p->data = 0; 20 | return 1; 21 | } 22 | p->data = (Byte *)alloc->Alloc(alloc, size); 23 | if (p->data != 0) 24 | { 25 | p->size = size; 26 | return 1; 27 | } 28 | return 0; 29 | } 30 | 31 | void Buf_Free(CBuf *p, ISzAlloc *alloc) 32 | { 33 | alloc->Free(alloc, p->data); 34 | p->data = 0; 35 | p->size = 0; 36 | } 37 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/7zBuf.h: -------------------------------------------------------------------------------- 1 | /* 7zBuf.h -- Byte Buffer 2 | 2008-10-04 : Igor Pavlov : Public domain */ 3 | 4 | #ifndef __7Z_BUF_H 5 | #define __7Z_BUF_H 6 | 7 | #include "Types.h" 8 | 9 | typedef struct 10 | { 11 | Byte *data; 12 | size_t size; 13 | } CBuf; 14 | 15 | void Buf_Init(CBuf *p); 16 | int Buf_Create(CBuf *p, size_t size, ISzAlloc *alloc); 17 | void Buf_Free(CBuf *p, ISzAlloc *alloc); 18 | 19 | typedef struct 20 | { 21 | Byte *data; 22 | size_t size; 23 | size_t pos; 24 | } CDynBuf; 25 | 26 | void DynBuf_Construct(CDynBuf *p); 27 | void DynBuf_SeekToBeg(CDynBuf *p); 28 | int DynBuf_Write(CDynBuf *p, const Byte *buf, size_t size, ISzAlloc *alloc); 29 | void DynBuf_Free(CDynBuf *p, ISzAlloc *alloc); 30 | 31 | #endif 32 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/7zBuf2.c: -------------------------------------------------------------------------------- 1 | /* 7zBuf2.c -- Byte Buffer 2 | 2008-10-04 : Igor Pavlov : Public domain */ 3 | 4 | #include 5 | #include "7zBuf.h" 6 | 7 | void DynBuf_Construct(CDynBuf *p) 8 | { 9 | p->data = 0; 10 | p->size = 0; 11 | p->pos = 0; 12 | } 13 | 14 | void DynBuf_SeekToBeg(CDynBuf *p) 15 | { 16 | p->pos = 0; 17 | } 18 | 19 | int DynBuf_Write(CDynBuf *p, const Byte *buf, size_t size, ISzAlloc *alloc) 20 | { 21 | if (size > p->size - p->pos) 22 | { 23 | size_t newSize = p->pos + size; 24 | Byte *data; 25 | newSize += newSize / 4; 26 | data = (Byte *)alloc->Alloc(alloc, newSize); 27 | if (data == 0) 28 | return 0; 29 | p->size = newSize; 30 | memcpy(data, p->data, p->pos); 31 | alloc->Free(alloc, p->data); 32 | p->data = data; 33 | } 34 | memcpy(p->data + p->pos, buf, size); 35 | p->pos += size; 36 | return 1; 37 | } 38 | 39 | void DynBuf_Free(CDynBuf *p, ISzAlloc *alloc) 40 | { 41 | alloc->Free(alloc, p->data); 42 | p->data = 0; 43 | p->size = 0; 44 | p->pos = 0; 45 | } 46 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/7zCrc.c: -------------------------------------------------------------------------------- 1 | /* 7zCrc.c -- CRC32 calculation 2 | 2008-08-05 3 | Igor Pavlov 4 | Public domain */ 5 | 6 | #include "7zCrc.h" 7 | 8 | #define kCrcPoly 0xEDB88320 9 | UInt32 g_CrcTable[256]; 10 | 11 | void MY_FAST_CALL CrcGenerateTable(void) 12 | { 13 | UInt32 i; 14 | for (i = 0; i < 256; i++) 15 | { 16 | UInt32 r = i; 17 | int j; 18 | for (j = 0; j < 8; j++) 19 | r = (r >> 1) ^ (kCrcPoly & ~((r & 1) - 1)); 20 | g_CrcTable[i] = r; 21 | } 22 | } 23 | 24 | UInt32 MY_FAST_CALL CrcUpdate(UInt32 v, const void *data, size_t size) 25 | { 26 | const Byte *p = (const Byte *)data; 27 | for (; size > 0 ; size--, p++) 28 | v = CRC_UPDATE_BYTE(v, *p); 29 | return v; 30 | } 31 | 32 | UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size) 33 | { 34 | return CrcUpdate(CRC_INIT_VAL, data, size) ^ 0xFFFFFFFF; 35 | } 36 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/7zCrc.h: -------------------------------------------------------------------------------- 1 | /* 7zCrc.h -- CRC32 calculation 2 | 2008-03-13 3 | Igor Pavlov 4 | Public domain */ 5 | 6 | #ifndef __7Z_CRC_H 7 | #define __7Z_CRC_H 8 | 9 | #include 10 | 11 | #include "Types.h" 12 | 13 | extern UInt32 g_CrcTable[]; 14 | 15 | void MY_FAST_CALL CrcGenerateTable(void); 16 | 17 | #define CRC_INIT_VAL 0xFFFFFFFF 18 | #define CRC_GET_DIGEST(crc) ((crc) ^ 0xFFFFFFFF) 19 | #define CRC_UPDATE_BYTE(crc, b) (g_CrcTable[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) 20 | 21 | UInt32 MY_FAST_CALL CrcUpdate(UInt32 crc, const void *data, size_t size); 22 | UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size); 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/7zFile.h: -------------------------------------------------------------------------------- 1 | /* 7zFile.h -- File IO 2 | 2008-11-22 : Igor Pavlov : Public domain */ 3 | 4 | #ifndef __7Z_FILE_H 5 | #define __7Z_FILE_H 6 | 7 | #ifdef _WIN32 8 | #define USE_WINDOWS_FILE 9 | #endif 10 | 11 | #ifdef USE_WINDOWS_FILE 12 | #include 13 | #else 14 | #include 15 | #endif 16 | 17 | #include "Types.h" 18 | 19 | 20 | /* ---------- File ---------- */ 21 | 22 | typedef struct 23 | { 24 | #ifdef USE_WINDOWS_FILE 25 | HANDLE handle; 26 | #else 27 | FILE *file; 28 | #endif 29 | } CSzFile; 30 | 31 | void File_Construct(CSzFile *p); 32 | WRes InFile_Open(CSzFile *p, const char *name); 33 | WRes OutFile_Open(CSzFile *p, const char *name); 34 | WRes File_Close(CSzFile *p); 35 | 36 | /* reads max(*size, remain file's size) bytes */ 37 | WRes File_Read(CSzFile *p, void *data, size_t *size); 38 | 39 | /* writes *size bytes */ 40 | WRes File_Write(CSzFile *p, const void *data, size_t *size); 41 | 42 | WRes File_Seek(CSzFile *p, Int64 *pos, ESzSeek origin); 43 | WRes File_GetLength(CSzFile *p, UInt64 *length); 44 | 45 | 46 | /* ---------- FileInStream ---------- */ 47 | 48 | typedef struct 49 | { 50 | ISeqInStream s; 51 | CSzFile file; 52 | } CFileSeqInStream; 53 | 54 | void FileSeqInStream_CreateVTable(CFileSeqInStream *p); 55 | 56 | 57 | typedef struct 58 | { 59 | ISeekInStream s; 60 | CSzFile file; 61 | } CFileInStream; 62 | 63 | void FileInStream_CreateVTable(CFileInStream *p); 64 | 65 | 66 | typedef struct 67 | { 68 | ISeqOutStream s; 69 | CSzFile file; 70 | } CFileOutStream; 71 | 72 | void FileOutStream_CreateVTable(CFileOutStream *p); 73 | 74 | #endif 75 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/7zVersion.h: -------------------------------------------------------------------------------- 1 | #define MY_VER_MAJOR 4 2 | #define MY_VER_MINOR 63 3 | #define MY_VER_BUILD 0 4 | #define MY_VERSION "4.63" 5 | #define MY_DATE "2008-12-31" 6 | #define MY_COPYRIGHT ": Igor Pavlov : Public domain" 7 | #define MY_VERSION_COPYRIGHT_DATE MY_VERSION " " MY_COPYRIGHT " : " MY_DATE 8 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/Alloc.c: -------------------------------------------------------------------------------- 1 | /* Alloc.c -- Memory allocation functions 2 | 2008-09-24 3 | Igor Pavlov 4 | Public domain */ 5 | 6 | #ifdef _WIN32 7 | #include 8 | #endif 9 | #include 10 | 11 | #include "Alloc.h" 12 | 13 | /* #define _SZ_ALLOC_DEBUG */ 14 | 15 | /* use _SZ_ALLOC_DEBUG to debug alloc/free operations */ 16 | #ifdef _SZ_ALLOC_DEBUG 17 | #include 18 | int g_allocCount = 0; 19 | int g_allocCountMid = 0; 20 | int g_allocCountBig = 0; 21 | #endif 22 | 23 | void *MyAlloc(size_t size) 24 | { 25 | if (size == 0) 26 | return 0; 27 | #ifdef _SZ_ALLOC_DEBUG 28 | { 29 | void *p = malloc(size); 30 | fprintf(stderr, "\nAlloc %10d bytes, count = %10d, addr = %8X", size, g_allocCount++, (unsigned)p); 31 | return p; 32 | } 33 | #else 34 | return malloc(size); 35 | #endif 36 | } 37 | 38 | void MyFree(void *address) 39 | { 40 | #ifdef _SZ_ALLOC_DEBUG 41 | if (address != 0) 42 | fprintf(stderr, "\nFree; count = %10d, addr = %8X", --g_allocCount, (unsigned)address); 43 | #endif 44 | free(address); 45 | } 46 | 47 | #ifdef _WIN32 48 | 49 | void *MidAlloc(size_t size) 50 | { 51 | if (size == 0) 52 | return 0; 53 | #ifdef _SZ_ALLOC_DEBUG 54 | fprintf(stderr, "\nAlloc_Mid %10d bytes; count = %10d", size, g_allocCountMid++); 55 | #endif 56 | return VirtualAlloc(0, size, MEM_COMMIT, PAGE_READWRITE); 57 | } 58 | 59 | void MidFree(void *address) 60 | { 61 | #ifdef _SZ_ALLOC_DEBUG 62 | if (address != 0) 63 | fprintf(stderr, "\nFree_Mid; count = %10d", --g_allocCountMid); 64 | #endif 65 | if (address == 0) 66 | return; 67 | VirtualFree(address, 0, MEM_RELEASE); 68 | } 69 | 70 | #ifndef MEM_LARGE_PAGES 71 | #undef _7ZIP_LARGE_PAGES 72 | #endif 73 | 74 | #ifdef _7ZIP_LARGE_PAGES 75 | SIZE_T g_LargePageSize = 0; 76 | typedef SIZE_T (WINAPI *GetLargePageMinimumP)(); 77 | #endif 78 | 79 | void SetLargePageSize() 80 | { 81 | #ifdef _7ZIP_LARGE_PAGES 82 | SIZE_T size = 0; 83 | GetLargePageMinimumP largePageMinimum = (GetLargePageMinimumP) 84 | GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetLargePageMinimum"); 85 | if (largePageMinimum == 0) 86 | return; 87 | size = largePageMinimum(); 88 | if (size == 0 || (size & (size - 1)) != 0) 89 | return; 90 | g_LargePageSize = size; 91 | #endif 92 | } 93 | 94 | 95 | void *BigAlloc(size_t size) 96 | { 97 | if (size == 0) 98 | return 0; 99 | #ifdef _SZ_ALLOC_DEBUG 100 | fprintf(stderr, "\nAlloc_Big %10d bytes; count = %10d", size, g_allocCountBig++); 101 | #endif 102 | 103 | #ifdef _7ZIP_LARGE_PAGES 104 | if (g_LargePageSize != 0 && g_LargePageSize <= (1 << 30) && size >= (1 << 18)) 105 | { 106 | void *res = VirtualAlloc(0, (size + g_LargePageSize - 1) & (~(g_LargePageSize - 1)), 107 | MEM_COMMIT | MEM_LARGE_PAGES, PAGE_READWRITE); 108 | if (res != 0) 109 | return res; 110 | } 111 | #endif 112 | return VirtualAlloc(0, size, MEM_COMMIT, PAGE_READWRITE); 113 | } 114 | 115 | void BigFree(void *address) 116 | { 117 | #ifdef _SZ_ALLOC_DEBUG 118 | if (address != 0) 119 | fprintf(stderr, "\nFree_Big; count = %10d", --g_allocCountBig); 120 | #endif 121 | 122 | if (address == 0) 123 | return; 124 | VirtualFree(address, 0, MEM_RELEASE); 125 | } 126 | 127 | #endif 128 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/Alloc.h: -------------------------------------------------------------------------------- 1 | /* Alloc.h -- Memory allocation functions 2 | 2008-03-13 3 | Igor Pavlov 4 | Public domain */ 5 | 6 | #ifndef __COMMON_ALLOC_H 7 | #define __COMMON_ALLOC_H 8 | 9 | #include 10 | 11 | void *MyAlloc(size_t size); 12 | void MyFree(void *address); 13 | 14 | #ifdef _WIN32 15 | 16 | void SetLargePageSize(); 17 | 18 | void *MidAlloc(size_t size); 19 | void MidFree(void *address); 20 | void *BigAlloc(size_t size); 21 | void BigFree(void *address); 22 | 23 | #else 24 | 25 | #define MidAlloc(size) MyAlloc(size) 26 | #define MidFree(address) MyFree(address) 27 | #define BigAlloc(size) MyAlloc(size) 28 | #define BigFree(address) MyFree(address) 29 | 30 | #endif 31 | 32 | #endif 33 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/Bcj2.c: -------------------------------------------------------------------------------- 1 | /* Bcj2.c -- Converter for x86 code (BCJ2) 2 | 2008-10-04 : Igor Pavlov : Public domain */ 3 | 4 | #include "Bcj2.h" 5 | 6 | #ifdef _LZMA_PROB32 7 | #define CProb UInt32 8 | #else 9 | #define CProb UInt16 10 | #endif 11 | 12 | #define IsJcc(b0, b1) ((b0) == 0x0F && ((b1) & 0xF0) == 0x80) 13 | #define IsJ(b0, b1) ((b1 & 0xFE) == 0xE8 || IsJcc(b0, b1)) 14 | 15 | #define kNumTopBits 24 16 | #define kTopValue ((UInt32)1 << kNumTopBits) 17 | 18 | #define kNumBitModelTotalBits 11 19 | #define kBitModelTotal (1 << kNumBitModelTotalBits) 20 | #define kNumMoveBits 5 21 | 22 | #define RC_READ_BYTE (*buffer++) 23 | #define RC_TEST { if (buffer == bufferLim) return SZ_ERROR_DATA; } 24 | #define RC_INIT2 code = 0; range = 0xFFFFFFFF; \ 25 | { int i; for (i = 0; i < 5; i++) { RC_TEST; code = (code << 8) | RC_READ_BYTE; }} 26 | 27 | #define NORMALIZE if (range < kTopValue) { RC_TEST; range <<= 8; code = (code << 8) | RC_READ_BYTE; } 28 | 29 | #define IF_BIT_0(p) ttt = *(p); bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound) 30 | #define UPDATE_0(p) range = bound; *(p) = (CProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); NORMALIZE; 31 | #define UPDATE_1(p) range -= bound; code -= bound; *(p) = (CProb)(ttt - (ttt >> kNumMoveBits)); NORMALIZE; 32 | 33 | int Bcj2_Decode( 34 | const Byte *buf0, SizeT size0, 35 | const Byte *buf1, SizeT size1, 36 | const Byte *buf2, SizeT size2, 37 | const Byte *buf3, SizeT size3, 38 | Byte *outBuf, SizeT outSize) 39 | { 40 | CProb p[256 + 2]; 41 | SizeT inPos = 0, outPos = 0; 42 | 43 | const Byte *buffer, *bufferLim; 44 | UInt32 range, code; 45 | Byte prevByte = 0; 46 | 47 | unsigned int i; 48 | for (i = 0; i < sizeof(p) / sizeof(p[0]); i++) 49 | p[i] = kBitModelTotal >> 1; 50 | 51 | buffer = buf3; 52 | bufferLim = buffer + size3; 53 | RC_INIT2 54 | 55 | if (outSize == 0) 56 | return SZ_OK; 57 | 58 | for (;;) 59 | { 60 | Byte b; 61 | CProb *prob; 62 | UInt32 bound; 63 | UInt32 ttt; 64 | 65 | SizeT limit = size0 - inPos; 66 | if (outSize - outPos < limit) 67 | limit = outSize - outPos; 68 | while (limit != 0) 69 | { 70 | Byte b = buf0[inPos]; 71 | outBuf[outPos++] = b; 72 | if (IsJ(prevByte, b)) 73 | break; 74 | inPos++; 75 | prevByte = b; 76 | limit--; 77 | } 78 | 79 | if (limit == 0 || outPos == outSize) 80 | break; 81 | 82 | b = buf0[inPos++]; 83 | 84 | if (b == 0xE8) 85 | prob = p + prevByte; 86 | else if (b == 0xE9) 87 | prob = p + 256; 88 | else 89 | prob = p + 257; 90 | 91 | IF_BIT_0(prob) 92 | { 93 | UPDATE_0(prob) 94 | prevByte = b; 95 | } 96 | else 97 | { 98 | UInt32 dest; 99 | const Byte *v; 100 | UPDATE_1(prob) 101 | if (b == 0xE8) 102 | { 103 | v = buf1; 104 | if (size1 < 4) 105 | return SZ_ERROR_DATA; 106 | buf1 += 4; 107 | size1 -= 4; 108 | } 109 | else 110 | { 111 | v = buf2; 112 | if (size2 < 4) 113 | return SZ_ERROR_DATA; 114 | buf2 += 4; 115 | size2 -= 4; 116 | } 117 | dest = (((UInt32)v[0] << 24) | ((UInt32)v[1] << 16) | 118 | ((UInt32)v[2] << 8) | ((UInt32)v[3])) - ((UInt32)outPos + 4); 119 | outBuf[outPos++] = (Byte)dest; 120 | if (outPos == outSize) 121 | break; 122 | outBuf[outPos++] = (Byte)(dest >> 8); 123 | if (outPos == outSize) 124 | break; 125 | outBuf[outPos++] = (Byte)(dest >> 16); 126 | if (outPos == outSize) 127 | break; 128 | outBuf[outPos++] = prevByte = (Byte)(dest >> 24); 129 | } 130 | } 131 | return (outPos == outSize) ? SZ_OK : SZ_ERROR_DATA; 132 | } 133 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/Bcj2.h: -------------------------------------------------------------------------------- 1 | /* Bcj2.h -- Converter for x86 code (BCJ2) 2 | 2008-10-04 : Igor Pavlov : Public domain */ 3 | 4 | #ifndef __BCJ2_H 5 | #define __BCJ2_H 6 | 7 | #include "Types.h" 8 | 9 | /* 10 | Conditions: 11 | outSize <= FullOutputSize, 12 | where FullOutputSize is full size of output stream of x86_2 filter. 13 | 14 | If buf0 overlaps outBuf, there are two required conditions: 15 | 1) (buf0 >= outBuf) 16 | 2) (buf0 + size0 >= outBuf + FullOutputSize). 17 | 18 | Returns: 19 | SZ_OK 20 | SZ_ERROR_DATA - Data error 21 | */ 22 | 23 | int Bcj2_Decode( 24 | const Byte *buf0, SizeT size0, 25 | const Byte *buf1, SizeT size1, 26 | const Byte *buf2, SizeT size2, 27 | const Byte *buf3, SizeT size3, 28 | Byte *outBuf, SizeT outSize); 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/Bra.c: -------------------------------------------------------------------------------- 1 | /* Bra.c -- Converters for RISC code 2 | 2008-10-04 : Igor Pavlov : Public domain */ 3 | 4 | #include "Bra.h" 5 | 6 | SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) 7 | { 8 | SizeT i; 9 | if (size < 4) 10 | return 0; 11 | size -= 4; 12 | ip += 8; 13 | for (i = 0; i <= size; i += 4) 14 | { 15 | if (data[i + 3] == 0xEB) 16 | { 17 | UInt32 dest; 18 | UInt32 src = ((UInt32)data[i + 2] << 16) | ((UInt32)data[i + 1] << 8) | (data[i + 0]); 19 | src <<= 2; 20 | if (encoding) 21 | dest = ip + (UInt32)i + src; 22 | else 23 | dest = src - (ip + (UInt32)i); 24 | dest >>= 2; 25 | data[i + 2] = (Byte)(dest >> 16); 26 | data[i + 1] = (Byte)(dest >> 8); 27 | data[i + 0] = (Byte)dest; 28 | } 29 | } 30 | return i; 31 | } 32 | 33 | SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) 34 | { 35 | SizeT i; 36 | if (size < 4) 37 | return 0; 38 | size -= 4; 39 | ip += 4; 40 | for (i = 0; i <= size; i += 2) 41 | { 42 | if ((data[i + 1] & 0xF8) == 0xF0 && 43 | (data[i + 3] & 0xF8) == 0xF8) 44 | { 45 | UInt32 dest; 46 | UInt32 src = 47 | (((UInt32)data[i + 1] & 0x7) << 19) | 48 | ((UInt32)data[i + 0] << 11) | 49 | (((UInt32)data[i + 3] & 0x7) << 8) | 50 | (data[i + 2]); 51 | 52 | src <<= 1; 53 | if (encoding) 54 | dest = ip + (UInt32)i + src; 55 | else 56 | dest = src - (ip + (UInt32)i); 57 | dest >>= 1; 58 | 59 | data[i + 1] = (Byte)(0xF0 | ((dest >> 19) & 0x7)); 60 | data[i + 0] = (Byte)(dest >> 11); 61 | data[i + 3] = (Byte)(0xF8 | ((dest >> 8) & 0x7)); 62 | data[i + 2] = (Byte)dest; 63 | i += 2; 64 | } 65 | } 66 | return i; 67 | } 68 | 69 | SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) 70 | { 71 | SizeT i; 72 | if (size < 4) 73 | return 0; 74 | size -= 4; 75 | for (i = 0; i <= size; i += 4) 76 | { 77 | if ((data[i] >> 2) == 0x12 && (data[i + 3] & 3) == 1) 78 | { 79 | UInt32 src = ((UInt32)(data[i + 0] & 3) << 24) | 80 | ((UInt32)data[i + 1] << 16) | 81 | ((UInt32)data[i + 2] << 8) | 82 | ((UInt32)data[i + 3] & (~3)); 83 | 84 | UInt32 dest; 85 | if (encoding) 86 | dest = ip + (UInt32)i + src; 87 | else 88 | dest = src - (ip + (UInt32)i); 89 | data[i + 0] = (Byte)(0x48 | ((dest >> 24) & 0x3)); 90 | data[i + 1] = (Byte)(dest >> 16); 91 | data[i + 2] = (Byte)(dest >> 8); 92 | data[i + 3] &= 0x3; 93 | data[i + 3] |= dest; 94 | } 95 | } 96 | return i; 97 | } 98 | 99 | SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) 100 | { 101 | UInt32 i; 102 | if (size < 4) 103 | return 0; 104 | size -= 4; 105 | for (i = 0; i <= size; i += 4) 106 | { 107 | if ((data[i] == 0x40 && (data[i + 1] & 0xC0) == 0x00) || 108 | (data[i] == 0x7F && (data[i + 1] & 0xC0) == 0xC0)) 109 | { 110 | UInt32 src = 111 | ((UInt32)data[i + 0] << 24) | 112 | ((UInt32)data[i + 1] << 16) | 113 | ((UInt32)data[i + 2] << 8) | 114 | ((UInt32)data[i + 3]); 115 | UInt32 dest; 116 | 117 | src <<= 2; 118 | if (encoding) 119 | dest = ip + i + src; 120 | else 121 | dest = src - (ip + i); 122 | dest >>= 2; 123 | 124 | dest = (((0 - ((dest >> 22) & 1)) << 22) & 0x3FFFFFFF) | (dest & 0x3FFFFF) | 0x40000000; 125 | 126 | data[i + 0] = (Byte)(dest >> 24); 127 | data[i + 1] = (Byte)(dest >> 16); 128 | data[i + 2] = (Byte)(dest >> 8); 129 | data[i + 3] = (Byte)dest; 130 | } 131 | } 132 | return i; 133 | } 134 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/Bra.h: -------------------------------------------------------------------------------- 1 | /* Bra.h -- Branch converters for executables 2 | 2008-10-04 : Igor Pavlov : Public domain */ 3 | 4 | #ifndef __BRA_H 5 | #define __BRA_H 6 | 7 | #include "Types.h" 8 | 9 | /* 10 | These functions convert relative addresses to absolute addresses 11 | in CALL instructions to increase the compression ratio. 12 | 13 | In: 14 | data - data buffer 15 | size - size of data 16 | ip - current virtual Instruction Pinter (IP) value 17 | state - state variable for x86 converter 18 | encoding - 0 (for decoding), 1 (for encoding) 19 | 20 | Out: 21 | state - state variable for x86 converter 22 | 23 | Returns: 24 | The number of processed bytes. If you call these functions with multiple calls, 25 | you must start next call with first byte after block of processed bytes. 26 | 27 | Type Endian Alignment LookAhead 28 | 29 | x86 little 1 4 30 | ARMT little 2 2 31 | ARM little 4 0 32 | PPC big 4 0 33 | SPARC big 4 0 34 | IA64 little 16 0 35 | 36 | size must be >= Alignment + LookAhead, if it's not last block. 37 | If (size < Alignment + LookAhead), converter returns 0. 38 | 39 | Example: 40 | 41 | UInt32 ip = 0; 42 | for () 43 | { 44 | ; size must be >= Alignment + LookAhead, if it's not last block 45 | SizeT processed = Convert(data, size, ip, 1); 46 | data += processed; 47 | size -= processed; 48 | ip += processed; 49 | } 50 | */ 51 | 52 | #define x86_Convert_Init(state) { state = 0; } 53 | SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding); 54 | SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); 55 | SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); 56 | SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); 57 | SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); 58 | SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); 59 | 60 | #endif 61 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/Bra86.c: -------------------------------------------------------------------------------- 1 | /* Bra86.c -- Converter for x86 code (BCJ) 2 | 2008-10-04 : Igor Pavlov : Public domain */ 3 | 4 | #include "Bra.h" 5 | 6 | #define Test86MSByte(b) ((b) == 0 || (b) == 0xFF) 7 | 8 | const Byte kMaskToAllowedStatus[8] = {1, 1, 1, 0, 1, 0, 0, 0}; 9 | const Byte kMaskToBitNumber[8] = {0, 1, 2, 2, 3, 3, 3, 3}; 10 | 11 | SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding) 12 | { 13 | SizeT bufferPos = 0, prevPosT; 14 | UInt32 prevMask = *state & 0x7; 15 | if (size < 5) 16 | return 0; 17 | ip += 5; 18 | prevPosT = (SizeT)0 - 1; 19 | 20 | for (;;) 21 | { 22 | Byte *p = data + bufferPos; 23 | Byte *limit = data + size - 4; 24 | for (; p < limit; p++) 25 | if ((*p & 0xFE) == 0xE8) 26 | break; 27 | bufferPos = (SizeT)(p - data); 28 | if (p >= limit) 29 | break; 30 | prevPosT = bufferPos - prevPosT; 31 | if (prevPosT > 3) 32 | prevMask = 0; 33 | else 34 | { 35 | prevMask = (prevMask << ((int)prevPosT - 1)) & 0x7; 36 | if (prevMask != 0) 37 | { 38 | Byte b = p[4 - kMaskToBitNumber[prevMask]]; 39 | if (!kMaskToAllowedStatus[prevMask] || Test86MSByte(b)) 40 | { 41 | prevPosT = bufferPos; 42 | prevMask = ((prevMask << 1) & 0x7) | 1; 43 | bufferPos++; 44 | continue; 45 | } 46 | } 47 | } 48 | prevPosT = bufferPos; 49 | 50 | if (Test86MSByte(p[4])) 51 | { 52 | UInt32 src = ((UInt32)p[4] << 24) | ((UInt32)p[3] << 16) | ((UInt32)p[2] << 8) | ((UInt32)p[1]); 53 | UInt32 dest; 54 | for (;;) 55 | { 56 | Byte b; 57 | int index; 58 | if (encoding) 59 | dest = (ip + (UInt32)bufferPos) + src; 60 | else 61 | dest = src - (ip + (UInt32)bufferPos); 62 | if (prevMask == 0) 63 | break; 64 | index = kMaskToBitNumber[prevMask] * 8; 65 | b = (Byte)(dest >> (24 - index)); 66 | if (!Test86MSByte(b)) 67 | break; 68 | src = dest ^ ((1 << (32 - index)) - 1); 69 | } 70 | p[4] = (Byte)(~(((dest >> 24) & 1) - 1)); 71 | p[3] = (Byte)(dest >> 16); 72 | p[2] = (Byte)(dest >> 8); 73 | p[1] = (Byte)dest; 74 | bufferPos += 5; 75 | } 76 | else 77 | { 78 | prevMask = ((prevMask << 1) & 0x7) | 1; 79 | bufferPos++; 80 | } 81 | } 82 | prevPosT = bufferPos - prevPosT; 83 | *state = ((prevPosT > 3) ? 0 : ((prevMask << ((int)prevPosT - 1)) & 0x7)); 84 | return bufferPos; 85 | } 86 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/BraIA64.c: -------------------------------------------------------------------------------- 1 | /* BraIA64.c -- Converter for IA-64 code 2 | 2008-10-04 : Igor Pavlov : Public domain */ 3 | 4 | #include "Bra.h" 5 | 6 | static const Byte kBranchTable[32] = 7 | { 8 | 0, 0, 0, 0, 0, 0, 0, 0, 9 | 0, 0, 0, 0, 0, 0, 0, 0, 10 | 4, 4, 6, 6, 0, 0, 7, 7, 11 | 4, 4, 0, 0, 4, 4, 0, 0 12 | }; 13 | 14 | SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) 15 | { 16 | SizeT i; 17 | if (size < 16) 18 | return 0; 19 | size -= 16; 20 | for (i = 0; i <= size; i += 16) 21 | { 22 | UInt32 instrTemplate = data[i] & 0x1F; 23 | UInt32 mask = kBranchTable[instrTemplate]; 24 | UInt32 bitPos = 5; 25 | int slot; 26 | for (slot = 0; slot < 3; slot++, bitPos += 41) 27 | { 28 | UInt32 bytePos, bitRes; 29 | UInt64 instruction, instNorm; 30 | int j; 31 | if (((mask >> slot) & 1) == 0) 32 | continue; 33 | bytePos = (bitPos >> 3); 34 | bitRes = bitPos & 0x7; 35 | instruction = 0; 36 | for (j = 0; j < 6; j++) 37 | instruction += (UInt64)data[i + j + bytePos] << (8 * j); 38 | 39 | instNorm = instruction >> bitRes; 40 | if (((instNorm >> 37) & 0xF) == 0x5 && ((instNorm >> 9) & 0x7) == 0) 41 | { 42 | UInt32 src = (UInt32)((instNorm >> 13) & 0xFFFFF); 43 | UInt32 dest; 44 | src |= ((UInt32)(instNorm >> 36) & 1) << 20; 45 | 46 | src <<= 4; 47 | 48 | if (encoding) 49 | dest = ip + (UInt32)i + src; 50 | else 51 | dest = src - (ip + (UInt32)i); 52 | 53 | dest >>= 4; 54 | 55 | instNorm &= ~((UInt64)(0x8FFFFF) << 13); 56 | instNorm |= ((UInt64)(dest & 0xFFFFF) << 13); 57 | instNorm |= ((UInt64)(dest & 0x100000) << (36 - 20)); 58 | 59 | instruction &= (1 << bitRes) - 1; 60 | instruction |= (instNorm << bitRes); 61 | for (j = 0; j < 6; j++) 62 | data[i + j + bytePos] = (Byte)(instruction >> (8 * j)); 63 | } 64 | } 65 | } 66 | return i; 67 | } 68 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/CpuArch.h: -------------------------------------------------------------------------------- 1 | /* CpuArch.h 2 | 2008-08-05 3 | Igor Pavlov 4 | Public domain */ 5 | 6 | #ifndef __CPUARCH_H 7 | #define __CPUARCH_H 8 | 9 | /* 10 | LITTLE_ENDIAN_UNALIGN means: 11 | 1) CPU is LITTLE_ENDIAN 12 | 2) it's allowed to make unaligned memory accesses 13 | if LITTLE_ENDIAN_UNALIGN is not defined, it means that we don't know 14 | about these properties of platform. 15 | */ 16 | 17 | #if defined(_M_IX86) || defined(_M_X64) || defined(_M_AMD64) || defined(__i386__) || defined(__x86_64__) 18 | #define LITTLE_ENDIAN_UNALIGN 19 | #endif 20 | 21 | #ifdef LITTLE_ENDIAN_UNALIGN 22 | 23 | #define GetUi16(p) (*(const UInt16 *)(p)) 24 | #define GetUi32(p) (*(const UInt32 *)(p)) 25 | #define GetUi64(p) (*(const UInt64 *)(p)) 26 | #define SetUi32(p, d) *(UInt32 *)(p) = (d); 27 | 28 | #else 29 | 30 | #define GetUi16(p) (((const Byte *)(p))[0] | ((UInt16)((const Byte *)(p))[1] << 8)) 31 | 32 | #define GetUi32(p) ( \ 33 | ((const Byte *)(p))[0] | \ 34 | ((UInt32)((const Byte *)(p))[1] << 8) | \ 35 | ((UInt32)((const Byte *)(p))[2] << 16) | \ 36 | ((UInt32)((const Byte *)(p))[3] << 24)) 37 | 38 | #define GetUi64(p) (GetUi32(p) | ((UInt64)GetUi32(((const Byte *)(p)) + 4) << 32)) 39 | 40 | #define SetUi32(p, d) { UInt32 _x_ = (d); \ 41 | ((Byte *)(p))[0] = (Byte)_x_; \ 42 | ((Byte *)(p))[1] = (Byte)(_x_ >> 8); \ 43 | ((Byte *)(p))[2] = (Byte)(_x_ >> 16); \ 44 | ((Byte *)(p))[3] = (Byte)(_x_ >> 24); } 45 | 46 | #endif 47 | 48 | #if defined(LITTLE_ENDIAN_UNALIGN) && defined(_WIN64) && (_MSC_VER >= 1300) 49 | 50 | #pragma intrinsic(_byteswap_ulong) 51 | #pragma intrinsic(_byteswap_uint64) 52 | #define GetBe32(p) _byteswap_ulong(*(const UInt32 *)(const Byte *)(p)) 53 | #define GetBe64(p) _byteswap_uint64(*(const UInt64 *)(const Byte *)(p)) 54 | 55 | #else 56 | 57 | #define GetBe32(p) ( \ 58 | ((UInt32)((const Byte *)(p))[0] << 24) | \ 59 | ((UInt32)((const Byte *)(p))[1] << 16) | \ 60 | ((UInt32)((const Byte *)(p))[2] << 8) | \ 61 | ((const Byte *)(p))[3] ) 62 | 63 | #define GetBe64(p) (((UInt64)GetBe32(p) << 32) | GetBe32(((const Byte *)(p)) + 4)) 64 | 65 | #endif 66 | 67 | #define GetBe16(p) (((UInt16)((const Byte *)(p))[0] << 8) | ((const Byte *)(p))[1]) 68 | 69 | #endif 70 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/LzFind.h: -------------------------------------------------------------------------------- 1 | /* LzFind.h -- Match finder for LZ algorithms 2 | 2008-10-04 : Igor Pavlov : Public domain */ 3 | 4 | #ifndef __LZFIND_H 5 | #define __LZFIND_H 6 | 7 | #include "Types.h" 8 | 9 | typedef UInt32 CLzRef; 10 | 11 | typedef struct _CMatchFinder 12 | { 13 | Byte *buffer; 14 | UInt32 pos; 15 | UInt32 posLimit; 16 | UInt32 streamPos; 17 | UInt32 lenLimit; 18 | 19 | UInt32 cyclicBufferPos; 20 | UInt32 cyclicBufferSize; /* it must be = (historySize + 1) */ 21 | 22 | UInt32 matchMaxLen; 23 | CLzRef *hash; 24 | CLzRef *son; 25 | UInt32 hashMask; 26 | UInt32 cutValue; 27 | 28 | Byte *bufferBase; 29 | ISeqInStream *stream; 30 | int streamEndWasReached; 31 | 32 | UInt32 blockSize; 33 | UInt32 keepSizeBefore; 34 | UInt32 keepSizeAfter; 35 | 36 | UInt32 numHashBytes; 37 | int directInput; 38 | int btMode; 39 | /* int skipModeBits; */ 40 | int bigHash; 41 | UInt32 historySize; 42 | UInt32 fixedHashSize; 43 | UInt32 hashSizeSum; 44 | UInt32 numSons; 45 | SRes result; 46 | UInt32 crc[256]; 47 | } CMatchFinder; 48 | 49 | #define Inline_MatchFinder_GetPointerToCurrentPos(p) ((p)->buffer) 50 | #define Inline_MatchFinder_GetIndexByte(p, index) ((p)->buffer[(Int32)(index)]) 51 | 52 | #define Inline_MatchFinder_GetNumAvailableBytes(p) ((p)->streamPos - (p)->pos) 53 | 54 | int MatchFinder_NeedMove(CMatchFinder *p); 55 | Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p); 56 | void MatchFinder_MoveBlock(CMatchFinder *p); 57 | void MatchFinder_ReadIfRequired(CMatchFinder *p); 58 | 59 | void MatchFinder_Construct(CMatchFinder *p); 60 | 61 | /* Conditions: 62 | historySize <= 3 GB 63 | keepAddBufferBefore + matchMaxLen + keepAddBufferAfter < 511MB 64 | */ 65 | int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, 66 | UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, 67 | ISzAlloc *alloc); 68 | void MatchFinder_Free(CMatchFinder *p, ISzAlloc *alloc); 69 | void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, UInt32 numItems); 70 | void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue); 71 | 72 | UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *buffer, CLzRef *son, 73 | UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 _cutValue, 74 | UInt32 *distances, UInt32 maxLen); 75 | 76 | /* 77 | Conditions: 78 | Mf_GetNumAvailableBytes_Func must be called before each Mf_GetMatchLen_Func. 79 | Mf_GetPointerToCurrentPos_Func's result must be used only before any other function 80 | */ 81 | 82 | typedef void (*Mf_Init_Func)(void *object); 83 | typedef Byte (*Mf_GetIndexByte_Func)(void *object, Int32 index); 84 | typedef UInt32 (*Mf_GetNumAvailableBytes_Func)(void *object); 85 | typedef const Byte * (*Mf_GetPointerToCurrentPos_Func)(void *object); 86 | typedef UInt32 (*Mf_GetMatches_Func)(void *object, UInt32 *distances); 87 | typedef void (*Mf_Skip_Func)(void *object, UInt32); 88 | 89 | typedef struct _IMatchFinder 90 | { 91 | Mf_Init_Func Init; 92 | Mf_GetIndexByte_Func GetIndexByte; 93 | Mf_GetNumAvailableBytes_Func GetNumAvailableBytes; 94 | Mf_GetPointerToCurrentPos_Func GetPointerToCurrentPos; 95 | Mf_GetMatches_Func GetMatches; 96 | Mf_Skip_Func Skip; 97 | } IMatchFinder; 98 | 99 | void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable); 100 | 101 | void MatchFinder_Init(CMatchFinder *p); 102 | UInt32 Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances); 103 | UInt32 Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances); 104 | void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num); 105 | void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num); 106 | 107 | #endif 108 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/LzHash.h: -------------------------------------------------------------------------------- 1 | /* LzHash.h -- HASH functions for LZ algorithms 2 | 2008-10-04 : Igor Pavlov : Public domain */ 3 | 4 | #ifndef __LZHASH_H 5 | #define __LZHASH_H 6 | 7 | #define kHash2Size (1 << 10) 8 | #define kHash3Size (1 << 16) 9 | #define kHash4Size (1 << 20) 10 | 11 | #define kFix3HashSize (kHash2Size) 12 | #define kFix4HashSize (kHash2Size + kHash3Size) 13 | #define kFix5HashSize (kHash2Size + kHash3Size + kHash4Size) 14 | 15 | #define HASH2_CALC hashValue = cur[0] | ((UInt32)cur[1] << 8); 16 | 17 | #define HASH3_CALC { \ 18 | UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ 19 | hash2Value = temp & (kHash2Size - 1); \ 20 | hashValue = (temp ^ ((UInt32)cur[2] << 8)) & p->hashMask; } 21 | 22 | #define HASH4_CALC { \ 23 | UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ 24 | hash2Value = temp & (kHash2Size - 1); \ 25 | hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \ 26 | hashValue = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)) & p->hashMask; } 27 | 28 | #define HASH5_CALC { \ 29 | UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ 30 | hash2Value = temp & (kHash2Size - 1); \ 31 | hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \ 32 | hash4Value = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)); \ 33 | hashValue = (hash4Value ^ (p->crc[cur[4]] << 3)) & p->hashMask; \ 34 | hash4Value &= (kHash4Size - 1); } 35 | 36 | /* #define HASH_ZIP_CALC hashValue = ((cur[0] | ((UInt32)cur[1] << 8)) ^ p->crc[cur[2]]) & 0xFFFF; */ 37 | #define HASH_ZIP_CALC hashValue = ((cur[2] | ((UInt32)cur[0] << 8)) ^ p->crc[cur[1]]) & 0xFFFF; 38 | 39 | 40 | #define MT_HASH2_CALC \ 41 | hash2Value = (p->crc[cur[0]] ^ cur[1]) & (kHash2Size - 1); 42 | 43 | #define MT_HASH3_CALC { \ 44 | UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ 45 | hash2Value = temp & (kHash2Size - 1); \ 46 | hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); } 47 | 48 | #define MT_HASH4_CALC { \ 49 | UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ 50 | hash2Value = temp & (kHash2Size - 1); \ 51 | hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \ 52 | hash4Value = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)) & (kHash4Size - 1); } 53 | 54 | #endif 55 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/LzmaEnc.h: -------------------------------------------------------------------------------- 1 | /* LzmaEnc.h -- LZMA Encoder 2 | 2008-10-04 : Igor Pavlov : Public domain */ 3 | 4 | #ifndef __LZMAENC_H 5 | #define __LZMAENC_H 6 | 7 | #include "Types.h" 8 | 9 | #define LZMA_PROPS_SIZE 5 10 | 11 | typedef struct _CLzmaEncProps 12 | { 13 | int level; /* 0 <= level <= 9 */ 14 | UInt32 dictSize; /* (1 << 12) <= dictSize <= (1 << 27) for 32-bit version 15 | (1 << 12) <= dictSize <= (1 << 30) for 64-bit version 16 | default = (1 << 24) */ 17 | int lc; /* 0 <= lc <= 8, default = 3 */ 18 | int lp; /* 0 <= lp <= 4, default = 0 */ 19 | int pb; /* 0 <= pb <= 4, default = 2 */ 20 | int algo; /* 0 - fast, 1 - normal, default = 1 */ 21 | int fb; /* 5 <= fb <= 273, default = 32 */ 22 | int btMode; /* 0 - hashChain Mode, 1 - binTree mode - normal, default = 1 */ 23 | int numHashBytes; /* 2, 3 or 4, default = 4 */ 24 | UInt32 mc; /* 1 <= mc <= (1 << 30), default = 32 */ 25 | unsigned writeEndMark; /* 0 - do not write EOPM, 1 - write EOPM, default = 0 */ 26 | int numThreads; /* 1 or 2, default = 2 */ 27 | } CLzmaEncProps; 28 | 29 | void LzmaEncProps_Init(CLzmaEncProps *p); 30 | void LzmaEncProps_Normalize(CLzmaEncProps *p); 31 | UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2); 32 | 33 | 34 | /* ---------- CLzmaEncHandle Interface ---------- */ 35 | 36 | /* LzmaEnc_* functions can return the following exit codes: 37 | Returns: 38 | SZ_OK - OK 39 | SZ_ERROR_MEM - Memory allocation error 40 | SZ_ERROR_PARAM - Incorrect paramater in props 41 | SZ_ERROR_WRITE - Write callback error. 42 | SZ_ERROR_PROGRESS - some break from progress callback 43 | SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version) 44 | */ 45 | 46 | typedef void * CLzmaEncHandle; 47 | 48 | CLzmaEncHandle LzmaEnc_Create(ISzAlloc *alloc); 49 | void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAlloc *alloc, ISzAlloc *allocBig); 50 | SRes LzmaEnc_SetProps(CLzmaEncHandle p, const CLzmaEncProps *props); 51 | SRes LzmaEnc_WriteProperties(CLzmaEncHandle p, Byte *properties, SizeT *size); 52 | SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStream *outStream, ISeqInStream *inStream, 53 | ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig); 54 | SRes LzmaEnc_MemEncode(CLzmaEncHandle p, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, 55 | int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig); 56 | 57 | /* ---------- One Call Interface ---------- */ 58 | 59 | /* LzmaEncode 60 | Return code: 61 | SZ_OK - OK 62 | SZ_ERROR_MEM - Memory allocation error 63 | SZ_ERROR_PARAM - Incorrect paramater 64 | SZ_ERROR_OUTPUT_EOF - output buffer overflow 65 | SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version) 66 | */ 67 | 68 | SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, 69 | const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark, 70 | ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig); 71 | 72 | #endif 73 | -------------------------------------------------------------------------------- /src/zmat/easylzma/pavlov/LzmaLib.c: -------------------------------------------------------------------------------- 1 | /* LzmaLib.c -- LZMA library wrapper 2 | 2008-08-05 3 | Igor Pavlov 4 | Public domain */ 5 | 6 | #include "LzmaEnc.h" 7 | #include "LzmaDec.h" 8 | #include "Alloc.h" 9 | #include "LzmaLib.h" 10 | 11 | static void *SzAlloc(void *p, size_t size) { p = p; return MyAlloc(size); } 12 | static void SzFree(void *p, void *address) { p = p; MyFree(address); } 13 | static ISzAlloc g_Alloc = { SzAlloc, SzFree }; 14 | 15 | MY_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, 16 | unsigned char *outProps, size_t *outPropsSize, 17 | int level, /* 0 <= level <= 9, default = 5 */ 18 | unsigned dictSize, /* use (1 << N) or (3 << N). 4 KB < dictSize <= 128 MB */ 19 | int lc, /* 0 <= lc <= 8, default = 3 */ 20 | int lp, /* 0 <= lp <= 4, default = 0 */ 21 | int pb, /* 0 <= pb <= 4, default = 2 */ 22 | int fb, /* 5 <= fb <= 273, default = 32 */ 23 | int numThreads /* 1 or 2, default = 2 */ 24 | ) 25 | { 26 | CLzmaEncProps props; 27 | LzmaEncProps_Init(&props); 28 | props.level = level; 29 | props.dictSize = dictSize; 30 | props.lc = lc; 31 | props.lp = lp; 32 | props.pb = pb; 33 | props.fb = fb; 34 | props.numThreads = numThreads; 35 | 36 | return LzmaEncode(dest, destLen, src, srcLen, &props, outProps, outPropsSize, 0, 37 | NULL, &g_Alloc, &g_Alloc); 38 | } 39 | 40 | 41 | MY_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t *srcLen, 42 | const unsigned char *props, size_t propsSize) 43 | { 44 | ELzmaStatus status; 45 | return LzmaDecode(dest, destLen, src, srcLen, props, (unsigned)propsSize, LZMA_FINISH_ANY, &status, &g_Alloc); 46 | } 47 | -------------------------------------------------------------------------------- /src/zmat/zmatlib.h: -------------------------------------------------------------------------------- 1 | /***************************************************************************//** 2 | ** \mainpage ZMat Library 3 | ** 4 | ** \author Qianqian Fang 5 | ** \copyright Qianqian Fang, 2019-2020 6 | ** 7 | ** \section sref URL: http://github.com/fangq/zmat 8 | ** 9 | ** \section slicense License 10 | ** GPL v3, see LICENSE.txt for details 11 | *******************************************************************************/ 12 | 13 | /***************************************************************************//** 14 | \file zmatlib.h 15 | 16 | @brief Header file for a portable data compression library of zlib, lz and easylzma 17 | *******************************************************************************/ 18 | 19 | #ifndef ZMAT_LIB_H 20 | #define ZMAT_LIB_H 21 | 22 | #ifndef NO_LZMA 23 | #include "easylzma/compress.h" 24 | #include "easylzma/decompress.h" 25 | #endif 26 | 27 | #ifndef NO_LZ4 28 | #include "lz4/lz4.h" 29 | #include "lz4/lz4hc.h" 30 | #endif 31 | 32 | #ifdef __cplusplus 33 | extern "C" 34 | { 35 | #endif 36 | 37 | enum TZipMethod {zmZlib, zmGzip, zmBase64, zmLzip, zmLzma, zmLz4, zmLz4hc}; 38 | 39 | int zmat_run(const size_t inputsize, unsigned char *inputstr, size_t *outputsize, unsigned char **outputbuf, const int zipid, int *ret, const int iscompress); 40 | int zmat_encode(const size_t inputsize, unsigned char *inputstr, size_t *outputsize, unsigned char **outputbuf, const int zipid, int *ret); 41 | int zmat_decode(const size_t inputsize, unsigned char *inputstr, size_t *outputsize, unsigned char **outputbuf, const int zipid, int *ret); 42 | 43 | int zmat_keylookup(char *origkey, const char *table[]); 44 | char *zmat_error(int id); 45 | 46 | unsigned char * base64_encode(const unsigned char *src, size_t len, 47 | size_t *out_len); 48 | unsigned char * base64_decode(const unsigned char *src, size_t len, 49 | size_t *out_len); 50 | #ifndef NO_LZMA 51 | /* compress a chunk of memory and return a dynamically allocated buffer 52 | * if successful. return value is an easylzma error code */ 53 | int simpleCompress(elzma_file_format format, 54 | const unsigned char * inData, 55 | size_t inLen, 56 | unsigned char ** outData, 57 | size_t * outLen); 58 | 59 | /* decompress a chunk of memory and return a dynamically allocated buffer 60 | * if successful. return value is an easylzma error code */ 61 | int simpleDecompress(elzma_file_format format, 62 | const unsigned char * inData, 63 | size_t inLen, 64 | unsigned char ** outData, 65 | size_t * outLen); 66 | #endif 67 | 68 | #ifdef __cplusplus 69 | } 70 | #endif 71 | 72 | #endif 73 | -------------------------------------------------------------------------------- /utils/cwdiffusion.m: -------------------------------------------------------------------------------- 1 | function [Phi r]= cwdiffusion(mua, musp, Reff, srcpos,detpos) 2 | % 3 | % [Phi r] = cwdiffusion(mua, musp, Reff, srcpos,detpos) 4 | % 5 | % semi-infinite medium analytical solution to diffusion model 6 | % 7 | % author: Qianqian Fang (q.fang neu.edu) 8 | % 9 | % input: 10 | % mua: the absorption coefficients in 1/mm 11 | % musp: the reduced scattering coefficients in 1/mm 12 | % Reff: the effective reflection coeff. 13 | % srcpos:array for the source positions (x,y,z) 14 | % detpos:array for the detector positions (x,y,z) 15 | % 16 | % output: 17 | % Phi: the output fluence for all source/detector pairs 18 | % r: (optional) source detector separations 19 | % 20 | % this file is part of Monte Carlo eXtreme (MCX) 21 | % License: GPLv3, see http://mcx.sf.net for details 22 | % see Boas2002, Haskell1994 23 | % 24 | 25 | D = 1/(3*(mua+musp)); 26 | zb = (1+Reff)/(1-Reff)*2*D; 27 | 28 | z0 = 1/(musp+mua); 29 | r=getdistance([srcpos(:,1:2) srcpos(:,3)+z0],detpos); 30 | r2=getdistance([srcpos(:,1:2) srcpos(:,3)-z0-2*zb],detpos); 31 | 32 | b=sqrt(3*mua*musp); 33 | 34 | % unit of phi: 1/(mm^2) 35 | Phi =1./(4*pi*D).*(exp(-b*r)./r - exp(-b*r2)./r2); 36 | -------------------------------------------------------------------------------- /utils/getdistance.m: -------------------------------------------------------------------------------- 1 | function separation=getdistance(srcpos,detpos) 2 | % separation=getdistance(srcpos,detpos) 3 | % 4 | % compute the source/detector separation from the positions 5 | % 6 | % author: Qianqian Fang (q.fang neu.edu) 7 | % 8 | % input: 9 | % srcpos:array for the source positions (x,y,z) 10 | % detpos:array for the detector positions (x,y,z) 11 | % 12 | % output: 13 | % separation: the distance matrix between all combinations 14 | % of sources and detectors. separation has the number 15 | % of source rows, and number of detector of columns. 16 | % 17 | % this file is part of Monte Carlo eXtreme (MCX) 18 | % License: GPLv3, see http://mcx.sf.net for details 19 | 20 | srcnum=length(srcpos(:,1)); 21 | detnum=length(detpos(:,1)); 22 | for s=1:srcnum 23 | for r=1:detnum 24 | separation(r,s)=norm(srcpos(s,:)-detpos(r,:),'fro'); 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /utils/islicer.m: -------------------------------------------------------------------------------- 1 | function h = islicer(vol,T, varargin) 2 | % 3 | % h = islicer(vol); 4 | % or 5 | % h = islicer(vol,T); 6 | % 7 | % author: Anders Brun, anders@cb.uu.se (2009) 8 | % url: https://www.mathworks.com/matlabcentral/fileexchange/25923-myslicer-make-mouse-interactive-slices-of-a-3-d-volume 9 | % original version: v1.1 (accessed on 07/25/2017) 10 | % 11 | % input: 12 | % vol: the 3-D or 4-D data being loaded 13 | % T: a 4x4 transformation matrix; if missing, T is a 4x4 identity 14 | % matrix 15 | % 16 | % output: 17 | % h: the handles to the 3 surfaces plotted along the x/y/z 18 | % planes 19 | % 20 | % this file is part of Monte Carlo eXtreme (MCX) 21 | % License: GPLv3, see http://mcx.sf.net for details 22 | % 23 | 24 | if nargin < 2 25 | T = eye(4); 26 | end 27 | 28 | h1 = slice3i(vol,T,1,round(size(vol,1)/2)); 29 | h2 = slice3i(vol,T,2,round(size(vol,2)/2)); 30 | h3 = slice3i(vol,T,3,round(size(vol,3)/2)); 31 | 32 | if(nargout>=1) 33 | h = [h1,h2,h3]; 34 | end 35 | 36 | set([h1,h2,h3],'CDataMapping','scaled', varargin{:}); 37 | 38 | %colormap(jet(64)); 39 | 40 | view(3); 41 | axis equal; 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /utils/loadmc2.m: -------------------------------------------------------------------------------- 1 | function [data, dref]=loadmc2(fname,dim,format) 2 | % 3 | % data=loadmc2(fname,dim,format) 4 | % or 5 | % [data dref]=loadmc2(fname,dim,format) 6 | % 7 | % author: Qianqian Fang (q.fang neu.edu) 8 | % 9 | % input: 10 | % fname: the file name to the output .mc2 file 11 | % dim: an array to specify the output data dimension 12 | % normally, dim=[nx,ny,nz,nt] 13 | % format:a string to indicate the format used to save 14 | % the .mc2 file; if omitted, it is set to 'float' 15 | % 16 | % output: 17 | % data: the output MCX solution data array, in the 18 | % same dimension specified by dim 19 | % dref(optional): diffuse reflectance at the surface of the domain. 20 | % if this output is not given while diffuse reflectance 21 | % is recorded, dref is shown as the negative values in 22 | % the data output. 23 | % 24 | % this file is part of Monte Carlo eXtreme (MCX) 25 | % License: GPLv3, see http://mcx.sf.net for details 26 | % 27 | 28 | if(nargin==2) 29 | format='float'; 30 | end 31 | 32 | fid=fopen(fname,'rb'); 33 | data=fread(fid,inf,format); 34 | fclose(fid); 35 | 36 | data=reshape(data,dim); 37 | 38 | if(nargout>1) 39 | dref=-data; 40 | dref(dref<0)=0; 41 | data(data<0)=0; 42 | end 43 | -------------------------------------------------------------------------------- /utils/mcxdcsg1.m: -------------------------------------------------------------------------------- 1 | function [tau,g1]=mcxdcsg1(detps,tau, disp_model, DV, lambda, format, varargin) 2 | % 3 | % [tau,g1]=mcxdcsg1(detps,tau, disp_model, DV, lambda, format) 4 | % 5 | % Compute simulated electric-field auto-correlation function using 6 | % simulated photon pathlengths and scattering momentum transfer 7 | % 8 | % author: Stefan Carp (carp nmr.mgh.harvard.edu) 9 | % 10 | % input: 11 | % detps: the file name of the output .mch file or the 2nd output from mcxlab 12 | % tau: correlation times at which to compute g1 13 | % (default: 1e-7 to 1e-1 seconds, log equidistant) 14 | % disp_model: displacement model ('brownian', 'random_flow', ) 15 | % (default: brownian, see further explanation below) 16 | % disp_var: value of displacement variable using mm as unit of 17 | % length and s as unit of time 18 | % (default: 1e-7 mm^2/s, see further explanation below) 19 | % lambda: wavelenght of light used in nm 20 | % (default: 785) 21 | % format: the format used to save the .mch file 22 | % (default: 'float') 23 | % 24 | % output: 25 | % 26 | % tau: correlation times at which g1 was computed provided for 27 | % convenience (copied from input if set, otherwise 28 | % outputs default) 29 | % g1: field auto-correlation curves, one for each detector 30 | % 31 | % The displacement model indicates the formula used to compute the root 32 | % mean square displacement of scattering particles during a given delay 33 | % 34 | % brownian: RMS= 6 * DV * tau; 35 | % DV(displacement variable)=Db (brownian diffusion coeff) 36 | % random_flow: RMS= DV^2 * tau^2; 37 | % DV = V (first moment of velocity distribution) 38 | % : any string other than 'brownian' or 'random_flow' will 39 | % be evaluate as is using Matlab evalf, make sure it uses 40 | % 'DV' as the flow related independent variable, tau is 41 | % indexed as tau(J). Any additional parameters can be 42 | % sent via "varargin" 43 | % 44 | % This file is part of Mesh-Based Monte Carlo 45 | % License: GPLv3, see http://mcx.space for details 46 | % 47 | 48 | if nargin<6, format='float'; end 49 | if nargin<5, lambda=785; end 50 | if nargin<4, DV=1e-7; end 51 | if nargin<3, disp_model='brownian'; end 52 | if nargin<2, tau=logspace(-7,-1,200); end 53 | 54 | if(ischar(detps)) 55 | [mch_data,mch_header]=loadmch(detps,format); 56 | [fpath,fname,fext]=fileparts(detps); 57 | 58 | cfg=loadjson([fpath filesep fname '.json']); 59 | prop=cell2mat(cfg.Domain.Media) 60 | mua=cell2mat({prop.mua}); 61 | mua=mua(2:end); 62 | n=cell2mat({prop.n}); 63 | n=n(2:end); 64 | medianum=length(mua)-1; 65 | detps=struct('detid',mch_data(1,:)'); 66 | detps.ppath=mch_data(3:2+medianum,:)'; 67 | if(size(mch_data,1)>=2*medianum+2) 68 | detps.mom=mch_data(medianum+3:2*medianum+2,:)'; 69 | end 70 | else 71 | mua=detps.prop(2:end,1)'; 72 | n=detps.prop(2:end,4)'; 73 | end 74 | 75 | if(~isfield(detps,'mom')) 76 | error('No momentum transfer data are found, please rerun your simulation and set cfg.ismomentum=1.'); 77 | end 78 | 79 | if strcmp(disp_model,'brownian'), 80 | disp_str='rmsdisp=6*DV.*tau(J);'; 81 | elseif strcmp(disp_model,'random_flow'), 82 | disp_str='rmsdisp=DV.^2.*tau(J).^2;'; 83 | else 84 | disp_str=['rmsdisp=' disp_model ';']; 85 | end 86 | 87 | k0=2*pi*n/(lambda*1e-6); 88 | 89 | detlist=sort(unique(detps.detid)); 90 | g1=zeros(max(detlist),length(tau)); 91 | 92 | for detid=1:length(detlist) 93 | I=detlist(detid); 94 | idx= find(detps.detid==I); 95 | fprintf('Processing detector %.0f: %.0f photons\n',I,length(idx)); 96 | 97 | for J=1:length(tau), 98 | eval(disp_str); 99 | g1(I,J)=sum(exp(-(k0.^2.*rmsdisp/3)*detps.mom'-mua*detps.ppath')); 100 | end 101 | g1_norm=sum(exp(-mua*detps.ppath')); 102 | g1(I,:)=g1(I,:)./g1_norm; 103 | end 104 | 105 | 106 | 107 | -------------------------------------------------------------------------------- /utils/mcxdettime.m: -------------------------------------------------------------------------------- 1 | function dett=mcxdettime(detp,prop) 2 | % 3 | % dett=mcxdetweight(detp,prop) 4 | % 5 | % Recalculate the detected photon time using partial path data and 6 | % optical properties (for perturbation Monte Carlo or detector readings) 7 | % 8 | % author: Qianqian Fang (q.fang neu.edu) 9 | % Ruoyang Yao (yaor rpi.edu) 10 | % 11 | % input: 12 | % detp: the 2nd output from mcxlab. detp must be a struct 13 | % prop: optical property list, as defined in the cfg.prop field of mcxlab's input 14 | % 15 | % output: 16 | % dett: re-caculated detected photon time based on the partial path data and optical property table 17 | % 18 | % this file is copied from Mesh-based Monte Carlo (MMC) 19 | % 20 | % License: GPLv3, see http://mcx.space/ for details 21 | % 22 | 23 | R_C0 = 3.335640951981520e-12; % inverse of light speed in vacuum 24 | 25 | medianum=size(prop,1); 26 | if(medianum<=1) 27 | error('empty property list'); 28 | end 29 | 30 | if(isstruct(detp)) 31 | dett=zeros(size(detp.ppath,1),1); 32 | for i=1:medianum-1 33 | dett=dett+prop(i+1,4)*detp.ppath(:,i)*R_C0; 34 | end 35 | else 36 | error('the first input must be a struct with a subfield named "ppath"'); 37 | end 38 | -------------------------------------------------------------------------------- /utils/mcxdettpsf.m: -------------------------------------------------------------------------------- 1 | function tpsf = mcxdettpsf(detp,detnum,prop,time) 2 | % 3 | % tpsf=mcxdettpsf(detp,detnum,prop,time) 4 | % 5 | % Calculate the temporal point spread function curve of a specified detector 6 | % given the partial path data, optical properties, and distribution of time bins 7 | % 8 | % author: Qianqian Fang (q.fang neu.edu) 9 | % Ruoyang Yao (yaor rpi.edu) 10 | % 11 | % input: 12 | % detp: the 2nd output from mcxlab. detp must be a struct with detid and ppath subfields 13 | % detnum: specified detector number 14 | % prop: optical property list, as defined in the cfg.prop field of mcxlab's input 15 | % time: distribution of time bins, a 1*3 vector [tstart tend tstep] 16 | % could be defined different from in the cfg of mcxlab's input 17 | % output: 18 | % tpsf: caculated temporal point spread function curve of the specified detector 19 | % 20 | % this file is copied from Mesh-based Monte Carlo (MMC) 21 | % 22 | % License: GPLv3, see http://mcx.space/ for details 23 | % 24 | 25 | % select the photon data of the specified detector 26 | detp.ppath=detp.ppath(detp.detid==detnum,:); 27 | detp.detid=detp.detid(detp.detid==detnum); 28 | 29 | % calculate the detected photon weight and arrival time 30 | replayweight=mcxdetweight(detp,prop); 31 | replaytime=mcxdettime(detp,prop); 32 | 33 | % define temporal point spread function vector 34 | nTG = round((time(2)-time(1))/time(3)); % maximum time gate number 35 | tpsf = zeros(nTG,1); 36 | 37 | % calculate the time bin, make sure not to exceed the boundary 38 | ntg = ceil((replaytime-time(1))/time(3)); 39 | ntg(ntg<1)=1; 40 | ntg(ntg>nTG)=nTG; 41 | 42 | % add each photon weight to corresponding time bin 43 | for i=1:length(replayweight) 44 | tpsf(ntg(i)) = tpsf(ntg(i))+replayweight(i); 45 | end 46 | 47 | end 48 | -------------------------------------------------------------------------------- /utils/mcxdetweight.m: -------------------------------------------------------------------------------- 1 | function detw=mcxdetweight(detp,prop) 2 | % 3 | % detw=mcxdetweight(detp,prop) 4 | % 5 | % Recalculate the detected photon weight using partial path data and 6 | % optical properties (for perturbation Monte Carlo or detector readings) 7 | % 8 | % author: Qianqian Fang (q.fang neu.edu) 9 | % 10 | % input: 11 | % detp: the 2nd output from mcxlab. detp must a struct 12 | % prop: optical property list, as defined in the cfg.prop field of mcxlab's input 13 | % 14 | % output: 15 | % detw: re-caculated detected photon weight based on the partial path data and optical property table 16 | % 17 | % this file is copied from Mesh-based Monte Carlo (MMC) 18 | % 19 | % License: GPLv3, see http://mcx.space/ for details 20 | % 21 | 22 | medianum=size(prop,1); 23 | if(medianum<=1) 24 | error('empty property list'); 25 | end 26 | 27 | if(isstruct(detp)) 28 | if(~isfield(detp,'w0')) 29 | detw=ones(size(detp.ppath,1),1); 30 | else 31 | detw=detp.w0; 32 | end 33 | for i=1:medianum-1 34 | detw=detw.*exp(-prop(i+1,1)*detp.ppath(:,i)); 35 | end 36 | else 37 | error('the first input must be a struct with a subfield named "ppath"'); 38 | end 39 | -------------------------------------------------------------------------------- /utils/mcxfluence2energy.m: -------------------------------------------------------------------------------- 1 | function output=mcxfluence2energy(flux,vol,prop,tstep) 2 | % 3 | % output=mcxfluence2energy(flux,cfg) 4 | % or 5 | % output=mcxfluence2energy(flux,vol,prop,tstep) 6 | % 7 | % Calculate energy deposition (1/mm^3) use fluence rate (1/mm^2/s) or vice versa 8 | % 9 | % author: Qianqian Fang (q.fang neu.edu) 10 | % 11 | % input: 12 | % flux: the 1st output from mcxlab. flux can be either a struct or an array (flux.data) 13 | % cfg: the input used in mcxlab 14 | % or, you can use 15 | % vol: if cfg is not given, user must provide the volume, i.e. cfg.vol, and 16 | % prop: the property list, i.e. cfg.prop, as well as 17 | % tstep: the time-step of the 18 | % output: 19 | % output: if cfg.output is 'flux', the output is the energy deposition (1/mm^3) 20 | % if cfg.output is 'energy', the output is the fluence rate (1/mm^2) 21 | % 22 | % this file is part of Monte Carlo eXtreme (MCX) 23 | % 24 | % License: GPLv3, see http://mcx.space/ for details 25 | % 26 | 27 | data=flux; 28 | 29 | if(nargin>=1 && isstruct(flux) && isfield(flux,'data')) 30 | data=flux.data; 31 | end 32 | 33 | if(nargin==2 && isstruct(vol) && isfield(vol,'vol') && isfield(vol,'prop')) 34 | cfg=vol; 35 | vol=cfg.vol; 36 | prop=cfg.prop; 37 | tstep=cfg.tstep; 38 | if(isfield(cfg,'outputtype') && strcmp(cfg.outputtype,'fluence')) 39 | data=data./tstep; 40 | end 41 | else 42 | error('must provide cfg, or vol/prop as inputs'); 43 | end 44 | 45 | mua=prop(:,1); 46 | mua=repmat(mua(vol+1),1,1,1,size(flux.data,4)); 47 | if(exist('cfg','var') && isfield(cfg,'outputtype') && strcmp(cfg.outputtype,'energy')) 48 | data(mua==0)=0; 49 | mua(mua==0)=1; 50 | output=data./(tstep*mua); 51 | else % otherwise, assume input is fluence rate 52 | output=data*(tstep).*mua; 53 | end -------------------------------------------------------------------------------- /utils/mcxloadfile.m: -------------------------------------------------------------------------------- 1 | function [data, header]=mcxloadfile(fname,varargin) 2 | % 3 | % [data, header]=mcxloadfile(fname) 4 | % or 5 | % [data, header]=mcxplotvol(fname,dim,format) 6 | % 7 | % author: Qianqian Fang (q.fang neu.edu) 8 | % 9 | % input: 10 | % fname: the file name to the output .mc2/.nii/binary volume file 11 | % dim: an array to specify the output data dimension 12 | % normally, dim=[nx,ny,nz,nt] 13 | % format:a string to indicate the format used to save 14 | % the .mc2 file; if omitted, it is set to 'float' 15 | % 16 | % output: 17 | % data: the 3-D or 4-D data being loaded 18 | % header: a structure recording the metadata of the file 19 | % 20 | % this file is part of Monte Carlo eXtreme (MCX) 21 | % License: GPLv3, see http://mcx.sf.net for details 22 | % 23 | 24 | [pathstr,name,ext] = fileparts(fname); 25 | 26 | if(strcmpi(ext,'.nii')) 27 | nii=mcxloadnii(fname,varargin{:}); 28 | data=nii.img; 29 | header=nii.hdr; 30 | elseif(strcmpi(ext,'.mc2')) 31 | data=loadmc2(fname,varargin{:}); 32 | data=log10(data); 33 | header.dim=varargin{1}; 34 | header.format=class(data); 35 | header.scale='log10'; 36 | elseif(strcmpi(ext,'.mch')) 37 | [data, header]=loadmch(fname),varargin{:}; 38 | else 39 | data=loadmc2(fname,varargin{:}); 40 | end 41 | -------------------------------------------------------------------------------- /utils/mcxmeanpath.m: -------------------------------------------------------------------------------- 1 | function avgpath=mcxmeanpath(detp,prop) 2 | % 3 | % avgpath=mcxmeanpath(detp,prop) 4 | % 5 | % Calculate the average pathlengths for each tissue type for a given source-detector pair 6 | % 7 | % author: Qianqian Fang (q.fang neu.edu) 8 | % 9 | % input: 10 | % detp: the 2nd output from mcxlab. detp can be either a struct or an array (detp.data) 11 | % prop: optical property list, as defined in the cfg.prop field of mcxlab's input 12 | % 13 | % output: 14 | % avepath: the average pathlength for each tissue type 15 | % 16 | % this file is copied from Mesh-based Monte Carlo (MMC) 17 | % 18 | % License: GPLv3, see http://mcx.space/ for details 19 | % 20 | 21 | detw=mcxdetweight(detp,prop); 22 | avgpath=sum(detp.ppath.*repmat(detw(:),1,size(detp.ppath,2))) / sum(detw(:)); 23 | -------------------------------------------------------------------------------- /utils/mcxmeanscat.m: -------------------------------------------------------------------------------- 1 | function avgnscat=mcxmeanscat(detp,prop) 2 | % 3 | % avgnscat=mcxmeanscat(detp,prop) 4 | % 5 | % Calculate the average scattering event counts for each tissue type for a given source-detector pair 6 | % 7 | % author: Qianqian Fang (q.fang neu.edu) 8 | % 9 | % input: 10 | % detp: the 2nd output from mcxlab. detp can be either a struct or an array (detp.data) 11 | % prop: optical property list, as defined in the cfg.prop field of mcxlab's input 12 | % 13 | % output: 14 | % avgnscat: the average scattering event count for each tissue type 15 | % 16 | % this file is copied from Mesh-based Monte Carlo (MMC) 17 | % 18 | % License: GPLv3, see http://mcx.space/ for details 19 | % 20 | 21 | detw=mcxdetweight(detp,prop); 22 | avgnscat=sum(double(detp.nscat).*repmat(detw(:),1,size(detp.nscat,2))) / sum(detw(:)); 23 | -------------------------------------------------------------------------------- /utils/mcxplotphotons.m: -------------------------------------------------------------------------------- 1 | function varargout=mcxplotphotons(traj,varargin) 2 | % 3 | % mcxplotphotons(traj) 4 | % or 5 | % mcxplotphotons(traj, 'color','r','marker','o') 6 | % [sorted, linehandle]=mcxplotphotons(traj) 7 | % 8 | % Plot photon trajectories from MCXLAB's output 9 | % 10 | % author: Qianqian Fang (q.fang neu.edu) 11 | % 12 | % input: 13 | % traj: the 5th output of mcxlab, storing the photon trajectory info 14 | % traj.id: the photon index being recorded 15 | % traj.pos: the 3D position of the photon; for each photon, the 16 | % positions are stored in serial order 17 | % traj.data: the combined output, in the form of 18 | % [id,pos,weight,reserved]' 19 | % 20 | % output: 21 | % sorted: a structure to store the sorted trajectory info 22 | % sorted.id: the sorted vector of photon id, staring from 0 23 | % sorted.pos: the sorted position vector of each photon, only 24 | % recording the scattering sites. 25 | % 26 | % this file is part of Monte Carlo eXtreme (MCX) 27 | % License: GPLv3, see http://mcx.sf.net for details 28 | % 29 | 30 | if(~isstruct(traj) && size(traj,2)==6) 31 | traj=struct('id',typecast(single(traj(:,1)),'uint32'),'pos',traj(:,2:4),'weight',traj(:,5)); 32 | end 33 | 34 | [newid, idx]=sort(traj.id); 35 | newpos=traj.pos(idx,:); 36 | hg=plot3(newpos(:,1),newpos(:,2),newpos(:,3),'.-',varargin{:}); 37 | 38 | output={struct('id',newid, 'pos',newpos), hg}; 39 | [varargout{1:nargout}]=output{1:nargout}; 40 | -------------------------------------------------------------------------------- /utils/mcxplotvol.m: -------------------------------------------------------------------------------- 1 | function [dat, filename, handles, hfig]=mcxplotvol(varargin) 2 | % 3 | % [dat, filename, handles]=mcxplotvol() 4 | % or 5 | % [dat, filename, handles]=mcxplotvol(fname) 6 | % [dat, filename, handles]=mcxplotvol(data) 7 | % [dat, filename, handles]=mcxplotvol(fname,dim,format) 8 | % 9 | % author: Qianqian Fang (q.fang neu.edu) 10 | % 11 | % input: 12 | % fname: the file name to the output .mc2/.nii/binary volume file 13 | % data: if the first input is an array, it is treated as the data 14 | % to be plotted 15 | % dim: an array to specify the output data dimension 16 | % normally, dim=[nx,ny,nz,nt] 17 | % format:a string to indicate the format used to save 18 | % the .mc2 file; if omitted, it is set to 'float' 19 | % 20 | % output: 21 | % dat:(optional) the 3-D or 4-D data being plotted 22 | % filename: (optional) the name of the file being plotted 23 | % handles:(optional) the handles to the slice surface object 24 | % 25 | % this file is part of Monte Carlo eXtreme (MCX) 26 | % License: GPLv3, see http://mcx.sf.net for details 27 | % 28 | 29 | if(nargin>=1) 30 | if(ischar(varargin{1})) 31 | fname=varargin{1}; 32 | data=mcxloadfile(fname, varargin{2:end}); 33 | else 34 | fname=''; 35 | data=varargin{1}; 36 | end 37 | else 38 | [fname pathname]=uigetfile( {'*.*'},'Pick a file'); 39 | fname=fullfile(pathname, fname); 40 | if(isempty(fname)) 41 | return; 42 | end 43 | [pathstr,name,ext] = fileparts(fname); 44 | if(~strcmpi(ext,'.nii') && length(varargin)<=1) 45 | prompt = {'Enter x-dimension:','Enter y-dimension:','Enter z-dimension:','Enter frame count:','Format:'}; 46 | dlg_title = 'Input'; 47 | num_lines = 1; 48 | defaultans = {'','','','1','float32'}; 49 | dim= inputdlg(prompt,dlg_title,num_lines,defaultans); 50 | dataformat=dim{5}; 51 | dim=cellfun(@(x) str2num(x), dim(1:4)); 52 | data=mcxloadfile(fname, dim(:)',dataformat); 53 | else 54 | data=mcxloadfile(fname, varargin{2:end}); 55 | end 56 | end 57 | 58 | %if(ndims(squeeze(data))==4) 59 | % data=sum(squeeze(data),4); 60 | %end 61 | 62 | if(nargout>=2) 63 | filename=fname; 64 | elseif(nargout>=1) 65 | dat=data; 66 | end 67 | 68 | hfig=figure; 69 | 70 | guidata=struct('filename',fname,'data',data,'frame',1); 71 | guidata.handles=islicer(data(:,:,:,guidata.frame)); 72 | 73 | set(hfig,'WindowKeyPressFcn',@changeframe) 74 | set(hfig,'name',['MCX Viewer (mcxplotvol) ' fname]); 75 | set(hfig,'NumberTitle','off'); 76 | set(gca,'UserData',guidata); 77 | 78 | 79 | helpinfo=sprintf('Drag mouse left-btn to move slices;\r Click and drag mouse mid-btn to rotate; \rDrag right-key up-down to change color level;\rUp-arrow key :next time-gate; \rDown-arrow key:prev time-gate'); 80 | 81 | helpbtn=uicontrol('Parent',hfig,'Style','pushbutton','String','Help','Units','points','Position',[10 10 50 20],'Visible','on','Callback',@showhelp); 82 | 83 | set(helpbtn,'TooltipString',helpinfo); 84 | 85 | 86 | xlabel(sprintf('x (frame=%d of %d)',1,size(data,4))); 87 | ylabel('y'); 88 | zlabel('z'); 89 | 90 | colorbar; 91 | 92 | 93 | function changeframe(src,event) 94 | 95 | guidata=get(gca,'UserData'); 96 | 97 | if(isempty(guidata) || ~isfield(guidata,'frame')) 98 | return; 99 | end 100 | 101 | newframe=-1; 102 | switch(event.Key) 103 | case 'uparrow' 104 | newframe=min(guidata.frame+1,size(guidata.data,4)); 105 | case 'downarrow' 106 | newframe=max(guidata.frame-1,1); 107 | end 108 | 109 | if(newframe>0 && newframe~=guidata.frame) 110 | delete(guidata.handles); 111 | guidata.handles=islicer(guidata.data(:,:,:,newframe)); 112 | xlabel(sprintf('x (frame=%d of %d)',newframe,size(guidata.data,4))); 113 | guidata.frame=newframe; 114 | set(gca,'UserData',guidata); 115 | end 116 | 117 | function showhelp(source,event) 118 | msgbox(get(source,'TooltipString'),'Help info'); 119 | -------------------------------------------------------------------------------- /utils/normalizemcx.m: -------------------------------------------------------------------------------- 1 | function phi=normalizemcx(data,mua,Vvox,dt,energyabsorbed,energytotal) 2 | % 3 | % phi=normalizemcx(data,mua,Vvox,dt,energyabsorbed,energytotal) 4 | % 5 | % Normalization of fluence distributions from Monte-Carlo simulations 6 | % 7 | % author: Qianqian Fang (q.fang neu.edu) 8 | % 9 | % input: 10 | % data: a 3D or 4D array for the raw output from MCX (probability) 11 | % mua: absorption coeff, with the same dimensions as data 12 | % Vvox: volume of a voxel (1/mm^3) 13 | % dt: time-gate width of MC simulation (s) 14 | % energyabsorbed: total energy being absorbed in the simulation 15 | % energytotal: total photon energy launched in the simulation 16 | % 17 | % output: 18 | % phi: the fluence under a unitary source 19 | % 20 | % For tMCimg output, set energyabsorbed to -1 and energytotal to 21 | % the total photon numbers 22 | % 23 | % This subroutine of part of Monte-Carlo eXtreme (mcx) package 24 | % 25 | 26 | if(energyabsorbed<0) 27 | energyabsorbed=energytotal+sum(data(find(data<0))); 28 | data(find(data<0))=0; 29 | end 30 | alpha=energyabsorbed/energytotal/(Vvox*sum(data(:).*mua(:)))/(dt); 31 | phi=alpha*data; 32 | -------------------------------------------------------------------------------- /utils/python/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | author: Shih-Cheng Tu 3 | email: mrtoastcheng@gmail.com 4 | 5 | """ 6 | from struct import unpack 7 | import numpy as np 8 | 9 | 10 | def load_mch(path): 11 | """ 12 | input: 13 | path: 14 | the file path of the .mch file. 15 | 16 | output: 17 | mch_data: 18 | the output detected photon data array 19 | data has at least M*2+2 columns (M=header.maxmedia), the first column is the 20 | ID of the detector; columns 2 to M+1 store the number of 21 | scattering events for every tissue region; the following M 22 | columns are the partial path lengths (in mm) for each medium type; 23 | the last column is the initial weight at launch time of each detecetd 24 | photon; when the momentum transfer is recorded, M columns of 25 | momentum tranfer for each medium is inserted after the partial path; 26 | when the exit photon position/dir are recorded, 6 additional columns 27 | are inserted before the last column, first 3 columns represent the 28 | exiting position (x/y/z); the next 3 columns are the dir vector (vx/vy/vz). 29 | in other words, data is stored in the follow format 30 | [detid(1) nscat(M) ppath(M) mom(M) p(3) v(3) w0(1)] 31 | 32 | header: 33 | file header info, a dictionary that contains 34 | version,medianum,detnum,recordnum,totalphoton,detectedphoton, 35 | savedphoton,lengthunit,seed byte,normalize,respin] 36 | 37 | photonseed: 38 | (optional) if the mch file contains a seed section, this 39 | returns the seed data for each detected photon. Each row of 40 | photonseed is a byte array, which can be used to initialize a 41 | seeded simulation. Note that the seed is RNG specific. You must use 42 | the an identical RNG to utilize these seeds for a new simulation. 43 | 44 | """ 45 | f = open(path, 'rb') 46 | mch_data = [] 47 | header = [] 48 | photon_seed = [] 49 | try: 50 | while True: 51 | # the first 4 byte in a mch file is always 'MCXH' 52 | buffer_ = f.read(4) 53 | if not buffer_: 54 | break 55 | elif buffer_ != b'MCXH': 56 | raise Exception("It might not be a mch file!") 57 | 58 | version = unpack('i', f.read(4))[0] 59 | maxmedia = unpack('i', f.read(4))[0] 60 | detnum = unpack('i', f.read(4))[0] 61 | colcount = unpack('i', f.read(4))[0] 62 | total_photon = unpack('i', f.read(4))[0] 63 | detected = unpack('i', f.read(4))[0] 64 | saved_photon = unpack('i', f.read(4))[0] 65 | unitmm = unpack('f', f.read(4))[0] 66 | seed_byte = unpack('i', f.read(4))[0] 67 | normalize = unpack('f', f.read(4))[0] 68 | respin = unpack('i', f.read(4))[0] 69 | junk = unpack('4i', f.read(4*4)) 70 | 71 | assert version == 1, "version higher than 1 is not supported" 72 | 73 | 74 | # data = unpack('%df' % (colcount), f.read(4*colcount)) 75 | data = unpack('%df' % (colcount*saved_photon), f.read(4*colcount*saved_photon)) 76 | data = np.asarray(data).reshape(saved_photon, colcount) 77 | # number of vortex -> actual length 78 | data[:, 2:1+maxmedia] = data[:, 2:1+maxmedia] * unitmm 79 | mch_data.append(data) 80 | 81 | # if "save photon seed" is True 82 | if seed_byte > 0: 83 | 84 | seeds = unpack('%dB' % (saved_photon*seed_byte), f.read(saved_photon*seed_byte)) 85 | photon_seed.append(np.asarray(seeds).reshape((seed_byte,saved_photon), order='F')) 86 | 87 | if respin > 1: 88 | total_photon *= respin 89 | 90 | header = {"version": version, 91 | "maxmedia": maxmedia, 92 | "detnum": detnum, 93 | "colcount": colcount, 94 | "total_photon": total_photon, 95 | "detected": detected, 96 | "saved_photon": saved_photon, 97 | "unitmm": unitmm, 98 | "seed_byte": seed_byte, 99 | "normalize": normalize, 100 | "respin": respin 101 | } 102 | 103 | finally: 104 | f.close() 105 | 106 | mch_data = np.asarray(mch_data).squeeze() 107 | 108 | if seed_byte > 0: 109 | photon_seed = np.asarray(photon_seed).transpose((0,2,1)).squeeze() 110 | return mch_data, header, photon_seed 111 | else: 112 | return mch_data, header 113 | 114 | 115 | def load_mc2(path, dimension): 116 | """ 117 | input: 118 | path: 119 | the file path of the .mc2 file. 120 | 121 | dimension: 122 | an array to specify the output data dimension 123 | normally, dim=[nx,ny,nz,nt] 124 | 125 | output: 126 | data: 127 | the output MCX solution data array, in the 128 | same dimension specified by dim 129 | 130 | """ 131 | f = open(path, 'rb') 132 | data = f.read() 133 | data = unpack('%df' % (len(data)/4), data) 134 | data = np.asarray(data).reshape(dimension, order='F') 135 | 136 | return data 137 | -------------------------------------------------------------------------------- /utils/serialcorr.m: -------------------------------------------------------------------------------- 1 | function report=serialcorr(randomseq,maxshift) 2 | % report=serialcorr(randomseq,maxshift) 3 | % 4 | % serial correlation function in a random sequence at a range of separations 5 | % 6 | % author: Qianqian Fang (q.fang neu.edu) 7 | % 8 | % input: 9 | % randomseq: a random sequence (1D array) 10 | % maxshift: the maximum separation to test with 11 | % 12 | % output: 13 | % report: the corr. coeff for the sequence between randomseq 14 | % and randomseq(i:end) where i<=maxshift 15 | % 16 | % this file is part of Monte Carlo eXtreme (MCX) 17 | % License: GPLv3, see http://mcx.sf.net for details 18 | % see Boas2002, Heskell1996 19 | 20 | report=zeros(maxshift,2); 21 | for i=1:maxshift 22 | [r,p]=corrcoef(randomseq(1:end-i),randomseq(i+1:end)); 23 | report(i,:)=[r(1,2),p(1,2)]; 24 | fprintf(1,'test shift %d (r=%20.16f p=%20.16f)\n',i,r(1,2),p(1,2)); 25 | end 26 | -------------------------------------------------------------------------------- /utils/stacked_bar3.m: -------------------------------------------------------------------------------- 1 | function h = stacked_bar3(array) 2 | if any(array(:) < 0) 3 | error('Only positive values supported') 4 | end 5 | 6 | dims = size(array); 7 | if any(dims==0) 8 | error('Empty dimensions are not supported') 9 | end 10 | 11 | switch length(dims) 12 | case 2 13 | ns = 1; 14 | case 3 15 | ns = dims(3); 16 | otherwise 17 | error('Must be a 3D array') 18 | end 19 | nr = dims(1); 20 | nc = dims(2); 21 | 22 | ax = newplot; 23 | co = ax.ColorOrder; 24 | h = gobjects(1,ns); 25 | view(ax,3) 26 | xlim(ax,[.5 nc+.5]) 27 | ylim(ax,[.5 nr+.5]) 28 | 29 | bw = .4; 30 | offmat = [-bw, +bw, 0; ... 31 | -bw, -bw, 0; ... 32 | +bw, -bw, 0; ... 33 | +bw, +bw, 0]; 34 | sidemat = [1, 2, 2, 1; ... 35 | 2, 3, 3, 2; ... 36 | 3, 4, 4, 3; ... 37 | 4, 1, 1, 4] ... 38 | + repmat([0, 0, 4*nr*nc, 4*nr*nc],[4, 1]); 39 | topmat = (1:4) + 4*nr*nc; 40 | 41 | top = zeros(dims(1:2)); 42 | for s = 1:ns 43 | bottom = top; 44 | top = bottom + array(:,:,s); 45 | 46 | verts = zeros(4*nr*nc*2, 3); 47 | faces = ones(5*nr*nc, 4); 48 | for r = 1:nr 49 | for c = 1:nc 50 | vindex = 4*(r-1 + nr*(c-1)); 51 | lindex = 5*(r-1 + nr*(c-1)); 52 | rindex = 4*(r-1 + nr*(c-1)); 53 | verts(vindex + (1:4)', :) = repmat([c,r,bottom(r,c)],[4,1]) + offmat; 54 | verts(vindex + 4*nr*nc + (1:4)', :) = repmat([c,r, top(r,c)],[4,1]) + offmat; 55 | faces(lindex + (1:5)',:) = rindex + [sidemat; topmat]; 56 | end 57 | end 58 | 59 | cix = 1+mod(s-1, size(co,1)); 60 | h(s) = patch('Vertices', verts, ... 61 | 'Faces', faces, ... 62 | 'FaceColor', co(cix,:), ... 63 | 'Parent', ax); 64 | 65 | bottom = top; 66 | end 67 | end -------------------------------------------------------------------------------- /utils/tddiffusion.m: -------------------------------------------------------------------------------- 1 | function Phi = tddiffusion(mua, musp, v, Reff, srcpos,detpos, t) 2 | % 3 | % Phi = tddiffusion(mua, musp, v, Reff, srcpos,detpos, t) 4 | % 5 | % semi-infinite medium analytical solution to diffusion model 6 | % 7 | % author: Qianqian Fang (q.fang neu.edu) 8 | % 9 | % input: 10 | % mua: the absorption coefficients in 1/mm 11 | % musp: the reduced scattering coefficients in 1/mm 12 | % v: the speed of light 13 | % Reff: the effective reflection coeff. 14 | % srcpos:array for the source positions (x,y,z) 15 | % detpos:array for the detector positions (x,y,z) 16 | % t: a list of time in s at which to evaluate the 17 | % analytical diffusion solution 18 | % 19 | % output: 20 | % Phi: the output fluence for all time points 21 | % 22 | % this file is part of Monte Carlo eXtreme (MCX) 23 | % License: GPLv3, see http://mcx.sf.net for details 24 | % see Boas2002 25 | % 26 | 27 | D = 1/(3*(mua+musp)); 28 | zb = (1+Reff)/(1-Reff)*2*D; 29 | 30 | z0 = 1/(musp+mua); 31 | r=getdistance([srcpos(:,1:2) srcpos(:,3)+z0],detpos); 32 | r2=getdistance([srcpos(:,1:2) srcpos(:,3)-z0-2*zb],detpos); 33 | 34 | s=4*D*v*t; 35 | 36 | % unit of phi: 1/(mm^2*s) 37 | Phi =v./((s*pi).^(3/2)).*exp(-mua*v*t).*(exp(-(r.^2)./s) - exp(-(r2.^2)./s)); 38 | --------------------------------------------------------------------------------