xopto.mcml.mc module

class Mc[source]

Bases: xopto.mcbase.mcworker.ClWorkerStandardBufferLutMixin, xopto.mcbase.mcworker.ClWorkerRngMixin, xopto.mcbase.mcworker.ClWorker

Multilayer Monte Carlo light propagation simulator object constructor. The object uses existing OpenCL kernel code in the mcml.h and mcml.c files and adds additional code and kernel configuration options generated by the source, detector, trace, fluence and other objects passed to the constructor. The generated OpenCL code is compiled just before the first call to the kernel/simulation invoked by the run method. All publically accessible properties of the objects (layers, source, detector, trace, fluence, …) can be changed between simulations.

Parameters
  • layers (mclayer.Layers or list[mclayer.Layer]) – A python list of layers. The list must contain at least three layers. The first and the last layer represent the surrounding medium at the top and bottom surfaces of the sample, respectively. The bottom surface of the topmost layer (surrounding medium) is located at at z=0. Positive direction of z axis points in the direction of layer stack.

  • source (mcsource.Source) –

    One of the available photon packet source object:

    • Line - Infinity thin beam.

    • UniformBeam - Collimated uniform beam.

    • GaussianBeam - Collimated beam with a Gaussian crosssection.

    • IsotropicPoint - Isotropic point source.

    • UniformFiber - Uniform intensity fiber source with a given numerical aperture.

    See the xopto.mcml.mcsource module for further sources.

  • detectors (mcdetector.Detectors) –

    A set of detectors for the top and bottom sample surfaces and specular reflections..

    The Detector object will set the following simulator options:

    • MC_USE_DETECTORS

    • MC_USE_TOP_DETECTOR

    • MC_USE_BOTTOM_DETECTOR

    • MC_USE_SPECULAR_DETECTOR

    • MC_USE_FP_LUT (if a lookup table is used)

  • trace (mctrace.Trace) –

    Trace object that can collect the various states of the photon packet including the initial, all intermediate and/or the final.

    The Trace object will set the following simulator options:

    • MC_USE_TRACE

  • fluence (mcfluence.Fluence or mcfluence.FluenceCyl or mcfluence.FluenceRz) –

    Fluence object that collects the energy deposited by the photon packets on a regular 3D grid.

    The Fluence object will set the following simulator options:

    • MC_USE_FLUENCE

  • surface (mcsurface.SurfaceLayouts) –

    Surface geometry that is applied to the top and / or bottom surfaces of the sample.

    The SurfaceLayouts object will set the following simulator options as required:

    • MC_USE_TOP_SURFACE_LAYOUT

    • MC_USE_BOTTOM_SURFACE_LAYOUT

    • MC_USE_SURFACE_LAYOUTS

  • types (mctypes.McDataTypes) –

    A class that defines all the simulator data types. Use one of the following predefined type classes derived from mctypes.McDataTypes:

    • mctypes.McDataTypesSingle

      • 32-bit size type

      • 32-bit default integers,

      • 64-bit detector accumulators,

      • 32-bit single precision floating-point arithmetics,

      • 32-bit photon packet counter (maximum number of photon packets per OpenCL kernel call limited to 4,294,967,295)

    • mctypes.McDataTypesDouble

      • 32-bit size type

      • 32-bit default integers,

      • 64-bit detector accumulators,

      • 64-bit double precision floating-point arithmetics,

      • 32-bit photon packet counter (maximum number of photon packets per OpenCL kernel call limited to 4,294,967,295)

    • mctypes.McDataTypesSingleCnt64

      • 64-bit size type

      • 32-bit default integers,

      • 64-bit detector accumulators,

      • 32-bit single precision floating-point arithmetics,

      • 64-bit photon packet counter (maximum number of photon packets per OpenCL kernel call virtually unlimited)

    • mctypes.McDataTypesDoubleCnt64

      • 64-bit size type

      • 32-bit default integers,

      • 64-bit detector accumulators,

      • 64-bit double precision floating-point arithmetics,

      • 64-bit photon packet counter (maximum number of photon packets per OpenCL kernel call virtually unlimited)

    A custom combination of data types can be defined by the mctypes.McDataTypes.custom() method.

  • options (List[mcoptions.McOption]) –

    A list of compile-time options for the simulator core.

    • mcoptions.McUseNativeMath: mcoptions.McUseNativeMath.on or mcoptions.McUseNativeMath.off Use of native math functions. Native functions are usually faster but less accurate. Default value is mcoptions.McUseNativeMath.off.

    • mcoptions.McMinimumPacketWeight: mcoptions.McMinimumPacketWeight(float) Minimum photon packet weight before going through photon packet termination or lottery. Default value is mcoptions.McMinimumPacketWeight(1e-4).

    • mcoptions.McUseLottery: mcoptions.McUseLottery(float) Terminate photon packet by lottery. Default value is mcoptions.McUseLottery.on.

    • mcoptions.McPacketLotteryChance: mcoptions.McPacketLotteryChance(float) Used if photon packets are terminated by lottery. If the value of a uniform random number exceeds the specified chance, the photon packet is terminated. Default value is mcoptions.McPacketLotteryChance(0.01).

    • mcoptions.McLutMemory: mcoptions.McLutMemory.global_mem or mcoptions.McLutMemory.constant_mem

    • McFpLutMemory: mcoptions.McFpLutMemory.global_mem or mcoptions.McFpLutMemory.constant_mem Set the OpenCL memory type for integer and floating-point data lookup tables that are used by some scattering phase functions, accumulators with custom angular sensitivity and photon packet sources with custom emission characteristics. Note that the default setting is mcoptions.McFpLutMemory.global_mem. Using the constant memory (mcoptions.McFpLutMemory.constant_mem) can be significantly (10x or more) faster, in particular on older GPUs. However, note that the amount of constant memory available on GPUs is typically limited to about 64k. If using lookup table-based scattering phase functions that can be fit into the constant memory, then set this option to mcoptions.McFpLutMemory.constant_mem. This can significantly speed up the MC simulations (~ 10x). To further reduce the amount of constant GPU memory required by the lookup table data arrays, set the scattering phase functions of the first and last layer (the sourrounding medium) to one that is used by the internal (sample) layers.

    • mcoptions.McDebugMode: mcoptions.McDebugMode.on or mcoptions.McDebugMode.off Enables stdout debug information on some devices. Default value is mcoptions.McDebugMode.off.

  • rnginit (np.uint64) – OpenCL random number generator initializer as a 64-bit unsigned integer. Use this initializer if there is a need to put the random, number generator into a known state.

  • cl_devices (str or cl.Device or List[cl.Device] or cl.Context cl.CommnadQueue) – A python list of OpenCL devices that are used for conducting the simulation.See the clGpuDevices and clCpuDevices functions of the clinfo module for details on obtaining a list of OpenCl capable devices. If None is provided, the first available device is used (GPU devices have priority over CPU devices). Use function clinfo.device to get a desired device by simple keywords, e.g. a call clinfo.device([‘amd’, ‘nvidia’, ‘hd’, ‘cpu’], that will search for an AMD GPU, Nvidia GPU, Intel Hd GPU, any CPU and return the first device found. The value of this input argument can also be an instance of OpenCL Context or an instance of OpenCL CommandQueue. Note that in case an instance of CommandQueue is passed, the value of parameter cl_profiling is ignored since it is not possible to enable or disable profiling on an existing OpenCL CommandQueue.

  • cl_build_options (List[str or cloptions.ClBuildOption]) –

    A list of OpenCL build option as specified by the OpenCl manuals at https://www.khronos.org/. An example of commonly used build options:

    cloptions=['-cl-opt-disable', '-Werror',
               '-cl-fast-relaxed-math', '-cl-mad-enable'].
    

    Note that the “-cl-fast-relaxed-math” build option will likely lead to a significant performance improvement but may on some platforms lead to errors in the simulated quantities.

  • cl_profiling (bool) – Enables OpenCL command queue profiling if set to True. Note that in case an instance of CommandQueue is passed as the cl_devices parameter, the value of parameter cl_profiling is ignored since it is not possible to enable or disable profiling on an existing OpenCL CommandQueue.

Examples

See the test/example.py for additional examples.

>>> source = mcsource.GaussianBeam(0.001, 0.22)
>>> l0 = mclayer.Layer(d=0.000, n=1.0, mua=0.0,  mus=0.0,   pf=Hg(0.5))
>>> l1 = mclayer.Layer(d=0.001, n=1.3, mua=1e2,  mus=100e2, pf=Hg(0.8))
>>> l2 = mclayer.Layer(d=0.010, n=1.3, mua=10e2, mus=30e2,  pf=Hg(0.7))
>>> l3 = mclayer.Layer(d=0.000, n=1.0, mua=0.0,  mus=0.0,   pf=Hg(0.5))
>>> layers = mclayer.Layers([l0, l1, l2, l3])
>>> trace = mctrace.Trace(maxlen=1000, options=mctrace.Trace.TRACE_ALL)
>>> mc = Mc(layers, source, trace)
>>> trace_data, _, _ = mc.run(100)
AUTOGEN_PATH = '/home/miran/.xopto/pyxopto/data/mcml/auto'

Directory that will be used to save the rendered OpenCL source code.

MC_CL_TEMPLATE_FILE = '/home/miran/src/pyxopto/tmp/release/pyxopto/xopto/mcml/kernel/mc.template.h'

Location of the OpenCL source template file.

append_r_lut(data: numpy.ndarray, force: bool = False)xopto.mcbase.mcutil.lut.LutEntry[source]

Append a read-only lookup table data array to the list of managed lookup table arrays.

Parameters
  • data (np.ndarray) – Lookup table data to be added to the managed list. The numpy array must be of integer or floating-point type.

  • force (bool) – Add the array to the managed list even if an existing entry for the given data array is found.

Returns

lutetry – Lookup table entry. Use the offset property to locate the first element of the entry in the lookup table buffer.

Return type

LutEntry

property cl_exec: pyopencl.Program

Compiled OpenCL code / executable with kernels.

clear_r_luts()[source]

Clear all the read-only lookup table managers

dbg()[source]
property detectors: xopto.mcml.mcdetector.base.Detectors

Detectors object if available.

devDataTypes()[source]
export_src(filename: Optional[str] = None)str[source]

Export the OpenCL source to a file.

Parameters

filename (str) – The OpenCl source code will be saved to this file. If a file name is not provided, the OpenCL source will be saved to Mc.AUTOGEN_PATH directory with a name “mcml_<random>.cl”

Returns

filename – The filename that was used to save the OpenCL source code.

Return type

str

property fluence: xopto.mcbase.mcfluence.fluence.Fluence

Fluence object if available.

layer(index: int)xopto.mcml.mclayer.layer.Layer[source]

Returns the layer at the specified index. Layers can be also accessed by the layers property and [] operator.

Parameters

index (int) – Index of the layer.

Returns

layer – Layer at the specified index.

Return type

xopto.mcml.mclayer.layer.Layer

layer_index(z: float)int[source]

Returns the index of the layer that contains the specified z coordinate.

Parameters

z (float) – Z coordinate for which to find the layer index.

Returns

index – Layer index that contains the specified z coordinate.

Return type

int

property layers: xopto.mcml.mclayer.layer.Layers

Sample layer stack.

property rmax: float

Maximum simulation radius measured from the photon packet source position (m).

rng_test(n: int, x: Optional[int] = None, a: Optional[int] = None)numpy.ndarray[source]

Generate random numbers on the OpenCL device. The random number generator is the same as used by the Monte Carlo kernel. The precision is inherited from the Simulator. The states / seeds x and a can be optionally generated with the rng property that is an instance of xopto.cl.clrng.Random.

Parameters
  • n (int) – The number of random numbers to generate.

  • x (np.uint64) – Mutable state of the random number generator.

  • a (np.uint32) – Immutable state of the random number generator.

Returns

data – A vector of n random numbers.

Return type

np.ndarray

run(nphotons: int, out: Optional[Tuple[xopto.mcbase.mctrace.Trace, Union[xopto.mcbase.mcfluence.fluence.Fluence, xopto.mcbase.mcfluence.fluencecyl.FluenceCyl, xopto.mcbase.mcfluence.fluencerz.FluenceRz, xopto.mcbase.mcfluence.fluencet.Fluencet, xopto.mcbase.mcfluence.fluencerzt.FluenceRzt, xopto.mcbase.mcfluence.fluencecylt.FluenceCylt], xopto.mcml.mcdetector.base.Detectors]] = None, wgsize: Optional[int] = None, maxthreads: Optional[int] = None, copyseeds: bool = False, exportsrc: Optional[bool] = None, verbose: bool = False)Tuple[xopto.mcbase.mctrace.Trace, Union[xopto.mcbase.mcfluence.fluence.Fluence, xopto.mcbase.mcfluence.fluencecyl.FluenceCyl, xopto.mcbase.mcfluence.fluencerz.FluenceRz, xopto.mcbase.mcfluence.fluencet.Fluencet, xopto.mcbase.mcfluence.fluencerzt.FluenceRzt, xopto.mcbase.mcfluence.fluencecylt.FluenceCylt], xopto.mcml.mcdetector.base.Detectors][source]

Run a simulation with the specified number of photon packets.

Parameters
  • nphotons (int) – Number of photon packets to simulate. Note that the maximum number of photon packets is limited to Mc.types.mc_cnt_max.

  • out (MC_RESULT_TYPE or None) – Existing trace, fluence and/or detector objects that will be updated with the simulation results if not None. Pass objects that were returned after the previous/first call of the run() method. Do NOT pass any of the objects that were used as input arguments of the Mc() constructor!.

  • wgsize (int) – Local work group size. If None (default), the optimal work group size is determined automatically.

  • maxthreads (int) – Total number of threads to use. Limited by the number of available random number generators (150,000).

  • copyseeds (bool) – If True, copy the mutable seeds of the random number generator from the OpenCL kernel to the host. This is only required if the seeds need to be reused or inspected (for debug purposes).

  • exportsrc (str or bool) – Optional location to save the OpenCL source code. The source file is saved only on the first run of the simulator.

  • verbose (bool) – If set to True, additional debug information is displayed.

Returns

  • trace (mctrace.Trace) – Trace object instance with simulation results or None if not used by the simulator.

  • fluence (mcfluence.Fluence or mcfluence.FluenceCyl or mcfluence.FluenceRz) – Fluence object instance with simulation results or None if not used by the simulator.

  • detector (mcdetector.Detectors) – Detectors object instance with simulation results or None if not used by the simulator.

Note

The returned mctrace.Trace, mcfluence.Fluence and mcdetector.Detector objects are not the same instances as were passed to the constructor Mc(). A new set of instances is created for the results of each run of the simulator.

The maximum number of photon packets that can be simulated in a single run is limited by the kernel data type used as the photon packet counter. The maximum value is limited to Mc.types.mc_cnt_max.

property run_report: dict

Timing and performance data of the latest kernel run as a dict with keys “upload”, “download”, “execution”, “threads” and “items”. The timing values with keys “upload”, “download” and “execution” are given in seconds. The number of OpenCL threads with key “threads” and the number of processed items with key “items” are integer values. All values are initialized to None.

sampling_volume(trace: xopto.mcbase.mctrace.Trace, sv: xopto.mcbase.mcsv.SamplingVolume, wgsize: Optional[int] = None, maxthreads: Optional[int] = None, exportsrc: Optional[bool] = None, verbose: bool = False)xopto.mcbase.mcsv.SamplingVolume[source]

Compute the sampling volume from the given simulation trace.

Parameters
  • trace (mctrace.Trace) – Simulation trace object to process.

  • sv (mcsv.SamplingVolume) – Target sampling volume that will be updated with the results.

  • wgsize (int) – Local work group size. If None (default), the optimal work group size is determined automatically.

  • maxthreads (int) – Total number of parallel threads to use. Limited by the number of available random number generators (150,000).

  • exportsrc (str or bool) – Optional location to save the OpenCL source code. The source file is saved only on the first run of the simulator.

  • verbose (bool) – If set to True, additional debug information is displayed.

Returns

sv – Input sampling volume updated with the data from the trace.

Return type

mcsv.SamplingVolume

property source: xopto.mcml.mcsource.base.Source

Photon packet source object.

property surface: xopto.mcml.mcsurface.base.SurfaceLayouts

Sample surface layout.

testMcFpDiv(x, y, native=True)[source]
testMcLog(x, native=True)[source]
testMcRSqrt(x, native=True)[source]
testMcSinCos(x)[source]
testMcSqrt(x, native=True)[source]
property trace: xopto.mcbase.mctrace.Trace

Trace object if available.

property types: xopto.mcbase.mctypes.McDataTypes

Simulator data types.