jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def test_structured_arrays(self):
        a, b = self.a, self.b
        dt = [('', 'i'), ('', 'i')]
        aa = np.array(list(zip(a, a)), dt)
        bb = np.array(list(zip(b, b)), dt)
        with suppress_warnings() as sup:
            sup.filter(DeprecationWarning)
            v = stats.itemfreq(aa)
        # Arrays don't compare equal because v[:,0] is object array
        assert_equal(tuple(v[2, 0]), tuple(bb[2]))
//  [python]
def test_structured_arrays(self):
        a, b = self.a, self.b
        dt = [('', 'i'), ('', 'i')]
        aa = np.array(list(zip(a, a)), dt)
        bb = np.array(list(zip(b, b)), dt)
        with suppress_warnings() as sup:
            sup.filter(DeprecationWarning)
            v = stats.binned_statistic(aa, aa, statistic='count')
        # Arrays don't compare equal because v[:,0] is object array
        assert_equal(tuple(v[2, 0]), tuple(bb[2]))
//  [python]
def cross_entropy_loss_weighted(output, labels):

    temp = labels.data.cpu().numpy()
    freqCount = scipystats.itemfreq(temp)
    total = freqCount[0][1]+freqCount[1][1]
    perc_1 = freqCount[1][1]/total
    perc_0 = freqCount[0][1]/total

    weight_array = [perc_1, perc_0]

    if torch.cuda.is_available():
        weight_tensor = torch.FloatTensor(weight_array).cuda()
    else:
        weight_tensor = torch.FloatTensor(weight_array)

    ce_loss = nn.CrossEntropyLoss(weight=weight_tensor)
    images, channels, height, width = output.data.shape
    loss = ce_loss(output, labels.long().view(images, height, width))
    return loss
//  [python]
def cross_entropy_loss_weighted(output, labels):

    temp = labels.data.cpu().numpy()
    freqCount = scipy.stats.binned_statistic(temp, temp, statistic='count', bins=2)
    total = freqCount[0][0]+freqCount[0][1]
    perc_1 = freqCount[0][1]/total
    perc_0 = freqCount[0][0]/total

    weight_array = [perc_1, perc_0]

    if torch.cuda.is_available():
        weight_tensor = torch.FloatTensor(weight_array).cuda()
    else:
        weight_tensor = torch.FloatTensor(weight_array)

    ce_loss = nn.CrossEntropyLoss(weight=weight_tensor)
    images, channels, height, width = output.data.shape
    loss = ce_loss(output, labels.long().view(images, height, width))
    return loss
//  [python]
def spectrogram(sig, rate, shape=(64, 384), win_len=512, fmin=150, fmax=15000, frequency_scale='mel', magnitude_scale='nonlinear', bandpass=True):

    # Compute overlap
    hop_len = int(len(sig) / (shape[1] - 1)) 
    win_overlap = win_len - hop_len + 2
    #print('WIN_LEN:', win_len, 'HOP_LEN:', hop_len, 'OVERLAP:', win_overlap)

    # Adjust N_FFT?
    if frequency_scale == 'mel':
        n_fft = win_len
    else:
        n_fft = shape[1] * 2

    # Bandpass filter?
    if bandpass:
        sig = applyBandpassFilter(sig, rate, fmin, fmax)

    # Compute spectrogram
    f, t, spec = scipy.signal.spectrogram(sig,
                                          fs=rate,
                                          window=scipy.signal.hanning(win_len),
                                          nperseg=win_len,
                                          noverlap=win_overlap,
                                          nfft=n_fft,
                                          detrend=False,
                                          mode='magnitude')

    # Scale frequency?
    if frequency_scale == 'mel':

        # Determine the indices of where to clip the spec
        valid_f_idx_start = f.searchsorted(fmin, side='left')
        valid_f_idx_end = f.searchsorted(fmax, side='right') - 1

        # Get mel filter banks
        mel_filterbank, mel_f = getMelFilterbank(shape[0], fmin, fmax, f, dtype=spec.dtype)

        # Clip to non-zero range so that unnecessary multiplications can be avoided
        mel_filterbank = mel_filterbank[valid_f_idx_start:(valid_f_idx_end + 1), :]

        # Clip the spec representation and apply the mel filterbank.
        # Due to the nature of np.dot(), the spec needs to be transposed prior, and reverted after
        spec = np.transpose(spec[valid_f_idx_start:(valid_f_idx_end + 1), :], [1, 0])
        spec = np.dot(spec, mel_filterbank)
        spec = np.transpose(spec, [1, 0])        

    # Magnitude transformation
    if magnitude_scale == 'pcen':
        
        # Convert scale using per-channel energy normalization as proposed by Wang et al., 2017
        # We adjust the parameters for bird voice recognition based on Lostanlen, 2019
        spec = pcen(spec, rate, hop_len)
        
    elif magnitude_scale == 'log':
        
        # Convert power spec to dB scale (compute dB relative to peak power)
        spec = spec ** 2
        spec = 10.0 * np.log10(np.maximum(1e-10, spec) / np.max(spec))
        spec = np.maximum(spec, spec.max() - 100) # top_db = 100

    elif magnitude_scale == 'nonlinear':

        # Convert magnitudes using nonlinearity as proposed by Schlüter, 2018
        a = -1.2 # Higher values yield better noise suppression
        s = 1.0 / (1.0 + np.exp(-a))
        spec = spec ** s

    # Flip spectrum vertically (only for better visialization, low freq. at bottom)
    spec = spec[::-1, ...]

    # Trim to desired shape if too large
    spec = spec[:shape[0], :shape[1]]

    # Normalize values between 0 and 1
    spec -= spec.min()
    if not spec.max() == 0:
        spec /= spec.max()
    else:
        spec = np.clip(spec, 0, 1)

    return spec
//  [python]
def spectrogram(sig, rate, shape=(64, 384), win_len=512, fmin=150, fmax=15000, frequency_scale='mel', magnitude_scale='nonlinear', bandpass=True):

    # Compute overlap
    hop_len = int(len(sig) / (shape[1] - 1)) 
    win_overlap = win_len - hop_len + 2
    #print('WIN_LEN:', win_len, 'HOP_LEN:', hop_len, 'OVERLAP:', win_overlap)

    # Adjust N_FFT?
    if frequency_scale == 'mel':
        n_fft = win_len
    else:
        n_fft = shape[1] * 2

    # Bandpass filter?
    if bandpass:
        sig = applyBandpassFilter(sig, rate, fmin, fmax)

    # Compute spectrogram
    f, t, spec = scipy.signal.spectrogram(sig,
                                          fs=rate,
                                          window=scipy.signal.windows.hann(win_len),
                                          nperseg=win_len,
                                          noverlap=win_overlap,
                                          nfft=n_fft,
                                          detrend=False,
                                          mode='magnitude')

    # Scale frequency?
    if frequency_scale == 'mel':

        # Determine the indices of where to clip the spec
        valid_f_idx_start = f.searchsorted(fmin, side='left')
        valid_f_idx_end = f.searchsorted(fmax, side='right') - 1

        # Get mel filter banks
        mel_filterbank, mel_f = getMelFilterbank(shape[0], fmin, fmax, f, dtype=spec.dtype)

        # Clip to non-zero range so that unnecessary multiplications can be avoided
        mel_filterbank = mel_filterbank[valid_f_idx_start:(valid_f_idx_end + 1), :]

        # Clip the spec representation and apply the mel filterbank.
        # Due to the nature of np.dot(), the spec needs to be transposed prior, and reverted after
        spec = np.transpose(spec[valid_f_idx_start:(valid_f_idx_end + 1), :], [1, 0])
        spec = np.dot(spec, mel_filterbank)
        spec = np.transpose(spec, [1, 0])        

    # Magnitude transformation
    if magnitude_scale == 'pcen':
        
        # Convert scale using per-channel energy normalization as proposed by Wang et al., 2017
        # We adjust the parameters for bird voice recognition based on Lostanlen, 2019
        spec = pcen(spec, rate, hop_len)
        
    elif magnitude_scale == 'log':
        
        # Convert power spec to dB scale (compute dB relative to peak power)
        spec = spec ** 2
        spec = 10.0 * np.log10(np.maximum(1e-10, spec) / np.max(spec))
        spec = np.maximum(spec, spec.max() - 100) # top_db = 100

    elif magnitude_scale == 'nonlinear':

        # Convert magnitudes using nonlinearity as proposed by Schlüter, 2018
        a = -1.2 # Higher values yield better noise suppression
        s = 1.0 / (1.0 + np.exp(-a))
        spec = spec ** s

    # Flip spectrum vertically (only for better visialization, low freq. at bottom)
    spec = spec[::-1, ...]

    # Trim to desired shape if too large
    spec = spec[:shape[0], :shape[1]]

    # Normalize values between 0 and 1
    spec -= spec.min()
    if not spec.max() == 0:
        spec /= spec.max()
    else:
        spec = np.clip(spec, 0, 1)

    return spec
//  [python]
def test_object_arrays(self):
        a, b = self.a, self.b
        dt = 'O'
        aa = np.empty(len(a), dt)
        aa[:] = a
        bb = np.empty(len(b), dt)
        bb[:] = b
        v = stats.itemfreq(aa)
        assert_array_equal(v[:, 0], bb)
//  [python]
def test_object_arrays(self):
        a, b = self.a, self.b
        dt = 'O'
        aa = np.empty(len(a), dt)
        aa[:] = a
        bb = np.empty(len(b), dt)
        bb[:] = b
        v = stats.binned_statistic(aa, aa, statistic='count')
        assert_array_equal(v[0], bb)
//  [python]
def test_numeric_types(self):
        # Check itemfreq works for all dtypes (adapted from np.unique tests)
        def _check_itemfreq(dt):
            a = np.array(self.a, dt)
            v = stats.itemfreq(a)
            assert_array_equal(v[:, 0], [1, 2, 5, 7])
            assert_array_equal(v[:, 1], np.array([20, 10, 20, 20], dtype=dt))

        dtypes = [np.int32, np.int64, np.float32, np.float64,
                  np.complex64, np.complex128]
        for dt in dtypes:
            yield _check_itemfreq, dt
//  [python]
def test_numeric_types(self):
        # Check itemfreq works for all dtypes (adapted from np.unique tests)
        def _check_itemfreq(dt):
            a = np.array(self.a, dt)
            v = stats.binned_statistic(a, a, statistic='count', bins=np.arange(min(a)-0.5,max(a)+1.5))
            assert_array_equal(v[0], [1, 2, 5, 7])
            assert_array_equal(v[1], np.array([20, 10, 20, 20], dtype=dt))

        dtypes = [np.int32, np.int64, np.float32, np.float64,
                  np.complex64, np.complex128]
        for dt in dtypes:
            yield _check_itemfreq, dt
//  [python]
def cadzow_np1(
    wav,
    fs=30000,
    rank=5,
    niter=1,
    fmax=7500,
    h=None,
    ovx=int(16),
    nswx=int(32),
    npad=int(0),
):
    """
    Apply Fxy rank-denoiser to a full recording of Neuropixel 1 probe geometry
    ntr - nswx has to be a multiple of (nswx - ovx)
    Examples of working set of parameters:
        ovx = int(5); nswx = int(33); ovx = int(6))
        ovx = int(16); nswx = int(32); ovx = int(0))
        ovx = int(32); nswx = int(64); ovx = int(0))
        ovx = int(24); nswx = int(64); ovx = int(0))
        ovx = int(8); nswx = int(16); ovx = int(0))
    :param wav: ntr, ns
    :param fs:
    :param ovx is the overlap in x
    :param nswx is the size of the window in x
    :param npad is the padding
    :return:
    """
    #
    ntr, ns = wav.shape
    h = h or neuropixel.trace_header(version=1)
    nwinx = int(np.ceil((ntr + npad * 2 - ovx) / (nswx - ovx)))
    fscale = scipy.fft.rfftfreq(ns, d=1 / fs)
    imax = np.searchsorted(fscale, fmax)
    WAV = scipy.fft.rfft(wav[:, :])
    padgain = s.hanning(npad * 2)[:npad]
    WAV = np.r_[
        np.flipud(WAV[1: npad + 1, :]) * padgain[:, np.newaxis],
        WAV,
        np.flipud(WAV[-npad - 2: -1, :]) * np.flipud(np.r_[padgain, 1])[:, np.newaxis],
    ]  # apply padding
    x = np.r_[np.flipud(h["x"][1: npad + 1]), h["x"], np.flipud(h["x"][-npad - 2: -1])]
    y = np.r_[
        np.flipud(h["y"][1: npad + 1]) - 120,
        h["y"],
        np.flipud(h["y"][-npad - 2: -1]) + 120,
    ]
    WAV_ = np.zeros_like(WAV)
    gain = np.zeros(ntr + npad * 2 + 1)
    hanning = s.hanning(ovx * 2 - 1)[0:ovx]
    assert np.all(np.isclose(hanning + np.flipud(hanning), 1))
    gain_window = np.r_[hanning, np.ones(nswx - ovx * 2), np.flipud(hanning)]
    for firstx in np.arange(nwinx) * (nswx - ovx):
        lastx = int(firstx + nswx)
        if firstx == 0:
            gw = np.r_[hanning * 0 + 1, np.ones(nswx - ovx * 2), np.flipud(hanning)]
        elif lastx == ntr:
            gw = np.r_[hanning, np.ones(nswx - ovx * 2), hanning * 0 + 1]
        else:
            gw = gain_window
        gain[firstx:lastx] += gw
        array = WAV[firstx:lastx, :]
        array = denoise(
            array, x=x[firstx:lastx], y=y[firstx:lastx], r=rank, imax=imax, niter=niter
        )
        WAV_[firstx:lastx, :] += array * gw[:, np.newaxis]

    WAV_ = WAV_[npad: -npad - 1]  # remove padding
    wav_ = scipy.fft.irfft(WAV_)
    return wav_
//  [python]
def cadzow_np1(
    wav,
    fs=30000,
    rank=5,
    niter=1,
    fmax=7500,
    h=None,
    ovx=int(16),
    nswx=int(32),
    npad=int(0),
):
    """
    Apply Fxy rank-denoiser to a full recording of Neuropixel 1 probe geometry
    ntr - nswx has to be a multiple of (nswx - ovx)
    Examples of working set of parameters:
        ovx = int(5); nswx = int(33); ovx = int(6))
        ovx = int(16); nswx = int(32); ovx = int(0))
        ovx = int(32); nswx = int(64); ovx = int(0))
        ovx = int(24); nswx = int(64); ovx = int(0))
        ovx = int(8); nswx = int(16); ovx = int(0))
    :param wav: ntr, ns
    :param fs:
    :param ovx is the overlap in x
    :param nswx is the size of the window in x
    :param npad is the padding
    :return:
    """
    #
    ntr, ns = wav.shape
    h = h or neuropixel.trace_header(version=1)
    nwinx = int(np.ceil((ntr + npad * 2 - ovx) / (nswx - ovx)))
    fscale = scipy.fft.rfftfreq(ns, d=1 / fs)
    imax = np.searchsorted(fscale, fmax)
    WAV = scipy.fft.rfft(wav[:, :])
    padgain = scipy.signal.windows.hann(npad * 2)[:npad]
    WAV = np.r_[
        np.flipud(WAV[1: npad + 1, :]) * padgain[:, np.newaxis],
        WAV,
        np.flipud(WAV[-npad - 2: -1, :]) * np.flipud(np.r_[padgain, 1])[:, np.newaxis],
    ]  # apply padding
    x = np.r_[np.flipud(h["x"][1: npad + 1]), h["x"], np.flipud(h["x"][-npad - 2: -1])]
    y = np.r_[
        np.flipud(h["y"][1: npad + 1]) - 120,
        h["y"],
        np.flipud(h["y"][-npad - 2: -1]) + 120,
    ]
    WAV_ = np.zeros_like(WAV)
    gain = np.zeros(ntr + npad * 2 + 1)
    hanning = scipy.signal.windows.hann(ovx * 2 - 1)[0:ovx]
    assert np.all(np.isclose(hanning + np.flipud(hanning), 1))
    gain_window = np.r_[hanning, np.ones(nswx - ovx * 2), np.flipud(hanning)]
    for firstx in np.arange(nwinx) * (nswx - ovx):
        lastx = int(firstx + nswx)
        if firstx == 0:
            gw = np.r_[hanning * 0 + 1, np.ones(nswx - ovx * 2), np.flipud(hanning)]
        elif lastx == ntr:
            gw = np.r_[hanning, np.ones(nswx - ovx * 2), hanning * 0 + 1]
        else:
            gw = gain_window
        gain[firstx:lastx] += gw
        array = WAV[firstx:lastx, :]
        array = denoise(
            array, x=x[firstx:lastx], y=y[firstx:lastx], r=rank, imax=imax, niter=niter
        )
        WAV_[firstx:lastx, :] += array * gw[:, np.newaxis]

    WAV_ = WAV_[npad: -npad - 1]  # remove padding
    wav_ = scipy.fft.irfft(WAV_)
    return wav_
//  [python]
def test_structured_arrays(self):
        a, b = self.a, self.b
        dt = [('', 'i'), ('', 'i')]
        aa = np.array(list(zip(a, a)), dt)
        bb = np.array(list(zip(b, b)), dt)
        v = stats.itemfreq(aa)
        # Arrays don't compare equal because v[:,0] is object array
        assert_equal(tuple(v[2, 0]), tuple(bb[2]))
//  [python]
def test_structured_arrays(self):
        a, b = self.a, self.b
        dt = [('', 'i'), ('', 'i')]
        aa = np.array(list(zip(a, a)), dt)
        bb = np.array(list(zip(b, b)), dt)
        v = stats.binned_statistic(aa, aa, statistic='count')
        # Arrays don't compare equal because v[:,0] is object array
        assert_equal(tuple(v[2, 0]), tuple(bb[2]))
//  [python]
def freq_count(a, **kwargs):
    freq = scipy.stats.itemfreq(a)
    if 'classes' in kwargs:
        cls = kwargs['classes']
        x = pd.Series(zeros(cls.shape, dtype=int), index=cls)
    else:
        x = pd.Series(zeros(freq.shape[0]), index=freq[:, 0], dtype=int)

    for l in freq: x[l[0]] = l[1]
    return x
//  [python]
def freq_count(a, **kwargs):
    freq = scipy.stats.binned_statistic(a, a, statistic='count', bins=np.arange(min(a), max(a)+2)-0.5)[0]
    if 'classes' in kwargs:
        cls = kwargs['classes']
        x = pd.Series(zeros(cls.shape, dtype=int), index=cls)
    else:
        x = pd.Series(zeros(freq.shape[0]), index=np.arange(min(a), max(a)+1), dtype=int)

    for l in range(len(freq)): x[l+min(a)] = freq[l]
    return x
//  [python]
def confused_classes(out, labels):
        """
        print out probabilities for each class that it is confused with each other
        """
        import operator
        for pitch in np.unique(labels):
            inds = np.where(labels==pitch)[0]
            outs_type = out[inds]
            frequ = stats.itemfreq(outs_type)
            values = np.asarray(frequ[:,1]).astype(int)
            dictionary = dict(zip(frequ[:,0], (values/float(np.sum(values))*100).astype(int)))
            sorted_dic = sorted(dictionary.items(), key=operator.itemgetter(1), reverse=True)
            print(pitch,"percentage predicted as", sorted_dic)
//  [python]
def confused_classes(out, labels):
        """
        print out probabilities for each class that it is confused with each other
        """
        import operator
        for pitch in np.unique(labels):
            inds = np.where(labels==pitch)[0]
            outs_type = out[inds]
            frequ = np.bincount(outs_type)
            values = frequ[frequ>0]
            dictionary = dict(zip(np.nonzero(frequ)[0], (values/float(np.sum(values))*100).astype(int)))
            sorted_dic = sorted(dictionary.items(), key=operator.itemgetter(1), reverse=True)
            print(pitch,"percentage predicted as", sorted_dic)
//  [python]
def cut_csv_to_pitchers(cf):
        """
        Take csv cf, and return a shorter version that contains only the data of the 5 pitchers with most data
        (for pitch type simplification)
        """
        def get_list_with_most(cf, column):
            """
            Get list of player ids of the players with most data
            """
            pitcher = cf[column].values #.astype(int)
            statistic = sp.stats.itemfreq(pitcher) #.sort(axis = 0)
            #if column == "Pitch Type":
            #    print(statistic)
            number = np.array(statistic[:,1])
            a = b = []
            for i in range(5):
                maxi = np.argmax(number)
                a.append(statistic[maxi,0])
                number[maxi]=0
            return a, statistic

        player, _ = get_list_with_most(cf, "Pitcher")
        print(player)
        ind = []
        for p in player:
            ind += (np.where(cf["Pitcher"].values==p)[0]).tolist()
        return cf.iloc[ind]
//  [python]
def cut_csv_to_pitchers(cf):
        """
        Take csv cf, and return a shorter version that contains only the data of the 5 pitchers with most data
        (for pitch type simplification)
        """
        def get_list_with_most(cf, column):
            """
            Get list of player ids of the players with most data
            """
            pitcher = cf[column].values #.astype(int)
            statistic, bin_edges, bin_number = sp.stats.binned_statistic(pitcher, pitcher, statistic='count') #.sort(axis = 0)
            #if column == "Pitch Type":
            #    print(statistic)
            number = np.array(statistic)
            a = b = []
            for i in range(5):
                maxi = np.argmax(number)
                a.append(statistic[maxi])
                number[maxi]=0
            return a, statistic

        player, _ = get_list_with_most(cf, "Pitcher")
        print(player)
        ind = []
        for p in player:
            ind += (np.where(cf["Pitcher"].values==p)[0]).tolist()
        return cf.iloc[ind]
//  [python]
def frequencies(self):
        kos = []
        for solution in self.solutions:
            for ko in solution.knockout_list:
                kos.append(ko.id)

        return scipy.stats.itemfreq(kos)
//  [python]
def frequencies(self):
        kos = []
        for solution in self.solutions:
            for ko in solution.knockout_list:
                kos.append(ko.id)

        return scipy.stats.binned_statistic(kos, kos, statistic='count')
//  [python]
def accuracy_per_class(out_list, ground_truth_list):
        """
        calculate the accuracy for each class
        """
        out = np.array(out_list)
        ground_truth = np.array(ground_truth_list)
        same = out[np.where(out==ground_truth)[0]]
        right_frequency = stats.itemfreq(same)
        total_frequency = stats.itemfreq(ground_truth)
        right_dict = dict(zip(right_frequency[:,0], right_frequency[:,1]))
        total_dict = dict(zip(total_frequency[:,0], total_frequency[:,1]))

        acc= total_dict
        for types in total_dict.keys():
            try:
                acc[types] = (int(right_dict[types])/float(total_dict[types]))
            except KeyError:
                acc[types] = 0
        return acc
//  [python]
def accuracy_per_class(out_list, ground_truth_list):
        """
        calculate the accuracy for each class
        """
        out = np.array(out_list)
        ground_truth = np.array(ground_truth_list)
        same = out[np.where(out==ground_truth)[0]]
        right_frequency = np.unique(same, return_counts=True)
        total_frequency = np.unique(ground_truth, return_counts=True)
        right_dict = dict(zip(right_frequency[0], right_frequency[1]))
        total_dict = dict(zip(total_frequency[0], total_frequency[1]))

        acc= total_dict
        for types in total_dict.keys():
            try:
                acc[types] = (int(right_dict[types])/float(total_dict[types]))
            except KeyError:
                acc[types] = 0
        return acc
//  [python]
def testRPortDistribution(self):
        n_rport = 10
        nr_neurons = 20
        hf.nest.ResetKernel()
        neuron_model = 'iaf_psc_exp_multisynapse'
        neuron_dict = {'tau_syn': [0.1 + i for i in range(n_rport)]}
        self.pop1 = hf.nest.Create(neuron_model, nr_neurons, neuron_dict)
        self.pop2 = hf.nest.Create(neuron_model, nr_neurons, neuron_dict)
        syn_params = {'model': 'static_synapse'}
        syn_params['receptor_type'] = {
            'distribution': 'uniform_int', 'low': 1, 'high': n_rport}
        hf.nest.Connect(self.pop1, self.pop2, self.conn_dict, syn_params)
        M = hf.get_weighted_connectivity_matrix(
            self.pop1, self.pop2, 'receptor')
        M = hf.gather_data(M)
        if M is not None:
            M = M.flatten()
            frequencies = scipy.stats.itemfreq(M)
            self.assertTrue(np.array_equal(frequencies[:, 0], np.arange(
                1, n_rport + 1)), 'Missing or invalid rports')
            chi, p = scipy.stats.chisquare(frequencies[:, 1])
            self.assertGreater(p, self.pval)
//  [python]
def testRPortDistribution(self):
        n_rport = 10
        nr_neurons = 20
        hf.nest.ResetKernel()
        neuron_model = 'iaf_psc_exp_multisynapse'
        neuron_dict = {'tau_syn': [0.1 + i for i in range(n_rport)]}
        self.pop1 = hf.nest.Create(neuron_model, nr_neurons, neuron_dict)
        self.pop2 = hf.nest.Create(neuron_model, nr_neurons, neuron_dict)
        syn_params = {'model': 'static_synapse'}
        syn_params['receptor_type'] = {
            'distribution': 'uniform_int', 'low': 1, 'high': n_rport}
        hf.nest.Connect(self.pop1, self.pop2, self.conn_dict, syn_params)
        M = hf.get_weighted_connectivity_matrix(
            self.pop1, self.pop2, 'receptor')
        M = hf.gather_data(M)
        if M is not None:
            M = M.flatten()
            frequencies, bin_edges, bin_number = scipy.stats.binned_statistic(M, M, statistic='count', bins=range(n_rport+2))
            frequencies = frequencies[1:-1] #remove first and last element due to binning
            self.assertTrue(np.array_equal(np.arange(1, n_rport + 1), bin_edges[1:-1]), 'Missing or invalid rports')
            chi, p = scipy.stats.chisquare(frequencies)
            self.assertGreater(p, self.pval)
//  [python]
def check_ks(pop1, pop2, label, alpha, params):
    clipped_dists = ['exponential_clipped',
                     'gamma_clipped', 'lognormal_clipped']
    discrete_dists = ['binomial', 'poisson', 'uniform_int',
                      'binomial_clipped', 'poisson_clipped']
    M = get_weighted_connectivity_matrix(pop1, pop2, label)
    M = M.flatten()

    if params['distribution'] in discrete_dists:
        frequencies = scipy.stats.itemfreq(M)
        expected = get_expected_freqs(params, frequencies[:, 0], len(M))
        chi, p = scipy.stats.chisquare(frequencies[:, 1], expected)
    elif params['distribution'] in clipped_dists:
        D, p = scipy.stats.kstest(M, get_clipped_cdf(
            params), alternative='two-sided')
    else:
        if params['distribution'] == 'normal':
            distrib = scipy.stats.norm
            args = params['mu'], params['sigma']
        elif params['distribution'] == 'normal_clipped':
            distrib = scipy.stats.truncnorm
            args = (
                (params['low'] - params['mu']) /
                params['sigma'] if 'low' in params else -np.inf,
                (params['high'] - params['mu']) /
                params['sigma'] if 'high' in params else -np.inf,
                params['mu'],
                params['sigma']
            )
        elif params['distribution'] == 'exponential':
            distrib = scipy.stats.expon
            args = 0, 1. / params['lambda']
        elif params['distribution'] == 'gamma':
            distrib = scipy.stats.gamma
            args = params['order'], 0, params['scale']
        elif params['distribution'] == 'lognormal':
            distrib = scipy.stats.lognorm
            args = params['sigma'], 0, np.exp(params['mu'])
        elif params['distribution'] == 'uniform':
            distrib = scipy.stats.uniform
            args = params['low'], params['high'] - params['low']
        else:
            raise ValueError("{} distribution not supported.".format(
                params['distribution']))
        D, p = scipy.stats.kstest(
            M, distrib.cdf, args=args, alternative='two-sided')

    return p > alpha
//  [python]
def check_ks(pop1, pop2, label, alpha, params):
    clipped_dists = ['exponential_clipped',
                     'gamma_clipped', 'lognormal_clipped']
    discrete_dists = ['binomial', 'poisson', 'uniform_int',
                      'binomial_clipped', 'poisson_clipped']
    M = get_weighted_connectivity_matrix(pop1, pop2, label)
    M = M.flatten()

    if params['distribution'] in discrete_dists:
        frequencies, bin_edges = np.histogram(M, bins=np.arange(min(M), max(M) + 2))
        expected = get_expected_freqs(params, bin_edges[:-1], len(M))
        chi, p = scipy.stats.chisquare(frequencies, expected)
    elif params['distribution'] in clipped_dists:
        D, p = scipy.stats.kstest(M, get_clipped_cdf(
            params), alternative='two-sided')
    else:
        if params['distribution'] == 'normal':
            distrib = scipy.stats.norm
            args = params['mu'], params['sigma']
        elif params['distribution'] == 'normal_clipped':
            distrib = scipy.stats.truncnorm
            args = (
                (params['low'] - params['mu']) /
                params['sigma'] if 'low' in params else -np.inf,
                (params['high'] - params['mu']) /
                params['sigma'] if 'high' in params else -np.inf,
                params['mu'],
                params['sigma']
            )
        elif params['distribution'] == 'exponential':
            distrib = scipy.stats.expon
            args = 0, 1. / params['lambda']
        elif params['distribution'] == 'gamma':
            distrib = scipy.stats.gamma
            args = params['order'], 0, params['scale']
        elif params['distribution'] == 'lognormal':
            distrib = scipy.stats.lognorm
            args = params['sigma'], 0, np.exp(params['mu'])
        elif params['distribution'] == 'uniform':
            distrib = scipy.stats.uniform
            args = params['low'], params['high'] - params['low']
        else:
            raise ValueError("{} distribution not supported.".format(
                params['distribution']))
        D, p = scipy.stats.kstest(
            M, distrib.cdf, args=args, alternative='two-sided')

    return p > alpha
//  [python]
def _fit_binary(self, X, y):
        if self.mode == 'equal_width':
            # Compute probability of class 1 in each equal width bin
            binned_stat = np.histogram(x=X[:, 1], bins=self.n_bins, range=self.input_range, weights=np.equal(1, y))
            self.prob_class_1 = binned_stat[0] / binned_stat[0].sum()
            self.binning = binned_stat[1]
        elif self.mode == 'equal_freq':
            # Find binning based on equal frequency
            self.binning = np.quantile(X[:, 1],
                                       q=np.linspace(self.input_range[0], self.input_range[1], self.n_bins + 1))

            # Compute probability of class 1 in equal frequency bins
            digitized = np.digitize(X[:, 1], bins=self.binning)
            digitized[digitized == len(self.binning)] = len(self.binning) - 1  # include rightmost edge in partition
            self.prob_class_1 = [y[digitized == i].mean() for i in range(1, len(self.binning))]

        return self
//  [python]
def _fit_binary(self, X, y):
        if self.mode == 'equal_width':
            # Compute probability of class 1 in each equal width bin
            binned_stat = scipy.stats.binned_statistic(x=X[:, 1], values=np.equal(1, y), statistic='mean',
                                                       bins=self.n_bins, range=self.input_range)
            self.prob_class_1 = binned_stat.statistic
            self.binning = binned_stat.bin_edges
        elif self.mode == 'equal_freq':
            # Find binning based on equal frequency
            self.binning = np.quantile(X[:, 1],
                                       q=np.linspace(self.input_range[0], self.input_range[1], self.n_bins + 1))

            # Compute probability of class 1 in equal frequency bins
            digitized = np.digitize(X[:, 1], bins=self.binning)
            digitized[digitized == len(self.binning)] = len(self.binning) - 1  # include rightmost edge in partition
            self.prob_class_1 = [y[digitized == i].mean() for i in range(1, len(self.binning))]

        return self
//  [python]
def compute_graph_stats(episode_lengths, episode_rewards, timestamps, initial_reset_timestamp, buckets):
    """Method to compute the aggregates for the graphs."""
    # Not a dependency of OpenAI Gym generally.
    import scipy.stats

    num_episodes = len(episode_lengths)

    # Catch for if no files written which causes error with scipy.stats.binned_statistic
    if num_episodes == 0:
        return None

    episode_rewards = np.array(episode_rewards)
    episode_lengths = np.array(episode_lengths)

    # The index of the start of each episode
    x_timestep = np.cumsum(np.insert(episode_lengths, 0, 0))[:-1]
    assert len(x_timestep) == num_episodes

    # Delta since the beginning of time
    x_seconds = [timestamp - initial_reset_timestamp for timestamp in timestamps]

    # The index of each episode
    x_episode = range(num_episodes)

    # Calculate the appropriate x/y statistics
    x_timestep_y_reward = scipy.stats.binned_statistic(x_timestep, episode_rewards, 'mean', buckets)
    x_timestep_y_length = scipy.stats.binned_statistic(x_timestep, episode_lengths, 'mean', buckets)

    x_episode_y_reward = scipy.stats.binned_statistic(x_episode, episode_rewards, 'mean', buckets)
    x_episode_y_length = scipy.stats.binned_statistic(x_episode, episode_lengths, 'mean', buckets)

    x_seconds_y_reward = scipy.stats.binned_statistic(x_seconds, episode_rewards, 'mean', buckets)
    x_seconds_y_length = scipy.stats.binned_statistic(x_seconds, episode_lengths, 'mean', buckets)

    return {
        'initial_reset_timestamp': initial_reset_timestamp,
        'x_timestep_y_reward': graphable_binned_statistic(x_timestep_y_reward),
        'x_timestep_y_length': graphable_binned_statistic(x_timestep_y_length),
        'x_episode_y_reward': graphable_binned_statistic(x_episode_y_reward),
        'x_episode_y_length': graphable_binned_statistic(x_episode_y_length),
        'x_seconds_y_length': graphable_binned_statistic(x_seconds_y_length),
        'x_seconds_y_reward': graphable_binned_statistic(x_seconds_y_reward),
    }
//  [python]
def bin_spectrum(spectrum, bins=None, log=True, min=None, max=None, **kwargs):
    """
    Bin a spectrum, with log-spaced frequency bins.

    Parameters
    ----------
    spectrum : `specutils.Spectrum1D`
    log : bool
        If true, compute bin edges based on the log base 10 of
        the frequency.
    bins : int or ~numpy.ndarray
        Number of bins, or the bin edges

    Returns
    -------
    new_spectrum :
    """
    nirspec_wl_range = (spectrum.wavelength > min) & (spectrum.wavelength < max)

    wavelength = spectrum.wavelength[nirspec_wl_range]
    flux = spectrum.flux[nirspec_wl_range]

    if log:
        wl_axis = np.log10(wavelength.to(u.um).value)
    else:
        wl_axis = wavelength.to(u.um).value

    # Bin the power spectrum:
    bs = binned_statistic(
        wl_axis, flux.value,
        statistic=lambda y: spectral_binning(
            y, all_x=wl_axis, all_y=flux.value
        ),
        bins=bins
    )
    if log:
        wl_bins = 10 ** (
            0.5 * (bs.bin_edges[1:] + bs.bin_edges[:-1])
        ) * u.um
    else:
        wl_bins = (
            0.5 * (bs.bin_edges[1:] + bs.bin_edges[:-1])
        ) * u.um
    nans = np.isnan(bs.statistic)
    interp_fluxes = bs.statistic.copy()
    if np.any(nans) and all(
        map(lambda x: len(x) > 0, [wl_bins[nans], wl_bins[~nans], bs.statistic[~nans]])
    ):
        interp_fluxes[nans] = np.interp(wl_bins[nans], wl_bins[~nans], bs.statistic[~nans])
    return Spectrum1D(
        flux=interp_fluxes * flux.unit, spectral_axis=wl_bins, meta=spectrum.meta
    )
//  [python]
def _extract_lphi_spectra(
    data, phi, lamb,
    lphi=None, lphi_tol=None,
    databin=None, binning=None, nlamb=None,
):
    """ Extra several 1d spectra from 2d image at lphi """

    # --------------
    # Check input
    if lphi is None:
        lphi = False
    if lphi is False:
        lphi_tol = False
    if lphi is not False:
        lphi = np.atleast_1d(lphi).astype(float).ravel()
        lphi_tol = float(lphi_tol)

    if lphi is False:
        return False, False
    nphi = len(lphi)

    # --------------
    # Compute non-trivial cases

    if binning is False:
        if nlamb is None:
            nlamb = lamb.shape[1]
        lphi_lamb = np.linspace(lamb.min(), lamb.max(), nlamb+1)
        lphi_spectra = np.full((data.shape[0], lphi_lamb.size-1, nphi), np.nan)
        for ii in range(nphi):
            indphi = np.abs(phi - lphi[ii]) < lphi_tol
            lphi_spectra[:, ii, :] = s.binned_statistic(
                lamb[indphi], data[:, indphi], bins=lphi_lamb,
                statistic='mean', range=None,
            )[0]

    else:
        lphi_lamb = 0.5*(
            binning['lamb']['edges'][1:] + binning['lamb']['edges'][:-1]
        )
        lphi_phi = 0.5*(
            binning['phi']['edges'][1:] + binning['phi']['edges'][:-1]
        )
        lphi_spectra = np.full((data.shape[0], nphi, lphi_lamb.size), np.nan)
        lphi_spectra1 = np.full((data.shape[0], nphi, lphi_lamb.size), np.nan)
        for ii in range(nphi):
            datai = databin[:, np.abs(lphi_phi - lphi[ii]) < lphi_tol, :]
            iok = np.any(~np.isnan(datai), axis=1)
            for jj in range(datai.shape[0]):
                if np.any(iok[jj, :]):
                    lphi_spectra[jj, ii, iok[jj, :]] = np.nanmean(
                        datai[jj, :, iok[jj, :]],
                        axis=1,
                    )

    return lphi_spectra, lphi_lamb
//  [python]
def _extract_lphi_spectra(
    data, phi, lamb,
    lphi=None, lphi_tol=None,
    databin=None, binning=None, nlamb=None,
):
    """ Extra several 1d spectra from 2d image at lphi """

    # --------------
    # Check input
    if lphi is None:
        lphi = False
    if lphi is False:
        lphi_tol = False
    if lphi is not False:
        lphi = np.atleast_1d(lphi).astype(float).ravel()
        lphi_tol = float(lphi_tol)

    if lphi is False:
        return False, False
    nphi = len(lphi)

    # --------------
    # Compute non-trivial cases

    if binning is False:
        if nlamb is None:
            nlamb = lamb.shape[1]
        lphi_lamb = np.linspace(lamb.min(), lamb.max(), nlamb+1)
        lphi_spectra = np.full((data.shape[0], lphi_lamb.size-1, nphi), np.nan)
        for ii in range(nphi):
            indphi = np.abs(phi - lphi[ii]) < lphi_tol
            lphi_spectra[:, ii, :] = scpstats.binned_statistic(
                lamb[indphi], data[:, indphi], bins=lphi_lamb,
                statistic='mean', range=None,
            )[0]

    else:
        lphi_lamb = 0.5*(
            binning['lamb']['edges'][1:] + binning['lamb']['edges'][:-1]
        )
        lphi_phi = 0.5*(
            binning['phi']['edges'][1:] + binning['phi']['edges'][:-1]
        )
        lphi_spectra = np.full((data.shape[0], nphi, lphi_lamb.size), np.nan)
        lphi_spectra1 = np.full((data.shape[0], nphi, lphi_lamb.size), np.nan)
        for ii in range(nphi):
            datai = databin[:, np.abs(lphi_phi - lphi[ii]) < lphi_tol, :]
            iok = np.any(~np.isnan(datai), axis=1)
            for jj in range(datai.shape[0]):
                if np.any(iok[jj, :]):
                    lphi_spectra[jj, ii, iok[jj, :]] = np.nanmean(
                        datai[jj, :, iok[jj, :]],
                        axis=1,
                    )

    return lphi_spectra, lphi_lamb
//  [python]
def rebin_log(self, f=0.01):
        """
        Logarithmic rebin of the periodogram.
        The new frequency depends on the previous frequency
        modified by a factor f:

        dnu_j = dnu_{j-1}*(1+f)

        Parameters:
        -----------
        f: float, optional, default 0.01
            parameter that steers the frequency resolution


        Returns:
            binfreq: numpy.ndarray
                the binned frequencies
            binps: numpy.ndarray
                the binned powers
        """

        df = self.df
        minfreq = self.freq[0] - 0.5*df
        maxfreq = self.freq[-1]
        binfreq = [minfreq, minfreq + df]
        while binfreq[-1] <= maxfreq:
            binfreq.append(binfreq[-1] + df*(1.+f))
            df = binfreq[-1]-binfreq[-2]

        binps, bin_edges, binno = scipy.stats.binned_statistic(self.freq, self.ps, statistic="mean", bins=binfreq)

        nsamples = np.array([len(binno[np.where(binno == i)[0]]) for i in xrange(np.max(binno))])
        df = np.diff(binfreq)
        binfreq = binfreq[:-1]+df/2.
        return binfreq, binps, nsamples
//  [python]
def bin_vals(x, y, log=True):
    stat = "median" if log else "mean"
    hist, edges, _ = s.binned_statistic(x, y, statistic=stat, bins=100)
    mids = 0.5 * (edges[1:] + edges[:-1])
    return mids, hist
//  [python]
def bin_vals(x, y, log=True):
    stat = "median" if log else "mean"
    hist, edges, _ = stats.binned_statistic(x, y, statistic=stat, bins=100)
    mids = 0.5 * (edges[1:] + edges[:-1])
    return mids, hist
//  [python]
def calculate_hd_ratemap(self, hds, activations, statistic="mean"):
    hds = np.arctan2(np.sin(hds), np.cos(hds))
    total_bin_act = s.binned_statistic(
        hds,
        activations,
        bins=self._bins,
        statistic=statistic,
        range=(-np.pi, np.pi))[0]
    return total_bin_act
//  [python]
def calculate_hd_ratemap(self, hds, activations, statistic="mean"):
    hds = np.arctan2(np.sin(hds), np.cos(hds))
    total_bin_act = scipy.stats.binned_statistic(
        hds,
        activations,
        bins=self._bins,
        statistic=statistic,
        range=(-np.pi, np.pi))[0]
    return total_bin_act
//  [python]
def _bin_statistics(x, y, **params):
    """Divide ``x`` into bins and evaluate the mean and the standard deviation of the corresponding elements of ``y`` over each bin.

    Args:
        x (numpy.ndarray): Vector of data.
        y (numpy.ndarray): Vector of data associated with the vector ``x``.

    Keyword Args:
        params (dict): Keyword arguments (except ``"x"``, ``"values"`` and ``"statistic"``) of `scipy.stats.binned_statistic <https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.binned_statistic.html>`_.

    Returns:
        tuple(numpy.ndarray, numpy.ndarray, numpy.ndarray):

            - ``bin_centers``: Vector of centers of the bins associated to ``x``.
            - ``bin_mean``: Vector of means of ``y`` over the bins.
            - ``std_mean``: Vector of standard deviations of ``y`` over the bins.
    """
    bin_mean, bin_edges, _ = s.binned_statistic(x, y, statistic="mean", **params)
    bin_centers = np.convolve(bin_edges, np.ones(2), "valid")
    bin_centers /= 2
    count, _, _ = s.binned_statistic(x, y, statistic="count", **params)
    bin_std, _, _ = s.binned_statistic(x, y, statistic="std", **params)
    bin_std /= np.sqrt(count)
    return bin_centers, bin_mean, bin_std
//  [python]
def _bin_statistics(x, y, **params):
    """Divide ``x`` into bins and evaluate the mean and the standard deviation of the corresponding elements of ``y`` over each bin.

    Args:
        x (numpy.ndarray): Vector of data.
        y (numpy.ndarray): Vector of data associated with the vector ``x``.

    Keyword Args:
        params (dict): Keyword arguments (except ``"x"``, ``"values"`` and ``"statistic"``) of `scipy.stats.binned_statistic <https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.binned_statistic.html>`_.

    Returns:
        tuple(numpy.ndarray, numpy.ndarray, numpy.ndarray):

            - ``bin_centers``: Vector of centers of the bins associated to ``x``.
            - ``bin_mean``: Vector of means of ``y`` over the bins.
            - ``std_mean``: Vector of standard deviations of ``y`` over the bins.
    """
    bin_mean, bin_edges, _ = stats.binned_statistic(x, y, statistic="mean", **params)
    bin_centers = np.convolve(bin_edges, np.ones(2), "valid")
    bin_centers /= 2
    count, _, _ = stats.binned_statistic(x, y, statistic="count", **params)
    bin_std, _, _ = stats.binned_statistic(x, y, statistic="std", **params)
    bin_std /= np.sqrt(count)
    return bin_centers, bin_mean, bin_std
