Skip to content

Make merging of Event, Epoch, SpikeTrainList and array annotations independent of how quantities handles np.concatenate #1978

Open

Description

@apdavison

Currently, np.concatenate and the functions built on it (np.hstack, np.vstack, np.stack, np.append) drop the units of Quantity arguments: they join the bare magnitudes, without converting units, and return a dimensionless result. Neo relies on this in several places by first rescaling the arguments to common units and then multiplying the result by those units:

  • neo/core/event.py:275
  • neo/core/epoch.py:324-325
  • neo/core/spiketrainlist.py:403
  • neo/core/dataobject.py:282
  • neo/core/spiketrain.py:978

for example

othertimes = other.times.rescale(self.times.units)
times = np.hstack([self.times, othertimes]) * self.times.units

python-quantities/python-quantities#293 (planned for quantities 0.18.0) makes these functions keep the units, converting all the arguments to the units of the first. With that change, the result above becomes ms**2, and test_Epoch_merge, test_Event_merge and TestSpikeTrainList::test_multiplexed fail.

A form that works with both behaviours, and doesn't depend on rescaling earlier, is to convert explicitly and stack the magnitudes:

units = self.times.units
times = np.hstack([self.times.magnitude, other.times.rescale(units).magnitude]) * units

There is also an existing bug in SpikeTrain.merge() (neo/core/spiketrain.py:976-978):

other_ann = np.concatenate([deepcopy(other.array_annotations[key]) for other in others])
if isinstance(self_ann, pq.Quantity):
    other_ann.rescale(self_ann.units)
    arr_ann = np.concatenate([self_ann, other_ann]) * self_ann.units

The result of rescale() is discarded, so array annotations from others are joined with no unit conversion and then labelled with the units of self_ann. For example, merging a quantity annotation of 1 * pq.s with one of 500 * pq.ms gives [1, 500] s. The first np.concatenate has the same problem when the others have different units from each other. The explicit form above fixes this too.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions