Git Product home page Git Product logo

montycarlo's Introduction

MontyCarlo (alpha, developmental releases)

license pyversion architecture os

MontyCarlo is a python framework for setting up simulations and/or developing applications whose basis is the simulation of particle transport. It simulates the propagation and effects of ionizing radiation (photons, electrons and positrons with energies between 1keV and 1GeV) in matter of homogeneous density, filling constructive solid geometry models.

This work has a poster presentation in the 3rd European Congress of Medical Physics and has been presented in a workshop organized by the Faculty of Sciences of the University of Porto and the Ludwig Maximilian University of Munich.

Getting started

Clone this repository and run

docker compose up -d

This will start a jupyter notebook server listening on http://localhost:8888.

Have fun exploring high energy particle tracks in a 3d environment!

  • White tracks: Photons
  • Blue tracks: electrons
  • Red tracks: positrons

The innermost sphere contains water, the outer sphere contains air and the rest of space is filled with gold.

ex01

Be sure to zoom in on every detail!

ex02

Other cool examples

CSGexample

img1

img2

What to expect

Speed

Although it is a python module this package is written in a happy mix of Python, Cython, C++. A notable example of a package that also does this is Numpy. Most of the initialization and pretty much all the programming user interface is in Python, so while setting up your simulation or handling the results of it, you'll be dealing with Python. However, from the moment you tell MontyCarlo to start simulating, it leaves the world of Python and starts running optimized C code. Each language is therefore placed strategically so that it can play to its strenghts.

Fun

Using the power of vtk through the wonderful work of mayavi remarkable visualizations are easy in Monty Carlo.

50keV electrons in water (secondary particles off):

Electrons in Water

10MeV electrons in water (primary in red, secondary photon in green)

image

SSSS250k

Bugs

This is a very early version of a fairly large code. Bugs are guaranteed! Submitting an issue is a great way to contribute to the project at this stage!

Available Features:

  • Construction of any material via a stochiometric formula and density water = Mat({1:2, 8:1}, 1);
  • Constructed materials are automatically cached in the folder your_project\mat.
  • Only spheres are available. This will remain as such until all this has been thoroughly tested:
    • Constructive Solid Geometry (CSG) using the | & and - operators;
    • linear transformations on the volumes (translation and rotation);
    • bounding volume hierarchy (BVH) constructed with the aid of the user;
    • a syntatic indication of the BVH using with statements;
    • a new method of particle transport that greatly accelerates the simulation of electrons and positrons;
  • The volumes surfaces are rendered and cached in your_project/geo;
  • Three particles are available:
    • Photons (analogue simulation);
      • Compton Scattering;
      • Rayleigh Scattering;
      • Photoelectric Effect;
      • Pair Production;
      • Triplet Production;
    • Electrons (class II condensed history);
      • Elastic Scattering (atom is not affected): Angular Deflection + Bremstrahlung Production;
      • Inelastic Scattering (atom is affected): Interaction with an individual atom + with the condensed medium as a whole;
    • Positrons (class II condensed history);
      • Elastic Scattering (atom is not affected): Angular Deflection + Bremstrahlung Production;
      • Inelastic Scattering (atom is affected): Interaction with an individual atom + with the condensed medium as a whole;
      • Anihilation (positron meets electron);
  • The simulation is coupled (e.g. supports secondary particle creation)
  • Supports simulation of post-ionization relaxation effects;
  • Two particle sources are available:
    • Isotropic point source: emits particles from a point with randomized directions - IsotropicPoint
    • Directional point source: emits particles from a point towards a specified direction - Beam
  • Automated database download on first import;
  • 3d plotting of particle trajectories;
  • 3d plotting of the constructed geometry;
  • simultaneous plotting of both geometry and trajectories;
  • One tally is available:
    • Z_TALLY - calculates PDD's
  • Automatic generation of *.html output files (work in progress though)

Possible Future Work

  • Sources
  • Tallying
    • Energy Deposition (1d, 2d, 3d, 4d(spatial + temporal) )
    • Flux
    • Others
  • Variance reduction
  • Image Detectors
  • Extension to E < 1keV (for laser applications)
  • Extension to E > 1GeV (for thermonuclear applications)
  • Implementation of other particles
    • Protons
    • Neutrons
    • etc...
  • Dedicated graphics engine (w/sphere tracing)
  • An auto-cad like GUI for CSG modeling
  • Geant4 like API
  • GPU accelaration
  • CPU multiprocessing/multithreading
  • Advanced data vizualization (w/ ParaView)
  • Distributed Cloud Computing
  • Dedicated python notebook (like Jupyter)

montycarlo's People

Contributors

ruifilipecampos avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

montycarlo's Issues

SDF not working in linux

from libc.math cimport fmin, fmax, sqrt, cos, sin

...

in def exit

if self.render:
@plt_geo.sdf3
def this():
def SDF(double[:,:] P):
cdef double3 p
cdef int N = len(P)
cdef cnp.ndarray sd = np.zeros(N)
cdef int i
for i in range(N):
p.x = P[i, 0]
p.y = P[i, 1]
p.z = P[i, 2]
sd[i] = self.SDF(p)
return sd
return SDF
generator = this()
import os
generator.save(f"geo/{self.name}.stl")

two parts of the program are not working:
-> the rendering of the surface
-> the boundary crossing

the only thing they have in common is this:

self.SDF(p) 

...

the signed distance function of the sphere

cdef double SDF(self, double3 _pos):
cdef double3 pos = _pos
self.tr.inv_pos(pos)
return sqrt(pos.x*pos.x + pos.y*pos.y + pos.z*pos.z) - self.r

might be this double3 stuff?... idk, it's the only thing that is here, that the physics engine is not using (the physics engine is working)

also this :

self.tr.inv_pos(pos) 

cdef class Primitive(CSGvol):
cdef Transform tr
def __init__(self):
super(Primitive, self).__init__()
self.tr = Identity(self)
def translate(self, dx, dy, dz):
self.tr = self.tr.translate(dx, dy, dz)
#self.mesh.translate([dx, dy, dz])
def rotate(self, axis, angle):
self.tr = self.tr.rotate(axis, angle)
@property
def matrix(self):
return self.tr.matrix
@property
def inv_matrix(self):
return self.tr.inv_matrix

cdef void inv_pos(self, double3& rpos):
cdef double3 pos = rpos
rpos.x = self.iT[0]*pos.x + self.iT[1]*pos.y + self.iT[2] *pos.z + self.iT[3]
rpos.y = self.iT[4]*pos.x + self.iT[5]*pos.y + self.iT[6] *pos.z + self.iT[7]
rpos.z = self.iT[8]*pos.x + self.iT[9]*pos.y + self.iT[10]*pos.z + self.iT[11]

Design a new database.

This is a separate project in itself. To my knowledge, there is not a modern SQL database version of the many physics data tables necessary for the simulation of particle transport through matter. Would be nice to standardize everything and even build an API to serve the data for research use.

[TASK] MVP.server: Design script execution arquitecture.

Python code is going to be uploaded to the server.

The server needs to run this code, which comes with serious security risks since the server itself is running Python.

A careful design preceded by some research is needed.

Change Dockerfile

The dockerfile should be more general and be written such that applications can be built on top of its image.

Doesn't find database.

Describe the bug

Traceback (most recent call last):
Importing .settings
  File "<string>", line 1, in <module>
_________________________________________________________________
  File "/Users/runner/work/MontyCarlo/MontyCarlo/MontyCarlo/__init__.py", line 29, in <module>
INSTALL PATH:  /Users/runner/work/MontyCarlo/MontyCarlo/MontyCarlo
    from MontyCarlo.geometry.main import *
----
  File "MontyCarlo/geometry/main.pyx", line 1, in init MontyCarlo.geometry.main
DEBUG: False
    # distutils: language = c++
---------------
  File "MontyCarlo/materials/pyRelax.pyx", line 56, in init MontyCarlo.materials.pyRelax
PHOTON CUT OFF: 5110.0 MeV
    from . import database as db
----
  File "/Users/runner/work/MontyCarlo/MontyCarlo/MontyCarlo/materials/database.py", line 596, in <module>
ELECTRON CUT OFF: 100000.0 MeV
    EADL = [getEADL(Z) for Z in range(1, 101)]
---------------------------------------------
  File "/Users/runner/work/MontyCarlo/MontyCarlo/MontyCarlo/materials/database.py", line 596, in <listcomp>

    EADL = [getEADL(Z) for Z in range(1, 101)]

  File "/Users/runner/work/MontyCarlo/MontyCarlo/MontyCarlo/materials/database.py", line 222, in getEADL
BRANCH: pre-alpha/0.0.41
    Aw, EADL_dict = get_bookmarked_text_EADL(EADL_path)

  File "/Users/runner/work/MontyCarlo/MontyCarlo/MontyCarlo/materials/database.py", line 158, in get_bookmarked_text_EADL
Importing .install
    with open(path, "r") as file:

FileNotFoundError: [Errno 2] No such file or directory: '/Users/runner/work/MontyCarlo/MontyCarlo/MontyCarlo/materials\\EADL\\1.txt'
The data being download can be seen in `https://github.com/RuiFilipeCampos/MontyCarlo/tree/pre-alpha/0.0.41/docs` 
in the `EADL`, `EPDL`, `EEDL`, and `elastic` folders. 

Downloading EADL...
Done!

Downloading EPDL...
Done!

Downloading EEDL...
Done!

Downloading electron elastic data...
Done!

Downloading electron positron data...
Done!

____INIT_____
Importing .plotter
Importing .tools.interpol1
Importing .tools.CubicInverseTransform ...
Importing .materials.pyRelax
Importing .materials.database

    ________________
    > Reading EADL. 
Error: Process completed with exit code 1.```

**To Reproduce**
Run build_and_run.yml

[TASK] Command line tools

Command line tools for creating and managing MontyCarlo projects.

python -m MontyCarlo --new my_project_name

This would then create the necessary folder structure and initial files. Maybe even a python script with boilerplate code.

[TASK] Organize code that implements the pickle protocol.

For example, these would likely read better if they were staticmethods.

def rebuildsampler(this):
cdef sampler self
self = <sampler> sampler.__new__(sampler)
self.Zeff = this.Zeff
self.k = this.k # molecule.k
self.X = this.X # np.array(XX)
self.Xmax = this.Xmax # np.array(Xmax)
self.E = this.E # np.array(molecule.E)*1e6
self.kcr = this.kcr # molecule.Wcr/(molecule.E*1e6)
self.logE = this.logE # np.log(molecule.E*1e6)
self.En = this.En
return self

[TASK] Review implementation of bremsstrahlung sampling.

cdef (double, double) full_sample(self, double E, mixmax_engine *genPTR):
"""Sample electrons fractional energy loss (k) and the emitted photons polar angular with respect to the direction of the electrons movement (theta).
"""
cdef double k = self._sample(E,genPTR)
#cdef double theta = sample_theta(E, self.Zeff, k)
return (k , sample_theta(E, self.Zeff, k, genPTR))
cdef double _sample(self, double E, mixmax_engine *genPTR):
"""Sample the electrons fractional energy loss (k).
"""
self.i = search._sortedArrayDOUBLE(self.E, E, 0, self.En)
if self.E[self.i] == E:
return self.sample_ds(genPTR)
cdef double logE1, logE2, logE
assert self.E[self.i] <= E < self.E[self.i+1]
logE1, logE2 = self.logE[self.i], self.logE[self.i+1]
logE = log(E)
#cdef double pi_1, pi_2
#pi_1 =
#pi_2 = (logE - logE1)/log_diff
if genPTR.get_next_float() > ( logE2 - logE ) / (logE2 - logE1):
self.i +=1
return self.sample_ds(genPTR)
cdef double sample_ds(self, mixmax_engine *genPTR):
"""Sample the electrons fractional energy loss (k) from the chosen X-Section.
"""
cdef double w
cdef double kcr = self.kcr[self.i]
cdef LLI XX = self.X[self.i]
cdef double Xmax = self.Xmax[self.i]
while 1:
w = kcr**genPTR.get_next_float()
if genPTR.get_next_float()*Xmax < XX._eval(w):
return w

Those three methods should be merged I think.

Build time is too high

image

  • Database download is no longer needed, this is no longer a pip package
  • I'm sure lots of requirements can be deprecated and removed, pyvista for example:
    • pyvista
    • everything related with the report generator
    • everything related to scipy should be re-implemented here, I'm not even sure if I'm using it at all
  • I think most of the time is being allocated to compiling MIXMAX, I should look into how to speed up that process, or just code the methods myself

BUG: key error

seeding with: 0, 0, 0, 123
seeding with: 0, 0, 0, 89715
Traceback (most recent call last):
D:\a\MontyCarlo\MontyCarlo\tests\_cmd.py
  File "D:\a\MontyCarlo\MontyCarlo\MontyCarlo\materials\database.py", line 553, in __getitem__
['import_test.py', '--built_inplace']
The path 'D:\a\MontyCarlo\MontyCarlo' has been appended to `sys.path`. If the path looks weird, you probably ran the script as a python file. Please run it as a module:
`python -m unit_test --built_inplace`
Importing MontyCarlo
Importing .settings
_________________________________________________________________
INSTALL PATH:  D:\a\MontyCarlo\MontyCarlo\MontyCarlo
----
DEBUG: False
---------------
PHOTON CUT OFF: 5110.0 MeV
----
ELECTRON CUT OFF: 100000.0 MeV
---------------------------------------------


BRANCH: pre-alpha/0.0.41

____INIT_____
Importing `.plotter`
Importing .tools.interpol1
Importing .tools.CubicInverseTransform ...
Importing `.materials.pyRelax`
Importing .materials.database
Importing .tools.vectors
Importing .tools.RITA
>>>> IMPORTING material.photon.CrossSection.pyx
>>>> IMPORTING material.photon.pyx
Importing `.materials.materials`
Importing `.materials.logger`
>>>> IMPORTING main.pyx
Importing .materials.electron.main
Importing `.types`
Importing .particles.particle
Importing .geometry.main
Importing .geometry.CSG
Importing .particles.positrons
Importing particles.photons
Importing .particles.electrons
Size of mater 128
Importing .sources
SEED: 725832839
Creating a material
Compiling data for material 'Untitled'
0
NUMBER OF PROFILES 1
1 1
0
1
2
NUMBER OF PROFILES 3
8 4
        DATA PROCESSING IN PYTHON
        > a = 2.9395944556963114
                err =  0.0 %
    2x<Atom Z=1, Aw = 1.00797 amu, I = 19.2 eV> 
    <Shell #1, fk = 1.0, Uk = 13.6 eV, Wk = 40.360955827712104 eV> 
 
    1x<Atom Z=8, Aw = 15.9994 amu, I = 95.0 eV> 
    <Shell #1, fk = 2.0, Uk = 538.0 eV, Wk = 1581.521246377744 eV> 
    <Shell #3, fk = 3.33, Uk = 21.049999999999997 eV, Wk = 62.8342736655728 eV> 
 

        GENERATING GOS MODEL IN CYTHON
        > creating shells
        > making density corrections
        > note: KE = logspace(1, 9, 5_000)
        GENERATING FULL SP
    return self.__cache__[Z+1]
KeyError: 8.0

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\a\MontyCarlo\MontyCarlo\tests\import_test.py", line 14, in <module>
    myco.Mat({1:2, 8:1}, 1)
  File "MontyCarlo\materials\materials.pyx", line 894, in MontyCarlo.materials.materials.Mat
  File "MontyCarlo\materials\materials.pyx", line 990, in MontyCarlo.materials.materials.Material.__init__
  File "MontyCarlo\materials\electron\main.pyx", line 295, in MontyCarlo.materials.electron.main.Electron.__init__
  File "MontyCarlo\materials\electron\main.pyx", line 614, in MontyCarlo.materials.electron.main.Inelastic.__init__
  File "MontyCarlo\materials\electron\GOSfinal.pyx", line 127, in MontyCarlo.materials.electron.GOSfinal.gosMolecule.__init__
  File "MontyCarlo\materials\electron\GOSfinal.pyx", line 368, in MontyCarlo.materials.electron.GOSfinal.gosAtom.__init__
  File "MontyCarlo\materials\electron\GOSfinal.pyx", line 1088, in MontyCarlo.materials.electron.GOSfinal.gosInnerShell.__init__
  File "D:\a\MontyCarlo\MontyCarlo\MontyCarlo\materials\database.py", line 555, in __getitem__
    self.__cache__[Z+1] = getEEDL(Z+1)
  File "D:\a\MontyCarlo\MontyCarlo\MontyCarlo\materials\database.py", line 294, in getEEDL
    EEDL_dict = get_bookmarked_text(EEDL_path)
NameError: name 'EEDL_path' is not defined
Error: Process completed with exit code 1.

`.tools.CubicInverseTransform` is using wrong pRNG.

cdef double _sample(self):
self.R = self.N * rand()
self.i = <int> self.R
if self.R - self.i < self.cut_offs[self.i]:
self.dx = rand() * self.DX[self.i]
self.y = self.c[3, self.i]
self.y += self.c[2, self.i]*self.dx
self.dx *= self.dx
self.y += self.c[1, self.i]*self.dx
self.dx *= self.dx
self.y += self.c[0, self.i]*self.dx
return self.y
self.i = self.rej_indexes[self.i]
self.y = self.c[3, self.i]
self.dx = rand()*self.DX[self.i]
self.y += self.c[2, self.i]*self.dx
self.dx *= self.dx
self.y += self.c[1, self.i]*self.dx
self.dx *= self.dx
self.y += self.c[0, self.i]*self.dx
return self.y

Using old pRNG.

Does not find elastic db

       MAKING ELASTIC SAMPLER
Traceback (most recent call last):
  File "import_test.py", line 14, in <module>
    myco.Mat({1:2, 8:1}, 1)
  File "MontyCarlo\materials\materials.pyx", line 894, in MontyCarlo.materials.materials.Mat
  File "MontyCarlo\materials\materials.pyx", line 990, in MontyCarlo.materials.materials.Material.__init__
  File "MontyCarlo\materials\electron\main.pyx", line 321, in MontyCarlo.materials.electron.main.Electron.__init__
  File "MontyCarlo\materials\electron\main.pyx", line 1066, in MontyCarlo.materials.electron.main.Elastic.__init__
  File "MontyCarlo\materials\electron\main.pyx", line 1363, in MontyCarlo.materials.electron.main.Elastic.compose
  File "C:\hostedtoolcache\windows\Python\3.8.10\x64\lib\site-packages\numpy\lib\npyio.py", line 417, in load
    fid = stack.enter_context(open(os_fspath(file), "rb"))
FileNotFoundError: [Errno 2] No such file or directory: 'D:\\a\\MontyCarlo\\MontyCarlo\\MontyCarlo\\materials\\electron\\elastic/1/HEtransportTCS.npy'

(macos) import MontyCarlo fails

Describe the bug
Traceback (most recent call last):

  File "<string>", line 1, in <module>
  File "/Users/runner/hostedtoolcache/Python/3.7.10/x64/lib/python3.7/site-packages/MontyCarlo/__init__.py", line 21, in <module>
    from ._init import eax
  File "MontyCarlo/_init.pyx", line 79, in init MontyCarlo._init
ValueError: Buffer dtype mismatch, expected 'int' but got 'long'

To Reproduce
Do first import on macos.

Desktop (please complete the following information):

  • OS: macos-latest

Interesting Repo!

Hi there! Cool repo!

I have been trying to run one of the examples and I think there is an issue with reading data.pkl? I am not sure though. Any thoughts on this? Thanks for your help!

Traceback (most recent call last):
File "C:/MontyCarloParticleTest.py", line 9, in
water = Mat({1: 2, 8: 1}, 1, name="Water")
File "MontyCarlo\materials\materials.pyx", line 894, in MontyCarlo.materials.materials.Mat
File "MontyCarlo\materials\materials.pyx", line 998, in MontyCarlo.materials.materials.Material.init
FileNotFoundError: [Errno 2] No such file or directory: 'mat/Water_C10.1_C20.1_Wcc100000.0_Wcr10000.0'

testing the cmd

myco@C:\Users\Rui Campos\.conda\envs\py361\Scripts>cd ..
myco@C:\Users\Rui Campos\.conda\envs\py361>cd ..
myco@C:\Users\Rui Campos\.conda\envs>cd ..
myco@C:\Users\Rui Campos\.conda>cd ..
myco@C:\Users\Rui Campos>cd Projects
myco@C:\Users\Rui Campos\Projects>ls
# Sorted alphabetically with capital letters coming first.

DIRECTORIES:
    (...)

FILES:
     autosetup.py
     setup.py
     teste.py

myco@C:\Users\Rui Campos\Projects>create onion
The name of your project is: onion


myco@C:\Users\Rui Campos\Projects>open onion
Initing MontyCarlo, just a sec....
Your project is now open!

myco@onion>build
myco@onion>run
C:\Users\Rui Campos\Downloads
Traceback (most recent call last):
  File "c:\users\rui campos\.conda\envs\py361\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\users\rui campos\.conda\envs\py361\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\Rui Campos\.conda\envs\py361\Scripts\myco.exe\__main__.py", line 7, in <module>
  File "c:\users\rui campos\.conda\envs\py361\lib\site-packages\MontyCarlo\cl\myco.py", line 266, in main
    MontyCarloShell().cmdloop()
  File "c:\users\rui campos\.conda\envs\py361\lib\cmd.py", line 138, in cmdloop
    stop = self.onecmd(line)
  File "c:\users\rui campos\.conda\envs\py361\lib\cmd.py", line 217, in onecmd
    return func(arg)
  File "c:\users\rui campos\.conda\envs\py361\lib\site-packages\MontyCarlo\cl\myco.py", line 169, in do_open
    MontyCarloProjectShell().cmdloop(project_path)
  File "c:\users\rui campos\.conda\envs\py361\lib\site-packages\MontyCarlo\cl\myco.py", line 245, in cmdloop
    super(MontyCarloProjectShell, self).cmdloop()
  File "c:\users\rui campos\.conda\envs\py361\lib\cmd.py", line 138, in cmdloop
    stop = self.onecmd(line)
  File "c:\users\rui campos\.conda\envs\py361\lib\cmd.py", line 217, in onecmd
    return func(arg)
  File "c:\users\rui campos\.conda\envs\py361\lib\site-packages\MontyCarlo\cl\myco.py", line 252, in do_run
    os.chdir(root.name)
FileNotFoundError: [WinError 2] O sistema não conseguiu localizar o ficheiro especificado: 'onion'

  • termcolor not in requirements

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.