martibosch / pylandstats

Computing landscape metrics in the Python ecosystem
https://doi.org/10.1371/journal.pone.0225734
GNU General Public License v3.0
82 stars 16 forks source link

loop of ufunc does not support argument 0 of type float which has no callable log method #50

Open mouzui opened 4 months ago

mouzui commented 4 months ago

PyLandStats version: 2.4.2 Python version: 3.12.3 Operating System: MacOS Description I encountered an issue while using the conditional_entropy function in the pylandstats package. The error message suggests there is a problem with the compute_entropy function when it attempts to handle the log method on a float. I was expecting the function to compute the conditional entropy without any errors.

What I Did I ran the code: This resulted in the following traceback:

Traceback (most recent call last): File "path/to/your/script.py", line 153, in cauculate(tif_file) File "path/to/your/script.py", line 105, in cauculate CONDENT = lscape.conditional_entropy() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "path/to/pylandstats/landscape.py", line 2638, in conditional_entropy return self.joint_entropy(base=base) - self.entropy(base=base) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "path/to/pylandstats/landscape.py", line 2611, in joint_entropy return compute_entropy(adjacencies, base=base) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "path/to/pylandstats/landscape.py", line 116, in compute_entropy entropy = -np.sum(pcounts * np.log(pcounts)) ^^^^^^^^^^^^^^^ TypeError: loop of ufunc does not support argument 0 of type float which has no callable log method Proposed Solution To fix this issue, I suggest modifying the compute_entropy function to ensure that counts is converted to a NumPy array with a float data type before performing any operations. Adding the following line at the beginning of the function should resolve the problem:

python Copy code def compute_entropy(counts, base=None): counts = np.asarray(counts, dtype=float) pcounts = (counts / counts.sum())[counts > 0] print("Proportional counts:", pcounts) entropy = -np.sum(pcounts * np.log(pcounts)) if base: entropy /= np.log(base) return entropy This change ensures that the counts variable is correctly handled as a NumPy array of floats, preventing the TypeError related to the log method.

Thank you for your attention to this matter.

Best regards