elephant icon indicating copy to clipboard operation
elephant copied to clipboard

[Bug] Underflow: Negative value in van_rossum_distance function

Open xxcStella opened this issue 1 month ago • 1 comments

Describe the bug

When uses the van_rossum_distance funtion in elephant.spike_train_dissimilarity, it may generate "nan" result and give error like "RuntimeWarning: invalid value encountered in sqrt return np.sqrt(XXX"). This is because there is no zero-checking function before squaring root, making it possible to square root an extremely small number (e.g. 1e-16).

To Reproduce

  1. Give a spike train with small values:
  import neo, quantities as pq
  from elephant.spike_train_dissimilarity import van_rossum_distance

  tau = 0.1 * pq.s
  a = neo.SpikeTrain([0.1782, 0.2286, 0.2804, 0.4972, 0.5504]*pq.s, t_start=0*pq.s, t_stop=4*pq.s)
  print(van_rossum_distance([a, a], tau)[0, 1])
nan
RuntimeWarning: invalid value encountered in sqrt return np.sqrt(vr_dist)

Expected behavior

In theory, the result should be 0. But the value is nan and the code gives error: RuntimeWarning: invalid value encountered in sqrt return np.sqrt(vr_dist)

Solution Before the return in van_rossum_distance function, add vr_dist[vr_dist < 0] = 0.0. This can clip any value lower than 0.

Environment

  • OS: Windows 11
  • How you installed elephant (conda, pip, source): pip
  • Python version: 3.8.20
  • neo python package version: 0.13.3
  • elephant python package version: 1.1.1 (latest)

xxcStella avatar Nov 19 '25 17:11 xxcStella

Hey @xxcStella , Thank you for reporting the issue and the example. I was able to reproduce the error as well. Also appreciate your suggested solution. At this point, we'll review the best way to handle it while keeping the results transparent. Thanks again for bringing this up, and I'll update the issue once we have a plan.

CozySocksAlways avatar Nov 20 '25 12:11 CozySocksAlways