jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def get_continuum(lam0, spec0, espec0, ccfconf=None):
    """Determine the continuum of the spectrum by fitting a spline

    Parameters
    ----------

    lam0: numpy array
        The wavelength vector
    spec0: numpy array
        The spectral vector
    espec0: numpy array
        The vector of spectral uncertainties
    ccfconf: CCFConfig object
        The CCF configuration object

    Returns
    -------
    cont: numpy array
        The continuum vector

"""

    lammin = lam0.min()
    N = np.log(lam0.max() / lammin) / np.log(1 + ccfconf.splinestep / 3e5)
    N = int(np.ceil(N))
    # Determine the nodes of the spline used for the continuum fit
    nodes = lammin * np.exp(
        np.arange(N) * np.log(1 + ccfconf.splinestep / 3e5))
    nodesedges = lammin * np.exp(
        (-0.5 + np.arange(N + 1)) * np.log(1 + ccfconf.splinestep / 3e5))
    medspec = np.median(spec0)
    if medspec <= 0:
        medspec = np.abs(medspec)
        if medspec == 0:
            medspec = 1
        logging.warning('The spectrum has a median that is non-positive...')

    BS = scipy.stats.binned_statistic(lam0, spec0, 'median', bins=nodesedges)
    p0 = np.log(np.maximum(BS.statistic, 1e-3 * medspec))
    p0[~np.isfinite(p0)] = np.log(medspec)

    ret = scipy.optimize.least_squares(fit_resid,
                                       p0,
                                       loss='soft_l1',
                                       args=((nodes, lam0, spec0, espec0),
                                             False))
    cont = fit_resid(ret['x'], (nodes, lam0, spec0, espec0), True)
    return cont