//  [python]
def get_enl_mode(enl_img: np.ndarray,
                 enl_min: int = 1,
                 enl_max: int = 20) -> float:
    """
    Put `enl_img` image into bins from enl_min, ... enl_max with intervals of
    .1 to find the maximum bin. Usually has one peak, but may wish to view the
    histogram.

    Parameters
    ----------
    enl_img : np.ndarray
        The image of per-pixel enl. Use the routine `get_enl_img`.
    enl_min : int
        The bottommost bin; must be greater than 1. Default is 1.
    enl_max : int
        The expected top most bin. Default is 20.

    Returns
    -------
    Float:
       The enl mode from the .1 bin.
    """
    if enl_min < 1:
        raise ValueError('enl_min must be > 1')

    data_ = enl_img[~np.isnan(enl_img)]

    int_max = int(np.ceil(data_.max()))
    data_max = min(int_max, enl_max)
    n_bins = (data_max - enl_min) * 10 + 1
    bins = np.linspace(enl_min, data_max, n_bins)

    result = np.histogram(data_, bins=bins)
    counts = result[0]
    return bins[np.argmax(counts)]
//  [python]
def get_enl_mode(enl_img: np.ndarray,
                 enl_min: int = 1,
                 enl_max: int = 20) -> float:
    """
    Put `enl_img` image into bins from enl_min, ... enl_max with intervals of
    .1 to find the maximum bin. Usually has one peak, but may wish to view the
    histogram.

    Parameters
    ----------
    enl_img : np.ndarray
        The image of per-pixel enl. Use the routine `get_enl_img`.
    enl_min : int
        The bottommost bin; must be greater than 1. Default is 1.
    enl_max : int
        The expected top most bin. Default is 20.

    Returns
    -------
    Float:
       The enl mode from the .1 bin.
    """
    if enl_min < 1:
        raise ValueError('enl_min must be > 1')

    data_ = enl_img[~np.isnan(enl_img)]

    int_max = int(np.ceil(data_.max()))
    data_max = min(int_max, enl_max)
    n_bins = (data_max - enl_min) * 10 + 1
    bins = np.linspace(enl_min, data_max, n_bins)

    result = scipy.stats.binned_statistic(data_,
                                          data_,
                                          statistic='count',
                                          bins=bins)
    counts = result.statistic
    return bins[np.argmax(counts)]
//  [python]
def fit_data(self, x, y, p0=None, bounds=None):
        #nParams=5
        ## Bounds
        #self.setup_bounds(bounds,nParams) # TODO
        ## Initial conditions
        #self.setup_guess(p0,bounds,nParams) # TODO

        # Cleaning data, and store it in object
        x,y=self.clean_data(x,y)

        I = np.argsort(x)
        x=x[I]
        y=y[I]

        # Estimating deltas
        xMin, xMax=np.min(x),np.max(x)
        yMin, yMax=np.min(y),np.max(y)
        DeltaX = (xMax-xMin)*0.02
        DeltaY = (yMax-yMin)*0.02

        # Binning data
        x_bin=np.linspace(xMin,xMax,min(200,len(x)))
        x_lin=x_bin[0:-1]+np.diff(x_bin)
        #y_lin=np.interp(x_lin,x,y) # TODO replace by bining
        y_lin = np.histogram(y, x_bin, weights=y)[0]/ np.histogram(y, x_bin)[0]
        y_lin, _, _ = stats.binned_statistic(x, y, statistic='mean', bins=x_bin)
        x_lin, _, _ = stats.binned_statistic(x, x, statistic='mean', bins=x_bin)
        bNaN=~np.isnan(y_lin)
        y_lin=y_lin[bNaN]
        x_lin=x_lin[bNaN]

        # --- Find good guess of parameters based on data
        # SpdGenOn
        iOn = np.where(y>0)[0][0]
        SpdGenOn_0    =  x[iOn]
        SpdGenOn_Bnds = (max(x[iOn]-DeltaX,xMin), min(x[iOn]+DeltaX,xMax))
        # Slpc
        Slpc_0    = 5
        Slpc_Bnds = (0,10)
        # RtTq
        RtTq_0    = yMax
        RtTq_Bnds = (yMax-DeltaY, yMax+DeltaY)
        # RtGnSp
        iCloseRt = np.where(y>yMax*0.50)[0][0]
        RtGnSp_0    = x[iCloseRt]
        RtGnSp_Bnds = ( RtGnSp_0 -DeltaX*2, RtGnSp_0+DeltaX*2)
        # Rgn2K
        #print('>>>',SpdGenOn_0, RtGnSp_0)
        bR2=np.logical_and(x>SpdGenOn_0, x<RtGnSp_0)
        exponents=[2]
        _, pfit, _ = fit_polynomial_discrete(x[bR2], y[bR2], exponents)
        #print(pfit)
        Rgn2K_0   =pfit[0]
        Rgn2K_Bnds=(pfit[0]/2, pfit[0]*2)
#         import matplotlib.pyplot as plt
#         fig,ax = plt.subplots(1, 1, sharey=False, figsize=(6.4,4.8)) # (6.4,4.8)
#         fig.subplots_adjust(left=0.12, right=0.95, top=0.95, bottom=0.11, hspace=0.20, wspace=0.20)
#         ax.plot(x,y ,'-'   , label='')
#         ax.plot(x[bR2],y[bR2],'ko', label='')
#         ax.plot(x_lin,y_lin,'bd', label='')
#         ax.set_xlabel('')
#         ax.set_ylabel('')
#         ax.tick_params(direction='in')
#         plt.show()
        def minimize_me(p):
            RtGnSp, RtTq  , Rgn2K , SlPc , SpdGenOn = p
            y_model=np.array([gentorque(x_lin, (RtGnSp, RtTq  , Rgn2K , SlPc , SpdGenOn))])
            eps = np.mean((y_lin-y_model)**2)
#             print(eps,p)
            return  eps
        bounds = (RtGnSp_Bnds, RtTq_Bnds, Rgn2K_Bnds, Slpc_Bnds, SpdGenOn_Bnds)
        p0     = [RtGnSp_0, RtTq_0, Rgn2K_0, Slpc_0, SpdGenOn_0]
        #print('Bounds',bounds)
        #print('p0',p0)
        res = so.minimize(minimize_me, x0=p0, bounds= bounds, method='SLSQP')
        pfit=res.x

        # --- Reporting information about the fit (after the fit)
        y_fit= gentorque(x, pfit)
        self.store_fit_info(y_fit, pfit)
        # --- Return a fitted function
        self.model['fitted_function']=lambda x: gentorque(x,pfit)