Python builtins.enumerate() Examples

The following are 16 code examples of builtins.enumerate(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module builtins , or try the search function .
Example #1
Source File: sanity.py    From reframe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def avg(iterable):
    '''Return the average of all the elements of ``iterable``.'''

    # We walk over the iterable manually in case this is a generator
    total = 0
    num_vals = None
    for num_vals, val in builtins.enumerate(iterable, start=1):
        total += val

    if num_vals is None:
        raise SanityError('attempt to get average on an empty container')

    return total / num_vals


# Other utility functions 
Example #2
Source File: sanity.py    From reframe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def count(iterable):
    '''Return the element count of ``iterable``.

    This is similar to the built-in :func:`len() <python:len>`, except that it
    can also handle any argument that supports iteration, including
    generators.
    '''
    try:
        return builtins.len(iterable)
    except TypeError:
        # Try to determine length by iterating over the iterable
        ret = 0
        for ret, _ in builtins.enumerate(iterable, start=1):
            pass

        return ret 
Example #3
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _get_callable_argspec_py2(func):
    argspec = inspect.getargspec(func)
    varpos = argspec.varargs
    varkw = argspec.keywords
    args = argspec.args
    tuplearg = False
    for elem in args:
        tuplearg = tuplearg or isinstance(elem, list)
    if tuplearg:
        msg = 'tuple argument(s) found'
        raise FyppFatalError(msg)
    defaults = {}
    if argspec.defaults is not None:
        for ind, default in enumerate(argspec.defaults):
            iarg = len(args) - len(argspec.defaults) + ind
            defaults[args[iarg]] = default
    return args, defaults, varpos, varkw 
Example #4
Source File: __coconut__.py    From pyprover with Apache License 2.0 5 votes vote down vote up
def __new__(cls, iterable, start=0):
        new_enumerate = _coconut.enumerate.__new__(cls, iterable, start)
        new_enumerate.iter = iterable
        new_enumerate.start = start
        return new_enumerate 
Example #5
Source File: __coconut__.py    From pyprover with Apache License 2.0 5 votes vote down vote up
def __repr__(self):
        return "enumerate(%r, %r)" % (self.iter, self.start) 
Example #6
Source File: __coconut__.py    From pyprover with Apache License 2.0 5 votes vote down vote up
def __call__(self, *args, **kwargs):
        key = (args, _coconut.frozenset(kwargs))
        use_backup = False
        try:
            hash(key)
        except _coconut.Exception:
            try:
                key = _coconut.pickle.dumps(key, -1)
            except _coconut.Exception:
                use_backup = True
        if use_backup:
            for i, (k, v) in _coconut.enumerate(self.backup_tee_store):
                if k == key:
                    to_tee, store_pos = v, i
                    break
            else:  # no break
                to_tee = self.func(*args, **kwargs)
                store_pos = None
            to_store, to_return = _coconut_tee(to_tee)
            if store_pos is None:
                self.backup_tee_store.append([key, to_store])
            else:
                self.backup_tee_store[store_pos][1] = to_store
        else:
            self.tee_store[key], to_return = _coconut_tee(self.tee_store.get(key) or self.func(*args, **kwargs))
        return to_return 
Example #7
Source File: setup.py    From pyprover with Apache License 2.0 5 votes vote down vote up
def __new__(cls, iterable, start=0):
        new_enumerate = _coconut.enumerate.__new__(cls, iterable, start)
        new_enumerate.iter = iterable
        new_enumerate.start = start
        return new_enumerate 
Example #8
Source File: setup.py    From pyprover with Apache License 2.0 5 votes vote down vote up
def __repr__(self):
        return "enumerate(%r, %r)" % (self.iter, self.start) 
Example #9
Source File: sanity.py    From reframe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def enumerate(iterable, start=0):
    '''Replacement for the built-in
    :func:`enumerate() <python:enumerate>` function.'''
    return builtins.enumerate(iterable, start) 
Example #10
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _get_call_arguments(self, fname, spans, argexpr, contents, argnames):
        if argexpr is None:
            posargs = []
            kwargs = {}
        else:
            # Parse and evaluate arguments passed in call header
            self._evaluator.openscope()
            try:
                posargs, kwargs = self._evaluate(
                    '__getargvalues(' + argexpr + ')', fname, spans[0][0])
            except Exception as exc:
                msg = "unable to parse argument expression '{0}'"\
                    .format(argexpr)
                raise FyppFatalError(msg, fname, spans[0], exc)
            self._evaluator.closescope()

        # Render arguments passed in call body
        args = []
        for content in contents:
            self._evaluator.openscope()
            rendered = self.render(content, divert=True)
            self._evaluator.closescope()
            if rendered.endswith('\n'):
                rendered = rendered[:-1]
            args.append(rendered)

        # Separate arguments in call body into positional and keyword ones:
        if argnames:
            posargs += args[:len(args) - len(argnames)]
            offset = len(args) - len(argnames)
            for iargname, argname in enumerate(argnames):
                ind = offset + iargname
                if argname in kwargs:
                    msg = "keyword argument '{0}' already defined"\
                        .format(argname)
                    raise FyppFatalError(msg, fname, spans[ind + 1])
                kwargs[argname] = args[ind]
        else:
            posargs += args

        return posargs, kwargs 
Example #11
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _postprocess_eval_lines(self, output, eval_inds, eval_pos):
        ilastproc = -1
        for ieval, ind in enumerate(eval_inds):
            span, fname = eval_pos[ieval]
            if ind <= ilastproc:
                continue
            iprev, eolprev = self._find_last_eol(output, ind)
            inext, eolnext = self._find_next_eol(output, ind)
            curline = self._glue_line(output, ind, iprev, eolprev, inext,
                                      eolnext)
            output[iprev + 1:inext] = [''] * (inext - iprev - 1)
            output[ind] = self._postprocess_eval_line(curline, fname, span)
            ilastproc = inext 
Example #12
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _argsplit_fortran(argtxt):
    txt = _INLINE_EVAL_REGION_REGEXP.sub(_blank_match, argtxt)
    splitpos = [-1]
    quote = None
    closing_brace_stack = []
    closing_brace = None
    for ind, char in enumerate(txt):
        if quote:
            if char == quote:
                quote = None
            continue
        if char in _QUOTES_FORTRAN:
            quote = char
            continue
        if char in _OPENING_BRACKETS_FORTRAN:
            closing_brace_stack.append(closing_brace)
            ind = _OPENING_BRACKETS_FORTRAN.index(char)
            closing_brace = _CLOSING_BRACKETS_FORTRAN[ind]
            continue
        if char in _CLOSING_BRACKETS_FORTRAN:
            if char == closing_brace:
                closing_brace = closing_brace_stack.pop(-1)
                continue
            else:
                msg = "unexpected closing delimiter '{0}' in expression '{1}' "\
                      "at position {2}".format(char, argtxt, ind + 1)
                raise FyppFatalError(msg)
        if not closing_brace and char == _ARGUMENT_SPLIT_CHAR_FORTRAN:
            splitpos.append(ind)
    if quote or closing_brace:
        msg = "open quotes or brackets in expression '{0}'".format(argtxt)
        raise FyppFatalError(msg)
    splitpos.append(len(txt))
    fragments = [argtxt[start + 1 : end]
                 for start, end in zip(splitpos, splitpos[1:])]
    return fragments 
Example #13
Source File: power_spectrums_plots.py    From mmvt with GNU General Public License v3.0 5 votes vote down vote up
def plot_power_spectrum_two_layers(powers_negative, powers_positive, times, title='', figure_fname='',
                                   only_power_spectrum=True, high_gamma_max=120):
    if not only_power_spectrum:
        fig, (ax1, ax2, ax3) = plt.subplots(3)#, sharex=True)
    else:
        fig, ax1 = plt.subplots()
    F, T = powers_negative.shape
    freqs = np.concatenate([np.arange(1, 30), np.arange(31, 60, 3), np.arange(60, high_gamma_max + 5, 5)])
    bands = dict(delta=[1, 4], theta=[4, 8], alpha=[8, 15], beta=[15, 30], gamma=[30, 55],
                 high_gamma=[65, high_gamma_max])

    im1 = _plot_powers(powers_negative, ax1, times, freqs)
    # cba = plt.colorbar(im1, shrink=0.25)
    im2 = _plot_powers(powers_positive, ax1, times, freqs)
    cbb = plt.colorbar(im2, shrink=0.25)
    plt.ylabel('frequency (Hz)')
    plt.xlabel('Time (s)')
    plt.title(title)

    if not only_power_spectrum:
        for band_name, band_freqs in bands.items():
            idx = [k for k, f in enumerate(freqs) if band_freqs[0] <= f <= band_freqs[1]]
            band_power = np.mean(powers_negative[idx, :], axis=0)
            ax2.plot(band_power.T, label=band_name)
        ax2.set_xlim([0, T])
        # ax2.legend()

        for band_name, band_freqs in bands.items():
            idx = [k for k, f in enumerate(freqs) if band_freqs[0] <= f <= band_freqs[1]]
            band_power = np.mean(powers_positive[idx, :], axis=0)
            ax3.plot(band_power.T, label=band_name)
        ax3.set_xlim([0, T])
        # ax3.legend()

    if figure_fname != '':
        print('Saving figure to {}'.format(figure_fname))
        plt.savefig(figure_fname, dpi=300)
        plt.close()
    else:
        plt.show() 
Example #14
Source File: power_spectrums_plots.py    From mmvt with GNU General Public License v3.0 5 votes vote down vote up
def calc_band_power(powers, freqs, band_freqs):
    idx = [k for k, f in enumerate(freqs) if band_freqs[0] <= f <= band_freqs[1]]
    return np.mean(powers[idx, :], axis=0) 
Example #15
Source File: power_spectrums_plots.py    From mmvt with GNU General Public License v3.0 4 votes vote down vote up
def plot_positive_and_negative_power_spectrum(
        powers_negative, powers_positive, times, title='', figure_fname='',
        only_power_spectrum=True, show_only_sig_in_graph=True, sig_threshold=2, high_gamma_max=120,
        min_f=1):
    from src.utils import color_maps_utils as cmu
    YlOrRd = cmu.create_YlOrRd_cm()
    PuBu = cmu.create_PuBu_cm()

    freqs = epi_utils.get_freqs(min_f, high_gamma_max)
    bands = epi_utils.calc_bands(min_f, high_gamma_max)

    if show_only_sig_in_graph:
        powers_positive[np.where(np.abs(powers_positive) < sig_threshold)] = 0
        powers_negative[np.where(np.abs(powers_negative) < sig_threshold)] = 0

    min_t, max_t = round(times[0], 1), round(times[-1], 1)
    fig, axs = plt.subplots(2, 2)
    pos_powers_ax, neg_powers_ax = axs[0, 0], axs[0, 1]
    pos_graph_ax, neg_graph_ax = axs[1, 0], axs[1, 1]
    pos_powers_ax.title.set_text('Positives')
    neg_powers_ax.title.set_text('Negatives')
    neg_cmap_vmin_vmax = (PuBu, np.min(powers_negative), -2 if show_only_sig_in_graph else 0)
    pos_cmap_vmin_vmax = (YlOrRd, 2 if show_only_sig_in_graph else 0, np.max(powers_positive))
    im1 = _plot_powers(powers_negative, neg_powers_ax, times, freqs, neg_cmap_vmin_vmax)
    # cba = plt.colorbar(im1, ax=neg_powers_ax,  shrink=0.25)
    im2 = _plot_powers(powers_positive, pos_powers_ax, times, freqs, pos_cmap_vmin_vmax)
    # cbb = plt.colorbar(im2, ax=pos_graph_ax, shrink=0.25)

    for band_name, band_freqs in bands.items():
        idx = [k for k, f in enumerate(freqs) if band_freqs[0] <= f <= band_freqs[1]]
        band_power = np.mean(powers_negative[idx, :], axis=0)
        neg_graph_ax.plot(times, band_power.T, label=band_name)
    neg_graph_ax.set_xlim([min_t, max_t])
    neg_graph_ax.set_ylim([None, -2 if show_only_sig_in_graph else 0])
    neg_graph_ax.legend()

    for band_name, band_freqs in bands.items():
        band_power = calc_band_power(powers_positive, freqs, band_freqs)
        pos_graph_ax.plot(times, band_power.T, label=band_name)
    pos_graph_ax.set_xlim([min_t, max_t])
    pos_graph_ax.set_ylim([2 if show_only_sig_in_graph else 0, None])

    # pos_graph_ax.legend()
    plt.suptitle(title)

    if figure_fname != '':
        print('Saving figure to {}'.format(figure_fname))
        plt.savefig(figure_fname, dpi=300)
        plt.close()
    else:
        plt.show() 
Example #16
Source File: pipeline.py    From mmvt with GNU General Public License v3.0 4 votes vote down vote up
def calc_induced_power(subject, run_num, windows_fnames, modality, inverse_method='dSPM', check_for_labels_files=True,
                       overwrite=False):

    def files_exist(window_fname):
        fol = op.join(root_dir, '{}-epilepsy-{}-{}-{}-induced_power'.format(
            subject, inverse_method, modality, utils.namebase(window_fname)))
        if not op.isdir(fol):
            return False
        files = glob.glob(op.join(fol, 'epilepsy_*_induced_power.npy'))
        if len(files) < 62:
            return False
        for fname in files:
            # file_mod_time = utils.file_modification_time_struct(fname)
            # if not (file_mod_time.tm_year >= 2019 and (file_mod_time.tm_mon == 7 and file_mod_time.tm_mday >= 10) or \
            #         (file_mod_time.tm_mon > 7)):
            if not utils.file_mod_after_date(fname, 10, 7, 2019):
                return False
        return True

    root_dir = op.join(EEG_DIR if modality == 'eeg' else MEG_DIR, subject)
    module = eeg if modality == 'eeg' else meg
    files_to_calc = [utils.namebase(window_fname) for window_fname in windows_fnames if not files_exist(window_fname)]
    if len(files_to_calc) == 0 and not overwrite:
        print('All files exist!')
        return
    else:
        print('Files needed to recalc:')
        for ind, fname in enumerate(files_to_calc):
            print('{}: {}'.format(ind + 1, fname))
        # ret = input('Do you want to continue (y/n)? ')
        # if not au.is_true(ret):
        #     return
    # output_fname = op.join(MMVT_DIR, 'eeg' if modality == 'eeg' else 'meg', '{}-epilepsy-{}-{}-{}_{}'.format(
    #     subject, inverse_method, modality, '{window}', '{band}'))
    for window_fname in windows_fnames:
        print('{} {} {}:'.format(subject, modality, utils.namebase(window_fname)))
        if files_exist(window_fname) and not overwrite:
            print('Already exist')
            continue
        args = module.read_cmd_args(dict(
            subject=subject,
            mri_subject=subject,
            function='calc_stc',
            task='epilepsy',
            inverse_method=inverse_method,
            inv_fname=op.join(root_dir, '{}-epilepsy{}-{}-inv.fif'.format(subject, run_num, modality)),
            fwd_fname=op.join(root_dir, '{}-epilepsy{}-{}-fwd.fif'.format(subject, run_num, modality)),
            calc_source_band_induced_power=True,
            fwd_usingEEG=modality in ['eeg', 'meeg'],
            evo_fname=window_fname,
            n_jobs=1,
            overwrite_stc=overwrite
        ))
        module.call_main(args)