jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def significance(graph: nx.Graph, communities: object, **kwargs: dict) -> object:
    """Significance estimates how likely a partition of dense communities appear in a random graph.

    :param graph: a networkx/igraph object
    :param communities: NodeClustering object
    :return: FitnessResult object

    Example:

    >>> from cdlib.algorithms import louvain
    >>> from cdlib import evaluation
    >>> g = nx.karate_club_graph()
    >>> communities = louvain(g)
    >>> mod = evaluation.significance(g,communities)

    :References:

    1. Traag, V. A., Aldecoa, R., & Delvenne, J. C. (2015). `Detecting communities using asymptotical surprise. <https://link.aps.org/doi/10.1103/PhysRevE.92.022816/>`_ Physical Review E, 92(2), 022816.
    """
    graph = convert_graph_formats(graph, nx.Graph)
    m = graph.number_of_edges()

    binom = scipy.special.comb(m, 2, exact=True)
    p = m / binom

    q = 0

    for community in communities.communities:
        try:
            c = nx.subgraph(graph, community)
            nc = c.number_of_nodes()
            mc = c.number_of_edges()

            binom_c = scipy.special.comb(nc, 2, exact=True)
            pc = mc / binom_c

            q += binom_c * (pc * np.log(pc / p) + (1 - pc) * np.log((1 - pc) / (1 - p)))
        except ZeroDivisionError:
            pass
    return FitnessResult(score=q)
//  [python]
def surprise(graph: nx.Graph, communities: object, **kwargs: dict) -> object:
    """Surprise is statistical approach proposes a quality metric assuming that edges between vertices emerge randomly according to a hyper-geometric distribution.

    According to the Surprise metric, the higher the score of a partition, the less likely it is resulted from a random realization, the better the quality of the community structure.

    :param graph: a networkx/igraph object
    :param communities: NodeClustering object
    :return: FitnessResult object

    Example:

    >>> from cdlib.algorithms import louvain
    >>> from cdlib import evaluation
    >>> g = nx.karate_club_graph()
    >>> communities = louvain(g)
    >>> mod = evaluation.surprise(g,communities)

    :References:

    1. Traag, V. A., Aldecoa, R., & Delvenne, J. C. (2015). `Detecting communities using asymptotical surprise. <https://link.aps.org/doi/10.1103/PhysRevE.92.022816/>`_ Physical Review E, 92(2), 022816.
    """
    graph = convert_graph_formats(graph, nx.Graph)
    m = graph.number_of_edges()
    n = graph.number_of_nodes()

    q = 0
    qa = 0
    sp = 0

    for community in communities.communities:
        c = nx.subgraph(graph, community)
        mc = c.number_of_edges()
        nc = c.number_of_nodes()

        q += mc
        qa += s.comb(nc, 2, exact=True)
    try:
        q = q / m
        qa = qa / s.comb(n, 2, exact=True)

        sp = m * (q * np.log(q / qa) + (1 - q) * np.log((1 - q) / (1 - qa)))
    except ZeroDivisionError:
        pass

    return FitnessResult(score=sp)
//  [python]
def surprise(graph: nx.Graph, communities: object, **kwargs: dict) -> object:
    """Surprise is statistical approach proposes a quality metric assuming that edges between vertices emerge randomly according to a hyper-geometric distribution.

    According to the Surprise metric, the higher the score of a partition, the less likely it is resulted from a random realization, the better the quality of the community structure.

    :param graph: a networkx/igraph object
    :param communities: NodeClustering object
    :return: FitnessResult object

    Example:

    >>> from cdlib.algorithms import louvain
    >>> from cdlib import evaluation
    >>> g = nx.karate_club_graph()
    >>> communities = louvain(g)
    >>> mod = evaluation.surprise(g,communities)

    :References:

    1. Traag, V. A., Aldecoa, R., & Delvenne, J. C. (2015). `Detecting communities using asymptotical surprise. <https://link.aps.org/doi/10.1103/PhysRevE.92.022816/>`_ Physical Review E, 92(2), 022816.
    """
    graph = convert_graph_formats(graph, nx.Graph)
    m = graph.number_of_edges()
    n = graph.number_of_nodes()

    q = 0
    qa = 0
    sp = 0

    for community in communities.communities:
        c = nx.subgraph(graph, community)
        mc = c.number_of_edges()
        nc = c.number_of_nodes()

        q += mc
        qa += scipy.special.comb(nc, 2, exact=True)
    try:
        q = q / m
        qa = qa / scipy.special.comb(n, 2, exact=True)

        sp = m * (q * np.log(q / qa) + (1 - q) * np.log((1 - q) / (1 - qa)))
    except ZeroDivisionError:
        pass

    return FitnessResult(score=sp)
//  [python]
def get_all_combinations(self, subset_size, superset=None):

        start_time = time.time()

        if superset is None:
            superset = np.arange(subset_size, dtype=np.int)

        alpha = int(subset_size / 2)

        if self.is_equal_split:
            combination_sizes = [alpha]
        else:
            combination_sizes = np.arange(1, alpha+1, dtype=np.int)

        num_combinations = 0
        for curr_combination_size in combination_sizes:
            num_combinations += int(scipy.misc.comb(subset_size, curr_combination_size))

        subsets1 = np.empty(num_combinations, dtype=np.object)
        subsets2 = np.empty(num_combinations, dtype=np.object)

        idx = -1
        none_idx = []
        for curr_combination_size in combination_sizes:
            for curr_subset in itertools.combinations(superset, curr_combination_size):
                idx += 1

                curr_subset = np.array(list(curr_subset))
                curr_subset_complement = np.setdiff1d(superset, curr_subset)

                if not self.compare_array_wrt_array_of_arrays(curr_subset, subsets2):
                    subsets1[idx] = curr_subset
                    subsets2[idx] = curr_subset_complement
                else:
                    none_idx.append(idx)
                    subsets1[idx] = None
                    subsets2[idx] = None

        if none_idx:
            none_idx = np.array(none_idx)
            all_idx = np.arange(num_combinations, dtype=np.int)
            not_none_idx = np.setdiff1d(all_idx, none_idx)
            del none_idx, all_idx
            subsets1 = subsets1[not_none_idx]
            subsets2 = subsets2[not_none_idx]
            del not_none_idx

        if self.debug:
            print('Time to compute combinations', time.time() - start_time)

        return subsets1, subsets2
//  [python]
def get_all_combinations(self, subset_size, superset=None):

        start_time = time.time()

        if superset is None:
            superset = np.arange(subset_size, dtype=np.int)

        alpha = int(subset_size / 2)

        if self.is_equal_split:
            combination_sizes = [alpha]
        else:
            combination_sizes = np.arange(1, alpha+1, dtype=np.int)

        num_combinations = 0
        for curr_combination_size in combination_sizes:
            num_combinations += int(scipy_special.comb(subset_size, curr_combination_size))

        subsets1 = np.empty(num_combinations, dtype=np.object)
        subsets2 = np.empty(num_combinations, dtype=np.object)

        idx = -1
        none_idx = []
        for curr_combination_size in combination_sizes:
            for curr_subset in itertools.combinations(superset, curr_combination_size):
                idx += 1

                curr_subset = np.array(list(curr_subset))
                curr_subset_complement = np.setdiff1d(superset, curr_subset)

                if not self.compare_array_wrt_array_of_arrays(curr_subset, subsets2):
                    subsets1[idx] = curr_subset
                    subsets2[idx] = curr_subset_complement
                else:
                    none_idx.append(idx)
                    subsets1[idx] = None
                    subsets2[idx] = None

        if none_idx:
            none_idx = np.array(none_idx)
            all_idx = np.arange(num_combinations, dtype=np.int)
            not_none_idx = np.setdiff1d(all_idx, none_idx)
            del none_idx, all_idx
            subsets1 = subsets1[not_none_idx]
            subsets2 = subsets2[not_none_idx]
            del not_none_idx

        if self.debug:
            print('Time to compute combinations', time.time() - start_time)

        return subsets1, subsets2
//  [python]
def with_special_errors(func):
    """
    Enable special function errors (such as underflow, overflow,
    loss of precision, etc.)
    """
    def wrapper(*a, **kw):
        old_filters = list(getattr(warnings, 'filters', []))
        old_errprint = sc.errprint(1)
        warnings.filterwarnings("error", category=sc.SpecialFunctionWarning)
        try:
            return func(*a, **kw)
        finally:
            sc.errprint(old_errprint)
            setattr(warnings, 'filters', old_filters)
    wrapper.__name__ = func.__name__
    wrapper.__doc__ = func.__doc__
    return wrapper
//  [python]
def with_special_errors(func):
    """
    Enable special function errors (such as underflow, overflow,
    loss of precision, etc.)
    """
    def wrapper(*a, **kw):
        old_filters = list(getattr(warnings, 'filters', []))
        old_errprint = sc.seterr(all='raise')
        warnings.filterwarnings("error", category=sc.SpecialFunctionWarning)
        try:
            return func(*a, **kw)
        finally:
            sc.seterr(**old_errprint)
            setattr(warnings, 'filters', old_filters)
    wrapper.__name__ = func.__name__
    wrapper.__doc__ = func.__doc__
    return wrapper
//  [python]
def test_errprint(self):
        with suppress_warnings() as sup:
            sup.filter(DeprecationWarning, "`errprint` is deprecated!")
            a = special.errprint()
            b = 1-a  # a is the state 1-a inverts state
            c = special.errprint(b)  # returns last state 'a'
            d = special.errprint(a)  # returns to original state
        assert_equal(a,c)
        assert_equal(d,b)
//  [python]
def test_errprint(self):
        with suppress_warnings() as sup:
            sup.filter(DeprecationWarning, "`errprint` is deprecated!")
            a = special.seterr(all='ignore')
            b = 1-a  # a is the state 1-a inverts state
            c = special.seterr(all='ignore')  # returns last state 'a'
            d = special.seterr(all='ignore')  # returns to original state
        assert_equal(a,c)
        assert_equal(d,b)
//  [python]
def test_errprint(self):
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            a = special.errprint()
            b = 1-a  # a is the state 1-a inverts state
            c = special.errprint(b)  # returns last state 'a'
            assert_equal(a,c)
            d = special.errprint(a)  # returns to original state
            assert_equal(d,b)
//  [python]
def test_errprint(self):
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            a = special.seterr()
            b = 1-a  # a is the state 1-a inverts state
            c = special.seterr(b)  # returns last state 'a'
            assert_equal(a,c)
            d = special.seterr(a)  # returns to original state
            assert_equal(d,b)
//  [python]
def test_fermions_states():
    import scipy.special

    hi = nkx.hilbert.SpinOrbitalFermions(5)
    assert hi.size == 5
    assert not hi.constrained
    assert hi.n_states == 2**5

    hi = nkx.hilbert.SpinOrbitalFermions(5, n_fermions=2)
    assert hi.size == 5
    assert hi.constrained
    assert np.all(hi.all_states().sum(axis=-1) == 2)
    assert hi.n_states == int(scipy.special.comb(5, 2))

    hi = nkx.hilbert.SpinOrbitalFermions(5, s=1 / 2, n_fermions=2)
    assert hi.size == 10
    assert hi.constrained
    np.testing.assert_array_equal(hi.all_states().sum(axis=-1), 2)
    # distribute 2 fermions over (2*number of orbitals)
    assert hi.n_states == int(scipy.special.comb(2 * 5, 2))

    hi = nkx.hilbert.SpinOrbitalFermions(5, s=1 / 2, n_fermions_per_spin=(2, 1))
    assert hi.size == 10
    assert hi.constrained
    np.testing.assert_array_equal(hi.all_states()[:, :5].sum(axis=-1), 2)
    np.testing.assert_array_equal(hi.all_states()[:, 5:].sum(axis=-1), 1)
    # product of all_states for -1/2 spin block and states for 1/2 block
    assert hi.n_states == int(scipy.special.comb(5, 2) * scipy.special.comb(5, 1))
//  [python]
def test_errprint():
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')
        flag = sc.errprint(True)
    try:
        assert_(isinstance(flag, bool))
        with warnings.catch_warnings(record=True) as w:
            sc.loggamma(0)
            assert_(w[-1].category is sc.SpecialFunctionWarning)
    finally:
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            sc.errprint(flag)
//  [python]
def test_errprint():
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')
        flag = sc.seterr(all='ignore')
    try:
        assert_(isinstance(flag, dict))
        with warnings.catch_warnings(record=True) as w:
            sc.loggamma(0)
            assert_(w[-1].category is sc.SpecialFunctionWarning)
    finally:
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            sc.seterr(**flag)
//  [python]
def _stats(self, a):
        sv = special.errprint(0)
        fac = asarray(special.zeta(a,1))
        mu = special.zeta(a-1.0,1)/fac
        mu2p = special.zeta(a-2.0,1)/fac
        var = mu2p - mu*mu
        mu3p = special.zeta(a-3.0,1)/fac
        mu3 = mu3p - 3*mu*mu2p + 2*mu**3
        g1 = mu3 / asarray(var**1.5)

        mu4p = special.zeta(a-4.0,1)/fac
        sv = special.errprint(sv)
        mu4 = mu4p - 4*mu3p*mu + 6*mu2p*mu*mu - 3*mu**4
        g2 = mu4 / asarray(var**2) - 3.0
        return mu, var, g1, g2
//  [python]
def _stats(self, a):
        sv = special.seterr(0)
        fac = asarray(special.zeta(a,1))
        mu = special.zeta(a-1.0,1)/fac
        mu2p = special.zeta(a-2.0,1)/fac
        var = mu2p - mu*mu
        mu3p = special.zeta(a-3.0,1)/fac
        mu3 = mu3p - 3*mu*mu2p + 2*mu**3
        g1 = mu3 / asarray(var**1.5)

        mu4p = special.zeta(a-4.0,1)/fac
        sv = special.seterr(sv)
        mu4 = mu4p - 4*mu3p*mu + 6*mu2p*mu*mu - 3*mu**4
        g2 = mu4 / asarray(var**2) - 3.0
        return mu, var, g1, g2
//  [python]
def factorial(n,exact=0):
    """
    The factorial function, n! = special.gamma(n+1).

    If exact is 0, then floating point precision is used, otherwise
    exact long integer is computed.

    - Array argument accepted only for exact=0 case.
    - If n<0, the return value is 0.

    Parameters
    ----------
    n : int or array_like of ints
        Calculate ``n!``.  Arrays are only supported with `exact` set
        to False.  If ``n < 0``, the return value is 0.
    exact : bool, optional
        The result can be approximated rapidly using the gamma-formula
        above.  If `exact` is set to True, calculate the
        answer exactly using integer arithmetic. Default is False.

    Returns
    -------
    nf : float or int
        Factorial of `n`, as an integer or a float depending on `exact`.

    Examples
    --------
    >>> arr = np.array([3,4,5])
    >>> sc.factorial(arr, exact=False)
    array([   6.,   24.,  120.])
    >>> sc.factorial(5, exact=True)
    120L

    """
    if exact:
        if n < 0:
            return 0
        val = 1
        for k in xrange(1,n+1):
            val *= k
        return val
    else:
        from scipy import special
        n = asarray(n)
        sv = special.errprint(0)
        vals = special.gamma(n+1)
        sv = special.errprint(sv)
        return where(n >= 0,vals,0)
//  [python]
def factorial(n,exact=0):
    """
    The factorial function, n! = special.gamma(n+1).

    If exact is 0, then floating point precision is used, otherwise
    exact long integer is computed.

    - Array argument accepted only for exact=0 case.
    - If n<0, the return value is 0.

    Parameters
    ----------
    n : int or array_like of ints
        Calculate ``n!``.  Arrays are only supported with `exact` set
        to False.  If ``n < 0``, the return value is 0.
    exact : bool, optional
        The result can be approximated rapidly using the gamma-formula
        above.  If `exact` is set to True, calculate the
        answer exactly using integer arithmetic. Default is False.

    Returns
    -------
    nf : float or int
        Factorial of `n`, as an integer or a float depending on `exact`.

    Examples
    --------
    >>> arr = np.array([3,4,5])
    >>> sc.factorial(arr, exact=False)
    array([   6.,   24.,  120.])
    >>> sc.factorial(5, exact=True)
    120L

    """
    if exact:
        if n < 0:
            return 0
        val = 1
        for k in xrange(1,n+1):
            val *= k
        return val
    else:
        from scipy import special
        n = asarray(n)
        sv = special.seterr(0)
        vals = special.gamma(n+1)
        sv = special.seterr(sv)
        return where(n >= 0,vals,0)
//  [python]
def comb(N,k,exact=1):
    if exact:
        if (k > N) or (N < 0) or (k < 0):
            return 0
        val = 1
        for j in xrange(min(k, N-k)):
            val = (val*(N-j))//(j+1)
        return val
    else:
        from scipy import special
        k,N = sp.asarray(k), sp.asarray(N)
        lgam = special.gammaln
        cond = (k <= N) & (N >= 0) & (k >= 0)
        sv = special.errprint(0)
        vals = sp.exp(lgam(N+1) - lgam(N-k+1) - lgam(k+1))
        sv = special.errprint(sv)
        return sp.where(cond, vals, 0.0)
//  [python]
def comb(N,k,exact=1):
    if exact:
        if (k > N) or (N < 0) or (k < 0):
            return 0
        val = 1
        for j in xrange(min(k, N-k)):
            val = (val*(N-j))//(j+1)
        return val
    else:
        from scipy import special
        k,N = sp.asarray(k), sp.asarray(N)
        lgam = special.gammaln
        cond = (k <= N) & (N >= 0) & (k >= 0)
        sv = special.seterr(all='ignore')
        vals = sp.exp(lgam(N+1) - lgam(N-k+1) - lgam(k+1))
        special.seterr(**sv)
        return sp.where(cond, vals, 0.0)
//  [python]
def set_floating_point_fatality():
    """Decide what to do when this thread encounters a floating point error in scipy/numpy."""
    warnings.simplefilter('error')  # Raise exception on scipy/numpy RuntimeWarning
    scipy.seterr(all='raise')
    np.seterrcall(NumpyLogger())
    np.seterr(all='raise')

    # Over- and underflow is bad, but we shouldn't stop someone mid-mission for it.
    np.seterr(over='log', under='log')
//  [python]
def set_floating_point_fatality():
    """Decide what to do when this thread encounters a floating point error in scipy/numpy."""
    warnings.simplefilter('error')  # Raise exception on scipy/numpy RuntimeWarning
    scipy.special.seterr(all='raise')
    np.seterrcall(NumpyLogger())
    np.seterr(all='raise')

    # Over- and underflow is bad, but we shouldn't stop someone mid-mission for it.
    np.seterr(over='log', under='log')
//  [python]
def test_seterr():
    entry_err = s.geterr()
    try:
        for category in _sf_error_code_map.keys():
            for action in _sf_error_actions:
                geterr_olderr = s.geterr()
                seterr_olderr = s.seterr(**{category: action})
                assert_(geterr_olderr == seterr_olderr)
                newerr = s.geterr()
                assert_(newerr[category] == action)
                geterr_olderr.pop(category)
                newerr.pop(category)
                assert_(geterr_olderr == newerr)
                _check_action(_sf_error_test_function,
                              (_sf_error_code_map[category],),
                               action)
    finally:
        s.seterr(**entry_err)
//  [python]
def test_seterr():
    entry_err = sc.geterr()
    try:
        for category in _sf_error_code_map.keys():
            for action in _sf_error_actions:
                geterr_olderr = sc.geterr()
                seterr_olderr = sc.seterr(**{category: action})
                assert_(geterr_olderr == seterr_olderr)
                newerr = sc.geterr()
                assert_(newerr[category] == action)
                geterr_olderr.pop(category)
                newerr.pop(category)
                assert_(geterr_olderr == newerr)
                _check_action(_sf_error_test_function,
                              (_sf_error_code_map[category],),
                               action)
    finally:
        sc.seterr(**entry_err)
//  [python]
def test_seterr():
    entry_err = s.geterr()
    try:
        for category, error_code in _sf_error_code_map.items():
            for action in _sf_error_actions:
                geterr_olderr = s.geterr()
                seterr_olderr = s.seterr(**{category: action})
                assert_(geterr_olderr == seterr_olderr)
                newerr = s.geterr()
                assert_(newerr[category] == action)
                geterr_olderr.pop(category)
                newerr.pop(category)
                assert_(geterr_olderr == newerr)
                _check_action(_sf_error_test_function, (error_code,), action)
    finally:
        s.seterr(**entry_err)
//  [python]
def test_seterr():
    entry_err = sc.geterr()
    try:
        for category, error_code in _sf_error_code_map.items():
            for action in _sf_error_actions:
                geterr_olderr = sc.geterr()
                seterr_olderr = sc.seterr(**{category: action})
                assert_(geterr_olderr == seterr_olderr)
                newerr = sc.geterr()
                assert_(newerr[category] == action)
                geterr_olderr.pop(category)
                newerr.pop(category)
                assert_(geterr_olderr == newerr)
                _check_action(_sf_error_test_function, (error_code,), action)
    finally:
        sc.seterr(**entry_err)
//  [python]
def smooth(x, window='boxcar', half_win=3):
    """
    performs smoothing in interested time window

    Parameters
    --------------
    x: timeseris data
    window: types of window to do smoothing
    half_win: half window length

    RETURNS:
    ------------------
    y: smoothed time window
    """
    # TODO: docsting
    window_len = 2 * half_win + 1
    # extending the data at beginning and at the end
    # to apply the window at the borders
    s = np.r_[x[window_len - 1:0:-1], x, x[-1:-window_len:-1]]
    if window == "boxcar":
        w = scipy.signal.boxcar(window_len).astype('complex')
    else:
        w = scipy.signal.hanning(window_len).astype('complex')
    y = np.convolve(w / w.sum(), s, mode='valid')
    return y[half_win:len(y) - half_win]
//  [python]
def smooth(x, window='boxcar', half_win=3):
    """
    performs smoothing in interested time window

    Parameters
    --------------
    x: timeseris data
    window: types of window to do smoothing
    half_win: half window length

    RETURNS:
    ------------------
    y: smoothed time window
    """
    # TODO: docsting
    window_len = 2 * half_win + 1
    # extending the data at beginning and at the end
    # to apply the window at the borders
    s = np.r_[x[window_len - 1:0:-1], x, x[-1:-window_len:-1]]
    if window == "boxcar":
        w = scipy.signal.boxcar(window_len).astype('complex')
    else:
        w = scipy.signal.windows.hann(window_len).astype('complex')
    y = np.convolve(w / w.sum(), s, mode='valid')
    return y[half_win:len(y) - half_win]
//  [python]
def comb(N,k,exact=0):
    """
    The number of combinations of N things taken k at a time.

    This is often expressed as "N choose k".

    Parameters
    ----------
    N : int, ndarray
        Number of things.
    k : int, ndarray
        Number of elements taken.
    exact : int, optional
        If `exact` is 0, then floating point precision is used, otherwise
        exact long integer is computed.

    Returns
    -------
    val : int, ndarray
        The total number of combinations.

    Notes
    -----
    - Array arguments accepted only for exact=0 case.
    - If k > N, N < 0, or k < 0, then a 0 is returned.

    Examples
    --------
    >>> k = np.array([3, 4])
    >>> n = np.array([10, 10])
    >>> sc.comb(n, k, exact=False)
    array([ 120.,  210.])
    >>> sc.comb(10, 3, exact=True)
    120L

    """
    if exact:
        if (k > N) or (N < 0) or (k < 0):
            return 0
        val = 1
        for j in xrange(min(k, N-k)):
            val = (val*(N-j))//(j+1)
        return val
    else:
        from scipy import special
        k,N = asarray(k), asarray(N)
        lgam = special.gammaln
        cond = (k <= N) & (N >= 0) & (k >= 0)
        sv = special.errprint(0)
        vals = exp(lgam(N+1) - lgam(N-k+1) - lgam(k+1))
        sv = special.errprint(sv)
        return where(cond, vals, 0.0)
//  [python]
def comb(N,k,exact=0):
    """
    The number of combinations of N things taken k at a time.

    This is often expressed as "N choose k".

    Parameters
    ----------
    N : int, ndarray
        Number of things.
    k : int, ndarray
        Number of elements taken.
    exact : int, optional
        If `exact` is 0, then floating point precision is used, otherwise
        exact long integer is computed.

    Returns
    -------
    val : int, ndarray
        The total number of combinations.

    Notes
    -----
    - Array arguments accepted only for exact=0 case.
    - If k > N, N < 0, or k < 0, then a 0 is returned.

    Examples
    --------
    >>> k = np.array([3, 4])
    >>> n = np.array([10, 10])
    >>> sc.comb(n, k, exact=False)
    array([ 120.,  210.])
    >>> sc.comb(10, 3, exact=True)
    120L

    """
    if exact:
        if (k > N) or (N < 0) or (k < 0):
            return 0
        val = 1
        for j in xrange(min(k, N-k)):
            val = (val*(N-j))//(j+1)
        return val
    else:
        from scipy import special
        k,N = asarray(k), asarray(N)
        lgam = special.gammaln
        cond = (k <= N) & (N >= 0) & (k >= 0)
        sv = special.seterr(all='ignore')
        vals = exp(lgam(N+1) - lgam(N-k+1) - lgam(k+1))
        special.seterr(**sv)
        return where(cond, vals, 0.0)
//  [python]
def smooth_features(features, win_len_smooth):
    # Apply temporal smoothing
    win = scipy.signal.hanning(win_len_smooth + 2, sym=False)
    win /= np.sum(win)
    win = np.atleast_2d(win)

    features = scipy.signal.convolve2d(features, win, mode='same')

    return features
//  [python]
def smooth_features(features, win_len_smooth):
    # Apply temporal smoothing
    win = scipy.signal.windows.hann(win_len_smooth + 2, sym=False)
    win /= np.sum(win)
    win = np.atleast_2d(win)

    features = scipy.signal.convolve2d(features, win, mode='same')

    return features
//  [python]
def burst(self, value):
		self._burst = value
		if self.burst is not None:
			windowed_samples = self.burst.samples * scipy.signal.hanning(len(self.burst.samples))
			spectrum = numpy.fft.fftshift(numpy.fft.fft(windowed_samples))
			self._mag_spectrum = numpy.log(numpy.absolute(spectrum))
			self._burst_max = max(self._mag_spectrum)
		self.update()
//  [python]
def burst(self, value):
		self._burst = value
		if self.burst is not None:
			windowed_samples = self.burst.samples * scipy.signal.windows.hann(len(self.burst.samples))
			spectrum = numpy.fft.fftshift(numpy.fft.fft(windowed_samples))
			self._mag_spectrum = numpy.log(numpy.absolute(spectrum))
			self._burst_max = max(self._mag_spectrum)
		self.update()
//  [python]
def linsmoothm(x, n):
    le = len(x)
    x = x.reshape((le))
    w = signal.hanning(n)
    w = w / np.sum(w)
    y = np.zeros((le))
    if np.mod(n, 2) == 0:
        l = int(n / 2)
        x = [1 * x[0], x, np.ones(l) * x[le - 1]]
        temp = []
        for sublist in x:
            for item in sublist:
                temp.append(item)
        x = np.array(temp)

    else:
        l = int((n - 1) / 2)
        x = [np.ones(1) * x[0], x, np.ones(l + 1) * x[le - 1]]
        temp = []
        for sublist in x:
            for item in sublist:
                temp.append(item)
        x = np.array(temp)

    for k in range(0, le):
        y[k] = np.dot(w, x[k:k + n])
    y = y.flatten()

    return y
//  [python]
def linsmoothm(x, n):
    le = len(x)
    x = x.reshape((le))
    w = signal.windows.hann(n)
    w = w / np.sum(w)
    y = np.zeros((le))
    if np.mod(n, 2) == 0:
        l = int(n / 2)
        x = [1 * x[0], x, np.ones(l) * x[le - 1]]
        temp = []
        for sublist in x:
            for item in sublist:
                temp.append(item)
        x = np.array(temp)

    else:
        l = int((n - 1) / 2)
        x = [np.ones(1) * x[0], x, np.ones(l + 1) * x[le - 1]]
        temp = []
        for sublist in x:
            for item in sublist:
                temp.append(item)
        x = np.array(temp)

    for k in range(0, le):
        y[k] = np.dot(w, x[k:k + n])
    y = y.flatten()

    return y
//  [python]
def __init__(self):
		super(burst_detector, self).__init__(
			name="Burst Detector",
			in_sig=[numpy.complex64],
			out_sig=[numpy.complex64]
		)

		self._burst_tag_symbol = gr.pmt.string_to_symbol('burst')
		self._burst = False

		self.block_size = 256
		
		self.hysteresis_timeout = 3 #int(math.ceil(768 / self.block_size))
		self.hysteresis_count = 0

		self.fft_window = scipy.signal.hanning(self.block_size)
		self.fft_in = pyfftw.n_byte_align_empty((self.block_size,), self.block_size, dtype='complex64')
		self.fft_out = pyfftw.n_byte_align_empty((self.block_size,), self.block_size, dtype='complex64')
		self.fft = pyfftw.FFTW(self.fft_in, self.fft_out)
//  [python]
def __init__(self):
		super(burst_detector, self).__init__(
			name="Burst Detector",
			in_sig=[numpy.complex64],
			out_sig=[numpy.complex64]
		)

		self._burst_tag_symbol = gr.pmt.string_to_symbol('burst')
		self._burst = False

		self.block_size = 256
		
		self.hysteresis_timeout = 3 #int(math.ceil(768 / self.block_size))
		self.hysteresis_count = 0

		self.fft_window = scipy.signal.windows.hann(self.block_size)
		self.fft_in = pyfftw.n_byte_align_empty((self.block_size,), self.block_size, dtype='complex64')
		self.fft_out = pyfftw.n_byte_align_empty((self.block_size,), self.block_size, dtype='complex64')
		self.fft = pyfftw.FFTW(self.fft_in, self.fft_out)
//  [python]
def smooth(x, window="boxcar", half_win=3):
    """some window smoothing"""
    # TODO: docsting
    window_len = 2 * half_win + 1
    # extending the data at beginning and at the end
    # to apply the window at the borders
    s = np.r_[x[window_len - 1 : 0 : -1], x, x[-1:-window_len:-1]]
    if window == "boxcar":
        w = scipy.signal.boxcar(window_len).astype("complex")
    else:
        w = scipy.signal.hanning(window_len).astype("complex")
    y = np.convolve(w / w.sum(), s, mode="valid")
    return y[half_win : len(y) - half_win]
//  [python]
def smooth(x, window="boxcar", half_win=3):
    """some window smoothing"""
    # TODO: docsting
    window_len = 2 * half_win + 1
    # extending the data at beginning and at the end
    # to apply the window at the borders
    s = np.r_[x[window_len - 1 : 0 : -1], x, x[-1:-window_len:-1]]
    if window == "boxcar":
        w = scipy.signal.boxcar(window_len).astype("complex")
    else:
        w = scipy.signal.windows.hann(window_len).astype("complex")
    y = np.convolve(w / w.sum(), s, mode="valid")
    return y[half_win : len(y) - half_win]
//  [python]
def gfp_smoothing(gfp, method, window):
    """
    Smoothe the Global Field Power Curve
 
    Args:
        gfp (ndarray):
            Array containing values for all time frames.
            Dimension: number of time frames x 1
        method ({'hamming', 'hanning'}):
            `hamming` : use hamming window to smooth
            `hanning` : use hanning window to smooth
        window (int):
            about 100
        
    Returns:
        smooth : array
			smoothed GFP curve
    """
    if method == 'hamming':
        smooth = scipy.signal.convolve(gfp, scipy.signal.hamming(window) )
    elif method == 'hanning':
        smooth = scipy.signal.convolve(gfp, scipy.signal.hanning(window) )
    return smooth
//  [python]
def gfp_smoothing(gfp, method, window):
    """
    Smoothe the Global Field Power Curve
 
    Args:
        gfp (ndarray):
            Array containing values for all time frames.
            Dimension: number of time frames x 1
        method ({'hamming', 'hanning'}):
            `hamming` : use hamming window to smooth
            `hanning` : use hanning window to smooth
        window (int):
            about 100
        
    Returns:
        smooth : array
			smoothed GFP curve
    """
    if method == 'hamming':
        smooth = scipy.signal.convolve(gfp, scipy.signal.hamming(window) )
    elif method == 'hanning':
        smooth = scipy.signal.convolve(gfp, scipy.signal.windows.hann(window) )
    return smooth
//  [python]
def generate():
    lines = []

    # Header
    lines.append("local radio = require('radio')")
    lines.append("")
    lines.append("local M = {}")

    # Window functions
    lines.append("M.window_rectangular = " + serialize(scipy.signal.boxcar(128).astype(numpy.float32)))
    lines.append("M.window_rectangular_periodic = " + serialize(scipy.signal.boxcar(128, False).astype(numpy.float32)))
    lines.append("M.window_hamming = " + serialize(scipy.signal.hamming(128).astype(numpy.float32)))
    lines.append("M.window_hamming_periodic = " + serialize(scipy.signal.hamming(128, False).astype(numpy.float32)))
    lines.append("M.window_hanning = " + serialize(scipy.signal.hanning(128).astype(numpy.float32)))
    lines.append("M.window_hanning_periodic = " + serialize(scipy.signal.hanning(128, False).astype(numpy.float32)))
    lines.append("M.window_bartlett = " + serialize(scipy.signal.bartlett(128).astype(numpy.float32)))
    lines.append("M.window_bartlett_periodic = " + serialize(scipy.signal.bartlett(128, False).astype(numpy.float32)))
    lines.append("M.window_blackman = " + serialize(scipy.signal.blackman(128).astype(numpy.float32)))
    lines.append("M.window_blackman_periodic = " + serialize(scipy.signal.blackman(128, False).astype(numpy.float32)))
    lines.append("")

    lines.append("return M")

    return RawSpec("\n".join(lines))
//  [python]
def generate():
    lines = []

    # Header
    lines.append("local radio = require('radio')")
    lines.append("")
    lines.append("local M = {}")

    # Window functions
    lines.append("M.window_rectangular = " + serialize(scipy.signal.boxcar(128).astype(numpy.float32)))
    lines.append("M.window_rectangular_periodic = " + serialize(scipy.signal.boxcar(128, False).astype(numpy.float32)))
    lines.append("M.window_hamming = " + serialize(scipy.signal.hamming(128).astype(numpy.float32)))
    lines.append("M.window_hamming_periodic = " + serialize(scipy.signal.hamming(128, False).astype(numpy.float32)))
    lines.append("M.window_hanning = " + serialize(scipy.signal.windows.hann(128).astype(numpy.float32)))
    lines.append("M.window_hanning_periodic = " + serialize(scipy.signal.windows.hann(128, False).astype(numpy.float32)))
    lines.append("M.window_bartlett = " + serialize(scipy.signal.bartlett(128).astype(numpy.float32)))
    lines.append("M.window_bartlett_periodic = " + serialize(scipy.signal.bartlett(128, False).astype(numpy.float32)))
    lines.append("M.window_blackman = " + serialize(scipy.signal.blackman(128).astype(numpy.float32)))
    lines.append("M.window_blackman_periodic = " + serialize(scipy.signal.blackman(128, False).astype(numpy.float32)))
    lines.append("")

    lines.append("return M")

    return RawSpec("\n".join(lines))
//  [python]
def compute(self):
        size = self.get_input("Window Size")

        out = SparseMatrix()
        out.matrix = sparse.csc_matrix(scipy.signal.hanning(size))
        self.set_output("Window", out)
//  [python]
def compute(self):
        size = self.get_input("Window Size")

        out = SparseMatrix()
        out.matrix = sparse.csc_matrix(scipy.signal.windows.hann(size))
        self.set_output("Window", out)
//  [python]
def smooth_hanning(x,k):
    """
    Convolve `x` with a Hanning window of length `k`.

    :param x: signal to be convolved
    :param k: size of Hanning window in samples

    :returns: convolved signal with same length as x
    """
    return np.convolve(x,signal.hanning(k)*2/(k-1),'same')
//  [python]
def smooth_hanning(x,k):
    """
    Convolve `x` with a Hanning window of length `k`.

    :param x: signal to be convolved
    :param k: size of Hanning window in samples

    :returns: convolved signal with same length as x
    """
    return np.convolve(x,signal.windows.hann(k)*2/(k-1),'same')
//  [python]
def NMREval(self, xn, xnhat):
        """ Method to perform NMR perceptual evaluation of audio quality between two signals.
        Args        :
            xn      :   (ndarray) 1D Array containing the true time domain signal.
            xnhat   :   (ndarray) 1D Array containing the estimated time domain signal.
        Returns     :
            NMR     :   (float)   A float measurement in dB providing a perceptually weighted
                        evaluation. Below -9 dB can be considered as in-audible difference/error.
        As appears in :
        - K. Brandenburg and T. Sporer,  “NMR and Masking Flag: Evaluation of Quality Using Perceptual Criteria,” in
        Proceedings of the AES 11th International Conference on Test and Measurement, Portland, USA, May 1992, pp. 169–179
        - J. Nikunen and T. Virtanen, "Noise-to-mask ratio minimization by weighted non-negative matrix factorization," in
         Acoustics Speech and Signal Processing (ICASSP), 2010 IEEE International Conference on, Dallas, TX, 2010, pp. 25-28.
        """
        mX, _ = TimeFrequencyDecomposition.STFT(xn, hanning(self.nfft/2 + 1), self.nfft, self.nfft/4)
        mXhat, _ = TimeFrequencyDecomposition.STFT(xnhat, hanning(self.nfft/2 + 1), self.nfft, self.nfft/4)

        # Compute Error
        Err = np.abs(mX - mXhat) ** 2.

        # Acquire Masking Threshold
        mT = self.maskingThreshold(mX)

        # Inverse the filter of masking threshold
        imT = 1./(mT + eps)

        # Outer/Middle Ear transfer function on the diagonal
        LTq = 10 ** (self.MOEar()/20.)

        # NMR computation
        NMR = 10. * np.log10((1./mX.shape[0]) * self._maxb * np.sum((imT * (Err*LTq))))
        print(NMR)
        return NMR
//  [python]
def NMREval(self, xn, xnhat):
        """ Method to perform NMR perceptual evaluation of audio quality between two signals.
        Args        :
            xn      :   (ndarray) 1D Array containing the true time domain signal.
            xnhat   :   (ndarray) 1D Array containing the estimated time domain signal.
        Returns     :
            NMR     :   (float)   A float measurement in dB providing a perceptually weighted
                        evaluation. Below -9 dB can be considered as in-audible difference/error.
        As appears in :
        - K. Brandenburg and T. Sporer,  “NMR and Masking Flag: Evaluation of Quality Using Perceptual Criteria,” in
        Proceedings of the AES 11th International Conference on Test and Measurement, Portland, USA, May 1992, pp. 169–179
        - J. Nikunen and T. Virtanen, "Noise-to-mask ratio minimization by weighted non-negative matrix factorization," in
         Acoustics Speech and Signal Processing (ICASSP), 2010 IEEE International Conference on, Dallas, TX, 2010, pp. 25-28.
        """
        mX, _ = TimeFrequencyDecomposition.STFT(xn, scipy.signal.windows.hann(self.nfft//2 + 1), self.nfft, self.nfft//4)
        mXhat, _ = TimeFrequencyDecomposition.STFT(xnhat, scipy.signal.windows.hann(self.nfft//2 + 1), self.nfft, self.nfft//4)

        # Compute Error
        Err = np.abs(mX - mXhat) ** 2.

        # Acquire Masking Threshold
        mT = self.maskingThreshold(mX)

        # Inverse the filter of masking threshold
        imT = 1./(mT + eps)

        # Outer/Middle Ear transfer function on the diagonal
        LTq = 10 ** (self.MOEar()/20.)

        # NMR computation
        NMR = 10. * np.log10((1./mX.shape[0]) * self._maxb * np.sum((imT * (Err*LTq))))
        print(NMR)
        return NMR
//  [python]
def hanning2d( a, b ):
    # build 2d window
    w2d = np.outer(ss.hanning(a), ss.hanning(b))
    return np.sqrt(w2d)
//  [python]
def hanning2d( a, b ):
    # build 2d window
    w2d = np.outer(ss.windows.hann(a), ss.windows.hann(b))
    return np.sqrt(w2d)
//  [python]
def smooth(x, window='boxcar', half_win=3):
    """ some window smoothing """
    window_len = 2 * half_win + 1
    # extending the data at beginning and at the end
    # to apply the window at the borders
    s = np.r_[x[window_len - 1:0:-1], x, x[-1:-window_len:-1]]
    if window == "boxcar":
        w = scipy.signal.boxcar(window_len).astype('complex')
    else:
        w = scipy.signal.hanning(window_len).astype('complex')
    y = np.convolve(w / w.sum(), s, mode='valid')
    return y[half_win:len(y) - half_win]
//  [python]
def smooth(x, window='boxcar', half_win=3):
    """ some window smoothing """
    window_len = 2 * half_win + 1
    # extending the data at beginning and at the end
    # to apply the window at the borders
    s = np.r_[x[window_len - 1:0:-1], x, x[-1:-window_len:-1]]
    if window == "boxcar":
        w = scipy.signal.boxcar(window_len).astype('complex')
    else:
        w = scipy.signal.windows.hann(window_len).astype('complex')
    y = np.convolve(w / w.sum(), s, mode='valid')
    return y[half_win:len(y) - half_win]
//  [python]
def plot_spectrogram(samples, sample_rate, title, pdf_file):
    
    window_size_sec = .005
    hop_size_percent = 20
    
    window_size = int(round(window_size_sec * sample_rate))
    window = signal.hanning(window_size, sym=False)
    hop_size = \
        int(round(window_size_sec * hop_size_percent / 100 * sample_rate))
        
    dft_size = 2 * tfa_utils.get_dft_size(window_size)
    
    gram = tfa_utils.compute_spectrogram(samples, window, hop_size, dft_size)
    
    gram = tfa_utils.linear_to_log(gram)
    
    # plot_histogram(gram)
    
    hop_size_sec = window_size_sec * hop_size_percent / 100
    times = np.arange(len(gram)) * hop_size_sec + window_size_sec / 2
    
    num_bins = dft_size / 2 + 1
    bin_size = sample_rate / dft_size
    freqs = np.arange(num_bins) * bin_size
        
    x = gram.transpose()
    
    plt.figure(figsize=(12, 6))
        
    start_time = times[0] - hop_size_sec / 2
    end_time = times[-1] + hop_size_sec / 2
    start_freq = freqs[0]
    end_freq = freqs[-1]
    extent = (start_time, end_time, start_freq, end_freq)
    
    # `vmin` and `vmax` were chosen by looking at histogram of spectrogram
    # values plotted by `plot_histogram` function.
    plt.imshow(
        x, cmap='gray_r', vmin=-25, vmax=125, origin='lower', extent=extent,
        aspect='auto')
    
    plt.title(title)
    plt.xlabel('Time (s)')
    plt.ylabel('Frequency (Hz)')
    # plt.ylim(0, 11000)

    pdf_file.savefig()
    
    plt.close()
//  [python]
def plot_spectrogram(samples, sample_rate, title, pdf_file):
    
    window_size_sec = .005
    hop_size_percent = 20
    
    window_size = int(round(window_size_sec * sample_rate))
    window = signal.windows.hann(window_size, sym=False)
    hop_size = \
        int(round(window_size_sec * hop_size_percent / 100 * sample_rate))
        
    dft_size = 2 * tfa_utils.get_dft_size(window_size)
    
    gram = tfa_utils.compute_spectrogram(samples, window, hop_size, dft_size)
    
    gram = tfa_utils.linear_to_log(gram)
    
    # plot_histogram(gram)
    
    hop_size_sec = window_size_sec * hop_size_percent / 100
    times = np.arange(len(gram)) * hop_size_sec + window_size_sec / 2
    
    num_bins = dft_size / 2 + 1
    bin_size = sample_rate / dft_size
    freqs = np.arange(num_bins) * bin_size
        
    x = gram.transpose()
    
    plt.figure(figsize=(12, 6))
        
    start_time = times[0] - hop_size_sec / 2
    end_time = times[-1] + hop_size_sec / 2
    start_freq = freqs[0]
    end_freq = freqs[-1]
    extent = (start_time, end_time, start_freq, end_freq)
    
    # `vmin` and `vmax` were chosen by looking at histogram of spectrogram
    # values plotted by `plot_histogram` function.
    plt.imshow(
        x, cmap='gray_r', vmin=-25, vmax=125, origin='lower', extent=extent,
        aspect='auto')
    
    plt.title(title)
    plt.xlabel('Time (s)')
    plt.ylabel('Frequency (Hz)')
    # plt.ylim(0, 11000)

    pdf_file.savefig()
    
    plt.close()
//  [python]
def preparePSF(md, PSSize):
    global PSFFileName, cachedPSF, cachedOTF2, cachedOTFH, autocorr
    
    PSFFilename = md['PSFFile']
                
    if (not (PSFFileName == PSFFilename)) or (not (cachedPSF.shape == PSSize)):
        try:
            ps, vox = md['taskQueue'].getQueueData(md['dataSourceID'], 'PSF')
        except:
            #fid = open(getFullExistingFilename(PSFFilename), 'rb')
            #ps, vox = pickle.load(fid)
            #fid.close()
            ps, vox = load_psf(PSFFilename)
            
        ps = ps.max(2)
        ps = ps - ps.min()
        #ps = ps*(ps > 0)
        ps = ps*scipy.signal.hanning(ps.shape[0])[:,None]*scipy.signal.hanning(ps.shape[1])[None,:]
        ps = ps/ps.sum()
        PSFFileName = PSFFilename
        pw = (numpy.array(PSSize) - ps.shape)/2.
        pw1 = numpy.floor(pw)
        pw2 = numpy.ceil(pw)
        cachedPSF = pad.with_constant(ps, ((pw2[0], pw1[0]), (pw2[1], pw1[1])), (0,))
        cachedOTFH = ifftn(cachedPSF)*cachedPSF.size
        cachedOTF2 = cachedOTFH*fftn(cachedPSF)
//  [python]
def preparePSF(md, PSSize):
    global PSFFileName, cachedPSF, cachedOTF2, cachedOTFH, autocorr
    
    PSFFilename = md['PSFFile']
                
    if (not (PSFFileName == PSFFilename)) or (not (cachedPSF.shape == PSSize)):
        try:
            ps, vox = md['taskQueue'].getQueueData(md['dataSourceID'], 'PSF')
        except:
            #fid = open(getFullExistingFilename(PSFFilename), 'rb')
            #ps, vox = pickle.load(fid)
            #fid.close()
            ps, vox = load_psf(PSFFilename)
            
        ps = ps.max(2)
        ps = ps - ps.min()
        #ps = ps*(ps > 0)
        ps = ps*scipy.signal.windows.hann(ps.shape[0])[:,None]*scipy.signal.windows.hann(ps.shape[1])[None,:]
        ps = ps/ps.sum()
        PSFFileName = PSFFilename
        pw = (numpy.array(PSSize) - ps.shape)/2.
        pw1 = numpy.floor(pw)
        pw2 = numpy.ceil(pw)
        cachedPSF = pad.with_constant(ps, ((pw2[0], pw1[0]), (pw2[1], pw1[1])), (0,))
        cachedOTFH = ifftn(cachedPSF)*cachedPSF.size
        cachedOTF2 = cachedOTFH*fftn(cachedPSF)
//  [python]
def hanning3d( a, b, c ):
    w2d = np.outer(ss.hanning(a), ss.hanning(b))
    w3d = np.zeros((a,b,c))
    for i in range(a):
        w3d[i, :, :] = np.outer(w2d[i,:].flatten(), ss.hanning(c))
    return w3d**(1.0/3.0)
//  [python]
def hanning3d( a, b, c ):
    w2d = np.outer(ss.windows.hann(a), ss.windows.hann(b))
    w3d = np.zeros((a,b,c))
    for i in range(a):
        w3d[i, :, :] = np.outer(w2d[i,:].flatten(), ss.windows.hann(c))
    return w3d**(1.0/3.0)
//  [python]
fs = 1000.0
t = np.arange(0,100,1/fs)
x = signal.chirp(t,0,t[-1],300,method='quadratic')

#%%
nfft = 512
win = signal.hanning(nfft)
//  [python]
fs = 1000.0
t = np.arange(0,100,1/fs)
x = signal.chirp(t,0,t[-1],300,method='quadratic')

#%%
nfft = 512
win = signal.windows.hann(nfft)
//  [python]
def stft(x, framesamp=256, hopsamp=64):
    w = scipy.signal.hanning(framesamp, False)
    w = np.sqrt(w)
    X = scipy.array([scipy.fft(w*x[i:i+framesamp]) 
                     for i in range(0, len(x)-framesamp+1, hopsamp)])
    return X
//  [python]
def stft(x, framesamp=256, hopsamp=64):
    w = scipy.signal.windows.hann(framesamp, False)
    w = np.sqrt(w)
    X = scipy.array([scipy.fft(w*x[i:i+framesamp]) 
                     for i in range(0, len(x)-framesamp+1, hopsamp)])
    return X
//  [python]
def get_power(wave, frame_rate, frame_length, frame_move, window_func=None):
    frame = frame_rate * frame_length
    overlap = frame_rate * frame_move
    step = frame - overlap
    frame_total = int(math.ceil(len(wave) / step))
    energy = np.zeros(frame_total)
    for i in range(frame_total):
        window = wave[np.arange(i * step, min(i * step + frame, len(wave)))]
        if window_func == "hanning":
            energy[i] = sum(np.multiply(window ** 2, scipy.signal.hanning(len(window))))
        else:
            energy[i] = sum(window ** 2)
    return energy