<commit_before>#!/usr/bin/env python

"""
Time encoding and decoding algorithms that make use of the
integrate-and-fire neuron model.

These functions make use of CUDA.

- iaf_decode            - IAF time decoding machine.
- iaf_encode            - IAF time encoding machine.

"""

__all__ = ['iaf_encode', 'iaf_decode']

from string import Template
from pycuda.compiler import SourceModule
import pycuda.gpuarray as gpuarray
import pycuda.driver as drv
import numpy as np
from numpy import ceil, inf
from scipy.signal import resample

import scikits.cuda.linalg as culinalg
import scikits.cuda.misc as cumisc

# Get installation location of C headers:
from scikits.cuda import install_headers

# Pseudoinverse singular value cutoff:
__pinv_rcond__ = 1e-6

# Kernel template for performing ideal/leaky IAF time encoding using a
# single encoder:
iaf_encode_mod_template = Template("""
#define USE_DOUBLE ${use_double}
#if USE_DOUBLE == 0
#define FLOAT float
#define EXP(x) expf(x)
#else
#define FLOAT double
#define EXP(x) exp(x)
#endif

// Nu must contain the length of u:
__global__ void iaf_encode(FLOAT *u, FLOAT *s,
                           unsigned int *i_s_0, FLOAT dt,
                           FLOAT b, FLOAT d,
                           FLOAT R, FLOAT C,
                           FLOAT *y_0, FLOAT *interval_0,
                           unsigned int use_trapz,
                           unsigned int Nu)
{
    unsigned int idx = threadIdx.x;

    FLOAT y;
    FLOAT interval;
    unsigned int i_s;
    FLOAT RC = R*C;
    unsigned int last;
    
    if (idx == 0) {
        y = y_0[0];
        interval = interval_0[0];
        i_s = i_s_0[0];           // index into spike array

        // Use the exponential Euler method when the neuron resistance
        // is not infinite:
        if ((use_trapz == 1) && isinf(R))
            last = Nu-1;
        else
            last = Nu;

        for (unsigned int i = 0; i < last; i++) {
            if isinf(R)
                if (use_trapz == 1)
                    y += dt*(b+(u[i]+u[i+1])/2)/C;
                else
                    y += dt*(b+u[i])/C;
            else
                y = y*EXP(-dt/RC)+R*(1.0-EXP(-dt/RC))*(b+u[i]);
            interval += dt;
            if (y >= d) {
                s[i_s] = interval;
                interval = 0;
                y -= d;
                i_s++;
            }
        }

        // Save the integrator and interval values for the next
        // iteration:
        y_0[0] = y;
        interval_0[0] = interval;
        i_s_0[0] = i_s;
    }                     
}
""")

def iaf_encode(u, dt, b, d, R=inf, C=1.0, dte=0.0, y=0.0, interval=0.0,
               quad_method='trapz', full_output=False):
    """
    IAF time encoding machine.
    
    Encode a finite length signal with an Integrate-and-Fire neuron.

    Parameters
    ----------
    u : array_like of floats
        Signal to encode.
    dt : float
        Sampling resolution of input signal; the sampling frequency
        is 1/dt Hz.
    b : float
        Encoder bias.
    d : float
        Encoder threshold.
    R : float
        Neuron resistance.
    C : float
        Neuron capacitance.
    dte : float
        Sampling resolution assumed by the encoder (s).
        This may not exceed `dt`.
    y : float
        Initial value of integrator.
    interval : float
        Time since last spike (in s).
    quad_method : {'rect', 'trapz'}
        Quadrature method to use (rectangular or trapezoidal) when the
        neuron is ideal; exponential Euler integration is used
        when the neuron is leaky.
    full_output : bool
        If set, the function returns the encoded data block followed
        by the given parameters (with updated values for `y` and `interval`).
        This is useful when the function is called repeatedly to
        encode a long signal.

    Returns
    -------
    s : ndarray of floats
        If `full_output` == False, returns the signal encoded as an
        array of time intervals between spikes.
    [s, dt, b, d, R, C, dte, y, interval, quad_method, full_output] : list
        If `full_output` == True, returns the encoded signal
        followed by updated encoder parameters.
        
    Notes
    -----
    When trapezoidal integration is used, the value of the integral
    will not be computed for the very last entry in `u`.

    """

    # Input sanity check:
    float_type = u.dtype.type
    if float_type == np.float32:
        use_double = 0
    elif float_type == np.float64:
        use_double = 1
    else:
        raise ValueError('unsupported data type')

    # Handle empty input:
    Nu = len(u)
    if Nu == 0:
        if full_output:
            return array((),float), dt, b, d, R, C, dte, y, interval, \
                   quad_method, full_output
        else:
            return array((),float)
    
    # Check whether the encoding resolution is finer than that of the<commit_msg>Rename variables in IAF encoder CUDA kernel.<commit_after>#!/usr/bin/env python

"""
Time encoding and decoding algorithms that make use of the
integrate-and-fire neuron model.

These functions make use of CUDA.

- iaf_decode            - IAF time decoding machine.
- iaf_encode            - IAF time encoding machine.

"""

__all__ = ['iaf_encode', 'iaf_decode']

from string import Template
from pycuda.compiler import SourceModule
import pycuda.gpuarray as gpuarray
import pycuda.driver as drv
import numpy as np
from numpy import ceil, inf
from scipy.signal import resample

import scikits.cuda.linalg as culinalg
import scikits.cuda.misc as cumisc

# Get installation location of C headers:
from scikits.cuda import install_headers

# Pseudoinverse singular value cutoff:
__pinv_rcond__ = 1e-6

# Kernel template for performing ideal/leaky IAF time encoding using a
# single encoder:
iaf_encode_mod_template = Template("""
#define USE_DOUBLE ${use_double}
#if USE_DOUBLE == 0
#define FLOAT float
#define EXP(x) expf(x)
#else
#define FLOAT double
#define EXP(x) exp(x)
#endif

// u: input signal
// s: returned array of spike times
// ns: initial length of spike train
// dt: time resolution
// b: neuron biases
// d: neuron thresholds
// R: neuron resistances
// C: neuron capacitances
// y: initial value of integrator
// interval: initial value of the neuron time interval
// use_trapz: use trapezoidal integration if set to 1
// Nu: length of u:
__global__ void iaf_encode(FLOAT *u, FLOAT *s,
                           unsigned int *ns, FLOAT dt,
                           FLOAT b, FLOAT d,
                           FLOAT R, FLOAT C,
                           FLOAT *y, FLOAT *interval,
                           unsigned int use_trapz,
                           unsigned int Nu)
{
    unsigned int idx = threadIdx.x;

    FLOAT y_curr, interval_curr;
    unsigned int ns_curr, last;
    FLOAT RC = R*C;
    
    if (idx == 0) {
        y_curr = y[0];
        interval_curr = interval[0];
        ns_curr = ns[0];

        // Use the exponential Euler method when the neuron resistance
        // is not infinite:
        if ((use_trapz == 1) && isinf(R))
            last = Nu-1;
        else
            last = Nu;

        for (unsigned int i = 0; i < last; i++) {
            if isinf(R)
                if (use_trapz == 1)
                    y_curr += dt*(b+(u[i]+u[i+1])/2)/C;
                else
                    y_curr += dt*(b+u[i])/C;
            else
                y_curr = y_curr*EXP(-dt/RC)+R*(1.0-EXP(-dt/RC))*(b+u[i]);
            interval_curr += dt;
            if (y_curr >= d) {
                s[ns_curr] = interval_curr;
                interval_curr = 0;
                y_curr -= d;
                ns_curr++;
            }
        }

        // Save the integrator and interval values for the next
        // iteration:
        y[0] = y_curr;
        interval[0] = interval_curr;
        ns[0] = ns_curr;
    }                     
}
""")

def iaf_encode(u, dt, b, d, R=inf, C=1.0, dte=0.0, y=0.0, interval=0.0,
               quad_method='trapz', full_output=False):
    """
    IAF time encoding machine.
    
    Encode a finite length signal with an Integrate-and-Fire neuron.

    Parameters
    ----------
    u : array_like of floats
        Signal to encode.
    dt : float
        Sampling resolution of input signal; the sampling frequency
        is 1/dt Hz.
    b : float
        Encoder bias.
    d : float
        Encoder threshold.
    R : float
        Neuron resistance.
    C : float
        Neuron capacitance.
    dte : float
        Sampling resolution assumed by the encoder (s).
        This may not exceed `dt`.
    y : float
        Initial value of integrator.
    interval : float
        Time since last spike (in s).
    quad_method : {'rect', 'trapz'}
        Quadrature method to use (rectangular or trapezoidal) when the
        neuron is ideal; exponential Euler integration is used
        when the neuron is leaky.
    full_output : bool
        If set, the function returns the encoded data block followed
        by the given parameters (with updated values for `y` and `interval`).
        This is useful when the function is called repeatedly to
        encode a long signal.

    Returns
    -------
    s : ndarray of floats
        If `full_output` is false, returns the signal encoded as an
        array of interspike intervals.
    [s, dt, b, d, R, C, dte, y, interval, quad_method, full_output] : list
        If `full_output` is true, returns the encoded signal
        followed by updated encoder parameters.
        
    Notes
    -----
    When trapezoidal integration is used, the value of the integral
    will not be computed for the very last entry in `u`.

    """

    # Input sanity check:
    float_type = u.dtype.type
    if float_type == np.float32:
        use_double = 0
    elif float_type == np.float64:
        use_double = 1
    else:
        raise ValueError('unsupported data type')

    # Handle empty input:
    Nu = len(u)
    if Nu == 0:
        if full_output:
            return array((),float), dt, b, d, R, C, dte, y, interval, \
                   quad_method, full_output
        else:
            return array((),float)
    
    # Check whether the encoding resolution is finer than that of the
{'fraction_non_alphanumeric': 0.09008570315543436, 'fraction_numerical': 0.007791195948578107, 'mean_word_length': 1.862838026205743, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1741111', 'n_tokens_mistral': 3204, 'n_tokens_neox': 3032, 'n_words': 1108}