使用JEP在Java中运行Python库时遇AttributeError错误求助
Let's break down what's happening here and how to fix it:
What's causing the error?
The ImmutableDenseNDimArray object you're encountering is JEP's own wrapped implementation of an NDArray—not a native NumPy ndarray. When the burst_detection library passes this object to Sympy's binomial function, Sympy expects inputs compatible with its type system (like native Python numbers, NumPy arrays, or Sympy symbols). Since JEP's NDArray doesn't implement the _to_mpmath method Sympy relies on for type conversion, you hit this AttributeError.
Your hunch about the Sympy line being the culprit is exactly right—this error originates directly from the c.binomial(d, r) call in the library code.
Fixes to try
Here are three straightforward solutions to resolve this compatibility gap:
Convert JEP NDArrays to native NumPy arrays in Python
Before executing the burst_detection logic, explicitly convert the JEP-wrapped arrays to NumPy's native format. Add these lines at the start of your Python code:import numpy as np # Convert JEP's NDArray to native NumPy arrays r = np.array(r) d = np.array(d)This gives Sympy a format it understands, and the
binomialfunction will operate as intended.Pass Java arrays directly as Python lists from Java
If you don't need to use JEP's NDArray features on the Java side, skip creatingNDArray<int[]>entirely. Just pass your Javaint[]arrays directly—JEP will automatically convert them to Python lists:jep.set("r", twf); // twf is your int[] array jep.set("d", ndpw); // ndpw is your other int[] arrayThen in Python, convert those lists to NumPy arrays (if the library expects array inputs) using
np.array()as shown above.Debug input types to confirm conversion
To verify the conversion worked, add a quick debug line in your Python code to check the types:print("d type:", type(d), "r type:", type(r))You should see output like
<class 'numpy.ndarray'>for both—this confirms you're working with native NumPy arrays that Sympy can handle.
Key takeaway
This is a classic cross-language type compatibility issue: JEP's NDArray is a Java-side abstraction that doesn't integrate smoothly with Python's scientific computing ecosystem (NumPy/Sympy). Adding a simple type conversion layer between JEP's wrapper and native Python/NumPy types resolves the problem entirely.
内容的提问来源于stack exchange,提问作者Cyber

