haarigerharald / geant4_pybind Goto Github PK
View Code? Open in Web Editor NEWAlternative Python bindings for Geant4
License: The Unlicense
Alternative Python bindings for Geant4
License: The Unlicense
I've been trying out the bindings - very nice work (Geant4 has a plan to migrate to pybind11, so would be interested to see if we could collaborate more here)!
One minor gotcha I encountered when naively trying to import the package from interactive Python (NB: from a local build, not a pip install
):
$ PYTHONPATH=$PWD/source python3.9
Python 3.9.8 (main, Nov 10 2021, 06:03:50)
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import geant4_pybind
Traceback (most recent call last):
File "<string>", line 124, in <module>
AttributeError: module '__main__' has no attribute '__file__'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: initialization failed
I think I've traced that to the datainit.py
module getting called, and specifically the line:
geant4_pybind/source/datainit.py
Line 123 in d9c774a
Whilst in general interactive use probably isn't the primary use case, it would be useful to support it. I'm happy to look at ways to fix this, but let me know what you think!
Hi Harald (if that's your name),
I discovered your package because I need to write a simple simulation in Geant4. I see that the version number of this project is very low and you don't support OpenGL visualization currently, so I won't be able to use it, but you seem to have a lot of stuff going that looks very promising. You are already building wheels for all platforms and you have a design document. You know about the finer points of ownership and how to integrate those in pybind11.
I maintain several HEP libraries that use pybind11, e.g. pyhepmc and iminuit, which are part of the Scikit-HEP project. Is this a hobby project or are you interested in building this into a professional package? If the answer is yes to the latter, I could nominate you for inclusion into the Scikit-HEP project, once this project has become a bit more mature.
Best regards,
Hans
Hi,
I wanted to define my own material, which I did successfully, but I wanted to change some its properties in the material properties table. I am getting an error, that python is Unable to convert function return value to a Python type!.
A simple example:
import geant4_pybind as g4
nist = g4.G4NistManager.Instance()
waterMaterial = nist.FindOrBuildMaterial("G4_WATER",isotopes=False )
waterMaterial.GetMaterialPropertiesTable()
results in:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
TypeError: Unregistered type : G4MaterialPropertiesTable
The above exception was the direct cause of the following exception:
TypeError Traceback (most recent call last)
Input In [2], in <cell line: 5>()
3 nist = g4.G4NistManager.Instance()
4 waterMaterial = nist.FindOrBuildMaterial("G4_WATER",isotopes=False )
----> 5 waterMaterial.GetMaterialPropertiesTable()
TypeError: Unable to convert function return value to a Python type! The signature was
(self: geant4_pybind.G4Material) -> G4MaterialPropertiesTable
Also, there is no g4.G4MaterialPropertiesTable type defined.
I would appreciate help in this matter.
Good afternoon, esteemed developer!
I would like to extend my gratitude to you for creating an exceptional project that meets our needs perfectly.
I was wondering if there are any plans to incorporate support for the LHEP physics suite for parameterizing hadron interactions. If possible, I would greatly appreciate any updates on this matter.
Hello.
The function 'export_G4RayTracerX' in pyG4RayTracerX.cc
must have a mandatory argument, see e.g. the function export_G4RayTracer
in pyG4RayTracer.cc
. The line https://github.com/HaarigerHarald/geant4_pybind/blob/main/source/visualization/pyG4RayTracerX.cc#L13 should be as follows
void export_G4RayTracerX(py::module &m)
I faced that error when building package for Archlinux.
I am trying to run some simple G4 examples to compare with https://github.com/JuliaHEP/Geant4.jl but I am having problems installing the extension on MacOS.
pip3 install geant4-pybind
:>>> from geant4_pybind import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/geant4_pybind.cpython-39-darwin.so, 2): Symbol not found: __ZTTNSt3__114basic_ofstreamIcNS_11char_traitsIcEEEE
Referenced from: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/geant4_pybind.cpython-39-darwin.so
Expected in: /usr/lib/libc++.1.dylib
in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/geant4_pybind.cpython-39-darwin.so
...
[490/490] Linking CXX shared module /private/var/folders/zz/gs4fh_9d5lx4k_q51gd7kvyr0000gn/T/pip-install-3_079jq7/geant4-pybind_d1557da9e313418685b29199fe58baf5/build/lib.macosx-13.4-arm64-cpython-39/geant4_pybind.cpython-39-darwin.so
Traceback (most recent call last):
File "/private/var/folders/zz/gs4fh_9d5lx4k_q51gd7kvyr0000gn/T/pip-install-3_079jq7/geant4-pybind_d1557da9e313418685b29199fe58baf5/doc/generate_stubs.py", line 14, in <module>
FunctionSignature.ignore_invalid_signature = True
NameError: name 'FunctionSignature' is not defined
Traceback (most recent call last):
File "/Users/Shared/cvmfs/sft.cern.ch/lcg/views/LCG_104/arm64-mac13-clang140-opt/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 363, in <module>
main()
File "/Users/Shared/cvmfs/sft.cern.ch/lcg/views/LCG_104/arm64-mac13-clang140-opt/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 345, in main
...
Do you know how to fix these installation issues? Thanks in advance.
Hi everyone, I am a newbie in geant4 and stuck in somewhere again. I do not know what did I wrong. When I execute my geant4_pybind python code the UI session starts but do not visualize anything. UI give me my defined materials list and suddenly crushes.
and then when I close interactive mode in visual studio it says:
Hi, I am trying to count the number of particle passed through my material and also the number of particles of how many of these particles reach to my germanium crystal inside my detector. I do not know which approach I should use. Can you help me with that please? Here is my code.
Installing geant4 from conda and this library fails on the examples when trying to open a visualization window. Batch mode works ok.
Compiling a geant4 example runs ok so I don't think there is anything wrong with geant4 instalation.
I get:
...
/vis/open OGL 600x600-0+0
/vis/sceneHandler/create OGL
/vis/viewer/create ! ! 600x600-0+0
Segmentation fault
When I run a complex program, I find that the program is running on just one thread, not on all the threads like Geant4 API. So can you tell me how to solve this problem?
Hello.
I have issues using the visualization package. When I execute example B1 geant4_pybind python code the UI session starts but do not visualize anything. The process freezes in the state shown in the screenshot.
If I run the Geant4 examples , the visualization works.
I'm not sure what the reason is, but I hope someone can give me a hint on what might be wrong here.
I'm using WSL with Ubuntu 22.04 and python 3.10 .
P.S. Sorry for my English
Description:
I'm encountering an issue with Geant4 Pybind where it's not utilizing the specified data directory for Geant4 datasets, even though I've downloaded the necessary data during the installation process.
Environment:
Steps to Reproduce:
cmake ../ -DCMAKE_INSTALL_PREFIX=$env_dir \
-DGEANT4_USE_QT=ON \
-DGEANT4_USE_OPENGL_X11=OFF \
-DGEANT4_USE_SYSTEM_EXPAT=OFF \
-DGEANT4_BUILD_TLS_MODEL=global-dynamic \
-DGEANT4_BUILD_MULTITHREADED=ON \
-DGEANT4_INSTALL_DATA=$install_geant4_data \
-DGEANT4_INSTALL_DATADIR=$geant4_data_lib \
-DGEANT4_INSTALL_DATA_TIMEOUT=0
from geant4_pybind import *
Expected Behavior:
The Geant4 Pybind module should utilize the data directory specified using the -DGEANT4_INSTALL_DATADIR
CMake option during installation ($geant4_data_lib
), where the data was downloaded. It should not prompt to download the data again.
Actual Behavior:
Upon running the code, Geant4 Pybind prompts to download the missing datasets to ~/.geant4_pybind
, even though the data directory was specified during the installation process.
Possible Solution:
There might be an issue with how the data directory configuration is being interpreted by Geant4 Pybind. It's possible that there's a bug or misconfiguration causing this behavior.
Thank you for your attention to this matter. I'm looking forward to a resolution that allows Geant4 Pybind to utilize the specified data directory for Geant4 datasets.
I am trying to use ComputeElectronicDEDX (and other calculators) from G4EmCalculator class. It is hard to me to uderstand how to use this properly. I just need Geant4 to calculate stopping power of protons of given energy in a predefined material (for instance "G4_WATER"). For now my code looks like this but I am getting just 0 regardless on the energy or material.
import geant4_pybind as g4
runManager = g4.G4RunManagerFactory.CreateRunManager(g4.G4RunManagerType.Serial)
physicsList = g4.QGSP_BIC_HP()
physicsList.SetVerboseLevel(1)
runManager.SetUserInitialization(physicsList)
GetParticleTable = g4.G4ParticleTable.GetParticleTable()
particle = GetParticleTable.FindParticle("proton")
nist = g4.G4NistManager.Instance()
material = nist.FindOrBuildMaterial("G4_WATER")
G4EmCalculator = g4.G4EmCalculator()
ElectronicDEDX=G4EmCalculator.ComputeElectronicDEDX(kinEnergy=100 * g4.MeV, particle=particle, material=material)
print(ElectronicDEDX)
>>> 0.0
I would appreciate is anyone could help me with this.
Hello.
I made a patch to compile geant4_pybind
for Geant4 11.2.
I was able to successfully compile the code, but then it failed at the linking stage:
Traceback (most recent call last):
File "/usr/bin/pybind11-stubgen", line 33, in <module>
sys.exit(load_entry_point('pybind11-stubgen==2.4.2', 'console_scripts', 'pybind11-stubgen')())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/site-packages/pybind11_stubgen/__init__.py", line 317, in main
run(
File "/usr/lib/python3.11/site-packages/pybind11_stubgen/__init__.py", line 356, in run
QualifiedName.from_str(module_name), importlib.import_module(module_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1204, in _gcd_import
File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 676, in _load_unlocked
File "<frozen importlib._bootstrap>", line 573, in module_from_spec
File "<frozen importlib._bootstrap_external>", line 1233, in create_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
ImportError: generic_type: type "G4TouchableHistory" is already registered!
I'm not sure what the reason is, but I hope someone can give me a hint on what might be wrong here.
P.S. I'm using Archlinux with python 3.11.6, pybind11-stubgen 2.4.2.
P.P.S. I have attached the patch to the issue.
In Geant4, you can delete a track in SteppingAction like this:
G4Track* track = step->GetTrack();
track->SetTrackStatus(fStopAndKill);
I've noticed that SetTrackStatus
(and seemingly many other setter methods) are not available in Python bindings. Is this intentional? Do you have any suggestions on how to kill a track, for example, when the energy has dropped below a certain threshold?
Hi,
is it foreseen to add support for simulation of optics? It would be very appreciated.
First and foremost, thank you for the great package. Most convenient and quickest installation of Geant4 I ever had!
I noticed that geant4_pybind
gets stuck when using G4MTRunManager
either directly or via the G4RunManagerFactory
when used with Windows 10. I recalled that some years ago, Geant4 only had multi-threading support for UNIX-based OSs. Therefore, I tried to run the same experiment in a Docker container based on Ubuntu.
In both cases, the physics processes get initialized and then the script is stuck. When switching to a serial run manager, everything seems to work fine.
I understand that this is most likely a side project of yours. Just wanted to let you know!
Thank you,
Philipp
PS: I just found that you also reverted back to using a serial manager in the examples. I guess you are already aware of this issue.
I am using geant4_pybind with Mac OS 10.15.7 and python 3.9. After installing it, I tried to run examples to check the correctness.
After running exampleB1, I get
Available UI session types: [ tcsh, csh ]
################################
!!! G4Backtrace is activated !!!
################################
**************************************************************
Geant4 version Name: geant4-11-00 [MT] (10-December-2021)
Copyright : Geant4 Collaboration
References : NIM A 506 (2003), 250-303
: IEEE-TNS 53 (2006), 270-278
: NIM A 835 (2016), 186-225
WWW : http://geant4.org/
**************************************************************
<<< Reference Physics List QBBC
Visualization Manager instantiating with verbosity "warnings (3)"...
Visualization Manager initialising...
Registering graphics systems...
You have successfully registered the following graphics systems.
Registered graphics systems are:
ASCIITree (ATree)
DAWNFILE (DAWNFILE)
G4HepRepFile (HepRepFile)
RayTracer (RayTracer)
VRML2FILE (VRML2FILE)
gMocrenFile (gMocrenFile)
Registering model factories...
You have successfully registered the following model factories.
Registered model factories:
generic
drawByAttribute
drawByCharge
drawByOriginVolume
drawByParticleID
drawByEncounteredVolume
Registered models:
None
Registered filter factories:
attributeFilter
chargeFilter
originVolumeFilter
particleFilter
encounteredVolumeFilter
Registered filters:
None
You have successfully registered the following user vis actions.
Run Duration User Vis Actions: none
End of Event User Vis Actions: none
End of Run User Vis Actions: none
Some /vis commands (optionally) take a string to specify colour.
"/vis/list" to see available colours.
/control/saveHistory
/run/verbose 2
#
# Change the default number of threads (in multi-threaded mode)
#/run/numberOfThreads 4
#
# Initialize kernel
/run/initialize
userDetector->Construct() start.
Checking overlaps for volume Envelope:0 (G4Box) ... OK!
Checking overlaps for volume Shape1:0 (G4Cons) ... OK!
Checking overlaps for volume Shape2:0 (G4Trd) ... OK!
World is registered to the default region.
physicsList->Construct() start.
### HadronInelasticQBBC Construct Process:
Emin(FTFP)= 3 GeV; Emax(FTFP)= 100000 GeV
Emin(BERT)= 1 GeV; Emax(BERT)= 6 GeV; Emax(BERTpions)= 12 GeV;
Emin(BIC) = 0 GeV; Emax(BIC)= 1.5 GeV.
### Adding tracking cuts for neutron TimeCut(ns)= 10000 KinEnergyCut(MeV)= 0
physicsList->CheckParticleList() start.
physicsList->setCut() start.
#
# Visualization setting
/control/execute vis.mac
# Macro file for the visualization setting in the initialization phase
# of the B1 example when running in interactive mode
#
# Use these open statements to open selected visualization
#
# Use this open statement to create an OpenGL view:
/vis/open OGL 600x600-0+0
/vis/sceneHandler/create OGL
parameter value (OGL) is not listed in the candidate List.
Candidates are: ASCIITree ATree DAWNFILE G4HepRepFile HepRepFile RayTracer VRML2FILE gMocrenFile
-------- WWWW ------- G4Exception-START -------- WWWW -------
*** G4Exception : UIMAN0123
issued by : G4UImanager::ApplyCommand
Invoked command has failed - see above. Available graphics systems are (short names):
ATree DAWNFILE HepRepFile RayTracer VRML2FILE gMocrenFile
Error code : 500
*** This is just a warning message. ***
-------- WWWW -------- G4Exception-END --------- WWWW -------
***** Illegal parameter (0) </vis/open OGL 600x600-0+0> *****
***** Batch is interrupted!! *****
-------- WWWW ------- G4Exception-START -------- WWWW -------
*** G4Exception : UIMAN0123
issued by : G4UImanager::ApplyCommand
Command aborted (500)
Error code : 500
*** This is just a warning message. ***
-------- WWWW -------- G4Exception-END --------- WWWW -------
***** Illegal parameter (0) </control/execute vis.mac> *****
***** Batch is interrupted!! *****
-------- WWWW ------- G4Exception-START -------- WWWW -------
*** G4Exception : UIMAN0123
issued by : G4UImanager::ApplyCommand
Command aborted (500)
Error code : 500
*** This is just a warning message. ***
-------- WWWW -------- G4Exception-END --------- WWWW -------
I have downloaded all the g4 data. The error seems to happen at
parameter value (OGL) is not listed in the candidate List.
Candidates are: ASCIITree ATree DAWNFILE G4HepRepFile HepRepFile RayTracer VRML2FILE gMocrenFile
Could you please provide any help? Thank you!
As the bindings are not feature complete one may need to extend them for their specific use. A very good starting point is incorporating automatically generated bindings (parsed.zip) from a custom parser. If the ownership model is non trivial however, please read the design overview and adapt the generated bindings accordingly.
For incremental debug builds one may want to build without pip, which can be achieved via:
pip3 install ninja pybind11-stubgen "setuptools>=42" "cmake>=3.16" wheel
python3 setup.py build_ext --debug install --user
The installation went fine, but the example usage failed,
In [1]: from geant4_pybind import G4UIExecutive
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
Cell In[1], line 1
----> 1 from geant4_pybind import G4UIExecutive
ImportError: dlopen(/Users/michele/Applications/mambaforge/envs/geant4/lib/python3.11/site-packages/geant4_pybind.cpython-311-darwin.so, 2): Symbol not found: __ZTTNSt3__114basic_ofstreamIcNS_11char_traitsIcEEEE
Referenced from: /Users/michele/Applications/mambaforge/envs/geant4/lib/python3.11/site-packages/geant4_pybind.cpython-311-darwin.so
Expected in: /usr/lib/libc++.1.dylib
in /Users/michele/Applications/mambaforge/envs/geant4/lib/python3.11/site-packages/geant4_pybind.cpython-311-darwin.so
I put here some info about my installation of Geant4 using geant4-config
to help the debug,
Known Features:
staticlibs[no]
multithreading[yes]
smartstack[no]
php_as_hp[no]
clhep[no]
expat[no]
zlib[no]
gdml[yes]
ptl[yes]
usolids[no]
freetype[yes]
hdf5[no]
g3tog4[no]
qt[yes]
motif[no]
raytracer-x11[no]
opengl-x11[no]
openinventor[no]
Key | Value |
---|---|
cxxstd | 17 |
tls-model | global-dynamic |
cflags | -DG4VIS_USE_OPENGL -DG4UI_USE_TCSH -DG4UI_USE_QT -DG4VIS_USE_OPENGLQT -I/Users/michele/Applications/mambaforge/envs/geant4/include/qt/ -I/Users/michele/Applications/mambaforge/envs/geant4/include/qt/QtCore -I/Users/michele/Applications/mambaforge/envs/geant4/.//mkspecs/macx-clang -I/Users/michele/Applications/mambaforge/envs/geant4/include/qt/QtGui -I/Applications/Xcode_13.2.1.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/System/Library/Frameworks/OpenGL.framework/Headers -I/Users/michele/Applications/mambaforge/envs/geant4/include/qt/QtWidgets -I/Users/michele/Applications/mambaforge/envs/geant4/include/qt/QtOpenGL -I/Users/michele/Applications/mambaforge/envs/geant4/include/qt/QtPrintSupport -I/Users/michele/Applications/mambaforge/envs/geant4/include/qt/Qt3DCore -I/Users/michele/Applications/mambaforge/envs/geant4/include/qt/QtNetwork -I/Users/michele/Applications/mambaforge/envs/geant4/include/qt/Qt3DExtras -I/Users/michele/Applications/mambaforge/envs/geant4/include/qt/Qt3DRender -I/Users/michele/Applications/mambaforge/envs/geant4/include/qt/Qt3DInput -I/Users/michele/Applications/mambaforge/envs/geant4/include/qt/QtGamepad -I/Users/michele/Applications/mambaforge/envs/geant4/include/qt/Qt3DLogic -march=core2 -mtune=haswell -mssse3 -ftree-vectorize -fPIC -fPIE -fstack-protector-strong -O2 -pipe -stdlib=libc++ -fvisibility-inlines-hidden -fmessage-length=0 -isystem /Users/michele/Applications/mambaforge/envs/geant4/include -fdebug-prefix-map=/Users/runner/miniforge3/conda-bld/geant4_1667500347678/work=/usr/local/src/conda/geant4-11.0.3 -fdebug-prefix-map=/Users/michele/Applications/mambaforge/envs/geant4=/usr/local/src/conda-prefix -D_LIBCPP_DISABLE_AVAILABILITY -W -Wall -pedantic -Wno-non-virtual-dtor -Wno-long-long -Wwrite-strings -Wpointer-arith -Woverloaded-virtual -Wno-variadic-macros -Wshadow -pipe -Qunused-arguments -DGL_SILENCE_DEPRECATION -pthread -ftls-model=global-dynamic -std=c++17 -I/Users/michele/Applications/mambaforge/envs/geant4/bin/../include/Geant4 -I/Users/michele/Applications/mambaforge/envs/geant4/include -I/Users/michele/Applications/mambaforge/envs/geant4/include |
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.