Skip to content

[Feature] Function to merge analogsignals #830

@morales-gregorio

Description

@morales-gregorio

Hey all,

I wrote the following function to merge analogsignals, because I needed it. The function is thought to be memory efficient, and thus systematically deletes the data that has been duplicated.

If you think this function can find a home somewhere in the neo codebase, let me know where and I can create a corresponding test and PR it.

def merge_anasiglist(anasiglist):
    """
    Merges neo.AnalogSignal objects into a single object.

    Units, sampling_rate, t_start, t_stop and signals shape must be the same
    for all signals. Otherwise a ValueError is raised.

    Parameters
    ----------
    anasiglist: list of neo.AnalogSignal
        list of analogsignals that will be merged

    Returns
    -------
    merged_anasig: neo.AnalogSignal
        merged output signal
    """
    # Check units, sampling_rate, t_start, t_stop and signal shape
    for anasig in anasiglist:
        if not anasiglist[0].units == anasig.units:
            raise ValueError('Units must be the same for all signals')
        if not anasiglist[0].sampling_rate == anasig.sampling_rate:
            raise ValueError('Sampling rate must be the same for all signals')
        if not anasiglist[0].t_start == anasig.t_start:
            raise ValueError('t_start must be the same for all signals')
        if not anasiglist[0].t_stop == anasig.t_stop:
            raise ValueError('t_stop must be the same for all signals')
        if not anasiglist[0].magnitude.shape == anasig.magnitude.shape:
            raise ValueError('All signals must have the same shape')

    # Initialize the arrays
    anasig0 = anasiglist.pop(0)
    data_array = anasig0.magnitude
    sr = anasig0.sampling_rate
    t_start = anasig0.t_start
    t_stop = anasig0.t_stop
    units = anasig0.units

    # Get the full array annotations
    for anasig in anasiglist:
        anasig0.array_annotations = anasig0._merge_array_annotations(anasig)

    array_annot = anasig0.array_annotations
    del anasig0

    while len(anasiglist) != 0:
        anasig = anasiglist.pop(0)
        data_array = np.concatenate((data_array, anasig.magnitude),
                                    axis=np.argmin(anasig.magnitude.shape))
        del anasig

    merged_anasig = neo.AnalogSignal(data_array,
                                     sampling_rate=sr,
                                     t_start=t_start,
                                     t_stop=t_stop,
                                     units=units,
                                     array_annotations=array_annot)
    return merged_anasig

Cheers!
Aitor

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions