Package: pytissueoptics
Light propagation with Monte Carlo in PythonThis is an extremely simple object-oriented code in Python that simulates the propagation of light in scattering tissue. It is not justsimple: it isoutrageously simpleandvery slow(see below). However, it isextremely easy to understandand most importantlyvery simple modify. It is a Python implementation of Monte Carlo, as beautifully illustrated by the standard, tested, and lovedMCML from Wang, Jacques and Zheng, itself based onPrahland completely documented, explained, dissected byJacquesandPrahl. Everyone is doing Monte Carlo in tissue, and nothing would be possible without the work of these pionneers.It may be slow, but speed is more than code performance: anyone with little to no experience can simulate something instantly instead of having to understand C, C++ or, god forbid, GPU code.  Therefore, you can quickly modifiy everything in an afternoon and get your results in a few hours, instead of learning C (a few weeks?), learn to work with compiled code (a few days? libraries anyone?) and finally modify the C code written by someone else (days? weeks?). I think the overall speed to be concerned about is "the time it takes to get an answer", not necessarily "the time it takes to run 100,000 photons". Considering many calculations with high performance code (in C for instance) take a few minutes, it is fairly reasonable to imagine you could start a calculation in Python, run it overnight and get an answer the next day after a few hours of calculations. I think there is a need for such a solution, and you will find it here.Therefore, the whole point is the following: this code is perfect for quickly prototyping a small calculation, and then determine if you need performance or not. For many things, you actually don't.Getting startedInstall with pip or get thecodefrom GitHub. You can run the example code immediately:pipinstallpytissueoptics--upgrade
python-mpytissueopticsYou need Python 3, it will not work with Python 2. The example code will show you a graph of the energy deposited in the plane xz from a isotropic source at the origin:Then it will display the logarithm (log10) of the intensity as a fonction of distance along the x direction:We can also display the intensity on surfaces:Then, the idea would be to modify the code for your geometry (layers, boxes, cubes, spheres, etc...) and compute what you want.What it can doThere are 6 main concepts (orClassin object-oriented language) in this code:Photon: The photon is the main actor:  it has a position, it propagates in a given direction.  Its direction is changed when it scatters. It does not know anything about geometry or physical properties of tissue.Source: A group of photons, such asIsotropicSource,PencilSourcewith specific properties. You provide the characteristics you want and it will give you a list of photons that responds to these criteria.  This list of photons will give you the answer you want after it has propagated in theObjectof interest.Material: The scattering properties and the methods to calculate the scattering angles are the responsibility of theMaterialclass. TheMaterialalso knows how to move the photon between two points (for instance, if there is birefringence, this is where you would put it although polarization is currently not implemented).Geometry: A real-world geometry (Box,Cube,Sphere,Layer, etc...). The geometry has two important variables: aMaterial(which will dictate its optical properties i.e. scattering and index) and aStatsobject to keep track of physical values of interest.  The material will provide the required functions to compute the scattering angles, and the photon will use these angles to compute its next position.  TheStatsobject will compute the relevant statistics.Stats: An object to keep track of something you want. For now, it keeps track of volumetric quantities (i.e. the energy deposited in the tissue) and intensities through the surfaces delimiting geometries.Finally, very usefulVector,UnitVectorandSurfacehelper classes with their subclasses are used to simplify any 3D computation with vectors, planes, surfaces, because they can be used like other values (they can be added, subtracted, normalized, etc...).LimitationsThere are many limitations, as this is mostly a teaching tool, but I use it for real calculations in my research:It really is not fully tested yet as of 1.0.4, especially withreflections.  Setting all indices to 1.0 is a safe measure to get safe results (but obviously without reflections).It only uses Henyey-Greenstein because it is sufficient most of the time.Documentation is sparse at best.You have probably noticed that the axes on the graphs are currently not labelled. Don't tell my students.Did I say it was slow? It is approximately 50x slower than the well-known codeMCMLon the same machine. I know, and now I know thatyouknow, but seeAdvantagesbelow.AdvantagesHowever, there are advantages:It is extremely simple to understand.The code is very clear with only a few files in a single directory.It can be used for teaching tissue optics.It can be used for teaching object-oriented programming for those not familiar with it.It is fairly easy to modify for your own purpose. Many modifications do not even require to subclass.In addition, because it is very easy to parallelize a Monte Carlo calculations (all runs are independant), splitting the job onto several CPUs is a good option to gain a factor of close to 10 in perfromance on many computers. I have not done it yet.The core of the codeThe code is in fact so simple, here is the complete code that can create graphs similar to the ones above in 10 seconds on my computer:frompytissueopticsimport*# We choose a material with scattering propertiesmat=Material(mu_s=30,mu_a=0.1,g=0.8,index=1.4)# We want stats: we must determine over what volume we want the energystats=Stats(min=(-2,-2,-2),max=(2,2,2),size=(50,50,50))# We pick a light sourcesource=PencilSource(direction=UnitVector(0,0,1),maxCount=10000)# We pick a geometrytissue=Layer(thickness=1,material=mat,stats=stats)# We propagate the photons from the source inside the geometryWorld.place(source,position=Vector(0,0,-1))World.place(tissue,position=Vector(0,0,0))World.compute(graphs=True)# Report the results for all geometriesWorld.report()The main function where the physics ishiddenisGeometry.propagate().World.compute()is a helper to call the function several times, and could possibly be parallelized:classGeometry:[...]defpropagate(self,photon):photon.transformToLocalCoordinates(self.origin)self.scoreWhenStarting(photon)d=0whilephoton.isAliveandself.contains(photon.r):# Pick distance to scattering pointifd<=0:d=self.material.getScatteringDistance(photon)distToPropagate,surface=self.nextExitInterface(photon.r,photon.ez,d)ifsurfaceisNone:# If the scattering point is still inside, we simply move# Default is simply photon.moveBy(d) but other things# would be here. Create a new material for other behaviourself.material.move(photon,d=d)d=0# Interact with volume: default is absorption only# Default is simply absorb energy. Create a Material# for other behaviourdelta=self.material.interactWith(photon)self.scoreInVolume(photon,delta)# Scatter within volumetheta,phi=self.material.getScatteringAngles(photon)photon.scatterBy(theta,phi)else:# If the photon crosses an interface, we move to the surfaceself.material.move(photon,d=distToPropagate)# Determine if reflected or not with Fresnel coefficientsifself.isReflected(photon,surface):# reflect photon and keep propagatingphoton.reflect(surface)photon.moveBy(d=1e-3)# Move away from surfaced-=distToPropagateelse:# transmit, score, and leavephoton.refract(surface)self.scoreWhenCrossing(photon,surface)photon.moveBy(d=1e-3)# We make sure we are outbreak# And go againphoton.roulette()# Because the code will not typically calculate millions of photons, it is# inexpensive to keep all the propagated photons.  This allows users# to go through the list after the fact for a calculation of their choiceself.scoreWhenFinal(photon)photon.transformFromLocalCoordinates(self.origin)[...]classWorld:[...]@classmethoddefcompute(self,graphs):World.startCalculation()N=0forsourceinWorld.sources:N+=source.maxCountfori,photoninenumerate(source):whilephoton.isAlive:currentGeometry=World.contains(photon.r)ifcurrentGeometryisnotNone:currentGeometry.propagate(photon)else:distance,surface,nextGeometry=World.nextObstacle(photon)ifsurfaceisnotNone:# Moving to next object in airphoton.moveBy(distance)R=photon.fresnelCoefficient(surface)photon.refract(surface)photon.decreaseWeightBy(R*photon.weight)photon.moveBy(1e-4)else:photon.weight=0World.showProgress(i+1,maxCount=source.maxCount,graphs=graphs)duration=World.completeCalculation()print("{0:.1f}ms per photon\n".format(duration*1000/N))Note that thispropagatefunction is part of theGeometryobject and does not make any assumption on the details of the geometry, and relies on whatever material was provided to get the scattering angles.How to go about modifying for your own purposeMaybe you have a special light source?SubclassSourcewith your own light source and compute the photon properties innewPhotonaccording to your own rules. Use your source instead ofIsotropicSourcein the example above:classMySource(Source):def__init__(self,myProperty,position,maxCount):super(MySource,self).__init__(position,maxCount)self.myProperty=myPropertydefnewPhoton(self)->Photon:p=Photon()# Do your thing here with self.myProperty and modify preturnpMaybe you have a special material scattering  model?SubclassMaterialand override the methods forgetScatteringAngles().  Use your material in your geometry instead ofMaterialin the example above. You could use the photon direction, polarization, position, or even its wavelength to compute its scattering angles:classFunkyMaterial(Material):def__init__(self,myProperty,mu_s=0,mu_a=0,g=0):super(MySource,self).__init__(mu_s,mu_a,g)self.myProperty=myPropertydefgetScatteringAngles(self,photon)->(float,float):# Do your thing here with self.myProperty and compute theta, phi# Use Photon if needed (position, direction, wavelength, etc..)return(theta,phi)Ifphoton.keepPathHistory()is called, it will keep track all positions during its lifetime. You can then compute whatever you want by rewriting that part of the code or with a hook function I will write at some point.Maybe you want to compute some funky stats? At each step,scoreInVolumeis called with the photon and the drop in energy at that step.  When leaving the geometry through a surface,scoreWhenCrossingis called with the photon and the last position inside.Maybe your have a special geometry? SubclassGeometryand override thecontainsmethod to compute whether or not a given position is inside your object or not, andintersectionto compute the point on the surface of your object where the photon exits.