//  [python]
def compute_graph_stats(episode_lengths, episode_rewards, timestamps, initial_reset_timestamp, buckets):
    """Method to compute the aggregates for the graphs."""
    import scipy.stats as s

    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 = list(range(num_episodes))

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

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

    x_seconds_y_reward = s.binned_statistic(x_seconds, episode_rewards, 'mean', buckets)
    x_seconds_y_length = s.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 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 = list(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 compute_spectrum2d(data):
    if data.ndim == 2:
        data = data[np.newaxis, ...]

    N, N_y, N_x = data.shape
    if N_x == 2 * N_y:
        data1 = data[:, :, :N_y]
        data2 = data[:, :, N_y:]
        data = np.concatenate((data1, data2), axis=0)
    N, N_y, N_x = data.shape

    # Take FFT and take amplitude
    fourier_image = np.fft.fftn(data, axes=(1,2))
    fourier_amplitudes = np.abs(fourier_image)**2

    # Get kx and ky
    kfreq_x = np.fft.fftfreq(N_x) * N_x
    kfreq_y = np.fft.fftfreq(N_y) * N_y

    # Combine into one wavenumber for both directions
    kfreq2D = np.meshgrid(kfreq_x, kfreq_y)
    knrm = np.sqrt(kfreq2D[0]**2 + kfreq2D[1]**2)
    knrm = np.repeat(knrm[np.newaxis, ...], repeats=N, axis=0)

    # Flatten arrays
    knrm = knrm.flatten()
    fourier_amplitudes = fourier_amplitudes.flatten()

    # Get k-bins and mean amplitude within each bin
    kbins = np.arange(0.5, N_x//2, 1)
    Abins, _, _ = s.binned_statistic(knrm, fourier_amplitudes,
                                         statistic="mean",
                                         bins=kbins)

    # Multiply by volume of bin
    Abins *= np.pi * (kbins[1:] ** 2 - kbins[:-1] ** 2)

    # Get center of k-bin for plotting
    kvals = 0.5 * (kbins[1:] + kbins[:-1])

    return (kvals, Abins)
//  [python]
def compute_spectrum2d(data):
    if data.ndim == 2:
        data = data[np.newaxis, ...]

    N, N_y, N_x = data.shape
    if N_x == 2 * N_y:
        data1 = data[:, :, :N_y]
        data2 = data[:, :, N_y:]
        data = np.concatenate((data1, data2), axis=0)
    N, N_y, N_x = data.shape

    # Take FFT and take amplitude
    fourier_image = np.fft.fftn(data, axes=(1,2))
    fourier_amplitudes = np.abs(fourier_image)**2

    # Get kx and ky
    kfreq_x = np.fft.fftfreq(N_x) * N_x
    kfreq_y = np.fft.fftfreq(N_y) * N_y

    # Combine into one wavenumber for both directions
    kfreq2D = np.meshgrid(kfreq_x, kfreq_y)
    knrm = np.sqrt(kfreq2D[0]**2 + kfreq2D[1]**2)
    knrm = np.repeat(knrm[np.newaxis, ...], repeats=N, axis=0)

    # Flatten arrays
    knrm = knrm.flatten()
    fourier_amplitudes = fourier_amplitudes.flatten()

    # Get k-bins and mean amplitude within each bin
    kbins = np.arange(0.5, N_x//2, 1)
    Abins, _, _ = stats.binned_statistic(knrm, fourier_amplitudes,
                                         statistic="mean",
                                         bins=kbins)

    # Multiply by volume of bin
    Abins *= np.pi * (kbins[1:] ** 2 - kbins[:-1] ** 2)

    # Get center of k-bin for plotting
    kvals = 0.5 * (kbins[1:] + kbins[:-1])

    return (kvals, Abins)
//  [python]
def _get_recombination_map_data(recomb_map):
    """Get positions and rates for a recombination map for plotting"""
    positions = np.array(recomb_map.get_positions())
    rates = np.array(recomb_map.get_rates())
    num_bins = 500
    v, bin_edges, _ = scipy.stats.binned_statistic(
        positions, rates, bins=num_bins)
    x = bin_edges[:-1][np.logical_not(np.isnan(v))]
    y = v[np.logical_not(np.isnan(v))]
    return x, y
//  [python]
def downbin_series(yhr, xhr, xlr, dxlr=None):
    """
    Re-bin series to lower resolution using `sp.binned_statistic`

    :param array_like yhr: Series to be degraded
    :param array_like xhr: High-res x grid
    :param array_like xlr: Low-res x grid
    :param array_like dxlr: Low-res x width grid. Default :py:obj:`None`

    :returns: array_like ylr: Low-res series
    """
    from scipy import stats

    if dxlr is None:
        # Calculate low-res
        #dxlr = xlr
        ValueError("Please supply dlam in downbin_spec()")

    # Reverse ordering if wl vector is decreasing with index
    if len(xlr) > 1:
        if xhr[0] > xhr[1]:
            xhr = np.array(xhr[::-1])
            spec = np.array(yhr[::-1])
        if xlr[0] > xlr[1]:
            xlr = np.array(xlr[::-1])
            dxlr = np.array(dxlr[::-1])

    # Calculate bin edges
    LRedges = np.hstack([xlr - 0.5*dxlr, xlr[-1]+0.5*dxlr[-1]])

    # Call scipy.stats.binned_statistic()
    ylr = stats.binned_statistic(xhr, yhr, statistic="mean", bins=LRedges)[0]

    return ylr
//  [python]
def downbin_series(yhr, xhr, xlr, dxlr=None):
    """
    Re-bin series to lower resolution using `sp.binned_statistic`

    :param array_like yhr: Series to be degraded
    :param array_like xhr: High-res x grid
    :param array_like xlr: Low-res x grid
    :param array_like dxlr: Low-res x width grid. Default :py:obj:`None`

    :returns: array_like ylr: Low-res series
    """
    from scipy.stats import binned_statistic

    if dxlr is None:
        # Calculate low-res
        #dxlr = xlr
        ValueError("Please supply dlam in downbin_spec()")

    # Reverse ordering if wl vector is decreasing with index
    if len(xlr) > 1:
        if xhr[0] > xhr[1]:
            xhr = np.array(xhr[::-1])
            spec = np.array(yhr[::-1])
        if xlr[0] > xlr[1]:
            xlr = np.array(xlr[::-1])
            dxlr = np.array(dxlr[::-1])

    # Calculate bin edges
    LRedges = np.hstack([xlr - 0.5*dxlr, xlr[-1]+0.5*dxlr[-1]])

    # Call scipy.stats.binned_statistic()
    ylr = binned_statistic(xhr, yhr, statistic="mean", bins=LRedges)[0]

    return ylr
//  [python]
def test_BinnedStatistics1D(stat, stat_f):
    x = np.linspace(0, 2 * np.pi, 100)
    values = np.sin(x * 5)

    bs = BinnedStatistic1D(x, statistic=stat, bins=10)
    bs_f = BinnedStatistic1D(x, statistic=stat_f, bins=10)

    ref, edges, _ = s.binned_statistic(x, values, statistic=stat, bins=10)

    assert_array_almost_equal(bs(values), ref)
    assert_array_almost_equal(bs_f(values), ref)
    assert_array_almost_equal(edges, bs.bin_edges)
    assert_array_almost_equal(edges, bs_f.bin_edges)

    rbinstat = BinnedStatistic1D(x)
    # make sure wrong shape is caught
    with assert_raises(ValueError):
        rbinstat(x[:-2])

    # try with same shape, should be fine
    rbinstat(x)
//  [python]
def test_BinnedStatistics1D(stat, stat_f):
    x = np.linspace(0, 2 * np.pi, 100)
    values = np.sin(x * 5)

    bs = BinnedStatistic1D(x, statistic=stat, bins=10)
    bs_f = BinnedStatistic1D(x, statistic=stat_f, bins=10)

    ref, edges, _ = scipy.stats.binned_statistic(x, values, statistic=stat, bins=10)

    assert_array_almost_equal(bs(values), ref)
    assert_array_almost_equal(bs_f(values), ref)
    assert_array_almost_equal(edges, bs.bin_edges)
    assert_array_almost_equal(edges, bs_f.bin_edges)

    rbinstat = BinnedStatistic1D(x)
    # make sure wrong shape is caught
    with assert_raises(ValueError):
        rbinstat(x[:-2])

    # try with same shape, should be fine
    rbinstat(x)
//  [python]
def get_mean_ms_per_ts(self, tag: str) -> float:
        """
        Get the mean time in milliseconds spent on operations with the
        given tag per timestep.

        :param str tag: The tag to get the data for
        :rtype: float
        """
        time_step_ms = FecDataView.get_simulation_time_step_ms()
        n_points = math.ceil(self._max_time / time_step_ms)
        endpoint = n_points * time_step_ms
        bins = numpy.linspace(0, endpoint, n_points + 1)
        mean_per_ts = numpy.histogram(self._tags[tag][_START_TIME], bins, weights=self._tags[tag][_DURATION])[0] / numpy.histogram(self._tags[tag][_START_TIME], bins)[0]
        mean_per_ts[numpy.isnan(mean_per_ts)] = 0
        return numpy.average(
            mean_per_ts[numpy.logical_not(numpy.isnan(mean_per_ts))])
//  [python]
def get_mean_ms_per_ts(self, tag: str) -> float:
        """
        Get the mean time in milliseconds spent on operations with the
        given tag per timestep.

        :param str tag: The tag to get the data for
        :rtype: float
        """
        time_step_ms = FecDataView.get_simulation_time_step_ms()
        n_points = math.ceil(self._max_time / time_step_ms)
        endpoint = n_points * time_step_ms
        bins = numpy.linspace(0, endpoint, n_points + 1)
        mean_per_ts = scipy.stats.binned_statistic(
            self._tags[tag][_START_TIME], self._tags[tag][_DURATION],
            "mean", bins).statistic
        mean_per_ts[numpy.isnan(mean_per_ts)] = 0
        return numpy.average(
            mean_per_ts[numpy.logical_not(numpy.isnan(mean_per_ts))])
//  [python]
def get_histo_labels(img, rmin0, rmax, nbins=50):
    """
    Takes an image of shape [H, W, Channel], gets blue and red bands,
    and computes histogram for blue values. then it finds the array indices
    for each bin of the histogram.

    Args:
        img (numpy array): the input image, part of a time series of images
        rmin0 (int): minimum edge of the histogram (later adjusted based on each image)
        rmax (int): maximum edge of the histogram
        nbins (int): number of histogram bins

    Returns:
        the array of histogram indices of same shape as a band or (nan, nan)
        which is later passed to compute hot when nanmean is called.

    """
    # make 3D arrays for blue and red bands to compute clear sky lines
    blue = img[:, :, 0]
    # finding samples, there should be at least 500 values to
    # compute clear sky line
    good_histo_values = np.where((blue < rmax) & (blue > rmin0), blue, 0)
    if np.count_nonzero(good_histo_values) > 500:
        # starts binning where we have good data
        rmin = np.min(good_histo_values[good_histo_values != 0])
        # computes the histogram for a single blue image
        (means, edges, numbers) = stats.binned_statistic(blue.flatten(),
                                                         blue.flatten(), statistic='mean',
                                                         bins=50, range=(int(rmin), int(rmax)))

        histo_labels_reshaped = np.reshape(
            numbers, (blue.shape[0], blue.shape[1]))
        return histo_labels_reshaped

    else:
        # we return None here to signal that we need to use the
        # mean slope and intercept for the good clear skylines
        return np.ones(blue.shape)*np.nan
//  [python]
def plot_moving_avg(df,time_mark,column,window,ax,label=None):
    time_df = df[[time_mark, column]].apply(pd.to_numeric)
    xlims = (time_df[time_mark].min(), time_df[time_mark].max()) # x lims for bins
    # xlims = x_extents
    bin_mean, bin_edges, bin_n = s.binned_statistic(time_df[time_mark], time_df[column],
                    statistic='mean', bins=np.arange(xlims[0]-1, xlims[1]+1, window))
    bin_centers = bin_edges[:-1] + np.diff(bin_edges) / 2

    ax.plot(bin_centers, bin_mean, lw=1, alpha=1,label=label)
//  [python]
def plot_moving_avg(df,time_mark,column,window,ax,label=None):
    time_df = df[[time_mark, column]].apply(pd.to_numeric)
    xlims = (time_df[time_mark].min(), time_df[time_mark].max()) # x lims for bins
    # xlims = x_extents
    bin_mean, bin_edges, bin_n = sps.binned_statistic(time_df[time_mark], time_df[column],
                    statistic='mean', bins=np.arange(xlims[0]-1, xlims[1]+1, window))
    bin_centers = bin_edges[:-1] + np.diff(bin_edges) / 2

    ax.plot(bin_centers, bin_mean, lw=1, alpha=1,label=label)
//  [python]
particle_diams = np.zeros(np.sum(N))
counter = 0
for i_bin in range(nbins):
    for i_part in range(len(M[i_bin])):
        particle_diams[counter] = ((6/np.pi)*M[i_bin][i_part])**(1/3)
        counter += 1

## Maybe we want to rebin the particles onto the sectional grid?
edges = np.logspace(-9,-6,100)
bin_values, bin_edges, binnumber = s.binned_statistic(
    particle_diams, particle_diams,statistic='count',bins=edges)
//  [python]
particle_diams = np.zeros(np.sum(N))
counter = 0
for i_bin in range(nbins):
    for i_part in range(len(M[i_bin])):
        particle_diams[counter] = ((6/np.pi)*M[i_bin][i_part])**(1/3)
        counter += 1

## Maybe we want to rebin the particles onto the sectional grid?
edges = np.logspace(-9,-6,100)
bin_values, bin_edges, binnumber = scipy.stats.binned_statistic(
    particle_diams, particle_diams,statistic='count',bins=edges)
//  [python]
def _binned_mean_stats(x, y, bins, bins_min_count):
    bin_counts, _, _ = s.binned_statistic(x, y, statistic='count', bins=bins)
    bin_means, bin_edges, _ = s.binned_statistic(x, y, bins=bins)
    bin_std, _, _ = s.binned_statistic(x, y, statistic='std', bins=bins)
    bin_width = (bin_edges[1] - bin_edges[0])
    bin_centers = bin_edges[1:] - bin_width/2
    if bins_min_count > 1:
        bin_centers = bin_centers[bin_counts > bins_min_count]
        bin_means = bin_means[bin_counts > bins_min_count]
        bin_std = bin_std[bin_counts > bins_min_count]
        bin_counts = bin_counts[bin_counts > bins_min_count]
    std_err = bin_std/np.sqrt(bin_counts)
    return bin_centers, bin_means, bin_std, std_err
//  [python]
def _binned_mean_stats(x, y, bins, bins_min_count):
    bin_counts, _, _ = scipy.stats.binned_statistic(x, y, statistic='count', bins=bins)
    bin_means, bin_edges, _ = scipy.stats.binned_statistic(x, y, bins=bins)
    bin_std, _, _ = scipy.stats.binned_statistic(x, y, statistic='std', bins=bins)
    bin_width = (bin_edges[1] - bin_edges[0])
    bin_centers = bin_edges[1:] - bin_width/2
    if bins_min_count > 1:
        bin_centers = bin_centers[bin_counts > bins_min_count]
        bin_means = bin_means[bin_counts > bins_min_count]
        bin_std = bin_std[bin_counts > bins_min_count]
        bin_counts = bin_counts[bin_counts > bins_min_count]
    std_err = bin_std/np.sqrt(bin_counts)
    return bin_centers, bin_means, bin_std, std_err
//  [python]
vals = np.zeros(100)
for i_repeat in range(100):
    u = np.random.rand(N)
    tau = -np.log(u)/r
    vals[i_repeat] = np.mean(tau)

print(np.mean(vals),np.std(vals),np.mean(vals)-np.std(vals),np.mean(vals)+np.std(vals))
print(vals)

bin_count, bin_edges, binnumber = scipy.stats.binned_statistic(tau,tau,statistic='count', bins=100)
//  [python]
def bin_grid(image, r_array, pixel_sizes, statistic="mean", mask=None, bins=None):
    """
    Bin and integrate an image, given the radial array of pixels

    Parameters
    ----------
    image: np.array
        The image in quesion
    r_array: np.array
        The array which maps pixel positions to tilt/rotation corrected radii
    pixel_sizes: tuple
        The size of the pixels in the same units as the r_array
    statistic: str or func, optional
        The statistic to compute over the integration, defaults to mean
    mask: bool array, optional
        The array of pixels to be removed from the image before integration
    bins: array, optional
        The bins to use in the integration, if none given the function will
        give its best assessment based on the pixel_size and r_array

    Returns
    -------
    bin_centers : array
        The center of each bin in R
    int_stat : array
        Radial integrated statistic of the image.

    See Also
    --------
    circular_average : circularly average an image, assuming linear radial
        spacing (less general)

    """
    if mask is None:
        mask = np.ones(image.shape, dtype=int).astype(bool)
    if bins is None:
        res = np.hypot(*pixel_sizes)
        bins = np.arange(np.min(r_array) - res * 0.5, np.max(r_array) + res * 0.5, res)

    int_stat, bin_edge, bin_num = s.binned_statistic(r_array[mask], image[mask], statistic=statistic, bins=bins)

    bin_centers = bin_edges_to_centers(bin_edge)

    return bin_centers, int_stat
//  [python]
def bin_grid(image, r_array, pixel_sizes, statistic="mean", mask=None, bins=None):
    """
    Bin and integrate an image, given the radial array of pixels

    Parameters
    ----------
    image: np.array
        The image in quesion
    r_array: np.array
        The array which maps pixel positions to tilt/rotation corrected radii
    pixel_sizes: tuple
        The size of the pixels in the same units as the r_array
    statistic: str or func, optional
        The statistic to compute over the integration, defaults to mean
    mask: bool array, optional
        The array of pixels to be removed from the image before integration
    bins: array, optional
        The bins to use in the integration, if none given the function will
        give its best assessment based on the pixel_size and r_array

    Returns
    -------
    bin_centers : array
        The center of each bin in R
    int_stat : array
        Radial integrated statistic of the image.

    See Also
    --------
    circular_average : circularly average an image, assuming linear radial
        spacing (less general)

    """
    if mask is None:
        mask = np.ones(image.shape, dtype=int).astype(bool)
    if bins is None:
        res = np.hypot(*pixel_sizes)
        bins = np.arange(np.min(r_array) - res * 0.5, np.max(r_array) + res * 0.5, res)

    int_stat, bin_edge, bin_num = sts.binned_statistic(r_array[mask], image[mask], statistic=statistic, bins=bins)

    bin_centers = bin_edges_to_centers(bin_edge)

    return bin_centers, int_stat
//  [python]
def binned_stat(x, y, statistic='mean', bin_edges='sturges', binmin=None):
    '''Calculate binned mean or median on X. Returns plotting variables

    bin_edges : int or list/array
        If int, this is the number of bins. If it is a list it defines the bin edges.

    '''

    # define range for bins
    data_mean = x.mean()
    data_std = x.std()
    bin_range = (data_mean - 3*data_std, data_mean + 3*data_std)

    # gives better bin edges. If a defined sequence is passed it will use that.
    bin_edges = np.histogram_bin_edges(x, bins=bin_edges, range=bin_range)

    # calculate mean
    bin_result = s.binned_statistic(x, y,
                                      statistic=statistic, bins=bin_edges)
    bin_means, bin_edges, bin_n = bin_result
    bin_centers = bin_edges[:-1] + np.diff(bin_edges) / 2

    # calculate error at each bin (standard error)
    bin_error_result = s.binned_statistic(x, y,
                                            statistic=np.std, bins=bin_edges)
    bin_stds, _, _ = bin_error_result

    # if using median, multiply this number by 1.253. Holds for large samples only
    if statistic == 'median':
        bin_stds = bin_stds * 1.253

    bin_count_results = s.binned_statistic(x, y,
                                             statistic='count', bins=bin_edges)
    bin_counts, _, _ = bin_count_results

    bin_errors = np.divide(bin_stds, np.sqrt(bin_counts))

    # remove bins with not enought datapoints
    if binmin:
        delete_me = []
        for i, points in enumerate(bin_counts):
            if points < binmin:
                delete_me.append(i)
        delete_me = tuple(delete_me)
        bin_centers = np.delete(bin_centers, delete_me)
        bin_means = np.delete(bin_means, delete_me)
        bin_errors = np.delete(bin_errors, delete_me)

        # only keep locations where there is data
        bin_centers = bin_centers[~np.isnan(bin_means)]
        bin_means = bin_means[~np.isnan(bin_means)]
        bin_errors = bin_errors[~np.isnan(bin_means)]

    return bin_centers, bin_means, bin_errors
//  [python]
def binned_stat(x, y, statistic='mean', bin_edges='sturges', binmin=None):
    '''Calculate binned mean or median on X. Returns plotting variables

    bin_edges : int or list/array
        If int, this is the number of bins. If it is a list it defines the bin edges.

    '''

    # define range for bins
    data_mean = x.mean()
    data_std = x.std()
    bin_range = (data_mean - 3*data_std, data_mean + 3*data_std)

    # gives better bin edges. If a defined sequence is passed it will use that.
    bin_edges = np.histogram_bin_edges(x, bins=bin_edges, range=bin_range)

    # calculate mean
    bin_result = sps.binned_statistic(x, y,
                                      statistic=statistic, bins=bin_edges)
    bin_means, bin_edges, bin_n = bin_result
    bin_centers = bin_edges[:-1] + np.diff(bin_edges) / 2

    # calculate error at each bin (standard error)
    bin_error_result = sps.binned_statistic(x, y,
                                            statistic=np.std, bins=bin_edges)
    bin_stds, _, _ = bin_error_result

    # if using median, multiply this number by 1.253. Holds for large samples only
    if statistic == 'median':
        bin_stds = bin_stds * 1.253

    bin_count_results = sps.binned_statistic(x, y,
                                             statistic='count', bins=bin_edges)
    bin_counts, _, _ = bin_count_results

    bin_errors = np.divide(bin_stds, np.sqrt(bin_counts))

    # remove bins with not enought datapoints
    if binmin:
        delete_me = []
        for i, points in enumerate(bin_counts):
            if points < binmin:
                delete_me.append(i)
        delete_me = tuple(delete_me)
        bin_centers = np.delete(bin_centers, delete_me)
        bin_means = np.delete(bin_means, delete_me)
        bin_errors = np.delete(bin_errors, delete_me)

        # only keep locations where there is data
        bin_centers = bin_centers[~np.isnan(bin_means)]
        bin_means = bin_means[~np.isnan(bin_means)]
        bin_errors = bin_errors[~np.isnan(bin_means)]

    return bin_centers, bin_means, bin_errors
//  [python]
def plot_derivative(Cells_df, time_mark='birth_time', x_extents=None, time_window=10):
    '''
    Plots the derivtive of the moving average of the cell parameters.

    Parameters
    ----------
    time_window : int
        Time window which the parameters statistic is calculated over
    '''

    sns.set(style="whitegrid", palette="pastel", color_codes=True, font_scale=1.25)

    # lists for plotting and formatting
    columns = ['sb', 'elong_rate', 'sd', 'tau', 'delta', 'septum_position']
    titles = ['Length at Birth', 'Elongation Rate', 'Length at Division',
              'Generation Time', 'Delta', 'Septum Position']
    ylabels = ['$\mu$m', '$\lambda$', '$\mu$m', 'min', '$\mu$m','daughter/mother']

    # create figure, going to apply graphs to each axis sequentially
    fig, axes = plt.subplots(nrows=len(columns)/2, ncols=2,
                            figsize=[10,5*len(columns)/2], squeeze=False)
    ax = np.ravel(axes)

    # over what times should we calculate stats?
    if x_extents == None:
        x_extents = (Cells_df['birth_time'].min(), Cells_df['birth_time'].max())

    # Now plot the filtered data
    for i, column in enumerate(columns):

        # get out just the data to be plot for one subplot
        time_df = Cells_df[[time_mark, column]].apply(pd.to_numeric)
        time_df.sort_values(by=time_mark, inplace=True)

        # graph moving average
        xlims = x_extents
        bin_mean, bin_edges, bin_n = s.binned_statistic(time_df[time_mark], time_df[column],
                        statistic='mean', bins=np.arange(xlims[0]-1, xlims[1]+1, time_window))
        bin_centers = bin_edges[:-1] + np.diff(bin_edges) / 2
        # ax[i].plot(bin_centers, bin_mean, lw=4, alpha=0.8, color=(1.0, 1.0, 0.0))

        mean_diff = np.diff(bin_mean)
        ax[i].plot(bin_centers[:-1], mean_diff, lw=4, alpha=0.8, color='blue')

        # formatting
        ax[i].set_title(titles[i], size=18)
        ax[i].set_ylabel(ylabels[i], size=16)

    ax[5].legend(['%s minute binned average' % time_window], fontsize=14, loc='lower right',
                 frameon=False)
    ax[4].set_xlabel('Frame [min/5]', size=16)
    ax[5].set_xlabel('Frame [min/5]', size=16)

    # Make title, need a little extra space
    plt.subplots_adjust(top=0.9, hspace=0.25)
    fig.suptitle('Cell Parameters Over Time', size=24)

    # sns.despine()

    return fig, ax
//  [python]
def plot_derivative(Cells_df, time_mark='birth_time', x_extents=None, time_window=10):
    '''
    Plots the derivtive of the moving average of the cell parameters.

    Parameters
    ----------
    time_window : int
        Time window which the parameters statistic is calculated over
    '''

    sns.set(style="whitegrid", palette="pastel", color_codes=True, font_scale=1.25)

    # lists for plotting and formatting
    columns = ['sb', 'elong_rate', 'sd', 'tau', 'delta', 'septum_position']
    titles = ['Length at Birth', 'Elongation Rate', 'Length at Division',
              'Generation Time', 'Delta', 'Septum Position']
    ylabels = ['$\mu$m', '$\lambda$', '$\mu$m', 'min', '$\mu$m','daughter/mother']

    # create figure, going to apply graphs to each axis sequentially
    fig, axes = plt.subplots(nrows=len(columns)/2, ncols=2,
                            figsize=[10,5*len(columns)/2], squeeze=False)
    ax = np.ravel(axes)

    # over what times should we calculate stats?
    if x_extents == None:
        x_extents = (Cells_df['birth_time'].min(), Cells_df['birth_time'].max())

    # Now plot the filtered data
    for i, column in enumerate(columns):

        # get out just the data to be plot for one subplot
        time_df = Cells_df[[time_mark, column]].apply(pd.to_numeric)
        time_df.sort_values(by=time_mark, inplace=True)

        # graph moving average
        xlims = x_extents
        bin_mean, bin_edges, bin_n = sps.binned_statistic(time_df[time_mark], time_df[column],
                        statistic='mean', bins=np.arange(xlims[0]-1, xlims[1]+1, time_window))
        bin_centers = bin_edges[:-1] + np.diff(bin_edges) / 2
        # ax[i].plot(bin_centers, bin_mean, lw=4, alpha=0.8, color=(1.0, 1.0, 0.0))

        mean_diff = np.diff(bin_mean)
        ax[i].plot(bin_centers[:-1], mean_diff, lw=4, alpha=0.8, color='blue')

        # formatting
        ax[i].set_title(titles[i], size=18)
        ax[i].set_ylabel(ylabels[i], size=16)

    ax[5].legend(['%s minute binned average' % time_window], fontsize=14, loc='lower right',
                 frameon=False)
    ax[4].set_xlabel('Frame [min/5]', size=16)
    ax[5].set_xlabel('Frame [min/5]', size=16)

    # Make title, need a little extra space
    plt.subplots_adjust(top=0.9, hspace=0.25)
    fig.suptitle('Cell Parameters Over Time', size=24)

    # sns.despine()

    return fig, ax
//  [python]
def test_random_state(self):
        f = stats.norm.pdf
        v_bound = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
        umax, vmin, vmax = np.sqrt(f(0)), -v_bound, v_bound
        np.random.seed(1234)
        r1 = stats.rvs_ratio_uniforms(f, umax, vmin, vmax, size=(3, 4))
        r2 = stats.rvs_ratio_uniforms(f, umax, vmin, vmax, size=(3, 4),
                                      random_state=1234)
        assert_equal(r1, r2)
//  [python]
def test_random_state(self):
        f = stats.norm.pdf
        v_bound = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
        umax, vmin, vmax = np.sqrt(f(0)), -v_bound, v_bound
        np.random.seed(1234)
        r1 = stats.sampling.RatioUniforms(f, umax, vmin, vmax).rvs(size=(3, 4))
        r2 = stats.sampling.RatioUniforms(f, umax, vmin, vmax, random_state=1234).rvs(size=(3, 4))
        assert_equal(r1, r2)
//  [python]
def binned_outlier(img, r, alpha, bins, mask=None):
    """
    Generates a mask by identifying outlier pixels in bins and masks any
    pixels which have a value greater or less than alpha * std away from the
    mean

    Parameters
    ----------
    img: 2darray
        The  image
    r: 2darray
        The  array which maps pixels to bins
    alpha: float or tuple or, 1darray
        Then number of acceptable standard deviations, if tuple then we use
        a linear distribution of alphas from alpha[0] to alpha[1], if array
        then we just use that as the distribution of alphas
    bins: list
        The bin edges
    mask: 1darray, bool
        A starting flattened mask

    Returns
    -------
    2darray:
        The mask
    """

    if mask is None:
        working_mask = np.ones(img.shape).astype(bool)
    else:
        working_mask = np.copy(mask).astype(bool)
    if working_mask.shape != img.shape:
        working_mask = working_mask.reshape(img.shape)
    msk_img = img[working_mask]
    msk_r = r[working_mask]

    int_r = np.digitize(r, bins[:-1], True) - 1
    # integration
    mean = s.binned_statistic(msk_r, msk_img, bins=bins, statistic="mean")[0]
    std = s.binned_statistic(msk_r, msk_img, bins=bins, statistic=np.std)[0]
    if type(alpha) is tuple:
        alpha = np.linspace(alpha[0], alpha[1], len(std))
    threshold = alpha * std
    lower = mean - threshold
    upper = mean + threshold

    # single out the too low and too high pixels
    working_mask *= img > lower[int_r]
    working_mask *= img < upper[int_r]

    return working_mask.astype(bool)
//  [python]
def binned_outlier(img, r, alpha, bins, mask=None):
    """
    Generates a mask by identifying outlier pixels in bins and masks any
    pixels which have a value greater or less than alpha * std away from the
    mean

    Parameters
    ----------
    img: 2darray
        The  image
    r: 2darray
        The  array which maps pixels to bins
    alpha: float or tuple or, 1darray
        Then number of acceptable standard deviations, if tuple then we use
        a linear distribution of alphas from alpha[0] to alpha[1], if array
        then we just use that as the distribution of alphas
    bins: list
        The bin edges
    mask: 1darray, bool
        A starting flattened mask

    Returns
    -------
    2darray:
        The mask
    """

    if mask is None:
        working_mask = np.ones(img.shape).astype(bool)
    else:
        working_mask = np.copy(mask).astype(bool)
    if working_mask.shape != img.shape:
        working_mask = working_mask.reshape(img.shape)
    msk_img = img[working_mask]
    msk_r = r[working_mask]

    int_r = np.digitize(r, bins[:-1], True) - 1
    # integration
    mean = sts.binned_statistic(msk_r, msk_img, bins=bins, statistic="mean")[0]
    std = sts.binned_statistic(msk_r, msk_img, bins=bins, statistic=np.std)[0]
    if type(alpha) is tuple:
        alpha = np.linspace(alpha[0], alpha[1], len(std))
    threshold = alpha * std
    lower = mean - threshold
    upper = mean + threshold

    # single out the too low and too high pixels
    working_mask *= img > lower[int_r]
    working_mask *= img < upper[int_r]

    return working_mask.astype(bool)
//  [python]
def test_rv_generation(self):
        # use KS test to check distribution of rvs
        # normal distribution
        f = stats.norm.pdf
        v_bound = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
        umax, vmin, vmax = np.sqrt(f(0)), -v_bound, v_bound
        rvs = stats.rvs_ratio_uniforms(f, umax, vmin, vmax, size=2500,
                                       random_state=12345)
        assert_equal(stats.kstest(rvs, 'norm')[1] > 0.25, True)

        # exponential distribution
        rvs = stats.rvs_ratio_uniforms(lambda x: np.exp(-x), umax=1,
                                       vmin=0, vmax=2*np.exp(-1),
                                       size=1000, random_state=12345)
        assert_equal(stats.kstest(rvs, 'expon')[1] > 0.25, True)
//  [python]
def test_rv_generation(self):
        # use KS test to check distribution of rvs
        # normal distribution
        f = stats.norm.pdf
        v_bound = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
        umax, vmin, vmax = np.sqrt(f(0)), -v_bound, v_bound
        rvs = stats.sampling.RatioUniforms(f, umax, vmin, vmax, random_state=12345).rvs(size=2500)
        assert_equal(stats.kstest(rvs, 'norm')[1] > 0.25, True)

        # exponential distribution
        rvs = stats.sampling.RatioUniforms(lambda x: np.exp(-x), umax=1,
                                       vmin=0, vmax=2*np.exp(-1), random_state=12345).rvs(size=1000)
        assert_equal(stats.kstest(rvs, 'expon')[1] > 0.25, True)
//  [python]
def test_consistency(self):
        f = stats.norm.pdf
        v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
        umax = np.sqrt(f(0))
        r1 = stats.rvs_ratio_uniforms(f, umax, -v, v, size=10, random_state=12345)
        deprecation_msg = ("Please use `RatioUniforms` from the "
                           "`scipy.stats.sampling` namespace.")
        with pytest.warns(DeprecationWarning, match=deprecation_msg):
            r2 = stats.rvs_ratio_uniforms(f, umax, -v, v, size=10,
                                          random_state=12345)
        assert_equal(r1, r2)
//  [python]
def test_consistency(self):
        f = stats.norm.pdf
        v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
        umax = np.sqrt(f(0))
        gen = stats.sampling.RatioUniforms(f, umax=umax, vmin=-v, vmax=v,
                                           random_state=12345)
        r1 = gen.rvs(10)
        deprecation_msg = ("Please use `RatioUniforms` from the "
                           "`scipy.stats.sampling` namespace.")
        with pytest.warns(DeprecationWarning, match=deprecation_msg):
            r2 = stats.rvs_ratio_uniforms(f, umax, -v, v, size=10,
                                          random_state=12345)
        assert_equal(r1, r2)
//  [python]
def test_rv_generation(self):
        # use KS test to check distribution of rvs
        # normal distribution
        f = stats.norm.pdf
        v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
        u = np.sqrt(f(0))
        gen = s.RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=12345)
        assert_equal(stats.kstest(gen.rvs(2500), 'norm')[1] > 0.25, True)

        # exponential distribution
        gen = s.RatioUniforms(lambda x: np.exp(-x), umax=1,
                            vmin=0, vmax=2*np.exp(-1), random_state=12345)
        assert_equal(stats.kstest(gen.rvs(1000), 'expon')[1] > 0.25, True)
//  [python]
def test_rv_generation(self):
        # use KS test to check distribution of rvs
        # normal distribution
        f = stats.norm.pdf
        v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
        u = np.sqrt(f(0))
        gen = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=12345)
        assert_equal(stats.kstest(gen.rvs(2500), 'norm')[1] > 0.25, True)

        # exponential distribution
        gen = RatioUniforms(lambda x: np.exp(-x), umax=1,
                            vmin=0, vmax=2*np.exp(-1), random_state=12345)
        assert_equal(stats.kstest(gen.rvs(1000), 'expon')[1] > 0.25, True)
//  [python]
def test_gig(self):
        # test generalized inverse gaussian distribution
        p, b = 0.5, 0.75

        def gig_mode(p, b):
            return b / (np.sqrt((p - 1)**2 + b**2) + 1 - p)

        def gig_pdf(x, p, b):
            c = 1/(2 * kv(p, b))
            return c * x**(p - 1) * np.exp(- b * (x + 1/x) / 2)

        def gig_cdf(x, p, b):
            x = np.atleast_1d(x)
            cdf = [quad(gig_pdf, 0, xi, args=(p, b))[0] for xi in x]
            return np.array(cdf)

        s = kv(p+2, b) / kv(p, b)
        vmax = np.sqrt(gig_pdf(gig_mode(p + 2, b), p + 2, b) * s)
        umax = np.sqrt(gig_pdf(gig_mode(p, b), p, b))

        rvs = stats.rvs_ratio_uniforms(lambda x: gig_pdf(x, p, b), umax,
                                       0, vmax, random_state=1234, size=1500)

        assert_equal(stats.kstest(rvs, lambda x: gig_cdf(x, p, b))[1] > 0.25,
                     True)
//  [python]
def test_gig(self):
        # test generalized inverse gaussian distribution
        p, b = 0.5, 0.75

        def gig_mode(p, b):
            return b / (np.sqrt((p - 1)**2 + b**2) + 1 - p)

        def gig_pdf(x, p, b):
            c = 1/(2 * kv(p, b))
            return c * x**(p - 1) * np.exp(- b * (x + 1/x) / 2)

        def gig_cdf(x, p, b):
            x = np.atleast_1d(x)
            cdf = [quad(gig_pdf, 0, xi, args=(p, b))[0] for xi in x]
            return np.array(cdf)

        s = kv(p+2, b) / kv(p, b)
        vmax = np.sqrt(gig_pdf(gig_mode(p + 2, b), p + 2, b) * s)
        umax = np.sqrt(gig_pdf(gig_mode(p, b), p, b))

        rvs = stats.sampling.RatioUniforms(lambda x: gig_pdf(x, p, b), umax,
                                       0, vmax, random_state=1234).rvs(size=1500)

        assert_equal(stats.kstest(rvs, lambda x: gig_cdf(x, p, b))[1] > 0.25,
                     True)
//  [python]
def test_shape(self):
        # test shape of return value depending on size parameter
        f = stats.norm.pdf
        v_bound = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
        umax, vmin, vmax = np.sqrt(f(0)), -v_bound, v_bound

        r1 = stats.rvs_ratio_uniforms(f, umax, vmin, vmax, size=3,
                                      random_state=1234)
        r2 = stats.rvs_ratio_uniforms(f, umax, vmin, vmax, size=(3,),
                                      random_state=1234)
        r3 = stats.rvs_ratio_uniforms(f, umax, vmin, vmax, size=(3, 1),
                                      random_state=1234)
        assert_equal(r1, r2)
        assert_equal(r2, r3.flatten())
        assert_equal(r1.shape, (3,))
        assert_equal(r3.shape, (3, 1))

        r4 = stats.rvs_ratio_uniforms(f, umax, vmin, vmax, size=(3, 3, 3),
                                      random_state=12)
        r5 = stats.rvs_ratio_uniforms(f, umax, vmin, vmax, size=27,
                                      random_state=12)
        assert_equal(r4.flatten(), r5)
        assert_equal(r4.shape, (3, 3, 3))

        r6 = stats.rvs_ratio_uniforms(f, umax, vmin, vmax, random_state=1234)
        r7 = stats.rvs_ratio_uniforms(f, umax, vmin, vmax, size=1,
                                      random_state=1234)
        r8 = stats.rvs_ratio_uniforms(f, umax, vmin, vmax, size=(1, ),
                                      random_state=1234)
        assert_equal(r6, r7)
        assert_equal(r7, r8)
//  [python]
def test_shape(self):
        # test shape of return value depending on size parameter
        f = stats.norm.pdf
        v_bound = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
        umax, vmin, vmax = np.sqrt(f(0)), -v_bound, v_bound

        r1 = stats.sampling.RatioUniforms(f, umax, vmin, vmax, size=3,
                                      random_state=1234).rvs()
        r2 = stats.sampling.RatioUniforms(f, umax, vmin, vmax, size=(3,),
                                      random_state=1234).rvs()
        r3 = stats.sampling.RatioUniforms(f, umax, vmin, vmax, size=(3, 1),
                                      random_state=1234).rvs()
        assert_equal(r1, r2)
        assert_equal(r2, r3.flatten())
        assert_equal(r1.shape, (3,))
        assert_equal(r3.shape, (3, 1))

        r4 = stats.sampling.RatioUniforms(f, umax, vmin, vmax, size=(3, 3, 3),
                                      random_state=12).rvs()
        r5 = stats.sampling.RatioUniforms(f, umax, vmin, vmax, size=27,
                                      random_state=12).rvs()
        assert_equal(r4.flatten(), r5)
        assert_equal(r4.shape, (3, 3, 3))

        r6 = stats.sampling.RatioUniforms(f, umax, vmin, vmax, random_state=1234).rvs()
        r7 = stats.sampling.RatioUniforms(f, umax, vmin, vmax, size=1,
                                      random_state=1234).rvs()
        r8 = stats.sampling.RatioUniforms(f, umax, vmin, vmax, size=(1, ),
                                      random_state=1234).rvs()
        assert_equal(r6, r7)
        assert_equal(r7, r8)
//  [python]
def test_random_state(self):
        f = stats.norm.pdf
        v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
        umax = np.sqrt(f(0))
        gen1 = s.RatioUniforms(f, umax=umax, vmin=-v, vmax=v, random_state=1234)
        r1 = gen1.rvs(10)
        np.random.seed(1234)
        gen2 = s.RatioUniforms(f, umax=umax, vmin=-v, vmax=v)
        r2 = gen2.rvs(10)
        assert_equal(r1, r2)
//  [python]
def test_random_state(self):
        f = stats.norm.pdf
        v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
        umax = np.sqrt(f(0))
        gen1 = RatioUniforms(f, umax=umax, vmin=-v, vmax=v, random_state=1234)
        r1 = gen1.rvs(10)
        np.random.seed(1234)
        gen2 = RatioUniforms(f, umax=umax, vmin=-v, vmax=v)
        r2 = gen2.rvs(10)
        assert_equal(r1, r2)
//  [python]
def test_exceptions(self):
        f = stats.norm.pdf
        # need vmin < vmax
        with assert_raises(ValueError, match="vmin must be smaller than vmax"):
            RatioUniforms(pdf=f, umax=1, vmin=3, vmax=1)
        with assert_raises(ValueError, match="vmin must be smaller than vmax"):
            RatioUniforms(pdf=f, umax=1, vmin=1, vmax=1)
        # need umax > 0
        with assert_raises(ValueError, match="umax must be positive"):
            RatioUniforms(pdf=f, umax=-1, vmin=1, vmax=3)
        with assert_raises(ValueError, match="umax must be positive"):
            RatioUniforms(pdf=f, umax=0, vmin=1, vmax=3)
//  [python]
def test_betai(self):
        np.random.seed(12345)
        for i in range(10):
            a = np.random.rand() * 5.
            b = np.random.rand() * 200.

            with warnings.catch_warnings():
                warnings.filterwarnings('ignore', category=DeprecationWarning)
                assert_equal(stats.betai(a, b, 0.), 0.)
                assert_equal(stats.betai(a, b, 1.), 1.)
                assert_equal(stats.mstats.betai(a, b, 0.), 0.)
                assert_equal(stats.mstats.betai(a, b, 1.), 1.)
                x = np.random.rand()
                assert_almost_equal(stats.betai(a, b, x),
                                    stats.mstats.betai(a, b, x), decimal=13)
//  [python]
def test_betai(self):
        np.random.seed(12345)
        for i in range(10):
            a = np.random.rand() * 5.
            b = np.random.rand() * 200.

            with warnings.catch_warnings():
                warnings.filterwarnings('ignore', category=DeprecationWarning)
                assert_equal(scipy.special.betainc(a, b, 0.), 0.)
                assert_equal(scipy.special.betainc(a, b, 1.), 1.)
                assert_equal(stats.mstats.betai(a, b, 0.), 0.)
                assert_equal(stats.mstats.betai(a, b, 1.), 1.)
                x = np.random.rand()
                assert_almost_equal(scipy.special.betainc(a, b, x),
                                    stats.mstats.betai(a, b, x), decimal=13)
//  [python]
def check_sample_mean(sm,v,n, popmean):
    # from stats.stats.ttest_1samp(a, popmean):
    # Calculates the t-obtained for the independent samples T-test on ONE group
    # of scores a, given a population mean.
    #
    # Returns: t-value, two-tailed prob
    df = n-1
    svar = ((n-1)*v) / float(df)    # looks redundant
    t = (sm-popmean) / np.sqrt(svar*(1.0/n))
    prob = stats.betai(0.5*df, 0.5, df/(df+t*t))

    # return t,prob
    npt.assert_(prob > 0.01, 'mean fail, t,prob = %f, %f, m, sm=%f,%f' %
            (t, prob, popmean, sm))
//  [python]
def check_sample_mean(sm,v,n, popmean):
    # from stats.stats.ttest_1samp(a, popmean):
    # Calculates the t-obtained for the independent samples T-test on ONE group
    # of scores a, given a population mean.
    #
    # Returns: t-value, two-tailed prob
    df = n-1
    svar = ((n-1)*v) / float(df)    # looks redundant
    t = (sm-popmean) / np.sqrt(svar*(1.0/n))
    prob = scipy.special.betainc(0.5*df, 0.5, df/(df+t*t))

    # return t,prob
    npt.assert_(prob > 0.01, 'mean fail, t,prob = %f, %f, m, sm=%f,%f' %
            (t, prob, popmean, sm))