return minimum, average, maximum of the signal peak
170394
def getSignalParameters(fitParams, n_std=3):
    '''
    
    '''
    signal = getSignalPeak(fitParams)
    mx = signal[1] + n_std * signal[2]
    mn = signal[1] - n_std * signal[2]
    if mn < fitParams[0][1]:
        mn = fitParams[0][1]  # set to bg
    return mn, signal[1], mx
567326
def get_waveform_amplitude(mean_masks, mean_waveforms):
    """"""

    assert mean_waveforms.ndim == 2
    n_samples, n_channels = mean_waveforms.shape

    assert mean_masks.ndim == 1
    assert mean_masks.shape == (n_channels,)

    mean_waveforms = mean_waveforms * mean_masks
    assert mean_waveforms.shape == (n_samples, n_channels)

    # Amplitudes.
    m, M = mean_waveforms.min(axis=0), mean_waveforms.max(axis=0)
    return M - m
255886
def getoptT(X, W, Y, Z, S, M_E, E, m0, rho):
    ''' 
    '''
    iter_max = 20
    norm2WZ = np.linalg.norm(W, ord='fro')**2 + np.linalg.norm(Z, ord='fro')**2
    f = np.zeros(iter_max + 1)
    f[0] = F_t(X, Y, S, M_E, E, m0, rho)

    t = -1e-1
    for i in range(iter_max):
        f[i + 1] = F_t(X + t * W, Y + t * Z, S, M_E, E, m0, rho)

        if f[i + 1] - f[0] <= 0.5 * t * norm2WZ:
            return t
        t /= 2
    return t
1049142
def _calc_damping_min(self):
        """"""
        return ((0.8005 + 0.0129 * self._plas_index * self._ocr ** -0.1069) *
                (self._stress_mean * KPA_TO_ATM)
                ** -0.2889 * (1 + 0.2919 * np.log(self._freq))) / 100
1056661
def calc_signal_power(params):

    '''
    

    '''

    for i, data_type in enumerate(['CSD','LFP','CSD_10_0', 'LFP_10_0']):
        if i % SIZE == RANK:

            # Load data
            if data_type in ['CSD','LFP']:
                fname=os.path.join(params.savefolder, data_type+'sum.h5')
            else:
                fname=os.path.join(params.populations_path, 'subsamples',
                                   str.split(data_type,'_')[0] + 'sum_' +
                                   str.split(data_type,'_')[1] + '_' +
                                   str.split(data_type,'_')[2] + '.h5')
            #open file
            f = h5py.File(fname)
            data = f['data'].value
            srate = f['srate'].value 
            tvec = np.arange(data.shape[1]) * 1000. / srate
        
            # slice
            slica = (tvec >= ana_params.transient)
            data = data[:,slica]
    
            # subtract mean
            dataT = data.T - data.mean(axis=1)
            data = dataT.T
            f.close()
    
            #extract PSD
            PSD=[]
            for i in np.arange(len(params.electrodeParams['z'])):
                if ana_params.mlab:
                    Pxx, freqs=plt.mlab.psd(data[i], NFFT=ana_params.NFFT,
                                        Fs=srate, noverlap=ana_params.noverlap,
                                        window=ana_params.window)
                else:
                    [freqs, Pxx] = hlp.powerspec([data[i]], tbin= 1.,
                                             Df=ana_params.Df, pointProcess=False)
                    mask = np.where(freqs >= 0.)
                    freqs = freqs[mask]
                    Pxx = Pxx.flatten()
                    Pxx = Pxx[mask]
                    Pxx = Pxx/tvec[tvec >= ana_params.transient].size**2
                PSD +=[Pxx.flatten()]
                
            PSD=np.array(PSD)
    
            # Save data
            f = h5py.File(os.path.join(params.savefolder, ana_params.analysis_folder,
                                       data_type + ana_params.fname_psd),'w')
            f['freqs']=freqs
            f['psd']=PSD
            f['transient']=ana_params.transient
            f['mlab']=ana_params.mlab
            f['NFFT']=ana_params.NFFT
            f['noverlap']=ana_params.noverlap
            f['window']=str(ana_params.window)
            f['Df']=str(ana_params.Df)
            f.close()

    return
200389
def get_signal_level(cell):
    

    signal = matching_line(cell, "Signal level=")
    if signal is None:
      return ""
    signal = signal.split("=")[1].split("/")
    if len(signal) == 2:
        return str(int(round(float(signal[0]) / float(signal[1]) * 100)))
    elif len(signal) == 1:
        return signal[0].split(' ')[0]
    else:
        return ""
1163746
def rms(signal, fs):
    
    # if a signal contains a some silence, taking the RMS of the whole
    # signal will be calculated as less loud as a signal without a silent
    # period. I don't like this, so I am going to chunk the signals, and
    # take the value of the most intense chunk
    chunk_time = 0.001  # 1 ms chunk
    chunk_samps = int(chunk_time * fs)
    amps = []
    if chunk_samps > 10:
        for i in range(0, len(signal) - chunk_samps, chunk_samps):
            amps.append(np.sqrt(np.mean(pow(signal[i:i + chunk_samps], 2))))
        amps.append(np.sqrt(np.mean(pow(signal[len(signal) - chunk_samps:], 2))))
        return np.amax(amps)
    else:
        # samplerate low, just rms the whole thing
        return np.sqrt(np.mean(pow(signal, 2)))
1101354
def min(self, default=None):
        
        return numpy.asscalar(numpy.min(self.values)) if self.values else default
1058041
def peak_interval(self, name, alpha=_alpha, npoints=_npoints, **kwargs):
        
        data = self.get(name, **kwargs)
        return peak_interval(data,alpha,npoints)
777449
def calc_spectrum(signal, rate):
    """"""
    npts = len(signal)
    padto = 1 << (npts - 1).bit_length()
    # print 'length of signal {}, pad to {}'.format(npts, padto)
    npts = padto

    sp = np.fft.rfft(signal, n=padto) / npts
    # print('sp len ', len(sp))
    freq = np.arange((npts / 2) + 1) / (npts / rate)
    # print('freq len ', len(freq))
    return freq, abs(sp)
83788
def max_or_none(val1, val2):
    """"""
    return max(val1, val2, key=lambda x: -sys.maxint if x is None else x)
560189
def _max(self):
        """"""
        return (
            self.range[1] if (self.range and self.range[1] is not None) else
            (max(self._values) if self._values else None)
        )
882449
def min(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs):
        
        axis = self._get_axis_number(axis) if axis is not None else 0
        data = self._validate_dtypes_min_max(axis, numeric_only)
        return data._reduce_dimension(
            data._query_compiler.min(
                axis=axis,
                skipna=skipna,
                level=level,
                numeric_only=numeric_only,
                **kwargs
            )
        )
708272
def shift_peaks(sig, peak_inds, search_radius, peak_up):
    
    sig_len = sig.shape[0]
    n_peaks = len(peak_inds)
    # The indices to shift each peak ind by
    shift_inds = np.zeros(n_peaks, dtype='int')

    # Iterate through peaks
    for i in range(n_peaks):
        ind = peak_inds[i]
        local_sig = sig[max(0, ind - search_radius):min(ind + search_radius, sig_len-1)]

        if peak_up:
            shift_inds[i] = np.argmax(local_sig)
        else:
            shift_inds[i] = np.argmin(local_sig)

    # May have to adjust early values
    for i in range(n_peaks):
        ind = peak_inds[i]
        if ind >= search_radius:
            break
        shift_inds[i] -= search_radius - ind

    shifted_peak_inds = peak_inds + shift_inds - search_radius

    return shifted_peak_inds
1015547
def bbox(self):
        """"""
        xmin = min(self.start.real, self.end.real)
        xmax = max(self.start.real, self.end.real)
        ymin = min(self.start.imag, self.end.imag)
        ymax = max(self.start.imag, self.end.imag)
        return xmin, xmax, ymin, ymax
1228359
def calc_max_min(ss):
    "
    xmin, xmax, ymin, ymax = 1e38, -1e38, 1e38, -1e38
    for s in ss:
        assert isinstance(s, ft.Spectrum)
        if len(s.x) > 0:
            xmin, xmax = min(min(s.x), xmin), max(max(s.x), xmax)
            ymin, ymax = min(min(s.y), ymin), max(max(s.y), ymax)
    xspan = xmax-xmin
    yspan = ymax - ymin
    return xmin, xmax, ymin, ymax, xspan, yspan
392828
def signal_bursts():
    
    np.random.seed(815)
    length = 5 * 512

    # Baseline low frequency plus noise.
    data = np.sin(np.linspace(0, 80 * np.pi, length))
    noise = np.random.ranf(length)
    noise /= noise.max()
    noise /= 15
    data += noise

    # Double last two fifths of the signal.
    data[-2 * 512:] *= 2.0
    chirp1 = 2.5 * np.sin(np.linspace(0, 400 * np.pi, 512))
    chirp1 *= np.linspace(1, 0, 512)
    data[512:2 * 512] += chirp1

    # Add second transient signal.
    chirp2 = 5.0 * np.sin(np.linspace(0, 200 * np.pi, 512))
    chirp2 *= np.linspace(1, 0, 512)
    data[3 * 512:4 * 512] += chirp2

    return data