CRPropa / CRPropa3

CRPropa is a public astrophysical simulation framework for propagating extraterrestrial ultra-high energy particles. https://crpropa.github.io/CRPropa3/
https://crpropa.desy.de
GNU General Public License v3.0
66 stars 66 forks source link

Segfault extending by inheritance in python #165

Open TobiasWinchen opened 6 years ago

TobiasWinchen commented 6 years ago

This is from the examples and reproduces the bug

import crpropa
from crpropa import Mpc, nG, EeV
import numpy as np

class MySourceFeature(crpropa.SourceFeature):
    """ Set the initial energy to 10 EeV """
    def __init__(self):
        crpropa.SourceFeature.__init__(self)

    def prepareParticle(self, particleState):
        particleState.setEnergy(10 * EeV)

vgrid = crpropa.VectorGrid(crpropa.Vector3d(0), 128, 1 * Mpc)
crpropa.initTurbulence(vgrid, 1 * nG, 2 * Mpc, 5 * Mpc, -11. / 3.)
BField = crpropa.MagneticFieldGrid(vgrid)

m = crpropa.ModuleList()
m.add(crpropa.PropagationCK(BField, 1e-4, 0.1 * Mpc, 5 * Mpc))
m.add(crpropa.MaximumTrajectoryLength(25 * Mpc))

# source setup
source = crpropa.Source()
source.add(crpropa.SourcePosition(crpropa.Vector3d(0, 0, 0) * Mpc))
source.add(crpropa.SourceIsotropicEmission())
source.add(crpropa.SourceParticleType(crpropa.nucleusId(1, 1)))
source.add(crpropa.SourceEnergy(1 * EeV))
source.add(MySourceFeature())
m.run(source, 1000)

occures not always; occures in single threaded and multi threaded execution

TobiasWinchen commented 6 years ago

The bug also affects ObserverFeatures and Modules written in python. However,

source.add(MySourceFeature()) will fail;

sf = MySourceFeature() source.add(sf)

will work. The reason is that in the former case the object is deleted by python. See also: https://github.com/swig/swig/issues/779

Monkey patching ( https://github.com/swig/swig/issues/723) might be a solution to disown the created object first but is surely an ugly solution.

adundovi commented 6 years ago

It is the same issue I had almost 3 years ago, see #27 . Disown is, I agree, an ugly solution, while the one where the python is taking care of the ownership is what I regularly use and it works.

I would write a recommendation how to handle this on the wiki, section about extending CRPropa from Python, and close the issue. I'm afraid we cannot do more.

lukasmerten commented 6 years ago

I had this problem, too.

I agree with Andrej let's just put an explanation in the wiki and maybe a comment in the example for the source feature. So when the example is used people will know why the object has to be created outside of the class attributes.

TobiasWinchen commented 6 years ago

Okay, I will add a tag `Won't fix' to the bug to mark that we won't work on it, but I don't think that we should close such issues. If #27 hadn't been closed it would have saved me the time figuring out the problem.